@quad-education/sdk 0.0.0-stage → 0.1.3

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.
Files changed (69) hide show
  1. package/LICENSE.md +15 -0
  2. package/README.md +106 -2
  3. package/dist/contract-tests/apps.d.ts +373 -0
  4. package/dist/contract-tests/apps.js +309 -0
  5. package/dist/contract-tests/index.d.ts +3 -0
  6. package/dist/contract-tests/index.js +2 -0
  7. package/dist/contract-tests/suite.d.ts +57 -0
  8. package/dist/contract-tests/suite.js +1405 -0
  9. package/dist/src/client/connect.d.ts +10 -0
  10. package/dist/src/client/connect.js +12 -0
  11. package/dist/src/client/create-client.d.ts +14 -0
  12. package/dist/src/client/create-client.js +76 -0
  13. package/dist/src/client/handshake-client.d.ts +16 -0
  14. package/dist/src/client/handshake-client.js +37 -0
  15. package/dist/src/contract/errors.d.ts +8 -0
  16. package/dist/src/contract/errors.js +13 -0
  17. package/dist/src/contract/recipients.d.ts +28 -0
  18. package/dist/src/contract/recipients.js +12 -0
  19. package/dist/src/contract/types.d.ts +442 -0
  20. package/dist/src/contract/types.js +1 -0
  21. package/dist/src/engine/audit.d.ts +27 -0
  22. package/dist/src/engine/audit.js +105 -0
  23. package/dist/src/engine/cron.d.ts +17 -0
  24. package/dist/src/engine/cron.js +143 -0
  25. package/dist/src/engine/db-indexes.d.ts +11 -0
  26. package/dist/src/engine/db-indexes.js +82 -0
  27. package/dist/src/engine/engine.d.ts +156 -0
  28. package/dist/src/engine/engine.js +953 -0
  29. package/dist/src/engine/host.d.ts +39 -0
  30. package/dist/src/engine/host.js +73 -0
  31. package/dist/src/engine/in-process.d.ts +5 -0
  32. package/dist/src/engine/in-process.js +18 -0
  33. package/dist/src/engine/index.d.ts +10 -0
  34. package/dist/src/engine/index.js +8 -0
  35. package/dist/src/engine/query.d.ts +16 -0
  36. package/dist/src/engine/query.js +106 -0
  37. package/dist/src/engine/runner.d.ts +26 -0
  38. package/dist/src/engine/runner.js +260 -0
  39. package/dist/src/engine/state.d.ts +107 -0
  40. package/dist/src/engine/state.js +16 -0
  41. package/dist/src/engine/storage.d.ts +46 -0
  42. package/dist/src/engine/storage.js +86 -0
  43. package/dist/src/engine/tasks.d.ts +17 -0
  44. package/dist/src/engine/tasks.js +245 -0
  45. package/dist/src/engine/validate-input.d.ts +9 -0
  46. package/dist/src/engine/validate-input.js +76 -0
  47. package/dist/src/engine/values.d.ts +10 -0
  48. package/dist/src/engine/values.js +58 -0
  49. package/dist/src/handshake.d.ts +16 -0
  50. package/dist/src/handshake.js +9 -0
  51. package/dist/src/index.d.ts +3 -0
  52. package/dist/src/index.js +4 -0
  53. package/dist/src/jobs/define.d.ts +41 -0
  54. package/dist/src/jobs/define.js +28 -0
  55. package/dist/src/jobs/host.d.ts +13 -0
  56. package/dist/src/jobs/host.js +22 -0
  57. package/dist/src/jobs/index.d.ts +1 -0
  58. package/dist/src/jobs/index.js +2 -0
  59. package/dist/src/jobs/worker.d.ts +17 -0
  60. package/dist/src/jobs/worker.js +25 -0
  61. package/dist/src/platform-types.d.ts +19 -0
  62. package/dist/src/platform-types.js +1 -0
  63. package/dist/src/port-rpc.d.ts +42 -0
  64. package/dist/src/port-rpc.js +85 -0
  65. package/dist/src/protocol.d.ts +41 -0
  66. package/dist/src/protocol.js +45 -0
  67. package/dist/src/testing/index.d.ts +78 -0
  68. package/dist/src/testing/index.js +118 -0
  69. package/package.json +71 -3
