@tearleads/client-sdk 0.1.114 → 0.1.115
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/data/persistence/container-contents/containerRecoveryPersistence.js +152 -38
- package/data/persistence/container-contents/containerRecoveryPersistence.js.map +1 -1
- package/data/persistence/container-contents/documentContainerProjectionPersistence.js +47 -18
- package/data/persistence/container-contents/documentContainerProjectionPersistence.js.map +1 -1
- package/data/persistence/container-contents/documentPlacement.js +24 -5
- package/data/persistence/container-contents/documentPlacement.js.map +1 -1
- package/data/persistence/documents/containerDocumentTombstoneHoldsPersistence.js +1 -1
- package/data/persistence/documents/containerDocumentTombstoneHoldsPersistence.js.map +1 -1
- package/data/persistence/documents/documentDiscoveryEvidencePersistence.js +43 -35
- package/data/persistence/documents/documentDiscoveryEvidencePersistence.js.map +1 -1
- package/data/persistence/documents/documentsPersistence.js +4 -58
- package/data/persistence/documents/documentsPersistence.js.map +1 -1
- package/data/persistence/documents/internal/containerDocumentTombstoneHolds.js +15 -11
- package/data/persistence/documents/internal/containerDocumentTombstoneHolds.js.map +1 -1
- package/data/persistence/documents/internal/containerDocumentTombstones.js +87 -35
- package/data/persistence/documents/internal/containerDocumentTombstones.js.map +1 -1
- package/data/persistence/documents/internal/discoveredDocumentPlacement.js +5 -2
- package/data/persistence/documents/internal/discoveredDocumentPlacement.js.map +1 -1
- package/data/persistence/documents/internal/discoveredDocumentUpsert.js +174 -0
- package/data/persistence/documents/internal/discoveredDocumentUpsert.js.map +1 -0
- package/data/persistence/documents/internal/documentRows.js +96 -1
- package/data/persistence/documents/internal/documentRows.js.map +1 -1
- package/data/persistence/documents/internal/rowQueryPersistence.js +38 -20
- package/data/persistence/documents/internal/rowQueryPersistence.js.map +1 -1
- package/data/persistence/documents/records/documentRecordPersistence.d.ts +5 -0
- package/data/persistence/documents/records/documentRecordPersistence.js +41 -6
- package/data/persistence/documents/records/documentRecordPersistence.js.map +1 -1
- package/data/persistence/documents/records/index.d.ts +1 -1
- package/data/persistence/documents/records/index.js +1 -1
- package/data/persistence/documents/records/index.js.map +1 -1
- package/data/persistence/keyingCheckpoints/documentPurgeCheckpointPersistence.d.ts +2 -0
- package/data/persistence/keyingCheckpoints/documentPurgeCheckpointPersistence.js +17 -1
- package/data/persistence/keyingCheckpoints/documentPurgeCheckpointPersistence.js.map +1 -1
- package/package.json +1 -1
- package/workflows/container-contents/remoteReset/containerRemoteReset.js +12 -7
- package/workflows/container-contents/remoteReset/containerRemoteReset.js.map +1 -1
- package/workflows/documents/remoteReset/documentRemoteReset.js +31 -18
- package/workflows/documents/remoteReset/documentRemoteReset.js.map +1 -1
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
import { and, eq, lte } from "drizzle-orm";
|
|
1
|
+
import { and, eq, getTableColumns, lte } from "drizzle-orm";
|
|
2
2
|
import { DEFAULT_DOCUMENT_KIND, DOCUMENTS_APP_KIND, } from "../../../documents/documentConstants.js";
|
|
3
3
|
import { deriveStoredDocumentTitle, } from "../../../documents/documentKinds.js";
|
|
4
4
|
import { serializeDocumentSyncPullContinuation } from "../../../documents/shared/sync/pullContinuation.js";
|
|
5
5
|
import { normalizeEffectiveAccessLevel } from "../../../keying/accessLevel.js";
|
|
6
6
|
import { documentProjection, documentProjectionText, documents, } from "../../../sqlite/schema/index.js";
|
|
7
|
+
import { sqliteInsertBatchSize } from "../../../sqlite/sqliteBindBudget.js";
|
|
7
8
|
import { getClientSQLitePersistenceRuntime, } from "../../../sqlite/sqlitePersistenceRuntime.js";
|
|
9
|
+
import { excludedValue } from "../../../sqlite/sqliteUpsert.js";
|
|
8
10
|
import { CLEARED_DOCUMENT_SYNC_FAILURE } from "../records/documentSyncFailurePersistence.js";
|
|
9
11
|
import { getProjectionDocumentKind, getProjectionText, getProjectionTitle, getProjectionUpdatedAt, } from "./documentProjectionRows.js";
|
|
10
12
|
export function getDocumentScope(localId) {
|
|
@@ -125,6 +127,99 @@ export async function saveDocumentRows(input) {
|
|
|
125
127
|
await saveDocumentProjectionRows(input);
|
|
126
128
|
return true;
|
|
127
129
|
}
|
|
130
|
+
/** A `set` clause that applies each conflicting row's own proposed values. */
|
|
131
|
+
function excludedSet(columns, row) {
|
|
132
|
+
const set = {};
|
|
133
|
+
for (const key of Object.keys(row)) {
|
|
134
|
+
const column = columns[key];
|
|
135
|
+
if (!column)
|
|
136
|
+
throw new Error(`Unknown upsert column ${key}`);
|
|
137
|
+
set[key] = excludedValue(column);
|
|
138
|
+
}
|
|
139
|
+
return set;
|
|
140
|
+
}
|
|
141
|
+
function chunks(values, size) {
|
|
142
|
+
const result = [];
|
|
143
|
+
for (let offset = 0; offset < values.length; offset += size) {
|
|
144
|
+
result.push(values.slice(offset, offset + size));
|
|
145
|
+
}
|
|
146
|
+
return result;
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* `saveDocumentRows` for documents with DISTINCT local ids, as multi-row
|
|
150
|
+
* statements: one fenced documents upsert per chunk and row shape, then the
|
|
151
|
+
* projection and text upserts for the rows the fence let through. Returns
|
|
152
|
+
* those local ids; a row the recovery-generation fence skips returns no row,
|
|
153
|
+
* exactly as the single-row upsert does.
|
|
154
|
+
*/
|
|
155
|
+
export async function saveDocumentRowsBatch(input) {
|
|
156
|
+
const { entries, tx } = input;
|
|
157
|
+
const documentColumns = getTableColumns(documents);
|
|
158
|
+
// A row that omits an optional column leaves it untouched on update, so
|
|
159
|
+
// rows are grouped by their column shape and each shape gets its own set.
|
|
160
|
+
const shapes = new Map();
|
|
161
|
+
for (const entry of entries) {
|
|
162
|
+
const row = toDocumentRecordRow(entry);
|
|
163
|
+
const shape = Object.keys(row).join(",");
|
|
164
|
+
shapes.set(shape, [...(shapes.get(shape) ?? []), row]);
|
|
165
|
+
}
|
|
166
|
+
const saved = new Set();
|
|
167
|
+
for (const rows of shapes.values()) {
|
|
168
|
+
const [first] = rows;
|
|
169
|
+
if (!first)
|
|
170
|
+
continue;
|
|
171
|
+
const set = excludedSet(documentColumns, first);
|
|
172
|
+
for (const chunk of chunks(rows, sqliteInsertBatchSize(documents))) {
|
|
173
|
+
const returned = await tx
|
|
174
|
+
.insert(documents)
|
|
175
|
+
.values(chunk)
|
|
176
|
+
.onConflictDoUpdate({
|
|
177
|
+
target: [documents.appKind, documents.localId],
|
|
178
|
+
set,
|
|
179
|
+
setWhere: lte(documents.recoveryGeneration, excludedValue(documents.recoveryGeneration)),
|
|
180
|
+
})
|
|
181
|
+
.returning({ localId: documents.localId });
|
|
182
|
+
for (const row of returned)
|
|
183
|
+
saved.add(row.localId);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
const savedEntries = entries.filter((entry) => saved.has(entry.document.id));
|
|
187
|
+
const projectionRows = savedEntries.map(({ document, updatedAt }) => ({
|
|
188
|
+
localId: document.id,
|
|
189
|
+
documentId: document.documentId,
|
|
190
|
+
containerId: document.containerId,
|
|
191
|
+
documentKind: document.documentKind ?? DEFAULT_DOCUMENT_KIND,
|
|
192
|
+
title: document.title ?? deriveStoredDocumentTitle(document.text),
|
|
193
|
+
updatedAt,
|
|
194
|
+
}));
|
|
195
|
+
const [firstProjection] = projectionRows;
|
|
196
|
+
if (firstProjection) {
|
|
197
|
+
const set = excludedSet(getTableColumns(documentProjection), firstProjection);
|
|
198
|
+
for (const chunk of chunks(projectionRows, sqliteInsertBatchSize(documentProjection))) {
|
|
199
|
+
await tx
|
|
200
|
+
.insert(documentProjection)
|
|
201
|
+
.values(chunk)
|
|
202
|
+
.onConflictDoUpdate({ target: documentProjection.localId, set })
|
|
203
|
+
.run();
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
const textRows = savedEntries.map(({ document }) => ({
|
|
207
|
+
localId: document.id,
|
|
208
|
+
text: document.text,
|
|
209
|
+
}));
|
|
210
|
+
const [firstText] = textRows;
|
|
211
|
+
if (firstText) {
|
|
212
|
+
const set = excludedSet(getTableColumns(documentProjectionText), firstText);
|
|
213
|
+
for (const chunk of chunks(textRows, sqliteInsertBatchSize(documentProjectionText))) {
|
|
214
|
+
await tx
|
|
215
|
+
.insert(documentProjectionText)
|
|
216
|
+
.values(chunk)
|
|
217
|
+
.onConflictDoUpdate({ target: documentProjectionText.localId, set })
|
|
218
|
+
.run();
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
return saved;
|
|
222
|
+
}
|
|
128
223
|
function didStoredDocumentContentChange(existing, next) {
|
|
129
224
|
return (existing === null ||
|
|
130
225
|
existing.documentKind !== (next.documentKind ?? DEFAULT_DOCUMENT_KIND) ||
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentRows.js","sourceRoot":"","sources":["documentRows.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EACL,qBAAqB,EACrB,kBAAkB,GACnB,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EACL,yBAAyB,GAE1B,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,qCAAqC,EAAE,MAAM,iDAAiD,CAAC;AACxG,OAAO,EAAE,6BAA6B,EAAE,MAAM,6BAA6B,CAAC;AAC5E,OAAO,EACL,kBAAkB,EAClB,sBAAsB,EACtB,SAAS,GACV,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAEL,iCAAiC,GAClC,MAAM,0CAA0C,CAAC;AAGlD,OAAO,EAAE,6BAA6B,EAAE,MAAM,2CAA2C,CAAC;AAE1F,OAAO,EACL,yBAAyB,EACzB,iBAAiB,EACjB,kBAAkB,EAClB,sBAAsB,GACvB,MAAM,0BAA0B,CAAC;AAElC,MAAM,UAAU,gBAAgB,CAAC,OAAe;IAC9C,OAAO;QACL,OAAO,EAAE,kBAAkB;QAC3B,OAAO;KACR,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,cAAc,CAClC,OAAgB,EAChB,OAAe;IAEf,MAAM,EAAE,EAAE,EAAE,GAAG,iCAAiC,CAAC,OAAO,CAAC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kBAAkB,CAAC;YAC3D,kBAAkB,EAAE,QAAQ,CAAC,kBAAkB;YAC/C,IAAI,EAAE,iBAAiB,CAAC,kBAAkB,CAAC;YAC3C,KAAK,EAAE,kBAAkB,CAAC,kBAAkB,CAAC;SAC9C;QACH,CAAC,CAAC,IAAI,EACR,QAAQ,CACT;QACC,CAAC,CAAC,GAAG;QACL,CAAC,CAAC,sBAAsB,CAAC,kBAAkB,CAAC,IAAI,GAAG,CAAC;AACxD,CAAC","sourcesContent":["import { and, eq, lte } from \"drizzle-orm\";\nimport {\n DEFAULT_DOCUMENT_KIND,\n DOCUMENTS_APP_KIND,\n} from \"../../../documents/documentConstants\";\nimport {\n deriveStoredDocumentTitle,\n type StoredDocumentKind,\n} from \"../../../documents/documentKinds\";\nimport { serializeDocumentSyncPullContinuation } from \"../../../documents/shared/sync/pullContinuation\";\nimport { normalizeEffectiveAccessLevel } from \"../../../keying/accessLevel\";\nimport {\n documentProjection,\n documentProjectionText,\n documents,\n} from \"../../../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\nimport type { DocumentScope } from \"../records\";\nimport { CLEARED_DOCUMENT_SYNC_FAILURE } from \"../records/documentSyncFailurePersistence\";\nimport type { StoredDocumentRecord } from \"../types\";\nimport {\n getProjectionDocumentKind,\n getProjectionText,\n getProjectionTitle,\n getProjectionUpdatedAt,\n} from \"./documentProjectionRows\";\n\nexport function getDocumentScope(localId: string): DocumentScope {\n return {\n appKind: DOCUMENTS_APP_KIND,\n localId,\n };\n}\n\nexport async function hasDocumentRow(\n execSql: ExecSql,\n localId: string,\n): Promise<boolean> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({ localId: documents.localId })\n .from(documents)\n .where(\n and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n eq(documents.localId, localId),\n ),\n )\n .limit(1);\n return rows.length > 0;\n}\n\nfunction toDocumentRecordRow(input: {\n document: StoredDocumentRecord;\n updatedAt: string;\n}) {\n const { document, updatedAt } = input;\n return {\n appKind: DOCUMENTS_APP_KIND,\n localId: document.id,\n documentId: document.documentId,\n recoveryGeneration: document.recoveryGeneration ?? 0,\n recoveryDocumentId: document.documentId\n ? null\n : (document.recoveryDocumentId ?? null),\n snapshotEndVersion: document.snapshotEndVersion,\n accessEpoch: document.accessEpoch,\n accessStateHash: document.accessStateHash ?? null,\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n document.effectiveAccessLevel,\n ),\n lastCommitLsn: document.lastCommitLsn ?? null,\n documentManifestBundle: document.documentManifestBundle ?? null,\n contentKeyBundle: document.contentKeyBundle ?? null,\n documentKekTargets: document.documentKekTargets ?? null,\n // Only touch the outgoing-delta marker when the caller manages it. Callers\n // that leave it undefined (e.g. discovery upserts, registration bootstrap)\n // must not clobber a marker a device-first deferRemoteSync write persisted.\n ...(document.pendingBaseVersion === undefined\n ? {}\n : { pendingBaseVersion: document.pendingBaseVersion }),\n ...(document.pullContinuation === undefined\n ? {}\n : {\n pullContinuation: serializeDocumentSyncPullContinuation(\n document.pullContinuation,\n ),\n }),\n updatedAt,\n };\n}\n\nasync function saveDocumentProjectionRows(input: {\n document: StoredDocumentRecord;\n tx: ClientSQLiteTransactionScope;\n updatedAt: string;\n}): Promise<void> {\n const { document, tx, updatedAt } = input;\n const projectionRow = {\n localId: document.id,\n documentId: document.documentId,\n containerId: document.containerId,\n documentKind: document.documentKind ?? DEFAULT_DOCUMENT_KIND,\n title: document.title ?? deriveStoredDocumentTitle(document.text),\n updatedAt,\n };\n await tx\n .insert(documentProjection)\n .values(projectionRow)\n .onConflictDoUpdate({\n target: documentProjection.localId,\n set: projectionRow,\n })\n .run();\n\n const projectionTextRow = {\n localId: document.id,\n text: document.text,\n };\n await tx\n .insert(documentProjectionText)\n .values(projectionTextRow)\n .onConflictDoUpdate({\n target: documentProjectionText.localId,\n set: projectionTextRow,\n })\n .run();\n}\n\nexport async function createDocumentRowsIfAbsent(input: {\n document: StoredDocumentRecord;\n tx: ClientSQLiteTransactionScope;\n updatedAt: string;\n}): Promise<boolean> {\n const { document, tx, updatedAt } = input;\n const documentRow = toDocumentRecordRow({ document, updatedAt });\n const inserted = await tx\n .insert(documents)\n .values(documentRow)\n .onConflictDoNothing({\n target: [documents.appKind, documents.localId],\n })\n .returning({ localId: documents.localId });\n if (inserted.length === 0) {\n return false;\n }\n\n await saveDocumentProjectionRows(input);\n return true;\n}\n\nexport async function saveDocumentRows(input: {\n /** Clears the recorded sync failure in the same guarded upsert. */\n clearSyncFailure?: boolean;\n document: StoredDocumentRecord;\n tx: ClientSQLiteTransactionScope;\n updatedAt: string;\n}): Promise<boolean> {\n const { document, tx, updatedAt } = input;\n const documentRow = {\n ...toDocumentRecordRow({ document, updatedAt }),\n ...(input.clearSyncFailure ? CLEARED_DOCUMENT_SYNC_FAILURE : {}),\n };\n // The recovery-generation fence rides on the upsert: a stored row from a\n // newer recovery generation is left untouched and returns no row, so a\n // stale writer skips the projection writes without a separate read.\n const saved = await tx\n .insert(documents)\n .values(documentRow)\n .onConflictDoUpdate({\n target: [documents.appKind, documents.localId],\n set: documentRow,\n setWhere: lte(\n documents.recoveryGeneration,\n documentRow.recoveryGeneration,\n ),\n })\n .returning({ localId: documents.localId });\n if (saved.length === 0) {\n return false;\n }\n await saveDocumentProjectionRows(input);\n return true;\n}\n\nfunction didStoredDocumentContentChange(\n existing: Pick<\n StoredDocumentRecord,\n \"documentKind\" | \"snapshotEndVersion\" | \"text\" | \"title\"\n > | null,\n next: Pick<\n StoredDocumentRecord,\n \"documentKind\" | \"snapshotEndVersion\" | \"text\" | \"title\"\n >,\n): boolean {\n return (\n existing === null ||\n existing.documentKind !== (next.documentKind ?? DEFAULT_DOCUMENT_KIND) ||\n existing.snapshotEndVersion !== next.snapshotEndVersion ||\n existing.text !== next.text ||\n existing.title !== (next.title ?? deriveStoredDocumentTitle(next.text))\n );\n}\n\nexport async function resolveDocumentSaveTimestamp(input: {\n document: StoredDocumentRecord;\n options?: { updatedAt?: string } | undefined;\n tx: ClientSQLiteTransactionScope;\n}): Promise<string> {\n const { document, options, tx } = input;\n if (options?.updatedAt) {\n return options.updatedAt;\n }\n\n // One read for the stored row and its projection; the projection columns\n // are not nullable, so they are null exactly when the projection is absent.\n const [existing] = await tx\n .select({\n snapshotEndVersion: documents.snapshotEndVersion,\n documentKind: documentProjection.documentKind,\n text: documentProjectionText.text,\n title: documentProjection.title,\n updatedAt: documentProjection.updatedAt,\n })\n .from(documents)\n .leftJoin(\n documentProjection,\n eq(documentProjection.localId, documents.localId),\n )\n .leftJoin(\n documentProjectionText,\n eq(documentProjectionText.localId, documentProjection.localId),\n )\n .where(\n and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n eq(documents.localId, document.id),\n ),\n )\n .limit(1);\n return documentSaveTimestampFrom(\n existing\n ? {\n projection:\n existing.documentKind != null &&\n existing.title != null &&\n existing.updatedAt != null\n ? {\n documentKind: existing.documentKind,\n text: existing.text,\n title: existing.title,\n updatedAt: existing.updatedAt,\n }\n : null,\n snapshotEndVersion: existing.snapshotEndVersion,\n }\n : null,\n document,\n );\n}\n\n/**\n * The save timestamp from rows already read in the saving transaction: the\n * stored time survives only when the content is unchanged.\n */\nexport function documentSaveTimestampFrom(\n existing: {\n projection: {\n documentKind: StoredDocumentKind;\n text: string | null;\n title: string;\n updatedAt: string;\n } | null;\n snapshotEndVersion: string;\n } | null,\n document: StoredDocumentRecord,\n): string {\n const existingProjection = existing?.projection ?? undefined;\n const now = new Date().toISOString();\n return didStoredDocumentContentChange(\n existing\n ? {\n documentKind: getProjectionDocumentKind(existingProjection),\n snapshotEndVersion: existing.snapshotEndVersion,\n text: getProjectionText(existingProjection),\n title: getProjectionTitle(existingProjection),\n }\n : null,\n document,\n )\n ? now\n : getProjectionUpdatedAt(existingProjection) || now;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"documentRows.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ACN,CAAC,CAAC;YACE,YAAY,EAAE,yBAAyB,CAAC,kBAAkB,CAAC;YAC3D,kBAAkB,EAAE,QAAQ,CAAC,kBAAkB;YAC/C,IAAI,EAAE,iBAAiB,CAAC,kBAAkB,CAAC;YAC3C,KAAK,EAAE,kBAAkB,CAAC,kBAAkB,CAAC;SAC9C;QACH,CAAC,CAAC,IAAI,EACR,QAAQ,CACT;QACC,CAAC,CAAC,GAAG;QACL,CAAC,CAAC,sBAAsB,CAAC,kBAAkB,CAAC,IAAI,GAAG,CAAC;AACxD,CAAC","sourcesContent":["import { and, eq, getTableColumns, lte, type SQL } from \"drizzle-orm\";\nimport type { SQLiteColumn } from \"drizzle-orm/sqlite-core\";\nimport {\n DEFAULT_DOCUMENT_KIND,\n DOCUMENTS_APP_KIND,\n} from \"../../../documents/documentConstants\";\nimport {\n deriveStoredDocumentTitle,\n type StoredDocumentKind,\n} from \"../../../documents/documentKinds\";\nimport { serializeDocumentSyncPullContinuation } from \"../../../documents/shared/sync/pullContinuation\";\nimport { normalizeEffectiveAccessLevel } from \"../../../keying/accessLevel\";\nimport {\n documentProjection,\n documentProjectionText,\n documents,\n} from \"../../../sqlite/schema\";\nimport { sqliteInsertBatchSize } from \"../../../sqlite/sqliteBindBudget\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport { excludedValue } from \"../../../sqlite/sqliteUpsert\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\nimport type { DocumentScope } from \"../records\";\nimport { CLEARED_DOCUMENT_SYNC_FAILURE } from \"../records/documentSyncFailurePersistence\";\nimport type { StoredDocumentRecord } from \"../types\";\nimport {\n getProjectionDocumentKind,\n getProjectionText,\n getProjectionTitle,\n getProjectionUpdatedAt,\n} from \"./documentProjectionRows\";\n\nexport function getDocumentScope(localId: string): DocumentScope {\n return {\n appKind: DOCUMENTS_APP_KIND,\n localId,\n };\n}\n\nexport async function hasDocumentRow(\n execSql: ExecSql,\n localId: string,\n): Promise<boolean> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({ localId: documents.localId })\n .from(documents)\n .where(\n and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n eq(documents.localId, localId),\n ),\n )\n .limit(1);\n return rows.length > 0;\n}\n\nfunction toDocumentRecordRow(input: {\n document: StoredDocumentRecord;\n updatedAt: string;\n}) {\n const { document, updatedAt } = input;\n return {\n appKind: DOCUMENTS_APP_KIND,\n localId: document.id,\n documentId: document.documentId,\n recoveryGeneration: document.recoveryGeneration ?? 0,\n recoveryDocumentId: document.documentId\n ? null\n : (document.recoveryDocumentId ?? null),\n snapshotEndVersion: document.snapshotEndVersion,\n accessEpoch: document.accessEpoch,\n accessStateHash: document.accessStateHash ?? null,\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n document.effectiveAccessLevel,\n ),\n lastCommitLsn: document.lastCommitLsn ?? null,\n documentManifestBundle: document.documentManifestBundle ?? null,\n contentKeyBundle: document.contentKeyBundle ?? null,\n documentKekTargets: document.documentKekTargets ?? null,\n // Only touch the outgoing-delta marker when the caller manages it. Callers\n // that leave it undefined (e.g. discovery upserts, registration bootstrap)\n // must not clobber a marker a device-first deferRemoteSync write persisted.\n ...(document.pendingBaseVersion === undefined\n ? {}\n : { pendingBaseVersion: document.pendingBaseVersion }),\n ...(document.pullContinuation === undefined\n ? {}\n : {\n pullContinuation: serializeDocumentSyncPullContinuation(\n document.pullContinuation,\n ),\n }),\n updatedAt,\n };\n}\n\nasync function saveDocumentProjectionRows(input: {\n document: StoredDocumentRecord;\n tx: ClientSQLiteTransactionScope;\n updatedAt: string;\n}): Promise<void> {\n const { document, tx, updatedAt } = input;\n const projectionRow = {\n localId: document.id,\n documentId: document.documentId,\n containerId: document.containerId,\n documentKind: document.documentKind ?? DEFAULT_DOCUMENT_KIND,\n title: document.title ?? deriveStoredDocumentTitle(document.text),\n updatedAt,\n };\n await tx\n .insert(documentProjection)\n .values(projectionRow)\n .onConflictDoUpdate({\n target: documentProjection.localId,\n set: projectionRow,\n })\n .run();\n\n const projectionTextRow = {\n localId: document.id,\n text: document.text,\n };\n await tx\n .insert(documentProjectionText)\n .values(projectionTextRow)\n .onConflictDoUpdate({\n target: documentProjectionText.localId,\n set: projectionTextRow,\n })\n .run();\n}\n\nexport async function createDocumentRowsIfAbsent(input: {\n document: StoredDocumentRecord;\n tx: ClientSQLiteTransactionScope;\n updatedAt: string;\n}): Promise<boolean> {\n const { document, tx, updatedAt } = input;\n const documentRow = toDocumentRecordRow({ document, updatedAt });\n const inserted = await tx\n .insert(documents)\n .values(documentRow)\n .onConflictDoNothing({\n target: [documents.appKind, documents.localId],\n })\n .returning({ localId: documents.localId });\n if (inserted.length === 0) {\n return false;\n }\n\n await saveDocumentProjectionRows(input);\n return true;\n}\n\nexport async function saveDocumentRows(input: {\n /** Clears the recorded sync failure in the same guarded upsert. */\n clearSyncFailure?: boolean;\n document: StoredDocumentRecord;\n tx: ClientSQLiteTransactionScope;\n updatedAt: string;\n}): Promise<boolean> {\n const { document, tx, updatedAt } = input;\n const documentRow = {\n ...toDocumentRecordRow({ document, updatedAt }),\n ...(input.clearSyncFailure ? CLEARED_DOCUMENT_SYNC_FAILURE : {}),\n };\n // The recovery-generation fence rides on the upsert: a stored row from a\n // newer recovery generation is left untouched and returns no row, so a\n // stale writer skips the projection writes without a separate read.\n const saved = await tx\n .insert(documents)\n .values(documentRow)\n .onConflictDoUpdate({\n target: [documents.appKind, documents.localId],\n set: documentRow,\n setWhere: lte(\n documents.recoveryGeneration,\n documentRow.recoveryGeneration,\n ),\n })\n .returning({ localId: documents.localId });\n if (saved.length === 0) {\n return false;\n }\n await saveDocumentProjectionRows(input);\n return true;\n}\n\ntype UpsertRow = Record<string, unknown>;\n\n/** A `set` clause that applies each conflicting row's own proposed values. */\nfunction excludedSet(\n columns: Record<string, SQLiteColumn>,\n row: UpsertRow,\n): Record<string, SQL> {\n const set: Record<string, SQL> = {};\n for (const key of Object.keys(row)) {\n const column = columns[key];\n if (!column) throw new Error(`Unknown upsert column ${key}`);\n set[key] = excludedValue(column);\n }\n return set;\n}\n\nfunction chunks<T>(values: ReadonlyArray<T>, size: number): T[][] {\n const result: T[][] = [];\n for (let offset = 0; offset < values.length; offset += size) {\n result.push(values.slice(offset, offset + size));\n }\n return result;\n}\n\n/**\n * `saveDocumentRows` for documents with DISTINCT local ids, as multi-row\n * statements: one fenced documents upsert per chunk and row shape, then the\n * projection and text upserts for the rows the fence let through. Returns\n * those local ids; a row the recovery-generation fence skips returns no row,\n * exactly as the single-row upsert does.\n */\nexport async function saveDocumentRowsBatch(input: {\n entries: ReadonlyArray<{ document: StoredDocumentRecord; updatedAt: string }>;\n tx: ClientSQLiteTransactionScope;\n}): Promise<Set<string>> {\n const { entries, tx } = input;\n const documentColumns: Record<string, SQLiteColumn> =\n getTableColumns(documents);\n // A row that omits an optional column leaves it untouched on update, so\n // rows are grouped by their column shape and each shape gets its own set.\n const shapes = new Map<string, ReturnType<typeof toDocumentRecordRow>[]>();\n for (const entry of entries) {\n const row = toDocumentRecordRow(entry);\n const shape = Object.keys(row).join(\",\");\n shapes.set(shape, [...(shapes.get(shape) ?? []), row]);\n }\n const saved = new Set<string>();\n for (const rows of shapes.values()) {\n const [first] = rows;\n if (!first) continue;\n const set = excludedSet(documentColumns, first);\n for (const chunk of chunks(rows, sqliteInsertBatchSize(documents))) {\n const returned = await tx\n .insert(documents)\n .values(chunk)\n .onConflictDoUpdate({\n target: [documents.appKind, documents.localId],\n set,\n setWhere: lte(\n documents.recoveryGeneration,\n excludedValue(documents.recoveryGeneration),\n ),\n })\n .returning({ localId: documents.localId });\n for (const row of returned) saved.add(row.localId);\n }\n }\n\n const savedEntries = entries.filter((entry) => saved.has(entry.document.id));\n const projectionRows = savedEntries.map(({ document, updatedAt }) => ({\n localId: document.id,\n documentId: document.documentId,\n containerId: document.containerId,\n documentKind: document.documentKind ?? DEFAULT_DOCUMENT_KIND,\n title: document.title ?? deriveStoredDocumentTitle(document.text),\n updatedAt,\n }));\n const [firstProjection] = projectionRows;\n if (firstProjection) {\n const set = excludedSet(\n getTableColumns(documentProjection),\n firstProjection,\n );\n for (const chunk of chunks(\n projectionRows,\n sqliteInsertBatchSize(documentProjection),\n )) {\n await tx\n .insert(documentProjection)\n .values(chunk)\n .onConflictDoUpdate({ target: documentProjection.localId, set })\n .run();\n }\n }\n const textRows = savedEntries.map(({ document }) => ({\n localId: document.id,\n text: document.text,\n }));\n const [firstText] = textRows;\n if (firstText) {\n const set = excludedSet(getTableColumns(documentProjectionText), firstText);\n for (const chunk of chunks(\n textRows,\n sqliteInsertBatchSize(documentProjectionText),\n )) {\n await tx\n .insert(documentProjectionText)\n .values(chunk)\n .onConflictDoUpdate({ target: documentProjectionText.localId, set })\n .run();\n }\n }\n return saved;\n}\n\nfunction didStoredDocumentContentChange(\n existing: Pick<\n StoredDocumentRecord,\n \"documentKind\" | \"snapshotEndVersion\" | \"text\" | \"title\"\n > | null,\n next: Pick<\n StoredDocumentRecord,\n \"documentKind\" | \"snapshotEndVersion\" | \"text\" | \"title\"\n >,\n): boolean {\n return (\n existing === null ||\n existing.documentKind !== (next.documentKind ?? DEFAULT_DOCUMENT_KIND) ||\n existing.snapshotEndVersion !== next.snapshotEndVersion ||\n existing.text !== next.text ||\n existing.title !== (next.title ?? deriveStoredDocumentTitle(next.text))\n );\n}\n\nexport async function resolveDocumentSaveTimestamp(input: {\n document: StoredDocumentRecord;\n options?: { updatedAt?: string } | undefined;\n tx: ClientSQLiteTransactionScope;\n}): Promise<string> {\n const { document, options, tx } = input;\n if (options?.updatedAt) {\n return options.updatedAt;\n }\n\n // One read for the stored row and its projection; the projection columns\n // are not nullable, so they are null exactly when the projection is absent.\n const [existing] = await tx\n .select({\n snapshotEndVersion: documents.snapshotEndVersion,\n documentKind: documentProjection.documentKind,\n text: documentProjectionText.text,\n title: documentProjection.title,\n updatedAt: documentProjection.updatedAt,\n })\n .from(documents)\n .leftJoin(\n documentProjection,\n eq(documentProjection.localId, documents.localId),\n )\n .leftJoin(\n documentProjectionText,\n eq(documentProjectionText.localId, documentProjection.localId),\n )\n .where(\n and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n eq(documents.localId, document.id),\n ),\n )\n .limit(1);\n return documentSaveTimestampFrom(\n existing\n ? {\n projection:\n existing.documentKind != null &&\n existing.title != null &&\n existing.updatedAt != null\n ? {\n documentKind: existing.documentKind,\n text: existing.text,\n title: existing.title,\n updatedAt: existing.updatedAt,\n }\n : null,\n snapshotEndVersion: existing.snapshotEndVersion,\n }\n : null,\n document,\n );\n}\n\n/**\n * The save timestamp from rows already read in the saving transaction: the\n * stored time survives only when the content is unchanged.\n */\nexport function documentSaveTimestampFrom(\n existing: {\n projection: {\n documentKind: StoredDocumentKind;\n text: string | null;\n title: string;\n updatedAt: string;\n } | null;\n snapshotEndVersion: string;\n } | null,\n document: StoredDocumentRecord,\n): string {\n const existingProjection = existing?.projection ?? undefined;\n const now = new Date().toISOString();\n return didStoredDocumentContentChange(\n existing\n ? {\n documentKind: getProjectionDocumentKind(existingProjection),\n snapshotEndVersion: existing.snapshotEndVersion,\n text: getProjectionText(existingProjection),\n title: getProjectionTitle(existingProjection),\n }\n : null,\n document,\n )\n ? now\n : getProjectionUpdatedAt(existingProjection) || now;\n}\n"]}
|
|
@@ -1,34 +1,30 @@
|
|
|
1
|
-
import { and, desc, eq, notInArray } from "drizzle-orm";
|
|
1
|
+
import { and, desc, eq, inArray, notInArray } from "drizzle-orm";
|
|
2
2
|
import { DOCUMENTS_APP_KIND } from "../../../documents/documentConstants.js";
|
|
3
3
|
import { HIDDEN_DOCUMENT_SUMMARY_KINDS } from "../../../documents/documentSummary.js";
|
|
4
4
|
import { documentProjection, documentProjectionText, documents, } from "../../../sqlite/schema/index.js";
|
|
5
|
+
import { sqliteRowsPerStatement } from "../../../sqlite/sqliteBindBudget.js";
|
|
5
6
|
import { getClientSQLitePersistenceRuntime } from "../../../sqlite/sqlitePersistenceRuntime.js";
|
|
6
7
|
import { documentRecordSelection, findLocalIdByDocumentId, loadDocumentRecord, mapSelectedDocumentRecord, } from "../records/index.js";
|
|
7
8
|
import { documentSummaryJoin, documentSummarySelection, getProjectionContainerId, getProjectionDocumentKind, getProjectionText, getProjectionTitle, mapDocumentSummary, } from "./documentProjectionRows.js";
|
|
8
9
|
import { getDocumentScope, hasDocumentRow } from "./documentRows.js";
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
10
|
+
const storedDocumentStateSelection = {
|
|
11
|
+
...documentRecordSelection,
|
|
12
|
+
projectionContainerId: documentProjection.containerId,
|
|
13
|
+
projectionDocumentKind: documentProjection.documentKind,
|
|
14
|
+
projectionText: documentProjectionText.text,
|
|
15
|
+
projectionTitle: documentProjection.title,
|
|
16
|
+
projectionUpdatedAt: documentProjection.updatedAt,
|
|
17
|
+
};
|
|
18
|
+
function storedDocumentStateQuery(execSql, localIds) {
|
|
15
19
|
const { db } = getClientSQLitePersistenceRuntime(execSql);
|
|
16
|
-
|
|
17
|
-
.select(
|
|
18
|
-
...documentRecordSelection,
|
|
19
|
-
projectionContainerId: documentProjection.containerId,
|
|
20
|
-
projectionDocumentKind: documentProjection.documentKind,
|
|
21
|
-
projectionText: documentProjectionText.text,
|
|
22
|
-
projectionTitle: documentProjection.title,
|
|
23
|
-
projectionUpdatedAt: documentProjection.updatedAt,
|
|
24
|
-
})
|
|
20
|
+
return db
|
|
21
|
+
.select(storedDocumentStateSelection)
|
|
25
22
|
.from(documents)
|
|
26
23
|
.leftJoin(documentProjection, eq(documentProjection.localId, documents.localId))
|
|
27
24
|
.leftJoin(documentProjectionText, eq(documentProjectionText.localId, documentProjection.localId))
|
|
28
|
-
.where(and(eq(documents.appKind, DOCUMENTS_APP_KIND),
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
return null;
|
|
25
|
+
.where(and(eq(documents.appKind, DOCUMENTS_APP_KIND), localIds));
|
|
26
|
+
}
|
|
27
|
+
function mapStoredDocumentState(row) {
|
|
32
28
|
const { projectionContainerId, projectionDocumentKind, projectionText, projectionTitle, projectionUpdatedAt, ...recordRow } = row;
|
|
33
29
|
// Projection columns are NOT NULL, so they are null exactly when the
|
|
34
30
|
// projection row is absent.
|
|
@@ -55,6 +51,28 @@ export async function loadStoredDocumentState(execSql, localId) {
|
|
|
55
51
|
},
|
|
56
52
|
};
|
|
57
53
|
}
|
|
54
|
+
/**
|
|
55
|
+
* The canonical record and its projection from ONE joined statement, so the
|
|
56
|
+
* pair comes from one snapshot and a save inside the same transaction can
|
|
57
|
+
* reuse the projection instead of reading it again.
|
|
58
|
+
*/
|
|
59
|
+
export async function loadStoredDocumentState(execSql, localId) {
|
|
60
|
+
const [row] = await storedDocumentStateQuery(execSql, eq(documents.localId, localId)).limit(1);
|
|
61
|
+
return row ? mapStoredDocumentState(row) : null;
|
|
62
|
+
}
|
|
63
|
+
/** `loadStoredDocumentState` for many local ids, one joined read per chunk. */
|
|
64
|
+
export async function loadStoredDocumentStates(execSql, localIds) {
|
|
65
|
+
const states = new Map();
|
|
66
|
+
const unique = Array.from(new Set(localIds));
|
|
67
|
+
// One bind for the app kind; the rest carry local ids.
|
|
68
|
+
const chunkSize = sqliteRowsPerStatement(1, 1);
|
|
69
|
+
for (let offset = 0; offset < unique.length; offset += chunkSize) {
|
|
70
|
+
const rows = await storedDocumentStateQuery(execSql, inArray(documents.localId, unique.slice(offset, offset + chunkSize)));
|
|
71
|
+
for (const row of rows)
|
|
72
|
+
states.set(row.id, mapStoredDocumentState(row));
|
|
73
|
+
}
|
|
74
|
+
return states;
|
|
75
|
+
}
|
|
58
76
|
export const documentRowQueryPersistence = {
|
|
59
77
|
async listDocuments(execSql) {
|
|
60
78
|
const { db } = getClientSQLitePersistenceRuntime(execSql);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rowQueryPersistence.js","sourceRoot":"","sources":["rowQueryPersistence.ts"],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,CAAC;QAED,OAAO,EAAE,WAAW,EAAE,aAAa,CAAC,WAAW,EAAE,CAAC;IACpD,CAAC;CACF,CAAC","sourcesContent":["import { and, desc, eq, notInArray } from \"drizzle-orm\";\nimport { DOCUMENTS_APP_KIND } from \"../../../documents/documentConstants\";\nimport type { StoredDocumentKind } from \"../../../documents/documentKinds\";\nimport { HIDDEN_DOCUMENT_SUMMARY_KINDS } from \"../../../documents/documentSummary\";\nimport {\n documentProjection,\n documentProjectionText,\n documents,\n} from \"../../../sqlite/schema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport {\n documentRecordSelection,\n findLocalIdByDocumentId,\n loadDocumentRecord,\n mapSelectedDocumentRecord,\n} from \"../records\";\nimport type { DocumentsPersistence, StoredDocumentRecord } from \"../types\";\nimport {\n documentSummaryJoin,\n documentSummarySelection,\n getProjectionContainerId,\n getProjectionDocumentKind,\n getProjectionText,\n getProjectionTitle,\n mapDocumentSummary,\n} from \"./documentProjectionRows\";\nimport { getDocumentScope, hasDocumentRow } from \"./documentRows\";\n\n/** The projection columns a stored record was loaded with, if any. */\nexport interface StoredDocumentProjectionState {\n documentKind: StoredDocumentKind;\n text: string | null;\n title: string;\n updatedAt: string;\n}\n\n/**\n * The canonical record and its projection from ONE joined statement, so the\n * pair comes from one snapshot and a save inside the same transaction can\n * reuse the projection instead of reading it again.\n */\nexport async function loadStoredDocumentState(\n execSql: Parameters<DocumentsPersistence[\"loadDocument\"]>[0],\n localId: string,\n): Promise<{\n projection: StoredDocumentProjectionState | null;\n record: StoredDocumentRecord;\n} | null> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const [row] = await db\n .select({\n ...documentRecordSelection,\n projectionContainerId: documentProjection.containerId,\n projectionDocumentKind: documentProjection.documentKind,\n projectionText: documentProjectionText.text,\n projectionTitle: documentProjection.title,\n projectionUpdatedAt: documentProjection.updatedAt,\n })\n .from(documents)\n .leftJoin(\n documentProjection,\n eq(documentProjection.localId, documents.localId),\n )\n .leftJoin(\n documentProjectionText,\n eq(documentProjectionText.localId, documentProjection.localId),\n )\n .where(\n and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n eq(documents.localId, localId),\n ),\n )\n .limit(1);\n if (!row) return null;\n const {\n projectionContainerId,\n projectionDocumentKind,\n projectionText,\n projectionTitle,\n projectionUpdatedAt,\n ...recordRow\n } = row;\n // Projection columns are NOT NULL, so they are null exactly when the\n // projection row is absent.\n const projectionRow =\n projectionDocumentKind !== null &&\n projectionTitle !== null &&\n projectionUpdatedAt !== null\n ? {\n containerId: projectionContainerId,\n documentKind: projectionDocumentKind,\n text: projectionText,\n title: projectionTitle,\n }\n : undefined;\n return {\n projection:\n projectionRow && projectionUpdatedAt !== null\n ? { ...projectionRow, updatedAt: projectionUpdatedAt }\n : null,\n record: {\n ...mapSelectedDocumentRecord(recordRow),\n containerId: getProjectionContainerId(projectionRow),\n documentKind: getProjectionDocumentKind(projectionRow),\n text: getProjectionText(projectionRow),\n title: getProjectionTitle(projectionRow),\n },\n };\n}\n\ntype DocumentRowQueryPersistence = Pick<\n DocumentsPersistence,\n | \"listDocuments\"\n | \"findDocumentLocalIdsByContainerId\"\n | \"findLocalIdByDocumentId\"\n | \"hasDocument\"\n | \"documentIdentityMatches\"\n | \"loadDocument\"\n | \"loadDocumentContainer\"\n>;\n\nexport const documentRowQueryPersistence: DocumentRowQueryPersistence = {\n async listDocuments(execSql) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select(documentSummarySelection)\n .from(documentProjection)\n .leftJoin(documents, documentSummaryJoin)\n .where(\n notInArray(documentProjection.documentKind, [\n ...HIDDEN_DOCUMENT_SUMMARY_KINDS,\n ]),\n )\n .orderBy(\n desc(documentProjection.updatedAt),\n desc(documentProjection.localId),\n );\n\n return rows.map(mapDocumentSummary);\n },\n async findDocumentLocalIdsByContainerId(execSql, containerId) {\n // Unlike `listDocumentsByContainerIdsOrDocumentIds`, this deliberately does\n // NOT drop `HIDDEN_DOCUMENT_SUMMARY_KINDS` — it exists to reach the hidden\n // `organization_profile` document by the container it is linked to, which is\n // how a *foreign* org's display name is found on a member who synced the doc\n // under its server documentId rather than the provisioner-only local alias.\n // `documentProjection` is written and deleted in lockstep with the\n // `documents` rows (all DOCUMENTS_APP_KIND), so filtering by containerId\n // alone is sufficient — no join to `documents` is needed to select localId.\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({ localId: documentProjection.localId })\n .from(documentProjection)\n .where(eq(documentProjection.containerId, containerId))\n .orderBy(\n desc(documentProjection.updatedAt),\n desc(documentProjection.localId),\n );\n return rows\n .map((row) => row.localId)\n .filter((localId): localId is string => localId !== null);\n },\n findLocalIdByDocumentId: (execSql, documentId) =>\n findLocalIdByDocumentId(execSql, DOCUMENTS_APP_KIND, documentId),\n async hasDocument(execSql, localId) {\n return hasDocumentRow(execSql, localId);\n },\n async documentIdentityMatches(\n execSql,\n localId,\n expectedDocumentId,\n expectedRecoveryGeneration,\n ) {\n const record = await loadDocumentRecord(execSql, getDocumentScope(localId));\n return (\n record?.documentId === expectedDocumentId &&\n (record.recoveryGeneration ?? 0) === expectedRecoveryGeneration\n );\n },\n async loadDocument(execSql, localId) {\n return (await loadStoredDocumentState(execSql, localId))?.record ?? null;\n },\n async loadDocumentContainer(execSql, localId) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n // Select the row itself, not just its container, so an existing row with a\n // null container is reported as `{ containerId: null }` while a missing row\n // is reported as `undefined` — the caller relies on that distinction to know\n // whether the projection has authoritative placement to defer to.\n const projectionRows = await db\n .select({ containerId: documentProjection.containerId })\n .from(documentProjection)\n .where(eq(documentProjection.localId, localId))\n .limit(1);\n const projectionRow = projectionRows[0];\n if (!projectionRow) {\n return undefined;\n }\n\n return { containerId: projectionRow.containerId };\n },\n};\n"]}
|
|
1
|
+
{"version":3,"file":"rowQueryPersistence.js","sourceRoot":"","sources":["rowQueryPersistence.ts"],"names":[],"mappings":"AAAA,O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from \"../../../documents/documentConstants\";\nimport type { StoredDocumentKind } from \"../../../documents/documentKinds\";\nimport { HIDDEN_DOCUMENT_SUMMARY_KINDS } from \"../../../documents/documentSummary\";\nimport {\n documentProjection,\n documentProjectionText,\n documents,\n} from \"../../../sqlite/schema\";\nimport { sqliteRowsPerStatement } from \"../../../sqlite/sqliteBindBudget\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport {\n documentRecordSelection,\n findLocalIdByDocumentId,\n loadDocumentRecord,\n mapSelectedDocumentRecord,\n} from \"../records\";\nimport type { DocumentsPersistence, StoredDocumentRecord } from \"../types\";\nimport {\n documentSummaryJoin,\n documentSummarySelection,\n getProjectionContainerId,\n getProjectionDocumentKind,\n getProjectionText,\n getProjectionTitle,\n mapDocumentSummary,\n} from \"./documentProjectionRows\";\nimport { getDocumentScope, hasDocumentRow } from \"./documentRows\";\n\n/** The projection columns a stored record was loaded with, if any. */\nexport interface StoredDocumentProjectionState {\n documentKind: StoredDocumentKind;\n text: string | null;\n title: string;\n updatedAt: string;\n}\n\nconst storedDocumentStateSelection = {\n ...documentRecordSelection,\n projectionContainerId: documentProjection.containerId,\n projectionDocumentKind: documentProjection.documentKind,\n projectionText: documentProjectionText.text,\n projectionTitle: documentProjection.title,\n projectionUpdatedAt: documentProjection.updatedAt,\n};\n\nexport interface StoredDocumentState {\n projection: StoredDocumentProjectionState | null;\n record: StoredDocumentRecord;\n}\n\nfunction storedDocumentStateQuery(\n execSql: Parameters<DocumentsPersistence[\"loadDocument\"]>[0],\n localIds: SQL | undefined,\n) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n return db\n .select(storedDocumentStateSelection)\n .from(documents)\n .leftJoin(\n documentProjection,\n eq(documentProjection.localId, documents.localId),\n )\n .leftJoin(\n documentProjectionText,\n eq(documentProjectionText.localId, documentProjection.localId),\n )\n .where(and(eq(documents.appKind, DOCUMENTS_APP_KIND), localIds));\n}\n\nfunction mapStoredDocumentState(\n row: Awaited<ReturnType<typeof storedDocumentStateQuery>>[number],\n): StoredDocumentState {\n const {\n projectionContainerId,\n projectionDocumentKind,\n projectionText,\n projectionTitle,\n projectionUpdatedAt,\n ...recordRow\n } = row;\n // Projection columns are NOT NULL, so they are null exactly when the\n // projection row is absent.\n const projectionRow =\n projectionDocumentKind !== null &&\n projectionTitle !== null &&\n projectionUpdatedAt !== null\n ? {\n containerId: projectionContainerId,\n documentKind: projectionDocumentKind,\n text: projectionText,\n title: projectionTitle,\n }\n : undefined;\n return {\n projection:\n projectionRow && projectionUpdatedAt !== null\n ? { ...projectionRow, updatedAt: projectionUpdatedAt }\n : null,\n record: {\n ...mapSelectedDocumentRecord(recordRow),\n containerId: getProjectionContainerId(projectionRow),\n documentKind: getProjectionDocumentKind(projectionRow),\n text: getProjectionText(projectionRow),\n title: getProjectionTitle(projectionRow),\n },\n };\n}\n\n/**\n * The canonical record and its projection from ONE joined statement, so the\n * pair comes from one snapshot and a save inside the same transaction can\n * reuse the projection instead of reading it again.\n */\nexport async function loadStoredDocumentState(\n execSql: Parameters<DocumentsPersistence[\"loadDocument\"]>[0],\n localId: string,\n): Promise<StoredDocumentState | null> {\n const [row] = await storedDocumentStateQuery(\n execSql,\n eq(documents.localId, localId),\n ).limit(1);\n return row ? mapStoredDocumentState(row) : null;\n}\n\n/** `loadStoredDocumentState` for many local ids, one joined read per chunk. */\nexport async function loadStoredDocumentStates(\n execSql: Parameters<DocumentsPersistence[\"loadDocument\"]>[0],\n localIds: ReadonlyArray<string>,\n): Promise<Map<string, StoredDocumentState>> {\n const states = new Map<string, StoredDocumentState>();\n const unique = Array.from(new Set(localIds));\n // One bind for the app kind; the rest carry local ids.\n const chunkSize = sqliteRowsPerStatement(1, 1);\n for (let offset = 0; offset < unique.length; offset += chunkSize) {\n const rows = await storedDocumentStateQuery(\n execSql,\n inArray(documents.localId, unique.slice(offset, offset + chunkSize)),\n );\n for (const row of rows) states.set(row.id, mapStoredDocumentState(row));\n }\n return states;\n}\n\ntype DocumentRowQueryPersistence = Pick<\n DocumentsPersistence,\n | \"listDocuments\"\n | \"findDocumentLocalIdsByContainerId\"\n | \"findLocalIdByDocumentId\"\n | \"hasDocument\"\n | \"documentIdentityMatches\"\n | \"loadDocument\"\n | \"loadDocumentContainer\"\n>;\n\nexport const documentRowQueryPersistence: DocumentRowQueryPersistence = {\n async listDocuments(execSql) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select(documentSummarySelection)\n .from(documentProjection)\n .leftJoin(documents, documentSummaryJoin)\n .where(\n notInArray(documentProjection.documentKind, [\n ...HIDDEN_DOCUMENT_SUMMARY_KINDS,\n ]),\n )\n .orderBy(\n desc(documentProjection.updatedAt),\n desc(documentProjection.localId),\n );\n\n return rows.map(mapDocumentSummary);\n },\n async findDocumentLocalIdsByContainerId(execSql, containerId) {\n // Unlike `listDocumentsByContainerIdsOrDocumentIds`, this deliberately does\n // NOT drop `HIDDEN_DOCUMENT_SUMMARY_KINDS` — it exists to reach the hidden\n // `organization_profile` document by the container it is linked to, which is\n // how a *foreign* org's display name is found on a member who synced the doc\n // under its server documentId rather than the provisioner-only local alias.\n // `documentProjection` is written and deleted in lockstep with the\n // `documents` rows (all DOCUMENTS_APP_KIND), so filtering by containerId\n // alone is sufficient — no join to `documents` is needed to select localId.\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({ localId: documentProjection.localId })\n .from(documentProjection)\n .where(eq(documentProjection.containerId, containerId))\n .orderBy(\n desc(documentProjection.updatedAt),\n desc(documentProjection.localId),\n );\n return rows\n .map((row) => row.localId)\n .filter((localId): localId is string => localId !== null);\n },\n findLocalIdByDocumentId: (execSql, documentId) =>\n findLocalIdByDocumentId(execSql, DOCUMENTS_APP_KIND, documentId),\n async hasDocument(execSql, localId) {\n return hasDocumentRow(execSql, localId);\n },\n async documentIdentityMatches(\n execSql,\n localId,\n expectedDocumentId,\n expectedRecoveryGeneration,\n ) {\n const record = await loadDocumentRecord(execSql, getDocumentScope(localId));\n return (\n record?.documentId === expectedDocumentId &&\n (record.recoveryGeneration ?? 0) === expectedRecoveryGeneration\n );\n },\n async loadDocument(execSql, localId) {\n return (await loadStoredDocumentState(execSql, localId))?.record ?? null;\n },\n async loadDocumentContainer(execSql, localId) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n // Select the row itself, not just its container, so an existing row with a\n // null container is reported as `{ containerId: null }` while a missing row\n // is reported as `undefined` — the caller relies on that distinction to know\n // whether the projection has authoritative placement to defer to.\n const projectionRows = await db\n .select({ containerId: documentProjection.containerId })\n .from(documentProjection)\n .where(eq(documentProjection.localId, localId))\n .limit(1);\n const projectionRow = projectionRows[0];\n if (!projectionRow) {\n return undefined;\n }\n\n return { containerId: projectionRow.containerId };\n },\n};\n"]}
|
|
@@ -272,4 +272,9 @@ export declare const documentRecordSelection: {
|
|
|
272
272
|
export declare function mapSelectedDocumentRecord(row: SelectedDocumentRecordRow): DocumentRecord;
|
|
273
273
|
export declare function loadDocumentRecord(execSql: ExecSql, scope: DocumentScope): Promise<DocumentRecord | null>;
|
|
274
274
|
export declare function findLocalIdByDocumentId(execSql: ExecSql, appKind: string, documentId: string): Promise<string | null>;
|
|
275
|
+
/**
|
|
276
|
+
* `findLocalIdByDocumentId` for many document ids: one read per chunk, in the
|
|
277
|
+
* same preference order, keeping the first row per document id.
|
|
278
|
+
*/
|
|
279
|
+
export declare function findLocalIdsByDocumentIds(execSql: ExecSql, appKind: string, documentIds: ReadonlyArray<string>): Promise<Map<string, string>>;
|
|
275
280
|
export declare function deleteDocumentRecord(execSql: ExecSql, scope: DocumentScope): Promise<void>;
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { and, desc, eq, sql } from "drizzle-orm";
|
|
1
|
+
import { and, desc, eq, inArray, sql } from "drizzle-orm";
|
|
2
2
|
import { deserializeDocumentSyncPullContinuation } from "../../../documents/shared/sync/pullContinuation.js";
|
|
3
3
|
import { normalizeEffectiveAccessLevel } from "../../../keying/accessLevel.js";
|
|
4
4
|
import { documentHistoryUpdates, documents } from "../../../sqlite/schema/index.js";
|
|
5
|
+
import { sqliteRowsPerStatement } from "../../../sqlite/sqliteBindBudget.js";
|
|
5
6
|
import { getClientSQLitePersistenceRuntime } from "../../../sqlite/sqlitePersistenceRuntime.js";
|
|
6
7
|
/**
|
|
7
8
|
* The ONE select shape for a full documents-row record: every reader that
|
|
@@ -66,8 +67,12 @@ export async function loadDocumentRecord(execSql, scope) {
|
|
|
66
67
|
.limit(1);
|
|
67
68
|
return rows[0] ? mapSelectedDocumentRecord(rows[0]) : null;
|
|
68
69
|
}
|
|
69
|
-
|
|
70
|
-
|
|
70
|
+
/**
|
|
71
|
+
* Duplicate remote identities can survive an interrupted local adoption, so
|
|
72
|
+
* the row to use for a document id is chosen by this order: queued or
|
|
73
|
+
* deferred edits first, then a stable fallback.
|
|
74
|
+
*/
|
|
75
|
+
function localIdPreferenceOrder() {
|
|
71
76
|
const hasPendingUpdates = sql `EXISTS (
|
|
72
77
|
SELECT 1
|
|
73
78
|
FROM ${documentHistoryUpdates}
|
|
@@ -82,16 +87,46 @@ export async function findLocalIdByDocumentId(execSql, appKind, documentId) {
|
|
|
82
87
|
AND ${documents.pendingBaseVersion} <> ${documents.snapshotEndVersion}
|
|
83
88
|
)
|
|
84
89
|
)`;
|
|
90
|
+
return [
|
|
91
|
+
desc(hasPendingLocalWork),
|
|
92
|
+
desc(documents.updatedAt),
|
|
93
|
+
desc(documents.localId),
|
|
94
|
+
];
|
|
95
|
+
}
|
|
96
|
+
export async function findLocalIdByDocumentId(execSql, appKind, documentId) {
|
|
97
|
+
const { db } = getClientSQLitePersistenceRuntime(execSql);
|
|
85
98
|
const rows = await db
|
|
86
99
|
.select({ localId: documents.localId })
|
|
87
100
|
.from(documents)
|
|
88
101
|
.where(and(eq(documents.appKind, appKind), eq(documents.documentId, documentId)))
|
|
89
|
-
|
|
90
|
-
// Preserve queued or deferred edits, then make the fallback stable.
|
|
91
|
-
.orderBy(desc(hasPendingLocalWork), desc(documents.updatedAt), desc(documents.localId))
|
|
102
|
+
.orderBy(...localIdPreferenceOrder())
|
|
92
103
|
.limit(1);
|
|
93
104
|
return rows[0]?.localId ?? null;
|
|
94
105
|
}
|
|
106
|
+
/**
|
|
107
|
+
* `findLocalIdByDocumentId` for many document ids: one read per chunk, in the
|
|
108
|
+
* same preference order, keeping the first row per document id.
|
|
109
|
+
*/
|
|
110
|
+
export async function findLocalIdsByDocumentIds(execSql, appKind, documentIds) {
|
|
111
|
+
const { db } = getClientSQLitePersistenceRuntime(execSql);
|
|
112
|
+
const localIds = new Map();
|
|
113
|
+
const unique = Array.from(new Set(documentIds));
|
|
114
|
+
// One bind for the app kind; the rest carry document ids.
|
|
115
|
+
const chunkSize = sqliteRowsPerStatement(1, 1);
|
|
116
|
+
for (let offset = 0; offset < unique.length; offset += chunkSize) {
|
|
117
|
+
const rows = await db
|
|
118
|
+
.select({ documentId: documents.documentId, localId: documents.localId })
|
|
119
|
+
.from(documents)
|
|
120
|
+
.where(and(eq(documents.appKind, appKind), inArray(documents.documentId, unique.slice(offset, offset + chunkSize))))
|
|
121
|
+
.orderBy(...localIdPreferenceOrder());
|
|
122
|
+
for (const row of rows) {
|
|
123
|
+
if (row.documentId !== null && !localIds.has(row.documentId)) {
|
|
124
|
+
localIds.set(row.documentId, row.localId);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return localIds;
|
|
129
|
+
}
|
|
95
130
|
export async function deleteDocumentRecord(execSql, scope) {
|
|
96
131
|
await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {
|
|
97
132
|
await db
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentRecordPersistence.js","sourceRoot":"","sources":["documentRecordPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,uCAAuC,EA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B,CACxC,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,KAAK,CACJ,GAAG,CACD,EAAE,CAAC,SAAS,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,EACpC,EAAE,CAAC,SAAS,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,CACrC,CACF;aACA,GAAG,EAAE,CAAC;IACX,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { and, desc, eq, sql } from \"drizzle-orm\";\nimport { deserializeDocumentSyncPullContinuation } from \"../../../documents/shared/sync/pullContinuation\";\nimport { normalizeEffectiveAccessLevel } from \"../../../keying/accessLevel\";\nimport { documentHistoryUpdates, documents } from \"../../../sqlite/schema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\nimport type {\n DocumentRecord,\n DocumentScope,\n SelectedDocumentRecordRow,\n} from \"./documentPersistenceTypes\";\n\n/**\n * The ONE select shape for a full documents-row record: every reader that\n * feeds mapSelectedDocumentRecord spreads this, so a new record column cannot\n * silently miss one of them.\n */\nexport const documentRecordSelection = {\n id: documents.localId,\n documentId: documents.documentId,\n recoveryGeneration: documents.recoveryGeneration,\n recoveryDocumentId: documents.recoveryDocumentId,\n snapshotEndVersion: documents.snapshotEndVersion,\n accessEpoch: documents.accessEpoch,\n accessStateHash: documents.accessStateHash,\n effectiveAccessLevel: documents.effectiveAccessLevel,\n lastCommitLsn: documents.lastCommitLsn,\n documentManifestBundle: documents.documentManifestBundle,\n contentKeyBundle: documents.contentKeyBundle,\n documentKekTargets: documents.documentKekTargets,\n pendingBaseVersion: documents.pendingBaseVersion,\n pullContinuation: documents.pullContinuation,\n};\n\nexport function mapSelectedDocumentRecord(\n row: SelectedDocumentRecordRow,\n): DocumentRecord {\n const record: DocumentRecord = {\n id: row.id,\n documentId: row.documentId,\n recoveryGeneration: row.recoveryGeneration,\n snapshotEndVersion: row.snapshotEndVersion,\n accessEpoch: row.accessEpoch,\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n row.effectiveAccessLevel,\n ),\n lastCommitLsn: row.lastCommitLsn,\n contentKeyBundle: row.contentKeyBundle,\n documentKekTargets: row.documentKekTargets,\n documentManifestBundle: row.documentManifestBundle,\n };\n\n if (row.accessStateHash !== null) {\n record.accessStateHash = row.accessStateHash;\n }\n\n if (row.recoveryDocumentId !== null) {\n record.recoveryDocumentId = row.recoveryDocumentId;\n }\n\n // Only surface the marker when one was persisted, so a row that never stored\n // one keeps its prior shape (and init falls through to seeding it).\n if (row.pendingBaseVersion !== null) {\n record.pendingBaseVersion = row.pendingBaseVersion;\n }\n\n const pullContinuation = deserializeDocumentSyncPullContinuation(\n row.pullContinuation,\n );\n if (pullContinuation !== null) {\n record.pullContinuation = pullContinuation;\n } else if (row.pullContinuation !== null) {\n record.pullContinuationRecoveryRequired = true;\n }\n\n return record;\n}\n\nexport async function loadDocumentRecord(\n execSql: ExecSql,\n scope: DocumentScope,\n): Promise<DocumentRecord | null> {\n const { db } = getClientSQLitePersistenceRuntime(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\n return rows[0] ? mapSelectedDocumentRecord(rows[0]) : null;\n}\n\nexport async function findLocalIdByDocumentId(\n execSql: ExecSql,\n appKind: string,\n documentId: string,\n): Promise<string | null> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const hasPendingUpdates = sql<number>`EXISTS (\n SELECT 1\n FROM ${documentHistoryUpdates}\n WHERE ${documentHistoryUpdates.appKind} = ${documents.appKind}\n AND ${documentHistoryUpdates.localId} = ${documents.localId}\n AND ${documentHistoryUpdates.updateId} IS NOT NULL\n )`;\n const hasPendingLocalWork = sql<number>`(\n ${hasPendingUpdates}\n OR (\n ${documents.pendingBaseVersion} IS NOT NULL\n AND ${documents.pendingBaseVersion} <> ${documents.snapshotEndVersion}\n )\n )`;\n const rows = await db\n .select({ localId: documents.localId })\n .from(documents)\n .where(\n and(eq(documents.appKind, appKind), eq(documents.documentId, documentId)),\n )\n // Duplicate remote identities can survive an interrupted local adoption.\n // Preserve queued or deferred edits, then make the fallback stable.\n .orderBy(\n desc(hasPendingLocalWork),\n desc(documents.updatedAt),\n desc(documents.localId),\n )\n .limit(1);\n\n return rows[0]?.localId ?? null;\n}\n\nexport async function deleteDocumentRecord(\n execSql: ExecSql,\n scope: DocumentScope,\n): Promise<void> {\n await getClientSQLitePersistenceRuntime(execSql).runMutation(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"]}
|
|
1
|
+
{"version":3,"file":"documentRecordPersistence.js","sourceRoot":"","sources":["documentRecordPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAC1D,OAAO,EAAE,uCAAuC,EAAE,MAAM,iDAAiD,CAAC;AAC1G,OAAO,EAAE,6BAA6B,EAAE,MAAM,6BAA6B,CAAC;AAC5E,OAAO,EAAE,sBAAsB,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAC3E,OAAO,EAAE,sBAAsB,EAAE,MAAM,kCAAkC,CAAC;AAC1E,OAAO,EAAE,iCAAiC,EAAE,MAAM,0CAA0C,CAAC;AAQ7F;;;;GAIG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG;IACrC,EAAE,EAAE,SAAS,CAAC,OAAO;IACrB,UAAU,EAAE,SAAS,CAAC,UAAU;IAChC,kBAAkB,EAAE,SAAS,CAAC,kBAAkB;IAChD,kB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AO,CAAC,CACrC,CACF;aACA,GAAG,EAAE,CAAC;IACX,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { and, desc, eq, inArray, sql } from \"drizzle-orm\";\nimport { deserializeDocumentSyncPullContinuation } from \"../../../documents/shared/sync/pullContinuation\";\nimport { normalizeEffectiveAccessLevel } from \"../../../keying/accessLevel\";\nimport { documentHistoryUpdates, documents } from \"../../../sqlite/schema\";\nimport { sqliteRowsPerStatement } from \"../../../sqlite/sqliteBindBudget\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\nimport type {\n DocumentRecord,\n DocumentScope,\n SelectedDocumentRecordRow,\n} from \"./documentPersistenceTypes\";\n\n/**\n * The ONE select shape for a full documents-row record: every reader that\n * feeds mapSelectedDocumentRecord spreads this, so a new record column cannot\n * silently miss one of them.\n */\nexport const documentRecordSelection = {\n id: documents.localId,\n documentId: documents.documentId,\n recoveryGeneration: documents.recoveryGeneration,\n recoveryDocumentId: documents.recoveryDocumentId,\n snapshotEndVersion: documents.snapshotEndVersion,\n accessEpoch: documents.accessEpoch,\n accessStateHash: documents.accessStateHash,\n effectiveAccessLevel: documents.effectiveAccessLevel,\n lastCommitLsn: documents.lastCommitLsn,\n documentManifestBundle: documents.documentManifestBundle,\n contentKeyBundle: documents.contentKeyBundle,\n documentKekTargets: documents.documentKekTargets,\n pendingBaseVersion: documents.pendingBaseVersion,\n pullContinuation: documents.pullContinuation,\n};\n\nexport function mapSelectedDocumentRecord(\n row: SelectedDocumentRecordRow,\n): DocumentRecord {\n const record: DocumentRecord = {\n id: row.id,\n documentId: row.documentId,\n recoveryGeneration: row.recoveryGeneration,\n snapshotEndVersion: row.snapshotEndVersion,\n accessEpoch: row.accessEpoch,\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n row.effectiveAccessLevel,\n ),\n lastCommitLsn: row.lastCommitLsn,\n contentKeyBundle: row.contentKeyBundle,\n documentKekTargets: row.documentKekTargets,\n documentManifestBundle: row.documentManifestBundle,\n };\n\n if (row.accessStateHash !== null) {\n record.accessStateHash = row.accessStateHash;\n }\n\n if (row.recoveryDocumentId !== null) {\n record.recoveryDocumentId = row.recoveryDocumentId;\n }\n\n // Only surface the marker when one was persisted, so a row that never stored\n // one keeps its prior shape (and init falls through to seeding it).\n if (row.pendingBaseVersion !== null) {\n record.pendingBaseVersion = row.pendingBaseVersion;\n }\n\n const pullContinuation = deserializeDocumentSyncPullContinuation(\n row.pullContinuation,\n );\n if (pullContinuation !== null) {\n record.pullContinuation = pullContinuation;\n } else if (row.pullContinuation !== null) {\n record.pullContinuationRecoveryRequired = true;\n }\n\n return record;\n}\n\nexport async function loadDocumentRecord(\n execSql: ExecSql,\n scope: DocumentScope,\n): Promise<DocumentRecord | null> {\n const { db } = getClientSQLitePersistenceRuntime(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\n return rows[0] ? mapSelectedDocumentRecord(rows[0]) : null;\n}\n\n/**\n * Duplicate remote identities can survive an interrupted local adoption, so\n * the row to use for a document id is chosen by this order: queued or\n * deferred edits first, then a stable fallback.\n */\nfunction localIdPreferenceOrder() {\n const hasPendingUpdates = sql<number>`EXISTS (\n SELECT 1\n FROM ${documentHistoryUpdates}\n WHERE ${documentHistoryUpdates.appKind} = ${documents.appKind}\n AND ${documentHistoryUpdates.localId} = ${documents.localId}\n AND ${documentHistoryUpdates.updateId} IS NOT NULL\n )`;\n const hasPendingLocalWork = sql<number>`(\n ${hasPendingUpdates}\n OR (\n ${documents.pendingBaseVersion} IS NOT NULL\n AND ${documents.pendingBaseVersion} <> ${documents.snapshotEndVersion}\n )\n )`;\n return [\n desc(hasPendingLocalWork),\n desc(documents.updatedAt),\n desc(documents.localId),\n ];\n}\n\nexport async function findLocalIdByDocumentId(\n execSql: ExecSql,\n appKind: string,\n documentId: string,\n): Promise<string | null> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({ localId: documents.localId })\n .from(documents)\n .where(\n and(eq(documents.appKind, appKind), eq(documents.documentId, documentId)),\n )\n .orderBy(...localIdPreferenceOrder())\n .limit(1);\n\n return rows[0]?.localId ?? null;\n}\n\n/**\n * `findLocalIdByDocumentId` for many document ids: one read per chunk, in the\n * same preference order, keeping the first row per document id.\n */\nexport async function findLocalIdsByDocumentIds(\n execSql: ExecSql,\n appKind: string,\n documentIds: ReadonlyArray<string>,\n): Promise<Map<string, string>> {\n const { db } = getClientSQLitePersistenceRuntime(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({ documentId: documents.documentId, localId: documents.localId })\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\nexport async function deleteDocumentRecord(\n execSql: ExecSql,\n scope: DocumentScope,\n): Promise<void> {\n await getClientSQLitePersistenceRuntime(execSql).runMutation(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"]}
|
|
@@ -18,5 +18,5 @@ export declare function invalidateDocumentSyncPullContinuation(execSql: ExecSql,
|
|
|
18
18
|
}): Promise<DocumentRecord | null>;
|
|
19
19
|
export { enqueueDocumentPendingUpdate, enqueueDocumentPendingUpdateWithHistory, listDocumentPendingUpdates, MAX_PENDING_UPDATE_REKEYS, rekeyDocumentPendingUpdate, resetDocumentPendingUpdateRekeyBudget, settleDocumentPendingUpdate, unqueueDocumentPendingUpdates, } from "./documentPendingUpdatePersistence.js";
|
|
20
20
|
export type { DocumentRecord, DocumentScope, PendingUpdateFields, PendingUpdateRecord, } from "./documentPersistenceTypes.js";
|
|
21
|
-
export { deleteDocumentRecord, documentRecordSelection, findLocalIdByDocumentId, loadDocumentRecord, mapSelectedDocumentRecord, } from "./documentRecordPersistence.js";
|
|
21
|
+
export { deleteDocumentRecord, documentRecordSelection, findLocalIdByDocumentId, findLocalIdsByDocumentIds, loadDocumentRecord, mapSelectedDocumentRecord, } from "./documentRecordPersistence.js";
|
|
22
22
|
export { clearDocumentSyncFailure, hasRecordedTerminalSyncFailures, recordDocumentSyncFailure, } from "./documentSyncFailurePersistence.js";
|
|
@@ -30,6 +30,6 @@ export async function invalidateDocumentSyncPullContinuation(execSql, input) {
|
|
|
30
30
|
});
|
|
31
31
|
}
|
|
32
32
|
export { enqueueDocumentPendingUpdate, enqueueDocumentPendingUpdateWithHistory, listDocumentPendingUpdates, MAX_PENDING_UPDATE_REKEYS, rekeyDocumentPendingUpdate, resetDocumentPendingUpdateRekeyBudget, settleDocumentPendingUpdate, unqueueDocumentPendingUpdates, } from "./documentPendingUpdatePersistence.js";
|
|
33
|
-
export { deleteDocumentRecord, documentRecordSelection, findLocalIdByDocumentId, loadDocumentRecord, mapSelectedDocumentRecord, } from "./documentRecordPersistence.js";
|
|
33
|
+
export { deleteDocumentRecord, documentRecordSelection, findLocalIdByDocumentId, findLocalIdsByDocumentIds, loadDocumentRecord, mapSelectedDocumentRecord, } from "./documentRecordPersistence.js";
|
|
34
34
|
export { clearDocumentSyncFailure, hasRecordedTerminalSyncFailures, recordDocumentSyncFailure, } from "./documentSyncFailurePersistence.js";
|
|
35
35
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAA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CAAC,SAAS,CAAC,UAAU,EAAE,KAAK,CAAC,UAAU,CAAC,EAC1C,EAAE,CAAC,SAAS,CAAC,WAAW,EAAE,KAAK,CAAC,WAAW,CAAC,EAC5C,GAAG,CAAA,GAAG,SAAS,CAAC,eAAe,OAAO,KAAK,CAAC,eAAe,EAAE,EAC7D,GAAG,CAAA,GAAG,SAAS,CAAC,gBAAgB,OAAO,KAAK,CAAC,gBAAgB,EAAE,EAC/D,GAAG,CAAA,GAAG,SAAS,CAAC,kBAAkB,OAAO,KAAK,CAAC,kBAAkB,EAAE,EACnE,GAAG,CAAA,GAAG,SAAS,CAAC,sBAAsB,OAAO,KAAK,CAAC,sBAAsB,EAAE,EAC3E,GAAG,CAAA,GAAG,SAAS,CAAC,aAAa,OAAO,KAAK,CAAC,aAAa,EAAE,EACzD,EAAE,CAAC,SAAS,CAAC,gBAAgB,EAAE,oBAAoB,CAAC,CACrD,CACF;aACA,GAAG,EAAE,CAAC;QACT,OAAO,kBAAkB,CAAC,aAAa,EAAE;YACvC,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,OAAO,EAAE,KAAK,CAAC,OAAO;SACvB,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC;AAED,OAAO,EACL,4BAA4B,EAC5B,uCAAuC,EACvC,0BAA0B,EAC1B,yBAAyB,EACzB,0BAA0B,EAC1B,qCAAqC,EACrC,2BAA2B,EAC3B,6BAA6B,GAC9B,MAAM,oCAAoC,CAAC;AAO5C,OAAO,EACL,oBAAoB,EACpB,uBAAuB,EACvB,uBAAuB,EACvB,kBAAkB,EAClB,yBAAyB,GAC1B,MAAM,6BAA6B,CAAC;AACrC,OAAO,EACL,wBAAwB,EACxB,+BAA+B,EAC/B,yBAAyB,GAC1B,MAAM,kCAAkC,CAAC","sourcesContent":["import { and, eq, sql } from \"drizzle-orm\";\nimport {\n DOCUMENT_SYNC_PULL_RECOVERY_REQUIRED,\n type DocumentSyncPullContinuation,\n serializeDocumentSyncPullContinuation,\n} from \"../../../documents/shared/sync/pullContinuation\";\nimport {\n documentProjectionTables,\n documents,\n documentTables,\n} from \"../../../sqlite/schema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../../sqlite/sqlSchema\";\nimport type { DocumentRecord } from \"./documentPersistenceTypes\";\nimport { loadDocumentRecord } from \"./documentRecordPersistence\";\n\nexport function ensureDocumentTables(execSql: ExecSql): Promise<void> {\n return ensureSqlTables(execSql, documentTables);\n}\n\nexport function ensureDocumentProjectionTables(\n execSql: ExecSql,\n): Promise<void> {\n return ensureSqlTables(execSql, documentProjectionTables);\n}\n\n/** Replace only the exact rejected continuation with a durable recovery marker. */\nexport async function invalidateDocumentSyncPullContinuation(\n execSql: ExecSql,\n input: {\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): Promise<DocumentRecord | null> {\n await ensureDocumentTables(execSql);\n const expectedContinuation = serializeDocumentSyncPullContinuation(\n input.continuation,\n );\n if (expectedContinuation === null) return null;\n return runSerializedSqlMutation(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 loadDocumentRecord(lockedExecSql, {\n appKind: input.appKind,\n localId: input.localId,\n });\n });\n}\n\nexport {\n enqueueDocumentPendingUpdate,\n enqueueDocumentPendingUpdateWithHistory,\n listDocumentPendingUpdates,\n MAX_PENDING_UPDATE_REKEYS,\n rekeyDocumentPendingUpdate,\n resetDocumentPendingUpdateRekeyBudget,\n settleDocumentPendingUpdate,\n unqueueDocumentPendingUpdates,\n} from \"./documentPendingUpdatePersistence\";\nexport type {\n DocumentRecord,\n DocumentScope,\n PendingUpdateFields,\n PendingUpdateRecord,\n} from \"./documentPersistenceTypes\";\nexport {\n deleteDocumentRecord,\n documentRecordSelection,\n findLocalIdByDocumentId,\n loadDocumentRecord,\n mapSelectedDocumentRecord,\n} from \"./documentRecordPersistence\";\nexport {\n clearDocumentSyncFailure,\n hasRecordedTerminalSyncFailures,\n recordDocumentSyncFailure,\n} from \"./documentSyncFailurePersistence\";\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EACL,oCAAoC,EAEpC,qCAAqC,GACtC,MAAM,iDAAiD,CAAC;AACzD,OAAO,EACL,wBAAwB,EACxB,SAAS,EACT,cAAc,GACf,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,iCAAiC,EAAE,MAAM,0CAA0C,CAAC;AAC7F,OAAO,EAEL,eAAe,EACf,wBAAwB,GACzB,MAAM,2BAA2B,CAAC;AAEnC,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAEjE,MAAM,UAAU,oBAAoB,CAAC,OAAgB;IACnD,OAAO,eAAe,CAAC,OAAO,EAAE,cAAc,CAAC,CAAC;AAClD,CAAC;AAED,MAAM,UAAU,8BAA8B,CAC5C,OAAgB;IAEhB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D,EAAE,CAAC,SAAS,CAAC,gBAAgB,EAAE,oBAAoB,CAAC,CACrD,CACF;aACA,GAAG,EAAE,CAAC;QACT,OAAO,kBAAkB,CAAC,aAAa,EAAE;YACvC,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,OAAO,EAAE,KAAK,CAAC,OAAO;SACvB,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC;AAED,OAAO,EACL,4BAA4B,EAC5B,uCAAuC,EACvC,0BAA0B,EAC1B,yBAAyB,EACzB,0BAA0B,EAC1B,qCAAqC,EACrC,2BAA2B,EAC3B,6BAA6B,GAC9B,MAAM,oCAAoC,CAAC;AAO5C,OAAO,EACL,oBAAoB,EACpB,uBAAuB,EACvB,uBAAuB,EACvB,yBAAyB,EACzB,kBAAkB,EAClB,yBAAyB,GAC1B,MAAM,6BAA6B,CAAC;AACrC,OAAO,EACL,wBAAwB,EACxB,+BAA+B,EAC/B,yBAAyB,GAC1B,MAAM,kCAAkC,CAAC","sourcesContent":["import { and, eq, sql } from \"drizzle-orm\";\nimport {\n DOCUMENT_SYNC_PULL_RECOVERY_REQUIRED,\n type DocumentSyncPullContinuation,\n serializeDocumentSyncPullContinuation,\n} from \"../../../documents/shared/sync/pullContinuation\";\nimport {\n documentProjectionTables,\n documents,\n documentTables,\n} from \"../../../sqlite/schema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../../sqlite/sqlSchema\";\nimport type { DocumentRecord } from \"./documentPersistenceTypes\";\nimport { loadDocumentRecord } from \"./documentRecordPersistence\";\n\nexport function ensureDocumentTables(execSql: ExecSql): Promise<void> {\n return ensureSqlTables(execSql, documentTables);\n}\n\nexport function ensureDocumentProjectionTables(\n execSql: ExecSql,\n): Promise<void> {\n return ensureSqlTables(execSql, documentProjectionTables);\n}\n\n/** Replace only the exact rejected continuation with a durable recovery marker. */\nexport async function invalidateDocumentSyncPullContinuation(\n execSql: ExecSql,\n input: {\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): Promise<DocumentRecord | null> {\n await ensureDocumentTables(execSql);\n const expectedContinuation = serializeDocumentSyncPullContinuation(\n input.continuation,\n );\n if (expectedContinuation === null) return null;\n return runSerializedSqlMutation(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 loadDocumentRecord(lockedExecSql, {\n appKind: input.appKind,\n localId: input.localId,\n });\n });\n}\n\nexport {\n enqueueDocumentPendingUpdate,\n enqueueDocumentPendingUpdateWithHistory,\n listDocumentPendingUpdates,\n MAX_PENDING_UPDATE_REKEYS,\n rekeyDocumentPendingUpdate,\n resetDocumentPendingUpdateRekeyBudget,\n settleDocumentPendingUpdate,\n unqueueDocumentPendingUpdates,\n} from \"./documentPendingUpdatePersistence\";\nexport type {\n DocumentRecord,\n DocumentScope,\n PendingUpdateFields,\n PendingUpdateRecord,\n} from \"./documentPersistenceTypes\";\nexport {\n deleteDocumentRecord,\n documentRecordSelection,\n findLocalIdByDocumentId,\n findLocalIdsByDocumentIds,\n loadDocumentRecord,\n mapSelectedDocumentRecord,\n} from \"./documentRecordPersistence\";\nexport {\n clearDocumentSyncFailure,\n hasRecordedTerminalSyncFailures,\n recordDocumentSyncFailure,\n} from \"./documentSyncFailurePersistence\";\n"]}
|
|
@@ -9,4 +9,6 @@ export interface DocumentPurgeCheckpoint {
|
|
|
9
9
|
export declare function loadDocumentPurgeCheckpoint(execSql: ExecSql, documentId: string): Promise<DocumentPurgeCheckpoint | null>;
|
|
10
10
|
/** Whether the document was permanently purged, read in the caller's transaction. */
|
|
11
11
|
export declare function hasDocumentPurgeCheckpointInTransaction(tx: ClientSQLiteTransactionScope, documentId: string): Promise<boolean>;
|
|
12
|
+
/** The document ids among `documentIds` that carry a purge checkpoint. */
|
|
13
|
+
export declare function listPurgedDocumentIdsInTransaction(tx: ClientSQLiteTransactionScope, documentIds: ReadonlyArray<string>): Promise<Set<string>>;
|
|
12
14
|
export declare function storeDocumentPurgeCheckpointInTransaction(tx: ClientSQLiteTransactionScope, checkpoint: DocumentPurgeCheckpoint, updatedAt: string): Promise<void>;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { KeyingVerificationError } from "../../../internal/crypto/index.js";
|
|
2
|
-
import { eq } from "drizzle-orm";
|
|
2
|
+
import { eq, inArray } from "drizzle-orm";
|
|
3
3
|
import { documentPurgeCheckpoints, keyingCheckpointTables, } from "../../sqlite/schema/index.js";
|
|
4
|
+
import { sqliteRowsPerStatement } from "../../sqlite/sqliteBindBudget.js";
|
|
4
5
|
import { getClientSQLitePersistenceRuntime } from "../../sqlite/sqlitePersistenceRuntime.js";
|
|
5
6
|
import { ensureSqlTables } from "../../sqlite/sqlSchema.js";
|
|
6
7
|
export async function loadDocumentPurgeCheckpoint(execSql, documentId) {
|
|
@@ -26,6 +27,21 @@ export async function hasDocumentPurgeCheckpointInTransaction(tx, documentId) {
|
|
|
26
27
|
.limit(1);
|
|
27
28
|
return row !== undefined;
|
|
28
29
|
}
|
|
30
|
+
/** The document ids among `documentIds` that carry a purge checkpoint. */
|
|
31
|
+
export async function listPurgedDocumentIdsInTransaction(tx, documentIds) {
|
|
32
|
+
const purged = new Set();
|
|
33
|
+
const unique = Array.from(new Set(documentIds));
|
|
34
|
+
const chunkSize = sqliteRowsPerStatement(1);
|
|
35
|
+
for (let offset = 0; offset < unique.length; offset += chunkSize) {
|
|
36
|
+
const rows = await tx
|
|
37
|
+
.select({ documentId: documentPurgeCheckpoints.documentId })
|
|
38
|
+
.from(documentPurgeCheckpoints)
|
|
39
|
+
.where(inArray(documentPurgeCheckpoints.documentId, unique.slice(offset, offset + chunkSize)));
|
|
40
|
+
for (const row of rows)
|
|
41
|
+
purged.add(row.documentId);
|
|
42
|
+
}
|
|
43
|
+
return purged;
|
|
44
|
+
}
|
|
29
45
|
export async function storeDocumentPurgeCheckpointInTransaction(tx, checkpoint, updatedAt) {
|
|
30
46
|
const [stored] = await tx
|
|
31
47
|
.select({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentPurgeCheckpointPersistence.js","sourceRoot":"","sources":["documentPurgeCheckpointPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"documentPurgeCheckpointPersistence.js","sourceRoot":"","sources":["documentPurgeCheckpointPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EACL,wBAAwB,EACxB,sBAAsB,GACvB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,sBAAsB,EAAE,MAAM,+BAA+B,CAAC;AAEvE,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,CAAC;AAC1F,OAAO,EAAgB,eAAe,EAAE,MAAM,w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AAsE,CACvE,CAAC;QACJ,CAAC;QACD,OAAO;IACT,CAAC;IACD,MAAM,EAAE;SACL,MAAM,CAAC,wBAAwB,CAAC;SAChC,MAAM,CAAC,EAAE,GAAG,UAAU,EAAE,SAAS,EAAE,CAAC;SACpC,GAAG,EAAE,CAAC;AACX,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { eq, inArray } from \"drizzle-orm\";\nimport {\n documentPurgeCheckpoints,\n keyingCheckpointTables,\n} from \"../../sqlite/schema\";\nimport { sqliteRowsPerStatement } from \"../../sqlite/sqliteBindBudget\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\n\nexport interface DocumentPurgeCheckpoint {\n readonly documentId: string;\n readonly documentManifestHash: string;\n readonly organizationId: string;\n readonly purgeEventHash: string;\n}\n\nexport async function loadDocumentPurgeCheckpoint(\n execSql: ExecSql,\n documentId: string,\n): Promise<DocumentPurgeCheckpoint | null> {\n await ensureSqlTables(execSql, keyingCheckpointTables);\n const [row] = await getClientSQLitePersistenceRuntime(execSql)\n .db.select({\n documentId: documentPurgeCheckpoints.documentId,\n documentManifestHash: documentPurgeCheckpoints.documentManifestHash,\n organizationId: documentPurgeCheckpoints.organizationId,\n purgeEventHash: documentPurgeCheckpoints.purgeEventHash,\n })\n .from(documentPurgeCheckpoints)\n .where(eq(documentPurgeCheckpoints.documentId, documentId))\n .limit(1);\n return row ?? null;\n}\n\n/** Whether the document was permanently purged, read in the caller's transaction. */\nexport async function hasDocumentPurgeCheckpointInTransaction(\n tx: ClientSQLiteTransactionScope,\n documentId: string,\n): Promise<boolean> {\n const [row] = await tx\n .select({ documentId: documentPurgeCheckpoints.documentId })\n .from(documentPurgeCheckpoints)\n .where(eq(documentPurgeCheckpoints.documentId, documentId))\n .limit(1);\n return row !== undefined;\n}\n\n/** The document ids among `documentIds` that carry a purge checkpoint. */\nexport async function listPurgedDocumentIdsInTransaction(\n tx: ClientSQLiteTransactionScope,\n documentIds: ReadonlyArray<string>,\n): Promise<Set<string>> {\n const purged = new Set<string>();\n const unique = Array.from(new Set(documentIds));\n const chunkSize = sqliteRowsPerStatement(1);\n for (let offset = 0; offset < unique.length; offset += chunkSize) {\n const rows = await tx\n .select({ documentId: documentPurgeCheckpoints.documentId })\n .from(documentPurgeCheckpoints)\n .where(\n inArray(\n documentPurgeCheckpoints.documentId,\n unique.slice(offset, offset + chunkSize),\n ),\n );\n for (const row of rows) purged.add(row.documentId);\n }\n return purged;\n}\n\nexport async function storeDocumentPurgeCheckpointInTransaction(\n tx: ClientSQLiteTransactionScope,\n checkpoint: DocumentPurgeCheckpoint,\n updatedAt: string,\n): Promise<void> {\n const [stored] = await tx\n .select({\n documentManifestHash: documentPurgeCheckpoints.documentManifestHash,\n organizationId: documentPurgeCheckpoints.organizationId,\n purgeEventHash: documentPurgeCheckpoints.purgeEventHash,\n })\n .from(documentPurgeCheckpoints)\n .where(eq(documentPurgeCheckpoints.documentId, checkpoint.documentId))\n .limit(1);\n if (stored) {\n if (\n stored.documentManifestHash !== checkpoint.documentManifestHash ||\n stored.organizationId !== checkpoint.organizationId ||\n stored.purgeEventHash !== checkpoint.purgeEventHash\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"Document purge checkpoint conflicts with the verified terminal event\",\n );\n }\n return;\n }\n await tx\n .insert(documentPurgeCheckpoints)\n .values({ ...checkpoint, updatedAt })\n .run();\n}\n"]}
|