foldkit-sync 0.15.0 → 0.17.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 +567 -41
- package/dist/diagnostics.d.ts +74 -3
- package/dist/diagnostics.d.ts.map +1 -1
- package/dist/diagnostics.js +60 -4
- package/dist/diagnostics.js.map +1 -1
- package/dist/do.d.ts +49 -7
- package/dist/do.d.ts.map +1 -1
- package/dist/do.js +91 -8
- package/dist/do.js.map +1 -1
- package/dist/errors.d.ts +92 -1
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +87 -1
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +9 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -2
- package/dist/index.js.map +1 -1
- package/dist/journal.d.ts +52 -27
- package/dist/journal.d.ts.map +1 -1
- package/dist/journal.js +176 -64
- package/dist/journal.js.map +1 -1
- package/dist/make.d.ts +48 -17
- package/dist/make.d.ts.map +1 -1
- package/dist/make.js +11 -4
- package/dist/make.js.map +1 -1
- package/dist/migrations.d.ts +37 -0
- package/dist/migrations.d.ts.map +1 -0
- package/dist/migrations.js +56 -0
- package/dist/migrations.js.map +1 -0
- package/dist/mount.d.ts +1 -1
- package/dist/mount.d.ts.map +1 -1
- package/dist/mount.js +12 -6
- package/dist/mount.js.map +1 -1
- package/dist/refusal.d.ts +33 -0
- package/dist/refusal.d.ts.map +1 -0
- package/dist/refusal.js +47 -0
- package/dist/refusal.js.map +1 -0
- package/dist/serverJournal.d.ts +143 -0
- package/dist/serverJournal.d.ts.map +1 -0
- package/dist/serverJournal.js +503 -0
- package/dist/serverJournal.js.map +1 -0
- package/dist/sync.d.ts +150 -14
- package/dist/sync.d.ts.map +1 -1
- package/dist/sync.js +273 -64
- package/dist/sync.js.map +1 -1
- package/dist/transport.d.ts +10 -6
- package/dist/transport.d.ts.map +1 -1
- package/dist/transport.js.map +1 -1
- package/package.json +11 -8
package/dist/journal.js
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import { Cause, Context, Effect, Exit, Fiber, Layer, Match, Option, Result, Schema, Scope, Stream } from "effect";
|
|
2
|
+
import { Cursor, DocumentId, JournalError, Sequence } from "foldkit-durable/core";
|
|
2
3
|
import { checkRevalidate } from "./revalidate.js";
|
|
3
|
-
import { hostDefect, listenerFailed, reportTo } from "./diagnostics.js";
|
|
4
|
+
import { hostDefect, listenerFailed, reportTo, serverOnlySubmitted } from "./diagnostics.js";
|
|
4
5
|
import { serveSocket } from "./transport.js";
|
|
6
|
+
import { reaction, serverJournal } from "./serverJournal.js";
|
|
7
|
+
import { SyncRefusal, fitWords } from "./refusal.js";
|
|
5
8
|
import { sequence } from "./ids.js";
|
|
6
|
-
import {
|
|
9
|
+
import { ServerOnlyMessageError, UnreadableHistoryError, UnreadableMessageError, UnsupportedMessageVersionError } from "./errors.js";
|
|
7
10
|
// src/journal.ts
|
|
8
11
|
/**
|
|
9
12
|
* `foldkit-sync/journal` — the server's side of an exchange, over a
|
|
@@ -15,96 +18,200 @@ import { Cursor, DocumentId as DocumentId$1, Sequence as Sequence$1 } from "fold
|
|
|
15
18
|
* never went. Here, refused operations are reported by id, and the replica
|
|
16
19
|
* drops them.
|
|
17
20
|
*/
|
|
21
|
+
const encodeRefusal = Schema.encodeSync(SyncRefusal);
|
|
22
|
+
/** A refusal in the server's own words, which name no Entity's invariant. */
|
|
23
|
+
const invalidAs = (message) => SyncRefusal.Invalid({
|
|
24
|
+
entity: Option.none(),
|
|
25
|
+
rule: Option.none(),
|
|
26
|
+
message,
|
|
27
|
+
path: []
|
|
28
|
+
});
|
|
29
|
+
/** The version an entry claims, read before anything else of it, so a newer one is told from a malformed one. */
|
|
30
|
+
const claimedVersion = Schema.decodeUnknownOption(Schema.Struct({ messageVersion: Schema.optionalKey(Schema.Number) }));
|
|
31
|
+
/**
|
|
32
|
+
* What the replica is told: a socket sends an error's message, and the
|
|
33
|
+
* operation's id and version are another replica's. They stay on the error,
|
|
34
|
+
* for the server's own logs.
|
|
35
|
+
*/
|
|
36
|
+
const HISTORY_UNREADABLE = "This server cannot read the history of this document";
|
|
37
|
+
/**
|
|
38
|
+
* A stored row that will not read, as the journal reports it: a
|
|
39
|
+
* `JournalError` whose cause is the codec's own error, never told by its words.
|
|
40
|
+
*/
|
|
41
|
+
const unreadableHistory = (documentId, cause) => {
|
|
42
|
+
if (cause instanceof UnreadableMessageError) return Option.some(new UnreadableHistoryError({
|
|
43
|
+
documentId,
|
|
44
|
+
opId: cause.opId,
|
|
45
|
+
version: cause.version,
|
|
46
|
+
message: HISTORY_UNREADABLE
|
|
47
|
+
}));
|
|
48
|
+
if (cause instanceof UnsupportedMessageVersionError) return Option.some(new UnreadableHistoryError({
|
|
49
|
+
documentId,
|
|
50
|
+
opId: cause.opId,
|
|
51
|
+
version: cause.found,
|
|
52
|
+
message: HISTORY_UNREADABLE
|
|
53
|
+
}));
|
|
54
|
+
return Option.none();
|
|
55
|
+
};
|
|
56
|
+
/** What a replica that sent a server-only Message is told. */
|
|
57
|
+
const SERVER_ONLY_REASON = "Only the server makes this change";
|
|
58
|
+
/** The replica id an entry claims, for a diagnostic: read without trusting the rest of it. */
|
|
59
|
+
const replicaOf = (input) => Option.match(Schema.decodeUnknownOption(Schema.Struct({ replicaId: Schema.String }))(input), {
|
|
60
|
+
onNone: () => "?",
|
|
61
|
+
onSome: ({ replicaId }) => fitWords(replicaId)
|
|
62
|
+
});
|
|
18
63
|
/** The id an entry names, read without trusting the rest of it. */
|
|
19
64
|
const idOf = (input) => Option.map(Schema.decodeUnknownOption(Schema.Struct({ opId: Schema.String }))(input), ({ opId }) => opId);
|
|
20
65
|
/**
|
|
21
66
|
* One replica's exchanges with the journal, as the replica's transport
|
|
22
67
|
* speaks them (`Sync.transport.fromPromise`, or behind
|
|
23
68
|
* `Sync.transport.serve` on a socket). Each pending operation is appended in
|
|
24
|
-
* order, and acknowledged once committed, or already
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
69
|
+
* order, as received, and acknowledged once committed, or already
|
|
70
|
+
* committed. Every hook (`admit`, and the journal's `validate`, `authorize`,
|
|
71
|
+
* `reduce` and `stamp`) sees its Message upcast to the current version. One
|
|
72
|
+
* is rejected by its id when its message does not decode, it names another
|
|
73
|
+
* document, the journal refuses it (`authorize`, `validate`), or it was
|
|
74
|
+
* written at an older version no step reads (`Unreadable`); the replica drops
|
|
75
|
+
* it, or keeps an unreadable one in `refused`, rather than send it again. An
|
|
76
|
+
* entry written at a version newer than this server's fails the exchange
|
|
77
|
+
* before anything is appended, so its replica waits with its outbox whole; so
|
|
78
|
+
* do an entry with no id at all, a cursor ahead of the journal's, a
|
|
79
|
+
* connection `opens` refuses, `admit` or the journal failing, and a stored
|
|
80
|
+
* operation that will not read (`UnreadableHistoryError`). The reply carries what committed
|
|
30
81
|
* after the replica's cursor, a checkpoint when that history was compacted,
|
|
31
82
|
* and the journal's epoch, so a replica of a reset journal starts again.
|
|
32
83
|
*/
|
|
33
84
|
const journalExchange = (options) => {
|
|
34
85
|
const { sync, journal, principal } = options;
|
|
35
86
|
const limit = options.limit ?? 500;
|
|
36
|
-
const key = DocumentId
|
|
37
|
-
const
|
|
38
|
-
const
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
87
|
+
const key = DocumentId.make(sync.documentId);
|
|
88
|
+
const contract = sync.journalContract();
|
|
89
|
+
const supported = sync.codec.messageVersion;
|
|
90
|
+
/**
|
|
91
|
+
* An entry as written, with what it means: its Message upcast to the current
|
|
92
|
+
* version. Older and unread by any step is told apart, as `Unreadable`, and
|
|
93
|
+
* a Message only the server appends, as `Forbidden`; anything else that
|
|
94
|
+
* fails is not an operation this server accepts.
|
|
95
|
+
*/
|
|
96
|
+
const operationOf = (input) => {
|
|
97
|
+
try {
|
|
98
|
+
const written = sync.codec.writtenFrom(input, sync.documentId);
|
|
99
|
+
return Result.succeed({
|
|
100
|
+
written,
|
|
101
|
+
operation: sync.codec.normalizeOperation(written)
|
|
102
|
+
});
|
|
103
|
+
} catch (cause) {
|
|
104
|
+
return Result.fail(cause instanceof UnreadableMessageError || cause instanceof ServerOnlyMessageError ? cause : "invalid");
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
/** As the replica reads it: written at this server's version, with its order and actor. */
|
|
108
|
+
const committedOf = (committed) => {
|
|
109
|
+
const written = {
|
|
110
|
+
...contract.operation.encode(committed.operation),
|
|
111
|
+
serverSequence: committed.sequence,
|
|
112
|
+
actorId: committed.actorId
|
|
113
|
+
};
|
|
114
|
+
sync.codec.committedFrom(written, sync.documentId);
|
|
115
|
+
return written;
|
|
116
|
+
};
|
|
44
117
|
const exchange = (cursor, pending, seen) => Effect.gen(function* () {
|
|
45
118
|
if (options.opens !== void 0 && !(yield* options.opens)) return yield* Effect.fail(/* @__PURE__ */ new Error("This connection may not open the document"));
|
|
46
119
|
const epoch = yield* journal.epoch(key);
|
|
47
120
|
const from = seen !== void 0 && seen !== epoch ? 0 : cursor;
|
|
48
121
|
const at = yield* journal.cursor(key);
|
|
49
122
|
if (from > at) return yield* Effect.fail(/* @__PURE__ */ new Error(`Cursor ${cursor} is ahead of the server's ${at}`));
|
|
123
|
+
for (const input of pending) {
|
|
124
|
+
const found = Option.flatMapNullishOr(claimedVersion(input), (probe) => probe.messageVersion);
|
|
125
|
+
if (Option.isSome(found) && found.value > supported) return yield* Option.match(idOf(input), {
|
|
126
|
+
onNone: () => Effect.fail(/* @__PURE__ */ new Error("A pending entry names no operation")),
|
|
127
|
+
onSome: (opId) => Effect.fail(new UnsupportedMessageVersionError({
|
|
128
|
+
opId,
|
|
129
|
+
found: found.value,
|
|
130
|
+
supported,
|
|
131
|
+
message: `The replica writes Message version ${found.value}; this server reads up to ${supported}`
|
|
132
|
+
}))
|
|
133
|
+
});
|
|
134
|
+
}
|
|
50
135
|
const rejected = [];
|
|
136
|
+
const refusals = [];
|
|
51
137
|
const reasons = [];
|
|
52
|
-
const reject = (opId, reason) => {
|
|
138
|
+
const reject = (opId, refusal, reason) => {
|
|
53
139
|
rejected.push(opId);
|
|
140
|
+
refusals.push({
|
|
141
|
+
opId,
|
|
142
|
+
refusal: encodeRefusal(refusal)
|
|
143
|
+
});
|
|
54
144
|
reasons.push({
|
|
55
145
|
opId,
|
|
56
146
|
reason
|
|
57
147
|
});
|
|
58
148
|
};
|
|
149
|
+
const forbid = (opId, reason, otherwise) => {
|
|
150
|
+
const fitted = reason === void 0 ? void 0 : fitWords(reason);
|
|
151
|
+
reject(opId, SyncRefusal.Forbidden({ reason: Option.fromUndefinedOr(fitted) }), fitted ?? otherwise);
|
|
152
|
+
};
|
|
153
|
+
const invalid = (opId, message) => reject(opId, invalidAs(message), message);
|
|
59
154
|
const acknowledged = [];
|
|
60
155
|
for (const input of pending) {
|
|
61
156
|
const decoded = operationOf(input);
|
|
62
|
-
if (
|
|
157
|
+
if (Result.isFailure(decoded)) {
|
|
63
158
|
const id = idOf(input);
|
|
64
159
|
if (Option.isNone(id)) return yield* Effect.fail(/* @__PURE__ */ new Error("A pending entry names no operation"));
|
|
65
|
-
|
|
160
|
+
const failure = decoded.failure;
|
|
161
|
+
if (failure === "invalid") invalid(id.value, "Not an operation this server accepts");
|
|
162
|
+
else if (failure instanceof UnreadableMessageError) reject(id.value, SyncRefusal.Unreadable({ version: failure.version }), "Written by a version of the app this server cannot read");
|
|
163
|
+
else {
|
|
164
|
+
forbid(id.value, SERVER_ONLY_REASON, SERVER_ONLY_REASON);
|
|
165
|
+
yield* reportTo(options.diagnostics, serverOnlySubmitted(sync.documentId, id.value, replicaOf(input)));
|
|
166
|
+
}
|
|
66
167
|
continue;
|
|
67
168
|
}
|
|
68
|
-
const operation = decoded.
|
|
169
|
+
const { written, operation } = decoded.success;
|
|
69
170
|
const admitted = options.admit === void 0 ? true : options.admit(operation);
|
|
70
171
|
const decision = Effect.isEffect(admitted) ? yield* admitted : admitted;
|
|
71
172
|
if (decision !== true) {
|
|
72
|
-
|
|
173
|
+
forbid(operation.opId, decision === false ? void 0 : decision.reason, "This connection may not make changes");
|
|
73
174
|
continue;
|
|
74
175
|
}
|
|
75
|
-
yield* journal.append(key,
|
|
176
|
+
yield* journal.append(key, written, principal).pipe(Effect.map((appended) => acknowledged.push(Match.valueTags(appended, {
|
|
76
177
|
Committed: ({ committed }) => committed.operation.opId,
|
|
77
178
|
AlreadyCommitted: ({ opId }) => opId
|
|
78
179
|
}))), Effect.catchTags({
|
|
79
|
-
OperationRejectedError: (error) => Effect.sync(() =>
|
|
80
|
-
InvalidOperationError: () => Effect.sync(() =>
|
|
81
|
-
IdentityConflictError: () => Effect.sync(() =>
|
|
180
|
+
OperationRejectedError: (error) => Effect.sync(() => forbid(error.opId, error.reason, "Refused by the server")),
|
|
181
|
+
InvalidOperationError: () => Effect.sync(() => invalid(operation.opId, "Not a valid operation")),
|
|
182
|
+
IdentityConflictError: () => Effect.sync(() => invalid(operation.opId, "Its id was already used for another"))
|
|
82
183
|
}));
|
|
83
184
|
}
|
|
84
185
|
if (options.settle !== void 0) yield* options.settle;
|
|
186
|
+
const refused = refusals.length === 0 ? {} : { refusals };
|
|
85
187
|
const read = yield* journal.read(key, Cursor.make(from), { limit }).pipe(Effect.map((rows) => Option.some(rows)), Effect.catchTag("CompactedCursorError", () => Effect.succeed(Option.none())));
|
|
86
188
|
return yield* Option.match(read, {
|
|
87
|
-
onSome: (rows) => Effect.
|
|
88
|
-
|
|
189
|
+
onSome: (rows) => Effect.try({
|
|
190
|
+
try: () => rows.map(committedOf),
|
|
191
|
+
catch: (cause) => new Error("Could not read the log", { cause })
|
|
192
|
+
}).pipe(Effect.map((operations) => ({
|
|
193
|
+
operations,
|
|
89
194
|
rejected,
|
|
195
|
+
...refused,
|
|
90
196
|
reasons,
|
|
91
197
|
acknowledged,
|
|
92
198
|
more: rows.length === limit,
|
|
93
199
|
epoch
|
|
94
|
-
}),
|
|
200
|
+
}))),
|
|
95
201
|
onNone: () => Effect.map(journal.load(key), (loaded) => ({
|
|
96
202
|
operations: [],
|
|
97
203
|
rejected,
|
|
204
|
+
...refused,
|
|
98
205
|
reasons,
|
|
99
206
|
acknowledged,
|
|
100
207
|
checkpoint: {
|
|
101
208
|
cursor: loaded.cursor,
|
|
102
|
-
model: snapshot.encode(loaded.snapshot)
|
|
209
|
+
model: contract.snapshot.encode(loaded.snapshot)
|
|
103
210
|
},
|
|
104
211
|
epoch
|
|
105
212
|
}))
|
|
106
213
|
});
|
|
107
|
-
});
|
|
214
|
+
}).pipe(Effect.mapError((error) => error instanceof JournalError ? Option.getOrElse(unreadableHistory(sync.documentId, error.cause), () => error) : error));
|
|
108
215
|
return { exchange: (cursor, pending, seen) => Effect.runPromise(exchange(cursor, pending, seen)) };
|
|
109
216
|
};
|
|
110
217
|
/**
|
|
@@ -150,22 +257,32 @@ var TableAheadOfJournalError = class extends Schema.TaggedError()("SyncTableAhea
|
|
|
150
257
|
return `The table holds revision ${this.table}, past the journal's ${this.journal}: rebuild the table with the journal`;
|
|
151
258
|
}
|
|
152
259
|
};
|
|
260
|
+
/** The stored cursor `editsJournal` keeps: every edit at or before it is in the table. */
|
|
261
|
+
const EDITS_CURSOR = "edits";
|
|
153
262
|
/**
|
|
154
263
|
* The table as the journal's read model: `settle` applies each committed
|
|
155
264
|
* edit through `apply`, as a recovery intent, and `absorb` records in the
|
|
156
265
|
* journal what the table holds and compacts the log behind it. For
|
|
157
266
|
* `journalExchange`'s `settle`, and a clock that absorbs.
|
|
158
267
|
*
|
|
159
|
-
*
|
|
160
|
-
*
|
|
161
|
-
*
|
|
162
|
-
*
|
|
163
|
-
*
|
|
268
|
+
* How far the table holds is a cursor the journal stores (`journal.cursors`),
|
|
269
|
+
* started at the journal's floor, where compaction left it, so a server
|
|
270
|
+
* restarted over a journal that outlived it neither walks the log again nor
|
|
271
|
+
* asks for history that is gone. Intents are keyed by the journal's epoch as
|
|
272
|
+
* well as the operation, so after a reset an operation sent again is applied
|
|
273
|
+
* again, not taken as already run.
|
|
164
274
|
*/
|
|
165
275
|
const editsJournal = (options) => {
|
|
166
|
-
const { journal } = options;
|
|
167
|
-
|
|
168
|
-
|
|
276
|
+
const { journal, asServer } = options;
|
|
277
|
+
if (asServer === void 0 && (options.absorbed === void 0 || options.server === void 0)) throw new Error("editsJournal: pass asServer, or absorbed with server");
|
|
278
|
+
const key = DocumentId.make(options.documentId);
|
|
279
|
+
/** The stored cursor in the current epoch, started at the floor the first time. */
|
|
280
|
+
const tracked = Effect.gen(function* () {
|
|
281
|
+
const found = yield* journal.cursors.settled(key, EDITS_CURSOR);
|
|
282
|
+
if (Option.isSome(found)) return found.value;
|
|
283
|
+
yield* journal.cursors.track(key, EDITS_CURSOR, { from: "floor" });
|
|
284
|
+
return Option.getOrThrow(yield* journal.cursors.settled(key, EDITS_CURSOR));
|
|
285
|
+
});
|
|
169
286
|
const intents = (epoch) => (operation) => Option.match(options.editsOf(operation), {
|
|
170
287
|
onNone: () => [],
|
|
171
288
|
onSome: ({ changes, at }) => changes.map((change, index) => ({
|
|
@@ -176,41 +293,36 @@ const editsJournal = (options) => {
|
|
|
176
293
|
})
|
|
177
294
|
}))
|
|
178
295
|
});
|
|
179
|
-
const checked = Effect.gen(function* () {
|
|
180
|
-
const table = yield* options.tableRevision;
|
|
181
|
-
const at = yield* journal.cursor(key);
|
|
182
|
-
if (table > at) return yield* new TableAheadOfJournalError({
|
|
183
|
-
table,
|
|
184
|
-
journal: at
|
|
185
|
-
});
|
|
186
|
-
return Cursor.make(yield* journal.floor(key));
|
|
187
|
-
});
|
|
188
296
|
return {
|
|
189
297
|
settle: Effect.gen(function* () {
|
|
190
|
-
const
|
|
191
|
-
const
|
|
192
|
-
|
|
193
|
-
|
|
298
|
+
const table = yield* options.tableRevision;
|
|
299
|
+
const at = yield* journal.cursor(key);
|
|
300
|
+
if (table > at) return yield* new TableAheadOfJournalError({
|
|
301
|
+
table,
|
|
302
|
+
journal: at
|
|
194
303
|
});
|
|
195
|
-
const cursor = yield*
|
|
304
|
+
const { epoch, cursor } = yield* tracked;
|
|
305
|
+
const through = yield* journal.recover({
|
|
196
306
|
key,
|
|
197
|
-
from,
|
|
307
|
+
from: cursor,
|
|
198
308
|
intents: intents(epoch)
|
|
199
309
|
});
|
|
200
|
-
|
|
201
|
-
cursor,
|
|
202
|
-
epoch
|
|
203
|
-
});
|
|
310
|
+
if (through > cursor) yield* journal.cursors.advance(key, EDITS_CURSOR, epoch, through);
|
|
204
311
|
}),
|
|
205
312
|
absorb: Effect.gen(function* () {
|
|
206
|
-
const
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
const through = known.value.cursor;
|
|
313
|
+
const found = yield* journal.cursors.settled(key, EDITS_CURSOR);
|
|
314
|
+
if (Option.isNone(found) || found.value.cursor === 0) return;
|
|
315
|
+
const through = found.value.cursor;
|
|
210
316
|
const { snapshot, cursor } = yield* journal.load(key);
|
|
211
317
|
if (!options.holdsThrough(snapshot, through)) return;
|
|
212
|
-
yield*
|
|
213
|
-
|
|
318
|
+
const floor = yield* Option.match(Option.fromUndefinedOr(asServer), {
|
|
319
|
+
onSome: ({ journal: server, absorbed }) => Effect.gen(function* () {
|
|
320
|
+
yield* server.appendAsServer(absorbed(through), { key: `absorbed/${through}` });
|
|
321
|
+
return Math.min(through, yield* server.settledThrough);
|
|
322
|
+
}),
|
|
323
|
+
onNone: () => Effect.as(journal.append(key, options.absorbed(through, cursor), options.server), through)
|
|
324
|
+
});
|
|
325
|
+
if (floor > (yield* journal.floor(key))) yield* journal.compact(key, Sequence.make(floor));
|
|
214
326
|
})
|
|
215
327
|
};
|
|
216
328
|
};
|
|
@@ -305,6 +417,6 @@ const documentHost = (options) => {
|
|
|
305
417
|
});
|
|
306
418
|
};
|
|
307
419
|
};
|
|
308
|
-
export { TableAheadOfJournalError, documentHost, editsJournal, journalChanges, journalExchange, serveJournal };
|
|
420
|
+
export { TableAheadOfJournalError, documentHost, editsJournal, journalChanges, journalExchange, reaction, serveJournal, serverJournal };
|
|
309
421
|
|
|
310
422
|
//# sourceMappingURL=journal.js.map
|
package/dist/journal.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"journal.js","names":["JournalDocumentId","Sequence"],"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 {\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 type { Diagnostic, ReportDiagnostic } from 'foldkit-surface'\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 {\n hostDefect,\n listenerFailed,\n reportTo,\n type HostStage,\n type SyncDiagnostic,\n} from './diagnostics.js'\nimport { serveSocket, type SocketLike } from './transport.js'\n\nexport type { HostDefect, HostStage } from './diagnostics.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 * A listener that throws is reported as `ListenerFailed` and called again on\n * the next commit; a commit stream that breaks is reported as `HostDefect`\n * (`Changes`), since no notice follows it.\n */\nexport const journalChanges =\n <Shared, Principal>(\n journal: Journal<Operation, Shared, Principal, Operation>,\n documentId: string,\n options: {\n /** Where a failure is reported; the default reporter when not given, since this runs outside any context. */\n readonly diagnostics?: ReportDiagnostic | undefined\n } = {},\n ): ((listener: () => void) => () => void) =>\n listener => {\n const report = (diagnostic: SyncDiagnostic) => reportTo(options.diagnostics, diagnostic)\n const fiber = Effect.runFork(\n Stream.runForEach(\n Stream.filter(journal.subscribe, key => key === documentId),\n () =>\n Effect.try(listener).pipe(\n Effect.catch(thrown => report(listenerFailed('Notice', thrown.cause))),\n ),\n ).pipe(\n // A journal shutting down may end its stream by interrupting it, as it\n // may end it; any other cause ends every later notice unannounced.\n Effect.catchCause(cause =>\n Cause.hasInterruptsOnly(cause) ? Effect.void : report(hostDefect('Changes', cause)),\n ),\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 /**\n * Where an `opens` that failed before a notice, a notice that could not be\n * sent, or a broken commit stream is reported; the reporter in context when not given.\n */\n readonly diagnostics?: ReportDiagnostic | undefined\n },\n): (() => void) => {\n const client = journalExchange(options)\n const notices = journalChanges(options.journal, options.sync.documentId, {\n diagnostics: options.diagnostics,\n })\n const { opens, diagnostics } = options\n const report = (cause: Cause.Cause<unknown>) => reportTo(diagnostics, hostDefect('Notice', cause))\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(\n // A failed `opens` sends no notice, as a refusal does, and is reported.\n Effect.catchCause(opens, cause => Effect.as(report(cause), false)),\n ).then(open => {\n if (open) listener()\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 * Where this upgrade's diagnostics go, with its request: each `HostDefect`,\n * a failure answered \"Internal error\" (or a socket closed with 1011, or a\n * notice not sent) whose cause the replica is never told. The reporter in\n * the Effect context (`Diagnostics.Reporter`) when not given, by default the\n * log.\n */\n readonly diagnostics?:\n | ((diagnostic: Diagnostic, request: Request) => Effect.Effect<void>)\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 { diagnostics } = options\n const reporter: ReportDiagnostic | undefined =\n diagnostics === undefined ? undefined : diagnostic => diagnostics(diagnostic, request)\n const report = (stage: HostStage, cause: Cause.Cause<unknown>) =>\n reportTo(reporter, hostDefect(stage, cause))\n const defect = async (stage: HostStage, cause: Cause.Cause<unknown>) => {\n await Effect.runPromise(report(stage, cause))\n return refuse(internalError())\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.runPromiseExit(\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 )\n if (Exit.isFailure(opened)) return defect('Resolve', opened.cause)\n const { resolve, resolved } = opened.value\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 .then(\n open => Result.succeed(open),\n (error: unknown) => Result.fail(error),\n )\n if (Result.isFailure(journal)) return defect('Journal', Cause.die(journal.failure))\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: journal.success,\n principal,\n ...(settle === undefined ? {} : { settle: settle(journal.success) }),\n ...(opens === undefined ? {} : { opens: opens(principal) }),\n ...(admit === undefined\n ? {}\n : { admit: (operation: Operation) => admit(principal, operation) }),\n }\n } catch (error) {\n return defect('Exchange', Cause.die(error))\n }\n return Result.succeed({\n abandon: release,\n serve: socket => {\n const stop = serveJournal(socket, { ...exchange, diagnostics: reporter })\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 }).pipe(\n // The replica reads 1011 and no more: the cause is reported here.\n Effect.andThen(\n Option.isNone(Cause.findErrorOption(cause)) && !Cause.hasInterruptsOnly(cause)\n ? report('Revalidate', cause)\n : Effect.void,\n ),\n ),\n ),\n )\n const fiber = Effect.runFork(checking)\n socket.onClose(() => void Effect.runFork(Fiber.interrupt(fiber)))\n }\n socket.onClose(release)\n },\n })\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2FA,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,aAAkB,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,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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,CAAC,CAAC,KAED,OAAO,QACL,OAAO,OAAO,MAAM,gBAAgB,KAAK,CAAC,KAAK,CAAC,MAAM,kBAAkB,KAAK,IACzE,OAAO,cAAc,KAAK,IAC1B,OAAO,IACb,CACF,CACF,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"}
|
|
1
|
+
{"version":3,"file":"journal.js","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 {\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 type { Diagnostic, ReportDiagnostic } from 'foldkit-surface'\nimport {\n Cursor,\n DocumentId as JournalDocumentId,\n JournalError,\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 { fitWords, SyncRefusal } from './refusal.js'\nimport type { Operation, Sync, TransportClient, WrittenOperation } from './sync.js'\nimport {\n ServerOnlyMessageError,\n UnreadableHistoryError,\n UnreadableMessageError,\n UnsupportedMessageVersionError,\n} from './errors.js'\nimport { checkRevalidate } from './revalidate.js'\nimport {\n hostDefect,\n listenerFailed,\n reportTo,\n serverOnlySubmitted,\n type HostStage,\n type SyncDiagnostic,\n} from './diagnostics.js'\nimport { serveSocket, type SocketLike } from './transport.js'\nimport type { ServerJournal } from './serverJournal.js'\n\nexport type { HostDefect, HostStage } from './diagnostics.js'\nexport {\n reaction,\n serverJournal,\n type Parked,\n type Reaction,\n type ReactionOptions,\n type Requires,\n type ServerJournal,\n type ServerJournalOptions,\n type Trigger,\n} from './serverJournal.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, WrittenOperation>\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 * Where a `ServerOnlySubmitted` goes: a replica sent a Message only the\n * server appends. The reporter in context when not given, by default the log.\n */\n readonly diagnostics?: ReportDiagnostic | undefined\n}\n\nconst encodeRefusal = Schema.encodeSync(SyncRefusal)\n/** A refusal in the server's own words, which name no Entity's invariant. */\nconst invalidAs = (message: string): SyncRefusal =>\n SyncRefusal.Invalid({ entity: Option.none(), rule: Option.none(), message, path: [] })\n\n/** The version an entry claims, read before anything else of it, so a newer one is told from a malformed one. */\nconst claimedVersion = Schema.decodeUnknownOption(\n Schema.Struct({ messageVersion: Schema.optionalKey(Schema.Number) }),\n)\n\n/**\n * What the replica is told: a socket sends an error's message, and the\n * operation's id and version are another replica's. They stay on the error,\n * for the server's own logs.\n */\nconst HISTORY_UNREADABLE = 'This server cannot read the history of this document'\n\n/**\n * A stored row that will not read, as the journal reports it: a\n * `JournalError` whose cause is the codec's own error, never told by its words.\n */\nconst unreadableHistory = (\n documentId: string,\n cause: unknown,\n): Option.Option<UnreadableHistoryError> => {\n if (cause instanceof UnreadableMessageError)\n return Option.some(\n new UnreadableHistoryError({\n documentId,\n opId: cause.opId,\n version: cause.version,\n message: HISTORY_UNREADABLE,\n }),\n )\n if (cause instanceof UnsupportedMessageVersionError)\n return Option.some(\n new UnreadableHistoryError({\n documentId,\n opId: cause.opId,\n version: cause.found,\n message: HISTORY_UNREADABLE,\n }),\n )\n return Option.none()\n}\n\n/** What a replica that sent a server-only Message is told. */\nconst SERVER_ONLY_REASON = 'Only the server makes this change'\n\n/** The replica id an entry claims, for a diagnostic: read without trusting the rest of it. */\nconst replicaOf = (input: unknown): string =>\n Option.match(Schema.decodeUnknownOption(Schema.Struct({ replicaId: Schema.String }))(input), {\n onNone: () => '?',\n onSome: ({ replicaId }) => fitWords(replicaId),\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, as received, and acknowledged once committed, or already\n * committed. Every hook (`admit`, and the journal's `validate`, `authorize`,\n * `reduce` and `stamp`) sees its Message upcast to the current version. One\n * is rejected by its id when its message does not decode, it names another\n * document, the journal refuses it (`authorize`, `validate`), or it was\n * written at an older version no step reads (`Unreadable`); the replica drops\n * it, or keeps an unreadable one in `refused`, rather than send it again. An\n * entry written at a version newer than this server's fails the exchange\n * before anything is appended, so its replica waits with its outbox whole; so\n * do an entry with no id at all, a cursor ahead of the journal's, a\n * connection `opens` refuses, `admit` or the journal failing, and a stored\n * operation that will not read (`UnreadableHistoryError`). 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 contract = sync.journalContract()\n const supported = sync.codec.messageVersion\n /**\n * An entry as written, with what it means: its Message upcast to the current\n * version. Older and unread by any step is told apart, as `Unreadable`, and\n * a Message only the server appends, as `Forbidden`; anything else that\n * fails is not an operation this server accepts.\n */\n const operationOf = (\n input: unknown,\n ): Result.Result<\n { readonly written: WrittenOperation; readonly operation: Operation },\n UnreadableMessageError | ServerOnlyMessageError | 'invalid'\n > => {\n try {\n const written = sync.codec.writtenFrom(input, sync.documentId)\n return Result.succeed({ written, operation: sync.codec.normalizeOperation(written) })\n } catch (cause) {\n return Result.fail(\n cause instanceof UnreadableMessageError || cause instanceof ServerOnlyMessageError\n ? cause\n : 'invalid',\n )\n }\n }\n /** As the replica reads it: written at this server's version, with its order and actor. */\n const committedOf = (committed: Committed<Operation>) => {\n const written = {\n ...contract.operation.encode(committed.operation),\n serverSequence: committed.sequence,\n actorId: committed.actorId,\n }\n // Checked as the replica will check it: a row of another document is the server's fault.\n sync.codec.committedFrom(written, sync.documentId)\n return written\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 // A replica ahead of this server waits, its outbox whole: refused before\n // anything is appended, since a rejection would lose the edit.\n for (const input of pending) {\n const found = Option.flatMapNullishOr(claimedVersion(input), probe => probe.messageVersion)\n if (Option.isSome(found) && found.value > supported)\n return yield* Option.match(idOf(input), {\n onNone: () => Effect.fail(new Error('A pending entry names no operation')),\n onSome: opId =>\n Effect.fail(\n new UnsupportedMessageVersionError({\n opId,\n found: found.value,\n supported,\n message: `The replica writes Message version ${found.value}; this server reads up to ${supported}`,\n }),\n ),\n })\n }\n const rejected: Array<string> = []\n const refusals: Array<{ readonly opId: string; readonly refusal: unknown }> = []\n // Deprecated: the words alone, for a replica that reads `reason`.\n const reasons: Array<{ readonly opId: string; readonly reason: string }> = []\n // Words reach the person whose edit came back: a policy's own, or a fixed\n // sentence, never an error's message, which may carry internals.\n const reject = (opId: string, refusal: SyncRefusal, reason: string) => {\n rejected.push(opId)\n refusals.push({ opId, refusal: encodeRefusal(refusal) })\n reasons.push({ opId, reason })\n }\n const forbid = (opId: string, reason: string | undefined, otherwise: string) => {\n const fitted = reason === undefined ? undefined : fitWords(reason)\n reject(\n opId,\n SyncRefusal.Forbidden({ reason: Option.fromUndefinedOr(fitted) }),\n fitted ?? otherwise,\n )\n }\n const invalid = (opId: string, message: string) => reject(opId, invalidAs(message), message)\n const acknowledged: Array<string> = []\n for (const input of pending) {\n const decoded = operationOf(input)\n if (Result.isFailure(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 const failure = decoded.failure\n if (failure === 'invalid') invalid(id.value, 'Not an operation this server accepts')\n else if (failure instanceof UnreadableMessageError)\n reject(\n id.value,\n SyncRefusal.Unreadable({ version: failure.version }),\n 'Written by a version of the app this server cannot read',\n )\n else {\n forbid(id.value, SERVER_ONLY_REASON, SERVER_ONLY_REASON)\n yield* reportTo(\n options.diagnostics,\n serverOnlySubmitted(sync.documentId, id.value, replicaOf(input)),\n )\n }\n continue\n }\n const { written, operation } = decoded.success\n const admitted = options.admit === undefined ? true : options.admit(operation)\n const decision = Effect.isEffect(admitted) ? yield* admitted : admitted\n if (decision !== true) {\n forbid(\n operation.opId,\n decision === false ? undefined : decision.reason,\n 'This connection may not make changes',\n )\n continue\n }\n // As received: the journal compares a retransmission by what was sent.\n yield* journal.append(key, written, 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(() => forbid(error.opId, error.reason, 'Refused by the server')),\n InvalidOperationError: () =>\n Effect.sync(() => invalid(operation.opId, 'Not a valid operation')),\n IdentityConflictError: () =>\n Effect.sync(() => invalid(operation.opId, 'Its id was already used for another')),\n }),\n )\n }\n if (options.settle !== undefined) yield* options.settle\n // Sent only when something was refused: a replica built before `refusals`\n // decodes the reply strictly and fails on the key, so it fails only then.\n const refused = refusals.length === 0 ? {} : { refusals }\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.try({\n try: () => rows.map(committedOf),\n catch: cause => new Error('Could not read the log', { cause }),\n }).pipe(\n Effect.map(operations => ({\n operations,\n rejected,\n ...refused,\n reasons,\n acknowledged,\n more: rows.length === limit,\n epoch,\n })),\n ),\n onNone: () =>\n Effect.map(journal.load(key), loaded => ({\n operations: [],\n rejected,\n ...refused,\n reasons,\n acknowledged,\n checkpoint: {\n cursor: loaded.cursor,\n model: contract.snapshot.encode(loaded.snapshot),\n },\n epoch,\n })),\n })\n }).pipe(\n // A stored operation that will not read stops the document, typed for the server's logs.\n Effect.mapError(error =>\n error instanceof JournalError\n ? Option.getOrElse(unreadableHistory(sync.documentId, error.cause), () => error)\n : error,\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 * A listener that throws is reported as `ListenerFailed` and called again on\n * the next commit; a commit stream that breaks is reported as `HostDefect`\n * (`Changes`), since no notice follows it.\n */\nexport const journalChanges =\n <Shared, Principal>(\n journal: Journal<Operation, Shared, Principal, WrittenOperation>,\n documentId: string,\n options: {\n /** Where a failure is reported; the default reporter when not given, since this runs outside any context. */\n readonly diagnostics?: ReportDiagnostic | undefined\n } = {},\n ): ((listener: () => void) => () => void) =>\n listener => {\n const report = (diagnostic: SyncDiagnostic) => reportTo(options.diagnostics, diagnostic)\n const fiber = Effect.runFork(\n Stream.runForEach(\n Stream.filter(journal.subscribe, key => key === documentId),\n () =>\n Effect.try(listener).pipe(\n Effect.catch(thrown => report(listenerFailed('Notice', thrown.cause))),\n ),\n ).pipe(\n // A journal shutting down may end its stream by interrupting it, as it\n // may end it; any other cause ends every later notice unannounced.\n Effect.catchCause(cause =>\n Cause.hasInterruptsOnly(cause) ? Effect.void : report(hostDefect('Changes', cause)),\n ),\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 /**\n * Where an `opens` that failed before a notice, a notice that could not be\n * sent, or a broken commit stream is reported; the reporter in context when not given.\n */\n readonly diagnostics?: ReportDiagnostic | undefined\n },\n): (() => void) => {\n const client = journalExchange(options)\n const notices = journalChanges(options.journal, options.sync.documentId, {\n diagnostics: options.diagnostics,\n })\n const { opens, diagnostics } = options\n const report = (cause: Cause.Cause<unknown>) => reportTo(diagnostics, hostDefect('Notice', cause))\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(\n // A failed `opens` sends no notice, as a refusal does, and is reported.\n Effect.catchCause(opens, cause => Effect.as(report(cause), false)),\n ).then(open => {\n if (open) listener()\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, Absorbed = never> {\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, WrittenOperation>\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 * Records that the table holds every edit through `through`, as the\n * server: `absorbed(through)` is the server-only Message the replicas drop\n * those edits on hearing, appended under the key `absorbed/<through>`. The\n * log is compacted no further than the server journal's `settledThrough`,\n * so its reactions see every commit first.\n */\n readonly asServer?:\n | {\n readonly journal: ServerJournal<Absorbed, any>\n readonly absorbed: (through: number) => Absorbed\n }\n | undefined\n /**\n * @deprecated Declare the Message `serverOnly` and pass `asServer`; removed\n * in the next release. The server's operation saying the table holds every\n * edit through `through`, sequenced from `cursor`, the journal's, appended\n * as written.\n */\n readonly absorbed?: ((through: number, cursor: number) => WrittenOperation) | undefined\n /** @deprecated With `absorbed`: who the server commits it as. */\n readonly server?: Principal | undefined\n}\n\n/** The stored cursor `editsJournal` keeps: every edit at or before it is in the table. */\nconst EDITS_CURSOR = 'edits'\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 * How far the table holds is a cursor the journal stores (`journal.cursors`),\n * started at the journal's floor, where compaction left it, so a server\n * restarted over a journal that outlived it neither walks the log again nor\n * asks for history that is gone. Intents are keyed by the journal's epoch as\n * well as the operation, so after a reset an operation sent again is applied\n * again, not taken as already run.\n */\nexport const editsJournal = <Shared, Principal, Change, Absorbed = never>(\n options: EditsJournalOptions<Shared, Principal, Change, Absorbed>,\n): {\n readonly settle: Effect.Effect<void, unknown>\n readonly absorb: Effect.Effect<void, unknown>\n} => {\n const { journal, asServer } = options\n if (asServer === undefined && (options.absorbed === undefined || options.server === undefined))\n throw new Error('editsJournal: pass asServer, or absorbed with server')\n const key = JournalDocumentId.make(options.documentId)\n /** The stored cursor in the current epoch, started at the floor the first time. */\n const tracked = Effect.gen(function* () {\n const found = yield* journal.cursors.settled(key, EDITS_CURSOR)\n if (Option.isSome(found)) return found.value\n yield* journal.cursors.track(key, EDITS_CURSOR, { from: 'floor' })\n return Option.getOrThrow(yield* journal.cursors.settled(key, EDITS_CURSOR))\n })\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 const settle = Effect.gen(function* () {\n // The table must not be past the journal: every edit would be skipped.\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 // A new epoch is a new history: the stored cursor reads 0 in it.\n const { epoch, cursor } = yield* tracked\n const through = yield* journal.recover({ key, from: cursor, intents: intents(epoch) })\n if (through > cursor) yield* journal.cursors.advance(key, EDITS_CURSOR, epoch, through)\n })\n // Two absorbs at once need no lock: both name the record by `through`, so\n // the second is the first's retry, answered from history.\n const absorb = Effect.gen(function* () {\n const found = yield* journal.cursors.settled(key, EDITS_CURSOR)\n if (Option.isNone(found) || found.value.cursor === 0) return\n const through = found.value.cursor\n const { snapshot, cursor } = yield* journal.load(key)\n if (!options.holdsThrough(snapshot, through)) return\n const floor = yield* Option.match(Option.fromUndefinedOr(asServer), {\n onSome: ({ journal: server, absorbed }) =>\n Effect.gen(function* () {\n yield* server.appendAsServer(absorbed(through), { key: `absorbed/${through}` })\n return Math.min(through, yield* server.settledThrough)\n }),\n onNone: () =>\n Effect.as(\n journal.append(key, options.absorbed!(through, cursor), options.server!),\n through,\n ),\n })\n // What the log holds through `floor` is in the table and gone from the\n // snapshot; a replica behind it is sent the snapshot instead.\n if (floor > (yield* journal.floor(key))) yield* journal.compact(key, Sequence.make(floor))\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, WrittenOperation>>\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 | ((\n journal: Journal<Operation, Shared, Principal, WrittenOperation>,\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 /** 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 * Where this upgrade's diagnostics go, with its request: each `HostDefect`,\n * a failure answered \"Internal error\" (or a socket closed with 1011, or a\n * notice not sent) whose cause the replica is never told. The reporter in\n * the Effect context (`Diagnostics.Reporter`) when not given, by default the\n * log.\n */\n readonly diagnostics?:\n | ((diagnostic: Diagnostic, request: Request) => Effect.Effect<void>)\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 { diagnostics } = options\n const reporter: ReportDiagnostic | undefined =\n diagnostics === undefined ? undefined : diagnostic => diagnostics(diagnostic, request)\n const report = (stage: HostStage, cause: Cause.Cause<unknown>) =>\n reportTo(reporter, hostDefect(stage, cause))\n const defect = async (stage: HostStage, cause: Cause.Cause<unknown>) => {\n await Effect.runPromise(report(stage, cause))\n return refuse(internalError())\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.runPromiseExit(\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 )\n if (Exit.isFailure(opened)) return defect('Resolve', opened.cause)\n const { resolve, resolved } = opened.value\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 .then(\n open => Result.succeed(open),\n (error: unknown) => Result.fail(error),\n )\n if (Result.isFailure(journal)) return defect('Journal', Cause.die(journal.failure))\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: journal.success,\n principal,\n ...(settle === undefined ? {} : { settle: settle(journal.success) }),\n ...(opens === undefined ? {} : { opens: opens(principal) }),\n ...(admit === undefined\n ? {}\n : { admit: (operation: Operation) => admit(principal, operation) }),\n }\n } catch (error) {\n return defect('Exchange', Cause.die(error))\n }\n return Result.succeed({\n abandon: release,\n serve: socket => {\n const stop = serveJournal(socket, { ...exchange, diagnostics: reporter })\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 }).pipe(\n // The replica reads 1011 and no more: the cause is reported here.\n Effect.andThen(\n Option.isNone(Cause.findErrorOption(cause)) && !Cause.hasInterruptsOnly(cause)\n ? report('Revalidate', cause)\n : Effect.void,\n ),\n ),\n ),\n )\n const fiber = Effect.runFork(checking)\n socket.onClose(() => void Effect.runFork(Fiber.interrupt(fiber)))\n }\n socket.onClose(release)\n },\n })\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAoHA,MAAM,gBAAgB,OAAO,WAAW,WAAW;;AAEnD,MAAM,aAAa,YACjB,YAAY,QAAQ;CAAE,QAAQ,OAAO,KAAK;CAAG,MAAM,OAAO,KAAK;CAAG;CAAS,MAAM,CAAC;AAAE,CAAC;;AAGvF,MAAM,iBAAiB,OAAO,oBAC5B,OAAO,OAAO,EAAE,gBAAgB,OAAO,YAAY,OAAO,MAAM,EAAE,CAAC,CACrE;;;;;;AAOA,MAAM,qBAAqB;;;;;AAM3B,MAAM,qBACJ,YACA,UAC0C;CAC1C,IAAI,iBAAiB,wBACnB,OAAO,OAAO,KACZ,IAAI,uBAAuB;EACzB;EACA,MAAM,MAAM;EACZ,SAAS,MAAM;EACf,SAAS;CACX,CAAC,CACH;CACF,IAAI,iBAAiB,gCACnB,OAAO,OAAO,KACZ,IAAI,uBAAuB;EACzB;EACA,MAAM,MAAM;EACZ,SAAS,MAAM;EACf,SAAS;CACX,CAAC,CACH;CACF,OAAO,OAAO,KAAK;AACrB;;AAGA,MAAM,qBAAqB;;AAG3B,MAAM,aAAa,UACjB,OAAO,MAAM,OAAO,oBAAoB,OAAO,OAAO,EAAE,WAAW,OAAO,OAAO,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG;CAC3F,cAAc;CACd,SAAS,EAAE,gBAAgB,SAAS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