@crvouga/homelab 0.24.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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
- }