1
import { type Context, type JsonValue, replicatedState } from "@earendil-works/chord";2
import { awaitWithContext, BACKGROUND_CONTEXT, withoutAbortSignal } from "@earendil-works/chord/context";3
import { type Op, track } from "@earendil-works/chord/delta";4
import {5
type AnyDocToken,6
addressId,7
checkRecordScope,8
checkRecordVersion,9
materializeDocument,10
resolveAddress,11
} from "../documents.ts";12
import { SessionFailed, StorageRequestError } from "../errors.ts";13
import { idFromNumber } from "../ids.ts";14
import type {15
CommitChange,16
CommitPublication,17
ConversationDocFamilyToken,18
ConversationDocToken,19
ConversationId,20
ConversationQuery,21
ConversationRecord,22
Cursor,23
DocumentAddress,24
DocumentCommitChange,25
DocumentId,26
DocumentPoint,27
DocumentQuery,28
DocumentRecord,29
DocumentState,30
DocumentWatch,31
EntryId,32
EntryQuery,33
EntryRecord,34
Id,35
JsonObject,36
Page,37
RewindableConversationDocFamilyToken,38
RewindableConversationDocToken,39
Seq,40
Session,41
SessionDocFamilyToken,42
SessionDocToken,43
SessionEnd,44
Storage,45
StorageWrite,46
StoredDocument,47
SubmissionId,48
SubmissionQuery,49
SubmissionRecord,50
TaskDocFamilyToken,51
TaskDocToken,52
TaskId,53
TaskQuery,54
TaskRecord,55
Tx,56
} from "../types.ts";57
import {58
CommittedStateSource,59
CommittedWatch,60
type ObservedDocumentValue,61
RETIREMENT_OPERATIONS,62
} from "./observation.ts";63
import { type LoadedDocument, Transaction, type TransactionHost, type TransactionScope } from "./transaction.ts";65
/**66
* Open a Session kernel over one storage backend. `now` is the wall clock for task times; default `Date.now`. The first67
* error a Storage method throws fails the Session (`SessionFailed`); see `SessionImpl`.68
*/69
export function createSession(70
storage: Storage,71
options?: { readonly now?: () => number; readonly documentRetentionMs?: number },72
): Session {73
const retention = options?.documentRetentionMs;74
return new SessionImpl(storage, options?.now, retention === undefined ? undefined : () => retention);75
}77
/** Default document retention: ten minutes, as for kept contexts. */78
let defaultRetention = 600_000;80
/** Internal, for tests: the retention of every Session that keeps the default, as a suite run with eviction at once. */81
export function setDefaultDocumentRetention(ms: number): void {82
defaultRetention = ms;83
}85
/**86
* A retention as given, when it is a number of milliseconds, `0` or more (`Infinity` keeps documents); otherwise the87
* default.88
*/89
export function documentRetention(ms: number | undefined): number {90
return typeof ms === "number" && ms >= 0 ? ms : defaultRetention;91
}93
/** Longest delay `setTimeout` supports; a longer retention waits in several steps. */94
const MAX_TIMER_DELAY = 2_147_483_647;96
/**97
* Session kernel: one mutation line, the loaded document tracker cache, and committed publication.98
*99
* The cache is bounded by use: a document with no watch or document state attached leaves it once it was not read or100
* written for the retention period, and the next access loads it from Storage. Eviction runs as a job on the mutation101
* line, so no transaction ever holds a tracker that leaves.102
*103
* Only committed state is observable. Every commit callback, preparation, Storage settlement, adoption, and104
* publication enqueue runs while the line is held; listeners run later.105
*106
* Storage failures are final. Every Storage call goes through one guard: the first error a Storage method throws, other107
* than for a cancelled caller, fails the Session, as does a commit it cannot adopt. That call gets the error; every later108
* call and every Storage call still underway gets `SessionFailed`; close listeners run at once with the error, and the109
* Session then closes itself, Storage included, and `closed` settles. Nothing retries: transient errors are the110
* Storage's to retry. Reopening recovers from what was committed.111
*/112
export class SessionImpl implements Session {113
readonly #storage: Storage;114
readonly #documents = new Map<string, LoadedDocument>();115
/** Cached documents with no observer attached, by address, oldest use first, with the time of that use. */116
readonly #idleDocuments = new Map<string, number>();117
/** Observers attached per document incarnation (record ID); a cached incarnation with any is never evicted. */118
readonly #attachedDocuments = new Map<DocumentId, number>();119
readonly #clock: () => number;120
readonly #documentRetentionMs: () => number;121
/** The pending eviction: a timer for the oldest idle document, or a line job when the retention is 0. */122
#documentSweep: { readonly at: number; readonly timer: ReturnType<typeof setTimeout> | undefined } | undefined;123
#sweepJobs = 0;124
/** Set once a timer could not be unreferenced: then none is kept, and the end of each commit evicts what expired. */125
#documentTimersUnavailable = false;126
readonly #commitListeners = new Set<(publication: CommitPublication, context: Context) => void>();127
/** The Session's own listeners, such as its scheduler's: they keep memory in step with storage, so a throw fails it. */128
readonly #internalListeners = new Set<(publication: CommitPublication, context: Context) => void>();129
readonly #closeListeners = new Set<() => void>();130
readonly #host: TransactionHost;131
#tail: Promise<void> = Promise.resolve();132
#closing: Promise<void> | undefined;133
#failure: { readonly error: unknown } | undefined;134
/** Set when close reaches the backend: calls that fail from then on fail because it closes. */135
readonly #failed = Promise.withResolvers<never>();136
readonly #closed = Promise.withResolvers<SessionEnd>();138
get closed(): Promise<SessionEnd> {139
return this.#closed.promise;140
}142
/** Internal: the error that failed the Session, if one did. */143
get failure(): { readonly error: unknown } | undefined {144
return this.#failure;145
}147
/** Internal: rejects with `SessionFailed` the moment the Session fails, before work underway has ended; never resolves. */148
get failed(): Promise<never> {149
return this.#failed.promise;150
}152
constructor(153
storage: Storage,154
now: () => number = Date.now,155
documentRetentionMs: () => number | undefined = () => undefined,156
) {157
// Waits race it; none has to.158
this.#failed.promise.catch(() => {});159
this.#storage = new GuardedStorage(storage, this);160
// Cache bookkeeping must never change the outcome of the operation it follows: a clock or a retention setting161
// that throws counts as now, and as the default.162
this.#clock = () => {163
try {164
return now();165
} catch {166
return Date.now();167
}168
};169
this.#documentRetentionMs = () => {170
try {171
return documentRetention(documentRetentionMs());172
} catch {173
return documentRetention(undefined);174
}175
};176
this.#host = {177
storage: this.#storage,178
now,179
cached: (id) => {180
const cached = this.#documents.get(id);181
if (cached !== undefined) this.#touchDocument(id);182
return cached;183
},184
load: (definition, addressId, address, context) => this.#loadDocument(definition, addressId, address, context),185
install: (document) => {186
this.#documents.set(document.addressId, document);187
this.#touchDocument(document.addressId);188
},189
evict: (id, recordId) => {190
if (this.#documents.get(id)?.record.id === recordId) this.#dropDocument(id);191
},192
conversationCreated: (tx, record) => this.conversationCreated(tx, record),193
};194
}196
/** The Storage behind the failure guard; every component reads and writes through it. */197
protected get storage(): Storage {198
return this.#storage;199
}201
commit<T>(change: (tx: Tx) => T | Promise<T>, context: Context): Promise<T> {202
return this.commitWith(change, context);203
}205
/**206
* Internal: fail the Session with `error`, the first wins, and report it once. Admission ends, and close listeners run207
* now; they read the error from `failure`. The Storage guard calls this; the Harness also calls it for a throw in its208
* scheduler's own commits.209
*/210
fail(error: unknown): void {211
if (this.#failure !== undefined) return;212
this.#failure = { error };213
this.#failed.reject(new SessionFailed(error));214
// Seal first, so a report handler that calls back finds the Session failed. Closing runs the close listeners215
// synchronously; a failing backend close is the caller's to see, and here nobody waits.216
this.close(BACKGROUND_CONTEXT).catch(() => {});217
this.report(error);218
}220
/**221
* Internal commit exposing the concrete transaction and its internal operations, such as the reserved-ID root222
* bootstrap and task replacement. `scope` sets the default `tx.createTask()` conversation and the task attributed to223
* appended entries.224
*/225
commitWith<T>(change: (tx: Transaction) => T | Promise<T>, context: Context, scope?: TransactionScope): Promise<T> {226
try {227
this.assertUsable();228
} catch (error) {229
return Promise.reject(error);230
}231
return this.#enqueue(() => this.#runCommit(change, context, scope));232
}234
/** Internal: run a read-only job on the mutation line so multi-read derivations observe one committed state. */235
readOnLine<T>(job: () => Promise<T>): Promise<T> {236
try {237
this.assertUsable();238
} catch (error) {239
return Promise.reject(error);240
}241
return this.#enqueue(async () => {242
this.#assertHealthy();243
return job();244
});245
}247
/**248
* Internal: a conversation document's current incarnation and value, for a job already running on the line (see249
* `readOnLine()`). Absent documents are `undefined`.250
*/251
async conversationDocumentOnLine(252
token: ConversationDocToken<JsonObject>,253
conversationId: ConversationId,254
context: Context,255
): Promise<{ readonly record: DocumentRecord; readonly version: number; readonly value: JsonObject } | undefined> {256
const definition = token.definition;257
const resolved = resolveAddress(definition, [conversationId, context]);258
const loaded = await this.#loadDocument(definition, resolved.id, resolved.address, context);259
if (loaded === undefined) return undefined;260
checkRecordScope(definition, loaded.record);261
checkRecordVersion(definition, loaded.record, loaded.storedVersion);262
return { record: loaded.record, version: loaded.valueVersion, value: loaded.tracker.value };263
}265
snapshot<T extends JsonObject>(token: SessionDocToken<T>, context: Context): Promise<Readonly<T> | undefined>;266
snapshot<T extends JsonObject>(267
token: ConversationDocToken<T>,268
conversationId: ConversationId,269
context: Context,270
): Promise<Readonly<T> | undefined>;271
snapshot<T extends JsonObject>(272
token: TaskDocToken<T>,273
taskId: TaskId,274
context: Context,275
): Promise<Readonly<T> | undefined>;276
snapshot<T extends JsonObject, I extends JsonValue>(277
token: SessionDocFamilyToken<T, I>,278
key: string,279
context: Context,280
): Promise<Readonly<T> | undefined>;281
snapshot<T extends JsonObject, I extends JsonValue>(282
token: ConversationDocFamilyToken<T, I>,283
conversationId: ConversationId,284
key: string,285
context: Context,286
): Promise<Readonly<T> | undefined>;287
snapshot<T extends JsonObject, I extends JsonValue>(288
token: TaskDocFamilyToken<T, I>,289
taskId: TaskId,290
key: string,291
context: Context,292
): Promise<Readonly<T> | undefined>;293
async snapshot(token: AnyDocToken, ...args: readonly unknown[]): Promise<JsonObject | undefined> {294
this.assertUsable();295
const definition = token.definition;296
const resolved = resolveAddress(definition, args);297
const context = args[resolved.nextArgument] as Context;298
const cached = this.#documents.get(resolved.id);299
if (cached?.valueVersion === definition.version) this.#touchDocument(resolved.id);300
const loaded =301
cached?.valueVersion === definition.version302
? cached303
: await this.#enqueue(async () => {304
this.#assertHealthy();305
return this.#loadDocument(definition, resolved.id, resolved.address, context);306
});307
if (loaded === undefined) return undefined;308
checkRecordScope(definition, loaded.record);309
checkRecordVersion(definition, loaded.record, loaded.storedVersion);310
return loaded.tracker.value;311
}313
documentState<T extends JsonObject>(314
token: SessionDocToken<T>,315
context: Context,316
): Promise<DocumentState<T> | undefined>;317
documentState<T extends JsonObject>(318
token: ConversationDocToken<T>,319
conversationId: ConversationId,320
context: Context,321
): Promise<DocumentState<T> | undefined>;322
documentState<T extends JsonObject>(323
token: TaskDocToken<T>,324
taskId: TaskId,325
context: Context,326
): Promise<DocumentState<T> | undefined>;327
documentState<T extends JsonObject, I extends JsonValue>(328
token: SessionDocFamilyToken<T, I>,329
key: string,330
context: Context,331
): Promise<DocumentState<T> | undefined>;332
documentState<T extends JsonObject, I extends JsonValue>(333
token: ConversationDocFamilyToken<T, I>,334
conversationId: ConversationId,335
key: string,336
context: Context,337
): Promise<DocumentState<T> | undefined>;338
documentState<T extends JsonObject, I extends JsonValue>(339
token: TaskDocFamilyToken<T, I>,340
taskId: TaskId,341
key: string,342
context: Context,343
): Promise<DocumentState<T> | undefined>;344
documentState(token: AnyDocToken, ...args: readonly unknown[]): Promise<DocumentState<JsonObject> | undefined> {345
try {346
this.assertUsable();347
const definition = token.definition;348
const resolved = resolveAddress(definition, args);349
const context = args[resolved.nextArgument] as Context;350
return this.#enqueue(async () => {351
this.#assertHealthy();352
const loaded = await this.#loadDocument(definition, resolved.id, resolved.address, context);353
if (loaded === undefined) return undefined;354
const { observer: source, detach } = this.#attachDocument(355
definition,356
loaded,357
(value, release) => new CommittedStateSource<ObservedDocumentValue>(value, release),358
);359
try {360
return replicatedState(source, { onError: (error) => this.report(error) }) as DocumentState<JsonObject>;361
} catch (error) {362
detach();363
throw error;364
}365
});366
} catch (error) {367
return Promise.reject(error);368
}369
}371
watchDoc<T extends JsonObject>(token: SessionDocToken<T>, context: Context): Promise<DocumentWatch<T> | undefined>;372
watchDoc<T extends JsonObject>(373
token: ConversationDocToken<T>,374
conversationId: ConversationId,375
context: Context,376
): Promise<DocumentWatch<T> | undefined>;377
watchDoc<T extends JsonObject>(378
token: TaskDocToken<T>,379
taskId: TaskId,380
context: Context,381
): Promise<DocumentWatch<T> | undefined>;382
watchDoc<T extends JsonObject, I extends JsonValue>(383
token: SessionDocFamilyToken<T, I>,384
key: string,385
context: Context,386
): Promise<DocumentWatch<T> | undefined>;387
watchDoc<T extends JsonObject, I extends JsonValue>(388
token: ConversationDocFamilyToken<T, I>,389
conversationId: ConversationId,390
key: string,391
context: Context,392
): Promise<DocumentWatch<T> | undefined>;393
watchDoc<T extends JsonObject, I extends JsonValue>(394
token: TaskDocFamilyToken<T, I>,395
taskId: TaskId,396
key: string,397
context: Context,398
): Promise<DocumentWatch<T> | undefined>;399
async watchDoc(token: AnyDocToken, ...args: readonly unknown[]): Promise<DocumentWatch<JsonObject> | undefined> {400
this.assertUsable();401
const definition = token.definition;402
const resolved = resolveAddress(definition, args);403
const context = args[resolved.nextArgument] as Context;404
const signal = context.abortSignal;405
let cancelled = signal?.aborted ?? false;406
const markCancelled = (): void => {407
cancelled = true;408
};409
signal?.addEventListener("abort", markCancelled, { once: true });410
try {411
const watch = await this.#enqueue(async () => {412
this.#assertHealthy();413
if (cancelled) throw cancellationError(signal!);414
const loaded = await this.#loadDocument(definition, resolved.id, resolved.address, context);415
if (cancelled) throw cancellationError(signal!);416
if (loaded === undefined) return undefined;417
return this.#attachDocument(418
definition,419
loaded,420
(value, release) =>421
new CommittedWatch<ObservedDocumentValue>(value, release, (error) => this.report(error)),422
).observer;423
});424
if (watch === undefined) return undefined;425
if (cancelled) {426
watch.cancel();427
throw cancellationError(signal!);428
}429
if (signal !== undefined) watch.observeCancellation(signal);430
return watch as DocumentWatch<JsonObject>;431
} finally {432
signal?.removeEventListener("abort", markCancelled);433
}434
}436
snapshotAsOf<T extends JsonObject>(437
token: RewindableConversationDocToken<T>,438
conversationId: ConversationId,439
at: EntryId,440
context: Context,441
): Promise<Readonly<T> | undefined>;442
snapshotAsOf<T extends JsonObject, I extends JsonValue>(443
token: RewindableConversationDocFamilyToken<T, I>,444
conversationId: ConversationId,445
key: string,446
at: EntryId,447
context: Context,448
): Promise<Readonly<T> | undefined>;449
async snapshotAsOf(token: AnyDocToken, ...args: readonly unknown[]): Promise<JsonObject | undefined> {450
this.assertUsable();451
const definition = token.definition;452
const resolved = resolveAddress(definition, args);453
if (resolved.address.scope.kind !== "conversation") {454
throw new TypeError("Session.snapshotAsOf() requires a conversation document");455
}456
const conversationId = resolved.address.scope.conversationId;457
const atValue = args[resolved.nextArgument];458
if (typeof atValue !== "number" || !Number.isSafeInteger(atValue)) {459
throw new TypeError("Session.snapshotAsOf() requires an entry ID");460
}461
const at = idFromNumber<EntryId>(atValue);462
const context = args[resolved.nextArgument + 1] as Context;463
return this.#enqueue(async () => {464
this.#assertHealthy();465
const storedEntry = await this.#storage.entry(conversationId, at, context);466
if (storedEntry === undefined) {467
throw new Error(`Entry ${at} is not visible from conversation ${conversationId}`);468
}469
const address: DocumentAddress = {470
...resolved.address,471
scope: { kind: "conversation", conversationId: storedEntry.entry.conversationId },472
};473
const record = await this.#storage.findDocument(address, storedEntry.commitSeq, context);474
if (record === undefined) return undefined;475
const stored = await this.#storage.document(record.id, storedEntry.commitSeq, context);476
if (stored === undefined) {477
throw new Error(`Historical document ${record.id} (${record.kind}) cannot be read`);478
}479
return materializeDocument(definition, stored);480
});481
}483
close(context: Context): Promise<void> {484
if (this.#closing === undefined) {485
const cleanup = withoutAbortSignal(context);486
// Seal admission before anything else runs, then stop observers; admitted work settles before Storage closes.487
this.#closing = Promise.resolve()488
.then(() => this.beforeClose())489
.then(() =>490
this.#enqueue(async () => {491
this.#commitListeners.clear();492
this.#internalListeners.clear();493
this.#documents.clear();494
this.#idleDocuments.clear();495
this.#attachedDocuments.clear();496
try {497
await this.#storage.close(cleanup);498
} catch (error) {499
// A Storage that cannot close is a failed one; an earlier failure stays the cause.500
if (this.#failure === undefined) {501
this.#failure = { error };502
this.report(error);503
}504
throw error;505
}506
}),507
)508
.finally(() => {509
const failure = this.#failure;510
this.#closed.resolve(511
failure === undefined ? { reason: "closed" } : { reason: "failed", error: failure.error },512
);513
});514
this.#notifyClose();515
}516
return awaitWithContext(this.#closing, context);517
}519
/** Run the close listeners once, each on its own: one that fails is reported, and the rest still run. */520
#notifyClose(): void {521
if (this.#documentSweep?.timer !== undefined) clearTimeout(this.#documentSweep.timer);522
this.#documentSweep = undefined;523
const listeners = [...this.#closeListeners];524
this.#closeListeners.clear();525
for (const listener of listeners) contained(listener, (error) => this.report(error));526
}528
/** Internal: the Session's failure, and errors of listeners, which never fail what ran them. A plain Session drops them. */529
report(_error: unknown): void {}531
/**532
* Runs inside every transaction that creates or forks a conversation, after the conversation record is staged. A533
* plain Session stages nothing; a Harness stages its built-in documents.534
*/535
protected conversationCreated(_tx: Transaction, _record: ConversationRecord): Promise<void> {536
return Promise.resolve();537
}539
/** Runs after close seals admission and before the line closes Storage; must not reject. */540
protected beforeClose(): Promise<void> {541
return Promise.resolve();542
}544
/** Register a synchronous post-adoption listener. It must not block or call Session operations; a throw is reported. */545
subscribeCommits(listener: (publication: CommitPublication, context: Context) => void): () => void {546
this.assertUsable();547
this.#commitListeners.add(listener);548
return () => this.#commitListeners.delete(listener);549
}551
/**552
* Internal: `subscribeCommits()` for the Session's own components, whose state follows each commit. A throw leaves553
* that state behind storage, so it fails the Session instead of being reported. They run before host listeners.554
*/555
observeCommits(listener: (publication: CommitPublication, context: Context) => void): () => void {556
this.assertUsable();557
this.#internalListeners.add(listener);558
return () => this.#internalListeners.delete(listener);559
}561
/**562
* Register a listener called synchronously when close begins, also when a failure closes the Session (`failure` is563
* then set). It must not block or call Session operations; a throw is reported.564
*/565
subscribeClose(listener: () => void): () => void {566
this.assertUsable();567
this.#closeListeners.add(listener);568
return () => this.#closeListeners.delete(listener);569
}571
/** Drop every loaded tracker on the mutation line; later access cold-loads from Storage. */572
unloadDocuments(): Promise<void> {573
return this.#enqueue(async () => {574
this.#documents.clear();575
this.#idleDocuments.clear();576
});577
}579
/**580
* Internal, for tests: how many documents the cache holds, how many are idle, how many incarnations are pinned, and how581
* many sweep jobs were queued on the line so far.582
*/583
get documentCacheSizes(): {584
readonly cached: number;585
readonly idle: number;586
readonly attached: number;587
readonly sweeps: number;588
} {589
return {590
cached: this.#documents.size,591
idle: this.#idleDocuments.size,592
attached: this.#attachedDocuments.size,593
sweeps: this.#sweepJobs,594
};595
}597
/** Note a use of a cached document: an unattached one becomes the newest idle one, and an eviction is scheduled. */598
#touchDocument(addressId: string): void {599
const cached = this.#documents.get(addressId);600
if (cached === undefined || this.#attachedDocuments.has(cached.record.id)) return;601
const now = this.#clock();602
const since = this.#idleDocuments.get(addressId);603
// A hot document moves to the back at most once per granule, a tenth of the retention up to 1 s: it may then leave604
// up to a granule early, which costs a reload, while a commit-heavy workload skips the reordering.605
if (since !== undefined && now - since < Math.min(1_000, this.#documentRetentionMs() / 10)) return;606
this.#idleDocuments.delete(addressId);607
this.#idleDocuments.set(addressId, now);608
// A pending sweep for the oldest document comes first unless the retention was shortened since; then it moves up.609
if (this.#documentSweep === undefined || this.#documentSweep.at > now + this.#documentRetentionMs()) {610
this.#scheduleDocumentSweep();611
}612
}614
#dropDocument(addressId: string): void {615
this.#documents.delete(addressId);616
this.#idleDocuments.delete(addressId);617
}619
/**620
* Schedule the eviction of the oldest idle document: on the line at once when the retention is 0, otherwise when it621
* expires, by a timer that never keeps the process alive. Where timers cannot be unreferenced, as in Cloudflare622
* Workers, none is kept: the end of each commit evicts what expired.623
*/624
#scheduleDocumentSweep(): void {625
if (this.#closing !== undefined) return;626
const oldest = this.#idleDocuments.values().next();627
if (oldest.done === true) return;628
const at = oldest.value + this.#documentRetentionMs();629
if (this.#documentSweep !== undefined && this.#documentSweep.at <= at) return;630
if (this.#documentSweep?.timer !== undefined) clearTimeout(this.#documentSweep.timer);631
// The pending sweep stays set until its job runs, so touches while the line is busy queue no more.632
const sweep = { at, timer: undefined as ReturnType<typeof setTimeout> | undefined };633
const run = (): void => {634
this.#sweepJobs++;635
this.#enqueue(async () => {636
if (this.#documentSweep === sweep) this.#documentSweep = undefined;637
if (this.#closing === undefined) this.#sweepDocuments();638
}).catch(() => {});639
};640
const delay = at - this.#clock();641
this.#documentSweep = sweep;642
if (delay <= 0) {643
queueMicrotask(run);644
return;645
}646
if (this.#documentTimersUnavailable) {647
this.#documentSweep = undefined;648
return;649
}650
const timer = setTimeout(run, Math.min(delay, MAX_TIMER_DELAY));651
const unref = (timer as { unref?: unknown }).unref;652
if (typeof unref !== "function") {653
clearTimeout(timer);654
this.#documentTimersUnavailable = true;655
this.#documentSweep = undefined;656
return;657
}658
unref.call(timer);659
sweep.timer = timer;660
}662
/** On the line: evict the idle documents whose retention passed, oldest first, then schedule the next eviction. */663
#sweepDocuments(): void {664
const expired = this.#clock() - this.#documentRetentionMs();665
for (const [addressId, since] of this.#idleDocuments) {666
if (since > expired) break;667
this.#dropDocument(addressId);668
}669
this.#scheduleDocumentSweep();670
}672
/** Pin a cached incarnation for one observer; the returned release unpins it once, idle again after the last. */673
#pinDocument(addressId: string, recordId: DocumentId): () => void {674
this.#attachedDocuments.set(recordId, (this.#attachedDocuments.get(recordId) ?? 0) + 1);675
this.#idleDocuments.delete(addressId);676
let pinned = true;677
return () => {678
if (!pinned) return;679
pinned = false;680
const count = (this.#attachedDocuments.get(recordId) ?? 1) - 1;681
if (count > 0) {682
this.#attachedDocuments.set(recordId, count);683
return;684
}685
this.#attachedDocuments.delete(recordId);686
if (this.#documents.get(addressId)?.record.id === recordId) this.#touchDocument(addressId);687
};688
}690
async #runCommit<T>(691
change: (tx: Transaction) => T | Promise<T>,692
context: Context,693
scope?: TransactionScope,694
): Promise<T> {695
this.#assertHealthy();696
context.abortSignal?.throwIfAborted();697
const tx = new Transaction(this.#host, context, scope);698
let result: T;699
try {700
result = await change(tx);701
// A callback that caught a failed read must not commit, nor succeed as if it had.702
this.#assertHealthy();703
} catch (error) {704
await tx.settleFailure();705
this.#sweepDocuments();706
throw error;707
}708
let writes: readonly StorageWrite[];709
try {710
writes = await tx.settleSuccess();711
} catch (error) {712
// Settlement aborted every change already.713
this.#sweepDocuments();714
throw error;715
}716
if (writes.length === 0) {717
tx.discard();718
this.#sweepDocuments();719
return result;720
}721
let seq: Seq;722
try {723
// Once admitted, caller cancellation does not interrupt Storage settlement.724
seq = await this.#storage.commit(writes, withoutAbortSignal(context));725
} catch (error) {726
// The guard has failed the Session.727
tx.discard();728
throw error;729
}730
let documents: DocumentCommitChange[];731
try {732
documents = tx.adopt(seq);733
} catch (error) {734
// Storage already committed; a failed adoption leaves memory behind durable state.735
this.fail(error);736
throw error;737
}738
for (const document of documents) this.#touchDocument(addressId(document.record));739
this.#publish(seq, writes, documents, context);740
this.#sweepDocuments();741
return result;742
}744
#publish(745
seq: Seq,746
writes: readonly StorageWrite[],747
documents: readonly DocumentCommitChange[],748
context: Context,749
): void {750
if (this.#commitListeners.size === 0 && this.#internalListeners.size === 0) return;751
const changes: CommitChange[] = [];752
for (const write of writes) {753
switch (write.type) {754
case "conversation":755
case "entry":756
case "task":757
case "submission":758
changes.push(write);759
}760
}761
for (const document of documents) changes.push(document);762
const publication: CommitPublication = { seq, changes };763
// The commit is durable: a failing listener neither fails the commit nor skips the others.764
for (const listener of [...this.#internalListeners]) {765
contained(766
() => listener(publication, context),767
(error) => this.fail(error),768
);769
}770
for (const listener of [...this.#commitListeners]) {771
contained(772
() => listener(publication, context),773
(error) => this.report(error),774
);775
}776
}778
/**779
* Attach an observer to one committed incarnation: check the definition, then forward this incarnation's committed780
* changes and close. `detach` removes both subscriptions.781
*/782
#attachDocument<O extends CommittedStateSource | CommittedWatch>(783
definition: AnyDocToken["definition"],784
loaded: LoadedDocument,785
create: (value: JsonObject, detach: () => void) => O,786
): { observer: O; detach: () => void } {787
checkRecordScope(definition, loaded.record);788
checkRecordVersion(definition, loaded.record, loaded.storedVersion);789
let unsubscribeCommit = (): void => {};790
let unsubscribeClose = (): void => {};791
// Attached, the incarnation stays cached; once its last observer detaches, or it retires, it is idle again.792
const unpin = this.#pinDocument(loaded.addressId, loaded.record.id);793
const detach = (): void => {794
unsubscribeCommit();795
unsubscribeClose();796
unpin();797
};798
let observer: O;799
try {800
observer = create(loaded.tracker.value, detach);801
} catch (error) {802
unpin();803
throw error;804
}805
const observed = { version: loaded.valueVersion };806
unsubscribeCommit = this.observeCommits((publication, context) => {807
for (const change of publication.changes) {808
if (change.type !== "document" || change.record.id !== loaded.record.id) continue;809
// A document state's frames carry no caller cancellation; a watch observes its own cancellation.810
const frameContext = observer instanceof CommittedStateSource ? withoutAbortSignal(context) : context;811
const ops = observedOperations(observed, change);812
// A migration-only base changes nothing for an observer of the new version.813
if (ops.length === 0) continue;814
// A retired incarnation never changes again: its observers keep their last value but pin nothing.815
if (change.value === null) unpin();816
observer.advance(change.value, ops, frameContext);817
}818
});819
unsubscribeClose = this.subscribeClose(() => observer.closeSession(this.#failure));820
return { observer, detach };821
}823
async #loadDocument(824
definition: AnyDocToken["definition"],825
addressId: string,826
address: DocumentAddress,827
context: Context,828
): Promise<LoadedDocument | undefined> {829
const cached = this.#documents.get(addressId);830
// A tracker serves only tokens of the version its value was materialized for; others reload from Storage.831
if (cached?.valueVersion === definition.version) {832
this.#touchDocument(addressId);833
return cached;834
}835
if (cached !== undefined) this.#dropDocument(addressId);836
const record = await this.#storage.findDocument(address, "current", context);837
if (record === undefined) return undefined;838
const stored = await this.#storage.document(record.id, "current", context);839
if (stored === undefined) throw new Error(`Current document ${record.id} (${record.kind}) cannot be read`);840
const value = materializeDocument(definition, stored);841
const loaded: LoadedDocument = {842
addressId,843
record: stored.record,844
storedVersion: stored.version,845
valueVersion: definition.version,846
deltasSinceBase: stored.deltasSinceBase,847
tracker: track(value),848
};849
this.#documents.set(addressId, loaded);850
this.#touchDocument(addressId);851
return loaded;852
}854
#enqueue<T>(job: () => Promise<T>): Promise<T> {855
const run = this.#tail.then(job);856
this.#tail = run.then(857
() => undefined,858
() => undefined,859
);860
return run;861
}863
/** Internal: throw `SessionFailed` when failed, else an error when closing. */864
assertUsable(): void {865
this.#assertHealthy();866
if (this.#closing !== undefined) throw new Error("Session is closed");867
}869
#assertHealthy(): void {870
if (this.#failure !== undefined) throw new SessionFailed(this.#failure.error);871
}872
}874
/**875
* Run a host callback that must not fail its caller: a throw, or a promise it returns that rejects, goes to `onError`,876
* which is not awaited.877
*/878
export function contained(callback: () => unknown, onError: (error: unknown) => void): void {879
try {880
const result = callback();881
// Any thenable, also a promise from another realm; `Promise.resolve` adopts it with handlers of its own.882
if (typeof (result as { then?: unknown } | null)?.then === "function") Promise.resolve(result).catch(onError);883
} catch (error) {884
onError(error);885
}886
}888
/**889
* Operations an observer applies for one committed change. An observer hydrated under another definition version holds890
* a differently shaped value, so it receives the new value as a root replacement instead of operations for that shape.891
*/892
function observedOperations(893
observed: { version: number },894
change: Extract<DocumentCommitChange, { readonly type: "document" }>,895
): readonly Op[] {896
if (change.value === null) return RETIREMENT_OPERATIONS;897
if (change.version === observed.version) return change.ops;898
observed.version = change.version!;899
return [["r", change.value]];900
}902
function cancellationError(signal: AbortSignal): Error {903
return signal.reason instanceof Error ? signal.reason : new DOMException("The operation was aborted", "AbortError");904
}906
/** What the guard needs of its Session: the failure so far, and how to fail it. */907
type FailureLatch = {908
readonly failure: { readonly error: unknown } | undefined;909
fail(error: unknown): void;910
};912
/**913
* The Session's Storage behind its failure guard; every component of the Session reads and writes through it. Before a914
* call, a failed Session gets `SessionFailed` without reaching the backend. A call that throws fails the Session and915
* rethrows the backend's error, unless it is a `StorageRequestError` or a read whose caller's context was aborted:916
* neither says the Storage is broken.917
* `close()` always reaches the backend, so a failed Session still closes it.918
*/919
class GuardedStorage implements Storage {920
readonly #storage: Storage;921
readonly #latch: FailureLatch;922
/** Backend calls underway, also those off the Session line, which close waits for before it closes the backend. */923
readonly #underway = new Set<Promise<unknown>>();924
#closing = false;926
constructor(storage: Storage, latch: FailureLatch) {927
this.#storage = storage;928
this.#latch = latch;929
}931
/** Never exempt, whatever it throws: once admitted, whether a failed batch committed is unknown. */932
commit(writes: readonly StorageWrite[], context: Context): Promise<Seq> {933
return this.#call(undefined, () => this.#storage.commit(writes, context));934
}936
mintId<I extends Id<string>>(): Promise<I> {937
return this.#call(undefined, () => this.#storage.mintId<I>());938
}940
conversation(id: ConversationId, context: Context): Promise<ConversationRecord | undefined> {941
return this.#call(context, () => this.#storage.conversation(id, context));942
}944
scanConversations(945
query: ConversationQuery,946
limit: number,947
cursor: Cursor | undefined,948
context: Context,949
): Promise<Page<ConversationRecord, Cursor>> {950
return this.#call(context, () => this.#storage.scanConversations(query, limit, cursor, context));951
}953
entry(id: EntryId, context: Context): Promise<{ readonly entry: EntryRecord; readonly commitSeq: Seq } | undefined>;954
entry(955
conversationId: ConversationId,956
id: EntryId,957
context: Context,958
): Promise<{ readonly entry: EntryRecord; readonly commitSeq: Seq } | undefined>;959
entry(960
first: EntryId | ConversationId,961
second: EntryId | Context,962
third?: Context,963
): Promise<{ readonly entry: EntryRecord; readonly commitSeq: Seq } | undefined> {964
if (third === undefined) {965
const context = second as Context;966
return this.#call(context, () => this.#storage.entry(first as EntryId, context));967
}968
return this.#call(third, () => this.#storage.entry(first as ConversationId, second as EntryId, third));969
}971
findLatestHeadMarker(972
conversationId: ConversationId,973
atOrBeforeEntryId: EntryId | undefined,974
context: Context,975
): Promise<(EntryRecord & { readonly head: EntryId }) | undefined> {976
return this.#call(context, () => this.#storage.findLatestHeadMarker(conversationId, atOrBeforeEntryId, context));977
}979
scanEntries(980
query: EntryQuery,981
limit: number,982
cursor: Cursor | undefined,983
context: Context,984
): Promise<Page<EntryRecord, Cursor>> {985
return this.#call(context, () => this.#storage.scanEntries(query, limit, cursor, context));986
}988
task(id: TaskId, context: Context): Promise<TaskRecord<JsonValue, JsonValue, JsonValue> | undefined> {989
return this.#call(context, () => this.#storage.task(id, context));990
}992
scanTasks(993
query: TaskQuery,994
limit: number,995
cursor: Cursor | undefined,996
context: Context,997
): Promise<Page<TaskRecord<JsonValue, JsonValue, JsonValue>, Cursor>> {998
return this.#call(context, () => this.#storage.scanTasks(query, limit, cursor, context));999
}1001
submission(id: SubmissionId, context: Context): Promise<SubmissionRecord | undefined> {1002
return this.#call(context, () => this.#storage.submission(id, context));1003
}1005
scanSubmissions(1006
query: SubmissionQuery,1007
limit: number,1008
cursor: Cursor | undefined,1009
context: Context,1010
): Promise<Page<SubmissionRecord, Cursor>> {1011
return this.#call(context, () => this.#storage.scanSubmissions(query, limit, cursor, context));1012
}1014
submissionByRequest(1015
conversationId: ConversationId,1016
requestId: string,1017
context: Context,1018
): Promise<SubmissionRecord | undefined> {1019
return this.#call(context, () => this.#storage.submissionByRequest(conversationId, requestId, context));1020
}1022
findDocument(address: DocumentAddress, at: DocumentPoint, context: Context): Promise<DocumentRecord | undefined> {1023
return this.#call(context, () => this.#storage.findDocument(address, at, context));1024
}1026
document(id: DocumentId, at: DocumentPoint, context: Context): Promise<StoredDocument | undefined> {1027
return this.#call(context, () => this.#storage.document(id, at, context));1028
}1030
scanDocuments(1031
query: DocumentQuery,1032
limit: number,1033
cursor: Cursor | undefined,1034
context: Context,1035
): Promise<Page<DocumentRecord, Cursor>> {1036
return this.#call(context, () => this.#storage.scanDocuments(query, limit, cursor, context));1037
}1039
/**1040
* Close the backend once every call underway has settled, so none outlives it or fails after `closed` settles. New1041
* calls are refused from here on: a paged read must not start its next page while the backend closes.1042
*/1043
async close(context: Context): Promise<void> {1044
this.#closing = true;1045
await Promise.allSettled([...this.#underway]);1046
return this.#storage.close(context);1047
}1049
/**1050
* Run one backend call under the guard. `read` is a read's context; `commit()` and `mintId()` pass none, so nothing1051
* exempts their errors: once a batch is admitted, whether it committed is unknown. A call still underway when another1052
* fails the Session ends with `SessionFailed` too, whatever it returns: nothing it read or wrote is used.1053
*/1054
async #call<T>(read: Context | undefined, run: () => Promise<T>): Promise<T> {1055
this.#assertHealthy();1056
if (this.#closing) throw new Error("Session is closed");1057
let result: T;1058
// An async wrapper, so a backend that throws synchronously is guarded too.1059
const call = (async () => run())();1060
this.#underway.add(call);1061
try {1062
result = await call;1063
} catch (error) {1064
this.#assertHealthy();1065
// An invalid read, or one its caller cancelled, says nothing about the Storage; it fails that call only.1066
const exempt =1067
read !== undefined && (error instanceof StorageRequestError || read.abortSignal?.aborted === true);1068
if (!exempt) this.#latch.fail(error);1069
throw error;1070
} finally {1071
this.#underway.delete(call);1072
}1073
this.#assertHealthy();1074
return result;1075
}1077
#assertHealthy(): void {1078
const failure = this.#latch.failure;1079
if (failure !== undefined) throw new SessionFailed(failure.error);1080
}1081
}