@midsummer-ai/sdk 0.1.0-staging.3772 → 0.1.0-staging.3778

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.
@@ -1,8 +1,373 @@
1
1
  import { r as platformApi } from "./here-BKjizr_N.mjs";
2
2
  import { n as bytesTagged, r as bytesUntagged } from "./bytes-C2pcyl9u.mjs";
3
3
  import { DatabaseError } from "./database/errors.mjs";
4
- import { i as payloadOf, r as fetchAt, t as Connection } from "./connection-C_JSWUrt.mjs";
4
+ import { a as socketAt, i as payloadOf, r as fetchAt, t as Connection } from "./connection-CpT0x1EE.mjs";
5
5
  import { t as callKey } from "./key-BrRdFY-n.mjs";
6
+ //#region src/database/door-socket.ts
7
+ /**
8
+ * The Database's socket protocol: binary frames on one TCP + TLS connection a server opens itself, many calls in flight
9
+ * and watches beside them. A Deployment's server opens one per request (`DoorSocket`) at the socket address its door
10
+ * names; `client.ts` decides what goes on it. All integers are little-endian.
11
+ *
12
+ * const socket = new DoorSocket(handle.socket("host:port"), "db-<id>", "Bearer <token>")
13
+ * if (socket.ready("Bearer <token>", body.length)) const { status, text } = await socket.call(body)
14
+ *
15
+ * - **Hello**, the client's first bytes, once: `MAGIC`, a u32 of the bytes after it, a u8 form (`FORM_JSON`), a u16 and
16
+ * the Database (`db-<id>`), a u16 and the token (the Authorization value). Frames may follow it at once; it is answered
17
+ * `HELLO_OK` (id 0: u32 calls allowed in flight, u32 the largest call), or `REFUSED` (id 0: u16 status, a JSON body)
18
+ * and the socket closes.
19
+ * - **Frames**, both ways: a u32 of the bytes after it (5 + the payload), a u32 id, a u8 kind, the payload. The client
20
+ * picks ids, unique among its unanswered calls and open watches; 0 is the hello's.
21
+ * - A `CALL`'s payload is exactly a `POST <door>/call` body, answered `ANSWER`: u16 HTTP status, u8 form, the body, in
22
+ * whatever order calls finish. A `WATCH` opens a watch, answered `OPENED` (u16 status, 101 open), then `DATA` for each
23
+ * message the Database pushes; `DATA` from the client is a message on it; `CLOSE` either way ends it.
24
+ */
25
+ /** A hello's first 4 bytes, by which the address knows the socket protocol from HTTP. */
26
+ const MAGIC = Uint8Array.of(0, 71, 72, 1);
27
+ /** The most a hello may hold after its magic and length. */
28
+ const MAX_HELLO = 16384;
29
+ /** The largest frame the Database sends: a push of 64 MiB, its id and kind. */
30
+ const MAX_FRAME = 67108869;
31
+ /** Until the hello is answered: calls in flight and a call's bytes, the Database's bounds. */
32
+ const IN_FLIGHT = 1024;
33
+ const MAX_CALL = 2 << 20;
34
+ const encoder$1 = new TextEncoder();
35
+ const decoder = new TextDecoder();
36
+ /** The client's hello for `database` (`db-<id>`) with `authorization` (`Bearer <token>`), bodies as JSON. */
37
+ function hello(database, authorization, form = 0) {
38
+ const db = encoder$1.encode(database), auth = encoder$1.encode(authorization);
39
+ const n = 5 + db.length + auth.length;
40
+ if (n > MAX_HELLO) throw new RangeError(`a hello holds at most ${MAX_HELLO} bytes; this one is ${n}`);
41
+ const out = new Uint8Array(8 + n), view = new DataView(out.buffer);
42
+ out.set(MAGIC, 0);
43
+ view.setUint32(4, n, true);
44
+ out[8] = form;
45
+ view.setUint16(9, db.length, true);
46
+ out.set(db, 11);
47
+ view.setUint16(11 + db.length, auth.length, true);
48
+ out.set(auth, 13 + db.length);
49
+ return out;
50
+ }
51
+ /** A frame either way: its length, `id`, `kind`, then `payload`. */
52
+ function frame(id, kind, payload = /* @__PURE__ */ new Uint8Array(0)) {
53
+ const out = new Uint8Array(9 + payload.length), view = new DataView(out.buffer);
54
+ view.setUint32(0, 5 + payload.length, true);
55
+ view.setUint32(4, id, true);
56
+ out[8] = kind;
57
+ out.set(payload, 9);
58
+ return out;
59
+ }
60
+ /** Frames out of the bytes a socket reads, however they are split. */
61
+ var FrameReader = class {
62
+ #chunks = [];
63
+ #size = 0;
64
+ #length;
65
+ /** The frames `chunk` completes, in order. A length no frame can have throws: the socket is not speaking the protocol. */
66
+ push(chunk) {
67
+ if (chunk.length) {
68
+ this.#chunks.push(chunk);
69
+ this.#size += chunk.length;
70
+ }
71
+ const frames = [];
72
+ for (;;) {
73
+ if (this.#length === void 0) {
74
+ if (this.#size < 9) break;
75
+ const head = this.#peek(4);
76
+ const length = new DataView(head.buffer, head.byteOffset, 4).getUint32(0, true);
77
+ if (length < 5 || length > MAX_FRAME) throw new RangeError(`a frame of ${length} bytes`);
78
+ this.#length = length;
79
+ }
80
+ if (this.#size < 4 + this.#length) break;
81
+ const bytes = this.#take(4 + this.#length);
82
+ this.#length = void 0;
83
+ frames.push({
84
+ id: new DataView(bytes.buffer, bytes.byteOffset, 8).getUint32(4, true),
85
+ kind: bytes[8],
86
+ body: bytes.subarray(9)
87
+ });
88
+ }
89
+ return frames;
90
+ }
91
+ #peek(n) {
92
+ const first = this.#chunks[0];
93
+ if (first.length >= n) return first;
94
+ const out = new Uint8Array(n);
95
+ let at = 0;
96
+ for (const chunk of this.#chunks) {
97
+ const part = chunk.subarray(0, n - at);
98
+ out.set(part, at);
99
+ at += part.length;
100
+ if (at === n) break;
101
+ }
102
+ return out;
103
+ }
104
+ #take(n) {
105
+ const first = this.#chunks[0];
106
+ let out;
107
+ if (first.length >= n) {
108
+ out = first.subarray(0, n);
109
+ if (first.length === n) this.#chunks.shift();
110
+ else this.#chunks[0] = first.subarray(n);
111
+ } else {
112
+ out = new Uint8Array(n);
113
+ let at = 0;
114
+ while (at < n) {
115
+ const chunk = this.#chunks[0], part = chunk.subarray(0, n - at);
116
+ out.set(part, at);
117
+ at += part.length;
118
+ if (part.length === chunk.length) this.#chunks.shift();
119
+ else this.#chunks[0] = chunk.subarray(part.length);
120
+ }
121
+ }
122
+ this.#size -= n;
123
+ return out;
124
+ }
125
+ };
126
+ /** What a call or watch on a socket that ended rejects with: nothing reached the Database that it answered, so send it another way. */
127
+ var SocketClosed = class extends Error {
128
+ closed = true;
129
+ constructor() {
130
+ super("the database's socket closed");
131
+ }
132
+ };
133
+ /** A watch the Database refused to open, with its status and why: the same refusal a WebSocket's open would get. */
134
+ var WatchRefused = class extends Error {
135
+ status;
136
+ constructor(status, why) {
137
+ super(why || `the database refused the watch (${status})`);
138
+ this.status = status;
139
+ }
140
+ };
141
+ /**
142
+ * One watch on a `DoorSocket`, in the shape of a WebSocket, so a `Connection` runs on it (its `dial`). The Database's
143
+ * own first message on a socket is its hello, which the socket's `HELLO_OK` stands in for and which never reaches the
144
+ * watch: an empty one is told to the watch's first listener, so the connection sends at once to the one unit a
145
+ * Database has.
146
+ */
147
+ var SocketWatch = class {
148
+ id;
149
+ socket;
150
+ readyState = 0;
151
+ binaryType = "arraybuffer";
152
+ #messages = /* @__PURE__ */ new Set();
153
+ #closes = /* @__PURE__ */ new Set();
154
+ #helloTold = false;
155
+ constructor(id, socket) {
156
+ this.id = id;
157
+ this.socket = socket;
158
+ }
159
+ addEventListener(type, listener) {
160
+ if (type === "message") {
161
+ this.#messages.add(listener);
162
+ if (!this.#helloTold) {
163
+ this.#helloTold = true;
164
+ queueMicrotask(() => this.message("{\"hello\":{}}"));
165
+ }
166
+ } else if (type === "close") this.#closes.add(listener);
167
+ }
168
+ removeEventListener(type, listener) {
169
+ if (type === "message") this.#messages.delete(listener);
170
+ else if (type === "close") this.#closes.delete(listener);
171
+ }
172
+ send(text) {
173
+ if (this.readyState !== 1) throw new SocketClosed();
174
+ this.socket.send(frame(this.id, 3, encoder$1.encode(text)));
175
+ }
176
+ /** Ends the watch: the Database is told, and its close heard here once. */
177
+ close() {
178
+ if (this.readyState === 3) return;
179
+ if (this.socket.state !== "closed") this.socket.send(frame(this.id, 4));
180
+ this.ended();
181
+ }
182
+ /** @internal The Database's message on it. */
183
+ message(data) {
184
+ if (this.readyState === 1) for (const listener of [...this.#messages]) listener({ data });
185
+ }
186
+ /** @internal It ended: its close is heard once. */
187
+ ended() {
188
+ if (this.readyState === 3) return;
189
+ this.readyState = 3;
190
+ this.socket.forget(this.id);
191
+ queueMicrotask(() => {
192
+ for (const listener of [...this.#closes]) listener();
193
+ });
194
+ }
195
+ };
196
+ /**
197
+ * One request's socket to its Database: the hello sent at once, calls and watches sent behind it without waiting, each
198
+ * answered by its id. It is `opening` until the hello is answered, `open` once it is, and `closed` once anything ends
199
+ * it (a refusal, a frame it can't read, the stream ending): every call and watch still unanswered then rejects with
200
+ * `SocketClosed`, and nothing more is sent. Nothing about it is ever waited on to make a call.
201
+ */
202
+ var DoorSocket = class {
203
+ authorization;
204
+ state = "opening";
205
+ /** How long until the hello was answered, in ms, once it is. */
206
+ openMs;
207
+ /** Why it closed, once it has. */
208
+ why;
209
+ #started = performance.now();
210
+ #raw;
211
+ #writer;
212
+ #queued = [];
213
+ #next = 1;
214
+ #inFlight = IN_FLIGHT;
215
+ #maxCall = MAX_CALL;
216
+ #calls = /* @__PURE__ */ new Map();
217
+ #watches = /* @__PURE__ */ new Map();
218
+ /** Opens the protocol on `made` for `database` (`db-<id>`) as `authorization` (`Bearer <token>`); a hello too long for it throws. */
219
+ constructor(made, database, authorization) {
220
+ this.authorization = authorization;
221
+ this.#queued.push(hello(database, authorization));
222
+ Promise.resolve(made).then((raw) => this.#run(raw), (error) => this.end(`it could not be opened (${error instanceof Error ? error.message : String(error)})`));
223
+ }
224
+ /** Whether a call of `bytes` as `authorization` goes on it now: open, its hello's token, within its bounds. */
225
+ ready(authorization, bytes) {
226
+ return this.state === "open" && authorization === this.authorization && bytes <= this.#maxCall && this.#calls.size < this.#inFlight;
227
+ }
228
+ /** One call (a `POST <door>/call` body): its answer, or `SocketClosed` once the socket ends first. */
229
+ call(body) {
230
+ if (this.state === "closed") return Promise.reject(new SocketClosed());
231
+ const id = this.#id();
232
+ return new Promise((done, failed) => {
233
+ this.#calls.set(id, {
234
+ done,
235
+ failed
236
+ });
237
+ this.send(frame(id, 1, body));
238
+ });
239
+ }
240
+ /** A watch opened with `first` its first message (may be none): resolves once the Database opens it. */
241
+ watch(first = "") {
242
+ if (this.state === "closed") return Promise.reject(new SocketClosed());
243
+ const id = this.#id(), watch = new SocketWatch(id, this);
244
+ return new Promise((done, failed) => {
245
+ this.#watches.set(id, {
246
+ watch,
247
+ opening: {
248
+ done,
249
+ failed
250
+ }
251
+ });
252
+ this.send(frame(id, 2, encoder$1.encode(first)));
253
+ });
254
+ }
255
+ /** @internal Sends a frame, behind the hello; a write that fails ends the socket. */
256
+ send(bytes) {
257
+ if (this.state === "closed") return;
258
+ if (!this.#writer) {
259
+ this.#queued.push(bytes);
260
+ return;
261
+ }
262
+ this.#writer.write(bytes).catch(() => this.end("a write failed"));
263
+ }
264
+ /** @internal A watch ended here: its id may be used again. */
265
+ forget(id) {
266
+ this.#watches.delete(id);
267
+ }
268
+ /** Ends it: what is unanswered rejects with `SocketClosed`, and the connection is closed. */
269
+ end(why = "it was closed") {
270
+ if (this.state === "closed") return;
271
+ this.state = "closed";
272
+ this.why = why;
273
+ for (const call of this.#calls.values()) call.failed(new SocketClosed());
274
+ this.#calls.clear();
275
+ for (const { watch, opening } of [...this.#watches.values()]) {
276
+ if (opening) opening.failed(new SocketClosed());
277
+ watch.ended();
278
+ }
279
+ this.#watches.clear();
280
+ try {
281
+ Promise.resolve(this.#raw?.close()).catch(() => {});
282
+ } catch {}
283
+ }
284
+ async #run(raw) {
285
+ this.#raw = raw;
286
+ if (this.state === "closed") {
287
+ try {
288
+ Promise.resolve(raw.close()).catch(() => {});
289
+ } catch {}
290
+ return;
291
+ }
292
+ raw.opened?.catch(() => {});
293
+ raw.closed?.then(() => this.end("the database closed it"), () => this.end("the connection failed"));
294
+ let reader;
295
+ try {
296
+ this.#writer = raw.writable.getWriter();
297
+ reader = raw.readable.getReader();
298
+ } catch {
299
+ this.end("its streams could not be read");
300
+ return;
301
+ }
302
+ for (const bytes of this.#queued.splice(0)) this.send(bytes);
303
+ const frames = new FrameReader();
304
+ try {
305
+ for (;;) {
306
+ const { value, done } = await reader.read();
307
+ if (done) break;
308
+ for (const each of frames.push(value)) this.#took(each);
309
+ if (this.state === "closed") return;
310
+ }
311
+ this.end("the database closed it");
312
+ } catch (error) {
313
+ this.end(error instanceof RangeError ? `the database sent ${error.message}` : "the connection failed");
314
+ }
315
+ }
316
+ #took({ id, kind, body }) {
317
+ const view = new DataView(body.buffer, body.byteOffset, body.byteLength);
318
+ if (id === 0 && kind === 0 && body.length >= 8) {
319
+ this.#inFlight = Math.min(IN_FLIGHT, view.getUint32(0, true));
320
+ this.#maxCall = Math.min(MAX_CALL, view.getUint32(4, true));
321
+ this.openMs = performance.now() - this.#started;
322
+ if (this.state === "opening") this.state = "open";
323
+ return;
324
+ }
325
+ if (id === 0 && kind === 5) {
326
+ this.end(body.length >= 2 ? `the database refused it (${view.getUint16(0, true)}: ${decoder.decode(body.subarray(2))})` : "the database refused it");
327
+ return;
328
+ }
329
+ if (kind === 1 && body.length >= 3) {
330
+ const call = this.#calls.get(id);
331
+ if (!call) return;
332
+ this.#calls.delete(id);
333
+ call.done({
334
+ status: view.getUint16(0, true),
335
+ text: decoder.decode(body.subarray(3))
336
+ });
337
+ return;
338
+ }
339
+ const held = this.#watches.get(id);
340
+ if (!held) return;
341
+ if (kind === 2 && body.length >= 2 && held.opening) {
342
+ const status = view.getUint16(0, true), opening = held.opening;
343
+ delete held.opening;
344
+ if (status === 101) {
345
+ held.watch.readyState = 1;
346
+ opening.done(held.watch);
347
+ return;
348
+ }
349
+ this.#watches.delete(id);
350
+ let why = decoder.decode(body.subarray(2));
351
+ try {
352
+ const refused = JSON.parse(why);
353
+ if (typeof refused.why === "string") why = refused.why;
354
+ } catch {}
355
+ opening.failed(new WatchRefused(status, why));
356
+ return;
357
+ }
358
+ if (kind === 3) held.watch.message(decoder.decode(body));
359
+ else if (kind === 4) held.watch.ended();
360
+ }
361
+ /** The next id no unanswered call or open watch has; never 0. */
362
+ #id() {
363
+ for (;;) {
364
+ const id = this.#next;
365
+ this.#next = this.#next >= 4294967295 ? 1 : this.#next + 1;
366
+ if (!this.#calls.has(id) && !this.#watches.has(id)) return id;
367
+ }
368
+ }
369
+ };
370
+ //#endregion
6
371
  //#region src/database/dev-token.ts
7
372
  /**
8
373
  * The development server's tokens (`./dev-server.ts`): an unsigned JWT naming its caller, which only the development
@@ -12,15 +377,19 @@ import { t as callKey } from "./key-BrRdFY-n.mjs";
12
377
  * const token = devToken("ada") // as one of the app's users
13
378
  * const server = devToken("site:dev") // as the app's server, as `midsummer dev` hands its servers
14
379
  */
15
- /** A token for the development server: an unsigned JWT naming `subject`, good for a day. Never accepted by a Database. */
16
- function devToken(subject) {
17
- const encode = (value) => btoa(JSON.stringify(value)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
380
+ /**
381
+ * A token for the development server: an unsigned JWT naming `subject`, good for a day, with the user's `name` and
382
+ * `email` when `profile` gives them. Never accepted by a Database.
383
+ */
384
+ function devToken(subject, profile = {}) {
385
+ const encode = (value) => btoa(String.fromCharCode(...new TextEncoder().encode(JSON.stringify(value)))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
18
386
  return `${encode({
19
387
  alg: "none",
20
388
  typ: "JWT"
21
389
  })}.${encode({
22
390
  iss: "midsummer-dev",
23
391
  sub: subject,
392
+ ...profile,
24
393
  exp: Math.floor(Date.now() / 1e3) + 86400
25
394
  })}.`;
26
395
  }
@@ -44,7 +413,8 @@ function devToken(subject) {
44
413
  * const db = await connect({ binding: "main" })
45
414
  *
46
415
  * In a Deployment that waits on nothing: the request hands its server the Database's address and a token, and the
47
- * calls the server makes at once go to the Database together, in one request.
416
+ * calls the server makes at once go to the Database together, in one request. The request's later calls and its
417
+ * watches go on one socket it opens beside its first call, where its Database has one.
48
418
  *
49
419
  * A server on Midsummer's own contract is also handed the handle as `context.database`:
50
420
  *
@@ -76,6 +446,16 @@ function devToken(subject) {
76
446
  * db.setAuth(clerk(getToken, { template: "midsummer" }))
77
447
  * db.clearAuth() // signed out
78
448
  */
449
+ /** The most characters a `UserProfile`'s name or email carries. */
450
+ const PROFILE_MOST = 320;
451
+ /** The profile a token carries: each of its fields that is text of 1 to `PROFILE_MOST` characters, else left out. */
452
+ function profileClaims(profile) {
453
+ const fits = (value) => typeof value === "string" && value.length > 0 && value.length <= 320;
454
+ return {
455
+ ...fits(profile?.name) ? { name: profile.name } : {},
456
+ ...fits(profile?.email) ? { email: profile.email } : {}
457
+ };
458
+ }
79
459
  /** The subjects the platform's own tokens use, which never name one of an app's users. */
80
460
  const SERVER_SUBJECT = /^(?:key|site|workload):/u;
81
461
  /** Why `as` can't name one of the app's users, or undefined when it can: the platform's rule for them. */
@@ -109,7 +489,9 @@ async function exchange(api, proof) {
109
489
  /**
110
490
  * A token for one signed-in user of your app, for your server to hand to that user's browser, which connects with
111
491
  * it (`signedInDatabase()`, `@midsummer-ai/sdk/react`'s `DatabaseProvider`, or `connect({ url, token, refresh })`).
112
- * Your server gives the user's id as `as`; your functions see that id as `ctx.auth.subject`. The token
492
+ * Your server gives the user's id as `as`; your functions see that id as `ctx.auth.subject`. On Midsummer, `profile`
493
+ * puts the user's name and email in the token too, as the claims `name` and `email`; a token exchanged for a
494
+ * database key carries the id alone. The token
113
495
  * runs public functions only, never internal ones. It lasts ten minutes: the browser asks your server again before
114
496
  * then. With Auth, `auth.handler` serves it already, at `/api/auth/database-token`.
115
497
  *
@@ -138,10 +520,11 @@ async function userToken(options) {
138
520
  const found = bound(binding);
139
521
  if ("handle" in found) {
140
522
  if (!found.handle.userToken) throw new DatabaseError("unavailable", `This deployment's runtime gives no user tokens for the database bound as ${binding}. That's Midsummer's fault, not your code's: ship again, and if it goes on, tell Midsummer.`);
141
- return found.handle.userToken(binding, options.as);
523
+ const profile = profileClaims(options.profile);
524
+ return Object.keys(profile).length ? found.handle.userToken(binding, options.as, profile) : found.handle.userToken(binding, options.as);
142
525
  }
143
526
  if ("dev" in found) return {
144
- token: devToken(options.as),
527
+ token: devToken(options.as, profileClaims(options.profile)),
145
528
  url: found.dev,
146
529
  expiresAt: Date.now() + 864e5
147
530
  };
@@ -343,7 +726,7 @@ async function isolation(url, key, token) {
343
726
  return {
344
727
  ...own,
345
728
  name,
346
- store: (await import("./store-CsBhnabU.mjs")).idbStore(name)
729
+ store: (await import("./store-Ch931wwA.mjs")).idbStore(name)
347
730
  };
348
731
  }
349
732
  const inPage = () => typeof globalThis.document !== "undefined";
@@ -427,19 +810,112 @@ async function opened(url, token, refresh, server, key) {
427
810
  }
428
811
  /** How long before its token runs out a door's calls renew it first. Every token a request hands has a minute or more left. */
429
812
  const DOOR_RENEW_MS = 3e4;
813
+ /** How long one request to a door may take, its answer read included, before it counts as no answer and is sent again. */
814
+ const DOOR_CALL_MS = 1e4;
815
+ /**
816
+ * A socket call's answer, or `SocketClosed` once it has held the call past `DOOR_CALL_MS`, with the socket closed so
817
+ * the request goes on by fetch: no call waits on a socket that stalled.
818
+ */
819
+ function answeredWithin(socket, call) {
820
+ let timer;
821
+ const stalled = new Promise((_, reject) => {
822
+ timer = setTimeout(() => {
823
+ try {
824
+ socket.end(`a call waited past ${DOOR_CALL_MS} ms`);
825
+ } catch {}
826
+ reject(new SocketClosed());
827
+ }, DOOR_CALL_MS);
828
+ });
829
+ return Promise.race([call, stalled]).finally(() => clearTimeout(timer));
830
+ }
430
831
  /** The most calls one request to a door carries; more made at once go in as many requests as they need. */
431
832
  const DOOR_BATCH = 256;
432
- /** The remakes this process asked for, by door: the calls at once that found their Database gone wait on one ask. */
433
- const remaking = /* @__PURE__ */ new Map();
434
833
  /**
435
- * A Deployment's server's calls to its Database, sent straight to the Database's door (`<door>/call`) with the token
436
- * its request handed in: stateless HTTPS, no hop through Midsummer and no socket. The calls made in one turn go
437
- * together in one request (`DOOR_BATCH` at most), each result matched by its `i`, and a mutation is tagged as on a socket,
438
- * so one sent again applies once. A call that gets no answer, or a 5xx, is sent again twice at most; a 401 renews the
439
- * token once. A token with under `DOOR_RENEW_MS` left is renewed before it is sent: from the door the request being
440
- * served was handed, else the handle's `token`. The door answering that it has no Database by its id (404
441
- * `not_found`, as after a move with its rows gone) asks the handle to make it again (`remake`), once, and sends the
442
- * calls once more. A watch opens a socket to the door at its first use, and only then.
834
+ * The remakes asked for, by the request's handle and door: that request's calls at once that found their Database gone
835
+ * wait on one ask. Another request asks for itself (the dispatcher makes it once for them all), so no request waits on
836
+ * an ask that ends with another request.
837
+ */
838
+ const remaking = /* @__PURE__ */ new WeakMap();
839
+ const lanes = /* @__PURE__ */ new WeakMap();
840
+ function laneOf(handle, door) {
841
+ let byDoor = lanes.get(handle);
842
+ if (!byDoor) {
843
+ byDoor = /* @__PURE__ */ new Map();
844
+ lanes.set(handle, byDoor);
845
+ }
846
+ let lane = byDoor.get(door);
847
+ if (!lane) {
848
+ lane = {
849
+ tried: false,
850
+ timed: false
851
+ };
852
+ byDoor.set(door, lane);
853
+ }
854
+ return lane;
855
+ }
856
+ /**
857
+ * Starts the connection to `door`'s address as soon as a request connects to it, without waiting on it: a request to
858
+ * the address's own health, which no Database answers, so the request's first call finds the connection made (a new
859
+ * one costs that call 50-160 ms; a kept one about 10). Once a request.
860
+ */
861
+ function warmUp(lane, door) {
862
+ if (lane.warm || lane.tried) return;
863
+ const warm = { at: performance.now() };
864
+ lane.warm = warm;
865
+ const ended = (status) => {
866
+ warm.ended = performance.now();
867
+ warm.status = status;
868
+ };
869
+ try {
870
+ fetchAt(new URL("/health", door).href).then((response) => {
871
+ ended(response.status);
872
+ response.body?.cancel().catch(() => {});
873
+ }, () => ended(0));
874
+ } catch {
875
+ ended(0);
876
+ }
877
+ }
878
+ const encoder = new TextEncoder();
879
+ /** A `Server-Timing` entry's number of milliseconds. */
880
+ const ms = (value) => value.toFixed(1);
881
+ /**
882
+ * The `db-first` entry of a request's first call to its door, which says where its time went: `token` (having the
883
+ * token: none when the request handed one), `call` (the call itself, `by fetch` or `by socket`), `warm` (the door's
884
+ * connection started at connect, ended before the call or still going beside it; `none` where none was started) and
885
+ * `socket` (open, and how long its hello took, or still opening, or none). A slow call beside a quick warm-up was the
886
+ * Database (waking, or the engine); a slow warm-up the connection.
887
+ */
888
+ function firstEntry(lane, tokenMs, callMs, started, status, bySocket) {
889
+ const warm = lane.warm;
890
+ const warmed = !warm ? "none" : warm.ended === void 0 ? `${ms(started - warm.at)} so far, beside the call` : `${ms(warm.ended - warm.at)} ${warm.ended <= started ? "before" : "beside"} the call (${warm.status})`;
891
+ const socket = lane.socket;
892
+ const opened = !socket ? "none" : socket.state === "open" ? `open in ${ms(socket.openMs ?? 0)}` : socket.state === "opening" ? "opening" : `closed (${socket.why})`;
893
+ return `db-first;dur=${ms(tokenMs + callMs)};desc="token ${ms(tokenMs)}, call ${ms(callMs)} by ${bySocket ? "socket" : "fetch"} (${status}), warm ${warmed}, socket ${opened}"`;
894
+ }
895
+ /** A WebSocket to `url` once it opens, as a `Connection`'s `dial` gives one. */
896
+ function openedAt(url) {
897
+ return new Promise((done, failed) => {
898
+ const ws = socketAt(url);
899
+ ws.addEventListener("open", () => done(ws), { once: true });
900
+ ws.addEventListener("error", () => failed(/* @__PURE__ */ new Error("socket error")), { once: true });
901
+ ws.addEventListener("close", () => failed(/* @__PURE__ */ new Error("socket closed")), { once: true });
902
+ });
903
+ }
904
+ /**
905
+ * A Deployment's server's calls to its Database, sent straight to the Database's door with the token its request
906
+ * handed in, with no hop through Midsummer. The calls made in one turn go together in one call (`DOOR_BATCH` at most),
907
+ * each result matched by its `i`, and a mutation is tagged, so one sent again applies once. A call that gets no answer,
908
+ * or a 5xx, is sent again twice at most; a 401 renews the token once. A token with under `DOOR_RENEW_MS` left is
909
+ * renewed before it is sent: from the door the request being served was handed, else the handle's `token`. The door
910
+ * answering that it has no Database by its id (404 `not_found`, as after a move with its rows gone) asks the handle to
911
+ * make it again (`remake`), once, and sends the calls once more.
912
+ *
913
+ * How a call goes, in each request (`Lane`): connecting starts the door's connection (`warmUp`). The request's first
914
+ * call goes by fetch (`POST <door>/call`), and beside it the request opens a socket to the door's socket address
915
+ * (`DoorSocket`), where the door has one and the runtime can open one; later calls of the request go on the socket once
916
+ * its hello is answered, by fetch until then. A watch goes on the socket too. Nothing waits on the socket: one that
917
+ * fails or closes leaves every call it held, and every later one of that request, to fetch, with no error; a watch
918
+ * opens a WebSocket to the door instead. A renewed token goes by fetch: a socket's token is its hello's.
443
919
  */
444
920
  function doorCalls(handle, binding, first) {
445
921
  let door = first;
@@ -450,7 +926,8 @@ function doorCalls(handle, binding, first) {
450
926
  const handed = force ? void 0 : now().door?.(binding);
451
927
  const next = handed && handed.url === door.url && handed.expiresAt - Date.now() > DOOR_RENEW_MS ? handed : {
452
928
  ...await now().token(binding),
453
- url: door.url
929
+ url: door.url,
930
+ ...door.socket ? { socket: door.socket } : {}
454
931
  };
455
932
  door = next;
456
933
  return next;
@@ -464,11 +941,23 @@ function doorCalls(handle, binding, first) {
464
941
  ...answer,
465
942
  i
466
943
  });
467
- /** One request of `ops` to the door, and how to find each one's answer by its `i`. */
944
+ /** The request's socket, opened beside its first call or watch, once: where the door names an address and the runtime opens sockets. */
945
+ const begin = (lane, asker, token) => {
946
+ if (lane.tried) return;
947
+ lane.tried = true;
948
+ const database = new URL(door.url).pathname.split("/").filter(Boolean).at(-1);
949
+ if (!door.socket || !asker.socket || !database) return;
950
+ try {
951
+ lane.socket = new DoorSocket(asker.socket(door.socket), database, `Bearer ${token}`);
952
+ } catch {}
953
+ };
954
+ /** One call of `ops` to the door, and how to find each one's answer by its `i`. */
468
955
  const post = async (ops) => {
469
- const body = JSON.stringify(ops), since = Date.now();
956
+ const body = JSON.stringify(ops), bytes = encoder.encode(body), since = Date.now();
957
+ const asker = now(), lane = laneOf(asker, door.url);
470
958
  let remade = false;
471
959
  for (let tries = 0;; tries += 1) {
960
+ const asked = performance.now();
472
961
  let token;
473
962
  try {
474
963
  token = await live();
@@ -479,56 +968,83 @@ function doorCalls(handle, binding, first) {
479
968
  error: `no new token for the database bound as ${binding} (${error instanceof Error ? error.message : String(error)})`
480
969
  });
481
970
  }
971
+ const tokenMs = performance.now() - asked;
972
+ begin(lane, asker, token);
973
+ const socket = lane.socket?.ready(`Bearer ${token}`, bytes.length) ? lane.socket : void 0;
482
974
  const started = performance.now();
483
- let response;
484
- try {
485
- response = await fetchAt(`${door.url}/call`, {
486
- method: "POST",
487
- headers: {
488
- authorization: `Bearer ${token}`,
489
- "content-type": "application/json"
490
- },
491
- body
492
- });
975
+ let status, text;
976
+ if (socket) try {
977
+ ({status, text} = await answeredWithin(socket, socket.call(bytes)));
493
978
  } catch (error) {
494
- if (tries < 2) continue;
495
- return all({
496
- ok: false,
497
- why: "unavailable",
498
- error: `couldn't reach the database bound as ${binding} (${error instanceof Error ? error.message : String(error)})`
499
- });
979
+ if (error instanceof SocketClosed) {
980
+ tries -= 1;
981
+ continue;
982
+ }
983
+ throw error;
984
+ }
985
+ else {
986
+ let response;
987
+ try {
988
+ response = await fetchAt(`${door.url}/call`, {
989
+ method: "POST",
990
+ headers: {
991
+ authorization: `Bearer ${token}`,
992
+ "content-type": "application/json"
993
+ },
994
+ body,
995
+ signal: AbortSignal.timeout(DOOR_CALL_MS)
996
+ });
997
+ text = await response.text();
998
+ } catch (error) {
999
+ if (tries < 2) continue;
1000
+ return all({
1001
+ ok: false,
1002
+ why: "unavailable",
1003
+ error: `couldn't reach the database bound as ${binding} (${error instanceof Error ? error.message : String(error)})`
1004
+ });
1005
+ }
1006
+ status = response.status;
500
1007
  }
501
- const text = await response.text();
502
- now().note?.(`db-call;dur=${(performance.now() - started).toFixed(1)};desc="${response.status}, ${ops.length} call${ops.length === 1 ? "" : "s"}"`);
503
- if (response.status === 401 && tries === 0) {
1008
+ const callMs = performance.now() - started;
1009
+ asker.note?.(`db-call;dur=${ms(callMs)};desc="${status}, ${ops.length} call${ops.length === 1 ? "" : "s"}${socket ? ", socket" : ""}"`);
1010
+ if (!lane.timed) {
1011
+ lane.timed = true;
1012
+ asker.note?.(firstEntry(lane, tokenMs, callMs, started, status, !!socket));
1013
+ }
1014
+ if (status === 401 && tries === 0) {
504
1015
  try {
505
1016
  await renew(true);
506
1017
  } catch {}
507
1018
  continue;
508
1019
  }
509
- if (!response.ok) {
1020
+ if (status < 200 || status > 299) {
510
1021
  let refused = {};
511
1022
  try {
512
1023
  refused = JSON.parse(text);
513
1024
  } catch {}
514
- const asker = now();
515
- if (response.status === 404 && refused.error === "not_found" && !remade && asker.remake) {
1025
+ if (status === 404 && refused.error === "not_found" && !remade && asker.remake) {
516
1026
  remade = true;
517
1027
  const at = door.url;
518
- let asking = remaking.get(at);
1028
+ let asked = remaking.get(asker);
1029
+ if (!asked) {
1030
+ asked = /* @__PURE__ */ new Map();
1031
+ remaking.set(asker, asked);
1032
+ }
1033
+ const mine = asked;
1034
+ let asking = mine.get(at);
519
1035
  if (!asking) {
520
1036
  const made = asker.remake(binding, since).catch(() => false).finally(() => {
521
- if (remaking.get(at) === made) remaking.delete(at);
1037
+ if (mine.get(at) === made) mine.delete(at);
522
1038
  });
523
1039
  asking = made;
524
- remaking.set(at, made);
1040
+ mine.set(at, made);
525
1041
  }
526
1042
  if (await asking) continue;
527
1043
  }
528
- if (response.status >= 500 && tries < 2) continue;
1044
+ if (status >= 500 && tries < 2) continue;
529
1045
  return all({
530
1046
  ok: false,
531
- why: response.status === 401 ? "denied" : typeof refused.error === "string" ? refused.error : "refused",
1047
+ why: status === 401 ? "denied" : typeof refused.error === "string" ? refused.error : "refused",
532
1048
  error: typeof refused.why === "string" ? refused.why : text.slice(0, 200)
533
1049
  });
534
1050
  }
@@ -547,7 +1063,7 @@ function doorCalls(handle, binding, first) {
547
1063
  };
548
1064
  }
549
1065
  };
550
- /** Sends what this turn queued, `DOOR_BATCH` calls a request. */
1066
+ /** Sends what this turn queued, `DOOR_BATCH` calls at a time. */
551
1067
  const flush = () => {
552
1068
  const batch = queued;
553
1069
  queued = [];
@@ -558,6 +1074,13 @@ function doorCalls(handle, binding, first) {
558
1074
  ...each.op
559
1075
  }))).then((answerOf) => {
560
1076
  part.forEach((each, n) => each.done(answerOf(n + 1)));
1077
+ }, (error) => {
1078
+ part.forEach((each, n) => each.done({
1079
+ i: n + 1,
1080
+ ok: false,
1081
+ why: "unavailable",
1082
+ error: `the call to the database bound as ${binding} failed (${error instanceof Error ? error.message : String(error)})`
1083
+ }));
561
1084
  });
562
1085
  }
563
1086
  };
@@ -568,7 +1091,22 @@ function doorCalls(handle, binding, first) {
568
1091
  done
569
1092
  });
570
1093
  });
571
- let socket;
1094
+ /**
1095
+ * A watch's socket for the request it opens in: a watch on the request's socket while that is open with the
1096
+ * connection's token, else a WebSocket to the door. A watch the Database refuses fails as a WebSocket's open would.
1097
+ */
1098
+ const dial = (lane) => async (connection) => {
1099
+ const socket = lane.socket;
1100
+ if (socket && socket.state !== "closed" && socket.authorization === `Bearer ${connection.token}`) try {
1101
+ return await socket.watch();
1102
+ } catch (error) {
1103
+ if (!(error instanceof SocketClosed)) throw error;
1104
+ }
1105
+ return openedAt(connection.url);
1106
+ };
1107
+ /** Each request's watches, on one connection that request opened. */
1108
+ const watchers = /* @__PURE__ */ new WeakMap();
1109
+ warmUp(laneOf(now(), door.url), door.url);
572
1110
  return {
573
1111
  async query(fn, args) {
574
1112
  const answer = await call({
@@ -592,18 +1130,25 @@ function doorCalls(handle, binding, first) {
592
1130
  },
593
1131
  watchQuery(fn, args, options, onValue) {
594
1132
  let stopped = false, stop = () => {};
595
- if (!socket) {
596
- const opening = live().then((token) => Connection.connect(door.url, {
597
- token,
598
- refresh: async () => (await renew(true)).token,
599
- shape: "server"
600
- }));
1133
+ const asker = now(), lane = laneOf(asker, door.url);
1134
+ let watcher = watchers.get(lane);
1135
+ if (!watcher) {
1136
+ const opening = live().then((token) => {
1137
+ begin(lane, asker, token);
1138
+ return Connection.open(door.url, {
1139
+ token,
1140
+ refresh: async () => (await renew(true)).token,
1141
+ shape: "server",
1142
+ dial: dial(lane)
1143
+ });
1144
+ });
601
1145
  opening.catch(() => {
602
- if (socket === opening) socket = void 0;
1146
+ if (watchers.get(lane) === opening) watchers.delete(lane);
603
1147
  });
604
- socket = opening;
1148
+ watchers.set(lane, opening);
1149
+ watcher = opening;
605
1150
  }
606
- socket.then((open) => {
1151
+ watcher.then((open) => {
607
1152
  if (!stopped) stop = open.watchQuery(fn, args, options, onValue);
608
1153
  }, (error) => {
609
1154
  if (!stopped) onValue(void 0, { error: caught(error) });
@@ -614,7 +1159,7 @@ function doorCalls(handle, binding, first) {
614
1159
  };
615
1160
  },
616
1161
  close() {
617
- socket?.then((open) => open.close(), () => {});
1162
+ watchers.get(laneOf(now(), door.url))?.then((open) => open.close(), () => {});
618
1163
  }
619
1164
  };
620
1165
  }
@@ -1080,4 +1625,4 @@ function oidc(getToken) {
1080
1625
  return async ({ forceRefreshToken }) => await getToken(forceRefreshToken) || null;
1081
1626
  }
1082
1627
  //#endregion
1083
- export { connect as a, signedInDatabase as c, clerk as i, userToken as l, DatabaseClient as n, databaseUrl as o, auth0 as r, oidc as s, DATABASE_TOKEN_PATH as t };
1628
+ export { clerk as a, oidc as c, userToken as d, auth0 as i, profileClaims as l, DatabaseClient as n, connect as o, PROFILE_MOST as r, databaseUrl as s, DATABASE_TOKEN_PATH as t, signedInDatabase as u };