@@ -0,0 +1,39 @@
1
+ import type { Principal } from '@quad-education/canonical';
2
+ import type { RunRequest, RunResult } from '../jobs/define.ts';
3
+ import type { Engine } from './engine.ts';
4
+ export type RejectedMessage = {
5
+ at: string;
6
+ origin: string;
7
+ reason: string;
8
+ };
9
+ /** A frame the shell hosts: the app's UI, or its hidden jobs host (D20). */
10
+ export type HostedFrame = {
11
+ readonly kind: 'ui' | 'jobs';
12
+ readonly iframe: HTMLIFrameElement;
13
+ /** Who the frame acts as. The app never chooses its own principal. */
14
+ readonly principal: () => Principal;
15
+ };
16
+ export type HostOptions = {
17
+ engine: Engine;
18
+ appId: string;
19
+ /** The app's exact origin. Handshakes are only answered for this origin and these frames. */
20
+ appOrigin: string;
21
+ /** The frames to host; read on every message, so the shell can swap frames. */
22
+ frames: () => readonly HostedFrame[];
23
+ onRejected?: (rejected: RejectedMessage) => void;
24
+ /** A job run finished in the jobs host. */
25
+ onRunDone?: (runId: string, result: RunResult) => void;
26
+ };
27
+ export type AppHost = {
28
+ dispose(): void;
29
+ /** Push the engine clock to every session (after the shell moves the demo clock). */
30
+ pushClock(): void;
31
+ /** Send a run to the connected jobs host; false if none is connected yet. */
32
+ dispatchRun(run: RunRequest): boolean;
33
+ };
34
+ /**
35
+ * Hosts an app's frames for the engine (D15). Waits for `quad:ready` from a hosted frame's
36
+ * window on the app origin, then hands over a private MessagePort. Every other window
37
+ * message is ignored and reported through `onRejected`.
38
+ */
39
+ export declare function hostApp(options: HostOptions): AppHost;
@@ -0,0 +1,73 @@
1
+ import { isReady } from "../handshake.js";
2
+ import { servePort } from "../port-rpc.js";
3
+ /**
4
+ * Hosts an app's frames for the engine (D15). Waits for `quad:ready` from a hosted frame's
5
+ * window on the app origin, then hands over a private MessagePort. Every other window
6
+ * message is ignored and reported through `onRejected`.
7
+ */
8
+ export function hostApp(options) {
9
+ const { engine, appId, appOrigin } = options;
10
+ // One session per handshake. A reloaded or re-rendered frame may connect more than once.
11
+ const sessions = [];
12
+ const reject = (origin, reason) => options.onRejected?.({ at: new Date().toISOString(), origin, reason });
13
+ function onMessage(e) {
14
+ // A page messaging itself (devtools, extensions) is not an app or an attacker; skip it.
15
+ if (e.source === window)
16
+ return;
17
+ if (e.origin !== appOrigin) {
18
+ reject(e.origin, 'message from an origin that is not the hosted app');
19
+ return;
20
+ }
21
+ const frame = options.frames().find((f) => f.iframe.contentWindow === e.source);
22
+ if (!frame) {
23
+ reject(e.origin, 'message from a window that is not one of the app’s frames');
24
+ return;
25
+ }
26
+ // A preview's app file (D69) is the shell's to handle, not the session's.
27
+ if (e.data?.type === 'quad:app-file')
28
+ return;
29
+ if (!isReady(e.data)) {
30
+ reject(e.origin, 'unexpected window message (RPC must use the session port)');
31
+ return;
32
+ }
33
+ const channel = new MessageChannel();
34
+ const principal = frame.principal();
35
+ const server = servePort(channel.port1,
36
+ // The jobs host acts as each run's principal, looked up from the engine's own record
37
+ // of the run (D7). A call that isn't part of a running job is refused.
38
+ frame.kind === 'jobs'
39
+ ? (method, params, meta) => engine.handle(appId, engine.runPrincipal(appId, meta.runId), method, params)
40
+ : (method, params) => engine.handle(appId, principal, method, params), frame.kind === 'jobs' && options.onRunDone ? { onRunDone: options.onRunDone } : {});
41
+ sessions.push({ frame, server });
42
+ const hello = {
43
+ type: 'quad:hello',
44
+ protocol: 1,
45
+ nonce: e.data.nonce,
46
+ session: engine.sessionInfo(appId),
47
+ };
48
+ frame.iframe.contentWindow.postMessage(hello, appOrigin, [channel.port2]);
49
+ }
50
+ window.addEventListener('message', onMessage);
51
+ return {
52
+ dispose() {
53
+ window.removeEventListener('message', onMessage);
54
+ for (const s of sessions.splice(0))
55
+ s.server.close();
56
+ },
57
+ pushClock: () => {
58
+ for (const s of sessions)
59
+ s.server.pushClock(engine.clockState());
60
+ },
61
+ dispatchRun(run) {
62
+ // The most recent jobs session whose frame is still hosted.
63
+ const live = options.frames();
64
+ const session = [...sessions]
65
+ .reverse()
66
+ .find((s) => s.frame.kind === 'jobs' && live.some((f) => f.iframe === s.frame.iframe));
67
+ if (!session)
68
+ return false;
69
+ session.server.dispatchRun(run);
70
+ return true;
71
+ },
72
+ };
73
+ }
@@ -0,0 +1,5 @@
1
+ import type { Principal } from '@quad-education/canonical';
2
+ import type { QuadSdk } from '../contract/types.ts';
3
+ import type { Engine } from './engine.ts';
4
+ /** An SDK connected to an engine in the same JavaScript context (tests). */
5
+ export declare function connectInProcess(engine: Engine, appId: string, principal: Principal): QuadSdk;
@@ -0,0 +1,18 @@
1
+ import { createSdkClient } from "../client/create-client.js";
2
+ import { deserializeError, serializeError } from "../protocol.js";
3
+ /** JSON round trip, so in-process calls behave like messages over a real transport. */
4
+ const wire = (value) => value === undefined ? value : JSON.parse(JSON.stringify(value));
5
+ /** An SDK connected to an engine in the same JavaScript context (tests). */
6
+ export function connectInProcess(engine, appId, principal) {
7
+ return createSdkClient({
8
+ async call(method, params) {
9
+ try {
10
+ return wire(await engine.handle(appId, wire(principal), method, wire(params)));
11
+ }
12
+ catch (e) {
13
+ throw deserializeError(serializeError(e));
14
+ }
15
+ },
16
+ nowMs: () => engine.nowMs(),
17
+ }, engine.sessionInfo(appId));
18
+ }
@@ -0,0 +1,10 @@
1
+ import { Engine, type EngineOptions } from './engine.ts';
2
+ export { Engine, type EngineOptions } from './engine.ts';
3
+ export { connectInProcess } from './in-process.ts';
4
+ export { hostApp, type AppHost, type HostOptions, type HostedFrame, type RejectedMessage, } from './host.ts';
5
+ export type { RunRequest, RunResult } from '../jobs/define.ts';
6
+ export type { StoredRun } from './state.ts';
7
+ export { servePort } from '../port-rpc.ts';
8
+ export { ENGINE_DB_NAME } from './storage.ts';
9
+ export type { OutboxEntry } from '../platform-types.ts';
10
+ export declare const createEngine: (options: EngineOptions) => Promise<Engine>;
@@ -0,0 +1,8 @@
1
+ // Platform-side: the in-browser engine. Apps must never import this (lint enforces it).
2
+ import { Engine } from "./engine.js";
3
+ export { Engine } from "./engine.js";
4
+ export { connectInProcess } from "./in-process.js";
5
+ export { hostApp, } from "./host.js";
6
+ export { servePort } from "../port-rpc.js";
7
+ export { ENGINE_DB_NAME } from "./storage.js";
8
+ export const createEngine = (options) => Engine.create(options);
@@ -0,0 +1,16 @@
1
+ type Row = Record<string, unknown>;
2
+ export type QueryOptions = {
3
+ where?: unknown;
4
+ orderBy?: unknown;
5
+ limit?: unknown;
6
+ cursor?: unknown;
7
+ };
8
+ /**
9
+ * Applies where, orderBy, limit and cursor to rows. `allowedFields` are the fields a caller
10
+ * may filter or sort on; anything else is a VALIDATION error (so ungranted tiers can't be probed).
11
+ */
12
+ export declare function runQuery<T extends Row>(rows: readonly T[], options: QueryOptions, allowedFields: ReadonlySet<string>): {
13
+ items: T[];
14
+ nextCursor: string | null;
15
+ };
16
+ export {};
@@ -0,0 +1,106 @@
1
+ import { QuadError } from "../contract/errors.js";
2
+ const MAX_LIMIT = 200;
3
+ const DEFAULT_LIMIT = 50;
4
+ const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
5
+ function compare(a, b) {
6
+ if (a === b)
7
+ return 0;
8
+ if (a === undefined || a === null)
9
+ return -1;
10
+ if (b === undefined || b === null)
11
+ return 1;
12
+ if (typeof a === 'number' && typeof b === 'number')
13
+ return a - b;
14
+ if (typeof a === 'boolean' && typeof b === 'boolean')
15
+ return Number(a) - Number(b);
16
+ return String(a).localeCompare(String(b));
17
+ }
18
+ function matcher(field, condition) {
19
+ if (!isPlainObject(condition))
20
+ return (v) => v === condition;
21
+ const keys = Object.keys(condition);
22
+ if (keys.length === 1 && 'in' in condition) {
23
+ if (!Array.isArray(condition.in))
24
+ throw new QuadError('VALIDATION', `where.${field}.in must be an array`);
25
+ const set = new Set(condition.in);
26
+ return (v) => set.has(v);
27
+ }
28
+ if (keys.length === 1 && 'ne' in condition)
29
+ return (v) => v !== condition.ne;
30
+ const ops = ['gt', 'gte', 'lt', 'lte'];
31
+ if (keys.length === 0 || !keys.every((k) => ops.includes(k))) {
32
+ throw new QuadError('VALIDATION', `where.${field}: use a value, { in }, { ne } or { gt, gte, lt, lte }`);
33
+ }
34
+ return (v) => v !== undefined &&
35
+ v !== null &&
36
+ (condition.gt === undefined || compare(v, condition.gt) > 0) &&
37
+ (condition.gte === undefined || compare(v, condition.gte) >= 0) &&
38
+ (condition.lt === undefined || compare(v, condition.lt) < 0) &&
39
+ (condition.lte === undefined || compare(v, condition.lte) <= 0);
40
+ }
41
+ function encodeCursor(offset, fingerprint) {
42
+ return btoa(JSON.stringify({ o: offset, f: fingerprint })).replace(/=+$/, '');
43
+ }
44
+ function decodeCursor(cursor, fingerprint) {
45
+ try {
46
+ const parsed = JSON.parse(atob(cursor));
47
+ if (typeof parsed.o === 'number' &&
48
+ Number.isInteger(parsed.o) &&
49
+ parsed.o >= 0 &&
50
+ parsed.f === fingerprint) {
51
+ return parsed.o;
52
+ }
53
+ }
54
+ catch {
55
+ // fall through
56
+ }
57
+ throw new QuadError('VALIDATION', 'invalid cursor; pass the nextCursor from the previous page with the same query');
58
+ }
59
+ /**
60
+ * Applies where, orderBy, limit and cursor to rows. `allowedFields` are the fields a caller
61
+ * may filter or sort on; anything else is a VALIDATION error (so ungranted tiers can't be probed).
62
+ */
63
+ export function runQuery(rows, options, allowedFields) {
64
+ if (options !== undefined && !isPlainObject(options))
65
+ throw new QuadError('VALIDATION', 'options must be an object');
66
+ const { where, orderBy, limit = DEFAULT_LIMIT, cursor } = options;
67
+ if (typeof limit !== 'number' || !Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {
68
+ throw new QuadError('VALIDATION', `limit must be an integer from 1 to ${MAX_LIMIT}`);
69
+ }
70
+ let result = [...rows];
71
+ if (where !== undefined) {
72
+ if (!isPlainObject(where))
73
+ throw new QuadError('VALIDATION', 'where must be an object');
74
+ for (const [field, condition] of Object.entries(where)) {
75
+ if (!allowedFields.has(field))
76
+ throw new QuadError('VALIDATION', `can't filter on '${field}'`);
77
+ const match = matcher(field, condition);
78
+ result = result.filter((r) => match(r[field]));
79
+ }
80
+ }
81
+ const orders = orderBy === undefined ? [] : Array.isArray(orderBy) ? orderBy : [orderBy];
82
+ for (const o of orders) {
83
+ if (!isPlainObject(o) || typeof o.field !== 'string' || !allowedFields.has(o.field)) {
84
+ throw new QuadError('VALIDATION', `can't order by '${String(isPlainObject(o) ? o.field : o)}'`);
85
+ }
86
+ if (o.direction !== undefined && o.direction !== 'asc' && o.direction !== 'desc') {
87
+ throw new QuadError('VALIDATION', "orderBy.direction must be 'asc' or 'desc'");
88
+ }
89
+ }
90
+ // Stable order: requested fields, then id, so pages never overlap.
91
+ result.sort((a, b) => {
92
+ for (const o of orders) {
93
+ const c = compare(a[o.field], b[o.field]);
94
+ if (c !== 0)
95
+ return o.direction === 'desc' ? -c : c;
96
+ }
97
+ return compare(a.id, b.id);
98
+ });
99
+ const fingerprint = JSON.stringify({ where, orderBy, limit });
100
+ const offset = cursor === undefined ? 0 : typeof cursor === 'string' ? decodeCursor(cursor, fingerprint) : -1;
101
+ if (offset < 0)
102
+ throw new QuadError('VALIDATION', 'cursor must be a string');
103
+ const items = result.slice(offset, offset + limit);
104
+ const next = offset + limit;
105
+ return { items, nextCursor: next < result.length ? encodeCursor(next, fingerprint) : null };
106
+ }
@@ -0,0 +1,26 @@
1
+ import type { CronJobInfo, ScheduledRun } from '../contract/types.ts';
2
+ import type { RunRequest, RunResult } from '../jobs/define.ts';
3
+ import { type App, type Ctx, type Kernel } from './state.ts';
4
+ export type { RunRequest, RunResult } from '../jobs/define.ts';
5
+ export declare function scheduleAt(k: Kernel, ctx: Ctx, input: Record<string, unknown>): Promise<ScheduledRun>;
6
+ export declare function scheduleCancel(k: Kernel, ctx: Ctx, id: unknown): Promise<ScheduledRun>;
7
+ export declare function scheduleList(ctx: Ctx, options: unknown): ScheduledRun[];
8
+ export declare function cronList(k: Kernel, ctx: Ctx): CronJobInfo[];
9
+ /**
10
+ * Start cron baselines at install, so a new job doesn't backfill from the distant past.
11
+ * If the demo clock is now behind a baseline (it was moved back, D14), the baseline moves
12
+ * back to now, rather than leaving the job silent until the clock catches up.
13
+ */
14
+ export declare function initCron(k: Kernel, app: App): Promise<void>;
15
+ /**
16
+ * Turns due schedules and cron occurrences into runs, then starts what may start: at most
17
+ * one run per job at a time (no overlap), oldest first. Missed cron occurrences collapse
18
+ * into one catch-up run (D8).
19
+ */
20
+ export declare function startDueRuns(k: Kernel, app: App): Promise<RunRequest[]>;
21
+ /** Records a run's result. Failures are retried up to three attempts, then marked failed. */
22
+ export declare function finishRun(k: Kernel, app: App, runId: string, result: RunResult): Promise<void>;
23
+ /** A run handed out but never dispatched (e.g. no jobs host yet) goes back to pending. */
24
+ export declare function releaseRun(k: Kernel, app: App, runId: string): Promise<void>;
25
+ /** Delivers a finished run again with the same runId (D20: handlers must be idempotent). */
26
+ export declare function redeliverRun(k: Kernel, app: App, runId: string): Promise<void>;
@@ -0,0 +1,260 @@
1
+ import { QuadError } from "../contract/errors.js";
2
+ import { appendAudit } from "./audit.js";
3
+ import { latestOccurrence, nextOccurrence } from "./cron.js";
4
+ import {} from "./state.js";
5
+ import { instant, isObject, json, str } from "./values.js";
6
+ const MAX_ATTEMPTS = 3;
7
+ /** A run that hasn't reported back within this long (wall clock) is delivered again. */
8
+ const RUN_TIMEOUT_MS = 60_000;
9
+ function scheduleView(s) {
10
+ const { appId: _appId, runAs, ...view } = s;
11
+ return { ...view, runsAs: runAs.kind === 'system' ? 'system' : 'user' };
12
+ }
13
+ const SYSTEM = (app) => ({ kind: 'system', appId: app.manifest.id });
14
+ /** Users see and cancel the jobs they scheduled; the system principal sees all. */
15
+ const ownsSchedule = (ctx, s) => ctx.principal.kind === 'system' || s.createdBy === ctx.actorId;
16
+ export async function scheduleAt(k, ctx, input) {
17
+ // Anyone the app serves may schedule (the session already checked the role). The job
18
+ // runs as the caller, so it can never do more than the caller could (D7).
19
+ const job = str(input.job, 'job');
20
+ if (!ctx.app.manifest.scheduled.includes(job)) {
21
+ throw new QuadError('UNDECLARED_TYPE', `job '${job}' isn't in the manifest's scheduled list`);
22
+ }
23
+ const key = k.idempotencyKey(input, 'schedule.at');
24
+ if (key && ctx.app.keys.has(key)) {
25
+ const existing = ctx.app.schedules.get(ctx.app.keys.get(key));
26
+ if (existing)
27
+ return scheduleView(existing);
28
+ }
29
+ const s = {
30
+ id: `sch_${crypto.randomUUID()}`,
31
+ appId: ctx.app.manifest.id,
32
+ job,
33
+ when: instant(input.when, 'when'),
34
+ payload: (input.payload === undefined ? null : json(input.payload, 'payload')),
35
+ status: 'pending',
36
+ createdAt: k.nowIso(),
37
+ createdBy: ctx.actorId,
38
+ runAs: ctx.principal,
39
+ };
40
+ ctx.app.schedules.set(s.id, s);
41
+ await k.persistPlatform(ctx.app, 'schedule', [s]);
42
+ if (key)
43
+ await k.remember(ctx, key, s.id);
44
+ return scheduleView(s);
45
+ }
46
+ export async function scheduleCancel(k, ctx, id) {
47
+ const s = ctx.app.schedules.get(str(id, 'id'));
48
+ if (!s || !ownsSchedule(ctx, s))
49
+ throw new QuadError('NOT_FOUND', `no scheduled job ${String(id)}`);
50
+ if (s.status !== 'pending')
51
+ throw new QuadError('VALIDATION', `this scheduled job is already ${s.status}`);
52
+ s.status = 'cancelled';
53
+ await k.persistPlatform(ctx.app, 'schedule', [s]);
54
+ return scheduleView(s);
55
+ }
56
+ export function scheduleList(ctx, options) {
57
+ const status = isObject(options) ? options.status : undefined;
58
+ if (status !== undefined && !['pending', 'done', 'cancelled'].includes(status)) {
59
+ throw new QuadError('VALIDATION', "status must be 'pending', 'done' or 'cancelled'");
60
+ }
61
+ return [...ctx.app.schedules.values()]
62
+ .filter((s) => ownsSchedule(ctx, s) && (status === undefined || s.status === status))
63
+ .sort((a, b) => a.when.localeCompare(b.when))
64
+ .map(scheduleView);
65
+ }
66
+ export function cronList(k, ctx) {
67
+ const tz = k.timezone();
68
+ return ctx.app.manifest.cron.map((job) => {
69
+ const next = nextOccurrence(job.schedule, tz, k.nowMs());
70
+ return {
71
+ name: job.name,
72
+ schedule: job.schedule,
73
+ description: job.description,
74
+ nextRunAt: next === null ? null : new Date(next).toISOString(),
75
+ lastScheduledFor: ctx.app.cron.get(job.name)?.lastScheduledFor ?? null,
76
+ };
77
+ });
78
+ }
79
+ /**
80
+ * Start cron baselines at install, so a new job doesn't backfill from the distant past.
81
+ * If the demo clock is now behind a baseline (it was moved back, D14), the baseline moves
82
+ * back to now, rather than leaving the job silent until the clock catches up.
83
+ */
84
+ export async function initCron(k, app) {
85
+ const changed = [];
86
+ const now = k.nowMs();
87
+ for (const job of app.manifest.cron) {
88
+ const state = app.cron.get(job.name);
89
+ if (state && Date.parse(state.lastScheduledFor) <= now)
90
+ continue;
91
+ const fresh = { id: job.name, lastScheduledFor: new Date(now).toISOString() };
92
+ app.cron.set(job.name, fresh);
93
+ changed.push(fresh);
94
+ }
95
+ await k.persistPlatform(app, 'cron', changed);
96
+ }
97
+ /**
98
+ * Turns due schedules and cron occurrences into runs, then starts what may start: at most
99
+ * one run per job at a time (no overlap), oldest first. Missed cron occurrences collapse
100
+ * into one catch-up run (D8).
101
+ */
102
+ export async function startDueRuns(k, app) {
103
+ const now = k.nowMs();
104
+ const changedRuns = new Map();
105
+ const changedSchedules = [];
106
+ const changedCron = [];
107
+ for (const s of app.schedules.values()) {
108
+ if (s.status !== 'pending' || Date.parse(s.when) > now)
109
+ continue;
110
+ const run = {
111
+ id: `sched:${s.id}`,
112
+ appId: app.manifest.id,
113
+ jobName: s.job,
114
+ kind: 'schedule',
115
+ scheduleId: s.id,
116
+ scheduledFor: s.when,
117
+ payload: s.payload,
118
+ runAs: s.runAs,
119
+ status: 'pending',
120
+ attempts: 0,
121
+ deliveries: 0,
122
+ };
123
+ if (!app.runs.has(run.id)) {
124
+ app.runs.set(run.id, run);
125
+ changedRuns.set(run.id, run);
126
+ }
127
+ s.status = 'done';
128
+ changedSchedules.push(s);
129
+ }
130
+ for (const job of app.manifest.cron) {
131
+ const state = app.cron.get(job.name);
132
+ if (!state)
133
+ continue;
134
+ const latest = latestOccurrence(job.schedule, k.timezone(), Date.parse(state.lastScheduledFor), now);
135
+ if (latest === null)
136
+ continue;
137
+ const scheduledFor = new Date(latest).toISOString();
138
+ const run = {
139
+ id: `cron:${job.name}:${scheduledFor}`,
140
+ appId: app.manifest.id,
141
+ jobName: job.name,
142
+ kind: 'cron',
143
+ scheduledFor,
144
+ payload: null,
145
+ runAs: SYSTEM(app),
146
+ status: 'pending',
147
+ attempts: 0,
148
+ deliveries: 0,
149
+ };
150
+ if (!app.runs.has(run.id)) {
151
+ app.runs.set(run.id, run);
152
+ changedRuns.set(run.id, run);
153
+ }
154
+ state.lastScheduledFor = scheduledFor;
155
+ changedCron.push(state);
156
+ }
157
+ const wall = Date.now();
158
+ for (const run of app.runs.values()) {
159
+ if (run.status === 'running' &&
160
+ run.startedAtMs !== undefined &&
161
+ wall - run.startedAtMs > RUN_TIMEOUT_MS) {
162
+ run.status = 'pending'; // never reported back: deliver again (at least once)
163
+ changedRuns.set(run.id, run);
164
+ }
165
+ }
166
+ const busy = new Set([...app.runs.values()].filter((r) => r.status === 'running').map((r) => r.jobName));
167
+ const started = [];
168
+ const pending = [...app.runs.values()]
169
+ .filter((r) => r.status === 'pending')
170
+ .sort((a, b) => a.scheduledFor.localeCompare(b.scheduledFor) || a.id.localeCompare(b.id));
171
+ for (const run of pending) {
172
+ if (busy.has(run.jobName))
173
+ continue; // never overlap runs of the same job
174
+ busy.add(run.jobName);
175
+ run.status = 'running';
176
+ run.attempts += 1;
177
+ run.deliveries += 1;
178
+ run.startedAt = k.nowIso();
179
+ run.startedAtMs = wall;
180
+ changedRuns.set(run.id, run);
181
+ started.push({
182
+ runId: run.id,
183
+ jobName: run.jobName,
184
+ scheduledFor: run.scheduledFor,
185
+ payload: run.payload,
186
+ attempt: run.attempts,
187
+ runAs: run.runAs,
188
+ });
189
+ }
190
+ await k.persistPlatform(app, 'run', [...changedRuns.values()]);
191
+ await k.persistPlatform(app, 'schedule', changedSchedules);
192
+ await k.persistPlatform(app, 'cron', changedCron);
193
+ return started;
194
+ }
195
+ /** Records a run's result. Failures are retried up to three attempts, then marked failed. */
196
+ export async function finishRun(k, app, runId, result) {
197
+ const run = app.runs.get(runId);
198
+ if (!run || run.status !== 'running')
199
+ return; // a late or duplicate report
200
+ run.finishedAt = k.nowIso();
201
+ delete run.startedAtMs;
202
+ if (result.ok) {
203
+ run.status = 'succeeded';
204
+ delete run.error;
205
+ }
206
+ else {
207
+ run.error = result.error;
208
+ run.status = run.attempts >= MAX_ATTEMPTS ? 'failed' : 'pending';
209
+ }
210
+ await k.persistPlatform(app, 'run', [run]);
211
+ await appendAudit(k, app, {
212
+ source: 'platform',
213
+ action: 'job.run',
214
+ actor: `system:${app.manifest.id}`,
215
+ summary: `${run.jobName} ${result.ok ? 'succeeded' : `failed (attempt ${run.attempts})`}`,
216
+ entity: 'job',
217
+ recordId: run.id,
218
+ visibility: 'app',
219
+ data: {
220
+ runId: run.id,
221
+ jobName: run.jobName,
222
+ scheduledFor: run.scheduledFor,
223
+ attempt: run.attempts,
224
+ outcome: result.ok ? 'succeeded' : 'failed',
225
+ ...(result.ok ? {} : { error: result.error }),
226
+ },
227
+ });
228
+ }
229
+ /** A run handed out but never dispatched (e.g. no jobs host yet) goes back to pending. */
230
+ export async function releaseRun(k, app, runId) {
231
+ const run = app.runs.get(runId);
232
+ if (!run || run.status !== 'running')
233
+ return;
234
+ run.status = 'pending';
235
+ run.attempts -= 1;
236
+ run.deliveries -= 1;
237
+ delete run.startedAtMs;
238
+ await k.persistPlatform(app, 'run', [run]);
239
+ }
240
+ /** Delivers a finished run again with the same runId (D20: handlers must be idempotent). */
241
+ export async function redeliverRun(k, app, runId) {
242
+ const run = app.runs.get(runId);
243
+ if (!run)
244
+ throw new QuadError('NOT_FOUND', `no run ${runId}`);
245
+ if (run.status === 'running' || run.status === 'pending')
246
+ return;
247
+ run.status = 'pending';
248
+ run.attempts = 0;
249
+ await k.persistPlatform(app, 'run', [run]);
250
+ await appendAudit(k, app, {
251
+ source: 'platform',
252
+ action: 'job.redelivered',
253
+ actor: `system:${app.manifest.id}`,
254
+ summary: `${run.jobName} redelivered (run ${run.id})`,
255
+ entity: 'job',
256
+ recordId: run.id,
257
+ visibility: 'app',
258
+ data: { runId: run.id, jobName: run.jobName, scheduledFor: run.scheduledFor },
259
+ });
260
+ }
@@ -0,0 +1,107 @@
1
+ import { type Dataset, type Principal, type Role } from '@quad-education/canonical';
2
+ import type { AppSchema, Manifest } from '@quad-education/schema';
3
+ import type { AuditEntry, JsonValue, ScheduledRun, Task } from '../contract/types.ts';
4
+ import type { PlatformKind } from './storage.ts';
5
+ export type StoredTask = Omit<Task, 'assignedToMe' | 'assignees'> & {
6
+ readonly appId: string;
7
+ assignees: string[];
8
+ /** What the parent assignees must be eligible for; re-checked on completion (D17). */
9
+ purpose?: 'correspondence' | 'consent';
10
+ status: Task['status'];
11
+ completedAt?: string;
12
+ completedBy?: string;
13
+ outcome?: string;
14
+ cancelledAt?: string;
15
+ cancelledBy?: string;
16
+ };
17
+ export type StoredSchedule = Omit<ScheduledRun, 'runsAs'> & {
18
+ readonly appId: string;
19
+ status: ScheduledRun['status'];
20
+ /** Who the job runs as: whoever scheduled it, in their session (D7). */
21
+ readonly runAs: Principal;
22
+ };
23
+ export type RunStatus = 'pending' | 'running' | 'succeeded' | 'failed';
24
+ /** One delivery target of a job: a cron occurrence or a scheduled one-off (D7, D8). */
25
+ export type StoredRun = {
26
+ /** Stable across redelivery (D20). */
27
+ readonly id: string;
28
+ readonly appId: string;
29
+ readonly jobName: string;
30
+ readonly kind: 'cron' | 'schedule';
31
+ readonly scheduleId?: string;
32
+ readonly scheduledFor: string;
33
+ readonly payload: JsonValue;
34
+ /** Cron runs as the system principal; a scheduled run as whoever scheduled it (D7). */
35
+ readonly runAs: Principal;
36
+ status: RunStatus;
37
+ attempts: number;
38
+ deliveries: number;
39
+ startedAt?: string;
40
+ /** Wall-clock start, for detecting runs that never reported back. */
41
+ startedAtMs?: number;
42
+ finishedAt?: string;
43
+ error?: string;
44
+ };
45
+ export type CronState = {
46
+ readonly id: string;
47
+ lastScheduledFor: string;
48
+ };
49
+ /** `cio` entries (sensitive reads, suppressions) are only shown in the shell's audit viewer (D19). */
50
+ export type StoredAudit = AuditEntry & {
51
+ readonly seq: number;
52
+ readonly visibility: 'app' | 'cio';
53
+ };
54
+ export type App = {
55
+ manifest: Manifest;
56
+ schema: AppSchema;
57
+ records: Map<string, Map<string, Record<string, unknown>>>;
58
+ keys: Map<string, unknown>;
59
+ tasks: Map<string, StoredTask>;
60
+ schedules: Map<string, StoredSchedule>;
61
+ runs: Map<string, StoredRun>;
62
+ cron: Map<string, CronState>;
63
+ audit: StoredAudit[];
64
+ };
65
+ export type Ctx = {
66
+ app: App;
67
+ principal: Principal;
68
+ actorId: string;
69
+ /** Students this principal can see, computed once per call. */
70
+ students?: 'all' | Set<string>;
71
+ };
72
+ export declare const isStaffOrSystem: (ctx: Ctx) => boolean;
73
+ export declare const roleOfPrincipal: (ctx: Ctx) => Role | "system";
74
+ /** Why a parent recipient was left out (D17). Recorded only in CIO-visible audit entries. */
75
+ export type SuppressedRecipient = {
76
+ personId: string;
77
+ regardingStudentId: string;
78
+ reason: 'restricted' | 'no-correspondence' | 'cannot-consent' | 'not-linked';
79
+ };
80
+ export type ResolvedRecipients = {
81
+ recipients: {
82
+ personId: string;
83
+ role: Role;
84
+ regarding?: string;
85
+ purpose?: 'correspondence' | 'consent';
86
+ }[];
87
+ suppressed: SuppressedRecipient[];
88
+ };
89
+ /** The engine internals the Slice B modules use. `Engine` implements it. */
90
+ export interface Kernel {
91
+ readonly dataset: Dataset;
92
+ nowIso(): string;
93
+ nowMs(): number;
94
+ timezone(): string;
95
+ persistPlatform(app: App, kind: PlatformKind, items: readonly {
96
+ id: string;
97
+ }[]): Promise<void>;
98
+ remember(ctx: Ctx, key: string, result: unknown): Promise<void>;
99
+ idempotencyKey(options: unknown, scope: string): string | undefined;
100
+ resolveRecipients(ctx: Ctx, to: unknown, regarding: string | undefined): ResolvedRecipients;
101
+ }
102
+ /**
103
+ * Whether the current principal can see a subject student, under the school's visibility
104
+ * policy (D4). Tasks and audit entries about a student follow it for everyone, staff
105
+ * included; only the system principal is exempt.
106
+ */
107
+ export declare function seesSubject(k: Pick<Kernel, 'dataset'>, ctx: Ctx, studentId: string | undefined): boolean;