synabun 2.4.0 β 2.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +47 -0
- package/README.md +1 -1
- package/browser-extension/content.js +73 -11
- package/browser-extension/engine.js +196 -15
- package/browser-extension/manifest.json +4 -2
- package/browser-extension/popup-strings.js +10 -4
- package/browser-extension/popup-view.js +1 -1
- package/browser-extension/popup.css +1 -0
- package/browser-extension/popup.html +4 -1
- package/browser-extension/popup.js +22 -10
- package/browser-extension/protocol.js +102 -11
- package/browser-extension/service-worker.js +20 -4
- package/browser-extension/tokens.css +1 -1
- package/docs/browser-extension-bridge.md +25 -5
- package/lib/data-home-files.js +47 -0
- package/lib/data-home-migration.js +34 -58
- package/lib/first-launch-protection.js +8 -2
- package/lib/update-snapshot.js +11 -4
- package/mcp-server/dist/http.d.ts.map +1 -1
- package/mcp-server/dist/http.js +25 -2
- package/mcp-server/dist/http.js.map +1 -1
- package/mcp-server/dist/index.d.ts.map +1 -1
- package/mcp-server/dist/index.js +62 -17
- package/mcp-server/dist/index.js.map +1 -1
- package/mcp-server/dist/services/browser-bench.d.ts +22 -22
- package/mcp-server/dist/services/memory-maintenance.d.ts +1 -0
- package/mcp-server/dist/services/memory-maintenance.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-maintenance.js +34 -45
- package/mcp-server/dist/services/memory-maintenance.js.map +1 -1
- package/mcp-server/dist/services/memory-migration-copy.d.ts +144 -0
- package/mcp-server/dist/services/memory-migration-copy.d.ts.map +1 -0
- package/mcp-server/dist/services/memory-migration-copy.js +467 -0
- package/mcp-server/dist/services/memory-migration-copy.js.map +1 -0
- package/mcp-server/dist/services/memory-migration-worker.d.ts +2 -0
- package/mcp-server/dist/services/memory-migration-worker.d.ts.map +1 -0
- package/mcp-server/dist/services/memory-migration-worker.js +60 -0
- package/mcp-server/dist/services/memory-migration-worker.js.map +1 -0
- package/mcp-server/dist/services/memory-retrieval.d.ts +4 -0
- package/mcp-server/dist/services/memory-retrieval.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-retrieval.js +188 -40
- package/mcp-server/dist/services/memory-retrieval.js.map +1 -1
- package/mcp-server/dist/services/memory-schema.d.ts +58 -2
- package/mcp-server/dist/services/memory-schema.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-schema.js +190 -13
- package/mcp-server/dist/services/memory-schema.js.map +1 -1
- package/mcp-server/dist/services/memory-sessions.d.ts +19 -1
- package/mcp-server/dist/services/memory-sessions.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-sessions.js +56 -20
- package/mcp-server/dist/services/memory-sessions.js.map +1 -1
- package/mcp-server/dist/services/memory-verification.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-verification.js +8 -5
- package/mcp-server/dist/services/memory-verification.js.map +1 -1
- package/mcp-server/dist/services/neural-interface.d.ts +6 -0
- package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
- package/mcp-server/dist/services/neural-interface.js +19 -2
- package/mcp-server/dist/services/neural-interface.js.map +1 -1
- package/mcp-server/dist/services/retrieval-reader-worker.d.ts +2 -0
- package/mcp-server/dist/services/retrieval-reader-worker.d.ts.map +1 -0
- package/mcp-server/dist/services/retrieval-reader-worker.js +76 -0
- package/mcp-server/dist/services/retrieval-reader-worker.js.map +1 -0
- package/mcp-server/dist/services/retrieval-reader.d.ts +38 -0
- package/mcp-server/dist/services/retrieval-reader.d.ts.map +1 -0
- package/mcp-server/dist/services/retrieval-reader.js +145 -0
- package/mcp-server/dist/services/retrieval-reader.js.map +1 -0
- package/mcp-server/dist/services/sqlite-write.d.ts +14 -0
- package/mcp-server/dist/services/sqlite-write.d.ts.map +1 -0
- package/mcp-server/dist/services/sqlite-write.js +94 -0
- package/mcp-server/dist/services/sqlite-write.js.map +1 -0
- package/mcp-server/dist/services/sqlite.d.ts +39 -0
- package/mcp-server/dist/services/sqlite.d.ts.map +1 -1
- package/mcp-server/dist/services/sqlite.js +249 -8
- package/mcp-server/dist/services/sqlite.js.map +1 -1
- package/mcp-server/dist/services/tool-catalog.d.ts +1 -1
- package/mcp-server/dist/services/typesafe-config.d.ts +7 -1
- package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
- package/mcp-server/dist/services/typesafe-config.js +32 -10
- package/mcp-server/dist/services/typesafe-config.js.map +1 -1
- package/mcp-server/dist/services/typesafe.d.ts.map +1 -1
- package/mcp-server/dist/services/typesafe.js +9 -7
- package/mcp-server/dist/services/typesafe.js.map +1 -1
- package/mcp-server/dist/services/vector-cache.d.ts +32 -0
- package/mcp-server/dist/services/vector-cache.d.ts.map +1 -1
- package/mcp-server/dist/services/vector-cache.js +161 -8
- package/mcp-server/dist/services/vector-cache.js.map +1 -1
- package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
- package/mcp-server/dist/tools/agents.d.ts +13 -8
- package/mcp-server/dist/tools/agents.d.ts.map +1 -1
- package/mcp-server/dist/tools/agents.js +35 -15
- package/mcp-server/dist/tools/agents.js.map +1 -1
- package/mcp-server/dist/tools/browser-advanced.d.ts +1 -1
- package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-advanced.js +10 -3
- package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
- package/mcp-server/dist/tools/browser-extension-setup.d.ts +5 -0
- package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -0
- package/mcp-server/dist/tools/browser-extension-setup.js +23 -0
- package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -0
- package/mcp-server/dist/tools/browser-interact.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-interact.js +6 -1
- package/mcp-server/dist/tools/browser-interact.js.map +1 -1
- package/mcp-server/dist/tools/fb-groups.d.ts +2 -2
- package/mcp-server/dist/tools/skill-tools.d.ts +4 -4
- package/mcp-server/dist/tools/tool-groups.d.ts +1 -1
- package/mcp-server/package-lock.json +2 -2
- package/mcp-server/package.json +1 -1
- package/mcp-server/src/http.ts +20 -2
- package/mcp-server/src/index.ts +59 -17
- package/mcp-server/src/services/memory-maintenance.ts +31 -28
- package/mcp-server/src/services/memory-migration-copy.ts +419 -0
- package/mcp-server/src/services/memory-migration-worker.ts +55 -0
- package/mcp-server/src/services/memory-retrieval.ts +173 -32
- package/mcp-server/src/services/memory-schema.ts +194 -12
- package/mcp-server/src/services/memory-sessions.ts +54 -21
- package/mcp-server/src/services/memory-verification.ts +7 -4
- package/mcp-server/src/services/neural-interface.ts +23 -2
- package/mcp-server/src/services/retrieval-reader-worker.ts +67 -0
- package/mcp-server/src/services/retrieval-reader.ts +131 -0
- package/mcp-server/src/services/sqlite-write.ts +60 -0
- package/mcp-server/src/services/sqlite.ts +246 -8
- package/mcp-server/src/services/typesafe-config.ts +25 -6
- package/mcp-server/src/services/typesafe.ts +9 -7
- package/mcp-server/src/services/vector-cache.ts +154 -9
- package/mcp-server/src/tools/agents.ts +33 -14
- package/mcp-server/src/tools/browser-advanced.ts +10 -3
- package/mcp-server/src/tools/browser-extension-setup.ts +30 -0
- package/mcp-server/src/tools/browser-interact.ts +5 -1
- package/neural-interface/i18n/en.json +266 -2
- package/neural-interface/i18n/pt-BR.json +267 -3
- package/neural-interface/lib/agents/builtins.json +207 -0
- package/neural-interface/lib/agents/registry.js +60 -15
- package/neural-interface/lib/agents/resolve.js +69 -10
- package/neural-interface/lib/agents/split.js +32 -4
- package/neural-interface/lib/assistant-api.js +19 -8
- package/neural-interface/lib/assistant-brains/claude.js +2 -0
- package/neural-interface/lib/assistant-brains/opencode.js +60 -11
- package/neural-interface/lib/assistant-catalog.js +2 -2
- package/neural-interface/lib/assistant-config.js +0 -7
- package/neural-interface/lib/assistant-dispatch.js +384 -119
- package/neural-interface/lib/assistant-persona.js +17 -5
- package/neural-interface/lib/assistant-pricing.js +65 -14
- package/neural-interface/lib/assistant-router.js +181 -54
- package/neural-interface/lib/assistant-run-wait.js +45 -28
- package/neural-interface/lib/assistant-runtime.js +48 -34
- package/neural-interface/lib/backup-contents.js +158 -0
- package/neural-interface/lib/backup-crypto-io.js +330 -0
- package/neural-interface/lib/backup-crypto-worker.js +130 -0
- package/neural-interface/lib/backup-crypto.js +525 -0
- package/neural-interface/lib/backup-download.js +268 -0
- package/neural-interface/lib/backup-encryption.js +318 -0
- package/neural-interface/lib/backup-groups.js +287 -0
- package/neural-interface/lib/backup-restore-session.js +176 -0
- package/neural-interface/lib/backup-restore-stage.js +60 -0
- package/neural-interface/lib/backup-service.js +836 -322
- package/neural-interface/lib/backup-zip-reader.js +30 -18
- package/neural-interface/lib/backup-zip-writer.js +34 -10
- package/neural-interface/lib/browser-extension-adapter.js +109 -24
- package/neural-interface/lib/browser-extension-bridge.js +42 -8
- package/neural-interface/lib/claude-agent-bridge.js +1 -0
- package/neural-interface/lib/claude-session-cleanup.js +5 -1
- package/neural-interface/lib/cli-update-planner.js +105 -6
- package/neural-interface/lib/client-diagnostics.js +42 -0
- package/neural-interface/lib/confined-fs.js +7 -2
- package/neural-interface/lib/coordination/README.md +8 -2
- package/neural-interface/lib/coordination/contract.js +161 -0
- package/neural-interface/lib/coordination/database.js +999 -0
- package/neural-interface/lib/coordination/operations.js +436 -0
- package/neural-interface/lib/coordination/service.js +68 -537
- package/neural-interface/lib/coordination/storage-worker.js +101 -0
- package/neural-interface/lib/coordination/store.js +219 -1111
- package/neural-interface/lib/db.js +70 -32
- package/neural-interface/lib/health-count.js +37 -0
- package/neural-interface/lib/loop-stall.js +139 -0
- package/neural-interface/lib/maritaca/client.js +2 -2
- package/neural-interface/lib/maritaca/models.js +12 -17
- package/neural-interface/lib/maritaca/opencode.js +4 -2
- package/neural-interface/lib/memory-api.js +9 -1
- package/neural-interface/lib/memory-session-capture.js +42 -10
- package/neural-interface/lib/memory-store-gate.js +313 -0
- package/neural-interface/lib/memory-store-migrate.js +65 -0
- package/neural-interface/lib/memory-timers.js +7 -7
- package/neural-interface/lib/native-loop-providers.js +13 -16
- package/neural-interface/lib/native-loop-runtime.js +34 -14
- package/neural-interface/lib/opencode-build-preflight.js +30 -8
- package/neural-interface/lib/opencode-native-boundary.js +69 -8
- package/neural-interface/lib/opencode-provider-view.js +14 -3
- package/neural-interface/lib/opencode-v2-ws-requests.js +31 -1
- package/neural-interface/lib/opencode2-client.js +2 -1
- package/neural-interface/lib/peer-identity.js +13 -8
- package/neural-interface/lib/recall-impact.js +122 -0
- package/neural-interface/lib/scratch-evidence.js +420 -0
- package/neural-interface/lib/scratch-process-guard.js +139 -0
- package/neural-interface/lib/scratch-references.js +279 -0
- package/neural-interface/lib/scratch-retention-core.js +385 -0
- package/neural-interface/lib/scratch-retention-worker.js +37 -0
- package/neural-interface/lib/scratch-retention.js +151 -0
- package/neural-interface/lib/session-cache-builder.js +70 -44
- package/neural-interface/lib/session-cache-worker.js +157 -0
- package/neural-interface/lib/session-indexer.js +28 -21
- package/neural-interface/lib/session-search-index.js +85 -0
- package/neural-interface/lib/skills/creation.js +1 -1
- package/neural-interface/lib/sqlite-integrity-worker.js +3 -1
- package/neural-interface/lib/style-guide/store.js +43 -3
- package/neural-interface/lib/system-restore.js +50 -0
- package/neural-interface/lib/teams/api.js +15 -6
- package/neural-interface/lib/teams/claims.js +67 -31
- package/neural-interface/lib/teams/index.js +7 -7
- package/neural-interface/lib/teams/integration.js +40 -40
- package/neural-interface/lib/teams/landing.js +6 -6
- package/neural-interface/lib/teams/recovery.js +24 -23
- package/neural-interface/lib/teams/scheduler.js +196 -97
- package/neural-interface/lib/teams/schema.js +1 -1
- package/neural-interface/lib/teams/state.js +14 -14
- package/neural-interface/lib/teams/worktrees.js +27 -27
- package/neural-interface/lib/whatsapp/bridge.js +2 -1
- package/neural-interface/lib/worker-confinement.js +47 -2
- package/neural-interface/lib/worker-mcp-channel.js +2 -0
- package/neural-interface/lib/worker-resume.js +5 -0
- package/neural-interface/lib/worker-stop.js +86 -0
- package/neural-interface/package-lock.json +2 -2
- package/neural-interface/package.json +1 -1
- package/neural-interface/public/index.html +260 -0
- package/neural-interface/public/offline.html +4 -3
- package/neural-interface/public/onboarding.html +259 -34
- package/neural-interface/public/shared/agents/studio/ax-agent-view.js +2 -2
- package/neural-interface/public/shared/agents/studio/ax-editor-view.js +1 -1
- package/neural-interface/public/shared/agents/studio/ax-library.js +0 -6
- package/neural-interface/public/shared/agents/studio/ax-main.js +14 -7
- package/neural-interface/public/shared/agents/studio/ax-ui.js +2 -2
- package/neural-interface/public/shared/agy/agy-options.js +11 -0
- package/neural-interface/public/shared/agy/agy-panel.js +29 -10
- package/neural-interface/public/shared/agy/agy-styles.js +14 -12
- package/neural-interface/public/shared/agy/agy-tabs-logic.js +4 -1
- package/neural-interface/public/shared/api.js +3 -2
- package/neural-interface/public/shared/assistant/asst-api.js +3 -3
- package/neural-interface/public/shared/assistant/asst-brain-picker.js +13 -6
- package/neural-interface/public/shared/assistant/asst-control.js +2 -0
- package/neural-interface/public/shared/assistant/asst-motion-gate.js +78 -4
- package/neural-interface/public/shared/assistant/asst-panel.js +18 -2
- package/neural-interface/public/shared/assistant/asst-rack-styles.js +4 -0
- package/neural-interface/public/shared/assistant/asst-render.js +106 -38
- package/neural-interface/public/shared/assistant/asst-route.js +102 -21
- package/neural-interface/public/shared/assistant/asst-routes-editor.js +1 -1
- package/neural-interface/public/shared/assistant/asst-sidepanel.js +4 -2
- package/neural-interface/public/shared/assistant/asst-state.js +11 -0
- package/neural-interface/public/shared/assistant/asst-styles.js +10 -23
- package/neural-interface/public/shared/assistant/route-identity.js +2 -1
- package/neural-interface/public/shared/cc-dropdown.js +21 -15
- package/neural-interface/public/shared/cdx/cdx-render.js +9 -0
- package/neural-interface/public/shared/cdx/cdx-settings.js +3 -1
- package/neural-interface/public/shared/cdx/cdx-styles.js +6 -0
- package/neural-interface/public/shared/cdx/cdx-tabs.js +29 -9
- package/neural-interface/public/shared/client-diagnostics.js +94 -0
- package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
- package/neural-interface/public/shared/cp/cp-styles.js +1 -1
- package/neural-interface/public/shared/effort-i18n.js +118 -0
- package/neural-interface/public/shared/html-shell.js +4 -51
- package/neural-interface/public/shared/loading-diagnostic-entry.js +64 -0
- package/neural-interface/public/shared/memory-store-wait.js +52 -0
- package/neural-interface/public/shared/morelogin-profile-field.js +1 -1
- package/neural-interface/public/shared/mtc/mtc-logic.js +2 -1
- package/neural-interface/public/shared/mtc/mtc-panel.js +8 -1
- package/neural-interface/public/shared/mtc/mtc-styles.js +13 -12
- package/neural-interface/public/shared/ocp-v2/ocp-v2-childpanel.js +7 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-location-logic.js +109 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-modelpicker.js +8 -1
- package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +118 -6
- package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +27 -3
- package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +13 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +2 -1
- package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +27 -93
- package/neural-interface/public/shared/ocp-v2/ocp-v2-variantpicker.js +17 -6
- package/neural-interface/public/shared/output-format.js +294 -0
- package/neural-interface/public/shared/owner-authority-view.js +4 -10
- package/neural-interface/public/shared/page-session.js +1 -1
- package/neural-interface/public/shared/provider-icons.js +6 -0
- package/neural-interface/public/shared/schedules-view.js +2 -1
- package/neural-interface/public/shared/server-presence.js +77 -0
- package/neural-interface/public/shared/settings/settings-ai-browser.js +5 -5
- package/neural-interface/public/shared/settings/settings-backup-contents.js +241 -0
- package/neural-interface/public/shared/settings/settings-backup-download.js +298 -0
- package/neural-interface/public/shared/settings/settings-backup-encryption-pane.js +335 -0
- package/neural-interface/public/shared/settings/settings-backup-encryption.js +545 -0
- package/neural-interface/public/shared/settings/settings-ia.js +1 -1
- package/neural-interface/public/shared/skills/studio/sx-geometry.js +12 -3
- package/neural-interface/public/shared/skills/studio/sx-main.js +14 -7
- package/neural-interface/public/shared/start-bridge.js +2 -2
- package/neural-interface/public/shared/studio-attention.js +6 -0
- package/neural-interface/public/shared/styles.css +354 -438
- package/neural-interface/public/shared/transcript-rows.js +28 -3
- package/neural-interface/public/shared/tray-auto-close.js +18 -5
- package/neural-interface/public/shared/ui-agents.js +1 -2
- package/neural-interface/public/shared/ui-automation-studio.js +168 -108
- package/neural-interface/public/shared/ui-claude-panel.js +42 -65
- package/neural-interface/public/shared/ui-loading.js +185 -25
- package/neural-interface/public/shared/ui-native-loop-router.js +59 -20
- package/neural-interface/public/shared/ui-navbar.js +2 -1
- package/neural-interface/public/shared/ui-output.js +533 -0
- package/neural-interface/public/shared/ui-owner-authority.js +48 -25
- package/neural-interface/public/shared/ui-schedules-studio.js +165 -128
- package/neural-interface/public/shared/ui-scroll-follow.js +97 -6
- package/neural-interface/public/shared/ui-sessions.js +2 -2
- package/neural-interface/public/shared/ui-settings-entry.js +18 -0
- package/neural-interface/public/shared/ui-settings.js +234 -67
- package/neural-interface/public/shared/ui-sidepanel-tray.js +3 -2
- package/neural-interface/public/shared/ui-sync.js +1 -0
- package/neural-interface/public/shared/ui-tooltip.js +16 -0
- package/neural-interface/public/shared/ui-tutorial.js +5 -6
- package/neural-interface/public/shared/ui-worker-end.js +27 -8
- package/neural-interface/public/shared/worker-end.js +9 -4
- package/neural-interface/public/sw.js +4 -3
- package/neural-interface/public/variant/2d/main.js +5 -0
- package/neural-interface/public/variant/3d/app.js +10 -0
- package/neural-interface/public/variant/3d/main.js +17 -4
- package/neural-interface/scripts/scratch-retention.mjs +20 -0
- package/neural-interface/server.js +507 -160
- package/npm-shrinkwrap.json +2 -2
- package/package.json +2 -1
- package/scripts/restore-data-home-from-backup.mjs +175 -8
- package/setup.js +18 -4
|
@@ -1,1138 +1,246 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
// recipient acknowledged it. Nothing is acknowledged by being read, so an event a recipient never
|
|
13
|
-
// acknowledged is handed out again, also after a restart (at-least-once).
|
|
14
|
-
// cursors per recipient, the seq up to which everything addressed to it is acknowledged.
|
|
15
|
-
// claims which slice of a team holds which files while it works (overlap is refused).
|
|
16
|
-
// team_tasks the journal of a team's and its slices' states, for recovery after a crash.
|
|
17
|
-
// outbox follow-ups queued for a run, kept until the run took them.
|
|
18
|
-
// migrations which schema versions this file has had applied.
|
|
19
|
-
//
|
|
20
|
-
// Waiting is a wake-up, never a poll: `subscribe` and `waitFor` are called back after the transaction that
|
|
21
|
-
// appended an event has committed, in this process. The file is its own (DATA_HOME/data/coordination.db), apart
|
|
22
|
-
// from memory.db: that one is shared with the MCP server and backed up, and coordination churn has no place in it.
|
|
23
|
-
//
|
|
24
|
-
// One process writes (the Neural Interface server, where /mcp is mounted too); everything here is synchronous
|
|
25
|
-
// except `waitFor`, so a JavaScript turn is never interleaved with another's. The Assistant's dispatcher and runtime
|
|
26
|
-
// use it through service.js (the mailbox, typed waits, the follow-up outbox); README.md beside this file is the
|
|
27
|
-
// reference for the phases that build on it.
|
|
1
|
+
// One long-lived worker owns the coordination DB. Requests (including reads) enter
|
|
2
|
+
// its MessagePort FIFO in submission order. Replies and notices follow SQLite commit.
|
|
3
|
+
import { Worker } from 'node:worker_threads';
|
|
4
|
+
import { markActivity } from '../loop-stall.js';
|
|
5
|
+
import { matchesOwnedPath } from '../teams/schema.js';
|
|
6
|
+
import { COORDINATION_LIMITS, CoordinationError, MIGRATIONS } from './contract.js';
|
|
7
|
+
export * from './contract.js';
|
|
8
|
+
|
|
9
|
+
const workerURL = new URL('./storage-worker.js', import.meta.url);
|
|
10
|
+
const unavailable = (code, message) => new CoordinationError(code, message, { status: 503 });
|
|
11
|
+
const methods = (names, call) => Object.fromEntries(names.split(' ').map(name => [name, (...args) => call(name, args)]));
|
|
28
12
|
|
|
29
|
-
import { randomUUID } from 'node:crypto';
|
|
30
|
-
import { mkdirSync } from 'node:fs';
|
|
31
|
-
import { dirname, join } from 'node:path';
|
|
32
|
-
import { DatabaseSync } from 'node:sqlite';
|
|
33
|
-
import { globsOverlap, isTeamSlug, matchesOwnedPath, normalizeOwnedPath, normalizeRelPath, ownedPathProblem } from '../teams/schema.js';
|
|
34
|
-
|
|
35
|
-
export const COORDINATION_SCHEMA_VERSION = 1;
|
|
36
|
-
export const COORDINATION_DB_FILE = 'coordination.db';
|
|
37
|
-
/** Most urgent first. `pending` hands out critical events before everything else. */
|
|
38
|
-
export const EVENT_PRIORITIES = Object.freeze(['critical', 'normal', 'low']);
|
|
39
|
-
export const DEFAULT_EVENT_PRIORITY = 'normal';
|
|
40
|
-
|
|
41
|
-
/**
|
|
42
|
-
* Event kinds the phases agree on, so two modules never name one thing twice. The store takes any kind of the
|
|
43
|
-
* right form; a kind listed here gets its priority from KIND_PRIORITY when an event names none.
|
|
44
|
-
*/
|
|
45
|
-
export const EVENT_KINDS = Object.freeze({
|
|
46
|
-
RUN_PROGRESS: 'run.progress', // a worker is still at it (what it is doing now)
|
|
47
|
-
RUN_RESULT: 'run.result', // a worker turn ended with a ## Result
|
|
48
|
-
RUN_NEEDS_INPUT: 'run.needs_input', // a worker asked a question only the user or the brain can answer
|
|
49
|
-
RUN_PERMISSION: 'run.permission', // a worker waits for a permission decision
|
|
50
|
-
RUN_FAILED: 'run.failed', // a run ended without a result
|
|
51
|
-
RUN_STALLED: 'run.stalled', // a run shows no sign of life
|
|
52
|
-
RUN_MESSAGE: 'run.message', // text from one agent to another (payload.text, payload.from)
|
|
53
|
-
RUN_STOPPED: 'run.stopped', // a run was stopped (the user, a budget, a cap); payload.run.completionReason says by what
|
|
54
|
-
RUN_INTERRUPTED: 'run.interrupted', // a server restart ended a run that could not be resumed
|
|
55
|
-
RUN_COMPLETED: 'run.completed', // a run ended after its work was done (its result came as run.result)
|
|
56
|
-
RUN_BUDGET: 'run.budget', // the session budget: a warning, the cap reached, usage that cannot be priced
|
|
57
|
-
RUN_NOTICE: 'run.notice', // something the owner of a run should hear once (the user wrote to the worker)
|
|
58
|
-
SESSION_MEMORY_DUE: 'session.memory_due', // a finished run has no memory yet (the runtime's reminder to its brain)
|
|
59
|
-
ROUTE_DECIDED: 'route.decided', // the user picked a model on a route card
|
|
60
|
-
ROUTE_EXPIRED: 'route.expired', // a route card got no answer in time
|
|
61
|
-
ROUTE_DECLINED: 'route.declined', // the user declined a route card
|
|
62
|
-
CLARIFY_ANSWERED: 'clarify.answered', // the user answered the Assistant's questions
|
|
63
|
-
CLARIFY_DECLINED: 'clarify.declined', // the user skipped them
|
|
64
|
-
TEAM_MESSAGE: 'team.message', // text on a team's channel (payload.text, payload.from)
|
|
65
|
-
TEAM_STATE: 'team.state', // a team moved to another state (lib/teams/schema.js TEAM_STATES)
|
|
66
|
-
SLICE_STATE: 'slice.state', // a slice moved to another state (SLICE_STATES)
|
|
67
|
-
SLICE_PROGRESS: 'slice.progress', // a slice's worker is still at it
|
|
68
|
-
CLAIM_CONFLICT: 'claim.conflict', // a worker needs a file another slice holds
|
|
69
|
-
INTEGRATION_CONFLICT: 'integration.conflict', // joining a slice on the integration branch did not apply cleanly
|
|
70
|
-
INTEGRATION_READY: 'integration.ready', // every slice is joined; the branch waits for the user
|
|
71
|
-
});
|
|
72
|
-
export const KIND_PRIORITY = Object.freeze({
|
|
73
|
-
'run.progress': 'low', 'slice.progress': 'low',
|
|
74
|
-
'run.result': 'normal', 'run.message': 'normal', 'team.state': 'normal', 'slice.state': 'normal', 'integration.ready': 'normal',
|
|
75
|
-
'run.stopped': 'normal', 'run.completed': 'normal', 'run.budget': 'normal', 'run.notice': 'normal',
|
|
76
|
-
'session.memory_due': 'normal', 'team.message': 'normal',
|
|
77
|
-
// A card's outcome is the user's own act: whoever relayed it (the WhatsApp bridge) finishes its bookkeeping first,
|
|
78
|
-
// so it rides the short debounce of normal events instead of starting a turn inside that call.
|
|
79
|
-
'route.decided': 'normal', 'route.expired': 'normal', 'route.declined': 'normal', 'clarify.answered': 'normal', 'clarify.declined': 'normal',
|
|
80
|
-
'run.needs_input': 'critical', 'run.permission': 'critical', 'run.failed': 'critical', 'run.stalled': 'critical',
|
|
81
|
-
'run.interrupted': 'critical',
|
|
82
|
-
'claim.conflict': 'critical', 'integration.conflict': 'critical',
|
|
83
|
-
});
|
|
84
|
-
|
|
85
|
-
export const COORDINATION_LIMITS = Object.freeze({
|
|
86
|
-
id: 200, kind: 64, recipient: 200, recipients: 64, payloadBytes: 256 * 1024, readLimit: 1000, defaultReadLimit: 100,
|
|
87
|
-
outboxText: 20000, state: 40, journalDataBytes: 64 * 1024, claimGlobs: 64, runIds: 500,
|
|
88
|
-
defaultWaitMs: 30_000, maxWaitMs: 10 * 60_000,
|
|
89
|
-
});
|
|
90
|
-
|
|
91
|
-
/** The recipient name of an Assistant session, of a run, of a team's integrator: one spelling for every module. */
|
|
92
|
-
export const sessionRecipient = (sessionId) => `session:${sessionId}`;
|
|
93
|
-
export const runRecipient = (runId) => `run:${runId}`;
|
|
94
|
-
export const teamRecipient = (teamId) => `team:${teamId}`;
|
|
95
|
-
|
|
96
|
-
/** Where the store lives under a data folder (DATA_HOME/data). */
|
|
97
|
-
export function coordinationDbPath(dataDir) {
|
|
98
|
-
if (typeof dataDir !== 'string' || !dataDir) throw new CoordinationError('PATH_REQUIRED', 'coordinationDbPath needs the data folder.');
|
|
99
|
-
return join(dataDir, COORDINATION_DB_FILE);
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
export class CoordinationError extends Error {
|
|
103
|
-
/** @param {string} code @param {string} message @param {object} [extra] */
|
|
104
|
-
constructor(code, message, extra = {}) {
|
|
105
|
-
super(message);
|
|
106
|
-
this.name = 'CoordinationError';
|
|
107
|
-
this.code = code;
|
|
108
|
-
this.status = code === 'CLOSED' ? 503 : 400;
|
|
109
|
-
Object.assign(this, extra);
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
const SCHEMA_V1 = `
|
|
114
|
-
CREATE TABLE events (
|
|
115
|
-
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
116
|
-
id TEXT NOT NULL UNIQUE,
|
|
117
|
-
session_id TEXT,
|
|
118
|
-
team_id TEXT,
|
|
119
|
-
run_id TEXT,
|
|
120
|
-
kind TEXT NOT NULL,
|
|
121
|
-
priority TEXT NOT NULL CHECK (priority IN ('critical', 'normal', 'low')),
|
|
122
|
-
payload TEXT NOT NULL DEFAULT 'null',
|
|
123
|
-
coalesce_key TEXT,
|
|
124
|
-
created_at INTEGER NOT NULL
|
|
125
|
-
);
|
|
126
|
-
CREATE INDEX events_team ON events (team_id, seq);
|
|
127
|
-
CREATE INDEX events_session ON events (session_id, seq);
|
|
128
|
-
CREATE INDEX events_run ON events (run_id, seq);
|
|
129
|
-
|
|
130
|
-
CREATE TABLE deliveries (
|
|
131
|
-
recipient TEXT NOT NULL,
|
|
132
|
-
event_id TEXT NOT NULL REFERENCES events (id) ON DELETE CASCADE,
|
|
133
|
-
seq INTEGER NOT NULL,
|
|
134
|
-
delivered_at INTEGER,
|
|
135
|
-
acked_at INTEGER,
|
|
136
|
-
attempts INTEGER NOT NULL DEFAULT 0,
|
|
137
|
-
coalesced_into TEXT,
|
|
138
|
-
merged INTEGER NOT NULL DEFAULT 0,
|
|
139
|
-
PRIMARY KEY (recipient, event_id)
|
|
140
|
-
) WITHOUT ROWID;
|
|
141
|
-
CREATE INDEX deliveries_seq ON deliveries (recipient, seq);
|
|
142
|
-
CREATE INDEX deliveries_open ON deliveries (recipient, seq) WHERE acked_at IS NULL;
|
|
143
|
-
CREATE INDEX deliveries_event ON deliveries (event_id);
|
|
144
|
-
|
|
145
|
-
CREATE TABLE cursors (
|
|
146
|
-
recipient TEXT PRIMARY KEY,
|
|
147
|
-
seq INTEGER NOT NULL,
|
|
148
|
-
updated_at INTEGER NOT NULL
|
|
149
|
-
) WITHOUT ROWID;
|
|
150
|
-
|
|
151
|
-
CREATE TABLE claims (
|
|
152
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
153
|
-
team_id TEXT NOT NULL,
|
|
154
|
-
slice_id TEXT NOT NULL,
|
|
155
|
-
glob TEXT NOT NULL,
|
|
156
|
-
run_id TEXT,
|
|
157
|
-
created_at INTEGER NOT NULL,
|
|
158
|
-
released_at INTEGER
|
|
159
|
-
);
|
|
160
|
-
CREATE INDEX claims_team ON claims (team_id, released_at);
|
|
161
|
-
CREATE UNIQUE INDEX claims_one_active ON claims (team_id, slice_id, glob) WHERE released_at IS NULL;
|
|
162
|
-
|
|
163
|
-
CREATE TABLE team_tasks (
|
|
164
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
165
|
-
team_id TEXT NOT NULL,
|
|
166
|
-
slice_id TEXT NOT NULL DEFAULT '',
|
|
167
|
-
state TEXT NOT NULL,
|
|
168
|
-
run_id TEXT,
|
|
169
|
-
data TEXT NOT NULL DEFAULT '{}',
|
|
170
|
-
created_at INTEGER NOT NULL
|
|
171
|
-
);
|
|
172
|
-
CREATE INDEX team_tasks_team ON team_tasks (team_id, slice_id, id);
|
|
173
|
-
|
|
174
|
-
CREATE TABLE outbox (
|
|
175
|
-
n INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
176
|
-
id TEXT NOT NULL UNIQUE,
|
|
177
|
-
run_id TEXT NOT NULL,
|
|
178
|
-
text TEXT NOT NULL,
|
|
179
|
-
session_id TEXT,
|
|
180
|
-
meta TEXT NOT NULL DEFAULT '{}',
|
|
181
|
-
created_at INTEGER NOT NULL,
|
|
182
|
-
sent_at INTEGER,
|
|
183
|
-
attempts INTEGER NOT NULL DEFAULT 0
|
|
184
|
-
);
|
|
185
|
-
CREATE INDEX outbox_run ON outbox (run_id, n);
|
|
186
|
-
CREATE INDEX outbox_unsent ON outbox (run_id, n) WHERE sent_at IS NULL;
|
|
187
|
-
`;
|
|
188
|
-
|
|
189
|
-
/** Every schema change, in order. A new one is appended with the next version; one that shipped is never edited. */
|
|
190
|
-
export const MIGRATIONS = Object.freeze([
|
|
191
|
-
Object.freeze({ version: 1, name: 'events, deliveries, cursors, claims, team_tasks, outbox', up: (db) => db.exec(SCHEMA_V1) }),
|
|
192
|
-
]);
|
|
193
|
-
|
|
194
|
-
const KIND_RE = /^[a-z][a-z0-9_.:-]{0,63}$/;
|
|
195
|
-
// eslint-disable-next-line no-control-regex
|
|
196
|
-
const CONTROL_RE = /[\u0000-\u001f\u007f]/;
|
|
197
|
-
const iso = (ms) => (ms === null || ms === undefined ? null : new Date(Number(ms)).toISOString());
|
|
198
|
-
const isObject = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
|
|
199
|
-
const fail = (code, message, extra) => new CoordinationError(code, message, extra);
|
|
200
|
-
|
|
201
|
-
function idText(value, field, { required = false } = {}) {
|
|
202
|
-
if (value === null || value === undefined || value === '') {
|
|
203
|
-
if (required) throw fail('FIELD_REQUIRED', `${field} is required.`, { field });
|
|
204
|
-
return null;
|
|
205
|
-
}
|
|
206
|
-
if (typeof value !== 'string' || value.length > COORDINATION_LIMITS.id || CONTROL_RE.test(value)) {
|
|
207
|
-
throw fail('FIELD_INVALID', `${field} must be text of at most ${COORDINATION_LIMITS.id} characters with no control character.`, { field });
|
|
208
|
-
}
|
|
209
|
-
return value;
|
|
210
|
-
}
|
|
211
|
-
function recipientText(value) {
|
|
212
|
-
if (typeof value !== 'string' || !value || value.length > COORDINATION_LIMITS.recipient || CONTROL_RE.test(value)) {
|
|
213
|
-
throw fail('RECIPIENT_INVALID', `A recipient is a name of at most ${COORDINATION_LIMITS.recipient} characters, like "session:<id>" or "run:<id>".`, { field: 'recipient' });
|
|
214
|
-
}
|
|
215
|
-
return value;
|
|
216
|
-
}
|
|
217
|
-
function kindList(kinds) {
|
|
218
|
-
if (kinds === null || kinds === undefined) return null;
|
|
219
|
-
const list = (Array.isArray(kinds) ? kinds : [kinds]).map((kind) => String(kind));
|
|
220
|
-
for (const kind of list) if (!KIND_RE.test(kind)) throw fail('KIND_INVALID', `"${kind.slice(0, 80)}" is not an event kind.`, { field: 'kinds' });
|
|
221
|
-
return list.length ? [...new Set(list)] : null;
|
|
222
|
-
}
|
|
223
|
-
function limitOf(value, fallback = COORDINATION_LIMITS.defaultReadLimit) {
|
|
224
|
-
const n = Math.floor(Number(value));
|
|
225
|
-
return Number.isFinite(n) && n >= 1 ? Math.min(n, COORDINATION_LIMITS.readLimit) : fallback;
|
|
226
|
-
}
|
|
227
|
-
function seqOf(value, field = 'afterSeq') {
|
|
228
|
-
const n = Number(value);
|
|
229
|
-
if (!Number.isInteger(n) || n < 0) throw fail('SEQ_INVALID', `${field} must be a whole number from 0.`, { field });
|
|
230
|
-
return n;
|
|
231
|
-
}
|
|
232
|
-
function jsonText(value, field, maxBytes) {
|
|
233
|
-
let out;
|
|
234
|
-
try { out = JSON.stringify(value === undefined ? null : value); } catch (error) { throw fail('PAYLOAD_INVALID', `${field} cannot be written as JSON: ${error?.message || error}`, { field }); }
|
|
235
|
-
if (out === undefined) throw fail('PAYLOAD_INVALID', `${field} cannot be written as JSON.`, { field });
|
|
236
|
-
if (Buffer.byteLength(out, 'utf8') > maxBytes) throw fail('PAYLOAD_TOO_LARGE', `${field} is larger than ${Math.round(maxBytes / 1024)} KB.`, { field });
|
|
237
|
-
return out;
|
|
238
|
-
}
|
|
239
|
-
function parseJson(textValue, fallback = null) {
|
|
240
|
-
try { return JSON.parse(textValue); } catch { return fallback; }
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
function applyMigrations(db, migrations, now) {
|
|
244
|
-
db.exec('CREATE TABLE IF NOT EXISTS migrations (version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at INTEGER NOT NULL)');
|
|
245
|
-
const ordered = [...migrations].sort((a, b) => a.version - b.version);
|
|
246
|
-
const latest = ordered.length ? ordered[ordered.length - 1].version : 0;
|
|
247
|
-
const applied = Number(db.prepare('SELECT MAX(version) AS version FROM migrations').get()?.version) || 0;
|
|
248
|
-
// A file a newer SynaBun wrote is never read with older rules: its tables may mean something else by now.
|
|
249
|
-
if (applied > latest) throw fail('SCHEMA_NEWER', `The coordination store was written by a newer SynaBun (schema ${applied}; this one knows ${latest}).`, { found: applied, known: latest });
|
|
250
|
-
for (const migration of ordered) {
|
|
251
|
-
if (migration.version <= applied) continue;
|
|
252
|
-
db.exec('BEGIN IMMEDIATE');
|
|
253
|
-
try {
|
|
254
|
-
migration.up(db);
|
|
255
|
-
db.prepare('INSERT INTO migrations (version, name, applied_at) VALUES (?, ?, ?)').run(migration.version, String(migration.name || ''), now());
|
|
256
|
-
db.exec('COMMIT');
|
|
257
|
-
} catch (error) {
|
|
258
|
-
try { db.exec('ROLLBACK'); } catch { /* the failure below is the one to report */ }
|
|
259
|
-
throw fail('MIGRATION_FAILED', `Coordination store migration ${migration.version} failed: ${error?.message || error}`, { version: migration.version, cause: error });
|
|
260
|
-
}
|
|
261
|
-
}
|
|
262
|
-
return latest;
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
/**
|
|
266
|
-
* Open (and create or upgrade) the coordination store.
|
|
267
|
-
*
|
|
268
|
-
* @param {object} options
|
|
269
|
-
* @param {string} options.path the database file (`coordinationDbPath(dataDir)`); a test passes its own
|
|
270
|
-
* @param {() => number} [options.now] epoch milliseconds
|
|
271
|
-
* @param {() => string} [options.newId] ids for events, claims' rows and outbox items the caller did not name
|
|
272
|
-
* @param {number} [options.busyTimeoutMs] how long a statement waits for another connection's lock
|
|
273
|
-
* @param {'FULL'|'NORMAL'} [options.synchronous] FULL (default): a committed event survives a power cut
|
|
274
|
-
* @param {(tag: string, detail: any) => void} [options.log]
|
|
275
|
-
* @param {readonly object[]} [options.migrations] the schema steps (tests add one to try an upgrade)
|
|
276
|
-
*/
|
|
277
13
|
export function createCoordinationStore({
|
|
278
|
-
path,
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
busyTimeoutMs = 5000,
|
|
282
|
-
synchronous = 'FULL',
|
|
283
|
-
log = () => {},
|
|
284
|
-
migrations = MIGRATIONS,
|
|
14
|
+
path, now = Date.now, newId, busyTimeoutMs = 5000, shutdownTimeoutMs = 8000,
|
|
15
|
+
synchronous = 'FULL', log = () => {}, allowDegraded = false, limits, migrations = MIGRATIONS,
|
|
16
|
+
createWorker = (url, options) => new Worker(url, options),
|
|
285
17
|
} = {}) {
|
|
286
|
-
if (typeof path !== 'string'
|
|
287
|
-
if (
|
|
288
|
-
const
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
db.exec('BEGIN IMMEDIATE');
|
|
315
|
-
inTransaction = true;
|
|
316
|
-
let out;
|
|
317
|
-
try {
|
|
318
|
-
out = fn();
|
|
319
|
-
db.exec('COMMIT');
|
|
320
|
-
} catch (error) {
|
|
321
|
-
try { db.exec('ROLLBACK'); } catch { /* nothing was open any more */ }
|
|
322
|
-
throw error;
|
|
323
|
-
} finally {
|
|
324
|
-
inTransaction = false;
|
|
325
|
-
}
|
|
326
|
-
return out;
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
// ββ rows β what callers get ββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
330
|
-
const eventView = (row) => ({
|
|
331
|
-
id: row.id,
|
|
332
|
-
seq: Number(row.seq),
|
|
333
|
-
sessionId: row.session_id ?? null,
|
|
334
|
-
teamId: row.team_id ?? null,
|
|
335
|
-
runId: row.run_id ?? null,
|
|
336
|
-
kind: row.kind,
|
|
337
|
-
priority: row.priority,
|
|
338
|
-
payload: parseJson(row.payload),
|
|
339
|
-
createdAt: iso(row.created_at),
|
|
340
|
-
});
|
|
341
|
-
const deliveryView = (row) => ({
|
|
342
|
-
...eventView(row),
|
|
343
|
-
delivery: {
|
|
344
|
-
recipient: row.recipient,
|
|
345
|
-
deliveredAt: iso(row.delivered_at),
|
|
346
|
-
ackedAt: iso(row.acked_at),
|
|
347
|
-
attempts: Number(row.attempts) || 0,
|
|
348
|
-
// Handed out before and not acknowledged then: the consumer may have seen it already.
|
|
349
|
-
redelivered: (Number(row.attempts) || 0) > 1,
|
|
350
|
-
// How many older low-priority events this one stands for (coalesce).
|
|
351
|
-
merged: Number(row.merged) || 0,
|
|
352
|
-
},
|
|
353
|
-
});
|
|
354
|
-
const claimView = (row) => ({
|
|
355
|
-
id: Number(row.id), teamId: row.team_id, sliceId: row.slice_id, glob: row.glob, runId: row.run_id ?? null,
|
|
356
|
-
createdAt: iso(row.created_at), releasedAt: iso(row.released_at),
|
|
357
|
-
});
|
|
358
|
-
const journalView = (row) => ({
|
|
359
|
-
id: Number(row.id), teamId: row.team_id, sliceId: row.slice_id || null, state: row.state, runId: row.run_id ?? null,
|
|
360
|
-
data: parseJson(row.data, {}), createdAt: iso(row.created_at),
|
|
361
|
-
});
|
|
362
|
-
const outboxView = (row) => ({
|
|
363
|
-
id: row.id, runId: row.run_id, text: row.text, sessionId: row.session_id ?? null, meta: parseJson(row.meta, {}),
|
|
364
|
-
createdAt: iso(row.created_at), sentAt: iso(row.sent_at), attempts: Number(row.attempts) || 0,
|
|
365
|
-
});
|
|
366
|
-
|
|
367
|
-
// ββ events βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
368
|
-
const selectEventById = db.prepare('SELECT * FROM events WHERE id = ?');
|
|
369
|
-
const insertEvent = db.prepare('INSERT INTO events (id, session_id, team_id, run_id, kind, priority, payload, coalesce_key, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
|
|
370
|
-
const insertDelivery = db.prepare('INSERT INTO deliveries (recipient, event_id, seq) VALUES (?, ?, ?)');
|
|
371
|
-
const selectRecipientsOfEvent = db.prepare('SELECT recipient FROM deliveries WHERE event_id = ? ORDER BY recipient');
|
|
372
|
-
|
|
373
|
-
function readEventInput(event) {
|
|
374
|
-
if (!isObject(event)) throw fail('EVENT_INVALID', 'An event is an object with at least a kind.');
|
|
375
|
-
const kind = typeof event.kind === 'string' ? event.kind.trim() : '';
|
|
376
|
-
if (!KIND_RE.test(kind)) throw fail('KIND_INVALID', 'kind is a lower-case name like "run.result" (letters, digits, ".", "_", ":" and "-", at most 64).', { field: 'kind' });
|
|
377
|
-
const priority = event.priority === undefined || event.priority === null || event.priority === '' ? (KIND_PRIORITY[kind] || DEFAULT_EVENT_PRIORITY) : String(event.priority).toLowerCase();
|
|
378
|
-
if (!EVENT_PRIORITIES.includes(priority)) throw fail('PRIORITY_INVALID', `priority must be one of ${EVENT_PRIORITIES.join(', ')}.`, { field: 'priority' });
|
|
379
|
-
const to = event.to === undefined || event.to === null ? [] : (Array.isArray(event.to) ? event.to : [event.to]);
|
|
380
|
-
if (to.length > COORDINATION_LIMITS.recipients) throw fail('RECIPIENTS_TOO_MANY', `An event is addressed to at most ${COORDINATION_LIMITS.recipients} recipients.`, { field: 'to' });
|
|
381
|
-
return {
|
|
382
|
-
id: idText(event.id, 'id') || String(newId()),
|
|
383
|
-
sessionId: idText(event.sessionId, 'sessionId'),
|
|
384
|
-
teamId: idText(event.teamId, 'teamId'),
|
|
385
|
-
runId: idText(event.runId, 'runId'),
|
|
386
|
-
kind,
|
|
387
|
-
priority,
|
|
388
|
-
payload: jsonText(event.payload, 'payload', COORDINATION_LIMITS.payloadBytes),
|
|
389
|
-
coalesceKey: idText(event.coalesceKey, 'coalesceKey'),
|
|
390
|
-
to: [...new Set(to.map(recipientText))],
|
|
391
|
-
};
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
function appendOne(input) {
|
|
395
|
-
const existing = selectEventById.get(input.id);
|
|
396
|
-
// The same id again: the event is there already. Nothing is written and nobody is woken a second time.
|
|
397
|
-
if (existing) return { result: { id: existing.id, seq: Number(existing.seq), duplicate: true }, notice: null };
|
|
398
|
-
const createdAt = now();
|
|
399
|
-
const seq = Number(insertEvent.run(input.id, input.sessionId, input.teamId, input.runId, input.kind, input.priority, input.payload, input.coalesceKey, createdAt).lastInsertRowid);
|
|
400
|
-
for (const recipient of input.to) insertDelivery.run(recipient, input.id, seq);
|
|
401
|
-
const event = { id: input.id, seq, sessionId: input.sessionId, teamId: input.teamId, runId: input.runId, kind: input.kind, priority: input.priority, payload: parseJson(input.payload), createdAt: iso(createdAt) };
|
|
402
|
-
return { result: { id: input.id, seq, duplicate: false }, notice: { event, recipients: input.to } };
|
|
403
|
-
}
|
|
404
|
-
|
|
405
|
-
/**
|
|
406
|
-
* Add an event to the log and address it.
|
|
407
|
-
* @param {object} event
|
|
408
|
-
* @param {string} [event.id] the caller's own id: appending it again stores nothing new (`duplicate: true`)
|
|
409
|
-
* @param {string} event.kind "run.result", "slice.state", β¦
|
|
410
|
-
* @param {'critical'|'normal'|'low'} [event.priority] default: KIND_PRIORITY of the kind, else normal
|
|
411
|
-
* @param {string} [event.sessionId] the Assistant session it belongs to
|
|
412
|
-
* @param {string} [event.teamId]
|
|
413
|
-
* @param {string} [event.runId]
|
|
414
|
-
* @param {any} [event.payload] JSON, at most 256 KB
|
|
415
|
-
* @param {string|string[]} [event.to] recipients: each gets a delivery it must acknowledge. None: logged only.
|
|
416
|
-
* @param {string} [event.coalesceKey] low priority only: events of one key are merged by `coalesce` (default key: kind, run, team and session)
|
|
417
|
-
* @returns {{ id: string, seq: number, duplicate: boolean }}
|
|
418
|
-
*/
|
|
419
|
-
function append(event) {
|
|
420
|
-
const input = readEventInput(event);
|
|
421
|
-
const { result, notice } = transaction(() => appendOne(input));
|
|
422
|
-
if (notice) publish(notice);
|
|
423
|
-
return result;
|
|
424
|
-
}
|
|
425
|
-
|
|
426
|
-
/** Several events in one transaction: all of them are stored, or none. Same answers as `append`, in order. */
|
|
427
|
-
function appendMany(events) {
|
|
428
|
-
if (!Array.isArray(events)) throw fail('EVENT_INVALID', 'appendMany takes a list of events.');
|
|
429
|
-
const inputs = events.map(readEventInput);
|
|
430
|
-
const done = transaction(() => inputs.map(appendOne));
|
|
431
|
-
for (const { notice } of done) if (notice) publish(notice);
|
|
432
|
-
return done.map(({ result }) => result);
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
/** One event by its id (with the recipients it was addressed to), or null. */
|
|
436
|
-
function get(id) {
|
|
437
|
-
open();
|
|
438
|
-
const row = selectEventById.get(String(id));
|
|
439
|
-
return row ? { ...eventView(row), to: selectRecipientsOfEvent.all(row.id).map((r) => r.recipient) } : null;
|
|
440
|
-
}
|
|
441
|
-
|
|
442
|
-
/** The seq of the newest event (0 for an empty log). */
|
|
443
|
-
function lastSeq() {
|
|
444
|
-
open();
|
|
445
|
-
return Number(db.prepare('SELECT MAX(seq) AS seq FROM events').get()?.seq) || 0;
|
|
446
|
-
}
|
|
447
|
-
|
|
448
|
-
/**
|
|
449
|
-
* The log itself, oldest first: every event after `afterSeq` that matches, whoever it was addressed to. Reading
|
|
450
|
-
* it delivers and acknowledges nothing (a timeline, a scheduler's replay). `read` is the mailbox.
|
|
451
|
-
*/
|
|
452
|
-
function events({ afterSeq = 0, teamId = null, sessionId = null, runId = null, runIds = null, kinds = null, limit = null } = {}) {
|
|
453
|
-
open();
|
|
454
|
-
const where = ['seq > ?'];
|
|
455
|
-
const args = [seqOf(afterSeq)];
|
|
456
|
-
for (const [column, value, field] of [['team_id', teamId, 'teamId'], ['session_id', sessionId, 'sessionId'], ['run_id', runId, 'runId']]) {
|
|
457
|
-
const wanted = idText(value, field);
|
|
458
|
-
if (wanted !== null) { where.push(`${column} = ?`); args.push(wanted); }
|
|
459
|
-
}
|
|
460
|
-
// Several runs at once (a workflow's wait): an empty list matches nothing.
|
|
461
|
-
if (runIds !== null && runIds !== undefined) {
|
|
462
|
-
const runs = [...new Set((Array.isArray(runIds) ? runIds : [runIds]).map((id) => idText(id, 'runIds', { required: true })))];
|
|
463
|
-
if (!runs.length) return [];
|
|
464
|
-
if (runs.length > COORDINATION_LIMITS.runIds) throw fail('FIELD_INVALID', `runIds names at most ${COORDINATION_LIMITS.runIds} runs.`, { field: 'runIds' });
|
|
465
|
-
where.push(`run_id IN (${runs.map(() => '?').join(', ')})`);
|
|
466
|
-
args.push(...runs);
|
|
467
|
-
}
|
|
468
|
-
const list = kindList(kinds);
|
|
469
|
-
if (list) { where.push(`kind IN (${list.map(() => '?').join(', ')})`); args.push(...list); }
|
|
470
|
-
return db.prepare(`SELECT * FROM events WHERE ${where.join(' AND ')} ORDER BY seq ASC LIMIT ?`).all(...args, limitOf(limit)).map(eventView);
|
|
471
|
-
}
|
|
472
|
-
|
|
473
|
-
// ββ the mailbox: deliveries, acknowledgements, the cursor ββββββββββββββββββ
|
|
474
|
-
const selectCursor = db.prepare('SELECT seq FROM cursors WHERE recipient = ?');
|
|
475
|
-
const selectOpenFloor = db.prepare('SELECT MIN(seq) AS seq FROM deliveries WHERE recipient = ? AND acked_at IS NULL');
|
|
476
|
-
const selectCeiling = db.prepare('SELECT MAX(seq) AS seq FROM deliveries WHERE recipient = ?');
|
|
477
|
-
const upsertCursor = db.prepare('INSERT INTO cursors (recipient, seq, updated_at) VALUES (?, ?, ?) ON CONFLICT (recipient) DO UPDATE SET seq = excluded.seq, updated_at = excluded.updated_at');
|
|
478
|
-
const markDelivered = db.prepare('UPDATE deliveries SET delivered_at = COALESCE(delivered_at, ?), attempts = attempts + 1 WHERE recipient = ? AND event_id = ?');
|
|
479
|
-
const ackOne = db.prepare('UPDATE deliveries SET acked_at = ? WHERE recipient = ? AND event_id = ? AND acked_at IS NULL');
|
|
480
|
-
const ackUpTo = db.prepare('UPDATE deliveries SET acked_at = ? WHERE recipient = ? AND seq <= ? AND acked_at IS NULL');
|
|
481
|
-
|
|
482
|
-
/** The seq up to which everything addressed to the recipient is acknowledged (0: nothing yet). */
|
|
483
|
-
function cursor(recipient) {
|
|
484
|
-
open();
|
|
485
|
-
return Number(selectCursor.get(recipientText(recipient))?.seq) || 0;
|
|
486
|
-
}
|
|
487
|
-
/**
|
|
488
|
-
* How many events a recipient has not acknowledged (nothing is handed out or recorded).
|
|
489
|
-
* @param {string} recipient
|
|
490
|
-
* @param {{ kinds?: string|string[], priority?: string|string[] }} [options]
|
|
491
|
-
*/
|
|
492
|
-
function openCount(recipient, { kinds = null, priority = null } = {}) {
|
|
493
|
-
open();
|
|
494
|
-
const who = recipientText(recipient);
|
|
495
|
-
const list = kindList(kinds);
|
|
496
|
-
const levels = priority === null || priority === undefined ? null : (Array.isArray(priority) ? priority : [priority]).map((level) => String(level));
|
|
497
|
-
if (levels) for (const level of levels) if (!EVENT_PRIORITIES.includes(level)) throw fail('PRIORITY_INVALID', `priority must be one of ${EVENT_PRIORITIES.join(', ')}.`, { field: 'priority' });
|
|
498
|
-
if (!list && !levels) return Number(db.prepare('SELECT COUNT(*) AS n FROM deliveries WHERE recipient = ? AND acked_at IS NULL').get(who)?.n) || 0;
|
|
499
|
-
const where = ['d.recipient = ?', 'd.acked_at IS NULL'];
|
|
500
|
-
const args = [who];
|
|
501
|
-
if (list) { where.push(`e.kind IN (${list.map(() => '?').join(', ')})`); args.push(...list); }
|
|
502
|
-
if (levels) { where.push(`e.priority IN (${levels.map(() => '?').join(', ')})`); args.push(...levels); }
|
|
503
|
-
return Number(db.prepare(`SELECT COUNT(*) AS n FROM deliveries d JOIN events e ON e.id = d.event_id WHERE ${where.join(' AND ')}`).get(...args)?.n) || 0;
|
|
504
|
-
}
|
|
505
|
-
/**
|
|
506
|
-
* The recipients that have something open, with how many (after a restart: whose mailbox still holds events).
|
|
507
|
-
* @param {{ prefix?: string }} [query] `prefix`: only names that start with it ("session:")
|
|
508
|
-
* @returns {{ recipient: string, open: number, oldestSeq: number }[]}
|
|
509
|
-
*/
|
|
510
|
-
function recipients({ prefix = null } = {}) {
|
|
511
|
-
open();
|
|
512
|
-
const rows = db.prepare('SELECT recipient, COUNT(*) AS n, MIN(seq) AS seq FROM deliveries WHERE acked_at IS NULL GROUP BY recipient ORDER BY MIN(seq) ASC').all();
|
|
513
|
-
const start = prefix === null || prefix === undefined ? '' : String(prefix);
|
|
514
|
-
return rows.filter((row) => !start || String(row.recipient).startsWith(start)).map((row) => ({ recipient: row.recipient, open: Number(row.n) || 0, oldestSeq: Number(row.seq) || 0 }));
|
|
515
|
-
}
|
|
516
|
-
/** After acknowledgements: the cursor is just below the oldest event still open, or at the newest when none is. */
|
|
517
|
-
function settleCursor(recipient) {
|
|
518
|
-
const floor = selectOpenFloor.get(recipient)?.seq;
|
|
519
|
-
const next = floor === null || floor === undefined ? (Number(selectCeiling.get(recipient)?.seq) || 0) : Number(floor) - 1;
|
|
520
|
-
const current = Number(selectCursor.get(recipient)?.seq) || 0;
|
|
521
|
-
// Deliveries are only ever added above every earlier one, so the cursor never has a reason to move back.
|
|
522
|
-
const seq = Math.max(current, next);
|
|
523
|
-
if (seq !== current || !selectCursor.get(recipient)) upsertCursor.run(recipient, seq, now());
|
|
524
|
-
return seq;
|
|
525
|
-
}
|
|
526
|
-
|
|
527
|
-
function handOut(rows, recipient, peek) {
|
|
528
|
-
if (!peek && rows.length) {
|
|
529
|
-
const at = now();
|
|
530
|
-
for (const row of rows) {
|
|
531
|
-
markDelivered.run(at, recipient, row.id);
|
|
532
|
-
row.delivered_at = row.delivered_at ?? at;
|
|
533
|
-
row.attempts = (Number(row.attempts) || 0) + 1;
|
|
18
|
+
if (!path || typeof path !== 'string') throw new CoordinationError('PATH_REQUIRED', 'createCoordinationStore needs its database path.');
|
|
19
|
+
if (migrations !== MIGRATIONS) throw new CoordinationError('MIGRATIONS_INVALID', 'Custom migration functions must run in the storage worker. Add the version to MIGRATIONS.');
|
|
20
|
+
const pending = new Map(), subscribers = new Set();
|
|
21
|
+
const mailboxes = new Map(), outboxes = new Map(), claims = new Map();
|
|
22
|
+
let worker, generationReady, closePromise, openError, barrier, degraded = null, schemaVersion;
|
|
23
|
+
let initialized = false, online = false, closed = false, id = 0, referenced = 0;
|
|
24
|
+
const lockBudget = Number.isFinite(busyTimeoutMs) ? Math.max(0, busyTimeoutMs) : 5000;
|
|
25
|
+
function releaseRef(op) {
|
|
26
|
+
if (op !== 'waitFor' && --referenced === 0) worker.unref();
|
|
27
|
+
}
|
|
28
|
+
function report(tag, detail) { try { log(tag, detail); } catch { /* best effort */ } }
|
|
29
|
+
function count(map, key, n) { if (n) map.set(key, n); else map.delete(key); }
|
|
30
|
+
|
|
31
|
+
function receive(message) {
|
|
32
|
+
if (message.log) return report(message.log.tag, message.log.detail);
|
|
33
|
+
if (message.notice) {
|
|
34
|
+
const { event, recipients } = message.notice;
|
|
35
|
+
for (const r of recipients) if (r.startsWith('session:')) count(mailboxes, r, (mailboxes.get(r) || 0) + 1);
|
|
36
|
+
for (const sub of [...subscribers]) {
|
|
37
|
+
if (!subscribers.has(sub)) continue;
|
|
38
|
+
try {
|
|
39
|
+
const f = sub.filter;
|
|
40
|
+
const info = { recipients: [...recipients] };
|
|
41
|
+
const match = !f || (typeof f === 'function' ? f(event, info) :
|
|
42
|
+
(!f.recipient || recipients.includes(f.recipient)) &&
|
|
43
|
+
['kinds', 'priority', 'teamId', 'sessionId', 'runId'].every(k => f[k] == null || [f[k]].flat().includes(event[k === 'kinds' ? 'kind' : k])));
|
|
44
|
+
if (match) sub.fn(event, info);
|
|
45
|
+
} catch (error) { report('coordination:subscriber-error', error.message); }
|
|
534
46
|
}
|
|
47
|
+
return;
|
|
535
48
|
}
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
* A recipient's events after a position, oldest first: the cursor read.
|
|
543
|
-
* By default from the recipient's cursor and only what it has not acknowledged, so a consumer that starts again
|
|
544
|
-
* (a restart, a new turn) gets every open event once more. Handing an event out records `deliveredAt` and counts
|
|
545
|
-
* an attempt; it acknowledges nothing.
|
|
546
|
-
* @param {object} query
|
|
547
|
-
* @param {string} query.recipient
|
|
548
|
-
* @param {number} [query.afterSeq] default: the recipient's cursor
|
|
549
|
-
* @param {string|string[]} [query.kinds]
|
|
550
|
-
* @param {number} [query.limit] default 100, at most 1000
|
|
551
|
-
* @param {boolean} [query.includeAcked] also what was acknowledged (a history view)
|
|
552
|
-
* @param {boolean} [query.peek] look without recording a delivery
|
|
553
|
-
*/
|
|
554
|
-
function read({ recipient, afterSeq = null, kinds = null, limit = null, includeAcked = false, peek = false } = {}) {
|
|
555
|
-
const who = recipientText(recipient);
|
|
556
|
-
const list = kindList(kinds);
|
|
557
|
-
const max = limitOf(limit);
|
|
558
|
-
return transaction(() => {
|
|
559
|
-
const from = afterSeq === null || afterSeq === undefined ? (Number(selectCursor.get(who)?.seq) || 0) : seqOf(afterSeq);
|
|
560
|
-
const where = ['d.recipient = ?', 'd.seq > ?'];
|
|
561
|
-
const args = [who, from];
|
|
562
|
-
if (!includeAcked) where.push('d.acked_at IS NULL');
|
|
563
|
-
if (list) { where.push(`e.kind IN (${list.map(() => '?').join(', ')})`); args.push(...list); }
|
|
564
|
-
const rows = db.prepare(`SELECT ${DELIVERY_COLUMNS} FROM deliveries d JOIN events e ON e.id = d.event_id WHERE ${where.join(' AND ')} ORDER BY d.seq ASC LIMIT ?`).all(...args, max);
|
|
565
|
-
// An acknowledged event shown as history is not handed out again.
|
|
566
|
-
return includeAcked ? rows.map(deliveryView) : handOut(rows, who, peek);
|
|
567
|
-
});
|
|
568
|
-
}
|
|
569
|
-
|
|
570
|
-
/**
|
|
571
|
-
* Everything a recipient has not acknowledged, in the order to deal with it: critical events first, then the rest,
|
|
572
|
-
* each group oldest first. This is what a turn is composed from; like `read` it records the delivery.
|
|
573
|
-
* @param {string} recipient
|
|
574
|
-
* @param {object} [options]
|
|
575
|
-
* @param {string|string[]} [options.kinds]
|
|
576
|
-
* @param {number} [options.limit] default 100, at most 1000
|
|
577
|
-
* @param {boolean} [options.peek] look without recording a delivery
|
|
578
|
-
* @param {boolean} [options.coalesce] merge low-priority events first (`coalesce`)
|
|
579
|
-
*/
|
|
580
|
-
function pending(recipient, { kinds = null, limit = null, peek = false, coalesce: merge = false } = {}) {
|
|
581
|
-
const who = recipientText(recipient);
|
|
582
|
-
const list = kindList(kinds);
|
|
583
|
-
const max = limitOf(limit);
|
|
584
|
-
return transaction(() => {
|
|
585
|
-
if (merge) coalesce(who);
|
|
586
|
-
const where = ['d.recipient = ?', 'd.acked_at IS NULL'];
|
|
587
|
-
const args = [who];
|
|
588
|
-
if (list) { where.push(`e.kind IN (${list.map(() => '?').join(', ')})`); args.push(...list); }
|
|
589
|
-
const rows = db.prepare(`SELECT ${DELIVERY_COLUMNS} FROM deliveries d JOIN events e ON e.id = d.event_id WHERE ${where.join(' AND ')} ORDER BY (e.priority = 'critical') DESC, d.seq ASC LIMIT ?`).all(...args, max);
|
|
590
|
-
return handOut(rows, who, peek);
|
|
591
|
-
});
|
|
592
|
-
}
|
|
593
|
-
|
|
594
|
-
/**
|
|
595
|
-
* The recipient dealt with these events: they are not handed out again. Ids it was never sent, or already
|
|
596
|
-
* acknowledged, are skipped, so acknowledging twice is harmless.
|
|
597
|
-
* @returns {{ acked: number, cursor: number }}
|
|
598
|
-
*/
|
|
599
|
-
function ack(recipient, eventIds) {
|
|
600
|
-
const who = recipientText(recipient);
|
|
601
|
-
const ids = (Array.isArray(eventIds) ? eventIds : [eventIds]).filter((id) => id !== null && id !== undefined).map((id) => String(id));
|
|
602
|
-
return transaction(() => {
|
|
603
|
-
const at = now();
|
|
604
|
-
let acked = 0;
|
|
605
|
-
for (const id of new Set(ids)) acked += Number(ackOne.run(at, who, id).changes) || 0;
|
|
606
|
-
return { acked, cursor: settleCursor(who) };
|
|
607
|
-
});
|
|
608
|
-
}
|
|
609
|
-
|
|
610
|
-
/** Acknowledge everything addressed to the recipient up to and including `seq`. */
|
|
611
|
-
function ackThrough(recipient, seq) {
|
|
612
|
-
const who = recipientText(recipient);
|
|
613
|
-
const upTo = seqOf(seq, 'seq');
|
|
614
|
-
return transaction(() => {
|
|
615
|
-
const acked = Number(ackUpTo.run(now(), who, upTo).changes) || 0;
|
|
616
|
-
return { acked, cursor: settleCursor(who) };
|
|
617
|
-
});
|
|
618
|
-
}
|
|
619
|
-
|
|
620
|
-
/**
|
|
621
|
-
* Fold a recipient's open low-priority events: of every group that says the same kind of thing (same
|
|
622
|
-
* `coalesceKey`, else same kind, run, team and session) only the newest stays open, and it says how many it stands
|
|
623
|
-
* for (`delivery.merged`). The older ones are settled, not deleted: the log keeps them. Critical and normal events
|
|
624
|
-
* are never touched.
|
|
625
|
-
* @returns {{ merged: number, kept: { id: string, seq: number, merged: number }[] }}
|
|
626
|
-
*/
|
|
627
|
-
function coalesce(recipient) {
|
|
628
|
-
const who = recipientText(recipient);
|
|
629
|
-
return transaction(() => {
|
|
630
|
-
const rows = db.prepare(`SELECT d.event_id, d.seq, d.merged, e.kind, e.run_id, e.team_id, e.session_id, e.coalesce_key
|
|
631
|
-
FROM deliveries d JOIN events e ON e.id = d.event_id
|
|
632
|
-
WHERE d.recipient = ? AND d.acked_at IS NULL AND e.priority = 'low' ORDER BY d.seq ASC`).all(who);
|
|
633
|
-
const groups = new Map();
|
|
634
|
-
for (const row of rows) {
|
|
635
|
-
const key = row.coalesce_key !== null && row.coalesce_key !== undefined
|
|
636
|
-
? `key\u0000${row.coalesce_key}`
|
|
637
|
-
: ['kind', row.kind, row.run_id ?? '', row.team_id ?? '', row.session_id ?? ''].join('\u0000');
|
|
638
|
-
if (!groups.has(key)) groups.set(key, []);
|
|
639
|
-
groups.get(key).push(row);
|
|
640
|
-
}
|
|
641
|
-
const settle = db.prepare('UPDATE deliveries SET acked_at = ?, coalesced_into = ? WHERE recipient = ? AND event_id = ? AND acked_at IS NULL');
|
|
642
|
-
const grow = db.prepare('UPDATE deliveries SET merged = merged + ? WHERE recipient = ? AND event_id = ?');
|
|
643
|
-
const at = now();
|
|
644
|
-
let merged = 0;
|
|
645
|
-
const kept = [];
|
|
646
|
-
for (const group of groups.values()) {
|
|
647
|
-
if (group.length < 2) continue;
|
|
648
|
-
const newest = group[group.length - 1];
|
|
649
|
-
let folded = 0;
|
|
650
|
-
for (const older of group.slice(0, -1)) {
|
|
651
|
-
settle.run(at, newest.event_id, who, older.event_id);
|
|
652
|
-
folded += 1 + (Number(older.merged) || 0);
|
|
653
|
-
}
|
|
654
|
-
grow.run(folded, who, newest.event_id);
|
|
655
|
-
merged += group.length - 1;
|
|
656
|
-
kept.push({ id: newest.event_id, seq: Number(newest.seq), merged: (Number(newest.merged) || 0) + folded });
|
|
657
|
-
}
|
|
658
|
-
if (merged) settleCursor(who);
|
|
659
|
-
return { merged, kept };
|
|
660
|
-
});
|
|
661
|
-
}
|
|
662
|
-
|
|
663
|
-
// ββ wake-ups βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
664
|
-
function matchesFilter(filter, notice) {
|
|
665
|
-
if (typeof filter === 'function') return !!filter(notice.event, { recipients: notice.recipients });
|
|
666
|
-
if (!filter) return true;
|
|
667
|
-
const { event, recipients } = notice;
|
|
668
|
-
const among = (wanted, value) => (Array.isArray(wanted) ? wanted.includes(value) : wanted === value);
|
|
669
|
-
if (filter.recipient !== undefined && filter.recipient !== null && !recipients.includes(filter.recipient)) return false;
|
|
670
|
-
if (filter.kinds !== undefined && filter.kinds !== null && !among(filter.kinds, event.kind)) return false;
|
|
671
|
-
if (filter.priority !== undefined && filter.priority !== null && !among(filter.priority, event.priority)) return false;
|
|
672
|
-
for (const field of ['teamId', 'sessionId', 'runId']) {
|
|
673
|
-
if (filter[field] !== undefined && filter[field] !== null && filter[field] !== event[field]) return false;
|
|
49
|
+
if (message.update) {
|
|
50
|
+
const u = message.update;
|
|
51
|
+
if (u.mailbox) count(mailboxes, ...u.mailbox);
|
|
52
|
+
if (u.claims) { const [team, rows] = u.claims; if (rows.length) claims.set(team, rows); else claims.delete(team); }
|
|
53
|
+
for (const [key, n] of u.outboxes || []) count(outboxes, key, n);
|
|
54
|
+
return;
|
|
674
55
|
}
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
for (const
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
catch (error) { try { log('coordination:subscriber-error', error?.message || String(error)); } catch { /* a logger must not stop delivery */ } }
|
|
693
|
-
}
|
|
694
|
-
for (const waiter of [...waiters]) {
|
|
695
|
-
if (!waiters.has(waiter)) continue;
|
|
696
|
-
try { if (waiter.matches(next)) waiter.wake(); }
|
|
697
|
-
catch (error) { waiter.finish(null, error); }
|
|
698
|
-
}
|
|
56
|
+
const req = pending.get(message.id);
|
|
57
|
+
if (!req) return;
|
|
58
|
+
pending.delete(message.id);
|
|
59
|
+
releaseRef(req.op);
|
|
60
|
+
if (message.error) {
|
|
61
|
+
const error = new CoordinationError(message.error.code, message.error.message, message.error);
|
|
62
|
+
if (req.op === 'open') openError = error;
|
|
63
|
+
req.reject(error);
|
|
64
|
+
} else {
|
|
65
|
+
if (req.op === 'open') {
|
|
66
|
+
const data = message.value;
|
|
67
|
+
initialized = online = true;
|
|
68
|
+
degraded = data.degraded;
|
|
69
|
+
schemaVersion = data.schemaVersion;
|
|
70
|
+
for (const row of data.mailboxes) count(mailboxes, row.recipient, row.open);
|
|
71
|
+
for (const [key, n] of data.outboxes) count(outboxes, key, n);
|
|
72
|
+
for (const [key, rows] of data.claims) claims.set(key, rows);
|
|
699
73
|
}
|
|
700
|
-
|
|
701
|
-
publishing = false;
|
|
74
|
+
req.resolve(req.op === 'open' ? undefined : message.value);
|
|
702
75
|
}
|
|
703
76
|
}
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
open();
|
|
716
|
-
if (typeof fn !== 'function') throw fail('SUBSCRIBER_INVALID', 'subscribe needs a function to call.');
|
|
717
|
-
if (isObject(filter) && filter.kinds !== undefined && filter.kinds !== null) kindList(filter.kinds);
|
|
718
|
-
const subscriber = { filter: filter ?? null, fn };
|
|
719
|
-
subscribers.add(subscriber);
|
|
720
|
-
return () => { subscribers.delete(subscriber); };
|
|
721
|
-
}
|
|
722
|
-
|
|
723
|
-
/**
|
|
724
|
-
* Wait until there is something to read, then read it.
|
|
725
|
-
* With `recipient`: the mailbox, like `read` (open events after `afterSeq`, default the cursor). Without one: the
|
|
726
|
-
* log, like `events` (events after `afterSeq`, default the newest now, so only what comes).
|
|
727
|
-
* Resolves at once when something is there already. Never rejects for a timeout: `timedOut: true` and no events.
|
|
728
|
-
* @param {object} query
|
|
729
|
-
* @param {string} [query.recipient]
|
|
730
|
-
* @param {string|string[]} [query.kinds]
|
|
731
|
-
* @param {number} [query.afterSeq]
|
|
732
|
-
* @param {number} [query.timeoutMs] default 30 s, at most 10 minutes; 0 only looks
|
|
733
|
-
* @param {number} [query.limit]
|
|
734
|
-
* @param {string} [query.teamId] the log only
|
|
735
|
-
* @param {string} [query.sessionId] the log only
|
|
736
|
-
* @param {string} [query.runId] the log only
|
|
737
|
-
* @param {AbortSignal} [query.signal] give up early (`aborted: true`)
|
|
738
|
-
* @param {number} [query.pollMs] also look every so often: only for a file another process appends to, which
|
|
739
|
-
* cannot wake this one
|
|
740
|
-
* @returns {Promise<{ events: object[], timedOut: boolean, closed: boolean, aborted: boolean }>}
|
|
741
|
-
*/
|
|
742
|
-
function waitFor({ recipient = null, kinds = null, afterSeq = null, timeoutMs = COORDINATION_LIMITS.defaultWaitMs, limit = null, teamId = null, sessionId = null, runId = null, signal = null, pollMs = null } = {}) {
|
|
743
|
-
const answer = (events_, extra = {}) => ({ events: events_, timedOut: false, closed: false, aborted: false, ...extra });
|
|
744
|
-
let look;
|
|
745
|
-
let matches;
|
|
746
|
-
try {
|
|
747
|
-
if (closed) return Promise.resolve(answer([], { closed: true }));
|
|
748
|
-
const list = kindList(kinds);
|
|
749
|
-
if (recipient !== null && recipient !== undefined) {
|
|
750
|
-
const who = recipientText(recipient);
|
|
751
|
-
const from = afterSeq === null || afterSeq === undefined ? cursor(who) : seqOf(afterSeq);
|
|
752
|
-
look = () => read({ recipient: who, afterSeq: from, kinds: list, limit });
|
|
753
|
-
matches = (notice) => notice.event.seq > from && notice.recipients.includes(who) && (!list || list.includes(notice.event.kind));
|
|
754
|
-
} else {
|
|
755
|
-
const from = afterSeq === null || afterSeq === undefined ? lastSeq() : seqOf(afterSeq);
|
|
756
|
-
const scope = { teamId: idText(teamId, 'teamId'), sessionId: idText(sessionId, 'sessionId'), runId: idText(runId, 'runId') };
|
|
757
|
-
look = () => events({ afterSeq: from, kinds: list, limit, ...scope });
|
|
758
|
-
matches = (notice) => notice.event.seq > from && (!list || list.includes(notice.event.kind))
|
|
759
|
-
&& Object.entries(scope).every(([field, value]) => value === null || notice.event[field] === value);
|
|
760
|
-
}
|
|
761
|
-
const first = look();
|
|
762
|
-
if (first.length) return Promise.resolve(answer(first));
|
|
763
|
-
} catch (error) {
|
|
764
|
-
return Promise.reject(error);
|
|
765
|
-
}
|
|
766
|
-
const asked = Number(timeoutMs);
|
|
767
|
-
const budget = Math.max(0, Math.min(COORDINATION_LIMITS.maxWaitMs, Number.isFinite(asked) ? asked : COORDINATION_LIMITS.defaultWaitMs));
|
|
768
|
-
if (budget === 0) return Promise.resolve(answer([], { timedOut: true }));
|
|
769
|
-
if (signal?.aborted) return Promise.resolve(answer([], { aborted: true }));
|
|
770
|
-
return new Promise((resolveWait, rejectWait) => {
|
|
771
|
-
let timer = null;
|
|
772
|
-
let poll = null;
|
|
773
|
-
const onAbort = () => waiter.finish(answer([], { aborted: true }));
|
|
774
|
-
const waiter = {
|
|
775
|
-
matches,
|
|
776
|
-
wake() {
|
|
777
|
-
const found = look();
|
|
778
|
-
if (found.length) waiter.finish(answer(found));
|
|
779
|
-
},
|
|
780
|
-
finish(result, error = null) {
|
|
781
|
-
if (!waiters.delete(waiter)) return;
|
|
782
|
-
if (timer) clearTimeout(timer);
|
|
783
|
-
if (poll) clearInterval(poll);
|
|
784
|
-
signal?.removeEventListener?.('abort', onAbort);
|
|
785
|
-
if (error) rejectWait(error); else resolveWait(result);
|
|
786
|
-
},
|
|
787
|
-
};
|
|
788
|
-
waiters.add(waiter);
|
|
789
|
-
// A wait is never what keeps a process alive (a server that is going down, a script that is done): its timers
|
|
790
|
-
// are unreferenced, as the dispatcher's own waits are (lib/assistant-run-wait.js). `close()` answers it.
|
|
791
|
-
timer = setTimeout(() => waiter.finish(answer([], { timedOut: true })), budget);
|
|
792
|
-
timer.unref?.();
|
|
793
|
-
const every = Number(pollMs);
|
|
794
|
-
if (Number.isFinite(every) && every > 0) {
|
|
795
|
-
poll = setInterval(() => { try { waiter.wake(); } catch (error) { waiter.finish(null, error); } }, Math.max(20, every));
|
|
796
|
-
poll.unref?.();
|
|
77
|
+
function post(op, args, requestId = ++id) {
|
|
78
|
+
return new Promise((resolve, reject) => {
|
|
79
|
+
if (op !== 'waitFor' && referenced++ === 0) worker.ref();
|
|
80
|
+
pending.set(requestId, { op, resolve, reject });
|
|
81
|
+
try { worker.postMessage({ id: requestId, op, args, deadline: performance.now() + lockBudget, at: now === Date.now ? undefined : now() }); }
|
|
82
|
+
catch (error) {
|
|
83
|
+
pending.delete(requestId);
|
|
84
|
+
releaseRef(op);
|
|
85
|
+
reject(error.name === 'DataCloneError'
|
|
86
|
+
? new CoordinationError('PAYLOAD_INVALID', `Coordination ${op} requires serializable input: ${error.message}`)
|
|
87
|
+
: error);
|
|
797
88
|
}
|
|
798
|
-
signal?.addEventListener?.('abort', onAbort, { once: true });
|
|
799
89
|
});
|
|
800
90
|
}
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
* a pattern another slice of the team holds, nothing is written and the answer names every clash. The same slice
|
|
827
|
-
* claiming a pattern it already holds keeps the one claim (a later run of the slice takes it over).
|
|
828
|
-
* Patterns are owned paths (lib/teams/schema.js): project-relative, `*`, `?` and `**`, never outside the project.
|
|
829
|
-
* @param {object} input
|
|
830
|
-
* @param {string} input.teamId
|
|
831
|
-
* @param {string} input.sliceId
|
|
832
|
-
* @param {string} [input.runId] the run that works the slice now
|
|
833
|
-
* @param {string|string[]} input.globs
|
|
834
|
-
* @returns {{ ok: true, claims: object[] } | { ok: false, code: 'CLAIM_CONFLICT', conflicts: { glob: string, heldBy: object }[] }}
|
|
835
|
-
* @throws {CoordinationError} `CLAIM_INVALID` for a pattern that is not an owned path
|
|
836
|
-
*/
|
|
837
|
-
function claim({ teamId, sliceId, runId = null, globs } = {}) {
|
|
838
|
-
const team = slugText(teamId, 'teamId');
|
|
839
|
-
const slice = slugText(sliceId, 'sliceId');
|
|
840
|
-
const run = idText(runId, 'runId');
|
|
841
|
-
const list = globList(globs);
|
|
842
|
-
return transaction(() => {
|
|
843
|
-
const active = selectActiveClaims.all(team);
|
|
844
|
-
const conflicts = [];
|
|
845
|
-
for (const glob of list) {
|
|
846
|
-
for (const row of active) {
|
|
847
|
-
if (row.slice_id !== slice && globsOverlap(glob, row.glob)) conflicts.push({ glob, heldBy: claimView(row) });
|
|
91
|
+
function start() {
|
|
92
|
+
const instance = createWorker(workerURL, { workerData: {
|
|
93
|
+
coordinationStorage: true, path: degraded ? ':memory:' : path, synchronous, limits, allowDegraded: allowDegraded && !initialized,
|
|
94
|
+
busyTimeoutMs: lockBudget,
|
|
95
|
+
}, execArgv: process.execArgv.filter(arg => arg === '--experimental-sqlite') });
|
|
96
|
+
worker = instance;
|
|
97
|
+
instance.on('message', receive);
|
|
98
|
+
let cause;
|
|
99
|
+
instance.once('error', err => { cause = err; });
|
|
100
|
+
instance.once('exit', code => {
|
|
101
|
+
if (worker !== instance) return;
|
|
102
|
+
const reopen = online;
|
|
103
|
+
worker = null;
|
|
104
|
+
referenced = 0;
|
|
105
|
+
online = false;
|
|
106
|
+
const error = unavailable('WORKER_EXIT', `Coordination worker exited (${cause?.message || code}); outstanding commits are unconfirmed. Check durable IDs before retrying.`);
|
|
107
|
+
for (const req of pending.values()) req.reject(error);
|
|
108
|
+
pending.clear();
|
|
109
|
+
claims.clear(); mailboxes.clear(); outboxes.clear();
|
|
110
|
+
if (!closed) {
|
|
111
|
+
report('coordination:worker-exit', error.message);
|
|
112
|
+
// A disk connection can be reopened. A lost in-memory store cannot be recovered.
|
|
113
|
+
if (initialized && (path === ':memory:' || degraded)) openError = error;
|
|
114
|
+
else if (reopen) {
|
|
115
|
+
try { start(); } catch (err) { report('coordination:worker-start-error', err.message); }
|
|
848
116
|
}
|
|
849
117
|
}
|
|
850
|
-
if (conflicts.length) return { ok: false, code: 'CLAIM_CONFLICT', conflicts };
|
|
851
|
-
const at = now();
|
|
852
|
-
const claims = list.map((glob) => {
|
|
853
|
-
const mine = active.find((row) => row.slice_id === slice && row.glob === glob);
|
|
854
|
-
if (mine) {
|
|
855
|
-
if (run && mine.run_id !== run) { moveClaim.run(run, mine.id); mine.run_id = run; }
|
|
856
|
-
return claimView(mine);
|
|
857
|
-
}
|
|
858
|
-
const id = Number(insertClaim.run(team, slice, glob, run, at).lastInsertRowid);
|
|
859
|
-
return claimView({ id, team_id: team, slice_id: slice, glob, run_id: run, created_at: at, released_at: null });
|
|
860
|
-
});
|
|
861
|
-
return { ok: true, claims };
|
|
862
118
|
});
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
const run = idText(runId, 'runId');
|
|
874
|
-
if (run !== null) { where.push('run_id = ?'); args.push(run); }
|
|
875
|
-
const list = globList(globs, { required: false });
|
|
876
|
-
if (list && !list.length) return { released: 0 };
|
|
877
|
-
if (list) { where.push(`glob IN (${list.map(() => '?').join(', ')})`); args.push(...list); }
|
|
878
|
-
return transaction(() => ({ released: Number(db.prepare(`UPDATE claims SET released_at = ? WHERE ${where.join(' AND ')}`).run(now(), ...args).changes) || 0 }));
|
|
879
|
-
}
|
|
880
|
-
|
|
881
|
-
/**
|
|
882
|
-
* The claims of a team, oldest first. `path`: only those that hold this project-relative file ("who has it?").
|
|
883
|
-
* @param {object} query
|
|
884
|
-
* @param {string} query.teamId
|
|
885
|
-
* @param {string} [query.sliceId]
|
|
886
|
-
* @param {string} [query.runId]
|
|
887
|
-
* @param {string} [query.path]
|
|
888
|
-
* @param {boolean} [query.includeReleased] also claims given back (history)
|
|
889
|
-
*/
|
|
890
|
-
function claimsFor({ teamId, sliceId = null, runId = null, path = null, includeReleased = false } = {}) {
|
|
891
|
-
open();
|
|
892
|
-
const where = ['team_id = ?'];
|
|
893
|
-
const args = [slugText(teamId, 'teamId')];
|
|
894
|
-
if (!includeReleased) where.push('released_at IS NULL');
|
|
895
|
-
if (sliceId !== null && sliceId !== undefined) { where.push('slice_id = ?'); args.push(slugText(sliceId, 'sliceId')); }
|
|
896
|
-
const run = idText(runId, 'runId');
|
|
897
|
-
if (run !== null) { where.push('run_id = ?'); args.push(run); }
|
|
898
|
-
let rows = db.prepare(`SELECT * FROM claims WHERE ${where.join(' AND ')} ORDER BY id ASC`).all(...args);
|
|
899
|
-
if (path !== null && path !== undefined) {
|
|
900
|
-
const file = normalizeRelPath(path);
|
|
901
|
-
if (file === null) throw fail('FIELD_INVALID', 'path is a file path relative to the project.', { field: 'path' });
|
|
902
|
-
rows = rows.filter((row) => matchesOwnedPath(row.glob, file));
|
|
119
|
+
generationReady = post('open', []);
|
|
120
|
+
generationReady.catch(() => {}); // callers also observe this through ready and every operation
|
|
121
|
+
}
|
|
122
|
+
start();
|
|
123
|
+
function ensureWorker() {
|
|
124
|
+
if (!worker) start();
|
|
125
|
+
else if (openError?.code === 'SQLITE_BUSY') {
|
|
126
|
+
openError = null;
|
|
127
|
+
generationReady = post('open', []);
|
|
128
|
+
generationReady.catch(() => {});
|
|
903
129
|
}
|
|
904
|
-
return rows.map(claimView);
|
|
905
|
-
}
|
|
906
|
-
|
|
907
|
-
// ββ the journal of team tasks ββββββββββββββββββββββββββββββββββββββββββββββ
|
|
908
|
-
const insertJournal = db.prepare('INSERT INTO team_tasks (team_id, slice_id, state, run_id, data, created_at) VALUES (?, ?, ?, ?, ?, ?)');
|
|
909
|
-
|
|
910
|
-
function stateText(value) {
|
|
911
|
-
if (typeof value !== 'string' || !/^[a-z][a-z0-9_-]{0,39}$/.test(value)) throw fail('FIELD_INVALID', `state is a lower-case name of at most ${COORDINATION_LIMITS.state} characters, like "running".`, { field: 'state' });
|
|
912
|
-
return value;
|
|
913
130
|
}
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
/**
|
|
948
|
-
* Where a team stands: its own newest entry and the newest entry of each slice.
|
|
949
|
-
* @returns {{ teamId: string, team: object|null, slices: Record<string, object> }}
|
|
950
|
-
*/
|
|
951
|
-
state(teamId) {
|
|
952
|
-
open();
|
|
953
|
-
const rows = db.prepare('SELECT * FROM team_tasks WHERE id IN (SELECT MAX(id) FROM team_tasks WHERE team_id = ? GROUP BY slice_id) ORDER BY id ASC').all(slugText(teamId, 'teamId'));
|
|
954
|
-
const out = { teamId, team: null, slices: {} };
|
|
955
|
-
for (const row of rows) {
|
|
956
|
-
if (row.slice_id) out.slices[row.slice_id] = journalView(row);
|
|
957
|
-
else out.team = journalView(row);
|
|
131
|
+
function ordered(submit) {
|
|
132
|
+
if (closed) return Promise.reject(unavailable('CLOSED', 'The coordination store is closed.'));
|
|
133
|
+
if (openError && openError.code !== 'SQLITE_BUSY') return Promise.reject(openError);
|
|
134
|
+
ensureWorker();
|
|
135
|
+
const instance = worker;
|
|
136
|
+
const call = (op, args) => {
|
|
137
|
+
if (worker !== instance) return Promise.reject(unavailable('WORKER_EXIT', 'Coordination worker exited before submission.'));
|
|
138
|
+
markActivity(`coordination:${op}`);
|
|
139
|
+
return post(op, args);
|
|
140
|
+
};
|
|
141
|
+
return barrier ? barrier.then(() => submit(call)) : submit(call);
|
|
142
|
+
}
|
|
143
|
+
function request(op, args = []) {
|
|
144
|
+
// postMessage normally snapshots input immediately. A reserved discard
|
|
145
|
+
// delays posting, so take the same snapshot at submission in that case.
|
|
146
|
+
if (barrier) {
|
|
147
|
+
try { args = structuredClone(args); }
|
|
148
|
+
catch (error) { return Promise.reject(new CoordinationError('PAYLOAD_INVALID', error.message)); }
|
|
149
|
+
}
|
|
150
|
+
return ordered(call => call(op, args));
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// A mailbox predicate can depend on live dispatcher state. Reserve its FIFO
|
|
154
|
+
// position across the reads and acknowledgement, including during close.
|
|
155
|
+
function discard(recipient, match) {
|
|
156
|
+
const work = ordered(async call => {
|
|
157
|
+
let afterSeq = 0;
|
|
158
|
+
const ids = [];
|
|
159
|
+
for (;;) {
|
|
160
|
+
const page = await call('read', [{ recipient, afterSeq, limit: COORDINATION_LIMITS.readLimit, peek: true }]);
|
|
161
|
+
for (const event of page) if (match(event)) ids.push(event.id);
|
|
162
|
+
if (page.length < COORDINATION_LIMITS.readLimit) break;
|
|
163
|
+
afterSeq = page.at(-1).seq;
|
|
958
164
|
}
|
|
959
|
-
return
|
|
960
|
-
},
|
|
961
|
-
/**
|
|
962
|
-
* Every team the journal knows, by its own newest entry, oldest team first. `states`: only teams whose newest
|
|
963
|
-
* state is one of these (after a restart: the teams that were under way).
|
|
964
|
-
* @param {{ states?: string[] }} [query]
|
|
965
|
-
*/
|
|
966
|
-
teams({ states = null } = {}) {
|
|
967
|
-
open();
|
|
968
|
-
const rows = db.prepare("SELECT * FROM team_tasks WHERE id IN (SELECT MAX(id) FROM team_tasks WHERE slice_id = '' GROUP BY team_id) ORDER BY id ASC").all();
|
|
969
|
-
const wanted = Array.isArray(states) ? new Set(states) : null;
|
|
970
|
-
return rows.filter((row) => !wanted || wanted.has(row.state)).map(journalView);
|
|
971
|
-
},
|
|
972
|
-
});
|
|
973
|
-
|
|
974
|
-
// ββ the outbox: follow-ups for runs ββββββββββββββββββββββββββββββββββββββββ
|
|
975
|
-
const selectOutboxById = db.prepare('SELECT * FROM outbox WHERE id = ?');
|
|
976
|
-
const insertOutbox = db.prepare('INSERT INTO outbox (id, run_id, text, session_id, meta, created_at) VALUES (?, ?, ?, ?, ?, ?)');
|
|
977
|
-
const selectUnsent = db.prepare('SELECT * FROM outbox WHERE run_id = ? AND sent_at IS NULL ORDER BY n ASC LIMIT ?');
|
|
978
|
-
const countAttempt = db.prepare('UPDATE outbox SET attempts = attempts + 1 WHERE id = ?');
|
|
979
|
-
const markSent = db.prepare('UPDATE outbox SET sent_at = ? WHERE id = ? AND sent_at IS NULL');
|
|
980
|
-
const countUnsent = db.prepare('SELECT COUNT(*) AS n FROM outbox WHERE run_id = ? AND sent_at IS NULL');
|
|
981
|
-
const selectAllUnsent = db.prepare('SELECT * FROM outbox WHERE run_id = ? AND sent_at IS NULL ORDER BY n ASC');
|
|
982
|
-
const deleteUnsent = db.prepare('DELETE FROM outbox WHERE id = ? AND sent_at IS NULL');
|
|
983
|
-
|
|
984
|
-
const outbox = Object.freeze({
|
|
985
|
-
/**
|
|
986
|
-
* Queue a follow-up for a run. It stays queued until `markSent` says the run took it, across restarts.
|
|
987
|
-
* @param {{ id?: string, runId: string, text: string, sessionId?: string|null, meta?: object, maxQueued?: number }} item
|
|
988
|
-
* `id`: the caller's own; queueing it again stores nothing new (`duplicate: true`)
|
|
989
|
-
* `maxQueued`: the admission bound: with that many of the run's items still unsent, nothing is stored and
|
|
990
|
-
* `OUTBOX_FULL` (409, with `queued` and `limit`) is thrown
|
|
991
|
-
* @returns {{ id: string, duplicate: boolean }}
|
|
992
|
-
*/
|
|
993
|
-
enqueue({ id = null, runId, text, sessionId = null, meta = {}, maxQueued = null } = {}) {
|
|
994
|
-
const run = idText(runId, 'runId', { required: true });
|
|
995
|
-
if (typeof text !== 'string' || !text.trim()) throw fail('FIELD_REQUIRED', 'text is required: what the run is told.', { field: 'text' });
|
|
996
|
-
if (text.length > COORDINATION_LIMITS.outboxText) throw fail('FIELD_INVALID', `text is at most ${COORDINATION_LIMITS.outboxText} characters.`, { field: 'text' });
|
|
997
|
-
const session = idText(sessionId, 'sessionId');
|
|
998
|
-
if (!isObject(meta)) throw fail('FIELD_INVALID', 'meta is an object.', { field: 'meta' });
|
|
999
|
-
const body = jsonText(meta, 'meta', COORDINATION_LIMITS.journalDataBytes);
|
|
1000
|
-
const key = idText(id, 'id') || String(newId());
|
|
1001
|
-
const bound = maxQueued === null || maxQueued === undefined ? null : Math.floor(Number(maxQueued));
|
|
1002
|
-
if (bound !== null && (!Number.isFinite(bound) || bound < 1)) throw fail('FIELD_INVALID', 'maxQueued is a whole number from 1.', { field: 'maxQueued' });
|
|
1003
|
-
return transaction(() => {
|
|
1004
|
-
if (selectOutboxById.get(key)) return { id: key, duplicate: true };
|
|
1005
|
-
const queued = bound === null ? 0 : Number(countUnsent.get(run)?.n) || 0;
|
|
1006
|
-
if (bound !== null && queued >= bound) {
|
|
1007
|
-
throw fail('OUTBOX_FULL', `Run ${run} already has ${queued} follow-up${queued === 1 ? '' : 's'} waiting (at most ${bound}): wait until it took some, or send one message that says it all.`, { status: 409, runId: run, queued, limit: bound });
|
|
1008
|
-
}
|
|
1009
|
-
insertOutbox.run(key, run, text, session, body, now());
|
|
1010
|
-
return { id: key, duplicate: false };
|
|
1011
|
-
});
|
|
1012
|
-
},
|
|
1013
|
-
/** How many of a run's items are still unsent. */
|
|
1014
|
-
count(runId) {
|
|
1015
|
-
open();
|
|
1016
|
-
return Number(countUnsent.get(idText(runId, 'runId', { required: true }))?.n) || 0;
|
|
1017
|
-
},
|
|
1018
|
-
/**
|
|
1019
|
-
* Take unsent items out of the queue for good: the run ended, or was stopped, before it could take them. Sent
|
|
1020
|
-
* items are left alone. `ids` narrows it to those of the run's items.
|
|
1021
|
-
* @param {{ runId: string, ids?: string[] }} query
|
|
1022
|
-
* @returns {{ cancelled: object[] }} the items that were removed, in the order they were queued
|
|
1023
|
-
*/
|
|
1024
|
-
cancel({ runId, ids = null } = {}) {
|
|
1025
|
-
const run = idText(runId, 'runId', { required: true });
|
|
1026
|
-
const only = ids === null || ids === undefined ? null : new Set((Array.isArray(ids) ? ids : [ids]).map((id) => String(id)));
|
|
1027
|
-
return transaction(() => {
|
|
1028
|
-
const rows = selectAllUnsent.all(run).filter((row) => !only || only.has(row.id));
|
|
1029
|
-
for (const row of rows) deleteUnsent.run(row.id);
|
|
1030
|
-
return { cancelled: rows.map(outboxView) };
|
|
1031
|
-
});
|
|
1032
|
-
},
|
|
1033
|
-
/**
|
|
1034
|
-
* What is queued for a run and not sent yet, in the order it was queued. Taking marks nothing as sent: an item
|
|
1035
|
-
* comes back from every take until `markSent` names it (a crash between the two sends it again, never loses it).
|
|
1036
|
-
* @param {string} runId
|
|
1037
|
-
* @param {{ limit?: number }} [options]
|
|
1038
|
-
*/
|
|
1039
|
-
take(runId, { limit = null } = {}) {
|
|
1040
|
-
const run = idText(runId, 'runId', { required: true });
|
|
1041
|
-
return transaction(() => {
|
|
1042
|
-
const rows = selectUnsent.all(run, limitOf(limit));
|
|
1043
|
-
for (const row of rows) { countAttempt.run(row.id); row.attempts = (Number(row.attempts) || 0) + 1; }
|
|
1044
|
-
return rows.map(outboxView);
|
|
1045
|
-
});
|
|
1046
|
-
},
|
|
1047
|
-
/** These items reached their run. @returns {{ sent: number }} */
|
|
1048
|
-
markSent(ids) {
|
|
1049
|
-
const list = (Array.isArray(ids) ? ids : [ids]).filter((id) => id !== null && id !== undefined).map((id) => String(id));
|
|
1050
|
-
return transaction(() => {
|
|
1051
|
-
const at = now();
|
|
1052
|
-
let sent = 0;
|
|
1053
|
-
for (const id of new Set(list)) sent += Number(markSent.run(at, id).changes) || 0;
|
|
1054
|
-
return { sent };
|
|
1055
|
-
});
|
|
1056
|
-
},
|
|
1057
|
-
/** One item by its id, or null. */
|
|
1058
|
-
get(id) {
|
|
1059
|
-
open();
|
|
1060
|
-
const row = selectOutboxById.get(String(id));
|
|
1061
|
-
return row ? outboxView(row) : null;
|
|
1062
|
-
},
|
|
1063
|
-
/** The runs that have something queued (after a restart: who still has to be told something). */
|
|
1064
|
-
runs() {
|
|
1065
|
-
open();
|
|
1066
|
-
return db.prepare('SELECT run_id FROM outbox WHERE sent_at IS NULL GROUP BY run_id ORDER BY MIN(n) ASC').all().map((row) => row.run_id);
|
|
1067
|
-
},
|
|
1068
|
-
});
|
|
1069
|
-
|
|
1070
|
-
// ββ housekeeping βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
1071
|
-
/**
|
|
1072
|
-
* Drop what is settled and old: events older than `olderThanMs` whose every delivery is acknowledged (their
|
|
1073
|
-
* deliveries go with them), claims given back that long ago, outbox items sent that long ago. An event somebody
|
|
1074
|
-
* has not acknowledged is kept however old it is; the journal is never pruned.
|
|
1075
|
-
* @returns {{ events: number, claims: number, outbox: number }}
|
|
1076
|
-
*/
|
|
1077
|
-
function prune({ olderThanMs = 14 * 24 * 60 * 60 * 1000 } = {}) {
|
|
1078
|
-
const age = Number(olderThanMs);
|
|
1079
|
-
if (!Number.isFinite(age) || age < 0) throw fail('FIELD_INVALID', 'olderThanMs must be a number of milliseconds.', { field: 'olderThanMs' });
|
|
1080
|
-
return transaction(() => {
|
|
1081
|
-
const before = now() - age;
|
|
1082
|
-
return {
|
|
1083
|
-
events: Number(db.prepare('DELETE FROM events WHERE created_at < ? AND NOT EXISTS (SELECT 1 FROM deliveries d WHERE d.event_id = events.id AND d.acked_at IS NULL)').run(before).changes) || 0,
|
|
1084
|
-
claims: Number(db.prepare('DELETE FROM claims WHERE released_at IS NOT NULL AND released_at < ?').run(before).changes) || 0,
|
|
1085
|
-
outbox: Number(db.prepare('DELETE FROM outbox WHERE sent_at IS NOT NULL AND sent_at < ?').run(before).changes) || 0,
|
|
1086
|
-
};
|
|
165
|
+
return ids.length ? (await call('ack', [recipient, ids])).acked : 0;
|
|
1087
166
|
});
|
|
167
|
+
const settled = work.then(() => {}, () => {});
|
|
168
|
+
barrier = settled;
|
|
169
|
+
settled.then(() => { if (barrier === settled) barrier = null; });
|
|
170
|
+
return work;
|
|
1088
171
|
}
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
const
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
172
|
+
function subscribe(filter, fn) {
|
|
173
|
+
if (closed) throw unavailable('CLOSED', 'The coordination store is closed.');
|
|
174
|
+
if (typeof fn !== 'function') throw new CoordinationError('SUBSCRIBER_INVALID', 'subscribe needs a function to call.');
|
|
175
|
+
if (filter?.kinds != null && ![filter.kinds].flat().every(k => /^[a-z][a-z0-9_.:-]{0,63}$/.test(k))) throw new CoordinationError('KIND_INVALID', 'Invalid event kind.');
|
|
176
|
+
const sub = { filter, fn };
|
|
177
|
+
subscribers.add(sub);
|
|
178
|
+
return () => subscribers.delete(sub);
|
|
179
|
+
}
|
|
180
|
+
function waitFor({ signal, ...query } = {}) {
|
|
181
|
+
const empty = { events: [], timedOut: false, closed, aborted: !closed && !!signal?.aborted };
|
|
182
|
+
if (closed || signal?.aborted) return Promise.resolve(empty);
|
|
183
|
+
const instance = worker;
|
|
184
|
+
const requestId = ++id;
|
|
185
|
+
return ordered(() => {
|
|
186
|
+
if (instance && instance !== worker) throw unavailable('WORKER_EXIT', 'Coordination worker exited before wait.');
|
|
187
|
+
if (signal?.aborted) return { ...empty, aborted: true };
|
|
188
|
+
const owner = worker;
|
|
189
|
+
const result = post('waitFor', [query], requestId);
|
|
190
|
+
const abort = () => owner.postMessage({ abort: requestId });
|
|
191
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
192
|
+
return result.finally(() => signal?.removeEventListener('abort', abort));
|
|
193
|
+
});
|
|
1111
194
|
}
|
|
1112
|
-
|
|
1113
|
-
/**
|
|
1114
|
-
* Stop: everyone waiting is answered (`closed: true`), listeners are dropped and the file is closed. What was not
|
|
1115
|
-
* acknowledged stays in the file and is handed out again by the next store opened on it. Safe to call twice.
|
|
1116
|
-
*/
|
|
1117
195
|
function close() {
|
|
1118
|
-
if (
|
|
196
|
+
if (closePromise) return closePromise;
|
|
1119
197
|
closed = true;
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
198
|
+
const instance = worker;
|
|
199
|
+
let timer;
|
|
200
|
+
const drained = Promise.resolve(barrier).then(() => {
|
|
201
|
+
if (instance && instance !== worker) throw unavailable('WORKER_EXIT', 'Coordination worker exited during shutdown.');
|
|
202
|
+
if (instance) return post('close', []);
|
|
203
|
+
});
|
|
204
|
+
closePromise = Promise.race([
|
|
205
|
+
drained,
|
|
206
|
+
new Promise((_, reject) => {
|
|
207
|
+
timer = setTimeout(() => {
|
|
208
|
+
const error = unavailable('DRAIN_TIMEOUT', 'Coordination shutdown drain timed out; outstanding commits are unconfirmed.');
|
|
209
|
+
instance?.off('message', receive);
|
|
210
|
+
for (const req of pending.values()) req.reject(error);
|
|
211
|
+
pending.clear();
|
|
212
|
+
if (instance) {
|
|
213
|
+
// An OS I/O call can outlive the deadline. Release callers now.
|
|
214
|
+
worker = null;
|
|
215
|
+
instance.unref();
|
|
216
|
+
instance.terminate().catch(err => report('coordination:terminate-error', err.message));
|
|
217
|
+
}
|
|
218
|
+
reject(error);
|
|
219
|
+
}, shutdownTimeoutMs);
|
|
220
|
+
}),
|
|
221
|
+
]).finally(() => {
|
|
222
|
+
clearTimeout(timer);
|
|
223
|
+
subscribers.clear();
|
|
224
|
+
claims.clear(); mailboxes.clear(); outboxes.clear();
|
|
225
|
+
});
|
|
226
|
+
return closePromise;
|
|
1125
227
|
}
|
|
1126
|
-
|
|
228
|
+
const withId = input => newId && input && !input.id ? { ...input, id: newId() } : input;
|
|
1127
229
|
return Object.freeze({
|
|
1128
|
-
path,
|
|
1129
|
-
schemaVersion,
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
230
|
+
path, get ready() { return generationReady; }, get degraded() { return degraded; },
|
|
231
|
+
get closed() { return closed; }, get schemaVersion() { return schemaVersion; },
|
|
232
|
+
...methods('get events lastSeq read pending ack ackThrough cursor coalesce openCount recipients claim release claimsFor prune appliedMigrations', request),
|
|
233
|
+
append: event => request('append', [withId(event)]),
|
|
234
|
+
appendMany: events => request('appendMany', [newId && Array.isArray(events) ? events.map(withId) : events]),
|
|
235
|
+
journal: methods('write read state teams', (op, args) => request('journal.' + op, args)),
|
|
236
|
+
outbox: methods('enqueue count cancel take markSent get runs', (op, args) => request('outbox.' + op, op === 'enqueue' ? [withId(args[0])] : args)),
|
|
237
|
+
stats: async () => ({ ...await request('stats'), subscribers: subscribers.size }),
|
|
238
|
+
// The guard and scheduling predicates run synchronously. These projections
|
|
239
|
+
// reflect acknowledged worker changes and are rebuilt on connection open.
|
|
240
|
+
holdsClaim: (team, slice, file) => claims.get(team)?.some(row => row.sliceId === slice && matchesOwnedPath(row.glob, file)) || false,
|
|
241
|
+
mailboxCount: session => mailboxes.get('session:' + session) || 0,
|
|
242
|
+
outboxCount: run => online ? outboxes.get(run) || 0 : Infinity,
|
|
243
|
+
serviceRequest: (op, args) => request('service.' + op, args),
|
|
244
|
+
subscribe, waitFor, discard, close,
|
|
1137
245
|
});
|
|
1138
246
|
}
|