@capybara-hq/kernel 0.1.0-rc.131 → 0.1.0-rc.132

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 (41) hide show
  1. package/dist/catalog/plugin-import.d.ts +3 -1
  2. package/dist/catalog/plugin-import.js +19 -15
  3. package/dist/config/schema.d.ts +1 -0
  4. package/dist/config/schema.js +8 -0
  5. package/dist/ctx/create-ctx.d.ts +3 -2
  6. package/dist/ctx/create-ctx.js +10 -7
  7. package/dist/db/extension-db.d.ts +30 -0
  8. package/dist/db/extension-db.js +91 -0
  9. package/dist/db/extension-schema-transfer.d.ts +6 -0
  10. package/dist/db/extension-schema-transfer.js +141 -0
  11. package/dist/db/kernel-schema.d.ts +2 -4
  12. package/dist/db/migrator.d.ts +6 -0
  13. package/dist/db/migrator.js +39 -4
  14. package/dist/db/pool.d.ts +4 -0
  15. package/dist/db/pool.js +36 -1
  16. package/dist/erasure/org-catalog.js +2 -2
  17. package/dist/extensions/admin-ops.d.ts +3 -1
  18. package/dist/extensions/admin-ops.js +11 -7
  19. package/dist/extensions/extensions.module.js +3 -0
  20. package/dist/extensions/host.d.ts +4 -1
  21. package/dist/extensions/host.js +29 -6
  22. package/dist/extensions/instance.d.ts +3 -0
  23. package/dist/extensions/instance.js +3 -1
  24. package/dist/extensions/migrate-lock.d.ts +4 -1
  25. package/dist/extensions/migrate-lock.js +19 -2
  26. package/dist/infra/outbox/registry.d.ts +0 -14
  27. package/dist/infra/outbox/registry.js +0 -15
  28. package/dist/kernel.js +4 -0
  29. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  30. package/dist/lifecycle/kernel-lifecycle.js +26 -21
  31. package/dist/roles/worker.module.js +0 -6
  32. package/dist/runtime/maintenance.d.ts +1 -3
  33. package/dist/runtime/maintenance.js +3 -14
  34. package/package.json +1 -1
  35. package/src/migrations/0219_event_org_constraint_check.sql +29 -0
  36. package/src/migrations/0220_require_event_org.sql +18 -0
  37. package/src/migrations/0221_drop_connector_declaration_policy.sql +2 -0
  38. package/dist/conversations/event-org-backfill.d.ts +0 -111
  39. package/dist/conversations/event-org-backfill.js +0 -264
  40. package/dist/conversations/event-org-backfill.module.d.ts +0 -3
  41. package/dist/conversations/event-org-backfill.module.js +0 -18
package/dist/db/pool.js CHANGED
@@ -27,12 +27,47 @@ export function createDb(url, poolMax, onError = (err) => console.error("[db] id
27
27
  ...(opts.idleTimeoutMs !== undefined && { idleTimeoutMillis: opts.idleTimeoutMs }),
28
28
  // a client kept idle longer must notice a dead peer (a dropped VPN, a NAT timeout) by itself
29
29
  keepAlive: true,
30
+ ...(opts.onConnect && { onConnect: opts.onConnect }),
30
31
  });
31
32
  pool.on("error", onError);
32
33
  pool.on("connect", (client) => client.on("error", opts.onClientError ?? onError));
33
34
  const rls = opts.rls ?? "off";
34
35
  return new Kysely({
35
- dialect: new ScopedPostgresDialect({ pool }, rls),
36
+ dialect: new ScopedPostgresDialect({
37
+ pool: opts.closeActiveOnDestroy ? disposablePool(pool) : pool,
38
+ }, rls),
36
39
  plugins: rls !== "off" && unscopedQueryCheck() ? [captureUnscopedQueryOrigins] : [],
37
40
  });
38
41
  }
42
+ // pg.Pool.end waits for every checkout. After the host's drain, release remaining clients with
43
+ // an error so PostgreSQL closes their sessions. Late transaction cleanup can release safely.
44
+ function disposablePool(pool) {
45
+ const active = new Set();
46
+ let closing;
47
+ return {
48
+ Client: pg.Client,
49
+ options: pool.options,
50
+ async connect() {
51
+ const client = await pool.connect();
52
+ if (closing) {
53
+ client.release(true);
54
+ throw new Error("Extension database pool is closing");
55
+ }
56
+ const release = client.release.bind(client);
57
+ client.release = (error) => {
58
+ if (active.delete(client))
59
+ release(error);
60
+ };
61
+ active.add(client);
62
+ return client;
63
+ },
64
+ end() {
65
+ if (!closing) {
66
+ closing = pool.end();
67
+ for (const client of active)
68
+ client.release(true);
69
+ }
70
+ return closing;
71
+ },
72
+ };
73
+ }
@@ -1,5 +1,5 @@
1
1
  import { sql } from "kysely";
2
- // PostgreSQL 17 after 0218. Re-review the ownership map before updating this fingerprint.
2
+ // PostgreSQL 17 after 0221. 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 === "9823a80414192184ec8c3993da6372fe" ? undefined : "schema-drift";
33
+ return rows[0]?.fingerprint === "adf4514170b69e9a455891eacd3b9d03" ? undefined : "schema-drift";
34
34
  }
