@feltdb/feltkit 0.3.10 → 0.3.12
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/app.d.ts +86 -3
- package/dist/app.js +63 -2
- package/dist/app.js.map +1 -1
- package/dist/appboundry/build.d.ts +39 -1
- package/dist/appboundry/build.js +77 -7
- package/dist/appboundry/build.js.map +1 -1
- package/dist/appboundry/guest.js +79 -2
- package/dist/appboundry/guest.js.map +1 -1
- package/dist/appboundry/host.d.ts +44 -0
- package/dist/appboundry/host.js +456 -0
- package/dist/appboundry/host.js.map +1 -0
- 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.js +459 -8
- package/dist/cli/main.js.map +1 -1
- package/dist/cli/skills.d.ts +8 -0
- package/dist/cli/skills.js +37 -0
- package/dist/cli/skills.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/errors.d.ts +7 -1
- package/dist/errors.js +1 -0
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js.map +1 -1
- package/dist/platform/changes.d.ts +340 -0
- package/dist/platform/changes.js +353 -0
- package/dist/platform/changes.js.map +1 -0
- package/dist/platform/deployments.d.ts +653 -0
- package/dist/platform/deployments.js +530 -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/backup-environment.d.ts +25 -0
- package/dist/runtime/backup-environment.js +60 -0
- package/dist/runtime/backup-environment.js.map +1 -0
- package/dist/runtime/backup.d.ts +87 -0
- package/dist/runtime/backup.js +175 -0
- package/dist/runtime/backup.js.map +1 -0
- package/dist/runtime/capabilities.d.ts +1 -1
- package/dist/runtime/capabilities.js +19 -2
- package/dist/runtime/capabilities.js.map +1 -1
- package/dist/runtime/context.d.ts +7 -0
- package/dist/runtime/contract.js +5 -1
- package/dist/runtime/contract.js.map +1 -1
- package/dist/runtime/data.d.ts +28 -0
- package/dist/runtime/data.js +49 -1
- package/dist/runtime/data.js.map +1 -1
- package/dist/runtime/instance.js +17 -0
- package/dist/runtime/instance.js.map +1 -1
- package/dist/runtime/loader.js +6 -2
- 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 +7 -0
- package/dist/runtime/outbox.js +47 -0
- package/dist/runtime/outbox.js.map +1 -0
- package/dist/runtime/readiness.js +12 -0
- package/dist/runtime/readiness.js.map +1 -1
- package/dist/runtime/runtime.d.ts +65 -1
- package/dist/runtime/runtime.js +380 -66
- package/dist/runtime/runtime.js.map +1 -1
- package/dist/runtime/services.d.ts +30 -0
- package/dist/runtime/services.js +82 -1
- package/dist/runtime/services.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 +42 -2
- package/dist/schema.js +58 -2
- package/dist/schema.js.map +1 -1
- package/dist/server/admin.d.ts +1 -0
- package/dist/server/admin.js +27 -0
- package/dist/server/admin.js.map +1 -1
- package/dist/server/index.d.ts +4 -0
- package/dist/server/index.js +45 -1
- package/dist/server/index.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 +24 -0
- package/dist/testing/index.js +31 -0
- package/dist/testing/index.js.map +1 -1
- package/package.json +5 -5
- package/skills/.claude-plugin/marketplace.json +1 -1
- package/skills/.claude-plugin/plugin.json +1 -1
- package/skills/feltkit-agent/SKILL.md +1 -1
- package/skills/feltkit-build/SKILL.md +33 -2
- package/skills/feltkit-data/SKILL.md +12 -1
- package/skills/feltkit-operations/SKILL.md +1 -1
- package/skills/feltkit-services/SKILL.md +22 -2
package/dist/runtime/runtime.js
CHANGED
|
@@ -8,12 +8,16 @@
|
|
|
8
8
|
* close() is idempotent and releases the instance.
|
|
9
9
|
*/
|
|
10
10
|
import { AppPortError, createApplication, defineCapability, createMcpBridge, errors as appportErrors, idempotencyStorageKey } from "@appport/sdk";
|
|
11
|
+
import { grantsPermission } from "@appport/authorization";
|
|
12
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
11
13
|
import { performance } from "node:perf_hooks";
|
|
12
14
|
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
13
15
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
14
16
|
import { dirname, join } from "node:path";
|
|
15
17
|
import { IntegrationHost, integrationDescriptor } from "./integrations.js";
|
|
16
18
|
import { verifyStorage } from "./storage-check.js";
|
|
19
|
+
import { assertNotPartiallyRestored, backupLines } from "./backup.js";
|
|
20
|
+
import { backupMeta, remoteBackupRefusal } from "./backup-environment.js";
|
|
17
21
|
import { FeltKitError, isFeltKitError } from "../errors.js";
|
|
18
22
|
import { validate } from "../schema.js";
|
|
19
23
|
import { ActivityLog, errorSummary } from "./activity.js";
|
|
@@ -23,7 +27,10 @@ import { ModelHost } from "./decisions.js";
|
|
|
23
27
|
import { CollectionResolver, Reader, Writer, ensureCollectionMarkers, feltdbRefusalJSON } from "./data.js";
|
|
24
28
|
import { describeStorage } from "./environment.js";
|
|
25
29
|
import { defaultInstanceFactory } from "./instance.js";
|
|
26
|
-
import { ServicesHost } from "./services.js";
|
|
30
|
+
import { explainServiceDenials, ServicesHost } from "./services.js";
|
|
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";
|
|
27
34
|
import { credentialsFor, isCustodyError } from "./credentials.js";
|
|
28
35
|
import { AgentHost } from "./agent.js";
|
|
29
36
|
import { FeltDbIdempotencyStore } from "./idempotency.js";
|
|
@@ -78,6 +85,8 @@ export class FeltKitRuntime {
|
|
|
78
85
|
#resolver;
|
|
79
86
|
#state = "starting";
|
|
80
87
|
#inflight = new Set();
|
|
88
|
+
/** Set while backup() reads the state: calls and the services worker wait for it. */
|
|
89
|
+
#paused = null;
|
|
81
90
|
#dispatched = new Set();
|
|
82
91
|
#generation = 0;
|
|
83
92
|
#reloadListeners = new Set();
|
|
@@ -135,7 +144,12 @@ export class FeltKitRuntime {
|
|
|
135
144
|
// Verify the instance answers (on a server: this key reads, writes, and matches the
|
|
136
145
|
// active contract) before declaring the runtime ready.
|
|
137
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"));
|
|
138
149
|
step("storage");
|
|
150
|
+
runtime.#migrate = options.migrate ?? "auto";
|
|
151
|
+
await runtime.#ensureSchema(options.project.app, "start");
|
|
152
|
+
step("schema");
|
|
139
153
|
await ensureCollectionMarkers(instance.handle("feltkit.runtime"), options.project.app.collections.keys());
|
|
140
154
|
step("markers");
|
|
141
155
|
await runtime.#services.check();
|
|
@@ -221,6 +235,87 @@ export class FeltKitRuntime {
|
|
|
221
235
|
return () => this.#reloadListeners.delete(listener);
|
|
222
236
|
}
|
|
223
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 this.instance.handle("feltkit.schema").collection(MIGRATIONS_COLLECTION).find({}));
|
|
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
|
+
}
|
|
224
319
|
async reload(project) {
|
|
225
320
|
this.#assertReady();
|
|
226
321
|
if (project.app.name !== this.#project.app.name) {
|
|
@@ -229,6 +324,7 @@ export class FeltKitRuntime {
|
|
|
229
324
|
await ensureCollectionMarkers(this.instance.handle("feltkit.runtime"), project.app.collections.keys());
|
|
230
325
|
const previous = this.#appport;
|
|
231
326
|
this.#install(project);
|
|
327
|
+
await this.#ensureSchema(project.app, "reload");
|
|
232
328
|
this.#agent?.define();
|
|
233
329
|
await previous.close().catch(() => undefined);
|
|
234
330
|
for (const listener of this.#reloadListeners)
|
|
@@ -302,6 +398,11 @@ export class FeltKitRuntime {
|
|
|
302
398
|
mode: this.environment.production ? "production" : "development",
|
|
303
399
|
telemetry: { record: (entry) => this.#telemetry(entry) },
|
|
304
400
|
});
|
|
401
|
+
// Every transport (HTTP, WebSocket, MCP) dispatches through these two methods.
|
|
402
|
+
for (const method of ["handleRequest", "handleStreamRequest"]) {
|
|
403
|
+
const original = appport[method].bind(appport);
|
|
404
|
+
appport[method] = (request, options = {}) => this.#appportCaller.run({ principal: fromAppPortPrincipal(options?.principal ?? options?.session?.principal) }, () => original(request, options));
|
|
405
|
+
}
|
|
305
406
|
this.#project = project;
|
|
306
407
|
this.#authority = authority;
|
|
307
408
|
this.#services = services;
|
|
@@ -350,6 +451,23 @@ export class FeltKitRuntime {
|
|
|
350
451
|
},
|
|
351
452
|
});
|
|
352
453
|
}
|
|
454
|
+
/** The caller of the AppPort request being dispatched (see #gate). */
|
|
455
|
+
#appportCaller = new AsyncLocalStorage();
|
|
456
|
+
/**
|
|
457
|
+
* Authority before arguments on AppPort and MCP too: AppPort validates input before it
|
|
458
|
+
* consults the authorizer, so a capability's input schema runs this check first, from the
|
|
459
|
+
* same policy (roles → permissions). FeltKit's own call path authorizes again.
|
|
460
|
+
*/
|
|
461
|
+
#gate(fn) {
|
|
462
|
+
const scope = this.#appportCaller.getStore();
|
|
463
|
+
if (!scope || fn.access === "public")
|
|
464
|
+
return;
|
|
465
|
+
if (!scope.principal)
|
|
466
|
+
throw appportErrors.unauthorized("Authentication is required");
|
|
467
|
+
const required = Authority.required(fn.access);
|
|
468
|
+
if (required.length && !grantsPermission(this.#authority.permissionsFor(scope.principal), required[0]))
|
|
469
|
+
throw appportErrors.forbidden(`Missing permission: ${required[0]}`);
|
|
470
|
+
}
|
|
353
471
|
#capabilityFor(name, fn) {
|
|
354
472
|
const exposure = fn.capability;
|
|
355
473
|
return capabilityDefinition(name, fn, async (input, context) => {
|
|
@@ -367,7 +485,7 @@ export class FeltKitRuntime {
|
|
|
367
485
|
if (result.ok)
|
|
368
486
|
return result.value;
|
|
369
487
|
throw toAppPortError(result.error);
|
|
370
|
-
});
|
|
488
|
+
}, () => this.#gate(fn));
|
|
371
489
|
}
|
|
372
490
|
/** AppPort refuses some calls before FeltKit's handler runs (bad input, missing permission). Record those too. */
|
|
373
491
|
#telemetry(entry) {
|
|
@@ -446,13 +564,111 @@ export class FeltKitRuntime {
|
|
|
446
564
|
const session = (await this.sessions.list()).find((s) => s.principal?.id === subjectId);
|
|
447
565
|
return session?.principal ?? null;
|
|
448
566
|
}
|
|
449
|
-
/**
|
|
567
|
+
/**
|
|
568
|
+
* Perform one after-commit effect: claim the record (pending → performing, version-checked,
|
|
569
|
+
* so two processes never both perform it), perform it, record done or failed (shared
|
|
570
|
+
* transitions: runtime/transactions.ts). A notification carries the outbox id as its idempotency
|
|
571
|
+
* key, so a recovered send is not repeated; a recovered job or webhook event can be (at least
|
|
572
|
+
* once: docs/TRANSACTIONS.md, UPSTREAM-GAPS.md). Never throws:
|
|
573
|
+
* the mutation has committed, and its caller gets its result; a failure is on the record and in
|
|
574
|
+
* the log.
|
|
575
|
+
*/
|
|
576
|
+
async #performOutbox(record, services, principal, requestId) {
|
|
577
|
+
return performOutbox(outboxStore(this.instance.handle("app")), record.id, (claim, complete) => {
|
|
578
|
+
const effect = claim.effect;
|
|
579
|
+
// A job or webhook event is created in the transaction that records it done; a notification is sent directly.
|
|
580
|
+
if (effect.service === "jobs")
|
|
581
|
+
return this.#services.performInTransaction({ service: "jobs", type: effect.type, payload: effect.payload, ...(effect.options ? { options: effect.options } : {}) }, principal, requestId, complete);
|
|
582
|
+
if (effect.service === "webhooks")
|
|
583
|
+
return this.#services.performInTransaction({ service: "webhooks", type: effect.type, payload: effect.payload }, principal, requestId, complete);
|
|
584
|
+
return performEffect(services, claim);
|
|
585
|
+
}, { warn: (message) => this.logger.warn(message, { outboxId: record.id, requestId: record.requestId }) });
|
|
586
|
+
}
|
|
587
|
+
/**
|
|
588
|
+
* After-commit effects whose process stopped before performing them (pending past
|
|
589
|
+
* OUTBOX_RECOVER_AFTER_MS, or performing past OUTBOX_PERFORMING_STALE_MS), performed as the
|
|
590
|
+
* caller's current principal. A caller that can no longer be resolved fails the record.
|
|
591
|
+
*/
|
|
592
|
+
async recoverOutbox(now = Date.now()) {
|
|
593
|
+
const store = this.instance.handle("app");
|
|
594
|
+
const outbox = store.collection(OUTBOX_COLLECTION);
|
|
595
|
+
const stale = [...(await outbox.find({ state: "pending" })), ...(await outbox.find({ state: "performing" }))].filter((r) => isRecoverable(r, now));
|
|
596
|
+
let performed = 0;
|
|
597
|
+
for (const record of stale) {
|
|
598
|
+
const principal = await this.#resolveDurable(record.principalId);
|
|
599
|
+
if (!principal) {
|
|
600
|
+
await store
|
|
601
|
+
.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()) }] })
|
|
602
|
+
.catch(() => undefined);
|
|
603
|
+
continue;
|
|
604
|
+
}
|
|
605
|
+
const requestId = `outbox_${record.id}`;
|
|
606
|
+
const release = this.#services.enter(requestId, principal);
|
|
607
|
+
try {
|
|
608
|
+
const services = explainServiceDenials(this.#services.bind(principal, requestId, new Set(), true), record.function, principal, this.#authority);
|
|
609
|
+
if ((await this.#performOutbox(record, services, principal, requestId)) === "done")
|
|
610
|
+
performed += 1;
|
|
611
|
+
}
|
|
612
|
+
finally {
|
|
613
|
+
release();
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
return performed;
|
|
617
|
+
}
|
|
618
|
+
/** After-commit effects, newest first (optionally only those in `state`). */
|
|
619
|
+
async listOutbox(filter = {}) {
|
|
620
|
+
const rows = (await this.instance.handle("app").collection(OUTBOX_COLLECTION).find((filter.state ? { state: filter.state } : {})));
|
|
621
|
+
return rows
|
|
622
|
+
.map(({ __version: _v, ...r }) => r)
|
|
623
|
+
.sort((a, b) => b.createdAt - a.createdAt)
|
|
624
|
+
.slice(0, filter.limit ?? 100);
|
|
625
|
+
}
|
|
626
|
+
/**
|
|
627
|
+
* An operator's retry of a failed after-commit effect: back to pending (attempts and last error
|
|
628
|
+
* kept), then performed now as its caller, or by the worker if that caller cannot be resolved.
|
|
629
|
+
*/
|
|
630
|
+
async retryOutbox(id, by) {
|
|
631
|
+
this.#assertReady();
|
|
632
|
+
const store = this.instance.handle("app");
|
|
633
|
+
const outbox = store.collection(OUTBOX_COLLECTION);
|
|
634
|
+
const record = await outbox.get(id).catch(() => null);
|
|
635
|
+
if (!record)
|
|
636
|
+
throw new FeltKitError("NOT_FOUND", `No after-commit effect ${id}.`);
|
|
637
|
+
const next = retried(record, by, Date.now());
|
|
638
|
+
try {
|
|
639
|
+
await store.transaction({ operations: [{ collection: OUTBOX_COLLECTION, id, ifVersion: record.__version, value: next }] });
|
|
640
|
+
}
|
|
641
|
+
catch {
|
|
642
|
+
throw new FeltKitError("CONFLICT", `After-commit effect ${id} changed while it was being retried. Nothing was changed; read it again.`);
|
|
643
|
+
}
|
|
644
|
+
const principal = await this.#resolveDurable(record.principalId);
|
|
645
|
+
if (principal) {
|
|
646
|
+
const requestId = `outbox_${id}_retry`;
|
|
647
|
+
const release = this.#services.enter(requestId, principal);
|
|
648
|
+
try {
|
|
649
|
+
const services = explainServiceDenials(this.#services.bind(principal, requestId, new Set(), true), record.function, principal, this.#authority);
|
|
650
|
+
await this.#performOutbox(next, services, principal, requestId);
|
|
651
|
+
}
|
|
652
|
+
finally {
|
|
653
|
+
release();
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
const { __version: _v, ...after } = (await outbox.get(id));
|
|
657
|
+
return after;
|
|
658
|
+
}
|
|
659
|
+
/** Drive durable service work once (jobs, schedules, webhook deliveries, recovered after-commit effects). */
|
|
450
660
|
runServices() {
|
|
451
|
-
if (this.#state !== "ready")
|
|
661
|
+
if (this.#state !== "ready" || this.#paused)
|
|
452
662
|
return Promise.resolve({ jobs: 0, deliveries: 0, scheduled: 0 });
|
|
453
663
|
if (this.#ticking)
|
|
454
664
|
return this.#ticking;
|
|
455
|
-
const run =
|
|
665
|
+
const run = Promise.all([
|
|
666
|
+
this.#services.tick(`${this.app.name}:${process.pid}`),
|
|
667
|
+
this.recoverOutbox().catch((error) => {
|
|
668
|
+
this.logger.warn(`after-commit recovery: ${error.message}`);
|
|
669
|
+
return 0;
|
|
670
|
+
}),
|
|
671
|
+
]).then(([tick]) => tick).catch((error) => {
|
|
456
672
|
this.logger.warn(`services worker: ${error.message}`);
|
|
457
673
|
return { jobs: 0, deliveries: 0, scheduled: 0 };
|
|
458
674
|
});
|
|
@@ -588,7 +804,8 @@ export class FeltKitRuntime {
|
|
|
588
804
|
}
|
|
589
805
|
/** Run a query or mutation as `principal`. Authority is checked before the handler runs. */
|
|
590
806
|
call(name, rawArgs, options) {
|
|
591
|
-
|
|
807
|
+
// While a backup reads the state, new calls wait for it (see backup()).
|
|
808
|
+
const promise = this.#paused ? this.#paused.then(() => this.#call(name, rawArgs, options)) : this.#call(name, rawArgs, options);
|
|
592
809
|
this.#inflight.add(promise);
|
|
593
810
|
return promise.finally(() => this.#inflight.delete(promise));
|
|
594
811
|
}
|
|
@@ -623,16 +840,17 @@ export class FeltKitRuntime {
|
|
|
623
840
|
return failure(new FeltKitError("UNAVAILABLE", `The runtime is ${this.#state}.`));
|
|
624
841
|
if (!fn)
|
|
625
842
|
return failure(new FeltKitError("FUNCTION_NOT_FOUND", `No query or mutation named "${name}".`, { hint: "Function names are \"<module>:<export>\", e.g. \"tasks:list\"." }));
|
|
626
|
-
|
|
627
|
-
if (
|
|
628
|
-
return failure(new FeltKitError("
|
|
629
|
-
argKeys: argKeys(rawArgs),
|
|
630
|
-
});
|
|
843
|
+
// Never hand stored records to code that declares a different schema for them.
|
|
844
|
+
if (this.schema?.status === "blocked") {
|
|
845
|
+
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) }));
|
|
631
846
|
}
|
|
632
|
-
|
|
847
|
+
// Authority first, then the arguments: a caller that may not run the function learns
|
|
848
|
+
// nothing about its input contract, gets FORBIDDEN (not INVALID_ARGUMENT, which invites a
|
|
849
|
+
// corrected retry), and the attempt is recorded as a denial. `access` is a permission,
|
|
850
|
+
// "authenticated" or "public", so the decision never depends on the arguments.
|
|
633
851
|
let decision;
|
|
634
852
|
try {
|
|
635
|
-
decision = await this.#authority.authorize({ access: fn.access, principal, target: { name, version: 1 }, transport: options.via, requestId
|
|
853
|
+
decision = await this.#authority.authorize({ access: fn.access, principal, target: { name, version: 1 }, transport: options.via, requestId });
|
|
636
854
|
}
|
|
637
855
|
catch (error) {
|
|
638
856
|
return failure(error);
|
|
@@ -646,71 +864,135 @@ export class FeltKitRuntime {
|
|
|
646
864
|
...(options.appportDecisionId ? { appportDecisionId: options.appportDecisionId } : {}),
|
|
647
865
|
};
|
|
648
866
|
if (!decision.allowed) {
|
|
649
|
-
return failure(new FeltKitError(decision.code ?? "FORBIDDEN", decision.reason ?? "Not allowed"), { authority: authorityRecord, argKeys:
|
|
867
|
+
return failure(new FeltKitError(decision.code ?? "FORBIDDEN", decision.reason ?? "Not allowed"), { authority: authorityRecord, argKeys: argKeys(rawArgs) });
|
|
650
868
|
}
|
|
869
|
+
const parsed = validate(fn.argsSchema, rawArgs ?? {});
|
|
870
|
+
if (!parsed.ok) {
|
|
871
|
+
return failure(new FeltKitError("INVALID_ARGUMENT", `Invalid arguments for ${name}: ${parsed.issues.map((i) => `${i.path}: ${i.message}`).join("; ")}`, { details: { issues: parsed.issues } }), {
|
|
872
|
+
authority: authorityRecord,
|
|
873
|
+
argKeys: argKeys(rawArgs),
|
|
874
|
+
});
|
|
875
|
+
}
|
|
876
|
+
const args = parsed.value;
|
|
651
877
|
const handle = this.instance.handle("app");
|
|
652
|
-
const db = fn.kind === "mutation" ? new Writer(handle, this.#resolver) : new Reader(handle, this.#resolver);
|
|
653
878
|
const release = this.#services.enter(requestId, principal);
|
|
654
879
|
const servicesUsed = new Set();
|
|
655
|
-
const
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
880
|
+
const enabled = this.app.options.services ?? {};
|
|
881
|
+
// One attempt: a fresh ctx.db, ctx.services binding and outbox staging. Only a mutation that
|
|
882
|
+
// opted in (`retry: { sequenceConflicts }`) has more than one (runtime/transactions.ts).
|
|
883
|
+
const attempt = async () => {
|
|
884
|
+
const db = fn.kind === "mutation" ? new Writer(handle, this.#resolver) : new Reader(handle, this.#resolver);
|
|
885
|
+
const used = new Set();
|
|
886
|
+
const shared = {
|
|
887
|
+
auth: authContext(this.#authority, principal),
|
|
888
|
+
services: explainServiceDenials(this.#services.bind(principal, requestId, db.reads, fn.kind === "mutation", used), name, principal, this.#authority),
|
|
889
|
+
environment: { name: this.environment.name, production: this.environment.production, storage: describeStorage(this.environment.storage) },
|
|
890
|
+
requestId,
|
|
891
|
+
log: this.logger,
|
|
892
|
+
};
|
|
893
|
+
const starts = [];
|
|
894
|
+
const agent = {
|
|
895
|
+
start: (input) => {
|
|
896
|
+
if (!principal)
|
|
897
|
+
throw new FeltKitError("UNAUTHORIZED", "Starting agent work needs a signed-in caller.");
|
|
898
|
+
if (!this.#authority.permissionsFor(principal).some((g) => g === "*" || g === "feltkit.*" || g === "feltkit.agent.*" || g === "feltkit.agent.write")) {
|
|
899
|
+
throw new FeltKitError("FORBIDDEN", `${principal.id} may not start agent work (needs feltkit.agent.write).`);
|
|
900
|
+
}
|
|
901
|
+
const taskId = `task-${randomUUID()}`;
|
|
902
|
+
starts.push({ taskId, objective: String(input?.objective ?? ""), decision: input?.decision, ...(input?.subject ? { subject: input.subject } : {}) });
|
|
903
|
+
return { taskId };
|
|
904
|
+
},
|
|
905
|
+
};
|
|
906
|
+
const effects = db instanceof Writer
|
|
907
|
+
? afterCommit({
|
|
908
|
+
caller: name,
|
|
909
|
+
principal,
|
|
910
|
+
requestId,
|
|
911
|
+
enabled: { notifications: Boolean(enabled.notifications), webhooks: Boolean(enabled.webhooks), jobs: Boolean(enabled.jobs) },
|
|
912
|
+
stage: (record) => db.stageSystem(OUTBOX_COLLECTION, record),
|
|
913
|
+
newId: newOutboxId,
|
|
914
|
+
})
|
|
915
|
+
: null;
|
|
916
|
+
const ctx = fn.kind === "mutation" ? { ...shared, db, agent, afterCommit: effects, unsafe: { feltdb: this.instance.handle("app.unsafe") } } : { ...shared, db };
|
|
917
|
+
try {
|
|
918
|
+
const value = await fn.handler(ctx, args);
|
|
919
|
+
if (fn.returns) {
|
|
920
|
+
const output = validate(fn.returns, value);
|
|
921
|
+
if (!output.ok) {
|
|
922
|
+
throw new FeltKitError("INTERNAL", `${name} returned a value that does not match its \`returns\` schema: ${output.issues.map((i) => `${i.path}: ${i.message}`).join("; ")}`);
|
|
923
|
+
}
|
|
669
924
|
}
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
925
|
+
let commit;
|
|
926
|
+
if (db instanceof Writer) {
|
|
927
|
+
commit = await db.commit(options.idempotencyReplayKey ? idempotentTransactionId(options.idempotencyReplayKey) : requestId, {
|
|
928
|
+
keyed: options.idempotencyReplayKey !== undefined,
|
|
929
|
+
});
|
|
930
|
+
}
|
|
931
|
+
return { value, db, commit, starts, used };
|
|
932
|
+
}
|
|
933
|
+
catch (error) {
|
|
934
|
+
throw Object.assign(new AttemptFailed(error), { db, used });
|
|
935
|
+
}
|
|
936
|
+
finally {
|
|
937
|
+
for (const service of used)
|
|
938
|
+
servicesUsed.add(service);
|
|
939
|
+
}
|
|
674
940
|
};
|
|
675
|
-
|
|
941
|
+
let reads = [];
|
|
942
|
+
let retries = 0;
|
|
676
943
|
try {
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
throw new FeltKitError("INTERNAL", `${name} returned a value that does not match its \`returns\` schema: ${output.issues.map((i) => `${i.path}: ${i.message}`).join("; ")}`);
|
|
944
|
+
for (;;) {
|
|
945
|
+
let outcome;
|
|
946
|
+
try {
|
|
947
|
+
outcome = await attempt();
|
|
682
948
|
}
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
949
|
+
catch (failed) {
|
|
950
|
+
const { error, db, used } = failed;
|
|
951
|
+
reads = [...db.reads];
|
|
952
|
+
const conflict = isFeltKitError(error) && error.code === "CONFLICT" && isSequenceConflict(error.details?.failure);
|
|
953
|
+
if (conflict && fn.retry && retries < fn.retry.sequenceConflicts && used.size === 0) {
|
|
954
|
+
retries += 1;
|
|
955
|
+
continue;
|
|
956
|
+
}
|
|
957
|
+
throw error;
|
|
958
|
+
}
|
|
959
|
+
const { value, db, commit, starts } = outcome;
|
|
960
|
+
reads = [...db.reads];
|
|
961
|
+
if (db instanceof Writer && commit) {
|
|
962
|
+
if (commit.writes.length)
|
|
963
|
+
void this.changes.check();
|
|
964
|
+
// Agent work starts only once the mutation's writes are durable.
|
|
965
|
+
for (const start of starts)
|
|
966
|
+
this.#agent?.startAfterCommit(start, principal);
|
|
967
|
+
// So do after-commit effects: performed now, as the caller, while its binding is live.
|
|
968
|
+
const outbox = db.staged.filter((r) => r.collection === OUTBOX_COLLECTION).map((r) => r.value);
|
|
969
|
+
if (outbox.length) {
|
|
970
|
+
const bound = explainServiceDenials(this.#services.bind(principal, requestId, new Set(), true, servicesUsed), name, principal, this.#authority);
|
|
971
|
+
for (const record of outbox)
|
|
972
|
+
await this.#performOutbox(record, bound, principal, requestId);
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
finish({
|
|
976
|
+
outcome: "success",
|
|
977
|
+
authority: authorityRecord,
|
|
978
|
+
argKeys: Object.keys(args),
|
|
979
|
+
reads,
|
|
980
|
+
...(servicesUsed.size ? { services: [...servicesUsed] } : {}),
|
|
981
|
+
...(retries ? { detail: { sequenceRetries: retries } } : {}),
|
|
982
|
+
...(commit && commit.writes.length
|
|
983
|
+
? {
|
|
984
|
+
writes: commit.writes,
|
|
985
|
+
transactionId: commit.transactionId,
|
|
986
|
+
...(commit.commitRevision !== undefined ? { commitRevision: commit.commitRevision } : {}),
|
|
987
|
+
...(commit.revisionId ? { revisionId: commit.revisionId } : {}),
|
|
988
|
+
}
|
|
989
|
+
: {}),
|
|
688
990
|
});
|
|
689
|
-
|
|
690
|
-
void this.changes.check();
|
|
691
|
-
// Agent work starts only once the mutation's writes are durable.
|
|
692
|
-
for (const start of starts)
|
|
693
|
-
this.#agent?.startAfterCommit(start, principal);
|
|
991
|
+
return { ok: true, value: value === undefined ? null : value, reads, requestId };
|
|
694
992
|
}
|
|
695
|
-
finish({
|
|
696
|
-
outcome: "success",
|
|
697
|
-
authority: authorityRecord,
|
|
698
|
-
argKeys: Object.keys(args),
|
|
699
|
-
reads: [...db.reads],
|
|
700
|
-
...(servicesUsed.size ? { services: [...servicesUsed] } : {}),
|
|
701
|
-
...(commit && commit.writes.length
|
|
702
|
-
? {
|
|
703
|
-
writes: commit.writes,
|
|
704
|
-
transactionId: commit.transactionId,
|
|
705
|
-
...(commit.commitRevision !== undefined ? { commitRevision: commit.commitRevision } : {}),
|
|
706
|
-
...(commit.revisionId ? { revisionId: commit.revisionId } : {}),
|
|
707
|
-
}
|
|
708
|
-
: {}),
|
|
709
|
-
});
|
|
710
|
-
return { ok: true, value: value === undefined ? null : value, reads: [...db.reads], requestId };
|
|
711
993
|
}
|
|
712
994
|
catch (error) {
|
|
713
|
-
return failure(error, { authority: authorityRecord, argKeys: Object.keys(args), reads
|
|
995
|
+
return failure(error, { authority: authorityRecord, argKeys: Object.keys(args), reads, ...(servicesUsed.size ? { services: [...servicesUsed] } : {}), ...(retries ? { detail: { sequenceRetries: retries } } : {}) });
|
|
714
996
|
}
|
|
715
997
|
finally {
|
|
716
998
|
release();
|
|
@@ -763,6 +1045,28 @@ export class FeltKitRuntime {
|
|
|
763
1045
|
};
|
|
764
1046
|
}
|
|
765
1047
|
/** Stop accepting calls, wait for in-flight work, flush the activity log, release the instance. */
|
|
1048
|
+
/**
|
|
1049
|
+
* This environment's backup (docs/BACKUP.md), application-consistent: new calls and the services
|
|
1050
|
+
* worker wait while it reads, and the calls in flight finish first, so it holds each committed
|
|
1051
|
+
* transaction entirely or not at all.
|
|
1052
|
+
*/
|
|
1053
|
+
async backup() {
|
|
1054
|
+
this.#assertReady();
|
|
1055
|
+
if (this.environment.storage.kind !== "local")
|
|
1056
|
+
throw remoteBackupRefusal();
|
|
1057
|
+
while (this.#paused)
|
|
1058
|
+
await this.#paused;
|
|
1059
|
+
let release;
|
|
1060
|
+
this.#paused = new Promise((resolve) => (release = resolve));
|
|
1061
|
+
try {
|
|
1062
|
+
await Promise.allSettled([...this.#inflight]);
|
|
1063
|
+
return await backupLines(this.instance.handle("feltkit.backup"), backupMeta(this.app, this.environment.name));
|
|
1064
|
+
}
|
|
1065
|
+
finally {
|
|
1066
|
+
this.#paused = null;
|
|
1067
|
+
release();
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
766
1070
|
async close() {
|
|
767
1071
|
if (this.#state === "closed" || this.#state === "closing")
|
|
768
1072
|
return;
|
|
@@ -800,6 +1104,9 @@ function toAppPortError(error) {
|
|
|
800
1104
|
return appportErrors.notFound(error.message);
|
|
801
1105
|
case "CONFLICT":
|
|
802
1106
|
return appportErrors.conflict(error.message);
|
|
1107
|
+
// AppPort has no standard code for it: an extension code, never retryable.
|
|
1108
|
+
case "FAILED_PRECONDITION":
|
|
1109
|
+
return new AppPortError("feltkit.FAILED_PRECONDITION", error.message, { retryable: false, details: (error.details ?? null) });
|
|
803
1110
|
case "PAYLOAD_TOO_LARGE":
|
|
804
1111
|
return appportErrors.payloadTooLarge(error.message);
|
|
805
1112
|
// Not INTERNAL: a caller must be able to tell "may have been applied" from "failed".
|
|
@@ -844,4 +1151,11 @@ function emailChannelClass() {
|
|
|
844
1151
|
}
|
|
845
1152
|
return channel;
|
|
846
1153
|
}
|
|
1154
|
+
/** A failed attempt of a function call, carrying what it read and which services it used. */
|
|
1155
|
+
class AttemptFailed {
|
|
1156
|
+
error;
|
|
1157
|
+
constructor(error) {
|
|
1158
|
+
this.error = error;
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
847
1161
|
//# sourceMappingURL=runtime.js.map
|