js-libp2p icon indicating copy to clipboard operation
js-libp2p copied to clipboard

feat: add stream middleware

Open achingbrain opened this issue 7 months ago • 2 comments

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

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

achingbrain avatar Jun 03 '25 17:06 achingbrain

cc @dozyio

achingbrain avatar Jun 03 '25 17:06 achingbrain

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

dozyio avatar Jun 04 '25 22:06 dozyio