@@ -1,3 +1,4 @@
1
+ import { type ExtensionDbIdentity } from "../db/extension-db.js";
1
2
  import { ApiError } from "../errors.js";
2
3
  import { SuperAdminLock } from "../identity/super-admin.js";
3
4
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
@@ -64,6 +65,7 @@ export declare class ExtensionAdminOps {
64
65
  /** Reads packages (a downgrade checks the target version's migration files). */
65
66
  private readonly blobs;
66
67
  private readonly config;
68
+ private readonly extensionDbIdentity;
67
69
  /** Publishes `kernel.plugins.changed`. */
68
70
  private readonly bus;
69
71
  /**
@@ -91,7 +93,7 @@ export declare class ExtensionAdminOps {
91
93
  /** The config-declared extension names (they cannot be installed / disabled / uninstalled, C15). */
92
94
  registry: ExtensionRegistry,
93
95
  /** Reads packages (a downgrade checks the target version's migration files). */
94
- blobs: ExtensionBlobs, config: KernelConfigService,
96
+ blobs: ExtensionBlobs, config: KernelConfigService, extensionDbIdentity: ExtensionDbIdentity,
95
97
  /** Publishes `kernel.plugins.changed`. */
96
98
  bus: PublishBus,
97
99
  /**
@@ -14,6 +14,7 @@ import semver from "semver";
14
14
  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
+ import { ConfiguredExtensionDbIdentity } from "../db/extension-db.js";
17
18
  import { revokeSiteGrantsOfExtensionEverywhere } from "../device-access/site-grants.js";
18
19
  import { ApiError } from "../errors.js";
19
20
  import { audit } from "../identity/audit.js";
@@ -45,6 +46,7 @@ let ExtensionAdminOps = class ExtensionAdminOps {
45
46
  registry;
46
47
  blobs;
47
48
  config;
49
+ extensionDbIdentity;
48
50
  bus;
49
51
  lifecycle;
50
52
  log;
@@ -65,7 +67,7 @@ let ExtensionAdminOps = class ExtensionAdminOps {
65
67
  /** The config-declared extension names (they cannot be installed / disabled / uninstalled, C15). */
66
68
  registry,
67
69
  /** Reads packages (a downgrade checks the target version's migration files). */
68
- blobs, config,
70
+ blobs, config, extensionDbIdentity,
69
71
  /** Publishes `kernel.plugins.changed`. */
70
72
  bus,
71
73
  /**
@@ -86,6 +88,7 @@ let ExtensionAdminOps = class ExtensionAdminOps {
86
88
  this.registry = registry;
87
89
  this.blobs = blobs;
88
90
  this.config = config;
91
+ this.extensionDbIdentity = extensionDbIdentity;
89
92
  this.bus = bus;
90
93
  this.lifecycle = lifecycle;
91
94
  this.log = log;
@@ -237,7 +240,7 @@ let ExtensionAdminOps = class ExtensionAdminOps {
237
240
  return { changed: false, state: row.desired_state };
238
241
  }
239
242
  if (row && isDowngrade(pkg.version, row.version)) {
240
- const unrun = await unrunMigrations(db, name, target.migrationSql);
243
+ const unrun = await unrunMigrations(db, name, target.migrationSql, this.extensionDbIdentity.resolve(name), this.config.get().db.connectTimeoutMs);
241
244
  if (unrun.length > 0) {
242
245
  throw new ApiError("extension.downgrade_unsupported", `Extension ${name} ${pkg.version} has migrations that were never run here (${unrun.join(", ")}); extension migrations only expand, so downgrade only to a version whose migrations have all been applied`, unrun.map((file) => ({ file })));
243
246
  }
@@ -521,11 +524,12 @@ ExtensionAdminOps = __decorate([
521
524
  __param(6, Inject(ExtensionRegistry)),
522
525
  __param(7, Inject(ExtensionBlobs)),
523
526
  __param(8, Inject(KernelConfigService)),
524
- __param(9, Inject(KERNEL_BUS)),
525
- __param(10, Inject(ExtensionLifecycle)),
526
- __param(11, Inject(KERNEL_LOGGER)),
527
- __param(12, Inject(SingleProviderGuard)),
528
- __param(13, Inject(OutboxService))
527
+ __param(9, Inject(ConfiguredExtensionDbIdentity)),
528
+ __param(10, Inject(KERNEL_BUS)),
529
+ __param(11, Inject(ExtensionLifecycle)),
530
+ __param(12, Inject(KERNEL_LOGGER)),
531
+ __param(13, Inject(SingleProviderGuard)),
532
+ __param(14, Inject(OutboxService))
529
533
  ], ExtensionAdminOps);
530
534
  export { ExtensionAdminOps };
531
535
  /**
@@ -5,6 +5,7 @@ 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 { ConfiguredExtensionDbIdentity } from "../db/extension-db.js";
8
9
  import { DialInRelayModule } from "../dial-in/relay.module.js";
9
10
  import { SuperAdminLockModule } from "../identity/super-admin.js";
10
11
  import { ModelsModule } from "../models/models.module.js";
@@ -71,6 +72,7 @@ ExtensionsModule = __decorate([
71
72
  SingleProviderLock,
72
73
  SingleProviderGuard,
73
74
  ReplicaStatusStore,
75
+ ConfiguredExtensionDbIdentity,
74
76
  ExtensionHost,
75
77
  ExtensionLifecycle,
76
78
  ExtensionAdmin,
@@ -91,6 +93,7 @@ ExtensionsModule = __decorate([
91
93
  PluginInstallLock,
92
94
  PluginApproveLock,
93
95
  ReplicaStatusStore,
96
+ ConfiguredExtensionDbIdentity,
94
97
  ExtensionHost,
95
98
  ExtensionLifecycle,
96
99
  ExtensionAdmin,
@@ -7,6 +7,7 @@ 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
8
  import { type ExtensionNetSeams } from "../ctx/net.js";
9
9
  import type { Keyring } from "../ctx/secrets.js";
10
+ import { type ExtensionDbIdentity } from "../db/extension-db.js";
10
11
  import { DEVICE_ACCESS_BACKEND } from "../device-access/token.js";
11
12
  import { DialInAccess } from "../dial-in/access.js";
12
13
  import type { PluginRouteTable } from "../http/plugin-dispatch.js";
@@ -133,6 +134,7 @@ export declare class ExtensionHost {
133
134
  * org's point resolution (layering spec A §6).
134
135
  */
135
136
  private readonly effective;
137
+ private readonly dbIdentity;
136
138
  /**
137
139
  * Only resolves extensions and runs migrations in dependency order: no deployment config check, no
138
140
  * setup, no Redis (for `capybara migrate`). Like `load()` it checks secret markers first
@@ -145,6 +147,7 @@ export declare class ExtensionHost {
145
147
  */
146
148
  static migrateOnly(specifiers: string[], opts: {
147
149
  dbUrl: string;
150
+ extensionIdentity?: ExtensionDbIdentity;
148
151
  resolveFrom?: string;
149
152
  connectTimeoutMs?: number;
150
153
  autoApprove?: boolean;
@@ -312,7 +315,7 @@ export declare class ExtensionHost {
312
315
  }): PluginReadsBackend;
313
316
  },
314
317
  /** Tests only: `ctx.net`'s DNS and dispatcher seams (`EXTENSION_NET_SEAMS`). */
315
- netSeams?: ExtensionNetSeams);
318
+ netSeams?: ExtensionNetSeams, dbIdentity?: ExtensionDbIdentity);
316
319
  /** The startup config's `extensionConfig` (file / Nacos merged with env). */
