@capybara-hq/kernel 0.1.0-rc.107 → 0.1.0-rc.109
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 +13 -13
- package/dist/automations/acceptance.controller.d.ts +29 -0
- package/dist/automations/acceptance.controller.js +87 -0
- package/dist/automations/automations.module.js +4 -1
- package/dist/automations/automations.schemas.d.ts +46 -0
- package/dist/automations/automations.schemas.js +31 -0
- package/dist/automations/automations.service.js +10 -1
- package/dist/automations/errors.d.ts +5 -0
- package/dist/automations/errors.js +5 -0
- package/dist/automations/events/acceptance.d.ts +205 -0
- package/dist/automations/events/acceptance.js +822 -0
- package/dist/automations/events/deliver.d.ts +39 -0
- package/dist/automations/events/deliver.js +112 -0
- package/dist/automations/events/dispatcher.d.ts +26 -10
- package/dist/automations/events/dispatcher.js +98 -99
- package/dist/automations/events/sweep.job.d.ts +104 -18
- package/dist/automations/events/sweep.job.js +311 -45
- package/dist/automations/events/trigger-events.service.d.ts +31 -2
- package/dist/automations/events/trigger-events.service.js +113 -30
- package/dist/automations/store.d.ts +7 -3
- package/dist/automations/store.js +6 -0
- package/dist/automations/types.d.ts +5 -0
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/config/schema.d.ts +3 -0
- package/dist/config/schema.js +14 -0
- package/dist/ctx/create-ctx.d.ts +24 -4
- package/dist/ctx/create-ctx.js +119 -6
- package/dist/db/kernel-schema.d.ts +89 -1
- package/dist/errors.d.ts +18 -0
- package/dist/errors.js +18 -0
- package/dist/extensions/hooks.d.ts +8 -5
- package/dist/extensions/hooks.js +2 -1
- package/dist/extensions/host.d.ts +12 -2
- package/dist/extensions/host.js +21 -1
- package/dist/extensions/lifecycle-hooks.d.ts +21 -7
- package/dist/extensions/lifecycle-hooks.js +51 -3
- package/dist/extensions/permission-set.d.ts +33 -1
- package/dist/extensions/permission-set.js +28 -1
- package/dist/extensions/permission-view.d.ts +1 -1
- package/dist/extensions/permission-view.js +24 -1
- package/dist/extensions/run-lifecycle-owe.d.ts +67 -0
- package/dist/extensions/run-lifecycle-owe.js +84 -0
- package/dist/http/api.module.js +4 -0
- package/dist/inbox/inbox-item-actions.d.ts +37 -0
- package/dist/inbox/inbox-item-actions.js +69 -0
- package/dist/inbox/inbox-items.controller.d.ts +27 -0
- package/dist/inbox/inbox-items.controller.js +80 -0
- package/dist/inbox/inbox-items.service.d.ts +110 -0
- package/dist/inbox/inbox-items.service.js +324 -0
- package/dist/inbox/inbox.module.d.ts +2 -1
- package/dist/inbox/inbox.module.js +15 -4
- package/dist/inbox/inbox.schemas.d.ts +20 -1
- package/dist/inbox/inbox.schemas.js +16 -1
- package/dist/inbox/inbox.service.d.ts +29 -7
- package/dist/inbox/inbox.service.js +29 -8
- package/dist/inbox/token.d.ts +5 -0
- package/dist/inbox/token.js +5 -0
- package/dist/infra/config/kernel-config.service.js +2 -0
- package/dist/infra/outbox/registry.d.ts +17 -0
- package/dist/infra/outbox/registry.js +15 -0
- package/dist/kernel.module.js +6 -0
- package/dist/orgs/settings.service.d.ts +20 -0
- package/dist/orgs/settings.service.js +4 -0
- package/dist/platform/exclusions.js +15 -0
- package/dist/platform/operation.d.ts +8 -0
- package/dist/platform/ops/automations.ops.d.ts +3 -1
- package/dist/platform/ops/automations.ops.js +45 -3
- package/dist/platform/ops/inbox.ops.d.ts +3 -1
- package/dist/platform/ops/inbox.ops.js +69 -4
- package/dist/platform/ops/platform.ops.js +4 -3
- package/dist/plugin-reads/plugin-reads.service.d.ts +29 -0
- package/dist/plugin-reads/plugin-reads.service.js +210 -0
- package/dist/plugin-reads/token.d.ts +5 -0
- package/dist/plugin-reads/token.js +5 -0
- package/dist/push/jobs.d.ts +5 -0
- package/dist/push/jobs.js +2 -0
- package/dist/push/preferences.service.d.ts +2 -2
- package/dist/push/preferences.service.js +9 -3
- package/dist/push/push-owed.d.ts +2 -0
- package/dist/push/push-owed.js +10 -1
- package/dist/push/push.schemas.d.ts +5 -2
- package/dist/push/push.schemas.js +4 -3
- package/dist/push/recipients.d.ts +2 -0
- package/dist/push/recipients.js +44 -3
- package/dist/push/texts.d.ts +14 -5
- package/dist/push/texts.js +2 -1
- package/dist/push/triggers.d.ts +1 -1
- package/dist/runtime/run-finish.js +19 -1
- package/dist/runtime/run-jobs.d.ts +12 -2
- package/dist/runtime/run-jobs.js +41 -4
- package/dist/runtime/run-queue.js +10 -0
- package/dist/runtime/waits.js +24 -1
- package/dist/tools/builtins/platform.js +2 -0
- package/dist/tools/pipeline.d.ts +5 -0
- package/dist/tools/pipeline.js +13 -1
- package/dist/tools/registry.d.ts +6 -0
- package/package.json +3 -3
- package/src/migrations/0192_inbox_items.sql +50 -0
- package/src/migrations/0193_trigger_cause_handles.sql +49 -0
- package/src/migrations/0194_automation_acceptance.sql +83 -0
|
@@ -4,21 +4,65 @@ import { TransactionHost } from "../../infra/database/transaction-host.js";
|
|
|
4
4
|
import { LockService } from "../../infra/lock/lock.service.js";
|
|
5
5
|
import { OutboxService } from "../../infra/outbox/outbox.service.js";
|
|
6
6
|
import type { KernelLogger } from "../../log.js";
|
|
7
|
+
import { AcceptanceService } from "./acceptance.js";
|
|
8
|
+
/**
|
|
9
|
+
* A lost pair whose newest waiting delivery is older than this is no longer owed a job (the sweep
|
|
10
|
+
* logs it once and stops).
|
|
11
|
+
*/
|
|
12
|
+
export declare const WINDOW_GIVE_UP_MS = 86400000;
|
|
13
|
+
/**
|
|
14
|
+
* A directed event still `pending` this long after it was stored was passed over by a dispatch
|
|
15
|
+
* job (a worker from before acceptance routing, during a rolling deploy): the sweep owes it a
|
|
16
|
+
* dispatch job again.
|
|
17
|
+
*/
|
|
18
|
+
export declare const PENDING_DIRECTED_STALE_MS: number;
|
|
19
|
+
/**
|
|
20
|
+
* What the sweep does at `nowMs` for a lost pair whose newest waiting delivery is `ageMs` old:
|
|
21
|
+
* `owe` its job (every sweep for the first hour, then at sweeps on boundaries of a period that
|
|
22
|
+
* doubles with each doubling of the age: 10 minutes from 1 hour, 20 from 2, ..., 160 from 16),
|
|
23
|
+
* `wait`, or, past {@link WINDOW_GIVE_UP_MS}, `give_up` (`log` at the first sweep past it).
|
|
24
|
+
*/
|
|
25
|
+
export declare function reoweDecision(ageMs: number, nowMs: number): "owe" | "wait" | {
|
|
26
|
+
give_up: {
|
|
27
|
+
log: boolean;
|
|
28
|
+
};
|
|
29
|
+
};
|
|
7
30
|
/**
|
|
8
31
|
* The trigger event sweep (collaboration spec §4.7), every five minutes across replicas:
|
|
9
32
|
*
|
|
33
|
+
* - **Offers.** A work offer still `open` seven days ({@link OFFER_TTL_SECONDS}) after it was made
|
|
34
|
+
* is marked `expired` ({@link AcceptanceService.expireOffer}: its inbox item resolved, the
|
|
35
|
+
* source told `run.lifecycle` `offer_declined` with reason `expired`), one transaction each,
|
|
36
|
+
* before retention runs: an offer counts as open only while it is `open` and younger than that.
|
|
10
37
|
* - **Retention.** A trigger event settled (`dispatched`, `undelivered`, `depth_stopped`) more than
|
|
11
|
-
* `automations.eventRetentionDays` ago, none of whose deliveries still waits for a run
|
|
12
|
-
* deleted with its deliveries (the foreign key cascades), in batches of
|
|
13
|
-
* transaction each. A `pending` event (
|
|
14
|
-
*
|
|
15
|
-
* key); a chain whose event is gone
|
|
38
|
+
* `automations.eventRetentionDays` ago, none of whose deliveries still waits for a run and with
|
|
39
|
+
* no open work offer, is deleted with its deliveries (the foreign key cascades), in batches of
|
|
40
|
+
* {@link DELETE_BATCH}, one transaction each. A `pending` event (its dispatch has not settled
|
|
41
|
+
* it) stays, until the pending-directed rule below ends it. A run keeps its `trigger_key` and a
|
|
42
|
+
* kernel run its `trigger_event_id` (neither has a foreign key); a chain whose event is gone
|
|
43
|
+
* restarts at depth 0.
|
|
16
44
|
* - **Lost windows.** The dispatcher owes one coalesce job per window, from the delivery that opens
|
|
17
|
-
* it
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
45
|
+
* it (`<coalesceJobIdOfKey>-<eventId>`, due `coalesceSeconds` on). A pair whose newest waiting
|
|
46
|
+
* delivery has waited longer than the org's `coalesceSeconds` plus {@link COALESCE_STALE_MS}
|
|
47
|
+
* lost its job for good (dead in the outbox, or failed in the queue): every window the
|
|
48
|
+
* dispatcher opened, the newest included, was due by then. Unless an outbox row of the pair is
|
|
49
|
+
* still pending (the dispatcher's, any `<coalesceJobIdOfKey>-*`, or an earlier sweep's), the
|
|
50
|
+
* sweep owes a coalesce job of its own (`<coalesceJobIdOfKey>-<first event id>-sweep-<minute>`,
|
|
51
|
+
* due now), backing off by the age of the pair's newest waiting delivery ({@link reoweDecision})
|
|
52
|
+
* and giving up, with one warning, once that delivery is older than {@link WINDOW_GIVE_UP_MS}.
|
|
53
|
+
* The age is the newest window's, never the oldest's: an old window given up on does not stop a
|
|
54
|
+
* newer window of the pair that lost its job from being owed one (its flush takes both). The
|
|
55
|
+
* flush is idempotent, so a duplicate finds nothing waiting.
|
|
56
|
+
* - **Pending directed events.** A directed event still `pending` more than
|
|
57
|
+
* {@link PENDING_DIRECTED_STALE_MS} after it was stored (a dispatch job of a worker from before
|
|
58
|
+
* acceptance routing passed it over) is owed its dispatch job again
|
|
59
|
+
* (`trigger-dispatch-<eventId>-sweep-<minute>`) unless one is pending in the outbox, backing off
|
|
60
|
+
* by its age as a lost window does and giving up after {@link WINDOW_GIVE_UP_MS}: past it the
|
|
61
|
+
* event is marked `undelivered` with a warning, so retention can delete it, and its source is
|
|
62
|
+
* told `run.lifecycle` `offer_declined` with reason `undelivered` in the same transaction.
|
|
63
|
+
* - **Cause handles.** Expired `trigger_cause_handles` (`ctx.triggers.causeOf`) are deleted.
|
|
64
|
+
* - **Inbox items.** An inbox item resolved, or past its expiry, more than `inbox.retentionDays`
|
|
65
|
+
* ago is deleted (an open item past its expiry already left the inbox).
|
|
22
66
|
*/
|
|
23
67
|
export declare class TriggerEventSweepJob {
|
|
24
68
|
private readonly kdb;
|
|
@@ -27,23 +71,65 @@ export declare class TriggerEventSweepJob {
|
|
|
27
71
|
private readonly outbox;
|
|
28
72
|
readonly lockService: LockService;
|
|
29
73
|
readonly log: KernelLogger;
|
|
30
|
-
|
|
74
|
+
private readonly acceptance;
|
|
75
|
+
constructor(kdb: KernelDb, txHost: TransactionHost, config: Pick<KernelConfigService, "get">, outbox: Pick<OutboxService, "add">, lockService: LockService, log: KernelLogger, acceptance: Pick<AcceptanceService, "expireOffer">);
|
|
31
76
|
sweep(): Promise<void>;
|
|
32
|
-
/**
|
|
77
|
+
/**
|
|
78
|
+
* One sweep as of `now` (tests pass their own): how many offers it expired, events it deleted,
|
|
79
|
+
* windows it owed, cause handles and inbox items it deleted, and stale pending directed events
|
|
80
|
+
* it owed a dispatch again.
|
|
81
|
+
*/
|
|
33
82
|
sweepAt(now: Date): Promise<{
|
|
83
|
+
expiredOffers: number;
|
|
34
84
|
deleted: number;
|
|
35
85
|
owed: number;
|
|
86
|
+
handles: number;
|
|
87
|
+
inboxItems: number;
|
|
88
|
+
redispatched: number;
|
|
36
89
|
}>;
|
|
37
|
-
/**
|
|
38
|
-
private
|
|
90
|
+
/** Runs `batch` (one transaction each) until it deletes fewer than a full batch; the total. */
|
|
91
|
+
private inBatches;
|
|
92
|
+
/** Deletes expired cause handles, at most `limit`; returns how many. */
|
|
93
|
+
private deleteHandles;
|
|
94
|
+
/** Deletes inbox items resolved or expired before `cutoff`, at most `limit`; returns how many. */
|
|
95
|
+
private deleteInboxItems;
|
|
96
|
+
/**
|
|
97
|
+
* Open work offers made at or before `cutoff` (seven days before the sweep's `now`), oldest
|
|
98
|
+
* first, at most {@link MAX_STALE_OFFERS}.
|
|
99
|
+
*/
|
|
100
|
+
private staleOffers;
|
|
101
|
+
/**
|
|
102
|
+
* Deletes settled events older than `cutoff` (see the class), at most `limit`; how many. An
|
|
103
|
+
* offer made at or before `offerCutoff` no longer counts as open, whatever its state says.
|
|
104
|
+
*/
|
|
105
|
+
private deleteEvents;
|
|
39
106
|
/**
|
|
40
|
-
* The
|
|
41
|
-
* {@link COALESCE_STALE_MS} (see the class), oldest first
|
|
107
|
+
* The pairs whose newest waiting delivery is older than their org's `coalesceSeconds` plus
|
|
108
|
+
* {@link COALESCE_STALE_MS} (see the class), oldest first window first; a pair whose newest
|
|
109
|
+
* waiting delivery is past {@link WINDOW_GIVE_UP_MS} by more than one sweep is left out (given up
|
|
110
|
+
* on before).
|
|
42
111
|
*/
|
|
43
112
|
private waitingWindows;
|
|
44
113
|
/**
|
|
45
|
-
*
|
|
46
|
-
*
|
|
114
|
+
* Directed events still `pending` more than {@link PENDING_DIRECTED_STALE_MS} after they were
|
|
115
|
+
* stored, oldest first, at most {@link MAX_PENDING_DIRECTED}; no upper bound on age: one past
|
|
116
|
+
* {@link WINDOW_GIVE_UP_MS} is marked `undelivered` by the sweep and so leaves this list.
|
|
117
|
+
*/
|
|
118
|
+
private stalePendingDirected;
|
|
119
|
+
/**
|
|
120
|
+
* Marks a directed event that is still pending `undelivered` and tells its source
|
|
121
|
+
* (`run.lifecycle` `offer_declined`, reason `undelivered`) in the same transaction; true when it
|
|
122
|
+
* was pending.
|
|
123
|
+
*/
|
|
124
|
+
private giveUpPending;
|
|
125
|
+
/**
|
|
126
|
+
* Owes the event's dispatch job again unless a dispatch row of it is still pending in the
|
|
127
|
+
* outbox; true when it owed one.
|
|
128
|
+
*/
|
|
129
|
+
private oweDispatch;
|
|
130
|
+
/**
|
|
131
|
+
* Owes the window's coalesce job unless an outbox row of the pair (the dispatcher's for any of
|
|
132
|
+
* its windows, or an earlier sweep's) is still pending; true when it owed one.
|
|
47
133
|
*/
|
|
48
134
|
private oweFlush;
|
|
49
135
|
}
|
|
@@ -9,6 +9,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
|
9
9
|
};
|
|
10
10
|
import { Inject, Injectable } from "@nestjs/common";
|
|
11
11
|
import { sql } from "kysely";
|
|
12
|
+
import { oweOfferDeclinedIn } from "../../extensions/run-lifecycle-owe.js";
|
|
12
13
|
import { KernelConfigService } from "../../infra/config/kernel-config.service.js";
|
|
13
14
|
import { KernelDb } from "../../infra/database/kernel-db.js";
|
|
14
15
|
import { asPlatform, withOrgScope } from "../../infra/database/org-scope.js";
|
|
@@ -20,30 +21,86 @@ import { LockedCron } from "../../infra/schedule/locked-cron.decorator.js";
|
|
|
20
21
|
import { KERNEL_LOGGER } from "../../infra/tokens.js";
|
|
21
22
|
import { MAINTENANCE_QUEUE_NAME } from "../../runtime/maintenance-queue.js";
|
|
22
23
|
import { readAutomationSettings } from "../effective-settings.js";
|
|
23
|
-
import { AUTOMATION_COALESCE_JOB, TRIGGER_EVENT_SWEEP_JOB, } from "../job-ids.js";
|
|
24
|
+
import { AUTOMATION_COALESCE_JOB, TRIGGER_DISPATCH_JOB, TRIGGER_EVENT_SWEEP_JOB, triggerDispatchJobId, } from "../job-ids.js";
|
|
25
|
+
import { AcceptanceService, OFFER_TTL_SECONDS } from "./acceptance.js";
|
|
24
26
|
import { COALESCE_STALE_MS, coalesceJobIdOfKey } from "./guards.js";
|
|
25
27
|
const DAY_MS = 86_400_000;
|
|
28
|
+
const HOUR_MS = 3_600_000;
|
|
29
|
+
/** The sweep's period (its cron). */
|
|
30
|
+
const SWEEP_EVERY_MS = 5 * 60_000;
|
|
31
|
+
/**
|
|
32
|
+
* A lost pair whose newest waiting delivery is older than this is no longer owed a job (the sweep
|
|
33
|
+
* logs it once and stops).
|
|
34
|
+
*/
|
|
35
|
+
export const WINDOW_GIVE_UP_MS = DAY_MS;
|
|
26
36
|
/** Events deleted per transaction. */
|
|
27
37
|
const DELETE_BATCH = 500;
|
|
28
38
|
/** Batches per sweep; what is left waits for the next one. */
|
|
29
39
|
const MAX_BATCHES = 40;
|
|
30
40
|
/** Waiting windows looked at per sweep. */
|
|
31
41
|
const MAX_WINDOWS = 1000;
|
|
42
|
+
/**
|
|
43
|
+
* A directed event still `pending` this long after it was stored was passed over by a dispatch
|
|
44
|
+
* job (a worker from before acceptance routing, during a rolling deploy): the sweep owes it a
|
|
45
|
+
* dispatch job again.
|
|
46
|
+
*/
|
|
47
|
+
export const PENDING_DIRECTED_STALE_MS = 10 * 60_000;
|
|
48
|
+
/** Stale pending directed events looked at per sweep. */
|
|
49
|
+
const MAX_PENDING_DIRECTED = 1000;
|
|
50
|
+
/** Stale open work offers expired per sweep; what is left waits for the next one. */
|
|
51
|
+
const MAX_STALE_OFFERS = 1000;
|
|
52
|
+
/**
|
|
53
|
+
* What the sweep does at `nowMs` for a lost pair whose newest waiting delivery is `ageMs` old:
|
|
54
|
+
* `owe` its job (every sweep for the first hour, then at sweeps on boundaries of a period that
|
|
55
|
+
* doubles with each doubling of the age: 10 minutes from 1 hour, 20 from 2, ..., 160 from 16),
|
|
56
|
+
* `wait`, or, past {@link WINDOW_GIVE_UP_MS}, `give_up` (`log` at the first sweep past it).
|
|
57
|
+
*/
|
|
58
|
+
export function reoweDecision(ageMs, nowMs) {
|
|
59
|
+
if (ageMs > WINDOW_GIVE_UP_MS)
|
|
60
|
+
return { give_up: { log: ageMs - SWEEP_EVERY_MS <= WINDOW_GIVE_UP_MS } };
|
|
61
|
+
if (ageMs < HOUR_MS)
|
|
62
|
+
return "owe";
|
|
63
|
+
const period = SWEEP_EVERY_MS * 2 ** (Math.floor(Math.log2(ageMs / HOUR_MS)) + 1);
|
|
64
|
+
return Math.floor(nowMs / period) !== Math.floor((nowMs - SWEEP_EVERY_MS) / period)
|
|
65
|
+
? "owe"
|
|
66
|
+
: "wait";
|
|
67
|
+
}
|
|
32
68
|
/**
|
|
33
69
|
* The trigger event sweep (collaboration spec §4.7), every five minutes across replicas:
|
|
34
70
|
*
|
|
71
|
+
* - **Offers.** A work offer still `open` seven days ({@link OFFER_TTL_SECONDS}) after it was made
|
|
72
|
+
* is marked `expired` ({@link AcceptanceService.expireOffer}: its inbox item resolved, the
|
|
73
|
+
* source told `run.lifecycle` `offer_declined` with reason `expired`), one transaction each,
|
|
74
|
+
* before retention runs: an offer counts as open only while it is `open` and younger than that.
|
|
35
75
|
* - **Retention.** A trigger event settled (`dispatched`, `undelivered`, `depth_stopped`) more than
|
|
36
|
-
* `automations.eventRetentionDays` ago, none of whose deliveries still waits for a run
|
|
37
|
-
* deleted with its deliveries (the foreign key cascades), in batches of
|
|
38
|
-
* transaction each. A `pending` event (
|
|
39
|
-
*
|
|
40
|
-
* key); a chain whose event is gone
|
|
76
|
+
* `automations.eventRetentionDays` ago, none of whose deliveries still waits for a run and with
|
|
77
|
+
* no open work offer, is deleted with its deliveries (the foreign key cascades), in batches of
|
|
78
|
+
* {@link DELETE_BATCH}, one transaction each. A `pending` event (its dispatch has not settled
|
|
79
|
+
* it) stays, until the pending-directed rule below ends it. A run keeps its `trigger_key` and a
|
|
80
|
+
* kernel run its `trigger_event_id` (neither has a foreign key); a chain whose event is gone
|
|
81
|
+
* restarts at depth 0.
|
|
41
82
|
* - **Lost windows.** The dispatcher owes one coalesce job per window, from the delivery that opens
|
|
42
|
-
* it
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
*
|
|
46
|
-
*
|
|
83
|
+
* it (`<coalesceJobIdOfKey>-<eventId>`, due `coalesceSeconds` on). A pair whose newest waiting
|
|
84
|
+
* delivery has waited longer than the org's `coalesceSeconds` plus {@link COALESCE_STALE_MS}
|
|
85
|
+
* lost its job for good (dead in the outbox, or failed in the queue): every window the
|
|
86
|
+
* dispatcher opened, the newest included, was due by then. Unless an outbox row of the pair is
|
|
87
|
+
* still pending (the dispatcher's, any `<coalesceJobIdOfKey>-*`, or an earlier sweep's), the
|
|
88
|
+
* sweep owes a coalesce job of its own (`<coalesceJobIdOfKey>-<first event id>-sweep-<minute>`,
|
|
89
|
+
* due now), backing off by the age of the pair's newest waiting delivery ({@link reoweDecision})
|
|
90
|
+
* and giving up, with one warning, once that delivery is older than {@link WINDOW_GIVE_UP_MS}.
|
|
91
|
+
* The age is the newest window's, never the oldest's: an old window given up on does not stop a
|
|
92
|
+
* newer window of the pair that lost its job from being owed one (its flush takes both). The
|
|
93
|
+
* flush is idempotent, so a duplicate finds nothing waiting.
|
|
94
|
+
* - **Pending directed events.** A directed event still `pending` more than
|
|
95
|
+
* {@link PENDING_DIRECTED_STALE_MS} after it was stored (a dispatch job of a worker from before
|
|
96
|
+
* acceptance routing passed it over) is owed its dispatch job again
|
|
97
|
+
* (`trigger-dispatch-<eventId>-sweep-<minute>`) unless one is pending in the outbox, backing off
|
|
98
|
+
* by its age as a lost window does and giving up after {@link WINDOW_GIVE_UP_MS}: past it the
|
|
99
|
+
* event is marked `undelivered` with a warning, so retention can delete it, and its source is
|
|
100
|
+
* told `run.lifecycle` `offer_declined` with reason `undelivered` in the same transaction.
|
|
101
|
+
* - **Cause handles.** Expired `trigger_cause_handles` (`ctx.triggers.causeOf`) are deleted.
|
|
102
|
+
* - **Inbox items.** An inbox item resolved, or past its expiry, more than `inbox.retentionDays`
|
|
103
|
+
* ago is deleted (an open item past its expiry already left the inbox).
|
|
47
104
|
*/
|
|
48
105
|
let TriggerEventSweepJob = class TriggerEventSweepJob {
|
|
49
106
|
kdb;
|
|
@@ -52,39 +109,143 @@ let TriggerEventSweepJob = class TriggerEventSweepJob {
|
|
|
52
109
|
outbox;
|
|
53
110
|
lockService;
|
|
54
111
|
log;
|
|
55
|
-
|
|
112
|
+
acceptance;
|
|
113
|
+
constructor(kdb, txHost, config, outbox, lockService, log, acceptance) {
|
|
56
114
|
this.kdb = kdb;
|
|
57
115
|
this.txHost = txHost;
|
|
58
116
|
this.config = config;
|
|
59
117
|
this.outbox = outbox;
|
|
60
118
|
this.lockService = lockService;
|
|
61
119
|
this.log = log;
|
|
120
|
+
this.acceptance = acceptance;
|
|
62
121
|
}
|
|
63
122
|
async sweep() {
|
|
64
123
|
await this.sweepAt(new Date());
|
|
65
124
|
}
|
|
66
|
-
/**
|
|
125
|
+
/**
|
|
126
|
+
* One sweep as of `now` (tests pass their own): how many offers it expired, events it deleted,
|
|
127
|
+
* windows it owed, cause handles and inbox items it deleted, and stale pending directed events
|
|
128
|
+
* it owed a dispatch again.
|
|
129
|
+
*/
|
|
67
130
|
async sweepAt(now) {
|
|
68
|
-
const
|
|
69
|
-
const cutoff = new Date(now.getTime() -
|
|
70
|
-
let
|
|
71
|
-
for (
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
if (n < DELETE_BATCH)
|
|
75
|
-
break;
|
|
131
|
+
const cfg = this.config.get();
|
|
132
|
+
const cutoff = new Date(now.getTime() - OFFER_TTL_SECONDS * 1000);
|
|
133
|
+
let expiredOffers = 0;
|
|
134
|
+
for (const o of await this.staleOffers(cutoff)) {
|
|
135
|
+
if (await withOrgScope(o.orgId, () => this.acceptance.expireOffer(o.orgId, o.id, cutoff)))
|
|
136
|
+
expiredOffers++;
|
|
76
137
|
}
|
|
138
|
+
if (expiredOffers > 0)
|
|
139
|
+
this.log.info("open work offers expired", { expired: expiredOffers });
|
|
140
|
+
const days = cfg.automations.eventRetentionDays;
|
|
141
|
+
const deleted = await this.inBatches((b) => this.deleteEvents(new Date(now.getTime() - days * DAY_MS), cutoff, b));
|
|
77
142
|
if (deleted > 0)
|
|
78
143
|
this.log.info("old trigger events deleted", { deleted, retentionDays: days });
|
|
79
144
|
let owed = 0;
|
|
80
145
|
for (const w of await this.waitingWindows(now)) {
|
|
146
|
+
const age = now.getTime() - w.last.getTime();
|
|
147
|
+
const decision = reoweDecision(age, now.getTime());
|
|
148
|
+
if (decision === "wait")
|
|
149
|
+
continue;
|
|
150
|
+
if (decision !== "owe") {
|
|
151
|
+
if (decision.give_up.log)
|
|
152
|
+
this.log.warn("coalescing window lost its job for a day; the sweep stops owing one", {
|
|
153
|
+
orgId: w.orgId,
|
|
154
|
+
automationId: w.automationId,
|
|
155
|
+
subjectKey: w.subjectKey,
|
|
156
|
+
waitingSince: w.first.toISOString(),
|
|
157
|
+
newestSince: w.last.toISOString(),
|
|
158
|
+
});
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
81
161
|
if (await withOrgScope(w.orgId, () => this.oweFlush(w, now)))
|
|
82
162
|
owed++;
|
|
83
163
|
}
|
|
84
|
-
|
|
164
|
+
const handles = await this.inBatches((b) => this.deleteHandles(now, b));
|
|
165
|
+
const inboxDays = cfg.inbox.retentionDays;
|
|
166
|
+
const inboxItems = await this.inBatches((b) => this.deleteInboxItems(new Date(now.getTime() - inboxDays * DAY_MS), b));
|
|
167
|
+
if (inboxItems > 0)
|
|
168
|
+
this.log.info("old inbox items deleted", { deleted: inboxItems, retentionDays: inboxDays });
|
|
169
|
+
let redispatched = 0;
|
|
170
|
+
for (const e of await this.stalePendingDirected(now)) {
|
|
171
|
+
const decision = reoweDecision(now.getTime() - e.createdAt.getTime(), now.getTime());
|
|
172
|
+
if (typeof decision === "object") {
|
|
173
|
+
// a day of re-owed dispatches never settled it: end it, so retention can delete it
|
|
174
|
+
if (await withOrgScope(e.orgId, () => this.giveUpPending(e.orgId, e.id)))
|
|
175
|
+
this.log.warn("directed trigger event stayed pending for a day; marked undelivered", {
|
|
176
|
+
orgId: e.orgId,
|
|
177
|
+
eventId: e.id,
|
|
178
|
+
pendingSince: e.createdAt.toISOString(),
|
|
179
|
+
});
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
if (decision !== "owe")
|
|
183
|
+
continue;
|
|
184
|
+
if (await withOrgScope(e.orgId, () => this.oweDispatch(e.orgId, e.id, now)))
|
|
185
|
+
redispatched++;
|
|
186
|
+
}
|
|
187
|
+
return { expiredOffers, deleted, owed, handles, inboxItems, redispatched };
|
|
188
|
+
}
|
|
189
|
+
/** Runs `batch` (one transaction each) until it deletes fewer than a full batch; the total. */
|
|
190
|
+
async inBatches(batch) {
|
|
191
|
+
let total = 0;
|
|
192
|
+
for (let i = 0; i < MAX_BATCHES; i++) {
|
|
193
|
+
const n = await batch(DELETE_BATCH);
|
|
194
|
+
total += n;
|
|
195
|
+
if (n < DELETE_BATCH)
|
|
196
|
+
break;
|
|
197
|
+
}
|
|
198
|
+
return total;
|
|
199
|
+
}
|
|
200
|
+
/** Deletes expired cause handles, at most `limit`; returns how many. */
|
|
201
|
+
async deleteHandles(now, limit) {
|
|
202
|
+
const db = this.kdb.db;
|
|
203
|
+
return asPlatform("deployment-wide expired trigger cause handle sweep", async () => {
|
|
204
|
+
const r = await sql `
|
|
205
|
+
DELETE FROM capybara.trigger_cause_handles
|
|
206
|
+
WHERE id IN (
|
|
207
|
+
SELECT id FROM capybara.trigger_cause_handles
|
|
208
|
+
WHERE expires_at <= ${now}
|
|
209
|
+
LIMIT ${limit}
|
|
210
|
+
FOR UPDATE SKIP LOCKED
|
|
211
|
+
)
|
|
212
|
+
RETURNING id`.execute(db);
|
|
213
|
+
return r.rows.length;
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
/** Deletes inbox items resolved or expired before `cutoff`, at most `limit`; returns how many. */
|
|
217
|
+
async deleteInboxItems(cutoff, limit) {
|
|
218
|
+
const db = this.kdb.db;
|
|
219
|
+
return asPlatform("deployment-wide inbox item retention sweep", async () => {
|
|
220
|
+
const r = await sql `
|
|
221
|
+
DELETE FROM capybara.inbox_items
|
|
222
|
+
WHERE id IN (
|
|
223
|
+
SELECT id FROM capybara.inbox_items
|
|
224
|
+
WHERE resolved_at < ${cutoff} OR expires_at < ${cutoff}
|
|
225
|
+
LIMIT ${limit}
|
|
226
|
+
FOR UPDATE SKIP LOCKED
|
|
227
|
+
)
|
|
228
|
+
RETURNING id`.execute(db);
|
|
229
|
+
return r.rows.length;
|
|
230
|
+
});
|
|
85
231
|
}
|
|
86
|
-
/**
|
|
87
|
-
|
|
232
|
+
/**
|
|
233
|
+
* Open work offers made at or before `cutoff` (seven days before the sweep's `now`), oldest
|
|
234
|
+
* first, at most {@link MAX_STALE_OFFERS}.
|
|
235
|
+
*/
|
|
236
|
+
async staleOffers(cutoff) {
|
|
237
|
+
const rows = await asPlatform("deployment-wide stale work offer sweep", () => sql `
|
|
238
|
+
SELECT org_id, id FROM capybara.automation_offers
|
|
239
|
+
WHERE state = 'open' AND created_at <= ${cutoff}
|
|
240
|
+
ORDER BY created_at
|
|
241
|
+
LIMIT ${MAX_STALE_OFFERS}`.execute(this.kdb.db));
|
|
242
|
+
return rows.rows.map((r) => ({ orgId: r.org_id, id: r.id }));
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Deletes settled events older than `cutoff` (see the class), at most `limit`; how many. An
|
|
246
|
+
* offer made at or before `offerCutoff` no longer counts as open, whatever its state says.
|
|
247
|
+
*/
|
|
248
|
+
async deleteEvents(cutoff, offerCutoff, limit) {
|
|
88
249
|
const db = this.kdb.db;
|
|
89
250
|
return asPlatform("deployment-wide trigger event retention sweep", async () => {
|
|
90
251
|
const r = await sql `
|
|
@@ -97,8 +258,12 @@ let TriggerEventSweepJob = class TriggerEventSweepJob {
|
|
|
97
258
|
SELECT 1 FROM capybara.automation_event_deliveries d
|
|
98
259
|
WHERE d.event_id = e.id AND d.automation_run_id IS NULL
|
|
99
260
|
)
|
|
261
|
+
AND NOT EXISTS (
|
|
262
|
+
SELECT 1 FROM capybara.automation_offers o
|
|
263
|
+
WHERE o.event_id = e.id AND o.state = 'open' AND o.created_at > ${offerCutoff}
|
|
264
|
+
)
|
|
100
265
|
ORDER BY e.created_at
|
|
101
|
-
LIMIT ${
|
|
266
|
+
LIMIT ${limit}
|
|
102
267
|
FOR UPDATE SKIP LOCKED
|
|
103
268
|
)
|
|
104
269
|
RETURNING id`.execute(db);
|
|
@@ -106,22 +271,26 @@ let TriggerEventSweepJob = class TriggerEventSweepJob {
|
|
|
106
271
|
});
|
|
107
272
|
}
|
|
108
273
|
/**
|
|
109
|
-
* The
|
|
110
|
-
* {@link COALESCE_STALE_MS} (see the class), oldest first
|
|
274
|
+
* The pairs whose newest waiting delivery is older than their org's `coalesceSeconds` plus
|
|
275
|
+
* {@link COALESCE_STALE_MS} (see the class), oldest first window first; a pair whose newest
|
|
276
|
+
* waiting delivery is past {@link WINDOW_GIVE_UP_MS} by more than one sweep is left out (given up
|
|
277
|
+
* on before).
|
|
111
278
|
*/
|
|
112
279
|
async waitingWindows(now) {
|
|
113
280
|
const db = this.kdb.db;
|
|
114
281
|
// coalesceSeconds is at least 1: anything younger than the stale margin is not stale anywhere
|
|
115
282
|
const older = new Date(now.getTime() - COALESCE_STALE_MS);
|
|
283
|
+
const since = new Date(now.getTime() - WINDOW_GIVE_UP_MS - SWEEP_EVERY_MS);
|
|
116
284
|
const rows = await asPlatform("deployment-wide lost coalescing window sweep", () => sql `
|
|
117
|
-
SELECT
|
|
118
|
-
d.
|
|
119
|
-
d.created_at AS first
|
|
285
|
+
SELECT d.org_id, d.automation_id, d.subject_key,
|
|
286
|
+
(array_agg(d.event_id ORDER BY d.created_at, e.created_at, e.id))[1] AS first_event_id,
|
|
287
|
+
min(d.created_at) AS first, max(d.created_at) AS last
|
|
120
288
|
FROM capybara.automation_event_deliveries d
|
|
121
289
|
JOIN capybara.trigger_events e ON e.id = d.event_id
|
|
122
290
|
WHERE d.automation_run_id IS NULL
|
|
123
|
-
|
|
124
|
-
|
|
291
|
+
GROUP BY d.org_id, d.automation_id, d.subject_key
|
|
292
|
+
HAVING max(d.created_at) < ${older} AND max(d.created_at) >= ${since}
|
|
293
|
+
ORDER BY min(d.created_at)
|
|
125
294
|
LIMIT ${MAX_WINDOWS}`.execute(db));
|
|
126
295
|
const settings = new Map();
|
|
127
296
|
const out = [];
|
|
@@ -131,33 +300,117 @@ let TriggerEventSweepJob = class TriggerEventSweepJob {
|
|
|
131
300
|
coalesceSeconds = (await withOrgScope(r.org_id, () => readAutomationSettings(db, this.config, r.org_id))).coalesceSeconds;
|
|
132
301
|
settings.set(r.org_id, coalesceSeconds);
|
|
133
302
|
}
|
|
134
|
-
|
|
135
|
-
|
|
303
|
+
// the newest window the dispatcher may have opened is still due: not lost (yet)
|
|
304
|
+
const last = new Date(r.last);
|
|
305
|
+
if (now.getTime() - last.getTime() <= coalesceSeconds * 1000 + COALESCE_STALE_MS)
|
|
136
306
|
continue;
|
|
137
307
|
out.push({
|
|
138
308
|
orgId: r.org_id,
|
|
139
309
|
automationId: r.automation_id,
|
|
140
310
|
subjectKey: r.subject_key,
|
|
141
311
|
firstEventId: r.first_event_id,
|
|
142
|
-
first,
|
|
312
|
+
first: new Date(r.first),
|
|
313
|
+
last,
|
|
143
314
|
});
|
|
144
315
|
}
|
|
145
|
-
return out
|
|
316
|
+
return out;
|
|
146
317
|
}
|
|
147
318
|
/**
|
|
148
|
-
*
|
|
149
|
-
*
|
|
319
|
+
* Directed events still `pending` more than {@link PENDING_DIRECTED_STALE_MS} after they were
|
|
320
|
+
* stored, oldest first, at most {@link MAX_PENDING_DIRECTED}; no upper bound on age: one past
|
|
321
|
+
* {@link WINDOW_GIVE_UP_MS} is marked `undelivered` by the sweep and so leaves this list.
|
|
322
|
+
*/
|
|
323
|
+
async stalePendingDirected(now) {
|
|
324
|
+
const older = new Date(now.getTime() - PENDING_DIRECTED_STALE_MS);
|
|
325
|
+
const rows = await asPlatform("deployment-wide stale directed trigger event sweep", () => sql `
|
|
326
|
+
SELECT org_id, id, created_at FROM capybara.trigger_events
|
|
327
|
+
WHERE state = 'pending' AND audience IS NOT NULL
|
|
328
|
+
AND created_at < ${older}
|
|
329
|
+
ORDER BY created_at
|
|
330
|
+
LIMIT ${MAX_PENDING_DIRECTED}`.execute(this.kdb.db));
|
|
331
|
+
return rows.rows.map((r) => ({
|
|
332
|
+
orgId: r.org_id,
|
|
333
|
+
id: r.id,
|
|
334
|
+
createdAt: new Date(r.created_at),
|
|
335
|
+
}));
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* Marks a directed event that is still pending `undelivered` and tells its source
|
|
339
|
+
* (`run.lifecycle` `offer_declined`, reason `undelivered`) in the same transaction; true when it
|
|
340
|
+
* was pending.
|
|
341
|
+
*/
|
|
342
|
+
async giveUpPending(orgId, eventId) {
|
|
343
|
+
const db = this.kdb.db;
|
|
344
|
+
const r = await db
|
|
345
|
+
.updateTable("trigger_events")
|
|
346
|
+
.set({ state: "undelivered" })
|
|
347
|
+
.where("org_id", "=", orgId)
|
|
348
|
+
.where("id", "=", eventId)
|
|
349
|
+
.where("state", "=", "pending")
|
|
350
|
+
.returning(["plugin", "audience", "subject"])
|
|
351
|
+
.executeTakeFirst();
|
|
352
|
+
if (r === undefined)
|
|
353
|
+
return false;
|
|
354
|
+
if (r.audience !== null) {
|
|
355
|
+
await oweOfferDeclinedIn(db, this.outbox, {
|
|
356
|
+
orgId,
|
|
357
|
+
plugin: r.plugin,
|
|
358
|
+
eventId,
|
|
359
|
+
accountId: r.audience.accountId,
|
|
360
|
+
agentId: r.audience.agentId,
|
|
361
|
+
subject: r.subject,
|
|
362
|
+
reason: "undelivered",
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
return true;
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* Owes the event's dispatch job again unless a dispatch row of it is still pending in the
|
|
369
|
+
* outbox; true when it owed one.
|
|
370
|
+
*/
|
|
371
|
+
async oweDispatch(orgId, eventId, now) {
|
|
372
|
+
const prefix = triggerDispatchJobId(eventId);
|
|
373
|
+
const pending = await this.kdb.db
|
|
374
|
+
.selectFrom("outbox")
|
|
375
|
+
.select("id")
|
|
376
|
+
.where("org_id", "=", orgId)
|
|
377
|
+
.where("queue", "=", MAINTENANCE_QUEUE_NAME)
|
|
378
|
+
.where("job_name", "=", TRIGGER_DISPATCH_JOB)
|
|
379
|
+
.where(sql `starts_with(job_id, ${prefix})`)
|
|
380
|
+
.where("dead_at", "is", null)
|
|
381
|
+
.limit(1)
|
|
382
|
+
.executeTakeFirst();
|
|
383
|
+
if (pending !== undefined)
|
|
384
|
+
return false;
|
|
385
|
+
this.log.warn("directed trigger event still pending; the sweep owes its dispatch again", {
|
|
386
|
+
orgId,
|
|
387
|
+
eventId,
|
|
388
|
+
});
|
|
389
|
+
return this.outbox.add({
|
|
390
|
+
queue: MAINTENANCE_QUEUE_NAME,
|
|
391
|
+
name: TRIGGER_DISPATCH_JOB,
|
|
392
|
+
jobId: `${prefix}-sweep-${Math.floor(now.getTime() / 60_000)}`,
|
|
393
|
+
data: { orgId, eventId },
|
|
394
|
+
orgId,
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* Owes the window's coalesce job unless an outbox row of the pair (the dispatcher's for any of
|
|
399
|
+
* its windows, or an earlier sweep's) is still pending; true when it owed one.
|
|
150
400
|
*/
|
|
151
401
|
async oweFlush(w, now) {
|
|
152
402
|
const db = this.kdb.db;
|
|
153
|
-
const
|
|
403
|
+
const prefix = `${coalesceJobIdOfKey(w.automationId, w.subjectKey)}-`;
|
|
154
404
|
const pending = await db
|
|
155
405
|
.selectFrom("outbox")
|
|
156
406
|
.select("id")
|
|
157
407
|
.where("org_id", "=", w.orgId)
|
|
158
408
|
.where("queue", "=", MAINTENANCE_QUEUE_NAME)
|
|
159
409
|
.where("job_name", "=", AUTOMATION_COALESCE_JOB)
|
|
160
|
-
.where(
|
|
410
|
+
.where(sql `starts_with(job_id, ${prefix})`)
|
|
411
|
+
// the prefix alone could also be another subject's whose kind extends this key
|
|
412
|
+
.where(sql `data->>'automationId' = ${w.automationId}`)
|
|
413
|
+
.where(sql `data->>'subjectKey' = ${w.subjectKey}`)
|
|
161
414
|
.where("dead_at", "is", null)
|
|
162
415
|
.limit(1)
|
|
163
416
|
.executeTakeFirst();
|
|
@@ -172,7 +425,7 @@ let TriggerEventSweepJob = class TriggerEventSweepJob {
|
|
|
172
425
|
return this.outbox.add({
|
|
173
426
|
queue: MAINTENANCE_QUEUE_NAME,
|
|
174
427
|
name: AUTOMATION_COALESCE_JOB,
|
|
175
|
-
jobId: `${
|
|
428
|
+
jobId: `${prefix}${w.firstEventId}-sweep-${Math.floor(now.getTime() / 60_000)}`,
|
|
176
429
|
data: { orgId: w.orgId, automationId: w.automationId, subjectKey: w.subjectKey },
|
|
177
430
|
orgId: w.orgId,
|
|
178
431
|
});
|
|
@@ -183,20 +436,33 @@ __decorate([
|
|
|
183
436
|
], TriggerEventSweepJob.prototype, "sweep", null);
|
|
184
437
|
__decorate([
|
|
185
438
|
Transactional()
|
|
186
|
-
], TriggerEventSweepJob.prototype, "
|
|
439
|
+
], TriggerEventSweepJob.prototype, "deleteHandles", null);
|
|
440
|
+
__decorate([
|
|
441
|
+
Transactional()
|
|
442
|
+
], TriggerEventSweepJob.prototype, "deleteInboxItems", null);
|
|
443
|
+
__decorate([
|
|
444
|
+
Transactional()
|
|
445
|
+
], TriggerEventSweepJob.prototype, "deleteEvents", null);
|
|
446
|
+
__decorate([
|
|
447
|
+
Transactional()
|
|
448
|
+
], TriggerEventSweepJob.prototype, "giveUpPending", null);
|
|
449
|
+
__decorate([
|
|
450
|
+
Transactional()
|
|
451
|
+
], TriggerEventSweepJob.prototype, "oweDispatch", null);
|
|
187
452
|
__decorate([
|
|
188
453
|
Transactional()
|
|
189
454
|
], TriggerEventSweepJob.prototype, "oweFlush", null);
|
|
190
455
|
TriggerEventSweepJob = __decorate([
|
|
191
456
|
Injectable()
|
|
192
|
-
// org-filter: deployment-wide sweeps of trigger events
|
|
193
|
-
// owed job in its own org
|
|
457
|
+
// org-filter: deployment-wide sweeps of trigger events, waiting deliveries, work offers, cause
|
|
458
|
+
// handles and inbox items (LockedCron), each owed job and expired offer in its own org
|
|
194
459
|
,
|
|
195
460
|
__param(0, Inject(KernelDb)),
|
|
196
461
|
__param(1, Inject(TransactionHost)),
|
|
197
462
|
__param(2, Inject(KernelConfigService)),
|
|
198
463
|
__param(3, Inject(OutboxService)),
|
|
199
464
|
__param(4, Inject(LockService)),
|
|
200
|
-
__param(5, Inject(KERNEL_LOGGER))
|
|
465
|
+
__param(5, Inject(KERNEL_LOGGER)),
|
|
466
|
+
__param(6, Inject(AcceptanceService))
|
|
201
467
|
], TriggerEventSweepJob);
|
|
202
468
|
export { TriggerEventSweepJob };
|