@midsummer-ai/sdk 0.1.0-staging.3775 → 0.1.0-staging.3781
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/auth/contract.d.mts +2 -2
- package/auth/contract.mjs +1 -1
- package/auth/index.d.mts +2 -2
- package/auth/index.mjs +1 -1
- package/auth/react.mjs +1 -1
- package/auth/stand-in.d.mts +1 -1
- package/{auth-Bu4FIk-C.mjs → auth-DUEJfZvB.mjs} +1 -1
- package/{client-COPmSTKM.d.mts → client-BDjPQa7G.d.mts} +21 -2
- package/{client-G20sA352.mjs → client-CrJkXd5h.mjs} +627 -48
- package/{connection-C_JSWUrt.mjs → connection-CpT0x1EE.mjs} +3 -3
- package/database/client.d.mts +2 -2
- package/database/client.mjs +1 -1
- package/database/react.d.mts +1 -1
- package/{index-q1gV7MyO.d.mts → index-C0ykY_s9.d.mts} +1 -1
- package/package.json +1 -1
- package/{store-BpA6Q5Z_.d.mts → store-CRqU5WCe.d.mts} +1 -1
- package/{store-CsBhnabU.mjs → store-Ch931wwA.mjs} +1 -1
- package/{tabs-gHJHkhm2.mjs → tabs-C4NDJzfK.mjs} +1 -1
package/auth/contract.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { n as AuthStore } from "../store-
|
|
1
|
+
import { n as AuthStore } from "../store-CRqU5WCe.mjs";
|
|
2
2
|
import { SignInMail } from "./mail.mjs";
|
|
3
|
-
import { a as Auth } from "../index-
|
|
3
|
+
import { a as Auth } from "../index-C0ykY_s9.mjs";
|
|
4
4
|
//#region src/auth/contract.d.ts
|
|
5
5
|
interface AuthHarness {
|
|
6
6
|
/** Sign-in over a store with no users, made with `scopes: CONTRACT_SCOPES`. */
|
package/auth/contract.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { c as LIMITS, l as LIMIT_WINDOW_MS, r as AuthError, u as SETTINGS_TTL_MS } from "../auth-
|
|
1
|
+
import { c as LIMITS, l as LIMIT_WINDOW_MS, r as AuthError, u as SETTINGS_TTL_MS } from "../auth-DUEJfZvB.mjs";
|
|
2
2
|
import { IMPERSONATION_TOKEN_MS, startImpersonation } from "./impersonate.mjs";
|
|
3
3
|
//#region src/auth/contract.ts
|
|
4
4
|
/**
|
package/auth/index.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { n as AuthStore, r as databaseStore, t as AuthCall } from "../store-
|
|
1
|
+
import { n as AuthStore, r as databaseStore, t as AuthCall } from "../store-CRqU5WCe.mjs";
|
|
2
2
|
import { i as SignUpPolicy, n as CaptchaProvider, r as PublicSettings, t as AuthSettings } from "../settings-Dz3irtlu.mjs";
|
|
3
3
|
import { SignInMail, SignInMailKind, checkSignInMail, signInWords } from "./mail.mjs";
|
|
4
|
-
import { _ as AuthEvent, a as Auth, b as EventSend, c as AuthOptions, d as IMPERSONATION_S, f as SESSION_CACHE_S, g as createAuth, h as auth, i as AgentKey, l as AuthUser, m as SignedInAgent, n as AUTH_ROUTES, o as AuthError, p as SignedIn, r as AgentGrant, s as AuthErrorCode, t as AUTH_PATH, u as AuthUserRecord, v as AuthEventBatch, y as AuthEventType } from "../index-
|
|
4
|
+
import { _ as AuthEvent, a as Auth, b as EventSend, c as AuthOptions, d as IMPERSONATION_S, f as SESSION_CACHE_S, g as createAuth, h as auth, i as AgentKey, l as AuthUser, m as SignedInAgent, n as AUTH_ROUTES, o as AuthError, p as SignedIn, r as AgentGrant, s as AuthErrorCode, t as AUTH_PATH, u as AuthUserRecord, v as AuthEventBatch, y as AuthEventType } from "../index-C0ykY_s9.mjs";
|
|
5
5
|
import { i as authFiles } from "../files-B553U-d6.mjs";
|
|
6
6
|
export { AUTH_PATH, AUTH_ROUTES, AgentGrant, AgentKey, Auth, type AuthCall, AuthError, AuthErrorCode, type AuthEvent, type AuthEventBatch, type AuthEventType, AuthOptions, type AuthSettings, type AuthStore, AuthUser, AuthUserRecord, type CaptchaProvider, type EventSend, IMPERSONATION_S, type PublicSettings, SESSION_CACHE_S, type SignInMail, type SignInMailKind, type SignUpPolicy, SignedIn, SignedInAgent, auth, authFiles, checkSignInMail, createAuth, databaseStore, signInWords };
|
package/auth/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as SESSION_CACHE_S, d as databaseStore, i as IMPERSONATION_S, n as AUTH_ROUTES, o as auth, r as AuthError, s as createAuth, t as AUTH_PATH } from "../auth-
|
|
1
|
+
import { a as SESSION_CACHE_S, d as databaseStore, i as IMPERSONATION_S, n as AUTH_ROUTES, o as auth, r as AuthError, s as createAuth, t as AUTH_PATH } from "../auth-DUEJfZvB.mjs";
|
|
2
2
|
import { checkSignInMail, signInWords } from "./mail.mjs";
|
|
3
3
|
import { n as authFiles } from "../files-DhPeWwcT.mjs";
|
|
4
4
|
export { AUTH_PATH, AUTH_ROUTES, AuthError, IMPERSONATION_S, SESSION_CACHE_S, auth, authFiles, checkSignInMail, createAuth, databaseStore, signInWords };
|
package/auth/react.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as DATABASE_TOKEN_PATH, u as signedInDatabase } from "../client-
|
|
1
|
+
import { t as DATABASE_TOKEN_PATH, u as signedInDatabase } from "../client-CrJkXd5h.mjs";
|
|
2
2
|
import { DatabaseProvider } from "../database/react.mjs";
|
|
3
3
|
import { a as WORDS, c as deviceOf, i as CAPTCHA_WIDGETS, l as setupKeyOf, o as ago, r as AUTH_CSS, t as qrPath } from "../qr-Br1sOBmT.mjs";
|
|
4
4
|
import { AuthClientError, authClient } from "./client.mjs";
|
package/auth/stand-in.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { i as processEnv, r as platformApi, t as here } from "./here-BKjizr_N.mjs";
|
|
2
|
-
import { d as userToken, o as connect, s as databaseUrl } from "./client-
|
|
2
|
+
import { d as userToken, o as connect, s as databaseUrl } from "./client-CrJkXd5h.mjs";
|
|
3
3
|
import { sendSignInMail } from "./auth/mail.mjs";
|
|
4
4
|
import "./files-DhPeWwcT.mjs";
|
|
5
5
|
import { standIn } from "./auth/stand-in.mjs";
|
|
@@ -1,4 +1,14 @@
|
|
|
1
1
|
import { t as DatabaseError } from "./errors-CnQduDOt.mjs";
|
|
2
|
+
//#region src/database/door-socket.d.ts
|
|
3
|
+
/** A TCP + TLS socket as the runtime opens one: its two streams, when it opened and closed, and `close`. */
|
|
4
|
+
interface StreamSocket {
|
|
5
|
+
readonly readable: ReadableStream<Uint8Array>;
|
|
6
|
+
readonly writable: WritableStream<Uint8Array>;
|
|
7
|
+
readonly opened?: Promise<unknown>;
|
|
8
|
+
readonly closed?: Promise<unknown>;
|
|
9
|
+
close(): unknown;
|
|
10
|
+
}
|
|
11
|
+
//#endregion
|
|
2
12
|
//#region src/database/client.d.ts
|
|
3
13
|
/** A function's reference, as `api.<file>.<export>` holds it, typed by its arguments and its answer. */
|
|
4
14
|
interface Reference<Kind extends "query" | "mutation" | "action", Args = any, Returns = any> {
|
|
@@ -60,6 +70,10 @@ interface DatabaseToken {
|
|
|
60
70
|
readonly url: string;
|
|
61
71
|
readonly expiresAt: number;
|
|
62
72
|
}
|
|
73
|
+
/** A door a request hands its server: the Database's address and token, and where its socket is (`host:port`), where it has one. */
|
|
74
|
+
interface DoorToken extends DatabaseToken {
|
|
75
|
+
readonly socket?: string;
|
|
76
|
+
}
|
|
63
77
|
/**
|
|
64
78
|
* What Midsummer hands a Deployment as `context.database`: a token and address for a Database its Environment binds,
|
|
65
79
|
* as the app's server, and (`userToken`) as one of the app's users, for that user's browser.
|
|
@@ -71,7 +85,12 @@ interface BoundDatabases {
|
|
|
71
85
|
* Where the app's server calls the Database bound as `binding`, with its token and when that runs out, handed in
|
|
72
86
|
* with the request, so connecting asks for nothing. Undefined where the request was handed none: `token` serves.
|
|
73
87
|
*/
|
|
74
|
-
door?(binding: string):
|
|
88
|
+
door?(binding: string): DoorToken | undefined;
|
|
89
|
+
/**
|
|
90
|
+
* Opens a TCP + TLS socket to `address` (`host:port`, a door's `socket`) for the request being served, which lives
|
|
91
|
+
* only as long as that request. Undefined where the runtime has none: every call goes over HTTP.
|
|
92
|
+
*/
|
|
93
|
+
socket?(address: string): StreamSocket | Promise<StreamSocket>;
|
|
75
94
|
/**
|
|
76
95
|
* Has the Database bound as `binding` made again after its door returned that it has none for a call sent at `since`
|
|
77
96
|
* (as after a move, its rows gone): true when that call should be sent once more.
|
|
@@ -220,4 +239,4 @@ declare function clerk(getToken: (options: {
|
|
|
220
239
|
*/
|
|
221
240
|
declare function oidc(getToken: (forceRefresh: boolean) => Promise<string | null | undefined> | string | null | undefined): FetchToken;
|
|
222
241
|
//#endregion
|
|
223
|
-
export { userToken as S,
|
|
242
|
+
export { userToken as C, signedInDatabase as S, clerk as _, DATABASE_TOKEN_PATH as a, oidc as b, DatabaseToken as c, PROFILE_MOST as d, Reference as f, auth0 as g, UserProfile as h, ConnectOptions as i, DoorToken as l, SignedInDatabase as m, AuthState as n, Database as o, ReturnsOf as p, BoundDatabases as r, DatabaseClient as s, ArgsOf as t, FetchToken as u, connect as v, profileClaims as x, databaseUrl as y };
|
|
@@ -1,8 +1,377 @@
|
|
|
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-
|
|
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
|
+
/** Whether a call of `bytes` as `authorization` may be sent on it now, behind a hello not answered yet: not ended, its hello's token, within its bounds. */
|
|
229
|
+
takes(authorization, bytes) {
|
|
230
|
+
return this.state !== "closed" && authorization === this.authorization && bytes <= this.#maxCall && this.#calls.size < this.#inFlight;
|
|
231
|
+
}
|
|
232
|
+
/** One call (a `POST <door>/call` body): its answer, or `SocketClosed` once the socket ends first. */
|
|
233
|
+
call(body) {
|
|
234
|
+
if (this.state === "closed") return Promise.reject(new SocketClosed());
|
|
235
|
+
const id = this.#id();
|
|
236
|
+
return new Promise((done, failed) => {
|
|
237
|
+
this.#calls.set(id, {
|
|
238
|
+
done,
|
|
239
|
+
failed
|
|
240
|
+
});
|
|
241
|
+
this.send(frame(id, 1, body));
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
/** A watch opened with `first` its first message (may be none): resolves once the Database opens it. */
|
|
245
|
+
watch(first = "") {
|
|
246
|
+
if (this.state === "closed") return Promise.reject(new SocketClosed());
|
|
247
|
+
const id = this.#id(), watch = new SocketWatch(id, this);
|
|
248
|
+
return new Promise((done, failed) => {
|
|
249
|
+
this.#watches.set(id, {
|
|
250
|
+
watch,
|
|
251
|
+
opening: {
|
|
252
|
+
done,
|
|
253
|
+
failed
|
|
254
|
+
}
|
|
255
|
+
});
|
|
256
|
+
this.send(frame(id, 2, encoder$1.encode(first)));
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
/** @internal Sends a frame, behind the hello; a write that fails ends the socket. */
|
|
260
|
+
send(bytes) {
|
|
261
|
+
if (this.state === "closed") return;
|
|
262
|
+
if (!this.#writer) {
|
|
263
|
+
this.#queued.push(bytes);
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
this.#writer.write(bytes).catch(() => this.end("a write failed"));
|
|
267
|
+
}
|
|
268
|
+
/** @internal A watch ended here: its id may be used again. */
|
|
269
|
+
forget(id) {
|
|
270
|
+
this.#watches.delete(id);
|
|
271
|
+
}
|
|
272
|
+
/** Ends it: what is unanswered rejects with `SocketClosed`, and the connection is closed. */
|
|
273
|
+
end(why = "it was closed") {
|
|
274
|
+
if (this.state === "closed") return;
|
|
275
|
+
this.state = "closed";
|
|
276
|
+
this.why = why;
|
|
277
|
+
for (const call of this.#calls.values()) call.failed(new SocketClosed());
|
|
278
|
+
this.#calls.clear();
|
|
279
|
+
for (const { watch, opening } of [...this.#watches.values()]) {
|
|
280
|
+
if (opening) opening.failed(new SocketClosed());
|
|
281
|
+
watch.ended();
|
|
282
|
+
}
|
|
283
|
+
this.#watches.clear();
|
|
284
|
+
try {
|
|
285
|
+
Promise.resolve(this.#raw?.close()).catch(() => {});
|
|
286
|
+
} catch {}
|
|
287
|
+
}
|
|
288
|
+
async #run(raw) {
|
|
289
|
+
this.#raw = raw;
|
|
290
|
+
if (this.state === "closed") {
|
|
291
|
+
try {
|
|
292
|
+
Promise.resolve(raw.close()).catch(() => {});
|
|
293
|
+
} catch {}
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
raw.opened?.catch(() => {});
|
|
297
|
+
raw.closed?.then(() => this.end("the database closed it"), () => this.end("the connection failed"));
|
|
298
|
+
let reader;
|
|
299
|
+
try {
|
|
300
|
+
this.#writer = raw.writable.getWriter();
|
|
301
|
+
reader = raw.readable.getReader();
|
|
302
|
+
} catch {
|
|
303
|
+
this.end("its streams could not be read");
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
for (const bytes of this.#queued.splice(0)) this.send(bytes);
|
|
307
|
+
const frames = new FrameReader();
|
|
308
|
+
try {
|
|
309
|
+
for (;;) {
|
|
310
|
+
const { value, done } = await reader.read();
|
|
311
|
+
if (done) break;
|
|
312
|
+
for (const each of frames.push(value)) this.#took(each);
|
|
313
|
+
if (this.state === "closed") return;
|
|
314
|
+
}
|
|
315
|
+
this.end("the database closed it");
|
|
316
|
+
} catch (error) {
|
|
317
|
+
this.end(error instanceof RangeError ? `the database sent ${error.message}` : "the connection failed");
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
#took({ id, kind, body }) {
|
|
321
|
+
const view = new DataView(body.buffer, body.byteOffset, body.byteLength);
|
|
322
|
+
if (id === 0 && kind === 0 && body.length >= 8) {
|
|
323
|
+
this.#inFlight = Math.min(IN_FLIGHT, view.getUint32(0, true));
|
|
324
|
+
this.#maxCall = Math.min(MAX_CALL, view.getUint32(4, true));
|
|
325
|
+
this.openMs = performance.now() - this.#started;
|
|
326
|
+
if (this.state === "opening") this.state = "open";
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
329
|
+
if (id === 0 && kind === 5) {
|
|
330
|
+
this.end(body.length >= 2 ? `the database refused it (${view.getUint16(0, true)}: ${decoder.decode(body.subarray(2))})` : "the database refused it");
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
if (kind === 1 && body.length >= 3) {
|
|
334
|
+
const call = this.#calls.get(id);
|
|
335
|
+
if (!call) return;
|
|
336
|
+
this.#calls.delete(id);
|
|
337
|
+
call.done({
|
|
338
|
+
status: view.getUint16(0, true),
|
|
339
|
+
text: decoder.decode(body.subarray(3))
|
|
340
|
+
});
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
const held = this.#watches.get(id);
|
|
344
|
+
if (!held) return;
|
|
345
|
+
if (kind === 2 && body.length >= 2 && held.opening) {
|
|
346
|
+
const status = view.getUint16(0, true), opening = held.opening;
|
|
347
|
+
delete held.opening;
|
|
348
|
+
if (status === 101) {
|
|
349
|
+
held.watch.readyState = 1;
|
|
350
|
+
opening.done(held.watch);
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
353
|
+
this.#watches.delete(id);
|
|
354
|
+
let why = decoder.decode(body.subarray(2));
|
|
355
|
+
try {
|
|
356
|
+
const refused = JSON.parse(why);
|
|
357
|
+
if (typeof refused.why === "string") why = refused.why;
|
|
358
|
+
} catch {}
|
|
359
|
+
opening.failed(new WatchRefused(status, why));
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
if (kind === 3) held.watch.message(decoder.decode(body));
|
|
363
|
+
else if (kind === 4) held.watch.ended();
|
|
364
|
+
}
|
|
365
|
+
/** The next id no unanswered call or open watch has; never 0. */
|
|
366
|
+
#id() {
|
|
367
|
+
for (;;) {
|
|
368
|
+
const id = this.#next;
|
|
369
|
+
this.#next = this.#next >= 4294967295 ? 1 : this.#next + 1;
|
|
370
|
+
if (!this.#calls.has(id) && !this.#watches.has(id)) return id;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
};
|
|
374
|
+
//#endregion
|
|
6
375
|
//#region src/database/dev-token.ts
|
|
7
376
|
/**
|
|
8
377
|
* The development server's tokens (`./dev-server.ts`): an unsigned JWT naming its caller, which only the development
|
|
@@ -48,7 +417,8 @@ function devToken(subject, profile = {}) {
|
|
|
48
417
|
* const db = await connect({ binding: "main" })
|
|
49
418
|
*
|
|
50
419
|
* In a Deployment that waits on nothing: the request hands its server the Database's address and a token, and the
|
|
51
|
-
* calls the server makes at once go to the Database together, in one request.
|
|
420
|
+
* calls the server makes at once go to the Database together, in one request. The request's later calls and its
|
|
421
|
+
* watches go on one socket it opens beside its first call, where its Database has one.
|
|
52
422
|
*
|
|
53
423
|
* A server on Midsummer's own contract is also handed the handle as `context.database`:
|
|
54
424
|
*
|
|
@@ -360,7 +730,7 @@ async function isolation(url, key, token) {
|
|
|
360
730
|
return {
|
|
361
731
|
...own,
|
|
362
732
|
name,
|
|
363
|
-
store: (await import("./store-
|
|
733
|
+
store: (await import("./store-Ch931wwA.mjs")).idbStore(name)
|
|
364
734
|
};
|
|
365
735
|
}
|
|
366
736
|
const inPage = () => typeof globalThis.document !== "undefined";
|
|
@@ -446,6 +816,22 @@ async function opened(url, token, refresh, server, key) {
|
|
|
446
816
|
const DOOR_RENEW_MS = 3e4;
|
|
447
817
|
/** How long one request to a door may take, its answer read included, before it counts as no answer and is sent again. */
|
|
448
818
|
const DOOR_CALL_MS = 1e4;
|
|
819
|
+
/**
|
|
820
|
+
* A socket call's answer, or `SocketClosed` once it has held the call past `DOOR_CALL_MS`, with the socket closed so
|
|
821
|
+
* the request goes on by fetch: no call waits on a socket that stalled.
|
|
822
|
+
*/
|
|
823
|
+
function answeredWithin(socket, call) {
|
|
824
|
+
let timer;
|
|
825
|
+
const stalled = new Promise((_, reject) => {
|
|
826
|
+
timer = setTimeout(() => {
|
|
827
|
+
try {
|
|
828
|
+
socket.end(`a call waited past ${DOOR_CALL_MS} ms`);
|
|
829
|
+
} catch {}
|
|
830
|
+
reject(new SocketClosed());
|
|
831
|
+
}, DOOR_CALL_MS);
|
|
832
|
+
});
|
|
833
|
+
return Promise.race([call, stalled]).finally(() => clearTimeout(timer));
|
|
834
|
+
}
|
|
449
835
|
/** The most calls one request to a door carries; more made at once go in as many requests as they need. */
|
|
450
836
|
const DOOR_BATCH = 256;
|
|
451
837
|
/**
|
|
@@ -454,15 +840,91 @@ const DOOR_BATCH = 256;
|
|
|
454
840
|
* an ask that ends with another request.
|
|
455
841
|
*/
|
|
456
842
|
const remaking = /* @__PURE__ */ new WeakMap();
|
|
843
|
+
const lanes = /* @__PURE__ */ new WeakMap();
|
|
844
|
+
function laneOf(handle, door) {
|
|
845
|
+
let byDoor = lanes.get(handle);
|
|
846
|
+
if (!byDoor) {
|
|
847
|
+
byDoor = /* @__PURE__ */ new Map();
|
|
848
|
+
lanes.set(handle, byDoor);
|
|
849
|
+
}
|
|
850
|
+
let lane = byDoor.get(door);
|
|
851
|
+
if (!lane) {
|
|
852
|
+
lane = {
|
|
853
|
+
tried: false,
|
|
854
|
+
timed: false
|
|
855
|
+
};
|
|
856
|
+
byDoor.set(door, lane);
|
|
857
|
+
}
|
|
858
|
+
return lane;
|
|
859
|
+
}
|
|
860
|
+
/**
|
|
861
|
+
* Starts the connection to `door`'s address as soon as a request connects to it, without waiting on it: a request to
|
|
862
|
+
* the address's own health, which no Database answers, so the request's first call finds the connection made (a new
|
|
863
|
+
* one costs that call 50-160 ms; a kept one about 10). Once a request.
|
|
864
|
+
*/
|
|
865
|
+
function warmUp(lane, door) {
|
|
866
|
+
if (lane.warm || lane.tried) return;
|
|
867
|
+
const warm = { at: performance.now() };
|
|
868
|
+
lane.warm = warm;
|
|
869
|
+
const ended = (status) => {
|
|
870
|
+
warm.ended = performance.now();
|
|
871
|
+
warm.status = status;
|
|
872
|
+
};
|
|
873
|
+
try {
|
|
874
|
+
fetchAt(new URL("/health", door).href).then((response) => {
|
|
875
|
+
ended(response.status);
|
|
876
|
+
response.body?.cancel().catch(() => {});
|
|
877
|
+
}, () => ended(0));
|
|
878
|
+
} catch {
|
|
879
|
+
ended(0);
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
const encoder = new TextEncoder();
|
|
883
|
+
/** A `Server-Timing` entry's number of milliseconds. */
|
|
884
|
+
const ms = (value) => value.toFixed(1);
|
|
885
|
+
const legOf = (leg) => !leg ? "none" : leg.ms === void 0 ? leg.ended ?? "unanswered" : `${ms(leg.ms)} (${leg.status})${leg.ended ? ` ${leg.ended}` : ""}`;
|
|
457
886
|
/**
|
|
458
|
-
*
|
|
459
|
-
*
|
|
460
|
-
*
|
|
461
|
-
*
|
|
462
|
-
*
|
|
463
|
-
*
|
|
464
|
-
|
|
465
|
-
|
|
887
|
+
* The `db-first` entry of a request's first call to its door, which says where its time went: `token` (having the
|
|
888
|
+
* token: none when the request handed one), which path's answer `won`, each path's time (`socket` and `fetch`: its
|
|
889
|
+
* answer's, or how it ended without one, as dropped once the other won), `warm` (the door's connection started at
|
|
890
|
+
* connect, ended before the call or still going beside it; `none` where none was started) and the socket's hello
|
|
891
|
+
* (`hello`: how long until it was answered, or still opening, or none). A slow call beside a quick warm-up was the
|
|
892
|
+
* Database (waking, or the engine); a slow warm-up the connection.
|
|
893
|
+
*/
|
|
894
|
+
function firstEntry(lane, tokenMs, started, won, legs) {
|
|
895
|
+
const warm = lane.warm;
|
|
896
|
+
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})`;
|
|
897
|
+
const socket = lane.socket;
|
|
898
|
+
const hello = !socket ? "none" : socket.openMs !== void 0 ? `answered in ${ms(socket.openMs)}` : socket.state === "opening" ? "opening" : `closed (${socket.why})`;
|
|
899
|
+
return `db-first;dur=${ms(tokenMs + (legs[won]?.ms ?? 0))};desc="token ${ms(tokenMs)}, won by ${won}, socket ${legOf(legs.socket)}, fetch ${legOf(legs.fetch)}, warm ${warmed}, hello ${hello}"`;
|
|
900
|
+
}
|
|
901
|
+
/** A WebSocket to `url` once it opens, as a `Connection`'s `dial` gives one. */
|
|
902
|
+
function openedAt(url) {
|
|
903
|
+
return new Promise((done, failed) => {
|
|
904
|
+
const ws = socketAt(url);
|
|
905
|
+
ws.addEventListener("open", () => done(ws), { once: true });
|
|
906
|
+
ws.addEventListener("error", () => failed(/* @__PURE__ */ new Error("socket error")), { once: true });
|
|
907
|
+
ws.addEventListener("close", () => failed(/* @__PURE__ */ new Error("socket closed")), { once: true });
|
|
908
|
+
});
|
|
909
|
+
}
|
|
910
|
+
/**
|
|
911
|
+
* A Deployment's server's calls to its Database, sent straight to the Database's door with the token its request
|
|
912
|
+
* handed in, with no hop through Midsummer. The calls made in one turn go together in one call (`DOOR_BATCH` at most),
|
|
913
|
+
* each result matched by its `i`, and a mutation is tagged, so one sent again applies once. A call that gets no answer,
|
|
914
|
+
* or a 5xx, is sent again twice at most; a 401 renews the token once. A token with under `DOOR_RENEW_MS` left is
|
|
915
|
+
* renewed before it is sent: from the door the request being served was handed, else the handle's `token`. The door
|
|
916
|
+
* answering that it has no Database by its id (404 `not_found`, as after a move with its rows gone) asks the handle to
|
|
917
|
+
* make it again (`remake`), once, and sends the calls once more.
|
|
918
|
+
*
|
|
919
|
+
* How a call goes, in each request (`Lane`): connecting starts the door's connection (`warmUp`). The request's first
|
|
920
|
+
* call opens a socket to the door's socket address (`DoorSocket`), where the door has one and the runtime can open one,
|
|
921
|
+
* the call right behind its hello. Until the hello is answered, calls that may go twice (reads, and mutations under
|
|
922
|
+
* their exactly-once tag) also go by fetch (`POST <door>/call`) at once, and the first answer stands: a fetch the socket
|
|
923
|
+
* beat is aborted, a socket's late answer ignored and the socket kept. An action goes on the socket alone. Once the
|
|
924
|
+
* hello is answered every call goes on the socket alone. A watch goes on the socket too. A socket that fails or closes
|
|
925
|
+
* leaves every call it held, and every later one of that request, to fetch, with no error; a watch opens a WebSocket to
|
|
926
|
+
* the door instead. A door with no socket address is fetch alone. A renewed token goes by fetch: a socket's token is
|
|
927
|
+
* its hello's. Every path is bounded by `DOOR_CALL_MS`.
|
|
466
928
|
*/
|
|
467
929
|
function doorCalls(handle, binding, first) {
|
|
468
930
|
let door = first;
|
|
@@ -473,7 +935,8 @@ function doorCalls(handle, binding, first) {
|
|
|
473
935
|
const handed = force ? void 0 : now().door?.(binding);
|
|
474
936
|
const next = handed && handed.url === door.url && handed.expiresAt - Date.now() > DOOR_RENEW_MS ? handed : {
|
|
475
937
|
...await now().token(binding),
|
|
476
|
-
url: door.url
|
|
938
|
+
url: door.url,
|
|
939
|
+
...door.socket ? { socket: door.socket } : {}
|
|
477
940
|
};
|
|
478
941
|
door = next;
|
|
479
942
|
return next;
|
|
@@ -487,11 +950,26 @@ function doorCalls(handle, binding, first) {
|
|
|
487
950
|
...answer,
|
|
488
951
|
i
|
|
489
952
|
});
|
|
490
|
-
/**
|
|
491
|
-
const
|
|
492
|
-
|
|
953
|
+
/** The request's socket, opened beside its first call or watch, once: where the door names an address and the runtime opens sockets. */
|
|
954
|
+
const begin = (lane, asker, token) => {
|
|
955
|
+
if (lane.tried) return;
|
|
956
|
+
lane.tried = true;
|
|
957
|
+
const database = new URL(door.url).pathname.split("/").filter(Boolean).at(-1);
|
|
958
|
+
if (!door.socket || !asker.socket || !database) return;
|
|
959
|
+
try {
|
|
960
|
+
lane.socket = new DoorSocket(asker.socket(door.socket), database, `Bearer ${token}`);
|
|
961
|
+
} catch {}
|
|
962
|
+
};
|
|
963
|
+
/**
|
|
964
|
+
* One call of `ops` to the door, and how to find each one's answer by its `i`. `races`: every op may go on both paths
|
|
965
|
+
* at once (a read, or a write under its exactly-once tag); an action may not, and goes on one.
|
|
966
|
+
*/
|
|
967
|
+
const post = async (ops, races) => {
|
|
968
|
+
const body = JSON.stringify(ops), bytes = encoder.encode(body), since = Date.now();
|
|
969
|
+
const asker = now(), lane = laneOf(asker, door.url);
|
|
493
970
|
let remade = false;
|
|
494
971
|
for (let tries = 0;; tries += 1) {
|
|
972
|
+
const asked = performance.now();
|
|
495
973
|
let token;
|
|
496
974
|
try {
|
|
497
975
|
token = await live();
|
|
@@ -502,19 +980,69 @@ function doorCalls(handle, binding, first) {
|
|
|
502
980
|
error: `no new token for the database bound as ${binding} (${error instanceof Error ? error.message : String(error)})`
|
|
503
981
|
});
|
|
504
982
|
}
|
|
983
|
+
const tokenMs = performance.now() - asked;
|
|
984
|
+
begin(lane, asker, token);
|
|
985
|
+
const authorization = `Bearer ${token}`;
|
|
986
|
+
const socket = lane.socket?.takes(authorization, bytes.length) ? lane.socket : void 0;
|
|
987
|
+
const how = !socket ? "fetch" : socket.state === "open" || !races ? "socket" : "race";
|
|
505
988
|
const started = performance.now();
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
989
|
+
const first = !lane.timed;
|
|
990
|
+
lane.timed = true;
|
|
991
|
+
const legs = {};
|
|
992
|
+
const paths = [];
|
|
993
|
+
const bySocket = () => {
|
|
994
|
+
const leg = {};
|
|
995
|
+
legs.socket = leg;
|
|
996
|
+
return answeredWithin(socket, socket.call(bytes)).then((answer) => {
|
|
997
|
+
leg.ms = performance.now() - started;
|
|
998
|
+
leg.status = answer.status;
|
|
999
|
+
return {
|
|
1000
|
+
...answer,
|
|
1001
|
+
via: "socket"
|
|
1002
|
+
};
|
|
1003
|
+
}, (error) => {
|
|
1004
|
+
leg.ended = error instanceof SocketClosed ? `failed (${socket.why ?? "closed"})` : "failed";
|
|
1005
|
+
throw error;
|
|
1006
|
+
});
|
|
1007
|
+
};
|
|
1008
|
+
const byFetch = (signal) => {
|
|
1009
|
+
const leg = {};
|
|
1010
|
+
legs.fetch = leg;
|
|
1011
|
+
return (async () => {
|
|
1012
|
+
const response = await fetchAt(`${door.url}/call`, {
|
|
1013
|
+
method: "POST",
|
|
1014
|
+
headers: {
|
|
1015
|
+
authorization,
|
|
1016
|
+
"content-type": "application/json"
|
|
1017
|
+
},
|
|
1018
|
+
body,
|
|
1019
|
+
signal
|
|
1020
|
+
});
|
|
1021
|
+
const text = await response.text();
|
|
1022
|
+
leg.ms = performance.now() - started;
|
|
1023
|
+
leg.status = response.status;
|
|
1024
|
+
return {
|
|
1025
|
+
status: response.status,
|
|
1026
|
+
text,
|
|
1027
|
+
via: "fetch"
|
|
1028
|
+
};
|
|
1029
|
+
})().catch((error) => {
|
|
1030
|
+
leg.ended ??= "failed";
|
|
1031
|
+
throw error;
|
|
516
1032
|
});
|
|
517
|
-
|
|
1033
|
+
};
|
|
1034
|
+
let answer;
|
|
1035
|
+
if (how === "socket") try {
|
|
1036
|
+
answer = await bySocket();
|
|
1037
|
+
} catch (error) {
|
|
1038
|
+
if (error instanceof SocketClosed) {
|
|
1039
|
+
tries -= 1;
|
|
1040
|
+
continue;
|
|
1041
|
+
}
|
|
1042
|
+
throw error;
|
|
1043
|
+
}
|
|
1044
|
+
else if (how === "fetch") try {
|
|
1045
|
+
answer = await byFetch(AbortSignal.timeout(DOOR_CALL_MS));
|
|
518
1046
|
} catch (error) {
|
|
519
1047
|
if (tries < 2) continue;
|
|
520
1048
|
return all({
|
|
@@ -523,20 +1051,48 @@ function doorCalls(handle, binding, first) {
|
|
|
523
1051
|
error: `couldn't reach the database bound as ${binding} (${error instanceof Error ? error.message : String(error)})`
|
|
524
1052
|
});
|
|
525
1053
|
}
|
|
526
|
-
|
|
527
|
-
|
|
1054
|
+
else {
|
|
1055
|
+
const dropped = new AbortController();
|
|
1056
|
+
const viaSocket = bySocket(), viaFetch = byFetch(AbortSignal.any([dropped.signal, AbortSignal.timeout(DOOR_CALL_MS)]));
|
|
1057
|
+
paths.push(viaSocket, viaFetch);
|
|
1058
|
+
try {
|
|
1059
|
+
answer = await Promise.any([viaSocket, viaFetch]);
|
|
1060
|
+
} catch (failed) {
|
|
1061
|
+
if (tries < 2) continue;
|
|
1062
|
+
const error = failed.errors?.[1];
|
|
1063
|
+
return all({
|
|
1064
|
+
ok: false,
|
|
1065
|
+
why: "unavailable",
|
|
1066
|
+
error: `couldn't reach the database bound as ${binding} (${error instanceof Error ? error.message : String(error)})`
|
|
1067
|
+
});
|
|
1068
|
+
}
|
|
1069
|
+
if (answer.via === "socket") {
|
|
1070
|
+
legs.fetch.ended = "dropped";
|
|
1071
|
+
dropped.abort();
|
|
1072
|
+
} else legs.socket.ended = "ignored";
|
|
1073
|
+
viaSocket.catch(() => {});
|
|
1074
|
+
viaFetch.catch(() => {});
|
|
1075
|
+
}
|
|
1076
|
+
const { status, text } = answer;
|
|
1077
|
+
const callMs = performance.now() - started;
|
|
1078
|
+
asker.note?.(`db-call;dur=${ms(callMs)};desc="${status}, ${ops.length} call${ops.length === 1 ? "" : "s"}${answer.via === "socket" ? ", socket" : ""}${how === "race" ? `, raced` : ""}"`);
|
|
1079
|
+
if (first) {
|
|
1080
|
+
const note = () => asker.note?.(firstEntry(lane, tokenMs, started, answer.via, legs));
|
|
1081
|
+
if (how === "race") Promise.allSettled(paths).then(note);
|
|
1082
|
+
else note();
|
|
1083
|
+
}
|
|
1084
|
+
if (status === 401 && tries === 0) {
|
|
528
1085
|
try {
|
|
529
1086
|
await renew(true);
|
|
530
1087
|
} catch {}
|
|
531
1088
|
continue;
|
|
532
1089
|
}
|
|
533
|
-
if (
|
|
1090
|
+
if (status < 200 || status > 299) {
|
|
534
1091
|
let refused = {};
|
|
535
1092
|
try {
|
|
536
1093
|
refused = JSON.parse(text);
|
|
537
1094
|
} catch {}
|
|
538
|
-
|
|
539
|
-
if (response.status === 404 && refused.error === "not_found" && !remade && asker.remake) {
|
|
1095
|
+
if (status === 404 && refused.error === "not_found" && !remade && asker.remake) {
|
|
540
1096
|
remade = true;
|
|
541
1097
|
const at = door.url;
|
|
542
1098
|
let asked = remaking.get(asker);
|
|
@@ -555,10 +1111,10 @@ function doorCalls(handle, binding, first) {
|
|
|
555
1111
|
}
|
|
556
1112
|
if (await asking) continue;
|
|
557
1113
|
}
|
|
558
|
-
if (
|
|
1114
|
+
if (status >= 500 && tries < 2) continue;
|
|
559
1115
|
return all({
|
|
560
1116
|
ok: false,
|
|
561
|
-
why:
|
|
1117
|
+
why: status === 401 ? "denied" : typeof refused.error === "string" ? refused.error : "refused",
|
|
562
1118
|
error: typeof refused.why === "string" ? refused.why : text.slice(0, 200)
|
|
563
1119
|
});
|
|
564
1120
|
}
|
|
@@ -577,7 +1133,7 @@ function doorCalls(handle, binding, first) {
|
|
|
577
1133
|
};
|
|
578
1134
|
}
|
|
579
1135
|
};
|
|
580
|
-
/** Sends what this turn queued, `DOOR_BATCH` calls a
|
|
1136
|
+
/** Sends what this turn queued, `DOOR_BATCH` calls at a time. */
|
|
581
1137
|
const flush = () => {
|
|
582
1138
|
const batch = queued;
|
|
583
1139
|
queued = [];
|
|
@@ -586,7 +1142,7 @@ function doorCalls(handle, binding, first) {
|
|
|
586
1142
|
post(part.map((each, n) => ({
|
|
587
1143
|
i: n + 1,
|
|
588
1144
|
...each.op
|
|
589
|
-
}))).then((answerOf) => {
|
|
1145
|
+
})), part.every((each) => each.races)).then((answerOf) => {
|
|
590
1146
|
part.forEach((each, n) => each.done(answerOf(n + 1)));
|
|
591
1147
|
}, (error) => {
|
|
592
1148
|
part.forEach((each, n) => each.done({
|
|
@@ -598,14 +1154,30 @@ function doorCalls(handle, binding, first) {
|
|
|
598
1154
|
});
|
|
599
1155
|
}
|
|
600
1156
|
};
|
|
601
|
-
const call = (op) => new Promise((done) => {
|
|
1157
|
+
const call = (op, races = true) => new Promise((done) => {
|
|
602
1158
|
if (queued.length === 0) queueMicrotask(flush);
|
|
603
1159
|
queued.push({
|
|
604
1160
|
op,
|
|
1161
|
+
races,
|
|
605
1162
|
done
|
|
606
1163
|
});
|
|
607
1164
|
});
|
|
608
|
-
|
|
1165
|
+
/**
|
|
1166
|
+
* A watch's socket for the request it opens in: a watch on the request's socket while that is open with the
|
|
1167
|
+
* connection's token, else a WebSocket to the door. A watch the Database refuses fails as a WebSocket's open would.
|
|
1168
|
+
*/
|
|
1169
|
+
const dial = (lane) => async (connection) => {
|
|
1170
|
+
const socket = lane.socket;
|
|
1171
|
+
if (socket && socket.state !== "closed" && socket.authorization === `Bearer ${connection.token}`) try {
|
|
1172
|
+
return await socket.watch();
|
|
1173
|
+
} catch (error) {
|
|
1174
|
+
if (!(error instanceof SocketClosed)) throw error;
|
|
1175
|
+
}
|
|
1176
|
+
return openedAt(connection.url);
|
|
1177
|
+
};
|
|
1178
|
+
/** Each request's watches, on one connection that request opened. */
|
|
1179
|
+
const watchers = /* @__PURE__ */ new WeakMap();
|
|
1180
|
+
warmUp(laneOf(now(), door.url), door.url);
|
|
609
1181
|
return {
|
|
610
1182
|
async query(fn, args) {
|
|
611
1183
|
const answer = await call({
|
|
@@ -625,22 +1197,29 @@ function doorCalls(handle, binding, first) {
|
|
|
625
1197
|
f: fn.name,
|
|
626
1198
|
a: args,
|
|
627
1199
|
t: tag ?? `${client}:${tags += 1}`
|
|
628
|
-
});
|
|
1200
|
+
}, fn.kind !== "action");
|
|
629
1201
|
},
|
|
630
1202
|
watchQuery(fn, args, options, onValue) {
|
|
631
1203
|
let stopped = false, stop = () => {};
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
1204
|
+
const asker = now(), lane = laneOf(asker, door.url);
|
|
1205
|
+
let watcher = watchers.get(lane);
|
|
1206
|
+
if (!watcher) {
|
|
1207
|
+
const opening = live().then((token) => {
|
|
1208
|
+
begin(lane, asker, token);
|
|
1209
|
+
return Connection.open(door.url, {
|
|
1210
|
+
token,
|
|
1211
|
+
refresh: async () => (await renew(true)).token,
|
|
1212
|
+
shape: "server",
|
|
1213
|
+
dial: dial(lane)
|
|
1214
|
+
});
|
|
1215
|
+
});
|
|
638
1216
|
opening.catch(() => {
|
|
639
|
-
if (
|
|
1217
|
+
if (watchers.get(lane) === opening) watchers.delete(lane);
|
|
640
1218
|
});
|
|
641
|
-
|
|
1219
|
+
watchers.set(lane, opening);
|
|
1220
|
+
watcher = opening;
|
|
642
1221
|
}
|
|
643
|
-
|
|
1222
|
+
watcher.then((open) => {
|
|
644
1223
|
if (!stopped) stop = open.watchQuery(fn, args, options, onValue);
|
|
645
1224
|
}, (error) => {
|
|
646
1225
|
if (!stopped) onValue(void 0, { error: caught(error) });
|
|
@@ -651,7 +1230,7 @@ function doorCalls(handle, binding, first) {
|
|
|
651
1230
|
};
|
|
652
1231
|
},
|
|
653
1232
|
close() {
|
|
654
|
-
|
|
1233
|
+
watchers.get(laneOf(now(), door.url))?.then((open) => open.close(), () => {});
|
|
655
1234
|
}
|
|
656
1235
|
};
|
|
657
1236
|
}
|
|
@@ -409,8 +409,8 @@ var Connection = class Connection {
|
|
|
409
409
|
...options,
|
|
410
410
|
shape
|
|
411
411
|
};
|
|
412
|
-
if (o.store === void 0 && typeof indexedDB !== "undefined" && typeof document !== "undefined") o.store = (await import("./store-
|
|
413
|
-
if (o.tabs !== false && typeof document !== "undefined") return (await import("./tabs-
|
|
412
|
+
if (o.store === void 0 && typeof indexedDB !== "undefined" && typeof document !== "undefined") o.store = (await import("./store-Ch931wwA.mjs")).idbStore(new URL(url).host);
|
|
413
|
+
if (o.tabs !== false && typeof document !== "undefined") return (await import("./tabs-C4NDJzfK.mjs")).ConnectionTabs.connect(url, o);
|
|
414
414
|
return Connection.open(url, o);
|
|
415
415
|
}
|
|
416
416
|
/** A Connection over one socket, of the shape given (default "browser"), no detection (tabs.mjs opens its own so). */
|
|
@@ -2009,4 +2009,4 @@ var Connection = class Connection {
|
|
|
2009
2009
|
}
|
|
2010
2010
|
};
|
|
2011
2011
|
//#endregion
|
|
2012
|
-
export { payloadOf as i, TAG_TTL as n, fetchAt as r, Connection as t };
|
|
2012
|
+
export { socketAt as a, payloadOf as i, TAG_TTL as n, fetchAt as r, Connection as t };
|
package/database/client.d.mts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { n as DatabaseErrorCode, t as DatabaseError } from "../errors-CnQduDOt.mjs";
|
|
2
|
-
import {
|
|
3
|
-
export { ArgsOf, AuthState, BoundDatabases, ConnectOptions, DATABASE_TOKEN_PATH, Database, DatabaseClient, DatabaseError, type DatabaseErrorCode, DatabaseToken, FetchToken, PROFILE_MOST, Reference, ReturnsOf, SignedInDatabase, UserProfile, auth0, clerk, connect, databaseUrl, oidc, profileClaims, signedInDatabase, userToken };
|
|
2
|
+
import { C as userToken, S as signedInDatabase, _ as clerk, a as DATABASE_TOKEN_PATH, b as oidc, c as DatabaseToken, d as PROFILE_MOST, f as Reference, g as auth0, h as UserProfile, i as ConnectOptions, l as DoorToken, m as SignedInDatabase, n as AuthState, o as Database, p as ReturnsOf, r as BoundDatabases, s as DatabaseClient, t as ArgsOf, u as FetchToken, v as connect, x as profileClaims, y as databaseUrl } from "../client-BDjPQa7G.mjs";
|
|
3
|
+
export { ArgsOf, AuthState, BoundDatabases, ConnectOptions, DATABASE_TOKEN_PATH, Database, DatabaseClient, DatabaseError, type DatabaseErrorCode, DatabaseToken, DoorToken, FetchToken, PROFILE_MOST, Reference, ReturnsOf, SignedInDatabase, UserProfile, auth0, clerk, connect, databaseUrl, oidc, profileClaims, signedInDatabase, userToken };
|
package/database/client.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { DatabaseError } from "./errors.mjs";
|
|
2
|
-
import { a as clerk, c as oidc, d as userToken, i as auth0, l as profileClaims, n as DatabaseClient, o as connect, r as PROFILE_MOST, s as databaseUrl, t as DATABASE_TOKEN_PATH, u as signedInDatabase } from "../client-
|
|
2
|
+
import { a as clerk, c as oidc, d as userToken, i as auth0, l as profileClaims, n as DatabaseClient, o as connect, r as PROFILE_MOST, s as databaseUrl, t as DATABASE_TOKEN_PATH, u as signedInDatabase } from "../client-CrJkXd5h.mjs";
|
|
3
3
|
export { DATABASE_TOKEN_PATH, DatabaseClient, DatabaseError, PROFILE_MOST, auth0, clerk, connect, databaseUrl, oidc, profileClaims, signedInDatabase, userToken };
|
package/database/react.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as DatabaseError } from "../errors-CnQduDOt.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { f as Reference, o as Database } from "../client-BDjPQa7G.mjs";
|
|
3
3
|
import { ReactNode } from "react";
|
|
4
4
|
//#region src/database/react.d.ts
|
|
5
5
|
type ArgsOf<F> = F extends Reference<any, infer A, any> ? A : never;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as AuthStore } from "./store-
|
|
1
|
+
import { n as AuthStore } from "./store-CRqU5WCe.mjs";
|
|
2
2
|
import { n as CaptchaProvider, t as AuthSettings } from "./settings-Dz3irtlu.mjs";
|
|
3
3
|
import { SignInMail } from "./auth/mail.mjs";
|
|
4
4
|
//#region src/auth/events.d.ts
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@midsummer-ai/sdk",
|
|
3
|
-
"version": "0.1.0-staging.
|
|
3
|
+
"version": "0.1.0-staging.3781",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "Midsummer's handles for an app's code: its Database, Storage, Queues, Vector DB, AI, Email and Agents, with stand-ins for tests.",
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { o as Database } from "./client-
|
|
1
|
+
import { o as Database } from "./client-BDjPQa7G.mjs";
|
|
2
2
|
//#region src/auth/store.d.ts
|
|
3
3
|
/** One of `db/auth.ts`'s functions. */
|
|
4
4
|
type AuthCall = "create" | "findOne" | "findMany" | "count" | "update" | "updateMany" | "upsert" | "deleteMany" | "consume" | "increment" | "page";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as Connection } from "./connection-
|
|
1
|
+
import { t as Connection } from "./connection-CpT0x1EE.mjs";
|
|
2
2
|
//#region src/database/client/tabs.mjs
|
|
3
3
|
/** Argument index of the options that take a `tag` (a tab tags its own writes: the same tag after a handover). */
|
|
4
4
|
const TAGGED = {
|