@tearleads/client-sdk 0.1.235 → 0.1.237

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 (92) 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/documentRecordSchema.js +7 -0
  11. package/data/sqlite/schema/documentRecordSchema.js.map +1 -1
  12. package/data/sqlite/schema/index.d.ts +0 -45
  13. package/data/sqlite/schema/organizationSyncPauseSchema.js +6 -17
  14. package/data/sqlite/schema/organizationSyncPauseSchema.js.map +1 -1
  15. package/data/sync/organizationSyncPauseReadMachine.js +29 -0
  16. package/data/sync/organizationSyncPauseReadMachine.js.map +1 -0
  17. package/data/sync/organizationSyncPauses.d.ts +23 -34
  18. package/data/sync/organizationSyncPauses.js +49 -57
  19. package/data/sync/organizationSyncPauses.js.map +1 -1
  20. package/internal/validators/operation/organizationMemberships.d.ts +3 -21
  21. package/internal/validators/operation/organizationMemberships.js +2 -3
  22. package/internal/validators/operation/organizationMemberships.js.map +1 -1
  23. package/internal/validators/response/organizationMembership.d.ts +3 -3
  24. package/internal/validators/response/organizationMembership.js +3 -3
  25. package/internal/validators/response/organizationMembership.js.map +1 -1
  26. package/package.json +1 -1
  27. package/stores/container-contents/containerContentsStore.d.ts +1 -1
  28. package/stores/container-contents/containerContentsStore.js +0 -2
  29. package/stores/container-contents/containerContentsStore.js.map +1 -1
  30. package/stores/container-contents/syncAgent/index.js +6 -0
  31. package/stores/container-contents/syncAgent/index.js.map +1 -1
  32. package/stores/container-contents/types.d.ts +0 -6
  33. package/stores/container-contents/types.js.map +1 -1
  34. package/stores/documents/documentStore/index.js +3 -4
  35. package/stores/documents/documentStore/index.js.map +1 -1
  36. package/stores/documents/documentStore/initialization/index.js +7 -7
  37. package/stores/documents/documentStore/initialization/index.js.map +1 -1
  38. package/stores/documents/documentStore/sync/index.js +2 -5
  39. package/stores/documents/documentStore/sync/index.js.map +1 -1
  40. package/stores/documents/documentStore/sync/syncRequest.js +9 -2
  41. package/stores/documents/documentStore/sync/syncRequest.js.map +1 -1
  42. package/stores/documents/registry.d.ts +1 -34
  43. package/stores/documents/registry.js +4 -78
  44. package/stores/documents/registry.js.map +1 -1
  45. package/workflows/container-contents/metadata/metadataRemoteSync.js +1 -0
  46. package/workflows/container-contents/metadata/metadataRemoteSync.js.map +1 -1
  47. package/workflows/container-contents/pendingWrites/deferredTails.js +4 -0
  48. package/workflows/container-contents/pendingWrites/deferredTails.js.map +1 -1
  49. package/workflows/container-contents/remoteHydration/index.js +1 -1
  50. package/workflows/container-contents/remoteHydration/index.js.map +1 -1
  51. package/workflows/container-contents/remoteHydration/remoteContainers/organizationSyncPauseFilter.js +2 -4
  52. package/workflows/container-contents/remoteHydration/remoteContainers/organizationSyncPauseFilter.js.map +1 -1
  53. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js +3 -3
  54. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js.map +1 -1
  55. package/workflows/container-contents/syncPause/discoveryGuard.js +7 -6
  56. package/workflows/container-contents/syncPause/discoveryGuard.js.map +1 -1
  57. package/workflows/documents/remote/remoteDocumentCollaborators.d.ts +6 -2
  58. package/workflows/documents/remote/remoteDocumentCollaborators.js.map +1 -1
  59. package/workflows/documents/sync/index.js +8 -0
  60. package/workflows/documents/sync/index.js.map +1 -1
  61. package/workflows/documents/sync/readOnlySync.js +6 -0
  62. package/workflows/documents/sync/readOnlySync.js.map +1 -1
  63. package/workflows/documents/sync/remoteDocumentSyncPass.d.ts +7 -1
  64. package/workflows/documents/sync/remoteDocumentSyncPass.js.map +1 -1
  65. package/workflows/documents/sync/syncAttemptPlanning.js +24 -8
  66. package/workflows/documents/sync/syncAttemptPlanning.js.map +1 -1
  67. package/workflows/documents/syncFailures/index.js +6 -3
  68. package/workflows/documents/syncFailures/index.js.map +1 -1
  69. package/workflows/documents/syncFailures/syncAbandon.js +21 -0
  70. package/workflows/documents/syncFailures/syncAbandon.js.map +1 -1
  71. package/workflows/organizations/index.d.ts +1 -1
  72. package/workflows/organizations/index.js +1 -1
  73. package/workflows/organizations/index.js.map +1 -1
  74. package/workflows/organizations/memberships/organizationMemberships.d.ts +10 -35
  75. package/workflows/organizations/memberships/organizationMemberships.js +27 -44
  76. package/workflows/organizations/memberships/organizationMemberships.js.map +1 -1
  77. package/workflows/shared/runtimeInput.d.ts +11 -1
  78. package/workflows/shared/runtimeInput.js.map +1 -1
  79. package/workflows/sync/coordination.d.ts +1 -1
  80. package/workflows/sync/coordination.js +1 -1
  81. package/workflows/sync/coordination.js.map +1 -1
  82. package/workflows/sync/index.d.ts +1 -1
  83. package/workflows/sync/index.js +1 -1
  84. package/workflows/sync/index.js.map +1 -1
  85. package/data/persistence/container-contents/exclusiveDocumentPlacements.js +0 -61
  86. package/data/persistence/container-contents/exclusiveDocumentPlacements.js.map +0 -1
  87. package/stores/container-contents/operations/forgetOrganizationContentOperation.js +0 -76
  88. package/stores/container-contents/operations/forgetOrganizationContentOperation.js.map +0 -1
  89. package/stores/documents/removedDocumentStore.js +0 -40
  90. package/stores/documents/removedDocumentStore.js.map +0 -1
  91. package/workflows/container-contents/syncPause/documentRemoval.js +0 -165
  92. package/workflows/container-contents/syncPause/documentRemoval.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"documentRecordSchema.js","sourceRoot":"","sources":["documentRecordSchema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EACL,KAAK,EACL,OAAO,EACP,UAAU,EACV,WAAW,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,MAAM,cAAc,GAAkC;IAC3D;QACE,GAAG,oBAAoB,CAAC,SAAS,CAAC;QAClC,eAAe,EAAE;YACf,mBAAmB;YACnB,qBAAqB;YACrB,sBAAsB;YACtB,qBAAqB;YACrB,sBAAsB;YACtB,2BAA2B;SAC5B;KACF;IACD,oBAAoB,CAAC,0BAA0B,CAAC;IAChD;QACE,GAAG,oBAAoB,CAAC,sBAAsB,CAAC;QAC/C,eAAe,EAAE,CAAC,WAAW,CAAC;KAC/B;CACF,CAAC","sourcesContent":["import { sql } from \"drizzle-orm\";\nimport {\n index,\n integer,\n primaryKey,\n sqliteTable,\n text,\n uniqueIndex,\n} from \"drizzle-orm/sqlite-core\";\nimport { defineSqlTableSchema, type SqlTableSchema } from \"../sqlTableSchema\";\n\nconst accessLevelColumn = \"effective_access_level\";\n/**\n * Durable Loro-backed document records shared by app features.\n *\n * This table stores encrypted document runtime state for multiple app domains.\n * `appKind` namespaces records for documents and container metadata. User-facing\n * list data is projected into feature-specific read models.\n *\n * Columns:\n * - `appKind`: Local domain namespace for the row, such as `documents` or\n * `container-metadata`.\n * - `localId`: Stable local id inside `appKind`. It may be created before a\n * server `documentId` exists.\n * - `documentId`: Server document id once the record is known remotely, or\n * `null` while the document is local-only.\n * - `accessEpoch`: Latest access epoch persisted for the document. Defaults to\n * the initial epoch.\n * - `accessStateHash`: Current document access/manifest state hash returned by\n * sync, when known.\n * - `lastCommitLsn`: Last remote commit cursor applied to this local document.\n * - `documentManifestBundle`: Serialized document manifest bundle used for\n * encrypted document sync.\n * - `contentKeyBundle`: Serialized content-key material needed to open the\n * local document.\n * - `documentKekTargets`: Serialized KEK target state for document key wraps.\n * - `pendingBaseVersion`: Encoded oplog version through which every persisted\n * op is already enqueued or synced. Persisted so a restart restores the\n * outgoing-delta marker instead of re-seeding it past a device-first\n * `deferRemoteSync` write's un-advanced op. `null` when unset.\n * - `snapshotEndVersion`: Encoded end version vector of the persisted content\n * (which lives in the durable-history tables, never on this row), written on\n * every content persist. Lets the pending-write queue's deferred-tail scan\n * compare version coverage without loading content. Empty string when the\n * document has never hydrated content, which readers treat as \"no deferred\n * tail claimable\".\n * - `recoveryGeneration`: Atomic raw-history recovery writer fence.\n * - `recoveryDocumentId`: Former server id for cross-client post-purge recreation.\n * - `pullContinuation`: Durable progress for the next bounded remote pull.\n * - `syncFailureStatus`, `syncFailureMessage`, `syncFailureAttemptedAt`: The\n * last terminal sync failure or quarantined incoming update for this scope.\n * The durable write queue (queued rows of `documentHistoryUpdates`) has no\n * status columns, so these let the write-queue view and footer explain why\n * the document is blocked. `syncFailureMessage` is non-null exactly when a\n * failure is recorded; a newer failure replaces the old, and a later fully\n * validated sync pass, a remote reset, or the scope's teardown clears all\n * three.\n * - `updatedAt`: Local timestamp for the last persisted runtime-state update.\n *\n * Indexes:\n * - `(appKind, localId)` is the primary key and scopes local document lookups.\n * - `(appKind, documentId) where documentId is not null` supports resolving a\n * server document id back to the local row during discovery and relinking.\n */\nexport const documents = sqliteTable(\n \"documents\",\n {\n appKind: text(\"app_kind\").notNull(),\n localId: text(\"local_id\").notNull(),\n documentId: text(\"document_id\"),\n accessEpoch: integer(\"access_epoch\").notNull().default(1),\n accessStateHash: text(\"access_state_hash\"),\n effectiveAccessLevel: text(accessLevelColumn).notNull().default(\"read\"),\n lastCommitLsn: text(\"last_commit_lsn\"),\n documentManifestBundle: text(\"document_manifest_bundle\"),\n contentKeyBundle: text(\"content_key_bundle\"),\n documentKekTargets: text(\"document_kek_targets\"),\n pendingBaseVersion: text(\"pending_base_version\"),\n pullContinuation: text(\"pull_continuation\"),\n recoveryGeneration: integer(\"recovery_generation\").notNull().default(0),\n recoveryDocumentId: text(\"recovery_document_id\"),\n snapshotEndVersion: text(\"snapshot_end_version\").notNull().default(\"\"),\n syncFailureStatus: integer(\"sync_failure_status\"),\n syncFailureMessage: text(\"sync_failure_message\"),\n syncFailureAttemptedAt: text(\"sync_failure_attempted_at\"),\n updatedAt: text(\"updated_at\").notNull(),\n },\n (table) => [\n primaryKey({ columns: [table.appKind, table.localId] }),\n index(\"documents_app_document_idx\")\n .on(table.appKind, table.documentId)\n .where(sql`${table.documentId} IS NOT NULL`),\n ],\n);\n\n/**\n * Full-history persistence for local documents (checkpoint + tail) — the ONLY\n * durable content source. Record rows in `documents` carry runtime metadata\n * and the content frontier (`snapshotEndVersion`), never content. The\n * checkpoint holds a full-history snapshot refreshed only at compaction, and\n * the tail appends every update (local deltas and decrypted remote updates)\n * written since. Restore = import checkpoint + replay tail; compaction =\n * export full history from the live doc, replace the checkpoint, clear the\n * tail — all bounded and amortized. Container metadata stores its content (an\n * exported-updates blob) as its checkpoint row, with no tail.\n */\nexport const documentHistoryCheckpoints = sqliteTable(\n \"document_history_checkpoints\",\n {\n appKind: text(\"app_kind\").notNull(),\n localId: text(\"local_id\").notNull(),\n snapshot: text(\"snapshot\").notNull(),\n endVersionVector: text(\"end_version_vector\").notNull(),\n revision: text(\"revision\").notNull(),\n updatedAt: text(\"updated_at\").notNull(),\n },\n (table) => [primaryKey({ columns: [table.appKind, table.localId] })],\n);\n\n/**\n * The local update log: one row per Loro update, serving as both the history\n * tail (restore = checkpoint + tail) and the outbound write queue.\n *\n * Every locally authored update is stored once. While it waits for sync it\n * carries an `updateId` (the id submitted to the server) and the version-vector\n * metadata the submission needs; settlement clears them, leaving the row as\n * ordinary tail history until compaction folds it into a checkpoint. Before a\n * send, a contiguous run of queued local rows may be replaced by one merged\n * row holding exactly their operations: the first row is updated in place\n * (same `id`, `createdAt` and `rowid`, so the same queue and replay position)\n * under a fresh `updateId`, and the other rows are deleted.\n *\n * Columns:\n * - `id`: Row id; tail compaction deletes by it.\n * - `appKind`, `localId`: Document scope matching `documents`.\n * - `updateData`: Serialized Loro update payload.\n * - `origin`: \"local\" (authored on this device) or \"remote\" (decrypted\n * pulled update) for tail rows. Restores use it to advance the\n * outgoing-delta marker across remote rows — their ops are already\n * server-side — while a local row left behind by a crash stays below the\n * marker so the next edit re-derives and sends it. \"outbox\" marks a queued\n * update with no tail role (container metadata, whose content is its\n * checkpoint, and full-state re-uploads after a remote reset); restores and\n * compaction never see it and settlement deletes it.\n * - `createdAt`: Insertion timestamp; with `rowid`, deterministic replay order.\n * - `updateId`: Present exactly while the row is queued for sync; rekeyed\n * after a lost acknowledgement poisons the submitted id, and replaced by a\n * fresh id when queued rows merge. An id never names two payloads.\n * - `partialStartVersionVector` / `partialEndVersionVector`: Version vectors\n * around a queued partial update.\n * - `sourceVersionVector`: Present on a queued rotation baseline checkpoint.\n * - `rekeyCount`: Durable bound on rekeys of a queued row; a merged row takes\n * the largest count among the rows it replaces.\n *\n * Invariant: compaction never deletes a queued row, so a checkpoint can cover\n * a queued update's operations without removing it from the queue.\n */\nexport const documentHistoryUpdates = sqliteTable(\n \"document_history_updates\",\n {\n id: text(\"id\"),\n appKind: text(\"app_kind\").notNull(),\n localId: text(\"local_id\").notNull(),\n updateData: text(\"update_data\").notNull(),\n origin: text(\"origin\").notNull(),\n createdAt: text(\"created_at\").notNull(),\n updateId: text(\"update_id\"),\n partialStartVersionVector: text(\"partial_start_version_vector\"),\n partialEndVersionVector: text(\"partial_end_version_vector\"),\n sourceVersionVector: text(\"source_version_vector\"),\n rekeyCount: integer(\"rekey_count\").notNull().default(0),\n },\n (table) => [\n primaryKey({ columns: [table.id] }),\n index(\"document_history_updates_scope_created_idx\").on(\n table.appKind,\n table.localId,\n table.createdAt,\n ),\n uniqueIndex(\"document_history_updates_update_id_idx\")\n .on(table.updateId)\n .where(sql`${table.updateId} IS NOT NULL`),\n // Queued rows only: pending counts and pending loads skip settled history.\n index(\"document_history_updates_queued_scope_idx\")\n .on(table.appKind, table.localId, table.createdAt)\n .where(sql`${table.updateId} IS NOT NULL`),\n ],\n);\n\nexport const documentTables: ReadonlyArray<SqlTableSchema> = [\n {\n ...defineSqlTableSchema(documents),\n requiredColumns: [\n \"pull_continuation\",\n \"recovery_generation\",\n \"recovery_document_id\",\n \"sync_failure_status\",\n \"sync_failure_message\",\n \"sync_failure_attempted_at\",\n ],\n },\n defineSqlTableSchema(documentHistoryCheckpoints),\n {\n ...defineSqlTableSchema(documentHistoryUpdates),\n requiredColumns: [\"update_id\"],\n },\n];\n"]}
