@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.
Files changed (69) hide show
  1. package/bootstrap.json +1 -1
  2. package/dist/automations/events/trigger-events.service.d.ts +13 -1
  3. package/dist/automations/events/trigger-events.service.js +27 -14
  4. package/dist/catalog/marketplaces.service.d.ts +1 -1
  5. package/dist/config/schema.d.ts +8 -0
  6. package/dist/config/schema.js +67 -2
  7. package/dist/ctx/create-ctx.d.ts +4 -0
  8. package/dist/ctx/create-ctx.js +74 -27
  9. package/dist/ctx/durable-cancellation.d.ts +3 -0
  10. package/dist/ctx/durable-cancellation.js +8 -0
  11. package/dist/ctx/durable-effects.service.d.ts +81 -0
  12. package/dist/ctx/durable-effects.service.js +316 -0
  13. package/dist/ctx/durable-envelope.d.ts +24 -0
  14. package/dist/ctx/durable-envelope.js +80 -0
  15. package/dist/ctx/durable-failure.d.ts +7 -0
  16. package/dist/ctx/durable-failure.js +32 -0
  17. package/dist/ctx/durable-job.d.ts +9 -0
  18. package/dist/ctx/durable-job.js +2 -0
  19. package/dist/ctx/durable-keys.d.ts +27 -0
  20. package/dist/ctx/durable-keys.js +138 -0
  21. package/dist/ctx/durable-relay.d.ts +29 -0
  22. package/dist/ctx/durable-relay.js +250 -0
  23. package/dist/ctx/queue.d.ts +2 -0
  24. package/dist/ctx/queue.js +22 -15
  25. package/dist/db/extension-db.d.ts +8 -3
  26. package/dist/db/extension-db.js +109 -7
  27. package/dist/db/extension-handoff-schema.d.ts +6 -0
  28. package/dist/db/extension-handoff-schema.js +72 -0
  29. package/dist/db/extension-role-provision.d.ts +9 -0
  30. package/dist/db/extension-role-provision.js +89 -0
  31. package/dist/db/extension-schema-transfer.d.ts +2 -1
  32. package/dist/db/extension-schema-transfer.js +114 -18
  33. package/dist/db/kernel-schema.d.ts +16 -0
  34. package/dist/db/migrator.d.ts +2 -0
  35. package/dist/db/migrator.js +4 -3
  36. package/dist/erasure/org-catalog.js +2 -2
  37. package/dist/erasure/org-rules.js +1 -0
  38. package/dist/extensions/admin-ops.js +17 -1
  39. package/dist/extensions/extensions.module.js +10 -0
  40. package/dist/extensions/host.d.ts +6 -0
  41. package/dist/extensions/host.js +35 -21
  42. package/dist/extensions/instance.d.ts +2 -0
  43. package/dist/extensions/instance.js +6 -0
  44. package/dist/extensions/migrate-lock.js +1 -0
  45. package/dist/extensions/sources.d.ts +1 -0
  46. package/dist/extensions/sources.js +9 -0
  47. package/dist/inbox/inbox-items.service.d.ts +5 -0
  48. package/dist/inbox/inbox-items.service.js +57 -33
  49. package/dist/index.d.ts +3 -1
  50. package/dist/index.js +3 -1
  51. package/dist/infra/database/extension-effect-key-lock.d.ts +10 -0
  52. package/dist/infra/database/extension-effect-key-lock.js +69 -0
  53. package/dist/infra/database/extension-handoff.d.ts +27 -0
  54. package/dist/infra/database/extension-handoff.js +113 -0
  55. package/dist/infra/database/rls-role.d.ts +4 -11
  56. package/dist/infra/database/rls-role.js +71 -27
  57. package/dist/infra/outbox/outbox.dispatcher.d.ts +6 -1
  58. package/dist/infra/outbox/outbox.dispatcher.js +64 -4
  59. package/dist/infra/outbox/outbox.module.js +2 -0
  60. package/dist/infra/outbox/registry.d.ts +12 -0
  61. package/dist/infra/outbox/registry.js +12 -0
  62. package/dist/kernel.d.ts +2 -0
  63. package/dist/kernel.js +12 -1
  64. package/dist/lifecycle/kernel-lifecycle.js +2 -3
  65. package/dist/orgs/orgs.service.js +16 -0
  66. package/dist/roles/worker.module.js +2 -0
  67. package/package.json +3 -3
  68. package/src/migrations/0225_extension_effect_receipts.sql +25 -0
  69. package/src/migrations/0226_enable_kernel_rls.sql +30 -0
