@capybara-hq/kernel 0.1.0-rc.133 → 0.1.0-rc.134
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/automations/events/trigger-events.service.d.ts +13 -1
- package/dist/automations/events/trigger-events.service.js +27 -14
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/config/schema.d.ts +1 -0
- package/dist/config/schema.js +7 -0
- package/dist/ctx/create-ctx.d.ts +4 -0
- package/dist/ctx/create-ctx.js +74 -27
- package/dist/ctx/durable-cancellation.d.ts +3 -0
- package/dist/ctx/durable-cancellation.js +8 -0
- package/dist/ctx/durable-effects.service.d.ts +81 -0
- package/dist/ctx/durable-effects.service.js +316 -0
- package/dist/ctx/durable-envelope.d.ts +24 -0
- package/dist/ctx/durable-envelope.js +80 -0
- package/dist/ctx/durable-failure.d.ts +7 -0
- package/dist/ctx/durable-failure.js +32 -0
- package/dist/ctx/durable-job.d.ts +9 -0
- package/dist/ctx/durable-job.js +2 -0
- package/dist/ctx/durable-keys.d.ts +27 -0
- package/dist/ctx/durable-keys.js +138 -0
- package/dist/ctx/durable-relay.d.ts +29 -0
- package/dist/ctx/durable-relay.js +250 -0
- package/dist/ctx/queue.d.ts +2 -0
- package/dist/ctx/queue.js +22 -15
- package/dist/db/extension-db.js +2 -0
- package/dist/db/extension-handoff-schema.d.ts +6 -0
- package/dist/db/extension-handoff-schema.js +72 -0
- package/dist/db/extension-schema-transfer.d.ts +1 -1
- package/dist/db/extension-schema-transfer.js +18 -6
- package/dist/db/kernel-schema.d.ts +16 -0
- package/dist/erasure/org-catalog.js +2 -2
- package/dist/erasure/org-rules.js +1 -0
- package/dist/extensions/extensions.module.js +10 -0
- package/dist/extensions/host.d.ts +5 -0
- package/dist/extensions/host.js +33 -20
- package/dist/extensions/instance.d.ts +2 -0
- package/dist/extensions/instance.js +6 -0
- package/dist/extensions/sources.d.ts +1 -0
- package/dist/extensions/sources.js +9 -0
- package/dist/inbox/inbox-items.service.d.ts +5 -0
- package/dist/inbox/inbox-items.service.js +57 -33
- package/dist/infra/database/extension-effect-key-lock.d.ts +10 -0
- package/dist/infra/database/extension-effect-key-lock.js +69 -0
- package/dist/infra/database/extension-handoff.d.ts +27 -0
- package/dist/infra/database/extension-handoff.js +113 -0
- package/dist/infra/outbox/outbox.dispatcher.d.ts +6 -1
- package/dist/infra/outbox/outbox.dispatcher.js +64 -4
- package/dist/infra/outbox/outbox.module.js +2 -0
- package/dist/infra/outbox/registry.d.ts +12 -0
- package/dist/infra/outbox/registry.js +12 -0
- package/dist/kernel.js +1 -0
- package/dist/orgs/orgs.service.js +16 -0
- package/dist/roles/worker.module.js +2 -0
- package/package.json +2 -2
- package/src/migrations/0225_extension_effect_receipts.sql +25 -0
package/dist/extensions/host.js
CHANGED
|
@@ -17,8 +17,10 @@ import { ModuleRef } from "@nestjs/core";
|
|
|
17
17
|
import { TRIGGER_EVENTS_BACKEND } from "../automations/events/token.js";
|
|
18
18
|
import { changedPaths, configFields, getPath, secretValues, unreachableSecrets, } from "../config/fields.js";
|
|
19
19
|
import { pluginSchemaName, queryEnabledPlugins, } from "../ctx/create-ctx.js";
|
|
20
|
+
import { ExtensionEffects } from "../ctx/durable-effects.service.js";
|
|
20
21
|
import { EXTENSION_NET_SEAMS } from "../ctx/net.js";
|
|
21
22
|
import { ConfiguredExtensionDbIdentity, extensionDbIdentity, extensionDbPool, } from "../db/extension-db.js";
|
|
23
|
+
import { ensureLocalExtensionHandoff } from "../db/extension-handoff-schema.js";
|
|
22
24
|
import { transferKnownExtensionSchemas } from "../db/extension-schema-transfer.js";
|
|
23
25
|
import { kernelDb } from "../db/kernel-schema.js";
|
|
24
26
|
import { migrate } from "../db/migrator.js";
|
|
@@ -263,7 +265,7 @@ let ExtensionHost = class ExtensionHost {
|
|
|
263
265
|
assertSecretsReachable(manifest);
|
|
264
266
|
const identity = opts.extensionIdentity ?? extensionDbIdentity({ url: opts.dbUrl });
|
|
265
267
|
if (opts.extensionIdentity) {
|
|
266
|
-
await transferKnownExtensionSchemas(opts.dbUrl, identity, dirs.keys(), opts.connectTimeoutMs);
|
|
268
|
+
await transferKnownExtensionSchemas(opts.dbUrl, identity, dirs.keys(), opts.connectTimeoutMs, opts.handoffRuntimeLogin);
|
|
267
269
|
}
|
|
268
270
|
let toMigrate = ordered;
|
|
269
271
|
if (!opts.autoApprove && ordered.length > 0) {
|
|
@@ -507,6 +509,14 @@ let ExtensionHost = class ExtensionHost {
|
|
|
507
509
|
return undefined;
|
|
508
510
|
}
|
|
509
511
|
},
|
|
512
|
+
durableEffects: () => {
|
|
513
|
+
try {
|
|
514
|
+
return modules?.get(ExtensionEffects, { strict: false });
|
|
515
|
+
}
|
|
516
|
+
catch {
|
|
517
|
+
return undefined;
|
|
518
|
+
}
|
|
519
|
+
},
|
|
510
520
|
triggers: () => {
|
|
511
521
|
try {
|
|
512
522
|
return modules?.get(TRIGGER_EVENTS_BACKEND, { strict: false });
|
|
@@ -1806,26 +1816,29 @@ let ExtensionHost = class ExtensionHost {
|
|
|
1806
1816
|
let ctx;
|
|
1807
1817
|
const name = spec.manifest.name;
|
|
1808
1818
|
const identity = this.dbIdentity.resolve(name);
|
|
1809
|
-
const extensionDb = identity.
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1819
|
+
const extensionDb = extensionDbPool(identity, name, this.config.get().db, (err) => this.log.warn("extension database pool error", { plugin: name, err }));
|
|
1820
|
+
const p = (async () => {
|
|
1821
|
+
if (!identity.separate) {
|
|
1822
|
+
await ensureLocalExtensionHandoff(this.deps.db, this.deps.dbUrl, pluginSchemaName(name), this.deps.connectTimeoutMs);
|
|
1823
|
+
}
|
|
1824
|
+
return setupInstance(this.loadDeps, spec.manifest, {
|
|
1825
|
+
entryUrl: spec.entryUrl,
|
|
1826
|
+
source: spec.source,
|
|
1827
|
+
sha256: spec.sha256,
|
|
1828
|
+
config: spec.config,
|
|
1829
|
+
configHash: spec.configHash,
|
|
1830
|
+
permissions: spec.permissions,
|
|
1831
|
+
extensionDb,
|
|
1832
|
+
onCtx: (c) => {
|
|
1833
|
+
if (c)
|
|
1834
|
+
ctx = c;
|
|
1835
|
+
if (c || this.settingUp === ctx)
|
|
1836
|
+
this.settingUp = c;
|
|
1837
|
+
},
|
|
1838
|
+
});
|
|
1839
|
+
})().catch(async (error) => {
|
|
1827
1840
|
if (!ctx)
|
|
1828
|
-
await extensionDb
|
|
1841
|
+
await extensionDb.destroy();
|
|
1829
1842
|
throw error;
|
|
1830
1843
|
});
|
|
1831
1844
|
if (timeoutMs === undefined)
|
|
@@ -65,6 +65,8 @@ export declare class ExtensionInstance {
|
|
|
65
65
|
/** {@link hurry}:进行中的 dispose 不再等排空时限。 */
|
|
66
66
|
private readonly hurried;
|
|
67
67
|
constructor(init: ExtensionInstanceInit);
|
|
68
|
+
hasEffectQueue(name: string): boolean;
|
|
69
|
+
enqueueEffect(queue: string, data: unknown, jobId: string, delayMs?: number): Promise<void>;
|
|
68
70
|
/** 此刻的部署配置(hot 改动后是新值)。 */
|
|
69
71
|
get config(): unknown;
|
|
70
72
|
/** 部署配置摘要(见 `deploymentConfigHash`;hot 改动后随之更新)。 */
|
|
@@ -95,6 +95,12 @@ export class ExtensionInstance {
|
|
|
95
95
|
this.log = init.log;
|
|
96
96
|
this.inflight = new InflightTracker(this.name);
|
|
97
97
|
}
|
|
98
|
+
hasEffectQueue(name) {
|
|
99
|
+
return this.ctx.hasEffectQueue(name);
|
|
100
|
+
}
|
|
101
|
+
async enqueueEffect(queue, data, jobId, delayMs) {
|
|
102
|
+
await this.ctx.dispatchEffectQueue(queue, data, jobId, delayMs);
|
|
103
|
+
}
|
|
98
104
|
/** 此刻的部署配置(hot 改动后是新值)。 */
|
|
99
105
|
get config() {
|
|
100
106
|
return this.live.value;
|
|
@@ -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
|
-
|
|
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
|
-
|
|
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);
|
|
@@ -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,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},
|
|
@@ -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 };
|