1
+ {"version":3,"file":"documentRecordSchema.js","sourceRoot":"","sources":["documentRecordSchema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EACL,KAAK,EACL,OAAO,EACP,UAAU,EACV,WAAW,EACX,IAAI,EACJ,WAAW,GACZ,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,oBAAoB,EAAuB,MAAM,mBAAmB,CAAC;AAE9E,MAAM,iBAAiB,GAAG,wBAAwB,CAAC;AACnD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuDG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,WAAW,CAClC,WAAW,EACX;IACE,OAAO,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC,OAAO,EAAE;IACnC,OAAO,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC,OAAO,EAAE;IACnC,UAAU,EAAE,IAAI,CAAC,aAAa,CAAC;IAC/B,WAAW,EAAE,OAAO,CAAC,cAAc,CAAC,CAAC,OAAO,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC;IACzD,eAAe,EAAE,IAAI,CAAC,mBAAmB,CAAC;IAC1C,oBAAoB,EAAE,IAAI,CAAC,iBAAiB,CAAC,CAAC,OAAO,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC;IACvE,aAAa,EAAE,IAAI,CAAC,iBAAiB,CAAC;IACtC,sBAAsB,EAAE,IAAI,CAAC,0BAA0B,CAAC;IACxD,gBAAgB,EAAE,IAAI,CAAC,oBAAoB,CAAC;IAC5C,kBAAkB,EAAE,IAAI,CAAC,sBAAsB,CAAC;IAChD,kBAAkB,EAAE,IAAI,CAAC,sBAAsB,CAAC;IAChD,gBAAgB,EAAE,IAAI,CAAC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,EAAE,CAAC;IACnC,KAAK,CAAC,4CAA4C,CAAC,CAAC,EAAE,CACpD,KAAK,CAAC,OAAO,EACb,KAAK,CAAC,OAAO,EACb,KAAK,CAAC,SAAS,CAChB;IACD,WAAW,CAAC,wCAAwC,CAAC;SAClD,EAAE,CAAC,KAAK,CAAC,QAAQ,CAAC;SAClB,KAAK,CAAC,GAAG,CAAA,GAAG,KAAK,CAAC,QAAQ,cAAc,CAAC;IAC5C,2EAA2E;IAC3E,KAAK,CAAC,2CAA2C,CAAC;SAC/C,EAAE,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,SAAS,CAAC;SACjD,KAAK,CAAC,GAAG,CAAA,GAAG,KAAK,CAAC,QAAQ,cAAc,CAAC;CAC7C,CACF,CAAC;AAEF,MAAM,CAAC,MAAM,cAAc,GAAkC;IAC3D;QACE,GAAG,oBAAoB,CAAC,SAAS,CAAC;QAClC,eAAe,EAAE;YACf,mBAAmB;YACnB,qBAAqB;YACrB,sBAAsB;YACtB,qBAAqB;YACrB,sBAAsB;YACtB,2BAA2B;SAC5B;KACF;IACD,oBAAoB,CAAC,0BAA0B,CAAC;IAChD;QACE,GAAG,oBAAoB,CAAC,sBAAsB,CAAC;QAC/C,eAAe,EAAE,CAAC,WAAW,CAAC;KAC/B;CACF,CAAC","sourcesContent":["import { sql } from \"drizzle-orm\";\nimport {\n index,\n integer,\n primaryKey,\n sqliteTable,\n text,\n uniqueIndex,\n} from \"drizzle-orm/sqlite-core\";\nimport { defineSqlTableSchema, type SqlTableSchema } from \"../sqlTableSchema\";\n\nconst accessLevelColumn = \"effective_access_level\";\n/**\n * Durable Loro-backed document records shared by app features.\n *\n * This table stores encrypted document runtime state for multiple app domains.\n * `appKind` namespaces records for documents and container metadata. User-facing\n * list data is projected into feature-specific read models.\n *\n * Columns:\n * - `appKind`: Local domain namespace for the row, such as `documents` or\n * `container-metadata`.\n * - `localId`: Stable local id inside `appKind`. It may be created before a\n * server `documentId` exists.\n * - `documentId`: Server document id once the record is known remotely, or\n * `null` while the document is local-only.\n * - `accessEpoch`: Latest access epoch persisted for the document. Defaults to\n * the initial epoch.\n * - `accessStateHash`: Current document access/manifest state hash returned by\n * sync, when known.\n * - `lastCommitLsn`: Last remote commit cursor applied to this local document.\n * - `documentManifestBundle`: Serialized document manifest bundle used for\n * encrypted document sync.\n * - `contentKeyBundle`: Serialized content-key material needed to open the\n * local document.\n * - `documentKekTargets`: Serialized KEK target state for document key wraps.\n * - `pendingBaseVersion`: Encoded oplog version through which every persisted\n * op is already enqueued or synced. Persisted so a restart restores the\n * outgoing-delta marker instead of re-seeding it past a device-first\n * `deferRemoteSync` write's un-advanced op. `null` when unset.\n * - `snapshotEndVersion`: Encoded end version vector of the persisted content\n * (which lives in the durable-history tables, never on this row), written on\n * every content persist. Lets the pending-write queue's deferred-tail scan\n * compare version coverage without loading content. Empty string when the\n * document has never hydrated content, which readers treat as \"no deferred\n * tail claimable\".\n * - `recoveryGeneration`: Atomic raw-history recovery writer fence.\n * - `recoveryDocumentId`: Former server id for cross-client post-purge recreation.\n * - `pullContinuation`: Durable progress for the next bounded remote pull.\n * - `syncFailureStatus`, `syncFailureMessage`, `syncFailureAttemptedAt`: The\n * last terminal sync failure or quarantined incoming update for this scope.\n * The durable write queue (queued rows of `documentHistoryUpdates`) has no\n * status columns, so these let the write-queue view and footer explain why\n * the document is blocked. `syncFailureMessage` is non-null exactly when a\n * failure is recorded; a newer failure replaces the old, and a later fully\n * validated sync pass, a remote reset, or the scope's teardown clears all\n * three.\n * - `updatedAt`: Local timestamp for the last persisted runtime-state update.\n *\n * Indexes:\n * - `(appKind, localId)` is the primary key and scopes local document lookups.\n * - `(appKind, documentId) where documentId is not null` supports resolving a\n * server document id back to the local row during discovery and relinking.\n * - `(appKind, localId)` over records whose `pendingBaseVersion` differs from\n * a non-empty `snapshotEndVersion` serves the pending-write queue's\n * deferred-tail scan, which repeats that condition, so it reads only\n * unsettled records instead of every synced one.\n */\nexport const documents = sqliteTable(\n \"documents\",\n {\n appKind: text(\"app_kind\").notNull(),\n localId: text(\"local_id\").notNull(),\n documentId: text(\"document_id\"),\n accessEpoch: integer(\"access_epoch\").notNull().default(1),\n accessStateHash: text(\"access_state_hash\"),\n effectiveAccessLevel: text(accessLevelColumn).notNull().default(\"read\"),\n lastCommitLsn: text(\"last_commit_lsn\"),\n documentManifestBundle: text(\"document_manifest_bundle\"),\n contentKeyBundle: text(\"content_key_bundle\"),\n documentKekTargets: text(\"document_kek_targets\"),\n pendingBaseVersion: text(\"pending_base_version\"),\n pullContinuation: text(\"pull_continuation\"),\n recoveryGeneration: integer(\"recovery_generation\").notNull().default(0),\n recoveryDocumentId: text(\"recovery_document_id\"),\n snapshotEndVersion: text(\"snapshot_end_version\").notNull().default(\"\"),\n syncFailureStatus: integer(\"sync_failure_status\"),\n syncFailureMessage: text(\"sync_failure_message\"),\n syncFailureAttemptedAt: text(\"sync_failure_attempted_at\"),\n updatedAt: text(\"updated_at\").notNull(),\n },\n (table) => [\n primaryKey({ columns: [table.appKind, table.localId] }),\n index(\"documents_app_document_idx\")\n .on(table.appKind, table.documentId)\n .where(sql`${table.documentId} IS NOT NULL`),\n index(\"documents_deferred_tail_idx\")\n .on(table.appKind, table.localId)\n .where(\n sql`${table.snapshotEndVersion} <> '' AND ${table.pendingBaseVersion} IS NOT ${table.snapshotEndVersion}`,\n ),\n ],\n);\n\n/**\n * Full-history persistence for local documents (checkpoint + tail) — the ONLY\n * durable content source. Record rows in `documents` carry runtime metadata\n * and the content frontier (`snapshotEndVersion`), never content. The\n * checkpoint holds a full-history snapshot refreshed only at compaction, and\n * the tail appends every update (local deltas and decrypted remote updates)\n * written since. Restore = import checkpoint + replay tail; compaction =\n * export full history from the live doc, replace the checkpoint, clear the\n * tail — all bounded and amortized. Container metadata stores its content (an\n * exported-updates blob) as its checkpoint row, with no tail.\n */\nexport const documentHistoryCheckpoints = sqliteTable(\n \"document_history_checkpoints\",\n {\n appKind: text(\"app_kind\").notNull(),\n localId: text(\"local_id\").notNull(),\n snapshot: text(\"snapshot\").notNull(),\n endVersionVector: text(\"end_version_vector\").notNull(),\n revision: text(\"revision\").notNull(),\n updatedAt: text(\"updated_at\").notNull(),\n },\n (table) => [primaryKey({ columns: [table.appKind, table.localId] })],\n);\n\n/**\n * The local update log: one row per Loro update, serving as both the history\n * tail (restore = checkpoint + tail) and the outbound write queue.\n *\n * Every locally authored update is stored once. While it waits for sync it\n * carries an `updateId` (the id submitted to the server) and the version-vector\n * metadata the submission needs; settlement clears them, leaving the row as\n * ordinary tail history until compaction folds it into a checkpoint. Before a\n * send, a contiguous run of queued local rows may be replaced by one merged\n * row holding exactly their operations: the first row is updated in place\n * (same `id`, `createdAt` and `rowid`, so the same queue and replay position)\n * under a fresh `updateId`, and the other rows are deleted.\n *\n * Columns:\n * - `id`: Row id; tail compaction deletes by it.\n * - `appKind`, `localId`: Document scope matching `documents`.\n * - `updateData`: Serialized Loro update payload.\n * - `origin`: \"local\" (authored on this device) or \"remote\" (decrypted\n * pulled update) for tail rows. Restores use it to advance the\n * outgoing-delta marker across remote rows — their ops are already\n * server-side — while a local row left behind by a crash stays below the\n * marker so the next edit re-derives and sends it. \"outbox\" marks a queued\n * update with no tail role (container metadata, whose content is its\n * checkpoint, and full-state re-uploads after a remote reset); restores and\n * compaction never see it and settlement deletes it.\n * - `createdAt`: Insertion timestamp; with `rowid`, deterministic replay order.\n * - `updateId`: Present exactly while the row is queued for sync; rekeyed\n * after a lost acknowledgement poisons the submitted id, and replaced by a\n * fresh id when queued rows merge. An id never names two payloads.\n * - `partialStartVersionVector` / `partialEndVersionVector`: Version vectors\n * around a queued partial update.\n * - `sourceVersionVector`: Present on a queued rotation baseline checkpoint.\n * - `rekeyCount`: Durable bound on rekeys of a queued row; a merged row takes\n * the largest count among the rows it replaces.\n *\n * Invariant: compaction never deletes a queued row, so a checkpoint can cover\n * a queued update's operations without removing it from the queue.\n */\nexport const documentHistoryUpdates = sqliteTable(\n \"document_history_updates\",\n {\n id: text(\"id\"),\n appKind: text(\"app_kind\").notNull(),\n localId: text(\"local_id\").notNull(),\n updateData: text(\"update_data\").notNull(),\n origin: text(\"origin\").notNull(),\n createdAt: text(\"created_at\").notNull(),\n updateId: text(\"update_id\"),\n partialStartVersionVector: text(\"partial_start_version_vector\"),\n partialEndVersionVector: text(\"partial_end_version_vector\"),\n sourceVersionVector: text(\"source_version_vector\"),\n rekeyCount: integer(\"rekey_count\").notNull().default(0),\n },\n (table) => [\n primaryKey({ columns: [table.id] }),\n index(\"document_history_updates_scope_created_idx\").on(\n table.appKind,\n table.localId,\n table.createdAt,\n ),\n uniqueIndex(\"document_history_updates_update_id_idx\")\n .on(table.updateId)\n .where(sql`${table.updateId} IS NOT NULL`),\n // Queued rows only: pending counts and pending loads skip settled history.\n index(\"document_history_updates_queued_scope_idx\")\n .on(table.appKind, table.localId, table.createdAt)\n .where(sql`${table.updateId} IS NOT NULL`),\n ],\n);\n\nexport const documentTables: ReadonlyArray<SqlTableSchema> = [\n {\n ...defineSqlTableSchema(documents),\n requiredColumns: [\n \"pull_continuation\",\n \"recovery_generation\",\n \"recovery_document_id\",\n \"sync_failure_status\",\n \"sync_failure_message\",\n \"sync_failure_attempted_at\",\n ],\n },\n defineSqlTableSchema(documentHistoryCheckpoints),\n {\n ...defineSqlTableSchema(documentHistoryUpdates),\n requiredColumns: [\"update_id\"],\n },\n];\n"]}
@@ -12,51 +12,6 @@ export declare const localIntentTables: ReadonlyArray<SqlTableSchema>;
12
12
  export declare const documentPlacementIntentTables: ReadonlyArray<SqlTableSchema>;
13
13
  export declare const clientSqlTables: ReadonlyArray<SqlTableSchema>;
14
14
  export declare const clientSQLiteSchema: {
15
- organizationSyncPauseRemovals: import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
16
- name: "organization_sync_pause_removals";
17
- schema: undefined;
18
- columns: {
19
- localId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
20
- name: "local_id";
21
- tableName: "organization_sync_pause_removals";
22
- dataType: "string";
23
- columnType: "SQLiteText";
24
- data: string;
25
- driverParam: string;
26
- notNull: true;
27
- hasDefault: false;
28
- isPrimaryKey: true;
29
- isAutoincrement: false;
30
- hasRuntimeDefault: false;
31
- enumValues: [string, ...string[]];
32
- baseColumn: never;
33
- identity: undefined;
34
- generated: undefined;
35
- }, {}, {
36
- length: number | undefined;
37
- }>;
38
- organizationId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
39
- name: "organization_id";
40
- tableName: "organization_sync_pause_removals";
41
- dataType: "string";
42
- columnType: "SQLiteText";
43
- data: string;
44
- driverParam: string;
45
- notNull: true;
46
- hasDefault: false;
47
- isPrimaryKey: false;
48
- isAutoincrement: false;
49
- hasRuntimeDefault: false;
50
- enumValues: [string, ...string[]];
51
- baseColumn: never;
52
- identity: undefined;
53
- generated: undefined;
54
- }, {}, {
55
- length: number | undefined;
56
- }>;
57
- };
58
- dialect: "sqlite";
59
- }>;
60
15
  organizationSyncPauses: import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
