@ultimat3/cli 31.16.0 → 31.18.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.
Files changed (77) hide show
  1. package/README.md +11 -2
  2. package/package.json +29 -29
  3. package/src/cache-graph.ts +67 -0
  4. package/src/cmd-cache-spec.ts +25 -0
  5. package/src/cmd-cache.ts +187 -0
  6. package/src/cmd-config-spec.ts +23 -0
  7. package/src/cmd-config.ts +61 -0
  8. package/src/cmd-doctor.ts +3 -3
  9. package/src/cmd-exercise.ts +34 -10
  10. package/src/cmd-explain-spec.ts +24 -0
  11. package/src/cmd-explain.ts +201 -0
  12. package/src/cmd-generate-spec.ts +3 -3
  13. package/src/cmd-generate.ts +2 -2
  14. package/src/cmd-logs-spec.ts +34 -0
  15. package/src/cmd-logs.ts +80 -0
  16. package/src/cmd-planned.ts +15 -29
  17. package/src/cmd-token-spec.ts +54 -0
  18. package/src/cmd-token.ts +173 -0
  19. package/src/cmd-verify-spec.ts +13 -3
  20. package/src/cmd-verify.ts +2 -0
  21. package/src/config-redact.ts +39 -0
  22. package/src/dev-boot-data-dir.ts +69 -0
  23. package/src/dev-boot.ts +26 -13
  24. package/src/doctor-chart-alerts.ts +50 -22
  25. package/src/error-codes-tooling.ts +6 -4
  26. package/src/error-codes.ts +2 -0
  27. package/src/errors.ts +8 -2
  28. package/src/exercise-entry-edit.ts +5 -1
  29. package/src/exercise-routes.ts +59 -0
  30. package/src/explain-capture.ts +38 -0
  31. package/src/generate-chart-alerts.ts +99 -45
  32. package/src/generate-exercise.ts +2 -2
  33. package/src/generate-factories.ts +133 -0
  34. package/src/generate-files.ts +15 -0
  35. package/src/generate-kinds.ts +15 -0
  36. package/src/mcp-db-target.ts +4 -3
  37. package/src/mcp-errors.ts +4 -0
  38. package/src/messages-gate.ts +2 -0
  39. package/src/messages-ops.ts +32 -0
  40. package/src/messages-upgrade.ts +1 -0
  41. package/src/messages.ts +4 -0
  42. package/src/otlp-export.ts +16 -2
  43. package/src/registry.ts +10 -0
  44. package/src/role-start.ts +11 -5
  45. package/src/runtime-services.ts +35 -19
  46. package/src/serve-boot-phases.ts +30 -0
  47. package/src/serve-boot-warnings.ts +62 -0
  48. package/src/serve-boot.ts +30 -11
  49. package/src/templates/chart-dashboard.ts +245 -0
  50. package/src/templates/generate-cron-job.ts +90 -0
  51. package/src/templates/generate-purge.ts +93 -0
  52. package/src/templates/generate-webhook-receiver.ts +274 -0
  53. package/src/templates/github/ci.yml.ts +101 -36
  54. package/src/templates/guard-repo-raw-sql-test.ts +174 -0
  55. package/src/templates/guard-repo-raw-sql.ts +115 -145
  56. package/src/templates/guard-unbounded-fanout.ts +170 -0
  57. package/src/templates/scaffold-claude-commands.ts +3 -2
  58. package/src/templates/scaffold-docs.ts +3 -2
  59. package/src/templates/scaffold-guards.ts +3 -0
  60. package/src/templates/scaffold-helm-alert-rules.ts +160 -0
  61. package/src/templates/scaffold-helm-alerts.ts +22 -87
  62. package/src/templates/scaffold-helm-templates.ts +2 -0
  63. package/src/templates/scaffold-helm.ts +20 -4
  64. package/src/upgrade-gate.ts +18 -6
  65. package/src/upgrade-report.ts +4 -0
  66. package/src/verify-plan.ts +127 -0
  67. package/wiki/Admin-Dashboard.md +6 -2
  68. package/wiki/CI-Parallel-Gate.md +38 -1
  69. package/wiki/CLI-Reference.md +95 -14
  70. package/wiki/Caching-And-Invalidation.md +10 -10
  71. package/wiki/Configuration.md +4 -2
  72. package/wiki/Known-Gaps.md +1 -1
  73. package/wiki/MCP-And-AI.md +1 -1
  74. package/wiki/Observability.md +6 -1
  75. package/wiki/Testing.md +64 -0
  76. package/wiki/Troubleshooting.md +3 -2
  77. package/wiki/Upgrading.md +10 -0
package/src/registry.ts CHANGED
@@ -9,9 +9,11 @@
9
9
  import { affectedSpec } from './cmd-affected-spec';
10
10
  import { authSpec } from './cmd-auth-spec';
11
11
  import { buildSpec } from './cmd-build-spec';
12
+ import { cacheSpec } from './cmd-cache-spec';
12
13
  import { ciSpec } from './cmd-ci-spec';
13
14
  import { cleanSpec } from './cmd-clean-spec';
