@capybara-hq/kernel 0.1.0-rc.80 → 0.1.0-rc.82
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bootstrap.json +29 -29
- 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
|
@@ -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.
|
|
@@ -34,6 +34,8 @@ import { insecurePublicUrlWarning } from "../identity/cookies.js";
|
|
|
34
34
|
import { waitWithin } from "../infra/close-within.js";
|
|
35
35
|
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
36
36
|
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
37
|
+
import { asPlatform } from "../infra/database/org-scope.js";
|
|
38
|
+
import { rlsEnforceProblem } from "../infra/database/rls-role.js";
|
|
37
39
|
import { GracefulShutdown } from "../infra/lifecycle/graceful-shutdown.service.js";
|
|
38
40
|
import { ReplicaPresence } from "../infra/presence/replica-presence.js";
|
|
39
41
|
import { KERNEL_BUS, KERNEL_LOGGER, KERNEL_POOL, REDIS } from "../infra/tokens.js";
|
|
@@ -199,7 +201,13 @@ let KernelLifecycle = class KernelLifecycle {
|
|
|
199
201
|
if (this.shutdown.isShuttingDown())
|
|
200
202
|
throw new Error("kernel stopped during start");
|
|
201
203
|
}
|
|
202
|
-
|
|
204
|
+
onApplicationBootstrap() {
|
|
205
|
+
// the start sequence (migrations, bootstrap, extension load, the gateway's connections) is
|
|
206
|
+
// deployment-wide work (RLS spec §5.1); what it starts keeps this scope until an entry point
|
|
207
|
+
// (a request, a job, a run, an event) enters its own
|
|
208
|
+
return asPlatform("kernel start sequence", () => this.startSequence());
|
|
209
|
+
}
|
|
210
|
+
async startSequence() {
|
|
203
211
|
if (this.shutdown.isShuttingDown())
|
|
204
212
|
throw new Error("kernel is stopped");
|
|
205
213
|
const { config, options: opts } = this;
|
|
@@ -215,6 +223,13 @@ let KernelLifecycle = class KernelLifecycle {
|
|
|
215
223
|
this.checkpoint();
|
|
216
224
|
await sql `select 1`.execute(this.pool);
|
|
217
225
|
this.checkpoint();
|
|
226
|
+
if (cfg().db.rls === "enforce") {
|
|
227
|
+
// never fails the start: enforcement is a backstop, and the operator decides
|
|
228
|
+
const problem = await rlsEnforceProblem(this.pool);
|
|
229
|
+
if (problem !== undefined) {
|
|
230
|
+
this.log.error(`db.rls is enforce, but ${problem}: PostgreSQL filters nothing by the org scope there`);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
218
233
|
// In flight for the stop: aborted when the shutdown begins, which then waits for its session to end
|
|
219
234
|
await this.shutdown.trackInFlight(migrate(config.db.url, { schema: KERNEL_SCHEMA, dir: KERNEL_MIGRATIONS_DIR }, { connectTimeoutMs: config.db.connectTimeoutMs, signal: this.shutdown.signal }));
|
|
220
235
|
this.checkpoint();
|
package/dist/orgs/org.guard.js
CHANGED
|
@@ -12,6 +12,7 @@ import { Reflector } from "@nestjs/core";
|
|
|
12
12
|
import { ApiError } from "../errors.js";
|
|
13
13
|
import { AllowService } from "../identity/principal.js";
|
|
14
14
|
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
15
|
+
import { bindRequestScope } from "../infra/database/org-scope.js";
|
|
15
16
|
import { can, HUMAN_ONLY } from "./roles.js";
|
|
16
17
|
export const ORG_ACTION_KEY = "capybara:org:action";
|
|
17
18
|
/**
|
|
@@ -93,6 +94,9 @@ let OrgGuard = class OrgGuard {
|
|
|
93
94
|
const orgId = req.params.orgId;
|
|
94
95
|
if (!orgId)
|
|
95
96
|
throw new Error("OrgGuard: route has no :orgId parameter");
|
|
97
|
+
// the request works in this org from here on (RLS spec §5.1), the role check included: it
|
|
98
|
+
// reads only this org's membership; a refused check ends the request
|
|
99
|
+
bindRequestScope({ kind: "org", orgId });
|
|
96
100
|
const role = await authorizeOrgAction(this.db.db, p, orgId, action);
|
|
97
101
|
req.org = { orgId, role };
|
|
98
102
|
return true;
|
|
@@ -15,6 +15,7 @@ import { ApiError } from "../errors.js";
|
|
|
15
15
|
import { audit } from "../identity/audit.js";
|
|
16
16
|
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
17
17
|
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
18
|
+
import { asPlatform } from "../infra/database/org-scope.js";
|
|
18
19
|
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
19
20
|
import { Transactional } from "../infra/database/transactional.decorator.js";
|
|
20
21
|
import { KEYRING } from "../infra/tokens.js";
|
|
@@ -143,10 +144,12 @@ SealedReveals = __decorate([
|
|
|
143
144
|
export { SealedReveals };
|
|
144
145
|
/** Deletes the sealed reveals past `expires_at`; returns how many. */
|
|
145
146
|
export async function deleteExpiredSealedReveals(db) {
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
147
|
+
return asPlatform("deployment-wide expiry sweep over every org's sealed reveals", async () => {
|
|
148
|
+
// org-filter: deployment-wide expiry sweep over every org's sealed reveals (maintenance job)
|
|
149
|
+
const r = await db
|
|
150
|
+
.deleteFrom("platform_sealed_reveals")
|
|
151
|
+
.where("expires_at", "<=", sql `now()`)
|
|
152
|
+
.executeTakeFirst();
|
|
153
|
+
return Number(r.numDeletedRows);
|
|
154
|
+
});
|
|
152
155
|
}
|
|
@@ -13,6 +13,7 @@ import { BackgroundModule } from "../background/background.module.js";
|
|
|
13
13
|
import { BG_WAKE_JOB } from "../background/wake-rules.js";
|
|
14
14
|
import { OWNED_PLUGIN_CLEANUP_JOB } from "../catalog/job-ids.js";
|
|
15
15
|
import { OwnedPluginCleanup, OwnedPluginCleanupModule } from "../catalog/owned-plugin-cleanup.js";
|
|
16
|
+
import { EventLogModule } from "../conversations/event-log.js";
|
|
16
17
|
import { configuredProcessor } from "../infra/queue/configured-processor.js";
|
|
17
18
|
import { QueueModule } from "../infra/queue/queue.module.js";
|
|
18
19
|
import { runJob } from "../infra/queue/run-job.js";
|
|
@@ -97,7 +98,9 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
|
|
|
97
98
|
this.snapshots = snapshots;
|
|
98
99
|
}
|
|
99
100
|
process(job, token) {
|
|
100
|
-
return runJob(MAINTENANCE_QUEUE_NAME, job, () => this.dispatch(job, token)
|
|
101
|
+
return runJob(MAINTENANCE_QUEUE_NAME, job, () => this.dispatch(job, token), {
|
|
102
|
+
platform: "maintenance job (deployment-wide sweeps)",
|
|
103
|
+
});
|
|
101
104
|
}
|
|
102
105
|
/** Starts consuming (worker role, after the extensions loaded; built with `autorun: false`). */
|
|
103
106
|
start() {
|
|
@@ -253,6 +256,8 @@ MaintenanceModule = __decorate([
|
|
|
253
256
|
KernelScheduleModule,
|
|
254
257
|
// the exact stop a revoked background start owes (SandboxOperationReconcileJob)
|
|
255
258
|
BackgroundModule,
|
|
259
|
+
// the background list hint after reconciling a start (SandboxOperationReconcileJob)
|
|
260
|
+
EventLogModule,
|
|
256
261
|
RuntimeModule,
|
|
257
262
|
SandboxModule,
|
|
258
263
|
ToolsModule,
|
|
@@ -68,6 +68,7 @@ export declare class RunExecution {
|
|
|
68
68
|
constructor(db: KernelDb, xactLock: XactLock, txHost: TransactionHost);
|
|
69
69
|
claim(conversationId: string, runId: string, executionId: string, live?: () => boolean): Promise<ExecutionClaim | null>;
|
|
70
70
|
withClaim<T>(claim: ExecutionClaim, live: () => boolean, fn: () => Promise<T>): Promise<T>;
|
|
71
|
+
private claimed;
|
|
71
72
|
/**
|
|
72
73
|
* The admission (see the class), then the root and the current conversation; NO KEY UPDATE
|
|
73
74
|
* allows foreign key references while excluding deletion and other writers. The root stays
|
|
@@ -10,6 +10,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
|
10
10
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
11
11
|
import { Inject, Injectable } from "@nestjs/common";
|
|
12
12
|
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
13
|
+
import { withOrgScope } from "../infra/database/org-scope.js";
|
|
13
14
|
import { TransactionHost, withTransactionFence } from "../infra/database/transaction-host.js";
|
|
14
15
|
import { Transactional } from "../infra/database/transactional.decorator.js";
|
|
15
16
|
import { XactLock } from "../infra/database/xact-lock.js";
|
|
@@ -113,6 +114,10 @@ let RunExecution = class RunExecution {
|
|
|
113
114
|
return run ? claim : null;
|
|
114
115
|
}
|
|
115
116
|
withClaim(claim, live, fn) {
|
|
117
|
+
// the run works in its org (RLS spec §5.1): every query of the claimed run carries that scope
|
|
118
|
+
return withOrgScope(claim.orgId, () => this.claimed(claim, live, fn));
|
|
119
|
+
}
|
|
120
|
+
claimed(claim, live, fn) {
|
|
116
121
|
return invocationClaim.run(Object.freeze({ ...claim }), () => withTransactionFence(async ({ shared, prelude }) => {
|
|
117
122
|
const admitShared = shared && !exclusiveScope.getStore();
|
|
118
123
|
if (prelude && admitShared)
|
|
@@ -12,6 +12,7 @@ import { sql } from "kysely";
|
|
|
12
12
|
import { EventLog } from "../conversations/event-log.js";
|
|
13
13
|
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
14
14
|
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
15
|
+
import { asPlatform } from "../infra/database/org-scope.js";
|
|
15
16
|
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
16
17
|
import { Transactional } from "../infra/database/transactional.decorator.js";
|
|
17
18
|
import { KernelEvents } from "../infra/events/kernel-events.js";
|
|
@@ -95,14 +96,16 @@ export async function orphanCandidates(db, statuses, minAgeMs, limit, after) {
|
|
|
95
96
|
// org-filter: outbox rows looked up by queue and deterministic kernel job id (unique across the
|
|
96
97
|
// deployment) in the deployment-wide orphan check; outbox.org_id is nullable
|
|
97
98
|
export async function jobInOutbox(db, queue, jobId) {
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
99
|
+
return asPlatform("orphan check: outbox rows by kernel job id", async () => {
|
|
100
|
+
const row = await db
|
|
101
|
+
.selectFrom("outbox")
|
|
102
|
+
.select("id")
|
|
103
|
+
.where("queue", "=", queue)
|
|
104
|
+
.where("job_id", "=", jobId)
|
|
105
|
+
.where("dead_at", "is", null)
|
|
106
|
+
.executeTakeFirst();
|
|
107
|
+
return row !== undefined;
|
|
108
|
+
});
|
|
106
109
|
}
|
|
107
110
|
/** Every page of {@link orphanCandidates}, at most {@link RUN_ORPHAN_CHECK_MAX_PAGES}. */
|
|
108
111
|
async function* candidatePages(db, statuses, minAgeMs, after) {
|
|
@@ -271,13 +274,15 @@ let RunOrphanCheck = class RunOrphanCheck {
|
|
|
271
274
|
// org-filter: outbox rows looked up by queue and deterministic kernel job id (unique across the
|
|
272
275
|
// deployment) in the deployment-wide orphan check; outbox.org_id is nullable
|
|
273
276
|
async hasDeadDelivery(c) {
|
|
274
|
-
return ((
|
|
275
|
-
.
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
277
|
+
return asPlatform("orphan check: outbox rows by kernel job id", async () => {
|
|
278
|
+
return ((await this.db
|
|
279
|
+
.selectFrom("outbox")
|
|
280
|
+
.select("id")
|
|
281
|
+
.where("queue", "=", c.queue)
|
|
282
|
+
.where("job_id", "=", c.jobId)
|
|
283
|
+
.where("dead_at", ">=", sql `${c.since}::timestamptz`)
|
|
284
|
+
.executeTakeFirst()) !== undefined);
|
|
285
|
+
});
|
|
281
286
|
}
|
|
282
287
|
/**
|
|
283
288
|
* Neither a conversation lock holder nor the run's job in BullMQ (nor, queued, in the outbox: an
|