@uniflowed/server 0.0.0-alpha.7 → 0.0.0-alpha.9

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/lambda.js ADDED
@@ -0,0 +1,266 @@
1
+ // @flow
2
+ //
3
+ // `@uniflowed/server/lambda`: the AWS Lambda half of serving a build.
4
+ //
5
+ // A serverless target has no server. What it has is one function per
6
+ // invocation, whose signature belongs to the platform rather than to the Web —
7
+ // so this module is a translation, and the thing being translated is the same
8
+ // [`./fetch.js`] handler `uf start` and every other front door answer through.
9
+ //
10
+ // # One event shape, named
11
+ //
12
+ // **Payload format version 2.0**, which is what a Lambda Function URL always
13
+ // sends and what an API Gateway *HTTP* API sends by default. It is not what an
14
+ // API Gateway *REST* API sends (that is format 1.0, with `httpMethod`,
15
+ // `path` and `multiValueHeaders`), and it is not an ALB target-group event.
16
+ // Supporting all three by sniffing the event would be three untested code
17
+ // paths where the platform's own documentation says which one you get; this
18
+ // one is named in `docs/app/reference/cli/_uf.page.mdx`, and an event that is
19
+ // not it is refused by [`toRequest`] with a message saying so rather than
20
+ // answered from fields that happen to be undefined.
21
+ //
22
+ // # Buffered, and why that is a limitation rather than a choice
23
+ //
24
+ // `createFetchHandler` answers a document as a stream, so a `<Suspense>`
25
+ // fallback reaches the browser while the page behind it is still resolving.
26
+ // A Lambda response in this format is a JSON value, so the whole body is read
27
+ // before the invocation returns and none of that streaming survives. Response
28
+ // streaming exists — `awslambda.streamifyResponse`, on a Function URL whose
29
+ // invoke mode is `RESPONSE_STREAM` — and this module does not implement it:
30
+ // the wrapper is a global the managed runtime injects, so nothing outside a
31
+ // real invocation can drive it, and an untested streaming path is worse than a
32
+ // buffered one that says it is buffered. The 6 MB response payload limit is
33
+ // the platform's and applies to what this returns.
34
+ //
35
+ // # The static half is here rather than on a CDN, unless you put one there
36
+ //
37
+ // `staticDir` is served through `./node.js`'s `createStaticHandler`, from the
38
+ // deployment package itself, so the function answers a prerendered document
39
+ // and a hashed asset without any other infrastructure existing. That is the
40
+ // shape that works the moment it is uploaded; it is not the shape anybody
41
+ // should keep. Every byte of `static/` is then billed as invocation time and
42
+ // counted against the package limit, and a CloudFront distribution or an S3
43
+ // origin in front of the function is what the platform expects. Leaving
44
+ // `staticDir` out is how you say you have one — the application half then
45
+ // answers alone, exactly as it does on a worker.
46
+
47
+ import { Buffer } from "node:buffer";
48
+
49
+ import { createStaticHandler } from "./node.js";
50
+
51
+ import type { RequestLifecycle } from "./internal/context.js";
52
+
53
+ export type { RequestLifecycle } from "./internal/context.js";
54
+
55
+ /**
56
+ * An HTTP API payload format 2.0 event, as much of it as this module reads.
57
+ *
58
+ * Inexact and almost entirely optional, because it arrives from the platform
59
+ * rather than from a caller: the fields uf needs are checked in [`toRequest`],
60
+ * where a missing one can be reported as the wrong event shape.
61
+ */
62
+ export type LambdaHttpEvent = {
63
+ readonly version?: string,
64
+ readonly rawPath?: string,
65
+ readonly rawQueryString?: string,
66
+ readonly cookies?: $ReadOnlyArray<string>,
67
+ readonly headers?: { readonly [string]: string | void },
68
+ readonly body?: string,
69
+ readonly isBase64Encoded?: boolean,
70
+ readonly requestContext?: {
71
+ readonly domainName?: string,
72
+ readonly http?: {
73
+ readonly method?: string,
74
+ readonly path?: string,
75
+ ...
76
+ },
77
+ ...
78
+ },
79
+ ...
80
+ };
81
+
82
+ /** What Lambda expects back for payload format 2.0. */
83
+ export type LambdaHttpResult = {|
84
+ readonly statusCode: number,
85
+ readonly headers: { [string]: string },
86
+ readonly cookies: $ReadOnlyArray<string>,
87
+ readonly body: string,
88
+ readonly isBase64Encoded: boolean,
89
+ |};
90
+
91
+ /** Everything the serverless half needs to answer an invocation. */
92
+ export type LambdaHandlerOptions = {|
93
+ /** The application, from the generated `handler.js`. */
94
+ readonly handle: (request: Request) => Promise<Response>,
95
+ /** That same module's `beginRequest`; see [`./node.js`]'s header for why. */
96
+ readonly beginRequest: (request: Request) => RequestLifecycle,
97
+ /**
98
+ * The directory holding the build's own files, if the package carries them.
99
+ *
100
+ * Omitted where a CDN answers for them; see the header.
101
+ */
102
+ readonly staticDir?: string,
103
+ |};
104
+
105
+ /**
106
+ * The `getSetCookie` half of `Headers`.
107
+ *
108
+ * Declared rather than called straight off the value because iterating
109
+ * `Headers` joins repeated fields with a comma, and `Set-Cookie` is the one
110
+ * field where that is a corruption rather than a spelling: two cookies become
111
+ * one header nothing can parse back apart. `getSetCookie` is the standard
112
+ * answer and every runtime that can run this has it — but a runtime that does
113
+ * not would throw here rather than at the point the cookies were set, so the
114
+ * absence is checked.
115
+ */
116
+ type SetCookieReader = {
117
+ readonly getSetCookie?: () => $ReadOnlyArray<string>,
118
+ ...
119
+ };
120
+
121
+ /**
122
+ * Media types whose bodies are text, and therefore not base64.
123
+ *
124
+ * The same shape of decision `./node.js` makes with `CONTENT_TYPES`, and the
125
+ * same default: what is not known to be text is returned base64-encoded, which
126
+ * is lossless for every byte sequence. Getting it the other way round would
127
+ * corrupt an image silently.
128
+ */
129
+ const TEXT_TYPES: $ReadOnlyArray<string> = Object.freeze([
130
+ "application/javascript",
131
+ "application/json",
132
+ "application/manifest+json",
133
+ "application/xml",
134
+ "image/svg+xml",
135
+ ]);
136
+
137
+ /** Whether a response with this `content-type` can be returned as a string. */
138
+ function isText(contentType: string | null): boolean {
139
+ if (contentType == null) return false;
140
+ const media = contentType.split(";")[0].trim().toLowerCase();
141
+ if (media.startsWith("text/")) return true;
142
+ if (media.endsWith("+json") || media.endsWith("+xml")) return true;
143
+ return TEXT_TYPES.includes(media);
144
+ }
145
+
146
+ /**
147
+ * The event as a `Request`.
148
+ *
149
+ * The URL is rebuilt rather than taken from a field, because no field holds
150
+ * one: the path is `rawPath`, the query is `rawQueryString`, and the authority
151
+ * is the `host` header the client sent — falling back to the API's own domain,
152
+ * which is what a health check with no `Host` arrives with. `https`, always:
153
+ * both a Function URL and an HTTP API terminate TLS, and there is no spelling
154
+ * of either that a browser reaches over `http`.
155
+ *
156
+ * Cookies come from `event.cookies` and not from a header, because that is
157
+ * where format 2.0 puts them — an application reading `cookies()` would
158
+ * otherwise see none of them, which is the kind of difference between a
159
+ * deployment and `uf start` this whole seam exists to prevent.
160
+ */
161
+ export function toRequest(event: LambdaHttpEvent): Request {
162
+ const method = event.requestContext?.http?.method;
163
+ const rawPath = event.rawPath;
164
+ if (typeof method !== "string" || typeof rawPath !== "string") {
165
+ throw new Error(
166
+ "uf: this handler reads AWS Lambda payload format 2.0 — a Lambda Function URL, " +
167
+ "or an API Gateway HTTP API — and the event it was given has no " +
168
+ "`requestContext.http.method` and `rawPath`. An API Gateway REST API sends " +
169
+ "format 1.0 and an ALB sends its own shape; neither is supported.",
170
+ );
171
+ }
172
+
173
+ const headers = new Headers();
174
+ const source = event.headers ?? {};
175
+ for (const name of Object.keys(source)) {
176
+ const value = source[name];
177
+ if (typeof value === "string") headers.set(name, value);
178
+ }
179
+ const cookies = event.cookies ?? [];
180
+ if (cookies.length > 0) headers.set("cookie", cookies.join("; "));
181
+
182
+ const authority =
183
+ headers.get("host") ?? event.requestContext?.domainName ?? "lambda.amazonaws.com";
184
+ const query = event.rawQueryString ?? "";
185
+ const url = new URL(`https://${authority}${rawPath}${query === "" ? "" : `?${query}`}`);
186
+
187
+ const init: { [string]: mixed } = { method: method.toUpperCase(), headers };
188
+ // `Request` refuses a body on a `GET` or a `HEAD`, and API Gateway is under
189
+ // no obligation not to send one: a client can, and the invocation would then
190
+ // fail with a `TypeError` from the constructor rather than answer.
191
+ if (typeof event.body === "string" && !["GET", "HEAD"].includes(method.toUpperCase())) {
192
+ init.body =
193
+ event.isBase64Encoded === true ? Buffer.from(event.body, "base64") : Buffer.from(event.body);
194
+ }
195
+ return new Request(url, init);
196
+ }
197
+
198
+ /** A `Response` as the JSON value Lambda returns to the client. */
199
+ export async function toResult(response: Response): Promise<LambdaHttpResult> {
200
+ const headers: { [string]: string } = {};
201
+ for (const [name, value] of response.headers) {
202
+ // Skipped here and carried in `cookies` below: see [`SetCookieReader`].
203
+ if (name.toLowerCase() === "set-cookie") continue;
204
+ headers[name] = value;
205
+ }
206
+ const reader: SetCookieReader = response.headers;
207
+ const cookies = typeof reader.getSetCookie === "function" ? [...reader.getSetCookie()] : [];
208
+
209
+ const body = Buffer.from(await response.arrayBuffer());
210
+ const text = isText(response.headers.get("content-type"));
211
+ return {
212
+ statusCode: response.status,
213
+ headers,
214
+ cookies,
215
+ body: text ? body.toString("utf8") : body.toString("base64"),
216
+ isBase64Encoded: !text,
217
+ };
218
+ }
219
+
220
+ /**
221
+ * A built uf application as a Lambda handler.
222
+ *
223
+ * Static files first, then the application — the order `uf preview` cannot
224
+ * deviate from and therefore the order every other front door matches. The
225
+ * request is begun here and settled once the body has been read into the
226
+ * result, which on this target is genuinely "the response has been produced":
227
+ * an invocation that returned before its `after()` callbacks ran would have
228
+ * them killed with the sandbox, so `settle` is awaited rather than deferred.
229
+ */
230
+ export function createLambdaHandler(
231
+ options: LambdaHandlerOptions,
232
+ ): (event: LambdaHttpEvent) => Promise<LambdaHttpResult> {
233
+ const { handle, beginRequest, staticDir } = options;
234
+ const serveStatic = staticDir == null ? null : createStaticHandler({ root: staticDir });
235
+
236
+ return async function lambdaHandler(event: LambdaHttpEvent): Promise<LambdaHttpResult> {
237
+ const request = toRequest(event);
238
+ const lifecycle = beginRequest(request);
239
+ try {
240
+ return await lifecycle.run(async () => {
241
+ const asset = serveStatic == null ? null : await serveStatic(request);
242
+ return await toResult(asset ?? (await handle(request)));
243
+ });
244
+ } catch (error) {
245
+ // The same 500 `./node.js`'s `nodeListener` writes, and for the same
246
+ // reasons: the body must not carry the stack, and the console — which on
247
+ // Lambda is CloudWatch — is where the operator is already looking. A
248
+ // rejected invocation would be a 502 from API Gateway instead, which is
249
+ // a different answer from `uf start`'s for the same failure.
250
+ //
251
+ // `toRequest` above is deliberately outside this: an event in the wrong
252
+ // format is a misconfigured function rather than a failed request, and
253
+ // answering it 500 forever would hide that.
254
+ console.error(error);
255
+ return {
256
+ statusCode: 500,
257
+ headers: { "content-type": "text/plain; charset=utf-8" },
258
+ cookies: [],
259
+ body: "500 Internal Server Error\n",
260
+ isBase64Encoded: false,
261
+ };
262
+ } finally {
263
+ await lifecycle.settle();
264
+ }
265
+ };
266
+ }