@capybara-hq/kernel 0.1.0-rc.133 → 0.1.0-rc.134

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.
Files changed (54) hide show
  1. package/dist/automations/events/trigger-events.service.d.ts +13 -1
  2. package/dist/automations/events/trigger-events.service.js +27 -14
  3. package/dist/catalog/marketplaces.service.d.ts +1 -1
  4. package/dist/config/schema.d.ts +1 -0
  5. package/dist/config/schema.js +7 -0
  6. package/dist/ctx/create-ctx.d.ts +4 -0
  7. package/dist/ctx/create-ctx.js +74 -27
  8. package/dist/ctx/durable-cancellation.d.ts +3 -0
  9. package/dist/ctx/durable-cancellation.js +8 -0
  10. package/dist/ctx/durable-effects.service.d.ts +81 -0
  11. package/dist/ctx/durable-effects.service.js +316 -0
  12. package/dist/ctx/durable-envelope.d.ts +24 -0
  13. package/dist/ctx/durable-envelope.js +80 -0
  14. package/dist/ctx/durable-failure.d.ts +7 -0
  15. package/dist/ctx/durable-failure.js +32 -0
  16. package/dist/ctx/durable-job.d.ts +9 -0
  17. package/dist/ctx/durable-job.js +2 -0
  18. package/dist/ctx/durable-keys.d.ts +27 -0
  19. package/dist/ctx/durable-keys.js +138 -0
  20. package/dist/ctx/durable-relay.d.ts +29 -0
  21. package/dist/ctx/durable-relay.js +250 -0
  22. package/dist/ctx/queue.d.ts +2 -0
  23. package/dist/ctx/queue.js +22 -15
  24. package/dist/db/extension-db.js +2 -0
  25. package/dist/db/extension-handoff-schema.d.ts +6 -0
  26. package/dist/db/extension-handoff-schema.js +72 -0
  27. package/dist/db/extension-schema-transfer.d.ts +1 -1
  28. package/dist/db/extension-schema-transfer.js +18 -6
  29. package/dist/db/kernel-schema.d.ts +16 -0
  30. package/dist/erasure/org-catalog.js +2 -2
  31. package/dist/erasure/org-rules.js +1 -0
  32. package/dist/extensions/extensions.module.js +10 -0
  33. package/dist/extensions/host.d.ts +5 -0
  34. package/dist/extensions/host.js +33 -20
  35. package/dist/extensions/instance.d.ts +2 -0
  36. package/dist/extensions/instance.js +6 -0
  37. package/dist/extensions/sources.d.ts +1 -0
  38. package/dist/extensions/sources.js +9 -0
  39. package/dist/inbox/inbox-items.service.d.ts +5 -0
  40. package/dist/inbox/inbox-items.service.js +57 -33
  41. package/dist/infra/database/extension-effect-key-lock.d.ts +10 -0
  42. package/dist/infra/database/extension-effect-key-lock.js +69 -0
  43. package/dist/infra/database/extension-handoff.d.ts +27 -0
  44. package/dist/infra/database/extension-handoff.js +113 -0
  45. package/dist/infra/outbox/outbox.dispatcher.d.ts +6 -1
  46. package/dist/infra/outbox/outbox.dispatcher.js +64 -4
  47. package/dist/infra/outbox/outbox.module.js +2 -0
  48. package/dist/infra/outbox/registry.d.ts +12 -0
  49. package/dist/infra/outbox/registry.js +12 -0
  50. package/dist/kernel.js +1 -0
  51. package/dist/orgs/orgs.service.js +16 -0
  52. package/dist/roles/worker.module.js +2 -0
  53. package/package.json +2 -2
  54. package/src/migrations/0225_extension_effect_receipts.sql +25 -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 };
