@ultimat3/testing 30.7.0 → 30.9.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.
@@ -4,12 +4,29 @@
4
4
  // computed from the pass's own state, by one mechanism and no per-primitive case.
5
5
 
6
6
  import type { Actor } from '@ultimat3/core';
7
- import { bindDrawn } from '@ultimat3/core';
7
+ import {
8
+ bindDrawn,
9
+ isUltimateError,
10
+ renderExerciseKey,
11
+ renderFixShellArg,
12
+ renderThrowable,
13
+ } from '@ultimat3/core';
8
14
  import type { ExerciseOverride } from './define-exercise';
9
15
  import { withExerciseRequest } from './exercise-request';
16
+ import { testJobs } from './fixture-jobs';
17
+
18
+ /**
19
+ * `onCallQueue`: the caller has installed the queue the call it feeds runs on (the control's), and
20
+ * the input binds on it — so a job it enqueues is there when the call looks it up by id. Without
21
+ * it the input gets a queue of its own for its duration: no call shares one with it (the tenant
22
+ * proof's B legs and the scale sweep each open theirs after the bind).
23
+ */
24
+ export interface BindAt {
25
+ readonly onCallQueue?: boolean;
26
+ }
10
27
 
11
28
  /** `(drawn, actor) => input`, or `undefined` when the override binds nothing. */
12
- export type OverrideInput = (drawn: unknown, actor: Actor | null) => Promise<unknown>;
29
+ export type OverrideInput = (drawn: unknown, actor: Actor | null, at?: BindAt) => Promise<unknown>;
13
30
 
14
31
  export function overrideInput(
15
32
  name: string,
@@ -18,13 +35,38 @@ export function overrideInput(
18
35
  // Any entry but `off` may bind: `{ input }` alone keeps the pass's own actor and still binds.
19
36
  const bind = bindDrawn(override === undefined || 'off' in override ? undefined : override.input);
20
37
  if (bind === undefined) return undefined;
21
- const declared = override === undefined || 'off' in override ? undefined : override.actor;
22
- return async (drawn, actor) =>
23
- rehomed(
24
- await withExerciseRequest(name, actor, async () => bind(drawn)),
25
- declared?.orgId,
26
- actor?.orgId,
27
- );
38
+ const entry = override === undefined || 'off' in override ? undefined : override;
39
+ const declared = entry?.actor;
40
+ // The entry's own request: the binder sees the cookies and headers the call itself will.
41
+ return async (drawn, actor, at) => {
42
+ const run = async () =>
43
+ rehomed(
44
+ await withExerciseRequest(name, actor, async () => bind(drawn), entry?.request),
45
+ declared?.orgId,
46
+ actor?.orgId,
47
+ );
48
+ if (at?.onCallQueue === true) return run();
49
+ // No call's queue to share: one of its own, so app code that enqueues has a driver.
50
+ await using _jobs = await testJobs();
51
+ // Awaited HERE: a bare `return run()` leaves the block, and disposes the queue, mid-bind.
52
+ return await run();
53
+ };
54
+ }
55
+
56
+ /**
57
+ * What an entry's input that THREW makes of its primitive's record: unreached, under the throw's
58
+ * own code (an uncoded one is `X_EXERCISE_INPUT_THREW`), and a fix naming the entry. Never a
59
+ * defect: the throw is the app's exercise.ts, and blaming the handler sends the author elsewhere.
60
+ * `key` is the entry's key as it would be written — kind-qualified when a name is shared.
61
+ */
62
+ export function inputThrew(name: string, key: string, error: unknown) {
63
+ const coded = isUltimateError(error);
64
+ return {
65
+ outcome: 'unreached' as const,
66
+ code: coded ? error.code : 'X_EXERCISE_INPUT_THREW',
67
+ reason: `its exercise.ts input threw before the call: ${coded ? error.cause : renderThrowable(error)}`,
68
+ fix: `x exercise ${renderFixShellArg(name, '<name>')} --json # after defineExercise({ ${renderExerciseKey(key)}: { input } }) in apps/web/exercise.ts returns a value (it runs as the seated actor, inside the call's request), or { off: '<why>' }`,
69
+ };
28
70
  }
29
71
 
30
72
  /**
@@ -52,6 +52,11 @@ export interface TenantFinding {
52
52
  /** WRITE_CROSSED: the table and the primary key of A's changed row */
53
53
  readonly table?: string;
54
54
  readonly id?: string;
55
+ /**
56
+ * LEAK from a `tenant: 'none'` job handed nothing of A's: a read across every org that opened no
57
+ * `crossTenant()` scope — its fix is that scope, never a repository scoped to an actor it lacks.
58
+ */
59
+ readonly sweep?: true;
55
60
  }
