@bastani/atomic 0.10.17 → 0.10.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (312) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/dist/_shared/dist-KOELCESV.js +2 -2
  3. package/dist/_shared/fork-row-index-UAUAQRD5.js +2 -2
  4. package/dist/_shared/lib-4PES5P4V.js +2 -2
  5. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js +6 -6
  6. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js.map +1 -1
  7. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +16 -4
  8. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js.map +1 -1
  9. package/dist/_shared/mode-shared-2QJSCUM6.js +16 -9
  10. package/dist/_shared/mode-shared-2QJSCUM6.js.map +1 -1
  11. package/dist/_shared/p0-cli-BB45ZQY6.js +1 -0
  12. package/dist/_shared/p0-cli-BB45ZQY6.js.map +1 -1
  13. package/dist/_shared/p1a-prewarm-XIU57JHF.js +4 -3
  14. package/dist/_shared/p1a-prewarm-XIU57JHF.js.map +1 -1
  15. package/dist/_shared/p2-shell-main-B2WIALFD.js +1 -1
  16. package/dist/_shared/p2-shell-main-B2WIALFD.js.map +1 -1
  17. package/dist/_shared/runtime-O4KCSG4C.js +2 -2
  18. package/dist/_shared/sdk-OHKMDJ74.js +18 -15
  19. package/dist/_shared/sdk-OHKMDJ74.js.map +1 -1
  20. package/dist/_shared/session-data-AHTU7IS6.js +2 -2
  21. package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
  22. package/dist/_shared/{startup-0-0-ERMIDHQT.js → startup-0-0-OV6RAEAP.js} +338 -75
  23. package/dist/_shared/startup-0-0-OV6RAEAP.js.map +1 -0
  24. package/dist/_shared/{startup-0-1-RTASI3HG.js → startup-0-1-EZAJI6RE.js} +82 -5
  25. package/dist/_shared/startup-0-1-EZAJI6RE.js.map +1 -0
  26. package/dist/_shared/startup-0-2-YZZOC22D.js +4 -4
  27. package/dist/_shared/startup-0-3-DE2NCS6A.js +4 -4
  28. package/dist/_shared/startup-0-4-ZMJV547D.js +12 -7
  29. package/dist/_shared/startup-0-4-ZMJV547D.js.map +1 -1
  30. package/dist/_shared/startup-0-5-HZX3ZPTP.js +41 -12
  31. package/dist/_shared/startup-0-5-HZX3ZPTP.js.map +1 -1
  32. package/dist/_shared/startup-10-0-TDQNBDDL.js +5 -5
  33. package/dist/_shared/startup-10-0-TDQNBDDL.js.map +1 -1
  34. package/dist/_shared/startup-12-0-55AAXBJZ.js +1 -1
  35. package/dist/_shared/startup-14-0-MLX36RBG.js +2 -2
  36. package/dist/_shared/startup-15-0-YUKGAC63.js +2 -2
  37. package/dist/_shared/startup-15-1-4S7FLMNG.js +261 -75
  38. package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
  39. package/dist/_shared/startup-8-0-34CBHPZH.js +23 -8
  40. package/dist/_shared/startup-8-0-34CBHPZH.js.map +1 -1
  41. package/dist/_shared/startup-8-1-LZFXSD3Z.js +328 -19
  42. package/dist/_shared/startup-8-1-LZFXSD3Z.js.map +1 -1
  43. package/dist/_shared/storage-command-7MGXLJGZ.js +74 -10
  44. package/dist/_shared/storage-command-7MGXLJGZ.js.map +1 -1
  45. package/dist/_shared/storage-status-K7PX2RXA.js +2 -2
  46. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  47. package/dist/_shared/team-DOQKICG2.js +1 -1
  48. package/dist/_shared/tree-outline-MUEPK5B7.js +2 -2
  49. package/dist/builtin/intercom/broker/broker.bundle.mjs +158 -78
  50. package/dist/builtin/intercom/broker/multinode-router.ts +41 -8
  51. package/dist/builtin/intercom/broker/multinode-state-store.ts +6 -1
  52. package/dist/builtin/intercom/broker/sql-lease-store.ts +89 -80
  53. package/dist/builtin/intercom/broker/sql-pending-ask-store.ts +65 -6
  54. package/dist/builtin/intercom/index.bundle.mjs +1 -1
  55. package/dist/builtin/intercom/package.json +1 -1
  56. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  57. package/dist/builtin/mcp/package.json +1 -1
  58. package/dist/builtin/subagents/package.json +1 -1
  59. package/dist/builtin/subagents/src/extension/index.bundle.mjs +1 -1
  60. package/dist/builtin/web-access/index.bundle.mjs +1 -1
  61. package/dist/builtin/web-access/package.json +1 -1
  62. package/dist/cli/args.js +2 -2
  63. package/dist/cli/auth-cli.code.js +2 -2
  64. package/dist/cli/auth-cli.impl.js +3 -3
  65. package/dist/cli/auth-cli.js +3 -3
  66. package/dist/cli/blueprint-command.code.js +1 -1
  67. package/dist/cli/blueprint-command.impl.js +3 -3
  68. package/dist/cli/blueprint-command.js +3 -3
  69. package/dist/cli/intercom-command.code.js +2 -2
  70. package/dist/cli/intercom-command.impl.js +3 -3
  71. package/dist/cli/intercom-command.js +3 -3
  72. package/dist/cli/list-models.code.js +2 -2
  73. package/dist/cli/list-models.impl.js +3 -3
  74. package/dist/cli/list-models.js +3 -3
  75. package/dist/cli/session-picker.code.js +1 -1
  76. package/dist/cli/session-picker.impl.js +3 -3
  77. package/dist/cli/session-picker.js +3 -3
  78. package/dist/cli/startup-ui.code.js +1 -1
  79. package/dist/cli/startup-ui.impl.js +3 -3
  80. package/dist/cli/startup-ui.js +3 -3
  81. package/dist/cli/storage-command.impl.js +3 -3
  82. package/dist/cli/storage-command.js +3 -3
  83. package/dist/cli/storage-search-session.code.js +1 -1
  84. package/dist/cli/storage-search-session.impl.js +3 -3
  85. package/dist/cli/storage-search-session.js +3 -3
  86. package/dist/cli/team-command.code.js +1 -1
  87. package/dist/cli/team-command.impl.js +3 -3
  88. package/dist/cli/team-command.js +3 -3
  89. package/dist/cli.js +2 -2
  90. package/dist/core/debug.impl.js +3 -3
  91. package/dist/core/debug.js +3 -3
  92. package/dist/core/export-html/card-projection.impl.js +3 -3
  93. package/dist/core/export-html/card-projection.js +3 -3
  94. package/dist/core/export-html/index.code.js +2 -2
  95. package/dist/core/export-html/index.impl.js +3 -3
  96. package/dist/core/export-html/index.js +3 -3
  97. package/dist/core/export-html/json-spans.impl.js +3 -3
  98. package/dist/core/export-html/json-spans.js +3 -3
  99. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  100. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  101. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  102. package/dist/core/export-html/tool-renderer.js +3 -3
  103. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  104. package/dist/core/extensions/jiti-loader.js +3 -3
  105. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  106. package/dist/core/extensions/jiti-static-loader.js +3 -3
  107. package/dist/core/extensions/loader-host-modules.code.js +1 -1
  108. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  109. package/dist/core/extensions/loader-host-modules.js +3 -3
  110. package/dist/core/extensions/loader-virtual-modules.js +1 -1
  111. package/dist/core/extensions/runner-context.js +1 -1
  112. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  113. package/dist/core/intercom-broker-control-host.js +3 -3
  114. package/dist/core/intercom-broker-control.code.js +3 -3
  115. package/dist/core/intercom-broker-control.impl.js +3 -3
  116. package/dist/core/intercom-broker-control.js +3 -3
  117. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  118. package/dist/core/package-manager-storage-adapters.js +3 -3
  119. package/dist/core/sdk.code.js +2 -2
  120. package/dist/core/sdk.impl.js +3 -3
  121. package/dist/core/sdk.js +3 -3
  122. package/dist/core/session-append-recovery.d.ts +3 -3
  123. package/dist/core/session-manager-core.d.ts +1 -1
  124. package/dist/core/session-manager-core.js +14 -13
  125. package/dist/core/session-manager-core.js.map +1 -1
  126. package/dist/core/session-manager-list.impl.js +3 -3
  127. package/dist/core/session-manager-list.js +3 -3
  128. package/dist/core/session-manager.code.js +1 -1
  129. package/dist/core/session-manager.impl.js +3 -3
  130. package/dist/core/session-manager.js +3 -3
  131. package/dist/core/session-storage.impl.js +3 -3
  132. package/dist/core/session-storage.js +3 -3
  133. package/dist/core/storage/database.d.ts +6 -2
  134. package/dist/core/storage/database.js.map +1 -1
  135. package/dist/core/storage/errors.d.ts +8 -5
  136. package/dist/core/storage/errors.js +5 -3
  137. package/dist/core/storage/errors.js.map +1 -1
  138. package/dist/core/storage/fenced-paths.d.ts +15 -0
  139. package/dist/core/storage/fenced-paths.js +25 -0
  140. package/dist/core/storage/fenced-paths.js.map +1 -1
  141. package/dist/core/storage/index.js +2 -2
  142. package/dist/core/storage/migrations.d.ts +2 -11
  143. package/dist/core/storage/migrations.js +2 -9
  144. package/dist/core/storage/migrations.js.map +1 -1
  145. package/dist/core/storage/node-sqlite-thread.js +2 -2
  146. package/dist/core/storage/node-sqlite.js +2 -2
  147. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  148. package/dist/core/storage/offline-snapshot-file.js +3 -3
  149. package/dist/core/storage/postgres-locks.d.ts +11 -0
  150. package/dist/core/storage/postgres-locks.js +9 -0
  151. package/dist/core/storage/postgres-locks.js.map +1 -0
  152. package/dist/core/storage/provider.js +2 -2
  153. package/dist/core/storage/selection.js +2 -2
  154. package/dist/core/storage/session/branch-fork-source.code.js +2 -2
  155. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  156. package/dist/core/storage/session/branch-fork-source.js +3 -3
  157. package/dist/core/storage/session/card-view.impl.js +3 -3
  158. package/dist/core/storage/session/card-view.js +3 -3
  159. package/dist/core/storage/session/child-reader.code.js +3 -3
  160. package/dist/core/storage/session/child-reader.impl.js +3 -3
  161. package/dist/core/storage/session/child-reader.js +3 -3
  162. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  163. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  164. package/dist/core/storage/session/expanded-child-details.code.js +2 -2
  165. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  166. package/dist/core/storage/session/expanded-child-details.js +3 -3
  167. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  168. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  169. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  170. package/dist/core/storage/session/fork-row-index.js +3 -3
  171. package/dist/core/storage/session/fork-staging.code.js +1 -1
  172. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  173. package/dist/core/storage/session/fork-staging.js +3 -3
  174. package/dist/core/storage/session/fork-window.code.js +3 -3
  175. package/dist/core/storage/session/fork-window.impl.js +3 -3
  176. package/dist/core/storage/session/fork-window.js +3 -3
  177. package/dist/core/storage/session/history-pages.impl.js +3 -3
  178. package/dist/core/storage/session/history-pages.js +3 -3
  179. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  180. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  181. package/dist/core/storage/session/jsonl-session-store.d.ts +1 -0
  182. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  183. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  184. package/dist/core/storage/session/memory-session-store.d.ts +1 -0
  185. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  186. package/dist/core/storage/session/memory-session-store.js +3 -3
  187. package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
  188. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  189. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  190. package/dist/core/storage/session/released-history-files.code.js +2 -2
  191. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  192. package/dist/core/storage/session/released-history-files.js +3 -3
  193. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  194. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  195. package/dist/core/storage/session/session-resume.impl.js +3 -3
  196. package/dist/core/storage/session/session-resume.js +3 -3
  197. package/dist/core/storage/session/session-summary.d.ts +9 -1
  198. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  199. package/dist/core/storage/session/snapshot-cut.js +3 -3
  200. package/dist/core/storage/session/snapshot-history.code.js +3 -3
  201. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  202. package/dist/core/storage/session/snapshot-history.js +3 -3
  203. package/dist/core/storage/session/sql-session-store.d.ts +2 -1
  204. package/dist/core/storage/session/sql-session-store.impl.js +3 -3
  205. package/dist/core/storage/session/sql-session-store.js +3 -3
  206. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  207. package/dist/core/storage/session/tree-outline.js +3 -3
  208. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  209. package/dist/core/storage/session/tree-presentation.js +3 -3
  210. package/dist/core/storage/session/types.d.ts +1 -0
  211. package/dist/core/storage/sqlite-facade.js +12 -5
  212. package/dist/core/storage/sqlite-facade.js.map +1 -1
  213. package/dist/core/storage/storage-status.impl.js +3 -3
  214. package/dist/core/storage/storage-status.js +3 -3
  215. package/dist/core/storage/team.impl.js +3 -3
  216. package/dist/core/storage/team.js +3 -3
  217. package/dist/core/structured-output/index.impl.js +3 -3
  218. package/dist/core/structured-output/index.js +3 -3
  219. package/dist/core/tasks/heartbeat-notice.d.ts +0 -1
  220. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  221. package/dist/core/tasks/task-completion-entry.js +3 -3
  222. package/dist/core/tasks/task-file-history.code.js +3 -3
  223. package/dist/core/tasks/task-file-history.impl.js +3 -3
  224. package/dist/core/tasks/task-file-history.js +3 -3
  225. package/dist/core/tasks/task-reference-archive.code.js +3 -3
  226. package/dist/core/tasks/task-reference-archive.js +3 -3
  227. package/dist/core/tasks/task-reference-identity.js +3 -3
  228. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  229. package/dist/core/tasks/task-reference-stream.js +3 -3
  230. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  231. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  232. package/dist/core/tasks/task-view-source.impl.js +3 -3
  233. package/dist/core/tasks/task-view-source.js +3 -3
  234. package/dist/core/tools/history-session.d.ts +1 -1
  235. package/dist/core/tools/output-accumulator.d.ts +3 -0
  236. package/dist/core/tools/read-url.code.js +2 -2
  237. package/dist/core/tools/read-url.impl.js +3 -3
  238. package/dist/core/tools/read-url.js +3 -3
  239. package/dist/core/worktree-snapshot/blob-store.d.ts +14 -16
  240. package/dist/core/worktree-snapshot/blob-store.js +194 -81
  241. package/dist/core/worktree-snapshot/blob-store.js.map +1 -1
  242. package/dist/core/worktree-snapshot/collection-claim.js +8 -0
  243. package/dist/core/worktree-snapshot/collection-claim.js.map +1 -0
  244. package/dist/core/worktree-snapshot/errors.code.js +2 -2
  245. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  246. package/dist/core/worktree-snapshot/errors.js +3 -3
  247. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  248. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  249. package/dist/core/worktree-snapshot/snapshot-epoch-migration.js +209 -0
  250. package/dist/core/worktree-snapshot/snapshot-epoch-migration.js.map +1 -0
  251. package/dist/core/worktree-snapshot/snapshot-epoch.js +100 -0
  252. package/dist/core/worktree-snapshot/snapshot-epoch.js.map +1 -0
  253. package/dist/extensions/codemode/execute.code.js +1 -1
  254. package/dist/extensions/codemode/execute.impl.js +3 -3
  255. package/dist/extensions/codemode/execute.js +3 -3
  256. package/dist/extensions/codemode/renderer.code.js +1 -1
  257. package/dist/extensions/codemode/renderer.impl.js +3 -3
  258. package/dist/extensions/codemode/renderer.js +3 -3
  259. package/dist/extensions/mcp/cli.code.js +1 -1
  260. package/dist/extensions/mcp/cli.impl.js +3 -3
  261. package/dist/extensions/mcp/cli.js +3 -3
  262. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  263. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  264. package/dist/extensions/mcp/cli.lazy.js +3 -3
  265. package/dist/extensions/mcp/runtime.impl.js +3 -3
  266. package/dist/extensions/mcp/runtime.js +3 -3
  267. package/dist/index.js +2 -2
  268. package/dist/main-first-time-setup.code.js +1 -1
  269. package/dist/main-first-time-setup.impl.js +3 -3
  270. package/dist/main-first-time-setup.js +3 -3
  271. package/dist/modes/interactive/components/stored-tree-view.code.js +2 -2
  272. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  273. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  274. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  275. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  276. package/dist/modes/interactive/interactive-mode-helpers.d.ts +8 -1
  277. package/dist/modes/interactive-engine/isolated-runtime.d.ts +21 -0
  278. package/dist/modes/interactive-engine/protocol.d.ts +6 -0
  279. package/dist/modes/rpc/rpc-client.d.ts +2 -0
  280. package/dist/package-manager-cli.code.js +4 -4
  281. package/dist/package-manager-cli.impl.js +3 -3
  282. package/dist/package-manager-cli.js +3 -3
  283. package/dist/rpc-entry.js +1 -1
  284. package/dist/startup-files.json +1 -1
  285. package/dist/startup-stages/4.js +1 -1
  286. package/dist/startup-stages/6.js +1 -1
  287. package/dist/utils/interactive-engine-bootstrap.d.ts +2 -0
  288. package/dist/utils/interactive-engine-env.d.ts +2 -0
  289. package/dist/utils/startup-database-spare.code.js +2 -2
  290. package/dist/utils/startup-database-spare.impl.js +3 -3
  291. package/dist/utils/startup-database-spare.js +3 -3
  292. package/dist/utils/tools-manager.code.js +1 -1
  293. package/dist/utils/tools-manager.impl.js +3 -3
  294. package/dist/utils/tools-manager.js +3 -3
  295. package/docs/background-tasks/reference.md +1 -1
  296. package/docs/background-tasks.md +1 -1
  297. package/docs/changelog.mdx +18 -1
  298. package/docs/guides/resume-on-any-machine.md +1 -1
  299. package/docs/reference/cli.md +4 -3
  300. package/docs/sdk.md +2 -1
  301. package/docs/sessions.md +5 -2
  302. package/docs/settings.md +1 -0
  303. package/docs/storage/custom-adapters.md +1 -1
  304. package/docs/storage/postgres/pgbouncer.md +3 -1
  305. package/docs/storage/postgres/tuning.md +2 -0
  306. package/docs/storage/postgres.md +58 -7
  307. package/docs/storage.md +4 -2
  308. package/docs/tools.md +1 -0
  309. package/docs/worktree-snapshots/reference.md +1 -1
  310. package/package.json +8 -8
  311. package/dist/_shared/startup-0-0-ERMIDHQT.js.map +0 -1
  312. package/dist/_shared/startup-0-1-RTASI3HG.js.map +0 -1