61
16
  name: "organization_sync_pauses";
62
17
  schema: undefined;
@@ -1,32 +1,21 @@
1
1
  import { sqliteTable, text } from "drizzle-orm/sqlite-core";
2
2
  import { defineSqlTableSchema } from "../sqlTableSchema.js";
3
3
  /**
4
- * Organizations whose content this user has paused syncing to their devices.
4
+ * Organizations whose content sync this user has paused on this device.
5
5
  *
6
- * A device-local copy of the user's own choice, which the server keeps on their
7
- * roster entry and sends with their membership list, so a device that starts
8
- * offline still honors it. It is never an access or keying input: a paused
9
- * organization keeps its grants and keys, and only its metadata root stays on
10
- * the device.
6
+ * The device's own record of the user's choice, which the server also keeps on
7
+ * their roster entry and sends with their membership list, so a device that
8
+ * starts offline still honors it. It is never an access or keying input: a
9
+ * paused organization keeps its grants, keys, and local copy; the device only
10
+ * stops sending and fetching its content until the user resumes.
11
11
  */
12
12
  export const organizationSyncPauses = sqliteTable("organization_sync_pauses", {
13
13
  organizationId: text("organization_id").primaryKey(),
14
14
  });
15
- /**
16
- * Documents a pause's cleanup removed from this device, kept while their
17
- * organization stays paused so reopening one, even after a restart, does not
18
- * recreate it locally. Resuming the organization drops its rows.
19
- */
20
- export const organizationSyncPauseRemovals = sqliteTable("organization_sync_pause_removals", {
21
- localId: text("local_id").primaryKey(),
22
- organizationId: text("organization_id").notNull(),
23
- });
24
15
  export const organizationSyncPauseTables = [
25
16
  defineSqlTableSchema(organizationSyncPauses),
26
- defineSqlTableSchema(organizationSyncPauseRemovals),
27
17
  ];
