@capybara-hq/kernel 0.1.0-rc.133 → 0.1.0-rc.135
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 +1 -1
- package/dist/automations/events/trigger-events.service.d.ts +13 -1
- package/dist/automations/events/trigger-events.service.js +27 -14
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/config/schema.d.ts +8 -0
- package/dist/config/schema.js +67 -2
- package/dist/ctx/create-ctx.d.ts +4 -0
- package/dist/ctx/create-ctx.js +74 -27
- package/dist/ctx/durable-cancellation.d.ts +3 -0
- package/dist/ctx/durable-cancellation.js +8 -0
- package/dist/ctx/durable-effects.service.d.ts +81 -0
- package/dist/ctx/durable-effects.service.js +316 -0
- package/dist/ctx/durable-envelope.d.ts +24 -0
- package/dist/ctx/durable-envelope.js +80 -0
- package/dist/ctx/durable-failure.d.ts +7 -0
- package/dist/ctx/durable-failure.js +32 -0
- package/dist/ctx/durable-job.d.ts +9 -0
- package/dist/ctx/durable-job.js +2 -0
- package/dist/ctx/durable-keys.d.ts +27 -0
- package/dist/ctx/durable-keys.js +138 -0
- package/dist/ctx/durable-relay.d.ts +29 -0
- package/dist/ctx/durable-relay.js +250 -0
- package/dist/ctx/queue.d.ts +2 -0
- package/dist/ctx/queue.js +22 -15
- package/dist/db/extension-db.d.ts +8 -3
- package/dist/db/extension-db.js +109 -7
- package/dist/db/extension-handoff-schema.d.ts +6 -0
- package/dist/db/extension-handoff-schema.js +72 -0
- package/dist/db/extension-role-provision.d.ts +9 -0
- package/dist/db/extension-role-provision.js +89 -0
- package/dist/db/extension-schema-transfer.d.ts +2 -1
- package/dist/db/extension-schema-transfer.js +114 -18
- package/dist/db/kernel-schema.d.ts +16 -0
- package/dist/db/migrator.d.ts +2 -0
- package/dist/db/migrator.js +4 -3
- package/dist/erasure/org-catalog.js +2 -2
- package/dist/erasure/org-rules.js +1 -0
- package/dist/extensions/admin-ops.js +17 -1
- package/dist/extensions/extensions.module.js +10 -0
- package/dist/extensions/host.d.ts +6 -0
- package/dist/extensions/host.js +35 -21
- package/dist/extensions/instance.d.ts +2 -0
- package/dist/extensions/instance.js +6 -0
- package/dist/extensions/migrate-lock.js +1 -0
- package/dist/extensions/sources.d.ts +1 -0
- package/dist/extensions/sources.js +9 -0
- package/dist/inbox/inbox-items.service.d.ts +5 -0
- package/dist/inbox/inbox-items.service.js +57 -33
- package/dist/index.d.ts +3 -1
- package/dist/index.js +3 -1
- package/dist/infra/database/extension-effect-key-lock.d.ts +10 -0
- package/dist/infra/database/extension-effect-key-lock.js +69 -0
- package/dist/infra/database/extension-handoff.d.ts +27 -0
- package/dist/infra/database/extension-handoff.js +113 -0
- package/dist/infra/database/rls-role.d.ts +4 -11
- package/dist/infra/database/rls-role.js +71 -27
- package/dist/infra/outbox/outbox.dispatcher.d.ts +6 -1
- package/dist/infra/outbox/outbox.dispatcher.js +64 -4
- package/dist/infra/outbox/outbox.module.js +2 -0
- package/dist/infra/outbox/registry.d.ts +12 -0
- package/dist/infra/outbox/registry.js +12 -0
- package/dist/kernel.d.ts +2 -0
- package/dist/kernel.js +12 -1
- package/dist/lifecycle/kernel-lifecycle.js +2 -3
- package/dist/orgs/orgs.service.js +16 -0
- package/dist/roles/worker.module.js +2 -0
- package/package.json +3 -3
- package/src/migrations/0225_extension_effect_receipts.sql +25 -0
- package/src/migrations/0226_enable_kernel_rls.sql +30 -0
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
8
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
9
|
+
};
|
|
10
|
+
import { EXTENSION_NAME_RE } from "@capybara-hq/plugin-sdk";
|
|
11
|
+
import { Inject, Injectable } from "@nestjs/common";
|
|
12
|
+
import { sql } from "kysely";
|
|
13
|
+
import { ConfiguredExtensionDbIdentity } from "../db/extension-db.js";
|
|
14
|
+
import { ExtensionRegistry } from "../extensions/registry.js";
|
|
15
|
+
import { ReplicaStatusStore } from "../extensions/sources.js";
|
|
16
|
+
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
17
|
+
import { handoffReference, markHandoffParked, readHandoff, readHandoffRow, readUnreferencedParks, retryHandoff, settleHandoff, } from "../infra/database/extension-handoff.js";
|
|
18
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
19
|
+
import { asPlatform, withOrgScope } from "../infra/database/org-scope.js";
|
|
20
|
+
import { LockService } from "../infra/lock/lock.service.js";
|
|
21
|
+
import { OutboxDispatcher } from "../infra/outbox/outbox.dispatcher.js";
|
|
22
|
+
import { LockedInterval } from "../infra/schedule/locked-interval.js";
|
|
23
|
+
import { KERNEL_LOGGER } from "../infra/tokens.js";
|
|
24
|
+
import { ExtensionEffects } from "./durable-effects.service.js";
|
|
25
|
+
import { ExtensionEnvelopeClockSkew, effectHash, InvalidExtensionEnvelope, } from "./durable-envelope.js";
|
|
26
|
+
import { classifyEffectFailure, ExtensionEffectFailure, effectFailureMessage, } from "./durable-failure.js";
|
|
27
|
+
import { EXTENSION_EFFECT_REDRIVE_JOB } from "./durable-job.js";
|
|
28
|
+
import { ExtensionEffectKeys } from "./durable-keys.js";
|
|
29
|
+
const EXTENSION_HANDOFF_RELAY = "extension-handoff-relay";
|
|
30
|
+
const BATCH = 32;
|
|
31
|
+
const PARK_BUDGET = 4;
|
|
32
|
+
const LAST_RETRY = 19;
|
|
33
|
+
const HANDOFF_MISSING = "handoff_missing: The extension handoff table is missing";
|
|
34
|
+
let ExtensionEffectRelay = class ExtensionEffectRelay {
|
|
35
|
+
dispatcher;
|
|
36
|
+
effects;
|
|
37
|
+
keys;
|
|
38
|
+
identity;
|
|
39
|
+
registry;
|
|
40
|
+
status;
|
|
41
|
+
db;
|
|
42
|
+
config;
|
|
43
|
+
lockService;
|
|
44
|
+
log;
|
|
45
|
+
constructor(dispatcher, effects, keys, identity, registry, status, db, config, lockService, log) {
|
|
46
|
+
this.dispatcher = dispatcher;
|
|
47
|
+
this.effects = effects;
|
|
48
|
+
this.keys = keys;
|
|
49
|
+
this.identity = identity;
|
|
50
|
+
this.registry = registry;
|
|
51
|
+
this.status = status;
|
|
52
|
+
this.db = db;
|
|
53
|
+
this.config = config;
|
|
54
|
+
this.lockService = lockService;
|
|
55
|
+
this.log = log;
|
|
56
|
+
}
|
|
57
|
+
async relay(signal) {
|
|
58
|
+
await this.relayOnce(signal);
|
|
59
|
+
}
|
|
60
|
+
async retireKeys() {
|
|
61
|
+
await this.keys.retireUnused();
|
|
62
|
+
}
|
|
63
|
+
async relayOnce(signal) {
|
|
64
|
+
const plugins = await asPlatform("Find known extension handoff tables", () => this.db.db.selectFrom("extension_name_owners").select("name").execute());
|
|
65
|
+
const names = new Set([
|
|
66
|
+
...plugins.map(({ name }) => name),
|
|
67
|
+
...this.registry.all().map(({ name }) => name),
|
|
68
|
+
]);
|
|
69
|
+
let loaded;
|
|
70
|
+
let loadedAt = 0;
|
|
71
|
+
let refreshed = false;
|
|
72
|
+
const load = () => {
|
|
73
|
+
loadedAt = Date.now();
|
|
74
|
+
return this.keys.forVerification();
|
|
75
|
+
};
|
|
76
|
+
const ring = async (row) => {
|
|
77
|
+
loaded ??= load();
|
|
78
|
+
let keys = await loaded;
|
|
79
|
+
const keyId = row.envelope?.keyId;
|
|
80
|
+
if (typeof keyId !== "string" || Object.hasOwn(keys.keys, keyId))
|
|
81
|
+
return keys;
|
|
82
|
+
if (!refreshed && /^[a-f0-9-]{36}$/i.test(keyId)) {
|
|
83
|
+
refreshed = true;
|
|
84
|
+
loaded = load();
|
|
85
|
+
keys = await loaded;
|
|
86
|
+
}
|
|
87
|
+
if (!Object.hasOwn(keys.keys, keyId) && row.created_at.getTime() >= loadedAt - 1000) {
|
|
88
|
+
throw new ExtensionEnvelopeClockSkew("The handoff was written after the verification snapshot");
|
|
89
|
+
}
|
|
90
|
+
return keys;
|
|
91
|
+
};
|
|
92
|
+
for (const plugin of names) {
|
|
93
|
+
if (signal?.aborted)
|
|
94
|
+
return;
|
|
95
|
+
if (!EXTENSION_NAME_RE.test(plugin))
|
|
96
|
+
continue;
|
|
97
|
+
const lease = await this.lockService.acquire(`extension-effect-relay-${plugin}`, {
|
|
98
|
+
ttlMs: 30_000,
|
|
99
|
+
...(signal && { signal }),
|
|
100
|
+
});
|
|
101
|
+
if (!lease)
|
|
102
|
+
continue;
|
|
103
|
+
const active = signal ? AbortSignal.any([lease.lost, signal]) : lease.lost;
|
|
104
|
+
try {
|
|
105
|
+
const identity = this.identity.resolve(plugin);
|
|
106
|
+
const login = identity.separate ? identity.login : null;
|
|
107
|
+
await asPlatform("Relay extension handoffs and their outbox references", async () => {
|
|
108
|
+
await this.redrive(plugin, login, ring, active);
|
|
109
|
+
await this.ingest(plugin, login, ring, active);
|
|
110
|
+
await this.cleanup(plugin, login, ring, active);
|
|
111
|
+
});
|
|
112
|
+
await this.status.clearNote(plugin, HANDOFF_MISSING);
|
|
113
|
+
}
|
|
114
|
+
catch (error) {
|
|
115
|
+
const failure = classifyEffectFailure(error);
|
|
116
|
+
if (failure.code === "handoff_missing") {
|
|
117
|
+
this.log.error("Extension handoff health fault", {
|
|
118
|
+
plugin,
|
|
119
|
+
code: failure.code,
|
|
120
|
+
message: failure.message,
|
|
121
|
+
});
|
|
122
|
+
await this.status.note(plugin, HANDOFF_MISSING);
|
|
123
|
+
}
|
|
124
|
+
else {
|
|
125
|
+
this.log.warn("Extension handoff relay failed", { plugin, code: failure.code });
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
finally {
|
|
129
|
+
await lease.release();
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
async redrive(plugin, login, ring, signal) {
|
|
134
|
+
// org-filter: deployment-wide outbox scan by plugin; only the verified envelope supplies delivery scope.
|
|
135
|
+
const rows = await asPlatform("Find due extension redrive references", () => this.db.db
|
|
136
|
+
.selectFrom("outbox")
|
|
137
|
+
.select(["id", "org_id", "data"])
|
|
138
|
+
.where("job_name", "=", EXTENSION_EFFECT_REDRIVE_JOB)
|
|
139
|
+
.where(sql `data->>'plugin' = ${plugin}`)
|
|
140
|
+
.where("dead_at", "is", null)
|
|
141
|
+
.where("next_attempt_at", "<=", sql `now()`)
|
|
142
|
+
.orderBy("id")
|
|
143
|
+
.limit(BATCH)
|
|
144
|
+
.execute());
|
|
145
|
+
for (const row of rows) {
|
|
146
|
+
if (signal.aborted)
|
|
147
|
+
return;
|
|
148
|
+
try {
|
|
149
|
+
const reference = row.data;
|
|
150
|
+
if (typeof reference.rowId !== "string" || typeof reference.hash !== "string") {
|
|
151
|
+
throw new ExtensionEffectFailure("handoff_changed", "The redrive reference is invalid");
|
|
152
|
+
}
|
|
153
|
+
const source = await readHandoffRow(this.db.pool, plugin, login, reference.rowId);
|
|
154
|
+
if (!source || handoffReference(plugin, source).hash !== reference.hash) {
|
|
155
|
+
throw new ExtensionEffectFailure("handoff_changed", "The original handoff is missing or has changed");
|
|
156
|
+
}
|
|
157
|
+
const body = await this.effects.verify(source.envelope, await ring(source));
|
|
158
|
+
if (body.plugin !== plugin || body.orgId !== row.org_id) {
|
|
159
|
+
throw new ExtensionEffectFailure("scope_mismatch", "The verified handoff scope differs from the redrive row");
|
|
160
|
+
}
|
|
161
|
+
await withOrgScope(body.orgId, () => this.effects.deliver(body));
|
|
162
|
+
// org-filter: the deployment relay settles the redrive row by its kernel-owned ID.
|
|
163
|
+
await this.db.db.deleteFrom("outbox").where("id", "=", row.id).execute();
|
|
164
|
+
await settleHandoff(this.db.pool, plugin, login, source.id);
|
|
165
|
+
}
|
|
166
|
+
catch (error) {
|
|
167
|
+
if (!(error instanceof ExtensionEnvelopeClockSkew))
|
|
168
|
+
await this.dispatcher.deferDirect(row.id, effectFailureMessage(classifyEffectFailure(error)));
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
async ingest(plugin, login, ring, signal) {
|
|
173
|
+
const rows = await readHandoff(this.db.pool, plugin, login, BATCH);
|
|
174
|
+
let parks = 0;
|
|
175
|
+
for (const row of rows) {
|
|
176
|
+
if (signal.aborted)
|
|
177
|
+
return;
|
|
178
|
+
let body;
|
|
179
|
+
let verified = false;
|
|
180
|
+
let failure;
|
|
181
|
+
try {
|
|
182
|
+
body = await this.effects.verify(row.envelope, await ring(row));
|
|
183
|
+
if (body.plugin !== plugin) {
|
|
184
|
+
throw new ExtensionEffectFailure("scope_mismatch", "The verified handoff belongs to another extension");
|
|
185
|
+
}
|
|
186
|
+
verified = true;
|
|
187
|
+
const effect = body;
|
|
188
|
+
await withOrgScope(effect.orgId, () => this.effects.deliver(effect));
|
|
189
|
+
}
|
|
190
|
+
catch (error) {
|
|
191
|
+
if (error instanceof ExtensionEnvelopeClockSkew)
|
|
192
|
+
continue;
|
|
193
|
+
if (!verified &&
|
|
194
|
+
!(error instanceof InvalidExtensionEnvelope || error instanceof ExtensionEffectFailure))
|
|
195
|
+
throw error;
|
|
196
|
+
failure = classifyEffectFailure(error);
|
|
197
|
+
const reason = effectFailureMessage(failure);
|
|
198
|
+
if ((verified && row.attempts < LAST_RETRY) || parks >= PARK_BUDGET) {
|
|
199
|
+
await retryHandoff(this.db.pool, plugin, login, row, reason);
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
const reference = handoffReference(plugin, row);
|
|
203
|
+
const org = verified ? body?.orgId : undefined;
|
|
204
|
+
const jobId = `extension-handoff-${effectHash([plugin, row.id])}`;
|
|
205
|
+
if (!(await this.effects.park(org, jobId, reference, reason, row.attempts + 1))) {
|
|
206
|
+
await retryHandoff(this.db.pool, plugin, login, row, reason);
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
parks++;
|
|
210
|
+
if (verified) {
|
|
211
|
+
await markHandoffParked(this.db.pool, plugin, login, row.id, reason);
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
await settleHandoff(this.db.pool, plugin, login, row.id);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
async cleanup(plugin, login, ring, signal) {
|
|
219
|
+
for (const row of await readUnreferencedParks(this.db.pool, plugin, login, BATCH)) {
|
|
220
|
+
if (signal.aborted)
|
|
221
|
+
return;
|
|
222
|
+
const body = await this.effects.verify(row.envelope, await ring(row));
|
|
223
|
+
if (body.plugin !== plugin)
|
|
224
|
+
throw new ExtensionEffectFailure("scope_mismatch", "The parked row belongs to a different extension");
|
|
225
|
+
const cancelled = await withOrgScope(body.orgId, () => this.effects.cancelIfDeleted(body));
|
|
226
|
+
if (cancelled || !row.has_reference)
|
|
227
|
+
await settleHandoff(this.db.pool, plugin, login, row.id);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
};
|
|
231
|
+
__decorate([
|
|
232
|
+
LockedInterval(EXTENSION_HANDOFF_RELAY, () => 2000)
|
|
233
|
+
], ExtensionEffectRelay.prototype, "relay", null);
|
|
234
|
+
__decorate([
|
|
235
|
+
LockedInterval("extension-effect-key-retirement", () => 60_000)
|
|
236
|
+
], ExtensionEffectRelay.prototype, "retireKeys", null);
|
|
237
|
+
ExtensionEffectRelay = __decorate([
|
|
238
|
+
Injectable(),
|
|
239
|
+
__param(0, Inject(OutboxDispatcher)),
|
|
240
|
+
__param(1, Inject(ExtensionEffects)),
|
|
241
|
+
__param(2, Inject(ExtensionEffectKeys)),
|
|
242
|
+
__param(3, Inject(ConfiguredExtensionDbIdentity)),
|
|
243
|
+
__param(4, Inject(ExtensionRegistry)),
|
|
244
|
+
__param(5, Inject(ReplicaStatusStore)),
|
|
245
|
+
__param(6, Inject(KernelDb)),
|
|
246
|
+
__param(7, Inject(KernelConfigService)),
|
|
247
|
+
__param(8, Inject(LockService)),
|
|
248
|
+
__param(9, Inject(KERNEL_LOGGER))
|
|
249
|
+
], ExtensionEffectRelay);
|
|
250
|
+
export { ExtensionEffectRelay };
|
package/dist/ctx/queue.d.ts
CHANGED
|
@@ -11,6 +11,8 @@ export declare function createQueue(redisUrl: string, namespace: string, opts: {
|
|
|
11
11
|
runWorkers: boolean;
|
|
12
12
|
log?: Pick<Logger, "error">;
|
|
13
13
|
}): ExtensionContext["queue"] & {
|
|
14
|
+
hasDefined(name: string): boolean;
|
|
15
|
+
dispatchEffect(name: string, data: unknown, jobId: string, delayMs?: number): Promise<void>;
|
|
14
16
|
close(): Promise<void>;
|
|
15
17
|
/** 停止取新任务(不等进行中的):撤销插件实例的第一步。 */
|
|
16
18
|
pauseWorkers(): Promise<void>;
|
package/dist/ctx/queue.js
CHANGED
|
@@ -51,7 +51,24 @@ export function createQueue(redisUrl, namespace, opts) {
|
|
|
51
51
|
}
|
|
52
52
|
return q;
|
|
53
53
|
};
|
|
54
|
+
const add = async (name, data, o) => {
|
|
55
|
+
assertOpen();
|
|
56
|
+
assertNoColon("queue name", name);
|
|
57
|
+
if (o?.jobId !== undefined)
|
|
58
|
+
assertNoColon("jobId", o.jobId);
|
|
59
|
+
const jobOptions = {
|
|
60
|
+
capybaraScope: currentScope() ?? null,
|
|
61
|
+
...(o?.jobId !== undefined && { jobId: o.jobId }),
|
|
62
|
+
...(o?.delayMs !== undefined && { delay: o.delayMs }),
|
|
63
|
+
attempts: 3,
|
|
64
|
+
backoff: { type: "exponential", delay: 1000 },
|
|
65
|
+
removeOnComplete: 1000,
|
|
66
|
+
removeOnFail: 5000,
|
|
67
|
+
};
|
|
68
|
+
await getQueue(name).add(name, data, jobOptions);
|
|
69
|
+
};
|
|
54
70
|
return {
|
|
71
|
+
hasDefined: (name) => !closed && defined.has(name),
|
|
55
72
|
define(name, handler, o) {
|
|
56
73
|
assertOpen();
|
|
57
74
|
assertNoColon("queue name", name);
|
|
@@ -83,21 +100,11 @@ export function createQueue(redisUrl, namespace, opts) {
|
|
|
83
100
|
worker.on("failed", (job, err) => log.error("queue job failed", { queue: name, jobId: job?.id, err }));
|
|
84
101
|
workers.set(name, worker);
|
|
85
102
|
},
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
const jobOptions = {
|
|
92
|
-
capybaraScope: currentScope() ?? null,
|
|
93
|
-
...(o?.jobId !== undefined && { jobId: o.jobId }),
|
|
94
|
-
...(o?.delayMs !== undefined && { delay: o.delayMs }),
|
|
95
|
-
attempts: 3,
|
|
96
|
-
backoff: { type: "exponential", delay: 1000 },
|
|
97
|
-
removeOnComplete: 1000,
|
|
98
|
-
removeOnFail: 5000,
|
|
99
|
-
};
|
|
100
|
-
await getQueue(name).add(name, data, jobOptions);
|
|
103
|
+
add,
|
|
104
|
+
async dispatchEffect(name, data, jobId, delayMs) {
|
|
105
|
+
if (!defined.has(name))
|
|
106
|
+
throw new Error("Extension effect queue is not registered");
|
|
107
|
+
await add(name, data, { jobId, ...(delayMs === undefined ? {} : { delayMs }) });
|
|
101
108
|
},
|
|
102
109
|
async pauseWorkers() {
|
|
103
110
|
await Promise.all([...workers.values()].map((w) => w.pause(true).catch(() => { })));
|
|
@@ -5,11 +5,15 @@ export type ExtensionDbConnection = {
|
|
|
5
5
|
login: string;
|
|
6
6
|
url: string;
|
|
7
7
|
separate: boolean;
|
|
8
|
+
/** Only dedicated identities can be handed to an isolated extension. */
|
|
9
|
+
dedicated?: true;
|
|
8
10
|
};
|
|
9
11
|
/** Kernel-owned credentials, resolved from the canonical extension name. */
|
|
10
12
|
export interface ExtensionDbIdentity {
|
|
11
13
|
resolve(name: string): ExtensionDbConnection;
|
|
12
14
|
readonly sharedLogin?: string | undefined;
|
|
15
|
+
/** Used only by the one-shot operator to provision staged extensions. */
|
|
16
|
+
provisionedNames?(): string[];
|
|
13
17
|
}
|
|
14
18
|
export declare class ConfiguredExtensionDbIdentity implements ExtensionDbIdentity {
|
|
15
19
|
private readonly identity;
|
|
@@ -17,11 +21,12 @@ export declare class ConfiguredExtensionDbIdentity implements ExtensionDbIdentit
|
|
|
17
21
|
get sharedLogin(): string | undefined;
|
|
18
22
|
resolve(name: string): ExtensionDbConnection;
|
|
19
23
|
}
|
|
20
|
-
export declare function
|
|
24
|
+
export declare function validateExtensionCredentials(db: Pick<KernelConfig["db"], "extensionsUrl" | "extensionCredentialsDir">): void;
|
|
25
|
+
export declare function extensionDbIdentity(db: Pick<KernelConfig["db"], "url" | "extensionsUrl" | "extensionCredentialsDir">): ExtensionDbIdentity;
|
|
21
26
|
export declare function pluginSchemaName(name: string): string;
|
|
22
|
-
export declare function assertExtensionSession(client: pg.ClientBase, login: string): Promise<void>;
|
|
27
|
+
export declare function assertExtensionSession(client: pg.ClientBase, login: string, dedicatedSchema?: string): Promise<void>;
|
|
23
28
|
/** A missing schema is normal before a plugin's first migration. */
|
|
24
|
-
export declare function assertExtensionSchemaOwner(client: pg.ClientBase, schema: string, login: string): Promise<void>;
|
|
29
|
+
export declare function assertExtensionSchemaOwner(client: pg.ClientBase, schema: string, login: string, required?: boolean): Promise<void>;
|
|
25
30
|
/** One small, scope-aware pool per active extension instance. The host owns its lifetime. */
|
|
26
31
|
export declare function extensionDbPool(identity: ExtensionDbConnection, name: string, config: {
|
|
27
32
|
connectTimeoutMs?: number | undefined;
|
package/dist/db/extension-db.js
CHANGED
|
@@ -7,6 +7,10 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
|
|
|
7
7
|
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
8
8
|
return function (target, key) { decorator(target, key, paramIndex); }
|
|
9
9
|
};
|
|
10
|
+
import { createHash } from "node:crypto";
|
|
11
|
+
import { closeSync, constants, fstatSync, openSync, readdirSync, readFileSync } from "node:fs";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
import { EXTENSION_NAME_RE } from "@capybara-hq/plugin-sdk";
|
|
10
14
|
import { Inject, Injectable } from "@nestjs/common";
|
|
11
15
|
import pg from "pg";
|
|
12
16
|
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
@@ -28,19 +32,99 @@ ConfiguredExtensionDbIdentity = __decorate([
|
|
|
28
32
|
__param(0, Inject(KernelConfigService))
|
|
29
33
|
], ConfiguredExtensionDbIdentity);
|
|
30
34
|
export { ConfiguredExtensionDbIdentity };
|
|
35
|
+
function readExtensionPassword(directory, name) {
|
|
36
|
+
if (!EXTENSION_NAME_RE.test(name))
|
|
37
|
+
throw new Error(`Invalid extension name: ${name}`);
|
|
38
|
+
let fd;
|
|
39
|
+
try {
|
|
40
|
+
fd = openSync(join(directory, `${name}.password`), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
throw new Error(`Cannot open database credential for extension ${name} in db.extensionCredentialsDir`);
|
|
44
|
+
}
|
|
45
|
+
try {
|
|
46
|
+
const info = fstatSync(fd);
|
|
47
|
+
if (!info.isFile() || (info.mode & 0o7777) !== 0o600)
|
|
48
|
+
throw new Error(`Database credential for extension ${name} must be a regular file with mode 0600`);
|
|
49
|
+
const password = readFileSync(fd, "utf8").replace(/\r?\n$/, "");
|
|
50
|
+
if (!password ||
|
|
51
|
+
[...password].some((character) => {
|
|
52
|
+
const code = character.charCodeAt(0);
|
|
53
|
+
return code < 32 || code > 126;
|
|
54
|
+
})) {
|
|
55
|
+
throw new Error(`Database credential for extension ${name} must contain a printable ASCII password`);
|
|
56
|
+
}
|
|
57
|
+
return password;
|
|
58
|
+
}
|
|
59
|
+
finally {
|
|
60
|
+
closeSync(fd);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function credentialNames(directory) {
|
|
64
|
+
try {
|
|
65
|
+
return readdirSync(directory)
|
|
66
|
+
.filter((file) => file.endsWith(".password"))
|
|
67
|
+
.map((file) => file.slice(0, -".password".length))
|
|
68
|
+
.sort();
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
throw new Error("Cannot read db.extensionCredentialsDir");
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
export function validateExtensionCredentials(db) {
|
|
75
|
+
if (db.extensionsUrl === undefined)
|
|
76
|
+
return;
|
|
77
|
+
const directory = db.extensionCredentialsDir;
|
|
78
|
+
if (!directory)
|
|
79
|
+
throw new Error("db.extensionsUrl requires db.extensionCredentialsDir");
|
|
80
|
+
const seen = new Map();
|
|
81
|
+
for (const name of credentialNames(directory)) {
|
|
82
|
+
const fingerprint = createHash("sha256")
|
|
83
|
+
.update(readExtensionPassword(directory, name))
|
|
84
|
+
.digest("hex");
|
|
85
|
+
const other = seen.get(fingerprint);
|
|
86
|
+
if (other)
|
|
87
|
+
throw new Error(`Database credentials for extensions ${other} and ${name} must use distinct passwords`);
|
|
88
|
+
seen.set(fingerprint, name);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
31
91
|
export function extensionDbIdentity(db) {
|
|
32
92
|
const url = db.extensionsUrl ?? db.url;
|
|
33
93
|
const separate = db.extensionsUrl !== undefined;
|
|
34
|
-
let
|
|
94
|
+
let endpoint;
|
|
35
95
|
try {
|
|
36
|
-
|
|
96
|
+
endpoint = new pg.Client({ connectionString: url });
|
|
37
97
|
}
|
|
38
98
|
catch {
|
|
39
99
|
throw new Error("Invalid PostgreSQL connection URL for extensions");
|
|
40
100
|
}
|
|
101
|
+
const { user: login, database } = endpoint;
|
|
41
102
|
if (!login)
|
|
42
103
|
throw new Error("PostgreSQL connection needs a login");
|
|
43
|
-
|
|
104
|
+
const directory = db.extensionCredentialsDir;
|
|
105
|
+
if (!separate)
|
|
106
|
+
return { resolve: () => ({ login, url, separate: false }) };
|
|
107
|
+
if (!directory)
|
|
108
|
+
throw new Error("db.extensionsUrl requires db.extensionCredentialsDir");
|
|
109
|
+
if (!database)
|
|
110
|
+
throw new Error("Dedicated extension connections need a PostgreSQL database");
|
|
111
|
+
if (!URL.canParse(url))
|
|
112
|
+
throw new Error("db.extensionsUrl must be a PostgreSQL URL");
|
|
113
|
+
return {
|
|
114
|
+
sharedLogin: login,
|
|
115
|
+
provisionedNames: () => credentialNames(directory),
|
|
116
|
+
resolve(name) {
|
|
117
|
+
const password = readExtensionPassword(directory, name);
|
|
118
|
+
const hash = createHash("sha256").update(database).update("\0").update(name).digest("hex");
|
|
119
|
+
const username = `cap_ext_${hash.slice(0, 40)}`;
|
|
120
|
+
const target = new URL(url);
|
|
121
|
+
target.searchParams.delete("user");
|
|
122
|
+
target.searchParams.delete("password");
|
|
123
|
+
target.username = username;
|
|
124
|
+
target.password = encodeURIComponent(password);
|
|
125
|
+
return { login: username, url: target.toString(), separate: true, dedicated: true };
|
|
126
|
+
},
|
|
127
|
+
};
|
|
44
128
|
}
|
|
45
129
|
export function pluginSchemaName(name) {
|
|
46
130
|
return `plugin_${name.replaceAll("-", "_")}`;
|
|
@@ -58,17 +142,33 @@ const extensionLoginCheck = `
|
|
|
58
142
|
), false) as isolated
|
|
59
143
|
from pg_catalog.pg_roles r where r.rolname = $1
|
|
60
144
|
`;
|
|
61
|
-
export async function assertExtensionSession(client, login) {
|
|
145
|
+
export async function assertExtensionSession(client, login, dedicatedSchema) {
|
|
62
146
|
const { rows: [actual], } = await client.query("select current_user as login");
|
|
63
147
|
const { rows: [role], } = await client.query(extensionLoginCheck, [login]);
|
|
64
148
|
if (actual?.login !== login || !role?.isolated) {
|
|
65
149
|
throw new Error("db.extensionsUrl must authenticate as a restricted extension login with no access to capybara");
|
|
66
150
|
}
|
|
151
|
+
if (dedicatedSchema !== undefined) {
|
|
152
|
+
const { rows: [privileges], } = await client.query(`select pg_catalog.has_database_privilege(current_database(), 'CREATE') as can_create,
|
|
153
|
+
exists (
|
|
154
|
+
select from pg_catalog.pg_shdepend d
|
|
155
|
+
cross join lateral pg_catalog.pg_identify_object(d.classid, d.objid, d.objsubid) obj
|
|
156
|
+
where d.dbid = (select oid from pg_catalog.pg_database where datname = current_database())
|
|
157
|
+
and d.refclassid = 'pg_catalog.pg_authid'::regclass
|
|
158
|
+
and d.refobjid = current_user::regrole and d.deptype = 'o'
|
|
159
|
+
and coalesce(obj.schema, case when obj.type = 'schema' then obj.name end) <> $1
|
|
160
|
+
) as foreign_owner`, [dedicatedSchema]);
|
|
161
|
+
if (!privileges || privileges.can_create || privileges.foreign_owner)
|
|
162
|
+
throw new Error(`Extension login ${login} has database CREATE or owns objects outside its schema`);
|
|
163
|
+
}
|
|
67
164
|
}
|
|
68
165
|
/** A missing schema is normal before a plugin's first migration. */
|
|
69
|
-
export async function assertExtensionSchemaOwner(client, schema, login) {
|
|
166
|
+
export async function assertExtensionSchemaOwner(client, schema, login, required = false) {
|
|
70
167
|
const { rows: [namespace], } = await client.query(`select pg_catalog.pg_get_userbyid(nspowner) as owner
|
|
71
168
|
from pg_catalog.pg_namespace where nspname = $1`, [schema]);
|
|
169
|
+
if (required && !namespace) {
|
|
170
|
+
throw new Error(`Missing extension schema ${schema}. Run the one-shot extension database provisioner.`);
|
|
171
|
+
}
|
|
72
172
|
if (namespace && namespace.owner !== login) {
|
|
73
173
|
throw new Error(`Extension schema ${schema} is owned by ${namespace.owner}, expected ${login}. Run capybara migrate with the owner URL to transfer plugin schemas.`);
|
|
74
174
|
}
|
|
@@ -83,8 +183,10 @@ export function extensionDbPool(identity, name, config, onError) {
|
|
|
83
183
|
rls: config.rls,
|
|
84
184
|
closeActiveOnDestroy: true,
|
|
85
185
|
onConnect: async (client) => {
|
|
86
|
-
|
|
87
|
-
|
|
186
|
+
if (!identity.separate)
|
|
187
|
+
return;
|
|
188
|
+
await assertExtensionSession(client, identity.login, identity.dedicated ? schema : undefined);
|
|
189
|
+
await assertExtensionSchemaOwner(client, schema, identity.login, identity.dedicated);
|
|
88
190
|
await client.query("select pg_catalog.set_config('search_path', $1, false)", [searchPath]);
|
|
89
191
|
},
|
|
90
192
|
});
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type Kysely } from "kysely";
|
|
2
|
+
import pg from "pg";
|
|
3
|
+
/** Creates a handoff owned by the one-shot provisioner. The extension can append only. */
|
|
4
|
+
export declare function provisionExtensionHandoff(owner: pg.ClientBase, schema: string, extensionLogin: string, runtimeLogin: string): Promise<void>;
|
|
5
|
+
/** Single-login deployments use the kernel's own connection for this table. */
|
|
6
|
+
export declare function ensureLocalExtensionHandoff(db: Kysely<unknown>, dbUrl: string, schema: string, connectTimeoutMs: number | undefined): Promise<void>;
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { sql } from "kysely";
|
|
2
|
+
import pg from "pg";
|
|
3
|
+
import { EXTENSION_EFFECT_HANDOFF } from "../infra/database/extension-handoff.js";
|
|
4
|
+
import { lockMigrationSchema } from "./migrator.js";
|
|
5
|
+
import { pgConnectOptions } from "./pool.js";
|
|
6
|
+
function createHandoffTable(table) {
|
|
7
|
+
return `
|
|
8
|
+
create table if not exists ${table} (
|
|
9
|
+
id uuid primary key,
|
|
10
|
+
created_at timestamptz not null default pg_catalog.now(),
|
|
11
|
+
attempts integer not null default 0,
|
|
12
|
+
last_error text,
|
|
13
|
+
parked_at timestamptz,
|
|
14
|
+
next_attempt_at timestamptz not null default pg_catalog.now(),
|
|
15
|
+
envelope jsonb not null check (pg_catalog.octet_length(envelope::text) <= 131500)
|
|
16
|
+
);
|
|
17
|
+
create index if not exists _capybara_effect_due on ${table} (next_attempt_at, id)
|
|
18
|
+
where parked_at is null;
|
|
19
|
+
create index if not exists _capybara_effect_parked on ${table} (parked_at, id)
|
|
20
|
+
where parked_at is not null;
|
|
21
|
+
create index if not exists _capybara_effect_key on ${table} ((envelope->>'keyId'))
|
|
22
|
+
`;
|
|
23
|
+
}
|
|
24
|
+
/** Creates a handoff owned by the one-shot provisioner. The extension can append only. */
|
|
25
|
+
export async function provisionExtensionHandoff(owner, schema, extensionLogin, runtimeLogin) {
|
|
26
|
+
await lockMigrationSchema(owner, schema, "transaction");
|
|
27
|
+
const ns = pg.escapeIdentifier(schema);
|
|
28
|
+
const writer = pg.escapeIdentifier(extensionLogin);
|
|
29
|
+
const reader = pg.escapeIdentifier(runtimeLogin);
|
|
30
|
+
const table = `${ns}.${pg.escapeIdentifier(EXTENSION_EFFECT_HANDOFF)}`;
|
|
31
|
+
await owner.query(`create schema if not exists ${ns} authorization ${writer}`);
|
|
32
|
+
await owner.query(createHandoffTable(table));
|
|
33
|
+
const { rows: [relation], } = await owner.query(`
|
|
34
|
+
select c.relowner = (select oid from pg_roles where rolname = current_user) and c.relkind = 'r' as valid
|
|
35
|
+
from pg_class c where c.oid = to_regclass($1)
|
|
36
|
+
`, [table]);
|
|
37
|
+
if (!relation?.valid)
|
|
38
|
+
throw new Error(`Invalid handoff owner or type for ${schema}`);
|
|
39
|
+
await owner.query(`revoke all on table ${table} from public, ${writer}`);
|
|
40
|
+
await owner.query(`grant insert (id, envelope) on table ${table} to ${writer}`);
|
|
41
|
+
await owner.query(`grant usage on schema ${ns} to ${reader}`);
|
|
42
|
+
await owner.query(`grant select, delete on table ${table} to ${reader}`);
|
|
43
|
+
await owner.query(`grant update (attempts, last_error, next_attempt_at, parked_at) on table ${table} to ${reader}`);
|
|
44
|
+
}
|
|
45
|
+
/** Single-login deployments use the kernel's own connection for this table. */
|
|
46
|
+
export async function ensureLocalExtensionHandoff(db, dbUrl, schema, connectTimeoutMs) {
|
|
47
|
+
const qualified = `${schema}.${EXTENSION_EFFECT_HANDOFF}`;
|
|
48
|
+
const existing = await sql `
|
|
49
|
+
select pg_catalog.to_regclass(${qualified}) is not null as present
|
|
50
|
+
`.execute(db);
|
|
51
|
+
if (existing.rows[0]?.present)
|
|
52
|
+
return;
|
|
53
|
+
const client = new pg.Client({
|
|
54
|
+
connectionString: dbUrl,
|
|
55
|
+
...pgConnectOptions({ connectTimeoutMs }),
|
|
56
|
+
});
|
|
57
|
+
client.on("error", () => { });
|
|
58
|
+
try {
|
|
59
|
+
await client.connect();
|
|
60
|
+
await client.query("begin");
|
|
61
|
+
await client.query("set local lock_timeout = '5s'");
|
|
62
|
+
await lockMigrationSchema(client, schema, "transaction");
|
|
63
|
+
const ns = pg.escapeIdentifier(schema);
|
|
64
|
+
const table = `${ns}.${pg.escapeIdentifier(EXTENSION_EFFECT_HANDOFF)}`;
|
|
65
|
+
await client.query(`create schema if not exists ${ns}`);
|
|
66
|
+
await client.query(createHandoffTable(table));
|
|
67
|
+
await client.query("commit");
|
|
68
|
+
}
|
|
69
|
+
finally {
|
|
70
|
+
await client.end();
|
|
71
|
+
}
|
|
72
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import pg from "pg";
|
|
2
|
+
import type { KernelConfig } from "../config/schema.js";
|
|
3
|
+
import type { ExtensionDbConnection } from "./extension-db.js";
|
|
4
|
+
export declare const EMPTY_EXTENSION_SCHEMA_COMMENT = "Capybara provisioned empty extension schema";
|
|
5
|
+
export declare function createProvisionedExtensionSchema(admin: pg.ClientBase, schema: string, login: string): Promise<void>;
|
|
6
|
+
type ExtensionLimits = Pick<KernelConfig["db"], "extensionConnectionLimit" | "extensionStatementTimeoutMs" | "extensionIdleTransactionTimeoutMs" | "extensionTempFileLimitKb">;
|
|
7
|
+
/** Runs in the operator transaction under the extension provisioning lock. */
|
|
8
|
+
export declare function provisionExtensionRole(admin: pg.ClientBase, name: string, identity: ExtensionDbConnection, limits: ExtensionLimits): Promise<boolean>;
|
|
9
|
+
export {};
|