@quad-education/sdk 0.1.4 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/contract-tests/apps.d.ts +79 -0
- package/dist/contract-tests/apps.js +56 -0
- package/dist/contract-tests/harness.d.ts +11 -0
- package/dist/contract-tests/harness.js +40 -0
- package/dist/contract-tests/helpers.d.ts +5 -0
- package/dist/contract-tests/helpers.js +25 -0
- package/dist/contract-tests/index.d.ts +4 -2
- package/dist/contract-tests/index.js +3 -1
- package/dist/contract-tests/standalone-apps.d.ts +183 -0
- package/dist/contract-tests/standalone-apps.js +178 -0
- package/dist/contract-tests/standalone.d.ts +2 -0
- package/dist/contract-tests/standalone.js +709 -0
- package/dist/contract-tests/suite.d.ts +10 -3
- package/dist/contract-tests/suite.js +207 -42
- package/dist/src/client/connect.d.ts +13 -3
- package/dist/src/client/connect.js +21 -3
- package/dist/src/client/handshake-client.d.ts +2 -0
- package/dist/src/client/handshake-client.js +2 -0
- package/dist/src/client/http-transport.d.ts +18 -0
- package/dist/src/client/http-transport.js +76 -0
- package/dist/src/client/live.d.ts +39 -0
- package/dist/src/client/live.js +122 -0
- package/dist/src/contract/errors.d.ts +1 -1
- package/dist/src/contract/principals.d.ts +30 -0
- package/dist/src/contract/principals.js +12 -0
- package/dist/src/contract/recipients.d.ts +8 -2
- package/dist/src/contract/types.d.ts +18 -2
- package/dist/src/contract/types.js +1 -1
- package/dist/src/engine/audit.d.ts +2 -2
- package/dist/src/engine/audit.js +8 -6
- package/dist/src/engine/db-indexes.js +6 -1
- package/dist/src/engine/engine.d.ts +53 -17
- package/dist/src/engine/engine.js +260 -156
- package/dist/src/engine/host.d.ts +2 -2
- package/dist/src/engine/host.js +1 -1
- package/dist/src/engine/in-process.d.ts +2 -2
- package/dist/src/engine/index.d.ts +3 -1
- package/dist/src/engine/index.js +1 -0
- package/dist/src/engine/memory-store.d.ts +32 -0
- package/dist/src/engine/memory-store.js +123 -0
- package/dist/src/engine/runner.d.ts +2 -2
- package/dist/src/engine/runner.js +31 -26
- package/dist/src/engine/state.d.ts +21 -15
- package/dist/src/engine/state.js +31 -3
- package/dist/src/engine/store.d.ts +48 -0
- package/dist/src/engine/store.js +1 -0
- package/dist/src/engine/tasks.d.ts +4 -6
- package/dist/src/engine/tasks.js +27 -24
- package/dist/src/index.d.ts +1 -0
- package/dist/src/index.js +1 -0
- package/dist/src/jobs/define.d.ts +2 -2
- package/dist/src/platform-types.d.ts +2 -2
- package/package.json +4 -4
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { ActingAs } from '../contract/principals.ts';
|
|
2
2
|
import type { RunRequest, RunResult } from '../jobs/define.ts';
|
|
3
3
|
import type { Engine } from './engine.ts';
|
|
4
4
|
export type RejectedMessage = {
|
|
@@ -11,7 +11,7 @@ export type HostedFrame = {
|
|
|
11
11
|
readonly kind: 'ui' | 'jobs';
|
|
12
12
|
readonly iframe: HTMLIFrameElement;
|
|
13
13
|
/** Who the frame acts as. The app never chooses its own principal. */
|
|
14
|
-
readonly principal: () =>
|
|
14
|
+
readonly principal: () => ActingAs;
|
|
15
15
|
};
|
|
16
16
|
export type HostOptions = {
|
|
17
17
|
engine: Engine;
|
package/dist/src/engine/host.js
CHANGED
|
@@ -36,7 +36,7 @@ export function hostApp(options) {
|
|
|
36
36
|
// The jobs host acts as each run's principal, looked up from the engine's own record
|
|
37
37
|
// of the run (D7). A call that isn't part of a running job is refused.
|
|
38
38
|
frame.kind === 'jobs'
|
|
39
|
-
? (method, params, meta) => engine.handle(appId, engine.runPrincipal(appId, meta.runId), method, params)
|
|
39
|
+
? async (method, params, meta) => engine.handle(appId, await engine.runPrincipal(appId, meta.runId), method, params)
|
|
40
40
|
: (method, params) => engine.handle(appId, principal, method, params), frame.kind === 'jobs' && options.onRunDone ? { onRunDone: options.onRunDone } : {});
|
|
41
41
|
sessions.push({ frame, server });
|
|
42
42
|
const hello = {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { ActingAs } from '../contract/principals.ts';
|
|
2
2
|
import type { QuadSdk } from '../contract/types.ts';
|
|
3
3
|
import type { Engine } from './engine.ts';
|
|
4
4
|
/** An SDK connected to an engine in the same JavaScript context (tests). */
|
|
5
|
-
export declare function connectInProcess(engine: Engine, appId: string, principal:
|
|
5
|
+
export declare function connectInProcess(engine: Engine, appId: string, principal: ActingAs): QuadSdk;
|
|
@@ -3,7 +3,9 @@ export { Engine, type EngineOptions } from './engine.ts';
|
|
|
3
3
|
export { connectInProcess } from './in-process.ts';
|
|
4
4
|
export { hostApp, type AppHost, type HostOptions, type HostedFrame, type RejectedMessage, } from './host.ts';
|
|
5
5
|
export type { RunRequest, RunResult } from '../jobs/define.ts';
|
|
6
|
-
export type { StoredRun } from './state.ts';
|
|
6
|
+
export type { CronState, StoredAudit, StoredRun, StoredSchedule, StoredTask } from './state.ts';
|
|
7
|
+
export { MemoryStore } from './memory-store.ts';
|
|
8
|
+
export type { AppStore, PlatformKind, ReadHint, StoredRecordData } from './store.ts';
|
|
7
9
|
export { servePort } from '../port-rpc.ts';
|
|
8
10
|
export { ENGINE_DB_NAME } from './storage.ts';
|
|
9
11
|
export type { OutboxEntry } from '../platform-types.ts';
|
package/dist/src/engine/index.js
CHANGED
|
@@ -3,6 +3,7 @@ import { Engine } from "./engine.js";
|
|
|
3
3
|
export { Engine } from "./engine.js";
|
|
4
4
|
export { connectInProcess } from "./in-process.js";
|
|
5
5
|
export { hostApp, } from "./host.js";
|
|
6
|
+
export { MemoryStore } from "./memory-store.js";
|
|
6
7
|
export { servePort } from "../port-rpc.js";
|
|
7
8
|
export { ENGINE_DB_NAME } from "./storage.js";
|
|
8
9
|
export const createEngine = (options) => Engine.create(options);
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { OutboxEntry } from '../platform-types.ts';
|
|
2
|
+
import { type PlatformKind } from './storage.ts';
|
|
3
|
+
import type { AppStore, ReadHint, StoredRecordData } from './store.ts';
|
|
4
|
+
/**
|
|
5
|
+
* The in-browser store (D15): an app's state in memory, written through to IndexedDB. Reads hand out the stored
|
|
6
|
+
* objects themselves, and the engine changes them and puts them back, which is how it has always worked.
|
|
7
|
+
*/
|
|
8
|
+
export declare class MemoryStore implements AppStore {
|
|
9
|
+
private readonly storage;
|
|
10
|
+
private readonly apps;
|
|
11
|
+
private constructor();
|
|
12
|
+
static open(indexedDB: IDBFactory, dbName?: string): Promise<MemoryStore>;
|
|
13
|
+
private state;
|
|
14
|
+
open(appId: string, schemaHash: string): Promise<void>;
|
|
15
|
+
clear(appId: string): Promise<void>;
|
|
16
|
+
getRecord(appId: string, entity: string, id: string): Promise<StoredRecordData | undefined>;
|
|
17
|
+
putRecord(appId: string, entity: string, record: StoredRecordData): Promise<void>;
|
|
18
|
+
deleteRecord(appId: string, entity: string, record: StoredRecordData): Promise<void>;
|
|
19
|
+
candidates(appId: string, entity: string, _hint: ReadHint): Promise<StoredRecordData[]>;
|
|
20
|
+
recordStamps(appId: string): Promise<Record<string, Record<string, string>>>;
|
|
21
|
+
getKey(appId: string, key: string): Promise<unknown>;
|
|
22
|
+
putKey(appId: string, key: string, result: unknown): Promise<void>;
|
|
23
|
+
getPlatform<T>(appId: string, kind: PlatformKind, id: string): Promise<T | undefined>;
|
|
24
|
+
allPlatform<T>(appId: string, kind: PlatformKind): Promise<T[]>;
|
|
25
|
+
putPlatform(appId: string, kind: PlatformKind, items: readonly {
|
|
26
|
+
id: string;
|
|
27
|
+
}[]): Promise<void>;
|
|
28
|
+
nextAuditSeq(appId: string): Promise<number>;
|
|
29
|
+
putOutbox(_appId: string, entries: readonly OutboxEntry[]): Promise<void>;
|
|
30
|
+
outbox(appId: string): Promise<OutboxEntry[]>;
|
|
31
|
+
close(): void;
|
|
32
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { EngineStorage, } from "./storage.js";
|
|
2
|
+
const emptyState = () => ({
|
|
3
|
+
records: new Map(),
|
|
4
|
+
keys: new Map(),
|
|
5
|
+
platform: {
|
|
6
|
+
task: new Map(),
|
|
7
|
+
schedule: new Map(),
|
|
8
|
+
run: new Map(),
|
|
9
|
+
cron: new Map(),
|
|
10
|
+
audit: new Map(),
|
|
11
|
+
},
|
|
12
|
+
auditSeq: 0,
|
|
13
|
+
});
|
|
14
|
+
/**
|
|
15
|
+
* The in-browser store (D15): an app's state in memory, written through to IndexedDB. Reads hand out the stored
|
|
16
|
+
* objects themselves, and the engine changes them and puts them back, which is how it has always worked.
|
|
17
|
+
*/
|
|
18
|
+
export class MemoryStore {
|
|
19
|
+
storage;
|
|
20
|
+
apps = new Map();
|
|
21
|
+
constructor(storage) {
|
|
22
|
+
this.storage = storage;
|
|
23
|
+
}
|
|
24
|
+
static async open(indexedDB, dbName) {
|
|
25
|
+
return new MemoryStore(await EngineStorage.open(indexedDB, dbName));
|
|
26
|
+
}
|
|
27
|
+
state(appId) {
|
|
28
|
+
let s = this.apps.get(appId);
|
|
29
|
+
if (!s)
|
|
30
|
+
this.apps.set(appId, (s = emptyState()));
|
|
31
|
+
return s;
|
|
32
|
+
}
|
|
33
|
+
async open(appId, schemaHash) {
|
|
34
|
+
const meta = await this.storage.getMeta(appId);
|
|
35
|
+
if (meta && meta.schemaHash !== schemaHash)
|
|
36
|
+
await this.storage.clearApp(appId, { schemaChangeOnly: true });
|
|
37
|
+
await this.storage.put('meta', [{ appId, schemaHash }]);
|
|
38
|
+
const state = emptyState();
|
|
39
|
+
for (const r of await this.storage.getAll('records', appId)) {
|
|
40
|
+
let rows = state.records.get(r.entity);
|
|
41
|
+
if (!rows)
|
|
42
|
+
state.records.set(r.entity, (rows = new Map()));
|
|
43
|
+
rows.set(r.id, r.data);
|
|
44
|
+
}
|
|
45
|
+
for (const k of await this.storage.getAll('keys', appId))
|
|
46
|
+
state.keys.set(k.key, k.result);
|
|
47
|
+
for (const row of await this.storage.getAll('platform', appId)) {
|
|
48
|
+
let data = row.data;
|
|
49
|
+
// Rows stored before run-as rules (D7) have no runAs; those were system-scheduled.
|
|
50
|
+
if (row.kind === 'schedule' || row.kind === 'run')
|
|
51
|
+
data = { ...data, runAs: data.runAs ?? { kind: 'system', appId } };
|
|
52
|
+
state.platform[row.kind].set(row.id, data);
|
|
53
|
+
if (row.kind === 'audit')
|
|
54
|
+
state.auditSeq = Math.max(state.auditSeq, data.seq ?? 0);
|
|
55
|
+
}
|
|
56
|
+
this.apps.set(appId, state);
|
|
57
|
+
}
|
|
58
|
+
async clear(appId) {
|
|
59
|
+
await this.storage.clearApp(appId);
|
|
60
|
+
this.apps.set(appId, emptyState());
|
|
61
|
+
}
|
|
62
|
+
async getRecord(appId, entity, id) {
|
|
63
|
+
return this.state(appId).records.get(entity)?.get(id);
|
|
64
|
+
}
|
|
65
|
+
async putRecord(appId, entity, record) {
|
|
66
|
+
const s = this.state(appId);
|
|
67
|
+
let rows = s.records.get(entity);
|
|
68
|
+
if (!rows)
|
|
69
|
+
s.records.set(entity, (rows = new Map()));
|
|
70
|
+
rows.set(record.id, record);
|
|
71
|
+
await this.storage.put('records', [{ appId, entity, id: record.id, data: record }]);
|
|
72
|
+
}
|
|
73
|
+
async deleteRecord(appId, entity, record) {
|
|
74
|
+
this.state(appId)
|
|
75
|
+
.records.get(entity)
|
|
76
|
+
?.delete(record.id);
|
|
77
|
+
await this.storage.deleteRecord(appId, entity, record.id);
|
|
78
|
+
}
|
|
79
|
+
async candidates(appId, entity, _hint) {
|
|
80
|
+
return [...(this.state(appId).records.get(entity)?.values() ?? [])];
|
|
81
|
+
}
|
|
82
|
+
async recordStamps(appId) {
|
|
83
|
+
const out = {};
|
|
84
|
+
for (const [entity, rows] of this.state(appId).records) {
|
|
85
|
+
out[entity] = Object.fromEntries([...rows.values()].map((r) => [r.id, r.updatedAt]));
|
|
86
|
+
}
|
|
87
|
+
return out;
|
|
88
|
+
}
|
|
89
|
+
async getKey(appId, key) {
|
|
90
|
+
return this.state(appId).keys.get(key);
|
|
91
|
+
}
|
|
92
|
+
async putKey(appId, key, result) {
|
|
93
|
+
this.state(appId).keys.set(key, result);
|
|
94
|
+
await this.storage.put('keys', [{ appId, key, result }]);
|
|
95
|
+
}
|
|
96
|
+
async getPlatform(appId, kind, id) {
|
|
97
|
+
return this.state(appId).platform[kind].get(id);
|
|
98
|
+
}
|
|
99
|
+
async allPlatform(appId, kind) {
|
|
100
|
+
return [...this.state(appId).platform[kind].values()];
|
|
101
|
+
}
|
|
102
|
+
async putPlatform(appId, kind, items) {
|
|
103
|
+
if (items.length === 0)
|
|
104
|
+
return;
|
|
105
|
+
const map = this.state(appId).platform[kind];
|
|
106
|
+
for (const item of items)
|
|
107
|
+
map.set(item.id, item);
|
|
108
|
+
await this.storage.putPlatform(appId, kind, items);
|
|
109
|
+
}
|
|
110
|
+
async nextAuditSeq(appId) {
|
|
111
|
+
return ++this.state(appId).auditSeq;
|
|
112
|
+
}
|
|
113
|
+
async putOutbox(_appId, entries) {
|
|
114
|
+
if (entries.length > 0)
|
|
115
|
+
await this.storage.put('outbox', entries);
|
|
116
|
+
}
|
|
117
|
+
async outbox(appId) {
|
|
118
|
+
return this.storage.getAll('outbox', appId);
|
|
119
|
+
}
|
|
120
|
+
close() {
|
|
121
|
+
this.storage.close();
|
|
122
|
+
}
|
|
123
|
+
}
|
|
@@ -4,8 +4,8 @@ import { type App, type Ctx, type Kernel } from './state.ts';
|
|
|
4
4
|
export type { RunRequest, RunResult } from '../jobs/define.ts';
|
|
5
5
|
export declare function scheduleAt(k: Kernel, ctx: Ctx, input: Record<string, unknown>): Promise<ScheduledRun>;
|
|
6
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[]
|
|
7
|
+
export declare function scheduleList(k: Kernel, ctx: Ctx, options: unknown): Promise<ScheduledRun[]>;
|
|
8
|
+
export declare function cronList(k: Kernel, ctx: Ctx): Promise<CronJobInfo[]>;
|
|
9
9
|
/**
|
|
10
10
|
* Start cron baselines at install, so a new job doesn't backfill from the distant past.
|
|
11
11
|
* If the demo clock is now behind a baseline (it was moved back, D14), the baseline moves
|
|
@@ -16,13 +16,16 @@ const ownsSchedule = (ctx, s) => ctx.principal.kind === 'system' || s.createdBy
|
|
|
16
16
|
export async function scheduleAt(k, ctx, input) {
|
|
17
17
|
// Anyone the app serves may schedule (the session already checked the role). The job
|
|
18
18
|
// runs as the caller, so it can never do more than the caller could (D7).
|
|
19
|
+
if (ctx.principal.kind === 'guest')
|
|
20
|
+
throw new QuadError('FORBIDDEN', 'guests cannot schedule jobs: nobody is signed in to run them as');
|
|
19
21
|
const job = str(input.job, 'job');
|
|
20
22
|
if (!ctx.app.manifest.scheduled.includes(job)) {
|
|
21
23
|
throw new QuadError('UNDECLARED_TYPE', `job '${job}' isn't in the manifest's scheduled list`);
|
|
22
24
|
}
|
|
23
25
|
const key = k.idempotencyKey(input, 'schedule.at');
|
|
24
|
-
|
|
25
|
-
|
|
26
|
+
const remembered = key ? await k.store.getKey(ctx.app.manifest.id, key) : undefined;
|
|
27
|
+
if (typeof remembered === 'string') {
|
|
28
|
+
const existing = await k.store.getPlatform(ctx.app.manifest.id, 'schedule', remembered);
|
|
26
29
|
if (existing)
|
|
27
30
|
return scheduleView(existing);
|
|
28
31
|
}
|
|
@@ -37,14 +40,13 @@ export async function scheduleAt(k, ctx, input) {
|
|
|
37
40
|
createdBy: ctx.actorId,
|
|
38
41
|
runAs: ctx.principal,
|
|
39
42
|
};
|
|
40
|
-
ctx.app.schedules.set(s.id, s);
|
|
41
43
|
await k.persistPlatform(ctx.app, 'schedule', [s]);
|
|
42
44
|
if (key)
|
|
43
45
|
await k.remember(ctx, key, s.id);
|
|
44
46
|
return scheduleView(s);
|
|
45
47
|
}
|
|
46
48
|
export async function scheduleCancel(k, ctx, id) {
|
|
47
|
-
const s = ctx.app.
|
|
49
|
+
const s = await k.store.getPlatform(ctx.app.manifest.id, 'schedule', str(id, 'id'));
|
|
48
50
|
if (!s || !ownsSchedule(ctx, s))
|
|
49
51
|
throw new QuadError('NOT_FOUND', `no scheduled job ${String(id)}`);
|
|
50
52
|
if (s.status !== 'pending')
|
|
@@ -53,18 +55,20 @@ export async function scheduleCancel(k, ctx, id) {
|
|
|
53
55
|
await k.persistPlatform(ctx.app, 'schedule', [s]);
|
|
54
56
|
return scheduleView(s);
|
|
55
57
|
}
|
|
56
|
-
export function scheduleList(ctx, options) {
|
|
58
|
+
export async function scheduleList(k, ctx, options) {
|
|
57
59
|
const status = isObject(options) ? options.status : undefined;
|
|
58
60
|
if (status !== undefined && !['pending', 'done', 'cancelled'].includes(status)) {
|
|
59
61
|
throw new QuadError('VALIDATION', "status must be 'pending', 'done' or 'cancelled'");
|
|
60
62
|
}
|
|
61
|
-
|
|
63
|
+
const all = await k.store.allPlatform(ctx.app.manifest.id, 'schedule');
|
|
64
|
+
return all
|
|
62
65
|
.filter((s) => ownsSchedule(ctx, s) && (status === undefined || s.status === status))
|
|
63
66
|
.sort((a, b) => a.when.localeCompare(b.when))
|
|
64
67
|
.map(scheduleView);
|
|
65
68
|
}
|
|
66
|
-
export function cronList(k, ctx) {
|
|
67
|
-
const tz = k.timezone();
|
|
69
|
+
export async function cronList(k, ctx) {
|
|
70
|
+
const tz = k.timezone(ctx.app);
|
|
71
|
+
const states = await k.store.allPlatform(ctx.app.manifest.id, 'cron');
|
|
68
72
|
return ctx.app.manifest.cron.map((job) => {
|
|
69
73
|
const next = nextOccurrence(job.schedule, tz, k.nowMs());
|
|
70
74
|
return {
|
|
@@ -72,7 +76,7 @@ export function cronList(k, ctx) {
|
|
|
72
76
|
schedule: job.schedule,
|
|
73
77
|
description: job.description,
|
|
74
78
|
nextRunAt: next === null ? null : new Date(next).toISOString(),
|
|
75
|
-
lastScheduledFor:
|
|
79
|
+
lastScheduledFor: states.find((s) => s.id === job.name)?.lastScheduledFor ?? null,
|
|
76
80
|
};
|
|
77
81
|
});
|
|
78
82
|
}
|
|
@@ -85,12 +89,10 @@ export async function initCron(k, app) {
|
|
|
85
89
|
const changed = [];
|
|
86
90
|
const now = k.nowMs();
|
|
87
91
|
for (const job of app.manifest.cron) {
|
|
88
|
-
const state = app.cron
|
|
92
|
+
const state = await k.store.getPlatform(app.manifest.id, 'cron', job.name);
|
|
89
93
|
if (state && Date.parse(state.lastScheduledFor) <= now)
|
|
90
94
|
continue;
|
|
91
|
-
|
|
92
|
-
app.cron.set(job.name, fresh);
|
|
93
|
-
changed.push(fresh);
|
|
95
|
+
changed.push({ id: job.name, lastScheduledFor: new Date(now).toISOString() });
|
|
94
96
|
}
|
|
95
97
|
await k.persistPlatform(app, 'cron', changed);
|
|
96
98
|
}
|
|
@@ -104,7 +106,10 @@ export async function startDueRuns(k, app) {
|
|
|
104
106
|
const changedRuns = new Map();
|
|
105
107
|
const changedSchedules = [];
|
|
106
108
|
const changedCron = [];
|
|
107
|
-
|
|
109
|
+
const id = app.manifest.id;
|
|
110
|
+
const schedules = await k.store.allPlatform(id, 'schedule');
|
|
111
|
+
const runs = new Map((await k.store.allPlatform(id, 'run')).map((r) => [r.id, r]));
|
|
112
|
+
for (const s of schedules) {
|
|
108
113
|
if (s.status !== 'pending' || Date.parse(s.when) > now)
|
|
109
114
|
continue;
|
|
110
115
|
const run = {
|
|
@@ -120,18 +125,18 @@ export async function startDueRuns(k, app) {
|
|
|
120
125
|
attempts: 0,
|
|
121
126
|
deliveries: 0,
|
|
122
127
|
};
|
|
123
|
-
if (!
|
|
124
|
-
|
|
128
|
+
if (!runs.has(run.id)) {
|
|
129
|
+
runs.set(run.id, run);
|
|
125
130
|
changedRuns.set(run.id, run);
|
|
126
131
|
}
|
|
127
132
|
s.status = 'done';
|
|
128
133
|
changedSchedules.push(s);
|
|
129
134
|
}
|
|
130
135
|
for (const job of app.manifest.cron) {
|
|
131
|
-
const state =
|
|
136
|
+
const state = await k.store.getPlatform(id, 'cron', job.name);
|
|
132
137
|
if (!state)
|
|
133
138
|
continue;
|
|
134
|
-
const latest = latestOccurrence(job.schedule, k.timezone(), Date.parse(state.lastScheduledFor), now);
|
|
139
|
+
const latest = latestOccurrence(job.schedule, k.timezone(app), Date.parse(state.lastScheduledFor), now);
|
|
135
140
|
if (latest === null)
|
|
136
141
|
continue;
|
|
137
142
|
const scheduledFor = new Date(latest).toISOString();
|
|
@@ -147,15 +152,15 @@ export async function startDueRuns(k, app) {
|
|
|
147
152
|
attempts: 0,
|
|
148
153
|
deliveries: 0,
|
|
149
154
|
};
|
|
150
|
-
if (!
|
|
151
|
-
|
|
155
|
+
if (!runs.has(run.id)) {
|
|
156
|
+
runs.set(run.id, run);
|
|
152
157
|
changedRuns.set(run.id, run);
|
|
153
158
|
}
|
|
154
159
|
state.lastScheduledFor = scheduledFor;
|
|
155
160
|
changedCron.push(state);
|
|
156
161
|
}
|
|
157
162
|
const wall = Date.now();
|
|
158
|
-
for (const run of
|
|
163
|
+
for (const run of runs.values()) {
|
|
159
164
|
if (run.status === 'running' &&
|
|
160
165
|
run.startedAtMs !== undefined &&
|
|
161
166
|
wall - run.startedAtMs > RUN_TIMEOUT_MS) {
|
|
@@ -163,9 +168,9 @@ export async function startDueRuns(k, app) {
|
|
|
163
168
|
changedRuns.set(run.id, run);
|
|
164
169
|
}
|
|
165
170
|
}
|
|
166
|
-
const busy = new Set([...
|
|
171
|
+
const busy = new Set([...runs.values()].filter((r) => r.status === 'running').map((r) => r.jobName));
|
|
167
172
|
const started = [];
|
|
168
|
-
const pending = [...
|
|
173
|
+
const pending = [...runs.values()]
|
|
169
174
|
.filter((r) => r.status === 'pending')
|
|
170
175
|
.sort((a, b) => a.scheduledFor.localeCompare(b.scheduledFor) || a.id.localeCompare(b.id));
|
|
171
176
|
for (const run of pending) {
|
|
@@ -194,7 +199,7 @@ export async function startDueRuns(k, app) {
|
|
|
194
199
|
}
|
|
195
200
|
/** Records a run's result. Failures are retried up to three attempts, then marked failed. */
|
|
196
201
|
export async function finishRun(k, app, runId, result) {
|
|
197
|
-
const run = app.
|
|
202
|
+
const run = await k.store.getPlatform(app.manifest.id, 'run', runId);
|
|
198
203
|
if (!run || run.status !== 'running')
|
|
199
204
|
return; // a late or duplicate report
|
|
200
205
|
run.finishedAt = k.nowIso();
|
|
@@ -228,7 +233,7 @@ export async function finishRun(k, app, runId, result) {
|
|
|
228
233
|
}
|
|
229
234
|
/** A run handed out but never dispatched (e.g. no jobs host yet) goes back to pending. */
|
|
230
235
|
export async function releaseRun(k, app, runId) {
|
|
231
|
-
const run = app.
|
|
236
|
+
const run = await k.store.getPlatform(app.manifest.id, 'run', runId);
|
|
232
237
|
if (!run || run.status !== 'running')
|
|
233
238
|
return;
|
|
234
239
|
run.status = 'pending';
|
|
@@ -239,7 +244,7 @@ export async function releaseRun(k, app, runId) {
|
|
|
239
244
|
}
|
|
240
245
|
/** Delivers a finished run again with the same runId (D20: handlers must be idempotent). */
|
|
241
246
|
export async function redeliverRun(k, app, runId) {
|
|
242
|
-
const run = app.
|
|
247
|
+
const run = await k.store.getPlatform(app.manifest.id, 'run', runId);
|
|
243
248
|
if (!run)
|
|
244
249
|
throw new QuadError('NOT_FOUND', `no run ${runId}`);
|
|
245
250
|
if (run.status === 'running' || run.status === 'pending')
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { type Dataset, type Principal, type Role } from '@quad-education/canonical';
|
|
2
2
|
import type { AppSchema, Manifest } from '@quad-education/schema';
|
|
3
|
+
import type { ActingAs } from '../contract/principals.ts';
|
|
3
4
|
import type { AuditEntry, JsonValue, ScheduledRun, Task } from '../contract/types.ts';
|
|
4
|
-
import type { PlatformKind } from './
|
|
5
|
+
import type { AppStore, PlatformKind } from './store.ts';
|
|
5
6
|
export type StoredTask = Omit<Task, 'assignedToMe' | 'assignees'> & {
|
|
6
7
|
readonly appId: string;
|
|
7
8
|
assignees: string[];
|
|
@@ -18,7 +19,7 @@ export type StoredSchedule = Omit<ScheduledRun, 'runsAs'> & {
|
|
|
18
19
|
readonly appId: string;
|
|
19
20
|
status: ScheduledRun['status'];
|
|
20
21
|
/** Who the job runs as: whoever scheduled it, in their session (D7). */
|
|
21
|
-
readonly runAs:
|
|
22
|
+
readonly runAs: ActingAs;
|
|
22
23
|
};
|
|
23
24
|
export type RunStatus = 'pending' | 'running' | 'succeeded' | 'failed';
|
|
24
25
|
/** One delivery target of a job: a cron occurrence or a scheduled one-off (D7, D8). */
|
|
@@ -32,7 +33,7 @@ export type StoredRun = {
|
|
|
32
33
|
readonly scheduledFor: string;
|
|
33
34
|
readonly payload: JsonValue;
|
|
34
35
|
/** Cron runs as the system principal; a scheduled run as whoever scheduled it (D7). */
|
|
35
|
-
readonly runAs:
|
|
36
|
+
readonly runAs: ActingAs;
|
|
36
37
|
status: RunStatus;
|
|
37
38
|
attempts: number;
|
|
38
39
|
deliveries: number;
|
|
@@ -51,26 +52,30 @@ export type StoredAudit = AuditEntry & {
|
|
|
51
52
|
readonly seq: number;
|
|
52
53
|
readonly visibility: 'app' | 'cio';
|
|
53
54
|
};
|
|
55
|
+
/** An installed app: what it is. Its state lives in the engine's `AppStore`. */
|
|
54
56
|
export type App = {
|
|
55
57
|
manifest: Manifest;
|
|
56
58
|
schema: AppSchema;
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
tasks: Map<string, StoredTask>;
|
|
60
|
-
schedules: Map<string, StoredSchedule>;
|
|
61
|
-
runs: Map<string, StoredRun>;
|
|
62
|
-
cron: Map<string, CronState>;
|
|
63
|
-
audit: StoredAudit[];
|
|
59
|
+
/** An app with no school has its own timezone (V2c); otherwise the school's. */
|
|
60
|
+
timezone?: string;
|
|
64
61
|
};
|
|
65
62
|
export type Ctx = {
|
|
66
63
|
app: App;
|
|
67
|
-
principal:
|
|
64
|
+
principal: ActingAs;
|
|
68
65
|
actorId: string;
|
|
66
|
+
/** Whether this call can reach a school: a school app, in an environment that has one (V2c, D100). */
|
|
67
|
+
school: boolean;
|
|
69
68
|
/** Students this principal can see, computed once per call. */
|
|
70
69
|
students?: 'all' | Set<string>;
|
|
71
70
|
};
|
|
72
71
|
export declare const isStaffOrSystem: (ctx: Ctx) => boolean;
|
|
73
|
-
|
|
72
|
+
/**
|
|
73
|
+
* The school principal for a call that needs a school, or NOT_AVAILABLE: an account or a guest has no school,
|
|
74
|
+
* nor does a standalone app, nor an environment configured without one (V2c, D100).
|
|
75
|
+
*/
|
|
76
|
+
export declare function schoolPrincipal(ctx: Ctx): Principal;
|
|
77
|
+
/** The role names a principal acts under: its school role, an account's app roles, or `guest`. */
|
|
78
|
+
export declare function roleNamesOf(p: ActingAs): readonly string[];
|
|
74
79
|
/** Why a parent recipient was left out (D17). Recorded only in CIO-visible audit entries. */
|
|
75
80
|
export type SuppressedRecipient = {
|
|
76
81
|
personId: string;
|
|
@@ -80,7 +85,7 @@ export type SuppressedRecipient = {
|
|
|
80
85
|
export type ResolvedRecipients = {
|
|
81
86
|
recipients: {
|
|
82
87
|
personId: string;
|
|
83
|
-
role: Role;
|
|
88
|
+
role: Role | (string & {});
|
|
84
89
|
regarding?: string;
|
|
85
90
|
purpose?: 'correspondence' | 'consent';
|
|
86
91
|
}[];
|
|
@@ -89,15 +94,16 @@ export type ResolvedRecipients = {
|
|
|
89
94
|
/** The engine internals the Slice B modules use. `Engine` implements it. */
|
|
90
95
|
export interface Kernel {
|
|
91
96
|
readonly dataset: Dataset;
|
|
97
|
+
readonly store: AppStore;
|
|
92
98
|
nowIso(): string;
|
|
93
99
|
nowMs(): number;
|
|
94
|
-
timezone(): string;
|
|
100
|
+
timezone(app: App): string;
|
|
95
101
|
persistPlatform(app: App, kind: PlatformKind, items: readonly {
|
|
96
102
|
id: string;
|
|
97
103
|
}[]): Promise<void>;
|
|
98
104
|
remember(ctx: Ctx, key: string, result: unknown): Promise<void>;
|
|
99
105
|
idempotencyKey(options: unknown, scope: string): string | undefined;
|
|
100
|
-
resolveRecipients(ctx: Ctx, to: unknown, regarding: string | undefined): ResolvedRecipients
|
|
106
|
+
resolveRecipients(ctx: Ctx, to: unknown, regarding: string | undefined): Promise<ResolvedRecipients>;
|
|
101
107
|
}
|
|
102
108
|
/**
|
|
103
109
|
* Whether the current principal can see a subject student, under the school's visibility
|
package/dist/src/engine/state.js
CHANGED
|
@@ -1,6 +1,31 @@
|
|
|
1
1
|
import { visibleStudentIds, } from '@quad-education/canonical';
|
|
2
|
-
|
|
3
|
-
export const
|
|
2
|
+
import { QuadError } from "../contract/errors.js";
|
|
3
|
+
export const isStaffOrSystem = (ctx) => ctx.principal.kind === 'system' ||
|
|
4
|
+
(ctx.principal.kind === 'user' && ctx.principal.role === 'staff');
|
|
5
|
+
/**
|
|
6
|
+
* The school principal for a call that needs a school, or NOT_AVAILABLE: an account or a guest has no school,
|
|
7
|
+
* nor does a standalone app, nor an environment configured without one (V2c, D100).
|
|
8
|
+
*/
|
|
9
|
+
export function schoolPrincipal(ctx) {
|
|
10
|
+
const p = ctx.principal;
|
|
11
|
+
if (!ctx.school || p.kind === 'account' || p.kind === 'guest') {
|
|
12
|
+
throw new QuadError('NOT_AVAILABLE', 'there is no school here: this needs a school app running in a school');
|
|
13
|
+
}
|
|
14
|
+
return p;
|
|
15
|
+
}
|
|
16
|
+
/** The role names a principal acts under: its school role, an account's app roles, or `guest`. */
|
|
17
|
+
export function roleNamesOf(p) {
|
|
18
|
+
switch (p.kind) {
|
|
19
|
+
case 'user':
|
|
20
|
+
return [p.role];
|
|
21
|
+
case 'account':
|
|
22
|
+
return p.roles;
|
|
23
|
+
case 'guest':
|
|
24
|
+
return ['guest'];
|
|
25
|
+
default:
|
|
26
|
+
return [];
|
|
27
|
+
}
|
|
28
|
+
}
|
|
4
29
|
/**
|
|
5
30
|
* Whether the current principal can see a subject student, under the school's visibility
|
|
6
31
|
* policy (D4). Tasks and audit entries about a student follow it for everyone, staff
|
|
@@ -9,7 +34,10 @@ export const roleOfPrincipal = (ctx) => ctx.principal.kind === 'system' ? 'syste
|
|
|
9
34
|
export function seesSubject(k, ctx, studentId) {
|
|
10
35
|
if (studentId === undefined || ctx.principal.kind === 'system')
|
|
11
36
|
return true;
|
|
12
|
-
|
|
37
|
+
const principal = schoolPrincipal(ctx);
|
|
38
|
+
if (principal.kind === 'system')
|
|
39
|
+
return true;
|
|
40
|
+
ctx.students ??= visibleStudentIds(principal, k.dataset);
|
|
13
41
|
return ctx.students === 'all'
|
|
14
42
|
? k.dataset.students.some((s) => s.id === studentId)
|
|
15
43
|
: ctx.students.has(studentId);
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { AppSchema } from '@quad-education/schema';
|
|
2
|
+
import type { OutboxEntry } from '../platform-types.ts';
|
|
3
|
+
import type { PlatformKind } from './storage.ts';
|
|
4
|
+
export type { PlatformKind };
|
|
5
|
+
/** A stored record: the app's fields plus the system fields (id, createdAt, createdBy, updatedAt, updatedBy). */
|
|
6
|
+
export type StoredRecordData = Record<string, unknown>;
|
|
7
|
+
/**
|
|
8
|
+
* What a read needs from a store. A store may return a superset of the matching records and never fewer: the
|
|
9
|
+
* engine applies the access rules, the filters, the order and the page itself. The hints only let a store that
|
|
10
|
+
* has indexes read less.
|
|
11
|
+
*/
|
|
12
|
+
export type ReadHint = {
|
|
13
|
+
/** Every record the caller may read was created by this actor (the only rule is `own`). */
|
|
14
|
+
readonly ownedBy?: string;
|
|
15
|
+
readonly where?: unknown;
|
|
16
|
+
readonly orderBy?: unknown;
|
|
17
|
+
/** The entity's declared indexes, each a list of field names. */
|
|
18
|
+
readonly indexes: readonly (readonly string[])[];
|
|
19
|
+
};
|
|
20
|
+
export interface AppStore {
|
|
21
|
+
/**
|
|
22
|
+
* Get the app's state ready. When the stored schema hash differs from `schemaHash`, records and idempotency keys
|
|
23
|
+
* are cleared first (D12), and the new hash is recorded. A store with indexes needs the schema to lay them out.
|
|
24
|
+
*/
|
|
25
|
+
open(appId: string, schemaHash: string, schema: AppSchema): Promise<void>;
|
|
26
|
+
/** Remove everything the app has stored: records, keys, outbox and platform state. */
|
|
27
|
+
clear(appId: string): Promise<void>;
|
|
28
|
+
getRecord(appId: string, entity: string, id: string): Promise<StoredRecordData | undefined>;
|
|
29
|
+
/** Write a record. `previous` is the version being replaced, so indexes can be kept in step. */
|
|
30
|
+
putRecord(appId: string, entity: string, record: StoredRecordData, previous?: StoredRecordData): Promise<void>;
|
|
31
|
+
deleteRecord(appId: string, entity: string, record: StoredRecordData): Promise<void>;
|
|
32
|
+
/** Records of one entity that may match a read (see `ReadHint`). */
|
|
33
|
+
candidates(appId: string, entity: string, hint: ReadHint): Promise<StoredRecordData[]>;
|
|
34
|
+
/** Every record id and update time, by entity (for the run-twice effects snapshot). */
|
|
35
|
+
recordStamps(appId: string): Promise<Record<string, Record<string, string>>>;
|
|
36
|
+
getKey(appId: string, key: string): Promise<unknown>;
|
|
37
|
+
putKey(appId: string, key: string, result: unknown): Promise<void>;
|
|
38
|
+
getPlatform<T>(appId: string, kind: PlatformKind, id: string): Promise<T | undefined>;
|
|
39
|
+
allPlatform<T>(appId: string, kind: PlatformKind): Promise<T[]>;
|
|
40
|
+
putPlatform(appId: string, kind: PlatformKind, items: readonly {
|
|
41
|
+
id: string;
|
|
42
|
+
}[]): Promise<void>;
|
|
43
|
+
/** The next audit sequence number for the app: 1, then 2 and so on, never repeated. */
|
|
44
|
+
nextAuditSeq(appId: string): Promise<number>;
|
|
45
|
+
putOutbox(appId: string, entries: readonly OutboxEntry[]): Promise<void>;
|
|
46
|
+
outbox(appId: string): Promise<OutboxEntry[]>;
|
|
47
|
+
close(): void | Promise<void>;
|
|
48
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -4,14 +4,12 @@ export declare function taskView(ctx: Ctx, t: StoredTask): Task;
|
|
|
4
4
|
export declare function assignTask(k: Kernel, ctx: Ctx, input: Record<string, unknown>): Promise<{
|
|
5
5
|
tasks: Task[];
|
|
6
6
|
}>;
|
|
7
|
-
export declare function getTask(k: Kernel, ctx: Ctx, id: unknown): Task
|
|
8
|
-
export declare function listTasks(k: Kernel, ctx: Ctx, options: unknown): {
|
|
7
|
+
export declare function getTask(k: Kernel, ctx: Ctx, id: unknown): Promise<Task>;
|
|
8
|
+
export declare function listTasks(k: Kernel, ctx: Ctx, options: unknown): Promise<{
|
|
9
9
|
items: Task[];
|
|
10
10
|
nextCursor: string | null;
|
|
11
|
-
}
|
|
11
|
+
}>;
|
|
12
12
|
export declare function completeTask(k: Kernel, ctx: Ctx, id: unknown, options: unknown): Promise<Task>;
|
|
13
13
|
export declare function cancelTask(k: Kernel, ctx: Ctx, id: unknown): Promise<Task>;
|
|
14
14
|
/** Open tasks assigned to a person (the shell's inbox). */
|
|
15
|
-
export declare function inbox(
|
|
16
|
-
tasks: Map<string, StoredTask>;
|
|
17
|
-
}, personId: string): StoredTask[];
|
|
15
|
+
export declare function inbox(k: Kernel, appId: string, personId: string): Promise<StoredTask[]>;
|