28
18
  export const organizationSyncPauseSQLiteSchema = {
29
- organizationSyncPauseRemovals,
30
19
  organizationSyncPauses,
31
20
  };
32
21
  //# sourceMappingURL=organizationSyncPauseSchema.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"organizationSyncPauseSchema.js","sourceRoot":"","sources":["organizationSyncPauseSchema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EAAE,oBAAoB,EAAuB,MAAM,mBAAmB,CAAC;AAE9E;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG,WAAW,CAAC,0BAA0B,EAAE;IAC5E,cAAc,EAAE,IAAI,CAAC,iBAAiB,CAAC,CAAC,UAAU,EAAE;CACrD,CAAC,CAAC;AAEH;;;;GAIG;AACH,MAAM,CAAC,MAAM,6BAA6B,GAAG,WAAW,CACtD,kCAAkC,EAClC;IACE,OAAO,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC,UAAU,EAAE;IACtC,cAAc,EAAE,IAAI,CAAC,iBAAiB,CAAC,CAAC,OAAO,EAAE;CAClD,CACF,CAAC;AAEF,MAAM,CAAC,MAAM,2BAA2B,GAAkC;IACxE,oBAAoB,CAAC,sBAAsB,CAAC;IAC5C,oBAAoB,CAAC,6BAA6B,CAAC;CACpD,CAAC;AAEF,MAAM,CAAC,MAAM,iCAAiC,GAAG;IAC/C,6BAA6B;IAC7B,sBAAsB;CACvB,CAAC","sourcesContent":["import { sqliteTable, text } from \"drizzle-orm/sqlite-core\";\nimport { defineSqlTableSchema, type SqlTableSchema } from \"../sqlTableSchema\";\n\n/**\n * Organizations whose content this user has paused syncing to their devices.\n *\n * A device-local copy of the user's own choice, which the server keeps on their\n * roster entry and sends with their membership list, so a device that starts\n * offline still honors it. It is never an access or keying input: a paused\n * organization keeps its grants and keys, and only its metadata root stays on\n * the device.\n */\nexport const organizationSyncPauses = sqliteTable(\"organization_sync_pauses\", {\n organizationId: text(\"organization_id\").primaryKey(),\n});\n\n/**\n * Documents a pause's cleanup removed from this device, kept while their\n * organization stays paused so reopening one, even after a restart, does not\n * recreate it locally. Resuming the organization drops its rows.\n */\nexport const organizationSyncPauseRemovals = sqliteTable(\n \"organization_sync_pause_removals\",\n {\n localId: text(\"local_id\").primaryKey(),\n organizationId: text(\"organization_id\").notNull(),\n },\n);\n\nexport const organizationSyncPauseTables: ReadonlyArray<SqlTableSchema> = [\n defineSqlTableSchema(organizationSyncPauses),\n defineSqlTableSchema(organizationSyncPauseRemovals),\n];\n\nexport const organizationSyncPauseSQLiteSchema = {\n organizationSyncPauseRemovals,\n organizationSyncPauses,\n};\n"]}
