@ultimat3/testing 31.48.0 → 31.50.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.
@@ -3,7 +3,7 @@
3
3
  // check-and-add, and a store that reads then writes admits past the limit under parallel calls.
4
4
 
5
5
  import { expect, test } from 'bun:test';
6
- import type { MeterKey, MeterStore } from '@ultimat3/action/adapter';
6
+ import type { MeterDrawResult, MeterKey, MeterStore } from '@ultimat3/action/adapter';
7
7
  import type { SharedExamples } from './shared-examples';
8
8
  import { sharedExamples } from './shared-examples';
9
9
 
@@ -34,6 +34,30 @@ const drawOf =
34
34
  (limit: number, periodStartMs = START, over: Partial<MeterKey> = {}) =>
35
35
  store.draw({ ...key, ...over, periodStartMs, limit });
36
36
 
37
+ /** A draw of `amount` under `drawKey` — `drawMeter`'s shape at the port. */
38
+ const keyedOf =
39
+ (store: MeterStore, key: MeterKey) =>
40
+ (limit: number, amount: number, drawKey: string, periodStartMs = START) =>
41
+ store.draw({ ...key, periodStartMs, limit, amount, drawKey });
42
+
43
+ /**
44
+ * A draw's answer, judged on what the port requires: `replayed` must be `true` on a replay, and on
45
+ * anything else may be `false` or absent; `periodStartMs` is checked by the check that names it,
46
+ * where it differs from the request's and is therefore required.
47
+ */
48
+ function expectDraw(
49
+ result: MeterDrawResult,
50
+ expected: { allowed: boolean; used: number; warned: boolean; replayed?: true },
51
+ ): void {
52
+ expect({ allowed: result.allowed, used: result.used, warned: result.warned }).toEqual({
53
+ allowed: expected.allowed,
54
+ used: expected.used,
55
+ warned: expected.warned,
56
+ });
57
+ if (expected.replayed === true) expect(result.replayed).toBe(true);
58
+ else expect(result.replayed === undefined || result.replayed === false).toBe(true);
59
+ }
60
+
37
61
  export const METER_STORE_CHECKS: readonly MeterStoreCheck[] = [
38
62
  {
39
63
  name: 'declares its scope',
@@ -79,7 +103,7 @@ export const METER_STORE_CHECKS: readonly MeterStoreCheck[] = [
79
103
  expect((await draw(2, START + DAY)).allowed).toBe(false);
80
104
  // A replica a period behind cannot reset today's count by drawing against yesterday.
81
105
  expect((await draw(2, START)).allowed).toBe(false);
82
- expect(await draw(2, START + 2 * DAY)).toEqual({ allowed: true, used: 1, warned: false });
106
+ expectDraw(await draw(2, START + 2 * DAY), { allowed: true, used: 1, warned: false });
83
107
  },
84
108
  },
85
109
  {
@@ -88,7 +112,7 @@ export const METER_STORE_CHECKS: readonly MeterStoreCheck[] = [
88
112
  const draw = drawOf(store, keyOf());
89
113
  await draw(1);
90
114
  expect((await draw(1)).allowed).toBe(false);
91
- expect(await draw(5)).toEqual({ allowed: true, used: 2, warned: false });
115
+ expectDraw(await draw(5), { allowed: true, used: 2, warned: false });
92
116
  },
93
117
  },
94
118
  {
@@ -103,6 +127,142 @@ export const METER_STORE_CHECKS: readonly MeterStoreCheck[] = [
103
127
  expect((await draw(1)).allowed).toBe(false);
104
128
  },
105
129
  },
130
+ {
131
+ name: 'an amount counts whole, and one that would pass the limit counts nothing',
132
+ async run(store) {
133
+ const key = keyOf();
134
+ const draw = (limit: number, amount: number) =>
135
+ store.draw({ ...key, periodStartMs: START, limit, amount });
136
+ expectDraw(await draw(10, 7), { allowed: true, used: 7, warned: false });
137
+ expectDraw(await draw(10, 4), { allowed: false, used: 7, warned: false });
138
+ expectDraw(await draw(10, 3), { allowed: true, used: 10, warned: false });
139
+ expect((await draw(10, 1)).allowed).toBe(false);
140
+ },
141
+ },
142
+ {
143
+ name: `${RACERS} parallel draws under one key add it once`,
144
+ async run(store) {
145
+ const keyed = keyedOf(store, keyOf());
146
+ const results = await Promise.all(Array.from({ length: RACERS }, () => keyed(100, 3, 'k1')));
147
+ expect(results.every((result) => result.allowed)).toBe(true);
148
+ expect(results.filter((result) => result.replayed !== true)).toHaveLength(1);
149
+ expectDraw(await keyed(100, 3, 'k2'), { allowed: true, used: 6, warned: false });
150
+ expectDraw(await keyed(100, 3, 'k1'), {
151
+ allowed: true,
152
+ used: 6,
153
+ warned: false,
154
+ replayed: true,
155
+ });
156
+ },
157
+ },
158
+ {
159
+ name: 'a refused keyed draw leaves its key unspent, and a replay answers a spent allowance',
160
+ async run(store) {
161
+ const keyed = keyedOf(store, keyOf());
162
+ expect((await keyed(5, 5, 'k1')).allowed).toBe(true);
163
+ expectDraw(await keyed(5, 1, 'k2'), { allowed: false, used: 5, warned: false });
164
+ expectDraw(await keyed(5, 5, 'k1'), {
165
+ allowed: true,
166
+ used: 5,
167
+ warned: false,
168
+ replayed: true,
169
+ });
170
+ expectDraw(await keyed(6, 1, 'k2'), { allowed: true, used: 6, warned: false });
171
+ },
172
+ },
173
+ {
174
+ name: 'a key is remembered into the next period and forgotten in the one after',
175
+ async run(store) {
176
+ const keyed = keyedOf(store, keyOf());
177
+ await keyed(10, 4, 'k1');
178
+ expectDraw(await keyed(10, 4, 'k1', START + DAY), {
179
+ allowed: true,
180
+ used: 0,
181
+ warned: false,
182
+ replayed: true,
183
+ });
184
+ expectDraw(await keyed(10, 2, 'k2', START + DAY), {
185
+ allowed: true,
186
+ used: 2,
187
+ warned: false,
188
+ });
189
+ expectDraw(await keyed(10, 4, 'k1', START + 2 * DAY), {
190
+ allowed: true,
191
+ used: 4,
192
+ warned: false,
193
+ });
194
+ },
195
+ },
196
+ {
197
+ name: 'declares that it counts amounts and remembers draw keys',
198
+ async run(store) {
199
+ expect(store.keyedDraws).toBe(true);
200
+ },
201
+ },
202
+ {
203
+ name: 'a lagging keyed draw counts in the open period, and its key lasts as long as that period',
204
+ async run(store) {
205
+ const key = keyOf();
206
+ const keyed = keyedOf(store, key);
207
+ await drawOf(store, key)(100, START + DAY);
208
+ const late = await keyed(100, 3, 'late', START);
209
+ expectDraw(late, { allowed: true, used: 4, warned: false });
210
+ // Required here, where it differs from the request's: absent, `drawMeter` would answer day
211
+ // one's reset for a charge made on day two.
212
+ expect(late.periodStartMs).toBe(START + DAY);
213
+ // Charged on day two, so day three still remembers it: a retry adds nothing.
214
+ expectDraw(await keyed(100, 3, 'late', START + 2 * DAY), {
215
+ allowed: true,
216
+ used: 0,
217
+ warned: false,
218
+ replayed: true,
219
+ });
220
+ },
221
+ },
222
+ {
223
+ name: "a lagging retry of a key the counter's own period has forgotten is counted again",
224
+ async run(store) {
225
+ const key = keyOf();
226
+ const keyed = keyedOf(store, key);
227
+ await keyed(100, 3, 'k', START);
228
+ await drawOf(store, key)(100, START + 2 * DAY);
229
+ // The counter is on day three, which remembers day two's keys and no older ones — the refusal
230
+ // too: judged by the request's day two, it would find day one's key and replay it.
231
+ expectDraw(await keyed(3, 3, 'k', START + DAY), { allowed: false, used: 1, warned: false });
232
+ expectDraw(await keyed(100, 3, 'k', START + DAY), { allowed: true, used: 4, warned: false });
233
+ },
234
+ },
235
+ {
236
+ name: 'a refused draw of a later period forgets no key the open period still remembers',
237
+ async run(store) {
238
+ const key = keyOf();
239
+ const keyed = keyedOf(store, key);
240
+ await keyed(10, 1, 'k', START);
241
+ await drawOf(store, key)(10, START + DAY);
242
+ expect((await keyed(10, 11, 'too-big', START + 2 * DAY)).allowed).toBe(false);
243
+ expectDraw(await keyed(10, 1, 'k', START + DAY), {
244
+ allowed: true,
245
+ used: 1,
246
+ warned: false,
247
+ replayed: true,
248
+ });
249
+ },
250
+ },
251
+ {
252
+ name: 'a refused first draw leaves no counter a lagging draw could spend',
253
+ async run(store) {
254
+ const key = keyOf();
255
+ const keyed = keyedOf(store, key);
256
+ expect((await keyed(10, 11, 'too-big', START + DAY)).allowed).toBe(false);
257
+ expectDraw(await keyed(10, 10, 'k', START), { allowed: true, used: 10, warned: false });
258
+ // Day two never admitted a draw, so its allowance is whole.
259
+ expectDraw(await drawOf(store, key)(10, START + DAY), {
260
+ allowed: true,
261
+ used: 1,
262
+ warned: false,
263
+ });
264
+ },
265
+ },
106
266
  {
107
267
  name: "a period's warning has one claimant, is released for a retry, and resets with the period",
108
268
  async run(store) {
@@ -1,7 +1,7 @@
1
1
  // What every test starts from, put back by the preload before each one — the per-TEST half of
2
- // isolation, beside `file-boundary.ts`'s per-file half: the jobs event bus, which STORES what it is
3
- // handed (an answer one test published resumed the next test's waiting run), and the installed
4
- // rate-limit store, read per request (a bucket one test drained was the next test's 429).
2
+ // isolation, beside `file-boundary.ts`'s per-file half: the jobs event bus (it STORES what it is
3
+ // handed), the installed rate-limit store (a drained bucket was the next test's 429) and the
4
+ // once-per-operation wire-dates warn (a rerun in one process never saw its warn).
5
5
 
6
6
  import { beforeEach } from 'bun:test';
7
7
  import type { clearDefaultRateLimitBuckets } from '@ultimat3/http/adapter';
@@ -42,9 +42,9 @@ function resolvedFrom(pkg: string): string | null {
42
42
  const paths = new Map<string, string | null>();
43
43
 
44
44
  /**
45
- * Before each test: a fresh DEFAULT event bus and the DEFAULT rate-limit buckets emptied — each
46
- * only when its package is loaded. Already evaluated, so each import answers from the registry, the
47
- * same instance. Only the defaults: a bus or store installed for the file (`beforeAll`, a booted
45
+ * Before each test: a fresh DEFAULT event bus, the DEFAULT rate-limit buckets emptied and the
46
+ * wire-dates warn forgotten — each only when its package is loaded. Already evaluated, so each
47
+ * import answers from the registry, the same instance. Only the defaults: a bus or store installed for the file (`beforeAll`, a booted
48
48
  * app's) stays installed, and carries across that file's tests as it would in production.
49
49
  */
50
50
  export async function resetPerTestState(): Promise<void> {
@@ -62,6 +62,13 @@ export async function resetPerTestState(): Promise<void> {
62
62
  };
63
63
  http.clearDefaultRateLimitBuckets();
64
64
  }
65
+ const wireDates = loaded('@ultimat3/http', 'wire-dates-cap.ts');
66
+ if (wireDates !== undefined) {
67
+ // An internal seam, off the package's API on purpose: an app forgets nothing it warned about.
68
+ // Its name is held by `per-test-reset.test.ts`, which reds if this stops resetting the set.
69
+ const http = (await import(wireDates)) as { readonly resetWireDatesCap: () => void };
70
+ http.resetWireDatesCap();
71
+ }
65
72
  }
66
73
 
67
74
  /**
@@ -1,7 +1,7 @@
1
- // From the oracle's red nodes to what an author pastes: the entity, and the `indexes: [{ on }]`
2
- // entry by property. Pure. Also where a red node is argued away by the declaration itself: a
3
- // lookup that pins a unique key reads one row whatever the planner walked to find it, and a whole
4
- // read a keyed join side could probe by a declared index is one the planner declined on cost.
1
+ // From the oracle's red nodes to what an author pastes: the entity and the `indexes: [{ on }]`
2
+ // entry by property. Pure. Also where the declaration argues a red node away: a unique key pinned
3
+ // reads one row, and a keyed join side's probe or a walk a held index serves (keys, then order)
4
+ // is credited as one the planner declined on a small seed's costs.
5
5
 
6
6
  import { trigramDeclaration } from '@ultimat3/entity';
7
7
  import type { PlanVerdict, PlanVerdictCode } from './plan-oracle';
@@ -264,7 +264,15 @@ export function planFindings(
264
264
  const tenant = description.columns.find((c) => c.property === entity.$tenantColumn)?.column;
265
265
  const lead = tenant !== undefined && verdict.equality.includes(tenant) ? [tenant] : [];
266
266
  const columns = [...new Set([...lead, ...verdict.equality, ...order, ...verdict.range])];
267
- if (held(declared, columns)) return [{ ...finding, index: [], unserved: 'declared' }];
267
+ if (held(declared, columns)) {
268
+ // A WALK the held index would serve — its equality columns, then the order — is the planner
269
+ // declining that index on cost. Seq scans are off, so it had it; on a seed of a few rows a
270
+ // partial index (`where revoked_at is null`) costs as little as the keyed one. A schema
271
+ // heuristic, not a promise about production plans: many revoked rows sharing a key and few
272
+ // active ones can keep the walk cheaper at volume. Credited, never re-proven, as `probed` is.
273
+ // A whole-table scan with the index held is still red: something defeats it.
274
+ return walked ? [] : [{ ...finding, index: [], unserved: 'declared' }];
275
+ }
268
276
  return [{ ...finding, index: columns.flatMap((column) => byColumn.get(column) ?? []) }];
269
277
  });
270
278
  }
package/src/plan-sweep.ts CHANGED
@@ -103,7 +103,7 @@ async function explain(
103
103
  }
104
104
 
105
105
  /** One statement's verdicts: its access path planned as is, its limited sort with sorts off. */
106
- async function judge(
106
+ export async function judgeStatement(
107
107
  client: DbClient,
108
108
  statement: string,
109
109
  tables: PlanTableColumns,
@@ -157,7 +157,7 @@ export async function sweepPlans(
157
157
  if (entity === undefined) continue;
158
158
  const declared = entity.$describe().scan;
159
159
  const exemptBy = scan ?? declared;
160
- const planned = exemptBy === undefined ? await judge(client, statement, judged) : {};
160
+ const planned = exemptBy === undefined ? await judgeStatement(client, statement, judged) : {};
161
161
  for (const name of primitives) {
162
162
  const proof = proofOf(name);
163
163
  proof.planned += 1;
package/src/preload.ts CHANGED
@@ -97,7 +97,8 @@ if (Bun.env[ISOLATED_ENV] !== '1') {
97
97
  // clear the loader's handler at the first file's boundary, where the module graph it retains is
98
98
  // released with it. Installed the other way round, the release still fires but the graph the loader
99
99
  // already built is what is held, and every finished file stays resident — measured on Bun 1.4.0,
100
- // 8 files, 1 -> 8 live global objects (this file's own leak fixture).
100
+ // 8 files, 1 -> 8 live global objects (this file's own leak fixture). On Bun 1.4.6+ the call is a
101
+ // no-op: the runtime clears the plugins at the isolation swap itself.
101
102
  releasePluginsAfterIsolatedFile();
102
103
 
103
104
  // Every `.tsx` compiles with the framework's JSX factory from the first file on, in every test
@@ -110,6 +111,12 @@ releasePluginsAfterIsolatedFile();
110
111
  const { installRenderLoader } = await import('@ultimat3/render/server');
111
112
  installRenderLoader();
112
113
 
114
+ // And the app's site asset table, as the boot installs it: a stylesheet calling Sass `asset()` is
115
+ // compiled the moment a test imports its module, and with no table every test importing it died
116
+ // with `X_ASSET_MISSING` on a fresh app. Again per file, so a test's own resolver never outlives it.
117
+ const { installAppAssets } = await import('./app-assets');
118
+ if (installAppAssets()) onFileBoundary(() => installAppAssets());
119
+
113
120
  // Opt-out exists for one case: a test that deliberately exercises a real integration in a job the
114
121
  // team runs on purpose. It is an env var, not an API, so it cannot be set from inside a test file.
115
122
  if (Bun.env['ULTIMATE_TEST_ALLOW_NET'] !== '1') sealNetwork();
@@ -3,16 +3,21 @@
3
3
  // them. No browser, no server, no cast: a test asserts on markup and on visible text.
4
4
 
5
5
  import type { Actor } from '@ultimat3/core';
6
- import { assert, ctxOf, runWithContext } from '@ultimat3/core';
6
+ import { assert, ctxOf, runWithContext, tryUseContext } from '@ultimat3/core';
7
+ import { asCtx, defineHttpConfig, requestContext } from '@ultimat3/http';
8
+ import { splitLocalePrefix } from '@ultimat3/i18n';
7
9
  import type { AssetPath, IslandDirective, RouteConfig, RouteParams } from '@ultimat3/render';
10
+ import { decodeHtmlEntities } from './html-entities';
8
11
 
9
12
  /** What a component rendered. */
10
13
  export interface RenderedView {
11
14
  /** The markup, exactly as the document would carry it. */
12
15
  readonly html: string;
13
16
  /**
14
- * What a reader sees: tags, scripts and styles removed, entities decoded, whitespace collapsed
15
- * to single spaces. Compare it with `t('<key>')` — the markup escapes what the catalog does not.
17
+ * What a reader sees: tags, scripts and styles removed, character references decoded (every
18
+ * numeric one, and the common named ones: `&amp;`, `&lt;`, `&gt;`, `&quot;`, `&apos;`, `&nbsp;`,
19
+ * typographic quotes and dashes, `&hellip;`, `&copy;` …), whitespace collapsed to single spaces.
20
+ * Compare it with `t('<key>')` — the markup escapes what the catalog does not.
16
21
  */
17
22
  readonly text: string;
18
23
  }
@@ -47,7 +52,13 @@ export interface RouteModule<TData> {
47
52
  }
48
53
 
49
54
  export interface RouteRequest {
50
- /** Absolute, as a request's is. Its search string becomes the page's `query`. */
55
+ /**
56
+ * Absolute, as a request's is. Its search string becomes the page's `query`, and a leading
57
+ * routed locale segment (`https://x/es/precios`, `es` among the app's locales) is the locale
58
+ * `load`, `meta` and the page render in, as the router reads it. Unprefixed, and with no
59
+ * `actor`, the render opens no request context: standalone it is the default locale, and inside
60
+ * a caller's own `runWithContext` it is that context's.
61
+ */
51
62
  readonly url?: string;
52
63
  readonly params?: RouteParams;
53
64
  /** Who is asking. `load` and the page run inside a request context holding this actor. */
@@ -62,25 +73,27 @@ export interface RouteRequest {
62
73
  * for a route with no favicon to resolve.
63
74
  */
64
75
  readonly favicon?: AssetPath | undefined;
76
+ /**
77
+ * The cookies the request carries, by name: `load` and the page read them with
78
+ * `useRequestCookie(name)`, as a browser's request is read. Given, the render runs inside a GET
79
+ * request for `url`. Absent, no request is made: the render runs in whatever context it was called
80
+ * from — outside any request, a cookie read is `X_NO_REQUEST`.
81
+ */
82
+ readonly cookies?: Readonly<Record<string, string>> | undefined;
65
83
  }
66
84
 
67
85
  const DEFAULT_URL = 'http://localhost/';
68
86
 
69
87
  const SCRIPT_OR_STYLE = /<(script|style)\b[^>]*>[\s\S]*?<\/\1>/g;
70
88
 
71
- /**
72
- * `&amp;` last: decoding it first would turn the text `&amp;lt;` — an author's literal `&lt;` —
73
- * into `<`, a character the page never showed.
74
- */
89
+ /** HTML's collapsible whitespace: never U+00A0, which a translation may carry (`10&nbsp;€`). */
90
+ const COLLAPSIBLE = /[ \t\n\f\r]+/g;
91
+
92
+ /** Tags dropped before references are decoded, so a decoded `<` never reads as a tag. */
75
93
  const visibleText = (html: string): string =>
76
- html
77
- .replace(SCRIPT_OR_STYLE, ' ')
78
- .replace(/<[^>]*>/g, ' ')
79
- .replaceAll('&lt;', '<')
80
- .replaceAll('&gt;', '>')
81
- .replaceAll('&amp;', '&')
82
- .replace(/\s+/g, ' ')
83
- .trim();
94
+ decodeHtmlEntities(html.replace(SCRIPT_OR_STYLE, ' ').replace(/<[^>]*>/g, ' '))
95
+ .replace(COLLAPSIBLE, ' ')
96
+ .replace(/^[ ]+|[ ]+$/g, '');
84
97
 
85
98
  const viewOf = (html: string): RenderedView => ({ html, text: visibleText(html) });
86
99
 
@@ -159,6 +172,45 @@ export async function renderRoute<TData>(
159
172
  return { ...viewOf(html), data, meta, islands: islands.directives, favicon };
160
173
  };
161
174
 
162
- if (request.actor === undefined) return run();
163
- return runWithContext(ctxOf({ actor: request.actor }), run);
175
+ // The locale a request for this URL would render in: a leading routed `/<locale>/` segment, as
176
+ // the router splits it. Unprefixed, the default — which `currentLocale()` answers outside a
177
+ // context too, so neither a locale nor an actor means no request context at all.
178
+ const locale = splitLocalePrefix(new URL(url).pathname)?.locale;
179
+ const rendered = request.cookies === undefined ? run : () => inRequest(url, request.cookies, run);
180
+ if (request.actor === undefined && locale === undefined) return rendered();
181
+ return runWithContext(
182
+ ctxOf({
183
+ ...(request.actor === undefined ? {} : { actor: request.actor }),
184
+ ...(locale === undefined ? {} : { locale }),
185
+ }),
186
+ rendered,
187
+ );
188
+ }
189
+
190
+ /**
191
+ * `fn` inside a GET request for `url` carrying `cookies`, each percent-encoded as `useRequestCookie`
192
+ * (core's `readCookie`) decodes it. The context it was called in keeps its actor and locale: the
193
+ * request's fields go over it, never its principal.
194
+ */
195
+ function inRequest<T>(
196
+ url: string,
197
+ cookies: Readonly<Record<string, string>> | undefined,
198
+ fn: () => Promise<T>,
199
+ ): Promise<T> {
200
+ const pairs = Object.entries(cookies ?? {}).map(
201
+ ([name, value]) => `${name}=${encodeURIComponent(value)}`,
202
+ );
203
+ const request = requestContext({
204
+ url: new URL(url),
205
+ method: 'GET',
206
+ role: 'web',
207
+ config: defineHttpConfig({ rateLimit: { scope: 'process' } }),
208
+ requestHeaders: pairs.length === 0 ? {} : { cookie: pairs.join('; ') },
209
+ });
210
+ const outer = tryUseContext();
211
+ const scope =
212
+ outer === undefined
213
+ ? request
214
+ : { ...outer, ...request, actor: outer.actor, locale: outer.locale };
215
+ return runWithContext(asCtx(scope), fn);
164
216
  }