@feltdb/feltkit 0.3.11 → 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 +80 -3
- package/dist/app.js +41 -0
- package/dist/app.js.map +1 -1
- package/dist/appboundry/build.d.ts +39 -1
- package/dist/appboundry/build.js +47 -4
- 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.js +445 -7
- 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/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 +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/contract.js +4 -3
- package/dist/runtime/contract.js.map +1 -1
- package/dist/runtime/data.d.ts +6 -2
- package/dist/runtime/data.js +29 -23
- 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 +6 -82
- package/dist/runtime/outbox.js +14 -59
- package/dist/runtime/outbox.js.map +1 -1
- package/dist/runtime/readiness.js +12 -0
- package/dist/runtime/readiness.js.map +1 -1
- package/dist/runtime/runtime.d.ts +60 -2
- package/dist/runtime/runtime.js +301 -116
- package/dist/runtime/runtime.js.map +1 -1
- package/dist/runtime/services.d.ts +22 -0
- package/dist/runtime/services.js +35 -0
- 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 +13 -1
- package/dist/schema.js +21 -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 +4 -1
- package/dist/testing/index.js +5 -3
- package/dist/testing/index.js.map +1 -1
- package/package.json +3 -3
- package/skills/.claude-plugin/marketplace.json +1 -1
- package/skills/.claude-plugin/plugin.json +1 -1
- package/skills/feltkit-build/SKILL.md +6 -3
- package/skills/feltkit-data/SKILL.md +11 -0
- package/skills/feltkit-services/SKILL.md +6 -4
package/dist/runtime/runtime.js
CHANGED
|
@@ -16,6 +16,8 @@ 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 { assertNotPartiallyRestored, backupLines } from "./backup.js";
|
|
20
|
+
import { backupMeta, remoteBackupRefusal } from "./backup-environment.js";
|
|
19
21
|
import { FeltKitError, isFeltKitError } from "../errors.js";
|
|
20
22
|
import { validate } from "../schema.js";
|
|
21
23
|
import { ActivityLog, errorSummary } from "./activity.js";
|
|
@@ -26,7 +28,9 @@ import { CollectionResolver, Reader, Writer, ensureCollectionMarkers, feltdbRefu
|
|
|
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 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
|
+
}
|
|
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)
|
|
@@ -473,61 +566,39 @@ export class FeltKitRuntime {
|
|
|
473
566
|
}
|
|
474
567
|
/**
|
|
475
568
|
* 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
|
-
*
|
|
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.
|
|
479
575
|
*/
|
|
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;
|
|
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 }) });
|
|
512
586
|
}
|
|
513
587
|
/**
|
|
514
588
|
* 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.
|
|
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.
|
|
517
591
|
*/
|
|
518
592
|
async recoverOutbox(now = Date.now()) {
|
|
519
593
|
const store = this.instance.handle("app");
|
|
520
|
-
const
|
|
521
|
-
|
|
522
|
-
...(await store.collection(OUTBOX_COLLECTION).find({ state: "performing" })).filter((r) => now - r.updatedAt >= OUTBOX_RECOVER_AFTER_MS * 10),
|
|
523
|
-
];
|
|
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));
|
|
524
596
|
let performed = 0;
|
|
525
597
|
for (const record of stale) {
|
|
526
598
|
const principal = await this.#resolveDurable(record.principalId);
|
|
527
599
|
if (!principal) {
|
|
528
|
-
const { __version, ...fields } = record;
|
|
529
600
|
await store
|
|
530
|
-
.transaction({ operations: [{ collection: OUTBOX_COLLECTION, id: record.id, ifVersion: __version, value:
|
|
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()) }] })
|
|
531
602
|
.catch(() => undefined);
|
|
532
603
|
continue;
|
|
533
604
|
}
|
|
@@ -535,7 +606,7 @@ export class FeltKitRuntime {
|
|
|
535
606
|
const release = this.#services.enter(requestId, principal);
|
|
536
607
|
try {
|
|
537
608
|
const services = explainServiceDenials(this.#services.bind(principal, requestId, new Set(), true), record.function, principal, this.#authority);
|
|
538
|
-
if ((await this.#performOutbox(record, services)) === "done")
|
|
609
|
+
if ((await this.#performOutbox(record, services, principal, requestId)) === "done")
|
|
539
610
|
performed += 1;
|
|
540
611
|
}
|
|
541
612
|
finally {
|
|
@@ -544,9 +615,50 @@ export class FeltKitRuntime {
|
|
|
544
615
|
}
|
|
545
616
|
return performed;
|
|
546
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
|
+
}
|
|
547
659
|
/** Drive durable service work once (jobs, schedules, webhook deliveries, recovered after-commit effects). */
|
|
548
660
|
runServices() {
|
|
549
|
-
if (this.#state !== "ready")
|
|
661
|
+
if (this.#state !== "ready" || this.#paused)
|
|
550
662
|
return Promise.resolve({ jobs: 0, deliveries: 0, scheduled: 0 });
|
|
551
663
|
if (this.#ticking)
|
|
552
664
|
return this.#ticking;
|
|
@@ -692,7 +804,8 @@ export class FeltKitRuntime {
|
|
|
692
804
|
}
|
|
693
805
|
/** Run a query or mutation as `principal`. Authority is checked before the handler runs. */
|
|
694
806
|
call(name, rawArgs, options) {
|
|
695
|
-
|
|
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);
|
|
696
809
|
this.#inflight.add(promise);
|
|
697
810
|
return promise.finally(() => this.#inflight.delete(promise));
|
|
698
811
|
}
|
|
@@ -727,6 +840,10 @@ export class FeltKitRuntime {
|
|
|
727
840
|
return failure(new FeltKitError("UNAVAILABLE", `The runtime is ${this.#state}.`));
|
|
728
841
|
if (!fn)
|
|
729
842
|
return failure(new FeltKitError("FUNCTION_NOT_FOUND", `No query or mutation named "${name}".`, { hint: "Function names are \"<module>:<export>\", e.g. \"tasks:list\"." }));
|
|
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) }));
|
|
846
|
+
}
|
|
730
847
|
// Authority first, then the arguments: a caller that may not run the function learns
|
|
731
848
|
// nothing about its input contract, gets FORBIDDEN (not INVALID_ARGUMENT, which invites a
|
|
732
849
|
// corrected retry), and the attempt is recorded as a denial. `access` is a permission,
|
|
@@ -758,85 +875,124 @@ export class FeltKitRuntime {
|
|
|
758
875
|
}
|
|
759
876
|
const args = parsed.value;
|
|
760
877
|
const handle = this.instance.handle("app");
|
|
761
|
-
const db = fn.kind === "mutation" ? new Writer(handle, this.#resolver) : new Reader(handle, this.#resolver);
|
|
762
878
|
const release = this.#services.enter(requestId, principal);
|
|
763
879
|
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
880
|
const enabled = this.app.options.services ?? {};
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
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) },
|
|
789
890
|
requestId,
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
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
|
+
}
|
|
801
924
|
}
|
|
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);
|
|
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
|
+
});
|
|
819
930
|
}
|
|
931
|
+
return { value, db, commit, starts, used };
|
|
820
932
|
}
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
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
|
+
}
|
|
940
|
+
};
|
|
941
|
+
let reads = [];
|
|
942
|
+
let retries = 0;
|
|
943
|
+
try {
|
|
944
|
+
for (;;) {
|
|
945
|
+
let outcome;
|
|
946
|
+
try {
|
|
947
|
+
outcome = await attempt();
|
|
948
|
+
}
|
|
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;
|
|
833
956
|
}
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
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
|
+
: {}),
|
|
990
|
+
});
|
|
991
|
+
return { ok: true, value: value === undefined ? null : value, reads, requestId };
|
|
992
|
+
}
|
|
837
993
|
}
|
|
838
994
|
catch (error) {
|
|
839
|
-
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 } } : {}) });
|
|
840
996
|
}
|
|
841
997
|
finally {
|
|
842
998
|
release();
|
|
@@ -889,6 +1045,28 @@ export class FeltKitRuntime {
|
|
|
889
1045
|
};
|
|
890
1046
|
}
|
|
891
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
|
+
}
|
|
892
1070
|
async close() {
|
|
893
1071
|
if (this.#state === "closed" || this.#state === "closing")
|
|
894
1072
|
return;
|
|
@@ -973,4 +1151,11 @@ function emailChannelClass() {
|
|
|
973
1151
|
}
|
|
974
1152
|
return channel;
|
|
975
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
|
+
}
|
|
976
1161
|
//# sourceMappingURL=runtime.js.map
|