@bastani/atomic 0.10.11-alpha.1 → 0.10.11-alpha.2

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 (303) hide show
  1. package/CHANGELOG.md +56 -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 +7 -7
  6. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +7 -7
  7. package/dist/_shared/mode-shared-2QJSCUM6.js +7 -7
  8. package/dist/_shared/p1a-prewarm-XIU57JHF.js +3 -3
  9. package/dist/_shared/runtime-O4KCSG4C.js +5 -5
  10. package/dist/_shared/{sdk-AVFII7NK.js → sdk-IQMULKFU.js} +2438 -470
  11. package/dist/_shared/sdk-IQMULKFU.js.map +1 -0
  12. package/dist/_shared/session-data-AHTU7IS6.js +3 -3
  13. package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
  14. package/dist/_shared/settings-startup-8-DNZ2RIHM.js +1 -1
  15. package/dist/_shared/{settings-startup-4QCVCI53.js → settings-startup-HXQLSUWM.js} +8 -2
  16. package/dist/_shared/settings-startup-HXQLSUWM.js.map +1 -0
  17. package/dist/_shared/{startup-0-0-57KF6LZH.js → startup-0-0-3IXNMFM2.js} +392 -15
  18. package/dist/_shared/startup-0-0-3IXNMFM2.js.map +1 -0
  19. package/dist/_shared/{startup-0-1-GIY75K46.js → startup-0-1-7T2IAE7J.js} +51 -243
  20. package/dist/_shared/startup-0-1-7T2IAE7J.js.map +1 -0
  21. package/dist/_shared/{startup-0-2-27OWFHV6.js → startup-0-2-5QHPCEON.js} +225 -7
  22. package/dist/_shared/startup-0-2-5QHPCEON.js.map +1 -0
  23. package/dist/_shared/{startup-0-3-T4DVFYWX.js → startup-0-3-4ZYBYQNM.js} +273 -14
  24. package/dist/_shared/startup-0-3-4ZYBYQNM.js.map +1 -0
  25. package/dist/_shared/startup-0-4-ZMJV547D.js +6 -6
  26. package/dist/_shared/startup-0-5-YDW47QX6.js +7 -7
  27. package/dist/_shared/startup-10-0-TDQNBDDL.js +7 -7
  28. package/dist/_shared/startup-12-0-55AAXBJZ.js +2 -2
  29. package/dist/_shared/startup-14-0-MLX36RBG.js +4 -4
  30. package/dist/_shared/startup-15-0-YUKGAC63.js +5 -5
  31. package/dist/_shared/startup-15-1-4S7FLMNG.js +7 -7
  32. package/dist/_shared/startup-8-0-34CBHPZH.js +421 -84
  33. package/dist/_shared/startup-8-0-34CBHPZH.js.map +1 -1
  34. package/dist/_shared/startup-8-1-X32CYSXB.js +77 -13
  35. package/dist/_shared/startup-8-1-X32CYSXB.js.map +1 -1
  36. package/dist/_shared/storage-command-7MGXLJGZ.js +7 -5
  37. package/dist/_shared/storage-command-7MGXLJGZ.js.map +1 -1
  38. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  39. package/dist/_shared/tree-outline-MUEPK5B7.js +3 -3
  40. package/dist/builtin/intercom/CHANGELOG.md +11 -0
  41. package/dist/builtin/intercom/broker/broker.bundle.mjs +205 -82
  42. package/dist/builtin/intercom/broker/sql-lease-store.ts +38 -27
  43. package/dist/builtin/intercom/broker/sql-outbox-store.ts +228 -65
  44. package/dist/builtin/intercom/broker/sql-schema.ts +82 -27
  45. package/dist/builtin/intercom/index.bundle.mjs +1 -1
  46. package/dist/builtin/intercom/package.json +1 -1
  47. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  48. package/dist/builtin/mcp/package.json +1 -1
  49. package/dist/builtin/subagents/CHANGELOG.md +6 -0
  50. package/dist/builtin/subagents/package.json +1 -1
  51. package/dist/builtin/subagents/src/extension/index.bundle.mjs +1 -1
  52. package/dist/builtin/web-access/index.bundle.mjs +1 -1
  53. package/dist/builtin/web-access/package.json +1 -1
  54. package/dist/cli/args.js +2 -2
  55. package/dist/cli/auth-cli.code.js +4 -4
  56. package/dist/cli/auth-cli.impl.js +3 -3
  57. package/dist/cli/auth-cli.js +3 -3
  58. package/dist/cli/blueprint-command.code.js +2 -2
  59. package/dist/cli/blueprint-command.impl.js +3 -3
  60. package/dist/cli/blueprint-command.js +3 -3
  61. package/dist/cli/intercom-command.code.js +3 -3
  62. package/dist/cli/intercom-command.impl.js +3 -3
  63. package/dist/cli/intercom-command.js +3 -3
  64. package/dist/cli/list-models.code.js +2 -2
  65. package/dist/cli/list-models.impl.js +3 -3
  66. package/dist/cli/list-models.js +3 -3
  67. package/dist/cli/session-picker.code.js +2 -2
  68. package/dist/cli/session-picker.impl.js +3 -3
  69. package/dist/cli/session-picker.js +3 -3
  70. package/dist/cli/startup-ui.code.js +2 -2
  71. package/dist/cli/startup-ui.impl.js +3 -3
  72. package/dist/cli/startup-ui.js +3 -3
  73. package/dist/cli/storage-command.impl.js +3 -3
  74. package/dist/cli/storage-command.js +3 -3
  75. package/dist/cli/storage-search-session.code.js +2 -2
  76. package/dist/cli/storage-search-session.impl.js +3 -3
  77. package/dist/cli/storage-search-session.js +3 -3
  78. package/dist/cli/team-command.code.js +2 -2
  79. package/dist/cli/team-command.impl.js +3 -3
  80. package/dist/cli/team-command.js +3 -3
  81. package/dist/cli.js +2 -2
  82. package/dist/core/debug.impl.js +3 -3
  83. package/dist/core/debug.js +3 -3
  84. package/dist/core/export-html/card-projection.impl.js +3 -3
  85. package/dist/core/export-html/card-projection.js +3 -3
  86. package/dist/core/export-html/index.code.js +2 -2
  87. package/dist/core/export-html/index.impl.js +3 -3
  88. package/dist/core/export-html/index.js +3 -3
  89. package/dist/core/export-html/json-spans.impl.js +3 -3
  90. package/dist/core/export-html/json-spans.js +3 -3
  91. package/dist/core/export-html/oversized-render-inputs.code.js +1 -1
  92. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  93. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  94. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  95. package/dist/core/export-html/tool-renderer.js +3 -3
  96. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  97. package/dist/core/extensions/jiti-loader.js +3 -3
  98. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  99. package/dist/core/extensions/jiti-static-loader.js +3 -3
  100. package/dist/core/extensions/loader-host-modules.code.js +1 -1
  101. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  102. package/dist/core/extensions/loader-host-modules.js +3 -3
  103. package/dist/core/extensions/loader-virtual-modules.js +1 -1
  104. package/dist/core/extensions/runner-context.js +2 -2
  105. package/dist/core/intercom-broker-control-host.code.js +1 -1
  106. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  107. package/dist/core/intercom-broker-control-host.js +3 -3
  108. package/dist/core/intercom-broker-control.code.js +3 -3
  109. package/dist/core/intercom-broker-control.impl.js +3 -3
  110. package/dist/core/intercom-broker-control.js +3 -3
  111. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  112. package/dist/core/package-manager-storage-adapters.js +3 -3
  113. package/dist/core/sdk.code.js +3 -3
  114. package/dist/core/sdk.impl.js +3 -3
  115. package/dist/core/sdk.js +3 -3
  116. package/dist/core/session-manager-core.js +26 -14
  117. package/dist/core/session-manager-core.js.map +1 -1
  118. package/dist/core/session-manager-list.impl.js +3 -3
  119. package/dist/core/session-manager-list.js +3 -3
  120. package/dist/core/session-manager.code.js +3 -3
  121. package/dist/core/session-manager.impl.js +3 -3
  122. package/dist/core/session-manager.js +3 -3
  123. package/dist/core/session-open-markers.js +3 -0
  124. package/dist/core/session-open-markers.js.map +1 -0
  125. package/dist/core/session-storage.impl.js +3 -3
  126. package/dist/core/session-storage.js +3 -3
  127. package/dist/core/storage/added-exports.js +3 -0
  128. package/dist/core/storage/added-exports.js.map +1 -1
  129. package/dist/core/storage/database.d.ts +37 -0
  130. package/dist/core/storage/database.js.map +1 -1
  131. package/dist/core/storage/index.d.ts +1 -1
  132. package/dist/core/storage/index.js +2 -2
  133. package/dist/core/storage/index.js.map +1 -1
  134. package/dist/core/storage/migrations.d.ts +12 -3
  135. package/dist/core/storage/migrations.js +24 -11
  136. package/dist/core/storage/migrations.js.map +1 -1
  137. package/dist/core/storage/node-sqlite-thread.js +31 -2
  138. package/dist/core/storage/node-sqlite-thread.js.map +1 -1
  139. package/dist/core/storage/node-sqlite.js +86 -2
  140. package/dist/core/storage/node-sqlite.js.map +1 -1
  141. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  142. package/dist/core/storage/offline-snapshot-file.js +3 -3
  143. package/dist/core/storage/prefix.js +5 -0
  144. package/dist/core/storage/prefix.js.map +1 -1
  145. package/dist/core/storage/provider.js +2 -2
  146. package/dist/core/storage/schema-catalog.d.ts +82 -4
  147. package/dist/core/storage/schema-catalog.js +242 -32
  148. package/dist/core/storage/schema-catalog.js.map +1 -1
  149. package/dist/core/storage/selection.js +2 -2
  150. package/dist/core/storage/session/branch-fork-source.code.js +9 -8
  151. package/dist/core/storage/session/branch-fork-source.code.js.map +1 -1
  152. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  153. package/dist/core/storage/session/branch-fork-source.js +3 -3
  154. package/dist/core/storage/session/card-view.impl.js +3 -3
  155. package/dist/core/storage/session/card-view.js +3 -3
  156. package/dist/core/storage/session/child-reader.code.js +4 -4
  157. package/dist/core/storage/session/child-reader.impl.js +3 -3
  158. package/dist/core/storage/session/child-reader.js +3 -3
  159. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  160. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  161. package/dist/core/storage/session/errors.js +1 -1
  162. package/dist/core/storage/session/expanded-child-details.code.js +3 -3
  163. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  164. package/dist/core/storage/session/expanded-child-details.js +3 -3
  165. package/dist/core/storage/session/fork-detach.d.ts +118 -0
  166. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  167. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  168. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  169. package/dist/core/storage/session/fork-row-index.js +3 -3
  170. package/dist/core/storage/session/fork-schema.js +53 -0
  171. package/dist/core/storage/session/fork-schema.js.map +1 -0
  172. package/dist/core/storage/session/fork-segments.d.ts +58 -0
  173. package/dist/core/storage/session/fork-staging.code.js +3 -3
  174. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  175. package/dist/core/storage/session/fork-staging.js +3 -3
  176. package/dist/core/storage/session/fork-sweep.js +61 -0
  177. package/dist/core/storage/session/fork-sweep.js.map +1 -0
  178. package/dist/core/storage/session/fork-window.code.js +4 -4
  179. package/dist/core/storage/session/fork-window.impl.js +3 -3
  180. package/dist/core/storage/session/fork-window.js +3 -3
  181. package/dist/core/storage/session/history-pages.impl.js +3 -3
  182. package/dist/core/storage/session/history-pages.js +3 -3
  183. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  184. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  185. package/dist/core/storage/session/jsonl-session-store.d.ts +37 -1
  186. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  187. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  188. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  189. package/dist/core/storage/session/memory-session-store.js +3 -3
  190. package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
  191. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  192. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  193. package/dist/core/storage/session/released-history-files.code.js +3 -3
  194. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  195. package/dist/core/storage/session/released-history-files.js +3 -3
  196. package/dist/core/storage/session/resident-fork-rows.code.js +1 -1
  197. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  198. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  199. package/dist/core/storage/session/session-resume.impl.js +3 -3
  200. package/dist/core/storage/session/session-resume.js +3 -3
  201. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  202. package/dist/core/storage/session/snapshot-cut.js +3 -3
  203. package/dist/core/storage/session/snapshot-history.code.js +4 -4
  204. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  205. package/dist/core/storage/session/snapshot-history.js +3 -3
  206. package/dist/core/storage/session/sql-session-store.code.js +1 -1
  207. package/dist/core/storage/session/sql-session-store.d.ts +349 -12
  208. package/dist/core/storage/session/sql-session-store.impl.js +4 -4
  209. package/dist/core/storage/session/sql-session-store.js +4 -4
  210. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  211. package/dist/core/storage/session/tree-outline.js +3 -3
  212. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  213. package/dist/core/storage/session/tree-presentation.js +3 -3
  214. package/dist/core/storage/session/types.d.ts +22 -0
  215. package/dist/core/storage/sqlite-facade.d.ts +17 -1
  216. package/dist/core/storage/sqlite-facade.js +33 -0
  217. package/dist/core/storage/sqlite-facade.js.map +1 -1
  218. package/dist/core/storage/storage-status.impl.js +3 -3
  219. package/dist/core/storage/storage-status.js +3 -3
  220. package/dist/core/storage/team.impl.js +3 -3
  221. package/dist/core/storage/team.js +3 -3
  222. package/dist/core/structured-output/index.code.js +1 -1
  223. package/dist/core/structured-output/index.impl.js +3 -3
  224. package/dist/core/structured-output/index.js +3 -3
  225. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  226. package/dist/core/tasks/task-completion-entry.js +3 -3
  227. package/dist/core/tasks/task-file-history.code.js +4 -4
  228. package/dist/core/tasks/task-file-history.impl.js +3 -3
  229. package/dist/core/tasks/task-file-history.js +3 -3
  230. package/dist/core/tasks/task-reference-archive.code.js +4 -4
  231. package/dist/core/tasks/task-reference-archive.js +3 -3
  232. package/dist/core/tasks/task-reference-identity.js +3 -3
  233. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  234. package/dist/core/tasks/task-reference-stream.js +3 -3
  235. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  236. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  237. package/dist/core/tasks/task-view-source.impl.js +3 -3
  238. package/dist/core/tasks/task-view-source.js +3 -3
  239. package/dist/core/tools/history-session.d.ts +2 -0
  240. package/dist/core/tools/read-url.code.js +2 -2
  241. package/dist/core/tools/read-url.impl.js +3 -3
  242. package/dist/core/tools/read-url.js +3 -3
  243. package/dist/core/worktree-snapshot/blob-store.d.ts +31 -0
  244. package/dist/core/worktree-snapshot/blob-store.js +164 -49
  245. package/dist/core/worktree-snapshot/blob-store.js.map +1 -1
  246. package/dist/core/worktree-snapshot/errors.code.js +3 -3
  247. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  248. package/dist/core/worktree-snapshot/errors.js +3 -3
  249. package/dist/core/worktree-snapshot/fork-snapshot-index.js +121 -0
  250. package/dist/core/worktree-snapshot/fork-snapshot-index.js.map +1 -0
  251. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  252. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  253. package/dist/extensions/codemode/execute.code.js +2 -2
  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 +2 -2
  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.code.js +1 -1
  266. package/dist/extensions/mcp/runtime.impl.js +3 -3
  267. package/dist/extensions/mcp/runtime.js +3 -3
  268. package/dist/index.js +6 -6
  269. package/dist/main-first-time-setup.code.js +2 -2
  270. package/dist/main-first-time-setup.impl.js +3 -3
  271. package/dist/main-first-time-setup.js +3 -3
  272. package/dist/modes/interactive/components/stored-tree-view.code.js +3 -3
  273. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  274. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  275. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  276. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  277. package/dist/modes/print-mode.js +1 -1
  278. package/dist/package-manager-cli.code.js +5 -5
  279. package/dist/package-manager-cli.impl.js +3 -3
  280. package/dist/package-manager-cli.js +3 -3
  281. package/dist/rpc-entry.js +1 -1
  282. package/dist/startup-files.json +1 -1
  283. package/dist/startup-stages/2.js +1 -0
  284. package/dist/startup-stages/5.js +1 -1
  285. package/dist/startup-stages/7.js +5 -1
  286. package/dist/startup-stages/8.js +2 -2
  287. package/dist/utils/startup-database-spare.code.js +3 -3
  288. package/dist/utils/startup-database-spare.impl.js +3 -3
  289. package/dist/utils/startup-database-spare.js +3 -3
  290. package/dist/utils/tools-manager.code.js +1 -1
  291. package/dist/utils/tools-manager.impl.js +3 -3
  292. package/dist/utils/tools-manager.js +3 -3
  293. package/docs/guides/postgres-pgbouncer.md +14 -7
  294. package/docs/guides/postgres-tuning.md +9 -9
  295. package/docs/sessions.md +9 -0
  296. package/docs/storage.md +47 -6
  297. package/package.json +8 -8
  298. package/dist/_shared/sdk-AVFII7NK.js.map +0 -1
  299. package/dist/_shared/settings-startup-4QCVCI53.js.map +0 -1
  300. package/dist/_shared/startup-0-0-57KF6LZH.js.map +0 -1
  301. package/dist/_shared/startup-0-1-GIY75K46.js.map +0 -1
  302. package/dist/_shared/startup-0-2-27OWFHV6.js.map +0 -1
  303. package/dist/_shared/startup-0-3-T4DVFYWX.js.map +0 -1
