@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
@@ -66,6 +66,7 @@ export declare class ReplicaStatusStore {
66
66
  * 该插件这一行属于生效的那一方(配置声明),所以只追加 detail。
67
67
  */
68
68
  note(plugin: string, detail: string): Promise<void>;
69
+ clearNote(plugin: string, detail: string): Promise<void>;
69
70
  /**
70
71
  * 心跳:本副本全部行的 `heartbeat_at` 取当前时间(每次 reconcile 之后调用;读状态的一方只算心跳不超过
71
72
  * 3 个 reconcile 周期的副本,C16)。
@@ -88,6 +88,15 @@ let ReplicaStatusStore = class ReplicaStatusStore {
88
88
  .where("plugin", "=", plugin)
89
89
  .execute();
90
90
  }
91
+ async clearNote(plugin, detail) {
92
+ await this.db
93
+ .updateTable("extension_replica_status")
94
+ .set({ detail: null })
95
+ .where("replica_id", "=", this.replicaId)
96
+ .where("plugin", "=", plugin)
97
+ .where("detail", "=", this.cleanDetail(detail))
98
+ .execute();
99
+ }
91
100
  /**
92
101
  * 心跳:本副本全部行的 `heartbeat_at` 取当前时间(每次 reconcile 之后调用;读状态的一方只算心跳不超过
93
102
  * 3 个 reconcile 周期的副本,C16)。
@@ -77,9 +77,14 @@ export declare class InboxItemsService {
77
77
  */
78
78
  post(source: InboxSource, p: InboxPost, opts?: {
79
79
  detail?: Record<string, unknown>;
80
+ resolved?: boolean;
80
81
  }): Promise<{
81
82
  itemId: string;
82
83
  }>;
84
+ /** Checks the current recipient and permissions before a durable post is prepared or delivered. */
85
+ prepare(source: InboxSource, p: InboxPost): Promise<string | null>;
86
+ /** Resolves open posts of this exact plugin, recipient and post key. */
87
+ resolveForPostKey(plugin: string, orgId: string, accountId: string, postKey: string): Promise<void>;
83
88
  /** The open items of (org, account, source, plugin) with `dedupe`, closed as `expired`. */
84
89
  private sameKey;
85
90
  /**
@@ -68,39 +68,8 @@ let InboxItemsService = class InboxItemsService {
68
68
  * `org_disabled` (the plugin is not enabled in the org).
69
69
  */
70
70
  async post(source, p, opts = {}) {
71
- if (typeof p !== "object" || p === null)
72
- throw invalid("the item must be an object");
73
- const plugin = source.kind === "plugin" ? source.plugin : null;
74
- const errs = validateInboxPost(p, plugin ?? "").filter((e) => plugin !== null || e !== "link_invalid");
75
- if (plugin === null) {
76
- if (p.link !== undefined && (typeof p.link !== "string" || !kernelLinkOk(p.link)))
77
- errs.push("link_invalid");
78
- if (p.actions !== undefined && p.actions.length > 0)
79
- errs.push("kernel_item_actions");
80
- }
81
- if (errs.length > 0)
82
- throw invalid(`invalid inbox item: ${errs.join(", ")}`);
71
+ const plugin = await this.prepare(source, p);
83
72
  const db = this.kdb.db;
84
- const org = await db
85
- .selectFrom("orgs")
86
- .select("id")
87
- .where("id", "=", p.orgId)
88
- .where("deleted_at", "is", null)
89
- .executeTakeFirst();
90
- if (org === undefined)
91
- throw invalid(`org ${p.orgId} does not exist or is deleted`);
92
- if (plugin !== null && !(await isExtensionEnabled(db, p.orgId, plugin)))
93
- throw new InboxError("org_disabled", `${plugin} is not enabled in org ${p.orgId}`);
94
- const member = await db
95
- .selectFrom("memberships")
96
- .innerJoin("accounts", "accounts.id", "memberships.account_id")
97
- .select("accounts.id")
98
- .where("memberships.org_id", "=", p.orgId)
99
- .where("memberships.account_id", "=", p.accountId)
100
- .where("accounts.status", "=", "active")
101
- .executeTakeFirst();
102
- if (member === undefined)
103
- throw invalid(`account ${p.accountId} is not an active member of org ${p.orgId}`);
104
73
  const dedupe = p.dedupeKey ?? null;
105
74
  if (dedupe !== null) {
106
75
  // an expired item with the key leaves the index's way: it is closed, a new one replaces it
@@ -127,6 +96,7 @@ let InboxItemsService = class InboxItemsService {
127
96
  org_id: p.orgId,
128
97
  account_id: p.accountId,
129
98
  source: source.kind,
99
+ ...(opts.resolved && { state: "resolved", resolved_at: sql `now()` }),
130
100
  plugin,
131
101
  kind: p.kind,
132
102
  title: single(p.title),
@@ -148,7 +118,8 @@ let InboxItemsService = class InboxItemsService {
148
118
  // the conflicting item may close between the insert and the read: then the insert runs again
149
119
  for (let attempt = 0; attempt < 2; attempt++) {
150
120
  if ((await insert()) !== undefined) {
151
- await this.push.oweInboxItem(id, p.orgId);
121
+ if (!opts.resolved)
122
+ await this.push.oweInboxItem(id, p.orgId);
152
123
  return { itemId: id };
153
124
  }
154
125
  if (dedupe === null)
@@ -168,6 +139,56 @@ let InboxItemsService = class InboxItemsService {
168
139
  }
169
140
  throw new Error("inbox item insert kept conflicting with a closed item");
170
141
  }
142
+ /** Checks the current recipient and permissions before a durable post is prepared or delivered. */
143
+ async prepare(source, p) {
144
+ if (typeof p !== "object" || p === null)
145
+ throw invalid("the item must be an object");
146
+ const plugin = source.kind === "plugin" ? source.plugin : null;
147
+ const errs = validateInboxPost(p, plugin ?? "").filter((e) => plugin !== null || e !== "link_invalid");
148
+ if (plugin === null) {
149
+ if (p.link !== undefined && (typeof p.link !== "string" || !kernelLinkOk(p.link)))
150
+ errs.push("link_invalid");
151
+ if (p.actions !== undefined && p.actions.length > 0)
152
+ errs.push("kernel_item_actions");
153
+ }
154
+ if (errs.length > 0)
155
+ throw invalid(`invalid inbox item: ${errs.join(", ")}`);
156
+ const db = this.kdb.db;
157
+ const org = await db
158
+ .selectFrom("orgs")
159
+ .select("id")
160
+ .where("id", "=", p.orgId)
161
+ .where("deleted_at", "is", null)
162
+ .executeTakeFirst();
163
+ if (org === undefined)
164
+ throw invalid(`org ${p.orgId} does not exist or is deleted`);
165
+ if (plugin !== null && !(await isExtensionEnabled(db, p.orgId, plugin)))
166
+ throw new InboxError("org_disabled", `${plugin} is not enabled in org ${p.orgId}`);
167
+ const member = await db
168
+ .selectFrom("memberships")
169
+ .innerJoin("accounts", "accounts.id", "memberships.account_id")
170
+ .select("accounts.id")
171
+ .where("memberships.org_id", "=", p.orgId)
172
+ .where("memberships.account_id", "=", p.accountId)
173
+ .where("accounts.status", "=", "active")
174
+ .executeTakeFirst();
175
+ if (member === undefined)
176
+ throw invalid(`account ${p.accountId} is not an active member of org ${p.orgId}`);
177
+ return plugin;
178
+ }
179
+ /** Resolves open posts of this exact plugin, recipient and post key. */
180
+ async resolveForPostKey(plugin, orgId, accountId, postKey) {
181
+ await this.kdb.db
182
+ .updateTable("inbox_items")
183
+ .set({ state: "resolved", resolved_at: sql `now()` })
184
+ .where("org_id", "=", orgId)
185
+ .where("account_id", "=", accountId)
186
+ .where("source", "=", "plugin")
187
+ .where("plugin", "=", plugin)
188
+ .where("dedupe_key", "=", postKey)
189
+ .where("state", "=", "open")
190
+ .execute();
191
+ }
171
192
  /** The open items of (org, account, source, plugin) with `dedupe`, closed as `expired`. */
172
193
  sameKey(orgId, accountId, source, dedupe) {
173
194
  const plugin = source.kind === "plugin" ? source.plugin : "";
@@ -299,6 +320,9 @@ let InboxItemsService = class InboxItemsService {
299
320
  __decorate([
300
321
  Transactional()
301
322
  ], InboxItemsService.prototype, "post", null);
323
+ __decorate([
324
+ Transactional({ propagation: "mandatory" })
325
+ ], InboxItemsService.prototype, "resolveForPostKey", null);
302
326
  __decorate([
303
327
  Transactional()
304
328
  ], InboxItemsService.prototype, "resolveForPlugin", null);
package/dist/index.d.ts CHANGED
@@ -20,6 +20,8 @@ export { createKv } from "./ctx/kv.js";
20
20
  export { createLock } from "./ctx/lock.js";
21
21
  export { createQueue } from "./ctx/queue.js";
22
22
  export { createKeyring, createSecrets, type DerivedKeys, type Keyring, REWRAP_BATCH_SIZE, type RewrapResult, rewrapToCurrentMasterKey, } from "./ctx/secrets.js";
23
+ export { extensionDbIdentity } from "./db/extension-db.js";
24
+ export { createProvisionedExtensionSchema, provisionExtensionRole, } from "./db/extension-role-provision.js";
23
25
  export { type KernelDatabase, type KernelSchemaDb, kernelDb } from "./db/kernel-schema.js";
24
26
  export { type MigrationOwner, migrate } from "./db/migrator.js";
25
27
  export { createDb } from "./db/pool.js";
@@ -64,7 +66,7 @@ export type { RlsMode } from "./infra/database/scoped-dialect.js";
64
66
  export { onProcessFault } from "./infra/health/process-fault.js";
65
67
  export { GUARD_CIRCUIT_LIMIT, GUARD_CIRCUIT_WINDOW_MS, installProcessGuards, type ProcessGuardDeps, } from "./infra/lifecycle/process-guards.js";
66
68
  export { handleShutdownSignals, type ShutdownSignalHandle, type ShutdownSignalOptions, } from "./infra/lifecycle/shutdown-signals.js";
67
- export { KERNEL_MIGRATIONS_DIR, KERNEL_SCHEMA, migrateAll, prepareKernelDatabase, } from "./kernel.js";
69
+ export { declaredExtensionNames, KERNEL_MIGRATIONS_DIR, KERNEL_SCHEMA, migrateAll, prepareKernelDatabase, } from "./kernel.js";
68
70
  export { createLogger, type KernelLogger, LOG_FORMATS, LOG_LEVELS, type LogFormat, type LoggerOptions, type LogLevel, type LogOutput, } from "./log.js";
69
71
  export { createConfiguredLogger, loggerOptionsFromConfig } from "./log-config.js";
70
72
  export { type ContextJob, type JobWrapper, type LogContext, logContext, setJobWrapper, setTraceContextSource, withJobContext, withLogContext, } from "./log-context.js";
package/dist/index.js CHANGED
@@ -19,6 +19,8 @@ export { createKv } from "./ctx/kv.js";
19
19
  export { createLock } from "./ctx/lock.js";
20
20
  export { createQueue } from "./ctx/queue.js";
21
21
  export { createKeyring, createSecrets, REWRAP_BATCH_SIZE, rewrapToCurrentMasterKey, } from "./ctx/secrets.js";
22
+ export { extensionDbIdentity } from "./db/extension-db.js";
23
+ export { createProvisionedExtensionSchema, provisionExtensionRole, } from "./db/extension-role-provision.js";
22
24
  export { kernelDb } from "./db/kernel-schema.js";
23
25
  export { migrate } from "./db/migrator.js";
24
26
  export { createDb } from "./db/pool.js";
@@ -61,7 +63,7 @@ export { asPlatform, currentScope, setUnscopedQueryCheck, withOrgScope, } from "
61
63
  export { onProcessFault } from "./infra/health/process-fault.js";
62
64
  export { GUARD_CIRCUIT_LIMIT, GUARD_CIRCUIT_WINDOW_MS, installProcessGuards, } from "./infra/lifecycle/process-guards.js";
63
65
  export { handleShutdownSignals, } from "./infra/lifecycle/shutdown-signals.js";
64
- export { KERNEL_MIGRATIONS_DIR, KERNEL_SCHEMA, migrateAll, prepareKernelDatabase, } from "./kernel.js";
66
+ export { declaredExtensionNames, KERNEL_MIGRATIONS_DIR, KERNEL_SCHEMA, migrateAll, prepareKernelDatabase, } from "./kernel.js";
65
67
  export { createLogger, LOG_FORMATS, LOG_LEVELS, } from "./log.js";
66
68
  export { createConfiguredLogger, loggerOptionsFromConfig } from "./log-config.js";
67
69
  export { logContext, setJobWrapper, setTraceContextSource, withJobContext, withLogContext, } from "./log-context.js";
@@ -0,0 +1,10 @@
1
+ import { type Kysely, type QueryExecutorProvider } from "kysely";
2
+ import { type ExtensionDbIdentity } from "../../db/extension-db.js";
3
+ type TransactionExecutor = QueryExecutorProvider & Pick<Kysely<unknown>, "isTransaction">;
4
+ /** The pin must stay on the connection that will commit the envelope. */
5
+ export declare function pinSigningKey(db: Kysely<unknown>, keyId: string): Promise<boolean>;
6
+ /** A live signer keeps its key, and retirement can still collect other unused keys. */
7
+ export declare function tryLockRetiredKey(db: TransactionExecutor, keyId: string): Promise<boolean>;
8
+ /** Includes parked and unloaded extensions' envelopes. A failed scan leaves every key intact. */
9
+ export declare function handoffKeysInUse(db: QueryExecutorProvider, keyIds: readonly string[], identity: Pick<ExtensionDbIdentity, "resolve">): Promise<Set<string>>;
10
+ export {};
@@ -0,0 +1,69 @@
1
+ import { EXTENSION_NAME_RE } from "@capybara-hq/plugin-sdk";
2
+ import { sql } from "kysely";
3
+ import { pluginSchemaName } from "../../db/extension-db.js";
4
+ import { EXTENSION_EFFECT_HANDOFF } from "./extension-handoff.js";
5
+ const signingKeyLock = (keyId) => sql `pg_catalog.hashtextextended(${`capybara.extension-effect-signing-key:${keyId}`}, 0)`;
6
+ /** The pin must stay on the connection that will commit the envelope. */
7
+ export async function pinSigningKey(db, keyId) {
8
+ if (!db.isTransaction)
9
+ throw new Error("Extension effect signing requires a local transaction");
10
+ const { rows } = await sql `
11
+ select pg_catalog.pg_try_advisory_xact_lock_shared(${signingKeyLock(keyId)}) as acquired
12
+ `.execute(db.withoutPlugins());
13
+ return rows[0]?.acquired === true;
14
+ }
15
+ /** A live signer keeps its key, and retirement can still collect other unused keys. */
16
+ export async function tryLockRetiredKey(db, keyId) {
17
+ if (!db.isTransaction)
18
+ throw new Error("Extension effect key retirement requires a transaction");
19
+ const { rows } = await sql `
20
+ select pg_catalog.pg_try_advisory_xact_lock(${signingKeyLock(keyId)}) as acquired
21
+ `.execute(db);
22
+ return rows[0]?.acquired === true;
23
+ }
24
+ /** Includes parked and unloaded extensions' envelopes. A failed scan leaves every key intact. */
25
+ export async function handoffKeysInUse(db, keyIds, identity) {
26
+ if (keyIds.length === 0)
27
+ return new Set();
28
+ await sql `set local lock_timeout = '500ms'`.execute(db);
29
+ await sql `set local statement_timeout = '1000ms'`.execute(db);
30
+ const prefix = "plugin_";
31
+ const { rows: tables } = await sql `
32
+ select n.nspname as schema, c.oid, c.relkind = 'r' and not c.relrowsecurity as ordinary,
33
+ pg_catalog.pg_get_userbyid(c.relowner) as owner, current_user as login
34
+ from pg_catalog.pg_class c
35
+ join pg_catalog.pg_namespace n on n.oid = c.relnamespace
36
+ where pg_catalog.left(n.nspname, ${prefix.length}) = ${prefix}
37
+ and c.relname = ${EXTENSION_EFFECT_HANDOFF}
38
+ `.execute(db);
39
+ const used = new Set();
40
+ for (const { schema, oid, ordinary, owner, login } of tables) {
41
+ const plugin = schema.slice(prefix.length).replaceAll("_", "-");
42
+ if (!EXTENSION_NAME_RE.test(plugin) || pluginSchemaName(plugin) !== schema)
43
+ continue;
44
+ const extension = identity.resolve(plugin);
45
+ if (!ordinary || (extension.separate ? owner === extension.login : owner !== login)) {
46
+ throw new Error("Cannot verify extension effect handoff owner during key retirement");
47
+ }
48
+ const table = sql.id(schema, EXTENSION_EFFECT_HANDOFF);
49
+ await sql `lock table only ${table} in access share mode`.execute(db);
50
+ const { rows } = await sql `
51
+ select pg_catalog.to_regclass(${`${schema}.${EXTENSION_EFFECT_HANDOFF}`}) = ${oid}::oid
52
+ and c.relkind = 'r' and not c.relrowsecurity
53
+ and pg_catalog.pg_get_userbyid(c.relowner) = ${owner} as matches
54
+ from pg_catalog.pg_class c
55
+ where c.oid = ${oid}::oid
56
+ `.execute(db);
57
+ if (!rows[0]?.matches)
58
+ throw new Error("Extension effect handoff changed during key retirement");
59
+ const references = await sql `
60
+ select distinct envelope->>'keyId' as id from only ${table}
61
+ where envelope->>'keyId' = any(${keyIds}::text[])
62
+ `.execute(db);
63
+ for (const { id } of references.rows)
64
+ used.add(id);
65
+ if (used.size === keyIds.length)
66
+ break;
67
+ }
68
+ return used;
69
+ }
@@ -0,0 +1,27 @@
1
+ import { type Kysely } from "kysely";
2
+ import type { ExtensionEffectEnvelope } from "../../ctx/durable-effects.service.js";
3
+ export declare const isExtensionTransaction: (db: Kysely<unknown>) => boolean;
4
+ export declare const EXTENSION_EFFECT_HANDOFF = "_capybara_effect_handoff";
5
+ export declare function handoffTable(plugin: string): string;
6
+ export declare function appendEffect(tx: Kysely<unknown>, plugin: string, envelope: ExtensionEffectEnvelope): Promise<void>;
7
+ export interface HandoffRow {
8
+ id: string;
9
+ envelope: ExtensionEffectEnvelope;
10
+ attempts: number;
11
+ created_at: Date;
12
+ }
13
+ export declare function readHandoff(db: Kysely<unknown>, plugin: string, extensionLogin: string | null, batch: number): Promise<HandoffRow[]>;
14
+ export declare function retryHandoff(db: Kysely<unknown>, plugin: string, extensionLogin: string | null, row: Pick<HandoffRow, "id" | "attempts">, reason: string): Promise<void>;
15
+ export declare function settleHandoff(db: Kysely<unknown>, plugin: string, extensionLogin: string | null, id: string): Promise<void>;
16
+ export interface HandoffReference {
17
+ plugin: string;
18
+ rowId: string;
19
+ hash: string;
20
+ size: number;
21
+ }
22
+ export declare function handoffReference(plugin: string, row: HandoffRow): HandoffReference;
23
+ export declare function readHandoffRow(db: Kysely<unknown>, plugin: string, login: string | null, id: string): Promise<HandoffRow | undefined>;
24
+ export declare function markHandoffParked(db: Kysely<unknown>, plugin: string, login: string | null, id: string, reason: string): Promise<void>;
25
+ export declare function readUnreferencedParks(db: Kysely<unknown>, plugin: string, login: string | null, batch: number): Promise<(HandoffRow & {
26
+ has_reference: boolean;
27
+ })[]>;
@@ -0,0 +1,113 @@
1
+ import { createHash } from "node:crypto";
2
+ import { sql } from "kysely";
3
+ import { ExtensionEffectFailure } from "../../ctx/durable-failure.js";
4
+ import { pluginSchemaName } from "../../db/extension-db.js";
5
+ export const isExtensionTransaction = (db) => db.isTransaction;
6
+ export const EXTENSION_EFFECT_HANDOFF = "_capybara_effect_handoff";
7
+ export function handoffTable(plugin) {
8
+ return `${pluginSchemaName(plugin)}.${EXTENSION_EFFECT_HANDOFF}`;
9
+ }
10
+ export async function appendEffect(tx, plugin, envelope) {
11
+ try {
12
+ await sql `
13
+ insert into ${sql.table(handoffTable(plugin))} (id, envelope)
14
+ values (pg_catalog.gen_random_uuid(), cast(${JSON.stringify(envelope)} as jsonb))
15
+ `.execute(tx.withoutPlugins());
16
+ }
17
+ catch (error) {
18
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "42P01") {
19
+ throw new Error(`Extension handoff for ${plugin} is unavailable. Run capybara migrate using the split-role schema provisioning procedure.`, { cause: error });
20
+ }
21
+ throw error;
22
+ }
23
+ }
24
+ async function withVerifiedHandoff(db, plugin, extensionLogin, run) {
25
+ const name = handoffTable(plugin);
26
+ return db.transaction().execute(async (tx) => {
27
+ await sql `set local lock_timeout = '500ms'`.execute(tx);
28
+ await sql `set local statement_timeout = '1000ms'`.execute(tx);
29
+ const relation = async () => {
30
+ const { rows } = await sql `
31
+ select c.relkind = 'r' and
32
+ case when ${extensionLogin}::text is null then
33
+ pg_catalog.pg_get_userbyid(c.relowner) = current_user
34
+ else
35
+ pg_catalog.pg_get_userbyid(c.relowner) <> ${extensionLogin}
36
+ end as valid
37
+ from pg_catalog.pg_class c where c.oid = pg_catalog.to_regclass(${name})
38
+ `.execute(tx);
39
+ return rows[0];
40
+ };
41
+ const before = await relation();
42
+ if (!before)
43
+ throw new ExtensionEffectFailure("handoff_missing", "The extension handoff table is missing");
44
+ if (!before.valid)
45
+ throw new Error("Invalid extension handoff relation");
46
+ await sql `lock table ${sql.table(name)} in access share mode`.execute(tx);
47
+ if (!(await relation())?.valid)
48
+ throw new Error("Invalid extension handoff relation");
49
+ return run(tx, name);
50
+ });
51
+ }
52
+ export async function readHandoff(db, plugin, extensionLogin, batch) {
53
+ return withVerifiedHandoff(db, plugin, extensionLogin, async (trx, name) => {
54
+ const result = await sql `
55
+ select id, envelope, attempts, created_at from ${sql.table(name)}
56
+ where parked_at is null and next_attempt_at <= pg_catalog.now()
57
+ order by next_attempt_at, id limit ${batch}
58
+ `.execute(trx);
59
+ return result.rows;
60
+ });
61
+ }
62
+ export async function retryHandoff(db, plugin, extensionLogin, row, reason) {
63
+ const delay = Math.min(300, 2 ** Math.min(9, row.attempts));
64
+ await withVerifiedHandoff(db, plugin, extensionLogin, async (tx, name) => {
65
+ await sql `
66
+ update ${sql.table(name)}
67
+ set attempts = least(19, attempts + 1), last_error = ${reason}, next_attempt_at = pg_catalog.now() + make_interval(secs => ${delay})
68
+ where id = ${row.id} and attempts = ${row.attempts}
69
+ `.execute(tx);
70
+ });
71
+ }
72
+ export async function settleHandoff(db, plugin, extensionLogin, id) {
73
+ await withVerifiedHandoff(db, plugin, extensionLogin, async (trx, name) => {
74
+ await sql `delete from ${sql.table(name)} where id = ${id}`.execute(trx);
75
+ });
76
+ }
77
+ export function handoffReference(plugin, row) {
78
+ const bytes = JSON.stringify(row.envelope);
79
+ return {
80
+ plugin,
81
+ rowId: row.id,
82
+ hash: createHash("sha256").update(bytes).digest("hex"),
83
+ size: Buffer.byteLength(bytes),
84
+ };
85
+ }
86
+ export async function readHandoffRow(db, plugin, login, id) {
87
+ return withVerifiedHandoff(db, plugin, login, async (tx, name) => (await sql `select id, envelope, attempts, created_at from ${sql.table(name)} where id = ${id}`.execute(tx)).rows[0]);
88
+ }
89
+ export async function markHandoffParked(db, plugin, login, id, reason) {
90
+ await withVerifiedHandoff(db, plugin, login, async (tx, name) => {
91
+ await sql `update ${sql.table(name)} set parked_at = pg_catalog.now(), last_error = ${reason} where id = ${id}`.execute(tx);
92
+ });
93
+ }
94
+ export async function readUnreferencedParks(db, plugin, login, batch) {
95
+ return withVerifiedHandoff(db, plugin, login, async (tx, name) => {
96
+ const { rows } = await sql `
97
+ select source.id, source.envelope, source.attempts, source.created_at,
98
+ job.id is not null as has_reference
99
+ from ${sql.table(name)} source
100
+ left join lateral (
101
+ select job.id, job.org_id from capybara.outbox job
102
+ where job.job_name = 'extension-effect-redrive'
103
+ and job.data->>'plugin' = ${plugin} and job.data->>'rowId' = source.id::text
104
+ limit 1
105
+ ) job on true
106
+ where source.parked_at is not null and (job.id is null or (job.org_id is not null and not exists (
107
+ select 1 from capybara.orgs org where org.id = job.org_id and org.deleted_at is null
108
+ )))
109
+ order by source.parked_at, source.id limit ${batch}
110
+ `.execute(tx);
111
+ return rows;
112
+ });
113
+ }
@@ -1,11 +1,4 @@
1
- import { type Kysely } from "kysely";
2
- /**
3
- * Why `db.rls: enforce` would filter nothing on this pool, or undefined when it can work (RLS spec
4
- * §10):
5
- * - PostgreSQL never applies a row level security policy to a superuser or a role with BYPASSRLS,
6
- * even on a table that forces RLS. The official compose file's `POSTGRES_USER` is a superuser, so
7
- * such a deployment needs a role of its own before enforcing;
8
- * - the policies ship dark: migration 0182 creates them without `ENABLE` / `FORCE ROW LEVEL
9
- * SECURITY`, which a later migration (phase 5) runs. Until then no org-scoped table applies them.
10
- */
11
- export declare function rlsEnforceProblem(pool: Kysely<any>): Promise<string | undefined>;
1
+ import { type QueryExecutorProvider } from "kysely";
2
+ export declare function matchesOrgScopePredicate(clause: string | null): boolean;
3
+ /** Checks the serving login and migrated schema before the kernel starts in enforce mode. */
4
+ export declare function rlsEnforceProblem(pool: QueryExecutorProvider, expectedOwner: string): Promise<string | undefined>;
@@ -1,33 +1,77 @@
1
1
  import { sql } from "kysely";
2
- /**
3
- * Why `db.rls: enforce` would filter nothing on this pool, or undefined when it can work (RLS spec
4
- * §10):
5
- * - PostgreSQL never applies a row level security policy to a superuser or a role with BYPASSRLS,
6
- * even on a table that forces RLS. The official compose file's `POSTGRES_USER` is a superuser, so
7
- * such a deployment needs a role of its own before enforcing;
8
- * - the policies ship dark: migration 0182 creates them without `ENABLE` / `FORCE ROW LEVEL
9
- * SECURITY`, which a later migration (phase 5) runs. Until then no org-scoped table applies them.
10
- */
11
- // biome-ignore lint/suspicious/noExplicitAny: the pool carries no schema types
12
- export async function rlsEnforceProblem(pool) {
13
- const role = await sql `
14
- select rolsuper as superuser, rolbypassrls as bypass from pg_roles
15
- where rolname = current_user`.execute(pool);
16
- const row = role.rows[0];
17
- if (row?.superuser)
2
+ // PostgreSQL deparses the uncorrelated subqueries with result aliases. Check the
3
+ // policy expression in full so an extra condition or a substituted setting is drift.
4
+ export function matchesOrgScopePredicate(clause) {
5
+ const normalized = clause
6
+ ?.replace(/\s+/g, " ")
7
+ .replace(/\b(?:capybara|pg_catalog)\.(?=\w+\()/g, "");
8
+ return (normalized === "rls_admits(org_id)" ||
9
+ normalized ===
10
+ "rls_admits(org_id, ( SELECT rls_scope_unrestricted() AS rls_scope_unrestricted), " +
11
+ "( SELECT current_setting('capybara.org_id'::text, true) AS current_setting))");
12
+ }
13
+ /** Checks the serving login and migrated schema before the kernel starts in enforce mode. */
14
+ export async function rlsEnforceProblem(pool, expectedOwner) {
15
+ const { rows: [role], } = await sql `
16
+ select bool_or(rolsuper) as superuser, bool_or(rolbypassrls) as bypass
17
+ from pg_catalog.pg_roles where rolname in (current_user, session_user)`.execute(pool);
18
+ if (role?.superuser)
18
19
  return "the database role is a superuser";
19
- if (row?.bypass)
20
+ if (role?.bypass)
20
21
  return "the database role has BYPASSRLS";
21
- const off = await sql `
22
- select c.relname as table from pg_class c
23
- join pg_namespace n on n.oid = c.relnamespace and n.nspname = 'capybara'
24
- where c.relkind = 'r' and not (c.relrowsecurity and c.relforcerowsecurity)
25
- and exists (select 1 from pg_attribute a
26
- where a.attrelid = c.oid and a.attname = 'org_id' and not a.attisdropped)
27
- order by 1`.execute(pool);
28
- if (off.rows.length > 0) {
29
- const first = off.rows[0]?.table;
30
- return `row level security is not enabled and forced on ${off.rows.length} org-scoped table(s) (${first}, …; RLS spec phase 5 enables them)`;
22
+ const { rows: [schema], } = await sql `
23
+ select pg_catalog.pg_get_userbyid(nspowner) as owner,
24
+ (pg_catalog.pg_has_role(current_user, nspowner, 'MEMBER')
25
+ or pg_catalog.pg_has_role(session_user, nspowner, 'MEMBER')) as "canOwn"
26
+ from pg_catalog.pg_namespace where nspname = 'capybara'`.execute(pool);
27
+ if (!schema)
28
+ return "the capybara schema is missing";
29
+ if (schema.canOwn)
30
+ return "the database role owns or is a member of the owner of the capybara schema";
31
+ if (schema.owner !== expectedOwner)
32
+ return `the capybara schema has unexpected owner ${schema.owner}; expected ${expectedOwner}`;
33
+ // The deparser may omit a visible function's schema. Check its catalog dependencies too.
34
+ const { rows: tables } = await sql `
35
+ select c.relname as "table", pg_catalog.pg_get_userbyid(c.relowner) as owner,
36
+ (c.relrowsecurity and c.relforcerowsecurity) as active,
37
+ p.polcmd as command,
38
+ pg_catalog.pg_get_expr(p.polqual, c.oid) as "using",
39
+ pg_catalog.pg_get_expr(p.polwithcheck, c.oid) as "withCheck",
40
+ exists (
41
+ select from pg_catalog.pg_depend d
42
+ where d.classid = 'pg_catalog.pg_policy'::pg_catalog.regclass and d.objid = p.oid
43
+ and d.refclassid = 'pg_catalog.pg_proc'::pg_catalog.regclass
44
+ and not exists (
45
+ select from (values
46
+ (pg_catalog.to_regprocedure('capybara.rls_admits(text)')),
47
+ (pg_catalog.to_regprocedure('capybara.rls_admits(text,boolean,text)')),
48
+ (pg_catalog.to_regprocedure('capybara.rls_scope_unrestricted()'))
49
+ ) as allowed(oid) where allowed.oid = d.refobjid
50
+ )
51
+ ) as "hasOtherFunctions",
52
+ (c.relname = 'conversation_events' and not a.attnotnull) as "nullableEventOrg"
53
+ from pg_catalog.pg_class c
54
+ join pg_catalog.pg_namespace n on n.oid = c.relnamespace and n.nspname = 'capybara'
55
+ join pg_catalog.pg_attribute a on a.attrelid = c.oid and a.attname = 'org_id' and not a.attisdropped
56
+ left join pg_catalog.pg_policy p on p.polrelid = c.oid and p.polname = 'org_scope'
57
+ where c.relkind in ('r', 'p')
58
+ order by c.relname`.execute(pool);
59
+ for (const table of tables) {
60
+ const name = `capybara.${table.table}`;
61
+ if (table.owner !== expectedOwner)
62
+ return `${name} has unexpected owner ${table.owner}; expected ${expectedOwner}`;
63
+ if (table.command === null)
64
+ return `${name} is missing its org_scope policy`;
65
+ if (!table.active)
66
+ return `row level security is not enabled and forced on ${name}`;
67
+ if (table.command !== "*")
68
+ return `${name} org_scope policy must apply to ALL commands`;
69
+ if (table.hasOtherFunctions ||
70
+ !matchesOrgScopePredicate(table.using) ||
71
+ !matchesOrgScopePredicate(table.withCheck))
72
+ return `${name} org_scope policy must use the kernel rls_admits(org_id) predicate for USING and WITH CHECK`;
73
+ if (table.nullableEventOrg)
74
+ return "capybara.conversation_events.org_id must be NOT NULL";
31
75
  }
32
76
  return undefined;
33
77
  }
@@ -1,5 +1,6 @@
1
1
  import { ModuleRef } from "@nestjs/core";
2
2
  import type { Queue } from "bullmq";
3
+ import { ExtensionRegistry } from "../../extensions/registry.js";
3
4
  import type { KernelLogger } from "../../log.js";
4
5
  import { KernelDb } from "../database/kernel-db.js";
5
6
  import { TransactionHost } from "../database/transaction-host.js";
@@ -62,11 +63,12 @@ export declare class OutboxDispatcher {
62
63
  private readonly log;
63
64
  private readonly moduleRef;
64
65
  private readonly dispatchFails;
66
+ private readonly extensions?;
65
67
  /** The owners' queue instances resolved so far (a per-process handle cache). */
66
68
  private readonly queues;
67
69
  /** Fast-path passes running in this process (bounded by OUTBOX_FAST_PATH_CONCURRENCY). */
68
70
  private fastPaths;
69
- constructor(txHost: TransactionHost, db: KernelDb, log: KernelLogger, moduleRef: Pick<ModuleRef, "get">, dispatchFails?: (queue: KernelQueueName) => boolean);
71
+ constructor(txHost: TransactionHost, db: KernelDb, log: KernelLogger, moduleRef: Pick<ModuleRef, "get">, dispatchFails?: (queue: KernelQueueName) => boolean, extensions?: ExtensionRegistry | undefined);
70
72
  /** The queue instance its owner module registered, or undefined when no loaded module has it. */
71
73
  private queue;
72
74
  /** The kernel queues this process can add to, with their handles. */
@@ -94,6 +96,9 @@ export declare class OutboxDispatcher {
94
96
  * bounded by {@link OUTBOX_REDIS_TIMEOUT_MS}.
95
97
  */
96
98
  private claimAndSend;
99
+ private sendExtensionJob;
100
+ /** Uses the regular outbox backoff for a worker that applies an owed effect directly. */
101
+ deferDirect(id: string, reason: string): Promise<void>;
97
102
  /**
98
103
  * Records a failed add on its rows (after the claim transaction, so the attempt is kept whatever
99
104
  * that transaction did): one more attempt, the error, the next attempt by {@link OUTBOX_BACKOFF},