@bastani/atomic 0.10.0 → 0.10.1-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (233) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/dist/builtin/intercom/package.json +1 -1
  3. package/dist/builtin/mcp/package.json +1 -1
  4. package/dist/builtin/subagents/CHANGELOG.md +6 -0
  5. package/dist/builtin/subagents/package.json +1 -1
  6. package/dist/builtin/subagents/skills/tmux/scripts/wait-for-text.sh +33 -3
  7. package/dist/builtin/web-access/package.json +1 -1
  8. package/dist/core/agent-session-events.d.ts.map +1 -1
  9. package/dist/core/agent-session-events.js +21 -6
  10. package/dist/core/agent-session-events.js.map +1 -1
  11. package/dist/core/lifecycle-timings.d.ts +6 -0
  12. package/dist/core/lifecycle-timings.d.ts.map +1 -1
  13. package/dist/core/lifecycle-timings.js +12 -0
  14. package/dist/core/lifecycle-timings.js.map +1 -1
  15. package/dist/core/queued-message-delivery.d.ts +41 -0
  16. package/dist/core/queued-message-delivery.d.ts.map +1 -0
  17. package/dist/core/queued-message-delivery.js +48 -0
  18. package/dist/core/queued-message-delivery.js.map +1 -0
  19. package/dist/core/storage/node-sqlite-thread.d.ts +64 -0
  20. package/dist/core/storage/node-sqlite-thread.d.ts.map +1 -0
  21. package/dist/core/storage/node-sqlite-thread.js +326 -0
  22. package/dist/core/storage/node-sqlite-thread.js.map +1 -0
  23. package/dist/core/storage/node-sqlite.d.ts.map +1 -1
  24. package/dist/core/storage/node-sqlite.js +230 -104
  25. package/dist/core/storage/node-sqlite.js.map +1 -1
  26. package/dist/core/tasks/agent-panel-source.d.ts +5 -0
  27. package/dist/core/tasks/agent-panel-source.d.ts.map +1 -1
  28. package/dist/core/tasks/agent-panel-source.js +1 -1
  29. package/dist/core/tasks/agent-panel-source.js.map +1 -1
  30. package/dist/modes/interactive/agent-view/agent-view-bridge.d.ts +8 -1
  31. package/dist/modes/interactive/agent-view/agent-view-bridge.d.ts.map +1 -1
  32. package/dist/modes/interactive/agent-view/agent-view-bridge.js.map +1 -1
  33. package/dist/modes/interactive/agent-view/agent-view-switcher.d.ts +11 -5
  34. package/dist/modes/interactive/agent-view/agent-view-switcher.d.ts.map +1 -1
  35. package/dist/modes/interactive/agent-view/agent-view-switcher.js +17 -5
  36. package/dist/modes/interactive/agent-view/agent-view-switcher.js.map +1 -1
  37. package/dist/modes/interactive/agent-view/contracts.d.ts +5 -0
  38. package/dist/modes/interactive/agent-view/contracts.d.ts.map +1 -1
  39. package/dist/modes/interactive/agent-view/contracts.js.map +1 -1
  40. package/dist/modes/interactive/agent-view/install.d.ts.map +1 -1
  41. package/dist/modes/interactive/agent-view/install.js +6 -3
  42. package/dist/modes/interactive/agent-view/install.js.map +1 -1
  43. package/dist/modes/interactive/agent-view/local-port.d.ts +5 -0
  44. package/dist/modes/interactive/agent-view/local-port.d.ts.map +1 -1
  45. package/dist/modes/interactive/agent-view/local-port.js +8 -0
  46. package/dist/modes/interactive/agent-view/local-port.js.map +1 -1
  47. package/dist/modes/interactive/agent-view/remote-port.d.ts +4 -1
  48. package/dist/modes/interactive/agent-view/remote-port.d.ts.map +1 -1
  49. package/dist/modes/interactive/agent-view/remote-port.js +22 -8
  50. package/dist/modes/interactive/agent-view/remote-port.js.map +1 -1
  51. package/dist/modes/interactive/agent-view/transcript-slot.d.ts +9 -0
  52. package/dist/modes/interactive/agent-view/transcript-slot.d.ts.map +1 -1
  53. package/dist/modes/interactive/agent-view/transcript-slot.js +141 -1
  54. package/dist/modes/interactive/agent-view/transcript-slot.js.map +1 -1
  55. package/dist/modes/interactive/components/agent-panel.d.ts +6 -0
  56. package/dist/modes/interactive/components/agent-panel.d.ts.map +1 -1
  57. package/dist/modes/interactive/components/agent-panel.js +40 -10
  58. package/dist/modes/interactive/components/agent-panel.js.map +1 -1
  59. package/dist/modes/interactive/components/atomic-working-status.d.ts +15 -0
  60. package/dist/modes/interactive/components/atomic-working-status.d.ts.map +1 -1
  61. package/dist/modes/interactive/components/atomic-working-status.js +51 -3
  62. package/dist/modes/interactive/components/atomic-working-status.js.map +1 -1
  63. package/dist/modes/interactive/components/bash-execution.d.ts +2 -0
  64. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
  65. package/dist/modes/interactive/components/bash-execution.js +5 -1
  66. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  67. package/dist/modes/interactive/components/branch-summary-message.d.ts +2 -0
  68. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -1
  69. package/dist/modes/interactive/components/branch-summary-message.js +5 -1
  70. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
  71. package/dist/modes/interactive/components/chat-message-renderer.d.ts +2 -0
  72. package/dist/modes/interactive/components/chat-message-renderer.d.ts.map +1 -1
  73. package/dist/modes/interactive/components/chat-message-renderer.js +17 -6
  74. package/dist/modes/interactive/components/chat-message-renderer.js.map +1 -1
  75. package/dist/modes/interactive/components/chat-session-host-events.d.ts.map +1 -1
  76. package/dist/modes/interactive/components/chat-session-host-events.js +35 -4
  77. package/dist/modes/interactive/components/chat-session-host-events.js.map +1 -1
  78. package/dist/modes/interactive/components/chat-session-host-rendering.d.ts.map +1 -1
  79. package/dist/modes/interactive/components/chat-session-host-rendering.js +70 -13
  80. package/dist/modes/interactive/components/chat-session-host-rendering.js.map +1 -1
  81. package/dist/modes/interactive/components/chat-session-host-runtime.d.ts +7 -0
  82. package/dist/modes/interactive/components/chat-session-host-runtime.d.ts.map +1 -1
  83. package/dist/modes/interactive/components/chat-session-host-runtime.js +25 -4
  84. package/dist/modes/interactive/components/chat-session-host-runtime.js.map +1 -1
  85. package/dist/modes/interactive/components/chat-session-host-state.d.ts +41 -1
  86. package/dist/modes/interactive/components/chat-session-host-state.d.ts.map +1 -1
  87. package/dist/modes/interactive/components/chat-session-host-state.js +24 -3
  88. package/dist/modes/interactive/components/chat-session-host-state.js.map +1 -1
  89. package/dist/modes/interactive/components/chat-session-host-steering.d.ts.map +1 -1
  90. package/dist/modes/interactive/components/chat-session-host-steering.js +2 -1
  91. package/dist/modes/interactive/components/chat-session-host-steering.js.map +1 -1
  92. package/dist/modes/interactive/components/chat-session-host.d.ts +13 -1
  93. package/dist/modes/interactive/components/chat-session-host.d.ts.map +1 -1
  94. package/dist/modes/interactive/components/chat-session-host.js +20 -2
  95. package/dist/modes/interactive/components/chat-session-host.js.map +1 -1
  96. package/dist/modes/interactive/components/chat-transcript.d.ts +15 -0
  97. package/dist/modes/interactive/components/chat-transcript.d.ts.map +1 -1
  98. package/dist/modes/interactive/components/chat-transcript.js +14 -1
  99. package/dist/modes/interactive/components/chat-transcript.js.map +1 -1
  100. package/dist/modes/interactive/components/compaction-boundary-message.d.ts +2 -0
  101. package/dist/modes/interactive/components/compaction-boundary-message.d.ts.map +1 -1
  102. package/dist/modes/interactive/components/compaction-boundary-message.js +5 -1
  103. package/dist/modes/interactive/components/compaction-boundary-message.js.map +1 -1
  104. package/dist/modes/interactive/components/custom-entry.d.ts +2 -0
  105. package/dist/modes/interactive/components/custom-entry.d.ts.map +1 -1
  106. package/dist/modes/interactive/components/custom-entry.js +5 -1
  107. package/dist/modes/interactive/components/custom-entry.js.map +1 -1
  108. package/dist/modes/interactive/components/custom-message.d.ts +2 -0
  109. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
  110. package/dist/modes/interactive/components/custom-message.js +5 -1
  111. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  112. package/dist/modes/interactive/components/model-column.d.ts +96 -0
  113. package/dist/modes/interactive/components/model-column.d.ts.map +1 -0
  114. package/dist/modes/interactive/components/model-column.js +207 -0
  115. package/dist/modes/interactive/components/model-column.js.map +1 -0
  116. package/dist/modes/interactive/components/prompt-slot.d.ts +73 -0
  117. package/dist/modes/interactive/components/prompt-slot.d.ts.map +1 -0
  118. package/dist/modes/interactive/components/prompt-slot.js +201 -0
  119. package/dist/modes/interactive/components/prompt-slot.js.map +1 -0
  120. package/dist/modes/interactive/components/queued-messages-view.d.ts +6 -3
  121. package/dist/modes/interactive/components/queued-messages-view.d.ts.map +1 -1
  122. package/dist/modes/interactive/components/queued-messages-view.js +7 -4
  123. package/dist/modes/interactive/components/queued-messages-view.js.map +1 -1
  124. package/dist/modes/interactive/components/session-selector.d.ts +2 -0
  125. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  126. package/dist/modes/interactive/components/session-selector.js +4 -0
  127. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  128. package/dist/modes/interactive/components/skill-invocation-message.d.ts +2 -0
  129. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -1
  130. package/dist/modes/interactive/components/skill-invocation-message.js +5 -1
  131. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
  132. package/dist/modes/interactive/components/task-board.d.ts +12 -3
  133. package/dist/modes/interactive/components/task-board.d.ts.map +1 -1
  134. package/dist/modes/interactive/components/task-board.js +33 -17
  135. package/dist/modes/interactive/components/task-board.js.map +1 -1
  136. package/dist/modes/interactive/components/task-inspector.d.ts +6 -1
  137. package/dist/modes/interactive/components/task-inspector.d.ts.map +1 -1
  138. package/dist/modes/interactive/components/task-inspector.js +27 -7
  139. package/dist/modes/interactive/components/task-inspector.js.map +1 -1
  140. package/dist/modes/interactive/components/task-row.d.ts +4 -0
  141. package/dist/modes/interactive/components/task-row.d.ts.map +1 -1
  142. package/dist/modes/interactive/components/task-row.js +7 -1
  143. package/dist/modes/interactive/components/task-row.js.map +1 -1
  144. package/dist/modes/interactive/components/task-transcript-page.d.ts +5 -0
  145. package/dist/modes/interactive/components/task-transcript-page.d.ts.map +1 -1
  146. package/dist/modes/interactive/components/task-transcript-page.js +25 -0
  147. package/dist/modes/interactive/components/task-transcript-page.js.map +1 -1
  148. package/dist/modes/interactive/components/tool-execution.d.ts +7 -0
  149. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  150. package/dist/modes/interactive/components/tool-execution.js +19 -2
  151. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  152. package/dist/modes/interactive/components/tool-group-tracker.d.ts +20 -3
  153. package/dist/modes/interactive/components/tool-group-tracker.d.ts.map +1 -1
  154. package/dist/modes/interactive/components/tool-group-tracker.js +34 -7
  155. package/dist/modes/interactive/components/tool-group-tracker.js.map +1 -1
  156. package/dist/modes/interactive/components/transcript-block-clicks.d.ts +14 -2
  157. package/dist/modes/interactive/components/transcript-block-clicks.d.ts.map +1 -1
  158. package/dist/modes/interactive/components/transcript-block-clicks.js +23 -2
  159. package/dist/modes/interactive/components/transcript-block-clicks.js.map +1 -1
  160. package/dist/modes/interactive/interactive-agent-events.js +10 -2
  161. package/dist/modes/interactive/interactive-agent-events.js.map +1 -1
  162. package/dist/modes/interactive/interactive-extension-runtime.d.ts +12 -1
  163. package/dist/modes/interactive/interactive-extension-runtime.d.ts.map +1 -1
  164. package/dist/modes/interactive/interactive-extension-runtime.js +37 -5
  165. package/dist/modes/interactive/interactive-extension-runtime.js.map +1 -1
  166. package/dist/modes/interactive/interactive-input-handling.d.ts.map +1 -1
  167. package/dist/modes/interactive/interactive-input-handling.js +70 -46
  168. package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
  169. package/dist/modes/interactive/interactive-mode-base.d.ts.map +1 -1
  170. package/dist/modes/interactive/interactive-mode-base.js +7 -1
  171. package/dist/modes/interactive/interactive-mode-base.js.map +1 -1
  172. package/dist/modes/interactive/interactive-prompt-turn.js +17 -9
  173. package/dist/modes/interactive/interactive-prompt-turn.js.map +1 -1
  174. package/dist/modes/interactive/interactive-queueing.d.ts.map +1 -1
  175. package/dist/modes/interactive/interactive-queueing.js +2 -1
  176. package/dist/modes/interactive/interactive-queueing.js.map +1 -1
  177. package/dist/modes/interactive/interactive-render-chat.d.ts +18 -1
  178. package/dist/modes/interactive/interactive-render-chat.d.ts.map +1 -1
  179. package/dist/modes/interactive/interactive-render-chat.js +90 -10
  180. package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
  181. package/dist/modes/interactive/interactive-session-routing.js +2 -0
  182. package/dist/modes/interactive/interactive-session-routing.js.map +1 -1
  183. package/dist/modes/interactive/interactive-task-projection.js +2 -2
  184. package/dist/modes/interactive/interactive-task-projection.js.map +1 -1
  185. package/dist/modes/interactive/screen-hold.d.ts +41 -0
  186. package/dist/modes/interactive/screen-hold.d.ts.map +1 -0
  187. package/dist/modes/interactive/screen-hold.js +80 -0
  188. package/dist/modes/interactive/screen-hold.js.map +1 -0
  189. package/dist/modes/interactive/started-run-echo.d.ts +66 -0
  190. package/dist/modes/interactive/started-run-echo.d.ts.map +1 -0
  191. package/dist/modes/interactive/started-run-echo.js +75 -0
  192. package/dist/modes/interactive/started-run-echo.js.map +1 -0
  193. package/dist/modes/interactive-engine/engine-custom-ui.d.ts +1 -0
  194. package/dist/modes/interactive-engine/engine-custom-ui.d.ts.map +1 -1
  195. package/dist/modes/interactive-engine/engine-custom-ui.js +25 -1
  196. package/dist/modes/interactive-engine/engine-custom-ui.js.map +1 -1
  197. package/dist/modes/interactive-engine/engine-quit-intent.d.ts.map +1 -1
  198. package/dist/modes/interactive-engine/engine-quit-intent.js +3 -0
  199. package/dist/modes/interactive-engine/engine-quit-intent.js.map +1 -1
  200. package/dist/modes/interactive-engine/protocol.d.ts +5 -0
  201. package/dist/modes/interactive-engine/protocol.d.ts.map +1 -1
  202. package/dist/modes/interactive-engine/protocol.js +7 -1
  203. package/dist/modes/interactive-engine/protocol.js.map +1 -1
  204. package/dist/modes/interactive-engine/remote-component.d.ts +10 -2
  205. package/dist/modes/interactive-engine/remote-component.d.ts.map +1 -1
  206. package/dist/modes/interactive-engine/remote-component.js +19 -2
  207. package/dist/modes/interactive-engine/remote-component.js.map +1 -1
  208. package/dist/modes/interactive-engine/remote-renderer.d.ts +10 -0
  209. package/dist/modes/interactive-engine/remote-renderer.d.ts.map +1 -1
  210. package/dist/modes/interactive-engine/remote-renderer.js +24 -4
  211. package/dist/modes/interactive-engine/remote-renderer.js.map +1 -1
  212. package/dist/modes/interactive-engine/transcript-frame-layout.d.ts +50 -0
  213. package/dist/modes/interactive-engine/transcript-frame-layout.d.ts.map +1 -0
  214. package/dist/modes/interactive-engine/transcript-frame-layout.js +95 -0
  215. package/dist/modes/interactive-engine/transcript-frame-layout.js.map +1 -0
  216. package/dist/modes/rpc/agent-panel-bridge.d.ts.map +1 -1
  217. package/dist/modes/rpc/agent-panel-bridge.js +16 -0
  218. package/dist/modes/rpc/agent-panel-bridge.js.map +1 -1
  219. package/dist/modes/rpc/agent-view-engine-registry.d.ts.map +1 -1
  220. package/dist/modes/rpc/agent-view-engine-registry.js +36 -1
  221. package/dist/modes/rpc/agent-view-engine-registry.js.map +1 -1
  222. package/dist/modes/rpc/agent-view-rpc-panel.d.ts.map +1 -1
  223. package/dist/modes/rpc/agent-view-rpc-panel.js +5 -1
  224. package/dist/modes/rpc/agent-view-rpc-panel.js.map +1 -1
  225. package/dist/modes/rpc/task-ui-bridge.js +1 -1
  226. package/dist/modes/rpc/task-ui-bridge.js.map +1 -1
  227. package/docs/background-tasks.md +1 -1
  228. package/docs/development.md +2 -0
  229. package/docs/extensions/authoring.md +1 -1
  230. package/docs/keybindings.md +2 -2
  231. package/docs/storage.md +1 -0
  232. package/npm-shrinkwrap.json +49 -49
  233. package/package.json +6 -6
