@loozo/angular-launch 0.0.5 → 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/README.md +1068 -187
- package/builders/application.js +32 -3
- package/builders/channel-forwarding.d.ts +15 -0
- package/builders/channel-forwarding.js +61 -0
- package/builders/options.d.ts +6 -2
- package/builders/options.js +16 -5
- package/builders/serve.js +198 -140
- package/channel.d.ts +55 -0
- package/channel.js +232 -0
- package/client.d.ts +63 -33
- package/connect.d.ts +201 -0
- package/connect.js +148 -0
- package/generation/index.d.ts +2 -123
- package/generation/index.js +3 -669
- package/generation/redirects.d.ts +14 -0
- package/generation/redirects.js +43 -0
- package/generation/run.d.ts +168 -0
- package/generation/run.js +659 -0
- package/index.d.ts +8 -1
- package/index.js +3 -0
- package/json.d.ts +9 -0
- package/json.js +24 -0
- package/launch-queries.d.ts +16 -0
- package/launch-queries.js +3 -0
- package/navigation.d.ts +36 -0
- package/navigation.js +47 -0
- package/node/index.d.ts +60 -0
- package/node/index.js +178 -0
- package/node/upgrade-listener-slot.d.ts +1 -0
- package/node/upgrade-listener-slot.js +4 -0
- package/outcomes.d.ts +71 -0
- package/outcomes.js +146 -0
- package/package.json +21 -11
- package/redirect-translation.d.ts +53 -0
- package/redirect-translation.js +141 -0
- package/{generated.d.ts → remote-client.d.ts} +1 -1
- package/remote-client.js +179 -0
- package/route-types.d.ts +130 -0
- package/route-types.js +1 -0
- package/route.d.ts +45 -0
- package/route.js +113 -0
- package/schemas/application.json +19 -3
- package/schemas/serve.json +3 -3
- package/server/application.d.ts +107 -0
- package/server/application.js +108 -0
- package/server/backend.d.ts +62 -31
- package/server/backend.js +149 -55
- package/server/channel-messages.d.ts +54 -0
- package/server/channel-messages.js +84 -0
- package/server/channel-socket.d.ts +67 -0
- package/server/channel-socket.js +322 -0
- package/server/definitions.d.ts +270 -294
- package/server/definitions.js +35 -115
- package/server/dispatch.d.ts +121 -66
- package/server/dispatch.js +267 -87
- package/server/event-stream.d.ts +63 -0
- package/server/event-stream.js +173 -0
- package/server/generated.d.ts +3 -1
- package/server/generated.js +3 -1
- package/server/index.d.ts +6 -3
- package/server/index.js +3 -2
- package/server/outcomes.d.ts +64 -2
- package/server/outcomes.js +85 -4
- package/server/read-cookies.d.ts +19 -0
- package/server/read-cookies.js +39 -0
- package/server/response-effects.d.ts +105 -0
- package/server/response-effects.js +78 -0
- package/server/stages.d.ts +62 -0
- package/server/stages.js +51 -0
- package/server/upgrade.d.ts +57 -0
- package/server/upgrade.js +116 -0
- package/source-text.d.ts +1 -0
- package/source-text.js +56 -0
- package/stream.d.ts +34 -0
- package/stream.js +161 -0
- package/tanstack-query/README.md +113 -21
- package/tanstack-query/create-queries.d.ts +2 -0
- package/tanstack-query/{generated.js → create-queries.js} +13 -11
- package/tanstack-query/hydration-window.d.ts +11 -0
- package/tanstack-query/hydration-window.js +9 -0
- package/tanstack-query/hydration.d.ts +4 -14
- package/tanstack-query/hydration.js +9 -12
- package/tanstack-query/index.d.ts +1 -1
- package/tanstack-query/queries.d.ts +50 -33
- package/testing/call-procedure.d.ts +154 -0
- package/testing/call-procedure.js +97 -0
- package/testing/index.d.ts +2 -0
- package/testing/index.js +1 -0
- package/generated.js +0 -90
- package/generation/context-file.d.ts +0 -2
- package/generation/context-file.js +0 -3
- package/tanstack-query/generated.d.ts +0 -5
package/server/dispatch.js
CHANGED
|
@@ -1,10 +1,41 @@
|
|
|
1
1
|
import { frameworkFailures } from "../client.js";
|
|
2
|
-
import { serializeJson } from "../json.js";
|
|
2
|
+
import { parseJson, serializeJson } from "../json.js";
|
|
3
3
|
import { inputIssues } from "../input-issues.js";
|
|
4
|
+
import { channelMessages, MessageRefused } from "./channel-messages.js";
|
|
4
5
|
import { declaredFailures } from "./errors.js";
|
|
6
|
+
import { eventStream } from "./event-stream.js";
|
|
5
7
|
import { outcomeOf } from "./outcomes.js";
|
|
6
|
-
|
|
8
|
+
import { createResponseEffects, } from "./response-effects.js";
|
|
9
|
+
import { createStageRunner } from "./stages.js";
|
|
10
|
+
// Shared by every copy of the package, so a scope one copy created runs its stages when
|
|
11
|
+
// another copy dispatches with it. The value holds the scope's stage runner and its
|
|
12
|
+
// rendering-call function.
|
|
13
|
+
const scopeMarker = Symbol.for("@loozo/angular-launch/private-request-scope/v3");
|
|
7
14
|
const bindingHeader = "x-loozo-launch-scope";
|
|
15
|
+
/**
|
|
16
|
+
* Runs one call made while rendering a page in the copy of the package that created
|
|
17
|
+
* `scope`, with that copy's application binding.
|
|
18
|
+
*
|
|
19
|
+
* @remarks
|
|
20
|
+
* Internal; not exported from a public entry point. Angular bundles the server entry, which
|
|
21
|
+
* creates the scope and answers RPCs, apart from the server application, which renders, so
|
|
22
|
+
* modules both import exist once in each bundle. Running the call in the creating copy
|
|
23
|
+
* runs the stages, middleware and handlers of the bundle that answers RPCs, so a page and
|
|
24
|
+
* an RPC of one server share their module state. The call otherwise runs as
|
|
25
|
+
* {@link runProcedure} in `"rendering"` mode, which checks the scope again.
|
|
26
|
+
*
|
|
27
|
+
* @param scope - A scope that passed {@link assertBoundScope} for the rendering application.
|
|
28
|
+
* @param path - The request path.
|
|
29
|
+
* @param envelope - The parsed request body.
|
|
30
|
+
* @param request - The page request the scope is bound to.
|
|
31
|
+
* @param signal - The call's abort signal.
|
|
32
|
+
* @param effects - Collects the call's cookies and headers.
|
|
33
|
+
* @returns The reply to deliver.
|
|
34
|
+
*/
|
|
35
|
+
export function runRenderingCall(scope, path, envelope, request, signal, effects) {
|
|
36
|
+
const state = scope[scopeMarker];
|
|
37
|
+
return state.render(path, envelope, request, signal, effects);
|
|
38
|
+
}
|
|
8
39
|
/**
|
|
9
40
|
* Checks whether a value has the shape of a {@link RequestScope}.
|
|
10
41
|
*
|
|
@@ -16,50 +47,56 @@ const bindingHeader = "x-loozo-launch-scope";
|
|
|
16
47
|
* @returns `true` for values carrying the request scope brand and fields.
|
|
17
48
|
*/
|
|
18
49
|
export function isRequestScope(value) {
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
50
|
+
if (typeof value !== "object" || value === null || !(scopeMarker in value)) {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
const runner = value[scopeMarker];
|
|
54
|
+
return (typeof runner === "object" &&
|
|
55
|
+
runner !== null &&
|
|
56
|
+
"run" in runner &&
|
|
57
|
+
typeof runner.run === "function" &&
|
|
58
|
+
"render" in runner &&
|
|
59
|
+
typeof runner.render === "function" &&
|
|
23
60
|
"request" in value &&
|
|
24
61
|
value.request instanceof Request &&
|
|
25
62
|
"appId" in value &&
|
|
26
63
|
typeof value.appId === "string" &&
|
|
27
64
|
"binding" in value &&
|
|
28
|
-
typeof value.binding === "string"
|
|
29
|
-
"value" in value);
|
|
65
|
+
typeof value.binding === "string");
|
|
30
66
|
}
|
|
31
67
|
/**
|
|
32
|
-
*
|
|
33
|
-
* {@link RequestScope}.
|
|
68
|
+
* Binds a live server request into a {@link RequestScope}, running nothing.
|
|
34
69
|
*
|
|
35
70
|
* @remarks
|
|
36
71
|
* Internal: exported only from `@loozo/angular-launch/_server` for the generated
|
|
37
|
-
* `
|
|
72
|
+
* `createRequestScope` in `server.generated.ts`; call that instead.
|
|
38
73
|
* The scope's `request` is a clone of `request` with an added
|
|
39
|
-
* `x-loozo-launch-scope` header, so the original stays usable.
|
|
40
|
-
*
|
|
74
|
+
* `x-loozo-launch-scope` header, so the original stays usable. Stages receive that clone
|
|
75
|
+
* and its signal. Calls made while rendering with the scope run with `application`, in
|
|
76
|
+
* this copy of the package: see {@link runRenderingCall}.
|
|
41
77
|
*
|
|
42
|
-
* @typeParam Definition - The application's context definition.
|
|
43
78
|
* @param application - The application binding.
|
|
44
79
|
* @param request - The live server request.
|
|
45
80
|
* @returns The request scope.
|
|
46
|
-
* @throws
|
|
47
|
-
* `TypeError` when `request`'s body was already read and can't be cloned.
|
|
81
|
+
* @throws TypeError when `request`'s body was already read and can't be cloned.
|
|
48
82
|
*/
|
|
49
|
-
export
|
|
83
|
+
export function createRequestScope(application, request) {
|
|
50
84
|
const binding = crypto.randomUUID();
|
|
51
85
|
const headers = new Headers(request.headers);
|
|
52
86
|
headers.set(bindingHeader, binding);
|
|
53
87
|
// Keep the caller's body usable and its signal linked via native Request clones.
|
|
54
88
|
const boundRequest = new Request(request.clone(), { headers });
|
|
55
|
-
const
|
|
56
|
-
|
|
89
|
+
const run = createStageRunner({ request: boundRequest, signal: boundRequest.signal });
|
|
90
|
+
const scope = {
|
|
57
91
|
appId: application.id,
|
|
58
92
|
binding,
|
|
59
93
|
request: boundRequest,
|
|
60
|
-
|
|
61
|
-
|
|
94
|
+
[scopeMarker]: {
|
|
95
|
+
run,
|
|
96
|
+
render: (path, envelope, pageRequest, signal, effects) => runProcedure(path, envelope, scope, application, pageRequest, "rendering", signal, effects),
|
|
97
|
+
},
|
|
62
98
|
};
|
|
99
|
+
return scope;
|
|
63
100
|
}
|
|
64
101
|
export function assertBoundScope(scope, application, request) {
|
|
65
102
|
if (!isRequestScope(scope) ||
|
|
@@ -70,6 +107,21 @@ export function assertBoundScope(scope, application, request) {
|
|
|
70
107
|
throw new Error("Launch request/application scope binding mismatch");
|
|
71
108
|
}
|
|
72
109
|
}
|
|
110
|
+
function outcomeReply(outcome, application) {
|
|
111
|
+
if (outcome.kind === "forbidden") {
|
|
112
|
+
return failure("FORBIDDEN");
|
|
113
|
+
}
|
|
114
|
+
if (outcome.kind === "notFound") {
|
|
115
|
+
return { status: 404, body: { notFound: null } };
|
|
116
|
+
}
|
|
117
|
+
// No Location header: fetch then hands the 303 to the client instead of following it.
|
|
118
|
+
// A translated app's page builds swap the listed static words into their own language; any
|
|
119
|
+
// other frame keeps exactly `{ to }`.
|
|
120
|
+
if (application.translateSegments && outcome.words.length > 0) {
|
|
121
|
+
return { status: 303, body: { redirect: { to: outcome.to, words: outcome.words } } };
|
|
122
|
+
}
|
|
123
|
+
return { status: 303, body: { redirect: { to: outcome.to } } };
|
|
124
|
+
}
|
|
73
125
|
export function failure(code) {
|
|
74
126
|
const frame = frameworkFailures[code];
|
|
75
127
|
return { status: frame.status, body: { error: { code, message: frame.message, data: null } } };
|
|
@@ -87,8 +139,7 @@ export function isJsonMediaType(contentType) {
|
|
|
87
139
|
return contentType?.split(";", 1)[0].trim().toLowerCase() === "application/json";
|
|
88
140
|
}
|
|
89
141
|
/**
|
|
90
|
-
* Runs `chain` in order around `last`, passing each middleware the context
|
|
91
|
-
* one continued with.
|
|
142
|
+
* Runs `chain` in order around `last`, passing each middleware the call's context.
|
|
92
143
|
*
|
|
93
144
|
* @remarks
|
|
94
145
|
* Rejects when a middleware throws, calls `next` twice (whether it then returns or
|
|
@@ -99,26 +150,22 @@ export function isJsonMediaType(contentType) {
|
|
|
99
150
|
* detached, or replaced it with another error such as `forbidden()`.
|
|
100
151
|
*/
|
|
101
152
|
async function runChain(chain, context, args, last) {
|
|
102
|
-
async function step(index
|
|
153
|
+
async function step(index) {
|
|
103
154
|
if (index === chain.length) {
|
|
104
|
-
await last(
|
|
155
|
+
await last();
|
|
105
156
|
return;
|
|
106
157
|
}
|
|
107
158
|
const token = {};
|
|
108
159
|
let calls = 0;
|
|
109
160
|
let rest;
|
|
110
|
-
function next(
|
|
161
|
+
function next() {
|
|
111
162
|
calls += 1;
|
|
112
163
|
let continued;
|
|
113
164
|
if (calls > 1) {
|
|
114
165
|
continued = Promise.reject(new Error("Launch middleware called next() more than once"));
|
|
115
166
|
}
|
|
116
167
|
else {
|
|
117
|
-
|
|
118
|
-
if (added !== undefined) {
|
|
119
|
-
merged = { ...current, ...added };
|
|
120
|
-
}
|
|
121
|
-
continued = step(index + 1, merged).then(() => token);
|
|
168
|
+
continued = step(index + 1).then(() => token);
|
|
122
169
|
rest = continued;
|
|
123
170
|
}
|
|
124
171
|
// A middleware that doesn't await this promise can't leave its rejection unhandled;
|
|
@@ -126,11 +173,19 @@ async function runChain(chain, context, args, last) {
|
|
|
126
173
|
continued.catch(() => undefined);
|
|
127
174
|
return continued;
|
|
128
175
|
}
|
|
129
|
-
const
|
|
176
|
+
const entry = chain[index];
|
|
177
|
+
let run;
|
|
178
|
+
// A bare function is the middleware's `run`.
|
|
179
|
+
if (typeof entry === "function") {
|
|
180
|
+
run = entry;
|
|
181
|
+
}
|
|
182
|
+
else {
|
|
183
|
+
run = entry.run;
|
|
184
|
+
}
|
|
130
185
|
let returned;
|
|
131
186
|
let thrown;
|
|
132
187
|
try {
|
|
133
|
-
returned = await run({ ...args, context
|
|
188
|
+
returned = await run({ ...args, context, next });
|
|
134
189
|
}
|
|
135
190
|
catch (error) {
|
|
136
191
|
thrown = { error };
|
|
@@ -149,7 +204,7 @@ async function runChain(chain, context, args, last) {
|
|
|
149
204
|
throw thrown.error;
|
|
150
205
|
}
|
|
151
206
|
}
|
|
152
|
-
await step(0
|
|
207
|
+
await step(0);
|
|
153
208
|
}
|
|
154
209
|
async function declaredReply(procedure, error) {
|
|
155
210
|
let declared;
|
|
@@ -184,48 +239,79 @@ async function declaredReply(procedure, error) {
|
|
|
184
239
|
*
|
|
185
240
|
* In order: the scope must belong to `application` and `request` (`INTERNAL`); the
|
|
186
241
|
* path must be `/_rpc/<namespace>/<procedure>` for a registered procedure
|
|
187
|
-
* (`RPC_NOT_FOUND`); a mutation in `"rendering"` mode is refused
|
|
242
|
+
* (`RPC_NOT_FOUND`); a mutation, stream or channel in `"rendering"` mode is refused
|
|
243
|
+
* (`FORBIDDEN`); a channel in `"http"` mode, or any other kind in `"socket"` mode, is
|
|
244
|
+
* `RPC_NOT_FOUND`; the
|
|
188
245
|
* envelope must be strict JSON (`INTERNAL` otherwise, such as for `{ input: undefined }`,
|
|
189
246
|
* a cycle or an accessor), and exactly `{ input }` (`INVALID_INPUT` with no issues);
|
|
190
|
-
* the
|
|
247
|
+
* the owning route's stages run, root first, each at most once per scope (a stage that
|
|
248
|
+
* throws `forbidden()`, `notFound()` or `redirect()` answers with that outcome, and any
|
|
249
|
+
* other failure gives `INTERNAL` with the reply's `failedStage` naming it); the owning
|
|
250
|
+
* route's `.use()` middleware runs with no input; the input must pass the schema
|
|
191
251
|
* (`INVALID_INPUT` with the schema's issues), or be `null` without one (`INVALID_INPUT`
|
|
192
252
|
* with no issues); the procedure's middleware runs with the validated input; then the
|
|
193
253
|
* handler. The handler's strict JSON result is returned with status 200, and its
|
|
194
254
|
* declared errors with their status. `forbidden()` thrown from middleware or the
|
|
195
|
-
* handler gives `FORBIDDEN
|
|
196
|
-
*
|
|
255
|
+
* handler gives `FORBIDDEN`, `notFound()` a 404 with `{ notFound: null }` and
|
|
256
|
+
* `redirect()` a 303 with `{ redirect: { to } }` (plus `words` in a translated application);
|
|
257
|
+
* a middleware that calls `next` twice
|
|
258
|
+
* or doesn't return its result gives `INTERNAL`.
|
|
259
|
+
*
|
|
260
|
+
* A stream's handler returns an iterable instead of a result. Its iterator goes to
|
|
261
|
+
* `start`, and the call goes on until the stream ends: the reply is then a 200 with
|
|
262
|
+
* `null` body, or the failure the stream ended with. Without `start`, a stream fails
|
|
263
|
+
* with `INTERNAL`.
|
|
264
|
+
*
|
|
265
|
+
* A channel runs like a stream, and its handler also receives `messages`, read from
|
|
266
|
+
* `inbox` and validated with its message schema. A message that fails validation, or a
|
|
267
|
+
* protocol violation the inbox reports, ends the call with `INVALID_INPUT`.
|
|
268
|
+
*
|
|
269
|
+
* Stages, middleware and handlers set cookies and headers through `effects.control`; the
|
|
270
|
+
* caller commits and applies them. A stage writes to the call that first ran it.
|
|
197
271
|
*
|
|
198
|
-
* @param registry - The application's RPC groups.
|
|
199
272
|
* @param path - The request path.
|
|
200
273
|
* @param envelope - The parsed request body.
|
|
201
|
-
* @param scope - The request scope whose
|
|
274
|
+
* @param scope - The request scope whose stages the call runs.
|
|
202
275
|
* @param application - The application binding the scope must belong to.
|
|
203
276
|
* @param request - The request the scope must be bound to.
|
|
204
|
-
* @param mode - `"http"` for browser requests (the default)
|
|
205
|
-
* made during server rendering.
|
|
277
|
+
* @param mode - `"http"` for browser requests (the default), `"socket"` for websocket
|
|
278
|
+
* upgrades, or `"rendering"` for calls made during server rendering.
|
|
206
279
|
* @param signal - The call's abort signal. Defaults to `request`'s signal.
|
|
280
|
+
* @param effects - Collects the call's cookies and headers. Defaults to fresh effects
|
|
281
|
+
* nothing reads.
|
|
282
|
+
* @param start - Receives a stream's or channel's iterator once its handler returned it.
|
|
283
|
+
* @param inbox - A channel's incoming messages.
|
|
207
284
|
* @returns The reply to send.
|
|
208
285
|
*/
|
|
209
|
-
export async function
|
|
286
|
+
export async function runProcedure(path, envelope, scope, application, request, mode = "http", signal = request.signal, effects = createResponseEffects(), start, inbox) {
|
|
210
287
|
try {
|
|
211
288
|
assertBoundScope(scope, application, request);
|
|
212
289
|
const parts = /^\/_rpc\/([A-Za-z_][A-Za-z0-9_]*)\/([A-Za-z_][A-Za-z0-9_]*)$/.exec(path);
|
|
213
|
-
if (!parts || !Object.hasOwn(
|
|
290
|
+
if (!parts || !Object.hasOwn(application.namespaces, parts[1])) {
|
|
214
291
|
return failure("RPC_NOT_FOUND");
|
|
215
292
|
}
|
|
216
|
-
const
|
|
217
|
-
if (!Object.hasOwn(
|
|
293
|
+
const namespace = application.namespaces[parts[1]];
|
|
294
|
+
if (!Object.hasOwn(namespace.procedures, parts[2])) {
|
|
218
295
|
return failure("RPC_NOT_FOUND");
|
|
219
296
|
}
|
|
220
|
-
const procedure =
|
|
221
|
-
if (procedure.kind !== "query" &&
|
|
222
|
-
|
|
297
|
+
const procedure = namespace.procedures[parts[2]];
|
|
298
|
+
if (procedure.kind !== "query" &&
|
|
299
|
+
procedure.kind !== "mutation" &&
|
|
300
|
+
procedure.kind !== "stream" &&
|
|
301
|
+
procedure.kind !== "channel") {
|
|
302
|
+
throw new Error("Launch application contains an unsupported procedure");
|
|
223
303
|
}
|
|
224
304
|
// Rendering never performs writes, even for unmarked HttpClient calls or
|
|
225
|
-
// callers/interceptors that relabel a generated method or enable caching.
|
|
226
|
-
|
|
305
|
+
// callers/interceptors that relabel a generated method or enable caching. Streams
|
|
306
|
+
// and channels don't finish, so they don't run during rendering either.
|
|
307
|
+
if (mode === "rendering" && procedure.kind !== "query") {
|
|
227
308
|
return failure("FORBIDDEN");
|
|
228
309
|
}
|
|
310
|
+
// A channel exists only as a websocket, and a websocket carries only channels.
|
|
311
|
+
const isChannel = procedure.kind === "channel";
|
|
312
|
+
if ((mode === "http" && isChannel) || (mode === "socket" && !isChannel)) {
|
|
313
|
+
return failure("RPC_NOT_FOUND");
|
|
314
|
+
}
|
|
229
315
|
// Even direct transport crosses the exact same strict JSON boundary.
|
|
230
316
|
const normalized = JSON.parse(serializeJson(envelope));
|
|
231
317
|
if (typeof normalized !== "object" ||
|
|
@@ -236,9 +322,28 @@ export async function dispatch(registry, path, envelope, scope, application, req
|
|
|
236
322
|
return invalidInput();
|
|
237
323
|
}
|
|
238
324
|
let reply;
|
|
325
|
+
const response = effects.control;
|
|
326
|
+
let context = {};
|
|
327
|
+
if (namespace.stages.length > 0) {
|
|
328
|
+
const stages = namespace.stages;
|
|
329
|
+
const state = scope[scopeMarker];
|
|
330
|
+
const staged = await state.run(stages, response);
|
|
331
|
+
if ("failed" in staged) {
|
|
332
|
+
const outcome = outcomeOf(staged.error);
|
|
333
|
+
if (outcome !== undefined) {
|
|
334
|
+
return outcomeReply(outcome, application);
|
|
335
|
+
}
|
|
336
|
+
console.error("Launch context stage failed", staged.error);
|
|
337
|
+
return {
|
|
338
|
+
...failure("INTERNAL"),
|
|
339
|
+
failedStage: { route: staged.failed.route, error: staged.error },
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
context = staged.context;
|
|
343
|
+
}
|
|
239
344
|
try {
|
|
240
|
-
//
|
|
241
|
-
await runChain(
|
|
345
|
+
// The route's middleware runs before validation, so it never sees the raw input.
|
|
346
|
+
await runChain(namespace.use, context, { input: undefined, request, signal, response }, async () => {
|
|
242
347
|
let input;
|
|
243
348
|
if (procedure.input) {
|
|
244
349
|
const parsed = await procedure.input["~standard"].validate(normalized.input);
|
|
@@ -252,16 +357,44 @@ export async function dispatch(registry, path, envelope, scope, application, req
|
|
|
252
357
|
reply = invalidInput();
|
|
253
358
|
return;
|
|
254
359
|
}
|
|
255
|
-
await runChain(procedure.use,
|
|
256
|
-
const
|
|
257
|
-
|
|
360
|
+
await runChain(procedure.use, context, { input, request, signal, response }, async () => {
|
|
361
|
+
const args = { context, input, request, signal, response };
|
|
362
|
+
if (isChannel) {
|
|
363
|
+
// The caller left while the pipeline ran: the handler doesn't run, and the
|
|
364
|
+
// middleware's `next()` resolves.
|
|
365
|
+
if (signal.aborted) {
|
|
366
|
+
reply = { status: 200, body: null };
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
if (!inbox || !procedure.message) {
|
|
370
|
+
throw new Error("Launch channels need a websocket and a message schema");
|
|
371
|
+
}
|
|
372
|
+
args.messages = channelMessages(inbox, procedure.message);
|
|
373
|
+
}
|
|
374
|
+
const output = await procedure.handler(args);
|
|
375
|
+
if (procedure.kind !== "stream" && !isChannel) {
|
|
376
|
+
reply = { status: 200, body: JSON.parse(serializeJson(output)) };
|
|
377
|
+
return;
|
|
378
|
+
}
|
|
379
|
+
if (!start) {
|
|
380
|
+
throw new Error("Launch streams need an HTTP response to run in");
|
|
381
|
+
}
|
|
382
|
+
const iterator = output[Symbol.asyncIterator]();
|
|
383
|
+
const finished = Promise.withResolvers();
|
|
384
|
+
start({ iterator, finished });
|
|
385
|
+
await finished.promise;
|
|
386
|
+
reply = { status: 200, body: null };
|
|
258
387
|
});
|
|
259
388
|
});
|
|
260
389
|
}
|
|
261
390
|
catch (error) {
|
|
262
391
|
const outcome = outcomeOf(error);
|
|
263
|
-
if (outcome
|
|
264
|
-
return
|
|
392
|
+
if (outcome !== undefined) {
|
|
393
|
+
return outcomeReply(outcome, application);
|
|
394
|
+
}
|
|
395
|
+
// The caller sent a bad message: its own fault, not an unexpected failure.
|
|
396
|
+
if (error instanceof MessageRefused) {
|
|
397
|
+
return invalidInput(error.issues);
|
|
265
398
|
}
|
|
266
399
|
return await declaredReply(procedure, error);
|
|
267
400
|
}
|
|
@@ -275,7 +408,15 @@ export async function dispatch(registry, path, envelope, scope, application, req
|
|
|
275
408
|
return failure("INTERNAL");
|
|
276
409
|
}
|
|
277
410
|
}
|
|
278
|
-
|
|
411
|
+
/** The plain-text 400 for an RPC to a host that isn't allowed, logged. */
|
|
412
|
+
export function hostRefusal(hostname) {
|
|
413
|
+
console.error(`Launch refused an RPC for host ${hostname}`);
|
|
414
|
+
return new Response("Host not allowed", {
|
|
415
|
+
status: 400,
|
|
416
|
+
headers: { "content-type": "text/plain", "x-content-type-options": "nosniff" },
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
export function hostAllowed(hostname, allowedHosts) {
|
|
279
420
|
for (const allowed of allowedHosts) {
|
|
280
421
|
if (allowed === "*" || allowed === hostname) {
|
|
281
422
|
return true;
|
|
@@ -287,7 +428,7 @@ function hostAllowed(hostname, allowedHosts) {
|
|
|
287
428
|
return false;
|
|
288
429
|
}
|
|
289
430
|
/** Why `request` can't be proven same-origin, or `undefined` when it can. */
|
|
290
|
-
function crossSiteReason(request, origins) {
|
|
431
|
+
export function crossSiteReason(request, origins) {
|
|
291
432
|
const site = request.headers.get("sec-fetch-site");
|
|
292
433
|
const origin = request.headers.get("origin");
|
|
293
434
|
if (origin !== null && origins.includes(origin)) {
|
|
@@ -321,31 +462,36 @@ function crossSiteReason(request, origins) {
|
|
|
321
462
|
* app's own origin, otherwise the reply is `FORBIDDEN`: an `Origin` listed in `origins`
|
|
322
463
|
* passes; otherwise `Sec-Fetch-Site`, when sent, must be `same-origin`; otherwise
|
|
323
464
|
* `Origin`, when sent, must equal the request URL's origin; a request with neither
|
|
324
|
-
* header is refused. No
|
|
325
|
-
*
|
|
326
|
-
*
|
|
327
|
-
* no issues.
|
|
465
|
+
* header is refused. No stage runs for any of these refusals. A fresh request scope is
|
|
466
|
+
* then created, which runs nothing, and a body that isn't JSON gives `INVALID_INPUT` with
|
|
467
|
+
* no issues before any stage runs.
|
|
328
468
|
* JSON responses carry `Cache-Control: private, no-store`, `Vary: Cookie` and
|
|
329
469
|
* `X-Content-Type-Options: nosniff`.
|
|
330
470
|
*
|
|
331
|
-
* @
|
|
332
|
-
*
|
|
471
|
+
* Once the call reached {@link runProcedure}, its response carries the headers and cookies the
|
|
472
|
+
* call set, whatever its outcome. Launch's own headers replace the call's headers of the
|
|
473
|
+
* same name, and each cookie adds a `Set-Cookie` header.
|
|
474
|
+
*
|
|
475
|
+
* A stream answers like any call until its handler returns its iterable. From then on the
|
|
476
|
+
* response is a 200 `text/event-stream` (see `eventStream`) with
|
|
477
|
+
* `Cache-Control: private, no-store, no-transform`, `Vary: Cookie`,
|
|
478
|
+
* `X-Content-Type-Options: nosniff` and `X-Accel-Buffering: no`, and the call's signal
|
|
479
|
+
* also aborts when the host cancels the body. The response's cookies and headers are the
|
|
480
|
+
* ones set when the handler returned its iterable: setting a cookie later throws, and
|
|
481
|
+
* later header changes are ignored.
|
|
482
|
+
*
|
|
333
483
|
* @param application - The application binding.
|
|
334
484
|
* @param request - The incoming server request.
|
|
335
485
|
* @param options - The allowed hosts and further allowed origins.
|
|
336
486
|
* @returns The RPC response, or `null` when the path doesn't start with `/_rpc/`.
|
|
337
487
|
*/
|
|
338
|
-
export async function handleRpc(
|
|
488
|
+
export async function handleRpc(application, request, { allowedHosts, origins = [] }) {
|
|
339
489
|
const url = new URL(request.url);
|
|
340
490
|
if (!url.pathname.startsWith("/_rpc/")) {
|
|
341
491
|
return null;
|
|
342
492
|
}
|
|
343
493
|
if (!hostAllowed(url.hostname, allowedHosts)) {
|
|
344
|
-
|
|
345
|
-
return new Response("Host not allowed", {
|
|
346
|
-
status: 400,
|
|
347
|
-
headers: { "content-type": "text/plain", "x-content-type-options": "nosniff" },
|
|
348
|
-
});
|
|
494
|
+
return hostRefusal(url.hostname);
|
|
349
495
|
}
|
|
350
496
|
if (request.method !== "POST" ||
|
|
351
497
|
!isJsonMediaType(request.headers.get("content-type")) ||
|
|
@@ -357,32 +503,66 @@ export async function handleRpc(registry, application, request, { allowedHosts,
|
|
|
357
503
|
console.error(`Launch refused a cross-origin RPC: ${crossSite}`);
|
|
358
504
|
return response(failure("FORBIDDEN"));
|
|
359
505
|
}
|
|
506
|
+
const effects = createResponseEffects();
|
|
360
507
|
let reply;
|
|
361
508
|
try {
|
|
362
|
-
const scope =
|
|
509
|
+
const scope = createRequestScope(application, request);
|
|
363
510
|
let envelope;
|
|
364
511
|
try {
|
|
365
|
-
envelope = await request.
|
|
512
|
+
envelope = parseJson(await request.text());
|
|
366
513
|
}
|
|
367
514
|
catch {
|
|
368
515
|
return response(invalidInput());
|
|
369
516
|
}
|
|
370
|
-
|
|
517
|
+
// Hosts cancel a streaming body when its client goes away; that aborts the call too.
|
|
518
|
+
const cancel = new AbortController();
|
|
519
|
+
const signal = AbortSignal.any([scope.request.signal, cancel.signal]);
|
|
520
|
+
const started = Promise.withResolvers();
|
|
521
|
+
const outcome = runProcedure(url.pathname, envelope, scope, application, scope.request, "http", signal, effects, started.resolve);
|
|
522
|
+
// Failures before a stream's handler returned are ordinary replies.
|
|
523
|
+
const first = await Promise.race([outcome, started.promise]);
|
|
524
|
+
if ("iterator" in first) {
|
|
525
|
+
// The response starts now; the rest of the call is the stream itself.
|
|
526
|
+
effects.commit();
|
|
527
|
+
return streamResponse(eventStream(first, outcome, cancel, signal), effects);
|
|
528
|
+
}
|
|
529
|
+
reply = first;
|
|
371
530
|
}
|
|
372
531
|
catch (error) {
|
|
373
|
-
console.error("Launch
|
|
532
|
+
console.error("Launch request scope failed", error);
|
|
374
533
|
reply = failure("INTERNAL");
|
|
375
534
|
}
|
|
376
|
-
|
|
535
|
+
effects.commit();
|
|
536
|
+
return response(reply, effects);
|
|
377
537
|
}
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
538
|
+
/** The call's headers, then Launch's own over them, then the call's cookies. */
|
|
539
|
+
export function responseHeaders(own, effects) {
|
|
540
|
+
const headers = new Headers(effects?.headers);
|
|
541
|
+
for (const [name, value] of Object.entries(own)) {
|
|
542
|
+
headers.set(name, value);
|
|
543
|
+
}
|
|
544
|
+
for (const cookie of effects?.cookies ?? []) {
|
|
545
|
+
headers.append("set-cookie", cookie);
|
|
546
|
+
}
|
|
547
|
+
return headers;
|
|
548
|
+
}
|
|
549
|
+
function streamResponse(body, effects) {
|
|
550
|
+
const headers = responseHeaders({
|
|
551
|
+
"content-type": "text/event-stream",
|
|
552
|
+
"cache-control": "private, no-store, no-transform",
|
|
553
|
+
vary: "Cookie",
|
|
554
|
+
"x-content-type-options": "nosniff",
|
|
555
|
+
// nginx buffers proxied responses unless told not to.
|
|
556
|
+
"x-accel-buffering": "no",
|
|
557
|
+
}, effects);
|
|
558
|
+
return new Response(body, { status: 200, headers });
|
|
559
|
+
}
|
|
560
|
+
export function response(reply, effects) {
|
|
561
|
+
const headers = responseHeaders({
|
|
562
|
+
"content-type": "application/json",
|
|
563
|
+
"cache-control": "private, no-store",
|
|
564
|
+
vary: "Cookie",
|
|
565
|
+
"x-content-type-options": "nosniff",
|
|
566
|
+
}, effects);
|
|
567
|
+
return new Response(serializeJson(reply.body), { status: reply.status, headers });
|
|
388
568
|
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { Reply } from "./dispatch.js";
|
|
2
|
+
/** How often a stream sends a comment, so idle proxies keep its connection open. */
|
|
3
|
+
export declare const keepAliveMs = 15000;
|
|
4
|
+
/**
|
|
5
|
+
* A stream whose handler returned its iterable: the response can start.
|
|
6
|
+
*
|
|
7
|
+
* @remarks
|
|
8
|
+
* Internal. `runProcedure` hands it over and waits for `finished`: resolving it ends the
|
|
9
|
+
* handler's part of the call, rejecting it fails the call with that error.
|
|
10
|
+
*/
|
|
11
|
+
export interface StreamStart {
|
|
12
|
+
/** The handler's iterator. */
|
|
13
|
+
readonly iterator: AsyncIterator<unknown>;
|
|
14
|
+
/** Settles the handler's part of the call. */
|
|
15
|
+
readonly finished: {
|
|
16
|
+
readonly resolve: () => void;
|
|
17
|
+
readonly reject: (error: unknown) => void;
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Ends the handler's part of a stream or channel that stopped early, such as when its caller
|
|
22
|
+
* went away.
|
|
23
|
+
*
|
|
24
|
+
* @remarks
|
|
25
|
+
* Internal. Lets the handler's pending step finish, then asks the iterator to return, which
|
|
26
|
+
* runs a generator's `finally` blocks. The step's failure, if any, settles the call, but only
|
|
27
|
+
* after that cleanup ran.
|
|
28
|
+
*
|
|
29
|
+
* @param start - The started stream or channel.
|
|
30
|
+
* @param pending - The handler's last requested step, if any.
|
|
31
|
+
*/
|
|
32
|
+
export declare function settleStopped(start: StreamStart, pending: Promise<IteratorResult<unknown>> | undefined): Promise<void>;
|
|
33
|
+
/**
|
|
34
|
+
* The frame that ends a failed stream or channel: the reply's body with its status, as
|
|
35
|
+
* `{ status, error }`, `{ status, redirect }` or `{ status, notFound }`.
|
|
36
|
+
*
|
|
37
|
+
* @param reply - The call's failure reply.
|
|
38
|
+
* @returns The frame as strict JSON text.
|
|
39
|
+
*/
|
|
40
|
+
export declare function failureFrame(reply: Reply): string;
|
|
41
|
+
/**
|
|
42
|
+
* The `text/event-stream` body of a started stream.
|
|
43
|
+
*
|
|
44
|
+
* @remarks
|
|
45
|
+
* Internal. Sends one `value` event per yielded value, then, once the whole call settled
|
|
46
|
+
* (`outcome`, middleware included), one `end` event or one `error` event whose data is
|
|
47
|
+
* the reply's frame with its status: `{ status, error }`, `{ status, redirect }` or
|
|
48
|
+
* `{ status, notFound }`. A comment goes out every {@link keepAliveMs}.
|
|
49
|
+
*
|
|
50
|
+
* Pull-based, so a slow reader pauses the handler. A yielded value that isn't strict JSON
|
|
51
|
+
* fails the call. The stream stops when `signal` aborts, which it does when the host
|
|
52
|
+
* cancels the body or aborts the request: the body errors, the handler's pending step is
|
|
53
|
+
* awaited and the iterator asked to return, which runs a generator's `finally` blocks once
|
|
54
|
+
* it next yields. The handler's part of the call then ends, with the failure if that step
|
|
55
|
+
* threw, so middleware that wraps the stream never cleans up under a running handler.
|
|
56
|
+
*
|
|
57
|
+
* @param start - The started stream.
|
|
58
|
+
* @param outcome - The whole call's reply, from `runProcedure`.
|
|
59
|
+
* @param cancel - Aborted when the body is cancelled.
|
|
60
|
+
* @param signal - The call's signal: it follows `cancel` and the request's signal.
|
|
61
|
+
* @returns The response body.
|
|
62
|
+
*/
|
|
63
|
+
export declare function eventStream(start: StreamStart, outcome: Promise<Reply>, cancel: AbortController, signal: AbortSignal): ReadableStream<Uint8Array>;
|