@ultimat3/testing 31.15.0 → 31.17.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/CLAUDE.md +4 -0
- package/README.md +5 -1
- package/package.json +22 -22
- package/src/define-exercise.ts +28 -4
- package/src/errors.ts +7 -0
- package/src/exercise-crash.ts +9 -1
- package/src/exercise-report.ts +3 -0
- package/src/exercise-route-loads.ts +205 -0
- package/src/exercise-route-subjects.ts +162 -0
- package/src/exercise-statement-ceiling.ts +147 -0
- package/src/exercise-sweeps.ts +9 -6
- package/src/exercise.ts +48 -8
- package/src/fixture-jobs.ts +1 -1
- package/src/index.ts +19 -0
- package/src/scale-sweep-findings.ts +46 -0
- package/src/scale-sweep-run.ts +21 -13
- package/src/scale-sweep-seed.ts +140 -0
- package/src/scale-sweep.ts +19 -6
- package/src/seed-graph-values.ts +4 -1
- package/src/seed-graph.ts +5 -1
- package/src/sql-tables.ts +61 -0
package/CLAUDE.md
CHANGED
|
@@ -52,12 +52,16 @@ the off-barrel entry points `registry-isolation.ts`, `conformance.ts`. Full rule
|
|
|
52
52
|
| Fixtures | the preload registers the framework bag — an app registers only what it alone knows: `seed` as `seedFixture({ seeds, driver })` (`fixture-seed.ts`: once per test per name, rows captured on the way in, picked by label), `actorFor` |
|
|
53
53
|
| Every `e2eTest` is audited | `e2e-a11y*.ts`, `ax-node.ts`; no switch, `allow` needs a `because` † |
|
|
54
54
|
| The exercise pass runs what is registered | `exercise.ts` (`runExercisePass`): every action, query, job once, own tenant pair; overrides only via `defineExercise` † |
|
|
55
|
+
| A route `load` is exercised like a read | `exercise-route-loads.ts`: after the primitives, own tenant pair, swept and planned with them; its record is `RouteLoadRecord`, never in `records`; the crash proof's runs pace on the frozen clock (`exercise-crash.ts`) |
|
|
55
56
|
| An override `input` is awaited, as the call's actor | `exercise-override-input.ts`: inside the call's own request — the one way to a signed input † |
|
|
56
57
|
| A passkey test signs for real | `softAuthenticator` is `@ultimat3/auth/soft-authenticator`'s, never re-exported here (one value, one path: `flight-copies`) and never a second one (auth's own suites need it, and auth cannot import testing) |
|
|
57
58
|
| A reached job is crash-proven | `exercise-crash.ts`: only `diverged` is red (`X_JOB_CRASH_DIVERGED`) † |
|
|
58
59
|
| The tenant proof is taint only | `tenant-proof.ts`: B, A, B; B is A's role minus `tenancy:cross`. Leak = seeded canary or unhanded id (`tenant-canary.ts`); write = moved digest. Only `crossed` is red |
|
|
59
60
|
| Every statement the pass sent is planned | `plan-sweep.ts` + `plan-oracle.ts`: `X_QUERY_UNINDEXED` / `X_QUERY_SORT_UNSERVED` with the `indexes:` fix; no generic plan is `X_QUERY_PLAN_UNAVAILABLE`, never a pass † |
|
|
60
61
|
| A shape that grows with the rows is red | `scale-sweep-run.ts` + pure `judgeScale`: `X_QUERY_SCALES_WITH_ROWS` † |
|
|
62
|
+
| A sized-seed refusal is one finding, not N `unproven` | `scale-sweep-seed.ts`: table by table; only a primitive that read the lost table is `unproven`, `scaleSeedFindings` → `X_EXERCISE_SEED_FAILED` (`scale-sweep-run.test.ts`) |
|
|
63
|
+
| A lost table is read where a table is named | `sql-tables.ts` `statementTables`: `from`/`join`/`update`/`into`/`using` and their comma lists, never a column spelled like one; a view or history table over a lost table is lost too (`scale-sweep-seed.test.ts`). `x doctor`'s raw tenant SQL probe reads tables by the same function |
|
|
64
|
+
| One call has a statement ceiling | `exercise-statement-ceiling.ts`: `STATEMENTS_MAX` 100 per call, `statements: { max, why }` per entry; `X_STATEMENTS_OVER_BUDGET` (`exercise-statement-ceiling.test.ts`) |
|
|
61
65
|
| An erase is PROVED, not asserted | `subject-proof.ts`: a survivor outside `retain` is `X_SUBJECT_ERASE_INCOMPLETE`, never the value † |
|
|
62
66
|
| A captured failure replays as a test | `repro.ts`: `reproduce(bundle, { driver })`, `reproJob(runJobs, failure)` — what `x repro --write` emits † |
|
|
63
67
|
| A vendor's answers are a cassette | `cassette.ts`: replay = `mockFetch` routes, seal kept; record refused under `CI`, secrets scanned before disk; written by action's `stableStringify`, loaded dynamically (`serializeCassette`) † |
|
package/README.md
CHANGED
|
@@ -38,7 +38,8 @@ unitTest('the clock moves only when the test moves it', ({ clock }) => {
|
|
|
38
38
|
| `seed-graph-error.ts` | `X_SEED_GRAPH_UNSATISFIED`, its fix naming the `defineFactory` to write; `X_SEED_GRAPH_ENTITY_UNKNOWN`, a plan and a writer built from two entity sets |
|
|
39
39
|
| `seed-writer.ts` | `entitySeedWriter({ entities, client })` or `({ entities, driver? })` — the `SeedWriter` that writes a graph through each entity's own repository: Postgres or PGlite through a client, or a driver. `@ultimat3/entity` loads on the first write. `snapshot(rows)`, required on every `SeedWriter`, reads rows back as one digest each (`md5(t::text)` over a client), `null` for a row gone |
|
|
40
40
|
| `exercise.ts` | `runExercisePass({ entities, writer, roles, seed?, overrides?, only? })` — every registered action, query and job once, each on its own committed tenant pair, one `ExerciseRecord` per primitive, the tenant proof's verdict on its `tenant`. What `x exercise` runs |
|
|
41
|
-
| `
|
|
41
|
+
| `exercise-route-subjects.ts` · `exercise-route-loads.ts` | `routeLoadSubjects()` — every `app/`/`site/` file route with a `load`; handed to `runExercisePass({ …, routes, onRoutes })`, each load runs after the primitives in a tenant pair of its own (an `:id` bound to a seeded row, else the route's `prerender()` sample), one `RouteLoadRecord` each with the statement ceiling, scale and plan proofs |
|
|
42
|
+
| `define-exercise.ts` | `defineExercise({ <name>: { actor, input?, runs? } \| { off: '<why>' } }, { actor?: <entity>, factories?: { <entity name>: defineFactory(…) }, setup?: () => mockFetch(…) \| cassette(…) })` — an app's overrides (the second argument names the entity whose rows are the actors, and the factories that build a table no generated row satisfies — a cross-column `satisfies` — keyed by entity name, unknown ones `X_DECLARATION_UNKNOWN`), `apps/web/exercise.ts`'s one export; a blank `off` is `X_CONTRACT_EXERCISE_UNDECLARED`, an unknown name `X_DECLARATION_UNKNOWN` when the pass runs. An entry's `statements: { max, why }` moves that primitive's statement ceiling (a blank `why` is `X_CONTRACT_EXERCISE_UNDECLARED`, `max` a whole count ≥ 1) |
|
|
42
43
|
| `exercise-setup.ts` | `withExerciseSetup(room, setup)`: the app's `setup` run inside the sealed room before the first row, its handle disposed before the room restores the network; an `allowHost` in it is `X_EXERCISE_SETUP_UNSEALED`. Types `ExerciseSetup`, `ExerciseSetupHandle` |
|
|
43
44
|
| `exercise-actor.ts` · `exercise-input.ts` · `exercise-report.ts` | the first `x policy explain` actor the policy allows, minted in the primitive's tenant · the input: override, then a seeded id by field stem, then the minimal draw (`@ultimat3/schema/sample`, loaded dynamically) · the room one run executes in (network sealed, mail captured, clock frozen) and its record |
|
|
44
45
|
| `exercise-override-line.ts` | `overrideLine`, the entry an unreached record says to paste: valid TS — the actor the pass ran as (`testActor(name, { roles, permissions }).actor`, `null` signed out, left out when the entry declares one) and each id field bound to the seeded row the pass used; an id it could not bind is the string `UNBOUND_ID` |
|
|
@@ -46,6 +47,9 @@ unitTest('the clock moves only when the test moves it', ({ clock }) => {
|
|
|
46
47
|
| `tenant-canary.ts` | internal: `tenantTaint` — one tenant's rows, ids and marks (row canaries, key parts of `MIN_TAINT_ID_LENGTH` 8 or more no other tenant shares); `findTaint` — every path holding one |
|
|
47
48
|
| `exercise-crash.ts` | internal: `proveCrash` — a job the pass reached, run through `crashProof` with its control's input and actor, after the tenant proof; the `CrashProof` on `ExerciseRecord.crash` |
|
|
48
49
|
| `scale-sweep.ts` · `scale-sweep-graph.ts` · `scale-sweep-run.ts` · `exercise-sweeps.ts` | `judgeScale(small, large)`, pure · one tenant at a size, its rows of no tenant pointed at the pass's own · the two sized runs · both sweeps after the pass, onto each record's `scale` and `plans` |
|
|
50
|
+
| `scale-sweep-seed.ts` · `scale-sweep-findings.ts` | the sized seed written table by table: a refusal loses that table and the tables pointing at it, and leaves `unproven` (with `seed: ScaleSeedFailure`) only the primitives whose own statements read one · `scaleSeedFindings(records)`: one `X_EXERCISE_SEED_FAILED` per lost table, every reader named |
|
|
51
|
+
| `sql-tables.ts` | `statementTables(sql)`, pure: every table one statement names after `from` / `join` / `update` / `into` / `using`, each name of a comma list there too (`from orgs o, posts p`), last part of a qualified or quoted name, lowercased. The sweep's lost-table reader and `x doctor`'s raw tenant SQL probe read tables by it |
|
|
52
|
+
| `exercise-statement-ceiling.ts` | `judgeStatementCeiling(calls, declared?)`, pure: the busiest call's statements no `expectedQueryLoop` declared (`expected` counts the rest) against `STATEMENTS_MAX` (100) or the entry's `statements.max`, onto `ExerciseRecord.statementCeiling` · `statementCeilingFindings(records)`: `X_STATEMENTS_OVER_BUDGET`, the three busiest shapes named. Whether either finding is red is the caller's (`x exercise`) |
|
|
49
53
|
| `plan-oracle.ts` · `plan-sweep.ts` · `plan-sweep-fix.ts` · `plan-sweep-report.ts` | `judgePlan(answer, tables)`, pure: the red nodes · `sweepPlans(client, sent, entities)`: `PREPARE` + `explain execute` in a read-only transaction · verdict to `indexes:` line · the coded findings `x exercise` prints |
|
|
50
54
|
| `job-crash-proof.ts` | `crashProof(handle, input, { context?, seed? })` — one clean run, then the worker killed at every step boundary it crossed, then each answer lost; `{ boundaries, divergences, reruns }`, a divergence carrying its `X_JOB_CRASH_DIVERGED` |
|
|
51
55
|
| `job-simulate.ts` | `simulateJobs({ seed?, seeds, jobs, workers, faults, invariant })` — seeded races on the shared simulated driver; `X_JOB_SIM_INVARIANT`, `X_JOB_SIM_NONDETERMINISTIC`; `x test job --seed <n>` replays one |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ultimat3/testing",
|
|
3
|
-
"version": "31.
|
|
3
|
+
"version": "31.17.0",
|
|
4
4
|
"description": "Test harness: cloned template DBs per worker, frozen clock, sealed network, 6 test types",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ultimate",
|
|
@@ -47,26 +47,26 @@
|
|
|
47
47
|
"test": "bun test"
|
|
48
48
|
},
|
|
49
49
|
"dependencies": {
|
|
50
|
-
"@ultimat3/action": "31.
|
|
51
|
-
"@ultimat3/ai": "31.
|
|
52
|
-
"@ultimat3/auth": "31.
|
|
53
|
-
"@ultimat3/cache": "31.
|
|
54
|
-
"@ultimat3/core": "31.
|
|
55
|
-
"@ultimat3/db": "31.
|
|
56
|
-
"@ultimat3/entity": "31.
|
|
57
|
-
"@ultimat3/http": "31.
|
|
58
|
-
"@ultimat3/i18n": "31.
|
|
59
|
-
"@ultimat3/jobs": "31.
|
|
60
|
-
"@ultimat3/mail": "31.
|
|
61
|
-
"@ultimat3/notify": "31.
|
|
62
|
-
"@ultimat3/policy": "31.
|
|
63
|
-
"@ultimat3/pwa": "31.
|
|
64
|
-
"@ultimat3/query": "31.
|
|
65
|
-
"@ultimat3/realtime": "31.
|
|
66
|
-
"@ultimat3/render": "31.
|
|
67
|
-
"@ultimat3/schema": "31.
|
|
68
|
-
"@ultimat3/scraping": "31.
|
|
69
|
-
"@ultimat3/seo": "31.
|
|
70
|
-
"@ultimat3/time": "31.
|
|
50
|
+
"@ultimat3/action": "31.17.0",
|
|
51
|
+
"@ultimat3/ai": "31.17.0",
|
|
52
|
+
"@ultimat3/auth": "31.17.0",
|
|
53
|
+
"@ultimat3/cache": "31.17.0",
|
|
54
|
+
"@ultimat3/core": "31.17.0",
|
|
55
|
+
"@ultimat3/db": "31.17.0",
|
|
56
|
+
"@ultimat3/entity": "31.17.0",
|
|
57
|
+
"@ultimat3/http": "31.17.0",
|
|
58
|
+
"@ultimat3/i18n": "31.17.0",
|
|
59
|
+
"@ultimat3/jobs": "31.17.0",
|
|
60
|
+
"@ultimat3/mail": "31.17.0",
|
|
61
|
+
"@ultimat3/notify": "31.17.0",
|
|
62
|
+
"@ultimat3/policy": "31.17.0",
|
|
63
|
+
"@ultimat3/pwa": "31.17.0",
|
|
64
|
+
"@ultimat3/query": "31.17.0",
|
|
65
|
+
"@ultimat3/realtime": "31.17.0",
|
|
66
|
+
"@ultimat3/render": "31.17.0",
|
|
67
|
+
"@ultimat3/schema": "31.17.0",
|
|
68
|
+
"@ultimat3/scraping": "31.17.0",
|
|
69
|
+
"@ultimat3/seo": "31.17.0",
|
|
70
|
+
"@ultimat3/time": "31.17.0"
|
|
71
71
|
}
|
|
72
72
|
}
|
package/src/define-exercise.ts
CHANGED
|
@@ -3,13 +3,19 @@
|
|
|
3
3
|
// A blank `off` is refused at declaration, an unknown name when the pass runs. A key is a bare name
|
|
4
4
|
// or a kind-qualified one (`'job:eraseAccount'`), which wins over the bare name for its kind.
|
|
5
5
|
|
|
6
|
-
import type {
|
|
7
|
-
import { renderCauseValue, renderFixLiteral, UltimateError } from '@ultimat3/core';
|
|
6
|
+
import type { ExerciseActorOptions, ExerciseOffOptions } from '@ultimat3/action';
|
|
7
|
+
import { finiteCount, renderCauseValue, renderFixLiteral, UltimateError } from '@ultimat3/core';
|
|
8
8
|
import type { ExerciseSetup } from './exercise-setup';
|
|
9
|
+
import type { ExerciseStatementCeiling } from './exercise-statement-ceiling';
|
|
9
10
|
import type { SeedFactory } from './seed-graph-plan';
|
|
10
11
|
|
|
11
|
-
/**
|
|
12
|
-
|
|
12
|
+
/**
|
|
13
|
+
* 39's option type — `{ actor, input?, runs? }` or `{ off: '<reason>' }` — and the pass's own
|
|
14
|
+
* `statements: { max, why }`: the ceiling one call is held to, `STATEMENTS_MAX` when omitted.
|
|
15
|
+
*/
|
|
16
|
+
export type ExerciseOverride =
|
|
17
|
+
| (ExerciseActorOptions & { readonly statements?: ExerciseStatementCeiling })
|
|
18
|
+
| ExerciseOffOptions;
|
|
13
19
|
|
|
14
20
|
/**
|
|
15
21
|
* What `defineExercise` returns: the overrides, by primitive name. Read by `runExercisePass` and,
|
|
@@ -81,6 +87,23 @@ const blankReason = (name: string): UltimateError =>
|
|
|
81
87
|
fix: `defineExercise({ ${renderFixLiteral(name, '<name>')}: { off: '<why this primitive cannot run in the exercise pass>' } }) # in apps/web/exercise.ts`,
|
|
82
88
|
});
|
|
83
89
|
|
|
90
|
+
/** The same silence for a ceiling: `statements: { max }` with no stated reason to move it. */
|
|
91
|
+
const blankCeiling = (name: string): UltimateError =>
|
|
92
|
+
new UltimateError({
|
|
93
|
+
code: 'X_CONTRACT_EXERCISE_UNDECLARED',
|
|
94
|
+
cause: `defineExercise() moves the statement ceiling of ${renderCauseValue(name)} with a blank why, so the exception is silent`,
|
|
95
|
+
fix: `defineExercise({ ${renderFixLiteral(name, '<name>')}: { statements: { max: <n>, why: '<why one call sends that many>' } } }) # in apps/web/exercise.ts`,
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
/** The entry's ceiling, held to a whole count ≥ 1 and a stated reason. */
|
|
99
|
+
const checkCeiling = (name: string, override: ExerciseOverride): void => {
|
|
100
|
+
if ('off' in override || override.statements === undefined) return;
|
|
101
|
+
finiteCount('defineExercise()', `${name}.statements.max`, override.statements.max, 1);
|
|
102
|
+
const { why } = override.statements;
|
|
103
|
+
// Typed, but an untyped `exercise.ts` can omit it: absent is as silent as blank.
|
|
104
|
+
if (typeof why !== 'string' || why.trim().length === 0) throw blankCeiling(name);
|
|
105
|
+
};
|
|
106
|
+
|
|
84
107
|
export function defineExercise(
|
|
85
108
|
overrides: Readonly<Record<string, ExerciseOverride>>,
|
|
86
109
|
app: ExerciseAppOptions = {},
|
|
@@ -89,6 +112,7 @@ export function defineExercise(
|
|
|
89
112
|
// `Object.entries`, never `for in`: an inherited key is not a declaration.
|
|
90
113
|
for (const [name, override] of Object.entries(overrides)) {
|
|
91
114
|
if ('off' in override && override.off.trim().length === 0) throw blankReason(name);
|
|
115
|
+
checkCeiling(name, override);
|
|
92
116
|
entries.set(name, override);
|
|
93
117
|
}
|
|
94
118
|
return Object.freeze({
|
package/src/errors.ts
CHANGED
|
@@ -76,6 +76,9 @@ export const TESTING_ERROR_CODES = [
|
|
|
76
76
|
'X_TEST_MAIL_EXPECTED',
|
|
77
77
|
'X_TEST_ADAPTER_PORT_UNSWAPPABLE',
|
|
78
78
|
'X_TEST_FACTORY_INVALID',
|
|
79
|
+
'X_EXERCISE_SEED_FAILED',
|
|
80
|
+
'X_STATEMENTS_OVER_BUDGET',
|
|
81
|
+
'X_EXERCISE_EMPTY_REACH',
|
|
79
82
|
] as const;
|
|
80
83
|
|
|
81
84
|
export type TestingErrorCode = (typeof TESTING_ERROR_CODES)[number];
|
|
@@ -154,6 +157,10 @@ export const TESTING_ERROR_TITLES: Readonly<Record<TestingErrorCode, string>> =
|
|
|
154
157
|
X_TEST_MAIL_EXPECTED: 'toHaveSentMail was handed something other than the mail fixture',
|
|
155
158
|
X_TEST_ADAPTER_PORT_UNSWAPPABLE: 'swapAdapter() was named a port it cannot swap for one test',
|
|
156
159
|
X_TEST_FACTORY_INVALID: 'a factory builds a row its own entity refuses',
|
|
160
|
+
X_EXERCISE_SEED_FAILED: 'The scale sweep could not write the sized rows of one entity',
|
|
161
|
+
X_STATEMENTS_OVER_BUDGET: 'One primitive call sent more statements than its ceiling',
|
|
162
|
+
X_EXERCISE_EMPTY_REACH:
|
|
163
|
+
'an exercised primitive was reached and sent no statement and had no effect',
|
|
157
164
|
};
|
|
158
165
|
|
|
159
166
|
// Titles must be registered for `format()` to render the contract's first line. Every code above is
|
package/src/exercise-crash.ts
CHANGED
|
@@ -6,6 +6,7 @@ import type { Actor } from '@ultimat3/core';
|
|
|
6
6
|
import { ctxOf, isUltimateError, renderThrowable } from '@ultimat3/core';
|
|
7
7
|
import type { AnyJobHandle } from '@ultimat3/jobs';
|
|
8
8
|
import type { CrashFinding, CrashProof } from './exercise-report';
|
|
9
|
+
import { PRELOAD_CLOCK } from './fixture-jobs';
|
|
9
10
|
import type { CrashDivergence } from './job-crash-proof';
|
|
10
11
|
import { crashProof } from './job-crash-proof';
|
|
11
12
|
|
|
@@ -31,7 +32,14 @@ export async function proveCrash(
|
|
|
31
32
|
input: unknown,
|
|
32
33
|
actor: Actor | null,
|
|
33
34
|
): Promise<CrashProof> {
|
|
34
|
-
|
|
35
|
+
// The control's worker clock (`fixture-jobs.ts`): `ctxOf`'s default read the frozen `Date` but
|
|
36
|
+
// had no `advance`, so a `backfill()` pacer slept its whole `rate` interval in WALL time on every
|
|
37
|
+
// killed rerun — 8 of the reference app's 23 s pass.
|
|
38
|
+
const worker = ctxOf(
|
|
39
|
+
actor === null
|
|
40
|
+
? { role: 'worker', clock: PRELOAD_CLOCK }
|
|
41
|
+
: { role: 'worker', actor, clock: PRELOAD_CLOCK },
|
|
42
|
+
);
|
|
35
43
|
try {
|
|
36
44
|
const report = await crashProof(handle, input, { context: () => worker });
|
|
37
45
|
const counted = {
|
package/src/exercise-report.ts
CHANGED
|
@@ -9,6 +9,7 @@ import { expectedSeqScanReason, statementFingerprint } from '@ultimat3/db';
|
|
|
9
9
|
import { captureDeterminism, installDeterminism, restoreCapturedDeterminism } from './determinism';
|
|
10
10
|
import type { ExerciseDefect } from './exercise-defect';
|
|
11
11
|
import { roomMail } from './exercise-room-mail';
|
|
12
|
+
import type { StatementCeilingProof } from './exercise-statement-ceiling';
|
|
12
13
|
import { routeMatches } from './mock-route';
|
|
13
14
|
import type { PlanProof, SentStatement } from './plan-sweep';
|
|
14
15
|
import type { LoggedRequest } from './request-log';
|
|
@@ -128,6 +129,8 @@ export interface ExerciseRecord {
|
|
|
128
129
|
readonly plans?: PlanProof;
|
|
129
130
|
/** On a reached primitive: its statement shapes at 2 and at 8 rows a table (`scale-sweep.ts`). */
|
|
130
131
|
readonly scale?: ScaleProof;
|
|
132
|
+
/** On a primitive whose control ran: its busiest call against its statement ceiling. */
|
|
133
|
+
readonly statementCeiling?: StatementCeilingProof;
|
|
131
134
|
/** Wall time of each proof that ran on it; `ms` above is the control's own call. */
|
|
132
135
|
readonly proofMs?: ProofMs;
|
|
133
136
|
}
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
// One route `load` in the exercise pass: called once in its own seeded tenant, inside the room, as
|
|
2
|
+
// the runtime calls it (`routeDataFor` in a request as the chosen actor) — its statements counted,
|
|
3
|
+
// its busiest call held to the statement ceiling, then swept at 2 and 8 rows a table and planned
|
|
4
|
+
// beside the primitives. A page read is a read like a query's: an N+1 in it is the same red.
|
|
5
|
+
|
|
6
|
+
import type { Actor } from '@ultimat3/core';
|
|
7
|
+
import { isUltimateError, renderThrowable } from '@ultimat3/core';
|
|
8
|
+
import type { ExerciseOverrides } from './define-exercise';
|
|
9
|
+
import type { RoleGrants } from './exercise-actor';
|
|
10
|
+
import { seatActorUsers } from './exercise-actor-user';
|
|
11
|
+
import type {
|
|
12
|
+
ExerciseEffect,
|
|
13
|
+
ExerciseRecord,
|
|
14
|
+
ExerciseRoom,
|
|
15
|
+
Observation,
|
|
16
|
+
ProofMs,
|
|
17
|
+
} from './exercise-report';
|
|
18
|
+
import { withExerciseRequest } from './exercise-request';
|
|
19
|
+
import type { RouteLoadSubject, RouteParamsValue } from './exercise-route-subjects';
|
|
20
|
+
import { chooseRouteActor, routeParams, routeUrl } from './exercise-route-subjects';
|
|
21
|
+
import type { StatementCeilingProof } from './exercise-statement-ceiling';
|
|
22
|
+
import { judgeStatementCeiling } from './exercise-statement-ceiling';
|
|
23
|
+
import { actorRowsOf, seated } from './exercise-sweeps';
|
|
24
|
+
import type { PlanProof } from './plan-sweep';
|
|
25
|
+
import type { ScaleProof } from './scale-sweep';
|
|
26
|
+
import type { ScaleSubject } from './scale-sweep-run';
|
|
27
|
+
import type { SeedGraph } from './seed-graph-plan';
|
|
28
|
+
import type { SeedEntity } from './seed-graph-shape';
|
|
29
|
+
|
|
30
|
+
/** What one route's `load` did in the pass. `name` is the URL pattern; `file` the route file. */
|
|
31
|
+
export interface RouteLoadRecord {
|
|
32
|
+
readonly kind: 'route';
|
|
33
|
+
readonly name: string;
|
|
34
|
+
readonly file: string;
|
|
35
|
+
readonly outcome: 'reached' | 'refused' | 'unreached';
|
|
36
|
+
readonly code?: string;
|
|
37
|
+
readonly reason?: string;
|
|
38
|
+
readonly statements: number;
|
|
39
|
+
readonly effects: readonly ExerciseEffect[];
|
|
40
|
+
readonly ms: number;
|
|
41
|
+
readonly statementCeiling?: StatementCeilingProof;
|
|
42
|
+
readonly plans?: PlanProof;
|
|
43
|
+
readonly scale?: ScaleProof;
|
|
44
|
+
readonly proofMs?: ProofMs;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The room's and the sweeps' key: never a primitive's, whose names are identifiers. */
|
|
48
|
+
export const routeLabel = (path: string): string => `route:${path}`;
|
|
49
|
+
|
|
50
|
+
/** The pass's options, as far as choosing who loads a page goes. */
|
|
51
|
+
export interface RouteCallOptions {
|
|
52
|
+
readonly entities: readonly SeedEntity[];
|
|
53
|
+
readonly overrides?: ExerciseOverrides;
|
|
54
|
+
readonly roles: RoleGrants;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The page's data, resolved as a render resolves it, in a request as `actor`. */
|
|
58
|
+
export const callRoute = (
|
|
59
|
+
route: RouteLoadSubject,
|
|
60
|
+
params: RouteParamsValue,
|
|
61
|
+
actor: Actor | null,
|
|
62
|
+
): Promise<unknown> =>
|
|
63
|
+
withExerciseRequest(routeLabel(route.path), actor, () =>
|
|
64
|
+
route.load({ params, url: routeUrl(route.path, params) }),
|
|
65
|
+
);
|
|
66
|
+
|
|
67
|
+
/** Who loads `route` in `tenant` of `graph`, and with which params — or none. */
|
|
68
|
+
export async function routeCall(
|
|
69
|
+
route: RouteLoadSubject,
|
|
70
|
+
options: RouteCallOptions,
|
|
71
|
+
graph: SeedGraph,
|
|
72
|
+
tenant: string,
|
|
73
|
+
): Promise<
|
|
74
|
+
| { readonly actor: Actor | null; readonly params: RouteParamsValue }
|
|
75
|
+
| { readonly refused?: true; readonly reason: string }
|
|
76
|
+
> {
|
|
77
|
+
const chosen = chooseRouteActor(route.permission, options.roles, tenant);
|
|
78
|
+
if (chosen.kind === 'refused') return { refused: true, reason: chosen.reason };
|
|
79
|
+
const actor = seated(chosen.actor, tenant, actorRowsOf(options, graph));
|
|
80
|
+
const params = await routeParams(route, graph, options.entities, { tenant, actorId: actor?.id });
|
|
81
|
+
if (params.kind === 'none') return { reason: params.reason };
|
|
82
|
+
// A user, as a request's actor always is: its `x_users` row before the call.
|
|
83
|
+
await seatActorUsers([actor]);
|
|
84
|
+
return { actor, params: params.params };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const unreachedBy = (seen: Observation<unknown>) => {
|
|
88
|
+
if ('error' in seen) {
|
|
89
|
+
const { error } = seen;
|
|
90
|
+
return {
|
|
91
|
+
outcome: 'unreached' as const,
|
|
92
|
+
...(isUltimateError(error) ? { code: error.code } : {}),
|
|
93
|
+
reason: `its load threw: ${renderThrowable(error)}`,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
const [host] = seen.observed.refusedHosts;
|
|
97
|
+
return host === undefined
|
|
98
|
+
? undefined
|
|
99
|
+
: { outcome: 'unreached' as const, reason: `its load called ${host}, which the pass seals` };
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
/** `route`'s load once, in `tenant`: the record before the sweeps add their proofs. */
|
|
103
|
+
export async function exerciseRouteLoad(
|
|
104
|
+
route: RouteLoadSubject,
|
|
105
|
+
options: RouteCallOptions,
|
|
106
|
+
at: { readonly graph: SeedGraph; readonly tenant: string; readonly room: ExerciseRoom },
|
|
107
|
+
): Promise<RouteLoadRecord> {
|
|
108
|
+
const none = { kind: 'route' as const, name: route.path, file: route.file };
|
|
109
|
+
const empty = { ...none, statements: 0, effects: [], ms: 0 };
|
|
110
|
+
const call = await routeCall(route, options, at.graph, at.tenant);
|
|
111
|
+
if ('reason' in call) {
|
|
112
|
+
return {
|
|
113
|
+
...empty,
|
|
114
|
+
outcome: call.refused === true ? 'refused' : 'unreached',
|
|
115
|
+
reason: call.reason,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
const started = performance.now();
|
|
119
|
+
const seen = await at.room.observe(routeLabel(route.path), () =>
|
|
120
|
+
callRoute(route, call.params, call.actor),
|
|
121
|
+
);
|
|
122
|
+
const ms = Math.round(performance.now() - started);
|
|
123
|
+
const { observed } = seen;
|
|
124
|
+
const ran = { ...none, statements: observed.statements, effects: observed.effects, ms };
|
|
125
|
+
const statementCeiling = judgeStatementCeiling([observed]);
|
|
126
|
+
const failed = unreachedBy(seen);
|
|
127
|
+
return {
|
|
128
|
+
...ran,
|
|
129
|
+
...(failed ?? { outcome: 'reached' as const }),
|
|
130
|
+
...(statementCeiling === undefined ? {} : { statementCeiling }),
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** The route as the scale sweep calls it: `input` is the params `routeCall` bound at each size. */
|
|
135
|
+
export const routeScaleSubject = (route: RouteLoadSubject): ScaleSubject => ({
|
|
136
|
+
name: routeLabel(route.path),
|
|
137
|
+
call: async (input, actor) => {
|
|
138
|
+
await callRoute(route, input as RouteParamsValue, actor);
|
|
139
|
+
return {};
|
|
140
|
+
},
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Every route after the primitives, each in the tenant pair after theirs (`pairGraph`'s rule: its
|
|
145
|
+
* cost is its pair's), and the sweep's view of them: a scale subject and its sized-call recipe.
|
|
146
|
+
*/
|
|
147
|
+
export async function runRouteLoads(
|
|
148
|
+
routes: readonly RouteLoadSubject[],
|
|
149
|
+
options: RouteCallOptions,
|
|
150
|
+
at: {
|
|
151
|
+
readonly view: (index: number) => SeedGraph;
|
|
152
|
+
readonly tenant: (index: number) => string;
|
|
153
|
+
readonly room: ExerciseRoom;
|
|
154
|
+
},
|
|
155
|
+
): Promise<readonly RouteLoadRecord[]> {
|
|
156
|
+
const records: RouteLoadRecord[] = [];
|
|
157
|
+
for (const [i, route] of routes.entries()) {
|
|
158
|
+
const graph = at.view(i);
|
|
159
|
+
records.push(
|
|
160
|
+
await exerciseRouteLoad(route, options, { graph, tenant: at.tenant(i), room: at.room }),
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
return records;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** The sized-call recipe for a route label, or `undefined` when the label is not a route's. */
|
|
167
|
+
export async function routeSizedCall(
|
|
168
|
+
routes: readonly RouteLoadSubject[],
|
|
169
|
+
options: RouteCallOptions,
|
|
170
|
+
at: { readonly label: string; readonly graph: SeedGraph; readonly tenant: string },
|
|
171
|
+
): Promise<{ readonly actor: Actor | null; readonly input: unknown } | undefined> {
|
|
172
|
+
const route = routes.find((one) => routeLabel(one.path) === at.label);
|
|
173
|
+
if (route === undefined) return undefined;
|
|
174
|
+
const call = await routeCall(route, options, at.graph, at.tenant);
|
|
175
|
+
return 'reason' in call ? undefined : { actor: call.actor, input: call.params };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** The sweeps' key for a record of either kind: a route's label, else the primitive's own. */
|
|
179
|
+
export const sweepLabel =
|
|
180
|
+
(label: (record: ExerciseRecord) => string) =>
|
|
181
|
+
(record: ExerciseRecord | RouteLoadRecord): string =>
|
|
182
|
+
record.kind === 'route' ? routeLabel(record.name) : label(record);
|
|
183
|
+
|
|
184
|
+
/** The routes whose load answered, as the scale sweep calls them. */
|
|
185
|
+
export const reachedRouteSubjects = (
|
|
186
|
+
routes: readonly RouteLoadSubject[],
|
|
187
|
+
records: readonly RouteLoadRecord[],
|
|
188
|
+
): readonly ScaleSubject[] =>
|
|
189
|
+
routes
|
|
190
|
+
.filter((route) => records.some((r) => r.name === route.path && r.outcome === 'reached'))
|
|
191
|
+
.map(routeScaleSubject);
|
|
192
|
+
|
|
193
|
+
/** The swept records apart again: the primitives' list stays what the pass always returned. */
|
|
194
|
+
export function splitRouteRecords(records: readonly (ExerciseRecord | RouteLoadRecord)[]): {
|
|
195
|
+
readonly primitives: readonly ExerciseRecord[];
|
|
196
|
+
readonly routes: readonly RouteLoadRecord[];
|
|
197
|
+
} {
|
|
198
|
+
const primitives: ExerciseRecord[] = [];
|
|
199
|
+
const routes: RouteLoadRecord[] = [];
|
|
200
|
+
for (const record of records) {
|
|
201
|
+
if (record.kind === 'route') routes.push(record);
|
|
202
|
+
else primitives.push(record);
|
|
203
|
+
}
|
|
204
|
+
return { primitives, routes };
|
|
205
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// The route `load`s an exercise pass drives: every `app/` and `site/` file route that declares one,
|
|
2
|
+
// read off `@ultimat3/render`'s route table — the one list `x routes` and the manifest print. Who
|
|
3
|
+
// loads it (the route's permission, else a signed-in actor) and with which params (a seeded row's
|
|
4
|
+
// id, else the route's own `prerender()` sample) are decided here; the call is the runtime's own.
|
|
5
|
+
|
|
6
|
+
import type { Actor } from '@ultimat3/core';
|
|
7
|
+
import { renderThrowable } from '@ultimat3/core';
|
|
8
|
+
import { rolesGranting } from '@ultimat3/policy';
|
|
9
|
+
import type { RoleGrants } from './exercise-actor';
|
|
10
|
+
import { exerciseActorId } from './exercise-actor';
|
|
11
|
+
import { seededIds } from './exercise-input';
|
|
12
|
+
import type { SeedGraph } from './seed-graph-plan';
|
|
13
|
+
import type { SeedEntity } from './seed-graph-shape';
|
|
14
|
+
|
|
15
|
+
export type RouteParamsValue = Readonly<Record<string, string>>;
|
|
16
|
+
|
|
17
|
+
/** One route as the pass drives it: what `load` is called with, by whom, and the call. */
|
|
18
|
+
export interface RouteLoadSubject {
|
|
19
|
+
/** The URL pattern, `/posts/:id` — the record's name. */
|
|
20
|
+
readonly path: string;
|
|
21
|
+
/** The route file, relative to the app: what a finding points at. */
|
|
22
|
+
readonly file: string;
|
|
23
|
+
/** The pattern's params, in order. */
|
|
24
|
+
readonly params: readonly string[];
|
|
25
|
+
/** The route's `policy.permission`, when it declares one. */
|
|
26
|
+
readonly permission?: string;
|
|
27
|
+
/** `routeDataFor(config, ctx)`: the runtime's one way to resolve a page's data. */
|
|
28
|
+
load(ctx: { readonly params: RouteParamsValue; readonly url: string }): Promise<unknown>;
|
|
29
|
+
/** The route's `prerender()`, when it declares one: a sample of params it knows exist. */
|
|
30
|
+
samples?(): Promise<readonly unknown[]>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Each file route with a `load`, in the table's order. Loaded on demand: the barrel stays lean. */
|
|
34
|
+
export async function routeLoadSubjects(): Promise<readonly RouteLoadSubject[]> {
|
|
35
|
+
const { routeDataFor, routeEntries } = await import('@ultimat3/render');
|
|
36
|
+
return routeEntries()
|
|
37
|
+
.filter((entry) => entry.config.load !== undefined)
|
|
38
|
+
.map((entry): RouteLoadSubject => {
|
|
39
|
+
const { prerender, policy } = entry.config;
|
|
40
|
+
return {
|
|
41
|
+
path: entry.path,
|
|
42
|
+
file: entry.file,
|
|
43
|
+
params: entry.pattern.keys,
|
|
44
|
+
...(policy === undefined ? {} : { permission: policy.permission }),
|
|
45
|
+
load: (ctx) => routeDataFor(entry.config, ctx),
|
|
46
|
+
...(prerender === undefined ? {} : { samples: async () => prerender() }),
|
|
47
|
+
};
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export type RouteActorChoice =
|
|
52
|
+
| { readonly kind: 'actor'; readonly actor: Actor | null }
|
|
53
|
+
| { readonly kind: 'refused'; readonly reason: string };
|
|
54
|
+
|
|
55
|
+
const holds = (actor: Actor, permission: string): boolean =>
|
|
56
|
+
(actor.permissions ?? []).includes(permission) ||
|
|
57
|
+
rolesGranting(permission).some((role) => (actor.roles ?? []).includes(role));
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* The route's guard is a permission, never a policy: the first role holding it. With none, a
|
|
61
|
+
* signed-in actor before the anonymous one — a page that branches on the viewer reads more rows.
|
|
62
|
+
*/
|
|
63
|
+
export function chooseRouteActor(
|
|
64
|
+
permission: string | undefined,
|
|
65
|
+
grants: RoleGrants,
|
|
66
|
+
tenant: string,
|
|
67
|
+
): RouteActorChoice {
|
|
68
|
+
const candidates = grants(tenant);
|
|
69
|
+
const signedIn = candidates.filter((c) => c.actor !== null);
|
|
70
|
+
const pick =
|
|
71
|
+
permission === undefined
|
|
72
|
+
? (signedIn[0] ?? candidates[0])
|
|
73
|
+
: signedIn.find((c) => c.actor !== null && holds(c.actor, permission));
|
|
74
|
+
if (pick === undefined) {
|
|
75
|
+
return {
|
|
76
|
+
kind: 'refused',
|
|
77
|
+
reason: `none of ${candidates.map((c) => c.name).join(', ') || 'the role grants'} holds ${permission ?? 'a role'}`,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
const { actor, name } = pick;
|
|
81
|
+
return {
|
|
82
|
+
kind: 'actor',
|
|
83
|
+
actor: actor === null ? null : Object.freeze({ ...actor, id: exerciseActorId(name, tenant) }),
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** A `prerender()` item as params: a bare string fills the one param, an entry carries its own. */
|
|
88
|
+
const sampleParams = (item: unknown, keys: readonly string[]): RouteParamsValue | undefined => {
|
|
89
|
+
if (typeof item === 'string')
|
|
90
|
+
return keys.length === 1 ? { [keys[0] as string]: item } : undefined;
|
|
91
|
+
if (typeof item !== 'object' || item === null) return undefined;
|
|
92
|
+
const nested = (item as { readonly params?: unknown }).params;
|
|
93
|
+
const record = (typeof nested === 'object' && nested !== null ? nested : item) as Record<
|
|
94
|
+
string,
|
|
95
|
+
unknown
|
|
96
|
+
>;
|
|
97
|
+
const out: Record<string, string> = {};
|
|
98
|
+
for (const key of keys) {
|
|
99
|
+
// Own keys only: a param named `constructor` must never read the prototype's.
|
|
100
|
+
const value = Object.hasOwn(record, key) ? record[key] : undefined;
|
|
101
|
+
if (typeof value !== 'string') return undefined;
|
|
102
|
+
out[key] = value;
|
|
103
|
+
}
|
|
104
|
+
return out;
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
export type RouteParamsChoice =
|
|
108
|
+
| { readonly kind: 'params'; readonly params: RouteParamsValue }
|
|
109
|
+
| { readonly kind: 'none'; readonly reason: string };
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Each param bound to a seeded row's id the tenant sees (`:id` on `/posts/:id` is a `posts` key,
|
|
113
|
+
* by the rule an input's `id` is bound by), else the route's first `prerender()` item.
|
|
114
|
+
*/
|
|
115
|
+
export async function routeParams(
|
|
116
|
+
route: RouteLoadSubject,
|
|
117
|
+
graph: SeedGraph,
|
|
118
|
+
entities: readonly SeedEntity[],
|
|
119
|
+
scope: { readonly tenant: string; readonly actorId?: string | undefined },
|
|
120
|
+
): Promise<RouteParamsChoice> {
|
|
121
|
+
if (route.params.length === 0) return { kind: 'params', params: {} };
|
|
122
|
+
const lookup = seededIds(graph, entities, { ...scope, subject: route.path });
|
|
123
|
+
const bound: Record<string, string> = {};
|
|
124
|
+
for (const key of route.params) {
|
|
125
|
+
const hit = lookup(key);
|
|
126
|
+
if (hit === undefined || typeof hit.value !== 'string') break;
|
|
127
|
+
bound[key] = hit.value;
|
|
128
|
+
}
|
|
129
|
+
if (Object.keys(bound).length === route.params.length) return { kind: 'params', params: bound };
|
|
130
|
+
const unbound = route.params.map((key) => `:${key}`).join(', ');
|
|
131
|
+
if (route.samples === undefined) {
|
|
132
|
+
return {
|
|
133
|
+
kind: 'none',
|
|
134
|
+
reason: `${unbound} names no seeded entity's key and the route declares no prerender() sample`,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
let items: readonly unknown[];
|
|
138
|
+
try {
|
|
139
|
+
items = await route.samples();
|
|
140
|
+
} catch (error) {
|
|
141
|
+
return { kind: 'none', reason: `its prerender() threw: ${renderThrowable(error)}` };
|
|
142
|
+
}
|
|
143
|
+
const sample = items.map((item) => sampleParams(item, route.params)).find(Boolean);
|
|
144
|
+
return sample === undefined
|
|
145
|
+
? { kind: 'none', reason: `${unbound} is not filled by any item its prerender() answered` }
|
|
146
|
+
: { kind: 'params', params: sample };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** This machine: the origin a load is told, as a served request's `href` is absolute. */
|
|
150
|
+
const EXERCISE_ORIGIN = 'http://localhost';
|
|
151
|
+
|
|
152
|
+
/** The URL the load is told — absolute, as the runtime's `at.href` is: the pattern, params in. */
|
|
153
|
+
export const routeUrl = (path: string, params: RouteParamsValue): string =>
|
|
154
|
+
EXERCISE_ORIGIN +
|
|
155
|
+
path.replace(/[:*]([A-Za-z0-9_]+)/g, (whole, key: string) => {
|
|
156
|
+
const value = Object.hasOwn(params, key) ? params[key] : undefined;
|
|
157
|
+
if (value === undefined) return whole;
|
|
158
|
+
// A catch-all keeps its slashes: `/docs/*path` with `a/b` is `/docs/a/b`.
|
|
159
|
+
return whole.startsWith('*')
|
|
160
|
+
? value.split('/').map(encodeURIComponent).join('/')
|
|
161
|
+
: encodeURIComponent(value);
|
|
162
|
+
});
|