14
15
  import { clientSpec } from './cmd-client-spec';
16
+ import { configSpec } from './cmd-config-spec';
15
17
  import { dbSpec } from './cmd-db-spec';
16
18
  import { deploySpec } from './cmd-deploy-spec';
17
19
  import { devSpec } from './cmd-dev-spec';
@@ -21,6 +23,7 @@ import { drillSpec } from './cmd-drill-spec';
21
23
  import { envSpec } from './cmd-env-spec';
22
24
  import { errorsSpec } from './cmd-errors-spec';
23
25
  import { exerciseSpec } from './cmd-exercise-spec';
26
+ import { explainSpec } from './cmd-explain-spec';
24
27
  import { fixSpec } from './cmd-fix-spec';
25
28
  import { generateSpec } from './cmd-generate-spec';
26
29
  import { graphSpec } from './cmd-graph-spec';
@@ -31,6 +34,7 @@ import { createHelpCommand, createVersionCommand } from './cmd-help';
31
34
  import { i18nSpec } from './cmd-i18n-spec';
32
35
  import { impactSpec } from './cmd-impact-spec';
33
36
  import { jobsSpec } from './cmd-jobs-spec';
37
+ import { logsSpec } from './cmd-logs-spec';
34
38
  import { mailSpec } from './cmd-mail-spec';
35
39
  import { manifestSpec } from './cmd-manifest-spec';
36
40
  import { mcpSpec } from './cmd-mcp-spec';
@@ -46,6 +50,7 @@ import { shotSpec } from './cmd-shot-spec';
46
50
  import { stopSpec } from './cmd-stop-spec';
47
51
  import { tasksSpec } from './cmd-tasks-spec';
48
52
  import { testSpec } from './cmd-test-spec';
53
+ import { tokenSpec } from './cmd-token-spec';
49
54
  import { upgradeSpec } from './cmd-upgrade-spec';
50
55
  import { vapidSpec } from './cmd-vapid-spec';
51
56
  import { verifySpec } from './cmd-verify-spec';
@@ -125,6 +130,11 @@ export const LAZY_COMMANDS: readonly LazyCommand[] = [
125
130
  lazy(clientSpec, async () => (await import('./cmd-client')).clientCommand),
126
131
  lazy(graphSpec, async () => (await import('./cmd-graph')).graphCommand),
127
132
  lazy(impactSpec, async () => (await import('./cmd-impact')).impactCommand),
133
+ lazy(tokenSpec, async () => (await import('./cmd-token')).tokenCommand),
134
+ lazy(configSpec, async () => (await import('./cmd-config')).configCommand),
135
+ lazy(logsSpec, async () => (await import('./cmd-logs')).logsCommand),
136
+ lazy(cacheSpec, async () => (await import('./cmd-cache')).cacheCommand),
137
+ lazy(explainSpec, async () => (await import('./cmd-explain')).explainCommand),
128
138
  ];
129
139
 
130
140
  /**
package/src/role-start.ts CHANGED
@@ -50,6 +50,7 @@ import { reportUnservedQueues } from './runtime-jobs-unserved';
50
50
  import { startLiveFeed } from './runtime-live-feed';
51
51
  import { type RunningServices, releaseOrThrow } from './runtime-services';
52
52
  import { inlineScriptSources } from './script-csp';
53
+ import { bootWarningConcernsAny } from './serve-boot-warnings';
53
54
  import { inlineStyleSources } from './style-csp';
54
55
  import { syncConnectSources } from './sync-url';
55
56
  import { trustedHopsFromEnv } from './trusted-hops';
@@ -157,10 +158,7 @@ function warnIfProcessScoped(store: RateLimitStore): void {
157
158
  * runtime, which is `httpServer`'s per-process memory store and `scope: 'process'` below.
158
159
  */
159
160
  function rateLimitStoreFor(options: StartRolesOptions): RateLimitStore | undefined {
160
- const supplied = options.overrides?.rateLimitStore;
161
- if (supplied === undefined) return options.runtime.rateLimitStore;
162
- warnIfProcessScoped(supplied);
163
- return supplied;
161
+ return options.overrides?.rateLimitStore ?? options.runtime.rateLimitStore;
164
162
  }
165
163
 
