foldkit-sync 0.11.1 → 0.12.1
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 +23 -3
- package/dist/do.d.mts +39 -7
- package/dist/do.d.mts.map +1 -1
- package/dist/do.mjs +94 -41
- package/dist/do.mjs.map +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/journal-BtYEDz0E.mjs +301 -0
- package/dist/journal-BtYEDz0E.mjs.map +1 -0
- package/dist/journal.d.mts +75 -2
- package/dist/journal.d.mts.map +1 -1
- package/dist/journal.mjs +1 -212
- package/package.json +15 -15
- package/dist/journal.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -303,7 +303,7 @@ export class SyncHost extends defineDocumentHost(DurableObject, {
|
|
|
303
303
|
sync: TodoSync,
|
|
304
304
|
// A D1 journal as the durable D1 guide opens one.
|
|
305
305
|
openJournal: (_ctx, env) => openTodosJournal(env.DB),
|
|
306
|
-
resolvePrincipal: request => request.headers.get('x-actor') ?? 'anon',
|
|
306
|
+
resolvePrincipal: request => Effect.succeed(request.headers.get('x-actor') ?? 'anon'),
|
|
307
307
|
}) {}
|
|
308
308
|
```
|
|
309
309
|
|
|
@@ -324,13 +324,33 @@ Sync.transport.socket({ url: 'wss://example.com/sync' })
|
|
|
324
324
|
`openJournal` runs once, on the first upgrade: over D1 (`d1: true`, see
|
|
325
325
|
[the durable D1 guide](../durable/README.md#on-cloudflare-d1-d1-true)), or
|
|
326
326
|
the object's SQLite storage through `ctx`.
|
|
327
|
-
- Each upgrade resolves its own principal
|
|
328
|
-
|
|
327
|
+
- Each upgrade resolves its own principal, an Effect that refuses the caller
|
|
328
|
+
by failing with a `RemoteUnauthenticated` (`RemoteServer.unauthenticated()`
|
|
329
|
+
makes one): a 401 carrying its message. Non-upgrades are 404s that open
|
|
330
|
+
nothing. A resolver that breaks, a `layer` that fails to build, or a
|
|
331
|
+
journal that never opened, is a 500 that says nothing of it.
|
|
332
|
+
- A resolver that reads a service (a session store) takes it from
|
|
333
|
+
`layer: env => Layer`, required exactly when the resolver needs one. It is
|
|
334
|
+
built per upgrade and kept until the socket closes, so `revalidate` reads
|
|
335
|
+
an open store; a refused upgrade closes it at once.
|
|
336
|
+
- `revalidate: { every, key? }` asks the resolver again, of the upgrade
|
|
337
|
+
request, while the socket is open: a refusal closes it with 4401, and a
|
|
338
|
+
principal whose `key` (`Policy.keyOf`) changed with 1012, which the
|
|
339
|
+
replica reconnects after. Without it a socket serves its first principal until it closes.
|
|
329
340
|
- `settle: (env, journal) => Effect` runs after each exchange's appends, before
|
|
330
341
|
the reply is read, to apply what committed elsewhere — the Remote tables a
|
|
331
342
|
reader then queries. `journal.recover` makes it crash-safe and idempotent;
|
|
332
343
|
`env` and the journal are handed over because the store they reach lives
|
|
333
344
|
outside the exchange.
|
|
345
|
+
- Off Cloudflare, `documentHost` from `foldkit-sync/journal` is the same
|
|
346
|
+
host without the class: `documentHost({ sync, journal, resolvePrincipal,
|
|
347
|
+
layer?, revalidate?, opens?, admit?, settle? })` answers each upgrade
|
|
348
|
+
request before a socket opens, refused with the `Response` to send, or
|
|
349
|
+
accepted with `serve`, for the socket once the runtime has opened it (a
|
|
350
|
+
`HostSocket`: Sync's socket, plus `closeWith(code, reason)`), and
|
|
351
|
+
`abandon`, for when it never will (the client left, the handshake was
|
|
352
|
+
refused). One of the two must follow: until then the upgrade holds what
|
|
353
|
+
its `layer` built. `defineDocumentHost` is built on it.
|
|
334
354
|
- A server socket is not a live stream: another request cannot wake the fiber
|
|
335
355
|
of an open SSE response in a worker, not even from the same isolate. What
|
|
336
356
|
crosses requests there is the store they share (D1 here), and the live side
|
package/dist/do.d.mts
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
import { n as AuthorizeDecision, v as Operation, w as Sync } from "./make-CFOcLcQ1.mjs";
|
|
2
|
-
import { Effect } from "effect";
|
|
2
|
+
import { Duration, Effect, Layer } from "effect";
|
|
3
3
|
import { Journal } from "foldkit-durable/core";
|
|
4
|
+
import { RemoteUnauthenticated } from "foldkit-remote";
|
|
4
5
|
//#region src/do.d.ts
|
|
5
6
|
/** The sliver of a Durable Object the host uses: state for the journal to open with. */
|
|
6
7
|
export interface DocumentHostContext {
|
|
7
8
|
readonly storage?: unknown;
|
|
8
9
|
}
|
|
9
10
|
/** What `defineDocumentHost` needs of the application, per document. */
|
|
10
|
-
export interface DocumentHostConfig<Message, Shared, Principal, Env> {
|
|
11
|
+
export interface DocumentHostConfig<Message, Shared, Principal, Env, RP = never> {
|
|
11
12
|
/** The document's contract: its codecs and journal shape. */
|
|
12
13
|
readonly sync: Sync<Message, Shared>;
|
|
13
14
|
/**
|
|
@@ -18,8 +19,14 @@ export interface DocumentHostConfig<Message, Shared, Principal, Env> {
|
|
|
18
19
|
* tries again.
|
|
19
20
|
*/
|
|
20
21
|
readonly openJournal: (ctx: DocumentHostContext, env: Env) => Promise<Journal<Operation, Shared, Principal, Operation>>;
|
|
21
|
-
/**
|
|
22
|
-
|
|
22
|
+
/**
|
|
23
|
+
* Who is opening this socket, from the upgrade request. Fails with a
|
|
24
|
+
* `RemoteUnauthenticated` (`foldkit-remote`; `RemoteServer.unauthenticated()`
|
|
25
|
+
* makes one) to refuse it: a 401 carrying its message. A defect is a 500
|
|
26
|
+
* that says nothing of it. What it needs (a session store) comes from
|
|
27
|
+
* `layer`.
|
|
28
|
+
*/
|
|
29
|
+
readonly resolvePrincipal: (request: Request, env: Env) => Effect.Effect<Principal, RemoteUnauthenticated, RP>;
|
|
23
30
|
/**
|
|
24
31
|
* Runs after each exchange's appends and before the reply is read: apply
|
|
25
32
|
* what committed to another store, through `journal.recover`. Takes the
|
|
@@ -27,6 +34,19 @@ export interface DocumentHostConfig<Message, Shared, Principal, Env> {
|
|
|
27
34
|
* outside the exchange. See `serveJournal`.
|
|
28
35
|
*/
|
|
29
36
|
readonly settle?: ((env: Env, journal: Journal<Operation, Shared, Principal, Operation>) => Effect.Effect<void, unknown>) | undefined;
|
|
37
|
+
/**
|
|
38
|
+
* Asks `resolvePrincipal` again, of the upgrade request, every `every`
|
|
39
|
+
* while the socket is open: a refusal closes it with 4401, and a principal
|
|
40
|
+
* whose `key` differs from the one it opened with (`Policy.keyOf`) closes
|
|
41
|
+
* it with 1012, which the replica reconnects after, as the new principal;
|
|
42
|
+
* without `key` only a refusal closes it. Without it a socket
|
|
43
|
+
* serves the principal it opened with until it closes, a revoked session
|
|
44
|
+
* included.
|
|
45
|
+
*/
|
|
46
|
+
readonly revalidate?: {
|
|
47
|
+
readonly every: Duration.Input;
|
|
48
|
+
readonly key?: ((principal: Principal) => unknown) | undefined;
|
|
49
|
+
} | undefined;
|
|
30
50
|
/** Whether `principal` may open the document. See `journalExchange`'s `opens`. */
|
|
31
51
|
readonly opens?: ((principal: Principal) => Effect.Effect<boolean>) | undefined;
|
|
32
52
|
/**
|
|
@@ -41,6 +61,17 @@ export interface DocumentHostConfig<Message, Shared, Principal, Env> {
|
|
|
41
61
|
*/
|
|
42
62
|
readonly pair?: (() => readonly [client: WebSocket, server: AcceptingWebSocket]) | undefined;
|
|
43
63
|
}
|
|
64
|
+
/**
|
|
65
|
+
* What the resolver needs, from the environment: required exactly when it
|
|
66
|
+
* needs something. Built per upgrade and kept until the socket closes, since
|
|
67
|
+
* `revalidate` asks the resolver again while it is open; an upgrade that is
|
|
68
|
+
* refused closes it at once.
|
|
69
|
+
*/
|
|
70
|
+
export type DocumentHostLayer<Env, RP> = [RP] extends [never] ? {
|
|
71
|
+
readonly layer?: undefined;
|
|
72
|
+
} : {
|
|
73
|
+
readonly layer: (env: Env) => Layer.Layer<RP>;
|
|
74
|
+
};
|
|
44
75
|
/**
|
|
45
76
|
* A server `WebSocket`: accepted once it serves. The `accept` member is a
|
|
46
77
|
* worker-runtime extension the DOM type does not declare.
|
|
@@ -50,10 +81,11 @@ export interface AcceptingWebSocket extends WebSocket {
|
|
|
50
81
|
}
|
|
51
82
|
/**
|
|
52
83
|
* Defines the Durable Object class serving one document's Sync exchange.
|
|
53
|
-
* Non-upgrades are 404s that open nothing; a
|
|
54
|
-
*
|
|
84
|
+
* Non-upgrades are 404s that open nothing; a refused principal is a 401; a
|
|
85
|
+
* resolver that breaks, or a journal that never opened, a 500 that says
|
|
86
|
+
* nothing of it.
|
|
55
87
|
*/
|
|
56
|
-
export declare const defineDocumentHost: <Message, Shared, Principal, Env>(Base: new (ctx: DocumentHostContext, env: Env) => object, config: DocumentHostConfig<Message, Shared, Principal, Env>) => new (ctx: DocumentHostContext, env: Env) => {
|
|
88
|
+
export declare const defineDocumentHost: <Message, Shared, Principal, Env, RP = never>(Base: new (ctx: DocumentHostContext, env: Env) => object, config: DocumentHostConfig<Message, Shared, Principal, Env, RP> & DocumentHostLayer<Env, RP>) => new (ctx: DocumentHostContext, env: Env) => {
|
|
57
89
|
fetch(request: Request): Promise<Response>;
|
|
58
90
|
};
|
|
59
91
|
//#endregion
|
package/dist/do.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"do.d.mts","names":[],"sources":["../src/do.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"do.d.mts","names":[],"sources":["../src/do.ts"],"mappings":";;;;;;iBAyCiB;WACN;;;iBAIM,mBAAmB,SAAS,QAAQ,WAAW,KAAK;;WAE1D,MAAM,KAAK,SAAS;;;;;;;;WAQpB,cACP,KAAK,qBACL,KAAK,QACF,QAAQ,QAAQ,WAAW,QAAQ,WAAW;;;;;;;;WAQ1C,mBACP,SAAS,SACT,KAAK,QACF,OAAO,OAAO,WAAW,uBAAuB;;;;;;;WAO5C,WAEH,KAAK,KACL,SAAS,QAAQ,WAAW,QAAQ,WAAW,eAC5C,OAAO;;;;;;;;;;WAWP;aAEM,OAAO,SAAS;aAChB,QAAQ,WAAW;;;WAIzB,UAAU,WAAW,cAAc,OAAO;;;;;WAK1C,UAEH,WAAW,WACX,WAAW,cACR,oBAAoB,OAAO,OAAO;;;;;;WAOlC,wBAAwB,QAAQ,WAAW,QAAQ;;;;;;;;YASlD,kBAAkB,KAAK,OAAO;WAC3B;;WACA,QAAQ,KAAK,QAAQ,MAAM,MAAM;;;;;;iBAM/B,2BAA2B;EAC1C;;;;;;;;qBAuCW,qBAAsB,SAAS,QAAQ,WAAW,KAAK,YAAU,WACjE,KAAK,qBAAqB,KAAK,gBAAc,QAChD,mBAAmB,SAAS,QAAQ,WAAW,KAAK,MAAM,kBAAkB,KAAK,aACnF,KAAK,qBAAqB,KAAK;EAAU,MAAM,SAAS,UAAU,QAAQ"}
|
package/dist/do.mjs
CHANGED
|
@@ -1,6 +1,46 @@
|
|
|
1
1
|
import { u as workerSocket } from "./transport-DiKXy5zx.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { n as documentHost, s as checkRevalidate } from "./journal-BtYEDz0E.mjs";
|
|
3
|
+
import { Result } from "effect";
|
|
3
4
|
//#region src/do.ts
|
|
5
|
+
/**
|
|
6
|
+
* `foldkit-sync/do`: serve one document's Sync exchange from a Cloudflare
|
|
7
|
+
* Durable Object, the single writer its journal wants. Each socket the
|
|
8
|
+
* object accepts exchanges against the same journal through `serveJournal`;
|
|
9
|
+
* the replica side already exists as `Sync.transport.socket` over the
|
|
10
|
+
* object's `wss://…` URL, which hears other writers' commits as notices.
|
|
11
|
+
*
|
|
12
|
+
* The class takes its `DurableObject` base as a parameter, so this module
|
|
13
|
+
* imports no worker runtime and loads anywhere:
|
|
14
|
+
*
|
|
15
|
+
* ```ts
|
|
16
|
+
* import { DurableObject } from 'cloudflare:workers'
|
|
17
|
+
*
|
|
18
|
+
* export class SyncHost extends defineDocumentHost(DurableObject, {
|
|
19
|
+
* sync: Todos,
|
|
20
|
+
* openJournal: (_ctx, env) => openTodosJournal(env.DB),
|
|
21
|
+
* resolvePrincipal: request =>
|
|
22
|
+
* Effect.succeed({ actorId: request.headers.get('x-actor') ?? 'anon' }),
|
|
23
|
+
* }) {}
|
|
24
|
+
* ```
|
|
25
|
+
*
|
|
26
|
+
* Open the journal once per object: on the first upgrade, so probes never
|
|
27
|
+
* provision storage. Route one object per document (`idFromName(sync
|
|
28
|
+
* .documentId)`); its in-memory cache and change stream are then exact
|
|
29
|
+
* because nothing else writes.
|
|
30
|
+
*/
|
|
31
|
+
/**
|
|
32
|
+
* Closes a socket with `code`, and `reason` when the platform takes it: a
|
|
33
|
+
* reason past 123 bytes, or a socket already gone, still closes or is closed.
|
|
34
|
+
*/
|
|
35
|
+
const closeWith = (socket, code, reason) => {
|
|
36
|
+
try {
|
|
37
|
+
socket.close(code, reason);
|
|
38
|
+
} catch {
|
|
39
|
+
try {
|
|
40
|
+
socket.close(code);
|
|
41
|
+
} catch {}
|
|
42
|
+
}
|
|
43
|
+
};
|
|
4
44
|
const defaultPair = () => {
|
|
5
45
|
const maker = globalThis.WebSocketPair;
|
|
6
46
|
if (maker === void 0) throw new Error("DocumentHost: no WebSocketPair global; pass `pair` explicitly");
|
|
@@ -9,49 +49,62 @@ const defaultPair = () => {
|
|
|
9
49
|
};
|
|
10
50
|
/**
|
|
11
51
|
* Defines the Durable Object class serving one document's Sync exchange.
|
|
12
|
-
* Non-upgrades are 404s that open nothing; a
|
|
13
|
-
*
|
|
52
|
+
* Non-upgrades are 404s that open nothing; a refused principal is a 401; a
|
|
53
|
+
* resolver that breaks, or a journal that never opened, a 500 that says
|
|
54
|
+
* nothing of it.
|
|
14
55
|
*/
|
|
15
|
-
const defineDocumentHost = (Base, config) =>
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
56
|
+
const defineDocumentHost = (Base, config) => {
|
|
57
|
+
checkRevalidate(config.revalidate, "defineDocumentHost");
|
|
58
|
+
return class extends Base {
|
|
59
|
+
host;
|
|
60
|
+
constructor(ctx, env) {
|
|
61
|
+
super(ctx, env);
|
|
62
|
+
let ready;
|
|
63
|
+
const { layer, settle } = config;
|
|
64
|
+
this.host = documentHost({
|
|
65
|
+
sync: config.sync,
|
|
66
|
+
journal: () => (ready ??= config.openJournal(ctx, env)).catch((error) => {
|
|
67
|
+
ready = void 0;
|
|
68
|
+
throw error;
|
|
69
|
+
}),
|
|
70
|
+
resolvePrincipal: (request) => config.resolvePrincipal(request, env),
|
|
71
|
+
layer: layer === void 0 ? void 0 : () => layer(env),
|
|
72
|
+
revalidate: config.revalidate,
|
|
73
|
+
settle: settle === void 0 ? void 0 : (journal) => settle(env, journal),
|
|
74
|
+
opens: config.opens,
|
|
75
|
+
admit: config.admit
|
|
76
|
+
});
|
|
31
77
|
}
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
78
|
+
async fetch(request) {
|
|
79
|
+
if (request.headers.get("Upgrade")?.toLowerCase() !== "websocket") return Response.json({ error: "not found" }, { status: 404 });
|
|
80
|
+
let pair;
|
|
81
|
+
try {
|
|
82
|
+
pair = (config.pair ?? defaultPair)();
|
|
83
|
+
} catch (error) {
|
|
84
|
+
console.error("[foldkit-sync] serving an upgrade broke:", error);
|
|
85
|
+
return Response.json({ error: "Internal error" }, { status: 500 });
|
|
86
|
+
}
|
|
87
|
+
const [client, server] = pair;
|
|
88
|
+
const answered = await this.host(request);
|
|
89
|
+
if (Result.isFailure(answered)) return answered.failure;
|
|
90
|
+
const { serve, abandon } = answered.success;
|
|
91
|
+
try {
|
|
92
|
+
server.accept();
|
|
93
|
+
serve({
|
|
94
|
+
...workerSocket(server),
|
|
95
|
+
closeWith: (code, reason) => closeWith(server, code, reason)
|
|
96
|
+
});
|
|
97
|
+
return new Response(null, {
|
|
98
|
+
status: 101,
|
|
99
|
+
webSocket: client
|
|
100
|
+
});
|
|
101
|
+
} catch (error) {
|
|
102
|
+
console.error("[foldkit-sync] serving an upgrade broke:", error);
|
|
103
|
+
abandon();
|
|
104
|
+
return Response.json({ error: "Internal error" }, { status: 500 });
|
|
105
|
+
}
|
|
38
106
|
}
|
|
39
|
-
|
|
40
|
-
server.accept();
|
|
41
|
-
const { admit } = config;
|
|
42
|
-
serveJournal(workerSocket(server), {
|
|
43
|
-
sync: config.sync,
|
|
44
|
-
journal,
|
|
45
|
-
principal,
|
|
46
|
-
...config.settle === void 0 ? {} : { settle: config.settle(this.hostEnv, journal) },
|
|
47
|
-
...config.opens === void 0 ? {} : { opens: config.opens(principal) },
|
|
48
|
-
...admit === void 0 ? {} : { admit: (operation) => admit(principal, operation) }
|
|
49
|
-
});
|
|
50
|
-
return new Response(null, {
|
|
51
|
-
status: 101,
|
|
52
|
-
webSocket: client
|
|
53
|
-
});
|
|
54
|
-
}
|
|
107
|
+
};
|
|
55
108
|
};
|
|
56
109
|
//#endregion
|
|
57
110
|
export { defineDocumentHost };
|
package/dist/do.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"do.mjs","names":[],"sources":["../src/do.ts"],"sourcesContent":["/**\n * `foldkit-sync/do`: serve one document's Sync exchange from a Cloudflare\n * Durable Object, the single writer its journal wants. Each socket the\n * object accepts exchanges against the same journal through `serveJournal`;\n * the replica side already exists as `Sync.transport.socket` over the\n * object's `wss://…` URL, which hears other writers' commits as notices.\n *\n * The class takes its `DurableObject` base as a parameter, so this module\n * imports no worker runtime and loads anywhere:\n *\n * ```ts\n * import { DurableObject } from 'cloudflare:workers'\n *\n * export class SyncHost extends defineDocumentHost(DurableObject, {\n * sync: Todos,\n * openJournal: (_ctx, env) => openTodosJournal(env.DB),\n * resolvePrincipal: request => ({ actorId: request.headers.get('x-actor') ?? 'anon' }),\n * }) {}\n * ```\n *\n * Open the journal once per object: on the first upgrade, so probes never\n * provision storage. Route one object per document (`idFromName(sync\n * .documentId)`); its in-memory cache and change stream are then exact\n * because nothing else writes.\n */\nimport type { Effect } from 'effect'\nimport type { Journal } from 'foldkit-durable/core'\nimport { serveJournal } from './journal.js'\nimport type { AuthorizeDecision } from './make.js'\nimport type { Operation, Sync } from './sync.js'\nimport { workerSocket } from './transport.js'\n\n/** The sliver of a Durable Object the host uses: state for the journal to open with. */\nexport interface DocumentHostContext {\n readonly storage?: unknown\n}\n\n/** What `defineDocumentHost` needs of the application, per document. */\nexport interface DocumentHostConfig<Message, Shared, Principal, Env> {\n /** The document's contract: its codecs and journal shape. */\n readonly sync: Sync<Message, Shared>\n /**\n * Opens the document's journal, once: on the first upgrade, not on\n * construction, so probes never provision storage. Over D1 (`d1: true`),\n * or the object's SQLite storage through `ctx`. May build with Effect and\n * unwrap; a rejection answers the upgrade with a 500, and the next upgrade\n * tries again.\n */\n readonly openJournal: (\n ctx: DocumentHostContext,\n env: Env,\n ) => Promise<Journal<Operation, Shared, Principal, Operation>>\n /** Who is opening this socket, from the upgrade request. May throw: a 401. */\n readonly resolvePrincipal: (request: Request, env: Env) => Principal | Promise<Principal>\n /**\n * Runs after each exchange's appends and before the reply is read: apply\n * what committed to another store, through `journal.recover`. Takes the\n * environment — a D1 binding, say — and the journal, because both live\n * outside the exchange. See `serveJournal`.\n */\n readonly settle?:\n | ((\n env: Env,\n journal: Journal<Operation, Shared, Principal, Operation>,\n ) => Effect.Effect<void, unknown>)\n | undefined\n /** Whether `principal` may open the document. See `journalExchange`'s `opens`. */\n readonly opens?: ((principal: Principal) => Effect.Effect<boolean>) | undefined\n /**\n * Whether an operation from `principal` may be appended, before the journal\n * sees it. See `journalExchange`'s `admit`.\n */\n readonly admit?:\n | ((\n principal: Principal,\n operation: Operation,\n ) => AuthorizeDecision | Effect.Effect<AuthorizeDecision, unknown>)\n | undefined\n /**\n * Makes the socket pair for an upgrade: the server end is accepted before\n * serving. Defaults to the `WebSocketPair` global where one exists (a\n * worker, miniflare); pass one in tests.\n */\n readonly pair?: (() => readonly [client: WebSocket, server: AcceptingWebSocket]) | undefined\n}\n\n/**\n * A server `WebSocket`: accepted once it serves. The `accept` member is a\n * worker-runtime extension the DOM type does not declare.\n */\nexport interface AcceptingWebSocket extends WebSocket {\n accept(): void\n}\n\nconst defaultPair = (): readonly [client: WebSocket, server: AcceptingWebSocket] => {\n const maker = (\n globalThis as {\n readonly WebSocketPair?:\n (new () => { readonly 0: WebSocket; readonly 1: AcceptingWebSocket }) | undefined\n }\n ).WebSocketPair\n if (maker === undefined)\n throw new Error('DocumentHost: no WebSocketPair global; pass `pair` explicitly')\n const pair = new maker()\n return [pair[0], pair[1]] as const\n}\n\n/**\n * Defines the Durable Object class serving one document's Sync exchange.\n * Non-upgrades are 404s that open nothing; a throwing principal resolution\n * is a 401; a journal that never opened is a 500 that says nothing of it.\n */\nexport const defineDocumentHost = <Message, Shared, Principal, Env>(\n Base: new (ctx: DocumentHostContext, env: Env) => object,\n config: DocumentHostConfig<Message, Shared, Principal, Env>,\n): new (ctx: DocumentHostContext, env: Env) => { fetch(request: Request): Promise<Response> } =>\n class extends Base {\n private readonly hostContext: DocumentHostContext\n private readonly hostEnv: Env\n private ready: Promise<Journal<Operation, Shared, Principal, Operation>> | undefined\n\n constructor(ctx: DocumentHostContext, env: Env) {\n super(ctx, env)\n this.hostContext = ctx\n this.hostEnv = env\n }\n\n async fetch(request: Request): Promise<Response> {\n if (request.headers.get('Upgrade')?.toLowerCase() !== 'websocket')\n return Response.json({ error: 'not found' }, { status: 404 })\n let principal: Principal\n try {\n principal = await config.resolvePrincipal(request, this.hostEnv)\n } catch (error) {\n return Response.json(\n { error: error instanceof Error ? error.message : String(error) },\n { status: 401 },\n )\n }\n let journal: Journal<Operation, Shared, Principal, Operation>\n try {\n journal = await (this.ready ??= config.openJournal(this.hostContext, this.hostEnv))\n } catch {\n // A failed open provisions nothing: the next upgrade tries again.\n this.ready = undefined\n return Response.json({ error: 'Internal error' }, { status: 500 })\n }\n const [client, server] = (config.pair ?? defaultPair)()\n server.accept()\n const { admit } = config\n serveJournal(workerSocket(server), {\n sync: config.sync,\n journal,\n principal,\n ...(config.settle === undefined ? {} : { settle: config.settle(this.hostEnv, journal) }),\n ...(config.opens === undefined ? {} : { opens: config.opens(principal) }),\n ...(admit === undefined\n ? {}\n : { admit: (operation: Operation) => admit(principal, operation) }),\n })\n return new Response(null, {\n status: 101,\n // The worker runtime reads the client out of the upgrade response;\n // the DOM's `ResponseInit` has no such member.\n webSocket: client,\n } as ResponseInit)\n }\n }\n"],"mappings":";;;AA8FA,MAAM,oBAA8E;CAClF,MAAM,QACJ,WAIA;CACF,IAAI,UAAU,KAAA,GACZ,MAAM,IAAI,MAAM,+DAA+D;CACjF,MAAM,OAAO,IAAI,MAAM;CACvB,OAAO,CAAC,KAAK,IAAI,KAAK,EAAE;AAC1B;;;;;;AAOA,MAAa,sBACX,MACA,WAEA,cAAc,KAAK;CACjB;CACA;CACA;CAEA,YAAY,KAA0B,KAAU;EAC9C,MAAM,KAAK,GAAG;EACd,KAAK,cAAc;EACnB,KAAK,UAAU;CACjB;CAEA,MAAM,MAAM,SAAqC;EAC/C,IAAI,QAAQ,QAAQ,IAAI,SAAS,CAAC,EAAE,YAAY,MAAM,aACpD,OAAO,SAAS,KAAK,EAAE,OAAO,YAAY,GAAG,EAAE,QAAQ,IAAI,CAAC;EAC9D,IAAI;EACJ,IAAI;GACF,YAAY,MAAM,OAAO,iBAAiB,SAAS,KAAK,OAAO;EACjE,SAAS,OAAO;GACd,OAAO,SAAS,KACd,EAAE,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE,GAChE,EAAE,QAAQ,IAAI,CAChB;EACF;EACA,IAAI;EACJ,IAAI;GACF,UAAU,OAAO,KAAK,UAAU,OAAO,YAAY,KAAK,aAAa,KAAK,OAAO;EACnF,QAAQ;GAEN,KAAK,QAAQ,KAAA;GACb,OAAO,SAAS,KAAK,EAAE,OAAO,iBAAiB,GAAG,EAAE,QAAQ,IAAI,CAAC;EACnE;EACA,MAAM,CAAC,QAAQ,WAAW,OAAO,QAAQ,YAAA,CAAa;EACtD,OAAO,OAAO;EACd,MAAM,EAAE,UAAU;EAClB,aAAa,aAAa,MAAM,GAAG;GACjC,MAAM,OAAO;GACb;GACA;GACA,GAAI,OAAO,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,OAAO,OAAO,KAAK,SAAS,OAAO,EAAE;GACtF,GAAI,OAAO,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,OAAO,MAAM,SAAS,EAAE;GACvE,GAAI,UAAU,KAAA,IACV,CAAC,IACD,EAAE,QAAQ,cAAyB,MAAM,WAAW,SAAS,EAAE;EACrE,CAAC;EACD,OAAO,IAAI,SAAS,MAAM;GACxB,QAAQ;GAGR,WAAW;EACb,CAAiB;CACnB;AACF"}
|
|
1
|
+
{"version":3,"file":"do.mjs","names":[],"sources":["../src/do.ts"],"sourcesContent":["/**\n * `foldkit-sync/do`: serve one document's Sync exchange from a Cloudflare\n * Durable Object, the single writer its journal wants. Each socket the\n * object accepts exchanges against the same journal through `serveJournal`;\n * the replica side already exists as `Sync.transport.socket` over the\n * object's `wss://…` URL, which hears other writers' commits as notices.\n *\n * The class takes its `DurableObject` base as a parameter, so this module\n * imports no worker runtime and loads anywhere:\n *\n * ```ts\n * import { DurableObject } from 'cloudflare:workers'\n *\n * export class SyncHost extends defineDocumentHost(DurableObject, {\n * sync: Todos,\n * openJournal: (_ctx, env) => openTodosJournal(env.DB),\n * resolvePrincipal: request =>\n * Effect.succeed({ actorId: request.headers.get('x-actor') ?? 'anon' }),\n * }) {}\n * ```\n *\n * Open the journal once per object: on the first upgrade, so probes never\n * provision storage. Route one object per document (`idFromName(sync\n * .documentId)`); its in-memory cache and change stream are then exact\n * because nothing else writes.\n */\nimport { type Duration, type Effect, type Layer, Result } from 'effect'\nimport type { RemoteUnauthenticated } from 'foldkit-remote'\nimport type { Journal } from 'foldkit-durable/core'\nimport {\n documentHost,\n type Accepted,\n type DocumentHostOptions,\n type DocumentHostOptionsLayer,\n} from './journal.js'\nimport { checkRevalidate } from './revalidate.js'\nimport type { AuthorizeDecision } from './make.js'\nimport type { Operation, Sync } from './sync.js'\nimport { workerSocket } from './transport.js'\n\n/** The sliver of a Durable Object the host uses: state for the journal to open with. */\nexport interface DocumentHostContext {\n readonly storage?: unknown\n}\n\n/** What `defineDocumentHost` needs of the application, per document. */\nexport interface DocumentHostConfig<Message, Shared, Principal, Env, RP = never> {\n /** The document's contract: its codecs and journal shape. */\n readonly sync: Sync<Message, Shared>\n /**\n * Opens the document's journal, once: on the first upgrade, not on\n * construction, so probes never provision storage. Over D1 (`d1: true`),\n * or the object's SQLite storage through `ctx`. May build with Effect and\n * unwrap; a rejection answers the upgrade with a 500, and the next upgrade\n * tries again.\n */\n readonly openJournal: (\n ctx: DocumentHostContext,\n env: Env,\n ) => Promise<Journal<Operation, Shared, Principal, Operation>>\n /**\n * Who is opening this socket, from the upgrade request. Fails with a\n * `RemoteUnauthenticated` (`foldkit-remote`; `RemoteServer.unauthenticated()`\n * makes one) to refuse it: a 401 carrying its message. A defect is a 500\n * that says nothing of it. What it needs (a session store) comes from\n * `layer`.\n */\n readonly resolvePrincipal: (\n request: Request,\n env: Env,\n ) => Effect.Effect<Principal, RemoteUnauthenticated, RP>\n /**\n * Runs after each exchange's appends and before the reply is read: apply\n * what committed to another store, through `journal.recover`. Takes the\n * environment — a D1 binding, say — and the journal, because both live\n * outside the exchange. See `serveJournal`.\n */\n readonly settle?:\n | ((\n env: Env,\n journal: Journal<Operation, Shared, Principal, Operation>,\n ) => Effect.Effect<void, unknown>)\n | undefined\n /**\n * Asks `resolvePrincipal` again, of the upgrade request, every `every`\n * while the socket is open: a refusal closes it with 4401, and a principal\n * whose `key` differs from the one it opened with (`Policy.keyOf`) closes\n * it with 1012, which the replica reconnects after, as the new principal;\n * without `key` only a refusal closes it. Without it a socket\n * serves the principal it opened with until it closes, a revoked session\n * included.\n */\n readonly revalidate?:\n | {\n readonly every: Duration.Input\n readonly key?: ((principal: Principal) => unknown) | undefined\n }\n | undefined\n /** Whether `principal` may open the document. See `journalExchange`'s `opens`. */\n readonly opens?: ((principal: Principal) => Effect.Effect<boolean>) | undefined\n /**\n * Whether an operation from `principal` may be appended, before the journal\n * sees it. See `journalExchange`'s `admit`.\n */\n readonly admit?:\n | ((\n principal: Principal,\n operation: Operation,\n ) => AuthorizeDecision | Effect.Effect<AuthorizeDecision, unknown>)\n | undefined\n /**\n * Makes the socket pair for an upgrade: the server end is accepted before\n * serving. Defaults to the `WebSocketPair` global where one exists (a\n * worker, miniflare); pass one in tests.\n */\n readonly pair?: (() => readonly [client: WebSocket, server: AcceptingWebSocket]) | undefined\n}\n\n/**\n * What the resolver needs, from the environment: required exactly when it\n * needs something. Built per upgrade and kept until the socket closes, since\n * `revalidate` asks the resolver again while it is open; an upgrade that is\n * refused closes it at once.\n */\nexport type DocumentHostLayer<Env, RP> = [RP] extends [never]\n ? { readonly layer?: undefined }\n : { readonly layer: (env: Env) => Layer.Layer<RP> }\n\n/**\n * A server `WebSocket`: accepted once it serves. The `accept` member is a\n * worker-runtime extension the DOM type does not declare.\n */\nexport interface AcceptingWebSocket extends WebSocket {\n accept(): void\n}\n\n/**\n * Closes a socket with `code`, and `reason` when the platform takes it: a\n * reason past 123 bytes, or a socket already gone, still closes or is closed.\n */\nconst closeWith = (socket: WebSocket, code: number, reason: string): void => {\n try {\n socket.close(code, reason)\n } catch {\n try {\n socket.close(code)\n } catch {\n // Already closed.\n }\n }\n}\n\nconst defaultPair = (): readonly [client: WebSocket, server: AcceptingWebSocket] => {\n const maker = (\n globalThis as {\n readonly WebSocketPair?:\n | (new () => { readonly 0: WebSocket; readonly 1: AcceptingWebSocket })\n | undefined\n }\n ).WebSocketPair\n if (maker === undefined)\n throw new Error('DocumentHost: no WebSocketPair global; pass `pair` explicitly')\n const pair = new maker()\n return [pair[0], pair[1]] as const\n}\n\n/**\n * Defines the Durable Object class serving one document's Sync exchange.\n * Non-upgrades are 404s that open nothing; a refused principal is a 401; a\n * resolver that breaks, or a journal that never opened, a 500 that says\n * nothing of it.\n */\nexport const defineDocumentHost = <Message, Shared, Principal, Env, RP = never>(\n Base: new (ctx: DocumentHostContext, env: Env) => object,\n config: DocumentHostConfig<Message, Shared, Principal, Env, RP> & DocumentHostLayer<Env, RP>,\n): new (ctx: DocumentHostContext, env: Env) => { fetch(request: Request): Promise<Response> } => {\n checkRevalidate(config.revalidate, 'defineDocumentHost')\n return class extends Base {\n private readonly host: (request: Request) => Promise<Result.Result<Accepted, Response>>\n\n constructor(ctx: DocumentHostContext, env: Env) {\n super(ctx, env)\n let ready: Promise<Journal<Operation, Shared, Principal, Operation>> | undefined\n const { layer, settle } = config\n this.host = documentHost<Message, Shared, Principal, RP>({\n sync: config.sync,\n // Opened on the first upgrade a principal passes, so probes never\n // provision storage; a failed open is tried again on the next.\n journal: () =>\n (ready ??= config.openJournal(ctx, env)).catch((error: unknown) => {\n ready = undefined\n throw error\n }),\n resolvePrincipal: request => config.resolvePrincipal(request, env),\n layer: layer === undefined ? undefined : () => layer(env),\n revalidate: config.revalidate,\n settle: settle === undefined ? undefined : journal => settle(env, journal),\n opens: config.opens,\n admit: config.admit,\n // `DocumentHostLayer` already tied `layer` to `RP` on the config; the\n // conditional cannot be resolved for an `RP` still generic here.\n } as DocumentHostOptions<Message, Shared, Principal, RP> & DocumentHostOptionsLayer<RP>)\n }\n\n async fetch(request: Request): Promise<Response> {\n if (request.headers.get('Upgrade')?.toLowerCase() !== 'websocket')\n return Response.json({ error: 'not found' }, { status: 404 })\n // Made first: a runtime without WebSocketPair is a 500 that resolves no one.\n let pair: readonly [client: WebSocket, server: AcceptingWebSocket]\n try {\n pair = (config.pair ?? defaultPair)()\n } catch (error) {\n // The replica learns nothing of it; whoever runs the host must.\n console.error('[foldkit-sync] serving an upgrade broke:', error)\n return Response.json({ error: 'Internal error' }, { status: 500 })\n }\n const [client, server] = pair\n const answered = await this.host(request)\n if (Result.isFailure(answered)) return answered.failure\n const { serve, abandon } = answered.success\n try {\n server.accept()\n serve({\n ...workerSocket(server),\n closeWith: (code, reason) => closeWith(server, code, reason),\n })\n return new Response(null, {\n status: 101,\n // The worker runtime reads the client out of the upgrade response;\n // the DOM's `ResponseInit` has no such member.\n webSocket: client,\n } as ResponseInit)\n } catch (error) {\n console.error('[foldkit-sync] serving an upgrade broke:', error)\n abandon()\n return Response.json({ error: 'Internal error' }, { status: 500 })\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4IA,MAAM,aAAa,QAAmB,MAAc,WAAyB;CAC3E,IAAI;EACF,OAAO,MAAM,MAAM,MAAM;CAC3B,QAAQ;EACN,IAAI;GACF,OAAO,MAAM,IAAI;EACnB,QAAQ,CAER;CACF;AACF;AAEA,MAAM,oBAA8E;CAClF,MAAM,QACJ,WAKA;CACF,IAAI,UAAU,KAAA,GACZ,MAAM,IAAI,MAAM,+DAA+D;CACjF,MAAM,OAAO,IAAI,MAAM;CACvB,OAAO,CAAC,KAAK,IAAI,KAAK,EAAE;AAC1B;;;;;;;AAQA,MAAa,sBACX,MACA,WAC+F;CAC/F,gBAAgB,OAAO,YAAY,oBAAoB;CACvD,OAAO,cAAc,KAAK;EACxB;EAEA,YAAY,KAA0B,KAAU;GAC9C,MAAM,KAAK,GAAG;GACd,IAAI;GACJ,MAAM,EAAE,OAAO,WAAW;GAC1B,KAAK,OAAO,aAA6C;IACvD,MAAM,OAAO;IAGb,gBACG,UAAU,OAAO,YAAY,KAAK,GAAG,EAAA,CAAG,OAAO,UAAmB;KACjE,QAAQ,KAAA;KACR,MAAM;IACR,CAAC;IACH,mBAAkB,YAAW,OAAO,iBAAiB,SAAS,GAAG;IACjE,OAAO,UAAU,KAAA,IAAY,KAAA,UAAkB,MAAM,GAAG;IACxD,YAAY,OAAO;IACnB,QAAQ,WAAW,KAAA,IAAY,KAAA,KAAY,YAAW,OAAO,KAAK,OAAO;IACzE,OAAO,OAAO;IACd,OAAO,OAAO;GAGhB,CAAuF;EACzF;EAEA,MAAM,MAAM,SAAqC;GAC/C,IAAI,QAAQ,QAAQ,IAAI,SAAS,CAAC,EAAE,YAAY,MAAM,aACpD,OAAO,SAAS,KAAK,EAAE,OAAO,YAAY,GAAG,EAAE,QAAQ,IAAI,CAAC;GAE9D,IAAI;GACJ,IAAI;IACF,QAAQ,OAAO,QAAQ,YAAA,CAAa;GACtC,SAAS,OAAO;IAEd,QAAQ,MAAM,4CAA4C,KAAK;IAC/D,OAAO,SAAS,KAAK,EAAE,OAAO,iBAAiB,GAAG,EAAE,QAAQ,IAAI,CAAC;GACnE;GACA,MAAM,CAAC,QAAQ,UAAU;GACzB,MAAM,WAAW,MAAM,KAAK,KAAK,OAAO;GACxC,IAAI,OAAO,UAAU,QAAQ,GAAG,OAAO,SAAS;GAChD,MAAM,EAAE,OAAO,YAAY,SAAS;GACpC,IAAI;IACF,OAAO,OAAO;IACd,MAAM;KACJ,GAAG,aAAa,MAAM;KACtB,YAAY,MAAM,WAAW,UAAU,QAAQ,MAAM,MAAM;IAC7D,CAAC;IACD,OAAO,IAAI,SAAS,MAAM;KACxB,QAAQ;KAGR,WAAW;IACb,CAAiB;GACnB,SAAS,OAAO;IACd,QAAQ,MAAM,4CAA4C,KAAK;IAC/D,QAAQ;IACR,OAAO,SAAS,KAAK,EAAE,OAAO,iBAAiB,GAAG,EAAE,QAAQ,IAAI,CAAC;GACnE;EACF;CACF;AACF"}
|