@ultimat3/cli 31.26.0 → 31.27.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 +44 -36
- package/README.md +5 -4
- package/package.json +29 -29
- package/src/app-mcp.ts +17 -3
- package/src/cmd-cache-spec.ts +5 -2
- package/src/cmd-db-spec.ts +2 -3
- package/src/cmd-db.ts +0 -2
- package/src/cmd-deploy-verify-sample.ts +93 -0
- package/src/cmd-deploy-verify.ts +2 -41
- package/src/cmd-dev-spec.ts +15 -1
- package/src/cmd-dev.ts +31 -4
- package/src/cmd-doctor.ts +4 -1
- package/src/cmd-exercise-spec.ts +7 -1
- package/src/cmd-exercise.ts +22 -10
- package/src/cmd-generate.ts +2 -0
- package/src/cmd-jobs-spec.ts +3 -6
- package/src/cmd-jobs.ts +1 -7
- package/src/cmd-logs-spec.ts +2 -1
- package/src/cmd-logs.ts +9 -28
- package/src/cmd-planned.ts +11 -45
- package/src/cmd-profile-frames.ts +99 -0
- package/src/cmd-profile-spec.ts +24 -0
- package/src/cmd-profile.ts +164 -0
- package/src/cmd-status-sample.ts +57 -0
- package/src/cmd-status-spec.ts +30 -0
- package/src/cmd-status.ts +108 -0
- package/src/cmd-token-spec.ts +5 -2
- package/src/cmd-token.ts +7 -3
- package/src/coverage-island.ts +121 -0
- package/src/coverage-lcov.ts +49 -5
- package/src/coverage-remap.ts +146 -0
- package/src/db-replay-engine-prepared.ts +66 -0
- package/src/db-replay-engine-template.ts +156 -0
- package/src/db-replay-engine.ts +4 -0
- package/src/db-replay-scratch-reap.ts +54 -0
- package/src/deploy-verify-flags.ts +9 -2
- package/src/deploy-verify-grade.ts +10 -3
- package/src/dev-boot.ts +14 -1
- package/src/dev-dashboard-guard.ts +57 -10
- package/src/dev-host.ts +46 -0
- package/src/dev-tls-cache.ts +103 -0
- package/src/dev-tls-der.ts +69 -0
- package/src/dev-tls.ts +120 -0
- package/src/doctor-browser.ts +60 -0
- package/src/error-codes-verify.ts +47 -0
- package/src/error-codes.ts +14 -23
- package/src/exercise-database.ts +40 -7
- package/src/exercise-push-device.ts +51 -0
- package/src/exercise-route-api.ts +74 -0
- package/src/exercise-routes.ts +14 -5
- package/src/exercise-services.ts +3 -1
- package/src/exercise-shard-flag.ts +47 -0
- package/src/fix-command.ts +2 -2
- package/src/generate-factories.ts +5 -11
- package/src/generate-feature-required.ts +9 -4
- package/src/generate-files.ts +20 -2
- package/src/generate-kinds.ts +5 -1
- package/src/guards.ts +21 -6
- package/src/island-bundle-options.ts +48 -0
- package/src/island-bundle.ts +18 -46
- package/src/island-link.ts +5 -0
- package/src/island-outputs.ts +5 -0
- package/src/mcp-errors-verify.ts +35 -0
- package/src/mcp-errors.ts +10 -19
- package/src/mcp-host-logs.ts +121 -0
- package/src/mcp-host.ts +12 -73
- package/src/messages-floor.ts +19 -0
- package/src/messages-status.ts +10 -0
- package/src/messages.ts +21 -0
- package/src/registry.ts +4 -0
- package/src/role-start-types.ts +7 -0
- package/src/role-start.ts +4 -0
- package/src/serve-boot.ts +7 -1
- package/src/serve-env-tls.ts +57 -0
- package/src/solid-loader.ts +27 -10
- package/src/templates/generate-export-rows.ts +136 -0
- package/src/templates/generate-import-rows.ts +186 -0
- package/src/templates/generate-rows-slice.ts +95 -0
- package/src/templates/github/ci.yml.ts +4 -0
- package/src/templates/scaffold-db-package.ts +3 -0
- package/src/templates/scaffold-docs.ts +8 -6
- package/src/templates/scaffold-repo.ts +2 -7
- package/src/templates/scaffold-site.ts +4 -1
- package/src/templates/scaffold-suites.ts +72 -0
- package/src/templates/scaffold-test-services.ts +35 -10
- package/src/templates/scaffold-verify-floor.ts +53 -31
- package/src/templates/shapes/api.ts +4 -0
- package/src/templates/slice-foundation.ts +3 -3
- package/src/unthrown-codes.ts +1 -1
- package/src/upgrade-gate.ts +6 -1
- package/src/upgrade-guards-baseline.ts +43 -0
- package/src/upgrade-guards.ts +37 -2
- package/src/upgrade-report.ts +3 -0
- package/src/verify-coverage-run.ts +42 -11
- package/src/verify-e2e.ts +115 -4
- package/src/verify-floor.ts +27 -0
- package/src/verify-guard-baseline.ts +109 -0
- package/src/verify-live.ts +72 -0
- package/src/verify-merge-skips.ts +51 -0
- package/src/verify-merge.ts +36 -2
- package/src/verify-run.ts +48 -7
- package/src/verify-services.ts +287 -0
- package/src/verify-skip-reason.ts +53 -0
- package/src/verify-strict.ts +108 -0
- package/src/verify-test-command.ts +129 -0
- package/src/verify-tests.ts +39 -126
- package/types/babel-modules.d.ts +2 -0
- package/wiki/CLI-Reference.md +142 -23
- package/wiki/Caching-And-Invalidation.md +1 -1
- package/wiki/Entities-And-Migrations.md +1 -1
- package/wiki/Jobs-And-Workflows.md +3 -3
- package/wiki/Known-Gaps.md +5 -1
- package/wiki/MCP-And-AI.md +1 -1
- package/wiki/PWA-And-Offline.md +1 -1
- package/wiki/Troubleshooting.md +3 -3
- package/wiki/Tutorial-05-Deploy-Free.md +2 -2
- package/wiki/Upgrading.md +3 -0
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
// An island chunk's lcov lines, credited back to the app sources it was built from through the
|
|
2
|
+
// chunk's own source map. Pure: the sidecar text, the record and the files on disk come in, and
|
|
3
|
+
// per-source line facts go out. `coverage-island.ts` does the reading.
|
|
4
|
+
|
|
5
|
+
import type { FileCoverage, LcovRecord } from './coverage-lcov';
|
|
6
|
+
|
|
7
|
+
/** One chunk's map as `mountIsland` recorded it: the build's cwd, its `sources` and their text. */
|
|
8
|
+
export interface ChunkMap {
|
|
9
|
+
/** The chunk's file name as the test process imported it — the basename of its `SF:` line. */
|
|
10
|
+
readonly module: string;
|
|
11
|
+
/** Every `sources` entry resolved to an absolute POSIX path (Bun writes them cwd-relative). */
|
|
12
|
+
readonly sources: readonly string[];
|
|
13
|
+
readonly sourcesContent: readonly (string | undefined)[];
|
|
14
|
+
readonly mappings: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const BASE64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
|
|
18
|
+
|
|
19
|
+
/** One segment's base64-VLQ fields, or nothing when a character is not base64. */
|
|
20
|
+
function vlqFields(segment: string): readonly number[] | undefined {
|
|
21
|
+
const fields: number[] = [];
|
|
22
|
+
let value = 0;
|
|
23
|
+
let shift = 0;
|
|
24
|
+
for (const ch of segment) {
|
|
25
|
+
const digit = BASE64.indexOf(ch);
|
|
26
|
+
if (digit === -1) return undefined;
|
|
27
|
+
value += (digit & 31) * 2 ** shift;
|
|
28
|
+
if ((digit & 32) === 0) {
|
|
29
|
+
fields.push(value % 2 === 1 ? -(value - 1) / 2 : value / 2);
|
|
30
|
+
value = 0;
|
|
31
|
+
shift = 0;
|
|
32
|
+
} else shift += 5;
|
|
33
|
+
}
|
|
34
|
+
return fields;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Generated line (0-based) → the source index and 0-based original line of its FIRST mapped
|
|
39
|
+
* segment. The first segment only: a generated line that folds several original lines ran at least
|
|
40
|
+
* where it starts, and crediting every line it folds is how a minified two-line chunk would claim
|
|
41
|
+
* the whole island. An undercount, never a claim.
|
|
42
|
+
*
|
|
43
|
+
* A segment that names exactly the position the one before it named is skipped: Bun maps a line's
|
|
44
|
+
* leading indent back to where the PREVIOUS statement ended (`AAAA`), so taking it credited every
|
|
45
|
+
* indented line to the line above it (measured, Bun 1.4.4).
|
|
46
|
+
*/
|
|
47
|
+
export function firstSegments(
|
|
48
|
+
mappings: string,
|
|
49
|
+
): readonly (readonly [number, number] | undefined)[] {
|
|
50
|
+
const out: (readonly [number, number] | undefined)[] = [];
|
|
51
|
+
let source = 0;
|
|
52
|
+
let line = 0;
|
|
53
|
+
let seen = false;
|
|
54
|
+
for (const generated of mappings.split(';')) {
|
|
55
|
+
let first: readonly [number, number] | undefined;
|
|
56
|
+
for (const segment of generated.split(',')) {
|
|
57
|
+
const fields = segment === '' ? undefined : vlqFields(segment);
|
|
58
|
+
if (fields === undefined || fields.length < 4) continue;
|
|
59
|
+
source += fields[1] as number;
|
|
60
|
+
line += fields[2] as number;
|
|
61
|
+
const carried = seen && fields[1] === 0 && fields[2] === 0 && fields[3] === 0;
|
|
62
|
+
seen = true;
|
|
63
|
+
if (!carried) first ??= [source, line];
|
|
64
|
+
}
|
|
65
|
+
out.push(first);
|
|
66
|
+
}
|
|
67
|
+
return out;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** What one chunk says about one source: the 1-based lines it ran and the ones it did not. */
|
|
71
|
+
export interface ChunkLines {
|
|
72
|
+
readonly hit: ReadonlySet<number>;
|
|
73
|
+
readonly miss: ReadonlySet<number>;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* The chunk's `DA:` lines as lines of the app's sources. `relativeOf` keys a source (absolute
|
|
78
|
+
* path) the way the app's coverage is keyed, or refuses it; `disk` is that file's text now.
|
|
79
|
+
*
|
|
80
|
+
* A line is credited only when the text the chunk was built from holds, at that line number, the
|
|
81
|
+
* same non-blank text the file holds on disk. A plugin that rewrote the file (Babel's Solid
|
|
82
|
+
* transform without `retainLines`) moves every line, and a map then points at lines of code the
|
|
83
|
+
* file does not have there: those are dropped rather than credited to whatever sits at that number.
|
|
84
|
+
*/
|
|
85
|
+
export function chunkLines(
|
|
86
|
+
record: LcovRecord,
|
|
87
|
+
map: ChunkMap,
|
|
88
|
+
relativeOf: (absolute: string) => string | undefined,
|
|
89
|
+
disk: (relative: string) => string | undefined,
|
|
90
|
+
): ReadonlyMap<string, ChunkLines> {
|
|
91
|
+
const segments = firstSegments(map.mappings);
|
|
92
|
+
const keys = map.sources.map(relativeOf);
|
|
93
|
+
const built = map.sourcesContent.map((text) => text?.split('\n'));
|
|
94
|
+
const now = keys.map((key) => (key === undefined ? undefined : disk(key)?.split('\n')));
|
|
95
|
+
const out = new Map<string, { hit: Set<number>; miss: Set<number> }>();
|
|
96
|
+
for (const [generated, hits] of record.lines) {
|
|
97
|
+
const at = segments[generated - 1];
|
|
98
|
+
if (at === undefined) continue;
|
|
99
|
+
const [index, zeroLine] = at;
|
|
100
|
+
const key = keys[index];
|
|
101
|
+
const text = built[index]?.[zeroLine]?.trim();
|
|
102
|
+
if (key === undefined || text === undefined || text === '') continue;
|
|
103
|
+
if (now[index]?.[zeroLine]?.trim() !== text) continue;
|
|
104
|
+
const facts = out.get(key) ?? { hit: new Set<number>(), miss: new Set<number>() };
|
|
105
|
+
(hits > 0 ? facts.hit : facts.miss).add(zeroLine + 1);
|
|
106
|
+
out.set(key, facts);
|
|
107
|
+
}
|
|
108
|
+
for (const facts of out.values()) for (const line of facts.hit) facts.miss.delete(line);
|
|
109
|
+
return out;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* A source's coverage once a chunk's lines are added to it.
|
|
114
|
+
*
|
|
115
|
+
* Loaded directly too (`base`): a line the direct record missed and the chunk ran becomes hit, and
|
|
116
|
+
* nothing else moves — the line set stays the one Bun counted, so the chunk can only turn misses
|
|
117
|
+
* into hits. Functions keep the direct record's counts: Bun's lcov names no function, so which of
|
|
118
|
+
* the chunk's functions belong to this file is unknowable, and the direct count is a lower bound.
|
|
119
|
+
*
|
|
120
|
+
* Not loaded directly anywhere: weighed by the lines the chunk MAPS — its executable lines, as Bun
|
|
121
|
+
* would have counted them had it loaded the source — hit where the chunk ran them. Never by text
|
|
122
|
+
* lines: an import, a type or a JSX line is no line a map can credit, so weighing them read a fully
|
|
123
|
+
* driven island at 9 of 36 lines (the scaffold's theme toggle). Functions are `0 / 0`, NOT the
|
|
124
|
+
* unloaded estimate: shards fold by taking the best function count any of them reached
|
|
125
|
+
* (`mergeFileCoverage`), so an estimate here beside a shard that loaded the file directly
|
|
126
|
+
* replaced its real denominator — measured on `examples/dummy`, functions fell 67.0% → 63.4%.
|
|
127
|
+
*/
|
|
128
|
+
export function withChunkLines(base: FileCoverage | undefined, lines: ChunkLines): FileCoverage {
|
|
129
|
+
if (base !== undefined) {
|
|
130
|
+
const turned = base.miss.filter((line) => lines.hit.has(line));
|
|
131
|
+
if (turned.length === 0) return base;
|
|
132
|
+
return {
|
|
133
|
+
...base,
|
|
134
|
+
hit: [...base.hit, ...turned].sort((a, b) => a - b),
|
|
135
|
+
miss: base.miss.filter((line) => !lines.hit.has(line)),
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
const byLine = (a: number, b: number): number => a - b;
|
|
139
|
+
return {
|
|
140
|
+
hit: [...lines.hit].sort(byLine),
|
|
141
|
+
miss: [...lines.miss].filter((line) => !lines.hit.has(line)).sort(byLine),
|
|
142
|
+
funcsFound: 0,
|
|
143
|
+
funcsHit: 0,
|
|
144
|
+
chunkOnly: true,
|
|
145
|
+
};
|
|
146
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// A scratch database that starts PREPARED (framework tables and migrations applied) without paying
|
|
2
|
+
// for the preparation twice: on the embedded engine a data-directory snapshot keyed by what
|
|
3
|
+
// produced it (`@ultimat3/db`'s `dataSnapshot`), on Postgres a template database of that key cloned
|
|
4
|
+
// with `CREATE DATABASE … TEMPLATE`. The key IS the invalidation: a new migration is a new key.
|
|
5
|
+
|
|
6
|
+
// why: Bun ships no path joiner.
|
|
7
|
+
import { join } from 'node:path';
|
|
8
|
+
import type { DbClient } from '@ultimat3/db';
|
|
9
|
+
import { pgliteClient } from '@ultimat3/db';
|
|
10
|
+
import type { ReplayEngine } from './db-replay-engine';
|
|
11
|
+
import { withScratchDatabase } from './db-replay-engine';
|
|
12
|
+
import type { ScratchPreparation } from './db-replay-engine-template';
|
|
13
|
+
import { PREPARED_KEEP, withPreparedPostgres } from './db-replay-engine-template';
|
|
14
|
+
|
|
15
|
+
export type { ScratchPreparation } from './db-replay-engine-template';
|
|
16
|
+
export { PREPARED_KEEP, templateNameFor } from './db-replay-engine-template';
|
|
17
|
+
|
|
18
|
+
/** Where the embedded snapshots live: a directory of their own, under the app's state dir. */
|
|
19
|
+
export const preparedSnapshotDir = (stateDir: string): string => join(stateDir, 'cache', 'scratch');
|
|
20
|
+
|
|
21
|
+
async function withPreparedPglite<T>(
|
|
22
|
+
engine: Extract<ReplayEngine, { kind: 'embedded' }>,
|
|
23
|
+
stateDir: string,
|
|
24
|
+
preparation: ScratchPreparation,
|
|
25
|
+
work: (client: DbClient) => Promise<T>,
|
|
26
|
+
): Promise<T> {
|
|
27
|
+
const client = pgliteClient({
|
|
28
|
+
extensions: engine.extensions,
|
|
29
|
+
snapshotDir: join(stateDir, 'cache'),
|
|
30
|
+
dataSnapshot: {
|
|
31
|
+
dir: preparedSnapshotDir(stateDir),
|
|
32
|
+
key: preparation.key,
|
|
33
|
+
keep: PREPARED_KEEP,
|
|
34
|
+
},
|
|
35
|
+
});
|
|
36
|
+
try {
|
|
37
|
+
if (!(await client.restoredDataSnapshot?.())) {
|
|
38
|
+
await preparation.prepare(client);
|
|
39
|
+
// After the preparation and before any row of the caller's: what is kept is the schema.
|
|
40
|
+
await client.saveDataSnapshot?.();
|
|
41
|
+
}
|
|
42
|
+
return await work(client);
|
|
43
|
+
} finally {
|
|
44
|
+
await client.close();
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* `work` on a scratch database `preparation` has been applied to — restored or cloned when its key
|
|
50
|
+
* was prepared before, prepared (and kept) when not. No `stateDir`, embedded: prepared every time.
|
|
51
|
+
*/
|
|
52
|
+
export async function withPreparedScratch<T>(
|
|
53
|
+
engine: ReplayEngine,
|
|
54
|
+
stateDir: string | undefined,
|
|
55
|
+
preparation: ScratchPreparation,
|
|
56
|
+
work: (client: DbClient) => Promise<T>,
|
|
57
|
+
): Promise<T> {
|
|
58
|
+
if (engine.kind === 'postgres') return withPreparedPostgres(engine.adminUrl, preparation, work);
|
|
59
|
+
if (stateDir === undefined) {
|
|
60
|
+
return withScratchDatabase(engine, stateDir, async (client) => {
|
|
61
|
+
await preparation.prepare(client);
|
|
62
|
+
return work(client);
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
return withPreparedPglite(engine, stateDir, preparation, work);
|
|
66
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
// The Postgres half of a prepared scratch database: a template per key (`CREATE DATABASE …
|
|
2
|
+
// TEMPLATE`), built once under that key's advisory lock — polled to a deadline, never a statement
|
|
3
|
+
// the pool's timeout cancels — and a working clone per run, stamped so a killed run's is reaped.
|
|
4
|
+
|
|
5
|
+
import type { DbClient } from '@ultimat3/db';
|
|
6
|
+
import { DbError, postgresClient, raw, sql } from '@ultimat3/db';
|
|
7
|
+
import { reapScratch, stampScratch } from './db-replay-scratch-reap';
|
|
8
|
+
|
|
9
|
+
/** What a prepared scratch is: how to prepare one, and the hash of everything that decides it. */
|
|
10
|
+
export interface ScratchPreparation {
|
|
11
|
+
/** Hex digest of every input the preparation reads (schema DDL, migrations, extensions). */
|
|
12
|
+
readonly key: string;
|
|
13
|
+
readonly prepare: (client: DbClient) => Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Prepared states kept besides the newest: a branch switch back is a hit, and the disk bounded. */
|
|
17
|
+
export const PREPARED_KEEP = 2;
|
|
18
|
+
|
|
19
|
+
/** How long a run waits for another's build of the same key: a migration, never a seed. */
|
|
20
|
+
export const TEMPLATE_LOCK_WAIT_MS = 5 * 60 * 1000;
|
|
21
|
+
const TEMPLATE_LOCK_POLL_MS = 250;
|
|
22
|
+
|
|
23
|
+
/** A Postgres template's name for `key`: a prefix this module alone creates and drops. */
|
|
24
|
+
const TEMPLATE_PREFIX = 'x_scratch_tpl_';
|
|
25
|
+
/** Hex characters of the key a template's name carries. */
|
|
26
|
+
const KEY_CHARS = 24;
|
|
27
|
+
/** Exactly a template name, as a regular expression: never LIKE, whose `_` is any character. */
|
|
28
|
+
const TEMPLATE_NAME = `^${TEMPLATE_PREFIX}[0-9a-f]{${String(KEY_CHARS)}}$`;
|
|
29
|
+
export const templateNameFor = (key: string): string =>
|
|
30
|
+
`${TEMPLATE_PREFIX}${key.slice(0, KEY_CHARS)}`;
|
|
31
|
+
/** Where a template is built before it is renamed into place: a name eviction never matches. */
|
|
32
|
+
const buildPrefixFor = (key: string): string => `x_scratch_bld_${key.slice(0, KEY_CHARS)}_`;
|
|
33
|
+
|
|
34
|
+
const lockSql = (name: string) => sql`select pg_try_advisory_lock(hashtext(${name})) as held`;
|
|
35
|
+
const unlockSql = (name: string) => sql`select pg_advisory_unlock(hashtext(${name}))`;
|
|
36
|
+
|
|
37
|
+
type Admin = Pick<DbClient, 'one' | 'query' | 'execute'>;
|
|
38
|
+
|
|
39
|
+
/** The key's lock, polled: a builder may hold it for a whole migration, past any statement bound. */
|
|
40
|
+
async function acquire(session: Admin, template: string): Promise<void> {
|
|
41
|
+
const started = performance.now();
|
|
42
|
+
for (;;) {
|
|
43
|
+
const row = await session.one<{ held: boolean }>(lockSql(template));
|
|
44
|
+
if (row?.held === true) return;
|
|
45
|
+
const waited = Math.round(performance.now() - started);
|
|
46
|
+
if (waited >= TEMPLATE_LOCK_WAIT_MS) {
|
|
47
|
+
throw new DbError({
|
|
48
|
+
code: 'X_DB_LOCK_TIMEOUT',
|
|
49
|
+
cause: `another process held the build lock of scratch template ${template} for ${String(waited)} ms, so this run could not clone it`,
|
|
50
|
+
fix: `psql "$TEST_DATABASE_URL" -c "select pid, query from pg_stat_activity where datname like 'x_scratch_bld_%'" # then stop that run, or wait for it`,
|
|
51
|
+
meta: { template, waitedMs: waited },
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
await Bun.sleep(Math.min(TEMPLATE_LOCK_POLL_MS, TEMPLATE_LOCK_WAIT_MS - waited));
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Every template of the exact name shape past the newest kept, each only while nobody holds it. */
|
|
59
|
+
async function evictTemplates(admin: Admin, current: string): Promise<void> {
|
|
60
|
+
const stale = await admin.query<{ datname: string }>(
|
|
61
|
+
sql`select datname from pg_database where datname ~ ${TEMPLATE_NAME} and datname <> ${current} order by oid desc`,
|
|
62
|
+
);
|
|
63
|
+
for (const { datname } of stale.slice(PREPARED_KEEP)) {
|
|
64
|
+
// A process cloning it holds its lock: skipped, never dropped under the clone.
|
|
65
|
+
if ((await admin.one<{ held: boolean }>(lockSql(datname)))?.held !== true) continue;
|
|
66
|
+
try {
|
|
67
|
+
await admin.execute(raw(`drop database if exists "${datname}" with (force)`));
|
|
68
|
+
} finally {
|
|
69
|
+
await admin.execute(unlockSql(datname));
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** A killed build's databases for `key`: only the key's lock holder builds it, so any is debris. */
|
|
75
|
+
async function sweepBuilds(admin: Admin, key: string): Promise<void> {
|
|
76
|
+
if (!/^[0-9a-f]+$/.test(key.slice(0, KEY_CHARS))) return;
|
|
77
|
+
const debris = await admin.query<{ datname: string }>(
|
|
78
|
+
sql`select datname from pg_database where datname ~ ${`^${buildPrefixFor(key)}[0-9]+$`}`,
|
|
79
|
+
);
|
|
80
|
+
for (const { datname } of debris) {
|
|
81
|
+
await admin.execute(raw(`drop database if exists "${datname}" with (force)`));
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* The template for `key`, built once: into a database of its own name, renamed into place only when
|
|
87
|
+
* prepared, and dropped if the preparation fails — so no build, killed or refused, reads as ready.
|
|
88
|
+
* Called under the key's lock.
|
|
89
|
+
*/
|
|
90
|
+
async function ensureTemplate(
|
|
91
|
+
admin: Admin,
|
|
92
|
+
adminUrl: string,
|
|
93
|
+
preparation: ScratchPreparation,
|
|
94
|
+
): Promise<string> {
|
|
95
|
+
const template = templateNameFor(preparation.key);
|
|
96
|
+
const found = await admin.one(sql`select 1 as hit from pg_database where datname = ${template}`);
|
|
97
|
+
if (found !== null) return template;
|
|
98
|
+
await sweepBuilds(admin, preparation.key);
|
|
99
|
+
const building = `${buildPrefixFor(preparation.key)}${String(process.pid)}`;
|
|
100
|
+
await admin.execute(raw(`create database "${building}" template template0`));
|
|
101
|
+
try {
|
|
102
|
+
const target = new URL(adminUrl);
|
|
103
|
+
target.pathname = `/${building}`;
|
|
104
|
+
// `migrate`: no statement timeout — a migration is as long as it is.
|
|
105
|
+
const client = postgresClient({ url: target.toString(), role: 'migrate' });
|
|
106
|
+
try {
|
|
107
|
+
await preparation.prepare(client);
|
|
108
|
+
} finally {
|
|
109
|
+
await client.close();
|
|
110
|
+
}
|
|
111
|
+
await admin.execute(raw(`alter database "${building}" rename to "${template}"`));
|
|
112
|
+
} catch (error) {
|
|
113
|
+
await admin.execute(raw(`drop database if exists "${building}" with (force)`));
|
|
114
|
+
throw error;
|
|
115
|
+
}
|
|
116
|
+
await evictTemplates(admin, template);
|
|
117
|
+
return template;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** `work` on a fresh clone of `preparation`'s template, built first when the key is new. */
|
|
121
|
+
export async function withPreparedPostgres<T>(
|
|
122
|
+
adminUrl: string,
|
|
123
|
+
preparation: ScratchPreparation,
|
|
124
|
+
work: (client: DbClient) => Promise<T>,
|
|
125
|
+
): Promise<T> {
|
|
126
|
+
const database = `x_scratch_${String(process.pid)}_${crypto.randomUUID().slice(0, 8)}`;
|
|
127
|
+
// `migrate`: no statement timeout on the clone of a large template, nor on the build.
|
|
128
|
+
const admin = postgresClient({ url: adminUrl, role: 'migrate' });
|
|
129
|
+
try {
|
|
130
|
+
await reapScratch(admin);
|
|
131
|
+
const template = templateNameFor(preparation.key);
|
|
132
|
+
{
|
|
133
|
+
// One session holds the lock: a pool's next statement may land on another.
|
|
134
|
+
using session = await admin.reserve();
|
|
135
|
+
await acquire(session, template);
|
|
136
|
+
try {
|
|
137
|
+
await ensureTemplate(session, adminUrl, preparation);
|
|
138
|
+
await session.execute(raw(`create database "${database}" template "${template}"`));
|
|
139
|
+
await stampScratch(session, database);
|
|
140
|
+
} finally {
|
|
141
|
+
await session.execute(unlockSql(template));
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
const target = new URL(adminUrl);
|
|
145
|
+
target.pathname = `/${database}`;
|
|
146
|
+
const client = postgresClient({ url: target.toString() });
|
|
147
|
+
try {
|
|
148
|
+
return await work(client);
|
|
149
|
+
} finally {
|
|
150
|
+
await client.close();
|
|
151
|
+
await admin.execute(raw(`drop database if exists "${database}" with (force)`));
|
|
152
|
+
}
|
|
153
|
+
} finally {
|
|
154
|
+
await admin.close();
|
|
155
|
+
}
|
|
156
|
+
}
|
package/src/db-replay-engine.ts
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
import { join } from 'node:path';
|
|
8
8
|
import type { DbClient, LinkedExtensions, Migration } from '@ultimat3/db';
|
|
9
9
|
import { DbError, linkPgliteExtensions, pgliteClient, postgresClient, raw } from '@ultimat3/db';
|
|
10
|
+
import { reapScratch, stampScratch } from './db-replay-scratch-reap';
|
|
10
11
|
import { migrationExtensions } from './migration-extensions';
|
|
11
12
|
|
|
12
13
|
type Env = Readonly<Record<string, string | undefined>>;
|
|
@@ -69,9 +70,12 @@ async function withPostgresScratch<T>(
|
|
|
69
70
|
const database = scratchName();
|
|
70
71
|
const admin = postgresClient({ url: adminUrl });
|
|
71
72
|
try {
|
|
73
|
+
// A killed run's working database, stamped and old, goes first (`db-replay-scratch-reap.ts`).
|
|
74
|
+
await reapScratch(admin);
|
|
72
75
|
// `template0`: the server's `template1` may carry objects an operator put there, and they
|
|
73
76
|
// would be dumped as the app's.
|
|
74
77
|
await admin.execute(raw(`create database ${database} template template0`));
|
|
78
|
+
await stampScratch(admin, database);
|
|
75
79
|
const target = new URL(adminUrl);
|
|
76
80
|
target.pathname = `/${database}`;
|
|
77
81
|
const client = postgresClient({ url: target.toString() });
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// The working databases a scratch run creates on a shared Postgres — the schema dump's and the
|
|
2
|
+
// exercise pass's clones — stamped with the SERVER's clock when created, and a killed run's reaped
|
|
3
|
+
// by the next run once older than `SCRATCH_MAX_AGE_MS`: `reapBranches`' shape (`@ultimat3/db`'s
|
|
4
|
+
// `branch.ts`). Only a stamped database of this module's exact name shape is ever dropped.
|
|
5
|
+
|
|
6
|
+
import type { DbClient } from '@ultimat3/db';
|
|
7
|
+
import { identifier, literal, raw, sql } from '@ultimat3/db';
|
|
8
|
+
|
|
9
|
+
/** The comment a working database carries: this marker, then its creation as UTC ISO seconds. */
|
|
10
|
+
export const SCRATCH_MARKER = 'ultimate:scratch:';
|
|
11
|
+
|
|
12
|
+
/** A working database older than this is a killed run's: no pass holds one for six hours. */
|
|
13
|
+
export const SCRATCH_MAX_AGE_MS = 6 * 60 * 60 * 1000;
|
|
14
|
+
|
|
15
|
+
/** Exactly a working database's name — `x_scratch_<pid>_<8 hex>`, `x_schema_dump_<pid>_<8 hex>`. */
|
|
16
|
+
const WORKING_NAME = '^x_(scratch|schema_dump)_[0-9]+_[0-9a-f]{8}$';
|
|
17
|
+
|
|
18
|
+
/** Exactly a stamp: anything else in the comment is somebody else's, and never read as an age. */
|
|
19
|
+
const STAMP = /^ultimate:scratch:(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z)$/;
|
|
20
|
+
|
|
21
|
+
type Admin = Pick<DbClient, 'one' | 'query' | 'execute'>;
|
|
22
|
+
|
|
23
|
+
/** Stamp `database` with the server's now: the age a later run reads is the server's, too. */
|
|
24
|
+
export async function stampScratch(admin: Admin, database: string): Promise<void> {
|
|
25
|
+
const row = await admin.one<{ at: string }>(
|
|
26
|
+
sql`select to_char(now() at time zone 'utc', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') as at`,
|
|
27
|
+
);
|
|
28
|
+
if (row === null) return;
|
|
29
|
+
await admin.execute(
|
|
30
|
+
sql`comment on database ${identifier(database)} is ${literal(`${SCRATCH_MARKER}${row.at}`)}`,
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Drop every stamped working database older than `maxAgeMs` by the server's clock; their names. */
|
|
35
|
+
export async function reapScratch(
|
|
36
|
+
admin: Admin,
|
|
37
|
+
maxAgeMs: number = SCRATCH_MAX_AGE_MS,
|
|
38
|
+
): Promise<readonly string[]> {
|
|
39
|
+
const rows = await admin.query<{ name: string; comment: string | null; now_ms: string | number }>(
|
|
40
|
+
sql`select d.datname as name, shobj_description(d.oid, 'pg_database') as comment,
|
|
41
|
+
(extract(epoch from now()) * 1000)::bigint as now_ms
|
|
42
|
+
from pg_database d where d.datname ~ ${WORKING_NAME}`,
|
|
43
|
+
);
|
|
44
|
+
const reaped: string[] = [];
|
|
45
|
+
for (const row of rows) {
|
|
46
|
+
const stamp = STAMP.exec(row.comment ?? '')?.[1];
|
|
47
|
+
if (stamp === undefined) continue;
|
|
48
|
+
const created = Date.parse(stamp);
|
|
49
|
+
if (!Number.isFinite(created) || Number(row.now_ms) - created < maxAgeMs) continue;
|
|
50
|
+
await admin.execute(raw(`drop database if exists "${row.name}" with (force)`));
|
|
51
|
+
reaped.push(row.name);
|
|
52
|
+
}
|
|
53
|
+
return reaped;
|
|
54
|
+
}
|
|
@@ -48,9 +48,16 @@ function parsedOrNaN(raw: string): number {
|
|
|
48
48
|
* The origin, and only that: `/readyz` lives at the root, so a path would be silently dropped, and
|
|
49
49
|
* credentials would ride into every log line that names the URL. The cause never echoes the value.
|
|
50
50
|
*/
|
|
51
|
-
function readOrigin(
|
|
51
|
+
export function readOrigin(
|
|
52
|
+
raw: string | undefined,
|
|
53
|
+
// The command the refusal names, and a runnable invocation of it: `x status` reads `--url` too.
|
|
54
|
+
asker: { readonly command: string; readonly example: string } = {
|
|
55
|
+
command: VERIFY_COMMAND,
|
|
56
|
+
example: EXAMPLE,
|
|
57
|
+
},
|
|
58
|
+
): string {
|
|
52
59
|
const refuse = (reason: string): BadFlagError =>
|
|
53
|
-
new BadFlagError({ flag: 'url', command:
|
|
60
|
+
new BadFlagError({ flag: 'url', command: asker.command, reason, fix: asker.example });
|
|
54
61
|
if (raw === undefined) throw refuse('it is required: the origin the load balancer answers on');
|
|
55
62
|
const parsed = URL.canParse(raw) ? new URL(raw) : undefined;
|
|
56
63
|
if (parsed === undefined || !['http:', 'https:'].includes(parsed.protocol)) {
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// graded per queue. No socket, no database, no clock — `cmd-deploy-verify.ts` owns the waiting.
|
|
3
3
|
|
|
4
4
|
import type { WorkerRecord } from '@ultimat3/jobs';
|
|
5
|
+
import { printableBuild } from './cmd-deploy-verify-sample';
|
|
5
6
|
|
|
6
7
|
/** One `GET /readyz`. A `null` status is a sample nothing answered: refused, reset, timed out. */
|
|
7
8
|
export interface Sample {
|
|
@@ -116,16 +117,22 @@ export function failureOf(tally: SampleTally, build: string): SampleFailure {
|
|
|
116
117
|
return namedNone && tally.unstamped > 0 ? 'X_DEPLOY_BUILD_UNSTAMPED' : 'X_DEPLOY_BUILD_MISMATCH';
|
|
117
118
|
}
|
|
118
119
|
|
|
119
|
-
/**
|
|
120
|
+
/**
|
|
121
|
+
* The tally as `--json` reports it. The window's bookkeeping stays out. A build name is the
|
|
122
|
+
* server's own bytes, so it is printed through `printableBuild`; the tally itself stays raw, which
|
|
123
|
+
* is what the grade matched on.
|
|
124
|
+
*/
|
|
120
125
|
export const tallyToJson = (tally: SampleTally) => ({
|
|
121
126
|
total: tally.total,
|
|
122
127
|
good: tally.good,
|
|
123
|
-
byBuild:
|
|
128
|
+
byBuild: Object.fromEntries(
|
|
129
|
+
Object.entries(tally.byBuild).map(([name, count]) => [printableBuild(name), count]),
|
|
130
|
+
),
|
|
124
131
|
byStatus: { ...tally.byStatus },
|
|
125
132
|
/** Each build's share of every sample, to three places: a stuck roll reads as its old share. */
|
|
126
133
|
share: Object.fromEntries(
|
|
127
134
|
Object.entries(tally.byBuild).map(([name, count]) => [
|
|
128
|
-
name,
|
|
135
|
+
printableBuild(name),
|
|
129
136
|
Math.round((count / Math.max(1, tally.total)) * 1000) / 1000,
|
|
130
137
|
]),
|
|
131
138
|
),
|
package/src/dev-boot.ts
CHANGED
|
@@ -18,6 +18,7 @@ import type { DevDashboardInput, DevStatus } from './dev-dashboard';
|
|
|
18
18
|
import { devPanels } from './dev-dashboard';
|
|
19
19
|
import { createInvalidationLog } from './dev-dashboard-invalidations';
|
|
20
20
|
import { declareDevEnvironment, needsDevEnvironmentDeclaration } from './dev-environment';
|
|
21
|
+
import { dialableUrl } from './dev-host';
|
|
21
22
|
import { createStatementLedger } from './dev-n-plus-one';
|
|
22
23
|
import type { DevState } from './dev-rebuild';
|
|
23
24
|
import { buildGeneration, devRebuilder } from './dev-rebuild';
|
|
@@ -40,6 +41,7 @@ import { replicaOverrides } from './runtime-replica';
|
|
|
40
41
|
import type { RunningServices } from './runtime-services';
|
|
41
42
|
import { releaseOrThrow, startServices } from './runtime-services';
|
|
42
43
|
import { metricsPortFor, releaseBoot } from './serve';
|
|
44
|
+
import type { ListenerTls } from './serve-env-tls';
|
|
43
45
|
import { loopFacts, loopFinding, loopNotice } from './statement-loop';
|
|
44
46
|
|
|
45
47
|
export interface DevServer {
|
|
@@ -71,6 +73,13 @@ export interface DevServer {
|
|
|
71
73
|
export interface StartDevOptions {
|
|
72
74
|
readonly root: string;
|
|
73
75
|
readonly port: number;
|
|
76
|
+
/**
|
|
77
|
+
* The interface every socket binds (`WebBinding` is one decision): `x dev --host`. Absent is
|
|
78
|
+
* loopback. `/_x` answers a loopback peer and Host whatever this says (`hostRefusal`).
|
|
79
|
+
*/
|
|
80
|
+
readonly hostname?: string;
|
|
81
|
+
/** `x dev --tls`: the generated local pair (`dev-tls.ts`); the web listener serves https. */
|
|
82
|
+
readonly tls?: ListenerTls;
|
|
74
83
|
readonly env: Readonly<Record<string, string | undefined>>;
|
|
75
84
|
readonly roles?: readonly Role[];
|
|
76
85
|
readonly onReload?: (file: string, durationMs: number) => void;
|
|
@@ -279,6 +288,9 @@ async function bootDev(
|
|
|
279
288
|
const running = await startRoles({
|
|
280
289
|
roles: options.roles ?? DEV_ROLES,
|
|
281
290
|
port: options.port,
|
|
291
|
+
// Dev-mode whatever the interface: a wider bind is still a development process.
|
|
292
|
+
...(options.hostname === undefined ? {} : { http: { dev: true, hostname: options.hostname } }),
|
|
293
|
+
...(options.tls === undefined ? {} : { tls: options.tls }),
|
|
282
294
|
// `serve.ts`'s expression, called rather than restated: `METRICS_PORT` was read in the
|
|
283
295
|
// container and ignored here, so the scrape port an operator moved was the one port `x dev`
|
|
284
296
|
// could not move — and the second `x dev` on a box died binding the hardcoded 9090.
|
|
@@ -319,7 +331,8 @@ async function bootDev(
|
|
|
319
331
|
const watcher = watchTree({ root: options.root, onChange: rebuild });
|
|
320
332
|
|
|
321
333
|
server = {
|
|
322
|
-
|
|
334
|
+
// Dialable, never Bun's `http://0.0.0.0:<port>`: the lock, `x shot` and `/_x` read this.
|
|
335
|
+
url: dialableUrl(running.url ?? `http://localhost:${options.port}`),
|
|
323
336
|
services,
|
|
324
337
|
roles: running.roles,
|
|
325
338
|
mcp: mcpPath,
|
|
@@ -1,10 +1,18 @@
|
|
|
1
|
-
// The doors in front of `/_x
|
|
2
|
-
//
|
|
3
|
-
//
|
|
1
|
+
// The doors in front of `/_x`. `x dev` binds loopback by default, but a page the developer has
|
|
2
|
+
// open can still reach it: by DNS rebinding (a hostile name that resolves to 127.0.0.1, read back
|
|
3
|
+
// same-origin) and by a cross-site request to the SQL panel. Bound wider (`--host`), a LAN peer
|
|
4
|
+
// can knock too, naming a loopback Host itself — so the peer's own address is asked as well.
|
|
4
5
|
|
|
5
6
|
import { proveSameOrigin, renderFixShellArg, UltimateError } from '@ultimat3/core';
|
|
6
7
|
import type { UltimateRequest } from '@ultimat3/http';
|
|
7
|
-
import {
|
|
8
|
+
import {
|
|
9
|
+
callerLocality,
|
|
10
|
+
csrfBlocked,
|
|
11
|
+
HttpError,
|
|
12
|
+
jsonResponse,
|
|
13
|
+
RELAY_HEADERS,
|
|
14
|
+
selfOrigin,
|
|
15
|
+
} from '@ultimat3/http';
|
|
8
16
|
import { t } from '@ultimat3/schema';
|
|
9
17
|
import { isLoopbackHostname } from './loopback-host';
|
|
10
18
|
|
|
@@ -20,23 +28,62 @@ export class DevHostRefusedError extends UltimateError {
|
|
|
20
28
|
}
|
|
21
29
|
}
|
|
22
30
|
|
|
31
|
+
/**
|
|
32
|
+
* A `/_x` request from a peer that is not this machine — `x dev --host` bound a wider interface,
|
|
33
|
+
* and `/_x` (the app's SQL, outbox and spans) stays loopback-only whatever it bound. The fix dials
|
|
34
|
+
* the same server through loopback, which a wildcard bind answers on too.
|
|
35
|
+
*/
|
|
36
|
+
export class DevPeerRefusedError extends UltimateError {
|
|
37
|
+
constructor(input: { devUrl: string; relay?: string }) {
|
|
38
|
+
// The scheme and port the server speaks (`x dev --tls` is https), on the loopback name.
|
|
39
|
+
const parsed = URL.parse(input.devUrl);
|
|
40
|
+
const scheme = parsed?.protocol === 'https:' ? 'https' : 'http';
|
|
41
|
+
const port = parsed?.port ?? '';
|
|
42
|
+
const loopback = `${scheme}://localhost${port === '' ? '' : `:${port}`}/_x`;
|
|
43
|
+
super({
|
|
44
|
+
code: 'X_DEV_PEER_REFUSED',
|
|
45
|
+
cause:
|
|
46
|
+
input.relay === undefined
|
|
47
|
+
? 'a /_x request came from a peer address that is not loopback — x dev was bound past loopback with --host, and the dev dashboard answers this machine only'
|
|
48
|
+
: `a /_x request carried ${input.relay}, which a relay writes and a browser never sends — a tunnel or proxy in front of this x dev speaks for callers that are not this machine, and the dev dashboard answers this machine only`,
|
|
49
|
+
fix: `curl -sS -H 'accept: application/json' ${renderFixShellArg(loopback, 'http://localhost:3000/_x')} # on the machine x dev runs on; x dev --host 0.0.0.0 keeps loopback bound`,
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The first relay header the request carries — named in the refusal, never its value. */
|
|
55
|
+
const relayOf = (request: UltimateRequest): string | undefined =>
|
|
56
|
+
RELAY_HEADERS.find((name) => request.header(name) !== null);
|
|
57
|
+
|
|
23
58
|
/** The Host as sent, else the one the URL was built from — Bun builds it from the header. */
|
|
24
59
|
const hostnameOf = (request: UltimateRequest): string | undefined => {
|
|
25
60
|
const header = request.header('host') ?? request.url.host;
|
|
26
61
|
return URL.parse(`http://${header}`)?.hostname;
|
|
27
62
|
};
|
|
28
63
|
|
|
64
|
+
const refusal = (error: UltimateError, status: number): Response =>
|
|
65
|
+
jsonResponse(
|
|
66
|
+
{ ok: false, error: { code: error.code, cause: error.cause, fix: error.fix } },
|
|
67
|
+
{ status },
|
|
68
|
+
);
|
|
69
|
+
|
|
29
70
|
/**
|
|
30
71
|
* `421 Misdirected Request` for a Host that is not this machine, on every `/_x` route. The status
|
|
31
|
-
* says "not this server", which is the truth: a rebound name was never meant to reach it.
|
|
72
|
+
* says "not this server", which is the truth: a rebound name was never meant to reach it. Then
|
|
73
|
+
* `403` for a peer that is not this machine — the Host was right, the caller is not allowed.
|
|
32
74
|
*/
|
|
33
75
|
export function hostRefusal(request: UltimateRequest, devUrl: string): Response | undefined {
|
|
34
76
|
const hostname = hostnameOf(request);
|
|
35
|
-
if (hostname
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
77
|
+
if (hostname === undefined || !isLoopbackHostname(hostname)) {
|
|
78
|
+
return refusal(new DevHostRefusedError({ devUrl }), 421);
|
|
79
|
+
}
|
|
80
|
+
// http's one rule (`callerLocality`), the same the dev overlay and the dev MCP token ask.
|
|
81
|
+
const locality = callerLocality({ ip: request.ctx.ip, headers: request.headers });
|
|
82
|
+
if (locality === 'local') return undefined;
|
|
83
|
+
const relay = locality === 'relayed' ? relayOf(request) : undefined;
|
|
84
|
+
return refusal(
|
|
85
|
+
new DevPeerRefusedError({ devUrl, ...(relay === undefined ? {} : { relay }) }),
|
|
86
|
+
403,
|
|
40
87
|
);
|
|
41
88
|
}
|
|
42
89
|
|