@feltdb/feltkit 0.3.11 → 0.3.13
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/README.md +4 -3
- package/dist/app.d.ts +98 -3
- package/dist/app.js +63 -0
- package/dist/app.js.map +1 -1
- package/dist/appboundry/build.d.ts +39 -1
- package/dist/appboundry/build.js +57 -6
- package/dist/appboundry/build.js.map +1 -1
- package/dist/appboundry/guest.js +46 -5
- package/dist/appboundry/guest.js.map +1 -1
- package/dist/appboundry/host.d.ts +24 -5
- package/dist/appboundry/host.js +234 -141
- package/dist/appboundry/host.js.map +1 -1
- package/dist/appboundry/runtime.d.ts +44 -0
- package/dist/appboundry/runtime.js +99 -0
- package/dist/appboundry/runtime.js.map +1 -0
- package/dist/cli/entry.d.ts +1 -0
- package/dist/cli/entry.js +4 -0
- package/dist/cli/entry.js.map +1 -0
- package/dist/cli/main.d.ts +5 -0
- package/dist/cli/main.js +550 -13
- package/dist/cli/main.js.map +1 -1
- package/dist/cli/test-reporter.d.ts +9 -0
- package/dist/cli/test-reporter.js +26 -0
- package/dist/cli/test-reporter.js.map +1 -0
- package/dist/client/index.d.ts +3 -0
- package/dist/client/index.js +3 -0
- package/dist/client/index.js.map +1 -1
- package/dist/dashboard/assets/index-BSnW2DC-.js +15 -0
- package/dist/dashboard/assets/{index-91I1zDK-.css → index-BXTNQAg1.css} +1 -1
- package/dist/dashboard/index.html +3 -3
- package/dist/docs.d.ts +12 -0
- package/dist/docs.js +42 -0
- package/dist/docs.js.map +1 -0
- package/dist/errors.d.ts +15 -0
- package/dist/errors.js +9 -0
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js.map +1 -1
- package/dist/platform/changes.d.ts +340 -0
- package/dist/platform/changes.js +355 -0
- package/dist/platform/changes.js.map +1 -0
- package/dist/platform/deployments.d.ts +653 -0
- package/dist/platform/deployments.js +532 -0
- package/dist/platform/deployments.js.map +1 -0
- package/dist/platform/operations.d.ts +74 -0
- package/dist/platform/operations.js +198 -0
- package/dist/platform/operations.js.map +1 -0
- package/dist/platform/platform.d.ts +78 -0
- package/dist/platform/platform.js +264 -0
- package/dist/platform/platform.js.map +1 -0
- package/dist/platform/server.d.ts +25 -0
- package/dist/platform/server.js +165 -0
- package/dist/platform/server.js.map +1 -0
- package/dist/platform/source.d.ts +27 -0
- package/dist/platform/source.js +142 -0
- package/dist/platform/source.js.map +1 -0
- package/dist/runtime/activity.d.ts +25 -0
- package/dist/runtime/activity.js +38 -12
- package/dist/runtime/activity.js.map +1 -1
- package/dist/runtime/agent.d.ts +16 -0
- package/dist/runtime/agent.js +92 -28
- package/dist/runtime/agent.js.map +1 -1
- package/dist/runtime/backup-environment.d.ts +32 -0
- package/dist/runtime/backup-environment.js +92 -0
- package/dist/runtime/backup-environment.js.map +1 -0
- package/dist/runtime/backup.d.ts +129 -0
- package/dist/runtime/backup.js +344 -0
- package/dist/runtime/backup.js.map +1 -0
- package/dist/runtime/capabilities.js +4 -2
- package/dist/runtime/capabilities.js.map +1 -1
- package/dist/runtime/changes.js +2 -2
- package/dist/runtime/changes.js.map +1 -1
- package/dist/runtime/contract.js +4 -3
- package/dist/runtime/contract.js.map +1 -1
- package/dist/runtime/data.d.ts +36 -5
- package/dist/runtime/data.js +165 -55
- package/dist/runtime/data.js.map +1 -1
- package/dist/runtime/decisions.js +2 -1
- package/dist/runtime/decisions.js.map +1 -1
- package/dist/runtime/instance.js +17 -0
- package/dist/runtime/instance.js.map +1 -1
- package/dist/runtime/integrations.js +14 -6
- package/dist/runtime/integrations.js.map +1 -1
- package/dist/runtime/loader.js +28 -4
- package/dist/runtime/loader.js.map +1 -1
- package/dist/runtime/migration-context.d.ts +25 -0
- package/dist/runtime/migration-context.js +69 -0
- package/dist/runtime/migration-context.js.map +1 -0
- package/dist/runtime/outbox.d.ts +6 -82
- package/dist/runtime/outbox.js +14 -59
- package/dist/runtime/outbox.js.map +1 -1
- package/dist/runtime/readiness.js +18 -1
- package/dist/runtime/readiness.js.map +1 -1
- package/dist/runtime/runtime.d.ts +84 -8
- package/dist/runtime/runtime.js +372 -131
- package/dist/runtime/runtime.js.map +1 -1
- package/dist/runtime/services.d.ts +41 -5
- package/dist/runtime/services.js +49 -4
- package/dist/runtime/services.js.map +1 -1
- package/dist/runtime/sessions.js +4 -3
- package/dist/runtime/sessions.js.map +1 -1
- package/dist/runtime/state-contract.d.ts +167 -0
- package/dist/runtime/state-contract.js +438 -0
- package/dist/runtime/state-contract.js.map +1 -0
- package/dist/runtime/transactions.d.ts +199 -0
- package/dist/runtime/transactions.js +246 -0
- package/dist/runtime/transactions.js.map +1 -0
- package/dist/schema.d.ts +13 -1
- package/dist/schema.js +21 -2
- package/dist/schema.js.map +1 -1
- package/dist/server/admin.d.ts +3 -2
- package/dist/server/admin.js +62 -10
- package/dist/server/admin.js.map +1 -1
- package/dist/server/index.d.ts +6 -1
- package/dist/server/index.js +90 -9
- package/dist/server/index.js.map +1 -1
- package/dist/server/mcp.js +1 -1
- package/dist/server/mcp.js.map +1 -1
- package/dist/server/project.d.ts +5 -0
- package/dist/server/project.js +13 -2
- package/dist/server/project.js.map +1 -1
- package/dist/testing/index.d.ts +10 -3
- package/dist/testing/index.js +33 -7
- package/dist/testing/index.js.map +1 -1
- package/docs/AGENT-OPERATIONS.md +515 -0
- package/docs/APPBOUNDRY.md +240 -0
- package/docs/ARCHITECTURE.md +126 -0
- package/docs/BACKUP.md +115 -0
- package/docs/GUARANTEES.md +457 -0
- package/docs/PATH-TO-PRODUCTION.md +117 -0
- package/docs/README.md +15 -0
- package/docs/SECURITY.md +182 -0
- package/docs/TRANSACTIONS.md +216 -0
- package/docs/UPSTREAM-GAPS.md +270 -0
- package/docs/WHY-FELTKIT.md +64 -0
- package/docs/assets/feltkit-logo-dark.png +0 -0
- package/docs/assets/feltkit-logo.png +0 -0
- package/package.json +10 -8
- package/skills/.claude-plugin/marketplace.json +1 -1
- package/skills/.claude-plugin/plugin.json +3 -3
- package/skills/feltkit-agent/SKILL.md +9 -5
- package/skills/feltkit-build/SKILL.md +16 -4
- package/skills/feltkit-data/SKILL.md +20 -3
- package/skills/feltkit-services/SKILL.md +13 -7
- package/dist/dashboard/assets/index-BhFOquA7.js +0 -15
- package/dist/dashboard/theme.js +0 -11
package/dist/runtime/runtime.js
CHANGED
|
@@ -16,17 +16,21 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
|
16
16
|
import { dirname, join } from "node:path";
|
|
17
17
|
import { IntegrationHost, integrationDescriptor } from "./integrations.js";
|
|
18
18
|
import { verifyStorage } from "./storage-check.js";
|
|
19
|
-
import {
|
|
19
|
+
import { assertNotPartiallyRestored, writeBackup } from "./backup.js";
|
|
20
|
+
import { backupMeta, remoteBackupRefusal } from "./backup-environment.js";
|
|
21
|
+
import { FeltKitError, isFeltKitError, statusFor } from "../errors.js";
|
|
20
22
|
import { validate } from "../schema.js";
|
|
21
23
|
import { ActivityLog, errorSummary } from "./activity.js";
|
|
22
24
|
import { Authority, authContext, fromAppPortPrincipal, normalizePrincipal } from "./authority.js";
|
|
23
25
|
import { ChangeFeed } from "./changes.js";
|
|
24
26
|
import { ModelHost } from "./decisions.js";
|
|
25
|
-
import { CollectionResolver, Reader, Writer, ensureCollectionMarkers, feltdbRefusalJSON } from "./data.js";
|
|
27
|
+
import { CollectionResolver, Reader, Writer, ensureCollectionMarkers, feltdbRefusalJSON, readAll } from "./data.js";
|
|
26
28
|
import { describeStorage } from "./environment.js";
|
|
27
29
|
import { defaultInstanceFactory } from "./instance.js";
|
|
28
30
|
import { explainServiceDenials, ServicesHost } from "./services.js";
|
|
29
|
-
import {
|
|
31
|
+
import { applySchema, blockedHint, describePlan, MIGRATIONS_COLLECTION, planSchema, publicPlan } from "./state-contract.js";
|
|
32
|
+
import { afterCommit, newOutboxId, OUTBOX_COLLECTION, performEffect } from "./outbox.js";
|
|
33
|
+
import { isRecoverable, isSequenceConflict, outboxStore, performOutbox, retried, settled } from "./transactions.js";
|
|
30
34
|
import { credentialsFor, isCustodyError } from "./credentials.js";
|
|
31
35
|
import { AgentHost } from "./agent.js";
|
|
32
36
|
import { FeltDbIdempotencyStore } from "./idempotency.js";
|
|
@@ -81,6 +85,8 @@ export class FeltKitRuntime {
|
|
|
81
85
|
#resolver;
|
|
82
86
|
#state = "starting";
|
|
83
87
|
#inflight = new Set();
|
|
88
|
+
/** Set while backup() reads the state: calls and the services worker wait for it. */
|
|
89
|
+
#paused = null;
|
|
84
90
|
#dispatched = new Set();
|
|
85
91
|
#generation = 0;
|
|
86
92
|
#reloadListeners = new Set();
|
|
@@ -138,7 +144,12 @@ export class FeltKitRuntime {
|
|
|
138
144
|
// Verify the instance answers (on a server: this key reads, writes, and matches the
|
|
139
145
|
// active contract) before declaring the runtime ready.
|
|
140
146
|
await verifyStorage(options.environment, instance.handle("feltkit.runtime"), options.project.app);
|
|
147
|
+
// A restore that did not complete is not an application (docs/BACKUP.md).
|
|
148
|
+
await assertNotPartiallyRestored(instance.handle("feltkit.runtime"));
|
|
141
149
|
step("storage");
|
|
150
|
+
runtime.#migrate = options.migrate ?? "auto";
|
|
151
|
+
await runtime.#ensureSchema(options.project.app, "start");
|
|
152
|
+
step("schema");
|
|
142
153
|
await ensureCollectionMarkers(instance.handle("feltkit.runtime"), options.project.app.collections.keys());
|
|
143
154
|
step("markers");
|
|
144
155
|
await runtime.#services.check();
|
|
@@ -224,6 +235,87 @@ export class FeltKitRuntime {
|
|
|
224
235
|
return () => this.#reloadListeners.delete(listener);
|
|
225
236
|
}
|
|
226
237
|
/** Swap in a new application definition. State, sessions, and history are untouched. */
|
|
238
|
+
/** The application's schema lifecycle state (see SchemaStatus). */
|
|
239
|
+
schema = null;
|
|
240
|
+
#migrate = "auto";
|
|
241
|
+
/** What `feltkit migrate` would do now. Writes nothing. */
|
|
242
|
+
async schemaPlan() {
|
|
243
|
+
this.#assertReady();
|
|
244
|
+
return publicPlan(await planSchema(this.instance.handle("feltkit.schema"), this.#project.app));
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Apply the declared schema (with pending migrations) as one FeltDB evolution, or refuse
|
|
248
|
+
* with what blocks it. Nothing changes on refusal. Then this runtime serves the result.
|
|
249
|
+
*/
|
|
250
|
+
async migrateSchema(options) {
|
|
251
|
+
this.#assertReady();
|
|
252
|
+
const db = this.instance.handle("feltkit.schema");
|
|
253
|
+
const applied = await applySchema(db, this.#project.app, { by: options.by, environment: this.environment.name });
|
|
254
|
+
const plan = publicPlan(await planSchema(db, this.#project.app));
|
|
255
|
+
this.schema = { status: plan.status === "unmanaged" ? "unmanaged" : "current", plan, ...(applied ? { applied } : {}), at: new Date().toISOString() };
|
|
256
|
+
if (applied)
|
|
257
|
+
this.logger.info(`Schema ${applied.from ? `v${applied.from.version}` : "none"} → v${applied.to.version} applied by ${options.by}`);
|
|
258
|
+
return applied;
|
|
259
|
+
}
|
|
260
|
+
/** Evolutions applied to this store, newest first. */
|
|
261
|
+
async schemaHistory() {
|
|
262
|
+
const rows = (await readAll(this.instance.handle("feltkit.schema"), { collection: MIGRATIONS_COLLECTION }));
|
|
263
|
+
return rows.map(({ __version: _v, ...r }) => r).sort((a, b) => b.appliedAt.localeCompare(a.appliedAt));
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* Bring the store's schema to what feltkit/ declares, or say exactly why not. At start in
|
|
267
|
+
* production a change FeltDB would refuse (or any change, with migrate: "manual") stops the
|
|
268
|
+
* runtime before it serves; in development the server keeps running and every function
|
|
269
|
+
* call says what to migrate.
|
|
270
|
+
*/
|
|
271
|
+
async #ensureSchema(app, phase) {
|
|
272
|
+
const db = this.instance.handle("feltkit.schema");
|
|
273
|
+
const at = () => new Date().toISOString();
|
|
274
|
+
let plan = publicPlan(await planSchema(db, app));
|
|
275
|
+
if (plan.status === "current" || plan.status === "unmanaged") {
|
|
276
|
+
this.schema = { status: plan.status, plan, at: at() };
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
if (this.#migrate === "off" && plan.status !== "blocked") {
|
|
280
|
+
// Opened to read or migrate: report, change nothing.
|
|
281
|
+
this.schema = plan.active
|
|
282
|
+
? { status: "blocked", plan: { ...plan, reason: plan.reason ?? "the schema changed and has not been migrated" }, at: at() }
|
|
283
|
+
: { status: "pending", plan, at: at() };
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
const blockedByPolicy = this.#migrate !== "auto" && plan.active !== null;
|
|
287
|
+
if (plan.status === "blocked" || blockedByPolicy) {
|
|
288
|
+
if (!plan.active) {
|
|
289
|
+
this.schema = { status: "unverified", plan, at: at() };
|
|
290
|
+
this.logger.warn(`Schema unverified: ${plan.reason}. FeltKit serves this data as before, without FeltDB enforcing the schema. ${blockedHint(plan)}`);
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
this.schema = { status: "blocked", plan, at: at() };
|
|
294
|
+
const why = blockedByPolicy && plan.status !== "blocked" ? "The schema changed and this runtime does not migrate (migrate: manual)." : `The schema change cannot be applied: ${plan.reason}.`;
|
|
295
|
+
const hint = blockedByPolicy && plan.status !== "blocked" ? "Run `npx feltkit migrate --env <env>` to review and apply it." : blockedHint(plan);
|
|
296
|
+
if (phase === "start" && this.environment.production && this.#migrate !== "off") {
|
|
297
|
+
throw new FeltKitError("CONFIGURATION", `${why}\n ${describePlan(plan).join("\n ")}`, { hint });
|
|
298
|
+
}
|
|
299
|
+
this.logger.error(`${why} Every function call is refused until it is migrated.\n ${describePlan(plan).join("\n ")}\n ${hint}`);
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
const applied = await applySchema(db, app, { by: `feltkit ${phase}`, environment: this.environment.name }).catch((error) => error);
|
|
303
|
+
if (applied instanceof Error) {
|
|
304
|
+
// FeltDB refused what the plan expected it to accept: nothing changed.
|
|
305
|
+
plan = publicPlan(await planSchema(db, app));
|
|
306
|
+
this.schema = { status: plan.active ? "blocked" : "unverified", plan: { ...plan, status: "blocked", reason: applied.message }, at: at() };
|
|
307
|
+
if (phase === "start" && this.environment.production && plan.active)
|
|
308
|
+
throw applied;
|
|
309
|
+
this.logger.error(`${applied.message}${applied.hint ? `\n ${applied.hint}` : ""}`);
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
this.schema = { status: "current", plan: publicPlan(await planSchema(db, app)), ...(applied ? { applied } : {}), at: at() };
|
|
313
|
+
if (applied) {
|
|
314
|
+
const from = applied.from ? `v${applied.from.version}` : "none";
|
|
315
|
+
const what = [...applied.changes.map((c) => `${c.kind} ${c.path}`), ...applied.migrations.map((m) => `migration "${m}"`)];
|
|
316
|
+
this.logger.info(`Schema ${from} → v${applied.to.version} applied${what.length ? `: ${what.join(", ")}` : " (FeltDB now enforces it)"}`);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
227
319
|
async reload(project) {
|
|
228
320
|
this.#assertReady();
|
|
229
321
|
if (project.app.name !== this.#project.app.name) {
|
|
@@ -232,6 +324,7 @@ export class FeltKitRuntime {
|
|
|
232
324
|
await ensureCollectionMarkers(this.instance.handle("feltkit.runtime"), project.app.collections.keys());
|
|
233
325
|
const previous = this.#appport;
|
|
234
326
|
this.#install(project);
|
|
327
|
+
await this.#ensureSchema(project.app, "reload");
|
|
235
328
|
this.#agent?.define();
|
|
236
329
|
await previous.close().catch(() => undefined);
|
|
237
330
|
for (const listener of this.#reloadListeners)
|
|
@@ -292,7 +385,7 @@ export class FeltKitRuntime {
|
|
|
292
385
|
capabilities.push(this.#integrationCapability(integration, op));
|
|
293
386
|
}
|
|
294
387
|
const appport = createApplication({
|
|
295
|
-
application: { id: app.name, name: app.name, version: app.
|
|
388
|
+
application: { id: app.name, name: app.name, version: app.version, ...(app.options.description ? { description: app.options.description } : {}) },
|
|
296
389
|
capabilities,
|
|
297
390
|
authorizer: authority.authorizer,
|
|
298
391
|
db: this.instance.handle("appport"),
|
|
@@ -345,14 +438,6 @@ export class FeltKitRuntime {
|
|
|
345
438
|
if (!isFeltKitError(error))
|
|
346
439
|
throw error;
|
|
347
440
|
const details = (error.details ?? null);
|
|
348
|
-
if (error.code === "OUTCOME_UNKNOWN")
|
|
349
|
-
throw new AppPortError("OUTCOME_UNKNOWN", error.message, { retryable: false, details });
|
|
350
|
-
if (error.code === "UNAVAILABLE")
|
|
351
|
-
throw new AppPortError("UNAVAILABLE", error.message, { retryable: true, details });
|
|
352
|
-
if (error.code === "CONFIGURATION")
|
|
353
|
-
throw new AppPortError("NOT_CONFIGURED", error.message, { retryable: false, details: { hint: error.hint ?? null } });
|
|
354
|
-
if (error.code === "CONFLICT")
|
|
355
|
-
throw appportErrors.conflict(error.message, details);
|
|
356
441
|
throw toAppPortError(error.toJSON());
|
|
357
442
|
}
|
|
358
443
|
},
|
|
@@ -360,6 +445,30 @@ export class FeltKitRuntime {
|
|
|
360
445
|
}
|
|
361
446
|
/** The caller of the AppPort request being dispatched (see #gate). */
|
|
362
447
|
#appportCaller = new AsyncLocalStorage();
|
|
448
|
+
/**
|
|
449
|
+
* The approved agent action being executed (agent.ts #execute), in this process only: the
|
|
450
|
+
* one way a non-person principal runs an `approval: "required"` mutation. Nothing a caller
|
|
451
|
+
* sends (headers, envelope metadata, transport names) can set it.
|
|
452
|
+
*/
|
|
453
|
+
#approvedAction = new AsyncLocalStorage();
|
|
454
|
+
/** Run `work` as the execution of an approved action (called by the agent lifecycle only). */
|
|
455
|
+
runApproved(action, work) {
|
|
456
|
+
return this.#approvedAction.run(Object.freeze({ ...action }), work);
|
|
457
|
+
}
|
|
458
|
+
/**
|
|
459
|
+
* Why `principal` may not run `fn` directly, or null. An approval-required mutation needs a
|
|
460
|
+
* person, or the approved action for exactly this capability.
|
|
461
|
+
*/
|
|
462
|
+
#approvalRefusal(name, fn, principal) {
|
|
463
|
+
if (fn.approval !== "required" || !principal || principal.type === "user")
|
|
464
|
+
return null;
|
|
465
|
+
const approved = this.#approvedAction.getStore();
|
|
466
|
+
if (approved && fn.capability && approved.capability === fn.capability.name)
|
|
467
|
+
return null;
|
|
468
|
+
return fn.capability
|
|
469
|
+
? `${fn.capability.name} requires a person's approval: a ${principal.type} cannot run it directly. Propose it with feltkit_agent_propose; it runs once a person approves it.`
|
|
470
|
+
: `${name} requires a person's approval and is not published as a capability, so only a person can run it.`;
|
|
471
|
+
}
|
|
363
472
|
/**
|
|
364
473
|
* Authority before arguments on AppPort and MCP too: AppPort validates input before it
|
|
365
474
|
* consults the authorizer, so a capability's input schema runs this check first, from the
|
|
@@ -374,6 +483,10 @@ export class FeltKitRuntime {
|
|
|
374
483
|
const required = Authority.required(fn.access);
|
|
375
484
|
if (required.length && !grantsPermission(this.#authority.permissionsFor(scope.principal), required[0]))
|
|
376
485
|
throw appportErrors.forbidden(`Missing permission: ${required[0]}`);
|
|
486
|
+
const name = [...this.#project.functions.entries()].find(([, f]) => f === fn)?.[0] ?? fn.capability?.name ?? "";
|
|
487
|
+
const refusal = this.#approvalRefusal(name, fn, scope.principal);
|
|
488
|
+
if (refusal)
|
|
489
|
+
throw appportErrors.forbidden(refusal, { approval: "required" });
|
|
377
490
|
}
|
|
378
491
|
#capabilityFor(name, fn) {
|
|
379
492
|
const exposure = fn.capability;
|
|
@@ -423,6 +536,7 @@ export class FeltKitRuntime {
|
|
|
423
536
|
args: fn.argsSchema.toJSONSchema(),
|
|
424
537
|
...(fn.returns ? { returns: fn.returns.toJSONSchema() } : {}),
|
|
425
538
|
...(fn.capability ? { capability: { name: fn.capability.name, version: fn.capability.version } } : {}),
|
|
539
|
+
...(fn.approval ? { approval: fn.approval } : {}),
|
|
426
540
|
}))
|
|
427
541
|
.sort((a, b) => a.name.localeCompare(b.name));
|
|
428
542
|
}
|
|
@@ -473,61 +587,40 @@ export class FeltKitRuntime {
|
|
|
473
587
|
}
|
|
474
588
|
/**
|
|
475
589
|
* Perform one after-commit effect: claim the record (pending → performing, version-checked,
|
|
476
|
-
* so two processes never both perform it), perform it, record done or failed
|
|
477
|
-
*
|
|
478
|
-
*
|
|
590
|
+
* so two processes never both perform it), perform it, record done or failed (shared
|
|
591
|
+
* transitions: runtime/transactions.ts). A notification carries the outbox id as its idempotency
|
|
592
|
+
* key, so a recovered send is not repeated; a recovered job or webhook event can be (at least
|
|
593
|
+
* once: docs/TRANSACTIONS.md, UPSTREAM-GAPS.md). Never throws:
|
|
594
|
+
* the mutation has committed, and its caller gets its result; a failure is on the record and in
|
|
595
|
+
* the log.
|
|
479
596
|
*/
|
|
480
|
-
async #performOutbox(record, services) {
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
return
|
|
489
|
-
|
|
490
|
-
await write(current, { state: "performing", attempts: (current.attempts ?? 0) + 1 });
|
|
491
|
-
}
|
|
492
|
-
catch {
|
|
493
|
-
return "skipped"; // another process claimed it
|
|
494
|
-
}
|
|
495
|
-
current = (await store.collection(OUTBOX_COLLECTION).get(record.id));
|
|
496
|
-
let outcome;
|
|
497
|
-
try {
|
|
498
|
-
await performEffect(services, current);
|
|
499
|
-
outcome = { state: "done" };
|
|
500
|
-
}
|
|
501
|
-
catch (error) {
|
|
502
|
-
outcome = { state: "failed", error: effectError(error) };
|
|
503
|
-
this.logger.warn(`after-commit ${current.effect.service}.${current.effect.method} from ${current.function} failed: ${outcome.error.message}`, { outboxId: current.id, requestId: current.requestId });
|
|
504
|
-
}
|
|
505
|
-
try {
|
|
506
|
-
await write(current, outcome);
|
|
507
|
-
}
|
|
508
|
-
catch (error) {
|
|
509
|
-
this.logger.warn(`after-commit ${current.id}: could not record ${outcome.state}: ${error.message}`);
|
|
510
|
-
}
|
|
511
|
-
return outcome.state;
|
|
597
|
+
async #performOutbox(record, services, principal, requestId) {
|
|
598
|
+
return performOutbox(outboxStore(this.instance.handle("app")), record.id, (claim, complete) => {
|
|
599
|
+
const effect = claim.effect;
|
|
600
|
+
// A job or webhook event is created in the transaction that records it done; a notification is sent directly.
|
|
601
|
+
if (effect.service === "jobs")
|
|
602
|
+
return this.#services.performInTransaction({ service: "jobs", type: effect.type, payload: effect.payload, ...(effect.options ? { options: effect.options } : {}) }, principal, requestId, complete);
|
|
603
|
+
if (effect.service === "webhooks")
|
|
604
|
+
return this.#services.performInTransaction({ service: "webhooks", type: effect.type, payload: effect.payload }, principal, requestId, complete);
|
|
605
|
+
return performEffect(services, claim);
|
|
606
|
+
}, { warn: (message) => this.logger.warn(message, { outboxId: record.id, requestId: record.requestId }) });
|
|
512
607
|
}
|
|
513
608
|
/**
|
|
514
609
|
* After-commit effects whose process stopped before performing them (pending past
|
|
515
|
-
* OUTBOX_RECOVER_AFTER_MS, or performing
|
|
516
|
-
* current principal. A caller that can no longer be resolved fails the record.
|
|
610
|
+
* OUTBOX_RECOVER_AFTER_MS, or performing past OUTBOX_PERFORMING_STALE_MS), performed as the
|
|
611
|
+
* caller's current principal. A caller that can no longer be resolved fails the record.
|
|
517
612
|
*/
|
|
518
613
|
async recoverOutbox(now = Date.now()) {
|
|
519
614
|
const store = this.instance.handle("app");
|
|
520
|
-
const
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
];
|
|
615
|
+
const outbox = store.collection(OUTBOX_COLLECTION);
|
|
616
|
+
const read = async (state) => (await readAll(store, { collection: OUTBOX_COLLECTION, where: [{ field: "state", eq: state }] }));
|
|
617
|
+
const stale = [...(await read("pending")), ...(await read("performing"))].filter((r) => isRecoverable(r, now));
|
|
524
618
|
let performed = 0;
|
|
525
619
|
for (const record of stale) {
|
|
526
620
|
const principal = await this.#resolveDurable(record.principalId);
|
|
527
621
|
if (!principal) {
|
|
528
|
-
const { __version, ...fields } = record;
|
|
529
622
|
await store
|
|
530
|
-
.transaction({ operations: [{ collection: OUTBOX_COLLECTION, id: record.id, ifVersion: __version, value:
|
|
623
|
+
.transaction({ operations: [{ collection: OUTBOX_COLLECTION, id: record.id, ifVersion: record.__version, value: settled(record, { ok: false, error: { code: "UNAUTHORIZED", message: `${record.principalId} could not be resolved to a current principal (no active session or API key), so the effect was not performed.` } }, Date.now()) }] })
|
|
531
624
|
.catch(() => undefined);
|
|
532
625
|
continue;
|
|
533
626
|
}
|
|
@@ -535,7 +628,7 @@ export class FeltKitRuntime {
|
|
|
535
628
|
const release = this.#services.enter(requestId, principal);
|
|
536
629
|
try {
|
|
537
630
|
const services = explainServiceDenials(this.#services.bind(principal, requestId, new Set(), true), record.function, principal, this.#authority);
|
|
538
|
-
if ((await this.#performOutbox(record, services)) === "done")
|
|
631
|
+
if ((await this.#performOutbox(record, services, principal, requestId)) === "done")
|
|
539
632
|
performed += 1;
|
|
540
633
|
}
|
|
541
634
|
finally {
|
|
@@ -544,10 +637,51 @@ export class FeltKitRuntime {
|
|
|
544
637
|
}
|
|
545
638
|
return performed;
|
|
546
639
|
}
|
|
640
|
+
/** After-commit effects, newest first (optionally only those in `state`). */
|
|
641
|
+
async listOutbox(filter = {}) {
|
|
642
|
+
const rows = (await this.instance.handle("app").collection(OUTBOX_COLLECTION).find((filter.state ? { state: filter.state } : {})));
|
|
643
|
+
return rows
|
|
644
|
+
.map(({ __version: _v, ...r }) => r)
|
|
645
|
+
.sort((a, b) => b.createdAt - a.createdAt)
|
|
646
|
+
.slice(0, filter.limit ?? 100);
|
|
647
|
+
}
|
|
648
|
+
/**
|
|
649
|
+
* An operator's retry of a failed after-commit effect: back to pending (attempts and last error
|
|
650
|
+
* kept), then performed now as its caller, or by the worker if that caller cannot be resolved.
|
|
651
|
+
*/
|
|
652
|
+
async retryOutbox(id, by) {
|
|
653
|
+
this.#assertReady();
|
|
654
|
+
const store = this.instance.handle("app");
|
|
655
|
+
const outbox = store.collection(OUTBOX_COLLECTION);
|
|
656
|
+
const record = await outbox.get(id).catch(() => null);
|
|
657
|
+
if (!record)
|
|
658
|
+
throw new FeltKitError("NOT_FOUND", `No after-commit effect ${id}.`);
|
|
659
|
+
const next = retried(record, by, Date.now());
|
|
660
|
+
try {
|
|
661
|
+
await store.transaction({ operations: [{ collection: OUTBOX_COLLECTION, id, ifVersion: record.__version, value: next }] });
|
|
662
|
+
}
|
|
663
|
+
catch {
|
|
664
|
+
throw new FeltKitError("CONFLICT", `After-commit effect ${id} changed while it was being retried. Nothing was changed; read it again.`);
|
|
665
|
+
}
|
|
666
|
+
const principal = await this.#resolveDurable(record.principalId);
|
|
667
|
+
if (principal) {
|
|
668
|
+
const requestId = `outbox_${id}_retry`;
|
|
669
|
+
const release = this.#services.enter(requestId, principal);
|
|
670
|
+
try {
|
|
671
|
+
const services = explainServiceDenials(this.#services.bind(principal, requestId, new Set(), true), record.function, principal, this.#authority);
|
|
672
|
+
await this.#performOutbox(next, services, principal, requestId);
|
|
673
|
+
}
|
|
674
|
+
finally {
|
|
675
|
+
release();
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
const { __version: _v, ...after } = (await outbox.get(id));
|
|
679
|
+
return after;
|
|
680
|
+
}
|
|
547
681
|
/** Drive durable service work once (jobs, schedules, webhook deliveries, recovered after-commit effects). */
|
|
548
682
|
runServices() {
|
|
549
|
-
if (this.#state !== "ready")
|
|
550
|
-
return Promise.resolve({ jobs: 0, deliveries: 0, scheduled: 0 });
|
|
683
|
+
if (this.#state !== "ready" || this.#paused)
|
|
684
|
+
return Promise.resolve({ jobs: 0, deliveries: 0, scheduled: 0, failed: { jobs: 0, deliveries: 0 } });
|
|
551
685
|
if (this.#ticking)
|
|
552
686
|
return this.#ticking;
|
|
553
687
|
const run = Promise.all([
|
|
@@ -558,7 +692,7 @@ export class FeltKitRuntime {
|
|
|
558
692
|
}),
|
|
559
693
|
]).then(([tick]) => tick).catch((error) => {
|
|
560
694
|
this.logger.warn(`services worker: ${error.message}`);
|
|
561
|
-
return { jobs: 0, deliveries: 0, scheduled: 0 };
|
|
695
|
+
return { jobs: 0, deliveries: 0, scheduled: 0, failed: { jobs: 0, deliveries: 0 } };
|
|
562
696
|
});
|
|
563
697
|
this.#ticking = run.finally(() => (this.#ticking = undefined));
|
|
564
698
|
this.#inflight.add(this.#ticking);
|
|
@@ -692,7 +826,8 @@ export class FeltKitRuntime {
|
|
|
692
826
|
}
|
|
693
827
|
/** Run a query or mutation as `principal`. Authority is checked before the handler runs. */
|
|
694
828
|
call(name, rawArgs, options) {
|
|
695
|
-
|
|
829
|
+
// While a backup reads the state, new calls wait for it (see backup()).
|
|
830
|
+
const promise = this.#paused ? this.#paused.then(() => this.#call(name, rawArgs, options)) : this.#call(name, rawArgs, options);
|
|
696
831
|
this.#inflight.add(promise);
|
|
697
832
|
return promise.finally(() => this.#inflight.delete(promise));
|
|
698
833
|
}
|
|
@@ -727,6 +862,10 @@ export class FeltKitRuntime {
|
|
|
727
862
|
return failure(new FeltKitError("UNAVAILABLE", `The runtime is ${this.#state}.`));
|
|
728
863
|
if (!fn)
|
|
729
864
|
return failure(new FeltKitError("FUNCTION_NOT_FOUND", `No query or mutation named "${name}".`, { hint: "Function names are \"<module>:<export>\", e.g. \"tasks:list\"." }));
|
|
865
|
+
// Never hand stored records to code that declares a different schema for them.
|
|
866
|
+
if (this.schema?.status === "blocked") {
|
|
867
|
+
return failure(new FeltKitError("CONFIGURATION", `The application's schema changed and the stored data has not been migrated: ${this.schema.plan.reason ?? "run `feltkit migrate`"}. No function runs until it is.`, { hint: blockedHint(this.schema.plan) }));
|
|
868
|
+
}
|
|
730
869
|
// Authority first, then the arguments: a caller that may not run the function learns
|
|
731
870
|
// nothing about its input contract, gets FORBIDDEN (not INVALID_ARGUMENT, which invites a
|
|
732
871
|
// corrected retry), and the attempt is recorded as a denial. `access` is a permission,
|
|
@@ -749,6 +888,15 @@ export class FeltKitRuntime {
|
|
|
749
888
|
if (!decision.allowed) {
|
|
750
889
|
return failure(new FeltKitError(decision.code ?? "FORBIDDEN", decision.reason ?? "Not allowed"), { authority: authorityRecord, argKeys: argKeys(rawArgs) });
|
|
751
890
|
}
|
|
891
|
+
// The approval requirement, at the execution boundary every interface goes through (/api,
|
|
892
|
+
// AppPort, MCP, jobs, decisions): permission alone is not enough for a non-person caller.
|
|
893
|
+
const approvalRefusal = this.#approvalRefusal(name, fn, principal);
|
|
894
|
+
if (approvalRefusal) {
|
|
895
|
+
return failure(new FeltKitError("FORBIDDEN", approvalRefusal, { details: { approval: "required" }, hint: "Ask a person to run it, or propose it and wait for their approval." }), { authority: { ...authorityRecord, allowed: false, reason: "approval required" }, argKeys: argKeys(rawArgs) });
|
|
896
|
+
}
|
|
897
|
+
const approvedAction = fn.approval === "required" && principal?.type !== "user" ? this.#approvedAction.getStore() : undefined;
|
|
898
|
+
if (approvedAction)
|
|
899
|
+
Object.assign(authorityRecord, { approval: { taskId: approvedAction.taskId, actionId: approvedAction.actionId, approvedBy: approvedAction.approvedBy } });
|
|
752
900
|
const parsed = validate(fn.argsSchema, rawArgs ?? {});
|
|
753
901
|
if (!parsed.ok) {
|
|
754
902
|
return failure(new FeltKitError("INVALID_ARGUMENT", `Invalid arguments for ${name}: ${parsed.issues.map((i) => `${i.path}: ${i.message}`).join("; ")}`, { details: { issues: parsed.issues } }), {
|
|
@@ -758,85 +906,124 @@ export class FeltKitRuntime {
|
|
|
758
906
|
}
|
|
759
907
|
const args = parsed.value;
|
|
760
908
|
const handle = this.instance.handle("app");
|
|
761
|
-
const db = fn.kind === "mutation" ? new Writer(handle, this.#resolver) : new Reader(handle, this.#resolver);
|
|
762
909
|
const release = this.#services.enter(requestId, principal);
|
|
763
910
|
const servicesUsed = new Set();
|
|
764
|
-
const shared = {
|
|
765
|
-
auth: authContext(this.#authority, principal),
|
|
766
|
-
services: explainServiceDenials(this.#services.bind(principal, requestId, db.reads, fn.kind === "mutation", servicesUsed), name, principal, this.#authority),
|
|
767
|
-
environment: { name: this.environment.name, production: this.environment.production, storage: describeStorage(this.environment.storage) },
|
|
768
|
-
requestId,
|
|
769
|
-
log: this.logger,
|
|
770
|
-
};
|
|
771
|
-
const starts = [];
|
|
772
|
-
const agent = {
|
|
773
|
-
start: (input) => {
|
|
774
|
-
if (!principal)
|
|
775
|
-
throw new FeltKitError("UNAUTHORIZED", "Starting agent work needs a signed-in caller.");
|
|
776
|
-
if (!this.#authority.permissionsFor(principal).some((g) => g === "*" || g === "feltkit.*" || g === "feltkit.agent.*" || g === "feltkit.agent.write")) {
|
|
777
|
-
throw new FeltKitError("FORBIDDEN", `${principal.id} may not start agent work (needs feltkit.agent.write).`);
|
|
778
|
-
}
|
|
779
|
-
const taskId = `task-${randomUUID()}`;
|
|
780
|
-
starts.push({ taskId, objective: String(input?.objective ?? ""), decision: input?.decision, ...(input?.subject ? { subject: input.subject } : {}) });
|
|
781
|
-
return { taskId };
|
|
782
|
-
},
|
|
783
|
-
};
|
|
784
911
|
const enabled = this.app.options.services ?? {};
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
912
|
+
// One attempt: a fresh ctx.db, ctx.services binding and outbox staging. Only a mutation that
|
|
913
|
+
// opted in (`retry: { sequenceConflicts }`) has more than one (runtime/transactions.ts).
|
|
914
|
+
const attempt = async () => {
|
|
915
|
+
const db = fn.kind === "mutation" ? new Writer(handle, this.#resolver) : new Reader(handle, this.#resolver);
|
|
916
|
+
const used = new Set();
|
|
917
|
+
const shared = {
|
|
918
|
+
auth: authContext(this.#authority, principal),
|
|
919
|
+
services: explainServiceDenials(this.#services.bind(principal, requestId, db.reads, fn.kind === "mutation", used), name, principal, this.#authority),
|
|
920
|
+
environment: { name: this.environment.name, production: this.environment.production, storage: describeStorage(this.environment.storage) },
|
|
789
921
|
requestId,
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
922
|
+
log: this.logger,
|
|
923
|
+
};
|
|
924
|
+
const starts = [];
|
|
925
|
+
const agent = {
|
|
926
|
+
start: (input) => {
|
|
927
|
+
if (!principal)
|
|
928
|
+
throw new FeltKitError("UNAUTHORIZED", "Starting agent work needs a signed-in caller.");
|
|
929
|
+
if (!this.#authority.permissionsFor(principal).some((g) => g === "*" || g === "feltkit.*" || g === "feltkit.agent.*" || g === "feltkit.agent.write")) {
|
|
930
|
+
throw new FeltKitError("FORBIDDEN", `${principal.id} may not start agent work (needs feltkit.agent.write).`);
|
|
931
|
+
}
|
|
932
|
+
const taskId = `task-${randomUUID()}`;
|
|
933
|
+
starts.push({ taskId, objective: String(input?.objective ?? ""), decision: input?.decision, ...(input?.subject ? { subject: input.subject } : {}) });
|
|
934
|
+
return { taskId };
|
|
935
|
+
},
|
|
936
|
+
};
|
|
937
|
+
const effects = db instanceof Writer
|
|
938
|
+
? afterCommit({
|
|
939
|
+
caller: name,
|
|
940
|
+
principal,
|
|
941
|
+
requestId,
|
|
942
|
+
enabled: { notifications: Boolean(enabled.notifications), webhooks: Boolean(enabled.webhooks), jobs: Boolean(enabled.jobs) },
|
|
943
|
+
stage: (record) => db.stageSystem(OUTBOX_COLLECTION, record),
|
|
944
|
+
newId: newOutboxId,
|
|
945
|
+
})
|
|
946
|
+
: null;
|
|
947
|
+
const ctx = fn.kind === "mutation" ? { ...shared, db, agent, afterCommit: effects, unsafe: { feltdb: this.instance.handle("app.unsafe") } } : { ...shared, db };
|
|
948
|
+
try {
|
|
949
|
+
const value = await fn.handler(ctx, args);
|
|
950
|
+
if (fn.returns) {
|
|
951
|
+
const output = validate(fn.returns, value);
|
|
952
|
+
if (!output.ok) {
|
|
953
|
+
throw new FeltKitError("INTERNAL", `${name} returned a value that does not match its \`returns\` schema: ${output.issues.map((i) => `${i.path}: ${i.message}`).join("; ")}`);
|
|
954
|
+
}
|
|
801
955
|
}
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
});
|
|
808
|
-
if (commit.writes.length)
|
|
809
|
-
void this.changes.check();
|
|
810
|
-
// Agent work starts only once the mutation's writes are durable.
|
|
811
|
-
for (const start of starts)
|
|
812
|
-
this.#agent?.startAfterCommit(start, principal);
|
|
813
|
-
// So do after-commit effects: performed now, as the caller, while its binding is live.
|
|
814
|
-
const outbox = db.staged.filter((r) => r.collection === OUTBOX_COLLECTION).map((r) => r.value);
|
|
815
|
-
if (outbox.length) {
|
|
816
|
-
const bound = explainServiceDenials(this.#services.bind(principal, requestId, new Set(), true, servicesUsed), name, principal, this.#authority);
|
|
817
|
-
for (const record of outbox)
|
|
818
|
-
await this.#performOutbox(record, bound);
|
|
956
|
+
let commit;
|
|
957
|
+
if (db instanceof Writer) {
|
|
958
|
+
commit = await db.commit(options.idempotencyReplayKey ? idempotentTransactionId(options.idempotencyReplayKey) : requestId, {
|
|
959
|
+
keyed: options.idempotencyReplayKey !== undefined,
|
|
960
|
+
});
|
|
819
961
|
}
|
|
962
|
+
return { value, db, commit, starts, used };
|
|
820
963
|
}
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
964
|
+
catch (error) {
|
|
965
|
+
throw Object.assign(new AttemptFailed(error), { db, used });
|
|
966
|
+
}
|
|
967
|
+
finally {
|
|
968
|
+
for (const service of used)
|
|
969
|
+
servicesUsed.add(service);
|
|
970
|
+
}
|
|
971
|
+
};
|
|
972
|
+
let reads = [];
|
|
973
|
+
let retries = 0;
|
|
974
|
+
try {
|
|
975
|
+
for (;;) {
|
|
976
|
+
let outcome;
|
|
977
|
+
try {
|
|
978
|
+
outcome = await attempt();
|
|
979
|
+
}
|
|
980
|
+
catch (failed) {
|
|
981
|
+
const { error, db, used } = failed;
|
|
982
|
+
reads = [...db.reads];
|
|
983
|
+
const conflict = isFeltKitError(error) && error.code === "CONFLICT" && isSequenceConflict(error.details?.failure);
|
|
984
|
+
if (conflict && fn.retry && retries < fn.retry.sequenceConflicts && used.size === 0) {
|
|
985
|
+
retries += 1;
|
|
986
|
+
continue;
|
|
833
987
|
}
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
988
|
+
throw error;
|
|
989
|
+
}
|
|
990
|
+
const { value, db, commit, starts } = outcome;
|
|
991
|
+
reads = [...db.reads];
|
|
992
|
+
if (db instanceof Writer && commit) {
|
|
993
|
+
if (commit.writes.length)
|
|
994
|
+
void this.changes.check();
|
|
995
|
+
// Agent work starts only once the mutation's writes are durable.
|
|
996
|
+
for (const start of starts)
|
|
997
|
+
this.#agent?.startAfterCommit(start, principal);
|
|
998
|
+
// So do after-commit effects: performed now, as the caller, while its binding is live.
|
|
999
|
+
const outbox = db.staged.filter((r) => r.collection === OUTBOX_COLLECTION).map((r) => r.value);
|
|
1000
|
+
if (outbox.length) {
|
|
1001
|
+
const bound = explainServiceDenials(this.#services.bind(principal, requestId, new Set(), true, servicesUsed), name, principal, this.#authority);
|
|
1002
|
+
for (const record of outbox)
|
|
1003
|
+
await this.#performOutbox(record, bound, principal, requestId);
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
finish({
|
|
1007
|
+
outcome: "success",
|
|
1008
|
+
authority: authorityRecord,
|
|
1009
|
+
argKeys: Object.keys(args),
|
|
1010
|
+
reads,
|
|
1011
|
+
...(servicesUsed.size ? { services: [...servicesUsed] } : {}),
|
|
1012
|
+
...(retries ? { detail: { sequenceRetries: retries } } : {}),
|
|
1013
|
+
...(commit && commit.writes.length
|
|
1014
|
+
? {
|
|
1015
|
+
writes: commit.writes,
|
|
1016
|
+
transactionId: commit.transactionId,
|
|
1017
|
+
...(commit.commitRevision !== undefined ? { commitRevision: commit.commitRevision } : {}),
|
|
1018
|
+
...(commit.revisionId ? { revisionId: commit.revisionId } : {}),
|
|
1019
|
+
}
|
|
1020
|
+
: {}),
|
|
1021
|
+
});
|
|
1022
|
+
return { ok: true, value: value === undefined ? null : value, reads, requestId };
|
|
1023
|
+
}
|
|
837
1024
|
}
|
|
838
1025
|
catch (error) {
|
|
839
|
-
return failure(error, { authority: authorityRecord, argKeys: Object.keys(args), reads
|
|
1026
|
+
return failure(error, { authority: authorityRecord, argKeys: Object.keys(args), reads, ...(servicesUsed.size ? { services: [...servicesUsed] } : {}), ...(retries ? { detail: { sequenceRetries: retries } } : {}) });
|
|
840
1027
|
}
|
|
841
1028
|
finally {
|
|
842
1029
|
release();
|
|
@@ -871,7 +1058,7 @@ export class FeltKitRuntime {
|
|
|
871
1058
|
overview() {
|
|
872
1059
|
const storage = describeStorage(this.environment.storage);
|
|
873
1060
|
return {
|
|
874
|
-
application: { name: this.app.name, version: this.app.
|
|
1061
|
+
application: { name: this.app.name, version: this.app.version, description: this.app.options.description ?? null },
|
|
875
1062
|
state: this.#state,
|
|
876
1063
|
startedAt: this.startedAt,
|
|
877
1064
|
generation: this.#generation,
|
|
@@ -889,6 +1076,35 @@ export class FeltKitRuntime {
|
|
|
889
1076
|
};
|
|
890
1077
|
}
|
|
891
1078
|
/** Stop accepting calls, wait for in-flight work, flush the activity log, release the instance. */
|
|
1079
|
+
/**
|
|
1080
|
+
* This environment's backup (docs/BACKUP.md), application-consistent: new calls and the services
|
|
1081
|
+
* worker wait while it reads, and the calls in flight finish first, so it holds each committed
|
|
1082
|
+
* transaction entirely or not at all.
|
|
1083
|
+
*/
|
|
1084
|
+
/** This environment's backup as lines in memory (small stores, tests); backupTo streams it. */
|
|
1085
|
+
async backup() {
|
|
1086
|
+
const lines = [];
|
|
1087
|
+
await this.backupTo((line) => void lines.push(line));
|
|
1088
|
+
return lines;
|
|
1089
|
+
}
|
|
1090
|
+
/** Write this environment's backup line by line to `sink`, with calls and the services worker paused while it reads. */
|
|
1091
|
+
async backupTo(sink) {
|
|
1092
|
+
this.#assertReady();
|
|
1093
|
+
if (this.environment.storage.kind !== "local")
|
|
1094
|
+
throw remoteBackupRefusal();
|
|
1095
|
+
while (this.#paused)
|
|
1096
|
+
await this.#paused;
|
|
1097
|
+
let release;
|
|
1098
|
+
this.#paused = new Promise((resolve) => (release = resolve));
|
|
1099
|
+
try {
|
|
1100
|
+
await Promise.allSettled([...this.#inflight]);
|
|
1101
|
+
return (await writeBackup(this.instance.handle("feltkit.backup"), backupMeta(this.app, this.environment.name), sink)).header;
|
|
1102
|
+
}
|
|
1103
|
+
finally {
|
|
1104
|
+
this.#paused = null;
|
|
1105
|
+
release();
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
892
1108
|
async close() {
|
|
893
1109
|
if (this.#state === "closed" || this.#state === "closing")
|
|
894
1110
|
return;
|
|
@@ -912,6 +1128,18 @@ function argKeys(value) {
|
|
|
912
1128
|
function toAppPort(principal) {
|
|
913
1129
|
return { id: principal.id, type: principal.type === "agent" ? "application" : principal.type, attributes: { roles: principal.roles, feltkitType: principal.type } };
|
|
914
1130
|
}
|
|
1131
|
+
/**
|
|
1132
|
+
* HTTP status for the AppPort codes FeltKit itself returns that AppPort's HTTP binding does not
|
|
1133
|
+
* know (its table answers 500 for any code outside the standard set). Derived from statusFor,
|
|
1134
|
+
* so /api and /appport answer the same status for the same failure.
|
|
1135
|
+
*/
|
|
1136
|
+
export const FELTKIT_APPPORT_STATUS = {
|
|
1137
|
+
"feltkit.FAILED_PRECONDITION": statusFor("FAILED_PRECONDITION"),
|
|
1138
|
+
UPSTREAM_REJECTED: statusFor("UPSTREAM_REJECTED"),
|
|
1139
|
+
OUTCOME_UNKNOWN: statusFor("OUTCOME_UNKNOWN"),
|
|
1140
|
+
UNAVAILABLE: statusFor("UNAVAILABLE"),
|
|
1141
|
+
NOT_CONFIGURED: statusFor("CONFIGURATION"),
|
|
1142
|
+
};
|
|
915
1143
|
function toAppPortError(error) {
|
|
916
1144
|
switch (error.code) {
|
|
917
1145
|
case "UNAUTHORIZED":
|
|
@@ -925,7 +1153,7 @@ function toAppPortError(error) {
|
|
|
925
1153
|
case "FUNCTION_NOT_FOUND":
|
|
926
1154
|
return appportErrors.notFound(error.message);
|
|
927
1155
|
case "CONFLICT":
|
|
928
|
-
return
|
|
1156
|
+
return new AppPortError("CONFLICT", error.message, { retryable: error.retryable === true });
|
|
929
1157
|
// AppPort has no standard code for it: an extension code, never retryable.
|
|
930
1158
|
case "FAILED_PRECONDITION":
|
|
931
1159
|
return new AppPortError("feltkit.FAILED_PRECONDITION", error.message, { retryable: false, details: (error.details ?? null) });
|
|
@@ -936,6 +1164,12 @@ function toAppPortError(error) {
|
|
|
936
1164
|
return new AppPortError("OUTCOME_UNKNOWN", error.message, { retryable: false, details: (error.details ?? null) });
|
|
937
1165
|
case "UNAVAILABLE":
|
|
938
1166
|
return new AppPortError("UNAVAILABLE", error.message, { retryable: true, details: (error.details ?? null) });
|
|
1167
|
+
// An external API refused the request: its identity and status survive, never retryable.
|
|
1168
|
+
case "UPSTREAM_REJECTED":
|
|
1169
|
+
return new AppPortError("UPSTREAM_REJECTED", error.message, { retryable: false, details: (error.details ?? null) });
|
|
1170
|
+
// The server lacks something an operator must provide (a credential, a URL): not retryable.
|
|
1171
|
+
case "CONFIGURATION":
|
|
1172
|
+
return new AppPortError("NOT_CONFIGURED", error.message, { retryable: false, details: { hint: error.hint ?? null } });
|
|
939
1173
|
default:
|
|
940
1174
|
return appportErrors.internal(error.message);
|
|
941
1175
|
}
|
|
@@ -973,4 +1207,11 @@ function emailChannelClass() {
|
|
|
973
1207
|
}
|
|
974
1208
|
return channel;
|
|
975
1209
|
}
|
|
1210
|
+
/** A failed attempt of a function call, carrying what it read and which services it used. */
|
|
1211
|
+
class AttemptFailed {
|
|
1212
|
+
error;
|
|
1213
|
+
constructor(error) {
|
|
1214
|
+
this.error = error;
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
976
1217
|
//# sourceMappingURL=runtime.js.map
|