166
164
  /**
@@ -174,7 +172,6 @@ function startWeb(
174
172
  devices: readonly DeviceMount[],
175
173
  mount?: WebSocketMount<SyncWs>,
176
174
  ): ServerHandle {
177
- warnIfUnauthenticatable(options.routes);
178
175
  const binding = options.http ?? DEV_BINDING;
179
176
  const hops = trustedHopsFromEnv(options.env);
180
177
  const store = rateLimitStoreFor(options);
@@ -270,6 +267,15 @@ export async function startRoles(options: StartRolesOptions): Promise<RunningRol
270
267
  (options.http ?? DEV_BINDING).dev,
271
268
  );
272
269
  assertOneJobDriver(options.runtime);
270
+ // Once per process, and only where a role in it can act on the line (`serve-boot-warnings.ts`):
271
+ // `rateLimitStoreFor` is asked twice in a web boot, and a scheduler spends no limit at all.
272
+ if (bootWarningConcernsAny('auth-unconfigured', selected)) {
273
+ warnIfUnauthenticatable(options.routes);
274
+ }
275
+ const supplied = options.overrides?.rateLimitStore;
276
+ if (supplied !== undefined && bootWarningConcernsAny('rate-limit-process-scoped', selected)) {
277
+ warnIfProcessScoped(supplied);
278
+ }
273
279
  // Roles bind sockets in order, so a role that fails to start has to release the ones before it.
274
280
  // Without this a failed `sync` leaves the web server bound and unreachable by any caller.
275
281
  const started: (() => Promise<void>)[] = [];
@@ -6,7 +6,9 @@
6
6
  import { postgresAuthLimiter, postgresTotpReplayGuard } from '@ultimat3/auth';
7
7
  import type { PurgeDriver } from '@ultimat3/cache';
8
8
  import { isNoopPurgeDriver, selectPurgeDriver } from '@ultimat3/cache';
9
+ import type { Clock } from '@ultimat3/core';
9
10
  import {
11
+ finiteCount,
10
12
  type RealtimeConfig,
11
13
  type Role,
12
14
  registerReadinessCheck,
@@ -158,35 +160,48 @@ export function cdnLabel(runtime: RunningServices): string {
158
160
  }
159
161
 
160
162
  /**
161
- * A readiness check over a dependency that can only be asked asynchronously.
162
- *
163
- * `ReadinessCheck` is synchronous and that is the mechanism, not a limitation: a probe that awaits
164
- * a network call takes as long as the dependency does, so a slow database makes `/readyz` miss its
165
- * `timeoutSeconds`, the kubelet reads that as unready, and capacity is pulled from an already
166
- * struggling system — the outage the probe existed to prevent, caused by the probe.
167
- *
168
- * So the read answers the PREVIOUS probe and schedules the next, which is the standard cached
169
- * health shape: staleness is one poll period, and the poll period is the operator's own
170
- * `periodSeconds`. Deliberately not a `setInterval`: a timer would probe a process nobody is
171
- * asking about, and in `x dev` every probe is a statement — one span, one trace id — so a
172
- * one-per-second heartbeat would evict every real request from `/_x/timeline` inside a minute.
163
+ * The fewest milliseconds between two pings. Production saw `select $1` as the most-called
164
+ * statement — 38,195 in 26 h — because every read once the last ping settled started another. One
165
+ * second is below any kubelet `periodSeconds`, so the answer a probe reads is never staler than
166
+ * the probe period it already accepted.
167
+ */
168
+ export const READINESS_PROBE_MIN_MS = 1_000;
169
+
170
+ /**
171
+ * `ReadinessCheck` is synchronous and that is the mechanism: a probe that awaits a network call
172
+ * takes as long as the dependency does, so a slow database makes `/readyz` miss its
173
+ * `timeoutSeconds`, and capacity is pulled from an already struggling system. Deliberately not a
174
+ * `setInterval`: a timer probes a process nobody is asking about, and in `x dev` every probe is a
175
+ * statement on `/_x/timeline`.
173
176
  *
174
- * It starts `true` because it is already proven: `startQueue` pinged this pool before this line
175
- * ran, and a boot that could not would have thrown instead of reaching here.
177
+ * It starts `true`, with the interval already running, because it is proven: `startQueue` pinged
178
+ * this pool before this line ran, and a boot that could not would have thrown instead.
176
179
  */
