foldkit-sync 0.11.1 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +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/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 +5 -5
- 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;;;;;;;;qBAsCW,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 }) | 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,WAIA;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"}
|
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
import { b as sequence, c as serveSocket } from "./transport-DiKXy5zx.mjs";
|
|
2
|
+
import { Cause, Context, Duration, Effect, Exit, Fiber, Layer, Match, Option, Result, Schema, Scope, Stream } from "effect";
|
|
3
|
+
import { Cursor, DocumentId, Sequence } from "foldkit-durable/core";
|
|
4
|
+
//#region src/revalidate.ts
|
|
5
|
+
/** Shared by `documentHost` and `defineDocumentHost`; not part of either entry's API. */
|
|
6
|
+
/** Refuses a revalidation interval that would ask the session store without pause. */
|
|
7
|
+
const checkRevalidate = (revalidate, who) => {
|
|
8
|
+
if (revalidate !== void 0 && !Duration.isGreaterThan(Duration.fromInputUnsafe(revalidate.every), Duration.zero)) throw new Error(`${who}: revalidate.every must be longer than zero`);
|
|
9
|
+
};
|
|
10
|
+
//#endregion
|
|
11
|
+
//#region src/journal.ts
|
|
12
|
+
/**
|
|
13
|
+
* `foldkit-sync/journal` — the server's side of an exchange, over a
|
|
14
|
+
* `foldkit-durable` journal. Every Sync server needs the same loop: append
|
|
15
|
+
* what a replica sends, refuse what cannot be taken, and read back what
|
|
16
|
+
* committed since the replica's cursor. Written by hand three times, it
|
|
17
|
+
* failed the same way: an operation that did not decode failed the whole
|
|
18
|
+
* exchange, so the replica sent it again on every one and the edits behind it
|
|
19
|
+
* never went. Here, refused operations are reported by id, and the replica
|
|
20
|
+
* drops them.
|
|
21
|
+
*/
|
|
22
|
+
/** The id an entry names, read without trusting the rest of it. */
|
|
23
|
+
const idOf = (input) => Option.map(Schema.decodeUnknownOption(Schema.Struct({ opId: Schema.String }))(input), ({ opId }) => opId);
|
|
24
|
+
/**
|
|
25
|
+
* One replica's exchanges with the journal, as the replica's transport
|
|
26
|
+
* speaks them (`Sync.transport.fromPromise`, or behind
|
|
27
|
+
* `Sync.transport.serve` on a socket). Each pending operation is appended in
|
|
28
|
+
* order, and acknowledged once committed, or already committed. One is
|
|
29
|
+
* rejected by its id when its message does not decode, it names another
|
|
30
|
+
* document, or the journal refuses it (`authorize`, `validate`); the replica
|
|
31
|
+
* drops it rather than send it again. Only an entry with no id at all, a
|
|
32
|
+
* cursor ahead of the journal's, a connection `opens` refuses, or `admit` or
|
|
33
|
+
* the journal failing fails the exchange. The reply carries what committed
|
|
34
|
+
* after the replica's cursor, a checkpoint when that history was compacted,
|
|
35
|
+
* and the journal's epoch, so a replica of a reset journal starts again.
|
|
36
|
+
*/
|
|
37
|
+
const journalExchange = (options) => {
|
|
38
|
+
const { sync, journal, principal } = options;
|
|
39
|
+
const limit = options.limit ?? 500;
|
|
40
|
+
const key = DocumentId.make(sync.documentId);
|
|
41
|
+
const snapshot = sync.journalContract().snapshot;
|
|
42
|
+
const operationOf = Option.liftThrowable((input) => sync.codec.operationFrom(input, sync.documentId));
|
|
43
|
+
const committedOf = (committed) => sync.codec.committedFrom({
|
|
44
|
+
...committed.operation,
|
|
45
|
+
serverSequence: committed.sequence,
|
|
46
|
+
actorId: committed.actorId
|
|
47
|
+
}, sync.documentId);
|
|
48
|
+
const exchange = (cursor, pending, seen) => Effect.gen(function* () {
|
|
49
|
+
if (options.opens !== void 0 && !(yield* options.opens)) return yield* Effect.fail(/* @__PURE__ */ new Error("This connection may not open the document"));
|
|
50
|
+
const epoch = yield* journal.epoch(key);
|
|
51
|
+
const from = seen !== void 0 && seen !== epoch ? 0 : cursor;
|
|
52
|
+
const at = yield* journal.cursor(key);
|
|
53
|
+
if (from > at) return yield* Effect.fail(/* @__PURE__ */ new Error(`Cursor ${cursor} is ahead of the server's ${at}`));
|
|
54
|
+
const rejected = [];
|
|
55
|
+
const reasons = [];
|
|
56
|
+
const reject = (opId, reason) => {
|
|
57
|
+
rejected.push(opId);
|
|
58
|
+
reasons.push({
|
|
59
|
+
opId,
|
|
60
|
+
reason
|
|
61
|
+
});
|
|
62
|
+
};
|
|
63
|
+
const acknowledged = [];
|
|
64
|
+
for (const input of pending) {
|
|
65
|
+
const decoded = operationOf(input);
|
|
66
|
+
if (Option.isNone(decoded)) {
|
|
67
|
+
const id = idOf(input);
|
|
68
|
+
if (Option.isNone(id)) return yield* Effect.fail(/* @__PURE__ */ new Error("A pending entry names no operation"));
|
|
69
|
+
reject(id.value, "Not an operation this server accepts");
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
const operation = decoded.value;
|
|
73
|
+
const admitted = options.admit === void 0 ? true : options.admit(operation);
|
|
74
|
+
const decision = Effect.isEffect(admitted) ? yield* admitted : admitted;
|
|
75
|
+
if (decision !== true) {
|
|
76
|
+
reject(operation.opId, decision === false ? "This connection may not make changes" : decision.reason);
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
yield* journal.append(key, operation, principal).pipe(Effect.map((appended) => acknowledged.push(Match.valueTags(appended, {
|
|
80
|
+
Committed: ({ committed }) => committed.operation.opId,
|
|
81
|
+
AlreadyCommitted: ({ opId }) => opId
|
|
82
|
+
}))), Effect.catchTags({
|
|
83
|
+
OperationRejectedError: (error) => Effect.sync(() => reject(error.opId, error.reason ?? "Refused by the server")),
|
|
84
|
+
InvalidOperationError: () => Effect.sync(() => reject(operation.opId, "Not a valid operation")),
|
|
85
|
+
IdentityConflictError: () => Effect.sync(() => reject(operation.opId, "Its id was already used for another"))
|
|
86
|
+
}));
|
|
87
|
+
}
|
|
88
|
+
if (options.settle !== void 0) yield* options.settle;
|
|
89
|
+
const read = yield* journal.read(key, Cursor.make(from), { limit }).pipe(Effect.map((rows) => Option.some(rows)), Effect.catchTag("CompactedCursorError", () => Effect.succeed(Option.none())));
|
|
90
|
+
return yield* Option.match(read, {
|
|
91
|
+
onSome: (rows) => Effect.succeed({
|
|
92
|
+
operations: rows.map(committedOf),
|
|
93
|
+
rejected,
|
|
94
|
+
reasons,
|
|
95
|
+
acknowledged,
|
|
96
|
+
more: rows.length === limit,
|
|
97
|
+
epoch
|
|
98
|
+
}),
|
|
99
|
+
onNone: () => Effect.map(journal.load(key), (loaded) => ({
|
|
100
|
+
operations: [],
|
|
101
|
+
rejected,
|
|
102
|
+
reasons,
|
|
103
|
+
acknowledged,
|
|
104
|
+
checkpoint: {
|
|
105
|
+
cursor: loaded.cursor,
|
|
106
|
+
model: snapshot.encode(loaded.snapshot)
|
|
107
|
+
},
|
|
108
|
+
epoch
|
|
109
|
+
}))
|
|
110
|
+
});
|
|
111
|
+
});
|
|
112
|
+
return { exchange: (cursor, pending, seen) => Effect.runPromise(exchange(cursor, pending, seen)) };
|
|
113
|
+
};
|
|
114
|
+
/**
|
|
115
|
+
* Calls `listener` each time the document commits, for `Sync.transport.serve`'s
|
|
116
|
+
* `changes`, so a socket wakes its replica to exchange. Returns the unsubscribe.
|
|
117
|
+
*/
|
|
118
|
+
const journalChanges = (journal, documentId) => (listener) => {
|
|
119
|
+
const fiber = Effect.runFork(Stream.runForEach(Stream.filter(journal.subscribe, (key) => key === documentId), () => Effect.sync(listener)));
|
|
120
|
+
return () => Effect.runSync(Fiber.interrupt(fiber));
|
|
121
|
+
};
|
|
122
|
+
/**
|
|
123
|
+
* Serves one accepted socket over the journal: each exchange frame answered by
|
|
124
|
+
* `journalExchange` with the connection's principal, and a notice sent after
|
|
125
|
+
* each commit, so the replica hears of others' edits. Returns the stop.
|
|
126
|
+
*/
|
|
127
|
+
const serveJournal = (socket, options) => {
|
|
128
|
+
const client = journalExchange(options);
|
|
129
|
+
const notices = journalChanges(options.journal, options.sync.documentId);
|
|
130
|
+
const { opens } = options;
|
|
131
|
+
return serveSocket(socket, {
|
|
132
|
+
exchange: (cursor, pending, epoch) => client.exchange(sequence(cursor), pending, epoch),
|
|
133
|
+
changes: opens === void 0 ? notices : (listener) => notices(() => void Effect.runPromise(opens).then((open) => {
|
|
134
|
+
if (open) listener();
|
|
135
|
+
}, () => {}))
|
|
136
|
+
});
|
|
137
|
+
};
|
|
138
|
+
/**
|
|
139
|
+
* The table holds revisions past every sequence the journal has: it outlived
|
|
140
|
+
* a reset of the journal, or was built from another. New edits commit at
|
|
141
|
+
* sequences the table already passed, so `apply` would skip every one and
|
|
142
|
+
* the replicas count each absorbed: rebuild the table with the journal.
|
|
143
|
+
*/
|
|
144
|
+
var TableAheadOfJournalError = class extends Schema.TaggedError()("SyncTableAheadOfJournalError", {
|
|
145
|
+
table: Schema.Number,
|
|
146
|
+
journal: Schema.Number
|
|
147
|
+
}) {
|
|
148
|
+
get message() {
|
|
149
|
+
return `The table holds revision ${this.table}, past the journal's ${this.journal}: rebuild the table with the journal`;
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
/**
|
|
153
|
+
* The table as the journal's read model: `settle` applies each committed
|
|
154
|
+
* edit through `apply`, as a recovery intent, and `absorb` records in the
|
|
155
|
+
* journal what the table holds and compacts the log behind it. For
|
|
156
|
+
* `journalExchange`'s `settle`, and a clock that absorbs.
|
|
157
|
+
*
|
|
158
|
+
* Recovery starts at the journal's floor, where compaction left it, so a
|
|
159
|
+
* server restarted over a journal that outlived it does not ask for history
|
|
160
|
+
* that is gone. Intents are keyed by the journal's epoch as well as the
|
|
161
|
+
* operation, so after a reset an operation sent again is applied again, not
|
|
162
|
+
* taken as already run.
|
|
163
|
+
*/
|
|
164
|
+
const editsJournal = (options) => {
|
|
165
|
+
const { journal } = options;
|
|
166
|
+
const key = DocumentId.make(options.documentId);
|
|
167
|
+
let applied = Option.none();
|
|
168
|
+
const intents = (epoch) => (operation) => Option.match(options.editsOf(operation), {
|
|
169
|
+
onNone: () => [],
|
|
170
|
+
onSome: ({ changes, at }) => changes.map((change, index) => ({
|
|
171
|
+
key: `${epoch}:${operation.opId}:${index}`,
|
|
172
|
+
run: Option.match(at, {
|
|
173
|
+
onNone: () => Effect.fail(/* @__PURE__ */ new Error(`Edit ${operation.opId} committed without its sequence`)),
|
|
174
|
+
onSome: (sequence) => options.apply(change, sequence)
|
|
175
|
+
})
|
|
176
|
+
}))
|
|
177
|
+
});
|
|
178
|
+
const checked = Effect.gen(function* () {
|
|
179
|
+
const table = yield* options.tableRevision;
|
|
180
|
+
const at = yield* journal.cursor(key);
|
|
181
|
+
if (table > at) return yield* new TableAheadOfJournalError({
|
|
182
|
+
table,
|
|
183
|
+
journal: at
|
|
184
|
+
});
|
|
185
|
+
return Cursor.make(yield* journal.floor(key));
|
|
186
|
+
});
|
|
187
|
+
return {
|
|
188
|
+
settle: Effect.gen(function* () {
|
|
189
|
+
const epoch = yield* journal.epoch(key);
|
|
190
|
+
const from = yield* Option.match(Option.filter(applied, (previous) => previous.epoch === epoch), {
|
|
191
|
+
onSome: ({ cursor }) => Effect.succeed(cursor),
|
|
192
|
+
onNone: () => checked
|
|
193
|
+
});
|
|
194
|
+
const cursor = yield* journal.recover({
|
|
195
|
+
key,
|
|
196
|
+
from,
|
|
197
|
+
intents: intents(epoch)
|
|
198
|
+
});
|
|
199
|
+
applied = Option.some({
|
|
200
|
+
cursor,
|
|
201
|
+
epoch
|
|
202
|
+
});
|
|
203
|
+
}),
|
|
204
|
+
absorb: Effect.gen(function* () {
|
|
205
|
+
const epoch = yield* journal.epoch(key);
|
|
206
|
+
const known = Option.filter(applied, (previous) => previous.epoch === epoch);
|
|
207
|
+
if (Option.isNone(known)) return;
|
|
208
|
+
const through = known.value.cursor;
|
|
209
|
+
const { snapshot, cursor } = yield* journal.load(key);
|
|
210
|
+
if (!options.holdsThrough(snapshot, through)) return;
|
|
211
|
+
yield* journal.append(key, options.absorbed(through, cursor), options.server);
|
|
212
|
+
yield* journal.compact(key, Sequence.make(through));
|
|
213
|
+
})
|
|
214
|
+
};
|
|
215
|
+
};
|
|
216
|
+
/** What a revalidation that found another principal fails with. */
|
|
217
|
+
const changed = Symbol("changed");
|
|
218
|
+
const internalError = () => Response.json({ error: "Internal error" }, { status: 500 });
|
|
219
|
+
/**
|
|
220
|
+
* One document's Sync host, for any runtime that upgrades a request to a
|
|
221
|
+
* socket: a Durable Object (`foldkit-sync/do`), or Node's `ws`. Each
|
|
222
|
+
* upgrade is answered before the socket opens: refused (`Result.fail`, a
|
|
223
|
+
* 401 for a principal refused, a 500 for a resolver or journal that broke),
|
|
224
|
+
* or accepted (`Accepted`): `serve` the socket once the runtime has opened
|
|
225
|
+
* it, against the journal, as the principal it resolved, asking again while
|
|
226
|
+
* it is open when `revalidate` says to; or `abandon` it when the runtime
|
|
227
|
+
* never will, which releases what the upgrade built.
|
|
228
|
+
*/
|
|
229
|
+
const documentHost = (options) => {
|
|
230
|
+
checkRevalidate(options.revalidate, "documentHost");
|
|
231
|
+
return async (request) => {
|
|
232
|
+
const scope = Effect.runSync(Scope.make());
|
|
233
|
+
const release = () => void Effect.runFork(Scope.close(scope, Exit.void));
|
|
234
|
+
const refuse = (response) => {
|
|
235
|
+
release();
|
|
236
|
+
return Result.fail(response);
|
|
237
|
+
};
|
|
238
|
+
const { layer } = options;
|
|
239
|
+
const ask = Effect.suspend(() => options.resolvePrincipal(request));
|
|
240
|
+
const opened = await Effect.runPromise(Effect.gen(function* () {
|
|
241
|
+
const services = layer === void 0 ? Context.empty() : yield* Layer.buildWithScope(layer(), scope);
|
|
242
|
+
const resolve = Effect.provide(ask, services);
|
|
243
|
+
return {
|
|
244
|
+
resolve,
|
|
245
|
+
resolved: yield* Effect.result(resolve)
|
|
246
|
+
};
|
|
247
|
+
})).catch(() => void 0);
|
|
248
|
+
if (opened === void 0) return refuse(internalError());
|
|
249
|
+
const { resolve, resolved } = opened;
|
|
250
|
+
if (Result.isFailure(resolved)) return refuse(Response.json({ error: resolved.failure.message }, { status: 401 }));
|
|
251
|
+
const principal = resolved.success;
|
|
252
|
+
const journal = await Promise.resolve().then(options.journal).catch(() => void 0);
|
|
253
|
+
if (journal === void 0) return refuse(internalError());
|
|
254
|
+
let exchange;
|
|
255
|
+
try {
|
|
256
|
+
const { admit, settle, opens } = options;
|
|
257
|
+
exchange = {
|
|
258
|
+
sync: options.sync,
|
|
259
|
+
journal,
|
|
260
|
+
principal,
|
|
261
|
+
...settle === void 0 ? {} : { settle: settle(journal) },
|
|
262
|
+
...opens === void 0 ? {} : { opens: opens(principal) },
|
|
263
|
+
...admit === void 0 ? {} : { admit: (operation) => admit(principal, operation) }
|
|
264
|
+
};
|
|
265
|
+
} catch (error) {
|
|
266
|
+
console.error("[foldkit-sync] answering an upgrade broke:", error);
|
|
267
|
+
return refuse(internalError());
|
|
268
|
+
}
|
|
269
|
+
return Result.succeed({
|
|
270
|
+
abandon: release,
|
|
271
|
+
serve: (socket) => {
|
|
272
|
+
const stop = serveJournal(socket, exchange);
|
|
273
|
+
const { revalidate } = options;
|
|
274
|
+
if (revalidate !== void 0) {
|
|
275
|
+
const { every, key } = revalidate;
|
|
276
|
+
const checking = Effect.sleep(every).pipe(Effect.andThen(resolve), Effect.flatMap((now) => key === void 0 || key(principal) === key(now) ? Effect.void : Effect.fail(changed)), Effect.forever, Effect.catchCause((cause) => Effect.sync(() => {
|
|
277
|
+
stop();
|
|
278
|
+
const [code, reason] = Option.match(Cause.findErrorOption(cause), {
|
|
279
|
+
onNone: () => [1011, "Internal error"],
|
|
280
|
+
onSome: (error) => error === changed ? [1012, "Who is asking changed"] : [4401, error.message]
|
|
281
|
+
});
|
|
282
|
+
try {
|
|
283
|
+
socket.closeWith(code, reason);
|
|
284
|
+
} catch {
|
|
285
|
+
socket.close();
|
|
286
|
+
} finally {
|
|
287
|
+
release();
|
|
288
|
+
}
|
|
289
|
+
})));
|
|
290
|
+
const fiber = Effect.runFork(checking);
|
|
291
|
+
socket.onClose(() => void Effect.runFork(Fiber.interrupt(fiber)));
|
|
292
|
+
}
|
|
293
|
+
socket.onClose(release);
|
|
294
|
+
}
|
|
295
|
+
});
|
|
296
|
+
};
|
|
297
|
+
};
|
|
298
|
+
//#endregion
|
|
299
|
+
export { journalExchange as a, journalChanges as i, documentHost as n, serveJournal as o, editsJournal as r, checkRevalidate as s, TableAheadOfJournalError as t };
|
|
300
|
+
|
|
301
|
+
//# sourceMappingURL=journal-BtYEDz0E.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"journal-BtYEDz0E.mjs","names":["JournalDocumentId"],"sources":["../src/revalidate.ts","../src/journal.ts"],"sourcesContent":["/** Shared by `documentHost` and `defineDocumentHost`; not part of either entry's API. */\nimport { Duration } from 'effect'\n\n/** Refuses a revalidation interval that would ask the session store without pause. */\nexport const checkRevalidate = (\n revalidate: { readonly every: Duration.Input } | undefined,\n who: string,\n): void => {\n if (\n revalidate !== undefined &&\n !Duration.isGreaterThan(Duration.fromInputUnsafe(revalidate.every), Duration.zero)\n )\n throw new Error(`${who}: revalidate.every must be longer than zero`)\n}\n","/**\n * `foldkit-sync/journal` — the server's side of an exchange, over a\n * `foldkit-durable` journal. Every Sync server needs the same loop: append\n * what a replica sends, refuse what cannot be taken, and read back what\n * committed since the replica's cursor. Written by hand three times, it\n * failed the same way: an operation that did not decode failed the whole\n * exchange, so the replica sent it again on every one and the edits behind it\n * never went. Here, refused operations are reported by id, and the replica\n * drops them.\n */\nimport {\n Cause,\n Context,\n Duration,\n Effect,\n Exit,\n Fiber,\n Layer,\n Match,\n Option,\n Result,\n Schema,\n Scope,\n Stream,\n} from 'effect'\nimport type { RemoteUnauthenticated } from 'foldkit-remote'\nimport {\n Cursor,\n DocumentId as JournalDocumentId,\n Sequence,\n type Committed,\n type Journal,\n} from 'foldkit-durable/core'\nimport { sequence } from './ids.js'\nimport type { AuthorizeDecision } from './make.js'\nimport type { Operation, Sync, TransportClient } from './sync.js'\nimport { checkRevalidate } from './revalidate.js'\nimport { serveSocket, type SocketLike } from './transport.js'\n\nexport interface JournalExchangeOptions<Message, Shared, Principal> {\n /** The document's contract: its codecs, and the snapshot a checkpoint encodes. */\n readonly sync: Sync<Message, Shared>\n /**\n * The journal made from `sync.journalContract()`, which orders and keeps the\n * document. One that takes any input, or only operations, is accepted.\n */\n readonly journal: Journal<Operation, Shared, Principal, Operation>\n /**\n * Who is exchanging, as the transport established it. The journal's\n * `authorize` reads it; a refused operation is reported as rejected.\n */\n readonly principal: 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`. It runs on\n * every exchange, so a write that failed is tried again on the next.\n */\n readonly settle?: Effect.Effect<void, unknown> | undefined\n /**\n * Whether the connection may open the document at all, to read it or to\n * change it: a principal outside its readers. Refused, every exchange fails,\n * and nothing is read or appended.\n */\n readonly opens?: Effect.Effect<boolean> | undefined\n /**\n * Whether an operation may be appended, decided before the journal sees it,\n * by what the transport established rather than by the document: a principal\n * that may only read, or a rule that reads the rows an edit names, which\n * cannot run under the journal's lock (`foldkit-guard/sync`). `true` admits;\n * a refusal is rejected by the operation's id, with its reason when it gives\n * one. One that fails fails the exchange, as the journal failing does. The\n * journal's own `authorize` is where a rule about the document goes.\n */\n readonly admit?:\n | ((operation: Operation) => AuthorizeDecision | Effect.Effect<AuthorizeDecision, unknown>)\n | undefined\n /** The most committed operations one reply carries; a replica further behind asks again. Default 500. */\n readonly limit?: number | undefined\n}\n\n/** The id an entry names, read without trusting the rest of it. */\nconst idOf = (input: unknown): Option.Option<string> =>\n Option.map(\n Schema.decodeUnknownOption(Schema.Struct({ opId: Schema.String }))(input),\n ({ opId }) => opId,\n )\n\n/**\n * One replica's exchanges with the journal, as the replica's transport\n * speaks them (`Sync.transport.fromPromise`, or behind\n * `Sync.transport.serve` on a socket). Each pending operation is appended in\n * order, and acknowledged once committed, or already committed. One is\n * rejected by its id when its message does not decode, it names another\n * document, or the journal refuses it (`authorize`, `validate`); the replica\n * drops it rather than send it again. Only an entry with no id at all, a\n * cursor ahead of the journal's, a connection `opens` refuses, or `admit` or\n * the journal failing fails the exchange. The reply carries what committed\n * after the replica's cursor, a checkpoint when that history was compacted,\n * and the journal's epoch, so a replica of a reset journal starts again.\n */\nexport const journalExchange = <Message, Shared, Principal>(\n options: JournalExchangeOptions<Message, Shared, Principal>,\n): TransportClient => {\n const { sync, journal, principal } = options\n const limit = options.limit ?? 500\n const key = JournalDocumentId.make(sync.documentId)\n const snapshot = sync.journalContract().snapshot\n const operationOf = Option.liftThrowable((input: unknown) =>\n sync.codec.operationFrom(input, sync.documentId),\n )\n const committedOf = (committed: Committed<Operation>) =>\n sync.codec.committedFrom(\n { ...committed.operation, serverSequence: committed.sequence, actorId: committed.actorId },\n sync.documentId,\n )\n\n const exchange = (cursor: number, pending: ReadonlyArray<unknown>, seen?: string) =>\n Effect.gen(function* () {\n if (options.opens !== undefined && !(yield* options.opens)) {\n return yield* Effect.fail(new Error('This connection may not open the document'))\n }\n // A replica that saw another epoch holds a cursor into history this journal\n // lacks (it was reset): it is answered from the start. Otherwise a cursor\n // past the journal's is refused before anything is appended, or the\n // operations would commit and their acknowledgements be lost.\n const epoch = yield* journal.epoch(key)\n const from = seen !== undefined && seen !== epoch ? 0 : cursor\n const at = yield* journal.cursor(key)\n if (from > at) {\n return yield* Effect.fail(new Error(`Cursor ${cursor} is ahead of the server's ${at}`))\n }\n const rejected: Array<string> = []\n const reasons: Array<{ readonly opId: string; readonly reason: string }> = []\n // Each reason is words for the person whose edit came back: a policy's own,\n // or a fixed sentence, never an error's message, which may carry internals.\n const reject = (opId: string, reason: string) => {\n rejected.push(opId)\n reasons.push({ opId, reason })\n }\n const acknowledged: Array<string> = []\n for (const input of pending) {\n const decoded = operationOf(input)\n if (Option.isNone(decoded)) {\n const id = idOf(input)\n if (Option.isNone(id))\n return yield* Effect.fail(new Error('A pending entry names no operation'))\n reject(id.value, 'Not an operation this server accepts')\n continue\n }\n const operation = decoded.value\n const admitted = options.admit === undefined ? true : options.admit(operation)\n const decision = Effect.isEffect(admitted) ? yield* admitted : admitted\n if (decision !== true) {\n reject(\n operation.opId,\n decision === false ? 'This connection may not make changes' : decision.reason,\n )\n continue\n }\n yield* journal.append(key, operation, principal).pipe(\n Effect.map(appended =>\n acknowledged.push(\n Match.valueTags(appended, {\n Committed: ({ committed }): string => committed.operation.opId,\n AlreadyCommitted: ({ opId }): string => opId,\n }),\n ),\n ),\n // A refusal, an operation the journal cannot apply, and an id reused for\n // other content fail the same way on every retry, so they are rejected; a\n // `JournalError` may not, so it still fails the exchange.\n Effect.catchTags({\n OperationRejectedError: error =>\n Effect.sync(() => reject(error.opId, error.reason ?? 'Refused by the server')),\n InvalidOperationError: () =>\n Effect.sync(() => reject(operation.opId, 'Not a valid operation')),\n IdentityConflictError: () =>\n Effect.sync(() => reject(operation.opId, 'Its id was already used for another')),\n }),\n )\n }\n if (options.settle !== undefined) yield* options.settle\n // A cursor below the compacted floor is answered with the snapshot; the\n // read decides that itself, so a compaction cannot slip in between.\n const read = yield* journal.read(key, Cursor.make(from), { limit }).pipe(\n Effect.map(rows => Option.some(rows)),\n Effect.catchTag('CompactedCursorError', () => Effect.succeed(Option.none())),\n )\n return yield* Option.match(read, {\n onSome: rows =>\n Effect.succeed({\n operations: rows.map(committedOf),\n rejected,\n reasons,\n acknowledged,\n more: rows.length === limit,\n epoch,\n }),\n onNone: () =>\n Effect.map(journal.load(key), loaded => ({\n operations: [],\n rejected,\n reasons,\n acknowledged,\n checkpoint: { cursor: loaded.cursor, model: snapshot.encode(loaded.snapshot) },\n epoch,\n })),\n })\n })\n\n return {\n exchange: (cursor, pending, seen) => Effect.runPromise(exchange(cursor, pending, seen)),\n }\n}\n\n/**\n * Calls `listener` each time the document commits, for `Sync.transport.serve`'s\n * `changes`, so a socket wakes its replica to exchange. Returns the unsubscribe.\n */\nexport const journalChanges =\n <Shared, Principal>(\n journal: Journal<Operation, Shared, Principal, Operation>,\n documentId: string,\n ): ((listener: () => void) => () => void) =>\n listener => {\n const fiber = Effect.runFork(\n Stream.runForEach(\n Stream.filter(journal.subscribe, key => key === documentId),\n () => Effect.sync(listener),\n ),\n )\n return () => Effect.runSync(Fiber.interrupt(fiber))\n }\n\n/**\n * Serves one accepted socket over the journal: each exchange frame answered by\n * `journalExchange` with the connection's principal, and a notice sent after\n * each commit, so the replica hears of others' edits. Returns the stop.\n */\nexport const serveJournal = <Message, Shared, Principal>(\n socket: SocketLike,\n options: JournalExchangeOptions<Message, Shared, Principal>,\n): (() => void) => {\n const client = journalExchange(options)\n const notices = journalChanges(options.journal, options.sync.documentId)\n const { opens } = options\n return serveSocket(socket, {\n exchange: (cursor, pending, epoch) => client.exchange(sequence(cursor), pending, epoch),\n // A connection that may not open the document is told nothing of its commits.\n changes:\n opens === undefined\n ? notices\n : listener =>\n notices(\n () =>\n void Effect.runPromise(opens).then(\n open => {\n if (open) listener()\n },\n () => {},\n ),\n ),\n })\n}\n\n/**\n * The table holds revisions past every sequence the journal has: it outlived\n * a reset of the journal, or was built from another. New edits commit at\n * sequences the table already passed, so `apply` would skip every one and\n * the replicas count each absorbed: rebuild the table with the journal.\n */\nexport class TableAheadOfJournalError extends Schema.TaggedError<TableAheadOfJournalError>()(\n 'SyncTableAheadOfJournalError',\n { table: Schema.Number, journal: Schema.Number },\n) {\n override get message(): string {\n return `The table holds revision ${this.table}, past the journal's ${this.journal}: rebuild the table with the journal`\n }\n}\n\nexport interface EditsJournalOptions<Shared, Principal, Change> {\n /** The document whose edits the table reads. */\n readonly documentId: string\n /** The journal the edits commit to. */\n readonly journal: Journal<Operation, Shared, Principal, Operation>\n /**\n * The cells an operation edits, with the sequence its stamp wrote in; none\n * for an operation that edits nothing. An edit committed without a sequence\n * is not this journal's: its intents fail rather than write revision 0.\n */\n readonly editsOf: (operation: Operation) => Option.Option<{\n readonly changes: ReadonlyArray<Change>\n readonly at: Option.Option<number>\n }>\n /**\n * Writes one committed change to the table, with the sequence it committed\n * at. It runs as a recovery intent, so it may run again after a crash: it\n * must never move a row back (`revision <= at`). A failure stops recovery\n * there, and the next settle tries it again.\n *\n * It cannot refuse an edit: the edit has committed. One naming a row the\n * table lacks is refused at commit instead, by the journal's `validate`,\n * so its sender is told; let through, it would change nothing and vanish\n * once absorbed.\n */\n readonly apply: (change: Change, at: number) => Effect.Effect<void, unknown>\n /**\n * The highest revision the table holds. Settling refuses to start while it\n * is past the journal's cursor (`TableAheadOfJournalError`), since every\n * edit would then be skipped and counted absorbed; it asks again on each\n * settle until the two agree.\n */\n readonly tableRevision: Effect.Effect<number, unknown>\n /** Whether the snapshot still keeps an edit committed through `through`: whether to absorb. */\n readonly holdsThrough: (snapshot: Shared, through: number) => boolean\n /**\n * The server's operation saying the table holds every edit through\n * `through`, sequenced from `cursor`, the journal's: the replicas drop those\n * edits on hearing it.\n */\n readonly absorbed: (through: number, cursor: number) => Operation\n /** Who the server commits `absorbed` as; the contract's `authorize` should let only it. */\n readonly server: Principal\n}\n\n/**\n * The table as the journal's read model: `settle` applies each committed\n * edit through `apply`, as a recovery intent, and `absorb` records in the\n * journal what the table holds and compacts the log behind it. For\n * `journalExchange`'s `settle`, and a clock that absorbs.\n *\n * Recovery starts at the journal's floor, where compaction left it, so a\n * server restarted over a journal that outlived it does not ask for history\n * that is gone. Intents are keyed by the journal's epoch as well as the\n * operation, so after a reset an operation sent again is applied again, not\n * taken as already run.\n */\nexport const editsJournal = <Shared, Principal, Change>(\n options: EditsJournalOptions<Shared, Principal, Change>,\n): {\n readonly settle: Effect.Effect<void, unknown>\n readonly absorb: Effect.Effect<void, unknown>\n} => {\n const { journal } = options\n const key = JournalDocumentId.make(options.documentId)\n // Operations at or before `applied.cursor` have every change in the table,\n // in `applied.epoch`: none until a settle has run in this process.\n let applied: Option.Option<{ readonly cursor: Cursor; readonly epoch: string }> = Option.none()\n const intents = (epoch: string) => (operation: Operation) =>\n Option.match(options.editsOf(operation), {\n onNone: () => [],\n onSome: ({ changes, at }) =>\n changes.map((change, index) => ({\n key: `${epoch}:${operation.opId}:${index}`,\n run: Option.match(at, {\n onNone: () =>\n Effect.fail(new Error(`Edit ${operation.opId} committed without its sequence`)),\n onSome: sequence => options.apply(change, sequence),\n }),\n })),\n })\n // Before the first recovery of an epoch: the table must not be past it.\n const checked = Effect.gen(function* () {\n const table = yield* options.tableRevision\n const at = yield* journal.cursor(key)\n if (table > at) return yield* new TableAheadOfJournalError({ table, journal: at })\n return Cursor.make(yield* journal.floor(key))\n })\n const settle = Effect.gen(function* () {\n const epoch = yield* journal.epoch(key)\n // A new epoch is a new history: recovery starts over at its floor.\n const from = yield* Option.match(\n Option.filter(applied, previous => previous.epoch === epoch),\n {\n onSome: ({ cursor }) => Effect.succeed(cursor),\n onNone: () => checked,\n },\n )\n const cursor = yield* journal.recover({ key, from, intents: intents(epoch) })\n applied = Option.some({ cursor, epoch })\n })\n // Two absorbs at once need no lock: both name the record by the journal's\n // cursor, so the second is the first's retry, answered from history.\n const absorb = Effect.gen(function* () {\n const epoch = yield* journal.epoch(key)\n const known = Option.filter(applied, previous => previous.epoch === epoch)\n if (Option.isNone(known)) return\n const through = known.value.cursor\n const { snapshot, cursor } = yield* journal.load(key)\n if (!options.holdsThrough(snapshot, through)) return\n yield* journal.append(key, options.absorbed(through, cursor), options.server)\n // What the log holds through `through` is in the table and gone from\n // the snapshot; a replica behind it is sent the snapshot instead.\n yield* journal.compact(key, Sequence.make(through))\n })\n return { settle, absorb }\n}\n\n/** A server socket a host serves on: Sync's socket, and a close with a code the replica reads. */\nexport interface HostSocket extends SocketLike {\n /** Closes with `code` and `reason`; one already closed stays so. */\n closeWith(code: number, reason: string): void\n}\n\n/**\n * An upgrade `documentHost` accepted. Exactly one of the two must follow:\n * `serve` once the runtime has opened the socket, or `abandon` when it never\n * will (the client left, the runtime refused the handshake), which releases\n * what the upgrade built.\n */\nexport interface Accepted {\n readonly serve: (socket: HostSocket) => void\n readonly abandon: () => void\n}\n\n/** What `documentHost` needs: one document, who may open it, and what they may do. */\nexport interface DocumentHostOptions<Message, Shared, Principal, RP = never> {\n readonly sync: Sync<Message, Shared>\n /**\n * The document's journal, asked on each upgrade a principal passed; keep\n * it open between calls. A rejection answers the upgrade with a 500.\n */\n readonly journal: () => Promise<Journal<Operation, Shared, Principal, Operation>>\n /**\n * Who is opening the socket, from the upgrade request. Fails with a\n * `RemoteUnauthenticated` (`RemoteServer.unauthenticated()`) to refuse it:\n * a 401 carrying its message. A defect is a 500 that says nothing of it.\n * A browser's `WebSocket` sends no header of the page's: `Origin` and the\n * cookie are what it has.\n */\n readonly resolvePrincipal: (\n request: Request,\n ) => Effect.Effect<Principal, RemoteUnauthenticated, RP>\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 serves the\n * principal it opened with until it closes, a revoked session included.\n */\n readonly revalidate?:\n | {\n readonly every: Duration.Input\n readonly key?: ((principal: Principal) => unknown) | undefined\n }\n | undefined\n /** After each exchange's appends, given the journal. See `journalExchange`'s `settle`. */\n readonly settle?:\n | ((journal: Journal<Operation, Shared, Principal, Operation>) => 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 /** Whether an operation from `principal` may be appended. See `journalExchange`'s `admit`. */\n readonly admit?:\n | ((\n principal: Principal,\n operation: Operation,\n ) => AuthorizeDecision | Effect.Effect<AuthorizeDecision, unknown>)\n | undefined\n}\n\n/** What a revalidation that found another principal fails with. */\nconst changed = Symbol('changed')\n\nconst internalError = () => Response.json({ error: 'Internal error' }, { status: 500 })\n\n/**\n * What the resolver needs (a session store), required exactly when it\n * needs something. Built per upgrade and kept until the socket closes,\n * since `revalidate` asks again while it is open; an upgrade it refuses\n * closes it at once.\n */\nexport type DocumentHostOptionsLayer<RP> = [RP] extends [never]\n ? { readonly layer?: undefined }\n : { readonly layer: () => Layer.Layer<RP> }\n\n/**\n * One document's Sync host, for any runtime that upgrades a request to a\n * socket: a Durable Object (`foldkit-sync/do`), or Node's `ws`. Each\n * upgrade is answered before the socket opens: refused (`Result.fail`, a\n * 401 for a principal refused, a 500 for a resolver or journal that broke),\n * or accepted (`Accepted`): `serve` the socket once the runtime has opened\n * it, against the journal, as the principal it resolved, asking again while\n * it is open when `revalidate` says to; or `abandon` it when the runtime\n * never will, which releases what the upgrade built.\n */\nexport const documentHost = <Message, Shared, Principal, RP = never>(\n options: DocumentHostOptions<Message, Shared, Principal, RP> & DocumentHostOptionsLayer<RP>,\n): ((request: Request) => Promise<Result.Result<Accepted, Response>>) => {\n checkRevalidate(options.revalidate, 'documentHost')\n return async request => {\n // The upgrade's services live as long as its socket.\n const scope = Effect.runSync(Scope.make())\n const release = (): void => void Effect.runFork(Scope.close(scope, Exit.void))\n const refuse = (response: Response) => {\n release()\n return Result.fail(response)\n }\n const { layer } = options\n // Suspended, so the resolver is called each time this runs (a resolver\n // may decide when called, not when its Effect runs), and one that throws\n // is a 500 like one that dies.\n const ask = Effect.suspend(() => options.resolvePrincipal(request))\n // The layer and the first answer in one run: either breaking is a 500.\n const opened = await Effect.runPromise(\n Effect.gen(function* () {\n const services: Context.Context<RP> =\n layer === undefined\n ? // No layer is a resolver that needs nothing (`DocumentHostLayer`).\n (Context.empty() as Context.Context<RP>)\n : yield* Layer.buildWithScope(layer(), scope)\n const resolve = Effect.provide(ask, services)\n return { resolve, resolved: yield* Effect.result(resolve) }\n }),\n ).catch(() => undefined)\n if (opened === undefined) return refuse(internalError())\n const { resolve, resolved } = opened\n if (Result.isFailure(resolved))\n return refuse(Response.json({ error: resolved.failure.message }, { status: 401 }))\n const principal = resolved.success\n // A throw is a rejection like any other: a 500.\n const journal = await Promise.resolve()\n .then(options.journal)\n .catch(() => undefined)\n if (journal === undefined) return refuse(internalError())\n // An application's `opens` or `settle` may throw: a 500, before any socket opens.\n let exchange: JournalExchangeOptions<Message, Shared, Principal>\n try {\n const { admit, settle, opens } = options\n exchange = {\n sync: options.sync,\n journal,\n principal,\n ...(settle === undefined ? {} : { settle: settle(journal) }),\n ...(opens === undefined ? {} : { opens: opens(principal) }),\n ...(admit === undefined\n ? {}\n : { admit: (operation: Operation) => admit(principal, operation) }),\n }\n } catch (error) {\n console.error('[foldkit-sync] answering an upgrade broke:', error)\n return refuse(internalError())\n }\n return Result.succeed({\n abandon: release,\n serve: socket => {\n const stop = serveJournal(socket, exchange)\n const { revalidate } = options\n if (revalidate !== undefined) {\n const { every, key } = revalidate\n const checking = Effect.sleep(every).pipe(\n Effect.andThen(resolve),\n Effect.flatMap(now =>\n key === undefined || key(principal) === key(now) ? Effect.void : Effect.fail(changed),\n ),\n Effect.forever,\n Effect.catchCause(cause =>\n Effect.sync(() => {\n // Before closing: a socket may fire its own close only on the\n // replica's reply, and frames in flight until then would\n // still be appended as the principal just refused.\n stop()\n const [code, reason] = Option.match(Cause.findErrorOption(cause), {\n // A defect: this side broke, and the replica learns that it did.\n onNone: () => [1011, 'Internal error'] as const,\n onSome: error =>\n error === changed\n ? ([1012, 'Who is asking changed'] as const)\n : ([4401, error.message] as const),\n })\n try {\n socket.closeWith(code, reason)\n } catch {\n // A reason the platform refuses (past 123 bytes): the code alone.\n socket.close()\n } finally {\n release()\n }\n }),\n ),\n )\n const fiber = Effect.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AAQ,OAAO,GACtB,OAAO,SAAQ,QACb,QAAQ,KAAA,KAAa,IAAI,SAAS,MAAM,IAAI,GAAG,IAAI,OAAO,OAAO,OAAO,KAAK,OAAO,CACtF,GACA,OAAO,SACP,OAAO,YAAW,UAChB,OAAO,WAAW;MAIhB,KAAK;MACL,MAAM,CAAC,MAAM,UAAU,OAAO,MAAM,MAAM,gBAAgB,KAAK,GAAG;OAEhE,cAAc,CAAC,MAAM,gBAAgB;OACrC,SAAQ,UACN,UAAU,UACL,CAAC,MAAM,uBAAuB,IAC9B,CAAC,MAAM,MAAM,OAAO;MAC7B,CAAC;MACD,IAAI;OACF,OAAO,UAAU,MAAM,MAAM;MAC/B,QAAQ;OAEN,OAAO,MAAM;MACf,UAAU;OACR,QAAQ;MACV;KACF,CAAC,CACH,CACF;KACA,MAAM,QAAQ,OAAO,QAAQ,QAAQ;KACrC,OAAO,cAAc,KAAK,OAAO,QAAQ,MAAM,UAAU,KAAK,CAAC,CAAC;IAClE;IACA,OAAO,QAAQ,OAAO;GACxB;EACF,CAAC;CACH;AACF"}
|
package/dist/journal.d.mts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { E as TransportClient, M as SocketLike, n as AuthorizeDecision, v as Operation, w as Sync } from "./make-CFOcLcQ1.mjs";
|
|
2
|
-
import { Effect, Option, Schema } from "effect";
|
|
2
|
+
import { Cause, Duration, Effect, Layer, Option, Result, Schema } from "effect";
|
|
3
3
|
import { Journal } from "foldkit-durable/core";
|
|
4
|
+
import { RemoteUnauthenticated } from "foldkit-remote";
|
|
4
5
|
//#region src/journal.d.ts
|
|
5
6
|
export interface JournalExchangeOptions<Message, Shared, Principal> {
|
|
6
7
|
/** The document's contract: its codecs, and the snapshot a checkpoint encodes. */
|
|
@@ -68,7 +69,7 @@ export declare const serveJournal: <Message, Shared, Principal>(socket: SocketLi
|
|
|
68
69
|
declare const TableAheadOfJournalError_base: Schema.Class<TableAheadOfJournalError, Schema.TaggedStruct<"SyncTableAheadOfJournalError", {
|
|
69
70
|
readonly table: Schema.Number;
|
|
70
71
|
readonly journal: Schema.Number;
|
|
71
|
-
}>,
|
|
72
|
+
}>, Cause.YieldableError>;
|
|
72
73
|
/**
|
|
73
74
|
* The table holds revisions past every sequence the journal has: it outlived
|
|
74
75
|
* a reset of the journal, or was built from another. New edits commit at
|
|
@@ -138,6 +139,78 @@ export declare const editsJournal: <Shared, Principal, Change>(options: EditsJou
|
|
|
138
139
|
readonly settle: Effect.Effect<void, unknown>;
|
|
139
140
|
readonly absorb: Effect.Effect<void, unknown>;
|
|
140
141
|
};
|
|
142
|
+
/** A server socket a host serves on: Sync's socket, and a close with a code the replica reads. */
|
|
143
|
+
export interface HostSocket extends SocketLike {
|
|
144
|
+
/** Closes with `code` and `reason`; one already closed stays so. */
|
|
145
|
+
closeWith(code: number, reason: string): void;
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* An upgrade `documentHost` accepted. Exactly one of the two must follow:
|
|
149
|
+
* `serve` once the runtime has opened the socket, or `abandon` when it never
|
|
150
|
+
* will (the client left, the runtime refused the handshake), which releases
|
|
151
|
+
* what the upgrade built.
|
|
152
|
+
*/
|
|
153
|
+
export interface Accepted {
|
|
154
|
+
readonly serve: (socket: HostSocket) => void;
|
|
155
|
+
readonly abandon: () => void;
|
|
156
|
+
}
|
|
157
|
+
/** What `documentHost` needs: one document, who may open it, and what they may do. */
|
|
158
|
+
export interface DocumentHostOptions<Message, Shared, Principal, RP = never> {
|
|
159
|
+
readonly sync: Sync<Message, Shared>;
|
|
160
|
+
/**
|
|
161
|
+
* The document's journal, asked on each upgrade a principal passed; keep
|
|
162
|
+
* it open between calls. A rejection answers the upgrade with a 500.
|
|
163
|
+
*/
|
|
164
|
+
readonly journal: () => Promise<Journal<Operation, Shared, Principal, Operation>>;
|
|
165
|
+
/**
|
|
166
|
+
* Who is opening the socket, from the upgrade request. Fails with a
|
|
167
|
+
* `RemoteUnauthenticated` (`RemoteServer.unauthenticated()`) to refuse it:
|
|
168
|
+
* a 401 carrying its message. A defect is a 500 that says nothing of it.
|
|
169
|
+
* A browser's `WebSocket` sends no header of the page's: `Origin` and the
|
|
170
|
+
* cookie are what it has.
|
|
171
|
+
*/
|
|
172
|
+
readonly resolvePrincipal: (request: Request) => Effect.Effect<Principal, RemoteUnauthenticated, RP>;
|
|
173
|
+
/**
|
|
174
|
+
* Asks `resolvePrincipal` again, of the upgrade request, every `every`
|
|
175
|
+
* while the socket is open: a refusal closes it with 4401, and a principal
|
|
176
|
+
* whose `key` differs from the one it opened with (`Policy.keyOf`) closes
|
|
177
|
+
* it with 1012, which the replica reconnects after, as the new principal;
|
|
178
|
+
* without `key` only a refusal closes it. Without it a socket serves the
|
|
179
|
+
* principal it opened with until it closes, a revoked session included.
|
|
180
|
+
*/
|
|
181
|
+
readonly revalidate?: {
|
|
182
|
+
readonly every: Duration.Input;
|
|
183
|
+
readonly key?: ((principal: Principal) => unknown) | undefined;
|
|
184
|
+
} | undefined;
|
|
185
|
+
/** After each exchange's appends, given the journal. See `journalExchange`'s `settle`. */
|
|
186
|
+
readonly settle?: ((journal: Journal<Operation, Shared, Principal, Operation>) => Effect.Effect<void, unknown>) | undefined;
|
|
187
|
+
/** Whether `principal` may open the document. See `journalExchange`'s `opens`. */
|
|
188
|
+
readonly opens?: ((principal: Principal) => Effect.Effect<boolean>) | undefined;
|
|
189
|
+
/** Whether an operation from `principal` may be appended. See `journalExchange`'s `admit`. */
|
|
190
|
+
readonly admit?: ((principal: Principal, operation: Operation) => AuthorizeDecision | Effect.Effect<AuthorizeDecision, unknown>) | undefined;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* What the resolver needs (a session store), required exactly when it
|
|
194
|
+
* needs something. Built per upgrade and kept until the socket closes,
|
|
195
|
+
* since `revalidate` asks again while it is open; an upgrade it refuses
|
|
196
|
+
* closes it at once.
|
|
197
|
+
*/
|
|
198
|
+
export type DocumentHostOptionsLayer<RP> = [RP] extends [never] ? {
|
|
199
|
+
readonly layer?: undefined;
|
|
200
|
+
} : {
|
|
201
|
+
readonly layer: () => Layer.Layer<RP>;
|
|
202
|
+
};
|
|
203
|
+
/**
|
|
204
|
+
* One document's Sync host, for any runtime that upgrades a request to a
|
|
205
|
+
* socket: a Durable Object (`foldkit-sync/do`), or Node's `ws`. Each
|
|
206
|
+
* upgrade is answered before the socket opens: refused (`Result.fail`, a
|
|
207
|
+
* 401 for a principal refused, a 500 for a resolver or journal that broke),
|
|
208
|
+
* or accepted (`Accepted`): `serve` the socket once the runtime has opened
|
|
209
|
+
* it, against the journal, as the principal it resolved, asking again while
|
|
210
|
+
* it is open when `revalidate` says to; or `abandon` it when the runtime
|
|
211
|
+
* never will, which releases what the upgrade built.
|
|
212
|
+
*/
|
|
213
|
+
export declare const documentHost: <Message, Shared, Principal, RP = never>(options: DocumentHostOptions<Message, Shared, Principal, RP> & DocumentHostOptionsLayer<RP>) => ((request: Request) => Promise<Result.Result<Accepted, Response>>);
|
|
141
214
|
//#endregion
|
|
142
215
|
export {};
|
|
143
216
|
//# sourceMappingURL=journal.d.mts.map
|
package/dist/journal.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"journal.d.mts","names":[],"sources":["../src/journal.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"journal.d.mts","names":[],"sources":["../src/journal.ts"],"mappings":";;;;;iBAuCiB,uBAAuB,SAAS,QAAQ;;WAE9C,MAAM,KAAK,SAAS;;;;;WAKpB,SAAS,QAAQ,WAAW,QAAQ,WAAW;;;;;WAK/C,WAAW;;;;;;WAMX,SAAS,OAAO;;;;;;WAMhB,QAAQ,OAAO;;;;;;;;;;WAUf,UACH,WAAW,cAAc,oBAAoB,OAAO,OAAO;;WAGxD;;;;;;;;;;;;;;;qBAuBE,kBAAmB,SAAS,QAAQ,WAAS,SAC/C,uBAAuB,SAAS,QAAQ,eAChD;;;;;qBAqHU,iBACV,QAAQ,WAAS,SACP,QAAQ,WAAW,QAA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
package/dist/journal.mjs
CHANGED
|
@@ -1,212 +1 @@
|
|
|
1
|
-
|
|
2
|
-
import { Effect, Fiber, Match, Option, Schema, Stream } from "effect";
|
|
3
|
-
import { Cursor, DocumentId, Sequence } from "foldkit-durable/core";
|
|
4
|
-
//#region src/journal.ts
|
|
5
|
-
/**
|
|
6
|
-
* `foldkit-sync/journal` — the server's side of an exchange, over a
|
|
7
|
-
* `foldkit-durable` journal. Every Sync server needs the same loop: append
|
|
8
|
-
* what a replica sends, refuse what cannot be taken, and read back what
|
|
9
|
-
* committed since the replica's cursor. Written by hand three times, it
|
|
10
|
-
* failed the same way: an operation that did not decode failed the whole
|
|
11
|
-
* exchange, so the replica sent it again on every one and the edits behind it
|
|
12
|
-
* never went. Here, refused operations are reported by id, and the replica
|
|
13
|
-
* drops them.
|
|
14
|
-
*/
|
|
15
|
-
/** The id an entry names, read without trusting the rest of it. */
|
|
16
|
-
const idOf = (input) => Option.map(Schema.decodeUnknownOption(Schema.Struct({ opId: Schema.String }))(input), ({ opId }) => opId);
|
|
17
|
-
/**
|
|
18
|
-
* One replica's exchanges with the journal, as the replica's transport
|
|
19
|
-
* speaks them (`Sync.transport.fromPromise`, or behind
|
|
20
|
-
* `Sync.transport.serve` on a socket). Each pending operation is appended in
|
|
21
|
-
* order, and acknowledged once committed, or already committed. One is
|
|
22
|
-
* rejected by its id when its message does not decode, it names another
|
|
23
|
-
* document, or the journal refuses it (`authorize`, `validate`); the replica
|
|
24
|
-
* drops it rather than send it again. Only an entry with no id at all, a
|
|
25
|
-
* cursor ahead of the journal's, a connection `opens` refuses, or `admit` or
|
|
26
|
-
* the journal failing fails the exchange. The reply carries what committed
|
|
27
|
-
* after the replica's cursor, a checkpoint when that history was compacted,
|
|
28
|
-
* and the journal's epoch, so a replica of a reset journal starts again.
|
|
29
|
-
*/
|
|
30
|
-
const journalExchange = (options) => {
|
|
31
|
-
const { sync, journal, principal } = options;
|
|
32
|
-
const limit = options.limit ?? 500;
|
|
33
|
-
const key = DocumentId.make(sync.documentId);
|
|
34
|
-
const snapshot = sync.journalContract().snapshot;
|
|
35
|
-
const operationOf = Option.liftThrowable((input) => sync.codec.operationFrom(input, sync.documentId));
|
|
36
|
-
const committedOf = (committed) => sync.codec.committedFrom({
|
|
37
|
-
...committed.operation,
|
|
38
|
-
serverSequence: committed.sequence,
|
|
39
|
-
actorId: committed.actorId
|
|
40
|
-
}, sync.documentId);
|
|
41
|
-
const exchange = (cursor, pending, seen) => Effect.gen(function* () {
|
|
42
|
-
if (options.opens !== void 0 && !(yield* options.opens)) return yield* Effect.fail(/* @__PURE__ */ new Error("This connection may not open the document"));
|
|
43
|
-
const epoch = yield* journal.epoch(key);
|
|
44
|
-
const from = seen !== void 0 && seen !== epoch ? 0 : cursor;
|
|
45
|
-
const at = yield* journal.cursor(key);
|
|
46
|
-
if (from > at) return yield* Effect.fail(/* @__PURE__ */ new Error(`Cursor ${cursor} is ahead of the server's ${at}`));
|
|
47
|
-
const rejected = [];
|
|
48
|
-
const reasons = [];
|
|
49
|
-
const reject = (opId, reason) => {
|
|
50
|
-
rejected.push(opId);
|
|
51
|
-
reasons.push({
|
|
52
|
-
opId,
|
|
53
|
-
reason
|
|
54
|
-
});
|
|
55
|
-
};
|
|
56
|
-
const acknowledged = [];
|
|
57
|
-
for (const input of pending) {
|
|
58
|
-
const decoded = operationOf(input);
|
|
59
|
-
if (Option.isNone(decoded)) {
|
|
60
|
-
const id = idOf(input);
|
|
61
|
-
if (Option.isNone(id)) return yield* Effect.fail(/* @__PURE__ */ new Error("A pending entry names no operation"));
|
|
62
|
-
reject(id.value, "Not an operation this server accepts");
|
|
63
|
-
continue;
|
|
64
|
-
}
|
|
65
|
-
const operation = decoded.value;
|
|
66
|
-
const admitted = options.admit === void 0 ? true : options.admit(operation);
|
|
67
|
-
const decision = Effect.isEffect(admitted) ? yield* admitted : admitted;
|
|
68
|
-
if (decision !== true) {
|
|
69
|
-
reject(operation.opId, decision === false ? "This connection may not make changes" : decision.reason);
|
|
70
|
-
continue;
|
|
71
|
-
}
|
|
72
|
-
yield* journal.append(key, operation, principal).pipe(Effect.map((appended) => acknowledged.push(Match.valueTags(appended, {
|
|
73
|
-
Committed: ({ committed }) => committed.operation.opId,
|
|
74
|
-
AlreadyCommitted: ({ opId }) => opId
|
|
75
|
-
}))), Effect.catchTags({
|
|
76
|
-
OperationRejectedError: (error) => Effect.sync(() => reject(error.opId, error.reason ?? "Refused by the server")),
|
|
77
|
-
InvalidOperationError: () => Effect.sync(() => reject(operation.opId, "Not a valid operation")),
|
|
78
|
-
IdentityConflictError: () => Effect.sync(() => reject(operation.opId, "Its id was already used for another"))
|
|
79
|
-
}));
|
|
80
|
-
}
|
|
81
|
-
if (options.settle !== void 0) yield* options.settle;
|
|
82
|
-
const read = yield* journal.read(key, Cursor.make(from), { limit }).pipe(Effect.map((rows) => Option.some(rows)), Effect.catchTag("CompactedCursorError", () => Effect.succeed(Option.none())));
|
|
83
|
-
return yield* Option.match(read, {
|
|
84
|
-
onSome: (rows) => Effect.succeed({
|
|
85
|
-
operations: rows.map(committedOf),
|
|
86
|
-
rejected,
|
|
87
|
-
reasons,
|
|
88
|
-
acknowledged,
|
|
89
|
-
more: rows.length === limit,
|
|
90
|
-
epoch
|
|
91
|
-
}),
|
|
92
|
-
onNone: () => Effect.map(journal.load(key), (loaded) => ({
|
|
93
|
-
operations: [],
|
|
94
|
-
rejected,
|
|
95
|
-
reasons,
|
|
96
|
-
acknowledged,
|
|
97
|
-
checkpoint: {
|
|
98
|
-
cursor: loaded.cursor,
|
|
99
|
-
model: snapshot.encode(loaded.snapshot)
|
|
100
|
-
},
|
|
101
|
-
epoch
|
|
102
|
-
}))
|
|
103
|
-
});
|
|
104
|
-
});
|
|
105
|
-
return { exchange: (cursor, pending, seen) => Effect.runPromise(exchange(cursor, pending, seen)) };
|
|
106
|
-
};
|
|
107
|
-
/**
|
|
108
|
-
* Calls `listener` each time the document commits, for `Sync.transport.serve`'s
|
|
109
|
-
* `changes`, so a socket wakes its replica to exchange. Returns the unsubscribe.
|
|
110
|
-
*/
|
|
111
|
-
const journalChanges = (journal, documentId) => (listener) => {
|
|
112
|
-
const fiber = Effect.runFork(Stream.runForEach(Stream.filter(journal.subscribe, (key) => key === documentId), () => Effect.sync(listener)));
|
|
113
|
-
return () => Effect.runSync(Fiber.interrupt(fiber));
|
|
114
|
-
};
|
|
115
|
-
/**
|
|
116
|
-
* Serves one accepted socket over the journal: each exchange frame answered by
|
|
117
|
-
* `journalExchange` with the connection's principal, and a notice sent after
|
|
118
|
-
* each commit, so the replica hears of others' edits. Returns the stop.
|
|
119
|
-
*/
|
|
120
|
-
const serveJournal = (socket, options) => {
|
|
121
|
-
const client = journalExchange(options);
|
|
122
|
-
const notices = journalChanges(options.journal, options.sync.documentId);
|
|
123
|
-
const { opens } = options;
|
|
124
|
-
return serveSocket(socket, {
|
|
125
|
-
exchange: (cursor, pending, epoch) => client.exchange(sequence(cursor), pending, epoch),
|
|
126
|
-
changes: opens === void 0 ? notices : (listener) => notices(() => void Effect.runPromise(opens).then((open) => {
|
|
127
|
-
if (open) listener();
|
|
128
|
-
}, () => {}))
|
|
129
|
-
});
|
|
130
|
-
};
|
|
131
|
-
/**
|
|
132
|
-
* The table holds revisions past every sequence the journal has: it outlived
|
|
133
|
-
* a reset of the journal, or was built from another. New edits commit at
|
|
134
|
-
* sequences the table already passed, so `apply` would skip every one and
|
|
135
|
-
* the replicas count each absorbed: rebuild the table with the journal.
|
|
136
|
-
*/
|
|
137
|
-
var TableAheadOfJournalError = class extends Schema.TaggedError()("SyncTableAheadOfJournalError", {
|
|
138
|
-
table: Schema.Number,
|
|
139
|
-
journal: Schema.Number
|
|
140
|
-
}) {
|
|
141
|
-
get message() {
|
|
142
|
-
return `The table holds revision ${this.table}, past the journal's ${this.journal}: rebuild the table with the journal`;
|
|
143
|
-
}
|
|
144
|
-
};
|
|
145
|
-
/**
|
|
146
|
-
* The table as the journal's read model: `settle` applies each committed
|
|
147
|
-
* edit through `apply`, as a recovery intent, and `absorb` records in the
|
|
148
|
-
* journal what the table holds and compacts the log behind it. For
|
|
149
|
-
* `journalExchange`'s `settle`, and a clock that absorbs.
|
|
150
|
-
*
|
|
151
|
-
* Recovery starts at the journal's floor, where compaction left it, so a
|
|
152
|
-
* server restarted over a journal that outlived it does not ask for history
|
|
153
|
-
* that is gone. Intents are keyed by the journal's epoch as well as the
|
|
154
|
-
* operation, so after a reset an operation sent again is applied again, not
|
|
155
|
-
* taken as already run.
|
|
156
|
-
*/
|
|
157
|
-
const editsJournal = (options) => {
|
|
158
|
-
const { journal } = options;
|
|
159
|
-
const key = DocumentId.make(options.documentId);
|
|
160
|
-
let applied = Option.none();
|
|
161
|
-
const intents = (epoch) => (operation) => Option.match(options.editsOf(operation), {
|
|
162
|
-
onNone: () => [],
|
|
163
|
-
onSome: ({ changes, at }) => changes.map((change, index) => ({
|
|
164
|
-
key: `${epoch}:${operation.opId}:${index}`,
|
|
165
|
-
run: Option.match(at, {
|
|
166
|
-
onNone: () => Effect.fail(/* @__PURE__ */ new Error(`Edit ${operation.opId} committed without its sequence`)),
|
|
167
|
-
onSome: (sequence) => options.apply(change, sequence)
|
|
168
|
-
})
|
|
169
|
-
}))
|
|
170
|
-
});
|
|
171
|
-
const checked = Effect.gen(function* () {
|
|
172
|
-
const table = yield* options.tableRevision;
|
|
173
|
-
const at = yield* journal.cursor(key);
|
|
174
|
-
if (table > at) return yield* new TableAheadOfJournalError({
|
|
175
|
-
table,
|
|
176
|
-
journal: at
|
|
177
|
-
});
|
|
178
|
-
return Cursor.make(yield* journal.floor(key));
|
|
179
|
-
});
|
|
180
|
-
return {
|
|
181
|
-
settle: Effect.gen(function* () {
|
|
182
|
-
const epoch = yield* journal.epoch(key);
|
|
183
|
-
const from = yield* Option.match(Option.filter(applied, (previous) => previous.epoch === epoch), {
|
|
184
|
-
onSome: ({ cursor }) => Effect.succeed(cursor),
|
|
185
|
-
onNone: () => checked
|
|
186
|
-
});
|
|
187
|
-
const cursor = yield* journal.recover({
|
|
188
|
-
key,
|
|
189
|
-
from,
|
|
190
|
-
intents: intents(epoch)
|
|
191
|
-
});
|
|
192
|
-
applied = Option.some({
|
|
193
|
-
cursor,
|
|
194
|
-
epoch
|
|
195
|
-
});
|
|
196
|
-
}),
|
|
197
|
-
absorb: Effect.gen(function* () {
|
|
198
|
-
const epoch = yield* journal.epoch(key);
|
|
199
|
-
const known = Option.filter(applied, (previous) => previous.epoch === epoch);
|
|
200
|
-
if (Option.isNone(known)) return;
|
|
201
|
-
const through = known.value.cursor;
|
|
202
|
-
const { snapshot, cursor } = yield* journal.load(key);
|
|
203
|
-
if (!options.holdsThrough(snapshot, through)) return;
|
|
204
|
-
yield* journal.append(key, options.absorbed(through, cursor), options.server);
|
|
205
|
-
yield* journal.compact(key, Sequence.make(through));
|
|
206
|
-
})
|
|
207
|
-
};
|
|
208
|
-
};
|
|
209
|
-
//#endregion
|
|
210
|
-
export { TableAheadOfJournalError, editsJournal, journalChanges, journalExchange, serveJournal };
|
|
211
|
-
|
|
212
|
-
//# sourceMappingURL=journal.mjs.map
|
|
1
|
+
export { t as TableAheadOfJournalError, n as documentHost, r as editsJournal, i as journalChanges, a as journalExchange, o as serveJournal } from "./journal-BtYEDz0E.mjs";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "foldkit-sync",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.0",
|
|
4
4
|
"description": "A local-first replica of a shared Foldkit projection: offline outbox, optimistic updates, and reconciliation.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"foldkit",
|
|
@@ -65,7 +65,7 @@
|
|
|
65
65
|
"effect": "^4.0.0",
|
|
66
66
|
"foldkit": "^0.168.0",
|
|
67
67
|
"foldkit-durable": "0.9.0",
|
|
68
|
-
"foldkit-remote": "0.
|
|
68
|
+
"foldkit-remote": "0.18.0"
|
|
69
69
|
},
|
|
70
70
|
"peerDependenciesMeta": {
|
|
71
71
|
"foldkit-durable": {
|
|
@@ -86,10 +86,10 @@
|
|
|
86
86
|
"miniflare": "4.20260730.0",
|
|
87
87
|
"tsdown": "^0.23.1",
|
|
88
88
|
"typescript": "7.0.2",
|
|
89
|
-
"foldkit-entity": "0.10.0",
|
|
90
89
|
"foldkit-durable": "0.9.0",
|
|
91
|
-
"foldkit-
|
|
92
|
-
"foldkit-
|
|
90
|
+
"foldkit-agent": "0.8.1",
|
|
91
|
+
"foldkit-remote": "0.18.0",
|
|
92
|
+
"foldkit-entity": "0.10.0"
|
|
93
93
|
},
|
|
94
94
|
"scripts": {
|
|
95
95
|
"build": "tsdown",
|
package/dist/journal.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"journal.mjs","names":["JournalDocumentId"],"sources":["../src/journal.ts"],"sourcesContent":["/**\n * `foldkit-sync/journal` — the server's side of an exchange, over a\n * `foldkit-durable` journal. Every Sync server needs the same loop: append\n * what a replica sends, refuse what cannot be taken, and read back what\n * committed since the replica's cursor. Written by hand three times, it\n * failed the same way: an operation that did not decode failed the whole\n * exchange, so the replica sent it again on every one and the edits behind it\n * never went. Here, refused operations are reported by id, and the replica\n * drops them.\n */\nimport { Effect, Fiber, Match, Option, Schema, Stream } from 'effect'\nimport {\n Cursor,\n DocumentId as JournalDocumentId,\n Sequence,\n type Committed,\n type Journal,\n} from 'foldkit-durable/core'\nimport { sequence } from './ids.js'\nimport type { AuthorizeDecision } from './make.js'\nimport type { Operation, Sync, TransportClient } from './sync.js'\nimport { serveSocket, type SocketLike } from './transport.js'\n\nexport interface JournalExchangeOptions<Message, Shared, Principal> {\n /** The document's contract: its codecs, and the snapshot a checkpoint encodes. */\n readonly sync: Sync<Message, Shared>\n /**\n * The journal made from `sync.journalContract()`, which orders and keeps the\n * document. One that takes any input, or only operations, is accepted.\n */\n readonly journal: Journal<Operation, Shared, Principal, Operation>\n /**\n * Who is exchanging, as the transport established it. The journal's\n * `authorize` reads it; a refused operation is reported as rejected.\n */\n readonly principal: 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`. It runs on\n * every exchange, so a write that failed is tried again on the next.\n */\n readonly settle?: Effect.Effect<void, unknown> | undefined\n /**\n * Whether the connection may open the document at all, to read it or to\n * change it: a principal outside its readers. Refused, every exchange fails,\n * and nothing is read or appended.\n */\n readonly opens?: Effect.Effect<boolean> | undefined\n /**\n * Whether an operation may be appended, decided before the journal sees it,\n * by what the transport established rather than by the document: a principal\n * that may only read, or a rule that reads the rows an edit names, which\n * cannot run under the journal's lock (`foldkit-guard/sync`). `true` admits;\n * a refusal is rejected by the operation's id, with its reason when it gives\n * one. One that fails fails the exchange, as the journal failing does. The\n * journal's own `authorize` is where a rule about the document goes.\n */\n readonly admit?:\n | ((operation: Operation) => AuthorizeDecision | Effect.Effect<AuthorizeDecision, unknown>)\n | undefined\n /** The most committed operations one reply carries; a replica further behind asks again. Default 500. */\n readonly limit?: number | undefined\n}\n\n/** The id an entry names, read without trusting the rest of it. */\nconst idOf = (input: unknown): Option.Option<string> =>\n Option.map(\n Schema.decodeUnknownOption(Schema.Struct({ opId: Schema.String }))(input),\n ({ opId }) => opId,\n )\n\n/**\n * One replica's exchanges with the journal, as the replica's transport\n * speaks them (`Sync.transport.fromPromise`, or behind\n * `Sync.transport.serve` on a socket). Each pending operation is appended in\n * order, and acknowledged once committed, or already committed. One is\n * rejected by its id when its message does not decode, it names another\n * document, or the journal refuses it (`authorize`, `validate`); the replica\n * drops it rather than send it again. Only an entry with no id at all, a\n * cursor ahead of the journal's, a connection `opens` refuses, or `admit` or\n * the journal failing fails the exchange. The reply carries what committed\n * after the replica's cursor, a checkpoint when that history was compacted,\n * and the journal's epoch, so a replica of a reset journal starts again.\n */\nexport const journalExchange = <Message, Shared, Principal>(\n options: JournalExchangeOptions<Message, Shared, Principal>,\n): TransportClient => {\n const { sync, journal, principal } = options\n const limit = options.limit ?? 500\n const key = JournalDocumentId.make(sync.documentId)\n const snapshot = sync.journalContract().snapshot\n const operationOf = Option.liftThrowable((input: unknown) =>\n sync.codec.operationFrom(input, sync.documentId),\n )\n const committedOf = (committed: Committed<Operation>) =>\n sync.codec.committedFrom(\n { ...committed.operation, serverSequence: committed.sequence, actorId: committed.actorId },\n sync.documentId,\n )\n\n const exchange = (cursor: number, pending: ReadonlyArray<unknown>, seen?: string) =>\n Effect.gen(function* () {\n if (options.opens !== undefined && !(yield* options.opens)) {\n return yield* Effect.fail(new Error('This connection may not open the document'))\n }\n // A replica that saw another epoch holds a cursor into history this journal\n // lacks (it was reset): it is answered from the start. Otherwise a cursor\n // past the journal's is refused before anything is appended, or the\n // operations would commit and their acknowledgements be lost.\n const epoch = yield* journal.epoch(key)\n const from = seen !== undefined && seen !== epoch ? 0 : cursor\n const at = yield* journal.cursor(key)\n if (from > at) {\n return yield* Effect.fail(new Error(`Cursor ${cursor} is ahead of the server's ${at}`))\n }\n const rejected: Array<string> = []\n const reasons: Array<{ readonly opId: string; readonly reason: string }> = []\n // Each reason is words for the person whose edit came back: a policy's own,\n // or a fixed sentence, never an error's message, which may carry internals.\n const reject = (opId: string, reason: string) => {\n rejected.push(opId)\n reasons.push({ opId, reason })\n }\n const acknowledged: Array<string> = []\n for (const input of pending) {\n const decoded = operationOf(input)\n if (Option.isNone(decoded)) {\n const id = idOf(input)\n if (Option.isNone(id))\n return yield* Effect.fail(new Error('A pending entry names no operation'))\n reject(id.value, 'Not an operation this server accepts')\n continue\n }\n const operation = decoded.value\n const admitted = options.admit === undefined ? true : options.admit(operation)\n const decision = Effect.isEffect(admitted) ? yield* admitted : admitted\n if (decision !== true) {\n reject(\n operation.opId,\n decision === false ? 'This connection may not make changes' : decision.reason,\n )\n continue\n }\n yield* journal.append(key, operation, principal).pipe(\n Effect.map(appended =>\n acknowledged.push(\n Match.valueTags(appended, {\n Committed: ({ committed }): string => committed.operation.opId,\n AlreadyCommitted: ({ opId }): string => opId,\n }),\n ),\n ),\n // A refusal, an operation the journal cannot apply, and an id reused for\n // other content fail the same way on every retry, so they are rejected; a\n // `JournalError` may not, so it still fails the exchange.\n Effect.catchTags({\n OperationRejectedError: error =>\n Effect.sync(() => reject(error.opId, error.reason ?? 'Refused by the server')),\n InvalidOperationError: () =>\n Effect.sync(() => reject(operation.opId, 'Not a valid operation')),\n IdentityConflictError: () =>\n Effect.sync(() => reject(operation.opId, 'Its id was already used for another')),\n }),\n )\n }\n if (options.settle !== undefined) yield* options.settle\n // A cursor below the compacted floor is answered with the snapshot; the\n // read decides that itself, so a compaction cannot slip in between.\n const read = yield* journal.read(key, Cursor.make(from), { limit }).pipe(\n Effect.map(rows => Option.some(rows)),\n Effect.catchTag('CompactedCursorError', () => Effect.succeed(Option.none())),\n )\n return yield* Option.match(read, {\n onSome: rows =>\n Effect.succeed({\n operations: rows.map(committedOf),\n rejected,\n reasons,\n acknowledged,\n more: rows.length === limit,\n epoch,\n }),\n onNone: () =>\n Effect.map(journal.load(key), loaded => ({\n operations: [],\n rejected,\n reasons,\n acknowledged,\n checkpoint: { cursor: loaded.cursor, model: snapshot.encode(loaded.snapshot) },\n epoch,\n })),\n })\n })\n\n return {\n exchange: (cursor, pending, seen) => Effect.runPromise(exchange(cursor, pending, seen)),\n }\n}\n\n/**\n * Calls `listener` each time the document commits, for `Sync.transport.serve`'s\n * `changes`, so a socket wakes its replica to exchange. Returns the unsubscribe.\n */\nexport const journalChanges =\n <Shared, Principal>(\n journal: Journal<Operation, Shared, Principal, Operation>,\n documentId: string,\n ): ((listener: () => void) => () => void) =>\n listener => {\n const fiber = Effect.runFork(\n Stream.runForEach(\n Stream.filter(journal.subscribe, key => key === documentId),\n () => Effect.sync(listener),\n ),\n )\n return () => Effect.runSync(Fiber.interrupt(fiber))\n }\n\n/**\n * Serves one accepted socket over the journal: each exchange frame answered by\n * `journalExchange` with the connection's principal, and a notice sent after\n * each commit, so the replica hears of others' edits. Returns the stop.\n */\nexport const serveJournal = <Message, Shared, Principal>(\n socket: SocketLike,\n options: JournalExchangeOptions<Message, Shared, Principal>,\n): (() => void) => {\n const client = journalExchange(options)\n const notices = journalChanges(options.journal, options.sync.documentId)\n const { opens } = options\n return serveSocket(socket, {\n exchange: (cursor, pending, epoch) => client.exchange(sequence(cursor), pending, epoch),\n // A connection that may not open the document is told nothing of its commits.\n changes:\n opens === undefined\n ? notices\n : listener =>\n notices(\n () =>\n void Effect.runPromise(opens).then(\n open => {\n if (open) listener()\n },\n () => {},\n ),\n ),\n })\n}\n\n/**\n * The table holds revisions past every sequence the journal has: it outlived\n * a reset of the journal, or was built from another. New edits commit at\n * sequences the table already passed, so `apply` would skip every one and\n * the replicas count each absorbed: rebuild the table with the journal.\n */\nexport class TableAheadOfJournalError extends Schema.TaggedError<TableAheadOfJournalError>()(\n 'SyncTableAheadOfJournalError',\n { table: Schema.Number, journal: Schema.Number },\n) {\n override get message(): string {\n return `The table holds revision ${this.table}, past the journal's ${this.journal}: rebuild the table with the journal`\n }\n}\n\nexport interface EditsJournalOptions<Shared, Principal, Change> {\n /** The document whose edits the table reads. */\n readonly documentId: string\n /** The journal the edits commit to. */\n readonly journal: Journal<Operation, Shared, Principal, Operation>\n /**\n * The cells an operation edits, with the sequence its stamp wrote in; none\n * for an operation that edits nothing. An edit committed without a sequence\n * is not this journal's: its intents fail rather than write revision 0.\n */\n readonly editsOf: (operation: Operation) => Option.Option<{\n readonly changes: ReadonlyArray<Change>\n readonly at: Option.Option<number>\n }>\n /**\n * Writes one committed change to the table, with the sequence it committed\n * at. It runs as a recovery intent, so it may run again after a crash: it\n * must never move a row back (`revision <= at`). A failure stops recovery\n * there, and the next settle tries it again.\n *\n * It cannot refuse an edit: the edit has committed. One naming a row the\n * table lacks is refused at commit instead, by the journal's `validate`,\n * so its sender is told; let through, it would change nothing and vanish\n * once absorbed.\n */\n readonly apply: (change: Change, at: number) => Effect.Effect<void, unknown>\n /**\n * The highest revision the table holds. Settling refuses to start while it\n * is past the journal's cursor (`TableAheadOfJournalError`), since every\n * edit would then be skipped and counted absorbed; it asks again on each\n * settle until the two agree.\n */\n readonly tableRevision: Effect.Effect<number, unknown>\n /** Whether the snapshot still keeps an edit committed through `through`: whether to absorb. */\n readonly holdsThrough: (snapshot: Shared, through: number) => boolean\n /**\n * The server's operation saying the table holds every edit through\n * `through`, sequenced from `cursor`, the journal's: the replicas drop those\n * edits on hearing it.\n */\n readonly absorbed: (through: number, cursor: number) => Operation\n /** Who the server commits `absorbed` as; the contract's `authorize` should let only it. */\n readonly server: Principal\n}\n\n/**\n * The table as the journal's read model: `settle` applies each committed\n * edit through `apply`, as a recovery intent, and `absorb` records in the\n * journal what the table holds and compacts the log behind it. For\n * `journalExchange`'s `settle`, and a clock that absorbs.\n *\n * Recovery starts at the journal's floor, where compaction left it, so a\n * server restarted over a journal that outlived it does not ask for history\n * that is gone. Intents are keyed by the journal's epoch as well as the\n * operation, so after a reset an operation sent again is applied again, not\n * taken as already run.\n */\nexport const editsJournal = <Shared, Principal, Change>(\n options: EditsJournalOptions<Shared, Principal, Change>,\n): {\n readonly settle: Effect.Effect<void, unknown>\n readonly absorb: Effect.Effect<void, unknown>\n} => {\n const { journal } = options\n const key = JournalDocumentId.make(options.documentId)\n // Operations at or before `applied.cursor` have every change in the table,\n // in `applied.epoch`: none until a settle has run in this process.\n let applied: Option.Option<{ readonly cursor: Cursor; readonly epoch: string }> = Option.none()\n const intents = (epoch: string) => (operation: Operation) =>\n Option.match(options.editsOf(operation), {\n onNone: () => [],\n onSome: ({ changes, at }) =>\n changes.map((change, index) => ({\n key: `${epoch}:${operation.opId}:${index}`,\n run: Option.match(at, {\n onNone: () =>\n Effect.fail(new Error(`Edit ${operation.opId} committed without its sequence`)),\n onSome: sequence => options.apply(change, sequence),\n }),\n })),\n })\n // Before the first recovery of an epoch: the table must not be past it.\n const checked = Effect.gen(function* () {\n const table = yield* options.tableRevision\n const at = yield* journal.cursor(key)\n if (table > at) return yield* new TableAheadOfJournalError({ table, journal: at })\n return Cursor.make(yield* journal.floor(key))\n })\n const settle = Effect.gen(function* () {\n const epoch = yield* journal.epoch(key)\n // A new epoch is a new history: recovery starts over at its floor.\n const from = yield* Option.match(\n Option.filter(applied, previous => previous.epoch === epoch),\n {\n onSome: ({ cursor }) => Effect.succeed(cursor),\n onNone: () => checked,\n },\n )\n const cursor = yield* journal.recover({ key, from, intents: intents(epoch) })\n applied = Option.some({ cursor, epoch })\n })\n // Two absorbs at once need no lock: both name the record by the journal's\n // cursor, so the second is the first's retry, answered from history.\n const absorb = Effect.gen(function* () {\n const epoch = yield* journal.epoch(key)\n const known = Option.filter(applied, previous => previous.epoch === epoch)\n if (Option.isNone(known)) return\n const through = known.value.cursor\n const { snapshot, cursor } = yield* journal.load(key)\n if (!options.holdsThrough(snapshot, through)) return\n yield* journal.append(key, options.absorbed(through, cursor), options.server)\n // What the log holds through `through` is in the table and gone from\n // the snapshot; a replica behind it is sent the snapshot instead.\n yield* journal.compact(key, Sequence.make(through))\n })\n return { settle, absorb }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAiEA,MAAM,QAAQ,UACZ,OAAO,IACL,OAAO,oBAAoB,OAAO,OAAO,EAAE,MAAM,OAAO,OAAO,CAAC,CAAC,CAAC,CAAC,KAAK,IACvE,EAAE,WAAW,IAChB;;;;;;;;;;;;;;AAeF,MAAa,mBACX,YACoB;CACpB,MAAM,EAAE,MAAM,SAAS,cAAc;CACrC,MAAM,QAAQ,QAAQ,SAAS;CAC/B,MAAM,MAAMA,WAAkB,KAAK,KAAK,UAAU;CAClD,MAAM,WAAW,KAAK,gBAAgB,CAAC,CAAC;CACxC,MAAM,cAAc,OAAO,eAAe,UACxC,KAAK,MAAM,cAAc,OAAO,KAAK,UAAU,CACjD;CACA,MAAM,eAAe,cACnB,KAAK,MAAM,cACT;EAAE,GAAG,UAAU;EAAW,gBAAgB,UAAU;EAAU,SAAS,UAAU;CAAQ,GACzF,KAAK,UACP;CAEF,MAAM,YAAY,QAAgB,SAAiC,SACjE,OAAO,IAAI,aAAa;EACtB,IAAI,QAAQ,UAA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