@capybara-hq/kernel 0.1.0-rc.36 → 0.1.0-rc.38
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/bootstrap.json +5 -5
- package/dist/admin/admin.module.d.ts +3 -2
- package/dist/admin/admin.module.js +9 -5
- package/dist/admin/audit-log.service.d.ts +51 -0
- package/dist/admin/{platform-audit.service.js → audit-log.service.js} +20 -12
- package/dist/admin/audit.controller.d.ts +18 -6
- package/dist/admin/audit.controller.js +36 -6
- package/dist/admin/audit.schemas.d.ts +9 -1
- package/dist/admin/audit.schemas.js +22 -2
- package/dist/admin/org-network.controller.d.ts +30 -0
- package/dist/admin/org-network.controller.js +77 -0
- package/dist/admin/org-network.schemas.d.ts +16 -0
- package/dist/admin/org-network.schemas.js +27 -0
- package/dist/admin/org-network.service.d.ts +41 -0
- package/dist/admin/org-network.service.js +101 -0
- package/dist/admin/outbox-dead.controller.d.ts +4 -6
- package/dist/admin/outbox-dead.controller.js +9 -6
- package/dist/admin/outbox-dead.schemas.d.ts +16 -0
- package/dist/admin/outbox-dead.schemas.js +25 -1
- package/dist/admin/outbox-dead.service.d.ts +16 -7
- package/dist/admin/outbox-dead.service.js +34 -10
- package/dist/admin/overview.service.d.ts +3 -3
- package/dist/admin/overview.service.js +0 -1
- package/dist/agents/agent-lookup.js +2 -10
- package/dist/agents/agents.service.js +9 -20
- package/dist/agents/definition.d.ts +3 -51
- package/dist/agents/definition.js +4 -254
- package/dist/agents/org-templates.js +2 -6
- package/dist/agents/readiness.controller.d.ts +4 -12
- package/dist/agents/readiness.controller.js +4 -12
- package/dist/agents/readiness.service.d.ts +23 -11
- package/dist/agents/readiness.service.js +31 -14
- package/dist/agents/templates.d.ts +0 -6
- package/dist/agents/templates.js +8 -34
- package/dist/background/store.d.ts +2 -0
- package/dist/background/store.js +3 -1
- package/dist/background/wake-rules.js +2 -1
- package/dist/catalog/admin-catalog.controller.d.ts +1 -2
- package/dist/catalog/admin-catalog.controller.js +1 -2
- package/dist/catalog/appearance.service.js +1 -3
- package/dist/catalog/catalog-content.d.ts +1 -1
- package/dist/catalog/catalog-content.js +1 -4
- package/dist/catalog/catalog-items.js +3 -3
- package/dist/catalog/catalog-scope.service.d.ts +10 -28
- package/dist/catalog/catalog-scope.service.js +22 -73
- package/dist/catalog/cli.d.ts +0 -11
- package/dist/catalog/cli.js +0 -20
- package/dist/catalog/component-scope.service.js +0 -2
- package/dist/catalog/component-state.js +2 -2
- package/dist/catalog/install-status.d.ts +6 -0
- package/dist/catalog/install-status.js +6 -0
- package/dist/catalog/job-ids.d.ts +0 -4
- package/dist/catalog/job-ids.js +0 -4
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/catalog/org-catalog.service.d.ts +2 -0
- package/dist/catalog/org-catalog.service.js +8 -3
- package/dist/catalog/org-extension-switch.d.ts +7 -2
- package/dist/catalog/org-extension-switch.js +56 -9
- package/dist/catalog/org-plugin-uploads.d.ts +6 -15
- package/dist/catalog/org-plugin-uploads.js +9 -27
- package/dist/catalog/owned-items.js +1 -3
- package/dist/catalog/platform-import-update.js +1 -1
- package/dist/catalog/plugin-import.d.ts +15 -13
- package/dist/catalog/plugin-import.js +21 -30
- package/dist/catalog/plugin-install.d.ts +3 -43
- package/dist/catalog/plugin-install.js +8 -150
- package/dist/catalog/plugin-package.d.ts +5 -10
- package/dist/catalog/plugin-package.js +12 -33
- package/dist/catalog/plugin-upgrade.js +5 -4
- package/dist/catalog/scope-jobs.d.ts +34 -34
- package/dist/catalog/scope-jobs.js +50 -37
- package/dist/catalog/scope-orgs.d.ts +1 -1
- package/dist/catalog/scope-orgs.js +1 -2
- package/dist/catalog/scope-sync-workers.d.ts +4 -3
- package/dist/catalog/scope-sync-workers.js +18 -6
- package/dist/catalog/scope-sync.d.ts +56 -59
- package/dist/catalog/scope-sync.js +96 -166
- package/dist/catalog/unshare.d.ts +3 -4
- package/dist/catalog/unshare.js +5 -8
- package/dist/channels/job-ids.d.ts +2 -6
- package/dist/channels/job-ids.js +2 -6
- package/dist/channels/outbound.d.ts +1 -1
- package/dist/channels/outbound.js +1 -1
- package/dist/channels/supervisor.d.ts +2 -3
- package/dist/channels/supervisor.js +2 -3
- package/dist/client/client-access.service.js +1 -1
- package/dist/config/env.js +19 -1
- package/dist/config/load.d.ts +0 -6
- package/dist/config/load.js +8 -27
- package/dist/config/schema.d.ts +54 -47
- package/dist/config/schema.js +198 -42
- package/dist/conversations/attachments.service.d.ts +10 -3
- package/dist/conversations/attachments.service.js +49 -16
- package/dist/conversations/conversations.controller.d.ts +0 -39
- package/dist/conversations/conversations.controller.js +0 -39
- package/dist/conversations/event-log.js +4 -1
- package/dist/conversations/events.d.ts +71 -46
- package/dist/conversations/events.js +124 -112
- package/dist/conversations/media-types.d.ts +25 -0
- package/dist/conversations/media-types.js +38 -0
- package/dist/conversations/queue.d.ts +3 -1
- package/dist/conversations/queue.service.js +9 -2
- package/dist/conversations/titles.js +6 -0
- package/dist/ctx/create-ctx.d.ts +8 -1
- package/dist/ctx/create-ctx.js +13 -3
- package/dist/ctx/net.d.ts +50 -0
- package/dist/ctx/net.js +67 -0
- package/dist/ctx/secrets.d.ts +24 -7
- package/dist/ctx/secrets.js +97 -30
- package/dist/db/kernel-schema.d.ts +27 -6
- package/dist/devices/devices.service.js +2 -1
- package/dist/errors.d.ts +10 -2
- package/dist/errors.js +10 -2
- package/dist/evals/reconstruct.d.ts +4 -17
- package/dist/evals/reconstruct.js +13 -53
- package/dist/evals/recorded-tools.d.ts +0 -27
- package/dist/evals/recorded-tools.js +2 -92
- package/dist/evals/run-replay.d.ts +1 -6
- package/dist/evals/run-replay.js +10 -17
- package/dist/evals/sets.service.d.ts +17 -5
- package/dist/evals/sets.service.js +33 -12
- package/dist/evals/snapshot.d.ts +1 -2
- package/dist/evals/snapshot.js +4 -17
- package/dist/extensions/admin-ops.d.ts +6 -1
- package/dist/extensions/admin-ops.js +17 -4
- package/dist/extensions/admin-view.d.ts +7 -4
- package/dist/extensions/admin-view.js +27 -21
- package/dist/extensions/bootstrap.js +0 -1
- package/dist/extensions/cli.js +0 -1
- package/dist/extensions/extensions.module.js +3 -0
- package/dist/extensions/host.d.ts +9 -4
- package/dist/extensions/host.js +14 -8
- package/dist/extensions/installs.d.ts +1 -3
- package/dist/extensions/instance.d.ts +0 -2
- package/dist/extensions/instance.js +0 -3
- package/dist/extensions/org-config.d.ts +4 -4
- package/dist/extensions/org-config.js +13 -22
- package/dist/extensions/package.d.ts +6 -6
- package/dist/extensions/package.js +3 -7
- package/dist/extensions/permission-view.d.ts +2 -4
- package/dist/extensions/plugin-items.d.ts +21 -1
- package/dist/extensions/plugin-items.js +28 -0
- package/dist/extensions/sync.js +5 -10
- package/dist/extensions/unavailable.js +0 -1
- package/dist/http/api.module.js +4 -1
- package/dist/identity/audit.d.ts +0 -12
- package/dist/identity/audit.js +0 -27
- package/dist/identity/auth.controller.js +5 -9
- package/dist/identity/cookies.d.ts +4 -9
- package/dist/identity/cookies.js +8 -32
- package/dist/identity/initial-passwords.d.ts +1 -1
- package/dist/identity/initial-passwords.js +1 -2
- package/dist/identity/sessions.d.ts +0 -6
- package/dist/identity/sessions.js +0 -18
- package/dist/inbox/platform-inbox.service.d.ts +33 -1
- package/dist/inbox/platform-inbox.service.js +56 -6
- package/dist/index.d.ts +4 -2
- package/dist/index.js +4 -2
- package/dist/infra/cli/master-key-rewrap.d.ts +15 -0
- package/dist/infra/cli/master-key-rewrap.js +24 -0
- package/dist/infra/config/kernel-config.service.js +0 -17
- package/dist/infra/database/transaction-host.d.ts +32 -1
- package/dist/infra/database/transaction-host.js +30 -4
- package/dist/infra/database/xact-lock.d.ts +16 -0
- package/dist/infra/database/xact-lock.js +28 -1
- package/dist/infra/health/health.controller.js +8 -0
- package/dist/infra/health/process-fault.d.ts +16 -0
- package/dist/infra/health/process-fault.js +49 -0
- package/dist/infra/lifecycle/process-guards.d.ts +8 -2
- package/dist/infra/lifecycle/process-guards.js +12 -3
- package/dist/infra/lifecycle/shutdown-signals.d.ts +10 -1
- package/dist/infra/lifecycle/shutdown-signals.js +28 -13
- package/dist/infra/outbox/outbox.service.d.ts +12 -9
- package/dist/infra/outbox/outbox.service.js +22 -26
- package/dist/infra/outbox/registry.d.ts +15 -7
- package/dist/infra/outbox/registry.js +39 -23
- package/dist/lifecycle/kernel-lifecycle.js +1 -7
- package/dist/models/enablement.d.ts +5 -6
- package/dist/models/enablement.js +7 -14
- package/dist/net/public-address.d.ts +21 -1
- package/dist/net/public-address.js +56 -10
- package/dist/net/safe-fetch.d.ts +4 -1
- package/dist/net/safe-fetch.js +15 -4
- package/dist/orgs/directory-sync.js +2 -0
- package/dist/orgs/members.service.js +5 -0
- package/dist/orgs/network-allowances.service.d.ts +79 -0
- package/dist/orgs/network-allowances.service.js +371 -0
- package/dist/orgs/offboarding.d.ts +3 -1
- package/dist/orgs/offboarding.js +9 -2
- package/dist/orgs/org-lock.d.ts +28 -2
- package/dist/orgs/org-lock.js +59 -4
- package/dist/orgs/orgs.controller.d.ts +11 -2
- package/dist/orgs/orgs.controller.js +19 -3
- package/dist/orgs/orgs.module.d.ts +3 -2
- package/dist/orgs/orgs.module.js +6 -2
- package/dist/orgs/orgs.schemas.d.ts +12 -0
- package/dist/orgs/orgs.schemas.js +5 -0
- package/dist/orgs/orgs.service.js +6 -1
- package/dist/orgs/settings.controller.d.ts +3 -2
- package/dist/orgs/settings.service.d.ts +59 -14
- package/dist/orgs/settings.service.js +102 -20
- package/dist/overrides.d.ts +7 -7
- package/dist/overrides.js +4 -4
- package/dist/packages/tgz.d.ts +0 -2
- package/dist/packages/tgz.js +0 -2
- package/dist/platform/exclusions.js +0 -5
- package/dist/platform/operation.js +1 -1
- package/dist/platform/ops/admin.ops.d.ts +2 -2
- package/dist/platform/ops/admin.ops.js +9 -6
- package/dist/platform/ops/agents.ops.js +1 -1
- package/dist/platform/ops/connectors.ops.js +46 -1
- package/dist/platform/ops/evals.ops.js +1 -64
- package/dist/platform/ops/extensions-admin.ops.js +1 -1
- package/dist/platform/ops/inbox.ops.js +16 -3
- package/dist/platform/ops/org-plugins.ops.js +1 -1
- package/dist/platform/ops/orgs.ops.d.ts +11 -3
- package/dist/platform/ops/orgs.ops.js +139 -5
- package/dist/platform/ops/outbox.ops.js +5 -5
- package/dist/platform/route-schemas.js +3 -0
- package/dist/roles/worker-role.d.ts +2 -3
- package/dist/roles/worker-role.js +3 -13
- package/dist/runtime/checkpointer.d.ts +3 -0
- package/dist/runtime/checkpointer.js +7 -4
- package/dist/runtime/context/build.d.ts +56 -18
- package/dist/runtime/context/build.js +143 -50
- package/dist/runtime/context/compaction.d.ts +1 -3
- package/dist/runtime/context/compaction.js +42 -8
- package/dist/runtime/context/run-context.js +1 -2
- package/dist/runtime/context/skills.d.ts +27 -56
- package/dist/runtime/context/skills.js +42 -114
- package/dist/runtime/context/tool-changes.d.ts +3 -3
- package/dist/runtime/context/tool-changes.js +6 -16
- package/dist/runtime/hook-calls.d.ts +6 -6
- package/dist/runtime/hook-calls.js +7 -7
- package/dist/runtime/langgraph-loop.js +9 -3
- package/dist/runtime/maintenance.d.ts +3 -11
- package/dist/runtime/maintenance.js +5 -20
- package/dist/runtime/model-call.d.ts +5 -0
- package/dist/runtime/model-call.js +48 -36
- package/dist/runtime/providers.d.ts +33 -35
- package/dist/runtime/providers.js +64 -109
- package/dist/runtime/run-context.service.js +7 -22
- package/dist/runtime/run-deletion.d.ts +6 -0
- package/dist/runtime/run-deletion.js +39 -16
- package/dist/runtime/run-execution.d.ts +56 -3
- package/dist/runtime/run-execution.js +81 -11
- package/dist/runtime/run-finish.js +2 -1
- package/dist/runtime/run-liveness.d.ts +11 -0
- package/dist/runtime/run-liveness.js +19 -0
- package/dist/runtime/run-orphan-check.job.js +2 -1
- package/dist/runtime/run-queue.js +8 -16
- package/dist/runtime/run-worker.d.ts +2 -2
- package/dist/runtime/run-worker.js +8 -6
- package/dist/runtime/step-log.d.ts +5 -0
- package/dist/runtime/step-log.js +9 -4
- package/dist/runtime/subagents/definition.d.ts +16 -20
- package/dist/runtime/subagents/definition.js +27 -27
- package/dist/runtime/subagents/dispatch.d.ts +6 -2
- package/dist/runtime/subagents/dispatch.js +17 -3
- package/dist/runtime/subagents/org-agents.js +1 -2
- package/dist/runtime/subagents/preamble.d.ts +3 -2
- package/dist/runtime/subagents/preamble.js +3 -2
- package/dist/runtime/subagents/render.d.ts +1 -2
- package/dist/runtime/subagents/render.js +1 -2
- package/dist/runtime/subagents/skill-fork.d.ts +2 -4
- package/dist/runtime/subagents/template-skills.d.ts +47 -0
- package/dist/runtime/subagents/template-skills.js +76 -0
- package/dist/runtime/waits.js +3 -1
- package/dist/schedules/effective-settings.d.ts +9 -3
- package/dist/schedules/effective-settings.js +5 -4
- package/dist/schedules/fire.js +11 -0
- package/dist/schedules/scheduled-tasks.service.js +5 -0
- package/dist/schedules/unattended.d.ts +2 -0
- package/dist/schedules/unattended.js +6 -1
- package/dist/skills/agent-skills.service.js +1 -2
- package/dist/skills/catalog.d.ts +1 -3
- package/dist/skills/catalog.js +1 -3
- package/dist/skills/conversation-catalog.d.ts +1 -2
- package/dist/skills/conversation-catalog.js +1 -2
- package/dist/skills/usable.js +2 -3
- package/dist/storage/storage.service.js +9 -1
- package/dist/tools/approvals.service.js +2 -4
- package/dist/tools/builtin-names.d.ts +2 -9
- package/dist/tools/builtin-names.js +4 -13
- package/dist/tools/builtins/sandbox/bash.js +3 -3
- package/dist/tools/builtins/sandbox/common.d.ts +7 -13
- package/dist/tools/builtins/sandbox/common.js +8 -115
- package/dist/tools/builtins/sandbox/fetch-attachment.d.ts +10 -0
- package/dist/tools/builtins/sandbox/fetch-attachment.js +119 -0
- package/dist/tools/builtins/sandbox/glob.js +1 -3
- package/dist/tools/builtins/sandbox/grep.js +3 -5
- package/dist/tools/builtins/sandbox/index.d.ts +8 -5
- package/dist/tools/builtins/sandbox/index.js +10 -5
- package/dist/tools/builtins/sandbox/read.js +3 -2
- package/dist/tools/builtins/tool-search.d.ts +4 -7
- package/dist/tools/builtins/tool-search.js +6 -10
- package/dist/tools/connector-account-policies.d.ts +30 -3
- package/dist/tools/connector-account-policies.js +54 -7
- package/dist/tools/connector-content.js +1 -0
- package/dist/tools/connectors.controller.d.ts +24 -11
- package/dist/tools/connectors.controller.js +35 -6
- package/dist/tools/connectors.schemas.d.ts +14 -1
- package/dist/tools/connectors.schemas.js +14 -2
- package/dist/tools/connectors.service.d.ts +22 -0
- package/dist/tools/connectors.service.js +65 -6
- package/dist/tools/drift.d.ts +6 -2
- package/dist/tools/drift.js +10 -5
- package/dist/tools/git-push-policy.d.ts +4 -1
- package/dist/tools/git-push-policy.js +3 -1
- package/dist/tools/info.d.ts +1 -7
- package/dist/tools/info.js +5 -18
- package/dist/tools/job-ids.d.ts +0 -4
- package/dist/tools/job-ids.js +1 -6
- package/dist/tools/pipeline.d.ts +4 -10
- package/dist/tools/pipeline.js +17 -62
- package/dist/tools/policy.d.ts +6 -2
- package/dist/tools/policy.js +14 -12
- package/dist/tools/registry.js +1 -5
- package/dist/ui/views.d.ts +5 -5
- package/dist/ui/views.js +10 -16
- package/package.json +3 -3
- package/src/migrations/0137_audit_org_idx.sql +5 -0
- package/src/migrations/0138_plugin_install_status_no_upgrading.sql +18 -0
- package/src/migrations/0139_retire_legacy_forms.sql +183 -0
- package/src/migrations/0140_retire_history_forms.sql +148 -0
- package/src/migrations/0141_install_ledger_promoted_rows.sql +36 -0
- package/src/migrations/0142_backfill_event_fields.sql +74 -0
- package/src/migrations/0143_backfill_model_call_fields.sql +105 -0
- package/src/migrations/0144_retire_frozen_definition_keys.sql +163 -0
- package/src/migrations/0145_org_network_allowances.sql +12 -0
- package/dist/admin/platform-audit.service.d.ts +0 -41
- package/dist/conversations/job-ids.d.ts +0 -6
- package/dist/conversations/job-ids.js +0 -6
- package/dist/extensions/job-ids.d.ts +0 -6
- package/dist/extensions/job-ids.js +0 -6
- package/dist/infra/queue/retired-schedulers.d.ts +0 -7
- package/dist/infra/queue/retired-schedulers.js +0 -9
- package/dist/orgs/job-ids.d.ts +0 -8
- package/dist/orgs/job-ids.js +0 -8
- package/dist/runtime/context/legacy-text.d.ts +0 -22
- package/dist/runtime/context/legacy-text.js +0 -37
- package/dist/runtime/job-ids.d.ts +0 -10
- package/dist/runtime/job-ids.js +0 -10
- package/dist/runtime/retired-schedulers.d.ts +0 -7
- package/dist/runtime/retired-schedulers.js +0 -31
- package/dist/storage/job-ids.d.ts +0 -6
- package/dist/storage/job-ids.js +0 -6
- package/dist/tools/legacy-data.d.ts +0 -34
- package/dist/tools/legacy-data.js +0 -76
- package/dist/tools/legacy-keys.d.ts +0 -51
- package/dist/tools/legacy-keys.js +0 -114
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { KernelConfig } from "../../config/schema.js";
|
|
2
|
+
import { type RewrapResult } from "../../ctx/secrets.js";
|
|
3
|
+
import type { KernelLogger } from "../../log.js";
|
|
4
|
+
/**
|
|
5
|
+
* `capybara secrets rewrap`: opens a PostgreSQL-only CLI context over `config` (its keyring is
|
|
6
|
+
* `masterKey` plus `masterKeyPrevious`) and rewraps everything sealed with a previous master key
|
|
7
|
+
* with the current one ({@link rewrapToCurrentMasterKey}). Returns the counts and the current
|
|
8
|
+
* master key id (a hash prefix, never key material).
|
|
9
|
+
*/
|
|
10
|
+
export declare function rewrapMasterKeys(config: KernelConfig, opts: {
|
|
11
|
+
logger: KernelLogger;
|
|
12
|
+
batchSize?: number;
|
|
13
|
+
}): Promise<RewrapResult & {
|
|
14
|
+
currentMasterKeyId: string;
|
|
15
|
+
}>;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { rewrapToCurrentMasterKey } from "../../ctx/secrets.js";
|
|
2
|
+
import { KernelDb } from "../database/kernel-db.js";
|
|
3
|
+
import { TransactionHost } from "../database/transaction-host.js";
|
|
4
|
+
import { KEYRING } from "../tokens.js";
|
|
5
|
+
import { openKernelCli } from "./kernel-cli.module.js";
|
|
6
|
+
/**
|
|
7
|
+
* `capybara secrets rewrap`: opens a PostgreSQL-only CLI context over `config` (its keyring is
|
|
8
|
+
* `masterKey` plus `masterKeyPrevious`) and rewraps everything sealed with a previous master key
|
|
9
|
+
* with the current one ({@link rewrapToCurrentMasterKey}). Returns the counts and the current
|
|
10
|
+
* master key id (a hash prefix, never key material).
|
|
11
|
+
*/
|
|
12
|
+
export async function rewrapMasterKeys(config, opts) {
|
|
13
|
+
const app = await openKernelCli(config, { logger: opts.logger, modules: [], redis: false });
|
|
14
|
+
try {
|
|
15
|
+
const keyring = app.get(KEYRING);
|
|
16
|
+
const result = await rewrapToCurrentMasterKey({ db: app.get(KernelDb), txHost: app.get(TransactionHost) }, keyring, opts.batchSize !== undefined ? { batchSize: opts.batchSize } : {});
|
|
17
|
+
return { ...result, currentMasterKeyId: keyring.currentId };
|
|
18
|
+
}
|
|
19
|
+
finally {
|
|
20
|
+
await app.close().catch((err) => {
|
|
21
|
+
opts.logger.debug("secrets rewrap: closing the CLI context failed", { err });
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
}
|
|
@@ -69,18 +69,6 @@ const HOT_APPLIERS = {
|
|
|
69
69
|
"attribution.pr": () => { },
|
|
70
70
|
"attribution.sessionUrl": () => { },
|
|
71
71
|
};
|
|
72
|
-
/**
|
|
73
|
-
* Environment variables of renamed config keys, with their replacements: warned about once when
|
|
74
|
-
* the service starts (agent map spec §6: `subagents.maxConcurrentPerRun` became
|
|
75
|
-
* `subagents.maxConcurrentPerConversation`). A retired file or Nacos key cannot be told here: the
|
|
76
|
-
* schema strips unknown keys before the kernel receives its config.
|
|
77
|
-
*/
|
|
78
|
-
const RETIRED_ENV = [
|
|
79
|
-
[
|
|
80
|
-
"CAPYBARA_SUBAGENTS__MAX_CONCURRENT_PER_RUN",
|
|
81
|
-
"CAPYBARA_SUBAGENTS__MAX_CONCURRENT_PER_CONVERSATION",
|
|
82
|
-
],
|
|
83
|
-
];
|
|
84
72
|
const HOT_PATHS = configFields(KernelConfigSchema)
|
|
85
73
|
.filter((f) => f.meta?.hot)
|
|
86
74
|
.map((f) => f.path);
|
|
@@ -101,11 +89,6 @@ let KernelConfigService = class KernelConfigService {
|
|
|
101
89
|
this.env = input.env ?? process.env;
|
|
102
90
|
log.setLevel(input.config.log.level);
|
|
103
91
|
log.addSecrets(secretValues(KernelConfigSchema, input.config));
|
|
104
|
-
for (const [old, now] of RETIRED_ENV) {
|
|
105
|
-
if (this.env[old] !== undefined) {
|
|
106
|
-
log.warn(`${old} is no longer read and is ignored; set ${now} instead`, { env: old });
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
92
|
}
|
|
110
93
|
get() {
|
|
111
94
|
return this.current;
|
|
@@ -8,8 +8,22 @@ interface TransactionStore {
|
|
|
8
8
|
hooks: AfterCommitHook[];
|
|
9
9
|
/** Set once the transaction settled: continuations that outlive it must not use it. */
|
|
10
10
|
done: boolean;
|
|
11
|
+
/**
|
|
12
|
+
* How a fence admitted it (`withTransactionFence`), once the fence ran; undefined when no fence
|
|
13
|
+
* admitted it (no fence in context, or read only).
|
|
14
|
+
*/
|
|
15
|
+
admission?: AdmissionMode;
|
|
11
16
|
}
|
|
12
|
-
|
|
17
|
+
/** How a fence admits the transaction it runs in ({@link TransactionOptions.admission}). */
|
|
18
|
+
export interface FenceAdmission {
|
|
19
|
+
/** The transaction asked for shared admission (`admission: "shared"`). */
|
|
20
|
+
shared: boolean;
|
|
21
|
+
}
|
|
22
|
+
/** The mode a fence admitted a transaction in (a fence returning nothing admits exclusively). */
|
|
23
|
+
export type AdmissionMode = "shared" | "exclusive";
|
|
24
|
+
/** A fence: checks the caller's authority, takes its admission locks and says in which mode. */
|
|
25
|
+
export type TransactionFence = (admission: FenceAdmission) => Promise<AdmissionMode | undefined | void>;
|
|
26
|
+
export declare function withTransactionFence<T>(fence: TransactionFence, fn: () => Promise<T>): Promise<T>;
|
|
13
27
|
export type Propagation = "required" | "requires_new" | "mandatory";
|
|
14
28
|
export interface TransactionOptions {
|
|
15
29
|
/**
|
|
@@ -23,9 +37,26 @@ export interface TransactionOptions {
|
|
|
23
37
|
isolationLevel?: IsolationLevel;
|
|
24
38
|
/** Access mode of a transaction this call opens (ignored when it joins one). */
|
|
25
39
|
accessMode?: AccessMode;
|
|
40
|
+
/**
|
|
41
|
+
* How the caller's fence (`withTransactionFence`) admits a transaction this call opens (ignored
|
|
42
|
+
* when it joins one, or with no fence in context). Default: the fence's exclusive admission.
|
|
43
|
+
* `shared`: the run loop's own hot-path writes (event appends, checkpoints, the suspend), which
|
|
44
|
+
* the run fence admits under a shared lock so the runs of one org write in parallel
|
|
45
|
+
* (`RunExecution`); a fence may still admit it exclusively (inside a tool step).
|
|
46
|
+
*/
|
|
47
|
+
admission?: "shared";
|
|
26
48
|
}
|
|
27
49
|
/** Queues `fn` on the current live root transaction; with none open, runs it at once. */
|
|
28
50
|
export declare function queueAfterCommit(fn: AfterCommitHook): void;
|
|
51
|
+
/** Whether the live transaction in context was admitted by a fence (a claimed run's write). */
|
|
52
|
+
export declare function inFencedTransaction(): boolean;
|
|
53
|
+
/**
|
|
54
|
+
* Throws when the live transaction in context was admitted shared by the run fence
|
|
55
|
+
* (`RunExecution`): such a transaction holds conversation rows without the org row, so taking an
|
|
56
|
+
* org-level lock (`what`: the org row, a membership, an advisory lock) would invert the global lock
|
|
57
|
+
* order org admission → org row → conversations. Called by every org-level lock.
|
|
58
|
+
*/
|
|
59
|
+
export declare function assertNotSharedAdmission(what: string): void;
|
|
29
60
|
/** The transaction store in the current async context (used by `afterCommit`). */
|
|
30
61
|
export declare function currentStore(): TransactionStore | undefined;
|
|
31
62
|
/**
|
|
@@ -46,6 +46,22 @@ function liveStore() {
|
|
|
46
46
|
const store = storage.getStore();
|
|
47
47
|
return store && !store.done ? store : undefined;
|
|
48
48
|
}
|
|
49
|
+
/** Whether the live transaction in context was admitted by a fence (a claimed run's write). */
|
|
50
|
+
export function inFencedTransaction() {
|
|
51
|
+
return liveStore()?.admission !== undefined;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Throws when the live transaction in context was admitted shared by the run fence
|
|
55
|
+
* (`RunExecution`): such a transaction holds conversation rows without the org row, so taking an
|
|
56
|
+
* org-level lock (`what`: the org row, a membership, an advisory lock) would invert the global lock
|
|
57
|
+
* order org admission → org row → conversations. Called by every org-level lock.
|
|
58
|
+
*/
|
|
59
|
+
export function assertNotSharedAdmission(what) {
|
|
60
|
+
if (liveStore()?.admission === "shared") {
|
|
61
|
+
throw new Error(`${what} inside a transaction the run fence admitted shared: hot-path writes take no ` +
|
|
62
|
+
'org-level lock (open it without admission: "shared")');
|
|
63
|
+
}
|
|
64
|
+
}
|
|
49
65
|
/** The transaction store in the current async context (used by `afterCommit`). */
|
|
50
66
|
export function currentStore() {
|
|
51
67
|
return liveStore();
|
|
@@ -91,6 +107,13 @@ let TransactionHost = class TransactionHost {
|
|
|
91
107
|
}
|
|
92
108
|
if (propagation === "required" && this.current())
|
|
93
109
|
return fn();
|
|
110
|
+
if (opts.admission === "shared" &&
|
|
111
|
+
opts.isolationLevel !== undefined &&
|
|
112
|
+
opts.isolationLevel !== "read committed") {
|
|
113
|
+
// shared admission reads the org row unlocked after the advisory lock: only a fresh
|
|
114
|
+
// statement snapshot (READ COMMITTED) sees a deletion that committed while it waited
|
|
115
|
+
throw new Error('admission: "shared" needs READ COMMITTED isolation');
|
|
116
|
+
}
|
|
94
117
|
const hooks = [];
|
|
95
118
|
let store;
|
|
96
119
|
let result;
|
|
@@ -101,12 +124,15 @@ let TransactionHost = class TransactionHost {
|
|
|
101
124
|
if (opts.accessMode !== undefined)
|
|
102
125
|
builder = builder.setAccessMode(opts.accessMode);
|
|
103
126
|
result = await builder.execute((trx) => {
|
|
104
|
-
|
|
105
|
-
|
|
127
|
+
const fence = opts.accessMode === "read only" ? undefined : fences.getStore();
|
|
128
|
+
const own = { pool: this.pool, trx, hooks, done: false };
|
|
129
|
+
store = own;
|
|
130
|
+
return storage.run(own, async () => {
|
|
106
131
|
// PostgreSQL forbids row locks in a read-only snapshot and enforces that it cannot
|
|
107
132
|
// mutate. Every later mutation or external dispatch still enters a writable fence.
|
|
108
|
-
if (
|
|
109
|
-
await
|
|
133
|
+
if (fence) {
|
|
134
|
+
own.admission = (await fence({ shared: opts.admission === "shared" })) || "exclusive";
|
|
135
|
+
}
|
|
110
136
|
return fn();
|
|
111
137
|
});
|
|
112
138
|
});
|
|
@@ -14,4 +14,20 @@ export declare class XactLock {
|
|
|
14
14
|
constructor(db: KernelDb, txHost: TransactionHost);
|
|
15
15
|
/** Takes the lock named `key` until the caller's transaction ends (waits while another holds it). */
|
|
16
16
|
lock(key: string): Promise<void>;
|
|
17
|
+
/**
|
|
18
|
+
* The org admission lock in its shared mode: the run fence admitting a run's hot-path write
|
|
19
|
+
* (`RunExecution`). Shared holders never wait for each other; they wait for an exclusive holder,
|
|
20
|
+
* and also queue behind an exclusive waiter (PostgreSQL grants heavyweight locks in order), so
|
|
21
|
+
* org deletion and offboarding are never starved by a stream of run writes. Two-key form
|
|
22
|
+
* ({@link ORG_ADMISSION_SPACE}, org id): a key space apart from {@link lock}'s one-key locks.
|
|
23
|
+
*/
|
|
24
|
+
admitOrgShared(orgId: string): Promise<void>;
|
|
25
|
+
/**
|
|
26
|
+
* The org admission lock in its exclusive mode: org deletion and offboarding (`OrgLock`), taken
|
|
27
|
+
* first in their transaction. Waits for every admitted hot-path write of the org and keeps new
|
|
28
|
+
* ones out until the transaction ends.
|
|
29
|
+
*/
|
|
30
|
+
admitOrgExclusive(orgId: string): Promise<void>;
|
|
17
31
|
}
|
|
32
|
+
/** The first key of the org admission lock ({@link XactLock.admitOrgShared}). */
|
|
33
|
+
export declare const ORG_ADMISSION_SPACE = "capybara.org-admission";
|
|
@@ -10,7 +10,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
|
10
10
|
import { Inject, Injectable } from "@nestjs/common";
|
|
11
11
|
import { sql } from "kysely";
|
|
12
12
|
import { KernelDb } from "./kernel-db.js";
|
|
13
|
-
import { TransactionHost } from "./transaction-host.js";
|
|
13
|
+
import { assertNotSharedAdmission, TransactionHost } from "./transaction-host.js";
|
|
14
14
|
import { Transactional } from "./transactional.decorator.js";
|
|
15
15
|
/**
|
|
16
16
|
* Transaction-scoped advisory locks (decision R9 of the Nest kernel spec): `pg_advisory_xact_lock`
|
|
@@ -29,15 +29,42 @@ let XactLock = class XactLock {
|
|
|
29
29
|
}
|
|
30
30
|
/** Takes the lock named `key` until the caller's transaction ends (waits while another holds it). */
|
|
31
31
|
async lock(key) {
|
|
32
|
+
assertNotSharedAdmission(`the advisory lock ${key}`);
|
|
32
33
|
await sql `SELECT pg_advisory_xact_lock(hashtext(${key}))`.execute(this.db.db);
|
|
33
34
|
}
|
|
35
|
+
/**
|
|
36
|
+
* The org admission lock in its shared mode: the run fence admitting a run's hot-path write
|
|
37
|
+
* (`RunExecution`). Shared holders never wait for each other; they wait for an exclusive holder,
|
|
38
|
+
* and also queue behind an exclusive waiter (PostgreSQL grants heavyweight locks in order), so
|
|
39
|
+
* org deletion and offboarding are never starved by a stream of run writes. Two-key form
|
|
40
|
+
* ({@link ORG_ADMISSION_SPACE}, org id): a key space apart from {@link lock}'s one-key locks.
|
|
41
|
+
*/
|
|
42
|
+
async admitOrgShared(orgId) {
|
|
43
|
+
await sql `SELECT pg_advisory_xact_lock_shared(hashtext(${ORG_ADMISSION_SPACE}), hashtext(${orgId}))`.execute(this.db.db);
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* The org admission lock in its exclusive mode: org deletion and offboarding (`OrgLock`), taken
|
|
47
|
+
* first in their transaction. Waits for every admitted hot-path write of the org and keeps new
|
|
48
|
+
* ones out until the transaction ends.
|
|
49
|
+
*/
|
|
50
|
+
async admitOrgExclusive(orgId) {
|
|
51
|
+
await sql `SELECT pg_advisory_xact_lock(hashtext(${ORG_ADMISSION_SPACE}), hashtext(${orgId}))`.execute(this.db.db);
|
|
52
|
+
}
|
|
34
53
|
};
|
|
35
54
|
__decorate([
|
|
36
55
|
Transactional({ propagation: "mandatory" })
|
|
37
56
|
], XactLock.prototype, "lock", null);
|
|
57
|
+
__decorate([
|
|
58
|
+
Transactional({ propagation: "mandatory" })
|
|
59
|
+
], XactLock.prototype, "admitOrgShared", null);
|
|
60
|
+
__decorate([
|
|
61
|
+
Transactional({ propagation: "mandatory" })
|
|
62
|
+
], XactLock.prototype, "admitOrgExclusive", null);
|
|
38
63
|
XactLock = __decorate([
|
|
39
64
|
Injectable(),
|
|
40
65
|
__param(0, Inject(KernelDb)),
|
|
41
66
|
__param(1, Inject(TransactionHost))
|
|
42
67
|
], XactLock);
|
|
43
68
|
export { XactLock };
|
|
69
|
+
/** The first key of the org admission lock ({@link XactLock.admitOrgShared}). */
|
|
70
|
+
export const ORG_ADMISSION_SPACE = "capybara.org-admission";
|
|
@@ -12,6 +12,7 @@ import { HealthCheckService, HealthIndicatorService, } from "@nestjs/terminus";
|
|
|
12
12
|
import { Public } from "../../identity/principal.js";
|
|
13
13
|
import { KERNEL_LOGGER } from "../tokens.js";
|
|
14
14
|
import { HEALTH_CHECKS } from "./health.options.js";
|
|
15
|
+
import { processFault } from "./process-fault.js";
|
|
15
16
|
import { SHUTDOWN_STATE } from "./shutdown-state.js";
|
|
16
17
|
/** A dependency that hangs (Redis reconnecting, commands in the offline queue) must still give 503 fast. */
|
|
17
18
|
export const CHECK_TIMEOUT_MS = 2_000;
|
|
@@ -45,6 +46,13 @@ let HealthController = class HealthController {
|
|
|
45
46
|
};
|
|
46
47
|
if (this.shutdown.isShuttingDown())
|
|
47
48
|
return stopping();
|
|
49
|
+
// A swallowed fatal event: not ready while `capybara start` stops gracefully and exits 1
|
|
50
|
+
// (liveness stays)
|
|
51
|
+
const faulted = processFault();
|
|
52
|
+
if (faulted !== undefined) {
|
|
53
|
+
reply.code(503);
|
|
54
|
+
return { ok: false, faulted: faulted.kind };
|
|
55
|
+
}
|
|
48
56
|
const names = Object.keys(this.checks);
|
|
49
57
|
const logged = new Set();
|
|
50
58
|
const fns = names.map((name) => () => this.indicators
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Marks this process faulted (idempotent: the first kind stays, and only the first mark notifies
|
|
3
|
+
* the listeners; a listener that throws does not keep the others from running).
|
|
4
|
+
*/
|
|
5
|
+
export declare function markProcessFaulted(kind: string): void;
|
|
6
|
+
/** The kind of the first swallowed fatal event, or `undefined` while the process is clean. */
|
|
7
|
+
export declare function processFault(): {
|
|
8
|
+
kind: string;
|
|
9
|
+
} | undefined;
|
|
10
|
+
/**
|
|
11
|
+
* Calls `listener` when this process is marked faulted (at once when it already is); returns a
|
|
12
|
+
* function that removes it.
|
|
13
|
+
*/
|
|
14
|
+
export declare function onProcessFault(listener: (kind: string) => void): () => void;
|
|
15
|
+
/** Test seam: clears the state (the listeners stay). */
|
|
16
|
+
export declare function resetProcessFault(): void;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether this process swallowed a fatal event (an unhandled rejection or uncaught exception the
|
|
3
|
+
* process guards kept running through). Readiness answers 503 from then on, and `capybara start`
|
|
4
|
+
* stops gracefully and exits with 1 (`onProcessFault`, wired by `handleShutdownSignals`) so any
|
|
5
|
+
* restart policy replaces the process; liveness is unchanged. Per-process state about this process
|
|
6
|
+
* itself, never shared across replicas, and never cleared (a faulted process is meant to be
|
|
7
|
+
* replaced).
|
|
8
|
+
*/
|
|
9
|
+
let fault;
|
|
10
|
+
const listeners = new Set();
|
|
11
|
+
/**
|
|
12
|
+
* Marks this process faulted (idempotent: the first kind stays, and only the first mark notifies
|
|
13
|
+
* the listeners; a listener that throws does not keep the others from running).
|
|
14
|
+
*/
|
|
15
|
+
export function markProcessFaulted(kind) {
|
|
16
|
+
if (fault !== undefined)
|
|
17
|
+
return;
|
|
18
|
+
fault = { kind };
|
|
19
|
+
for (const l of [...listeners]) {
|
|
20
|
+
try {
|
|
21
|
+
l(kind);
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
// a listener failing must not stop the others (nor reach the guard that marked the fault)
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
/** The kind of the first swallowed fatal event, or `undefined` while the process is clean. */
|
|
29
|
+
export function processFault() {
|
|
30
|
+
return fault;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Calls `listener` when this process is marked faulted (at once when it already is); returns a
|
|
34
|
+
* function that removes it.
|
|
35
|
+
*/
|
|
36
|
+
export function onProcessFault(listener) {
|
|
37
|
+
if (fault !== undefined) {
|
|
38
|
+
listener(fault.kind);
|
|
39
|
+
return () => { };
|
|
40
|
+
}
|
|
41
|
+
listeners.add(listener);
|
|
42
|
+
return () => {
|
|
43
|
+
listeners.delete(listener);
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/** Test seam: clears the state (the listeners stay). */
|
|
47
|
+
export function resetProcessFault() {
|
|
48
|
+
fault = undefined;
|
|
49
|
+
}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import type { KernelLogger } from "../../log.js";
|
|
2
2
|
/**
|
|
3
3
|
* Process-level guards for `capybara start`: an unhandled rejection or an uncaught exception is
|
|
4
|
-
* logged and the process
|
|
4
|
+
* logged and does not kill the process at once: it stops gracefully instead (see below), unless
|
|
5
|
+
* the events come in bursts.
|
|
5
6
|
*
|
|
6
7
|
* Node's default for an async failure nobody handles is to kill the process. That default assumes
|
|
7
8
|
* the program state is corrupt, which holds for errors thrown by business logic, but the ones seen
|
|
@@ -16,7 +17,12 @@ import type { KernelLogger } from "../../log.js";
|
|
|
16
17
|
*
|
|
17
18
|
* What this cannot save: a V8 heap exhaustion is a hard abort no listener sees; and a resource that
|
|
18
19
|
* first fails through an uncaught event and afterwards only through caught errors (500s) keeps the
|
|
19
|
-
* process alive but broken, which used to self-heal through a crash and a restart.
|
|
20
|
+
* process alive but broken, which used to self-heal through a crash and a restart. To keep that
|
|
21
|
+
* self-healing, every swallowed fatal event marks the process faulted (`markProcessFaulted`):
|
|
22
|
+
* `/readyz` answers 503 from then on, and `capybara start` runs its graceful stop (the bounded
|
|
23
|
+
* drain of a SIGTERM) and exits with 1, so any restart policy starts a clean process (readiness
|
|
24
|
+
* alone restarts nothing). `/healthz` (liveness) is unchanged. The record carries
|
|
25
|
+
* `severity: "fatal"` (the logger has no fatal level).
|
|
20
26
|
*
|
|
21
27
|
* Every line of the recorder is wrapped: a handler that throws while the process handles a fatal
|
|
22
28
|
* event would defeat the guard. Records go through the kernel logger (pino, redacted) with
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
+
import { markProcessFaulted } from "../health/process-fault.js";
|
|
1
2
|
/**
|
|
2
3
|
* Process-level guards for `capybara start`: an unhandled rejection or an uncaught exception is
|
|
3
|
-
* logged and the process
|
|
4
|
+
* logged and does not kill the process at once: it stops gracefully instead (see below), unless
|
|
5
|
+
* the events come in bursts.
|
|
4
6
|
*
|
|
5
7
|
* Node's default for an async failure nobody handles is to kill the process. That default assumes
|
|
6
8
|
* the program state is corrupt, which holds for errors thrown by business logic, but the ones seen
|
|
@@ -15,7 +17,12 @@
|
|
|
15
17
|
*
|
|
16
18
|
* What this cannot save: a V8 heap exhaustion is a hard abort no listener sees; and a resource that
|
|
17
19
|
* first fails through an uncaught event and afterwards only through caught errors (500s) keeps the
|
|
18
|
-
* process alive but broken, which used to self-heal through a crash and a restart.
|
|
20
|
+
* process alive but broken, which used to self-heal through a crash and a restart. To keep that
|
|
21
|
+
* self-healing, every swallowed fatal event marks the process faulted (`markProcessFaulted`):
|
|
22
|
+
* `/readyz` answers 503 from then on, and `capybara start` runs its graceful stop (the bounded
|
|
23
|
+
* drain of a SIGTERM) and exits with 1, so any restart policy starts a clean process (readiness
|
|
24
|
+
* alone restarts nothing). `/healthz` (liveness) is unchanged. The record carries
|
|
25
|
+
* `severity: "fatal"` (the logger has no fatal level).
|
|
19
26
|
*
|
|
20
27
|
* Every line of the recorder is wrapped: a handler that throws while the process handles a fatal
|
|
21
28
|
* event would defeat the guard. Records go through the kernel logger (pino, redacted) with
|
|
@@ -47,13 +54,15 @@ export function createFatalRecorder(deps) {
|
|
|
47
54
|
const t = now();
|
|
48
55
|
recent = recent.filter((x) => t - x < GUARD_CIRCUIT_WINDOW_MS);
|
|
49
56
|
recent.push(t);
|
|
57
|
+
safely(() => markProcessFaulted(kind));
|
|
50
58
|
safely(() => deps
|
|
51
59
|
.log()
|
|
52
|
-
.error(kind === "unhandledRejection" ? "unhandled promise rejection" : "uncaught exception", { marker: GUARD_LOG_MARKER, kind, err }));
|
|
60
|
+
.error(kind === "unhandledRejection" ? "unhandled promise rejection" : "uncaught exception", { marker: GUARD_LOG_MARKER, severity: "fatal", kind, err }));
|
|
53
61
|
if (recent.length > GUARD_CIRCUIT_LIMIT && !open) {
|
|
54
62
|
open = true;
|
|
55
63
|
safely(() => deps.log().error("too many fatal events; exiting so the process is restarted clean", {
|
|
56
64
|
marker: GUARD_LOG_MARKER,
|
|
65
|
+
severity: "fatal",
|
|
57
66
|
kind: "circuit-open",
|
|
58
67
|
events: recent.length,
|
|
59
68
|
windowMs: GUARD_CIRCUIT_WINDOW_MS,
|
|
@@ -10,6 +10,14 @@ export interface ShutdownSignalOptions {
|
|
|
10
10
|
* Default `process.exit`.
|
|
11
11
|
*/
|
|
12
12
|
exit?: (code: number) => void;
|
|
13
|
+
/**
|
|
14
|
+
* Subscribes to this process's fault (a swallowed fatal event, `onProcessFault`); returns the
|
|
15
|
+
* unsubscribe. A fault runs the same graceful stop as a signal, then exits with 1 either way, so
|
|
16
|
+
* any restart policy replaces the process (readiness alone restarts nothing: Kubernetes only
|
|
17
|
+
* takes the pod out of its endpoints, a worker serves no traffic, compose does not restart an
|
|
18
|
+
* unhealthy container). `capybara start` passes it; default: none (tests, library use).
|
|
19
|
+
*/
|
|
20
|
+
faults?: (onFault: (kind: string) => void) => () => void;
|
|
13
21
|
}
|
|
14
22
|
export interface ShutdownSignalHandle {
|
|
15
23
|
/** The shutdown a signal started, settled once `exit` was called; undefined before any signal. */
|
|
@@ -25,6 +33,7 @@ export interface ShutdownSignalHandle {
|
|
|
25
33
|
* flushing the logs. A second signal while that runs exits with 1 at once, so an operator's second
|
|
26
34
|
* Ctrl-C (or an orchestrator's repeated SIGTERM) never waits on a stuck shutdown. Nest's handlers
|
|
27
35
|
* would begin the shutdown only after every module's `onModuleDestroy`, ignore a second signal,
|
|
28
|
-
* flush nothing and end the process by re-raising the signal.
|
|
36
|
+
* flush nothing and end the process by re-raising the signal. With `faults`, a swallowed fatal
|
|
37
|
+
* event starts the same stop and exits with 1.
|
|
29
38
|
*/
|
|
30
39
|
export declare function handleShutdownSignals(close: () => Promise<void>, log: KernelLogger, opts?: ShutdownSignalOptions): ShutdownSignalHandle;
|
|
@@ -8,7 +8,8 @@ export const SHUTDOWN_SIGNALS = ["SIGTERM", "SIGINT"];
|
|
|
8
8
|
* flushing the logs. A second signal while that runs exits with 1 at once, so an operator's second
|
|
9
9
|
* Ctrl-C (or an orchestrator's repeated SIGTERM) never waits on a stuck shutdown. Nest's handlers
|
|
10
10
|
* would begin the shutdown only after every module's `onModuleDestroy`, ignore a second signal,
|
|
11
|
-
* flush nothing and end the process by re-raising the signal.
|
|
11
|
+
* flush nothing and end the process by re-raising the signal. With `faults`, a swallowed fatal
|
|
12
|
+
* event starts the same stop and exits with 1.
|
|
12
13
|
*/
|
|
13
14
|
export function handleShutdownSignals(close, log, opts = {}) {
|
|
14
15
|
const signals = opts.signals ?? process;
|
|
@@ -16,33 +17,47 @@ export function handleShutdownSignals(close, log, opts = {}) {
|
|
|
16
17
|
let exiting;
|
|
17
18
|
// Set by a second signal: the forced exit(1) stays the process's code
|
|
18
19
|
let forced = false;
|
|
20
|
+
let unsubscribe = () => { };
|
|
19
21
|
const dispose = () => {
|
|
20
22
|
for (const s of SHUTDOWN_SIGNALS)
|
|
21
23
|
signals.off(s, onSignal);
|
|
24
|
+
unsubscribe();
|
|
22
25
|
};
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
dispose();
|
|
27
|
-
forced = true;
|
|
28
|
-
exit(1);
|
|
29
|
-
return;
|
|
30
|
-
}
|
|
31
|
-
log.info("signal received; shutting down", { signal });
|
|
32
|
-
const end = (code) => log
|
|
26
|
+
/** Runs `close` once, then exits with `code` (1 when the stop failed). */
|
|
27
|
+
function stop(code) {
|
|
28
|
+
const end = (c) => log
|
|
33
29
|
.flush()
|
|
34
30
|
.catch(() => { })
|
|
35
31
|
.then(() => {
|
|
36
32
|
dispose();
|
|
37
33
|
if (!forced)
|
|
38
|
-
exit(
|
|
34
|
+
exit(c);
|
|
39
35
|
});
|
|
40
|
-
exiting = close().then(() => end(
|
|
36
|
+
exiting = close().then(() => end(code), (err) => {
|
|
41
37
|
log.error("shutdown failed", { err });
|
|
42
38
|
return end(1);
|
|
43
39
|
});
|
|
44
40
|
}
|
|
41
|
+
function onSignal(signal) {
|
|
42
|
+
if (exiting) {
|
|
43
|
+
log.warn("second signal received; exiting immediately", { signal });
|
|
44
|
+
dispose();
|
|
45
|
+
forced = true;
|
|
46
|
+
exit(1);
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
log.info("signal received; shutting down", { signal });
|
|
50
|
+
stop(0);
|
|
51
|
+
}
|
|
45
52
|
for (const s of SHUTDOWN_SIGNALS)
|
|
46
53
|
signals.on(s, onSignal);
|
|
54
|
+
if (opts.faults) {
|
|
55
|
+
unsubscribe = opts.faults((kind) => {
|
|
56
|
+
if (exiting)
|
|
57
|
+
return;
|
|
58
|
+
log.error("fatal event swallowed; shutting down so the process is replaced", { kind });
|
|
59
|
+
stop(1);
|
|
60
|
+
});
|
|
61
|
+
}
|
|
47
62
|
return { exiting: () => exiting, dispose };
|
|
48
63
|
}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import type { KernelLogger } from "../../log.js";
|
|
2
1
|
import { KernelDb } from "../database/kernel-db.js";
|
|
3
2
|
import { TransactionHost } from "../database/transaction-host.js";
|
|
4
3
|
import type { KernelQueueName } from "../queue/queue-names.js";
|
|
@@ -23,10 +22,16 @@ export type OutboxFastPath = (ids: readonly string[]) => Promise<void>;
|
|
|
23
22
|
/** The fast path `add` hands each committed transaction's rows to (`OutboxModule` provides it). */
|
|
24
23
|
export declare const OUTBOX_FAST_PATH: unique symbol;
|
|
25
24
|
/**
|
|
26
|
-
*
|
|
27
|
-
*
|
|
25
|
+
* A job id reused with different data: the id is wrong (two pieces of work share it), so the
|
|
26
|
+
* caller's transaction fails in every environment instead of silently running one of them.
|
|
28
27
|
*/
|
|
29
|
-
export declare
|
|
28
|
+
export declare class OutboxConflictError extends Error {
|
|
29
|
+
readonly queue: string;
|
|
30
|
+
readonly jobId: string;
|
|
31
|
+
readonly job: string;
|
|
32
|
+
readonly owedJob: string;
|
|
33
|
+
constructor(queue: string, jobId: string, job: string, owedJob: string);
|
|
34
|
+
}
|
|
30
35
|
/**
|
|
31
36
|
* Writes owed work as a row in the caller's transaction (spec §3.2): the row commits or rolls back
|
|
32
37
|
* with the business write, and after the commit the fast path delivers it when it is due now (a
|
|
@@ -35,15 +40,13 @@ export declare const OUTBOX_STRICT_CONFLICTS: unique symbol;
|
|
|
35
40
|
export declare class OutboxService {
|
|
36
41
|
readonly txHost: TransactionHost;
|
|
37
42
|
private readonly db;
|
|
38
|
-
private readonly log;
|
|
39
43
|
private readonly fastPath;
|
|
40
|
-
|
|
41
|
-
constructor(txHost: TransactionHost, db: KernelDb, log: KernelLogger, fastPath: OutboxFastPath, strictConflicts?: boolean);
|
|
44
|
+
constructor(txHost: TransactionHost, db: KernelDb, fastPath: OutboxFastPath);
|
|
42
45
|
/**
|
|
43
46
|
* Adds the job to the outbox in the transaction in context (throws outside one). Returns true when
|
|
44
47
|
* it inserted a row, false when the same (queue, jobId) is already owed (a no-op; a dead row is
|
|
45
|
-
* not owed). A conflict whose stored data differs is a bug in the job id: it throws
|
|
46
|
-
*
|
|
48
|
+
* not owed). A conflict whose stored data differs is a bug in the job id: it throws
|
|
49
|
+
* {@link OutboxConflictError}, so the caller's transaction fails. Undefined data is stored as JSON null.
|
|
47
50
|
*/
|
|
48
51
|
add<T>(job: OutboxJob<T>): Promise<boolean>;
|
|
49
52
|
/**
|
|
@@ -8,19 +8,31 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
|
8
8
|
return function (target, key) { decorator(target, key, paramIndex); }
|
|
9
9
|
};
|
|
10
10
|
import { isDeepStrictEqual } from "node:util";
|
|
11
|
-
import { Inject, Injectable
|
|
11
|
+
import { Inject, Injectable } from "@nestjs/common";
|
|
12
12
|
import { afterCommit } from "../database/after-commit.js";
|
|
13
13
|
import { KernelDb } from "../database/kernel-db.js";
|
|
14
14
|
import { currentStore, TransactionHost } from "../database/transaction-host.js";
|
|
15
15
|
import { Transactional } from "../database/transactional.decorator.js";
|
|
16
|
-
import { KERNEL_LOGGER } from "../tokens.js";
|
|
17
16
|
/** The fast path `add` hands each committed transaction's rows to (`OutboxModule` provides it). */
|
|
18
17
|
export const OUTBOX_FAST_PATH = Symbol("OUTBOX_FAST_PATH");
|
|
19
18
|
/**
|
|
20
|
-
*
|
|
21
|
-
*
|
|
19
|
+
* A job id reused with different data: the id is wrong (two pieces of work share it), so the
|
|
20
|
+
* caller's transaction fails in every environment instead of silently running one of them.
|
|
22
21
|
*/
|
|
23
|
-
export
|
|
22
|
+
export class OutboxConflictError extends Error {
|
|
23
|
+
queue;
|
|
24
|
+
jobId;
|
|
25
|
+
job;
|
|
26
|
+
owedJob;
|
|
27
|
+
constructor(queue, jobId, job, owedJob) {
|
|
28
|
+
super(`outbox job id reused with different data: ${JSON.stringify({ queue, jobId, job, owedJob })}`);
|
|
29
|
+
this.queue = queue;
|
|
30
|
+
this.jobId = jobId;
|
|
31
|
+
this.job = job;
|
|
32
|
+
this.owedJob = owedJob;
|
|
33
|
+
this.name = "OutboxConflictError";
|
|
34
|
+
}
|
|
35
|
+
}
|
|
24
36
|
/** Jobs per insert statement of {@link OutboxService.addMany} (6 parameters each). */
|
|
25
37
|
const ADD_MANY_CHUNK = 1000;
|
|
26
38
|
/** The row of `job` (throws on a job id with `:`). */
|
|
@@ -57,21 +69,17 @@ const pendingIds = new WeakMap();
|
|
|
57
69
|
let OutboxService = class OutboxService {
|
|
58
70
|
txHost;
|
|
59
71
|
db;
|
|
60
|
-
log;
|
|
61
72
|
fastPath;
|
|
62
|
-
|
|
63
|
-
constructor(txHost, db, log, fastPath, strictConflicts = false) {
|
|
73
|
+
constructor(txHost, db, fastPath) {
|
|
64
74
|
this.txHost = txHost;
|
|
65
75
|
this.db = db;
|
|
66
|
-
this.log = log;
|
|
67
76
|
this.fastPath = fastPath;
|
|
68
|
-
this.strictConflicts = strictConflicts;
|
|
69
77
|
}
|
|
70
78
|
/**
|
|
71
79
|
* Adds the job to the outbox in the transaction in context (throws outside one). Returns true when
|
|
72
80
|
* it inserted a row, false when the same (queue, jobId) is already owed (a no-op; a dead row is
|
|
73
|
-
* not owed). A conflict whose stored data differs is a bug in the job id: it throws
|
|
74
|
-
*
|
|
81
|
+
* not owed). A conflict whose stored data differs is a bug in the job id: it throws
|
|
82
|
+
* {@link OutboxConflictError}, so the caller's transaction fails. Undefined data is stored as JSON null.
|
|
75
83
|
*/
|
|
76
84
|
async add(job) {
|
|
77
85
|
const json = JSON.stringify(job.data ?? null);
|
|
@@ -95,16 +103,7 @@ let OutboxService = class OutboxService {
|
|
|
95
103
|
.executeTakeFirst();
|
|
96
104
|
// no row: the owed one was delivered (and deleted) since the conflict; BullMQ dedupes the id
|
|
97
105
|
if (stored && !isDeepStrictEqual(stored.data, JSON.parse(json))) {
|
|
98
|
-
|
|
99
|
-
const fields = {
|
|
100
|
-
queue: job.queue,
|
|
101
|
-
jobId: job.jobId,
|
|
102
|
-
job: job.name,
|
|
103
|
-
owedJob: stored.job_name,
|
|
104
|
-
};
|
|
105
|
-
if (this.strictConflicts)
|
|
106
|
-
throw new Error(`${msg}: ${JSON.stringify(fields)}`);
|
|
107
|
-
this.log.error(msg, fields);
|
|
106
|
+
throw new OutboxConflictError(job.queue, job.jobId, job.name, stored.job_name);
|
|
108
107
|
}
|
|
109
108
|
return false;
|
|
110
109
|
}
|
|
@@ -157,9 +156,6 @@ OutboxService = __decorate([
|
|
|
157
156
|
Injectable(),
|
|
158
157
|
__param(0, Inject(TransactionHost)),
|
|
159
158
|
__param(1, Inject(KernelDb)),
|
|
160
|
-
__param(2, Inject(
|
|
161
|
-
__param(3, Inject(OUTBOX_FAST_PATH)),
|
|
162
|
-
__param(4, Optional()),
|
|
163
|
-
__param(4, Inject(OUTBOX_STRICT_CONFLICTS))
|
|
159
|
+
__param(2, Inject(OUTBOX_FAST_PATH))
|
|
164
160
|
], OutboxService);
|
|
165
161
|
export { OutboxService };
|