Skip to content

feat: add stream middleware #3173

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft

Conversation

achingbrain
Copy link
Member

Adds middleware handlers for protocol streams. They are invoked for incoming and outgoing streams and allow access to the stream and connection before the handler (incoming) or caller (outgoing) receive them.

This way middleware can wrap streams in transforms, or deny access, or something else.

libp2p.use('/my/protocol/1.0.0', (stream, connection, next) => {
  const originalSource = stream.source

  // increment all byte values in the stream by one
  stream.source = (async function * () {
    for await (const buf of originalSource) {
      buf = buf.map(val => val + 1)

      yield buf
    }
  })()

  // pass the stream on to the next middleware
  next(stream, connection)
})

Change checklist

  • I have performed a self-review of my own code
  • I have made corresponding changes to the documentation if necessary (this includes comments as well)
  • I have added tests that prove my fix is effective or that my feature works

@achingbrain
Copy link
Member Author

cc @dozyio

Adds middleware handlers for protocol streams.  They are invoked
for incoming and outgoing streams and allow access to the stream
and connection before the handler (incoming) or caller (outgoing)
receive them.

This way middleware can wrap streams in transforms, or deny access,
or something else.

```ts
libp2p.use('/my/protocol/1.0.0', (stream, connection, next) => {
  const originalSource = stream.source

  // increment all byte values in the stream by one
  stream.source = (async function * () {
    for await (const buf of originalSource) {
      buf = buf.map(val => val + 1)

      yield buf
    }
  })()

  // pass the stream on to the next middleware
  next(stream, connection)
})
```
@achingbrain achingbrain force-pushed the feat/add-stream-middleware branch from 7e58596 to aee23bc Compare June 3, 2025 18:03
@dozyio
Copy link
Contributor

dozyio commented Jun 4, 2025

Amazing @achingbrain! thank you - Will have a play over the weekend

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants