@tearleads/client-sdk 0.1.210 → 0.1.212

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.
Files changed (76) hide show
  1. package/client/organizations/index.js +5 -5
  2. package/client/organizations/index.js.map +1 -1
  3. package/client/organizations/principalMutationScope.js +7 -1
  4. package/client/organizations/principalMutationScope.js.map +1 -1
  5. package/client/organizations/principalMutations.d.ts +8 -6
  6. package/client/organizations/principalMutations.js +8 -8
  7. package/client/organizations/principalMutations.js.map +1 -1
  8. package/client/organizations/recipientAdmission.d.ts +2 -1
  9. package/client/organizations/recipientAdmission.js +2 -2
  10. package/client/organizations/recipientAdmission.js.map +1 -1
  11. package/client/runtime/workflowRuntime.d.ts +2 -1
  12. package/client/runtime/workflowRuntime.js +1 -1
  13. package/client/runtime/workflowRuntime.js.map +1 -1
  14. package/data/persistence/container-contents/containerContentsPersistence.js +2 -2
  15. package/data/persistence/container-contents/containerContentsPersistence.js.map +1 -1
  16. package/data/persistence/container-contents/containerMetadataMutationPersistence.js +2 -2
  17. package/data/persistence/container-contents/containerMetadataMutationPersistence.js.map +1 -1
  18. package/data/persistence/container-contents/containerMetadataPullContinuationPersistence.js +2 -2
  19. package/data/persistence/container-contents/containerMetadataPullContinuationPersistence.js.map +1 -1
  20. package/data/persistence/container-contents/containerPendingUpdatePersistence.js +6 -6
  21. package/data/persistence/container-contents/containerPendingUpdatePersistence.js.map +1 -1
  22. package/data/persistence/documents/internal/discardDocument.js +4 -4
  23. package/data/persistence/documents/internal/discardDocument.js.map +1 -1
  24. package/data/persistence/documents/internal/discoveredDocumentUpsert.js +3 -3
  25. package/data/persistence/documents/internal/discoveredDocumentUpsert.js.map +1 -1
  26. package/data/persistence/documents/internal/documentDeletionPersistence.js +8 -8
  27. package/data/persistence/documents/internal/documentDeletionPersistence.js.map +1 -1
  28. package/data/persistence/documents/internal/documentMutationPersistence.js +4 -3
  29. package/data/persistence/documents/internal/documentMutationPersistence.js.map +1 -1
  30. package/data/persistence/documents/internal/documentPullContinuationPersistence.js +2 -2
  31. package/data/persistence/documents/internal/documentPullContinuationPersistence.js.map +1 -1
  32. package/data/persistence/documents/internal/rowQueryPersistence.js +3 -3
  33. package/data/persistence/documents/internal/rowQueryPersistence.js.map +1 -1
  34. package/data/persistence/documents/internal/syncQueuePersistence.js +12 -13
  35. package/data/persistence/documents/internal/syncQueuePersistence.js.map +1 -1
  36. package/data/persistence/documents/records/documentHistoryPersistence.d.ts +24 -20
  37. package/data/persistence/documents/records/documentHistoryPersistence.js +59 -90
  38. package/data/persistence/documents/records/documentHistoryPersistence.js.map +1 -1
  39. package/data/persistence/documents/records/documentPendingUpdatePersistence.d.ts +10 -25
  40. package/data/persistence/documents/records/documentPendingUpdatePersistence.js +19 -79
  41. package/data/persistence/documents/records/documentPendingUpdatePersistence.js.map +1 -1
  42. package/data/persistence/documents/records/documentQueuedUpdateReplacement.d.ts +4 -14
  43. package/data/persistence/documents/records/documentQueuedUpdateReplacement.js +27 -42
  44. package/data/persistence/documents/records/documentQueuedUpdateReplacement.js.map +1 -1
  45. package/data/persistence/documents/records/documentRecordPersistence.d.ts +5 -8
  46. package/data/persistence/documents/records/documentRecordPersistence.js +2 -55
  47. package/data/persistence/documents/records/documentRecordPersistence.js.map +1 -1
  48. package/data/persistence/documents/records/documentRecordRepository.d.ts +133 -0
  49. package/data/persistence/documents/records/documentRecordRepository.js +286 -0
  50. package/data/persistence/documents/records/documentRecordRepository.js.map +1 -0
  51. package/data/persistence/documents/records/documentSyncFailurePersistence.d.ts +9 -12
  52. package/data/persistence/documents/records/documentSyncFailurePersistence.js +19 -34
  53. package/data/persistence/documents/records/documentSyncFailurePersistence.js.map +1 -1
  54. package/data/persistence/documents/records/index.d.ts +4 -19
  55. package/data/persistence/documents/records/index.js +5 -29
  56. package/data/persistence/documents/records/index.js.map +1 -1
  57. package/package.json +1 -1
  58. package/stores/documents/documentStore/sync/attachmentUploadFailure.js +2 -2
  59. package/stores/documents/documentStore/sync/attachmentUploadFailure.js.map +1 -1
  60. package/stores/documents/documentStore/sync/syncAttachments.js +2 -2
  61. package/stores/documents/documentStore/sync/syncAttachments.js.map +1 -1
  62. package/stores/documents/documentStore/sync/syncShared.js +2 -2
  63. package/stores/documents/documentStore/sync/syncShared.js.map +1 -1
  64. package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js +2 -2
  65. package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js.map +1 -1
  66. package/workflows/container-contents/pendingWrites/index.js +4 -3
  67. package/workflows/container-contents/pendingWrites/index.js.map +1 -1
  68. package/workflows/container-contents/recovery/accessRestoration.js +2 -2
  69. package/workflows/container-contents/recovery/accessRestoration.js.map +1 -1
  70. package/workflows/documents/index.d.ts +1 -1
  71. package/workflows/documents/index.js +1 -1
  72. package/workflows/documents/index.js.map +1 -1
  73. package/workflows/documents/syncRekeys/syncRecoveryRekey.js +3 -2
  74. package/workflows/documents/syncRekeys/syncRecoveryRekey.js.map +1 -1
  75. package/workflows/organizations/readModel/listLocalOrganizations.js +2 -2
  76. package/workflows/organizations/readModel/listLocalOrganizations.js.map +1 -1
@@ -0,0 +1,133 @@
1
+ import { type DocumentSyncPullContinuation } from "../../../documents/shared/sync/pullContinuation.js";
2
+ import { type ExecSql } from "../../../sqlite/sqlSchema.js";
3
+ import { type DocumentHistoryCheckpointReplacement, type DocumentHistoryRestoreState, type DocumentHistoryTailEntry, type DocumentHistoryTailSize, type DocumentHistoryUpdateOrigin } from "./documentHistoryPersistence.js";
4
+ import type { DocumentRecord, DocumentScope, PendingUpdateFields, QueuedPendingUpdateRecord } from "./documentPersistenceTypes.js";
5
+ import { type QueuedUpdateReplacement } from "./documentQueuedUpdateReplacement.js";
6
+ import { type DocumentSyncFailureFields } from "./documentSyncFailurePersistence.js";
7
+ /** The exact continuation `invalidateDocumentSyncPullContinuation` replaces. */
8
+ export interface DocumentSyncPullContinuationInvalidation {
9
+ accessEpoch: number;
10
+ accessStateHash: string | null;
11
+ appKind: string;
12
+ continuation: DocumentSyncPullContinuation;
13
+ contentKeyBundle: string | null;
14
+ documentId: string;
15
+ documentKekTargets: string | null;
16
+ documentManifestBundle: string | null;
17
+ lastCommitLsn: string | null;
18
+ localId: string;
19
+ }
20
+ /**
21
+ * A document scope's record row, its history checkpoint and tail, its queue
22
+ * of pending updates and its recorded sync failure, bound to one executor
23
+ * and clock. Each method keeps the transaction shape it always had: reads
24
+ * run on the bound handle, writers run their own serialized mutation (or an
25
+ * immediate transaction where noted). Build it from the executor you hold;
26
+ * inside a locked section that is the locked handle. Work inside a caller's
27
+ * transaction takes the handle per call through the `*InTransaction`
28
+ * functions instead.
29
+ */
30
+ export declare class DocumentRecordRepository {
31
+ private readonly execSql;
32
+ private readonly now;
33
+ constructor(execSql: ExecSql, now?: () => Date);
34
+ /** Replace only the exact rejected continuation with a durable recovery marker. */
35
+ invalidateDocumentSyncPullContinuation(input: DocumentSyncPullContinuationInvalidation): Promise<DocumentRecord | null>;
36
+ loadDocumentRecord(scope: DocumentScope): Promise<DocumentRecord | null>;
37
+ findLocalIdByDocumentId(appKind: string, documentId: string): Promise<string | null>;
38
+ /**
39
+ * `findLocalIdByDocumentId` for many document ids: one read per chunk, in
40
+ * the same preference order, keeping the first row per document id.
41
+ */
42
+ findLocalIdsByDocumentIds(appKind: string, documentIds: ReadonlyArray<string>): Promise<Map<string, string>>;
43
+ deleteDocumentRecord(scope: DocumentScope): Promise<void>;
44
+ listDocumentPendingUpdates(scope: DocumentScope): Promise<QueuedPendingUpdateRecord[]>;
45
+ /**
46
+ * Queue an update that has no history-tail role: container metadata (its
47
+ * content is its checkpoint) and full-state re-uploads after a remote reset.
48
+ */
49
+ enqueueDocumentPendingUpdate(scope: DocumentScope, pendingUpdate: PendingUpdateFields): Promise<string>;
50
+ /**
51
+ * Append a locally authored update to the history tail AND queue it, as one
52
+ * row in one immediate transaction. A crash can therefore never leave the
53
+ * op restorable from history while missing from the outgoing queue, where a
54
+ * null-marker restore would classify it as covered and never send it.
55
+ */
56
+ enqueueDocumentPendingUpdateWithHistory(scope: DocumentScope, pendingUpdate: PendingUpdateFields, options?: {
57
+ expectedDocumentId: string | null;
58
+ expectedRecoveryGeneration: number;
59
+ }): Promise<string | null>;
60
+ /**
61
+ * Reset the durable re-key budget for every queued update in a scope. The
62
+ * cap exists to stop a server that keeps conflicting fresh ids from driving
63
+ * a network-speed loop — but a budget burned during an unrelated outage
64
+ * (e.g. yesterday's stale-bundle deadlock 409ing every submit) should not
65
+ * be terminal forever. An explicit manual retry is the deliberate,
66
+ * rate-limited signal that conditions changed, so it gets a fresh budget.
67
+ */
68
+ resetDocumentPendingUpdateRekeyBudget(scope: DocumentScope): Promise<void>;
69
+ /** See `MAX_PENDING_UPDATE_REKEYS`: the new id, or null with no progress. */
70
+ rekeyDocumentPendingUpdate(id: string): Promise<string | null>;
71
+ /** Settle one queued update by id, whatever its scope. */
72
+ settleDocumentPendingUpdate(id: string): Promise<void>;
73
+ unqueueDocumentPendingUpdates(scope: DocumentScope): Promise<void>;
74
+ /**
75
+ * Replace queued local updates with one merged update, all or nothing, in
76
+ * one immediate transaction. Every check must hold or nothing changes and
77
+ * the result is null: the document still has the captured document id and
78
+ * recovery generation, and the members are still queued under their ids as
79
+ * ordinary local rows (no outbox row, no rotation checkpoint) forming one
80
+ * contiguous run in queue order that starts with the first listed member.
81
+ *
82
+ * The first member's row is updated in place, so it keeps its row id,
83
+ * `created_at` and rowid (its queue and history-tail position), and
84
+ * receives a fresh update id (an id is never reused for different
85
+ * content), the merged data and vectors, and `rekeyCount`. The other
86
+ * members are deleted. Resolves to the merged row's new update id.
87
+ */
88
+ replaceDocumentQueuedUpdates(scope: DocumentScope, replacement: QueuedUpdateReplacement): Promise<string | null>;
89
+ appendDocumentHistoryUpdates(scope: DocumentScope, updates: readonly string[], origin: DocumentHistoryUpdateOrigin): Promise<void>;
90
+ /**
91
+ * The checkpoint + ordered tail for a scope, or null when NEITHER exists (a
92
+ * discovered shell that has not hydrated content yet; the caller starts the
93
+ * document empty and the remote pull supplies the content). A tail WITHOUT
94
+ * a checkpoint — a crash between the first enqueued edit's tail append and
95
+ * the birth-checkpoint seed — restores as tail-only (`snapshot: ""`): those
96
+ * tail rows can be the only durable copy of a local edit, so they must
97
+ * never be silently ignored.
98
+ */
99
+ loadDocumentHistoryRestoreState(scope: DocumentScope): Promise<DocumentHistoryRestoreState | null>;
100
+ /**
101
+ * Size of the tail compaction can shrink. Queued rows are excluded: they
102
+ * stay until settlement, so counting them would re-export full history on
103
+ * every persist while offline edits wait to sync.
104
+ */
105
+ readDocumentHistoryTailSize(scope: DocumentScope): Promise<DocumentHistoryTailSize>;
106
+ /**
107
+ * The current compactable tail rows WITH their payloads, so a compactor can
108
+ * prove each row's ops are covered by the snapshot it is about to install
109
+ * (another pane's append may carry ops this pane's document has not merged
110
+ * yet). Queued rows are never candidates.
111
+ */
112
+ listDocumentHistoryTailEntries(scope: DocumentScope): Promise<DocumentHistoryTailEntry[]>;
113
+ /**
114
+ * Replace the scope's checkpoint with a fresh full-history snapshot and
115
+ * delete ONLY the tail rows the caller captured before exporting it. Every
116
+ * append path writes its tail row after the ops are already in the live
117
+ * document, so any row captured before the export is provably covered by
118
+ * the snapshot — while a row appended concurrently (between export and
119
+ * this delete) survives for the next compaction instead of being lost.
120
+ */
121
+ replaceDocumentHistoryCheckpoint(scope: DocumentScope, input: DocumentHistoryCheckpointReplacement): Promise<boolean>;
122
+ deleteDocumentHistory(scope: DocumentScope): Promise<void>;
123
+ /**
124
+ * Record the last terminal failure or incoming-update quarantine on the
125
+ * scope's row; the caller supplies `attemptedAt`. A scope with no
126
+ * `documents` row has nothing left to explain, so it is a no-op there.
127
+ */
128
+ recordDocumentSyncFailure(scope: DocumentScope, failure: DocumentSyncFailureFields): Promise<void>;
129
+ /** Whether any queued local write has recorded a terminal failure. */
130
+ hasRecordedTerminalSyncFailures(): Promise<boolean>;
131
+ /** Drop the recorded failure for a scope. */
132
+ clearDocumentSyncFailure(scope: DocumentScope): Promise<void>;
133
+ }
@@ -0,0 +1,286 @@
1
+ import { and, eq, inArray, sql } from "drizzle-orm";
2
+ import { DOCUMENT_SYNC_PULL_RECOVERY_REQUIRED, serializeDocumentSyncPullContinuation, } from "../../../documents/shared/sync/pullContinuation.js";
3
+ import { localIntentTables } from "../../../sqlite/schema/index.js";
4
+ import { documentHistoryUpdates, documents, documentTables, } from "../../../sqlite/schema/documentRecordSchema.js";
5
+ import { sqliteRowsPerStatement } from "../../../sqlite/sqliteBindBudget.js";
6
+ import { getClientSQLitePersistenceRuntime } from "../../../sqlite/sqlitePersistenceRuntime.js";
7
+ import { ensureSqlTables, runSerializedSqlMutation, } from "../../../sqlite/sqlSchema.js";
8
+ import { deleteDocumentHistoryInTransaction, insertDocumentHistoryUpdatesInTransaction, replaceDocumentHistoryCheckpointInTransaction, selectDocumentHistoryRestoreState, selectDocumentHistoryTailEntries, selectDocumentHistoryTailSize, } from "./documentHistoryPersistence.js";
9
+ import { documentWriteFenceMatchesInTransaction, insertDocumentPendingUpdateInTransaction, insertDocumentPendingUpdateWithHistoryInTransaction, queuedInScope, rekeyDocumentPendingUpdateInTransaction, selectDocumentPendingUpdates, settleDocumentPendingUpdateInTransaction, unqueueDocumentScopesInTransaction, } from "./documentPendingUpdatePersistence.js";
10
+ import { replaceDocumentQueuedUpdatesInTransaction, } from "./documentQueuedUpdateReplacement.js";
11
+ import { documentRecordSelection, localIdPreferenceOrder, mapSelectedDocumentRecord, } from "./documentRecordPersistence.js";
12
+ import { clearDocumentSyncFailureInTransaction, recordDocumentSyncFailureInTransaction, selectHasRecordedTerminalSyncFailures, } from "./documentSyncFailurePersistence.js";
13
+ /**
14
+ * A document scope's record row, its history checkpoint and tail, its queue
15
+ * of pending updates and its recorded sync failure, bound to one executor
16
+ * and clock. Each method keeps the transaction shape it always had: reads
17
+ * run on the bound handle, writers run their own serialized mutation (or an
18
+ * immediate transaction where noted). Build it from the executor you hold;
19
+ * inside a locked section that is the locked handle. Work inside a caller's
20
+ * transaction takes the handle per call through the `*InTransaction`
21
+ * functions instead.
22
+ */
23
+ export class DocumentRecordRepository {
24
+ execSql;
25
+ now;
26
+ constructor(execSql, now = () => new Date()) {
27
+ this.execSql = execSql;
28
+ this.now = now;
29
+ }
30
+ /** Replace only the exact rejected continuation with a durable recovery marker. */
31
+ async invalidateDocumentSyncPullContinuation(input) {
32
+ await ensureSqlTables(this.execSql, documentTables);
33
+ const expectedContinuation = serializeDocumentSyncPullContinuation(input.continuation);
34
+ if (expectedContinuation === null)
35
+ return null;
36
+ return runSerializedSqlMutation(this.execSql, async (lockedExecSql) => {
37
+ const { db } = getClientSQLitePersistenceRuntime(lockedExecSql);
38
+ await db
39
+ .update(documents)
40
+ .set({ pullContinuation: DOCUMENT_SYNC_PULL_RECOVERY_REQUIRED })
41
+ .where(and(eq(documents.appKind, input.appKind), eq(documents.localId, input.localId), eq(documents.documentId, input.documentId), eq(documents.accessEpoch, input.accessEpoch), sql `${documents.accessStateHash} IS ${input.accessStateHash}`, sql `${documents.contentKeyBundle} IS ${input.contentKeyBundle}`, sql `${documents.documentKekTargets} IS ${input.documentKekTargets}`, sql `${documents.documentManifestBundle} IS ${input.documentManifestBundle}`, sql `${documents.lastCommitLsn} IS ${input.lastCommitLsn}`, eq(documents.pullContinuation, expectedContinuation)))
42
+ .run();
43
+ return new DocumentRecordRepository(lockedExecSql, this.now).loadDocumentRecord({ appKind: input.appKind, localId: input.localId });
44
+ });
45
+ }
46
+ async loadDocumentRecord(scope) {
47
+ const { db } = getClientSQLitePersistenceRuntime(this.execSql);
48
+ const rows = await db
49
+ .select(documentRecordSelection)
50
+ .from(documents)
51
+ .where(and(eq(documents.appKind, scope.appKind), eq(documents.localId, scope.localId)))
52
+ .limit(1);
53
+ return rows[0] ? mapSelectedDocumentRecord(rows[0]) : null;
54
+ }
55
+ async findLocalIdByDocumentId(appKind, documentId) {
56
+ const { db } = getClientSQLitePersistenceRuntime(this.execSql);
57
+ const rows = await db
58
+ .select({ localId: documents.localId })
59
+ .from(documents)
60
+ .where(and(eq(documents.appKind, appKind), eq(documents.documentId, documentId)))
61
+ .orderBy(...localIdPreferenceOrder())
62
+ .limit(1);
63
+ return rows[0]?.localId ?? null;
64
+ }
65
+ /**
66
+ * `findLocalIdByDocumentId` for many document ids: one read per chunk, in
67
+ * the same preference order, keeping the first row per document id.
68
+ */
69
+ async findLocalIdsByDocumentIds(appKind, documentIds) {
70
+ const { db } = getClientSQLitePersistenceRuntime(this.execSql);
71
+ const localIds = new Map();
72
+ const unique = Array.from(new Set(documentIds));
73
+ // One bind for the app kind; the rest carry document ids.
74
+ const chunkSize = sqliteRowsPerStatement(1, 1);
75
+ for (let offset = 0; offset < unique.length; offset += chunkSize) {
76
+ const rows = await db
77
+ .select({
78
+ documentId: documents.documentId,
79
+ localId: documents.localId,
80
+ })
81
+ .from(documents)
82
+ .where(and(eq(documents.appKind, appKind), inArray(documents.documentId, unique.slice(offset, offset + chunkSize))))
83
+ .orderBy(...localIdPreferenceOrder());
84
+ for (const row of rows) {
85
+ if (row.documentId !== null && !localIds.has(row.documentId)) {
86
+ localIds.set(row.documentId, row.localId);
87
+ }
88
+ }
89
+ }
90
+ return localIds;
91
+ }
92
+ async deleteDocumentRecord(scope) {
93
+ await getClientSQLitePersistenceRuntime(this.execSql).runMutation(async (db) => {
94
+ await db
95
+ .delete(documents)
96
+ .where(and(eq(documents.appKind, scope.appKind), eq(documents.localId, scope.localId)))
97
+ .run();
98
+ });
99
+ }
100
+ async listDocumentPendingUpdates(scope) {
101
+ const { db } = getClientSQLitePersistenceRuntime(this.execSql);
102
+ return selectDocumentPendingUpdates(db, scope);
103
+ }
104
+ /**
105
+ * Queue an update that has no history-tail role: container metadata (its
106
+ * content is its checkpoint) and full-state re-uploads after a remote reset.
107
+ */
108
+ async enqueueDocumentPendingUpdate(scope, pendingUpdate) {
109
+ const updateId = crypto.randomUUID();
110
+ await getClientSQLitePersistenceRuntime(this.execSql).runMutation(async (db) => {
111
+ await insertDocumentPendingUpdateInTransaction(db, {
112
+ createdAt: this.now().toISOString(),
113
+ pendingUpdate,
114
+ scope,
115
+ updateId,
116
+ });
117
+ });
118
+ return updateId;
119
+ }
120
+ /**
121
+ * Append a locally authored update to the history tail AND queue it, as one
122
+ * row in one immediate transaction. A crash can therefore never leave the
123
+ * op restorable from history while missing from the outgoing queue, where a
124
+ * null-marker restore would classify it as covered and never send it.
125
+ */
126
+ async enqueueDocumentPendingUpdateWithHistory(scope, pendingUpdate, options) {
127
+ const createdAt = this.now().toISOString();
128
+ return getClientSQLitePersistenceRuntime(this.execSql).transaction(async (tx) => {
129
+ if (options &&
130
+ !(await documentWriteFenceMatchesInTransaction(tx, scope, options))) {
131
+ return null;
132
+ }
133
+ return insertDocumentPendingUpdateWithHistoryInTransaction({
134
+ createdAt,
135
+ pendingUpdate,
136
+ scope,
137
+ tx,
138
+ });
139
+ }, { behavior: "immediate" });
140
+ }
141
+ /**
142
+ * Reset the durable re-key budget for every queued update in a scope. The
143
+ * cap exists to stop a server that keeps conflicting fresh ids from driving
144
+ * a network-speed loop — but a budget burned during an unrelated outage
145
+ * (e.g. yesterday's stale-bundle deadlock 409ing every submit) should not
146
+ * be terminal forever. An explicit manual retry is the deliberate,
147
+ * rate-limited signal that conditions changed, so it gets a fresh budget.
148
+ */
149
+ async resetDocumentPendingUpdateRekeyBudget(scope) {
150
+ await getClientSQLitePersistenceRuntime(this.execSql).runMutation(async (db) => {
151
+ await db
152
+ .update(documentHistoryUpdates)
153
+ .set({ rekeyCount: 0 })
154
+ .where(queuedInScope(scope));
155
+ });
156
+ }
157
+ /** See `MAX_PENDING_UPDATE_REKEYS`: the new id, or null with no progress. */
158
+ async rekeyDocumentPendingUpdate(id) {
159
+ const nextId = crypto.randomUUID();
160
+ const rekeyed = await getClientSQLitePersistenceRuntime(this.execSql).runMutation((db) => rekeyDocumentPendingUpdateInTransaction(db, id, nextId));
161
+ return rekeyed ? nextId : null;
162
+ }
163
+ /** Settle one queued update by id, whatever its scope. */
164
+ async settleDocumentPendingUpdate(id) {
165
+ await getClientSQLitePersistenceRuntime(this.execSql).runMutation(async (db) => {
166
+ await settleDocumentPendingUpdateInTransaction(db, id);
167
+ });
168
+ }
169
+ async unqueueDocumentPendingUpdates(scope) {
170
+ await getClientSQLitePersistenceRuntime(this.execSql).runMutation(async (db) => {
171
+ await unqueueDocumentScopesInTransaction(db, [scope]);
172
+ });
173
+ }
174
+ /**
175
+ * Replace queued local updates with one merged update, all or nothing, in
176
+ * one immediate transaction. Every check must hold or nothing changes and
177
+ * the result is null: the document still has the captured document id and
178
+ * recovery generation, and the members are still queued under their ids as
179
+ * ordinary local rows (no outbox row, no rotation checkpoint) forming one
180
+ * contiguous run in queue order that starts with the first listed member.
181
+ *
182
+ * The first member's row is updated in place, so it keeps its row id,
183
+ * `created_at` and rowid (its queue and history-tail position), and
184
+ * receives a fresh update id (an id is never reused for different
185
+ * content), the merged data and vectors, and `rekeyCount`. The other
186
+ * members are deleted. Resolves to the merged row's new update id.
187
+ */
188
+ async replaceDocumentQueuedUpdates(scope, replacement) {
189
+ if (replacement.memberUpdateIds.length < 2)
190
+ return null;
191
+ return getClientSQLitePersistenceRuntime(this.execSql).transaction((tx) => replaceDocumentQueuedUpdatesInTransaction(tx, scope, replacement), { behavior: "immediate" });
192
+ }
193
+ async appendDocumentHistoryUpdates(scope, updates, origin) {
194
+ if (updates.length === 0) {
195
+ return;
196
+ }
197
+ await ensureSqlTables(this.execSql, documentTables);
198
+ const createdAt = this.now().toISOString();
199
+ await getClientSQLitePersistenceRuntime(this.execSql).runMutation((db) => insertDocumentHistoryUpdatesInTransaction(db, {
200
+ createdAt,
201
+ origin,
202
+ scope,
203
+ updates,
204
+ }));
205
+ }
206
+ /**
207
+ * The checkpoint + ordered tail for a scope, or null when NEITHER exists (a
208
+ * discovered shell that has not hydrated content yet; the caller starts the
209
+ * document empty and the remote pull supplies the content). A tail WITHOUT
210
+ * a checkpoint — a crash between the first enqueued edit's tail append and
211
+ * the birth-checkpoint seed — restores as tail-only (`snapshot: ""`): those
212
+ * tail rows can be the only durable copy of a local edit, so they must
213
+ * never be silently ignored.
214
+ */
215
+ async loadDocumentHistoryRestoreState(scope) {
216
+ await ensureSqlTables(this.execSql, documentTables);
217
+ const { db } = getClientSQLitePersistenceRuntime(this.execSql);
218
+ return selectDocumentHistoryRestoreState(db, scope);
219
+ }
220
+ /**
221
+ * Size of the tail compaction can shrink. Queued rows are excluded: they
222
+ * stay until settlement, so counting them would re-export full history on
223
+ * every persist while offline edits wait to sync.
224
+ */
225
+ async readDocumentHistoryTailSize(scope) {
226
+ await ensureSqlTables(this.execSql, documentTables);
227
+ const { db } = getClientSQLitePersistenceRuntime(this.execSql);
228
+ return selectDocumentHistoryTailSize(db, scope);
229
+ }
230
+ /**
231
+ * The current compactable tail rows WITH their payloads, so a compactor can
232
+ * prove each row's ops are covered by the snapshot it is about to install
233
+ * (another pane's append may carry ops this pane's document has not merged
234
+ * yet). Queued rows are never candidates.
235
+ */
236
+ async listDocumentHistoryTailEntries(scope) {
237
+ await ensureSqlTables(this.execSql, documentTables);
238
+ const { db } = getClientSQLitePersistenceRuntime(this.execSql);
239
+ return selectDocumentHistoryTailEntries(db, scope);
240
+ }
241
+ /**
242
+ * Replace the scope's checkpoint with a fresh full-history snapshot and
243
+ * delete ONLY the tail rows the caller captured before exporting it. Every
244
+ * append path writes its tail row after the ops are already in the live
245
+ * document, so any row captured before the export is provably covered by
246
+ * the snapshot — while a row appended concurrently (between export and
247
+ * this delete) survives for the next compaction instead of being lost.
248
+ */
249
+ async replaceDocumentHistoryCheckpoint(scope, input) {
250
+ await ensureSqlTables(this.execSql, documentTables);
251
+ // Sequential (non-transactional) so callers already inside a transaction
252
+ // can nest this. Crash between the statements leaves the new checkpoint
253
+ // plus covered tail rows — a safe superset, since tail replay is
254
+ // idempotent by op identity. The replacement itself is a compare-and-swap
255
+ // on the stored revision, so the version gate cannot be bypassed by a
256
+ // concurrent compactor between the read and the write: whoever loses the
257
+ // CAS re-reads and re-evaluates the gate against the winner's checkpoint.
258
+ return getClientSQLitePersistenceRuntime(this.execSql).runMutation((tx) => replaceDocumentHistoryCheckpointInTransaction(tx, scope, input, this.now));
259
+ }
260
+ async deleteDocumentHistory(scope) {
261
+ await ensureSqlTables(this.execSql, documentTables);
262
+ await getClientSQLitePersistenceRuntime(this.execSql).runMutation((tx) => deleteDocumentHistoryInTransaction(tx, scope));
263
+ }
264
+ /**
265
+ * Record the last terminal failure or incoming-update quarantine on the
266
+ * scope's row; the caller supplies `attemptedAt`. A scope with no
267
+ * `documents` row has nothing left to explain, so it is a no-op there.
268
+ */
269
+ async recordDocumentSyncFailure(scope, failure) {
270
+ await getClientSQLitePersistenceRuntime(this.execSql).runMutation((db) => recordDocumentSyncFailureInTransaction(db, scope, failure));
271
+ }
272
+ /** Whether any queued local write has recorded a terminal failure. */
273
+ async hasRecordedTerminalSyncFailures() {
274
+ await ensureSqlTables(this.execSql, [
275
+ ...documentTables,
276
+ ...localIntentTables,
277
+ ]);
278
+ const { db } = getClientSQLitePersistenceRuntime(this.execSql);
279
+ return selectHasRecordedTerminalSyncFailures(db);
280
+ }
281
+ /** Drop the recorded failure for a scope. */
282
+ async clearDocumentSyncFailure(scope) {
283
+ await getClientSQLitePersistenceRuntime(this.execSql).runMutation((db) => clearDocumentSyncFailureInTransaction(db, scope));
284
+ }
285
+ }
286
+ //# sourceMappingURL=documentRecordRepository.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"documentRecordRepository.js","sourceRoot":"","sources":["documentRecordRepository.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EACL,oCAAoC,EAEpC,qCAAqC,GACtC,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EACL,sBAAsB,EACtB,SAAS,EACT,cAAc,GACf,MAA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C,CAAC,EAAE,EAAE,EAAE,CACvE,kCAAkC,CAAC,EAAE,EAAE,KAAK,CAAC,CAC9C,CAAC;IACJ,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,yBAAyB,CAC7B,KAAoB,EACpB,OAAkC;QAElC,MAAM,iCAAiC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,WAAW,CAAC,CAAC,EAAE,EAAE,EAAE,CACvE,sCAAsC,CAAC,EAAE,EAAE,KAAK,EAAE,OAAO,CAAC,CAC3D,CAAC;IACJ,CAAC;IAED,sEAAsE;IACtE,KAAK,CAAC,+BAA+B;QACnC,MAAM,eAAe,CAAC,IAAI,CAAC,OAAO,EAAE;YAClC,GAAG,cAAc;YACjB,GAAG,iBAAiB;SACrB,CAAC,CAAC;QACH,MAAM,EAAE,EAAE,EAAE,GAAG,iCAAiC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAC/D,OAAO,qCAAqC,CAAC,EAAE,CAAC,CAAC;IACnD,CAAC;IAED,6CAA6C;IAC7C,KAAK,CAAC,wBAAwB,CAAC,KAAoB;QACjD,MAAM,iCAAiC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,WAAW,CAAC,CAAC,EAAE,EAAE,EAAE,CACvE,qCAAqC,CAAC,EAAE,EAAE,KAAK,CAAC,CACjD,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { and, eq, inArray, sql } from \"drizzle-orm\";\nimport {\n DOCUMENT_SYNC_PULL_RECOVERY_REQUIRED,\n type DocumentSyncPullContinuation,\n serializeDocumentSyncPullContinuation,\n} from \"../../../documents/shared/sync/pullContinuation\";\nimport { localIntentTables } from \"../../../sqlite/schema\";\nimport {\n documentHistoryUpdates,\n documents,\n documentTables,\n} from \"../../../sqlite/schema/documentRecordSchema\";\nimport { sqliteRowsPerStatement } from \"../../../sqlite/sqliteBindBudget\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../../sqlite/sqlSchema\";\nimport {\n type DocumentHistoryCheckpointReplacement,\n type DocumentHistoryRestoreState,\n type DocumentHistoryTailEntry,\n type DocumentHistoryTailSize,\n type DocumentHistoryUpdateOrigin,\n deleteDocumentHistoryInTransaction,\n insertDocumentHistoryUpdatesInTransaction,\n replaceDocumentHistoryCheckpointInTransaction,\n selectDocumentHistoryRestoreState,\n selectDocumentHistoryTailEntries,\n selectDocumentHistoryTailSize,\n} from \"./documentHistoryPersistence\";\nimport {\n documentWriteFenceMatchesInTransaction,\n insertDocumentPendingUpdateInTransaction,\n insertDocumentPendingUpdateWithHistoryInTransaction,\n queuedInScope,\n rekeyDocumentPendingUpdateInTransaction,\n selectDocumentPendingUpdates,\n settleDocumentPendingUpdateInTransaction,\n unqueueDocumentScopesInTransaction,\n} from \"./documentPendingUpdatePersistence\";\nimport type {\n DocumentRecord,\n DocumentScope,\n PendingUpdateFields,\n QueuedPendingUpdateRecord,\n} from \"./documentPersistenceTypes\";\nimport {\n type QueuedUpdateReplacement,\n replaceDocumentQueuedUpdatesInTransaction,\n} from \"./documentQueuedUpdateReplacement\";\nimport {\n documentRecordSelection,\n localIdPreferenceOrder,\n mapSelectedDocumentRecord,\n} from \"./documentRecordPersistence\";\nimport {\n clearDocumentSyncFailureInTransaction,\n type DocumentSyncFailureFields,\n recordDocumentSyncFailureInTransaction,\n selectHasRecordedTerminalSyncFailures,\n} from \"./documentSyncFailurePersistence\";\n\n/** The exact continuation `invalidateDocumentSyncPullContinuation` replaces. */\nexport interface DocumentSyncPullContinuationInvalidation {\n accessEpoch: number;\n accessStateHash: string | null;\n appKind: string;\n continuation: DocumentSyncPullContinuation;\n contentKeyBundle: string | null;\n documentId: string;\n documentKekTargets: string | null;\n documentManifestBundle: string | null;\n lastCommitLsn: string | null;\n localId: string;\n}\n\n/**\n * A document scope's record row, its history checkpoint and tail, its queue\n * of pending updates and its recorded sync failure, bound to one executor\n * and clock. Each method keeps the transaction shape it always had: reads\n * run on the bound handle, writers run their own serialized mutation (or an\n * immediate transaction where noted). Build it from the executor you hold;\n * inside a locked section that is the locked handle. Work inside a caller's\n * transaction takes the handle per call through the `*InTransaction`\n * functions instead.\n */\nexport class DocumentRecordRepository {\n private readonly execSql: ExecSql;\n private readonly now: () => Date;\n\n constructor(execSql: ExecSql, now: () => Date = () => new Date()) {\n this.execSql = execSql;\n this.now = now;\n }\n\n /** Replace only the exact rejected continuation with a durable recovery marker. */\n async invalidateDocumentSyncPullContinuation(\n input: DocumentSyncPullContinuationInvalidation,\n ): Promise<DocumentRecord | null> {\n await ensureSqlTables(this.execSql, documentTables);\n const expectedContinuation = serializeDocumentSyncPullContinuation(\n input.continuation,\n );\n if (expectedContinuation === null) return null;\n return runSerializedSqlMutation(this.execSql, async (lockedExecSql) => {\n const { db } = getClientSQLitePersistenceRuntime(lockedExecSql);\n await db\n .update(documents)\n .set({ pullContinuation: DOCUMENT_SYNC_PULL_RECOVERY_REQUIRED })\n .where(\n and(\n eq(documents.appKind, input.appKind),\n eq(documents.localId, input.localId),\n eq(documents.documentId, input.documentId),\n eq(documents.accessEpoch, input.accessEpoch),\n sql`${documents.accessStateHash} IS ${input.accessStateHash}`,\n sql`${documents.contentKeyBundle} IS ${input.contentKeyBundle}`,\n sql`${documents.documentKekTargets} IS ${input.documentKekTargets}`,\n sql`${documents.documentManifestBundle} IS ${input.documentManifestBundle}`,\n sql`${documents.lastCommitLsn} IS ${input.lastCommitLsn}`,\n eq(documents.pullContinuation, expectedContinuation),\n ),\n )\n .run();\n return new DocumentRecordRepository(\n lockedExecSql,\n this.now,\n ).loadDocumentRecord({ appKind: input.appKind, localId: input.localId });\n });\n }\n\n async loadDocumentRecord(\n scope: DocumentScope,\n ): Promise<DocumentRecord | null> {\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .select(documentRecordSelection)\n .from(documents)\n .where(\n and(\n eq(documents.appKind, scope.appKind),\n eq(documents.localId, scope.localId),\n ),\n )\n .limit(1);\n return rows[0] ? mapSelectedDocumentRecord(rows[0]) : null;\n }\n\n async findLocalIdByDocumentId(\n appKind: string,\n documentId: string,\n ): Promise<string | null> {\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .select({ localId: documents.localId })\n .from(documents)\n .where(\n and(\n eq(documents.appKind, appKind),\n eq(documents.documentId, documentId),\n ),\n )\n .orderBy(...localIdPreferenceOrder())\n .limit(1);\n return rows[0]?.localId ?? null;\n }\n\n /**\n * `findLocalIdByDocumentId` for many document ids: one read per chunk, in\n * the same preference order, keeping the first row per document id.\n */\n async findLocalIdsByDocumentIds(\n appKind: string,\n documentIds: ReadonlyArray<string>,\n ): Promise<Map<string, string>> {\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const localIds = new Map<string, string>();\n const unique = Array.from(new Set(documentIds));\n // One bind for the app kind; the rest carry document ids.\n const chunkSize = sqliteRowsPerStatement(1, 1);\n for (let offset = 0; offset < unique.length; offset += chunkSize) {\n const rows = await db\n .select({\n documentId: documents.documentId,\n localId: documents.localId,\n })\n .from(documents)\n .where(\n and(\n eq(documents.appKind, appKind),\n inArray(\n documents.documentId,\n unique.slice(offset, offset + chunkSize),\n ),\n ),\n )\n .orderBy(...localIdPreferenceOrder());\n for (const row of rows) {\n if (row.documentId !== null && !localIds.has(row.documentId)) {\n localIds.set(row.documentId, row.localId);\n }\n }\n }\n return localIds;\n }\n\n async deleteDocumentRecord(scope: DocumentScope): Promise<void> {\n await getClientSQLitePersistenceRuntime(this.execSql).runMutation(\n async (db) => {\n await db\n .delete(documents)\n .where(\n and(\n eq(documents.appKind, scope.appKind),\n eq(documents.localId, scope.localId),\n ),\n )\n .run();\n },\n );\n }\n\n async listDocumentPendingUpdates(\n scope: DocumentScope,\n ): Promise<QueuedPendingUpdateRecord[]> {\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n return selectDocumentPendingUpdates(db, scope);\n }\n\n /**\n * Queue an update that has no history-tail role: container metadata (its\n * content is its checkpoint) and full-state re-uploads after a remote reset.\n */\n async enqueueDocumentPendingUpdate(\n scope: DocumentScope,\n pendingUpdate: PendingUpdateFields,\n ): Promise<string> {\n const updateId = crypto.randomUUID();\n await getClientSQLitePersistenceRuntime(this.execSql).runMutation(\n async (db) => {\n await insertDocumentPendingUpdateInTransaction(db, {\n createdAt: this.now().toISOString(),\n pendingUpdate,\n scope,\n updateId,\n });\n },\n );\n return updateId;\n }\n\n /**\n * Append a locally authored update to the history tail AND queue it, as one\n * row in one immediate transaction. A crash can therefore never leave the\n * op restorable from history while missing from the outgoing queue, where a\n * null-marker restore would classify it as covered and never send it.\n */\n async enqueueDocumentPendingUpdateWithHistory(\n scope: DocumentScope,\n pendingUpdate: PendingUpdateFields,\n options?: {\n expectedDocumentId: string | null;\n expectedRecoveryGeneration: number;\n },\n ): Promise<string | null> {\n const createdAt = this.now().toISOString();\n return getClientSQLitePersistenceRuntime(this.execSql).transaction(\n async (tx) => {\n if (\n options &&\n !(await documentWriteFenceMatchesInTransaction(tx, scope, options))\n ) {\n return null;\n }\n return insertDocumentPendingUpdateWithHistoryInTransaction({\n createdAt,\n pendingUpdate,\n scope,\n tx,\n });\n },\n { behavior: \"immediate\" },\n );\n }\n\n /**\n * Reset the durable re-key budget for every queued update in a scope. The\n * cap exists to stop a server that keeps conflicting fresh ids from driving\n * a network-speed loop — but a budget burned during an unrelated outage\n * (e.g. yesterday's stale-bundle deadlock 409ing every submit) should not\n * be terminal forever. An explicit manual retry is the deliberate,\n * rate-limited signal that conditions changed, so it gets a fresh budget.\n */\n async resetDocumentPendingUpdateRekeyBudget(\n scope: DocumentScope,\n ): Promise<void> {\n await getClientSQLitePersistenceRuntime(this.execSql).runMutation(\n async (db) => {\n await db\n .update(documentHistoryUpdates)\n .set({ rekeyCount: 0 })\n .where(queuedInScope(scope));\n },\n );\n }\n\n /** See `MAX_PENDING_UPDATE_REKEYS`: the new id, or null with no progress. */\n async rekeyDocumentPendingUpdate(id: string): Promise<string | null> {\n const nextId = crypto.randomUUID();\n const rekeyed = await getClientSQLitePersistenceRuntime(\n this.execSql,\n ).runMutation((db) =>\n rekeyDocumentPendingUpdateInTransaction(db, id, nextId),\n );\n return rekeyed ? nextId : null;\n }\n\n /** Settle one queued update by id, whatever its scope. */\n async settleDocumentPendingUpdate(id: string): Promise<void> {\n await getClientSQLitePersistenceRuntime(this.execSql).runMutation(\n async (db) => {\n await settleDocumentPendingUpdateInTransaction(db, id);\n },\n );\n }\n\n async unqueueDocumentPendingUpdates(scope: DocumentScope): Promise<void> {\n await getClientSQLitePersistenceRuntime(this.execSql).runMutation(\n async (db) => {\n await unqueueDocumentScopesInTransaction(db, [scope]);\n },\n );\n }\n\n /**\n * Replace queued local updates with one merged update, all or nothing, in\n * one immediate transaction. Every check must hold or nothing changes and\n * the result is null: the document still has the captured document id and\n * recovery generation, and the members are still queued under their ids as\n * ordinary local rows (no outbox row, no rotation checkpoint) forming one\n * contiguous run in queue order that starts with the first listed member.\n *\n * The first member's row is updated in place, so it keeps its row id,\n * `created_at` and rowid (its queue and history-tail position), and\n * receives a fresh update id (an id is never reused for different\n * content), the merged data and vectors, and `rekeyCount`. The other\n * members are deleted. Resolves to the merged row's new update id.\n */\n async replaceDocumentQueuedUpdates(\n scope: DocumentScope,\n replacement: QueuedUpdateReplacement,\n ): Promise<string | null> {\n if (replacement.memberUpdateIds.length < 2) return null;\n return getClientSQLitePersistenceRuntime(this.execSql).transaction(\n (tx) => replaceDocumentQueuedUpdatesInTransaction(tx, scope, replacement),\n { behavior: \"immediate\" },\n );\n }\n\n async appendDocumentHistoryUpdates(\n scope: DocumentScope,\n updates: readonly string[],\n origin: DocumentHistoryUpdateOrigin,\n ): Promise<void> {\n if (updates.length === 0) {\n return;\n }\n await ensureSqlTables(this.execSql, documentTables);\n const createdAt = this.now().toISOString();\n await getClientSQLitePersistenceRuntime(this.execSql).runMutation((db) =>\n insertDocumentHistoryUpdatesInTransaction(db, {\n createdAt,\n origin,\n scope,\n updates,\n }),\n );\n }\n\n /**\n * The checkpoint + ordered tail for a scope, or null when NEITHER exists (a\n * discovered shell that has not hydrated content yet; the caller starts the\n * document empty and the remote pull supplies the content). A tail WITHOUT\n * a checkpoint — a crash between the first enqueued edit's tail append and\n * the birth-checkpoint seed — restores as tail-only (`snapshot: \"\"`): those\n * tail rows can be the only durable copy of a local edit, so they must\n * never be silently ignored.\n */\n async loadDocumentHistoryRestoreState(\n scope: DocumentScope,\n ): Promise<DocumentHistoryRestoreState | null> {\n await ensureSqlTables(this.execSql, documentTables);\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n return selectDocumentHistoryRestoreState(db, scope);\n }\n\n /**\n * Size of the tail compaction can shrink. Queued rows are excluded: they\n * stay until settlement, so counting them would re-export full history on\n * every persist while offline edits wait to sync.\n */\n async readDocumentHistoryTailSize(\n scope: DocumentScope,\n ): Promise<DocumentHistoryTailSize> {\n await ensureSqlTables(this.execSql, documentTables);\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n return selectDocumentHistoryTailSize(db, scope);\n }\n\n /**\n * The current compactable tail rows WITH their payloads, so a compactor can\n * prove each row's ops are covered by the snapshot it is about to install\n * (another pane's append may carry ops this pane's document has not merged\n * yet). Queued rows are never candidates.\n */\n async listDocumentHistoryTailEntries(\n scope: DocumentScope,\n ): Promise<DocumentHistoryTailEntry[]> {\n await ensureSqlTables(this.execSql, documentTables);\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n return selectDocumentHistoryTailEntries(db, scope);\n }\n\n /**\n * Replace the scope's checkpoint with a fresh full-history snapshot and\n * delete ONLY the tail rows the caller captured before exporting it. Every\n * append path writes its tail row after the ops are already in the live\n * document, so any row captured before the export is provably covered by\n * the snapshot — while a row appended concurrently (between export and\n * this delete) survives for the next compaction instead of being lost.\n */\n async replaceDocumentHistoryCheckpoint(\n scope: DocumentScope,\n input: DocumentHistoryCheckpointReplacement,\n ): Promise<boolean> {\n await ensureSqlTables(this.execSql, documentTables);\n // Sequential (non-transactional) so callers already inside a transaction\n // can nest this. Crash between the statements leaves the new checkpoint\n // plus covered tail rows — a safe superset, since tail replay is\n // idempotent by op identity. The replacement itself is a compare-and-swap\n // on the stored revision, so the version gate cannot be bypassed by a\n // concurrent compactor between the read and the write: whoever loses the\n // CAS re-reads and re-evaluates the gate against the winner's checkpoint.\n return getClientSQLitePersistenceRuntime(this.execSql).runMutation((tx) =>\n replaceDocumentHistoryCheckpointInTransaction(tx, scope, input, this.now),\n );\n }\n\n async deleteDocumentHistory(scope: DocumentScope): Promise<void> {\n await ensureSqlTables(this.execSql, documentTables);\n await getClientSQLitePersistenceRuntime(this.execSql).runMutation((tx) =>\n deleteDocumentHistoryInTransaction(tx, scope),\n );\n }\n\n /**\n * Record the last terminal failure or incoming-update quarantine on the\n * scope's row; the caller supplies `attemptedAt`. A scope with no\n * `documents` row has nothing left to explain, so it is a no-op there.\n */\n async recordDocumentSyncFailure(\n scope: DocumentScope,\n failure: DocumentSyncFailureFields,\n ): Promise<void> {\n await getClientSQLitePersistenceRuntime(this.execSql).runMutation((db) =>\n recordDocumentSyncFailureInTransaction(db, scope, failure),\n );\n }\n\n /** Whether any queued local write has recorded a terminal failure. */\n async hasRecordedTerminalSyncFailures(): Promise<boolean> {\n await ensureSqlTables(this.execSql, [\n ...documentTables,\n ...localIntentTables,\n ]);\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n return selectHasRecordedTerminalSyncFailures(db);\n }\n\n /** Drop the recorded failure for a scope. */\n async clearDocumentSyncFailure(scope: DocumentScope): Promise<void> {\n await getClientSQLitePersistenceRuntime(this.execSql).runMutation((db) =>\n clearDocumentSyncFailureInTransaction(db, scope),\n );\n }\n}\n"]}
@@ -1,7 +1,6 @@
1
- import { type ClientSQLiteTransactionScope } from "../../../sqlite/sqlitePersistenceRuntime.js";
2
- import { type ExecSql } from "../../../sqlite/sqlSchema.js";
1
+ import type { ClientSQLiteTransactionScope } from "../../../sqlite/sqlitePersistenceRuntime.js";
3
2
  import type { DocumentScope } from "./documentPersistenceTypes.js";
4
- interface DocumentSyncFailureFields {
3
+ export interface DocumentSyncFailureFields {
5
4
  readonly attemptedAt: string;
6
5
  readonly message: string;
7
6
  readonly status: number | null;
@@ -19,7 +18,7 @@ export declare const CLEARED_DOCUMENT_SYNC_FAILURE: {
19
18
  * failure replaces the old. A scope with no `documents` row has nothing left
20
19
  * to explain, so the update is a no-op there.
21
20
  */
22
- export declare function recordDocumentSyncFailure(execSql: ExecSql, scope: DocumentScope, failure: DocumentSyncFailureFields): Promise<void>;
21
+ export declare function recordDocumentSyncFailureInTransaction(tx: ClientSQLiteTransactionScope, scope: DocumentScope, failure: DocumentSyncFailureFields): Promise<void>;
23
22
  /**
24
23
  * Whether any queued local write has recorded a terminal failure — a document
25
24
  * row carrying a sync failure or an intent row carrying `last_error`. This is
@@ -27,13 +26,11 @@ export declare function recordDocumentSyncFailure(execSql: ExecSql, scope: Docum
27
26
  * access is restored): without it a transient denial during bootstrap would
28
27
  * fire recovery work with nothing to recover, racing the startup sync passes.
29
28
  */
30
- export declare function hasRecordedTerminalSyncFailures(execSql: ExecSql): Promise<boolean>;
31
- /** Clear a scope's recorded failure inside a caller's transaction. */
32
- export declare function clearDocumentSyncFailureInTransaction(tx: ClientSQLiteTransactionScope, scope: DocumentScope): Promise<void>;
29
+ export declare function selectHasRecordedTerminalSyncFailures(db: Pick<ClientSQLiteTransactionScope, "select">): Promise<boolean>;
33
30
  /**
34
- * Drop the recorded failure for a scope. Called when a later sync pass for the
35
- * scope succeeds and whenever the scope's local sync state is torn down, so a
36
- * stale failure never outlives the condition it describes.
31
+ * Clear a scope's recorded failure inside a caller's transaction. Called when
32
+ * a later sync pass for the scope succeeds and whenever the scope's local sync
33
+ * state is torn down, so a stale failure never outlives the condition it
34
+ * describes.
37
35
  */
38
- export declare function clearDocumentSyncFailure(execSql: ExecSql, scope: DocumentScope): Promise<void>;
39
- export {};
36
+ export declare function clearDocumentSyncFailureInTransaction(tx: ClientSQLiteTransactionScope, scope: DocumentScope): Promise<void>;
@@ -1,8 +1,6 @@
1
1
  import { and, eq, isNotNull } from "drizzle-orm";
2
- import { localIntents, localIntentTables } from "../../../sqlite/schema/index.js";
3
- import { documents, documentTables, } from "../../../sqlite/schema/documentRecordSchema.js";
4
- import { getClientSQLitePersistenceRuntime, } from "../../../sqlite/sqlitePersistenceRuntime.js";
5
- import { ensureSqlTables } from "../../../sqlite/sqlSchema.js";
2
+ import { localIntents } from "../../../sqlite/schema/index.js";
3
+ import { documents } from "../../../sqlite/schema/documentRecordSchema.js";
6
4
  /** The `documents` column values of a scope with no recorded failure. */
7
5
  export const CLEARED_DOCUMENT_SYNC_FAILURE = {
8
6
  syncFailureAttemptedAt: null,
@@ -19,18 +17,16 @@ function scopeWhere(scope) {
19
17
  * failure replaces the old. A scope with no `documents` row has nothing left
20
18
  * to explain, so the update is a no-op there.
21
19
  */
22
- export async function recordDocumentSyncFailure(execSql, scope, failure) {
23
- await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {
24
- await db
25
- .update(documents)
26
- .set({
27
- syncFailureAttemptedAt: failure.attemptedAt,
28
- syncFailureMessage: failure.message,
29
- syncFailureStatus: failure.status,
30
- })
31
- .where(scopeWhere(scope))
32
- .run();
33
- });
20
+ export async function recordDocumentSyncFailureInTransaction(tx, scope, failure) {
21
+ await tx
22
+ .update(documents)
23
+ .set({
24
+ syncFailureAttemptedAt: failure.attemptedAt,
25
+ syncFailureMessage: failure.message,
26
+ syncFailureStatus: failure.status,
27
+ })
28
+ .where(scopeWhere(scope))
29
+ .run();
34
30
  }
35
31
  /**
36
32
  * Whether any queued local write has recorded a terminal failure — a document
@@ -39,9 +35,7 @@ export async function recordDocumentSyncFailure(execSql, scope, failure) {
39
35
  * access is restored): without it a transient denial during bootstrap would
40
36
  * fire recovery work with nothing to recover, racing the startup sync passes.
41
37
  */
42
- export async function hasRecordedTerminalSyncFailures(execSql) {
43
- await ensureSqlTables(execSql, [...documentTables, ...localIntentTables]);
44
- const { db } = getClientSQLitePersistenceRuntime(execSql);
38
+ export async function selectHasRecordedTerminalSyncFailures(db) {
45
39
  const [failure] = await db
46
40
  .select({ localId: documents.localId })
47
41
  .from(documents)
@@ -57,7 +51,12 @@ export async function hasRecordedTerminalSyncFailures(execSql) {
57
51
  .limit(1);
58
52
  return intent !== undefined;
59
53
  }
60
- /** Clear a scope's recorded failure inside a caller's transaction. */
54
+ /**
55
+ * Clear a scope's recorded failure inside a caller's transaction. Called when
56
+ * a later sync pass for the scope succeeds and whenever the scope's local sync
57
+ * state is torn down, so a stale failure never outlives the condition it
58
+ * describes.
59
+ */
61
60
  export async function clearDocumentSyncFailureInTransaction(tx, scope) {
62
61
  await tx
63
62
  .update(documents)
@@ -65,18 +64,4 @@ export async function clearDocumentSyncFailureInTransaction(tx, scope) {
65
64
  .where(scopeWhere(scope))
66
65
  .run();
67
66
  }
68
- /**
69
- * Drop the recorded failure for a scope. Called when a later sync pass for the
70
- * scope succeeds and whenever the scope's local sync state is torn down, so a
71
- * stale failure never outlives the condition it describes.
72
- */
73
- export async function clearDocumentSyncFailure(execSql, scope) {
74
- await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {
75
- await db
76
- .update(documents)
77
- .set(CLEARED_DOCUMENT_SYNC_FAILURE)
78
- .where(scopeWhere(scope))
79
- .run();
80
- });
81
- }
82
67
  //# sourceMappingURL=documentSyncFailurePersistence.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"documentSyncFailurePersistence.js","sourceRoot":"","sources":["documentSyncFailurePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AACzE,OAAO,EACL,SAAS,EACT,cAAc,GACf,MAAM,6CAA6C,CAAC;AACrD,OAAO,EAEL,iCAAiC,GAClC,MAAM,0CAA0C,CAAC;AAClD,OAAO,EA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SAAS,CAAC;SACf,KAAK,CAAC,SAAS,CAAC,SAAS,CAAC,kBAAkB,CAAC,CAAC;SAC9C,KAAK,CAAC,CAAC,CAAC,CAAC;IACZ,IAAI,OAAO,EAAE,CAAC;QACZ,OAAO,IAAI,CAAC;IACd,CAAC;IACD,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,EAAE;SACtB,MAAM,CAAC,EAAE,EAAE,EAAE,YAAY,CAAC,EAAE,EAAE,CAAC;SAC/B,IAAI,CAAC,YAAY,CAAC;SAClB,KAAK,CAAC,SAAS,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;SACxC,KAAK,CAAC,CAAC,CAAC,CAAC;IACZ,OAAO,MAAM,KAAK,SAAS,CAAC;AAC9B,CAAC;AAED,sEAAsE;AACtE,MAAM,CAAC,KAAK,UAAU,qCAAqC,CACzD,EAAgC,EAChC,KAAoB;IAEpB,MAAM,EAAE;SACL,MAAM,CAAC,SAAS,CAAC;SACjB,GAAG,CAAC,6BAA6B,CAAC;SAClC,KAAK,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;SACxB,GAAG,EAAE,CAAC;AACX,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAC5C,OAAgB,EAChB,KAAoB;IAEpB,MAAM,iCAAiC,CAAC,OAAO,CAAC,CAAC,WAAW,CAAC,KAAK,EAAE,EAAE,EAAE,EAAE;QACxE,MAAM,EAAE;aACL,MAAM,CAAC,SAAS,CAAC;aACjB,GAAG,CAAC,6BAA6B,CAAC;aAClC,KAAK,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;aACxB,GAAG,EAAE,CAAC;IACX,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { and, eq, isNotNull } from \"drizzle-orm\";\nimport { localIntents, localIntentTables } from \"../../../sqlite/schema\";\nimport {\n documents,\n documentTables,\n} from \"../../../sqlite/schema/documentRecordSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../../sqlite/sqlSchema\";\nimport type { DocumentScope } from \"./documentPersistenceTypes\";\n\ninterface DocumentSyncFailureFields {\n readonly attemptedAt: string;\n readonly message: string;\n readonly status: number | null;\n}\n\n/** The `documents` column values of a scope with no recorded failure. */\nexport const CLEARED_DOCUMENT_SYNC_FAILURE = {\n syncFailureAttemptedAt: null,\n syncFailureMessage: null,\n syncFailureStatus: null,\n} as const;\n\nfunction scopeWhere(scope: DocumentScope) {\n return and(\n eq(documents.appKind, scope.appKind),\n eq(documents.localId, scope.localId),\n );\n}\n\n/**\n * Record the last terminal failure or incoming-update quarantine on a document\n * scope's row. The durable pending-update queue has no status columns, so\n * these columns let the write-queue view explain a blocked document. A newer\n * failure replaces the old. A scope with no `documents` row has nothing left\n * to explain, so the update is a no-op there.\n */\nexport async function recordDocumentSyncFailure(\n execSql: ExecSql,\n scope: DocumentScope,\n failure: DocumentSyncFailureFields,\n): Promise<void> {\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n await db\n .update(documents)\n .set({\n syncFailureAttemptedAt: failure.attemptedAt,\n syncFailureMessage: failure.message,\n syncFailureStatus: failure.status,\n })\n .where(scopeWhere(scope))\n .run();\n });\n}\n\n/**\n * Whether any queued local write has recorded a terminal failure — a document\n * row carrying a sync failure or an intent row carrying `last_error`. This is\n * the evidence gate for recovery triggers (e.g. re-arming write lanes when org\n * access is restored): without it a transient denial during bootstrap would\n * fire recovery work with nothing to recover, racing the startup sync passes.\n */\nexport async function hasRecordedTerminalSyncFailures(\n execSql: ExecSql,\n): Promise<boolean> {\n await ensureSqlTables(execSql, [...documentTables, ...localIntentTables]);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const [failure] = await db\n .select({ localId: documents.localId })\n .from(documents)\n .where(isNotNull(documents.syncFailureMessage))\n .limit(1);\n if (failure) {\n return true;\n }\n const [intent] = await db\n .select({ id: localIntents.id })\n .from(localIntents)\n .where(isNotNull(localIntents.lastError))\n .limit(1);\n return intent !== undefined;\n}\n\n/** Clear a scope's recorded failure inside a caller's transaction. */\nexport async function clearDocumentSyncFailureInTransaction(\n tx: ClientSQLiteTransactionScope,\n scope: DocumentScope,\n): Promise<void> {\n await tx\n .update(documents)\n .set(CLEARED_DOCUMENT_SYNC_FAILURE)\n .where(scopeWhere(scope))\n .run();\n}\n\n/**\n * Drop the recorded failure for a scope. Called when a later sync pass for the\n * scope succeeds and whenever the scope's local sync state is torn down, so a\n * stale failure never outlives the condition it describes.\n */\nexport async function clearDocumentSyncFailure(\n execSql: ExecSql,\n scope: DocumentScope,\n): Promise<void> {\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n await db\n .update(documents)\n .set(CLEARED_DOCUMENT_SYNC_FAILURE)\n .where(scopeWhere(scope))\n .run();\n });\n}\n"]}
1
+ {"version":3,"file":"documentSyncFailurePersistence.js","sourceRoot":"","sources":["documentSyncFailurePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AACtD,OAAO,EAAE,SAAS,EAAE,MAAM,6CAA6C,CAAC;AAUxE,yEAAyE;AACzE,MAAM,CAAC,MAAM,6BAA6B,GAAG;IAC3C,sBAAsB,EAAE,IAAI;IAC5B,kBAAkB,EAAE,IAAI;IACxB,iBAAiB,EAAE,IAAI;CACf,CAAC;AAEX,SAAS,UAAU,CAAC,KAAoB;IACtC,OAAO,GAAG,CACR,EAAE,CAAC,SAAS,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,EACpC,EAAE,CAAC,SAAS,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,CACrC,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,sCAAsC,CAC1D,EAAg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NotNull } from \"drizzle-orm\";\nimport { localIntents } from \"../../../sqlite/schema\";\nimport { documents } from \"../../../sqlite/schema/documentRecordSchema\";\nimport type { ClientSQLiteTransactionScope } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport type { DocumentScope } from \"./documentPersistenceTypes\";\n\nexport interface DocumentSyncFailureFields {\n readonly attemptedAt: string;\n readonly message: string;\n readonly status: number | null;\n}\n\n/** The `documents` column values of a scope with no recorded failure. */\nexport const CLEARED_DOCUMENT_SYNC_FAILURE = {\n syncFailureAttemptedAt: null,\n syncFailureMessage: null,\n syncFailureStatus: null,\n} as const;\n\nfunction scopeWhere(scope: DocumentScope) {\n return and(\n eq(documents.appKind, scope.appKind),\n eq(documents.localId, scope.localId),\n );\n}\n\n/**\n * Record the last terminal failure or incoming-update quarantine on a document\n * scope's row. The durable pending-update queue has no status columns, so\n * these columns let the write-queue view explain a blocked document. A newer\n * failure replaces the old. A scope with no `documents` row has nothing left\n * to explain, so the update is a no-op there.\n */\nexport async function recordDocumentSyncFailureInTransaction(\n tx: ClientSQLiteTransactionScope,\n scope: DocumentScope,\n failure: DocumentSyncFailureFields,\n): Promise<void> {\n await tx\n .update(documents)\n .set({\n syncFailureAttemptedAt: failure.attemptedAt,\n syncFailureMessage: failure.message,\n syncFailureStatus: failure.status,\n })\n .where(scopeWhere(scope))\n .run();\n}\n\n/**\n * Whether any queued local write has recorded a terminal failure — a document\n * row carrying a sync failure or an intent row carrying `last_error`. This is\n * the evidence gate for recovery triggers (e.g. re-arming write lanes when org\n * access is restored): without it a transient denial during bootstrap would\n * fire recovery work with nothing to recover, racing the startup sync passes.\n */\nexport async function selectHasRecordedTerminalSyncFailures(\n db: Pick<ClientSQLiteTransactionScope, \"select\">,\n): Promise<boolean> {\n const [failure] = await db\n .select({ localId: documents.localId })\n .from(documents)\n .where(isNotNull(documents.syncFailureMessage))\n .limit(1);\n if (failure) {\n return true;\n }\n const [intent] = await db\n .select({ id: localIntents.id })\n .from(localIntents)\n .where(isNotNull(localIntents.lastError))\n .limit(1);\n return intent !== undefined;\n}\n\n/**\n * Clear a scope's recorded failure inside a caller's transaction. Called when\n * a later sync pass for the scope succeeds and whenever the scope's local sync\n * state is torn down, so a stale failure never outlives the condition it\n * describes.\n */\nexport async function clearDocumentSyncFailureInTransaction(\n tx: ClientSQLiteTransactionScope,\n scope: DocumentScope,\n): Promise<void> {\n await tx\n .update(documents)\n .set(CLEARED_DOCUMENT_SYNC_FAILURE)\n .where(scopeWhere(scope))\n .run();\n}\n"]}