@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
|
@@ -15,6 +15,7 @@ import { ApiError } from "../errors.js";
|
|
|
15
15
|
import { CacheService } from "../infra/cache/cache.service.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 { LockService } from "../infra/lock/lock.service.js";
|
|
@@ -1017,20 +1018,21 @@ let AttachmentsService = class AttachmentsService {
|
|
|
1017
1018
|
// org-filter: deployment-wide cleanup job across all orgs; each claimed row is deleted by its
|
|
1018
1019
|
// own id and handled in its own org (r.org_id)
|
|
1019
1020
|
async purgeRead() {
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
.
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1021
|
+
return asPlatform("deployment-wide cleanup job across all orgs", async () => {
|
|
1022
|
+
if (!this.storage.available)
|
|
1023
|
+
return 0;
|
|
1024
|
+
const hours = this.config.get().attachments.readPurgeAfterHours;
|
|
1025
|
+
let deleted = 0;
|
|
1026
|
+
const failed = [];
|
|
1027
|
+
for (;;) {
|
|
1028
|
+
const claimed = await this.db
|
|
1029
|
+
.updateTable("attachments")
|
|
1030
|
+
.set({ status: "deleting" })
|
|
1031
|
+
.where("id", "in", this.db
|
|
1032
|
+
.selectFrom("attachments")
|
|
1033
|
+
.select("id")
|
|
1034
|
+
.where("purpose", "=", "read")
|
|
1035
|
+
.where("conversation_id", "in", sql `(
|
|
1034
1036
|
WITH RECURSIVE gone(id, level) AS (
|
|
1035
1037
|
SELECT c.id, 0 FROM capybara.conversations c
|
|
1036
1038
|
WHERE c.deleted_at < now() - make_interval(hours => ${hours})
|
|
@@ -1041,37 +1043,38 @@ let AttachmentsService = class AttachmentsService {
|
|
|
1041
1043
|
)
|
|
1042
1044
|
SELECT id FROM gone
|
|
1043
1045
|
)`)
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1046
|
+
.$if(failed.length > 0, (q) => q.where("id", "not in", failed))
|
|
1047
|
+
.orderBy("created_at")
|
|
1048
|
+
.limit(READ_PURGE_BATCH)
|
|
1049
|
+
.forUpdate()
|
|
1050
|
+
.skipLocked())
|
|
1051
|
+
.returning(["id", "org_id", "object_key"])
|
|
1052
|
+
.execute();
|
|
1053
|
+
if (claimed.length === 0)
|
|
1054
|
+
return deleted;
|
|
1055
|
+
for (const r of claimed) {
|
|
1056
|
+
try {
|
|
1057
|
+
await this.storage.kernel(r.org_id).delete(r.object_key);
|
|
1058
|
+
await this.db
|
|
1059
|
+
.deleteFrom("attachments")
|
|
1060
|
+
.where("id", "=", r.id)
|
|
1061
|
+
.where("purpose", "=", "read")
|
|
1062
|
+
.execute();
|
|
1063
|
+
deleted++;
|
|
1064
|
+
}
|
|
1065
|
+
catch (err) {
|
|
1066
|
+
failed.push(r.id);
|
|
1067
|
+
this.log.warn("cannot purge read attachment; will retry", {
|
|
1068
|
+
orgId: r.org_id,
|
|
1069
|
+
attachmentId: r.id,
|
|
1070
|
+
err,
|
|
1071
|
+
});
|
|
1072
|
+
}
|
|
1070
1073
|
}
|
|
1074
|
+
if (claimed.length < READ_PURGE_BATCH)
|
|
1075
|
+
return deleted;
|
|
1071
1076
|
}
|
|
1072
|
-
|
|
1073
|
-
return deleted;
|
|
1074
|
-
}
|
|
1077
|
+
});
|
|
1075
1078
|
}
|
|
1076
1079
|
/**
|
|
1077
1080
|
* 删除过期(`expires_at < now()`)且从未绑定到会话的附件:先把行认领为 `deleting`(`FOR UPDATE SKIP LOCKED`,
|
|
@@ -1083,62 +1086,64 @@ let AttachmentsService = class AttachmentsService {
|
|
|
1083
1086
|
// org-filter: deployment-wide cleanup job across all orgs; each claimed row is deleted by its
|
|
1084
1087
|
// own id and handled in its own org (r.org_id)
|
|
1085
1088
|
async deleteExpired() {
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
.
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
.
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1089
|
+
return asPlatform("deployment-wide cleanup job across all orgs", async () => {
|
|
1090
|
+
if (!this.storage.available)
|
|
1091
|
+
return 0;
|
|
1092
|
+
let deleted = 0;
|
|
1093
|
+
const failed = [];
|
|
1094
|
+
for (;;) {
|
|
1095
|
+
const claimed = await this.db
|
|
1096
|
+
.updateTable("attachments")
|
|
1097
|
+
.set({ status: "deleting" })
|
|
1098
|
+
.where("id", "in", this.db
|
|
1099
|
+
.selectFrom("attachments")
|
|
1100
|
+
.select("id")
|
|
1101
|
+
.where("conversation_id", "is", null)
|
|
1102
|
+
.where("expires_at", "<", sql `now()`)
|
|
1103
|
+
.$if(failed.length > 0, (q) => q.where("id", "not in", failed))
|
|
1104
|
+
.orderBy("expires_at")
|
|
1105
|
+
.limit(CLEANUP_BATCH)
|
|
1106
|
+
.forUpdate()
|
|
1107
|
+
.skipLocked())
|
|
1108
|
+
.returning(["id", "org_id", "object_key", "purpose"])
|
|
1109
|
+
.execute();
|
|
1110
|
+
if (claimed.length === 0)
|
|
1111
|
+
return deleted;
|
|
1112
|
+
for (const r of claimed) {
|
|
1113
|
+
try {
|
|
1114
|
+
const store = this.storage.kernel(r.org_id);
|
|
1115
|
+
await store.delete(r.object_key);
|
|
1116
|
+
if (r.purpose === "skill-package") {
|
|
1117
|
+
// delete the unpacked files only when no version references them (a failed or unused upload)
|
|
1118
|
+
const prefix = skillFilesPrefix(r.id);
|
|
1119
|
+
const used = await this.db
|
|
1120
|
+
.selectFrom("skill_versions")
|
|
1121
|
+
.select("skill_id")
|
|
1122
|
+
.where("object_prefix", "=", prefix)
|
|
1123
|
+
.executeTakeFirst();
|
|
1124
|
+
if (!used)
|
|
1125
|
+
await store.deletePrefix(prefix);
|
|
1126
|
+
}
|
|
1127
|
+
await this.db
|
|
1128
|
+
.deleteFrom("attachments")
|
|
1129
|
+
.where("id", "=", r.id)
|
|
1130
|
+
.where("conversation_id", "is", null)
|
|
1131
|
+
.execute();
|
|
1132
|
+
deleted++;
|
|
1133
|
+
}
|
|
1134
|
+
catch (err) {
|
|
1135
|
+
failed.push(r.id);
|
|
1136
|
+
this.log.warn("cannot delete expired attachment; will retry", {
|
|
1137
|
+
orgId: r.org_id,
|
|
1138
|
+
attachmentId: r.id,
|
|
1139
|
+
err,
|
|
1140
|
+
});
|
|
1122
1141
|
}
|
|
1123
|
-
await this.db
|
|
1124
|
-
.deleteFrom("attachments")
|
|
1125
|
-
.where("id", "=", r.id)
|
|
1126
|
-
.where("conversation_id", "is", null)
|
|
1127
|
-
.execute();
|
|
1128
|
-
deleted++;
|
|
1129
|
-
}
|
|
1130
|
-
catch (err) {
|
|
1131
|
-
failed.push(r.id);
|
|
1132
|
-
this.log.warn("cannot delete expired attachment; will retry", {
|
|
1133
|
-
orgId: r.org_id,
|
|
1134
|
-
attachmentId: r.id,
|
|
1135
|
-
err,
|
|
1136
|
-
});
|
|
1137
1142
|
}
|
|
1143
|
+
if (claimed.length < CLEANUP_BATCH)
|
|
1144
|
+
return deleted;
|
|
1138
1145
|
}
|
|
1139
|
-
|
|
1140
|
-
return deleted;
|
|
1141
|
-
}
|
|
1146
|
+
});
|
|
1142
1147
|
}
|
|
1143
1148
|
};
|
|
1144
1149
|
__decorate([
|
|
@@ -509,6 +509,7 @@ export declare const HANDOFF_URL_MAX_CHARS = 2000;
|
|
|
509
509
|
* name no tool has (ToolSearch mode, spec 5.5): expected behaviour, the model is told to load it
|
|
510
510
|
* (or search for it) first. The result
|
|
511
511
|
* stays `isError: true` for the model; the web shows it as a neutral outcome too.
|
|
512
|
+
* `launch_unconfirmed`: a background `Bash` start whose outcome is being reconciled (see below).
|
|
512
513
|
* `handoff`: a `Platform` operation whose decision stays with a person on a web page (platform web
|
|
513
514
|
* parity spec §4.4, §6): the card's title and either a relative web path (`link`, also in the
|
|
514
515
|
* result text as `reviewUrl`) or a connector to connect (`connect`: the web's Connect button starts
|
|
@@ -561,6 +562,9 @@ export declare const ToolViewSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
561
562
|
}>;
|
|
562
563
|
}, z.core.$strip>, z.ZodObject<{
|
|
563
564
|
kind: z.ZodLiteral<"not_loaded">;
|
|
565
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
566
|
+
kind: z.ZodLiteral<"launch_unconfirmed">;
|
|
567
|
+
taskId: z.ZodString;
|
|
564
568
|
}, z.core.$strip>, z.ZodObject<{
|
|
565
569
|
kind: z.ZodLiteral<"reveal">;
|
|
566
570
|
reveal: z.ZodEnum<{
|
|
@@ -1457,6 +1461,9 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
|
|
|
1457
1461
|
}>;
|
|
1458
1462
|
}, z.core.$strip>, z.ZodObject<{
|
|
1459
1463
|
kind: z.ZodLiteral<"not_loaded">;
|
|
1464
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
1465
|
+
kind: z.ZodLiteral<"launch_unconfirmed">;
|
|
1466
|
+
taskId: z.ZodString;
|
|
1460
1467
|
}, z.core.$strip>, z.ZodObject<{
|
|
1461
1468
|
kind: z.ZodLiteral<"reveal">;
|
|
1462
1469
|
reveal: z.ZodEnum<{
|
|
@@ -565,6 +565,7 @@ const HANDOFF_PATH = /^\/(?![/\\])[^\\\s]*$/;
|
|
|
565
565
|
* name no tool has (ToolSearch mode, spec 5.5): expected behaviour, the model is told to load it
|
|
566
566
|
* (or search for it) first. The result
|
|
567
567
|
* stays `isError: true` for the model; the web shows it as a neutral outcome too.
|
|
568
|
+
* `launch_unconfirmed`: a background `Bash` start whose outcome is being reconciled (see below).
|
|
568
569
|
* `handoff`: a `Platform` operation whose decision stays with a person on a web page (platform web
|
|
569
570
|
* parity spec §4.4, §6): the card's title and either a relative web path (`link`, also in the
|
|
570
571
|
* result text as `reviewUrl`) or a connector to connect (`connect`: the web's Connect button starts
|
|
@@ -610,6 +611,14 @@ export const ToolViewSchema = z.discriminatedUnion("kind", [
|
|
|
610
611
|
reason: z.enum(["not_read", "modified"]),
|
|
611
612
|
}),
|
|
612
613
|
z.object({ kind: z.literal("not_loaded") }),
|
|
614
|
+
/**
|
|
615
|
+
* A background `Bash` start the kernel sent but could not confirm (a transport loss after the
|
|
616
|
+
* dispatch): the task may be running, and the kernel reconciles it under its original identity.
|
|
617
|
+
* The result stays `isError: true` for the model with the same text; the web shows the row as
|
|
618
|
+
* reconciling, not failed, until the task is confirmed running, finishes, or is given up
|
|
619
|
+
* (`lost`). Display only.
|
|
620
|
+
*/
|
|
621
|
+
z.object({ kind: z.literal("launch_unconfirmed"), taskId: z.string().min(1).max(64) }),
|
|
613
622
|
/**
|
|
614
623
|
* A `Platform` operation whose result is shown to the run's person once, read by call (the
|
|
615
624
|
* initial password, the invitation link; profiles govern every approval, ruling R6): the web
|
package/dist/ctx/bus.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { withoutOrgScope } from "../infra/database/org-scope.js";
|
|
1
2
|
import { runOutsideTransaction } from "../infra/database/transaction-host.js";
|
|
2
3
|
import { withoutLogContext } from "../log-context.js";
|
|
3
4
|
import { assertNamespace } from "./namespace.js";
|
|
@@ -22,12 +23,13 @@ export function createBusSubscriber(subFactory, log = consoleLog) {
|
|
|
22
23
|
const c = subFactory();
|
|
23
24
|
c.on("message", (channel, message) => {
|
|
24
25
|
// the connection's callbacks carry the async context of the first subscribe (a request's
|
|
25
|
-
// log fields, possibly an open transaction): every handler starts from an
|
|
26
|
-
|
|
26
|
+
// log fields and org scope, possibly an open transaction): every handler starts from an
|
|
27
|
+
// empty one
|
|
28
|
+
runOutsideTransaction(() => withoutOrgScope(() => withoutLogContext(() => {
|
|
27
29
|
for (const h of [...(channels.get(channel)?.handlers ?? [])]) {
|
|
28
30
|
invokeIsolated(log, channel, () => h(message));
|
|
29
31
|
}
|
|
30
|
-
}));
|
|
32
|
+
})));
|
|
31
33
|
});
|
|
32
34
|
c.on("error", (err) => log.error("bus subscriber connection error", { err }));
|
|
33
35
|
conn = c;
|
package/dist/ctx/queue.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Queue, Worker } from "bullmq";
|
|
2
2
|
import { Redis } from "ioredis";
|
|
3
|
-
import {
|
|
3
|
+
import { runJob } from "../infra/queue/run-job.js";
|
|
4
4
|
import { assertNamespace } from "./namespace.js";
|
|
5
5
|
/** 未注入 logger 时的兜底:输出到 stderr。 */
|
|
6
6
|
const consoleLog = {
|
|
@@ -61,7 +61,9 @@ export function createQueue(redisUrl, namespace, opts) {
|
|
|
61
61
|
return;
|
|
62
62
|
const st = { n: 0, idle: [] };
|
|
63
63
|
active.set(name, st);
|
|
64
|
-
const worker = new Worker(queueName(name),
|
|
64
|
+
const worker = new Worker(queueName(name),
|
|
65
|
+
// runJob: the log context and the org scope of the job (its data's `orgId`, else platform)
|
|
66
|
+
(job) => runJob(queueName(name), job, async () => {
|
|
65
67
|
st.n += 1;
|
|
66
68
|
try {
|
|
67
69
|
await handler(job.data);
|
package/dist/db/pool.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Kysely } from "kysely";
|
|
2
|
+
import { type RlsMode } from "../infra/database/scoped-dialect.js";
|
|
2
3
|
/** 内核连接池的 PG `application_name`(便于在 pg_stat_activity 中识别)。 */
|
|
3
4
|
export declare const KERNEL_APPLICATION_NAME = "capybara-kernel";
|
|
4
5
|
/**
|
|
@@ -28,4 +29,9 @@ export declare function createDb(url: string, poolMax: number, onError?: (err: E
|
|
|
28
29
|
* without this a backend killed between two statements is an uncaught exception.
|
|
29
30
|
*/
|
|
30
31
|
onClientError?: ((err: Error) => void) | undefined;
|
|
32
|
+
/**
|
|
33
|
+
* `db.rls`: whether every connection carries the org scope of its caller (RLS spec §5.2;
|
|
34
|
+
* `scoped-dialect.ts`). Unset = `off`, a plain pool.
|
|
35
|
+
*/
|
|
36
|
+
rls?: RlsMode | undefined;
|
|
31
37
|
}): Kysely<any>;
|
package/dist/db/pool.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { Kysely
|
|
1
|
+
import { Kysely } from "kysely";
|
|
2
2
|
import pg from "pg";
|
|
3
|
+
import { ScopedPostgresDialect } from "../infra/database/scoped-dialect.js";
|
|
3
4
|
/** 内核连接池的 PG `application_name`(便于在 pg_stat_activity 中识别)。 */
|
|
4
5
|
export const KERNEL_APPLICATION_NAME = "capybara-kernel";
|
|
5
6
|
/**
|
|
@@ -28,5 +29,5 @@ export function createDb(url, poolMax, onError = (err) => console.error("[db] id
|
|
|
28
29
|
});
|
|
29
30
|
pool.on("error", onError);
|
|
30
31
|
pool.on("connect", (client) => client.on("error", opts.onClientError ?? onError));
|
|
31
|
-
return new Kysely({ dialect: new
|
|
32
|
+
return new Kysely({ dialect: new ScopedPostgresDialect({ pool }, opts.rls ?? "off") });
|
|
32
33
|
}
|
|
@@ -10,6 +10,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
|
10
10
|
import { Inject, Injectable } from "@nestjs/common";
|
|
11
11
|
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
12
12
|
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
13
|
+
import { asPlatform } from "../infra/database/org-scope.js";
|
|
13
14
|
import { LockService } from "../infra/lock/lock.service.js";
|
|
14
15
|
import { LockedInterval } from "../infra/schedule/locked-interval.js";
|
|
15
16
|
import { KERNEL_LOGGER } from "../infra/tokens.js";
|
|
@@ -55,79 +56,81 @@ let LegacySandboxCleanupJob = class LegacySandboxCleanupJob {
|
|
|
55
56
|
// org-filter: deployment-wide sweep of the legacy sandboxes table across all orgs
|
|
56
57
|
// (LockedInterval), each row keyed by its own conversation id
|
|
57
58
|
async runOnce(now = new Date(), signal) {
|
|
58
|
-
|
|
59
|
-
.
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
.
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
.
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
59
|
+
return asPlatform("deployment-wide sweep of the legacy sandboxes table across all orgs", async () => {
|
|
60
|
+
const any = await this.db
|
|
61
|
+
.selectFrom("sandboxes")
|
|
62
|
+
.select("conversation_id")
|
|
63
|
+
.limit(1)
|
|
64
|
+
.executeTakeFirst();
|
|
65
|
+
if (any === undefined)
|
|
66
|
+
return { destroyed: 0, kept: 0 };
|
|
67
|
+
const byProvider = await this.db
|
|
68
|
+
.selectFrom("sandboxes")
|
|
69
|
+
.select(["provider", (eb) => eb.fn.countAll().as("n")])
|
|
70
|
+
.groupBy("provider")
|
|
71
|
+
.execute();
|
|
72
|
+
const loaded = byProvider.filter((p) => this.providers.forDevice(p.provider) !== undefined);
|
|
73
|
+
const unloaded = byProvider.filter((p) => this.providers.forDevice(p.provider) === undefined);
|
|
74
|
+
const kept = unloaded.reduce((sum, p) => sum + Number(p.n), 0);
|
|
75
|
+
if (unloaded.length > 0 && now.getTime() % 3_600_000 < PERIOD_MS) {
|
|
76
|
+
this.log.warn("legacy sandboxes kept: their provider is not loaded", {
|
|
77
|
+
providers: unloaded.map((p) => p.provider),
|
|
78
|
+
count: kept,
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
if (loaded.length === 0)
|
|
82
|
+
return { destroyed: 0, kept };
|
|
83
|
+
const rows = await this.db
|
|
84
|
+
.selectFrom("sandboxes")
|
|
85
|
+
.select(["conversation_id", "provider", "prev_provider"])
|
|
86
|
+
.where("provider", "in", loaded.map((p) => p.provider))
|
|
87
|
+
.orderBy("sweep_failed_at", (o) => o.asc().nullsFirst())
|
|
88
|
+
.orderBy("conversation_id")
|
|
89
|
+
.limit(BATCH)
|
|
90
|
+
.execute();
|
|
91
|
+
let destroyed = 0;
|
|
92
|
+
for (const row of rows) {
|
|
93
|
+
if (signal?.aborted)
|
|
94
|
+
break;
|
|
95
|
+
const name = `cap-${row.conversation_id}`;
|
|
96
|
+
const impl = this.providers.forDevice(row.provider)?.impl;
|
|
97
|
+
if (impl === undefined)
|
|
98
|
+
continue; // unloaded since the query: kept for a later tick
|
|
99
|
+
const callSignal = () => signal
|
|
100
|
+
? AbortSignal.any([signal, AbortSignal.timeout(CALL_TIMEOUT_MS)])
|
|
101
|
+
: AbortSignal.timeout(CALL_TIMEOUT_MS);
|
|
102
|
+
try {
|
|
103
|
+
// no device lease holds a legacy row: nothing to fence the destroy with
|
|
104
|
+
await impl.destroyByName(name, callSignal(), null);
|
|
105
|
+
await impl.destroyFileSystemByName(name, callSignal());
|
|
106
|
+
if (row.prev_provider !== null && row.prev_provider !== row.provider) {
|
|
107
|
+
const prev = this.providers.forDevice(row.prev_provider)?.impl;
|
|
108
|
+
if (prev !== undefined)
|
|
109
|
+
await prev.destroyByName(name, callSignal(), null);
|
|
110
|
+
else {
|
|
111
|
+
this.log.warn("legacy sandbox of a replaced provider left: provider not loaded", {
|
|
112
|
+
name,
|
|
113
|
+
provider: row.prev_provider,
|
|
114
|
+
});
|
|
115
|
+
}
|
|
113
116
|
}
|
|
117
|
+
await this.db
|
|
118
|
+
.deleteFrom("sandboxes")
|
|
119
|
+
.where("conversation_id", "=", row.conversation_id)
|
|
120
|
+
.execute();
|
|
121
|
+
destroyed++;
|
|
122
|
+
}
|
|
123
|
+
catch (err) {
|
|
124
|
+
this.log.warn("cannot destroy legacy sandbox; will retry", { name, err });
|
|
125
|
+
await this.db
|
|
126
|
+
.updateTable("sandboxes")
|
|
127
|
+
.set({ sweep_failed_at: now })
|
|
128
|
+
.where("conversation_id", "=", row.conversation_id)
|
|
129
|
+
.execute();
|
|
114
130
|
}
|
|
115
|
-
await this.db
|
|
116
|
-
.deleteFrom("sandboxes")
|
|
117
|
-
.where("conversation_id", "=", row.conversation_id)
|
|
118
|
-
.execute();
|
|
119
|
-
destroyed++;
|
|
120
|
-
}
|
|
121
|
-
catch (err) {
|
|
122
|
-
this.log.warn("cannot destroy legacy sandbox; will retry", { name, err });
|
|
123
|
-
await this.db
|
|
124
|
-
.updateTable("sandboxes")
|
|
125
|
-
.set({ sweep_failed_at: now })
|
|
126
|
-
.where("conversation_id", "=", row.conversation_id)
|
|
127
|
-
.execute();
|
|
128
131
|
}
|
|
129
|
-
|
|
130
|
-
|
|
132
|
+
return { destroyed, kept };
|
|
133
|
+
});
|
|
131
134
|
}
|
|
132
135
|
};
|
|
133
136
|
__decorate([
|
|
@@ -94,7 +94,14 @@ declare class DeviceConnection {
|
|
|
94
94
|
private publishFailures;
|
|
95
95
|
private publishCapacity;
|
|
96
96
|
get deviceId(): string;
|
|
97
|
+
/**
|
|
98
|
+
* Runs `fn` in the device's org (RLS spec §5.3: per-event work of a long connection enters the
|
|
99
|
+
* org its credential resolved). Socket listeners run in the emitter's async context, not the
|
|
100
|
+
* one that registered them, so each enters it again.
|
|
101
|
+
*/
|
|
102
|
+
private inOrg;
|
|
97
103
|
start(): void;
|
|
104
|
+
private arm;
|
|
98
105
|
private onFrame;
|
|
99
106
|
/**
|
|
100
107
|
* The accepted hello: claims the lease, records the program facts, then asks the provider
|
|
@@ -195,6 +202,7 @@ export declare class DialInGateway {
|
|
|
195
202
|
* before the upgrade): null for an unknown or revoked credential.
|
|
196
203
|
*/
|
|
197
204
|
admit(credential: string): Promise<DialInAdmission>;
|
|
205
|
+
private admitted;
|
|
198
206
|
/**
|
|
199
207
|
* Serves one upgraded socket of a machine until it closes, speaking `protocol` (the route
|
|
200
208
|
* admitted it). The credential and the provider are checked again here, with the socket paused,
|
package/dist/dial-in/gateway.js
CHANGED
|
@@ -11,6 +11,7 @@ import { randomUUID } from "node:crypto";
|
|
|
11
11
|
import { DIAL_IN_PROTOCOL_RE, parseDialInMachineFrame, } from "@capybara-hq/plugin-sdk";
|
|
12
12
|
import { Inject, Injectable } from "@nestjs/common";
|
|
13
13
|
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
14
|
+
import { asPlatform, withOrgScope, withoutOrgScope } from "../infra/database/org-scope.js";
|
|
14
15
|
import { LockService } from "../infra/lock/lock.service.js";
|
|
15
16
|
import { KERNEL_BUS, KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
|
|
16
17
|
import { storedResult, wireFrameOf } from "./envelope.js";
|
|
@@ -185,7 +186,22 @@ class DeviceConnection {
|
|
|
185
186
|
get deviceId() {
|
|
186
187
|
return this.identity.deviceId;
|
|
187
188
|
}
|
|
189
|
+
/**
|
|
190
|
+
* Runs `fn` in the device's org (RLS spec §5.3: per-event work of a long connection enters the
|
|
191
|
+
* org its credential resolved). Socket listeners run in the emitter's async context, not the
|
|
192
|
+
* one that registered them, so each enters it again.
|
|
193
|
+
*/
|
|
194
|
+
inOrg(fn) {
|
|
195
|
+
// never throw inside a socket listener: a device without an org (impossible by the schema)
|
|
196
|
+
// runs unscoped, which fails closed
|
|
197
|
+
const { orgId } = this.identity;
|
|
198
|
+
return orgId ? withOrgScope(orgId, fn) : withoutOrgScope(fn);
|
|
199
|
+
}
|
|
188
200
|
start() {
|
|
201
|
+
// the timers armed here keep this scope (timers carry their creator's async context)
|
|
202
|
+
this.inOrg(() => this.arm());
|
|
203
|
+
}
|
|
204
|
+
arm() {
|
|
189
205
|
const { socket } = this;
|
|
190
206
|
this.helloTimer = setTimeout(() => this.close(DEVICE_CLOSE.protocol, "hello expected"), HELLO_TIMEOUT_MS);
|
|
191
207
|
this.schedulePing();
|
|
@@ -206,10 +222,10 @@ class DeviceConnection {
|
|
|
206
222
|
: Buffer.isBuffer(data)
|
|
207
223
|
? data.toString("utf8")
|
|
208
224
|
: Buffer.from(data).toString("utf8");
|
|
209
|
-
void this.onFrame(text);
|
|
225
|
+
void this.inOrg(() => this.onFrame(text));
|
|
210
226
|
});
|
|
211
227
|
socket.on("close", () => {
|
|
212
|
-
void this.shutdown();
|
|
228
|
+
void this.inOrg(() => this.shutdown());
|
|
213
229
|
});
|
|
214
230
|
}
|
|
215
231
|
async onFrame(text) {
|
|
@@ -785,6 +801,10 @@ let DialInGateway = class DialInGateway {
|
|
|
785
801
|
* before the upgrade): null for an unknown or revoked credential.
|
|
786
802
|
*/
|
|
787
803
|
async admit(credential) {
|
|
804
|
+
// the credential names the device and its org: looked up before any org is known
|
|
805
|
+
return asPlatform("dial-in credential lookup", () => this.admitted(credential));
|
|
806
|
+
}
|
|
807
|
+
async admitted(credential) {
|
|
788
808
|
const identity = await this.machines.authenticate(credential);
|
|
789
809
|
if (identity === null)
|
|
790
810
|
return null;
|