@@ -0,0 +1,89 @@
1
+ import { createHash, createHmac, pbkdf2Sync, randomBytes, timingSafeEqual } from "node:crypto";
2
+ import pg from "pg";
3
+ export const EMPTY_EXTENSION_SCHEMA_COMMENT = "Capybara provisioned empty extension schema";
4
+ export async function createProvisionedExtensionSchema(admin, schema, login) {
5
+ const identifier = pg.escapeIdentifier(schema);
6
+ await admin.query(`create schema ${identifier} authorization ${pg.escapeIdentifier(login)}`);
7
+ await admin.query(`comment on schema ${identifier} is ${pg.escapeLiteral(EMPTY_EXTENSION_SCHEMA_COMMENT)}`);
8
+ }
9
+ const scramIterations = 4096;
10
+ function scramVerifier(password, salt, iterations) {
11
+ const salted = pbkdf2Sync(password, salt, iterations, 32, "sha256");
12
+ const client = createHmac("sha256", salted).update("Client Key").digest();
13
+ const stored = createHash("sha256").update(client).digest("base64");
14
+ const server = createHmac("sha256", salted).update("Server Key").digest("base64");
15
+ return `SCRAM-SHA-256$${iterations}:${salt.toString("base64")}$${stored}:${server}`;
16
+ }
17
+ function matchesCredential(password, stored) {
18
+ const match = stored?.match(/^SCRAM-SHA-256\$(\d+):([A-Za-z0-9+/]+=*)\$/);
19
+ if (!match || !stored)
20
+ return false;
21
+ const iterations = Number(match[1]);
22
+ if (iterations < 1 || iterations > 100_000)
23
+ return false;
24
+ const expected = Buffer.from(scramVerifier(password, Buffer.from(match[2], "base64"), iterations));
25
+ const actual = Buffer.from(stored);
26
+ return actual.length === expected.length && timingSafeEqual(actual, expected);
27
+ }
28
+ /** Runs in the operator transaction under the extension provisioning lock. */
29
+ export async function provisionExtensionRole(admin, name, identity, limits) {
30
+ if (!identity.dedicated)
31
+ throw new Error("Extension provisioning requires a dedicated login");
32
+ const client = new pg.Client({ connectionString: identity.url });
33
+ if (!client.database || !client.password) {
34
+ throw new Error(`Missing PostgreSQL database or credential for extension ${name}`);
35
+ }
36
+ const database = await admin.query("select current_database() as db");
37
+ if (database.rows[0]?.db !== client.database)
38
+ throw new Error(`The provisioner and extension ${name} must use the same PostgreSQL database`);
39
+ const login = pg.escapeIdentifier(identity.login);
40
+ const defaults = {
41
+ statement_timeout: `${limits.extensionStatementTimeoutMs}ms`,
42
+ idle_in_transaction_session_timeout: `${limits.extensionIdleTransactionTimeoutMs}ms`,
43
+ temp_file_limit: `${limits.extensionTempFileLimitKb}kB`,
44
+ search_path: "public",
45
+ };
46
+ const marker = `Capybara extension login for ${client.database}/${name}`;
47
+ const { rows: [existing], } = await admin.query(`select pg_catalog.shobj_description(r.oid, 'pg_authid') as marker,
48
+ exists (select from pg_catalog.pg_stat_activity where usename = r.rolname) as active,
49
+ r.rolcanlogin and not (r.rolsuper or r.rolcreatedb or r.rolcreaterole
50
+ or r.rolreplication or r.rolbypassrls or r.rolinherit)
51
+ and r.rolconnlimit = $2 and coalesce(r.rolvaliduntil, 'infinity') = 'infinity' as restricted,
52
+ r.rolpassword as verifier, settings.setconfig as defaults
53
+ from pg_catalog.pg_authid r
54
+ left join pg_catalog.pg_db_role_setting settings on settings.setrole = r.oid and settings.setdatabase = 0
55
+ where r.rolname = $1`, [identity.login, limits.extensionConnectionLimit]);
56
+ if (existing && existing.marker !== marker) {
57
+ throw new Error(`Refusing to take over unexpected extension login ${identity.login}`);
58
+ }
59
+ const sameCredential = existing && matchesCredential(client.password, existing.verifier);
60
+ if (existing?.restricted &&
61
+ sameCredential &&
62
+ Object.entries(defaults).every(([key, value]) => existing.defaults?.includes(`${key}=${value}`))) {
63
+ return false;
64
+ }
65
+ if (existing?.active) {
66
+ throw new Error(`Drain sessions for extension ${name} before provisioning its database login`);
67
+ }
68
+ if (!existing) {
69
+ await admin.query(`create role ${login} nologin`);
70
+ await admin.query(`comment on role ${login} is ${pg.escapeLiteral(marker)}`);
71
+ }
72
+ if (!sameCredential) {
73
+ try {
74
+ const verifier = scramVerifier(client.password, randomBytes(16), scramIterations);
75
+ await admin.query(`alter role ${login} password ${pg.escapeLiteral(verifier)}`);
76
+ }
77
+ catch {
78
+ throw new Error(`Could not set the PostgreSQL password for extension ${name}`);
79
+ }
80
+ }
81
+ await admin.query(`alter role ${login} login nosuperuser nocreatedb nocreaterole noreplication nobypassrls noinherit
82
+ connection limit ${limits.extensionConnectionLimit} valid until 'infinity'`);
83
+ for (const [key, value] of Object.entries(defaults)) {
84
+ await admin.query(`alter role ${login} set ${key} = ${pg.escapeLiteral(value)}`);
85
+ }
86
+ await admin.query(`grant connect on database ${pg.escapeIdentifier(client.database)} to ${login}`);
87
+ await admin.query(`grant usage on schema public to ${login}`);
88
+ return true;
89
+ }
@@ -1,6 +1,7 @@
1
+ import type { KernelConfig } from "../config/schema.js";
1
2
  import { type ExtensionDbIdentity } from "./extension-db.js";