@@ -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
- async add(name, data, o) {
87
- assertOpen();
88
- assertNoColon("queue name", name);
89
- if (o?.jobId !== undefined)
90
- assertNoColon("jobId", o.jobId);
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(() => { })));
@@ -83,6 +83,8 @@ export function extensionDbPool(identity, name, config, onError) {
83
83
  rls: config.rls,
84
84
  closeActiveOnDestroy: true,
85
85
  onConnect: async (client) => {
86
+ if (!identity.separate)
87
+ return;
86
88
  await assertExtensionSession(client, identity.login);
87
89
  await assertExtensionSchemaOwner(client, schema, identity.login);
88
90
  await client.query("select pg_catalog.set_config('search_path', $1, false)", [searchPath]);
@@ -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
+ }
@@ -3,4 +3,4 @@ import { type ExtensionDbIdentity } from "./extension-db.js";
3
3
  * One-shot cutover. The URL authenticates the bootstrap/legacy login, which must be able
4
4
  * to transfer ownership. Run before starting replicas with the new extension identity.
5
5
  */
6
- export declare function transferKnownExtensionSchemas(bootstrapUrl: string, identity: ExtensionDbIdentity, declaredNames: Iterable<string>, connectTimeoutMs?: number): Promise<void>;
6
+ export declare function transferKnownExtensionSchemas(bootstrapUrl: string, identity: ExtensionDbIdentity, declaredNames: Iterable<string>, connectTimeoutMs?: number, runtimeLogin?: string): Promise<void>;
@@ -1,6 +1,8 @@
1
1
  import { EXTENSION_NAME_RE } from "@capybara-hq/plugin-sdk";
2
2
  import pg from "pg";
3
+ import { EXTENSION_EFFECT_HANDOFF } from "../infra/database/extension-handoff.js";
3
4
  import { assertExtensionSession, pluginSchemaName, } from "./extension-db.js";
5
+ import { provisionExtensionHandoff } from "./extension-handoff-schema.js";
4
6
  import { assertSameMigrationDatabase, lockMigrationSchema } from "./migrator.js";
5
7
  import { pgConnectOptions } from "./pool.js";
6
8
  async function transferExtensionSchema(client, schema, target, sources) {
@@ -42,15 +44,17 @@ async function transferExtensionSchema(client, schema, target, sources) {
42
44
  exists (
43
45
  select from pg_depend d where d.classid = o.classid and d.objid = o.objid
44
46
  and d.objsubid = 0 and d.refclassid = 'pg_extension'::regclass and d.deptype = 'e'
45
- ) as extension_member
47
+ ) as extension_member,
48
+ (c.relname = $2 or (t.typname = $2 and t.typrelid <> 0)) as handoff
46
49
  from objects o
47
50
  cross join lateral pg_identify_object(o.classid, o.objid, 0) object
48
51
  left join pg_class c on o.classid = 'pg_class'::regclass and c.oid = o.objid
49
52
  left join pg_proc p on o.classid = 'pg_proc'::regclass and p.oid = o.objid
50
53
  left join pg_type t on o.classid = 'pg_type'::regclass and t.oid = o.objid
51
54
  order by object.identity
52
- `, [namespace.oid]);
53
- const unexpected = objects.filter((object) => !object.kind ||
55
+ `, [namespace.oid, EXTENSION_EFFECT_HANDOFF]);
56
+ const owned = objects.filter((object) => !object.handoff);
57
+ const unexpected = owned.filter((object) => !object.kind ||
54
58
  object.extension_member ||
55
59
  (object.owner !== target && object.owner !== namespace.owner));
56
60
  if (unexpected.length) {
@@ -62,7 +66,7 @@ async function transferExtensionSchema(client, schema, target, sources) {
62
66
  await client.query(`alter schema ${pg.escapeIdentifier(schema)} owner to ${quotedTarget}`);
63
67
  }
64
68
  // PostgreSQL moves table-owned sequences, row types and indexes with their parent table.
65
- for (const object of objects) {
69
+ for (const object of owned) {
66
70
  if (object.kind && object.owner !== target && !object.attached_sequence) {
67
71
  // Kind is from the fixed catalog mapping. PostgreSQL returns the quoted object identity.
68
72
  await client.query(`alter ${object.kind} ${object.identity} owner to ${quotedTarget}`);
@@ -91,7 +95,7 @@ async function confirmTargetDatabase(owner, target, connectTimeoutMs) {
91
95
  * One-shot cutover. The URL authenticates the bootstrap/legacy login, which must be able
92
96
  * to transfer ownership. Run before starting replicas with the new extension identity.
93
97
  */
94
- export async function transferKnownExtensionSchemas(bootstrapUrl, identity, declaredNames, connectTimeoutMs) {
98
+ export async function transferKnownExtensionSchemas(bootstrapUrl, identity, declaredNames, connectTimeoutMs, runtimeLogin) {
95
99
  const owner = new pg.Client({
96
100
  connectionString: bootstrapUrl,
97
101
  ...pgConnectOptions({ connectTimeoutMs }),
@@ -103,7 +107,10 @@ export async function transferKnownExtensionSchemas(bootstrapUrl, identity, decl
103
107
  try {
104
108
  await owner.query("set local search_path = pg_catalog");
105
109
  await owner.query("set local lock_timeout = '30s'");
106
- const { rows: [legacy], } = await owner.query("select current_user as login");
110
+ const { rows: [legacy], } = await owner.query(`
111
+ select current_user as login,
112
+ pg_catalog.has_database_privilege(pg_catalog.current_database(), 'CREATE') as can_create
113
+ `);
107
114
  if (!legacy)
108
115
  throw new Error("Could not verify the schema transfer login");
109
116
  const { rows: registered } = await owner.query(`select name from capybara.extension_name_owners
@@ -127,6 +134,11 @@ export async function transferKnownExtensionSchemas(bootstrapUrl, identity, decl
127
134
  }
128
135
  for (const { schema, target } of targets) {
129
136
  await transferExtensionSchema(owner, schema, target.login, sources);
137
+ // Repeated migrations may use the restricted runtime login. Only the one-shot
138
+ // provisioner can create the contract table and grant access to it.
139
+ if (runtimeLogin !== undefined && legacy.can_create) {
140
+ await provisionExtensionHandoff(owner, schema, target.login, runtimeLogin);
141
+ }
130
142
  }
131
143
  await owner.query("commit");
132
144
  }
@@ -1843,6 +1843,20 @@ export interface StoredInboxAction {
1843
1843
  };
1844
1844
  }
1845
1845
  export type InboxItemState = "open" | "resolved" | "expired";
1846
+ export interface ExtensionEffectCancellationsTable {
1847
+ id: string;
1848
+ plugin: string;
1849
+ reason: string;
1850
+ cancelled_at: Ts;
1851
+ }
1852
+ export interface ExtensionEffectReceiptsTable {
1853
+ org_id: string;
1854
+ plugin: string;
1855
+ kind: string;
1856
+ effect_key: string;
1857
+ payload_hash: string;
1858
+ result: Json<unknown>;
1859
+ }
1846
1860
  /** 0192: a personal inbox item (collaboration spec §4.9), for one person in one org. */
1847
1861
  export interface InboxItemsTable {
1848
1862
  id: string;
@@ -2108,6 +2122,8 @@ export interface KernelDatabase {
2108
2122
  trigger_events: TriggerEventsTable;
2109
2123
  trigger_cause_handles: TriggerCauseHandlesTable;
2110
2124
  inbox_items: InboxItemsTable;
2125
+ extension_effect_receipts: ExtensionEffectReceiptsTable;
2126
+ extension_effect_cancellations: ExtensionEffectCancellationsTable;
2111
2127
  automation_acceptance: AutomationAcceptanceTable;
2112
2128
  automation_offers: AutomationOffersTable;
2113
2129
  automation_event_deliveries: AutomationEventDeliveriesTable;
@@ -1,5 +1,5 @@
1
1
  import { sql } from "kysely";
2
- // PostgreSQL 17 after 0223. Re-review the ownership map before updating this fingerprint.
2
+ // PostgreSQL 17 after 0225. Re-review the ownership map before updating this fingerprint.
3
3
  // It includes relation/column identities and ordered PK, UNIQUE and inbound/outbound FK
4
4
  // columns and actions, including FKs from outside the kernel schema.
5
5
  export async function orgCatalogDrift(db) {
@@ -30,5 +30,5 @@ WITH catalog AS (
30
30
  )
31
31
  SELECT md5(string_agg(entry, chr(10) ORDER BY entry COLLATE "C")) AS fingerprint FROM catalog
32
32
  `.execute(db);
33
- return rows[0]?.fingerprint === "e1db306cfaad233fd8970147ed2ca6a4" ? undefined : "schema-drift";
33
+ return rows[0]?.fingerprint === "3693e0b7004dae3c5721abfadc80e1e8" ? undefined : "schema-drift";
34
34
  }
@@ -100,6 +100,7 @@ export const rowRules = [
100
100
  ];
101
101
  export const anonymousAccountRule = rule("org_anonymous_accounts", "org_id");
102
102
  export const lateRules = [
103
+ rule("extension_effect_receipts", "org_id, plugin, kind, effect_key"),
103
104
  rule("retention_coverage", "org_id"),
104
105
  rule("audit_events", "id"),
105
106
  rule("outbox", "id"),
@@ -5,9 +5,13 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
5
5
  return c > 3 && r && Object.defineProperty(target, key, r), r;
6
6
  };
7
7
  import { Module } from "@nestjs/common";
8
+ import { TriggerEventsModule } from "../automations/events/events.module.js";
9
+ import { ExtensionEffects } from "../ctx/durable-effects.service.js";
10
+ import { ExtensionEffectKeys } from "../ctx/durable-keys.js";
8
11
  import { ConfiguredExtensionDbIdentity } from "../db/extension-db.js";
9
12
  import { DialInRelayModule } from "../dial-in/relay.module.js";
10
13
  import { SuperAdminLockModule } from "../identity/super-admin.js";
14
+ import { InboxItemsModule } from "../inbox/inbox-items.service.js";
11
15
  import { ModelsModule } from "../models/models.module.js";
12
16
  import { OrgNetworkAllowancesModule } from "../orgs/network-allowances.service.js";
13
17
  import { OrgLockModule } from "../orgs/org-lock.js";
@@ -46,6 +50,8 @@ ExtensionsModule = __decorate([
46
50
  Module({
47
51
  imports: [
48
52
  ExtensionRegistryModule,
53
+ TriggerEventsModule,
54
+ InboxItemsModule,
49
55
  SuperAdminLockModule,
50
56
  OrgLockModule,
51
57
  StorageModule,
@@ -74,6 +80,8 @@ ExtensionsModule = __decorate([
74
80
  ReplicaStatusStore,
75
81
  ConfiguredExtensionDbIdentity,
76
82
  ExtensionHost,
83
+ ExtensionEffects,
84
+ ExtensionEffectKeys,
77
85
  ExtensionLifecycle,
78
86
  ExtensionAdmin,
79
87
  ExtensionAdminOps,
@@ -95,6 +103,8 @@ ExtensionsModule = __decorate([
95
103
  ReplicaStatusStore,
96
104
  ConfiguredExtensionDbIdentity,
97
105
  ExtensionHost,
106
+ ExtensionEffects,
107
+ ExtensionEffectKeys,
98
108
  ExtensionLifecycle,
99
109
  ExtensionAdmin,
100
110
  ExtensionAdminOps,
@@ -5,6 +5,7 @@ import type { KernelAppOptions } from "../app.js";
5
5
  import { TRIGGER_EVENTS_BACKEND } from "../automations/events/token.js";
6
6
  import type { BusSubscriber } from "../ctx/bus.js";
7
7
  import { type DeviceAccessBackend, type InboxBackend, type PluginReadsBackend, type Route, type TriggersBackend } from "../ctx/create-ctx.js";
8
+ import { ExtensionEffects } from "../ctx/durable-effects.service.js";
8
9
  import { type ExtensionNetSeams } from "../ctx/net.js";
9
10
  import type { Keyring } from "../ctx/secrets.js";
10
11
  import { type ExtensionDbIdentity } from "../db/extension-db.js";
@@ -148,6 +149,7 @@ export declare class ExtensionHost {
148
149
  */
149
150
  static migrateOnly(specifiers: string[], opts: {
150
151
  dbUrl: string;
152
+ handoffRuntimeLogin?: string;
151
153
  extensionIdentity?: ExtensionDbIdentity;
152
154
  resolveFrom?: string;
153
155
  connectTimeoutMs?: number;
@@ -309,6 +311,9 @@ export declare class ExtensionHost {
309
311
  get(token: typeof SERVICE_EVENTS_BACKEND, opts: {
310
312
  strict: false;
311
313
  }): ServiceEventsBackend;
314
+ get(token: typeof ExtensionEffects, opts: {
315
+ strict: false;
316
+ }): ExtensionEffects;
312
317
  get(token: typeof TRIGGER_EVENTS_BACKEND, opts: {
313
318
  strict: false;
314
319
  }): TriggersBackend;