@crvouga/homelab 0.25.0 → 0.26.1

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.
@@ -269,8 +269,21 @@ export async function serviceRecoveryCheck(run: Runner): Promise<Check> {
269
269
  );
270
270
  }
271
271
 
272
- /** The server answers its local API now, not merely that a process exists. */
273
- async function t3HealthCheck(run: Runner): Promise<Check> {
272
+ /** The retained first successful loopback probe, measured from this boot. */
273
+ async function bootToServingSeconds(run: Runner): Promise<number | null> {
274
+ const marker = await run([
275
+ 'cat',
276
+ `/run/user/${userInfo().uid}/personal-t3-boot-readiness-ms`,
277
+ ]);
278
+ const value = marker.stdout.trim();
279
+ const milliseconds = Number(value);
280
+ return marker.ok && /^\d+$/.test(value) && Number.isSafeInteger(milliseconds)
281
+ ? milliseconds / 1000
282
+ : null;
283
+ }
284
+
285
+ /** Check the current server independently of the boot readiness record. */
286
+ export async function t3HealthCheck(run: Runner): Promise<Check> {
274
287
  const probe = await run(
275
288
  [
276
289
  'curl',
@@ -282,21 +295,57 @@ async function t3HealthCheck(run: Runner): Promise<Check> {
282
295
  ],
283
296
  { timeoutMs: 15_000 }
284
297
  );
285
- let identified = false;
298
+ const answers = probe.ok && hasEnvironmentIdentity(probe.stdout);
299
+ const boot = answers ? await bootServing(run) : { late: false, summary: '' };
300
+ const ok = answers && !boot.late;
301
+ return {
302
+ id: 'worker:t3-health',
303
+ status: ok ? 'pass' : 'fail',
304
+ summary: boot.late
305
+ ? boot.summary
306
+ : `${answers ? 'T3 local API answers with its environment identity within 10 seconds.' : 'T3 local API did not answer with its environment identity within 10 seconds.'}${boot.summary}${await hangEvidence(run, userInfo().homedir)}`,
307
+ ...(!ok
308
+ ? {
309
+ remedy: {
310
+ action: boot.late
311
+ ? 'The first successful T3 loopback probe was later than t3Service.bootServingSeconds in ansible/ubuntu/policy.json. Read the journal of the T3 unit and of personal-worker-recovery for what delayed the start after boot.'
312
+ : 'Apply the approved converge revision over verified SSH, then rerun check --workers. No password prompt or state reset is attempted by health.',
313
+ },
314
+ }
315
+ : {}),
316
+ };
317
+ }
318
+
319
+ function hasEnvironmentIdentity(response: string): boolean {
286
320
  try {
287
- const value: unknown = JSON.parse(probe.stdout);
288
- identified =
321
+ const value: unknown = JSON.parse(response);
322
+ return (
289
323
  typeof value === 'object' &&
290
324
  value !== null &&
291
- typeof (value as Record<string, unknown>)['environmentId'] === 'string';
325
+ typeof (value as Record<string, unknown>)['environmentId'] === 'string'
326
+ );
292
327
  } catch {
293
- /* Raw responses are never reported. */
328
+ return false;
294
329
  }
295
- return check(
296
- 'worker:t3-health',
297
- probe.ok && identified,
298
- `T3 local API answers with its environment identity within 10 seconds.${await hangEvidence(run, userInfo().homedir)}`
299
- );
330
+ }
331
+
332
+ /** Compare the first successful loopback probe with the boot-serving deadline. */
333
+ async function bootServing(
334
+ run: Runner
335
+ ): Promise<{ late: boolean; summary: string }> {
336
+ const limit = policy.t3Service.bootServingSeconds;
337
+ const serving = await bootToServingSeconds(run);
338
+ if (serving === null)
339
+ return { late: false, summary: ' Boot readiness was not measured.' };
340
+ if (serving > limit)
341
+ return {
342
+ late: true,
343
+ summary: `T3_BOOT_SERVING_LATE: The first successful T3 loopback probe was ${serving} seconds after boot, past the ${limit} seconds a worker is given to serve after a power loss.`,
344
+ };
345
+ return {
346
+ late: false,
347
+ summary: ` The first successful T3 loopback probe was ${serving} seconds after boot (at most ${limit}).`,
348
+ };
300
349
  }
301
350
 
302
351
  const DAY_SECONDS = 86_400;
package/src/t3/profile.ts DELETED
@@ -1,204 +0,0 @@
1
- import { dirname, join } from 'node:path';
2
- import type { Check } from '../types';
3
- import { canonical, object, read, write } from './files';
4
- import { fleetJson } from '../fleet-config';
5
-
6
- /** What happens to one declared setting. `release` stops managing a key the
7
- * fleet no longer declares and leaves its value to the machine.
8
- */
9
- export type ProfileAction =
10
- 'create' | 'update' | 'delete' | 'release' | 'unchanged' | 'conflict';
11
- export type ProfileChange = { key: string; action: ProfileAction };
12
-
13
- /** The values the fleet last wrote, kept beside T3's settings: the base of
14
- * the three-way merge between what is declared, what T3 holds and what was
15
- * applied before.
16
- */
17
- export const profileRecord = (settings: string): string =>
18
- join(dirname(settings), 'personal-profile.json');
19
-
20
- const same = (a: unknown, b: unknown): boolean => canonical(a) === canonical(b);
21
-
22
- /** Managed keys converge, keys nobody declared are left alone, and a key
23
- * changed on the machine since the fleet last wrote it (or that existed
24
- * before the fleet declared it) is a conflict, never overwritten.
25
- */
26
- export function planProfile(
27
- settings: Record<string, unknown>,
28
- applied: Record<string, unknown>,
29
- declared: Record<string, unknown>
30
- ) {
31
- const next = { ...settings };
32
- const record = { ...applied };
33
- const changes: ProfileChange[] = [];
34
- const keys = [
35
- ...new Set([...Object.keys(declared), ...Object.keys(applied)]),
36
- ].sort();
37
- for (const key of keys) {
38
- const present = Object.hasOwn(settings, key);
39
- const managed = Object.hasOwn(applied, key);
40
- const action = actionFor(key, declared, {
41
- present,
42
- managed,
43
- current: settings[key],
44
- base: applied[key],
45
- });
46
- changes.push({ key, action });
47
- if (action === 'create' || action === 'update') {
48
- next[key] = declared[key];
49
- record[key] = declared[key];
50
- } else if (action === 'unchanged') record[key] = declared[key];
51
- else if (action === 'delete') {
52
- delete next[key];
53
- delete record[key];
54
- } else if (action === 'release') delete record[key];
55
- }
56
- return {
57
- settings: next,
58
- record,
59
- changes,
60
- settingsChanged: !same(next, settings),
61
- recordChanged: !same(record, applied),
62
- };
63
- }
64
-
65
- function actionFor(
66
- key: string,
67
- declared: Record<string, unknown>,
68
- {
69
- present,
70
- managed,
71
- current,
72
- base,
73
- }: { present: boolean; managed: boolean; current: unknown; base: unknown }
74
- ): ProfileAction {
75
- if (!Object.hasOwn(declared, key)) {
76
- if (present && same(current, base)) return 'delete';
77
- return 'release';
78
- }
79
- const wanted = declared[key];
80
- if (present && same(current, wanted)) return 'unchanged';
81
- if (!present) return managed ? 'conflict' : 'create';
82
- return managed && same(current, base) ? 'update' : 'conflict';
83
- }
84
-
85
- export interface ProfileOptions {
86
- apply: boolean;
87
- /** Tries before a settings file T3 keeps rewriting is reported busy. */
88
- attempts?: number;
89
- pause?: () => Promise<void>;
90
- /** Runs between the read and the write: where T3 may write too. */
91
- beforeWrite?: () => Promise<void>;
92
- }
93
-
94
- /** Plans, and with `apply` writes, the declared profile. T3 writes the same
95
- * file and offers no compare-and-swap, so a write happens only when the file
96
- * is still what was read; otherwise the merge is planned again, a bounded
97
- * number of times.
98
- */
99
- export async function reconcileProfile(
100
- settingsPath: string,
101
- declared: Record<string, unknown>,
102
- options: ProfileOptions
103
- ) {
104
- const recordPath = profileRecord(settingsPath);
105
- const attempts = options.attempts ?? 3;
106
- const pause =
107
- options.pause ?? (() => new Promise((done) => setTimeout(done, 500)));
108
- for (let attempt = 1; ; attempt++) {
109
- const raw = await read(settingsPath);
110
- const recordRaw = await read(recordPath);
111
- const plan = planProfile(
112
- object(raw),
113
- readRecord(recordRaw, settingsPath),
114
- declared
115
- );
116
- if (!options.apply || (!plan.settingsChanged && !plan.recordChanged))
117
- return { ...plan, applied: false };
118
- await options.beforeWrite?.();
119
- if (!plan.settingsChanged || (await read(settingsPath)) === raw) {
120
- if (plan.settingsChanged)
121
- await write(
122
- settingsPath,
123
- JSON.stringify(plan.settings, null, 2) + '\n'
124
- );
125
- await write(
126
- recordPath,
127
- canonical({ version: 1, target: settingsPath, settings: plan.record }) +
128
- '\n'
129
- );
130
- return { ...plan, applied: true };
131
- }
132
- if (attempt >= attempts) throw new Error('T3_SETTINGS_BUSY');
133
- await pause();
134
- }
135
- }
136
-
137
- function readRecord(
138
- raw: string | null,
139
- target: string
140
- ): Record<string, unknown> {
141
- if (raw === null) return {};
142
- const record = object(raw);
143
- if (record['version'] !== 1 || record['target'] !== target)
144
- throw new Error('T3_PROFILE_RECORD_INVALID');
145
- return object(JSON.stringify(record['settings'] ?? {}));
146
- }
147
-
148
- /** `t3:profile`: the declared settings on this machine. A report names the
149
- * keys and what happens to them, never a value: a tool server's settings may
150
- * carry a credential.
151
- */
152
- export async function profileCheck(
153
- settingsPath: string,
154
- declared: Record<string, unknown>,
155
- options: ProfileOptions
156
- ): Promise<Check> {
157
- const remedy = (action: string) => ({ remedy: { action } });
158
- try {
159
- const result = await reconcileProfile(settingsPath, declared, options);
160
- const conflicts = result.changes.filter(
161
- (change) => change.action === 'conflict'
162
- );
163
- if (conflicts.length)
164
- return {
165
- id: 't3:profile',
166
- status: 'warn',
167
- summary: 'T3_PROFILE_CONFLICT',
168
- ...remedy(
169
- `These T3 settings were changed on this machine since homelab last wrote them, or existed before they were declared, and were left as they are: ${conflicts.map((change) => change.key).join(', ')}. Put the value every machine should hold under t3.profile in ${fleetJson()}, or remove the setting on this machine, then run converge.`
170
- ),
171
- };
172
- const pending = result.changes.filter(
173
- (change) => !['unchanged', 'conflict'].includes(change.action)
174
- );
175
- if (!options.apply && pending.length)
176
- return {
177
- id: 't3:profile',
178
- status: 'warn',
179
- summary: 'T3_PROFILE_PENDING',
180
- ...remedy(
181
- `converge would change these T3 settings: ${pending.map((change) => `${change.key} (${change.action})`).join(', ')}.`
182
- ),
183
- };
184
- return {
185
- id: 't3:profile',
186
- status: 'pass',
187
- summary: Object.keys(declared).length
188
- ? 'T3 on this machine holds every setting of the declared profile; settings nobody declared are its own.'
189
- : 'No T3 profile is declared; every setting stays local.',
190
- };
191
- } catch (error) {
192
- const busy = error instanceof Error && error.message === 'T3_SETTINGS_BUSY';
193
- return {
194
- id: 't3:profile',
195
- status: 'fail',
196
- summary: busy ? 'T3_SETTINGS_BUSY' : 'T3_PROFILE_UNVERIFIED',
197
- ...remedy(
198
- busy
199
- ? 'T3 kept rewriting its settings while homelab merged the profile. Run converge again; nothing was overwritten.'
200
- : 'Repair T3’s settings.json (or restore personal-profile.json from a backup) on this machine, then run converge.'
201
- ),
202
- };
203
- }
204
- }