56
61
 
57
62
  /** The tenant proof's verdict on one primitive: B attacked A's rows twice, around A's own call. */
@@ -1,38 +1,21 @@
1
1
  // The context an action or a query runs in during the exercise pass: an HTTP request's, built the
2
2
  // way the pipeline builds one, because `surface: 'http'` is the call the pass makes. A bare `Ctx`
3
3
  // has no inbound headers, so a session action's `useRequestContext()` answered X_NO_REQUEST, a 500.
4
+ // The build is `@ultimat3/http`'s `withRequestAs`, the one the contract step makes too.
4
5
 
5
6
  import type { Actor } from '@ultimat3/core';
6
- import { anonymousActor, runWithContext, useContext, withChildContext } from '@ultimat3/core';
7
-
8
- /** Where the pass's requests say they came from: no host the app serves, and never sent. */
9
- const EXERCISE_ORIGIN = 'https://exercise.test';
7
+ import type { ExerciseRequestOption } from '@ultimat3/http';
10
8
 
11
9
  /**
12
- * `fn` inside a fresh request as `actor`: no cookie, no header, a POST to the primitive's own name,
13
- * nothing spending a rate bucket. The actor is ON the request, so the caller passes `invoke` no
14
- * `actor` — its impersonation path rebuilds a plain child context and drops the request's fields.
15
- * The child is derived first for the services an actor binds, then the request's fields go over
16
- * it, as `withAnonymousRequest` (`@ultimat3/http`) does.
10
+ * `fn` inside a fresh request as `actor`, carrying the entry's `request` (none: no cookie, no
11
+ * header). `@ultimat3/http` is loaded on the call, so the barrel stays off it.
17
12
  */
18
13
  export async function withExerciseRequest<T>(
19
14
  name: string,
20
15
  actor: Actor | null,
21
16
  fn: () => Promise<T>,
17
+ request?: ExerciseRequestOption,
22
18
  ): Promise<T> {
23
- const http = await import('@ultimat3/http');
24
- const request = http.requestContext({
25
- url: new URL(`/${encodeURIComponent(name)}`, EXERCISE_ORIGIN),
26
- method: 'POST',
27
- role: 'web',
28
- config: http.defineHttpConfig({ rateLimit: { scope: 'process' } }),
29
- requestHeaders: new Headers(),
30
- });
31
- return runWithContext(http.asCtx(request), () =>
32
- withChildContext({ actor: actor ?? anonymousActor() }, () => {
33
- const child = useContext();
34
- const scope = { ...child, ...request, actor: child.actor };
35
- return runWithContext(http.asCtx(scope), fn);
36
- }),
37
- );
19
+ const { withRequestAs } = await import('@ultimat3/http');
20
+ return withRequestAs(name, actor, request, fn);
38
21
  }
@@ -1,6 +1,7 @@
1
1
  // `defineExercise(…, { setup })`, run: the app's hook inside the pass's sealed room, before the
2
2
  // first row is seeded, disposed before the room restores the network. What it installs — a
3
3
  // `mockFetch` route, a `cassette()` — answers a vendor call; `allowHost` would send one for real.
4
+ // Several hooks (one per feature group) run in order and are undone in reverse.
4
5
 
5
6
  import { renderCauseValue, UltimateError } from '@ultimat3/core';
6
7
  import type { ExerciseRoom } from './exercise-report';
@@ -35,30 +36,46 @@ async function release(handle: unknown): Promise<void> {
35
36
  }
36
37
 
