@bastani/atomic 0.10.11-alpha.2 → 0.10.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +307 -0
- package/README.md +5 -8
- package/dist/_shared/dist-KOELCESV.js +2 -2
- package/dist/_shared/fork-row-index-UAUAQRD5.js +2 -2
- package/dist/_shared/lib-4PES5P4V.js +2 -2
- package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js +6 -6
- package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +5 -5
- package/dist/_shared/mode-shared-2QJSCUM6.js +6 -6
- package/dist/_shared/p0-cli-BB45ZQY6.js +46 -67
- package/dist/_shared/p0-cli-BB45ZQY6.js.map +1 -1
- package/dist/_shared/p1a-prewarm-XIU57JHF.js +7 -8
- package/dist/_shared/p1a-prewarm-XIU57JHF.js.map +1 -1
- package/dist/_shared/{p1b-elig-ENCUPKKJ.js → p1b-elig-TVB5CBLL.js} +36 -8
- package/dist/_shared/p1b-elig-TVB5CBLL.js.map +1 -0
- package/dist/_shared/p2-shell-main-B2WIALFD.js +6 -3
- package/dist/_shared/p2-shell-main-B2WIALFD.js.map +1 -1
- package/dist/_shared/runtime-O4KCSG4C.js +3 -3
- package/dist/_shared/{sdk-IQMULKFU.js → sdk-B5LEWGGI.js} +1218 -657
- package/dist/_shared/sdk-B5LEWGGI.js.map +1 -0
- package/dist/_shared/session-data-AHTU7IS6.js +2 -2
- package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
- package/dist/_shared/{startup-0-0-3IXNMFM2.js → startup-0-0-XJJDOIEC.js} +50 -48
- package/dist/_shared/startup-0-0-XJJDOIEC.js.map +1 -0
- package/dist/_shared/{startup-0-1-7T2IAE7J.js → startup-0-1-M6OWAYHH.js} +540 -136
- package/dist/_shared/startup-0-1-M6OWAYHH.js.map +1 -0
- package/dist/_shared/startup-0-2-5QHPCEON.js +47 -48
- package/dist/_shared/startup-0-2-5QHPCEON.js.map +1 -1
- package/dist/_shared/startup-0-3-4ZYBYQNM.js +5 -5
- package/dist/_shared/startup-0-4-ZMJV547D.js +12 -7
- package/dist/_shared/startup-0-4-ZMJV547D.js.map +1 -1
- package/dist/_shared/startup-0-5-YDW47QX6.js +7 -7
- package/dist/_shared/startup-0-5-YDW47QX6.js.map +1 -1
- package/dist/_shared/startup-10-0-TDQNBDDL.js +6 -6
- package/dist/_shared/startup-12-0-55AAXBJZ.js +2 -2
- package/dist/_shared/startup-14-0-MLX36RBG.js +4 -5
- package/dist/_shared/startup-14-0-MLX36RBG.js.map +1 -1
- package/dist/_shared/startup-15-0-YUKGAC63.js +4 -4
- package/dist/_shared/startup-15-1-4S7FLMNG.js +19 -27
- package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
- package/dist/_shared/startup-8-0-34CBHPZH.js +2144 -249
- package/dist/_shared/startup-8-0-34CBHPZH.js.map +1 -1
- package/dist/_shared/{startup-8-1-X32CYSXB.js → startup-8-1-LZFXSD3Z.js} +98 -1184
- package/dist/_shared/startup-8-1-LZFXSD3Z.js.map +1 -0
- package/dist/_shared/storage-command-7MGXLJGZ.js +188 -37
- package/dist/_shared/storage-command-7MGXLJGZ.js.map +1 -1
- package/dist/_shared/storage-status-K7PX2RXA.js +557 -0
- package/dist/_shared/storage-status-K7PX2RXA.js.map +1 -0
- package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
- package/dist/_shared/team-DOQKICG2.js +376 -0
- package/dist/_shared/team-DOQKICG2.js.map +1 -0
- package/dist/_shared/tree-outline-MUEPK5B7.js +2 -2
- package/dist/builtin/intercom/CHANGELOG.md +88 -0
- package/dist/builtin/intercom/README.md +2 -2
- package/dist/builtin/intercom/broker/broker.bundle.mjs +1917 -381
- package/dist/builtin/intercom/broker/client.ts +8 -0
- package/dist/builtin/intercom/broker/database-wake-up-bus.ts +324 -68
- package/dist/builtin/intercom/broker/multinode-router.ts +256 -39
- package/dist/builtin/intercom/broker/multinode-state-store.ts +71 -5
- package/dist/builtin/intercom/broker/open-broker-state.ts +14 -0
- package/dist/builtin/intercom/broker/send-order-gate.ts +5 -2
- package/dist/builtin/intercom/broker/sql-add-column.ts +50 -5
- package/dist/builtin/intercom/broker/sql-ended-child-queue-store.ts +3 -2
- package/dist/builtin/intercom/broker/sql-held-send-store.ts +2 -2
- package/dist/builtin/intercom/broker/sql-known-session-store.ts +43 -19
- package/dist/builtin/intercom/broker/sql-lease-store.ts +473 -121
- package/dist/builtin/intercom/broker/sql-outbox-store.ts +821 -79
- package/dist/builtin/intercom/broker/sql-pending-ask-store.ts +8 -5
- package/dist/builtin/intercom/broker/sql-released-ask-store.ts +12 -5
- package/dist/builtin/intercom/broker/sql-restoring-reservation-store.ts +256 -8
- package/dist/builtin/intercom/broker/sql-retention.ts +150 -0
- package/dist/builtin/intercom/broker/sql-schema.ts +175 -24
- package/dist/builtin/intercom/broker/sql-sent-message-authority.ts +74 -19
- package/dist/builtin/intercom/broker/wake-up-bus.ts +6 -0
- package/dist/builtin/intercom/index.bundle.mjs +14 -4
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/mcp/index.bundle.mjs +1 -1
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/CHANGELOG.md +20 -0
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/subagents/skills/skill-creator/eval-viewer/generate_review.py +8 -1
- package/dist/builtin/subagents/src/extension/index.bundle.mjs +1 -1
- package/dist/builtin/web-access/index.bundle.mjs +2 -10
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/bun/bundled-sqlite.js +41 -0
- package/dist/bun/bundled-sqlite.js.map +1 -0
- package/dist/cli/args.js +2 -2
- package/dist/cli/auth-cli.code.js +4 -4
- package/dist/cli/auth-cli.impl.js +3 -3
- package/dist/cli/auth-cli.js +3 -3
- package/dist/cli/blueprint-command.code.js +3 -3
- package/dist/cli/blueprint-command.impl.js +3 -3
- package/dist/cli/blueprint-command.js +3 -3
- package/dist/cli/intercom-command.code.js +3 -3
- package/dist/cli/intercom-command.code.js.map +1 -1
- package/dist/cli/intercom-command.impl.js +3 -3
- package/dist/cli/intercom-command.js +3 -3
- package/dist/cli/list-models.code.js +2 -2
- package/dist/cli/list-models.impl.js +3 -3
- package/dist/cli/list-models.js +3 -3
- package/dist/cli/session-picker.code.js +1 -1
- package/dist/cli/session-picker.impl.js +3 -3
- package/dist/cli/session-picker.js +3 -3
- package/dist/cli/startup-ui.code.js +1 -1
- package/dist/cli/startup-ui.impl.js +3 -3
- package/dist/cli/startup-ui.js +3 -3
- package/dist/cli/storage-command.impl.js +3 -3
- package/dist/cli/storage-command.js +3 -3
- package/dist/cli/storage-search-session.code.js +3 -3
- package/dist/cli/storage-search-session.impl.js +3 -3
- package/dist/cli/storage-search-session.js +3 -3
- package/dist/cli/team-command.code.js +19 -113
- package/dist/cli/team-command.code.js.map +1 -1
- package/dist/cli/team-command.impl.js +3 -3
- package/dist/cli/team-command.js +3 -3
- package/dist/cli.js +5 -18
- package/dist/cli.js.map +1 -1
- package/dist/core/agent-rehydrate-errors.d.ts +4 -9
- package/dist/core/compaction/compactor.d.ts +3 -3
- package/dist/core/debug.code.js +1 -1
- package/dist/core/debug.impl.js +3 -3
- package/dist/core/debug.js +3 -3
- package/dist/core/export-html/card-projection.impl.js +3 -3
- package/dist/core/export-html/card-projection.js +3 -3
- package/dist/core/export-html/index.code.js +4 -4
- package/dist/core/export-html/index.code.js.map +1 -1
- package/dist/core/export-html/index.impl.js +3 -3
- package/dist/core/export-html/index.js +3 -3
- package/dist/core/export-html/json-spans.impl.js +3 -3
- package/dist/core/export-html/json-spans.js +3 -3
- package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
- package/dist/core/export-html/oversized-render-inputs.js +3 -3
- package/dist/core/export-html/tool-renderer.impl.js +3 -3
- package/dist/core/export-html/tool-renderer.js +3 -3
- package/dist/core/extensions/jiti-loader.impl.js +3 -3
- package/dist/core/extensions/jiti-loader.js +3 -3
- package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
- package/dist/core/extensions/jiti-static-loader.js +3 -3
- package/dist/core/extensions/loader-host-modules.code.js +1 -1
- package/dist/core/extensions/loader-host-modules.impl.js +3 -3
- package/dist/core/extensions/loader-host-modules.js +3 -3
- package/dist/core/extensions/loader-virtual-modules.js +1 -1
- package/dist/core/extensions/runner-context.js +2 -2
- package/dist/core/intercom-broker-control-host.code.js +2 -2
- package/dist/core/intercom-broker-control-host.impl.js +3 -3
- package/dist/core/intercom-broker-control-host.js +3 -3
- package/dist/core/intercom-broker-control.code.js +3 -3
- package/dist/core/intercom-broker-control.impl.js +3 -3
- package/dist/core/intercom-broker-control.js +3 -3
- package/dist/core/package-manager-storage-adapters.code.js +1 -1
- package/dist/core/package-manager-storage-adapters.impl.js +3 -3
- package/dist/core/package-manager-storage-adapters.js +3 -3
- package/dist/core/process-start-token.d.ts +12 -3
- package/dist/core/process-tree-containment.d.ts +16 -0
- package/dist/core/sdk-types.d.ts +1 -2
- package/dist/core/sdk-types.js.map +1 -1
- package/dist/core/sdk.code.js +3 -3
- package/dist/core/sdk.impl.js +3 -3
- package/dist/core/sdk.js +3 -3
- package/dist/core/session-manager-core.js +5 -5
- package/dist/core/session-manager-list.impl.js +3 -3
- package/dist/core/session-manager-list.js +3 -3
- package/dist/core/session-manager.code.js +1 -1
- package/dist/core/session-manager.impl.js +3 -3
- package/dist/core/session-manager.js +3 -3
- package/dist/core/session-storage.code.js +1 -1
- package/dist/core/session-storage.impl.js +3 -3
- package/dist/core/session-storage.js +3 -3
- package/dist/core/settings-schema.d.ts +0 -3
- package/dist/core/storage/added-exports-0-10-11.js +19 -0
- package/dist/core/storage/added-exports-0-10-11.js.map +1 -0
- package/dist/core/storage/creation-time.js +105 -0
- package/dist/core/storage/creation-time.js.map +1 -0
- package/dist/core/storage/database.d.ts +25 -5
- package/dist/core/storage/database.js.map +1 -1
- package/dist/core/storage/dialect.d.ts +1 -1
- package/dist/core/storage/dialect.js +1 -1
- package/dist/core/storage/dialect.js.map +1 -1
- package/dist/core/storage/errors.d.ts +13 -13
- package/dist/core/storage/errors.js +10 -16
- package/dist/core/storage/errors.js.map +1 -1
- package/dist/core/storage/fenced-paths.d.ts +18 -6
- package/dist/core/storage/fenced-paths.js +18 -6
- package/dist/core/storage/fenced-paths.js.map +1 -1
- package/dist/core/storage/file-identity.d.ts +2 -0
- package/dist/core/storage/file-identity.js +24 -8
- package/dist/core/storage/file-identity.js.map +1 -1
- package/dist/core/storage/index.d.ts +3 -2
- package/dist/core/storage/index.js +5 -3
- package/dist/core/storage/index.js.map +1 -1
- package/dist/core/storage/libsql-removed.d.ts +71 -0
- package/dist/core/storage/libsql-removed.js +123 -0
- package/dist/core/storage/libsql-removed.js.map +1 -0
- package/dist/core/storage/migrations.d.ts +78 -14
- package/dist/core/storage/migrations.js +375 -49
- package/dist/core/storage/migrations.js.map +1 -1
- package/dist/core/storage/node-sqlite-file-gate.js +0 -15
- package/dist/core/storage/node-sqlite-file-gate.js.map +1 -1
- package/dist/core/storage/node-sqlite-thread.js +215 -30
- package/dist/core/storage/node-sqlite-thread.js.map +1 -1
- package/dist/core/storage/node-sqlite.js +484 -72
- package/dist/core/storage/node-sqlite.js.map +1 -1
- package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
- package/dist/core/storage/offline-snapshot-file.js +3 -3
- package/dist/core/storage/prefix.d.ts +1 -1
- package/dist/core/storage/prefix.js +9 -2
- package/dist/core/storage/prefix.js.map +1 -1
- package/dist/core/storage/process-selection.d.ts +5 -5
- package/dist/core/storage/provider.js +2 -2
- package/dist/core/storage/schema-catalog.d.ts +76 -15
- package/dist/core/storage/schema-catalog.js +359 -68
- package/dist/core/storage/schema-catalog.js.map +1 -1
- package/dist/core/storage/selection.d.ts +7 -82
- package/dist/core/storage/selection.js +20 -235
- package/dist/core/storage/selection.js.map +1 -1
- package/dist/core/storage/session/branch-fork-source.code.js +2 -2
- package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
- package/dist/core/storage/session/branch-fork-source.js +3 -3
- package/dist/core/storage/session/card-view.impl.js +3 -3
- package/dist/core/storage/session/card-view.js +3 -3
- package/dist/core/storage/session/child-reader.code.js +3 -3
- package/dist/core/storage/session/child-reader.impl.js +3 -3
- package/dist/core/storage/session/child-reader.js +3 -3
- package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
- package/dist/core/storage/session/chunked-resume-projection.js +3 -3
- package/dist/core/storage/session/expanded-child-details.code.js +2 -2
- package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
- package/dist/core/storage/session/expanded-child-details.js +3 -3
- package/dist/core/storage/session/fork-detach.d.ts +11 -1
- package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
- package/dist/core/storage/session/fork-row-bytes.js +3 -3
- package/dist/core/storage/session/fork-row-index.impl.js +3 -3
- package/dist/core/storage/session/fork-row-index.js +3 -3
- package/dist/core/storage/session/fork-staging.code.js +4 -7
- package/dist/core/storage/session/fork-staging.code.js.map +1 -1
- package/dist/core/storage/session/fork-staging.impl.js +3 -3
- package/dist/core/storage/session/fork-staging.js +3 -3
- package/dist/core/storage/session/fork-sweep.js +31 -7
- package/dist/core/storage/session/fork-sweep.js.map +1 -1
- package/dist/core/storage/session/fork-window.code.js +3 -3
- package/dist/core/storage/session/fork-window.impl.js +3 -3
- package/dist/core/storage/session/fork-window.js +3 -3
- package/dist/core/storage/session/history-pages.impl.js +3 -3
- package/dist/core/storage/session/history-pages.js +3 -3
- package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
- package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
- package/dist/core/storage/session/jsonl-session-lock.d.ts +100 -0
- package/dist/core/storage/session/jsonl-session-store.d.ts +46 -24
- package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
- package/dist/core/storage/session/jsonl-session-store.js +3 -3
- package/dist/core/storage/session/memory-session-store.impl.js +3 -3
- package/dist/core/storage/session/memory-session-store.js +3 -3
- package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
- package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
- package/dist/core/storage/session/pinned-branch-resume.js +3 -3
- package/dist/core/storage/session/released-history-files.code.js +9 -9
- package/dist/core/storage/session/released-history-files.code.js.map +1 -1
- package/dist/core/storage/session/released-history-files.impl.js +3 -3
- package/dist/core/storage/session/released-history-files.js +3 -3
- package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
- package/dist/core/storage/session/resident-fork-rows.js +3 -3
- package/dist/core/storage/session/session-resume.impl.js +3 -3
- package/dist/core/storage/session/session-resume.js +3 -3
- package/dist/core/storage/session/session-search-index.d.ts +52 -5
- package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
- package/dist/core/storage/session/snapshot-cut.js +3 -3
- package/dist/core/storage/session/snapshot-history.code.js +3 -3
- package/dist/core/storage/session/snapshot-history.impl.js +3 -3
- package/dist/core/storage/session/snapshot-history.js +3 -3
- package/dist/core/storage/session/sql-session-store.code.js +1 -1
- package/dist/core/storage/session/sql-session-store.d.ts +99 -18
- package/dist/core/storage/session/sql-session-store.impl.js +3 -3
- package/dist/core/storage/session/sql-session-store.js +3 -3
- package/dist/core/storage/session/tree-outline.impl.js +3 -3
- package/dist/core/storage/session/tree-outline.js +3 -3
- package/dist/core/storage/session/tree-presentation.impl.js +3 -3
- package/dist/core/storage/session/tree-presentation.js +3 -3
- package/dist/core/storage/sqlite-facade.d.ts +12 -1
- package/dist/core/storage/sqlite-facade.js +310 -33
- package/dist/core/storage/sqlite-facade.js.map +1 -1
- package/dist/core/storage/sqlite-open-batch.js +10 -0
- package/dist/core/storage/sqlite-open-batch.js.map +1 -0
- package/dist/core/storage/storage-status.code.js +1 -1
- package/dist/core/storage/storage-status.impl.js +3 -3
- package/dist/core/storage/storage-status.js +3 -3
- package/dist/core/storage/team.code.js +1 -1
- package/dist/core/storage/team.d.ts +26 -115
- package/dist/core/storage/team.impl.js +3 -3
- package/dist/core/storage/team.js +3 -3
- package/dist/core/structured-output/index.code.js +1 -1
- package/dist/core/structured-output/index.impl.js +3 -3
- package/dist/core/structured-output/index.js +3 -3
- package/dist/core/tasks/task-completion-entry.impl.js +3 -3
- package/dist/core/tasks/task-completion-entry.js +3 -3
- package/dist/core/tasks/task-file-history.code.js +3 -3
- package/dist/core/tasks/task-file-history.impl.js +3 -3
- package/dist/core/tasks/task-file-history.js +3 -3
- package/dist/core/tasks/task-reference-archive.code.js +4 -4
- package/dist/core/tasks/task-reference-archive.js +3 -3
- package/dist/core/tasks/task-reference-identity.js +3 -3
- package/dist/core/tasks/task-reference-stream.impl.js +3 -3
- package/dist/core/tasks/task-reference-stream.js +3 -3
- package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
- package/dist/core/tasks/task-unsaved-answer.js +3 -3
- package/dist/core/tasks/task-view-source.code.js +1 -1
- package/dist/core/tasks/task-view-source.impl.js +3 -3
- package/dist/core/tasks/task-view-source.js +3 -3
- package/dist/core/tools/history-tasks.d.ts +3 -2
- package/dist/core/tools/read-url.code.js +4 -4
- package/dist/core/tools/read-url.impl.js +3 -3
- package/dist/core/tools/read-url.js +3 -3
- package/dist/core/worktree-snapshot/blob-store.d.ts +44 -5
- package/dist/core/worktree-snapshot/blob-store.js +553 -30
- package/dist/core/worktree-snapshot/blob-store.js.map +1 -1
- package/dist/core/worktree-snapshot/errors.code.js +2 -2
- package/dist/core/worktree-snapshot/errors.impl.js +3 -3
- package/dist/core/worktree-snapshot/errors.js +3 -3
- package/dist/core/worktree-snapshot/fork-blob-guard.js +81 -0
- package/dist/core/worktree-snapshot/fork-blob-guard.js.map +1 -0
- package/dist/core/worktree-snapshot/fork-snapshot-index.js +208 -50
- package/dist/core/worktree-snapshot/fork-snapshot-index.js.map +1 -1
- package/dist/core/worktree-snapshot/session-index-reset.code.js +4 -0
- package/dist/core/worktree-snapshot/session-index-reset.code.js.map +1 -1
- package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
- package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
- package/dist/extensions/codemode/execute.code.js +1 -1
- package/dist/extensions/codemode/execute.impl.js +3 -3
- package/dist/extensions/codemode/execute.js +3 -3
- package/dist/extensions/codemode/renderer.code.js +2 -2
- package/dist/extensions/codemode/renderer.impl.js +3 -3
- package/dist/extensions/codemode/renderer.js +3 -3
- package/dist/extensions/mcp/cli.code.js +3 -3
- package/dist/extensions/mcp/cli.impl.js +3 -3
- package/dist/extensions/mcp/cli.js +3 -3
- package/dist/extensions/mcp/cli.lazy.code.js +2 -2
- package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
- package/dist/extensions/mcp/cli.lazy.js +3 -3
- package/dist/extensions/mcp/runtime.code.js +1 -1
- package/dist/extensions/mcp/runtime.impl.js +3 -3
- package/dist/extensions/mcp/runtime.js +3 -3
- package/dist/index.d.ts +3 -1
- package/dist/index.js +5 -5
- package/dist/main-first-time-setup.code.js +1 -1
- package/dist/main-first-time-setup.impl.js +3 -3
- package/dist/main-first-time-setup.js +3 -3
- package/dist/main.js +1 -1
- package/dist/modes/interactive/components/stored-tree-view.code.js +2 -2
- package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
- package/dist/modes/interactive/components/stored-tree-view.js +3 -3
- package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
- package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
- package/dist/modes/interactive/startup-shell-eligibility.js +1 -1
- package/dist/modes/interactive-engine/engine-prewarm.d.ts +1 -1
- package/dist/modes/print-mode.js +1 -1
- package/dist/package-manager-cli.code.js +6 -6
- package/dist/package-manager-cli.impl.js +3 -3
- package/dist/package-manager-cli.js +3 -3
- package/dist/rpc-entry.js +1 -1
- package/dist/startup-files.json +1 -1
- package/dist/startup-stages/10.js +1 -1
- package/dist/startup-stages/11.js +1 -1
- package/dist/startup-stages/12.js +1 -1
- package/dist/startup-stages/2.js +2 -4
- package/dist/startup-stages/3.js +1 -3
- package/dist/startup-stages/4.js +1 -2
- package/dist/startup-stages/5.js +1 -1
- package/dist/startup-stages/6.js +5 -7
- package/dist/startup-stages/7.js +3 -10
- package/dist/startup-stages/8.js +7 -2
- package/dist/startup-stages/9.js +1 -7
- package/dist/startup-stages/stages.json +1 -1
- package/dist/utils/compile-cache-deferral.js +8 -13
- package/dist/utils/compile-cache-deferral.js.map +1 -1
- package/dist/utils/compile-cache-warmup-host.js +3 -4
- package/dist/utils/compile-cache-warmup-host.js.map +1 -1
- package/dist/utils/compile-cache.js +12 -100
- package/dist/utils/compile-cache.js.map +1 -1
- package/dist/utils/startup-database-spare.code.js +2 -2
- package/dist/utils/startup-database-spare.impl.js +3 -3
- package/dist/utils/startup-database-spare.js +3 -3
- package/dist/utils/tools-manager.code.js +1 -1
- package/dist/utils/tools-manager.impl.js +3 -3
- package/dist/utils/tools-manager.js +3 -3
- package/dist/utils/worker-threads.js +2 -15
- package/dist/utils/worker-threads.js.map +1 -1
- package/docs/build.md +3 -3
- package/docs/changelog.mdx +1498 -69
- package/docs/compaction/reference.md +5 -5
- package/docs/compaction.md +7 -9
- package/docs/containerization.md +2 -2
- package/docs/custom-provider/api-reference.md +1 -1
- package/docs/docs.json +37 -10
- package/docs/environment-variables.md +0 -2
- package/docs/extensions/api-reference.md +4 -4
- package/docs/getting-started/installation.md +3 -0
- package/docs/guides/configuration.md +1 -1
- package/docs/guides/non-interactive.md +1 -1
- package/docs/guides/resume-on-any-machine.md +14 -22
- package/docs/guides/team-setup.md +56 -83
- package/docs/guides.md +2 -4
- package/docs/herdr.md +1 -1
- package/docs/index.md +1 -1
- package/docs/intercom/operations.md +26 -21
- package/docs/intercom/reference.md +2 -2
- package/docs/intercom.md +1 -1
- package/docs/libraries/storage-postgres.md +9 -9
- package/docs/libraries.md +2 -3
- package/docs/models-configuration.md +2 -2
- package/docs/models.md +2 -3
- package/docs/packages/authoring.md +7 -7
- package/docs/packages.md +1 -1
- package/docs/programmatic.md +2 -2
- package/docs/quickstart.md +1 -1
- package/docs/reference/cli.md +6 -11
- package/docs/reference.md +2 -2
- package/docs/rpc/extension-ui.md +2 -2
- package/docs/sdk/reference.md +5 -4
- package/docs/sdk/storage.md +8 -92
- package/docs/sdk/structured-decisions.md +1 -1
- package/docs/sdk/web-server.md +3 -3
- package/docs/sdk.md +14 -4
- package/docs/security.md +1 -1
- package/docs/session-format.md +5 -5
- package/docs/sessions.md +29 -49
- package/docs/settings.md +7 -8
- package/docs/storage/custom-adapters.md +255 -0
- package/docs/storage/jsonl.md +117 -0
- package/docs/{guides/postgres-pgbouncer.md → storage/postgres/pgbouncer.md} +66 -68
- package/docs/storage/postgres/tuning.md +337 -0
- package/docs/storage/postgres.md +556 -0
- package/docs/storage/sqlite.md +99 -0
- package/docs/storage.md +326 -990
- package/docs/subagents/authoring.md +1 -1
- package/docs/subagents.md +2 -2
- package/docs/tools.md +1 -1
- package/docs/worktree-snapshots.md +2 -2
- package/package.json +9 -9
- package/schemas/models.schema.json +2 -2
- package/schemas/settings.schema.json +0 -14
- package/dist/_shared/p1b-elig-ENCUPKKJ.js.map +0 -1
- package/dist/_shared/sdk-IQMULKFU.js.map +0 -1
- package/dist/_shared/startup-0-0-3IXNMFM2.js.map +0 -1
- package/dist/_shared/startup-0-1-7T2IAE7J.js.map +0 -1
- package/dist/_shared/startup-8-1-X32CYSXB.js.map +0 -1
- package/dist/core/intercom-broker-control.d.ts +0 -129
- package/dist/startup-stages/13.js +0 -1
- package/docs/guides/postgres-tuning.md +0 -311
- package/docs/libraries/storage-libsql.md +0 -97
|
@@ -25,17 +25,49 @@ import {
|
|
|
25
25
|
type OutboxEnqueueRequest,
|
|
26
26
|
type OutboxEnqueueResult,
|
|
27
27
|
type OutboxFrame,
|
|
28
|
+
type OutboxReleaseClaimResult,
|
|
29
|
+
type OutboxRenewClaimResult,
|
|
28
30
|
type OutboxRow,
|
|
29
31
|
type OutboxRowState,
|
|
30
32
|
type OutboxStore,
|
|
31
33
|
type StateStoreInvalidReason,
|
|
32
34
|
} from "./multinode-state-store.js";
|
|
35
|
+
import { wakeUpNotices } from "./database-wake-up-bus.js";
|
|
33
36
|
import { addMissingColumns } from "./sql-add-column.js";
|
|
34
|
-
import {
|
|
37
|
+
import { deleteInBatches, SETTLED, storeNow, UNDELIVERED } from "./sql-retention.js";
|
|
38
|
+
import type { OutboxReservation } from "./sql-sent-message-authority.js";
|
|
39
|
+
import { ensureBrokerSchema, RETRY_UNAPPLIED, withBrokerSchemaCatalog } from "./sql-schema.js";
|
|
35
40
|
|
|
36
|
-
|
|
41
|
+
/**
|
|
42
|
+
* The settings a PostgreSQL send that runs in one round trip (`enqueueAtOnce`) records its decisions in, for the
|
|
43
|
+
* statements after the one that made them: whether the recipient's queue has room for the row, and which reservation
|
|
44
|
+
* of the message the send deletes if its row is not queued.
|
|
45
|
+
*/
|
|
46
|
+
const SEND_ROOM = "atomic.intercom_send_room";
|
|
47
|
+
const SEND_FORGET = "atomic.intercom_send_forget";
|
|
48
|
+
/**
|
|
49
|
+
* The settings a one-round-trip send to a recipient its sender found offline records, for the statements after the row's
|
|
50
|
+
* insert: the broker holding the recipient's live presence, read with the insert, the row's sequence and recipient, and whether the
|
|
51
|
+
* hint log took the send's lock without waiting, so its wake-up hint was written.
|
|
52
|
+
*/
|
|
53
|
+
const SEND_WAKE = "atomic.intercom_send_wake";
|
|
54
|
+
const SEND_WAKE_VERSION = "atomic.intercom_send_wake_version";
|
|
55
|
+
const SEND_WAKE_TARGET = "atomic.intercom_send_wake_target";
|
|
56
|
+
const SEND_HINT = "atomic.intercom_send_hint";
|
|
57
|
+
/**
|
|
58
|
+
* The settings a one-round-trip PostgreSQL delivery settlement records for the statements after its update: the
|
|
59
|
+
* unmatched claim ids to look up, the distinct remote origin brokers to wake with outcome hints, and whether the hint
|
|
60
|
+
* log took the settlement's lock without waiting (#6715).
|
|
61
|
+
*/
|
|
62
|
+
const SETTLE_UNMATCHED = "atomic.intercom_settle_unmatched";
|
|
63
|
+
const SETTLE_WAKE = "atomic.intercom_settle_wake";
|
|
64
|
+
const SETTLE_HINT = "atomic.intercom_settle_hint";
|
|
37
65
|
/** The setting a PostgreSQL claim transaction records in that its recipient has undelivered rows, and its locks are held. */
|
|
38
66
|
const CLAIM_GATE = "atomic.intercom_outbox_claim";
|
|
67
|
+
/** The setting a PostgreSQL batched renewal records in when fewer rows renewed than it was given, so its follow-up read runs. */
|
|
68
|
+
const RENEW_MISSES = "atomic.intercom_renew_misses";
|
|
69
|
+
/** The setting a PostgreSQL batch claim release records in when fewer rows matched than were given (#6713). */
|
|
70
|
+
const RELEASE_MISSES = "atomic.intercom_release_misses";
|
|
39
71
|
/** The most `markDelivered` calls one transaction settles together (#6560). */
|
|
40
72
|
const MARK_DELIVERED_BATCH_MAX = 100;
|
|
41
73
|
|
|
@@ -79,6 +111,8 @@ function toRow(record: OutboxRecord): OutboxRow {
|
|
|
79
111
|
|
|
80
112
|
const isSettled = (record: OutboxRecord): boolean => record.state === "delivered" || record.state === "failed";
|
|
81
113
|
|
|
114
|
+
const renewedAnswer = () => ({ status: "renewed" }) as const;
|
|
115
|
+
|
|
82
116
|
/**
|
|
83
117
|
* #5607: the wake-up hint written with an offline recipient's row failed, so neither was written. The hint is only a
|
|
84
118
|
* hint: the caller writes the row again without it (`withoutFailedWake`).
|
|
@@ -117,6 +151,16 @@ export interface SqlOutboxStore extends OutboxStore {
|
|
|
117
151
|
* connection sends them with the transaction's start instead of a round trip each (#6560).
|
|
118
152
|
*/
|
|
119
153
|
enqueueLeading(request: OutboxEnqueueRequest): readonly SqliteStatement[];
|
|
154
|
+
/**
|
|
155
|
+
* PostgreSQL: `enqueue`, and with `reservation` a send that reserves its message with it as `enqueueIn` does under
|
|
156
|
+
* its guard, in one transaction of the recipient's domain whose every decision the database makes, so it is one round
|
|
157
|
+
* trip and holds the recipient's lock domain for no round trip at all, a wake-up hint for an offline recipient's host
|
|
158
|
+
* included. Undefined for a request that `enqueueIn` refuses, which takes `enqueueIn`'s way.
|
|
159
|
+
*/
|
|
160
|
+
enqueueAtOnce?(
|
|
161
|
+
request: OutboxEnqueueRequest,
|
|
162
|
+
reservation?: OutboxReservation,
|
|
163
|
+
): Promise<OutboxEnqueueResult> | undefined;
|
|
120
164
|
}
|
|
121
165
|
|
|
122
166
|
/**
|
|
@@ -157,7 +201,15 @@ export async function withoutFailedWake<T>(
|
|
|
157
201
|
* The lock domain of one recipient's sends, `<outbox>:<recipient>`: a send reserves its message and queues its row in
|
|
158
202
|
* one transaction of it (`reserveAndEnqueue`, `enqueue`), so sends to one recipient run one at a time, and commit their
|
|
159
203
|
* rows in the order of their sequence, and a send's checks of that recipient's queue (its size budget) hold until it
|
|
160
|
-
* commits. Sends to other recipients, claims and every write of one row run beside them (#6560).
|
|
204
|
+
* commits. Sends to other recipients, claims and every write of one row run beside them (#6560). A send that a lock
|
|
205
|
+
* timeout ended runs again before the next send to that recipient this process makes starts (`RETRY_UNAPPLIED`).
|
|
206
|
+
*
|
|
207
|
+
* Sends to one recipient deliberately exclude one another, though a send holds the lock only while the database runs its
|
|
208
|
+
* statements, never across a round trip. Letting them share it (with a claim excluding them instead) would let them run
|
|
209
|
+
* side by side, but rows would then commit out of sequence order: a broker of an earlier release, which claims without
|
|
210
|
+
* waiting for sends, could hand a recipient's later message out before an earlier one during a rolling upgrade, and two
|
|
211
|
+
* sends could both see room for the last message the recipient's queue accepts and exceed its size budget. The time it
|
|
212
|
+
* would save, a few milliseconds per send, is not worth either.
|
|
161
213
|
*/
|
|
162
214
|
export function recipientTransaction(
|
|
163
215
|
database: SqliteDatabase,
|
|
@@ -165,7 +217,7 @@ export function recipientTransaction(
|
|
|
165
217
|
targetIdentity: string,
|
|
166
218
|
): SqliteTransactionOptions {
|
|
167
219
|
const outbox = `${validateStoragePrefix(prefix, dialectOf(database).name)}intercom_outbox`;
|
|
168
|
-
return { concurrency: { kind: "serial", domain: `${outbox}:${targetIdentity}` } };
|
|
220
|
+
return { ...RETRY_UNAPPLIED, concurrency: { kind: "serial", domain: `${outbox}:${targetIdentity}` } };
|
|
169
221
|
}
|
|
170
222
|
|
|
171
223
|
/**
|
|
@@ -174,7 +226,10 @@ export function recipientTransaction(
|
|
|
174
226
|
* transactions an older broker runs on these tables (#6560).
|
|
175
227
|
*/
|
|
176
228
|
export function rowTransaction(): SqliteTransactionOptions {
|
|
177
|
-
return {
|
|
229
|
+
return {
|
|
230
|
+
...RETRY_UNAPPLIED,
|
|
231
|
+
concurrency: { kind: "fenced", audit: fencedPath("intercom-outbox-row"), excludesSerial: true },
|
|
232
|
+
};
|
|
178
233
|
}
|
|
179
234
|
|
|
180
235
|
/**
|
|
@@ -193,7 +248,7 @@ export function openSqlOutboxStore(options: IntercomBrokerStateOptions): Promise
|
|
|
193
248
|
async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Promise<SqlOutboxStore> {
|
|
194
249
|
const { database } = options;
|
|
195
250
|
const table = `${validateStoragePrefix(options.prefix, dialectOf(database).name)}intercom_outbox`;
|
|
196
|
-
const { types, nowMs, greatest, lockClause, name: dialect } = dialectOf(database);
|
|
251
|
+
const { types, nowMs, greatest, lockClause, jsonValues, name: dialect } = dialectOf(database);
|
|
197
252
|
/** Claim writes and expiry: each decides on the rows it locks (#6560). */
|
|
198
253
|
const fenced = rowTransaction();
|
|
199
254
|
const ageSince = (column: string) => greatest("0", `${nowMs} - ${column}`);
|
|
@@ -214,18 +269,14 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
|
|
|
214
269
|
failure_reason TEXT,
|
|
215
270
|
settled_at ${types.int}
|
|
216
271
|
);
|
|
217
|
-
CREATE INDEX IF NOT EXISTS ${table}_target ON ${table}(target_identity, state, sequence);
|
|
218
272
|
`;
|
|
219
273
|
await ensureBrokerSchema(database, options.prefix, "outbox", (tx) => tx.exec(schema));
|
|
220
274
|
// #3983: added later; a table from an older broker gets the column, and an older broker ignores it.
|
|
221
275
|
await addMissingColumns(database, table, { saving_at: types.int });
|
|
222
276
|
// #4896: when the row was queued and the size of its frame; rows an older broker wrote have neither.
|
|
223
277
|
await addMissingColumns(database, table, { queued_at: types.int, frame_bytes: types.int });
|
|
224
|
-
//
|
|
225
|
-
//
|
|
226
|
-
await ensureBrokerSchema(database, options.prefix, "outbox-indexes", (tx) =>
|
|
227
|
-
tx.exec(`CREATE INDEX IF NOT EXISTS ${table}_target_bytes ON ${table}(target_identity, state, frame_bytes)`),
|
|
228
|
-
);
|
|
278
|
+
// Its partial indexes, and its fillfactor on PostgreSQL, are set at the end of a broker's open
|
|
279
|
+
// (`ensureRetentionIndexes`), where the other stores' tables are there too.
|
|
229
280
|
|
|
230
281
|
const columns = `sequence, message_id, target_identity, origin_broker_id, digest, frame_json, state,
|
|
231
282
|
claim_attempts, claimant_id, claim_token, failure_reason,
|
|
@@ -270,6 +321,7 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
|
|
|
270
321
|
assignments: string,
|
|
271
322
|
params: readonly SqliteValue[],
|
|
272
323
|
answer: (written: OutboxRecord) => Result,
|
|
324
|
+
relaxedDurability = false,
|
|
273
325
|
): Promise<Result | OutboxClaimWriteRejection> => {
|
|
274
326
|
if (claim.messageId.length === 0) return Promise.resolve(invalid("empty-message-id"));
|
|
275
327
|
if (claim.claimantId.length === 0) return Promise.resolve(invalid("empty-claimant-id"));
|
|
@@ -288,67 +340,531 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
|
|
|
288
340
|
if (isSettled(record)) return { status: "settled", row: toRow(record) } as const;
|
|
289
341
|
return { status: "stale" } as const;
|
|
290
342
|
},
|
|
291
|
-
{ ...fenced, leading: [write] },
|
|
343
|
+
{ ...fenced, leading: [write], ...(relaxedDurability ? { relaxedDurability } : {}) },
|
|
292
344
|
);
|
|
293
345
|
};
|
|
294
346
|
|
|
295
347
|
const settled = `failure_reason = ?, settled_at = ${nowMs},
|
|
296
348
|
claimant_id = NULL, claim_token = NULL, claim_renewed_at = NULL, saving_at = NULL`;
|
|
297
349
|
|
|
350
|
+
// One bound JSON array of `[messageId, token, claimantId]` triples keeps the statement text fixed for any batch size
|
|
351
|
+
// and matches each row against one whole claim rather than separate lists of ids and tokens (#6560).
|
|
352
|
+
const claimsCte =
|
|
353
|
+
dialect === "postgres"
|
|
354
|
+
? "WITH claims AS (SELECT c ->> 0 AS message_id, c ->> 1 AS claim_token, c ->> 2 AS claimant_id FROM jsonb_array_elements(?::jsonb) AS c)"
|
|
355
|
+
: "WITH claims AS (SELECT json_extract(value, '$[0]') AS message_id, json_extract(value, '$[1]') AS claim_token, json_extract(value, '$[2]') AS claimant_id FROM json_each(?))";
|
|
356
|
+
const claimTriples = (claims: readonly OutboxClaim[]): string =>
|
|
357
|
+
JSON.stringify(claims.map((claim) => [claim.messageId, claim.token, claim.claimantId]));
|
|
358
|
+
const matchesClaim =
|
|
359
|
+
"(message_id, claim_token, claimant_id) IN (SELECT message_id, claim_token, claimant_id FROM claims)";
|
|
360
|
+
const messageIdIn = (subquery: string) =>
|
|
361
|
+
dialect === "postgres" ? `message_id = ANY(ARRAY(${subquery}))` : `message_id IN (${subquery})`;
|
|
362
|
+
const lockedClaimsWhere =
|
|
363
|
+
dialect === "postgres"
|
|
364
|
+
? `${messageIdIn(
|
|
365
|
+
`SELECT message_id FROM ${table} WHERE state = 'claimed'
|
|
366
|
+
AND ${messageIdIn("SELECT message_id FROM claims")} AND ${matchesClaim}
|
|
367
|
+
ORDER BY sequence${lockClause("update")}`,
|
|
368
|
+
)} AND state = 'claimed' AND ${matchesClaim}`
|
|
369
|
+
: `state = 'claimed' AND ${matchesClaim}`;
|
|
370
|
+
|
|
371
|
+
type MarkDeliveredEntry = {
|
|
372
|
+
readonly claim: OutboxClaim;
|
|
373
|
+
readonly wakeOrigin: boolean;
|
|
374
|
+
};
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* Settles each of `entries`, of distinct rows, as delivered, in one transaction: one UPDATE that locks their rows in
|
|
378
|
+
* sequence order on PostgreSQL, as a claim locks a recipient's rows, and changes those whose claim is still current,
|
|
379
|
+
* followed in the same transaction by the optional outcome hints for remote origin brokers (with NOWAIT on
|
|
380
|
+
* PostgreSQL so a contended hint log never fails the settlement) and the lookup of any unmatched rows (#6560, #6715,
|
|
381
|
+
* #6716).
|
|
382
|
+
*/
|
|
383
|
+
const markDeliveredTogether = (entries: readonly MarkDeliveredEntry[]): Promise<OutboxDeliveredResult[]> => {
|
|
384
|
+
const wantsWake = entries.some(({ wakeOrigin }) => wakeOrigin);
|
|
385
|
+
if (dialect !== "postgres") {
|
|
386
|
+
const runSqlite = (wakes: boolean): Promise<OutboxDeliveredResult[]> => {
|
|
387
|
+
const claims = entries.map(({ claim }) => claim);
|
|
388
|
+
const write: SqliteStatement = {
|
|
389
|
+
sql: `${claimsCte}
|
|
390
|
+
UPDATE ${table} SET state = 'delivered', ${settled}
|
|
391
|
+
WHERE ${lockedClaimsWhere}
|
|
392
|
+
RETURNING ${columns}`,
|
|
393
|
+
params: [claimTriples(claims), null],
|
|
394
|
+
};
|
|
395
|
+
return database.transaction(
|
|
396
|
+
async (executor) => {
|
|
397
|
+
const written = new Map(
|
|
398
|
+
(await executor.all<OutboxRecord>(write.sql, ...write.params)).map((record) => [
|
|
399
|
+
record.message_id,
|
|
400
|
+
record,
|
|
401
|
+
]),
|
|
402
|
+
);
|
|
403
|
+
const others = claims.filter((claim) => !written.has(claim.messageId));
|
|
404
|
+
const found =
|
|
405
|
+
others.length === 0
|
|
406
|
+
? new Map<string, OutboxRecord>()
|
|
407
|
+
: new Map(
|
|
408
|
+
(
|
|
409
|
+
await executor.all<OutboxRecord>(
|
|
410
|
+
`SELECT ${columns} FROM ${table} WHERE ${messageIdIn(`SELECT value FROM ${jsonValues("?")}`)}`,
|
|
411
|
+
JSON.stringify(others.map((claim) => claim.messageId)),
|
|
412
|
+
)
|
|
413
|
+
).map((record) => [record.message_id, record]),
|
|
414
|
+
);
|
|
415
|
+
const wokenOrigins = new Map<string, number>();
|
|
416
|
+
if (wakes) {
|
|
417
|
+
for (const { claim, wakeOrigin } of entries) {
|
|
418
|
+
if (!wakeOrigin) continue;
|
|
419
|
+
const delivered = written.get(claim.messageId);
|
|
420
|
+
if (delivered === undefined || delivered.origin_broker_id === claim.claimantId) continue;
|
|
421
|
+
const sequence = Number(delivered.sequence);
|
|
422
|
+
const prev = wokenOrigins.get(delivered.origin_broker_id);
|
|
423
|
+
if (prev === undefined || sequence > prev) wokenOrigins.set(delivered.origin_broker_id, sequence);
|
|
424
|
+
}
|
|
425
|
+
if (wokenOrigins.size > 0) {
|
|
426
|
+
const notifications = database.notifications;
|
|
427
|
+
const hintRows = [...wokenOrigins.entries()];
|
|
428
|
+
const statements: SqliteStatement[] = [
|
|
429
|
+
{
|
|
430
|
+
sql: `INSERT INTO ${wakeups}(broker_id, reason, version, created_at)
|
|
431
|
+
SELECT json_extract(value, '$[0]'), 'outcome',
|
|
432
|
+
CAST(json_extract(value, '$[1]') AS ${types.int}), ${nowMs}
|
|
433
|
+
FROM json_each(?)`,
|
|
434
|
+
params: [JSON.stringify(hintRows)],
|
|
435
|
+
},
|
|
436
|
+
...(notifications === undefined
|
|
437
|
+
? []
|
|
438
|
+
: hintRows.flatMap(([brokerId]) => wakeUpNotices(notifications, wakeups, leases, brokerId))),
|
|
439
|
+
];
|
|
440
|
+
await (async () => {
|
|
441
|
+
for (const { sql, params } of statements) await executor.run(sql, ...params);
|
|
442
|
+
})().catch((cause: unknown) => {
|
|
443
|
+
throw new OutboxWakeFailedError(cause);
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
return entries.map(({ claim, wakeOrigin }): OutboxDeliveredResult => {
|
|
448
|
+
const delivered = written.get(claim.messageId);
|
|
449
|
+
if (delivered !== undefined) {
|
|
450
|
+
const woke =
|
|
451
|
+
wakes &&
|
|
452
|
+
wakeOrigin &&
|
|
453
|
+
wokenOrigins.has(delivered.origin_broker_id) &&
|
|
454
|
+
delivered.origin_broker_id !== claim.claimantId
|
|
455
|
+
? delivered.origin_broker_id
|
|
456
|
+
: undefined;
|
|
457
|
+
return { status: "delivered", row: toRow(delivered), ...(woke === undefined ? {} : { woke }) };
|
|
458
|
+
}
|
|
459
|
+
const record = found.get(claim.messageId);
|
|
460
|
+
if (record === undefined) return { status: "unknown" };
|
|
461
|
+
if (isSettled(record)) return { status: "settled", row: toRow(record) };
|
|
462
|
+
return { status: "stale" };
|
|
463
|
+
});
|
|
464
|
+
},
|
|
465
|
+
{ ...fenced, leading: [write] },
|
|
466
|
+
);
|
|
467
|
+
};
|
|
468
|
+
return wantsWake
|
|
469
|
+
? runSqlite(true).catch((error) => {
|
|
470
|
+
if (error instanceof OutboxWakeFailedError) return runSqlite(false);
|
|
471
|
+
throw error;
|
|
472
|
+
})
|
|
473
|
+
: runSqlite(false);
|
|
474
|
+
}
|
|
475
|
+
const run = (wakes: boolean): Promise<OutboxDeliveredResult[]> => {
|
|
476
|
+
// The claims go as one JSON parameter, so the statement's text is the same however many it settles: a server
|
|
477
|
+
// that keeps prepared statements, and pg_stat_statements, see one statement, not one per count (#6560). Each
|
|
478
|
+
// row is found by its key, then checked against its claim.
|
|
479
|
+
const write: SqliteStatement = {
|
|
480
|
+
sql: `WITH claims AS MATERIALIZED (
|
|
481
|
+
SELECT c ->> 0 AS message_id, c ->> 1 AS claim_token, c ->> 2 AS claimant_id,
|
|
482
|
+
(c ->> 3)::int AS wake
|
|
483
|
+
FROM jsonb_array_elements(?::jsonb) AS c
|
|
484
|
+
), updated AS (
|
|
485
|
+
UPDATE ${table} SET state = 'delivered', ${settled}
|
|
486
|
+
WHERE ${lockedClaimsWhere}
|
|
487
|
+
RETURNING ${columns}
|
|
488
|
+
), recorded AS MATERIALIZED (
|
|
489
|
+
SELECT
|
|
490
|
+
set_config('${SETTLE_UNMATCHED}', COALESCE((
|
|
491
|
+
SELECT jsonb_agg(c.message_id)::text FROM claims c
|
|
492
|
+
WHERE NOT EXISTS (SELECT 1 FROM updated u WHERE u.message_id = c.message_id)
|
|
493
|
+
), ''), true) AS unmatched,
|
|
494
|
+
set_config('${SETTLE_WAKE}', COALESCE((
|
|
495
|
+
SELECT jsonb_agg(jsonb_build_array(origin_broker_id, max_sequence))::text
|
|
496
|
+
FROM (
|
|
497
|
+
SELECT u.origin_broker_id, MAX(u.sequence) AS max_sequence
|
|
498
|
+
FROM updated u
|
|
499
|
+
JOIN claims c ON c.message_id = u.message_id
|
|
500
|
+
WHERE c.wake = 1 AND u.origin_broker_id <> c.claimant_id
|
|
501
|
+
GROUP BY u.origin_broker_id
|
|
502
|
+
) AS origins
|
|
503
|
+
), ''), true) AS wake_hints
|
|
504
|
+
)
|
|
505
|
+
SELECT updated.*
|
|
506
|
+
FROM recorded LEFT JOIN updated ON TRUE`,
|
|
507
|
+
params: [
|
|
508
|
+
JSON.stringify(
|
|
509
|
+
entries.map(({ claim, wakeOrigin }) => [
|
|
510
|
+
claim.messageId,
|
|
511
|
+
claim.token,
|
|
512
|
+
claim.claimantId,
|
|
513
|
+
wakes && wakeOrigin ? 1 : 0,
|
|
514
|
+
]),
|
|
515
|
+
),
|
|
516
|
+
null,
|
|
517
|
+
],
|
|
518
|
+
};
|
|
519
|
+
// Locks the hint log without waiting and writes one outcome hint per distinct remote origin broker; a hint
|
|
520
|
+
// log held locked by another session leaves the settlement intact without its hints (#6715).
|
|
521
|
+
const writeHints: SqliteStatement = {
|
|
522
|
+
sql: `DO $atomic_settle$ BEGIN
|
|
523
|
+
IF COALESCE(current_setting('${SETTLE_WAKE}', true), '') <> '' THEN
|
|
524
|
+
LOCK TABLE ${wakeups} IN ROW EXCLUSIVE MODE NOWAIT;
|
|
525
|
+
INSERT INTO ${wakeups}(broker_id, reason, version, created_at)
|
|
526
|
+
SELECT h ->> 0, 'outcome', (h ->> 1)::bigint, ${nowMs}
|
|
527
|
+
FROM jsonb_array_elements(current_setting('${SETTLE_WAKE}', true)::jsonb) AS h;
|
|
528
|
+
PERFORM set_config('${SETTLE_HINT}', 'written', true);
|
|
529
|
+
END IF;
|
|
530
|
+
EXCEPTION WHEN lock_not_available THEN NULL;
|
|
531
|
+
END $atomic_settle$`,
|
|
532
|
+
params: [],
|
|
533
|
+
};
|
|
534
|
+
const hintRead: SqliteStatement = {
|
|
535
|
+
sql: `SELECT COALESCE(current_setting('${SETTLE_HINT}', true), '') AS written`,
|
|
536
|
+
params: [],
|
|
537
|
+
};
|
|
538
|
+
const readOthers: SqliteStatement = {
|
|
539
|
+
sql: `SELECT ${columns} FROM ${table}
|
|
540
|
+
WHERE message_id = ANY(ARRAY(
|
|
541
|
+
SELECT jsonb_array_elements_text(
|
|
542
|
+
COALESCE(NULLIF(current_setting('${SETTLE_UNMATCHED}', true), ''), '[]')::jsonb
|
|
543
|
+
)
|
|
544
|
+
))`,
|
|
545
|
+
params: [],
|
|
546
|
+
};
|
|
547
|
+
const leading = wakes ? [write, writeHints, hintRead, readOthers] : [write, readOthers];
|
|
548
|
+
return database
|
|
549
|
+
.transaction(
|
|
550
|
+
async (executor) => {
|
|
551
|
+
const written = new Map(
|
|
552
|
+
(await executor.all<OutboxRecord>(write.sql, ...write.params))
|
|
553
|
+
.filter((record) => record.message_id !== null)
|
|
554
|
+
.map((record) => [record.message_id, record]),
|
|
555
|
+
);
|
|
556
|
+
let hintWritten = false;
|
|
557
|
+
if (wakes) {
|
|
558
|
+
await executor.run(writeHints.sql).catch((cause: unknown) => {
|
|
559
|
+
throw new OutboxWakeFailedError(cause);
|
|
560
|
+
});
|
|
561
|
+
const hintRow = await executor.get<SqliteRow & { written: string }>(hintRead.sql);
|
|
562
|
+
hintWritten = hintRow?.written === "written";
|
|
563
|
+
}
|
|
564
|
+
const found = new Map(
|
|
565
|
+
(await executor.all<OutboxRecord>(readOthers.sql)).map((record) => [record.message_id, record]),
|
|
566
|
+
);
|
|
567
|
+
return entries.map(({ claim, wakeOrigin }): OutboxDeliveredResult => {
|
|
568
|
+
const delivered = written.get(claim.messageId);
|
|
569
|
+
if (delivered !== undefined) {
|
|
570
|
+
const woke =
|
|
571
|
+
hintWritten && wakeOrigin && delivered.origin_broker_id !== claim.claimantId
|
|
572
|
+
? delivered.origin_broker_id
|
|
573
|
+
: undefined;
|
|
574
|
+
return { status: "delivered", row: toRow(delivered), ...(woke === undefined ? {} : { woke }) };
|
|
575
|
+
}
|
|
576
|
+
const record = found.get(claim.messageId);
|
|
577
|
+
if (record === undefined) return { status: "unknown" };
|
|
578
|
+
if (isSettled(record)) return { status: "settled", row: toRow(record) };
|
|
579
|
+
return { status: "stale" };
|
|
580
|
+
});
|
|
581
|
+
},
|
|
582
|
+
{ ...fenced, leading, leadingOnly: true },
|
|
583
|
+
)
|
|
584
|
+
.then((results) => {
|
|
585
|
+
const notifications = database.notifications;
|
|
586
|
+
if (notifications !== undefined) {
|
|
587
|
+
const brokers = new Set<string>();
|
|
588
|
+
for (const result of results)
|
|
589
|
+
if (result.status === "delivered" && result.woke !== undefined) brokers.add(result.woke);
|
|
590
|
+
for (const brokerId of brokers)
|
|
591
|
+
for (const { sql, params } of wakeUpNotices(notifications, wakeups, leases, brokerId))
|
|
592
|
+
void database.run(sql, ...params).catch(() => {});
|
|
593
|
+
}
|
|
594
|
+
return results;
|
|
595
|
+
});
|
|
596
|
+
};
|
|
597
|
+
return wantsWake
|
|
598
|
+
? run(true).catch((error) => {
|
|
599
|
+
if (error instanceof OutboxWakeFailedError) return run(false);
|
|
600
|
+
throw error;
|
|
601
|
+
})
|
|
602
|
+
: run(false);
|
|
603
|
+
};
|
|
604
|
+
|
|
298
605
|
/**
|
|
299
|
-
*
|
|
300
|
-
* locks
|
|
301
|
-
*
|
|
606
|
+
* Renews each of `claims` in one transaction: one UPDATE that matches each row against an exact `(message_id,
|
|
607
|
+
* claim_token, claimant_id)` triple, locks the rows in sequence order on PostgreSQL so it never waits in a cycle with
|
|
608
|
+
* claims or settlements, and updates only claims still current. On PostgreSQL the update, a gated follow-up read for
|
|
609
|
+
* misses, and the commit go in one round trip. Like `renewClaim`, its commit does not wait for the disk: the next
|
|
610
|
+
* renewal repeats one a server crash lost (#6560, #6712).
|
|
302
611
|
*/
|
|
303
|
-
const
|
|
304
|
-
const
|
|
305
|
-
|
|
612
|
+
const renewClaims = async (claims: readonly OutboxClaim[]): Promise<OutboxRenewClaimResult[]> => {
|
|
613
|
+
const results: (OutboxRenewClaimResult | undefined)[] = claims.map((claim) =>
|
|
614
|
+
claim.messageId.length === 0
|
|
615
|
+
? invalid("empty-message-id")
|
|
616
|
+
: claim.claimantId.length === 0
|
|
617
|
+
? invalid("empty-claimant-id")
|
|
618
|
+
: undefined,
|
|
619
|
+
);
|
|
620
|
+
const valid = claims.filter((_, index) => results[index] === undefined);
|
|
621
|
+
if (valid.length === 0) return results as OutboxRenewClaimResult[];
|
|
622
|
+
const key = (messageId: string, token: string, claimantId: string) =>
|
|
623
|
+
JSON.stringify([messageId, token, claimantId]);
|
|
624
|
+
const answer = (
|
|
625
|
+
renewed: ReadonlySet<string>,
|
|
626
|
+
found: ReadonlyMap<string, OutboxRecord>,
|
|
627
|
+
): OutboxRenewClaimResult[] =>
|
|
628
|
+
claims.map((claim, index): OutboxRenewClaimResult => {
|
|
629
|
+
const checked = results[index];
|
|
630
|
+
if (checked !== undefined) return checked;
|
|
631
|
+
if (renewed.has(key(claim.messageId, claim.token, claim.claimantId))) return renewedAnswer();
|
|
632
|
+
const record = found.get(claim.messageId);
|
|
633
|
+
if (record === undefined) return { status: "unknown" };
|
|
634
|
+
if (isSettled(record)) return { status: "settled", row: toRow(record) };
|
|
635
|
+
return { status: "stale" };
|
|
636
|
+
});
|
|
637
|
+
if (dialect === "postgres") {
|
|
638
|
+
const write: SqliteStatement = {
|
|
639
|
+
sql: `${claimsCte}, renewed AS (
|
|
640
|
+
UPDATE ${table} SET claim_renewed_at = ${nowMs}
|
|
641
|
+
WHERE ${lockedClaimsWhere}
|
|
642
|
+
RETURNING message_id, claim_token, claimant_id
|
|
643
|
+
), gate AS MATERIALIZED (
|
|
644
|
+
SELECT set_config('${RENEW_MISSES}', CASE WHEN (SELECT COUNT(*) FROM renewed) < CAST(? AS ${types.int}) THEN '1' ELSE '' END, true) AS misses
|
|
645
|
+
)
|
|
646
|
+
SELECT renewed.message_id, renewed.claim_token, renewed.claimant_id
|
|
647
|
+
FROM gate LEFT JOIN renewed ON TRUE`,
|
|
648
|
+
params: [claimTriples(valid), valid.length],
|
|
649
|
+
};
|
|
650
|
+
const readMisses: SqliteStatement = {
|
|
651
|
+
sql: `SELECT ${columns} FROM ${table}
|
|
652
|
+
WHERE current_setting('${RENEW_MISSES}', true) = '1'
|
|
653
|
+
AND ${messageIdIn(`SELECT value FROM ${jsonValues("?")}`)}`,
|
|
654
|
+
params: [JSON.stringify(valid.map((claim) => claim.messageId))],
|
|
655
|
+
};
|
|
656
|
+
return database.transaction(
|
|
657
|
+
async (executor) => {
|
|
658
|
+
const renewed = new Set<string>();
|
|
659
|
+
for (const row of await executor.all<
|
|
660
|
+
SqliteRow & { message_id: string | null; claim_token: string | null; claimant_id: string | null }
|
|
661
|
+
>(write.sql, ...write.params))
|
|
662
|
+
if (row.message_id !== null && row.claim_token !== null && row.claimant_id !== null)
|
|
663
|
+
renewed.add(key(row.message_id, row.claim_token, row.claimant_id));
|
|
664
|
+
const found = new Map(
|
|
665
|
+
(await executor.all<OutboxRecord>(readMisses.sql, ...readMisses.params)).map((record) => [
|
|
666
|
+
record.message_id,
|
|
667
|
+
record,
|
|
668
|
+
]),
|
|
669
|
+
);
|
|
670
|
+
return answer(renewed, found);
|
|
671
|
+
},
|
|
672
|
+
{ ...fenced, leading: [write, readMisses], leadingOnly: true, relaxedDurability: true },
|
|
673
|
+
);
|
|
674
|
+
}
|
|
306
675
|
const write: SqliteStatement = {
|
|
307
|
-
sql:
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
RETURNING ${columns}`,
|
|
313
|
-
params: [null, ...keys, ...keys],
|
|
676
|
+
sql: `${claimsCte}
|
|
677
|
+
UPDATE ${table} SET claim_renewed_at = ${nowMs}
|
|
678
|
+
WHERE ${lockedClaimsWhere}
|
|
679
|
+
RETURNING message_id, claim_token, claimant_id`,
|
|
680
|
+
params: [claimTriples(valid)],
|
|
314
681
|
};
|
|
315
682
|
return database.transaction(
|
|
316
683
|
async (executor) => {
|
|
317
|
-
const
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
684
|
+
const renewed = new Set<string>();
|
|
685
|
+
for (const row of await executor.all<
|
|
686
|
+
SqliteRow & { message_id: string; claim_token: string; claimant_id: string }
|
|
687
|
+
>(write.sql, ...write.params))
|
|
688
|
+
renewed.add(key(row.message_id, row.claim_token, row.claimant_id));
|
|
689
|
+
const others = valid.filter((claim) => !renewed.has(key(claim.messageId, claim.token, claim.claimantId)));
|
|
321
690
|
const found =
|
|
322
691
|
others.length === 0
|
|
323
692
|
? new Map<string, OutboxRecord>()
|
|
324
693
|
: new Map(
|
|
325
694
|
(
|
|
326
695
|
await executor.all<OutboxRecord>(
|
|
327
|
-
`SELECT ${columns} FROM ${table} WHERE
|
|
328
|
-
|
|
696
|
+
`SELECT ${columns} FROM ${table} WHERE ${messageIdIn(`SELECT value FROM ${jsonValues("?")}`)}`,
|
|
697
|
+
JSON.stringify(others.map((claim) => claim.messageId)),
|
|
329
698
|
)
|
|
330
699
|
).map((record) => [record.message_id, record]),
|
|
331
700
|
);
|
|
332
|
-
return
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
701
|
+
return answer(renewed, found);
|
|
702
|
+
},
|
|
703
|
+
{ ...fenced, leading: [write], relaxedDurability: true },
|
|
704
|
+
);
|
|
705
|
+
};
|
|
706
|
+
|
|
707
|
+
const claimKey = (messageId: string, token: string, claimantId: string) =>
|
|
708
|
+
JSON.stringify([messageId, token, claimantId]);
|
|
709
|
+
const missColumns = `sequence, message_id, target_identity, origin_broker_id, digest,
|
|
710
|
+
CASE WHEN state IN ('delivered', 'failed') THEN frame_json ELSE '' END AS frame_json,
|
|
711
|
+
state, claim_attempts, claimant_id, claim_token, failure_reason,
|
|
712
|
+
CASE WHEN claim_renewed_at IS NULL THEN NULL ELSE ${ageSince("claim_renewed_at")} END AS claim_age,
|
|
713
|
+
CASE WHEN saving_at IS NULL THEN NULL ELSE ${ageSince("saving_at")} END AS saving_age`;
|
|
714
|
+
const releaseAssignments = (unwritten: boolean) => {
|
|
715
|
+
const attempts = unwritten ? `, claim_attempts = ${greatest("0", "claim_attempts - 1")}` : "";
|
|
716
|
+
return `state = 'queued', claimant_id = NULL, claim_token = NULL, claim_renewed_at = NULL, saving_at = NULL${attempts}`;
|
|
717
|
+
};
|
|
718
|
+
|
|
719
|
+
/**
|
|
720
|
+
* Releases each of `claims` in one durable transaction, locking matching rows in sequence order as claims, renewals
|
|
721
|
+
* and settlements do so none waits for another in a cycle, and matching each row by its full `(message_id,
|
|
722
|
+
* claim_token, claimant_id)` tuple. On PostgreSQL, the update and conditional miss lookup go out together with
|
|
723
|
+
* `BEGIN` and `COMMIT` (`leadingOnly: true`), so releasing any number of claims takes one round trip (#6713).
|
|
724
|
+
*/
|
|
725
|
+
const releaseClaims = async (
|
|
726
|
+
claims: readonly OutboxClaim[],
|
|
727
|
+
releaseOptions?: { readonly unwritten?: boolean },
|
|
728
|
+
): Promise<OutboxReleaseClaimResult[]> => {
|
|
729
|
+
if (claims.length === 0) return [];
|
|
730
|
+
const results: (OutboxReleaseClaimResult | undefined)[] = claims.map((claim) =>
|
|
731
|
+
claim.messageId.length === 0
|
|
732
|
+
? invalid("empty-message-id")
|
|
733
|
+
: claim.claimantId.length === 0
|
|
734
|
+
? invalid("empty-claimant-id")
|
|
735
|
+
: undefined,
|
|
736
|
+
);
|
|
737
|
+
const valid: { readonly claim: OutboxClaim; readonly index: number }[] = [];
|
|
738
|
+
claims.forEach((claim, index) => {
|
|
739
|
+
if (results[index] === undefined) valid.push({ claim, index });
|
|
740
|
+
});
|
|
741
|
+
if (valid.length === 0) return results as OutboxReleaseClaimResult[];
|
|
742
|
+
const assignments = releaseAssignments(releaseOptions?.unwritten === true);
|
|
743
|
+
const classifyMiss = (record: OutboxRecord | undefined): OutboxReleaseClaimResult => {
|
|
744
|
+
if (record === undefined) return { status: "unknown" };
|
|
745
|
+
if (isSettled(record)) return { status: "settled", row: toRow(record) };
|
|
746
|
+
return { status: "stale" };
|
|
747
|
+
};
|
|
748
|
+
if (dialect === "postgres") {
|
|
749
|
+
const write: SqliteStatement = {
|
|
750
|
+
sql: `${claimsCte}, released AS (
|
|
751
|
+
UPDATE ${table} AS outbox SET ${assignments}
|
|
752
|
+
FROM (SELECT DISTINCT message_id, claim_token, claimant_id FROM claims) AS matched
|
|
753
|
+
WHERE outbox.message_id = ANY(ARRAY(
|
|
754
|
+
SELECT message_id FROM ${table}
|
|
755
|
+
WHERE state = 'claimed'
|
|
756
|
+
AND ${messageIdIn("SELECT message_id FROM claims")}
|
|
757
|
+
AND ${matchesClaim}
|
|
758
|
+
ORDER BY sequence${lockClause("update")}
|
|
759
|
+
))
|
|
760
|
+
AND outbox.state = 'claimed'
|
|
761
|
+
AND outbox.message_id = matched.message_id
|
|
762
|
+
AND outbox.claim_token = matched.claim_token
|
|
763
|
+
AND outbox.claimant_id = matched.claimant_id
|
|
764
|
+
RETURNING outbox.message_id, matched.claim_token, matched.claimant_id
|
|
765
|
+
), gate AS MATERIALIZED (
|
|
766
|
+
SELECT set_config('${RELEASE_MISSES}', CASE WHEN (SELECT COUNT(*) FROM released) < CAST(? AS ${types.int}) THEN '1' ELSE '' END, true) AS misses
|
|
767
|
+
)
|
|
768
|
+
SELECT released.message_id, released.claim_token, released.claimant_id
|
|
769
|
+
FROM gate LEFT JOIN released ON TRUE`,
|
|
770
|
+
params: [claimTriples(valid.map(({ claim }) => claim)), valid.length],
|
|
771
|
+
};
|
|
772
|
+
const readMisses: SqliteStatement = {
|
|
773
|
+
sql: `SELECT ${missColumns} FROM ${table}
|
|
774
|
+
WHERE current_setting('${RELEASE_MISSES}', true) = '1'
|
|
775
|
+
AND ${messageIdIn(`SELECT value FROM ${jsonValues("?")}`)}`,
|
|
776
|
+
params: [JSON.stringify([...new Set(valid.map(({ claim }) => claim.messageId))])],
|
|
777
|
+
};
|
|
778
|
+
return database.transaction(
|
|
779
|
+
async (executor) => {
|
|
780
|
+
const releasedRows = await executor.all<
|
|
781
|
+
SqliteRow & { message_id: string | null; claim_token: string | null; claimant_id: string | null }
|
|
782
|
+
>(write.sql, ...write.params);
|
|
783
|
+
const foundRows = await executor.all<OutboxRecord>(readMisses.sql, ...readMisses.params);
|
|
784
|
+
const releasedKeys = new Set<string>();
|
|
785
|
+
for (const row of releasedRows) {
|
|
786
|
+
if (row.message_id !== null && row.claim_token !== null && row.claimant_id !== null) {
|
|
787
|
+
releasedKeys.add(claimKey(row.message_id, row.claim_token, row.claimant_id));
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
const found = new Map(foundRows.map((record) => [record.message_id, record]));
|
|
791
|
+
return claims.map((claim, index): OutboxReleaseClaimResult => {
|
|
792
|
+
const checked = results[index];
|
|
793
|
+
if (checked !== undefined) return checked;
|
|
794
|
+
if (releasedKeys.delete(claimKey(claim.messageId, claim.token, claim.claimantId))) {
|
|
795
|
+
return { status: "released" };
|
|
796
|
+
}
|
|
797
|
+
return classifyMiss(found.get(claim.messageId));
|
|
798
|
+
});
|
|
799
|
+
},
|
|
800
|
+
{ ...fenced, leading: [write, readMisses], leadingOnly: true },
|
|
801
|
+
);
|
|
802
|
+
}
|
|
803
|
+
// SQLite: partition into distinct-messageId waves (a single wave for distinct inputs) inside one serialized
|
|
804
|
+
// transaction so RETURNING message_id uniquely identifies the matched input entry even for duplicate message ids.
|
|
805
|
+
const waves: { readonly claim: OutboxClaim; readonly index: number }[][] = [];
|
|
806
|
+
for (const entry of valid) {
|
|
807
|
+
let wave = waves.find((candidate) => !candidate.some((other) => other.claim.messageId === entry.claim.messageId));
|
|
808
|
+
if (wave === undefined) {
|
|
809
|
+
wave = [];
|
|
810
|
+
waves.push(wave);
|
|
811
|
+
}
|
|
812
|
+
wave.push(entry);
|
|
813
|
+
}
|
|
814
|
+
const writeWave = (wave: readonly { readonly claim: OutboxClaim; readonly index: number }[]): SqliteStatement => ({
|
|
815
|
+
sql: `${claimsCte}
|
|
816
|
+
UPDATE ${table} SET ${assignments}
|
|
817
|
+
WHERE ${lockedClaimsWhere}
|
|
818
|
+
RETURNING message_id`,
|
|
819
|
+
params: [claimTriples(wave.map(({ claim }) => claim))],
|
|
820
|
+
});
|
|
821
|
+
const firstWrite = writeWave(waves[0]!);
|
|
822
|
+
return database.transaction(
|
|
823
|
+
async (executor) => {
|
|
824
|
+
const releasedIndices = new Set<number>();
|
|
825
|
+
for (let waveIndex = 0; waveIndex < waves.length; waveIndex++) {
|
|
826
|
+
const wave = waves[waveIndex]!;
|
|
827
|
+
const write = waveIndex === 0 ? firstWrite : writeWave(wave);
|
|
828
|
+
const rows = await executor.all<SqliteRow & { message_id: string }>(write.sql, ...write.params);
|
|
829
|
+
const matchedIds = new Set(rows.map((row) => row.message_id));
|
|
830
|
+
for (const { claim, index } of wave) {
|
|
831
|
+
if (matchedIds.has(claim.messageId)) releasedIndices.add(index);
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
const missedIds = [
|
|
835
|
+
...new Set(valid.filter(({ index }) => !releasedIndices.has(index)).map(({ claim }) => claim.messageId)),
|
|
836
|
+
];
|
|
837
|
+
const found =
|
|
838
|
+
missedIds.length === 0
|
|
839
|
+
? new Map<string, OutboxRecord>()
|
|
840
|
+
: new Map(
|
|
841
|
+
(
|
|
842
|
+
await executor.all<OutboxRecord>(
|
|
843
|
+
`SELECT ${missColumns} FROM ${table} WHERE ${messageIdIn(`SELECT value FROM ${jsonValues("?")}`)}`,
|
|
844
|
+
JSON.stringify(missedIds),
|
|
845
|
+
)
|
|
846
|
+
).map((record) => [record.message_id, record]),
|
|
847
|
+
);
|
|
848
|
+
return claims.map((claim, index): OutboxReleaseClaimResult => {
|
|
849
|
+
const checked = results[index];
|
|
850
|
+
if (checked !== undefined) return checked;
|
|
851
|
+
if (releasedIndices.has(index)) return { status: "released" };
|
|
852
|
+
return classifyMiss(found.get(claim.messageId));
|
|
339
853
|
});
|
|
340
854
|
},
|
|
341
|
-
{ ...fenced, leading: [
|
|
855
|
+
{ ...fenced, leading: [firstWrite] },
|
|
342
856
|
);
|
|
343
857
|
};
|
|
344
858
|
|
|
345
859
|
/**
|
|
346
|
-
* The `markDelivered` calls waiting for the transaction that settles them, in the order they were made.
|
|
347
|
-
*
|
|
348
|
-
*
|
|
860
|
+
* The `markDelivered` calls waiting for the transaction that settles them, in the order they were made. Calls made
|
|
861
|
+
* while one transaction settles others go together in the next, sharing one transaction and its commit instead of
|
|
862
|
+
* running one transaction each: one transaction at a time, so each commits after every call made before it (#6560,
|
|
863
|
+
* #6716).
|
|
349
864
|
*/
|
|
350
865
|
const deliveries: {
|
|
351
866
|
readonly claim: OutboxClaim;
|
|
867
|
+
readonly wakeOrigin: boolean;
|
|
352
868
|
readonly resolve: (result: OutboxDeliveredResult) => void;
|
|
353
869
|
readonly reject: (error: unknown) => void;
|
|
354
870
|
}[] = [];
|
|
@@ -369,7 +885,9 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
|
|
|
369
885
|
rows.add(deliveries[count++]!.claim.messageId);
|
|
370
886
|
const batch = deliveries.splice(0, count);
|
|
371
887
|
try {
|
|
372
|
-
const results = await markDeliveredTogether(
|
|
888
|
+
const results = await markDeliveredTogether(
|
|
889
|
+
batch.map(({ claim, wakeOrigin }) => ({ claim, wakeOrigin })),
|
|
890
|
+
);
|
|
373
891
|
batch.forEach(({ resolve }, index) => resolve(results[index]!));
|
|
374
892
|
} catch (error) {
|
|
375
893
|
for (const { reject } of batch) reject(error);
|
|
@@ -379,7 +897,7 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
|
|
|
379
897
|
};
|
|
380
898
|
|
|
381
899
|
/**
|
|
382
|
-
* #4896: the recipient's undelivered rows and their frame bytes, read from `<table>
|
|
900
|
+
* #4896: the recipient's undelivered rows and their frame bytes, read from `<table>_undelivered` alone. Only rows an
|
|
383
901
|
* older broker wrote, without `frame_bytes`, are measured from their frames.
|
|
384
902
|
*/
|
|
385
903
|
const sizedTotalsStatement = (targetIdentity: string): SqliteStatement => ({
|
|
@@ -496,16 +1014,23 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
|
|
|
496
1014
|
const hint = async () => {
|
|
497
1015
|
// PostgreSQL: never wait behind another session's lock on the hint log; such a hint goes without. The hint
|
|
498
1016
|
// is a new row, so it needs no lock domain of its own (#6560): see `fencedPath("intercom-wakeup-hint")`.
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
1017
|
+
// Notified once it commits, as the wake-up bus's own hints are, so the host does not wait for its backup
|
|
1018
|
+
// poll (#6560); on Postgres the notifications go right behind the commit, outside it.
|
|
1019
|
+
const notifications = database.notifications;
|
|
1020
|
+
const statements: SqliteStatement[] = [
|
|
1021
|
+
...(dialect === "postgres" ? [{ sql: `LOCK TABLE ${wakeups} IN ROW EXCLUSIVE MODE NOWAIT`, params: [] }] : []),
|
|
1022
|
+
{
|
|
1023
|
+
sql: `INSERT INTO ${wakeups}(broker_id, reason, version, created_at, target_identity)
|
|
1024
|
+
VALUES (?, 'outbox', ?, ${nowMs}, ?)`,
|
|
1025
|
+
params: [host, Number(inserted.sequence), request.targetIdentity],
|
|
1026
|
+
},
|
|
1027
|
+
...(notifications === undefined ? [] : wakeUpNotices(notifications, wakeups, leases, host)),
|
|
1028
|
+
];
|
|
1029
|
+
// Together, in one round trip, on a pipelined transaction's own handle, which sends calls in the order they
|
|
1030
|
+
// are made: a lock refused aborts the transaction, so the insert after it fails too.
|
|
1031
|
+
if (finisherOf?.(executor) !== undefined)
|
|
1032
|
+
await Promise.all(statements.map(({ sql, params }) => executor.run(sql, ...params)));
|
|
1033
|
+
else for (const { sql, params } of statements) await executor.run(sql, ...params);
|
|
509
1034
|
};
|
|
510
1035
|
await hint().catch((cause: unknown) => {
|
|
511
1036
|
throw new OutboxWakeFailedError(cause);
|
|
@@ -519,15 +1044,208 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
|
|
|
519
1044
|
...(request.owed === true ? [] : [sizedTotalsStatement(request.targetIdentity)]),
|
|
520
1045
|
];
|
|
521
1046
|
|
|
1047
|
+
/**
|
|
1048
|
+
* PostgreSQL: a send in statements that the database decides alone, sent together with the transaction's start and
|
|
1049
|
+
* commit. The recipient's lock domain, taken with the start, is held while the server runs them and never across a
|
|
1050
|
+
* round trip to the broker, so sends to one busy recipient wait for each other only that long. Under the lock, as
|
|
1051
|
+
* `enqueueIn` and the guard decide it across round trips:
|
|
1052
|
+
* 1. `decide` reads the message's row and reservation and the recipient's queue, and records in the transaction whether
|
|
1053
|
+
* the queue has room for the row, and whether the send's earlier reservation goes because it has not.
|
|
1054
|
+
* 2. With a reservation, it is written only while no row of the message with another digest is queued, and either the
|
|
1055
|
+
* queue has room or the send's own row is queued already; a reservation of the message already there is left as it is.
|
|
1056
|
+
* 3. The row is inserted only while the queue has room and the send's digest holds the reservation. For a recipient its
|
|
1057
|
+
* sender found offline (`wakeHostWithinMs`), the insert also reads, and locks shared, the recipient's live presence,
|
|
1058
|
+
* as `enqueueIn` does, and records the broker holding it.
|
|
1059
|
+
* 4. With such a broker, a block locks the hint log without waiting and writes the hint, naming the broker and the row's
|
|
1060
|
+
* sequence, and records that it did: a hint log another session holds locked leaves the send without its hint, as
|
|
1061
|
+
* in `enqueueIn`, and fails nothing.
|
|
1062
|
+
* 5. A read of whether it did.
|
|
1063
|
+
* 6. A reservation the send wrote is deleted again when its row is not queued, and an earlier one when the queue was full.
|
|
1064
|
+
* 7. The message's row is read, to answer a send whose row was not inserted.
|
|
1065
|
+
* Each statement sees what every transaction that committed before it wrote, as each of `enqueueIn`'s does. The hint's
|
|
1066
|
+
* notification goes out after the commit, so the transaction ends without waiting for it.
|
|
1067
|
+
*/
|
|
1068
|
+
const enqueueAtOnce = (
|
|
1069
|
+
request: OutboxEnqueueRequest,
|
|
1070
|
+
reservation?: OutboxReservation,
|
|
1071
|
+
): Promise<OutboxEnqueueResult> | undefined => {
|
|
1072
|
+
const messageId = request.frame.message.id;
|
|
1073
|
+
if (request.targetIdentity.length === 0 || request.originBrokerId.length === 0 || messageId.length === 0)
|
|
1074
|
+
return undefined;
|
|
1075
|
+
const frameJson = JSON.stringify(request.frame);
|
|
1076
|
+
const frameBytes = Buffer.byteLength(frameJson);
|
|
1077
|
+
const queuedTotals =
|
|
1078
|
+
request.owed === true
|
|
1079
|
+
? { sql: "(SELECT 1) AS totals", params: [] as SqliteValue[] }
|
|
1080
|
+
: {
|
|
1081
|
+
sql: `(SELECT COUNT(*) AS row_count, COALESCE(SUM(frame_bytes), 0) + COALESCE((
|
|
1082
|
+
SELECT SUM(LENGTH(frame_json)) FROM ${table}
|
|
1083
|
+
WHERE target_identity = ? AND ${UNDELIVERED} AND frame_bytes IS NULL
|
|
1084
|
+
), 0) AS byte_count
|
|
1085
|
+
FROM ${table} WHERE target_identity = ? AND ${UNDELIVERED}) AS totals`,
|
|
1086
|
+
params: [request.targetIdentity, request.targetIdentity],
|
|
1087
|
+
};
|
|
1088
|
+
const room =
|
|
1089
|
+
request.owed === true
|
|
1090
|
+
? { sql: "1", params: [] as SqliteValue[] }
|
|
1091
|
+
: {
|
|
1092
|
+
sql: "CASE WHEN totals.row_count < ? AND totals.byte_count + ? <= ? THEN 1 ELSE 0 END",
|
|
1093
|
+
params: [OUTBOX_TARGET_MAX_ROWS, frameBytes, OUTBOX_TARGET_MAX_BYTES],
|
|
1094
|
+
};
|
|
1095
|
+
const holder = reservation?.holder ?? { sql: "SELECT CAST(NULL AS TEXT)", params: [] };
|
|
1096
|
+
const decide: SqliteStatement = {
|
|
1097
|
+
sql: `SELECT decided.room, decided.queued_digest, decided.reserved_digest,
|
|
1098
|
+
set_config('${SEND_ROOM}', CASE WHEN decided.room = 1 THEN 'room' ELSE 'full' END, true) AS room_gate,
|
|
1099
|
+
set_config('${SEND_FORGET}', CASE WHEN decided.room = 0 AND decided.queued_digest IS NULL
|
|
1100
|
+
AND decided.reserved_digest = ? THEN 'earlier' ELSE '' END, true) AS forget_gate
|
|
1101
|
+
FROM (
|
|
1102
|
+
SELECT ${room.sql} AS room, (SELECT digest FROM ${table} WHERE message_id = ?) AS queued_digest,
|
|
1103
|
+
(${holder.sql}) AS reserved_digest
|
|
1104
|
+
FROM ${queuedTotals.sql}
|
|
1105
|
+
) AS decided`,
|
|
1106
|
+
params: [reservation?.digest ?? null, ...room.params, messageId, ...holder.params, ...queuedTotals.params],
|
|
1107
|
+
};
|
|
1108
|
+
const hasRoom = `current_setting('${SEND_ROOM}', true) = 'room'`;
|
|
1109
|
+
const reserve = reservation?.reserveWhere(
|
|
1110
|
+
{
|
|
1111
|
+
sql: `NOT EXISTS (SELECT 1 FROM ${table} WHERE message_id = ? AND digest <> ?)
|
|
1112
|
+
AND (${hasRoom} OR EXISTS (SELECT 1 FROM ${table} WHERE message_id = ? AND digest = ?))`,
|
|
1113
|
+
params: [messageId, request.digest, messageId, request.digest],
|
|
1114
|
+
},
|
|
1115
|
+
`set_config('${SEND_FORGET}', 'new', true) AS reserved`,
|
|
1116
|
+
);
|
|
1117
|
+
const held = reservation?.held ?? { sql: "1 = 1", params: [] };
|
|
1118
|
+
const wakes = request.wakeHostWithinMs !== undefined;
|
|
1119
|
+
// #5607: read in this transaction, under the row's insert, as `enqueueIn` reads it: see there.
|
|
1120
|
+
const presence = wakes
|
|
1121
|
+
? {
|
|
1122
|
+
sql: `, set_config('${SEND_WAKE}', COALESCE((
|
|
1123
|
+
SELECT presence.holder_id FROM ${leases} presence
|
|
1124
|
+
WHERE presence.kind = 'presence' AND presence.key = ? AND presence.holder_id IS NOT NULL
|
|
1125
|
+
AND ${greatest("0", `${nowMs} - presence.renewed_at`)} <= ?${lockClause("share")}
|
|
1126
|
+
), ''), true) AS presence_holder, set_config('${SEND_WAKE_VERSION}', CAST(sequence AS TEXT), true) AS hint_version,
|
|
1127
|
+
set_config('${SEND_WAKE_TARGET}', target_identity, true) AS hint_target`,
|
|
1128
|
+
params: [request.targetIdentity, request.wakeHostWithinMs!] as SqliteValue[],
|
|
1129
|
+
}
|
|
1130
|
+
: { sql: "", params: [] as SqliteValue[] };
|
|
1131
|
+
const insert: SqliteStatement = {
|
|
1132
|
+
sql: `INSERT INTO ${table}(message_id, target_identity, origin_broker_id, digest, frame_json, state, queued_at,
|
|
1133
|
+
frame_bytes)
|
|
1134
|
+
SELECT ?, ?, ?, ?, ?, 'queued', ${nowMs}, CAST(? AS ${types.int})
|
|
1135
|
+
WHERE ${hasRoom} AND ${held.sql}
|
|
1136
|
+
ON CONFLICT(message_id) DO NOTHING
|
|
1137
|
+
RETURNING ${columns}${presence.sql}`,
|
|
1138
|
+
params: [
|
|
1139
|
+
messageId,
|
|
1140
|
+
request.targetIdentity,
|
|
1141
|
+
request.originBrokerId,
|
|
1142
|
+
request.digest,
|
|
1143
|
+
frameJson,
|
|
1144
|
+
frameBytes,
|
|
1145
|
+
...held.params,
|
|
1146
|
+
...presence.params,
|
|
1147
|
+
],
|
|
1148
|
+
};
|
|
1149
|
+
const woken = `COALESCE(current_setting('${SEND_WAKE}', true), '')`;
|
|
1150
|
+
// Locks the hint log and writes the hint only with such a broker, and never waits behind another session's lock on
|
|
1151
|
+
// the log: such a send goes without its hint (#5607). A hint is a new row, so it needs no lock domain of its own
|
|
1152
|
+
// (#6560): see `fencedPath("intercom-wakeup-hint")`. Even an insert of no row would wait for the log's lock, so the
|
|
1153
|
+
// insert is made in the block, only once the lock is held.
|
|
1154
|
+
const writeHint: SqliteStatement = {
|
|
1155
|
+
sql: `DO $atomic_send$ BEGIN
|
|
1156
|
+
IF ${woken} <> '' THEN
|
|
1157
|
+
LOCK TABLE ${wakeups} IN ROW EXCLUSIVE MODE NOWAIT;
|
|
1158
|
+
INSERT INTO ${wakeups}(broker_id, reason, version, created_at, target_identity)
|
|
1159
|
+
VALUES (${woken}, 'outbox', CAST(current_setting('${SEND_WAKE_VERSION}') AS BIGINT), ${nowMs},
|
|
1160
|
+
current_setting('${SEND_WAKE_TARGET}'));
|
|
1161
|
+
PERFORM set_config('${SEND_HINT}', 'written', true);
|
|
1162
|
+
END IF;
|
|
1163
|
+
EXCEPTION WHEN lock_not_available THEN NULL;
|
|
1164
|
+
END $atomic_send$`,
|
|
1165
|
+
params: [],
|
|
1166
|
+
};
|
|
1167
|
+
const hint: SqliteStatement = {
|
|
1168
|
+
sql: `SELECT ${woken} AS broker_id WHERE COALESCE(current_setting('${SEND_HINT}', true), '') = 'written'`,
|
|
1169
|
+
params: [],
|
|
1170
|
+
};
|
|
1171
|
+
const forget = reservation?.forgetWhere({
|
|
1172
|
+
sql: `current_setting('${SEND_FORGET}', true) = 'earlier' OR (current_setting('${SEND_FORGET}', true) = 'new'
|
|
1173
|
+
AND NOT EXISTS (SELECT 1 FROM ${table} WHERE message_id = ? AND digest = ?))`,
|
|
1174
|
+
params: [messageId, request.digest],
|
|
1175
|
+
});
|
|
1176
|
+
const queued = selectStatement(messageId);
|
|
1177
|
+
const leading = [
|
|
1178
|
+
decide,
|
|
1179
|
+
...(reserve === undefined ? [] : [reserve]),
|
|
1180
|
+
insert,
|
|
1181
|
+
...(wakes ? [writeHint, hint] : []),
|
|
1182
|
+
...(forget === undefined ? [] : [forget]),
|
|
1183
|
+
queued,
|
|
1184
|
+
];
|
|
1185
|
+
const answer = async (executor: SqliteExecutor): Promise<OutboxEnqueueResult> => {
|
|
1186
|
+
// In the order of `leading`, each answered with the transaction's start: no call waits for a round trip.
|
|
1187
|
+
const decided = (await executor.get<SqliteRow & { room: SqliteValue; reserved_digest: string | null }>(
|
|
1188
|
+
decide.sql,
|
|
1189
|
+
...decide.params,
|
|
1190
|
+
))!;
|
|
1191
|
+
if (reserve !== undefined) await executor.all(reserve.sql, ...reserve.params);
|
|
1192
|
+
const row = await executor.get<OutboxRecord>(insert.sql, ...insert.params);
|
|
1193
|
+
let woke: string | undefined;
|
|
1194
|
+
if (wakes) {
|
|
1195
|
+
// A database that cannot run the block (no PL/pgSQL for this role) writes the send again without its hint.
|
|
1196
|
+
await executor.run(writeHint.sql).catch((cause: unknown) => {
|
|
1197
|
+
throw new OutboxWakeFailedError(cause);
|
|
1198
|
+
});
|
|
1199
|
+
woke = (await executor.get<SqliteRow & { broker_id: string }>(hint.sql, ...hint.params))?.broker_id;
|
|
1200
|
+
}
|
|
1201
|
+
if (forget !== undefined) await executor.run(forget.sql, ...forget.params);
|
|
1202
|
+
const found = await executor.get<OutboxRecord>(queued.sql, ...queued.params);
|
|
1203
|
+
if (row !== undefined)
|
|
1204
|
+
return { status: "inserted", row: toRow(row), ...(woke === undefined ? {} : { woke }) } as const;
|
|
1205
|
+
// Another digest held the message's reservation: the send is refused, as before it wrote anything.
|
|
1206
|
+
if (decided.reserved_digest !== null && decided.reserved_digest !== reservation?.digest)
|
|
1207
|
+
return { status: "conflict", messageId };
|
|
1208
|
+
if (found !== undefined)
|
|
1209
|
+
return found.digest === request.digest
|
|
1210
|
+
? { status: "duplicate", row: toRow(found) }
|
|
1211
|
+
: { status: "conflict", messageId };
|
|
1212
|
+
if (Number(decided.room) === 0)
|
|
1213
|
+
return { status: "full", limit: OUTBOX_TARGET_MAX_ROWS, byteLimit: OUTBOX_TARGET_MAX_BYTES };
|
|
1214
|
+
return { status: "conflict", messageId };
|
|
1215
|
+
};
|
|
1216
|
+
return database
|
|
1217
|
+
.transaction(answer, {
|
|
1218
|
+
...recipientTransaction(database, options.prefix, request.targetIdentity),
|
|
1219
|
+
leading,
|
|
1220
|
+
leadingOnly: true,
|
|
1221
|
+
})
|
|
1222
|
+
.then((result) => {
|
|
1223
|
+
// Notified once the hint committed, on the host's own channel (and the shared one only for a host of an
|
|
1224
|
+
// earlier release), as the wake-up bus's own hints are, so the host does not wait for its backup poll
|
|
1225
|
+
// (#6560); the hint is there for its poll if a notification is lost.
|
|
1226
|
+
const notifications = database.notifications;
|
|
1227
|
+
if (result.status === "inserted" && result.woke !== undefined && notifications !== undefined) {
|
|
1228
|
+
const notices = wakeUpNotices(notifications, wakeups, leases, result.woke);
|
|
1229
|
+
if (notifications.send !== undefined) void notifications.send(notices).catch(() => {});
|
|
1230
|
+
else for (const { sql, params } of notices) void database.run(sql, ...params).catch(() => {});
|
|
1231
|
+
}
|
|
1232
|
+
return result;
|
|
1233
|
+
});
|
|
1234
|
+
};
|
|
1235
|
+
|
|
1236
|
+
const enqueueAtOnceIfPostgres = (request: OutboxEnqueueRequest, reservation?: OutboxReservation) =>
|
|
1237
|
+
dialect === "postgres" ? enqueueAtOnce(request, reservation) : undefined;
|
|
1238
|
+
|
|
522
1239
|
return {
|
|
523
1240
|
enqueueIn,
|
|
524
1241
|
enqueueLeading,
|
|
1242
|
+
...(dialect === "postgres" ? { enqueueAtOnce } : {}),
|
|
525
1243
|
async enqueue(request) {
|
|
526
1244
|
if (request.targetIdentity.length === 0) return invalid("empty-target-identity");
|
|
527
1245
|
if (request.originBrokerId.length === 0) return invalid("empty-broker-id");
|
|
528
1246
|
if (request.frame.message.id.length === 0) return invalid("empty-message-id");
|
|
529
1247
|
return withoutFailedWake(request, (attempt) =>
|
|
530
|
-
database.transaction((executor) => enqueueIn(executor, attempt), {
|
|
1248
|
+
enqueueAtOnceIfPostgres(attempt) ?? database.transaction((executor) => enqueueIn(executor, attempt), {
|
|
531
1249
|
...recipientTransaction(database, options.prefix, attempt.targetIdentity),
|
|
532
1250
|
leading: enqueueLeading(attempt),
|
|
533
1251
|
}),
|
|
@@ -612,6 +1330,7 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
|
|
|
612
1330
|
return claimed(records.filter((record) => record.message_id !== null));
|
|
613
1331
|
},
|
|
614
1332
|
{
|
|
1333
|
+
...RETRY_UNAPPLIED,
|
|
615
1334
|
concurrency: { kind: "serial", domain: `${table}_claims:${targetIdentity}` },
|
|
616
1335
|
leading: [waiting, statement],
|
|
617
1336
|
leadingOnly: true,
|
|
@@ -619,7 +1338,7 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
|
|
|
619
1338
|
},
|
|
620
1339
|
);
|
|
621
1340
|
}
|
|
622
|
-
// SQLite
|
|
1341
|
+
// SQLite: a write statement takes the database's write lock even when it changes nothing, so a read
|
|
623
1342
|
// decides first, without it, whether there is anything to claim: empty scans (such as fan-out wake-up polls across
|
|
624
1343
|
// idle sessions) cost one read. Linearizable: if a row commits after this snapshot, its enqueue writes a new
|
|
625
1344
|
// wake-up hint. The same read answers a claim another claimant holds, or one of only the claimant's own rows in
|
|
@@ -665,23 +1384,29 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
|
|
|
665
1384
|
},
|
|
666
1385
|
|
|
667
1386
|
renewClaim(claim) {
|
|
668
|
-
|
|
1387
|
+
// Its claimant renews again within the renewal interval, far inside the claim's staleness limit: a renewal lost
|
|
1388
|
+
// in a crash of the database server leaves the claim a renewal older and still current, so its commit does not
|
|
1389
|
+
// wait for the disk.
|
|
1390
|
+
return withClaim(claim, `claim_renewed_at = ${nowMs}`, [], renewedAnswer, true);
|
|
669
1391
|
},
|
|
670
1392
|
|
|
1393
|
+
renewClaims,
|
|
1394
|
+
|
|
671
1395
|
reportSaving(claim) {
|
|
672
1396
|
return withClaim(claim, `saving_at = ${nowMs}`, [], () => ({ status: "renewed" }) as const);
|
|
673
1397
|
},
|
|
674
1398
|
|
|
675
1399
|
releaseClaim(claim, options) {
|
|
676
|
-
const attempts = options?.unwritten === true ? `, claim_attempts = ${greatest("0", "claim_attempts - 1")}` : "";
|
|
677
1400
|
return withClaim(
|
|
678
1401
|
claim,
|
|
679
|
-
|
|
1402
|
+
releaseAssignments(options?.unwritten === true),
|
|
680
1403
|
[],
|
|
681
1404
|
() => ({ status: "released" }) as const,
|
|
682
1405
|
);
|
|
683
1406
|
},
|
|
684
1407
|
|
|
1408
|
+
releaseClaims,
|
|
1409
|
+
|
|
685
1410
|
async releaseClaimsOf(claimantId) {
|
|
686
1411
|
// Its rows locked in sequence order, as a claim locks them, so the two never wait for each other (#6560).
|
|
687
1412
|
const { changes } = await database.run(
|
|
@@ -696,14 +1421,12 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
|
|
|
696
1421
|
return changes;
|
|
697
1422
|
},
|
|
698
1423
|
|
|
699
|
-
markDelivered(claim) {
|
|
700
|
-
if (
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
row: toRow(written),
|
|
704
|
-
}));
|
|
1424
|
+
markDelivered(claim, options) {
|
|
1425
|
+
if (claim.messageId.length === 0) return Promise.resolve(invalid("empty-message-id"));
|
|
1426
|
+
if (claim.claimantId.length === 0) return Promise.resolve(invalid("empty-claimant-id"));
|
|
1427
|
+
const wakeOrigin = options?.wakeOrigin === true;
|
|
705
1428
|
return new Promise<OutboxDeliveredResult>((resolve, reject) => {
|
|
706
|
-
deliveries.push({ claim, resolve, reject });
|
|
1429
|
+
deliveries.push({ claim, wakeOrigin, resolve, reject });
|
|
707
1430
|
if (delivering) return;
|
|
708
1431
|
delivering = true;
|
|
709
1432
|
void deliverQueued();
|
|
@@ -728,10 +1451,22 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
|
|
|
728
1451
|
return { status: "listed", rows: (await undelivered(database, targetIdentity, limit)).map(toRow) };
|
|
729
1452
|
},
|
|
730
1453
|
|
|
1454
|
+
async withUndelivered(targetIdentities) {
|
|
1455
|
+
if (targetIdentities.length === 0) return new Set<string>();
|
|
1456
|
+
// One lookup of `<outbox>_undelivered` per recipient, its ids as one JSON parameter, so the text is the same however
|
|
1457
|
+
// many there are. No lock, and no row or frame read (#6560).
|
|
1458
|
+
const found = await database.all<SqliteRow & { readonly target_identity: string }>(
|
|
1459
|
+
`SELECT value AS target_identity FROM ${jsonValues("?")}
|
|
1460
|
+
WHERE EXISTS (SELECT 1 FROM ${table} WHERE target_identity = value AND ${UNDELIVERED})`,
|
|
1461
|
+
JSON.stringify(targetIdentities),
|
|
1462
|
+
);
|
|
1463
|
+
return new Set(found.map((row) => row.target_identity));
|
|
1464
|
+
},
|
|
1465
|
+
|
|
731
1466
|
async undeliveredPosition(targetIdentity, messageId) {
|
|
732
1467
|
if (targetIdentity.length === 0) return invalid("empty-target-identity");
|
|
733
1468
|
if (messageId.length === 0) return invalid("empty-message-id");
|
|
734
|
-
// Counted on
|
|
1469
|
+
// Counted on `<outbox>_undelivered`: no row, and no frame, is read.
|
|
735
1470
|
const counted = await database.get<{ position: SqliteValue }>(
|
|
736
1471
|
`SELECT COUNT(*) AS position FROM ${table}
|
|
737
1472
|
WHERE target_identity = ? AND ${UNDELIVERED} AND sequence <= (
|
|
@@ -746,11 +1481,16 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
|
|
|
746
1481
|
},
|
|
747
1482
|
|
|
748
1483
|
async prune(settledOlderThanMs, queuedOlderThanMs) {
|
|
1484
|
+
// Each age compared as `column < now - age`, so an index on the column answers it.
|
|
1485
|
+
const now = storeNow(database);
|
|
749
1486
|
if (queuedOlderThanMs !== undefined) {
|
|
750
1487
|
// Every recipient's rows, each locked in sequence order and decided on in its newest version, as a claim
|
|
751
|
-
// locks them: a renewal that commits first keeps its row, and expiry waits for no lock domain (#6560).
|
|
752
|
-
|
|
753
|
-
|
|
1488
|
+
// locks them: a renewal that commits first keeps its row, and expiry waits for no lock domain (#6560). PostgreSQL
|
|
1489
|
+
// takes the locked rows' ids as one array, so the update finds each by its key rather than joining the table.
|
|
1490
|
+
const lockedWhere = (where: string) => {
|
|
1491
|
+
const locked = `SELECT message_id FROM ${table} WHERE ${where} ORDER BY sequence${lockClause("update")}`;
|
|
1492
|
+
return dialect === "postgres" ? `message_id = ANY(ARRAY(${locked}))` : `message_id IN (${locked})`;
|
|
1493
|
+
};
|
|
754
1494
|
await database.transaction(async (executor) => {
|
|
755
1495
|
// A row an older broker queued has no time: its retention starts now.
|
|
756
1496
|
await executor.run(
|
|
@@ -759,8 +1499,8 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
|
|
|
759
1499
|
await executor.run(
|
|
760
1500
|
`UPDATE ${table} SET state = 'failed', ${settled}
|
|
761
1501
|
WHERE ${lockedWhere(
|
|
762
|
-
`${UNDELIVERED} AND ${
|
|
763
|
-
AND (claim_renewed_at IS NULL OR ${
|
|
1502
|
+
`${UNDELIVERED} AND queued_at < ${now} - ?
|
|
1503
|
+
AND (claim_renewed_at IS NULL OR claim_renewed_at < ${now} - ?)`,
|
|
764
1504
|
)}`,
|
|
765
1505
|
JSON.stringify(OUTBOX_EXPIRED_REASON),
|
|
766
1506
|
queuedOlderThanMs,
|
|
@@ -768,12 +1508,14 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
|
|
|
768
1508
|
);
|
|
769
1509
|
}, fenced);
|
|
770
1510
|
}
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
1511
|
+
// Oldest first, from `<outbox>_settled`, in batches.
|
|
1512
|
+
return deleteInBatches(database, {
|
|
1513
|
+
table,
|
|
1514
|
+
key: "sequence",
|
|
1515
|
+
where: `${SETTLED} AND settled_at < ${now} - ?`,
|
|
1516
|
+
params: [settledOlderThanMs],
|
|
1517
|
+
orderBy: "settled_at",
|
|
1518
|
+
});
|
|
777
1519
|
},
|
|
778
1520
|
};
|
|
779
1521
|
}
|