@@ -1 +1 @@
1
- {"version":3,"file":"node-sqlite.js","sourceRoot":"","sources":["../../../src/core/storage/node-sqlite.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,EACL,UAAU,EAEV,IAAI,EACJ,WAAW,EACX,YAAY,EACZ,QAAQ,EACR,UAAU,EACV,KAAK,EACL,KAAK,GACL,MAAM,SAAS,CAAC;AACjB,OAAO,EACN,KAAK,EACL,KAAK,EACL,OAAO,EACP,QAAQ,EACR,QAAQ,EACR,EAAE,EACF,IAAI,EACJ,MAAM,EACN,MAAM,EACN,MAAM,EACN,SAAS,GACT,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,M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eAAe,CAAC,YAAY,CAAC,CAAC;QACnC,MAAM,WAAW,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;IACtC,CAAC;AACF,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,mBAAmB,CAAC,QAAwB;IAC3D,IAAI,CAAC,CAAC,QAAQ,YAAY,kBAAkB,CAAC;QAC5C,MAAM,IAAI,gCAAgC,CAAC,QAAQ,CAAC,UAAU,EAAE,qBAAqB,CAAC,CAAC;IACxF,OAAO,QAAQ,CAAC,gBAAgB,EAAE,CAAC;AACpC,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,yBAAyB,CAAC,QAAwB;IACjE,IAAI,CAAC,CAAC,QAAQ,YAAY,kBAAkB,CAAC;QAC5C,MAAM,IAAI,gCAAgC,CAAC,QAAQ,CAAC,UAAU,EAAE,2BAA2B,CAAC,CAAC;IAC9F,OAAO,QAAQ,CAAC,sBAAsB,EAAE,CAAC;AAC1C,CAAC","sourcesContent":["import {\n\tclose,\n\texistsSync,\n\ttype FSWatcher,\n\topen,\n\treaddirSync,\n\trealpathSync,\n\tstatSync,\n\tunlinkSync,\n\twatch,\n\twrite,\n} from \"node:fs\";\nimport {\n\tlstat,\n\tmkdir,\n\treaddir,\n\treadFile,\n\trealpath,\n\trm,\n\tstat,\n\tstatfs,\n\tunlink,\n\tutimes,\n\twriteFile,\n} from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport { platform } from \"node:os\";\nimport { basename, dirname, join, resolve, win32 } from \"node:path\";\nimport type { DatabaseSync } from \"node:sqlite\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { promisify } from \"node:util\";\nimport type * as native from \"@bastani/atomic-natives\";\nimport type {\n\tSqliteDatabase,\n\tSqliteExecutor,\n\tSqliteRow,\n\tSqliteTransactionOptions,\n\tSqliteValue,\n\tStorageDescriptor,\n} from \"./database.js\";\nimport { sqliteDialect } from \"./dialect.js\";\nimport {\n\tpayloadTooLargeKind,\n\tSQLITE_PAYLOAD_LIMITS,\n\tStorageAdapterLoadError,\n\tStorageConfigError,\n\ttype StorageFailureCause,\n\tStorageInvalidTextError,\n\tStoragePayloadTooLargeError,\n\tStorageRollbackError,\n\tStorageTransactionClosedError,\n\tStorageUnavailableError,\n\tStorageUnsupportedOperationError,\n\tStorageWriteLockTimeoutError,\n\tStorageWriterQueueDegradedError,\n\ttype StorageWriterQueueDegradedReason,\n\tStorageWriterQueueUnusableError,\n\tStoreClosedError,\n} from \"./errors.js\";\nimport { isSqliteBusy, switchToWriteAheadLog, switchToWriteAheadLogSync } from \"./write-ahead-log.js\";\n\n/** Loaded at the first degradation only, so opening a database does not load debug output. */\nlet debugOutput: Promise<typeof import(\"../debug.ts\")> | undefined;\n\nfunction reportDegradationInDebugMode(degradation: StorageWriterQueueDegradedError): void {\n\tconst errno = (degradation.cause as { readonly code?: unknown } | undefined)?.code;\n\tdebugOutput ??= import(\"../debug.ts\");\n\tvoid debugOutput.then(\n\t\t({ reportDebugAsync: reportDebug }) =>\n\t\t\treportDebug(\"storage\", \"writer-queue-degraded\", {\n\t\t\t\tcode: degradation.code,\n\t\t\t\treason: degradation.reason,\n\t\t\t\tadapter: degradation.adapter,\n\t\t\t\tlocation: degradation.location,\n\t\t\t\terrno: typeof errno === \"string\" ? errno : undefined,\n\t\t\t}),\n\t\t(error: unknown) => process.emitWarning(error instanceof Error ? error : String(error)),\n\t);\n}\n\n/**\n * A ticket its owner has not refreshed for this long belongs to a process that died or stopped waiting. A ticket\n * refreshed this far in the future is stale too: the system clock stepped back since, or its owner stamped it from a\n * clock of its own.\n */\nconst TICKET_STALE_MS = 2_000;\n/** Stale tickets older than this are removed by whichever writer notices them. */\nconst TICKET_REMOVE_AFTER_MS = 10 * TICKET_STALE_MS;\n/** How often a waiting writer refreshes its ticket: well within `TICKET_STALE_MS`, even for a writer short of CPU. */\nconst TICKET_REFRESH_MS = TICKET_STALE_MS / 4;\nconst TICKET_TIME = /^(\\d{15})-/;\n/** Now on the database's clock, in milliseconds: the clock tickets are stamped and aged on (see `SqliteWriteQueue`). */\nconst DATABASE_NOW = `SELECT ${sqliteDialect.nowMs} AS now`;\n\n/** An in-memory connection of the process's own, which the database clock is read through. */\nlet clockConnection: DatabaseSync | undefined;\n\n/**\n * Now on the clock SQLite reads for `unixepoch()`: the system clock, which every process shares, whatever this\n * process's own says. SQLite reads it from the operating system, not from a database file, so a connection of the\n * process's own reads the same time as every handle's, and a handle can read it after it is closed.\n */\nfunction databaseNow(Database: typeof DatabaseSync): number {\n\tclockConnection ??= new Database(\":memory:\");\n\treturn Number(clockConnection.prepare(DATABASE_NOW).get()!.now);\n}\n\nlet ticketSequence = 0;\n\n/**\n * A ticket named after every live one: its time is the later of now and just after the latest live ticket's, so\n * order follows arrival even when processes' clocks disagree or the clock steps back.\n */\nfunction ticketName(live: readonly string[]): string {\n\tticketSequence += 1;\n\tlet time = Date.now();\n\tfor (const name of live) time = Math.max(time, Number(TICKET_TIME.exec(name)?.[1] ?? 0) + 1);\n\treturn `${String(time).padStart(15, \"0\")}-${process.pid}-${ticketSequence}`;\n}\n\nfunction isMissingFile(error: unknown): boolean {\n\treturn (error as NodeJS.ErrnoException).code === \"ENOENT\";\n}\n\n/**\n * A ticket that is gone or going: Windows reports a deleted file that another process still has open (to stat or\n * touch it) as EPERM until that handle closes.\n */\nfunction isVanishedTicket(error: unknown): boolean {\n\treturn isMissingFile(error) || ((error as NodeJS.ErrnoException).code === \"EPERM\" && platform() === \"win32\");\n}\n\n/**\n * Writes an empty queue entry, making its directory only when it is missing, as it is the first time the database\n * is contended: a writer joining the queue makes no more round trips off the event loop than it must.\n */\nasync function writeEntry(path: string, flag: \"wx\" | \"w\"): Promise<void> {\n\ttry {\n\t\tawait writeFile(path, \"\", { flag });\n\t} catch (error) {\n\t\tif (!isMissingFile(error)) throw error;\n\t\tawait mkdir(dirname(path), { recursive: true });\n\t\tawait writeFile(path, \"\", { flag });\n\t}\n}\n\n/** A queue entry and when its owner last marked it live, on the database clock. */\ninterface QueueEntry {\n\treadonly name: string;\n\treadonly mtimeMs: number;\n}\n\n/** A queue entry judged live: `fresh` when its owner marked it live within `TICKET_STALE_MS` on the database clock. */\ninterface LiveEntry {\n\treadonly name: string;\n\treadonly fresh: boolean;\n}\n\n/** When this writer first saw a ticket at its current modification time, on its own running clock. */\ninterface Sighting {\n\treadonly mtimeMs: number;\n\treadonly sinceRunningMs: number;\n}\n\nconst TICKET_PID = /^\\d{15}-(\\d+)-/;\n\n/** The queue entries of this process's writers that are waiting for the lock, by path: they are live, whatever their age. */\nconst waitingHere = new Set<string>();\n\n/**\n * First come, first served for SQLite's write lock across processes. SQLite has no queue for `BEGIN IMMEDIATE`: a\n * writer that polls after `SQLITE_BUSY` loses to one that begins the moment the lock is free, and a busy process\n * can take the lock again and again while another waits for its whole deadline (#3978). A writer that has been\n * refused takes a ticket, a file named after every live ticket, in a directory next to the database; it then\n * attempts the lock only once no live older ticket is ahead of it, and a writer that arrives while tickets wait\n * queues behind them instead of overtaking. Uncontended writers only list an absent or empty directory.\n *\n * Handing the lock on does not wait for anyone to poll (#4316): each queued writer watches a release notice of its\n * own, a file named like its ticket in a directory beside the queue's (`<file>-wakes`), and the writer that lets go\n * of the lock touches the oldest live ticket's notice, so its writer attempts the lock at once. The two never\n * share a file: only a ticket's owner moves the ticket's modification time, which is what keeps it live, so a\n * notice neither keeps a dead or stopped waiter's ticket alive nor, sent late, rolls a live one back to an older\n * time. A writer also rechecks on a timer, for the releases nobody announces: a holder killed with the lock, a\n * ticket ahead whose owner died, a raw SQLite client, an older Atomic.\n *\n * Tickets are stamped and aged on the database's clock, the system clock SQLite reads for `unixepoch()`, which also\n * stamps the files: every process shares it. A process's own clock can differ from it by seconds. On Windows, V8\n * extrapolates `Date.now()` from a reading of the system clock it renews once a minute, so after the system clock is\n * set (a virtual machine's time synchronization, say) a running process stays off by the step until then, and\n * processes aging tickets on their own clocks took live tickets for stale and overtook their writers (#4387).\n */\nclass SqliteWriteQueue {\n\tprivate readonly directory: string;\n\tprivate readonly noticeDirectory: string;\n\tprivate readonly degraded: (reason: StorageWriterQueueDegradedReason, cause: unknown) => void;\n\t/** Now on the database's clock, in milliseconds. */\n\treadonly now: () => number;\n\tprivate observedAt: number | undefined;\n\t/** Time this writer was seen to run while it looked at the queue; see `advance`. */\n\tprivate runningMs = 0;\n\t/** Each listed ticket's modification time when this writer first saw it, and its running clock then. */\n\tprivate readonly sightings = new Map<string, Sighting>();\n\n\t/** `degraded` records what the queue had to give up on without failing the transaction that met it. */\n\tconstructor(\n\t\tdatabasePath: string,\n\t\tdegraded: (reason: StorageWriterQueueDegradedReason, cause: unknown) => void,\n\t\tnow: () => number,\n\t) {\n\t\tthis.directory = `${databasePath}-writers`;\n\t\tthis.noticeDirectory = `${databasePath}-wakes`;\n\t\tthis.degraded = degraded;\n\t\tthis.now = now;\n\t}\n\n\t/** Marks this process as running now: time from here until its next look at the queue is time it was seen to run. */\n\tobserve(): void {\n\t\tthis.observedAt = performance.now();\n\t}\n\n\t/**\n\t * Advances this writer's running clock to this look and returns it. Time since its last look counts up to a waiting\n\t * writer's refresh, `TICKET_REFRESH_MS`; time beyond that is time this process was not seen to run, which a stall of\n\t * the whole host takes from every owner alike, so it is not held against their tickets.\n\t */\n\tprivate advance(): number {\n\t\tconst lookedAt = performance.now();\n\t\tif (this.observedAt !== undefined) this.runningMs += Math.min(lookedAt - this.observedAt, TICKET_REFRESH_MS);\n\t\tthis.observedAt = lookedAt;\n\t\treturn this.runningMs;\n\t}\n\n\t/**\n\t * Judges a queue's entries, sorted by name, on the database clock: the live ones, oldest first, and the ones\n\t * abandoned long enough to remove. A ticket refreshed within `TICKET_STALE_MS` is live. A ticket of a writer in\n\t * this process is live while that writer waits, and only then. A stale ticket of a process that is gone is passed\n\t * over. A stale ticket of a process that still exists is passed over only once this writer has itself run for\n\t * `TICKET_STALE_MS` since the ticket's last refresh, counting from when it first saw the ticket if it was stale then:\n\t * a stall of the whole host is never held against a ticket until its owner had the time to refresh it after the\n\t * stall, however soon this writer looks again, and a writer that starts after a stall, which saw none of it, waits\n\t * as long for the tickets it finds before passing over them.\n\t */\n\tprivate judge(entries: readonly QueueEntry[], now: number): { live: LiveEntry[]; abandoned: string[] } {\n\t\tconst running = this.advance();\n\t\tconst listed = new Set<string>();\n\t\tconst live: LiveEntry[] = [];\n\t\tconst abandoned: string[] = [];\n\t\tfor (const entry of entries) {\n\t\t\tlisted.add(entry.name);\n\t\t\tconst age = Math.abs(now - entry.mtimeMs);\n\t\t\tconst fresh = age < TICKET_STALE_MS;\n\t\t\tconst pid = Number(TICKET_PID.exec(entry.name)?.[1]);\n\t\t\tif (pid === process.pid) {\n\t\t\t\tif (waitingHere.has(join(this.directory, entry.name))) live.push({ name: entry.name, fresh: true });\n\t\t\t\telse if (fresh) live.push({ name: entry.name, fresh });\n\t\t\t\telse if (age > TICKET_REMOVE_AFTER_MS) abandoned.push(entry.name);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlet sighting = this.sightings.get(entry.name);\n\t\t\tif (sighting?.mtimeMs !== entry.mtimeMs) {\n\t\t\t\tsighting = { mtimeMs: entry.mtimeMs, sinceRunningMs: running - (fresh ? age : 0) };\n\t\t\t\tthis.sightings.set(entry.name, sighting);\n\t\t\t}\n\t\t\tif (fresh) live.push({ name: entry.name, fresh });\n\t\t\telse if (running - sighting.sinceRunningMs < TICKET_STALE_MS && Number.isSafeInteger(pid) && processAlive(pid))\n\t\t\t\tlive.push({ name: entry.name, fresh });\n\t\t\telse if (age > TICKET_REMOVE_AFTER_MS) abandoned.push(entry.name);\n\t\t}\n\t\tfor (const name of this.sightings.keys()) if (!listed.has(name)) this.sightings.delete(name);\n\t\treturn { live, abandoned };\n\t}\n\n\t/** Whether the queue directory exists: an uncontended writer finds none and reads nothing more. */\n\tcontended(): boolean {\n\t\treturn existsSync(this.directory);\n\t}\n\n\tcontendedOffLoop(): Promise<boolean> {\n\t\treturn pathExists(this.directory);\n\t}\n\n\t/** Takes a ticket behind `live`, writing it and its notice off the event loop. */\n\tasync join(live: readonly string[]): Promise<SqliteWriteTicket> {\n\t\tthis.observe();\n\t\tconst name = ticketName(live);\n\t\tconst ticket = new SqliteWriteTicket(this, name, join(this.directory, name), join(this.noticeDirectory, name));\n\t\tawait this.create(ticket, \"wx\");\n\t\treturn ticket;\n\t}\n\n\t/**\n\t * Writes the ticket's release notice, then the ticket, so a writer that finds the ticket can always touch its\n\t * notice. A ticket that cannot be written takes its notice with it; `wx` never takes over another writer's files.\n\t */\n\tasync create(ticket: SqliteWriteTicket, flag: \"wx\" | \"w\"): Promise<void> {\n\t\tawait writeEntry(ticket.noticePath, flag);\n\t\ttry {\n\t\t\tawait writeEntry(ticket.path, flag);\n\t\t\twaitingHere.add(ticket.path);\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tawait unlink(ticket.noticePath);\n\t\t\t} catch (cleanup) {\n\t\t\t\tthis.removalFailed(cleanup);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/** A ticket's notice, then the ticket: removed in that order, so no notice outlives its ticket. */\n\tprivate entryPaths(name: string): string[] {\n\t\treturn [join(this.noticeDirectory, name), join(this.directory, name)];\n\t}\n\n\t/** Whether removing an entry has to stop at `error`; one that is not a vanished entry is recorded as degraded. */\n\tprivate removalFailed(error: unknown): boolean {\n\t\tif (isVanishedTicket(error)) return false;\n\t\tthis.degraded(\"stale-ticket-kept\", error);\n\t\treturn true;\n\t}\n\n\t/** Removes an abandoned entry found while reading the queue. */\n\tremoveEntry(name: string): void {\n\t\tfor (const path of this.entryPaths(name)) {\n\t\t\ttry {\n\t\t\t\tunlinkSync(path);\n\t\t\t} catch (error) {\n\t\t\t\tif (this.removalFailed(error)) return;\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Removes an entry off the event loop: a leaving writer's own, or an abandoned one a waiting writer found. */\n\tasync removeEntryOffLoop(name: string): Promise<void> {\n\t\tfor (const path of this.entryPaths(name)) {\n\t\t\ttry {\n\t\t\t\tawait unlink(path);\n\t\t\t} catch (error) {\n\t\t\t\tif (this.removalFailed(error)) return;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Hands the turn on once this connection has let go of the write lock: touches the release notice of the oldest\n\t * live ticket, which its writer watches, so that writer attempts the lock at once. A ticket that is live only\n\t * because its owner has not yet had the time to refresh it (see `judge`) may belong to a writer that stopped, so the\n\t * notices of the tickets behind it are touched too, up to the first one refreshed on time. The ticket itself is not\n\t * touched: its modification time marks it live and only its owner moves it, so a release can neither keep a dead\n\t * writer's ticket alive nor undo the owner's refresh that came after the queue was read. A ticket that left\n\t * meanwhile passes the turn to the next one. `except` is the releasing writer's own ticket, still on its way out.\n\t */\n\tasync wakeNext(except?: string): Promise<void> {\n\t\tif (!(await this.contendedOffLoop())) return;\n\t\tfor (const ticket of await this.liveEntriesOffLoop(except)) {\n\t\t\ttry {\n\t\t\t\tconst now = new Date();\n\t\t\t\tawait utimes(join(this.noticeDirectory, ticket.name), now, now);\n\t\t\t\tif (ticket.fresh) return;\n\t\t\t} catch (error) {\n\t\t\t\tif (!isVanishedTicket(error)) throw error;\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Live tickets, oldest first; see `liveTicketEntries`. */\n\tliveTickets(except?: string): string[] {\n\t\treturn this.liveTicketEntries(except).map((ticket) => ticket.name);\n\t}\n\n\t/**\n\t * Live tickets, oldest first; stale ones long abandoned are removed on the way. A ticket is judged on the time this\n\t * writer was seen to run since it first saw it (see `judge`), so a stall of the whole host neither passes over nor\n\t * removes the tickets of writers it stopped too. A queue directory or a ticket that\n\t * vanishes while it is read counts as absent; any other failure to read the queue is thrown, so no caller takes a\n\t * queue it cannot read for an empty one. Removing an abandoned ticket is housekeeping: it is ignored whether or not\n\t * it goes, so a failure other than the ticket having vanished (another user's ticket in a shared directory, say)\n\t * is recorded as degraded, once, and never fails a transaction.\n\t */\n\tprivate liveTicketEntries(except?: string): LiveEntry[] {\n\t\tlet names: string[];\n\t\t// Uncontended writers find no directory; checking costs a third of a failed listing, twice per transaction.\n\t\tif (!this.contended()) return [];\n\t\ttry {\n\t\t\tnames = readdirSync(this.directory);\n\t\t} catch (error) {\n\t\t\tif (!isMissingFile(error)) throw error;\n\t\t\treturn [];\n\t\t}\n\t\t// An empty queue, as contention leaves it, is read without the clock.\n\t\tif (names.length === 0) return [];\n\t\tconst now = this.now();\n\t\tconst entries: QueueEntry[] = [];\n\t\tfor (const name of names.sort()) {\n\t\t\tif (name === except) continue;\n\t\t\ttry {\n\t\t\t\tentries.push({ name, mtimeMs: statSync(join(this.directory, name)).mtimeMs });\n\t\t\t} catch (error) {\n\t\t\t\tif (!isVanishedTicket(error)) throw error;\n\t\t\t}\n\t\t}\n\t\tconst { live, abandoned } = this.judge(entries, now);\n\t\tfor (const name of abandoned) this.removeEntry(name);\n\t\treturn live;\n\t}\n\n\t/** Live tickets other than `except`, oldest first, read off the event loop; see `liveEntriesOffLoop`. */\n\tasync liveTicketsOffLoop(except?: string): Promise<string[]> {\n\t\treturn (await this.liveEntriesOffLoop(except)).map((entry) => entry.name);\n\t}\n\n\t/**\n\t * Live tickets other than `except`, oldest first: read off the event loop and judged like `liveTicketEntries`.\n\t * Entries are read together; the first failure in listing order that is not a vanished entry is thrown.\n\t */\n\tprivate async liveEntriesOffLoop(except?: string): Promise<LiveEntry[]> {\n\t\tlet names: string[];\n\t\ttry {\n\t\t\tnames = await readdir(this.directory);\n\t\t} catch (error) {\n\t\t\tif (!isMissingFile(error)) throw error;\n\t\t\treturn [];\n\t\t}\n\t\tif (names.length === 0) return [];\n\t\tconst listed = names.sort().filter((name) => name !== except);\n\t\tconst read = await Promise.all(\n\t\t\tlisted.map((name) =>\n\t\t\t\tstat(join(this.directory, name)).then(\n\t\t\t\t\t(found): QueueEntry => ({ name, mtimeMs: found.mtimeMs }),\n\t\t\t\t\t(error: unknown) => ({ name, error }),\n\t\t\t\t),\n\t\t\t),\n\t\t);\n\t\tconst entries: QueueEntry[] = [];\n\t\tfor (const entry of read) {\n\t\t\tif (!(\"error\" in entry)) entries.push(entry);\n\t\t\telse if (!isVanishedTicket(entry.error)) throw entry.error;\n\t\t}\n\t\tconst { live, abandoned } = this.judge(entries, this.now());\n\t\tfor (const name of abandoned) await this.removeEntryOffLoop(name);\n\t\treturn live;\n\t}\n}\n\nclass SqliteWriteTicket {\n\tprivate left = false;\n\tprivate readonly queue: SqliteWriteQueue;\n\treadonly name: string;\n\treadonly path: string;\n\treadonly noticePath: string;\n\t/** When this writer last marked the ticket live, on the monotonic clock. */\n\tprivate refreshed = performance.now();\n\n\tconstructor(queue: SqliteWriteQueue, name: string, path: string, noticePath: string) {\n\t\tthis.queue = queue;\n\t\tthis.name = name;\n\t\tthis.path = path;\n\t\tthis.noticePath = noticePath;\n\t}\n\n\t/**\n\t * Keeps this ticket live: refreshes it once `TICKET_REFRESH_MS` have passed since it was created or last\n\t * refreshed, recreating it and its release notice in the place it had if it was removed as stale while this\n\t * writer stalled. Returns whether the notice was recreated, which ends a watch on the removed one. The file work\n\t * runs off the event loop.\n\t */\n\tasync keepLive(): Promise<boolean> {\n\t\tif (performance.now() - this.refreshed < TICKET_REFRESH_MS) return false;\n\t\tthis.refreshed = performance.now();\n\t\tconst now = new Date(this.queue.now());\n\t\ttry {\n\t\t\tawait utimes(this.path, now, now);\n\t\t\treturn false;\n\t\t} catch (error) {\n\t\t\tif (!isVanishedTicket(error)) throw error;\n\t\t\tawait this.queue.create(this, \"w\");\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t/** Whether an older live ticket is still ahead of this one, read off the event loop. */\n\tasync behindOthers(): Promise<boolean> {\n\t\treturn (await this.queue.liveTicketsOffLoop(this.name)).some((other) => other < this.name);\n\t}\n\n\t/** Watches this writer's release notice: anything that touches the file, as a releasing writer does. */\n\twatch(onUnavailable: (cause: Error) => void): ReleaseNotices {\n\t\treturn new ReleaseNotices(this.noticePath, onUnavailable);\n\t}\n\n\tasync leave(): Promise<void> {\n\t\tif (this.left) return;\n\t\tthis.left = true;\n\t\ttry {\n\t\t\tawait this.queue.removeEntryOffLoop(this.name);\n\t\t} finally {\n\t\t\twaitingHere.delete(this.path);\n\t\t}\n\t}\n}\n\n/**\n * The release notices a queued writer receives while it waits: a change to its notice file, which is how the writer\n * that lets go of the lock hands it the turn. The watch starts before the writer first checks the lock. A notice that\n * arrives while the writer reads the queue or attempts the lock is kept until its next wait, which then ends at once,\n * so one sent while it checks is never lost; `clear` forgets the notices a fresh look at the queue and the lock covers.\n */\nclass ReleaseNotices {\n\tprivate watcher?: FSWatcher;\n\tprivate arrived = false;\n\tprivate wake?: () => void;\n\n\tconstructor(path: string, onUnavailable: (cause: Error) => void) {\n\t\ttry {\n\t\t\tconst watcher = watch(path, () => {\n\t\t\t\tthis.arrived = true;\n\t\t\t\tthis.wake?.();\n\t\t\t});\n\t\t\twatcher.on(\"error\", (cause: Error) => {\n\t\t\t\tthis.close();\n\t\t\t\tonUnavailable(cause);\n\t\t\t});\n\t\t\tthis.watcher = watcher;\n\t\t} catch (cause) {\n\t\t\tonUnavailable(cause as Error);\n\t\t}\n\t}\n\n\tget watching(): boolean {\n\t\treturn this.watcher !== undefined;\n\t}\n\n\t/** Forgets the notices received so far: the writer is about to look at the queue and the lock afresh. */\n\tclear(): void {\n\t\tthis.arrived = false;\n\t}\n\n\t/** Resolves once a notice arrives, at once if one arrived since `clear`, or after `ms`. */\n\twait(ms: number): Promise<void> {\n\t\tif (this.arrived) return Promise.resolve();\n\t\treturn new Promise((resolve) => {\n\t\t\tconst done = () => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tthis.wake = undefined;\n\t\t\t\tresolve();\n\t\t\t};\n\t\t\tconst timer = setTimeout(done, ms);\n\t\t\tthis.wake = done;\n\t\t});\n\t}\n\n\tclose(): void {\n\t\tthis.watcher?.close();\n\t\tthis.watcher = undefined;\n\t}\n}\n\nlet holderSequence = 0;\nconst HOLDER_RECORD = /^(held|want) (\\d{15})\\n/;\n\nfunction processAlive(pid: number): boolean {\n\ttry {\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch (error) {\n\t\treturn (error as NodeJS.ErrnoException).code === \"EPERM\";\n\t}\n}\n\n/**\n * Which process holds the write lock, for the error of a writer that gives up waiting for it. Each connection\n * records in a file of its own next to the database, named by its process, when it starts trying for the lock (before\n * its first attempt, which waits for the record to be written), when it took the lock, and that it is free once it\n * lets go or gives up; only its connection writes a record, so records never race. Nothing reads them until a writer\n * gives up: the live record taken most recently names the holder. A holder whose record does not yet say it took the\n * lock, stopped or starved right after taking it, still says it was trying for it; it is then one of the candidates the\n * writer that gives up lists, not named. A connection removes the records\n * of exited processes when it creates its own, so the killed ones do not pile up. Recording is a diagnostic: a\n * record that cannot be created, written or cleaned up never fails a transaction. The failure is recorded as a\n * degradation instead, and a writer that gives up waiting may then name no holder.\n */\nclass SqliteHolderRecord {\n\tprivate descriptor?: number;\n\tprivate writes: Promise<void> = Promise.resolve();\n\tprivate readonly directory: string;\n\tprivate readonly path: string;\n\tprivate readonly unavailable: (cause: unknown) => void;\n\n\t/** `unavailable` records a failure to keep the record, or to remove an exited process's. */\n\tconstructor(databasePath: string, unavailable: (cause: unknown) => void) {\n\t\tthis.directory = holderDirectory(databasePath);\n\t\tholderSequence += 1;\n\t\tthis.path = join(this.directory, `${process.pid}-${holderSequence}`);\n\t\tthis.unavailable = unavailable;\n\t}\n\n\t/**\n\t * Creates the record off the event loop as a writable connection opens, removing exited processes' records on the\n\t * way, so that taking the lock only writes to it in place.\n\t */\n\tasync open(): Promise<void> {\n\t\ttry {\n\t\t\tawait mkdir(this.directory, { recursive: true });\n\t\t\tawait removeExitedHolderRecords(this.directory, this.unavailable);\n\t\t\tthis.descriptor = await openFile(this.path, \"w\");\n\t\t} catch (cause) {\n\t\t\tthis.unavailable(cause);\n\t\t}\n\t}\n\n\t/** Records that this connection is about to try for the lock; written before its first attempt. */\n\ttrying(): Promise<void> {\n\t\treturn this.write(`want ${String(Date.now()).padStart(15, \"0\")}\\n`);\n\t}\n\n\theld(): Promise<void> {\n\t\treturn this.write(`held ${String(Date.now()).padStart(15, \"0\")}\\n`);\n\t}\n\n\tfree(): Promise<void> {\n\t\treturn this.write(`free ${\"0\".repeat(15)}\\n`);\n\t}\n\n\t/** The process, this one or another, whose record says it took the write lock most recently; see `writeLockHolder`. */\n\tlatestHolder(): Promise<WriteLockHolder | undefined> {\n\t\treturn writeLockHolder(this.directory, basename(this.path));\n\t}\n\n\tasync close(): Promise<void> {\n\t\tawait this.writes;\n\t\tawait this.remove();\n\t}\n\n\tprivate async remove(): Promise<void> {\n\t\tconst descriptor = this.descriptor;\n\t\tif (descriptor === undefined) return;\n\t\tthis.descriptor = undefined;\n\t\ttry {\n\t\t\tawait closeFile(descriptor);\n\t\t\tawait unlink(this.path);\n\t\t} catch {\n\t\t\t// Already gone; a leftover record of an exited process is ignored and removed by whoever reads it.\n\t\t}\n\t}\n\n\t/**\n\t * Every record has the same length and is written in place, so a reader never sees a shorter, stale tail. A\n\t * connection without a record, read-only or unable to create one, writes nothing.\n\t */\n\tprivate write(record: string): Promise<void> {\n\t\tthis.writes = this.writes.then(async () => {\n\t\t\tconst descriptor = this.descriptor;\n\t\t\tif (descriptor === undefined) return;\n\t\t\ttry {\n\t\t\t\tawait writeFileAt(descriptor, record, 0);\n\t\t\t} catch (cause) {\n\t\t\t\tawait this.remove();\n\t\t\t\tthis.unavailable(cause);\n\t\t\t}\n\t\t});\n\t\treturn this.writes;\n\t}\n}\n\nfunction holderDirectory(databasePath: string): string {\n\treturn `${databasePath}-holders`;\n}\n\nexport function sqliteOpenLockPath(databasePath: string): string {\n\treturn `${databasePath}-open.lock`;\n}\n\ntype NativeOpenLocks = Pick<typeof native, \"tryAdvisoryLock\" | \"trySharedAdvisoryLock\"> &\n\tPartial<Pick<typeof native, \"tryAdvisoryLockAsync\">>;\n\ninterface HeldOpenLock {\n\treadonly lock: { release(): void };\n\treadonly path: string;\n\treadonly target: string;\n}\n\nlet nativeOpenLocks: NativeOpenLocks | null | undefined;\n\nfunction openLocks(): NativeOpenLocks | null {\n\tif (nativeOpenLocks === undefined) {\n\t\ttry {\n\t\t\tlet binding: Partial<NativeOpenLocks>;\n\t\t\ttry {\n\t\t\t\tbinding = createRequire(import.meta.url)(\"@bastani/atomic-natives\") as Partial<NativeOpenLocks>;\n\t\t\t} catch {\n\t\t\t\tbinding = createRequire(pathToFileURL(process.execPath).href)(\n\t\t\t\t\t\"@bastani/atomic-natives\",\n\t\t\t\t) as Partial<NativeOpenLocks>;\n\t\t\t}\n\t\t\tnativeOpenLocks =\n\t\t\t\ttypeof binding.tryAdvisoryLock === \"function\" && typeof binding.trySharedAdvisoryLock === \"function\"\n\t\t\t\t\t? (binding as NativeOpenLocks)\n\t\t\t\t\t: null;\n\t\t} catch {\n\t\t\tnativeOpenLocks = null;\n\t\t}\n\t}\n\treturn nativeOpenLocks;\n}\n\nfunction sqliteTargetFilePath(spec: string): string | undefined {\n\tif (spec === \"\" || spec === \":memory:\") return undefined;\n\tif (!spec.startsWith(\"file:\")) return spec;\n\tconst hashIndex = spec.indexOf(\"#\");\n\tconst withoutHash = hashIndex === -1 ? spec : spec.slice(0, hashIndex);\n\tconst queryIndex = withoutHash.indexOf(\"?\");\n\tconst uriPart = queryIndex === -1 ? withoutHash : withoutHash.slice(0, queryIndex);\n\tconst queryPart = queryIndex === -1 ? \"\" : withoutHash.slice(queryIndex + 1);\n\tif (new URLSearchParams(queryPart).get(\"mode\") === \"memory\") return undefined;\n\tconst body = uriPart.slice(\"file:\".length);\n\tif (body === \"\" || body === \":memory:\") return undefined;\n\tif (uriPart.startsWith(\"file://\")) {\n\t\ttry {\n\t\t\treturn fileURLToPath(uriPart);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\ttry {\n\t\tconst decoded = decodeURIComponent(body);\n\t\tif (process.platform === \"win32\" && /^\\/[a-zA-Z]:/.test(decoded)) return decoded.slice(1);\n\t\treturn resolve(decoded);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction isMissingOpenLockDir(error: unknown): boolean {\n\tif (isMissingFile(error)) return true;\n\tconst message = error instanceof Error ? error.message : String(error);\n\treturn /No such file or directory|cannot find the path|os error [23]\\b/i.test(message);\n}\n\nfunction pathExists(path: string): Promise<boolean> {\n\treturn stat(path).then(\n\t\t() => true,\n\t\t() => false,\n\t);\n}\n\nasync function resolveOpenLockTarget(filePath: string, readOnly: boolean): Promise<string | undefined> {\n\ttry {\n\t\treturn await realpath(filePath);\n\t} catch {\n\t\tif (readOnly) return undefined;\n\t\tawait mkdir(dirname(filePath), { recursive: true });\n\t\treturn join(await realpath(dirname(filePath)), basename(filePath));\n\t}\n}\n\nasync function acquireOpenLock(\n\tfilePath: string | undefined,\n\treadOnly: boolean,\n\tbusyTimeoutMs: number,\n): Promise<HeldOpenLock | undefined> {\n\tconst locks = openLocks();\n\tif (locks === null || filePath === undefined) return undefined;\n\tconst started = performance.now();\n\tlet delay = 5;\n\tfor (;;) {\n\t\tconst target = await resolveOpenLockTarget(filePath, readOnly);\n\t\tif (target === undefined) return undefined;\n\t\tconst lockPath = sqliteOpenLockPath(target);\n\t\tif (\n\t\t\treadOnly &&\n\t\t\t!(await pathExists(holderDirectory(target))) &&\n\t\t\t!(await pathExists(lockPath)) &&\n\t\t\t!(await pathExists(`${target}.lock`))\n\t\t)\n\t\t\treturn undefined;\n\t\tlet lock: { release(): void } | null = null;\n\t\tlet refusal: unknown;\n\t\ttry {\n\t\t\tlock = locks.trySharedAdvisoryLock(sqliteFilePath(lockPath), 0);\n\t\t} catch (error) {\n\t\t\tif (readOnly) return undefined;\n\t\t\tif (await isPassingOpenLockRefusal(error, lockPath)) refusal = error;\n\t\t\telse if (!isMissingOpenLockDir(error)) throw error;\n\t\t}\n\t\tif (lock !== null) {\n\t\t\tconst held: HeldOpenLock = { lock, path: sqliteFilePath(lockPath), target };\n\t\t\tif (readOnly && !(await pathExists(target))) {\n\t\t\t\tawait releaseOpenLock(held);\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\treturn held;\n\t\t}\n\t\tconst remaining = started + busyTimeoutMs - performance.now();\n\t\tif (remaining <= 0 && refusal !== undefined) throw refusal;\n\t\tif (remaining <= 0)\n\t\t\tthrow Object.assign(new Error(\"database is locked\"), {\n\t\t\t\tcode: \"ERR_SQLITE_ERROR\",\n\t\t\t\terrcode: 5,\n\t\t\t\terrstr: \"database is locked\",\n\t\t\t});\n\t\tawait new Promise((resolve) => setTimeout(resolve, Math.min(delay, remaining)));\n\t\tdelay = Math.min(delay * 2, 50);\n\t}\n}\n\n/**\n * Windows refuses to create a file for a few milliseconds after another process removes one of the same name, with\n * `Access is denied` while nothing is at the path; an open waits that out like a held lock, within its busy timeout.\n * A refusal while a file is at the path is a real permission error.\n */\nasync function isPassingOpenLockRefusal(error: unknown, lockPath: string): Promise<boolean> {\n\tif (process.platform !== \"win32\") return false;\n\tconst message = error instanceof Error ? error.message : String(error);\n\tif (!/\\(os error 5\\)/.test(message)) return false;\n\treturn lstat(lockPath).then(\n\t\t() => false,\n\t\t(cause: unknown) => isMissingFile(cause),\n\t);\n}\n\nfunction isOpenLockPermissionError(error: unknown): boolean {\n\tconst code = (error as NodeJS.ErrnoException | undefined)?.code;\n\tif (code === \"EACCES\" || code === \"EPERM\" || code === \"EROFS\") return true;\n\tconst message = error instanceof Error ? error.message : String(error);\n\treturn process.platform === \"win32\"\n\t\t? /\\(os error (?:5|19|65)\\)/.test(message)\n\t\t: /\\(os error (?:1|13|30)\\)/.test(message);\n}\n\nfunction acquireOpenLockSync(location: string): HeldOpenLock | undefined {\n\tconst locks = openLocks();\n\tconst filePath = sqliteTargetFilePath(location);\n\tif (locks === null || filePath === undefined) return undefined;\n\tconst target = realpathSync(filePath);\n\tconst lockPath = sqliteFilePath(sqliteOpenLockPath(target));\n\tlet lock: { release(): void } | null;\n\ttry {\n\t\tlock = locks.trySharedAdvisoryLock(lockPath, 50);\n\t} catch (error) {\n\t\tif (isOpenLockPermissionError(error)) return undefined;\n\t\tthrow error;\n\t}\n\tif (lock === null)\n\t\tthrow Object.assign(new Error(\"database is locked\"), {\n\t\t\tcode: \"ERR_SQLITE_ERROR\",\n\t\t\terrcode: 5,\n\t\t\terrstr: \"database is locked\",\n\t\t});\n\treturn { lock, path: lockPath, target };\n}\n\nasync function releaseOpenLock(openLock: HeldOpenLock | undefined): Promise<void> {\n\tif (openLock === undefined) return;\n\topenLock.lock.release();\n\ttry {\n\t\tconst exclusive = (await openLocks()?.tryAdvisoryLockAsync?.(openLock.path, 0)) ?? null;\n\t\tif (exclusive !== null) {\n\t\t\ttry {\n\t\t\t\tawait rm(openLock.path, { force: true });\n\t\t\t} finally {\n\t\t\t\texclusive.release();\n\t\t\t}\n\t\t}\n\t} catch {}\n}\n\nconst openFile = promisify(open);\nconst closeFile = promisify(close);\nconst writeFileAt = promisify(write) as (descriptor: number, data: string, position: number) => Promise<unknown>;\n\n/** The process a holder record belongs to, from its name: `<pid>-<sequence>`. */\nfunction holderPid(name: string): number | undefined {\n\tconst pid = Number(/^(\\d+)-/.exec(name)?.[1] ?? Number.NaN);\n\treturn Number.isSafeInteger(pid) && pid > 0 ? pid : undefined;\n}\n\n/**\n * Removes the records of exited processes, off the event loop. One another connection removed first is gone; any\n * other failure to remove one goes to `failed`, and the rest are still removed.\n */\nasync function removeExitedHolderRecords(directory: string, failed: (cause: unknown) => void): Promise<void> {\n\tfor (const name of await readdir(directory)) {\n\t\tconst pid = holderPid(name);\n\t\tif (pid === undefined || processAlive(pid)) continue;\n\t\ttry {\n\t\t\tawait unlink(join(directory, name));\n\t\t} catch (error) {\n\t\t\tif (!isVanishedTicket(error)) failed(error);\n\t\t}\n\t}\n}\n\n/** A live process's record: when it took the lock, or started trying for it; neither when it is free. */\ninterface LiveHolderRecord {\n\treadonly name: string;\n\treadonly pid: number;\n\treadonly heldSince?: number;\n\treadonly tryingSince?: number;\n}\n\n/** The records of live processes; the records of exited ones are removed. */\nasync function liveHolderRecords(directory: string): Promise<LiveHolderRecord[]> {\n\tlet names: string[];\n\ttry {\n\t\tnames = await readdir(directory);\n\t} catch {\n\t\treturn [];\n\t}\n\tconst live: LiveHolderRecord[] = [];\n\tfor (const name of names) {\n\t\tconst pid = holderPid(name);\n\t\tif (pid === undefined) continue;\n\t\tif (!processAlive(pid)) {\n\t\t\ttry {\n\t\t\t\tawait unlink(join(directory, name));\n\t\t\t} catch {\n\t\t\t\t// Another connection removed it first.\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tlet record: string;\n\t\ttry {\n\t\t\trecord = await readFile(join(directory, name), \"utf8\");\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tconst [, state, since] = HOLDER_RECORD.exec(record) ?? [];\n\t\tlive.push({\n\t\t\tname,\n\t\t\tpid,\n\t\t\t...(state === \"held\" ? { heldSince: Number(since) } : {}),\n\t\t\t...(state === \"want\" ? { tryingSince: Number(since) } : {}),\n\t\t});\n\t}\n\treturn live;\n}\n\n/** Who holds the write lock, as far as the records prove it. */\ntype WriteLockHolder = { readonly pid: number; readonly heldMs: number } | { readonly candidates: readonly number[] };\n\n/**\n * The live process whose record says it took the write lock most recently, and for how long it has held it. A record\n * that says a connection is only trying for the lock proves nothing: a waiter stopped in the queue keeps saying so while\n * a later writer takes the lock past it. So when no record says it took the lock, as for a holder stopped before its\n * record could say so, no process is named; the processes of the other connections trying for the lock, not `own`, are\n * the candidates, one of which may hold it.\n */\nasync function writeLockHolder(directory: string, own: string): Promise<WriteLockHolder | undefined> {\n\tlet held: { pid: number; since: number } | undefined;\n\tconst candidates = new Set<number>();\n\tfor (const record of await liveHolderRecords(directory)) {\n\t\tconst { pid, heldSince, tryingSince } = record;\n\t\tif (heldSince !== undefined && (held === undefined || heldSince > held.since)) held = { pid, since: heldSince };\n\t\tif (record.name !== own && tryingSince !== undefined) candidates.add(pid);\n\t}\n\tif (held !== undefined) return { pid: held.pid, heldMs: Math.max(0, Date.now() - held.since) };\n\treturn candidates.size === 0 ? undefined : { candidates: [...candidates].sort((a, b) => a - b) };\n}\n\ninterface TransactionGates {\n\treadonly files: Map<string, Promise<void>>;\n\treadonly connections: WeakMap<DatabaseSync, Promise<void>>;\n}\n\n// Share gates across module reloads as well as adapter instances. Only live queues retain file identities.\nconst TRANSACTION_GATES = Symbol.for(\"atomic-storage/node-sqlite-transaction-gates@1\");\nconst gateBag = globalThis as typeof globalThis & Record<symbol, TransactionGates | undefined>;\nconst gates: TransactionGates = gateBag[TRANSACTION_GATES] ?? { files: new Map(), connections: new WeakMap() };\ngateBag[TRANSACTION_GATES] = gates;\n\nfunction gateTransaction<T>(identity: string | DatabaseSync, operation: () => Promise<T>): Promise<T> {\n\tconst prior = typeof identity === \"string\" ? gates.files.get(identity) : gates.connections.get(identity);\n\tconst result = (prior ?? Promise.resolve()).then(operation);\n\tconst settled = result.then(\n\t\t() => {},\n\t\t() => {},\n\t);\n\tif (typeof identity === \"string\") gates.files.set(identity, settled);\n\telse gates.connections.set(identity, settled);\n\tvoid settled.then(() => {\n\t\tif (typeof identity === \"string\") {\n\t\t\tif (gates.files.get(identity) === settled) gates.files.delete(identity);\n\t\t} else if (gates.connections.get(identity) === settled) gates.connections.delete(identity);\n\t});\n\treturn result;\n}\n\n/** Copies binary parameters so queued work binds the bytes the caller passed, not later buffer contents. */\nfunction snapshotParams(params: readonly SqliteValue[]): SqliteValue[] {\n\treturn params.map((value) => (value instanceof Uint8Array ? new Uint8Array(value) : value));\n}\n\n/**\n * Bun's `DatabaseSync.close()` defers closing the file until garbage collection finalizes every statement the\n * connection prepared, so the database, WAL and shared-memory files stay open (and locked on Windows). The adapter\n * keeps no statement references, so a synchronous collection finalizes them and releases the files. Node finalizes\n * statements inside `close()` and has no `Bun` global.\n */\nfunction finalizeReleasedStatements(): void {\n\t(globalThis as { Bun?: { gc(force: boolean): void } }).Bun?.gc(true);\n}\n\n/**\n * Default for how long a transaction keeps retrying `BEGIN IMMEDIATE` while the write lock is held and nobody makes\n * progress through it: every commit by another connection restarts the wait, so only a lock held without commits\n * for this long fails the transaction.\n */\nconst DEFAULT_NODE_SQLITE_LOCK_WAIT_MS = 30_000;\n/**\n * How often a queued writer that watches its ticket rechecks without being told to: it refreshes its ticket (well\n * within `TICKET_STALE_MS`, even for a writer starved of CPU) and notices releases nobody announces. Handing the lock\n * on between Atomic writers does not wait for it.\n */\nconst LOCK_WAIT_RECHECK_MS = 250;\n/**\n * How often a writer that cannot watch its ticket (or has no queue: an in-memory or wrapped connection) retries the\n * lock within the connection's lock wait. Past it, for a transaction that waits longer, it retries every\n * `LOCK_WAIT_RECHECK_MS`, so writers polling a stalled lock leave the stalled holder the CPU it needs.\n */\nconst UNWATCHED_LOCK_RETRY_MS = 20;\n/**\n * How long a refused writer keeps trying the lock on every event-loop turn once another connection has committed\n * since its last look (see `attemptThroughRelease`): one Windows timer tick (15.6 ms), so the attempts cover the time\n * between two ticks, when a writer that does not queue and runs on its own timers lets go of the lock.\n */\nconst LOCK_RELEASE_RETRY_MS = 16;\n/** Most attempts in one `LOCK_RELEASE_RETRY_MS` span, so it ends even on a clock that does not move. */\nconst LOCK_RELEASE_RETRY_ATTEMPTS = 1_000;\n/** Most transactions one group commit carries, so a batch cannot keep the write lock from other processes for long. */\nconst MAX_GROUP_COMMIT_TRANSACTIONS = 128;\n/**\n * Default for how long a group commit runs its members before it commits them and takes the lock again for the\n * rest: a batch of cheap transactions in a process starved of CPU still lets other processes' writers in between.\n * The bound is checked between members, so one member's own work, however long, is never split.\n */\nexport const DEFAULT_GROUP_COMMIT_HOLD_MS = 100;\n/** The span `getWriterQueueStats` reports on. */\nconst WRITER_QUEUE_STATS_WINDOW_MS = 10_000;\n\ninterface QueuedTransaction {\n\treadonly callback: (transaction: SqliteExecutor) => Promise<unknown>;\n\treadonly resolve: (value: unknown) => void;\n\treadonly reject: (error: unknown) => void;\n\treadonly lockWaitMs?: number;\n}\n\n/**\n * Transactions committed together. `position` is the connection operation that commits them; a batch directly behind\n * it (`position + 1`, so no statement between) is absorbed when this one first takes the lock. A waiting batch takes\n * new transactions until a statement is queued after it.\n */\ninterface PendingBatch {\n\treadonly members: QueuedTransaction[];\n\tposition: number;\n\topen: boolean;\n}\n\ntype TransactionOutcome =\n\t| { readonly ok: true; readonly value: unknown }\n\t| { readonly ok: false; readonly error: unknown };\n\n/** One connection's use of the write lock over the last `WRITER_QUEUE_STATS_WINDOW_MS`, on the monotonic clock. */\nexport interface WriterQueueStats {\n\t/** Share of the window, 0 to 1, this connection held the write lock: from `BEGIN IMMEDIATE` to commit or rollback. */\n\treadonly lockHeldRatio: number;\n\t/** Writers waiting in the cross-process queue right now, in any process; 0 without a queue (in-memory, wrapped). */\n\treadonly waiters: number;\n\t/** Median time this connection's acquisitions in the window waited for the lock, in ms; 0 with none. */\n\treadonly p50WaitMs: number;\n\t/** 95th-percentile (nearest-rank) wait for the lock in the window, in ms; 0 with none. */\n\treadonly p95WaitMs: number;\n\t/** Commits by this connection per second over the window. */\n\treadonly commitsPerSecond: number;\n}\n\n/** Samples in time order; those older than the window are dropped as new ones arrive. */\nclass WindowSamples<T extends { readonly at: number }> {\n\tprivate items: T[] = [];\n\tprivate first = 0;\n\n\tpush(item: T): void {\n\t\tthis.items.push(item);\n\t\tthis.drop(item.at - WRITER_QUEUE_STATS_WINDOW_MS);\n\t}\n\n\tsince(from: number): T[] {\n\t\tthis.drop(from);\n\t\treturn this.items.slice(this.first);\n\t}\n\n\tprivate drop(before: number): void {\n\t\twhile (this.first < this.items.length && this.items[this.first]!.at < before) this.first += 1;\n\t\tif (this.first * 2 > this.items.length) {\n\t\t\tthis.items = this.items.slice(this.first);\n\t\t\tthis.first = 0;\n\t\t}\n\t}\n}\n\nfunction nearestRank(sorted: readonly number[], percentile: number): number {\n\tif (sorted.length === 0) return 0;\n\treturn sorted[Math.ceil((percentile / 100) * sorted.length) - 1]!;\n}\n\n/** Records when a connection waits for, holds, and commits through the write lock. */\nclass WriteLockUse {\n\tprivate readonly opened = performance.now();\n\tprivate heldSince?: number;\n\t/** Completed holds, by when they ended. */\n\tprivate readonly holds = new WindowSamples<{ readonly at: number; readonly start: number }>();\n\tprivate readonly commits = new WindowSamples<{ readonly at: number }>();\n\tprivate readonly waits = new WindowSamples<{ readonly at: number; readonly waitMs: number }>();\n\n\tacquired(waitStarted: number): void {\n\t\tconst now = performance.now();\n\t\tthis.heldSince = now;\n\t\tthis.waits.push({ at: now, waitMs: now - waitStarted });\n\t}\n\n\treleased(committed: boolean): void {\n\t\tconst now = performance.now();\n\t\tthis.holds.push({ at: now, start: this.heldSince ?? now });\n\t\tthis.heldSince = undefined;\n\t\tif (committed) this.commits.push({ at: now });\n\t}\n\n\tstats(waiters: number): WriterQueueStats {\n\t\tconst now = performance.now();\n\t\tconst windowMs = Math.min(WRITER_QUEUE_STATS_WINDOW_MS, now - this.opened);\n\t\tif (windowMs <= 0) return { lockHeldRatio: 0, waiters, p50WaitMs: 0, p95WaitMs: 0, commitsPerSecond: 0 };\n\t\tconst from = now - windowMs;\n\t\tlet heldMs = this.heldSince === undefined ? 0 : now - Math.max(this.heldSince, from);\n\t\tfor (const hold of this.holds.since(from)) heldMs += hold.at - Math.max(hold.start, from);\n\t\tconst waits = this.waits\n\t\t\t.since(from)\n\t\t\t.map((wait) => wait.waitMs)\n\t\t\t.sort((a, b) => a - b);\n\t\treturn {\n\t\t\tlockHeldRatio: Math.min(1, heldMs / windowMs),\n\t\t\twaiters,\n\t\t\tp50WaitMs: nearestRank(waits, 50),\n\t\t\tp95WaitMs: nearestRank(waits, 95),\n\t\t\tcommitsPerSecond: this.commits.since(from).length / (windowMs / 1000),\n\t\t};\n\t}\n}\n\n/** The driver's own reason, kept in the error message so it survives relays that forward only `message`. */\nfunction sqliteFailureDetail(cause: unknown): string | undefined {\n\tif (!(cause instanceof Error) || cause.message === \"\") return undefined;\n\tconst code = (cause as { errcode?: unknown }).errcode;\n\treturn typeof code === \"number\" ? `${cause.message} (SQLite code ${code})` : cause.message;\n}\n\nfunction unavailable(descriptor: StorageDescriptor, cause: unknown, detail = sqliteFailureDetail(cause)) {\n\t// A value over SQLite's length limit fails the same way every time: permanent, never an outage (#4954).\n\tif (payloadTooLargeKind(cause as StorageFailureCause) !== undefined) {\n\t\treturn new StoragePayloadTooLargeError(SQLITE_PAYLOAD_LIMITS.value ?? 0, 0, {\n\t\t\tdescriptor,\n\t\t\tcause: cause as StorageFailureCause,\n\t\t});\n\t}\n\treturn new StorageUnavailableError(descriptor, cause as StorageFailureCause, detail);\n}\n\nfunction normalizeRow(row: Record<string, SqliteValue>): SqliteRow {\n\treturn Object.fromEntries(\n\t\tObject.entries(row).map(([key, value]) => [\n\t\t\tkey,\n\t\t\ttypeof value === \"bigint\" &&\n\t\t\tvalue >= -BigInt(Number.MAX_SAFE_INTEGER) &&\n\t\t\tvalue <= BigInt(Number.MAX_SAFE_INTEGER)\n\t\t\t\t? Number(value)\n\t\t\t\t: value instanceof Uint8Array\n\t\t\t\t\t? new Uint8Array(value)\n\t\t\t\t\t: value,\n\t\t]),\n\t);\n}\n\nclass NodeSqliteDatabase implements SqliteDatabase {\n\treadonly descriptor: StorageDescriptor;\n\tprivate readonly connection: DatabaseSync;\n\tprivate jsonbExtract?: Promise<boolean>;\n\tprivate tail: Promise<void> = Promise.resolve();\n\t/** Operations queued on this connection so far; a batch's `position` is the one that commits it. */\n\tprivate enqueued = 0;\n\t/** Batches whose commit has not started, in order; the last one takes new transactions while it is open. */\n\tprivate readonly waitingBatches: PendingBatch[] = [];\n\tprivate closing = false;\n\tprivate closePromise?: Promise<void>;\n\tprivate readonly executor: ReturnType<NodeSqliteDatabase[\"createExecutor\"]>;\n\n\tprivate readonly ownsConnection: boolean;\n\tprivate readonly transactionIdentity: string | DatabaseSync;\n\tprivate readonly lockWaitMs: number;\n\tprivate readonly groupCommitHoldMs: number;\n\t/** Cross-process first-come-first-served order for the write lock; absent for in-memory databases. */\n\tprivate readonly writeQueue?: SqliteWriteQueue;\n\t/** This connection's record of when it holds the write lock, named in the error of a writer that gives up. */\n\tprivate readonly holderRecord?: SqliteHolderRecord;\n\tprivate readonly openLock?: HeldOpenLock;\n\tprivate readonly lockUse = new WriteLockUse();\n\t/** The ticket of the writer holding the lock, on its way out of the queue while the transaction runs. */\n\tprivate leaving?: { readonly ticket: string; readonly left: Promise<void> };\n\t/** What the writers' queue gave up on, once per reason, in the order it first happened. */\n\tprivate readonly degradations = new Map<StorageWriterQueueDegradedReason, StorageWriterQueueDegradedError>();\n\n\tconstructor(\n\t\tconnection: DatabaseSync,\n\t\tdescriptor: StorageDescriptor,\n\t\townsConnection = true,\n\t\ttransactionIdentity: string | DatabaseSync = connection,\n\t\tlockWaitMs = DEFAULT_NODE_SQLITE_LOCK_WAIT_MS,\n\t\tgroupCommitHoldMs = DEFAULT_GROUP_COMMIT_HOLD_MS,\n\t\topenLock?: HeldOpenLock,\n\t) {\n\t\tthis.lockWaitMs = lockWaitMs;\n\t\tthis.groupCommitHoldMs = groupCommitHoldMs;\n\t\tthis.transactionIdentity = transactionIdentity;\n\t\tthis.ownsConnection = ownsConnection;\n\t\tthis.connection = connection;\n\t\tthis.descriptor = descriptor;\n\t\tthis.openLock = openLock;\n\t\tthis.executor = this.createExecutor(() => true);\n\t\tif (typeof transactionIdentity === \"string\") {\n\t\t\tthis.writeQueue = new SqliteWriteQueue(\n\t\t\t\ttransactionIdentity,\n\t\t\t\t(reason, cause) => this.degraded(reason, cause),\n\t\t\t\t() => databaseNow(connection.constructor as typeof DatabaseSync),\n\t\t\t);\n\t\t\tthis.holderRecord = new SqliteHolderRecord(transactionIdentity, (cause) =>\n\t\t\t\tthis.degraded(\"holder-record-unavailable\", cause),\n\t\t\t);\n\t\t}\n\t}\n\n\tsupportsJsonbExtract(): Promise<boolean> {\n\t\t// Bun on macOS loads the system SQLite. Its functions need not match the build-time version.\n\t\tthis.jsonbExtract ??= this.enqueueStatement(() => this.executor.checkJsonbExtract()).catch(() => {\n\t\t\t// A schema lock can also prevent preparation. Don't remember it as a missing function.\n\t\t\tthis.jsonbExtract = undefined;\n\t\t\treturn false;\n\t\t});\n\t\treturn this.jsonbExtract;\n\t}\n\n\t/**\n\t * The bytes this process may still write on the file system that holds the database file (where a link to it points,\n\t * and where its write-ahead log goes), or undefined for a database in memory or when the file system does not say.\n\t */\n\tasync freeBytes(): Promise<number | undefined> {\n\t\tconst path = this.descriptor.location;\n\t\tif (path === \"\" || path === \":memory:\") return undefined;\n\t\ttry {\n\t\t\t// The file itself, not its directory: a link to a database on another file system measures that file system.\n\t\t\tconst { bavail, bsize } = await statfs(path);\n\t\t\treturn Number(bavail) * Number(bsize);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\t/** Creates this connection's write-lock record; see `SqliteHolderRecord`. */\n\tasync openHolderRecord(): Promise<void> {\n\t\tawait this.holderRecord?.open();\n\t}\n\n\twriterQueueStats(): WriterQueueStats {\n\t\treturn this.lockUse.stats(this.queueOp(() => this.writeQueue?.liveTickets().length ?? 0));\n\t}\n\n\tprivate driver<T>(operation: () => T): T {\n\t\ttry {\n\t\t\treturn operation();\n\t\t} catch (cause) {\n\t\t\tthrow unavailable(this.descriptor, cause);\n\t\t}\n\t}\n\n\t/**\n\t * One non-blocking `BEGIN IMMEDIATE`. node:sqlite runs `busy_timeout` synchronously, so a lock held by another\n\t * process would freeze this process's event loop for the whole timeout. The attempt runs with `busy_timeout=0`\n\t * and the connection's own value is restored before returning or throwing, so single statements outside a\n\t * transaction keep it. Callers reach this only through `enqueue` and the transaction gate, so nothing else runs\n\t * on the connection in between.\n\t */\n\tprivate tryBegin(): void {\n\t\tthis.driver(() => {\n\t\t\tconst configured = Number(this.connection.prepare(\"PRAGMA busy_timeout\").get()?.timeout ?? 0);\n\t\t\tthis.connection.exec(\"PRAGMA busy_timeout=0\");\n\t\t\tlet began = false;\n\t\t\ttry {\n\t\t\t\tthis.connection.exec(\"BEGIN IMMEDIATE\");\n\t\t\t\tbegan = true;\n\t\t\t} finally {\n\t\t\t\ttry {\n\t\t\t\t\tthis.connection.exec(`PRAGMA busy_timeout=${configured}`);\n\t\t\t\t} catch (restoreFailure) {\n\t\t\t\t\t// Never hand back a transaction on a connection whose lock wait is no longer the configured one.\n\t\t\t\t\tif (began) this.connection.exec(\"ROLLBACK\");\n\t\t\t\t\t// biome-ignore lint/correctness/noUnsafeFinally: a failed restore must replace the attempt's outcome.\n\t\t\t\t\tthrow restoreFailure;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\t/** Changes whenever another connection commits to the database: the lock is being used, not held idle. */\n\tprivate dataVersion(): number {\n\t\treturn this.driver(() => Number(this.connection.prepare(\"PRAGMA data_version\").get()?.data_version ?? 0));\n\t}\n\n\t/**\n\t * Takes the write lock without blocking the event loop. Nothing has run yet when `BEGIN IMMEDIATE` reports\n\t * SQLITE_BUSY, so the attempt is retried. A refused writer queues with writers in other processes and attempts the\n\t * lock only when no earlier writer is still waiting, so none starves (#3978). It attempts again the moment the\n\t * writer releasing the lock touches its ticket (#4316), and otherwise when its recheck timer fires. The wait ends\n\t * only when no other connection has committed for `lockWaitMs`, whether this writer is still queued or already\n\t * trying the lock: a queued writer counts only real commits as progress, not older tickets ahead of it. The\n\t * `StorageWriteLockTimeoutError` of a writer that gives up names the process holding the lock. Every other failure,\n\t * including a writers' queue that cannot be used, rejects at once with its cause.\n\t */\n\tprivate async begin(lockWaitMs = this.lockWaitMs): Promise<void> {\n\t\tconst waitStarted = performance.now();\n\t\tlet ticket: SqliteWriteTicket | undefined;\n\t\tlet notices: ReleaseNotices | undefined;\n\t\tlet holding = false;\n\t\ttry {\n\t\t\t// Before its first attempt, so a holder stopped or starved the moment it takes the lock is still named.\n\t\t\tawait this.holderRecord?.trying();\n\t\t\t// Writers already waiting in other processes go first.\n\t\t\tconst queue = this.writeQueue;\n\t\t\tqueue?.observe();\n\t\t\tif (queue !== undefined && (await queue.contendedOffLoop())) {\n\t\t\t\tconst waiting = await this.queueFileOp(() => queue.liveTicketsOffLoop());\n\t\t\t\tif (waiting.length > 0) ticket = await this.queueFileOp(() => queue.join(waiting));\n\t\t\t}\n\t\t\t// Read only once this writer waits, so an uncontended transaction pays nothing for it.\n\t\t\tlet version = ticket === undefined ? undefined : this.dataVersion();\n\t\t\tlet stalledSince = performance.now();\n\t\t\tlet lastCause: unknown;\n\t\t\tfor (;;) {\n\t\t\t\tnotices?.clear();\n\t\t\t\tif (ticket !== undefined) notices = await this.watchTicket(ticket, notices);\n\t\t\t\tconst behind = ticket !== undefined && (await this.queueFileOp(() => ticket!.behindOthers()));\n\t\t\t\tif (!behind) {\n\t\t\t\t\tconst refused = this.attemptBegin();\n\t\t\t\t\tif (refused === undefined) {\n\t\t\t\t\t\tholding = true;\n\t\t\t\t\t\tthis.acquired(waitStarted);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tlastCause = refused;\n\t\t\t\t\tif (ticket === undefined && queue !== undefined) {\n\t\t\t\t\t\t// A release before this ticket existed told nobody: watch it, then try once more before waiting.\n\t\t\t\t\t\tticket = await this.queueFileOp(async () => queue.join(await queue.liveTicketsOffLoop()));\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Only another connection's commit is progress; a queued writer measures its stall the same way.\n\t\t\t\tconst current = this.dataVersion();\n\t\t\t\tconst committed = version !== undefined && current !== version;\n\t\t\t\tif (version === undefined) version = current;\n\t\t\t\telse if (committed) {\n\t\t\t\t\tversion = current;\n\t\t\t\t\tstalledSince = performance.now();\n\t\t\t\t}\n\t\t\t\tconst stalledMs = performance.now() - stalledSince;\n\t\t\t\tif (stalledMs >= lockWaitMs) throw await this.lockWaitTimeout(lockWaitMs, stalledMs, behind, lastCause);\n\t\t\t\tif (!behind && committed && (await this.attemptThroughRelease())) {\n\t\t\t\t\tholding = true;\n\t\t\t\t\tthis.acquired(waitStarted);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst recheckMs =\n\t\t\t\t\tnotices?.watching === true || stalledMs >= this.lockWaitMs\n\t\t\t\t\t\t? LOCK_WAIT_RECHECK_MS\n\t\t\t\t\t\t: UNWATCHED_LOCK_RETRY_MS;\n\t\t\t\tconst delay = Math.min(recheckMs, lockWaitMs - stalledMs);\n\t\t\t\tawait (notices?.wait(delay) ?? new Promise<void>((resolve) => setTimeout(resolve, delay)));\n\t\t\t}\n\t\t} finally {\n\t\t\tnotices?.close();\n\t\t\t// A writer holding the lock never waits for the queue's files: another connection of this process that writes\n\t\t\t// meanwhile waits for the lock in SQLite's busy handler, which blocks this thread until the lock is free, so\n\t\t\t// the holder could not go on. Its ticket leaves while the transaction runs; the release waits for it to be gone.\n\t\t\tif (holding && ticket !== undefined) this.leaving = { ticket: ticket.name, left: ticket.leave() };\n\t\t\telse await ticket?.leave();\n\t\t\tif (!holding) await this.holderRecord?.free();\n\t\t}\n\t}\n\n\t/** One attempt at the lock: `undefined` once it is taken, or the SQLITE_BUSY that refused it. Anything else throws. */\n\tprivate attemptBegin(): unknown {\n\t\ttry {\n\t\t\tthis.tryBegin();\n\t\t\treturn undefined;\n\t\t} catch (error) {\n\t\t\tconst cause = error instanceof StorageUnavailableError ? error.cause : undefined;\n\t\t\tif (!isSqliteBusy(cause)) throw error;\n\t\t\treturn cause;\n\t\t}\n\t}\n\n\t/**\n\t * After a refused attempt, while other connections are committing through the lock, keeps attempting it on every\n\t * event-loop turn for `LOCK_RELEASE_RETRY_MS`; returns whether it took the lock. A timer only ever wakes this writer\n\t * on the system's timer tick, and on Windows that tick is 15.6 ms, shared by every process: a writer that does\n\t * not queue (a raw SQLite client, an older Atomic) and takes the lock again from its own timer does so on the same\n\t * tick, so the lock is free only between ticks and a writer that tried only when its timer fired never found it\n\t * free while that writer kept committing. Trying on every turn for a tick finds the lock the moment such a\n\t * writer's commit lets go of it.\n\t */\n\tprivate async attemptThroughRelease(): Promise<boolean> {\n\t\tconst until = performance.now() + LOCK_RELEASE_RETRY_MS;\n\t\tfor (let attempt = 0; attempt < LOCK_RELEASE_RETRY_ATTEMPTS && performance.now() < until; attempt++) {\n\t\t\tawait new Promise<void>((resolve) => setImmediate(resolve));\n\t\t\tif (this.attemptBegin() === undefined) return true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Keeps the ticket live and watched: one watch for the whole wait, started again only when the ticket had to be\n\t * recreated, since a watch ends with the file it watched.\n\t */\n\tprivate async watchTicket(ticket: SqliteWriteTicket, notices: ReleaseNotices | undefined): Promise<ReleaseNotices> {\n\t\tconst recreated = await this.queueFileOp(() => ticket.keepLive());\n\t\tif (notices !== undefined && !recreated) return notices;\n\t\tnotices?.close();\n\t\treturn ticket.watch((cause) => this.degraded(\"watch-unavailable\", cause));\n\t}\n\n\tprivate async lockWaitTimeout(\n\t\tlockWaitMs: number,\n\t\tstalledMs: number,\n\t\tbehind: boolean,\n\t\tlastCause: unknown,\n\t): Promise<StorageWriteLockTimeoutError> {\n\t\tconst holder = await this.holderRecord?.latestHolder();\n\t\treturn new StorageWriteLockTimeoutError(\n\t\t\tthis.descriptor,\n\t\t\t{\n\t\t\t\ttimeoutMs: lockWaitMs,\n\t\t\t\telapsedMs: Math.round(stalledMs),\n\t\t\t\tphase: behind ? \"queued\" : \"acquiring\",\n\t\t\t\t...(holder !== undefined && \"pid\" in holder ? { holderPid: holder.pid, holderHeldMs: holder.heldMs } : {}),\n\t\t\t\t...(holder !== undefined && \"candidates\" in holder\n\t\t\t\t\t? { holderCandidates: holder.candidates.join(\", \") }\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t\tlastCause as StorageFailureCause,\n\t\t);\n\t}\n\n\tprivate acquired(waitStarted: number): void {\n\t\tthis.holderRecord?.held();\n\t\tthis.lockUse.acquired(waitStarted);\n\t}\n\n\t/**\n\t * Runs the moment COMMIT or ROLLBACK lets go of the write lock, before any caller settles, so no caller's work can\n\t * delay the next writer: it hands the turn to the oldest writer waiting in another process. A turn that cannot be\n\t * handed on is still noticed by that writer's recheck timer, so it never fails the transaction.\n\t */\n\tprivate async released(committed: boolean): Promise<void> {\n\t\tthis.lockUse.released(committed);\n\t\tconst recorded = this.holderRecord?.free();\n\t\tconst leaving = this.leaving;\n\t\tthis.leaving = undefined;\n\t\t// Gone before the turn is handed on, so the writer it wakes finds no ticket of this one ahead of it.\n\t\tawait leaving?.left;\n\t\ttry {\n\t\t\tawait this.writeQueue?.wakeNext(leaving?.ticket);\n\t\t} catch (cause) {\n\t\t\tthis.degraded(\"wake-failed\", cause);\n\t\t}\n\t\tawait recorded;\n\t}\n\n\t/**\n\t * Records a degradation of the writers' queue once per reason, then emits it as a process warning for hosts that\n\t * listen for one. The record is what stays readable where warnings are suppressed, as in Atomic's own processes;\n\t * nothing fails.\n\t */\n\tprivate degraded(reason: StorageWriterQueueDegradedReason, cause: unknown): void {\n\t\tif (this.degradations.has(reason)) return;\n\t\tconst degradation = new StorageWriterQueueDegradedError(this.descriptor, reason, cause as StorageFailureCause);\n\t\tthis.degradations.set(reason, degradation);\n\t\tprocess.emitWarning(degradation);\n\t\treportDegradationInDebugMode(degradation);\n\t}\n\n\twriterQueueDegradation(): readonly StorageWriterQueueDegradedError[] {\n\t\treturn [...this.degradations.values()];\n\t}\n\n\t/** Runs a writers'-queue file operation; a failure (an unwritable queue directory, say) is a typed storage failure. */\n\tprivate queueOp<T>(operation: () => T): T {\n\t\ttry {\n\t\t\treturn operation();\n\t\t} catch (cause) {\n\t\t\tthrow new StorageWriterQueueUnusableError(this.descriptor, cause as StorageFailureCause);\n\t\t}\n\t}\n\n\t/** `queueOp` for the file work a waiting writer does off the event loop. */\n\tprivate async queueFileOp<T>(operation: () => Promise<T>): Promise<T> {\n\t\ttry {\n\t\t\treturn await operation();\n\t\t} catch (cause) {\n\t\t\tthrow new StorageWriterQueueUnusableError(this.descriptor, cause as StorageFailureCause);\n\t\t}\n\t}\n\n\tprivate createExecutor(active: () => boolean): SqliteExecutor & { checkJsonbExtract(): Promise<boolean> } {\n\t\tconst execute = async <T>(operation: () => T, params: readonly SqliteValue[] = []): Promise<T> => {\n\t\t\tif (!active()) throw new StorageTransactionClosedError();\n\t\t\tconst invalidIndex = params.findIndex((value) => typeof value === \"string\" && value.includes(\"\\0\"));\n\t\t\tif (invalidIndex !== -1) throw new StorageInvalidTextError(invalidIndex);\n\t\t\treturn this.driver(operation);\n\t\t};\n\t\tconst statement = (sql: string) => {\n\t\t\tconst prepared = this.connection.prepare(sql);\n\t\t\tprepared.setReadBigInts(true);\n\t\t\treturn prepared;\n\t\t};\n\t\treturn {\n\t\t\tcheckJsonbExtract: () =>\n\t\t\t\texecute(() => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tstatement(\"SELECT jsonb_extract('[]', '$')\");\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (error instanceof Error && error.message === \"no such function: jsonb_extract\") return false;\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\texec: (sql) => execute(() => this.connection.exec(sql)),\n\t\t\trun: (sql, ...params) => execute(() => ({ changes: Number(statement(sql).run(...params).changes) }), params),\n\t\t\tget: <T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]) =>\n\t\t\t\texecute(() => {\n\t\t\t\t\tconst row = statement(sql).get(...params);\n\t\t\t\t\treturn row === undefined ? undefined : (normalizeRow(row) as T);\n\t\t\t\t}, params),\n\t\t\tall: <T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]) =>\n\t\t\t\texecute(\n\t\t\t\t\t() =>\n\t\t\t\t\t\tstatement(sql)\n\t\t\t\t\t\t\t.all(...params)\n\t\t\t\t\t\t\t.map((row) => normalizeRow(row) as T),\n\t\t\t\t\tparams,\n\t\t\t\t),\n\t\t};\n\t}\n\n\tprivate enqueue<T>(operation: () => Promise<T>): Promise<T> {\n\t\tif (this.closing) return Promise.reject(new StoreClosedError(this.descriptor));\n\t\tthis.enqueued += 1;\n\t\tconst result = this.tail.then(operation);\n\t\tthis.tail = result.then(\n\t\t\t() => {},\n\t\t\t() => {},\n\t\t);\n\t\treturn result;\n\t}\n\n\t/** A statement queued after open transactions runs after them, so later transactions start a new batch. */\n\tprivate enqueueStatement<T>(operation: () => Promise<T>): Promise<T> {\n\t\tconst last = this.waitingBatches.at(-1);\n\t\tif (last !== undefined) last.open = false;\n\t\treturn this.enqueue(operation);\n\t}\n\n\texec(sql: string): Promise<void> {\n\t\treturn this.enqueueStatement(() => this.executor.exec(sql));\n\t}\n\n\trun(sql: string, ...params: readonly SqliteValue[]) {\n\t\tconst bound = snapshotParams(params);\n\t\treturn this.enqueueStatement(() => this.executor.run(sql, ...bound));\n\t}\n\n\tget<T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]): Promise<T | undefined> {\n\t\tconst bound = snapshotParams(params);\n\t\treturn this.enqueueStatement(() => this.executor.get<T>(sql, ...bound));\n\t}\n\n\tall<T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]): Promise<T[]> {\n\t\tconst bound = snapshotParams(params);\n\t\treturn this.enqueueStatement(() => this.executor.all<T>(sql, ...bound));\n\t}\n\n\t/** Idle-only housekeeping: do not join a batch, wait behind an operation on this handle or another handle's\n\t * transaction, or get in front of writers already waiting on another process. */\n\tasync tryMaintenance(callback: (tx: SqliteExecutor) => Promise<void>): Promise<boolean> {\n\t\tconst position = this.enqueued;\n\t\tlet idle = false;\n\t\tvoid this.tail.then(() => {\n\t\t\tidle = true;\n\t\t});\n\t\tawait Promise.resolve();\n\t\tif (!idle || this.enqueued !== position || this.closing) return false;\n\t\treturn this.enqueueStatement(async () => {\n\t\t\tconst key = this.transactionIdentity;\n\t\t\tif (typeof key === \"string\" ? gates.files.has(key) : gates.connections.has(key)) return false;\n\t\t\treturn gateTransaction(key, async () => {\n\t\t\t\t// The queue's directory outlives its writers: only a live ticket means a writer is waiting. One that cannot be\n\t\t\t\t// read counts as a writer waiting.\n\t\t\t\tconst queue = this.writeQueue;\n\t\t\t\tif (queue !== undefined && (await queue.contendedOffLoop())) {\n\t\t\t\t\tconst waiting = await queue.liveTicketsOffLoop().catch(() => undefined);\n\t\t\t\t\tif (waiting === undefined || waiting.length > 0) return false;\n\t\t\t\t}\n\t\t\t\tconst start = performance.now();\n\t\t\t\tawait this.holderRecord?.trying();\n\t\t\t\ttry {\n\t\t\t\t\tif (this.attemptBegin() !== undefined) {\n\t\t\t\t\t\tawait this.holderRecord?.free();\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tawait this.holderRecord?.free();\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tthis.acquired(start);\n\t\t\t\treturn new Promise<boolean>((resolve, reject) => {\n\t\t\t\t\tvoid this.commitAlone({ callback, resolve: () => resolve(true), reject }).catch(reject);\n\t\t\t\t});\n\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Group commit: transactions queued while earlier work holds the connection join one `BEGIN IMMEDIATE … COMMIT`,\n\t * each inside its own savepoint and in the order they were requested. A transaction that throws rolls back only\n\t * its savepoint and rejects only its caller; every caller settles after the shared commit, so durability is the\n\t * same as a transaction of its own. Under load one lock acquisition and one sync serve the whole batch, including\n\t * the transactions requested while it waited for the lock. A batch waits for the lock as long as the most patient\n\t * of its transactions.\n\t */\n\ttransaction<T>(\n\t\tcallback: (transaction: SqliteExecutor) => Promise<T>,\n\t\toptions?: SqliteTransactionOptions,\n\t): Promise<T> {\n\t\tif (options?.readOnly === true) {\n\t\t\treturn this.enqueueStatement(async () => {\n\t\t\t\tawait this.executor.exec(\"BEGIN\");\n\t\t\t\tlet active = true;\n\t\t\t\ttry {\n\t\t\t\t\tconst value = await callback(this.createExecutor(() => active));\n\t\t\t\t\tactive = false;\n\t\t\t\t\tawait this.executor.exec(\"COMMIT\");\n\t\t\t\t\treturn value;\n\t\t\t\t} catch (cause) {\n\t\t\t\t\tactive = false;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.executor.exec(\"ROLLBACK\");\n\t\t\t\t\t} catch (rollbackCause) {\n\t\t\t\t\t\tthrow new StorageRollbackError(cause as StorageFailureCause, rollbackCause as StorageFailureCause);\n\t\t\t\t\t}\n\t\t\t\t\tthrow cause;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\tif (this.closing) return Promise.reject(new StoreClosedError(this.descriptor));\n\t\treturn new Promise<T>((resolve, reject) => {\n\t\t\tconst queued: QueuedTransaction = {\n\t\t\t\tcallback,\n\t\t\t\tresolve: resolve as (value: unknown) => void,\n\t\t\t\treject,\n\t\t\t\tlockWaitMs: options?.lockWaitMs,\n\t\t\t};\n\t\t\tconst last = this.waitingBatches.at(-1);\n\t\t\tif (last?.open === true && last.members.length < MAX_GROUP_COMMIT_TRANSACTIONS) {\n\t\t\t\tlast.members.push(queued);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.startBatch([queued]);\n\t\t});\n\t}\n\n\tprivate startBatch(members: QueuedTransaction[]): void {\n\t\tconst batch: PendingBatch = { members, position: 0, open: true };\n\t\tthis.waitingBatches.push(batch);\n\t\tvoid this.enqueue(() => this.commitBatch(batch));\n\t\tbatch.position = this.enqueued;\n\t}\n\n\tprivate commitBatch(batch: PendingBatch): Promise<void> {\n\t\t// The batch ahead of it took its transactions along when it got the lock.\n\t\tif (this.waitingBatches[0] !== batch) return Promise.resolve();\n\t\tthis.waitingBatches.shift();\n\t\treturn gateTransaction(this.transactionIdentity, () => this.runBatch(batch, true));\n\t}\n\n\t/**\n\t * Takes the write lock for the batch, then commits it on its own or as a group. On its first acquisition the\n\t * transactions requested directly behind it while it waited join it: otherwise they would queue for the lock all\n\t * over again once it lets go. Members left after the hold budget take the lock again with nothing new, so other\n\t * connections to the file wait for at most one batch of this one's.\n\t */\n\tprivate async runBatch(batch: PendingBatch, firstAcquisition: boolean): Promise<void> {\n\t\ttry {\n\t\t\tawait this.begin(this.lockWait(batch.members));\n\t\t} catch (cause) {\n\t\t\tfor (const queued of batch.members.splice(0)) queued.reject(cause);\n\t\t\treturn;\n\t\t}\n\t\tif (firstAcquisition) this.absorbNext(batch);\n\t\tawait (batch.members.length === 1 ? this.commitAlone(batch.members.pop()!) : this.commitMembers(batch));\n\t}\n\n\t/**\n\t * Moves the transactions of the batches queued directly behind this one (no statement between them) into this one,\n\t * up to the batch size limit. They run after this batch's own, in the order they were requested.\n\t */\n\tprivate absorbNext(batch: PendingBatch): void {\n\t\tfor (let next = this.waitingBatches[0]; next?.position === batch.position + 1; next = this.waitingBatches[0]) {\n\t\t\tbatch.members.push(...next.members.splice(0, MAX_GROUP_COMMIT_TRANSACTIONS - batch.members.length));\n\t\t\tif (next.members.length > 0) return;\n\t\t\tthis.waitingBatches.shift();\n\t\t\tbatch.position = next.position;\n\t\t}\n\t}\n\n\tprivate lockWait(batch: readonly QueuedTransaction[]): number {\n\t\treturn Math.max(...batch.map((queued) => queued.lockWaitMs ?? this.lockWaitMs));\n\t}\n\n\t/** A transaction with nobody queued with it commits on its own, without savepoints. */\n\tprivate async commitAlone(queued: QueuedTransaction): Promise<void> {\n\t\tlet active = true;\n\t\ttry {\n\t\t\tconst value = await queued.callback(this.createExecutor(() => active));\n\t\t\tactive = false;\n\t\t\tawait this.executor.exec(\"COMMIT\");\n\t\t\tawait this.released(true);\n\t\t\tqueued.resolve(value);\n\t\t} catch (cause) {\n\t\t\tactive = false;\n\t\t\ttry {\n\t\t\t\tawait this.executor.exec(\"ROLLBACK\");\n\t\t\t} catch (rollbackCause) {\n\t\t\t\tawait this.released(false);\n\t\t\t\tqueued.reject(new StorageRollbackError(cause as StorageFailureCause, rollbackCause as StorageFailureCause));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait this.released(false);\n\t\t\tqueued.reject(cause);\n\t\t}\n\t}\n\n\t/**\n\t * Runs the batch's members in one transaction, for at most `groupCommitHoldMs`: members left when it runs out\n\t * wait for the lock again, still ahead of anything queued after them.\n\t */\n\tprivate async commitMembers(batch: PendingBatch): Promise<void> {\n\t\tconst began = performance.now();\n\t\tconst outcomes: TransactionOutcome[] = [];\n\t\tfor (const queued of batch.members) {\n\t\t\tif (outcomes.length > 0 && performance.now() - began >= this.groupCommitHoldMs) break;\n\t\t\tconst savepoint = `atomic_group_${outcomes.length}`;\n\t\t\tlet active = true;\n\t\t\ttry {\n\t\t\t\tawait this.executor.exec(`SAVEPOINT ${savepoint}`);\n\t\t\t\tconst value = await queued.callback(this.createExecutor(() => active));\n\t\t\t\tactive = false;\n\t\t\t\tawait this.executor.exec(`RELEASE ${savepoint}`);\n\t\t\t\toutcomes.push({ ok: true, value });\n\t\t\t} catch (cause) {\n\t\t\t\tactive = false;\n\t\t\t\ttry {\n\t\t\t\t\tawait this.executor.exec(`ROLLBACK TO ${savepoint}`);\n\t\t\t\t\tawait this.executor.exec(`RELEASE ${savepoint}`);\n\t\t\t\t} catch (rollbackCause) {\n\t\t\t\t\tawait this.abandonMembers(batch, outcomes, cause, rollbackCause);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\toutcomes.push({ ok: false, error: cause });\n\t\t\t}\n\t\t}\n\t\tconst ran = batch.members.splice(0, outcomes.length);\n\t\tlet commitCause: unknown;\n\t\tlet committed = true;\n\t\ttry {\n\t\t\tawait this.executor.exec(\"COMMIT\");\n\t\t} catch (cause) {\n\t\t\tcommitted = false;\n\t\t\tcommitCause = cause;\n\t\t\tawait this.rollbackQuietly();\n\t\t}\n\t\tawait this.released(committed);\n\t\tran.forEach((queued, index) => {\n\t\t\tconst outcome = outcomes[index]!;\n\t\t\tif (!committed) queued.reject(outcome.ok ? commitCause : outcome.error);\n\t\t\telse if (outcome.ok) queued.resolve(outcome.value);\n\t\t\telse queued.reject(outcome.error);\n\t\t});\n\t\tif (batch.members.length > 0) await this.runBatch(batch, false);\n\t}\n\n\t/**\n\t * A savepoint that cannot be rolled back leaves the whole transaction unusable: earlier members lose their\n\t * uncommitted writes and fail, the failing member reports both causes, and members that have not run yet get a\n\t * fresh transaction right away, still ahead of anything queued after them, because nothing of theirs has happened.\n\t */\n\tprivate async abandonMembers(\n\t\tbatch: PendingBatch,\n\t\toutcomes: TransactionOutcome[],\n\t\tcause: unknown,\n\t\trollbackCause: unknown,\n\t): Promise<void> {\n\t\tawait this.rollbackQuietly();\n\t\tawait this.released(false);\n\t\tconst failed = outcomes.length;\n\t\tconst ran = batch.members.splice(0, failed + 1);\n\t\tran.slice(0, failed).forEach((queued, index) => {\n\t\t\tconst outcome = outcomes[index]!;\n\t\t\tqueued.reject(outcome.ok ? unavailable(this.descriptor, rollbackCause) : outcome.error);\n\t\t});\n\t\tran[failed]!.reject(new StorageRollbackError(cause as StorageFailureCause, rollbackCause as StorageFailureCause));\n\t\tif (batch.members.length > 0) await this.runBatch(batch, false);\n\t}\n\n\tprivate async rollbackQuietly(): Promise<void> {\n\t\ttry {\n\t\t\tawait this.executor.exec(\"ROLLBACK\");\n\t\t} catch {\n\t\t\t// SQLite already rolled the transaction back; there is nothing left to undo.\n\t\t}\n\t}\n\n\tclose(): Promise<void> {\n\t\tif (!this.closePromise) {\n\t\t\tthis.closing = true;\n\t\t\tthis.closePromise = this.tail.then(async () => {\n\t\t\t\ttry {\n\t\t\t\t\tawait this.holderRecord?.close();\n\t\t\t\t\tthis.driver(() => {\n\t\t\t\t\t\tif (this.ownsConnection) this.connection.close();\n\t\t\t\t\t\tfinalizeReleasedStatements();\n\t\t\t\t\t});\n\t\t\t\t} finally {\n\t\t\t\t\tawait releaseOpenLock(this.openLock);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\treturn this.closePromise;\n\t}\n}\n\n/** Rejects a group-commit budget that is not a finite number of milliseconds, 0 or more, before anything opens. */\nfunction groupCommitHold(value: number | undefined): number {\n\tif (value === undefined) return DEFAULT_GROUP_COMMIT_HOLD_MS;\n\tif (!Number.isFinite(value) || value < 0)\n\t\tthrow new StorageConfigError(\n\t\t\t\"sdk\",\n\t\t\t\"groupCommitHoldMs\",\n\t\t\t\"non-negative-finite-number-required\",\n\t\t\t`Pass a finite number of milliseconds, 0 or more, or omit it for the default of ${DEFAULT_GROUP_COMMIT_HOLD_MS} ms`,\n\t\t);\n\treturn value;\n}\n\n/**\n * Longest Windows database path SQLite opens as written. SQLite's Windows file calls fail a path, or the `-journal`,\n * `-wal` or `-shm` file beside it, over 260 characters (`MAX_PATH`) with code 14 (#5139); this leaves room for those.\n */\nconst WINDOWS_SQLITE_PLAIN_PATH_LIMIT = 240;\n\n/**\n * The path SQLite opens `path` by. On Windows a file path longer than SQLite can open as written takes the `\\\\?\\`\n * long-path form, which SQLite accepts at any length (#5139). Every other path, `:memory:`, `file:` URIs and every\n * path on other platforms are passed unchanged, so the database's location reads as before wherever it fits.\n */\nexport function sqliteFilePath(path: string, platform: NodeJS.Platform = process.platform): string {\n\tif (platform !== \"win32\" || path === \":memory:\" || path.startsWith(\"file:\")) return path;\n\treturn win32.resolve(path).length > WINDOWS_SQLITE_PLAIN_PATH_LIMIT ? win32.toNamespacedPath(path) : path;\n}\n\n/** `location` without the `\\\\?\\` or `\\\\?\\UNC\\` prefix of the Windows long-path form: the path it names. */\nexport function ordinarySqlitePath<T extends string | null>(location: T): T {\n\tif (location === null) return location;\n\tif (location.startsWith(\"\\\\\\\\?\\\\UNC\\\\\")) return `\\\\\\\\${location.slice(8)}` as T;\n\tif (location.startsWith(\"\\\\\\\\?\\\\\")) return location.slice(4) as T;\n\treturn location;\n}\n\n/**\n * Opens `path` with SQLite, through the long-path form when it needs it, and has the connection report its location as\n * the ordinary path, so every reader of it (identity, error messages, callers comparing paths) sees the path it was\n * given whatever its length (#5139).\n */\nfunction openConnection(Database: typeof DatabaseSync, path: string, readOnly: boolean): DatabaseSync {\n\tconst opened = sqliteFilePath(path);\n\tconst connection = new Database(opened, { readOnly });\n\tif (opened !== path) {\n\t\tconst location = connection.location.bind(connection);\n\t\tconnection.location = (name?: string) => ordinarySqlitePath(location(name));\n\t}\n\treturn connection;\n}\n\nexport async function openNodeSqliteDatabase(\n\tpath: string,\n\t{\n\t\tbusyTimeoutMs = 5000,\n\t\tlockWaitMs = DEFAULT_NODE_SQLITE_LOCK_WAIT_MS,\n\t\treadOnly = false,\n\t\tgroupCommitHoldMs,\n\t}: {\n\t\tbusyTimeoutMs?: number;\n\t\tlockWaitMs?: number;\n\t\treadOnly?: boolean;\n\t\t/**\n\t\t * How long one group commit runs queued transactions before it commits them and lets other processes' writers\n\t\t * take the lock (`DEFAULT_GROUP_COMMIT_HOLD_MS` when omitted). Checked between transactions, so one\n\t\t * transaction is never split. 0 commits each transaction on its own.\n\t\t */\n\t\tgroupCommitHoldMs?: number;\n\t} = {},\n): Promise<SqliteDatabase> {\n\tconst holdMs = groupCommitHold(groupCommitHoldMs);\n\tconst descriptor = { adapter: \"node-sqlite\", location: path };\n\t// Load node:sqlite on first open: importing it prints Node's experimental warning, which every importer of the\n\t// package entry point would otherwise see.\n\tlet Database: typeof DatabaseSync;\n\ttry {\n\t\t({ DatabaseSync: Database } = await import(\"node:sqlite\"));\n\t} catch (cause) {\n\t\tthrow new StorageAdapterLoadError(\"node:sqlite\", cause as StorageFailureCause);\n\t}\n\tconst targetFile = sqliteTargetFilePath(path);\n\tlet heldOpenLock: HeldOpenLock | undefined;\n\tlet connection: DatabaseSync | undefined;\n\ttry {\n\t\tif (!readOnly && targetFile !== undefined) await mkdir(dirname(targetFile), { recursive: true });\n\t\theldOpenLock = await acquireOpenLock(targetFile, readOnly, busyTimeoutMs);\n\t\tconnection = openConnection(Database, path, readOnly);\n\t\tconnection.exec(`PRAGMA busy_timeout=${busyTimeoutMs}`);\n\t\tif (!readOnly) {\n\t\t\tconst writable = connection;\n\t\t\t// SQLite does not wait for another process's lock while it changes the mode; the switch waits itself.\n\t\t\tawait switchToWriteAheadLog((sql) => writable.exec(sql), busyTimeoutMs);\n\t\t\twritable.exec(\"PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON\");\n\t\t}\n\t\tconst location = connection.location();\n\t\tconst identity =\n\t\t\tlocation === null\n\t\t\t\t? connection\n\t\t\t\t: heldOpenLock?.target !== undefined && location === targetFile\n\t\t\t\t\t? heldOpenLock.target\n\t\t\t\t\t: await realpath(location);\n\t\tif (typeof identity === \"string\" && heldOpenLock !== undefined && heldOpenLock.target !== identity) {\n\t\t\tawait releaseOpenLock(heldOpenLock);\n\t\t\theldOpenLock = await acquireOpenLock(identity, readOnly, busyTimeoutMs);\n\t\t}\n\t\tconst database = new NodeSqliteDatabase(connection, descriptor, true, identity, lockWaitMs, holdMs, heldOpenLock);\n\t\tObject.defineProperty(database, \"readOnly\", { value: readOnly });\n\t\tif (!readOnly) await database.openHolderRecord();\n\t\treturn database;\n\t} catch (cause) {\n\t\ttry {\n\t\t\tconnection?.close();\n\t\t} catch {\n\t\t\t// Preserve the opening failure if cleanup also fails.\n\t\t} finally {\n\t\t\tawait releaseOpenLock(heldOpenLock);\n\t\t}\n\t\tthrow unavailable(descriptor, cause);\n\t}\n}\n\n/** The busy timeout `wrapNodeSqliteDatabase` sets on a caller's connection. */\nconst WRAPPED_BUSY_TIMEOUT_MS = 5000;\n\nexport function wrapNodeSqliteDatabase(connection: DatabaseSync): SqliteDatabase {\n\tconst descriptor = { adapter: \"node-sqlite\", location: \":memory:\" };\n\tlet heldOpenLock: HeldOpenLock | undefined;\n\ttry {\n\t\tdescriptor.location = ordinarySqlitePath(connection.location()) || \":memory:\";\n\t\theldOpenLock = acquireOpenLockSync(descriptor.location);\n\t\tconnection.exec(`PRAGMA busy_timeout=${WRAPPED_BUSY_TIMEOUT_MS}`);\n\t\t// SQLite does not wait for another process's lock while it changes the mode; the switch waits itself.\n\t\tswitchToWriteAheadLogSync((sql) => connection.exec(sql), WRAPPED_BUSY_TIMEOUT_MS);\n\t\tconnection.exec(\"PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON\");\n\t\treturn new NodeSqliteDatabase(connection, descriptor, false, connection, undefined, undefined, heldOpenLock);\n\t} catch (cause) {\n\t\tvoid releaseOpenLock(heldOpenLock);\n\t\tthrow unavailable(descriptor, cause);\n\t}\n}\n\n/**\n * How one database handle has used the write lock over the last 10 seconds, and how many writers wait for it now in\n * any process. Throws `StorageUnsupportedOperationError` for a handle that `openNodeSqliteDatabase` or\n * `wrapNodeSqliteDatabase` did not return, and `StorageUnavailableError` when the writers' queue cannot be read.\n */\nexport function getWriterQueueStats(database: SqliteDatabase): WriterQueueStats {\n\tif (!(database instanceof NodeSqliteDatabase))\n\t\tthrow new StorageUnsupportedOperationError(database.descriptor, \"getWriterQueueStats\");\n\treturn database.writerQueueStats();\n}\n\n/**\n * What the writers' queue of a database handle has given up on, once per reason in the order it first happened, as\n * `StorageWriterQueueDegradedError`s: a waiting writer that cannot watch its ticket, a writer that could not notify\n * the next one, an abandoned ticket that could not be removed. Empty while the queue is healthy, and for a handle\n * without a cross-process queue (in-memory or wrapped). Transactions keep working through each of them; the same\n * errors are also emitted as process warnings, which Atomic's own processes suppress. Throws\n * `StorageUnsupportedOperationError` for a handle that `openNodeSqliteDatabase` or `wrapNodeSqliteDatabase` did not\n * return.\n */\nexport function getWriterQueueDegradation(database: SqliteDatabase): readonly StorageWriterQueueDegradedError[] {\n\tif (!(database instanceof NodeSqliteDatabase))\n\t\tthrow new StorageUnsupportedOperationError(database.descriptor, \"getWriterQueueDegradation\");\n\treturn database.writerQueueDegradation();\n}\n"]}
1
+ {"version":3,"file":"node-sqlite.js","sourceRoot":"","sources":["../../../src/core/storage/node-sqlite.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,EACL,UAAU,EAEV,IAAI,EACJ,WAAW,EACX,YAAY,EACZ,QAAQ,EACR,UAAU,EACV,KAAK,EACL,KAAK,GACL,MAAM,SAAS,CAAC;AACjB,OAAO,EACN,KAAK,EACL,KAAK,EACL,OAAO,EACP,QAAQ,EACR,QAAQ,EACR,EAAE,EACF,IAAI,EACJ,MAAM,EACN,MAAM,EACN,MAAM,EACN,SAAS,GACT,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnC,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE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B,EAAE,CAAC;AAC1C,CAAC","sourcesContent":["import {\n\tclose,\n\texistsSync,\n\ttype FSWatcher,\n\topen,\n\treaddirSync,\n\trealpathSync,\n\tstatSync,\n\tunlinkSync,\n\twatch,\n\twrite,\n} from \"node:fs\";\nimport {\n\tlstat,\n\tmkdir,\n\treaddir,\n\treadFile,\n\trealpath,\n\trm,\n\tstat,\n\tstatfs,\n\tunlink,\n\tutimes,\n\twriteFile,\n} from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport { platform } from \"node:os\";\nimport { basename, dirname, join, resolve, win32 } from \"node:path\";\nimport type { DatabaseSync } from \"node:sqlite\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { promisify } from \"node:util\";\nimport { isSharedArrayBuffer, isUint8Array } from \"node:util/types\";\nimport type * as native from \"@bastani/atomic-natives\";\nimport type {\n\tSqliteDatabase,\n\tSqliteExecutor,\n\tSqliteRow,\n\tSqliteTransactionOptions,\n\tSqliteValue,\n\tStorageDescriptor,\n} from \"./database.js\";\nimport { sqliteDialect } from \"./dialect.js\";\nimport {\n\tpayloadTooLargeKind,\n\tSQLITE_PAYLOAD_LIMITS,\n\tStorageAdapterLoadError,\n\tStorageConfigError,\n\ttype StorageFailureCause,\n\tStorageInvalidTextError,\n\tStoragePayloadTooLargeError,\n\tStorageRollbackError,\n\tStorageTransactionClosedError,\n\tStorageUnavailableError,\n\tStorageUnsupportedOperationError,\n\tStorageWriteLockTimeoutError,\n\tStorageWriterQueueDegradedError,\n\ttype StorageWriterQueueDegradedReason,\n\tStorageWriterQueueUnusableError,\n\tStoreClosedError,\n} from \"./errors.js\";\nimport { type ConnectionAnswer, type ConnectionRequest, ThreadConnection } from \"./node-sqlite-thread.js\";\nimport { isSqliteBusy, switchToWriteAheadLog, switchToWriteAheadLogSync } from \"./write-ahead-log.js\";\n\n/** Loaded at the first degradation only, so opening a database does not load debug output. */\nlet debugOutput: Promise<typeof import(\"../debug.ts\")> | undefined;\n\nfunction reportDegradationInDebugMode(degradation: StorageWriterQueueDegradedError): void {\n\tconst errno = (degradation.cause as { readonly code?: unknown } | undefined)?.code;\n\tdebugOutput ??= import(\"../debug.ts\");\n\tvoid debugOutput.then(\n\t\t({ reportDebugAsync: reportDebug }) =>\n\t\t\treportDebug(\"storage\", \"writer-queue-degraded\", {\n\t\t\t\tcode: degradation.code,\n\t\t\t\treason: degradation.reason,\n\t\t\t\tadapter: degradation.adapter,\n\t\t\t\tlocation: degradation.location,\n\t\t\t\terrno: typeof errno === \"string\" ? errno : undefined,\n\t\t\t}),\n\t\t(error: unknown) => process.emitWarning(error instanceof Error ? error : String(error)),\n\t);\n}\n\n/**\n * A ticket its owner has not refreshed for this long belongs to a process that died or stopped waiting. A ticket\n * refreshed this far in the future is stale too: the system clock stepped back since, or its owner stamped it from a\n * clock of its own.\n */\nconst TICKET_STALE_MS = 2_000;\n/** Stale tickets older than this are removed by whichever writer notices them. */\nconst TICKET_REMOVE_AFTER_MS = 10 * TICKET_STALE_MS;\n/** How often a waiting writer refreshes its ticket: well within `TICKET_STALE_MS`, even for a writer short of CPU. */\nconst TICKET_REFRESH_MS = TICKET_STALE_MS / 4;\nconst TICKET_TIME = /^(\\d{15})-/;\n/** Now on the database's clock, in milliseconds: the clock tickets are stamped and aged on (see `SqliteWriteQueue`). */\nconst DATABASE_NOW = `SELECT ${sqliteDialect.nowMs} AS now`;\n\n/** An in-memory connection of the process's own, which the database clock is read through. */\nlet clockConnection: DatabaseSync | undefined;\n/** node:sqlite's connection class, once an open loaded it. */\nlet loadedDatabaseSync: typeof DatabaseSync | undefined;\n\n/**\n * Now on the clock SQLite reads for `unixepoch()`: the system clock, which every process shares, whatever this\n * process's own says. SQLite reads it from the operating system, not from a database file, so a connection of the\n * process's own reads the same time as every handle's, and a handle can read it after it is closed. A connection on a\n * thread of its own reads it there; this reads it on the calling thread, for a connection there and for the\n * synchronous `getWriterQueueStats`.\n */\nfunction databaseNow(): number {\n\tclockConnection ??= new loadedDatabaseSync!(\":memory:\");\n\treturn Number(clockConnection.prepare(DATABASE_NOW).get()!.now);\n}\n\nlet ticketSequence = 0;\n\n/**\n * A ticket named after every live one: its time is the later of now and just after the latest live ticket's, so\n * order follows arrival even when processes' clocks disagree or the clock steps back.\n */\nfunction ticketName(live: readonly string[]): string {\n\tticketSequence += 1;\n\tlet time = Date.now();\n\tfor (const name of live) time = Math.max(time, Number(TICKET_TIME.exec(name)?.[1] ?? 0) + 1);\n\treturn `${String(time).padStart(15, \"0\")}-${process.pid}-${ticketSequence}`;\n}\n\nfunction isMissingFile(error: unknown): boolean {\n\treturn (error as NodeJS.ErrnoException).code === \"ENOENT\";\n}\n\n/**\n * A ticket that is gone or going: Windows reports a deleted file that another process still has open (to stat or\n * touch it) as EPERM until that handle closes.\n */\nfunction isVanishedTicket(error: unknown): boolean {\n\treturn isMissingFile(error) || ((error as NodeJS.ErrnoException).code === \"EPERM\" && platform() === \"win32\");\n}\n\n/**\n * Writes an empty queue entry, making its directory only when it is missing, as it is the first time the database\n * is contended: a writer joining the queue makes no more round trips off the event loop than it must.\n */\nasync function writeEntry(path: string, flag: \"wx\" | \"w\"): Promise<void> {\n\ttry {\n\t\tawait writeFile(path, \"\", { flag });\n\t} catch (error) {\n\t\tif (!isMissingFile(error)) throw error;\n\t\tawait mkdir(dirname(path), { recursive: true });\n\t\tawait writeFile(path, \"\", { flag });\n\t}\n}\n\n/** A queue entry and when its owner last marked it live, on the database clock. */\ninterface QueueEntry {\n\treadonly name: string;\n\treadonly mtimeMs: number;\n}\n\n/** A queue entry judged live: `fresh` when its owner marked it live within `TICKET_STALE_MS` on the database clock. */\ninterface LiveEntry {\n\treadonly name: string;\n\treadonly fresh: boolean;\n}\n\n/** When this writer first saw a ticket at its current modification time, on its own running clock. */\ninterface Sighting {\n\treadonly mtimeMs: number;\n\treadonly sinceRunningMs: number;\n}\n\nconst TICKET_PID = /^\\d{15}-(\\d+)-/;\n\n/** The queue entries of this process's writers that are waiting for the lock, by path: they are live, whatever their age. */\nconst waitingHere = new Set<string>();\n\n/**\n * First come, first served for SQLite's write lock across processes. SQLite has no queue for `BEGIN IMMEDIATE`: a\n * writer that polls after `SQLITE_BUSY` loses to one that begins the moment the lock is free, and a busy process\n * can take the lock again and again while another waits for its whole deadline (#3978). A writer that has been\n * refused takes a ticket, a file named after every live ticket, in a directory next to the database; it then\n * attempts the lock only once no live older ticket is ahead of it, and a writer that arrives while tickets wait\n * queues behind them instead of overtaking. Uncontended writers only list an absent or empty directory.\n *\n * Handing the lock on does not wait for anyone to poll (#4316): each queued writer watches a release notice of its\n * own, a file named like its ticket in a directory beside the queue's (`<file>-wakes`), and the writer that lets go\n * of the lock touches the oldest live ticket's notice, so its writer attempts the lock at once. The two never\n * share a file: only a ticket's owner moves the ticket's modification time, which is what keeps it live, so a\n * notice neither keeps a dead or stopped waiter's ticket alive nor, sent late, rolls a live one back to an older\n * time. A writer also rechecks on a timer, for the releases nobody announces: a holder killed with the lock, a\n * ticket ahead whose owner died, a raw SQLite client, an older Atomic.\n *\n * Tickets are stamped and aged on the database's clock, the system clock SQLite reads for `unixepoch()`, which also\n * stamps the files: every process shares it. A process's own clock can differ from it by seconds. On Windows, V8\n * extrapolates `Date.now()` from a reading of the system clock it renews once a minute, so after the system clock is\n * set (a virtual machine's time synchronization, say) a running process stays off by the step until then, and\n * processes aging tickets on their own clocks took live tickets for stale and overtook their writers (#4387).\n */\nclass SqliteWriteQueue {\n\tprivate readonly directory: string;\n\tprivate readonly noticeDirectory: string;\n\tprivate readonly degraded: (reason: StorageWriterQueueDegradedReason, cause: unknown) => void;\n\t/** Now on the database's clock, in milliseconds, read where the connection runs. */\n\treadonly now: () => number | Promise<number>;\n\tprivate observedAt: number | undefined;\n\t/** Time this writer was seen to run while it looked at the queue; see `advance`. */\n\tprivate runningMs = 0;\n\t/** Each listed ticket's modification time when this writer first saw it, and its running clock then. */\n\tprivate readonly sightings = new Map<string, Sighting>();\n\n\t/** `degraded` records what the queue had to give up on without failing the transaction that met it. */\n\tconstructor(\n\t\tdatabasePath: string,\n\t\tdegraded: (reason: StorageWriterQueueDegradedReason, cause: unknown) => void,\n\t\tnow: () => number | Promise<number>,\n\t) {\n\t\tthis.directory = `${databasePath}-writers`;\n\t\tthis.noticeDirectory = `${databasePath}-wakes`;\n\t\tthis.degraded = degraded;\n\t\tthis.now = now;\n\t}\n\n\t/** Marks this process as running now: time from here until its next look at the queue is time it was seen to run. */\n\tobserve(): void {\n\t\tthis.observedAt = performance.now();\n\t}\n\n\t/**\n\t * Advances this writer's running clock to this look and returns it. Time since its last look counts up to a waiting\n\t * writer's refresh, `TICKET_REFRESH_MS`; time beyond that is time this process was not seen to run, which a stall of\n\t * the whole host takes from every owner alike, so it is not held against their tickets.\n\t */\n\tprivate advance(): number {\n\t\tconst lookedAt = performance.now();\n\t\tif (this.observedAt !== undefined) this.runningMs += Math.min(lookedAt - this.observedAt, TICKET_REFRESH_MS);\n\t\tthis.observedAt = lookedAt;\n\t\treturn this.runningMs;\n\t}\n\n\t/**\n\t * Judges a queue's entries, sorted by name, on the database clock: the live ones, oldest first, and the ones\n\t * abandoned long enough to remove. A ticket refreshed within `TICKET_STALE_MS` is live. A ticket of a writer in\n\t * this process is live while that writer waits, and only then. A stale ticket of a process that is gone is passed\n\t * over. A stale ticket of a process that still exists is passed over only once this writer has itself run for\n\t * `TICKET_STALE_MS` since the ticket's last refresh, counting from when it first saw the ticket if it was stale then:\n\t * a stall of the whole host is never held against a ticket until its owner had the time to refresh it after the\n\t * stall, however soon this writer looks again, and a writer that starts after a stall, which saw none of it, waits\n\t * as long for the tickets it finds before passing over them.\n\t */\n\tprivate judge(entries: readonly QueueEntry[], now: number): { live: LiveEntry[]; abandoned: string[] } {\n\t\tconst running = this.advance();\n\t\tconst listed = new Set<string>();\n\t\tconst live: LiveEntry[] = [];\n\t\tconst abandoned: string[] = [];\n\t\tfor (const entry of entries) {\n\t\t\tlisted.add(entry.name);\n\t\t\tconst age = Math.abs(now - entry.mtimeMs);\n\t\t\tconst fresh = age < TICKET_STALE_MS;\n\t\t\tconst pid = Number(TICKET_PID.exec(entry.name)?.[1]);\n\t\t\tif (pid === process.pid) {\n\t\t\t\tif (waitingHere.has(join(this.directory, entry.name))) live.push({ name: entry.name, fresh: true });\n\t\t\t\telse if (fresh) live.push({ name: entry.name, fresh });\n\t\t\t\telse if (age > TICKET_REMOVE_AFTER_MS) abandoned.push(entry.name);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlet sighting = this.sightings.get(entry.name);\n\t\t\tif (sighting?.mtimeMs !== entry.mtimeMs) {\n\t\t\t\tsighting = { mtimeMs: entry.mtimeMs, sinceRunningMs: running - (fresh ? age : 0) };\n\t\t\t\tthis.sightings.set(entry.name, sighting);\n\t\t\t}\n\t\t\tif (fresh) live.push({ name: entry.name, fresh });\n\t\t\telse if (running - sighting.sinceRunningMs < TICKET_STALE_MS && Number.isSafeInteger(pid) && processAlive(pid))\n\t\t\t\tlive.push({ name: entry.name, fresh });\n\t\t\telse if (age > TICKET_REMOVE_AFTER_MS) abandoned.push(entry.name);\n\t\t}\n\t\tfor (const name of this.sightings.keys()) if (!listed.has(name)) this.sightings.delete(name);\n\t\treturn { live, abandoned };\n\t}\n\n\t/** Whether the queue directory exists: an uncontended writer finds none and reads nothing more. */\n\tcontended(): boolean {\n\t\treturn existsSync(this.directory);\n\t}\n\n\tcontendedOffLoop(): Promise<boolean> {\n\t\treturn pathExists(this.directory);\n\t}\n\n\t/** Takes a ticket behind `live`, writing it and its notice off the event loop. */\n\tasync join(live: readonly string[]): Promise<SqliteWriteTicket> {\n\t\tthis.observe();\n\t\tconst name = ticketName(live);\n\t\tconst ticket = new SqliteWriteTicket(this, name, join(this.directory, name), join(this.noticeDirectory, name));\n\t\tawait this.create(ticket, \"wx\");\n\t\treturn ticket;\n\t}\n\n\t/**\n\t * Writes the ticket's release notice, then the ticket, so a writer that finds the ticket can always touch its\n\t * notice. A ticket that cannot be written takes its notice with it; `wx` never takes over another writer's files.\n\t */\n\tasync create(ticket: SqliteWriteTicket, flag: \"wx\" | \"w\"): Promise<void> {\n\t\tawait writeEntry(ticket.noticePath, flag);\n\t\ttry {\n\t\t\tawait writeEntry(ticket.path, flag);\n\t\t\twaitingHere.add(ticket.path);\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tawait unlink(ticket.noticePath);\n\t\t\t} catch (cleanup) {\n\t\t\t\tthis.removalFailed(cleanup);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/** A ticket's notice, then the ticket: removed in that order, so no notice outlives its ticket. */\n\tprivate entryPaths(name: string): string[] {\n\t\treturn [join(this.noticeDirectory, name), join(this.directory, name)];\n\t}\n\n\t/** Whether removing an entry has to stop at `error`; one that is not a vanished entry is recorded as degraded. */\n\tprivate removalFailed(error: unknown): boolean {\n\t\tif (isVanishedTicket(error)) return false;\n\t\tthis.degraded(\"stale-ticket-kept\", error);\n\t\treturn true;\n\t}\n\n\t/** Removes an abandoned entry found while reading the queue. */\n\tremoveEntry(name: string): void {\n\t\tfor (const path of this.entryPaths(name)) {\n\t\t\ttry {\n\t\t\t\tunlinkSync(path);\n\t\t\t} catch (error) {\n\t\t\t\tif (this.removalFailed(error)) return;\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Removes an entry off the event loop: a leaving writer's own, or an abandoned one a waiting writer found. */\n\tasync removeEntryOffLoop(name: string): Promise<void> {\n\t\tfor (const path of this.entryPaths(name)) {\n\t\t\ttry {\n\t\t\t\tawait unlink(path);\n\t\t\t} catch (error) {\n\t\t\t\tif (this.removalFailed(error)) return;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Hands the turn on once this connection has let go of the write lock: touches the release notice of the oldest\n\t * live ticket, which its writer watches, so that writer attempts the lock at once. A ticket that is live only\n\t * because its owner has not yet had the time to refresh it (see `judge`) may belong to a writer that stopped, so the\n\t * notices of the tickets behind it are touched too, up to the first one refreshed on time. The ticket itself is not\n\t * touched: its modification time marks it live and only its owner moves it, so a release can neither keep a dead\n\t * writer's ticket alive nor undo the owner's refresh that came after the queue was read. A ticket that left\n\t * meanwhile passes the turn to the next one. `except` is the releasing writer's own ticket, still on its way out.\n\t */\n\tasync wakeNext(except?: string): Promise<void> {\n\t\tif (!(await this.contendedOffLoop())) return;\n\t\tfor (const ticket of await this.liveEntriesOffLoop(except)) {\n\t\t\ttry {\n\t\t\t\tconst now = new Date();\n\t\t\t\tawait utimes(join(this.noticeDirectory, ticket.name), now, now);\n\t\t\t\tif (ticket.fresh) return;\n\t\t\t} catch (error) {\n\t\t\t\tif (!isVanishedTicket(error)) throw error;\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Live tickets, oldest first; see `liveTicketEntries`. */\n\tliveTickets(except?: string): string[] {\n\t\treturn this.liveTicketEntries(except).map((ticket) => ticket.name);\n\t}\n\n\t/**\n\t * Live tickets, oldest first; stale ones long abandoned are removed on the way. A ticket is judged on the time this\n\t * writer was seen to run since it first saw it (see `judge`), so a stall of the whole host neither passes over nor\n\t * removes the tickets of writers it stopped too. A queue directory or a ticket that\n\t * vanishes while it is read counts as absent; any other failure to read the queue is thrown, so no caller takes a\n\t * queue it cannot read for an empty one. Removing an abandoned ticket is housekeeping: it is ignored whether or not\n\t * it goes, so a failure other than the ticket having vanished (another user's ticket in a shared directory, say)\n\t * is recorded as degraded, once, and never fails a transaction.\n\t */\n\tprivate liveTicketEntries(except?: string): LiveEntry[] {\n\t\tlet names: string[];\n\t\t// Uncontended writers find no directory; checking costs a third of a failed listing, twice per transaction.\n\t\tif (!this.contended()) return [];\n\t\ttry {\n\t\t\tnames = readdirSync(this.directory);\n\t\t} catch (error) {\n\t\t\tif (!isMissingFile(error)) throw error;\n\t\t\treturn [];\n\t\t}\n\t\t// An empty queue, as contention leaves it, is read without the clock.\n\t\tif (names.length === 0) return [];\n\t\tconst now = databaseNow();\n\t\tconst entries: QueueEntry[] = [];\n\t\tfor (const name of names.sort()) {\n\t\t\tif (name === except) continue;\n\t\t\ttry {\n\t\t\t\tentries.push({ name, mtimeMs: statSync(join(this.directory, name)).mtimeMs });\n\t\t\t} catch (error) {\n\t\t\t\tif (!isVanishedTicket(error)) throw error;\n\t\t\t}\n\t\t}\n\t\tconst { live, abandoned } = this.judge(entries, now);\n\t\tfor (const name of abandoned) this.removeEntry(name);\n\t\treturn live;\n\t}\n\n\t/** Live tickets other than `except`, oldest first, read off the event loop; see `liveEntriesOffLoop`. */\n\tasync liveTicketsOffLoop(except?: string): Promise<string[]> {\n\t\treturn (await this.liveEntriesOffLoop(except)).map((entry) => entry.name);\n\t}\n\n\t/**\n\t * Live tickets other than `except`, oldest first: read off the event loop and judged like `liveTicketEntries`.\n\t * Entries are read together; the first failure in listing order that is not a vanished entry is thrown.\n\t */\n\tprivate async liveEntriesOffLoop(except?: string): Promise<LiveEntry[]> {\n\t\tlet names: string[];\n\t\ttry {\n\t\t\tnames = await readdir(this.directory);\n\t\t} catch (error) {\n\t\t\tif (!isMissingFile(error)) throw error;\n\t\t\treturn [];\n\t\t}\n\t\tif (names.length === 0) return [];\n\t\tconst listed = names.sort().filter((name) => name !== except);\n\t\tconst read = await Promise.all(\n\t\t\tlisted.map((name) =>\n\t\t\t\tstat(join(this.directory, name)).then(\n\t\t\t\t\t(found): QueueEntry => ({ name, mtimeMs: found.mtimeMs }),\n\t\t\t\t\t(error: unknown) => ({ name, error }),\n\t\t\t\t),\n\t\t\t),\n\t\t);\n\t\tconst entries: QueueEntry[] = [];\n\t\tfor (const entry of read) {\n\t\t\tif (!(\"error\" in entry)) entries.push(entry);\n\t\t\telse if (!isVanishedTicket(entry.error)) throw entry.error;\n\t\t}\n\t\tconst { live, abandoned } = this.judge(entries, await this.now());\n\t\tfor (const name of abandoned) await this.removeEntryOffLoop(name);\n\t\treturn live;\n\t}\n}\n\nclass SqliteWriteTicket {\n\tprivate left = false;\n\tprivate readonly queue: SqliteWriteQueue;\n\treadonly name: string;\n\treadonly path: string;\n\treadonly noticePath: string;\n\t/** When this writer last marked the ticket live, on the monotonic clock. */\n\tprivate refreshed = performance.now();\n\n\tconstructor(queue: SqliteWriteQueue, name: string, path: string, noticePath: string) {\n\t\tthis.queue = queue;\n\t\tthis.name = name;\n\t\tthis.path = path;\n\t\tthis.noticePath = noticePath;\n\t}\n\n\t/**\n\t * Keeps this ticket live: refreshes it once `TICKET_REFRESH_MS` have passed since it was created or last\n\t * refreshed, recreating it and its release notice in the place it had if it was removed as stale while this\n\t * writer stalled. Returns whether the notice was recreated, which ends a watch on the removed one. The file work\n\t * runs off the event loop.\n\t */\n\tasync keepLive(): Promise<boolean> {\n\t\tif (performance.now() - this.refreshed < TICKET_REFRESH_MS) return false;\n\t\tthis.refreshed = performance.now();\n\t\tconst now = new Date(await this.queue.now());\n\t\ttry {\n\t\t\tawait utimes(this.path, now, now);\n\t\t\treturn false;\n\t\t} catch (error) {\n\t\t\tif (!isVanishedTicket(error)) throw error;\n\t\t\tawait this.queue.create(this, \"w\");\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t/** Whether an older live ticket is still ahead of this one, read off the event loop. */\n\tasync behindOthers(): Promise<boolean> {\n\t\treturn (await this.queue.liveTicketsOffLoop(this.name)).some((other) => other < this.name);\n\t}\n\n\t/** Watches this writer's release notice: anything that touches the file, as a releasing writer does. */\n\twatch(onUnavailable: (cause: Error) => void): ReleaseNotices {\n\t\treturn new ReleaseNotices(this.noticePath, onUnavailable);\n\t}\n\n\tasync leave(): Promise<void> {\n\t\tif (this.left) return;\n\t\tthis.left = true;\n\t\ttry {\n\t\t\tawait this.queue.removeEntryOffLoop(this.name);\n\t\t} finally {\n\t\t\twaitingHere.delete(this.path);\n\t\t}\n\t}\n}\n\n/**\n * The release notices a queued writer receives while it waits: a change to its notice file, which is how the writer\n * that lets go of the lock hands it the turn. The watch starts before the writer first checks the lock. A notice that\n * arrives while the writer reads the queue or attempts the lock is kept until its next wait, which then ends at once,\n * so one sent while it checks is never lost; `clear` forgets the notices a fresh look at the queue and the lock covers.\n */\nclass ReleaseNotices {\n\tprivate watcher?: FSWatcher;\n\tprivate arrived = false;\n\tprivate wake?: () => void;\n\n\tconstructor(path: string, onUnavailable: (cause: Error) => void) {\n\t\ttry {\n\t\t\tconst watcher = watch(path, () => {\n\t\t\t\tthis.arrived = true;\n\t\t\t\tthis.wake?.();\n\t\t\t});\n\t\t\twatcher.on(\"error\", (cause: Error) => {\n\t\t\t\tthis.close();\n\t\t\t\tonUnavailable(cause);\n\t\t\t});\n\t\t\tthis.watcher = watcher;\n\t\t} catch (cause) {\n\t\t\tonUnavailable(cause as Error);\n\t\t}\n\t}\n\n\tget watching(): boolean {\n\t\treturn this.watcher !== undefined;\n\t}\n\n\t/** Forgets the notices received so far: the writer is about to look at the queue and the lock afresh. */\n\tclear(): void {\n\t\tthis.arrived = false;\n\t}\n\n\t/** Resolves once a notice arrives, at once if one arrived since `clear`, or after `ms`. */\n\twait(ms: number): Promise<void> {\n\t\tif (this.arrived) return Promise.resolve();\n\t\treturn new Promise((resolve) => {\n\t\t\tconst done = () => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tthis.wake = undefined;\n\t\t\t\tresolve();\n\t\t\t};\n\t\t\tconst timer = setTimeout(done, ms);\n\t\t\tthis.wake = done;\n\t\t});\n\t}\n\n\tclose(): void {\n\t\tthis.watcher?.close();\n\t\tthis.watcher = undefined;\n\t}\n}\n\nlet holderSequence = 0;\nconst HOLDER_RECORD = /^(held|want) (\\d{15})\\n/;\n\nfunction processAlive(pid: number): boolean {\n\ttry {\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch (error) {\n\t\treturn (error as NodeJS.ErrnoException).code === \"EPERM\";\n\t}\n}\n\n/**\n * Which process holds the write lock, for the error of a writer that gives up waiting for it. Each connection\n * records in a file of its own next to the database, named by its process, when it starts trying for the lock (before\n * its first attempt, which waits for the record to be written), when it took the lock, and that it is free once it\n * lets go or gives up; only its connection writes a record, so records never race. Nothing reads them until a writer\n * gives up: the live record taken most recently names the holder. A holder whose record does not yet say it took the\n * lock, stopped or starved right after taking it, still says it was trying for it; it is then one of the candidates the\n * writer that gives up lists, not named. A connection removes the records\n * of exited processes when it creates its own, so the killed ones do not pile up. Recording is a diagnostic: a\n * record that cannot be created, written or cleaned up never fails a transaction. The failure is recorded as a\n * degradation instead, and a writer that gives up waiting may then name no holder.\n */\nclass SqliteHolderRecord {\n\tprivate descriptor?: number;\n\tprivate writes: Promise<void> = Promise.resolve();\n\tprivate readonly directory: string;\n\tprivate readonly path: string;\n\tprivate readonly unavailable: (cause: unknown) => void;\n\n\t/** `unavailable` records a failure to keep the record, or to remove an exited process's. */\n\tconstructor(databasePath: string, unavailable: (cause: unknown) => void) {\n\t\tthis.directory = holderDirectory(databasePath);\n\t\tholderSequence += 1;\n\t\tthis.path = join(this.directory, `${process.pid}-${holderSequence}`);\n\t\tthis.unavailable = unavailable;\n\t}\n\n\t/**\n\t * Creates the record off the event loop as a writable connection opens, removing exited processes' records on the\n\t * way, so that taking the lock only writes to it in place.\n\t */\n\tasync open(): Promise<void> {\n\t\ttry {\n\t\t\tawait mkdir(this.directory, { recursive: true });\n\t\t\tawait removeExitedHolderRecords(this.directory, this.unavailable);\n\t\t\tthis.descriptor = await openFile(this.path, \"w\");\n\t\t} catch (cause) {\n\t\t\tthis.unavailable(cause);\n\t\t}\n\t}\n\n\t/** Records that this connection is about to try for the lock; written before its first attempt. */\n\ttrying(): Promise<void> {\n\t\treturn this.write(`want ${String(Date.now()).padStart(15, \"0\")}\\n`);\n\t}\n\n\theld(): Promise<void> {\n\t\treturn this.write(`held ${String(Date.now()).padStart(15, \"0\")}\\n`);\n\t}\n\n\tfree(): Promise<void> {\n\t\treturn this.write(`free ${\"0\".repeat(15)}\\n`);\n\t}\n\n\t/** The process, this one or another, whose record says it took the write lock most recently; see `writeLockHolder`. */\n\tlatestHolder(): Promise<WriteLockHolder | undefined> {\n\t\treturn writeLockHolder(this.directory, basename(this.path));\n\t}\n\n\tasync close(): Promise<void> {\n\t\tawait this.writes;\n\t\tawait this.remove();\n\t}\n\n\tprivate async remove(): Promise<void> {\n\t\tconst descriptor = this.descriptor;\n\t\tif (descriptor === undefined) return;\n\t\tthis.descriptor = undefined;\n\t\ttry {\n\t\t\tawait closeFile(descriptor);\n\t\t\tawait unlink(this.path);\n\t\t} catch {\n\t\t\t// Already gone; a leftover record of an exited process is ignored and removed by whoever reads it.\n\t\t}\n\t}\n\n\t/**\n\t * Every record has the same length and is written in place, so a reader never sees a shorter, stale tail. A\n\t * connection without a record, read-only or unable to create one, writes nothing.\n\t */\n\tprivate write(record: string): Promise<void> {\n\t\tthis.writes = this.writes.then(async () => {\n\t\t\tconst descriptor = this.descriptor;\n\t\t\tif (descriptor === undefined) return;\n\t\t\ttry {\n\t\t\t\tawait writeFileAt(descriptor, record, 0);\n\t\t\t} catch (cause) {\n\t\t\t\tawait this.remove();\n\t\t\t\tthis.unavailable(cause);\n\t\t\t}\n\t\t});\n\t\treturn this.writes;\n\t}\n}\n\nfunction holderDirectory(databasePath: string): string {\n\treturn `${databasePath}-holders`;\n}\n\nexport function sqliteOpenLockPath(databasePath: string): string {\n\treturn `${databasePath}-open.lock`;\n}\n\ntype NativeOpenLocks = Pick<typeof native, \"tryAdvisoryLock\" | \"trySharedAdvisoryLock\"> &\n\tPartial<Pick<typeof native, \"tryAdvisoryLockAsync\" | \"trySharedAdvisoryLockAsync\">>;\n\ninterface HeldOpenLock {\n\treadonly lock: { release(): void };\n\treadonly path: string;\n\treadonly target: string;\n}\n\nlet nativeOpenLocks: NativeOpenLocks | null | undefined;\n\nfunction openLocks(): NativeOpenLocks | null {\n\tif (nativeOpenLocks === undefined) {\n\t\ttry {\n\t\t\tlet binding: Partial<NativeOpenLocks>;\n\t\t\ttry {\n\t\t\t\tbinding = createRequire(import.meta.url)(\"@bastani/atomic-natives\") as Partial<NativeOpenLocks>;\n\t\t\t} catch {\n\t\t\t\tbinding = createRequire(pathToFileURL(process.execPath).href)(\n\t\t\t\t\t\"@bastani/atomic-natives\",\n\t\t\t\t) as Partial<NativeOpenLocks>;\n\t\t\t}\n\t\t\tnativeOpenLocks =\n\t\t\t\ttypeof binding.tryAdvisoryLock === \"function\" && typeof binding.trySharedAdvisoryLock === \"function\"\n\t\t\t\t\t? (binding as NativeOpenLocks)\n\t\t\t\t\t: null;\n\t\t} catch {\n\t\t\tnativeOpenLocks = null;\n\t\t}\n\t}\n\treturn nativeOpenLocks;\n}\n\nfunction sqliteTargetFilePath(spec: string): string | undefined {\n\tif (spec === \"\" || spec === \":memory:\") return undefined;\n\tif (!spec.startsWith(\"file:\")) return spec;\n\tconst hashIndex = spec.indexOf(\"#\");\n\tconst withoutHash = hashIndex === -1 ? spec : spec.slice(0, hashIndex);\n\tconst queryIndex = withoutHash.indexOf(\"?\");\n\tconst uriPart = queryIndex === -1 ? withoutHash : withoutHash.slice(0, queryIndex);\n\tconst queryPart = queryIndex === -1 ? \"\" : withoutHash.slice(queryIndex + 1);\n\tif (new URLSearchParams(queryPart).get(\"mode\") === \"memory\") return undefined;\n\tconst body = uriPart.slice(\"file:\".length);\n\tif (body === \"\" || body === \":memory:\") return undefined;\n\tif (uriPart.startsWith(\"file://\")) {\n\t\ttry {\n\t\t\treturn fileURLToPath(uriPart);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\ttry {\n\t\tconst decoded = decodeURIComponent(body);\n\t\tif (process.platform === \"win32\" && /^\\/[a-zA-Z]:/.test(decoded)) return decoded.slice(1);\n\t\treturn resolve(decoded);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Whether SQLite opens `spec` as an in-memory database: `:memory:`, `file::memory:`, or a `file:` URI whose last `mode`\n * parameter, the one SQLite applies, is `memory`. Anything else, a URI this cannot read included, may be a file.\n */\nfunction isInMemoryDatabase(spec: string): boolean {\n\tif (spec === \":memory:\") return true;\n\tif (!spec.startsWith(\"file:\")) return false;\n\tconst hashIndex = spec.indexOf(\"#\");\n\tconst withoutHash = hashIndex === -1 ? spec : spec.slice(0, hashIndex);\n\tconst queryIndex = withoutHash.indexOf(\"?\");\n\tconst uriPart = queryIndex === -1 ? withoutHash : withoutHash.slice(0, queryIndex);\n\tif (uriPart === \"file::memory:\") return true;\n\tconst query = new URLSearchParams(queryIndex === -1 ? \"\" : withoutHash.slice(queryIndex + 1));\n\treturn query.getAll(\"mode\").at(-1) === \"memory\";\n}\n\nfunction isMissingOpenLockDir(error: unknown): boolean {\n\tif (isMissingFile(error)) return true;\n\tconst message = error instanceof Error ? error.message : String(error);\n\treturn /No such file or directory|cannot find the path|os error [23]\\b/i.test(message);\n}\n\nfunction pathExists(path: string): Promise<boolean> {\n\treturn stat(path).then(\n\t\t() => true,\n\t\t() => false,\n\t);\n}\n\nasync function resolveOpenLockTarget(filePath: string, readOnly: boolean): Promise<string | undefined> {\n\ttry {\n\t\treturn await realpath(filePath);\n\t} catch {\n\t\tif (readOnly) return undefined;\n\t\tawait mkdir(dirname(filePath), { recursive: true });\n\t\treturn join(await realpath(dirname(filePath)), basename(filePath));\n\t}\n}\n\nasync function acquireOpenLock(\n\tfilePath: string | undefined,\n\treadOnly: boolean,\n\tbusyTimeoutMs: number,\n): Promise<HeldOpenLock | undefined> {\n\tconst locks = openLocks();\n\tif (locks === null || filePath === undefined) return undefined;\n\tconst started = performance.now();\n\tlet delay = 5;\n\tfor (;;) {\n\t\tconst target = await resolveOpenLockTarget(filePath, readOnly);\n\t\tif (target === undefined) return undefined;\n\t\tconst lockPath = sqliteOpenLockPath(target);\n\t\tif (\n\t\t\treadOnly &&\n\t\t\t!(await pathExists(holderDirectory(target))) &&\n\t\t\t!(await pathExists(lockPath)) &&\n\t\t\t!(await pathExists(`${target}.lock`))\n\t\t)\n\t\t\treturn undefined;\n\t\tlet lock: { release(): void } | null = null;\n\t\tlet refusal: unknown;\n\t\ttry {\n\t\t\tlock =\n\t\t\t\tlocks.trySharedAdvisoryLockAsync === undefined\n\t\t\t\t\t? legacySharedOpenLock(locks, sqliteFilePath(lockPath))\n\t\t\t\t\t: await locks.trySharedAdvisoryLockAsync(sqliteFilePath(lockPath), 0);\n\t\t} catch (error) {\n\t\t\tif (readOnly) return undefined;\n\t\t\tif (await isPassingOpenLockRefusal(error, lockPath)) refusal = error;\n\t\t\telse if (!isMissingOpenLockDir(error)) throw error;\n\t\t}\n\t\tif (lock !== null) {\n\t\t\tconst held: HeldOpenLock = { lock, path: sqliteFilePath(lockPath), target };\n\t\t\tif (readOnly && !(await pathExists(target))) {\n\t\t\t\tawait releaseOpenLock(held);\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\treturn held;\n\t\t}\n\t\tconst remaining = started + busyTimeoutMs - performance.now();\n\t\tif (remaining <= 0 && refusal !== undefined) throw refusal;\n\t\tif (remaining <= 0)\n\t\t\tthrow Object.assign(new Error(\"database is locked\"), {\n\t\t\t\tcode: \"ERR_SQLITE_ERROR\",\n\t\t\t\terrcode: 5,\n\t\t\t\terrstr: \"database is locked\",\n\t\t\t});\n\t\tawait new Promise((resolve) => setTimeout(resolve, Math.min(delay, remaining)));\n\t\tdelay = Math.min(delay * 2, 50);\n\t}\n}\n\n/**\n * The shared open lock, tried once on the calling thread, for a native binding older than the one this package ships,\n * which has no form of it that runs elsewhere: an open still respects another process's exclusive lock.\n */\nfunction legacySharedOpenLock(locks: NativeOpenLocks, lockPath: string): { release(): void } | null {\n\treturn locks.trySharedAdvisoryLock(lockPath, 0);\n}\n\n/**\n * Windows refuses to create a file for a few milliseconds after another process removes one of the same name, with\n * `Access is denied` while nothing is at the path; an open waits that out like a held lock, within its busy timeout.\n * A refusal while a file is at the path is a real permission error.\n */\nasync function isPassingOpenLockRefusal(error: unknown, lockPath: string): Promise<boolean> {\n\tif (process.platform !== \"win32\") return false;\n\tconst message = error instanceof Error ? error.message : String(error);\n\tif (!/\\(os error 5\\)/.test(message)) return false;\n\treturn lstat(lockPath).then(\n\t\t() => false,\n\t\t(cause: unknown) => isMissingFile(cause),\n\t);\n}\n\nfunction isOpenLockPermissionError(error: unknown): boolean {\n\tconst code = (error as NodeJS.ErrnoException | undefined)?.code;\n\tif (code === \"EACCES\" || code === \"EPERM\" || code === \"EROFS\") return true;\n\tconst message = error instanceof Error ? error.message : String(error);\n\treturn process.platform === \"win32\"\n\t\t? /\\(os error (?:5|19|65)\\)/.test(message)\n\t\t: /\\(os error (?:1|13|30)\\)/.test(message);\n}\n\nfunction acquireOpenLockSync(location: string): HeldOpenLock | undefined {\n\tconst locks = openLocks();\n\tconst filePath = sqliteTargetFilePath(location);\n\tif (locks === null || filePath === undefined) return undefined;\n\tconst target = realpathSync(filePath);\n\tconst lockPath = sqliteFilePath(sqliteOpenLockPath(target));\n\tlet lock: { release(): void } | null;\n\ttry {\n\t\tlock = locks.trySharedAdvisoryLock(lockPath, 50);\n\t} catch (error) {\n\t\tif (isOpenLockPermissionError(error)) return undefined;\n\t\tthrow error;\n\t}\n\tif (lock === null)\n\t\tthrow Object.assign(new Error(\"database is locked\"), {\n\t\t\tcode: \"ERR_SQLITE_ERROR\",\n\t\t\terrcode: 5,\n\t\t\terrstr: \"database is locked\",\n\t\t});\n\treturn { lock, path: lockPath, target };\n}\n\nasync function releaseOpenLock(openLock: HeldOpenLock | undefined): Promise<void> {\n\tif (openLock === undefined) return;\n\topenLock.lock.release();\n\ttry {\n\t\tconst exclusive = (await openLocks()?.tryAdvisoryLockAsync?.(openLock.path, 0)) ?? null;\n\t\tif (exclusive !== null) {\n\t\t\ttry {\n\t\t\t\tawait rm(openLock.path, { force: true });\n\t\t\t} finally {\n\t\t\t\texclusive.release();\n\t\t\t}\n\t\t}\n\t} catch {}\n}\n\nconst openFile = promisify(open);\nconst closeFile = promisify(close);\nconst writeFileAt = promisify(write) as (descriptor: number, data: string, position: number) => Promise<unknown>;\n\n/** The process a holder record belongs to, from its name: `<pid>-<sequence>`. */\nfunction holderPid(name: string): number | undefined {\n\tconst pid = Number(/^(\\d+)-/.exec(name)?.[1] ?? Number.NaN);\n\treturn Number.isSafeInteger(pid) && pid > 0 ? pid : undefined;\n}\n\n/**\n * Removes the records of exited processes, off the event loop. One another connection removed first is gone; any\n * other failure to remove one goes to `failed`, and the rest are still removed.\n */\nasync function removeExitedHolderRecords(directory: string, failed: (cause: unknown) => void): Promise<void> {\n\tfor (const name of await readdir(directory)) {\n\t\tconst pid = holderPid(name);\n\t\tif (pid === undefined || processAlive(pid)) continue;\n\t\ttry {\n\t\t\tawait unlink(join(directory, name));\n\t\t} catch (error) {\n\t\t\tif (!isVanishedTicket(error)) failed(error);\n\t\t}\n\t}\n}\n\n/** A live process's record: when it took the lock, or started trying for it; neither when it is free. */\ninterface LiveHolderRecord {\n\treadonly name: string;\n\treadonly pid: number;\n\treadonly heldSince?: number;\n\treadonly tryingSince?: number;\n}\n\n/** The records of live processes; the records of exited ones are removed. */\nasync function liveHolderRecords(directory: string): Promise<LiveHolderRecord[]> {\n\tlet names: string[];\n\ttry {\n\t\tnames = await readdir(directory);\n\t} catch {\n\t\treturn [];\n\t}\n\tconst live: LiveHolderRecord[] = [];\n\tfor (const name of names) {\n\t\tconst pid = holderPid(name);\n\t\tif (pid === undefined) continue;\n\t\tif (!processAlive(pid)) {\n\t\t\ttry {\n\t\t\t\tawait unlink(join(directory, name));\n\t\t\t} catch {\n\t\t\t\t// Another connection removed it first.\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tlet record: string;\n\t\ttry {\n\t\t\trecord = await readFile(join(directory, name), \"utf8\");\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tconst [, state, since] = HOLDER_RECORD.exec(record) ?? [];\n\t\tlive.push({\n\t\t\tname,\n\t\t\tpid,\n\t\t\t...(state === \"held\" ? { heldSince: Number(since) } : {}),\n\t\t\t...(state === \"want\" ? { tryingSince: Number(since) } : {}),\n\t\t});\n\t}\n\treturn live;\n}\n\n/** Who holds the write lock, as far as the records prove it. */\ntype WriteLockHolder = { readonly pid: number; readonly heldMs: number } | { readonly candidates: readonly number[] };\n\n/**\n * The live process whose record says it took the write lock most recently, and for how long it has held it. A record\n * that says a connection is only trying for the lock proves nothing: a waiter stopped in the queue keeps saying so while\n * a later writer takes the lock past it. So when no record says it took the lock, as for a holder stopped before its\n * record could say so, no process is named; the processes of the other connections trying for the lock, not `own`, are\n * the candidates, one of which may hold it.\n */\nasync function writeLockHolder(directory: string, own: string): Promise<WriteLockHolder | undefined> {\n\tlet held: { pid: number; since: number } | undefined;\n\tconst candidates = new Set<number>();\n\tfor (const record of await liveHolderRecords(directory)) {\n\t\tconst { pid, heldSince, tryingSince } = record;\n\t\tif (heldSince !== undefined && (held === undefined || heldSince > held.since)) held = { pid, since: heldSince };\n\t\tif (record.name !== own && tryingSince !== undefined) candidates.add(pid);\n\t}\n\tif (held !== undefined) return { pid: held.pid, heldMs: Math.max(0, Date.now() - held.since) };\n\treturn candidates.size === 0 ? undefined : { candidates: [...candidates].sort((a, b) => a - b) };\n}\n\ninterface TransactionGates {\n\treadonly files: Map<string, Promise<void>>;\n\treadonly connections: WeakMap<object, Promise<void>>;\n}\n\n// Share gates across module reloads as well as adapter instances. Only live queues retain file identities.\nconst TRANSACTION_GATES = Symbol.for(\"atomic-storage/node-sqlite-transaction-gates@1\");\nconst gateBag = globalThis as typeof globalThis & Record<symbol, TransactionGates | undefined>;\nconst gates: TransactionGates = gateBag[TRANSACTION_GATES] ?? { files: new Map(), connections: new WeakMap() };\ngateBag[TRANSACTION_GATES] = gates;\n\nfunction gateTransaction<T>(identity: string | object, operation: () => Promise<T>): Promise<T> {\n\tconst prior = typeof identity === \"string\" ? gates.files.get(identity) : gates.connections.get(identity);\n\tconst result = (prior ?? Promise.resolve()).then(operation);\n\tconst settled = result.then(\n\t\t() => {},\n\t\t() => {},\n\t);\n\tif (typeof identity === \"string\") gates.files.set(identity, settled);\n\telse gates.connections.set(identity, settled);\n\tvoid settled.then(() => {\n\t\tif (typeof identity === \"string\") {\n\t\t\tif (gates.files.get(identity) === settled) gates.files.delete(identity);\n\t\t} else if (gates.connections.get(identity) === settled) gates.connections.delete(identity);\n\t});\n\treturn result;\n}\n\n/** Copies binary parameters so queued work binds the bytes the caller passed, not later buffer contents. */\nfunction snapshotParams(params: readonly SqliteValue[]): SqliteValue[] {\n\treturn params.map((value) => (value instanceof Uint8Array ? new Uint8Array(value) : value));\n}\n\n/**\n * Bun's `DatabaseSync.close()` defers closing the file until garbage collection finalizes every statement the\n * connection prepared, so the database, WAL and shared-memory files stay open (and locked on Windows). The adapter\n * keeps no statement references, so a synchronous collection finalizes them and releases the files. Node finalizes\n * statements inside `close()` and has no `Bun` global.\n */\nfunction finalizeReleasedStatements(): void {\n\t(globalThis as { Bun?: { gc(force: boolean): void } }).Bun?.gc(true);\n}\n\n/**\n * Default for how long a transaction keeps retrying `BEGIN IMMEDIATE` while the write lock is held and nobody makes\n * progress through it: every commit by another connection restarts the wait, so only a lock held without commits\n * for this long fails the transaction.\n */\nconst DEFAULT_NODE_SQLITE_LOCK_WAIT_MS = 30_000;\n/**\n * How often a queued writer that watches its ticket rechecks without being told to: it refreshes its ticket (well\n * within `TICKET_STALE_MS`, even for a writer starved of CPU) and notices releases nobody announces. Handing the lock\n * on between Atomic writers does not wait for it.\n */\nconst LOCK_WAIT_RECHECK_MS = 250;\n/**\n * How often a writer that cannot watch its ticket (or has no queue: an in-memory or wrapped connection) retries the\n * lock within the connection's lock wait. Past it, for a transaction that waits longer, it retries every\n * `LOCK_WAIT_RECHECK_MS`, so writers polling a stalled lock leave the stalled holder the CPU it needs.\n */\nconst UNWATCHED_LOCK_RETRY_MS = 20;\n/**\n * How long a refused writer keeps trying the lock on every event-loop turn once another connection has committed\n * since its last look (see `attemptThroughRelease`): one Windows timer tick (15.6 ms), so the attempts cover the time\n * between two ticks, when a writer that does not queue and runs on its own timers lets go of the lock.\n */\nconst LOCK_RELEASE_RETRY_MS = 16;\n/** Most attempts in one `LOCK_RELEASE_RETRY_MS` span, so it ends even on a clock that does not move. */\nconst LOCK_RELEASE_RETRY_ATTEMPTS = 1_000;\n/** Most transactions one group commit carries, so a batch cannot keep the write lock from other processes for long. */\nconst MAX_GROUP_COMMIT_TRANSACTIONS = 128;\n/**\n * Default for how long a group commit runs its members before it commits them and takes the lock again for the\n * rest: a batch of cheap transactions in a process starved of CPU still lets other processes' writers in between.\n * The bound is checked between members, so one member's own work, however long, is never split.\n */\nexport const DEFAULT_GROUP_COMMIT_HOLD_MS = 100;\n/** The span `getWriterQueueStats` reports on. */\nconst WRITER_QUEUE_STATS_WINDOW_MS = 10_000;\n\ninterface QueuedTransaction {\n\treadonly callback: (transaction: SqliteExecutor) => Promise<unknown>;\n\treadonly resolve: (value: unknown) => void;\n\treadonly reject: (error: unknown) => void;\n\treadonly lockWaitMs?: number;\n}\n\n/**\n * Transactions committed together. `position` is the connection operation that commits them; a batch directly behind\n * it (`position + 1`, so no statement between) is absorbed when this one first takes the lock. A waiting batch takes\n * new transactions until a statement is queued after it.\n */\ninterface PendingBatch {\n\treadonly members: QueuedTransaction[];\n\tposition: number;\n\topen: boolean;\n}\n\ntype TransactionOutcome =\n\t| { readonly ok: true; readonly value: unknown }\n\t| { readonly ok: false; readonly error: unknown };\n\n/** One connection's use of the write lock over the last `WRITER_QUEUE_STATS_WINDOW_MS`, on the monotonic clock. */\nexport interface WriterQueueStats {\n\t/** Share of the window, 0 to 1, this connection held the write lock: from `BEGIN IMMEDIATE` to commit or rollback. */\n\treadonly lockHeldRatio: number;\n\t/** Writers waiting in the cross-process queue right now, in any process; 0 without a queue (in-memory, wrapped). */\n\treadonly waiters: number;\n\t/** Median time this connection's acquisitions in the window waited for the lock, in ms; 0 with none. */\n\treadonly p50WaitMs: number;\n\t/** 95th-percentile (nearest-rank) wait for the lock in the window, in ms; 0 with none. */\n\treadonly p95WaitMs: number;\n\t/** Commits by this connection per second over the window. */\n\treadonly commitsPerSecond: number;\n}\n\n/** Samples in time order; those older than the window are dropped as new ones arrive. */\nclass WindowSamples<T extends { readonly at: number }> {\n\tprivate items: T[] = [];\n\tprivate first = 0;\n\n\tpush(item: T): void {\n\t\tthis.items.push(item);\n\t\tthis.drop(item.at - WRITER_QUEUE_STATS_WINDOW_MS);\n\t}\n\n\tsince(from: number): T[] {\n\t\tthis.drop(from);\n\t\treturn this.items.slice(this.first);\n\t}\n\n\tprivate drop(before: number): void {\n\t\twhile (this.first < this.items.length && this.items[this.first]!.at < before) this.first += 1;\n\t\tif (this.first * 2 > this.items.length) {\n\t\t\tthis.items = this.items.slice(this.first);\n\t\t\tthis.first = 0;\n\t\t}\n\t}\n}\n\nfunction nearestRank(sorted: readonly number[], percentile: number): number {\n\tif (sorted.length === 0) return 0;\n\treturn sorted[Math.ceil((percentile / 100) * sorted.length) - 1]!;\n}\n\n/** Records when a connection waits for, holds, and commits through the write lock. */\nclass WriteLockUse {\n\tprivate readonly opened = performance.now();\n\tprivate heldSince?: number;\n\t/** Completed holds, by when they ended. */\n\tprivate readonly holds = new WindowSamples<{ readonly at: number; readonly start: number }>();\n\tprivate readonly commits = new WindowSamples<{ readonly at: number }>();\n\tprivate readonly waits = new WindowSamples<{ readonly at: number; readonly waitMs: number }>();\n\n\tacquired(waitStarted: number): void {\n\t\tconst now = performance.now();\n\t\tthis.heldSince = now;\n\t\tthis.waits.push({ at: now, waitMs: now - waitStarted });\n\t}\n\n\treleased(committed: boolean): void {\n\t\tconst now = performance.now();\n\t\tthis.holds.push({ at: now, start: this.heldSince ?? now });\n\t\tthis.heldSince = undefined;\n\t\tif (committed) this.commits.push({ at: now });\n\t}\n\n\tstats(waiters: number): WriterQueueStats {\n\t\tconst now = performance.now();\n\t\tconst windowMs = Math.min(WRITER_QUEUE_STATS_WINDOW_MS, now - this.opened);\n\t\tif (windowMs <= 0) return { lockHeldRatio: 0, waiters, p50WaitMs: 0, p95WaitMs: 0, commitsPerSecond: 0 };\n\t\tconst from = now - windowMs;\n\t\tlet heldMs = this.heldSince === undefined ? 0 : now - Math.max(this.heldSince, from);\n\t\tfor (const hold of this.holds.since(from)) heldMs += hold.at - Math.max(hold.start, from);\n\t\tconst waits = this.waits\n\t\t\t.since(from)\n\t\t\t.map((wait) => wait.waitMs)\n\t\t\t.sort((a, b) => a - b);\n\t\treturn {\n\t\t\tlockHeldRatio: Math.min(1, heldMs / windowMs),\n\t\t\twaiters,\n\t\t\tp50WaitMs: nearestRank(waits, 50),\n\t\t\tp95WaitMs: nearestRank(waits, 95),\n\t\t\tcommitsPerSecond: this.commits.since(from).length / (windowMs / 1000),\n\t\t};\n\t}\n}\n\n/** The driver's own reason, kept in the error message so it survives relays that forward only `message`. */\nfunction sqliteFailureDetail(cause: unknown): string | undefined {\n\tif (!(cause instanceof Error) || cause.message === \"\") return undefined;\n\tconst code = (cause as { errcode?: unknown }).errcode;\n\treturn typeof code === \"number\" ? `${cause.message} (SQLite code ${code})` : cause.message;\n}\n\nfunction unavailable(descriptor: StorageDescriptor, cause: unknown, detail = sqliteFailureDetail(cause)) {\n\t// A value over SQLite's length limit fails the same way every time: permanent, never an outage (#4954).\n\tif (payloadTooLargeKind(cause as StorageFailureCause) !== undefined) {\n\t\treturn new StoragePayloadTooLargeError(SQLITE_PAYLOAD_LIMITS.value ?? 0, 0, {\n\t\t\tdescriptor,\n\t\t\tcause: cause as StorageFailureCause,\n\t\t});\n\t}\n\treturn new StorageUnavailableError(descriptor, cause as StorageFailureCause, detail);\n}\n\nfunction normalizeRow(row: Record<string, SqliteValue>): SqliteRow {\n\treturn Object.fromEntries(\n\t\tObject.entries(row).map(([key, value]) => [\n\t\t\tkey,\n\t\t\ttypeof value === \"bigint\" &&\n\t\t\tvalue >= -BigInt(Number.MAX_SAFE_INTEGER) &&\n\t\t\tvalue <= BigInt(Number.MAX_SAFE_INTEGER)\n\t\t\t\t? Number(value)\n\t\t\t\t: value instanceof Uint8Array\n\t\t\t\t\t? new Uint8Array(value)\n\t\t\t\t\t: value,\n\t\t]),\n\t);\n}\n\n/**\n * A connection whose statements run on the calling thread: an in-memory database, which never waits for the disk or\n * for a lock another connection holds, and a connection its caller opened and passed to `wrapNodeSqliteDatabase` (a\n * `DatabaseSync` cannot move to another thread). It answers each request as a connection's own thread does.\n */\nclass CallerThreadConnection {\n\tprivate readonly connection: DatabaseSync;\n\tprivate readonly ownsConnection: boolean;\n\n\tconstructor(connection: DatabaseSync, ownsConnection: boolean) {\n\t\tthis.connection = connection;\n\t\tthis.ownsConnection = ownsConnection;\n\t}\n\n\trequest(request: ConnectionRequest): ConnectionAnswer {\n\t\tswitch (request.kind) {\n\t\t\tcase \"open\":\n\t\t\t\treturn this.connection.location();\n\t\t\tcase \"exec\":\n\t\t\t\tthis.connection.exec(request.sql);\n\t\t\t\treturn undefined;\n\t\t\tcase \"run\":\n\t\t\t\treturn { changes: Number(this.statement(request.sql).run(...request.params).changes) };\n\t\t\tcase \"get\": {\n\t\t\t\tconst row = this.statement(request.sql).get(...request.params);\n\t\t\t\treturn row === undefined ? undefined : normalizeRow(row);\n\t\t\t}\n\t\t\tcase \"all\":\n\t\t\t\treturn this.statement(request.sql)\n\t\t\t\t\t.all(...request.params)\n\t\t\t\t\t.map((row) => normalizeRow(row));\n\t\t\tcase \"begin\":\n\t\t\t\tthis.begin();\n\t\t\t\treturn undefined;\n\t\t\tcase \"dataVersion\":\n\t\t\t\treturn Number(this.connection.prepare(\"PRAGMA data_version\").get()?.data_version ?? 0);\n\t\t\tcase \"now\":\n\t\t\t\treturn databaseNow();\n\t\t\tcase \"jsonbExtract\":\n\t\t\t\ttry {\n\t\t\t\t\tthis.statement(\"SELECT jsonb_extract('[]', '$')\");\n\t\t\t\t\treturn true;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (error instanceof Error && error.message === \"no such function: jsonb_extract\") return false;\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\tcase \"close\":\n\t\t\t\tif (this.ownsConnection) this.connection.close();\n\t\t\t\tfinalizeReleasedStatements();\n\t\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate statement(sql: string) {\n\t\tconst prepared = this.connection.prepare(sql);\n\t\tprepared.setReadBigInts(true);\n\t\treturn prepared;\n\t}\n\n\t/** One `BEGIN IMMEDIATE` that does not wait for a busy lock; see `NodeSqliteDatabase.tryBegin`. */\n\tprivate begin(): void {\n\t\tconst configured = Number(this.connection.prepare(\"PRAGMA busy_timeout\").get()?.timeout ?? 0);\n\t\tthis.connection.exec(\"PRAGMA busy_timeout=0\");\n\t\tlet began = false;\n\t\ttry {\n\t\t\tthis.connection.exec(\"BEGIN IMMEDIATE\");\n\t\t\tbegan = true;\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tthis.connection.exec(`PRAGMA busy_timeout=${configured}`);\n\t\t\t} catch (restoreFailure) {\n\t\t\t\t// Never hand back a transaction on a connection whose lock wait is no longer the configured one.\n\t\t\t\tif (began) this.connection.exec(\"ROLLBACK\");\n\t\t\t\t// biome-ignore lint/correctness/noUnsafeFinally: a failed restore must replace the attempt's outcome.\n\t\t\t\tthrow restoreFailure;\n\t\t\t}\n\t\t}\n\t}\n}\n\n/** Where a connection's statements run: a thread of its own, or the calling thread. */\ntype SqliteConnection = ThreadConnection | CallerThreadConnection;\n\n/**\n * Sends one request to `connection`: a promise of its answer from a connection on a thread of its own, and the answer\n * itself from one on the calling thread, which runs it before returning, as node:sqlite does.\n */\nfunction send(connection: SqliteConnection, request: ConnectionRequest): ConnectionAnswer | Promise<ConnectionAnswer> {\n\tif (!(connection instanceof ThreadConnection) || !(\"params\" in request)) return connection.request(request);\n\treturn connection.request({ ...request, params: request.params.map(sendable) });\n}\n\n/**\n * A binary value as a connection's thread is sent it: the bytes it holds now, as a statement on the calling thread\n * binds them when it runs. A message shares a `SharedArrayBuffer` with the thread, so a change the caller makes before\n * the thread runs the statement would reach it, and it copies the whole buffer behind a view, so a view of part of a\n * buffer, or of a shared one, is sent as a copy of its own bytes. Any other value is sent as it is.\n */\nfunction sendable(value: SqliteValue): SqliteValue {\n\tif (!isUint8Array(value)) return value;\n\tif (!isSharedArrayBuffer(value.buffer) && value.byteOffset === 0 && value.byteLength === value.buffer.byteLength)\n\t\treturn value;\n\treturn new Uint8Array(value);\n}\n\nclass NodeSqliteDatabase implements SqliteDatabase {\n\treadonly descriptor: StorageDescriptor;\n\tprivate readonly connection: SqliteConnection;\n\tprivate jsonbExtract?: Promise<boolean>;\n\tprivate tail: Promise<void> = Promise.resolve();\n\t/** Operations queued on this connection so far; a batch's `position` is the one that commits it. */\n\tprivate enqueued = 0;\n\t/** Batches whose commit has not started, in order; the last one takes new transactions while it is open. */\n\tprivate readonly waitingBatches: PendingBatch[] = [];\n\tprivate closing = false;\n\tprivate closePromise?: Promise<void>;\n\tprivate readonly executor: ReturnType<NodeSqliteDatabase[\"createExecutor\"]>;\n\n\tprivate readonly transactionIdentity: string | object;\n\tprivate readonly lockWaitMs: number;\n\tprivate readonly groupCommitHoldMs: number;\n\t/** Cross-process first-come-first-served order for the write lock; absent for in-memory databases. */\n\tprivate readonly writeQueue?: SqliteWriteQueue;\n\t/** This connection's record of when it holds the write lock, named in the error of a writer that gives up. */\n\tprivate readonly holderRecord?: SqliteHolderRecord;\n\tprivate readonly openLock?: HeldOpenLock;\n\tprivate readonly lockUse = new WriteLockUse();\n\t/** The ticket of the writer holding the lock, on its way out of the queue while the transaction runs. */\n\tprivate leaving?: { readonly ticket: string; readonly left: Promise<void> };\n\t/** What the writers' queue gave up on, once per reason, in the order it first happened. */\n\tprivate readonly degradations = new Map<StorageWriterQueueDegradedReason, StorageWriterQueueDegradedError>();\n\n\tconstructor(\n\t\tconnection: SqliteConnection,\n\t\tdescriptor: StorageDescriptor,\n\t\ttransactionIdentity: string | object = connection,\n\t\tlockWaitMs = DEFAULT_NODE_SQLITE_LOCK_WAIT_MS,\n\t\tgroupCommitHoldMs = DEFAULT_GROUP_COMMIT_HOLD_MS,\n\t\topenLock?: HeldOpenLock,\n\t) {\n\t\tthis.lockWaitMs = lockWaitMs;\n\t\tthis.groupCommitHoldMs = groupCommitHoldMs;\n\t\tthis.transactionIdentity = transactionIdentity;\n\t\tthis.connection = connection;\n\t\tthis.descriptor = descriptor;\n\t\tthis.openLock = openLock;\n\t\tthis.executor = this.createExecutor(() => true);\n\t\tif (typeof transactionIdentity === \"string\") {\n\t\t\tthis.writeQueue = new SqliteWriteQueue(\n\t\t\t\ttransactionIdentity,\n\t\t\t\t(reason, cause) => this.degraded(reason, cause),\n\t\t\t\t() => send(connection, { kind: \"now\" }) as number | Promise<number>,\n\t\t\t);\n\t\t\tthis.holderRecord = new SqliteHolderRecord(transactionIdentity, (cause) =>\n\t\t\t\tthis.degraded(\"holder-record-unavailable\", cause),\n\t\t\t);\n\t\t}\n\t}\n\n\tsupportsJsonbExtract(): Promise<boolean> {\n\t\t// Bun on macOS loads the system SQLite. Its functions need not match the build-time version.\n\t\tthis.jsonbExtract ??= this.enqueueStatement(() => this.executor.checkJsonbExtract()).catch(() => {\n\t\t\t// A schema lock can also prevent preparation. Don't remember it as a missing function.\n\t\t\tthis.jsonbExtract = undefined;\n\t\t\treturn false;\n\t\t});\n\t\treturn this.jsonbExtract;\n\t}\n\n\t/**\n\t * The bytes this process may still write on the file system that holds the database file (where a link to it points,\n\t * and where its write-ahead log goes), or undefined for a database in memory or when the file system does not say.\n\t */\n\tasync freeBytes(): Promise<number | undefined> {\n\t\tconst path = this.descriptor.location;\n\t\tif (path === \"\" || path === \":memory:\") return undefined;\n\t\ttry {\n\t\t\t// The file itself, not its directory: a link to a database on another file system measures that file system.\n\t\t\tconst { bavail, bsize } = await statfs(path);\n\t\t\treturn Number(bavail) * Number(bsize);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\t/** Creates this connection's write-lock record; see `SqliteHolderRecord`. */\n\tasync openHolderRecord(): Promise<void> {\n\t\tawait this.holderRecord?.open();\n\t}\n\n\twriterQueueStats(): WriterQueueStats {\n\t\treturn this.lockUse.stats(this.queueOp(() => this.writeQueue?.liveTickets().length ?? 0));\n\t}\n\n\t/**\n\t * Sends one request to the connection. A driver failure is a `StorageUnavailableError`, thrown at once by a\n\t * connection on the calling thread and rejected by one on a thread of its own.\n\t */\n\tprivate call(request: ConnectionRequest): ConnectionAnswer | Promise<ConnectionAnswer> {\n\t\tlet answer: ConnectionAnswer | Promise<ConnectionAnswer>;\n\t\ttry {\n\t\t\tanswer = send(this.connection, request);\n\t\t} catch (cause) {\n\t\t\tthrow unavailable(this.descriptor, cause);\n\t\t}\n\t\tif (!(answer instanceof Promise)) return answer;\n\t\treturn answer.catch((cause: unknown) => {\n\t\t\tthrow unavailable(this.descriptor, cause);\n\t\t});\n\t}\n\n\t/**\n\t * One non-blocking `BEGIN IMMEDIATE`. node:sqlite runs `busy_timeout` synchronously, so a lock held by another\n\t * process would hold the connection's thread for the whole timeout. The attempt runs with `busy_timeout=0` and the\n\t * connection's own value is restored before answering, so single statements outside a transaction keep it.\n\t * Callers reach this only through `enqueue` and the transaction gate, so nothing else runs on the connection in\n\t * between.\n\t */\n\tprivate tryBegin(): undefined | Promise<undefined> {\n\t\treturn this.call({ kind: \"begin\" }) as undefined | Promise<undefined>;\n\t}\n\n\t/** Changes whenever another connection commits to the database: the lock is being used, not held idle. */\n\tprivate async dataVersion(): Promise<number> {\n\t\treturn (await this.call({ kind: \"dataVersion\" })) as number;\n\t}\n\n\t/**\n\t * Takes the write lock without blocking the event loop. Nothing has run yet when `BEGIN IMMEDIATE` reports\n\t * SQLITE_BUSY, so the attempt is retried. A refused writer queues with writers in other processes and attempts the\n\t * lock only when no earlier writer is still waiting, so none starves (#3978). It attempts again the moment the\n\t * writer releasing the lock touches its ticket (#4316), and otherwise when its recheck timer fires. The wait ends\n\t * only when no other connection has committed for `lockWaitMs`, whether this writer is still queued or already\n\t * trying the lock: a queued writer counts only real commits as progress, not older tickets ahead of it. The\n\t * `StorageWriteLockTimeoutError` of a writer that gives up names the process holding the lock. Every other failure,\n\t * including a writers' queue that cannot be used, rejects at once with its cause.\n\t */\n\tprivate async begin(lockWaitMs = this.lockWaitMs): Promise<void> {\n\t\tconst waitStarted = performance.now();\n\t\tlet ticket: SqliteWriteTicket | undefined;\n\t\tlet notices: ReleaseNotices | undefined;\n\t\tlet holding = false;\n\t\ttry {\n\t\t\t// Before its first attempt, so a holder stopped or starved the moment it takes the lock is still named.\n\t\t\tawait this.holderRecord?.trying();\n\t\t\t// Writers already waiting in other processes go first.\n\t\t\tconst queue = this.writeQueue;\n\t\t\tqueue?.observe();\n\t\t\tif (queue !== undefined && (await queue.contendedOffLoop())) {\n\t\t\t\tconst waiting = await this.queueFileOp(() => queue.liveTicketsOffLoop());\n\t\t\t\tif (waiting.length > 0) ticket = await this.queueFileOp(() => queue.join(waiting));\n\t\t\t}\n\t\t\t// Read only once this writer waits, so an uncontended transaction pays nothing for it.\n\t\t\tlet version = ticket === undefined ? undefined : await this.dataVersion();\n\t\t\tlet stalledSince = performance.now();\n\t\t\tlet lastCause: unknown;\n\t\t\tfor (;;) {\n\t\t\t\tnotices?.clear();\n\t\t\t\tif (ticket !== undefined) notices = await this.watchTicket(ticket, notices);\n\t\t\t\tconst behind = ticket !== undefined && (await this.queueFileOp(() => ticket!.behindOthers()));\n\t\t\t\tif (!behind) {\n\t\t\t\t\tconst attempt = this.attemptBegin();\n\t\t\t\t\tconst refused = attempt instanceof Promise ? await attempt : attempt;\n\t\t\t\t\tif (refused === undefined) {\n\t\t\t\t\t\tholding = true;\n\t\t\t\t\t\tthis.acquired(waitStarted);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tlastCause = refused;\n\t\t\t\t\tif (ticket === undefined && queue !== undefined) {\n\t\t\t\t\t\t// A release before this ticket existed told nobody: watch it, then try once more before waiting.\n\t\t\t\t\t\tticket = await this.queueFileOp(async () => queue.join(await queue.liveTicketsOffLoop()));\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Only another connection's commit is progress; a queued writer measures its stall the same way.\n\t\t\t\tconst current = await this.dataVersion();\n\t\t\t\tconst committed = version !== undefined && current !== version;\n\t\t\t\tif (version === undefined) version = current;\n\t\t\t\telse if (committed) {\n\t\t\t\t\tversion = current;\n\t\t\t\t\tstalledSince = performance.now();\n\t\t\t\t}\n\t\t\t\tconst stalledMs = performance.now() - stalledSince;\n\t\t\t\tif (stalledMs >= lockWaitMs) throw await this.lockWaitTimeout(lockWaitMs, stalledMs, behind, lastCause);\n\t\t\t\tif (!behind && committed && (await this.attemptThroughRelease())) {\n\t\t\t\t\tholding = true;\n\t\t\t\t\tthis.acquired(waitStarted);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst recheckMs =\n\t\t\t\t\tnotices?.watching === true || stalledMs >= this.lockWaitMs\n\t\t\t\t\t\t? LOCK_WAIT_RECHECK_MS\n\t\t\t\t\t\t: UNWATCHED_LOCK_RETRY_MS;\n\t\t\t\tconst delay = Math.min(recheckMs, lockWaitMs - stalledMs);\n\t\t\t\tawait (notices?.wait(delay) ?? new Promise<void>((resolve) => setTimeout(resolve, delay)));\n\t\t\t}\n\t\t} finally {\n\t\t\tnotices?.close();\n\t\t\t// A writer holding the lock never waits for the queue's files: another connection of this process that writes\n\t\t\t// meanwhile waits for the lock in SQLite's busy handler, which blocks this thread until the lock is free, so\n\t\t\t// the holder could not go on. Its ticket leaves while the transaction runs; the release waits for it to be gone.\n\t\t\tif (holding && ticket !== undefined) this.leaving = { ticket: ticket.name, left: ticket.leave() };\n\t\t\telse await ticket?.leave();\n\t\t\tif (!holding) await this.holderRecord?.free();\n\t\t}\n\t}\n\n\t/**\n\t * One attempt at the lock: `undefined` once it is taken, or the SQLITE_BUSY that refused it. Anything else fails.\n\t * Answered at once on the calling thread, and as a promise by a connection on a thread of its own.\n\t */\n\tprivate attemptBegin(): unknown {\n\t\tconst refusal = (error: unknown): unknown => {\n\t\t\tconst cause = error instanceof StorageUnavailableError ? error.cause : undefined;\n\t\t\tif (!isSqliteBusy(cause)) throw error;\n\t\t\treturn cause;\n\t\t};\n\t\tlet attempt: undefined | Promise<undefined>;\n\t\ttry {\n\t\t\tattempt = this.tryBegin();\n\t\t} catch (error) {\n\t\t\treturn refusal(error);\n\t\t}\n\t\treturn attempt instanceof Promise ? attempt.then(() => undefined, refusal) : undefined;\n\t}\n\n\t/**\n\t * After a refused attempt, while other connections are committing through the lock, keeps attempting it on every\n\t * event-loop turn for `LOCK_RELEASE_RETRY_MS`; returns whether it took the lock. A timer only ever wakes this writer\n\t * on the system's timer tick, and on Windows that tick is 15.6 ms, shared by every process: a writer that does\n\t * not queue (a raw SQLite client, an older Atomic) and takes the lock again from its own timer does so on the same\n\t * tick, so the lock is free only between ticks and a writer that tried only when its timer fired never found it\n\t * free while that writer kept committing. Trying on every turn for a tick finds the lock the moment such a\n\t * writer's commit lets go of it.\n\t */\n\tprivate async attemptThroughRelease(): Promise<boolean> {\n\t\tconst until = performance.now() + LOCK_RELEASE_RETRY_MS;\n\t\tfor (let attempt = 0; attempt < LOCK_RELEASE_RETRY_ATTEMPTS && performance.now() < until; attempt++) {\n\t\t\tawait new Promise<void>((resolve) => setImmediate(resolve));\n\t\t\tif ((await this.attemptBegin()) === undefined) return true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Keeps the ticket live and watched: one watch for the whole wait, started again only when the ticket had to be\n\t * recreated, since a watch ends with the file it watched.\n\t */\n\tprivate async watchTicket(ticket: SqliteWriteTicket, notices: ReleaseNotices | undefined): Promise<ReleaseNotices> {\n\t\tconst recreated = await this.queueFileOp(() => ticket.keepLive());\n\t\tif (notices !== undefined && !recreated) return notices;\n\t\tnotices?.close();\n\t\treturn ticket.watch((cause) => this.degraded(\"watch-unavailable\", cause));\n\t}\n\n\tprivate async lockWaitTimeout(\n\t\tlockWaitMs: number,\n\t\tstalledMs: number,\n\t\tbehind: boolean,\n\t\tlastCause: unknown,\n\t): Promise<StorageWriteLockTimeoutError> {\n\t\tconst holder = await this.holderRecord?.latestHolder();\n\t\treturn new StorageWriteLockTimeoutError(\n\t\t\tthis.descriptor,\n\t\t\t{\n\t\t\t\ttimeoutMs: lockWaitMs,\n\t\t\t\telapsedMs: Math.round(stalledMs),\n\t\t\t\tphase: behind ? \"queued\" : \"acquiring\",\n\t\t\t\t...(holder !== undefined && \"pid\" in holder ? { holderPid: holder.pid, holderHeldMs: holder.heldMs } : {}),\n\t\t\t\t...(holder !== undefined && \"candidates\" in holder\n\t\t\t\t\t? { holderCandidates: holder.candidates.join(\", \") }\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t\tlastCause as StorageFailureCause,\n\t\t);\n\t}\n\n\tprivate acquired(waitStarted: number): void {\n\t\tthis.holderRecord?.held();\n\t\tthis.lockUse.acquired(waitStarted);\n\t}\n\n\t/**\n\t * Runs the moment COMMIT or ROLLBACK lets go of the write lock, before any caller settles, so no caller's work can\n\t * delay the next writer: it hands the turn to the oldest writer waiting in another process. A turn that cannot be\n\t * handed on is still noticed by that writer's recheck timer, so it never fails the transaction.\n\t */\n\tprivate async released(committed: boolean): Promise<void> {\n\t\tthis.lockUse.released(committed);\n\t\tconst recorded = this.holderRecord?.free();\n\t\tconst leaving = this.leaving;\n\t\tthis.leaving = undefined;\n\t\t// Gone before the turn is handed on, so the writer it wakes finds no ticket of this one ahead of it.\n\t\tawait leaving?.left;\n\t\ttry {\n\t\t\tawait this.writeQueue?.wakeNext(leaving?.ticket);\n\t\t} catch (cause) {\n\t\t\tthis.degraded(\"wake-failed\", cause);\n\t\t}\n\t\tawait recorded;\n\t}\n\n\t/**\n\t * Records a degradation of the writers' queue once per reason, then emits it as a process warning for hosts that\n\t * listen for one. The record is what stays readable where warnings are suppressed, as in Atomic's own processes;\n\t * nothing fails.\n\t */\n\tprivate degraded(reason: StorageWriterQueueDegradedReason, cause: unknown): void {\n\t\tif (this.degradations.has(reason)) return;\n\t\tconst degradation = new StorageWriterQueueDegradedError(this.descriptor, reason, cause as StorageFailureCause);\n\t\tthis.degradations.set(reason, degradation);\n\t\tprocess.emitWarning(degradation);\n\t\treportDegradationInDebugMode(degradation);\n\t}\n\n\twriterQueueDegradation(): readonly StorageWriterQueueDegradedError[] {\n\t\treturn [...this.degradations.values()];\n\t}\n\n\t/** Runs a writers'-queue file operation; a failure (an unwritable queue directory, say) is a typed storage failure. */\n\tprivate queueOp<T>(operation: () => T): T {\n\t\ttry {\n\t\t\treturn operation();\n\t\t} catch (cause) {\n\t\t\tthrow new StorageWriterQueueUnusableError(this.descriptor, cause as StorageFailureCause);\n\t\t}\n\t}\n\n\t/** `queueOp` for the file work a waiting writer does off the event loop. */\n\tprivate async queueFileOp<T>(operation: () => Promise<T>): Promise<T> {\n\t\ttry {\n\t\t\treturn await operation();\n\t\t} catch (cause) {\n\t\t\tthrow new StorageWriterQueueUnusableError(this.descriptor, cause as StorageFailureCause);\n\t\t}\n\t}\n\n\t/**\n\t * Statements on the connection, each sent the moment it is called, so calls a transaction makes without awaiting\n\t * the ones before run in the order it made them, as on a connection that runs each one as it is called.\n\t */\n\tprivate createExecutor(active: () => boolean): SqliteExecutor & { checkJsonbExtract(): Promise<boolean> } {\n\t\tconst execute = async <T>(request: ConnectionRequest, params: readonly SqliteValue[] = []): Promise<T> => {\n\t\t\tif (!active()) throw new StorageTransactionClosedError();\n\t\t\tconst invalidIndex = params.findIndex((value) => typeof value === \"string\" && value.includes(\"\\0\"));\n\t\t\tif (invalidIndex !== -1) throw new StorageInvalidTextError(invalidIndex);\n\t\t\treturn this.call(request) as T | Promise<T>;\n\t\t};\n\t\treturn {\n\t\t\tcheckJsonbExtract: () => execute<boolean>({ kind: \"jsonbExtract\" }),\n\t\t\texec: (sql) => execute<void>({ kind: \"exec\", sql }),\n\t\t\trun: (sql, ...params) => execute<{ changes: number }>({ kind: \"run\", sql, params }, params),\n\t\t\tget: <T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]) =>\n\t\t\t\texecute<T | undefined>({ kind: \"get\", sql, params }, params),\n\t\t\tall: <T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]) =>\n\t\t\t\texecute<T[]>({ kind: \"all\", sql, params }, params),\n\t\t};\n\t}\n\n\tprivate enqueue<T>(operation: () => Promise<T>): Promise<T> {\n\t\tif (this.closing) return Promise.reject(new StoreClosedError(this.descriptor));\n\t\tthis.enqueued += 1;\n\t\tconst result = this.tail.then(operation);\n\t\tthis.tail = result.then(\n\t\t\t() => {},\n\t\t\t() => {},\n\t\t);\n\t\treturn result;\n\t}\n\n\t/** A statement queued after open transactions runs after them, so later transactions start a new batch. */\n\tprivate enqueueStatement<T>(operation: () => Promise<T>): Promise<T> {\n\t\tconst last = this.waitingBatches.at(-1);\n\t\tif (last !== undefined) last.open = false;\n\t\treturn this.enqueue(operation);\n\t}\n\n\texec(sql: string): Promise<void> {\n\t\treturn this.enqueueStatement(() => this.executor.exec(sql));\n\t}\n\n\trun(sql: string, ...params: readonly SqliteValue[]) {\n\t\tconst bound = snapshotParams(params);\n\t\treturn this.enqueueStatement(() => this.executor.run(sql, ...bound));\n\t}\n\n\tget<T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]): Promise<T | undefined> {\n\t\tconst bound = snapshotParams(params);\n\t\treturn this.enqueueStatement(() => this.executor.get<T>(sql, ...bound));\n\t}\n\n\tall<T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]): Promise<T[]> {\n\t\tconst bound = snapshotParams(params);\n\t\treturn this.enqueueStatement(() => this.executor.all<T>(sql, ...bound));\n\t}\n\n\t/** Idle-only housekeeping: do not join a batch, wait behind an operation on this handle or another handle's\n\t * transaction, or get in front of writers already waiting on another process. */\n\tasync tryMaintenance(callback: (tx: SqliteExecutor) => Promise<void>): Promise<boolean> {\n\t\tconst position = this.enqueued;\n\t\tlet idle = false;\n\t\tvoid this.tail.then(() => {\n\t\t\tidle = true;\n\t\t});\n\t\tawait Promise.resolve();\n\t\tif (!idle || this.enqueued !== position || this.closing) return false;\n\t\treturn this.enqueueStatement(async () => {\n\t\t\tconst key = this.transactionIdentity;\n\t\t\tif (typeof key === \"string\" ? gates.files.has(key) : gates.connections.has(key)) return false;\n\t\t\treturn gateTransaction(key, async () => {\n\t\t\t\t// The queue's directory outlives its writers: only a live ticket means a writer is waiting. One that cannot be\n\t\t\t\t// read counts as a writer waiting.\n\t\t\t\tconst queue = this.writeQueue;\n\t\t\t\tif (queue !== undefined && (await queue.contendedOffLoop())) {\n\t\t\t\t\tconst waiting = await queue.liveTicketsOffLoop().catch(() => undefined);\n\t\t\t\t\tif (waiting === undefined || waiting.length > 0) return false;\n\t\t\t\t}\n\t\t\t\tconst start = performance.now();\n\t\t\t\tawait this.holderRecord?.trying();\n\t\t\t\ttry {\n\t\t\t\t\tconst attempt = this.attemptBegin();\n\t\t\t\t\tif ((attempt instanceof Promise ? await attempt : attempt) !== undefined) {\n\t\t\t\t\t\tawait this.holderRecord?.free();\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tawait this.holderRecord?.free();\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tthis.acquired(start);\n\t\t\t\treturn new Promise<boolean>((resolve, reject) => {\n\t\t\t\t\tvoid this.commitAlone({ callback, resolve: () => resolve(true), reject }).catch(reject);\n\t\t\t\t});\n\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Group commit: transactions queued while earlier work holds the connection join one `BEGIN IMMEDIATE … COMMIT`,\n\t * each inside its own savepoint and in the order they were requested. A transaction that throws rolls back only\n\t * its savepoint and rejects only its caller; every caller settles after the shared commit, so durability is the\n\t * same as a transaction of its own. Under load one lock acquisition and one sync serve the whole batch, including\n\t * the transactions requested while it waited for the lock. A batch waits for the lock as long as the most patient\n\t * of its transactions.\n\t */\n\ttransaction<T>(\n\t\tcallback: (transaction: SqliteExecutor) => Promise<T>,\n\t\toptions?: SqliteTransactionOptions,\n\t): Promise<T> {\n\t\tif (options?.readOnly === true) {\n\t\t\treturn this.enqueueStatement(async () => {\n\t\t\t\tawait this.executor.exec(\"BEGIN\");\n\t\t\t\tlet active = true;\n\t\t\t\ttry {\n\t\t\t\t\tconst value = await callback(this.createExecutor(() => active));\n\t\t\t\t\tactive = false;\n\t\t\t\t\tawait this.executor.exec(\"COMMIT\");\n\t\t\t\t\treturn value;\n\t\t\t\t} catch (cause) {\n\t\t\t\t\tactive = false;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.executor.exec(\"ROLLBACK\");\n\t\t\t\t\t} catch (rollbackCause) {\n\t\t\t\t\t\tthrow new StorageRollbackError(cause as StorageFailureCause, rollbackCause as StorageFailureCause);\n\t\t\t\t\t}\n\t\t\t\t\tthrow cause;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\tif (this.closing) return Promise.reject(new StoreClosedError(this.descriptor));\n\t\treturn new Promise<T>((resolve, reject) => {\n\t\t\tconst queued: QueuedTransaction = {\n\t\t\t\tcallback,\n\t\t\t\tresolve: resolve as (value: unknown) => void,\n\t\t\t\treject,\n\t\t\t\tlockWaitMs: options?.lockWaitMs,\n\t\t\t};\n\t\t\tconst last = this.waitingBatches.at(-1);\n\t\t\tif (last?.open === true && last.members.length < MAX_GROUP_COMMIT_TRANSACTIONS) {\n\t\t\t\tlast.members.push(queued);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.startBatch([queued]);\n\t\t});\n\t}\n\n\tprivate startBatch(members: QueuedTransaction[]): void {\n\t\tconst batch: PendingBatch = { members, position: 0, open: true };\n\t\tthis.waitingBatches.push(batch);\n\t\tvoid this.enqueue(() => this.commitBatch(batch));\n\t\tbatch.position = this.enqueued;\n\t}\n\n\tprivate commitBatch(batch: PendingBatch): Promise<void> {\n\t\t// The batch ahead of it took its transactions along when it got the lock.\n\t\tif (this.waitingBatches[0] !== batch) return Promise.resolve();\n\t\tthis.waitingBatches.shift();\n\t\treturn gateTransaction(this.transactionIdentity, () => this.runBatch(batch, true));\n\t}\n\n\t/**\n\t * Takes the write lock for the batch, then commits it on its own or as a group. On its first acquisition the\n\t * transactions requested directly behind it while it waited join it: otherwise they would queue for the lock all\n\t * over again once it lets go. Members left after the hold budget take the lock again with nothing new, so other\n\t * connections to the file wait for at most one batch of this one's.\n\t */\n\tprivate async runBatch(batch: PendingBatch, firstAcquisition: boolean): Promise<void> {\n\t\ttry {\n\t\t\tawait this.begin(this.lockWait(batch.members));\n\t\t} catch (cause) {\n\t\t\tfor (const queued of batch.members.splice(0)) queued.reject(cause);\n\t\t\treturn;\n\t\t}\n\t\tif (firstAcquisition) this.absorbNext(batch);\n\t\tawait (batch.members.length === 1 ? this.commitAlone(batch.members.pop()!) : this.commitMembers(batch));\n\t}\n\n\t/**\n\t * Moves the transactions of the batches queued directly behind this one (no statement between them) into this one,\n\t * up to the batch size limit. They run after this batch's own, in the order they were requested.\n\t */\n\tprivate absorbNext(batch: PendingBatch): void {\n\t\tfor (let next = this.waitingBatches[0]; next?.position === batch.position + 1; next = this.waitingBatches[0]) {\n\t\t\tbatch.members.push(...next.members.splice(0, MAX_GROUP_COMMIT_TRANSACTIONS - batch.members.length));\n\t\t\tif (next.members.length > 0) return;\n\t\t\tthis.waitingBatches.shift();\n\t\t\tbatch.position = next.position;\n\t\t}\n\t}\n\n\tprivate lockWait(batch: readonly QueuedTransaction[]): number {\n\t\treturn Math.max(...batch.map((queued) => queued.lockWaitMs ?? this.lockWaitMs));\n\t}\n\n\t/** A transaction with nobody queued with it commits on its own, without savepoints. */\n\tprivate async commitAlone(queued: QueuedTransaction): Promise<void> {\n\t\tlet active = true;\n\t\ttry {\n\t\t\tconst value = await queued.callback(this.createExecutor(() => active));\n\t\t\tactive = false;\n\t\t\tawait this.executor.exec(\"COMMIT\");\n\t\t\tawait this.released(true);\n\t\t\tqueued.resolve(value);\n\t\t} catch (cause) {\n\t\t\tactive = false;\n\t\t\ttry {\n\t\t\t\tawait this.executor.exec(\"ROLLBACK\");\n\t\t\t} catch (rollbackCause) {\n\t\t\t\tawait this.released(false);\n\t\t\t\tqueued.reject(new StorageRollbackError(cause as StorageFailureCause, rollbackCause as StorageFailureCause));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait this.released(false);\n\t\t\tqueued.reject(cause);\n\t\t}\n\t}\n\n\t/**\n\t * Runs the batch's members in one transaction, for at most `groupCommitHoldMs`: members left when it runs out\n\t * wait for the lock again, still ahead of anything queued after them.\n\t */\n\tprivate async commitMembers(batch: PendingBatch): Promise<void> {\n\t\tconst began = performance.now();\n\t\tconst outcomes: TransactionOutcome[] = [];\n\t\tfor (const queued of batch.members) {\n\t\t\tif (outcomes.length > 0 && performance.now() - began >= this.groupCommitHoldMs) break;\n\t\t\tconst savepoint = `atomic_group_${outcomes.length}`;\n\t\t\tlet active = true;\n\t\t\ttry {\n\t\t\t\tawait this.executor.exec(`SAVEPOINT ${savepoint}`);\n\t\t\t\tconst value = await queued.callback(this.createExecutor(() => active));\n\t\t\t\tactive = false;\n\t\t\t\tawait this.executor.exec(`RELEASE ${savepoint}`);\n\t\t\t\toutcomes.push({ ok: true, value });\n\t\t\t} catch (cause) {\n\t\t\t\tactive = false;\n\t\t\t\ttry {\n\t\t\t\t\tawait this.executor.exec(`ROLLBACK TO ${savepoint}`);\n\t\t\t\t\tawait this.executor.exec(`RELEASE ${savepoint}`);\n\t\t\t\t} catch (rollbackCause) {\n\t\t\t\t\tawait this.abandonMembers(batch, outcomes, cause, rollbackCause);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\toutcomes.push({ ok: false, error: cause });\n\t\t\t}\n\t\t}\n\t\tconst ran = batch.members.splice(0, outcomes.length);\n\t\tlet commitCause: unknown;\n\t\tlet committed = true;\n\t\ttry {\n\t\t\tawait this.executor.exec(\"COMMIT\");\n\t\t} catch (cause) {\n\t\t\tcommitted = false;\n\t\t\tcommitCause = cause;\n\t\t\tawait this.rollbackQuietly();\n\t\t}\n\t\tawait this.released(committed);\n\t\tran.forEach((queued, index) => {\n\t\t\tconst outcome = outcomes[index]!;\n\t\t\tif (!committed) queued.reject(outcome.ok ? commitCause : outcome.error);\n\t\t\telse if (outcome.ok) queued.resolve(outcome.value);\n\t\t\telse queued.reject(outcome.error);\n\t\t});\n\t\tif (batch.members.length > 0) await this.runBatch(batch, false);\n\t}\n\n\t/**\n\t * A savepoint that cannot be rolled back leaves the whole transaction unusable: earlier members lose their\n\t * uncommitted writes and fail, the failing member reports both causes, and members that have not run yet get a\n\t * fresh transaction right away, still ahead of anything queued after them, because nothing of theirs has happened.\n\t */\n\tprivate async abandonMembers(\n\t\tbatch: PendingBatch,\n\t\toutcomes: TransactionOutcome[],\n\t\tcause: unknown,\n\t\trollbackCause: unknown,\n\t): Promise<void> {\n\t\tawait this.rollbackQuietly();\n\t\tawait this.released(false);\n\t\tconst failed = outcomes.length;\n\t\tconst ran = batch.members.splice(0, failed + 1);\n\t\tran.slice(0, failed).forEach((queued, index) => {\n\t\t\tconst outcome = outcomes[index]!;\n\t\t\tqueued.reject(outcome.ok ? unavailable(this.descriptor, rollbackCause) : outcome.error);\n\t\t});\n\t\tran[failed]!.reject(new StorageRollbackError(cause as StorageFailureCause, rollbackCause as StorageFailureCause));\n\t\tif (batch.members.length > 0) await this.runBatch(batch, false);\n\t}\n\n\tprivate async rollbackQuietly(): Promise<void> {\n\t\ttry {\n\t\t\tawait this.executor.exec(\"ROLLBACK\");\n\t\t} catch {\n\t\t\t// SQLite already rolled the transaction back; there is nothing left to undo.\n\t\t}\n\t}\n\n\tclose(): Promise<void> {\n\t\tif (!this.closePromise) {\n\t\t\tthis.closing = true;\n\t\t\tthis.closePromise = this.tail.then(async () => {\n\t\t\t\ttry {\n\t\t\t\t\tawait this.holderRecord?.close();\n\t\t\t\t\tawait this.call({ kind: \"close\" });\n\t\t\t\t} finally {\n\t\t\t\t\tawait releaseOpenLock(this.openLock);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\treturn this.closePromise;\n\t}\n}\n\n/** Rejects a group-commit budget that is not a finite number of milliseconds, 0 or more, before anything opens. */\nfunction groupCommitHold(value: number | undefined): number {\n\tif (value === undefined) return DEFAULT_GROUP_COMMIT_HOLD_MS;\n\tif (!Number.isFinite(value) || value < 0)\n\t\tthrow new StorageConfigError(\n\t\t\t\"sdk\",\n\t\t\t\"groupCommitHoldMs\",\n\t\t\t\"non-negative-finite-number-required\",\n\t\t\t`Pass a finite number of milliseconds, 0 or more, or omit it for the default of ${DEFAULT_GROUP_COMMIT_HOLD_MS} ms`,\n\t\t);\n\treturn value;\n}\n\n/**\n * Longest Windows database path SQLite opens as written. SQLite's Windows file calls fail a path, or the `-journal`,\n * `-wal` or `-shm` file beside it, over 260 characters (`MAX_PATH`) with code 14 (#5139); this leaves room for those.\n */\nconst WINDOWS_SQLITE_PLAIN_PATH_LIMIT = 240;\n\n/**\n * The path SQLite opens `path` by. On Windows a file path longer than SQLite can open as written takes the `\\\\?\\`\n * long-path form, which SQLite accepts at any length (#5139). Every other path, `:memory:`, `file:` URIs and every\n * path on other platforms are passed unchanged, so the database's location reads as before wherever it fits.\n */\nexport function sqliteFilePath(path: string, platform: NodeJS.Platform = process.platform): string {\n\tif (platform !== \"win32\" || path === \":memory:\" || path.startsWith(\"file:\")) return path;\n\treturn win32.resolve(path).length > WINDOWS_SQLITE_PLAIN_PATH_LIMIT ? win32.toNamespacedPath(path) : path;\n}\n\n/** `location` without the `\\\\?\\` or `\\\\?\\UNC\\` prefix of the Windows long-path form: the path it names. */\nexport function ordinarySqlitePath<T extends string | null>(location: T): T {\n\tif (location === null) return location;\n\tif (location.startsWith(\"\\\\\\\\?\\\\UNC\\\\\")) return `\\\\\\\\${location.slice(8)}` as T;\n\tif (location.startsWith(\"\\\\\\\\?\\\\\")) return location.slice(4) as T;\n\treturn location;\n}\n\n/**\n * Opens an in-memory database (see `isInMemoryDatabase`) on the calling thread: it has no file, so neither opening it\n * nor its statements wait for the disk, and SQLite's busy handler never waits for it, since no connection of any\n * process holds a lock on it.\n */\nfunction openOnCallerThread(\n\tDatabase: typeof DatabaseSync,\n\tpath: string,\n\treadOnly: boolean,\n): { readonly connection: CallerThreadConnection; readonly location: string | null } {\n\tconst connection = new Database(path, { readOnly });\n\treturn { connection: new CallerThreadConnection(connection, true), location: connection.location() };\n}\n\n/**\n * Opens `path` with SQLite on a thread of its own, through the long-path form when it needs it, and reports its\n * location as the ordinary path, so every reader of it (identity, error messages, callers comparing paths) sees the\n * path it was given whatever its length (#5139).\n */\nasync function openOnOwnThread(\n\tpath: string,\n\treadOnly: boolean,\n): Promise<{ readonly connection: ThreadConnection; readonly location: string | null }> {\n\tconst { connection, location } = await ThreadConnection.open(path, { readOnly, openAs: sqliteFilePath(path) });\n\treturn { connection, location: ordinarySqlitePath(location) };\n}\n\nexport async function openNodeSqliteDatabase(\n\tpath: string,\n\t{\n\t\tbusyTimeoutMs = 5000,\n\t\tlockWaitMs = DEFAULT_NODE_SQLITE_LOCK_WAIT_MS,\n\t\treadOnly = false,\n\t\tgroupCommitHoldMs,\n\t}: {\n\t\tbusyTimeoutMs?: number;\n\t\tlockWaitMs?: number;\n\t\treadOnly?: boolean;\n\t\t/**\n\t\t * How long one group commit runs queued transactions before it commits them and lets other processes' writers\n\t\t * take the lock (`DEFAULT_GROUP_COMMIT_HOLD_MS` when omitted). Checked between transactions, so one\n\t\t * transaction is never split. 0 commits each transaction on its own.\n\t\t */\n\t\tgroupCommitHoldMs?: number;\n\t} = {},\n): Promise<SqliteDatabase> {\n\tconst holdMs = groupCommitHold(groupCommitHoldMs);\n\tconst descriptor = { adapter: \"node-sqlite\", location: path };\n\t// Load node:sqlite on first open: importing it prints Node's experimental warning, which every importer of the\n\t// package entry point would otherwise see.\n\tlet Database: typeof DatabaseSync;\n\ttry {\n\t\t({ DatabaseSync: Database } = await import(\"node:sqlite\"));\n\t} catch (cause) {\n\t\tthrow new StorageAdapterLoadError(\"node:sqlite\", cause as StorageFailureCause);\n\t}\n\tloadedDatabaseSync ??= Database;\n\tconst targetFile = sqliteTargetFilePath(path);\n\tlet heldOpenLock: HeldOpenLock | undefined;\n\tlet connection: SqliteConnection | undefined;\n\ttry {\n\t\tif (!readOnly && targetFile !== undefined) await mkdir(dirname(targetFile), { recursive: true });\n\t\theldOpenLock = await acquireOpenLock(targetFile, readOnly, busyTimeoutMs);\n\t\t// A file-backed connection runs on a thread of its own, so opening it, waiting for its locks and its synced\n\t\t// commits never hold this thread (#5376).\n\t\tconst opened = isInMemoryDatabase(path)\n\t\t\t? openOnCallerThread(Database, path, readOnly)\n\t\t\t: await openOnOwnThread(path, readOnly);\n\t\tconst configured = opened.connection;\n\t\tconnection = configured;\n\t\tconst exec = (sql: string) => send(configured, { kind: \"exec\", sql });\n\t\tawait exec(`PRAGMA busy_timeout=${busyTimeoutMs}`);\n\t\tif (!readOnly) {\n\t\t\t// SQLite does not wait for another process's lock while it changes the mode; the switch waits itself.\n\t\t\tawait switchToWriteAheadLog(exec, busyTimeoutMs);\n\t\t\tawait exec(\"PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON\");\n\t\t}\n\t\tconst location = opened.location;\n\t\tconst identity =\n\t\t\tlocation === null\n\t\t\t\t? connection\n\t\t\t\t: heldOpenLock?.target !== undefined && location === targetFile\n\t\t\t\t\t? heldOpenLock.target\n\t\t\t\t\t: await realpath(location);\n\t\tif (typeof identity === \"string\" && heldOpenLock !== undefined && heldOpenLock.target !== identity) {\n\t\t\tawait releaseOpenLock(heldOpenLock);\n\t\t\theldOpenLock = await acquireOpenLock(identity, readOnly, busyTimeoutMs);\n\t\t}\n\t\tconst database = new NodeSqliteDatabase(connection, descriptor, identity, lockWaitMs, holdMs, heldOpenLock);\n\t\tObject.defineProperty(database, \"readOnly\", { value: readOnly });\n\t\tif (!readOnly) await database.openHolderRecord();\n\t\treturn database;\n\t} catch (cause) {\n\t\ttry {\n\t\t\tif (connection !== undefined) await send(connection, { kind: \"close\" });\n\t\t} catch {\n\t\t\t// Preserve the opening failure if cleanup also fails.\n\t\t} finally {\n\t\t\tawait releaseOpenLock(heldOpenLock);\n\t\t}\n\t\tthrow unavailable(descriptor, cause);\n\t}\n}\n\n/** The busy timeout `wrapNodeSqliteDatabase` sets on a caller's connection. */\nconst WRAPPED_BUSY_TIMEOUT_MS = 5000;\n\nexport function wrapNodeSqliteDatabase(connection: DatabaseSync): SqliteDatabase {\n\tconst descriptor = { adapter: \"node-sqlite\", location: \":memory:\" };\n\tlet heldOpenLock: HeldOpenLock | undefined;\n\ttry {\n\t\tdescriptor.location = ordinarySqlitePath(connection.location()) || \":memory:\";\n\t\theldOpenLock = acquireOpenLockSync(descriptor.location);\n\t\tconnection.exec(`PRAGMA busy_timeout=${WRAPPED_BUSY_TIMEOUT_MS}`);\n\t\t// SQLite does not wait for another process's lock while it changes the mode; the switch waits itself.\n\t\tswitchToWriteAheadLogSync((sql) => connection.exec(sql), WRAPPED_BUSY_TIMEOUT_MS);\n\t\tconnection.exec(\"PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON\");\n\t\treturn new NodeSqliteDatabase(\n\t\t\tnew CallerThreadConnection(connection, false),\n\t\t\tdescriptor,\n\t\t\tconnection,\n\t\t\tundefined,\n\t\t\tundefined,\n\t\t\theldOpenLock,\n\t\t);\n\t} catch (cause) {\n\t\tvoid releaseOpenLock(heldOpenLock);\n\t\tthrow unavailable(descriptor, cause);\n\t}\n}\n\n/**\n * How one database handle has used the write lock over the last 10 seconds, and how many writers wait for it now in\n * any process. Throws `StorageUnsupportedOperationError` for a handle that `openNodeSqliteDatabase` or\n * `wrapNodeSqliteDatabase` did not return, and `StorageUnavailableError` when the writers' queue cannot be read.\n */\nexport function getWriterQueueStats(database: SqliteDatabase): WriterQueueStats {\n\tif (!(database instanceof NodeSqliteDatabase))\n\t\tthrow new StorageUnsupportedOperationError(database.descriptor, \"getWriterQueueStats\");\n\treturn database.writerQueueStats();\n}\n\n/**\n * What the writers' queue of a database handle has given up on, once per reason in the order it first happened, as\n * `StorageWriterQueueDegradedError`s: a waiting writer that cannot watch its ticket, a writer that could not notify\n * the next one, an abandoned ticket that could not be removed. Empty while the queue is healthy, and for a handle\n * without a cross-process queue (in-memory or wrapped). Transactions keep working through each of them; the same\n * errors are also emitted as process warnings, which Atomic's own processes suppress. Throws\n * `StorageUnsupportedOperationError` for a handle that `openNodeSqliteDatabase` or `wrapNodeSqliteDatabase` did not\n * return.\n */\nexport function getWriterQueueDegradation(database: SqliteDatabase): readonly StorageWriterQueueDegradedError[] {\n\tif (!(database instanceof NodeSqliteDatabase))\n\t\tthrow new StorageUnsupportedOperationError(database.descriptor, \"getWriterQueueDegradation\");\n\treturn database.writerQueueDegradation();\n}\n"]}