@tearleads/client-sdk 0.1.215 → 0.1.217
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/documentContainerProjectionPersistence.d.ts +32 -0
- package/data/persistence/container-contents/documentContainerProjectionPersistence.js +35 -28
- package/data/persistence/container-contents/documentContainerProjectionPersistence.js.map +1 -1
- package/data/persistence/container-contents/documentPlacement.d.ts +20 -0
- package/data/sync/organizationSyncPauses.d.ts +21 -10
- package/data/sync/organizationSyncPauses.js +73 -59
- package/data/sync/organizationSyncPauses.js.map +1 -1
- package/index.d.ts +1 -1
- package/index.js +1 -1
- package/index.js.map +1 -1
- package/package.json +1 -1
- package/stores/documents/documentStore/initialization/index.js +2 -2
- package/stores/documents/documentStore/initialization/index.js.map +1 -1
- package/workflows/container-contents/container-state/purge/purgeTree.js +2 -2
- package/workflows/container-contents/container-state/purge/purgeTree.js.map +1 -1
- package/workflows/container-contents/documentLinks/documentLinkIntent.js +4 -4
- package/workflows/container-contents/documentLinks/documentLinkIntent.js.map +1 -1
- package/workflows/container-contents/documentLinks/index.js +4 -11
- package/workflows/container-contents/documentLinks/index.js.map +1 -1
- package/workflows/container-contents/documentMove/documentMoveIntent.js +2 -3
- package/workflows/container-contents/documentMove/documentMoveIntent.js.map +1 -1
- package/workflows/container-contents/documentMove/documentMoveVanishedRefresh.js +2 -2
- package/workflows/container-contents/documentMove/documentMoveVanishedRefresh.js.map +1 -1
- package/workflows/container-contents/documentQueries/documentSubtreeQueries.js +3 -3
- package/workflows/container-contents/documentQueries/documentSubtreeQueries.js.map +1 -1
- package/workflows/container-contents/documentQueries/index.js +3 -3
- package/workflows/container-contents/documentQueries/index.js.map +1 -1
- package/workflows/container-contents/index.d.ts +1 -1
- package/workflows/container-contents/index.js +1 -1
- package/workflows/container-contents/index.js.map +1 -1
- package/workflows/container-contents/syncPause/discoveryGuard.js +2 -2
- package/workflows/container-contents/syncPause/discoveryGuard.js.map +1 -1
- package/workflows/container-contents/syncPause/documentRemoval.js +2 -2
- package/workflows/container-contents/syncPause/documentRemoval.js.map +1 -1
- package/workflows/sync/index.d.ts +1 -1
- package/workflows/sync/index.js +1 -1
- package/workflows/sync/index.js.map +1 -1
- package/workflows/container-contents/documentLinks/index.d.ts +0 -46
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type ClientSQLiteTransactionScope } from "../../sqlite/sqlitePersistenceRuntime.js";
|
|
2
|
+
import { type ExecSql } from "../../sqlite/sqlSchema.js";
|
|
3
|
+
import { type DocumentPlacementInput, type DocumentPlacementWriteOptions } from "./documentPlacement.js";
|
|
4
|
+
/** Link rows and their tombstone holds leave together on a remote reset. */
|
|
5
|
+
export declare function deleteDocumentPlacementRowsByContainerIds(tx: ClientSQLiteTransactionScope, containerIds: ReadonlyArray<string>): Promise<void>;
|
|
6
|
+
export declare function deleteDocumentPlacementRowsByDocumentIds(tx: ClientSQLiteTransactionScope, documentIds: ReadonlyArray<string>): Promise<void>;
|
|
7
|
+
/** Removes the listed (document, container) placements, 50 pairs per statement. */
|
|
8
|
+
export declare function deleteDocumentPlacementRowsInTransaction(tx: ClientSQLiteTransactionScope, placements: ReadonlyArray<{
|
|
9
|
+
readonly containerId: string;
|
|
10
|
+
readonly documentId: string;
|
|
11
|
+
}>): Promise<void>;
|
|
12
|
+
/**
|
|
13
|
+
* Removes each document's placements outside the containers its head links,
|
|
14
|
+
* batching documents so one statement stays inside SQLite's bind budget.
|
|
15
|
+
*/
|
|
16
|
+
export declare function deleteUnlinkedDocumentPlacementRowsInTransaction(tx: ClientSQLiteTransactionScope, linkedContainerIdsByDocumentId: ReadonlyMap<string, ReadonlySet<string>>): Promise<void>;
|
|
17
|
+
/** Removes a deleted document's queued placement intents and link targets. */
|
|
18
|
+
export declare function deleteDocumentPlacementIntentsInTransaction(tx: ClientSQLiteTransactionScope, documentId: string): Promise<void>;
|
|
19
|
+
/** The caller owns the open document commit and must propagate every failure. */
|
|
20
|
+
export declare function replaceDocumentLinksInTransaction(transactionExecSql: ExecSql, documentId: string, containerIds: readonly string[], options?: Omit<DocumentPlacementWriteOptions, "stillCurrent">): Promise<void>;
|
|
21
|
+
/** The document container projection, bound to one executor and clock. */
|
|
22
|
+
export declare class DocumentContainerProjectionRepository {
|
|
23
|
+
private readonly execSql;
|
|
24
|
+
private readonly now;
|
|
25
|
+
constructor(execSql: ExecSql, now?: () => Date);
|
|
26
|
+
ensureSchema(): Promise<void>;
|
|
27
|
+
listLinkedContainerIds(documentId: string): Promise<ReadonlyArray<string>>;
|
|
28
|
+
listLinkedContainerIdsByDocumentIds(documentIds: ReadonlyArray<string>): Promise<ReadonlyMap<string, ReadonlyArray<string>>>;
|
|
29
|
+
listDocumentIdsByContainerIds(containerIds: ReadonlyArray<string>): Promise<ReadonlyArray<string>>;
|
|
30
|
+
replaceDocumentLinks(documentId: string, containerIds: ReadonlyArray<string>, options?: DocumentPlacementWriteOptions): Promise<void>;
|
|
31
|
+
replaceDocumentLinksBatch(inputs: ReadonlyArray<DocumentPlacementInput>, options?: DocumentPlacementWriteOptions): Promise<void>;
|
|
32
|
+
}
|
|
@@ -90,7 +90,7 @@ async function ensureDocumentLinksSchema(execSql) {
|
|
|
90
90
|
...documentTables,
|
|
91
91
|
]);
|
|
92
92
|
}
|
|
93
|
-
async function replaceDocumentLinkRows(tx, latest, options) {
|
|
93
|
+
async function replaceDocumentLinkRows(tx, latest, now, options) {
|
|
94
94
|
const writable = await filterWritableDocumentPlacements(tx, [...latest.values()], options);
|
|
95
95
|
if (writable.length === 0)
|
|
96
96
|
return;
|
|
@@ -112,7 +112,7 @@ async function replaceDocumentLinkRows(tx, latest, options) {
|
|
|
112
112
|
.map((input) => input.documentId)))
|
|
113
113
|
.run();
|
|
114
114
|
}
|
|
115
|
-
const updatedAt =
|
|
115
|
+
const updatedAt = now().toISOString();
|
|
116
116
|
const rows = writable.flatMap((input) => Array.from(new Set(input.containerIds))
|
|
117
117
|
.sort()
|
|
118
118
|
.map((containerId) => ({
|
|
@@ -132,29 +132,36 @@ async function replaceDocumentLinkRows(tx, latest, options) {
|
|
|
132
132
|
/** The caller owns the open document commit and must propagate every failure. */
|
|
133
133
|
export async function replaceDocumentLinksInTransaction(transactionExecSql, documentId, containerIds, options) {
|
|
134
134
|
await ensureDocumentLinksSchema(transactionExecSql);
|
|
135
|
-
await replaceDocumentLinkRows(getClientSQLitePersistenceRuntime(transactionExecSql).db, new Map([[documentId, { documentId, containerIds }]]), options);
|
|
135
|
+
await replaceDocumentLinkRows(getClientSQLitePersistenceRuntime(transactionExecSql).db, new Map([[documentId, { documentId, containerIds }]]), () => new Date(), options);
|
|
136
136
|
}
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
137
|
+
/** The document container projection, bound to one executor and clock. */
|
|
138
|
+
export class DocumentContainerProjectionRepository {
|
|
139
|
+
execSql;
|
|
140
|
+
now;
|
|
141
|
+
constructor(execSql, now = () => new Date()) {
|
|
142
|
+
this.execSql = execSql;
|
|
143
|
+
this.now = now;
|
|
144
|
+
}
|
|
145
|
+
async ensureSchema() {
|
|
146
|
+
await ensureSqlTables(this.execSql, documentContainerProjectionTables);
|
|
147
|
+
}
|
|
148
|
+
async listLinkedContainerIds(documentId) {
|
|
149
|
+
await this.ensureSchema();
|
|
150
|
+
const { db } = getClientSQLitePersistenceRuntime(this.execSql);
|
|
144
151
|
const rows = await db
|
|
145
152
|
.select({ containerId: documentContainerProjection.containerId })
|
|
146
153
|
.from(documentContainerProjection)
|
|
147
154
|
.where(eq(documentContainerProjection.documentId, documentId))
|
|
148
155
|
.orderBy(asc(documentContainerProjection.containerId));
|
|
149
156
|
return rows.map((row) => row.containerId);
|
|
150
|
-
}
|
|
151
|
-
async listLinkedContainerIdsByDocumentIds(
|
|
152
|
-
await
|
|
157
|
+
}
|
|
158
|
+
async listLinkedContainerIdsByDocumentIds(documentIds) {
|
|
159
|
+
await this.ensureSchema();
|
|
153
160
|
const uniqueDocumentIds = Array.from(new Set(documentIds));
|
|
154
161
|
if (uniqueDocumentIds.length === 0) {
|
|
155
162
|
return new Map();
|
|
156
163
|
}
|
|
157
|
-
const { db } = getClientSQLitePersistenceRuntime(execSql);
|
|
164
|
+
const { db } = getClientSQLitePersistenceRuntime(this.execSql);
|
|
158
165
|
const rows = await db
|
|
159
166
|
.select({
|
|
160
167
|
documentId: documentContainerProjection.documentId,
|
|
@@ -173,36 +180,36 @@ export const sqlDocumentContainerProjectionPersistence = {
|
|
|
173
180
|
linkedContainerIdsByDocumentId.set(row.documentId, linkedContainerIds);
|
|
174
181
|
}
|
|
175
182
|
return linkedContainerIdsByDocumentId;
|
|
176
|
-
}
|
|
177
|
-
async listDocumentIdsByContainerIds(
|
|
178
|
-
await
|
|
183
|
+
}
|
|
184
|
+
async listDocumentIdsByContainerIds(containerIds) {
|
|
185
|
+
await this.ensureSchema();
|
|
179
186
|
const uniqueContainerIds = Array.from(new Set(containerIds));
|
|
180
187
|
if (uniqueContainerIds.length === 0) {
|
|
181
188
|
return [];
|
|
182
189
|
}
|
|
183
|
-
const { db } = getClientSQLitePersistenceRuntime(execSql);
|
|
190
|
+
const { db } = getClientSQLitePersistenceRuntime(this.execSql);
|
|
184
191
|
const rows = await db
|
|
185
192
|
.selectDistinct({ documentId: documentContainerProjection.documentId })
|
|
186
193
|
.from(documentContainerProjection)
|
|
187
194
|
.where(inArray(documentContainerProjection.containerId, uniqueContainerIds))
|
|
188
195
|
.orderBy(asc(documentContainerProjection.documentId));
|
|
189
196
|
return rows.map((row) => row.documentId);
|
|
190
|
-
}
|
|
191
|
-
async replaceDocumentLinks(
|
|
192
|
-
await
|
|
193
|
-
}
|
|
194
|
-
async replaceDocumentLinksBatch(
|
|
195
|
-
await ensureDocumentLinksSchema(execSql);
|
|
197
|
+
}
|
|
198
|
+
async replaceDocumentLinks(documentId, containerIds, options) {
|
|
199
|
+
await this.replaceDocumentLinksBatch([{ documentId, containerIds }], options);
|
|
200
|
+
}
|
|
201
|
+
async replaceDocumentLinksBatch(inputs, options) {
|
|
202
|
+
await ensureDocumentLinksSchema(this.execSql);
|
|
196
203
|
const latest = new Map(inputs.map((input) => [input.documentId, input]));
|
|
197
204
|
if (latest.size === 0)
|
|
198
205
|
return;
|
|
199
|
-
const runtime = getClientSQLitePersistenceRuntime(execSql);
|
|
200
|
-
const replace = (tx) => replaceDocumentLinkRows(tx, latest, options);
|
|
206
|
+
const runtime = getClientSQLitePersistenceRuntime(this.execSql);
|
|
207
|
+
const replace = (tx) => replaceDocumentLinkRows(tx, latest, this.now, options);
|
|
201
208
|
if (options?.stillCurrent) {
|
|
202
209
|
await runtime.guardedTransaction(replace, options.stillCurrent);
|
|
203
210
|
return;
|
|
204
211
|
}
|
|
205
212
|
await runtime.transaction(replace);
|
|
206
|
-
}
|
|
207
|
-
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
208
215
|
//# sourceMappingURL=documentContainerProjectionPersistence.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentContainerProjectionPersistence.js","sourceRoot":"","sources":["documentContainerProjectionPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,UAAU,EAAE,EAAE,EAAY,MAAM,aAAa,CAAC;AAC9E,OAAO,EACL,6BAA6B,EAC7B,iBAAiB,EACjB,kBAAkB,EAClB,YAAY,GACb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,yBAAyB,EAAE,MAAM,mDAAmD,CAAC;AAC9F,OAAO,EACL,2BAA2B,EAC3B,iCAAiC,GAClC,MAAM,8CAA8C,CAAC;AACtD,OAAO,EAAE,cAAc,EAAE,MAAM,0CAA0C,CAAC;AAC1E,OAAO,EACL,2BAA2B,EAC3B,kBAAkB,EAClB,4BAA4B,EAC5B,qBAAqB,GACtB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAEL,iCAAiC,GACl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AAC,EAAE,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;QAC/C,IAAI,OAAO,EAAE,YAAY,EAAE,CAAC;YAC1B,MAAM,OAAO,CAAC,kBAAkB,CAAC,OAAO,EAAE,OAAO,CAAC,YAAY,CAAC,CAAC;YAChE,OAAO;QACT,CAAC;QACD,MAAM,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;IACrC,CAAC;CACF,CAAC","sourcesContent":["import { and, asc, eq, inArray, notInArray, or, type SQL } from \"drizzle-orm\";\nimport {\n documentPlacementIntentTables,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n} from \"../../sqlite/schema\";\nimport { documentIntentLinkTargets } from \"../../sqlite/schema/documentPlacementIntentSchema\";\nimport {\n documentContainerProjection,\n documentContainerProjectionTables,\n} from \"../../sqlite/schema/documentProjectionSchema\";\nimport { documentTables } from \"../../sqlite/schema/documentRecordSchema\";\nimport {\n REMOTE_RESET_SQL_BATCH_SIZE,\n remoteResetBatches,\n SQLITE_BOUND_VARIABLE_BUDGET,\n sqliteInsertBatchSize,\n} from \"../../sqlite/sqliteBindBudget\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport {\n deleteContainerDocumentTombstoneHoldRowsForLinks,\n deleteContainerDocumentTombstoneHoldsForContainers,\n deleteContainerDocumentTombstoneHoldsForDocuments,\n placementPairsMatch,\n} from \"../documents/containerDocumentTombstoneHoldsPersistence\";\n\nimport {\n type DocumentPlacementInput,\n type DocumentPlacementWriteOptions,\n filterWritableDocumentPlacements,\n} from \"./documentPlacement\";\n\nconst LINK_INSERT_BATCH_SIZE = sqliteInsertBatchSize(\n documentContainerProjection,\n);\n\ninterface DocumentContainerProjectionPersistence {\n ensureSchema: (execSql: ExecSql) => Promise<void>;\n listLinkedContainerIds: (\n execSql: ExecSql,\n documentId: string,\n ) => Promise<ReadonlyArray<string>>;\n listLinkedContainerIdsByDocumentIds: (\n execSql: ExecSql,\n documentIds: ReadonlyArray<string>,\n ) => Promise<ReadonlyMap<string, ReadonlyArray<string>>>;\n listDocumentIdsByContainerIds: (\n execSql: ExecSql,\n containerIds: ReadonlyArray<string>,\n ) => Promise<ReadonlyArray<string>>;\n replaceDocumentLinks: (\n execSql: ExecSql,\n documentId: string,\n containerIds: ReadonlyArray<string>,\n options?: DocumentPlacementWriteOptions,\n ) => Promise<void>;\n replaceDocumentLinksBatch: (\n execSql: ExecSql,\n inputs: ReadonlyArray<DocumentPlacementInput>,\n options?: DocumentPlacementWriteOptions,\n ) => Promise<void>;\n}\n\n/** Link rows and their tombstone holds leave together on a remote reset. */\nexport async function deleteDocumentPlacementRowsByContainerIds(\n tx: ClientSQLiteTransactionScope,\n containerIds: ReadonlyArray<string>,\n): Promise<void> {\n await tx\n .delete(documentContainerProjection)\n .where(inArray(documentContainerProjection.containerId, containerIds))\n .run();\n await deleteContainerDocumentTombstoneHoldsForContainers(tx, containerIds);\n}\n\nexport async function deleteDocumentPlacementRowsByDocumentIds(\n tx: ClientSQLiteTransactionScope,\n documentIds: ReadonlyArray<string>,\n): Promise<void> {\n await tx\n .delete(documentContainerProjection)\n .where(inArray(documentContainerProjection.documentId, documentIds))\n .run();\n await deleteContainerDocumentTombstoneHoldsForDocuments(tx, documentIds);\n}\n\n/** Removes the listed (document, container) placements, 50 pairs per statement. */\nexport async function deleteDocumentPlacementRowsInTransaction(\n tx: ClientSQLiteTransactionScope,\n placements: ReadonlyArray<{\n readonly containerId: string;\n readonly documentId: string;\n }>,\n): Promise<void> {\n for (const batch of remoteResetBatches(placements)) {\n await tx\n .delete(documentContainerProjection)\n .where(\n placementPairsMatch(\n batch,\n documentContainerProjection.documentId,\n documentContainerProjection.containerId,\n ),\n )\n .run();\n }\n}\n\n/**\n * Removes each document's placements outside the containers its head links,\n * batching documents so one statement stays inside SQLite's bind budget.\n */\nexport async function deleteUnlinkedDocumentPlacementRowsInTransaction(\n tx: ClientSQLiteTransactionScope,\n linkedContainerIdsByDocumentId: ReadonlyMap<string, ReadonlySet<string>>,\n): Promise<void> {\n let batch: SQL[] = [];\n let binds = 0;\n const flush = async () => {\n if (batch.length === 0) return;\n await tx\n .delete(documentContainerProjection)\n .where(or(...batch))\n .run();\n batch = [];\n binds = 0;\n };\n for (const [documentId, linked] of linkedContainerIdsByDocumentId) {\n // The document id plus one bind per linked container.\n const documentBinds = 1 + linked.size;\n if (\n batch.length >= REMOTE_RESET_SQL_BATCH_SIZE ||\n binds + documentBinds > SQLITE_BOUND_VARIABLE_BUDGET\n ) {\n await flush();\n }\n batch.push(unlinkedDocumentPlacementRows(documentId, linked));\n binds += documentBinds;\n }\n await flush();\n}\n\n/** A document's placements outside the containers its head links. */\nfunction unlinkedDocumentPlacementRows(\n documentId: string,\n linkedContainerIds: ReadonlySet<string>,\n): SQL {\n const ofDocument = eq(documentContainerProjection.documentId, documentId);\n return linkedContainerIds.size === 0\n ? ofDocument\n : (and(\n ofDocument,\n notInArray(documentContainerProjection.containerId, [\n ...linkedContainerIds,\n ]),\n ) ?? ofDocument);\n}\n\n/** Removes a deleted document's queued placement intents and link targets. */\nexport async function deleteDocumentPlacementIntentsInTransaction(\n tx: ClientSQLiteTransactionScope,\n documentId: string,\n): Promise<void> {\n const placementIntent = and(\n inLocalIntentLane(LOCAL_INTENT_LANES.documentPlacement),\n eq(localIntents.subjectId, documentId),\n );\n await tx\n .delete(documentIntentLinkTargets)\n .where(\n inArray(\n documentIntentLinkTargets.intentId,\n tx\n .select({ id: localIntents.id })\n .from(localIntents)\n .where(placementIntent),\n ),\n )\n .run();\n await tx.delete(localIntents).where(placementIntent).run();\n}\n\nasync function ensureDocumentLinksSchema(execSql: ExecSql): Promise<void> {\n await ensureSqlTables(execSql, [\n ...documentContainerProjectionTables,\n ...documentPlacementIntentTables,\n ...documentTables,\n ]);\n}\n\nasync function replaceDocumentLinkRows(\n tx: ClientSQLiteTransactionScope,\n latest: ReadonlyMap<string, DocumentPlacementInput>,\n options?: DocumentPlacementWriteOptions,\n): Promise<void> {\n const writable = await filterWritableDocumentPlacements(\n tx,\n [...latest.values()],\n options,\n );\n if (writable.length === 0) return;\n // A placement the writer re-asserts is no longer tombstoned: a\n // listing that links it again, or a local move that owns it, releases\n // the hold so the document is not hidden until the next retry.\n if (options?.moveIntentId) {\n await deleteContainerDocumentTombstoneHoldsForDocuments(\n tx,\n writable.map((input) => input.documentId),\n );\n } else {\n await deleteContainerDocumentTombstoneHoldRowsForLinks(tx, writable);\n }\n // Each document binds once; finish every deletion before inserting.\n for (\n let index = 0;\n index < writable.length;\n index += SQLITE_BOUND_VARIABLE_BUDGET\n ) {\n await tx\n .delete(documentContainerProjection)\n .where(\n inArray(\n documentContainerProjection.documentId,\n writable\n .slice(index, index + SQLITE_BOUND_VARIABLE_BUDGET)\n .map((input) => input.documentId),\n ),\n )\n .run();\n }\n const updatedAt = new Date().toISOString();\n const rows = writable.flatMap((input) =>\n Array.from(new Set(input.containerIds))\n .sort()\n .map((containerId) => ({\n documentId: input.documentId,\n containerId,\n updatedAt,\n })),\n );\n // A lane page of multi-link documents can carry more link rows than\n // one statement may bind.\n for (let index = 0; index < rows.length; index += LINK_INSERT_BATCH_SIZE) {\n await tx\n .insert(documentContainerProjection)\n .values(rows.slice(index, index + LINK_INSERT_BATCH_SIZE))\n .run();\n }\n}\n\n/** The caller owns the open document commit and must propagate every failure. */\nexport async function replaceDocumentLinksInTransaction(\n transactionExecSql: ExecSql,\n documentId: string,\n containerIds: readonly string[],\n options?: Omit<DocumentPlacementWriteOptions, \"stillCurrent\">,\n): Promise<void> {\n await ensureDocumentLinksSchema(transactionExecSql);\n await replaceDocumentLinkRows(\n getClientSQLitePersistenceRuntime(transactionExecSql).db,\n new Map([[documentId, { documentId, containerIds }]]),\n options,\n );\n}\n\nexport const sqlDocumentContainerProjectionPersistence: DocumentContainerProjectionPersistence =\n {\n async ensureSchema(execSql) {\n await ensureSqlTables(execSql, documentContainerProjectionTables);\n },\n async listLinkedContainerIds(execSql, documentId) {\n await ensureSqlTables(execSql, documentContainerProjectionTables);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({ containerId: documentContainerProjection.containerId })\n .from(documentContainerProjection)\n .where(eq(documentContainerProjection.documentId, documentId))\n .orderBy(asc(documentContainerProjection.containerId));\n\n return rows.map((row) => row.containerId);\n },\n async listLinkedContainerIdsByDocumentIds(execSql, documentIds) {\n await ensureSqlTables(execSql, documentContainerProjectionTables);\n const uniqueDocumentIds = Array.from(new Set(documentIds));\n if (uniqueDocumentIds.length === 0) {\n return new Map();\n }\n\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({\n documentId: documentContainerProjection.documentId,\n containerId: documentContainerProjection.containerId,\n })\n .from(documentContainerProjection)\n .where(\n inArray(documentContainerProjection.documentId, uniqueDocumentIds),\n )\n .orderBy(\n asc(documentContainerProjection.documentId),\n asc(documentContainerProjection.containerId),\n );\n\n const linkedContainerIdsByDocumentId = new Map<string, string[]>();\n for (const documentId of uniqueDocumentIds) {\n linkedContainerIdsByDocumentId.set(documentId, []);\n }\n\n for (const row of rows) {\n const linkedContainerIds =\n linkedContainerIdsByDocumentId.get(row.documentId) ?? [];\n linkedContainerIds.push(row.containerId);\n linkedContainerIdsByDocumentId.set(row.documentId, linkedContainerIds);\n }\n\n return linkedContainerIdsByDocumentId;\n },\n async listDocumentIdsByContainerIds(execSql, containerIds) {\n await ensureSqlTables(execSql, documentContainerProjectionTables);\n const uniqueContainerIds = Array.from(new Set(containerIds));\n if (uniqueContainerIds.length === 0) {\n return [];\n }\n\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .selectDistinct({ documentId: documentContainerProjection.documentId })\n .from(documentContainerProjection)\n .where(\n inArray(documentContainerProjection.containerId, uniqueContainerIds),\n )\n .orderBy(asc(documentContainerProjection.documentId));\n\n return rows.map((row) => row.documentId);\n },\n async replaceDocumentLinks(execSql, documentId, containerIds, options) {\n await sqlDocumentContainerProjectionPersistence.replaceDocumentLinksBatch(\n execSql,\n [{ documentId, containerIds }],\n options,\n );\n },\n async replaceDocumentLinksBatch(execSql, inputs, options) {\n await ensureDocumentLinksSchema(execSql);\n const latest = new Map(inputs.map((input) => [input.documentId, input]));\n if (latest.size === 0) return;\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const replace = (tx: ClientSQLiteTransactionScope) =>\n replaceDocumentLinkRows(tx, latest, options);\n if (options?.stillCurrent) {\n await runtime.guardedTransaction(replace, options.stillCurrent);\n return;\n }\n await runtime.transaction(replace);\n },\n };\n"]}
|
|
1
|
+
{"version":3,"file":"documentContainerProjectionPersistence.js","sourceRoot":"","sources":["documentContainerProjectionPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,UAAU,EAAE,EAAE,EAAY,MAAM,aAAa,CAAC;AAC9E,OAAO,EACL,6BAA6B,EAC7B,iBAAiB,EACjB,kBAAkB,EAClB,YAAY,GACb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,yBAAyB,EAAE,MAAM,mDAAmD,CAAC;AAC9F,OAAO,EACL,2BAA2B,EAC3B,iCAAiC,GAClC,MAAM,8CAA8C,CAAC;AACtD,OAAO,EAAE,cAAc,EAAE,MAAM,0CAA0C,CAAC;AAC1E,OAAO,EACL,2BAA2B,EAC3B,kBAAkB,EAClB,4BAA4B,EAC5B,qBAAqB,GACtB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACvE,OAAO,EACL,gDAAgD,EAChD,kDAAkD,EAClD,iDAAiD,EACjD,mBAAmB,GACpB,MAAM,yDAAyD,CAAC;AAEjE,OAAO,EAGL,gCAAgC,GACjC,MAAM,qBAAqB,CAA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AAO,CAAC,CAAC;QACzD,IAAI,OAAO,EAAE,YAAY,EAAE,CAAC;YAC1B,MAAM,OAAO,CAAC,kBAAkB,CAAC,OAAO,EAAE,OAAO,CAAC,YAAY,CAAC,CAAC;YAChE,OAAO;QACT,CAAC;QACD,MAAM,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;IACrC,CAAC;CACF","sourcesContent":["import { and, asc, eq, inArray, notInArray, or, type SQL } from \"drizzle-orm\";\nimport {\n documentPlacementIntentTables,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n} from \"../../sqlite/schema\";\nimport { documentIntentLinkTargets } from \"../../sqlite/schema/documentPlacementIntentSchema\";\nimport {\n documentContainerProjection,\n documentContainerProjectionTables,\n} from \"../../sqlite/schema/documentProjectionSchema\";\nimport { documentTables } from \"../../sqlite/schema/documentRecordSchema\";\nimport {\n REMOTE_RESET_SQL_BATCH_SIZE,\n remoteResetBatches,\n SQLITE_BOUND_VARIABLE_BUDGET,\n sqliteInsertBatchSize,\n} from \"../../sqlite/sqliteBindBudget\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport {\n deleteContainerDocumentTombstoneHoldRowsForLinks,\n deleteContainerDocumentTombstoneHoldsForContainers,\n deleteContainerDocumentTombstoneHoldsForDocuments,\n placementPairsMatch,\n} from \"../documents/containerDocumentTombstoneHoldsPersistence\";\n\nimport {\n type DocumentPlacementInput,\n type DocumentPlacementWriteOptions,\n filterWritableDocumentPlacements,\n} from \"./documentPlacement\";\n\nconst LINK_INSERT_BATCH_SIZE = sqliteInsertBatchSize(\n documentContainerProjection,\n);\n\n/** Link rows and their tombstone holds leave together on a remote reset. */\nexport async function deleteDocumentPlacementRowsByContainerIds(\n tx: ClientSQLiteTransactionScope,\n containerIds: ReadonlyArray<string>,\n): Promise<void> {\n await tx\n .delete(documentContainerProjection)\n .where(inArray(documentContainerProjection.containerId, containerIds))\n .run();\n await deleteContainerDocumentTombstoneHoldsForContainers(tx, containerIds);\n}\n\nexport async function deleteDocumentPlacementRowsByDocumentIds(\n tx: ClientSQLiteTransactionScope,\n documentIds: ReadonlyArray<string>,\n): Promise<void> {\n await tx\n .delete(documentContainerProjection)\n .where(inArray(documentContainerProjection.documentId, documentIds))\n .run();\n await deleteContainerDocumentTombstoneHoldsForDocuments(tx, documentIds);\n}\n\n/** Removes the listed (document, container) placements, 50 pairs per statement. */\nexport async function deleteDocumentPlacementRowsInTransaction(\n tx: ClientSQLiteTransactionScope,\n placements: ReadonlyArray<{\n readonly containerId: string;\n readonly documentId: string;\n }>,\n): Promise<void> {\n for (const batch of remoteResetBatches(placements)) {\n await tx\n .delete(documentContainerProjection)\n .where(\n placementPairsMatch(\n batch,\n documentContainerProjection.documentId,\n documentContainerProjection.containerId,\n ),\n )\n .run();\n }\n}\n\n/**\n * Removes each document's placements outside the containers its head links,\n * batching documents so one statement stays inside SQLite's bind budget.\n */\nexport async function deleteUnlinkedDocumentPlacementRowsInTransaction(\n tx: ClientSQLiteTransactionScope,\n linkedContainerIdsByDocumentId: ReadonlyMap<string, ReadonlySet<string>>,\n): Promise<void> {\n let batch: SQL[] = [];\n let binds = 0;\n const flush = async () => {\n if (batch.length === 0) return;\n await tx\n .delete(documentContainerProjection)\n .where(or(...batch))\n .run();\n batch = [];\n binds = 0;\n };\n for (const [documentId, linked] of linkedContainerIdsByDocumentId) {\n // The document id plus one bind per linked container.\n const documentBinds = 1 + linked.size;\n if (\n batch.length >= REMOTE_RESET_SQL_BATCH_SIZE ||\n binds + documentBinds > SQLITE_BOUND_VARIABLE_BUDGET\n ) {\n await flush();\n }\n batch.push(unlinkedDocumentPlacementRows(documentId, linked));\n binds += documentBinds;\n }\n await flush();\n}\n\n/** A document's placements outside the containers its head links. */\nfunction unlinkedDocumentPlacementRows(\n documentId: string,\n linkedContainerIds: ReadonlySet<string>,\n): SQL {\n const ofDocument = eq(documentContainerProjection.documentId, documentId);\n return linkedContainerIds.size === 0\n ? ofDocument\n : (and(\n ofDocument,\n notInArray(documentContainerProjection.containerId, [\n ...linkedContainerIds,\n ]),\n ) ?? ofDocument);\n}\n\n/** Removes a deleted document's queued placement intents and link targets. */\nexport async function deleteDocumentPlacementIntentsInTransaction(\n tx: ClientSQLiteTransactionScope,\n documentId: string,\n): Promise<void> {\n const placementIntent = and(\n inLocalIntentLane(LOCAL_INTENT_LANES.documentPlacement),\n eq(localIntents.subjectId, documentId),\n );\n await tx\n .delete(documentIntentLinkTargets)\n .where(\n inArray(\n documentIntentLinkTargets.intentId,\n tx\n .select({ id: localIntents.id })\n .from(localIntents)\n .where(placementIntent),\n ),\n )\n .run();\n await tx.delete(localIntents).where(placementIntent).run();\n}\n\nasync function ensureDocumentLinksSchema(execSql: ExecSql): Promise<void> {\n await ensureSqlTables(execSql, [\n ...documentContainerProjectionTables,\n ...documentPlacementIntentTables,\n ...documentTables,\n ]);\n}\n\nasync function replaceDocumentLinkRows(\n tx: ClientSQLiteTransactionScope,\n latest: ReadonlyMap<string, DocumentPlacementInput>,\n now: () => Date,\n options?: DocumentPlacementWriteOptions,\n): Promise<void> {\n const writable = await filterWritableDocumentPlacements(\n tx,\n [...latest.values()],\n options,\n );\n if (writable.length === 0) return;\n // A placement the writer re-asserts is no longer tombstoned: a\n // listing that links it again, or a local move that owns it, releases\n // the hold so the document is not hidden until the next retry.\n if (options?.moveIntentId) {\n await deleteContainerDocumentTombstoneHoldsForDocuments(\n tx,\n writable.map((input) => input.documentId),\n );\n } else {\n await deleteContainerDocumentTombstoneHoldRowsForLinks(tx, writable);\n }\n // Each document binds once; finish every deletion before inserting.\n for (\n let index = 0;\n index < writable.length;\n index += SQLITE_BOUND_VARIABLE_BUDGET\n ) {\n await tx\n .delete(documentContainerProjection)\n .where(\n inArray(\n documentContainerProjection.documentId,\n writable\n .slice(index, index + SQLITE_BOUND_VARIABLE_BUDGET)\n .map((input) => input.documentId),\n ),\n )\n .run();\n }\n const updatedAt = now().toISOString();\n const rows = writable.flatMap((input) =>\n Array.from(new Set(input.containerIds))\n .sort()\n .map((containerId) => ({\n documentId: input.documentId,\n containerId,\n updatedAt,\n })),\n );\n // A lane page of multi-link documents can carry more link rows than\n // one statement may bind.\n for (let index = 0; index < rows.length; index += LINK_INSERT_BATCH_SIZE) {\n await tx\n .insert(documentContainerProjection)\n .values(rows.slice(index, index + LINK_INSERT_BATCH_SIZE))\n .run();\n }\n}\n\n/** The caller owns the open document commit and must propagate every failure. */\nexport async function replaceDocumentLinksInTransaction(\n transactionExecSql: ExecSql,\n documentId: string,\n containerIds: readonly string[],\n options?: Omit<DocumentPlacementWriteOptions, \"stillCurrent\">,\n): Promise<void> {\n await ensureDocumentLinksSchema(transactionExecSql);\n await replaceDocumentLinkRows(\n getClientSQLitePersistenceRuntime(transactionExecSql).db,\n new Map([[documentId, { documentId, containerIds }]]),\n () => new Date(),\n options,\n );\n}\n\n/** The document container projection, bound to one executor and clock. */\nexport class DocumentContainerProjectionRepository {\n constructor(\n private readonly execSql: ExecSql,\n private readonly now: () => Date = () => new Date(),\n ) {}\n\n async ensureSchema(): Promise<void> {\n await ensureSqlTables(this.execSql, documentContainerProjectionTables);\n }\n\n async listLinkedContainerIds(\n documentId: string,\n ): Promise<ReadonlyArray<string>> {\n await this.ensureSchema();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .select({ containerId: documentContainerProjection.containerId })\n .from(documentContainerProjection)\n .where(eq(documentContainerProjection.documentId, documentId))\n .orderBy(asc(documentContainerProjection.containerId));\n\n return rows.map((row) => row.containerId);\n }\n\n async listLinkedContainerIdsByDocumentIds(\n documentIds: ReadonlyArray<string>,\n ): Promise<ReadonlyMap<string, ReadonlyArray<string>>> {\n await this.ensureSchema();\n const uniqueDocumentIds = Array.from(new Set(documentIds));\n if (uniqueDocumentIds.length === 0) {\n return new Map();\n }\n\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .select({\n documentId: documentContainerProjection.documentId,\n containerId: documentContainerProjection.containerId,\n })\n .from(documentContainerProjection)\n .where(inArray(documentContainerProjection.documentId, uniqueDocumentIds))\n .orderBy(\n asc(documentContainerProjection.documentId),\n asc(documentContainerProjection.containerId),\n );\n\n const linkedContainerIdsByDocumentId = new Map<string, string[]>();\n for (const documentId of uniqueDocumentIds) {\n linkedContainerIdsByDocumentId.set(documentId, []);\n }\n\n for (const row of rows) {\n const linkedContainerIds =\n linkedContainerIdsByDocumentId.get(row.documentId) ?? [];\n linkedContainerIds.push(row.containerId);\n linkedContainerIdsByDocumentId.set(row.documentId, linkedContainerIds);\n }\n\n return linkedContainerIdsByDocumentId;\n }\n\n async listDocumentIdsByContainerIds(\n containerIds: ReadonlyArray<string>,\n ): Promise<ReadonlyArray<string>> {\n await this.ensureSchema();\n const uniqueContainerIds = Array.from(new Set(containerIds));\n if (uniqueContainerIds.length === 0) {\n return [];\n }\n\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .selectDistinct({ documentId: documentContainerProjection.documentId })\n .from(documentContainerProjection)\n .where(\n inArray(documentContainerProjection.containerId, uniqueContainerIds),\n )\n .orderBy(asc(documentContainerProjection.documentId));\n\n return rows.map((row) => row.documentId);\n }\n\n async replaceDocumentLinks(\n documentId: string,\n containerIds: ReadonlyArray<string>,\n options?: DocumentPlacementWriteOptions,\n ): Promise<void> {\n await this.replaceDocumentLinksBatch(\n [{ documentId, containerIds }],\n options,\n );\n }\n\n async replaceDocumentLinksBatch(\n inputs: ReadonlyArray<DocumentPlacementInput>,\n options?: DocumentPlacementWriteOptions,\n ): Promise<void> {\n await ensureDocumentLinksSchema(this.execSql);\n const latest = new Map(inputs.map((input) => [input.documentId, input]));\n if (latest.size === 0) return;\n const runtime = getClientSQLitePersistenceRuntime(this.execSql);\n const replace = (tx: ClientSQLiteTransactionScope) =>\n replaceDocumentLinkRows(tx, latest, this.now, options);\n if (options?.stillCurrent) {\n await runtime.guardedTransaction(replace, options.stillCurrent);\n return;\n }\n await runtime.transaction(replace);\n }\n}\n"]}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { ClientSQLiteTransactionScope } from "../../sqlite/sqlitePersistenceRuntime.js";
|
|
2
|
+
export interface DocumentPlacementInput {
|
|
3
|
+
documentId: string;
|
|
4
|
+
containerIds: ReadonlyArray<string>;
|
|
5
|
+
accessEpoch?: number | undefined;
|
|
6
|
+
}
|
|
7
|
+
export interface DocumentPlacementWriteOptions {
|
|
8
|
+
stillCurrent?: (() => boolean) | undefined;
|
|
9
|
+
moveIntentId?: string | undefined;
|
|
10
|
+
}
|
|
11
|
+
export interface DocumentMovePlacement {
|
|
12
|
+
readonly id: string | null;
|
|
13
|
+
readonly intentType: string;
|
|
14
|
+
readonly targetContainerId: string;
|
|
15
|
+
}
|
|
16
|
+
export declare function loadDocumentMovePlacement(tx: ClientSQLiteTransactionScope, documentId: string): Promise<DocumentMovePlacement | undefined>;
|
|
17
|
+
/** `loadDocumentMovePlacement` for many documents, keyed by document id. */
|
|
18
|
+
export declare function loadDocumentMovePlacements(tx: ClientSQLiteTransactionScope, documentIds: ReadonlyArray<string>): Promise<Map<string, DocumentMovePlacement>>;
|
|
19
|
+
/** Check at commit time: neither intermediate replay nor discovery owns a pending move. */
|
|
20
|
+
export declare function filterWritableDocumentPlacements(tx: ClientSQLiteTransactionScope, inputs: readonly DocumentPlacementInput[], options?: DocumentPlacementWriteOptions): Promise<readonly DocumentPlacementInput[]>;
|
|
@@ -45,15 +45,26 @@ export interface OrganizationSyncPauses {
|
|
|
45
45
|
*/
|
|
46
46
|
runExclusive<T>(task: () => Promise<T>): Promise<T>;
|
|
47
47
|
}
|
|
48
|
-
/** The one pause set for a domain scope; a new scope starts unloaded. */
|
|
49
|
-
export declare function getOrCreateOrganizationSyncPauses(domainScope: DomainScope): OrganizationSyncPauses;
|
|
50
48
|
/**
|
|
51
|
-
*
|
|
52
|
-
*
|
|
49
|
+
* Persistence for organization sync pauses and the documents a pause's
|
|
50
|
+
* cleanup removed, bound to one executor.
|
|
53
51
|
*/
|
|
54
|
-
export declare
|
|
55
|
-
readonly
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
52
|
+
export declare class OrganizationSyncPauseRepository {
|
|
53
|
+
private readonly execSql;
|
|
54
|
+
constructor(execSql: ExecSql);
|
|
55
|
+
readPausedOrganizationIds(): Promise<Set<string>>;
|
|
56
|
+
writePausedOrganizationIds(organizationIds: ReadonlySet<string>): Promise<void>;
|
|
57
|
+
/**
|
|
58
|
+
* Records, in the caller's transaction, that a pause's cleanup removed this
|
|
59
|
+
* document, so reopening it does not recreate it while the pause lasts.
|
|
60
|
+
* A plain insert on the bound executor; it never opens a transaction.
|
|
61
|
+
*/
|
|
62
|
+
recordPauseRemovedDocument(removal: {
|
|
63
|
+
readonly localId: string;
|
|
64
|
+
readonly organizationId: string;
|
|
65
|
+
}): Promise<void>;
|
|
66
|
+
/** Whether a pause's cleanup removed this document and the pause holds. */
|
|
67
|
+
isPauseRemovedDocument(localId: string): Promise<boolean>;
|
|
68
|
+
}
|
|
69
|
+
/** The one pause set for a domain scope; a new scope starts unloaded. */
|
|
70
|
+
export declare function getOrCreateOrganizationSyncPauses(domainScope: DomainScope): OrganizationSyncPauses;
|
|
@@ -12,41 +12,78 @@ import { ensureSqlTables, runSerializedSqlMutation, } from "../sqlite/sqlSchema.
|
|
|
12
12
|
export function isRetainedWhileSyncPaused(container) {
|
|
13
13
|
return container.parentId === null && Boolean(container.systemSlot);
|
|
14
14
|
}
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
async
|
|
25
|
-
|
|
26
|
-
await
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
15
|
+
/**
|
|
16
|
+
* Persistence for organization sync pauses and the documents a pause's
|
|
17
|
+
* cleanup removed, bound to one executor.
|
|
18
|
+
*/
|
|
19
|
+
export class OrganizationSyncPauseRepository {
|
|
20
|
+
execSql;
|
|
21
|
+
constructor(execSql) {
|
|
22
|
+
this.execSql = execSql;
|
|
23
|
+
}
|
|
24
|
+
async readPausedOrganizationIds() {
|
|
25
|
+
await ensureSqlTables(this.execSql, organizationSyncPauseTables);
|
|
26
|
+
const rows = await getClientSQLitePersistenceRuntime(this.execSql)
|
|
27
|
+
.db.select({ organizationId: organizationSyncPauses.organizationId })
|
|
28
|
+
.from(organizationSyncPauses);
|
|
29
|
+
return new Set(rows.map((row) => row.organizationId));
|
|
30
|
+
}
|
|
31
|
+
// One transaction replaces the whole set, so a failed write keeps the
|
|
32
|
+
// previous pauses in force; inserts go in batches within SQLite's bind
|
|
33
|
+
// budget.
|
|
34
|
+
async writePausedOrganizationIds(organizationIds) {
|
|
35
|
+
await runSerializedSqlMutation(this.execSql, async (lockedExecSql) => {
|
|
36
|
+
await ensureSqlTables(lockedExecSql, organizationSyncPauseTables);
|
|
37
|
+
const ids = [...organizationIds];
|
|
38
|
+
const batchSize = sqliteInsertBatchSize(organizationSyncPauses);
|
|
39
|
+
await getClientSQLitePersistenceRuntime(lockedExecSql).transaction(async (tx) => {
|
|
40
|
+
await tx.delete(organizationSyncPauses).run();
|
|
41
|
+
for (let index = 0; index < ids.length; index += batchSize) {
|
|
42
|
+
await tx
|
|
43
|
+
.insert(organizationSyncPauses)
|
|
44
|
+
.values(ids
|
|
45
|
+
.slice(index, index + batchSize)
|
|
46
|
+
.map((organizationId) => ({ organizationId })))
|
|
47
|
+
.run();
|
|
48
|
+
}
|
|
49
|
+
// A resumed organization's removed documents may be reopened again.
|
|
32
50
|
await tx
|
|
33
|
-
.
|
|
34
|
-
.
|
|
35
|
-
.
|
|
36
|
-
|
|
51
|
+
.delete(organizationSyncPauseRemovals)
|
|
52
|
+
.where(notInArray(organizationSyncPauseRemovals.organizationId, tx
|
|
53
|
+
.select({
|
|
54
|
+
organizationId: organizationSyncPauses.organizationId,
|
|
55
|
+
})
|
|
56
|
+
.from(organizationSyncPauses)))
|
|
37
57
|
.run();
|
|
38
|
-
}
|
|
39
|
-
// A resumed organization's removed documents may be reopened again.
|
|
40
|
-
await tx
|
|
41
|
-
.delete(organizationSyncPauseRemovals)
|
|
42
|
-
.where(notInArray(organizationSyncPauseRemovals.organizationId, tx
|
|
43
|
-
.select({
|
|
44
|
-
organizationId: organizationSyncPauses.organizationId,
|
|
45
|
-
})
|
|
46
|
-
.from(organizationSyncPauses)))
|
|
47
|
-
.run();
|
|
58
|
+
});
|
|
48
59
|
});
|
|
49
|
-
}
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Records, in the caller's transaction, that a pause's cleanup removed this
|
|
63
|
+
* document, so reopening it does not recreate it while the pause lasts.
|
|
64
|
+
* A plain insert on the bound executor; it never opens a transaction.
|
|
65
|
+
*/
|
|
66
|
+
async recordPauseRemovedDocument(removal) {
|
|
67
|
+
await ensureSqlTables(this.execSql, organizationSyncPauseTables);
|
|
68
|
+
await getClientSQLitePersistenceRuntime(this.execSql)
|
|
69
|
+
.db.insert(organizationSyncPauseRemovals)
|
|
70
|
+
.values(removal)
|
|
71
|
+
.onConflictDoUpdate({
|
|
72
|
+
set: { organizationId: removal.organizationId },
|
|
73
|
+
target: organizationSyncPauseRemovals.localId,
|
|
74
|
+
})
|
|
75
|
+
.run();
|
|
76
|
+
}
|
|
77
|
+
/** Whether a pause's cleanup removed this document and the pause holds. */
|
|
78
|
+
async isPauseRemovedDocument(localId) {
|
|
79
|
+
await ensureSqlTables(this.execSql, organizationSyncPauseTables);
|
|
80
|
+
const rows = await getClientSQLitePersistenceRuntime(this.execSql)
|
|
81
|
+
.db.select({ localId: organizationSyncPauseRemovals.localId })
|
|
82
|
+
.from(organizationSyncPauseRemovals)
|
|
83
|
+
.where(eq(organizationSyncPauseRemovals.localId, localId))
|
|
84
|
+
.limit(1);
|
|
85
|
+
return rows.length > 0;
|
|
86
|
+
}
|
|
50
87
|
}
|
|
51
88
|
function createOrganizationSyncPauses() {
|
|
52
89
|
let paused = new Set();
|
|
@@ -60,7 +97,9 @@ function createOrganizationSyncPauses() {
|
|
|
60
97
|
};
|
|
61
98
|
const pauses = {
|
|
62
99
|
load(execSql) {
|
|
63
|
-
loading ??=
|
|
100
|
+
loading ??= new OrganizationSyncPauseRepository(execSql)
|
|
101
|
+
.readPausedOrganizationIds()
|
|
102
|
+
.then((stored) => {
|
|
64
103
|
paused = stored;
|
|
65
104
|
if (stored.size > 0)
|
|
66
105
|
notify();
|
|
@@ -89,7 +128,7 @@ function createOrganizationSyncPauses() {
|
|
|
89
128
|
if (change.paused.length === 0 && change.resumed.length === 0) {
|
|
90
129
|
return change;
|
|
91
130
|
}
|
|
92
|
-
await writePausedOrganizationIds(
|
|
131
|
+
await new OrganizationSyncPauseRepository(execSql).writePausedOrganizationIds(next);
|
|
93
132
|
paused = next;
|
|
94
133
|
notify();
|
|
95
134
|
return change;
|
|
@@ -121,29 +160,4 @@ export function getOrCreateOrganizationSyncPauses(domainScope) {
|
|
|
121
160
|
}
|
|
122
161
|
return pauses;
|
|
123
162
|
}
|
|
124
|
-
/**
|
|
125
|
-
* Records, in the caller's transaction, that a pause's cleanup removed this
|
|
126
|
-
* document, so reopening it does not recreate it while the pause lasts.
|
|
127
|
-
*/
|
|
128
|
-
export async function recordPauseRemovedDocument(execSql, removal) {
|
|
129
|
-
await ensureSqlTables(execSql, organizationSyncPauseTables);
|
|
130
|
-
await getClientSQLitePersistenceRuntime(execSql)
|
|
131
|
-
.db.insert(organizationSyncPauseRemovals)
|
|
132
|
-
.values(removal)
|
|
133
|
-
.onConflictDoUpdate({
|
|
134
|
-
set: { organizationId: removal.organizationId },
|
|
135
|
-
target: organizationSyncPauseRemovals.localId,
|
|
136
|
-
})
|
|
137
|
-
.run();
|
|
138
|
-
}
|
|
139
|
-
/** Whether a pause's cleanup removed this document and the pause still holds. */
|
|
140
|
-
export async function isPauseRemovedDocument(execSql, localId) {
|
|
141
|
-
await ensureSqlTables(execSql, organizationSyncPauseTables);
|
|
142
|
-
const rows = await getClientSQLitePersistenceRuntime(execSql)
|
|
143
|
-
.db.select({ localId: organizationSyncPauseRemovals.localId })
|
|
144
|
-
.from(organizationSyncPauseRemovals)
|
|
145
|
-
.where(eq(organizationSyncPauseRemovals.localId, localId))
|
|
146
|
-
.limit(1);
|
|
147
|
-
return rows.length > 0;
|
|
148
|
-
}
|
|
149
163
|
//# sourceMappingURL=organizationSyncPauses.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"organizationSyncPauses.js","sourceRoot":"","sources":["organizationSyncPauses.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAE7C,OAAO,EACL,6BAA6B,EAC7B,sBAAsB,EACtB,2BAA2B,GAC5B,MAAM,8CAA8C,CAAC;AACtD,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACnE,OAAO,EAAE,iCAAiC,EAAE,MAAM,oCAAoC,CAAC;AACvF,OAAO,EAEL,eAAe,EACf,wBAAwB,GACzB,MAAM,qBAAqB,CAAC;AAS7B;;;;;GAKG;AACH,MAAM,UAAU,yBAAyB,CACvC,SAAuC;IAEvC,OAAO,SAAS,CAAC,QAAQ,KAAK,IAAI,IAAI,OAAO,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;AACtE,CAAC;AA0CD,KAAK,UAAU,yBAAyB,CACtC,OAAgB;IAEhB,MAAM,eAAe,CAAC,OAAO,EAAE,2BAA2B,CAAC,CAAC;IAC5D,MAAM,IAAI,GAAG,MAAM,iCAAiC,CAAC,OAAO,CAAC;SAC1D,EAAE,CAAC,MAAM,CAAC,EAAE,cAAc,EAAE,sBAAsB,CAAC,cAAc,EAAE,CAAC;SACpE,IAAI,CAAC,sBAAsB,CAAC,CAAC;IAChC,OAAO,IA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AC,OAAO,EAAE,CAAC;SAC7D,IAAI,CAAC,6BAA6B,CAAC;SACnC,KAAK,CAAC,EAAE,CAAC,6BAA6B,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;SACzD,KAAK,CAAC,CAAC,CAAC,CAAC;IACZ,OAAO,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;AACzB,CAAC","sourcesContent":["import { eq, notInArray } from \"drizzle-orm\";\nimport type { DomainScope } from \"../shared/domainScope\";\nimport {\n organizationSyncPauseRemovals,\n organizationSyncPauses,\n organizationSyncPauseTables,\n} from \"../sqlite/schema/organizationSyncPauseSchema\";\nimport { sqliteInsertBatchSize } from \"../sqlite/sqliteBindBudget\";\nimport { getClientSQLitePersistenceRuntime } from \"../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../sqlite/sqlSchema\";\n\n/** The container fields the pause rule reads. */\nexport interface OrganizationSyncPauseSubject {\n readonly organizationId: string;\n readonly parentId: string | null;\n readonly systemSlot?: string | null | undefined;\n}\n\n/**\n * Whether a container stays on the device while its organization is paused:\n * only the organization's parentless system root, the metadata root every\n * Members recipient reads, which keeps the organization named and its\n * membership visible.\n */\nexport function isRetainedWhileSyncPaused(\n container: OrganizationSyncPauseSubject,\n): boolean {\n return container.parentId === null && Boolean(container.systemSlot);\n}\n\nexport interface OrganizationSyncPauseChange {\n readonly paused: readonly string[];\n readonly resumed: readonly string[];\n}\n\n/**\n * Which organizations this user paused syncing to their devices, for one\n * domain scope. Sync reads it synchronously once `load` has settled; the\n * persisted set lets a device that starts offline keep honoring a pause.\n */\nexport interface OrganizationSyncPauses {\n /** Loads the persisted set once; concurrent and later calls share it. */\n load(execSql: ExecSql): Promise<void>;\n isOrganizationPaused(organizationId: string): boolean;\n /**\n * Whether sync skips this container: every container of a paused\n * organization except the one `isRetainedWhileSyncPaused` keeps. The\n * session's active organization is never skipped, even when paused from\n * another device: its root is the session's workspace until it switches\n * away.\n */\n isContainerPaused(\n container: OrganizationSyncPauseSubject,\n activeOrganizationId: string | null,\n ): boolean;\n pausedOrganizationIds(): ReadonlySet<string>;\n /** Persists exactly this set and reports which organizations changed. */\n replace(\n execSql: ExecSql,\n organizationIds: Iterable<string>,\n ): Promise<OrganizationSyncPauseChange>;\n subscribe(listener: () => void): () => void;\n /**\n * Runs membership work for this scope one task at a time, so a membership\n * read that started before a pause or resume cannot apply after it.\n * Re-entrant calls from inside a task would wait on themselves.\n */\n runExclusive<T>(task: () => Promise<T>): Promise<T>;\n}\n\nasync function readPausedOrganizationIds(\n execSql: ExecSql,\n): Promise<Set<string>> {\n await ensureSqlTables(execSql, organizationSyncPauseTables);\n const rows = await getClientSQLitePersistenceRuntime(execSql)\n .db.select({ organizationId: organizationSyncPauses.organizationId })\n .from(organizationSyncPauses);\n return new Set(rows.map((row) => row.organizationId));\n}\n\n// One transaction replaces the whole set, so a failed write keeps the\n// previous pauses in force; inserts go in batches within SQLite's bind budget.\nasync function writePausedOrganizationIds(\n execSql: ExecSql,\n organizationIds: ReadonlySet<string>,\n): Promise<void> {\n await runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensureSqlTables(lockedExecSql, organizationSyncPauseTables);\n const ids = [...organizationIds];\n const batchSize = sqliteInsertBatchSize(organizationSyncPauses);\n await getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n await tx.delete(organizationSyncPauses).run();\n for (let index = 0; index < ids.length; index += batchSize) {\n await tx\n .insert(organizationSyncPauses)\n .values(\n ids\n .slice(index, index + batchSize)\n .map((organizationId) => ({ organizationId })),\n )\n .run();\n }\n // A resumed organization's removed documents may be reopened again.\n await tx\n .delete(organizationSyncPauseRemovals)\n .where(\n notInArray(\n organizationSyncPauseRemovals.organizationId,\n tx\n .select({\n organizationId: organizationSyncPauses.organizationId,\n })\n .from(organizationSyncPauses),\n ),\n )\n .run();\n },\n );\n });\n}\n\nfunction createOrganizationSyncPauses(): OrganizationSyncPauses {\n let paused: ReadonlySet<string> = new Set();\n let loading: Promise<void> | null = null;\n let replacing: Promise<void> = Promise.resolve();\n let exclusive: Promise<void> = Promise.resolve();\n const listeners = new Set<() => void>();\n const notify = () => {\n for (const listener of listeners) listener();\n };\n\n const pauses: OrganizationSyncPauses = {\n load(execSql) {\n loading ??= readPausedOrganizationIds(execSql).then(\n (stored) => {\n paused = stored;\n if (stored.size > 0) notify();\n },\n (error: unknown) => {\n // Let a later call retry a failed read.\n loading = null;\n throw error;\n },\n );\n return loading;\n },\n isOrganizationPaused: (organizationId) => paused.has(organizationId),\n isContainerPaused: (container, activeOrganizationId) =>\n paused.has(container.organizationId) &&\n container.organizationId !== activeOrganizationId &&\n !isRetainedWhileSyncPaused(container),\n pausedOrganizationIds: () => paused,\n replace(execSql, organizationIds) {\n const next = new Set(organizationIds);\n // Serialize replacements so each one diffs against the set the previous\n // one committed.\n const run = replacing.then(async () => {\n await pauses.load(execSql);\n const change = {\n paused: [...next].filter((id) => !paused.has(id)).sort(),\n resumed: [...paused].filter((id) => !next.has(id)).sort(),\n };\n if (change.paused.length === 0 && change.resumed.length === 0) {\n return change;\n }\n await writePausedOrganizationIds(execSql, next);\n paused = next;\n notify();\n return change;\n });\n replacing = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n runExclusive(task) {\n const run = exclusive.then(task);\n exclusive = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n },\n };\n return pauses;\n}\n\nconst pausesByScope = new WeakMap<DomainScope, OrganizationSyncPauses>();\n\n/** The one pause set for a domain scope; a new scope starts unloaded. */\nexport function getOrCreateOrganizationSyncPauses(\n domainScope: DomainScope,\n): OrganizationSyncPauses {\n let pauses = pausesByScope.get(domainScope);\n if (!pauses) {\n pauses = createOrganizationSyncPauses();\n pausesByScope.set(domainScope, pauses);\n }\n return pauses;\n}\n\n/**\n * Records, in the caller's transaction, that a pause's cleanup removed this\n * document, so reopening it does not recreate it while the pause lasts.\n */\nexport async function recordPauseRemovedDocument(\n execSql: ExecSql,\n removal: { readonly localId: string; readonly organizationId: string },\n): Promise<void> {\n await ensureSqlTables(execSql, organizationSyncPauseTables);\n await getClientSQLitePersistenceRuntime(execSql)\n .db.insert(organizationSyncPauseRemovals)\n .values(removal)\n .onConflictDoUpdate({\n set: { organizationId: removal.organizationId },\n target: organizationSyncPauseRemovals.localId,\n })\n .run();\n}\n\n/** Whether a pause's cleanup removed this document and the pause still holds. */\nexport async function isPauseRemovedDocument(\n execSql: ExecSql,\n localId: string,\n): Promise<boolean> {\n await ensureSqlTables(execSql, organizationSyncPauseTables);\n const rows = await getClientSQLitePersistenceRuntime(execSql)\n .db.select({ localId: organizationSyncPauseRemovals.localId })\n .from(organizationSyncPauseRemovals)\n .where(eq(organizationSyncPauseRemovals.localId, localId))\n .limit(1);\n return rows.length > 0;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"organizationSyncPauses.js","sourceRoot":"","sources":["organizationSyncPauses.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAE7C,OAAO,EACL,6BAA6B,EAC7B,sBAAsB,EACtB,2BAA2B,GAC5B,MAAM,8CAA8C,CAAC;AACtD,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACnE,OAAO,EAAE,iCAAiC,EAAE,MAAM,oCAAoC,CAAC;AACvF,OAAO,EAEL,eAAe,EACf,wBAAwB,GACzB,MAAM,qBAAqB,CAAC;AAS7B;;;;;GAKG;AACH,MAAM,UAAU,yBAAyB,CACvC,SAAuC;IAEvC,OAAO,SAAS,CAAC,QAAQ,KAAK,IAAI,IAAI,OAAO,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;AACtE,CAAC;AA0CD;;;GAGG;AACH,MAAM,OAAO,+BAA+B;IACzB,OAAO,CAAU;IAElC,YAAY,OAAgB;QAC1B,IAAI,CAAC,OAAO,GAA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Y,CAAC,IAAI;YACf,MAAM,GAAG,GAAG,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YACjC,SAAS,GAAG,GAAG,CAAC,IAAI,CAClB,GAAG,EAAE,CAAC,SAAS,EACf,GAAG,EAAE,CAAC,SAAS,CAChB,CAAC;YACF,OAAO,GAAG,CAAC;QACb,CAAC;KACF,CAAC;IACF,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,MAAM,aAAa,GAAG,IAAI,OAAO,EAAuC,CAAC;AAEzE,yEAAyE;AACzE,MAAM,UAAU,iCAAiC,CAC/C,WAAwB;IAExB,IAAI,MAAM,GAAG,aAAa,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IAC5C,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,MAAM,GAAG,4BAA4B,EAAE,CAAC;QACxC,aAAa,CAAC,GAAG,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC;IACzC,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { eq, notInArray } from \"drizzle-orm\";\nimport type { DomainScope } from \"../shared/domainScope\";\nimport {\n organizationSyncPauseRemovals,\n organizationSyncPauses,\n organizationSyncPauseTables,\n} from \"../sqlite/schema/organizationSyncPauseSchema\";\nimport { sqliteInsertBatchSize } from \"../sqlite/sqliteBindBudget\";\nimport { getClientSQLitePersistenceRuntime } from \"../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../sqlite/sqlSchema\";\n\n/** The container fields the pause rule reads. */\nexport interface OrganizationSyncPauseSubject {\n readonly organizationId: string;\n readonly parentId: string | null;\n readonly systemSlot?: string | null | undefined;\n}\n\n/**\n * Whether a container stays on the device while its organization is paused:\n * only the organization's parentless system root, the metadata root every\n * Members recipient reads, which keeps the organization named and its\n * membership visible.\n */\nexport function isRetainedWhileSyncPaused(\n container: OrganizationSyncPauseSubject,\n): boolean {\n return container.parentId === null && Boolean(container.systemSlot);\n}\n\nexport interface OrganizationSyncPauseChange {\n readonly paused: readonly string[];\n readonly resumed: readonly string[];\n}\n\n/**\n * Which organizations this user paused syncing to their devices, for one\n * domain scope. Sync reads it synchronously once `load` has settled; the\n * persisted set lets a device that starts offline keep honoring a pause.\n */\nexport interface OrganizationSyncPauses {\n /** Loads the persisted set once; concurrent and later calls share it. */\n load(execSql: ExecSql): Promise<void>;\n isOrganizationPaused(organizationId: string): boolean;\n /**\n * Whether sync skips this container: every container of a paused\n * organization except the one `isRetainedWhileSyncPaused` keeps. The\n * session's active organization is never skipped, even when paused from\n * another device: its root is the session's workspace until it switches\n * away.\n */\n isContainerPaused(\n container: OrganizationSyncPauseSubject,\n activeOrganizationId: string | null,\n ): boolean;\n pausedOrganizationIds(): ReadonlySet<string>;\n /** Persists exactly this set and reports which organizations changed. */\n replace(\n execSql: ExecSql,\n organizationIds: Iterable<string>,\n ): Promise<OrganizationSyncPauseChange>;\n subscribe(listener: () => void): () => void;\n /**\n * Runs membership work for this scope one task at a time, so a membership\n * read that started before a pause or resume cannot apply after it.\n * Re-entrant calls from inside a task would wait on themselves.\n */\n runExclusive<T>(task: () => Promise<T>): Promise<T>;\n}\n\n/**\n * Persistence for organization sync pauses and the documents a pause's\n * cleanup removed, bound to one executor.\n */\nexport class OrganizationSyncPauseRepository {\n private readonly execSql: ExecSql;\n\n constructor(execSql: ExecSql) {\n this.execSql = execSql;\n }\n\n async readPausedOrganizationIds(): Promise<Set<string>> {\n await ensureSqlTables(this.execSql, organizationSyncPauseTables);\n const rows = await getClientSQLitePersistenceRuntime(this.execSql)\n .db.select({ organizationId: organizationSyncPauses.organizationId })\n .from(organizationSyncPauses);\n return new Set(rows.map((row) => row.organizationId));\n }\n\n // One transaction replaces the whole set, so a failed write keeps the\n // previous pauses in force; inserts go in batches within SQLite's bind\n // budget.\n async writePausedOrganizationIds(\n organizationIds: ReadonlySet<string>,\n ): Promise<void> {\n await runSerializedSqlMutation(this.execSql, async (lockedExecSql) => {\n await ensureSqlTables(lockedExecSql, organizationSyncPauseTables);\n const ids = [...organizationIds];\n const batchSize = sqliteInsertBatchSize(organizationSyncPauses);\n await getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n await tx.delete(organizationSyncPauses).run();\n for (let index = 0; index < ids.length; index += batchSize) {\n await tx\n .insert(organizationSyncPauses)\n .values(\n ids\n .slice(index, index + batchSize)\n .map((organizationId) => ({ organizationId })),\n )\n .run();\n }\n // A resumed organization's removed documents may be reopened again.\n await tx\n .delete(organizationSyncPauseRemovals)\n .where(\n notInArray(\n organizationSyncPauseRemovals.organizationId,\n tx\n .select({\n organizationId: organizationSyncPauses.organizationId,\n })\n .from(organizationSyncPauses),\n ),\n )\n .run();\n },\n );\n });\n }\n\n /**\n * Records, in the caller's transaction, that a pause's cleanup removed this\n * document, so reopening it does not recreate it while the pause lasts.\n * A plain insert on the bound executor; it never opens a transaction.\n */\n async recordPauseRemovedDocument(removal: {\n readonly localId: string;\n readonly organizationId: string;\n }): Promise<void> {\n await ensureSqlTables(this.execSql, organizationSyncPauseTables);\n await getClientSQLitePersistenceRuntime(this.execSql)\n .db.insert(organizationSyncPauseRemovals)\n .values(removal)\n .onConflictDoUpdate({\n set: { organizationId: removal.organizationId },\n target: organizationSyncPauseRemovals.localId,\n })\n .run();\n }\n\n /** Whether a pause's cleanup removed this document and the pause holds. */\n async isPauseRemovedDocument(localId: string): Promise<boolean> {\n await ensureSqlTables(this.execSql, organizationSyncPauseTables);\n const rows = await getClientSQLitePersistenceRuntime(this.execSql)\n .db.select({ localId: organizationSyncPauseRemovals.localId })\n .from(organizationSyncPauseRemovals)\n .where(eq(organizationSyncPauseRemovals.localId, localId))\n .limit(1);\n return rows.length > 0;\n }\n}\n\nfunction createOrganizationSyncPauses(): OrganizationSyncPauses {\n let paused: ReadonlySet<string> = new Set();\n let loading: Promise<void> | null = null;\n let replacing: Promise<void> = Promise.resolve();\n let exclusive: Promise<void> = Promise.resolve();\n const listeners = new Set<() => void>();\n const notify = () => {\n for (const listener of listeners) listener();\n };\n\n const pauses: OrganizationSyncPauses = {\n load(execSql) {\n loading ??= new OrganizationSyncPauseRepository(execSql)\n .readPausedOrganizationIds()\n .then(\n (stored) => {\n paused = stored;\n if (stored.size > 0) notify();\n },\n (error: unknown) => {\n // Let a later call retry a failed read.\n loading = null;\n throw error;\n },\n );\n return loading;\n },\n isOrganizationPaused: (organizationId) => paused.has(organizationId),\n isContainerPaused: (container, activeOrganizationId) =>\n paused.has(container.organizationId) &&\n container.organizationId !== activeOrganizationId &&\n !isRetainedWhileSyncPaused(container),\n pausedOrganizationIds: () => paused,\n replace(execSql, organizationIds) {\n const next = new Set(organizationIds);\n // Serialize replacements so each one diffs against the set the previous\n // one committed.\n const run = replacing.then(async () => {\n await pauses.load(execSql);\n const change = {\n paused: [...next].filter((id) => !paused.has(id)).sort(),\n resumed: [...paused].filter((id) => !next.has(id)).sort(),\n };\n if (change.paused.length === 0 && change.resumed.length === 0) {\n return change;\n }\n await new OrganizationSyncPauseRepository(\n execSql,\n ).writePausedOrganizationIds(next);\n paused = next;\n notify();\n return change;\n });\n replacing = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n runExclusive(task) {\n const run = exclusive.then(task);\n exclusive = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n },\n };\n return pauses;\n}\n\nconst pausesByScope = new WeakMap<DomainScope, OrganizationSyncPauses>();\n\n/** The one pause set for a domain scope; a new scope starts unloaded. */\nexport function getOrCreateOrganizationSyncPauses(\n domainScope: DomainScope,\n): OrganizationSyncPauses {\n let pauses = pausesByScope.get(domainScope);\n if (!pauses) {\n pauses = createOrganizationSyncPauses();\n pausesByScope.set(domainScope, pauses);\n }\n return pauses;\n}\n"]}
|
package/index.d.ts
CHANGED
|
@@ -14,7 +14,7 @@ export type { TearleadsDatabaseOptions, TearleadsOptions, } from "./TearleadsOpt
|
|
|
14
14
|
export type { BlobAttachmentCollaborators, BlobAttachmentServiceApi, BlobByteSource, BlobByteSourceInput, BlobBytes, BlobStore, DecryptDocumentAttachmentBlobRequest, DetachDocumentAttachmentRequest, DetachDocumentAttachmentResult, EncryptedBlobStoreCipher, EncryptedBlobStoreKey, EncryptedBlobStoreOptions, HydrateDocumentAttachmentBlobsRequest, HydratedDocumentAttachmentBlob, UploadDocumentAttachmentRequest, UploadDocumentAttachmentResult, WrapEncryptedBlobStoreOptions, } from "./workflows/blobs/index.js";
|
|
15
15
|
export { BlobAttachmentService, blobByteSourceInputLength, createBlobByteSource, createBlobStore, createEncryptedBlobStore, createLazyEncryptedBlobStore, createMemoryBlobStore, purgeOpfsBlobStore, readBlobByteSource, wrapEncryptedBlobStore, } from "./workflows/blobs/index.js";
|
|
16
16
|
export type { ContainerContentsRootAdopter, ContainerContentsRootAdoptionInput, ContainerContentsStoreWorkflowRuntime, ContainerContentsWorkflowRuntime, ContainerDocumentLinkInput as ContainerDocumentQueriesLinkInput, ContainerSystemSlotDefinition, PendingDownloadQueueItem, RecoveryFolder, } from "./workflows/container-contents/index.js";
|
|
17
|
-
export { ContainerSyncWatermarkRepository, createContainerContentsDocumentsRuntime, createContainerContentsProjectionUserKeyResolver, createContainerContentsStoreWorkflowRuntime, createContainerContentsSyncLane, createContainerContentsWorkflowRuntime, createContainerParentSyncLane, createInitializedContainerMetadataDocument, defaultContainerContentsPersistence, deriveContainerSystemSlot,
|
|
17
|
+
export { ContainerSyncWatermarkRepository, createContainerContentsDocumentsRuntime, createContainerContentsProjectionUserKeyResolver, createContainerContentsStoreWorkflowRuntime, createContainerContentsSyncLane, createContainerContentsWorkflowRuntime, createContainerParentSyncLane, createInitializedContainerMetadataDocument, DocumentContainerProjectionRepository, defaultContainerContentsPersistence, deriveContainerSystemSlot, listBlobInfo, loadContainerInfo, loadDocumentAttributionRanges, loadDocumentInfo, syncedContainerDocumentObjectSyncState, } from "./workflows/container-contents/index.js";
|
|
18
18
|
export type { AggregatedContainerKekLog, ContainerMutationAuthor, ContainerMutationCollaborators, ContainerReciteApi, ContainerWriteRefusal, KeyringRebuildResult, MaterializedContainerRekeyPlan, } from "./workflows/containers/index.js";
|
|
19
19
|
export { buildMaterializedContainerRekeyPlan, buildRootContainerCreatePlan, ContainerAuthorAccessError, ContainerKekRepairInaccessibleError, ContainerKekRepairRequiredError, ContainerKeyringOverrideStaleError, ContainerMutationService, ContainerPathTooDeepError, classifyContainerWriteRefusal, containerWriterProjectionFromRekeyPlan, fetchContainerKekLog, HistoricalWrapUnavailableError, type HistoricalWrapUnavailableReason, isProjectionVerificationCancelledError, rebuildKeyringEntriesFromLog, recoverKeyringEntryFromWraps, rootContainerWriterProjectionFromCreatePlan, } from "./workflows/containers/index.js";
|
|
20
20
|
export type { DocumentBirthResult, DocumentRecord, DocumentSyncContainerRekeyBuilder, DocumentSyncPullContinuation, DocumentSyncUpdateIsolationError, DocumentsPersistence, DocumentsWorkflowRuntime, DocumentsWorkflowRuntimeInput, IncomingDocumentSyncUpdateValidator, LocalAttachmentRecord, PendingAttachmentRecord, PendingUpdateInsert, PendingUpdateRecord, QueuedPendingUpdateRecord, SyncRemoteDocumentInput, } from "./workflows/documents/index.js";
|
package/index.js
CHANGED
|
@@ -8,7 +8,7 @@ export { createContainerContentsStore, createContainerContentsStoreState, create
|
|
|
8
8
|
export { createDocumentStore, discardRegisteredDocumentLocalState, getOrCreateDocumentStore, hasPendingLocalDocumentWrites, openDocumentStore, requestDomainDocumentSync, subscribeToPersistedDocuments, } from "./stores/documents/index.js";
|
|
9
9
|
export { Tearleads } from "./Tearleads.js";
|
|
10
10
|
export { BlobAttachmentService, blobByteSourceInputLength, createBlobByteSource, createBlobStore, createEncryptedBlobStore, createLazyEncryptedBlobStore, createMemoryBlobStore, purgeOpfsBlobStore, readBlobByteSource, wrapEncryptedBlobStore, } from "./workflows/blobs/index.js";
|
|
11
|
-
export { ContainerSyncWatermarkRepository, createContainerContentsDocumentsRuntime, createContainerContentsProjectionUserKeyResolver, createContainerContentsStoreWorkflowRuntime, createContainerContentsSyncLane, createContainerContentsWorkflowRuntime, createContainerParentSyncLane, createInitializedContainerMetadataDocument, defaultContainerContentsPersistence, deriveContainerSystemSlot,
|
|
11
|
+
export { ContainerSyncWatermarkRepository, createContainerContentsDocumentsRuntime, createContainerContentsProjectionUserKeyResolver, createContainerContentsStoreWorkflowRuntime, createContainerContentsSyncLane, createContainerContentsWorkflowRuntime, createContainerParentSyncLane, createInitializedContainerMetadataDocument, DocumentContainerProjectionRepository, defaultContainerContentsPersistence, deriveContainerSystemSlot, listBlobInfo, loadContainerInfo, loadDocumentAttributionRanges, loadDocumentInfo, syncedContainerDocumentObjectSyncState, } from "./workflows/container-contents/index.js";
|
|
12
12
|
export { buildMaterializedContainerRekeyPlan, buildRootContainerCreatePlan, ContainerAuthorAccessError, ContainerKekRepairInaccessibleError, ContainerKekRepairRequiredError, ContainerKeyringOverrideStaleError, ContainerMutationService, ContainerPathTooDeepError, classifyContainerWriteRefusal, containerWriterProjectionFromRekeyPlan, fetchContainerKekLog, HistoricalWrapUnavailableError, isProjectionVerificationCancelledError, rebuildKeyringEntriesFromLog, recoverKeyringEntryFromWraps, rootContainerWriterProjectionFromCreatePlan, } from "./workflows/containers/index.js";
|
|
13
13
|
export { buildMaterializedDocumentCreatePlan, createDocumentProjectionUserKeyResolver, createDocumentsWorkflowRuntime, createRemoteDocument, DOCUMENT_SYNC_TRACE_FRAGMENT, DOCUMENT_SYNC_TRACE_PATTERN, DOCUMENTS_APP_KIND, DocumentRawHistoryUnavailableError, defaultDocumentsPersistence, deletePersistedDocument, deriveStableDocumentId, isDatabaseUnavailableError, isDocumentSyncUpdateIsolationError, isEmptyDocumentHistoryChange, persistedDocumentCreateStateFromResponse, readPullContinuation, syncRemoteDocument, unwrapContainerKekPath, unwrapDocumentContentKeyTarget, validateDocumentSyncUpdateImports, } from "./workflows/documents/index.js";
|
|
14
14
|
export { abandonJournaledPrincipalMutation, addOrganizationGroupUser, buildInitialGroupPolicyRequest, buildInitialMemberGroupPolicyRequest, buildOrganizationGroupPolicyHistory, buildOrganizationProfileDocumentPatch, buildRosterProfileDocumentPatch, checkNativePurchaseEligibility, createInitializedRosterProfileDocument, createOrganizationGroup, DEFAULT_PERSONAL_ORGANIZATION_PROFILE_NAME, deriveOrganizationMetadataContainerSystemSlot, deriveOrganizationRosterProfileContainerSystemSlot, discardUnreadableJournaledPrincipalMutation, GroupMembershipNameMismatchError, GroupShareNameMismatchError, getOrganizationProfileDocumentLocalId, getRosterProfileDocumentLocalId, loadLocalOrganizationDataUsage, loadLocalOrganizationDirectoryAndGroups, loadOrganizationBilling, loadOrganizationBillingHistory, loadOrganizationBillingManagementUrl, ORGANIZATION_DOCUMENT_USAGE_CATEGORIES, ORGANIZATION_METADATA_CONTAINER_NAME, ORGANIZATION_PROFILE_DOCUMENT_KIND, ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME, PendingPrincipalMutationError, PrincipalMutationOutcomeUnknownError, ROSTER_PROFILE_DOCUMENT_KIND, readJournaledPrincipalMutation, readOrganizationProfileName, reconcileOrganizationDataUsage, reconcileOrganizationDirectoryAndGroups, recoverJournaledPrincipalMutation, removeOrganizationGroupUser, resolveOrganizationBillingView, retainAcknowledgedPrincipalCurrents, revokeOrganizationContainerGrant, shareRemoteContainerWithGroup, startOrganizationTrial, submitJournaledPrincipalMutation, subscribeOrganizationReadModelInvalidation, UnreadablePrincipalMutationError, updateOrganizationProfile, updateOrganizationRosterEntry, } from "./workflows/organizations/index.js";
|