@ultimat3/cli 31.23.0 → 31.25.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 (57) hide show
  1. package/CLAUDE.md +4 -2
  2. package/README.md +1 -0
  3. package/package.json +29 -29
  4. package/src/cmd-db-recount.ts +81 -24
  5. package/src/cmd-db-spec.ts +9 -1
  6. package/src/cmd-db.ts +1 -0
  7. package/src/cmd-doctor.ts +7 -1
  8. package/src/cmd-generate-spec.ts +3 -2
  9. package/src/cmd-generate.ts +4 -0
  10. package/src/db-diagnostics.ts +6 -0
  11. package/src/db-generate.ts +14 -3
  12. package/src/doctor-guards.ts +5 -3
  13. package/src/doctor-redundant-indexes.ts +76 -0
  14. package/src/fix-sequence.ts +0 -1
  15. package/src/framework-schema.ts +5 -4
  16. package/src/generate-files.ts +10 -0
  17. package/src/generate-invite.ts +195 -0
  18. package/src/generate-kinds.ts +4 -0
  19. package/src/messages.ts +3 -0
  20. package/src/metrics-endpoint.ts +5 -3
  21. package/src/redundant-indexes.ts +101 -0
  22. package/src/retained-assets-boot.ts +28 -15
  23. package/src/role-replicator.ts +26 -4
  24. package/src/role-start.ts +13 -0
  25. package/src/runtime-boot-warnings.ts +65 -0
  26. package/src/runtime-cache.ts +14 -8
  27. package/src/runtime-liveness.ts +23 -0
  28. package/src/schema-drift.ts +5 -2
  29. package/src/serve-boot-warnings.ts +9 -8
  30. package/src/serve.ts +4 -1
  31. package/src/templates/guard-error-declared.ts +48 -11
  32. package/src/templates/guard-repo-unbounded.ts +29 -13
  33. package/src/templates/invite-pages.ts +151 -0
  34. package/src/templates/invite-tests.ts +228 -0
  35. package/src/templates/invite.ts +293 -0
  36. package/src/templates/scaffold-container-compose.ts +3 -2
  37. package/src/templates/scaffold-guards.ts +26 -3
  38. package/src/templates/scaffold-helm-templates.ts +1 -1
  39. package/src/templates/scaffold-repo.ts +1 -0
  40. package/wiki/Auth.md +24 -0
  41. package/wiki/Building-Your-Own-Base.md +20 -0
  42. package/wiki/CLI-Reference.md +7 -1
  43. package/wiki/Entities-And-Migrations.md +6 -2
  44. package/wiki/FAQ.md +2 -2
  45. package/wiki/Home.md +1 -1
  46. package/wiki/Jobs-And-Workflows.md +8 -6
  47. package/wiki/Known-Gaps.md +1 -2
  48. package/wiki/Migrations-And-Backfills.md +1 -1
  49. package/wiki/Observability.md +2 -1
  50. package/wiki/Outbound-HTTP.md +40 -0
  51. package/wiki/Policies-And-Authz.md +52 -20
  52. package/wiki/Realtime.md +18 -1
  53. package/wiki/Scheduled-Tasks.md +1 -1
  54. package/wiki/Shapes.md +3 -2
  55. package/wiki/Testing.md +1 -0
  56. package/wiki/Tutorial-04-Jobs-And-Realtime.md +1 -1
  57. package/wiki/Upgrading.md +2 -0
