@quad-education/sdk 0.1.4 → 0.3.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 +3 -1
- package/dist/contract-tests/apps.d.ts +1 -1
- package/dist/contract-tests/apps.js +1 -1
- 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 +1 -0
- package/dist/contract-tests/index.js +1 -0
- package/dist/contract-tests/suite.js +3 -24
- package/dist/src/contract/types.d.ts +1 -1
- 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 +14 -12
- package/dist/src/engine/engine.js +100 -135
- package/dist/src/engine/host.js +1 -1
- 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 +27 -24
- package/dist/src/engine/state.d.ts +4 -9
- 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 +17 -21
- package/package.json +4 -4
|
@@ -7,7 +7,8 @@ import { appendAudit, auditView, listAudit, recordAudit } from "./audit.js";
|
|
|
7
7
|
import { checkIndexCoverage } from "./db-indexes.js";
|
|
8
8
|
import { runQuery } from "./query.js";
|
|
9
9
|
import { cronList, finishRun, initCron, redeliverRun, releaseRun, scheduleAt, scheduleCancel, scheduleList, startDueRuns, } from "./runner.js";
|
|
10
|
-
import {
|
|
10
|
+
import { isStaffOrSystem, } from "./state.js";
|
|
11
|
+
import { MemoryStore } from "./memory-store.js";
|
|
11
12
|
import { assignTask, cancelTask, completeTask, getTask, inbox, listTasks, taskView, } from "./tasks.js";
|
|
12
13
|
import { entityOf, fieldOf, validateInput } from "./validate-input.js";
|
|
13
14
|
const SYSTEM_FIELDS = ['id', 'createdAt', 'createdBy', 'updatedAt', 'updatedBy'];
|
|
@@ -34,10 +35,10 @@ export class Engine {
|
|
|
34
35
|
clock = { kind: 'offset', offsetMs: 0 };
|
|
35
36
|
byId = new Map();
|
|
36
37
|
dataset;
|
|
37
|
-
|
|
38
|
-
constructor(dataset,
|
|
38
|
+
store;
|
|
39
|
+
constructor(dataset, store) {
|
|
39
40
|
this.dataset = dataset;
|
|
40
|
-
this.
|
|
41
|
+
this.store = store;
|
|
41
42
|
for (const entity of Object.keys(ENTITIES)) {
|
|
42
43
|
if (isDerived(entity)) {
|
|
43
44
|
// Worked out when an app first reads it (V2s S4.1), so it isn't indexed by id here.
|
|
@@ -52,11 +53,14 @@ export class Engine {
|
|
|
52
53
|
}
|
|
53
54
|
}
|
|
54
55
|
static async create(options) {
|
|
55
|
-
const
|
|
56
|
-
|
|
56
|
+
const store = options.store ??
|
|
57
|
+
(options.indexedDB ? await MemoryStore.open(options.indexedDB, options.dbName) : undefined);
|
|
58
|
+
if (!store)
|
|
59
|
+
throw new Error('an engine needs a store or an IndexedDB factory');
|
|
60
|
+
return new Engine(options.dataset, store);
|
|
57
61
|
}
|
|
58
62
|
close() {
|
|
59
|
-
this.
|
|
63
|
+
void this.store.close();
|
|
60
64
|
}
|
|
61
65
|
// ---- Platform-side API (shell and tests) ----
|
|
62
66
|
/** Load an app, resetting its store if the schema changed since last time (D12). */
|
|
@@ -65,51 +69,8 @@ export class Engine {
|
|
|
65
69
|
if (!parsed.ok)
|
|
66
70
|
throw new QuadError('VALIDATION', `invalid manifest: ${parsed.problems.join('; ')}`);
|
|
67
71
|
const appId = parsed.manifest.id;
|
|
68
|
-
|
|
69
|
-
const
|
|
70
|
-
if (meta && meta.schemaHash !== hash)
|
|
71
|
-
await this.storage.clearApp(appId, { schemaChangeOnly: true });
|
|
72
|
-
await this.storage.put('meta', [{ appId, schemaHash: hash }]);
|
|
73
|
-
const app = {
|
|
74
|
-
manifest: parsed.manifest,
|
|
75
|
-
schema,
|
|
76
|
-
records: new Map(),
|
|
77
|
-
keys: new Map(),
|
|
78
|
-
tasks: new Map(),
|
|
79
|
-
schedules: new Map(),
|
|
80
|
-
runs: new Map(),
|
|
81
|
-
cron: new Map(),
|
|
82
|
-
audit: [],
|
|
83
|
-
};
|
|
84
|
-
for (const entity of Object.keys(schema))
|
|
85
|
-
app.records.set(entity, new Map());
|
|
86
|
-
for (const r of await this.storage.getAll('records', appId)) {
|
|
87
|
-
app.records.get(r.entity)?.set(r.id, r.data);
|
|
88
|
-
}
|
|
89
|
-
for (const k of await this.storage.getAll('keys', appId))
|
|
90
|
-
app.keys.set(k.key, k.result);
|
|
91
|
-
for (const row of await this.storage.getAll('platform', appId)) {
|
|
92
|
-
if (row.kind === 'task')
|
|
93
|
-
app.tasks.set(row.id, row.data);
|
|
94
|
-
// Rows stored before run-as rules (D7) have no runAs; those were system-scheduled.
|
|
95
|
-
else if (row.kind === 'schedule' || row.kind === 'run') {
|
|
96
|
-
const data = row.data;
|
|
97
|
-
const withRunAs = { ...data, runAs: data.runAs ?? { kind: 'system', appId } };
|
|
98
|
-
if (row.kind === 'schedule')
|
|
99
|
-
app.schedules.set(row.id, withRunAs);
|
|
100
|
-
else
|
|
101
|
-
app.runs.set(row.id, withRunAs);
|
|
102
|
-
}
|
|
103
|
-
else if (row.kind === 'cron')
|
|
104
|
-
app.cron.set(row.id, row.data);
|
|
105
|
-
else
|
|
106
|
-
app.audit.push(row.data);
|
|
107
|
-
}
|
|
108
|
-
app.audit.sort((a, b) => a.seq - b.seq);
|
|
109
|
-
// Cron jobs no longer in the manifest stop; new ones start from now.
|
|
110
|
-
for (const name of app.cron.keys())
|
|
111
|
-
if (!app.manifest.cron.some((c) => c.name === name))
|
|
112
|
-
app.cron.delete(name);
|
|
72
|
+
await this.store.open(appId, schemaHash(schema), schema);
|
|
73
|
+
const app = { manifest: parsed.manifest, schema };
|
|
113
74
|
this.apps.set(appId, app);
|
|
114
75
|
await initCron(this, app);
|
|
115
76
|
}
|
|
@@ -119,53 +80,56 @@ export class Engine {
|
|
|
119
80
|
/** Clear an app's data and outbox (the shell's reset button). */
|
|
120
81
|
async resetApp(appId) {
|
|
121
82
|
const app = this.appFor(appId);
|
|
122
|
-
await this.
|
|
123
|
-
for (const records of app.records.values())
|
|
124
|
-
records.clear();
|
|
125
|
-
app.keys.clear();
|
|
126
|
-
app.tasks.clear();
|
|
127
|
-
app.schedules.clear();
|
|
128
|
-
app.runs.clear();
|
|
129
|
-
app.cron.clear();
|
|
130
|
-
app.audit.length = 0;
|
|
83
|
+
await this.store.clear(appId);
|
|
131
84
|
await initCron(this, app);
|
|
132
85
|
}
|
|
133
86
|
// ---- Platform-side API for Slice B (shell and tests) ----
|
|
134
87
|
/** Open tasks assigned to a person: the shell's inbox (D6). */
|
|
135
|
-
inbox(appId, personId) {
|
|
88
|
+
async inbox(appId, personId) {
|
|
136
89
|
const app = this.appFor(appId);
|
|
137
|
-
const ctx = {
|
|
138
|
-
|
|
90
|
+
const ctx = {
|
|
91
|
+
app,
|
|
92
|
+
principal: { kind: 'system', appId },
|
|
93
|
+
actorId: `system:${appId}`,
|
|
94
|
+
};
|
|
95
|
+
return (await inbox(this, appId, personId)).map((t) => taskView(ctx, t));
|
|
139
96
|
}
|
|
140
97
|
/** Every audit entry, including CIO-only ones (the shell's audit viewer, D19). */
|
|
141
|
-
auditLog(appId) {
|
|
142
|
-
|
|
98
|
+
async auditLog(appId) {
|
|
99
|
+
const entries = await this.store.allPlatform(appId, 'audit');
|
|
100
|
+
return entries
|
|
101
|
+
.sort((a, b) => a.seq - b.seq)
|
|
102
|
+
.map((e) => ({ ...auditView(e), visibility: e.visibility }));
|
|
143
103
|
}
|
|
144
104
|
/** Counts of everything a job can change, for run-twice tests (D20). */
|
|
145
105
|
async effectsSnapshot(appId) {
|
|
146
|
-
const
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
106
|
+
const [records, tasks, schedules, audit, outbox] = await Promise.all([
|
|
107
|
+
this.store.recordStamps(appId),
|
|
108
|
+
this.store.allPlatform(appId, 'task'),
|
|
109
|
+
this.store.allPlatform(appId, 'schedule'),
|
|
110
|
+
this.store.allPlatform(appId, 'audit'),
|
|
111
|
+
this.outbox(appId),
|
|
112
|
+
]);
|
|
151
113
|
return {
|
|
152
|
-
outbox:
|
|
153
|
-
tasks: Object.fromEntries(
|
|
154
|
-
schedules: Object.fromEntries(
|
|
155
|
-
audit:
|
|
114
|
+
outbox: outbox.length,
|
|
115
|
+
tasks: Object.fromEntries(tasks.map((t) => [t.id, t.status])),
|
|
116
|
+
schedules: Object.fromEntries(schedules.map((s) => [s.id, s.status])),
|
|
117
|
+
audit: audit.length,
|
|
156
118
|
records,
|
|
157
119
|
};
|
|
158
120
|
}
|
|
159
121
|
/** Runs for the job log, newest first. */
|
|
160
|
-
runs(appId) {
|
|
161
|
-
|
|
122
|
+
async runs(appId) {
|
|
123
|
+
const runs = await this.store.allPlatform(appId, 'run');
|
|
124
|
+
return runs.sort((a, b) => b.scheduledFor.localeCompare(a.scheduledFor) || a.id.localeCompare(b.id));
|
|
162
125
|
}
|
|
163
126
|
/**
|
|
164
127
|
* Who a call from the jobs host acts as: the principal of the run it belongs to (D7).
|
|
165
128
|
* Only runs that are currently running count, so a finished run's id can't be replayed.
|
|
166
129
|
*/
|
|
167
|
-
runPrincipal(appId, runId) {
|
|
168
|
-
|
|
130
|
+
async runPrincipal(appId, runId) {
|
|
131
|
+
this.appFor(appId);
|
|
132
|
+
const run = runId === undefined ? undefined : await this.store.getPlatform(appId, 'run', runId);
|
|
169
133
|
if (!run || run.status !== 'running') {
|
|
170
134
|
throw new QuadError('FORBIDDEN', 'calls from the jobs host must belong to a running job');
|
|
171
135
|
}
|
|
@@ -198,10 +162,10 @@ export class Engine {
|
|
|
198
162
|
return this.dataset.schools[0].timezone;
|
|
199
163
|
}
|
|
200
164
|
async persistPlatform(app, kind, items) {
|
|
201
|
-
await this.
|
|
165
|
+
await this.store.putPlatform(app.manifest.id, kind, items);
|
|
202
166
|
}
|
|
203
167
|
async outbox(appId) {
|
|
204
|
-
const entries = await this.
|
|
168
|
+
const entries = await this.store.outbox(appId);
|
|
205
169
|
return entries.sort((a, b) => a.sentAt.localeCompare(b.sentAt) || a.id.localeCompare(b.id));
|
|
206
170
|
}
|
|
207
171
|
/** Freeze the clock at an instant, or return to real time with `null` (D14). */
|
|
@@ -233,7 +197,7 @@ export class Engine {
|
|
|
233
197
|
}
|
|
234
198
|
sessionInfo(appId) {
|
|
235
199
|
this.appFor(appId);
|
|
236
|
-
return { appId, timezone: this.
|
|
200
|
+
return { appId, timezone: this.timezone(), clock: this.clock };
|
|
237
201
|
}
|
|
238
202
|
/** Handle one SDK call from `appId` on behalf of `principal`. */
|
|
239
203
|
async handle(appId, principal, method, params) {
|
|
@@ -285,7 +249,7 @@ export class Engine {
|
|
|
285
249
|
case 'schedule.cancel':
|
|
286
250
|
return scheduleCancel(this, ctx, p.id);
|
|
287
251
|
case 'schedule.list':
|
|
288
|
-
return scheduleList(ctx, p);
|
|
252
|
+
return scheduleList(this, ctx, p);
|
|
289
253
|
case 'cron.list':
|
|
290
254
|
return cronList(this, ctx);
|
|
291
255
|
case 'audit.record':
|
|
@@ -483,7 +447,7 @@ export class Engine {
|
|
|
483
447
|
if (typeof value !== 'string' || !def) {
|
|
484
448
|
throw new QuadError('VALIDATION', `'${String(value)}' is not an entity in this app's schema`);
|
|
485
449
|
}
|
|
486
|
-
return { name: value, def
|
|
450
|
+
return { name: value, def };
|
|
487
451
|
}
|
|
488
452
|
nowIso() {
|
|
489
453
|
return new Date(this.nowMs()).toISOString();
|
|
@@ -525,9 +489,11 @@ export class Engine {
|
|
|
525
489
|
/** Fields the current role may see or write (D25 visibleTo). The system principal sees all. */
|
|
526
490
|
fieldVisible(ctx, def, field) {
|
|
527
491
|
const visibleTo = fieldOf(def, field)?.visibleTo;
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
492
|
+
if (ctx.principal.kind === 'system' || visibleTo === undefined)
|
|
493
|
+
return true;
|
|
494
|
+
// Written in any case: an app role `Staff` is previewed by the staff persona.
|
|
495
|
+
const role = ctx.principal.role;
|
|
496
|
+
return visibleTo.some((v) => v.toLowerCase() === role);
|
|
531
497
|
}
|
|
532
498
|
/** A record as the current role receives it: hidden fields removed, not just emptied. */
|
|
533
499
|
shapeRecord(ctx, def, record) {
|
|
@@ -540,21 +506,21 @@ export class Engine {
|
|
|
540
506
|
requireOperation(ctx, entity, def, op) {
|
|
541
507
|
const rules = this.rules(ctx, def, op);
|
|
542
508
|
if (rules !== 'system' && rules.length === 0) {
|
|
543
|
-
const who = ctx.principal.kind === '
|
|
509
|
+
const who = ctx.principal.kind === 'system' ? 'system' : ctx.principal.role;
|
|
544
510
|
throw new QuadError('NOT_PERMITTED', `${who} users may not ${op} ${entity} records`);
|
|
545
511
|
}
|
|
546
512
|
return rules;
|
|
547
513
|
}
|
|
548
514
|
/** A readable record, or NOT_FOUND whether it's missing or just not yours (no existence leak). */
|
|
549
|
-
readable(ctx, entity, id) {
|
|
550
|
-
const record =
|
|
515
|
+
async readable(ctx, entity, id) {
|
|
516
|
+
const record = await this.store.getRecord(ctx.app.manifest.id, entity.name, str(id, 'id'));
|
|
551
517
|
if (!record || !this.canRead(ctx, entity.def, record)) {
|
|
552
518
|
throw new QuadError('NOT_FOUND', `no ${entity.name} record ${String(id)}`);
|
|
553
519
|
}
|
|
554
520
|
return record;
|
|
555
521
|
}
|
|
556
522
|
/** Writes may only touch fields the role can see, and may only point the subject at a visible student. */
|
|
557
|
-
checkWrite(ctx, entity, values) {
|
|
523
|
+
async checkWrite(ctx, entity, values) {
|
|
558
524
|
for (const key of Object.keys(values)) {
|
|
559
525
|
if (!this.fieldVisible(ctx, entity.def, key)) {
|
|
560
526
|
throw new QuadError('NOT_PERMITTED', `${entity.name}.${key} isn't available to you`);
|
|
@@ -578,7 +544,7 @@ export class Engine {
|
|
|
578
544
|
}
|
|
579
545
|
else {
|
|
580
546
|
const targetDef = entityOf(ctx.app.schema, field.to);
|
|
581
|
-
const target = ctx.app.
|
|
547
|
+
const target = await this.store.getRecord(ctx.app.manifest.id, field.to, value);
|
|
582
548
|
if (!targetDef || !target || !this.canRead(ctx, targetDef, target)) {
|
|
583
549
|
throw new QuadError('VALIDATION', `${key}: no ${field.to} record ${value}`);
|
|
584
550
|
}
|
|
@@ -586,25 +552,20 @@ export class Engine {
|
|
|
586
552
|
}
|
|
587
553
|
}
|
|
588
554
|
async remember(ctx, key, result) {
|
|
589
|
-
ctx.app.
|
|
590
|
-
await this.storage.put('keys', [{ appId: ctx.app.manifest.id, key, result }]);
|
|
555
|
+
await this.store.putKey(ctx.app.manifest.id, key, result);
|
|
591
556
|
}
|
|
592
557
|
idempotencyKey(options, scope) {
|
|
593
558
|
if (!isObject(options) || options.idempotencyKey === undefined)
|
|
594
559
|
return undefined;
|
|
595
560
|
return `${scope}:${str(options.idempotencyKey, 'idempotencyKey')}`;
|
|
596
561
|
}
|
|
597
|
-
async persist(ctx, entity, record) {
|
|
598
|
-
await this.storage.put('records', [
|
|
599
|
-
{ appId: ctx.app.manifest.id, entity, id: record.id, data: record },
|
|
600
|
-
]);
|
|
601
|
-
}
|
|
602
562
|
async dbCreate(ctx, entityValue, input, options) {
|
|
603
563
|
const entity = this.dbEntity(ctx, entityValue);
|
|
604
564
|
const rules = this.requireOperation(ctx, entity.name, entity.def, 'create');
|
|
605
565
|
const key = this.idempotencyKey(options, `db.create:${entity.name}`);
|
|
606
|
-
|
|
607
|
-
|
|
566
|
+
const remembered = key ? await this.store.getKey(ctx.app.manifest.id, key) : undefined;
|
|
567
|
+
if (typeof remembered === 'string') {
|
|
568
|
+
const existing = await this.store.getRecord(ctx.app.manifest.id, entity.name, remembered);
|
|
608
569
|
if (existing && this.canRead(ctx, entity.def, existing))
|
|
609
570
|
return this.shapeRecord(ctx, entity.def, existing);
|
|
610
571
|
}
|
|
@@ -612,7 +573,7 @@ export class Engine {
|
|
|
612
573
|
for (const k of Object.keys(values))
|
|
613
574
|
if (values[k] === null)
|
|
614
575
|
delete values[k];
|
|
615
|
-
this.checkWrite(ctx, entity, values);
|
|
576
|
+
await this.checkWrite(ctx, entity, values);
|
|
616
577
|
const now = this.nowIso();
|
|
617
578
|
const record = {
|
|
618
579
|
id: `${entity.name}_${crypto.randomUUID()}`,
|
|
@@ -625,21 +586,20 @@ export class Engine {
|
|
|
625
586
|
if (!this.matches(ctx, entity.def, rules, record)) {
|
|
626
587
|
throw new QuadError('NOT_PERMITTED', `you may not create this ${entity.name} record`);
|
|
627
588
|
}
|
|
628
|
-
|
|
629
|
-
await this.persist(ctx, entity.name, record);
|
|
589
|
+
await this.store.putRecord(ctx.app.manifest.id, entity.name, record);
|
|
630
590
|
if (key)
|
|
631
591
|
await this.remember(ctx, key, record.id);
|
|
632
592
|
return this.shapeRecord(ctx, entity.def, record);
|
|
633
593
|
}
|
|
634
594
|
async dbUpdate(ctx, entityValue, id, patch) {
|
|
635
595
|
const entity = this.dbEntity(ctx, entityValue);
|
|
636
|
-
const existing = this.readable(ctx, entity, id);
|
|
596
|
+
const existing = await this.readable(ctx, entity, id);
|
|
637
597
|
const rules = this.requireOperation(ctx, entity.name, entity.def, 'update');
|
|
638
598
|
if (!this.matches(ctx, entity.def, rules, existing)) {
|
|
639
599
|
throw new QuadError('NOT_PERMITTED', `you may not update this ${entity.name} record`);
|
|
640
600
|
}
|
|
641
601
|
const values = validateInput(entity.name, entity.def, patch, { partial: true });
|
|
642
|
-
this.checkWrite(ctx, entity, values);
|
|
602
|
+
await this.checkWrite(ctx, entity, values);
|
|
643
603
|
const record = { ...existing };
|
|
644
604
|
for (const [k, v] of Object.entries(values)) {
|
|
645
605
|
if (v === null)
|
|
@@ -652,18 +612,17 @@ export class Engine {
|
|
|
652
612
|
if (!this.matches(ctx, entity.def, rules, record)) {
|
|
653
613
|
throw new QuadError('NOT_PERMITTED', `this change would take the ${entity.name} record out of your reach`);
|
|
654
614
|
}
|
|
655
|
-
|
|
656
|
-
await this.persist(ctx, entity.name, record);
|
|
615
|
+
await this.store.putRecord(ctx.app.manifest.id, entity.name, record, existing);
|
|
657
616
|
return this.shapeRecord(ctx, entity.def, record);
|
|
658
617
|
}
|
|
659
|
-
dbGet(ctx, entityValue, id) {
|
|
618
|
+
async dbGet(ctx, entityValue, id) {
|
|
660
619
|
const entity = this.dbEntity(ctx, entityValue);
|
|
661
620
|
this.requireOperation(ctx, entity.name, entity.def, 'read');
|
|
662
|
-
return this.shapeRecord(ctx, entity.def, this.readable(ctx, entity, id));
|
|
621
|
+
return this.shapeRecord(ctx, entity.def, await this.readable(ctx, entity, id));
|
|
663
622
|
}
|
|
664
623
|
async dbList(ctx, entityValue, options) {
|
|
665
624
|
const entity = this.dbEntity(ctx, entityValue);
|
|
666
|
-
this.requireOperation(ctx, entity.name, entity.def, 'read');
|
|
625
|
+
const rules = this.requireOperation(ctx, entity.name, entity.def, 'read');
|
|
667
626
|
const { include, ...query } = (isObject(options) ? options : {});
|
|
668
627
|
const includes = include === undefined ? [] : Array.isArray(include) ? include : null;
|
|
669
628
|
if (!includes)
|
|
@@ -676,7 +635,13 @@ export class Engine {
|
|
|
676
635
|
}
|
|
677
636
|
}
|
|
678
637
|
// Access first, then filters and pages: results and cursors only ever cover readable records.
|
|
679
|
-
const
|
|
638
|
+
const candidates = await this.store.candidates(ctx.app.manifest.id, entity.name, {
|
|
639
|
+
...(rules !== 'system' && rules.every((r) => r === 'own') ? { ownedBy: ctx.actorId } : {}),
|
|
640
|
+
where: query.where,
|
|
641
|
+
orderBy: query.orderBy,
|
|
642
|
+
indexes: entity.def.indexes,
|
|
643
|
+
});
|
|
644
|
+
const readable = candidates.filter((r) => this.canRead(ctx, entity.def, r));
|
|
680
645
|
const fields = new Set([
|
|
681
646
|
...SYSTEM_FIELDS,
|
|
682
647
|
...Object.keys(entity.def.fields).filter((f) => this.fieldVisible(ctx, entity.def, f)),
|
|
@@ -688,19 +653,19 @@ export class Engine {
|
|
|
688
653
|
if (includes.length === 0)
|
|
689
654
|
return { items, nextCursor: page.nextCursor };
|
|
690
655
|
const schoolReads = new Map();
|
|
691
|
-
const withIncluded =
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
this.resolveRef(ctx, entity.def.fields[f], r[f], schoolReads)
|
|
696
|
-
|
|
697
|
-
}
|
|
656
|
+
const withIncluded = [];
|
|
657
|
+
for (const r of items) {
|
|
658
|
+
const included = {};
|
|
659
|
+
for (const f of includes)
|
|
660
|
+
included[f] = await this.resolveRef(ctx, entity.def.fields[f], r[f], schoolReads);
|
|
661
|
+
withIncluded.push({ ...r, $included: included });
|
|
662
|
+
}
|
|
698
663
|
for (const [target, count] of schoolReads) {
|
|
699
664
|
await this.auditSensitiveRead(ctx, target, this.tiers(ctx, target), count, 'db.include');
|
|
700
665
|
}
|
|
701
666
|
return { items: withIncluded, nextCursor: page.nextCursor };
|
|
702
667
|
}
|
|
703
|
-
resolveRef(ctx, field, value, schoolReads) {
|
|
668
|
+
async resolveRef(ctx, field, value, schoolReads) {
|
|
704
669
|
if (typeof value !== 'string' || !field.to)
|
|
705
670
|
return null;
|
|
706
671
|
if (field.to.startsWith('school.')) {
|
|
@@ -716,20 +681,19 @@ export class Engine {
|
|
|
716
681
|
}
|
|
717
682
|
// Included app records follow their own entity's rules (D25).
|
|
718
683
|
const def = entityOf(ctx.app.schema, field.to);
|
|
719
|
-
const record = ctx.app.
|
|
684
|
+
const record = await this.store.getRecord(ctx.app.manifest.id, field.to, value);
|
|
720
685
|
return def && record && this.canRead(ctx, def, record)
|
|
721
686
|
? this.shapeRecord(ctx, def, record)
|
|
722
687
|
: null;
|
|
723
688
|
}
|
|
724
689
|
async dbDelete(ctx, entityValue, id) {
|
|
725
690
|
const entity = this.dbEntity(ctx, entityValue);
|
|
726
|
-
const existing = this.readable(ctx, entity, id);
|
|
691
|
+
const existing = await this.readable(ctx, entity, id);
|
|
727
692
|
const rules = this.requireOperation(ctx, entity.name, entity.def, 'delete');
|
|
728
693
|
if (!this.matches(ctx, entity.def, rules, existing)) {
|
|
729
694
|
throw new QuadError('NOT_PERMITTED', `you may not delete this ${entity.name} record`);
|
|
730
695
|
}
|
|
731
|
-
|
|
732
|
-
await this.storage.deleteRecord(ctx.app.manifest.id, entity.name, existing.id);
|
|
696
|
+
await this.store.deleteRecord(ctx.app.manifest.id, entity.name, existing);
|
|
733
697
|
return null;
|
|
734
698
|
}
|
|
735
699
|
// ---- notify (D10, D17) ----
|
|
@@ -740,8 +704,9 @@ export class Engine {
|
|
|
740
704
|
throw new QuadError('UNDECLARED_TYPE', `notification type '${type}' isn't declared in app.manifest.json`);
|
|
741
705
|
}
|
|
742
706
|
const key = this.idempotencyKey(input, 'notify.send');
|
|
743
|
-
|
|
744
|
-
|
|
707
|
+
const remembered = key ? await this.store.getKey(ctx.app.manifest.id, key) : undefined;
|
|
708
|
+
if (remembered !== undefined)
|
|
709
|
+
return remembered;
|
|
745
710
|
const subject = str(input.subject, 'subject');
|
|
746
711
|
const body = str(input.body, 'body');
|
|
747
712
|
const channel = input.channel ?? 'inApp';
|
|
@@ -759,7 +724,7 @@ export class Engine {
|
|
|
759
724
|
if (this.byId.get(regarding)?.entity !== 'students')
|
|
760
725
|
throw new QuadError('VALIDATION', `no student ${regarding}`);
|
|
761
726
|
}
|
|
762
|
-
const { recipients, suppressed } = this.resolveRecipients(ctx, input.to, regarding);
|
|
727
|
+
const { recipients, suppressed } = await this.resolveRecipients(ctx, input.to, regarding);
|
|
763
728
|
const sentAt = this.nowIso();
|
|
764
729
|
const entries = recipients.map((r) => ({
|
|
765
730
|
id: `out_${crypto.randomUUID()}`,
|
|
@@ -776,8 +741,7 @@ export class Engine {
|
|
|
776
741
|
sentBy: ctx.actorId,
|
|
777
742
|
simulated: true,
|
|
778
743
|
}));
|
|
779
|
-
|
|
780
|
-
await this.storage.put('outbox', entries);
|
|
744
|
+
await this.store.putOutbox(manifest.id, entries);
|
|
781
745
|
await appendAudit(this, ctx.app, {
|
|
782
746
|
source: 'platform',
|
|
783
747
|
action: 'notification.sent',
|
|
@@ -807,12 +771,12 @@ export class Engine {
|
|
|
807
771
|
* Resolves recipients to people, applying the app's roles and D17. Parents are only ever
|
|
808
772
|
* reached about a specific student, and only through an eligible, unrestricted link.
|
|
809
773
|
*/
|
|
810
|
-
resolveRecipients(ctx, to, regarding) {
|
|
774
|
+
async resolveRecipients(ctx, to, regarding) {
|
|
811
775
|
const list = Array.isArray(to) ? to : [to];
|
|
812
776
|
if (list.length === 0)
|
|
813
777
|
throw new QuadError('VALIDATION', 'to must name at least one recipient');
|
|
814
778
|
const roles = servedRoles(ctx.app.manifest);
|
|
815
|
-
const senderIsStaff = ctx
|
|
779
|
+
const senderIsStaff = isStaffOrSystem(ctx);
|
|
816
780
|
const out = new Map();
|
|
817
781
|
const suppressed = new Map();
|
|
818
782
|
const suppress = (personId, studentId, purpose) => {
|
|
@@ -872,10 +836,11 @@ export class Engine {
|
|
|
872
836
|
else if ('role' in r) {
|
|
873
837
|
if (!['staff', 'student', 'parent'].includes(r.role))
|
|
874
838
|
throw new QuadError('VALIDATION', `unknown role ${String(r.role)}`);
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
839
|
+
const role = r.role;
|
|
840
|
+
if (!roles.includes(role))
|
|
841
|
+
throw new QuadError('VALIDATION', `${ctx.app.manifest.name} doesn't serve ${role} users`);
|
|
842
|
+
for (const p of this.dataset[PEOPLE[role]])
|
|
843
|
+
add(p.id, role);
|
|
879
844
|
}
|
|
880
845
|
else if ('relationship' in r && r.relationship === 'parentsOf') {
|
|
881
846
|
const studentId = str(r.studentId, 'studentId');
|
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 = {
|
|
@@ -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
|
+
}
|