@capybara-hq/kernel 0.1.0-rc.80 → 0.1.0-rc.81
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/admin/outbox-dead.service.js +133 -120
- package/dist/background/store.js +78 -67
- package/dist/background/tasks.service.d.ts +6 -0
- package/dist/background/tasks.service.js +3 -0
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/catalog/plugin-import.js +45 -40
- package/dist/catalog/scope-sync-workers.js +3 -0
- package/dist/channels/inbound.d.ts +6 -1
- package/dist/channels/inbound.js +18 -1
- package/dist/client/client-reports.service.js +9 -6
- package/dist/config/schema.d.ts +5 -0
- package/dist/config/schema.js +6 -0
- package/dist/conversations/attachments.service.js +101 -96
- package/dist/conversations/events.d.ts +7 -0
- package/dist/conversations/events.js +9 -0
- package/dist/ctx/bus.js +5 -3
- package/dist/ctx/queue.js +4 -2
- package/dist/db/pool.d.ts +6 -0
- package/dist/db/pool.js +3 -2
- package/dist/devices/legacy-cleanup.job.js +73 -70
- package/dist/dial-in/gateway.d.ts +8 -0
- package/dist/dial-in/gateway.js +22 -2
- package/dist/extensions/admin-ops.js +22 -19
- package/dist/extensions/lifecycle-hooks.js +3 -1
- package/dist/http/app.js +3 -1
- package/dist/http/plugin-dispatch.js +8 -0
- package/dist/identity/auth.guard.js +13 -3
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -0
- package/dist/infra/database/database.module.js +1 -0
- package/dist/infra/database/org-scope.d.ts +59 -0
- package/dist/infra/database/org-scope.js +68 -0
- package/dist/infra/database/rls-role.d.ts +11 -0
- package/dist/infra/database/rls-role.js +33 -0
- package/dist/infra/database/scoped-dialect.d.ts +18 -0
- package/dist/infra/database/scoped-dialect.js +245 -0
- package/dist/infra/outbox/outbox.dispatcher.js +98 -90
- package/dist/infra/outbox/outbox.service.js +29 -26
- package/dist/infra/queue/run-job.d.ts +8 -2
- package/dist/infra/queue/run-job.js +16 -3
- package/dist/infra/schedule/locked-tick.js +12 -4
- package/dist/infra/schedule/scheduled-runs.js +3 -1
- package/dist/lifecycle/kernel-lifecycle.d.ts +1 -0
- package/dist/lifecycle/kernel-lifecycle.js +16 -1
- package/dist/orgs/org.guard.js +4 -0
- package/dist/platform/sealed-reveals.js +9 -6
- package/dist/runtime/maintenance.js +6 -1
- package/dist/runtime/run-execution.d.ts +1 -0
- package/dist/runtime/run-execution.js +5 -0
- package/dist/runtime/run-orphan-check.job.js +20 -15
- package/dist/sandbox/legacy-retirement.js +438 -397
- package/dist/sandbox/modes.d.ts +10 -0
- package/dist/sandbox/modes.js +23 -0
- package/dist/sandbox/operation-reconcile.job.d.ts +14 -1
- package/dist/sandbox/operation-reconcile.job.js +35 -3
- package/dist/sandbox/permission-config-publication.js +83 -77
- package/dist/sandbox/sandbox.service.d.ts +24 -0
- package/dist/sandbox/sandbox.service.js +159 -62
- package/dist/schedules/store.js +17 -14
- package/dist/tools/builtins/sandbox/bash.js +16 -1
- package/dist/tools/drift.js +31 -24
- package/dist/tools/outputs.js +20 -17
- package/package.json +2 -2
- package/src/migrations/0182_rls_policies.sql +202 -0
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
import { CompiledQuery, PostgresDialect, } from "kysely";
|
|
2
|
+
import { currentScope, scopeKey, unscopedQueryCheck } from "./org-scope.js";
|
|
3
|
+
const SET_SCOPE = "select set_config('capybara.org_id', $1, $4), set_config('capybara.scope', $2, $4), " +
|
|
4
|
+
"set_config('capybara.rls', $3, $4)";
|
|
5
|
+
/** The three settings for `scope`; an unscoped context sends empty values (fail closed). */
|
|
6
|
+
function setScopeQuery(scope, rls, local) {
|
|
7
|
+
const orgId = scope?.kind === "org" ? scope.orgId : "";
|
|
8
|
+
const kind = scope?.kind ?? "";
|
|
9
|
+
return CompiledQuery.raw(SET_SCOPE, [orgId, kind, rls, local]);
|
|
10
|
+
}
|
|
11
|
+
/** Tables of the `capybara` schema with an `org_id` column (for the unscoped-query check). */
|
|
12
|
+
const ORG_TABLES_SQL = "select table_name from information_schema.columns " +
|
|
13
|
+
"where table_schema = 'capybara' and column_name = 'org_id'";
|
|
14
|
+
const TABLE_REF = /"capybara"\."([a-z0-9_]+)"|\bcapybara\.([a-z0-9_]+)/g;
|
|
15
|
+
/**
|
|
16
|
+
* One checkout of a pool connection. Before a query runs, the scope of the caller's async context
|
|
17
|
+
* is put on the connection unless it is already there: session-level (`set_config(…, false)`)
|
|
18
|
+
* outside a transaction, transaction-local (`true`) inside one, the first right after `BEGIN`.
|
|
19
|
+
* A fresh checkout knows nothing about the session's values, so its first query always sets all
|
|
20
|
+
* three: whatever an earlier holder left on the connection is overwritten before it can be read,
|
|
21
|
+
* and a returned connection carries no scope into its next user. Queries on one checkout run one
|
|
22
|
+
* after another (as pg runs them anyway), so a scope change and the query it precedes are never
|
|
23
|
+
* split by another query of the same transaction.
|
|
24
|
+
*/
|
|
25
|
+
class ScopedConnection {
|
|
26
|
+
inner;
|
|
27
|
+
rls;
|
|
28
|
+
orgTables;
|
|
29
|
+
/** The scope key now on the connection; undefined when unknown (fresh, or after a commit). */
|
|
30
|
+
applied;
|
|
31
|
+
inTransaction = false;
|
|
32
|
+
tail = Promise.resolve();
|
|
33
|
+
constructor(inner, rls, orgTables) {
|
|
34
|
+
this.inner = inner;
|
|
35
|
+
this.rls = rls;
|
|
36
|
+
this.orgTables = orgTables;
|
|
37
|
+
}
|
|
38
|
+
// cancellation (an aborted query) goes to the inner connection, which knows the backend; the
|
|
39
|
+
// kernel passes no abort signal to queries, so terminating a whole session is never asked for
|
|
40
|
+
cancelQuery(provider) {
|
|
41
|
+
return this.inner.cancelQuery?.(provider) ?? Promise.resolve();
|
|
42
|
+
}
|
|
43
|
+
collectSessionInfo() {
|
|
44
|
+
return this.inner.collectSessionInfo?.() ?? Promise.resolve();
|
|
45
|
+
}
|
|
46
|
+
/** Runs `fn` after every earlier operation of this checkout settled. */
|
|
47
|
+
serial(fn) {
|
|
48
|
+
const run = this.tail.then(fn, fn);
|
|
49
|
+
this.tail = run.catch(() => { });
|
|
50
|
+
return run;
|
|
51
|
+
}
|
|
52
|
+
async ensure(scope) {
|
|
53
|
+
const key = scopeKey(scope);
|
|
54
|
+
if (this.applied === key)
|
|
55
|
+
return;
|
|
56
|
+
this.applied = undefined;
|
|
57
|
+
await this.inner.executeQuery(setScopeQuery(scope, this.rls, this.inTransaction));
|
|
58
|
+
this.applied = key;
|
|
59
|
+
}
|
|
60
|
+
async check(scope, sql) {
|
|
61
|
+
const check = unscopedQueryCheck();
|
|
62
|
+
if (!check || scope)
|
|
63
|
+
return;
|
|
64
|
+
const tables = await this.orgTables(this.inner);
|
|
65
|
+
for (const m of sql.matchAll(TABLE_REF)) {
|
|
66
|
+
const table = m[1] ?? m[2];
|
|
67
|
+
if (table && tables.has(table))
|
|
68
|
+
check(table, sql);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
executeQuery(query) {
|
|
72
|
+
const scope = currentScope();
|
|
73
|
+
return this.serial(async () => {
|
|
74
|
+
await this.check(scope, query.sql);
|
|
75
|
+
await this.ensure(scope);
|
|
76
|
+
return this.inner.executeQuery(query);
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* A cursor holds this checkout until it is closed: the scope is set and the stream read inside
|
|
81
|
+
* one serial step, so no query of another scope runs in between.
|
|
82
|
+
*/
|
|
83
|
+
async *streamQuery(query, chunkSize) {
|
|
84
|
+
const scope = currentScope();
|
|
85
|
+
let release = () => { };
|
|
86
|
+
const held = new Promise((resolve) => {
|
|
87
|
+
release = resolve;
|
|
88
|
+
});
|
|
89
|
+
let ready = () => { };
|
|
90
|
+
const started = new Promise((resolve, reject) => {
|
|
91
|
+
ready = (error) => (error === undefined ? resolve() : reject(error));
|
|
92
|
+
});
|
|
93
|
+
void this.serial(async () => {
|
|
94
|
+
try {
|
|
95
|
+
await this.check(scope, query.sql);
|
|
96
|
+
await this.ensure(scope);
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
ready(error ?? new Error("scope setup failed"));
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
ready();
|
|
103
|
+
await held;
|
|
104
|
+
});
|
|
105
|
+
try {
|
|
106
|
+
await started;
|
|
107
|
+
yield* this.inner.streamQuery(query, chunkSize);
|
|
108
|
+
}
|
|
109
|
+
finally {
|
|
110
|
+
release();
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
/** `BEGIN`, then the scope of the caller transaction-local, as the transaction's first statement. */
|
|
114
|
+
begin(driver, settings) {
|
|
115
|
+
const scope = currentScope();
|
|
116
|
+
return this.serial(async () => {
|
|
117
|
+
await driver.beginTransaction(this.inner, settings);
|
|
118
|
+
this.inTransaction = true;
|
|
119
|
+
this.applied = undefined;
|
|
120
|
+
try {
|
|
121
|
+
await this.ensure(scope);
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
// Kysely rolls back only a transaction whose begin resolved: end this one here, or the
|
|
125
|
+
// connection would return to the pool inside it (best effort; the error is the caller's)
|
|
126
|
+
await driver.rollbackTransaction(this.inner).catch(() => { });
|
|
127
|
+
this.inTransaction = false;
|
|
128
|
+
this.applied = undefined;
|
|
129
|
+
throw error;
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
/** `COMMIT` / `ROLLBACK`: the local values end, the session's (unknown here) apply again. */
|
|
134
|
+
end(fn) {
|
|
135
|
+
return this.serial(async () => {
|
|
136
|
+
try {
|
|
137
|
+
await fn();
|
|
138
|
+
}
|
|
139
|
+
finally {
|
|
140
|
+
this.inTransaction = false;
|
|
141
|
+
this.applied = undefined;
|
|
142
|
+
}
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* A savepoint statement, in order with the queries. A rollback to a savepoint also undoes a
|
|
147
|
+
* scope set after it, so the scope on the connection is unknown again.
|
|
148
|
+
*/
|
|
149
|
+
step(fn, rollsBack = false) {
|
|
150
|
+
return this.serial(async () => {
|
|
151
|
+
try {
|
|
152
|
+
await fn();
|
|
153
|
+
}
|
|
154
|
+
finally {
|
|
155
|
+
if (rollsBack)
|
|
156
|
+
this.applied = undefined;
|
|
157
|
+
}
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Wraps Kysely's Postgres driver so every connection carries the caller's org scope
|
|
163
|
+
* ({@link ScopedConnection}). Everything else (pooling, cancellation, savepoints) is the inner
|
|
164
|
+
* driver's.
|
|
165
|
+
*/
|
|
166
|
+
class ScopedDriver {
|
|
167
|
+
inner;
|
|
168
|
+
rls;
|
|
169
|
+
tables;
|
|
170
|
+
constructor(inner, rls) {
|
|
171
|
+
this.inner = inner;
|
|
172
|
+
this.rls = rls;
|
|
173
|
+
}
|
|
174
|
+
init() {
|
|
175
|
+
return this.inner.init();
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* The org-scoped tables, read once (on the connection of the query that first needs them, so the
|
|
179
|
+
* check never waits for a second pool connection).
|
|
180
|
+
*/
|
|
181
|
+
orgTables = (conn) => {
|
|
182
|
+
this.tables ??= conn
|
|
183
|
+
.executeQuery(CompiledQuery.raw(ORG_TABLES_SQL))
|
|
184
|
+
.then((r) => new Set(r.rows.map((row) => row.table_name)));
|
|
185
|
+
this.tables.catch(() => {
|
|
186
|
+
this.tables = undefined;
|
|
187
|
+
});
|
|
188
|
+
return this.tables;
|
|
189
|
+
};
|
|
190
|
+
async acquireConnection() {
|
|
191
|
+
const inner = await this.inner.acquireConnection();
|
|
192
|
+
return new ScopedConnection(inner, this.rls, this.orgTables);
|
|
193
|
+
}
|
|
194
|
+
beginTransaction(conn, settings) {
|
|
195
|
+
return scoped(conn).begin(this.inner, settings);
|
|
196
|
+
}
|
|
197
|
+
commitTransaction(conn) {
|
|
198
|
+
const c = scoped(conn);
|
|
199
|
+
return c.end(() => this.inner.commitTransaction(c.inner));
|
|
200
|
+
}
|
|
201
|
+
rollbackTransaction(conn) {
|
|
202
|
+
const c = scoped(conn);
|
|
203
|
+
return c.end(() => this.inner.rollbackTransaction(c.inner));
|
|
204
|
+
}
|
|
205
|
+
async savepoint(conn, name, compile) {
|
|
206
|
+
const c = scoped(conn);
|
|
207
|
+
await c.step(async () => this.inner.savepoint?.(c.inner, name, compile));
|
|
208
|
+
}
|
|
209
|
+
async rollbackToSavepoint(conn, name, compile) {
|
|
210
|
+
const c = scoped(conn);
|
|
211
|
+
await c.step(async () => this.inner.rollbackToSavepoint?.(c.inner, name, compile), true);
|
|
212
|
+
}
|
|
213
|
+
async releaseSavepoint(conn, name, compile) {
|
|
214
|
+
const c = scoped(conn);
|
|
215
|
+
await c.step(async () => this.inner.releaseSavepoint?.(c.inner, name, compile));
|
|
216
|
+
}
|
|
217
|
+
releaseConnection(conn) {
|
|
218
|
+
return this.inner.releaseConnection(scoped(conn).inner);
|
|
219
|
+
}
|
|
220
|
+
destroy() {
|
|
221
|
+
return this.inner.destroy();
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
function scoped(conn) {
|
|
225
|
+
if (!(conn instanceof ScopedConnection))
|
|
226
|
+
throw new Error("Not a scoped pool connection");
|
|
227
|
+
return conn;
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* The kernel pool's dialect: Kysely's Postgres dialect, with {@link ScopedDriver} unless `rls` is
|
|
231
|
+
* `off` (then nothing changes, not even a round trip).
|
|
232
|
+
*/
|
|
233
|
+
export class ScopedPostgresDialect extends PostgresDialect {
|
|
234
|
+
rls;
|
|
235
|
+
constructor(config, rls) {
|
|
236
|
+
super(config);
|
|
237
|
+
this.rls = rls;
|
|
238
|
+
}
|
|
239
|
+
createDriver() {
|
|
240
|
+
const inner = super.createDriver();
|
|
241
|
+
if (this.rls === "off")
|
|
242
|
+
return inner;
|
|
243
|
+
return new ScopedDriver(inner, this.rls === "enforce" ? "enforce" : "off");
|
|
244
|
+
}
|
|
245
|
+
}
|
|
@@ -12,6 +12,7 @@ import { Inject, Injectable, Optional } from "@nestjs/common";
|
|
|
12
12
|
import { ModuleRef } from "@nestjs/core";
|
|
13
13
|
import { sql } from "kysely";
|
|
14
14
|
import { KernelDb } from "../database/kernel-db.js";
|
|
15
|
+
import { asPlatform } from "../database/org-scope.js";
|
|
15
16
|
import { TransactionHost } from "../database/transaction-host.js";
|
|
16
17
|
import { Transactional } from "../database/transactional.decorator.js";
|
|
17
18
|
import { QUEUE_JOB_DEFAULTS } from "../queue/queue.module.js";
|
|
@@ -193,74 +194,76 @@ let OutboxDispatcher = class OutboxDispatcher {
|
|
|
193
194
|
* bounded by {@link OUTBOX_REDIS_TIMEOUT_MS}.
|
|
194
195
|
*/
|
|
195
196
|
async claimAndSend(claim) {
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
.
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
const
|
|
215
|
-
|
|
216
|
-
group
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
const now = Date.now();
|
|
221
|
-
const deadline = now + OUTBOX_REDIS_TIMEOUT_MS;
|
|
222
|
-
const delivered = [];
|
|
223
|
-
const failed = [];
|
|
224
|
-
// after the first failure the queues left are failed without a try: Redis is likely down
|
|
225
|
-
let firstError;
|
|
226
|
-
for (const [name, group] of byQueue) {
|
|
227
|
-
const ids = group.map((r) => r.id);
|
|
228
|
-
if (firstError !== undefined) {
|
|
229
|
-
failed.push({
|
|
230
|
-
ids,
|
|
231
|
-
error: `not tried after an earlier queue failed: ${firstError}`.slice(0, MAX_ERROR_LENGTH),
|
|
232
|
-
});
|
|
233
|
-
continue;
|
|
234
|
-
}
|
|
235
|
-
try {
|
|
236
|
-
if (this.dispatchFails(name))
|
|
237
|
-
throw new Error("outbox dispatch failure (test seam)");
|
|
238
|
-
const queue = queues.get(name);
|
|
239
|
-
if (!queue)
|
|
240
|
-
throw new Error(`"${name}" is not a kernel queue`);
|
|
241
|
-
const left = deadline - Date.now();
|
|
242
|
-
if (left <= 0)
|
|
243
|
-
throw new Error(`no time left of the pass's ${OUTBOX_REDIS_TIMEOUT_MS} ms`);
|
|
244
|
-
await withTimeout(queue.addBulk(group.map((r) => ({
|
|
245
|
-
name: r.job_name,
|
|
246
|
-
data: r.data,
|
|
247
|
-
opts: {
|
|
248
|
-
...QUEUE_JOB_DEFAULTS,
|
|
249
|
-
...outboxJobOptions(r.job_name),
|
|
250
|
-
jobId: r.job_id,
|
|
251
|
-
delay: r.run_at ? Math.max(0, r.run_at.getTime() - now) : 0,
|
|
252
|
-
},
|
|
253
|
-
}))), left, `addBulk to ${name}`);
|
|
254
|
-
delivered.push(...ids);
|
|
197
|
+
return asPlatform("deployment-wide relay", async () => {
|
|
198
|
+
const queues = new Map(this.reachable());
|
|
199
|
+
if (queues.size === 0)
|
|
200
|
+
return { sent: 0, failed: [] };
|
|
201
|
+
// rows of a queue this process cannot reach are left for a process that can
|
|
202
|
+
let query = this.db
|
|
203
|
+
.selectFrom("outbox")
|
|
204
|
+
.select(["id", "queue", "job_name", "job_id", "data", "run_at"])
|
|
205
|
+
.where("dead_at", "is", null)
|
|
206
|
+
.where("queue", "in", [...queues.keys()]);
|
|
207
|
+
query =
|
|
208
|
+
"ids" in claim
|
|
209
|
+
? query.where("id", "in", [...claim.ids])
|
|
210
|
+
: query.where("next_attempt_at", "<=", sql `now()`).limit(claim.limit);
|
|
211
|
+
const rows = await query.orderBy("id").forUpdate().skipLocked().execute();
|
|
212
|
+
if (rows.length === 0)
|
|
213
|
+
return { sent: 0, failed: [] };
|
|
214
|
+
const byQueue = new Map();
|
|
215
|
+
for (const row of rows) {
|
|
216
|
+
const group = byQueue.get(row.queue);
|
|
217
|
+
if (group)
|
|
218
|
+
group.push(row);
|
|
219
|
+
else
|
|
220
|
+
byQueue.set(row.queue, [row]);
|
|
255
221
|
}
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
222
|
+
const now = Date.now();
|
|
223
|
+
const deadline = now + OUTBOX_REDIS_TIMEOUT_MS;
|
|
224
|
+
const delivered = [];
|
|
225
|
+
const failed = [];
|
|
226
|
+
// after the first failure the queues left are failed without a try: Redis is likely down
|
|
227
|
+
let firstError;
|
|
228
|
+
for (const [name, group] of byQueue) {
|
|
229
|
+
const ids = group.map((r) => r.id);
|
|
230
|
+
if (firstError !== undefined) {
|
|
231
|
+
failed.push({
|
|
232
|
+
ids,
|
|
233
|
+
error: `not tried after an earlier queue failed: ${firstError}`.slice(0, MAX_ERROR_LENGTH),
|
|
234
|
+
});
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
try {
|
|
238
|
+
if (this.dispatchFails(name))
|
|
239
|
+
throw new Error("outbox dispatch failure (test seam)");
|
|
240
|
+
const queue = queues.get(name);
|
|
241
|
+
if (!queue)
|
|
242
|
+
throw new Error(`"${name}" is not a kernel queue`);
|
|
243
|
+
const left = deadline - Date.now();
|
|
244
|
+
if (left <= 0)
|
|
245
|
+
throw new Error(`no time left of the pass's ${OUTBOX_REDIS_TIMEOUT_MS} ms`);
|
|
246
|
+
await withTimeout(queue.addBulk(group.map((r) => ({
|
|
247
|
+
name: r.job_name,
|
|
248
|
+
data: r.data,
|
|
249
|
+
opts: {
|
|
250
|
+
...QUEUE_JOB_DEFAULTS,
|
|
251
|
+
...outboxJobOptions(r.job_name),
|
|
252
|
+
jobId: r.job_id,
|
|
253
|
+
delay: r.run_at ? Math.max(0, r.run_at.getTime() - now) : 0,
|
|
254
|
+
},
|
|
255
|
+
}))), left, `addBulk to ${name}`);
|
|
256
|
+
delivered.push(...ids);
|
|
257
|
+
}
|
|
258
|
+
catch (e) {
|
|
259
|
+
firstError = errMsg(e);
|
|
260
|
+
failed.push({ ids, error: firstError.slice(0, MAX_ERROR_LENGTH) });
|
|
261
|
+
}
|
|
259
262
|
}
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
263
|
+
if (delivered.length > 0)
|
|
264
|
+
await this.db.deleteFrom("outbox").where("id", "in", delivered).execute();
|
|
265
|
+
return { sent: delivered.length, failed };
|
|
266
|
+
});
|
|
264
267
|
}
|
|
265
268
|
/**
|
|
266
269
|
* Records a failed add on its rows (after the claim transaction, so the attempt is kept whatever
|
|
@@ -268,31 +271,36 @@ let OutboxDispatcher = class OutboxDispatcher {
|
|
|
268
271
|
* and `dead_at` at the last attempt. Returns how many rows it made dead.
|
|
269
272
|
*/
|
|
270
273
|
async recordFailure(group) {
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
.
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
274
|
+
return asPlatform("deployment-wide relay", async () => {
|
|
275
|
+
const { baseMs, capMs, maxAttempts } = OUTBOX_BACKOFF;
|
|
276
|
+
// the right-hand sides read the row before the update: the first failure waits baseMs
|
|
277
|
+
const backoffMs = sql `least(${capMs}::float8, ${baseMs}::float8 * power(2, attempts))`;
|
|
278
|
+
const updated = await this.db
|
|
279
|
+
.updateTable("outbox")
|
|
280
|
+
.set({
|
|
281
|
+
attempts: sql `attempts + 1`,
|
|
282
|
+
last_error: group.error,
|
|
283
|
+
next_attempt_at: sql `now() + ${backoffMs} * interval '1 millisecond'`,
|
|
284
|
+
dead_at: sql `case when attempts + 1 >= ${maxAttempts}::int then now() end`,
|
|
285
|
+
})
|
|
286
|
+
.where("id", "in", group.ids)
|
|
287
|
+
.where("dead_at", "is", null)
|
|
288
|
+
.returning(["dead_at"])
|
|
289
|
+
.execute();
|
|
290
|
+
const dead = updated.filter((r) => r.dead_at !== null).length;
|
|
291
|
+
this.log.warn("outbox delivery failed; retrying with backoff", {
|
|
292
|
+
rows: group.ids.length,
|
|
293
|
+
dead,
|
|
294
|
+
error: group.error,
|
|
295
|
+
});
|
|
296
|
+
if (dead > 0) {
|
|
297
|
+
this.log.error("outbox rows dead after the last attempt", {
|
|
298
|
+
rows: dead,
|
|
299
|
+
error: group.error,
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
return dead;
|
|
291
303
|
});
|
|
292
|
-
if (dead > 0) {
|
|
293
|
-
this.log.error("outbox rows dead after the last attempt", { rows: dead, error: group.error });
|
|
294
|
-
}
|
|
295
|
-
return dead;
|
|
296
304
|
}
|
|
297
305
|
};
|
|
298
306
|
__decorate([
|
|
@@ -11,6 +11,7 @@ import { isDeepStrictEqual } from "node:util";
|
|
|
11
11
|
import { Inject, Injectable } from "@nestjs/common";
|
|
12
12
|
import { afterCommit } from "../database/after-commit.js";
|
|
13
13
|
import { KernelDb } from "../database/kernel-db.js";
|
|
14
|
+
import { asPlatform } from "../database/org-scope.js";
|
|
14
15
|
import { currentStore, TransactionHost } from "../database/transaction-host.js";
|
|
15
16
|
import { Transactional } from "../database/transactional.decorator.js";
|
|
16
17
|
/** The fast path `add` hands each committed transaction's rows to (`OutboxModule` provides it). */
|
|
@@ -82,32 +83,34 @@ let OutboxService = class OutboxService {
|
|
|
82
83
|
* {@link OutboxConflictError}, so the caller's transaction fails. Undefined data is stored as JSON null.
|
|
83
84
|
*/
|
|
84
85
|
async add(job) {
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
.
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
if (
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
.
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
86
|
+
return asPlatform("the outbox is a deployment-wide table", async () => {
|
|
87
|
+
const json = JSON.stringify(job.data ?? null);
|
|
88
|
+
const row = await this.db
|
|
89
|
+
.insertInto("outbox")
|
|
90
|
+
.values(rowOf(job))
|
|
91
|
+
.onConflict((oc) => oc.columns(["queue", "job_id"]).where("dead_at", "is", null).doNothing())
|
|
92
|
+
.returning("id")
|
|
93
|
+
.executeTakeFirst();
|
|
94
|
+
if (row) {
|
|
95
|
+
if (dueNow(job))
|
|
96
|
+
this.deliverAfterCommit(row.id);
|
|
97
|
+
return true;
|
|
98
|
+
}
|
|
99
|
+
// org-filter: by the unique (queue, job_id) of the conflicting insert just above; job ids are
|
|
100
|
+
// kernel-built and the outbox is deployment-wide
|
|
101
|
+
const stored = await this.db
|
|
102
|
+
.selectFrom("outbox")
|
|
103
|
+
.select(["job_name", "data"])
|
|
104
|
+
.where("queue", "=", job.queue)
|
|
105
|
+
.where("job_id", "=", job.jobId)
|
|
106
|
+
.where("dead_at", "is", null)
|
|
107
|
+
.executeTakeFirst();
|
|
108
|
+
// no row: the owed one was delivered (and deleted) since the conflict; BullMQ dedupes the id
|
|
109
|
+
if (stored && !isDeepStrictEqual(stored.data, JSON.parse(json))) {
|
|
110
|
+
throw new OutboxConflictError(job.queue, job.jobId, job.name, stored.job_name);
|
|
111
|
+
}
|
|
112
|
+
return false;
|
|
113
|
+
});
|
|
111
114
|
}
|
|
112
115
|
/**
|
|
113
116
|
* {@link add} for many jobs in one multi-row insert per {@link ADD_MANY_CHUNK} jobs (an eval
|
|
@@ -2,7 +2,11 @@ import { type ContextJob } from "../../log-context.js";
|
|
|
2
2
|
/**
|
|
3
3
|
* The wrapper every queue processor runs its job in: a fresh async context (no transaction of
|
|
4
4
|
* whoever enqueued the job or started the worker is visible), `queue` / `jobId` / `runId` in the
|
|
5
|
-
* log context, and the tracing span when tracing is on (`withJobContext`).
|
|
5
|
+
* log context, and the tracing span when tracing is on (`withJobContext`). The org scope (RLS spec
|
|
6
|
+
* §5.3, §10) is the job's org when its data carries a string `orgId`; else the platform scope when
|
|
7
|
+
* the queue's work is deployment-wide (`opts.platform`, the reason); else none, never inherited
|
|
8
|
+
* from whoever started the worker (a missing org fails closed once RLS is enforced, and the
|
|
9
|
+
* unscoped-query check reports it).
|
|
6
10
|
*
|
|
7
11
|
* ```ts
|
|
8
12
|
* @Processor("cap-kernel-titles")
|
|
@@ -13,4 +17,6 @@ import { type ContextJob } from "../../log-context.js";
|
|
|
13
17
|
* }
|
|
14
18
|
* ```
|
|
15
19
|
*/
|
|
16
|
-
export declare function runJob<T>(queue: string, job: ContextJob, fn: () => Promise<T
|
|
20
|
+
export declare function runJob<T>(queue: string, job: ContextJob, fn: () => Promise<T>, opts?: {
|
|
21
|
+
platform?: string;
|
|
22
|
+
}): Promise<T>;
|
|
@@ -1,9 +1,14 @@
|
|
|
1
1
|
import { withJobContext } from "../../log-context.js";
|
|
2
|
+
import { asPlatform, withOrgScope, withoutOrgScope } from "../database/org-scope.js";
|
|
2
3
|
import { runOutsideTransaction } from "../database/transaction-host.js";
|
|
3
4
|
/**
|
|
4
5
|
* The wrapper every queue processor runs its job in: a fresh async context (no transaction of
|
|
5
6
|
* whoever enqueued the job or started the worker is visible), `queue` / `jobId` / `runId` in the
|
|
6
|
-
* log context, and the tracing span when tracing is on (`withJobContext`).
|
|
7
|
+
* log context, and the tracing span when tracing is on (`withJobContext`). The org scope (RLS spec
|
|
8
|
+
* §5.3, §10) is the job's org when its data carries a string `orgId`; else the platform scope when
|
|
9
|
+
* the queue's work is deployment-wide (`opts.platform`, the reason); else none, never inherited
|
|
10
|
+
* from whoever started the worker (a missing org fails closed once RLS is enforced, and the
|
|
11
|
+
* unscoped-query check reports it).
|
|
7
12
|
*
|
|
8
13
|
* ```ts
|
|
9
14
|
* @Processor("cap-kernel-titles")
|
|
@@ -14,6 +19,14 @@ import { runOutsideTransaction } from "../database/transaction-host.js";
|
|
|
14
19
|
* }
|
|
15
20
|
* ```
|
|
16
21
|
*/
|
|
17
|
-
export function runJob(queue, job, fn) {
|
|
18
|
-
|
|
22
|
+
export function runJob(queue, job, fn, opts = {}) {
|
|
23
|
+
const orgId = job.data?.orgId;
|
|
24
|
+
const run = () => withJobContext(queue, job, fn);
|
|
25
|
+
return runOutsideTransaction(() => {
|
|
26
|
+
if (typeof orgId === "string" && orgId !== "")
|
|
27
|
+
return withOrgScope(orgId, run);
|
|
28
|
+
if (opts.platform !== undefined)
|
|
29
|
+
return asPlatform(opts.platform, run);
|
|
30
|
+
return withoutOrgScope(run);
|
|
31
|
+
});
|
|
19
32
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { withLogContext } from "../../log-context.js";
|
|
2
|
+
import { asPlatform } from "../database/org-scope.js";
|
|
2
3
|
import { runOutsideTransaction } from "../database/transaction-host.js";
|
|
3
4
|
/** Marks a method wrapped by `@LockedCron` / `@LockedInterval` (read by `ScheduledRuns`). */
|
|
4
5
|
export const LOCKED_JOB = Symbol("LOCKED_JOB");
|
|
@@ -61,13 +62,17 @@ export async function runLockedTick(host, o) {
|
|
|
61
62
|
const signal = scope?.signal;
|
|
62
63
|
/** Errors during the stop are expected (the job aborted, Redis closing): WARN, not ERROR. */
|
|
63
64
|
const logFailure = (msg, fields) => signal?.aborted ? log.warn(msg, fields) : log.error(msg, fields);
|
|
64
|
-
|
|
65
|
+
// a periodic sweep is deployment-wide work (RLS spec §5.1); one that handles each org in turn
|
|
66
|
+
// enters that org's scope itself
|
|
67
|
+
const run = runOutsideTransaction(() => asPlatform(`cron ${o.name}`, () => withLogContext({ cron: o.name }, async () => {
|
|
65
68
|
let tick;
|
|
66
69
|
try {
|
|
67
70
|
if (o.start) {
|
|
68
71
|
tick = "start";
|
|
69
72
|
if (!(await lockService.lease(`cron:${o.name}:start`, "start", o.start.ttlMs))) {
|
|
70
|
-
log.info("cron skipped: start run already taken by another replica", {
|
|
73
|
+
log.info("cron skipped: start run already taken by another replica", {
|
|
74
|
+
cron: o.name,
|
|
75
|
+
});
|
|
71
76
|
return;
|
|
72
77
|
}
|
|
73
78
|
}
|
|
@@ -115,7 +120,10 @@ export async function runLockedTick(host, o) {
|
|
|
115
120
|
log.info("cron run stopped by the shutdown", { cron: o.name, error: errMsg(err) });
|
|
116
121
|
}
|
|
117
122
|
else if (handle.lost.aborted) {
|
|
118
|
-
log.warn("cron run stopped: its run lock was lost", {
|
|
123
|
+
log.warn("cron run stopped: its run lock was lost", {
|
|
124
|
+
cron: o.name,
|
|
125
|
+
error: errMsg(err),
|
|
126
|
+
});
|
|
119
127
|
}
|
|
120
128
|
else {
|
|
121
129
|
log.error("cron job failed", { cron: o.name, error: errMsg(err), err });
|
|
@@ -126,7 +134,7 @@ export async function runLockedTick(host, o) {
|
|
|
126
134
|
.release()
|
|
127
135
|
.catch((err) => logFailure("cron lock release failed", { cron: o.name, err }));
|
|
128
136
|
}
|
|
129
|
-
}));
|
|
137
|
+
})));
|
|
130
138
|
try {
|
|
131
139
|
await (scope ? scope.track(run) : run);
|
|
132
140
|
}
|
|
@@ -11,6 +11,7 @@ import { Inject, Injectable, } from "@nestjs/common";
|
|
|
11
11
|
import { DiscoveryService, MetadataScanner } from "@nestjs/core";
|
|
12
12
|
import { SchedulerRegistry } from "@nestjs/schedule";
|
|
13
13
|
import { waitWithin } from "../close-within.js";
|
|
14
|
+
import { asPlatform } from "../database/org-scope.js";
|
|
14
15
|
import { runOutsideTransaction } from "../database/transaction-host.js";
|
|
15
16
|
import { GracefulShutdown } from "../lifecycle/graceful-shutdown.service.js";
|
|
16
17
|
import { KERNEL_LOGGER } from "../tokens.js";
|
|
@@ -88,7 +89,8 @@ let ScheduledRuns = class ScheduledRuns {
|
|
|
88
89
|
const body = this.bodies.get(name);
|
|
89
90
|
if (!body)
|
|
90
91
|
return false;
|
|
91
|
-
|
|
92
|
+
// deployment-wide like the tick itself (RLS spec §5.1)
|
|
93
|
+
await runOutsideTransaction(() => asPlatform(`cron ${name}`, () => Promise.resolve(body(this.abort.signal))));
|
|
92
94
|
return true;
|
|
93
95
|
}
|
|
94
96
|
/** The start gate is open: ticks and start runs may run. */
|
|
@@ -123,6 +123,7 @@ export declare class KernelLifecycle implements OnApplicationBootstrap, BeforeAp
|
|
|
123
123
|
releaseOnly(): void;
|
|
124
124
|
private checkpoint;
|
|
125
125
|
onApplicationBootstrap(): Promise<void>;
|
|
126
|
+
private startSequence;
|
|
126
127
|
/**
|
|
127
128
|
* Listens on `port` (0.0.0.0; every role listens: worker-only serves only `/healthz` and
|
|
128
129
|
* `/readyz`) after the start sequence; returns the actual port.
|