@@ -0,0 +1,195 @@
1
+ // `x g invite`: the member invite's files written through the one writer (`writeFiles` — a second
2
+ // run conflicts and writes nothing), then the edits outside them: `member:invite` granted to
3
+ // `admin`, the three actions listed in the API index, and each one's exercise entry turned off
4
+ // with its reason, so the app's next `x verify` is green. No name and no flag: one invite per app.
5
+
6
+ import { indexBindingFindings } from './api-registration';
7
+ import { generateSpec } from './cmd-generate-spec';
8
+ import type { CommandContext } from './command';
9
+ import { invocationOf } from './command';
10
+ import { BadFlagError } from './errors';
11
+ import { localiseCatalogs, namedOrAppLocales } from './generate-catalog-locales';
12
+ import { appDisk, plannedDisk } from './generate-disk';
13
+ import { writtenExercises } from './generate-exercise';
14
+ import { generate } from './generate-files';
15
+ import { followUpEdits } from './generate-follow-ups';
16
+ import { formatWritten } from './generate-format-written';
17
+ import { appManifestIfAny, existingArtifacts } from './generate-sign-in-manifest';
18
+ import { planWrites, writeFiles } from './generate-write';
19
+ import { resolveDbModule } from './handle-registration';
20
+ import { resolveCatalogModule } from './i18n-audit';
21
+ import { msg } from './messages';
22
+ import type { CommandResult } from './output';
23
+ import { flagBool, flagList, type ParsedArgs } from './parse';
24
+ import { resolveLocales } from './templates';
25
+ import { withDependency } from './workspace-dep-edit';
26
+
27
+ const KIND = 'invite';
28
+
29
+ /** The `x g` flags this generator reads; any other one would change nothing, so is refused. */
30
+ const READS = new Set(['force', 'dry-run', 'locales', 'json']);
31
+
32
+ /** No `<name>` and no flag it ignores: a second spelling of one command is refused, not dropped. */
33
+ export function refuseInviteArgs(args: ParsedArgs): void {
34
+ const named = args.positionals[1];
35
+ if (named !== undefined) {
36
+ throw new BadFlagError({
37
+ flag: 'name',
38
+ command: 'g invite',
39
+ reason: `an app has one member invite, so "${named}" names nothing`,
40
+ fix: 'x g invite',
41
+ });
42
+ }
43
+ for (const flag of generateSpec.flags ?? []) {
44
+ if (READS.has(flag.name)) continue;
45
+ const value = args.flags.get(flag.name);
46
+ if (value === undefined || value === flag.default) continue;
47
+ throw new BadFlagError({
48
+ flag: flag.name,
49
+ command: 'g invite',
50
+ reason: `the invite generator does not read --${flag.name}, so it would change nothing`,
51
+ fix: 'x g invite',
52
+ });
53
+ }
54
+ }
55
+
56
+ const ROOT_MANIFEST = 'package.json';
57
+ const MAIL_PACKAGE = '@ultimat3/mail';
58
+
59
+ /**
60
+ * The root manifest with `@ultimat3/mail` declared at the range the app already holds
61
+ * `@ultimat3/auth` at — the invite mails. `x new` declares it from this release on; the edit is for an
62
+ * app scaffolded before that. `undefined` when it is
63
+ * declared already, or the manifest is not one this can read; `package-shape` then names the line.
64
+ */
65
+ async function mailDependency(root: string): Promise<string | undefined> {
66
+ const text = await appDisk(root).read(ROOT_MANIFEST);
67
+ if (text === undefined) return undefined;
68
+ let parsed: unknown;
69
+ try {
70
+ parsed = JSON.parse(text);
71
+ } catch {
72
+ return undefined;
73
+ }
74
+ const deps =
75
+ typeof parsed === 'object' && parsed !== null && 'dependencies' in parsed
76
+ ? (parsed as { readonly dependencies?: unknown }).dependencies
77
+ : undefined;
78
+ const range =
79
+ typeof deps === 'object' && deps !== null
80
+ ? (deps as Readonly<Record<string, unknown>>)['@ultimat3/auth']
81
+ : undefined;
82
+ return typeof range === 'string' ? withDependency(text, MAIL_PACKAGE, range) : undefined;
83
+ }
84
+
85
+ export async function runInvite(ctx: CommandContext, root: string): Promise<CommandResult> {
86
+ refuseInviteArgs(ctx.args);
87
+ const catalogModule = await resolveCatalogModule(root);
88
+ const dbModule = await resolveDbModule(root);
89
+ const locales = resolveLocales(await namedOrAppLocales(root, flagList(ctx.args, 'locales')));
90
+ const files = await localiseCatalogs(
91
+ root,
92
+ generate({
93
+ kind: KIND,
94
+ name: KIND,
95
+ locales,
96
+ ...(catalogModule === undefined ? {} : { catalogModule }),
97
+ }),
98
+ );
99
+ const invocation = [invocationOf(ctx, 'g'), KIND].join(' ');
100
+ const force = flagBool(ctx.args, 'force');
101
+ // An app already binding `inviteMember` in its API index is refused before anything lands.
102
+ const bindings = await indexBindingFindings(
103
+ root,
104
+ files.map((file) => file.path),
105
+ `${invocation} # after renaming what apps/web/api/index.ts already binds under that name`,
106
+ );
107
+
108
+ if (flagBool(ctx.args, 'dry-run')) {
109
+ const plan = await planWrites(root, files, force, invocation, KIND);
110
+ const planned = new Map(
111
+ files.flatMap((file) =>
112
+ plan.written.includes(file.path) && typeof file.contents === 'string'
113
+ ? [[file.path, file.contents] as const]
114
+ : [],
115
+ ),
116
+ );
117
+ const refused = [...plan.conflicts, ...bindings];
118
+ const follow =
119
+ refused.length > 0
120
+ ? { edited: [], findings: [] }
121
+ : await followUpEdits(
122
+ root,
123
+ plan.written,
124
+ dbModule,
125
+ plannedDisk(root, planned),
126
+ writtenExercises(files, plan.written),
127
+ );
128
+ const manifest = refused.length > 0 ? undefined : await mailDependency(root);
129
+ const touched =
130
+ refused.length > 0
131
+ ? []
132
+ : [
133
+ ...new Set([
134
+ ...plan.written,
135
+ ...follow.edited,
136
+ ...(manifest === undefined ? [] : [ROOT_MANIFEST]),
137
+ ]),
138
+ ];
139
+ const findings = [...refused, ...follow.findings];
140
+ return {
141
+ ok: findings.length === 0,
142
+ command: 'g',
143
+ summary: msg('cli.generate.planned', { count: touched.length, kind: KIND, name: KIND }),
144
+ data: {
145
+ files: touched,
146
+ ...(touched.length === 0 ? {} : { refreshes: [...(await existingArtifacts(root))] }),
147
+ dryRun: true,
148
+ },
149
+ lines: touched.map((path) => msg('cli.file.added', { path })),
150
+ findings,
151
+ };
152
+ }
153
+
154
+ const report =
155
+ bindings.length > 0
156
+ ? { written: [], conflicts: bindings }
157
+ : await writeFiles(root, files, force, invocation, KIND);
158
+ if (report.conflicts.length > 0) {
159
+ return {
160
+ ok: false,
161
+ command: 'g',
162
+ summary: msg('cli.generate.wrote', { count: 0, kind: KIND, name: KIND }),
163
+ data: { files: [] },
164
+ findings: report.conflicts,
165
+ };
166
+ }
167
+ const manifest = await mailDependency(root);
168
+ if (manifest !== undefined) await appDisk(root).write(ROOT_MANIFEST, manifest);
169
+ const follow = await followUpEdits(
170
+ root,
171
+ report.written,
172
+ dbModule,
173
+ appDisk(root),
174
+ writtenExercises(files, report.written),
175
+ );
176
+ await formatWritten(root, report.written, ctx.runner);
177
+ const refreshed = await appManifestIfAny(root);
178
+ const written = [
179
+ ...new Set([
180
+ ...report.written,
181
+ ...(manifest === undefined ? [] : [ROOT_MANIFEST]),
182
+ ...follow.edited,
183
+ ...refreshed.written,
184
+ ]),
185
+ ];
186
+ const findings = [...follow.findings, ...refreshed.findings];
187
+ return {
188
+ ok: findings.length === 0,
189
+ command: 'g',
190
+ summary: msg('cli.generate.wrote', { count: written.length, kind: KIND, name: KIND }),
191
+ data: { files: written },
192
+ lines: written.map((path) => msg('cli.file.added', { path })),
193
+ findings,
194
+ };
195
+ }
@@ -34,6 +34,8 @@ export const GENERATORS = [
34
34
  'admin:page',
35
35
  'guard',
36
36
  'sign-in',
37
+ // The member invite over `defineMemberInvite`: one per app, no `<name>` (`generate-invite.ts`).
38
+ 'invite',
37
39
  'chart-alerts',
38
40
  'chart-dashboard',
39
41
  'app',
@@ -300,6 +302,8 @@ const EXAMPLE_NAME: Readonly<Record<Generator, string>> = {
300
302
  guard: 'migration-safety',
301
303
  // Sign-in takes no name: its "example" is the flag that picks a shape, so the line still runs.
302
304
  'sign-in': '--password',
305
+ // No name and no flag: the example is the bare command, and `--json` keeps the line runnable.
306
+ invite: '--json',
303
307
  // No name either: an app has one chart. `--print` runs with or without one.
304
308
  'chart-alerts': '--print',
305
309
  'chart-dashboard': '--print',
package/src/messages.ts CHANGED
@@ -104,6 +104,9 @@ const CATALOG = {
104
104
  // `x doctor`'s reminder: the rolling rail is off until this key is set (`doctor-rolling.ts`).
105
105
  'cli.doctor.rollingSince':
106
106
  'the rolling-deploy rail is off: set "rollingSince": "{newest}" in x.verify.json to judge every migration after your newest',
107
+ // `x doctor`'s listing: implicit indexes another one already serves (`doctor-redundant-indexes.ts`).
108
+ 'cli.doctor.redundantIndexes':
109
+ '{count} implicit index(es) another index already leads with, each paid for on every write; drop them in a migration you review: {fix}',
107
110
  // `x doctor`'s warnings: beside the verdict on `main`, red on `next` (`doctor-warnings.ts`).
108
111
  'cli.doctor.warnings': '{count} warning(s) — not in the verdict until the next major:',
109
112
  'cli.doctor.warning': ' {code}: {cause} — fix: {fix}',
@@ -8,7 +8,6 @@ import {
8
8
  BUILD_ID_HEADER,
9
9
  finiteCount,
10
10
  type HealthPayload,
11
- healthzPayload,
12
11
  logger,
13
12
  METRICS_CONTENT_TYPE,
14
13
  METRICS_PATH,
@@ -20,6 +19,7 @@ import {
20
19
  UltimateError,
21
20
  } from '@ultimat3/core';
22
21
  import { neighbouringPort, PORT_RANGE, syncPortFor } from './flag-number';
22
+ import { livenessPayload } from './runtime-liveness';
23
23
  import { quoteArg } from './shell-quote';
24
24
 
25
25
  /**
@@ -211,7 +211,8 @@ export interface MetricsEndpoint {
211
211
 
212
212
  /**
213
213
  * `/healthz` and `/readyz` for the roles whose only socket this is — `worker`, `scheduler`,
214
- * `replicator` — so the replicator's readiness check (`role-replicator.ts`) is read by a probe.
214
+ * `replicator` — so the replicator's readiness check (`role-replicator.ts`) is read by a probe, and
215
+ * `/healthz` is their LIVENESS: 503 once any running loop's heartbeat is past its bound.
215
216
  * The verdict only, never the report: this port is unauthenticated, and check names are topology.
216
217
  */
217
218
  function healthResponse(payload: HealthPayload, role: string, buildId: string | null): Response {
@@ -262,7 +263,8 @@ export function startMetricsEndpoint(options: MetricsEndpointOptions = {}): Metr
262
263
  fetch(request: Request): Response {
263
264
  const url = new URL(request.url);
264
265
  const role = options.role ?? 'unknown';
265
- if (url.pathname === '/healthz') return healthResponse(healthzPayload(), role, buildId);
266
+ // Liveness reads the loops' heartbeats (`runtime-liveness.ts`): the probe a wedge fails.
267
+ if (url.pathname === '/healthz') return healthResponse(livenessPayload(), role, buildId);
266
268
  if (url.pathname === '/readyz') {
267
269
  return healthResponse(
268
270
  readyzPayload({ deep: url.searchParams.get('deep') === '1' }),
@@ -0,0 +1,101 @@
1
+ // Single responsibility: which implicit indexes the app's entities describe that another index
2
+ // already serves (`RegistryEntry.coveredIndexes`), and the descriptions `x db gen` diffs with those
3
+ // left out — on `--drop-redundant`, and for good once a migration has dropped one.
4
+
5
+ import type { Migration, SchemaDescription } from '@ultimat3/db';
6
+ import { declaredSchema } from '@ultimat3/db';
7
+ import type { EntityDescription, RegistryEntry } from '@ultimat3/entity';
8
+
9
+ export interface RedundantIndex {
10
+ readonly table: string;
11
+ readonly name: string;
12
+ /** Physical columns, in index order. */
13
+ readonly columns: readonly string[];
14
+ /** The index, primary key or unique invariant that already leads with them. */
15
+ readonly coveredBy: string;
16
+ }
17
+
18
+ /** Every covered implicit index of the registry, in registry order. */
19
+ export const redundantIndexes = (entries: readonly RegistryEntry[]): readonly RedundantIndex[] =>
20
+ entries.flatMap((entry) =>
21
+ (entry.coveredIndexes ?? []).map((index) => ({
22
+ table: entry.tableName,
23
+ name: index.name,
24
+ columns: index.columns,
25
+ coveredBy: index.coveredBy,
26
+ })),
27
+ );
28
+
29
+ /** Each table the snapshot records, to the index names it holds. */
30
+ const recordedIndexes = (current: SchemaDescription): ReadonlyMap<string, ReadonlySet<string>> =>
31
+ new Map(
32
+ current.tables.map((table) => [table.name, new Set(table.indexes.map((index) => index.name))]),
33
+ );
34
+
35
+ /**
36
+ * The covered indexes still in the newest snapshot: what `--drop-redundant` would drop now. A
37
+ * table the snapshot does not hold yet is left out — its first migration has not been written.
38
+ */
39
+ export const pendingRedundant = (
40
+ redundant: readonly RedundantIndex[],
41
+ current: SchemaDescription,
42
+ ): readonly RedundantIndex[] => {
43
+ const recorded = recordedIndexes(current);
44
+ return redundant.filter((index) => recorded.get(index.table)?.has(index.name) === true);
45
+ };
46
+
47
+ /**
48
+ * Each table the newest snapshot holds, to the index names an EARLIER snapshot recorded on it and
49
+ * the newest no longer does: what a migration dropped. Absent from the newest alone is not that —
50
+ * a covered index newly declared on an existing table was never built.
51
+ */
52
+ const droppedIndexes = (
53
+ migrations: readonly Migration[],
54
+ current: SchemaDescription,
55
+ ): ReadonlyMap<string, ReadonlySet<string>> => {
56
+ const recorded = recordedIndexes(current);
57
+ const dropped = new Map<string, Set<string>>();
58
+ for (const migration of migrations) {
59
+ for (const table of migration.snapshot?.tables ?? []) {
60
+ const held = recorded.get(table.name);
61
+ if (held === undefined) continue;
62
+ for (const index of table.indexes) {
63
+ if (held.has(index.name)) continue;
64
+ dropped.set(table.name, (dropped.get(table.name) ?? new Set()).add(index.name));
65
+ }
66
+ }
67
+ }
68
+ return dropped;
69
+ };
70
+
71
+ /**
72
+ * The descriptions to diff. A covered index on a table the newest snapshot holds is left out when
73
+ * `drop` asks for it, or when a migration already dropped it — a plain `x db gen` rebuilding it
74
+ * would undo that review. A NEW table, or a covered index never built, keeps every index:
75
+ * dropping is never a default.
76
+ */
77
+ export const settledDescriptions = (
78
+ entries: readonly RegistryEntry[],
79
+ migrations: readonly Migration[],
80
+ drop: boolean,
81
+ ): readonly EntityDescription[] => {
82
+ const current = declaredSchema(migrations);
83
+ if (current === undefined) return entries.map((entry) => entry.describe());
84
+ const recorded = recordedIndexes(current);
85
+ const dropped = droppedIndexes(migrations, current);
86
+ return entries.map((entry) => {
87
+ const description = entry.describe();
88
+ const held = recorded.get(entry.tableName);
89
+ const gone = dropped.get(entry.tableName);
90
+ const left = new Set(
91
+ (entry.coveredIndexes ?? [])
92
+ .filter((index) => held !== undefined && (drop || gone?.has(index.name) === true))
93
+ .map((index) => index.name),
94
+ );
95
+ if (left.size === 0) return description;
96
+ return {
97
+ ...description,
98
+ indexes: description.indexes.filter((index) => !left.has(index.name)),
99
+ };
100
+ });
101
+ };
@@ -3,7 +3,13 @@
3
3
  // binds, so before `/readyz` can say ready — and hand back the reader the asset routes miss into.
4
4
 
5
5
  import type { AppConfig, AssetsRetainConfig } from '@ultimat3/core';
6
- import { ConfigInvalidError, logger, renderFixLiteral, UltimateError } from '@ultimat3/core';
6
+ import {
7
+ bootWarning,
8
+ ConfigInvalidError,
9
+ logger,
10
+ renderFixLiteral,
11
+ UltimateError,
12
+ } from '@ultimat3/core';
7
13
  import type { Storage } from '@ultimat3/storage';
8
14
  import type { IslandBundle } from './island-bundle';
9
15
  import type { BuildAsset, PublishReport, RetainLog } from './retained-assets';
@@ -11,7 +17,7 @@ import { publishBuildAssets } from './retained-assets';
11
17
  import { retainedPrefix } from './retained-assets-layout';
12
18
  import type { RetainedAssets } from './retained-assets-read';
13
19
  import { retainedAssets } from './retained-assets-read';
14
- import { warnOncePerBuild } from './retained-assets-warned';
20
+ import { retainedBuildOnce } from './runtime-boot-warnings';
15
21
  import { siteAssetTable } from './site-assets';
16
22
  import type { StyleBundle } from './style-bundle';
17
23
  import type { FrameworkScript } from './worker-bundle';
@@ -83,11 +89,9 @@ const LOCAL_ENVIRONMENTS: ReadonlySet<string> = new Set(['development', 'test'])
83
89
 
84
90
  /** This file is the web role's boot alone (`serve-web.ts`): the role half of the warned key. */
85
91
  const WEB_ROLE = 'web';
86
-
87
92
  /**
88
- * Once per build id for the web role, not per boot: the marker sits on the app's default disk,
89
- * the one place every pod of a deploy may share (`warnOncePerBuild`). With no `app.config.ts`
90
- * there is no app name to scope it by, so that boot says it every time.
93
+ * Once per build id for the web role, not per boot (`retainedBuildOnce`). With no `app.config.ts`
94
+ * there is no app name to scope the marker by, so that boot says it every time.
91
95
  */
92
96
  async function warnUndeclared(input: RetainBootInput): Promise<void> {
93
97
  if (LOCAL_ENVIRONMENTS.has(input.environment) || buildAssetsOf(input).length === 0) return;
@@ -95,17 +99,26 @@ async function warnUndeclared(input: RetainBootInput): Promise<void> {
95
99
  environment: input.environment,
96
100
  disks: input.storage.diskNames,
97
101
  });
98
- const warn = (): void =>
99
- (input.log ?? logger).warn(warning.format(), { code: warning.code, ...warning.meta });
100
- if (input.config === undefined) return warn();
101
- await warnOncePerBuild(
102
+ await bootWarning(
103
+ {
104
+ code: warning.code,
105
+ roles: [WEB_ROLE],
106
+ once: input.config === undefined ? undefined : 'build',
107
+ message: warning.format(),
108
+ fields: warning.meta,
109
+ },
102
110
  {
103
- disk: () => input.storage.disk(),
104
- prefix: retainedPrefix(input.config.name, input.environment),
105
- role: WEB_ROLE,
106
- buildId: input.buildId,
111
+ roles: [WEB_ROLE],
112
+ log: input.log ?? logger,
113
+ buildOnce:
114
+ input.config === undefined
115
+ ? undefined
116
+ : retainedBuildOnce({
117
+ storage: input.storage,
118
+ prefix: retainedPrefix(input.config.name, input.environment),
119
+ buildId: input.buildId,
120
+ }),
107
121
  },
108
- warn,
109
122
  );
110
123
  }
111
124
 
@@ -10,6 +10,7 @@ import {
10
10
  renderThrowable,
11
11
  } from '@ultimat3/core';
12
12
  import { describeEntities } from '@ultimat3/entity';
13
+ import { loopHeartbeat } from '@ultimat3/jobs';
13
14
  import { ReplicatorSlotHeldError } from '@ultimat3/realtime';
14
15
  import type { Replicator, ReplicatorOptions, Transport } from '@ultimat3/realtime/server';
15
16
  import {
@@ -107,6 +108,13 @@ const noEntitiesRefusal = (dev: boolean): BadFlagError | ConfigInvalidError =>
107
108
  meta: { role: 'replicator' },
108
109
  });
109
110
 
111
+ /**
112
+ * The replicator's tick for its heartbeat: the feed's status interval (10 s), the longest a live
113
+ * walsender stays silent. Event-driven — a quiet feed is healthy — so only a change held open past
114
+ * the bound (`livenessBoundMs`) is a wedge: a publish that never returns.
115
+ */
116
+ const REPLICATOR_TICK_MS = 10_000;
117
+
110
118
  /** The name `/readyz` reports the replicator under. */
111
119
  export const REPLICATOR_READINESS_CHECK = 'replicator';
112
120
 
@@ -174,10 +182,15 @@ export async function startReplicator(options: StartReplicatorOptions): Promise<
174
182
  const selection = selectChangeFeed(options.env, { entities });
175
183
  const slot = selection.slot ?? '';
176
184
  const key = replicatorLockKey(slot);
185
+ const heartbeat = loopHeartbeat('realtime.replicator', {
186
+ tickMs: REPLICATOR_TICK_MS,
187
+ periodic: false,
188
+ });
177
189
  const replicator = (options.create ?? changeFeedReplicator)({
178
190
  feed: selection.feed,
179
191
  transport: options.transport,
180
192
  lock: selection.lock,
193
+ heartbeat,
181
194
  });
182
195
  // `start()` answers `false` for the one condition that is not this process's fault: another
183
196
  // process holds the lock. A dev boot has nothing to fail over to, so it is terminal there, with
@@ -186,10 +199,18 @@ export async function startReplicator(options: StartReplicatorOptions): Promise<
186
199
  // terminated the old holder, so every rollout stalled (`replicator.ts`'s header: the loser stays
187
200
  // up, unready).
188
201
  let cancelStandby = (): void => undefined;
189
- if (!(await replicator.start())) {
190
- if (options.dev) throw new ReplicatorSlotHeldError({ key });
191
- logger.warn('replicator.standby', { key, detail: 'another process holds the slot' });
192
- cancelStandby = standBy(replicator, key);
202
+ // Started BEFORE the feed: a change the feed delivers while it starts opens a pass, and a start
203
+ // after it would clear that pass. Judged by `/healthz` on the scrape port (`runtime-liveness.ts`).
204
+ heartbeat.start();
205
+ try {
206
+ if (!(await replicator.start())) {
207
+ if (options.dev) throw new ReplicatorSlotHeldError({ key });
208
+ logger.warn('replicator.standby', { key, detail: 'another process holds the slot' });
209
+ cancelStandby = standBy(replicator, key);
210
+ }
211
+ } catch (error) {
212
+ heartbeat.stop();
213
+ throw error;
193
214
  }
194
215
  const unregister = watchReplicatorReadiness(replicator);
195
216
  return {
@@ -201,6 +222,7 @@ export async function startReplicator(options: StartReplicatorOptions): Promise<
201
222
  // ask for a slot after the role that wanted it has gone.
202
223
  cancelStandby();
203
224
  unregister();
225
+ heartbeat.stop();
204
226
  await replicator.stop();
205
227
  },
206
228
  };
package/src/role-start.ts CHANGED
@@ -29,6 +29,7 @@ import {
29
29
  registeredJobs,
30
30
  } from '@ultimat3/jobs';
31
31
  import type { SyncWs } from '@ultimat3/realtime/server';
32
+ import { loadAppConfig } from './app-config-load';
32
33
  import { errorPageHook } from './error-pages';
33
34
  import { BadFlagError, RuntimeDriverSplitError } from './errors';
34
35
  import {
@@ -44,6 +45,7 @@ import type { RunningRoles, StartRolesOptions } from './role-start-types';
44
45
  import { DEV_ROLES } from './role-start-types';
45
46
  import { prepareSync, type RunningSync, syncReadsChanges } from './role-sync';
46
47
  import { startWorkerWake } from './role-wake';
48
+ import { installRoleBootWarnings } from './runtime-boot-warnings';
47
49
  import { devHooks } from './runtime-hooks';
48
50
  import { workerOptionsFor } from './runtime-jobs';
49
51
  import { reportUnservedQueues } from './runtime-jobs-unserved';
@@ -287,6 +289,17 @@ export async function startRoles(options: StartRolesOptions): Promise<RunningRol
287
289
  // call and another's HTTP call spend one bucket in one table.
288
290
  // A frame of its own over what `startServices` adopted, popped by its own undo — so stopping
289
291
  // these roles takes back exactly this install, whatever else stacked over or under it.
292
+ // Once, before any role serves: which roles core's `bootWarning` concerns, and its per-build
293
+ // marker store (`runtime-boot-warnings.ts`). Released by the stop, like every frame here.
294
+ const config = options.root === undefined ? undefined : await loadAppConfig(options.root);
295
+ const releaseWarnings = installRoleBootWarnings({
296
+ roles: selected,
297
+ config,
298
+ storage: options.runtime.storage,
299
+ env: options.env,
300
+ buildId: options.buildId,
301
+ });
302
+ started.push(async () => releaseWarnings());
290
303
  const limits = rateLimitStoreFor(options);
291
304
  const restoreLimits = limits === undefined ? () => undefined : installRateLimitStore(limits);
292
305
  started.push(async () => restoreLimits());
@@ -0,0 +1,65 @@
1
+ // The boot's half of core's `bootWarning`: the roles this process runs and the per-build memory —
2
+ // a zero-byte marker on the disk every pod of a deploy shares (`retained-assets-warned.ts`) —
3
+ // installed once by `startRoles`. The marker and storage modules load on the first `once: 'build'`
4
+ // claim, so a role that never says one evaluates neither.
5
+
6
+ import type { AppConfig, BuildOnceStore, Role } from '@ultimat3/core';
7
+ import { resolveEnvironment } from '@ultimat3/core';
8
+ import { installBootWarnings } from '@ultimat3/core/adapter';
9
+ import type { Storage } from '@ultimat3/storage';
10
+ import { retainedPrefix } from './retained-assets-layout';
11
+
12
+ /** The code whose marker predates the store: it keeps `<prefix>/warned/<role>/`. */
13
+ const RETAIN_UNDECLARED = 'X_ASSET_RETAIN_UNDECLARED';
14
+
15
+ /**
16
+ * Core's `once: 'build'` memory over `warnOncePerBuild`. The retain warning keeps the marker it
17
+ * always had, `<prefix>/warned/<role>/`; any other code is `<role>~<code>`, its own directory, so
18
+ * neither silences nor prunes the other. The app's own disks win over the host's, as every
19
+ * framework route reads them (`servedStorage`).
20
+ */
21
+ export function retainedBuildOnce(input: {
22
+ readonly storage: Storage;
23
+ readonly prefix: string;
24
+ readonly buildId: string;
25
+ }): BuildOnceStore {
26
+ return async (claim, say) => {
27
+ const [{ warnOncePerBuild }, { servedStorage }] = await Promise.all([
28
+ import('./retained-assets-warned'),
29
+ import('./runtime-storage'),
30
+ ]);
31
+ const storage = servedStorage(input.storage);
32
+ await warnOncePerBuild(
33
+ {
34
+ disk: () => storage.disk(),
35
+ prefix: input.prefix,
36
+ role: claim.code === RETAIN_UNDECLARED ? claim.role : `${claim.role}~${claim.code}`,
37
+ buildId: input.buildId,
38
+ },
39
+ say,
40
+ );
41
+ };
42
+ }
43
+
44
+ export interface RoleBootWarningsInput {
45
+ readonly roles: readonly Role[];
46
+ /** `undefined` with no `app.config.ts`: no app name to scope a marker by, so no build store. */
47
+ readonly config: Pick<AppConfig, 'name'> | undefined;
48
+ readonly storage: Storage;
49
+ readonly env: Readonly<Record<string, string | undefined>>;
50
+ readonly buildId: string;
51
+ }
52
+
53
+ /** Installs the booting roles and, with an app config, the build store. Returns the release. */
54
+ export function installRoleBootWarnings(input: RoleBootWarningsInput): () => void {
55
+ if (input.config === undefined) return installBootWarnings({ roles: input.roles });
56
+ const environment = resolveEnvironment({ env: input.env, fallback: 'production' });
57
+ return installBootWarnings({
58
+ roles: input.roles,
59
+ buildOnce: retainedBuildOnce({
60
+ storage: input.storage,
61
+ prefix: retainedPrefix(input.config.name, environment),
62
+ buildId: input.buildId,
63
+ }),
64
+ });
65
+ }
@@ -29,6 +29,7 @@ import type { AppConfig, CacheTierName } from '@ultimat3/core';
29
29
  import {
30
30
  backoffDelay,
31
31
  defineConfig,
32
+ failureStreak,
32
33
  finiteCount,
33
34
  isOutageMilestone,
34
35
  logger,
@@ -290,15 +291,23 @@ export function startCacheTiers(options: CacheTiersOptions): () => Promise<void>
290
291
  // delete too; this is the sender's half, and does not depend on hearing its own publish.)
291
292
  await purgeEdgeAgain(batch);
292
293
  };
294
+ // A flapping bus refuses the settle of every reconnect: one line per cause, one when it lands.
295
+ const settleFailures = failureStreak({
296
+ event: 'cache.broadcast.deferred-failed',
297
+ recoveredEvent: 'cache.broadcast.deferred-recovered',
298
+ level: 'warn',
299
+ });
293
300
  // ONE settle at a time. It is asked for by every reconnect and after every accepted publish,
294
301
  // and two that overlapped both published the same batch (and the same flush-all). A call that
295
302
  // arrives mid-run asks for one more pass instead, which finds whatever the run did not carry.
303
+ // The outcome is reported HERE, once per run: a joiner that reported it too counted one refused
304
+ // settle once per reconnect that joined it. Never rejects — what is unpublished stays owed.
296
305
  let settling: Promise<void> | undefined;
297
306
  let again = false;
298
- const settle = (): Promise<void> => {
307
+ const settleQuietly = (): void => {
299
308
  if (settling !== undefined) {
300
309
  again = true;
301
- return settling;
310
+ return;
302
311
  }
303
312
  settling = (async (): Promise<void> => {
304
313
  try {
@@ -306,17 +315,14 @@ export function startCacheTiers(options: CacheTiersOptions): () => Promise<void>
306
315
  again = false;
307
316
  await settleOnce();
308
317
  } while (again);
318
+ settleFailures.passed();
319
+ } catch (error) {
320
+ settleFailures.failed(error);
309
321
  } finally {
310
322
  again = false;
311
323
  settling = undefined;
312
324
  }
313
325
  })();
314
- return settling;
315
- };
316
- const settleQuietly = (): void => {
317
- void settle().catch((error: unknown) => {
318
- logger.warn('cache.broadcast.deferred-failed', { error: broadcastErrorText(error) });
319
- });
320
326
  };
321
327
 
322
328
  registerInvalidationBroadcast(async (wireTags) => {