@projected/http 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/server.ts ADDED
@@ -0,0 +1,263 @@
1
+ import type {
2
+ AnyContracts,
3
+ Application,
4
+ Authenticator,
5
+ Metadata,
6
+ OperationKind,
7
+ OperationResult,
8
+ Principal,
9
+ } from "@projected/application";
10
+ import { openApiDocument, type OpenApiOptions } from "./openapi.js";
11
+ import { HEADERS, PLURAL, PROBLEM_TYPES, problem, problemForDispatchError, problemForOperateError, type Problem } from "./protocol.js";
12
+
13
+ /** A web-standard request handler: runs on Node (via {@link serve}), Bun, Deno and edge runtimes. */
14
+ export type FetchHandler = (request: Request) => Promise<Response>;
15
+
16
+ export interface HttpHandlerOptions {
17
+ /** Mount point, e.g. `/api`. Defaults to the root. */
18
+ readonly basePath?: string;
19
+ /** Largest accepted batch. Defaults to 100. */
20
+ readonly maxBatchSize?: number;
21
+ /** Serve the OpenAPI document at `GET /openapi.json`. Defaults to true. */
22
+ readonly openApi?: boolean | OpenApiOptions;
23
+ /** Generates message ids for requests without an `X-Message-Id` header. */
24
+ readonly messageIds?: () => string;
25
+ /**
26
+ * Establishes the principal of each request (e.g. `betterAuthAuthenticator(auth)`). Without
27
+ * one, every request is anonymous and only `access: "public"` operations can run.
28
+ */
29
+ readonly authenticator?: Authenticator;
30
+ /** `WWW-Authenticate` value sent with 401 responses. Defaults to `Bearer`. */
31
+ readonly authenticationChallenge?: string;
32
+ /**
33
+ * Other handlers to serve under path prefixes, checked first — e.g. an auth provider's own
34
+ * sign-in routes: `{ "/api/auth": auth.handler }`.
35
+ */
36
+ readonly routes?: Readonly<Record<string, FetchHandler>>;
37
+ }
38
+
39
+ /** One entry of a batch. A failed entry did not reach a business outcome. */
40
+ export type BatchItemResult = OperationResult | { readonly status: "failed"; readonly problem: Problem };
41
+
42
+ const json = (body: unknown, status: number, headers: Record<string, string> = {}): Response =>
43
+ new Response(JSON.stringify(body), {
44
+ status,
45
+ headers: { "content-type": status >= 400 ? "application/problem+json" : "application/json", ...headers },
46
+ });
47
+
48
+ const ROUTE = /^\/(commands|queries)\/([a-z0-9-]+)\/version\/([1-9][0-9]*)$/;
49
+ const BATCH = /^\/(commands|queries)$/;
50
+ const TASK = /^\/operate\/([a-z0-9-]+)$/;
51
+ const KIND: Record<string, OperationKind> = { commands: "command", queries: "query" };
52
+
53
+ /**
54
+ * Serve an application over HTTP. Every route is derived from its contracts:
55
+ *
56
+ * - `POST /commands/{type}/version/{version}` — run one command; the body is its input
57
+ * - `POST /queries/{type}/version/{version}` — run one query
58
+ * - `POST /commands`, `POST /queries` — run a batch: `{ "commands": [{ type, version, data }] }`
59
+ * - `GET /openapi.json` — the OpenAPI 3.1 document
60
+ * - `GET /health/live` (and `GET /health`) — liveness: the process answers
61
+ * - `GET /health/ready` — readiness: the application's {@link Application.health} report, 503
62
+ * while a dependency is down or the service is draining
63
+ * - `POST /operate/{task}` — run an operator task, for principals with `projected:operate`
64
+ */
65
+ export function httpHandler<C extends AnyContracts>(app: Application<C>, options: HttpHandlerOptions = {}): FetchHandler {
66
+ const basePath = (options.basePath ?? "").replace(/\/+$/, "");
67
+ const maxBatchSize = options.maxBatchSize ?? 100;
68
+ const newId = options.messageIds ?? (() => crypto.randomUUID());
69
+ const openApiOptions = typeof options.openApi === "object" ? options.openApi : {};
70
+ const document = options.openApi === false ? undefined : openApiDocument(app.contracts, openApiOptions);
71
+
72
+ const telemetry = app.telemetry;
73
+ const mounts = Object.entries(options.routes ?? {})
74
+ .map(([prefix, handler]) => [prefix.replace(/\/+$/, ""), handler] as const)
75
+ .sort(([a], [b]) => b.length - a.length);
76
+
77
+ const metadataFrom = (request: Request, principal: Principal | undefined): Metadata => {
78
+ const header = (name: string) => request.headers.get(name) ?? undefined;
79
+ const messageId = header(HEADERS.messageId) ?? newId();
80
+ return {
81
+ messageId,
82
+ correlationId: header(HEADERS.correlationId) ?? messageId,
83
+ causationId: header(HEADERS.causationId),
84
+ idempotencyKey: header(HEADERS.idempotencyKey),
85
+ ...(principal === undefined ? {} : { principal }),
86
+ };
87
+ };
88
+
89
+ const traceHeaders = (metadata: Metadata) => ({
90
+ [HEADERS.messageId]: metadata.messageId,
91
+ [HEADERS.correlationId]: metadata.correlationId,
92
+ });
93
+
94
+ const readJson = async (request: Request): Promise<{ ok: true; body: unknown } | { ok: false; problem: Problem }> => {
95
+ const contentType = request.headers.get("content-type") ?? "";
96
+ const text = await request.text();
97
+ if (text.trim() === "") return { ok: true, body: {} };
98
+ if (!/^application\/([a-z.+-]*\+)?json\b/i.test(contentType)) {
99
+ return {
100
+ ok: false,
101
+ problem: problem(PROBLEM_TYPES.unsupportedMediaType, "Unsupported media type", 415, "Send application/json"),
102
+ };
103
+ }
104
+ try {
105
+ return { ok: true, body: JSON.parse(text) };
106
+ } catch {
107
+ return { ok: false, problem: problem(PROBLEM_TYPES.malformedRequest, "Malformed request", 400, "Body is not valid JSON") };
108
+ }
109
+ };
110
+
111
+ const runOne = async (kind: OperationKind, type: string, version: number, input: unknown, metadata: Metadata) =>
112
+ app.dispatch({ kind, type, version, input, metadata });
113
+
114
+ const challenge = options.authenticationChallenge ?? "Bearer";
115
+ const respondToProblem = (response: Problem, headers: Record<string, string>): Response => {
116
+ const extra: Record<string, string> =
117
+ response.status === 503 ? { "retry-after": "1" } : response.status === 401 ? { "www-authenticate": challenge } : {};
118
+ return json(response, response.status, { ...headers, ...extra });
119
+ };
120
+
121
+ /** The request's principal, or the response when it cannot be established. */
122
+ const authenticate = async (request: Request): Promise<{ ok: true; principal: Principal | undefined } | { ok: false; response: Response }> => {
123
+ if (options.authenticator === undefined) return { ok: true, principal: undefined };
124
+ const headers = Object.fromEntries([...request.headers].map(([name, value]) => [name.toLowerCase(), value]));
125
+ const authenticated = await options.authenticator.authenticate({ headers });
126
+ return authenticated.isErr()
127
+ ? { ok: false, response: respondToProblem(problem(PROBLEM_TYPES.dependencyUnavailable, "Service temporarily unavailable", 503), {}) }
128
+ : { ok: true, principal: authenticated.value };
129
+ };
130
+
131
+ const handleTask = async (request: Request, task: string) => {
132
+ const authenticated = await authenticate(request);
133
+ if (!authenticated.ok) return authenticated.response;
134
+ const metadata = metadataFrom(request, authenticated.principal);
135
+ const body = await readJson(request);
136
+ if (!body.ok) return json(body.problem, body.problem.status, traceHeaders(metadata));
137
+ const outcome = await app.operate(task, body.body, metadata);
138
+ return outcome.match({
139
+ ok: (value) => json({ status: "ok", value }, 200, traceHeaders(metadata)),
140
+ err: (error) => respondToProblem(problemForOperateError(error), traceHeaders(metadata)),
141
+ });
142
+ };
143
+
144
+ const handleOperation = async (request: Request, single: RegExpExecArray | null, batch: RegExpExecArray | null) => {
145
+ const authenticated = await authenticate(request);
146
+ if (!authenticated.ok) return authenticated.response;
147
+ const principal = authenticated.principal;
148
+ const metadata = metadataFrom(request, principal);
149
+ const body = await readJson(request);
150
+ if (!body.ok) return json(body.problem, body.problem.status, traceHeaders(metadata));
151
+
152
+ if (single !== null) {
153
+ const [, plural = "", type = "", version = "0"] = single;
154
+ const outcome = await runOne(KIND[plural] as OperationKind, type, Number(version), body.body, metadata);
155
+ return outcome.match({
156
+ ok: (result) => json(result, 200, traceHeaders(metadata)),
157
+ err: (error) => respondToProblem(problemForDispatchError(error), traceHeaders(metadata)),
158
+ });
159
+ }
160
+
161
+ const [, plural = ""] = batch ?? [];
162
+ const kind = KIND[plural] as OperationKind;
163
+ const items = (body.body as Record<string, unknown> | null)?.[PLURAL[kind]];
164
+ if (!Array.isArray(items)) {
165
+ return json(
166
+ problem(PROBLEM_TYPES.malformedRequest, "Malformed request", 400, `Expected { "${PLURAL[kind]}": [...] }`),
167
+ 400,
168
+ traceHeaders(metadata),
169
+ );
170
+ }
171
+ if (items.length > maxBatchSize) {
172
+ return json(
173
+ problem(PROBLEM_TYPES.payloadTooLarge, "Batch too large", 413, `At most ${maxBatchSize} items per batch`),
174
+ 413,
175
+ traceHeaders(metadata),
176
+ );
177
+ }
178
+ const results: BatchItemResult[] = [];
179
+ for (const [index, item] of items.entries()) {
180
+ const { type, version, data } = (item ?? {}) as { type?: unknown; version?: unknown; data?: unknown };
181
+ if (typeof type !== "string" || typeof version !== "number") {
182
+ results.push({
183
+ status: "failed",
184
+ problem: problem(PROBLEM_TYPES.malformedRequest, "Malformed batch item", 400, `Item ${index} needs type and version`),
185
+ });
186
+ continue;
187
+ }
188
+ // A batch's Idempotency-Key covers every item: retrying the batch replays each item's outcome.
189
+ const itemMetadata: Metadata = {
190
+ ...metadata,
191
+ messageId: `${metadata.messageId}/${index}`,
192
+ idempotencyKey: metadata.idempotencyKey === undefined ? undefined : `${metadata.idempotencyKey}/${index}`,
193
+ };
194
+ const outcome = await runOne(kind, type, version, data ?? {}, itemMetadata);
195
+ results.push(
196
+ outcome.match<BatchItemResult>({
197
+ ok: (result) => result,
198
+ err: (error) => ({ status: "failed", problem: problemForDispatchError(error) }),
199
+ }),
200
+ );
201
+ }
202
+ return json({ results }, 200, traceHeaders(metadata));
203
+ };
204
+
205
+ return async (request) => {
206
+ const url = new URL(request.url);
207
+ for (const [prefix, handler] of mounts) {
208
+ if (url.pathname === prefix || url.pathname.startsWith(`${prefix}/`)) return handler(request);
209
+ }
210
+ if (basePath !== "" && url.pathname !== basePath && !url.pathname.startsWith(`${basePath}/`)) {
211
+ return json(problem(PROBLEM_TYPES.notFound, "Not found", 404), 404);
212
+ }
213
+ const path = url.pathname.slice(basePath.length) || "/";
214
+
215
+ if (path === "/health" || path === "/health/live") {
216
+ return request.method === "GET" ? json({ status: "ok" }, 200) : methodNotAllowed("GET");
217
+ }
218
+ if (path === "/health/ready") {
219
+ if (request.method !== "GET") return methodNotAllowed("GET");
220
+ const report = await app.health();
221
+ // Not a problem document: probes and operators read the report either way.
222
+ return new Response(JSON.stringify(report), {
223
+ status: report.status === "ready" ? 200 : 503,
224
+ headers: { "content-type": "application/json", "cache-control": "no-store" },
225
+ });
226
+ }
227
+ if (path === "/openapi.json" && document !== undefined) {
228
+ return request.method === "GET" ? json(document, 200) : methodNotAllowed("GET");
229
+ }
230
+
231
+ const single = ROUTE.exec(path);
232
+ const batch = single === null ? BATCH.exec(path) : null;
233
+ const task = single === null && batch === null ? TASK.exec(path) : null;
234
+ if (single === null && batch === null && task === null) return json(problem(PROBLEM_TYPES.notFound, "Not found", 404), 404);
235
+ if (request.method !== "POST") return methodNotAllowed("POST");
236
+
237
+ const carrier = Object.fromEntries([...request.headers].map(([name, value]) => [name.toLowerCase(), value]));
238
+ const route = task !== null ? "/operate/{task}" : single === null ? `/${batch?.[1] ?? ""}` : `/${single[1] ?? ""}/{type}/version/{version}`;
239
+ return telemetry.continueFrom(carrier, () =>
240
+ telemetry.span(
241
+ `POST ${route}`,
242
+ { kind: "server", attributes: { "http.request.method": "POST", "http.route": route, "url.path": url.pathname } },
243
+ async (span) => {
244
+ const started = performance.now();
245
+ const response = task !== null ? await handleTask(request, task[1] ?? "") : await handleOperation(request, single, batch);
246
+ span.setAttributes({ "http.response.status_code": response.status });
247
+ if (response.status >= 500) span.fail(`HTTP ${response.status}`);
248
+ // OpenTelemetry's semantic convention: seconds, by method, route and status.
249
+ telemetry.record("http.server.request.duration", (performance.now() - started) / 1000, {
250
+ "http.request.method": "POST",
251
+ "http.route": route,
252
+ "http.response.status_code": response.status,
253
+ });
254
+ return response;
255
+ },
256
+ ),
257
+ );
258
+ };
259
+ }
260
+
261
+ function methodNotAllowed(allow: string): Response {
262
+ return json(problem(PROBLEM_TYPES.methodNotAllowed, "Method not allowed", 405), 405, { allow });
263
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.