mayura 0.1.0-dev.0 → 1.0.0-rc.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/README.md +152 -35
- package/docs/README.md +82 -0
- package/docs/ai-agents.md +73 -0
- package/docs/cli/dev.md +111 -0
- package/docs/cli/init.md +192 -0
- package/docs/cli/operations.md +235 -0
- package/docs/cli/overview.md +129 -0
- package/docs/cli/run.md +182 -0
- package/docs/concepts/agent.md +197 -0
- package/docs/concepts/costs-and-budgets.md +177 -0
- package/docs/concepts/outcomes.md +154 -0
- package/docs/concepts/permissions.md +155 -0
- package/docs/concepts/runtime.md +172 -0
- package/docs/concepts/tools.md +202 -0
- package/docs/concepts/workflows.md +134 -0
- package/docs/guides/approvals-and-human-input.md +278 -0
- package/docs/guides/artifacts.md +123 -0
- package/docs/guides/child-agents.md +158 -0
- package/docs/guides/code-mode.md +233 -0
- package/docs/guides/deployment.md +644 -0
- package/docs/guides/durable-workflows.md +463 -0
- package/docs/guides/guardrails.md +205 -0
- package/docs/guides/helpers.md +176 -0
- package/docs/guides/lifecycle-hooks.md +187 -0
- package/docs/guides/mcp.md +123 -0
- package/docs/guides/memory-and-context.md +293 -0
- package/docs/guides/model-providers.md +371 -0
- package/docs/guides/model-routing.md +138 -0
- package/docs/guides/observability.md +238 -0
- package/docs/guides/operator-console.md +140 -0
- package/docs/guides/react.md +276 -0
- package/docs/guides/sagas-and-loops.md +212 -0
- package/docs/guides/server-and-client.md +559 -0
- package/docs/guides/skills.md +152 -0
- package/docs/guides/storage.md +251 -0
- package/docs/guides/streaming.md +146 -0
- package/docs/guides/terminal.md +166 -0
- package/docs/guides/testing.md +220 -0
- package/docs/guides/vision.md +155 -0
- package/docs/guides/webhooks.md +172 -0
- package/docs/guides/workflow-composition.md +141 -0
- package/docs/guides/workflow-operations.md +269 -0
- package/docs/installation.md +90 -0
- package/docs/introduction.md +74 -0
- package/docs/project/credits.md +78 -0
- package/docs/project/security.md +178 -0
- package/docs/project/support.md +91 -0
- package/docs/project/versioning.md +122 -0
- package/docs/quickstart.md +190 -0
- package/docs/reference/entry-points.md +146 -0
- package/lib/adapter-code-docker/dist/index.d.ts +8 -1
- package/lib/adapter-code-docker/dist/index.d.ts.map +1 -1
- package/lib/adapter-code-docker/dist/index.js +64 -67
- package/lib/adapter-code-docker/dist/index.js.map +1 -1
- package/lib/adapter-code-docker/dist/options.d.ts +15 -0
- package/lib/adapter-code-docker/dist/options.d.ts.map +1 -0
- package/lib/adapter-code-docker/dist/options.js +56 -0
- package/lib/adapter-code-docker/dist/options.js.map +1 -0
- package/lib/adapter-code-docker/image/Dockerfile +4 -2
- package/lib/adapter-code-docker/package.json +1 -1
- package/lib/adapter-code-docker/src/index.ts +63 -65
- package/lib/adapter-code-docker/src/options.ts +51 -0
- package/lib/adapter-code-quickjs/dist/index.d.ts +16 -4
- package/lib/adapter-code-quickjs/dist/index.d.ts.map +1 -1
- package/lib/adapter-code-quickjs/dist/index.js +94 -50
- package/lib/adapter-code-quickjs/dist/index.js.map +1 -1
- package/lib/adapter-code-quickjs/dist/worker-command.d.ts +27 -0
- package/lib/adapter-code-quickjs/dist/worker-command.d.ts.map +1 -0
- package/lib/adapter-code-quickjs/dist/worker-command.js +66 -0
- package/lib/adapter-code-quickjs/dist/worker-command.js.map +1 -0
- package/lib/adapter-code-quickjs/dist/worker.js +421 -104
- package/lib/adapter-code-quickjs/dist/worker.js.map +1 -1
- package/lib/adapter-code-quickjs/package.json +1 -1
- package/lib/adapter-code-quickjs/src/index.ts +88 -44
- package/lib/adapter-code-quickjs/src/worker-command.ts +68 -0
- package/lib/adapter-code-quickjs/src/worker.ts +315 -89
- package/lib/adapter-mcp/package.json +1 -1
- package/lib/artifacts/dist/contracts.d.ts +6 -2
- package/lib/artifacts/dist/contracts.d.ts.map +1 -1
- package/lib/artifacts/dist/contracts.js.map +1 -1
- package/lib/artifacts/dist/index.d.ts +1 -0
- package/lib/artifacts/dist/index.d.ts.map +1 -1
- package/lib/artifacts/dist/index.js +1 -0
- package/lib/artifacts/dist/index.js.map +1 -1
- package/lib/artifacts/dist/local-store.d.ts.map +1 -1
- package/lib/artifacts/dist/local-store.js +4 -7
- package/lib/artifacts/dist/local-store.js.map +1 -1
- package/lib/artifacts/dist/media.d.ts +11 -0
- package/lib/artifacts/dist/media.d.ts.map +1 -0
- package/lib/artifacts/dist/media.js +18 -0
- package/lib/artifacts/dist/media.js.map +1 -0
- package/lib/artifacts/package.json +1 -1
- package/lib/artifacts/src/contracts.ts +6 -2
- package/lib/artifacts/src/index.ts +1 -0
- package/lib/artifacts/src/local-store.ts +5 -7
- package/lib/artifacts/src/media.ts +20 -0
- package/lib/cli/dist/agent-guide.d.ts +10 -0
- package/lib/cli/dist/agent-guide.d.ts.map +1 -0
- package/lib/cli/dist/agent-guide.js +48 -0
- package/lib/cli/dist/agent-guide.js.map +1 -0
- package/lib/cli/dist/application.d.ts +24 -0
- package/lib/cli/dist/application.d.ts.map +1 -1
- package/lib/cli/dist/application.js +21 -0
- package/lib/cli/dist/application.js.map +1 -1
- package/lib/cli/dist/bin.js +26 -6
- package/lib/cli/dist/bin.js.map +1 -1
- package/lib/cli/dist/dev.d.ts.map +1 -1
- package/lib/cli/dist/dev.js +7 -1
- package/lib/cli/dist/dev.js.map +1 -1
- package/lib/cli/dist/index.d.ts +3 -3
- package/lib/cli/dist/index.d.ts.map +1 -1
- package/lib/cli/dist/index.js +19 -9
- package/lib/cli/dist/index.js.map +1 -1
- package/lib/cli/dist/interactive.d.ts.map +1 -1
- package/lib/cli/dist/interactive.js +52 -11
- package/lib/cli/dist/interactive.js.map +1 -1
- package/lib/cli/dist/operations.d.ts +25 -2
- package/lib/cli/dist/operations.d.ts.map +1 -1
- package/lib/cli/dist/operations.js +125 -12
- package/lib/cli/dist/operations.js.map +1 -1
- package/lib/cli/dist/output.d.ts.map +1 -1
- package/lib/cli/dist/output.js +3 -0
- package/lib/cli/dist/output.js.map +1 -1
- package/lib/cli/dist/providers.d.ts +34 -4
- package/lib/cli/dist/providers.d.ts.map +1 -1
- package/lib/cli/dist/providers.js +26 -5
- package/lib/cli/dist/providers.js.map +1 -1
- package/lib/cli/package.json +1 -1
- package/lib/cli/src/agent-guide.ts +47 -0
- package/lib/cli/src/application.ts +24 -0
- package/lib/cli/src/bin.ts +22 -5
- package/lib/cli/src/dev.ts +5 -1
- package/lib/cli/src/index.ts +18 -10
- package/lib/cli/src/interactive.ts +44 -12
- package/lib/cli/src/operations.ts +82 -12
- package/lib/cli/src/output.ts +3 -0
- package/lib/cli/src/providers.ts +45 -10
- package/lib/cli/starters/approval-workflow/dot-env.example +11 -0
- package/lib/cli/starters/approval-workflow/package.json +1 -2
- package/lib/cli/starters/approval-workflow/src/config.ts +25 -7
- package/lib/cli/starters/approval-workflow/src/intake.ts +1 -2
- package/lib/cli/starters/approval-workflow/src/model.ts +11 -4
- package/lib/cli/starters/approval-workflow/src/workflow.ts +1 -2
- package/lib/cli/starters/cli-agent/README.md +121 -0
- package/lib/cli/starters/cli-agent/dot-env.example +37 -0
- package/lib/cli/starters/cli-agent/dot-github/workflows/ci.yml +13 -0
- package/lib/cli/starters/cli-agent/dot-gitignore +10 -0
- package/lib/cli/starters/cli-agent/mayura.project.json +15 -0
- package/lib/cli/starters/cli-agent/package.json +28 -0
- package/lib/cli/starters/cli-agent/skills/release-notes/SKILL.md +18 -0
- package/lib/cli/starters/cli-agent/skills/release-notes/references/example.md +12 -0
- package/lib/cli/starters/cli-agent/src/assistant.ts +124 -0
- package/lib/cli/starters/cli-agent/src/cli.ts +72 -0
- package/lib/cli/starters/cli-agent/src/config.ts +117 -0
- package/lib/cli/starters/cli-agent/src/model.ts +34 -0
- package/lib/cli/starters/cli-agent/src/workspace.ts +170 -0
- package/lib/cli/starters/cli-agent/test/assistant.test.ts +205 -0
- package/lib/cli/starters/cli-agent/tsconfig.json +20 -0
- package/lib/cli/starters/event-automation/README.md +4 -3
- package/lib/cli/starters/event-automation/dot-env.example +11 -0
- package/lib/cli/starters/event-automation/package.json +1 -2
- package/lib/cli/starters/event-automation/src/config.ts +25 -7
- package/lib/cli/starters/event-automation/src/ingress.ts +3 -5
- package/lib/cli/starters/event-automation/src/model.ts +11 -4
- package/lib/cli/starters/event-automation/src/send-sample.ts +1 -1
- package/lib/cli/starters/event-automation/src/tracker/main.ts +1 -1
- package/lib/cli/starters/event-automation/src/tracker/mcp-server.ts +1 -1
- package/lib/cli/starters/event-automation/src/tracker/tickets.ts +1 -1
- package/lib/cli/starters/event-automation/src/tracker-tools.ts +1 -1
- package/lib/cli/starters/event-automation/src/triage.ts +15 -22
- package/lib/cli/starters/event-automation/src/workflows.ts +1 -1
- package/lib/cli/starters/event-automation/test/automation.test.ts +3 -3
- package/lib/cli/starters/research-team/README.md +2 -2
- package/lib/cli/starters/research-team/dot-env.example +11 -0
- package/lib/cli/starters/research-team/package.json +1 -2
- package/lib/cli/starters/research-team/src/config.ts +25 -7
- package/lib/cli/starters/research-team/src/desk.ts +1 -2
- package/lib/cli/starters/research-team/src/library/index.ts +1 -2
- package/lib/cli/starters/research-team/src/model.ts +11 -4
- package/lib/cli/starters/research-team/src/services.ts +1 -1
- package/lib/cli/starters/research-team/src/team.ts +1 -2
- package/lib/cli/starters/research-team/src/workflow.ts +45 -59
- package/lib/cli/starters/support-agent/dot-env.example +11 -0
- package/lib/cli/starters/support-agent/package.json +1 -2
- package/lib/cli/starters/support-agent/src/assistant.ts +5 -5
- package/lib/cli/starters/support-agent/src/config.ts +25 -7
- package/lib/cli/starters/support-agent/src/guardrails.ts +3 -1
- package/lib/cli/starters/support-agent/src/model.ts +11 -4
- package/lib/cli/starters/support-agent/src/returns.ts +1 -2
- package/lib/cli/starters/support-agent/test/support.test.ts +25 -1
- package/lib/cli/templates/basic-agent.ts +1 -2
- package/lib/cli/templates/capability-policy.ts +1 -2
- package/lib/cli/templates/code-mode-workflow.ts +1 -1
- package/lib/cli/templates/durable-approval.ts +1 -1
- package/lib/cli/templates/parallel-research.ts +1 -2
- package/lib/cli/templates/typed-tool-runner.ts +1 -2
- package/lib/client/dist/forms.d.ts.map +1 -1
- package/lib/client/dist/forms.js +3 -4
- package/lib/client/dist/forms.js.map +1 -1
- package/lib/client/dist/headless.d.ts +3 -1
- package/lib/client/dist/headless.d.ts.map +1 -1
- package/lib/client/dist/headless.js +10 -6
- package/lib/client/dist/headless.js.map +1 -1
- package/lib/client/dist/index.d.ts +95 -6
- package/lib/client/dist/index.d.ts.map +1 -1
- package/lib/client/dist/index.js +397 -124
- package/lib/client/dist/index.js.map +1 -1
- package/lib/client/dist/workflows.d.ts +1 -1
- package/lib/client/dist/workflows.d.ts.map +1 -1
- package/lib/client/dist/workflows.js +7 -6
- package/lib/client/dist/workflows.js.map +1 -1
- package/lib/client/package.json +1 -1
- package/lib/client/src/forms.ts +3 -4
- package/lib/client/src/headless.ts +13 -7
- package/lib/client/src/index.ts +344 -74
- package/lib/client/src/workflows.ts +8 -7
- package/lib/client-react/package.json +1 -1
- package/lib/code-mode/dist/index.d.ts +32 -1
- package/lib/code-mode/dist/index.d.ts.map +1 -1
- package/lib/code-mode/dist/index.js +289 -221
- package/lib/code-mode/dist/index.js.map +1 -1
- package/lib/code-mode/package.json +1 -1
- package/lib/code-mode/src/index.ts +288 -184
- package/lib/code-mode-workflows/package.json +1 -1
- package/lib/context/package.json +1 -1
- package/lib/core/dist/budget.d.ts.map +1 -1
- package/lib/core/dist/budget.js +17 -2
- package/lib/core/dist/budget.js.map +1 -1
- package/lib/core/dist/contracts.d.ts +57 -0
- package/lib/core/dist/contracts.d.ts.map +1 -1
- package/lib/core/dist/contracts.js +36 -0
- package/lib/core/dist/contracts.js.map +1 -1
- package/lib/core/dist/destination.d.ts +12 -0
- package/lib/core/dist/destination.d.ts.map +1 -0
- package/lib/core/dist/destination.js +37 -0
- package/lib/core/dist/destination.js.map +1 -0
- package/lib/core/dist/event-stream.d.ts +1 -1
- package/lib/core/dist/event-stream.d.ts.map +1 -1
- package/lib/core/dist/event-stream.js +7 -0
- package/lib/core/dist/event-stream.js.map +1 -1
- package/lib/core/dist/host.d.ts +3 -0
- package/lib/core/dist/host.d.ts.map +1 -1
- package/lib/core/dist/host.js +3 -0
- package/lib/core/dist/host.js.map +1 -1
- package/lib/core/dist/index.d.ts +2 -0
- package/lib/core/dist/index.d.ts.map +1 -1
- package/lib/core/dist/index.js +2 -0
- package/lib/core/dist/index.js.map +1 -1
- package/lib/core/dist/media.d.ts +98 -0
- package/lib/core/dist/media.d.ts.map +1 -0
- package/lib/core/dist/media.js +227 -0
- package/lib/core/dist/media.js.map +1 -0
- package/lib/core/dist/model-schema.d.ts +37 -0
- package/lib/core/dist/model-schema.d.ts.map +1 -0
- package/lib/core/dist/model-schema.js +154 -0
- package/lib/core/dist/model-schema.js.map +1 -0
- package/lib/core/package.json +1 -1
- package/lib/core/src/budget.ts +17 -2
- package/lib/core/src/contracts.ts +71 -3
- package/lib/core/src/destination.ts +33 -0
- package/lib/core/src/event-stream.ts +5 -1
- package/lib/core/src/host.ts +3 -0
- package/lib/core/src/index.ts +2 -0
- package/lib/core/src/media.ts +228 -0
- package/lib/core/src/model-schema.ts +129 -0
- package/lib/exporter-otlp/dist/otlp-http-json.js +1 -1
- package/lib/exporter-otlp/dist/otlp-http-json.js.map +1 -1
- package/lib/exporter-otlp/dist/signals.js +2 -2
- package/lib/exporter-otlp/dist/signals.js.map +1 -1
- package/lib/exporter-otlp/package.json +1 -1
- package/lib/exporter-otlp/src/otlp-http-json.ts +1 -1
- package/lib/exporter-otlp/src/signals.ts +2 -2
- package/lib/guardrails/package.json +1 -1
- package/lib/helpers/package.json +1 -1
- package/lib/memory/dist/index.js +1 -1
- package/lib/memory/dist/index.js.map +1 -1
- package/lib/memory/dist/native.d.ts.map +1 -1
- package/lib/memory/dist/native.js +4 -3
- package/lib/memory/dist/native.js.map +1 -1
- package/lib/memory/package.json +1 -1
- package/lib/memory/src/index.ts +1 -1
- package/lib/memory/src/native.ts +4 -3
- package/lib/memory-remote/package.json +1 -1
- package/lib/observability/package.json +1 -1
- package/lib/provider-anthropic/dist/index.d.ts +36 -3
- package/lib/provider-anthropic/dist/index.d.ts.map +1 -1
- package/lib/provider-anthropic/dist/index.js +128 -78
- package/lib/provider-anthropic/dist/index.js.map +1 -1
- package/lib/provider-anthropic/package.json +1 -1
- package/lib/provider-anthropic/src/index.ts +152 -76
- package/lib/provider-openai/dist/index.d.ts +71 -4
- package/lib/provider-openai/dist/index.d.ts.map +1 -1
- package/lib/provider-openai/dist/index.js +259 -96
- package/lib/provider-openai/dist/index.js.map +1 -1
- package/lib/provider-openai/package.json +1 -1
- package/lib/provider-openai/src/index.ts +282 -84
- package/lib/runtime/dist/agent.d.ts +18 -1
- package/lib/runtime/dist/agent.d.ts.map +1 -1
- package/lib/runtime/dist/agent.js +59 -3
- package/lib/runtime/dist/agent.js.map +1 -1
- package/lib/runtime/dist/composition.d.ts.map +1 -1
- package/lib/runtime/dist/composition.js +2 -1
- package/lib/runtime/dist/composition.js.map +1 -1
- package/lib/runtime/dist/hooks.d.ts +15 -3
- package/lib/runtime/dist/hooks.d.ts.map +1 -1
- package/lib/runtime/dist/hooks.js.map +1 -1
- package/lib/runtime/dist/index.d.ts +1 -1
- package/lib/runtime/dist/index.d.ts.map +1 -1
- package/lib/runtime/dist/index.js.map +1 -1
- package/lib/runtime/dist/response.d.ts +7 -1
- package/lib/runtime/dist/response.d.ts.map +1 -1
- package/lib/runtime/dist/response.js +23 -2
- package/lib/runtime/dist/response.js.map +1 -1
- package/lib/runtime/dist/router.d.ts +10 -3
- package/lib/runtime/dist/router.d.ts.map +1 -1
- package/lib/runtime/dist/router.js +45 -8
- package/lib/runtime/dist/router.js.map +1 -1
- package/lib/runtime/dist/runtime.d.ts +9 -1
- package/lib/runtime/dist/runtime.d.ts.map +1 -1
- package/lib/runtime/dist/runtime.js +50 -22
- package/lib/runtime/dist/runtime.js.map +1 -1
- package/lib/runtime/package.json +1 -1
- package/lib/runtime/src/agent.ts +69 -3
- package/lib/runtime/src/composition.ts +2 -1
- package/lib/runtime/src/hooks.ts +10 -4
- package/lib/runtime/src/index.ts +1 -1
- package/lib/runtime/src/response.ts +20 -2
- package/lib/runtime/src/router.ts +43 -10
- package/lib/runtime/src/runtime.ts +58 -27
- package/lib/sdk/dist/index.d.ts +9 -1
- package/lib/sdk/dist/index.d.ts.map +1 -1
- package/lib/sdk/dist/index.js +9 -1
- package/lib/sdk/dist/index.js.map +1 -1
- package/lib/sdk/package.json +1 -1
- package/lib/sdk/src/index.ts +9 -1
- package/lib/server/dist/index.d.ts +201 -3
- package/lib/server/dist/index.d.ts.map +1 -1
- package/lib/server/dist/index.js +701 -149
- package/lib/server/dist/index.js.map +1 -1
- package/lib/server/dist/inspector-bundle.d.ts +1 -1
- package/lib/server/dist/inspector-bundle.d.ts.map +1 -1
- package/lib/server/dist/inspector-bundle.js +4 -4
- package/lib/server/dist/inspector-bundle.js.map +1 -1
- package/lib/server/package.json +1 -1
- package/lib/server/src/index.ts +611 -135
- package/lib/server/src/inspector-bundle.ts +4 -4
- package/lib/server-node/dist/hardening.d.ts +1 -1
- package/lib/server-node/dist/hardening.d.ts.map +1 -1
- package/lib/server-node/dist/hardening.js +4 -2
- package/lib/server-node/dist/hardening.js.map +1 -1
- package/lib/server-node/dist/index.d.ts +2 -1
- package/lib/server-node/dist/index.d.ts.map +1 -1
- package/lib/server-node/dist/index.js.map +1 -1
- package/lib/server-node/dist/probe.js +2 -2
- package/lib/server-node/dist/probe.js.map +1 -1
- package/lib/server-node/dist/production.d.ts +8 -1
- package/lib/server-node/dist/production.d.ts.map +1 -1
- package/lib/server-node/dist/production.js +15 -2
- package/lib/server-node/dist/production.js.map +1 -1
- package/lib/server-node/package.json +1 -1
- package/lib/server-node/src/hardening.ts +5 -3
- package/lib/server-node/src/index.ts +2 -1
- package/lib/server-node/src/probe.ts +2 -2
- package/lib/server-node/src/production.ts +23 -3
- package/lib/skills/dist/index.d.ts +81 -0
- package/lib/skills/dist/index.d.ts.map +1 -0
- package/lib/skills/dist/index.js +311 -0
- package/lib/skills/dist/index.js.map +1 -0
- package/lib/skills/package.json +5 -0
- package/lib/skills/src/index.ts +260 -0
- package/lib/storage/dist/index.d.ts +1 -1
- package/lib/storage/dist/index.d.ts.map +1 -1
- package/lib/storage/dist/index.js.map +1 -1
- package/lib/storage/package.json +1 -1
- package/lib/storage/src/index.ts +1 -1
- package/lib/storage-contracts/dist/contracts.d.ts +12 -5
- package/lib/storage-contracts/dist/contracts.d.ts.map +1 -1
- package/lib/storage-contracts/dist/contracts.js +24 -6
- package/lib/storage-contracts/dist/contracts.js.map +1 -1
- package/lib/storage-contracts/dist/index.d.ts +2 -0
- package/lib/storage-contracts/dist/index.d.ts.map +1 -1
- package/lib/storage-contracts/dist/index.js +2 -0
- package/lib/storage-contracts/dist/index.js.map +1 -1
- package/lib/storage-contracts/dist/memory-contracts.js +1 -1
- package/lib/storage-contracts/dist/memory-contracts.js.map +1 -1
- package/lib/storage-contracts/dist/run-records.d.ts +100 -0
- package/lib/storage-contracts/dist/run-records.d.ts.map +1 -0
- package/lib/storage-contracts/dist/run-records.js +464 -0
- package/lib/storage-contracts/dist/run-records.js.map +1 -0
- package/lib/storage-contracts/dist/schema-digest.d.ts +17 -0
- package/lib/storage-contracts/dist/schema-digest.d.ts.map +1 -0
- package/lib/storage-contracts/dist/schema-digest.js +94 -0
- package/lib/storage-contracts/dist/schema-digest.js.map +1 -0
- package/lib/storage-contracts/dist/submission-journal.js +1 -1
- package/lib/storage-contracts/dist/submission-journal.js.map +1 -1
- package/lib/storage-contracts/dist/workflow-format5.d.ts +30 -2
- package/lib/storage-contracts/dist/workflow-format5.d.ts.map +1 -1
- package/lib/storage-contracts/dist/workflow-format5.js +57 -5
- package/lib/storage-contracts/dist/workflow-format5.js.map +1 -1
- package/lib/storage-contracts/package.json +1 -1
- package/lib/storage-contracts/src/contracts.ts +29 -5
- package/lib/storage-contracts/src/index.ts +2 -0
- package/lib/storage-contracts/src/memory-contracts.ts +1 -1
- package/lib/storage-contracts/src/run-records.ts +365 -0
- package/lib/storage-contracts/src/schema-digest.ts +71 -0
- package/lib/storage-contracts/src/submission-journal.ts +1 -1
- package/lib/storage-contracts/src/workflow-format5.ts +70 -6
- package/lib/storage-postgres/dist/index.d.ts +1 -1
- package/lib/storage-postgres/dist/index.d.ts.map +1 -1
- package/lib/storage-postgres/dist/index.js.map +1 -1
- package/lib/storage-postgres/dist/postgres.d.ts +15 -0
- package/lib/storage-postgres/dist/postgres.d.ts.map +1 -1
- package/lib/storage-postgres/dist/postgres.js +18 -7
- package/lib/storage-postgres/dist/postgres.js.map +1 -1
- package/lib/storage-postgres/package.json +1 -1
- package/lib/storage-postgres/src/index.ts +1 -1
- package/lib/storage-postgres/src/postgres.ts +34 -8
- package/lib/storage-sql/dist/aggregate-session.js +1 -1
- package/lib/storage-sql/dist/aggregate-session.js.map +1 -1
- package/lib/storage-sql/dist/scheduled-database.js +1 -1
- package/lib/storage-sql/dist/scheduled-database.js.map +1 -1
- package/lib/storage-sql/dist/workflow-tree-validation.js +1 -1
- package/lib/storage-sql/dist/workflow-tree-validation.js.map +1 -1
- package/lib/storage-sql/package.json +1 -1
- package/lib/storage-sql/src/aggregate-session.ts +1 -1
- package/lib/storage-sql/src/scheduled-database.ts +1 -1
- package/lib/storage-sql/src/workflow-tree-validation.ts +1 -1
- package/lib/storage-sqlite/dist/sqlite-database.js +4 -4
- package/lib/storage-sqlite/dist/sqlite-database.js.map +1 -1
- package/lib/storage-sqlite/dist/sqlite-worker.js +2 -2
- package/lib/storage-sqlite/dist/sqlite-worker.js.map +1 -1
- package/lib/storage-sqlite/dist/sqlite.js +1 -1
- package/lib/storage-sqlite/dist/sqlite.js.map +1 -1
- package/lib/storage-sqlite/package.json +1 -1
- package/lib/storage-sqlite/src/sqlite-database.ts +4 -4
- package/lib/storage-sqlite/src/sqlite-worker.ts +2 -2
- package/lib/storage-sqlite/src/sqlite.ts +1 -1
- package/lib/terminal/dist/index.d.ts +92 -0
- package/lib/terminal/dist/index.d.ts.map +1 -0
- package/lib/terminal/dist/index.js +397 -0
- package/lib/terminal/dist/index.js.map +1 -0
- package/lib/terminal/package.json +5 -0
- package/lib/terminal/src/index.ts +273 -0
- package/lib/testing/dist/index.d.ts +44 -1
- package/lib/testing/dist/index.d.ts.map +1 -1
- package/lib/testing/dist/index.js +63 -10
- package/lib/testing/dist/index.js.map +1 -1
- package/lib/testing/package.json +1 -1
- package/lib/testing/src/index.ts +83 -10
- package/lib/tools/dist/index.d.ts +32 -4
- package/lib/tools/dist/index.d.ts.map +1 -1
- package/lib/tools/dist/index.js +64 -11
- package/lib/tools/dist/index.js.map +1 -1
- package/lib/tools/package.json +1 -1
- package/lib/tools/src/index.ts +74 -13
- package/lib/workflows/dist/abandoned.d.ts +15 -0
- package/lib/workflows/dist/abandoned.d.ts.map +1 -0
- package/lib/workflows/dist/abandoned.js +33 -0
- package/lib/workflows/dist/abandoned.js.map +1 -0
- package/lib/workflows/dist/agent-step.d.ts +83 -0
- package/lib/workflows/dist/agent-step.d.ts.map +1 -0
- package/lib/workflows/dist/agent-step.js +161 -0
- package/lib/workflows/dist/agent-step.js.map +1 -0
- package/lib/workflows/dist/children-runtime.js +8 -8
- package/lib/workflows/dist/children-runtime.js.map +1 -1
- package/lib/workflows/dist/composite-fleet.js +2 -2
- package/lib/workflows/dist/composite-fleet.js.map +1 -1
- package/lib/workflows/dist/composite-host.d.ts.map +1 -1
- package/lib/workflows/dist/composite-host.js +26 -2
- package/lib/workflows/dist/composite-host.js.map +1 -1
- package/lib/workflows/dist/hook-relay.js +2 -2
- package/lib/workflows/dist/hook-relay.js.map +1 -1
- package/lib/workflows/dist/index.d.ts +1 -1
- package/lib/workflows/dist/index.d.ts.map +1 -1
- package/lib/workflows/dist/index.js.map +1 -1
- package/lib/workflows/dist/leadership.js +3 -3
- package/lib/workflows/dist/leadership.js.map +1 -1
- package/lib/workflows/dist/lifecycle-definition.d.ts +26 -4
- package/lib/workflows/dist/lifecycle-definition.d.ts.map +1 -1
- package/lib/workflows/dist/lifecycle-definition.js +31 -6
- package/lib/workflows/dist/lifecycle-definition.js.map +1 -1
- package/lib/workflows/dist/lifecycle-fleet.d.ts.map +1 -1
- package/lib/workflows/dist/lifecycle-fleet.js +9 -11
- package/lib/workflows/dist/lifecycle-fleet.js.map +1 -1
- package/lib/workflows/dist/lifecycle-host.d.ts.map +1 -1
- package/lib/workflows/dist/lifecycle-host.js +26 -2
- package/lib/workflows/dist/lifecycle-host.js.map +1 -1
- package/lib/workflows/dist/lifecycle-human-transport.d.ts +22 -2
- package/lib/workflows/dist/lifecycle-human-transport.d.ts.map +1 -1
- package/lib/workflows/dist/lifecycle-human-transport.js +115 -33
- package/lib/workflows/dist/lifecycle-human-transport.js.map +1 -1
- package/lib/workflows/dist/lifecycle-runtime.d.ts +62 -1
- package/lib/workflows/dist/lifecycle-runtime.d.ts.map +1 -1
- package/lib/workflows/dist/lifecycle-runtime.js +268 -64
- package/lib/workflows/dist/lifecycle-runtime.js.map +1 -1
- package/lib/workflows/dist/lifecycle.d.ts +6 -4
- package/lib/workflows/dist/lifecycle.d.ts.map +1 -1
- package/lib/workflows/dist/lifecycle.js +2 -0
- package/lib/workflows/dist/lifecycle.js.map +1 -1
- package/lib/workflows/dist/loop-runtime.d.ts.map +1 -1
- package/lib/workflows/dist/loop-runtime.js +38 -26
- package/lib/workflows/dist/loop-runtime.js.map +1 -1
- package/lib/workflows/dist/migration.d.ts +1 -1
- package/lib/workflows/dist/migration.d.ts.map +1 -1
- package/lib/workflows/dist/migration.js +3 -3
- package/lib/workflows/dist/migration.js.map +1 -1
- package/lib/workflows/dist/operator-transports.d.ts +24 -2
- package/lib/workflows/dist/operator-transports.d.ts.map +1 -1
- package/lib/workflows/dist/operator-transports.js +49 -3
- package/lib/workflows/dist/operator-transports.js.map +1 -1
- package/lib/workflows/dist/runtime.d.ts.map +1 -1
- package/lib/workflows/dist/runtime.js +34 -22
- package/lib/workflows/dist/runtime.js.map +1 -1
- package/lib/workflows/dist/saga-runtime.d.ts.map +1 -1
- package/lib/workflows/dist/saga-runtime.js +44 -30
- package/lib/workflows/dist/saga-runtime.js.map +1 -1
- package/lib/workflows/dist/scheduled-helpers.d.ts.map +1 -1
- package/lib/workflows/dist/scheduled-helpers.js +3 -3
- package/lib/workflows/dist/scheduled-helpers.js.map +1 -1
- package/lib/workflows/dist/storage-failure.d.ts +16 -0
- package/lib/workflows/dist/storage-failure.d.ts.map +1 -0
- package/lib/workflows/dist/storage-failure.js +38 -0
- package/lib/workflows/dist/storage-failure.js.map +1 -0
- package/lib/workflows/dist/sweep-position.d.ts +22 -0
- package/lib/workflows/dist/sweep-position.d.ts.map +1 -0
- package/lib/workflows/dist/sweep-position.js +45 -0
- package/lib/workflows/dist/sweep-position.js.map +1 -0
- package/lib/workflows/dist/traces.js +2 -2
- package/lib/workflows/dist/traces.js.map +1 -1
- package/lib/workflows/dist/worker.d.ts +31 -0
- package/lib/workflows/dist/worker.d.ts.map +1 -1
- package/lib/workflows/dist/worker.js +94 -0
- package/lib/workflows/dist/worker.js.map +1 -1
- package/lib/workflows/package.json +1 -1
- package/lib/workflows/src/abandoned.ts +32 -0
- package/lib/workflows/src/agent-step.ts +199 -0
- package/lib/workflows/src/children-runtime.ts +8 -8
- package/lib/workflows/src/composite-fleet.ts +2 -2
- package/lib/workflows/src/composite-host.ts +21 -3
- package/lib/workflows/src/hook-relay.ts +2 -2
- package/lib/workflows/src/index.ts +2 -1
- package/lib/workflows/src/leadership.ts +3 -3
- package/lib/workflows/src/lifecycle-definition.ts +50 -9
- package/lib/workflows/src/lifecycle-fleet.ts +7 -8
- package/lib/workflows/src/lifecycle-host.ts +21 -5
- package/lib/workflows/src/lifecycle-human-transport.ts +110 -26
- package/lib/workflows/src/lifecycle-runtime.ts +270 -60
- package/lib/workflows/src/lifecycle.ts +7 -0
- package/lib/workflows/src/loop-runtime.ts +34 -25
- package/lib/workflows/src/migration.ts +2 -2
- package/lib/workflows/src/operator-transports.ts +48 -4
- package/lib/workflows/src/runtime.ts +28 -22
- package/lib/workflows/src/saga-runtime.ts +38 -28
- package/lib/workflows/src/scheduled-helpers.ts +3 -3
- package/lib/workflows/src/storage-failure.ts +37 -0
- package/lib/workflows/src/sweep-position.ts +52 -0
- package/lib/workflows/src/traces.ts +2 -2
- package/lib/workflows/src/worker.ts +79 -1
- package/lib/workstream/dist/humans.d.ts +7 -3
- package/lib/workstream/dist/humans.d.ts.map +1 -1
- package/lib/workstream/dist/humans.js +13 -2
- package/lib/workstream/dist/humans.js.map +1 -1
- package/lib/workstream/dist/index.js +2 -2
- package/lib/workstream/dist/index.js.map +1 -1
- package/lib/workstream/dist/timers.js +2 -2
- package/lib/workstream/dist/timers.js.map +1 -1
- package/lib/workstream/dist/webhooks.d.ts +6 -2
- package/lib/workstream/dist/webhooks.d.ts.map +1 -1
- package/lib/workstream/dist/webhooks.js +17 -7
- package/lib/workstream/dist/webhooks.js.map +1 -1
- package/lib/workstream/package.json +1 -1
- package/lib/workstream/src/humans.ts +15 -5
- package/lib/workstream/src/index.ts +2 -2
- package/lib/workstream/src/timers.ts +2 -2
- package/lib/workstream/src/webhooks.ts +21 -8
- package/llms-full.txt +9766 -0
- package/llms.txt +92 -0
- package/package.json +18 -6
|
@@ -27,6 +27,20 @@ export interface WorkflowLifecycleTimerNodeManifest {
|
|
|
27
27
|
readonly when?: WorkflowBinding;
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
+
/**
|
|
31
|
+
* Waits for one named signal delivered from outside the run. `name` is what a sender addresses (unique among the
|
|
32
|
+
* definition's signal nodes); `deadlineAtMs`, when set, times the step out if no signal arrived by then. The payload
|
|
33
|
+
* validator is code, like a tool's validators, and is not part of this material.
|
|
34
|
+
*/
|
|
35
|
+
export interface WorkflowLifecycleSignalNodeManifest {
|
|
36
|
+
readonly kind: 'signal';
|
|
37
|
+
readonly id: string;
|
|
38
|
+
readonly dependsOn: readonly string[];
|
|
39
|
+
readonly name: string;
|
|
40
|
+
readonly deadlineAtMs: WorkflowBinding | null;
|
|
41
|
+
readonly when?: WorkflowBinding;
|
|
42
|
+
}
|
|
43
|
+
|
|
30
44
|
/**
|
|
31
45
|
* Any lifecycle node may carry `when`: a binding over the input or a dependency's output. The node runs only when it
|
|
32
46
|
* resolves to a value other than `null` or `false`; otherwise it is `bypassed` without being admitted or charged.
|
|
@@ -34,7 +48,8 @@ export interface WorkflowLifecycleTimerNodeManifest {
|
|
|
34
48
|
*/
|
|
35
49
|
export type WorkflowLifecycleManifestNode = (WorkflowManifestNode & { readonly when?: WorkflowBinding })
|
|
36
50
|
| WorkflowLifecycleHumanNodeManifest
|
|
37
|
-
| WorkflowLifecycleTimerNodeManifest
|
|
51
|
+
| WorkflowLifecycleTimerNodeManifest
|
|
52
|
+
| WorkflowLifecycleSignalNodeManifest;
|
|
38
53
|
|
|
39
54
|
/** Immutable data-only definition material for explicit lifecycle suspension nodes. */
|
|
40
55
|
export interface WorkflowLifecycleManifest {
|
|
@@ -48,6 +63,7 @@ export interface WorkflowLifecycleManifest {
|
|
|
48
63
|
export type WorkflowLifecycleStatus = 'running' | 'waiting' | 'paused' | 'succeeded' | 'failed' | 'blocked' | 'cancelled' | 'outcome_unknown';
|
|
49
64
|
export type WorkflowLifecycleHumanStepStatus = 'pending' | 'waiting' | 'succeeded' | 'timed_out' | 'skipped' | 'bypassed';
|
|
50
65
|
export type WorkflowLifecycleTimerStepStatus = 'pending' | 'waiting' | 'succeeded' | 'skipped' | 'bypassed';
|
|
66
|
+
export type WorkflowLifecycleSignalStepStatus = 'pending' | 'waiting' | 'succeeded' | 'timed_out' | 'skipped' | 'bypassed';
|
|
51
67
|
/** `bypassed`: the step's `when` condition did not hold, so it never started. Dependents treat it like success with output `null`. */
|
|
52
68
|
export type WorkflowLifecycleToolStepStatus = WorkflowFormat2StepStatus | 'bypassed';
|
|
53
69
|
export type WorkflowLifecycleToolStep = Omit<WorkflowFormat2Step, 'status'> & { status: WorkflowLifecycleToolStepStatus };
|
|
@@ -72,7 +88,22 @@ export interface WorkflowLifecycleTimerStep {
|
|
|
72
88
|
firedAtMs: number | null;
|
|
73
89
|
}
|
|
74
90
|
|
|
75
|
-
|
|
91
|
+
/**
|
|
92
|
+
* A signal step. A signal delivered before the step starts is kept on the `pending` step (`signalId` set) and
|
|
93
|
+
* completes it as soon as it starts, provided it arrived before the deadline. `output` is the validated payload.
|
|
94
|
+
*/
|
|
95
|
+
export interface WorkflowLifecycleSignalStep {
|
|
96
|
+
readonly kind: 'signal';
|
|
97
|
+
status: WorkflowLifecycleSignalStepStatus;
|
|
98
|
+
readonly callId: string;
|
|
99
|
+
output: JsonValue;
|
|
100
|
+
signalId: string | null;
|
|
101
|
+
payloadDigest: string | null;
|
|
102
|
+
receivedAtMs: number | null;
|
|
103
|
+
deadlineAtMs: number | null;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export type WorkflowLifecycleStep = WorkflowLifecycleToolStep | WorkflowLifecycleHumanStep | WorkflowLifecycleTimerStep | WorkflowLifecycleSignalStep;
|
|
76
107
|
|
|
77
108
|
export interface WorkflowLifecycleState {
|
|
78
109
|
readonly format: 5;
|
|
@@ -95,6 +126,9 @@ const humanKinds = new Set<WorkflowLifecycleHumanKind>(['information', 'correcti
|
|
|
95
126
|
const lifecycleStatuses = new Set<WorkflowLifecycleStatus>(['running', 'waiting', 'paused', 'succeeded', 'failed', 'blocked', 'cancelled', 'outcome_unknown']);
|
|
96
127
|
const humanStepStatuses = new Set<WorkflowLifecycleHumanStepStatus>(['pending', 'waiting', 'succeeded', 'timed_out', 'skipped', 'bypassed']);
|
|
97
128
|
const timerStepStatuses = new Set<WorkflowLifecycleTimerStepStatus>(['pending', 'waiting', 'succeeded', 'skipped', 'bypassed']);
|
|
129
|
+
const signalStepStatuses = new Set<WorkflowLifecycleSignalStepStatus>(['pending', 'waiting', 'succeeded', 'timed_out', 'skipped', 'bypassed']);
|
|
130
|
+
/** Signal names and ids: what the operator API accepts for `signalName` and `signalId`. */
|
|
131
|
+
const signalPattern = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,127}$/;
|
|
98
132
|
/** Statuses a dependent step may build on. */
|
|
99
133
|
const satisfied = new Set(['succeeded', 'bypassed']);
|
|
100
134
|
|
|
@@ -182,12 +216,12 @@ export function workflowLifecycleManifest(value: unknown): WorkflowLifecycleMani
|
|
|
182
216
|
if (!Object.hasOwn(node, 'when')) return node;
|
|
183
217
|
const { when: _when, ...rest } = node; return rest;
|
|
184
218
|
}
|
|
185
|
-
if (node['kind'] !== 'human' && node['kind'] !== 'timer') invalid();
|
|
219
|
+
if (node['kind'] !== 'human' && node['kind'] !== 'timer' && node['kind'] !== 'signal') invalid();
|
|
186
220
|
return { kind: 'join', id: node['id'], dependsOn: node['dependsOn'] };
|
|
187
221
|
});
|
|
188
222
|
const common = workflowManifest({ id: manifest['id'], version: manifest['version'], graph: projected, result: manifest['result'] });
|
|
189
223
|
const ids = new Set(common.graph.map(node => node.id));
|
|
190
|
-
let humans = 0; let timers = 0;
|
|
224
|
+
let humans = 0; let timers = 0; const signals = new Set<string>();
|
|
191
225
|
|
|
192
226
|
for (const raw of graph) {
|
|
193
227
|
const node = object(raw);
|
|
@@ -204,6 +238,13 @@ export function workflowLifecycleManifest(value: unknown): WorkflowLifecycleMani
|
|
|
204
238
|
temporalBinding(node['fireAtMs'], ids, dependencies);
|
|
205
239
|
continue;
|
|
206
240
|
}
|
|
241
|
+
if (node['kind'] === 'signal') {
|
|
242
|
+
fields(node, ['kind', 'id', 'dependsOn', 'name', 'deadlineAtMs', ...optional]);
|
|
243
|
+
if (typeof node['name'] !== 'string' || !signalPattern.test(node['name']) || signals.has(node['name'])) invalid();
|
|
244
|
+
signals.add(node['name']);
|
|
245
|
+
if (node['deadlineAtMs'] !== null) temporalBinding(node['deadlineAtMs'], ids, dependencies);
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
207
248
|
humans += 1;
|
|
208
249
|
fields(node, ['kind', 'id', 'dependsOn', 'requestKind', 'schemaId', 'schemaDigest', 'prompt', 'context', 'subjectDigest', 'deadlineAtMs', ...optional]);
|
|
209
250
|
if (!humanKinds.has(node['requestKind'] as WorkflowLifecycleHumanKind)
|
|
@@ -216,7 +257,7 @@ export function workflowLifecycleManifest(value: unknown): WorkflowLifecycleMani
|
|
|
216
257
|
if (node['subjectDigest'] !== null) digestBinding(node['subjectDigest'], ids, dependencies);
|
|
217
258
|
if (node['deadlineAtMs'] !== null) temporalBinding(node['deadlineAtMs'], ids, dependencies);
|
|
218
259
|
}
|
|
219
|
-
if (humans > 32 || timers > 64) invalid();
|
|
260
|
+
if (humans > 32 || timers > 64 || signals.size > 64) invalid();
|
|
220
261
|
return freezeJson(manifest) as unknown as WorkflowLifecycleManifest;
|
|
221
262
|
} catch {
|
|
222
263
|
return invalid();
|
|
@@ -243,6 +284,9 @@ export function initialWorkflowLifecycleState(
|
|
|
243
284
|
: node.kind === 'timer'
|
|
244
285
|
? { kind: 'timer', status: 'pending', callId: `step:${node.id}`, output: null,
|
|
245
286
|
fireAtMs: null, firedAtMs: null }
|
|
287
|
+
: node.kind === 'signal'
|
|
288
|
+
? { kind: 'signal', status: 'pending', callId: `step:${node.id}`, output: null,
|
|
289
|
+
signalId: null, payloadDigest: null, receivedAtMs: null, deadlineAtMs: null }
|
|
246
290
|
: { kind: node.kind, status: 'pending', callId: `step:${node.id}`, output: null,
|
|
247
291
|
receipt: null, approval: null, costReserved: 0, candidateHash: null },
|
|
248
292
|
])),
|
|
@@ -312,6 +356,24 @@ export function workflowLifecycleState(record: Pick<StoredRecord, 'id' | 'state'
|
|
|
312
356
|
}
|
|
313
357
|
continue;
|
|
314
358
|
}
|
|
359
|
+
if (step['kind'] === 'signal') {
|
|
360
|
+
fields(step, ['kind', 'status', 'callId', 'output', 'signalId', 'payloadDigest', 'receivedAtMs', 'deadlineAtMs']);
|
|
361
|
+
if (!signalStepStatuses.has(step['status'] as WorkflowLifecycleSignalStepStatus)) invalid();
|
|
362
|
+
if (step['signalId'] !== null && (typeof step['signalId'] !== 'string' || !signalPattern.test(step['signalId']))) invalid();
|
|
363
|
+
if (step['payloadDigest'] !== null) hash(step['payloadDigest']);
|
|
364
|
+
if (step['receivedAtMs'] !== null) integer(step['receivedAtMs']);
|
|
365
|
+
if (step['deadlineAtMs'] !== null) integer(step['deadlineAtMs']);
|
|
366
|
+
// A signal is recorded completely or not at all.
|
|
367
|
+
const received = step['signalId'] !== null;
|
|
368
|
+
if ([step['payloadDigest'], step['receivedAtMs']].some(value => (value !== null) !== received) || (!received && step['output'] !== null)) invalid();
|
|
369
|
+
if (step['status'] === 'pending' && step['deadlineAtMs'] !== null) invalid();
|
|
370
|
+
if (step['status'] === 'succeeded' && !received) invalid();
|
|
371
|
+
if (step['status'] === 'waiting' && received) invalid();
|
|
372
|
+
if (step['status'] === 'timed_out' && (received || step['deadlineAtMs'] === null)) invalid();
|
|
373
|
+
if ((step['status'] === 'skipped' || step['status'] === 'bypassed') && (received || step['deadlineAtMs'] !== null)) invalid();
|
|
374
|
+
if (step['status'] === 'waiting') waiting += 1;
|
|
375
|
+
continue;
|
|
376
|
+
}
|
|
315
377
|
invalid();
|
|
316
378
|
}
|
|
317
379
|
if (computedReserved !== reservedMicros) invalid();
|
|
@@ -346,7 +408,7 @@ export function assertWorkflowLifecycleStateMatchesManifest(
|
|
|
346
408
|
if (step['receipt'] !== null && object(step['receipt'])['toolId'] !== node.tool) invalid();
|
|
347
409
|
if (integer(step['costReserved']) > node.costMicros) invalid();
|
|
348
410
|
}
|
|
349
|
-
if (node.kind === 'human' && step['deadlineAtMs'] !== null && node.deadlineAtMs === null) invalid();
|
|
411
|
+
if ((node.kind === 'human' || node.kind === 'signal') && step['deadlineAtMs'] !== null && node.deadlineAtMs === null) invalid();
|
|
350
412
|
}
|
|
351
413
|
} catch { return corrupt(); }
|
|
352
414
|
}
|
|
@@ -368,6 +430,8 @@ export function workflowLifecycleOutputs(state: WorkflowLifecycleState): Record<
|
|
|
368
430
|
} else if (step['kind'] === 'timer') {
|
|
369
431
|
const fireAtMs = integer(step['fireAtMs']); const firedAtMs = integer(step['firedAtMs']);
|
|
370
432
|
if (firedAtMs < fireAtMs || canonical(step['output']!) !== canonical(jsonValue({ fireAtMs, firedAtMs }))) invalid();
|
|
433
|
+
} else if (step['kind'] === 'signal') {
|
|
434
|
+
if (typeof step['signalId'] !== 'string') invalid(); hash(step['payloadDigest']); integer(step['receivedAtMs']);
|
|
371
435
|
} else if (step['kind'] !== 'join') invalid();
|
|
372
436
|
return [id, step['output']!];
|
|
373
437
|
}));
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export { createPostgresStore, type PostgresStoreOptions } from './postgres.js';
|
|
1
|
+
export { createPostgresStore, type PostgresPoolOptions, type PostgresStoreOptions } from './postgres.js';
|
|
2
2
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,KAAK,oBAAoB,EAAE,MAAM,eAAe,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,KAAK,mBAAmB,EAAE,KAAK,oBAAoB,EAAE,MAAM,eAAe,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAuD,MAAM,eAAe,CAAC","sourcesContent":["export { createPostgresStore, type PostgresPoolOptions, type PostgresStoreOptions } from './postgres.js';\n"]}
|
|
@@ -2,6 +2,21 @@ import { type WorkflowGraphDiscoveryAggregateStore, type DurableBudgetAggregateS
|
|
|
2
2
|
export interface PostgresStoreOptions {
|
|
3
3
|
readonly connectionString: string;
|
|
4
4
|
readonly schema?: string;
|
|
5
|
+
/**
|
|
6
|
+
* The connection pool. The defaults suit a long-running server: up to 8 connections, 5 s to connect, idle connections
|
|
7
|
+
* closed after 10 s. On serverless functions, where every instance has its own pool, use `max: 1` or `2` and connect
|
|
8
|
+
* through your provider's pooler. Mayura keeps no session state between transactions (each operation is one
|
|
9
|
+
* transaction, with `SET LOCAL` settings and transaction-scoped locks), which is what transaction-mode poolers need.
|
|
10
|
+
*/
|
|
11
|
+
readonly pool?: PostgresPoolOptions;
|
|
12
|
+
}
|
|
13
|
+
export interface PostgresPoolOptions {
|
|
14
|
+
/** Most connections open at once, 1 to 100. Default 8. */
|
|
15
|
+
readonly max?: number;
|
|
16
|
+
/** How long to wait for a connection, 100 to 120,000 ms. Default 5,000. */
|
|
17
|
+
readonly connectionTimeoutMs?: number;
|
|
18
|
+
/** How long an idle connection stays open, 100 to 3,600,000 ms. Default 10,000. */
|
|
19
|
+
readonly idleTimeoutMs?: number;
|
|
5
20
|
}
|
|
6
21
|
/** Optional PostgreSQL adapter. A schema is isolated storage, not an authorization boundary. */
|
|
7
22
|
export declare function createPostgresStore(options: PostgresStoreOptions): WorkflowGraphDiscoveryAggregateStore & DurableBudgetAggregateStore & WorkflowTreeDiscoveryAggregateStore & MemoryIndexAggregateStore;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postgres.d.ts","sourceRoot":"","sources":["../src/postgres.ts"],"names":[],"mappings":"AACA,OAAO,EAA6H,KAAK,oCAAoC,EAAE,KAAK,2BAA2B,EAAE,KAAK,mCAAmC,EAAE,KAAK,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AAW7T,MAAM,WAAW,oBAAoB;
|
|
1
|
+
{"version":3,"file":"postgres.d.ts","sourceRoot":"","sources":["../src/postgres.ts"],"names":[],"mappings":"AACA,OAAO,EAA6H,KAAK,oCAAoC,EAAE,KAAK,2BAA2B,EAAE,KAAK,mCAAmC,EAAE,KAAK,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AAW7T,MAAM,WAAW,oBAAoB;IACnC,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;IAClC,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IACzB;;;;;OAKG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE,mBAAmB,CAAC;CACrC;AACD,MAAM,WAAW,mBAAmB;IAClC,0DAA0D;IAC1D,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC;IACtB,2EAA2E;IAC3E,QAAQ,CAAC,mBAAmB,CAAC,EAAE,MAAM,CAAC;IACtC,mFAAmF;IACnF,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;CACjC;AA0BD,gGAAgG;AAChG,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,oBAAoB,GAAG,oCAAoC,GAAG,2BAA2B,GAAG,mCAAmC,GAAG,yBAAyB,CA8LvM"}
|
|
@@ -15,7 +15,7 @@ function record(row) {
|
|
|
15
15
|
}
|
|
16
16
|
function safeFailure(error) {
|
|
17
17
|
if (typeof error === 'object' && error !== null && 'code' in error && error.code === '23505') {
|
|
18
|
-
return new StorageError('CONFLICT', 'A
|
|
18
|
+
return new StorageError('CONFLICT', 'A record with this ID or idempotency key already exists in this scope with different content; use a new ID or key.');
|
|
19
19
|
}
|
|
20
20
|
return storageError(error);
|
|
21
21
|
}
|
|
@@ -32,7 +32,18 @@ export function createPostgresStore(options) {
|
|
|
32
32
|
const prefix = `"${schema}"`;
|
|
33
33
|
const aggregates = `${prefix}.mayura_aggregates`;
|
|
34
34
|
const eventsTable = `${prefix}.mayura_events`;
|
|
35
|
-
const
|
|
35
|
+
const settings = options.pool === undefined ? {} : options.pool;
|
|
36
|
+
if (settings === null || typeof settings !== 'object' || Object.keys(settings).some(key => !['max', 'connectionTimeoutMs', 'idleTimeoutMs'].includes(key))) {
|
|
37
|
+
throw new StorageError('INVALID_INPUT', 'PostgreSQL pool options are max, connectionTimeoutMs and idleTimeoutMs.');
|
|
38
|
+
}
|
|
39
|
+
const max = settings.max ?? 8;
|
|
40
|
+
const connectionTimeoutMs = settings.connectionTimeoutMs ?? 5_000;
|
|
41
|
+
const idleTimeoutMs = settings.idleTimeoutMs ?? 10_000;
|
|
42
|
+
for (const [name, value, minimum, maximum] of [['max', max, 1, 100], ['connectionTimeoutMs', connectionTimeoutMs, 100, 120_000], ['idleTimeoutMs', idleTimeoutMs, 100, 3_600_000]]) {
|
|
43
|
+
if (!Number.isSafeInteger(value) || value < minimum || value > maximum)
|
|
44
|
+
throw new StorageError('INVALID_INPUT', `PostgreSQL pool ${name} must be an integer from ${minimum} to ${maximum}.`);
|
|
45
|
+
}
|
|
46
|
+
const pool = new Pool({ connectionString: options.connectionString, max, connectionTimeoutMillis: connectionTimeoutMs, idleTimeoutMillis: idleTimeoutMs });
|
|
36
47
|
// Idle-client errors must not become unhandled EventEmitter exceptions. Commands still fail closed.
|
|
37
48
|
pool.on('error', () => { });
|
|
38
49
|
let initialized = false;
|
|
@@ -41,9 +52,9 @@ export function createPostgresStore(options) {
|
|
|
41
52
|
let closePromise;
|
|
42
53
|
const available = (requireInitialization = true) => {
|
|
43
54
|
if (closed)
|
|
44
|
-
throw new StorageError('STORE_CLOSED', 'Storage has been closed.');
|
|
55
|
+
throw new StorageError('STORE_CLOSED', 'Storage has been closed; open a new store to continue.');
|
|
45
56
|
if (requireInitialization && !initialized)
|
|
46
|
-
throw new StorageError('STORE_NOT_INITIALIZED', '
|
|
57
|
+
throw new StorageError('STORE_NOT_INITIALIZED', 'Storage is not initialized: call `await store.initialize()` before using it.');
|
|
47
58
|
};
|
|
48
59
|
const transaction = async (body) => {
|
|
49
60
|
let client;
|
|
@@ -148,7 +159,7 @@ export function createPostgresStore(options) {
|
|
|
148
159
|
if (!existing)
|
|
149
160
|
throw new StorageError('STORAGE_UNAVAILABLE', 'Existing submission is unavailable.');
|
|
150
161
|
if (existing.submission_digest !== digest)
|
|
151
|
-
throw new StorageError('CONFLICT', '
|
|
162
|
+
throw new StorageError('CONFLICT', 'This idempotency key was already used for a different submission (other input, definition or settings); resubmit exactly the same request, or use a new key.');
|
|
152
163
|
return { record: record(existing), created: false };
|
|
153
164
|
});
|
|
154
165
|
},
|
|
@@ -177,7 +188,7 @@ export function createPostgresStore(options) {
|
|
|
177
188
|
const version = integer(current.version);
|
|
178
189
|
const sequence = integer(current.event_sequence);
|
|
179
190
|
if (version !== input.expectedVersion)
|
|
180
|
-
throw new StorageError('CONFLICT', '
|
|
191
|
+
throw new StorageError('CONFLICT', 'The record changed after it was read (another writer updated it); read it again and retry.');
|
|
181
192
|
const updated = await client.query(`UPDATE ${aggregates} SET state = $1, version = $2, event_sequence = $3 WHERE scope = $4 AND id = $5 RETURNING *`, [JSON.stringify(input.state), nextCounter(version, 1), nextCounter(sequence, input.events.length), input.scope, input.id]);
|
|
182
193
|
await append(client, input.scope, input.id, sequence, input.events);
|
|
183
194
|
const row = updated.rows[0];
|
|
@@ -199,7 +210,7 @@ export function createPostgresStore(options) {
|
|
|
199
210
|
const version = integer(current.version);
|
|
200
211
|
const sequence = integer(current.event_sequence);
|
|
201
212
|
if (version !== input.expectedVersion || current.definition_hash !== input.expectedDefinitionHash)
|
|
202
|
-
throw new StorageError('CONFLICT', '
|
|
213
|
+
throw new StorageError('CONFLICT', 'The record or its pinned definition changed after it was read; read it again and retry.');
|
|
203
214
|
const updated = await client.query(`UPDATE ${aggregates} SET state = $1, definition_hash = $2, version = $3, event_sequence = $4 WHERE scope = $5 AND id = $6 RETURNING *`, [JSON.stringify(input.state), input.definitionHash, nextCounter(version, 1), nextCounter(sequence, input.events.length), input.scope, input.id]);
|
|
204
215
|
await append(client, input.scope, input.id, sequence, input.events);
|
|
205
216
|
const row = updated.rows[0];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postgres.js","sourceRoot":"","sources":["../src/postgres.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IA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ACjJ,CAAC,KAAK,EAAE,EAAE,EAAE,KAAK,EAAE,eAAe,CAAC,CAAC,CAAC;gBACvC,OAAO,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAe,EAAE,CAAC,CAAC,EAAE,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,IAAI,EAAE,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,EAAE,SAAS,EAAE,GAAG,CAAC,UAAU,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC,CAAC;YACzL,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBAAC,MAAM,WAAW,CAAC,KAAK,CAAC,CAAC;YAAC,CAAC;QAC/C,CAAC;QACD,KAAK,EAAE,GAAG,EAAE;YACV,IAAI,CAAC,YAAY,EAAE,CAAC;gBAAC,MAAM,GAAG,IAAI,CAAC;gBAAC,YAAY,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE,GAAG,MAAM,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;YAAC,CAAC;YACzH,OAAO,YAAY,CAAC;QACtB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { Pool, type PoolClient } from 'pg';\nimport { StorageError, storageError, type CreateRecord, type StoredRecord, type StoredEvent, type UpdateRecord, type MigrateRecord, type WorkflowGraphDiscoveryAggregateStore, type DurableBudgetAggregateStore, type WorkflowTreeDiscoveryAggregateStore, type MemoryIndexAggregateStore } from '@mayura/storage-contracts';\nimport {\n createCommand, updateCommand, migrateCommand, submissionDigest, nextCounter, identifier, cursor, storedObject, EVENT_PAGE_SIZE,\n SchedulerDatabase, type SchedulerBackend, type SchedulerSession, schedulerFacade,\n ScheduledWorkflowDatabase, scheduledFacade, workflowGraphFacade, initializeOwnership, ownedRun, writerRequired,\n ExecutionWaitDatabase, executionWaitFacade,\n workflowGraphDiscoveryFacade,\n DurableBudgetDatabase, durableBudgetFacade, MemoryIndexDatabase, memoryIndexFacade,\n WorkflowTreeDatabase, workflowTreeFacade, workflowTreeDiscoveryFacade,\n} from '@mayura/storage-sql/host';\n\nexport interface PostgresStoreOptions { readonly connectionString: string; readonly schema?: string }\ninterface Row {\n scope: string; id: string; idempotency_key: string; definition_hash: string;\n submission_digest: string; version: string; event_sequence: string; state: string;\n}\n\nfunction integer(value: string): number {\n const result = Number(value);\n if (!Number.isSafeInteger(result) || result < 0) throw new StorageError('STORAGE_UNAVAILABLE', 'Stored counter failed integrity validation.');\n return result;\n}\n\nfunction record(row: Row): StoredRecord {\n return {\n scope: row.scope, id: row.id, idempotencyKey: row.idempotency_key,\n definitionHash: row.definition_hash, version: integer(row.version), state: storedObject(JSON.parse(row.state)),\n };\n}\n\nfunction safeFailure(error: unknown): StorageError {\n if (typeof error === 'object' && error !== null && 'code' in error && error.code === '23505') {\n return new StorageError('CONFLICT', 'A scoped record or idempotency key already exists.');\n }\n return storageError(error);\n}\n\n/** Optional PostgreSQL adapter. A schema is isolated storage, not an authorization boundary. */\nexport function createPostgresStore(options: PostgresStoreOptions): WorkflowGraphDiscoveryAggregateStore & DurableBudgetAggregateStore & WorkflowTreeDiscoveryAggregateStore & MemoryIndexAggregateStore {\n if (typeof options.connectionString !== 'string' || options.connectionString.length === 0) {\n throw new StorageError('INVALID_INPUT', 'PostgreSQL connection string is required.');\n }\n const schema = options.schema ?? 'mayura';\n if (!/^[a-z_][a-z0-9_]{0,62}$/.test(schema)) {\n throw new StorageError('INVALID_INPUT', 'PostgreSQL schema must be a lowercase identifier of at most 63 characters.');\n }\n // The only interpolated SQL fragment is validated above; all record values are parameters.\n const prefix = `\"${schema}\"`;\n const aggregates = `${prefix}.mayura_aggregates`;\n const eventsTable = `${prefix}.mayura_events`;\n const pool = new Pool({ connectionString: options.connectionString, max: 8, connectionTimeoutMillis: 5_000, idleTimeoutMillis: 10_000 });\n // Idle-client errors must not become unhandled EventEmitter exceptions. Commands still fail closed.\n pool.on('error', () => { /* Driver detail is intentionally not exposed through the public adapter. */ });\n let initialized = false;\n let closed = false;\n let initializePromise: Promise<void> | undefined;\n let closePromise: Promise<void> | undefined;\n\n const available = (requireInitialization = true): void => {\n if (closed) throw new StorageError('STORE_CLOSED', 'Storage has been closed.');\n if (requireInitialization && !initialized) throw new StorageError('STORE_NOT_INITIALIZED', 'Initialize storage before accessing records.');\n };\n\n const transaction = async <T>(body: (client: PoolClient) => Promise<T>): Promise<T> => {\n let client: PoolClient | undefined;\n try {\n client = await pool.connect();\n await client.query('BEGIN');\n await client.query(\"SET LOCAL statement_timeout = '10s'\");\n await client.query(\"SET LOCAL lock_timeout = '5s'\");\n const result = await body(client);\n await client.query('COMMIT');\n return result;\n } catch (error) {\n if (client) { try { await client.query('ROLLBACK'); } catch { /* Original safe failure remains authoritative. */ } }\n throw safeFailure(error);\n } finally { client?.release(); }\n };\n\n const append = async (client: PoolClient, scope: string, id: string, sequence: number, events: CreateRecord['events']): Promise<void> => {\n for (const [index, event] of events.entries()) {\n await client.query(`INSERT INTO ${eventsTable} (scope, aggregate_id, sequence, type, data, created_at)\n VALUES ($1, $2, $3, $4, $5, transaction_timestamp())`,\n [scope, id, nextCounter(sequence, index + 1), event.type, JSON.stringify(event.data)]);\n }\n };\n\n const session = (client: PoolClient): SchedulerSession => ({\n query: async <T>(sql: string, parameters: readonly unknown[] = []) => {\n let ordinal = 0;\n // Scheduler SQL uses only positional ? placeholders, never interpolated application text.\n const result = await client.query(sql.replace(/\\?/g, () => `$${++ordinal}`), [...parameters]);\n return result.rows as T[];\n },\n });\n const backend: SchedulerBackend = { dialect:'postgres',prefix:`${prefix}.`,transaction:body => transaction(client => body(session(client))) };\n const schedulerDatabase = new SchedulerDatabase(backend);\n const workflowsDatabase = new ScheduledWorkflowDatabase(backend,schedulerDatabase);\n const executionWaitDatabase = new ExecutionWaitDatabase(backend,workflowsDatabase);\n const durableBudgetDatabase = new DurableBudgetDatabase(backend);\n const workflowTreeDatabase = new WorkflowTreeDatabase(backend,schedulerDatabase);\n const memoryDatabase = new MemoryIndexDatabase(backend);\n return {\n scheduler: schedulerFacade((method, input) => { available(); return schedulerDatabase.execute(method, input); }),\n workflows: scheduledFacade((method,input) => { available(); return workflowsDatabase.execute(method,input); }),\n workflowGraphs: workflowGraphFacade((method,input) => { available(); return workflowsDatabase.execute(method,input,2); }),\n workflowGraphDiscovery: workflowGraphDiscoveryFacade((method,input) => { available(); return workflowsDatabase.discover(method,input); }),\n executionWaits: executionWaitFacade((method,input) => { available(); return executionWaitDatabase.execute(method,input); }),\n durableBudgets: durableBudgetFacade((method,input) => { available(); return durableBudgetDatabase.execute(method,input); }),\n workflowTrees: workflowTreeFacade((method,input) => { available(); return workflowTreeDatabase.execute(method,input); }),\n workflowTreeDiscovery: workflowTreeDiscoveryFacade((method,input)=>{available();return workflowTreeDatabase.discover(method,input);}),\n memory: memoryIndexFacade((method,input) => { available(); return memoryDatabase.execute(method,input); }),\n initialize: async () => {\n available(false);\n if (!initializePromise) {\n initializePromise = transaction(async (client) => {\n // Serialize schema bootstrap across application instances without holding business locks.\n await client.query('SELECT pg_advisory_xact_lock(hashtext($1))', [`mayura:storage-schema:${schema}`]);\n await client.query(`CREATE SCHEMA IF NOT EXISTS ${prefix}`);\n await client.query(`CREATE TABLE IF NOT EXISTS ${prefix}.mayura_storage_meta (version INTEGER PRIMARY KEY CHECK(version = 1))`);\n await client.query(`INSERT INTO ${prefix}.mayura_storage_meta (version) VALUES (1) ON CONFLICT DO NOTHING`);\n const versions = await client.query<{ version: number }>(`SELECT version FROM ${prefix}.mayura_storage_meta`);\n if (versions.rows.length !== 1 || versions.rows[0]?.version !== 1) throw new StorageError('STORAGE_UNAVAILABLE', 'Unsupported storage schema version.');\n await client.query(`CREATE TABLE IF NOT EXISTS ${aggregates} (\n scope TEXT NOT NULL, id TEXT NOT NULL, idempotency_key TEXT NOT NULL,\n definition_hash TEXT NOT NULL, submission_digest TEXT NOT NULL,\n version BIGINT NOT NULL CHECK(version > 0), event_sequence BIGINT NOT NULL CHECK(event_sequence >= 0),\n state TEXT NOT NULL, PRIMARY KEY(scope, id), UNIQUE(scope, idempotency_key)\n )`);\n await client.query(`CREATE TABLE IF NOT EXISTS ${eventsTable} (\n scope TEXT NOT NULL, aggregate_id TEXT NOT NULL, sequence BIGINT NOT NULL CHECK(sequence > 0),\n type TEXT NOT NULL, data TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL,\n PRIMARY KEY(scope, aggregate_id, sequence),\n FOREIGN KEY(scope, aggregate_id) REFERENCES ${aggregates}(scope, id)\n )`);\n await initializeOwnership(session(client),backend);\n }).then(() => { initialized = true; }).catch((error: unknown) => { initializePromise = undefined; throw error; });\n }\n await initializePromise;\n },\n create: async (raw: CreateRecord) => {\n available();\n const input = createCommand(raw);\n const digest = submissionDigest(input);\n return transaction(async (client) => {\n const inserted = await client.query<Row>(`INSERT INTO ${aggregates}\n (scope, id, idempotency_key, definition_hash, submission_digest, version, event_sequence, state)\n VALUES ($1, $2, $3, $4, $5, 1, $6, $7)\n ON CONFLICT (scope, idempotency_key) DO NOTHING RETURNING *`,\n [input.scope, input.id, input.idempotencyKey, input.definitionHash, digest, input.events.length, JSON.stringify(input.state)]);\n const row = inserted.rows[0];\n if (row) {\n await append(client, input.scope, input.id, 0, input.events);\n return { record: record(row), created: true };\n }\n const found = await client.query<Row>(`SELECT * FROM ${aggregates} WHERE scope = $1 AND idempotency_key = $2`, [input.scope, input.idempotencyKey]);\n const existing = found.rows[0];\n if (!existing) throw new StorageError('STORAGE_UNAVAILABLE', 'Existing submission is unavailable.');\n if (existing.submission_digest !== digest) throw new StorageError('CONFLICT', 'Idempotency key already belongs to a different submission.');\n return { record: record(existing), created: false };\n });\n },\n read: async (scope, id) => {\n available(); identifier(scope, 'Scope'); identifier(id, 'Record ID');\n try {\n const result = await pool.query<Row>(`SELECT * FROM ${aggregates} WHERE scope = $1 AND id = $2`, [scope, id]);\n return result.rows[0] ? record(result.rows[0]) : undefined;\n } catch (error) { throw safeFailure(error); }\n },\n update: async (raw: UpdateRecord) => {\n available();\n const input = updateCommand(raw);\n return transaction(async (client) => {\n const selected = await client.query<Row>(`SELECT * FROM ${aggregates} WHERE scope = $1 AND id = $2 FOR UPDATE`, [input.scope, input.id]);\n const current = selected.rows[0];\n if (!current) throw new StorageError('NOT_FOUND', 'Record was not found in this scope.');\n if (await ownedRun(session(client),backend,input.scope,input.id)) writerRequired();\n const version = integer(current.version);\n const sequence = integer(current.event_sequence);\n if (version !== input.expectedVersion) throw new StorageError('CONFLICT', 'Record version has changed.');\n const updated = await client.query<Row>(`UPDATE ${aggregates} SET state = $1, version = $2, event_sequence = $3 WHERE scope = $4 AND id = $5 RETURNING *`,\n [JSON.stringify(input.state), nextCounter(version, 1), nextCounter(sequence, input.events.length), input.scope, input.id]);\n await append(client, input.scope, input.id, sequence, input.events);\n const row = updated.rows[0];\n if (!row) throw new StorageError('STORAGE_UNAVAILABLE', 'Updated record is unavailable.');\n return record(row);\n });\n },\n migrate: async (raw: MigrateRecord) => {\n available();\n const input = migrateCommand(raw);\n return transaction(async (client) => {\n const selected = await client.query<Row>(`SELECT * FROM ${aggregates} WHERE scope = $1 AND id = $2 FOR UPDATE`, [input.scope, input.id]);\n const current = selected.rows[0];\n if (!current) throw new StorageError('NOT_FOUND', 'Record was not found in this scope.');\n if (await ownedRun(session(client),backend,input.scope,input.id)) writerRequired();\n const version = integer(current.version); const sequence = integer(current.event_sequence);\n if (version !== input.expectedVersion || current.definition_hash !== input.expectedDefinitionHash) throw new StorageError('CONFLICT', 'Record version or definition has changed.');\n const updated = await client.query<Row>(`UPDATE ${aggregates} SET state = $1, definition_hash = $2, version = $3, event_sequence = $4 WHERE scope = $5 AND id = $6 RETURNING *`,\n [JSON.stringify(input.state), input.definitionHash, nextCounter(version, 1), nextCounter(sequence, input.events.length), input.scope, input.id]);\n await append(client, input.scope, input.id, sequence, input.events);\n const row = updated.rows[0];\n if (!row) throw new StorageError('STORAGE_UNAVAILABLE', 'Migrated record is unavailable.');\n return record(row);\n });\n },\n events: async (scope, id, after = 0) => {\n available(); identifier(scope, 'Scope'); identifier(id, 'Record ID'); cursor(after);\n try {\n const result = await pool.query<{ sequence: string; type: string; data: string; created_at: Date }>(\n `SELECT sequence, type, data, created_at FROM ${eventsTable} WHERE scope = $1 AND aggregate_id = $2 AND sequence > $3 ORDER BY sequence LIMIT $4`,\n [scope, id, after, EVENT_PAGE_SIZE]);\n return result.rows.map((row): StoredEvent => ({ sequence: integer(row.sequence), type: row.type, data: storedObject(JSON.parse(row.data)), createdAt: row.created_at.toISOString() }));\n } catch (error) { throw safeFailure(error); }\n },\n close: () => {\n if (!closePromise) { closed = true; closePromise = pool.end().catch((error: unknown) => { throw safeFailure(error); }); }\n return closePromise;\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"postgres.js","sourceRoot":"","sources":["../src/postgres.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAmB,MAAM,IAAI,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAE,YAAY,EAAwP,MAAM,2BAA2B,CAAC;AAC7T,OAAO,EACL,aAAa,EAAE,aAAa,EAAE,cAAc,EAAE,gBAAgB,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,EAAE,YAAY,EAAE,eAAe,EAC9H,iBAAiB,EAAgD,eAAe,EAChF,yBAAyB,EAAE,eAAe,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,QAAQ,EAAE,cAAc,EAC9G,qBAAqB,EAAE,mBAAmB,EAC1C,4BAA4B,EAC5B,qBAAqB,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,iBAAiB,EAClF,oBAAoB,EAAE,kBAAkB,EAAE,2BAA2B,GACtE,MAAM,0BAA0B,CAAC;AA0BlC,SAAS,OAAO,CAAC,KAAa;IAC5B,MAAM,MAAM,GAAG,MAAM,CAAC,K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C,CAAC,KAAc,EAAE,EAAE,GAAG,MAAM,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;YAAC,CAAC;YACzH,OAAO,YAAY,CAAC;QACtB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { Pool, type PoolClient } from 'pg';\nimport { StorageError, storageError, type CreateRecord, type StoredRecord, type StoredEvent, type UpdateRecord, type MigrateRecord, type WorkflowGraphDiscoveryAggregateStore, type DurableBudgetAggregateStore, type WorkflowTreeDiscoveryAggregateStore, type MemoryIndexAggregateStore } from '@mayura/storage-contracts';\nimport {\n createCommand, updateCommand, migrateCommand, submissionDigest, nextCounter, identifier, cursor, storedObject, EVENT_PAGE_SIZE,\n SchedulerDatabase, type SchedulerBackend, type SchedulerSession, schedulerFacade,\n ScheduledWorkflowDatabase, scheduledFacade, workflowGraphFacade, initializeOwnership, ownedRun, writerRequired,\n ExecutionWaitDatabase, executionWaitFacade,\n workflowGraphDiscoveryFacade,\n DurableBudgetDatabase, durableBudgetFacade, MemoryIndexDatabase, memoryIndexFacade,\n WorkflowTreeDatabase, workflowTreeFacade, workflowTreeDiscoveryFacade,\n} from '@mayura/storage-sql/host';\n\nexport interface PostgresStoreOptions {\n readonly connectionString: string;\n readonly schema?: string;\n /**\n * The connection pool. The defaults suit a long-running server: up to 8 connections, 5 s to connect, idle connections\n * closed after 10 s. On serverless functions, where every instance has its own pool, use `max: 1` or `2` and connect\n * through your provider's pooler. Mayura keeps no session state between transactions (each operation is one\n * transaction, with `SET LOCAL` settings and transaction-scoped locks), which is what transaction-mode poolers need.\n */\n readonly pool?: PostgresPoolOptions;\n}\nexport interface PostgresPoolOptions {\n /** Most connections open at once, 1 to 100. Default 8. */\n readonly max?: number;\n /** How long to wait for a connection, 100 to 120,000 ms. Default 5,000. */\n readonly connectionTimeoutMs?: number;\n /** How long an idle connection stays open, 100 to 3,600,000 ms. Default 10,000. */\n readonly idleTimeoutMs?: number;\n}\ninterface Row {\n scope: string; id: string; idempotency_key: string; definition_hash: string;\n submission_digest: string; version: string; event_sequence: string; state: string;\n}\n\nfunction integer(value: string): number {\n const result = Number(value);\n if (!Number.isSafeInteger(result) || result < 0) throw new StorageError('STORAGE_UNAVAILABLE', 'Stored counter failed integrity validation.');\n return result;\n}\n\nfunction record(row: Row): StoredRecord {\n return {\n scope: row.scope, id: row.id, idempotencyKey: row.idempotency_key,\n definitionHash: row.definition_hash, version: integer(row.version), state: storedObject(JSON.parse(row.state)),\n };\n}\n\nfunction safeFailure(error: unknown): StorageError {\n if (typeof error === 'object' && error !== null && 'code' in error && error.code === '23505') {\n return new StorageError('CONFLICT', 'A record with this ID or idempotency key already exists in this scope with different content; use a new ID or key.');\n }\n return storageError(error);\n}\n\n/** Optional PostgreSQL adapter. A schema is isolated storage, not an authorization boundary. */\nexport function createPostgresStore(options: PostgresStoreOptions): WorkflowGraphDiscoveryAggregateStore & DurableBudgetAggregateStore & WorkflowTreeDiscoveryAggregateStore & MemoryIndexAggregateStore {\n if (typeof options.connectionString !== 'string' || options.connectionString.length === 0) {\n throw new StorageError('INVALID_INPUT', 'PostgreSQL connection string is required.');\n }\n const schema = options.schema ?? 'mayura';\n if (!/^[a-z_][a-z0-9_]{0,62}$/.test(schema)) {\n throw new StorageError('INVALID_INPUT', 'PostgreSQL schema must be a lowercase identifier of at most 63 characters.');\n }\n // The only interpolated SQL fragment is validated above; all record values are parameters.\n const prefix = `\"${schema}\"`;\n const aggregates = `${prefix}.mayura_aggregates`;\n const eventsTable = `${prefix}.mayura_events`;\n const settings = options.pool === undefined ? {} : options.pool;\n if (settings === null || typeof settings !== 'object' || Object.keys(settings).some(key => !['max', 'connectionTimeoutMs', 'idleTimeoutMs'].includes(key))) {\n throw new StorageError('INVALID_INPUT', 'PostgreSQL pool options are max, connectionTimeoutMs and idleTimeoutMs.');\n }\n const max = settings.max ?? 8; const connectionTimeoutMs = settings.connectionTimeoutMs ?? 5_000; const idleTimeoutMs = settings.idleTimeoutMs ?? 10_000;\n for (const [name, value, minimum, maximum] of [['max', max, 1, 100], ['connectionTimeoutMs', connectionTimeoutMs, 100, 120_000], ['idleTimeoutMs', idleTimeoutMs, 100, 3_600_000]] as const) {\n if (!Number.isSafeInteger(value) || value < minimum || value > maximum) throw new StorageError('INVALID_INPUT', `PostgreSQL pool ${name} must be an integer from ${minimum} to ${maximum}.`);\n }\n const pool = new Pool({ connectionString: options.connectionString, max, connectionTimeoutMillis: connectionTimeoutMs, idleTimeoutMillis: idleTimeoutMs });\n // Idle-client errors must not become unhandled EventEmitter exceptions. Commands still fail closed.\n pool.on('error', () => { /* Driver detail is intentionally not exposed through the public adapter. */ });\n let initialized = false;\n let closed = false;\n let initializePromise: Promise<void> | undefined;\n let closePromise: Promise<void> | undefined;\n\n const available = (requireInitialization = true): void => {\n if (closed) throw new StorageError('STORE_CLOSED', 'Storage has been closed; open a new store to continue.');\n if (requireInitialization && !initialized) throw new StorageError('STORE_NOT_INITIALIZED', 'Storage is not initialized: call `await store.initialize()` before using it.');\n };\n\n const transaction = async <T>(body: (client: PoolClient) => Promise<T>): Promise<T> => {\n let client: PoolClient | undefined;\n try {\n client = await pool.connect();\n await client.query('BEGIN');\n await client.query(\"SET LOCAL statement_timeout = '10s'\");\n await client.query(\"SET LOCAL lock_timeout = '5s'\");\n const result = await body(client);\n await client.query('COMMIT');\n return result;\n } catch (error) {\n if (client) { try { await client.query('ROLLBACK'); } catch { /* Original safe failure remains authoritative. */ } }\n throw safeFailure(error);\n } finally { client?.release(); }\n };\n\n const append = async (client: PoolClient, scope: string, id: string, sequence: number, events: CreateRecord['events']): Promise<void> => {\n for (const [index, event] of events.entries()) {\n await client.query(`INSERT INTO ${eventsTable} (scope, aggregate_id, sequence, type, data, created_at)\n VALUES ($1, $2, $3, $4, $5, transaction_timestamp())`,\n [scope, id, nextCounter(sequence, index + 1), event.type, JSON.stringify(event.data)]);\n }\n };\n\n const session = (client: PoolClient): SchedulerSession => ({\n query: async <T>(sql: string, parameters: readonly unknown[] = []) => {\n let ordinal = 0;\n // Scheduler SQL uses only positional ? placeholders, never interpolated application text.\n const result = await client.query(sql.replace(/\\?/g, () => `$${++ordinal}`), [...parameters]);\n return result.rows as T[];\n },\n });\n const backend: SchedulerBackend = { dialect:'postgres',prefix:`${prefix}.`,transaction:body => transaction(client => body(session(client))) };\n const schedulerDatabase = new SchedulerDatabase(backend);\n const workflowsDatabase = new ScheduledWorkflowDatabase(backend,schedulerDatabase);\n const executionWaitDatabase = new ExecutionWaitDatabase(backend,workflowsDatabase);\n const durableBudgetDatabase = new DurableBudgetDatabase(backend);\n const workflowTreeDatabase = new WorkflowTreeDatabase(backend,schedulerDatabase);\n const memoryDatabase = new MemoryIndexDatabase(backend);\n return {\n scheduler: schedulerFacade((method, input) => { available(); return schedulerDatabase.execute(method, input); }),\n workflows: scheduledFacade((method,input) => { available(); return workflowsDatabase.execute(method,input); }),\n workflowGraphs: workflowGraphFacade((method,input) => { available(); return workflowsDatabase.execute(method,input,2); }),\n workflowGraphDiscovery: workflowGraphDiscoveryFacade((method,input) => { available(); return workflowsDatabase.discover(method,input); }),\n executionWaits: executionWaitFacade((method,input) => { available(); return executionWaitDatabase.execute(method,input); }),\n durableBudgets: durableBudgetFacade((method,input) => { available(); return durableBudgetDatabase.execute(method,input); }),\n workflowTrees: workflowTreeFacade((method,input) => { available(); return workflowTreeDatabase.execute(method,input); }),\n workflowTreeDiscovery: workflowTreeDiscoveryFacade((method,input)=>{available();return workflowTreeDatabase.discover(method,input);}),\n memory: memoryIndexFacade((method,input) => { available(); return memoryDatabase.execute(method,input); }),\n initialize: async () => {\n available(false);\n if (!initializePromise) {\n initializePromise = transaction(async (client) => {\n // Serialize schema bootstrap across application instances without holding business locks.\n await client.query('SELECT pg_advisory_xact_lock(hashtext($1))', [`mayura:storage-schema:${schema}`]);\n await client.query(`CREATE SCHEMA IF NOT EXISTS ${prefix}`);\n await client.query(`CREATE TABLE IF NOT EXISTS ${prefix}.mayura_storage_meta (version INTEGER PRIMARY KEY CHECK(version = 1))`);\n await client.query(`INSERT INTO ${prefix}.mayura_storage_meta (version) VALUES (1) ON CONFLICT DO NOTHING`);\n const versions = await client.query<{ version: number }>(`SELECT version FROM ${prefix}.mayura_storage_meta`);\n if (versions.rows.length !== 1 || versions.rows[0]?.version !== 1) throw new StorageError('STORAGE_UNAVAILABLE', 'Unsupported storage schema version.');\n await client.query(`CREATE TABLE IF NOT EXISTS ${aggregates} (\n scope TEXT NOT NULL, id TEXT NOT NULL, idempotency_key TEXT NOT NULL,\n definition_hash TEXT NOT NULL, submission_digest TEXT NOT NULL,\n version BIGINT NOT NULL CHECK(version > 0), event_sequence BIGINT NOT NULL CHECK(event_sequence >= 0),\n state TEXT NOT NULL, PRIMARY KEY(scope, id), UNIQUE(scope, idempotency_key)\n )`);\n await client.query(`CREATE TABLE IF NOT EXISTS ${eventsTable} (\n scope TEXT NOT NULL, aggregate_id TEXT NOT NULL, sequence BIGINT NOT NULL CHECK(sequence > 0),\n type TEXT NOT NULL, data TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL,\n PRIMARY KEY(scope, aggregate_id, sequence),\n FOREIGN KEY(scope, aggregate_id) REFERENCES ${aggregates}(scope, id)\n )`);\n await initializeOwnership(session(client),backend);\n }).then(() => { initialized = true; }).catch((error: unknown) => { initializePromise = undefined; throw error; });\n }\n await initializePromise;\n },\n create: async (raw: CreateRecord) => {\n available();\n const input = createCommand(raw);\n const digest = submissionDigest(input);\n return transaction(async (client) => {\n const inserted = await client.query<Row>(`INSERT INTO ${aggregates}\n (scope, id, idempotency_key, definition_hash, submission_digest, version, event_sequence, state)\n VALUES ($1, $2, $3, $4, $5, 1, $6, $7)\n ON CONFLICT (scope, idempotency_key) DO NOTHING RETURNING *`,\n [input.scope, input.id, input.idempotencyKey, input.definitionHash, digest, input.events.length, JSON.stringify(input.state)]);\n const row = inserted.rows[0];\n if (row) {\n await append(client, input.scope, input.id, 0, input.events);\n return { record: record(row), created: true };\n }\n const found = await client.query<Row>(`SELECT * FROM ${aggregates} WHERE scope = $1 AND idempotency_key = $2`, [input.scope, input.idempotencyKey]);\n const existing = found.rows[0];\n if (!existing) throw new StorageError('STORAGE_UNAVAILABLE', 'Existing submission is unavailable.');\n if (existing.submission_digest !== digest) throw new StorageError('CONFLICT', 'This idempotency key was already used for a different submission (other input, definition or settings); resubmit exactly the same request, or use a new key.');\n return { record: record(existing), created: false };\n });\n },\n read: async (scope, id) => {\n available(); identifier(scope, 'Scope'); identifier(id, 'Record ID');\n try {\n const result = await pool.query<Row>(`SELECT * FROM ${aggregates} WHERE scope = $1 AND id = $2`, [scope, id]);\n return result.rows[0] ? record(result.rows[0]) : undefined;\n } catch (error) { throw safeFailure(error); }\n },\n update: async (raw: UpdateRecord) => {\n available();\n const input = updateCommand(raw);\n return transaction(async (client) => {\n const selected = await client.query<Row>(`SELECT * FROM ${aggregates} WHERE scope = $1 AND id = $2 FOR UPDATE`, [input.scope, input.id]);\n const current = selected.rows[0];\n if (!current) throw new StorageError('NOT_FOUND', 'Record was not found in this scope.');\n if (await ownedRun(session(client),backend,input.scope,input.id)) writerRequired();\n const version = integer(current.version);\n const sequence = integer(current.event_sequence);\n if (version !== input.expectedVersion) throw new StorageError('CONFLICT', 'The record changed after it was read (another writer updated it); read it again and retry.');\n const updated = await client.query<Row>(`UPDATE ${aggregates} SET state = $1, version = $2, event_sequence = $3 WHERE scope = $4 AND id = $5 RETURNING *`,\n [JSON.stringify(input.state), nextCounter(version, 1), nextCounter(sequence, input.events.length), input.scope, input.id]);\n await append(client, input.scope, input.id, sequence, input.events);\n const row = updated.rows[0];\n if (!row) throw new StorageError('STORAGE_UNAVAILABLE', 'Updated record is unavailable.');\n return record(row);\n });\n },\n migrate: async (raw: MigrateRecord) => {\n available();\n const input = migrateCommand(raw);\n return transaction(async (client) => {\n const selected = await client.query<Row>(`SELECT * FROM ${aggregates} WHERE scope = $1 AND id = $2 FOR UPDATE`, [input.scope, input.id]);\n const current = selected.rows[0];\n if (!current) throw new StorageError('NOT_FOUND', 'Record was not found in this scope.');\n if (await ownedRun(session(client),backend,input.scope,input.id)) writerRequired();\n const version = integer(current.version); const sequence = integer(current.event_sequence);\n if (version !== input.expectedVersion || current.definition_hash !== input.expectedDefinitionHash) throw new StorageError('CONFLICT', 'The record or its pinned definition changed after it was read; read it again and retry.');\n const updated = await client.query<Row>(`UPDATE ${aggregates} SET state = $1, definition_hash = $2, version = $3, event_sequence = $4 WHERE scope = $5 AND id = $6 RETURNING *`,\n [JSON.stringify(input.state), input.definitionHash, nextCounter(version, 1), nextCounter(sequence, input.events.length), input.scope, input.id]);\n await append(client, input.scope, input.id, sequence, input.events);\n const row = updated.rows[0];\n if (!row) throw new StorageError('STORAGE_UNAVAILABLE', 'Migrated record is unavailable.');\n return record(row);\n });\n },\n events: async (scope, id, after = 0) => {\n available(); identifier(scope, 'Scope'); identifier(id, 'Record ID'); cursor(after);\n try {\n const result = await pool.query<{ sequence: string; type: string; data: string; created_at: Date }>(\n `SELECT sequence, type, data, created_at FROM ${eventsTable} WHERE scope = $1 AND aggregate_id = $2 AND sequence > $3 ORDER BY sequence LIMIT $4`,\n [scope, id, after, EVENT_PAGE_SIZE]);\n return result.rows.map((row): StoredEvent => ({ sequence: integer(row.sequence), type: row.type, data: storedObject(JSON.parse(row.data)), createdAt: row.created_at.toISOString() }));\n } catch (error) { throw safeFailure(error); }\n },\n close: () => {\n if (!closePromise) { closed = true; closePromise = pool.end().catch((error: unknown) => { throw safeFailure(error); }); }\n return closePromise;\n },\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export { createPostgresStore, type PostgresStoreOptions } from './postgres.js';
|
|
1
|
+
export { createPostgresStore, type PostgresPoolOptions, type PostgresStoreOptions } from './postgres.js';
|
|
@@ -10,7 +10,25 @@ import {
|
|
|
10
10
|
WorkflowTreeDatabase, workflowTreeFacade, workflowTreeDiscoveryFacade,
|
|
11
11
|
} from '@mayura/storage-sql/host';
|
|
12
12
|
|
|
13
|
-
export interface PostgresStoreOptions {
|
|
13
|
+
export interface PostgresStoreOptions {
|
|
14
|
+
readonly connectionString: string;
|
|
15
|
+
readonly schema?: string;
|
|
16
|
+
/**
|
|
17
|
+
* The connection pool. The defaults suit a long-running server: up to 8 connections, 5 s to connect, idle connections
|
|
18
|
+
* closed after 10 s. On serverless functions, where every instance has its own pool, use `max: 1` or `2` and connect
|
|
19
|
+
* through your provider's pooler. Mayura keeps no session state between transactions (each operation is one
|
|
20
|
+
* transaction, with `SET LOCAL` settings and transaction-scoped locks), which is what transaction-mode poolers need.
|
|
21
|
+
*/
|
|
22
|
+
readonly pool?: PostgresPoolOptions;
|
|
23
|
+
}
|
|
24
|
+
export interface PostgresPoolOptions {
|
|
25
|
+
/** Most connections open at once, 1 to 100. Default 8. */
|
|
26
|
+
readonly max?: number;
|
|
27
|
+
/** How long to wait for a connection, 100 to 120,000 ms. Default 5,000. */
|
|
28
|
+
readonly connectionTimeoutMs?: number;
|
|
29
|
+
/** How long an idle connection stays open, 100 to 3,600,000 ms. Default 10,000. */
|
|
30
|
+
readonly idleTimeoutMs?: number;
|
|
31
|
+
}
|
|
14
32
|
interface Row {
|
|
15
33
|
scope: string; id: string; idempotency_key: string; definition_hash: string;
|
|
16
34
|
submission_digest: string; version: string; event_sequence: string; state: string;
|
|
@@ -31,7 +49,7 @@ function record(row: Row): StoredRecord {
|
|
|
31
49
|
|
|
32
50
|
function safeFailure(error: unknown): StorageError {
|
|
33
51
|
if (typeof error === 'object' && error !== null && 'code' in error && error.code === '23505') {
|
|
34
|
-
return new StorageError('CONFLICT', 'A
|
|
52
|
+
return new StorageError('CONFLICT', 'A record with this ID or idempotency key already exists in this scope with different content; use a new ID or key.');
|
|
35
53
|
}
|
|
36
54
|
return storageError(error);
|
|
37
55
|
}
|
|
@@ -49,7 +67,15 @@ export function createPostgresStore(options: PostgresStoreOptions): WorkflowGrap
|
|
|
49
67
|
const prefix = `"${schema}"`;
|
|
50
68
|
const aggregates = `${prefix}.mayura_aggregates`;
|
|
51
69
|
const eventsTable = `${prefix}.mayura_events`;
|
|
52
|
-
const
|
|
70
|
+
const settings = options.pool === undefined ? {} : options.pool;
|
|
71
|
+
if (settings === null || typeof settings !== 'object' || Object.keys(settings).some(key => !['max', 'connectionTimeoutMs', 'idleTimeoutMs'].includes(key))) {
|
|
72
|
+
throw new StorageError('INVALID_INPUT', 'PostgreSQL pool options are max, connectionTimeoutMs and idleTimeoutMs.');
|
|
73
|
+
}
|
|
74
|
+
const max = settings.max ?? 8; const connectionTimeoutMs = settings.connectionTimeoutMs ?? 5_000; const idleTimeoutMs = settings.idleTimeoutMs ?? 10_000;
|
|
75
|
+
for (const [name, value, minimum, maximum] of [['max', max, 1, 100], ['connectionTimeoutMs', connectionTimeoutMs, 100, 120_000], ['idleTimeoutMs', idleTimeoutMs, 100, 3_600_000]] as const) {
|
|
76
|
+
if (!Number.isSafeInteger(value) || value < minimum || value > maximum) throw new StorageError('INVALID_INPUT', `PostgreSQL pool ${name} must be an integer from ${minimum} to ${maximum}.`);
|
|
77
|
+
}
|
|
78
|
+
const pool = new Pool({ connectionString: options.connectionString, max, connectionTimeoutMillis: connectionTimeoutMs, idleTimeoutMillis: idleTimeoutMs });
|
|
53
79
|
// Idle-client errors must not become unhandled EventEmitter exceptions. Commands still fail closed.
|
|
54
80
|
pool.on('error', () => { /* Driver detail is intentionally not exposed through the public adapter. */ });
|
|
55
81
|
let initialized = false;
|
|
@@ -58,8 +84,8 @@ export function createPostgresStore(options: PostgresStoreOptions): WorkflowGrap
|
|
|
58
84
|
let closePromise: Promise<void> | undefined;
|
|
59
85
|
|
|
60
86
|
const available = (requireInitialization = true): void => {
|
|
61
|
-
if (closed) throw new StorageError('STORE_CLOSED', 'Storage has been closed.');
|
|
62
|
-
if (requireInitialization && !initialized) throw new StorageError('STORE_NOT_INITIALIZED', '
|
|
87
|
+
if (closed) throw new StorageError('STORE_CLOSED', 'Storage has been closed; open a new store to continue.');
|
|
88
|
+
if (requireInitialization && !initialized) throw new StorageError('STORE_NOT_INITIALIZED', 'Storage is not initialized: call `await store.initialize()` before using it.');
|
|
63
89
|
};
|
|
64
90
|
|
|
65
91
|
const transaction = async <T>(body: (client: PoolClient) => Promise<T>): Promise<T> => {
|
|
@@ -157,7 +183,7 @@ export function createPostgresStore(options: PostgresStoreOptions): WorkflowGrap
|
|
|
157
183
|
const found = await client.query<Row>(`SELECT * FROM ${aggregates} WHERE scope = $1 AND idempotency_key = $2`, [input.scope, input.idempotencyKey]);
|
|
158
184
|
const existing = found.rows[0];
|
|
159
185
|
if (!existing) throw new StorageError('STORAGE_UNAVAILABLE', 'Existing submission is unavailable.');
|
|
160
|
-
if (existing.submission_digest !== digest) throw new StorageError('CONFLICT', '
|
|
186
|
+
if (existing.submission_digest !== digest) throw new StorageError('CONFLICT', 'This idempotency key was already used for a different submission (other input, definition or settings); resubmit exactly the same request, or use a new key.');
|
|
161
187
|
return { record: record(existing), created: false };
|
|
162
188
|
});
|
|
163
189
|
},
|
|
@@ -178,7 +204,7 @@ export function createPostgresStore(options: PostgresStoreOptions): WorkflowGrap
|
|
|
178
204
|
if (await ownedRun(session(client),backend,input.scope,input.id)) writerRequired();
|
|
179
205
|
const version = integer(current.version);
|
|
180
206
|
const sequence = integer(current.event_sequence);
|
|
181
|
-
if (version !== input.expectedVersion) throw new StorageError('CONFLICT', '
|
|
207
|
+
if (version !== input.expectedVersion) throw new StorageError('CONFLICT', 'The record changed after it was read (another writer updated it); read it again and retry.');
|
|
182
208
|
const updated = await client.query<Row>(`UPDATE ${aggregates} SET state = $1, version = $2, event_sequence = $3 WHERE scope = $4 AND id = $5 RETURNING *`,
|
|
183
209
|
[JSON.stringify(input.state), nextCounter(version, 1), nextCounter(sequence, input.events.length), input.scope, input.id]);
|
|
184
210
|
await append(client, input.scope, input.id, sequence, input.events);
|
|
@@ -196,7 +222,7 @@ export function createPostgresStore(options: PostgresStoreOptions): WorkflowGrap
|
|
|
196
222
|
if (!current) throw new StorageError('NOT_FOUND', 'Record was not found in this scope.');
|
|
197
223
|
if (await ownedRun(session(client),backend,input.scope,input.id)) writerRequired();
|
|
198
224
|
const version = integer(current.version); const sequence = integer(current.event_sequence);
|
|
199
|
-
if (version !== input.expectedVersion || current.definition_hash !== input.expectedDefinitionHash) throw new StorageError('CONFLICT', '
|
|
225
|
+
if (version !== input.expectedVersion || current.definition_hash !== input.expectedDefinitionHash) throw new StorageError('CONFLICT', 'The record or its pinned definition changed after it was read; read it again and retry.');
|
|
200
226
|
const updated = await client.query<Row>(`UPDATE ${aggregates} SET state = $1, definition_hash = $2, version = $3, event_sequence = $4 WHERE scope = $5 AND id = $6 RETURNING *`,
|
|
201
227
|
[JSON.stringify(input.state), input.definitionHash, nextCounter(version, 1), nextCounter(sequence, input.events.length), input.scope, input.id]);
|
|
202
228
|
await append(client, input.scope, input.id, sequence, input.events);
|
|
@@ -62,7 +62,7 @@ export async function createAggregate(tx, backend, input, now) {
|
|
|
62
62
|
}
|
|
63
63
|
const existing = (await tx.query(`SELECT * FROM ${backend.prefix}mayura_aggregates WHERE scope = ? AND idempotency_key = ?${lockSql(backend)}`, [input.scope, input.idempotencyKey]))[0];
|
|
64
64
|
if (!existing || existing.submission_digest !== digest)
|
|
65
|
-
throw new StorageError('CONFLICT', '
|
|
65
|
+
throw new StorageError('CONFLICT', 'This idempotency key was already used for a different submission (other input, definition or settings); resubmit exactly the same request, or use a new key.');
|
|
66
66
|
return { row: existing, created: false };
|
|
67
67
|
}
|
|
68
68
|
/** Only internal semantic reducers call this after the aggregate lock; it is not a public replacement-state API. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"aggregate-session.js","sourceRoot":"","sources":["../src/aggregate-session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAA+D,MAAM,gBAAgB,CAAC;AAC3G,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAO1F,MAAM,UAAU,aAAa,CAAC,KAAsB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AyG,EAC7K,CAAC,IAAI,CAAC,SAAS,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC,EAAE,OAAO,EAAE,WAAW,CAAC,QAAQ,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,CAAC,KAAK,EAAE,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/G,IAAI,CAAC,OAAO;QAAE,MAAM,IAAI,YAAY,CAAC,qBAAqB,EAAE,+BAA+B,CAAC,CAAC;IAC7F,MAAM,qBAAqB,CAAC,EAAE,EAAE,OAAO,EAAE,GAAG,CAAC,KAAK,EAAE,GAAG,CAAC,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC;IAAC,OAAO,OAAO,CAAC;AACrG,CAAC","sourcesContent":["import { StorageError, type CreateRecord, type StoredRecord, type StoredEventInput } from './contracts.js';\nimport { identifier, nextCounter, storedObject, submissionDigest } from './validation.js';\nimport type { SchedulerBackend, SchedulerSession } from './scheduler-database.js';\n\nexport interface AggregateRow {\n scope: string; id: string; idempotency_key: string; definition_hash: string; submission_digest: string;\n version: number | string; event_sequence: number | string; state: string;\n}\nexport function storedInteger(value: number | string): number {\n const result = Number(value);\n if (!Number.isSafeInteger(result) || result < 0) throw new StorageError('STORAGE_UNAVAILABLE', 'Stored aggregate counter is invalid.');\n return result;\n}\nexport function aggregateRecord(row: AggregateRow): StoredRecord {\n try {\n const version = storedInteger(row.version); if (version === 0) throw new Error();\n return { scope: row.scope, id: row.id, idempotencyKey: row.idempotency_key, definitionHash: row.definition_hash,\n version, state: storedObject(JSON.parse(row.state)) };\n }\n catch { throw new StorageError('STORAGE_UNAVAILABLE', 'Stored aggregate failed integrity validation.'); }\n}\nexport function writerRequired(): never { throw new StorageError('SCHEDULED_WRITER_REQUIRED', 'This run requires its scheduled workflow writer.'); }\nexport function lockSql(backend: SchedulerBackend, skip = false): string { return backend.dialect === 'postgres' ? ` FOR UPDATE${skip ? ' SKIP LOCKED' : ''}` : ''; }\n\n/** Locks the identity even before its aggregate exists; SQLite's writer transaction already does this. */\nexport async function lockRunIdentity(tx: SchedulerSession, backend: SchedulerBackend, scope: string, id: string): Promise<void> {\n if (backend.dialect === 'postgres') await tx.query('SELECT pg_advisory_xact_lock(hashtext(?))', [JSON.stringify(['mayura:workflow-run:v1', backend.prefix, scope, id])]);\n}\nexport async function loadAggregate(tx: SchedulerSession, backend: SchedulerBackend, scope: string, id: string, skip = false): Promise<AggregateRow | undefined> {\n return (await tx.query<AggregateRow>(`SELECT * FROM ${backend.prefix}mayura_aggregates WHERE scope = ? AND id = ?${lockSql(backend, skip)}`, [scope, id]))[0];\n}\nexport async function ownedRun(tx: SchedulerSession, backend: SchedulerBackend, scope: string, id: string): Promise<boolean> {\n return (await tx.query(`SELECT aggregate_id FROM ${backend.prefix}mayura_workflow_owners WHERE scope = ? AND aggregate_id = ?`, [scope, id])).length !== 0;\n}\n/** Always available after ordinary store initialization, even before the workflow capability is used. */\nexport async function initializeOwnership(tx: SchedulerSession, backend: SchedulerBackend): Promise<void> {\n await tx.query(`CREATE TABLE IF NOT EXISTS ${backend.prefix}mayura_workflow_owners (\n scope TEXT NOT NULL, aggregate_id TEXT NOT NULL, profile INTEGER NOT NULL CHECK(profile > 0),\n aggregate_version BIGINT NOT NULL CHECK(aggregate_version > 0), definition_hash TEXT NOT NULL,\n policy_hash TEXT NOT NULL, resource_hash TEXT NOT NULL, data TEXT NOT NULL,\n PRIMARY KEY(scope, aggregate_id), FOREIGN KEY(scope, aggregate_id) REFERENCES ${backend.prefix}mayura_aggregates(scope, id))`);\n}\nexport async function storageClock(tx: SchedulerSession, backend: SchedulerBackend, floor = 0): Promise<number> {\n const sql = backend.dialect === 'postgres' ? 'SELECT floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint AS now_ms'\n : \"SELECT CAST(strftime('%s','now') AS INTEGER) * 1000 + CAST(substr(strftime('%f','now'),4,3) AS INTEGER) AS now_ms\";\n const value = (await tx.query<{ now_ms: number | string }>(sql))[0]?.now_ms;\n if (value === undefined) throw new StorageError('STORAGE_UNAVAILABLE', 'Storage time is unavailable.');\n return Math.max(floor, storedInteger(value));\n}\nexport async function appendAggregateEvents(tx: SchedulerSession, backend: SchedulerBackend, scope: string, id: string, sequence: number, events: readonly StoredEventInput[], now: number): Promise<void> {\n const time = new Date(now).toISOString();\n for (const [index, event] of events.entries()) await tx.query(`INSERT INTO ${backend.prefix}mayura_events (scope, aggregate_id, sequence, type, data, created_at) VALUES (?, ?, ?, ?, ?, ?)`,\n [scope, id, nextCounter(sequence, index + 1), identifier(event.type, 'Event'), JSON.stringify(event.data), time]);\n}\nexport async function createAggregate(tx: SchedulerSession, backend: SchedulerBackend, input: CreateRecord, now: number): Promise<{ row: AggregateRow; created: boolean }> {\n const digest = submissionDigest(input);\n const rows = await tx.query<AggregateRow>(`INSERT INTO ${backend.prefix}mayura_aggregates (scope, id, idempotency_key, definition_hash, submission_digest, version, event_sequence, state)\n VALUES (?, ?, ?, ?, ?, 1, ?, ?) ON CONFLICT (scope, idempotency_key) DO NOTHING RETURNING *`,\n [input.scope, input.id, input.idempotencyKey, input.definitionHash, digest, input.events.length, JSON.stringify(input.state)]);\n if (rows[0]) { await appendAggregateEvents(tx, backend, input.scope, input.id, 0, input.events, now); return { row: rows[0], created: true }; }\n const existing = (await tx.query<AggregateRow>(`SELECT * FROM ${backend.prefix}mayura_aggregates WHERE scope = ? AND idempotency_key = ?${lockSql(backend)}`, [input.scope, input.idempotencyKey]))[0];\n if (!existing || existing.submission_digest !== digest) throw new StorageError('CONFLICT', 'Submission identity belongs to different content.');\n return { row: existing, created: false };\n}\n/** Only internal semantic reducers call this after the aggregate lock; it is not a public replacement-state API. */\nexport async function writeAggregate(tx: SchedulerSession, backend: SchedulerBackend, row: AggregateRow, state: StoredRecord['state'], events: readonly StoredEventInput[], now: number): Promise<AggregateRow> {\n const version = nextCounter(storedInteger(row.version), 1); const sequence = storedInteger(row.event_sequence);\n const updated = (await tx.query<AggregateRow>(`UPDATE ${backend.prefix}mayura_aggregates SET state = ?, version = ?, event_sequence = ? WHERE scope = ? AND id = ? RETURNING *`,\n [JSON.stringify(storedObject(state)), version, nextCounter(sequence, events.length), row.scope, row.id]))[0];\n if (!updated) throw new StorageError('STORAGE_UNAVAILABLE', 'Locked aggregate disappeared.');\n await appendAggregateEvents(tx, backend, row.scope, row.id, sequence, events, now); return updated;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"aggregate-session.js","sourceRoot":"","sources":["../src/aggregate-session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAA+D,MAAM,gBAAgB,CAAC;AAC3G,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAO1F,MAAM,UAAU,aAAa,CAAC,KAAsB;IAClD,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;IAC7B,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,MAAM,GAAG,CAAC;QAAE,MAAM,IAAI,YAAY,CAAC,qBAAqB,EAAE,sCAAsC,CAAC,CAAC;IACvI,OAAO,MAAM,CAAC;AAChB,CAAC;AACD,MAAM,UAAU,eAAe,CAAC,GAAiB;IAC/C,IAAI,CAAC;QACH,MAAM,OAAO,GAAG,aAAa,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QAAC,IAAI,OAAO,KAAK,CAAC;YAAE,MAAM,IAAI,KAAK,EAAE,CAAC;QACjF,OAAO,EAAE,KAAK,EAAE,GAAG,CAAC,KAAK,EAAE,EAAE,EAAE,GAAG,CAAC,EAAE,EAAE,cAAc,EAAE,GAAG,CAAC,eAAe,EAAE,cAAc,EAAE,GAAG,CAAC,eAAe;YAC7G,OAAO,EAAE,KAAK,EAAE,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC;IAC1D,CAAC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;QAAE,MAAM,IAAI,YAAY,CAAC,UAAU,EAAE,8JAA8J,CAAC,CAAC;IAC3P,OAAO,EAAE,GAAG,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAC3C,CAAC;AACD,oHAAoH;AACpH,MAAM,CAAC,KAAK,UAAU,cAAc,CAAC,EAAoB,EAAE,OAAyB,EAAE,GAAiB,EAAE,KAA4B,EAAE,MAAmC,EAAE,GAAW;IACrL,MAAM,OAAO,GAAG,WAAW,CAAC,aAAa,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC;IAAC,MAAM,QAAQ,GAAG,aAAa,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;IAC/G,MAAM,OAAO,GAAG,CAAC,MAAM,EAAE,CAAC,KAAK,CAAe,UAAU,OAAO,CAAC,MAAM,yGAAyG,EAC7K,CAAC,IAAI,CAAC,SAAS,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC,EAAE,OAAO,EAAE,WAAW,CAAC,QAAQ,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,CAAC,KAAK,EAAE,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/G,IAAI,CAAC,OAAO;QAAE,MAAM,IAAI,YAAY,CAAC,qBAAqB,EAAE,+BAA+B,CAAC,CAAC;IAC7F,MAAM,qBAAqB,CAAC,EAAE,EAAE,OAAO,EAAE,GAAG,CAAC,KAAK,EAAE,GAAG,CAAC,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC;IAAC,OAAO,OAAO,CAAC;AACrG,CAAC","sourcesContent":["import { StorageError, type CreateRecord, type StoredRecord, type StoredEventInput } from './contracts.js';\nimport { identifier, nextCounter, storedObject, submissionDigest } from './validation.js';\nimport type { SchedulerBackend, SchedulerSession } from './scheduler-database.js';\n\nexport interface AggregateRow {\n scope: string; id: string; idempotency_key: string; definition_hash: string; submission_digest: string;\n version: number | string; event_sequence: number | string; state: string;\n}\nexport function storedInteger(value: number | string): number {\n const result = Number(value);\n if (!Number.isSafeInteger(result) || result < 0) throw new StorageError('STORAGE_UNAVAILABLE', 'Stored aggregate counter is invalid.');\n return result;\n}\nexport function aggregateRecord(row: AggregateRow): StoredRecord {\n try {\n const version = storedInteger(row.version); if (version === 0) throw new Error();\n return { scope: row.scope, id: row.id, idempotencyKey: row.idempotency_key, definitionHash: row.definition_hash,\n version, state: storedObject(JSON.parse(row.state)) };\n }\n catch { throw new StorageError('STORAGE_UNAVAILABLE', 'Stored aggregate failed integrity validation.'); }\n}\nexport function writerRequired(): never { throw new StorageError('SCHEDULED_WRITER_REQUIRED', 'This run requires its scheduled workflow writer.'); }\nexport function lockSql(backend: SchedulerBackend, skip = false): string { return backend.dialect === 'postgres' ? ` FOR UPDATE${skip ? ' SKIP LOCKED' : ''}` : ''; }\n\n/** Locks the identity even before its aggregate exists; SQLite's writer transaction already does this. */\nexport async function lockRunIdentity(tx: SchedulerSession, backend: SchedulerBackend, scope: string, id: string): Promise<void> {\n if (backend.dialect === 'postgres') await tx.query('SELECT pg_advisory_xact_lock(hashtext(?))', [JSON.stringify(['mayura:workflow-run:v1', backend.prefix, scope, id])]);\n}\nexport async function loadAggregate(tx: SchedulerSession, backend: SchedulerBackend, scope: string, id: string, skip = false): Promise<AggregateRow | undefined> {\n return (await tx.query<AggregateRow>(`SELECT * FROM ${backend.prefix}mayura_aggregates WHERE scope = ? AND id = ?${lockSql(backend, skip)}`, [scope, id]))[0];\n}\nexport async function ownedRun(tx: SchedulerSession, backend: SchedulerBackend, scope: string, id: string): Promise<boolean> {\n return (await tx.query(`SELECT aggregate_id FROM ${backend.prefix}mayura_workflow_owners WHERE scope = ? AND aggregate_id = ?`, [scope, id])).length !== 0;\n}\n/** Always available after ordinary store initialization, even before the workflow capability is used. */\nexport async function initializeOwnership(tx: SchedulerSession, backend: SchedulerBackend): Promise<void> {\n await tx.query(`CREATE TABLE IF NOT EXISTS ${backend.prefix}mayura_workflow_owners (\n scope TEXT NOT NULL, aggregate_id TEXT NOT NULL, profile INTEGER NOT NULL CHECK(profile > 0),\n aggregate_version BIGINT NOT NULL CHECK(aggregate_version > 0), definition_hash TEXT NOT NULL,\n policy_hash TEXT NOT NULL, resource_hash TEXT NOT NULL, data TEXT NOT NULL,\n PRIMARY KEY(scope, aggregate_id), FOREIGN KEY(scope, aggregate_id) REFERENCES ${backend.prefix}mayura_aggregates(scope, id))`);\n}\nexport async function storageClock(tx: SchedulerSession, backend: SchedulerBackend, floor = 0): Promise<number> {\n const sql = backend.dialect === 'postgres' ? 'SELECT floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint AS now_ms'\n : \"SELECT CAST(strftime('%s','now') AS INTEGER) * 1000 + CAST(substr(strftime('%f','now'),4,3) AS INTEGER) AS now_ms\";\n const value = (await tx.query<{ now_ms: number | string }>(sql))[0]?.now_ms;\n if (value === undefined) throw new StorageError('STORAGE_UNAVAILABLE', 'Storage time is unavailable.');\n return Math.max(floor, storedInteger(value));\n}\nexport async function appendAggregateEvents(tx: SchedulerSession, backend: SchedulerBackend, scope: string, id: string, sequence: number, events: readonly StoredEventInput[], now: number): Promise<void> {\n const time = new Date(now).toISOString();\n for (const [index, event] of events.entries()) await tx.query(`INSERT INTO ${backend.prefix}mayura_events (scope, aggregate_id, sequence, type, data, created_at) VALUES (?, ?, ?, ?, ?, ?)`,\n [scope, id, nextCounter(sequence, index + 1), identifier(event.type, 'Event'), JSON.stringify(event.data), time]);\n}\nexport async function createAggregate(tx: SchedulerSession, backend: SchedulerBackend, input: CreateRecord, now: number): Promise<{ row: AggregateRow; created: boolean }> {\n const digest = submissionDigest(input);\n const rows = await tx.query<AggregateRow>(`INSERT INTO ${backend.prefix}mayura_aggregates (scope, id, idempotency_key, definition_hash, submission_digest, version, event_sequence, state)\n VALUES (?, ?, ?, ?, ?, 1, ?, ?) ON CONFLICT (scope, idempotency_key) DO NOTHING RETURNING *`,\n [input.scope, input.id, input.idempotencyKey, input.definitionHash, digest, input.events.length, JSON.stringify(input.state)]);\n if (rows[0]) { await appendAggregateEvents(tx, backend, input.scope, input.id, 0, input.events, now); return { row: rows[0], created: true }; }\n const existing = (await tx.query<AggregateRow>(`SELECT * FROM ${backend.prefix}mayura_aggregates WHERE scope = ? AND idempotency_key = ?${lockSql(backend)}`, [input.scope, input.idempotencyKey]))[0];\n if (!existing || existing.submission_digest !== digest) throw new StorageError('CONFLICT', 'This idempotency key was already used for a different submission (other input, definition or settings); resubmit exactly the same request, or use a new key.');\n return { row: existing, created: false };\n}\n/** Only internal semantic reducers call this after the aggregate lock; it is not a public replacement-state API. */\nexport async function writeAggregate(tx: SchedulerSession, backend: SchedulerBackend, row: AggregateRow, state: StoredRecord['state'], events: readonly StoredEventInput[], now: number): Promise<AggregateRow> {\n const version = nextCounter(storedInteger(row.version), 1); const sequence = storedInteger(row.event_sequence);\n const updated = (await tx.query<AggregateRow>(`UPDATE ${backend.prefix}mayura_aggregates SET state = ?, version = ?, event_sequence = ? WHERE scope = ? AND id = ? RETURNING *`,\n [JSON.stringify(storedObject(state)), version, nextCounter(sequence, events.length), row.scope, row.id]))[0];\n if (!updated) throw new StorageError('STORAGE_UNAVAILABLE', 'Locked aggregate disappeared.');\n await appendAggregateEvents(tx, backend, row.scope, row.id, sequence, events, now); return updated;\n}\n"]}
|
|
@@ -1018,7 +1018,7 @@ export class ScheduledWorkflowDatabase {
|
|
|
1018
1018
|
return this.snapshot(run);
|
|
1019
1019
|
}
|
|
1020
1020
|
catch (error) {
|
|
1021
|
-
if (!(error instanceof StorageError) || error.
|
|
1021
|
+
if (!(error instanceof StorageError) || error.storageCode !== 'STALE_CLAIM')
|
|
1022
1022
|
throw error;
|
|
1023
1023
|
await this.blockExpiredReview(tx, run, job);
|
|
1024
1024
|
if (run.events.length > 0) {
|