ba57568a846de970fbd45d82dca759e735320439
72
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
ba57568a84 |
feat(http): liveness and readiness probes with a drain window (CARD-17, #115)
createApp({ health: true }) serves GET/HEAD /__live__ and /__ready__.
Ready reports booting until boot() resolves, ok or degraded (from
app.degraded()) after that, and draining from the moment close() starts.
Probes are answered by the adapters, ahead of the request gate and of
handle(): Node in serve() (src/http/server.ts), the Fetch path in
app.fetch before it awaits the boot. Otherwise ready could never say
booting. Being ahead of the gate means maxConcurrentRequests never sheds
a probe (D14). Being ahead of handle() means no step, provider, plugin or
onError runs, and no lifecycle event is emitted, so logRequests and
metrics never see a probe. Security headers still apply, plus
cache-control: no-store. Other methods get 405 with Allow: GET, HEAD.
A probe through app.fetch before any boot starts the boot without
awaiting it. On the edge, or under a bare Deno.serve(app.fetch), nothing
else may boot the app, and an orchestrator that waits for ready before
sending traffic would wait forever.
health: { drainDelayMs } (D14) marks the app draining and keeps the
listener open for that long before connections drain. Without it, Node
closes idle keep-alive sockets at once, and a probe sees a reset rather
than the 503. The window is spent out of the close budget. serveDeno and
serveBun start the same window, through a symbol-keyed hook on the app,
before server.shutdown() / server.stop(false). workerd has no close(),
so it never reports draining.
While health is on, /__live__ and /__ready__ join the reserved-path
boot check that CARD-21 introduced, for local and mesh-spliced routes.
Invalid health values throw at createApp.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
|
||
|
|
2c00cc3407 |
feat(mesh)!: reserve /__mesh__/control on every adapter (CARD-21, #126)
The Node upgrade listener only intercepted /__mesh__/control when a mesh control channel was configured; otherwise a user @Ws route there was served. app.upgrade (Deno, Bun, edge) always checked the path first and closed 1008. The same app therefore worked on Node and was refused everywhere else. D17 makes the path reserved in every app, mesh or not: - createApp fails when a @Ws, @Stream or HTTP route claims the path, naming the declaration. A literal pattern is checked by equality, a parameterised one (/__mesh__/:x, /__mesh__/:rest*) by matching the reserved path against it. Patterns whose first segment is not the literal __mesh__ (/:org/:repo, /:rest*) still boot: the adapters answer the path before route matching, so those routes never see it. - A route exported by a teapot is checked during the teacup splice. - The Node listener, with no control channel, accepts the upgrade and closes 1008 with the reason app.upgrade gives. The reason is now one shared constant. The check lives in src/http/reserved-paths.ts so CARD-17 can add /__live__ and /__ready__ to the same list. BREAKING CHANGE: an app that declares a route at /__mesh__/control, or a pattern under /__mesh__/ that matches it, now fails createApp. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
88cbe41f72 |
feat(edge)!: trust cf-connecting-ip only under trustProxy, for HTTP and WebSocket (CARD-23, #119)
edgeHandler copied cf-connecting-ip into ctx.ip on every WebSocket upgrade, so any client that sent the header chose its own address, and it never read the header for HTTP, so IP-keyed plugins saw '' there. D21 settles both: the header counts only under trustProxy, on both paths, with no new option. The adapter cannot make that call, because trustProxy is an app option. So edgeHandler records the header against the object it hands the app (the Request for HTTP, the WsRequest for an upgrade) in an internal registry next to the Deno/Bun peer one, and app.fetch and app.upgrade both consult it through one helper, trustedProxyClient(), which returns '' unless trustProxy is on. Under trustProxy it takes precedence over x-forwarded-for, since Cloudflare sets it itself and XFF can carry client-supplied hops. Nothing else records into the registry, so the Node, Deno and Bun adapters, and a bare app.fetch or app.upgrade, ignore the header as before. BREAKING CHANGE: an edge WebSocket upgrade no longer takes ctx.ip from cf-connecting-ip unless the app sets trustProxy: true; without it, ctx.ip is ''. Refs: #119 Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
8bf54ec168 |
fix(http): keep every ? after the first in the query string (CARD-25, GitHub #48)
parseQuery took `url.split('?')[1]`, so a second `?` ended the query
string and `/search?q=what?now` gave `q: 'what'`. RFC 3986 §3.4 allows
`?` inside a query. The query string is now everything after the first
`?` and before `#`, if one is present. The early return for URLs without
a query is kept, and so is its measurement note. The comment that
deferred this behaviour question is removed because the question is now
decided (D23).
Path extraction already split on the first `?` and is unchanged.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
|
||
|
|
69bdc8adec |
test(bun): expect 1009 for oversized WebSocket frames on Bun 1.4+
CI picked up Bun 1.4.4 (`oven-sh/setup-bun@v2`, latest), which now sends a real `1009` close frame when `maxPayloadLength` refuses a frame. Bun 1.3 dropped the connection instead, so the peer saw `1006` — the difference D1 documented and these two assertions pinned on purpose so a Bun upgrade would be noticed. It was: `runtimes (bun)` fails on develop. The assertion now follows `Bun.version` (1006 before 1.4, 1009 from 1.4), so a further change in either direction still fails. JSDoc, README and the #107 CHANGELOG entry say which Bun versions do what. Verified with Bun 1.3.14 and 1.4.4 (26/26 each); lint, format, typecheck, npm test. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
63f60134ea |
feat(router)!: fail boot on unreachable or ambiguous constrained params
Before, when two sibling routes could match the same request, the router
picked one by registration order or precedence, and nothing reported it.
Boot now refuses two cases between routes of the same method that branch at
the same segment under the same prefix:
- ambiguous: both params are constrained, the constraints accept a common
segment, and the rest of both patterns can match one request. The error
names both declarations and a witness segment with an example path.
- unreachable: a plain param sits next to a constraint that accepts every
segment, and the constraint wins every request the plain param could take.
A plain param next to a constraint that leaves some segments over is the
documented fallback pattern and still boots.
The check is exact. assertSafeConstraint admits only a linear, group-free
subset, so every constraint reads back as a sequence of (character set, min,
max) blocks. Atom sets follow u-flag semantics. \p{...} is the one construct
that is not modelled, and for it the engine is asked once per code point. A
product walk over two block sequences finds a common segment, or proves none
exists, in O(|A|*|B|*(|A|+|B|)*K) with K <= 2048. "Accepts every segment" is
a closed-form test on the blocks. Both are measured against what the router
hands a param: a decoded, non-empty segment that is never "." or "..".
The check runs per table under that table's own precedence. HTTP ranks by
specificity. WebSocket takes the first declared match. @Stream routes sit in
both tables. Routes exported by different teapots are checked against each
other. Local against remote keeps the local override and its warning.
The lookup path is unchanged. router.ts only exports the two token regexes,
so the boot check and assertSafeConstraint read atoms the same way.
BREAKING CHANGE: an app that declares two overlapping constrained siblings
(e.g. /u/:id(\d+) and /u/:n(\d{1,3})), or a plain param beside a constraint
that accepts every segment, now fails createApp. So do a plain WebSocket param
declared before a constrained sibling, and such pairs across mesh teapots.
Refs: #127
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
|
||
|
|
7a9932f095 |
test(router): prove misses after index build recompile nothing (CARD-10, #109)
The linear matcher answered every 404, 405 and automatic OPTIONS by compiling the whole route table. The radix index compiles each pattern once, when the index for an array is built. Nothing asserted that, so a regression to per-request compilation or per-request index builds would only show up as a slower benchmark. compilePattern is called inside router.ts, where a spy on the module export cannot see it, so the router gains two internal counters (compilePattern calls, index builds), exposed as @internal routerSeamCounts() next to walkStackSize. router.ts is not a package entry. The new test warms the index, then repeats 404, 405 and OPTIONS misses through resolveRoute/allowedMethods, buildFetch and app.fetch, and asserts both counts stay constant while status and Allow stay correct. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
1b30f15c02 |
perf(router): reset the walk stack only when a lookup throws
The finally block added in
|
||
|
|
a2b71e2472 |
fix(router): drop pending walk frames when a segment fails to decode
The walk stack is shared across lookups. A malformed % escape threw out of decodeSegment with frames still pushed, so repeated direct matcher calls on such paths retained them. Truncate both arrays back to the entry length in a finally block, and check it with a test. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
5e0ae94ba2 |
fix(router): walk the radix index without recursion
The lookup walk recursed once per path segment, so a valid deep route such as 4,999 static segments followed by /:x threw RangeError where the linear matcher matched. Walk on an explicit stack instead, visiting frames in the same order, and cover the case through buildFetch. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
815f76116f |
perf(router): index HTTP routes in a radix tree
Replace the linear, specificity-sorted scan behind matchRoute, resolveRoute and allowedMethods with a segment trie per HTTP method, built once per route array from the compiled segments compilePattern already produces. Ranking stays global: every terminal carries its position in the old sorted bucket (moreSpecific, declaration order on ties), and the walk keeps the lowest rank it can reach, pruning subtrees that cannot beat it. The tree decides which routes can match; the rank alone decides which one does. A static branch that dead-ends deeper backtracks into its param, constrained and catch-all siblings. All-static routes are also kept by exact path per method. A hit there is provably the tree's best match, so a static request is answered without splitting the path; a miss falls through to the walk. Mesh-spliced remote routes go in a second tree, per the owner's design decision. Both trees answer, the more specific match wins and an equal one goes to the earlier declaration, so local still beats remote on a tie. Allow, 405 and implicit HEAD run over the union. An app without remote routes does one lookup. allowedMethods walks the index instead of recompiling every route on a miss, and an implicit HEAD no longer builds a fresh index from a filtered array on every request. The frozen parity corpus passes unchanged. The frozen mutant script cannot run against the new layout by design, so test/router-index-mutants.ts re-targets its twelve bug classes at the new code and runs the same untouched suite. Refs #109 Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
bd478ce09c |
build!: require Node 22
Node 18 and Node 20 are end-of-life and receive no security patches, so supporting them before RC.1 would mean promising a runtime nobody can patch. Node 22 is the oldest line still maintained. engines.node moves to >=22, @types/node to ^22, the tsup target to node22, and CI's build job from Node 18 to 22, so every workflow now runs Node 22 only. The docs, the bug report example and the comments that stated 18 as the floor follow. The node:crypto fallback in the HTTP core existed only for Node 18, which lacked the global crypto; it goes with its regression test, which said as much. The ws fallback for the WebSocket client stays: Node 22 has the global, but it can still be switched off with a flag. Moving off Node 18 and 20 also unblocks vitest 4, which the remaining dev audit advisories need. BREAKING CHANGE: Node 18 and Node 20 are no longer supported. The minimum is Node 22. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
26bacdb304 |
fix(ws): bound inbound frames synchronously and all-or-nothing
Two gaps in boundInbound, both from review of #117. The bound ran in an async pump reading the adapter's channel. `ws` emits a whole TCP read's worth of frames synchronously, so the unbounded channel took the burst before the pump saw the first frame: with maxWsQueue 2, a 2,000-frame burst reached the channel in full before close(1013). boundInbound now taps the channel through an internal, non-exported hook that runs inside push(), so each frame is bounded before it is queued. Measured on the Node listen() path, the same burst now closes on the 3rd frame. accept() also offered a frame to consumers in order and closed 1013 when a later queue was full, so the rejected frame had already reached earlier consumers. Capacity is now checked for every consumer before any delivery. Refs #107 Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
7fa02d16be |
fix(ws): give every inbound consumer its own bounded queue
boundInbound returned one shared FIFO to every `inbound` iterator, with a single waiter slot. Two consumers waiting at once left one hanging forever, sequential consumers split frames, and one consumer's return() ended the stream for all. Node used to fan out through `channel`; Deno, Bun and edge already shared one iterator before #107, so the bug was older there. Each iterator now gets its own queue, and maxWsQueue bounds each one. Frames that arrive before anyone reads still go to the first consumer, which keeps the mesh `hello`. Refs #107 Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
f78c9dc6fd |
fix(runtime): give ctx.ip the socket peer on Deno and Bun
buildFetch had no channel for a peer address, so ctx.ip was '' for
every HTTP request served by serveDeno or serveBun unless trustProxy and
x-forwarded-for supplied one. Everything keyed on the address shared one
value: the rate-limit plugin put every client in a single bucket, and
one client could exhaust the limit for all of them.
The adapters now record the peer in a WeakMap keyed by the Request
object (src/http/peer.ts, not exported) and pass that same object to
app.fetch. A header would be visible to handlers and spoofable; a second
fetch parameter would be public API. buildFetch derives ctx.ip as Node's
deriveIp does: the first x-forwarded-for hop when trustProxy is on and
the header is present, the peer otherwise. trustProxy without the header
therefore falls back to the peer instead of answering ''.
The map hangs off globalThis under Symbol.for('@green-tea/core:peer')
rather than living in the module. tsup's CommonJS build bundles index,
deno and bun as separate files with no shared chunk, so each gets its
own copy of peer.ts; with a module-private map, serveBun from
@green-tea/core/bun recorded peers that app.fetch from @green-tea/core
never saw, and ctx.ip stayed ''. A test loads a second instance of the
module to pin this.
A bare app.fetch from user code, or a Request copied from the adapter's,
has no entry and answers exactly what it did before. Addresses are
passed through unnormalised. WebSocket and the edge adapter are
unchanged; trusting cf-connecting-ip is a separate decision.
Closes #116
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
|
||
|
|
ae60cd68a2 |
fix(http): enforce maxBodyBytes while reading fetch request bodies
The fetch adapter read every body through request.arrayBuffer() and compared the length afterwards, so Deno, Bun and the edge buffered an oversized upload in full before refusing it. readFetchBytes now reads request.body chunk by chunk, stops at the chunk that crosses the limit and cancels the reader, so no further chunk is pulled. A content-length that already declares more than the limit is refused before anything is read, on both adapters. On Node the request used to wait for its first chunk, which a client that sends only headers never delivers. A malformed or absent header is ignored and the running count enforces the limit. The response is the same 413 through onError, and the route-over-server precedence for maxBodyBytes and maxParts is untouched; the new tests pin it. The over-read is proven with a counting stream rather than a status code, which is the same 413 either way. The stream uses a high-water mark of 0: the default of 1 pulls a chunk at construction, before any reader exists, which would make "nothing was read" unprovable. Socket-level tests on Deno, Bun and workerd use a 1000-byte route limit so every refused body fits in the socket buffer. With a multi-megabyte body the client is still writing when the 413 lands and sometimes sees ECONNRESET instead, which is the transport racing the answer. The Bun socket test also disables keep-alive: Bun's own fetch client reuses a socket after a response that arrived before the body was read, and its next request on it comes back 400 or 431. Node's fetch against the same Bun server does not. Closes #105 Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
0540bef07b |
feat(ws)!: bound inbound WebSocket message size and queue
Inbound WebSocket traffic was unbounded per connection: Node used ws's 100 MiB default payload, the other runtimes had no cap of their own, and the queue behind `inbound` was an unbounded channel on every runtime, so one client could exhaust memory with large messages or a slow consumer. Add `limits.maxWsMessageBytes` (default 1 MiB, close 1009) and `limits.maxWsQueue` (default 16 unread messages, close 1013), as recorded in D1. Both are server-wide and validated by createApp, which throws a TypeError for anything but a positive integer. Enforcement is shared in `boundInbound`, which subscribes immediately and replaces the subscribe-before-boot trick in app.upgrade. Node and Bun also get the native pre-buffer cap; Bun drops the connection without a close frame, so its peer sees 1006, which is documented and tested. Deno and workerd expose no such option and check the size after receipt. BREAKING CHANGE: messages over 1 MiB now close the connection with 1009, and a connection with 16 unread inbound messages is closed with 1013 on the next one, including a handler that never reads `inbound`. Closes #107 Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
59763c9af5 |
fix(ws): reject malformed upgrades instead of crashing the server
The Node 'upgrade' listener matched the raw request path without the normalization HTTP runs. A bad percent escape in a param segment threw URIError synchronously inside the listener, an uncaught exception that ends the process, and '//' silently matched a route HTTP refuses. Upgrades now normalize the path first: malformed escapes and repeated slashes get a 400, an unknown route a written 404 instead of a bare destroy, and any other throw in the listener a 500. app.upgrade (Deno/Bun/edge) closes 1008 'invalid request path' rather than 1011. On Deno the adapter's socket is still CONNECTING when an early 1008 is sent, and that close was a no-op that left the peer hanging; eventSocket now defers such a close to 'open'. Closes #104 Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
1069c727c8 |
fix(http): catch failures at the Node request-listener boundary
The Node request listener was an async function, and http.createServer ignores the promise a listener returns. Anything that rejected outside the region where errors convert to a response - a custom static resolver, a handler header value Node refuses to write (ERR_INVALID_CHAR), a stream that fails between flushing its headers and its first frame - became an unhandled rejection, which Node's default mode turns into a process exit. The listener now hands the request to serve() and catches its rejection in failSafe(), per refinement decision D2: - writable: a fixed 500 with connection: close, written through the patched writeHead so the security headers still land, without calling onError again; - headers or body already sent, or the client gone: destroy the socket; - the failure is logged through logger.error first, guarded, with String(err) for non-Error values. No request:end is emitted for these requests: observers do not alter the response, and the core never completed it. The request gate slot is already released by the existing finally, which the tests prove. Deno, Bun and the edge are unaffected: they receive app.fetch's promise and the runtime answers a rejection itself. Closes #108 Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
8c5855c59e |
perf(router): settle route ranking when the table is built, not per request
Route matching scanned every method-matching route on every request and ranked the
candidates as it went, calling `moreSpecific` — two `compilePattern` lookups each — per
candidate. Both the scan and the ranking scale with the size of the route table, and the
answer they compute cannot change between requests: the table is assembled once, after the
graph is prepared, and handed to the adapter unchanged.
So the ranking moves to where the table is built. Routes are compiled, bucketed by method
and sorted most-specific-first, and matching walks until the first match and returns it.
`sort` is stable, so patterns of equal specificity keep registration order — which is what
the old scan produced by refusing to replace its best on a tie.
Measured on a request to a parameterised route registered last, against the same tree
without these changes, medians of five and seven rounds:
6 routes no change (every row overlaps)
50 routes +3.3%, +3.5% across two runs
200 routes +14.9%, +12.0% — twelve rounds, not one crossing sample
The shape is the point rather than any single number: the saving is proportional to how
many candidates a request walks past, so it is invisible on a small table by construction.
That is also why it went unnoticed. The benchmark had no route-table-width dimension until
this commit added one, so every matcher change measured as noise no matter how real.
Two smaller savings on the same path. `decodeSegment` now skips `decodeURIComponent` when
the segment holds no `%`, the same gate `normalizeRequestPath` already applies to the whole
path for the same reason. And decoding memoizes per request rather than per candidate: a
scan reaching the same parameter position on several routes used to decode the same string
once per route, and position is all decoding depends on.
`allStatic` is deleted. It short-circuited the scan on an all-literal match, which sorting
subsumes — such a pattern now sorts first and wins by position.
The index is keyed by the identity of the route array, so it is built once and collected
with the table it describes. A table assembled fresh — mesh splicing a teapot's exports in
at boot — is a different array and gets its own index, so no caller has to invalidate
anything.
`matchRoute precedence` already covered the ordering this rewrite had to preserve, and it
passes unchanged. Two cases were missing and are added: that equal specificity keeps
registration order, which is the property the stable sort now carries, and that a parameter
decodes to the same value however many candidates the scan walks. Both pass against the
previous implementation too — they describe behaviour that already existed, which is what
makes them evidence the rewrite preserved it rather than evidence of the change.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
|
||
|
|
86a0d9c91b |
fix(observability): correlate stream events with the request that opened them
`src/http/core.ts` documented the design as "`stream:open`/`stream:close` already describe
the connection, and now carry the same `requestId`". They carried `{ name }` and nothing
else, on all three emitters, and `Bus.emit` forwards a payload verbatim — so there was
nowhere else it could have been arriving from. The comment described an intent that was
never carried out.
The split it describes is right: a route returning an `AsyncIterable` is done in
milliseconds while its connection may live for hours, so ending the request span at the
handler's return keeps hour-long SSE connections out of the same latency distribution as
2ms replies. But the split only works if the two can be **joined**, and `requestId` is the
join key — it is what `EventPayload` defines itself as. Without it an exporter could not
say which request opened the connection still holding a slot, and `traceId`, carried
verbatim so an exporter can hand it to OTLP, never reached the longest-lived thing the
server does.
`route` comes along for a second reason. The contract this beta settled says label on
`route`, never on `name` — and `route` was absent from precisely the events a stream gauge
is built from, leaving a correct consumer with nothing to label. On a stream event `name`
is always the route pattern rather than the concrete path, so the two are the same value
here; both are emitted because the rule a consumer follows is written against `route`.
A WebSocket upgrade correlates itself. It is an HTTP request with headers like any other,
so `runWsConnection` derives its own correlation and adopts a gateway's `x-request-id`
rather than opening a second identity for a connection that already has one. Deriving it
in the one place a ws connection is set up is what keeps it one identity per connection
instead of one per emitter, and it also carries `transport: 'ws'`, which nothing on that
path previously distinguished.
Verified non-vacuous: reverting `src/` fails exactly the six new correlation assertions
across the three emitters and leaves the thirteen lifecycle ones green.
Closes #84
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
|
||
|
|
7d39aebfab |
fix(stream): report a stream's lifecycle on every adapter, not only Node
`pipeStream` emitted `stream:open`/`:close`/`:error` and wrote the encoder's error frame. `asReadableStream` — the path every Fetch runtime takes, so Deno, Bun, workerd and `app.fetch()` on Node — emitted nothing and called `controller.error(err)`. Both halves of that were silent. A consumer counting `stream:error` saw zero on three of the four runtimes while the streams were failing normally, and the client got a truncated body with no explanation, which from the outside is indistinguishable from a clean end of stream. The observability guide documents these three events without qualification; on three runtimes they did not exist. The error path now frames rather than breaks. Enqueue `encodeError`'s frame, then close cleanly — the Node behaviour, and the better one: an SSE consumer that received an `error` event knows what happened, where a transport-level failure looks exactly like the connection dropping. `controller.error` is kept for an encoder with no error frame to offer, because then breaking the stream is the only signal left. `stream:close` is latched. A `cancel` can land after the body already ended, and the three exits — done, error, cancel — must not each emit their own. The test drives both adapters from one route table rather than asserting them in separate blocks, since a table that describes one and then the other is how the two drifted in the first place. Verified non-vacuous: reverting `src/http/web.ts` fails all four fetch rows and leaves the three Node ones green, which is the split that says the test is measuring the adapter and not the framework. The `sse()` injection test from the previous commit went back to `app.fetch`. It had been written against `listen()` only because the fetch path swallowed the error — that was a workaround for this bug, and it is no longer needed. Closes #83 Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
1c4f3fb8cb |
perf(http): skip the request-budget bookkeeping when no budget is set
Every request registered a `close` listener and set an acquire flag, including in the apps — most of them — that never set `maxConcurrentRequests`. `acquire()` returns `true` unconditionally when the limit is unset and `release()` early-returns for the same reason, so both the closure and the EventEmitter registration were pure overhead: a per-request cost, on the hot path, for a feature that is off. The gate exposes `limited` rather than each adapter re-deriving it from `opts`, because the gate is what knows. `acquire()` cannot say it — its `true` means "admitted" and "not counting" alike, which is exactly why a caller reading only the result pays either way. With a budget configured nothing changes: the listener is what releases a slot when a client disconnects mid-handler, and it comes back. The guard is about the unset case, not about dropping the feature, and the test asserts both halves so a fix for one cannot quietly become a regression in the other. Verified non-vacuous: reverting `src/` fails the assertion with the listener it counts. Closes #74. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
c00f714aa8 |
feat(bus): give an unmatched request a bounded route to be labelled by
`route:unmatched` was the one terminal request event carrying no `route`, so the only
subject a consumer could reach was `name` — and on that event `name` is the concrete,
caller-controlled path.
The cardinality doctrine is already written into the codebase and it is right: a metrics
consumer that labels a counter with a concrete path gets one label per distinct URL, and
unbounded label cardinality takes down the metrics backend rather than the application.
That reasoning applies hardest to exactly this event. A matched route's path is bounded by
the route table; an unmatched one is bounded by nothing at all, and a scanner walking
/aaa, /aab, /aac is a memory leak with a metrics backend attached.
The framework did not create the trap knowingly. It just left the one field that avoids
it empty, precisely where it mattered most.
`route:unmatched` and the `request:end` that follows it now both carry
`route: '<unmatched>'`, exported as `UNMATCHED_ROUTE` so nobody has to hardcode the
string to compare against it. A single series for every path that was never a route,
rather than a fallback each consumer invents and some get wrong. It cannot collide with a
pattern a user can declare, since those start with `/`.
Written down alongside it, because a field alone does not teach the rule: `name` is
caller-controlled and must not be a metric label — true of `request:start` too, which is
not terminal and so was never the one anyone counted. And `route:unmatched` is not a
synonym for failure: a static file served by `createApp({ static })` matched no route
either and answers 200, so the status comes from `request:end`, like everything else.
Closes #65.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
|
||
|
|
5294e62a5a |
fix(errors): an onError that throws degrades to the built-in renderer
`createApp({ onError })` is the advertised way to render errors, it runs on the request
path, and it ran with no boundary around it. A renderer that threw did not produce a 500
— it took the process with it, exit code 1.
This is #72 in a different callback, and easier to reach: not a cross-origin request, but
*any* request that produces an error. The stack from the reproduction goes through
`unmatchedOutcome`, so the renderer produces the 404 too — an app with a custom renderer
and no matching route was one request away from exiting.
It is also the worst-timed crash there was. The renderer only runs once something has
already gone wrong, so the failure mode read: an error occurs, the code written to report
it fails, and instead of a degraded report the server ends.
All six call sites funnel through `renderError`, so the guard goes there once. A renderer
that throws falls back to `errorToResponse` — the built-in rendering, which is exactly
what the option overrides and therefore the honest thing to fall back to. The original
error still gets its response; that is the whole point. The renderer's own failure is
logged separately and names both errors, because they are different errors and a reader
chasing the wrong one loses an afternoon.
Verified against the built `dist/` with the issue's own reproduction: `404`, process
alive, one error line naming the renderer.
`viewEngine` was checked in the same pass, since it is the other user callback on a render
path and its having a boundary was not something to assume. It has one — the pipeline's
catch covers it, so a broken engine is a 500. Asserted now rather than left to inference.
Amends the `request:failed` test added a commit ago, which asserted the crashing behaviour
as its baseline: a throwing renderer now yields the fallback's status rather than none.
The `finally` that carries the emission stays, demoted from first line of defence to
second — a failure whose reporting is what broke is the worst one to lose.
Closes #80.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
|
||
|
|
5d8363d225 |
feat(bus): guarantee that every request:end has a request:start
`request:start` had one emitter and `request:end` had three, so the pairing every
consumer would reasonably assume held by accident rather than by promise. The
`maxConcurrentRequests` merge added the first terminal path that breaks it: a shed
request emits `request:end` and nothing before it, because it never reaches `handle()`.
Both shed paths now emit the pair, through one shared `emitShedPair` rather than two
copies — the guarantee lives in one place, and the two adapters already had a duplicate
of this block between them.
## Why the pair rather than documenting `request:end` as standalone
Both were defensible and the alternative was seriously considered. It loses on one
concrete case: the obvious in-flight gauge.
bus.on('request:start', () => inFlight++);
bus.on('request:end', () => inFlight--);
Without the guarantee that drifts negative the moment a server sheds — under load, which
is exactly when an operator is reading it, and it fails by producing a plausible wrong
number rather than an error. Documenting "do not do that" asks every consumer to read
the warning; guaranteeing the pair makes the obvious code correct.
Emitting a `start` for a shed request is not a fabrication, which was the objection worth
answering: the request *did* arrive. The gate refused it before the router, and
`request:start` says a request arrived, not that it routed.
The cost of the guarantee is that it binds every future emitter, and that is real. It is
paid down by `test/lifecycle-pairing.test.ts`, which enumerates every response shape —
200, 404, 500, 413, 204 preflight, and 503 on both adapters — and asserts the pair and
the shared `requestId`. The constraint is now something CI enforces rather than something
a contributor has to remember. Verified non-vacuous: dropping the `request:start`
emission fails the two shed rows and nothing else.
Also writes down, next to `LifecycleEvent` where a consumer reads it, the half of this
that is not new: `request:end` is terminal and universal and is the one to count;
`request:failed` and `route:unmatched` describe the same request and are additional.
Closes #73.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
|
||
|
|
b8b3548f15 |
perf(cors): resolve the request's headers once, not two or three times
`security` and `cors` were computed twice for every request and three times for a
preflight: once in the adapter, to seed the headers a response written *above*
`handle()` still has to carry — a shed 503, a 413 from the body reader — and again in
`dispatch`, plus a third time inside `corsPreflightHeaders`.
Nothing was incorrect, because the predicate is expected to be pure with respect to one
request. The cost is that `cors.origins` is a predicate precisely so it can be a lookup:
an allowlist in Redis, a tenant query. The framework charged the caller's latency budget
and their backend two to three times for an answer whose inputs did not change in
between, and made a predicate with a counter in it count double.
`handle()` now takes the headers the adapter already computed and hands them down, with
`computeInjected` kept as the fallback for a caller that has none.
`corsPreflightHeaders` extends that result instead of re-deriving it. The Node adapter
was carrying its own copy of `computeInjected`, inlined; it uses the real one now, which
is what removes the duplicate rather than papering over it.
Measured against the built `dist/`, same script that produced the numbers in the issue:
GET with Origin 2x -> 1x
OPTIONS preflight 3x -> 1x
buildFetch, Origin 2x -> 1x
GET without Origin 0x -> 0x (never reached the predicate; unchanged)
The risk here is not the call count, it is that `injected` carries the security headers
onto every response shape — so the tests that matter are the existing ones across
`transport-security`, `http-headers`, `fetch`, `parity` and `web-stream`, all green.
The two new tests assert the count directly, on both adapters, which is the assertion
that keeps it from drifting back.
Closes #77.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
|
||
|
|
e5d5fb801a |
feat(shutdown): opt into SIGINT/SIGTERM with createApp({ handleSignals })
The README promised shutdown was *"an extension point, not a SIGTERM handler you
write"*. Half of it was true: `dispose()`, `onShutdown` and `hooks` all deliver the
*content* of teardown, but nothing called `close()`, so every application still wrote
the handler — and wrote it three times, because the spelling is per runtime. Forget it
and the container is SIGKILLed after its grace period, every `dispose()` the registry
so carefully ordered never runs, and nothing reports it.
`createApp({ handleSignals: true })` registers SIGINT/SIGTERM to close and exit.
Off by default, and that is the design rather than caution: a library that installs
process-wide handlers behind your back is worse than one that installs none, because
when the process exits is the application's call. Both halves are now supported and
documented — keep the handler, or hand it over. What is not optional either way is
that *something* calls `close()`, and the README now says so instead of implying the
framework already had it covered.
Declared once on `createApp`, wired per runtime by whichever boot call runs:
`listen()`, `serveDeno()` and `serveBun()` each pass the closer that drains *their*
server to `app.handleSignals`, which returns a close that also unregisters. On Deno
that unregistering is load-bearing rather than tidy — a live `Deno.addSignalListener`
holds the process open, so an app that closed itself would otherwise hang.
Unregistering first also means a *second* signal falls through to the platform default
and ends the process at once. That is deliberate: Ctrl-C twice is the way out of a
teardown that is stuck, and swallowing it for the length of a 10s budget would read as
a hang. An orchestrator sends SIGTERM once and then SIGKILL, so it never gets there.
Tested against real processes, because a handler whose job is to exit its own process
cannot be fired by hand in the runner: Node covers SIGTERM, SIGINT, the double-signal
escape hatch and the default-off case; Deno covers `Deno.addSignalListener`/`Deno.exit`,
which is the API that actually differs. Bun shares Node's `process` path.
Closes #70.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
|
||
|
|
4896ee86d2 |
fix(jsr): resolve require from source, not from tsup's banner
JSR publishes `src/` and runs no bundler, so the `createRequire` banner tsup gives
the ESM build (tsup.config.ts) never exists there. Every lazy `require(...)` in the
source had nothing to resolve, and one of them was unguarded: `@Html('file')` and
template mode died at boot on Deno with `ReferenceError: require is not defined`.
The two guarded sites were worse than the crash, because they answered confidently
and wrongly. `static` reported *"needs a filesystem and is unavailable on this
runtime (edge)"* while running on Deno, which has one; multipart reported busboy as
not installed while it sat in node_modules. Both blamed the runtime for a packaging
problem, and both named a runtime the reader was not on.
Route all ten call sites through one `nodeRequire`, which prefers the ambient
`require` — so the CJS build and the banner-carrying ESM build behave exactly as
before — and otherwise rebuilds one from `process.getBuiltinModule('node:module')`.
Node 22.3+, Deno and Bun all expose that synchronously, which is the requirement:
every caller sits on a sync path a dynamic `import()` could not serve. It resolves
from `process.cwd()`, since a peer dependency like busboy belongs to the application,
not to a module served over https from a registry.
Where neither exists — workerd, where esbuild rewrites the call into its own throwing
stub — the behaviour is unchanged: the guarded sites still catch, and their "edge has
no filesystem" story is finally the true one.
Covered by a Deno suite that imports `src/` exactly as JSR serves it. The other Deno
tests already did that; none of them touched a path that loads a Node builtin lazily,
which is how a package that died at boot kept a green suite.
Closes #69.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
|
||
|
|
bb0b01cf26 |
fix(cors): deny the origin when the origins predicate throws
`CorsOptions.origins` accepts a predicate, and it runs on the request path above the region where errors convert to a response. A predicate that threw became a rejected promise nobody awaited, and Node's default for that is to exit — so one cross-origin GET took the process down, with `onError` never reaching it. The trigger is a browser: `originAllowed` only runs when an `Origin` header is present, so the crash is reachable by any cross-origin client and by no test that forgets the header, which is how it survived a green suite. Guard the call at `originAllowed`, the single point all four call sites funnel through (the Node handler, `computeInjected` on both adapters, and the preflight path). A predicate that throws denies the origin: a lookup that failed has not said yes, and a broken allowlist must never widen into an open one. The failure is reported through the app logger rather than swallowed — `HttpOptions` already carries one. The published behaviour changes for a throwing predicate only. Every other origin shape is untouched, and the security headers still land on the response. Amends one test from the `maxConcurrentRequests` contribution, which asserted the old crash as its baseline while proving the gate does not leak a slot. It still proves that, against a transient failure that is now answered rather than fatal. Closes #72. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
ff94e55496 |
feat: cap concurrent requests across runtimes
CI / dco (push) Has been skipped
CI / build (push) Successful in 28s
CI / runtimes (deno) (push) Successful in 19s
CI / runtimes (bun) (push) Successful in 59s
CI / runtimes (edge) (push) Successful in 11s
CI / dco (pull_request) Successful in 6s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 21s
CI / build (pull_request) Successful in 29s
Signed-off-by: hgshreyas <hgshreyas.cs24@bmsce.ac.in> |
||
|
|
82e1678dea |
fix: warn when connection limit drops a socket
Signed-off-by: hgshreyas <hgshreyas.cs24@bmsce.ac.in> |
||
|
|
9b5347aa75 |
fix(observability): correlate requests on Node 18, where there is no global crypto
`engines` promises `>=18`. The global `crypto` arrived unflagged in Node 19.
Between those two facts, `correlateRequest` compiled cleanly against an ambient
`declare const crypto` and then threw `ReferenceError: crypto is not defined` on
the first request of every Node 18 process — which is to say the observability
work made the framework unusable on its own stated floor.
Nothing local could see it. Every developer machine here runs 20 or 22, and
Deno, Bun and workerd all expose the global. CI's Node 18 job caught it on the
promotion pull request, which is the entire reason that job is pinned to the
floor rather than to the current release.
The global stays the primary path, because it is why this file does not simply
import node:crypto: it is the runtime-neutral core, and node:crypto is not
available to all four runtimes. The fallback is reached only where the global is
absent, so workerd never evaluates the require, and the ESM build has a real one
from the createRequire banner already in tsup.config.ts. Verified in both built
formats rather than assumed — esbuild rewrites it to require("crypto"), which is
the same module.
test/node-floor.test.ts stubs the global away to reproduce the floor's condition
on any Node, and was confirmed to fail against the previous code. The bug was
invisible where it was written; this makes it visible there.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
|
||
|
|
a4bb3c02d6 |
refactor(http): resolve each request once, in the core that already routes it
Both adapters routed every request themselves, and then handle() routed it
again from the same inputs — a four-route app walked its table 2.5 times
per request. Neither side was wrong: an adapter must know the route to
decide whether to read a body, and the core must know it to dispatch.
The cause was the shape of the handoff. NeutralRequest carried an
already-parsed body, so producing one was the adapter's problem, and every
policy that depends on the matched route came with it — these four chains
were written out in server.ts and web.ts character for character:
matched.def.maxBodyBytes ?? opts?.limits?.maxBodyBytes ?? 1_000_000
matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last'
matched.def.maxParts ?? opts?.limits?.maxParts ?? 1000
opts?.limits?.maxBodyBytes ?? 1_000_000
A fifth knob, or one changed default, meant editing both or letting the
runtimes quietly disagree about limits.
Handing over the ability to read rather than the result moves the decision
to where the route is already known. What stays in an adapter is what
genuinely differs between runtimes: getting bytes in, putting bytes out.
Enforcement stays with the reader too, because Node aborts an oversized
upload as chunks arrive while a fetch runtime can only measure what
arrayBuffer() already resolved — passing the limit in preserves that.
413/400/501 keep their exact current shape, Node's connection: close
included; it now has the test it never had.
Measured through app.fetch, both versions in one process, interleaved:
40 routes with the match declared last, 3.89 -> 3.58 us (-8.2%). One
route, where there is no second scan to save, is unchanged.
The first cut of this was 13% SLOWER, and the reason is worth recording:
a per-request closure for the reader plus the error-context object it
captured cost 250 ns, and the async frames around a body that did not
exist cost another 215 ns — together more than the duplicate scan the
whole change removes. The reader is now built once per server and takes
the runtime's request as an argument, and a bodiless request touches no
promise on this path at all.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
|
||
|
|
0c9f8a545e |
fix(router): route dot segments the same way on every runtime
The same bytes on the wire reached different routes depending on where the app ran. `GET /public/../admin` hit a `/admin` route under Deno, Bun and workerd, and 404'd under Node — 200 vs 404 for one request. The fetch-based runtimes resolve dot segments inside the `Request` constructor, before green-tea is handed anything: `new Request( 'http://x/public/../admin').url` is already `http://x/admin`. Node's raw target has no such step. Rejecting outright — the stricter policy, and what this module already does for `//` — is not implementable on three of the four runtimes, because the raw target is unrecoverable there. So Node converges on the rule the other three cannot opt out of. `%2e` is a dot to the URL parser, so the encoded spelling resolves too; leaving it out would keep it as a way to reach a route the plain spelling resolves away from. Cost is gated: paths with no `.` and no `%` pay two indexOf scans (20.0 -> 21.7 ns for `/hello`), a literal dot pays the regex (35.5 ns), and only real dot segments pay the split (103.6 ns). The existing parity suite could not have caught this — its `both()` helper goes through `fetch()`, which normalizes the URL before it reaches the wire. The new cases write the request line to a socket by hand. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
e625d5c881 |
perf(router): stop the route scan at a match nothing can outrank
matchRoute evaluated every registered route before answering, so `/hello` cost the same whether it was declared first or last among 32 routes — 1227 ns against 1237 ns. That is ~38 ns of scanning per registered route on every request, growing with the route table, and the benchmark app has the smallest table any real service would have. Specificity ranks a literal segment above every other kind, so a pattern made only of literals cannot be outranked by anything else matching the same path, and an equal rank keeps registration order — which is the route already in hand. Finishing the scan only re-derives it. The path split moves out of matchCompiled for the same reason: `split` + `filter` ran once per candidate route on every request, always producing the same array. Doing it once per request is 63.7% off a 32-route scan that early exit cannot help at all (a :param match, which must be compared against the rest of the table). Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
8d8ef7ed09 |
perf(http): look injected header keys up directly instead of rebuilding a Set
mergeInjectedHeaders rebuilt a lowercased Set of the injected header keys on every response: an array from Object.keys, a mapped array from toLowerCase, and a Set from that. Three allocations to answer a question the object already answers. The lowercasing was the redundant part. Every key `injected` can hold is written as a lowercase literal in src/security.ts — buildSecurityHeaders and resolveCors are its only sources — so the mapped array was a copy of the keys it started with. hasOwnProperty rather than `in`: a handler may legitimately send a header named constructor or toString, and `in` would find those on Object.prototype and drop them silently. 146.4ns to 55.9ns in isolation; -3.2% end to end over five interleaved rounds, with all five pairs favouring the change. Third of three fixes from the same profile, and all three are one pattern: work done unconditionally for a case that rarely or never applies — validating encoding that is almost never malformed, parsing a query string that is not there, lowercasing keys that already were. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
0c5decbeae |
perf(router): skip query parsing when there is no query string
parseQuery ran on every request. For a URL without a `?` it split the string,
built a URLSearchParams from '', looped zero times and returned {} — three
allocations to arrive at an empty object, on the majority of requests.
92.3ns before, 18.6ns after, in isolation. End to end: -3.1% request latency
over five interleaved rounds.
Only the guard is new. Switching the parse itself to indexOf + slice would drop
another allocation, but it changes what a second `?` in a URL means, and that
is a behaviour question that does not belong in a performance commit.
Found by CPU-profiling the request path rather than guessing. Worth recording
what that profile showed: almost nothing in it is green-tea. Building the
web-standard Request/Response/Headers in undici dominates — appendHeader alone
is 5.2%, Response construction 2.8%, stream state 4.5%, GC 5% — while the only
green-tea frames above 1.5% were mergeInjectedHeaders at 2.6% and this at 1.8%.
The per-request cost of app.fetch is mostly the price of returning a real
Response, not framework logic. mergeInjectedHeaders is the next candidate: it
rebuilds a lowercased Set of the injected header keys on every response, and
those keys are fixed for the life of the app.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
|
||
|
|
86dd3fe9b6 |
perf(router): stop decoding every path segment to throw the result away
normalizeRequestPath ran on every request and validated percent-encoding by splitting the path and calling decodeURIComponent on each segment, discarding every result — matching is done on the raw path. Two array allocations and one decodeURIComponent per segment, per request, to prove that a string nobody decodes could be decoded. Measured in isolation: 95.8ns for /hello, 342.7ns for a six-segment route. The guard costs 15.7ns and 6.7ns for the same two paths. Same validation. decodeURIComponent throws on the first malformed % sequence wherever it appears, so one call on the whole string catches what per-segment calls caught, and %2F inside a segment decodes fine either way. Only the throw was ever used. The existing tests for malformed encoding and repeated slashes pass unchanged. Found by sweeping all 178 commits between |
||
|
|
e052d5ba8f |
feat(observability): request-level events, and request logging that reads them
Tasks 5 and 6, in that order rather than the plan's: request logging is a
subscriber, so the events it subscribes to had to exist first.
handle() now emits request:start, request:end, route:matched and
route:unmatched. request:end fires when the handler returns, not when a stream
it produced finishes — a streaming route is done here in milliseconds while its
connection may live for hours, and ending the span at close would put hour-long
SSE connections and 2ms buffered replies in one latency distribution. The
stream events already describe the connection and now share the requestId.
route:unmatched covers 404 and 405 both. Naming it after one outcome, as the
report's route.not_found does, would misreport the other.
logRequests(bus, logger) is the consumer: info per completed request, error per
failed one, and it returns an unsubscribe so it is removable rather than merely
optional. createApp({ logRequests: true }) turns it on and is off by default,
because a framework that writes to stdout uninvited is one you have to
configure before you can use it. withConsoleFallback wraps it, since Bus.emit
isolates listener failures by design and a user logger that throws would
otherwise stop writing with nothing to say so. A test proves both halves: the
request still succeeds, and the failure still surfaces.
The bus reaches handle() through HttpOptions so the Node and Fetch adapters
share one channel instead of growing separate ones.
Cost, measured: nothing. First attempt wrapped dispatch in a second async frame
and that alone cost 0.43us per request — a promise and two microtask ticks,
an order of magnitude more than the four Map lookups it was there to arrange.
handle() is no longer async and hands back dispatch's own promise when nothing
subscribes; 4.716-4.791us against 4.736-4.793 before, which is the same number.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
|
||
|
|
7b0a3d4e24 |
docs(observability): record why randomUUID is the fast option, not the lazy one
Benchmarked the alternatives rather than leaving the question open. Every
supported runtime already batches entropy behind randomUUID, so the intuitive
replacements lose: Math.random() twice into base36 is 3.5x slower at 265ns
because the string work dominates, an unbatched getRandomValues is 472ns, and
a uint32 pool through toString(36) is 114ns.
The only cross-runtime improvement is a hand-rolled entropy pool with a hex
lookup table at 50ns, which saves 26ns — 0.26% of a real 10.19us request. Not
worth owning an entropy pool for. Buffer.toString('hex') matches it but is
Node-only, which this file cannot be.
Table left in the code so the next person does not re-run it.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
|
||
|
|
dabab1812b |
perf(observability): hoist a per-request closure out of correlateRequest
The `first` helper was declared inside correlateRequest, so it was allocated on every request. It captures nothing, so module scope is where it always belonged. Measured at 0.16us against a ~4.4us in-process request — 45% of the entire remaining observability overhead, from one line. Total overhead is now +0.24us rather than +0.44us, which against the 10.19us of a real socketed request is ~2.4%. Ablation of what is left, so the next person does not repeat it: randomUUID is 0.16us of the 0.24 and the other 0.08 is the header read, the extra properties and three hasListeners lookups. Building the correlation literal per request costs nothing measurable — V8 keeps it on the stack — so do not go optimising that one. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
633ef58032 |
perf(observability): do not build event payloads for an empty room
The correlation work regressed the in-process hot path from 4.52us to 5.43us per request, ~20%. The design predicted 0.25% per step and was wrong by more than an order of magnitude, so recording what the measurement actually said: spreading correlation into payloads ~197ns <- the cost crypto.randomUUID() ~170ns in place try/catch inside the step loop ~2.6ns <- not the cost emit() cannot avoid the first: its argument is already built by the time it is called. Only the caller can decline to build it, so Bus.hasListeners lets it, and runSteps hoists the check out of the loop since listeners are registered at boot. An application subscribing to nothing now pays a branch instead of four payloads and three clock reads for an audience of nobody. That recovers half. 4.96us remains against 4.52us — ~10% in process, ~4.5% against the 10.19us of a real socketed request. Two ways to shave the rest were measured and both rejected in comments: a lazy requestId is defeated by the first spread, and a boot-prefix counter is 5x cheaper but trades the standard identifier shape for ~1.7%. Neither earns its complexity yet. The remaining cost is the feature, not an accident: correlation only exists if something carries it. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
2c47ee8896 |
feat(observability): correlate and time the lifecycle event stream
Tasks 1-3 of the observability plan. The Bus already had 19 emission points; what it lacked was any way to tell which request an event belonged to, which made the whole stream unusable under concurrency. Every per-request event now carries requestId, traceId, route, method and transport, and request:step:leave carries durationMs — a field that has been declared in EventPayload since the beginning with nothing ever writing it. Identity is derived in the adapters rather than in handle(), because both read and size-check the body first: a 413 is answered without handle() ever seeing the request, so generating there would leave exactly the failures an operator most wants to correlate with nothing to correlate them by. An incoming x-request-id is adopted rather than replaced, and traceparent is carried verbatim — core implements no propagation spec. Timing takes N+1 readings for N steps, since one step's end is the next one's start. Measured at 25.2ns per step against a ~10.19us request. request:step:error now names the step that actually failed. It reported name: 'pipeline' before, discarding the one fact it exists to carry, because it was emitted from the outer catch where that is all that is known. The outer catch emits request:failed instead: one marks the span, the other the trace. route carries the matched pattern and never the concrete path. Labelling a metric on raw URLs gives unbounded cardinality and takes down the metrics backend rather than the app, so it is a contract, with a test. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
586e14da72 |
feat(runtimes): a bounded close() on the Deno and Bun adapters
Closes #15, taking the second of the two answers it framed: app.close() stays Node-only, and each transport that owns a handle offers the same close({ timeoutMs }). app.close() returns at its `if (!server)` guard on Deno and Bun because they serve through app.fetch and never through listen(), and only the transport can drain what it accepted. The warning there now names the replacement instead of pointing at this issue. The runtimes do not agree, and the code says so rather than averaging them: Bun escalates. stop(false) drains, stop(true) forces, and the deadline moves between them like Node's closeAllConnections(). Deno cannot. Its two levers are mutually exclusive — aborting the serve signal while shutdown() is pending throws BadResource from Deno's own listener, uncaught and fatal under deno test. Measured on 2.9: abort alone is clean, abort after shutdown is not. So on Deno the deadline bounds how long close() waits, not when connections die, and both the type and the timeout warning say that outright. Silently accepting an option that does less is the failure mode AGENTS.md rules out. closeWithDeadline is shared so the two cannot drift into different meanings of the same timeoutMs, and it resolves on its own timer rather than awaiting the force call — Bun's stop(true) was measured waiting out a handler with a pending timer, which is exactly the unbounded wait the deadline exists to prevent. serveDeno now owns the AbortController it serves with, chaining any caller signal into it so neither party loses control; a test covers that. The Bun ambient said stop() returns void, which was simply wrong. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
30f33b6383 |
fix(http): narrow buffered bodies to what the runtime's Response accepts
A Node Buffer is a Uint8Array at runtime, but its declared backing store is ArrayBufferLike, which admits SharedArrayBuffer — and BodyInit takes only ArrayBuffer-backed views. Deno's lib rejected it outright at web.ts:112. This is the app.fetch path, so the hole was on Deno, Bun and edge alike; it went unnoticed because every implementation is forgiving about it at runtime. Re-views rather than copies: this is the buffered-response path, and a copy per response would cost real throughput on the runtimes that have no other adapter. byteOffset and byteLength are load-bearing there — Buffer.from hands back a window into a shared 8 KB pool, and dropping them returns the whole pool. A direct test covers that; the static-serving one covers the integration. The type is derived from Response's own constructor because BodyInit is not a global under lib es2020 plus @types/node, though Response itself is. Refs: Green-Tea/core#19 Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
8c781c1258 |
fix: treat non-positive connection limits as unlimited
Signed-off-by: hgshreyas <hgshreyas.cs24@bmsce.ac.in> |
||
|
|
9e5e5cffe9 |
feat: add concurrent connection limits
Signed-off-by: hgshreyas <hgshreyas.cs24@bmsce.ac.in> |
||
|
|
a2acec69bf |
feat(openapi): document constrained route params
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |
||
|
|
9a61ba8646 |
feat(http): complete HEAD and OPTIONS semantics
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com> |