@ultimat3/cli 31.28.0 → 31.29.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.
@@ -0,0 +1,178 @@
1
+ // The panel table of the Grafana dashboard every Ultimate chart ships: requests, latency, statements,
2
+ // pool, jobs, realtime, the process, the Postgres server and the framework schema, over the series
3
+ // the framework declares. `chart-dashboard.ts` renders it as Grafana's JSON model.
4
+
5
+ export interface DashboardTarget {
6
+ readonly expr: string;
7
+ /** Grafana's legend template, `{{label}}` interpolated per series. */
8
+ readonly legend: string;
9
+ }
10
+
11
+ export interface DashboardPanel {
12
+ readonly title: string;
13
+ /** Grafana's unit id: `reqps`, `s`, `bytes`, `percentunit`, `short`. */
14
+ readonly unit: string;
15
+ readonly targets: readonly DashboardTarget[];
16
+ }
17
+
18
+ /** One release in one namespace — the two labels the ServiceMonitor puts on every series. */
19
+ const SCOPE = 'namespace="$namespace",app_kubernetes_io_instance="$release"';
20
+ const RATE = '[$__rate_interval]';
21
+
22
+ const s = (name: string, extra?: string): string =>
23
+ `${name}{${extra === undefined ? SCOPE : `${SCOPE},${extra}`}}`;
24
+
25
+ const p = (q: number, name: string, by: string): string =>
26
+ `histogram_quantile(${String(q)}, sum by (${by}, le) (rate(${s(`${name}_bucket`)}${RATE})))`;
27
+
28
+ export const DASHBOARD_PANELS: readonly DashboardPanel[] = [
29
+ {
30
+ title: 'Requests per second, by status class',
31
+ unit: 'reqps',
32
+ targets: [
33
+ { expr: `sum by (status) (rate(${s('http_requests_total')}${RATE}))`, legend: '{{status}}' },
34
+ ],
35
+ },
36
+ {
37
+ title: 'Latency p95, by route',
38
+ unit: 's',
39
+ targets: [{ expr: p(0.95, 'http_request_duration_seconds', 'route'), legend: '{{route}}' }],
40
+ },
41
+ {
42
+ title: '5xx share of requests',
43
+ unit: 'percentunit',
44
+ targets: [
45
+ {
46
+ expr: `sum(rate(${s('http_requests_total', 'status="5xx"')}${RATE})) / sum(rate(${s('http_requests_total')}${RATE}))`,
47
+ legend: '5xx',
48
+ },
49
+ ],
50
+ },
51
+ {
52
+ title: 'Statement p95, by operation',
53
+ unit: 's',
54
+ targets: [
55
+ {
56
+ expr: p(0.95, 'db_client_operation_duration_seconds', 'db_operation_name'),
57
+ legend: 'p95 {{db_operation_name}}',
58
+ },
59
+ ],
60
+ },
61
+ {
62
+ title: 'Database pool, by pod',
63
+ unit: 'short',
64
+ targets: [
65
+ { expr: `sum by (pod) (${s('db_pool_in_use')})`, legend: 'in use {{pod}}' },
66
+ { expr: `sum by (pod) (${s('db_pool_waiting')})`, legend: 'waiting {{pod}}' },
67
+ { expr: `sum by (pod) (${s('db_pool_max')})`, legend: 'max {{pod}}' },
68
+ ],
69
+ },
70
+ {
71
+ title: 'Jobs per second, by queue and outcome',
72
+ unit: 'short',
73
+ targets: [
74
+ {
75
+ expr: `sum by (queue, outcome) (rate(${s('jobs_total')}${RATE}))`,
76
+ legend: '{{queue}} {{outcome}}',
77
+ },
78
+ ],
79
+ },
80
+ {
81
+ title: 'Queue: oldest ready job and dead letters',
82
+ unit: 's',
83
+ targets: [
84
+ { expr: `max by (queue) (${s('queue_oldest_ready_seconds')})`, legend: 'oldest {{queue}}' },
85
+ { expr: `max by (queue) (${s('queue_dead_jobs')})`, legend: 'dead {{queue}}' },
86
+ ],
87
+ },
88
+ {
89
+ title: 'Job duration p95, by queue',
90
+ unit: 's',
91
+ targets: [{ expr: p(0.95, 'job_duration_seconds', 'queue'), legend: '{{queue}}' }],
92
+ },
93
+ {
94
+ title: 'Realtime: connections and dropped frames',
95
+ unit: 'short',
96
+ targets: [
97
+ { expr: `sum by (pod) (${s('connections')})`, legend: 'connections {{pod}}' },
98
+ {
99
+ expr: `sum(rate(${s('channel_frames_dropped_total')}${RATE}))`,
100
+ legend: 'frames dropped/s',
101
+ },
102
+ ],
103
+ },
104
+ {
105
+ title: 'Memory: RSS over the container limit, by pod',
106
+ unit: 'percentunit',
107
+ targets: [
108
+ {
109
+ expr: `max by (pod) (${s('process_resident_memory_bytes')} / ${s('process_memory_limit_bytes')})`,
110
+ legend: '{{pod}}',
111
+ },
112
+ ],
113
+ },
114
+ {
115
+ title: 'CPU seconds per second, by pod',
116
+ unit: 'short',
117
+ targets: [
118
+ { expr: `sum by (pod) (rate(${s('process_cpu_seconds_total')}${RATE}))`, legend: '{{pod}}' },
119
+ ],
120
+ },
121
+ {
122
+ title: 'Event-loop lag p99, by pod',
123
+ unit: 's',
124
+ targets: [{ expr: p(0.99, 'process_event_loop_lag_seconds', 'pod'), legend: '{{pod}}' }],
125
+ },
126
+ {
127
+ title: 'Restarts in the last hour, by role',
128
+ unit: 'short',
129
+ targets: [
130
+ {
131
+ expr: `sum by (app_kubernetes_io_component) (changes(${s('process_start_time_seconds')}[1h]))`,
132
+ legend: '{{app_kubernetes_io_component}}',
133
+ },
134
+ ],
135
+ },
136
+ {
137
+ title: 'Postgres: client connections against max_connections',
138
+ unit: 'short',
139
+ targets: [
140
+ { expr: `max(${s('db_server_connections')})`, legend: 'connections' },
141
+ { expr: `max(${s('db_server_max_connections')})`, legend: 'max_connections' },
142
+ ],
143
+ },
144
+ {
145
+ title: 'Postgres: longest open transaction',
146
+ unit: 's',
147
+ targets: [{ expr: `max(${s('db_longest_transaction_seconds')})`, legend: 'longest' }],
148
+ },
149
+ {
150
+ title: 'Postgres: autovacuum backlog, the worst table (1 = due)',
151
+ unit: 'short',
152
+ targets: [{ expr: `max(${s('db_autovacuum_backlog_ratio')})`, legend: 'dead / trigger' }],
153
+ },
154
+ {
155
+ title: 'Postgres: WAL retained, by replication slot',
156
+ unit: 'bytes',
157
+ targets: [
158
+ {
159
+ expr: `max by (slot) (${s('db_replication_slot_retained_bytes')})`,
160
+ legend: '{{slot}}',
161
+ },
162
+ ],
163
+ },
164
+ {
165
+ title: 'Framework schema: unapplied and major skew, by role',
166
+ unit: 'short',
167
+ targets: [
168
+ {
169
+ expr: `count by (app_kubernetes_io_component) (${s('framework_schema_applied')} == 0)`,
170
+ legend: 'unapplied {{app_kubernetes_io_component}}',
171
+ },
172
+ {
173
+ expr: `max by (app_kubernetes_io_component) (${s('framework_schema_major_skew')})`,
174
+ legend: 'skew {{app_kubernetes_io_component}}',
175
+ },
176
+ ],
177
+ },
178
+ ];
@@ -2,140 +2,11 @@
2
2
  // pool, jobs, realtime and the process, over the series the framework declares. One column of
