@twinsearth/timemachine-dsh-plugin 0.2.1 → 0.2.3
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/CHANGELOG.md +39 -0
- package/README.md +51 -9
- package/docs/ARCHITECTURE.md +37 -1
- package/docs/REQUIREMENTS.md +11 -0
- package/docs/TESTPLAN.md +34 -6
- package/lib/client.js +144 -6
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/src/guide-repair.mjs +387 -0
- package/src/plugin.mjs +33 -1
- package/src/point.mjs +2 -2
- package/src/service.mjs +75 -2
- package/src/telemetry.mjs +363 -0
- package/src/version.mjs +2 -0
|
@@ -0,0 +1,363 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Install identity, lease heartbeat and remote statistics for Time Machine.
|
|
3
|
+
*
|
|
4
|
+
* The install token is the only identity: a fresh directory (or a fresh
|
|
5
|
+
* install) creates a new token and is counted once. Restarting the same
|
|
6
|
+
* directory reuses the token. If the install directory is read-only, a stable
|
|
7
|
+
* path + hostname digest is used instead, which keeps restarts stable but
|
|
8
|
+
* cannot distinguish a reinstall in the same path.
|
|
9
|
+
*/
|
|
10
|
+
import crypto from 'node:crypto';
|
|
11
|
+
import fs from 'node:fs';
|
|
12
|
+
import os from 'node:os';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
import { fileURLToPath } from 'node:url';
|
|
15
|
+
|
|
16
|
+
import { PLUGIN_VERSION } from './version.mjs';
|
|
17
|
+
|
|
18
|
+
export const DEFAULT_TELEMETRY_URL = 'http://43.142.74.71:38081';
|
|
19
|
+
export const TOKEN_FILE = '.timemachine-install-token';
|
|
20
|
+
export const LEASE_MS = 399 * 60 * 1000;
|
|
21
|
+
export const CYCLE_MS = 3 * 60 * 60 * 1000;
|
|
22
|
+
export const STATS_CACHE_MS = 30 * 1000;
|
|
23
|
+
export const RECONNECT_COOLDOWN_MS = 400 * 60 * 1000;
|
|
24
|
+
|
|
25
|
+
const TOKEN_RE = /^[A-Za-z0-9_-]{16,128}$/u;
|
|
26
|
+
const START_DELAY_MIN_MS = 1000;
|
|
27
|
+
const START_DELAY_MAX_MS = 11000;
|
|
28
|
+
const CLAIM_RETRY_MIN_MS = 2 * 60 * 1000;
|
|
29
|
+
const CLAIM_RETRY_MAX_MS = 6 * 60 * 1000;
|
|
30
|
+
const RECEIPT_RETRY_MIN_MS = 2 * 60 * 1000;
|
|
31
|
+
const RECEIPT_RETRY_MAX_MS = 6 * 60 * 1000;
|
|
32
|
+
const RECONNECT_FIRST_MIN_MS = 1000;
|
|
33
|
+
const RECONNECT_FIRST_MAX_MS = 60 * 1000;
|
|
34
|
+
const RECONNECT_STEPS_MS = [100 * 1000, 300 * 1000, 1000 * 1000];
|
|
35
|
+
|
|
36
|
+
function randomBetween(min, max) {
|
|
37
|
+
return Math.floor(Math.random() * (max - min + 1)) + min;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function iso(value) {
|
|
41
|
+
return Number.isFinite(value) && value > 0 ? new Date(value).toISOString() : null;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function parseTime(value) {
|
|
45
|
+
if (typeof value === 'number' && Number.isFinite(value)) return value;
|
|
46
|
+
if (typeof value !== 'string' || value === '') return 0;
|
|
47
|
+
const parsed = Date.parse(value);
|
|
48
|
+
return Number.isFinite(parsed) ? parsed : 0;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Package root, i.e. the directory containing package.json and plugin.json. */
|
|
52
|
+
export function packageRoot() {
|
|
53
|
+
return path.resolve(fileURLToPath(new URL('..', import.meta.url)));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function installTokenPath(root) {
|
|
57
|
+
return path.join(path.resolve(root), TOKEN_FILE);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function readToken(file) {
|
|
61
|
+
try {
|
|
62
|
+
const value = fs.readFileSync(file, 'utf8').trim();
|
|
63
|
+
return TOKEN_RE.test(value) ? value : null;
|
|
64
|
+
} catch {
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Read or create the install token in the plugin directory.
|
|
71
|
+
* Never throws: a read-only directory degrades to a stable digest.
|
|
72
|
+
*/
|
|
73
|
+
export function ensureInstallToken(root, { hostname = os.hostname() } = {}) {
|
|
74
|
+
const dir = path.resolve(root);
|
|
75
|
+
const file = installTokenPath(dir);
|
|
76
|
+
const existing = readToken(file);
|
|
77
|
+
if (existing) return { token: existing, source: 'file', path: file };
|
|
78
|
+
|
|
79
|
+
const token = crypto.randomBytes(24).toString('hex');
|
|
80
|
+
try {
|
|
81
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
82
|
+
const fd = fs.openSync(file, 'wx', 0o600);
|
|
83
|
+
try {
|
|
84
|
+
fs.writeFileSync(fd, `${token}\n`, 'utf8');
|
|
85
|
+
fs.fsyncSync(fd);
|
|
86
|
+
} finally {
|
|
87
|
+
fs.closeSync(fd);
|
|
88
|
+
}
|
|
89
|
+
try { fs.chmodSync(file, 0o600); } catch { /* best effort on Windows */ }
|
|
90
|
+
return { token, source: 'file', path: file };
|
|
91
|
+
} catch (error) {
|
|
92
|
+
// Another process may have won the O_EXCL race.
|
|
93
|
+
const raced = readToken(file);
|
|
94
|
+
if (raced) return { token: raced, source: 'file', path: file };
|
|
95
|
+
const digest = crypto
|
|
96
|
+
.createHash('sha256')
|
|
97
|
+
.update(`timemachine-install\0${dir}\0${hostname}`)
|
|
98
|
+
.digest('hex');
|
|
99
|
+
return { token: digest, source: 'fallback', path: file, error: error instanceof Error ? error.message : String(error) };
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function normalizeStats(payload) {
|
|
104
|
+
if (!payload || payload.ok === false) throw new Error(payload?.error ?? 'stats unavailable');
|
|
105
|
+
const online = Number(payload.online);
|
|
106
|
+
const sevenDay = Number(payload.sevenDay ?? payload.seven_day ?? payload.active7d);
|
|
107
|
+
const installs = Number(payload.installs ?? payload.history);
|
|
108
|
+
if (![online, sevenDay, installs].every((value) => Number.isFinite(value))) {
|
|
109
|
+
throw new Error('stats payload is incomplete');
|
|
110
|
+
}
|
|
111
|
+
return {
|
|
112
|
+
ok: true,
|
|
113
|
+
version: payload.version ?? PLUGIN_VERSION,
|
|
114
|
+
online,
|
|
115
|
+
sevenDay,
|
|
116
|
+
installs,
|
|
117
|
+
history: Number(payload.history ?? installs),
|
|
118
|
+
updated_at: payload.updated_at ?? payload.updatedAt ?? null,
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Create the telemetry state machine. `start()` is deliberately delayed by
|
|
124
|
+
* 1–11 s so a fleet restart does not stampede the service.
|
|
125
|
+
*/
|
|
126
|
+
export function createTelemetry({
|
|
127
|
+
root = packageRoot(),
|
|
128
|
+
url = process.env.TIMEMACHINE_STATS_URL || DEFAULT_TELEMETRY_URL,
|
|
129
|
+
logger = null,
|
|
130
|
+
fetchImpl = globalThis.fetch,
|
|
131
|
+
} = {}) {
|
|
132
|
+
const baseUrl = String(url).replace(/\/+$/u, '');
|
|
133
|
+
const tokenInfo = ensureInstallToken(root);
|
|
134
|
+
let token = tokenInfo.token;
|
|
135
|
+
let stopped = false;
|
|
136
|
+
let timer = null;
|
|
137
|
+
let lastOkAt = Date.now();
|
|
138
|
+
let leaseUntil = 0;
|
|
139
|
+
let nextReceiptAt = 0;
|
|
140
|
+
let missed = 0;
|
|
141
|
+
let statsCache = null;
|
|
142
|
+
let statsCacheAt = 0;
|
|
143
|
+
let statsInFlight = null;
|
|
144
|
+
let lastError = '';
|
|
145
|
+
let reconnecting = false;
|
|
146
|
+
let reconnectStep = 0;
|
|
147
|
+
|
|
148
|
+
function warn(message) {
|
|
149
|
+
if (message === lastError) return;
|
|
150
|
+
lastError = message;
|
|
151
|
+
try {
|
|
152
|
+
logger?.warn?.(`timemachine: telemetry ${message}`);
|
|
153
|
+
} catch { /* logging must never break the plugin */ }
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async function request(route, body, method = 'POST') {
|
|
157
|
+
if (typeof fetchImpl !== 'function') throw new Error('fetch is unavailable');
|
|
158
|
+
const controller = new AbortController();
|
|
159
|
+
const timeout = setTimeout(() => controller.abort(), 5000);
|
|
160
|
+
timeout.unref?.();
|
|
161
|
+
try {
|
|
162
|
+
const response = await fetchImpl(`${baseUrl}${route}`, {
|
|
163
|
+
method,
|
|
164
|
+
headers: body === undefined ? { accept: 'application/json' } : { accept: 'application/json', 'content-type': 'application/json' },
|
|
165
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
166
|
+
signal: controller.signal,
|
|
167
|
+
});
|
|
168
|
+
let payload = null;
|
|
169
|
+
try { payload = await response.json(); } catch { payload = null; }
|
|
170
|
+
if (!response.ok) throw new Error(payload?.error ?? `HTTP ${response.status}`);
|
|
171
|
+
if (!payload || payload.ok === false) throw new Error(payload?.error ?? 'bad response');
|
|
172
|
+
return payload;
|
|
173
|
+
} finally {
|
|
174
|
+
clearTimeout(timeout);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function schedule(delay, work, label) {
|
|
179
|
+
if (stopped) return;
|
|
180
|
+
if (timer) clearTimeout(timer);
|
|
181
|
+
const ms = Math.max(0, Math.floor(Number(delay) || 0));
|
|
182
|
+
timer = setTimeout(() => {
|
|
183
|
+
timer = null;
|
|
184
|
+
Promise.resolve()
|
|
185
|
+
.then(work)
|
|
186
|
+
.catch((error) => warn(`${label}: ${error instanceof Error ? error.message : String(error)}`));
|
|
187
|
+
}, ms);
|
|
188
|
+
timer.unref?.();
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function applySchedule(payload) {
|
|
192
|
+
const lease = parseTime(payload.lease_until ?? payload.leaseUntil);
|
|
193
|
+
const next = parseTime(payload.next_receipt_at ?? payload.nextReceiptAt);
|
|
194
|
+
if (lease > 0) leaseUntil = lease;
|
|
195
|
+
if (next > 0) nextReceiptAt = next;
|
|
196
|
+
lastOkAt = Date.now();
|
|
197
|
+
lastError = '';
|
|
198
|
+
missed = 0;
|
|
199
|
+
reconnecting = false;
|
|
200
|
+
reconnectStep = 0;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function scheduleReceipt() {
|
|
204
|
+
const delay = nextReceiptAt > 0 ? nextReceiptAt - Date.now() : 0;
|
|
205
|
+
schedule(Math.max(1000, delay), receipt, 'receipt');
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
async function leaseOnce() {
|
|
209
|
+
const payload = await request('/v1/lease', {
|
|
210
|
+
token,
|
|
211
|
+
version: PLUGIN_VERSION,
|
|
212
|
+
platform: process.platform,
|
|
213
|
+
arch: process.arch,
|
|
214
|
+
});
|
|
215
|
+
applySchedule(payload);
|
|
216
|
+
return payload;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function scheduleReconnect() {
|
|
220
|
+
if (stopped || reconnecting) return;
|
|
221
|
+
reconnecting = true;
|
|
222
|
+
reconnectStep = 0;
|
|
223
|
+
const delay = randomBetween(RECONNECT_FIRST_MIN_MS, RECONNECT_FIRST_MAX_MS);
|
|
224
|
+
schedule(delay, reconnectTick, 'reconnect-first');
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
async function reconnectTick() {
|
|
228
|
+
if (stopped) return;
|
|
229
|
+
try {
|
|
230
|
+
await leaseOnce();
|
|
231
|
+
scheduleReceipt();
|
|
232
|
+
return;
|
|
233
|
+
} catch (error) {
|
|
234
|
+
warn(`reconnect failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
235
|
+
if (reconnectStep >= RECONNECT_STEPS_MS.length) {
|
|
236
|
+
reconnecting = false;
|
|
237
|
+
reconnectStep = 0;
|
|
238
|
+
schedule(RECONNECT_COOLDOWN_MS, claim, 'reconnect-cooldown');
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
const delay = RECONNECT_STEPS_MS[reconnectStep];
|
|
242
|
+
reconnectStep += 1;
|
|
243
|
+
schedule(delay, reconnectTick, `reconnect-${reconnectStep}`);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function onClaimFailure() {
|
|
248
|
+
if (Date.now() - lastOkAt >= LEASE_MS || (leaseUntil > 0 && Date.now() >= leaseUntil)) {
|
|
249
|
+
scheduleReconnect();
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
schedule(randomBetween(CLAIM_RETRY_MIN_MS, CLAIM_RETRY_MAX_MS), claim, 'claim-retry');
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
async function claim() {
|
|
256
|
+
if (stopped) return;
|
|
257
|
+
try {
|
|
258
|
+
await leaseOnce();
|
|
259
|
+
scheduleReceipt();
|
|
260
|
+
} catch (error) {
|
|
261
|
+
warn(`claim failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
262
|
+
onClaimFailure();
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
async function receipt() {
|
|
267
|
+
if (stopped) return;
|
|
268
|
+
try {
|
|
269
|
+
const payload = await request('/v1/receipt', {
|
|
270
|
+
token,
|
|
271
|
+
scheduled_for: iso(nextReceiptAt),
|
|
272
|
+
});
|
|
273
|
+
applySchedule(payload);
|
|
274
|
+
scheduleReceipt();
|
|
275
|
+
} catch (error) {
|
|
276
|
+
warnedReceipt(error);
|
|
277
|
+
missed += 1;
|
|
278
|
+
if (missed < 3) {
|
|
279
|
+
schedule(randomBetween(RECEIPT_RETRY_MIN_MS, RECEIPT_RETRY_MAX_MS), receipt, 'receipt-retry');
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
missed = 0;
|
|
283
|
+
// Three misses: put this install back into the next cycle and claim again.
|
|
284
|
+
const now = Date.now();
|
|
285
|
+
const nextCycle = now - (now % CYCLE_MS) + CYCLE_MS;
|
|
286
|
+
schedule(Math.max(1000, nextCycle - now + randomBetween(START_DELAY_MIN_MS, START_DELAY_MAX_MS)), claim, 'next-cycle');
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function warnedReceipt(error) {
|
|
291
|
+
warn(`receipt failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
async function getStats() {
|
|
295
|
+
const now = Date.now();
|
|
296
|
+
if (statsCache && now - statsCacheAt < STATS_CACHE_MS) return statsCache;
|
|
297
|
+
if (statsInFlight) return statsInFlight;
|
|
298
|
+
statsInFlight = (async () => {
|
|
299
|
+
try {
|
|
300
|
+
const payload = await request('/v1/stats', undefined, 'GET');
|
|
301
|
+
const normalized = normalizeStats(payload);
|
|
302
|
+
statsCache = normalized;
|
|
303
|
+
statsCacheAt = Date.now();
|
|
304
|
+
return normalized;
|
|
305
|
+
} catch (error) {
|
|
306
|
+
warn(`stats failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
307
|
+
if (statsCache) return { ...statsCache, stale: true };
|
|
308
|
+
return {
|
|
309
|
+
ok: false,
|
|
310
|
+
version: PLUGIN_VERSION,
|
|
311
|
+
online: null,
|
|
312
|
+
sevenDay: null,
|
|
313
|
+
installs: null,
|
|
314
|
+
history: null,
|
|
315
|
+
updated_at: null,
|
|
316
|
+
error: 'stats unavailable',
|
|
317
|
+
};
|
|
318
|
+
} finally {
|
|
319
|
+
statsInFlight = null;
|
|
320
|
+
}
|
|
321
|
+
})();
|
|
322
|
+
return statsInFlight;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function snapshot() {
|
|
326
|
+
return {
|
|
327
|
+
version: PLUGIN_VERSION,
|
|
328
|
+
token_source: tokenInfo.source,
|
|
329
|
+
connected: leaseUntil > Date.now(),
|
|
330
|
+
lease_until: iso(leaseUntil),
|
|
331
|
+
next_receipt_at: iso(nextReceiptAt),
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
function start() {
|
|
336
|
+
if (!stopped) {
|
|
337
|
+
schedule(randomBetween(START_DELAY_MIN_MS, START_DELAY_MAX_MS), claim, 'startup');
|
|
338
|
+
}
|
|
339
|
+
return api;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function stop() {
|
|
343
|
+
stopped = true;
|
|
344
|
+
if (timer) clearTimeout(timer);
|
|
345
|
+
timer = null;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
const api = {
|
|
349
|
+
start,
|
|
350
|
+
stop,
|
|
351
|
+
getStats,
|
|
352
|
+
snapshot,
|
|
353
|
+
get token() { return token; },
|
|
354
|
+
get installRoot() { return path.resolve(root); },
|
|
355
|
+
};
|
|
356
|
+
return api;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/** Convenience entry used by the Cordis plugin. */
|
|
360
|
+
export function startTelemetry(options = {}) {
|
|
361
|
+
if (process.env.TIMEMACHINE_TELEMETRY_DISABLED === '1') return null;
|
|
362
|
+
return createTelemetry(options).start();
|
|
363
|
+
}
|
package/src/version.mjs
ADDED