@ultimat3/cli 31.16.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/README.md +7 -1
- package/package.json +29 -29
- package/src/cache-graph.ts +67 -0
- package/src/cmd-cache-spec.ts +25 -0
- package/src/cmd-cache.ts +187 -0
- package/src/cmd-config-spec.ts +23 -0
- package/src/cmd-config.ts +61 -0
- package/src/cmd-exercise.ts +34 -10
- package/src/cmd-explain-spec.ts +24 -0
- package/src/cmd-explain.ts +201 -0
- package/src/cmd-logs-spec.ts +34 -0
- package/src/cmd-logs.ts +80 -0
- package/src/cmd-planned.ts +15 -29
- package/src/cmd-token-spec.ts +54 -0
- package/src/cmd-token.ts +173 -0
- package/src/cmd-verify-spec.ts +13 -3
- package/src/cmd-verify.ts +2 -0
- package/src/config-redact.ts +39 -0
- package/src/dev-boot-data-dir.ts +69 -0
- package/src/dev-boot.ts +26 -13
- package/src/error-codes-tooling.ts +6 -4
- package/src/error-codes.ts +2 -0
- package/src/errors.ts +8 -2
- package/src/exercise-entry-edit.ts +5 -1
- package/src/exercise-routes.ts +59 -0
- package/src/explain-capture.ts +38 -0
- package/src/generate-exercise.ts +2 -2
- package/src/generate-factories.ts +133 -0
- package/src/generate-files.ts +11 -0
- package/src/generate-kinds.ts +13 -0
- package/src/mcp-db-target.ts +4 -3
- package/src/mcp-errors.ts +4 -0
- package/src/messages-gate.ts +2 -0
- package/src/messages-ops.ts +32 -0
- package/src/messages-upgrade.ts +1 -0
- package/src/messages.ts +2 -0
- package/src/otlp-export.ts +16 -2
- package/src/registry.ts +10 -0
- package/src/role-start.ts +11 -5
- package/src/runtime-services.ts +35 -19
- package/src/serve-boot-phases.ts +30 -0
- package/src/serve-boot-warnings.ts +62 -0
- package/src/serve-boot.ts +30 -11
- package/src/templates/generate-cron-job.ts +90 -0
- package/src/templates/generate-purge.ts +93 -0
- package/src/templates/generate-webhook-receiver.ts +274 -0
- package/src/templates/github/ci.yml.ts +101 -36
- package/src/templates/guard-repo-raw-sql-test.ts +174 -0
- package/src/templates/guard-repo-raw-sql.ts +115 -145
- package/src/templates/guard-unbounded-fanout.ts +170 -0
- package/src/templates/scaffold-claude-commands.ts +3 -2
- package/src/templates/scaffold-docs.ts +3 -2
- package/src/templates/scaffold-guards.ts +3 -0
- package/src/upgrade-gate.ts +18 -6
- package/src/upgrade-report.ts +4 -0
- package/src/verify-plan.ts +127 -0
- package/wiki/CI-Parallel-Gate.md +38 -1
- package/wiki/CLI-Reference.md +90 -12
- package/wiki/Caching-And-Invalidation.md +10 -10
- package/wiki/Configuration.md +4 -2
- package/wiki/Known-Gaps.md +1 -1
- package/wiki/MCP-And-AI.md +1 -1
- package/wiki/Testing.md +32 -0
- package/wiki/Troubleshooting.md +3 -2
- package/wiki/Upgrading.md +6 -0
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// `x g purge` — the retention sweep for every `retain` the schema declares, and the hourly task that
|
|
2
|
+
// fires it. `purge()` is a factory over `job()`, never a ninth primitive; without one covering a
|
|
3
|
+
// `retain`, `x verify` refuses it (`X_ENTITY_RETAIN_UNSWEPT`), so this is the declaration that answers.
|
|
4
|
+
|
|
5
|
+
import type { FeatureTarget } from './entity';
|
|
6
|
+
import type { GeneratedFile, NameSet } from './naming';
|
|
7
|
+
import { names } from './naming';
|
|
8
|
+
|
|
9
|
+
const source = (
|
|
10
|
+
name: NameSet,
|
|
11
|
+
): string => `// ${name.camel}: every \`retain\` the schema declares, kept. \`purge()\` is a factory over job(),
|
|
12
|
+
// so a sweep is retried, cancellable and in the manifest like any job. \`entities: 'declared'\`
|
|
13
|
+
// reads the declarations on every pass: a new \`retain\` on an entity needs no line here.
|
|
14
|
+
// List this module in apps/web/api/index.ts's \`jobs:\` to register it; ../tasks fires it hourly.
|
|
15
|
+
|
|
16
|
+
import { purge } from '@ultimat3/jobs';
|
|
17
|
+
|
|
18
|
+
export const ${name.camel} = purge({
|
|
19
|
+
// Pinned: the queue keys the rows it already stores by this name.
|
|
20
|
+
name: '${name.kebab}',
|
|
21
|
+
entities: 'declared',
|
|
22
|
+
});
|
|
23
|
+
`;
|
|
24
|
+
|
|
25
|
+
const taskSource = (
|
|
26
|
+
name: NameSet,
|
|
27
|
+
): string => `// ${name.camel}Hourly: fires ${name.camel} on the framework's purge cron, in an explicit zone. A task
|
|
28
|
+
// only enqueues; the sweep itself is the durable, retried job.
|
|
29
|
+
|
|
30
|
+
import { DEFAULT_PURGE_CRON, task } from '@ultimat3/jobs';
|
|
31
|
+
import { ${name.camel} } from '../jobs/${name.kebab}';
|
|
32
|
+
|
|
33
|
+
export const ${name.camel}Hourly = task({
|
|
34
|
+
name: '${name.kebab}.hourly',
|
|
35
|
+
cron: DEFAULT_PURGE_CRON,
|
|
36
|
+
tz: 'UTC',
|
|
37
|
+
enqueue: () => [[${name.camel}, {}]],
|
|
38
|
+
});
|
|
39
|
+
`;
|
|
40
|
+
|
|
41
|
+
const jobSuite = (
|
|
42
|
+
name: NameSet,
|
|
43
|
+
): string => `// ${name.camel}'s durable identity — one live sweep per name — and the task that fires it.
|
|
44
|
+
|
|
45
|
+
import { DEFAULT_PURGE_CRON, memoryJobDriver } from '@ultimat3/jobs';
|
|
46
|
+
import { beforeAll, expect, jobTest, swapAdapter } from '@ultimat3/testing';
|
|
47
|
+
import { ${name.camel}Hourly } from '../tasks/${name.kebab}-hourly';
|
|
48
|
+
import { ${name.camel} } from './${name.kebab}';
|
|
49
|
+
|
|
50
|
+
// The queue is a process-global adapter port, so it is swapped for this file and put back after.
|
|
51
|
+
beforeAll(() => swapAdapter('jobs', memoryJobDriver()));
|
|
52
|
+
|
|
53
|
+
jobTest('${name.camel} is a job its hourly task enqueues, in an explicit zone', () => {
|
|
54
|
+
expect(${name.camel}.kind).toBe('job');
|
|
55
|
+
expect(${name.camel}Hourly.cron).toBe(DEFAULT_PURGE_CRON);
|
|
56
|
+
expect(${name.camel}Hourly.tz).toBe('UTC');
|
|
57
|
+
expect(${name.camel}Hourly.entries().map(([handle]) => handle)).toEqual([${name.camel}]);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
jobTest('${name.camel} enqueues once, and dedupes a second sweep while one is live', async () => {
|
|
61
|
+
const first = await ${name.camel}.enqueue({});
|
|
62
|
+
expect(first.deduped).toBe(false);
|
|
63
|
+
const again = await ${name.camel}.enqueue({});
|
|
64
|
+
expect(again.deduped).toBe(true);
|
|
65
|
+
});
|
|
66
|
+
`;
|
|
67
|
+
|
|
68
|
+
const unitSuite = (
|
|
69
|
+
name: NameSet,
|
|
70
|
+
): string => `// ${name.camel}'s BODY, run by a worker in this process: one pass completes and reports what it
|
|
71
|
+
// removed — a number, never a guess, so \`x jobs show\` can print it.
|
|
72
|
+
|
|
73
|
+
import { expect, unitTest } from '@ultimat3/testing';
|
|
74
|
+
import { ${name.camel} } from './${name.kebab}';
|
|
75
|
+
|
|
76
|
+
unitTest('one pass completes and reports how many rows it removed', async ({ runJobs }) => {
|
|
77
|
+
const trace = await runJobs(${name.camel}, {});
|
|
78
|
+
expect(trace.executions.map((run) => run.outcome)).toEqual(['completed']);
|
|
79
|
+
expect(trace.executions[0]?.result).toMatchObject({ removed: 0 });
|
|
80
|
+
});
|
|
81
|
+
`;
|
|
82
|
+
|
|
83
|
+
/** The sweep and its job/unit tests in the feature's `jobs/`, the hourly task in its `tasks/`. */
|
|
84
|
+
export function purgeFiles(rawName: string, target: FeatureTarget): readonly GeneratedFile[] {
|
|
85
|
+
const name = names(rawName);
|
|
86
|
+
const dir = `${target.surfaceDir}/${target.feature}`;
|
|
87
|
+
return [
|
|
88
|
+
{ path: `${dir}/jobs/${name.kebab}.ts`, contents: source(name) },
|
|
89
|
+
{ path: `${dir}/jobs/${name.kebab}.job.test.ts`, contents: jobSuite(name) },
|
|
90
|
+
{ path: `${dir}/jobs/${name.kebab}.test.ts`, contents: unitSuite(name) },
|
|
91
|
+
{ path: `${dir}/tasks/${name.kebab}-hourly.ts`, contents: taskSource(name) },
|
|
92
|
+
];
|
|
93
|
+
}
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
// `x g webhook-receiver` — one inbound webhook: `webhookReceiver()`, a factory over `job()` plus the
|
|
2
|
+
// route that feeds it. The route reads the exact bytes, `verify` checks the hmac and reads the event
|
|
3
|
+
// OUT OF THE SIGNED BYTES, the event is queued durably and only then acknowledged. Which vendor and
|
|
4
|
+
// what an event means stay the app's: the template is a timestamped hmac, refused outside a window.
|
|
5
|
+
|
|
6
|
+
import type { ExerciseEntry } from '../exercise-entry-edit';
|
|
7
|
+
import type { FeatureTarget } from './entity';
|
|
8
|
+
import type { GeneratedFile, NameSet } from './naming';
|
|
9
|
+
import { names } from './naming';
|
|
10
|
+
|
|
11
|
+
/** `billing-events` → `BILLING_EVENTS`: the prefix of the path, header and secret constants. */
|
|
12
|
+
const constant = (name: NameSet): string => name.kebab.replaceAll('-', '_').toUpperCase();
|
|
13
|
+
|
|
14
|
+
const source = (name: NameSet, path: string): string => {
|
|
15
|
+
const c = constant(name);
|
|
16
|
+
return `// ${name.camel}: one inbound webhook. \`webhookReceiver()\` is a factory over job(): the route reads the
|
|
17
|
+
// exact bytes, \`verify\` checks the hmac over \`<timestamp>.<body>\`, refuses a delivery signed
|
|
18
|
+
// outside the replay window and reads the event out of the SIGNED bytes — so one captured request
|
|
19
|
+
// is neither replayable later nor under fresh ids — and the event is queued durably before it is
|
|
20
|
+
// acknowledged. List this module in apps/web/api/index.ts's \`jobs:\`: the boot mounts it.
|
|
21
|
+
|
|
22
|
+
import { ambientClock } from '@ultimat3/core';
|
|
23
|
+
import { defineError } from '@ultimat3/core/page';
|
|
24
|
+
import { verifyBodyHmac } from '@ultimat3/http';
|
|
25
|
+
import { t, webhookReceiver } from '@ultimat3/jobs';
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Where the vendor sends events, and the two headers it signs with. ASSUMED, so check your
|
|
29
|
+
* vendor's docs: the mac is hex HMAC-SHA256 over \`<unix seconds>.<raw body>\` (Stripe's \`v1\`
|
|
30
|
+
* canonical form) behind \`sha256=\`, the seconds in their own header. A vendor that signs another
|
|
31
|
+
* shape changes \`signedBytes\` and these names — never drops the timestamp: without it a
|
|
32
|
+
* captured delivery verifies forever.
|
|
33
|
+
*/
|
|
34
|
+
export const ${c}_PATH = '/hooks/${name.kebab}';
|
|
35
|
+
export const ${c}_SIGNATURE_HEADER = 'x-signature';
|
|
36
|
+
export const ${c}_TIMESTAMP_HEADER = 'x-signature-timestamp';
|
|
37
|
+
/** The replay bound, both ways: five minutes is the window senders in the wild already assume. */
|
|
38
|
+
export const ${c}_TOLERANCE_MS = 300_000;
|
|
39
|
+
|
|
40
|
+
/** The part of the vendor's payload this app reads. The app's schema, never the framework's. */
|
|
41
|
+
const ${name.pascal}Event = t.object({ id: t.string, type: t.string });
|
|
42
|
+
|
|
43
|
+
/** The body verified and is not the event: the vendor sent it, so a retry sends it again. */
|
|
44
|
+
export const ${name.pascal}Unreadable = defineError<string>({
|
|
45
|
+
code: 'X_${c}_UNREADABLE',
|
|
46
|
+
title: 'a verified ${name.kebab} event is not the shape this app reads',
|
|
47
|
+
status: 400,
|
|
48
|
+
cause: (reason) => \`the ${name.kebab} event verified and \${reason}\`,
|
|
49
|
+
fix: 'x jobs list --name ${name.kebab} --json — then compare the vendor payload with ${name.pascal}Event in ${path}',
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Authentic and old: a replay, or a sender clock far off. Checked AFTER the mac, so this code
|
|
54
|
+
* means "signed by the vendor" and never "unreadable": the queue dedupes only while a job is live.
|
|
55
|
+
*/
|
|
56
|
+
export const ${name.pascal}Stale = defineError<string>({
|
|
57
|
+
code: 'X_${c}_STALE',
|
|
58
|
+
title: 'a signed ${name.kebab} delivery is outside the replay window',
|
|
59
|
+
status: 401,
|
|
60
|
+
cause: (reason) => \`the ${name.kebab} delivery is signed and \${reason}\`,
|
|
61
|
+
fix: 'const ${c}_TOLERANCE_MS = 600_000; // in ${path}, only if the vendor queues deliveries longer than five minutes — an older one is a replay and stays refused',
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Comma-separated, so a rotation keeps the old secret live beside the new one. Unset is \`['']\`,
|
|
66
|
+
* which \`verifyBodyHmac\` refuses as X_CONFIG_INVALID — never a mac under an empty key.
|
|
67
|
+
*/
|
|
68
|
+
const SECRET_ENV = '${c}_WEBHOOK_SECRET';
|
|
69
|
+
const secrets = (): readonly string[] => (Bun.env[SECRET_ENV] ?? '').split(',');
|
|
70
|
+
|
|
71
|
+
/** \`<stamp>.\` then the body, as bytes: the body is never decoded before the mac is taken. */
|
|
72
|
+
function signedBytes(stamp: string, body: Uint8Array): Uint8Array {
|
|
73
|
+
const head = new TextEncoder().encode(\`\${stamp}.\`);
|
|
74
|
+
const bytes = new Uint8Array(head.length + body.length);
|
|
75
|
+
bytes.set(head);
|
|
76
|
+
bytes.set(body, head.length);
|
|
77
|
+
return bytes;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The signed seconds against this clock. A stamp that is not seconds is no window at all. */
|
|
81
|
+
function assertFresh(stamp: string): void {
|
|
82
|
+
if (!/^\\d{1,12}$/.test(stamp)) {
|
|
83
|
+
throw new ${name.pascal}Stale('carries no unix-seconds timestamp');
|
|
84
|
+
}
|
|
85
|
+
const skewMs = Math.abs(ambientClock().now().getTime() - Number(stamp) * 1_000);
|
|
86
|
+
if (skewMs > ${c}_TOLERANCE_MS) {
|
|
87
|
+
const reason = \`was signed \${skewMs}ms from this clock, beyond \${${c}_TOLERANCE_MS}ms\`;
|
|
88
|
+
throw new ${name.pascal}Stale(reason);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* The verified text as the event. \`JSON.parse\`'s own message quotes the token it stopped at,
|
|
94
|
+
* which is a piece of the body, so it is replaced whole by a code that names none of it.
|
|
95
|
+
*/
|
|
96
|
+
function readEvent(text: string | null) {
|
|
97
|
+
let value: unknown;
|
|
98
|
+
try {
|
|
99
|
+
value = JSON.parse(text ?? '');
|
|
100
|
+
} catch {
|
|
101
|
+
throw new ${name.pascal}Unreadable('is not JSON');
|
|
102
|
+
}
|
|
103
|
+
try {
|
|
104
|
+
return ${name.pascal}Event.parse(value, '${name.kebab} event');
|
|
105
|
+
} catch {
|
|
106
|
+
throw new ${name.pascal}Unreadable('does not carry a string id and type');
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export const ${name.camel} = webhookReceiver({
|
|
111
|
+
// Pinned: the queue keys its rows by this name, and the route is \`webhook.${name.kebab}\`.
|
|
112
|
+
name: '${name.kebab}',
|
|
113
|
+
path: ${c}_PATH,
|
|
114
|
+
// The vendor's account is the app's, not an org's. A per-org receiver reads the org out of the
|
|
115
|
+
// verified event instead: \`tenant: (event) => event.orgId\`.
|
|
116
|
+
tenant: 'none',
|
|
117
|
+
verify: (inbound) => {
|
|
118
|
+
const stamp = inbound.headers.get(${c}_TIMESTAMP_HEADER) ?? '';
|
|
119
|
+
const { text } = verifyBodyHmac({
|
|
120
|
+
bytes: signedBytes(stamp, inbound.bytes),
|
|
121
|
+
secret: secrets(),
|
|
122
|
+
given: inbound.headers.get(${c}_SIGNATURE_HEADER),
|
|
123
|
+
encoding: 'hex',
|
|
124
|
+
prefix: 'sha256=',
|
|
125
|
+
});
|
|
126
|
+
assertFresh(stamp);
|
|
127
|
+
const event = readEvent(text === null ? null : text.slice(stamp.length + 1));
|
|
128
|
+
return { eventId: event.id, topic: event.type, payload: event };
|
|
129
|
+
},
|
|
130
|
+
// At least once per event id: a redelivery inside the window after this settles runs again, so a
|
|
131
|
+
// write here is an upsert keyed by \`eventId\`, never an insert.
|
|
132
|
+
handle: async ({ eventId, payload }) => ({ eventId, type: payload.type }),
|
|
133
|
+
retry: { attempts: 5, backoff: 'exponential' },
|
|
134
|
+
});
|
|
135
|
+
`;
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
const unitSuite = (name: NameSet): string => {
|
|
139
|
+
const c = constant(name);
|
|
140
|
+
return `// ${name.camel}, unit: the vendor's bytes through the real pipeline on the in-memory queue. What
|
|
141
|
+
// is worth failing on is this app's half — the secret, the replay window, the event read out of
|
|
142
|
+
// the SIGNED body and the code that replaces a parser message — never the framework's route.
|
|
143
|
+
|
|
144
|
+
import { ambientClock, hmac } from '@ultimat3/core';
|
|
145
|
+
import { defineHttpConfig, httpPipeline, httpRouter } from '@ultimat3/http';
|
|
146
|
+
import { expect, unitTest } from '@ultimat3/testing';
|
|
147
|
+
import {
|
|
148
|
+
${c}_PATH,
|
|
149
|
+
${c}_SIGNATURE_HEADER,
|
|
150
|
+
${c}_TIMESTAMP_HEADER,
|
|
151
|
+
${c}_TOLERANCE_MS,
|
|
152
|
+
${name.camel},
|
|
153
|
+
} from './${name.kebab}';
|
|
154
|
+
|
|
155
|
+
const SECRET = 'whsec_${name.snake}_unit';
|
|
156
|
+
const SECRET_ENV = '${c}_WEBHOOK_SECRET';
|
|
157
|
+
|
|
158
|
+
/** The secret this run verifies under, put back after: the environment is process-global. */
|
|
159
|
+
const withSecret = async (secret: string, run: () => Promise<void>): Promise<void> => {
|
|
160
|
+
const before = Bun.env[SECRET_ENV];
|
|
161
|
+
Bun.env[SECRET_ENV] = secret;
|
|
162
|
+
try {
|
|
163
|
+
await run();
|
|
164
|
+
} finally {
|
|
165
|
+
if (before === undefined) delete Bun.env[SECRET_ENV];
|
|
166
|
+
else Bun.env[SECRET_ENV] = before;
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
/** Unix seconds on the clock the receiver reads, \`agoMs\` in the past. */
|
|
171
|
+
const stampAgo = (agoMs = 0): string =>
|
|
172
|
+
String(Math.floor((ambientClock().now().getTime() - agoMs) / 1_000));
|
|
173
|
+
|
|
174
|
+
/** What the vendor sends: a mac over \`<timestamp>.<body>\`, so the time is signed too. */
|
|
175
|
+
const sign = (body: string, stamp: string, secret = SECRET): string =>
|
|
176
|
+
\`sha256=\${hmac('sha256', secret, \`\${stamp}.\${body}\`, 'hex')}\`;
|
|
177
|
+
|
|
178
|
+
const deliver = (body: string, signature: string, stamp: string): Promise<Response> =>
|
|
179
|
+
httpPipeline({
|
|
180
|
+
table: httpRouter(${name.camel}.routes()),
|
|
181
|
+
config: defineHttpConfig({ rateLimit: { scope: 'process' }, dev: false }),
|
|
182
|
+
}).handle(
|
|
183
|
+
new Request(\`http://localhost\${${c}_PATH}\`, {
|
|
184
|
+
method: 'POST',
|
|
185
|
+
headers: {
|
|
186
|
+
[${c}_SIGNATURE_HEADER]: signature,
|
|
187
|
+
[${c}_TIMESTAMP_HEADER]: stamp,
|
|
188
|
+
},
|
|
189
|
+
body,
|
|
190
|
+
}),
|
|
191
|
+
{ role: 'web' },
|
|
192
|
+
);
|
|
193
|
+
|
|
194
|
+
unitTest('a signed event is queued, then handled from its verified payload', ({ runJobs }) =>
|
|
195
|
+
withSecret(SECRET, async () => {
|
|
196
|
+
const body = '{"id":"evt_unit","type":"thing.happened"}';
|
|
197
|
+
const stamp = stampAgo();
|
|
198
|
+
const response = await deliver(body, sign(body, stamp), stamp);
|
|
199
|
+
expect(await response.json()).toEqual({ ok: true, eventId: 'evt_unit', deduped: false });
|
|
200
|
+
const trace = await runJobs.drain();
|
|
201
|
+
expect(trace.executions.map((run) => [run.outcome, run.result])).toEqual([
|
|
202
|
+
['completed', { eventId: 'evt_unit', type: 'thing.happened' }],
|
|
203
|
+
]);
|
|
204
|
+
}),
|
|
205
|
+
);
|
|
206
|
+
|
|
207
|
+
unitTest('a body signed under another secret is refused, and nothing is queued', ({ runJobs }) =>
|
|
208
|
+
withSecret(SECRET, async () => {
|
|
209
|
+
const body = '{"id":"evt_forged","type":"thing.happened"}';
|
|
210
|
+
const stamp = stampAgo();
|
|
211
|
+
const response = await deliver(body, sign(body, stamp, 'whsec_someone_else'), stamp);
|
|
212
|
+
expect((await response.json()).code).toBe('X_WEBHOOK_SIGNATURE_INVALID');
|
|
213
|
+
expect(await runJobs.depth(${name.camel})).toBe(0);
|
|
214
|
+
}),
|
|
215
|
+
);
|
|
216
|
+
|
|
217
|
+
unitTest('a delivery replayed after the window is refused, and nothing is queued', ({ runJobs }) =>
|
|
218
|
+
withSecret(SECRET, async () => {
|
|
219
|
+
const body = '{"id":"evt_replayed","type":"thing.happened"}';
|
|
220
|
+
const old = stampAgo(${c}_TOLERANCE_MS + 60_000);
|
|
221
|
+
const replayed = await deliver(body, sign(body, old), old);
|
|
222
|
+
expect(replayed.status).toBe(401);
|
|
223
|
+
expect((await replayed.json()).code).toBe('X_${c}_STALE');
|
|
224
|
+
// The same signature under a fresh timestamp: the time is inside the mac, so it is a forgery.
|
|
225
|
+
const restamped = await deliver(body, sign(body, old), stampAgo());
|
|
226
|
+
expect((await restamped.json()).code).toBe('X_WEBHOOK_SIGNATURE_INVALID');
|
|
227
|
+
expect(await runJobs.depth(${name.camel})).toBe(0);
|
|
228
|
+
}),
|
|
229
|
+
);
|
|
230
|
+
|
|
231
|
+
unitTest('a signed body that is not the event is refused with this app code', ({ runJobs }) =>
|
|
232
|
+
withSecret(SECRET, async () => {
|
|
233
|
+
const body = '{"id":"evt_short"}';
|
|
234
|
+
const stamp = stampAgo();
|
|
235
|
+
const response = await deliver(body, sign(body, stamp), stamp);
|
|
236
|
+
expect(response.status).toBe(400);
|
|
237
|
+
expect((await response.json()).code).toBe('X_${c}_UNREADABLE');
|
|
238
|
+
expect(await runJobs.depth(${name.camel})).toBe(0);
|
|
239
|
+
}),
|
|
240
|
+
);
|
|
241
|
+
`;
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* The job's entry in `apps/web/exercise.ts`. A draw cannot sign a vendor's event and `payload` is
|
|
246
|
+
* free JSON the handler trusts as verified, so `x exercise` queues what the route would have.
|
|
247
|
+
*/
|
|
248
|
+
const exerciseEntry = (name: NameSet): ExerciseEntry => ({
|
|
249
|
+
name: name.kebab,
|
|
250
|
+
value: [
|
|
251
|
+
'{',
|
|
252
|
+
' actor: null,',
|
|
253
|
+
' // What the verified route queues: the event read out of the signed body.',
|
|
254
|
+
' input: () => ({',
|
|
255
|
+
" eventId: 'evt_exercise',",
|
|
256
|
+
" topic: 'thing.happened',",
|
|
257
|
+
" payload: { id: 'evt_exercise', type: 'thing.happened' },",
|
|
258
|
+
' }),',
|
|
259
|
+
'}',
|
|
260
|
+
].join('\n'),
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
/** The receiver and its unit test, in the feature's `jobs/`. */
|
|
264
|
+
export function webhookReceiverFiles(
|
|
265
|
+
rawName: string,
|
|
266
|
+
target: FeatureTarget,
|
|
267
|
+
): readonly GeneratedFile[] {
|
|
268
|
+
const name = names(rawName);
|
|
269
|
+
const path = `${target.surfaceDir}/${target.feature}/jobs/${name.kebab}.ts`;
|
|
270
|
+
return [
|
|
271
|
+
{ path, contents: source(name, path), exercise: exerciseEntry(name) },
|
|
272
|
+
{ path: path.replace(/\.ts$/, '.test.ts'), contents: unitSuite(name) },
|
|
273
|
+
];
|
|
274
|
+
}
|
|
@@ -1,15 +1,10 @@
|
|
|
1
|
-
// The CI half of what `x new` writes: the gate workflow
|
|
2
|
-
// the image workflow (`image.yml.ts`)
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
// life with a gate that ran on exactly one machine — the author's. The two commands are
|
|
6
|
-
// `bun run setup` and `bun run verify` and NOT a restatement of their steps: a workflow that spelled
|
|
7
|
-
// out `bun install`, `x db migrate` and `x verify`'s steps is a second definition of the gate,
|
|
8
|
-
// free to drift from the scripts a human runs, and axiom 1 has one way to do each thing.
|
|
9
|
-
// `bun run verify` is `x verify` alone: its `budgets` step builds when the stats are missing or
|
|
10
|
-
// older than the source (plan 101, 21), so no build step runs before it.
|
|
1
|
+
// The CI half of what `x new` writes: the gate workflow, cut into parallel parts by
|
|
2
|
+
// `x verify plan` and folded back by `x verify merge`, and the image workflow (`image.yml.ts`)
|
|
3
|
+
// that publishes only what that gate passed. Every command it runs is one of the app's own scripts
|
|
4
|
+
// — `bun run setup`, `bun run verify …` — never a restatement of the gate's steps (axiom 1).
|
|
11
5
|
|
|
12
6
|
import { REQUIRED_BUN } from '../../app-root';
|
|
7
|
+
import { DEFAULT_PLAN_PARTS } from '../../verify-plan';
|
|
13
8
|
import type { GeneratedFile, NameSet } from '../naming';
|
|
14
9
|
import { TEST_COMPOSE_PATH, TEST_ENV_PATH } from '../scaffold-test-services';
|
|
15
10
|
import { DEPENDABOT_PATH, dependabot } from './dependabot.yml';
|
|
@@ -30,15 +25,37 @@ const CI_WORKFLOW_NAME = 'ci';
|
|
|
30
25
|
*/
|
|
31
26
|
const SETUP_BUN = 'oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0';
|
|
32
27
|
|
|
28
|
+
/** The plan job's one command: the app's `verify` script, so the CLI it asks is the one installed. */
|
|
29
|
+
export const PLAN_COMMAND = `bun run verify plan --parts ${String(DEFAULT_PLAN_PARTS)} --json`;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Every job's first three steps: the tree, the Bun floor, the install cache. `bun-version` is
|
|
33
|
+
* `package.json`'s `engines.bun` floor exactly — the OLDEST runtime the app declares, so a call
|
|
34
|
+
* that needs a newer Bun fails here rather than in the install of whoever took the app at its
|
|
35
|
+
* word; never `latest`, a runtime change nobody chose. The cache is keyed on the lockfile.
|
|
36
|
+
*/
|
|
37
|
+
const SETUP_STEPS = ` - uses: actions/checkout@v7
|
|
38
|
+
- uses: ${SETUP_BUN}
|
|
39
|
+
with:
|
|
40
|
+
# engines.bun in package.json, exactly: the oldest Bun this app says it runs on.
|
|
41
|
+
bun-version: '${REQUIRED_BUN}'
|
|
42
|
+
- uses: actions/cache@v6
|
|
43
|
+
with:
|
|
44
|
+
path: ~/.bun/install/cache
|
|
45
|
+
key: bun-\${{ runner.os }}-\${{ hashFiles('bun.lock') }}
|
|
46
|
+
restore-keys: bun-\${{ runner.os }}-`;
|
|
47
|
+
|
|
33
48
|
const ci = (app: NameSet): string => `name: ${CI_WORKFLOW_NAME}
|
|
34
49
|
|
|
35
|
-
# The gate for ${app.kebab}: the
|
|
36
|
-
#
|
|
37
|
-
#
|
|
50
|
+
# The gate for ${app.kebab}: \`bun run setup\` and \`bun run verify\`, the two commands \`README.md\`
|
|
51
|
+
# tells a human to run, on machines that have never seen this repository — the gate cut into
|
|
52
|
+
# parts that run side by side. \`x verify plan\` names the parts, each runs \`x verify --only\` on its
|
|
53
|
+
# slice, and \`x verify merge\` is the verdict: green only when the parts were the whole gate. A
|
|
54
|
+
# check that exists only in CI is one nobody can reproduce locally; each part reproduces with its
|
|
55
|
+
# own flags, and \`bun run verify\` alone is the same gate on one machine.
|
|
38
56
|
#
|
|
39
|
-
#
|
|
40
|
-
#
|
|
41
|
-
# which on a fresh runner it always is, so no build step comes first.
|
|
57
|
+
# No build step comes first: the \`budgets\` step runs \`x build --target static\` itself when
|
|
58
|
+
# \`.x/build-stats.json\` is missing or older than the source, as on every fresh runner.
|
|
42
59
|
#
|
|
43
60
|
# \`bun run setup\` brings up embedded Postgres in-process; the TEST services come from
|
|
44
61
|
# \`docker/docker-compose.test.yml\` — Postgres 18, Redis, NATS and S3 in RAM, durability and logs
|
|
@@ -63,38 +80,86 @@ permissions:
|
|
|
63
80
|
contents: read
|
|
64
81
|
|
|
65
82
|
jobs:
|
|
66
|
-
|
|
83
|
+
# The plan: \`x verify plan\` cuts the gate into runners, and the matrix below is its answer read
|
|
84
|
+
# by \`fromJSON\` — never a list of steps typed here, which a new gate step would silently miss.
|
|
85
|
+
plan:
|
|
67
86
|
# A branch in THIS repository with an open pull request fires both events for one commit, and
|
|
68
87
|
# the push run already gates that exact tree — so the pull_request run is skipped, not paid for
|
|
69
88
|
# twice. A pull request from a FORK fires no push here, and it still runs.
|
|
70
89
|
if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name != github.repository
|
|
71
90
|
# A free GitHub-hosted runner unless the repository variable \`CI_RUNNER\` names another label.
|
|
72
91
|
runs-on: ${RUNS_ON}
|
|
92
|
+
timeout-minutes: 5
|
|
93
|
+
outputs:
|
|
94
|
+
matrix: \${{ steps.plan.outputs.matrix }}
|
|
95
|
+
steps:
|
|
96
|
+
${SETUP_STEPS}
|
|
97
|
+
- run: bun install
|
|
98
|
+
- id: plan
|
|
99
|
+
run: echo "matrix=$(${PLAN_COMMAND} | jq -c '.data.matrix')" >> "$GITHUB_OUTPUT"
|
|
100
|
+
|
|
101
|
+
# One part of the gate per runner: \`x verify --only <steps> [--shard i/n]\`, its document kept.
|
|
102
|
+
gate:
|
|
103
|
+
name: gate (\${{ matrix.part }})
|
|
104
|
+
needs: plan
|
|
105
|
+
runs-on: ${RUNS_ON}
|
|
73
106
|
# A bound on a HANG, not on cost: a step that never returns holds a runner until GitHub's
|
|
74
107
|
# six-hour default expires, and the failure is invisible for all six of them.
|
|
75
108
|
timeout-minutes: 20
|
|
109
|
+
strategy:
|
|
110
|
+
# Every part runs to its end: the verdict below needs each one's document, red or green.
|
|
111
|
+
fail-fast: false
|
|
112
|
+
matrix: \${{ fromJSON(needs.plan.outputs.matrix) }}
|
|
76
113
|
steps:
|
|
77
|
-
|
|
78
|
-
- uses: ${SETUP_BUN}
|
|
79
|
-
with:
|
|
80
|
-
# \`package.json\`'s \`engines.bun\` floor, exactly — the OLDEST runtime this app declares
|
|
81
|
-
# it supports, so a call that needs a newer Bun fails here rather than in the install of
|
|
82
|
-
# whoever took the app at its word. Never \`latest\`: a Bun minor landing unannounced is a
|
|
83
|
-
# runtime change nobody chose.
|
|
84
|
-
bun-version: '${REQUIRED_BUN}'
|
|
85
|
-
# Bun's download cache, keyed on the lockfile: \`bun run setup\`'s install then links from
|
|
86
|
-
# disk instead of fetching every package again on every run.
|
|
87
|
-
- uses: actions/cache@v6
|
|
88
|
-
with:
|
|
89
|
-
path: ~/.bun/install/cache
|
|
90
|
-
key: bun-\${{ runner.os }}-\${{ hashFiles('bun.lock') }}
|
|
91
|
-
restore-keys: bun-\${{ runner.os }}-
|
|
114
|
+
${SETUP_STEPS}
|
|
92
115
|
# Two steps rather than one \`&&\`, so the log names which half failed and times each.
|
|
93
116
|
- run: bun run setup
|
|
94
|
-
#
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
-
|
|
117
|
+
# What the part's \`needs\` asks for and no more: \`--wait\` returns once every healthcheck
|
|
118
|
+
# passes, and only the URLs of what was started reach the suites — a URL to a server that is
|
|
119
|
+
# not running is a red suite, where an absent one is a suite that skips.
|
|
120
|
+
- if: matrix.needs == 'database'
|
|
121
|
+
run: |
|
|
122
|
+
docker compose -f ${TEST_COMPOSE_PATH} up -d --wait postgres
|
|
123
|
+
grep '^TEST_DATABASE_URL=' ${TEST_ENV_PATH} >> "$GITHUB_ENV"
|
|
124
|
+
- if: matrix.needs == 'services'
|
|
125
|
+
run: |
|
|
126
|
+
docker compose -f ${TEST_COMPOSE_PATH} up -d --wait
|
|
127
|
+
cat ${TEST_ENV_PATH} >> "$GITHUB_ENV"
|
|
128
|
+
# Under $RUNNER_TEMP, never in the checkout, where \`lint\` would walk the open file.
|
|
129
|
+
- env:
|
|
130
|
+
PART: \${{ matrix.part }}
|
|
131
|
+
ONLY: \${{ matrix.only }}
|
|
132
|
+
SHARD: \${{ matrix.shard }}
|
|
133
|
+
run: |
|
|
134
|
+
mkdir -p "$RUNNER_TEMP/parts"
|
|
135
|
+
bun run verify --only "$ONLY" \${SHARD:+--shard "$SHARD"} --json > "$RUNNER_TEMP/parts/$PART.json"
|
|
136
|
+
# Uploaded when the part is RED too: a part with no document reads, in the merge, as a step
|
|
137
|
+
# nobody ran. \`overwrite\`, so a re-run's document replaces the attempt it re-ran.
|
|
138
|
+
- uses: actions/upload-artifact@v7
|
|
139
|
+
if: \${{ !cancelled() }}
|
|
140
|
+
with:
|
|
141
|
+
name: verify-part-\${{ matrix.part }}
|
|
142
|
+
path: \${{ runner.temp }}/parts/\${{ matrix.part }}.json
|
|
143
|
+
if-no-files-found: error
|
|
144
|
+
overwrite: true
|
|
145
|
+
|
|
146
|
+
# THE VERDICT: \`x verify merge\` is green only when the parts are provably the whole gate — every
|
|
147
|
+
# step from exactly one part, every shard of a split over one corpus, each part green. It runs
|
|
148
|
+
# when a part is red (\`!cancelled()\`), because a skipped verdict reads as no verdict.
|
|
149
|
+
verify:
|
|
150
|
+
needs: [plan, gate]
|
|
151
|
+
if: \${{ !cancelled() && needs.plan.result == 'success' }}
|
|
152
|
+
runs-on: ${RUNS_ON}
|
|
153
|
+
timeout-minutes: 5
|
|
154
|
+
steps:
|
|
155
|
+
${SETUP_STEPS}
|
|
156
|
+
- run: bun install
|
|
157
|
+
- uses: actions/download-artifact@v8
|
|
158
|
+
with:
|
|
159
|
+
pattern: verify-part-*
|
|
160
|
+
path: \${{ runner.temp }}/parts
|
|
161
|
+
merge-multiple: true
|
|
162
|
+
- run: bun run verify merge "$RUNNER_TEMP"/parts/*.json
|
|
98
163
|
`;
|
|
99
164
|
|
|
100
165
|
/** The CI a new app is born with, in reading order: the gate, the image, the dependency updates. */
|