slack-term 1.57.0 → 1.58.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -2
- package/dist/cli.js +278 -271
- package/package.json +15 -7
- package/ts/ask.ts +41 -0
- package/ts/askPush.ts +21 -17
- package/ts/asyncArgs.ts +21 -0
- package/ts/brand.ts +9 -5
- package/ts/cli.ts +275 -36
- package/ts/profiles.ts +19 -7
- package/ts/slack.ts +124 -11
- package/worker/src/index.ts +27 -0
- package/worker/src/router/admin.ts +80 -0
- package/worker/src/router/core.ts +1222 -0
- package/worker/src/router/do.ts +355 -0
- package/worker/src/router/fetch.ts +76 -0
- package/worker/src/router/intake.ts +82 -0
- package/worker/src/router/wire.ts +401 -0
- package/worker/src/slack.ts +3 -2
- package/worker/README.md +0 -216
|
@@ -0,0 +1,1222 @@
|
|
|
1
|
+
// The Router's state machine (tier 1 of the Slack thread router), as pure logic: no Cloudflare types and no clock of
|
|
2
|
+
// its own, so the CLI suite drives it under bun with bun:sqlite (tests/router-core.test.ts). do.ts adapts the Durable
|
|
3
|
+
// Object's SQLite, transactions and hibernating WebSockets to `Sql`, `Tx` and `Link`, and passes `now` (ms) into
|
|
4
|
+
// every call; nothing in here reads the time itself.
|
|
5
|
+
//
|
|
6
|
+
// What it keeps (SQLite):
|
|
7
|
+
// machines enrolled public keys, liveness as last seen, the last heartbeat (for change detection)
|
|
8
|
+
// lanes the lane directory: lane → machine, cwd (+ lane_seen: each machine's last heartbeat entry per lane)
|
|
9
|
+
// routes labelled rows: (channel, thread_ts | "" = the channel default) → {label → lane address}, cc, options
|
|
10
|
+
// messages routed messages only, with their text until delivery is final, deleted 7 days after intake (q1)
|
|
11
|
+
// deliveries the ledger: one row per (message, label) with its state, machine, attempts, ack token and clock
|
|
12
|
+
// alerts, audit, jobs (job beats), apps (intake liveness), events (Slack event ids, for dedupe)
|
|
13
|
+
//
|
|
14
|
+
// Routing (step 1: labelled rows; there is no rule engine here). A message uses its thread's row (a claim), else the
|
|
15
|
+
// channel default, else it is not routed: nothing is stored. Labels are `<letter><rank>`: a letter is a broadcast
|
|
16
|
+
// group, the digit the failover order inside it; `fb:<letter>` is a group's fallback, `cc:<lane>` an observer.
|
|
17
|
+
//
|
|
18
|
+
// Interpretations of the step-1 contract (the spec text is quoted where it matters):
|
|
19
|
+
// - "All ranks skipped → … the group waits" and "No rank left: the group is exhausted" are read together as: when a
|
|
20
|
+
// pass finds nothing to send, the group is exhausted if somebody holds it (a row in accepted/queued/unknown/read/
|
|
21
|
+
// timeout/shadow) — it stays open, no alert; otherwise it WAITS (one `waiting` row at its lowest retryable rank)
|
|
22
|
+
// as long as some rank may be retried, so a message whose b1 went offline (or answered unreachable) while every
|
|
23
|
+
// other rank was offline is replayed when a machine comes back rather than dropped (q2: "the envelope waits in
|
|
24
|
+
// tier 1"). Only a group with nothing left to retry (every rank declined, or never-again) is exhausted unheld,
|
|
25
|
+
// which opens delivery.undeliverable at once.
|
|
26
|
+
// - A rank that ended skipped/offline/failed may be retried by a later retry pass of a waiting group; declined,
|
|
27
|
+
// cancelled and the never-again states (accepted/queued/unknown/read/timeout/done/shadow) never are.
|
|
28
|
+
// - Waiting groups are retried on a machine's first heartbeat after it authenticates (handshake step 6, which is when
|
|
29
|
+
// its lanes are known), on any heartbeat that changes, and on placement changes, in message order.
|
|
30
|
+
// - `late: true` is set on every deliver whose message is older than 60 s at send time, not only on replays.
|
|
31
|
+
// - A replaced socket does not make its machine offline: the newer socket carries it (its `sent` rows are re-sent
|
|
32
|
+
// after the next first heartbeat, attempt + 1).
|
|
33
|
+
// - A lane placed on a machine that goes offline or stops listing it moves to another online machine that lists
|
|
34
|
+
// it (heartbeats are sent only on change, so waiting for that machine's next heartbeat could wait forever).
|
|
35
|
+
// - Alert `since` is the time the alert entered its current state.
|
|
36
|
+
|
|
37
|
+
import type { IntakeEvent, RoutedMessage } from "./intake.ts";
|
|
38
|
+
import {
|
|
39
|
+
AIP_VERSION, type Ack, type AlertKind, CHANNEL, type Envelope, type JobBeat, LABEL, LANE_ADDRESS, type LaneEntry,
|
|
40
|
+
type LaneStatus, type Mode, NAME, PUBKEY, type Receipt, type Source, type T1Frame, type T2Frame, TS, fromBase64url,
|
|
41
|
+
} from "./wire.ts";
|
|
42
|
+
|
|
43
|
+
// ---- injected seams
|
|
44
|
+
|
|
45
|
+
export type SqlValue = string | number | null;
|
|
46
|
+
export interface SqlCursor<T> {
|
|
47
|
+
toArray(): T[];
|
|
48
|
+
one(): T;
|
|
49
|
+
}
|
|
50
|
+
/** Shaped like a Durable Object's `ctx.storage.sql`. */
|
|
51
|
+
export interface Sql {
|
|
52
|
+
exec<T = Record<string, SqlValue>>(query: string, ...bindings: SqlValue[]): SqlCursor<T>;
|
|
53
|
+
}
|
|
54
|
+
/** Runs `fn` in one SQLite transaction (a Durable Object's `ctx.storage.transactionSync`). */
|
|
55
|
+
export type Tx = <T>(fn: () => T) => T;
|
|
56
|
+
/** The machines' sockets, as the Durable Object sees them. */
|
|
57
|
+
export interface Link {
|
|
58
|
+
/** Authenticated, open sockets: machine → its last sign of life (ms; a frame, or a runtime-answered ping). */
|
|
59
|
+
machines(): { machine: string; lastSeen: number }[];
|
|
60
|
+
/** Send one frame to the machine's socket; false when it has none or the send failed. */
|
|
61
|
+
send(machine: string, frame: T1Frame): boolean;
|
|
62
|
+
close(machine: string, code: number, reason: string): void;
|
|
63
|
+
}
|
|
64
|
+
export interface CoreOptions {
|
|
65
|
+
sql: Sql;
|
|
66
|
+
tx: Tx;
|
|
67
|
+
link: Link;
|
|
68
|
+
/** reported in welcome and /router/health (default shadow); the subrouter acts on it */
|
|
69
|
+
mode?: Mode;
|
|
70
|
+
/** intake.silent is evaluated only between these JST hours (default 8-22) */
|
|
71
|
+
daytime?: { start: number; end: number };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// ---- constants (q4 clocks are the route defaults)
|
|
75
|
+
|
|
76
|
+
/** A machine is online while its last ping or frame is less than this old. */
|
|
77
|
+
export const LIVE_MS = 90_000;
|
|
78
|
+
/** machine.silent: offline for this long. */
|
|
79
|
+
export const SILENT_MS = 180_000;
|
|
80
|
+
/** A deliver whose message is older than this carries late: true. */
|
|
81
|
+
export const LATE_MS = 60_000;
|
|
82
|
+
/** Messages, their ledger rows and Slack event ids are deleted this long after intake (q1). */
|
|
83
|
+
export const RETAIN_MS = 7 * 86_400_000;
|
|
84
|
+
/** A thread route (a claimed "[lane]" root, or one set by hand) with no message for this long is dropped, and audit
|
|
85
|
+
* rows older than this are deleted: otherwise every lane-root post would leave a row forever. Channel routes stay. */
|
|
86
|
+
export const ROUTE_IDLE_MS = 30 * 86_400_000;
|
|
87
|
+
/** intake.silent: an app with no events for this long (JST daytime only). */
|
|
88
|
+
export const INTAKE_SILENT_MS = 6 * 3_600_000;
|
|
89
|
+
/** job.late: no ok beat for this many periods. */
|
|
90
|
+
export const JOB_LATE_PERIODS = 3;
|
|
91
|
+
/** Close code for a socket silent past LIVE_MS (the relay's /ws uses the same one). */
|
|
92
|
+
export const CLOSE_SILENT = 4010;
|
|
93
|
+
export const DEFAULTS = { from: "human", read_s: 120, queue_max_s: 3600, ack_s: 600, offline: "failover" } as const;
|
|
94
|
+
const JST_MS = 9 * 3_600_000;
|
|
95
|
+
const DAY_MS = 86_400_000;
|
|
96
|
+
/** The audit rows GET /router/lanes returns. */
|
|
97
|
+
export const AUDIT_ROWS = 100;
|
|
98
|
+
/** Envelope text above this many characters is cut, so a frame stays under the link's 256 KiB. */
|
|
99
|
+
export const MAX_TEXT_CHARS = 40_000;
|
|
100
|
+
|
|
101
|
+
export const STATES = [
|
|
102
|
+
"waiting", "sent", "accepted", "queued", "unknown", "read", "done", "declined", "failed", "timeout", "offline", "skipped",
|
|
103
|
+
"cancelled", "shadow",
|
|
104
|
+
] as const;
|
|
105
|
+
export type State = (typeof STATES)[number];
|
|
106
|
+
/** the group's current rank, its clock running */
|
|
107
|
+
const ACTIVE: ReadonlySet<string> = new Set(["sent", "accepted", "queued", "unknown", "read"]);
|
|
108
|
+
/** somebody has the message: a group in this state is not undeliverable */
|
|
109
|
+
const HOLDING: ReadonlySet<string> = new Set(["accepted", "queued", "unknown", "read", "timeout", "shadow"]);
|
|
110
|
+
/** never sent again */
|
|
111
|
+
const NEVER_AGAIN: ReadonlySet<string> = new Set(["sent", "accepted", "queued", "unknown", "read", "timeout", "done", "shadow", "declined", "cancelled"]);
|
|
112
|
+
/** still open: a done elsewhere in the group cancels it */
|
|
113
|
+
const CANCELLABLE: ReadonlySet<string> = new Set(["sent", "accepted", "queued", "unknown", "read", "timeout"]);
|
|
114
|
+
/** counted as open deliveries in /router/health */
|
|
115
|
+
const OPEN: ReadonlySet<string> = new Set(["waiting", "sent", "accepted", "queued", "unknown", "read", "timeout"]);
|
|
116
|
+
|
|
117
|
+
// ---- routes
|
|
118
|
+
|
|
119
|
+
export type Offline = "failover" | "queue";
|
|
120
|
+
/** One routes row: (channel, thread_ts) → labelled lane addresses and options. thread_ts "" = the channel default. */
|
|
121
|
+
export interface Route {
|
|
122
|
+
channel: string;
|
|
123
|
+
thread_ts: string;
|
|
124
|
+
/** label (a1, b2) → lane:<name>[@<agent id>] */
|
|
125
|
+
to: Record<string, string>;
|
|
126
|
+
/** observers: lane addresses */
|
|
127
|
+
cc: string[];
|
|
128
|
+
/** "human", "any" or one user id */
|
|
129
|
+
from: string;
|
|
130
|
+
read_s: number;
|
|
131
|
+
queue_max_s: number;
|
|
132
|
+
ack_s: number;
|
|
133
|
+
fallback?: string;
|
|
134
|
+
offline: Offline;
|
|
135
|
+
}
|
|
136
|
+
export type RouteInput = Partial<Omit<Route, "channel" | "thread_ts" | "to">> & { channel: string; thread_ts?: string; to: Record<string, string> };
|
|
137
|
+
|
|
138
|
+
const USER = /^[UW][A-Z0-9]{2,}$/;
|
|
139
|
+
const SECONDS_MAX = 604_800;
|
|
140
|
+
|
|
141
|
+
/** Problems with an admin route row ([] = valid). */
|
|
142
|
+
export function checkRoute(x: unknown): string[] {
|
|
143
|
+
if (!x || typeof x !== "object" || Array.isArray(x)) return ["route: want an object"];
|
|
144
|
+
const r = x as Record<string, unknown>;
|
|
145
|
+
const errs: string[] = [];
|
|
146
|
+
if (typeof r.channel !== "string" || !CHANNEL.test(r.channel)) errs.push("route.channel: want a channel id");
|
|
147
|
+
if (r.thread_ts !== undefined && r.thread_ts !== "" && (typeof r.thread_ts !== "string" || !TS.test(r.thread_ts))) {
|
|
148
|
+
errs.push("route.thread_ts: want a Slack ts (or none for the channel default)");
|
|
149
|
+
}
|
|
150
|
+
if (!r.to || typeof r.to !== "object" || Array.isArray(r.to)) errs.push("route.to: want {label: lane address}");
|
|
151
|
+
else {
|
|
152
|
+
for (const [l, a] of Object.entries(r.to)) {
|
|
153
|
+
if (!LABEL.test(l)) errs.push(`route.to.${l}: want a label like b2`);
|
|
154
|
+
if (typeof a !== "string" || !LANE_ADDRESS.test(a)) errs.push(`route.to.${l}: want lane:<name>[@<agent id>]`);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
if (r.cc !== undefined && (!Array.isArray(r.cc) || !r.cc.every((a) => typeof a === "string" && LANE_ADDRESS.test(a)))) {
|
|
158
|
+
errs.push("route.cc: want lane addresses");
|
|
159
|
+
}
|
|
160
|
+
if (r.from !== undefined && r.from !== "human" && r.from !== "any" && (typeof r.from !== "string" || !USER.test(r.from))) {
|
|
161
|
+
errs.push("route.from: want human, any or a user id");
|
|
162
|
+
}
|
|
163
|
+
for (const k of ["read_s", "queue_max_s", "ack_s"]) {
|
|
164
|
+
const v = r[k];
|
|
165
|
+
if (v !== undefined && (!Number.isInteger(v) || (v as number) < 1 || (v as number) > SECONDS_MAX)) errs.push(`route.${k}: want 1..${SECONDS_MAX} seconds`);
|
|
166
|
+
}
|
|
167
|
+
if (r.fallback !== undefined && (typeof r.fallback !== "string" || !LANE_ADDRESS.test(r.fallback))) errs.push("route.fallback: want a lane address");
|
|
168
|
+
if (r.offline !== undefined && r.offline !== "failover" && r.offline !== "queue") errs.push("route.offline: want failover|queue");
|
|
169
|
+
if (!errs.length && !Object.keys(r.to as object).length && !(Array.isArray(r.cc) && r.cc.length)) errs.push("route: want at least one target (to or cc)");
|
|
170
|
+
return errs;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function normalizeRoute(r: RouteInput): Route {
|
|
174
|
+
return {
|
|
175
|
+
channel: r.channel,
|
|
176
|
+
thread_ts: r.thread_ts ?? "",
|
|
177
|
+
to: { ...r.to },
|
|
178
|
+
cc: [...new Set(r.cc ?? [])],
|
|
179
|
+
from: r.from ?? DEFAULTS.from,
|
|
180
|
+
read_s: r.read_s ?? DEFAULTS.read_s,
|
|
181
|
+
queue_max_s: r.queue_max_s ?? DEFAULTS.queue_max_s,
|
|
182
|
+
ack_s: r.ack_s ?? DEFAULTS.ack_s,
|
|
183
|
+
...(r.fallback !== undefined ? { fallback: r.fallback } : {}),
|
|
184
|
+
offline: r.offline ?? DEFAULTS.offline,
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** lane:<name>[@<pin>] → name */
|
|
189
|
+
export const laneOf = (address: string): string => address.slice(5).split("@")[0]!;
|
|
190
|
+
/** b2 → b, fb:b → b */
|
|
191
|
+
const grpOf = (label: string): string => (label.startsWith("fb:") ? label.slice(3) : label[0]!);
|
|
192
|
+
|
|
193
|
+
/** The group letters a route sends to, sorted. */
|
|
194
|
+
function lettersOf(r: Route): string[] {
|
|
195
|
+
return [...new Set(Object.keys(r.to).map((l) => l[0]!))].sort();
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
type Candidate = { label: string; rank: number; address: string; lane: string };
|
|
199
|
+
/** A group's ranks in failover order, then its fallback (`fb:<letter>`, rank 10) unless that lane is already a rank. */
|
|
200
|
+
function ranksOf(r: Route, letter: string): Candidate[] {
|
|
201
|
+
const ranks = Object.entries(r.to)
|
|
202
|
+
.filter(([l]) => l[0] === letter)
|
|
203
|
+
.map(([label, address]) => ({ label, rank: Number(label[1]), address, lane: laneOf(address) }))
|
|
204
|
+
.sort((a, b) => a.rank - b.rank);
|
|
205
|
+
if (r.fallback !== undefined && !ranks.some((c) => c.lane === laneOf(r.fallback!))) {
|
|
206
|
+
ranks.push({ label: `fb:${letter}`, rank: 10, address: r.fallback, lane: laneOf(r.fallback) });
|
|
207
|
+
}
|
|
208
|
+
return ranks;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// ---- rows
|
|
212
|
+
|
|
213
|
+
type MachineRow = {
|
|
214
|
+
machine: string; pubkey: string; revoked_at: number | null; enrolled_at: number; version: string | null; first_seen: number | null;
|
|
215
|
+
last_seen: number | null; online: number; offline_since: number | null; hb: string | null;
|
|
216
|
+
};
|
|
217
|
+
type LaneRow = { lane: string; machine: string; cwd: string | null; first_seen: number; placed_at: number; prev_machine: string | null };
|
|
218
|
+
type SeenRow = { lane: string; machine: string; listed: number; health: string; agents: number; cwd: string | null; at: number };
|
|
219
|
+
type MsgRow = {
|
|
220
|
+
seq: number; id: string; app: string; team: string; channel: string; ts: string; thread_ts: string | null; user: string; human: number;
|
|
221
|
+
text: string | null; files: string | null; route: string; at: number; final: number; final_at: number | null;
|
|
222
|
+
};
|
|
223
|
+
type DeliveryRow = {
|
|
224
|
+
msg: number; label: string; grp: string | null; rank: number; role: "worker" | "observer"; address: string; lane: string;
|
|
225
|
+
machine: string | null; state: State; why: string | null; attempts: number; token: string | null; endpoint: string | null;
|
|
226
|
+
status: string | null; ack: string | null; sent_at: number | null; accepted_at: number | null; deadline: number | null; at: number;
|
|
227
|
+
};
|
|
228
|
+
type AlertRow = { kind: AlertKind; subject: string; state: "open" | "cleared"; since: number; updated_at: number; detail: string | null };
|
|
229
|
+
type JobRow = { machine: string; job: string; ok: number; at: number; every_s: number; last_ok: number | null; first_at: number; detail: string | null };
|
|
230
|
+
|
|
231
|
+
const SCHEMA = [
|
|
232
|
+
"CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v TEXT NOT NULL)",
|
|
233
|
+
`CREATE TABLE IF NOT EXISTS machines (
|
|
234
|
+
machine TEXT PRIMARY KEY, pubkey TEXT NOT NULL, revoked_at INTEGER, enrolled_at INTEGER NOT NULL, version TEXT,
|
|
235
|
+
first_seen INTEGER, last_seen INTEGER, online INTEGER NOT NULL DEFAULT 0, offline_since INTEGER, hb TEXT
|
|
236
|
+
)`,
|
|
237
|
+
`CREATE TABLE IF NOT EXISTS lanes (
|
|
238
|
+
lane TEXT PRIMARY KEY, machine TEXT NOT NULL, cwd TEXT, first_seen INTEGER NOT NULL, placed_at INTEGER NOT NULL, prev_machine TEXT
|
|
239
|
+
)`,
|
|
240
|
+
`CREATE TABLE IF NOT EXISTS lane_seen (
|
|
241
|
+
lane TEXT NOT NULL, machine TEXT NOT NULL, listed INTEGER NOT NULL, health TEXT NOT NULL, agents INTEGER NOT NULL, cwd TEXT,
|
|
242
|
+
at INTEGER NOT NULL, PRIMARY KEY (lane, machine)
|
|
243
|
+
)`,
|
|
244
|
+
"CREATE TABLE IF NOT EXISTS audit (id INTEGER PRIMARY KEY AUTOINCREMENT, at INTEGER NOT NULL, kind TEXT NOT NULL, lane TEXT, machine TEXT, detail TEXT)",
|
|
245
|
+
"CREATE TABLE IF NOT EXISTS routes (channel TEXT NOT NULL, thread_ts TEXT NOT NULL, spec TEXT NOT NULL, at INTEGER NOT NULL, PRIMARY KEY (channel, thread_ts))",
|
|
246
|
+
`CREATE TABLE IF NOT EXISTS messages (
|
|
247
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, app TEXT NOT NULL, team TEXT NOT NULL, channel TEXT NOT NULL,
|
|
248
|
+
ts TEXT NOT NULL, thread_ts TEXT, user TEXT NOT NULL, human INTEGER NOT NULL, text TEXT, files TEXT, route TEXT NOT NULL,
|
|
249
|
+
at INTEGER NOT NULL, final INTEGER NOT NULL DEFAULT 0, final_at INTEGER
|
|
250
|
+
)`,
|
|
251
|
+
"CREATE INDEX IF NOT EXISTS messages_at ON messages (at)",
|
|
252
|
+
"CREATE INDEX IF NOT EXISTS messages_ct ON messages (channel, ts)",
|
|
253
|
+
"CREATE TABLE IF NOT EXISTS events (event_id TEXT PRIMARY KEY, at INTEGER NOT NULL)",
|
|
254
|
+
"CREATE INDEX IF NOT EXISTS events_at ON events (at)",
|
|
255
|
+
`CREATE TABLE IF NOT EXISTS deliveries (
|
|
256
|
+
msg INTEGER NOT NULL, label TEXT NOT NULL, grp TEXT, rank INTEGER NOT NULL, role TEXT NOT NULL, address TEXT NOT NULL,
|
|
257
|
+
lane TEXT NOT NULL, machine TEXT, state TEXT NOT NULL, why TEXT, attempts INTEGER NOT NULL DEFAULT 0, token TEXT, endpoint TEXT,
|
|
258
|
+
status TEXT, ack TEXT, sent_at INTEGER, accepted_at INTEGER, deadline INTEGER, at INTEGER NOT NULL, PRIMARY KEY (msg, label)
|
|
259
|
+
)`,
|
|
260
|
+
"CREATE INDEX IF NOT EXISTS deliveries_deadline ON deliveries (deadline)",
|
|
261
|
+
"CREATE INDEX IF NOT EXISTS deliveries_state ON deliveries (state, machine)",
|
|
262
|
+
"CREATE UNIQUE INDEX IF NOT EXISTS deliveries_token ON deliveries (token)",
|
|
263
|
+
`CREATE TABLE IF NOT EXISTS alerts (
|
|
264
|
+
kind TEXT NOT NULL, subject TEXT NOT NULL, state TEXT NOT NULL, since INTEGER NOT NULL, updated_at INTEGER NOT NULL, detail TEXT,
|
|
265
|
+
PRIMARY KEY (kind, subject)
|
|
266
|
+
)`,
|
|
267
|
+
`CREATE TABLE IF NOT EXISTS jobs (
|
|
268
|
+
machine TEXT NOT NULL, job TEXT NOT NULL, ok INTEGER NOT NULL, at INTEGER NOT NULL, every_s INTEGER NOT NULL, last_ok INTEGER,
|
|
269
|
+
first_at INTEGER NOT NULL, detail TEXT, PRIMARY KEY (machine, job)
|
|
270
|
+
)`,
|
|
271
|
+
"CREATE TABLE IF NOT EXISTS apps (app TEXT PRIMARY KEY, first_at INTEGER NOT NULL, last_event INTEGER NOT NULL)",
|
|
272
|
+
];
|
|
273
|
+
|
|
274
|
+
export type IntakeResult = { routed: boolean; duplicate?: boolean; id?: string };
|
|
275
|
+
export type Result = { ok: true } | { ok: false; error: string; owner?: string };
|
|
276
|
+
|
|
277
|
+
const iso = (ms: number): string => new Date(ms).toISOString();
|
|
278
|
+
|
|
279
|
+
export class RouterCore {
|
|
280
|
+
private readonly sql: Sql;
|
|
281
|
+
private readonly tx: Tx;
|
|
282
|
+
private readonly link: Link;
|
|
283
|
+
readonly mode: Mode;
|
|
284
|
+
private readonly daytime: { start: number; end: number };
|
|
285
|
+
private epochValue = "";
|
|
286
|
+
/** Online machines → last sign of life, as of the current call's sync(). */
|
|
287
|
+
private live = new Map<string, number>();
|
|
288
|
+
/** Machines a send to failed during the current call; reap() takes them offline before the call returns. */
|
|
289
|
+
private readonly dead = new Set<string>();
|
|
290
|
+
|
|
291
|
+
constructor(o: CoreOptions) {
|
|
292
|
+
this.sql = o.sql;
|
|
293
|
+
this.tx = o.tx;
|
|
294
|
+
this.link = o.link;
|
|
295
|
+
this.mode = o.mode ?? "shadow";
|
|
296
|
+
this.daytime = o.daytime ?? { start: 8, end: 22 };
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** Create the tables (idempotent) and return the router epoch: names this storage, like the relay's. */
|
|
300
|
+
init(epoch: () => string = () => crypto.randomUUID()): string {
|
|
301
|
+
for (const q of SCHEMA) this.sql.exec(q);
|
|
302
|
+
this.sql.exec("INSERT OR IGNORE INTO meta (k, v) VALUES ('epoch', ?)", epoch());
|
|
303
|
+
this.epochValue = this.sql.exec<{ v: string }>("SELECT v FROM meta WHERE k = 'epoch'").one().v;
|
|
304
|
+
return this.epochValue;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
get epoch(): string {
|
|
308
|
+
return this.epochValue;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// ======== entry points: each runs in one transaction, after sync(now)
|
|
312
|
+
|
|
313
|
+
/** Nothing happened but time passed (the alarm), or a socket closed: liveness, clocks, alerts, retention. */
|
|
314
|
+
tick(now: number): void {
|
|
315
|
+
this.run(now, () => undefined);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** The enrolled, unrevoked public key of `machine`, or null. */
|
|
319
|
+
pubkeyOf(machine: string): string | null {
|
|
320
|
+
return this.sql.exec<{ pubkey: string }>("SELECT pubkey FROM machines WHERE machine = ? AND revoked_at IS NULL", machine).toArray()[0]?.pubkey ?? null;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** A machine's socket just authenticated: welcome first, then everything else. */
|
|
324
|
+
authenticated(machine: string, version: string, now: number): void {
|
|
325
|
+
this.tx(() => {
|
|
326
|
+
this.emit(machine, {
|
|
327
|
+
v: AIP_VERSION, op: "welcome", machine, epoch: this.epochValue, mode: this.mode, lanes: this.placedOn(machine), now,
|
|
328
|
+
});
|
|
329
|
+
this.sql.exec("UPDATE machines SET version = ? WHERE machine = ?", version.slice(0, 64), machine);
|
|
330
|
+
this.sync(now);
|
|
331
|
+
this.reap(now);
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** A validated frame from an authenticated machine. `first`: the first heartbeat on this socket. */
|
|
336
|
+
handle(machine: string, f: T2Frame, now: number, first = false): void {
|
|
337
|
+
switch (f.op) {
|
|
338
|
+
case "heartbeat":
|
|
339
|
+
return this.heartbeat(machine, f.lanes, f.jobs ?? [], now, first);
|
|
340
|
+
case "beat":
|
|
341
|
+
return this.beat(machine, f, now);
|
|
342
|
+
case "receipt":
|
|
343
|
+
return this.receipt(machine, f.receipt, now);
|
|
344
|
+
case "ack":
|
|
345
|
+
return this.ack(machine, f.ack, now);
|
|
346
|
+
case "claim":
|
|
347
|
+
return this.claim(machine, f, now);
|
|
348
|
+
case "placement":
|
|
349
|
+
return this.placement(machine, f, now);
|
|
350
|
+
case "auth":
|
|
351
|
+
return this.run(now, () => void this.emit(machine, { v: AIP_VERSION, op: "error", error: "already authenticated" }));
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
heartbeat(machine: string, lanes: LaneStatus[], jobs: JobBeat[], now: number, first = false): void {
|
|
356
|
+
this.run(now, () => {
|
|
357
|
+
for (const j of jobs) this.recordBeat(machine, j, now);
|
|
358
|
+
const sorted = [...lanes].sort((a, b) => (a.lane < b.lane ? -1 : a.lane > b.lane ? 1 : 0));
|
|
359
|
+
const canon = JSON.stringify(sorted.map((l) => [l.lane, l.cwd ?? null, l.health, l.agents]));
|
|
360
|
+
const prev = this.machine(machine)?.hb ?? null;
|
|
361
|
+
const changed = canon !== prev;
|
|
362
|
+
if (changed) this.sql.exec("UPDATE machines SET hb = ? WHERE machine = ?", canon, machine);
|
|
363
|
+
// An unchanged heartbeat is a no-op (no audit row). The first one after a (re)connect is evaluated anyway: the
|
|
364
|
+
// machine was offline, so placements and conflicts may have changed meanwhile.
|
|
365
|
+
if (changed || first) {
|
|
366
|
+
const listed = new Set(sorted.map((l) => l.lane));
|
|
367
|
+
const before = this.sql.exec<{ lane: string }>("SELECT lane FROM lane_seen WHERE machine = ? AND listed = 1", machine).toArray().map((r) => r.lane);
|
|
368
|
+
for (const l of sorted) {
|
|
369
|
+
this.sql.exec(
|
|
370
|
+
`INSERT INTO lane_seen (lane, machine, listed, health, agents, cwd, at) VALUES (?, ?, 1, ?, ?, ?, ?)
|
|
371
|
+
ON CONFLICT (lane, machine) DO UPDATE SET listed = 1, health = excluded.health, agents = excluded.agents, cwd = excluded.cwd, at = excluded.at`,
|
|
372
|
+
l.lane, machine, l.health, l.agents, l.cwd ?? null, now,
|
|
373
|
+
);
|
|
374
|
+
}
|
|
375
|
+
const gone = before.filter((l) => !listed.has(l));
|
|
376
|
+
for (const l of gone) this.sql.exec("UPDATE lane_seen SET listed = 0, at = ? WHERE lane = ? AND machine = ?", now, l, machine);
|
|
377
|
+
const dirty = new Set<string>();
|
|
378
|
+
for (const l of sorted) this.placeListed(l.lane, machine, l.cwd, now, dirty);
|
|
379
|
+
for (const l of gone) this.reconcileLane(l, now, dirty);
|
|
380
|
+
this.evalConflicts([...listed, ...gone], now);
|
|
381
|
+
this.directories(dirty);
|
|
382
|
+
}
|
|
383
|
+
if (changed || first) this.replay(first ? machine : null, now);
|
|
384
|
+
});
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
beat(machine: string, b: JobBeat, now: number): void {
|
|
388
|
+
this.run(now, () => this.recordBeat(machine, b, now));
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
receipt(machine: string, r: Receipt, now: number): void {
|
|
392
|
+
this.run(now, () => {
|
|
393
|
+
const hash = r.key.lastIndexOf("#");
|
|
394
|
+
if (hash < 0) return;
|
|
395
|
+
const msg = this.msgById(r.key.slice(0, hash));
|
|
396
|
+
const row = msg && this.row(msg.seq, r.key.slice(hash + 1));
|
|
397
|
+
// Only the machine the key was sent to may answer for it.
|
|
398
|
+
if (!msg || !row || row.machine !== machine) return;
|
|
399
|
+
const route = this.routeOf(msg);
|
|
400
|
+
this.sql.exec("UPDATE deliveries SET endpoint = ?, status = ? WHERE msg = ? AND label = ?", r.endpoint.slice(0, 200), r.status, row.msg, row.label);
|
|
401
|
+
const ok = r.status === "accepted" || r.status === "queued" || r.status === "unknown";
|
|
402
|
+
if (row.role === "observer") {
|
|
403
|
+
// No clocks, no failover: final at any receipt.
|
|
404
|
+
if (row.state === "sent") this.set(row, { state: r.shadow && ok ? "shadow" : ok ? (r.status as State) : "failed", why: r.detail ?? null, deadline: null }, now);
|
|
405
|
+
} else if (row.state === "sent" || row.state === "unknown" || row.state === "queued") {
|
|
406
|
+
if (r.shadow && ok) {
|
|
407
|
+
this.set(row, { state: "shadow", why: r.detail ?? null, deadline: null }, now);
|
|
408
|
+
this.delivered(msg, row.grp!, now);
|
|
409
|
+
} else if (r.status === "accepted") {
|
|
410
|
+
this.set(row, { state: "accepted", accepted_at: now, deadline: now + route.ack_s * 1000 }, now);
|
|
411
|
+
this.delivered(msg, row.grp!, now);
|
|
412
|
+
} else if (r.status === "queued") {
|
|
413
|
+
// The read clock pauses; the cap runs from the send.
|
|
414
|
+
if (row.state !== "queued") this.set(row, { state: "queued", deadline: (row.sent_at ?? now) + route.queue_max_s * 1000 }, now);
|
|
415
|
+
this.delivered(msg, row.grp!, now);
|
|
416
|
+
} else if (r.status === "unknown") {
|
|
417
|
+
// May have been delivered: the read clock keeps running.
|
|
418
|
+
if (row.state === "sent") this.set(row, { state: "unknown" }, now);
|
|
419
|
+
this.delivered(msg, row.grp!, now);
|
|
420
|
+
} else if (row.state === "sent") {
|
|
421
|
+
this.set(row, { state: "failed", why: r.detail ?? r.status, deadline: null }, now);
|
|
422
|
+
this.advance(msg, row.grp!, row.rank, now);
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
// offline / timeout / anything else: recorded above (endpoint, status), clocks untouched.
|
|
426
|
+
this.checkFinal(msg, now);
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
ack(machine: string, a: Ack, now: number): void {
|
|
431
|
+
void machine; // any authenticated machine may carry an ack: the token names the delivery
|
|
432
|
+
this.run(now, () => {
|
|
433
|
+
const row = this.sql.exec<DeliveryRow>("SELECT * FROM deliveries WHERE token = ?", a.token).toArray()[0];
|
|
434
|
+
if (!row) return;
|
|
435
|
+
const msg = this.msgBySeq(row.msg)!;
|
|
436
|
+
this.sql.exec("UPDATE deliveries SET ack = ? WHERE msg = ? AND label = ?", a.kind, row.msg, row.label);
|
|
437
|
+
if (row.role === "observer") return; // recorded, changes nothing
|
|
438
|
+
const route = this.routeOf(msg);
|
|
439
|
+
if (a.kind === "read") {
|
|
440
|
+
if (row.state === "sent" || row.state === "unknown" || row.state === "queued" || row.state === "accepted") {
|
|
441
|
+
const from = row.accepted_at ?? now;
|
|
442
|
+
this.set(row, { state: "read", accepted_at: from, deadline: from + route.ack_s * 1000 }, now);
|
|
443
|
+
this.delivered(msg, row.grp!, now);
|
|
444
|
+
}
|
|
445
|
+
} else if (a.kind === "done") {
|
|
446
|
+
if (!["done", "cancelled", "declined", "skipped", "shadow"].includes(row.state)) {
|
|
447
|
+
this.set(row, { state: "done", deadline: null }, now);
|
|
448
|
+
this.delivered(msg, row.grp!, now);
|
|
449
|
+
// Every later rank of the group still open stands down.
|
|
450
|
+
for (const r of this.groupRows(msg.seq, row.grp!)) {
|
|
451
|
+
if (r.rank > row.rank && CANCELLABLE.has(r.state)) {
|
|
452
|
+
if (r.machine && this.live.has(r.machine)) this.emit(r.machine, { v: AIP_VERSION, op: "cancel", key: `${msg.id}#${r.label}`, why: `${row.label} answered` });
|
|
453
|
+
this.set(r, { state: "cancelled", why: `${row.label} answered`, deadline: null }, now);
|
|
454
|
+
} else if (r.state === "waiting") this.set(r, { state: "skipped", why: `${row.label} answered` }, now);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
} else if ((ACTIVE.has(row.state) || row.state === "timeout") && msg.final !== 1) {
|
|
458
|
+
// Not after final: the text is gone, a later rank would get an empty message.
|
|
459
|
+
this.set(row, { state: "declined", why: "declined", deadline: null }, now);
|
|
460
|
+
this.advance(msg, row.grp!, row.rank, now);
|
|
461
|
+
}
|
|
462
|
+
this.checkFinal(msg, now);
|
|
463
|
+
});
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
claim(machine: string, f: Extract<T2Frame, { op: "claim" }>, now: number): void {
|
|
467
|
+
this.run(now, () => {
|
|
468
|
+
const lane = this.lane(f.lane);
|
|
469
|
+
if (!lane || lane.machine !== machine) return this.result(machine, f.id, { ok: false, error: `lane ${f.lane} is not placed on ${machine}` });
|
|
470
|
+
const { channel, thread_ts } = f.thread;
|
|
471
|
+
const cur = this.route(channel, thread_ts);
|
|
472
|
+
const b1 = cur?.to.b1;
|
|
473
|
+
if (cur && (b1 === undefined || laneOf(b1) !== f.lane)) {
|
|
474
|
+
return this.result(machine, f.id, { ok: false, error: "thread claimed", ...(b1 !== undefined ? { owner: b1 } : {}) });
|
|
475
|
+
}
|
|
476
|
+
const row = this.claimRow(channel, thread_ts, f.lane);
|
|
477
|
+
Object.assign(row.to, f.to ?? {});
|
|
478
|
+
row.cc = [...new Set([...row.cc, ...(f.cc ?? [])])];
|
|
479
|
+
this.saveRoute(row, now);
|
|
480
|
+
this.audit(now, "claim", f.lane, machine, `${channel}/${thread_ts}`);
|
|
481
|
+
this.result(machine, f.id, { ok: true });
|
|
482
|
+
});
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
placement(machine: string, f: Extract<T2Frame, { op: "placement" }>, now: number): void {
|
|
486
|
+
this.run(now, () => {
|
|
487
|
+
const cur = this.lane(f.lane);
|
|
488
|
+
const dirty = new Set<string>();
|
|
489
|
+
let res: Result = { ok: true };
|
|
490
|
+
let conflict: string[] | undefined;
|
|
491
|
+
if (!cur) {
|
|
492
|
+
this.place(f.lane, machine, f.cwd ?? null, now);
|
|
493
|
+
dirty.add(machine);
|
|
494
|
+
} else if (cur.machine === machine) {
|
|
495
|
+
if (f.cwd !== undefined && f.cwd !== cur.cwd) {
|
|
496
|
+
this.sql.exec("UPDATE lanes SET cwd = ? WHERE lane = ?", f.cwd, f.lane);
|
|
497
|
+
dirty.add(machine);
|
|
498
|
+
}
|
|
499
|
+
} else if (f.move === true || !this.live.has(cur.machine) || !this.listedBy(f.lane, cur.machine)) {
|
|
500
|
+
this.move(f.lane, machine, f.cwd ?? cur.cwd, now, "lane.move");
|
|
501
|
+
dirty.add(machine).add(cur.machine);
|
|
502
|
+
} else {
|
|
503
|
+
// Placed on another online machine that lists it: the placement stays, recorded as a conflict.
|
|
504
|
+
conflict = [cur.machine, machine];
|
|
505
|
+
res = { ok: false, error: `lane ${f.lane} is placed on ${cur.machine}, which lists it (send move: true to take it)` };
|
|
506
|
+
}
|
|
507
|
+
this.result(machine, f.id, res);
|
|
508
|
+
if (conflict) this.conflict(f.lane, conflict, now);
|
|
509
|
+
this.directories(dirty);
|
|
510
|
+
if (dirty.size) this.replay(null, now);
|
|
511
|
+
});
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
intake(app: string, ev: IntakeEvent, now: number): IntakeResult {
|
|
515
|
+
return this.run(now, (): IntakeResult => {
|
|
516
|
+
this.sql.exec(
|
|
517
|
+
"INSERT INTO apps (app, first_at, last_event) VALUES (?, ?, ?) ON CONFLICT (app) DO UPDATE SET last_event = excluded.last_event",
|
|
518
|
+
app, now, now,
|
|
519
|
+
);
|
|
520
|
+
this.clearAlert("intake.silent", app, now);
|
|
521
|
+
if (ev.event_id !== undefined) {
|
|
522
|
+
const fresh = this.sql.exec("INSERT OR IGNORE INTO events (event_id, at) VALUES (?, ?) RETURNING event_id", ev.event_id, now).toArray();
|
|
523
|
+
if (!fresh.length) return { routed: false, duplicate: true };
|
|
524
|
+
}
|
|
525
|
+
const m = ev.message;
|
|
526
|
+
if (!m) return { routed: false };
|
|
527
|
+
const id = `slack:${m.team}/${m.channel}/${m.ts}`;
|
|
528
|
+
// The same message heard twice (message + app_mention, or a retry with a new event id).
|
|
529
|
+
if (this.msgById(id)) return { routed: false, duplicate: true, id };
|
|
530
|
+
// A thread root "[lane] …" claims its thread for a placed lane (bot posts too: that is how lanes post roots).
|
|
531
|
+
if (m.root !== undefined && m.thread_ts === undefined && this.lane(m.root) && !this.route(m.channel, m.ts)) {
|
|
532
|
+
this.saveRoute(this.claimRow(m.channel, m.ts, m.root), now);
|
|
533
|
+
this.audit(now, "claim.root", m.root, this.lane(m.root)!.machine, `${m.channel}/${m.ts}`);
|
|
534
|
+
}
|
|
535
|
+
const route = this.route(m.channel, m.thread_ts ?? m.ts) ?? this.route(m.channel, "");
|
|
536
|
+
if (!route || !fromMatches(route.from, m) || (!Object.keys(route.to).length && !route.cc.length)) return { routed: false };
|
|
537
|
+
// A thread route in use is not idle (ROUTE_IDLE_MS).
|
|
538
|
+
this.sql.exec("UPDATE routes SET at = ? WHERE channel = ? AND thread_ts = ? AND thread_ts <> ''", now, m.channel, m.thread_ts ?? m.ts);
|
|
539
|
+
const seq = this.sql.exec<{ seq: number }>(
|
|
540
|
+
`INSERT INTO messages (id, app, team, channel, ts, thread_ts, user, human, text, files, route, at)
|
|
541
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING seq`,
|
|
542
|
+
id, app, m.team, m.channel, m.ts, m.thread_ts ?? null, m.user, m.human ? 1 : 0, m.text,
|
|
543
|
+
m.files?.length ? JSON.stringify(m.files) : null, JSON.stringify(route), now,
|
|
544
|
+
).one().seq;
|
|
545
|
+
const msg = this.msgBySeq(seq)!;
|
|
546
|
+
for (const letter of lettersOf(route)) this.advance(msg, letter, 0, now);
|
|
547
|
+
for (const address of route.cc) this.observe(msg, `cc:${laneOf(address)}`, address, now);
|
|
548
|
+
this.checkFinal(msg, now);
|
|
549
|
+
return { routed: true, id };
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
// ---- admin
|
|
554
|
+
|
|
555
|
+
health(now: number): {
|
|
556
|
+
ok: true; mode: Mode; epoch: string; machines: { machine: string; online: boolean; last_seen: number | null }[]; open_deliveries: number; alerts_open: number;
|
|
557
|
+
} {
|
|
558
|
+
return this.run(now, () => {
|
|
559
|
+
const machines = this.sql.exec<MachineRow>("SELECT * FROM machines WHERE revoked_at IS NULL ORDER BY machine").toArray()
|
|
560
|
+
.map((m) => ({ machine: m.machine, online: this.live.has(m.machine), last_seen: this.live.get(m.machine) ?? m.last_seen }));
|
|
561
|
+
const open = this.sql.exec<{ n: number }>(
|
|
562
|
+
`SELECT COUNT(*) AS n FROM deliveries WHERE state IN (${[...OPEN].map(() => "?").join(", ")})`, ...OPEN,
|
|
563
|
+
).one().n;
|
|
564
|
+
const alerts = this.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM alerts WHERE state = 'open'").one().n;
|
|
565
|
+
return { ok: true as const, mode: this.mode, epoch: this.epochValue, machines, open_deliveries: open, alerts_open: alerts };
|
|
566
|
+
});
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/** Enroll a machine or rotate its key (base64url raw Ed25519). A rotation closes the socket the old key opened. */
|
|
570
|
+
enroll(machine: string, pubkey: string, now: number): { ok: true; machine: string; rotated: boolean } | { ok: false; error: string } {
|
|
571
|
+
if (!NAME.test(machine)) return { ok: false, error: "machine: want a machine name" };
|
|
572
|
+
if (!PUBKEY.test(pubkey) || fromBase64url(pubkey)?.length !== 32) return { ok: false, error: "pubkey: want a raw Ed25519 public key, base64url (43 chars)" };
|
|
573
|
+
return this.run(now, () => {
|
|
574
|
+
const cur = this.machine(machine);
|
|
575
|
+
if (!cur) {
|
|
576
|
+
this.sql.exec("INSERT INTO machines (machine, pubkey, enrolled_at) VALUES (?, ?, ?)", machine, pubkey, now);
|
|
577
|
+
this.audit(now, "machine.enroll", null, machine, null);
|
|
578
|
+
return { ok: true as const, machine, rotated: false };
|
|
579
|
+
}
|
|
580
|
+
this.sql.exec("UPDATE machines SET pubkey = ?, revoked_at = NULL WHERE machine = ?", pubkey, machine);
|
|
581
|
+
this.audit(now, "machine.rotate", null, machine, null);
|
|
582
|
+
if (cur.pubkey !== pubkey && this.live.has(machine)) this.drop(machine, now, 4401, "key rotated");
|
|
583
|
+
return { ok: true as const, machine, rotated: true };
|
|
584
|
+
});
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
/** Revoke a machine's key and close its socket. false: not enrolled. */
|
|
588
|
+
revoke(machine: string, now: number): boolean {
|
|
589
|
+
return this.run(now, () => {
|
|
590
|
+
const cur = this.machine(machine);
|
|
591
|
+
if (!cur || cur.revoked_at !== null) return false;
|
|
592
|
+
this.sql.exec("UPDATE machines SET revoked_at = ? WHERE machine = ?", now, machine);
|
|
593
|
+
this.audit(now, "machine.revoke", null, machine, null);
|
|
594
|
+
if (this.live.has(machine)) this.drop(machine, now, 4401, "revoked");
|
|
595
|
+
this.clearAlert("machine.silent", machine, now, "revoked");
|
|
596
|
+
for (const j of this.sql.exec<{ job: string }>("SELECT job FROM jobs WHERE machine = ?", machine).toArray()) {
|
|
597
|
+
this.clearAlert("job.late", `${machine}/${j.job}`, now, "machine revoked");
|
|
598
|
+
}
|
|
599
|
+
return true;
|
|
600
|
+
});
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
lanesView(): { lanes: { lane: string; machine: string; cwd: string | null; placed_at: number; prev_machine: string | null }[]; audit: { at: number; kind: string; lane: string | null; machine: string | null; detail: string | null }[] } {
|
|
604
|
+
return {
|
|
605
|
+
lanes: this.sql.exec<LaneRow>("SELECT * FROM lanes ORDER BY lane").toArray()
|
|
606
|
+
.map((l) => ({ lane: l.lane, machine: l.machine, cwd: l.cwd, placed_at: l.placed_at, prev_machine: l.prev_machine })),
|
|
607
|
+
audit: this.sql.exec<{ at: number; kind: string; lane: string | null; machine: string | null; detail: string | null }>(
|
|
608
|
+
"SELECT at, kind, lane, machine, detail FROM audit ORDER BY id DESC LIMIT ?", AUDIT_ROWS,
|
|
609
|
+
).toArray(),
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
/** Admin: seed a lane or move it (audit lane.seed). */
|
|
614
|
+
seedLane(lane: string, machine: string, cwd: string | undefined, now: number): { ok: true; lane: LaneRow } | { ok: false; error: string } {
|
|
615
|
+
if (!NAME.test(lane)) return { ok: false, error: "lane: want a lane name" };
|
|
616
|
+
if (!NAME.test(machine)) return { ok: false, error: "machine: want a machine name" };
|
|
617
|
+
return this.run(now, () => {
|
|
618
|
+
if (!this.machine(machine)) return { ok: false as const, error: `machine ${machine} is not enrolled` };
|
|
619
|
+
const cur = this.lane(lane);
|
|
620
|
+
const dirty = new Set<string>([machine]);
|
|
621
|
+
if (!cur) {
|
|
622
|
+
this.sql.exec("INSERT INTO lanes (lane, machine, cwd, first_seen, placed_at) VALUES (?, ?, ?, ?, ?)", lane, machine, cwd ?? null, now, now);
|
|
623
|
+
} else {
|
|
624
|
+
this.sql.exec(
|
|
625
|
+
"UPDATE lanes SET machine = ?, cwd = ?, placed_at = ?, prev_machine = ? WHERE lane = ?",
|
|
626
|
+
machine, cwd ?? cur.cwd, cur.machine === machine ? cur.placed_at : now, cur.machine === machine ? cur.prev_machine : cur.machine, lane,
|
|
627
|
+
);
|
|
628
|
+
dirty.add(cur.machine);
|
|
629
|
+
}
|
|
630
|
+
this.audit(now, "lane.seed", lane, machine, cur && cur.machine !== machine ? `from ${cur.machine}` : null);
|
|
631
|
+
this.directories(dirty);
|
|
632
|
+
this.replay(null, now);
|
|
633
|
+
return { ok: true as const, lane: this.lane(lane)! };
|
|
634
|
+
});
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
putRoute(r: RouteInput, now: number): Route {
|
|
638
|
+
return this.run(now, () => {
|
|
639
|
+
const route = normalizeRoute(r);
|
|
640
|
+
this.saveRoute(route, now);
|
|
641
|
+
this.audit(now, "route.put", null, null, `${route.channel}/${route.thread_ts}`);
|
|
642
|
+
return route;
|
|
643
|
+
});
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
deleteRoute(channel: string, thread_ts: string, now: number): boolean {
|
|
647
|
+
return this.run(now, () => {
|
|
648
|
+
const n = this.sql.exec("DELETE FROM routes WHERE channel = ? AND thread_ts = ? RETURNING channel", channel, thread_ts).toArray().length;
|
|
649
|
+
if (n) this.audit(now, "route.delete", null, null, `${channel}/${thread_ts}`);
|
|
650
|
+
return n > 0;
|
|
651
|
+
});
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
routesView(): { routes: Route[] } {
|
|
655
|
+
return { routes: this.sql.exec<{ spec: string }>("SELECT spec FROM routes ORDER BY channel, thread_ts").toArray().map((r) => JSON.parse(r.spec) as Route) };
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
messageView(channel: string, ts: string): {
|
|
659
|
+
id: string; app: string; text: string | null; final: boolean; at: number;
|
|
660
|
+
deliveries: { label: string; lane: string; machine: string | null; role: string; state: State; attempts: number; endpoint: string | null; why: string | null; at: number }[];
|
|
661
|
+
} | null {
|
|
662
|
+
const m = this.sql.exec<MsgRow>("SELECT * FROM messages WHERE channel = ? AND ts = ? ORDER BY seq DESC LIMIT 1", channel, ts).toArray()[0];
|
|
663
|
+
if (!m) return null;
|
|
664
|
+
const rows = this.sql.exec<DeliveryRow>("SELECT * FROM deliveries WHERE msg = ? ORDER BY role DESC, grp, rank, label", m.seq).toArray();
|
|
665
|
+
return {
|
|
666
|
+
id: m.id, app: m.app, text: m.text, final: m.final === 1, at: m.at,
|
|
667
|
+
deliveries: rows.map((d) => ({
|
|
668
|
+
label: d.label, lane: d.lane, machine: d.machine, role: d.role, state: d.state, attempts: d.attempts, endpoint: d.endpoint, why: d.why, at: d.at,
|
|
669
|
+
})),
|
|
670
|
+
};
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
alertsView(): { alerts: { kind: AlertKind; subject: string; state: "open" | "cleared"; since: number; detail: string | null }[] } {
|
|
674
|
+
return {
|
|
675
|
+
alerts: this.sql.exec<AlertRow>("SELECT * FROM alerts ORDER BY state DESC, since DESC, kind, subject").toArray()
|
|
676
|
+
.map((a) => ({ kind: a.kind, subject: a.subject, state: a.state, since: a.since, detail: a.detail })),
|
|
677
|
+
};
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
/** The earliest time anything is due (a clock, a liveness or silence threshold, a beat deadline, retention); null
|
|
681
|
+
* when nothing is pending. The Durable Object's alarm is always set to this. */
|
|
682
|
+
nextDeadline(now: number): number | null {
|
|
683
|
+
void now;
|
|
684
|
+
const c: number[] = [];
|
|
685
|
+
const add = (t: number | null | undefined): void => void (t !== null && t !== undefined && c.push(t));
|
|
686
|
+
add(this.sql.exec<{ t: number | null }>("SELECT MIN(deadline) AS t FROM deliveries WHERE deadline IS NOT NULL").one().t);
|
|
687
|
+
for (const s of this.link.machines()) add(s.lastSeen + LIVE_MS);
|
|
688
|
+
const off = this.sql.exec<{ t: number | null }>(
|
|
689
|
+
`SELECT MIN(offline_since) AS t FROM machines m WHERE revoked_at IS NULL AND online = 0 AND first_seen IS NOT NULL AND offline_since IS NOT NULL
|
|
690
|
+
AND NOT EXISTS (SELECT 1 FROM alerts a WHERE a.kind = 'machine.silent' AND a.subject = m.machine AND a.state = 'open')`,
|
|
691
|
+
).one().t;
|
|
692
|
+
if (off !== null) add(off + SILENT_MS);
|
|
693
|
+
for (const j of this.lateCandidates()) add((j.last_ok ?? j.first_at) + JOB_LATE_PERIODS * j.every_s * 1000);
|
|
694
|
+
for (const a of this.sql.exec<{ last_event: number }>(
|
|
695
|
+
`SELECT last_event FROM apps p WHERE NOT EXISTS (SELECT 1 FROM alerts a WHERE a.kind = 'intake.silent' AND a.subject = p.app AND a.state = 'open')`,
|
|
696
|
+
).toArray()) add(this.nextDaytime(a.last_event + INTAKE_SILENT_MS));
|
|
697
|
+
for (const w of this.waitingGroups()) if (!this.isOpen("delivery.undeliverable", `${w.msg.id}#${w.grp}`)) add(w.msg.at + this.routeOf(w.msg).read_s * 1000);
|
|
698
|
+
const oldest = this.sql.exec<{ t: number | null }>("SELECT MIN(at) AS t FROM messages").one().t;
|
|
699
|
+
if (oldest !== null) add(oldest + RETAIN_MS);
|
|
700
|
+
const oldestEvent = this.sql.exec<{ t: number | null }>("SELECT MIN(at) AS t FROM events").one().t;
|
|
701
|
+
if (oldestEvent !== null) add(oldestEvent + RETAIN_MS);
|
|
702
|
+
const oldestCleared = this.sql.exec<{ t: number | null }>("SELECT MIN(updated_at) AS t FROM alerts WHERE state = 'cleared'").one().t;
|
|
703
|
+
if (oldestCleared !== null) add(oldestCleared + RETAIN_MS);
|
|
704
|
+
const idle = this.sql.exec<{ t: number | null }>("SELECT MIN(at) AS t FROM routes WHERE thread_ts <> ''").one().t;
|
|
705
|
+
if (idle !== null) add(idle + ROUTE_IDLE_MS);
|
|
706
|
+
const oldestAudit = this.sql.exec<{ t: number | null }>("SELECT MIN(at) AS t FROM audit").one().t;
|
|
707
|
+
if (oldestAudit !== null) add(oldestAudit + ROUTE_IDLE_MS);
|
|
708
|
+
return c.length ? Math.min(...c) : null;
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
/** Is `ms` inside the JST daytime window intake.silent is evaluated in? */
|
|
712
|
+
inDaytime(ms: number): boolean {
|
|
713
|
+
return this.nextDaytime(ms) === ms;
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
// ======== internals
|
|
717
|
+
|
|
718
|
+
private run<T>(now: number, fn: () => T): T {
|
|
719
|
+
return this.tx(() => {
|
|
720
|
+
this.sync(now);
|
|
721
|
+
const out = fn();
|
|
722
|
+
this.reap(now);
|
|
723
|
+
return out;
|
|
724
|
+
});
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
/** Liveness, then due clocks, alerts and retention. Runs at the start of every entry point. */
|
|
728
|
+
private sync(now: number): void {
|
|
729
|
+
// 1. Liveness: online while the last ping or frame is less than LIVE_MS old.
|
|
730
|
+
const seen = new Map<string, number>();
|
|
731
|
+
for (const s of this.link.machines()) seen.set(s.machine, Math.max(seen.get(s.machine) ?? 0, s.lastSeen));
|
|
732
|
+
this.live = new Map();
|
|
733
|
+
for (const [m, t] of seen) {
|
|
734
|
+
if (this.pubkeyOf(m) === null) this.link.close(m, 4401, "revoked");
|
|
735
|
+
else if (now - t >= LIVE_MS) this.link.close(m, CLOSE_SILENT, "silent");
|
|
736
|
+
else this.live.set(m, t);
|
|
737
|
+
}
|
|
738
|
+
for (const m of this.sql.exec<MachineRow>("SELECT * FROM machines WHERE revoked_at IS NULL OR online = 1").toArray()) {
|
|
739
|
+
const t = this.live.get(m.machine);
|
|
740
|
+
if (t !== undefined) {
|
|
741
|
+
if (m.online !== 1) {
|
|
742
|
+
this.sql.exec(
|
|
743
|
+
"UPDATE machines SET online = 1, offline_since = NULL, first_seen = COALESCE(first_seen, ?), last_seen = ? WHERE machine = ?",
|
|
744
|
+
now, t, m.machine,
|
|
745
|
+
);
|
|
746
|
+
this.clearAlert("machine.silent", m.machine, now);
|
|
747
|
+
} else if (m.last_seen === null || t > m.last_seen) this.sql.exec("UPDATE machines SET last_seen = ? WHERE machine = ?", t, m.machine);
|
|
748
|
+
} else if (m.online === 1) {
|
|
749
|
+
// Silent sockets went offline when they crossed LIVE_MS; a closed one, now.
|
|
750
|
+
const last = seen.get(m.machine);
|
|
751
|
+
this.offline(m.machine, last !== undefined ? Math.min(now, last + LIVE_MS) : now, now);
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
// 2. Clocks, in deadline order.
|
|
755
|
+
for (const d of this.sql.exec<{ msg: number; label: string }>(
|
|
756
|
+
"SELECT msg, label FROM deliveries WHERE deadline IS NOT NULL AND deadline <= ? ORDER BY deadline, msg, label", now,
|
|
757
|
+
).toArray()) {
|
|
758
|
+
const r = this.row(d.msg, d.label);
|
|
759
|
+
if (!r || r.deadline === null || r.deadline > now) continue;
|
|
760
|
+
if (!ACTIVE.has(r.state)) {
|
|
761
|
+
this.sql.exec("UPDATE deliveries SET deadline = NULL WHERE msg = ? AND label = ?", r.msg, r.label);
|
|
762
|
+
continue;
|
|
763
|
+
}
|
|
764
|
+
const msg = this.msgBySeq(r.msg)!;
|
|
765
|
+
const route = this.routeOf(msg);
|
|
766
|
+
const why = r.state === "queued" ? `queued past ${route.queue_max_s} s`
|
|
767
|
+
: r.state === "accepted" || r.state === "read" ? `no done within ${route.ack_s} s`
|
|
768
|
+
: `no receipt within ${route.read_s} s`;
|
|
769
|
+
this.set(r, { state: "timeout", why, deadline: null }, now);
|
|
770
|
+
this.advance(msg, r.grp!, r.rank, now);
|
|
771
|
+
this.checkFinal(msg, now);
|
|
772
|
+
}
|
|
773
|
+
// 3. Alerts that open by themselves.
|
|
774
|
+
for (const m of this.sql.exec<{ machine: string; offline_since: number }>(
|
|
775
|
+
"SELECT machine, offline_since FROM machines WHERE revoked_at IS NULL AND online = 0 AND first_seen IS NOT NULL AND offline_since IS NOT NULL AND offline_since <= ?",
|
|
776
|
+
now - SILENT_MS,
|
|
777
|
+
).toArray()) this.openAlert("machine.silent", m.machine, now, `offline since ${iso(m.offline_since)}`);
|
|
778
|
+
for (const j of this.lateCandidates()) {
|
|
779
|
+
const base = j.last_ok ?? j.first_at;
|
|
780
|
+
if (now >= base + JOB_LATE_PERIODS * j.every_s * 1000) {
|
|
781
|
+
this.openAlert("job.late", `${j.machine}/${j.job}`, now, j.last_ok === null ? `no ok beat since ${iso(j.first_at)}` : `last ok beat ${iso(j.last_ok)}`);
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
if (this.inDaytime(now)) {
|
|
785
|
+
for (const a of this.sql.exec<{ app: string; last_event: number }>("SELECT app, last_event FROM apps WHERE last_event <= ?", now - INTAKE_SILENT_MS).toArray()) {
|
|
786
|
+
this.openAlert("intake.silent", a.app, now, `no events since ${iso(a.last_event)}`);
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
for (const w of this.waitingGroups()) {
|
|
790
|
+
if (now >= w.msg.at + this.routeOf(w.msg).read_s * 1000) this.openAlert("delivery.undeliverable", `${w.msg.id}#${w.grp}`, now, `waiting: ${w.why ?? "no rank reachable"}`);
|
|
791
|
+
}
|
|
792
|
+
// 4. Retention (q1): 7 days after intake, whatever the state.
|
|
793
|
+
const cutoff = now - RETAIN_MS;
|
|
794
|
+
for (const m of this.sql.exec<{ seq: number; id: string }>("SELECT seq, id FROM messages WHERE at <= ?", cutoff).toArray()) {
|
|
795
|
+
this.sql.exec("DELETE FROM deliveries WHERE msg = ?", m.seq);
|
|
796
|
+
this.sql.exec("DELETE FROM messages WHERE seq = ?", m.seq);
|
|
797
|
+
for (const a of this.sql.exec<{ subject: string }>(
|
|
798
|
+
"SELECT subject FROM alerts WHERE kind = 'delivery.undeliverable' AND state = 'open' AND substr(subject, 1, ?) = ?", m.id.length + 1, `${m.id}#`,
|
|
799
|
+
).toArray()) this.clearAlert("delivery.undeliverable", a.subject, now, "message expired");
|
|
800
|
+
}
|
|
801
|
+
this.sql.exec("DELETE FROM events WHERE at <= ?", cutoff);
|
|
802
|
+
this.sql.exec("DELETE FROM alerts WHERE state = 'cleared' AND updated_at <= ?", cutoff);
|
|
803
|
+
this.sql.exec("DELETE FROM routes WHERE thread_ts <> '' AND at <= ?", now - ROUTE_IDLE_MS);
|
|
804
|
+
this.sql.exec("DELETE FROM audit WHERE at <= ?", now - ROUTE_IDLE_MS);
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
/** Take machines whose sends failed offline, until none is left (offline handling may send, and fail, again). */
|
|
808
|
+
private reap(now: number): void {
|
|
809
|
+
while (this.dead.size) {
|
|
810
|
+
const m = this.dead.values().next().value!;
|
|
811
|
+
this.dead.delete(m);
|
|
812
|
+
if (this.live.has(m)) this.drop(m, now, 1011, "send failed");
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
/** Close a machine's socket now and handle it as offline. */
|
|
817
|
+
private drop(machine: string, now: number, code: number, reason: string): void {
|
|
818
|
+
this.link.close(machine, code, reason);
|
|
819
|
+
this.live.delete(machine);
|
|
820
|
+
this.offline(machine, now, now);
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
/** A machine went offline (q2): its unreceipted sends fail over at once. */
|
|
824
|
+
private offline(machine: string, since: number, now: number): void {
|
|
825
|
+
this.sql.exec("UPDATE machines SET online = 0, offline_since = ? WHERE machine = ?", since, machine);
|
|
826
|
+
for (const r of this.sql.exec<DeliveryRow>("SELECT * FROM deliveries WHERE machine = ? AND state = 'sent' ORDER BY msg, rank, label", machine).toArray()) {
|
|
827
|
+
const msg = this.msgBySeq(r.msg)!;
|
|
828
|
+
if (r.role === "observer") this.set(r, { state: "waiting", why: `${machine} went offline` }, now);
|
|
829
|
+
else {
|
|
830
|
+
this.set(r, { state: "offline", why: `${machine} went offline`, deadline: null }, now);
|
|
831
|
+
this.advance(msg, r.grp!, r.rank, now);
|
|
832
|
+
}
|
|
833
|
+
this.checkFinal(msg, now);
|
|
834
|
+
}
|
|
835
|
+
const dirty = new Set<string>();
|
|
836
|
+
for (const l of this.sql.exec<{ lane: string }>("SELECT lane FROM lanes WHERE machine = ?", machine).toArray()) this.reconcileLane(l.lane, now, dirty);
|
|
837
|
+
this.evalConflicts(this.sql.exec<{ lane: string }>("SELECT lane FROM lane_seen WHERE machine = ? AND listed = 1", machine).toArray().map((r) => r.lane), now);
|
|
838
|
+
this.directories(dirty);
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
private emit(machine: string, frame: T1Frame): void {
|
|
842
|
+
if (!this.link.send(machine, frame)) this.dead.add(machine);
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
private result(machine: string, ref: string, r: Result): void {
|
|
846
|
+
this.emit(machine, { v: AIP_VERSION, op: "result", ref, ...r });
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
// ---- routing
|
|
850
|
+
|
|
851
|
+
/** One pass over a group's ranks after rank `after` (0: from the start): send to the first reachable one. */
|
|
852
|
+
private advance(msg: MsgRow, letter: string, after: number, now: number): void {
|
|
853
|
+
const route = this.routeOf(msg);
|
|
854
|
+
const ranks = ranksOf(route, letter);
|
|
855
|
+
let rows = this.groupMap(msg.seq, letter);
|
|
856
|
+
if ([...rows.values()].some((r) => r.state === "done" || r.state === "shadow" || ACTIVE.has(r.state))) return;
|
|
857
|
+
const held = [...rows.values()].some((r) => HOLDING.has(r.state));
|
|
858
|
+
const why: string[] = [];
|
|
859
|
+
for (const c of ranks) {
|
|
860
|
+
if (c.rank <= after) continue;
|
|
861
|
+
// The fallback is for a message no rank could receive at all.
|
|
862
|
+
if (c.rank === 10 && held) break;
|
|
863
|
+
const row = rows.get(c.label);
|
|
864
|
+
if (row && NEVER_AGAIN.has(row.state)) continue;
|
|
865
|
+
const v = this.reach(c.lane, route.offline);
|
|
866
|
+
if ("machine" in v) return this.send(msg, c, "worker", row, v.machine, now);
|
|
867
|
+
if ("wait" in v) {
|
|
868
|
+
this.put(msg, c, "worker", row, { state: "waiting", why: v.why }, now);
|
|
869
|
+
return;
|
|
870
|
+
}
|
|
871
|
+
this.put(msg, c, "worker", row, { state: "skipped", why: v.why }, now);
|
|
872
|
+
why.push(`${c.label}: ${v.why}`);
|
|
873
|
+
}
|
|
874
|
+
// Nothing sent. Somebody holds it: exhausted, stays open, no alert.
|
|
875
|
+
rows = this.groupMap(msg.seq, letter);
|
|
876
|
+
if ([...rows.values()].some((r) => HOLDING.has(r.state))) return;
|
|
877
|
+
// Nobody holds it: wait at the lowest rank that may be retried, else it is undeliverable.
|
|
878
|
+
const retry = ranks.find((c) => {
|
|
879
|
+
const r = rows.get(c.label);
|
|
880
|
+
return !r || !NEVER_AGAIN.has(r.state);
|
|
881
|
+
});
|
|
882
|
+
if (retry) {
|
|
883
|
+
const r = rows.get(retry.label);
|
|
884
|
+
this.put(msg, retry, "worker", r, { state: "waiting", why: r?.why ?? why[0] ?? "no rank reachable" }, now);
|
|
885
|
+
} else {
|
|
886
|
+
this.openAlert("delivery.undeliverable", `${msg.id}#${letter}`, now, `no rank left (${[...rows.values()].map((r) => `${r.label} ${r.state}`).join(", ")})`);
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
/** An observer: sent when its lane's machine is online, else waiting until it is. No clocks, no failover. */
|
|
891
|
+
private observe(msg: MsgRow, label: string, address: string, now: number): void {
|
|
892
|
+
const row = this.row(msg.seq, label);
|
|
893
|
+
if (row && row.state !== "waiting") return;
|
|
894
|
+
const c = { label, rank: 0, address, lane: laneOf(address) };
|
|
895
|
+
const placed = this.lane(c.lane);
|
|
896
|
+
if (placed && this.live.has(placed.machine)) return this.send(msg, c, "observer", row, placed.machine, now);
|
|
897
|
+
this.put(msg, c, "observer", row, { state: "waiting", why: placed ? `${placed.machine} is offline` : `lane ${c.lane} is not placed` }, now);
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
private reach(lane: string, offline: Offline): { machine: string } | { wait: true; why: string } | { why: string } {
|
|
901
|
+
const placed = this.lane(lane);
|
|
902
|
+
if (!placed) return { why: `lane ${lane} is not placed` };
|
|
903
|
+
const m = placed.machine;
|
|
904
|
+
if (!this.live.has(m)) return offline === "queue" ? { wait: true, why: `${m} is offline (offline: queue)` } : { why: `${m} is offline` };
|
|
905
|
+
const seen = this.sql.exec<SeenRow>("SELECT * FROM lane_seen WHERE lane = ? AND machine = ?", lane, m).toArray()[0];
|
|
906
|
+
if (!seen || !seen.listed) return { why: `${m} does not list ${lane}` };
|
|
907
|
+
if (seen.health === "down" || seen.health === "limited") return { why: `${lane} on ${m} is ${seen.health}` };
|
|
908
|
+
return { machine: m };
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
private send(msg: MsgRow, c: Candidate, role: "worker" | "observer", row: DeliveryRow | undefined, machine: string, now: number): void {
|
|
912
|
+
const route = this.routeOf(msg);
|
|
913
|
+
const attempts = (row?.attempts ?? 0) + 1;
|
|
914
|
+
const token = role === "worker" ? (row?.token ?? crypto.randomUUID()) : null;
|
|
915
|
+
this.put(msg, c, role, row, {
|
|
916
|
+
state: "sent", why: null, machine, attempts, token, sent_at: now, accepted_at: null, deadline: role === "worker" ? now + route.read_s * 1000 : null,
|
|
917
|
+
}, now);
|
|
918
|
+
// Another rank of this group that was waiting is no longer what the group waits on.
|
|
919
|
+
if (role === "worker") {
|
|
920
|
+
this.sql.exec(
|
|
921
|
+
"UPDATE deliveries SET state = 'skipped', why = ?, at = ? WHERE msg = ? AND grp = ? AND state = 'waiting' AND label != ?",
|
|
922
|
+
`${c.label} sent`, now, msg.seq, grpOf(c.label), c.label,
|
|
923
|
+
);
|
|
924
|
+
}
|
|
925
|
+
this.emit(machine, this.deliverFrame(msg, c.label, c.address, role, attempts, token, now));
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
/** Re-send a `sent` row on its machine's new socket (attempt + 1, its clock unchanged). */
|
|
929
|
+
private resend(msg: MsgRow, r: DeliveryRow, now: number): void {
|
|
930
|
+
this.sql.exec("UPDATE deliveries SET attempts = attempts + 1, at = ? WHERE msg = ? AND label = ?", now, r.msg, r.label);
|
|
931
|
+
this.emit(r.machine!, this.deliverFrame(msg, r.label, r.address, r.role, r.attempts + 1, r.token, now));
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
private deliverFrame(msg: MsgRow, label: string, address: string, role: "worker" | "observer", attempt: number, token: string | null, now: number): T1Frame {
|
|
935
|
+
const src: Source = {
|
|
936
|
+
kind: "slack", workspace: msg.team, app: msg.app, channel: msg.channel, ts: msg.ts,
|
|
937
|
+
...(msg.thread_ts !== null ? { thread_ts: msg.thread_ts } : {}),
|
|
938
|
+
user: { id: msg.user, human: msg.human === 1 },
|
|
939
|
+
};
|
|
940
|
+
const text = msg.text ?? "";
|
|
941
|
+
const envelope: Envelope = {
|
|
942
|
+
v: AIP_VERSION, key: `${msg.id}#${label}`, id: msg.id, to: address, role, label, attempt, src,
|
|
943
|
+
text: text.length > MAX_TEXT_CHARS ? `${text.slice(0, MAX_TEXT_CHARS)} […]` : text,
|
|
944
|
+
...(msg.files !== null ? { files: JSON.parse(msg.files) as string[] } : {}),
|
|
945
|
+
...(token !== null ? { ack: { token } } : {}),
|
|
946
|
+
};
|
|
947
|
+
return { v: AIP_VERSION, op: "deliver", envelope, ...(now - msg.at > LATE_MS ? { late: true } : {}) };
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
/** A machine's first heartbeat after it authenticated (re-send its `sent` rows), or any change: retry waiting
|
|
951
|
+
* groups and observers. In message order. */
|
|
952
|
+
private replay(machine: string | null, now: number): void {
|
|
953
|
+
for (const d of this.sql.exec<{ msg: number; label: string }>(
|
|
954
|
+
"SELECT msg, label FROM deliveries WHERE state = 'waiting' OR (state = 'sent' AND machine = ?) ORDER BY msg, rank, label", machine,
|
|
955
|
+
).toArray()) {
|
|
956
|
+
const r = this.row(d.msg, d.label);
|
|
957
|
+
if (!r) continue;
|
|
958
|
+
const msg = this.msgBySeq(r.msg)!;
|
|
959
|
+
if (r.state === "sent" && r.machine === machine) this.resend(msg, r, now);
|
|
960
|
+
else if (r.state === "waiting") {
|
|
961
|
+
if (r.role === "observer") this.observe(msg, r.label, r.address, now);
|
|
962
|
+
else this.advance(msg, r.grp!, 0, now);
|
|
963
|
+
}
|
|
964
|
+
this.checkFinal(msg, now);
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
/** A row of the group reached somebody: its undeliverable alert (if any) clears. */
|
|
969
|
+
private delivered(msg: MsgRow, grp: string, now: number): void {
|
|
970
|
+
this.clearAlert("delivery.undeliverable", `${msg.id}#${grp}`, now, "delivered");
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
/** Final: every group done or exhausted and every observer receipted. Then the text goes (q1). */
|
|
974
|
+
private checkFinal(msg: MsgRow, now: number): void {
|
|
975
|
+
const cur = this.msgBySeq(msg.seq);
|
|
976
|
+
if (!cur || cur.final === 1) return;
|
|
977
|
+
const route = this.routeOf(cur);
|
|
978
|
+
const rows = this.sql.exec<DeliveryRow>("SELECT * FROM deliveries WHERE msg = ?", cur.seq).toArray();
|
|
979
|
+
for (const letter of lettersOf(route)) {
|
|
980
|
+
const g = rows.filter((r) => r.grp === letter);
|
|
981
|
+
if (g.some((r) => r.state === "done" || r.state === "shadow")) continue;
|
|
982
|
+
if (!g.length || g.some((r) => ACTIVE.has(r.state) || r.state === "waiting")) return;
|
|
983
|
+
}
|
|
984
|
+
for (const address of route.cc) {
|
|
985
|
+
const r = rows.find((x) => x.label === `cc:${laneOf(address)}`);
|
|
986
|
+
if (!r || r.state === "sent" || r.state === "waiting") return;
|
|
987
|
+
}
|
|
988
|
+
this.sql.exec("UPDATE messages SET text = NULL, final = 1, final_at = ? WHERE seq = ?", now, cur.seq);
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
// ---- lane directory (q3: auto-allowed, recorded)
|
|
992
|
+
|
|
993
|
+
/** Machine `m` lists `lane` in a heartbeat. */
|
|
994
|
+
private placeListed(lane: string, m: string, cwd: string | undefined, now: number, dirty: Set<string>): void {
|
|
995
|
+
const cur = this.lane(lane);
|
|
996
|
+
if (!cur) {
|
|
997
|
+
this.place(lane, m, cwd ?? null, now);
|
|
998
|
+
dirty.add(m);
|
|
999
|
+
} else if (cur.machine !== m && (!this.live.has(cur.machine) || !this.listedBy(lane, cur.machine))) {
|
|
1000
|
+
this.move(lane, m, cwd ?? cur.cwd, now, "lane.move");
|
|
1001
|
+
dirty.add(m).add(cur.machine);
|
|
1002
|
+
}
|
|
1003
|
+
// On m already: health only (lane_seen). On another online machine that lists it: a conflict (evalConflicts).
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
/** A lane whose machine is offline or no longer lists it moves to another online machine that lists it. */
|
|
1007
|
+
private reconcileLane(lane: string, now: number, dirty: Set<string>): void {
|
|
1008
|
+
const cur = this.lane(lane);
|
|
1009
|
+
if (!cur || (this.live.has(cur.machine) && this.listedBy(lane, cur.machine))) return;
|
|
1010
|
+
const to = this.sql.exec<SeenRow>("SELECT * FROM lane_seen WHERE lane = ? AND listed = 1 AND machine != ? ORDER BY at DESC, machine", lane, cur.machine)
|
|
1011
|
+
.toArray().find((s) => this.live.has(s.machine));
|
|
1012
|
+
if (!to) return;
|
|
1013
|
+
this.move(lane, to.machine, to.cwd ?? cur.cwd, now, "lane.move");
|
|
1014
|
+
dirty.add(to.machine).add(cur.machine);
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
/** lane.conflict: open (once per episode, with one audit row) while two online machines list the lane. */
|
|
1018
|
+
private evalConflicts(lanes: Iterable<string>, now: number): void {
|
|
1019
|
+
for (const lane of new Set(lanes)) {
|
|
1020
|
+
const listers = this.sql.exec<{ machine: string }>("SELECT machine FROM lane_seen WHERE lane = ? AND listed = 1 ORDER BY machine", lane).toArray()
|
|
1021
|
+
.map((r) => r.machine).filter((m) => this.live.has(m));
|
|
1022
|
+
if (listers.length > 1) this.conflict(lane, listers, now);
|
|
1023
|
+
else this.clearAlert("lane.conflict", lane, now, listers.length ? `only ${listers[0]} lists it` : "nobody lists it");
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
private conflict(lane: string, machines: string[], now: number): void {
|
|
1028
|
+
const placed = this.lane(lane)?.machine ?? null;
|
|
1029
|
+
const detail = `placed on ${placed}; listed by ${machines.join(", ")}`;
|
|
1030
|
+
if (this.openAlert("lane.conflict", lane, now, detail)) this.audit(now, "lane.conflict", lane, placed, detail);
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
private place(lane: string, machine: string, cwd: string | null, now: number): void {
|
|
1034
|
+
this.sql.exec("INSERT INTO lanes (lane, machine, cwd, first_seen, placed_at) VALUES (?, ?, ?, ?, ?)", lane, machine, cwd, now, now);
|
|
1035
|
+
this.audit(now, "lane.new", lane, machine, cwd);
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
private move(lane: string, to: string, cwd: string | null, now: number, kind: string): void {
|
|
1039
|
+
const from = this.lane(lane)!.machine;
|
|
1040
|
+
this.sql.exec("UPDATE lanes SET machine = ?, cwd = ?, placed_at = ?, prev_machine = ? WHERE lane = ?", to, cwd, now, from, lane);
|
|
1041
|
+
this.audit(now, kind, lane, to, `from ${from}`);
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
private directories(machines: Set<string>): void {
|
|
1045
|
+
for (const m of machines) if (this.live.has(m)) this.emit(m, { v: AIP_VERSION, op: "directory", lanes: this.placedOn(m) });
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
private placedOn(machine: string): LaneEntry[] {
|
|
1049
|
+
return this.sql.exec<{ lane: string; cwd: string | null }>("SELECT lane, cwd FROM lanes WHERE machine = ? ORDER BY lane", machine).toArray()
|
|
1050
|
+
.map((l) => (l.cwd !== null ? { lane: l.lane, cwd: l.cwd } : { lane: l.lane }));
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
private listedBy(lane: string, machine: string): boolean {
|
|
1054
|
+
return this.sql.exec<{ listed: number }>("SELECT listed FROM lane_seen WHERE lane = ? AND machine = ?", lane, machine).toArray()[0]?.listed === 1;
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
// ---- jobs
|
|
1058
|
+
|
|
1059
|
+
private recordBeat(machine: string, b: JobBeat, now: number): void {
|
|
1060
|
+
const at = Math.min(b.at, now);
|
|
1061
|
+
this.sql.exec(
|
|
1062
|
+
`INSERT INTO jobs (machine, job, ok, at, every_s, last_ok, first_at, detail) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
1063
|
+
ON CONFLICT (machine, job) DO UPDATE SET ok = excluded.ok, at = excluded.at, every_s = excluded.every_s, detail = excluded.detail,
|
|
1064
|
+
last_ok = CASE WHEN excluded.ok = 1 THEN MAX(COALESCE(jobs.last_ok, 0), excluded.at) ELSE jobs.last_ok END`,
|
|
1065
|
+
machine, b.job, b.ok ? 1 : 0, at, b.every_s, b.ok ? at : null, now, b.detail?.slice(0, 200) ?? null,
|
|
1066
|
+
);
|
|
1067
|
+
if (b.ok) this.clearAlert("job.late", `${machine}/${b.job}`, now, "ok beat");
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
/** Jobs of enrolled machines whose job.late is not open. */
|
|
1071
|
+
private lateCandidates(): JobRow[] {
|
|
1072
|
+
return this.sql.exec<JobRow>(
|
|
1073
|
+
`SELECT j.* FROM jobs j JOIN machines m ON m.machine = j.machine WHERE m.revoked_at IS NULL
|
|
1074
|
+
AND NOT EXISTS (SELECT 1 FROM alerts a WHERE a.kind = 'job.late' AND a.subject = j.machine || '/' || j.job AND a.state = 'open')`,
|
|
1075
|
+
).toArray();
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
// ---- alerts (state only in step 1; every change goes to the online machines as an alert frame)
|
|
1079
|
+
|
|
1080
|
+
/** true when it opened now (it was not open). */
|
|
1081
|
+
private openAlert(kind: AlertKind, subject: string, now: number, detail: string): boolean {
|
|
1082
|
+
if (this.isOpen(kind, subject)) return false;
|
|
1083
|
+
this.sql.exec(
|
|
1084
|
+
`INSERT INTO alerts (kind, subject, state, since, updated_at, detail) VALUES (?, ?, 'open', ?, ?, ?)
|
|
1085
|
+
ON CONFLICT (kind, subject) DO UPDATE SET state = 'open', since = excluded.since, updated_at = excluded.updated_at, detail = excluded.detail`,
|
|
1086
|
+
kind, subject, now, now, detail,
|
|
1087
|
+
);
|
|
1088
|
+
this.broadcastAlert(kind, subject, "open", now, detail);
|
|
1089
|
+
return true;
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
private clearAlert(kind: AlertKind, subject: string, now: number, detail?: string): void {
|
|
1093
|
+
if (!this.isOpen(kind, subject)) return;
|
|
1094
|
+
this.sql.exec(
|
|
1095
|
+
"UPDATE alerts SET state = 'cleared', since = ?, updated_at = ?, detail = COALESCE(?, detail) WHERE kind = ? AND subject = ?",
|
|
1096
|
+
now, now, detail ?? null, kind, subject,
|
|
1097
|
+
);
|
|
1098
|
+
this.broadcastAlert(kind, subject, "cleared", now, detail);
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
private isOpen(kind: AlertKind, subject: string): boolean {
|
|
1102
|
+
return this.sql.exec<{ state: string }>("SELECT state FROM alerts WHERE kind = ? AND subject = ?", kind, subject).toArray()[0]?.state === "open";
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
private broadcastAlert(kind: AlertKind, subject: string, state: "open" | "cleared", since: number, detail: string | undefined): void {
|
|
1106
|
+
for (const m of this.live.keys()) {
|
|
1107
|
+
this.emit(m, { v: AIP_VERSION, op: "alert", alert: { kind, subject, state, since, ...(detail !== undefined ? { detail } : {}) } });
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
/** The first instant at or after `t` inside the JST daytime window. */
|
|
1112
|
+
private nextDaytime(t: number): number {
|
|
1113
|
+
const jst = t + JST_MS;
|
|
1114
|
+
const day = Math.floor(jst / DAY_MS) * DAY_MS;
|
|
1115
|
+
const start = day + this.daytime.start * 3_600_000;
|
|
1116
|
+
const end = day + this.daytime.end * 3_600_000;
|
|
1117
|
+
if (jst < start) return start - JST_MS;
|
|
1118
|
+
if (jst < end) return t;
|
|
1119
|
+
return start + DAY_MS - JST_MS;
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
private waitingGroups(): { msg: MsgRow; grp: string; why: string | null }[] {
|
|
1123
|
+
return this.sql.exec<{ msg: number; grp: string; why: string | null }>(
|
|
1124
|
+
"SELECT msg, grp, MIN(why) AS why FROM deliveries WHERE state = 'waiting' AND role = 'worker' GROUP BY msg, grp ORDER BY msg, grp",
|
|
1125
|
+
).toArray().flatMap((w) => {
|
|
1126
|
+
const msg = this.msgBySeq(w.msg);
|
|
1127
|
+
return msg ? [{ msg, grp: w.grp, why: w.why }] : [];
|
|
1128
|
+
});
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
// ---- rows
|
|
1132
|
+
|
|
1133
|
+
private audit(now: number, kind: string, lane: string | null, machine: string | null, detail: string | null): void {
|
|
1134
|
+
this.sql.exec("INSERT INTO audit (at, kind, lane, machine, detail) VALUES (?, ?, ?, ?, ?)", now, kind, lane, machine, detail);
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
private machine(machine: string): MachineRow | undefined {
|
|
1138
|
+
return this.sql.exec<MachineRow>("SELECT * FROM machines WHERE machine = ?", machine).toArray()[0];
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
private lane(lane: string): LaneRow | undefined {
|
|
1142
|
+
return this.sql.exec<LaneRow>("SELECT * FROM lanes WHERE lane = ?", lane).toArray()[0];
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
private route(channel: string, thread_ts: string): Route | undefined {
|
|
1146
|
+
const r = this.sql.exec<{ spec: string }>("SELECT spec FROM routes WHERE channel = ? AND thread_ts = ?", channel, thread_ts).toArray()[0];
|
|
1147
|
+
return r ? (JSON.parse(r.spec) as Route) : undefined;
|
|
1148
|
+
}
|
|
1149
|
+
|
|
1150
|
+
private saveRoute(r: Route, now: number): void {
|
|
1151
|
+
this.sql.exec(
|
|
1152
|
+
"INSERT INTO routes (channel, thread_ts, spec, at) VALUES (?, ?, ?, ?) ON CONFLICT (channel, thread_ts) DO UPDATE SET spec = excluded.spec, at = excluded.at",
|
|
1153
|
+
r.channel, r.thread_ts, JSON.stringify(r), now,
|
|
1154
|
+
);
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
/** A thread's row claimed for `lane`: a copy of the channel default with b1 replaced, or {b1} alone. */
|
|
1158
|
+
private claimRow(channel: string, thread_ts: string, lane: string): Route {
|
|
1159
|
+
const def = this.route(channel, "");
|
|
1160
|
+
const base = def ? { ...def, to: { ...def.to }, cc: [...def.cc] } : normalizeRoute({ channel, to: {} });
|
|
1161
|
+
return { ...base, channel, thread_ts, to: { ...base.to, b1: `lane:${lane}` } };
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
private routeOf(msg: MsgRow): Route {
|
|
1165
|
+
return JSON.parse(msg.route) as Route;
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
private msgById(id: string): MsgRow | undefined {
|
|
1169
|
+
return this.sql.exec<MsgRow>("SELECT * FROM messages WHERE id = ?", id).toArray()[0];
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
private msgBySeq(seq: number): MsgRow | undefined {
|
|
1173
|
+
return this.sql.exec<MsgRow>("SELECT * FROM messages WHERE seq = ?", seq).toArray()[0];
|
|
1174
|
+
}
|
|
1175
|
+
|
|
1176
|
+
private row(msg: number, label: string): DeliveryRow | undefined {
|
|
1177
|
+
return this.sql.exec<DeliveryRow>("SELECT * FROM deliveries WHERE msg = ? AND label = ?", msg, label).toArray()[0];
|
|
1178
|
+
}
|
|
1179
|
+
|
|
1180
|
+
private groupRows(msg: number, grp: string): DeliveryRow[] {
|
|
1181
|
+
return this.sql.exec<DeliveryRow>("SELECT * FROM deliveries WHERE msg = ? AND grp = ? ORDER BY rank", msg, grp).toArray();
|
|
1182
|
+
}
|
|
1183
|
+
|
|
1184
|
+
private groupMap(msg: number, grp: string): Map<string, DeliveryRow> {
|
|
1185
|
+
return new Map(this.groupRows(msg, grp).map((r) => [r.label, r]));
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
/** Insert or update one ledger row. */
|
|
1189
|
+
private put(
|
|
1190
|
+
msg: MsgRow, c: Candidate, role: "worker" | "observer", row: DeliveryRow | undefined,
|
|
1191
|
+
f: Partial<Pick<DeliveryRow, "state" | "why" | "machine" | "attempts" | "token" | "sent_at" | "accepted_at" | "deadline">>, now: number,
|
|
1192
|
+
): void {
|
|
1193
|
+
if (row) return this.set(row, f, now);
|
|
1194
|
+
const grp = role === "worker" ? grpOf(c.label) : null;
|
|
1195
|
+
this.sql.exec(
|
|
1196
|
+
`INSERT INTO deliveries (msg, label, grp, rank, role, address, lane, machine, state, why, attempts, token, sent_at, accepted_at, deadline, at)
|
|
1197
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
1198
|
+
msg.seq, c.label, grp, c.rank, role, c.address, c.lane, f.machine ?? null, f.state ?? "waiting", f.why ?? null, f.attempts ?? 0,
|
|
1199
|
+
f.token ?? null, f.sent_at ?? null, f.accepted_at ?? null, f.deadline ?? null, now,
|
|
1200
|
+
);
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
private set(
|
|
1204
|
+
row: DeliveryRow, f: Partial<Pick<DeliveryRow, "state" | "why" | "machine" | "attempts" | "token" | "sent_at" | "accepted_at" | "deadline">>, now: number,
|
|
1205
|
+
): void {
|
|
1206
|
+
const keys = Object.keys(f) as (keyof typeof f)[];
|
|
1207
|
+
if (!keys.length) return;
|
|
1208
|
+
this.sql.exec(
|
|
1209
|
+
`UPDATE deliveries SET ${keys.map((k) => `${k} = ?`).join(", ")}, at = ? WHERE msg = ? AND label = ?`,
|
|
1210
|
+
...keys.map((k) => (f[k] ?? null) as SqlValue), now, row.msg, row.label,
|
|
1211
|
+
);
|
|
1212
|
+
Object.assign(row, f);
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
function fromMatches(from: string, m: RoutedMessage): boolean {
|
|
1217
|
+
if (m.self) return false; // the receiving app's own posts are never delivered
|
|
1218
|
+
if (from === "human") return m.human;
|
|
1219
|
+
if (from === "any") return true;
|
|
1220
|
+
return m.user === from;
|
|
1221
|
+
}
|
|
1222
|
+
|