Repository navigation
perf(middleware): precompose the middleware chain at construction time - #264
Conversation
Fold middleware into the fetch handler once in wrapFetch instead of dispatching recursively per request. This drops the per-request frame, length read, index compare, and array access per layer — only the inherent per-layer `next` closure remains (~18-25% faster dispatch at 1-5 middleware, neutral at 10). Also makes mutation semantics consistent: middleware added to `server.options.middleware` after construction now uniformly has no effect (previously honored only when the array was non-empty at construction, since the empty case already returned the raw handler). All in-tree mutators (plugins, tracing, trust-proxy, mTLS) run before wrapFetch, so behavior is unchanged. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthrough
ChangesMiddleware composition
Estimated code review effort: 2 (Simple) | ~10 minutes Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
commit: |
What
wrapFetchnow folds the middleware array into a single composed handler once at construction time, instead of recursively dispatching throughcallMiddlewareon every request.Why
Per request, the recursive dispatch paid one call frame with 4 arguments, a
middleware.lengthread, an index comparison, an array access, and a closure allocation per layer. After the fold, only the per-layernextclosure remains — that one is inherent to thenext: () => ResponseAPI since it must capture per-request state.Micro-benchmark (Node, passthrough middleware, sentinel response to isolate dispatch cost): ~18–25% faster dispatch at 1–5 middleware (~10–20 ns/request), neutral at 10. srvx's own plugins add 0–3 middleware, which is the range where the fold wins. End-to-end this is small relative to total request cost, but it's free.
Behavior note
Middleware added to
server.options.middlewareafter construction now consistently has no effect. This was never a coherent contract: the old code honored late additions only when the array was non-empty at construction, because the empty case already returned the raw fetch handler. All in-tree mutators (_plugins.ts,_trust-proxy.ts,mtls.ts,tracing.ts) run inside plugins, which every adapter applies before callingwrapFetch, so nothing observable changes.Testing
🤖 Generated with Claude Code
Summary by CodeRabbit