Files
core/src/edge.ts
T
chrnx 7df1eae5a1
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 17s
CI / build (pull_request) Successful in 28s
CI / runtimes (deno) (pull_request) Successful in 22s
CI / runtimes (edge) (pull_request) Successful in 18s
feat(http): response compression with gzip and br (CARD-16, #112)
Text responses went out uncompressed unless a proxy sat in front of every
runtime. createApp({ compression: true | { threshold, encodings } }), off
by default, implements D13 strategy B as accepted on 2026-10-22.

- One function, compressOutcome, runs after handle() and before either
  adapter writes, so Node and the fetch runtimes cannot diverge.
- Accept-Encoding negotiation with q-values, identity, * and q=0; ties go
  to server preference (br before gzip). Vary: Accept-Encoding is merged
  wherever the request decided the outcome, including every 304. Skips:
  existing Content-Encoding or Content-Range, no or an incompressible
  Content-Type (ndjson is compressible), Cache-Control: no-transform.
  HEAD and bodies under threshold keep Vary; 204 gets none.
- Node, Deno, Bun: node:zlib only, loaded lazily through nodeRequire.
  Buffered bodies use the async API, never the sync one; br at quality 4.
  Content-Length is dropped from an encoded body.
- Streams (SSE, ndjson): a zlib stream flushed after every frame, error
  frame and ping, piped into res on Node and wrapped around the
  ReadableStream on fetch runtimes. Backpressure follows the compressor;
  a client leaving destroys it.
- Edge: core never encodes and sets Vary only. Edge is recognised by
  edgeHandler, which marks the app through an internal symbol, and by
  createApp detecting workerd (navigator.userAgent, or node:zlib failing
  to load), which covers a bare app.fetch export.
- ETags from CARD-15 are taken on the identity body and stay weak, so the
  tag does not change with the coding.

Deno runs zlib's async API on the main thread; that is documented and
pinned by a test, not worked around.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:48:42 -05:00

50 lines
2.4 KiB
TypeScript

import type { App } from './app/types';
import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter';
import { MARK_EDGE } from './http/compression';
// Minimal ambient for the Cloudflare Workers globals we use — avoids @cloudflare/workers-types.
// Declares only what we call; mirrors the real workerd signatures.
interface EdgeWebSocket extends EventfulSocket {
accept(): void;
}
interface EdgeCtx {
waitUntil(promise: Promise<unknown>): void;
}
declare const WebSocketPair: { new (): { 0: EdgeWebSocket; 1: EdgeWebSocket } };
/**
* Cloudflare Workers / edge handler: HTTP + SSE via app.fetch, WebSocket via WebSocketPair.
* Use as `export default { fetch: edgeHandler(app) }`. Requires the `nodejs_compat`
* compatibility flag. The WS lifecycle runs on ctx.waitUntil so it survives past the 101 response.
*
* **Shutdown teardown never runs here, and nothing can make it.** Node, Deno and Bun all reach the
* teardown registry through a `close()` that some object owns; workerd has no shutdown to intercept
* — an isolate is discarded, not closed. A plugin or provider that relies on `onShutdown`/`dispose()`
* to release something is therefore *silently* inert on the edge, which is why this says so rather
* than a best-effort call on an event that does not exist. Anything that must be released belongs in
* the request that acquired it, or in a platform binding that manages its own lifetime.
*
* **`compression` never encodes here.** Cloudflare compresses in front of the Worker, so core sets
* only `Vary: Accept-Encoding`; wrapping the app in `edgeHandler` marks it as edge explicitly.
*/
export function edgeHandler(
app: App,
): (request: Request, env?: unknown, ctx?: EdgeCtx) => Response | Promise<Response> {
(app as { [MARK_EDGE]?: () => void })[MARK_EDGE]?.();
return (request, _env, ctx) => {
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
const [client, server] = Object.values(new WebSocketPair()) as [EdgeWebSocket, EdgeWebSocket];
server.accept();
const wsReq = toWsRequest(request, request.headers.get('cf-connecting-ip') ?? '');
const lifecycle = upgradeSafely(app, wsReq, eventSocket(server));
if (ctx?.waitUntil) ctx.waitUntil(lifecycle);
else void lifecycle;
return new Response(null, { status: 101, webSocket: client } as ResponseInit & { webSocket: EdgeWebSocket });
}
return app.fetch(request);
};
}