@parcha/agentrun-serve 0.0.0-stage → 0.1.0-beta.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +748 -0
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +2190 -2
- package/dist/adapters.d.ts +234 -0
- package/dist/adapters.js +585 -0
- package/dist/agents.d.ts +130 -0
- package/dist/agents.js +308 -0
- package/dist/app.d.ts +7 -0
- package/dist/app.js +384 -0
- package/dist/background.d.ts +28 -0
- package/dist/background.js +376 -0
- package/dist/bound-files.d.ts +4 -0
- package/dist/bound-files.js +164 -0
- package/dist/box/record.d.ts +6 -0
- package/dist/box/record.js +41 -0
- package/dist/box/sweep.d.ts +53 -0
- package/dist/box/sweep.js +193 -0
- package/dist/box-egress.d.ts +98 -0
- package/dist/box-egress.js +259 -0
- package/dist/box-image.d.ts +98 -0
- package/dist/box-image.js +285 -0
- package/dist/box-relay-vm.d.ts +80 -0
- package/dist/box-relay-vm.js +389 -0
- package/dist/box-relay.d.ts +45 -0
- package/dist/box-relay.js +227 -0
- package/dist/boxes.d.ts +72 -0
- package/dist/boxes.js +189 -0
- package/dist/browser-cost.d.ts +41 -0
- package/dist/browser-cost.js +158 -0
- package/dist/cap.d.ts +332 -0
- package/dist/cap.js +992 -0
- package/dist/catalog.d.ts +20 -0
- package/dist/catalog.js +53 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +167 -0
- package/dist/coding-tools.d.ts +35 -0
- package/dist/coding-tools.js +87 -0
- package/dist/console/THIRD-PARTY-NOTICES.txt +1721 -0
- package/dist/console/assets/index-34jfpIbQ.js +481 -0
- package/dist/console/assets/index-DUHbWcIP.css +1 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-CIEtRijs.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-BB5xRk30.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-BHyURHCj.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-C_uLvvQ5.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-Dj6eZy5f.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-DpeVePZf.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-greek-400-normal-CNojz0t3.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-600-normal-3KAm9r92.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-400-normal-B11XCQ5g.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-600-normal-DXv3JcnD.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-DHMOLxAi.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-DiQlUoE6.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-BeU3T8wf.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-ByoDsISC.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-CSpzN4cI.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-Dtizs43-.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-400-normal-Cph9ettZ.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-400-normal-DfGZKnlb.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-600-normal-BGBUNdzT.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-600-normal-COje25QW.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-4l4lq8zr.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-BGzXWJeR.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-8_E36CQj.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-C27an7Zc.woff +0 -0
- package/dist/console/index.html +15 -0
- package/dist/content-filter.d.ts +7 -0
- package/dist/content-filter.js +23 -0
- package/dist/daytona-api.d.ts +21 -0
- package/dist/daytona-api.js +101 -0
- package/dist/decision-rows.d.ts +19 -0
- package/dist/decision-rows.js +123 -0
- package/dist/decisions.d.ts +94 -0
- package/dist/decisions.js +184 -0
- package/dist/effort-guidance.d.ts +5 -0
- package/dist/effort-guidance.js +14 -0
- package/dist/environment.d.ts +5 -0
- package/dist/environment.js +11 -0
- package/dist/errors.d.ts +74 -0
- package/dist/errors.js +69 -0
- package/dist/exa-keyless.d.ts +35 -0
- package/dist/exa-keyless.js +202 -0
- package/dist/fetch-page.d.ts +114 -0
- package/dist/fetch-page.js +182 -0
- package/dist/files.d.ts +65 -0
- package/dist/files.js +158 -0
- package/dist/grade.d.ts +93 -0
- package/dist/grade.js +328 -0
- package/dist/graph-served.d.ts +23 -0
- package/dist/graph-served.js +75 -0
- package/dist/graph-view.d.ts +102 -0
- package/dist/graph-view.js +219 -0
- package/dist/harness-app.d.ts +40 -0
- package/dist/harness-app.js +708 -0
- package/dist/harness-opencode/adapter.d.ts +45 -0
- package/dist/harness-opencode/adapter.js +272 -0
- package/dist/harness-opencode/binary.d.ts +18 -0
- package/dist/harness-opencode/binary.js +87 -0
- package/dist/harness-opencode/config.d.ts +24 -0
- package/dist/harness-opencode/config.js +61 -0
- package/dist/harness-opencode/harness.d.ts +77 -0
- package/dist/harness-opencode/harness.js +620 -0
- package/dist/harness-opencode/host/mcp.d.ts +40 -0
- package/dist/harness-opencode/host/mcp.js +208 -0
- package/dist/harness-opencode/host/policy.d.ts +71 -0
- package/dist/harness-opencode/host/policy.js +419 -0
- package/dist/harness-opencode/host/server.d.ts +55 -0
- package/dist/harness-opencode/host/server.js +165 -0
- package/dist/harness-opencode/index.d.ts +9 -0
- package/dist/harness-opencode/index.js +6 -0
- package/dist/harness-opencode/verify.d.ts +32 -0
- package/dist/harness-opencode/verify.js +75 -0
- package/dist/harness-opencode/versions.d.ts +33 -0
- package/dist/harness-opencode/versions.js +64 -0
- package/dist/harness.d.ts +56 -0
- package/dist/harness.js +77 -0
- package/dist/home-path.d.ts +27 -0
- package/dist/home-path.js +78 -0
- package/dist/host-tools.d.ts +30 -0
- package/dist/host-tools.js +154 -0
- package/dist/host.d.ts +39 -0
- package/dist/host.js +85 -0
- package/dist/hosted-search.d.ts +27 -0
- package/dist/hosted-search.js +133 -0
- package/dist/import-sources.d.ts +104 -0
- package/dist/import-sources.js +629 -0
- package/dist/import-summary.d.ts +25 -0
- package/dist/import-summary.js +75 -0
- package/dist/import-worker.d.ts +26 -0
- package/dist/import-worker.js +41 -0
- package/dist/import.d.ts +145 -0
- package/dist/import.js +1222 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +6 -0
- package/dist/key-check.d.ts +37 -0
- package/dist/key-check.js +112 -0
- package/dist/key-refusal.d.ts +51 -0
- package/dist/key-refusal.js +191 -0
- package/dist/learn/check.d.ts +108 -0
- package/dist/learn/check.js +277 -0
- package/dist/learn/grade.d.ts +80 -0
- package/dist/learn/grade.js +445 -0
- package/dist/learn/index.d.ts +7 -0
- package/dist/learn/index.js +11 -0
- package/dist/learn/invisible.d.ts +5 -0
- package/dist/learn/invisible.js +42 -0
- package/dist/learn/notes.d.ts +59 -0
- package/dist/learn/notes.js +147 -0
- package/dist/learn/reflect.d.ts +49 -0
- package/dist/learn/reflect.js +213 -0
- package/dist/learn/secrets.d.ts +18 -0
- package/dist/learn/secrets.js +131 -0
- package/dist/learn/skills.d.ts +97 -0
- package/dist/learn/skills.js +271 -0
- package/dist/learned-workflow.d.ts +59 -0
- package/dist/learned-workflow.js +191 -0
- package/dist/learning-routes.d.ts +196 -0
- package/dist/learning-routes.js +609 -0
- package/dist/learning-run.d.ts +306 -0
- package/dist/learning-run.js +819 -0
- package/dist/learning-words.d.ts +76 -0
- package/dist/learning-words.js +174 -0
- package/dist/learning.d.ts +418 -0
- package/dist/learning.js +946 -0
- package/dist/llm.d.ts +40 -0
- package/dist/llm.js +37 -0
- package/dist/llms.txt +37 -0
- package/dist/mcp-servers.d.ts +118 -0
- package/dist/mcp-servers.js +450 -0
- package/dist/mcp.d.ts +51 -0
- package/dist/mcp.js +392 -0
- package/dist/model.d.ts +186 -0
- package/dist/model.js +485 -0
- package/dist/monid.d.ts +74 -0
- package/dist/monid.js +277 -0
- package/dist/openapi/agentrun-v2.openapi.json +4806 -0
- package/dist/openapi.d.ts +10 -0
- package/dist/openapi.js +1727 -0
- package/dist/owner.d.ts +55 -0
- package/dist/owner.js +222 -0
- package/dist/packs.d.ts +71 -0
- package/dist/packs.js +180 -0
- package/dist/page.d.ts +32 -0
- package/dist/page.js +133 -0
- package/dist/paid-calls.d.ts +50 -0
- package/dist/paid-calls.js +110 -0
- package/dist/pause.d.ts +70 -0
- package/dist/pause.js +97 -0
- package/dist/pdf-pages.d.ts +44 -0
- package/dist/pdf-pages.js +147 -0
- package/dist/place.d.ts +69 -0
- package/dist/place.js +137 -0
- package/dist/print.d.ts +20 -0
- package/dist/print.js +29 -0
- package/dist/propose.d.ts +40 -0
- package/dist/propose.js +112 -0
- package/dist/quiet-sqlite-warning.d.ts +1 -0
- package/dist/quiet-sqlite-warning.js +14 -0
- package/dist/request-start.d.ts +22 -0
- package/dist/request-start.js +350 -0
- package/dist/result.d.ts +3 -0
- package/dist/result.js +5 -0
- package/dist/rows.d.ts +46 -0
- package/dist/rows.js +121 -0
- package/dist/run-box.d.ts +186 -0
- package/dist/run-box.js +590 -0
- package/dist/run-manifest.d.ts +27 -0
- package/dist/run-manifest.js +60 -0
- package/dist/runnable.d.ts +83 -0
- package/dist/runnable.js +170 -0
- package/dist/runs.d.ts +1062 -0
- package/dist/runs.js +3020 -0
- package/dist/secret-cut.d.ts +27 -0
- package/dist/secret-cut.js +109 -0
- package/dist/secrets.d.ts +62 -0
- package/dist/secrets.js +158 -0
- package/dist/server-lock.d.ts +44 -0
- package/dist/server-lock.js +140 -0
- package/dist/server.d.ts +722 -0
- package/dist/server.js +2118 -0
- package/dist/sessions.d.ts +4 -0
- package/dist/sessions.js +105 -0
- package/dist/sign-ins.d.ts +99 -0
- package/dist/sign-ins.js +288 -0
- package/dist/skills.d.ts +43 -0
- package/dist/skills.js +96 -0
- package/dist/stats.d.ts +106 -0
- package/dist/stats.js +103 -0
- package/dist/tool-gate.d.ts +266 -0
- package/dist/tool-gate.js +554 -0
- package/dist/tool-keys.d.ts +187 -0
- package/dist/tool-keys.js +315 -0
- package/dist/tool-plane.d.ts +228 -0
- package/dist/tool-plane.js +400 -0
- package/dist/tools.d.ts +202 -0
- package/dist/tools.js +372 -0
- package/dist/trigger-secrets.d.ts +32 -0
- package/dist/trigger-secrets.js +143 -0
- package/dist/triggers.d.ts +439 -0
- package/dist/triggers.js +863 -0
- package/dist/turn-end.d.ts +24 -0
- package/dist/turn-end.js +15 -0
- package/dist/turns.d.ts +34 -0
- package/dist/turns.js +202 -0
- package/dist/uploads.d.ts +104 -0
- package/dist/uploads.js +474 -0
- package/dist/usage-lines.d.ts +26 -0
- package/dist/usage-lines.js +28 -0
- package/dist/usage.d.ts +29 -0
- package/dist/usage.js +58 -0
- package/dist/validate.d.ts +57 -0
- package/dist/validate.js +184 -0
- package/dist/web-fetch.d.ts +64 -0
- package/dist/web-fetch.js +262 -0
- package/dist/web-search.d.ts +54 -0
- package/dist/web-search.js +136 -0
- package/dist/webhooks.d.ts +189 -0
- package/dist/webhooks.js +503 -0
- package/dist/workspace-paths.d.ts +33 -0
- package/dist/workspace-paths.js +104 -0
- package/dist/workspace.d.ts +88 -0
- package/dist/workspace.js +369 -0
- package/launcher/agentrun-serve +109 -0
- package/package.json +100 -4
- package/skills/agentrun-serve/SKILL.md +128 -0
package/dist/triggers.js
ADDED
|
@@ -0,0 +1,863 @@
|
|
|
1
|
+
// Triggers: what starts a run with no caller. A trigger is a source (here a schedule: a cron line in an IANA zone, one
|
|
2
|
+
// time, or every N seconds on a grid) and a target (here a run of an agent, always capped). They live in
|
|
3
|
+
// DIR/triggers.json, written whole and synced on every change, with each trigger's last HISTORY_KEPT firings. Never in
|
|
4
|
+
// store.sqlite, which runs open.
|
|
5
|
+
// A firing starts exactly once. Its key is fixed by what it fires for: the trigger and its nominal time (a schedule), or
|
|
6
|
+
// the trigger and the caller's Idempotency-Key (run now). One write records it `due` and moves the trigger's next time
|
|
7
|
+
// on; a key already in the history is not recorded again, nor a run now's key within its day after it left the history. Then its run is started with the key as its origin, which
|
|
8
|
+
// the agent store keeps in the run's own insert, so a firing driven again after a restart finds its run and starts no
|
|
9
|
+
// second one. While the trigger's last run is active (working, or waiting on a person), a firing is `skipped`, never
|
|
10
|
+
// queued: a firing queued behind a run parked on a person would wait for as long as the person does.
|
|
11
|
+
// One timer, at the soonest next time of an enabled trigger (or a firing's retry), is armed again after each change. A
|
|
12
|
+
// next time is reckoned from the last nominal time, never from the clock, so a late timer does not drift. Of the times
|
|
13
|
+
// that came while the server was down, or its timer late past LATE_MS, the latest fires if it is within the trigger's
|
|
14
|
+
// catch-up window and the rest are one `missed` row; the schedule goes on from now. A failed firing queues a
|
|
15
|
+
// trigger.failed webhook message, and FAILURES_TO_PAUSE in a row turn the trigger off.
|
|
16
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
17
|
+
import { readFileSync } from "node:fs";
|
|
18
|
+
import { join } from "node:path";
|
|
19
|
+
import { Cron } from "croner";
|
|
20
|
+
import { ApiError, invalid } from "./errors.js";
|
|
21
|
+
import { writeDurableSync } from "./files.js";
|
|
22
|
+
import { EFFORTS } from "./model.js";
|
|
23
|
+
import { ID, IDEMPOTENCY_TTL_S, isObject, unknownFields } from "./validate.js";
|
|
24
|
+
export const TRIGGERS_FILE = "triggers.json";
|
|
25
|
+
/** The firings each trigger keeps, newest last; a firing still due is never dropped, nor a failure whose trigger.failed is
|
|
26
|
+
* not queued yet (up to UNTOLD_KEPT). */
|
|
27
|
+
export const HISTORY_KEPT = 200;
|
|
28
|
+
/** The most firings a trigger holds due. A message_run firing to a working run stays due, tried every 5 s, until the
|
|
29
|
+
* run takes it: one per idle point, so twenty is far past a sender's burst while the run works, and with up to 16 KiB of
|
|
30
|
+
* payload each they add at most 320 KiB to the file every write rewrites. Past it a webhook event and a run now are
|
|
31
|
+
* refused (429, retryable) before anything is written, and a schedule's time is skipped. */
|
|
32
|
+
export const DUE_KEPT = 20;
|
|
33
|
+
/** How long a refused event is told to wait (Retry-After). */
|
|
34
|
+
const FULL_RETRY_S = 30;
|
|
35
|
+
/** The most failures a trigger keeps past its history while their trigger.failed waits for the outbox. A schedule turns
|
|
36
|
+
* itself off after FAILURES_TO_PAUSE in a row, but runs that start between failures, and run now, can add more. */
|
|
37
|
+
const UNTOLD_KEPT = 50;
|
|
38
|
+
/** The shortest every_s, and so the most often a schedule fires: a cron line has no seconds field. */
|
|
39
|
+
export const MIN_EVERY_S = 60;
|
|
40
|
+
/** The longest every_s: a year and a day. */
|
|
41
|
+
export const MAX_EVERY_S = 366 * 86_400;
|
|
42
|
+
export const SOURCE_KINDS = ["schedule", "webhook"];
|
|
43
|
+
export const TARGET_KINDS = ["start_run", "message_run"];
|
|
44
|
+
export const OVERLAP = ["skip"];
|
|
45
|
+
export const FIRING_STATUSES = ["due", "started", "sent", "skipped", "failed", "missed"];
|
|
46
|
+
/** The most of a webhook's payload a firing passes on: the rest is cut, at a character's start. */
|
|
47
|
+
export const PAYLOAD_KEPT_BYTES = 16 * 1024;
|
|
48
|
+
/** How late a missed time may be and still fire once, by default: an hour. */
|
|
49
|
+
export const CATCHUP_WINDOW_S = 3600;
|
|
50
|
+
/** The failed firings in a row that turn a trigger off. */
|
|
51
|
+
export const FAILURES_TO_PAUSE = 5;
|
|
52
|
+
/** A nominal time the timer reaches later than this was missed: the server was down, or its timer late. */
|
|
53
|
+
const LATE_MS = 60_000;
|
|
54
|
+
/** The most missed times one row counts one by one; past it the schedule jumps to now. */
|
|
55
|
+
const MISSED_COUNTED = 10_000;
|
|
56
|
+
/** The waits before a firing a full server refused (429), or whose last run could not be read, is tried again. */
|
|
57
|
+
const RETRY_MS = [5_000, 15_000, 60_000, 300_000];
|
|
58
|
+
/** How soon a message refused because its run is working is tried again: not a failure, so no backoff. */
|
|
59
|
+
const WORKING_RETRY_MS = 5_000;
|
|
60
|
+
/** How soon a write that failed under the timer is tried again. */
|
|
61
|
+
const WRITE_RETRY_MS = 5_000;
|
|
62
|
+
/** Node fires a longer timeout at once: a far next time is reached in steps of at most this. */
|
|
63
|
+
const MAX_TIMEOUT_MS = 2 ** 31 - 1;
|
|
64
|
+
const MAX_NAME = 200;
|
|
65
|
+
/** The most firings each trigger keeps past its history for their key's day: a bound on the file (commit()). */
|
|
66
|
+
const KEPT_FIRINGS = 1_000;
|
|
67
|
+
const ENDED = new Set(["completed", "failed", "cancelled"]);
|
|
68
|
+
const dueOf = (trigger) => trigger.firings.filter((f) => f.status === "due").length;
|
|
69
|
+
const LOST_AT_SETUP = "The server stopped while setting up the run.";
|
|
70
|
+
const settled = (t) => ({ overlap: "skip", catchup_window_s: t.catchup_window_s ?? CATCHUP_WINDOW_S, failures_in_a_row: t.failures_in_a_row ?? 0, disabled: t.disabled ?? null });
|
|
71
|
+
const REAL_CLOCK = {
|
|
72
|
+
now: () => Date.now(),
|
|
73
|
+
arm(fire, ms) {
|
|
74
|
+
const timer = setTimeout(fire, Math.min(ms, MAX_TIMEOUT_MS));
|
|
75
|
+
timer.unref();
|
|
76
|
+
return { clear: () => clearTimeout(timer) };
|
|
77
|
+
},
|
|
78
|
+
};
|
|
79
|
+
const iso = (ms) => new Date(ms).toISOString();
|
|
80
|
+
/** RFC 3339 in UTC, to the second: the form a schedule's key is made of. */
|
|
81
|
+
const second = (ms) => iso(ms).replace(/\.\d{3}Z$/, "Z");
|
|
82
|
+
const RFC3339 = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d+)?(Z|[+-](\d{2}):(\d{2}))$/i;
|
|
83
|
+
/** An RFC 3339 date-time with its offset, as an instant; undefined for one that names no real time (month 13, Feb 30,
|
|
84
|
+
* 25 o'clock, an offset past 23:59), which Date.parse would refuse or roll over. */
|
|
85
|
+
function instantOf(text) {
|
|
86
|
+
const parts = typeof text === "string" ? RFC3339.exec(text) : null;
|
|
87
|
+
if (!parts)
|
|
88
|
+
return undefined;
|
|
89
|
+
const [y, mo, d, h, mi, s, , , oh = "0", om = "0"] = parts.slice(1).map((p) => p ?? "0").map(String);
|
|
90
|
+
const days = new Date(Date.UTC(Number(y), Number(mo), 0)).getUTCDate();
|
|
91
|
+
if (Number(mo) < 1 || Number(mo) > 12 || Number(d) < 1 || Number(d) > days || Number(h) > 23 || Number(mi) > 59 || Number(s) > 59 || Number(oh) > 23 || Number(om) > 59)
|
|
92
|
+
return undefined;
|
|
93
|
+
const at = Date.parse(text);
|
|
94
|
+
return Number.isFinite(at) ? at : undefined;
|
|
95
|
+
}
|
|
96
|
+
export const firingKey = (kind, triggerId, what) => `fir_${createHash("sha256").update(`${kind}\n${triggerId}\n${what}`).digest("hex").slice(0, 32)}`;
|
|
97
|
+
const cronOf = (source) => new Cron(source.cron, { timezone: source.timezone, mode: "5-part" });
|
|
98
|
+
/** The source's first nominal time strictly after `after`, or null when it has none (or none a Date holds). */
|
|
99
|
+
function nextAfter(source, after, cron) {
|
|
100
|
+
if (source.kind === "webhook")
|
|
101
|
+
return null;
|
|
102
|
+
const at = nextOf(source, after, cron);
|
|
103
|
+
return at !== null && Number.isFinite(at) && Math.abs(at) <= DATE_MAX_MS ? at : null;
|
|
104
|
+
}
|
|
105
|
+
/** `cron`: the source's Cron, made once by a caller that asks for many times. */
|
|
106
|
+
function nextOf(source, after, cron) {
|
|
107
|
+
if ("cron" in source)
|
|
108
|
+
return (cron ?? cronOf(source)).nextRun(new Date(after))?.getTime() ?? null;
|
|
109
|
+
if ("at" in source)
|
|
110
|
+
return Date.parse(source.at) > after ? Date.parse(source.at) : null;
|
|
111
|
+
const start = Date.parse(source.start_at);
|
|
112
|
+
const step = source.every_s * 1000;
|
|
113
|
+
return start > after ? start : start + (Math.floor((after - start) / step) + 1) * step;
|
|
114
|
+
}
|
|
115
|
+
/** The source's latest nominal time at or before `now`, given one that is (`first`), found without walking to it: an
|
|
116
|
+
* interval's on its grid, a cron line's by croner's search back from a second past now (previousRuns is exclusive and
|
|
117
|
+
* to the second), which yields the times nextRun does, across clock changes too. */
|
|
118
|
+
function latestBy(source, first, now, cron) {
|
|
119
|
+
if ("at" in source)
|
|
120
|
+
return first;
|
|
121
|
+
if ("every_s" in source)
|
|
122
|
+
return first + Math.floor((now - first) / (source.every_s * 1000)) * source.every_s * 1000;
|
|
123
|
+
const at = (cron ?? cronOf(source)).previousRuns(1, new Date(Math.floor(now / 1000) * 1000 + 1000))[0]?.getTime();
|
|
124
|
+
return at !== undefined && at >= first && at <= now ? at : first;
|
|
125
|
+
}
|
|
126
|
+
/** A time in `zone` as a person reads it: "Nov 1, 2026, 1:30 AM PDT". */
|
|
127
|
+
const local = (ms, zone) => new Intl.DateTimeFormat("en-US", { timeZone: validZone(zone) ? zone : "UTC", year: "numeric", month: "short", day: "numeric", hour: "numeric", minute: "2-digit", timeZoneName: "short" }).format(ms);
|
|
128
|
+
const zoneOf = (source) => ("timezone" in source ? source.timezone : "UTC");
|
|
129
|
+
const validZone = (zone) => {
|
|
130
|
+
try {
|
|
131
|
+
new Intl.DateTimeFormat("en-US", { timeZone: zone });
|
|
132
|
+
return true;
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
return false;
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
/** Why a schedule kept in the file no longer reads (its zone or its cron line, which this croner or this ICU refuses):
|
|
139
|
+
* a trigger with one is turned off with the reason, alone, and never stalls the others. */
|
|
140
|
+
function sourceProblem(source) {
|
|
141
|
+
if (!("cron" in source))
|
|
142
|
+
return undefined;
|
|
143
|
+
if (!validZone(source.timezone))
|
|
144
|
+
return `the zone ${source.timezone} is not one this server knows`;
|
|
145
|
+
try {
|
|
146
|
+
cronOf(source).nextRun(new Date(0));
|
|
147
|
+
return undefined;
|
|
148
|
+
}
|
|
149
|
+
catch (error) {
|
|
150
|
+
return `the cron line does not read: ${error.message}`;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
function sourceOf(value, now, issues) {
|
|
154
|
+
const bad = (field, reason, message) => void issues.push({ field: `source${field ? `.${field}` : ""}`, reason, message });
|
|
155
|
+
if (!isObject(value))
|
|
156
|
+
return bad("", value === undefined ? "missing" : "wrong_type", "source is an object: {kind: \"schedule\", cron, timezone}, {kind: \"schedule\", at}, {kind: \"schedule\", every_s, start_at?} or {kind: \"webhook\"}"), undefined;
|
|
157
|
+
if (value.kind === "webhook") {
|
|
158
|
+
issues.push(...unknownFields(value, ["kind"]).map((i) => ({ ...i, field: `source.${i.field}` })));
|
|
159
|
+
return { kind: "webhook" };
|
|
160
|
+
}
|
|
161
|
+
if (value.kind !== "schedule")
|
|
162
|
+
return bad("kind", "not_an_option", `source.kind is one of ${SOURCE_KINDS.join(", ")}`), undefined;
|
|
163
|
+
const forms = ["cron", "at", "every_s"].filter((field) => value[field] !== undefined);
|
|
164
|
+
if (forms.length !== 1)
|
|
165
|
+
return bad("", "invalid", "a schedule names exactly one of cron, at and every_s"), undefined;
|
|
166
|
+
if (value.cron !== undefined) {
|
|
167
|
+
issues.push(...unknownFields(value, ["kind", "cron", "timezone"]).map((i) => ({ ...i, field: `source.${i.field}` })));
|
|
168
|
+
const timezone = value.timezone ?? "UTC";
|
|
169
|
+
if (typeof timezone !== "string" || !validZone(timezone))
|
|
170
|
+
return bad("timezone", "invalid", "timezone is an IANA zone, such as America/Los_Angeles (default UTC)"), undefined;
|
|
171
|
+
if (typeof value.cron !== "string" || value.cron.trim().split(/\s+/).length !== 5)
|
|
172
|
+
return bad("cron", "invalid", "cron is five fields, minute hour day-of-month month day-of-week: a schedule fires at most once a minute"), undefined;
|
|
173
|
+
const source = { kind: "schedule", cron: value.cron.trim(), timezone };
|
|
174
|
+
try {
|
|
175
|
+
if (nextAfter(source, now) === null)
|
|
176
|
+
return bad("cron", "invalid", "cron never fires"), undefined;
|
|
177
|
+
}
|
|
178
|
+
catch (error) {
|
|
179
|
+
return bad("cron", "invalid", `cron does not read: ${error.message}`), undefined;
|
|
180
|
+
}
|
|
181
|
+
return source;
|
|
182
|
+
}
|
|
183
|
+
if (value.at !== undefined) {
|
|
184
|
+
issues.push(...unknownFields(value, ["kind", "at"]).map((i) => ({ ...i, field: `source.${i.field}` })));
|
|
185
|
+
const given = instantOf(value.at);
|
|
186
|
+
if (given === undefined)
|
|
187
|
+
return bad("at", "invalid", "at is an RFC 3339 date-time with its offset"), undefined;
|
|
188
|
+
const at = Math.floor(given / 1000) * 1000;
|
|
189
|
+
if (at <= now)
|
|
190
|
+
return bad("at", "invalid", "at is in the past"), undefined;
|
|
191
|
+
return { kind: "schedule", at: second(at) };
|
|
192
|
+
}
|
|
193
|
+
issues.push(...unknownFields(value, ["kind", "every_s", "start_at"]).map((i) => ({ ...i, field: `source.${i.field}` })));
|
|
194
|
+
if (!Number.isSafeInteger(value.every_s) || value.every_s < MIN_EVERY_S || value.every_s > MAX_EVERY_S)
|
|
195
|
+
return bad("every_s", "invalid", `every_s is a whole number of seconds, ${MIN_EVERY_S} to ${MAX_EVERY_S}`), undefined;
|
|
196
|
+
const given = value.start_at === undefined ? now : instantOf(value.start_at);
|
|
197
|
+
if (given === undefined)
|
|
198
|
+
return bad("start_at", "invalid", "start_at is an RFC 3339 date-time with its offset"), undefined;
|
|
199
|
+
// The grid's origin, to the second (down, so one made now first fires an interval from now): the first firing is at it
|
|
200
|
+
// when it is ahead, else one step after it.
|
|
201
|
+
const start = Math.floor(given / 1000) * 1000;
|
|
202
|
+
return { kind: "schedule", every_s: value.every_s, start_at: second(start) };
|
|
203
|
+
}
|
|
204
|
+
function targetOf(value, issues) {
|
|
205
|
+
const bad = (field, reason, message) => void issues.push({ field: `target${field ? `.${field}` : ""}`, reason, message });
|
|
206
|
+
if (!isObject(value))
|
|
207
|
+
return bad("", value === undefined ? "missing" : "wrong_type", "target is an object: {kind: \"start_run\", agent_id, input, max_cost_usd?, effort?} or {kind: \"message_run\", run_id, input}"), undefined;
|
|
208
|
+
const before = issues.length;
|
|
209
|
+
if (value.kind === "message_run") {
|
|
210
|
+
issues.push(...unknownFields(value, ["kind", "run_id", "input"]).map((i) => ({ ...i, field: `target.${i.field}` })));
|
|
211
|
+
if (typeof value.run_id !== "string" || !ID.test(value.run_id))
|
|
212
|
+
bad("run_id", value.run_id === undefined ? "missing" : "wrong_type", "run_id is a run's id");
|
|
213
|
+
if (!isObject(value.input) || typeof value.input.content !== "string")
|
|
214
|
+
bad("input", value.input === undefined ? "missing" : "wrong_type", "input is the message, as POST /runs/{run_id}/messages takes it: {content}");
|
|
215
|
+
return issues.length > before ? undefined : { kind: "message_run", run_id: value.run_id, input: { content: value.input.content } };
|
|
216
|
+
}
|
|
217
|
+
if (value.kind !== "start_run")
|
|
218
|
+
return bad("kind", "not_an_option", `target.kind is one of ${TARGET_KINDS.join(", ")}`), undefined;
|
|
219
|
+
issues.push(...unknownFields(value, ["kind", "agent_id", "input", "max_cost_usd", "effort"]).map((i) => ({ ...i, field: `target.${i.field}` })));
|
|
220
|
+
if (typeof value.agent_id !== "string" || !ID.test(value.agent_id))
|
|
221
|
+
bad("agent_id", value.agent_id === undefined ? "missing" : "wrong_type", "agent_id is an agent's id");
|
|
222
|
+
if (!isObject(value.input))
|
|
223
|
+
bad("input", value.input === undefined ? "missing" : "wrong_type", "input is the run's input, as POST /agents/{agent_id}/runs takes it: {content}");
|
|
224
|
+
if (value.max_cost_usd !== undefined && !(typeof value.max_cost_usd === "number" && value.max_cost_usd > 0 && Number.isFinite(value.max_cost_usd)))
|
|
225
|
+
bad("max_cost_usd", "wrong_type", "max_cost_usd is a number above 0");
|
|
226
|
+
if (value.effort !== undefined && !EFFORTS.includes(value.effort))
|
|
227
|
+
bad("effort", "not_an_option", `effort is one of ${EFFORTS.join(", ")}`);
|
|
228
|
+
if (issues.length > before)
|
|
229
|
+
return undefined;
|
|
230
|
+
return { kind: "start_run", agent_id: value.agent_id, input: value.input, ...(typeof value.max_cost_usd === "number" ? { max_cost_usd: value.max_cost_usd } : {}), ...(typeof value.effort === "string" ? { effort: value.effort } : {}) };
|
|
231
|
+
}
|
|
232
|
+
/** `catchup_window_s`, as given (absent: undefined). */
|
|
233
|
+
function settingsOf(body, issues) {
|
|
234
|
+
if (body.catchup_window_s !== undefined && !(Number.isSafeInteger(body.catchup_window_s) && body.catchup_window_s >= 0 && body.catchup_window_s <= MAX_EVERY_S))
|
|
235
|
+
issues.push({ field: "catchup_window_s", reason: "invalid", message: `catchup_window_s is a whole number of seconds, 0 to ${MAX_EVERY_S} (0: a missed time never fires)` });
|
|
236
|
+
return typeof body.catchup_window_s === "number" ? { catchup_window_s: body.catchup_window_s } : {};
|
|
237
|
+
}
|
|
238
|
+
const WRITABLE = ["name", "enabled", "source", "target", "catchup_window_s"];
|
|
239
|
+
/** A trigger as triggers.json keeps it, whole: what the engine reads of it is there, of its type. */
|
|
240
|
+
function wellFormed(t) {
|
|
241
|
+
if (!isObject(t) || typeof t.id !== "string" || typeof t.name !== "string" || typeof t.enabled !== "boolean" || typeof t.created_at !== "string" || typeof t.updated_at !== "string")
|
|
242
|
+
return false;
|
|
243
|
+
if (!(t.next_at === null || instantOf(t.next_at) !== undefined) || !(t.last_run_id === undefined || typeof t.last_run_id === "string"))
|
|
244
|
+
return false;
|
|
245
|
+
if (!(t.catchup_window_s === undefined || Number.isSafeInteger(t.catchup_window_s)) || !(t.failures_in_a_row === undefined || Number.isSafeInteger(t.failures_in_a_row)) || !(t.disabled === undefined || t.disabled === null || isObject(t.disabled)))
|
|
246
|
+
return false;
|
|
247
|
+
const { source, target } = t;
|
|
248
|
+
if (!isObject(source) || !(source.kind === "webhook" || source.kind === "schedule"))
|
|
249
|
+
return false;
|
|
250
|
+
const timed = source.kind === "webhook" || (typeof source.cron === "string" ? typeof source.timezone === "string" : source.at !== undefined ? instantOf(source.at) !== undefined : Number.isSafeInteger(source.every_s) && instantOf(source.start_at) !== undefined);
|
|
251
|
+
const aimed = isObject(target) && isObject(target.input) && (target.kind === "message_run" ? typeof target.run_id === "string" : target.kind === "start_run" && typeof target.agent_id === "string" && (target.max_cost_usd === undefined || typeof target.max_cost_usd === "number"));
|
|
252
|
+
if (!timed || !aimed)
|
|
253
|
+
return false;
|
|
254
|
+
const firing = (f) => isObject(f) && typeof f.key === "string" && FIRING_STATUSES.includes(f.status) && (f.by === "schedule" || f.by === "manual" || f.by === "webhook") && instantOf(f.nominal_at) !== undefined && typeof f.at === "string";
|
|
255
|
+
const list = (value) => value === undefined || (Array.isArray(value) && value.every(firing));
|
|
256
|
+
return Array.isArray(t.firings) && t.firings.every(firing) && list(t.kept_firings) && list(t.run_now_kept);
|
|
257
|
+
}
|
|
258
|
+
export class Triggers {
|
|
259
|
+
deps;
|
|
260
|
+
file;
|
|
261
|
+
clock;
|
|
262
|
+
triggers = [];
|
|
263
|
+
/** Why triggers.json does not read: nothing fires and nothing is written over it until it does. */
|
|
264
|
+
unreadable;
|
|
265
|
+
timer;
|
|
266
|
+
/** The firings in their turn, queued or being driven, by key, with that turn: a firing is asked for once at a time,
|
|
267
|
+
* and the timer arms for none of them until its turn ends. */
|
|
268
|
+
driving = new Map();
|
|
269
|
+
/** Due firings whose last write failed, by key, and when to drive them again: on disk they may hold no retry time. */
|
|
270
|
+
rewrite = new Map();
|
|
271
|
+
/** Each trigger's firings, driven one after another in the order asked: a firing's overlap check reads what the one
|
|
272
|
+
* before it settled to (a firing a crash left due settles to its run before the next start's own is checked). */
|
|
273
|
+
turns = new Map();
|
|
274
|
+
closed = false;
|
|
275
|
+
constructor(data, deps) {
|
|
276
|
+
this.deps = deps;
|
|
277
|
+
this.file = join(data, TRIGGERS_FILE);
|
|
278
|
+
this.clock = deps.clock ?? REAL_CLOCK;
|
|
279
|
+
let text;
|
|
280
|
+
try {
|
|
281
|
+
text = readFileSync(this.file, "utf8");
|
|
282
|
+
}
|
|
283
|
+
catch (error) {
|
|
284
|
+
if (error.code !== "ENOENT")
|
|
285
|
+
this.unreadable = error.message;
|
|
286
|
+
}
|
|
287
|
+
if (text === undefined)
|
|
288
|
+
return;
|
|
289
|
+
try {
|
|
290
|
+
const doc = JSON.parse(text);
|
|
291
|
+
if (!isObject(doc) || doc.v !== 1 || !Array.isArray(doc.triggers))
|
|
292
|
+
throw new Error("not a triggers file of version 1");
|
|
293
|
+
const bad = doc.triggers.findIndex((t) => !wellFormed(t));
|
|
294
|
+
if (bad >= 0)
|
|
295
|
+
throw new Error(`its trigger at ${bad} is not one this server reads`);
|
|
296
|
+
this.triggers = doc.triggers;
|
|
297
|
+
for (const t of this.triggers) {
|
|
298
|
+
if (t.run_now_kept)
|
|
299
|
+
t.kept_firings = [...(t.kept_firings ?? []), ...t.run_now_kept];
|
|
300
|
+
delete t.run_now_kept;
|
|
301
|
+
}
|
|
302
|
+
// A trigger an earlier server wrote before trigger.failed existed has no failures_in_a_row: its failures were never
|
|
303
|
+
// to be told, so a first start that tells them does not send them late. The next write keeps the mark.
|
|
304
|
+
for (const t of this.triggers)
|
|
305
|
+
if (t.failures_in_a_row === undefined)
|
|
306
|
+
for (const f of t.firings)
|
|
307
|
+
if (f.status === "failed")
|
|
308
|
+
f.notified = true;
|
|
309
|
+
}
|
|
310
|
+
catch (error) {
|
|
311
|
+
this.unreadable = error.message;
|
|
312
|
+
}
|
|
313
|
+
if (this.unreadable)
|
|
314
|
+
deps.say({ condition: "triggers_unreadable", file: this.file, error: this.unreadable });
|
|
315
|
+
}
|
|
316
|
+
/** At the server's start: every firing an earlier server left due driven again (its origin key makes a run
|
|
317
|
+
* it already started the same run), the times missed while it was down recorded, the timer armed, and each failure's
|
|
318
|
+
* trigger.failed queued that is not yet. */
|
|
319
|
+
start() {
|
|
320
|
+
this.offUnreadable(this.triggers.filter((t) => t.enabled && sourceProblem(t.source)), this.clock.now());
|
|
321
|
+
// A trigger.failed an earlier server wrote the firing of but never queued: queued before the first tick records
|
|
322
|
+
// anything, so no trim reaches it first.
|
|
323
|
+
for (const t of this.unreadable ? [] : this.triggers)
|
|
324
|
+
for (const f of t.firings)
|
|
325
|
+
if (unmarked(f))
|
|
326
|
+
this.notifyFailed(t.id, f.key);
|
|
327
|
+
this.tick();
|
|
328
|
+
this.arm();
|
|
329
|
+
}
|
|
330
|
+
close() {
|
|
331
|
+
this.closed = true;
|
|
332
|
+
this.timer?.clear();
|
|
333
|
+
this.timer = undefined;
|
|
334
|
+
}
|
|
335
|
+
list() {
|
|
336
|
+
return { triggers: this.readable().map((t) => this.view(t)) };
|
|
337
|
+
}
|
|
338
|
+
get(id) {
|
|
339
|
+
return this.view(this.need(id));
|
|
340
|
+
}
|
|
341
|
+
firings(id) {
|
|
342
|
+
return { firings: [...this.need(id).firings].reverse().map(firingView) };
|
|
343
|
+
}
|
|
344
|
+
async create(body) {
|
|
345
|
+
this.readable();
|
|
346
|
+
const now = this.clock.now();
|
|
347
|
+
const issues = unknownFields(body, WRITABLE);
|
|
348
|
+
const source = sourceOf(body.source, now, issues);
|
|
349
|
+
const target = targetOf(body.target, issues);
|
|
350
|
+
const settings = settingsOf(body, issues);
|
|
351
|
+
if (body.name !== undefined && !(typeof body.name === "string" && body.name.trim() && body.name.length <= MAX_NAME))
|
|
352
|
+
issues.push({ field: "name", reason: "invalid", message: `name is a string of 1 to ${MAX_NAME} characters` });
|
|
353
|
+
if (body.enabled !== undefined && typeof body.enabled !== "boolean")
|
|
354
|
+
issues.push({ field: "enabled", reason: "wrong_type", message: "enabled is true or false" });
|
|
355
|
+
// Checked as its runs are given it: the input, then the line saying what fired it (a name the trigger may yet take).
|
|
356
|
+
if (target)
|
|
357
|
+
issues.push(...(await this.deps.targetIssues(given(typeof body.name === "string" ? body.name.trim() : `trg_${"0".repeat(24)}`, source, target, now))));
|
|
358
|
+
if (issues.length || !source || !target)
|
|
359
|
+
throw invalid(issues);
|
|
360
|
+
const id = `trg_${randomBytes(12).toString("hex")}`;
|
|
361
|
+
const enabled = body.enabled !== false;
|
|
362
|
+
const trigger = { id, name: typeof body.name === "string" ? body.name.trim() : id, enabled, source, target, catchup_window_s: settings.catchup_window_s ?? CATCHUP_WINDOW_S, failures_in_a_row: 0, disabled: null, created_at: iso(now), updated_at: iso(now), next_at: enabled ? nextIso(source, now) : null, firings: [] };
|
|
363
|
+
// A webhook trigger's secret is kept before the trigger is: one that cannot be kept (no seal key) makes none.
|
|
364
|
+
const secret = source.kind === "webhook" ? this.deps.secrets.mint(id) : undefined;
|
|
365
|
+
this.commit(() => void this.triggers.push(trigger));
|
|
366
|
+
this.arm();
|
|
367
|
+
return { ...this.view(trigger), ...(secret ? { secret } : {}) };
|
|
368
|
+
}
|
|
369
|
+
/** A webhook trigger's new secret, shown this once; the old one signs nothing from now on. */
|
|
370
|
+
rotate(id) {
|
|
371
|
+
const trigger = this.need(id);
|
|
372
|
+
if (trigger.source.kind !== "webhook")
|
|
373
|
+
throw invalid([{ field: "source.kind", reason: "not_allowed", message: "Only a webhook trigger has a secret." }]);
|
|
374
|
+
return { secret: this.deps.secrets.mint(id) };
|
|
375
|
+
}
|
|
376
|
+
/** Whether `id` is a webhook trigger that is on: the one a signed request to /v2/hooks/{id} may fire. */
|
|
377
|
+
hookable(id) {
|
|
378
|
+
const trigger = this.unreadable ? undefined : this.triggers.find((t) => t.id === id);
|
|
379
|
+
return trigger?.source.kind === "webhook" && trigger.enabled;
|
|
380
|
+
}
|
|
381
|
+
/** A signed request to /v2/hooks/{id} (server.ts checked it): its firing, keyed by its `webhook-id`, recorded due in
|
|
382
|
+
* one write and driven after the answer. `created` false: that webhook-id's firing, as it stands. */
|
|
383
|
+
receive(id, webhookId, payload) {
|
|
384
|
+
const trigger = this.need(id);
|
|
385
|
+
const key = firingKey("webhook", id, webhookId);
|
|
386
|
+
const known = this.known(trigger, key);
|
|
387
|
+
if (known)
|
|
388
|
+
return { created: false, firing: firingView(known) };
|
|
389
|
+
this.roomFor(trigger);
|
|
390
|
+
const now = this.clock.now();
|
|
391
|
+
const firing = { key, by: "webhook", nominal_at: second(now), status: "due", at: iso(now), payload: cut(payload) };
|
|
392
|
+
this.commit(() => this.record(trigger, firing));
|
|
393
|
+
void this.inTurn(id, key);
|
|
394
|
+
return { created: true, firing: firingView(firing) };
|
|
395
|
+
}
|
|
396
|
+
/** PATCH: any of name, enabled, source, target and catchup_window_s. Enabled again, or its source changed, a trigger goes on from now: a
|
|
397
|
+
* paused range is skipped, never caught up. Only the fields named change, applied to the trigger as it stands once
|
|
398
|
+
* the target's check is done: an edit made meanwhile keeps its own. */
|
|
399
|
+
async update(id, body) {
|
|
400
|
+
const was = this.need(id);
|
|
401
|
+
const issues = unknownFields(body, WRITABLE);
|
|
402
|
+
const source = body.source === undefined ? undefined : sourceOf(body.source, this.clock.now(), issues);
|
|
403
|
+
const target = body.target === undefined ? undefined : targetOf(body.target, issues);
|
|
404
|
+
const settings = settingsOf(body, issues);
|
|
405
|
+
if (body.name !== undefined && !(typeof body.name === "string" && body.name.trim() && body.name.length <= MAX_NAME))
|
|
406
|
+
issues.push({ field: "name", reason: "invalid", message: `name is a string of 1 to ${MAX_NAME} characters` });
|
|
407
|
+
if (body.enabled !== undefined && typeof body.enabled !== "boolean")
|
|
408
|
+
issues.push({ field: "enabled", reason: "wrong_type", message: "enabled is true or false" });
|
|
409
|
+
if (target)
|
|
410
|
+
issues.push(...(await this.deps.targetIssues(given(typeof body.name === "string" ? body.name.trim() : was.name, source ?? was.source, target, this.clock.now()))));
|
|
411
|
+
if (issues.length || (body.source !== undefined && !source) || (body.target !== undefined && !target))
|
|
412
|
+
throw invalid(issues);
|
|
413
|
+
const trigger = this.need(id);
|
|
414
|
+
if (source && source.kind !== trigger.source.kind)
|
|
415
|
+
throw invalid([{ field: "source.kind", reason: "not_allowed", message: "A trigger's source kind is fixed: make a new trigger for another." }]);
|
|
416
|
+
const now = this.clock.now();
|
|
417
|
+
const enabled = typeof body.enabled === "boolean" ? body.enabled : trigger.enabled;
|
|
418
|
+
const problem = enabled && !source ? sourceProblem(trigger.source) : undefined;
|
|
419
|
+
if (problem)
|
|
420
|
+
throw invalid([{ field: "source", reason: "invalid", message: `This schedule no longer reads (${problem}): give it a new source.` }]);
|
|
421
|
+
const next = !enabled ? null : source || !trigger.enabled ? nextIso(source ?? trigger.source, now) : trigger.next_at;
|
|
422
|
+
if (enabled && next === null && trigger.source.kind === "schedule")
|
|
423
|
+
throw invalid([{ field: "enabled", reason: "invalid", message: "This schedule has no time left to fire at: give it a new source." }]);
|
|
424
|
+
// On again, a trigger starts a new streak: a failure streak that turned it off is behind it.
|
|
425
|
+
const again = enabled && !trigger.enabled ? { failures_in_a_row: 0, disabled: null } : {};
|
|
426
|
+
this.commit(() => Object.assign(trigger, { ...(typeof body.name === "string" ? { name: body.name.trim() } : {}), ...(source ? { source } : {}), ...(target ? { target } : {}), ...settings, ...again, enabled, updated_at: iso(now), next_at: next }));
|
|
427
|
+
this.arm();
|
|
428
|
+
return this.view(trigger);
|
|
429
|
+
}
|
|
430
|
+
remove(id) {
|
|
431
|
+
const trigger = this.need(id);
|
|
432
|
+
this.commit(() => void (this.triggers = this.triggers.filter((t) => t !== trigger)));
|
|
433
|
+
if (trigger.source.kind === "webhook")
|
|
434
|
+
this.deps.secrets.remove(id);
|
|
435
|
+
this.arm();
|
|
436
|
+
}
|
|
437
|
+
/** Run now: one firing per Idempotency-Key, driven before the answer. `created` false: the key's firing, as it stands. */
|
|
438
|
+
async fire(id, idempotencyKey) {
|
|
439
|
+
const trigger = this.need(id);
|
|
440
|
+
const key = firingKey("manual", id, idempotencyKey);
|
|
441
|
+
const known = this.known(trigger, key);
|
|
442
|
+
if (known)
|
|
443
|
+
return { created: false, firing: firingView(known) };
|
|
444
|
+
this.roomFor(trigger);
|
|
445
|
+
const now = this.clock.now();
|
|
446
|
+
const firing = { key, by: "manual", nominal_at: second(now), status: "due", at: iso(now) };
|
|
447
|
+
this.commit(() => this.record(trigger, firing));
|
|
448
|
+
await this.inTurn(id, key);
|
|
449
|
+
return { created: true, firing: firingView(this.find(id, key)?.firing ?? firing) };
|
|
450
|
+
}
|
|
451
|
+
// ---- the timer and the firings --------------------------------------------------------------------------------------
|
|
452
|
+
/** Every enabled trigger whose next time has come: its firing recorded and its next time moved on, in one write; then
|
|
453
|
+
* each due firing whose time has come driven, and the timer armed again. */
|
|
454
|
+
tick() {
|
|
455
|
+
this.timer = undefined;
|
|
456
|
+
if (this.closed || this.unreadable)
|
|
457
|
+
return;
|
|
458
|
+
const now = this.clock.now();
|
|
459
|
+
const due = this.triggers.filter((t) => t.enabled && t.next_at !== null && Date.parse(t.next_at) <= now);
|
|
460
|
+
if (due.length) {
|
|
461
|
+
// One whose source no longer reads is turned off alone, before the write, so it neither stalls the others nor
|
|
462
|
+
// reads as a write that failed.
|
|
463
|
+
const unreadable = due.filter((t) => sourceProblem(t.source));
|
|
464
|
+
if (!this.offUnreadable(unreadable, now)) {
|
|
465
|
+
this.timer = this.clock.arm(() => this.tick(), WRITE_RETRY_MS);
|
|
466
|
+
return;
|
|
467
|
+
}
|
|
468
|
+
try {
|
|
469
|
+
this.commit(() => { for (const trigger of due)
|
|
470
|
+
if (!unreadable.includes(trigger))
|
|
471
|
+
this.advance(trigger, now); });
|
|
472
|
+
}
|
|
473
|
+
catch (error) {
|
|
474
|
+
this.deps.say({ condition: "triggers_unwritable", file: this.file, error: error.code ?? error.message });
|
|
475
|
+
this.timer = this.clock.arm(() => this.tick(), WRITE_RETRY_MS);
|
|
476
|
+
return;
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
const drive = this.triggers.flatMap((t) => t.firings.filter((f) => f.status === "due" && ((!f.retry_at && !this.rewrite.has(f.key)) || this.dueAt(f) <= now)).map((f) => [t.id, f.key]));
|
|
480
|
+
for (const [, key] of drive)
|
|
481
|
+
this.rewrite.delete(key);
|
|
482
|
+
const tell = this.triggers.flatMap((t) => t.firings.filter((f) => unmarked(f) && this.dueAt(f) <= now).map((f) => [t.id, f.key]));
|
|
483
|
+
for (const [id, key] of tell) {
|
|
484
|
+
this.rewrite.delete(key);
|
|
485
|
+
this.notifyFailed(id, key);
|
|
486
|
+
}
|
|
487
|
+
this.arm();
|
|
488
|
+
for (const [id, key] of drive)
|
|
489
|
+
void this.inTurn(id, key);
|
|
490
|
+
}
|
|
491
|
+
/** `key`'s firing driven after every firing of its trigger asked before it. */
|
|
492
|
+
inTurn(triggerId, key) {
|
|
493
|
+
const known = this.driving.get(key);
|
|
494
|
+
if (known)
|
|
495
|
+
return known;
|
|
496
|
+
const turn = (this.turns.get(triggerId) ?? Promise.resolve()).then(() => this.drive(triggerId, key));
|
|
497
|
+
this.turns.set(triggerId, turn);
|
|
498
|
+
this.driving.set(key, turn);
|
|
499
|
+
void turn.finally(() => {
|
|
500
|
+
this.driving.delete(key);
|
|
501
|
+
if (this.turns.get(triggerId) === turn)
|
|
502
|
+
this.turns.delete(triggerId);
|
|
503
|
+
// A firing still due after its turn (a retry) is armed for again.
|
|
504
|
+
this.arm();
|
|
505
|
+
});
|
|
506
|
+
return turn;
|
|
507
|
+
}
|
|
508
|
+
/** Each of `triggers` turned off, with why its source no longer reads, in one write, and said. False when the write
|
|
509
|
+
* failed, which is said too: the caller tries again after WRITE_RETRY_MS. */
|
|
510
|
+
offUnreadable(triggers, now) {
|
|
511
|
+
if (!triggers.length)
|
|
512
|
+
return true;
|
|
513
|
+
const why = new Map(triggers.map((t) => [t, sourceProblem(t.source)]));
|
|
514
|
+
try {
|
|
515
|
+
this.commit(() => {
|
|
516
|
+
for (const [t, detail] of why)
|
|
517
|
+
Object.assign(t, { enabled: false, next_at: null, disabled: { at: iso(now), reason: "source_unreadable", detail } });
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
catch (error) {
|
|
521
|
+
this.deps.say({ condition: "triggers_unwritable", file: this.file, error: error.code ?? error.message });
|
|
522
|
+
return false;
|
|
523
|
+
}
|
|
524
|
+
for (const [t, detail] of why)
|
|
525
|
+
this.deps.say({ condition: "trigger_source_unreadable", trigger: t.id, error: detail });
|
|
526
|
+
return true;
|
|
527
|
+
}
|
|
528
|
+
/** Records `trigger`'s firings up to now and moves its next time on from the last nominal one. Of the times that have
|
|
529
|
+
* come, the latest fires (on time, or late within catchup_window_s: a catch-up, under its own nominal key), and every
|
|
530
|
+
* other is one `missed` row with their count. A one-time schedule, or one that never fires again, is turned off. */
|
|
531
|
+
advance(trigger, now) {
|
|
532
|
+
const { source } = trigger;
|
|
533
|
+
// A webhook trigger has no next time, so it is never here.
|
|
534
|
+
if (source.kind === "webhook")
|
|
535
|
+
return;
|
|
536
|
+
const cron = "cron" in source ? cronOf(source) : undefined;
|
|
537
|
+
const windowMs = settled(trigger).catchup_window_s * 1000;
|
|
538
|
+
const first = Date.parse(trigger.next_at);
|
|
539
|
+
const last = latestBy(source, first, now, cron);
|
|
540
|
+
// The times from first to last: an interval's counted on its grid, a cron line's walked, at most MISSED_COUNTED.
|
|
541
|
+
let count = 1;
|
|
542
|
+
let capped = false;
|
|
543
|
+
if ("every_s" in source)
|
|
544
|
+
count += (last - first) / (source.every_s * 1000);
|
|
545
|
+
else
|
|
546
|
+
for (let at = first; at < last; count++) {
|
|
547
|
+
if (count === MISSED_COUNTED) {
|
|
548
|
+
capped = true;
|
|
549
|
+
break;
|
|
550
|
+
}
|
|
551
|
+
at = nextAfter(source, at, cron) ?? last;
|
|
552
|
+
}
|
|
553
|
+
const late = now - last;
|
|
554
|
+
const fires = late <= LATE_MS || late <= windowMs;
|
|
555
|
+
// Capped, the times counted are all before the last: every one of them was missed, and more besides.
|
|
556
|
+
const missed = capped || !fires ? count : count - 1;
|
|
557
|
+
// Every time reckoned before anything is written: a source that throws leaves the trigger as it was.
|
|
558
|
+
const next = nextAfter(source, last, cron);
|
|
559
|
+
if (missed > 0)
|
|
560
|
+
this.record(trigger, { key: firingKey("schedule", trigger.id, `missed\n${second(first)}`), by: "schedule", nominal_at: second(first), status: "missed", at: iso(now), count: missed, reason: `The server was down or its timer late: ${missed === 1 && !capped ? "this time was" : `${missed}${capped ? " or more" : ""} times from this one were`} not fired.` });
|
|
561
|
+
// A message_run firing has no overlap check, so a run that stays busy would hold one more due firing each time.
|
|
562
|
+
const full = dueOf(trigger) >= DUE_KEPT ? { status: "skipped", reason: `${DUE_KEPT} earlier firings are still waiting to reach the run.` } : { status: "due" };
|
|
563
|
+
if (fires)
|
|
564
|
+
this.record(trigger, { key: firingKey("schedule", trigger.id, second(last)), by: "schedule", nominal_at: second(last), ...full, at: iso(now), ...(late > LATE_MS ? { catch_up: true } : {}) });
|
|
565
|
+
trigger.next_at = next === null ? null : iso(next);
|
|
566
|
+
if (next === null)
|
|
567
|
+
trigger.enabled = false;
|
|
568
|
+
}
|
|
569
|
+
/** A firing taken from due to its end: skipped when its trigger's last run is active, else its run started. A full
|
|
570
|
+
* server (429), or a last run that could not be read, keeps it due and tries again later. Nothing it holds across a wait is an object: the trigger may be edited or
|
|
571
|
+
* deleted meanwhile, so each step finds it again by id and key. */
|
|
572
|
+
async drive(triggerId, key) {
|
|
573
|
+
try {
|
|
574
|
+
const found = this.find(triggerId, key);
|
|
575
|
+
if (!found || found.firing.status !== "due")
|
|
576
|
+
return;
|
|
577
|
+
// Its run already started (the store has its key) is its run, whatever runs now.
|
|
578
|
+
const prior = await this.deps.runOf(key).then((run) => ({ run }), (error) => ({ retry: error }));
|
|
579
|
+
if (this.closed)
|
|
580
|
+
return;
|
|
581
|
+
if ("retry" in prior)
|
|
582
|
+
return this.retry(triggerId, key, prior.retry);
|
|
583
|
+
// A key stays bound to its run: one lost at setup is this firing's failure, never fired again. The next firing
|
|
584
|
+
// goes ahead, and a run now is the person's retry.
|
|
585
|
+
if (prior.run?.setup_lost)
|
|
586
|
+
return this.failed(triggerId, key, { code: "run_failed", message: LOST_AT_SETUP }, { run_id: prior.run.run_id, reason: LOST_AT_SETUP });
|
|
587
|
+
if (prior.run)
|
|
588
|
+
return this.started(triggerId, key, prior.run.run_id);
|
|
589
|
+
if (found.trigger.target.kind === "message_run")
|
|
590
|
+
return await this.send(triggerId, key);
|
|
591
|
+
const busy = await this.busy(found.trigger, found.firing).catch((error) => ({ retry: error }));
|
|
592
|
+
if (this.closed)
|
|
593
|
+
return;
|
|
594
|
+
if (typeof busy === "string")
|
|
595
|
+
return this.settle(triggerId, key, { status: "skipped", reason: busy });
|
|
596
|
+
if (busy)
|
|
597
|
+
return this.retry(triggerId, key, busy.retry);
|
|
598
|
+
const now = this.find(triggerId, key);
|
|
599
|
+
if (!now)
|
|
600
|
+
return;
|
|
601
|
+
// The target as it is now: an edit during the overlap check may have made it a message.
|
|
602
|
+
if (now.trigger.target.kind === "message_run")
|
|
603
|
+
return await this.send(triggerId, key);
|
|
604
|
+
let started;
|
|
605
|
+
try {
|
|
606
|
+
started = await this.deps.start(now.trigger.target, inputOf(now.trigger, now.firing), { id: triggerId, firing_key: key });
|
|
607
|
+
}
|
|
608
|
+
catch (error) {
|
|
609
|
+
// Stopping, the start may have been cut by the close: the firing stays due for the next start, whose origin key
|
|
610
|
+
// finds a run this one made.
|
|
611
|
+
if (this.closed)
|
|
612
|
+
return;
|
|
613
|
+
if (error instanceof ApiError && ["rate_limited", "home_busy", "unavailable"].includes(error.code))
|
|
614
|
+
return this.retry(triggerId, key, error);
|
|
615
|
+
return this.failed(triggerId, key, { code: error instanceof ApiError ? error.code : "internal", message: error.message });
|
|
616
|
+
}
|
|
617
|
+
if (this.closed)
|
|
618
|
+
return;
|
|
619
|
+
this.started(triggerId, key, started.run_id);
|
|
620
|
+
}
|
|
621
|
+
catch (error) {
|
|
622
|
+
// A throw none of the answers above handles: whatever it left (still due, most likely) is driven again after the
|
|
623
|
+
// write retry's wait, never at once (its retry time may have passed).
|
|
624
|
+
this.rewrite.set(key, this.clock.now() + WRITE_RETRY_MS);
|
|
625
|
+
this.deps.say({ condition: "trigger_firing_failed", trigger: triggerId, firing: key, error: error.message });
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
/** A message_run firing: its message to the target's run, under its key. No overlap: the run's own state picks how the
|
|
629
|
+
* message lands (steer, answer or follow-up). */
|
|
630
|
+
async send(triggerId, key) {
|
|
631
|
+
const found = this.find(triggerId, key);
|
|
632
|
+
if (!found || found.trigger.target.kind !== "message_run")
|
|
633
|
+
return;
|
|
634
|
+
const { target } = found.trigger;
|
|
635
|
+
let skipped;
|
|
636
|
+
try {
|
|
637
|
+
skipped = (await this.deps.message(target, inputOf(found.trigger, found.firing), key))?.skipped;
|
|
638
|
+
}
|
|
639
|
+
catch (error) {
|
|
640
|
+
if (this.closed)
|
|
641
|
+
return;
|
|
642
|
+
if (error instanceof ApiError && ["rate_limited", "home_busy", "unavailable"].includes(error.code))
|
|
643
|
+
return this.retry(triggerId, key, error);
|
|
644
|
+
return this.failed(triggerId, key, { code: error instanceof ApiError ? error.code : "internal", message: error.message }, { run_id: target.run_id });
|
|
645
|
+
}
|
|
646
|
+
if (this.closed)
|
|
647
|
+
return;
|
|
648
|
+
if (skipped)
|
|
649
|
+
return this.settle(triggerId, key, { status: "skipped", reason: skipped });
|
|
650
|
+
this.settle(triggerId, key, { status: "sent", run_id: target.run_id }, (t) => void (t.failures_in_a_row = 0));
|
|
651
|
+
}
|
|
652
|
+
find(triggerId, key) {
|
|
653
|
+
const trigger = this.triggers.find((t) => t.id === triggerId);
|
|
654
|
+
const firing = trigger?.firings.find((f) => f.key === key);
|
|
655
|
+
return trigger && firing ? { trigger, firing } : undefined;
|
|
656
|
+
}
|
|
657
|
+
/** Why `firing` is skipped (overlap: skip), if it is: an earlier firing still due, or the last run still active. */
|
|
658
|
+
async busy(trigger, firing) {
|
|
659
|
+
const earlier = trigger.firings.slice(0, trigger.firings.indexOf(firing));
|
|
660
|
+
if (earlier.some((f) => f.status === "due"))
|
|
661
|
+
return "An earlier firing is still waiting to start its run.";
|
|
662
|
+
const last = trigger.last_run_id;
|
|
663
|
+
if (!last)
|
|
664
|
+
return undefined;
|
|
665
|
+
const status = await this.deps.statusOf(last);
|
|
666
|
+
if (status === null || ENDED.has(status))
|
|
667
|
+
return undefined;
|
|
668
|
+
return status === "input_required" ? `The last run, ${last}, is waiting for a person.` : `The last run, ${last}, is still ${status}.`;
|
|
669
|
+
}
|
|
670
|
+
retry(triggerId, key, error) {
|
|
671
|
+
// A run that is working refused a message that may not answer it: no failed try, and looked at again soon, so the
|
|
672
|
+
// message lands within WORKING_RETRY_MS of the turn's end.
|
|
673
|
+
if (error instanceof ApiError && error.extra.details?.reason === "working") {
|
|
674
|
+
return this.settle(triggerId, key, { status: "due", retry_at: iso(this.clock.now() + WORKING_RETRY_MS), reason: error.message });
|
|
675
|
+
}
|
|
676
|
+
const attempts = (this.find(triggerId, key)?.firing.attempts ?? 0) + 1;
|
|
677
|
+
const wait = Math.max(RETRY_MS[Math.min(attempts, RETRY_MS.length) - 1], error instanceof ApiError ? (error.extra.retry_after_ms ?? 0) : 0);
|
|
678
|
+
this.settle(triggerId, key, { status: "due", attempts, retry_at: iso(this.clock.now() + wait), reason: error.message });
|
|
679
|
+
}
|
|
680
|
+
started(triggerId, key, runId) {
|
|
681
|
+
this.settle(triggerId, key, { status: "started", run_id: runId }, (t) => void (t.failures_in_a_row = 0));
|
|
682
|
+
this.deps.say({ condition: "trigger_fired", trigger: triggerId, firing: key, run: runId });
|
|
683
|
+
}
|
|
684
|
+
/** A failed firing: one more in its trigger's streak, the trigger turned off at FAILURES_TO_PAUSE, and trigger.failed
|
|
685
|
+
* queued (after the firing is written: a start finds one not yet queued and queues it, under the same webhook-id). */
|
|
686
|
+
failed(triggerId, key, error, also = {}) {
|
|
687
|
+
this.settle(triggerId, key, { status: "failed", error, ...also }, (t, firing) => {
|
|
688
|
+
t.failures_in_a_row = settled(t).failures_in_a_row + 1;
|
|
689
|
+
if (t.failures_in_a_row < FAILURES_TO_PAUSE || !t.enabled)
|
|
690
|
+
return;
|
|
691
|
+
Object.assign(t, { enabled: false, next_at: null, disabled: { at: iso(this.clock.now()), reason: "auto_paused" } });
|
|
692
|
+
firing.paused = true;
|
|
693
|
+
});
|
|
694
|
+
this.notifyFailed(triggerId, key);
|
|
695
|
+
}
|
|
696
|
+
notifyFailed(triggerId, key) {
|
|
697
|
+
const found = this.find(triggerId, key);
|
|
698
|
+
if (!found || found.firing.status !== "failed" || found.firing.notified)
|
|
699
|
+
return;
|
|
700
|
+
const { trigger, firing } = found;
|
|
701
|
+
const told = this.deps.notify({ trigger_id: trigger.id, name: trigger.name, firing_key: key, nominal_at: firing.nominal_at, error: firing.error, auto_paused: firing.paused === true }, key);
|
|
702
|
+
// A mark that does not land (the outbox's write failed, or this file's: settle) is tried again soon while the server
|
|
703
|
+
// runs (tick), under the same key, which the outbox holds once: a restart then finds it marked.
|
|
704
|
+
if (told === "queued" || told === "off")
|
|
705
|
+
this.settle(triggerId, key, { notified: true });
|
|
706
|
+
else if (told === "unsaved")
|
|
707
|
+
this.rewrite.set(key, this.clock.now() + WRITE_RETRY_MS);
|
|
708
|
+
}
|
|
709
|
+
/** The firing's new state, written with `also` done to its trigger; one whose trigger was deleted meanwhile is gone with it. */
|
|
710
|
+
settle(triggerId, key, change, also) {
|
|
711
|
+
try {
|
|
712
|
+
this.commit(() => {
|
|
713
|
+
const found = this.find(triggerId, key);
|
|
714
|
+
if (!found)
|
|
715
|
+
return;
|
|
716
|
+
// Out of due, a firing keeps no retry, nor the reason the last try gave.
|
|
717
|
+
Object.assign(found.firing, change.status === "due" || change.status === undefined ? change : { reason: undefined, attempts: undefined, retry_at: undefined, ...change });
|
|
718
|
+
if (change.status !== undefined && change.status !== "due")
|
|
719
|
+
delete found.firing.payload;
|
|
720
|
+
// Run ids are UUIDv7s, which sort by when the run started: a firing that finds an older run (a run now's key
|
|
721
|
+
// retried past its day) never takes the place of a later one.
|
|
722
|
+
const last = found.trigger.last_run_id;
|
|
723
|
+
if (change.run_id && found.trigger.target.kind === "start_run" && !(last && last > change.run_id))
|
|
724
|
+
found.trigger.last_run_id = change.run_id;
|
|
725
|
+
also?.(found.trigger, found.firing);
|
|
726
|
+
});
|
|
727
|
+
}
|
|
728
|
+
catch (error) {
|
|
729
|
+
// Left as it was: driven again soon (arm), under the same origin key, and at the next start.
|
|
730
|
+
this.rewrite.set(key, this.clock.now() + WRITE_RETRY_MS);
|
|
731
|
+
this.deps.say({ condition: "triggers_unwritable", file: this.file, error: error.code ?? error.message });
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
record(trigger, firing) {
|
|
735
|
+
if (trigger.firings.some((f) => f.key === firing.key))
|
|
736
|
+
return;
|
|
737
|
+
trigger.firings.push(firing);
|
|
738
|
+
let over = trigger.firings.length - HISTORY_KEPT;
|
|
739
|
+
// Kept past the history: a firing still due, and a failure whose trigger.failed is not queued yet (the outbox's write,
|
|
740
|
+
// or this file's, keeps failing), the newest UNTOLD_KEPT of them; an older one's notice is dropped, and said.
|
|
741
|
+
const untold = new Set(trigger.firings.filter(unmarked).slice(-UNTOLD_KEPT));
|
|
742
|
+
const gone = over > 0 ? trigger.firings.filter((f) => f.status !== "due" && !untold.has(f) && over-- > 0) : [];
|
|
743
|
+
for (const f of gone)
|
|
744
|
+
if (unmarked(f))
|
|
745
|
+
this.deps.say({ condition: "trigger_notice_dropped", trigger: trigger.id, firing: f.key });
|
|
746
|
+
trigger.firings = trigger.firings.filter((f) => !gone.includes(f));
|
|
747
|
+
const kept = [...(trigger.kept_firings ?? []), ...gone.filter((f) => f.by === "manual" || f.by === "webhook")].filter((f) => this.inDay(f)).slice(-KEPT_FIRINGS);
|
|
748
|
+
if (kept.length)
|
|
749
|
+
trigger.kept_firings = kept;
|
|
750
|
+
else
|
|
751
|
+
delete trigger.kept_firings;
|
|
752
|
+
}
|
|
753
|
+
/** A new firing's room: refused (429, retryable, nothing written) while the trigger holds DUE_KEPT firings due. */
|
|
754
|
+
roomFor(trigger) {
|
|
755
|
+
if (dueOf(trigger) < DUE_KEPT)
|
|
756
|
+
return;
|
|
757
|
+
this.deps.say({ condition: "trigger_firings_full", trigger: trigger.id, due: DUE_KEPT });
|
|
758
|
+
throw new ApiError("rate_limited", `${DUE_KEPT} firings are still due for this trigger, waiting on its run; send it again later.`, { retry_after_ms: FULL_RETRY_S * 1000, details: { due: DUE_KEPT } }, { "retry-after": String(FULL_RETRY_S) });
|
|
759
|
+
}
|
|
760
|
+
/** The firing `key` names, in the history or kept for its key's day after it left. */
|
|
761
|
+
known(trigger, key) {
|
|
762
|
+
return trigger.firings.find((f) => f.key === key) ?? trigger.kept_firings?.find((f) => f.key === key && this.inDay(f));
|
|
763
|
+
}
|
|
764
|
+
/** Whether a firing is within its key's day, as an Idempotency-Key answers. */
|
|
765
|
+
inDay(firing) {
|
|
766
|
+
return this.clock.now() - Date.parse(firing.at) <= IDEMPOTENCY_TTL_S * 1000;
|
|
767
|
+
}
|
|
768
|
+
/** The timer, at the soonest next time of an enabled trigger or retry of a due firing. */
|
|
769
|
+
arm() {
|
|
770
|
+
this.timer?.clear();
|
|
771
|
+
this.timer = undefined;
|
|
772
|
+
if (this.closed || this.unreadable)
|
|
773
|
+
return;
|
|
774
|
+
let soonest = Infinity;
|
|
775
|
+
for (const t of this.triggers) {
|
|
776
|
+
if (t.enabled && t.next_at !== null)
|
|
777
|
+
soonest = Math.min(soonest, Date.parse(t.next_at));
|
|
778
|
+
// One being driven arms nothing: its end arms the timer again. A failure whose mark did not land arms its retry.
|
|
779
|
+
for (const f of t.firings)
|
|
780
|
+
if ((f.status === "due" && !this.driving.has(f.key)) || unmarked(f))
|
|
781
|
+
soonest = Math.min(soonest, this.dueAt(f));
|
|
782
|
+
}
|
|
783
|
+
if (soonest !== Infinity)
|
|
784
|
+
this.timer = this.clock.arm(() => this.tick(), Math.max(0, soonest - this.clock.now()));
|
|
785
|
+
}
|
|
786
|
+
/** When a due firing is driven next: after the write retry's wait when its write or its drive failed (that wait wins
|
|
787
|
+
* over a retry time that may have passed), else at its retry; one with neither is driven by whatever recorded it. */
|
|
788
|
+
dueAt(firing) {
|
|
789
|
+
return this.rewrite.get(firing.key) ?? (firing.retry_at ? Date.parse(firing.retry_at) : Infinity);
|
|
790
|
+
}
|
|
791
|
+
/** `change` applied and written whole, or, when the write fails, undone and thrown. Each change, a signed request's
|
|
792
|
+
* firing included, copies and rewrites the whole file and syncs it: one writer (server.lock), and a bounded file. A
|
|
793
|
+
* firing is about 170 bytes of JSON, a due webhook firing's payload at most 16 KiB more, and a trigger keeps at most
|
|
794
|
+
* HISTORY_KEPT (200) in its history and KEPT_FIRINGS (1,000) past it: about 230 KiB a trigger at its fullest, which
|
|
795
|
+
* measured about 3 ms a write (copy, JSON and fsync) on an SSD. Its history runs past HISTORY_KEPT by at most
|
|
796
|
+
* UNTOLD_KEPT (50) failures not yet told and DUE_KEPT (20) due firings, whose payloads add at most 320 KiB. */
|
|
797
|
+
commit(change) {
|
|
798
|
+
if (this.closed)
|
|
799
|
+
throw new ApiError("unavailable", "The server is stopping.");
|
|
800
|
+
const before = structuredClone(this.triggers);
|
|
801
|
+
try {
|
|
802
|
+
const result = change();
|
|
803
|
+
writeDurableSync(this.file, `${JSON.stringify({ v: 1, triggers: this.triggers })}\n`);
|
|
804
|
+
return result;
|
|
805
|
+
}
|
|
806
|
+
catch (error) {
|
|
807
|
+
this.triggers = before;
|
|
808
|
+
throw error;
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
readable() {
|
|
812
|
+
if (this.unreadable)
|
|
813
|
+
throw new ApiError("store_unreadable", `${TRIGGERS_FILE} in the data directory does not read (${this.unreadable}); it is never written over. Fix it or move it away, then restart.`);
|
|
814
|
+
return this.triggers;
|
|
815
|
+
}
|
|
816
|
+
need(id) {
|
|
817
|
+
const trigger = this.readable().find((t) => t.id === id);
|
|
818
|
+
if (!trigger)
|
|
819
|
+
throw new ApiError("not_found", `no trigger ${id}`);
|
|
820
|
+
return trigger;
|
|
821
|
+
}
|
|
822
|
+
view(trigger) {
|
|
823
|
+
const { firings, kept_firings: _, ...rest } = trigger;
|
|
824
|
+
return { ...rest, last_run_id: trigger.last_run_id ?? null, ...settled(trigger), last_firing: firings.length ? firingView(firings.at(-1)) : null };
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
const nextIso = (source, now) => {
|
|
828
|
+
const at = nextAfter(source, now);
|
|
829
|
+
return at === null ? null : iso(at);
|
|
830
|
+
};
|
|
831
|
+
/** A failed firing whose trigger.failed is not marked queued. */
|
|
832
|
+
const unmarked = (firing) => firing.status === "failed" && !firing.notified;
|
|
833
|
+
/** A time a Date holds: past it (about the year 275760) a next time is none. */
|
|
834
|
+
const DATE_MAX_MS = 8.64e15;
|
|
835
|
+
function firingView(firing) {
|
|
836
|
+
return { key: firing.key, by: firing.by, nominal_at: firing.nominal_at, status: firing.status, at: firing.at, run_id: firing.run_id ?? null, reason: firing.reason ?? null, error: firing.error ?? null, ...(firing.count !== undefined ? { count: firing.count } : {}), ...(firing.catch_up ? { catch_up: true } : {}), ...(firing.retry_at ? { attempts: firing.attempts ?? 0, retry_at: firing.retry_at } : {}) };
|
|
837
|
+
}
|
|
838
|
+
/** `target` with its input as a firing of a trigger named `name` would give it to its run: what create and PATCH check. */
|
|
839
|
+
function given(name, source, target, now) {
|
|
840
|
+
const trigger = { name, source: source ?? { kind: "schedule", at: second(now) }, target };
|
|
841
|
+
return { ...target, input: inputOf(trigger, { key: "", by: "manual", nominal_at: second(now), status: "due", at: iso(now) }) };
|
|
842
|
+
}
|
|
843
|
+
/** The run's input: the trigger's, then a webhook's payload marked untrusted, then a line saying what fired it and when,
|
|
844
|
+
* in the trigger's zone. */
|
|
845
|
+
function inputOf(trigger, firing) {
|
|
846
|
+
const when = local(Date.parse(firing.nominal_at), zoneOf(trigger.source));
|
|
847
|
+
const what = trigger.source.kind === "webhook" ? `the webhook trigger "${trigger.name}"` : `the schedule "${trigger.name}"`;
|
|
848
|
+
const line = firing.by === "schedule" ? `(Started by ${what} for ${when}.)` : firing.by === "manual" ? `(Started by hand from ${what} at ${when}.)` : `(From ${what}, received at ${when}.)`;
|
|
849
|
+
// The payload is whatever its sender wrote: an instruction in it is data, and its closing tag cannot end the block.
|
|
850
|
+
const payload = firing.payload === undefined ? "" : `\n\n<trigger-payload source="webhook" untrusted>\n${firing.payload.replaceAll("</trigger-payload", "<\\/trigger-payload")}\n</trigger-payload>`;
|
|
851
|
+
const { input } = trigger.target;
|
|
852
|
+
return typeof input.content === "string" ? { ...input, content: `${input.content}${payload}\n\n${line}` } : input;
|
|
853
|
+
}
|
|
854
|
+
/** `text` cut to PAYLOAD_KEPT_BYTES of UTF-8 at a character's start, and said to be cut. */
|
|
855
|
+
function cut(text) {
|
|
856
|
+
const bytes = Buffer.from(text, "utf8");
|
|
857
|
+
if (bytes.length <= PAYLOAD_KEPT_BYTES)
|
|
858
|
+
return text;
|
|
859
|
+
let end = PAYLOAD_KEPT_BYTES;
|
|
860
|
+
while (end > 0 && (bytes[end] & 0xc0) === 0x80)
|
|
861
|
+
end--;
|
|
862
|
+
return `${bytes.subarray(0, end).toString("utf8")}\n[cut: the payload was ${bytes.length} bytes, past ${PAYLOAD_KEPT_BYTES}]`;
|
|
863
|
+
}
|