@tearleads/client-sdk 0.1.235 → 0.1.236

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/client/containerContents/documentDiscovery.js +1 -1
  2. package/client/containerContents/documentDiscovery.js.map +1 -1
  3. package/client/organizations/index.js +1 -1
  4. package/client/organizations/index.js.map +1 -1
  5. package/client/organizations/organizationMemberships.d.ts +6 -5
  6. package/client/organizations/organizationMemberships.js +12 -69
  7. package/client/organizations/organizationMemberships.js.map +1 -1
  8. package/client/runtime/workflowRuntime.js +5 -1
  9. package/client/runtime/workflowRuntime.js.map +1 -1
  10. package/data/sqlite/schema/index.d.ts +0 -45
  11. package/data/sqlite/schema/organizationSyncPauseSchema.js +6 -17
  12. package/data/sqlite/schema/organizationSyncPauseSchema.js.map +1 -1
  13. package/data/sync/organizationSyncPauseReadMachine.js +29 -0
  14. package/data/sync/organizationSyncPauseReadMachine.js.map +1 -0
  15. package/data/sync/organizationSyncPauses.d.ts +23 -34
  16. package/data/sync/organizationSyncPauses.js +49 -57
  17. package/data/sync/organizationSyncPauses.js.map +1 -1
  18. package/internal/validators/operation/organizationMemberships.d.ts +3 -21
  19. package/internal/validators/operation/organizationMemberships.js +2 -3
  20. package/internal/validators/operation/organizationMemberships.js.map +1 -1
  21. package/internal/validators/response/organizationMembership.d.ts +3 -3
  22. package/internal/validators/response/organizationMembership.js +3 -3
  23. package/internal/validators/response/organizationMembership.js.map +1 -1
  24. package/package.json +1 -1
  25. package/stores/container-contents/containerContentsStore.d.ts +1 -1
  26. package/stores/container-contents/containerContentsStore.js +0 -2
  27. package/stores/container-contents/containerContentsStore.js.map +1 -1
  28. package/stores/container-contents/syncAgent/index.js +6 -0
  29. package/stores/container-contents/syncAgent/index.js.map +1 -1
  30. package/stores/container-contents/types.d.ts +0 -6
  31. package/stores/container-contents/types.js.map +1 -1
  32. package/stores/documents/documentStore/index.js +3 -4
  33. package/stores/documents/documentStore/index.js.map +1 -1
  34. package/stores/documents/documentStore/initialization/index.js +7 -7
  35. package/stores/documents/documentStore/initialization/index.js.map +1 -1
  36. package/stores/documents/documentStore/sync/index.js +2 -5
  37. package/stores/documents/documentStore/sync/index.js.map +1 -1
  38. package/stores/documents/documentStore/sync/syncRequest.js +9 -2
  39. package/stores/documents/documentStore/sync/syncRequest.js.map +1 -1
  40. package/stores/documents/registry.d.ts +1 -34
  41. package/stores/documents/registry.js +4 -78
  42. package/stores/documents/registry.js.map +1 -1
  43. package/workflows/container-contents/metadata/metadataRemoteSync.js +1 -0
  44. package/workflows/container-contents/metadata/metadataRemoteSync.js.map +1 -1
  45. package/workflows/container-contents/remoteHydration/index.js +1 -1
  46. package/workflows/container-contents/remoteHydration/index.js.map +1 -1
  47. package/workflows/container-contents/remoteHydration/remoteContainers/organizationSyncPauseFilter.js +2 -4
  48. package/workflows/container-contents/remoteHydration/remoteContainers/organizationSyncPauseFilter.js.map +1 -1
  49. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js +3 -3
  50. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js.map +1 -1
  51. package/workflows/container-contents/syncPause/discoveryGuard.js +7 -6
  52. package/workflows/container-contents/syncPause/discoveryGuard.js.map +1 -1
  53. package/workflows/documents/remote/remoteDocumentCollaborators.d.ts +6 -2
  54. package/workflows/documents/remote/remoteDocumentCollaborators.js.map +1 -1
  55. package/workflows/documents/sync/index.js +8 -0
  56. package/workflows/documents/sync/index.js.map +1 -1
  57. package/workflows/documents/sync/readOnlySync.js +6 -0
  58. package/workflows/documents/sync/readOnlySync.js.map +1 -1
  59. package/workflows/documents/sync/remoteDocumentSyncPass.d.ts +7 -1
  60. package/workflows/documents/sync/remoteDocumentSyncPass.js.map +1 -1
  61. package/workflows/documents/sync/syncAttemptPlanning.js +24 -8
  62. package/workflows/documents/sync/syncAttemptPlanning.js.map +1 -1
  63. package/workflows/documents/syncFailures/index.js +6 -3
  64. package/workflows/documents/syncFailures/index.js.map +1 -1
  65. package/workflows/documents/syncFailures/syncAbandon.js +21 -0
  66. package/workflows/documents/syncFailures/syncAbandon.js.map +1 -1
  67. package/workflows/organizations/index.d.ts +1 -1
  68. package/workflows/organizations/index.js +1 -1
  69. package/workflows/organizations/index.js.map +1 -1
  70. package/workflows/organizations/memberships/organizationMemberships.d.ts +10 -35
  71. package/workflows/organizations/memberships/organizationMemberships.js +27 -44
  72. package/workflows/organizations/memberships/organizationMemberships.js.map +1 -1
  73. package/workflows/shared/runtimeInput.d.ts +11 -1
  74. package/workflows/shared/runtimeInput.js.map +1 -1
  75. package/workflows/sync/coordination.d.ts +1 -1
  76. package/workflows/sync/coordination.js +1 -1
  77. package/workflows/sync/coordination.js.map +1 -1
  78. package/workflows/sync/index.d.ts +1 -1
  79. package/workflows/sync/index.js +1 -1
  80. package/workflows/sync/index.js.map +1 -1
  81. package/data/persistence/container-contents/exclusiveDocumentPlacements.js +0 -61
  82. package/data/persistence/container-contents/exclusiveDocumentPlacements.js.map +0 -1
  83. package/stores/container-contents/operations/forgetOrganizationContentOperation.js +0 -76
  84. package/stores/container-contents/operations/forgetOrganizationContentOperation.js.map +0 -1
  85. package/stores/documents/removedDocumentStore.js +0 -40
  86. package/stores/documents/removedDocumentStore.js.map +0 -1
  87. package/workflows/container-contents/syncPause/documentRemoval.js +0 -165
  88. package/workflows/container-contents/syncPause/documentRemoval.js.map +0 -1
