@bastani/atomic 0.10.10-alpha.2 → 0.10.11-alpha.1
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 +142 -0
- package/README.md +1 -1
- 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 +8 -10
- package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js.map +1 -1
- package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +6 -6
- package/dist/_shared/mode-shared-2QJSCUM6.js +52 -15
- package/dist/_shared/mode-shared-2QJSCUM6.js.map +1 -1
- package/dist/_shared/p1a-prewarm-XIU57JHF.js +3 -3
- package/dist/_shared/runtime-O4KCSG4C.js +3 -3
- package/dist/_shared/{sdk-RRLVN7ER.js → sdk-AVFII7NK.js} +757 -233
- package/dist/_shared/sdk-AVFII7NK.js.map +1 -0
- package/dist/_shared/session-data-AHTU7IS6.js +3 -3
- package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
- package/dist/_shared/{startup-0-0-4VG2G44V.js → startup-0-0-57KF6LZH.js} +94 -42
- package/dist/_shared/startup-0-0-57KF6LZH.js.map +1 -0
- package/dist/_shared/{startup-0-1-XTIL65D4.js → startup-0-1-GIY75K46.js} +75 -13
- package/dist/_shared/startup-0-1-GIY75K46.js.map +1 -0
- package/dist/_shared/startup-0-2-27OWFHV6.js +72 -7
- package/dist/_shared/startup-0-2-27OWFHV6.js.map +1 -1
- package/dist/_shared/startup-0-3-T4DVFYWX.js +4 -4
- package/dist/_shared/startup-0-4-ZMJV547D.js +4 -4
- package/dist/_shared/{startup-0-5-FD2P735I.js → startup-0-5-YDW47QX6.js} +27 -69
- package/dist/_shared/startup-0-5-YDW47QX6.js.map +1 -0
- package/dist/_shared/startup-10-0-TDQNBDDL.js +6 -6
- package/dist/_shared/startup-12-0-55AAXBJZ.js +3 -3
- package/dist/_shared/startup-14-0-MLX36RBG.js +4 -4
- package/dist/_shared/startup-15-0-YUKGAC63.js +31 -7
- package/dist/_shared/startup-15-0-YUKGAC63.js.map +1 -1
- package/dist/_shared/startup-15-1-4S7FLMNG.js +7 -6
- package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
- package/dist/_shared/startup-8-0-34CBHPZH.js +4 -4
- package/dist/_shared/{startup-8-1-4KANEHRA.js → startup-8-1-X32CYSXB.js} +1219 -714
- package/dist/_shared/startup-8-1-X32CYSXB.js.map +1 -0
- package/dist/_shared/storage-command-7MGXLJGZ.js +14 -8
- package/dist/_shared/storage-command-7MGXLJGZ.js.map +1 -1
- package/dist/_shared/task-reference-stream-JWMUZSJX.js +1 -1
- package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
- package/dist/_shared/tree-outline-MUEPK5B7.js +2 -2
- package/dist/builtin/intercom/CHANGELOG.md +24 -0
- package/dist/builtin/intercom/broker/broker.bundle.mjs +993 -362
- package/dist/builtin/intercom/broker/database-wake-up-bus.ts +103 -24
- package/dist/builtin/intercom/broker/multinode-router.ts +42 -21
- package/dist/builtin/intercom/broker/multinode-state-store.ts +22 -1
- package/dist/builtin/intercom/broker/open-broker-state.ts +82 -31
- package/dist/builtin/intercom/broker/paths.ts +8 -4
- package/dist/builtin/intercom/broker/released-asker-remote-replies.ts +18 -6
- package/dist/builtin/intercom/broker/sql-add-column.ts +4 -1
- package/dist/builtin/intercom/broker/sql-ended-child-queue-store.ts +65 -44
- package/dist/builtin/intercom/broker/sql-held-send-store.ts +11 -3
- package/dist/builtin/intercom/broker/sql-known-session-store.ts +24 -12
- package/dist/builtin/intercom/broker/sql-lease-store.ts +375 -65
- package/dist/builtin/intercom/broker/sql-outbox-store.ts +270 -101
- package/dist/builtin/intercom/broker/sql-pending-ask-store.ts +20 -9
- package/dist/builtin/intercom/broker/sql-released-ask-store.ts +14 -6
- package/dist/builtin/intercom/broker/sql-restoring-reservation-store.ts +27 -11
- package/dist/builtin/intercom/broker/sql-schema.ts +139 -1
- package/dist/builtin/intercom/broker/sql-sent-message-authority.ts +97 -34
- package/dist/builtin/intercom/index.bundle.mjs +11 -8
- 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/SKILL.md +1 -1
- package/dist/builtin/subagents/src/extension/index.bundle.mjs +62 -23
- package/dist/builtin/web-access/CHANGELOG.md +9 -0
- package/dist/builtin/web-access/index.bundle.mjs +1 -1
- package/dist/builtin/web-access/package.json +1 -1
- 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 +2 -2
- 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 +2 -2
- package/dist/cli/team-command.impl.js +3 -3
- package/dist/cli/team-command.js +3 -3
- package/dist/cli.js +2 -2
- package/dist/core/agent-session-methods.d.ts +3 -0
- package/dist/core/agent-session-methods.js.map +1 -1
- package/dist/core/agent-session.d.ts +1 -0
- package/dist/core/compaction/compactor.d.ts +2 -0
- package/dist/core/debug.impl.js +3 -3
- package/dist/core/debug.js +3 -3
- package/dist/core/export-html/card-projection.code.js +1 -1
- 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 +2 -2
- 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.code.js +1 -1
- 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 +2 -2
- package/dist/core/extensions/runner-context.js +3 -3
- package/dist/core/extensions/runner-context.js.map +1 -1
- package/dist/core/intercom-broker-control-host.code.js +1 -1
- 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/model-registry.js +1 -1
- package/dist/core/model-resolver-defaults.d.ts +3 -2
- 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/sdk.code.js +3 -4
- package/dist/core/sdk.impl.js +3 -3
- package/dist/core/sdk.js +3 -3
- package/dist/core/session-manager-core.d.ts +5 -2
- package/dist/core/session-manager-core.js +17 -13
- package/dist/core/session-manager-core.js.map +1 -1
- 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/storage/added-exports.d.ts +6 -0
- package/dist/core/storage/added-exports.js +16 -0
- package/dist/core/storage/added-exports.js.map +1 -0
- package/dist/core/storage/database.d.ts +16 -0
- package/dist/core/storage/database.js.map +1 -1
- package/dist/core/storage/fenced-paths.d.ts +47 -0
- package/dist/core/storage/fenced-paths.js +53 -0
- package/dist/core/storage/fenced-paths.js.map +1 -1
- package/dist/core/storage/file-identity.js +31 -2
- package/dist/core/storage/file-identity.js.map +1 -1
- package/dist/core/storage/index.d.ts +3 -0
- package/dist/core/storage/index.js +5 -2
- package/dist/core/storage/index.js.map +1 -1
- package/dist/core/storage/migrations.d.ts +22 -0
- package/dist/core/storage/migrations.js +55 -0
- package/dist/core/storage/migrations.js.map +1 -1
- package/dist/core/storage/node-sqlite-thread.js +19 -6
- package/dist/core/storage/node-sqlite-thread.js.map +1 -1
- package/dist/core/storage/node-sqlite.js +53 -4
- 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 +3 -2
- package/dist/core/storage/prefix.js +18 -2
- package/dist/core/storage/prefix.js.map +1 -1
- package/dist/core/storage/provider.js +2 -2
- package/dist/core/storage/schema-catalog.d.ts +42 -0
- package/dist/core/storage/schema-catalog.js +141 -0
- package/dist/core/storage/schema-catalog.js.map +1 -0
- package/dist/core/storage/selection.js +2 -2
- package/dist/core/storage/session/branch-fork-source.code.js +41 -20
- package/dist/core/storage/session/branch-fork-source.code.js.map +1 -1
- 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.code.js +1 -1
- 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 +3 -3
- 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-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 +176 -36
- 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-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-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 +2 -2
- 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 +5 -0
- 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-chat-records.d.ts +15 -0
- package/dist/core/storage/session/sql-session-store.code.js +1 -1
- package/dist/core/storage/session/sql-session-store.d.ts +102 -5
- package/dist/core/storage/session/sql-session-store.impl.js +4 -4
- package/dist/core/storage/session/sql-session-store.js +4 -4
- 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.code.js +1 -1
- 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/session/types.d.ts +14 -0
- package/dist/core/storage/sqlite-facade.d.ts +37 -5
- package/dist/core/storage/sqlite-facade.js +351 -18
- package/dist/core/storage/sqlite-facade.js.map +1 -1
- package/dist/core/storage/statement-sequence.d.ts +83 -0
- package/dist/core/storage/statement-sequence.js +21 -0
- package/dist/core/storage/statement-sequence.js.map +1 -1
- 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.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.code.js +1 -1
- 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/bash.d.ts +8 -4
- package/dist/core/tools/history-session.d.ts +5 -0
- package/dist/core/tools/history-tasks.d.ts +123 -0
- package/dist/core/tools/kill.d.ts +5 -2
- package/dist/core/tools/powershell.d.ts +2 -2
- package/dist/core/tools/read-url.code.js +3 -3
- package/dist/core/tools/read-url.impl.js +3 -3
- package/dist/core/tools/read-url.js +3 -3
- package/dist/core/tools/read.d.ts +12 -2
- package/dist/core/tools/resource-selectors.d.ts +2 -0
- package/dist/core/tools/search.d.ts +12 -2
- package/dist/core/worktree-snapshot/blob-store.d.ts +14 -2
- package/dist/core/worktree-snapshot/blob-store.js +69 -16
- 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/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 +2 -2
- 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.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/agent-panel.d.ts +1 -0
- 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/task-inspector.d.ts +2 -0
- package/dist/modes/interactive/components/user-message-selector-archive.code.js +1 -1
- 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/interactive-mode-helpers.d.ts +2 -2
- package/dist/modes/print-mode.js +1 -1
- package/dist/modes/rpc/agent-panel-bridge.d.ts +5 -0
- 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/0.js +1 -1
- package/dist/startup-stages/1.js +1 -1
- package/dist/startup-stages/10.js +1 -1
- package/dist/startup-stages/12.js +1 -1
- package/dist/startup-stages/2.js +8 -1
- package/dist/startup-stages/3.js +1 -6
- package/dist/startup-stages/5.js +1 -1
- package/dist/startup-stages/7.js +1 -5
- 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/docs/background-tasks.md +123 -23
- package/docs/compaction.md +18 -0
- package/docs/docs.json +2 -0
- package/docs/environment-variables.md +1 -1
- package/docs/getting-started/installation.md +9 -2
- package/docs/guides/postgres-pgbouncer.md +339 -0
- package/docs/guides/postgres-tuning.md +311 -0
- package/docs/guides/resume-on-any-machine.md +2 -2
- package/docs/guides.md +2 -0
- package/docs/index.md +1 -1
- package/docs/libraries/agent-core.md +1 -1
- package/docs/libraries/ai.md +2 -2
- package/docs/libraries/codemode.md +1 -1
- package/docs/libraries/storage-libsql.md +6 -1
- package/docs/libraries/storage-postgres.md +11 -6
- package/docs/libraries/tui.md +1 -1
- package/docs/libraries.md +2 -2
- package/docs/programmatic.md +1 -1
- package/docs/quickstart.md +1 -1
- package/docs/sdk/storage.md +1 -1
- package/docs/sdk/web-server.md +1 -3
- package/docs/sdk.md +1 -7
- package/docs/sessions.md +58 -2
- package/docs/settings.md +20 -1
- package/docs/skills/authoring.md +1 -1
- package/docs/skills.md +79 -6
- package/docs/storage.md +262 -12
- package/docs/subagents/reference.md +2 -2
- package/docs/subagents.md +4 -3
- package/docs/tools.md +44 -10
- package/docs/windows.md +1 -1
- package/package.json +9 -9
- package/dist/_shared/sdk-RRLVN7ER.js.map +0 -1
- package/dist/_shared/startup-0-0-4VG2G44V.js.map +0 -1
- package/dist/_shared/startup-0-1-XTIL65D4.js.map +0 -1
- package/dist/_shared/startup-0-5-FD2P735I.js.map +0 -1
- package/dist/_shared/startup-8-1-4KANEHRA.js.map +0 -1
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
export type { SnapshotIndexTables } from "../worktree-snapshot/blob-store.ts";
|
|
2
2
|
export { MemorySnapshotBlobStore, SqlSnapshotBlobStore, snapshotIndexTables } from "../worktree-snapshot/blob-store.ts";
|
|
3
3
|
export type { SnapshotBlob, SnapshotBlobStore } from "../worktree-snapshot/types.ts";
|
|
4
|
+
/** @internal How a transaction of a pipelined connection sends its last writes with its commit (#6560). */
|
|
5
|
+
export { transactionFinisher } from "./added-exports.js";
|
|
4
6
|
export type { FencedPathId, SqliteBatchOptions, SqliteDatabase, SqliteExecutor, SqliteRow, SqliteRunResult, SqliteStatement, SqliteTransactionOptions, SqliteValue, StorageDescriptor, StorageListenerState, StorageNotificationEvent, StorageNotificationSubscription, StorageNotifications, TransactionConcurrency, } from "./database.js";
|
|
5
7
|
export * from "./dialect.js";
|
|
6
8
|
export * from "./errors.js";
|
|
@@ -11,6 +13,7 @@ export { DEFAULT_GROUP_COMMIT_HOLD_MS, getWriterQueueDegradation, getWriterQueue
|
|
|
11
13
|
export { POSTGRES_HASHED_STORAGE_IDENTIFIER_SUFFIXES, POSTGRES_MAX_STORAGE_PREFIX_LENGTH, POSTGRES_STORAGE_IDENTIFIER_SUFFIXES, renderStorageIdentifiers, storageMigrationTable, validateStoragePrefix, } from "./prefix.js";
|
|
12
14
|
export * from "./provider.js";
|
|
13
15
|
export { assertStorageSchemaVersion, assertStoredSchemaVersion } from "./schema.js";
|
|
16
|
+
export * from "./schema-catalog.js";
|
|
14
17
|
export { getTeamProfile, type InMemorySecretRef, inMemorySecret, isPostgresUrl, joinTeam, LIBSQL_ADAPTER_PACKAGE, LOCAL_SESSIONS_STORAGE, leaveTeam, POSTGRES_ADAPTER_PACKAGE, REDACTED_SECRET, type StorageInputSelection, type StorageSettingsSelection, selectStorage, selectStorageAsync, TEAM_PREFIX_ENV, TEAM_PROFILE_ENV, TEAM_TOKEN_ENV, TEAM_TOKEN_FILE_ENV, TEAM_URL_ENV, type TeamProfileSelectionOptions, type TeamStorageSelection, teamProfileSelection, } from "./selection.js";
|
|
15
18
|
export type { ExpandedChildCall, ExpandedChildDetails } from "./session/expanded-child-details.js";
|
|
16
19
|
export declare function readExpandedChildDetails(...args: Parameters<typeof import("./session/expanded-child-details.js").readExpandedChildDetails>): Promise<import("./session/expanded-child-details.js").ExpandedChildDetails>;
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
export { MemorySnapshotBlobStore, SqlSnapshotBlobStore, snapshotIndexTables } from "../worktree-snapshot/blob-store.js";
|
|
2
|
+
/** @internal How a transaction of a pipelined connection sends its last writes with its commit (#6560). */
|
|
3
|
+
export { transactionFinisher } from "./added-exports.js";
|
|
2
4
|
export * from "./dialect.js";
|
|
3
5
|
export * from "./errors.js";
|
|
4
6
|
export * from "./fenced-paths.js";
|
|
@@ -8,6 +10,7 @@ export { DEFAULT_GROUP_COMMIT_HOLD_MS, getWriterQueueDegradation, getWriterQueue
|
|
|
8
10
|
export { POSTGRES_HASHED_STORAGE_IDENTIFIER_SUFFIXES, POSTGRES_MAX_STORAGE_PREFIX_LENGTH, POSTGRES_STORAGE_IDENTIFIER_SUFFIXES, renderStorageIdentifiers, storageMigrationTable, validateStoragePrefix, } from "./prefix.js";
|
|
9
11
|
export * from "./provider.js";
|
|
10
12
|
export { assertStorageSchemaVersion, assertStoredSchemaVersion } from "./schema.js";
|
|
13
|
+
export * from "./schema-catalog.js";
|
|
11
14
|
export { getTeamProfile, inMemorySecret, isPostgresUrl, joinTeam, LIBSQL_ADAPTER_PACKAGE, LOCAL_SESSIONS_STORAGE, leaveTeam, POSTGRES_ADAPTER_PACKAGE, REDACTED_SECRET, selectStorage, selectStorageAsync, TEAM_PREFIX_ENV, TEAM_PROFILE_ENV, TEAM_TOKEN_ENV, TEAM_TOKEN_FILE_ENV, TEAM_URL_ENV, teamProfileSelection, } from "./selection.js";
|
|
12
15
|
export async function readExpandedChildDetails(...args) {
|
|
13
16
|
return (await import("./session/expanded-child-details.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"))).readExpandedChildDetails(...args);
|
|
@@ -37,7 +40,7 @@ function __atomicOnDemandFailed(error, feature) {
|
|
|
37
40
|
return (async () => {
|
|
38
41
|
const root = new URL("../../", import.meta.url);
|
|
39
42
|
const releases = (globalThis[Symbol.for("atomic.in-place-update-release.v1")] ??= new Map());
|
|
40
|
-
const key = `${root.href}#0.10.
|
|
43
|
+
const key = `${root.href}#0.10.11-alpha.1`;
|
|
41
44
|
let release = releases.get(key);
|
|
42
45
|
if (release === undefined) {
|
|
43
46
|
const current = (async () => {
|
|
@@ -65,7 +68,7 @@ function __atomicOnDemandFailed(error, feature) {
|
|
|
65
68
|
} catch {
|
|
66
69
|
// No installation to read, as in a bundle of the package: the release the process runs decides.
|
|
67
70
|
}
|
|
68
|
-
const updatedTo = typeof installed === "string" && installed !== "0.10.
|
|
71
|
+
const updatedTo = typeof installed === "string" && installed !== "0.10.11-alpha.1" ? installed : running !== undefined && running.version !== "0.10.11-alpha.1" ? "0.10.11-alpha.1" : undefined;
|
|
69
72
|
if (updatedTo === undefined) throw error;
|
|
70
73
|
const application = typeof running?.name === "string" ? running.name : "atomic";
|
|
71
74
|
const restart = new Error(`${application} was updated to ${updatedTo} while this session was running; restart it to keep using ${feature}.`, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/core/storage/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/core/storage/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,oBAAoB,EAAE,mBAAmB,EA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AAC;AAChG,CAAC;AACD,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACzC,GAAG,IAA2F;IAE9F,OAAO,CAAC,MAAM,MAAM,CAAC,qCAAqC,CAAC,CAAC,CAAC,oBAAoB,CAAC,GAAG,IAAI,CAAC,CAAC;AAC5F,CAAC;AACD,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAC5C,GAAG,IAAoF;IAEvF,OAAO,CAAC,MAAM,MAAM,CAAC,2BAA2B,CAAC,CAAC,CAAC,uBAAuB,CAAC,GAAG,IAAI,CAAC,CAAC;AACrF,CAAC;AACD,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACzC,GAAG,IAAkF;IAErF,OAAO,CAAC,MAAM,MAAM,CAAC,4BAA4B,CAAC,CAAC,CAAC,oBAAoB,CAAC,GAAG,IAAI,CAAC,CAAC;AACnF,CAAC;AACD,mFAAmF;AACnF,MAAM,CAAC,KAAK,SAAS,CAAC,CAAC,kBAAkB,CACxC,GAAG,IAAgF;IAEnF,KAAK,CAAC,CAAC,CAAC,MAAM,MAAM,CAAC,4BAA4B,CAAC,CAAC,CAAC,kBAAkB,CAAC,GAAG,IAAI,CAAC,CAAC;AACjF,CAAC;AACD,MAAM,CAAC,KAAK,SAAS,CAAC,CAAC,wBAAwB,CAC9C,GAAG,IAAsF;IAEzF,KAAK,CAAC,CAAC,CAAC,MAAM,MAAM,CAAC,4BAA4B,CAAC,CAAC,CAAC,wBAAwB,CAAC,GAAG,IAAI,CAAC,CAAC;AACvF,CAAC;AAiCD,cAAc,oBAAoB,CAAC;AAanC,OAAO,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC","sourcesContent":["export type { SnapshotIndexTables } from \"../worktree-snapshot/blob-store.ts\";\nexport { MemorySnapshotBlobStore, SqlSnapshotBlobStore, snapshotIndexTables } from \"../worktree-snapshot/blob-store.ts\";\nexport type { SnapshotBlob, SnapshotBlobStore } from \"../worktree-snapshot/types.ts\";\n/** @internal How a transaction of a pipelined connection sends its last writes with its commit (#6560). */\nexport { transactionFinisher } from \"./added-exports.js\";\nexport type {\n\tFencedPathId,\n\tSqliteBatchOptions,\n\tSqliteDatabase,\n\tSqliteExecutor,\n\tSqliteRow,\n\tSqliteRunResult,\n\tSqliteStatement,\n\tSqliteTransactionOptions,\n\tSqliteValue,\n\tStorageDescriptor,\n\tStorageListenerState,\n\tStorageNotificationEvent,\n\tStorageNotificationSubscription,\n\tStorageNotifications,\n\tTransactionConcurrency,\n} from \"./database.js\";\nexport * from \"./dialect.js\";\nexport * from \"./errors.js\";\nexport * from \"./fenced-paths.js\";\nexport {\n\tclaimFileAtomically,\n\tclaimFileAtomicallyAsync,\n\tdefaultSessionDatabasePath,\n\tdefaultSessionDatabasePathAsync,\n\tdefaultSharedStoragePath,\n\tdefaultSharedStoragePathAsync,\n\treadClaimFile,\n\treadClaimFileAsync,\n\ttype StorageHomeSettings,\n\tsameDirectory,\n\tsameDirectoryAsync,\n\tstorageHomeDir,\n\tstorageHomeDirAsync,\n\tstoragePathBaseDir,\n\tstoragePathBaseDirAsync,\n\tworkflowsStorageDir,\n\tworkflowsStorageDirAsync,\n} from \"./file-identity.js\";\nexport * from \"./migrations.js\";\nexport {\n\tDEFAULT_GROUP_COMMIT_HOLD_MS,\n\tgetWriterQueueDegradation,\n\tgetWriterQueueStats,\n\topenNodeSqliteDatabase,\n\tsqliteFilePath,\n\ttype WriterQueueStats,\n\twrapNodeSqliteDatabase,\n} from \"./node-sqlite.js\";\nexport {\n\tPOSTGRES_HASHED_STORAGE_IDENTIFIER_SUFFIXES,\n\tPOSTGRES_MAX_STORAGE_PREFIX_LENGTH,\n\tPOSTGRES_STORAGE_IDENTIFIER_SUFFIXES,\n\trenderStorageIdentifiers,\n\tstorageMigrationTable,\n\tvalidateStoragePrefix,\n} from \"./prefix.js\";\nexport * from \"./provider.js\";\nexport { assertStorageSchemaVersion, assertStoredSchemaVersion } from \"./schema.js\";\nexport * from \"./schema-catalog.js\";\nexport {\n\tgetTeamProfile,\n\ttype InMemorySecretRef,\n\tinMemorySecret,\n\tisPostgresUrl,\n\tjoinTeam,\n\tLIBSQL_ADAPTER_PACKAGE,\n\tLOCAL_SESSIONS_STORAGE,\n\tleaveTeam,\n\tPOSTGRES_ADAPTER_PACKAGE,\n\tREDACTED_SECRET,\n\ttype StorageInputSelection,\n\ttype StorageSettingsSelection,\n\tselectStorage,\n\tselectStorageAsync,\n\tTEAM_PREFIX_ENV,\n\tTEAM_PROFILE_ENV,\n\tTEAM_TOKEN_ENV,\n\tTEAM_TOKEN_FILE_ENV,\n\tTEAM_URL_ENV,\n\ttype TeamProfileSelectionOptions,\n\ttype TeamStorageSelection,\n\tteamProfileSelection,\n} from \"./selection.js\";\nexport type { ExpandedChildCall, ExpandedChildDetails } from \"./session/expanded-child-details.js\";\nexport async function readExpandedChildDetails(\n\t...args: Parameters<typeof import(\"./session/expanded-child-details.js\").readExpandedChildDetails>\n) {\n\treturn (await import(\"./session/expanded-child-details.js\")).readExpandedChildDetails(...args);\n}\nexport async function readSavedChildLaunch(\n\t...args: Parameters<typeof import(\"./session/expanded-child-details.js\").readSavedChildLaunch>\n) {\n\treturn (await import(\"./session/expanded-child-details.js\")).readSavedChildLaunch(...args);\n}\nexport async function readSessionChildCatalog(\n\t...args: Parameters<typeof import(\"./session/child-reader.js\").readSessionChildCatalog>\n) {\n\treturn (await import(\"./session/child-reader.js\")).readSessionChildCatalog(...args);\n}\nexport async function findInSessionHistory(\n\t...args: Parameters<typeof import(\"./session/history-pages.js\").findInSessionHistory>\n) {\n\treturn (await import(\"./session/history-pages.js\")).findInSessionHistory(...args);\n}\n// Ordinary storage setup does not open a transcript reader or import its encoders.\nexport async function* readSessionHistory(\n\t...args: Parameters<typeof import(\"./session/history-pages.js\").readSessionHistory>\n) {\n\tyield* (await import(\"./session/history-pages.js\")).readSessionHistory(...args);\n}\nexport async function* readSessionHistoryChunks(\n\t...args: Parameters<typeof import(\"./session/history-pages.js\").readSessionHistoryChunks>\n) {\n\tyield* (await import(\"./session/history-pages.js\")).readSessionHistoryChunks(...args);\n}\nexport type {\n\tArchivedChildCatalogEntry,\n\tOversizedSessionEntry,\n\tSessionBlob,\n\tSessionCompactionPoint,\n\tSessionEntriesPage,\n\tSessionEntriesQuery,\n\tSessionEntryAt,\n\tSessionEntryRange,\n\tSessionEntrySizes,\n\tSessionForkWindow,\n\tSessionHistoryItem,\n\tSessionHistoryPage,\n\tSessionHistoryReadOptions,\n\tSessionHistoryTotals,\n\tSessionRecoveryState,\n\tSessionResume,\n\tSessionResumeRetainedSetting,\n\tSessionResumeRetainedSettings,\n\tSessionSearchCoverage,\n\tSessionSearchExtendOptions,\n\tSessionSearchIndex,\n\tSessionSearchText,\n\tSessionStateEntry,\n\tSessionStore,\n\tSessionStoredEntry,\n\tSessionTail,\n\tSessionTaskReferenceCandidate,\n\tSessionTaskReferenceDuplicatePage,\n\tSessionTaskReferenceDuplicateQuery,\n\tSessionUsageTotals,\n} from \"./session/types.js\";\nexport * from \"./sqlite-facade.js\";\nexport type {\n\tJoinTeamOptions,\n\tLeaveTeamOptions,\n\tTeamBrokerRestart,\n\tTeamJoinResult,\n\tTeamKeptSetting,\n\tTeamLeaveResult,\n\tTeamProfile,\n\tTeamProfileName,\n\tTeamProfileOptions,\n\tTeamSettingKey,\n} from \"./team.js\";\nexport { switchToWriteAheadLog } from \"./write-ahead-log.js\";\n"]}
|
|
@@ -70,6 +70,12 @@ export interface StorageSchemaSetup {
|
|
|
70
70
|
*/
|
|
71
71
|
readonly revision: number;
|
|
72
72
|
}
|
|
73
|
+
/**
|
|
74
|
+
* Whether the catalog an open in progress read (`withStorageSchemaCatalog`) records `schema.revision` for the
|
|
75
|
+
* store already, so {@link ensureStorageSchema} would run nothing: the store's open then skips its schema transaction
|
|
76
|
+
* and its lock (#6560). False outside such an open, on SQLite, and when the revision is not recorded.
|
|
77
|
+
*/
|
|
78
|
+
export declare function storageSchemaCurrent(database: SqliteDatabase, schema: StorageSchemaSetup): Promise<boolean>;
|
|
73
79
|
/**
|
|
74
80
|
* Runs `setup`, a store's idempotent schema statements (`CREATE … IF NOT EXISTS`, guarded `ALTER TABLE … ADD COLUMN`),
|
|
75
81
|
* in the caller's transaction `executor` unless the ledger already records `revision` for the store (#5218). On a
|
|
@@ -80,4 +86,20 @@ export interface StorageSchemaSetup {
|
|
|
80
86
|
* every time, as before.
|
|
81
87
|
*/
|
|
82
88
|
export declare function ensureStorageSchema(executor: SqliteExecutor, dialect: StorageDialect, schema: StorageSchemaSetup, setup: () => Promise<void>): Promise<void>;
|
|
89
|
+
/** What {@link ensureTableFillfactor} sets, and records under `schema:<domain>` in the ledger. */
|
|
90
|
+
export interface StorageFillfactorSetup extends StorageSchemaSetup {
|
|
91
|
+
/** The table, already prefixed. */
|
|
92
|
+
readonly table: string;
|
|
93
|
+
/** The percentage of each new page the table fills on insert, leaving the rest for updated row versions. */
|
|
94
|
+
readonly fillfactor: number;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Sets `setup.table`'s fillfactor on PostgreSQL, once per database, recorded in the ledger as `schema:<domain>`: each
|
|
98
|
+
* page then keeps room for a new version of the rows on it, so updates of rows that change no indexed column stay on
|
|
99
|
+
* their page as HOT updates and touch no index (#6560). It applies to the pages written from then on; `VACUUM FULL`
|
|
100
|
+
* or pg_repack rewrites the existing ones with it. Nothing runs where the catalog an open read records the step, where
|
|
101
|
+
* the table has a fillfactor already, or where this role does not own the table: a runtime role without DDL opens as
|
|
102
|
+
* before, and `atomic storage migrate`, run as the owner, sets it. Does nothing on SQLite and libSQL.
|
|
103
|
+
*/
|
|
104
|
+
export declare function ensureTableFillfactor(database: SqliteDatabase, setup: StorageFillfactorSetup): Promise<void>;
|
|
83
105
|
//# sourceMappingURL=migrations.d.ts.map
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { dialectOf } from "./dialect.js";
|
|
2
2
|
import { StorageConfigError, StorageSchemaVersionError } from "./errors.js";
|
|
3
|
+
import { schemaCatalogOf } from "./schema-catalog.js";
|
|
3
4
|
const DEFAULT_MIGRATION_TABLE = "atomic_migrations";
|
|
4
5
|
function checkSteps(steps) {
|
|
5
6
|
let previous = 0;
|
|
@@ -82,6 +83,13 @@ export async function applyStorageMigrations(database, domain, steps, options =
|
|
|
82
83
|
checkSteps(steps);
|
|
83
84
|
const dialect = dialectOf(database);
|
|
84
85
|
const table = options.table ?? DEFAULT_MIGRATION_TABLE;
|
|
86
|
+
const recorded = dialect.versionedMigrations ? await recordedInCatalog(database, table, domain) : undefined;
|
|
87
|
+
const supported = steps.at(-1)?.version ?? 0;
|
|
88
|
+
if (recorded !== undefined && recorded >= supported && supported > 0) {
|
|
89
|
+
if (recorded > supported && !options.acceptNewer)
|
|
90
|
+
throw new StorageSchemaVersionError(domain, recorded, supported);
|
|
91
|
+
return { applied: [], version: recorded };
|
|
92
|
+
}
|
|
85
93
|
return database.transaction(async (transaction) => {
|
|
86
94
|
if (dialect.versionedMigrations)
|
|
87
95
|
return applyVersioned(transaction, dialect, table, domain, steps, options.acceptNewer);
|
|
@@ -90,6 +98,16 @@ export async function applyStorageMigrations(database, domain, steps, options =
|
|
|
90
98
|
return { applied: steps.map((step) => step.version), version: steps.at(-1)?.version ?? 0 };
|
|
91
99
|
}, { retryTransientFailures: true, concurrency: { kind: "serial", domain: table } });
|
|
92
100
|
}
|
|
101
|
+
/**
|
|
102
|
+
* The version `table` records for `domain` in the catalog an open in progress read, or undefined outside one: an open
|
|
103
|
+
* that finds every step recorded neither locks nor runs a transaction, as the steps would change nothing (#6560).
|
|
104
|
+
*/
|
|
105
|
+
async function recordedInCatalog(database, table, domain) {
|
|
106
|
+
const catalog = await schemaCatalogOf(database, table);
|
|
107
|
+
if (catalog === undefined || !catalog.hasTable(table))
|
|
108
|
+
return undefined;
|
|
109
|
+
return catalog.recordedVersion(domain);
|
|
110
|
+
}
|
|
93
111
|
/**
|
|
94
112
|
* Migrates each of `migrations` in order, as {@link applyStorageMigrations} would, and resolves with each one's result.
|
|
95
113
|
* Where the dialect records no versions (SQLite), every step runs every time, so the domains share one transaction: one
|
|
@@ -166,6 +184,17 @@ async function underShortLockWaits(executor, setup) {
|
|
|
166
184
|
}
|
|
167
185
|
await executor.exec(`SET LOCAL lock_timeout = '${String(previous?.wait ?? "0").replaceAll("'", "''")}'`);
|
|
168
186
|
}
|
|
187
|
+
/**
|
|
188
|
+
* Whether the catalog an open in progress read (`withStorageSchemaCatalog`) records `schema.revision` for the
|
|
189
|
+
* store already, so {@link ensureStorageSchema} would run nothing: the store's open then skips its schema transaction
|
|
190
|
+
* and its lock (#6560). False outside such an open, on SQLite, and when the revision is not recorded.
|
|
191
|
+
*/
|
|
192
|
+
export async function storageSchemaCurrent(database, schema) {
|
|
193
|
+
if (!dialectOf(database).versionedMigrations)
|
|
194
|
+
return false;
|
|
195
|
+
const recorded = await recordedInCatalog(database, schema.ledger, `schema:${schema.domain}`);
|
|
196
|
+
return recorded !== undefined && recorded >= schema.revision;
|
|
197
|
+
}
|
|
169
198
|
/**
|
|
170
199
|
* Runs `setup`, a store's idempotent schema statements (`CREATE … IF NOT EXISTS`, guarded `ALTER TABLE … ADD COLUMN`),
|
|
171
200
|
* in the caller's transaction `executor` unless the ledger already records `revision` for the store (#5218). On a
|
|
@@ -198,4 +227,30 @@ export async function ensureStorageSchema(executor, dialect, schema, setup) {
|
|
|
198
227
|
await createLedger(executor, dialect, ledger);
|
|
199
228
|
await executor.run(`INSERT INTO ${ledger} (domain, version, applied_at) VALUES (?, ?, ${dialect.nowMs}) ON CONFLICT DO NOTHING`, key, revision);
|
|
200
229
|
}
|
|
230
|
+
/**
|
|
231
|
+
* Sets `setup.table`'s fillfactor on PostgreSQL, once per database, recorded in the ledger as `schema:<domain>`: each
|
|
232
|
+
* page then keeps room for a new version of the rows on it, so updates of rows that change no indexed column stay on
|
|
233
|
+
* their page as HOT updates and touch no index (#6560). It applies to the pages written from then on; `VACUUM FULL`
|
|
234
|
+
* or pg_repack rewrites the existing ones with it. Nothing runs where the catalog an open read records the step, where
|
|
235
|
+
* the table has a fillfactor already, or where this role does not own the table: a runtime role without DDL opens as
|
|
236
|
+
* before, and `atomic storage migrate`, run as the owner, sets it. Does nothing on SQLite and libSQL.
|
|
237
|
+
*/
|
|
238
|
+
export async function ensureTableFillfactor(database, setup) {
|
|
239
|
+
const dialect = dialectOf(database);
|
|
240
|
+
if (dialect.name !== "postgres" || database.readOnly === true)
|
|
241
|
+
return;
|
|
242
|
+
const { ledger, domain, revision, table, fillfactor } = setup;
|
|
243
|
+
const schema = { ledger, domain, revision };
|
|
244
|
+
if (await storageSchemaCurrent(database, schema))
|
|
245
|
+
return;
|
|
246
|
+
const found = await database.get(`SELECT pg_catalog.pg_has_role(current_user, c.relowner, 'USAGE') AS owned,
|
|
247
|
+
coalesce(array_to_string(c.reloptions, ',') LIKE '%fillfactor=%', false) AS tuned
|
|
248
|
+
FROM pg_catalog.pg_class c WHERE c.relnamespace = current_schema()::regnamespace AND c.relname = ?`, dialect.identifier(table));
|
|
249
|
+
const yes = (value) => value === true || Number(value) === 1;
|
|
250
|
+
if (found === undefined || yes(found.tuned) || !yes(found.owned))
|
|
251
|
+
return;
|
|
252
|
+
await database.transaction((tx) => ensureStorageSchema(tx, dialect, schema, async () => {
|
|
253
|
+
await tx.exec(`ALTER TABLE ${table} SET (fillfactor = ${Math.trunc(fillfactor)})`);
|
|
254
|
+
}), { retryTransientFailures: true, concurrency: { kind: "serial", domain: ledger } });
|
|
255
|
+
}
|
|
201
256
|
//# sourceMappingURL=migrations.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migrations.js","sourceRoot":"","sources":["../../../src/core/storage/migrations.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAuB,MAAM,cAAc,CAAC;AAC9D,OAAO,EAAE,kBAAkB,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AAgC5E,MAAM,uBAAuB,GAAG,mBAAmB,CAAC;AAEpD,SAAS,UAAU,CAAC,KAAsC;IAC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AAQ,CAAC,GAAG,CACjB,eAAe,MAAM,gDAAgD,OAAO,CAAC,KAAK,0BAA0B,EAC5G,GAAG,EACH,QAAQ,CACR,CAAC;AACH,CAAC","sourcesContent":["import type { SqliteDatabase, SqliteExecutor, SqliteRow } from \"./database.js\";\nimport { dialectOf, type StorageDialect } from \"./dialect.js\";\nimport { StorageConfigError, StorageSchemaVersionError } from \"./errors.js\";\n\n/** One version of a domain's schema. */\nexport interface StorageMigrationStep {\n\t/** A positive integer; a domain's steps are listed in increasing order. */\n\treadonly version: number;\n\t/**\n\t * Brings the schema from the previous version to this one. It may use only `transaction`: the runner may run the\n\t * whole migration again after a transient failure. On a dialect without `versionedMigrations` (SQLite) every step\n\t * runs each time, so its statements must be idempotent (`CREATE … IF NOT EXISTS`).\n\t */\n\tup(transaction: SqliteExecutor, dialect: StorageDialect): Promise<void>;\n}\n\nexport interface StorageMigrationOptions {\n\t/** The ledger table, already prefixed (`renderStorageIdentifiers`); default `atomic_migrations`. */\n\treadonly table?: string;\n\t/**\n\t * A recorded version newer than the last step is accepted, and nothing runs, instead of refusing with\n\t * `StorageSchemaVersionError`. Only for a domain whose later steps stay additive, so a build that knows fewer of\n\t * them still reads and writes it correctly (#5065).\n\t */\n\treadonly acceptNewer?: boolean;\n}\n\nexport interface StorageMigrationResult {\n\t/** The versions this call ran, in order. */\n\treadonly applied: readonly number[];\n\t/** The domain's schema version after the call. */\n\treadonly version: number;\n}\n\nconst DEFAULT_MIGRATION_TABLE = \"atomic_migrations\";\n\nfunction checkSteps(steps: readonly StorageMigrationStep[]): void {\n\tlet previous = 0;\n\tfor (const step of steps) {\n\t\tif (!Number.isSafeInteger(step.version) || step.version <= previous)\n\t\t\tthrow new StorageConfigError(\n\t\t\t\t\"sdk\",\n\t\t\t\t\"steps\",\n\t\t\t\t\"versions-increasing\",\n\t\t\t\t\"Number migration steps 1, 2, 3, … in increasing order\",\n\t\t\t);\n\t\tprevious = step.version;\n\t}\n}\n\n/** Whether `table` exists, read from the catalog: no DDL, so a role without CREATE can ask (#5218). */\nasync function tableExists(executor: SqliteExecutor, dialect: StorageDialect, table: string): Promise<boolean> {\n\tconst probe = dialect.tableExists(table);\n\treturn (await executor.get(probe.sql, ...probe.params)) !== undefined;\n}\n\n/**\n * Refuses, before any DDL, a role that cannot use the schema the database runs in: the setup would fail with a bare\n * `3F000` or `42501` that names neither the grant nor the role (#5218). PostgreSQL only.\n */\nasync function assertSchemaUsage(executor: SqliteExecutor, dialect: StorageDialect): Promise<void> {\n\tif (dialect.name !== \"postgres\") return;\n\tconst access = await executor.get<SqliteRow & { schema: string; role: string; present: number; usage: number }>(\n\t\t`SELECT s.name AS schema, current_user AS role, (n.oid IS NOT NULL)::int AS present,\n\t\t\tcoalesce(has_schema_privilege(n.oid, 'USAGE'), false)::int AS usage\n\t\tFROM (SELECT trim(both '\"' from split_part(current_setting('search_path'), ',', 1)) AS name) s\n\t\tLEFT JOIN pg_catalog.pg_namespace n ON n.nspname = s.name`,\n\t);\n\tif (access === undefined || Number(access.present) === 0 || Number(access.usage) === 1) return;\n\tthrow new StorageConfigError(\n\t\t\"sdk\",\n\t\t\"privileges\",\n\t\t\"missing-privilege\",\n\t\t`Role \"${access.role}\" has no USAGE on schema ${access.schema}, so it can neither find Atomic's tables there nor create them. Grant it as the schema's owner: GRANT USAGE ON SCHEMA ${access.schema} TO \"${access.role}\"; and, for a runtime role, the table grants in \"Set up the database\" in docs/storage.md`,\n\t);\n}\n\n/** Creates the ledger `table` unless it exists, so a current schema runs no DDL (#5218). */\nasync function createLedger(executor: SqliteExecutor, dialect: StorageDialect, table: string): Promise<void> {\n\tif (await tableExists(executor, dialect, table)) return;\n\tawait assertSchemaUsage(executor, dialect);\n\t// Two stores that set up their schemas at once never race to create the ledger they share.\n\tif (dialect.name === \"postgres\") {\n\t\tawait executor.get(\"SELECT pg_advisory_xact_lock(hashtextextended(?, 0)) AS locked\", `${table}:schema`);\n\t\tif (await tableExists(executor, dialect, table)) return;\n\t}\n\tconst { int, text } = dialect.types;\n\tawait executor.exec(\n\t\t`CREATE TABLE IF NOT EXISTS ${table} (domain ${text} NOT NULL, version ${int} NOT NULL, applied_at ${int} NOT NULL, PRIMARY KEY (domain, version))${dialect.tableOptions}`,\n\t);\n}\n\n/** The highest version `table` records for `domain`, 0 when none or when the ledger does not exist yet. */\nasync function recordedVersion(\n\texecutor: SqliteExecutor,\n\tdialect: StorageDialect,\n\ttable: string,\n\tdomain: string,\n): Promise<number> {\n\tif (!(await tableExists(executor, dialect, table))) return 0;\n\tconst row = await executor.get<SqliteRow & { version: number | null }>(\n\t\t`SELECT MAX(version) AS version FROM ${table} WHERE domain = ?`,\n\t\tdomain,\n\t);\n\treturn Number(row?.version ?? 0);\n}\n\nasync function applyVersioned(\n\ttransaction: SqliteExecutor,\n\tdialect: StorageDialect,\n\ttable: string,\n\tdomain: string,\n\tsteps: readonly StorageMigrationStep[],\n\tacceptNewer = false,\n): Promise<StorageMigrationResult> {\n\tconst current = await recordedVersion(transaction, dialect, table, domain);\n\tconst supported = steps.at(-1)?.version ?? 0;\n\tif (current > supported) {\n\t\tif (acceptNewer) return { applied: [], version: current };\n\t\tthrow new StorageSchemaVersionError(domain, current, supported);\n\t}\n\tconst applied: number[] = [];\n\t// Probed first: a current schema, whose ledger exists, runs no DDL (#5218).\n\tawait createLedger(transaction, dialect, table);\n\tfor (const step of steps) {\n\t\tif (step.version <= current) continue;\n\t\tawait step.up(transaction, dialect);\n\t\tawait transaction.run(`INSERT INTO ${table} VALUES (?, ?, ${dialect.nowMs})`, domain, step.version);\n\t\tapplied.push(step.version);\n\t}\n\treturn { applied, version: Math.max(current, supported) };\n}\n\n/**\n * Advances `domain`'s schema to the last of `steps`, or refuses. Runs in one `serial` transaction whose domain is the ledger\n * table's name, so concurrent migrators under one prefix run one after another and a failed step rolls back the\n * whole call. Where the dialect has `versionedMigrations` (Postgres), applied versions are recorded in `table`: only\n * missing steps run, and a recorded version newer than the last step is a `StorageSchemaVersionError`. On SQLite\n * nothing is recorded (schemas stay what older Atomic versions share) and every step runs, idempotently; the domain's\n * own version row stays authoritative there.\n */\nexport async function applyStorageMigrations(\n\tdatabase: SqliteDatabase,\n\tdomain: string,\n\tsteps: readonly StorageMigrationStep[],\n\toptions: StorageMigrationOptions = {},\n): Promise<StorageMigrationResult> {\n\tcheckSteps(steps);\n\tconst dialect = dialectOf(database);\n\tconst table = options.table ?? DEFAULT_MIGRATION_TABLE;\n\treturn database.transaction(\n\t\tasync (transaction) => {\n\t\t\tif (dialect.versionedMigrations)\n\t\t\t\treturn applyVersioned(transaction, dialect, table, domain, steps, options.acceptNewer);\n\t\t\tfor (const step of steps) await step.up(transaction, dialect);\n\t\t\treturn { applied: steps.map((step) => step.version), version: steps.at(-1)?.version ?? 0 };\n\t\t},\n\t\t{ retryTransientFailures: true, concurrency: { kind: \"serial\", domain: table } },\n\t);\n}\n\n/** One domain's migration for {@link applyStorageMigrationsTogether}: the arguments of {@link applyStorageMigrations}. */\nexport interface StorageDomainMigration {\n\treadonly domain: string;\n\treadonly steps: readonly StorageMigrationStep[];\n\treadonly options?: StorageMigrationOptions;\n}\n\n/**\n * Migrates each of `migrations` in order, as {@link applyStorageMigrations} would, and resolves with each one's result.\n * Where the dialect records no versions (SQLite), every step runs every time, so the domains share one transaction: one\n * turn of the write lock for all of them, and a failure rolls back all of them. Elsewhere each domain migrates in a\n * transaction of its own, as `applyStorageMigrations` runs it.\n */\nexport async function applyStorageMigrationsTogether(\n\tdatabase: SqliteDatabase,\n\tmigrations: readonly StorageDomainMigration[],\n): Promise<StorageMigrationResult[]> {\n\tconst dialect = dialectOf(database);\n\tif (dialect.versionedMigrations) {\n\t\tconst results: StorageMigrationResult[] = [];\n\t\tfor (const { domain, steps, options } of migrations)\n\t\t\tresults.push(await applyStorageMigrations(database, domain, steps, options));\n\t\treturn results;\n\t}\n\tfor (const { steps } of migrations) checkSteps(steps);\n\tconst table = migrations[0]?.options?.table ?? DEFAULT_MIGRATION_TABLE;\n\treturn database.transaction(\n\t\tasync (transaction) => {\n\t\t\tconst results: StorageMigrationResult[] = [];\n\t\t\tfor (const { steps } of migrations) {\n\t\t\t\tfor (const step of steps) await step.up(transaction, dialect);\n\t\t\t\tresults.push({ applied: steps.map((step) => step.version), version: steps.at(-1)?.version ?? 0 });\n\t\t\t}\n\t\t\treturn results;\n\t\t},\n\t\t{ retryTransientFailures: true, concurrency: { kind: \"serial\", domain: table } },\n\t);\n}\n\n/** How long one schema setup statement waits for a table lock before the setup backs off and tries again (#5218). */\nexport const SCHEMA_SETUP_LOCK_WAIT_MS = 1_000;\n/** How many times a schema setup runs before a lock it keeps waiting for fails it. */\nconst SCHEMA_SETUP_ATTEMPTS = 8;\n/** The first pause between attempts; each later one doubles, up to {@link SCHEMA_SETUP_MAX_BACKOFF_MS}. */\nconst SCHEMA_SETUP_BACKOFF_MS = 100;\nconst SCHEMA_SETUP_MAX_BACKOFF_MS = 2_000;\n\n/** Whether `error`, or what caused it, is PostgreSQL's lock timeout (SQLSTATE `55P03`). */\nfunction isLockTimeout(error: unknown): boolean {\n\tlet current = error;\n\tfor (let depth = 0; depth < 8 && typeof current === \"object\" && current !== null; depth++) {\n\t\tconst code = (current as { code?: unknown }).code;\n\t\tif (code === \"55P03\" || code === \"lock-conflict\") return true;\n\t\tcurrent = (current as { cause?: unknown }).cause;\n\t}\n\treturn false;\n}\n\n/**\n * Runs `setup`, DDL that takes table locks such as `CREATE OR REPLACE TRIGGER`'s SHARE ROW EXCLUSIVE, with a short\n * `lock_timeout` in a savepoint: a lock it would wait for, such as one a stalled transaction holds, fails it after\n * {@link SCHEMA_SETUP_LOCK_WAIT_MS}, and it rolls back to the savepoint, backs off and tries again. A waiting DDL\n * statement queues every later writer of its table behind it, so it never waits long (#5218).\n */\nexport async function withShortSchemaLockWaits(\n\texecutor: SqliteExecutor,\n\tdialect: StorageDialect,\n\tsetup: () => Promise<void>,\n): Promise<void> {\n\tif (dialect.name !== \"postgres\") return setup();\n\treturn underShortLockWaits(executor, setup);\n}\n\nasync function underShortLockWaits(executor: SqliteExecutor, setup: () => Promise<void>): Promise<void> {\n\tconst previous = await executor.get<SqliteRow & { wait: string }>(\"SELECT current_setting('lock_timeout') AS wait\");\n\tfor (let attempt = 1; ; attempt++) {\n\t\tawait executor.exec(\"SAVEPOINT atomic_schema_setup\");\n\t\tawait executor.exec(`SET LOCAL lock_timeout = ${SCHEMA_SETUP_LOCK_WAIT_MS}`);\n\t\ttry {\n\t\t\tawait setup();\n\t\t\tawait executor.exec(\"RELEASE SAVEPOINT atomic_schema_setup\");\n\t\t\tbreak;\n\t\t} catch (error) {\n\t\t\tif (!isLockTimeout(error) || attempt >= SCHEMA_SETUP_ATTEMPTS) throw error;\n\t\t\tawait executor.exec(\"ROLLBACK TO SAVEPOINT atomic_schema_setup\");\n\t\t\tconst pause = Math.min(SCHEMA_SETUP_BACKOFF_MS * 2 ** (attempt - 1), SCHEMA_SETUP_MAX_BACKOFF_MS);\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, pause * (0.5 + Math.random() / 2)));\n\t\t}\n\t}\n\tawait executor.exec(`SET LOCAL lock_timeout = '${String(previous?.wait ?? \"0\").replaceAll(\"'\", \"''\")}'`);\n}\n\n/** What {@link ensureStorageSchema} records a store's schema setup under. */\nexport interface StorageSchemaSetup {\n\t/** The ledger table, already prefixed: `storageMigrationTable(prefix)`. */\n\treadonly ledger: string;\n\t/** The store's name in the ledger, unique among the stores under one prefix, such as `\"pool-queue\"`. */\n\treadonly domain: string;\n\t/**\n\t * The revision of the store's tables, indexes, triggers and columns: raise it whenever `setup` creates or alters\n\t * anything new, so a schema an earlier build set up runs `setup` again. Past ones stay recorded, never lowered.\n\t */\n\treadonly revision: number;\n}\n\n/**\n * Runs `setup`, a store's idempotent schema statements (`CREATE … IF NOT EXISTS`, guarded `ALTER TABLE … ADD COLUMN`),\n * in the caller's transaction `executor` unless the ledger already records `revision` for the store (#5218). On a\n * database with versioned migrations (PostgreSQL) a current schema runs no DDL at all, so a runtime role with only DML\n * privileges opens it; a schema that is behind runs `setup` under the store's advisory lock, then records the revision,\n * so concurrent processes set it up once. A role that may not run the DDL then fails with\n * `StorageConfigError` reason `missing-privilege` from the adapter. On SQLite, which records no ledger, `setup` runs\n * every time, as before.\n */\nexport async function ensureStorageSchema(\n\texecutor: SqliteExecutor,\n\tdialect: StorageDialect,\n\tschema: StorageSchemaSetup,\n\tsetup: () => Promise<void>,\n): Promise<void> {\n\tif (!dialect.versionedMigrations) {\n\t\tawait setup();\n\t\treturn;\n\t}\n\tconst { ledger, domain, revision } = schema;\n\tconst key = `schema:${domain}`;\n\tif ((await recordedVersion(executor, dialect, ledger, key)) >= revision) return;\n\tif (dialect.name === \"postgres\") {\n\t\t// Serialized per prefix, so hosts that start together on a new database set each store up once, and two stores\n\t\t// that create a table they share never race to create it.\n\t\tawait executor.get(\"SELECT pg_advisory_xact_lock(hashtextextended(?, 0)) AS locked\", `${ledger}:schema`);\n\t\tif ((await recordedVersion(executor, dialect, ledger, key)) >= revision) return;\n\t\tawait assertSchemaUsage(executor, dialect);\n\t\tawait underShortLockWaits(executor, setup);\n\t} else await setup();\n\tawait createLedger(executor, dialect, ledger);\n\tawait executor.run(\n\t\t`INSERT INTO ${ledger} (domain, version, applied_at) VALUES (?, ?, ${dialect.nowMs}) ON CONFLICT DO NOTHING`,\n\t\tkey,\n\t\trevision,\n\t);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"migrations.js","sourceRoot":"","sources":["../../../src/core/storage/migrations.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAuB,MAAM,cAAc,CAAC;AAC9D,OAAO,EAAE,kBAAkB,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AAC5E,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAgCtD,MAAM,uBAAuB,GAAG,mBAAmB,CAAC;AAEpD,SAAS,UAAU,CAAC,KAAsC;IACzD,IAAI,QAAQ,GAAG,CAAC,CAAC;IACjB,KAAK,MAA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AE,IAAI,EAAE,WAAW,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,CACjF,CAAC;AACH,CAAC","sourcesContent":["import type { SqliteDatabase, SqliteExecutor, SqliteRow } from \"./database.js\";\nimport { dialectOf, type StorageDialect } from \"./dialect.js\";\nimport { StorageConfigError, StorageSchemaVersionError } from \"./errors.js\";\nimport { schemaCatalogOf } from \"./schema-catalog.js\";\n\n/** One version of a domain's schema. */\nexport interface StorageMigrationStep {\n\t/** A positive integer; a domain's steps are listed in increasing order. */\n\treadonly version: number;\n\t/**\n\t * Brings the schema from the previous version to this one. It may use only `transaction`: the runner may run the\n\t * whole migration again after a transient failure. On a dialect without `versionedMigrations` (SQLite) every step\n\t * runs each time, so its statements must be idempotent (`CREATE … IF NOT EXISTS`).\n\t */\n\tup(transaction: SqliteExecutor, dialect: StorageDialect): Promise<void>;\n}\n\nexport interface StorageMigrationOptions {\n\t/** The ledger table, already prefixed (`renderStorageIdentifiers`); default `atomic_migrations`. */\n\treadonly table?: string;\n\t/**\n\t * A recorded version newer than the last step is accepted, and nothing runs, instead of refusing with\n\t * `StorageSchemaVersionError`. Only for a domain whose later steps stay additive, so a build that knows fewer of\n\t * them still reads and writes it correctly (#5065).\n\t */\n\treadonly acceptNewer?: boolean;\n}\n\nexport interface StorageMigrationResult {\n\t/** The versions this call ran, in order. */\n\treadonly applied: readonly number[];\n\t/** The domain's schema version after the call. */\n\treadonly version: number;\n}\n\nconst DEFAULT_MIGRATION_TABLE = \"atomic_migrations\";\n\nfunction checkSteps(steps: readonly StorageMigrationStep[]): void {\n\tlet previous = 0;\n\tfor (const step of steps) {\n\t\tif (!Number.isSafeInteger(step.version) || step.version <= previous)\n\t\t\tthrow new StorageConfigError(\n\t\t\t\t\"sdk\",\n\t\t\t\t\"steps\",\n\t\t\t\t\"versions-increasing\",\n\t\t\t\t\"Number migration steps 1, 2, 3, … in increasing order\",\n\t\t\t);\n\t\tprevious = step.version;\n\t}\n}\n\n/** Whether `table` exists, read from the catalog: no DDL, so a role without CREATE can ask (#5218). */\nasync function tableExists(executor: SqliteExecutor, dialect: StorageDialect, table: string): Promise<boolean> {\n\tconst probe = dialect.tableExists(table);\n\treturn (await executor.get(probe.sql, ...probe.params)) !== undefined;\n}\n\n/**\n * Refuses, before any DDL, a role that cannot use the schema the database runs in: the setup would fail with a bare\n * `3F000` or `42501` that names neither the grant nor the role (#5218). PostgreSQL only.\n */\nasync function assertSchemaUsage(executor: SqliteExecutor, dialect: StorageDialect): Promise<void> {\n\tif (dialect.name !== \"postgres\") return;\n\tconst access = await executor.get<SqliteRow & { schema: string; role: string; present: number; usage: number }>(\n\t\t`SELECT s.name AS schema, current_user AS role, (n.oid IS NOT NULL)::int AS present,\n\t\t\tcoalesce(has_schema_privilege(n.oid, 'USAGE'), false)::int AS usage\n\t\tFROM (SELECT trim(both '\"' from split_part(current_setting('search_path'), ',', 1)) AS name) s\n\t\tLEFT JOIN pg_catalog.pg_namespace n ON n.nspname = s.name`,\n\t);\n\tif (access === undefined || Number(access.present) === 0 || Number(access.usage) === 1) return;\n\tthrow new StorageConfigError(\n\t\t\"sdk\",\n\t\t\"privileges\",\n\t\t\"missing-privilege\",\n\t\t`Role \"${access.role}\" has no USAGE on schema ${access.schema}, so it can neither find Atomic's tables there nor create them. Grant it as the schema's owner: GRANT USAGE ON SCHEMA ${access.schema} TO \"${access.role}\"; and, for a runtime role, the table grants in \"Set up the database\" in docs/storage.md`,\n\t);\n}\n\n/** Creates the ledger `table` unless it exists, so a current schema runs no DDL (#5218). */\nasync function createLedger(executor: SqliteExecutor, dialect: StorageDialect, table: string): Promise<void> {\n\tif (await tableExists(executor, dialect, table)) return;\n\tawait assertSchemaUsage(executor, dialect);\n\t// Two stores that set up their schemas at once never race to create the ledger they share.\n\tif (dialect.name === \"postgres\") {\n\t\tawait executor.get(\"SELECT pg_advisory_xact_lock(hashtextextended(?, 0)) AS locked\", `${table}:schema`);\n\t\tif (await tableExists(executor, dialect, table)) return;\n\t}\n\tconst { int, text } = dialect.types;\n\tawait executor.exec(\n\t\t`CREATE TABLE IF NOT EXISTS ${table} (domain ${text} NOT NULL, version ${int} NOT NULL, applied_at ${int} NOT NULL, PRIMARY KEY (domain, version))${dialect.tableOptions}`,\n\t);\n}\n\n/** The highest version `table` records for `domain`, 0 when none or when the ledger does not exist yet. */\nasync function recordedVersion(\n\texecutor: SqliteExecutor,\n\tdialect: StorageDialect,\n\ttable: string,\n\tdomain: string,\n): Promise<number> {\n\tif (!(await tableExists(executor, dialect, table))) return 0;\n\tconst row = await executor.get<SqliteRow & { version: number | null }>(\n\t\t`SELECT MAX(version) AS version FROM ${table} WHERE domain = ?`,\n\t\tdomain,\n\t);\n\treturn Number(row?.version ?? 0);\n}\n\nasync function applyVersioned(\n\ttransaction: SqliteExecutor,\n\tdialect: StorageDialect,\n\ttable: string,\n\tdomain: string,\n\tsteps: readonly StorageMigrationStep[],\n\tacceptNewer = false,\n): Promise<StorageMigrationResult> {\n\tconst current = await recordedVersion(transaction, dialect, table, domain);\n\tconst supported = steps.at(-1)?.version ?? 0;\n\tif (current > supported) {\n\t\tif (acceptNewer) return { applied: [], version: current };\n\t\tthrow new StorageSchemaVersionError(domain, current, supported);\n\t}\n\tconst applied: number[] = [];\n\t// Probed first: a current schema, whose ledger exists, runs no DDL (#5218).\n\tawait createLedger(transaction, dialect, table);\n\tfor (const step of steps) {\n\t\tif (step.version <= current) continue;\n\t\tawait step.up(transaction, dialect);\n\t\tawait transaction.run(`INSERT INTO ${table} VALUES (?, ?, ${dialect.nowMs})`, domain, step.version);\n\t\tapplied.push(step.version);\n\t}\n\treturn { applied, version: Math.max(current, supported) };\n}\n\n/**\n * Advances `domain`'s schema to the last of `steps`, or refuses. Runs in one `serial` transaction whose domain is the ledger\n * table's name, so concurrent migrators under one prefix run one after another and a failed step rolls back the\n * whole call. Where the dialect has `versionedMigrations` (Postgres), applied versions are recorded in `table`: only\n * missing steps run, and a recorded version newer than the last step is a `StorageSchemaVersionError`. On SQLite\n * nothing is recorded (schemas stay what older Atomic versions share) and every step runs, idempotently; the domain's\n * own version row stays authoritative there.\n */\nexport async function applyStorageMigrations(\n\tdatabase: SqliteDatabase,\n\tdomain: string,\n\tsteps: readonly StorageMigrationStep[],\n\toptions: StorageMigrationOptions = {},\n): Promise<StorageMigrationResult> {\n\tcheckSteps(steps);\n\tconst dialect = dialectOf(database);\n\tconst table = options.table ?? DEFAULT_MIGRATION_TABLE;\n\tconst recorded = dialect.versionedMigrations ? await recordedInCatalog(database, table, domain) : undefined;\n\tconst supported = steps.at(-1)?.version ?? 0;\n\tif (recorded !== undefined && recorded >= supported && supported > 0) {\n\t\tif (recorded > supported && !options.acceptNewer)\n\t\t\tthrow new StorageSchemaVersionError(domain, recorded, supported);\n\t\treturn { applied: [], version: recorded };\n\t}\n\treturn database.transaction(\n\t\tasync (transaction) => {\n\t\t\tif (dialect.versionedMigrations)\n\t\t\t\treturn applyVersioned(transaction, dialect, table, domain, steps, options.acceptNewer);\n\t\t\tfor (const step of steps) await step.up(transaction, dialect);\n\t\t\treturn { applied: steps.map((step) => step.version), version: steps.at(-1)?.version ?? 0 };\n\t\t},\n\t\t{ retryTransientFailures: true, concurrency: { kind: \"serial\", domain: table } },\n\t);\n}\n\n/**\n * The version `table` records for `domain` in the catalog an open in progress read, or undefined outside one: an open\n * that finds every step recorded neither locks nor runs a transaction, as the steps would change nothing (#6560).\n */\nasync function recordedInCatalog(database: SqliteDatabase, table: string, domain: string): Promise<number | undefined> {\n\tconst catalog = await schemaCatalogOf(database, table);\n\tif (catalog === undefined || !catalog.hasTable(table)) return undefined;\n\treturn catalog.recordedVersion(domain);\n}\n\n/** One domain's migration for {@link applyStorageMigrationsTogether}: the arguments of {@link applyStorageMigrations}. */\nexport interface StorageDomainMigration {\n\treadonly domain: string;\n\treadonly steps: readonly StorageMigrationStep[];\n\treadonly options?: StorageMigrationOptions;\n}\n\n/**\n * Migrates each of `migrations` in order, as {@link applyStorageMigrations} would, and resolves with each one's result.\n * Where the dialect records no versions (SQLite), every step runs every time, so the domains share one transaction: one\n * turn of the write lock for all of them, and a failure rolls back all of them. Elsewhere each domain migrates in a\n * transaction of its own, as `applyStorageMigrations` runs it.\n */\nexport async function applyStorageMigrationsTogether(\n\tdatabase: SqliteDatabase,\n\tmigrations: readonly StorageDomainMigration[],\n): Promise<StorageMigrationResult[]> {\n\tconst dialect = dialectOf(database);\n\tif (dialect.versionedMigrations) {\n\t\tconst results: StorageMigrationResult[] = [];\n\t\tfor (const { domain, steps, options } of migrations)\n\t\t\tresults.push(await applyStorageMigrations(database, domain, steps, options));\n\t\treturn results;\n\t}\n\tfor (const { steps } of migrations) checkSteps(steps);\n\tconst table = migrations[0]?.options?.table ?? DEFAULT_MIGRATION_TABLE;\n\treturn database.transaction(\n\t\tasync (transaction) => {\n\t\t\tconst results: StorageMigrationResult[] = [];\n\t\t\tfor (const { steps } of migrations) {\n\t\t\t\tfor (const step of steps) await step.up(transaction, dialect);\n\t\t\t\tresults.push({ applied: steps.map((step) => step.version), version: steps.at(-1)?.version ?? 0 });\n\t\t\t}\n\t\t\treturn results;\n\t\t},\n\t\t{ retryTransientFailures: true, concurrency: { kind: \"serial\", domain: table } },\n\t);\n}\n\n/** How long one schema setup statement waits for a table lock before the setup backs off and tries again (#5218). */\nexport const SCHEMA_SETUP_LOCK_WAIT_MS = 1_000;\n/** How many times a schema setup runs before a lock it keeps waiting for fails it. */\nconst SCHEMA_SETUP_ATTEMPTS = 8;\n/** The first pause between attempts; each later one doubles, up to {@link SCHEMA_SETUP_MAX_BACKOFF_MS}. */\nconst SCHEMA_SETUP_BACKOFF_MS = 100;\nconst SCHEMA_SETUP_MAX_BACKOFF_MS = 2_000;\n\n/** Whether `error`, or what caused it, is PostgreSQL's lock timeout (SQLSTATE `55P03`). */\nfunction isLockTimeout(error: unknown): boolean {\n\tlet current = error;\n\tfor (let depth = 0; depth < 8 && typeof current === \"object\" && current !== null; depth++) {\n\t\tconst code = (current as { code?: unknown }).code;\n\t\tif (code === \"55P03\" || code === \"lock-conflict\") return true;\n\t\tcurrent = (current as { cause?: unknown }).cause;\n\t}\n\treturn false;\n}\n\n/**\n * Runs `setup`, DDL that takes table locks such as `CREATE OR REPLACE TRIGGER`'s SHARE ROW EXCLUSIVE, with a short\n * `lock_timeout` in a savepoint: a lock it would wait for, such as one a stalled transaction holds, fails it after\n * {@link SCHEMA_SETUP_LOCK_WAIT_MS}, and it rolls back to the savepoint, backs off and tries again. A waiting DDL\n * statement queues every later writer of its table behind it, so it never waits long (#5218).\n */\nexport async function withShortSchemaLockWaits(\n\texecutor: SqliteExecutor,\n\tdialect: StorageDialect,\n\tsetup: () => Promise<void>,\n): Promise<void> {\n\tif (dialect.name !== \"postgres\") return setup();\n\treturn underShortLockWaits(executor, setup);\n}\n\nasync function underShortLockWaits(executor: SqliteExecutor, setup: () => Promise<void>): Promise<void> {\n\tconst previous = await executor.get<SqliteRow & { wait: string }>(\"SELECT current_setting('lock_timeout') AS wait\");\n\tfor (let attempt = 1; ; attempt++) {\n\t\tawait executor.exec(\"SAVEPOINT atomic_schema_setup\");\n\t\tawait executor.exec(`SET LOCAL lock_timeout = ${SCHEMA_SETUP_LOCK_WAIT_MS}`);\n\t\ttry {\n\t\t\tawait setup();\n\t\t\tawait executor.exec(\"RELEASE SAVEPOINT atomic_schema_setup\");\n\t\t\tbreak;\n\t\t} catch (error) {\n\t\t\tif (!isLockTimeout(error) || attempt >= SCHEMA_SETUP_ATTEMPTS) throw error;\n\t\t\tawait executor.exec(\"ROLLBACK TO SAVEPOINT atomic_schema_setup\");\n\t\t\tconst pause = Math.min(SCHEMA_SETUP_BACKOFF_MS * 2 ** (attempt - 1), SCHEMA_SETUP_MAX_BACKOFF_MS);\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, pause * (0.5 + Math.random() / 2)));\n\t\t}\n\t}\n\tawait executor.exec(`SET LOCAL lock_timeout = '${String(previous?.wait ?? \"0\").replaceAll(\"'\", \"''\")}'`);\n}\n\n/** What {@link ensureStorageSchema} records a store's schema setup under. */\nexport interface StorageSchemaSetup {\n\t/** The ledger table, already prefixed: `storageMigrationTable(prefix)`. */\n\treadonly ledger: string;\n\t/** The store's name in the ledger, unique among the stores under one prefix, such as `\"pool-queue\"`. */\n\treadonly domain: string;\n\t/**\n\t * The revision of the store's tables, indexes, triggers and columns: raise it whenever `setup` creates or alters\n\t * anything new, so a schema an earlier build set up runs `setup` again. Past ones stay recorded, never lowered.\n\t */\n\treadonly revision: number;\n}\n\n/**\n * Whether the catalog an open in progress read (`withStorageSchemaCatalog`) records `schema.revision` for the\n * store already, so {@link ensureStorageSchema} would run nothing: the store's open then skips its schema transaction\n * and its lock (#6560). False outside such an open, on SQLite, and when the revision is not recorded.\n */\nexport async function storageSchemaCurrent(database: SqliteDatabase, schema: StorageSchemaSetup): Promise<boolean> {\n\tif (!dialectOf(database).versionedMigrations) return false;\n\tconst recorded = await recordedInCatalog(database, schema.ledger, `schema:${schema.domain}`);\n\treturn recorded !== undefined && recorded >= schema.revision;\n}\n\n/**\n * Runs `setup`, a store's idempotent schema statements (`CREATE … IF NOT EXISTS`, guarded `ALTER TABLE … ADD COLUMN`),\n * in the caller's transaction `executor` unless the ledger already records `revision` for the store (#5218). On a\n * database with versioned migrations (PostgreSQL) a current schema runs no DDL at all, so a runtime role with only DML\n * privileges opens it; a schema that is behind runs `setup` under the store's advisory lock, then records the revision,\n * so concurrent processes set it up once. A role that may not run the DDL then fails with\n * `StorageConfigError` reason `missing-privilege` from the adapter. On SQLite, which records no ledger, `setup` runs\n * every time, as before.\n */\nexport async function ensureStorageSchema(\n\texecutor: SqliteExecutor,\n\tdialect: StorageDialect,\n\tschema: StorageSchemaSetup,\n\tsetup: () => Promise<void>,\n): Promise<void> {\n\tif (!dialect.versionedMigrations) {\n\t\tawait setup();\n\t\treturn;\n\t}\n\tconst { ledger, domain, revision } = schema;\n\tconst key = `schema:${domain}`;\n\tif ((await recordedVersion(executor, dialect, ledger, key)) >= revision) return;\n\tif (dialect.name === \"postgres\") {\n\t\t// Serialized per prefix, so hosts that start together on a new database set each store up once, and two stores\n\t\t// that create a table they share never race to create it.\n\t\tawait executor.get(\"SELECT pg_advisory_xact_lock(hashtextextended(?, 0)) AS locked\", `${ledger}:schema`);\n\t\tif ((await recordedVersion(executor, dialect, ledger, key)) >= revision) return;\n\t\tawait assertSchemaUsage(executor, dialect);\n\t\tawait underShortLockWaits(executor, setup);\n\t} else await setup();\n\tawait createLedger(executor, dialect, ledger);\n\tawait executor.run(\n\t\t`INSERT INTO ${ledger} (domain, version, applied_at) VALUES (?, ?, ${dialect.nowMs}) ON CONFLICT DO NOTHING`,\n\t\tkey,\n\t\trevision,\n\t);\n}\n\n/** What {@link ensureTableFillfactor} sets, and records under `schema:<domain>` in the ledger. */\nexport interface StorageFillfactorSetup extends StorageSchemaSetup {\n\t/** The table, already prefixed. */\n\treadonly table: string;\n\t/** The percentage of each new page the table fills on insert, leaving the rest for updated row versions. */\n\treadonly fillfactor: number;\n}\n\n/**\n * Sets `setup.table`'s fillfactor on PostgreSQL, once per database, recorded in the ledger as `schema:<domain>`: each\n * page then keeps room for a new version of the rows on it, so updates of rows that change no indexed column stay on\n * their page as HOT updates and touch no index (#6560). It applies to the pages written from then on; `VACUUM FULL`\n * or pg_repack rewrites the existing ones with it. Nothing runs where the catalog an open read records the step, where\n * the table has a fillfactor already, or where this role does not own the table: a runtime role without DDL opens as\n * before, and `atomic storage migrate`, run as the owner, sets it. Does nothing on SQLite and libSQL.\n */\nexport async function ensureTableFillfactor(database: SqliteDatabase, setup: StorageFillfactorSetup): Promise<void> {\n\tconst dialect = dialectOf(database);\n\tif (dialect.name !== \"postgres\" || database.readOnly === true) return;\n\tconst { ledger, domain, revision, table, fillfactor } = setup;\n\tconst schema = { ledger, domain, revision };\n\tif (await storageSchemaCurrent(database, schema)) return;\n\tconst found = await database.get<SqliteRow & { owned: boolean | number; tuned: boolean | number }>(\n\t\t`SELECT pg_catalog.pg_has_role(current_user, c.relowner, 'USAGE') AS owned,\n\t\t\tcoalesce(array_to_string(c.reloptions, ',') LIKE '%fillfactor=%', false) AS tuned\n\t\tFROM pg_catalog.pg_class c WHERE c.relnamespace = current_schema()::regnamespace AND c.relname = ?`,\n\t\tdialect.identifier(table),\n\t);\n\tconst yes = (value: boolean | number | undefined) => value === true || Number(value) === 1;\n\tif (found === undefined || yes(found.tuned) || !yes(found.owned)) return;\n\tawait database.transaction(\n\t\t(tx) =>\n\t\t\tensureStorageSchema(tx, dialect, schema, async () => {\n\t\t\t\tawait tx.exec(`ALTER TABLE ${table} SET (fillfactor = ${Math.trunc(fillfactor)})`);\n\t\t\t}),\n\t\t{ retryTransientFailures: true, concurrency: { kind: \"serial\", domain: ledger } },\n\t);\n}\n"]}
|
|
@@ -59,10 +59,20 @@ function failure(error) {
|
|
|
59
59
|
};
|
|
60
60
|
}
|
|
61
61
|
|
|
62
|
+
const prepared = new Map();
|
|
63
|
+
|
|
62
64
|
function statement(sql) {
|
|
63
|
-
const
|
|
64
|
-
|
|
65
|
-
|
|
65
|
+
const cached = prepared.get(sql);
|
|
66
|
+
if (cached !== undefined) {
|
|
67
|
+
prepared.delete(sql);
|
|
68
|
+
prepared.set(sql, cached);
|
|
69
|
+
return cached;
|
|
70
|
+
}
|
|
71
|
+
const made = database.prepare(sql);
|
|
72
|
+
made.setReadBigInts(true);
|
|
73
|
+
prepared.set(sql, made);
|
|
74
|
+
if (prepared.size > workerData.statementCacheSize) prepared.delete(prepared.keys().next().value);
|
|
75
|
+
return made;
|
|
66
76
|
}
|
|
67
77
|
|
|
68
78
|
// Node 22 binds an empty Uint8Array that arrived in a message as NULL; a new empty one binds as a zero-length blob.
|
|
@@ -165,6 +175,7 @@ const handlers = {
|
|
|
165
175
|
}
|
|
166
176
|
},
|
|
167
177
|
close: () => {
|
|
178
|
+
prepared.clear();
|
|
168
179
|
database?.close();
|
|
169
180
|
globalThis.Bun?.gc?.(true);
|
|
170
181
|
},
|
|
@@ -275,6 +286,8 @@ export class ConnectionThreadEndedError extends Error {
|
|
|
275
286
|
const WORKER_CODE_OPTIONS = new Set(["--require", "-r", "--import", "--loader", "--experimental-loader"]);
|
|
276
287
|
/** The thread `startSpare` started for the next open, until an open takes it or `releaseSpare` ends it. */
|
|
277
288
|
let spare;
|
|
289
|
+
/** How many prepared statements a connection keeps for reuse, least recently used first out. */
|
|
290
|
+
export const STATEMENT_CACHE_SIZE = 256;
|
|
278
291
|
/** A node:sqlite connection running on its own worker thread. */
|
|
279
292
|
export class ThreadConnection {
|
|
280
293
|
worker;
|
|
@@ -289,7 +302,7 @@ export class ThreadConnection {
|
|
|
289
302
|
this.worker = new Worker(CONNECTION_SOURCE, {
|
|
290
303
|
eval: true,
|
|
291
304
|
execArgv: [],
|
|
292
|
-
workerData: { nowSql: `SELECT ${sqliteDialect.nowMs} AS now
|
|
305
|
+
workerData: { nowSql: `SELECT ${sqliteDialect.nowMs} AS now`, statementCacheSize: STATEMENT_CACHE_SIZE },
|
|
293
306
|
});
|
|
294
307
|
this.worker.on("message", (reply) => this.receive(reply));
|
|
295
308
|
this.worker.on("error", (error) => this.end(error));
|
|
@@ -459,7 +472,7 @@ function __atomicOnDemandFailed(error, feature) {
|
|
|
459
472
|
return (async () => {
|
|
460
473
|
const root = new URL("../../", import.meta.url);
|
|
461
474
|
const releases = (globalThis[Symbol.for("atomic.in-place-update-release.v1")] ??= new Map());
|
|
462
|
-
const key = `${root.href}#0.10.
|
|
475
|
+
const key = `${root.href}#0.10.11-alpha.1`;
|
|
463
476
|
let release = releases.get(key);
|
|
464
477
|
if (release === undefined) {
|
|
465
478
|
const current = (async () => {
|
|
@@ -487,7 +500,7 @@ function __atomicOnDemandFailed(error, feature) {
|
|
|
487
500
|
} catch {
|
|
488
501
|
// No installation to read, as in a bundle of the package: the release the process runs decides.
|
|
489
502
|
}
|
|
490
|
-
const updatedTo = typeof installed === "string" && installed !== "0.10.
|
|
503
|
+
const updatedTo = typeof installed === "string" && installed !== "0.10.11-alpha.1" ? installed : running !== undefined && running.version !== "0.10.11-alpha.1" ? "0.10.11-alpha.1" : undefined;
|
|
491
504
|
if (updatedTo === undefined) throw error;
|
|
492
505
|
const application = typeof running?.name === "string" ? running.name : "atomic";
|
|
493
506
|
const restart = new Error(`${application} was updated to ${updatedTo} while this session was running; restart it to keep using ${feature}.`, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node-sqlite-thread.js","sourceRoot":"","sources":["../../../src/core/storage/node-sqlite-thread.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAC7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,uCAAuC,CAAC;AAC3E,OAAO,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AAEpE,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAG7C;;;;;;GAMG;AACH,MAAM,iBAAiB,GAAG;EACxB,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmMpB,CAAC;AAiFF,MAAM,eAAe,GAA+C;IACnE,KAAK;IACL,SAAS;IACT,UAAU;IACV,WAAW;IACX,cAAc;IACd,SAAS;IACT,QAAQ;CACR,CAAC;AAEF,2FAA2F;AAC3F,MAAM,iBAAiB,GAAG,IAAI,GAAG,EAAkB,CAAC;AAEpD,kHAAkH;AAClH,SAAS,YAAY;IACpB,OAAO,GAAG,IAAI,CAAC,IAAI,KAAK,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,IAAI,CAAC,OAAO,EAAE,CAAC;AAC/D,CAAC;AAED,SAAS,gBAAgB,CAAC,IAAsB,EAAE,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I,IAAI,CAAC,KAAK,KAAK,SAAS;YAAE,OAAO;QACrC,iHAAiH;QACjH,6EAA6E;QAC7E,KAAK,KAAK,CAAC,KAAK,CAAC;QACjB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,MAAM,OAAO,GAAG,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;QAC3C,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;QACrB,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;QACpB,KAAK,MAAM,MAAM,IAAI,OAAO;YAAE,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACpD,CAAC;IAEO,KAAK,CAAC,IAAI;QACjB,IAAI,CAAC,GAAG,CAAC,IAAI,0BAA0B,CAAC,0BAA0B,CAAC,CAAC,CAAC;QACrE,MAAM,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE,CAAC;IAC/B,CAAC;IAED,wFAAwF;IACxF,MAAM,CAAC,QAAoB;QAC1B,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IACpC,CAAC;IAED;;;OAGG;IACH,MAAM,CAAC,KAAK,CAAC,qBAAqB,CACjC,IAAuB,EACvB,QAAyE,EACzE,eAA8B;QAE9B,MAAM,EAAE,8BAA8B,EAAE,GAAG,MAAM,MAAM,CAAC,uCAAuC,CAAC,CAAC;QACjG,IAAI,eAAe,EAAE,IAAI,8BAA8B,CAAC,IAAI,EAAE,KAAK,EAAE,QAAQ,CAAC,EAAE,CAAC;YAChF,gBAAgB,CAAC,UAAU,EAAE,CAAC;QAC/B,CAAC;IACF,CAAC;CACD","sourcesContent":["import { Worker } from \"node:worker_threads\";\nimport { startupNodeOptions } from \"@bastani/atomic-codemode/node-options\";\nimport { EVAL_WORKER_BUILTIN } from \"../../utils/worker-threads.js\";\nimport type { SqliteRow, SqliteValue } from \"./database.js\";\nimport { sqliteDialect } from \"./dialect.js\";\nimport type { SequencedStatement, SqliteSequence } from \"./statement-sequence.js\";\n\n/**\n * A node:sqlite connection that runs on a worker thread of its own (#5376). The thread owns the `DatabaseSync`; the\n * calling thread sends it one request at a time and receives each answer as a message, so no statement, lock wait or\n * synced commit runs on the caller's event loop. SQLite's busy handler waits on the connection's own thread, so a\n * statement waiting for a lock that another connection of the same process holds never stops that connection from\n * finishing.\n */\nconst CONNECTION_SOURCE = `\n${EVAL_WORKER_BUILTIN}\nconst { parentPort, workerData } = builtin(\"node:worker_threads\");\nprocess.emitWarning = () => {};\nconst { DatabaseSync } = builtin(\"node:sqlite\");\nlet database;\n\nconst STANDARD_ERRORS = [Error, TypeError, RangeError, SyntaxError, ReferenceError, EvalError, URIError];\n// Bun stamps every error with where it was thrown; the caller's copy gets its own.\nconst LOCATION_FIELDS = new Set([\"stack\", \"message\", \"line\", \"column\", \"originalLine\", \"originalColumn\", \"sourceURL\"]);\n\n// An object's own fields that hold plain values, with their enumerability.\nfunction fieldsOf(object, skip) {\n\tconst fields = [];\n\tfor (const key of Object.getOwnPropertyNames(object)) {\n\t\tif (skip.has(key)) continue;\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(object, key);\n\t\tconst value = descriptor?.value;\n\t\tif (value === null || (typeof value !== \"string\" && typeof value !== \"number\" && typeof value !== \"boolean\" && typeof value !== \"bigint\")) continue;\n\t\tfields.push([key, value, descriptor.enumerable === true]);\n\t}\n\treturn fields;\n}\n\n// A thrown error as it crosses to the caller: the standard constructor it descends from, its message, and its own\n// fields with their enumerability. A runtime's error class of its own between the error and that constructor (Bun's\n// node:sqlite errors have one holding name, code and toString) is described by its fields and whether it has a\n// toString of its own, and how it shows.\nfunction failure(error) {\n\tif (!(error instanceof Error)) return { constructor: \"Error\", message: String(error), fields: [] };\n\tlet standard = Object.getPrototypeOf(error);\n\tlet between;\n\twhile (standard !== null && !STANDARD_ERRORS.some((each) => each.prototype === standard)) {\n\t\tif (between === undefined) {\n\t\t\tconst toString = Object.getOwnPropertyDescriptor(standard, \"toString\");\n\t\t\tbetween = {\n\t\t\t\tfields: fieldsOf(standard, new Set([\"constructor\", \"message\"])),\n\t\t\t\t...(typeof toString?.value === \"function\" ? { toString: { enumerable: toString.enumerable === true } } : {}),\n\t\t\t};\n\t\t}\n\t\tstandard = Object.getPrototypeOf(standard);\n\t}\n\treturn {\n\t\tconstructor: standard === null ? \"Error\" : standard.constructor.name,\n\t\tmessage: String(error.message),\n\t\tfields: fieldsOf(error, LOCATION_FIELDS),\n\t\t...(between === undefined ? {} : { between }),\n\t};\n}\n\nfunction statement(sql) {\n\tconst prepared = database.prepare(sql);\n\tprepared.setReadBigInts(true);\n\treturn prepared;\n}\n\n// Node 22 binds an empty Uint8Array that arrived in a message as NULL; a new empty one binds as a zero-length blob.\nfunction bind(params) {\n\treturn params.map((value) => (value instanceof Uint8Array && value.byteLength === 0 ? new Uint8Array(0) : value));\n}\n\nfunction value(each) {\n\tif (typeof each === \"bigint\") return each >= -BigInt(Number.MAX_SAFE_INTEGER) && each <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(each) : each;\n\t// A copy of its own: a view of a larger buffer would send the whole buffer.\n\treturn each instanceof Uint8Array ? new Uint8Array(each) : each;\n}\n\n// Rows cross as their column names and one array of values each, in the order the driver gives a row's fields.\nfunction table(rows) {\n\tif (rows.length === 0) return { columns: [], values: [] };\n\tconst columns = Object.keys(rows[0]);\n\treturn { columns, values: rows.map((row) => columns.map((column) => value(row[column]))) };\n}\n\nconst handlers = {\n\topen: (request) => {\n\t\tdatabase = new DatabaseSync(request.path, { readOnly: request.readOnly });\n\t\treturn database.location();\n\t},\n\texec: (request) => {\n\t\tdatabase.exec(request.sql);\n\t},\n\trun: (request) => ({ changes: Number(statement(request.sql).run(...bind(request.params)).changes) }),\n\tget: (request) => {\n\t\tconst row = statement(request.sql).get(...bind(request.params));\n\t\treturn row === undefined ? undefined : table([row]);\n\t},\n\tall: (request) => table(statement(request.sql).all(...bind(request.params))),\n\t// One non-blocking BEGIN IMMEDIATE, the connection's busy timeout restored before answering.\n\tbegin: (request) => {\n\t\t// The file's lock word (see FREE in node-sqlite-file-gate.ts): taken before BEGIN, after waiting here for a\n\t\t// statement the calling thread runs meanwhile; settleLock gives it back once the transaction ended.\n\t\tif (request.lockState !== undefined) {\n\t\t\tconst state = new Int32Array(request.lockState);\n\t\t\tfor (;;) {\n\t\t\t\tconst found = Atomics.compareExchange(state, 0, 0, request.lockTag * 4 + 2);\n\t\t\t\tif (found === 0) break;\n\t\t\t\t// Anything but a statement of the calling thread (1) is another holder: a lock taken, as BEGIN would find.\n\t\t\t\tif (found !== 1)\n\t\t\t\t\tthrow Object.assign(new Error(\"database is locked\"), { code: \"ERR_SQLITE_ERROR\", errcode: 5, errstr: \"database is locked\" });\n\t\t\t\tAtomics.wait(state, 0, 1, 50);\n\t\t\t}\n\t\t\tAtomics.notify(state, 0);\n\t\t\tlockState = { state, held: request.lockTag * 4 + 3 };\n\t\t}\n\t\tconst configured = Number(database.prepare(\"PRAGMA busy_timeout\").get()?.timeout ?? 0);\n\t\tdatabase.exec(\"PRAGMA busy_timeout=0\");\n\t\tlet began = false;\n\t\ttry {\n\t\t\tdatabase.exec(\"BEGIN IMMEDIATE\");\n\t\t\tbegan = true;\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tdatabase.exec(\"PRAGMA busy_timeout=\" + configured);\n\t\t\t} catch (restoreFailure) {\n\t\t\t\tif (began) database.exec(\"ROLLBACK\");\n\t\t\t\tthrow restoreFailure;\n\t\t\t}\n\t\t}\n\t},\n\t// \\`repeat\\`, then each statement, in one request: the statements the caller would send one at a time, in the same\n\t// order, each prepared when it is reached. The caller's abort flag is read where the caller would check its signal.\n\tsequence: (request) => {\n\t\tconst abort = request.abort === undefined ? undefined : new Int32Array(request.abort);\n\t\tconst aborted = () => abort !== undefined && Atomics.load(abort, 0) !== 0;\n\t\tlet repeated = 0;\n\t\tif (request.repeat !== undefined) {\n\t\t\tconst { statement: repeat, times, minChanges } = request.repeat;\n\t\t\twhile (repeated < times) {\n\t\t\t\tif (aborted()) return { aborted: true };\n\t\t\t\tconst before = Number(statement(\"SELECT total_changes() AS changes\").get().changes);\n\t\t\t\tstatement(repeat.sql).run(...bind(repeat.params));\n\t\t\t\tconst after = Number(statement(\"SELECT total_changes() AS changes\").get().changes);\n\t\t\t\tif (after - before < minChanges) break;\n\t\t\t\trepeated++;\n\t\t\t}\n\t\t}\n\t\tfor (const { sql, params, script } of request.statements) {\n\t\t\tif (aborted()) return { aborted: true };\n\t\t\tif (script === true) database.exec(sql);\n\t\t\telse statement(sql).run(...bind(params));\n\t\t}\n\t\treturn { repeated };\n\t},\n\tdataVersion: () => Number(database.prepare(\"PRAGMA data_version\").get()?.data_version ?? 0),\n\tnow: () => Number(database.prepare(workerData.nowSql).get().now),\n\tjsonbExtract: () => {\n\t\ttry {\n\t\t\tstatement(\"SELECT jsonb_extract('[]', '$')\");\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message === \"no such function: jsonb_extract\") return false;\n\t\t\tthrow error;\n\t\t}\n\t},\n\tclose: () => {\n\t\tdatabase?.close();\n\t\tglobalThis.Bun?.gc?.(true);\n\t},\n};\n\n// The file's lock word while this connection takes or holds the lock: held while a transaction is open on it, given\n// back (and the waiting threads woken) once none is, before the request that ended it is answered.\nlet lockState;\n\nfunction settleLock() {\n\tif (lockState === undefined) return;\n\tconst { state, held } = lockState;\n\tlet open = false;\n\ttry {\n\t\topen = database?.isTransaction === true;\n\t} catch {}\n\tif (open) {\n\t\tif (Atomics.compareExchange(state, 0, held - 1, held) === held - 1) Atomics.notify(state, 0);\n\t\treturn;\n\t}\n\tlockState = undefined;\n\tif (Atomics.compareExchange(state, 0, held, 0) === held || Atomics.compareExchange(state, 0, held - 1, 0) === held - 1)\n\t\tAtomics.notify(state, 0);\n}\n\nfunction handle(request) {\n\ttry {\n\t\treturn handlers[request.kind](request);\n\t} finally {\n\t\tsettleLock();\n\t}\n}\n\nparentPort.on(\"message\", (request) => {\n\ttry {\n\t\tparentPort.postMessage({ id: request.id, value: handle(request) });\n\t} catch (error) {\n\t\tparentPort.postMessage({ id: request.id, failure: failure(error) });\n\t}\n});\n`;\n\n/**\n * Statements sent as one request (see `SqliteSequence`). `abort` holds one `Int32` the caller sets to non-zero when its\n * signal aborts: the thread reads it before each run of `repeat` and before each statement.\n */\nexport interface SequenceRequest {\n\treadonly kind: \"sequence\";\n\treadonly repeat?: SqliteSequence[\"repeat\"];\n\treadonly statements: readonly SequencedStatement[];\n\treadonly abort?: SharedArrayBuffer;\n}\n\n/**\n * What a sequence request is answered with: how many runs of `repeat` changed `minChanges` rows or more, or that it\n * stopped because the caller's signal aborted.\n */\nexport type SequenceAnswer = { readonly repeated: number } | { readonly aborted: true };\n\n/** What a connection's thread is asked to do; each request is answered once, in the order it was sent. */\nexport type ConnectionRequest =\n\t| { readonly kind: \"open\"; readonly path: string; readonly readOnly: boolean }\n\t| { readonly kind: \"exec\"; readonly sql: string }\n\t| { readonly kind: \"run\" | \"get\" | \"all\"; readonly sql: string; readonly params: readonly SqliteValue[] }\n\t| { readonly kind: \"begin\"; readonly lockState?: SharedArrayBuffer; readonly lockTag?: number }\n\t| { readonly kind: \"dataVersion\" | \"now\" | \"jsonbExtract\" | \"close\" }\n\t| SequenceRequest;\n\n/** Rows as they cross from a connection's thread: the column names, then each row's values in their order. */\ninterface RowTable {\n\treadonly columns: readonly string[];\n\treadonly values: readonly (readonly SqliteValue[])[];\n}\n\n/** What a request's answer carries as it crosses, before rows are rebuilt. */\ntype ConnectionValue =\n\t| RowTable\n\t| { readonly changes: number }\n\t| SequenceAnswer\n\t| string\n\t| number\n\t| boolean\n\t| null\n\t| undefined;\n\n/**\n * What a request is answered with: `get` a row or undefined, `all` rows, `run` the changes, `sequence` a\n * `SequenceAnswer`, `open` the location, `dataVersion` and `now` a number, `jsonbExtract` a boolean, the others\n * undefined.\n */\nexport type ConnectionAnswer =\n\t| SqliteRow\n\t| SqliteRow[]\n\t| { readonly changes: number }\n\t| SequenceAnswer\n\t| string\n\t| number\n\t| boolean\n\t| null\n\t| undefined;\n\n/** An own field that holds a plain value: its key, value and enumerability. */\ntype ConnectionField = readonly [string, string | number | boolean | bigint, boolean];\n\n/** A failure as it crosses from a connection's thread; see `failure` in the thread's source. */\ninterface ConnectionFailure {\n\treadonly constructor: string;\n\treadonly message: string;\n\treadonly fields: readonly ConnectionField[];\n\treadonly between?: {\n\t\treadonly fields: readonly ConnectionField[];\n\t\treadonly toString?: { readonly enumerable: boolean };\n\t};\n}\n\ninterface ConnectionReply {\n\treadonly id: number;\n\treadonly value?: ConnectionValue;\n\treadonly failure?: ConnectionFailure;\n}\n\nconst STANDARD_ERRORS: Readonly<Record<string, ErrorConstructor>> = {\n\tError,\n\tTypeError,\n\tRangeError,\n\tSyntaxError,\n\tReferenceError,\n\tEvalError,\n\tURIError,\n};\n\n/** One prototype per runtime error class seen, by what it holds: see `connectionError`. */\nconst betweenPrototypes = new Map<string, object>();\n\n/** How a runtime's error class of its own shows an error, as Bun's do: `TypeError [ERR_INVALID_ARG_VALUE]: …`. */\nfunction showWithCode(this: Error & { readonly code?: unknown }): string {\n\treturn `${this.name} [${String(this.code)}]: ${this.message}`;\n}\n\nfunction betweenPrototype(base: ErrorConstructor, between: NonNullable<ConnectionFailure[\"between\"]>): object {\n\tconst key = JSON.stringify([\n\t\tbase.name,\n\t\tbetween.fields.map(([field, value, enumerable]) => [field, String(value), enumerable]),\n\t\tbetween.toString,\n\t]);\n\tlet prototype = betweenPrototypes.get(key);\n\tif (prototype === undefined) {\n\t\tconst created: object = Object.create(base.prototype);\n\t\tfor (const [field, value, enumerable] of between.fields)\n\t\t\tObject.defineProperty(created, field, { value, enumerable, writable: true, configurable: true });\n\t\tif (between.toString !== undefined)\n\t\t\tObject.defineProperty(created, \"toString\", {\n\t\t\t\tvalue: showWithCode,\n\t\t\t\tenumerable: between.toString.enumerable,\n\t\t\t\twritable: true,\n\t\t\t\tconfigurable: true,\n\t\t\t});\n\t\tbetweenPrototypes.set(key, created);\n\t\tprototype = created;\n\t}\n\treturn prototype;\n}\n\n/**\n * The driver's error, rebuilt on the calling thread as the driver threw it: an instance of the same standard error\n * class with the same message, and the same own fields (`code`, `errcode`, `errstr` for SQLite's errors) with the same\n * enumerability. A runtime's own error class between them is stood in for by a prototype that holds the same fields and\n * shows the error the same way.\n */\nfunction connectionError(failure: ConnectionFailure): Error {\n\tconst base = STANDARD_ERRORS[failure.constructor] ?? Error;\n\tconst error = new base(failure.message);\n\tif (failure.between !== undefined) Object.setPrototypeOf(error, betweenPrototype(base, failure.between));\n\tfor (const [key, value, enumerable] of failure.fields)\n\t\tObject.defineProperty(error, key, { value, enumerable, writable: true, configurable: true });\n\treturn error;\n}\n\n/** The rows of `table`, each a plain object built the way the calling-thread connection builds them. */\nfunction rowsOf(table: RowTable): SqliteRow[] {\n\tconst { columns, values } = table;\n\treturn values.map((row) => Object.fromEntries(columns.map((column, index) => [column, row[index] as SqliteValue])));\n}\n\ninterface Waiter {\n\treadonly resolve: (value: ConnectionValue) => void;\n\treadonly reject: (error: unknown) => void;\n}\n\n/** Thrown for a request to a connection whose thread is gone: closed, or lost to an error or an exit. */\nexport class ConnectionThreadEndedError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"ConnectionThreadEndedError\";\n\t}\n}\n\n/** Options that make every worker thread run code of the user's: a preload or a module loader. */\nconst WORKER_CODE_OPTIONS = new Set([\"--require\", \"-r\", \"--import\", \"--loader\", \"--experimental-loader\"]);\n\n/** The thread `startSpare` started for the next open, until an open takes it or `releaseSpare` ends it. */\nlet spare: ThreadConnection | undefined;\n\n/** A node:sqlite connection running on its own worker thread. */\nexport class ThreadConnection {\n\tprivate readonly worker: Worker;\n\tprivate readonly waiting = new Map<number, Waiter>();\n\tprivate nextId = 1;\n\tprivate ended?: Error;\n\tprivate closing?: Promise<undefined>;\n\n\tprivate constructor() {\n\t\t// None of the process's own flags: the caller's preloads would run again for every connection, and its\n\t\t// `--input-type=module` would make this source a module. Whether node:sqlite is available was settled by the\n\t\t// open before it started the thread.\n\t\tthis.worker = new Worker(CONNECTION_SOURCE, {\n\t\t\teval: true,\n\t\t\texecArgv: [],\n\t\t\tworkerData: { nowSql: `SELECT ${sqliteDialect.nowMs} AS now` },\n\t\t});\n\t\tthis.worker.on(\"message\", (reply: ConnectionReply) => this.receive(reply));\n\t\tthis.worker.on(\"error\", (error: Error) => this.end(error));\n\t\tthis.worker.on(\"exit\", (code: number) =>\n\t\t\tthis.end(new ConnectionThreadEndedError(`SQLite connection thread exited with code ${code}`)),\n\t\t);\n\t}\n\n\t/**\n\t * Opens `openAs` (or `path`) on a thread of its own and resolves with the location SQLite reports for it. A failure\n\t * to start the thread or to open the database rejects with its cause; the thread is gone then.\n\t */\n\tstatic async open(\n\t\tpath: string,\n\t\toptions: { readonly readOnly: boolean; readonly openAs?: string },\n\t): Promise<{ readonly connection: ThreadConnection; readonly location: string | null }> {\n\t\tconst started = spare;\n\t\tspare = undefined;\n\t\tif (started !== undefined && started.ended === undefined) {\n\t\t\ttry {\n\t\t\t\treturn await ThreadConnection.openOn(started, path, options);\n\t\t\t} catch (error) {\n\t\t\t\t// The spare thread was lost before it answered: open on a thread of its own, as without one.\n\t\t\t\tif (error !== started.ended) throw error;\n\t\t\t}\n\t\t}\n\t\treturn ThreadConnection.openOn(new ThreadConnection(), path, options);\n\t}\n\n\t/**\n\t * Starts one connection thread now, for the next open to take, so that the thread's startup overlaps whatever the\n\t * process does until then (an interactive session loads its modules meanwhile). Idle, the thread keeps nothing\n\t * alive. Nothing starts when the process runs a preload or a module loader, which every worker thread runs again,\n\t * or runs under the permission model; a thread that cannot start leaves every open as it is without one.\n\t */\n\tstatic startSpare(): void {\n\t\tif (spare !== undefined || process.permission !== undefined) return;\n\t\tif (startupNodeOptions().some((option) => WORKER_CODE_OPTIONS.has(option.name))) return;\n\t\ttry {\n\t\t\tconst started = new ThreadConnection();\n\t\t\tstarted.worker.unref();\n\t\t\tspare = started;\n\t\t} catch {\n\t\t\t// Opens start their own threads.\n\t\t}\n\t}\n\n\t/** Ends the spare thread if no open has taken it. */\n\tstatic releaseSpare(): void {\n\t\tconst started = spare;\n\t\tspare = undefined;\n\t\tif (started !== undefined) void started.stop();\n\t}\n\n\tprivate static async openOn(\n\t\tconnection: ThreadConnection,\n\t\tpath: string,\n\t\toptions: { readonly readOnly: boolean; readonly openAs?: string },\n\t): Promise<{ readonly connection: ThreadConnection; readonly location: string | null }> {\n\t\ttry {\n\t\t\tconst location = await connection.request({\n\t\t\t\tkind: \"open\",\n\t\t\t\tpath: options.openAs ?? path,\n\t\t\t\treadOnly: options.readOnly,\n\t\t\t});\n\t\t\treturn { connection, location: typeof location === \"string\" ? location : null };\n\t\t} catch (error) {\n\t\t\tawait connection.stop();\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Sends one request; resolves with the thread's answer or rejects with the driver's error, rebuilt. While a request\n\t * waits for its answer the thread keeps the process alive; an idle connection does not, as a connection on the\n\t * calling thread would not.\n\t */\n\trequest(request: ConnectionRequest): Promise<ConnectionAnswer> {\n\t\tif (request.kind === \"close\") return this.close();\n\t\tconst answer = this.send(request);\n\t\tif (request.kind === \"get\")\n\t\t\treturn answer.then((value) => (value === undefined ? undefined : rowsOf(value as RowTable)[0]));\n\t\tif (request.kind === \"all\") return answer.then((value) => rowsOf(value as RowTable));\n\t\treturn answer as Promise<ConnectionAnswer>;\n\t}\n\n\tprivate send(request: ConnectionRequest): Promise<ConnectionValue> {\n\t\treturn new Promise<ConnectionValue>((resolve, reject) => {\n\t\t\tif (this.ended !== undefined) {\n\t\t\t\treject(this.ended);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst id = this.nextId++;\n\t\t\ttry {\n\t\t\t\tthis.worker.postMessage({ id, ...request });\n\t\t\t} catch (error) {\n\t\t\t\t// A value the thread cannot receive.\n\t\t\t\treject(error);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.waiting.set(id, { resolve, reject });\n\t\t\tif (this.waiting.size === 1) this.worker.ref();\n\t\t});\n\t}\n\n\t/**\n\t * Closes the database on its thread, then ends the thread: a `close` request. Requests sent after it are rejected. A\n\t * thread already lost has nothing to close.\n\t */\n\tprivate close(): Promise<undefined> {\n\t\tthis.closing ??= (async () => {\n\t\t\ttry {\n\t\t\t\tif (this.ended === undefined) await this.send({ kind: \"close\" });\n\t\t\t} finally {\n\t\t\t\tawait this.stop();\n\t\t\t}\n\t\t\treturn undefined;\n\t\t})();\n\t\treturn this.closing;\n\t}\n\n\tprivate receive(reply: ConnectionReply): void {\n\t\tconst waiter = this.waiting.get(reply.id);\n\t\tif (waiter === undefined) return;\n\t\tthis.waiting.delete(reply.id);\n\t\tif (this.waiting.size === 0) this.worker.unref();\n\t\tif (reply.failure === undefined) waiter.resolve(reply.value);\n\t\telse waiter.reject(connectionError(reply.failure));\n\t}\n\n\t/** Rejects every request still waiting, oldest first, and every later one. Ending again does nothing. */\n\tprivate end(cause: Error): void {\n\t\tif (this.ended !== undefined) return;\n\t\t// Kept for as long as the connection is: an error's stack, until formatted, keeps the functions of the frames it\n\t\t// names, and so whatever they hold, such as a session that closed its store.\n\t\tvoid cause.stack;\n\t\tthis.ended = cause;\n\t\tconst waiting = [...this.waiting.values()];\n\t\tthis.waiting.clear();\n\t\tthis.worker.unref();\n\t\tfor (const waiter of waiting) waiter.reject(cause);\n\t}\n\n\tprivate async stop(): Promise<void> {\n\t\tthis.end(new ConnectionThreadEndedError(\"SQLite connection closed\"));\n\t\tawait this.worker.terminate();\n\t}\n\n\t/** Calls `listener` once the connection's thread has exited, whether closed or lost. */\n\tonExit(listener: () => void): void {\n\t\tthis.worker.once(\"exit\", listener);\n\t}\n\n\t/**\n\t * Starts a spare worker for a non-interactive or storage-overridden CLI\n\t * invocation only when the real CLI/storage resolvers select a SQLite store.\n\t */\n\tstatic async startSpareIfSqlNeeded(\n\t\targs: readonly string[],\n\t\tterminal: { readonly stdinIsTTY: boolean; readonly stdoutIsTTY: boolean },\n\t\tstillBeforeMain: () => boolean,\n\t): Promise<void> {\n\t\tconst { shouldStartSpareDatabaseThread } = await import(\"../../utils/startup-database-spare.ts\");\n\t\tif (stillBeforeMain() && shouldStartSpareDatabaseThread(args, false, terminal)) {\n\t\t\tThreadConnection.startSpare();\n\t\t}\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"node-sqlite-thread.js","sourceRoot":"","sources":["../../../src/core/storage/node-sqlite-thread.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAC7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,uCAAuC,CAAC;AAC3E,OAAO,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AAEpE,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAG7C;;;;;;GAMG;AACH,MAAM,iBAAiB,GAAG;EACxB,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8MpB,CAAC;AAiFF,MAAM,eAAe,GAA+C;IACnE,KAAK;IACL,SAAS;IACT,UAAU;IACV,WAAW;IACX,cAAc;IACd,SAAS;IACT,QAAQ;CACR,CAAC;AAEF,2FAA2F;AAC3F,MAAM,iBAAiB,GAAG,IAAI,GAAG,EAAkB,CAAC;AAEpD,kHAAkH;AAClH,SAAS,YAAY;IACpB,OAAO,GAAG,IAAI,CAAC,IAAI,KAAK,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,IAAI,CAAC,OAAO,EAAE,CAAC;AAC/D,CAAC;AAED,SAAS,gBAAgB,CAAC,IAAsB,EAA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KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;IACpD,CAAC;IAED,yGAAyG;IACjG,GAAG,CAAC,KAAY;QACvB,IAAI,IAAI,CAAC,KAAK,KAAK,SAAS;YAAE,OAAO;QACrC,iHAAiH;QACjH,6EAA6E;QAC7E,KAAK,KAAK,CAAC,KAAK,CAAC;QACjB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,MAAM,OAAO,GAAG,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;QAC3C,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;QACrB,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;QACpB,KAAK,MAAM,MAAM,IAAI,OAAO;YAAE,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACpD,CAAC;IAEO,KAAK,CAAC,IAAI;QACjB,IAAI,CAAC,GAAG,CAAC,IAAI,0BAA0B,CAAC,0BAA0B,CAAC,CAAC,CAAC;QACrE,MAAM,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE,CAAC;IAC/B,CAAC;IAED,wFAAwF;IACxF,MAAM,CAAC,QAAoB;QAC1B,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IACpC,CAAC;IAED;;;OAGG;IACH,MAAM,CAAC,KAAK,CAAC,qBAAqB,CACjC,IAAuB,EACvB,QAAyE,EACzE,eAA8B;QAE9B,MAAM,EAAE,8BAA8B,EAAE,GAAG,MAAM,MAAM,CAAC,uCAAuC,CAAC,CAAC;QACjG,IAAI,eAAe,EAAE,IAAI,8BAA8B,CAAC,IAAI,EAAE,KAAK,EAAE,QAAQ,CAAC,EAAE,CAAC;YAChF,gBAAgB,CAAC,UAAU,EAAE,CAAC;QAC/B,CAAC;IACF,CAAC;CACD","sourcesContent":["import { Worker } from \"node:worker_threads\";\nimport { startupNodeOptions } from \"@bastani/atomic-codemode/node-options\";\nimport { EVAL_WORKER_BUILTIN } from \"../../utils/worker-threads.js\";\nimport type { SqliteRow, SqliteValue } from \"./database.js\";\nimport { sqliteDialect } from \"./dialect.js\";\nimport type { SequencedStatement, SqliteSequence } from \"./statement-sequence.js\";\n\n/**\n * A node:sqlite connection that runs on a worker thread of its own (#5376). The thread owns the `DatabaseSync`; the\n * calling thread sends it one request at a time and receives each answer as a message, so no statement, lock wait or\n * synced commit runs on the caller's event loop. SQLite's busy handler waits on the connection's own thread, so a\n * statement waiting for a lock that another connection of the same process holds never stops that connection from\n * finishing.\n */\nconst CONNECTION_SOURCE = `\n${EVAL_WORKER_BUILTIN}\nconst { parentPort, workerData } = builtin(\"node:worker_threads\");\nprocess.emitWarning = () => {};\nconst { DatabaseSync } = builtin(\"node:sqlite\");\nlet database;\n\nconst STANDARD_ERRORS = [Error, TypeError, RangeError, SyntaxError, ReferenceError, EvalError, URIError];\n// Bun stamps every error with where it was thrown; the caller's copy gets its own.\nconst LOCATION_FIELDS = new Set([\"stack\", \"message\", \"line\", \"column\", \"originalLine\", \"originalColumn\", \"sourceURL\"]);\n\n// An object's own fields that hold plain values, with their enumerability.\nfunction fieldsOf(object, skip) {\n\tconst fields = [];\n\tfor (const key of Object.getOwnPropertyNames(object)) {\n\t\tif (skip.has(key)) continue;\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(object, key);\n\t\tconst value = descriptor?.value;\n\t\tif (value === null || (typeof value !== \"string\" && typeof value !== \"number\" && typeof value !== \"boolean\" && typeof value !== \"bigint\")) continue;\n\t\tfields.push([key, value, descriptor.enumerable === true]);\n\t}\n\treturn fields;\n}\n\n// A thrown error as it crosses to the caller: the standard constructor it descends from, its message, and its own\n// fields with their enumerability. A runtime's error class of its own between the error and that constructor (Bun's\n// node:sqlite errors have one holding name, code and toString) is described by its fields and whether it has a\n// toString of its own, and how it shows.\nfunction failure(error) {\n\tif (!(error instanceof Error)) return { constructor: \"Error\", message: String(error), fields: [] };\n\tlet standard = Object.getPrototypeOf(error);\n\tlet between;\n\twhile (standard !== null && !STANDARD_ERRORS.some((each) => each.prototype === standard)) {\n\t\tif (between === undefined) {\n\t\t\tconst toString = Object.getOwnPropertyDescriptor(standard, \"toString\");\n\t\t\tbetween = {\n\t\t\t\tfields: fieldsOf(standard, new Set([\"constructor\", \"message\"])),\n\t\t\t\t...(typeof toString?.value === \"function\" ? { toString: { enumerable: toString.enumerable === true } } : {}),\n\t\t\t};\n\t\t}\n\t\tstandard = Object.getPrototypeOf(standard);\n\t}\n\treturn {\n\t\tconstructor: standard === null ? \"Error\" : standard.constructor.name,\n\t\tmessage: String(error.message),\n\t\tfields: fieldsOf(error, LOCATION_FIELDS),\n\t\t...(between === undefined ? {} : { between }),\n\t};\n}\n\nconst prepared = new Map();\n\nfunction statement(sql) {\n\tconst cached = prepared.get(sql);\n\tif (cached !== undefined) {\n\t\tprepared.delete(sql);\n\t\tprepared.set(sql, cached);\n\t\treturn cached;\n\t}\n\tconst made = database.prepare(sql);\n\tmade.setReadBigInts(true);\n\tprepared.set(sql, made);\n\tif (prepared.size > workerData.statementCacheSize) prepared.delete(prepared.keys().next().value);\n\treturn made;\n}\n\n// Node 22 binds an empty Uint8Array that arrived in a message as NULL; a new empty one binds as a zero-length blob.\nfunction bind(params) {\n\treturn params.map((value) => (value instanceof Uint8Array && value.byteLength === 0 ? new Uint8Array(0) : value));\n}\n\nfunction value(each) {\n\tif (typeof each === \"bigint\") return each >= -BigInt(Number.MAX_SAFE_INTEGER) && each <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(each) : each;\n\t// A copy of its own: a view of a larger buffer would send the whole buffer.\n\treturn each instanceof Uint8Array ? new Uint8Array(each) : each;\n}\n\n// Rows cross as their column names and one array of values each, in the order the driver gives a row's fields.\nfunction table(rows) {\n\tif (rows.length === 0) return { columns: [], values: [] };\n\tconst columns = Object.keys(rows[0]);\n\treturn { columns, values: rows.map((row) => columns.map((column) => value(row[column]))) };\n}\n\nconst handlers = {\n\topen: (request) => {\n\t\tdatabase = new DatabaseSync(request.path, { readOnly: request.readOnly });\n\t\treturn database.location();\n\t},\n\texec: (request) => {\n\t\tdatabase.exec(request.sql);\n\t},\n\trun: (request) => ({ changes: Number(statement(request.sql).run(...bind(request.params)).changes) }),\n\tget: (request) => {\n\t\tconst row = statement(request.sql).get(...bind(request.params));\n\t\treturn row === undefined ? undefined : table([row]);\n\t},\n\tall: (request) => table(statement(request.sql).all(...bind(request.params))),\n\t// One non-blocking BEGIN IMMEDIATE, the connection's busy timeout restored before answering.\n\tbegin: (request) => {\n\t\t// The file's lock word (see FREE in node-sqlite-file-gate.ts): taken before BEGIN, after waiting here for a\n\t\t// statement the calling thread runs meanwhile; settleLock gives it back once the transaction ended.\n\t\tif (request.lockState !== undefined) {\n\t\t\tconst state = new Int32Array(request.lockState);\n\t\t\tfor (;;) {\n\t\t\t\tconst found = Atomics.compareExchange(state, 0, 0, request.lockTag * 4 + 2);\n\t\t\t\tif (found === 0) break;\n\t\t\t\t// Anything but a statement of the calling thread (1) is another holder: a lock taken, as BEGIN would find.\n\t\t\t\tif (found !== 1)\n\t\t\t\t\tthrow Object.assign(new Error(\"database is locked\"), { code: \"ERR_SQLITE_ERROR\", errcode: 5, errstr: \"database is locked\" });\n\t\t\t\tAtomics.wait(state, 0, 1, 50);\n\t\t\t}\n\t\t\tAtomics.notify(state, 0);\n\t\t\tlockState = { state, held: request.lockTag * 4 + 3 };\n\t\t}\n\t\tconst configured = Number(database.prepare(\"PRAGMA busy_timeout\").get()?.timeout ?? 0);\n\t\tdatabase.exec(\"PRAGMA busy_timeout=0\");\n\t\tlet began = false;\n\t\ttry {\n\t\t\tdatabase.exec(\"BEGIN IMMEDIATE\");\n\t\t\tbegan = true;\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tdatabase.exec(\"PRAGMA busy_timeout=\" + configured);\n\t\t\t} catch (restoreFailure) {\n\t\t\t\tif (began) database.exec(\"ROLLBACK\");\n\t\t\t\tthrow restoreFailure;\n\t\t\t}\n\t\t}\n\t},\n\t// \\`repeat\\`, then each statement, in one request: the statements the caller would send one at a time, in the same\n\t// order, each prepared when it is reached. The caller's abort flag is read where the caller would check its signal.\n\tsequence: (request) => {\n\t\tconst abort = request.abort === undefined ? undefined : new Int32Array(request.abort);\n\t\tconst aborted = () => abort !== undefined && Atomics.load(abort, 0) !== 0;\n\t\tlet repeated = 0;\n\t\tif (request.repeat !== undefined) {\n\t\t\tconst { statement: repeat, times, minChanges } = request.repeat;\n\t\t\twhile (repeated < times) {\n\t\t\t\tif (aborted()) return { aborted: true };\n\t\t\t\tconst before = Number(statement(\"SELECT total_changes() AS changes\").get().changes);\n\t\t\t\tstatement(repeat.sql).run(...bind(repeat.params));\n\t\t\t\tconst after = Number(statement(\"SELECT total_changes() AS changes\").get().changes);\n\t\t\t\tif (after - before < minChanges) break;\n\t\t\t\trepeated++;\n\t\t\t}\n\t\t}\n\t\tfor (const { sql, params, script } of request.statements) {\n\t\t\tif (aborted()) return { aborted: true };\n\t\t\tif (script === true) database.exec(sql);\n\t\t\telse statement(sql).run(...bind(params));\n\t\t}\n\t\treturn { repeated };\n\t},\n\tdataVersion: () => Number(database.prepare(\"PRAGMA data_version\").get()?.data_version ?? 0),\n\tnow: () => Number(database.prepare(workerData.nowSql).get().now),\n\tjsonbExtract: () => {\n\t\ttry {\n\t\t\tstatement(\"SELECT jsonb_extract('[]', '$')\");\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message === \"no such function: jsonb_extract\") return false;\n\t\t\tthrow error;\n\t\t}\n\t},\n\tclose: () => {\n\t\tprepared.clear();\n\t\tdatabase?.close();\n\t\tglobalThis.Bun?.gc?.(true);\n\t},\n};\n\n// The file's lock word while this connection takes or holds the lock: held while a transaction is open on it, given\n// back (and the waiting threads woken) once none is, before the request that ended it is answered.\nlet lockState;\n\nfunction settleLock() {\n\tif (lockState === undefined) return;\n\tconst { state, held } = lockState;\n\tlet open = false;\n\ttry {\n\t\topen = database?.isTransaction === true;\n\t} catch {}\n\tif (open) {\n\t\tif (Atomics.compareExchange(state, 0, held - 1, held) === held - 1) Atomics.notify(state, 0);\n\t\treturn;\n\t}\n\tlockState = undefined;\n\tif (Atomics.compareExchange(state, 0, held, 0) === held || Atomics.compareExchange(state, 0, held - 1, 0) === held - 1)\n\t\tAtomics.notify(state, 0);\n}\n\nfunction handle(request) {\n\ttry {\n\t\treturn handlers[request.kind](request);\n\t} finally {\n\t\tsettleLock();\n\t}\n}\n\nparentPort.on(\"message\", (request) => {\n\ttry {\n\t\tparentPort.postMessage({ id: request.id, value: handle(request) });\n\t} catch (error) {\n\t\tparentPort.postMessage({ id: request.id, failure: failure(error) });\n\t}\n});\n`;\n\n/**\n * Statements sent as one request (see `SqliteSequence`). `abort` holds one `Int32` the caller sets to non-zero when its\n * signal aborts: the thread reads it before each run of `repeat` and before each statement.\n */\nexport interface SequenceRequest {\n\treadonly kind: \"sequence\";\n\treadonly repeat?: SqliteSequence[\"repeat\"];\n\treadonly statements: readonly SequencedStatement[];\n\treadonly abort?: SharedArrayBuffer;\n}\n\n/**\n * What a sequence request is answered with: how many runs of `repeat` changed `minChanges` rows or more, or that it\n * stopped because the caller's signal aborted.\n */\nexport type SequenceAnswer = { readonly repeated: number } | { readonly aborted: true };\n\n/** What a connection's thread is asked to do; each request is answered once, in the order it was sent. */\nexport type ConnectionRequest =\n\t| { readonly kind: \"open\"; readonly path: string; readonly readOnly: boolean }\n\t| { readonly kind: \"exec\"; readonly sql: string }\n\t| { readonly kind: \"run\" | \"get\" | \"all\"; readonly sql: string; readonly params: readonly SqliteValue[] }\n\t| { readonly kind: \"begin\"; readonly lockState?: SharedArrayBuffer; readonly lockTag?: number }\n\t| { readonly kind: \"dataVersion\" | \"now\" | \"jsonbExtract\" | \"close\" }\n\t| SequenceRequest;\n\n/** Rows as they cross from a connection's thread: the column names, then each row's values in their order. */\ninterface RowTable {\n\treadonly columns: readonly string[];\n\treadonly values: readonly (readonly SqliteValue[])[];\n}\n\n/** What a request's answer carries as it crosses, before rows are rebuilt. */\ntype ConnectionValue =\n\t| RowTable\n\t| { readonly changes: number }\n\t| SequenceAnswer\n\t| string\n\t| number\n\t| boolean\n\t| null\n\t| undefined;\n\n/**\n * What a request is answered with: `get` a row or undefined, `all` rows, `run` the changes, `sequence` a\n * `SequenceAnswer`, `open` the location, `dataVersion` and `now` a number, `jsonbExtract` a boolean, the others\n * undefined.\n */\nexport type ConnectionAnswer =\n\t| SqliteRow\n\t| SqliteRow[]\n\t| { readonly changes: number }\n\t| SequenceAnswer\n\t| string\n\t| number\n\t| boolean\n\t| null\n\t| undefined;\n\n/** An own field that holds a plain value: its key, value and enumerability. */\ntype ConnectionField = readonly [string, string | number | boolean | bigint, boolean];\n\n/** A failure as it crosses from a connection's thread; see `failure` in the thread's source. */\ninterface ConnectionFailure {\n\treadonly constructor: string;\n\treadonly message: string;\n\treadonly fields: readonly ConnectionField[];\n\treadonly between?: {\n\t\treadonly fields: readonly ConnectionField[];\n\t\treadonly toString?: { readonly enumerable: boolean };\n\t};\n}\n\ninterface ConnectionReply {\n\treadonly id: number;\n\treadonly value?: ConnectionValue;\n\treadonly failure?: ConnectionFailure;\n}\n\nconst STANDARD_ERRORS: Readonly<Record<string, ErrorConstructor>> = {\n\tError,\n\tTypeError,\n\tRangeError,\n\tSyntaxError,\n\tReferenceError,\n\tEvalError,\n\tURIError,\n};\n\n/** One prototype per runtime error class seen, by what it holds: see `connectionError`. */\nconst betweenPrototypes = new Map<string, object>();\n\n/** How a runtime's error class of its own shows an error, as Bun's do: `TypeError [ERR_INVALID_ARG_VALUE]: …`. */\nfunction showWithCode(this: Error & { readonly code?: unknown }): string {\n\treturn `${this.name} [${String(this.code)}]: ${this.message}`;\n}\n\nfunction betweenPrototype(base: ErrorConstructor, between: NonNullable<ConnectionFailure[\"between\"]>): object {\n\tconst key = JSON.stringify([\n\t\tbase.name,\n\t\tbetween.fields.map(([field, value, enumerable]) => [field, String(value), enumerable]),\n\t\tbetween.toString,\n\t]);\n\tlet prototype = betweenPrototypes.get(key);\n\tif (prototype === undefined) {\n\t\tconst created: object = Object.create(base.prototype);\n\t\tfor (const [field, value, enumerable] of between.fields)\n\t\t\tObject.defineProperty(created, field, { value, enumerable, writable: true, configurable: true });\n\t\tif (between.toString !== undefined)\n\t\t\tObject.defineProperty(created, \"toString\", {\n\t\t\t\tvalue: showWithCode,\n\t\t\t\tenumerable: between.toString.enumerable,\n\t\t\t\twritable: true,\n\t\t\t\tconfigurable: true,\n\t\t\t});\n\t\tbetweenPrototypes.set(key, created);\n\t\tprototype = created;\n\t}\n\treturn prototype;\n}\n\n/**\n * The driver's error, rebuilt on the calling thread as the driver threw it: an instance of the same standard error\n * class with the same message, and the same own fields (`code`, `errcode`, `errstr` for SQLite's errors) with the same\n * enumerability. A runtime's own error class between them is stood in for by a prototype that holds the same fields and\n * shows the error the same way.\n */\nfunction connectionError(failure: ConnectionFailure): Error {\n\tconst base = STANDARD_ERRORS[failure.constructor] ?? Error;\n\tconst error = new base(failure.message);\n\tif (failure.between !== undefined) Object.setPrototypeOf(error, betweenPrototype(base, failure.between));\n\tfor (const [key, value, enumerable] of failure.fields)\n\t\tObject.defineProperty(error, key, { value, enumerable, writable: true, configurable: true });\n\treturn error;\n}\n\n/** The rows of `table`, each a plain object built the way the calling-thread connection builds them. */\nfunction rowsOf(table: RowTable): SqliteRow[] {\n\tconst { columns, values } = table;\n\treturn values.map((row) => Object.fromEntries(columns.map((column, index) => [column, row[index] as SqliteValue])));\n}\n\ninterface Waiter {\n\treadonly resolve: (value: ConnectionValue) => void;\n\treadonly reject: (error: unknown) => void;\n}\n\n/** Thrown for a request to a connection whose thread is gone: closed, or lost to an error or an exit. */\nexport class ConnectionThreadEndedError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"ConnectionThreadEndedError\";\n\t}\n}\n\n/** Options that make every worker thread run code of the user's: a preload or a module loader. */\nconst WORKER_CODE_OPTIONS = new Set([\"--require\", \"-r\", \"--import\", \"--loader\", \"--experimental-loader\"]);\n\n/** The thread `startSpare` started for the next open, until an open takes it or `releaseSpare` ends it. */\nlet spare: ThreadConnection | undefined;\n\n/** How many prepared statements a connection keeps for reuse, least recently used first out. */\nexport const STATEMENT_CACHE_SIZE = 256;\n\n/** A node:sqlite connection running on its own worker thread. */\nexport class ThreadConnection {\n\tprivate readonly worker: Worker;\n\tprivate readonly waiting = new Map<number, Waiter>();\n\tprivate nextId = 1;\n\tprivate ended?: Error;\n\tprivate closing?: Promise<undefined>;\n\n\tprivate constructor() {\n\t\t// None of the process's own flags: the caller's preloads would run again for every connection, and its\n\t\t// `--input-type=module` would make this source a module. Whether node:sqlite is available was settled by the\n\t\t// open before it started the thread.\n\t\tthis.worker = new Worker(CONNECTION_SOURCE, {\n\t\t\teval: true,\n\t\t\texecArgv: [],\n\t\t\tworkerData: { nowSql: `SELECT ${sqliteDialect.nowMs} AS now`, statementCacheSize: STATEMENT_CACHE_SIZE },\n\t\t});\n\t\tthis.worker.on(\"message\", (reply: ConnectionReply) => this.receive(reply));\n\t\tthis.worker.on(\"error\", (error: Error) => this.end(error));\n\t\tthis.worker.on(\"exit\", (code: number) =>\n\t\t\tthis.end(new ConnectionThreadEndedError(`SQLite connection thread exited with code ${code}`)),\n\t\t);\n\t}\n\n\t/**\n\t * Opens `openAs` (or `path`) on a thread of its own and resolves with the location SQLite reports for it. A failure\n\t * to start the thread or to open the database rejects with its cause; the thread is gone then.\n\t */\n\tstatic async open(\n\t\tpath: string,\n\t\toptions: { readonly readOnly: boolean; readonly openAs?: string },\n\t): Promise<{ readonly connection: ThreadConnection; readonly location: string | null }> {\n\t\tconst started = spare;\n\t\tspare = undefined;\n\t\tif (started !== undefined && started.ended === undefined) {\n\t\t\ttry {\n\t\t\t\treturn await ThreadConnection.openOn(started, path, options);\n\t\t\t} catch (error) {\n\t\t\t\t// The spare thread was lost before it answered: open on a thread of its own, as without one.\n\t\t\t\tif (error !== started.ended) throw error;\n\t\t\t}\n\t\t}\n\t\treturn ThreadConnection.openOn(new ThreadConnection(), path, options);\n\t}\n\n\t/**\n\t * Starts one connection thread now, for the next open to take, so that the thread's startup overlaps whatever the\n\t * process does until then (an interactive session loads its modules meanwhile). Idle, the thread keeps nothing\n\t * alive. Nothing starts when the process runs a preload or a module loader, which every worker thread runs again,\n\t * or runs under the permission model; a thread that cannot start leaves every open as it is without one.\n\t */\n\tstatic startSpare(): void {\n\t\tif (spare !== undefined || process.permission !== undefined) return;\n\t\tif (startupNodeOptions().some((option) => WORKER_CODE_OPTIONS.has(option.name))) return;\n\t\ttry {\n\t\t\tconst started = new ThreadConnection();\n\t\t\tstarted.worker.unref();\n\t\t\tspare = started;\n\t\t} catch {\n\t\t\t// Opens start their own threads.\n\t\t}\n\t}\n\n\t/** Ends the spare thread if no open has taken it. */\n\tstatic releaseSpare(): void {\n\t\tconst started = spare;\n\t\tspare = undefined;\n\t\tif (started !== undefined) void started.stop();\n\t}\n\n\tprivate static async openOn(\n\t\tconnection: ThreadConnection,\n\t\tpath: string,\n\t\toptions: { readonly readOnly: boolean; readonly openAs?: string },\n\t): Promise<{ readonly connection: ThreadConnection; readonly location: string | null }> {\n\t\ttry {\n\t\t\tconst location = await connection.request({\n\t\t\t\tkind: \"open\",\n\t\t\t\tpath: options.openAs ?? path,\n\t\t\t\treadOnly: options.readOnly,\n\t\t\t});\n\t\t\treturn { connection, location: typeof location === \"string\" ? location : null };\n\t\t} catch (error) {\n\t\t\tawait connection.stop();\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Sends one request; resolves with the thread's answer or rejects with the driver's error, rebuilt. While a request\n\t * waits for its answer the thread keeps the process alive; an idle connection does not, as a connection on the\n\t * calling thread would not.\n\t */\n\trequest(request: ConnectionRequest): Promise<ConnectionAnswer> {\n\t\tif (request.kind === \"close\") return this.close();\n\t\tconst answer = this.send(request);\n\t\tif (request.kind === \"get\")\n\t\t\treturn answer.then((value) => (value === undefined ? undefined : rowsOf(value as RowTable)[0]));\n\t\tif (request.kind === \"all\") return answer.then((value) => rowsOf(value as RowTable));\n\t\treturn answer as Promise<ConnectionAnswer>;\n\t}\n\n\tprivate send(request: ConnectionRequest): Promise<ConnectionValue> {\n\t\treturn new Promise<ConnectionValue>((resolve, reject) => {\n\t\t\tif (this.ended !== undefined) {\n\t\t\t\treject(this.ended);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst id = this.nextId++;\n\t\t\ttry {\n\t\t\t\tthis.worker.postMessage({ id, ...request });\n\t\t\t} catch (error) {\n\t\t\t\t// A value the thread cannot receive.\n\t\t\t\treject(error);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.waiting.set(id, { resolve, reject });\n\t\t\tif (this.waiting.size === 1) this.worker.ref();\n\t\t});\n\t}\n\n\t/**\n\t * Closes the database on its thread, then ends the thread: a `close` request. Requests sent after it are rejected. A\n\t * thread already lost has nothing to close.\n\t */\n\tprivate close(): Promise<undefined> {\n\t\tthis.closing ??= (async () => {\n\t\t\ttry {\n\t\t\t\tif (this.ended === undefined) await this.send({ kind: \"close\" });\n\t\t\t} finally {\n\t\t\t\tawait this.stop();\n\t\t\t}\n\t\t\treturn undefined;\n\t\t})();\n\t\treturn this.closing;\n\t}\n\n\tprivate receive(reply: ConnectionReply): void {\n\t\tconst waiter = this.waiting.get(reply.id);\n\t\tif (waiter === undefined) return;\n\t\tthis.waiting.delete(reply.id);\n\t\tif (this.waiting.size === 0) this.worker.unref();\n\t\tif (reply.failure === undefined) waiter.resolve(reply.value);\n\t\telse waiter.reject(connectionError(reply.failure));\n\t}\n\n\t/** Rejects every request still waiting, oldest first, and every later one. Ending again does nothing. */\n\tprivate end(cause: Error): void {\n\t\tif (this.ended !== undefined) return;\n\t\t// Kept for as long as the connection is: an error's stack, until formatted, keeps the functions of the frames it\n\t\t// names, and so whatever they hold, such as a session that closed its store.\n\t\tvoid cause.stack;\n\t\tthis.ended = cause;\n\t\tconst waiting = [...this.waiting.values()];\n\t\tthis.waiting.clear();\n\t\tthis.worker.unref();\n\t\tfor (const waiter of waiting) waiter.reject(cause);\n\t}\n\n\tprivate async stop(): Promise<void> {\n\t\tthis.end(new ConnectionThreadEndedError(\"SQLite connection closed\"));\n\t\tawait this.worker.terminate();\n\t}\n\n\t/** Calls `listener` once the connection's thread has exited, whether closed or lost. */\n\tonExit(listener: () => void): void {\n\t\tthis.worker.once(\"exit\", listener);\n\t}\n\n\t/**\n\t * Starts a spare worker for a non-interactive or storage-overridden CLI\n\t * invocation only when the real CLI/storage resolvers select a SQLite store.\n\t */\n\tstatic async startSpareIfSqlNeeded(\n\t\targs: readonly string[],\n\t\tterminal: { readonly stdinIsTTY: boolean; readonly stdoutIsTTY: boolean },\n\t\tstillBeforeMain: () => boolean,\n\t): Promise<void> {\n\t\tconst { shouldStartSpareDatabaseThread } = await import(\"../../utils/startup-database-spare.ts\");\n\t\tif (stillBeforeMain() && shouldStartSpareDatabaseThread(args, false, terminal)) {\n\t\t\tThreadConnection.startSpare();\n\t\t}\n\t}\n}\n"]}
|