@@ -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.11-alpha.1`;
9
+ const key = `${root.href}#0.10.11-alpha.2`;
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.11-alpha.1") throw error;
31
- throw new Error((typeof running.name === "string" ? running.name : "atomic") + " was updated to 0.10.11-alpha.1 while this session was running; restart it to keep using session storage.", {
30
+ if (running === undefined || running.version === "0.10.11-alpha.2") throw error;
31
+ throw new Error((typeof running.name === "string" ? running.name : "atomic") + " was updated to 0.10.11-alpha.2 while this session was running; restart it to keep using session storage.", {
32
32
  cause: error,
33
33
  });
34
34
  }
@@ -7,6 +7,9 @@ import * as statementSequence from "./statement-sequence.js";
7
7
  * can load the modules that use these from the update: a named import of any of them would fail to link there, so they
8
8
  * take them from here, a path no earlier release has (#6560). Without them every open checks its schema in a
9
9
  * transaction, tables keep their default fillfactor, and a transaction's last writes run before its `COMMIT`, as there.
10
+ *
11
+ * Releases since 0.10.11-alpha.1 ship this module with these exports, so a process of one may hold its copy: an export
12
+ * added here would fail to link there. Later additions go in a module no release has, as `added-exports-0-10-11.ts`.
10
13
  */
11
14
  const schemaChecks = migrations;
12
15
  const finishers = statementSequence;
@@ -1 +1 @@
1
- {"version":3,"file":"added-exports.js","sourceRoot":"","sources":["../../../src/core/storage/added-exports.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,UAAU,MAAM,iBAAiB,CAAC;AAC9C,OAAO,KAAK,iBAAiB,MAAM,yBAAyB,CAAC;AAE7D;;;;;;;GAOG;AACH,MAAM,YAAY,GAAuF,UAAU,CAAC;AACpH,MAAM,SAAS,GAAmE,iBAAiB,CAAC;AAEpG,MAAM,CAAC,MAAM,oBAAoB,GAChC,YAAY,CAAC,oBAAoB,IAAI,CAAC,KAAK,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC;AAE1D,MAAM,CAAC,MAAM,qBAAqB,GACjC,YAAY,CAAC,qBAAqB,IAAI,CAAC,KAAK,IAAI,EAAE,GAAE,CAAC,CAAC,CAAC;AAExD,MAAM,CAAC,MAAM,mBAAmB,GAC/B,SAAS,CAAC,mBAAmB,IAAI,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC","sourcesContent":["import * as migrations from \"./migrations.js\";\nimport * as statementSequence from \"./statement-sequence.js\";\n\n/**\n * `storageSchemaCurrent` and `ensureTableFillfactor` of `migrations.ts` and `transactionFinisher` of\n * `statement-sequence.ts`, which the copies of those modules (and of `statement-batches.ts`) that 0.10.3 and 0.10.4\n * loaded lack. A process that loaded those copies before an in-place update replaced the installation keeps them, and\n * can load the modules that use these from the update: a named import of any of them would fail to link there, so they\n * take them from here, a path no earlier release has (#6560). Without them every open checks its schema in a\n * transaction, tables keep their default fillfactor, and a transaction's last writes run before its `COMMIT`, as there.\n */\nconst schemaChecks: Partial<Pick<typeof migrations, \"storageSchemaCurrent\" | \"ensureTableFillfactor\">> = migrations;\nconst finishers: Partial<Pick<typeof statementSequence, \"transactionFinisher\">> = statementSequence;\n\nexport const storageSchemaCurrent: typeof migrations.storageSchemaCurrent =\n\tschemaChecks.storageSchemaCurrent ?? (async () => false);\n\nexport const ensureTableFillfactor: typeof migrations.ensureTableFillfactor =\n\tschemaChecks.ensureTableFillfactor ?? (async () => {});\n\nexport const transactionFinisher: typeof statementSequence.transactionFinisher =\n\tfinishers.transactionFinisher ?? (() => undefined);\n"]}
1
+ {"version":3,"file":"added-exports.js","sourceRoot":"","sources":["../../../src/core/storage/added-exports.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,UAAU,MAAM,iBAAiB,CAAC;AAC9C,OAAO,KAAK,iBAAiB,MAAM,yBAAyB,CAAC;AAE7D;;;;;;;;;;GAUG;AACH,MAAM,YAAY,GAAuF,UAAU,CAAC;AACpH,MAAM,SAAS,GAAmE,iBAAiB,CAAC;AAEpG,MAAM,CAAC,MAAM,oBAAoB,GAChC,YAAY,CAAC,oBAAoB,IAAI,CAAC,KAAK,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC;AAE1D,MAAM,CAAC,MAAM,qBAAqB,GACjC,YAAY,CAAC,qBAAqB,IAAI,CAAC,KAAK,IAAI,EAAE,GAAE,CAAC,CAAC,CAAC;AAExD,MAAM,CAAC,MAAM,mBAAmB,GAC/B,SAAS,CAAC,mBAAmB,IAAI,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC","sourcesContent":["import * as migrations from \"./migrations.js\";\nimport * as statementSequence from \"./statement-sequence.js\";\n\n/**\n * `storageSchemaCurrent` and `ensureTableFillfactor` of `migrations.ts` and `transactionFinisher` of\n * `statement-sequence.ts`, which the copies of those modules (and of `statement-batches.ts`) that 0.10.3 and 0.10.4\n * loaded lack. A process that loaded those copies before an in-place update replaced the installation keeps them, and\n * can load the modules that use these from the update: a named import of any of them would fail to link there, so they\n * take them from here, a path no earlier release has (#6560). Without them every open checks its schema in a\n * transaction, tables keep their default fillfactor, and a transaction's last writes run before its `COMMIT`, as there.\n *\n * Releases since 0.10.11-alpha.1 ship this module with these exports, so a process of one may hold its copy: an export\n * added here would fail to link there. Later additions go in a module no release has, as `added-exports-0-10-11.ts`.\n */\nconst schemaChecks: Partial<Pick<typeof migrations, \"storageSchemaCurrent\" | \"ensureTableFillfactor\">> = migrations;\nconst finishers: Partial<Pick<typeof statementSequence, \"transactionFinisher\">> = statementSequence;\n\nexport const storageSchemaCurrent: typeof migrations.storageSchemaCurrent =\n\tschemaChecks.storageSchemaCurrent ?? (async () => false);\n\nexport const ensureTableFillfactor: typeof migrations.ensureTableFillfactor =\n\tschemaChecks.ensureTableFillfactor ?? (async () => {});\n\nexport const transactionFinisher: typeof statementSequence.transactionFinisher =\n\tfinishers.transactionFinisher ?? (() => undefined);\n"]}
@@ -51,6 +51,20 @@ export interface SqliteTransactionOptions {
51
51
  * fenced path's one guarded write: it never runs unused. Other drivers ignore it.
52
52
  */
53
53
  readonly leading?: readonly SqliteStatement[];
54
+ /**
55
+ * @internal The callback makes the `leading` calls, all of them in order, and no other. A pipelined driver then sends
56
+ * the commit right behind them, so the whole transaction costs one round trip: a call the callback makes after them
57
+ * fails without being sent. When a leading statement fails, the transaction rolls back and the callback's call of
58
+ * that statement fails. Other drivers ignore it.
59
+ */
60
+ readonly leadingOnly?: boolean;
61
+ /**
62
+ * @internal With `leading`, a `serial` transaction of a domain takes its locks in its first leading statement, a read,
63
+ * and only when that read returns a row, instead of with its start: a transaction whose first read finds nothing
64
+ * takes no lock. Every statement after it starts once the locks are held, so it sees every transaction that held them
65
+ * and committed. A driver that ignores it takes the locks with the start. Other drivers ignore it.
66
+ */
67
+ readonly lockIfLeadingFinds?: boolean;
54
68
  }
55
69
  /** How one batch waits for a busy write lock, and whether it goes ahead of the database's queued calls. */
56
70
  export interface SqliteBatchOptions {
@@ -134,6 +148,16 @@ export interface StorageNotifications {
134
148
  /** Opens the listening connection when it is not open, and resolves with its state once the first attempt settled. */
135
149
  state(): Promise<StorageListenerState>;
136
150
  }
151
+ /**
152
+ * @internal What a driver read of its schema in its open's own round trip (#6560): the rows of the catalog read
153
+ * `readStorageSchemaCatalog` makes (`kind` `relation`, `trigger` or `column`, with `name` and `detail`) and the
154
+ * versions `ledger` records, as rows of `domain` and `version`; `versions` is undefined when the ledger did not exist.
155
+ */
156
+ export interface StorageOpenedCatalog {
157
+ readonly ledger: string;
158
+ readonly rows: readonly SqliteRow[];
159
+ readonly versions: readonly SqliteRow[] | undefined;
160
+ }
137
161
  export interface SqliteDatabase extends SqliteExecutor {
138
162
  /**
139
163
  * True when the connection refuses writes, as `openNodeSqliteDatabase(path, { readOnly: true })` sets it, so opening a
@@ -166,7 +190,20 @@ export interface SqliteDatabase extends SqliteExecutor {
166
190
  tryMaintenance?(callback: (transaction: SqliteExecutor) => Promise<void>): Promise<boolean>;
167
191
  /** Opens a separate handle on this same database for reads. It has its own call queue; the caller must close it. */
168
192
  openReader?(): Promise<SqliteDatabase>;
193
+ /**
194
+ * @internal The schema the driver read when it opened, given once: the first store open answers its schema checks
195
+ * from it instead of reading the catalog again. Undefined after the first call, and where the driver read none.
196
+ */
197
+ takeOpenedCatalog?(): StorageOpenedCatalog | undefined;
169
198
  transaction<T>(callback: (transaction: SqliteExecutor) => Promise<T>, options?: SqliteTransactionOptions): Promise<T>;
199
+ /**
200
+ * @internal Runs `statement` by itself as one request that commits on its own, queued in this process as a
201
+ * transaction of `concurrency` is: behind the calls such a transaction waits for, and ahead of the calls that wait
202
+ * for it. The statement takes on the server whatever locks it needs itself, such as a function that takes the
203
+ * domain's advisory locks. A transient failure that applied nothing runs it again. Resolves with its rows. Present
204
+ * only where the driver runs transactions concurrently (PostgreSQL).
205
+ */
206
+ autocommit?(statement: SqliteStatement, concurrency: TransactionConcurrency): Promise<SqliteRow[]>;
170
207
  /**
171
208
  * Runs the statements in order, in one write transaction, as one call to the database: all of them commit or none
172
209
  * do. Resolves with each statement's rows. Present only when the driver can send a batch in one request, which
@@ -1 +1 @@
1
- {"version":3,"file":"database.js","sourceRoot":"","sources":["../../../src/core/storage/database.ts"],"names":[],"mappings":"","sourcesContent":["import type { StorageDialect } from \"./dialect.js\";\n\nexport type SqliteValue = null | number | bigint | string | Uint8Array;\nexport type SqliteRow = Readonly<Record<string, SqliteValue>>;\n\nexport interface SqliteRunResult {\n\treadonly changes: number;\n}\n\nexport interface SqliteExecutor {\n\texec(sql: string): Promise<void>;\n\trun(sql: string, ...params: readonly SqliteValue[]): Promise<SqliteRunResult>;\n\tget<T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]): Promise<T | undefined>;\n\tall<T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]): Promise<T[]>;\n}\n\nexport interface StorageDescriptor {\n\treadonly adapter: string;\n\treadonly location: string;\n}\n\n/** One statement of a batch: SQL with positional `?` parameters. */\nexport interface SqliteStatement {\n\treadonly sql: string;\n\treadonly params: readonly SqliteValue[];\n}\n\n/** How a transaction takes its snapshot or write lock, and whether it may run again. */\nexport interface SqliteTransactionOptions {\n\t/** @internal A consistent read snapshot without a writer lock. The callback must only read. */\n\treadonly readOnly?: boolean;\n\t/**\n\t * How long the transaction keeps waiting for the write lock while it is held and no other connection commits,\n\t * instead of the connection's own lock wait. A writer whose work must not fail because another process stalled\n\t * with the lock held (starved of CPU, paused by garbage collection, stopped by a signal) waits longer: the holder\n\t * still commits or rolls back once it runs again. Adapters without a lock wait of their own ignore it.\n\t */\n\treadonly lockWaitMs?: number;\n\t/**\n\t * Lets a database from `createSqliteDatabase` run the callback again, in a new transaction, when a transient\n\t * failure (`StorageTransientError`) ended the transaction before it committed, so nothing of it was written. Set it\n\t * only for a callback that does nothing but use the transaction handle: anything else it does happens once per run.\n\t * Other databases ignore it.\n\t */\n\treadonly retryTransientFailures?: boolean;\n\t/**\n\t * How the transaction excludes other writers; `{ kind: \"serial\" }` when absent. SQLite runs every kind as\n\t * `BEGIN IMMEDIATE` unless `readOnly` is set; only a driver that runs transactions concurrently (Postgres) tells them apart.\n\t */\n\treadonly concurrency?: TransactionConcurrency;\n\t/**\n\t * @internal The statements the callback makes first, in this order, before it acts on any answer. A driver whose\n\t * transactions are pipelined sends them with the transaction's start, so they cost no round trip of their own, and\n\t * starts the callback once they are answered; each call of the callback that makes the next of them gets its answer.\n\t * Name only reads: a call that differs from the next of them ends the lead, and the answers of the rest go unused,\n\t * though they ran. A write may lead only as the callback's first call, made on every run whatever it reads, such as a\n\t * fenced path's one guarded write: it never runs unused. Other drivers ignore it.\n\t */\n\treadonly leading?: readonly SqliteStatement[];\n}\n\n/** How one batch waits for a busy write lock, and whether it goes ahead of the database's queued calls. */\nexport interface SqliteBatchOptions {\n\t/**\n\t * How long a batch that found the database's write lock busy keeps sending again, with growing randomized waits\n\t * between tries. A busy batch wrote nothing, so sending it again is safe. Adapters without such a retry ignore it.\n\t */\n\treadonly lockWaitMs?: number;\n\t/**\n\t * Runs the batch before calls queued on this database that do not set it, and outside any limit the adapter puts on\n\t * concurrent writes: for small writes that must not wait behind others, such as a lease renewal.\n\t */\n\treadonly priority?: boolean;\n}\n\n/**\n * An audited fenced write path. Only `fencedPath(name)` in `fenced-paths.ts` makes one; a plain string is not one. The\n * brand is a string key, not a unique symbol, so the published declarations and the sources stay one type.\n */\nexport type FencedPathId = string & { readonly __atomicFencedPath: true };\n\n/**\n * `serial`: the body runs as if it were the only writer of `domain`, or of the whole database when `domain` is absent:\n * `BEGIN IMMEDIATE` on SQLite, `BEGIN` plus that domain's transaction advisory lock on Postgres. Several prefixes may\n * share one database, so `domain` names the scope in full: a store passes one of its prefixed table names.\n * `fenced`: the body runs under READ COMMITTED and takes the row locks it relies on itself. With `excludesSerial`, it\n * also waits for and excludes `serial` transactions without a domain, as a `serial` transaction with a domain does,\n * for a body whose check a whole-database writer (such as snapshot garbage collection) could otherwise race\n * (`StorageDialect.lockClause`); `audit` names the reviewed path. Identical to `serial` on SQLite.\n */\nexport type TransactionConcurrency =\n\t| { readonly kind: \"serial\"; readonly domain?: string }\n\t| { readonly kind: \"fenced\"; readonly audit: FencedPathId; readonly excludesSerial?: boolean };\n\n/**\n * What a database's listening connection is doing: `listening`, notifications arrive; `connecting`, it is not known yet;\n * `unavailable`, none arrive, and pollers find the work: `pooler` when the endpoint is a transaction pooler (a\n * notification sent through the database did not reach the listening session), `connection-failed` when the listening\n * connection could not be opened or broke.\n */\nexport type StorageListenerState =\n\t| { readonly status: \"listening\" }\n\t| { readonly status: \"connecting\" }\n\t| { readonly status: \"unavailable\"; readonly reason: \"pooler\" | \"connection-failed\" };\n\n/**\n * `notification`: a transaction that ran `notify(channel, payload)` committed. `listening`: the listening connection\n * began listening again after it was unavailable, so notifications sent meanwhile were lost.\n */\nexport type StorageNotificationEvent =\n\t| { readonly kind: \"notification\"; readonly payload: string }\n\t| { readonly kind: \"listening\" };\n\nexport interface StorageNotificationSubscription {\n\t/** Stops delivering events to this listener; idempotent. */\n\tclose(): void;\n}\n\n/**\n * Wake-ups through the database (#5103): Postgres `LISTEN`/`NOTIFY`. A notification is only a hint that a poller would\n * find the same work at its next poll; notifications are lost while the listening connection is down, and through a\n * transaction pooler none arrive, so a store that sends them keeps its poll.\n */\nexport interface StorageNotifications {\n\t/**\n\t * A statement that sends `payload` to the listeners of `channel` when the transaction it runs in commits, and never\n\t * when it rolls back: run it in the transaction of the write it announces. `channel` is a name such as\n\t * `<prefix>pool_ready`; the database shortens a long one the same way for `notify` and `listen`.\n\t */\n\tnotify(channel: string, payload: string): SqliteStatement;\n\t/** Delivers `channel`'s events to `listener`, on one listening connection the database shares between channels. */\n\tlisten(channel: string, listener: (event: StorageNotificationEvent) => void): StorageNotificationSubscription;\n\t/** Opens the listening connection when it is not open, and resolves with its state once the first attempt settled. */\n\tstate(): Promise<StorageListenerState>;\n}\n\nexport interface SqliteDatabase extends SqliteExecutor {\n\t/**\n\t * True when the connection refuses writes, as `openNodeSqliteDatabase(path, { readOnly: true })` sets it, so opening a\n\t * session store skips a cleanup write that would fail. Optional: a read-only connection that leaves it unset still\n\t * opens a session store, whose failed cleanup is ignored.\n\t */\n\treadonly readOnly?: boolean;\n\treadonly descriptor: StorageDescriptor;\n\t/**\n\t * @internal Which database this handle reaches, for comparison only: two handles this process opened answer the same\n\t * string only when a transaction of either reads and writes the very tables the other does (the same adapter, server\n\t * or file, database, schema or namespace). Undefined, or absent, where that cannot be told, as for a database in\n\t * memory: such a handle is the same database as itself alone.\n\t */\n\tdatabaseIdentity?(): string | undefined;\n\t/** @internal Checks whether this embedded connection can prepare a JSONB extraction without issuing a read. */\n\tsupportsJsonbExtract?(): Promise<boolean>;\n\t/** The SQL dialect the database speaks; absent means SQLite. Read it through `dialectOf(database)`. */\n\treadonly dialect?: StorageDialect;\n\t/** Wake-ups through the database; present only on a database that delivers them (Postgres). */\n\treadonly notifications?: StorageNotifications;\n\t/**\n\t * The bytes this process may still write on the file system that holds the database's file (where a link to the file\n\t * points, and where its write-ahead log goes), as a SQLite or libSQL file database reports them. Absent, or resolving\n\t * undefined, when this process cannot see the database's disk (a server, memory) or the file system does not say.\n\t */\n\tfreeBytes?(): Promise<number | undefined>;\n\t/** @internal Run one short maintenance transaction only if this handle, its writer gate and the database lock\n\t * are immediately available. A backend without no-wait admission leaves this absent. */\n\ttryMaintenance?(callback: (transaction: SqliteExecutor) => Promise<void>): Promise<boolean>;\n\t/** Opens a separate handle on this same database for reads. It has its own call queue; the caller must close it. */\n\topenReader?(): Promise<SqliteDatabase>;\n\ttransaction<T>(\n\t\tcallback: (transaction: SqliteExecutor) => Promise<T>,\n\t\toptions?: SqliteTransactionOptions,\n\t): Promise<T>;\n\t/**\n\t * Runs the statements in order, in one write transaction, as one call to the database: all of them commit or none\n\t * do. Resolves with each statement's rows. Present only when the driver can send a batch in one request, which\n\t * saves a round trip per statement against a remote database.\n\t */\n\tbatch?(statements: readonly SqliteStatement[], options?: SqliteBatchOptions): Promise<SqliteRow[][]>;\n\tclose(): Promise<void>;\n}\n"]}
1
+ {"version":3,"file":"database.js","sourceRoot":"","sources":["../../../src/core/storage/database.ts"],"names":[],"mappings":"","sourcesContent":["import type { StorageDialect } from \"./dialect.js\";\n\nexport type SqliteValue = null | number | bigint | string | Uint8Array;\nexport type SqliteRow = Readonly<Record<string, SqliteValue>>;\n\nexport interface SqliteRunResult {\n\treadonly changes: number;\n}\n\nexport interface SqliteExecutor {\n\texec(sql: string): Promise<void>;\n\trun(sql: string, ...params: readonly SqliteValue[]): Promise<SqliteRunResult>;\n\tget<T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]): Promise<T | undefined>;\n\tall<T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]): Promise<T[]>;\n}\n\nexport interface StorageDescriptor {\n\treadonly adapter: string;\n\treadonly location: string;\n}\n\n/** One statement of a batch: SQL with positional `?` parameters. */\nexport interface SqliteStatement {\n\treadonly sql: string;\n\treadonly params: readonly SqliteValue[];\n}\n\n/** How a transaction takes its snapshot or write lock, and whether it may run again. */\nexport interface SqliteTransactionOptions {\n\t/** @internal A consistent read snapshot without a writer lock. The callback must only read. */\n\treadonly readOnly?: boolean;\n\t/**\n\t * How long the transaction keeps waiting for the write lock while it is held and no other connection commits,\n\t * instead of the connection's own lock wait. A writer whose work must not fail because another process stalled\n\t * with the lock held (starved of CPU, paused by garbage collection, stopped by a signal) waits longer: the holder\n\t * still commits or rolls back once it runs again. Adapters without a lock wait of their own ignore it.\n\t */\n\treadonly lockWaitMs?: number;\n\t/**\n\t * Lets a database from `createSqliteDatabase` run the callback again, in a new transaction, when a transient\n\t * failure (`StorageTransientError`) ended the transaction before it committed, so nothing of it was written. Set it\n\t * only for a callback that does nothing but use the transaction handle: anything else it does happens once per run.\n\t * Other databases ignore it.\n\t */\n\treadonly retryTransientFailures?: boolean;\n\t/**\n\t * How the transaction excludes other writers; `{ kind: \"serial\" }` when absent. SQLite runs every kind as\n\t * `BEGIN IMMEDIATE` unless `readOnly` is set; only a driver that runs transactions concurrently (Postgres) tells them apart.\n\t */\n\treadonly concurrency?: TransactionConcurrency;\n\t/**\n\t * @internal The statements the callback makes first, in this order, before it acts on any answer. A driver whose\n\t * transactions are pipelined sends them with the transaction's start, so they cost no round trip of their own, and\n\t * starts the callback once they are answered; each call of the callback that makes the next of them gets its answer.\n\t * Name only reads: a call that differs from the next of them ends the lead, and the answers of the rest go unused,\n\t * though they ran. A write may lead only as the callback's first call, made on every run whatever it reads, such as a\n\t * fenced path's one guarded write: it never runs unused. Other drivers ignore it.\n\t */\n\treadonly leading?: readonly SqliteStatement[];\n\t/**\n\t * @internal The callback makes the `leading` calls, all of them in order, and no other. A pipelined driver then sends\n\t * the commit right behind them, so the whole transaction costs one round trip: a call the callback makes after them\n\t * fails without being sent. When a leading statement fails, the transaction rolls back and the callback's call of\n\t * that statement fails. Other drivers ignore it.\n\t */\n\treadonly leadingOnly?: boolean;\n\t/**\n\t * @internal With `leading`, a `serial` transaction of a domain takes its locks in its first leading statement, a read,\n\t * and only when that read returns a row, instead of with its start: a transaction whose first read finds nothing\n\t * takes no lock. Every statement after it starts once the locks are held, so it sees every transaction that held them\n\t * and committed. A driver that ignores it takes the locks with the start. Other drivers ignore it.\n\t */\n\treadonly lockIfLeadingFinds?: boolean;\n}\n\n/** How one batch waits for a busy write lock, and whether it goes ahead of the database's queued calls. */\nexport interface SqliteBatchOptions {\n\t/**\n\t * How long a batch that found the database's write lock busy keeps sending again, with growing randomized waits\n\t * between tries. A busy batch wrote nothing, so sending it again is safe. Adapters without such a retry ignore it.\n\t */\n\treadonly lockWaitMs?: number;\n\t/**\n\t * Runs the batch before calls queued on this database that do not set it, and outside any limit the adapter puts on\n\t * concurrent writes: for small writes that must not wait behind others, such as a lease renewal.\n\t */\n\treadonly priority?: boolean;\n}\n\n/**\n * An audited fenced write path. Only `fencedPath(name)` in `fenced-paths.ts` makes one; a plain string is not one. The\n * brand is a string key, not a unique symbol, so the published declarations and the sources stay one type.\n */\nexport type FencedPathId = string & { readonly __atomicFencedPath: true };\n\n/**\n * `serial`: the body runs as if it were the only writer of `domain`, or of the whole database when `domain` is absent:\n * `BEGIN IMMEDIATE` on SQLite, `BEGIN` plus that domain's transaction advisory lock on Postgres. Several prefixes may\n * share one database, so `domain` names the scope in full: a store passes one of its prefixed table names.\n * `fenced`: the body runs under READ COMMITTED and takes the row locks it relies on itself. With `excludesSerial`, it\n * also waits for and excludes `serial` transactions without a domain, as a `serial` transaction with a domain does,\n * for a body whose check a whole-database writer (such as snapshot garbage collection) could otherwise race\n * (`StorageDialect.lockClause`); `audit` names the reviewed path. Identical to `serial` on SQLite.\n */\nexport type TransactionConcurrency =\n\t| { readonly kind: \"serial\"; readonly domain?: string }\n\t| { readonly kind: \"fenced\"; readonly audit: FencedPathId; readonly excludesSerial?: boolean };\n\n/**\n * What a database's listening connection is doing: `listening`, notifications arrive; `connecting`, it is not known yet;\n * `unavailable`, none arrive, and pollers find the work: `pooler` when the endpoint is a transaction pooler (a\n * notification sent through the database did not reach the listening session), `connection-failed` when the listening\n * connection could not be opened or broke.\n */\nexport type StorageListenerState =\n\t| { readonly status: \"listening\" }\n\t| { readonly status: \"connecting\" }\n\t| { readonly status: \"unavailable\"; readonly reason: \"pooler\" | \"connection-failed\" };\n\n/**\n * `notification`: a transaction that ran `notify(channel, payload)` committed. `listening`: the listening connection\n * began listening again after it was unavailable, so notifications sent meanwhile were lost.\n */\nexport type StorageNotificationEvent =\n\t| { readonly kind: \"notification\"; readonly payload: string }\n\t| { readonly kind: \"listening\" };\n\nexport interface StorageNotificationSubscription {\n\t/** Stops delivering events to this listener; idempotent. */\n\tclose(): void;\n}\n\n/**\n * Wake-ups through the database (#5103): Postgres `LISTEN`/`NOTIFY`. A notification is only a hint that a poller would\n * find the same work at its next poll; notifications are lost while the listening connection is down, and through a\n * transaction pooler none arrive, so a store that sends them keeps its poll.\n */\nexport interface StorageNotifications {\n\t/**\n\t * A statement that sends `payload` to the listeners of `channel` when the transaction it runs in commits, and never\n\t * when it rolls back: run it in the transaction of the write it announces. `channel` is a name such as\n\t * `<prefix>pool_ready`; the database shortens a long one the same way for `notify` and `listen`.\n\t */\n\tnotify(channel: string, payload: string): SqliteStatement;\n\t/** Delivers `channel`'s events to `listener`, on one listening connection the database shares between channels. */\n\tlisten(channel: string, listener: (event: StorageNotificationEvent) => void): StorageNotificationSubscription;\n\t/** Opens the listening connection when it is not open, and resolves with its state once the first attempt settled. */\n\tstate(): Promise<StorageListenerState>;\n}\n\n/**\n * @internal What a driver read of its schema in its open's own round trip (#6560): the rows of the catalog read\n * `readStorageSchemaCatalog` makes (`kind` `relation`, `trigger` or `column`, with `name` and `detail`) and the\n * versions `ledger` records, as rows of `domain` and `version`; `versions` is undefined when the ledger did not exist.\n */\nexport interface StorageOpenedCatalog {\n\treadonly ledger: string;\n\treadonly rows: readonly SqliteRow[];\n\treadonly versions: readonly SqliteRow[] | undefined;\n}\n\nexport interface SqliteDatabase extends SqliteExecutor {\n\t/**\n\t * True when the connection refuses writes, as `openNodeSqliteDatabase(path, { readOnly: true })` sets it, so opening a\n\t * session store skips a cleanup write that would fail. Optional: a read-only connection that leaves it unset still\n\t * opens a session store, whose failed cleanup is ignored.\n\t */\n\treadonly readOnly?: boolean;\n\treadonly descriptor: StorageDescriptor;\n\t/**\n\t * @internal Which database this handle reaches, for comparison only: two handles this process opened answer the same\n\t * string only when a transaction of either reads and writes the very tables the other does (the same adapter, server\n\t * or file, database, schema or namespace). Undefined, or absent, where that cannot be told, as for a database in\n\t * memory: such a handle is the same database as itself alone.\n\t */\n\tdatabaseIdentity?(): string | undefined;\n\t/** @internal Checks whether this embedded connection can prepare a JSONB extraction without issuing a read. */\n\tsupportsJsonbExtract?(): Promise<boolean>;\n\t/** The SQL dialect the database speaks; absent means SQLite. Read it through `dialectOf(database)`. */\n\treadonly dialect?: StorageDialect;\n\t/** Wake-ups through the database; present only on a database that delivers them (Postgres). */\n\treadonly notifications?: StorageNotifications;\n\t/**\n\t * The bytes this process may still write on the file system that holds the database's file (where a link to the file\n\t * points, and where its write-ahead log goes), as a SQLite or libSQL file database reports them. Absent, or resolving\n\t * undefined, when this process cannot see the database's disk (a server, memory) or the file system does not say.\n\t */\n\tfreeBytes?(): Promise<number | undefined>;\n\t/** @internal Run one short maintenance transaction only if this handle, its writer gate and the database lock\n\t * are immediately available. A backend without no-wait admission leaves this absent. */\n\ttryMaintenance?(callback: (transaction: SqliteExecutor) => Promise<void>): Promise<boolean>;\n\t/** Opens a separate handle on this same database for reads. It has its own call queue; the caller must close it. */\n\topenReader?(): Promise<SqliteDatabase>;\n\t/**\n\t * @internal The schema the driver read when it opened, given once: the first store open answers its schema checks\n\t * from it instead of reading the catalog again. Undefined after the first call, and where the driver read none.\n\t */\n\ttakeOpenedCatalog?(): StorageOpenedCatalog | undefined;\n\ttransaction<T>(\n\t\tcallback: (transaction: SqliteExecutor) => Promise<T>,\n\t\toptions?: SqliteTransactionOptions,\n\t): Promise<T>;\n\t/**\n\t * @internal Runs `statement` by itself as one request that commits on its own, queued in this process as a\n\t * transaction of `concurrency` is: behind the calls such a transaction waits for, and ahead of the calls that wait\n\t * for it. The statement takes on the server whatever locks it needs itself, such as a function that takes the\n\t * domain's advisory locks. A transient failure that applied nothing runs it again. Resolves with its rows. Present\n\t * only where the driver runs transactions concurrently (PostgreSQL).\n\t */\n\tautocommit?(statement: SqliteStatement, concurrency: TransactionConcurrency): Promise<SqliteRow[]>;\n\t/**\n\t * Runs the statements in order, in one write transaction, as one call to the database: all of them commit or none\n\t * do. Resolves with each statement's rows. Present only when the driver can send a batch in one request, which\n\t * saves a round trip per statement against a remote database.\n\t */\n\tbatch?(statements: readonly SqliteStatement[], options?: SqliteBatchOptions): Promise<SqliteRow[][]>;\n\tclose(): Promise<void>;\n}\n"]}
@@ -3,7 +3,7 @@ export { MemorySnapshotBlobStore, SqlSnapshotBlobStore, snapshotIndexTables } fr
3
3
  export type { SnapshotBlob, SnapshotBlobStore } from "../worktree-snapshot/types.ts";
4
4
  /** @internal How a transaction of a pipelined connection sends its last writes with its commit (#6560). */
5
5
  export { transactionFinisher } from "./added-exports.js";
6
- export type { FencedPathId, SqliteBatchOptions, SqliteDatabase, SqliteExecutor, SqliteRow, SqliteRunResult, SqliteStatement, SqliteTransactionOptions, SqliteValue, StorageDescriptor, StorageListenerState, StorageNotificationEvent, StorageNotificationSubscription, StorageNotifications, TransactionConcurrency, } from "./database.js";
6
+ export type { FencedPathId, SqliteBatchOptions, SqliteDatabase, SqliteExecutor, SqliteRow, SqliteRunResult, SqliteStatement, SqliteTransactionOptions, SqliteValue, StorageDescriptor, StorageListenerState, StorageNotificationEvent, StorageNotificationSubscription, StorageNotifications, StorageOpenedCatalog, TransactionConcurrency, } from "./database.js";
7
7
  export * from "./dialect.js";
8
8
  export * from "./errors.js";
9
9
  export * from "./fenced-paths.js";
@@ -40,7 +40,7 @@ function __atomicOnDemandFailed(error, feature) {
40
40
  return (async () => {
41
41
  const root = new URL("../../", import.meta.url);
42
42
  const releases = (globalThis[Symbol.for("atomic.in-place-update-release.v1")] ??= new Map());
43
- const key = `${root.href}#0.10.11-alpha.1`;
43
+ const key = `${root.href}#0.10.11-alpha.2`;
44
44
  let release = releases.get(key);
45
45
  if (release === undefined) {
46
46
  const current = (async () => {
@@ -68,7 +68,7 @@ function __atomicOnDemandFailed(error, feature) {
68
68
  } catch {
69
69
  // No installation to read, as in a bundle of the package: the release the process runs decides.
70
70
  }
71
- const updatedTo = typeof installed === "string" && installed !== "0.10.11-alpha.1" ? installed : running !== undefined && running.version !== "0.10.11-alpha.1" ? "0.10.11-alpha.1" : undefined;
71
+ const updatedTo = typeof installed === "string" && installed !== "0.10.11-alpha.2" ? installed : running !== undefined && running.version !== "0.10.11-alpha.2" ? "0.10.11-alpha.2" : undefined;
72
72
  if (updatedTo === undefined) throw error;
73
73
  const application = typeof running?.name === "string" ? running.name : "atomic";
74
74
  const restart = new Error(`${application} was updated to ${updatedTo} while this session was running; restart it to keep using ${feature}.`, {
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/core/storage/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AAExH,2GAA2G;AAC3G,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAkBzD,cAAc,cAAc,CAAC;AAC7B,cAAc,aAAa,CAAC;AAC5B,cAAc,mBAAmB,CAAC;AAClC,OAAO,EACN,mBAAmB,EACnB,wBAAwB,EACxB,0BAA0B,EAC1B,+BAA+B,EAC/B,wBAAwB,EACxB,6BAA6B,EAC7B,aAAa,EACb,kBAAkB,EAElB,aAAa,EACb,kBAAkB,EAClB,cAAc,EACd,mBAAmB,EACnB,kBAAkB,EAClB,uBAAuB,EACvB,mBAAmB,EACnB,wBAAwB,GACxB,MAAM,oBAAoB,CAAC;AAC5B,cAAc,iBAAiB,CAAC;AAChC,OAAO,EACN,4BAA4B,EAC5B,yBAAyB,EACzB,mBAAmB,EACnB,sBAAsB,EACtB,cAAc,EAEd,sBAAsB,GACtB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACN,2CAA2C,EAC3C,kCAAkC,EAClC,oCA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AC,CAAC,MAAM,MAAM,CAAC,4BAA4B,CAAC,CAAC,CAAC,kBAAkB,CAAC,GAAG,IAAI,CAAC,CAAC;AACjF,CAAC;AACD,MAAM,CAAC,KAAK,SAAS,CAAC,CAAC,wBAAwB,CAC9C,GAAG,IAAsF;IAEzF,KAAK,CAAC,CAAC,CAAC,MAAM,MAAM,CAAC,4BAA4B,CAAC,CAAC,CAAC,wBAAwB,CAAC,GAAG,IAAI,CAAC,CAAC;AACvF,CAAC;AAiCD,cAAc,oBAAoB,CAAC;AAanC,OAAO,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC","sourcesContent":["export type { SnapshotIndexTables } from \"../worktree-snapshot/blob-store.ts\";\nexport { MemorySnapshotBlobStore, SqlSnapshotBlobStore, snapshotIndexTables } from \"../worktree-snapshot/blob-store.ts\";\nexport type { SnapshotBlob, SnapshotBlobStore } from \"../worktree-snapshot/types.ts\";\n/** @internal How a transaction of a pipelined connection sends its last writes with its commit (#6560). */\nexport { transactionFinisher } from \"./added-exports.js\";\nexport type {\n\tFencedPathId,\n\tSqliteBatchOptions,\n\tSqliteDatabase,\n\tSqliteExecutor,\n\tSqliteRow,\n\tSqliteRunResult,\n\tSqliteStatement,\n\tSqliteTransactionOptions,\n\tSqliteValue,\n\tStorageDescriptor,\n\tStorageListenerState,\n\tStorageNotificationEvent,\n\tStorageNotificationSubscription,\n\tStorageNotifications,\n\tTransactionConcurrency,\n} from \"./database.js\";\nexport * from \"./dialect.js\";\nexport * from \"./errors.js\";\nexport * from \"./fenced-paths.js\";\nexport {\n\tclaimFileAtomically,\n\tclaimFileAtomicallyAsync,\n\tdefaultSessionDatabasePath,\n\tdefaultSessionDatabasePathAsync,\n\tdefaultSharedStoragePath,\n\tdefaultSharedStoragePathAsync,\n\treadClaimFile,\n\treadClaimFileAsync,\n\ttype StorageHomeSettings,\n\tsameDirectory,\n\tsameDirectoryAsync,\n\tstorageHomeDir,\n\tstorageHomeDirAsync,\n\tstoragePathBaseDir,\n\tstoragePathBaseDirAsync,\n\tworkflowsStorageDir,\n\tworkflowsStorageDirAsync,\n} from \"./file-identity.js\";\nexport * from \"./migrations.js\";\nexport {\n\tDEFAULT_GROUP_COMMIT_HOLD_MS,\n\tgetWriterQueueDegradation,\n\tgetWriterQueueStats,\n\topenNodeSqliteDatabase,\n\tsqliteFilePath,\n\ttype WriterQueueStats,\n\twrapNodeSqliteDatabase,\n} from \"./node-sqlite.js\";\nexport {\n\tPOSTGRES_HASHED_STORAGE_IDENTIFIER_SUFFIXES,\n\tPOSTGRES_MAX_STORAGE_PREFIX_LENGTH,\n\tPOSTGRES_STORAGE_IDENTIFIER_SUFFIXES,\n\trenderStorageIdentifiers,\n\tstorageMigrationTable,\n\tvalidateStoragePrefix,\n} from \"./prefix.js\";\nexport * from \"./provider.js\";\nexport { assertStorageSchemaVersion, assertStoredSchemaVersion } from \"./schema.js\";\nexport * from \"./schema-catalog.js\";\nexport {\n\tgetTeamProfile,\n\ttype InMemorySecretRef,\n\tinMemorySecret,\n\tisPostgresUrl,\n\tjoinTeam,\n\tLIBSQL_ADAPTER_PACKAGE,\n\tLOCAL_SESSIONS_STORAGE,\n\tleaveTeam,\n\tPOSTGRES_ADAPTER_PACKAGE,\n\tREDACTED_SECRET,\n\ttype StorageInputSelection,\n\ttype StorageSettingsSelection,\n\tselectStorage,\n\tselectStorageAsync,\n\tTEAM_PREFIX_ENV,\n\tTEAM_PROFILE_ENV,\n\tTEAM_TOKEN_ENV,\n\tTEAM_TOKEN_FILE_ENV,\n\tTEAM_URL_ENV,\n\ttype TeamProfileSelectionOptions,\n\ttype TeamStorageSelection,\n\tteamProfileSelection,\n} from \"./selection.js\";\nexport type { ExpandedChildCall, ExpandedChildDetails } from \"./session/expanded-child-details.js\";\nexport async function readExpandedChildDetails(\n\t...args: Parameters<typeof import(\"./session/expanded-child-details.js\").readExpandedChildDetails>\n) {\n\treturn (await import(\"./session/expanded-child-details.js\")).readExpandedChildDetails(...args);\n}\nexport async function readSavedChildLaunch(\n\t...args: Parameters<typeof import(\"./session/expanded-child-details.js\").readSavedChildLaunch>\n) {\n\treturn (await import(\"./session/expanded-child-details.js\")).readSavedChildLaunch(...args);\n}\nexport async function readSessionChildCatalog(\n\t...args: Parameters<typeof import(\"./session/child-reader.js\").readSessionChildCatalog>\n) {\n\treturn (await import(\"./session/child-reader.js\")).readSessionChildCatalog(...args);\n}\nexport async function findInSessionHistory(\n\t...args: Parameters<typeof import(\"./session/history-pages.js\").findInSessionHistory>\n) {\n\treturn (await import(\"./session/history-pages.js\")).findInSessionHistory(...args);\n}\n// Ordinary storage setup does not open a transcript reader or import its encoders.\nexport async function* readSessionHistory(\n\t...args: Parameters<typeof import(\"./session/history-pages.js\").readSessionHistory>\n) {\n\tyield* (await import(\"./session/history-pages.js\")).readSessionHistory(...args);\n}\nexport async function* readSessionHistoryChunks(\n\t...args: Parameters<typeof import(\"./session/history-pages.js\").readSessionHistoryChunks>\n) {\n\tyield* (await import(\"./session/history-pages.js\")).readSessionHistoryChunks(...args);\n}\nexport type {\n\tArchivedChildCatalogEntry,\n\tOversizedSessionEntry,\n\tSessionBlob,\n\tSessionCompactionPoint,\n\tSessionEntriesPage,\n\tSessionEntriesQuery,\n\tSessionEntryAt,\n\tSessionEntryRange,\n\tSessionEntrySizes,\n\tSessionForkWindow,\n\tSessionHistoryItem,\n\tSessionHistoryPage,\n\tSessionHistoryReadOptions,\n\tSessionHistoryTotals,\n\tSessionRecoveryState,\n\tSessionResume,\n\tSessionResumeRetainedSetting,\n\tSessionResumeRetainedSettings,\n\tSessionSearchCoverage,\n\tSessionSearchExtendOptions,\n\tSessionSearchIndex,\n\tSessionSearchText,\n\tSessionStateEntry,\n\tSessionStore,\n\tSessionStoredEntry,\n\tSessionTail,\n\tSessionTaskReferenceCandidate,\n\tSessionTaskReferenceDuplicatePage,\n\tSessionTaskReferenceDuplicateQuery,\n\tSessionUsageTotals,\n} from \"./session/types.js\";\nexport * from \"./sqlite-facade.js\";\nexport type {\n\tJoinTeamOptions,\n\tLeaveTeamOptions,\n\tTeamBrokerRestart,\n\tTeamJoinResult,\n\tTeamKeptSetting,\n\tTeamLeaveResult,\n\tTeamProfile,\n\tTeamProfileName,\n\tTeamProfileOptions,\n\tTeamSettingKey,\n} from \"./team.js\";\nexport { switchToWriteAheadLog } from \"./write-ahead-log.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/core/storage/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AAExH,2GAA2G;AAC3G,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAmBzD,cAAc,cAAc,CAAC;AAC7B,cAAc,aAAa,CAAC;AAC5B,cAAc,mBAAmB,CAAC;AAClC,OAAO,EACN,mBAAmB,EACnB,wBAAwB,EACxB,0BAA0B,EAC1B,+BAA+B,EAC/B,wBAAwB,EACxB,6BAA6B,EAC7B,aAAa,EACb,kBAAkB,EAElB,aAAa,EACb,kBAAkB,EAClB,cAAc,EACd,mBAAmB,EACnB,kBAAkB,EAClB,uBAAuB,EACvB,mBAAmB,EACnB,wBAAwB,GACxB,MAAM,oBAAoB,CAAC;AAC5B,cAAc,iBAAiB,CAAC;AAChC,OAAO,EACN,4BAA4B,EAC5B,yBAAyB,EACzB,mBAAmB,EACnB,sBAAsB,EACtB,cAAc,EAEd,sBAAsB,GACtB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACN,2CAA2C,EAC3C,kCAAkC,EAClC,oCAAoC,EACpC,wBAAwB,EACxB,qBAAqB,EACrB,qBAAqB,GACrB,MAAM,aAAa,CAAC;AACrB,cAAc,eAAe,CAAC;AAC9B,OAAO,EAAE,0BAA0B,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AACpF,cAAc,qBAAqB,CAAC;AACpC,OAAO,EACN,cAAc,EAEd,cAAc,EACd,aAAa,EACb,QAAQ,EACR,sB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AwB,CAAC,GAAG,IAAI,CAAC,CAAC;AACvF,CAAC;AAiCD,cAAc,oBAAoB,CAAC;AAanC,OAAO,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC","sourcesContent":["export type { SnapshotIndexTables } from \"../worktree-snapshot/blob-store.ts\";\nexport { MemorySnapshotBlobStore, SqlSnapshotBlobStore, snapshotIndexTables } from \"../worktree-snapshot/blob-store.ts\";\nexport type { SnapshotBlob, SnapshotBlobStore } from \"../worktree-snapshot/types.ts\";\n/** @internal How a transaction of a pipelined connection sends its last writes with its commit (#6560). */\nexport { transactionFinisher } from \"./added-exports.js\";\nexport type {\n\tFencedPathId,\n\tSqliteBatchOptions,\n\tSqliteDatabase,\n\tSqliteExecutor,\n\tSqliteRow,\n\tSqliteRunResult,\n\tSqliteStatement,\n\tSqliteTransactionOptions,\n\tSqliteValue,\n\tStorageDescriptor,\n\tStorageListenerState,\n\tStorageNotificationEvent,\n\tStorageNotificationSubscription,\n\tStorageNotifications,\n\tStorageOpenedCatalog,\n\tTransactionConcurrency,\n} from \"./database.js\";\nexport * from \"./dialect.js\";\nexport * from \"./errors.js\";\nexport * from \"./fenced-paths.js\";\nexport {\n\tclaimFileAtomically,\n\tclaimFileAtomicallyAsync,\n\tdefaultSessionDatabasePath,\n\tdefaultSessionDatabasePathAsync,\n\tdefaultSharedStoragePath,\n\tdefaultSharedStoragePathAsync,\n\treadClaimFile,\n\treadClaimFileAsync,\n\ttype StorageHomeSettings,\n\tsameDirectory,\n\tsameDirectoryAsync,\n\tstorageHomeDir,\n\tstorageHomeDirAsync,\n\tstoragePathBaseDir,\n\tstoragePathBaseDirAsync,\n\tworkflowsStorageDir,\n\tworkflowsStorageDirAsync,\n} from \"./file-identity.js\";\nexport * from \"./migrations.js\";\nexport {\n\tDEFAULT_GROUP_COMMIT_HOLD_MS,\n\tgetWriterQueueDegradation,\n\tgetWriterQueueStats,\n\topenNodeSqliteDatabase,\n\tsqliteFilePath,\n\ttype WriterQueueStats,\n\twrapNodeSqliteDatabase,\n} from \"./node-sqlite.js\";\nexport {\n\tPOSTGRES_HASHED_STORAGE_IDENTIFIER_SUFFIXES,\n\tPOSTGRES_MAX_STORAGE_PREFIX_LENGTH,\n\tPOSTGRES_STORAGE_IDENTIFIER_SUFFIXES,\n\trenderStorageIdentifiers,\n\tstorageMigrationTable,\n\tvalidateStoragePrefix,\n} from \"./prefix.js\";\nexport * from \"./provider.js\";\nexport { assertStorageSchemaVersion, assertStoredSchemaVersion } from \"./schema.js\";\nexport * from \"./schema-catalog.js\";\nexport {\n\tgetTeamProfile,\n\ttype InMemorySecretRef,\n\tinMemorySecret,\n\tisPostgresUrl,\n\tjoinTeam,\n\tLIBSQL_ADAPTER_PACKAGE,\n\tLOCAL_SESSIONS_STORAGE,\n\tleaveTeam,\n\tPOSTGRES_ADAPTER_PACKAGE,\n\tREDACTED_SECRET,\n\ttype StorageInputSelection,\n\ttype StorageSettingsSelection,\n\tselectStorage,\n\tselectStorageAsync,\n\tTEAM_PREFIX_ENV,\n\tTEAM_PROFILE_ENV,\n\tTEAM_TOKEN_ENV,\n\tTEAM_TOKEN_FILE_ENV,\n\tTEAM_URL_ENV,\n\ttype TeamProfileSelectionOptions,\n\ttype TeamStorageSelection,\n\tteamProfileSelection,\n} from \"./selection.js\";\nexport type { ExpandedChildCall, ExpandedChildDetails } from \"./session/expanded-child-details.js\";\nexport async function readExpandedChildDetails(\n\t...args: Parameters<typeof import(\"./session/expanded-child-details.js\").readExpandedChildDetails>\n) {\n\treturn (await import(\"./session/expanded-child-details.js\")).readExpandedChildDetails(...args);\n}\nexport async function readSavedChildLaunch(\n\t...args: Parameters<typeof import(\"./session/expanded-child-details.js\").readSavedChildLaunch>\n) {\n\treturn (await import(\"./session/expanded-child-details.js\")).readSavedChildLaunch(...args);\n}\nexport async function readSessionChildCatalog(\n\t...args: Parameters<typeof import(\"./session/child-reader.js\").readSessionChildCatalog>\n) {\n\treturn (await import(\"./session/child-reader.js\")).readSessionChildCatalog(...args);\n}\nexport async function findInSessionHistory(\n\t...args: Parameters<typeof import(\"./session/history-pages.js\").findInSessionHistory>\n) {\n\treturn (await import(\"./session/history-pages.js\")).findInSessionHistory(...args);\n}\n// Ordinary storage setup does not open a transcript reader or import its encoders.\nexport async function* readSessionHistory(\n\t...args: Parameters<typeof import(\"./session/history-pages.js\").readSessionHistory>\n) {\n\tyield* (await import(\"./session/history-pages.js\")).readSessionHistory(...args);\n}\nexport async function* readSessionHistoryChunks(\n\t...args: Parameters<typeof import(\"./session/history-pages.js\").readSessionHistoryChunks>\n) {\n\tyield* (await import(\"./session/history-pages.js\")).readSessionHistoryChunks(...args);\n}\nexport type {\n\tArchivedChildCatalogEntry,\n\tOversizedSessionEntry,\n\tSessionBlob,\n\tSessionCompactionPoint,\n\tSessionEntriesPage,\n\tSessionEntriesQuery,\n\tSessionEntryAt,\n\tSessionEntryRange,\n\tSessionEntrySizes,\n\tSessionForkWindow,\n\tSessionHistoryItem,\n\tSessionHistoryPage,\n\tSessionHistoryReadOptions,\n\tSessionHistoryTotals,\n\tSessionRecoveryState,\n\tSessionResume,\n\tSessionResumeRetainedSetting,\n\tSessionResumeRetainedSettings,\n\tSessionSearchCoverage,\n\tSessionSearchExtendOptions,\n\tSessionSearchIndex,\n\tSessionSearchText,\n\tSessionStateEntry,\n\tSessionStore,\n\tSessionStoredEntry,\n\tSessionTail,\n\tSessionTaskReferenceCandidate,\n\tSessionTaskReferenceDuplicatePage,\n\tSessionTaskReferenceDuplicateQuery,\n\tSessionUsageTotals,\n} from \"./session/types.js\";\nexport * from \"./sqlite-facade.js\";\nexport type {\n\tJoinTeamOptions,\n\tLeaveTeamOptions,\n\tTeamBrokerRestart,\n\tTeamJoinResult,\n\tTeamKeptSetting,\n\tTeamLeaveResult,\n\tTeamProfile,\n\tTeamProfileName,\n\tTeamProfileOptions,\n\tTeamSettingKey,\n} from \"./team.js\";\nexport { switchToWriteAheadLog } from \"./write-ahead-log.js\";\n"]}
@@ -20,6 +20,13 @@ export interface StorageMigrationOptions {
20
20
  * them still reads and writes it correctly (#5065).
21
21
  */
22
22
  readonly acceptNewer?: boolean;
23
+ /**
24
+ * A recorded version above the last step and at most this one is accepted, and nothing runs; a newer one is still
25
+ * refused. For versions that only an explicit command records, never a migration this call would run: the sessions
26
+ * domain's version 3, which turns on forks that share their parent's history (#6560), and which builds that do not
27
+ * list it refuse.
28
+ */
29
+ readonly recordedThrough?: number;
23
30
  }
24
31
  export interface StorageMigrationResult {
25
32
  /** The versions this call ran, in order. */
@@ -73,7 +80,8 @@ export interface StorageSchemaSetup {
73
80
  /**
74
81
  * Whether the catalog an open in progress read (`withStorageSchemaCatalog`) records `schema.revision` for the
75
82
  * store already, so {@link ensureStorageSchema} would run nothing: the store's open then skips its schema transaction
76
- * and its lock (#6560). False outside such an open, on SQLite, and when the revision is not recorded.
83
+ * and its lock (#6560). On SQLite and libSQL the store's schema stamp records it, and only while nothing changed the
84
+ * schema since (`sqliteSchemaStampTable`). False outside such an open, and when the revision is not recorded.
77
85
  */
78
86
  export declare function storageSchemaCurrent(database: SqliteDatabase, schema: StorageSchemaSetup): Promise<boolean>;
79
87
  /**
@@ -82,8 +90,9 @@ export declare function storageSchemaCurrent(database: SqliteDatabase, schema: S
82
90
  * database with versioned migrations (PostgreSQL) a current schema runs no DDL at all, so a runtime role with only DML
83
91
  * privileges opens it; a schema that is behind runs `setup` under the store's advisory lock, then records the revision,
84
92
  * so concurrent processes set it up once. A role that may not run the DDL then fails with
85
- * `StorageConfigError` reason `missing-privilege` from the adapter. On SQLite, which records no ledger, `setup` runs
86
- * every time, as before.
93
+ * `StorageConfigError` reason `missing-privilege` from the adapter. On SQLite and libSQL, which keep no ledger, `setup`
94
+ * runs every time it is called, as before, and then stamps the store with the schema version the transaction leaves,
95
+ * which {@link storageSchemaCurrent} believes until the schema changes again (#6560).
87
96
  */
88
97
  export declare function ensureStorageSchema(executor: SqliteExecutor, dialect: StorageDialect, schema: StorageSchemaSetup, setup: () => Promise<void>): Promise<void>;
89
98
  /** What {@link ensureTableFillfactor} sets, and records under `schema:<domain>` in the ledger. */
@@ -1,6 +1,10 @@
1
1
  import { dialectOf } from "./dialect.js";
2
2
  import { StorageConfigError, StorageSchemaVersionError } from "./errors.js";
3
- import { schemaCatalogOf } from "./schema-catalog.js";
3
+ import { recordSqliteSchemaStamps, schemaCatalogOf, sqliteSchemaStampsOf } from "./schema-catalog.js";
4
+ /** Whether a recorded `version` above the last step, `supported`, is accepted under `options` instead of refused. */
5
+ function acceptsRecorded(version, supported, options) {
6
+ return version <= supported || options.acceptNewer === true || version <= (options.recordedThrough ?? supported);
7
+ }
4
8
  const DEFAULT_MIGRATION_TABLE = "atomic_migrations";
5
9
  function checkSteps(steps) {
6
10
  let previous = 0;
@@ -51,11 +55,11 @@ async function recordedVersion(executor, dialect, table, domain) {
51
55
  const row = await executor.get(`SELECT MAX(version) AS version FROM ${table} WHERE domain = ?`, domain);
52
56
  return Number(row?.version ?? 0);
53
57
  }
54
- async function applyVersioned(transaction, dialect, table, domain, steps, acceptNewer = false) {
58
+ async function applyVersioned(transaction, dialect, table, domain, steps, options = {}) {
55
59
  const current = await recordedVersion(transaction, dialect, table, domain);
56
60
  const supported = steps.at(-1)?.version ?? 0;
57
61
  if (current > supported) {
58
- if (acceptNewer)
62
+ if (acceptsRecorded(current, supported, options))
59
63
  return { applied: [], version: current };
60
64
  throw new StorageSchemaVersionError(domain, current, supported);
61
65
  }
@@ -86,13 +90,13 @@ export async function applyStorageMigrations(database, domain, steps, options =
86
90
  const recorded = dialect.versionedMigrations ? await recordedInCatalog(database, table, domain) : undefined;
87
91
  const supported = steps.at(-1)?.version ?? 0;
88
92
  if (recorded !== undefined && recorded >= supported && supported > 0) {
89
- if (recorded > supported && !options.acceptNewer)
93
+ if (!acceptsRecorded(recorded, supported, options))
90
94
  throw new StorageSchemaVersionError(domain, recorded, supported);
91
95
  return { applied: [], version: recorded };
92
96
  }
93
97
  return database.transaction(async (transaction) => {
94
98
  if (dialect.versionedMigrations)
95
- return applyVersioned(transaction, dialect, table, domain, steps, options.acceptNewer);
99
+ return applyVersioned(transaction, dialect, table, domain, steps, options);
96
100
  for (const step of steps)
97
101
  await step.up(transaction, dialect);
98
102
  return { applied: steps.map((step) => step.version), version: steps.at(-1)?.version ?? 0 };
@@ -187,13 +191,19 @@ async function underShortLockWaits(executor, setup) {
187
191
  /**
188
192
  * Whether the catalog an open in progress read (`withStorageSchemaCatalog`) records `schema.revision` for the
189
193
  * store already, so {@link ensureStorageSchema} would run nothing: the store's open then skips its schema transaction
190
- * and its lock (#6560). False outside such an open, on SQLite, and when the revision is not recorded.
194
+ * and its lock (#6560). On SQLite and libSQL the store's schema stamp records it, and only while nothing changed the
195
+ * schema since (`sqliteSchemaStampTable`). False outside such an open, and when the revision is not recorded.
191
196
  */
192
197
  export async function storageSchemaCurrent(database, schema) {
193
- if (!dialectOf(database).versionedMigrations)
198
+ const dialect = dialectOf(database);
199
+ const key = `schema:${schema.domain}`;
200
+ if (dialect.versionedMigrations) {
201
+ const recorded = await recordedInCatalog(database, schema.ledger, key);
202
+ return recorded !== undefined && recorded >= schema.revision;
203
+ }
204
+ if (dialect.name !== "sqlite")
194
205
  return false;
195
- const recorded = await recordedInCatalog(database, schema.ledger, `schema:${schema.domain}`);
196
- return recorded !== undefined && recorded >= schema.revision;
206
+ return ((await sqliteSchemaStampsOf(database, schema.ledger))?.get(key) ?? 0) >= schema.revision;
197
207
  }
198
208
  /**
199
209
  * Runs `setup`, a store's idempotent schema statements (`CREATE … IF NOT EXISTS`, guarded `ALTER TABLE … ADD COLUMN`),
@@ -201,12 +211,15 @@ export async function storageSchemaCurrent(database, schema) {
201
211
  * database with versioned migrations (PostgreSQL) a current schema runs no DDL at all, so a runtime role with only DML
202
212
  * privileges opens it; a schema that is behind runs `setup` under the store's advisory lock, then records the revision,
203
213
  * so concurrent processes set it up once. A role that may not run the DDL then fails with
204
- * `StorageConfigError` reason `missing-privilege` from the adapter. On SQLite, which records no ledger, `setup` runs
205
- * every time, as before.
214
+ * `StorageConfigError` reason `missing-privilege` from the adapter. On SQLite and libSQL, which keep no ledger, `setup`
215
+ * runs every time it is called, as before, and then stamps the store with the schema version the transaction leaves,
216
+ * which {@link storageSchemaCurrent} believes until the schema changes again (#6560).
206
217
  */
207
218
  export async function ensureStorageSchema(executor, dialect, schema, setup) {
208
219
  if (!dialect.versionedMigrations) {
209
220
  await setup();
221
+ if (dialect.name === "sqlite")
222
+ await recordSqliteSchemaStamps(executor, [schema]);
210
223
  return;
211
224
  }
212
225
  const { ledger, domain, revision } = schema;
@@ -1 +1 @@
1
- {"version":3,"file":"migrations.js","sourceRoot":"","sources":["../../../src/core/storage/migrations.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAuB,MAAM,cAAc,CAAC;AAC9D,OAAO,EAAE,kBAAkB,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AAC5E,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAgCtD,MAAM,uBAAuB,GAAG,mBAAmB,CAAC;AAEpD,SAAS,UAAU,CAAC,KAAsC;IACzD,IAAI,QAAQ,GAAG,CAAC,CAAC;IACjB,KAAK,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;AAED,uGAAuG;AACvG,KAAK,UAAU,WAAW,CAAC,QAAwB,EAAE,OAAuB,EAAE,KAAa;IAC1F,MAAM,KAAK,GAAG,OAAO,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;IACzC,OAAO,CAAC,MAAM,QAAQ,CAAC,GAAG,CAAC,KAAK,CAAC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CAAC;IAC5C,IAAI,MAAM,oBAAoB,CAAC,QAAQ,EAAE,MAAM,CAAC;QAAE,OAAO;IACzD,MAAM,KAAK,GAAG,MAAM,QAAQ,CAAC,GAAG,CAC/B;;qGAEmG,EACnG,OAAO,CAAC,UAAU,CAAC,KAAK,CAAC,CACzB,CAAC;IACF,MAAM,GAAG,GAAG,CAAC,KAAmC,EAAE,EAAE,CAAC,KAAK,KAAK,IAAI,IAAI,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IAC3F,IAAI,KAAK,KAAK,SAAS,IAAI,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC;QAAE,OAAO;IACzE,MAAM,QAAQ,CAAC,WAAW,CACzB,CAAC,EAAE,EAAE,EAAE,CACN,mBAAmB,CAAC,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,IAAI,EAAE;QACnD,MAAM,EAAE,CAAC,IAAI,CAAC,eAAe,KAAK,sBAAsB,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;IACpF,CAAC,CAAC,EACH,EAAE,sBAAsB,EAAE,IAAI,EAAE,WAAW,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,CACjF,CAAC;AACH,CAAC","sourcesContent":["import type { SqliteDatabase, SqliteExecutor, SqliteRow } from \"./database.js\";\nimport { dialectOf, type StorageDialect } from \"./dialect.js\";\nimport { StorageConfigError, StorageSchemaVersionError } from \"./errors.js\";\nimport { schemaCatalogOf } from \"./schema-catalog.js\";\n\n/** One version of a domain's schema. */\nexport interface StorageMigrationStep {\n\t/** A positive integer; a domain's steps are listed in increasing order. */\n\treadonly version: number;\n\t/**\n\t * Brings the schema from the previous version to this one. It may use only `transaction`: the runner may run the\n\t * whole migration again after a transient failure. On a dialect without `versionedMigrations` (SQLite) every step\n\t * runs each time, so its statements must be idempotent (`CREATE … IF NOT EXISTS`).\n\t */\n\tup(transaction: SqliteExecutor, dialect: StorageDialect): Promise<void>;\n}\n\nexport interface StorageMigrationOptions {\n\t/** The ledger table, already prefixed (`renderStorageIdentifiers`); default `atomic_migrations`. */\n\treadonly table?: string;\n\t/**\n\t * A recorded version newer than the last step is accepted, and nothing runs, instead of refusing with\n\t * `StorageSchemaVersionError`. Only for a domain whose later steps stay additive, so a build that knows fewer of\n\t * them still reads and writes it correctly (#5065).\n\t */\n\treadonly acceptNewer?: boolean;\n}\n\nexport interface StorageMigrationResult {\n\t/** The versions this call ran, in order. */\n\treadonly applied: readonly number[];\n\t/** The domain's schema version after the call. */\n\treadonly version: number;\n}\n\nconst DEFAULT_MIGRATION_TABLE = \"atomic_migrations\";\n\nfunction checkSteps(steps: readonly StorageMigrationStep[]): void {\n\tlet previous = 0;\n\tfor (const step of steps) {\n\t\tif (!Number.isSafeInteger(step.version) || step.version <= previous)\n\t\t\tthrow new StorageConfigError(\n\t\t\t\t\"sdk\",\n\t\t\t\t\"steps\",\n\t\t\t\t\"versions-increasing\",\n\t\t\t\t\"Number migration steps 1, 2, 3, … in increasing order\",\n\t\t\t);\n\t\tprevious = step.version;\n\t}\n}\n\n/** Whether `table` exists, read from the catalog: no DDL, so a role without CREATE can ask (#5218). */\nasync function tableExists(executor: SqliteExecutor, dialect: StorageDialect, table: string): Promise<boolean> {\n\tconst probe = dialect.tableExists(table);\n\treturn (await executor.get(probe.sql, ...probe.params)) !== undefined;\n}\n\n/**\n * Refuses, before any DDL, a role that cannot use the schema the database runs in: the setup would fail with a bare\n * `3F000` or `42501` that names neither the grant nor the role (#5218). PostgreSQL only.\n */\nasync function assertSchemaUsage(executor: SqliteExecutor, dialect: StorageDialect): Promise<void> {\n\tif (dialect.name !== \"postgres\") return;\n\tconst access = await executor.get<SqliteRow & { schema: string; role: string; present: number; usage: number }>(\n\t\t`SELECT s.name AS schema, current_user AS role, (n.oid IS NOT NULL)::int AS present,\n\t\t\tcoalesce(has_schema_privilege(n.oid, 'USAGE'), false)::int AS usage\n\t\tFROM (SELECT trim(both '\"' from split_part(current_setting('search_path'), ',', 1)) AS name) s\n\t\tLEFT JOIN pg_catalog.pg_namespace n ON n.nspname = s.name`,\n\t);\n\tif (access === undefined || Number(access.present) === 0 || Number(access.usage) === 1) return;\n\tthrow new StorageConfigError(\n\t\t\"sdk\",\n\t\t\"privileges\",\n\t\t\"missing-privilege\",\n\t\t`Role \"${access.role}\" has no USAGE on schema ${access.schema}, so it can neither find Atomic's tables there nor create them. Grant it as the schema's owner: GRANT USAGE ON SCHEMA ${access.schema} TO \"${access.role}\"; and, for a runtime role, the table grants in \"Set up the database\" in docs/storage.md`,\n\t);\n}\n\n/** Creates the ledger `table` unless it exists, so a current schema runs no DDL (#5218). */\nasync function createLedger(executor: SqliteExecutor, dialect: StorageDialect, table: string): Promise<void> {\n\tif (await tableExists(executor, dialect, table)) return;\n\tawait assertSchemaUsage(executor, dialect);\n\t// Two stores that set up their schemas at once never race to create the ledger they share.\n\tif (dialect.name === \"postgres\") {\n\t\tawait executor.get(\"SELECT pg_advisory_xact_lock(hashtextextended(?, 0)) AS locked\", `${table}:schema`);\n\t\tif (await tableExists(executor, dialect, table)) return;\n\t}\n\tconst { int, text } = dialect.types;\n\tawait executor.exec(\n\t\t`CREATE TABLE IF NOT EXISTS ${table} (domain ${text} NOT NULL, version ${int} NOT NULL, applied_at ${int} NOT NULL, PRIMARY KEY (domain, version))${dialect.tableOptions}`,\n\t);\n}\n\n/** The highest version `table` records for `domain`, 0 when none or when the ledger does not exist yet. */\nasync function recordedVersion(\n\texecutor: SqliteExecutor,\n\tdialect: StorageDialect,\n\ttable: string,\n\tdomain: string,\n): Promise<number> {\n\tif (!(await tableExists(executor, dialect, table))) return 0;\n\tconst row = await executor.get<SqliteRow & { version: number | null }>(\n\t\t`SELECT MAX(version) AS version FROM ${table} WHERE domain = ?`,\n\t\tdomain,\n\t);\n\treturn Number(row?.version ?? 0);\n}\n\nasync function applyVersioned(\n\ttransaction: SqliteExecutor,\n\tdialect: StorageDialect,\n\ttable: string,\n\tdomain: string,\n\tsteps: readonly StorageMigrationStep[],\n\tacceptNewer = false,\n): Promise<StorageMigrationResult> {\n\tconst current = await recordedVersion(transaction, dialect, table, domain);\n\tconst supported = steps.at(-1)?.version ?? 0;\n\tif (current > supported) {\n\t\tif (acceptNewer) return { applied: [], version: current };\n\t\tthrow new StorageSchemaVersionError(domain, current, supported);\n\t}\n\tconst applied: number[] = [];\n\t// Probed first: a current schema, whose ledger exists, runs no DDL (#5218).\n\tawait createLedger(transaction, dialect, table);\n\tfor (const step of steps) {\n\t\tif (step.version <= current) continue;\n\t\tawait step.up(transaction, dialect);\n\t\tawait transaction.run(`INSERT INTO ${table} VALUES (?, ?, ${dialect.nowMs})`, domain, step.version);\n\t\tapplied.push(step.version);\n\t}\n\treturn { applied, version: Math.max(current, supported) };\n}\n\n/**\n * Advances `domain`'s schema to the last of `steps`, or refuses. Runs in one `serial` transaction whose domain is the ledger\n * table's name, so concurrent migrators under one prefix run one after another and a failed step rolls back the\n * whole call. Where the dialect has `versionedMigrations` (Postgres), applied versions are recorded in `table`: only\n * missing steps run, and a recorded version newer than the last step is a `StorageSchemaVersionError`. On SQLite\n * nothing is recorded (schemas stay what older Atomic versions share) and every step runs, idempotently; the domain's\n * own version row stays authoritative there.\n */\nexport async function applyStorageMigrations(\n\tdatabase: SqliteDatabase,\n\tdomain: string,\n\tsteps: readonly StorageMigrationStep[],\n\toptions: StorageMigrationOptions = {},\n): Promise<StorageMigrationResult> {\n\tcheckSteps(steps);\n\tconst dialect = dialectOf(database);\n\tconst table = options.table ?? DEFAULT_MIGRATION_TABLE;\n\tconst recorded = dialect.versionedMigrations ? await recordedInCatalog(database, table, domain) : undefined;\n\tconst supported = steps.at(-1)?.version ?? 0;\n\tif (recorded !== undefined && recorded >= supported && supported > 0) {\n\t\tif (recorded > supported && !options.acceptNewer)\n\t\t\tthrow new StorageSchemaVersionError(domain, recorded, supported);\n\t\treturn { applied: [], version: recorded };\n\t}\n\treturn database.transaction(\n\t\tasync (transaction) => {\n\t\t\tif (dialect.versionedMigrations)\n\t\t\t\treturn applyVersioned(transaction, dialect, table, domain, steps, options.acceptNewer);\n\t\t\tfor (const step of steps) await step.up(transaction, dialect);\n\t\t\treturn { applied: steps.map((step) => step.version), version: steps.at(-1)?.version ?? 0 };\n\t\t},\n\t\t{ retryTransientFailures: true, concurrency: { kind: \"serial\", domain: table } },\n\t);\n}\n\n/**\n * The version `table` records for `domain` in the catalog an open in progress read, or undefined outside one: an open\n * that finds every step recorded neither locks nor runs a transaction, as the steps would change nothing (#6560).\n */\nasync function recordedInCatalog(database: SqliteDatabase, table: string, domain: string): Promise<number | undefined> {\n\tconst catalog = await schemaCatalogOf(database, table);\n\tif (catalog === undefined || !catalog.hasTable(table)) return undefined;\n\treturn catalog.recordedVersion(domain);\n}\n\n/** One domain's migration for {@link applyStorageMigrationsTogether}: the arguments of {@link applyStorageMigrations}. */\nexport interface StorageDomainMigration {\n\treadonly domain: string;\n\treadonly steps: readonly StorageMigrationStep[];\n\treadonly options?: StorageMigrationOptions;\n}\n\n/**\n * Migrates each of `migrations` in order, as {@link applyStorageMigrations} would, and resolves with each one's result.\n * Where the dialect records no versions (SQLite), every step runs every time, so the domains share one transaction: one\n * turn of the write lock for all of them, and a failure rolls back all of them. Elsewhere each domain migrates in a\n * transaction of its own, as `applyStorageMigrations` runs it.\n */\nexport async function applyStorageMigrationsTogether(\n\tdatabase: SqliteDatabase,\n\tmigrations: readonly StorageDomainMigration[],\n): Promise<StorageMigrationResult[]> {\n\tconst dialect = dialectOf(database);\n\tif (dialect.versionedMigrations) {\n\t\tconst results: StorageMigrationResult[] = [];\n\t\tfor (const { domain, steps, options } of migrations)\n\t\t\tresults.push(await applyStorageMigrations(database, domain, steps, options));\n\t\treturn results;\n\t}\n\tfor (const { steps } of migrations) checkSteps(steps);\n\tconst table = migrations[0]?.options?.table ?? DEFAULT_MIGRATION_TABLE;\n\treturn database.transaction(\n\t\tasync (transaction) => {\n\t\t\tconst results: StorageMigrationResult[] = [];\n\t\t\tfor (const { steps } of migrations) {\n\t\t\t\tfor (const step of steps) await step.up(transaction, dialect);\n\t\t\t\tresults.push({ applied: steps.map((step) => step.version), version: steps.at(-1)?.version ?? 0 });\n\t\t\t}\n\t\t\treturn results;\n\t\t},\n\t\t{ retryTransientFailures: true, concurrency: { kind: \"serial\", domain: table } },\n\t);\n}\n\n/** How long one schema setup statement waits for a table lock before the setup backs off and tries again (#5218). */\nexport const SCHEMA_SETUP_LOCK_WAIT_MS = 1_000;\n/** How many times a schema setup runs before a lock it keeps waiting for fails it. */\nconst SCHEMA_SETUP_ATTEMPTS = 8;\n/** The first pause between attempts; each later one doubles, up to {@link SCHEMA_SETUP_MAX_BACKOFF_MS}. */\nconst SCHEMA_SETUP_BACKOFF_MS = 100;\nconst SCHEMA_SETUP_MAX_BACKOFF_MS = 2_000;\n\n/** Whether `error`, or what caused it, is PostgreSQL's lock timeout (SQLSTATE `55P03`). */\nfunction isLockTimeout(error: unknown): boolean {\n\tlet current = error;\n\tfor (let depth = 0; depth < 8 && typeof current === \"object\" && current !== null; depth++) {\n\t\tconst code = (current as { code?: unknown }).code;\n\t\tif (code === \"55P03\" || code === \"lock-conflict\") return true;\n\t\tcurrent = (current as { cause?: unknown }).cause;\n\t}\n\treturn false;\n}\n\n/**\n * Runs `setup`, DDL that takes table locks such as `CREATE OR REPLACE TRIGGER`'s SHARE ROW EXCLUSIVE, with a short\n * `lock_timeout` in a savepoint: a lock it would wait for, such as one a stalled transaction holds, fails it after\n * {@link SCHEMA_SETUP_LOCK_WAIT_MS}, and it rolls back to the savepoint, backs off and tries again. A waiting DDL\n * statement queues every later writer of its table behind it, so it never waits long (#5218).\n */\nexport async function withShortSchemaLockWaits(\n\texecutor: SqliteExecutor,\n\tdialect: StorageDialect,\n\tsetup: () => Promise<void>,\n): Promise<void> {\n\tif (dialect.name !== \"postgres\") return setup();\n\treturn underShortLockWaits(executor, setup);\n}\n\nasync function underShortLockWaits(executor: SqliteExecutor, setup: () => Promise<void>): Promise<void> {\n\tconst previous = await executor.get<SqliteRow & { wait: string }>(\"SELECT current_setting('lock_timeout') AS wait\");\n\tfor (let attempt = 1; ; attempt++) {\n\t\tawait executor.exec(\"SAVEPOINT atomic_schema_setup\");\n\t\tawait executor.exec(`SET LOCAL lock_timeout = ${SCHEMA_SETUP_LOCK_WAIT_MS}`);\n\t\ttry {\n\t\t\tawait setup();\n\t\t\tawait executor.exec(\"RELEASE SAVEPOINT atomic_schema_setup\");\n\t\t\tbreak;\n\t\t} catch (error) {\n\t\t\tif (!isLockTimeout(error) || attempt >= SCHEMA_SETUP_ATTEMPTS) throw error;\n\t\t\tawait executor.exec(\"ROLLBACK TO SAVEPOINT atomic_schema_setup\");\n\t\t\tconst pause = Math.min(SCHEMA_SETUP_BACKOFF_MS * 2 ** (attempt - 1), SCHEMA_SETUP_MAX_BACKOFF_MS);\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, pause * (0.5 + Math.random() / 2)));\n\t\t}\n\t}\n\tawait executor.exec(`SET LOCAL lock_timeout = '${String(previous?.wait ?? \"0\").replaceAll(\"'\", \"''\")}'`);\n}\n\n/** What {@link ensureStorageSchema} records a store's schema setup under. */\nexport interface StorageSchemaSetup {\n\t/** The ledger table, already prefixed: `storageMigrationTable(prefix)`. */\n\treadonly ledger: string;\n\t/** The store's name in the ledger, unique among the stores under one prefix, such as `\"pool-queue\"`. */\n\treadonly domain: string;\n\t/**\n\t * The revision of the store's tables, indexes, triggers and columns: raise it whenever `setup` creates or alters\n\t * anything new, so a schema an earlier build set up runs `setup` again. Past ones stay recorded, never lowered.\n\t */\n\treadonly revision: number;\n}\n\n/**\n * Whether the catalog an open in progress read (`withStorageSchemaCatalog`) records `schema.revision` for the\n * store already, so {@link ensureStorageSchema} would run nothing: the store's open then skips its schema transaction\n * and its lock (#6560). False outside such an open, on SQLite, and when the revision is not recorded.\n */\nexport async function storageSchemaCurrent(database: SqliteDatabase, schema: StorageSchemaSetup): Promise<boolean> {\n\tif (!dialectOf(database).versionedMigrations) return false;\n\tconst recorded = await recordedInCatalog(database, schema.ledger, `schema:${schema.domain}`);\n\treturn recorded !== undefined && recorded >= schema.revision;\n}\n\n/**\n * Runs `setup`, a store's idempotent schema statements (`CREATE … IF NOT EXISTS`, guarded `ALTER TABLE … ADD COLUMN`),\n * in the caller's transaction `executor` unless the ledger already records `revision` for the store (#5218). On a\n * database with versioned migrations (PostgreSQL) a current schema runs no DDL at all, so a runtime role with only DML\n * privileges opens it; a schema that is behind runs `setup` under the store's advisory lock, then records the revision,\n * so concurrent processes set it up once. A role that may not run the DDL then fails with\n * `StorageConfigError` reason `missing-privilege` from the adapter. On SQLite, which records no ledger, `setup` runs\n * every time, as before.\n */\nexport async function ensureStorageSchema(\n\texecutor: SqliteExecutor,\n\tdialect: StorageDialect,\n\tschema: StorageSchemaSetup,\n\tsetup: () => Promise<void>,\n): Promise<void> {\n\tif (!dialect.versionedMigrations) {\n\t\tawait setup();\n\t\treturn;\n\t}\n\tconst { ledger, domain, revision } = schema;\n\tconst key = `schema:${domain}`;\n\tif ((await recordedVersion(executor, dialect, ledger, key)) >= revision) return;\n\tif (dialect.name === \"postgres\") {\n\t\t// Serialized per prefix, so hosts that start together on a new database set each store up once, and two stores\n\t\t// that create a table they share never race to create it.\n\t\tawait executor.get(\"SELECT pg_advisory_xact_lock(hashtextextended(?, 0)) AS locked\", `${ledger}:schema`);\n\t\tif ((await recordedVersion(executor, dialect, ledger, key)) >= revision) return;\n\t\tawait assertSchemaUsage(executor, dialect);\n\t\tawait underShortLockWaits(executor, setup);\n\t} else await setup();\n\tawait createLedger(executor, dialect, ledger);\n\tawait executor.run(\n\t\t`INSERT INTO ${ledger} (domain, version, applied_at) VALUES (?, ?, ${dialect.nowMs}) ON CONFLICT DO NOTHING`,\n\t\tkey,\n\t\trevision,\n\t);\n}\n\n/** What {@link ensureTableFillfactor} sets, and records under `schema:<domain>` in the ledger. */\nexport interface StorageFillfactorSetup extends StorageSchemaSetup {\n\t/** The table, already prefixed. */\n\treadonly table: string;\n\t/** The percentage of each new page the table fills on insert, leaving the rest for updated row versions. */\n\treadonly fillfactor: number;\n}\n\n/**\n * Sets `setup.table`'s fillfactor on PostgreSQL, once per database, recorded in the ledger as `schema:<domain>`: each\n * page then keeps room for a new version of the rows on it, so updates of rows that change no indexed column stay on\n * their page as HOT updates and touch no index (#6560). It applies to the pages written from then on; `VACUUM FULL`\n * or pg_repack rewrites the existing ones with it. Nothing runs where the catalog an open read records the step, where\n * the table has a fillfactor already, or where this role does not own the table: a runtime role without DDL opens as\n * before, and `atomic storage migrate`, run as the owner, sets it. Does nothing on SQLite and libSQL.\n */\nexport async function ensureTableFillfactor(database: SqliteDatabase, setup: StorageFillfactorSetup): Promise<void> {\n\tconst dialect = dialectOf(database);\n\tif (dialect.name !== \"postgres\" || database.readOnly === true) return;\n\tconst { ledger, domain, revision, table, fillfactor } = setup;\n\tconst schema = { ledger, domain, revision };\n\tif (await storageSchemaCurrent(database, schema)) return;\n\tconst found = await database.get<SqliteRow & { owned: boolean | number; tuned: boolean | number }>(\n\t\t`SELECT pg_catalog.pg_has_role(current_user, c.relowner, 'USAGE') AS owned,\n\t\t\tcoalesce(array_to_string(c.reloptions, ',') LIKE '%fillfactor=%', false) AS tuned\n\t\tFROM pg_catalog.pg_class c WHERE c.relnamespace = current_schema()::regnamespace AND c.relname = ?`,\n\t\tdialect.identifier(table),\n\t);\n\tconst yes = (value: boolean | number | undefined) => value === true || Number(value) === 1;\n\tif (found === undefined || yes(found.tuned) || !yes(found.owned)) return;\n\tawait database.transaction(\n\t\t(tx) =>\n\t\t\tensureStorageSchema(tx, dialect, schema, async () => {\n\t\t\t\tawait tx.exec(`ALTER TABLE ${table} SET (fillfactor = ${Math.trunc(fillfactor)})`);\n\t\t\t}),\n\t\t{ retryTransientFailures: true, concurrency: { kind: \"serial\", domain: ledger } },\n\t);\n}\n"]}
1
+ {"version":3,"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Dialect } from \"./dialect.js\";\nimport { StorageConfigError, StorageSchemaVersionError } from \"./errors.js\";\nimport { recordSqliteSchemaStamps, schemaCatalogOf, sqliteSchemaStampsOf } from \"./schema-catalog.js\";\n\n/** One version of a domain's schema. */\nexport interface StorageMigrationStep {\n\t/** A positive integer; a domain's steps are listed in increasing order. */\n\treadonly version: number;\n\t/**\n\t * Brings the schema from the previous version to this one. It may use only `transaction`: the runner may run the\n\t * whole migration again after a transient failure. On a dialect without `versionedMigrations` (SQLite) every step\n\t * runs each time, so its statements must be idempotent (`CREATE … IF NOT EXISTS`).\n\t */\n\tup(transaction: SqliteExecutor, dialect: StorageDialect): Promise<void>;\n}\n\nexport interface StorageMigrationOptions {\n\t/** The ledger table, already prefixed (`renderStorageIdentifiers`); default `atomic_migrations`. */\n\treadonly table?: string;\n\t/**\n\t * A recorded version newer than the last step is accepted, and nothing runs, instead of refusing with\n\t * `StorageSchemaVersionError`. Only for a domain whose later steps stay additive, so a build that knows fewer of\n\t * them still reads and writes it correctly (#5065).\n\t */\n\treadonly acceptNewer?: boolean;\n\t/**\n\t * A recorded version above the last step and at most this one is accepted, and nothing runs; a newer one is still\n\t * refused. For versions that only an explicit command records, never a migration this call would run: the sessions\n\t * domain's version 3, which turns on forks that share their parent's history (#6560), and which builds that do not\n\t * list it refuse.\n\t */\n\treadonly recordedThrough?: number;\n}\n\n/** Whether a recorded `version` above the last step, `supported`, is accepted under `options` instead of refused. */\nfunction acceptsRecorded(version: number, supported: number, options: StorageMigrationOptions): boolean {\n\treturn version <= supported || options.acceptNewer === true || version <= (options.recordedThrough ?? supported);\n}\n\nexport interface StorageMigrationResult {\n\t/** The versions this call ran, in order. */\n\treadonly applied: readonly number[];\n\t/** The domain's schema version after the call. */\n\treadonly version: number;\n}\n\nconst DEFAULT_MIGRATION_TABLE = \"atomic_migrations\";\n\nfunction checkSteps(steps: readonly StorageMigrationStep[]): void {\n\tlet previous = 0;\n\tfor (const step of steps) {\n\t\tif (!Number.isSafeInteger(step.version) || step.version <= previous)\n\t\t\tthrow new StorageConfigError(\n\t\t\t\t\"sdk\",\n\t\t\t\t\"steps\",\n\t\t\t\t\"versions-increasing\",\n\t\t\t\t\"Number migration steps 1, 2, 3, … in increasing order\",\n\t\t\t);\n\t\tprevious = step.version;\n\t}\n}\n\n/** Whether `table` exists, read from the catalog: no DDL, so a role without CREATE can ask (#5218). */\nasync function tableExists(executor: SqliteExecutor, dialect: StorageDialect, table: string): Promise<boolean> {\n\tconst probe = dialect.tableExists(table);\n\treturn (await executor.get(probe.sql, ...probe.params)) !== undefined;\n}\n\n/**\n * Refuses, before any DDL, a role that cannot use the schema the database runs in: the setup would fail with a bare\n * `3F000` or `42501` that names neither the grant nor the role (#5218). PostgreSQL only.\n */\nasync function assertSchemaUsage(executor: SqliteExecutor, dialect: StorageDialect): Promise<void> {\n\tif (dialect.name !== \"postgres\") return;\n\tconst access = await executor.get<SqliteRow & { schema: string; role: string; present: number; usage: number }>(\n\t\t`SELECT s.name AS schema, current_user AS role, (n.oid IS NOT NULL)::int AS present,\n\t\t\tcoalesce(has_schema_privilege(n.oid, 'USAGE'), false)::int AS usage\n\t\tFROM (SELECT trim(both '\"' from split_part(current_setting('search_path'), ',', 1)) AS name) s\n\t\tLEFT JOIN pg_catalog.pg_namespace n ON n.nspname = s.name`,\n\t);\n\tif (access === undefined || Number(access.present) === 0 || Number(access.usage) === 1) return;\n\tthrow new StorageConfigError(\n\t\t\"sdk\",\n\t\t\"privileges\",\n\t\t\"missing-privilege\",\n\t\t`Role \"${access.role}\" has no USAGE on schema ${access.schema}, so it can neither find Atomic's tables there nor create them. Grant it as the schema's owner: GRANT USAGE ON SCHEMA ${access.schema} TO \"${access.role}\"; and, for a runtime role, the table grants in \"Set up the database\" in docs/storage.md`,\n\t);\n}\n\n/** Creates the ledger `table` unless it exists, so a current schema runs no DDL (#5218). */\nasync function createLedger(executor: SqliteExecutor, dialect: StorageDialect, table: string): Promise<void> {\n\tif (await tableExists(executor, dialect, table)) return;\n\tawait assertSchemaUsage(executor, dialect);\n\t// Two stores that set up their schemas at once never race to create the ledger they share.\n\tif (dialect.name === \"postgres\") {\n\t\tawait executor.get(\"SELECT pg_advisory_xact_lock(hashtextextended(?, 0)) AS locked\", `${table}:schema`);\n\t\tif (await tableExists(executor, dialect, table)) return;\n\t}\n\tconst { int, text } = dialect.types;\n\tawait executor.exec(\n\t\t`CREATE TABLE IF NOT EXISTS ${table} (domain ${text} NOT NULL, version ${int} NOT NULL, applied_at ${int} NOT NULL, PRIMARY KEY (domain, version))${dialect.tableOptions}`,\n\t);\n}\n\n/** The highest version `table` records for `domain`, 0 when none or when the ledger does not exist yet. */\nasync function recordedVersion(\n\texecutor: SqliteExecutor,\n\tdialect: StorageDialect,\n\ttable: string,\n\tdomain: string,\n): Promise<number> {\n\tif (!(await tableExists(executor, dialect, table))) return 0;\n\tconst row = await executor.get<SqliteRow & { version: number | null }>(\n\t\t`SELECT MAX(version) AS version FROM ${table} WHERE domain = ?`,\n\t\tdomain,\n\t);\n\treturn Number(row?.version ?? 0);\n}\n\nasync function applyVersioned(\n\ttransaction: SqliteExecutor,\n\tdialect: StorageDialect,\n\ttable: string,\n\tdomain: string,\n\tsteps: readonly StorageMigrationStep[],\n\toptions: StorageMigrationOptions = {},\n): Promise<StorageMigrationResult> {\n\tconst current = await recordedVersion(transaction, dialect, table, domain);\n\tconst supported = steps.at(-1)?.version ?? 0;\n\tif (current > supported) {\n\t\tif (acceptsRecorded(current, supported, options)) return { applied: [], version: current };\n\t\tthrow new StorageSchemaVersionError(domain, current, supported);\n\t}\n\tconst applied: number[] = [];\n\t// Probed first: a current schema, whose ledger exists, runs no DDL (#5218).\n\tawait createLedger(transaction, dialect, table);\n\tfor (const step of steps) {\n\t\tif (step.version <= current) continue;\n\t\tawait step.up(transaction, dialect);\n\t\tawait transaction.run(`INSERT INTO ${table} VALUES (?, ?, ${dialect.nowMs})`, domain, step.version);\n\t\tapplied.push(step.version);\n\t}\n\treturn { applied, version: Math.max(current, supported) };\n}\n\n/**\n * Advances `domain`'s schema to the last of `steps`, or refuses. Runs in one `serial` transaction whose domain is the ledger\n * table's name, so concurrent migrators under one prefix run one after another and a failed step rolls back the\n * whole call. Where the dialect has `versionedMigrations` (Postgres), applied versions are recorded in `table`: only\n * missing steps run, and a recorded version newer than the last step is a `StorageSchemaVersionError`. On SQLite\n * nothing is recorded (schemas stay what older Atomic versions share) and every step runs, idempotently; the domain's\n * own version row stays authoritative there.\n */\nexport async function applyStorageMigrations(\n\tdatabase: SqliteDatabase,\n\tdomain: string,\n\tsteps: readonly StorageMigrationStep[],\n\toptions: StorageMigrationOptions = {},\n): Promise<StorageMigrationResult> {\n\tcheckSteps(steps);\n\tconst dialect = dialectOf(database);\n\tconst table = options.table ?? DEFAULT_MIGRATION_TABLE;\n\tconst recorded = dialect.versionedMigrations ? await recordedInCatalog(database, table, domain) : undefined;\n\tconst supported = steps.at(-1)?.version ?? 0;\n\tif (recorded !== undefined && recorded >= supported && supported > 0) {\n\t\tif (!acceptsRecorded(recorded, supported, options))\n\t\t\tthrow new StorageSchemaVersionError(domain, recorded, supported);\n\t\treturn { applied: [], version: recorded };\n\t}\n\treturn database.transaction(\n\t\tasync (transaction) => {\n\t\t\tif (dialect.versionedMigrations) return applyVersioned(transaction, dialect, table, domain, steps, options);\n\t\t\tfor (const step of steps) await step.up(transaction, dialect);\n\t\t\treturn { applied: steps.map((step) => step.version), version: steps.at(-1)?.version ?? 0 };\n\t\t},\n\t\t{ retryTransientFailures: true, concurrency: { kind: \"serial\", domain: table } },\n\t);\n}\n\n/**\n * The version `table` records for `domain` in the catalog an open in progress read, or undefined outside one: an open\n * that finds every step recorded neither locks nor runs a transaction, as the steps would change nothing (#6560).\n */\nasync function recordedInCatalog(database: SqliteDatabase, table: string, domain: string): Promise<number | undefined> {\n\tconst catalog = await schemaCatalogOf(database, table);\n\tif (catalog === undefined || !catalog.hasTable(table)) return undefined;\n\treturn catalog.recordedVersion(domain);\n}\n\n/** One domain's migration for {@link applyStorageMigrationsTogether}: the arguments of {@link applyStorageMigrations}. */\nexport interface StorageDomainMigration {\n\treadonly domain: string;\n\treadonly steps: readonly StorageMigrationStep[];\n\treadonly options?: StorageMigrationOptions;\n}\n\n/**\n * Migrates each of `migrations` in order, as {@link applyStorageMigrations} would, and resolves with each one's result.\n * Where the dialect records no versions (SQLite), every step runs every time, so the domains share one transaction: one\n * turn of the write lock for all of them, and a failure rolls back all of them. Elsewhere each domain migrates in a\n * transaction of its own, as `applyStorageMigrations` runs it.\n */\nexport async function applyStorageMigrationsTogether(\n\tdatabase: SqliteDatabase,\n\tmigrations: readonly StorageDomainMigration[],\n): Promise<StorageMigrationResult[]> {\n\tconst dialect = dialectOf(database);\n\tif (dialect.versionedMigrations) {\n\t\tconst results: StorageMigrationResult[] = [];\n\t\tfor (const { domain, steps, options } of migrations)\n\t\t\tresults.push(await applyStorageMigrations(database, domain, steps, options));\n\t\treturn results;\n\t}\n\tfor (const { steps } of migrations) checkSteps(steps);\n\tconst table = migrations[0]?.options?.table ?? DEFAULT_MIGRATION_TABLE;\n\treturn database.transaction(\n\t\tasync (transaction) => {\n\t\t\tconst results: StorageMigrationResult[] = [];\n\t\t\tfor (const { steps } of migrations) {\n\t\t\t\tfor (const step of steps) await step.up(transaction, dialect);\n\t\t\t\tresults.push({ applied: steps.map((step) => step.version), version: steps.at(-1)?.version ?? 0 });\n\t\t\t}\n\t\t\treturn results;\n\t\t},\n\t\t{ retryTransientFailures: true, concurrency: { kind: \"serial\", domain: table } },\n\t);\n}\n\n/** How long one schema setup statement waits for a table lock before the setup backs off and tries again (#5218). */\nexport const SCHEMA_SETUP_LOCK_WAIT_MS = 1_000;\n/** How many times a schema setup runs before a lock it keeps waiting for fails it. */\nconst SCHEMA_SETUP_ATTEMPTS = 8;\n/** The first pause between attempts; each later one doubles, up to {@link SCHEMA_SETUP_MAX_BACKOFF_MS}. */\nconst SCHEMA_SETUP_BACKOFF_MS = 100;\nconst SCHEMA_SETUP_MAX_BACKOFF_MS = 2_000;\n\n/** Whether `error`, or what caused it, is PostgreSQL's lock timeout (SQLSTATE `55P03`). */\nfunction isLockTimeout(error: unknown): boolean {\n\tlet current = error;\n\tfor (let depth = 0; depth < 8 && typeof current === \"object\" && current !== null; depth++) {\n\t\tconst code = (current as { code?: unknown }).code;\n\t\tif (code === \"55P03\" || code === \"lock-conflict\") return true;\n\t\tcurrent = (current as { cause?: unknown }).cause;\n\t}\n\treturn false;\n}\n\n/**\n * Runs `setup`, DDL that takes table locks such as `CREATE OR REPLACE TRIGGER`'s SHARE ROW EXCLUSIVE, with a short\n * `lock_timeout` in a savepoint: a lock it would wait for, such as one a stalled transaction holds, fails it after\n * {@link SCHEMA_SETUP_LOCK_WAIT_MS}, and it rolls back to the savepoint, backs off and tries again. A waiting DDL\n * statement queues every later writer of its table behind it, so it never waits long (#5218).\n */\nexport async function withShortSchemaLockWaits(\n\texecutor: SqliteExecutor,\n\tdialect: StorageDialect,\n\tsetup: () => Promise<void>,\n): Promise<void> {\n\tif (dialect.name !== \"postgres\") return setup();\n\treturn underShortLockWaits(executor, setup);\n}\n\nasync function underShortLockWaits(executor: SqliteExecutor, setup: () => Promise<void>): Promise<void> {\n\tconst previous = await executor.get<SqliteRow & { wait: string }>(\"SELECT current_setting('lock_timeout') AS wait\");\n\tfor (let attempt = 1; ; attempt++) {\n\t\tawait executor.exec(\"SAVEPOINT atomic_schema_setup\");\n\t\tawait executor.exec(`SET LOCAL lock_timeout = ${SCHEMA_SETUP_LOCK_WAIT_MS}`);\n\t\ttry {\n\t\t\tawait setup();\n\t\t\tawait executor.exec(\"RELEASE SAVEPOINT atomic_schema_setup\");\n\t\t\tbreak;\n\t\t} catch (error) {\n\t\t\tif (!isLockTimeout(error) || attempt >= SCHEMA_SETUP_ATTEMPTS) throw error;\n\t\t\tawait executor.exec(\"ROLLBACK TO SAVEPOINT atomic_schema_setup\");\n\t\t\tconst pause = Math.min(SCHEMA_SETUP_BACKOFF_MS * 2 ** (attempt - 1), SCHEMA_SETUP_MAX_BACKOFF_MS);\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, pause * (0.5 + Math.random() / 2)));\n\t\t}\n\t}\n\tawait executor.exec(`SET LOCAL lock_timeout = '${String(previous?.wait ?? \"0\").replaceAll(\"'\", \"''\")}'`);\n}\n\n/** What {@link ensureStorageSchema} records a store's schema setup under. */\nexport interface StorageSchemaSetup {\n\t/** The ledger table, already prefixed: `storageMigrationTable(prefix)`. */\n\treadonly ledger: string;\n\t/** The store's name in the ledger, unique among the stores under one prefix, such as `\"pool-queue\"`. */\n\treadonly domain: string;\n\t/**\n\t * The revision of the store's tables, indexes, triggers and columns: raise it whenever `setup` creates or alters\n\t * anything new, so a schema an earlier build set up runs `setup` again. Past ones stay recorded, never lowered.\n\t */\n\treadonly revision: number;\n}\n\n/**\n * Whether the catalog an open in progress read (`withStorageSchemaCatalog`) records `schema.revision` for the\n * store already, so {@link ensureStorageSchema} would run nothing: the store's open then skips its schema transaction\n * and its lock (#6560). On SQLite and libSQL 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 and libSQL, 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): 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\tif ((await recordedVersion(executor, dialect, ledger, key)) >= revision) return;\n\tif (dialect.name === \"postgres\") {\n\t\t// Serialized per prefix, so hosts that start together on a new database set each store up once, and two stores\n\t\t// that create a table they share never race to create it.\n\t\tawait executor.get(\"SELECT pg_advisory_xact_lock(hashtextextended(?, 0)) AS locked\", `${ledger}:schema`);\n\t\tif ((await recordedVersion(executor, dialect, ledger, key)) >= revision) return;\n\t\tawait assertSchemaUsage(executor, dialect);\n\t\tawait underShortLockWaits(executor, setup);\n\t} else await setup();\n\tawait createLedger(executor, dialect, ledger);\n\tawait executor.run(\n\t\t`INSERT INTO ${ledger} (domain, version, applied_at) VALUES (?, ?, ${dialect.nowMs}) ON CONFLICT DO NOTHING`,\n\t\tkey,\n\t\trevision,\n\t);\n}\n\n/** What {@link ensureTableFillfactor} sets, and records under `schema:<domain>` in the ledger. */\nexport interface StorageFillfactorSetup extends StorageSchemaSetup {\n\t/** The table, already prefixed. */\n\treadonly table: string;\n\t/** The percentage of each new page the table fills on insert, leaving the rest for updated row versions. */\n\treadonly fillfactor: number;\n}\n\n/**\n * Sets `setup.table`'s fillfactor on PostgreSQL, once per database, recorded in the ledger as `schema:<domain>`: each\n * page then keeps room for a new version of the rows on it, so updates of rows that change no indexed column stay on\n * their page as HOT updates and touch no index (#6560). It applies to the pages written from then on; `VACUUM FULL`\n * or pg_repack rewrites the existing ones with it. Nothing runs where the catalog an open read records the step, where\n * the table has a fillfactor already, or where this role does not own the table: a runtime role without DDL opens as\n * before, and `atomic storage migrate`, run as the owner, sets it. Does nothing on SQLite and libSQL.\n */\nexport async function ensureTableFillfactor(database: SqliteDatabase, setup: StorageFillfactorSetup): Promise<void> {\n\tconst dialect = dialectOf(database);\n\tif (dialect.name !== \"postgres\" || database.readOnly === true) return;\n\tconst { ledger, domain, revision, table, fillfactor } = setup;\n\tconst schema = { ledger, domain, revision };\n\tif (await storageSchemaCurrent(database, schema)) return;\n\tconst found = await database.get<SqliteRow & { owned: boolean | number; tuned: boolean | number }>(\n\t\t`SELECT pg_catalog.pg_has_role(current_user, c.relowner, 'USAGE') AS owned,\n\t\t\tcoalesce(array_to_string(c.reloptions, ',') LIKE '%fillfactor=%', false) AS tuned\n\t\tFROM pg_catalog.pg_class c WHERE c.relnamespace = current_schema()::regnamespace AND c.relname = ?`,\n\t\tdialect.identifier(table),\n\t);\n\tconst yes = (value: boolean | number | undefined) => value === true || Number(value) === 1;\n\tif (found === undefined || yes(found.tuned) || !yes(found.owned)) return;\n\tawait database.transaction(\n\t\t(tx) =>\n\t\t\tensureStorageSchema(tx, dialect, schema, async () => {\n\t\t\t\tawait tx.exec(`ALTER TABLE ${table} SET (fillfactor = ${Math.trunc(fillfactor)})`);\n\t\t\t}),\n\t\t{ retryTransientFailures: true, concurrency: { kind: \"serial\", domain: ledger } },\n\t);\n}\n"]}
@@ -107,6 +107,33 @@ const handlers = {
107
107
  return row === undefined ? undefined : table([row]);
108
108
  },
109
109
  all: (request) => table(statement(request.sql).all(...bind(request.params))),
110
+ // A read transaction's start: BEGIN, then its leading reads, in one request. A BEGIN that fails fails the request and
111
+ // leaves no transaction. The reads answer up to the first that fails, which, with the ones after it, the caller then
112
+ // sends on its own in the same transaction, so it fails or answers there as it always would.
113
+ read: (request) => {
114
+ database.exec("BEGIN");
115
+ const answers = [];
116
+ for (const { sql, params } of request.statements) {
117
+ try {
118
+ answers.push(table(statement(sql).all(...bind(params))));
119
+ } catch {
120
+ break;
121
+ }
122
+ }
123
+ return answers;
124
+ },
125
+ // A read transaction's end, which its caller does not wait for: COMMIT, or ROLLBACK where COMMIT fails, so the
126
+ // connection is never left inside it.
127
+ endRead: () => {
128
+ try {
129
+ database.exec("COMMIT");
130
+ } catch (error) {
131
+ try {
132
+ database.exec("ROLLBACK");
133
+ } catch {}
134
+ throw error;
135
+ }
136
+ },
110
137
  // One non-blocking BEGIN IMMEDIATE, the connection's busy timeout restored before answering.
111
138
  begin: (request) => {
112
139
  // The file's lock word (see FREE in node-sqlite-file-gate.ts): taken before BEGIN, after waiting here for a
@@ -381,6 +408,8 @@ export class ThreadConnection {
381
408
  return answer.then((value) => (value === undefined ? undefined : rowsOf(value)[0]));
382
409
  if (request.kind === "all")
383
410
  return answer.then((value) => rowsOf(value));
411
+ if (request.kind === "read")
412
+ return answer.then((value) => value.map(rowsOf));
384
413
  return answer;
385
414
  }
386
415
  send(request) {
@@ -472,7 +501,7 @@ function __atomicOnDemandFailed(error, feature) {
472
501
  return (async () => {
473
502
  const root = new URL("../../", import.meta.url);
474
503
  const releases = (globalThis[Symbol.for("atomic.in-place-update-release.v1")] ??= new Map());
475
- const key = `${root.href}#0.10.11-alpha.1`;
504
+ const key = `${root.href}#0.10.11-alpha.2`;
476
505
  let release = releases.get(key);
477
506
  if (release === undefined) {
478
507
  const current = (async () => {
@@ -500,7 +529,7 @@ function __atomicOnDemandFailed(error, feature) {
500
529
  } catch {
501
530
  // No installation to read, as in a bundle of the package: the release the process runs decides.
502
531
  }
503
- const updatedTo = typeof installed === "string" && installed !== "0.10.11-alpha.1" ? installed : running !== undefined && running.version !== "0.10.11-alpha.1" ? "0.10.11-alpha.1" : undefined;
532
+ const updatedTo = typeof installed === "string" && installed !== "0.10.11-alpha.2" ? installed : running !== undefined && running.version !== "0.10.11-alpha.2" ? "0.10.11-alpha.2" : undefined;
504
533
  if (updatedTo === undefined) throw error;
505
534
  const application = typeof running?.name === "string" ? running.name : "atomic";
506
535
  const restart = new Error(`${application} was updated to ${updatedTo} while this session was running; restart it to keep using ${feature}.`, {