@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.
- package/bootstrap.json +1 -1
- 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 +8 -0
- package/dist/config/schema.js +67 -2
- 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.d.ts +8 -3
- package/dist/db/extension-db.js +109 -7
- package/dist/db/extension-handoff-schema.d.ts +6 -0
- package/dist/db/extension-handoff-schema.js +72 -0
- package/dist/db/extension-role-provision.d.ts +9 -0
- package/dist/db/extension-role-provision.js +89 -0
- package/dist/db/extension-schema-transfer.d.ts +2 -1
- package/dist/db/extension-schema-transfer.js +114 -18
- package/dist/db/kernel-schema.d.ts +16 -0
- package/dist/db/migrator.d.ts +2 -0
- package/dist/db/migrator.js +4 -3
- package/dist/erasure/org-catalog.js +2 -2
- package/dist/erasure/org-rules.js +1 -0
- package/dist/extensions/admin-ops.js +17 -1
- package/dist/extensions/extensions.module.js +10 -0
- package/dist/extensions/host.d.ts +6 -0
- package/dist/extensions/host.js +35 -21
- package/dist/extensions/instance.d.ts +2 -0
- package/dist/extensions/instance.js +6 -0
- package/dist/extensions/migrate-lock.js +1 -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/index.d.ts +3 -1
- package/dist/index.js +3 -1
- 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/database/rls-role.d.ts +4 -11
- package/dist/infra/database/rls-role.js +71 -27
- 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.d.ts +2 -0
- package/dist/kernel.js +12 -1
- package/dist/lifecycle/kernel-lifecycle.js +2 -3
- package/dist/orgs/orgs.service.js +16 -0
- package/dist/roles/worker.module.js +2 -0
- package/package.json +3 -3
- package/src/migrations/0225_extension_effect_receipts.sql +25 -0
- package/src/migrations/0226_enable_kernel_rls.sql +30 -0
package/bootstrap.json
CHANGED
|
@@ -16,6 +16,16 @@ export declare const TRIGGER_URL_MAX_BYTES = 2048;
|
|
|
16
16
|
export declare const TRIGGER_FACT_LIST_MAX_ITEMS = 64;
|
|
17
17
|
/** How long a cause handle (`ctx.triggers.causeOf`) is accepted. */
|
|
18
18
|
export declare const TRIGGER_CAUSE_HANDLE_TTL_MS: number;
|
|
19
|
+
/** Who caused an event, as the kernel verified it. */
|
|
20
|
+
export interface VerifiedCause {
|
|
21
|
+
runId: string | null;
|
|
22
|
+
accountId: string | null;
|
|
23
|
+
depth: number;
|
|
24
|
+
causeWindow?: {
|
|
25
|
+
createdAt: number;
|
|
26
|
+
expiresAt: number;
|
|
27
|
+
};
|
|
28
|
+
}
|
|
19
29
|
/**
|
|
20
30
|
* Stores the events extensions emit (`ctx.triggers.emit`, collaboration spec §4.2) and owes their
|
|
21
31
|
* dispatch. The emitting extension, the event types it may emit (its approved manifest's
|
|
@@ -45,10 +55,12 @@ export declare class TriggerEventsService {
|
|
|
45
55
|
* Throws `TriggerError`: `type_not_declared`, `invalid_event` (a missing or malformed field, a
|
|
46
56
|
* forged or foreign cause), `org_disabled` (the plugin is not enabled in the org).
|
|
47
57
|
*/
|
|
48
|
-
emit(plugin: string, declared: readonly string[], e: TriggerEvent): Promise<{
|
|
58
|
+
emit(plugin: string, declared: readonly string[], e: TriggerEvent, preparedCause?: VerifiedCause): Promise<{
|
|
49
59
|
eventId: string;
|
|
50
60
|
duplicate: boolean;
|
|
51
61
|
}>;
|
|
62
|
+
/** Validates an intent before the extension records it in its own transaction. */
|
|
63
|
+
prepare(plugin: string, declared: readonly string[], e: TriggerEvent, preparedCause?: VerifiedCause): Promise<VerifiedCause>;
|
|
52
64
|
/**
|
|
53
65
|
* A handle for the cause `call` (`ctx.triggers.causeOf`, collaboration spec §4.2) that `plugin`
|
|
54
66
|
* may pass later as `cause: { handle }`: `call` is verified as `emit` verifies `cause.call` (a
|
|
@@ -138,19 +138,9 @@ let TriggerEventsService = class TriggerEventsService {
|
|
|
138
138
|
* Throws `TriggerError`: `type_not_declared`, `invalid_event` (a missing or malformed field, a
|
|
139
139
|
* forged or foreign cause), `org_disabled` (the plugin is not enabled in the org).
|
|
140
140
|
*/
|
|
141
|
-
async emit(plugin, declared, e) {
|
|
142
|
-
|
|
143
|
-
throw invalid("the event must be an object");
|
|
144
|
-
const errs = validateTriggerEvent(e, declared);
|
|
145
|
-
if (errs.includes("type_not_declared"))
|
|
146
|
-
throw new TriggerError("type_not_declared", `event type "${e.type}" is not declared in permissions.triggers.emit of ${plugin}`);
|
|
147
|
-
if (errs.length > 0)
|
|
148
|
-
throw invalid(`invalid event: ${errs.join(", ")}`);
|
|
149
|
-
checkShape(e);
|
|
141
|
+
async emit(plugin, declared, e, preparedCause) {
|
|
142
|
+
const cause = await this.prepare(plugin, declared, e, preparedCause);
|
|
150
143
|
const db = this.kdb.db;
|
|
151
|
-
if (!(await isExtensionEnabled(db, e.orgId, plugin)))
|
|
152
|
-
throw new TriggerError("org_disabled", `${plugin} is not enabled in org ${e.orgId}`);
|
|
153
|
-
const cause = await this.verifyCause(plugin, e);
|
|
154
144
|
const subject = {
|
|
155
145
|
kind: e.subject.kind,
|
|
156
146
|
id: e.subject.id,
|
|
@@ -199,6 +189,21 @@ let TriggerEventsService = class TriggerEventsService {
|
|
|
199
189
|
});
|
|
200
190
|
return { eventId: id, duplicate: false };
|
|
201
191
|
}
|
|
192
|
+
/** Validates an intent before the extension records it in its own transaction. */
|
|
193
|
+
async prepare(plugin, declared, e, preparedCause) {
|
|
194
|
+
if (!isPlainObject(e))
|
|
195
|
+
throw invalid("the event must be an object");
|
|
196
|
+
const errs = validateTriggerEvent(e, declared);
|
|
197
|
+
if (errs.includes("type_not_declared"))
|
|
198
|
+
throw new TriggerError("type_not_declared", `event type "${e.type}" is not declared in permissions.triggers.emit of ${plugin}`);
|
|
199
|
+
if (errs.length > 0)
|
|
200
|
+
throw invalid(`invalid event: ${errs.join(", ")}`);
|
|
201
|
+
checkShape(e);
|
|
202
|
+
const db = this.kdb.db;
|
|
203
|
+
if (!(await isExtensionEnabled(db, e.orgId, plugin)))
|
|
204
|
+
throw new TriggerError("org_disabled", `${plugin} is not enabled in org ${e.orgId}`);
|
|
205
|
+
return preparedCause ?? this.verifyCause(plugin, e);
|
|
206
|
+
}
|
|
202
207
|
/**
|
|
203
208
|
* A handle for the cause `call` (`ctx.triggers.causeOf`, collaboration spec §4.2) that `plugin`
|
|
204
209
|
* may pass later as `cause: { handle }`: `call` is verified as `emit` verifies `cause.call` (a
|
|
@@ -253,7 +258,7 @@ let TriggerEventsService = class TriggerEventsService {
|
|
|
253
258
|
const row = nonEmpty(cause.handle)
|
|
254
259
|
? await db
|
|
255
260
|
.selectFrom("trigger_cause_handles")
|
|
256
|
-
.select(["run_id", "depth", "cause_account_id"])
|
|
261
|
+
.select(["run_id", "depth", "cause_account_id", "created_at", "expires_at"])
|
|
257
262
|
.where("id", "=", cause.handle)
|
|
258
263
|
.where("org_id", "=", e.orgId)
|
|
259
264
|
.where("plugin", "=", plugin)
|
|
@@ -272,7 +277,15 @@ let TriggerEventsService = class TriggerEventsService {
|
|
|
272
277
|
.executeTakeFirst();
|
|
273
278
|
if (run === undefined)
|
|
274
279
|
throw invalid("the cause's run is not one of the event's org");
|
|
275
|
-
return {
|
|
280
|
+
return {
|
|
281
|
+
runId: run.id,
|
|
282
|
+
accountId: row.cause_account_id,
|
|
283
|
+
depth: row.depth,
|
|
284
|
+
causeWindow: {
|
|
285
|
+
createdAt: row.created_at.getTime(),
|
|
286
|
+
expiresAt: row.expires_at.getTime(),
|
|
287
|
+
},
|
|
288
|
+
};
|
|
276
289
|
}
|
|
277
290
|
if (!nonEmpty(cause.accountId))
|
|
278
291
|
throw invalid("cause.accountId must be an account id");
|
|
@@ -209,7 +209,7 @@ export declare function headsToResolve(entries: readonly MarketplaceEntry[], imp
|
|
|
209
209
|
/** The host versions (an entry's `minKernel` is judged against them). */
|
|
210
210
|
export declare const HOST_VERSIONS: {
|
|
211
211
|
readonly kernel: string;
|
|
212
|
-
readonly sdk: "0.1.0-rc.
|
|
212
|
+
readonly sdk: "0.1.0-rc.99";
|
|
213
213
|
};
|
|
214
214
|
/** Whether this deployment satisfies the entry's `minKernel`. */
|
|
215
215
|
export declare const entryCompatible: (e: Pick<MarketplaceEntry, "minKernel">) => boolean;
|
package/dist/config/schema.d.ts
CHANGED
|
@@ -69,10 +69,18 @@ export declare const KernelConfigSchema: z.ZodObject<{
|
|
|
69
69
|
url: z.ZodString;
|
|
70
70
|
migrationUrl: z.ZodOptional<z.ZodString>;
|
|
71
71
|
extensionsUrl: z.ZodOptional<z.ZodString>;
|
|
72
|
+
extensionCredentialsDir: z.ZodOptional<z.ZodString>;
|
|
73
|
+
extensionProvisioningUrl: z.ZodOptional<z.ZodString>;
|
|
74
|
+
extensionConnectionLimit: z.ZodDefault<z.ZodNumber>;
|
|
75
|
+
extensionStatementTimeoutMs: z.ZodDefault<z.ZodNumber>;
|
|
76
|
+
extensionIdleTransactionTimeoutMs: z.ZodDefault<z.ZodNumber>;
|
|
77
|
+
extensionTempFileLimitKb: z.ZodDefault<z.ZodNumber>;
|
|
78
|
+
extensionEffectRelayLogin: z.ZodOptional<z.ZodString>;
|
|
72
79
|
extensionPoolMax: z.ZodDefault<z.ZodNumber>;
|
|
73
80
|
poolMax: z.ZodDefault<z.ZodNumber>;
|
|
74
81
|
connectTimeoutMs: z.ZodDefault<z.ZodNumber>;
|
|
75
82
|
idleTimeoutMs: z.ZodDefault<z.ZodNumber>;
|
|
83
|
+
rlsOwnerRole: z.ZodDefault<z.ZodString>;
|
|
76
84
|
rls: z.ZodDefault<z.ZodEnum<{
|
|
77
85
|
enforce: "enforce";
|
|
78
86
|
off: "off";
|
package/dist/config/schema.js
CHANGED
|
@@ -342,7 +342,65 @@ export const KernelConfigSchema = z.strictObject({
|
|
|
342
342
|
.optional()
|
|
343
343
|
.meta(meta({
|
|
344
344
|
secret: true,
|
|
345
|
-
description: "PostgreSQL
|
|
345
|
+
description: "PostgreSQL endpoint and former shared login name for dedicated extension database identities",
|
|
346
|
+
})),
|
|
347
|
+
extensionCredentialsDir: z
|
|
348
|
+
.string()
|
|
349
|
+
.min(1)
|
|
350
|
+
.optional()
|
|
351
|
+
.meta(meta({
|
|
352
|
+
description: "Directory of operator-managed per-extension PostgreSQL password files",
|
|
353
|
+
})),
|
|
354
|
+
extensionProvisioningUrl: z
|
|
355
|
+
.string()
|
|
356
|
+
.min(1)
|
|
357
|
+
.optional()
|
|
358
|
+
.meta(meta({
|
|
359
|
+
secret: true,
|
|
360
|
+
description: "PostgreSQL administration URL for one-shot extension database provisioning only",
|
|
361
|
+
})),
|
|
362
|
+
extensionConnectionLimit: z
|
|
363
|
+
.number()
|
|
364
|
+
.int()
|
|
365
|
+
.min(2)
|
|
366
|
+
.max(1000)
|
|
367
|
+
.default(32)
|
|
368
|
+
.meta(meta({
|
|
369
|
+
description: "Maximum PostgreSQL sessions per extension across replicas, workers, lanes, and migrations",
|
|
370
|
+
})),
|
|
371
|
+
extensionStatementTimeoutMs: z
|
|
372
|
+
.number()
|
|
373
|
+
.int()
|
|
374
|
+
.positive()
|
|
375
|
+
.max(2_147_483_647)
|
|
376
|
+
.default(60_000)
|
|
377
|
+
.meta(meta({
|
|
378
|
+
description: "Default statement timeout for each dedicated extension login in milliseconds",
|
|
379
|
+
})),
|
|
380
|
+
extensionIdleTransactionTimeoutMs: z
|
|
381
|
+
.number()
|
|
382
|
+
.int()
|
|
383
|
+
.positive()
|
|
384
|
+
.max(2_147_483_647)
|
|
385
|
+
.default(30_000)
|
|
386
|
+
.meta(meta({
|
|
387
|
+
description: "Default idle-in-transaction timeout for each dedicated extension login in milliseconds",
|
|
388
|
+
})),
|
|
389
|
+
extensionTempFileLimitKb: z
|
|
390
|
+
.number()
|
|
391
|
+
.int()
|
|
392
|
+
.positive()
|
|
393
|
+
.max(2_147_483_647)
|
|
394
|
+
.default(65_536)
|
|
395
|
+
.meta(meta({
|
|
396
|
+
description: "Temporary file budget for each dedicated extension database session in KiB",
|
|
397
|
+
})),
|
|
398
|
+
extensionEffectRelayLogin: z
|
|
399
|
+
.string()
|
|
400
|
+
.min(1)
|
|
401
|
+
.optional()
|
|
402
|
+
.meta(meta({
|
|
403
|
+
description: "PostgreSQL runtime login granted access to extension handoffs by the one-shot schema transfer, default capybara_runtime",
|
|
346
404
|
})),
|
|
347
405
|
extensionPoolMax: z
|
|
348
406
|
.number()
|
|
@@ -372,11 +430,18 @@ export const KernelConfigSchema = z.strictObject({
|
|
|
372
430
|
.meta(meta({
|
|
373
431
|
description: "How long an idle PostgreSQL connection stays in the pool, in milliseconds",
|
|
374
432
|
})),
|
|
433
|
+
rlsOwnerRole: z
|
|
434
|
+
.string()
|
|
435
|
+
.min(1)
|
|
436
|
+
.default("capybara_owner")
|
|
437
|
+
.meta(meta({
|
|
438
|
+
description: "PostgreSQL role expected to own the kernel schema and org tables in enforce mode",
|
|
439
|
+
})),
|
|
375
440
|
rls: z
|
|
376
441
|
.enum(["off", "scoped", "enforce"])
|
|
377
442
|
.default("off")
|
|
378
443
|
.meta(meta({
|
|
379
|
-
description: "PostgreSQL row-level security mode where off leaves scope unset, scoped sets transaction-local scope while policies admit all rows, and enforce filters by transaction-local scope
|
|
444
|
+
description: "PostgreSQL row-level security mode where off leaves scope unset, scoped sets transaction-local scope while policies admit all rows, and enforce filters by transaction-local scope. Enforce requires the split database roles, the owner migration, and enabled and forced org policies at startup. Both scoped modes require session-capable connections, with ordinary standalone queries sharing a round trip with their scope setup.",
|
|
380
445
|
})),
|
|
381
446
|
})
|
|
382
447
|
.prefault({}),
|
package/dist/ctx/create-ctx.d.ts
CHANGED
|
@@ -20,6 +20,7 @@ import type { ShareLiveness } from "../shares/liveness.js";
|
|
|
20
20
|
import type { EmbedTokens } from "../ui/embed-token.js";
|
|
21
21
|
import { type UiActionHandler, type UiQueryHandler, type UiRender } from "../ui/registry.js";
|
|
22
22
|
import { type BusSubscriber } from "./bus.js";
|
|
23
|
+
import { type ExtensionEffects } from "./durable-effects.service.js";
|
|
23
24
|
import { type ExtensionNetServices } from "./net.js";
|
|
24
25
|
import { type Keyring } from "./secrets.js";
|
|
25
26
|
export { pluginSchemaName };
|
|
@@ -100,6 +101,7 @@ export interface KernelDeps {
|
|
|
100
101
|
* `ctx.inbox` calls reject.
|
|
101
102
|
*/
|
|
102
103
|
inbox?: () => InboxBackend | undefined;
|
|
104
|
+
durableEffects?: () => Pick<ExtensionEffects, "commit" | "prepare"> | undefined;
|
|
103
105
|
/**
|
|
104
106
|
* What `ctx.agents`, `ctx.conversations` and `ctx.people` call through (`PluginReadsService`),
|
|
105
107
|
* found at the time of use like `inbox`. Absent, or resolving to undefined: those calls reject.
|
|
@@ -199,6 +201,8 @@ export type UiResolution = ReturnType<typeof resolveUiSlots>;
|
|
|
199
201
|
export type KernelExtensionContext = ExtensionContext & {
|
|
200
202
|
/** 本实例的登记账(C17):每次登记记一笔,撤销时逐项撤销。 */
|
|
201
203
|
ledger: RegistrationLedger;
|
|
204
|
+
hasEffectQueue(name: string): boolean;
|
|
205
|
+
dispatchEffectQueue(name: string, data: unknown, jobId: string, delayMs?: number): Promise<void>;
|
|
202
206
|
/**
|
|
203
207
|
* 撤销第一步:停止取新的队列任务;`deadline`(epoch 毫秒)之后撤销队列 worker 时不再等进行中的任务。
|
|
204
208
|
*/
|
package/dist/ctx/create-ctx.js
CHANGED
|
@@ -8,12 +8,14 @@ import { enabledExtensionsQuery } from "../extensions/enabled.js";
|
|
|
8
8
|
import { checkHookRegistration } from "../extensions/hooks.js";
|
|
9
9
|
import { RegistrationLedger } from "../extensions/ledger.js";
|
|
10
10
|
import { audit } from "../identity/audit.js";
|
|
11
|
+
import { appendEffect, isExtensionTransaction } from "../infra/database/extension-handoff.js";
|
|
11
12
|
import { currentScope, withOrgScope } from "../infra/database/org-scope.js";
|
|
12
13
|
import { can } from "../orgs/roles.js";
|
|
13
14
|
import { PrefixedStorage } from "../storage/storage.service.js";
|
|
14
15
|
import { canUseSlot, orgUiTopic, PLATFORM_UI_TOPIC, PluginUiRegistration, } from "../ui/registry.js";
|
|
15
16
|
import { createBus } from "./bus.js";
|
|
16
17
|
import { checkDeviceProvider } from "./device-provider-check.js";
|
|
18
|
+
import { assertEffectKey, } from "./durable-effects.service.js";
|
|
17
19
|
import { createKv } from "./kv.js";
|
|
18
20
|
import { createLock } from "./lock.js";
|
|
19
21
|
import { createExtensionNet } from "./net.js";
|
|
@@ -156,9 +158,8 @@ async function recordDenial(deps, plugin, item) {
|
|
|
156
158
|
* 受控事务的 `Command`):其方法收到的回调拿到的 Kysely(`transaction().execute(cb)`、
|
|
157
159
|
* `connection().execute(cb)`)与返回的 Promise 结果(`startTransaction().execute()` 得到的受控事务)。
|
|
158
160
|
*/
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
return new Proxy(db, {
|
|
161
|
+
function guardDb(db, plugin, transactions) {
|
|
162
|
+
const guarded = new Proxy(db, {
|
|
162
163
|
get(target, prop) {
|
|
163
164
|
// `await using` 经 Symbol.asyncDispose 调用 destroy,同样拦截
|
|
164
165
|
if (prop === "destroy" || prop === Symbol.asyncDispose) {
|
|
@@ -169,24 +170,26 @@ function guardDb(db, plugin) {
|
|
|
169
170
|
const value = Reflect.get(target, prop, target);
|
|
170
171
|
if (typeof value !== "function")
|
|
171
172
|
return value;
|
|
172
|
-
return (...args) => guardValue(value.apply(target, args), plugin);
|
|
173
|
+
return (...args) => guardValue(value.apply(target, args), plugin, transactions);
|
|
173
174
|
},
|
|
174
175
|
});
|
|
176
|
+
if (isExtensionTransaction(db))
|
|
177
|
+
transactions.set(guarded, db);
|
|
178
|
+
return guarded;
|
|
175
179
|
}
|
|
176
180
|
/** 能(经回调或返回值)再拿到 Kysely 的构建器类。 */
|
|
177
181
|
const BUILDERS = [ConnectionBuilder, TransactionBuilder, ControlledTransactionBuilder, Command];
|
|
178
182
|
const isBuilder = (v) => BUILDERS.some((B) => v instanceof B);
|
|
179
183
|
/** Kysely → guardDb;构建器 → guardBuilder;其余原样返回。 */
|
|
180
|
-
function guardValue(v, plugin) {
|
|
181
|
-
// biome-ignore lint/suspicious/noExplicitAny: 内核不持有表结构类型
|
|
184
|
+
function guardValue(v, plugin, transactions) {
|
|
182
185
|
if (v instanceof Kysely)
|
|
183
|
-
return guardDb(v, plugin);
|
|
186
|
+
return guardDb(v, plugin, transactions);
|
|
184
187
|
if (isBuilder(v))
|
|
185
|
-
return guardBuilder(v, plugin);
|
|
188
|
+
return guardBuilder(v, plugin, transactions);
|
|
186
189
|
return v;
|
|
187
190
|
}
|
|
188
191
|
/** 包装构建器:回调参数里的 Kysely、返回值与 Promise 结果都经 guardValue。 */
|
|
189
|
-
function guardBuilder(builder, plugin) {
|
|
192
|
+
function guardBuilder(builder, plugin, transactions) {
|
|
190
193
|
return new Proxy(builder, {
|
|
191
194
|
get(target, prop) {
|
|
192
195
|
const value = Reflect.get(target, prop, target);
|
|
@@ -194,10 +197,12 @@ function guardBuilder(builder, plugin) {
|
|
|
194
197
|
return value;
|
|
195
198
|
return (...args) => {
|
|
196
199
|
const wrapped = args.map((a) => typeof a === "function"
|
|
197
|
-
? (...cbArgs) => a(...cbArgs.map((c) => guardValue(c, plugin)))
|
|
200
|
+
? (...cbArgs) => a(...cbArgs.map((c) => guardValue(c, plugin, transactions)))
|
|
198
201
|
: a);
|
|
199
|
-
const out = guardValue(value.apply(target, wrapped), plugin);
|
|
200
|
-
return out instanceof Promise
|
|
202
|
+
const out = guardValue(value.apply(target, wrapped), plugin, transactions);
|
|
203
|
+
return out instanceof Promise
|
|
204
|
+
? out.then((r) => guardValue(r, plugin, transactions))
|
|
205
|
+
: out;
|
|
201
206
|
};
|
|
202
207
|
},
|
|
203
208
|
});
|
|
@@ -507,23 +512,66 @@ identity = { sha256: null }) {
|
|
|
507
512
|
};
|
|
508
513
|
})()
|
|
509
514
|
: undefined;
|
|
515
|
+
const effectTransactions = new WeakMap();
|
|
516
|
+
const warnedLegacyEffects = new Set();
|
|
517
|
+
const durable = async (orgId, effect, options) => {
|
|
518
|
+
const backend = deps.durableEffects?.();
|
|
519
|
+
if (!backend)
|
|
520
|
+
throw new Error("Durable extension effects are not available in this process.");
|
|
521
|
+
const scope = currentScope();
|
|
522
|
+
if (scope?.kind === "org" && scope.orgId !== orgId) {
|
|
523
|
+
throw new Error("Extension effect org does not match the invocation scope");
|
|
524
|
+
}
|
|
525
|
+
if (options === undefined && (effect.kind === "trigger" || effect.kind === "inbox.post")) {
|
|
526
|
+
if (!warnedLegacyEffects.has(effect.kind)) {
|
|
527
|
+
const method = effect.kind === "trigger" ? "ctx.triggers.emit" : "ctx.inbox.post";
|
|
528
|
+
deps.log.warn(`${method} without idempotencyKey is deprecated and will be removed in the next release`, {
|
|
529
|
+
plugin: name,
|
|
530
|
+
});
|
|
531
|
+
warnedLegacyEffects.add(effect.kind);
|
|
532
|
+
}
|
|
533
|
+
return withOrgScope(orgId, () => backend.commit(name, orgId, undefined, effect));
|
|
534
|
+
}
|
|
535
|
+
const key = options?.idempotencyKey;
|
|
536
|
+
assertEffectKey(key);
|
|
537
|
+
const tx = options?.tx && effectTransactions.get(options.tx);
|
|
538
|
+
if (options?.tx !== undefined && !tx) {
|
|
539
|
+
throw new Error("The effect requires a live transaction from this extension's ctx.db");
|
|
540
|
+
}
|
|
541
|
+
if (tx === undefined) {
|
|
542
|
+
return withOrgScope(orgId, () => backend.commit(name, orgId, key, effect));
|
|
543
|
+
}
|
|
544
|
+
const envelope = await withOrgScope(orgId, () => backend.prepare(name, orgId, key, effect, tx));
|
|
545
|
+
await appendEffect(tx, name, envelope);
|
|
546
|
+
return { status: "staged", idempotencyKey: key };
|
|
547
|
+
};
|
|
548
|
+
const addOutbox = (async (effect, options) => {
|
|
549
|
+
const snapshot = structuredClone(effect);
|
|
550
|
+
if (!snapshot?.orgId || typeof snapshot.orgId !== "string") {
|
|
551
|
+
throw new Error("An extension outbox effect requires an org id");
|
|
552
|
+
}
|
|
553
|
+
if (snapshot.kind === "inbox.resolve" && !perms.inbox) {
|
|
554
|
+
throw new Error("Resolving an inbox item requires inbox permission");
|
|
555
|
+
}
|
|
556
|
+
if (snapshot.kind !== "inbox.resolve" && snapshot.kind !== "queue") {
|
|
557
|
+
throw new Error("Unknown extension outbox effect kind");
|
|
558
|
+
}
|
|
559
|
+
const result = await durable(snapshot.orgId, snapshot, options);
|
|
560
|
+
return options.tx ? result : undefined;
|
|
561
|
+
});
|
|
510
562
|
// ctx.triggers: only with permissions.triggers; the event types come from the approved manifest
|
|
511
563
|
// (a frozen copy: the extension changing its manifest object later changes nothing), and the
|
|
512
564
|
// event is stored in its own org's scope (TriggerEventsService checks the rest)
|
|
513
565
|
const triggersApi = perms.triggers
|
|
514
566
|
? (() => {
|
|
515
|
-
const declared = Object.freeze([...(perms.triggers?.emit ?? [])]);
|
|
516
567
|
return {
|
|
517
|
-
emit: async (event) => {
|
|
518
|
-
const b = deps.triggers?.();
|
|
519
|
-
if (!b)
|
|
520
|
-
throw new Error("Trigger events are not available in this process.");
|
|
568
|
+
emit: (async (event, options) => {
|
|
521
569
|
// one snapshot, read once: what is checked is what is stored
|
|
522
570
|
const snap = snapshotTriggerEvent(event);
|
|
523
571
|
if (typeof snap.orgId !== "string" || snap.orgId === "")
|
|
524
572
|
throw new TriggerError("invalid_event", "invalid event: missing_org_id");
|
|
525
|
-
return
|
|
526
|
-
},
|
|
573
|
+
return durable(snap.orgId, { kind: "trigger", data: snap }, options);
|
|
574
|
+
}),
|
|
527
575
|
// a handle bound to this extension and the call's run, in the call's org (the service
|
|
528
576
|
// checks the context is the pipeline's and its run is of that org)
|
|
529
577
|
causeOf: async (call) => {
|
|
@@ -544,10 +592,7 @@ identity = { sha256: null }) {
|
|
|
544
592
|
// copy read once (what is checked is what is stored)
|
|
545
593
|
const inboxApi = perms.inbox
|
|
546
594
|
? {
|
|
547
|
-
post: async (p) => {
|
|
548
|
-
const b = deps.inbox?.();
|
|
549
|
-
if (!b)
|
|
550
|
-
throw new Error("The inbox is not available in this process.");
|
|
595
|
+
post: (async (p, options) => {
|
|
551
596
|
let snap;
|
|
552
597
|
try {
|
|
553
598
|
snap = structuredClone(p);
|
|
@@ -560,9 +605,8 @@ identity = { sha256: null }) {
|
|
|
560
605
|
typeof snap.orgId !== "string" ||
|
|
561
606
|
snap.orgId === "")
|
|
562
607
|
throw new InboxError("invalid_item", "invalid inbox item: missing_org_id");
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
},
|
|
608
|
+
return durable(snap.orgId, { kind: "inbox.post", data: snap }, options);
|
|
609
|
+
}),
|
|
566
610
|
resolve: async (args) => {
|
|
567
611
|
const b = deps.inbox?.();
|
|
568
612
|
if (!b)
|
|
@@ -828,7 +872,10 @@ identity = { sha256: null }) {
|
|
|
828
872
|
},
|
|
829
873
|
add: queue.add,
|
|
830
874
|
},
|
|
831
|
-
db: guardDb((identity.db ?? deps.db).withSchema(pluginSchemaName(name)), name),
|
|
875
|
+
db: guardDb((identity.db ?? deps.db).withSchema(pluginSchemaName(name)), name, effectTransactions),
|
|
876
|
+
hasEffectQueue: queue.hasDefined,
|
|
877
|
+
dispatchEffectQueue: queue.dispatchEffect,
|
|
878
|
+
outbox: { add: addOutbox },
|
|
832
879
|
http: {
|
|
833
880
|
route(method, path, handler) {
|
|
834
881
|
if (typeof path !== "string" || !path.startsWith("/")) {
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** The caller records and settles the cancellation using its current kernel transaction. */
|
|
2
|
+
export async function cancelDeletedOrgEffect(db, plugin, id) {
|
|
3
|
+
await db
|
|
4
|
+
.insertInto("extension_effect_cancellations")
|
|
5
|
+
.values({ id, plugin, reason: "organization_deleted" })
|
|
6
|
+
.onConflict((conflict) => conflict.doNothing())
|
|
7
|
+
.execute();
|
|
8
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import type { ExtensionOutboxEffect, InboxPost, TriggerEvent } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
import { type Kysely } from "kysely";
|
|
3
|
+
import { TriggerEventsService, type VerifiedCause } from "../automations/events/trigger-events.service.js";
|
|
4
|
+
import { ExtensionRegistry } from "../extensions/registry.js";
|
|
5
|
+
import { InboxItemsService } from "../inbox/inbox-items.service.js";
|
|
6
|
+
import type { HandoffReference } from "../infra/database/extension-handoff.js";
|
|
7
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
8
|
+
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
9
|
+
import { XactLock } from "../infra/database/xact-lock.js";
|
|
10
|
+
import { OutboxService } from "../infra/outbox/outbox.service.js";
|
|
11
|
+
import type { EnvelopeKeyring } from "./durable-envelope.js";
|
|
12
|
+
import { type SignedEnvelope } from "./durable-envelope.js";
|
|
13
|
+
import { ExtensionEffectKeys } from "./durable-keys.js";
|
|
14
|
+
export type ExtensionEffect = {
|
|
15
|
+
kind: "trigger";
|
|
16
|
+
data: TriggerEvent;
|
|
17
|
+
} | {
|
|
18
|
+
kind: "inbox.post";
|
|
19
|
+
data: InboxPost;
|
|
20
|
+
} | ExtensionOutboxEffect;
|
|
21
|
+
type PreparedEffect = {
|
|
22
|
+
kind: "trigger";
|
|
23
|
+
data: Omit<TriggerEvent, "cause">;
|
|
24
|
+
cause: VerifiedCause;
|
|
25
|
+
} | Exclude<ExtensionEffect, {
|
|
26
|
+
kind: "trigger";
|
|
27
|
+
}>;
|
|
28
|
+
type EffectBody = {
|
|
29
|
+
plugin: string;
|
|
30
|
+
principal: {
|
|
31
|
+
kind: "extension";
|
|
32
|
+
name: string;
|
|
33
|
+
};
|
|
34
|
+
orgId: string;
|
|
35
|
+
key: string;
|
|
36
|
+
effect: PreparedEffect;
|
|
37
|
+
payloadHash: string;
|
|
38
|
+
issuedAt: number;
|
|
39
|
+
causeWindow?: NonNullable<VerifiedCause["causeWindow"]>;
|
|
40
|
+
};
|
|
41
|
+
export type ExtensionEffectEnvelope = SignedEnvelope<EffectBody>;
|
|
42
|
+
export declare function assertEffectKey(key: unknown): asserts key is string;
|
|
43
|
+
export declare class ExtensionEffects {
|
|
44
|
+
private readonly kdb;
|
|
45
|
+
readonly txHost: TransactionHost;
|
|
46
|
+
private readonly lock;
|
|
47
|
+
private readonly registry;
|
|
48
|
+
private readonly triggers;
|
|
49
|
+
private readonly inbox;
|
|
50
|
+
private readonly outbox;
|
|
51
|
+
private readonly keys;
|
|
52
|
+
constructor(kdb: KernelDb, txHost: TransactionHost, lock: XactLock, registry: ExtensionRegistry, triggers: TriggerEventsService, inbox: InboxItemsService, outbox: OutboxService, keys: ExtensionEffectKeys);
|
|
53
|
+
private instance;
|
|
54
|
+
private normalize;
|
|
55
|
+
prepare(plugin: string, orgId: string, key: string, effect: ExtensionEffect, extensionTx?: Kysely<unknown>): Promise<SignedEnvelope<{
|
|
56
|
+
plugin: string;
|
|
57
|
+
principal: {
|
|
58
|
+
kind: "extension";
|
|
59
|
+
name: string;
|
|
60
|
+
};
|
|
61
|
+
orgId: string;
|
|
62
|
+
key: string;
|
|
63
|
+
effect: PreparedEffect;
|
|
64
|
+
payloadHash: string;
|
|
65
|
+
issuedAt: number;
|
|
66
|
+
causeWindow?: {
|
|
67
|
+
createdAt: number;
|
|
68
|
+
expiresAt: number;
|
|
69
|
+
};
|
|
70
|
+
}>>;
|
|
71
|
+
verify(envelope: ExtensionEffectEnvelope, ring?: EnvelopeKeyring): Promise<EffectBody>;
|
|
72
|
+
commit(plugin: string, orgId: string, key: string | undefined, effect: ExtensionEffect): Promise<unknown>;
|
|
73
|
+
deliver(body: EffectBody): Promise<unknown>;
|
|
74
|
+
cancelIfDeleted(body: EffectBody): Promise<boolean>;
|
|
75
|
+
private activeOrg;
|
|
76
|
+
private apply;
|
|
77
|
+
private applyNew;
|
|
78
|
+
park(orgId: string | undefined, jobId: string, data: HandoffReference, reason: string, attempts: number): Promise<boolean>;
|
|
79
|
+
private inboxKeyIsResolved;
|
|
80
|
+
}
|
|
81
|
+
export {};
|