177
- function probedReadinessCheck(name: string, probe: () => Promise<unknown>): () => void {
180
+ export function probedReadinessCheck(
181
+ name: string,
182
+ probe: () => Promise<unknown>,
183
+ options: { readonly clock?: Clock; readonly minIntervalMs?: number } = {},
184
+ ): () => void {
185
+ const clock = options.clock ?? systemClock;
186
+ const minIntervalMs = finiteCount(
187
+ 'probedReadinessCheck',
188
+ 'minIntervalMs',
189
+ options.minIntervalMs ?? READINESS_PROBE_MIN_MS,
190
+ );
178
191
  let live = true;
179
192
  let inFlight = false;
193
+ let startedAt = clock.monotonic();
180
194
  const refresh = (): void => {
181
- if (inFlight) return;
195
+ if (inFlight || clock.monotonic() - startedAt < minIntervalMs) return;
182
196
  inFlight = true;
197
+ startedAt = clock.monotonic();
183
198
  void probe()
184
199
  .then(
185
200
  () => {
186
201
  live = true;
187
202
  },
188
- // Every rejection, including the coded `X_DB_UNAVAILABLE` a closed pool answers with. A
189
- // check that threw would be reported as failing anyway; catching it here keeps the reason
203
+ // Every rejection, including the coded `X_DB_UNAVAILABLE` a closed pool answers with: a
204
+ // check that threw is reported as failing anyway, and catching it here keeps the reason
190
205
  // out of the endpoint's own path, where nothing could report it.
191
206
  () => {
192
207
  live = false;
@@ -380,7 +395,8 @@ export async function startServices(
380
395
  // `packages/http/src/server.ts` calls that BEFORE `Bun.serve`, while `role-start.ts` calls it
381
396
  // before `sync`, `worker` and `scheduler` start. The chart's `readinessProbe` and the container
382
397
  // healthcheck both route on it, so a replica whose pool was gone kept taking traffic.
383
- started.push(probedReadinessCheck('database', () => db.ping()));
398
+ // At most one ping per `READINESS_PROBE_MIN_MS` on this boot's clock, however many pollers ask.
399
+ started.push(probedReadinessCheck('database', () => db.ping(), { clock }));
384
400
  // Dialled here rather than at selection: the socket is a resource the unwind below has to
385
401
  // release. AWAITED only by a process that cannot work without the bus — a `sync` node, a
386
402
  // replicator — where an unreachable one must fail the boot, not the first change nobody
@@ -0,0 +1,30 @@
1
+ // The container boot's timeline: one `boot.phase {role, name, ms}` line as each phase ends. A boot
2
+ // spent seconds between two unrelated log lines — a worker importing every page for an unstamped
3
+ // build id — and nothing said which step it was (plan 101, 14 U12).
4
+
5
+ import type { Clock, Role } from '@ultimat3/core';
6
+ import { logger, systemClock } from '@ultimat3/core';
7
+
8
+ /** The phases a serving boot runs, in order. A name not here is not a phase. */
9
+ export type BootPhase = 'services' | 'app-load' | 'app-checks' | 'build-id' | 'web' | 'roles';
10
+
11
+ export interface BootTimeline {
12
+ /** Ends `name`: logs its milliseconds since the previous phase ended, or since the start. */
13
+ phase(name: BootPhase): void;
14
+ /** Whole milliseconds since the timeline started. */
15
+ totalMs(): number;
16
+ }
17
+
18
+ /** Starts the clock. The process's own clock by default; a test hands a frozen one. */
19
+ export function bootTimeline(role: Role, clock: Clock = systemClock): BootTimeline {
20
+ const started = clock.monotonic();
21
+ let last = started;
22
+ return {
23
+ phase(name) {
24
+ const now = clock.monotonic();
25
+ logger.info('boot.phase', { role, name, ms: Math.round(now - last) });
26
+ last = now;
27
+ },
28
+ totalMs: () => Math.round(clock.monotonic() - started),
29
+ };
30
+ }
@@ -0,0 +1,62 @@
1
+ // The roles each boot warning concerns, in one table, and the step that runs the post-load ones for
2
+ // the booting role alone. Production logged the same warnings in all five roles on every boot — a
3
+ // warning a role cannot act on is noise that buries the one it can.
4
+
5
+ import type { Role } from '@ultimat3/core';
6
+
7
+ /** Every warning a container boot can say. A new one does not compile until it names its roles. */
8
+ export type BootWarning =
9
+ | 'idempotency-process-scoped'
10
+ | 'mfa-secret-unsealed'
11
+ | 'build-id-unstamped'
12
+ | 'auth-unconfigured'
13
+ | 'rate-limit-process-scoped';
14
+
15
+ const DECLARED: Readonly<Record<BootWarning, readonly Role[]>> = {
16
+ // An `Idempotency-Key` arrives on an HTTP request or an MCP call, both the web role's: a job
17
+ // invokes its action on the `job` surface with no key, and `sync` relays frames, not writes.
18
+ 'idempotency-process-scoped': ['web'],
19
+ // The second factor is asked for where a user signs in.
20
+ 'mfa-secret-unsealed': ['web'],
21
+ // Only a background load leaves pages out, so only it pays to import them for the build id.
22
+ 'build-id-unstamped': ['worker', 'scheduler'],
23
+ // Guarded routes are served by the web role alone; every other role is handed none.
24
+ 'auth-unconfigured': ['web'],
25
+ // A declared `rateLimit:` is spent wherever a primitive runs: HTTP and MCP on web, `.job()` on a
26
+ // worker, a live query's reads on sync. The scheduler only enqueues; the replicator invokes none.
27
+ 'rate-limit-process-scoped': ['web', 'worker', 'sync'],
28
+ };
29
+
30
+ /** A `Map`, so a lookup is an own-key read — never a member of `Object.prototype`. */
31
+ export const BOOT_WARNINGS: ReadonlyMap<BootWarning, readonly Role[]> = new Map(
32
+ Object.entries(DECLARED) as [BootWarning, readonly Role[]][],
33
+ );
34
+
35
+ /** Whether `warning` is one `role` can act on. An unknown warning concerns nobody. */
36
+ export const bootWarningConcerns = (warning: BootWarning, role: Role): boolean =>
37
+ BOOT_WARNINGS.get(warning)?.includes(role) ?? false;
38
+
39
+ /** Whether any of `roles` — `x dev` runs several in one process — can act on `warning`. */
40
+ export const bootWarningConcernsAny = (warning: BootWarning, roles: readonly Role[]): boolean =>
41
+ roles.some((role) => bootWarningConcerns(warning, role));
42
+
43
+ /** The post-load probes: each logs its own line and answers whether it had anything to say. */
44
+ export interface BootWarningProbes {
45
+ readonly idempotency: () => boolean;
46
+ readonly mfa: () => Promise<number>;
47
+ }
48
+
49
+ /** Runs the probes `role` is concerned by, in table order; answers the warnings actually said. */
50
+ export async function warnAtBoot(
51
+ role: Role,
52
+ probes: BootWarningProbes,
53
+ ): Promise<readonly BootWarning[]> {
54
+ const said: BootWarning[] = [];
55
+ if (bootWarningConcerns('idempotency-process-scoped', role) && probes.idempotency()) {
56
+ said.push('idempotency-process-scoped');
57
+ }
58
+ if (bootWarningConcerns('mfa-secret-unsealed', role) && (await probes.mfa()) > 0) {
59
+ said.push('mfa-secret-unsealed');
60
+ }
61
+ return said;
62
+ }
package/src/serve-boot.ts CHANGED
@@ -12,7 +12,7 @@ import { armFailureCapture } from './failure-capture-boot';
12
12
  import type { MetricsEndpoint } from './metrics-endpoint';
13
13
  import { startOtlpExport } from './otlp-export';
14
14
  import type { Finding } from './output';
15
- import { loadAppForRole, roleLoadFor } from './role-load';
15
+ import { loadAppForRole } from './role-load';
16
16
  import { startRoles } from './role-start';
17
17
  import { armRowSecurity, rowSecurityDeclared } from './row-security-boot';
18
18
  import { resolveServices } from './runtime-bindings';
@@ -22,6 +22,9 @@ import { warnUnsealedMfaSecrets } from './runtime-mfa-warning';
22
22
  import { replicaOverrides } from './runtime-replica';
23
23
  import type { RunningServices } from './runtime-services';
24
24
  import { releaseOrThrow, startServices } from './runtime-services';
25
+ import type { BootTimeline } from './serve-boot-phases';
26
+ import { bootTimeline } from './serve-boot-phases';
27
+ import { bootWarningConcerns, warnAtBoot } from './serve-boot-warnings';
25
28
  import { loadDrainConfig, loadHealthConfig } from './serve-drain';
26
29
  import { configureReporting, containerBinding, metricsPortFor, portFromEnv } from './serve-env';
27
30
  import { adoptPrebuiltStyles, reportBootBuilds, watchBootBuilds } from './serve-prebuilt';
@@ -37,7 +40,7 @@ import type { ServedApp, ServeOptions } from './serve-types';
37
40
  async function buildIdFor(options: ServeOptions, role: Role): Promise<string> {
38
41
  const stamped = options.env['BUILD_ID'];
39
42
  if (stamped !== undefined && stamped.length > 0) return stamped;
40
- if (roleLoadFor(role) === 'background') {
43
+ if (bootWarningConcerns('build-id-unstamped', role)) {
41
44
  logger.warn('ultimate build id unstamped', {
42
45
  role,
43
46
  cause:
@@ -89,6 +92,8 @@ export async function bootServing(boot: {
89
92
  readonly metrics: MetricsEndpoint;
90
93
  }): Promise<ServedApp> {
91
94
  const { options } = boot;
95
+ // One `boot.phase` line as each step ends, so a slow boot names its slow step (U12).
96
+ const timeline = bootTimeline(boot.role, options.runtime?.clock);
92
97
  const services = resolveServices(options.root, options.env);
93
98
  // A serving role on a real database runs no DDL: `ROLE=migrate` applied this build's framework
94
99
  // tables first, and this boot only verifies the stamp it left (`framework-schema-apply.ts`).
@@ -97,7 +102,8 @@ export async function bootServing(boot: {
97
102
  // The role decides whether this boot waits for the bus: only `sync` and the replicator do.
98
103
  const runtime = await startServices(services, options.env, options.runtime, schema, [boot.role]);
99
104
  boot.acquired.push(() => runtime.stop());
100
- return bootRoles({ ...boot, runtime });
105
+ timeline.phase('services');
106
+ return bootRoles({ ...boot, runtime, timeline });
101
107
  }
102
108
 
103
109
  /**
@@ -131,8 +137,9 @@ async function bootRoles(boot: {
131
137
  readonly acquired: (() => void | Promise<void>)[];
132
138
  /** The scrape listener `serveApp` opened before any of this work; `startRoles` adopts it. */
133
139
  readonly metrics: MetricsEndpoint;
140
+ readonly timeline: BootTimeline;
134
141
  }): Promise<ServedApp> {
135
- const { options, role, runtime, acquired, metrics } = boot;
142
+ const { options, role, runtime, acquired, metrics, timeline } = boot;
136
143
  // Before the app's modules, because importing one may register a `close` hook, and that phase
137
144
  // runs last-registered first: the flush has to be the hook registered earliest, or a teardown's
138
145
  // spans are recorded into an exporter already shut down. `OTEL_EXPORTER_OTLP_ENDPOINT` is in the
@@ -141,7 +148,11 @@ async function bootRoles(boot: {
141
148
  // different lifetime — so this is the production boot's alone (axiom 6).
142
149
  // At the FRONT of the unwind list, so the stop and a failed boot's rollback alike release it
143
150
  // last: the drain's own spans and the final counter snapshot still have somewhere to go.
144
- acquired.unshift(startOtlpExport(options.env));
151
+ // The config first, for `database.slowStatementMs`: `app.config.ts` declares, it registers no hook.
152
+ const appConfig = await loadAppConfig(options.root);
153
+ acquired.unshift(
154
+ startOtlpExport(options.env, { slowStatementMs: appConfig?.database.slowStatementMs }),
155
+ );
145
156
  // The image's compiled stylesheets, before the first page is imported — importing one IS
146
157
  // compiling its sheet — and the count of what this boot compiles anyway.
147
158
  adoptPrebuiltStyles(options.root);
@@ -158,17 +169,17 @@ async function bootRoles(boot: {
158
169
  logger.error('ultimate app module failed to load', { role, ...finding });
159
170
  }
160
171
  refuseHalfLoadedApp(role, loaded.findings);
172
+ timeline.phase('app-load');
161
173
  // After the app's modules and before any role serves: a role Postgres exempts from row security is
162
174
  // refused here (`X_DB_ROW_SECURITY_BYPASSED`), never discovered on another tenant's first read.
163
175
  // PGlite's one session is a superuser: there the boot serves as `x_app` instead of refusing.
164
176
  const embedded = runtime.services.db.mode === 'embedded';
165
- const appConfig = await loadAppConfig(options.root);
166
177
  acquired.push(await armRowSecurity(rowSecurityDeclared(appConfig), { embedded }));
167
178
  // `failureCapture.enabled`: a 5xx keeps a replayable bundle for `x repro` (off by default).
168
179
  acquired.push(armFailureCapture(appConfig, { store: runtime.failureStore }));
169
- // After the app's modules: an app swaps the store at import time, after `startServices`.
170
- warnIfIdempotencyProcessScoped();
180
+ timeline.phase('app-checks');
171
181
  const buildId = await buildIdFor(options, role);
182
+ timeline.phase('build-id');
172
183
  // Before the first socket opens: everything above this line fails loudly into the container's
173
184
  // own logs, everything below it is a served request, a claimed job or a routed frame.
174
185
  // Released with the boot, so a second boot in this process starts from the app's reporter alone.
@@ -181,9 +192,16 @@ async function bootRoles(boot: {
181
192
  role === 'web'
182
193
  ? await (await import('./serve-web')).webSurface(options, runtime, buildId)
183
194
  : undefined;
184
- if (web !== undefined) acquired.push(web.release);
185
- // The web role alone — it is where a second factor is asked for — and once per pod boot.
186
- if (role === 'web') await warnUnsealedMfaSecrets(runtime.db);
195
+ if (web !== undefined) {
196
+ acquired.push(web.release);
197
+ timeline.phase('web');
198
+ }
199
+ // After the app's modules — an app swaps the idempotency store at import time, after
200
+ // `startServices` — and each only in the roles its table row names (`serve-boot-warnings.ts`).
201
+ await warnAtBoot(role, {
202
+ idempotency: () => warnIfIdempotencyProcessScoped(),
203
+ mfa: () => warnUnsealedMfaSecrets(runtime.db),
204
+ });
187
205
  // Islands and stylesheets are the image build's to make (`x build --target prebuilt`). A role
188
206
  // that made either here served correctly and paid for it — seconds of CPU and a compiler's
189
207
  // memory, on every start of every replica — so it says so once, with the Dockerfile line.
@@ -230,6 +248,7 @@ async function bootRoles(boot: {
230
248
  ...(replicaOverride === undefined ? {} : { overrides: replicaOverride }),
231
249
  });
232
250
  acquired.push(() => running.stop());
251
+ timeline.phase('roles');
233
252
  return {
234
253
  kind: 'served',
235
254
  role,
@@ -0,0 +1,245 @@
1
+ // The one Grafana dashboard every Ultimate chart ships: requests, latency by route, statements,
2
+ // pool, jobs, realtime and the process, over the series the framework declares. One column of
3
+ // full-width panels, so a phone reads it as it is. The JSON and its ConfigMap are generated here;
4
+ // `docker/helm/` holds these bytes for the chart named `ultimate`.
5
+ import type { GeneratedFile, NameSet } from './naming';
6
+
7
+ export interface DashboardTarget {
8
+ readonly expr: string;
9
+ /** Grafana's legend template, `{{label}}` interpolated per series. */
10
+ readonly legend: string;
11
+ }
12
+
13
+ export interface DashboardPanel {
14
+ readonly title: string;
15
+ /** Grafana's unit id: `reqps`, `s`, `bytes`, `percentunit`, `short`. */
16
+ readonly unit: string;
17
+ readonly targets: readonly DashboardTarget[];
18
+ }
19
+
20
+ /** One release in one namespace — the two labels the ServiceMonitor puts on every series. */
21
+ const SCOPE = 'namespace="$namespace",app_kubernetes_io_instance="$release"';
22
+ const RATE = '[$__rate_interval]';
23
+
24
+ const s = (name: string, extra?: string): string =>
25
+ `${name}{${extra === undefined ? SCOPE : `${SCOPE},${extra}`}}`;
26
+
27
+ const p = (q: number, name: string, by: string): string =>
28
+ `histogram_quantile(${String(q)}, sum by (${by}, le) (rate(${s(`${name}_bucket`)}${RATE})))`;
29
+
30
+ export const DASHBOARD_PANELS: readonly DashboardPanel[] = [
31
+ {
32
+ title: 'Requests per second, by status class',
33
+ unit: 'reqps',
34
+ targets: [
35
+ { expr: `sum by (status) (rate(${s('http_requests_total')}${RATE}))`, legend: '{{status}}' },
36
+ ],
37
+ },
38
+ {
39
+ title: 'Latency p95, by route',
40
+ unit: 's',
41
+ targets: [{ expr: p(0.95, 'http_request_duration_seconds', 'route'), legend: '{{route}}' }],
42
+ },
43
+ {
44
+ title: '5xx share of requests',
45
+ unit: 'percentunit',
46
+ targets: [
47
+ {
48
+ expr: `sum(rate(${s('http_requests_total', 'status="5xx"')}${RATE})) / sum(rate(${s('http_requests_total')}${RATE}))`,
49
+ legend: '5xx',
50
+ },
51
+ ],
52
+ },
53
+ {
54
+ title: 'Statement p95, by operation',
55
+ unit: 's',
56
+ targets: [
57
+ {
58
+ expr: p(0.95, 'db_client_operation_duration_seconds', 'db_operation_name'),
59
+ legend: 'p95 {{db_operation_name}}',
60
+ },
61
+ ],
62
+ },
63
+ {
64
+ title: 'Database pool, by pod',
65
+ unit: 'short',
66
+ targets: [
67
+ { expr: `sum by (pod) (${s('db_pool_in_use')})`, legend: 'in use {{pod}}' },
68
+ { expr: `sum by (pod) (${s('db_pool_waiting')})`, legend: 'waiting {{pod}}' },
69
+ { expr: `sum by (pod) (${s('db_pool_max')})`, legend: 'max {{pod}}' },
70
+ ],
71
+ },
72
+ {
73
+ title: 'Jobs per second, by queue and outcome',
74
+ unit: 'short',
75
+ targets: [
76
+ {
77
+ expr: `sum by (queue, outcome) (rate(${s('jobs_total')}${RATE}))`,
78
+ legend: '{{queue}} {{outcome}}',
79
+ },
80
+ ],
81
+ },
82
+ {
83
+ title: 'Queue: oldest ready job and dead letters',
84
+ unit: 's',
85
+ targets: [
86
+ { expr: `max by (queue) (${s('queue_oldest_ready_seconds')})`, legend: 'oldest {{queue}}' },
87
+ { expr: `max by (queue) (${s('queue_dead_jobs')})`, legend: 'dead {{queue}}' },
88
+ ],
89
+ },
90
+ {
91
+ title: 'Job duration p95, by queue',
92
+ unit: 's',
93
+ targets: [{ expr: p(0.95, 'job_duration_seconds', 'queue'), legend: '{{queue}}' }],
94
+ },
95
+ {
96
+ title: 'Realtime: connections and dropped frames',
97
+ unit: 'short',
98
+ targets: [
99
+ { expr: `sum by (pod) (${s('connections')})`, legend: 'connections {{pod}}' },
100
+ {
101
+ expr: `sum(rate(${s('channel_frames_dropped_total')}${RATE}))`,
102
+ legend: 'frames dropped/s',
103
+ },
104
+ ],
105
+ },
106
+ {
107
+ title: 'Memory: RSS over the container limit, by pod',
108
+ unit: 'percentunit',
109
+ targets: [
110
+ {
111
+ expr: `max by (pod) (${s('process_resident_memory_bytes')} / ${s('process_memory_limit_bytes')})`,
112
+ legend: '{{pod}}',
113
+ },
114
+ ],
115
+ },
116
+ {
117
+ title: 'CPU seconds per second, by pod',
118
+ unit: 'short',
119
+ targets: [
120
+ { expr: `sum by (pod) (rate(${s('process_cpu_seconds_total')}${RATE}))`, legend: '{{pod}}' },
121
+ ],
122
+ },
123
+ {
124
+ title: 'Event-loop lag p99, by pod',
125
+ unit: 's',
126
+ targets: [{ expr: p(0.99, 'process_event_loop_lag_seconds', 'pod'), legend: '{{pod}}' }],
127
+ },
128
+ {
129
+ title: 'Restarts in the last hour, by role',
130
+ unit: 'short',
131
+ targets: [
132
+ {
133
+ expr: `sum by (app_kubernetes_io_component) (changes(${s('process_start_time_seconds')}[1h]))`,
134
+ legend: '{{app_kubernetes_io_component}}',
135
+ },
136
+ ],
137
+ },
138
+ ];
139
+
140
+ /** The stable uid a provisioned dashboard keeps across upgrades, so a bookmark survives. */
141
+ export const DASHBOARD_UID = 'ultimate-app';
142
+ export const DASHBOARD_FILE = 'docker/helm/dashboards/ultimate-app.json';
143
+
144
+ /** Every panel and variable reads the dashboard's own datasource variable. */
145
+ const DATASOURCE = { type: 'prometheus', uid: '$datasource' } as const;
146
+
147
+ const variable = (name: string, query: string) => ({
148
+ name,
149
+ type: 'query',
150
+ datasource: DATASOURCE,
151
+ query: { query, refId: name },
152
+ refresh: 2,
153
+ includeAll: false,
154
+ multi: false,
155
+ });
156
+
157
+ const PANEL_HEIGHT = 8;
158
+
159
+ /** The dashboard as Grafana's JSON model, two-space indented, one trailing newline. */
160
+ export function dashboardJson(): string {
161
+ const model = {
162
+ uid: DASHBOARD_UID,
163
+ title: 'Ultimate app',
164
+ tags: ['ultimate'],
165
+ timezone: 'utc',
166
+ schemaVersion: 39,
167
+ editable: true,
168
+ time: { from: 'now-6h', to: 'now' },
169
+ templating: {
170
+ list: [
171
+ { name: 'datasource', type: 'datasource', query: 'prometheus' },
172
+ variable('namespace', 'label_values(process_info, namespace)'),
173
+ variable(
174
+ 'release',
175
+ 'label_values(process_info{namespace="$namespace"}, app_kubernetes_io_instance)',
176
+ ),
177
+ ],
178
+ },
179
+ panels: DASHBOARD_PANELS.map((panel, index) => ({
180
+ id: index + 1,
181
+ type: 'timeseries',
182
+ title: panel.title,
183
+ datasource: DATASOURCE,
184
+ // One full-width column: the grid is 24 wide, and a phone shows it unchanged.
185
+ gridPos: { x: 0, y: index * PANEL_HEIGHT, w: 24, h: PANEL_HEIGHT },
186
+ fieldConfig: { defaults: { unit: panel.unit }, overrides: [] },
187
+ targets: panel.targets.map((target, at) => ({
188
+ refId: String.fromCharCode(65 + at),
189
+ expr: target.expr,
190
+ legendFormat: target.legend,
191
+ })),
192
+ })),
193
+ };
194
+ return `${biomeJson(model)}\n`;
195
+ }
196
+
197
+ const SCALAR = String.raw`(?:"(?:[^"\\\n]|\\.)*"|-?\d[\d.eE+-]*|true|false|null)`;
198
+ const SCALAR_ARRAY = new RegExp(String.raw`\[\n\s+(${SCALAR}(?:,\n\s+${SCALAR})*)\n\s*\]`, 'g');
199
+
200
+ /**
201
+ * `JSON.stringify` at two spaces, with an array of scalars on one line — how Biome formats JSON, so
202
+ * the file `x new` writes passes the app's own `biome check`. Objects stay expanded, as Biome keeps
203
+ * them.
204
+ */
205
+ function biomeJson(value: unknown): string {
206
+ return JSON.stringify(value, null, 2).replace(
207
+ SCALAR_ARRAY,
208
+ (_all, items: string) => `[${items.split(/,\n\s+/).join(', ')}]`,
209
+ );
210
+ }
211
+
212
+ const configMapTemplate = (chart: string): string => `{{/*
213
+ The chart's Grafana dashboard (dashboards/ultimate-app.json, written from @ultimat3/cli's panel
214
+ table), as a ConfigMap a Grafana sidecar provisions by label. Opt-in: dashboard.enabled. The JSON
215
+ is read with .Files.Get, never templated: its legends use Grafana's own double-brace syntax.
216
+ */}}
217
+ {{- $cfg := .Values.dashboard | default dict }}
218
+ {{- if eq (toString $cfg.enabled) "true" }}
219
+ apiVersion: v1
220
+ kind: ConfigMap
221
+ metadata:
222
+ name: {{ include "${chart}.fullname" . }}-dashboard
223
+ labels:
224
+ {{- include "${chart}.labels" . | nindent 4 }}
225
+ {{- toYaml ($cfg.labels | default (dict "grafana_dashboard" "1")) | nindent 4 }}
226
+ {{- with $cfg.annotations }}
227
+ annotations:
228
+ {{- toYaml . | nindent 4 }}
229
+ {{- end }}
230
+ data:
231
+ ultimate-app.json: |-
232
+ {{ .Files.Get "dashboards/ultimate-app.json" | indent 4 }}
233
+ {{- end }}
234
+ `;
235
+
236
+ /** The dashboard and the template that ships it. */
237
+ export function helmDashboardFiles(app: NameSet): readonly GeneratedFile[] {
238
+ return [
239
+ { path: DASHBOARD_FILE, contents: dashboardJson() },
240
+ {
241
+ path: 'docker/helm/templates/dashboard-configmap.yaml',
242
+ contents: configMapTemplate(app.kebab),
243
+ },
244
+ ];
245
+ }