@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
@@ -11,8 +11,13 @@ import { getQueueToken } from "@nestjs/bullmq";
11
11
  import { Inject, Injectable, Optional } from "@nestjs/common";
12
12
  import { ModuleRef } from "@nestjs/core";
13
13
  import { sql } from "kysely";
14
+ import { cancelDeletedOrgEffect } from "../../ctx/durable-cancellation.js";
15
+ import { classifyEffectFailure, ExtensionEffectFailure, effectFailureMessage, } from "../../ctx/durable-failure.js";
16
+ import { EXTENSION_EFFECT_REDRIVE_JOB, EXTENSION_QUEUE_EFFECT_JOB, } from "../../ctx/durable-job.js";
17
+ import { isExtensionEnabled } from "../../extensions/enabled.js";
18
+ import { ExtensionRegistry } from "../../extensions/registry.js";
14
19
  import { KernelDb } from "../database/kernel-db.js";
15
- import { asPlatform } from "../database/org-scope.js";
20
+ import { asPlatform, withOrgScope } from "../database/org-scope.js";
16
21
  import { TransactionHost } from "../database/transaction-host.js";
17
22
  import { Transactional } from "../database/transactional.decorator.js";
18
23
  import { QUEUE_JOB_DEFAULTS } from "../queue/queue.module.js";
