Registry Mirror
Skip to content

Conversation

@adenhertog

@adenhertog adenhertog commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Closes #263

Summary

Adds withMiddleware() with incoming, handler and outgoing stages, and native transport headers set by outgoing middleware. Removes the eight lifecycle emitters, withMessageReadMiddleware, MiddlewareDispatcher and TypedEmitter.

Background

The only extension points were read middleware over TransportMessage and eight synchronous emitters on BusInstance. Nothing wrapped an outgoing send or a single handler, and transports built native headers only from MessageAttributes, so raw headers (#202) couldn't be set.

Problem

Checked against master:

  • Confirmed & fixed: a read middleware that didn't call next() left the message in flight. The delete lived inside the final read middleware. Incoming middleware now runs around dispatchMessageToHandlers, and core deletes or returns the message after the chain settles (when incoming middleware does not call next() in bus-instance-middleware.integration.ts).
  • Confirmed & fixed: beforeDispatch was emitted after handlers.map(dispatchMessageToHandler) had already started the handlers. The emitter is removed, and the handler stage wraps each invocation.
  • Confirmed & fixed: MiddlewareDispatcher and TypedEmitter were exported from the root, and dispatchMessageToHandler was public. The first two are deleted (index.spec.ts asserts it), and dispatchMessageToHandler is now private.

Approach

  • Types (bus-core/src/middleware/): Next, Middleware<TContext> (it must return a Promise), IncomingContext extends HandlerContext, HandlerInvocationContext (+ handlerName), OutgoingContext (a send/publish union with mutable attributes and headers), BusMiddleware, and MiddlewareNextCalledTwice (names the stage). TransportSendOptions/TransportHeaders and TransportHeaderReserved are in transport/. All are exported from the root. The internal MiddlewarePipeline is built per bus in build().
  • Incoming: runs inside the bus' handling and lifecycle contexts, for polled and Receiver messages, including messages with no handler. Not calling next() deletes the message. A throw returns it for retry, and catching without rethrowing marks it handled. The context is frozen, and its sends go straight to the transport.
  • Handler: wraps each handler inside its outbox. Class handler resolution now happens inside the chain too, so a DI or transaction scope can wrap it. A throw discards only that handler's outbox, and the message is retried via HandlerDispatchRejected. For workflows it wraps the registered handler: state load, invoke and save. The registry names that handler after the workflow (via a small registerWorkflowHandler helper, so the handler bodies weren't reindented and the diff against Errors thrown in workflows aren't visible #152's changes stays small), so handlerName is the workflow name: the class name, or the state's $name for defineWorkflow. Function handlers use fn.name, or 'anonymous'.
  • Outgoing: runs in send()/publish() after prepareTransportOptions, which also stamps messageId/sentAt (from stamp a message id and sent time on every message, and add transport endpoint names #325), so middleware sees them (tested). Its last step snapshots the context (attributes two levels deep, headers), so changes made after next() never reach the transport, then either buffers into the outbox or calls transport.send/publish(message, attributes, { headers }). Flushing doesn't rerun it. Not calling next() drops the message with a debug log. If a middleware throws after next(), the message it just buffered is taken back out of the outbox, so "a throw buffers nothing" holds.
  • Transports: a new optional Transport.assertSendOptions() is called by core in the outgoing terminal step, before buffering or sending, so a reserved header rejects the send()/publish() itself instead of failing the outbox flush after siblings went out. RabbitMQ and SQS implement it and still check in send/publish. The in-memory queue reserves no names, so it doesn't implement it. RabbitMQ spreads headers into the AMQP headers (attributes, stickyAttributes, sentAt, failedAttempts, x-death and x-first-death-*/x-last-death-* are reserved). The integration tests show headers survive a retry and the dead letter queue on both transports. SQS writes each header as an SNS message attribute under its own name, typed as in toAttributeValue, with empty strings dropped. correlationId, messageId, sentAt and the attributes./stickyAttributes. prefixes are reserved. sentAt and messageId are reserved because stamp a message id and sent time on every message, and add transport endpoint names #325 writes them, so a middleware header can't overwrite them. Rebased onto stamp a message id and sent time on every message, and add transport endpoint names #325. InMemoryQueue keeps headers on raw.headers.
  • Tests: ported every emitter and read middleware user (bus-core specs and integration tests, bus-sqs-lambda). A RecordingInMemoryQueue fixture replaces afterSend/afterPublish observers. New tests: middleware-pipeline.spec.ts (order, short-circuit, next-twice per stage, and a middleware tested as a plain function) and bus-instance-middleware.integration.ts (every acceptance criterion, plus a two-bus isolation test). The "async lifecycle listener rejects" test was deleted, since listeners no longer exist.
  • Docs: /guide/middleware is rewritten for all three stages, with a hooks → middleware table. /guide/lifecycle-hooks is deleted, with a redirect (it was a GitBook path, so it's in the gitbook group), and the links to it are fixed. The custom transport page, its snippet and the add-transport skill cover TransportSendOptions.
  • MIGRATING.md entry, a minor changeset with a Breaking: note (bus-core, bus-rabbitmq, bus-sqs), and updates to the root and adapter CLAUDE.md.

For reviewers:

Tests: pnpm build, format:check, lint, test:unit (448 passed), all integration tests against the shared infra (379 passed), check:packages, check:message-types, docs:typecheck, docs:build, docs:check-redirects and docs:check-readmes.

🤖 Generated with Claude Code

adenhertog and others added 7 commits October 3, 2026 11:38
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@adenhertog
adenhertog force-pushed the issue-263-middleware branch from 3ffdeb4 to f28cf38 Compare October 3, 2026 01:44
adenhertog and others added 3 commits October 3, 2026 12:45
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…h headers

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@adenhertog
adenhertog merged commit b78d2aa into master Oct 3, 2026
5 checks passed
@adenhertog
adenhertog deleted the issue-263-middleware branch October 3, 2026 02:53
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.

Incoming and outgoing pipeline behaviours (middleware)

1 participant