37
38
  /**
38
- * `room` with `setup` run inside it. Its dispose releases what setup returned FIRST — a cassette's
39
- * own check reads the routes the pass used — then the room. A setup that throws, or lets a host
40
- * through, disposes both before the pass refuses.
39
+ * Every handle released, last first, and then the room — each whatever the one before it threw;
40
+ * the first throw is what the caller sees, once nothing is left installed.
41
+ */
42
+ async function releaseAll(handles: readonly unknown[], room: ExerciseRoom): Promise<void> {
43
+ let failed = false;
44
+ let first: unknown;
45
+ for (const handle of [...handles].reverse()) {
46
+ try {
47
+ await release(handle);
48
+ } catch (error) {
49
+ if (!failed) first = error;
50
+ failed = true;
51
+ }
52
+ }
53
+ await room[Symbol.asyncDispose]();
54
+ if (failed) throw first;
55
+ }
56
+
57
+ /**
58
+ * `room` with each setup run inside it, in order. Its dispose releases what they returned FIRST,
59
+ * in reverse — a cassette's own check reads the routes the pass used — then the room. A setup that
60
+ * throws disposes those that already ran and the room; one that lets a host through, all of them.
41
61
  */
42
62
  export async function withExerciseSetup(
43
63
  room: ExerciseRoom,
44
- setup: ExerciseSetup | undefined,
64
+ setup: ExerciseSetup | readonly ExerciseSetup[] | undefined,
45
65
  ): Promise<ExerciseRoom> {
46
- if (setup === undefined) return room;
66
+ const setups = setup === undefined ? [] : typeof setup === 'function' ? [setup] : setup;
67
+ if (setups.length === 0) return room;
47
68
  const before = new Set(captureNetwork().allowed);
48
- let handle: unknown;
49
- try {
50
- handle = await setup();
51
- } catch (error) {
52
- await room[Symbol.asyncDispose]();
53
- throw error;
54
- }
55
- const dispose = async (): Promise<void> => {
69
+ const handles: unknown[] = [];
70
+ for (const one of setups) {
56
71
  try {
57
- await release(handle);
58
- } finally {
59
- await room[Symbol.asyncDispose]();
72
+ handles.push(await one());
73
+ } catch (error) {
74
+ await releaseAll(handles, room);
75
+ throw error;
60
76
  }
61
- };
77
+ }
78
+ const dispose = (): Promise<void> => releaseAll(handles, room);
62
79
  const opened = captureNetwork().allowed.filter((host) => !before.has(host));
63
80
  if (opened.length > 0) {
64
81
  await dispose();
@@ -5,6 +5,7 @@
5
5
 
6
6
  import type { Actor } from '@ultimat3/core';
7
7
  import { renderCauseValue, renderFixShellArg, UltimateError } from '@ultimat3/core';
8
+ import type { ExerciseRequestOption } from '@ultimat3/http';
8
9
  import type { AnyJobHandle, JobExecution } from '@ultimat3/jobs';
9
10
  import { registeredJobs } from '@ultimat3/jobs';
10
11
  import type { Policy } from '@ultimat3/policy';
@@ -97,7 +98,15 @@ const jobSubject = (handle: AnyJobHandle): Subject => ({
97
98
  },
98
99
  });
99
100
 
100
- export async function subjectsOf(): Promise<readonly Subject[]> {
101
+ /** The `request` an action's or a query's entry declares, by kind: a job's call has none. */
102
+ export type RequestOf = (
103
+ kind: 'action' | 'query',
104
+ name: string,
105
+ ) => ExerciseRequestOption | undefined;
106
+
107
+ export async function subjectsOf(
108
+ requestOf: RequestOf = () => undefined,
109
+ ): Promise<readonly Subject[]> {
101
110
  // On demand, as every fixture here loads them: the barrel stays off `action` and `query`.
102
111
  const { invoke, listActions } = await import('@ultimat3/action');
103
112
  const { listQueries, runQuery } = await import('@ultimat3/query');
@@ -110,8 +119,11 @@ export async function subjectsOf(): Promise<readonly Subject[]> {
110
119
  policy: target.policy,
111
120
  permissions: target.describe().permissions,
112
121
  call: async (input, actor) => ({
113
- output: await withExerciseRequest(target.name, actor, () =>
114
- invoke(target, input, { surface: 'http' }),
122
+ output: await withExerciseRequest(
123
+ target.name,
124
+ actor,
125
+ () => invoke(target, input, { surface: 'http' }),
126
+ requestOf('action', target.name),
115
127
  ),
116
128
  }),
117
129
  }),
@@ -124,8 +136,11 @@ export async function subjectsOf(): Promise<readonly Subject[]> {
124
136
  policy: target.policy,
125
137
  permissions: target.describe().permissions,
126
138
  call: async (input, actor) => ({
127
- output: await withExerciseRequest(target.name, actor, () =>
128
- runQuery(target, input, { surface: 'http' }),
139
+ output: await withExerciseRequest(
140
+ target.name,
141
+ actor,
142
+ () => runQuery(target, input, { surface: 'http' }),
143
+ requestOf('query', target.name),
129
144
  ),
130
145
  }),
131
146
  }),
@@ -5,6 +5,7 @@
5
5
 
6
6
  import type { Actor } from '@ultimat3/core';
7
7
  import type { ExerciseOverrides } from './define-exercise';
8
+ import { overrideFor } from './define-exercise';
8
9
  import type { ActorRows, RoleGrants } from './exercise-actor';
9
10
  import { asSeededRow, chooseActor } from './exercise-actor';
10
11
  import type { Sampler } from './exercise-input';
@@ -44,7 +45,7 @@ export const seated = (actor: Actor | null, tenant: string, rows: ActorRows | un
44
45
  rows === undefined ? actor : asSeededRow(actor, tenant, rows);
45
46
 
46
47
  /** A primitive as a sized call needs it: its schema, its policy, and a job's seat. */
47
- type Callable = Pick<Subject, 'name' | 'input' | 'policy' | 'permissions' | 'seat'>;
48
+ type Callable = Pick<Subject, 'kind' | 'name' | 'input' | 'policy' | 'permissions' | 'seat'>;
48
49
 
49
50
  /** One call of `subject` in `tenant` of a sized graph: the control's actor and first input. */
50
51
  export async function sizedCall(
@@ -54,7 +55,7 @@ export async function sizedCall(
54
55
  at: { readonly graph: SeedGraph; readonly tenant: string; readonly self: boolean },
55
56
  ): Promise<{ readonly actor: Actor | null; readonly input: unknown } | undefined> {
56
57
  const { graph, tenant, self } = at;
57
- const override = options.overrides?.entries.get(subject.name);
58
+ const override = overrideFor(options.overrides, subject.kind, subject.name);
58
59
  const chosen = chooseActor(subject.policy, subject.permissions, options.roles, tenant, override);
59
60
  if (chosen.kind === 'refused') return undefined;
60
61
  const rows = actorRowsOf(options, graph);
@@ -68,7 +69,9 @@ export async function sizedCall(
68
69
  const lookup = seededIds(graph, options.entities, { ...scope, self });
69
70
  const drawn = bindIds(drawInput(sampler, subject.input, 0, 0), lookup);
70
71
  const bindInput = overrideInput(subject.name, override);
71
- const given = bindInput === undefined ? drawn : await bindInput(drawn, actor);
72
+ // On the sized call's own queue, installed by the sweep before this setup (`scale-sweep-run.ts`).
73
+ const given =
74
+ bindInput === undefined ? drawn : await bindInput(drawn, actor, { onCallQueue: true });
72
75
  return { actor, input: seatIn(subject, given, tenant) };
73
76
  }
74
77
 
@@ -93,10 +96,12 @@ const timed = (subject: ScaleSubject, spent: Map<string, number>): ScaleSubject
93
96
 
94
97
  /**
95
98
  * The scale sweep inside the room, the room closed, then the plan sweep — on the installed client
96
- * only: with none, the pass ran on a driver that sends no SQL and there is no plan to read.
99
+ * only: with none, the pass ran on a driver that sends no SQL and there is no plan to read. Each
100
+ * proof is found under `label(record)`, the name its primitive ran under in the room.
97
101
  */
98
102
  export async function attachSweeps(
99
103
  records: readonly ExerciseRecord[],
104
+ label: (record: ExerciseRecord) => string,
100
105
  options: ScaleSweepOptions,
101
106
  ): Promise<Swept> {
102
107
  const spent = new Map<string, number>();
@@ -120,9 +125,9 @@ export async function attachSweeps(
120
125
  plans: Math.round(performance.now() - plansStarted),
121
126
  };
122
127
  const swept = records.map((record) => {
123
- const proof = plans.get(record.name);
124
- const sized = scale.get(record.name);
125
- const scaleMs = spent.get(record.name);
128
+ const proof = plans.get(label(record));
129
+ const sized = scale.get(label(record));
130
+ const scaleMs = spent.get(label(record));
126
131
  const proofMs = {
127
132
  ...record.proofMs,
128
133
  ...(scaleMs === undefined ? {} : { scale: Math.round(scaleMs) }),