@@ -97,16 +102,18 @@ let OutboxDispatcher = class OutboxDispatcher {
97
102
  log;
98
103
  moduleRef;
99
104
  dispatchFails;
105
+ extensions;
100
106
  /** The owners' queue instances resolved so far (a per-process handle cache). */
101
107
  queues = new Map();
102
108
  /** Fast-path passes running in this process (bounded by OUTBOX_FAST_PATH_CONCURRENCY). */
103
109
  fastPaths = 0;
104
- constructor(txHost, db, log, moduleRef, dispatchFails = () => false) {
110
+ constructor(txHost, db, log, moduleRef, dispatchFails = () => false, extensions) {
105
111
  this.txHost = txHost;
106
112
  this.db = db;
107
113
  this.log = log;
108
114
  this.moduleRef = moduleRef;
109
115
  this.dispatchFails = dispatchFails;
116
+ this.extensions = extensions;
110
117
  }
111
118
  /** The queue instance its owner module registered, or undefined when no loaded module has it. */
112
119
  queue(name) {
@@ -201,8 +208,9 @@ let OutboxDispatcher = class OutboxDispatcher {
201
208
  // rows of a queue this process cannot reach are left for a process that can
202
209
  let query = this.db
203
210
  .selectFrom("outbox")
204
- .select(["id", "queue", "job_name", "job_id", "data", "run_at"])
211
+ .select(["id", "queue", "job_name", "job_id", "data", "run_at", "org_id"])
205
212
  .where("dead_at", "is", null)
213
+ .where("job_name", "!=", EXTENSION_EFFECT_REDRIVE_JOB)
206
214
  .where("queue", "in", [...queues.keys()]);
207
215
  query =
208
216
  "ids" in claim
@@ -213,6 +221,8 @@ let OutboxDispatcher = class OutboxDispatcher {
213
221
  return { sent: 0, failed: [] };
214
222
  const byQueue = new Map();
215
223
  for (const row of rows) {
224
+ if (row.job_name === EXTENSION_QUEUE_EFFECT_JOB)
225
+ continue;
216
226
  const group = byQueue.get(row.queue);
217
227
  if (group)
218
228
  group.push(row);
@@ -260,11 +270,59 @@ let OutboxDispatcher = class OutboxDispatcher {
260
270
  failed.push({ ids, error: firstError.slice(0, MAX_ERROR_LENGTH) });
261
271
  }
262
272
  }
273
+ for (const row of rows) {
274
+ if (row.job_name !== EXTENSION_QUEUE_EFFECT_JOB)
275
+ continue;
276
+ try {
277
+ if (this.dispatchFails(row.queue)) {
278
+ throw new Error("outbox dispatch failure (test seam)");
279
+ }
280
+ const left = deadline - Date.now();
281
+ if (left <= 0)
282
+ throw new Error("No time left in the outbox dispatch pass");
283
+ await withTimeout(this.sendExtensionJob(row), left, "add to extension queue");
284
+ delivered.push(row.id);
285
+ }
286
+ catch (error) {
287
+ failed.push({ ids: [row.id], error: effectFailureMessage(classifyEffectFailure(error)) });
288
+ }
289
+ }
263
290
  if (delivered.length > 0)
264
291
  await this.db.deleteFrom("outbox").where("id", "in", delivered).execute();
265
292
  return { sent: delivered.length, failed };
266
293
  });
267
294
  }
295
+ async sendExtensionJob(row) {
296
+ const data = row.data;
297
+ if (!row.org_id || data.orgId !== row.org_id) {
298
+ throw new ExtensionEffectFailure("scope_mismatch", "The queue effect scope differs from the outbox row");
299
+ }
300
+ const org = await this.db
301
+ .selectFrom("orgs")
302
+ .select("id")
303
+ .where("id", "=", row.org_id)
304
+ .where("deleted_at", "is", null)
305
+ .executeTakeFirst();
306
+ if (!org) {
307
+ await cancelDeletedOrgEffect(this.db.db, data.plugin, data.jobId);
308
+ return;
309
+ }
310
+ if (!(await isExtensionEnabled(this.db.db, org.id, data.plugin))) {
311
+ throw new ExtensionEffectFailure("org_disabled", "The extension is disabled in this organization");
312
+ }
313
+ const extension = this.extensions?.current(data.plugin);
314
+ if (!extension)
315
+ throw new ExtensionEffectFailure("extension_unavailable", "The extension is unavailable");
316
+ if (!extension.hasEffectQueue(data.queue)) {
317
+ throw new ExtensionEffectFailure("queue_unavailable", "The extension effect queue is not registered");
318
+ }
319
+ const delay = row.run_at ? Math.max(0, row.run_at.getTime() - Date.now()) : undefined;
320
+ await withOrgScope(org.id, () => extension.enqueueEffect(data.queue, data.data, data.jobId, delay));
321
+ }
322
+ /** Uses the regular outbox backoff for a worker that applies an owed effect directly. */
323
+ async deferDirect(id, reason) {
324
+ await this.recordFailure({ ids: [id], error: reason });
325
+ }
268
326
  /**
269
327
  * Records a failed add on its rows (after the claim transaction, so the attempt is kept whatever
270
328
  * that transaction did): one more attempt, the error, the next attempt by {@link OUTBOX_BACKOFF},
@@ -316,6 +374,8 @@ OutboxDispatcher = __decorate([
316
374
  __param(2, Inject(KERNEL_LOGGER)),
317
375
  __param(3, Inject(ModuleRef)),
318
376
  __param(4, Optional()),
319
- __param(4, Inject(OUTBOX_DISPATCH_FAILS))
377
+ __param(4, Inject(OUTBOX_DISPATCH_FAILS)),
378
+ __param(5, Optional()),
379
+ __param(5, Inject(ExtensionRegistry))
320
380
  ], OutboxDispatcher);
321
381
  export { OutboxDispatcher };
@@ -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 { Global, Module } from "@nestjs/common";
8
+ import { ExtensionRegistryModule } from "../../extensions/registry.js";
8
9
  import { OutboxDispatcher } from "./outbox.dispatcher.js";
9
10
  import { OUTBOX_FAST_PATH, OutboxService } from "./outbox.service.js";
10
11
  /**
@@ -35,6 +36,7 @@ let OutboxModule = class OutboxModule {
35
36
  OutboxModule = __decorate([
36
37
  Global(),
37
38
  Module({
39
+ imports: [ExtensionRegistryModule],
38
40
  providers: [
39
41
  OutboxService,
40
42
  OutboxDispatcher,
@@ -19,6 +19,18 @@ export interface OutboxJobSpec {
19
19
  * name without one does not type-check as an `OutboxJobName` (`add` does not check it at runtime).
20
20
  */
21
21
  export declare const OUTBOX_JOBS: {
22
+ readonly "extension-queue-effect": {
23
+ readonly queue: "cap-kernel-maintenance";
24
+ readonly processedIn: "packages/kernel/src/infra/outbox/outbox.dispatcher.ts";
25
+ readonly idempotent: "Adds a plugin queue job with a deterministic destination ID. Plugin job handlers are idempotent.";
26
+ readonly opts: {};
27
+ };
28
+ readonly "extension-effect-redrive": {
29
+ readonly queue: "cap-kernel-maintenance";
30
+ readonly processedIn: "packages/kernel/src/ctx/durable-relay.ts";
31
+ readonly idempotent: "Verifies the original signed effect and checks its durable receipt before applying it.";
32
+ readonly opts: {};
33
+ };
22
34
  readonly "data-erasure": {
23
35
  readonly queue: "cap-kernel-maintenance";
24
36
  readonly idempotent: "Each generation claims the durable request under a row lock. Stale and completed deliveries do nothing.";
@@ -21,6 +21,18 @@ const SCOPE_JOB_OPTS = {
21
21
  * name without one does not type-check as an `OutboxJobName` (`add` does not check it at runtime).
22
22
  */
23
23
  export const OUTBOX_JOBS = {
24
+ "extension-queue-effect": {
25
+ queue: "cap-kernel-maintenance",
26
+ processedIn: "packages/kernel/src/infra/outbox/outbox.dispatcher.ts",
27
+ idempotent: "Adds a plugin queue job with a deterministic destination ID. Plugin job handlers are idempotent.",
28
+ opts: {},
29
+ },
30
+ "extension-effect-redrive": {
31
+ queue: "cap-kernel-maintenance",
32
+ processedIn: "packages/kernel/src/ctx/durable-relay.ts",
33
+ idempotent: "Verifies the original signed effect and checks its durable receipt before applying it.",
34
+ opts: {},
35
+ },
24
36
  "data-erasure": {
25
37
  queue: "cap-kernel-maintenance",
26
38
  idempotent: "Each generation claims the durable request under a row lock. Stale and completed deliveries do nothing.",
package/dist/kernel.d.ts CHANGED
@@ -10,6 +10,8 @@ import type { PendingExtension } from "./extensions/approvals.js";
10
10
  export declare const KERNEL_MIGRATIONS_DIR: string;
11
11
  /** The kernel's PG schema. */
12
12
  export declare const KERNEL_SCHEMA = "capybara";
13
+ /** Static names of config-declared extensions, for deployment and fixture provisioning. */
14
+ export declare function declaredExtensionNames(specifiers: string[], resolveFrom?: string): Promise<Set<string>>;
13
15
  /** Only a login with migration privileges can initialize the kernel schema at startup. */
14
16
  export declare function prepareKernelDatabase(db: KernelConfig["db"], opts?: {
15
17
  pool?: QueryExecutorProvider;
package/dist/kernel.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { fileURLToPath } from "node:url";
2
- import { extensionDbIdentity } from "./db/extension-db.js";
2
+ import { extensionDbIdentity, validateExtensionCredentials } from "./db/extension-db.js";
3
3
  import { canMigrateKernel, migrate, verifyMigrations } from "./db/migrator.js";
4
4
  import { createDb } from "./db/pool.js";
5
5
  import { ExtensionHost } from "./extensions/host.js";
@@ -12,11 +12,18 @@ import { ExtensionHost } from "./extensions/host.js";
12
12
  export const KERNEL_MIGRATIONS_DIR = fileURLToPath(new URL("../src/migrations/", import.meta.url));
13
13
  /** The kernel's PG schema. */
14
14
  export const KERNEL_SCHEMA = "capybara";
15
+ /** Static names of config-declared extensions, for deployment and fixture provisioning. */
16
+ export function declaredExtensionNames(specifiers, resolveFrom) {
17
+ return ExtensionHost.declaredNames(specifiers, resolveFrom === undefined ? {} : { resolveFrom });
18
+ }
15
19
  const coreMigrations = { schema: KERNEL_SCHEMA, dir: KERNEL_MIGRATIONS_DIR };
16
20
  /** Only a login with migration privileges can initialize the kernel schema at startup. */
17
21
  export async function prepareKernelDatabase(db, opts = {}) {
18
22
  if (db.migrationUrl !== undefined)
19
23
  throw new Error("db.migrationUrl may only be set for capybara migrate");
24
+ if (db.extensionProvisioningUrl !== undefined)
25
+ throw new Error("db.extensionProvisioningUrl may only be set for capybara migrate");
26
+ validateExtensionCredentials(db);
20
27
  const prepare = async (pool) => {
21
28
  if (await canMigrateKernel(pool)) {
22
29
  await migrate(db.url, coreMigrations, {
@@ -45,6 +52,9 @@ export async function prepareKernelDatabase(db, opts = {}) {
45
52
  */
46
53
  export async function migrateAll(config, opts = {}) {
47
54
  const connectTimeoutMs = config.db.connectTimeoutMs;
55
+ if (config.db.extensionProvisioningUrl !== undefined && config.db.extensionsUrl === undefined)
56
+ throw new Error("db.extensionProvisioningUrl requires db.extensionsUrl");
57
+ validateExtensionCredentials(config.db);
48
58
  const kernel = await migrate(config.db.migrationUrl ?? config.db.url, coreMigrations, {
49
59
  connectTimeoutMs,
50
60
  });
@@ -52,6 +62,7 @@ export async function migrateAll(config, opts = {}) {
52
62
  dbUrl: config.db.url,
53
63
  ...(config.db.extensionsUrl !== undefined && {
54
64
  extensionIdentity: extensionDbIdentity(config.db),
65
+ extensionProvisioning: config.db,
55
66
  }),
56
67
  connectTimeoutMs,
57
68
  autoApprove: config.extensionPermissions.autoApprove,
@@ -226,10 +226,9 @@ let KernelLifecycle = class KernelLifecycle {
226
226
  await sql `select 1`.execute(this.pool);
227
227
  this.checkpoint();
228
228
  if (cfg().db.rls === "enforce") {
229
- // never fails the start: enforcement is a backstop, and the operator decides
230
- const problem = await rlsEnforceProblem(this.pool);
229
+ const problem = await rlsEnforceProblem(this.pool, cfg().db.rlsOwnerRole);
231
230
  if (problem !== undefined) {
232
- this.log.error(`db.rls is enforce, but ${problem}: PostgreSQL filters nothing by the org scope there`);
231
+ throw new Error(`Cannot start with db.rls=enforce: ${problem}. Prepare separate database logins and run capybara migrate before enabling enforcement.`);
233
232
  }
234
233
  }
235
234
  // In flight for the stop: aborted when the shutdown begins, which then waits for its session to end
@@ -13,6 +13,7 @@ import { sql } from "kysely";
13
13
  import { OwnedItems } from "../catalog/owned-items.js";
14
14
  import { cancelPendingRequests } from "../catalog/request-rules.js";
15
15
  import { PluginScopeSync } from "../catalog/scope-sync.js";
16
+ import { EXTENSION_QUEUE_EFFECT_JOB } from "../ctx/durable-job.js";
16
17
  import { ErasureRequests } from "../erasure/requests.js";
17
18
  import { ApiError } from "../errors.js";
18
19
  import { EvalBudget } from "../evals/budget.js";
@@ -270,6 +271,21 @@ let OrgsService = class OrgsService {
270
271
  .set({ deleted_at: sql `now()` })
271
272
  .where("id", "=", orgId)
272
273
  .execute();
274
+ await this.db
275
+ .insertInto("extension_effect_cancellations")
276
+ .columns(["id", "plugin", "reason"])
277
+ .expression((eb) => eb
278
+ .selectFrom("outbox")
279
+ .select([
280
+ "job_id as id",
281
+ sql `data->>'plugin'`.as("plugin"),
282
+ sql `'organization_deleted'`.as("reason"),
283
+ ])
284
+ .where("org_id", "=", orgId)
285
+ .where("job_name", "=", EXTENSION_QUEUE_EFFECT_JOB)
286
+ .where("dead_at", "is", null))
287
+ .onConflict((conflict) => conflict.doNothing())
288
+ .execute();
273
289
  // the org's owed jobs go with it; dead letters stay for the overview, and the deletion's own
274
290
  // cleanup work carries no org_id (transactional outbox spec §9). Usage reports stay owed: the
275
291
  // usage happened, and billing plugins are still told about a deleted org's usage
@@ -23,6 +23,7 @@ import { AttachmentCleanupJob } from "../conversations/attachments.service.js";
23
23
  import { EventLogModule } from "../conversations/event-log.js";
24
24
  import { PromptSuggestionsModule } from "../conversations/prompt-suggestions.js";
25
25
  import { TitlesModule } from "../conversations/titles.js";
26
+ import { ExtensionEffectRelay } from "../ctx/durable-relay.js";
26
27
  import { ConversationNoticeSweepJob, ConversationNoticesModule, } from "../device-access/conversation-notice-delivery.js";
27
28
  import { HostServiceStopSweepJob } from "../device-access/host-service-stop-sweep.js";
28
29
  import { DeviceServiceEventWorkersModule } from "../device-access/service-events.js";
@@ -134,6 +135,7 @@ let WorkerModule = WorkerModule_1 = class WorkerModule {
134
135
  ConversationNoticesModule,
135
136
  ],
136
137
  providers: [
138
+ ExtensionEffectRelay,
137
139
  ...(operationalMetricsEnabled() ? [OperationalMetricsSampler] : []),
138
140
  // the one repair of a run nobody runs (transactional outbox spec §8.3)
139
141
  RunOrphanCheck,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/kernel",
3
- "version": "0.1.0-rc.133",
3
+ "version": "0.1.0-rc.135",
4
4
  "description": "Capybara kernel: config, database, plugin host and HTTP API of the Capybara agent platform",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -70,7 +70,7 @@
70
70
  "yaml": "^2.9.1",
71
71
  "yauzl": "3.4.0",
72
72
  "zod": "^4.6.7",
73
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.98"
73
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.99"
74
74
  },
75
75
  "devDependencies": {
76
76
  "@langchain/langgraph-checkpoint-validation": "^1.2.0",
@@ -82,7 +82,7 @@
82
82
  "@types/yauzl": "3.4.0",
83
83
  "pg-cursor": "^2.22.1",
84
84
  "ws": "^8.22.0",
85
- "@capybara-hq/testing": "0.1.0-rc.54"
85
+ "@capybara-hq/testing": "0.1.0-rc.55"
86
86
  },
87
87
  "scripts": {
88
88
  "build": "tsc -b"
@@ -0,0 +1,25 @@
1
+ CREATE TABLE IF NOT EXISTS extension_effect_receipts (
2
+ org_id text NOT NULL REFERENCES orgs (id) ON DELETE CASCADE,
3
+ plugin text NOT NULL,
4
+ kind text NOT NULL,
5
+ effect_key text NOT NULL,
6
+ payload_hash text NOT NULL,
7
+ result jsonb NOT NULL DEFAULT 'null'::jsonb,
8
+ PRIMARY KEY (org_id, plugin, kind, effect_key)
9
+ );
10
+
11
+ DROP POLICY IF EXISTS org_scope ON extension_effect_receipts;
12
+ CREATE POLICY org_scope ON extension_effect_receipts
13
+ USING (rls_admits(org_id)) WITH CHECK (rls_admits(org_id));
14
+
15
+ -- Cancellation survives a hard delete of the organization. The digest contains no effect data.
16
+ CREATE TABLE IF NOT EXISTS extension_effect_cancellations (
17
+ id text PRIMARY KEY,
18
+ plugin text NOT NULL,
19
+ reason text NOT NULL,
20
+ cancelled_at timestamptz NOT NULL DEFAULT now()
21
+ );
22
+
23
+ CREATE INDEX IF NOT EXISTS outbox_extension_effect_reference
24
+ ON outbox ((data->>'plugin'), (data->>'rowId'))
25
+ WHERE job_name = 'extension-effect-redrive';
@@ -0,0 +1,30 @@
1
+ -- Phase 5 activates the existing kernel policies. Bound the wait for table locks while serving.
2
+ SET LOCAL lock_timeout = '2s';
3
+
4
+ -- capybara:allow-destructive catalog-driven verification and activation of existing kernel policies
5
+ DO $$
6
+ DECLARE
7
+ target record;
8
+ BEGIN
9
+ FOR target IN
10
+ SELECT c.relname, EXISTS (
11
+ SELECT FROM pg_catalog.pg_policy p
12
+ WHERE p.polrelid = c.oid AND p.polname = 'org_scope'
13
+ ) AS has_policy
14
+ FROM pg_catalog.pg_class c
15
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
16
+ JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid
17
+ WHERE n.nspname = 'capybara' AND c.relkind IN ('r', 'p')
18
+ AND a.attname = 'org_id' AND NOT a.attisdropped
19
+ ORDER BY has_policy, c.relname
20
+ LOOP
21
+ IF NOT target.has_policy THEN
22
+ RAISE EXCEPTION 'Missing org_scope policy on capybara.%', target.relname;
23
+ END IF;
24
+ EXECUTE format(
25
+ 'ALTER TABLE ONLY capybara.%I ENABLE ROW LEVEL SECURITY, FORCE ROW LEVEL SECURITY',
26
+ target.relname
27
+ );
28
+ END LOOP;
29
+ END
30
+ $$;