2
3
  /**
3
4
  * One-shot cutover. The URL authenticates the bootstrap/legacy login, which must be able
4
5
  * to transfer ownership. Run before starting replicas with the new extension identity.
5
6
  */
6
- export declare function transferKnownExtensionSchemas(bootstrapUrl: string, identity: ExtensionDbIdentity, declaredNames: Iterable<string>, connectTimeoutMs?: number): Promise<void>;
7
+ export declare function transferKnownExtensionSchemas(bootstrapUrl: string, identity: ExtensionDbIdentity, declaredNames: Iterable<string>, connectTimeoutMs?: number, provisioning?: KernelConfig["db"]): Promise<void>;
@@ -1,14 +1,20 @@
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";
6
+ import { createProvisionedExtensionSchema, provisionExtensionRole, } from "./extension-role-provision.js";
4
7
  import { assertSameMigrationDatabase, lockMigrationSchema } from "./migrator.js";
5
8
  import { pgConnectOptions } from "./pool.js";
6
- async function transferExtensionSchema(client, schema, target, sources) {
9
+ async function transferExtensionSchema(client, schema, target, sources, dedicated = false) {
7
10
  await lockMigrationSchema(client, schema, "transaction");
8
11
  const { rows: [namespace], } = await client.query(`select oid, pg_catalog.pg_get_userbyid(nspowner) as owner
9
12
  from pg_catalog.pg_namespace where nspname = $1`, [schema]);
10
- if (!namespace)
13
+ if (!namespace) {
14
+ if (dedicated)
15
+ await createProvisionedExtensionSchema(client, schema, target);
11
16
  return;
17
+ }
12
18
  if (namespace.owner !== target && !sources.has(namespace.owner)) {
13
19
  throw new Error(`Unexpected owner ${namespace.owner} for extension schema ${schema}`);
14
20
  }
@@ -42,15 +48,17 @@ async function transferExtensionSchema(client, schema, target, sources) {
42
48
  exists (
43
49
  select from pg_depend d where d.classid = o.classid and d.objid = o.objid
44
50
  and d.objsubid = 0 and d.refclassid = 'pg_extension'::regclass and d.deptype = 'e'
45
- ) as extension_member
51
+ ) as extension_member,
52
+ (c.relname = $2 or (t.typname = $2 and t.typrelid <> 0)) as handoff
46
53
  from objects o
47
54
  cross join lateral pg_identify_object(o.classid, o.objid, 0) object
48
55
  left join pg_class c on o.classid = 'pg_class'::regclass and c.oid = o.objid
49
56
  left join pg_proc p on o.classid = 'pg_proc'::regclass and p.oid = o.objid
50
57
  left join pg_type t on o.classid = 'pg_type'::regclass and t.oid = o.objid
51
58
  order by object.identity
52
- `, [namespace.oid]);
53
- const unexpected = objects.filter((object) => !object.kind ||
59
+ `, [namespace.oid, EXTENSION_EFFECT_HANDOFF]);
60
+ const owned = objects.filter((object) => !object.handoff);
61
+ const unexpected = owned.filter((object) => !object.kind ||
54
62
  object.extension_member ||
55
63
  (object.owner !== target && object.owner !== namespace.owner));
56
64
  if (unexpected.length) {
@@ -62,14 +70,29 @@ async function transferExtensionSchema(client, schema, target, sources) {
62
70
  await client.query(`alter schema ${pg.escapeIdentifier(schema)} owner to ${quotedTarget}`);
63
71
  }
64
72
  // PostgreSQL moves table-owned sequences, row types and indexes with their parent table.
65
- for (const object of objects) {
73
+ for (const object of owned) {
66
74
  if (object.kind && object.owner !== target && !object.attached_sequence) {
67
75
  // Kind is from the fixed catalog mapping. PostgreSQL returns the quoted object identity.
68
76
  await client.query(`alter ${object.kind} ${object.identity} owner to ${quotedTarget}`);
69
77
  }
70
78
  }
71
79
  }
72
- async function confirmTargetDatabase(owner, target, connectTimeoutMs) {
80
+ async function revokeForeignSchemaGrants(client, schema, relayLogin) {
81
+ const { rows } = await client.query(`select distinct case when acl.grantee = 0 then null else pg_get_userbyid(acl.grantee) end as grantee,
82
+ acl.privilege_type as privilege
83
+ from pg_namespace n cross join lateral aclexplode(n.nspacl) acl
84
+ where n.nspname = $1 and acl.grantee <> n.nspowner
85
+ and not (acl.grantee = to_regrole($2) and acl.privilege_type = 'USAGE')
86
+ order by grantee, privilege`, [schema, relayLogin]);
87
+ const revoked = [];
88
+ for (const { grantee, privilege } of rows) {
89
+ const recipient = grantee === null ? "PUBLIC" : pg.escapeIdentifier(grantee);
90
+ await client.query(`revoke ${privilege} on schema ${pg.escapeIdentifier(schema)} from ${recipient} cascade`);
91
+ revoked.push(`Revoked foreign ${privilege} on schema ${pg.escapeIdentifier(schema)} from ${recipient}`);
92
+ }
93
+ return revoked;
94
+ }
95
+ async function confirmTargetDatabase(owner, target, schema, connectTimeoutMs) {
73
96
  const client = new pg.Client({
74
97
  connectionString: target.url,
75
98
  ...pgConnectOptions({ connectTimeoutMs }),
@@ -77,7 +100,7 @@ async function confirmTargetDatabase(owner, target, connectTimeoutMs) {
77
100
  client.on("error", () => { });
78
101
  try {
79
102
  await client.connect();
80
- await assertExtensionSession(client, target.login);
103
+ await assertExtensionSession(client, target.login, target.dedicated ? schema : undefined);
81
104
  await assertSameMigrationDatabase(owner, client);
82
105
  }
83
106
  catch (cause) {
@@ -91,7 +114,7 @@ async function confirmTargetDatabase(owner, target, connectTimeoutMs) {
91
114
  * One-shot cutover. The URL authenticates the bootstrap/legacy login, which must be able
92
115
  * to transfer ownership. Run before starting replicas with the new extension identity.
93
116
  */
94
- export async function transferKnownExtensionSchemas(bootstrapUrl, identity, declaredNames, connectTimeoutMs) {
117
+ export async function transferKnownExtensionSchemas(bootstrapUrl, identity, declaredNames, connectTimeoutMs, provisioning) {
95
118
  const owner = new pg.Client({
96
119
  connectionString: bootstrapUrl,
97
120
  ...pgConnectOptions({ connectTimeoutMs }),
@@ -99,36 +122,109 @@ export async function transferKnownExtensionSchemas(bootstrapUrl, identity, decl
99
122
  owner.on("error", () => { });
100
123
  try {
101
124
  await owner.connect();
125
+ if (provisioning) {
126
+ const { rows: [role], } = await owner.query("select rolsuper from pg_catalog.pg_roles where rolname = current_user");
127
+ if (!role?.rolsuper)
128
+ throw new Error("db.extensionProvisioningUrl must authenticate as a PostgreSQL superuser");
129
+ await lockMigrationSchema(owner, "extension-provisioning", "session");
130
+ }
102
131
  await owner.query("begin");
103
132
  try {
104
133
  await owner.query("set local search_path = pg_catalog");
105
134
  await owner.query("set local lock_timeout = '30s'");
106
- const { rows: [legacy], } = await owner.query("select current_user as login");
135
+ const { rows: [legacy], } = await owner.query(`
136
+ select current_user as login, pg_get_userbyid(nspowner) as kernel_owner
137
+ from pg_catalog.pg_namespace where nspname = 'capybara'
138
+ `);
107
139
  if (!legacy)
108
140
  throw new Error("Could not verify the schema transfer login");
109
141
  const { rows: registered } = await owner.query(`select name from capybara.extension_name_owners
110
142
  union select name from capybara.extension_installs`);
111
- const names = new Set([...declaredNames, ...registered.map((row) => row.name)]);
143
+ const names = new Set([
144
+ ...declaredNames,
145
+ ...registered.map((row) => row.name),
146
+ ...(provisioning ? (identity.provisionedNames?.() ?? []) : []),
147
+ ]);
112
148
  const resolved = [...names].sort().map((name) => {
113
149
  if (!EXTENSION_NAME_RE.test(name))
114
150
  throw new Error(`Invalid extension name: ${name}`);
115
- return { schema: pluginSchemaName(name), target: identity.resolve(name) };
151
+ return { name, schema: pluginSchemaName(name), target: identity.resolve(name) };
116
152
  });
117
- const sources = new Set([legacy.login, ...resolved.map(({ target }) => target.login)]);
153
+ const legacySources = new Set([legacy.login, legacy.kernel_owner]);
118
154
  if (identity.sharedLogin !== undefined)
119
- sources.add(identity.sharedLogin);
155
+ legacySources.add(identity.sharedLogin);
156
+ const sources = new Set([...legacySources, ...resolved.map(({ target }) => target.login)]);
120
157
  const targets = resolved.filter(({ target }) => target.separate);
158
+ const unchanged = new Set();
159
+ const revoked = [];
160
+ if (provisioning) {
161
+ const { rows: owned } = await owner.query(`select nspname as schema, pg_get_userbyid(nspowner) as login
162
+ from pg_namespace where nspname = any($1::text[])`, [targets.map(({ schema }) => schema)]);
163
+ const owners = new Map(owned.map(({ schema, login }) => [schema, login]));
164
+ if (identity.sharedLogin && owned.some(({ login }) => login === identity.sharedLogin)) {
165
+ const stale = await owner.query(`select 1 from pg_catalog.pg_stat_activity where usename = $1 and datname = current_database()`, [identity.sharedLogin]);
166
+ if (stale.rows.length) {
167
+ throw new Error("Drain shared extension database sessions before transferring ownership");
168
+ }
169
+ }
170
+ const runtime = new pg.Client({ connectionString: provisioning.url });
171
+ runtime.on("error", () => { });
172
+ try {
173
+ await runtime.connect();
174
+ await assertSameMigrationDatabase(owner, runtime);
175
+ }
176
+ finally {
177
+ await runtime.end();
178
+ }
179
+ const { rows: [database], } = await owner.query("select current_database() as name");
180
+ if (!database)
181
+ throw new Error("Could not verify the extension provisioning database");
182
+ await owner.query(`revoke create, temporary on database ${pg.escapeIdentifier(database.name)} from public`);
183
+ for (const { name, schema, target } of targets) {
184
+ const changed = await provisionExtensionRole(owner, name, target, provisioning);
185
+ if (!changed && owners.get(schema) === target.login)
186
+ unchanged.add(schema);
187
+ }
188
+ await owner.query("commit");
189
+ await owner.query("begin");
190
+ await owner.query("set local search_path = pg_catalog");
191
+ await owner.query("set local lock_timeout = '30s'");
192
+ }
121
193
  const validated = new Set();
122
- for (const { target } of targets) {
123
- if (validated.has(target.url))
194
+ for (const { target, schema } of targets) {
195
+ if (unchanged.has(schema) || validated.has(target.url))
124
196
  continue;
125
- await confirmTargetDatabase(owner, target, connectTimeoutMs);
197
+ await confirmTargetDatabase(owner, target, schema, connectTimeoutMs);
126
198
  validated.add(target.url);
127
199
  }
128
200
  for (const { schema, target } of targets) {
129
- await transferExtensionSchema(owner, schema, target.login, sources);
201
+ await transferExtensionSchema(owner, schema, target.login, target.dedicated ? legacySources : sources, target.dedicated);
202
+ if (provisioning && target.dedicated) {
203
+ const relayLogin = provisioning.extensionEffectRelayLogin ?? "capybara_runtime";
204
+ await provisionExtensionHandoff(owner, schema, target.login, relayLogin);
205
+ revoked.push(...(await revokeForeignSchemaGrants(owner, schema, relayLogin)));
206
+ }
207
+ if (target.dedicated && identity.sharedLogin) {
208
+ const namespace = pg.escapeIdentifier(schema);
209
+ const old = pg.escapeIdentifier(identity.sharedLogin);
210
+ const { rows } = await owner.query("select 1 from pg_catalog.pg_roles where rolname = $1", [identity.sharedLogin]);
211
+ if (rows.length) {
212
+ await owner.query(`revoke all on schema ${namespace} from ${old}`);
213
+ await owner.query(`revoke all on all tables in schema ${namespace} from ${old}`);
214
+ await owner.query(`revoke all on all sequences in schema ${namespace} from ${old}`);
215
+ await owner.query(`revoke all on all routines in schema ${namespace} from ${old}`);
216
+ }
217
+ }
218
+ }
219
+ if (provisioning && identity.sharedLogin) {
220
+ const { rows: [old], } = await owner.query(`select current_database() as db from pg_catalog.pg_roles where rolname = $1`, [identity.sharedLogin]);
221
+ if (old) {
222
+ await owner.query(`revoke create on database ${pg.escapeIdentifier(old.db)} from ${pg.escapeIdentifier(identity.sharedLogin)}`);
223
+ }
130
224
  }
131
225
  await owner.query("commit");
226
+ for (const message of revoked)
227
+ process.stderr.write(`${JSON.stringify(message)}\n`);
132
228
  }
133
229
  catch (error) {
134
230
  await owner.query("rollback").catch(() => { });
@@ -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;
@@ -31,6 +31,8 @@ export declare function migrate(connectionString: string, owner: MigrationOwner,
31
31
  signal?: AbortSignal | undefined;
32
32
  /** Verify the effective PostgreSQL role before running an isolated extension migration. */
33
33
  extensionLogin?: string | undefined;
34
+ /** Dedicated logins own a pre-provisioned schema and cannot create schemas. */
35
+ extensionDedicated?: boolean | undefined;
34
36
  /** 迁移会话的 `statement_timeout`(毫秒);不给不设。 */
35
37
  statementTimeoutMs?: number | undefined;
36
38
  /** 迁移会话的 `lock_timeout`(毫秒,含按 schema 的咨询锁);不给不设。 */
@@ -140,7 +140,7 @@ export async function migrate(connectionString, owner, opts = {}) {
140
140
  try {
141
141
  await client.connect();
142
142
  if (opts.extensionLogin !== undefined)
143
- await assertExtensionSession(client, opts.extensionLogin);
143
+ await assertExtensionSession(client, opts.extensionLogin, opts.extensionDedicated ? schema : undefined);
144
144
  if (opts.statementTimeoutMs !== undefined) {
145
145
  await client.query(`set statement_timeout = ${Math.max(1, Math.floor(opts.statementTimeoutMs))}`);
146
146
  }
@@ -149,7 +149,7 @@ export async function migrate(connectionString, owner, opts = {}) {
149
149
  }
150
150
  await lockMigrationSchema(client, schema, "session");
151
151
  if (opts.extensionLogin !== undefined) {
152
- await assertExtensionSchemaOwner(client, schema, opts.extensionLogin);
152
+ await assertExtensionSchemaOwner(client, schema, opts.extensionLogin, opts.extensionDedicated);
153
153
  }
154
154
  if (schema === "capybara") {
155
155
  const { rows: [privileges], } = await client.query(kernelMigrationPrivileges);
@@ -157,7 +157,8 @@ export async function migrate(connectionString, owner, opts = {}) {
157
157
  throw new Error(`The migration login must own the capybara schema. ${migrateHint}`);
158
158
  }
159
159
  }
160
- await client.query(`create schema if not exists ${ident(schema)}`);
160
+ if (!opts.extensionDedicated)
161
+ await client.query(`create schema if not exists ${ident(schema)}`);
161
162
  await client.query(`create table if not exists ${table} (
162
163
  name text primary key,
163
164
  checksum text not null,
@@ -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"),
@@ -15,6 +15,7 @@ import { itemRemovedError } from "../catalog/ownership.js";
15
15
  import { oweDeployedExtensionSync } from "../catalog/scope-jobs.js";
16
16
  import { pluginSchemaName } from "../ctx/create-ctx.js";
17
17
  import { ConfiguredExtensionDbIdentity } from "../db/extension-db.js";
18
+ import { EMPTY_EXTENSION_SCHEMA_COMMENT } from "../db/extension-role-provision.js";
18
19
  import { oweHostServicesStop } from "../device-access/host-service-stop.js";
19
20
  import { revokeSiteGrantsOfExtensionEverywhere } from "../device-access/site-grants.js";
20
21
  import { ApiError } from "../errors.js";
@@ -22,6 +23,7 @@ import { audit } from "../identity/audit.js";
22
23
  import { SuperAdminLock } from "../identity/super-admin.js";
23
24
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
24
25
  import { afterCommit } from "../infra/database/after-commit.js";
26
+ import { EXTENSION_EFFECT_HANDOFF } from "../infra/database/extension-handoff.js";
25
27
  import { KernelDb } from "../infra/database/kernel-db.js";
26
28
  import { asPlatform } from "../infra/database/org-scope.js";
27
29
  import { TransactionHost } from "../infra/database/transaction-host.js";
@@ -579,7 +581,21 @@ function fallbackView(name, known, err) {
579
581
  /** 插件名已留下的数据:权限快照、部署配置、任一组织的配置,或插件 schema(`plugin_<name>`)。 */
580
582
  async function hasRetainedData(db, name) {
581
583
  return asPlatform("whether any org kept config for a plugin", async () => {
582
- const schema = await sql `SELECT 1 AS x FROM pg_namespace WHERE nspname = ${pluginSchemaName(name)}`.execute(db);
584
+ const schema = await sql `SELECT 1 AS x FROM pg_catalog.pg_namespace n
585
+ WHERE n.nspname = ${pluginSchemaName(name)} AND (
586
+ pg_catalog.obj_description(n.oid, 'pg_namespace') IS DISTINCT FROM ${EMPTY_EXTENSION_SCHEMA_COMMENT}
587
+ OR EXISTS (
588
+ SELECT FROM pg_catalog.pg_depend d
589
+ WHERE d.refclassid = 'pg_catalog.pg_namespace'::regclass AND d.refobjid = n.oid
590
+ AND d.deptype = 'n'
591
+ AND NOT EXISTS (
592
+ SELECT FROM pg_catalog.pg_class c
593
+ WHERE d.classid = 'pg_catalog.pg_class'::regclass AND c.oid = d.objid
594
+ AND c.relname = ${EXTENSION_EFFECT_HANDOFF} AND c.relkind = 'r'
595
+ AND c.relowner <> n.nspowner
596
+ )
597
+ )
598
+ )`.execute(db);
583
599
  if (schema.rows.length > 0)
584
600
  return true;
585
601
  // org-filter: whether any org kept config for the plugin name (a deployment-wide existence check)
@@ -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,
@@ -3,8 +3,10 @@ import type { Redis } from "ioredis";
3
3
  import type { core } from "zod";
4
4
  import type { KernelAppOptions } from "../app.js";
5
5
  import { TRIGGER_EVENTS_BACKEND } from "../automations/events/token.js";
6
+ import type { KernelConfig } from "../config/schema.js";
6
7
  import type { BusSubscriber } from "../ctx/bus.js";
7
8
  import { type DeviceAccessBackend, type InboxBackend, type PluginReadsBackend, type Route, type TriggersBackend } from "../ctx/create-ctx.js";
9
+ import { ExtensionEffects } from "../ctx/durable-effects.service.js";
8
10
  import { type ExtensionNetSeams } from "../ctx/net.js";
9
11
  import type { Keyring } from "../ctx/secrets.js";
10
12
  import { type ExtensionDbIdentity } from "../db/extension-db.js";
@@ -149,6 +151,7 @@ export declare class ExtensionHost {
149
151
  static migrateOnly(specifiers: string[], opts: {
150
152
  dbUrl: string;
151
153
  extensionIdentity?: ExtensionDbIdentity;
154
+ extensionProvisioning?: KernelConfig["db"];
152
155
  resolveFrom?: string;
153
156
  connectTimeoutMs?: number;
154
157
  autoApprove?: boolean;
@@ -309,6 +312,9 @@ export declare class ExtensionHost {
309
312
  get(token: typeof SERVICE_EVENTS_BACKEND, opts: {
310
313
  strict: false;
311
314
  }): ServiceEventsBackend;
315
+ get(token: typeof ExtensionEffects, opts: {
316
+ strict: false;
317
+ }): ExtensionEffects;
312
318
  get(token: typeof TRIGGER_EVENTS_BACKEND, opts: {
313
319
  strict: false;
314
320
  }): TriggersBackend;
@@ -17,8 +17,10 @@ import { ModuleRef } from "@nestjs/core";
17
17
  import { TRIGGER_EVENTS_BACKEND } from "../automations/events/token.js";
18
18
  import { changedPaths, configFields, getPath, secretValues, unreachableSecrets, } from "../config/fields.js";
19
19
  import { pluginSchemaName, queryEnabledPlugins, } from "../ctx/create-ctx.js";
20
+ import { ExtensionEffects } from "../ctx/durable-effects.service.js";
20
21
  import { EXTENSION_NET_SEAMS } from "../ctx/net.js";
21
22
  import { ConfiguredExtensionDbIdentity, extensionDbIdentity, extensionDbPool, } from "../db/extension-db.js";
23
+ import { ensureLocalExtensionHandoff } from "../db/extension-handoff-schema.js";
22
24
  import { transferKnownExtensionSchemas } from "../db/extension-schema-transfer.js";
23
25
  import { kernelDb } from "../db/kernel-schema.js";
24
26
  import { migrate } from "../db/migrator.js";
@@ -192,6 +194,7 @@ async function migratePlugin(connection, manifest, migrationsDir, connectTimeout
192
194
  connectTimeoutMs,
193
195
  signal,
194
196
  extensionLogin: connection.separate ? connection.login : undefined,
197
+ extensionDedicated: connection.dedicated,
195
198
  });
196
199
  return { schema, applied };
197
200
  }
@@ -262,8 +265,8 @@ let ExtensionHost = class ExtensionHost {
262
265
  for (const manifest of ordered)
263
266
  assertSecretsReachable(manifest);
264
267
  const identity = opts.extensionIdentity ?? extensionDbIdentity({ url: opts.dbUrl });
265
- if (opts.extensionIdentity) {
266
- await transferKnownExtensionSchemas(opts.dbUrl, identity, dirs.keys(), opts.connectTimeoutMs);
268
+ if (opts.extensionProvisioning?.extensionProvisioningUrl) {
269
+ await transferKnownExtensionSchemas(opts.extensionProvisioning.extensionProvisioningUrl, identity, dirs.keys(), opts.connectTimeoutMs, opts.extensionProvisioning);
267
270
  }
268
271
  let toMigrate = ordered;
269
272
  if (!opts.autoApprove && ordered.length > 0) {
@@ -507,6 +510,14 @@ let ExtensionHost = class ExtensionHost {
507
510
  return undefined;
508
511
  }
509
512
  },
513
+ durableEffects: () => {
514
+ try {
515
+ return modules?.get(ExtensionEffects, { strict: false });
516
+ }
517
+ catch {
518
+ return undefined;
519
+ }
520
+ },
510
521
  triggers: () => {
511
522
  try {
512
523
  return modules?.get(TRIGGER_EVENTS_BACKEND, { strict: false });
@@ -1806,26 +1817,29 @@ let ExtensionHost = class ExtensionHost {
1806
1817
  let ctx;
1807
1818
  const name = spec.manifest.name;
1808
1819
  const identity = this.dbIdentity.resolve(name);
1809
- const extensionDb = identity.separate
1810
- ? extensionDbPool(identity, name, this.config.get().db, (err) => this.log.warn("extension database pool error", { plugin: name, err }))
1811
- : undefined;
1812
- const p = setupInstance(this.loadDeps, spec.manifest, {
1813
- entryUrl: spec.entryUrl,
1814
- source: spec.source,
1815
- sha256: spec.sha256,
1816
- config: spec.config,
1817
- configHash: spec.configHash,
1818
- permissions: spec.permissions,
1819
- ...(extensionDb && { extensionDb }),
1820
- onCtx: (c) => {
1821
- if (c)
1822
- ctx = c;
1823
- if (c || this.settingUp === ctx)
1824
- this.settingUp = c;
1825
- },
1826
- }).catch(async (error) => {
1820
+ const extensionDb = extensionDbPool(identity, name, this.config.get().db, (err) => this.log.warn("extension database pool error", { plugin: name, err }));
1821
+ const p = (async () => {
1822
+ if (!identity.separate) {
1823
+ await ensureLocalExtensionHandoff(this.deps.db, this.deps.dbUrl, pluginSchemaName(name), this.deps.connectTimeoutMs);
1824
+ }
1825
+ return setupInstance(this.loadDeps, spec.manifest, {
1826
+ entryUrl: spec.entryUrl,
1827
+ source: spec.source,
1828
+ sha256: spec.sha256,
1829
+ config: spec.config,
1830
+ configHash: spec.configHash,
1831
+ permissions: spec.permissions,
1832
+ extensionDb,
1833
+ onCtx: (c) => {
1834
+ if (c)
1835
+ ctx = c;
1836
+ if (c || this.settingUp === ctx)
1837
+ this.settingUp = c;
1838
+ },
1839
+ });
1840
+ })().catch(async (error) => {
1827
1841
  if (!ctx)
1828
- await extensionDb?.destroy();
1842
+ await extensionDb.destroy();
1829
1843
  throw error;
1830
1844
  });
1831
1845
  if (timeoutMs === undefined)
@@ -65,6 +65,8 @@ export declare class ExtensionInstance {
65
65
  /** {@link hurry}:进行中的 dispose 不再等排空时限。 */
66
66
  private readonly hurried;
67
67
  constructor(init: ExtensionInstanceInit);
68
+ hasEffectQueue(name: string): boolean;
69
+ enqueueEffect(queue: string, data: unknown, jobId: string, delayMs?: number): Promise<void>;
68
70
  /** 此刻的部署配置(hot 改动后是新值)。 */
69
71
  get config(): unknown;
70
72
  /** 部署配置摘要(见 `deploymentConfigHash`;hot 改动后随之更新)。 */
@@ -95,6 +95,12 @@ export class ExtensionInstance {
95
95
  this.log = init.log;
96
96
  this.inflight = new InflightTracker(this.name);
97
97
  }
98
+ hasEffectQueue(name) {
99
+ return this.ctx.hasEffectQueue(name);
100
+ }
101
+ async enqueueEffect(queue, data, jobId, delayMs) {
102
+ await this.ctx.dispatchEffectQueue(queue, data, jobId, delayMs);
103
+ }
98
104
  /** 此刻的部署配置(hot 改动后是新值)。 */
99
105
  get config() {
100
106
  return this.live.value;
@@ -47,6 +47,7 @@ export async function ensureMigrated(d, name, sha256, dir) {
47
47
  connectTimeoutMs: d.connectTimeoutMs,
48
48
  signal: signals.length > 0 ? AbortSignal.any(signals) : undefined,
49
49
  extensionLogin: d.extensionDb?.separate ? d.extensionDb.login : undefined,
50
+ extensionDedicated: d.extensionDb?.dedicated,
50
51
  ...(d.timeoutMs !== undefined && {
51
52
  statementTimeoutMs: d.timeoutMs,
52
53
  lockTimeoutMs: Math.min(d.timeoutMs, MIGRATION_LOCK_TIMEOUT_MS),