3
3
  // full-width panels, so a phone reads it as it is. The JSON and its ConfigMap are generated here;
4
4
  // `docker/helm/` holds these bytes for the chart named `ultimate`.
5
+ import { DASHBOARD_PANELS, type DashboardPanel } from './chart-dashboard-panels';
5
6
  import type { GeneratedFile, NameSet } from './naming';
6
7
 
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
- ];
8
+ export type { DashboardPanel, DashboardTarget } from './chart-dashboard-panels';
9
+ export { DASHBOARD_PANELS } from './chart-dashboard-panels';
139
10
 
140
11
  /** The stable uid a provisioned dashboard keeps across upgrades, so a bookmark survives. */
141
12
  export const DASHBOARD_UID = 'ultimate-app';
@@ -156,8 +27,11 @@ const variable = (name: string, query: string) => ({
156
27
 
157
28
  const PANEL_HEIGHT = 8;
158
29
 
159
- /** The dashboard as Grafana's JSON model, two-space indented, one trailing newline. */
160
- export function dashboardJson(): string {
30
+ /**
31
+ * The dashboard as Grafana's JSON model, two-space indented, one trailing newline. `panels` is a
32
+ * seam for a codemod's test, which re-renders an older release's panel list.
33
+ */
34
+ export function dashboardJson(panels: readonly DashboardPanel[] = DASHBOARD_PANELS): string {
161
35
  const model = {
162
36
  uid: DASHBOARD_UID,
163
37
  title: 'Ultimate app',
@@ -176,7 +50,7 @@ export function dashboardJson(): string {
176
50
  ),
177
51
  ],
178
52
  },
179
- panels: DASHBOARD_PANELS.map((panel, index) => ({
53
+ panels: panels.map((panel, index) => ({
180
54
  id: index + 1,
181
55
  type: 'timeseries',
182
56
  title: panel.title,
@@ -243,7 +243,7 @@ that no longer matches an applied migration stops the release instead of corrupt
243
243
  | Render | \`preDeployCommand: ROLE=migrate bun apps/web/server.ts\` |
244
244
  | Fly.io | \`[deploy] release_command = "bun apps/web/server.ts"\` with \`ROLE=migrate\` |
245
245
  | Railway | a pre-deploy command running the same |
246
- | Kubernetes | an \`initContainer\` or a \`Job\` on the same image with \`ROLE=migrate\` |
246
+ | Kubernetes | the chart's one \`migrate\` Job on the same image (\`docker/helm\`), ordered before every role — never a per-pod \`initContainer\` |
247
247
  | Compose | the \`migrate\` service; every other role waits on \`service_completed_successfully\` |
248
248
 
249
249
  There is no \`x db migrate\` in that list on purpose: it is the developer's command and it needs the
@@ -288,7 +288,7 @@ somebody else's repository is a command that cannot run. \`--image\` sets \`imag
288
288
  | Object | Per | Note |
289
289
  |---|---|---|
290
290
  | Deployment + Service | enabled role | one image, \`ROLE\` and the port are the only difference |
291
- | Job | release | \`ROLE=migrate\`, a \`pre-install,pre-upgrade\` hook — it runs to completion first |
291
+ | Job | release | \`ROLE=migrate\`, run to completion first: a \`pre-install,pre-upgrade,pre-rollback\` hook, an Argo CD \`Sync\` hook in wave -1, and named by its image so any other applier gets a new Job per image |
292
292
  | Ingress | release | off by default; routes \`/_x/sync\` to sync and \`/\` to web |
293
293
  | HorizontalPodAutoscaler | role, opt-in | rps, websocket connections, queue depth — never CPU |
294
294
  | ServiceMonitor | release | scrapes \`/metrics\` on \`metricsPort\`, every serving role |
@@ -0,0 +1,105 @@
1
+ // The chart's rules past the request path: latency, the Postgres server (connections, long
2
+ // transactions, autovacuum, replication-slot WAL), the framework schema a rollout must apply first,
3
+ // and the volumes a namespace's claims fill. Joined into `CHART_ALERTS`; type-only imports, so no cycle.
4
+
5
+ import type { AlertScope, ChartAlert } from './scaffold-helm-alert-rules';
6
+
7
+ type Rule = Omit<ChartAlert, 'anchor'>;
8
+
9
+ /** `docs/ops/06-runbooks.md`'s heading for the rule: its name, lower-cased. */
10
+ const rule = (alert: Rule): ChartAlert => ({ ...alert, anchor: alert.alert.toLowerCase() });
11
+
12
+ /** 1 GiB of WAL held for one slot: minutes of a busy primary, hours of a quiet one. */
13
+ const SLOT_RETAINED_BYTES = 1_073_741_824;
14
+
15
+ const max = (s: AlertScope, series: string, extra = ''): string =>
16
+ `max by (${s.by}${extra}) (${s.series(series)})`;
17
+
18
+ export const DEPLOY_ALERTS: readonly ChartAlert[] = [
19
+ rule({
20
+ alert: 'UltimateRequestLatency',
21
+ threshold: 1,
22
+ // Release-wide, never per route: a mechanism's floor, not the app's latency objective — an app
23
+ // with one sets its own threshold, or a per-route rule of its own.
24
+ expr: (s) =>
25
+ `histogram_quantile(0.95, sum by (${s.by}, le) ` +
26
+ `(rate(${s.series('http_request_duration_seconds_bucket')}[5m]))) > ${s.threshold(1)}`,
27
+ for: '10m',
28
+ severity: 'warning',
29
+ summary: 'The p95 of request duration is above the threshold, in seconds',
30
+ }),
31
+ rule({
32
+ alert: 'UltimateConnectionsNearMax',
33
+ threshold: 0.8,
34
+ expr: (s) =>
35
+ `max by (${s.by}) (${s.series('db_server_connections')} / ` +
36
+ `${s.series('db_server_max_connections')}) > ${s.threshold(0.8)}`,
37
+ for: '10m',
38
+ severity: 'warning',
39
+ summary: "The Postgres server's open connections are near its max_connections",
40
+ }),
41
+ rule({
42
+ alert: 'UltimateLongTransaction',
43
+ threshold: 300,
44
+ expr: (s) => `${max(s, 'db_longest_transaction_seconds')} > ${s.threshold(300)}`,
45
+ for: '5m',
46
+ severity: 'warning',
47
+ summary: 'A transaction has been open longer than the threshold, holding back vacuum and locks',
48
+ }),
49
+ rule({
50
+ alert: 'UltimateAutovacuumLag',
51
+ threshold: 2,
52
+ expr: (s) => `${max(s, 'db_autovacuum_backlog_ratio')} > ${s.threshold(2)}`,
53
+ for: '30m',
54
+ severity: 'warning',
55
+ summary:
56
+ 'A table holds more dead tuples than its autovacuum trigger, and is not being vacuumed',
57
+ }),
58
+ rule({
59
+ alert: 'UltimateReplicationSlotRetention',
60
+ threshold: SLOT_RETAINED_BYTES,
61
+ expr: (s) =>
62
+ `${max(s, 'db_replication_slot_retained_bytes', ', slot')} > ${s.threshold(SLOT_RETAINED_BYTES)}`,
63
+ for: '15m',
64
+ severity: 'warning',
65
+ summary: 'A replication slot holds more WAL on the primary than the threshold, in bytes',
66
+ }),
67
+ rule({
68
+ alert: 'UltimateDbStatsStale',
69
+ // The four rules above read gauges a failed round leaves at their last value: without this, a
70
+ // dead sampler keeps every one of them quiet.
71
+ expr: (s) => `count by (${s.by}) (${s.series('db_stats_sample_ok')} == 0) > 0`,
72
+ for: '15m',
73
+ severity: 'warning',
74
+ summary:
75
+ 'The Postgres stats sampler is failing: the connection, transaction, autovacuum and slot values are stale',
76
+ }),
77
+ rule({
78
+ alert: 'UltimateSchemaUnapplied',
79
+ expr: (s) =>
80
+ `count by (${s.by}, ${s.component}) (${s.series('framework_schema_applied')} == 0) > 0`,
81
+ for: '10m',
82
+ severity: 'critical',
83
+ summary:
84
+ "A role is waiting: its build's framework schema or app migrations are not applied (x db migrate)",
85
+ }),
86
+ rule({
87
+ alert: 'UltimateVersionSkew',
88
+ expr: (s) => `${max(s, 'framework_schema_major_skew')} > 0`,
89
+ for: '30m',
90
+ severity: 'warning',
91
+ summary: 'Roles run a different major than the newest applied framework schema',
92
+ }),
93
+ rule({
94
+ alert: 'UltimateVolumeNearFull',
95
+ threshold: 0.85,
96
+ // The kubelet's series, per claim in the release's namespace: the chart mounts no claim, so the
97
+ // volumes this reads are its neighbours' — the database's, most often.
98
+ expr: (s) =>
99
+ `max by (namespace, persistentvolumeclaim) (${s.namespaced('kubelet_volume_stats_used_bytes')} / ` +
100
+ `${s.namespaced('kubelet_volume_stats_capacity_bytes')}) > ${s.threshold(0.85)}`,
101
+ for: '15m',
102
+ severity: 'warning',
103
+ summary: "A persistent volume in the release's namespace is fuller than the threshold",
104
+ }),
105
+ ];
@@ -1,11 +1,16 @@
1
1
  // The rule table every Ultimate chart's alerts are written from, renderer-neutral. Only mechanism
2
2
  // ships (axiom 8): a stalled queue, a dead letter, a lost lease, a dropped frame, error-budget burn,
3
- // job failures, pool, loop and memory saturation, a dead target. A latency target is the app's.
3
+ // job failures, pool, loop and memory saturation, a dead target — and `DEPLOY_ALERTS`' rest. A
4
+ // latency OBJECTIVE is the app's: the shipped latency rule is a generous floor it overrides.
5
+
6
+ import { DEPLOY_ALERTS } from './scaffold-helm-alert-deploy';
4
7
 
5
8
  /** How an expression names a series and groups its result, per renderer. */
6
9
  export interface AlertScope {
7
10
  /** `name{matchers}` — the scope's own matchers, then `extra`. */
8
11
  readonly series: (name: string, extra?: string) => string;
12
+ /** `name{namespace}` — a series the release does not emit (the kubelet's), scoped to its namespace. */
13
+ readonly namespaced: (name: string) => string;
9
14
  /** The labels every rule groups by, so one release (or one job) fires one alert. */
10
15
  readonly by: string;
11
16
  /** The label naming a scrape target's role. */
@@ -157,4 +162,5 @@ export const CHART_ALERTS: readonly ChartAlert[] = [
157
162
  severity: 'critical',
158
163
  summary: 'A role has a scrape target that is down',
159
164
  }),
165
+ ...DEPLOY_ALERTS,
160
166
  ];
@@ -19,6 +19,7 @@ const matchers = (own: string, extra?: string): string =>
19
19
  export const K8S_SCOPE: AlertScope = {
20
20
  series: (name, extra) =>
21
21
  `${name}{${matchers('namespace="{{ $.Release.Namespace }}",app_kubernetes_io_instance="{{ $.Release.Name }}"', extra)}}`,
22
+ namespaced: (name) => `${name}{namespace="{{ $.Release.Namespace }}"}`,
22
23
  by: 'namespace, app_kubernetes_io_instance',
23
24
  component: 'app_kubernetes_io_component',
24
25
  // The operator's own target label: one pod, whichever role it runs.
@@ -32,6 +33,8 @@ const plainScope = (own: string, objective: number): AlertScope => ({
32
33
  const inner = matchers(own, extra);
33
34
  return inner === '' ? name : `${name}{${inner}}`;
34
35
  },
36
+ // Outside Kubernetes no kubelet is scraped: the bare name matches what the loader has, if anything.
37
+ namespaced: (name) => name,
35
38
  by: 'job',
36
39
  component: 'instance',
37
40
  target: 'instance',
@@ -0,0 +1,85 @@
1
+ // The scaffolded chart's release phase: the one migrate Job, ordered before every role under helm,
2
+ // under Argo CD, and as an ordinary object under an applier that ignores both. Split from
3
+ // scaffold-helm-templates.ts; `docker/helm/templates/migrate-job.yaml` is the framework's copy.
4
+
5
+ import type { GeneratedFile, NameSet } from './naming';
6
+
7
+ export const MIGRATE_JOB_PATH = 'docker/helm/templates/migrate-job.yaml';
8
+
9
+ const migrateJob = (app: NameSet): string => `{{/*
10
+ The release phase: ROLE=migrate applies every pending migration under an advisory lock and exits,
11
+ before any serving role starts. Same image, same entry point — there is no second migration engine
12
+ and no toolchain in the container. ONE Job, ordered by whichever applier renders it:
13
+
14
+ helm (and Flux's helm-controller) a pre-install / pre-upgrade / pre-rollback hook: no role is
15
+ touched until it has succeeded. On a rollback it is the OLDER
16
+ build's migrate, which refuses a ledger a newer build left
17
+ destructive rows in (X_MIGRATION_ROLLBACK_DESTRUCTIVE) before
18
+ any role is rolled back onto it
19
+ Argo CD a Sync hook in wave -1. Its own annotation wins over the Helm
20
+ one Argo would otherwise map to PreSync — the phase that runs
21
+ before EVERY wave, so a database the same sync creates was
22
+ waited on forever. Put that database and the Secret the Job
23
+ reads in wave -2 or lower; every role sits in wave 0
24
+ an applier that ignores both an ordinary object, applied beside the roles. Its name hashes
25
+ (kubectl apply, a rendered tree) the image, the migrate block and the chart version, so a new
26
+ image is a new Job rather than an immutable-field refusal of
27
+ the whole apply (an env change alone is still refused: change
28
+ migrate.*, or delete the Job); the roles wait for the stamp it
29
+ leaves, unready, and maxUnavailable: 0 keeps the old pods
30
+ serving meanwhile
31
+
32
+ No init container on any role: a per-pod migrate is a second mechanism, run once per pod, and it
33
+ only ever ordered the Deployment that carried it. Deleted once it succeeds (hook-succeeded, which
34
+ Argo CD honours too); a failed one stays for kubectl logs until migrate.ttlSecondsAfterFinished (a day)
35
+ collects it. A retry of the same image replaces it sooner; a new image's Job has another name and
36
+ never does.
37
+ */}}
38
+ {{- if .Values.migrate.enabled }}
39
+ apiVersion: batch/v1
40
+ kind: Job
41
+ metadata:
42
+ {{- /*
43
+ The name hashes what should make a new Job — the image, the migrate block and the chart version —
44
+ and NEVER the rendered pod: an inline env value would be guessable from 32 bits of its hash.
45
+ 46 + "-migrate-" + 8 = 63, the ceiling of the job-name label every pod of it carries.
46
+ */}}
47
+ {{- $inputs := printf "%s|%s|%s" (include "${app.kebab}.image" .) (toYaml .Values.migrate) .Chart.Version }}
48
+ name: {{ printf "%s-migrate-%s" (include "${app.kebab}.fullname" . | trunc 46 | trimSuffix "-") ($inputs | sha256sum | trunc 8) }}
49
+ labels:
50
+ {{- include "${app.kebab}.labels" . | nindent 4 }}
51
+ app.kubernetes.io/component: migrate
52
+ annotations:
53
+ helm.sh/hook: pre-install,pre-upgrade,pre-rollback
54
+ helm.sh/hook-weight: "-5"
55
+ helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded
56
+ argocd.argoproj.io/hook: Sync
57
+ argocd.argoproj.io/sync-wave: "-1"
58
+ spec:
59
+ backoffLimit: {{ .Values.migrate.backoffLimit }}
60
+ {{- /*
61
+ Collected a day after it finishes unless migrate.ttlSecondsAfterFinished says otherwise: the one
62
+ cleanup an applier that ignores hooks gets. Such an applier that reconciles re-creates a collected
63
+ Job on its next pass, which re-runs a migrate with nothing to apply.
64
+ */}}
65
+ ttlSecondsAfterFinished: {{ ternary .Values.migrate.ttlSecondsAfterFinished 86400 (hasKey .Values.migrate "ttlSecondsAfterFinished") | int }}
66
+ template:
67
+ metadata:
68
+ labels:
69
+ {{- include "${app.kebab}.labels" . | nindent 8 }}
70
+ app.kubernetes.io/component: migrate
71
+ spec:
72
+ restartPolicy: Never
73
+ automountServiceAccountToken: false
74
+ securityContext: {{- toYaml .Values.podSecurityContext | nindent 8 }}
75
+ containers:
76
+ {{- include "${app.kebab}.container" (dict "role" "migrate" "cfg" .Values.migrate "root" .) | nindent 8 }}
77
+ volumes:
78
+ {{- include "${app.kebab}.tmpVolume" . | nindent 8 }}
79
+ {{- end }}
80
+ `;
81
+
82
+ /** The chart's migrate Job, as `x new` writes it. */
83
+ export function helmMigrateFile(app: NameSet): GeneratedFile {
84
+ return { path: MIGRATE_JOB_PATH, contents: migrateJob(app) };
85
+ }
@@ -6,6 +6,7 @@ import { helmDashboardFiles } from './chart-dashboard';
6
6
  import type { GeneratedFile, NameSet } from './naming';
7
7
  import { helmMonitoringFiles } from './scaffold-helm-alerts';
8
8
  import { helmFenceFiles } from './scaffold-helm-fences';
9
+ import { helmMigrateFile } from './scaffold-helm-migrate';
9
10
 
10
11
  const helpers = (
11
12
  app: NameSet,
@@ -325,41 +326,6 @@ spec:
325
326
  {{- end }}
326
327
  `;
327
328
 
328
- const migrateJob = (app: NameSet): string => `{{/*
329
- The release phase, as a pre-install / pre-upgrade hook: ROLE=migrate applies every pending
330
- migration under an advisory lock and exits, before any serving role starts. Same image, same entry
331
- point — there is no second migration engine and no toolchain in the container.
332
- */}}
333
- {{- if .Values.migrate.enabled }}
334
- apiVersion: batch/v1
335
- kind: Job
336
- metadata:
337
- name: {{ include "${app.kebab}.fullname" . }}-migrate
338
- labels:
339
- {{- include "${app.kebab}.labels" . | nindent 4 }}
340
- app.kubernetes.io/component: migrate
341
- annotations:
342
- helm.sh/hook: pre-install,pre-upgrade
343
- helm.sh/hook-weight: "-5"
344
- helm.sh/hook-delete-policy: before-hook-creation
345
- spec:
346
- backoffLimit: {{ .Values.migrate.backoffLimit }}
347
- template:
348
- metadata:
349
- labels:
350
- {{- include "${app.kebab}.labels" . | nindent 8 }}
351
- app.kubernetes.io/component: migrate
352
- spec:
353
- restartPolicy: Never
354
- automountServiceAccountToken: false
355
- securityContext: {{- toYaml .Values.podSecurityContext | nindent 8 }}
356
- containers:
357
- {{- include "${app.kebab}.container" (dict "role" "migrate" "cfg" .Values.migrate "root" .) | nindent 8 }}
358
- volumes:
359
- {{- include "${app.kebab}.tmpVolume" . | nindent 8 }}
360
- {{- end }}
361
- `;
362
-
363
329
  const ingress = (
364
330
  app: NameSet,
365
331
  ): string => `{{/* Standard ingress, no vendor edge primitives. Off by default: the host is yours to name. */}}
@@ -467,7 +433,7 @@ export function helmTemplateFiles(app: NameSet): readonly GeneratedFile[] {
467
433
  { path: 'docker/helm/templates/_helpers.tpl', contents: helpers(app) },
468
434
  { path: 'docker/helm/templates/deployments.yaml', contents: deployments(app) },
469
435
  { path: 'docker/helm/templates/service.yaml', contents: service(app) },
470
- { path: 'docker/helm/templates/migrate-job.yaml', contents: migrateJob(app) },
436
+ helmMigrateFile(app),
471
437
  { path: 'docker/helm/templates/ingress.yaml', contents: ingress(app) },
472
438
  { path: 'docker/helm/templates/hpa.yaml', contents: hpa(app) },
473
439
  ...helmFenceFiles(app),
@@ -191,6 +191,7 @@ minReadySeconds: 10
191
191
  migrate:
192
192
  enabled: true
193
193
  backoffLimit: 1
194
+ ttlSecondsAfterFinished: 86400 # a finished Job, and its logs, are collected after a day
194
195
  resources:
195
196
  requests: { cpu: 100m, memory: 128Mi }
196
197
  limits: { memory: 512Mi }