@bastani/atomic 0.10.1-alpha.1 → 0.10.2-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +76 -0
- package/dist/builtin/intercom/CHANGELOG.md +6 -0
- package/dist/builtin/intercom/broker/watchdog.ts +4 -0
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/CHANGELOG.md +22 -0
- package/dist/builtin/subagents/README.md +2 -0
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/subagents/skills/subagent/SKILL.md +3 -3
- package/dist/builtin/subagents/src/extension/index.bundle.mjs +269 -144
- package/dist/builtin/web-access/CHANGELOG.md +7 -0
- package/dist/builtin/web-access/index.bundle.mjs +9 -5
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/cli/list-models.d.ts.map +1 -1
- package/dist/cli/list-models.js +1 -14
- package/dist/cli/list-models.js.map +1 -1
- package/dist/core/agent-session-export.d.ts.map +1 -1
- package/dist/core/agent-session-export.js +13 -9
- package/dist/core/agent-session-export.js.map +1 -1
- package/dist/core/agent-session-message-queue.d.ts.map +1 -1
- package/dist/core/agent-session-message-queue.js +6 -3
- package/dist/core/agent-session-message-queue.js.map +1 -1
- package/dist/core/agent-session-methods.d.ts +3 -0
- package/dist/core/agent-session-methods.d.ts.map +1 -1
- package/dist/core/agent-session-methods.js.map +1 -1
- package/dist/core/agent-session-nested-tools.d.ts.map +1 -1
- package/dist/core/agent-session-nested-tools.js +2 -1
- package/dist/core/agent-session-nested-tools.js.map +1 -1
- package/dist/core/agent-session-prompt.d.ts.map +1 -1
- package/dist/core/agent-session-prompt.js +12 -0
- package/dist/core/agent-session-prompt.js.map +1 -1
- package/dist/core/agent-session-state.d.ts +6 -0
- package/dist/core/agent-session-state.d.ts.map +1 -1
- package/dist/core/agent-session-state.js +71 -4
- package/dist/core/agent-session-state.js.map +1 -1
- package/dist/core/agent-session-tool-hooks.d.ts.map +1 -1
- package/dist/core/agent-session-tool-hooks.js +9 -1
- package/dist/core/agent-session-tool-hooks.js.map +1 -1
- package/dist/core/agent-session-types.d.ts +2 -0
- package/dist/core/agent-session-types.d.ts.map +1 -1
- package/dist/core/agent-session-types.js.map +1 -1
- package/dist/core/agent-session.d.ts +3 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +7 -0
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/cache-stats.d.ts +15 -0
- package/dist/core/cache-stats.d.ts.map +1 -1
- package/dist/core/cache-stats.js +40 -2
- package/dist/core/cache-stats.js.map +1 -1
- package/dist/core/diagnostic-writer.d.ts.map +1 -1
- package/dist/core/diagnostic-writer.js +2 -1
- package/dist/core/diagnostic-writer.js.map +1 -1
- package/dist/core/export-html/template.js +14 -4
- package/dist/core/extensions/context-types.d.ts +6 -0
- package/dist/core/extensions/context-types.d.ts.map +1 -1
- package/dist/core/extensions/context-types.js.map +1 -1
- package/dist/core/extensions/loader-api.d.ts.map +1 -1
- package/dist/core/extensions/loader-api.js +5 -2
- package/dist/core/extensions/loader-api.js.map +1 -1
- package/dist/core/queued-message-delivery.d.ts +100 -7
- package/dist/core/queued-message-delivery.d.ts.map +1 -1
- package/dist/core/queued-message-delivery.js +194 -4
- package/dist/core/queued-message-delivery.js.map +1 -1
- package/dist/core/resume-cache-checkpoint.d.ts +32 -0
- package/dist/core/resume-cache-checkpoint.d.ts.map +1 -0
- package/dist/core/resume-cache-checkpoint.js +67 -0
- package/dist/core/resume-cache-checkpoint.js.map +1 -0
- package/dist/core/sdk-types.d.ts +37 -0
- package/dist/core/sdk-types.d.ts.map +1 -1
- package/dist/core/sdk-types.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +57 -28
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-manager-core.d.ts.map +1 -1
- package/dist/core/session-manager-core.js +12 -3
- package/dist/core/session-manager-core.js.map +1 -1
- package/dist/core/session-manager-entries.d.ts +13 -0
- package/dist/core/session-manager-entries.d.ts.map +1 -1
- package/dist/core/session-manager-entries.js +38 -6
- package/dist/core/session-manager-entries.js.map +1 -1
- package/dist/core/settings-lock-directory.d.ts.map +1 -1
- package/dist/core/settings-lock-directory.js +2 -1
- package/dist/core/settings-lock-directory.js.map +1 -1
- package/dist/core/storage/node-sqlite-file-gate.d.ts +173 -0
- package/dist/core/storage/node-sqlite-file-gate.d.ts.map +1 -0
- package/dist/core/storage/node-sqlite-file-gate.js +1033 -0
- package/dist/core/storage/node-sqlite-file-gate.js.map +1 -0
- package/dist/core/storage/node-sqlite-thread.d.ts +33 -6
- package/dist/core/storage/node-sqlite-thread.d.ts.map +1 -1
- package/dist/core/storage/node-sqlite-thread.js +72 -2
- package/dist/core/storage/node-sqlite-thread.js.map +1 -1
- package/dist/core/storage/node-sqlite.d.ts.map +1 -1
- package/dist/core/storage/node-sqlite.js +216 -15
- package/dist/core/storage/node-sqlite.js.map +1 -1
- package/dist/core/storage/session/entry-structure.d.ts.map +1 -1
- package/dist/core/storage/session/entry-structure.js +39 -2
- package/dist/core/storage/session/entry-structure.js.map +1 -1
- package/dist/core/storage/session/session-resume.d.ts.map +1 -1
- package/dist/core/storage/session/session-resume.js +1 -0
- package/dist/core/storage/session/session-resume.js.map +1 -1
- package/dist/core/storage/session/session-search-index.d.ts.map +1 -1
- package/dist/core/storage/session/session-search-index.js +56 -9
- package/dist/core/storage/session/session-search-index.js.map +1 -1
- package/dist/core/storage/statement-sequence.d.ts +36 -0
- package/dist/core/storage/statement-sequence.d.ts.map +1 -0
- package/dist/core/storage/statement-sequence.js +22 -0
- package/dist/core/storage/statement-sequence.js.map +1 -0
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +13 -4
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tasks/heartbeat-notice.d.ts.map +1 -1
- package/dist/core/tasks/heartbeat-notice.js +2 -1
- package/dist/core/tasks/heartbeat-notice.js.map +1 -1
- package/dist/core/tool-loadout.d.ts +4 -2
- package/dist/core/tool-loadout.d.ts.map +1 -1
- package/dist/core/tool-loadout.js +27 -5
- package/dist/core/tool-loadout.js.map +1 -1
- package/dist/core/tools/history-regex-worker.d.ts.map +1 -1
- package/dist/core/tools/history-regex-worker.js +2 -1
- package/dist/core/tools/history-regex-worker.js.map +1 -1
- package/dist/core/tools/powershell.d.ts +22 -22
- package/dist/core/tools/sqlite-selector-connection.d.ts.map +1 -1
- package/dist/core/tools/sqlite-selector-connection.js +7 -0
- package/dist/core/tools/sqlite-selector-connection.js.map +1 -1
- package/dist/core/transformed-system-prompt.d.ts +92 -0
- package/dist/core/transformed-system-prompt.d.ts.map +1 -0
- package/dist/core/transformed-system-prompt.js +240 -0
- package/dist/core/transformed-system-prompt.js.map +1 -0
- package/dist/extensions/codemode/execute.js +1 -1
- package/dist/extensions/codemode/execute.js.map +1 -1
- package/dist/extensions/codemode/tool.d.ts.map +1 -1
- package/dist/extensions/codemode/tool.js +16 -3
- package/dist/extensions/codemode/tool.js.map +1 -1
- package/dist/extensions/llama/ui.d.ts.map +1 -1
- package/dist/extensions/llama/ui.js +13 -8
- package/dist/extensions/llama/ui.js.map +1 -1
- package/dist/extensions/mcp/config.d.ts +2 -0
- package/dist/extensions/mcp/config.d.ts.map +1 -1
- package/dist/extensions/mcp/config.js +5 -0
- package/dist/extensions/mcp/config.js.map +1 -1
- package/dist/extensions/mcp/index.d.ts +4 -0
- package/dist/extensions/mcp/index.d.ts.map +1 -1
- package/dist/extensions/mcp/index.js +289 -64
- package/dist/extensions/mcp/index.js.map +1 -1
- package/dist/extensions/mcp/runtime.d.ts +1 -1
- package/dist/extensions/mcp/runtime.d.ts.map +1 -1
- package/dist/extensions/mcp/runtime.js +2 -2
- package/dist/extensions/mcp/runtime.js.map +1 -1
- package/dist/extensions/mcp/tool-records.d.ts +58 -0
- package/dist/extensions/mcp/tool-records.d.ts.map +1 -0
- package/dist/extensions/mcp/tool-records.js +129 -0
- package/dist/extensions/mcp/tool-records.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/modes/interactive/components/agent-panel.d.ts +2 -4
- package/dist/modes/interactive/components/agent-panel.d.ts.map +1 -1
- package/dist/modes/interactive/components/agent-panel.js +65 -80
- package/dist/modes/interactive/components/agent-panel.js.map +1 -1
- package/dist/modes/interactive/components/compaction-boundary-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/compaction-boundary-message.js +3 -3
- package/dist/modes/interactive/components/compaction-boundary-message.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +35 -28
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/notice-line.d.ts +16 -0
- package/dist/modes/interactive/components/notice-line.d.ts.map +1 -1
- package/dist/modes/interactive/components/notice-line.js +7 -0
- package/dist/modes/interactive/components/notice-line.js.map +1 -1
- package/dist/modes/interactive/components/prompt-slot.d.ts +1 -0
- package/dist/modes/interactive/components/prompt-slot.d.ts.map +1 -1
- package/dist/modes/interactive/components/prompt-slot.js +8 -4
- package/dist/modes/interactive/components/prompt-slot.js.map +1 -1
- package/dist/modes/interactive/components/task-board.d.ts +0 -1
- package/dist/modes/interactive/components/task-board.d.ts.map +1 -1
- package/dist/modes/interactive/components/task-board.js +6 -14
- package/dist/modes/interactive/components/task-board.js.map +1 -1
- package/dist/modes/interactive/components/task-row.d.ts.map +1 -1
- package/dist/modes/interactive/components/task-row.js +7 -6
- package/dist/modes/interactive/components/task-row.js.map +1 -1
- package/dist/modes/interactive/components/token-segment.d.ts +2 -1
- package/dist/modes/interactive/components/token-segment.d.ts.map +1 -1
- package/dist/modes/interactive/components/token-segment.js +2 -4
- package/dist/modes/interactive/components/token-segment.js.map +1 -1
- package/dist/modes/interactive/components/tree-selector-content.d.ts.map +1 -1
- package/dist/modes/interactive/components/tree-selector-content.js +2 -2
- package/dist/modes/interactive/components/tree-selector-content.js.map +1 -1
- package/dist/modes/interactive/components/working-run-meter.d.ts +0 -1
- package/dist/modes/interactive/components/working-run-meter.d.ts.map +1 -1
- package/dist/modes/interactive/components/working-run-meter.js +0 -9
- package/dist/modes/interactive/components/working-run-meter.js.map +1 -1
- package/dist/modes/interactive/extension-command-hold.d.ts +25 -0
- package/dist/modes/interactive/extension-command-hold.d.ts.map +1 -0
- package/dist/modes/interactive/extension-command-hold.js +45 -0
- package/dist/modes/interactive/extension-command-hold.js.map +1 -0
- package/dist/modes/interactive/interactive-agent-events.js +2 -1
- package/dist/modes/interactive/interactive-agent-events.js.map +1 -1
- package/dist/modes/interactive/interactive-extension-context.js +18 -10
- package/dist/modes/interactive/interactive-extension-context.js.map +1 -1
- package/dist/modes/interactive/interactive-extension-custom-ui.js +3 -0
- package/dist/modes/interactive/interactive-extension-custom-ui.js.map +1 -1
- package/dist/modes/interactive/interactive-input-handling.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-input-handling.js +54 -13
- package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
- package/dist/modes/interactive/interactive-model-routing.d.ts +6 -0
- package/dist/modes/interactive/interactive-model-routing.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-model-routing.js +15 -9
- package/dist/modes/interactive/interactive-model-routing.js.map +1 -1
- package/dist/modes/interactive/interactive-prompt-turn.js +4 -0
- package/dist/modes/interactive/interactive-prompt-turn.js.map +1 -1
- package/dist/modes/interactive/interactive-queueing.d.ts +7 -0
- package/dist/modes/interactive/interactive-queueing.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-queueing.js +47 -1
- package/dist/modes/interactive/interactive-queueing.js.map +1 -1
- package/dist/modes/interactive/interactive-session-routing.js +6 -0
- package/dist/modes/interactive/interactive-session-routing.js.map +1 -1
- package/dist/modes/interactive/interactive-slash-commands.js +165 -65
- package/dist/modes/interactive/interactive-slash-commands.js.map +1 -1
- package/dist/modes/interactive/screen-hold.d.ts +3 -0
- package/dist/modes/interactive/screen-hold.d.ts.map +1 -1
- package/dist/modes/interactive/screen-hold.js +9 -1
- package/dist/modes/interactive/screen-hold.js.map +1 -1
- package/dist/modes/interactive-engine/engine-health.d.ts +11 -3
- package/dist/modes/interactive-engine/engine-health.d.ts.map +1 -1
- package/dist/modes/interactive-engine/engine-health.js +5 -4
- package/dist/modes/interactive-engine/engine-health.js.map +1 -1
- package/dist/modes/interactive-engine/engine-quit-intent.d.ts +7 -0
- package/dist/modes/interactive-engine/engine-quit-intent.d.ts.map +1 -1
- package/dist/modes/interactive-engine/engine-quit-intent.js +19 -0
- package/dist/modes/interactive-engine/engine-quit-intent.js.map +1 -1
- package/dist/modes/interactive-engine/isolated-runtime.d.ts +18 -0
- package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
- package/dist/modes/interactive-engine/isolated-runtime.js +56 -4
- package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
- package/dist/modes/interactive-engine/protocol.d.ts +7 -0
- package/dist/modes/interactive-engine/protocol.d.ts.map +1 -1
- package/dist/modes/interactive-engine/protocol.js +1 -0
- package/dist/modes/interactive-engine/protocol.js.map +1 -1
- package/dist/modes/rpc/agent-panel-bridge.d.ts.map +1 -1
- package/dist/modes/rpc/agent-panel-bridge.js +0 -13
- package/dist/modes/rpc/agent-panel-bridge.js.map +1 -1
- package/dist/modes/rpc/rpc-client-process.d.ts +14 -1
- package/dist/modes/rpc/rpc-client-process.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client-process.js +74 -10
- package/dist/modes/rpc/rpc-client-process.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts +27 -1
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +81 -5
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/modes/rpc/rpc-event-buffer.d.ts +2 -0
- package/dist/modes/rpc/rpc-event-buffer.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-event-buffer.js +9 -0
- package/dist/modes/rpc/rpc-event-buffer.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +16 -3
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-session-binding.d.ts +7 -1
- package/dist/modes/rpc/rpc-session-binding.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-session-binding.js +10 -2
- package/dist/modes/rpc/rpc-session-binding.js.map +1 -1
- package/dist/utils/image-resize.d.ts.map +1 -1
- package/dist/utils/image-resize.js +2 -1
- package/dist/utils/image-resize.js.map +1 -1
- package/dist/utils/interactive-engine-bootstrap.d.ts +2 -0
- package/dist/utils/interactive-engine-bootstrap.d.ts.map +1 -1
- package/dist/utils/interactive-engine-bootstrap.js +1 -0
- package/dist/utils/interactive-engine-bootstrap.js.map +1 -1
- package/dist/utils/interactive-engine-env.d.ts +2 -0
- package/dist/utils/interactive-engine-env.d.ts.map +1 -1
- package/dist/utils/interactive-engine-env.js +1 -0
- package/dist/utils/interactive-engine-env.js.map +1 -1
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +2 -0
- package/dist/utils/shell.js.map +1 -1
- package/dist/utils/token-count.d.ts +8 -0
- package/dist/utils/token-count.d.ts.map +1 -0
- package/dist/utils/token-count.js +25 -0
- package/dist/utils/token-count.js.map +1 -0
- package/dist/utils/worker-threads.d.ts +18 -0
- package/dist/utils/worker-threads.d.ts.map +1 -0
- package/dist/utils/worker-threads.js +28 -0
- package/dist/utils/worker-threads.js.map +1 -0
- package/docs/background-tasks.md +13 -12
- package/docs/compaction.md +2 -2
- package/docs/development.md +1 -1
- package/docs/extensions/api-reference.md +5 -3
- package/docs/extensions/events.md +2 -0
- package/docs/mcp-servers.md +1 -1
- package/docs/settings.md +2 -0
- package/docs/storage.md +3 -1
- package/docs/subagents.md +6 -2
- package/docs/usage.md +1 -1
- package/npm-shrinkwrap.json +49 -49
- package/package.json +6 -6
|
@@ -0,0 +1,1033 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
/**
|
|
4
|
+
* What the process's connections to one file are doing with its write lock, in one `Int32` they all share: `FREE`, a
|
|
5
|
+
* statement of the calling thread running (`CALLER`), or a connection on a thread of its own taking it (`tag * 4 + 2`)
|
|
6
|
+
* or holding it (`tag * 4 + 3`), by its `tag`. That thread moves it with compare-and-exchange as SQLite takes and lets
|
|
7
|
+
* go of the lock: it takes the word before `BEGIN IMMEDIATE`, and gives it back once its transaction ended, before it
|
|
8
|
+
* answers. A statement of the calling thread runs only while it has the word itself (`runAdmitted`), so neither can
|
|
9
|
+
* take the lock from under the other.
|
|
10
|
+
*/
|
|
11
|
+
const FREE = 0;
|
|
12
|
+
const CALLER = 1;
|
|
13
|
+
/** A waiter for a call on `connection` that is decided at its turn: no deadline until then. */
|
|
14
|
+
function undecidedWaiter(connection) {
|
|
15
|
+
return {
|
|
16
|
+
deadline: Number.POSITIVE_INFINITY,
|
|
17
|
+
timer: undefined,
|
|
18
|
+
connection,
|
|
19
|
+
tryRun: () => false,
|
|
20
|
+
fail: () => { },
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
/** Tags stay below this, so a mark (`tag * 4 + 3`) is a positive `Int32`. */
|
|
24
|
+
const TAG_LIMIT = 2 ** 28;
|
|
25
|
+
// Shared across module copies, as the transaction gates are: a copy that runs a transaction's callback and a copy whose
|
|
26
|
+
// wrapped connection is called from it must see the same holds, words and asynchronous context.
|
|
27
|
+
const REGISTRY = Symbol.for("atomic-storage/node-sqlite-file-holds@1");
|
|
28
|
+
const registryBag = globalThis;
|
|
29
|
+
const registry = registryBag[REGISTRY] ?? {
|
|
30
|
+
files: new Map(),
|
|
31
|
+
words: new Map(),
|
|
32
|
+
scopes: new AsyncLocalStorage(),
|
|
33
|
+
wrapped: new Map(),
|
|
34
|
+
collected: new FinalizationRegistry((use) => use.release()),
|
|
35
|
+
untried: new WeakSet(),
|
|
36
|
+
};
|
|
37
|
+
registryBag[REGISTRY] = registry;
|
|
38
|
+
/** A threaded connection to `file` starts using the file's word (see `FREE`). */
|
|
39
|
+
export function useFileLock(file) {
|
|
40
|
+
let word = registry.words.get(file);
|
|
41
|
+
if (word === undefined) {
|
|
42
|
+
word = {
|
|
43
|
+
state: new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)),
|
|
44
|
+
tags: new Set(),
|
|
45
|
+
lastTag: 0,
|
|
46
|
+
};
|
|
47
|
+
registry.words.set(file, word);
|
|
48
|
+
}
|
|
49
|
+
// The next tag no connection to the file uses, from 1 up, wrapping before the marks would leave the Int32 range.
|
|
50
|
+
let tag = word.lastTag;
|
|
51
|
+
do
|
|
52
|
+
tag = (tag % (TAG_LIMIT - 1)) + 1;
|
|
53
|
+
while (word.tags.has(tag));
|
|
54
|
+
word.lastTag = tag;
|
|
55
|
+
word.tags.add(tag);
|
|
56
|
+
const { state, tags } = word;
|
|
57
|
+
let released = false;
|
|
58
|
+
return {
|
|
59
|
+
buffer: state.buffer,
|
|
60
|
+
tag,
|
|
61
|
+
clear: () => {
|
|
62
|
+
if (Atomics.compareExchange(state, 0, tag * 4 + 3, FREE) === tag * 4 + 3 ||
|
|
63
|
+
Atomics.compareExchange(state, 0, tag * 4 + 2, FREE) === tag * 4 + 2)
|
|
64
|
+
Atomics.notify(state, 0);
|
|
65
|
+
},
|
|
66
|
+
release: () => {
|
|
67
|
+
if (released)
|
|
68
|
+
return;
|
|
69
|
+
released = true;
|
|
70
|
+
tags.delete(tag);
|
|
71
|
+
if (tags.size === 0 && registry.words.get(file)?.tags === tags)
|
|
72
|
+
registry.words.delete(file);
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Runs `call`, a statement of the calling thread, if the file's word is free, holding the word while it runs, which is
|
|
78
|
+
* synchronous; undefined, running nothing, if a threaded connection takes or holds the lock.
|
|
79
|
+
*/
|
|
80
|
+
function runAdmitted(state, call) {
|
|
81
|
+
if (Atomics.compareExchange(state, 0, FREE, CALLER) !== FREE)
|
|
82
|
+
return undefined;
|
|
83
|
+
try {
|
|
84
|
+
return call();
|
|
85
|
+
}
|
|
86
|
+
finally {
|
|
87
|
+
Atomics.store(state, 0, FREE);
|
|
88
|
+
Atomics.notify(state, 0);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* A wrapped connection, `owner`, to `file` counts as open until `release` or until `owner` is collected, whichever
|
|
93
|
+
* comes first; see `FileHold`.
|
|
94
|
+
*/
|
|
95
|
+
export function useWrappedFile(file, owner) {
|
|
96
|
+
registry.wrapped.set(file, (registry.wrapped.get(file) ?? 0) + 1);
|
|
97
|
+
let released = false;
|
|
98
|
+
const use = {
|
|
99
|
+
release: () => {
|
|
100
|
+
if (released)
|
|
101
|
+
return;
|
|
102
|
+
released = true;
|
|
103
|
+
const count = (registry.wrapped.get(file) ?? 1) - 1;
|
|
104
|
+
if (count > 0)
|
|
105
|
+
registry.wrapped.set(file, count);
|
|
106
|
+
else
|
|
107
|
+
registry.wrapped.delete(file);
|
|
108
|
+
leaveScopesIfUnused();
|
|
109
|
+
},
|
|
110
|
+
};
|
|
111
|
+
registry.collected.register(owner, use, use);
|
|
112
|
+
return {
|
|
113
|
+
release: () => {
|
|
114
|
+
registry.collected.unregister(use);
|
|
115
|
+
use.release();
|
|
116
|
+
},
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
/** Opens a hold on `file`, identified as `fileIdentity` identifies it, scoped if a wrapped connection to it is open. */
|
|
120
|
+
export function holdFile(file) {
|
|
121
|
+
let gate = registry.files.get(file);
|
|
122
|
+
if (gate === undefined) {
|
|
123
|
+
gate = {
|
|
124
|
+
holds: new Set(),
|
|
125
|
+
waiters: [],
|
|
126
|
+
plans: new WeakMap(),
|
|
127
|
+
watching: false,
|
|
128
|
+
paced: false,
|
|
129
|
+
pumping: false,
|
|
130
|
+
polling: false,
|
|
131
|
+
};
|
|
132
|
+
registry.files.set(file, gate);
|
|
133
|
+
}
|
|
134
|
+
const hold = { file, scoped: registry.wrapped.has(file), open: true };
|
|
135
|
+
gate.holds.add(hold);
|
|
136
|
+
return hold;
|
|
137
|
+
}
|
|
138
|
+
/** Whether a scoped hold of the gate's file is open. */
|
|
139
|
+
function scopedHoldOpen(gate) {
|
|
140
|
+
for (const hold of gate.holds)
|
|
141
|
+
if (hold.scoped)
|
|
142
|
+
return true;
|
|
143
|
+
return false;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Leaves the asynchronous context once no wrapped connection is open and no scoped hold is: nothing reads it then, and
|
|
147
|
+
* on Node 22 an entered context keeps promise hooks on for every later await. It is entered again when needed.
|
|
148
|
+
*/
|
|
149
|
+
function leaveScopesIfUnused() {
|
|
150
|
+
if (registry.wrapped.size > 0)
|
|
151
|
+
return;
|
|
152
|
+
for (const gate of registry.files.values())
|
|
153
|
+
if (scopedHoldOpen(gate))
|
|
154
|
+
return;
|
|
155
|
+
registry.scopes.disable();
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Closes `hold`, once. When it was the file's last, the oldest call waiting for the file runs now, if the word is free
|
|
159
|
+
* and no call ran in this turn; the others follow one per turn (see `runNextWaiter`).
|
|
160
|
+
*/
|
|
161
|
+
export function releaseHold(hold) {
|
|
162
|
+
if (hold === undefined || !hold.open)
|
|
163
|
+
return;
|
|
164
|
+
hold.open = false;
|
|
165
|
+
const gate = registry.files.get(hold.file);
|
|
166
|
+
if (gate === undefined)
|
|
167
|
+
return;
|
|
168
|
+
gate.holds.delete(hold);
|
|
169
|
+
if (!scopedHoldOpen(gate))
|
|
170
|
+
runNextWaiter(hold.file, gate);
|
|
171
|
+
forgetIfIdle(hold.file, gate);
|
|
172
|
+
if (hold.scoped)
|
|
173
|
+
leaveScopesIfUnused();
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Runs the oldest waiting call if the word is free and no call ran on the file in this turn of the event loop, and
|
|
177
|
+
* schedules the next one for the next turn: calls that queued up behind a long transaction run one per turn, so none
|
|
178
|
+
* of them holds the event loop for the time of all of them. A call that finds the word taken waits again, still under
|
|
179
|
+
* its own deadline.
|
|
180
|
+
*/
|
|
181
|
+
function runNextWaiter(file, gate) {
|
|
182
|
+
if (gate.paced || gate.waiters.length === 0)
|
|
183
|
+
return;
|
|
184
|
+
const waiter = gate.waiters[0];
|
|
185
|
+
if (!waiter.tryRun()) {
|
|
186
|
+
failOverdue(file, gate);
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
gate.waiters.shift();
|
|
190
|
+
clearTimeout(waiter.timer);
|
|
191
|
+
ranThisTurn(file, gate);
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* The oldest call could not run: calls waiting past their deadline fail now, having run nothing (or refused, see
|
|
195
|
+
* `runTryingFirst`); the others keep their place.
|
|
196
|
+
*/
|
|
197
|
+
function failOverdue(file, gate) {
|
|
198
|
+
const now = performance.now();
|
|
199
|
+
const overdue = gate.waiters.filter((waiting) => now >= waiting.deadline);
|
|
200
|
+
for (const waiter of overdue) {
|
|
201
|
+
gate.waiters.splice(gate.waiters.indexOf(waiter), 1);
|
|
202
|
+
clearTimeout(waiter.timer);
|
|
203
|
+
waiter.fail();
|
|
204
|
+
}
|
|
205
|
+
// The calls behind them get their turn.
|
|
206
|
+
if (overdue.length > 0)
|
|
207
|
+
ranThisTurn(file, gate);
|
|
208
|
+
}
|
|
209
|
+
/** Notes that a call ran on the file in this turn; the next waiting one gets the next turn. */
|
|
210
|
+
function ranThisTurn(file, gate) {
|
|
211
|
+
gate.paced = true;
|
|
212
|
+
if (gate.pumping)
|
|
213
|
+
return;
|
|
214
|
+
gate.pumping = true;
|
|
215
|
+
setImmediate(() => {
|
|
216
|
+
gate.pumping = false;
|
|
217
|
+
gate.paced = false;
|
|
218
|
+
const state = registry.words.get(file)?.state;
|
|
219
|
+
runNextWaiter(file, gate);
|
|
220
|
+
if (state !== undefined)
|
|
221
|
+
watchWord(file, gate, state);
|
|
222
|
+
forgetIfIdle(file, gate);
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
function forgetIfIdle(file, gate) {
|
|
226
|
+
if (gate.holds.size === 0 &&
|
|
227
|
+
gate.waiters.length === 0 &&
|
|
228
|
+
!gate.pumping &&
|
|
229
|
+
!gate.polling &&
|
|
230
|
+
registry.files.get(file) === gate)
|
|
231
|
+
registry.files.delete(file);
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Runs a transaction's callback inside the transaction callbacks it was requested in (`scope`, captured when it was
|
|
235
|
+
* requested, since a group commit runs it from another's request) and inside its own hold, so calls it makes can be
|
|
236
|
+
* told apart.
|
|
237
|
+
*/
|
|
238
|
+
export function runInHold(hold, scope, callback) {
|
|
239
|
+
const store = hold?.scoped === true ? { hold, outer: scope } : scope;
|
|
240
|
+
// Nothing to change, as always for a process that wraps no connection to a file: no context is entered.
|
|
241
|
+
if (store === registry.scopes.getStore())
|
|
242
|
+
return callback();
|
|
243
|
+
return registry.scopes.run(store, callback);
|
|
244
|
+
}
|
|
245
|
+
/** The holds whose callbacks the caller runs in; captured when a call is made, not when it runs. */
|
|
246
|
+
export function currentHoldScope() {
|
|
247
|
+
return registry.scopes.getStore();
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Whether a call made now on a wrapped connection to `file` comes in behind a transaction: a scoped hold is open or
|
|
251
|
+
* calls wait for their turn. Read when the call is made; one made once that is over runs as it always has, however
|
|
252
|
+
* busy the file was before.
|
|
253
|
+
*/
|
|
254
|
+
export function inBacklog(file) {
|
|
255
|
+
const gate = registry.files.get(file);
|
|
256
|
+
return gate !== undefined && (scopedHoldOpen(gate) || gate.waiters.length > 0);
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* The gate of `file` when another context holds it open: some hold is open, and none of the callbacks `scope` runs in
|
|
260
|
+
* belongs to an open hold of it. A call made inside an open hold's own callback cannot wait for it, since the
|
|
261
|
+
* transaction waits for the call: it runs at once, as it always has. A call made in the backlog of a transaction
|
|
262
|
+
* (`backlog`, see `inBacklog`) also takes its turn behind the calls queued before it, one per turn.
|
|
263
|
+
*/
|
|
264
|
+
export function heldElsewhere(file, scope, backlog) {
|
|
265
|
+
const gate = registry.files.get(file);
|
|
266
|
+
if (gate === undefined || (!scopedHoldOpen(gate) && gate.waiters.length === 0 && !(gate.paced && backlog)))
|
|
267
|
+
return undefined;
|
|
268
|
+
for (let inner = scope; inner !== undefined; inner = inner.outer) {
|
|
269
|
+
if (inner.hold.open && inner.hold.file === file)
|
|
270
|
+
return undefined;
|
|
271
|
+
}
|
|
272
|
+
return gate;
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Runs `run` as soon as the file's word is free: at once if it is, as SQLite's busy handler would find the lock free;
|
|
276
|
+
* otherwise once a threaded connection gives the word back, or the file's last hold closes. Fails it with `busy()`,
|
|
277
|
+
* having run nothing, if the word is still taken at the end of the busy timeout of `database`, which `owner` owns
|
|
278
|
+
* (read only when the call has to wait). When that cannot be read, `run` runs at once, as it always has.
|
|
279
|
+
*/
|
|
280
|
+
export function runWhenFree(file, gate, owner, database, run, busy) {
|
|
281
|
+
const state = registry.words.get(file)?.state;
|
|
282
|
+
if (state === undefined)
|
|
283
|
+
return run();
|
|
284
|
+
// Calls already waiting go first, and one runs per turn.
|
|
285
|
+
runNextWaiter(file, gate);
|
|
286
|
+
const now = gate.waiters.length === 0 && !gate.paced ? runAdmitted(state, run) : undefined;
|
|
287
|
+
if (now !== undefined) {
|
|
288
|
+
ranThisTurn(file, gate);
|
|
289
|
+
return now;
|
|
290
|
+
}
|
|
291
|
+
const timeoutMs = busyTimeoutOf(gate, owner, database);
|
|
292
|
+
if (timeoutMs === undefined)
|
|
293
|
+
return run();
|
|
294
|
+
return new Promise((resolve, reject) => {
|
|
295
|
+
const waiter = undecidedWaiter(database);
|
|
296
|
+
gate.waiters.push(waiter);
|
|
297
|
+
armWhenFree(file, gate, waiter, state, timeoutMs, run, resolve, reject, busy);
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
/** Makes `waiter` run `run` once the word is free, for `runWhenFree`. */
|
|
301
|
+
function armWhenFree(file, gate, waiter, state, timeoutMs, run, resolve, reject, busy) {
|
|
302
|
+
waiter.deadline = performance.now() + timeoutMs;
|
|
303
|
+
// Decided once the event loop handled what it already received, such as the exit of a connection's thread, which
|
|
304
|
+
// a timer runs ahead of. At its deadline it fails if the word is taken. While the word is free it keeps its place:
|
|
305
|
+
// a free lock is never reported busy, and its turn comes (see `runNextWaiter`), so its busy timeout bounds how long
|
|
306
|
+
// it waits for the lock, not for its turn.
|
|
307
|
+
waiter.timer = setTimeout(() => setImmediate(() => {
|
|
308
|
+
const index = gate.waiters.indexOf(waiter);
|
|
309
|
+
if (index === -1 || Atomics.load(state, 0) === FREE)
|
|
310
|
+
return;
|
|
311
|
+
gate.waiters.splice(index, 1);
|
|
312
|
+
waiter.fail();
|
|
313
|
+
ranThisTurn(file, gate);
|
|
314
|
+
forgetIfIdle(file, gate);
|
|
315
|
+
}), timeoutMs);
|
|
316
|
+
waiter.tryRun = () => {
|
|
317
|
+
const ran = runAdmitted(state, run);
|
|
318
|
+
if (ran === undefined)
|
|
319
|
+
return false;
|
|
320
|
+
resolve(ran);
|
|
321
|
+
return true;
|
|
322
|
+
};
|
|
323
|
+
waiter.fail = () => reject(busy());
|
|
324
|
+
watchWord(file, gate, state);
|
|
325
|
+
}
|
|
326
|
+
/**
|
|
327
|
+
* Wakes the gate's waiting calls whenever the file's word changes, so a call runs the moment a threaded connection
|
|
328
|
+
* gives the lock back, before its answer reaches this thread. One watch per gate, for as long as calls wait.
|
|
329
|
+
*/
|
|
330
|
+
function watchWord(file, gate, state) {
|
|
331
|
+
for (;;) {
|
|
332
|
+
if (gate.watching || gate.waiters.length === 0)
|
|
333
|
+
return;
|
|
334
|
+
const observed = Atomics.load(state, 0);
|
|
335
|
+
// Freed since the caller found it taken: run what waits now rather than wait for a change that already came.
|
|
336
|
+
if (observed === FREE) {
|
|
337
|
+
// Free: the oldest runs now or at the next turn (see `runNextWaiter`); nothing to watch for until then.
|
|
338
|
+
runNextWaiter(file, gate);
|
|
339
|
+
forgetIfIdle(file, gate);
|
|
340
|
+
// Ran, or was refused a lock the word does not announce (another process's), which `pollWaiters` tries again.
|
|
341
|
+
if (gate.paced || Atomics.load(state, 0) === FREE)
|
|
342
|
+
return;
|
|
343
|
+
continue;
|
|
344
|
+
}
|
|
345
|
+
// Until the last deadline: each waiter's own timer decides at its deadline, so a watch never runs past it.
|
|
346
|
+
// Calls not decided yet (see `runDeferred`) need no watch: they are decided in their turn, whatever the word.
|
|
347
|
+
const deadlines = gate.waiters.map((waiter) => waiter.deadline).filter(Number.isFinite);
|
|
348
|
+
const untilMs = Math.max(...deadlines) - performance.now();
|
|
349
|
+
if (deadlines.length === 0 || untilMs <= 0)
|
|
350
|
+
return;
|
|
351
|
+
const result = Atomics.waitAsync(state, 0, observed, untilMs);
|
|
352
|
+
if (!result.async) {
|
|
353
|
+
if (result.value === "not-equal")
|
|
354
|
+
continue;
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
gate.watching = true;
|
|
358
|
+
void result.value.then(() => {
|
|
359
|
+
gate.watching = false;
|
|
360
|
+
runNextWaiter(file, gate);
|
|
361
|
+
forgetIfIdle(file, gate);
|
|
362
|
+
watchWord(file, gate, state);
|
|
363
|
+
});
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
/** Most plans one connection keeps while a file is held. */
|
|
368
|
+
const MAX_PLANS = 32;
|
|
369
|
+
function plansOf(gate, owner) {
|
|
370
|
+
let plans = gate.plans.get(owner);
|
|
371
|
+
if (plans === undefined) {
|
|
372
|
+
plans = { explained: new Map() };
|
|
373
|
+
gate.plans.set(owner, plans);
|
|
374
|
+
}
|
|
375
|
+
return plans;
|
|
376
|
+
}
|
|
377
|
+
/** Drops what the connection of `owner` prepared while `file` was held, as it closes. */
|
|
378
|
+
export function forgetPlans(file, owner) {
|
|
379
|
+
registry.files.get(file)?.plans.delete(owner);
|
|
380
|
+
}
|
|
381
|
+
/** The busy timeout `database` waits for a lock now, in milliseconds; undefined when it cannot be read. */
|
|
382
|
+
function busyTimeoutOf(gate, owner, database) {
|
|
383
|
+
const plans = plansOf(gate, owner);
|
|
384
|
+
try {
|
|
385
|
+
plans.busyTimeout ??= database.prepare("PRAGMA busy_timeout");
|
|
386
|
+
const timeout = Number(plans.busyTimeout.get()?.timeout);
|
|
387
|
+
return Number.isFinite(timeout) && timeout >= 0 ? timeout : undefined;
|
|
388
|
+
}
|
|
389
|
+
catch {
|
|
390
|
+
return undefined;
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
/** A blank or a comment, which SQLite skips between words. */
|
|
394
|
+
const GAP = String.raw `(?:\s|--[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/)`;
|
|
395
|
+
/** What SQLite skips before a statement's first word: blanks, comments and empty statements. */
|
|
396
|
+
const LEADING = new RegExp(`^(?:${GAP}|;)*`);
|
|
397
|
+
/**
|
|
398
|
+
* A PRAGMA, alone or under EXPLAIN or EXPLAIN QUERY PLAN (on text without what `LEADING` matches): SQLite may carry it
|
|
399
|
+
* out while it prepares it, so it is never prepared ahead.
|
|
400
|
+
*/
|
|
401
|
+
const PRAGMA_STATEMENT = new RegExp(`^(?:EXPLAIN${GAP}+(?:QUERY${GAP}+PLAN${GAP}+)?)?PRAGMA\\b`, "i");
|
|
402
|
+
/** A name as SQLite reads it, bare or quoted, with its quotes. */
|
|
403
|
+
const NAME = String.raw `(?:\w+|"(?:[^"]|"")*"|'(?:[^']|'')*'|\[[^\]]*\]|` + "`(?:[^`]|``)*`)";
|
|
404
|
+
/**
|
|
405
|
+
* A PRAGMA's name, past an optional EXPLAIN or EXPLAIN QUERY PLAN, `PRAGMA` and an optional schema (`schema.`), on text
|
|
406
|
+
* without what `LEADING` matches.
|
|
407
|
+
*/
|
|
408
|
+
const PRAGMA_NAME = new RegExp(`^(EXPLAIN${GAP}+(?:QUERY${GAP}+PLAN${GAP}+)?)?PRAGMA${GAP}+(?:(${NAME})${GAP}*\\.${GAP}*)?(${NAME})`, "i");
|
|
409
|
+
/** A name without its quotes, in lower case. */
|
|
410
|
+
function unquoted(name) {
|
|
411
|
+
const quote = name[0];
|
|
412
|
+
if (quote === '"' || quote === "'" || quote === "`")
|
|
413
|
+
return name.slice(1, -1).replaceAll(`${quote}${quote}`, quote).toLowerCase();
|
|
414
|
+
if (quote === "[")
|
|
415
|
+
return name.slice(1, -1).toLowerCase();
|
|
416
|
+
return name.toLowerCase();
|
|
417
|
+
}
|
|
418
|
+
/**
|
|
419
|
+
* PRAGMAs that write the file and are tried first: SQLite refuses each in its opening steps, before it changed
|
|
420
|
+
* anything. Every other PRAGMA runs as it always has: one that reads or sets a setting of the connection or another
|
|
421
|
+
* database needs no lock of the file in WAL mode, and runs at once anyway; and ones a try would change are among them:
|
|
422
|
+
* those of the busy timeout, which the try sets, also under EXPLAIN, since SQLite sets it while it prepares the
|
|
423
|
+
* statement; setters that change something before they meet the lock (`journal_mode`, `default_cache_size`,
|
|
424
|
+
* `auto_vacuum`, and the ones that apply to every attached database when no schema is named); checks that run the
|
|
425
|
+
* application's functions in the schema's constraints (`integrity_check`, `quick_check`); and ones that answer
|
|
426
|
+
* differently when refused the lock at once (a checkpoint that waits, `optimize`).
|
|
427
|
+
*/
|
|
428
|
+
const TRIED_PRAGMAS = new Set(["user_version", "application_id", "schema_version", "incremental_vacuum"]);
|
|
429
|
+
/** Whether a PRAGMA (on text without what `LEADING` matches) is tried first; see `TRIED_PRAGMAS`. */
|
|
430
|
+
function pragmaTriedFirst(statement) {
|
|
431
|
+
const match = PRAGMA_NAME.exec(statement);
|
|
432
|
+
if (match === null)
|
|
433
|
+
return false;
|
|
434
|
+
const [, explain, schema, name = ""] = match;
|
|
435
|
+
return (explain === undefined &&
|
|
436
|
+
(schema === undefined || unquoted(schema) === "main") &&
|
|
437
|
+
TRIED_PRAGMAS.has(unquoted(name)));
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* Built-in functions a try cannot run safely: ones that read the connection's change counters, which a refused try
|
|
441
|
+
* changes; `load_extension`, which runs an extension's code; and `sqlite_attach` (ATTACH), which reads another file
|
|
442
|
+
* with its own locks.
|
|
443
|
+
*/
|
|
444
|
+
const UNSAFE_FUNCTIONS = new Set(["changes", "total_changes", "last_insert_rowid", "load_extension", "sqlite_attach"]);
|
|
445
|
+
/** Steps of a plan that call a function or an aggregate, named in their P4 as `name(arguments)`. */
|
|
446
|
+
const FUNCTION_STEPS = new Set([
|
|
447
|
+
"Function",
|
|
448
|
+
"Function0",
|
|
449
|
+
"PureFunc",
|
|
450
|
+
"PureFunc0",
|
|
451
|
+
"AggStep",
|
|
452
|
+
"AggStep0",
|
|
453
|
+
"AggStep1",
|
|
454
|
+
"AggFinal",
|
|
455
|
+
"AggValue",
|
|
456
|
+
"AggInverse",
|
|
457
|
+
]);
|
|
458
|
+
/** The collating sequences SQLite builds in; `B` is how a plan's key lists `BINARY`. */
|
|
459
|
+
const BUILT_IN_COLLATIONS = new Set(["", "B", "BINARY", "NOCASE", "RTRIM"]);
|
|
460
|
+
/** Steps of a plan that compare with a collating sequence named in their P4 as `name-encoding`. */
|
|
461
|
+
const COLLATING_STEPS = new Set(["CollSeq", "Eq", "Ne", "Lt", "Le", "Gt", "Ge"]);
|
|
462
|
+
const COLLATION = /^(.*)-(?:8|16le|16be|16)$/;
|
|
463
|
+
/** A plan's key, `k(fields,collation,…)`, each collation after its `-` (descending) and `N.` (nulls last) marks. */
|
|
464
|
+
const KEY = /^k\(\d+((?:,[^,)]*)*)\)$/;
|
|
465
|
+
/** Whether a step of a plan compares with a collating sequence SQLite does not build in, an extension's code. */
|
|
466
|
+
function usesOtherCollation(opcode, p4) {
|
|
467
|
+
const key = KEY.exec(p4);
|
|
468
|
+
if (key !== null)
|
|
469
|
+
return key[1]
|
|
470
|
+
.split(",")
|
|
471
|
+
.slice(1)
|
|
472
|
+
.some((field) => !BUILT_IN_COLLATIONS.has(field.replace(/^-?(?:N\.)?/, "")));
|
|
473
|
+
if (!COLLATING_STEPS.has(opcode))
|
|
474
|
+
return false;
|
|
475
|
+
const name = COLLATION.exec(p4)?.[1];
|
|
476
|
+
return name !== undefined && !BUILT_IN_COLLATIONS.has(name);
|
|
477
|
+
}
|
|
478
|
+
/** A VACUUM, which may create the file it writes into before it is refused. */
|
|
479
|
+
const VACUUM_STATEMENT = /^VACUUM\b/i;
|
|
480
|
+
/** `UNSAFE_FUNCTIONS` but `sqlite_attach`, whose statement, ATTACH, names it otherwise. */
|
|
481
|
+
const UNSAFE_NAMES = ["changes", "total_changes", "last_insert_rowid", "load_extension"];
|
|
482
|
+
/** An INSERT, UPDATE or DELETE, possibly after a WITH clause: listing its plan resets `changes()`. */
|
|
483
|
+
const CHANGING_STATEMENT = /^(?:INSERT|REPLACE|UPDATE|DELETE|WITH)\b/i;
|
|
484
|
+
/**
|
|
485
|
+
* A string literal or a comment, which names nothing; or a name, bare (SQLite reads any character past ASCII as part of
|
|
486
|
+
* one) or quoted.
|
|
487
|
+
*/
|
|
488
|
+
const WORD = /'(?:[^']|'')*'|--[^\n]*|\/\*[\s\S]*?(?:\*\/|$)|"((?:[^"]|"")*)"|\[([^\]]*)\]|`((?:[^`]|``)*)`|([A-Za-z_\u0080-\u{10FFFF}][\w$\u0080-\u{10FFFF}]*)/gu;
|
|
489
|
+
/** The names `sql` uses, bare or quoted, in lower case: outside its string literals and comments. */
|
|
490
|
+
function namesIn(sql) {
|
|
491
|
+
const names = new Set();
|
|
492
|
+
for (const [, double, bracket, backtick, bare] of sql.matchAll(WORD)) {
|
|
493
|
+
const name = double?.replaceAll('""', '"') ?? bracket ?? backtick?.replaceAll("``", "`") ?? bare;
|
|
494
|
+
if (name !== undefined)
|
|
495
|
+
names.add(name.toLowerCase());
|
|
496
|
+
}
|
|
497
|
+
return names;
|
|
498
|
+
}
|
|
499
|
+
/**
|
|
500
|
+
* Whether `statement` names a function whose result a listing of its plan could change, which resets `changes()`
|
|
501
|
+
* for an INSERT, UPDATE or DELETE: one of `UNSAFE_NAMES`, or, for such a statement, a function SQLite does not build
|
|
502
|
+
* in, which could read the counters itself. When the connection cannot list its functions, every INSERT, UPDATE or
|
|
503
|
+
* DELETE counts.
|
|
504
|
+
*/
|
|
505
|
+
function namesUnsafeFunction(statement, database) {
|
|
506
|
+
const names = namesIn(statement);
|
|
507
|
+
if (UNSAFE_NAMES.some((name) => names.has(name)))
|
|
508
|
+
return true;
|
|
509
|
+
if (!CHANGING_STATEMENT.test(statement))
|
|
510
|
+
return false;
|
|
511
|
+
const userFunctions = functionsNotBuiltIn(database);
|
|
512
|
+
if (userFunctions === undefined)
|
|
513
|
+
return true;
|
|
514
|
+
for (const name of userFunctions)
|
|
515
|
+
if (names.has(name))
|
|
516
|
+
return true;
|
|
517
|
+
return false;
|
|
518
|
+
}
|
|
519
|
+
/** The database numbers of a connection's main database, the file itself, and of its temporary database. */
|
|
520
|
+
const MAIN_DATABASE = 0;
|
|
521
|
+
const TEMP_DATABASE = 1;
|
|
522
|
+
/**
|
|
523
|
+
* How a wrapped call runs while a threaded transaction of this thread holds its file:
|
|
524
|
+
*
|
|
525
|
+
* - `try first`: once at once with a busy timeout of 0 (see `runTryingFirst`), refused the lock, tried again. Only a
|
|
526
|
+
* statement whose plan proves that a refusal comes from its opening steps, before it did anything: the only
|
|
527
|
+
* databases it writes are the file and the temporary one, and the file is in WAL mode, where a commit needs no
|
|
528
|
+
* further lock; it calls no code but SQLite's own (no function or collating sequence SQLite does not build in, no
|
|
529
|
+
* virtual table, no `UNSAFE_FUNCTIONS`); it is no VACUUM, which may create the file it writes into before it is
|
|
530
|
+
* refused. A PRAGMA, which is never prepared ahead since SQLite may carry one out while preparing it, is tried first
|
|
531
|
+
* only if it is one of `TRIED_PRAGMAS`.
|
|
532
|
+
* - `as before`: every other single statement, an `exec` of no statement, and every call while the connection is
|
|
533
|
+
* inside a transaction of its own or the file is not in WAL mode. It runs exactly as it always has, with the
|
|
534
|
+
* connection's own busy timeout.
|
|
535
|
+
* - `script`: an `exec` of more than one statement (see `splitStatements`). It waits until no transaction of this
|
|
536
|
+
* thread holds the lock (see `runWhenFree`), so no part of it runs while the lock is held. An `exec` of exactly one
|
|
537
|
+
* statement runs as that statement.
|
|
538
|
+
*
|
|
539
|
+
* At a busy timeout of 0 every single statement runs as before: it never waits for the lock, and setting the timeout,
|
|
540
|
+
* as a try does, would remove a busy handler an extension installed, which reads as a timeout of 0. A script still
|
|
541
|
+
* waits (for no time), which sets no timeout.
|
|
542
|
+
*
|
|
543
|
+
* The plan of a statement is made once while the file is held and listed again for later calls. Listing the plan of
|
|
544
|
+
* an INSERT, UPDATE or DELETE resets the connection's `changes()`, which the statement's own run sets again; so a
|
|
545
|
+
* statement that names a function that reads the change counters or may (see `namesUnsafeFunction`) runs as before
|
|
546
|
+
* without its plan being listed.
|
|
547
|
+
*/
|
|
548
|
+
export function modeOf(gate, owner, database, sql, params, single) {
|
|
549
|
+
if (!single) {
|
|
550
|
+
const statements = splitStatements(sql);
|
|
551
|
+
if (statements.length > 1)
|
|
552
|
+
return "script";
|
|
553
|
+
// Nothing to run, nor to wait for.
|
|
554
|
+
if (statements.length === 0)
|
|
555
|
+
return "as before";
|
|
556
|
+
return modeOf(gate, owner, database, statements[0], params, true);
|
|
557
|
+
}
|
|
558
|
+
if (busyTimeoutOf(gate, owner, database) === 0)
|
|
559
|
+
return "as before";
|
|
560
|
+
// Inside a transaction of its own, a write's upgrade of the connection's read is refused at once, with no busy
|
|
561
|
+
// handler, and a try again could succeed or be refused otherwise.
|
|
562
|
+
if (database.isTransaction !== false ||
|
|
563
|
+
!inWriteAheadLog(gate, owner, database) ||
|
|
564
|
+
!triesAllowed(gate, owner, database))
|
|
565
|
+
return "as before";
|
|
566
|
+
// Decided on the text SQLite reads, past the blanks, comments and empty statements it skips.
|
|
567
|
+
const statement = sql.replace(LEADING, "");
|
|
568
|
+
if (PRAGMA_STATEMENT.test(statement))
|
|
569
|
+
return pragmaTriedFirst(statement) ? "try first" : "as before";
|
|
570
|
+
// Decided without its plan: listing the plan of an INSERT, UPDATE or DELETE resets the connection's changes().
|
|
571
|
+
if (VACUUM_STATEMENT.test(statement) || namesUnsafeFunction(statement, database))
|
|
572
|
+
return "as before";
|
|
573
|
+
const steps = planSteps(gate, owner, database, statement, params);
|
|
574
|
+
return steps !== undefined && triesSafely(steps, database) ? "try first" : "as before";
|
|
575
|
+
}
|
|
576
|
+
/**
|
|
577
|
+
* Whether calls on `database`, which `owner` owns, may be tried first: it never refused its busy timeout back after a
|
|
578
|
+
* try, and, checked once while the file is held, before anything is tried, the timeout can be read and set to the
|
|
579
|
+
* value it has. An authorizer you set can refuse either; then every call runs as before, and the timeout is never set.
|
|
580
|
+
*/
|
|
581
|
+
function triesAllowed(gate, owner, database) {
|
|
582
|
+
if (registry.untried.has(database))
|
|
583
|
+
return false;
|
|
584
|
+
const plans = plansOf(gate, owner);
|
|
585
|
+
if (plans.timeoutSettable === undefined) {
|
|
586
|
+
const timeoutMs = busyTimeoutOf(gate, owner, database);
|
|
587
|
+
try {
|
|
588
|
+
if (timeoutMs !== undefined)
|
|
589
|
+
setBusyTimeout(database, timeoutMs);
|
|
590
|
+
plans.timeoutSettable = timeoutMs !== undefined;
|
|
591
|
+
}
|
|
592
|
+
catch {
|
|
593
|
+
plans.timeoutSettable = false;
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
return plans.timeoutSettable;
|
|
597
|
+
}
|
|
598
|
+
/**
|
|
599
|
+
* Whether the file of `database`, which `owner` owns, is in WAL mode, read once while the file is held. A connection
|
|
600
|
+
* of this process on a thread of its own is open on the file, so it stays in WAL mode meanwhile.
|
|
601
|
+
*/
|
|
602
|
+
function inWriteAheadLog(gate, owner, database) {
|
|
603
|
+
const plans = plansOf(gate, owner);
|
|
604
|
+
if (plans.writeAheadLog === undefined) {
|
|
605
|
+
try {
|
|
606
|
+
plans.writeAheadLog = String(database.prepare("PRAGMA main.journal_mode").get()?.journal_mode) === "wal";
|
|
607
|
+
}
|
|
608
|
+
catch {
|
|
609
|
+
plans.writeAheadLog = false;
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
return plans.writeAheadLog;
|
|
613
|
+
}
|
|
614
|
+
/**
|
|
615
|
+
* Whether a plan, with the programs of the triggers it fires, can be refused the lock only in its opening steps, before
|
|
616
|
+
* it did anything (see `modeOf`). When the connection cannot list its functions, every function counts as one SQLite
|
|
617
|
+
* does not build in.
|
|
618
|
+
*/
|
|
619
|
+
function triesSafely(steps, database) {
|
|
620
|
+
let userFunctions = null;
|
|
621
|
+
for (const step of steps) {
|
|
622
|
+
const opcode = String(step.opcode);
|
|
623
|
+
if (opcode === "Transaction") {
|
|
624
|
+
const written = Number(step.p1);
|
|
625
|
+
if (Number(step.p2) !== 0 && written !== MAIN_DATABASE && written !== TEMP_DATABASE)
|
|
626
|
+
return false;
|
|
627
|
+
continue;
|
|
628
|
+
}
|
|
629
|
+
if (opcode === "Vacuum" || /^V[A-Z]/.test(opcode))
|
|
630
|
+
return false;
|
|
631
|
+
if (typeof step.p4 === "string" && usesOtherCollation(opcode, step.p4))
|
|
632
|
+
return false;
|
|
633
|
+
if (!FUNCTION_STEPS.has(opcode))
|
|
634
|
+
continue;
|
|
635
|
+
const name = /^([^(]+)\(/.exec(String(step.p4 ?? ""))?.[1]?.toLowerCase();
|
|
636
|
+
if (name === undefined || UNSAFE_FUNCTIONS.has(name))
|
|
637
|
+
return false;
|
|
638
|
+
if (userFunctions === null)
|
|
639
|
+
userFunctions = functionsNotBuiltIn(database);
|
|
640
|
+
if (userFunctions === undefined || userFunctions.has(name))
|
|
641
|
+
return false;
|
|
642
|
+
}
|
|
643
|
+
return true;
|
|
644
|
+
}
|
|
645
|
+
/** The names of the functions `database` has that SQLite does not build in; undefined when it cannot list them. */
|
|
646
|
+
function functionsNotBuiltIn(database) {
|
|
647
|
+
try {
|
|
648
|
+
const names = new Set();
|
|
649
|
+
let listed = 0;
|
|
650
|
+
for (const row of database.prepare("PRAGMA function_list").all()) {
|
|
651
|
+
listed++;
|
|
652
|
+
if (Number(row.builtin) === 0)
|
|
653
|
+
names.add(String(row.name).toLowerCase());
|
|
654
|
+
}
|
|
655
|
+
return listed === 0 ? undefined : names;
|
|
656
|
+
}
|
|
657
|
+
catch {
|
|
658
|
+
return undefined;
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
/** Whether `error` is SQLITE_BUSY itself (not one of its extended codes, such as SQLITE_BUSY_SNAPSHOT). */
|
|
662
|
+
function plainBusy(error) {
|
|
663
|
+
for (let cause = error; typeof cause === "object" && cause !== null;) {
|
|
664
|
+
const { errcode } = cause;
|
|
665
|
+
if (typeof errcode === "number")
|
|
666
|
+
return errcode === 5;
|
|
667
|
+
cause = cause.cause;
|
|
668
|
+
}
|
|
669
|
+
return false;
|
|
670
|
+
}
|
|
671
|
+
/**
|
|
672
|
+
* Runs `attempt`, a call that runs synchronously on `database`, once with a busy timeout of 0, then gives the
|
|
673
|
+
* connection back `timeoutMs`. Undefined, having run nothing, when the connection no longer tries calls first or does
|
|
674
|
+
* not take the busy timeout of 0, as read back (an authorizer you set can refuse or ignore it, though it allowed the
|
|
675
|
+
* value it had; see `triesAllowed`): the call is to run as before, and the connection is not tried first again. When
|
|
676
|
+
* the connection does not take the value back after the try, twice, the try's outcome is final, a refusal of the lock
|
|
677
|
+
* included, and the connection is never tried first again: its busy timeout can stay 0.
|
|
678
|
+
*/
|
|
679
|
+
function attemptOnce(database, timeoutMs, attempt) {
|
|
680
|
+
if (registry.untried.has(database))
|
|
681
|
+
return undefined;
|
|
682
|
+
let zero = false;
|
|
683
|
+
try {
|
|
684
|
+
setBusyTimeout(database, 0);
|
|
685
|
+
zero = readBusyTimeout(database) === 0;
|
|
686
|
+
}
|
|
687
|
+
catch {
|
|
688
|
+
// Refused: the timeout is unchanged.
|
|
689
|
+
}
|
|
690
|
+
if (!zero) {
|
|
691
|
+
registry.untried.add(database);
|
|
692
|
+
timeoutRestored(database, timeoutMs);
|
|
693
|
+
return undefined;
|
|
694
|
+
}
|
|
695
|
+
let outcome;
|
|
696
|
+
try {
|
|
697
|
+
outcome = { kind: "done", value: attempt() };
|
|
698
|
+
}
|
|
699
|
+
catch (error) {
|
|
700
|
+
outcome = plainBusy(error) ? { kind: "busy", error } : { kind: "failed", error };
|
|
701
|
+
}
|
|
702
|
+
if (!timeoutRestored(database, timeoutMs)) {
|
|
703
|
+
registry.untried.add(database);
|
|
704
|
+
if (outcome.kind === "busy")
|
|
705
|
+
return { kind: "failed", error: outcome.error };
|
|
706
|
+
}
|
|
707
|
+
return outcome;
|
|
708
|
+
}
|
|
709
|
+
/** Gives `database` back its busy timeout after a try, trying twice; whether it took it, as read back. */
|
|
710
|
+
function timeoutRestored(database, timeoutMs) {
|
|
711
|
+
for (let tries = 0; tries < 2; tries++) {
|
|
712
|
+
try {
|
|
713
|
+
setBusyTimeout(database, timeoutMs);
|
|
714
|
+
if (readBusyTimeout(database) === timeoutMs)
|
|
715
|
+
return true;
|
|
716
|
+
}
|
|
717
|
+
catch {
|
|
718
|
+
// Tried again once, then given up.
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
return false;
|
|
722
|
+
}
|
|
723
|
+
/** The busy timeout of `database` as it reads it now; undefined when it cannot be read. */
|
|
724
|
+
function readBusyTimeout(database) {
|
|
725
|
+
try {
|
|
726
|
+
const timeout = Number(database.prepare("PRAGMA busy_timeout").get()?.timeout);
|
|
727
|
+
return Number.isFinite(timeout) ? timeout : undefined;
|
|
728
|
+
}
|
|
729
|
+
catch {
|
|
730
|
+
return undefined;
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
/** Sets the connection's busy timeout: a setting of the connection, which touches no file. */
|
|
734
|
+
function setBusyTimeout(database, timeoutMs) {
|
|
735
|
+
database.exec(`PRAGMA busy_timeout=${timeoutMs}`);
|
|
736
|
+
}
|
|
737
|
+
/**
|
|
738
|
+
* Runs a single statement, `attempt` (synchronous on `database`, the connection `owner` owns), the way SQLite's busy
|
|
739
|
+
* handler would, without holding this thread: once at once with a busy timeout of 0; refused the lock, it waits off
|
|
740
|
+
* this thread and is tried again once a threaded transaction gives the lock back, or on a short poll for a lock another
|
|
741
|
+
* process holds, oldest first and one call per turn of the event loop; still refused at the end of the connection's
|
|
742
|
+
* busy timeout, it fails with that SQLITE_BUSY. Calls already waiting go first. When the busy timeout cannot be read,
|
|
743
|
+
* `asBefore` runs it as it always has.
|
|
744
|
+
*/
|
|
745
|
+
export function runTryingFirst(file, gate, owner, database, attempt, asBefore, busy) {
|
|
746
|
+
const timeoutMs = busyTimeoutOf(gate, owner, database);
|
|
747
|
+
if (timeoutMs === undefined)
|
|
748
|
+
return asBefore();
|
|
749
|
+
runNextWaiter(file, gate);
|
|
750
|
+
let refusal;
|
|
751
|
+
if (gate.waiters.length === 0 && !gate.paced) {
|
|
752
|
+
const first = attemptOnce(database, timeoutMs, attempt);
|
|
753
|
+
if (first === undefined)
|
|
754
|
+
return asBefore();
|
|
755
|
+
if (first.kind !== "busy") {
|
|
756
|
+
ranThisTurn(file, gate);
|
|
757
|
+
return first.kind === "done" ? Promise.resolve(first.value) : Promise.reject(first.error);
|
|
758
|
+
}
|
|
759
|
+
refusal = first.error;
|
|
760
|
+
}
|
|
761
|
+
return new Promise((resolve, reject) => {
|
|
762
|
+
const waiter = undecidedWaiter(database);
|
|
763
|
+
gate.waiters.push(waiter);
|
|
764
|
+
armTry(file, gate, waiter, database, timeoutMs, attempt, asBefore, refusal, resolve, reject, busy);
|
|
765
|
+
});
|
|
766
|
+
}
|
|
767
|
+
/**
|
|
768
|
+
* Makes `waiter` try `attempt` again on each wake until its deadline, `timeoutMs` from now, for `runTryingFirst`;
|
|
769
|
+
* `refusal` is the SQLITE_BUSY of its last try, if any.
|
|
770
|
+
*/
|
|
771
|
+
function armTry(file, gate, waiter, database, timeoutMs, attempt, asBefore, refusal, resolve, reject, busy) {
|
|
772
|
+
let lastRefusal = refusal;
|
|
773
|
+
// A try the connection does not allow runs the call as before (see `attemptOnce`).
|
|
774
|
+
const settle = (outcome) => {
|
|
775
|
+
if (outcome === undefined) {
|
|
776
|
+
resolve(asBefore());
|
|
777
|
+
return true;
|
|
778
|
+
}
|
|
779
|
+
if (outcome.kind === "busy") {
|
|
780
|
+
lastRefusal = outcome.error;
|
|
781
|
+
return false;
|
|
782
|
+
}
|
|
783
|
+
if (outcome.kind === "done")
|
|
784
|
+
resolve(outcome.value);
|
|
785
|
+
else
|
|
786
|
+
reject(outcome.error);
|
|
787
|
+
return true;
|
|
788
|
+
};
|
|
789
|
+
waiter.deadline = performance.now() + timeoutMs;
|
|
790
|
+
// At its deadline it is tried once more if it is the oldest; refused, or behind others while the lock is taken, it
|
|
791
|
+
// fails with the refusal. Behind others while the lock is free, it keeps its place.
|
|
792
|
+
waiter.timer = setTimeout(() => setImmediate(() => {
|
|
793
|
+
const index = gate.waiters.indexOf(waiter);
|
|
794
|
+
if (index === -1)
|
|
795
|
+
return;
|
|
796
|
+
if (index === 0 && settle(attemptOnce(database, timeoutMs, attempt))) {
|
|
797
|
+
gate.waiters.shift();
|
|
798
|
+
ranThisTurn(file, gate);
|
|
799
|
+
}
|
|
800
|
+
else if (index === 0 || wordTaken(file)) {
|
|
801
|
+
gate.waiters.splice(index, 1);
|
|
802
|
+
waiter.fail();
|
|
803
|
+
ranThisTurn(file, gate);
|
|
804
|
+
}
|
|
805
|
+
forgetIfIdle(file, gate);
|
|
806
|
+
}), timeoutMs);
|
|
807
|
+
waiter.tryRun = () => settle(attemptOnce(database, timeoutMs, attempt));
|
|
808
|
+
// Refused at its last try, it fails with that refusal; never tried, with SQLITE_BUSY as the runtime reports it.
|
|
809
|
+
waiter.fail = () => reject(lastRefusal ?? busy());
|
|
810
|
+
const state = registry.words.get(file)?.state;
|
|
811
|
+
if (state !== undefined)
|
|
812
|
+
watchWord(file, gate, state);
|
|
813
|
+
pollWaiters(file, gate);
|
|
814
|
+
}
|
|
815
|
+
/** Whether a call on `database` waits for its turn. */
|
|
816
|
+
export function connectionWaits(gate, database) {
|
|
817
|
+
return gate.waiters.some((waiter) => waiter.connection === database);
|
|
818
|
+
}
|
|
819
|
+
/**
|
|
820
|
+
* Runs a call on `database`, which `owner` owns, behind an earlier call on the same connection that waits, from this
|
|
821
|
+
* or another wrapped handle, so no call runs on a connection between a refused try of an earlier call and the try that
|
|
822
|
+
* follows, as none could while SQLite's busy handler waited. It is decided (see `modeOf`) only at its turn,
|
|
823
|
+
* since listing the plan of an INSERT, UPDATE or DELETE resets the connection's `changes()`, which a call before it
|
|
824
|
+
* could read; then it runs as `runTryingFirst` or `runWhenFree` would, or as before, with `call`. Once no threaded
|
|
825
|
+
* transaction holds the file, it runs as before.
|
|
826
|
+
*/
|
|
827
|
+
export function runDeferred(file, gate, owner, database, statement, attempt, call, busy) {
|
|
828
|
+
return new Promise((resolve, reject) => {
|
|
829
|
+
const waiter = undecidedWaiter(database);
|
|
830
|
+
waiter.tryRun = () => {
|
|
831
|
+
const mode = scopedHoldOpen(gate)
|
|
832
|
+
? modeOf(gate, owner, database, statement.sql, statement.params, statement.single)
|
|
833
|
+
: "as before";
|
|
834
|
+
const state = registry.words.get(file)?.state;
|
|
835
|
+
const timeoutMs = mode === "as before" ? undefined : busyTimeoutOf(gate, owner, database);
|
|
836
|
+
if (timeoutMs === undefined || (mode === "script" && state === undefined)) {
|
|
837
|
+
resolve(call());
|
|
838
|
+
return true;
|
|
839
|
+
}
|
|
840
|
+
if (mode === "script") {
|
|
841
|
+
const ran = runAdmitted(state, call);
|
|
842
|
+
if (ran !== undefined) {
|
|
843
|
+
resolve(ran);
|
|
844
|
+
return true;
|
|
845
|
+
}
|
|
846
|
+
armWhenFree(file, gate, waiter, state, timeoutMs, call, resolve, reject, busy);
|
|
847
|
+
return false;
|
|
848
|
+
}
|
|
849
|
+
const first = attemptOnce(database, timeoutMs, attempt);
|
|
850
|
+
if (first === undefined)
|
|
851
|
+
resolve(call());
|
|
852
|
+
else if (first.kind === "done")
|
|
853
|
+
resolve(first.value);
|
|
854
|
+
else if (first.kind === "failed")
|
|
855
|
+
reject(first.error);
|
|
856
|
+
else {
|
|
857
|
+
armTry(file, gate, waiter, database, timeoutMs, attempt, call, first.error, resolve, reject, busy);
|
|
858
|
+
return false;
|
|
859
|
+
}
|
|
860
|
+
return true;
|
|
861
|
+
};
|
|
862
|
+
gate.waiters.push(waiter);
|
|
863
|
+
});
|
|
864
|
+
}
|
|
865
|
+
/** Whether a threaded transaction of this thread takes or holds the file's lock now, as its word says. */
|
|
866
|
+
function wordTaken(file) {
|
|
867
|
+
const state = registry.words.get(file)?.state;
|
|
868
|
+
return state !== undefined && Atomics.load(state, 0) !== FREE;
|
|
869
|
+
}
|
|
870
|
+
/** How often calls refused a lock that no transaction of this thread holds (another process's) are tried again. */
|
|
871
|
+
const POLL_MS = 20;
|
|
872
|
+
/**
|
|
873
|
+
* Tries the oldest waiting call again every `POLL_MS` while calls wait, for locks no word announces. While the word is
|
|
874
|
+
* taken, the watch on it (`watchWord`) wakes the calls instead.
|
|
875
|
+
*/
|
|
876
|
+
function pollWaiters(file, gate) {
|
|
877
|
+
if (gate.polling || gate.waiters.length === 0)
|
|
878
|
+
return;
|
|
879
|
+
gate.polling = true;
|
|
880
|
+
setTimeout(() => {
|
|
881
|
+
gate.polling = false;
|
|
882
|
+
if (!wordTaken(file))
|
|
883
|
+
runNextWaiter(file, gate);
|
|
884
|
+
forgetIfIdle(file, gate);
|
|
885
|
+
pollWaiters(file, gate);
|
|
886
|
+
}, POLL_MS);
|
|
887
|
+
}
|
|
888
|
+
/**
|
|
889
|
+
* The statements of an `exec` text, split as SQLite reads them: past quoted strings and names (`'…'`, `"…"`, `` `…` ``,
|
|
890
|
+
* `[…]`) and comments, with a trigger's body (`CREATE TRIGGER … BEGIN … END`) kept in its statement. Empty statements
|
|
891
|
+
* are dropped. A comment left open runs to the end of the text; past a quote left open, or in a trigger's body without
|
|
892
|
+
* its END, the rest of the text is one statement, which SQLite fails.
|
|
893
|
+
*/
|
|
894
|
+
export function splitStatements(sql) {
|
|
895
|
+
const statements = [];
|
|
896
|
+
let start = 0;
|
|
897
|
+
let words = [];
|
|
898
|
+
let lastWord = "";
|
|
899
|
+
let tokens = false;
|
|
900
|
+
const trigger = () => words[0] === "CREATE" &&
|
|
901
|
+
(words[1] === "TRIGGER" || ((words[1] === "TEMP" || words[1] === "TEMPORARY") && words[2] === "TRIGGER"));
|
|
902
|
+
for (let index = 0; index < sql.length;) {
|
|
903
|
+
const char = sql[index];
|
|
904
|
+
if (char === "'" || char === '"' || char === "`" || char === "[") {
|
|
905
|
+
const close = char === "[" ? "]" : char;
|
|
906
|
+
let end = sql.indexOf(close, index + 1);
|
|
907
|
+
// A doubled quote stands for the quote itself, except in a bracketed name.
|
|
908
|
+
while (end !== -1 && close !== "]" && sql[end + 1] === close)
|
|
909
|
+
end = sql.indexOf(close, end + 2);
|
|
910
|
+
tokens = true;
|
|
911
|
+
// Unterminated: SQLite fails the statement there, after the ones before it ran.
|
|
912
|
+
if (end === -1)
|
|
913
|
+
break;
|
|
914
|
+
index = end + 1;
|
|
915
|
+
lastWord = "";
|
|
916
|
+
}
|
|
917
|
+
else if (char === "-" && sql[index + 1] === "-") {
|
|
918
|
+
const end = sql.indexOf("\n", index + 2);
|
|
919
|
+
index = end === -1 ? sql.length : end + 1;
|
|
920
|
+
}
|
|
921
|
+
else if (char === "/" && sql[index + 1] === "*") {
|
|
922
|
+
// Unterminated, the comment runs to the end of the text.
|
|
923
|
+
const end = sql.indexOf("*/", index + 2);
|
|
924
|
+
index = end === -1 ? sql.length : end + 2;
|
|
925
|
+
}
|
|
926
|
+
else if (char === ";") {
|
|
927
|
+
index += 1;
|
|
928
|
+
// Inside a trigger's body, only the semicolon after its END ends the statement.
|
|
929
|
+
if (trigger() && lastWord !== "END")
|
|
930
|
+
continue;
|
|
931
|
+
if (tokens)
|
|
932
|
+
statements.push(sql.slice(start, index - 1));
|
|
933
|
+
start = index;
|
|
934
|
+
words = [];
|
|
935
|
+
lastWord = "";
|
|
936
|
+
tokens = false;
|
|
937
|
+
}
|
|
938
|
+
else if (/[A-Za-z_]/.test(char)) {
|
|
939
|
+
let end = index + 1;
|
|
940
|
+
while (end < sql.length && /[\w$]/.test(sql[end]))
|
|
941
|
+
end += 1;
|
|
942
|
+
const word = sql.slice(index, end).toUpperCase();
|
|
943
|
+
if (words.length < 3)
|
|
944
|
+
words.push(word);
|
|
945
|
+
lastWord = word;
|
|
946
|
+
tokens = true;
|
|
947
|
+
index = end;
|
|
948
|
+
}
|
|
949
|
+
else {
|
|
950
|
+
if (!/\s/.test(char)) {
|
|
951
|
+
tokens = true;
|
|
952
|
+
lastWord = "";
|
|
953
|
+
}
|
|
954
|
+
index += 1;
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
// Past an unterminated quote, or in a trigger's body without its END, SQLite fails the rest as one statement.
|
|
958
|
+
if (tokens)
|
|
959
|
+
statements.push(sql.slice(start));
|
|
960
|
+
return statements;
|
|
961
|
+
}
|
|
962
|
+
/**
|
|
963
|
+
* The steps of the plan of `sql`, listed now from the plan kept for it (SQLite prepares a kept plan again when this
|
|
964
|
+
* connection changed its schema since, and fails it if the statement no longer prepares), or from a new one; undefined
|
|
965
|
+
* when SQLite cannot make one. The plan is bound to the call's `params` first, so parameters the statement cannot
|
|
966
|
+
* bind fail before the plan is listed, which resets `changes()` (see `modeOf`), as the statement fails before it runs.
|
|
967
|
+
*/
|
|
968
|
+
function planSteps(gate, owner, database, sql, params) {
|
|
969
|
+
const plans = plansOf(gate, owner);
|
|
970
|
+
const kept = plans.explained.get(sql);
|
|
971
|
+
if (kept !== undefined) {
|
|
972
|
+
try {
|
|
973
|
+
return kept.all(...params);
|
|
974
|
+
}
|
|
975
|
+
catch {
|
|
976
|
+
plans.explained.delete(sql);
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
try {
|
|
980
|
+
const explained = database.prepare(`EXPLAIN ${sql}`);
|
|
981
|
+
const steps = explained.all(...params);
|
|
982
|
+
if (plans.explained.size >= MAX_PLANS)
|
|
983
|
+
plans.explained.delete(plans.explained.keys().next().value);
|
|
984
|
+
plans.explained.set(sql, explained);
|
|
985
|
+
return steps;
|
|
986
|
+
}
|
|
987
|
+
catch {
|
|
988
|
+
return undefined;
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
let sqliteErrorShape;
|
|
992
|
+
/**
|
|
993
|
+
* How the runtime's node:sqlite builds its errors: their class (Bun has one of its own) and whether `code` is a field
|
|
994
|
+
* of each error, read once from a failure of a connection of this module's own. Plain `Error` fields when it cannot
|
|
995
|
+
* be read.
|
|
996
|
+
*/
|
|
997
|
+
function errorShape() {
|
|
998
|
+
if (sqliteErrorShape !== undefined)
|
|
999
|
+
return sqliteErrorShape;
|
|
1000
|
+
sqliteErrorShape = { prototype: Error.prototype, ownCode: true };
|
|
1001
|
+
try {
|
|
1002
|
+
const { DatabaseSync: Database } = createRequire(import.meta.url)("node:sqlite");
|
|
1003
|
+
const probe = new Database(":memory:");
|
|
1004
|
+
try {
|
|
1005
|
+
probe.exec("SELECT");
|
|
1006
|
+
}
|
|
1007
|
+
catch (error) {
|
|
1008
|
+
if (error instanceof Error)
|
|
1009
|
+
sqliteErrorShape = {
|
|
1010
|
+
prototype: Object.getPrototypeOf(error),
|
|
1011
|
+
ownCode: Object.hasOwn(error, "code"),
|
|
1012
|
+
};
|
|
1013
|
+
}
|
|
1014
|
+
finally {
|
|
1015
|
+
probe.close();
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
catch {
|
|
1019
|
+
// The plain shape stands.
|
|
1020
|
+
}
|
|
1021
|
+
return sqliteErrorShape;
|
|
1022
|
+
}
|
|
1023
|
+
/**
|
|
1024
|
+
* SQLITE_BUSY as the runtime's node:sqlite reports it, for a call that waited out its busy timeout without running:
|
|
1025
|
+
* the runtime's own error class with the fields a refused statement carries.
|
|
1026
|
+
*/
|
|
1027
|
+
export function sqliteBusyError() {
|
|
1028
|
+
const shape = errorShape();
|
|
1029
|
+
const error = Object.setPrototypeOf(new Error("database is locked"), shape.prototype);
|
|
1030
|
+
const fields = { errcode: 5, errstr: "database is locked" };
|
|
1031
|
+
return Object.assign(error, shape.ownCode ? { code: "ERR_SQLITE_ERROR", ...fields } : fields);
|
|
1032
|
+
}
|
|
1033
|
+
//# sourceMappingURL=node-sqlite-file-gate.js.map
|