@capybara-hq/kernel 0.1.0-rc.104 → 0.1.0-rc.106
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/dist/agents/agents.schemas.d.ts +9 -9
- package/dist/{schedules/schedules.controller.d.ts → automations/automations.controller.d.ts} +37 -32
- package/dist/{schedules/schedules.controller.js → automations/automations.controller.js} +68 -57
- package/dist/automations/automations.module.d.ts +16 -0
- package/dist/{schedules/schedules.module.js → automations/automations.module.js} +18 -15
- package/dist/{schedules/schedules.schemas.d.ts → automations/automations.schemas.d.ts} +151 -50
- package/dist/automations/automations.schemas.js +253 -0
- package/dist/{schedules/scheduled-tasks.service.d.ts → automations/automations.service.d.ts} +99 -52
- package/dist/{schedules/scheduled-tasks.service.js → automations/automations.service.js} +303 -134
- package/dist/{schedules → automations}/calendar.d.ts +8 -8
- package/dist/{schedules → automations}/calendar.js +2 -2
- package/dist/automations/effective-settings.d.ts +28 -0
- package/dist/automations/effective-settings.js +25 -0
- package/dist/automations/errors.d.ts +19 -0
- package/dist/automations/errors.js +19 -0
- package/dist/automations/events/coalesce.d.ts +28 -0
- package/dist/automations/events/coalesce.js +131 -0
- package/dist/automations/events/deadline.d.ts +10 -0
- package/dist/automations/events/deadline.js +24 -0
- package/dist/automations/events/dispatcher.d.ts +74 -0
- package/dist/automations/events/dispatcher.js +353 -0
- package/dist/automations/events/events.module.d.ts +7 -0
- package/dist/automations/events/events.module.js +26 -0
- package/dist/automations/events/guards.d.ts +32 -0
- package/dist/automations/events/guards.js +87 -0
- package/dist/automations/events/sweep.job.d.ts +49 -0
- package/dist/automations/events/sweep.job.js +202 -0
- package/dist/automations/events/token.d.ts +5 -0
- package/dist/automations/events/token.js +5 -0
- package/dist/automations/events/trigger-events.service.d.ts +47 -0
- package/dist/automations/events/trigger-events.service.js +254 -0
- package/dist/{schedules → automations}/fire.d.ts +57 -17
- package/dist/{schedules → automations}/fire.js +311 -79
- package/dist/{schedules → automations}/grant-rules.d.ts +1 -1
- package/dist/{schedules → automations}/grant-rules.js +5 -5
- package/dist/automations/job-ids.d.ts +113 -0
- package/dist/automations/job-ids.js +117 -0
- package/dist/{schedules → automations}/pause.d.ts +3 -3
- package/dist/{schedules → automations}/pause.js +3 -3
- package/dist/{schedules → automations}/run-tracker.d.ts +21 -10
- package/dist/{schedules → automations}/run-tracker.js +68 -56
- package/dist/{schedules → automations}/scan.job.d.ts +12 -8
- package/dist/{schedules → automations}/scan.job.js +39 -23
- package/dist/{schedules → automations}/schedule-math.d.ts +19 -12
- package/dist/{schedules → automations}/schedule-math.js +17 -7
- package/dist/{schedules → automations}/store.d.ts +57 -27
- package/dist/{schedules → automations}/store.js +102 -52
- package/dist/automations/store.module.d.ts +6 -0
- package/dist/{schedules → automations}/store.module.js +9 -9
- package/dist/automations/types.d.ts +178 -0
- package/dist/{schedules → automations}/unattended.d.ts +22 -11
- package/dist/{schedules → automations}/unattended.js +53 -30
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/channels/channels.module.js +3 -3
- package/dist/channels/outbound.d.ts +5 -5
- package/dist/channels/outbound.js +17 -17
- package/dist/channels/threads.d.ts +1 -1
- package/dist/channels/threads.js +1 -1
- package/dist/config/schema.d.ts +5 -1
- package/dist/config/schema.js +44 -6
- package/dist/conversations/approval-profile.d.ts +2 -2
- package/dist/conversations/approval-profile.js +3 -3
- package/dist/conversations/conversations.controller.d.ts +7 -1
- package/dist/conversations/conversations.controller.js +26 -10
- package/dist/conversations/conversations.service.d.ts +103 -25
- package/dist/conversations/conversations.service.js +138 -33
- package/dist/conversations/events.d.ts +48 -1
- package/dist/conversations/events.js +61 -9
- package/dist/conversations/message-context.d.ts +2 -2
- package/dist/conversations/message-context.js +1 -1
- package/dist/conversations/permission-profile-store.d.ts +2 -1
- package/dist/conversations/permission-profiles.controller.d.ts +3 -0
- package/dist/conversations/permission-profiles.service.js +1 -1
- package/dist/conversations/prompt-suggestion-request.d.ts +1 -1
- package/dist/conversations/prompt-suggestion-request.js +2 -1
- package/dist/conversations/queue.d.ts +7 -4
- package/dist/conversations/queue.js +6 -2
- package/dist/conversations/queue.service.d.ts +5 -5
- package/dist/conversations/queue.service.js +20 -14
- package/dist/ctx/create-ctx.d.ts +20 -1
- package/dist/ctx/create-ctx.js +59 -2
- package/dist/db/kernel-schema.d.ts +104 -25
- package/dist/devices/device-project-files.service.d.ts +88 -0
- package/dist/devices/device-project-files.service.js +249 -0
- package/dist/devices/device-projects.service.d.ts +40 -0
- package/dist/devices/device-projects.service.js +16 -13
- package/dist/devices/devices.controller.d.ts +9 -3
- package/dist/devices/devices.controller.js +27 -5
- package/dist/devices/devices.module.js +9 -1
- package/dist/devices/devices.schemas.js +6 -1
- package/dist/devices/dto.d.ts +15 -0
- package/dist/devices/dto.js +11 -0
- package/dist/devices/project-paths.d.ts +29 -0
- package/dist/devices/project-paths.js +66 -0
- package/dist/devices/project-rules.d.ts +5 -1
- package/dist/devices/project-rules.js +5 -1
- package/dist/errors.d.ts +47 -13
- package/dist/errors.js +47 -13
- package/dist/evals/reconstruct.d.ts +10 -1
- package/dist/evals/reconstruct.js +7 -0
- package/dist/extensions/host.d.ts +6 -1
- package/dist/extensions/host.js +10 -0
- package/dist/extensions/permission-set.d.ts +17 -1
- package/dist/extensions/permission-set.js +13 -1
- package/dist/extensions/permission-view.d.ts +1 -1
- package/dist/extensions/permission-view.js +4 -1
- package/dist/git/gateway.js +2 -2
- package/dist/handoff/app-schemes.d.ts +28 -0
- package/dist/handoff/app-schemes.js +41 -0
- package/dist/handoff/handoff-paths.d.ts +26 -0
- package/dist/handoff/handoff-paths.js +25 -0
- package/dist/handoff/handoff-tickets.d.ts +28 -0
- package/dist/handoff/handoff-tickets.js +111 -0
- package/dist/handoff/handoff.controller.d.ts +24 -0
- package/dist/handoff/handoff.controller.js +74 -0
- package/dist/handoff/handoff.module.d.ts +7 -0
- package/dist/handoff/handoff.module.js +26 -0
- package/dist/handoff/handoff.schemas.d.ts +13 -0
- package/dist/handoff/handoff.schemas.js +3 -0
- package/dist/handoff/handoff.service.d.ts +49 -0
- package/dist/handoff/handoff.service.js +96 -0
- package/dist/http/api.module.js +13 -5
- package/dist/http/meta.controller.d.ts +1 -0
- package/dist/http/meta.controller.js +7 -0
- package/dist/http/request-signal.d.ts +8 -0
- package/dist/http/request-signal.js +14 -0
- package/dist/identity/sso.controller.d.ts +30 -6
- package/dist/identity/sso.controller.js +51 -17
- package/dist/identity/sso.d.ts +10 -2
- package/dist/identity/sso.js +15 -3
- package/dist/inbox/inbox.module.js +2 -2
- package/dist/inbox/inbox.service.d.ts +8 -8
- package/dist/inbox/inbox.service.js +7 -7
- package/dist/infra/config/kernel-config.service.js +10 -5
- package/dist/infra/outbox/registry.d.ts +29 -2
- package/dist/infra/outbox/registry.js +30 -7
- package/dist/kernel.module.js +3 -0
- package/dist/orgs/roles.d.ts +1 -1
- package/dist/orgs/roles.js +3 -3
- package/dist/orgs/settings.controller.d.ts +1 -1
- package/dist/orgs/settings.service.d.ts +27 -11
- package/dist/orgs/settings.service.js +42 -24
- package/dist/overrides.d.ts +4 -4
- package/dist/overrides.js +1 -1
- package/dist/platform/exclusions.js +5 -0
- package/dist/platform/operation.js +2 -2
- package/dist/platform/ops/{schedules.ops.d.ts → automations.ops.d.ts} +4 -4
- package/dist/platform/ops/automations.ops.js +560 -0
- package/dist/platform/ops/connectors.ops.js +4 -2
- package/dist/platform/ops/devices.ops.d.ts +3 -1
- package/dist/platform/ops/devices.ops.js +77 -3
- package/dist/platform/ops/inbox.ops.js +4 -4
- package/dist/platform/ops/orgs.ops.js +1 -1
- package/dist/platform/ops/platform.ops.js +4 -4
- package/dist/platform/platform-ops.module.d.ts +2 -2
- package/dist/platform/platform-ops.module.js +5 -5
- package/dist/platform/route-schemas.js +3 -3
- package/dist/push/jobs.d.ts +3 -3
- package/dist/push/jobs.js +2 -2
- package/dist/push/preferences.service.js +1 -1
- package/dist/push/push-owed.d.ts +3 -3
- package/dist/push/push-owed.js +6 -6
- package/dist/push/push.schemas.d.ts +4 -4
- package/dist/push/push.schemas.js +3 -3
- package/dist/push/recipients.d.ts +4 -4
- package/dist/push/recipients.js +23 -23
- package/dist/push/texts.d.ts +3 -3
- package/dist/push/texts.js +2 -2
- package/dist/push/triggers.d.ts +1 -1
- package/dist/roles/worker.module.js +3 -3
- package/dist/runtime/compaction.service.d.ts +3 -1
- package/dist/runtime/compaction.service.js +3 -1
- package/dist/runtime/context/build.d.ts +6 -0
- package/dist/runtime/context/build.js +14 -3
- package/dist/runtime/context/compaction.d.ts +27 -1
- package/dist/runtime/context/compaction.js +102 -37
- package/dist/runtime/context/run-context.d.ts +38 -0
- package/dist/runtime/context/run-context.js +54 -0
- package/dist/runtime/maintenance.d.ts +8 -4
- package/dist/runtime/maintenance.js +37 -16
- package/dist/runtime/model-call.d.ts +6 -4
- package/dist/runtime/model-call.js +17 -7
- package/dist/runtime/project/knowledge.service.d.ts +16 -7
- package/dist/runtime/project/knowledge.service.js +31 -13
- package/dist/runtime/run-finish.d.ts +4 -4
- package/dist/runtime/run-finish.js +3 -3
- package/dist/runtime/run-queue.js +12 -7
- package/dist/runtime/run-worker.js +7 -1
- package/dist/runtime/runtime.module.js +3 -3
- package/dist/runtime/subagents/dispatch.js +11 -3
- package/dist/sandbox/browse-roots.d.ts +8 -0
- package/dist/sandbox/browse-roots.js +22 -0
- package/dist/sandbox/network-grants.d.ts +4 -4
- package/dist/sandbox/network-grants.js +7 -7
- package/dist/sandbox/operation-authority.d.ts +10 -3
- package/dist/sandbox/operation-authority.js +20 -10
- package/dist/sandbox/operation-intents.d.ts +3 -1
- package/dist/sandbox/operation-intents.js +11 -4
- package/dist/sandbox/permission-call-grants.js +2 -2
- package/dist/sandbox/permission-facts.js +1 -1
- package/dist/sandbox/review/classifier.d.ts +2 -2
- package/dist/sandbox/review/classifier.js +22 -11
- package/dist/sandbox/review/permission-candidate.d.ts +1 -1
- package/dist/sandbox/review/permission-candidate.js +1 -1
- package/dist/sandbox/sandbox.service.d.ts +15 -5
- package/dist/sandbox/sandbox.service.js +14 -8
- package/dist/storage/purge.d.ts +1 -1
- package/dist/storage/purge.js +2 -2
- package/dist/tools/approvals.service.d.ts +6 -6
- package/dist/tools/approvals.service.js +19 -19
- package/dist/tools/builtin-names.d.ts +12 -12
- package/dist/tools/builtin-names.js +29 -29
- package/dist/tools/builtins/{schedules.d.ts → automations.d.ts} +35 -33
- package/dist/tools/builtins/{schedules.js → automations.js} +236 -105
- package/dist/tools/builtins/builtin-tools.d.ts +8 -8
- package/dist/tools/builtins/builtin-tools.js +16 -16
- package/dist/tools/call-scope.d.ts +1 -1
- package/dist/tools/connectors.service.d.ts +4 -13
- package/dist/tools/connectors.service.js +12 -21
- package/dist/tools/git-asks.js +1 -1
- package/dist/tools/git-push-policy.d.ts +3 -3
- package/dist/tools/git-push-policy.js +6 -6
- package/dist/tools/network-asks.d.ts +3 -3
- package/dist/tools/network-asks.js +3 -3
- package/dist/tools/oauth/flow.d.ts +16 -2
- package/dist/tools/oauth/flow.js +23 -4
- package/dist/tools/oauth/oauth.controller.d.ts +19 -7
- package/dist/tools/oauth/oauth.controller.js +42 -12
- package/dist/tools/oauth/oauth.schemas.d.ts +14 -1
- package/dist/tools/oauth/oauth.schemas.js +4 -1
- package/dist/tools/pipeline.d.ts +4 -4
- package/dist/tools/pipeline.js +2 -2
- package/dist/tools/policy.d.ts +3 -3
- package/dist/tools/policy.js +3 -3
- package/dist/tools/tools.module.js +9 -9
- package/package.json +3 -3
- package/src/migrations/0188_automations_rename.sql +309 -0
- package/src/migrations/0189_event_automations.sql +136 -0
- package/dist/platform/ops/schedules.ops.js +0 -509
- package/dist/schedules/effective-settings.d.ts +0 -22
- package/dist/schedules/effective-settings.js +0 -18
- package/dist/schedules/errors.d.ts +0 -8
- package/dist/schedules/errors.js +0 -8
- package/dist/schedules/job-ids.d.ts +0 -81
- package/dist/schedules/job-ids.js +0 -95
- package/dist/schedules/schedules.module.d.ts +0 -16
- package/dist/schedules/schedules.schemas.js +0 -213
- package/dist/schedules/store.module.d.ts +0 -6
- package/dist/schedules/types.d.ts +0 -110
- /package/dist/{schedules → automations}/types.js +0 -0
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
8
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
9
|
+
};
|
|
10
|
+
import { matchesFilter, } from "@capybara-hq/plugin-sdk";
|
|
11
|
+
import { Inject, Injectable, Module } from "@nestjs/common";
|
|
12
|
+
import { sql } from "kysely";
|
|
13
|
+
import { conversationAncestors } from "../../conversations/tree.js";
|
|
14
|
+
import { ExtensionsModule } from "../../extensions/extensions.module.js";
|
|
15
|
+
import { ExtensionPointDefaults } from "../../extensions/point-defaults.js";
|
|
16
|
+
import { KernelConfigService } from "../../infra/config/kernel-config.service.js";
|
|
17
|
+
import { KernelDb } from "../../infra/database/kernel-db.js";
|
|
18
|
+
import { TransactionHost } from "../../infra/database/transaction-host.js";
|
|
19
|
+
import { Transactional } from "../../infra/database/transactional.decorator.js";
|
|
20
|
+
import { OutboxService } from "../../infra/outbox/outbox.service.js";
|
|
21
|
+
import { KERNEL_LOGGER } from "../../infra/tokens.js";
|
|
22
|
+
import { MAINTENANCE_QUEUE_NAME } from "../../runtime/maintenance-queue.js";
|
|
23
|
+
import { readAutomationSettings } from "../effective-settings.js";
|
|
24
|
+
import { AUTOMATION_COALESCE_JOB, } from "../job-ids.js";
|
|
25
|
+
import { AutomationStoreModule } from "../store.module.js";
|
|
26
|
+
import { EventCoalescer } from "./coalesce.js";
|
|
27
|
+
import { TriggerSourceTimeout, withDeadline } from "./deadline.js";
|
|
28
|
+
import { COALESCE_STALE_MS, coalesceJobId, depthExceeded, isSelfTriggered, subjectKey, } from "./guards.js";
|
|
29
|
+
import { TriggerEventSweepJob } from "./sweep.job.js";
|
|
30
|
+
export { TriggerSourceTimeout } from "./deadline.js";
|
|
31
|
+
/** Whether the automation's trigger still selects the event (re-read under its row lock). */
|
|
32
|
+
function triggerSelects(trigger, ev, decl) {
|
|
33
|
+
if (trigger.kind !== "event" || trigger.source !== ev.plugin)
|
|
34
|
+
return false;
|
|
35
|
+
if (!trigger.types.includes(ev.type))
|
|
36
|
+
return false;
|
|
37
|
+
const filter = trigger.filter ?? [];
|
|
38
|
+
return filterAllowed(filter, decl) && matchesFilter(filter, ev.facts);
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* A filter on a fact the source does not declare filterable never matches: an automation cannot
|
|
42
|
+
* filter on a fact its source keeps out of filters (collaboration spec §4.3).
|
|
43
|
+
*/
|
|
44
|
+
function filterAllowed(filter, decl) {
|
|
45
|
+
return filter.every((c) => {
|
|
46
|
+
const fact = Object.hasOwn(decl.facts, c.fact) ? decl.facts[c.fact] : undefined;
|
|
47
|
+
return fact?.filterable === true;
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Routes one stored trigger event to the event automations it fires (collaboration spec §4.3,
|
|
52
|
+
* §4.7), the `trigger-dispatch` job. In order:
|
|
53
|
+
* - an event no longer `pending` was dispatched before (a retried job): nothing to do;
|
|
54
|
+
* - a directed event (`audience` set) is left `pending` for acceptance routing (PR C);
|
|
55
|
+
* - past the org's `maxEventDepth` the event is `depth_stopped`;
|
|
56
|
+
* - a source the org switched off (`eventSourcesOff`), or one that does not serve the org now (its
|
|
57
|
+
* extension disabled, unloaded, its config invalid) or no longer declares the type, leaves the
|
|
58
|
+
* event `undelivered`: no run, no retry. A provider whose status could not be read (a transient
|
|
59
|
+
* error) fails the job, so BullMQ retries it;
|
|
60
|
+
* - the active, unexpired event automations of the org on this source and type whose filter
|
|
61
|
+
* matches the facts, minus the ones the event's cause run made (the same owner and the agent of
|
|
62
|
+
* the run's root conversation: self-trigger), are checked with the source's `visible()` once for
|
|
63
|
+
* all their owners; an owner it does not admit gets nothing;
|
|
64
|
+
* - each remaining automation gets a delivery, and the delivery that opens a window for its
|
|
65
|
+
* (automation, subject) pair owes the pair's `automation-coalesce` job, due `coalesceSeconds`
|
|
66
|
+
* on; later events of the window find its deliveries waiting and owe nothing, so the window ends
|
|
67
|
+
* in one run ({@link EventCoalescer}). The event becomes `dispatched`.
|
|
68
|
+
*
|
|
69
|
+
* The provider is asked outside any transaction; the deliveries, the owed jobs and the state are
|
|
70
|
+
* written in one, each automation row locked (id order), so a flush and a dispatch of one pair never
|
|
71
|
+
* interleave.
|
|
72
|
+
*/
|
|
73
|
+
let TriggerDispatcher = class TriggerDispatcher {
|
|
74
|
+
kdb;
|
|
75
|
+
txHost;
|
|
76
|
+
config;
|
|
77
|
+
points;
|
|
78
|
+
outbox;
|
|
79
|
+
log;
|
|
80
|
+
constructor(kdb, txHost, config, points, outbox, log) {
|
|
81
|
+
this.kdb = kdb;
|
|
82
|
+
this.txHost = txHost;
|
|
83
|
+
this.config = config;
|
|
84
|
+
this.points = points;
|
|
85
|
+
this.outbox = outbox;
|
|
86
|
+
this.log = log;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Dispatches event `eventId` of org `orgId` (see the class). The source's `events()` and
|
|
90
|
+
* `visible()` each have `tools.timeoutMs`: past it the job fails with
|
|
91
|
+
* {@link TriggerSourceTimeout} (BullMQ retries it), and on its last attempt (`finalAttempt`) the
|
|
92
|
+
* event is `undelivered` instead.
|
|
93
|
+
*/
|
|
94
|
+
async dispatch(data, opts = {}) {
|
|
95
|
+
const { orgId, eventId } = data;
|
|
96
|
+
const db = this.kdb.db;
|
|
97
|
+
const ev = await db
|
|
98
|
+
.selectFrom("trigger_events")
|
|
99
|
+
.selectAll()
|
|
100
|
+
.where("org_id", "=", orgId)
|
|
101
|
+
.where("id", "=", eventId)
|
|
102
|
+
.executeTakeFirst();
|
|
103
|
+
if (ev === undefined || ev.state !== "pending")
|
|
104
|
+
return;
|
|
105
|
+
const ctx = { orgId, eventId, plugin: ev.plugin, type: ev.type };
|
|
106
|
+
if (ev.audience !== null) {
|
|
107
|
+
// TODO(collaboration C2): directed events are routed by the acceptance rules
|
|
108
|
+
this.log.info("directed trigger event left pending for acceptance routing", ctx);
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
const settings = await readAutomationSettings(db, this.config, orgId);
|
|
112
|
+
if (depthExceeded(ev.depth, settings.maxEventDepth)) {
|
|
113
|
+
// TODO(collaboration C1): the inbox notice to the owners of the chain's last automation
|
|
114
|
+
this.log.warn("trigger event past the org's chain depth; not dispatched", {
|
|
115
|
+
...ctx,
|
|
116
|
+
depth: ev.depth,
|
|
117
|
+
maxEventDepth: settings.maxEventDepth,
|
|
118
|
+
});
|
|
119
|
+
await this.setState(orgId, eventId, "depth_stopped");
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
if (settings.eventSourcesOff.includes(ev.plugin)) {
|
|
123
|
+
this.log.info("trigger event of a source the org switched off; not dispatched", ctx);
|
|
124
|
+
await this.setState(orgId, eventId, "undelivered");
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
const { providers, failed } = await this.points.providersFor(orgId, "trigger-source");
|
|
128
|
+
const source = providers.find((p) => p.extension === ev.plugin);
|
|
129
|
+
if (source === undefined) {
|
|
130
|
+
if (failed.has(ev.plugin)) {
|
|
131
|
+
// a transient read error: neither serving nor known to be off; the job retries
|
|
132
|
+
throw new Error(`trigger source ${ev.plugin} status could not be read for org ${orgId}`);
|
|
133
|
+
}
|
|
134
|
+
this.log.info("trigger event of a source that does not serve the org; undelivered", ctx);
|
|
135
|
+
await this.setState(orgId, eventId, "undelivered");
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
const ms = this.config.get().tools.timeoutMs;
|
|
139
|
+
const ask = async (what, call) => {
|
|
140
|
+
try {
|
|
141
|
+
return await withDeadline(ev.plugin, what, ms, call);
|
|
142
|
+
}
|
|
143
|
+
catch (err) {
|
|
144
|
+
if (!(err instanceof TriggerSourceTimeout) || opts.finalAttempt !== true)
|
|
145
|
+
throw err;
|
|
146
|
+
this.log.warn("trigger source did not answer on the dispatch's last attempt; undelivered", {
|
|
147
|
+
...ctx,
|
|
148
|
+
err,
|
|
149
|
+
});
|
|
150
|
+
await this.setState(orgId, eventId, "undelivered");
|
|
151
|
+
return undefined;
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
const declared = await ask("events()", () => source.impl.events());
|
|
155
|
+
if (declared === undefined)
|
|
156
|
+
return;
|
|
157
|
+
const decl = declared.find((d) => d.type === ev.type);
|
|
158
|
+
if (decl === undefined) {
|
|
159
|
+
this.log.info("trigger event of a type its source no longer declares; undelivered", ctx);
|
|
160
|
+
await this.setState(orgId, eventId, "undelivered");
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
const cause = await this.causeOf(orgId, ev.cause_run_id);
|
|
164
|
+
const matching = (await this.candidates(orgId, ev.plugin, ev.type)).filter((a) => filterAllowed(a.filter, decl) &&
|
|
165
|
+
matchesFilter(a.filter, ev.facts) &&
|
|
166
|
+
!isSelfTriggered(a, cause));
|
|
167
|
+
let admitted = new Set();
|
|
168
|
+
const owners = [...new Set(matching.map((a) => a.accountId))].sort();
|
|
169
|
+
if (owners.length > 0) {
|
|
170
|
+
const seen = await ask("visible()", () => source.impl.visible({
|
|
171
|
+
orgId,
|
|
172
|
+
accountIds: owners,
|
|
173
|
+
subject: ev.subject,
|
|
174
|
+
config: source.config,
|
|
175
|
+
}));
|
|
176
|
+
if (seen === undefined)
|
|
177
|
+
return;
|
|
178
|
+
admitted = new Set(seen.filter((a) => owners.includes(a)));
|
|
179
|
+
}
|
|
180
|
+
await this.record(ev, matching.filter((a) => admitted.has(a.accountId)).map((a) => a.id), { decl, cause, coalesceSeconds: settings.coalesceSeconds });
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Delivers `ev` to `automationIds` and owes each opened window's coalesce job (see the class),
|
|
184
|
+
* then marks the event `dispatched`; nothing when another dispatch of it got there first. Each
|
|
185
|
+
* automation's trigger and agent are read again under its row lock: one edited since the match
|
|
186
|
+
* (another type, source or filter; the cause run's agent now) gets no delivery.
|
|
187
|
+
*/
|
|
188
|
+
async record(ev, automationIds, match) {
|
|
189
|
+
const { decl, cause, coalesceSeconds } = match;
|
|
190
|
+
const db = this.kdb.db;
|
|
191
|
+
const orgId = ev.org_id;
|
|
192
|
+
const held = await db
|
|
193
|
+
.selectFrom("trigger_events")
|
|
194
|
+
.select("state")
|
|
195
|
+
.where("org_id", "=", orgId)
|
|
196
|
+
.where("id", "=", ev.id)
|
|
197
|
+
.forUpdate()
|
|
198
|
+
.executeTakeFirst();
|
|
199
|
+
if (held?.state !== "pending")
|
|
200
|
+
return;
|
|
201
|
+
const key = subjectKey(ev.subject);
|
|
202
|
+
const now = Date.now();
|
|
203
|
+
for (const automationId of [...automationIds].sort()) {
|
|
204
|
+
// the automation row first, as the flush takes it: switched off, expired or deleted since,
|
|
205
|
+
// skipped
|
|
206
|
+
const live = await db
|
|
207
|
+
.selectFrom("automations")
|
|
208
|
+
.select(["account_id", "agent_id", "trigger"])
|
|
209
|
+
.where("org_id", "=", orgId)
|
|
210
|
+
.where("id", "=", automationId)
|
|
211
|
+
.where("status", "=", "active")
|
|
212
|
+
.where("deleted_at", "is", null)
|
|
213
|
+
.where((eb) => eb.or([eb("expires_at", "is", null), eb("expires_at", ">", sql `now()`)]))
|
|
214
|
+
.forUpdate()
|
|
215
|
+
.executeTakeFirst();
|
|
216
|
+
if (live === undefined)
|
|
217
|
+
continue;
|
|
218
|
+
if (!triggerSelects(live.trigger, ev, decl))
|
|
219
|
+
continue;
|
|
220
|
+
if (isSelfTriggered({ accountId: live.account_id, agentId: live.agent_id }, cause))
|
|
221
|
+
continue;
|
|
222
|
+
const waiting = await db
|
|
223
|
+
.selectFrom("automation_event_deliveries")
|
|
224
|
+
.select((eb) => eb.fn.min("created_at").as("first"))
|
|
225
|
+
.where("org_id", "=", orgId)
|
|
226
|
+
.where("automation_id", "=", automationId)
|
|
227
|
+
.where("subject_key", "=", key)
|
|
228
|
+
.where("automation_run_id", "is", null)
|
|
229
|
+
.executeTakeFirst();
|
|
230
|
+
const inserted = await db
|
|
231
|
+
.insertInto("automation_event_deliveries")
|
|
232
|
+
.values({ org_id: orgId, automation_id: automationId, event_id: ev.id, subject_key: key })
|
|
233
|
+
.onConflict((oc) => oc.columns(["automation_id", "event_id"]).doNothing())
|
|
234
|
+
.returning("event_id")
|
|
235
|
+
.executeTakeFirst();
|
|
236
|
+
if (inserted === undefined)
|
|
237
|
+
continue;
|
|
238
|
+
const first = waiting?.first ?? null;
|
|
239
|
+
const open = first !== null &&
|
|
240
|
+
now - new Date(first).getTime() < coalesceSeconds * 1000 + COALESCE_STALE_MS;
|
|
241
|
+
if (open)
|
|
242
|
+
continue;
|
|
243
|
+
if (first !== null) {
|
|
244
|
+
this.log.warn("coalescing window outlived its job; a new window takes its events", {
|
|
245
|
+
orgId,
|
|
246
|
+
automationId,
|
|
247
|
+
subjectKey: key,
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
await this.outbox.add({
|
|
251
|
+
queue: MAINTENANCE_QUEUE_NAME,
|
|
252
|
+
name: AUTOMATION_COALESCE_JOB,
|
|
253
|
+
// one id per window: an add while an earlier window's job of the pair is still active
|
|
254
|
+
// (flushing) or kept would otherwise be swallowed by BullMQ
|
|
255
|
+
jobId: `${coalesceJobId(automationId, ev.subject)}-${ev.id}`,
|
|
256
|
+
data: { orgId, automationId, subjectKey: key },
|
|
257
|
+
runAt: new Date(now + coalesceSeconds * 1000),
|
|
258
|
+
orgId,
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
await this.setState(orgId, ev.id, "dispatched");
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* The active, unexpired event automations of the org on `plugin` whose types include `type` (one
|
|
265
|
+
* past its `expires_at` gets nothing; the scan ends it).
|
|
266
|
+
*/
|
|
267
|
+
async candidates(orgId, plugin, type) {
|
|
268
|
+
const rows = await this.kdb.db
|
|
269
|
+
.selectFrom("automations")
|
|
270
|
+
.select(["id", "account_id", "agent_id", "trigger"])
|
|
271
|
+
.where("org_id", "=", orgId)
|
|
272
|
+
.where("status", "=", "active")
|
|
273
|
+
.where("deleted_at", "is", null)
|
|
274
|
+
.where((eb) => eb.or([eb("expires_at", "is", null), eb("expires_at", ">", sql `now()`)]))
|
|
275
|
+
.where(sql `trigger->>'kind' = 'event'`)
|
|
276
|
+
.where(sql `trigger->>'source' = ${plugin}`)
|
|
277
|
+
.where(sql `trigger->'types' @> ${JSON.stringify([type])}::jsonb`)
|
|
278
|
+
.orderBy("id")
|
|
279
|
+
.execute();
|
|
280
|
+
return rows.flatMap((r) => {
|
|
281
|
+
const t = r.trigger;
|
|
282
|
+
if (t.kind !== "event")
|
|
283
|
+
return [];
|
|
284
|
+
return [{ id: r.id, accountId: r.account_id, agentId: r.agent_id, filter: t.filter ?? [] }];
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* The owner and agent of the run that caused the event (self-trigger), or null. The agent is
|
|
289
|
+
* the root conversation's: a sub-agent dispatched by an automation's run (its conversation a
|
|
290
|
+
* child of the run's) acts for that run, so its events count as the automation's own.
|
|
291
|
+
*/
|
|
292
|
+
async causeOf(orgId, runId) {
|
|
293
|
+
if (runId === null)
|
|
294
|
+
return null;
|
|
295
|
+
const db = this.kdb.db;
|
|
296
|
+
const run = await db
|
|
297
|
+
.selectFrom("runs")
|
|
298
|
+
.innerJoin("conversations", "conversations.id", "runs.conversation_id")
|
|
299
|
+
.select(["runs.trigger_account_id", "conversations.id as conversation_id"])
|
|
300
|
+
.where("runs.id", "=", runId)
|
|
301
|
+
.where("conversations.org_id", "=", orgId)
|
|
302
|
+
.executeTakeFirst();
|
|
303
|
+
if (run?.trigger_account_id == null)
|
|
304
|
+
return null;
|
|
305
|
+
// nearest first: the last ancestor is the root (none: the run's conversation is the root)
|
|
306
|
+
const rootId = (await conversationAncestors(db, run.conversation_id)).at(-1) ?? run.conversation_id;
|
|
307
|
+
const root = await db
|
|
308
|
+
.selectFrom("conversations")
|
|
309
|
+
.select("agent_id")
|
|
310
|
+
.where("id", "=", rootId)
|
|
311
|
+
.where("org_id", "=", orgId)
|
|
312
|
+
.executeTakeFirst();
|
|
313
|
+
if (root?.agent_id == null)
|
|
314
|
+
return null;
|
|
315
|
+
return { runAccountId: run.trigger_account_id, runAgentId: root.agent_id };
|
|
316
|
+
}
|
|
317
|
+
async setState(orgId, eventId, state) {
|
|
318
|
+
await this.kdb.db
|
|
319
|
+
.updateTable("trigger_events")
|
|
320
|
+
.set({ state })
|
|
321
|
+
.where("org_id", "=", orgId)
|
|
322
|
+
.where("id", "=", eventId)
|
|
323
|
+
.where("state", "=", "pending")
|
|
324
|
+
.execute();
|
|
325
|
+
}
|
|
326
|
+
};
|
|
327
|
+
__decorate([
|
|
328
|
+
Transactional()
|
|
329
|
+
], TriggerDispatcher.prototype, "record", null);
|
|
330
|
+
TriggerDispatcher = __decorate([
|
|
331
|
+
Injectable(),
|
|
332
|
+
__param(0, Inject(KernelDb)),
|
|
333
|
+
__param(1, Inject(TransactionHost)),
|
|
334
|
+
__param(2, Inject(KernelConfigService)),
|
|
335
|
+
__param(3, Inject(ExtensionPointDefaults)),
|
|
336
|
+
__param(4, Inject(OutboxService)),
|
|
337
|
+
__param(5, Inject(KERNEL_LOGGER))
|
|
338
|
+
], TriggerDispatcher);
|
|
339
|
+
export { TriggerDispatcher };
|
|
340
|
+
/**
|
|
341
|
+
* The trigger event dispatcher and the coalescer, for the maintenance processor, and the trigger
|
|
342
|
+
* event sweep (`@LockedCron`): worker only (imported by `MaintenanceModule` alone).
|
|
343
|
+
*/
|
|
344
|
+
let TriggerDispatchModule = class TriggerDispatchModule {
|
|
345
|
+
};
|
|
346
|
+
TriggerDispatchModule = __decorate([
|
|
347
|
+
Module({
|
|
348
|
+
imports: [ExtensionsModule, AutomationStoreModule],
|
|
349
|
+
providers: [TriggerDispatcher, EventCoalescer, TriggerEventSweepJob],
|
|
350
|
+
exports: [TriggerDispatcher, EventCoalescer],
|
|
351
|
+
})
|
|
352
|
+
], TriggerDispatchModule);
|
|
353
|
+
export { TriggerDispatchModule };
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `ctx.triggers` (collaboration spec §4.2): {@link TriggerEventsService}. The extension host finds
|
|
3
|
+
* it at the time of use (`ModuleRef`, {@link TRIGGER_EVENTS_BACKEND}); the database and the outbox
|
|
4
|
+
* it writes through are global modules.
|
|
5
|
+
*/
|
|
6
|
+
export declare class TriggerEventsModule {
|
|
7
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
import { Module } from "@nestjs/common";
|
|
8
|
+
import { TRIGGER_EVENTS_BACKEND } from "./token.js";
|
|
9
|
+
import { TriggerEventsService } from "./trigger-events.service.js";
|
|
10
|
+
/**
|
|
11
|
+
* `ctx.triggers` (collaboration spec §4.2): {@link TriggerEventsService}. The extension host finds
|
|
12
|
+
* it at the time of use (`ModuleRef`, {@link TRIGGER_EVENTS_BACKEND}); the database and the outbox
|
|
13
|
+
* it writes through are global modules.
|
|
14
|
+
*/
|
|
15
|
+
let TriggerEventsModule = class TriggerEventsModule {
|
|
16
|
+
};
|
|
17
|
+
TriggerEventsModule = __decorate([
|
|
18
|
+
Module({
|
|
19
|
+
providers: [
|
|
20
|
+
TriggerEventsService,
|
|
21
|
+
{ provide: TRIGGER_EVENTS_BACKEND, useExisting: TriggerEventsService },
|
|
22
|
+
],
|
|
23
|
+
exports: [TriggerEventsService, TRIGGER_EVENTS_BACKEND],
|
|
24
|
+
})
|
|
25
|
+
], TriggerEventsModule);
|
|
26
|
+
export { TriggerEventsModule };
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { EventFilter, TriggerEventDeclaration, TriggerSubject } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
/**
|
|
3
|
+
* A window whose first delivery waits this long past its coalescing window is taken as lost (its
|
|
4
|
+
* job failed for good): the next event of the pair opens a new window with a job of its own, and
|
|
5
|
+
* the trigger event sweep owes a job for a window no event comes to (`TriggerEventSweepJob`).
|
|
6
|
+
*/
|
|
7
|
+
export declare const COALESCE_STALE_MS: number;
|
|
8
|
+
/** A stable, BullMQ-safe key for a trigger subject: `${kind}-${sha1(id).slice(0, 16)}`. */
|
|
9
|
+
export declare function subjectKey(s: TriggerSubject): string;
|
|
10
|
+
/** Deterministic job id for coalescing events of one subject into one automation run. */
|
|
11
|
+
export declare function coalesceJobId(automationId: string, s: TriggerSubject): string;
|
|
12
|
+
/** {@link coalesceJobId} from the subject's stored key ({@link subjectKey}). */
|
|
13
|
+
export declare function coalesceJobIdOfKey(automationId: string, key: string): string;
|
|
14
|
+
/** True when the event was caused by a run of this same automation account and agent. */
|
|
15
|
+
export declare function isSelfTriggered(a: {
|
|
16
|
+
accountId: string;
|
|
17
|
+
agentId: string;
|
|
18
|
+
}, cause: {
|
|
19
|
+
runAccountId: string;
|
|
20
|
+
runAgentId: string;
|
|
21
|
+
} | null): boolean;
|
|
22
|
+
export declare function depthExceeded(depth: number, max: number): boolean;
|
|
23
|
+
/** The most clauses an event automation's filter may have. */
|
|
24
|
+
export declare const FILTER_MAX_CLAUSES = 20;
|
|
25
|
+
/**
|
|
26
|
+
* Why `filter` cannot be saved for events of the declared types `decls` (the declarations of every
|
|
27
|
+
* type the automation selects); an empty list means it can. Each clause's fact must exist in every
|
|
28
|
+
* selected type, be `filterable`, and the operator and value must fit the fact's type: `eq` takes
|
|
29
|
+
* a scalar of the fact's type, `in` a string list on a string fact, `contains` a string on a
|
|
30
|
+
* string-list fact.
|
|
31
|
+
*/
|
|
32
|
+
export declare function validateFilter(filter: EventFilter, decls: TriggerEventDeclaration[]): string[];
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
/**
|
|
3
|
+
* A window whose first delivery waits this long past its coalescing window is taken as lost (its
|
|
4
|
+
* job failed for good): the next event of the pair opens a new window with a job of its own, and
|
|
5
|
+
* the trigger event sweep owes a job for a window no event comes to (`TriggerEventSweepJob`).
|
|
6
|
+
*/
|
|
7
|
+
export const COALESCE_STALE_MS = 10 * 60_000;
|
|
8
|
+
/** A stable, BullMQ-safe key for a trigger subject: `${kind}-${sha1(id).slice(0, 16)}`. */
|
|
9
|
+
export function subjectKey(s) {
|
|
10
|
+
const digest = createHash("sha1").update(s.id).digest("hex").slice(0, 16);
|
|
11
|
+
return `${s.kind.replaceAll(":", "-")}-${digest}`;
|
|
12
|
+
}
|
|
13
|
+
/** Deterministic job id for coalescing events of one subject into one automation run. */
|
|
14
|
+
export function coalesceJobId(automationId, s) {
|
|
15
|
+
return coalesceJobIdOfKey(automationId, subjectKey(s));
|
|
16
|
+
}
|
|
17
|
+
/** {@link coalesceJobId} from the subject's stored key ({@link subjectKey}). */
|
|
18
|
+
export function coalesceJobIdOfKey(automationId, key) {
|
|
19
|
+
return `automation-coalesce-${automationId.replaceAll(":", "-")}-${key}`;
|
|
20
|
+
}
|
|
21
|
+
/** True when the event was caused by a run of this same automation account and agent. */
|
|
22
|
+
export function isSelfTriggered(a, cause) {
|
|
23
|
+
return cause !== null && cause.runAccountId === a.accountId && cause.runAgentId === a.agentId;
|
|
24
|
+
}
|
|
25
|
+
export function depthExceeded(depth, max) {
|
|
26
|
+
return depth > max;
|
|
27
|
+
}
|
|
28
|
+
/** The most clauses an event automation's filter may have. */
|
|
29
|
+
export const FILTER_MAX_CLAUSES = 20;
|
|
30
|
+
const isScalarOf = (type, v) => type !== "string[]" && typeof v === type;
|
|
31
|
+
/**
|
|
32
|
+
* Why `filter` cannot be saved for events of the declared types `decls` (the declarations of every
|
|
33
|
+
* type the automation selects); an empty list means it can. Each clause's fact must exist in every
|
|
34
|
+
* selected type, be `filterable`, and the operator and value must fit the fact's type: `eq` takes
|
|
35
|
+
* a scalar of the fact's type, `in` a string list on a string fact, `contains` a string on a
|
|
36
|
+
* string-list fact.
|
|
37
|
+
*/
|
|
38
|
+
export function validateFilter(filter, decls) {
|
|
39
|
+
const errors = [];
|
|
40
|
+
if (filter.length > FILTER_MAX_CLAUSES) {
|
|
41
|
+
errors.push(`A filter has at most ${FILTER_MAX_CLAUSES} clauses`);
|
|
42
|
+
}
|
|
43
|
+
for (const c of filter) {
|
|
44
|
+
const facts = decls.map((d) => ({
|
|
45
|
+
type: d.type,
|
|
46
|
+
fact: Object.hasOwn(d.facts, c.fact) ? d.facts[c.fact] : undefined,
|
|
47
|
+
}));
|
|
48
|
+
const missing = facts.filter((f) => f.fact === undefined);
|
|
49
|
+
if (decls.length === 0 || missing.length > 0) {
|
|
50
|
+
const where = missing.map((m) => m.type).join(", ");
|
|
51
|
+
errors.push(`Fact "${c.fact}" is not declared by ${where === "" ? "the selected event types" : where}`);
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
const declared = facts.map((f) => f.fact);
|
|
55
|
+
if (declared.some((f) => !f.filterable)) {
|
|
56
|
+
errors.push(`Fact "${c.fact}" cannot be filtered on`);
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
const kinds = new Set(declared.map((f) => f.type));
|
|
60
|
+
if (kinds.size > 1) {
|
|
61
|
+
errors.push(`Fact "${c.fact}" has different types in the selected event types`);
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
const type = declared[0]?.type;
|
|
65
|
+
if (c.op === "eq") {
|
|
66
|
+
if (!isScalarOf(type, c.value)) {
|
|
67
|
+
errors.push(type === "string[]"
|
|
68
|
+
? `Fact "${c.fact}" is a list: use "contains" with a string`
|
|
69
|
+
: `Operator "eq" on fact "${c.fact}" needs a ${type} value`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
else if (c.op === "in") {
|
|
73
|
+
const ok = type === "string" && Array.isArray(c.value) && c.value.every((v) => typeof v === "string");
|
|
74
|
+
if (!ok)
|
|
75
|
+
errors.push(`Operator "in" on fact "${c.fact}" needs a list of strings on a string fact`);
|
|
76
|
+
}
|
|
77
|
+
else if (c.op === "contains") {
|
|
78
|
+
if (type !== "string[]" || typeof c.value !== "string") {
|
|
79
|
+
errors.push(`Operator "contains" on fact "${c.fact}" needs a string on a string-list fact`);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
else {
|
|
83
|
+
errors.push(`Operator "${String(c.op)}" is not supported`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return errors;
|
|
87
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { KernelConfigService } from "../../infra/config/kernel-config.service.js";
|
|
2
|
+
import { KernelDb } from "../../infra/database/kernel-db.js";
|
|
3
|
+
import { TransactionHost } from "../../infra/database/transaction-host.js";
|
|
4
|
+
import { LockService } from "../../infra/lock/lock.service.js";
|
|
5
|
+
import { OutboxService } from "../../infra/outbox/outbox.service.js";
|
|
6
|
+
import type { KernelLogger } from "../../log.js";
|
|
7
|
+
/**
|
|
8
|
+
* The trigger event sweep (collaboration spec §4.7), every five minutes across replicas:
|
|
9
|
+
*
|
|
10
|
+
* - **Retention.** A trigger event settled (`dispatched`, `undelivered`, `depth_stopped`) more than
|
|
11
|
+
* `automations.eventRetentionDays` ago, none of whose deliveries still waits for a run, is
|
|
12
|
+
* deleted with its deliveries (the foreign key cascades), in batches of {@link DELETE_BATCH}, one
|
|
13
|
+
* transaction each. A `pending` event (a directed one waiting for acceptance routing) stays. A
|
|
14
|
+
* run keeps its `trigger_key` and a kernel run its `trigger_event_id` (neither has a foreign
|
|
15
|
+
* key); a chain whose event is gone restarts at depth 0.
|
|
16
|
+
* - **Lost windows.** The dispatcher owes one coalesce job per window, from the delivery that opens
|
|
17
|
+
* it. A window whose first delivery has waited longer than the org's `coalesceSeconds` plus
|
|
18
|
+
* {@link COALESCE_STALE_MS} lost its job for good (dead in the outbox, or failed in the queue);
|
|
19
|
+
* unless an outbox row for it is still pending, the sweep owes a coalesce job of its own
|
|
20
|
+
* (`<window job id>-sweep-<minute>`, due now). The flush is idempotent, so a duplicate finds
|
|
21
|
+
* nothing waiting.
|
|
22
|
+
*/
|
|
23
|
+
export declare class TriggerEventSweepJob {
|
|
24
|
+
private readonly kdb;
|
|
25
|
+
readonly txHost: TransactionHost;
|
|
26
|
+
private readonly config;
|
|
27
|
+
private readonly outbox;
|
|
28
|
+
readonly lockService: LockService;
|
|
29
|
+
readonly log: KernelLogger;
|
|
30
|
+
constructor(kdb: KernelDb, txHost: TransactionHost, config: Pick<KernelConfigService, "get">, outbox: Pick<OutboxService, "add">, lockService: LockService, log: KernelLogger);
|
|
31
|
+
sweep(): Promise<void>;
|
|
32
|
+
/** One sweep as of `now` (tests pass their own): how many events it deleted and windows it owed. */
|
|
33
|
+
sweepAt(now: Date): Promise<{
|
|
34
|
+
deleted: number;
|
|
35
|
+
owed: number;
|
|
36
|
+
}>;
|
|
37
|
+
/** Deletes one batch of settled events older than `cutoff` (see the class); returns how many. */
|
|
38
|
+
private deleteBatch;
|
|
39
|
+
/**
|
|
40
|
+
* The windows whose first waiting delivery is older than their org's `coalesceSeconds` plus
|
|
41
|
+
* {@link COALESCE_STALE_MS} (see the class), oldest first.
|
|
42
|
+
*/
|
|
43
|
+
private waitingWindows;
|
|
44
|
+
/**
|
|
45
|
+
* Owes the window's coalesce job unless an outbox row for it (the dispatcher's or an earlier
|
|
46
|
+
* sweep's) is still pending; true when it owed one.
|
|
47
|
+
*/
|
|
48
|
+
private oweFlush;
|
|
49
|
+
}
|