1
+ {"version":3,"file":"organizationSyncPauseSchema.js","sourceRoot":"","sources":["organizationSyncPauseSchema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EAAE,oBAAoB,EAAuB,MAAM,mBAAmB,CAAC;AAE9E;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG,WAAW,CAAC,0BAA0B,EAAE;IAC5E,cAAc,EAAE,IAAI,CAAC,iBAAiB,CAAC,CAAC,UAAU,EAAE;CACrD,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,2BAA2B,GAAkC;IACxE,oBAAoB,CAAC,sBAAsB,CAAC;CAC7C,CAAC;AAEF,MAAM,CAAC,MAAM,iCAAiC,GAAG;IAC/C,sBAAsB;CACvB,CAAC","sourcesContent":["import { sqliteTable, text } from \"drizzle-orm/sqlite-core\";\nimport { defineSqlTableSchema, type SqlTableSchema } from \"../sqlTableSchema\";\n\n/**\n * Organizations whose content sync this user has paused on this device.\n *\n * The device's own record of the user's choice, which the server also keeps on\n * their roster entry and sends with their membership list, so a device that\n * starts offline still honors it. It is never an access or keying input: a\n * paused organization keeps its grants, keys, and local copy; the device only\n * stops sending and fetching its content until the user resumes.\n */\nexport const organizationSyncPauses = sqliteTable(\"organization_sync_pauses\", {\n organizationId: text(\"organization_id\").primaryKey(),\n});\n\nexport const organizationSyncPauseTables: ReadonlyArray<SqlTableSchema> = [\n defineSqlTableSchema(organizationSyncPauses),\n];\n\nexport const organizationSyncPauseSQLiteSchema = {\n organizationSyncPauses,\n};\n"]}
@@ -0,0 +1,29 @@
1
+ export const UNREAD_ORGANIZATION_SYNC_PAUSES = {
2
+ status: "unread",
3
+ };
4
+ /** Whether the pauses in memory may be stale because a read failed. */
5
+ export function organizationSyncPausesUnreadable(state) {
6
+ return (state.status === "failed" ||
7
+ (state.status === "reading" && state.afterFailure));
8
+ }
9
+ export function transitionOrganizationSyncPauseRead(state, event) {
10
+ switch (event.type) {
11
+ case "start":
12
+ // A read in flight or settled is shared, never restarted.
13
+ return state.status === "unread" || state.status === "failed"
14
+ ? {
15
+ afterFailure: state.status === "failed",
16
+ read: event.read,
17
+ status: "reading",
18
+ }
19
+ : state;
20
+ case "succeed":
21
+ return state.status === "reading"
22
+ ? { read: state.read, status: "read" }
23
+ : state;
24
+ case "fail":
25
+ // Dropping the read lets a later call retry it.
26
+ return state.status === "reading" ? { status: "failed" } : state;
27
+ }
28
+ }
29
+ //# sourceMappingURL=organizationSyncPauseReadMachine.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"organizationSyncPauseReadMachine.js","sourceRoot":"","sources":["organizationSyncPauseReadMachine.ts"],"names":[],"mappings":"AAuBA,MAAM,CAAC,MAAM,+BAA+B,GAA8B;IACxE,MAAM,EAAE,QAAQ;CACjB,CAAC;AAEF,uEAAuE;AACvE,MAAM,UAAU,gCAAgC,CAC9C,KAAgC;IAEhC,OAAO,CACL,KAAK,CAAC,MAAM,KAAK,QAAQ;QACzB,CAAC,KAAK,CAAC,MAAM,KAAK,SAAS,IAAI,KAAK,CAAC,YAAY,CAAC,CACnD,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,mCAAmC,CACjD,KAAgC,EAChC,KAAqC;IAErC,QAAQ,KAAK,CAAC,IAAI,EAAE,CAAC;QACnB,KAAK,OAAO;YACV,0DAA0D;YAC1D,OAAO,KAAK,CAAC,MAAM,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,KAAK,QAAQ;gBAC3D,CAAC,CAAC;oBACE,YAAY,EAAE,KAAK,CAAC,MAAM,KAAK,QAAQ;oBACvC,IAAI,EAAE,KAAK,CAAC,IAAI;oBAChB,MAAM,EAAE,SAAS;iBAClB;gBACH,CAAC,CAAC,KAAK,CAAC;QACZ,KAAK,SAAS;YACZ,OAAO,KAAK,CAAC,MAAM,KAAK,SAAS;gBAC/B,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE;gBACtC,CAAC,CAAC,KAAK,CAAC;QACZ,KAAK,MAAM;YACT,gDAAgD;YAChD,OAAO,KAAK,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC;IACrE,CAAC;AACH,CAAC","sourcesContent":["/**\n * The read of a scope's persisted organization sync pauses. The sync lanes\n * read the pauses from memory, so whether memory reflects storage decides\n * whether they may sync at all: a device that failed to read its pauses\n * cannot tell which organizations to hold, and holds them all until a read\n * succeeds. `read` carries the settled read so later callers share it.\n */\nexport type OrganizationSyncPauseRead =\n | { readonly status: \"unread\" }\n | {\n readonly status: \"reading\";\n readonly read: Promise<void>;\n /** The read before this one failed, so sync is still held. */\n readonly afterFailure: boolean;\n }\n | { readonly status: \"read\"; readonly read: Promise<void> }\n | { readonly status: \"failed\" };\n\nexport type OrganizationSyncPauseReadEvent =\n | { readonly type: \"start\"; readonly read: Promise<void> }\n | { readonly type: \"succeed\" }\n | { readonly type: \"fail\" };\n\nexport const UNREAD_ORGANIZATION_SYNC_PAUSES: OrganizationSyncPauseRead = {\n status: \"unread\",\n};\n\n/** Whether the pauses in memory may be stale because a read failed. */\nexport function organizationSyncPausesUnreadable(\n state: OrganizationSyncPauseRead,\n): boolean {\n return (\n state.status === \"failed\" ||\n (state.status === \"reading\" && state.afterFailure)\n );\n}\n\nexport function transitionOrganizationSyncPauseRead(\n state: OrganizationSyncPauseRead,\n event: OrganizationSyncPauseReadEvent,\n): OrganizationSyncPauseRead {\n switch (event.type) {\n case \"start\":\n // A read in flight or settled is shared, never restarted.\n return state.status === \"unread\" || state.status === \"failed\"\n ? {\n afterFailure: state.status === \"failed\",\n read: event.read,\n status: \"reading\",\n }\n : state;\n case \"succeed\":\n return state.status === \"reading\"\n ? { read: state.read, status: \"read\" }\n : state;\n case \"fail\":\n // Dropping the read lets a later call retry it.\n return state.status === \"reading\" ? { status: \"failed\" } : state;\n }\n}\n"]}
@@ -6,34 +6,32 @@ export interface OrganizationSyncPauseSubject {
6
6
  readonly parentId: string | null;
7
7
  readonly systemSlot?: string | null | undefined;
8
8
  }
9
- /**
10
- * Whether a container stays on the device while its organization is paused:
11
- * only the organization's parentless system root, the metadata root every
12
- * Members recipient reads, which keeps the organization named and its
13
- * membership visible.
14
- */
15
- export declare function isRetainedWhileSyncPaused(container: OrganizationSyncPauseSubject): boolean;
16
9
  export interface OrganizationSyncPauseChange {
17
10
  readonly paused: readonly string[];
18
11
  readonly resumed: readonly string[];
19
12
  }
20
13
  /**
21
- * Which organizations this user paused syncing to their devices, for one
22
- * domain scope. Sync reads it synchronously once `load` has settled; the
23
- * persisted set lets a device that starts offline keep honoring a pause.
14
+ * Which organizations this user paused syncing on this device, for one domain
15
+ * scope. Sync reads it synchronously once `load` has settled; the persisted
16
+ * set lets a device that starts offline keep honoring a pause.
24
17
  */
25
18
  export interface OrganizationSyncPauses {
26
19
  /** Loads the persisted set once; concurrent and later calls share it. */
27
20
  load(execSql: ExecSql): Promise<void>;
28
21
  isOrganizationPaused(organizationId: string): boolean;
22
+ /**
23
+ * Whether the organization's uploads and document pulls are held: it is
24
+ * paused, or the last read of the persisted set failed. A device that
25
+ * cannot read its pauses cannot tell which organizations to hold, so it
26
+ * holds them all, leaving local edits queued, until a read succeeds.
27
+ */
28
+ holdsSync(organizationId: string): boolean;
29
29
  /**
30
30
  * Whether sync skips this container: every container of a paused
31
- * organization except the one `isRetainedWhileSyncPaused` keeps. The
32
- * session's active organization is never skipped, even when paused from
33
- * another device: its root is the session's workspace until it switches
34
- * away.
31
+ * organization except its metadata root. The session's active organization
32
+ * is held like any other; its content is already on the device.
35
33
  */
36
- isContainerPaused(container: OrganizationSyncPauseSubject, activeOrganizationId: string | null): boolean;
34
+ isContainerPaused(container: OrganizationSyncPauseSubject): boolean;
37
35
  pausedOrganizationIds(): ReadonlySet<string>;
38
36
  /** Persists exactly this set and reports which organizations changed. */
39
37
  replace(execSql: ExecSql, organizationIds: Iterable<string>): Promise<OrganizationSyncPauseChange>;
@@ -46,25 +44,16 @@ export interface OrganizationSyncPauses {
46
44
  runExclusive<T>(task: () => Promise<T>): Promise<T>;
47
45
  }
48
46
  /**
49
- * Persistence for organization sync pauses and the documents a pause's
50
- * cleanup removed, bound to one executor.
47
+ * Loads the scope's paused organizations before a store starts syncing, since
48
+ * its sync lanes read them synchronously. A failed read is reported and never
49
+ * keeps the store from starting: the store opens and takes local edits, and
50
+ * every organization's sync stays held (see `holdsSync`) until a later read,
51
+ * such as the one hydration and discovery make before they fetch, succeeds.
51
52
  */
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
- }
53
+ export declare function loadOrganizationSyncPausesBeforeSync(input: {
54
+ readonly domainScope: DomainScope;
55
+ readonly execSql: ExecSql;
56
+ readonly log: (message: string) => void;
57
+ }): Promise<void>;
69
58
  /** The one pause set for a domain scope; a new scope starts unloaded. */
70
59
  export declare function getOrCreateOrganizationSyncPauses(domainScope: DomainScope): OrganizationSyncPauses;
@@ -1,22 +1,21 @@
1
- import { eq, notInArray } from "drizzle-orm";
2
- import { organizationSyncPauseRemovals, organizationSyncPauses, organizationSyncPauseTables, } from "../sqlite/schema/organizationSyncPauseSchema.js";
1
+ import { organizationSyncPauses, organizationSyncPauseTables, } from "../sqlite/schema/organizationSyncPauseSchema.js";
3
2
  import { sqliteInsertBatchSize } from "../sqlite/sqliteBindBudget.js";
4
3
  import { getClientSQLitePersistenceRuntime } from "../sqlite/sqlitePersistenceRuntime.js";
5
4
  import { ensureSqlTables, runSerializedSqlMutation, } from "../sqlite/sqlSchema.js";
5
+ import { organizationSyncPausesUnreadable, transitionOrganizationSyncPauseRead, UNREAD_ORGANIZATION_SYNC_PAUSES, } from "./organizationSyncPauseReadMachine.js";
6
+ import { requestAllDomainSyncLanes } from "./syncCoordinator.js";
6
7
  /**
7
- * Whether a container stays on the device while its organization is paused:
8
- * only the organization's parentless system root, the metadata root every
9
- * Members recipient reads, which keeps the organization named and its
10
- * membership visible.
8
+ * Whether a container keeps listing while its organization is paused: only
9
+ * the organization's parentless system root, the metadata root every Members
10
+ * recipient reads, so a device that has never synced the organization still
11
+ * lists it and can resume it. Its documents are held like any other once
12
+ * pulled.
11
13
  */
12
- export function isRetainedWhileSyncPaused(container) {
14
+ function syncsWhileOrganizationPaused(container) {
13
15
  return container.parentId === null && Boolean(container.systemSlot);
14
16
  }
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 {
17
+ /** Persistence for organization sync pauses, bound to one executor. */
18
+ class OrganizationSyncPauseRepository {
20
19
  execSql;
21
20
  constructor(execSql) {
22
21
  this.execSql = execSql;
@@ -46,48 +45,13 @@ export class OrganizationSyncPauseRepository {
46
45
  .map((organizationId) => ({ organizationId })))
47
46
  .run();
48
47
  }
49
- // A resumed organization's removed documents may be reopened again.
50
- await tx
51
- .delete(organizationSyncPauseRemovals)
52
- .where(notInArray(organizationSyncPauseRemovals.organizationId, tx
53
- .select({
54
- organizationId: organizationSyncPauses.organizationId,
55
- })
56
- .from(organizationSyncPauses)))
57
- .run();
58
48
  });
59
49
  });