317
320
  private get extensionConfig();
318
321
  /** `extensionPermissions.autoApprove` (development and trials only; see `planApprovals`). */
@@ -18,6 +18,8 @@ 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
20
  import { EXTENSION_NET_SEAMS } from "../ctx/net.js";
21
+ import { ConfiguredExtensionDbIdentity, extensionDbIdentity, extensionDbPool, } from "../db/extension-db.js";
22
+ import { transferKnownExtensionSchemas } from "../db/extension-schema-transfer.js";
21
23
  import { kernelDb } from "../db/kernel-schema.js";
22
24
  import { migrate } from "../db/migrator.js";
23
25
  import { createDb } from "../db/pool.js";
@@ -181,12 +183,16 @@ function warnPending(log, p) {
181
183
  * 无迁移时返回 undefined。迁移器在会话上持有按 schema 的咨询锁:多副本同时启动时只有一个在执行,其余等它结束后
182
184
  * 发现都已应用。
183
185
  */
184
- async function migratePlugin(dbUrl, manifest, migrationsDir, connectTimeoutMs, signal) {
186
+ async function migratePlugin(connection, manifest, migrationsDir, connectTimeoutMs, signal) {
185
187
  if (!migrationsDir)
186
188
  return undefined;
187
189
  const schema = pluginSchemaName(manifest.name);
188
190
  try {
189
- const { applied } = await migrate(dbUrl, { schema, dir: migrationsDir }, { connectTimeoutMs, signal });
191
+ const { applied } = await migrate(connection.url, { schema, dir: migrationsDir }, {
192
+ connectTimeoutMs,
193
+ signal,
194
+ extensionLogin: connection.separate ? connection.login : undefined,
195
+ });
190
196
  return { schema, applied };
191
197
  }
192
198
  catch (e) {
@@ -237,6 +243,7 @@ let ExtensionHost = class ExtensionHost {
237
243
  config;
238
244
  log;
239
245
  effective;
246
+ dbIdentity;
240
247
  /**
241
248
  * Only resolves extensions and runs migrations in dependency order: no deployment config check, no
242
249
  * setup, no Redis (for `capybara migrate`). Like `load()` it checks secret markers first
@@ -254,6 +261,10 @@ let ExtensionHost = class ExtensionHost {
254
261
  const ordered = resolveExtensions(entries.map((e) => e.manifest), SDK_VERSION);
255
262
  for (const manifest of ordered)
256
263
  assertSecretsReachable(manifest);
264
+ const identity = opts.extensionIdentity ?? extensionDbIdentity({ url: opts.dbUrl });
265
+ if (opts.extensionIdentity) {
266
+ await transferKnownExtensionSchemas(opts.dbUrl, identity, dirs.keys(), opts.connectTimeoutMs);
267
+ }
257
268
  let toMigrate = ordered;
258
269
  if (!opts.autoApprove && ordered.length > 0) {
259
270
  const sets = await permissionSets(ordered, dirs);
@@ -273,7 +284,7 @@ let ExtensionHost = class ExtensionHost {
273
284
  }
274
285
  const out = [];
275
286
  for (const manifest of toMigrate) {
276
- const r = await migratePlugin(opts.dbUrl, manifest, migrationsDirOf(manifest, dirs.get(manifest.name)), opts.connectTimeoutMs);
287
+ const r = await migratePlugin(identity.resolve(manifest.name), manifest, migrationsDirOf(manifest, dirs.get(manifest.name)), opts.connectTimeoutMs);
277
288
  if (r)
278
289
  out.push({ plugin: manifest.name, ...r });
279
290
  }
@@ -443,7 +454,7 @@ let ExtensionHost = class ExtensionHost {
443
454
  */
444
455
  modules,
445
456
  /** Tests only: `ctx.net`'s DNS and dispatcher seams (`EXTENSION_NET_SEAMS`). */
446
- netSeams) {
457
+ netSeams, dbIdentity = extensionDbIdentity(config.get().db)) {
447
458
  this.registry = registry;
448
459
  this.installs = installs;
449
460
  this.approvals = approvals;
@@ -451,6 +462,7 @@ let ExtensionHost = class ExtensionHost {
451
462
  this.config = config;
452
463
  this.log = log;
453
464
  this.effective = effective;
465
+ this.dbIdentity = dbIdentity;
454
466
  const c = config.get();
455
467
  this.hooks = new HookRegistry({
456
468
  instances: () => this.registry.all(),
@@ -1410,7 +1422,7 @@ let ExtensionHost = class ExtensionHost {
1410
1422
  // 安装记录:一个副本持锁迁移(C16),别的副本正在迁移时待定、旧实例照常;配置声明:按 schema 锁直接迁移
1411
1423
  const migrating = a.migrate
1412
1424
  ? a.migrate()
1413
- : migratePlugin(this.deps.dbUrl, manifest, a.migrationsDir, this.deps.connectTimeoutMs, this.abort.signal);
1425
+ : migratePlugin(this.dbIdentity.resolve(name), manifest, a.migrationsDir, this.deps.connectTimeoutMs, this.abort.signal);
1414
1426
  this.migrating = migrating;
1415
1427
  try {
1416
1428
  if ((await migrating) === "busy") {
@@ -1783,6 +1795,11 @@ let ExtensionHost = class ExtensionHost {
1783
1795
  warnUpgrades(this.log, this.imports);
1784
1796
  }
1785
1797
  let ctx;
1798
+ const name = spec.manifest.name;
1799
+ const identity = this.dbIdentity.resolve(name);
1800
+ const extensionDb = identity.separate
1801
+ ? extensionDbPool(identity, name, this.config.get().db, (err) => this.log.warn("extension database pool error", { plugin: name, err }))
1802
+ : undefined;
1786
1803
  const p = setupInstance(this.loadDeps, spec.manifest, {
1787
1804
  entryUrl: spec.entryUrl,
1788
1805
  source: spec.source,
@@ -1790,12 +1807,17 @@ let ExtensionHost = class ExtensionHost {
1790
1807
  config: spec.config,
1791
1808
  configHash: spec.configHash,
1792
1809
  permissions: spec.permissions,
1810
+ ...(extensionDb && { extensionDb }),
1793
1811
  onCtx: (c) => {
1794
1812
  if (c)
1795
1813
  ctx = c;
1796
1814
  if (c || this.settingUp === ctx)
1797
1815
  this.settingUp = c;
1798
1816
  },
1817
+ }).catch(async (error) => {
1818
+ if (!ctx)
1819
+ await extensionDb?.destroy();
1820
+ throw error;
1799
1821
  });
1800
1822
  if (timeoutMs === undefined)
1801
1823
  return p.then((inst) => this.logUiResolution(inst));
@@ -2476,6 +2498,7 @@ ExtensionHost = __decorate([
2476
2498
  __param(20, Optional()),
2477
2499
  __param(20, Inject(ModuleRef)),
2478
2500
  __param(21, Optional()),
2479
- __param(21, Inject(EXTENSION_NET_SEAMS))
2501
+ __param(21, Inject(EXTENSION_NET_SEAMS)),
2502
+ __param(22, Inject(ConfiguredExtensionDbIdentity))
2480
2503
  ], ExtensionHost);
2481
2504
  export { ExtensionHost };
@@ -1,5 +1,6 @@
1
1
  import { type DroppedUiContribution, type ExtensionManifest, type ExtensionPointRef, type ResolvedUiContribution, type StaticExtensionManifest } from "@capybara-hq/plugin-sdk";
2
2
  import { type ExtensionPointAccess, type KernelDeps, type KernelExtensionContext, LiveConfig, type RegisteredSetupCheck, type RegisteredTool, type Route } from "../ctx/create-ctx.js";
3
+ import type { extensionDbPool } from "../db/extension-db.js";
3
4
  import type { UiActionHandler, UiQueryHandler, UiRender } from "../ui/registry.js";
4
5
  import type { RegisteredHook } from "./hooks.js";
5
6
  import { InflightTracker } from "./inflight.js";
@@ -159,6 +160,7 @@ export declare function setupInstance(deps: LoadDeps, manifest: ExtensionManifes
159
160
  permissions: PermissionSet;
160
161
  /** 已建好 ctx、setup 进行中时回调(宿主据此在 close() 时立即关闭它)。 */
161
162
  onCtx?: (ctx: KernelExtensionContext | undefined) => void;
163
+ extensionDb?: ReturnType<typeof extensionDbPool>;
162
164
  }): Promise<ExtensionInstance>;
163
165
  /**
164
166
  * 加载一个插件实例:import → defineExtension → 有包内静态清单(`section`)时与 {@link staticManifestOf} 核对
@@ -179,4 +181,5 @@ export declare function loadInstance(deps: LoadDeps, input: {
179
181
  manifest: StaticExtensionManifest;
180
182
  };
181
183
  onCtx?: (ctx: KernelExtensionContext | undefined) => void;
184
+ extensionDb?: ReturnType<typeof extensionDbPool>;
182
185
  }): Promise<ExtensionInstance>;
@@ -2,6 +2,7 @@ import { dirname } from "node:path";
2
2
  import { fileURLToPath } from "node:url";
3
3
  import { defineExtension, ExtensionManifestError, staticManifestOf, } from "@capybara-hq/plugin-sdk";
4
4
  import { createExtensionContext, LiveConfig, } from "../ctx/create-ctx.js";
5
+ import { asPlatform } from "../infra/database/org-scope.js";
5
6
  import { InflightTracker } from "./inflight.js";
6
7
  const errMsg = (e) => (e instanceof Error ? e.message : String(e));
7
8
  /** 模块清单与审阅过的静态清单(包内 `capybara.manifest`)不一致。 */
@@ -299,10 +300,11 @@ export async function setupInstance(deps, manifest, input) {
299
300
  const live = new LiveConfig(input.config);
300
301
  const ctx = createExtensionContext(deps.kernel, manifest, live, deps.extensionPointAccess, {
301
302
  sha256: input.sha256,
303
+ ...(input.extensionDb && { db: input.extensionDb }),
302
304
  });
303
305
  input.onCtx?.(ctx);
304
306
  try {
305
- await manifest.setup(ctx);
307
+ await asPlatform("initialize an extension on this replica", () => manifest.setup(ctx));
306
308
  ctx.sealTools();
307
309
  for (const cap of manifest.provides) {
308
310
  if (!ctx.provided.has(cap)) {
@@ -1,3 +1,4 @@
1
+ import { type ExtensionDbConnection } from "../db/extension-db.js";
1
2
  import type { KernelSchemaDb } from "../db/kernel-schema.js";
2
3
  /** 插件迁移完成(kernel bus 主题,频道 `cap:kernel:plugins.migrated`,payload `{ plugin, sha256 }`)。 */
3
4
  export declare const PLUGINS_MIGRATED_TOPIC = "plugins.migrated";
@@ -8,6 +9,8 @@ export interface MigrateLockDeps {
8
9
  db: KernelSchemaDb;
9
10
  /** 迁移用独立连接(不走连接池)。 */
10
11
  dbUrl: string;
12
+ /** The schema migrations authenticate independently of the install record lock. */
13
+ extensionDb?: ExtensionDbConnection;
11
14
  connectTimeoutMs?: number | undefined;
12
15
  /** 发布 `plugins.migrated`(kernel bus)。 */
13
16
  bus: {
@@ -47,4 +50,4 @@ export declare function ensureMigrated(d: MigrateLockDeps, name: string, sha256:
47
50
  export declare function unrunMigrations(db: KernelSchemaDb, name: string, files: {
48
51
  file: string;
49
52
  sql: string;
50
- }[]): Promise<string[]>;
53
+ }[], identity?: ExtensionDbConnection, connectTimeoutMs?: number): Promise<string[]>;
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
2
2
  import { sql } from "kysely";
3
3
  import pg from "pg";
4
4
  import { pluginSchemaName } from "../ctx/create-ctx.js";
5
+ import { extensionDbPool } from "../db/extension-db.js";
5
6
  import { migrate } from "../db/migrator.js";
6
7
  import { pgConnectOptions } from "../db/pool.js";
7
8
  /** 插件迁移完成(kernel bus 主题,频道 `cap:kernel:plugins.migrated`,payload `{ plugin, sha256 }`)。 */
@@ -42,9 +43,10 @@ export async function ensureMigrated(d, name, sha256, dir) {
42
43
  const timeout = d.timeoutMs === undefined ? undefined : AbortSignal.timeout(d.timeoutMs);
43
44
  const signals = [d.signal, timeout].filter((x) => x !== undefined);
44
45
  try {
45
- await migrate(d.dbUrl, { schema: pluginSchemaName(name), dir }, {
46
+ await migrate(d.extensionDb?.url ?? d.dbUrl, { schema: pluginSchemaName(name), dir }, {
46
47
  connectTimeoutMs: d.connectTimeoutMs,
47
48
  signal: signals.length > 0 ? AbortSignal.any(signals) : undefined,
49
+ extensionLogin: d.extensionDb?.separate ? d.extensionDb.login : undefined,
48
50
  ...(d.timeoutMs !== undefined && {
49
51
  statementTimeoutMs: d.timeoutMs,
50
52
  lockTimeoutMs: Math.min(d.timeoutMs, MIGRATION_LOCK_TIMEOUT_MS),
@@ -83,9 +85,24 @@ export async function ensureMigrated(d, name, sha256, dir) {
83
85
  * 按插件 schema 的 `_migrations` 表比对文件名与 checksum(与迁移器相同的 sha256);改过内容的也算未执行。
84
86
  * 插件从没迁移过时返回全部文件。
85
87
  */
86
- export async function unrunMigrations(db, name, files) {
88
+ export async function unrunMigrations(db, name, files, identity, connectTimeoutMs) {
87
89
  if (files.length === 0)
88
90
  return [];
91
+ if (!identity?.separate)
92
+ return readUnrunMigrations(db, name, files);
93
+ const pool = extensionDbPool(identity, name, {
94
+ rls: "off",
95
+ connectTimeoutMs,
96
+ extensionPoolMax: 1,
97
+ });
98
+ try {
99
+ return await readUnrunMigrations(pool, name, files);
100
+ }
101
+ finally {
102
+ await pool.destroy();
103
+ }
104
+ }
105
+ async function readUnrunMigrations(db, name, files) {
89
106
  const schema = pluginSchemaName(name);
90
107
  const exists = await sql `SELECT to_regclass(${`"${schema}"._migrations`})::text AS t`.execute(db);
91
108
  const done = new Map();
@@ -111,20 +111,6 @@ export declare const OUTBOX_JOBS: {
111
111
  readonly removeOnFail: true;
112
112
  };
113
113
  };
114
- readonly "conversation-events-org-backfill": {
115
- readonly queue: "cap-kernel-maintenance";
116
- readonly idempotent: "Locks up to 5,000 NULL org_id rows after its (conversation_id, seq) cursor with FOR UPDATE SKIP LOCKED and fills each from its conversation's org_id; rows already filled are skipped and the next batch is owed atomically under a deterministic cursor job id";
117
- readonly processedIn: "packages/kernel/src/runtime/maintenance.ts";
118
- readonly opts: {
119
- readonly attempts: 5;
120
- readonly backoff: {
121
- readonly type: "exponential";
122
- readonly delay: 5000;
123
- };
124
- readonly removeOnComplete: true;
125
- readonly removeOnFail: true;
126
- };
127
- };
128
114
  readonly "file-release": {
129
115
  readonly queue: "cap-kernel-maintenance";
130
116
  readonly idempotent: "Re-reads the deleted file under its row lock and releases its blob only while nothing else points at it, or deletes its own staging key; a second run finds nothing to do";
@@ -98,21 +98,6 @@ export const OUTBOX_JOBS = {
98
98
  removeOnFail: true,
99
99
  },
100
100
  },
101
- // `conversations/event-org-backfill.ts` EVENT_ORG_BACKFILL_JOB: batched backfill of
102
- // `conversation_events.org_id` from `conversations`, owed by the periodic kickoff under
103
- // `eventOrgBackfillJobId(null)` and chained per 5,000-row batch under `eventOrgBackfillJobId(last)`
104
- "conversation-events-org-backfill": {
105
- queue: "cap-kernel-maintenance",
106
- idempotent: "Locks up to 5,000 NULL org_id rows after its (conversation_id, seq) cursor with FOR UPDATE SKIP LOCKED and fills each from its conversation's org_id; rows already filled are skipped and the next batch is owed atomically under a deterministic cursor job id",
107
- processedIn: "packages/kernel/src/runtime/maintenance.ts",
108
- // removed either way, so a later kickoff during a rolling deploy can owe the first batch again
109
- opts: {
110
- attempts: 5,
111
- backoff: { type: "exponential", delay: 5_000 },
112
- removeOnComplete: true,
113
- removeOnFail: true,
114
- },
115
- },
116
101
  // `files/blob-objects.ts` FILE_RELEASE_JOB: owed, deferred, by every discard and draft cleanup
117
102
  // of an upload, under `fileReleaseJobId`
118
103
  "file-release": {
package/dist/kernel.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { fileURLToPath } from "node:url";
2
+ import { extensionDbIdentity } from "./db/extension-db.js";
2
3
  import { canMigrateKernel, migrate, verifyMigrations } from "./db/migrator.js";
3
4
  import { createDb } from "./db/pool.js";
4
5
  import { ExtensionHost } from "./extensions/host.js";
@@ -49,6 +50,9 @@ export async function migrateAll(config, opts = {}) {
49
50
  });
50
51
  const plugins = await ExtensionHost.migrateOnly(config.extensions, {
51
52
  dbUrl: config.db.url,
53
+ ...(config.db.extensionsUrl !== undefined && {
54
+ extensionIdentity: extensionDbIdentity(config.db),
55
+ }),
52
56
  connectTimeoutMs,
53
57
  autoApprove: config.extensionPermissions.autoApprove,
54
58
  ...(opts.resolveFrom !== undefined && { resolveFrom: opts.resolveFrom }),
@@ -10,6 +10,7 @@ import { ChannelJobs } from "../channels/jobs.js";
10
10
  import { ChannelOutbound } from "../channels/outbound.js";
11
11
  import { PromptSuggestionQueue } from "../conversations/prompt-suggestions.js";
12
12
  import { TitleQueue } from "../conversations/titles.js";
13
+ import { type ExtensionDbIdentity } from "../db/extension-db.js";
13
14
  import { ExtensionBlobs } from "../extensions/blobs.js";
14
15
  import { BootstrapService } from "../extensions/bootstrap.js";
15
16
  import { BootstrapDefaultsService } from "../extensions/bootstrap-defaults.js";
@@ -76,6 +77,7 @@ export declare class KernelLifecycle implements OnApplicationBootstrap, BeforeAp
76
77
  private readonly kdb;
77
78
  private readonly shutdown;
78
79
  private readonly host;
80
+ private readonly extensionDbIdentity;
79
81
  private readonly registry;
80
82
  private readonly installs;
81
83
  private readonly blobs;
@@ -111,7 +113,7 @@ export declare class KernelLifecycle implements OnApplicationBootstrap, BeforeAp
111
113
  private bootstrapPackages;
112
114
  /** The merged bootstrap manifest, read once per start. */
113
115
  private mergedManifest;
114
- constructor(permissionConfig: PermissionConfigPublication, accounts: AccountsService, configService: KernelConfigService, log: KernelLogger, options: KernelAppOptions, pool: Kysely<any>, redis: Redis, kdb: KernelDb, shutdown: GracefulShutdown, host: ExtensionHost, registry: ExtensionRegistry, installs: ExtensionInstalls, blobs: ExtensionBlobs, extensionLifecycle: ExtensionLifecycle, replicaStatus: ReplicaStatusStore, bootstrap: BootstrapService, bootstrapDefaults: BootstrapDefaultsService, marketplaces: MarketplacesService, pluginImport: PluginImport, pluginUpdater: PlatformPluginUpdater, bus: Pick<ExtensionContext["bus"], "publish" | "subscribe">, usageReport: UsageReporter, titles: TitleQueue, suggestions: PromptSuggestionQueue, channelJobs: ChannelJobs, channelOutbound: ChannelOutbound, presence: ReplicaPresence, worker?: WorkerRole | undefined, gateway?: GatewayRole | undefined);
116
+ constructor(permissionConfig: PermissionConfigPublication, accounts: AccountsService, configService: KernelConfigService, log: KernelLogger, options: KernelAppOptions, pool: Kysely<any>, redis: Redis, kdb: KernelDb, shutdown: GracefulShutdown, host: ExtensionHost, extensionDbIdentity: ExtensionDbIdentity, registry: ExtensionRegistry, installs: ExtensionInstalls, blobs: ExtensionBlobs, extensionLifecycle: ExtensionLifecycle, replicaStatus: ReplicaStatusStore, bootstrap: BootstrapService, bootstrapDefaults: BootstrapDefaultsService, marketplaces: MarketplacesService, pluginImport: PluginImport, pluginUpdater: PlatformPluginUpdater, bus: Pick<ExtensionContext["bus"], "publish" | "subscribe">, usageReport: UsageReporter, titles: TitleQueue, suggestions: PromptSuggestionQueue, channelJobs: ChannelJobs, channelOutbound: ChannelOutbound, presence: ReplicaPresence, worker?: WorkerRole | undefined, gateway?: GatewayRole | undefined);
115
117
  /** The kernel HTTP application (set up by `buildKernelApp` before `init()`). */
116
118
  get http(): KernelHttpApp;
117
119
  attachHttp(http: KernelHttpApp): void;
@@ -17,6 +17,7 @@ import { ChannelJobs } from "../channels/jobs.js";
17
17
  import { ChannelOutbound } from "../channels/outbound.js";
18
18
  import { PromptSuggestionQueue } from "../conversations/prompt-suggestions.js";
19
19
  import { TitleQueue } from "../conversations/titles.js";
20
+ import { ConfiguredExtensionDbIdentity } from "../db/extension-db.js";
20
21
  import { ExtensionBlobs } from "../extensions/blobs.js";
21
22
  import { BootstrapFailedError, BootstrapService, } from "../extensions/bootstrap.js";
22
23
  import { BootstrapDefaultsService } from "../extensions/bootstrap-defaults.js";
@@ -98,6 +99,7 @@ let KernelLifecycle = class KernelLifecycle {
98
99
  kdb;
99
100
  shutdown;
100
101
  host;
102
+ extensionDbIdentity;
101
103
  registry;
102
104
  installs;
103
105
  blobs;
@@ -135,7 +137,7 @@ let KernelLifecycle = class KernelLifecycle {
135
137
  mergedManifest;
136
138
  constructor(permissionConfig, accounts, configService, log, options,
137
139
  // biome-ignore lint/suspicious/noExplicitAny: the pool carries no schema types
138
- pool, redis, kdb, shutdown, host, registry, installs, blobs, extensionLifecycle, replicaStatus, bootstrap, bootstrapDefaults, marketplaces, pluginImport, pluginUpdater, bus,
140
+ pool, redis, kdb, shutdown, host, extensionDbIdentity, registry, installs, blobs, extensionLifecycle, replicaStatus, bootstrap, bootstrapDefaults, marketplaces, pluginImport, pluginUpdater, bus,
139
141
  // the producers closed on every role (their consumers are the worker role's)
140
142
  usageReport, titles, suggestions, channelJobs, channelOutbound,
141
143
  // this process's presence beat, on every role (admin overview spec §5.1)
@@ -153,6 +155,7 @@ let KernelLifecycle = class KernelLifecycle {
153
155
  this.kdb = kdb;
154
156
  this.shutdown = shutdown;
155
157
  this.host = host;
158
+ this.extensionDbIdentity = extensionDbIdentity;
156
159
  this.registry = registry;
157
160
  this.installs = installs;
158
161
  this.blobs = blobs;
@@ -294,6 +297,7 @@ let KernelLifecycle = class KernelLifecycle {
294
297
  : ensureMigrated({
295
298
  db: this.kdb.db,
296
299
  dbUrl: config.db.url,
300
+ extensionDb: this.extensionDbIdentity.resolve(d.name),
297
301
  connectTimeoutMs: config.db.connectTimeoutMs,
298
302
  bus: this.bus,
299
303
  log: this.log,
@@ -572,26 +576,27 @@ KernelLifecycle = __decorate([
572
576
  __param(7, Inject(KernelDb)),
573
577
  __param(8, Inject(GracefulShutdown)),
574
578
  __param(9, Inject(ExtensionHost)),
575
- __param(10, Inject(ExtensionRegistry)),
576
- __param(11, Inject(ExtensionInstalls)),
577
- __param(12, Inject(ExtensionBlobs)),
578
- __param(13, Inject(ExtensionLifecycle)),
579
- __param(14, Inject(ReplicaStatusStore)),
580
- __param(15, Inject(BootstrapService)),
581
- __param(16, Inject(BootstrapDefaultsService)),
582
- __param(17, Inject(MarketplacesService)),
583
- __param(18, Inject(PluginImport)),
584
- __param(19, Inject(PlatformPluginUpdater)),
585
- __param(20, Inject(KERNEL_BUS)),
586
- __param(21, Inject(UsageReporter)),
587
- __param(22, Inject(TitleQueue)),
588
- __param(23, Inject(PromptSuggestionQueue)),
589
- __param(24, Inject(ChannelJobs)),
590
- __param(25, Inject(ChannelOutbound)),
591
- __param(26, Inject(ReplicaPresence)),
592
- __param(27, Optional()),
593
- __param(27, Inject(WorkerRole)),
579
+ __param(10, Inject(ConfiguredExtensionDbIdentity)),
580
+ __param(11, Inject(ExtensionRegistry)),
581
+ __param(12, Inject(ExtensionInstalls)),
582
+ __param(13, Inject(ExtensionBlobs)),
583
+ __param(14, Inject(ExtensionLifecycle)),
584
+ __param(15, Inject(ReplicaStatusStore)),
585
+ __param(16, Inject(BootstrapService)),
586
+ __param(17, Inject(BootstrapDefaultsService)),
587
+ __param(18, Inject(MarketplacesService)),
588
+ __param(19, Inject(PluginImport)),
589
+ __param(20, Inject(PlatformPluginUpdater)),
590
+ __param(21, Inject(KERNEL_BUS)),
591
+ __param(22, Inject(UsageReporter)),
592
+ __param(23, Inject(TitleQueue)),
593
+ __param(24, Inject(PromptSuggestionQueue)),
594
+ __param(25, Inject(ChannelJobs)),
595
+ __param(26, Inject(ChannelOutbound)),
596
+ __param(27, Inject(ReplicaPresence)),
594
597
  __param(28, Optional()),
595
- __param(28, Inject(GatewayRole))
598
+ __param(28, Inject(WorkerRole)),
599
+ __param(29, Optional()),
600
+ __param(29, Inject(GatewayRole))
596
601
  ], KernelLifecycle);
597
602
  export { KernelLifecycle };
@@ -21,8 +21,6 @@ import { ClientReportsCron } from "../client/client-reports.cron.js";
21
21
  import { AttachmentsModule } from "../conversations/attachments.module.js";
22
22
  import { AttachmentCleanupJob } from "../conversations/attachments.service.js";
23
23
  import { EventLogModule } from "../conversations/event-log.js";
24
- import { EventOrgBackfillKickoffJob } from "../conversations/event-org-backfill.js";
25
- import { EventOrgBackfillModule } from "../conversations/event-org-backfill.module.js";
26
24
  import { PromptSuggestionsModule } from "../conversations/prompt-suggestions.js";
27
25
  import { TitlesModule } from "../conversations/titles.js";
28
26
  import { ConversationNoticeSweepJob, ConversationNoticesModule, } from "../device-access/conversation-notice-delivery.js";
@@ -115,8 +113,6 @@ let WorkerModule = WorkerModule_1 = class WorkerModule {
115
113
  LibraryFilesModule,
116
114
  // the hashing and catch-up copy the kickoff owes
117
115
  FileLibraryJobsModule,
118
- // the batched conversation_events.org_id backfill the kickoff owes
119
- EventOrgBackfillModule,
120
116
  IdentityModule,
121
117
  StorageModule,
122
118
  SandboxModule,
@@ -142,8 +138,6 @@ let WorkerModule = WorkerModule_1 = class WorkerModule {
142
138
  FileDraftCleanupJob,
143
139
  // the daily blob sweep and the hourly kickoff of hashing and the catch-up copy (§7, §9)
144
140
  FileLibraryKickoffJob,
145
- // the periodic kickoff of the batched conversation_events.org_id backfill (issue #1175)
146
- EventOrgBackfillKickoffJob,
147
141
  StoragePurgeJob,
148
142
  RetentionSweep,
149
143
  ErasureSweep,