@@ -1,40 +0,0 @@
1
- const REMOVED_DOCUMENT_MESSAGE = "This document was removed while its organization's sync is paused";
2
- /**
3
- * Stands in for a store whose document a paused organization's cleanup
4
- * removed. It keeps showing the last snapshot, read-only, and does nothing
5
- * else, so an open editor neither recreates the document nor downloads it
6
- * while the pause lasts.
7
- */
8
- export function createRemovedDocumentStore(lastSnapshot) {
9
- const snapshot = {
10
- ...lastSnapshot,
11
- canAttach: false,
12
- canWrite: false,
13
- syncing: false,
14
- };
15
- const refuse = () => Promise.reject(new Error(REMOVED_DOCUMENT_MESSAGE));
16
- return {
17
- addRow: refuse,
18
- assertCanRotateContentKey: refuse,
19
- attachFiles: () => undefined,
20
- discardLocalState: async () => false,
21
- ensureInitialized: async () => false,
22
- getSnapshot: () => snapshot,
23
- hasQueuedWrites: () => false,
24
- hasUnsavedLocalEdits: () => false,
25
- removeAttachment: () => undefined,
26
- removeRow: refuse,
27
- replaceAttachment: refuse,
28
- requestRemoteSync: () => undefined,
29
- requestRemoteSyncAndWait: async () => false,
30
- requestSync: () => undefined,
31
- relink: async () => null,
32
- restoreContent: async () => false,
33
- setStructuredFields: refuse,
34
- setText: refuse,
35
- subscribe: () => () => undefined,
36
- updateRowFields: refuse,
37
- updateRuntime: () => undefined,
38
- };
39
- }
40
- //# sourceMappingURL=removedDocumentStore.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"removedDocumentStore.js","sourceRoot":"","sources":["removedDocumentStore.ts"],"names":[],"mappings":"AAEA,MAAM,wBAAwB,GAC5B,mEAAmE,CAAC;AAEtE;;;;;GAKG;AACH,MAAM,UAAU,0BAA0B,CACxC,YAA8B;IAE9B,MAAM,QAAQ,GAAqB;QACjC,GAAG,YAAY;QACf,SAAS,EAAE,KAAK;QAChB,QAAQ,EAAE,KAAK;QACf,OAAO,EAAE,KAAK;KACf,CAAC;IACF,MAAM,MAAM,GAAG,GAAG,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC,CAAC;IACzE,OAAO;QACL,MAAM,EAAE,MAAM;QACd,yBAAyB,EAAE,MAAM;QACjC,WAAW,EAAE,GAAG,EAAE,CAAC,SAAS;QAC5B,iBAAiB,EAAE,KAAK,IAAI,EAAE,CAAC,KAAK;QACpC,iBAAiB,EAAE,KAAK,IAAI,EAAE,CAAC,KAAK;QACpC,WAAW,EAAE,GAAG,EAAE,CAAC,QAAQ;QAC3B,eAAe,EAAE,GAAG,EAAE,CAAC,KAAK;QAC5B,oBAAoB,EAAE,GAAG,EAAE,CAAC,KAAK;QACjC,gBAAgB,EAAE,GAAG,EAAE,CAAC,SAAS;QACjC,SAAS,EAAE,MAAM;QACjB,iBAAiB,EAAE,MAAM;QACzB,iBAAiB,EAAE,GAAG,EAAE,CAAC,SAAS;QAClC,wBAAwB,EAAE,KAAK,IAAI,EAAE,CAAC,KAAK;QAC3C,WAAW,EAAE,GAAG,EAAE,CAAC,SAAS;QAC5B,MAAM,EAAE,KAAK,IAAI,EAAE,CAAC,IAAI;QACxB,cAAc,EAAE,KAAK,IAAI,EAAE,CAAC,KAAK;QACjC,mBAAmB,EAAE,MAAM;QAC3B,OAAO,EAAE,MAAM;QACf,SAAS,EAAE,GAAG,EAAE,CAAC,GAAG,EAAE,CAAC,SAAS;QAChC,eAAe,EAAE,MAAM;QACvB,aAAa,EAAE,GAAG,EAAE,CAAC,SAAS;KAC/B,CAAC;AACJ,CAAC","sourcesContent":["import type { DocumentSnapshot, DocumentStore } from \"./types\";\n\nconst REMOVED_DOCUMENT_MESSAGE =\n \"This document was removed while its organization's sync is paused\";\n\n/**\n * Stands in for a store whose document a paused organization's cleanup\n * removed. It keeps showing the last snapshot, read-only, and does nothing\n * else, so an open editor neither recreates the document nor downloads it\n * while the pause lasts.\n */\nexport function createRemovedDocumentStore(\n lastSnapshot: DocumentSnapshot,\n): DocumentStore {\n const snapshot: DocumentSnapshot = {\n ...lastSnapshot,\n canAttach: false,\n canWrite: false,\n syncing: false,\n };\n const refuse = () => Promise.reject(new Error(REMOVED_DOCUMENT_MESSAGE));\n return {\n addRow: refuse,\n assertCanRotateContentKey: refuse,\n attachFiles: () => undefined,\n discardLocalState: async () => false,\n ensureInitialized: async () => false,\n getSnapshot: () => snapshot,\n hasQueuedWrites: () => false,\n hasUnsavedLocalEdits: () => false,\n removeAttachment: () => undefined,\n removeRow: refuse,\n replaceAttachment: refuse,\n requestRemoteSync: () => undefined,\n requestRemoteSyncAndWait: async () => false,\n requestSync: () => undefined,\n relink: async () => null,\n restoreContent: async () => false,\n setStructuredFields: refuse,\n setText: refuse,\n subscribe: () => () => undefined,\n updateRowFields: refuse,\n updateRuntime: () => undefined,\n };\n}\n"]}
@@ -1,165 +0,0 @@
1
- import { deleteDocumentPlacements } from "../../../data/persistence/container-contents/documentContainerProjectionPersistence.js";
2
- import { listDocumentLocalIdsPlacedOnlyIn } from "../../../data/persistence/container-contents/exclusiveDocumentPlacements.js";
3
- import { runSerializedSqlMutation } from "../../../data/sqlite/sqlExec.js";
4
- import { registerClientSQLiteCommitGuard } from "../../../data/sqlite/sqliteCommitGuards.js";
5
- import { defaultDocumentsPersistence, deletePersistedDocument, } from "../../documents/index.js";
6
- import { OrganizationSyncPauseRepository } from "../../sync/coordination.js";
7
- import { carriesLocalWrites, listPendingWrites } from "../pendingWrites/index.js";
8
- // The deletion cascade binds several values per container across its
9
- // statements (its tombstone row alone binds a value per column), so a large
10
- // organization is removed in batches that stay within SQLite's bind budget.
11
- const CONTAINER_REMOVAL_BATCH_SIZE = 50;
12
- const refused = (status) => ({
13
- deletedContainerIds: [],
14
- deletedLocalIds: [],
15
- status,
16
- });
17
- /** Stops at the first batch that is no longer current. */
18
- async function deleteContainersInBatches(lockedExecSql, containerIds, deleteContainers) {
19
- const removedAt = new Date().toISOString();
20
- const deleted = [];
21
- for (let index = 0; index < containerIds.length; index += CONTAINER_REMOVAL_BATCH_SIZE) {
22
- const batch = containerIds.slice(index, index + CONTAINER_REMOVAL_BATCH_SIZE);
23
- const removed = await deleteContainers(lockedExecSql, batch.map((containerId) => ({
24
- containerId,
25
- reason: "access_revoked",
26
- updatedAt: removedAt,
27
- })));
28
- deleted.push(...removed);
29
- if (removed.length !== batch.length)
30
- break;
31
- }
32
- return deleted;
33
- }
34
- class DocumentRemovalNotCurrent extends Error {
35
- }
36
- /**
37
- * Deletes one document unless the removal stopped being current or a store
38
- * queued a write for it. The check runs as a commit guard, in the same
39
- * synchronous slice as the COMMIT, so an edit queued while the rows were being
40
- * deleted rolls the deletion back. When the COMMIT-time check passes, the
41
- * document's store is retired in that same slice, so an open editor turns
42
- * read-only before the deletion commits and no later edit can be accepted and
43
- * lost; a COMMIT that then fails restores it.
44
- */
45
- async function deleteDocumentUnlessEdited(input) {
46
- const expectedRecord = await defaultDocumentsPersistence.loadDocument(input.execSql, input.localId);
47
- if (!expectedRecord)
48
- return false;
49
- // The guard runs once when registered and again right before the COMMIT;
50
- // only that last run retires the store.
51
- let guardRuns = 0;
52
- let retired = false;
53
- try {
54
- const deleted = await deletePersistedDocument({
55
- beforeDeleteInTransaction: async (transactionExecSql) => {
56
- await new OrganizationSyncPauseRepository(transactionExecSql).recordPauseRemovedDocument({
57
- localId: input.localId,
58
- organizationId: input.organizationId,
59
- });
60
- registerClientSQLiteCommitGuard(transactionExecSql, () => {
61
- if (!input.stillCurrent() || input.hasQueuedWrites(input.localId)) {
62
- throw new DocumentRemovalNotCurrent();
63
- }
64
- guardRuns += 1;
65
- if (guardRuns > 1) {
66
- retired = true;
67
- input.retireDocument(input.localId);
68
- }
69
- });
70
- },
71
- deleteDocumentPlacements,
72
- documentProjectors: input.documentProjectors,
73
- execSql: input.execSql,
74
- expectedRecord,
75
- localId: input.localId,
76
- persistence: defaultDocumentsPersistence,
77
- });
78
- if (!deleted && retired)
79
- input.restoreDocument(input.localId);
80
- return deleted;
81
- }
82
- catch (error) {
83
- if (retired)
84
- input.restoreDocument(input.localId);
85
- if (error instanceof DocumentRemovalNotCurrent)
86
- return false;
87
- throw error;
88
- }
89
- }
90
- /**
91
- * Removes a paused organization's containers and the documents placed only in
92
- * them, unless a persisted pending write (a queued update, a deferred tail, an
93
- * intent, or an attachment upload) touches the organization, those
94
- * containers, or those documents. The scan and every deletion hold one SQLite
95
- * mutation lock, so no persisted write can land between them.
96
- *
97
- * An open store may also hold edits that have not reached SQLite yet, so
98
- * the removal refuses while any targeted document has queued writes; they
99
- * persist as pending writes and upload, and a later pass removes the rest.
100
- * The containers go first, under `stillCurrent`; documents are deleted only
101
- * after every container was, each under a commit guard against an edit
102
- * queued meanwhile or the removal no longer applying. A document edited mid-removal stays as a detached local
103
- * copy, like any document whose container this device lost. Documents that
104
- * were already detached are never touched: they may be the only copy of work
105
- * a recovery still needs.
106
- */
107
- /** Deletes documents in order until the removal stops being current. */
108
- async function deleteUneditedDocuments(input, lockedExecSql, localIds) {
109
- const deletedLocalIds = [];
110
- for (const localId of localIds) {
111
- if (!input.stillCurrent())
112
- break;
113
- if (await deleteDocumentUnlessEdited({
114
- documentProjectors: input.documentProjectors,
115
- execSql: lockedExecSql,
116
- hasQueuedWrites: input.hasQueuedWrites,
117
- localId,
118
- organizationId: input.organizationId,
119
- restoreDocument: input.restoreDocument,
120
- retireDocument: input.retireDocument,
121
- stillCurrent: input.stillCurrent,
122
- })) {
123
- deletedLocalIds.push(localId);
124
- }
125
- }
126
- return deletedLocalIds;
127
- }
128
- export async function removeOrganizationContentUnlessPending(input) {
129
- return runSerializedSqlMutation(input.execSql, async (lockedExecSql) => {
130
- const containerIds = new Set(input.containerIds);
131
- const localIds = await listDocumentLocalIdsPlacedOnlyIn(lockedExecSql, input.containerIds);
132
- if (containerIds.size === 0 && localIds.length === 0) {
133
- return {
134
- deletedContainerIds: [],
135
- deletedLocalIds: [],
136
- status: "removed",
137
- };
138
- }
139
- const documentIds = new Set(localIds);
140
- const pending = await listPendingWrites(lockedExecSql);
141
- if (pending.some((item) => carriesLocalWrites(item) &&
142
- (item.organizationId === input.organizationId ||
143
- (item.containerId !== null && containerIds.has(item.containerId)) ||
144
- documentIds.has(item.localId)))) {
145
- return refused("pending-writes");
146
- }
147
- if (localIds.some(input.hasQueuedWrites))
148
- return refused("queued-edits");
149
- const deletedContainerIds = await deleteContainersInBatches(lockedExecSql, [...containerIds], input.deleteContainers);
150
- if (deletedContainerIds.length !== containerIds.size) {
151
- return {
152
- deletedContainerIds,
153
- deletedLocalIds: [],
154
- status: "interrupted",
155
- };
156
- }
157
- const deletedLocalIds = await deleteUneditedDocuments(input, lockedExecSql, localIds);
158
- return {
159
- deletedContainerIds,
160
- deletedLocalIds,
161
- status: deletedLocalIds.length === localIds.length ? "removed" : "interrupted",
162
- };
163
- });
164
- }
165
- //# sourceMappingURL=documentRemoval.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"documentRemoval.js","sourceRoot":"","sources":["documentRemoval.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,qFAAqF,CAAC;AAC/H,OAAO,EAAE,gCAAgC,EAAE,MAAM,0EAA0E,CAAC;AAC5H,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,EAAE,+BAA+B,EAAE,MAAM,yCAAyC,CAAC;AAE1F,OAAO,EACL,2BAA2B,EAC3B,uBAAuB,GACxB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,+BAA+B,EAAE,MAAM,yBAAyB,CAAC;AAC1E,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAmBzE,qEAAqE;AACrE,4EAA4E;AAC5E,4EAA4E;AAC5E,MAAM,4BAA4B,GAAG,EAAE,CAAC;AAExC,MAAM,OAAO,GAAG,CACd,MAAyC,EACb,EAAE,CAAC,CAAC;IAChC,mBAAmB,EAAE,EAAE;IACvB,eAAe,EAAE,EAAE;IACnB,MAAM;CACP,CAAC,CAAC;AAQH,0DAA0D;AAC1D,KAAK,UAAU,yBAAyB,CACtC,aAAsB,EACtB,YAA+B,EAC/B,gBAG+B;IAE/B,MAAM,SAAS,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IAC3C,MAAM,OAAO,GAAa,EAAE,CAAC;IAC7B,KACE,IAAI,KAAK,GAAG,CAAC,EACb,KAAK,GAAG,YAAY,CAAC,MAAM,EAC3B,KAAK,IAAI,4BAA4B,EACrC,CAAC;QACD,MAAM,KAAK,GAAG,YAAY,CAAC,KAAK,CAC9B,KAAK,EACL,KAAK,GAAG,4BAA4B,CACrC,CAAC;QACF,MAAM,OAAO,GAAG,MAAM,gB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,MAAM,mBAAmB,GAAG,MAAM,yBAAyB,CACzD,aAAa,EACb,CAAC,GAAG,YAAY,CAAC,EACjB,KAAK,CAAC,gBAAgB,CACvB,CAAC;QACF,IAAI,mBAAmB,CAAC,MAAM,KAAK,YAAY,CAAC,IAAI,EAAE,CAAC;YACrD,OAAO;gBACL,mBAAmB;gBACnB,eAAe,EAAE,EAAE;gBACnB,MAAM,EAAE,aAAa;aACtB,CAAC;QACJ,CAAC;QACD,MAAM,eAAe,GAAG,MAAM,uBAAuB,CACnD,KAAK,EACL,aAAa,EACb,QAAQ,CACT,CAAC;QACF,OAAO;YACL,mBAAmB;YACnB,eAAe;YACf,MAAM,EACJ,eAAe,CAAC,MAAM,KAAK,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,aAAa;SACzE,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { deleteDocumentPlacements } from \"../../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport { listDocumentLocalIdsPlacedOnlyIn } from \"../../../data/persistence/container-contents/exclusiveDocumentPlacements\";\nimport { runSerializedSqlMutation } from \"../../../data/sqlite/sqlExec\";\nimport { registerClientSQLiteCommitGuard } from \"../../../data/sqlite/sqliteCommitGuards\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n defaultDocumentsPersistence,\n deletePersistedDocument,\n} from \"../../documents\";\nimport { OrganizationSyncPauseRepository } from \"../../sync/coordination\";\nimport { carriesLocalWrites, listPendingWrites } from \"../pendingWrites\";\nimport type { ContainerContentsWorkflowRuntimeInfra } from \"../runtime\";\n\nexport interface OrganizationContentRemoval {\n /**\n * `removed` when every targeted container and document is gone.\n * `pending-writes` and `queued-edits` refused before deleting anything.\n * `interrupted` stopped part way: the removal stopped being current, or a\n * document was edited while it ran and stayed.\n */\n readonly status:\n | \"removed\"\n | \"pending-writes\"\n | \"queued-edits\"\n | \"interrupted\";\n readonly deletedContainerIds: readonly string[];\n readonly deletedLocalIds: readonly string[];\n}\n\n// The deletion cascade binds several values per container across its\n// statements (its tombstone row alone binds a value per column), so a large\n// organization is removed in batches that stay within SQLite's bind budget.\nconst CONTAINER_REMOVAL_BATCH_SIZE = 50;\n\nconst refused = (\n status: \"pending-writes\" | \"queued-edits\",\n): OrganizationContentRemoval => ({\n deletedContainerIds: [],\n deletedLocalIds: [],\n status,\n});\n\ninterface ContainerRemoval {\n readonly containerId: string;\n readonly reason: \"access_revoked\";\n readonly updatedAt: string;\n}\n\n/** Stops at the first batch that is no longer current. */\nasync function deleteContainersInBatches(\n lockedExecSql: ExecSql,\n containerIds: readonly string[],\n deleteContainers: (\n lockedExecSql: ExecSql,\n removals: readonly ContainerRemoval[],\n ) => Promise<readonly string[]>,\n): Promise<string[]> {\n const removedAt = new Date().toISOString();\n const deleted: string[] = [];\n for (\n let index = 0;\n index < containerIds.length;\n index += CONTAINER_REMOVAL_BATCH_SIZE\n ) {\n const batch = containerIds.slice(\n index,\n index + CONTAINER_REMOVAL_BATCH_SIZE,\n );\n const removed = await deleteContainers(\n lockedExecSql,\n batch.map((containerId) => ({\n containerId,\n reason: \"access_revoked\",\n updatedAt: removedAt,\n })),\n );\n deleted.push(...removed);\n if (removed.length !== batch.length) break;\n }\n return deleted;\n}\n\nclass DocumentRemovalNotCurrent extends Error {}\n\n/**\n * Deletes one document unless the removal stopped being current or a store\n * queued a write for it. The check runs as a commit guard, in the same\n * synchronous slice as the COMMIT, so an edit queued while the rows were being\n * deleted rolls the deletion back. When the COMMIT-time check passes, the\n * document's store is retired in that same slice, so an open editor turns\n * read-only before the deletion commits and no later edit can be accepted and\n * lost; a COMMIT that then fails restores it.\n */\nasync function deleteDocumentUnlessEdited(input: {\n readonly documentProjectors: ContainerContentsWorkflowRuntimeInfra[\"documentProjectors\"];\n readonly execSql: ExecSql;\n readonly hasQueuedWrites: (localId: string) => boolean;\n readonly localId: string;\n readonly organizationId: string;\n readonly restoreDocument: (localId: string) => void;\n readonly retireDocument: (localId: string) => void;\n readonly stillCurrent: () => boolean;\n}): Promise<boolean> {\n const expectedRecord = await defaultDocumentsPersistence.loadDocument(\n input.execSql,\n input.localId,\n );\n if (!expectedRecord) return false;\n // The guard runs once when registered and again right before the COMMIT;\n // only that last run retires the store.\n let guardRuns = 0;\n let retired = false;\n try {\n const deleted = await deletePersistedDocument({\n beforeDeleteInTransaction: async (transactionExecSql) => {\n await new OrganizationSyncPauseRepository(\n transactionExecSql,\n ).recordPauseRemovedDocument({\n localId: input.localId,\n organizationId: input.organizationId,\n });\n registerClientSQLiteCommitGuard(transactionExecSql, () => {\n if (!input.stillCurrent() || input.hasQueuedWrites(input.localId)) {\n throw new DocumentRemovalNotCurrent();\n }\n guardRuns += 1;\n if (guardRuns > 1) {\n retired = true;\n input.retireDocument(input.localId);\n }\n });\n },\n deleteDocumentPlacements,\n documentProjectors: input.documentProjectors,\n execSql: input.execSql,\n expectedRecord,\n localId: input.localId,\n persistence: defaultDocumentsPersistence,\n });\n if (!deleted && retired) input.restoreDocument(input.localId);\n return deleted;\n } catch (error) {\n if (retired) input.restoreDocument(input.localId);\n if (error instanceof DocumentRemovalNotCurrent) return false;\n throw error;\n }\n}\n\n/**\n * Removes a paused organization's containers and the documents placed only in\n * them, unless a persisted pending write (a queued update, a deferred tail, an\n * intent, or an attachment upload) touches the organization, those\n * containers, or those documents. The scan and every deletion hold one SQLite\n * mutation lock, so no persisted write can land between them.\n *\n * An open store may also hold edits that have not reached SQLite yet, so\n * the removal refuses while any targeted document has queued writes; they\n * persist as pending writes and upload, and a later pass removes the rest.\n * The containers go first, under `stillCurrent`; documents are deleted only\n * after every container was, each under a commit guard against an edit\n * queued meanwhile or the removal no longer applying. A document edited mid-removal stays as a detached local\n * copy, like any document whose container this device lost. Documents that\n * were already detached are never touched: they may be the only copy of work\n * a recovery still needs.\n */\n/** Deletes documents in order until the removal stops being current. */\nasync function deleteUneditedDocuments(\n input: Parameters<typeof removeOrganizationContentUnlessPending>[0],\n lockedExecSql: ExecSql,\n localIds: readonly string[],\n): Promise<string[]> {\n const deletedLocalIds: string[] = [];\n for (const localId of localIds) {\n if (!input.stillCurrent()) break;\n if (\n await deleteDocumentUnlessEdited({\n documentProjectors: input.documentProjectors,\n execSql: lockedExecSql,\n hasQueuedWrites: input.hasQueuedWrites,\n localId,\n organizationId: input.organizationId,\n restoreDocument: input.restoreDocument,\n retireDocument: input.retireDocument,\n stillCurrent: input.stillCurrent,\n })\n ) {\n deletedLocalIds.push(localId);\n }\n }\n return deletedLocalIds;\n}\n\nexport async function removeOrganizationContentUnlessPending(input: {\n readonly containerIds: readonly string[];\n readonly deleteContainers: (\n lockedExecSql: ExecSql,\n removals: readonly ContainerRemoval[],\n ) => Promise<readonly string[]>;\n readonly documentProjectors: ContainerContentsWorkflowRuntimeInfra[\"documentProjectors\"];\n readonly execSql: ExecSql;\n /** Whether an open store holds writes for the document not yet in SQLite. */\n readonly hasQueuedWrites: (localId: string) => boolean;\n readonly organizationId: string;\n /** Undoes retireDocument when the deletion did not commit. */\n readonly restoreDocument: (localId: string) => void;\n /** Retires a deleted document's store; see deleteDocumentUnlessEdited. */\n readonly retireDocument: (localId: string) => void;\n /** Whether the removal still applies, e.g. the session did not switch in. */\n readonly stillCurrent: () => boolean;\n}): Promise<OrganizationContentRemoval> {\n return runSerializedSqlMutation(input.execSql, async (lockedExecSql) => {\n const containerIds = new Set(input.containerIds);\n const localIds = await listDocumentLocalIdsPlacedOnlyIn(\n lockedExecSql,\n input.containerIds,\n );\n if (containerIds.size === 0 && localIds.length === 0) {\n return {\n deletedContainerIds: [],\n deletedLocalIds: [],\n status: \"removed\",\n };\n }\n const documentIds = new Set(localIds);\n const pending = await listPendingWrites(lockedExecSql);\n if (\n pending.some(\n (item) =>\n carriesLocalWrites(item) &&\n (item.organizationId === input.organizationId ||\n (item.containerId !== null && containerIds.has(item.containerId)) ||\n documentIds.has(item.localId)),\n )\n ) {\n return refused(\"pending-writes\");\n }\n if (localIds.some(input.hasQueuedWrites)) return refused(\"queued-edits\");\n\n const deletedContainerIds = await deleteContainersInBatches(\n lockedExecSql,\n [...containerIds],\n input.deleteContainers,\n );\n if (deletedContainerIds.length !== containerIds.size) {\n return {\n deletedContainerIds,\n deletedLocalIds: [],\n status: \"interrupted\",\n };\n }\n const deletedLocalIds = await deleteUneditedDocuments(\n input,\n lockedExecSql,\n localIds,\n );\n return {\n deletedContainerIds,\n deletedLocalIds,\n status:\n deletedLocalIds.length === localIds.length ? \"removed\" : \"interrupted\",\n };\n });\n}\n"]}