@@ -52,6 +52,14 @@ const FENCED_PATHS = {
52
52
  ],
53
53
  conformance: "many brokers acquire, renew and release one lease concurrently: never two holders, fencing tokens strictly increase, a stale holder's renewal fails (#6560)",
54
54
  },
55
+ /** Intercom's lost-recipient sweep returns only the asks its guarded UPDATE marks ended. */
56
+ "intercom-lost-ask": {
57
+ fences: [
58
+ "the sweep leader's exact lease and the recipient's presence rows, FOR SHARE NOWAIT",
59
+ "open ask rows, in insertion order FOR UPDATE SKIP LOCKED before marking",
60
+ ],
61
+ conformance: "concurrent lost-recipient sweeps return an ask once and never queue on advisory locks (#6831)",
62
+ },
55
63
  /**
56
64
  * Intercom's wake-up hint log (`intercom_wakeups`): a hint is a row inserted once and deleted by its id or its age,
57
65
  * and no write reads the log to decide what to write, so its writers take no lock domain: the bus's `publish`
@@ -102,6 +110,23 @@ const FENCED_PATHS = {
102
110
  fences: ["the setup's advisory locks, all tried by its first statement without waiting"],
103
111
  conformance: "many hosts open a new database at once: each schema is set up once, every host opens, and none waits in a lock queue (#6560)",
104
112
  },
113
+ /** Snapshot reference writers and cleanup select the database's coordination mode in the transaction. */
114
+ "snapshot-epoch": {
115
+ fences: [
116
+ "shared epoch transition gate",
117
+ "legacy database key only in compatibility mode",
118
+ "domain key if required",
119
+ ],
120
+ conformance: "an ordinary session writer commits while an older collector holds the old key (#6832)",
121
+ },
122
+ /** Snapshot cleanup backs off outside the transaction if either advisory lock is busy. */
123
+ "snapshot-collection": {
124
+ fences: [
125
+ "claim bookkeeping: try the database lock shared, then try the collection table's lock exclusively, then update the claim row",
126
+ "data batches: try the legacy database lock exclusively, then recheck the claim and the data before writing",
127
+ ],
128
+ conformance: "busy snapshot collection does not queue ahead of session writers, then deletes the orphaned blobs (#6831)",
129
+ },
105
130
  /**
106
131
  * `SqlRateBuckets.acquire` and `cooldown`: one `UPDATE … RETURNING` (or upsert) of the scope's bucket row, which locks
107
132
  * no pool row, so it orders after none of them (#4768).
@@ -1 +1 @@
1
- {"version":3,"file":"fenced-paths.js","sourceRoot":"","sources":["../../../src/core/storage/fenced-paths.ts"],"names":[],"mappings":"AAUA;;;GAGG;AACH,MAAM,YAAY,GAAG;IACpB,gIAAgI;IAChI,YAAY,EAAE;QACb,MAAM,EAAE;YACP,8BAA8B;YAC9B,2CAA2C;YAC3C,uCAAuC;SACvC;QACD,WAAW,EAAE,6FAA6F;KAC1G;IACD,oHAAoH;IACpH,gBAAgB,EAAE;QACjB,MAAM,EAAE,CAAC,8BAA8B,EAAE,+BAA+B,EAAE,uBAAuB,CAAC;QAClG,WAAW,EAAE,6FAA6F;KAC1G;IACD,qHAAqH;IACrH,aAAa,EAAE;QACd,MAAM,EAAE;YACP,oHAAoH;YACpH,8BAA8B;YAC9B,+BAA+B;YAC/B,yGAAyG;YACzG,uBAAuB;SACvB;QACD,WAAW,EAAE,8EAA8E;KAC3F;IACD,0EAA0E;IAC1E,eAAe,EAAE;QAChB,MAAM,EAAE;YACP,8BAA8B;YAC9B,+BAA+B;YAC/B,2CAA2C;SAC3C;QACD,WAAW,EAAE,6FAA6F;KAC1G;IACD;;;;;;;OAOG;IACH,gBAAgB,EAAE;QACjB,MAAM,EAAE;YACP,4GAA4G;YAC5G,2EAA2E;SAC3E;QACD,WAAW,EACV,6JAA6J;KAC9J;IACD;;;;;OAKG;IACH,sBAAsB,EAAE;QACvB,MAAM,EAAE,CAAC,gDAAgD,CAAC;QAC1D,WAAW,EAAE,oFAAoF;KACjG;IACD;;;;;;;;;OASG;IACH,qBAAqB,EAAE;QACtB,MAAM,EAAE;YACP,mKAAmK;YACnK,mEAAmE;SACnE;QACD,WAAW,EACV,+JAA+J;KAChK;IACD;;;;;;;OAOG;IACH,oBAAoB,EAAE;QACrB,MAAM,EAAE,CAAC,4FAA4F,CAAC;QACtG,WAAW,EACV,6GAA6G;KAC9G;IACD;;;;;;OAMG;IACH,cAAc,EAAE;QACf,MAAM,EAAE,CAAC,8EAA8E,CAAC;QACxF,WAAW,EACV,8HAA8H;KAC/H;IACD;;;OAGG;IACH,aAAa,EAAE;QACd,MAAM,EAAE,CAAC,gDAAgD,CAAC;QAC1D,WAAW,EAAE,iGAAiG;KAC9G;CAC4D,CAAC;AAI/D,yCAAyC;AACzC,MAAM,UAAU,eAAe,CAAC,IAAoB;IACnD,OAAO,YAAY,CAAC,IAAI,CAAC,CAAC;AAC3B,CAAC;AAED,iGAAiG;AACjG,MAAM,UAAU,UAAU,CAAC,IAAoB;IAC9C,OAAO,IAAoB,CAAC;AAC7B,CAAC","sourcesContent":["import type { FencedPathId } from \"./database.js\";\n\n/** What makes a fenced write path correct without the domain's serial lock. */\nexport interface FencedPathAudit {\n\t/** The rows the path locks, in the order it locks them (the same order on every fenced path, so none deadlock). */\n\treadonly fences: readonly string[];\n\t/** The conformance test that runs the path concurrently on every backend. */\n\treadonly conformance: string;\n}\n\n/**\n * Every audited path that may run a `fenced` transaction. A path is added here, with its fences and its test, in the\n * change that makes it fenced; nothing else can name one.\n */\nconst FENCED_PATHS = {\n\t/** `SqlPoolQueue.claim`: one `UPDATE … WHERE id = (SELECT … FOR UPDATE SKIP LOCKED)`, so claimers never wait on one another. */\n\t\"pool-claim\": {\n\t\tfences: [\n\t\t\t\"root lease row FOR KEY SHARE\",\n\t\t\t\"root run row FOR SHARE, then pool control\",\n\t\t\t\"ready work row FOR UPDATE SKIP LOCKED\",\n\t\t],\n\t\tconformance: \"many hosts claim, commit and complete concurrently: no double claim, no lost settle (#5102)\",\n\t},\n\t/** `SqlPoolQueue.renew`, `extend` and `heartbeat`: the attempt's lease, its claim confirmation and usage report. */\n\t\"pool-heartbeat\": {\n\t\tfences: [\"root lease row FOR KEY SHARE\", \"attempt's work row FOR UPDATE\", \"root usage totals row\"],\n\t\tconformance: \"claim, commit, heartbeat, complete and takeover run concurrently without a deadlock (#5102)\",\n\t},\n\t/** `SqlPoolQueue.commit` of a checkpoint or a session: the event takes the run's next sequence under its run row. */\n\t\"pool-commit\": {\n\t\tfences: [\n\t\t\t\"the database-wide serial lock, shared, only when the checkpoint records worktree snapshots (before every row lock)\",\n\t\t\t\"root lease row FOR KEY SHARE\",\n\t\t\t\"attempt's work row FOR UPDATE\",\n\t\t\t\"root run row FOR UPDATE (FOR SHARE without an event), then pool control and the snapshots' stored blobs\",\n\t\t\t\"root usage totals row\",\n\t\t],\n\t\tconformance: \"32 concurrent writers commit one event per key with a dense sequence (#5102)\",\n\t},\n\t/** `SqlPoolQueue.complete`: the result and the work row's final state. */\n\t\"pool-complete\": {\n\t\tfences: [\n\t\t\t\"root lease row FOR KEY SHARE\",\n\t\t\t\"attempt's work row FOR UPDATE\",\n\t\t\t\"root run row FOR SHARE, then pool control\",\n\t\t],\n\t\tconformance: \"many hosts claim, commit and complete concurrently: no double claim, no lost settle (#5102)\",\n\t},\n\t/**\n\t * Intercom's broker leases (`openSqlBrokerLeaseStore`): `acquire` is one upsert whose guard takes the row only while\n\t * it is free, stale or the acquirer's own, `renew` and `release` one `UPDATE` guarded by holder and fencing token, and\n\t * `renewMany` those updates in (kind, key) order. Each decides on its own row lock, never on an earlier read (#6560).\n\t * On PostgreSQL a first acquisition takes its order from the lease order sequence, which waits for nothing; where\n\t * `atomic storage migrate` has not created it yet, `acquire`'s statement first upserts the acquisition-order counter\n\t * row instead, which no other path locks.\n\t */\n\t\"intercom-lease\": {\n\t\tfences: [\n\t\t\t\"acquire only, without the order sequence: the acquisition-order counter row, by the statement's own upsert\",\n\t\t\t\"each lease row, by its own guarded upsert or UPDATE, in (kind, key) order\",\n\t\t],\n\t\tconformance:\n\t\t\t\"many brokers acquire, renew and release one lease concurrently: never two holders, fencing tokens strictly increase, a stale holder's renewal fails (#6560)\",\n\t},\n\t/**\n\t * Intercom's wake-up hint log (`intercom_wakeups`): a hint is a row inserted once and deleted by its id or its age,\n\t * and no write reads the log to decide what to write, so its writers take no lock domain: the bus's `publish`\n\t * inserts a hint and notifies in one transaction that commits both, an outbox enqueue inserts one inside its own\n\t * transaction, and the bus's poll and pruning delete rows in single statements (#6560).\n\t */\n\t\"intercom-wakeup-hint\": {\n\t\tfences: [\"none: the new hint row only, by its own INSERT\"],\n\t\tconformance: \"delivers each hint published at once from several connections exactly once (#6560)\",\n\t},\n\t/**\n\t * Intercom's outbox rows and sent-message reservations (`openSqlOutboxStore`, `openSqlSentMessageAuthority`), which\n\t * left the outbox's one lock domain (#6560). A claim reads its recipient's undelivered rows `FOR UPDATE` in sequence\n\t * order, then claims them; a single claim's renewal, saving report, release and settlement are each one `UPDATE`\n\t * guarded by message id, claimant, token and state; batched `markDelivered`, `renewClaims`, `releaseClaims`, expiry\n\t * and `releaseClaimsOf` lock their rows in sequence order in a subquery; a reservation, an acceptance and a forget\n\t * are each one statement on the message's row, guarded by its digest. Each decides on the rows it locks, never on an\n\t * earlier read. They exclude the database-wide transactions an older broker runs on these tables (`excludesSerial`).\n\t * A send itself is a serial transaction of its recipient's domain.\n\t */\n\t\"intercom-outbox-row\": {\n\t\tfences: [\n\t\t\t\"outbox rows, FOR UPDATE in sequence order (claim, markDelivered batch, renewClaims, releaseClaims, expiry, releaseClaimsOf), or one row by its own guarded UPDATE\",\n\t\t\t\"one sent-message row, by its own guarded INSERT, UPDATE or DELETE\",\n\t\t],\n\t\tconformance:\n\t\t\t\"a send to one recipient does not wait while another recipient's claim holds its rows; sends to one recipient keep their order and suppress duplicates (#6560)\",\n\t},\n\t/**\n\t * A cleanup's claim of a lapsed fork staging transfer (`cleanupForkStaging`): it reads one lapsed lease row `FOR\n\t * UPDATE SKIP LOCKED`, then takes it over with one `UPDATE` guarded by the lease still being lapsed, so it never waits\n\t * for a live transfer whose writer or publication holds its lease, and two claims never take one transfer. Any lapsed\n\t * transfer may be claimed in any order. The claim names no transfer before it reads, so it takes no lock domain; the\n\t * owner's writes and the cleanup's removals are serial transactions of the transfer's own domain, and each decides on\n\t * the lease row it locks by its token first (#6560).\n\t */\n\t\"fork-staging-claim\": {\n\t\tfences: [\"one lapsed lease row of the staging table, FOR UPDATE SKIP LOCKED, then its guarded UPDATE\"],\n\t\tconformance:\n\t\t\t\"concurrent cleanups take each lapsed transfer over once and never a live one, beside staging clones (#6560)\",\n\t},\n\t/**\n\t * A schema setup that hosts opening a new database at once run once (`setUpStorageOnce`): its first statement tries,\n\t * without waiting, the advisory locks every setup of the same objects takes (the prefix's setup lock, and for a\n\t * domain's migration that domain's lock and the database's, shared, as an earlier build's migration takes them), and\n\t * the setup runs only where it took them all. A process that finds one taken waits outside any transaction until the\n\t * setup is recorded, so the hosts never queue for the lock (#6560).\n\t */\n\t\"schema-setup\": {\n\t\tfences: [\"the setup's advisory locks, all tried by its first statement without waiting\"],\n\t\tconformance:\n\t\t\t\"many hosts open a new database at once: each schema is set up once, every host opens, and none waits in a lock queue (#6560)\",\n\t},\n\t/**\n\t * `SqlRateBuckets.acquire` and `cooldown`: one `UPDATE … RETURNING` (or upsert) of the scope's bucket row, which locks\n\t * no pool row, so it orders after none of them (#4768).\n\t */\n\t\"rate-bucket\": {\n\t\tfences: [\"the scope's rate bucket row, by its own UPDATE\"],\n\t\tconformance: \"many hosts acquire from one rate bucket concurrently and never take more than it allows (#4768)\",\n\t},\n} as const satisfies Readonly<Record<string, FencedPathAudit>>;\n\nexport type FencedPathName = keyof typeof FENCED_PATHS;\n\n/** The audit record of a fenced path. */\nexport function fencedPathAudit(name: FencedPathName): FencedPathAudit {\n\treturn FENCED_PATHS[name];\n}\n\n/** The `FencedPathId` that lets an audited path run `{ kind: \"fenced\", audit }` transactions. */\nexport function fencedPath(name: FencedPathName): FencedPathId {\n\treturn name as FencedPathId;\n}\n"]}
1
+ {"version":3,"file":"fenced-paths.js","sourceRoot":"","sources":["../../../src/core/storage/fenced-paths.ts"],"names":[],"mappings":"AAUA;;;GAGG;AACH,MAAM,YAAY,GAAG;IACpB,gIAAgI;IAChI,YAAY,EAAE;QACb,MAAM,EAAE;YACP,8BAA8B;YAC9B,2CAA2C;YAC3C,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AAgD;YAChD,wBAAwB;SACxB;QACD,WAAW,EAAE,uFAAuF;KACpG;IACD,0FAA0F;IAC1F,qBAAqB,EAAE;QACtB,MAAM,EAAE;YACP,8HAA8H;YAC9H,4GAA4G;SAC5G;QACD,WAAW,EACV,2GAA2G;KAC5G;IACD;;;OAGG;IACH,aAAa,EAAE;QACd,MAAM,EAAE,CAAC,gDAAgD,CAAC;QAC1D,WAAW,EAAE,iGAAiG;KAC9G;CAC4D,CAAC;AAI/D,yCAAyC;AACzC,MAAM,UAAU,eAAe,CAAC,IAAoB;IACnD,OAAO,YAAY,CAAC,IAAI,CAAC,CAAC;AAC3B,CAAC;AAED,iGAAiG;AACjG,MAAM,UAAU,UAAU,CAAC,IAAoB;IAC9C,OAAO,IAAoB,CAAC;AAC7B,CAAC","sourcesContent":["import type { FencedPathId } from \"./database.js\";\n\n/** What makes a fenced write path correct without the domain's serial lock. */\nexport interface FencedPathAudit {\n\t/** The rows the path locks, in the order it locks them (the same order on every fenced path, so none deadlock). */\n\treadonly fences: readonly string[];\n\t/** The conformance test that runs the path concurrently on every backend. */\n\treadonly conformance: string;\n}\n\n/**\n * Every audited path that may run a `fenced` transaction. A path is added here, with its fences and its test, in the\n * change that makes it fenced; nothing else can name one.\n */\nconst FENCED_PATHS = {\n\t/** `SqlPoolQueue.claim`: one `UPDATE … WHERE id = (SELECT … FOR UPDATE SKIP LOCKED)`, so claimers never wait on one another. */\n\t\"pool-claim\": {\n\t\tfences: [\n\t\t\t\"root lease row FOR KEY SHARE\",\n\t\t\t\"root run row FOR SHARE, then pool control\",\n\t\t\t\"ready work row FOR UPDATE SKIP LOCKED\",\n\t\t],\n\t\tconformance: \"many hosts claim, commit and complete concurrently: no double claim, no lost settle (#5102)\",\n\t},\n\t/** `SqlPoolQueue.renew`, `extend` and `heartbeat`: the attempt's lease, its claim confirmation and usage report. */\n\t\"pool-heartbeat\": {\n\t\tfences: [\"root lease row FOR KEY SHARE\", \"attempt's work row FOR UPDATE\", \"root usage totals row\"],\n\t\tconformance: \"claim, commit, heartbeat, complete and takeover run concurrently without a deadlock (#5102)\",\n\t},\n\t/** `SqlPoolQueue.commit` of a checkpoint or a session: the event takes the run's next sequence under its run row. */\n\t\"pool-commit\": {\n\t\tfences: [\n\t\t\t\"the database-wide serial lock, shared, only when the checkpoint records worktree snapshots (before every row lock)\",\n\t\t\t\"root lease row FOR KEY SHARE\",\n\t\t\t\"attempt's work row FOR UPDATE\",\n\t\t\t\"root run row FOR UPDATE (FOR SHARE without an event), then pool control and the snapshots' stored blobs\",\n\t\t\t\"root usage totals row\",\n\t\t],\n\t\tconformance: \"32 concurrent writers commit one event per key with a dense sequence (#5102)\",\n\t},\n\t/** `SqlPoolQueue.complete`: the result and the work row's final state. */\n\t\"pool-complete\": {\n\t\tfences: [\n\t\t\t\"root lease row FOR KEY SHARE\",\n\t\t\t\"attempt's work row FOR UPDATE\",\n\t\t\t\"root run row FOR SHARE, then pool control\",\n\t\t],\n\t\tconformance: \"many hosts claim, commit and complete concurrently: no double claim, no lost settle (#5102)\",\n\t},\n\t/**\n\t * Intercom's broker leases (`openSqlBrokerLeaseStore`): `acquire` is one upsert whose guard takes the row only while\n\t * it is free, stale or the acquirer's own, `renew` and `release` one `UPDATE` guarded by holder and fencing token, and\n\t * `renewMany` those updates in (kind, key) order. Each decides on its own row lock, never on an earlier read (#6560).\n\t * On PostgreSQL a first acquisition takes its order from the lease order sequence, which waits for nothing; where\n\t * `atomic storage migrate` has not created it yet, `acquire`'s statement first upserts the acquisition-order counter\n\t * row instead, which no other path locks.\n\t */\n\t\"intercom-lease\": {\n\t\tfences: [\n\t\t\t\"acquire only, without the order sequence: the acquisition-order counter row, by the statement's own upsert\",\n\t\t\t\"each lease row, by its own guarded upsert or UPDATE, in (kind, key) order\",\n\t\t],\n\t\tconformance:\n\t\t\t\"many brokers acquire, renew and release one lease concurrently: never two holders, fencing tokens strictly increase, a stale holder's renewal fails (#6560)\",\n\t},\n\t/** Intercom's lost-recipient sweep returns only the asks its guarded UPDATE marks ended. */\n\t\"intercom-lost-ask\": {\n\t\tfences: [\n\t\t\t\"the sweep leader's exact lease and the recipient's presence rows, FOR SHARE NOWAIT\",\n\t\t\t\"open ask rows, in insertion order FOR UPDATE SKIP LOCKED before marking\",\n\t\t],\n\t\tconformance: \"concurrent lost-recipient sweeps return an ask once and never queue on advisory locks (#6831)\",\n\t},\n\t/**\n\t * Intercom's wake-up hint log (`intercom_wakeups`): a hint is a row inserted once and deleted by its id or its age,\n\t * and no write reads the log to decide what to write, so its writers take no lock domain: the bus's `publish`\n\t * inserts a hint and notifies in one transaction that commits both, an outbox enqueue inserts one inside its own\n\t * transaction, and the bus's poll and pruning delete rows in single statements (#6560).\n\t */\n\t\"intercom-wakeup-hint\": {\n\t\tfences: [\"none: the new hint row only, by its own INSERT\"],\n\t\tconformance: \"delivers each hint published at once from several connections exactly once (#6560)\",\n\t},\n\t/**\n\t * Intercom's outbox rows and sent-message reservations (`openSqlOutboxStore`, `openSqlSentMessageAuthority`), which\n\t * left the outbox's one lock domain (#6560). A claim reads its recipient's undelivered rows `FOR UPDATE` in sequence\n\t * order, then claims them; a single claim's renewal, saving report, release and settlement are each one `UPDATE`\n\t * guarded by message id, claimant, token and state; batched `markDelivered`, `renewClaims`, `releaseClaims`, expiry\n\t * and `releaseClaimsOf` lock their rows in sequence order in a subquery; a reservation, an acceptance and a forget\n\t * are each one statement on the message's row, guarded by its digest. Each decides on the rows it locks, never on an\n\t * earlier read. They exclude the database-wide transactions an older broker runs on these tables (`excludesSerial`).\n\t * A send itself is a serial transaction of its recipient's domain.\n\t */\n\t\"intercom-outbox-row\": {\n\t\tfences: [\n\t\t\t\"outbox rows, FOR UPDATE in sequence order (claim, markDelivered batch, renewClaims, releaseClaims, expiry, releaseClaimsOf), or one row by its own guarded UPDATE\",\n\t\t\t\"one sent-message row, by its own guarded INSERT, UPDATE or DELETE\",\n\t\t],\n\t\tconformance:\n\t\t\t\"a send to one recipient does not wait while another recipient's claim holds its rows; sends to one recipient keep their order and suppress duplicates (#6560)\",\n\t},\n\t/**\n\t * A cleanup's claim of a lapsed fork staging transfer (`cleanupForkStaging`): it reads one lapsed lease row `FOR\n\t * UPDATE SKIP LOCKED`, then takes it over with one `UPDATE` guarded by the lease still being lapsed, so it never waits\n\t * for a live transfer whose writer or publication holds its lease, and two claims never take one transfer. Any lapsed\n\t * transfer may be claimed in any order. The claim names no transfer before it reads, so it takes no lock domain; the\n\t * owner's writes and the cleanup's removals are serial transactions of the transfer's own domain, and each decides on\n\t * the lease row it locks by its token first (#6560).\n\t */\n\t\"fork-staging-claim\": {\n\t\tfences: [\"one lapsed lease row of the staging table, FOR UPDATE SKIP LOCKED, then its guarded UPDATE\"],\n\t\tconformance:\n\t\t\t\"concurrent cleanups take each lapsed transfer over once and never a live one, beside staging clones (#6560)\",\n\t},\n\t/**\n\t * A schema setup that hosts opening a new database at once run once (`setUpStorageOnce`): its first statement tries,\n\t * without waiting, the advisory locks every setup of the same objects takes (the prefix's setup lock, and for a\n\t * domain's migration that domain's lock and the database's, shared, as an earlier build's migration takes them), and\n\t * the setup runs only where it took them all. A process that finds one taken waits outside any transaction until the\n\t * setup is recorded, so the hosts never queue for the lock (#6560).\n\t */\n\t\"schema-setup\": {\n\t\tfences: [\"the setup's advisory locks, all tried by its first statement without waiting\"],\n\t\tconformance:\n\t\t\t\"many hosts open a new database at once: each schema is set up once, every host opens, and none waits in a lock queue (#6560)\",\n\t},\n\t/** Snapshot reference writers and cleanup select the database's coordination mode in the transaction. */\n\t\"snapshot-epoch\": {\n\t\tfences: [\n\t\t\t\"shared epoch transition gate\",\n\t\t\t\"legacy database key only in compatibility mode\",\n\t\t\t\"domain key if required\",\n\t\t],\n\t\tconformance: \"an ordinary session writer commits while an older collector holds the old key (#6832)\",\n\t},\n\t/** Snapshot cleanup backs off outside the transaction if either advisory lock is busy. */\n\t\"snapshot-collection\": {\n\t\tfences: [\n\t\t\t\"claim bookkeeping: try the database lock shared, then try the collection table's lock exclusively, then update the claim row\",\n\t\t\t\"data batches: try the legacy database lock exclusively, then recheck the claim and the data before writing\",\n\t\t],\n\t\tconformance:\n\t\t\t\"busy snapshot collection does not queue ahead of session writers, then deletes the orphaned blobs (#6831)\",\n\t},\n\t/**\n\t * `SqlRateBuckets.acquire` and `cooldown`: one `UPDATE … RETURNING` (or upsert) of the scope's bucket row, which locks\n\t * no pool row, so it orders after none of them (#4768).\n\t */\n\t\"rate-bucket\": {\n\t\tfences: [\"the scope's rate bucket row, by its own UPDATE\"],\n\t\tconformance: \"many hosts acquire from one rate bucket concurrently and never take more than it allows (#4768)\",\n\t},\n} as const satisfies Readonly<Record<string, FencedPathAudit>>;\n\nexport type FencedPathName = keyof typeof FENCED_PATHS;\n\n/** The audit record of a fenced path. */\nexport function fencedPathAudit(name: FencedPathName): FencedPathAudit {\n\treturn FENCED_PATHS[name];\n}\n\n/** The `FencedPathId` that lets an audited path run `{ kind: \"fenced\", audit }` transactions. */\nexport function fencedPath(name: FencedPathName): FencedPathId {\n\treturn name as FencedPathId;\n}\n"]}
@@ -42,7 +42,7 @@ function __atomicOnDemandFailed(error, feature) {
42
42
  return (async () => {
43
43
  const root = new URL("../../", import.meta.url);
44
44
  const releases = (globalThis[Symbol.for("atomic.in-place-update-release.v1")] ??= new Map());
45
- const key = `${root.href}#0.10.17`;
45
+ const key = `${root.href}#0.10.18`;
46
46
  let release = releases.get(key);
47
47
  if (release === undefined) {
48
48
  const current = (async () => {
@@ -70,7 +70,7 @@ function __atomicOnDemandFailed(error, feature) {
70
70
  } catch {
71
71
  // No installation to read, as in a bundle of the package: the release the process runs decides.
72
72
  }
73
- const updatedTo = typeof installed === "string" && installed !== "0.10.17" ? installed : running !== undefined && running.version !== "0.10.17" ? "0.10.17" : undefined;
73
+ const updatedTo = typeof installed === "string" && installed !== "0.10.18" ? installed : running !== undefined && running.version !== "0.10.18" ? "0.10.18" : undefined;
74
74
  if (updatedTo === undefined) throw error;
75
75
  const application = typeof running?.name === "string" ? running.name : "atomic";
76
76
  const restart = new Error(`${application} was updated to ${updatedTo} while this session was running; restart it to keep using ${feature}.`, {
@@ -1,5 +1,6 @@
1
1
  import type { SqliteDatabase, SqliteExecutor, SqliteStatement, TransactionConcurrency } from "./database.js";
2
2
  import { type StorageDialect } from "./dialect.js";
3
+ import { type PostgresTryLock } from "./postgres-locks.js";
3
4
  /** One version of a domain's schema. */
4
5
  export interface StorageMigrationStep {
5
6
  /** A positive integer; a domain's steps are listed in increasing order. */
@@ -37,17 +38,7 @@ export interface StorageMigrationResult {
37
38
  */
38
39
  export declare function applyStorageMigrations(database: SqliteDatabase, domain: string, steps: readonly StorageMigrationStep[], options?: StorageMigrationOptions): Promise<StorageMigrationResult>;
39
40
  /** @internal An advisory lock a {@link setUpStorageOnce} setup takes on PostgreSQL, without waiting for it. */
40
- export interface StorageSetupLock {
41
- /** The lock's name. */
42
- readonly scope: string;
43
- /**
44
- * The name is qualified by the transaction's schema, as the adapter names the locks of a serial transaction's domain
45
- * (`<schema>:<scope>`, and `<scope>` alone in `public`): one that excludes such transactions, as an earlier build runs.
46
- */
47
- readonly inSchema?: boolean;
48
- /** Taken shared, as a serial transaction with a domain takes the database's lock. */
49
- readonly shared?: boolean;
50
- }
41
+ export type StorageSetupLock = PostgresTryLock;
51
42
  /** @internal A schema setup that {@link setUpStorageOnce} runs once among the processes that start it together. */
52
43
  export interface StorageSetupOnce<T> {
53
44
  /**
@@ -2,6 +2,7 @@ import { refreshStorageSchemaCatalog } from "./added-exports-0-10-11.js";
2
2
  import { dialectOf } from "./dialect.js";
3
3
  import { StorageConfigError, StorageSchemaVersionError } from "./errors.js";
4
4
  import { fencedPath } from "./fenced-paths.js";
5
+ import { tryPostgresLocks } from "./postgres-locks.js";
5
6
  import { recordSqliteSchemaStamps, schemaCatalogOf, sqliteSchemaStampsOf } from "./schema-catalog.js";
6
7
  import * as statementSequence from "./statement-sequence.js";
7
8
  /**
@@ -215,14 +216,6 @@ const SQLITE_SETUP_WAIT_MS = 1_000;
215
216
  /** The first pause between two polls of a setup that another process runs; each later one doubles, up to the last. */
216
217
  const SETUP_POLL_MS = 20;
217
218
  const SETUP_MAX_POLL_MS = 250;
218
- /** The schema the transaction runs in, as `<schema>:`, and empty in `public`: what the adapter prefixes its locks with. */
219
- const SCHEMA_LOCK_PREFIX = `(SELECT CASE WHEN name = 'public' THEN '' ELSE name || ':' END
220
- FROM (SELECT trim(both '"' from split_part(current_setting('search_path'), ',', 1)) AS name) AS search)`;
221
- /** One read that takes every one of `locks` it can without waiting, and tells whether it took them all. */
222
- function tryLocksStatement(locks) {
223
- const taken = locks.map(({ inSchema, shared }) => `pg_try_advisory_xact_lock${shared === true ? "_shared" : ""}(hashtextextended(${inSchema === true ? `${SCHEMA_LOCK_PREFIX} || ` : ""}?, 0))`);
224
- return { sql: `SELECT (${taken.join(" AND ")})::int AS won`, params: locks.map(({ scope }) => scope) };
225
- }
226
219
  const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms * (0.5 + Math.random() / 2)));
227
220
  /**
228
221
  * @internal Runs `once.setup`, a schema setup, so that of the processes that start it at once, on a new database say,
@@ -260,7 +253,7 @@ function trySetup(database, once) {
260
253
  if (dialectOf(database).name === "postgres") {
261
254
  // A fenced transaction takes no lock with its start: the try is its first statement, sent with that start.
262
255
  return () => {
263
- const lock = tryLocksStatement(once.locks);
256
+ const lock = tryPostgresLocks(once.locks);
264
257
  return database.transaction(async (transaction) => {
265
258
  const row = await transaction.get(lock.sql, ...lock.params);
266
259
  if (row?.won !== true && Number(row?.won) !== 1)
@@ -1 +1 @@
1
- {"version":3,"file":"migrations.js","sourceRoot":"","sources":["../../../src/core/storage/migrations.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,2BAA2B,EAAE,MAAM,4BAA4B,CAAC;AAEzE,OAAO,EAAE,SAAS,EAAuB,MAAM,cAAc,CAAC;AAC9D,OAAO,EAAE,kBAAkB,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AAC5E,OAAO,EAAE,UAAU,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O,KAAK,CAAC;IACtC,IAAI,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IACvD,qGAAqG;IACrG,MAAM,uBAAuB,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,EAAE,EAAE,EAAE;QAC5D,MAAM,EAAE,CAAC,IAAI,CAAC,eAAe,KAAK,sBAAsB,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;IACpF,CAAC,CAAC,CAAC;IACH,OAAO,KAAK,CAAC;AACd,CAAC","sourcesContent":["import { refreshStorageSchemaCatalog } from \"./added-exports-0-10-11.js\";\nimport type { SqliteDatabase, SqliteExecutor, SqliteRow, SqliteStatement, TransactionConcurrency } from \"./database.js\";\nimport { dialectOf, type StorageDialect } from \"./dialect.js\";\nimport { StorageConfigError, StorageSchemaVersionError } from \"./errors.js\";\nimport { fencedPath } from \"./fenced-paths.js\";\nimport { recordSqliteSchemaStamps, schemaCatalogOf, sqliteSchemaStampsOf } from \"./schema-catalog.js\";\nimport type { SequencedStatement } from \"./statement-sequence.js\";\nimport * as statementSequence from \"./statement-sequence.js\";\n\n/**\n * `transactionFinisher` of `statement-sequence.ts`, which the copies 0.10.3 and 0.10.4 loaded lack: taken from the module\n * namespace, so this module links against them too. Without it a setup's last statements go out before its commit.\n */\nconst finishers: Partial<Pick<typeof statementSequence, \"transactionFinisher\">> = statementSequence;\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\trefuseWithoutSchemaUsage(await executor.get<SchemaAccess>(SCHEMA_USAGE_SQL));\n}\n\ntype SchemaAccess = SqliteRow & { schema: string; role: string; present: number; usage: number };\n\n/** The schema the transaction runs in, whether it exists, and whether this role may use it: PostgreSQL only. */\nconst SCHEMA_USAGE_SQL = `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\n/** Throws for `access`, a row of {@link SCHEMA_USAGE_SQL}, where the schema exists and this role may not use it. */\nfunction refuseWithoutSchemaUsage(access: SchemaAccess | undefined): void {\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/postgres.md`,\n\t);\n}\n\n/** Creates the ledger `table` unless it exists, so a current schema runs no DDL (#5218). */\nasync function createLedger(\n\texecutor: SqliteExecutor,\n\tdialect: StorageDialect,\n\ttable: string,\n\t/** The transaction holds the prefix's setup lock, exclusive, already: a {@link setUpStorageOnce} try took it. */\n\tlocked = false,\n): 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\" && !locked) {\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\t/** The ledger is known to exist: it is not looked up first. */\n\texists = false,\n): Promise<number> {\n\tif (!exists && !(await tableExists(executor, dialect, table))) return 0;\n\tconst row = await executor.get<SqliteRow & { version: number | null }>(...versionRead(table, domain));\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\t/** The ledger is known to exist, as a catalog read before the transaction found it: it is read, not looked up. */\n\tledgerExists = false,\n\t/** The transaction holds the setup's locks already: see {@link setUpStorageOnce}. */\n\tlocked = false,\n): Promise<StorageMigrationResult> {\n\tconst current = ledgerExists\n\t\t? Number(\n\t\t\t\t(await transaction.get<SqliteRow & { version: number | null }>(...versionRead(table, domain)))?.version ??\n\t\t\t\t\t0,\n\t\t\t)\n\t\t: 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\tif (!ledgerExists) await createLedger(transaction, dialect, table, locked);\n\t// Each step's record goes out with the next step's first statement, on a connection that pipelines a transaction's\n\t// statements; a failed one fails the migration.\n\tconst records: Promise<unknown>[] = [];\n\tfor (const step of steps) {\n\t\tif (step.version <= current) continue;\n\t\tawait step.up(transaction, dialect);\n\t\tconst recorded = transaction.run(`INSERT INTO ${table} VALUES (?, ?, ${dialect.nowMs})`, domain, step.version);\n\t\trecorded.catch(() => {});\n\t\trecords.push(recorded);\n\t\tapplied.push(step.version);\n\t}\n\tawait Promise.all(records);\n\treturn { applied, version: Math.max(current, supported) };\n}\n\n/** The read of the highest version `table` records for `domain`, as arguments of `get`. */\nfunction versionRead(table: string, domain: string): [string, string] {\n\treturn [`SELECT MAX(version) AS version FROM ${table} WHERE domain = ?`, domain];\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\t// One process sets a new database up while the others that open it at once wait for it to finish, without holding a\n\t// lock or a connection: the locks are those an earlier build's migration and setup take, so it waits for those too.\n\tif (dialect.name === \"postgres\" && supported > 0) {\n\t\tlet ledgerExists = await ledgerInCatalog(database, table);\n\t\treturn setUpStorageOnce(database, {\n\t\t\t// An earlier build migrates in a serial transaction of the ledger's domain: the database's lock and the domain's,\n\t\t\t// which this takes shared, so the domains migrate beside one another but never beside an earlier build's.\n\t\t\tget locks() {\n\t\t\t\treturn [\n\t\t\t\t\t...setupLocks(table, domain, ledgerExists),\n\t\t\t\t\t{ scope: POSTGRES_DATABASE_LOCK_SCOPE, inSchema: true, shared: true },\n\t\t\t\t\t{ scope: table, inSchema: true, shared: true },\n\t\t\t\t];\n\t\t\t},\n\t\t\tdone: async () => {\n\t\t\t\tconst version = await recordedNow(database, table, domain, ledgerExists);\n\t\t\t\tledgerExists ||= await ledgerInCatalog(database, table);\n\t\t\t\tif (version < supported) return undefined;\n\t\t\t\tif (version > supported && !options.acceptNewer)\n\t\t\t\t\tthrow new StorageSchemaVersionError(domain, version, supported);\n\t\t\t\treturn { applied: [], version };\n\t\t\t},\n\t\t\tget leading() {\n\t\t\t\tconst [sql, key] = versionRead(table, domain);\n\t\t\t\treturn ledgerExists ? [{ sql, params: [key] }] : [];\n\t\t\t},\n\t\t\tsetup: (transaction, locked) =>\n\t\t\t\tapplyVersioned(\n\t\t\t\t\ttransaction,\n\t\t\t\t\tdialect,\n\t\t\t\t\ttable,\n\t\t\t\t\tdomain,\n\t\t\t\t\tsteps,\n\t\t\t\t\toptions.acceptNewer,\n\t\t\t\t\tlocked && ledgerExists,\n\t\t\t\t\tlocked,\n\t\t\t\t),\n\t\t\tconcurrency: { kind: \"serial\", domain: table },\n\t\t});\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/**\n * The version `ledger` records for `domain` now, read without a lock or a transaction of its own; 0 where the ledger\n * does not exist. Where `ledgerExists`, one read of the ledger answers; otherwise, inside an open\n * (`withStorageSchemaCatalog`), the open's catalog is read again. Either way, once the version is found, the open's\n * catalog is read again at its next question, so the stores the open sets up next find what another process set up.\n */\nasync function recordedNow(\n\tdatabase: SqliteDatabase,\n\tledger: string,\n\tdomain: string,\n\tledgerExists: boolean,\n): Promise<number> {\n\tif (ledgerExists) {\n\t\tconst version = Number(\n\t\t\t(await database.get<SqliteRow & { version: number | null }>(...versionRead(ledger, domain)))?.version ?? 0,\n\t\t);\n\t\tif (version > 0) refreshStorageSchemaCatalog(database);\n\t\treturn version;\n\t}\n\trefreshStorageSchemaCatalog(database);\n\tconst catalog = await schemaCatalogOf(database, ledger);\n\tif (catalog !== undefined) return catalog.recordedVersion(domain);\n\treturn recordedVersion(database, dialectOf(database), ledger, domain);\n}\n\n/** Whether the catalog of the open in progress on `database` holds `ledger`: once it does, it always will. */\nasync function ledgerInCatalog(database: SqliteDatabase, ledger: string): Promise<boolean> {\n\treturn (await schemaCatalogOf(database, ledger))?.hasTable(ledger) === true;\n}\n\n/**\n * The advisory lock a serial transaction without a domain takes on PostgreSQL, and one with a domain takes shared: the\n * adapter's `DATABASE_LOCK_SCOPE`, named in the transaction's schema.\n */\nconst POSTGRES_DATABASE_LOCK_SCOPE = \"atomic\";\n\n/**\n * How long a setup that another process holds the lock for waits, polling, before it waits for the lock itself: only a\n * holder that stalls keeps it that long on PostgreSQL, since setting a schema up takes a few round trips.\n */\nconst SETUP_WAIT_MS = 15_000;\n/**\n * The same on a SQLite file, whose write lock a try also finds taken while other writers wait in its queue, as every\n * process's own writes do when many open at once: after this long it joins the queue, which hands the lock on in turn.\n */\nconst SQLITE_SETUP_WAIT_MS = 1_000;\n/** The first pause between two polls of a setup that another process runs; each later one doubles, up to the last. */\nconst SETUP_POLL_MS = 20;\nconst SETUP_MAX_POLL_MS = 250;\n\n/** @internal An advisory lock a {@link setUpStorageOnce} setup takes on PostgreSQL, without waiting for it. */\nexport interface StorageSetupLock {\n\t/** The lock's name. */\n\treadonly scope: string;\n\t/**\n\t * The name is qualified by the transaction's schema, as the adapter names the locks of a serial transaction's domain\n\t * (`<schema>:<scope>`, and `<scope>` alone in `public`): one that excludes such transactions, as an earlier build runs.\n\t */\n\treadonly inSchema?: boolean;\n\t/** Taken shared, as a serial transaction with a domain takes the database's lock. */\n\treadonly shared?: boolean;\n}\n\n/** @internal A schema setup that {@link setUpStorageOnce} runs once among the processes that start it together. */\nexport interface StorageSetupOnce<T> {\n\t/**\n\t * The advisory locks the setup holds on PostgreSQL: every lock a setup of the same objects by an earlier build takes,\n\t * so the two never run at once.\n\t */\n\treadonly locks: readonly StorageSetupLock[];\n\t/**\n\t * On PostgreSQL, the reads the setup makes first, in this order, sent with the try's start: see the transaction\n\t * option `leading`. Read, with `locks`, at each try.\n\t */\n\treadonly leading?: readonly SqliteStatement[];\n\t/**\n\t * Reads, without a lock or a transaction, whether the setup is done, such as by another process meanwhile: its answer\n\t * then, or undefined while it is not. Asked only after a try found the lock held.\n\t */\n\treadonly done: () => Promise<T | undefined>;\n\t/**\n\t * The setup, in its transaction: it checks again, under the lock, what it would change, and changes only that.\n\t * `locked` tells that the transaction holds `locks`, which it does not where it waited in the transaction\n\t * `concurrency` names.\n\t */\n\treadonly setup: (transaction: SqliteExecutor, locked: boolean) => Promise<T>;\n\t/** How the setup's transaction waits for the lock after polling for {@link SETUP_WAIT_MS}, as it did before. */\n\treadonly concurrency: TransactionConcurrency;\n}\n\n/** The schema the transaction runs in, as `<schema>:`, and empty in `public`: what the adapter prefixes its locks with. */\nconst SCHEMA_LOCK_PREFIX = `(SELECT CASE WHEN name = 'public' THEN '' ELSE name || ':' END\n\tFROM (SELECT trim(both '\"' from split_part(current_setting('search_path'), ',', 1)) AS name) AS search)`;\n\n/** One read that takes every one of `locks` it can without waiting, and tells whether it took them all. */\nfunction tryLocksStatement(locks: readonly StorageSetupLock[]): SqliteStatement {\n\tconst taken = locks.map(\n\t\t({ inSchema, shared }) =>\n\t\t\t`pg_try_advisory_xact_lock${shared === true ? \"_shared\" : \"\"}(hashtextextended(${inSchema === true ? `${SCHEMA_LOCK_PREFIX} || ` : \"\"}?, 0))`,\n\t);\n\treturn { sql: `SELECT (${taken.join(\" AND \")})::int AS won`, params: locks.map(({ scope }) => scope) };\n}\n\nconst pause = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms * (0.5 + Math.random() / 2)));\n\n/**\n * @internal Runs `once.setup`, a schema setup, so that of the processes that start it at once, on a new database say,\n * one runs it and the others wait for it without queueing for its lock (#6560). The setup's transaction tries its locks\n * without waiting: an advisory lock on PostgreSQL (`once.locks`), the database's write lock on a SQLite file. A process\n * that finds them taken holds no lock and no connection while it waits: it polls `once.done`, with growing pauses,\n * until the setup is done, and tries again whenever it is not, so a holder that set up something else, or failed, or\n * died, leaves the setup to the next try. After {@link SETUP_WAIT_MS} ({@link SQLITE_SETUP_WAIT_MS} on SQLite) it\n * waits for the lock in the transaction `once.concurrency` names, as before. Where the database tries no lock without waiting, the setup runs in that\n * transaction at once.\n */\nexport async function setUpStorageOnce<T>(database: SqliteDatabase, once: StorageSetupOnce<T>): Promise<T> {\n\tconst attempt = trySetup(database, once);\n\tconst waiting = () =>\n\t\tdatabase.transaction((transaction) => once.setup(transaction, false), {\n\t\t\tretryTransientFailures: true,\n\t\t\tconcurrency: once.concurrency,\n\t\t});\n\tif (attempt === undefined) return waiting();\n\tconst deadline =\n\t\tperformance.now() + (dialectOf(database).name === \"postgres\" ? SETUP_WAIT_MS : SQLITE_SETUP_WAIT_MS);\n\tfor (let wait = SETUP_POLL_MS; ; wait = Math.min(wait * 2, SETUP_MAX_POLL_MS)) {\n\t\tconst tried = await attempt();\n\t\tif (tried.won) return tried.value as T;\n\t\tif (performance.now() >= deadline) return waiting();\n\t\tawait pause(wait);\n\t\tconst done = await once.done();\n\t\tif (done !== undefined) return done;\n\t}\n}\n\n/** One try at `once`'s setup that does not wait for its locks, or undefined where `database` cannot try one. */\nfunction trySetup<T>(\n\tdatabase: SqliteDatabase,\n\tonce: StorageSetupOnce<T>,\n): (() => Promise<{ readonly won: boolean; readonly value?: T }>) | undefined {\n\tif (dialectOf(database).name === \"postgres\") {\n\t\t// A fenced transaction takes no lock with its start: the try is its first statement, sent with that start.\n\t\treturn () => {\n\t\t\tconst lock = tryLocksStatement(once.locks);\n\t\t\treturn database.transaction(\n\t\t\t\tasync (transaction) => {\n\t\t\t\t\tconst row = await transaction.get<SqliteRow & { won: number | boolean | null }>(\n\t\t\t\t\t\tlock.sql,\n\t\t\t\t\t\t...lock.params,\n\t\t\t\t\t);\n\t\t\t\t\tif (row?.won !== true && Number(row?.won) !== 1) return { won: false };\n\t\t\t\t\treturn { won: true, value: await once.setup(transaction, true) };\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tretryTransientFailures: true,\n\t\t\t\t\tconcurrency: { kind: \"fenced\", audit: fencedPath(\"schema-setup\") },\n\t\t\t\t\tleading: [lock, ...(once.leading ?? [])],\n\t\t\t\t},\n\t\t\t);\n\t\t};\n\t}\n\tconst tryMaintenance = database.tryMaintenance?.bind(database);\n\tif (tryMaintenance === undefined) return undefined;\n\treturn async () => {\n\t\tlet value: T | undefined;\n\t\tconst won = await tryMaintenance(async (transaction) => {\n\t\t\tvalue = await once.setup(transaction, false);\n\t\t});\n\t\treturn won ? { won, value } : { won };\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(\n\texecutor: SqliteExecutor,\n\tsetup: () => Promise<void>,\n\tknown?: SqliteRow & { wait: string | null },\n\tafter: readonly SequencedStatement[] = [],\n\tlast = false,\n): Promise<void> {\n\tconst previous = known ?? (await executor.get<SqliteRow & { wait: string }>(LOCK_WAIT_SQL));\n\tfor (let attempt = 1; ; attempt++) {\n\t\t// Sent with the setup's first statement, on a connection that pipelines a transaction's statements: no round trip\n\t\t// of its own. A failure of either fails the setup.\n\t\tconst saved = executor.exec(\n\t\t\t`SAVEPOINT atomic_schema_setup; SET LOCAL lock_timeout = ${SCHEMA_SETUP_LOCK_WAIT_MS}`,\n\t\t);\n\t\tsaved.catch(() => {});\n\t\ttry {\n\t\t\tawait setup();\n\t\t\tawait saved;\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\t// The savepoint's release, the lock wait restored, unless nothing follows in the transaction, and `after` go out\n\t// together: with the commit, where they are the transaction's `last` statements and its connection allows it.\n\tconst statements: SequencedStatement[] = [\n\t\t{ sql: \"RELEASE SAVEPOINT atomic_schema_setup\", params: [], script: true },\n\t\t...(last\n\t\t\t? []\n\t\t\t: [\n\t\t\t\t\t{\n\t\t\t\t\t\tsql: `SET LOCAL lock_timeout = '${String(previous?.wait ?? \"0\").replaceAll(\"'\", \"''\")}'`,\n\t\t\t\t\t\tparams: [],\n\t\t\t\t\t\tscript: true,\n\t\t\t\t\t},\n\t\t\t\t]),\n\t\t...after,\n\t];\n\tif (last && finishers.transactionFinisher?.(executor)?.(statements) === true) return;\n\tawait Promise.all(\n\t\tstatements.map((statement) =>\n\t\t\tstatement.script === true ? executor.exec(statement.sql) : executor.run(statement.sql, ...statement.params),\n\t\t),\n\t);\n}\n\n/** The transaction's lock wait, which a setup lowers while it runs and then restores. */\nconst LOCK_WAIT_SQL = \"SELECT current_setting('lock_timeout') AS wait\";\n\n/** The prefix's setup lock, which every schema setup holds on PostgreSQL: see {@link ensureStorageSchema}. */\nconst SETUP_LOCK_SQL = \"SELECT pg_advisory_xact_lock(hashtextextended(?, 0)) AS locked\";\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). On SQLite the store's schema stamp records it, and only while nothing changed the\n * schema since (`sqliteSchemaStampTable`). False outside such an open, and when the revision is not recorded.\n */\nexport async function storageSchemaCurrent(database: SqliteDatabase, schema: StorageSchemaSetup): Promise<boolean> {\n\tconst dialect = dialectOf(database);\n\tconst key = `schema:${schema.domain}`;\n\tif (dialect.versionedMigrations) {\n\t\tconst recorded = await recordedInCatalog(database, schema.ledger, key);\n\t\treturn recorded !== undefined && recorded >= schema.revision;\n\t}\n\tif (dialect.name !== \"sqlite\") return false;\n\treturn ((await sqliteSchemaStampsOf(database, schema.ledger))?.get(key) ?? 0) >= 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 keep no ledger, `setup`\n * runs every time it is called, as before, and then stamps the store with the schema version the transaction leaves,\n * which {@link storageSchemaCurrent} believes until the schema changes again (#6560).\n */\nexport async function ensureStorageSchema(\n\texecutor: SqliteExecutor,\n\tdialect: StorageDialect,\n\tschema: StorageSchemaSetup,\n\tsetup: () => Promise<void>,\n\toptions: EnsureStorageSchemaOptions = {},\n): Promise<void> {\n\tif (!dialect.versionedMigrations) {\n\t\tawait setup();\n\t\tif (dialect.name === \"sqlite\") await recordSqliteSchemaStamps(executor, [schema]);\n\t\treturn;\n\t}\n\tconst { ledger, domain, revision } = schema;\n\tconst key = `schema:${domain}`;\n\tconst record = {\n\t\tsql: `INSERT INTO ${ledger} (domain, version, applied_at) VALUES (?, ?, ${dialect.nowMs}) ON CONFLICT DO NOTHING`,\n\t\tparams: [key, revision],\n\t};\n\tif (dialect.name !== \"postgres\") {\n\t\tif ((await recordedVersion(executor, dialect, ledger, key)) >= revision) return;\n\t\tawait setup();\n\t\tawait createLedger(executor, dialect, ledger);\n\t\tawait executor.run(record.sql, ...record.params);\n\t\treturn;\n\t}\n\tlet ledgerFound = options.locked === true && options.ledgerExists === true;\n\tif (options.locked !== true) {\n\t\tledgerFound = await tableExists(executor, dialect, ledger);\n\t\tif (ledgerFound && (await recordedVersion(executor, dialect, ledger, key, true)) >= revision) return;\n\t}\n\t// Serialized per prefix, so hosts that start together on a new database set each store up once, and two stores\n\t// that create a table they share never race to create it. The reads go out with the lock, and each runs after it:\n\t// what a holder before it recorded, whether this role may use the schema, and the lock wait the setup restores.\n\tconst [first, usage, lockWait] = postgresSetupReads(dialect, ledger, key, ledgerFound);\n\tconst [, found, access, wait] = await Promise.all([\n\t\toptions.locked === true ? undefined : executor.get(SETUP_LOCK_SQL, `${ledger}:schema`),\n\t\texecutor.get<SqliteRow & { version: number | string | null }>(first.sql, ...first.params),\n\t\texecutor.get<SchemaAccess>(usage.sql, ...usage.params),\n\t\texecutor.get<SqliteRow & { wait: string }>(lockWait.sql, ...lockWait.params),\n\t]);\n\tconst ledgerExists = ledgerFound || found !== undefined;\n\tconst recorded = ledgerFound\n\t\t? Number(found?.version ?? 0)\n\t\t: ledgerExists\n\t\t\t? await recordedVersion(executor, dialect, ledger, key, true)\n\t\t\t: 0;\n\tif (recorded >= revision) return;\n\trefuseWithoutSchemaUsage(access);\n\tconst { int, text } = dialect.types;\n\t// The ledger, created where it is missing, and the record go out with the savepoint's release.\n\tconst createLedgerStatement = {\n\t\tsql: `CREATE TABLE IF NOT EXISTS ${ledger} (domain ${text} NOT NULL, version ${int} NOT NULL, applied_at ${int} NOT NULL, PRIMARY KEY (domain, version))${dialect.tableOptions}`,\n\t\tparams: [],\n\t\tscript: true,\n\t};\n\tawait underShortLockWaits(\n\t\texecutor,\n\t\tsetup,\n\t\twait,\n\t\tledgerExists ? [record] : [createLedgerStatement, record],\n\t\toptions.last === true,\n\t);\n}\n\n/** How {@link ensureStorageSchema} runs in a transaction that holds the setup's locks already. */\nexport interface EnsureStorageSchemaOptions {\n\t/**\n\t * The transaction holds the setup's locks already, as a {@link setUpStorageOnce} setup does: the ledger is read only\n\t * under them, and the prefix's setup lock is not taken again.\n\t */\n\treadonly locked?: boolean;\n\t/** With `locked`: the ledger exists, so its version is the first read, as {@link postgresSetupReads} lists them. */\n\treadonly ledgerExists?: boolean;\n\t/** The setup is the transaction's last call: its last statements go out with the commit. */\n\treadonly last?: boolean;\n}\n\n/**\n * The reads a PostgreSQL setup of the ledger key `key` makes first, under its locks, in this order: the version the\n * ledger records, where it is known to exist, or else whether it does; the schema's usage; and the lock wait the setup\n * restores. A {@link setUpStorageOnce} try sends them with its start.\n */\nfunction postgresSetupReads(\n\tdialect: StorageDialect,\n\tledger: string,\n\tkey: string,\n\tledgerExists: boolean,\n): readonly SqliteStatement[] {\n\treturn [\n\t\tledgerExists ? { sql: versionRead(ledger, key)[0], params: [key] } : dialect.tableExists(ledger),\n\t\t{ sql: SCHEMA_USAGE_SQL, params: [] },\n\t\t{ sql: LOCK_WAIT_SQL, params: [] },\n\t];\n}\n\n/**\n * The advisory locks a PostgreSQL setup recorded in `ledger` under `key` tries: the prefix's setup lock, exclusive while\n * the ledger may be missing, so one setup creates it, and shared once it exists, so the setups of other stores run\n * beside it while an earlier build's setup, which takes it exclusive, runs alone; and a lock of the key's own, so one\n * process sets each store up.\n */\nfunction setupLocks(ledger: string, key: string, ledgerExists: boolean): StorageSetupLock[] {\n\treturn [{ scope: `${ledger}:schema`, shared: ledgerExists }, { scope: `${ledger}:schema:${key}` }];\n}\n\n/**\n * Runs `setup`, a store's idempotent schema statements, as {@link ensureStorageSchema} does, in a transaction of its own:\n * of the processes that open a new database at once, one runs it and the others wait for the ledger to record it,\n * without its lock (`setUpStorageOnce`, #6560). Inside an open, a revision the open's catalog records runs nothing; the\n * caller checks that first (`storageSchemaCurrent`). PostgreSQL; elsewhere the setup runs in a serial transaction of the\n * ledger's domain.\n */\nexport async function ensureStorageSchemaOnce(\n\tdatabase: SqliteDatabase,\n\tschema: StorageSchemaSetup,\n\tsetup: (transaction: SqliteExecutor) => Promise<void>,\n): Promise<void> {\n\tconst dialect = dialectOf(database);\n\tconst { ledger, domain, revision } = schema;\n\tconst concurrency = { kind: \"serial\", domain: ledger } as const;\n\tif (dialect.name !== \"postgres\") {\n\t\tawait database.transaction((tx) => ensureStorageSchema(tx, dialect, schema, () => setup(tx)), {\n\t\t\tretryTransientFailures: true,\n\t\t\tconcurrency,\n\t\t});\n\t\treturn;\n\t}\n\tconst key = `schema:${domain}`;\n\tlet ledgerExists = await ledgerInCatalog(database, ledger);\n\tawait setUpStorageOnce(database, {\n\t\tget locks() {\n\t\t\treturn setupLocks(ledger, key, ledgerExists);\n\t\t},\n\t\tget leading() {\n\t\t\treturn postgresSetupReads(dialect, ledger, key, ledgerExists);\n\t\t},\n\t\tdone: async () => {\n\t\t\tconst recorded = await recordedNow(database, ledger, key, ledgerExists);\n\t\t\tledgerExists ||= await ledgerInCatalog(database, ledger);\n\t\t\treturn recorded >= revision ? true : undefined;\n\t\t},\n\t\tsetup: async (tx, locked) => {\n\t\t\tawait ensureStorageSchema(tx, dialect, schema, () => setup(tx), { locked, ledgerExists, last: true });\n\t\t\treturn true;\n\t\t},\n\t\tconcurrency,\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 * The fillfactor checks this process made that found nothing for it to do, by database (`databaseIdentity`, which\n * names the role and schema too), ledger and table, and the ones under way: the table had a fillfactor, or this role\n * does not own it (#6560). Such a check is not made again. One that set the fillfactor, or found no table, is.\n */\nconst fillfactorChecks = new Map<string, Promise<boolean>>();\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.\n * Otherwise one read of the table's catalog entry decides: nothing runs where the table has a fillfactor already, or\n * where this role does not own the table, so a runtime role without DDL opens as before, and `atomic storage migrate`,\n * run as the owner, sets it. A process reads that once for each database and table, so until migrate records the step\n * only its first open pays the read. Does nothing on SQLite.\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 } = setup;\n\tif (await storageSchemaCurrent(database, { ledger, domain, revision })) return;\n\tconst identity = database.databaseIdentity?.();\n\tif (identity === undefined) {\n\t\tawait checkTableFillfactor(database, setup);\n\t\treturn;\n\t}\n\tconst key = JSON.stringify([identity, ledger, table]);\n\tlet check = fillfactorChecks.get(key);\n\tif (check === undefined) {\n\t\tconst made = checkTableFillfactor(database, setup);\n\t\tcheck = made;\n\t\tfillfactorChecks.set(key, made);\n\t\tconst forget = () => {\n\t\t\tif (fillfactorChecks.get(key) === made) fillfactorChecks.delete(key);\n\t\t};\n\t\tmade.then((settled) => {\n\t\t\tif (!settled) forget();\n\t\t}, forget);\n\t}\n\tawait check;\n}\n\n/**\n * {@link ensureTableFillfactor}'s read of the table's catalog entry, and the change where it is due. True where it\n * found nothing this role can do: the table has a fillfactor, or this role does not own it.\n */\nasync function checkTableFillfactor(database: SqliteDatabase, setup: StorageFillfactorSetup): Promise<boolean> {\n\tconst dialect = dialectOf(database);\n\tconst { ledger, domain, revision, table, fillfactor } = setup;\n\tconst schema = { ledger, domain, revision };\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) return false;\n\tif (yes(found.tuned) || !yes(found.owned)) return true;\n\t// Hosts that open a new database at once set it once, and the others wait for that without the lock.\n\tawait ensureStorageSchemaOnce(database, schema, async (tx) => {\n\t\tawait tx.exec(`ALTER TABLE ${table} SET (fillfactor = ${Math.trunc(fillfactor)})`);\n\t});\n\treturn false;\n}\n"]}
1
+ {"version":3,"file":"migrations.js","sourceRoot":"","sources":["../../../src/core/storage/migrations.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,2BAA2B,EAAE,MAAM,4BAA4B,CAAC;AAEzE,OAAO,EAAE,SAAS,EAAuB,MAAM,cAAc,CAAC;AAC9D,OAAO,EAAE,kBAAkB,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AAC5E,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAwB,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC7E,OAAO,EAAE,wBAAwB,EAAE,eAAe,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAEtG,OAAO,KAAK,iBAAiB,MAAM,yBAAyB,CAAC;AAE7D;;;GAGG;AACH,MAAM,SAAS,GAAmE,iBAAiB,CAAC;AAgCpG,MAAM,uBAAuB,GAAG,mBAAmB,CAAC;AAEpD,SAAS,UAAU,CAAC,KAAsC;IACzD,IAAI,QAAQ,GAAG,CAAC,CAAC;IACjB,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QAC1B,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,IAAI,CAAC,OAAO,IAAI,QAAQ;YAClE,MAAM,IAAI,kBAAkB,CAC3B,KAAK,EACL,OAAO,EACP,qBAAqB,EACrB,uDAAuD,CACvD,CAAC;QACH,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC;IACzB,CAAC;AACF,CAAC;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AAE,OAAO,KAAK,CAAC;IACtC,IAAI,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IACvD,qGAAqG;IACrG,MAAM,uBAAuB,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,EAAE,EAAE,EAAE;QAC5D,MAAM,EAAE,CAAC,IAAI,CAAC,eAAe,KAAK,sBAAsB,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;IACpF,CAAC,CAAC,CAAC;IACH,OAAO,KAAK,CAAC;AACd,CAAC","sourcesContent":["import { refreshStorageSchemaCatalog } from \"./added-exports-0-10-11.js\";\nimport type { SqliteDatabase, SqliteExecutor, SqliteRow, SqliteStatement, TransactionConcurrency } from \"./database.js\";\nimport { dialectOf, type StorageDialect } from \"./dialect.js\";\nimport { StorageConfigError, StorageSchemaVersionError } from \"./errors.js\";\nimport { fencedPath } from \"./fenced-paths.js\";\nimport { type PostgresTryLock, tryPostgresLocks } from \"./postgres-locks.js\";\nimport { recordSqliteSchemaStamps, schemaCatalogOf, sqliteSchemaStampsOf } from \"./schema-catalog.js\";\nimport type { SequencedStatement } from \"./statement-sequence.js\";\nimport * as statementSequence from \"./statement-sequence.js\";\n\n/**\n * `transactionFinisher` of `statement-sequence.ts`, which the copies 0.10.3 and 0.10.4 loaded lack: taken from the module\n * namespace, so this module links against them too. Without it a setup's last statements go out before its commit.\n */\nconst finishers: Partial<Pick<typeof statementSequence, \"transactionFinisher\">> = statementSequence;\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\trefuseWithoutSchemaUsage(await executor.get<SchemaAccess>(SCHEMA_USAGE_SQL));\n}\n\ntype SchemaAccess = SqliteRow & { schema: string; role: string; present: number; usage: number };\n\n/** The schema the transaction runs in, whether it exists, and whether this role may use it: PostgreSQL only. */\nconst SCHEMA_USAGE_SQL = `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\n/** Throws for `access`, a row of {@link SCHEMA_USAGE_SQL}, where the schema exists and this role may not use it. */\nfunction refuseWithoutSchemaUsage(access: SchemaAccess | undefined): void {\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/postgres.md`,\n\t);\n}\n\n/** Creates the ledger `table` unless it exists, so a current schema runs no DDL (#5218). */\nasync function createLedger(\n\texecutor: SqliteExecutor,\n\tdialect: StorageDialect,\n\ttable: string,\n\t/** The transaction holds the prefix's setup lock, exclusive, already: a {@link setUpStorageOnce} try took it. */\n\tlocked = false,\n): 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\" && !locked) {\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\t/** The ledger is known to exist: it is not looked up first. */\n\texists = false,\n): Promise<number> {\n\tif (!exists && !(await tableExists(executor, dialect, table))) return 0;\n\tconst row = await executor.get<SqliteRow & { version: number | null }>(...versionRead(table, domain));\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\t/** The ledger is known to exist, as a catalog read before the transaction found it: it is read, not looked up. */\n\tledgerExists = false,\n\t/** The transaction holds the setup's locks already: see {@link setUpStorageOnce}. */\n\tlocked = false,\n): Promise<StorageMigrationResult> {\n\tconst current = ledgerExists\n\t\t? Number(\n\t\t\t\t(await transaction.get<SqliteRow & { version: number | null }>(...versionRead(table, domain)))?.version ??\n\t\t\t\t\t0,\n\t\t\t)\n\t\t: 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\tif (!ledgerExists) await createLedger(transaction, dialect, table, locked);\n\t// Each step's record goes out with the next step's first statement, on a connection that pipelines a transaction's\n\t// statements; a failed one fails the migration.\n\tconst records: Promise<unknown>[] = [];\n\tfor (const step of steps) {\n\t\tif (step.version <= current) continue;\n\t\tawait step.up(transaction, dialect);\n\t\tconst recorded = transaction.run(`INSERT INTO ${table} VALUES (?, ?, ${dialect.nowMs})`, domain, step.version);\n\t\trecorded.catch(() => {});\n\t\trecords.push(recorded);\n\t\tapplied.push(step.version);\n\t}\n\tawait Promise.all(records);\n\treturn { applied, version: Math.max(current, supported) };\n}\n\n/** The read of the highest version `table` records for `domain`, as arguments of `get`. */\nfunction versionRead(table: string, domain: string): [string, string] {\n\treturn [`SELECT MAX(version) AS version FROM ${table} WHERE domain = ?`, domain];\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\t// One process sets a new database up while the others that open it at once wait for it to finish, without holding a\n\t// lock or a connection: the locks are those an earlier build's migration and setup take, so it waits for those too.\n\tif (dialect.name === \"postgres\" && supported > 0) {\n\t\tlet ledgerExists = await ledgerInCatalog(database, table);\n\t\treturn setUpStorageOnce(database, {\n\t\t\t// An earlier build migrates in a serial transaction of the ledger's domain: the database's lock and the domain's,\n\t\t\t// which this takes shared, so the domains migrate beside one another but never beside an earlier build's.\n\t\t\tget locks() {\n\t\t\t\treturn [\n\t\t\t\t\t...setupLocks(table, domain, ledgerExists),\n\t\t\t\t\t{ scope: POSTGRES_DATABASE_LOCK_SCOPE, inSchema: true, shared: true },\n\t\t\t\t\t{ scope: table, inSchema: true, shared: true },\n\t\t\t\t];\n\t\t\t},\n\t\t\tdone: async () => {\n\t\t\t\tconst version = await recordedNow(database, table, domain, ledgerExists);\n\t\t\t\tledgerExists ||= await ledgerInCatalog(database, table);\n\t\t\t\tif (version < supported) return undefined;\n\t\t\t\tif (version > supported && !options.acceptNewer)\n\t\t\t\t\tthrow new StorageSchemaVersionError(domain, version, supported);\n\t\t\t\treturn { applied: [], version };\n\t\t\t},\n\t\t\tget leading() {\n\t\t\t\tconst [sql, key] = versionRead(table, domain);\n\t\t\t\treturn ledgerExists ? [{ sql, params: [key] }] : [];\n\t\t\t},\n\t\t\tsetup: (transaction, locked) =>\n\t\t\t\tapplyVersioned(\n\t\t\t\t\ttransaction,\n\t\t\t\t\tdialect,\n\t\t\t\t\ttable,\n\t\t\t\t\tdomain,\n\t\t\t\t\tsteps,\n\t\t\t\t\toptions.acceptNewer,\n\t\t\t\t\tlocked && ledgerExists,\n\t\t\t\t\tlocked,\n\t\t\t\t),\n\t\t\tconcurrency: { kind: \"serial\", domain: table },\n\t\t});\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/**\n * The version `ledger` records for `domain` now, read without a lock or a transaction of its own; 0 where the ledger\n * does not exist. Where `ledgerExists`, one read of the ledger answers; otherwise, inside an open\n * (`withStorageSchemaCatalog`), the open's catalog is read again. Either way, once the version is found, the open's\n * catalog is read again at its next question, so the stores the open sets up next find what another process set up.\n */\nasync function recordedNow(\n\tdatabase: SqliteDatabase,\n\tledger: string,\n\tdomain: string,\n\tledgerExists: boolean,\n): Promise<number> {\n\tif (ledgerExists) {\n\t\tconst version = Number(\n\t\t\t(await database.get<SqliteRow & { version: number | null }>(...versionRead(ledger, domain)))?.version ?? 0,\n\t\t);\n\t\tif (version > 0) refreshStorageSchemaCatalog(database);\n\t\treturn version;\n\t}\n\trefreshStorageSchemaCatalog(database);\n\tconst catalog = await schemaCatalogOf(database, ledger);\n\tif (catalog !== undefined) return catalog.recordedVersion(domain);\n\treturn recordedVersion(database, dialectOf(database), ledger, domain);\n}\n\n/** Whether the catalog of the open in progress on `database` holds `ledger`: once it does, it always will. */\nasync function ledgerInCatalog(database: SqliteDatabase, ledger: string): Promise<boolean> {\n\treturn (await schemaCatalogOf(database, ledger))?.hasTable(ledger) === true;\n}\n\n/**\n * The advisory lock a serial transaction without a domain takes on PostgreSQL, and one with a domain takes shared: the\n * adapter's `DATABASE_LOCK_SCOPE`, named in the transaction's schema.\n */\nconst POSTGRES_DATABASE_LOCK_SCOPE = \"atomic\";\n\n/**\n * How long a setup that another process holds the lock for waits, polling, before it waits for the lock itself: only a\n * holder that stalls keeps it that long on PostgreSQL, since setting a schema up takes a few round trips.\n */\nconst SETUP_WAIT_MS = 15_000;\n/**\n * The same on a SQLite file, whose write lock a try also finds taken while other writers wait in its queue, as every\n * process's own writes do when many open at once: after this long it joins the queue, which hands the lock on in turn.\n */\nconst SQLITE_SETUP_WAIT_MS = 1_000;\n/** The first pause between two polls of a setup that another process runs; each later one doubles, up to the last. */\nconst SETUP_POLL_MS = 20;\nconst SETUP_MAX_POLL_MS = 250;\n\n/** @internal An advisory lock a {@link setUpStorageOnce} setup takes on PostgreSQL, without waiting for it. */\nexport type StorageSetupLock = PostgresTryLock;\n\n/** @internal A schema setup that {@link setUpStorageOnce} runs once among the processes that start it together. */\nexport interface StorageSetupOnce<T> {\n\t/**\n\t * The advisory locks the setup holds on PostgreSQL: every lock a setup of the same objects by an earlier build takes,\n\t * so the two never run at once.\n\t */\n\treadonly locks: readonly StorageSetupLock[];\n\t/**\n\t * On PostgreSQL, the reads the setup makes first, in this order, sent with the try's start: see the transaction\n\t * option `leading`. Read, with `locks`, at each try.\n\t */\n\treadonly leading?: readonly SqliteStatement[];\n\t/**\n\t * Reads, without a lock or a transaction, whether the setup is done, such as by another process meanwhile: its answer\n\t * then, or undefined while it is not. Asked only after a try found the lock held.\n\t */\n\treadonly done: () => Promise<T | undefined>;\n\t/**\n\t * The setup, in its transaction: it checks again, under the lock, what it would change, and changes only that.\n\t * `locked` tells that the transaction holds `locks`, which it does not where it waited in the transaction\n\t * `concurrency` names.\n\t */\n\treadonly setup: (transaction: SqliteExecutor, locked: boolean) => Promise<T>;\n\t/** How the setup's transaction waits for the lock after polling for {@link SETUP_WAIT_MS}, as it did before. */\n\treadonly concurrency: TransactionConcurrency;\n}\n\nconst pause = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms * (0.5 + Math.random() / 2)));\n\n/**\n * @internal Runs `once.setup`, a schema setup, so that of the processes that start it at once, on a new database say,\n * one runs it and the others wait for it without queueing for its lock (#6560). The setup's transaction tries its locks\n * without waiting: an advisory lock on PostgreSQL (`once.locks`), the database's write lock on a SQLite file. A process\n * that finds them taken holds no lock and no connection while it waits: it polls `once.done`, with growing pauses,\n * until the setup is done, and tries again whenever it is not, so a holder that set up something else, or failed, or\n * died, leaves the setup to the next try. After {@link SETUP_WAIT_MS} ({@link SQLITE_SETUP_WAIT_MS} on SQLite) it\n * waits for the lock in the transaction `once.concurrency` names, as before. Where the database tries no lock without waiting, the setup runs in that\n * transaction at once.\n */\nexport async function setUpStorageOnce<T>(database: SqliteDatabase, once: StorageSetupOnce<T>): Promise<T> {\n\tconst attempt = trySetup(database, once);\n\tconst waiting = () =>\n\t\tdatabase.transaction((transaction) => once.setup(transaction, false), {\n\t\t\tretryTransientFailures: true,\n\t\t\tconcurrency: once.concurrency,\n\t\t});\n\tif (attempt === undefined) return waiting();\n\tconst deadline =\n\t\tperformance.now() + (dialectOf(database).name === \"postgres\" ? SETUP_WAIT_MS : SQLITE_SETUP_WAIT_MS);\n\tfor (let wait = SETUP_POLL_MS; ; wait = Math.min(wait * 2, SETUP_MAX_POLL_MS)) {\n\t\tconst tried = await attempt();\n\t\tif (tried.won) return tried.value as T;\n\t\tif (performance.now() >= deadline) return waiting();\n\t\tawait pause(wait);\n\t\tconst done = await once.done();\n\t\tif (done !== undefined) return done;\n\t}\n}\n\n/** One try at `once`'s setup that does not wait for its locks, or undefined where `database` cannot try one. */\nfunction trySetup<T>(\n\tdatabase: SqliteDatabase,\n\tonce: StorageSetupOnce<T>,\n): (() => Promise<{ readonly won: boolean; readonly value?: T }>) | undefined {\n\tif (dialectOf(database).name === \"postgres\") {\n\t\t// A fenced transaction takes no lock with its start: the try is its first statement, sent with that start.\n\t\treturn () => {\n\t\t\tconst lock = tryPostgresLocks(once.locks);\n\t\t\treturn database.transaction(\n\t\t\t\tasync (transaction) => {\n\t\t\t\t\tconst row = await transaction.get<SqliteRow & { won: number | boolean | null }>(\n\t\t\t\t\t\tlock.sql,\n\t\t\t\t\t\t...lock.params,\n\t\t\t\t\t);\n\t\t\t\t\tif (row?.won !== true && Number(row?.won) !== 1) return { won: false };\n\t\t\t\t\treturn { won: true, value: await once.setup(transaction, true) };\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tretryTransientFailures: true,\n\t\t\t\t\tconcurrency: { kind: \"fenced\", audit: fencedPath(\"schema-setup\") },\n\t\t\t\t\tleading: [lock, ...(once.leading ?? [])],\n\t\t\t\t},\n\t\t\t);\n\t\t};\n\t}\n\tconst tryMaintenance = database.tryMaintenance?.bind(database);\n\tif (tryMaintenance === undefined) return undefined;\n\treturn async () => {\n\t\tlet value: T | undefined;\n\t\tconst won = await tryMaintenance(async (transaction) => {\n\t\t\tvalue = await once.setup(transaction, false);\n\t\t});\n\t\treturn won ? { won, value } : { won };\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(\n\texecutor: SqliteExecutor,\n\tsetup: () => Promise<void>,\n\tknown?: SqliteRow & { wait: string | null },\n\tafter: readonly SequencedStatement[] = [],\n\tlast = false,\n): Promise<void> {\n\tconst previous = known ?? (await executor.get<SqliteRow & { wait: string }>(LOCK_WAIT_SQL));\n\tfor (let attempt = 1; ; attempt++) {\n\t\t// Sent with the setup's first statement, on a connection that pipelines a transaction's statements: no round trip\n\t\t// of its own. A failure of either fails the setup.\n\t\tconst saved = executor.exec(\n\t\t\t`SAVEPOINT atomic_schema_setup; SET LOCAL lock_timeout = ${SCHEMA_SETUP_LOCK_WAIT_MS}`,\n\t\t);\n\t\tsaved.catch(() => {});\n\t\ttry {\n\t\t\tawait setup();\n\t\t\tawait saved;\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\t// The savepoint's release, the lock wait restored, unless nothing follows in the transaction, and `after` go out\n\t// together: with the commit, where they are the transaction's `last` statements and its connection allows it.\n\tconst statements: SequencedStatement[] = [\n\t\t{ sql: \"RELEASE SAVEPOINT atomic_schema_setup\", params: [], script: true },\n\t\t...(last\n\t\t\t? []\n\t\t\t: [\n\t\t\t\t\t{\n\t\t\t\t\t\tsql: `SET LOCAL lock_timeout = '${String(previous?.wait ?? \"0\").replaceAll(\"'\", \"''\")}'`,\n\t\t\t\t\t\tparams: [],\n\t\t\t\t\t\tscript: true,\n\t\t\t\t\t},\n\t\t\t\t]),\n\t\t...after,\n\t];\n\tif (last && finishers.transactionFinisher?.(executor)?.(statements) === true) return;\n\tawait Promise.all(\n\t\tstatements.map((statement) =>\n\t\t\tstatement.script === true ? executor.exec(statement.sql) : executor.run(statement.sql, ...statement.params),\n\t\t),\n\t);\n}\n\n/** The transaction's lock wait, which a setup lowers while it runs and then restores. */\nconst LOCK_WAIT_SQL = \"SELECT current_setting('lock_timeout') AS wait\";\n\n/** The prefix's setup lock, which every schema setup holds on PostgreSQL: see {@link ensureStorageSchema}. */\nconst SETUP_LOCK_SQL = \"SELECT pg_advisory_xact_lock(hashtextextended(?, 0)) AS locked\";\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). On SQLite the store's schema stamp records it, and only while nothing changed the\n * schema since (`sqliteSchemaStampTable`). False outside such an open, and when the revision is not recorded.\n */\nexport async function storageSchemaCurrent(database: SqliteDatabase, schema: StorageSchemaSetup): Promise<boolean> {\n\tconst dialect = dialectOf(database);\n\tconst key = `schema:${schema.domain}`;\n\tif (dialect.versionedMigrations) {\n\t\tconst recorded = await recordedInCatalog(database, schema.ledger, key);\n\t\treturn recorded !== undefined && recorded >= schema.revision;\n\t}\n\tif (dialect.name !== \"sqlite\") return false;\n\treturn ((await sqliteSchemaStampsOf(database, schema.ledger))?.get(key) ?? 0) >= 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 keep no ledger, `setup`\n * runs every time it is called, as before, and then stamps the store with the schema version the transaction leaves,\n * which {@link storageSchemaCurrent} believes until the schema changes again (#6560).\n */\nexport async function ensureStorageSchema(\n\texecutor: SqliteExecutor,\n\tdialect: StorageDialect,\n\tschema: StorageSchemaSetup,\n\tsetup: () => Promise<void>,\n\toptions: EnsureStorageSchemaOptions = {},\n): Promise<void> {\n\tif (!dialect.versionedMigrations) {\n\t\tawait setup();\n\t\tif (dialect.name === \"sqlite\") await recordSqliteSchemaStamps(executor, [schema]);\n\t\treturn;\n\t}\n\tconst { ledger, domain, revision } = schema;\n\tconst key = `schema:${domain}`;\n\tconst record = {\n\t\tsql: `INSERT INTO ${ledger} (domain, version, applied_at) VALUES (?, ?, ${dialect.nowMs}) ON CONFLICT DO NOTHING`,\n\t\tparams: [key, revision],\n\t};\n\tif (dialect.name !== \"postgres\") {\n\t\tif ((await recordedVersion(executor, dialect, ledger, key)) >= revision) return;\n\t\tawait setup();\n\t\tawait createLedger(executor, dialect, ledger);\n\t\tawait executor.run(record.sql, ...record.params);\n\t\treturn;\n\t}\n\tlet ledgerFound = options.locked === true && options.ledgerExists === true;\n\tif (options.locked !== true) {\n\t\tledgerFound = await tableExists(executor, dialect, ledger);\n\t\tif (ledgerFound && (await recordedVersion(executor, dialect, ledger, key, true)) >= revision) return;\n\t}\n\t// Serialized per prefix, so hosts that start together on a new database set each store up once, and two stores\n\t// that create a table they share never race to create it. The reads go out with the lock, and each runs after it:\n\t// what a holder before it recorded, whether this role may use the schema, and the lock wait the setup restores.\n\tconst [first, usage, lockWait] = postgresSetupReads(dialect, ledger, key, ledgerFound);\n\tconst [, found, access, wait] = await Promise.all([\n\t\toptions.locked === true ? undefined : executor.get(SETUP_LOCK_SQL, `${ledger}:schema`),\n\t\texecutor.get<SqliteRow & { version: number | string | null }>(first.sql, ...first.params),\n\t\texecutor.get<SchemaAccess>(usage.sql, ...usage.params),\n\t\texecutor.get<SqliteRow & { wait: string }>(lockWait.sql, ...lockWait.params),\n\t]);\n\tconst ledgerExists = ledgerFound || found !== undefined;\n\tconst recorded = ledgerFound\n\t\t? Number(found?.version ?? 0)\n\t\t: ledgerExists\n\t\t\t? await recordedVersion(executor, dialect, ledger, key, true)\n\t\t\t: 0;\n\tif (recorded >= revision) return;\n\trefuseWithoutSchemaUsage(access);\n\tconst { int, text } = dialect.types;\n\t// The ledger, created where it is missing, and the record go out with the savepoint's release.\n\tconst createLedgerStatement = {\n\t\tsql: `CREATE TABLE IF NOT EXISTS ${ledger} (domain ${text} NOT NULL, version ${int} NOT NULL, applied_at ${int} NOT NULL, PRIMARY KEY (domain, version))${dialect.tableOptions}`,\n\t\tparams: [],\n\t\tscript: true,\n\t};\n\tawait underShortLockWaits(\n\t\texecutor,\n\t\tsetup,\n\t\twait,\n\t\tledgerExists ? [record] : [createLedgerStatement, record],\n\t\toptions.last === true,\n\t);\n}\n\n/** How {@link ensureStorageSchema} runs in a transaction that holds the setup's locks already. */\nexport interface EnsureStorageSchemaOptions {\n\t/**\n\t * The transaction holds the setup's locks already, as a {@link setUpStorageOnce} setup does: the ledger is read only\n\t * under them, and the prefix's setup lock is not taken again.\n\t */\n\treadonly locked?: boolean;\n\t/** With `locked`: the ledger exists, so its version is the first read, as {@link postgresSetupReads} lists them. */\n\treadonly ledgerExists?: boolean;\n\t/** The setup is the transaction's last call: its last statements go out with the commit. */\n\treadonly last?: boolean;\n}\n\n/**\n * The reads a PostgreSQL setup of the ledger key `key` makes first, under its locks, in this order: the version the\n * ledger records, where it is known to exist, or else whether it does; the schema's usage; and the lock wait the setup\n * restores. A {@link setUpStorageOnce} try sends them with its start.\n */\nfunction postgresSetupReads(\n\tdialect: StorageDialect,\n\tledger: string,\n\tkey: string,\n\tledgerExists: boolean,\n): readonly SqliteStatement[] {\n\treturn [\n\t\tledgerExists ? { sql: versionRead(ledger, key)[0], params: [key] } : dialect.tableExists(ledger),\n\t\t{ sql: SCHEMA_USAGE_SQL, params: [] },\n\t\t{ sql: LOCK_WAIT_SQL, params: [] },\n\t];\n}\n\n/**\n * The advisory locks a PostgreSQL setup recorded in `ledger` under `key` tries: the prefix's setup lock, exclusive while\n * the ledger may be missing, so one setup creates it, and shared once it exists, so the setups of other stores run\n * beside it while an earlier build's setup, which takes it exclusive, runs alone; and a lock of the key's own, so one\n * process sets each store up.\n */\nfunction setupLocks(ledger: string, key: string, ledgerExists: boolean): StorageSetupLock[] {\n\treturn [{ scope: `${ledger}:schema`, shared: ledgerExists }, { scope: `${ledger}:schema:${key}` }];\n}\n\n/**\n * Runs `setup`, a store's idempotent schema statements, as {@link ensureStorageSchema} does, in a transaction of its own:\n * of the processes that open a new database at once, one runs it and the others wait for the ledger to record it,\n * without its lock (`setUpStorageOnce`, #6560). Inside an open, a revision the open's catalog records runs nothing; the\n * caller checks that first (`storageSchemaCurrent`). PostgreSQL; elsewhere the setup runs in a serial transaction of the\n * ledger's domain.\n */\nexport async function ensureStorageSchemaOnce(\n\tdatabase: SqliteDatabase,\n\tschema: StorageSchemaSetup,\n\tsetup: (transaction: SqliteExecutor) => Promise<void>,\n): Promise<void> {\n\tconst dialect = dialectOf(database);\n\tconst { ledger, domain, revision } = schema;\n\tconst concurrency = { kind: \"serial\", domain: ledger } as const;\n\tif (dialect.name !== \"postgres\") {\n\t\tawait database.transaction((tx) => ensureStorageSchema(tx, dialect, schema, () => setup(tx)), {\n\t\t\tretryTransientFailures: true,\n\t\t\tconcurrency,\n\t\t});\n\t\treturn;\n\t}\n\tconst key = `schema:${domain}`;\n\tlet ledgerExists = await ledgerInCatalog(database, ledger);\n\tawait setUpStorageOnce(database, {\n\t\tget locks() {\n\t\t\treturn setupLocks(ledger, key, ledgerExists);\n\t\t},\n\t\tget leading() {\n\t\t\treturn postgresSetupReads(dialect, ledger, key, ledgerExists);\n\t\t},\n\t\tdone: async () => {\n\t\t\tconst recorded = await recordedNow(database, ledger, key, ledgerExists);\n\t\t\tledgerExists ||= await ledgerInCatalog(database, ledger);\n\t\t\treturn recorded >= revision ? true : undefined;\n\t\t},\n\t\tsetup: async (tx, locked) => {\n\t\t\tawait ensureStorageSchema(tx, dialect, schema, () => setup(tx), { locked, ledgerExists, last: true });\n\t\t\treturn true;\n\t\t},\n\t\tconcurrency,\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 * The fillfactor checks this process made that found nothing for it to do, by database (`databaseIdentity`, which\n * names the role and schema too), ledger and table, and the ones under way: the table had a fillfactor, or this role\n * does not own it (#6560). Such a check is not made again. One that set the fillfactor, or found no table, is.\n */\nconst fillfactorChecks = new Map<string, Promise<boolean>>();\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.\n * Otherwise one read of the table's catalog entry decides: nothing runs where the table has a fillfactor already, or\n * where this role does not own the table, so a runtime role without DDL opens as before, and `atomic storage migrate`,\n * run as the owner, sets it. A process reads that once for each database and table, so until migrate records the step\n * only its first open pays the read. Does nothing on SQLite.\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 } = setup;\n\tif (await storageSchemaCurrent(database, { ledger, domain, revision })) return;\n\tconst identity = database.databaseIdentity?.();\n\tif (identity === undefined) {\n\t\tawait checkTableFillfactor(database, setup);\n\t\treturn;\n\t}\n\tconst key = JSON.stringify([identity, ledger, table]);\n\tlet check = fillfactorChecks.get(key);\n\tif (check === undefined) {\n\t\tconst made = checkTableFillfactor(database, setup);\n\t\tcheck = made;\n\t\tfillfactorChecks.set(key, made);\n\t\tconst forget = () => {\n\t\t\tif (fillfactorChecks.get(key) === made) fillfactorChecks.delete(key);\n\t\t};\n\t\tmade.then((settled) => {\n\t\t\tif (!settled) forget();\n\t\t}, forget);\n\t}\n\tawait check;\n}\n\n/**\n * {@link ensureTableFillfactor}'s read of the table's catalog entry, and the change where it is due. True where it\n * found nothing this role can do: the table has a fillfactor, or this role does not own it.\n */\nasync function checkTableFillfactor(database: SqliteDatabase, setup: StorageFillfactorSetup): Promise<boolean> {\n\tconst dialect = dialectOf(database);\n\tconst { ledger, domain, revision, table, fillfactor } = setup;\n\tconst schema = { ledger, domain, revision };\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) return false;\n\tif (yes(found.tuned) || !yes(found.owned)) return true;\n\t// Hosts that open a new database at once set it once, and the others wait for that without the lock.\n\tawait ensureStorageSchemaOnce(database, schema, async (tx) => {\n\t\tawait tx.exec(`ALTER TABLE ${table} SET (fillfactor = ${Math.trunc(fillfactor)})`);\n\t});\n\treturn false;\n}\n"]}
@@ -686,7 +686,7 @@ function __atomicOnDemandFailed(error, feature) {
686
686
  return (async () => {
687
687
  const root = new URL("../../", import.meta.url);
688
688
  const releases = (globalThis[Symbol.for("atomic.in-place-update-release.v1")] ??= new Map());
689
- const key = `${root.href}#0.10.17`;
689
+ const key = `${root.href}#0.10.18`;
690
690
  let release = releases.get(key);
691
691
  if (release === undefined) {
692
692
  const current = (async () => {
@@ -714,7 +714,7 @@ function __atomicOnDemandFailed(error, feature) {
714
714
  } catch {
715
715
  // No installation to read, as in a bundle of the package: the release the process runs decides.
716
716
  }
717
- const updatedTo = typeof installed === "string" && installed !== "0.10.17" ? installed : running !== undefined && running.version !== "0.10.17" ? "0.10.17" : undefined;
717
+ const updatedTo = typeof installed === "string" && installed !== "0.10.18" ? installed : running !== undefined && running.version !== "0.10.18" ? "0.10.18" : undefined;
718
718
  if (updatedTo === undefined) throw error;
719
719
  const application = typeof running?.name === "string" ? running.name : "atomic";
720
720
  const restart = new Error(`${application} was updated to ${updatedTo} while this session was running; restart it to keep using ${feature}.`, {
@@ -2773,7 +2773,7 @@ function __atomicOnDemandFailed(error, feature) {
2773
2773
  return (async () => {
2774
2774
  const root = new URL("../../", import.meta.url);
2775
2775
  const releases = (globalThis[Symbol.for("atomic.in-place-update-release.v1")] ??= new Map());
2776
- const key = `${root.href}#0.10.17`;
2776
+ const key = `${root.href}#0.10.18`;
2777
2777
  let release = releases.get(key);
2778
2778
  if (release === undefined) {
2779
2779
  const current = (async () => {
@@ -2801,7 +2801,7 @@ function __atomicOnDemandFailed(error, feature) {
2801
2801
  } catch {
2802
2802
  // No installation to read, as in a bundle of the package: the release the process runs decides.
2803
2803
  }
2804
- const updatedTo = typeof installed === "string" && installed !== "0.10.17" ? installed : running !== undefined && running.version !== "0.10.17" ? "0.10.17" : undefined;
2804
+ const updatedTo = typeof installed === "string" && installed !== "0.10.18" ? installed : running !== undefined && running.version !== "0.10.18" ? "0.10.18" : undefined;
2805
2805
  if (updatedTo === undefined) throw error;
2806
2806
  const application = typeof running?.name === "string" ? running.name : "atomic";
2807
2807
  const restart = new Error(`${application} was updated to ${updatedTo} while this session was running; restart it to keep using ${feature}.`, {
@@ -6,7 +6,7 @@ try {
6
6
  } catch (error) {
7
7
  const root = new URL("../../", import.meta.url);
8
8
  const releases = (globalThis[Symbol.for("atomic.in-place-update-release.v1")] ??= new Map());
9
- const key = `${root.href}#0.10.17`;
9
+ const key = `${root.href}#0.10.18`;
10
10
  let release = releases.get(key);
11
11
  if (release === undefined) {
12
12
  const current = (async () => {
@@ -27,8 +27,8 @@ try {
27
27
  release = current;
28
28
  }
29
29
  const running = await release;
30
- if (running === undefined || running.version === "0.10.17") throw error;
31
- throw new Error((typeof running.name === "string" ? running.name : "atomic") + " was updated to 0.10.17 while this session was running; restart it to keep using session storage.", {
30
+ if (running === undefined || running.version === "0.10.18") throw error;
31
+ throw new Error((typeof running.name === "string" ? running.name : "atomic") + " was updated to 0.10.18 while this session was running; restart it to keep using session storage.", {
32
32
  cause: error,
33
33
  });
34
34
  }
@@ -6,7 +6,7 @@ try {
6
6
  } catch (error) {
7
7
  const root = new URL("../../", import.meta.url);
8
8
  const releases = (globalThis[Symbol.for("atomic.in-place-update-release.v1")] ??= new Map());
9
- const key = `${root.href}#0.10.17`;
9
+ const key = `${root.href}#0.10.18`;
10
10
  let release = releases.get(key);
11
11
  if (release === undefined) {
12
12
  const current = (async () => {
@@ -27,8 +27,8 @@ try {
27
27
  release = current;
28
28
  }
29
29
  const running = await release;
30
- if (running === undefined || running.version === "0.10.17") throw error;
31
- throw new Error((typeof running.name === "string" ? running.name : "atomic") + " was updated to 0.10.17 while this session was running; restart it to keep using session storage.", {
30
+ if (running === undefined || running.version === "0.10.18") throw error;
31
+ throw new Error((typeof running.name === "string" ? running.name : "atomic") + " was updated to 0.10.18 while this session was running; restart it to keep using session storage.", {
32
32
  cause: error,
33
33
  });
34
34
  }
@@ -0,0 +1,11 @@
1
+ import type { SqliteStatement } from "./database.js";
2
+ /** An advisory lock PostgreSQL tries for the current transaction, without joining the lock queue. */
3
+ export interface PostgresTryLock {
4
+ readonly scope: string;
5
+ /** Qualify the scope like the adapter's serial locks: `<schema>:<scope>`, or just `<scope>` in `public`. */
6
+ readonly inSchema?: boolean;
7
+ readonly shared?: boolean;
8
+ }
9
+ /** A first statement that tries the given locks and says whether it took them all. */
10
+ export declare function tryPostgresLocks(locks: readonly PostgresTryLock[]): SqliteStatement;
11
+ //# sourceMappingURL=postgres-locks.d.ts.map
@@ -0,0 +1,9 @@
1
+ // The adapter sets a transaction-local search path with the storage schema as its first entry.
2
+ const SCHEMA_LOCK_PREFIX = `(SELECT CASE WHEN name = 'public' THEN '' ELSE name || ':' END
3
+ FROM (SELECT trim(both '"' from split_part(current_setting('search_path'), ',', 1)) AS name) AS search)`;
4
+ /** A first statement that tries the given locks and says whether it took them all. */
5
+ export function tryPostgresLocks(locks) {
6
+ const taken = locks.map(({ inSchema, shared }) => `pg_try_advisory_xact_lock${shared === true ? "_shared" : ""}(hashtextextended(${inSchema === true ? `${SCHEMA_LOCK_PREFIX} || ` : ""}?, 0))`);
7
+ return { sql: `SELECT (${taken.join(" AND ")})::int AS won`, params: locks.map(({ scope }) => scope) };
8
+ }
9
+ //# sourceMappingURL=postgres-locks.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres-locks.js","sourceRoot":"","sources":["../../../src/core/storage/postgres-locks.ts"],"names":[],"mappings":"AAUA,+FAA+F;AAC/F,MAAM,kBAAkB,GAAG;yGAC8E,CAAC;AAE1G,sFAAsF;AACtF,MAAM,UAAU,gBAAgB,CAAC,KAAiC;IACjE,MAAM,KAAK,GAAG,KAAK,CAAC,GAAG,CACtB,CAAC,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,CACxB,4BAA4B,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,qBAAqB,QAAQ,KAAK,IAAI,CAAC,CAAC,CAAC,GAAG,kBAAkB,MAAM,CAAC,CAAC,CAAC,EAAE,QAAQ,CAC9I,CAAC;IACF,OAAO,EAAE,GAAG,EAAE,WAAW,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,eAAe,EAAE,MAAM,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC;AACxG,CAAC","sourcesContent":["import type { SqliteStatement } from \"./database.js\";\n\n/** An advisory lock PostgreSQL tries for the current transaction, without joining the lock queue. */\nexport interface PostgresTryLock {\n\treadonly scope: string;\n\t/** Qualify the scope like the adapter's serial locks: `<schema>:<scope>`, or just `<scope>` in `public`. */\n\treadonly inSchema?: boolean;\n\treadonly shared?: boolean;\n}\n\n// The adapter sets a transaction-local search path with the storage schema as its first entry.\nconst SCHEMA_LOCK_PREFIX = `(SELECT CASE WHEN name = 'public' THEN '' ELSE name || ':' END\n\tFROM (SELECT trim(both '\"' from split_part(current_setting('search_path'), ',', 1)) AS name) AS search)`;\n\n/** A first statement that tries the given locks and says whether it took them all. */\nexport function tryPostgresLocks(locks: readonly PostgresTryLock[]): SqliteStatement {\n\tconst taken = locks.map(\n\t\t({ inSchema, shared }) =>\n\t\t\t`pg_try_advisory_xact_lock${shared === true ? \"_shared\" : \"\"}(hashtextextended(${inSchema === true ? `${SCHEMA_LOCK_PREFIX} || ` : \"\"}?, 0))`,\n\t);\n\treturn { sql: `SELECT (${taken.join(\" AND \")})::int AS won`, params: locks.map(({ scope }) => scope) };\n}\n"]}
@@ -443,7 +443,7 @@ function __atomicOnDemandFailed(error, feature) {
443
443
  return (async () => {
444
444
  const root = new URL("../../", import.meta.url);
445
445
  const releases = (globalThis[Symbol.for("atomic.in-place-update-release.v1")] ??= new Map());
446
- const key = `${root.href}#0.10.17`;
446
+ const key = `${root.href}#0.10.18`;
447
447
  let release = releases.get(key);
448
448
  if (release === undefined) {
449
449
  const current = (async () => {
@@ -471,7 +471,7 @@ function __atomicOnDemandFailed(error, feature) {
471
471
  } catch {
472
472
  // No installation to read, as in a bundle of the package: the release the process runs decides.
473
473
  }
474
- const updatedTo = typeof installed === "string" && installed !== "0.10.17" ? installed : running !== undefined && running.version !== "0.10.17" ? "0.10.17" : undefined;
474
+ const updatedTo = typeof installed === "string" && installed !== "0.10.18" ? installed : running !== undefined && running.version !== "0.10.18" ? "0.10.18" : undefined;
475
475
  if (updatedTo === undefined) throw error;
476
476
  const application = typeof running?.name === "string" ? running.name : "atomic";
477
477
  const restart = new Error(`${application} was updated to ${updatedTo} while this session was running; restart it to keep using ${feature}.`, {