Skip to content

feat: async middleware #3204

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

Open
wants to merge 8 commits into
base: main
Choose a base branch
from

Conversation

dozyio
Copy link
Contributor

@dozyio dozyio commented Jun 26, 2025

Description

feat: async middleware
fix: infinte loop
fix: cleanup failed streams
chore: add some logging
test: check failed middleware

Notes & open questions

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 and others added 4 commits June 3, 2025 19:03
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)
})
```
fix: infinte loop
fix: cleanup failed streams
chore: add some logging
test: check failed middleware
@dozyio dozyio requested a review from a team as a code owner June 26, 2025 08:22
@dozyio dozyio marked this pull request as draft June 26, 2025 08:48
@dozyio dozyio marked this pull request as ready for review June 26, 2025 12:01
@achingbrain
Copy link
Member

I think you might need to rebase your changes on top of main, there appear to be a bunch of duplicated commits here?

@dozyio dozyio changed the base branch from feat/add-stream-middleware to main June 26, 2025 16:15
@dozyio
Copy link
Contributor Author

dozyio commented Jun 26, 2025

I think you might need to rebase your changes on top of main, there appear to be a bunch of duplicated commits here?

Changed the PR to target main 👍

@achingbrain
Copy link
Member

Ah, yeah sorry - my mistake

@dozyio
Copy link
Contributor Author

dozyio commented Jun 26, 2025

Ah, yeah sorry - my mistake

Wasn't sure which branch to the do the PR against, my bad :)

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