60
50
  }
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
- }
87
51
  }
88
- function createOrganizationSyncPauses() {
52
+ function createOrganizationSyncPauses(domainScope) {
89
53
  let paused = new Set();
90
- let loading = null;
54
+ let read = UNREAD_ORGANIZATION_SYNC_PAUSES;
91
55
  let replacing = Promise.resolve();
92
56
  let exclusive = Promise.resolve();
93
57
  const listeners = new Set();
@@ -97,23 +61,36 @@ function createOrganizationSyncPauses() {
97
61
  };
98
62
  const pauses = {
99
63
  load(execSql) {
100
- loading ??= new OrganizationSyncPauseRepository(execSql)
64
+ if (read.status === "reading" || read.status === "read")
65
+ return read.read;
66
+ const reading = new OrganizationSyncPauseRepository(execSql)
101
67
  .readPausedOrganizationIds()
102
68
  .then((stored) => {
103
69
  paused = stored;
70
+ const recovered = organizationSyncPausesUnreadable(read);
71
+ read = transitionOrganizationSyncPauseRead(read, {
72
+ type: "succeed",
73
+ });
74
+ // Writes held while the set could not be read left their lanes
75
+ // idle, so every lane is re-driven.
76
+ if (recovered)
77
+ requestAllDomainSyncLanes(domainScope);
104
78
  if (stored.size > 0)
105
79
  notify();
106
80
  }, (error) => {
107
- // Let a later call retry a failed read.
108
- loading = null;
81
+ read = transitionOrganizationSyncPauseRead(read, { type: "fail" });
109
82
  throw error;
110
83
  });
111
- return loading;
84
+ read = transitionOrganizationSyncPauseRead(read, {
85
+ read: reading,
86
+ type: "start",
87
+ });
88
+ return reading;
112
89
  },
113
90
  isOrganizationPaused: (organizationId) => paused.has(organizationId),
114
- isContainerPaused: (container, activeOrganizationId) => paused.has(container.organizationId) &&
115
- container.organizationId !== activeOrganizationId &&
116
- !isRetainedWhileSyncPaused(container),
91
+ holdsSync: (organizationId) => organizationSyncPausesUnreadable(read) || paused.has(organizationId),
92
+ isContainerPaused: (container) => paused.has(container.organizationId) &&
93
+ !syncsWhileOrganizationPaused(container),
117
94
  pausedOrganizationIds: () => paused,
118
95
  replace(execSql, organizationIds) {
119
96
  const next = new Set(organizationIds);
@@ -151,11 +128,26 @@ function createOrganizationSyncPauses() {
151
128
  return pauses;
152
129
  }
153
130
  const pausesByScope = new WeakMap();
131
+ /**
132
+ * Loads the scope's paused organizations before a store starts syncing, since
133
+ * its sync lanes read them synchronously. A failed read is reported and never
134
+ * keeps the store from starting: the store opens and takes local edits, and
135
+ * every organization's sync stays held (see `holdsSync`) until a later read,
136
+ * such as the one hydration and discovery make before they fetch, succeeds.
137
+ */
138
+ export async function loadOrganizationSyncPausesBeforeSync(input) {
139
+ try {
140
+ await getOrCreateOrganizationSyncPauses(input.domainScope).load(input.execSql);
141
+ }
142
+ catch {
143
+ input.log("Sync: could not read the organization sync pauses");
144
+ }
145
+ }
154
146
  /** The one pause set for a domain scope; a new scope starts unloaded. */
155
147
  export function getOrCreateOrganizationSyncPauses(domainScope) {
156
148
  let pauses = pausesByScope.get(domainScope);
157
149
  if (!pauses) {
158
- pauses = createOrganizationSyncPauses();
150
+ pauses = createOrganizationSyncPauses(domainScope);
159
151
  pausesByScope.set(domainScope, pauses);
160
152
  }
161
153
  return pauses;
@@ -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;;;GAGG;AACH,MAAM,OAAO,+BAA+B;IACzB,O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QAAQ,CAAC,CAAC;YAC7B,CAAC,CAAC;QACJ,CAAC;QACD,YAAY,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"]}
1
+ {"version":3,"file":"organizationSyncPauses.js","sourceRoot":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B,OAAO,GAAG,EAAE;gBACV,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;YAC7B,CAAC,CAAC;QACJ,CAAC;QACD,YAAY,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;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,oCAAoC,CAAC,KAI1D;IACC,IAAI,CAAC;QACH,MAAM,iCAAiC,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,IAAI,CAC7D,KAAK,CAAC,OAAO,CACd,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,KAAK,CAAC,GAAG,CAAC,mDAAmD,CAAC,CAAC;IACjE,CAAC;AACH,CAAC;AAED,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,CAAC,WAAW,CAAC,CAAC;QACnD,aAAa,CAAC,GAAG,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC;IACzC,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import type { DomainScope } from \"../shared/domainScope\";\nimport {\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\";\nimport {\n organizationSyncPausesUnreadable,\n transitionOrganizationSyncPauseRead,\n UNREAD_ORGANIZATION_SYNC_PAUSES,\n} from \"./organizationSyncPauseReadMachine\";\nimport { requestAllDomainSyncLanes } from \"./syncCoordinator\";\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 keeps listing while its organization is paused: only\n * the organization's parentless system root, the metadata root every Members\n * recipient reads, so a device that has never synced the organization still\n * lists it and can resume it. Its documents are held like any other once\n * pulled.\n */\nfunction syncsWhileOrganizationPaused(\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 on this device, for one domain\n * scope. Sync reads it synchronously once `load` has settled; the persisted\n * 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 the organization's uploads and document pulls are held: it is\n * paused, or the last read of the persisted set failed. A device that\n * cannot read its pauses cannot tell which organizations to hold, so it\n * holds them all, leaving local edits queued, until a read succeeds.\n */\n holdsSync(organizationId: string): boolean;\n /**\n * Whether sync skips this container: every container of a paused\n * organization except its metadata root. The session's active organization\n * is held like any other; its content is already on the device.\n */\n isContainerPaused(container: OrganizationSyncPauseSubject): 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/** Persistence for organization sync pauses, bound to one executor. */\nclass 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 },\n );\n });\n }\n}\n\nfunction createOrganizationSyncPauses(\n domainScope: DomainScope,\n): OrganizationSyncPauses {\n let paused: ReadonlySet<string> = new Set();\n let read = UNREAD_ORGANIZATION_SYNC_PAUSES;\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 if (read.status === \"reading\" || read.status === \"read\") return read.read;\n const reading = new OrganizationSyncPauseRepository(execSql)\n .readPausedOrganizationIds()\n .then(\n (stored) => {\n paused = stored;\n const recovered = organizationSyncPausesUnreadable(read);\n read = transitionOrganizationSyncPauseRead(read, {\n type: \"succeed\",\n });\n // Writes held while the set could not be read left their lanes\n // idle, so every lane is re-driven.\n if (recovered) requestAllDomainSyncLanes(domainScope);\n if (stored.size > 0) notify();\n },\n (error: unknown) => {\n read = transitionOrganizationSyncPauseRead(read, { type: \"fail\" });\n throw error;\n },\n );\n read = transitionOrganizationSyncPauseRead(read, {\n read: reading,\n type: \"start\",\n });\n return reading;\n },\n isOrganizationPaused: (organizationId) => paused.has(organizationId),\n holdsSync: (organizationId) =>\n organizationSyncPausesUnreadable(read) || paused.has(organizationId),\n isContainerPaused: (container) =>\n paused.has(container.organizationId) &&\n !syncsWhileOrganizationPaused(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/**\n * Loads the scope's paused organizations before a store starts syncing, since\n * its sync lanes read them synchronously. A failed read is reported and never\n * keeps the store from starting: the store opens and takes local edits, and\n * every organization's sync stays held (see `holdsSync`) until a later read,\n * such as the one hydration and discovery make before they fetch, succeeds.\n */\nexport async function loadOrganizationSyncPausesBeforeSync(input: {\n readonly domainScope: DomainScope;\n readonly execSql: ExecSql;\n readonly log: (message: string) => void;\n}): Promise<void> {\n try {\n await getOrCreateOrganizationSyncPauses(input.domainScope).load(\n input.execSql,\n );\n } catch {\n input.log(\"Sync: could not read the organization sync pauses\");\n }\n}\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(domainScope);\n pausesByScope.set(domainScope, pauses);\n }\n return pauses;\n}\n"]}
@@ -141,15 +141,6 @@ export declare const updateOrganizationMembershipOperation: Omit<{
141
141
  }, {
142
142
  error: string;
143
143
  }>>;
144
- readonly 409: z.ZodType<{
145
- error: string;
146
- }, {
147
- error: string;
148
- }, z.core.$ZodTypeInternals<{
149
- error: string;
150
- }, {
151
- error: string;
152
- }>>;
153
144
  readonly 500: z.ZodType<{
154
145
  error: string;
155
146
  }, {
@@ -160,10 +151,10 @@ export declare const updateOrganizationMembershipOperation: Omit<{
160
151
  error: string;
161
152
  }>>;
162
153
  };
163
- readonly failureStatuses: readonly [400, 401, 404, 409, 500];
154
+ readonly failureStatuses: readonly [400, 401, 404, 500];
164
155
  readonly id: "organizationMemberships.update";
165
156
  readonly summary: "Update an organization membership";
166
- readonly description: "Changes the caller's own membership settings in an organization, such as pausing its sync to their devices. Pausing changes no grant, key, or policy. Returns 404 unless the caller's roster entry is active.";
157
+ readonly description: "Changes the caller's own membership settings in an organization, such as pausing its sync. A pause holds the organization's uploads and downloads on the caller's devices and changes no grant, key, or policy; any organization can be paused, the caller's personal one included. Returns 404 unless the caller's roster entry is active.";
167
158
  readonly method: "PUT";
168
159
  readonly params: z.ZodObject<{
169
160
  organizationId: z.ZodCustom<string, string>;
@@ -225,15 +216,6 @@ export declare const updateOrganizationMembershipOperation: Omit<{
225
216
  }, {
226
217
  error: string;
227
218
  }>>;
228
- readonly 409: z.ZodType<{
229
- error: string;
230
- }, {
231
- error: string;
232
- }, z.core.$ZodTypeInternals<{
233
- error: string;
234
- }, {
235
- error: string;
236
- }>>;
237
219
  readonly 500: z.ZodType<{
238
220
  error: string;
239
221
  }, {
@@ -246,7 +228,7 @@ export declare const updateOrganizationMembershipOperation: Omit<{
246
228
  } & {
247
229
  readonly 503: typeof ErrorResponseSchema;
248
230
  };
249
- readonly failureStatuses: readonly [400, 401, 404, 409, 500] | readonly [400, 401, 404, 409, 500, 503];
231
+ readonly failureStatuses: readonly [400, 401, 404, 500] | readonly [400, 401, 404, 500, 503];
250
232
  };
251
233
  /**
252
234
  * Files the session user's signed request to leave one organization. It is a
@@ -36,13 +36,12 @@ export const updateOrganizationMembershipOperation = defineJsonOperation({
36
36
  400: ErrorResponseSchema,
37
37
  401: SessionFailureResponseSchema,
38
38
  404: ErrorResponseSchema,
39
- 409: ErrorResponseSchema,
40
39
  500: ErrorResponseSchema,
41
40
  },
42
- failureStatuses: [400, 401, 404, 409, 500],
41
+ failureStatuses: [400, 401, 404, 500],
43
42
  id: "organizationMemberships.update",
44
43
  summary: "Update an organization membership",
45
- description: "Changes the caller's own membership settings in an organization, such as pausing its sync to their devices. Pausing changes no grant, key, or policy. Returns 404 unless the caller's roster entry is active.",
44
+ description: "Changes the caller's own membership settings in an organization, such as pausing its sync. A pause holds the organization's uploads and downloads on the caller's devices and changes no grant, key, or policy; any organization can be paused, the caller's personal one included. Returns 404 unless the caller's roster entry is active.",
46
45
  method: "PUT",
47
46
  params: OrganizationMembershipPathParamsSchema,
48
47
  path: "/organization-memberships/{organizationId}",