burrow-cli 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +594 -2
- package/bin/burrow.js +200 -0
- package/examples/acme-shop.tunnel.yml +18 -0
- package/package.json +45 -4
- package/src/access.js +163 -0
- package/src/add.js +106 -0
- package/src/cloudflare.js +131 -0
- package/src/commands.js +386 -0
- package/src/completion.js +127 -0
- package/src/config-file.js +31 -0
- package/src/config.js +82 -0
- package/src/dashboard/auth.js +79 -0
- package/src/dashboard/data.js +70 -0
- package/src/dashboard/logs.js +95 -0
- package/src/dashboard/manage.js +102 -0
- package/src/dashboard/panels/README.md +50 -0
- package/src/dashboard/panels/access.js +218 -0
- package/src/dashboard/panels/alerts.js +244 -0
- package/src/dashboard/panels/backup.js +193 -0
- package/src/dashboard/panels/bulk.js +246 -0
- package/src/dashboard/panels/cleanup.js +237 -0
- package/src/dashboard/panels/doctor.js +119 -0
- package/src/dashboard/panels/health.js +146 -0
- package/src/dashboard/panels/history.js +104 -0
- package/src/dashboard/panels/hooks.js +86 -0
- package/src/dashboard/panels/live.js +153 -0
- package/src/dashboard/panels/project-form.js +463 -0
- package/src/dashboard/panels/quick-actions.js +133 -0
- package/src/dashboard/panels/sessions.js +267 -0
- package/src/dashboard/panels/shares.js +280 -0
- package/src/dashboard/panels/stats.js +165 -0
- package/src/dashboard/panels/updates.js +156 -0
- package/src/dashboard/panels/uptime.js +115 -0
- package/src/dashboard/panels.js +53 -0
- package/src/dashboard/server.js +390 -0
- package/src/dashboard/session-store.js +47 -0
- package/src/dashboard/totp.js +103 -0
- package/src/dashboard/ui.js +454 -0
- package/src/doctor.js +342 -0
- package/src/edit.js +135 -0
- package/src/health-observer.js +81 -0
- package/src/history.js +145 -0
- package/src/hooks.js +256 -0
- package/src/naming.js +38 -0
- package/src/open.js +67 -0
- package/src/pending.js +72 -0
- package/src/process.js +95 -0
- package/src/project-form.js +134 -0
- package/src/project.js +114 -0
- package/src/prune.js +99 -0
- package/src/rename-state.js +39 -0
- package/src/restart.js +35 -0
- package/src/service.js +173 -0
- package/src/share-expiry.js +55 -0
- package/src/share.js +275 -0
- package/src/shell-words.js +284 -0
- package/src/stats.js +180 -0
- package/src/transfer.js +124 -0
- package/src/update.js +254 -0
- package/src/uptime.js +91 -0
- package/src/watch.js +263 -0
- package/src/zones.js +102 -0
package/src/stats.js
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { loadConfig, requireConfig } from './config.js';
|
|
2
|
+
import { Cloudflare, apiBase } from './cloudflare.js';
|
|
3
|
+
import { projectUrls } from './open.js';
|
|
4
|
+
|
|
5
|
+
// Cloudflare GraphQL Analytics. BURROW_CF_API_BASE (tests only) moves it to the mock API.
|
|
6
|
+
const endpoint = () => `${apiBase()}/graphql`;
|
|
7
|
+
const log = (...a) => console.log(...a);
|
|
8
|
+
|
|
9
|
+
export const QUERY = `query BurrowStats($zoneTag: string, $filter: ZoneHttpRequestsAdaptiveGroupsFilter_InputObject) {
|
|
10
|
+
viewer {
|
|
11
|
+
zones(filter: { zoneTag: $zoneTag }) {
|
|
12
|
+
httpRequestsAdaptiveGroups(limit: 5000, filter: $filter) {
|
|
13
|
+
count
|
|
14
|
+
sum { edgeResponseBytes }
|
|
15
|
+
dimensions { clientRequestHTTPHost edgeResponseStatus }
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
}`;
|
|
20
|
+
|
|
21
|
+
const UNITS = { m: 60e3, min: 60e3, h: 3600e3, d: 86400e3, w: 7 * 86400e3 };
|
|
22
|
+
export function parseSince(value = '24h', now = Date.now()) {
|
|
23
|
+
const v = String(value).trim();
|
|
24
|
+
const m = v.match(/^(\d+)\s*(m|min|h|d|w)$/i);
|
|
25
|
+
if (m && Number(m[1]) > 0) return new Date(now - Number(m[1]) * UNITS[m[2].toLowerCase()]);
|
|
26
|
+
if (/^\d{4}-\d{2}-\d{2}/.test(v)) {
|
|
27
|
+
const d = new Date(v);
|
|
28
|
+
if (!Number.isNaN(d.getTime()) && d.getTime() < now) return d;
|
|
29
|
+
}
|
|
30
|
+
throw new Error(`Invalid --since "${v}". Use 30m, 24h, 7d, 2w or an ISO date in the past.`);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Cloudflare wants RFC 3339 without milliseconds.
|
|
34
|
+
const iso = (d) => d.toISOString().replace(/\.\d{3}Z$/, 'Z');
|
|
35
|
+
|
|
36
|
+
export function aggregate(groups, hosts) {
|
|
37
|
+
const rows = new Map(hosts.map((h) => [h, {
|
|
38
|
+
hostname: h, requests: 0, bytes: 0, status: {}, classes: { '1xx': 0, '2xx': 0, '3xx': 0, '4xx': 0, '5xx': 0 },
|
|
39
|
+
}]));
|
|
40
|
+
for (const g of groups || []) {
|
|
41
|
+
const row = rows.get(g.dimensions?.clientRequestHTTPHost);
|
|
42
|
+
if (!row) continue;
|
|
43
|
+
const n = Number(g.count) || 0;
|
|
44
|
+
row.requests += n;
|
|
45
|
+
row.bytes += Number(g.sum?.edgeResponseBytes) || 0;
|
|
46
|
+
const code = String(g.dimensions?.edgeResponseStatus ?? '');
|
|
47
|
+
if (code) row.status[code] = (row.status[code] || 0) + n;
|
|
48
|
+
const cls = `${code[0]}xx`;
|
|
49
|
+
if (cls in row.classes) row.classes[cls] += n;
|
|
50
|
+
}
|
|
51
|
+
return [...rows.values()];
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function formatBytes(n) {
|
|
55
|
+
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
|
56
|
+
let i = 0;
|
|
57
|
+
let v = Number(n) || 0;
|
|
58
|
+
while (v >= 1000 && i < units.length - 1) { v /= 1000; i++; }
|
|
59
|
+
return i === 0 ? `${v} B` : `${v.toFixed(v < 10 ? 2 : 1)} ${units[i]}`;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const num = (n) => Number(n).toLocaleString('en-US');
|
|
63
|
+
|
|
64
|
+
export async function graphql(token, variables, query = QUERY) {
|
|
65
|
+
let res;
|
|
66
|
+
try {
|
|
67
|
+
res = await fetch(endpoint(), {
|
|
68
|
+
method: 'POST',
|
|
69
|
+
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
|
|
70
|
+
body: JSON.stringify({ query, variables }),
|
|
71
|
+
signal: AbortSignal.timeout(30000),
|
|
72
|
+
});
|
|
73
|
+
} catch (e) {
|
|
74
|
+
throw new Error(`GraphQL Analytics request failed: ${e.name === 'TimeoutError' ? 'timed out after 30s' : e.message}`);
|
|
75
|
+
}
|
|
76
|
+
let json = null;
|
|
77
|
+
try { json = await res.json(); } catch {}
|
|
78
|
+
const errors = json?.errors || [];
|
|
79
|
+
if (!res.ok || !json || errors.length) {
|
|
80
|
+
const msg = errors.map((e) => e.message).join('; ') || `HTTP ${res.status}`;
|
|
81
|
+
const auth = res.status === 401 || res.status === 403 || /authori[sz]|permission|forbidden|access/i.test(msg);
|
|
82
|
+
throw new Error(`GraphQL Analytics query failed: ${msg}${auth ? '. The API token needs Zone > Analytics > Read for this zone.' : ''}`);
|
|
83
|
+
}
|
|
84
|
+
return json.data;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Totals per hostname for one project (used by `burrow stats` and the dashboard).
|
|
88
|
+
export async function fetchStats(projectArg, opts = {}, cfg = loadConfig()) {
|
|
89
|
+
requireConfig(cfg, ['token', 'domain']);
|
|
90
|
+
const { project, urls } = projectUrls(projectArg, opts, cfg);
|
|
91
|
+
const hosts = [...new Set(urls.map((u) => new URL(u.url).hostname))];
|
|
92
|
+
const until = new Date();
|
|
93
|
+
const since = parseSince(opts.since, until.getTime());
|
|
94
|
+
const cf = new Cloudflare({ token: cfg.token, accountId: cfg.accountId, zoneId: cfg.zoneId });
|
|
95
|
+
const zoneTag = await cf.resolveZoneId(cfg.domain);
|
|
96
|
+
const data = await graphql(cfg.token, {
|
|
97
|
+
zoneTag,
|
|
98
|
+
filter: { datetime_geq: iso(since), datetime_lt: iso(until), clientRequestHTTPHost_in: hosts },
|
|
99
|
+
});
|
|
100
|
+
const rows = aggregate(data?.viewer?.zones?.[0]?.httpRequestsAdaptiveGroups, hosts);
|
|
101
|
+
const total = aggregate(rows.flatMap((r) => Object.entries(r.status).map(([code, count]) => ({
|
|
102
|
+
count, dimensions: { clientRequestHTTPHost: 'total', edgeResponseStatus: code },
|
|
103
|
+
}))), ['total'])[0];
|
|
104
|
+
total.bytes = rows.reduce((a, r) => a + r.bytes, 0);
|
|
105
|
+
return { project, hosts, since, until, zoneTag, rows, total };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Requests, 4xx, 5xx and bytes over time: 15-minute buckets up to 6 h, hourly beyond.
|
|
109
|
+
export const seriesQuery = (dim) => `query BurrowSeries($zoneTag: string, $filter: ZoneHttpRequestsAdaptiveGroupsFilter_InputObject) {
|
|
110
|
+
viewer {
|
|
111
|
+
zones(filter: { zoneTag: $zoneTag }) {
|
|
112
|
+
httpRequestsAdaptiveGroups(limit: 10000, filter: $filter) {
|
|
113
|
+
count
|
|
114
|
+
sum { edgeResponseBytes }
|
|
115
|
+
dimensions { ${dim} clientRequestHTTPHost edgeResponseStatus }
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}`;
|
|
120
|
+
|
|
121
|
+
export function bucketSpec(since, until) {
|
|
122
|
+
return until - since <= 6 * 3600e3 ? { dim: 'datetimeFifteenMinutes', step: 15 * 60e3 } : { dim: 'datetimeHour', step: 3600e3 };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// { all: [{ t, requests, e4xx, e5xx, bytes }], '<hostname>': [...] } with empty buckets filled in.
|
|
126
|
+
export function aggregateSeries(groups, hosts, { since, until, dim, step }) {
|
|
127
|
+
const start = Math.floor(since.getTime() / step) * step;
|
|
128
|
+
const times = [];
|
|
129
|
+
for (let t = start; t < until.getTime(); t += step) times.push(t);
|
|
130
|
+
const blank = () => times.map((t) => ({ t, requests: 0, e4xx: 0, e5xx: 0, bytes: 0 }));
|
|
131
|
+
const out = { all: blank() };
|
|
132
|
+
for (const h of hosts) out[h] = blank();
|
|
133
|
+
for (const g of groups || []) {
|
|
134
|
+
const host = g.dimensions?.clientRequestHTTPHost;
|
|
135
|
+
if (!out[host]) continue;
|
|
136
|
+
const t = Date.parse(g.dimensions?.[dim]);
|
|
137
|
+
const i = Math.floor((t - start) / step);
|
|
138
|
+
if (!(i >= 0 && i < times.length)) continue;
|
|
139
|
+
const n = Number(g.count) || 0;
|
|
140
|
+
const code = String(g.dimensions?.edgeResponseStatus ?? '');
|
|
141
|
+
for (const b of [out.all[i], out[host][i]]) {
|
|
142
|
+
b.requests += n;
|
|
143
|
+
b.bytes += Number(g.sum?.edgeResponseBytes) || 0;
|
|
144
|
+
if (code[0] === '4') b.e4xx += n;
|
|
145
|
+
if (code[0] === '5') b.e5xx += n;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return out;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export async function fetchSeries({ cfg, zoneTag, hosts, since, until }) {
|
|
152
|
+
const spec = bucketSpec(since.getTime(), until.getTime());
|
|
153
|
+
const data = await graphql(cfg.token, {
|
|
154
|
+
zoneTag, filter: { datetime_geq: iso(since), datetime_lt: iso(until), clientRequestHTTPHost_in: hosts },
|
|
155
|
+
}, seriesQuery(spec.dim));
|
|
156
|
+
return { step: spec.step, series: aggregateSeries(data?.viewer?.zones?.[0]?.httpRequestsAdaptiveGroups, hosts, { since, until, ...spec }) };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export async function stats(projectArg, opts = {}) {
|
|
160
|
+
const { project, since, until, zoneTag, rows, total } = await fetchStats(projectArg, opts, loadConfig());
|
|
161
|
+
|
|
162
|
+
if (opts.json) {
|
|
163
|
+
log(JSON.stringify({
|
|
164
|
+
project, since: iso(since), until: iso(until), zone: zoneTag, sampled: true,
|
|
165
|
+
hostnames: rows, total: { requests: total.requests, bytes: total.bytes, status: total.status, classes: total.classes },
|
|
166
|
+
}, null, 2));
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
log(`${project}: ${iso(since)} -> ${iso(until)} (Cloudflare analytics, sampled)`);
|
|
170
|
+
const width = Math.max(8, ...rows.map((r) => r.hostname.length));
|
|
171
|
+
const line = (name, r) => [
|
|
172
|
+
name.padEnd(width), num(r.requests).padStart(10), formatBytes(r.bytes).padStart(10),
|
|
173
|
+
...['2xx', '3xx', '4xx', '5xx'].map((c) => num(r.classes[c]).padStart(8)),
|
|
174
|
+
].join(' ');
|
|
175
|
+
log(['HOSTNAME'.padEnd(width), 'REQUESTS'.padStart(10), 'BANDWIDTH'.padStart(10), ...['2xx', '3xx', '4xx', '5xx'].map((c) => c.padStart(8))].join(' '));
|
|
176
|
+
for (const r of rows) log(line(r.hostname, r));
|
|
177
|
+
if (rows.length > 1) log(line('total', total));
|
|
178
|
+
const top = Object.entries(total.status).sort((a, b) => b[1] - a[1]).slice(0, 8);
|
|
179
|
+
log(top.length ? `Status codes: ${top.map(([c, n]) => `${c} ${num(n)}`).join(', ')}` : 'No requests in this window.');
|
|
180
|
+
}
|
package/src/transfer.js
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { dirname, join, resolve } from 'node:path';
|
|
3
|
+
import YAML from 'yaml';
|
|
4
|
+
import { configPath, stateDir } from './config.js';
|
|
5
|
+
import { parseProject } from './project.js';
|
|
6
|
+
import { readMeta, saveMeta } from './process.js';
|
|
7
|
+
import { shareNames } from './share.js';
|
|
8
|
+
|
|
9
|
+
const log = (...a) => console.error(...a); // stdout may carry the bundle
|
|
10
|
+
|
|
11
|
+
// Keep only known tunnel.yml fields, so nothing else (secrets included) is ever copied.
|
|
12
|
+
export function cleanProject(raw) {
|
|
13
|
+
if (!raw || typeof raw !== 'object') throw new Error('project entry must be a mapping');
|
|
14
|
+
const pick = (obj, keys) => Object.fromEntries(keys.filter((k) => obj[k] !== undefined).map((k) => [k, obj[k]]));
|
|
15
|
+
const out = pick(raw, ['project', 'domain', 'autostart']);
|
|
16
|
+
out.services = (Array.isArray(raw.services) ? raw.services : []).map((s) => {
|
|
17
|
+
const svc = pick(s || {}, ['name', 'root', 'url', 'originRequest']);
|
|
18
|
+
if (Array.isArray(s?.paths) && s.paths.length) svc.paths = s.paths.map((p) => pick(p || {}, ['path', 'url', 'originRequest']));
|
|
19
|
+
return svc;
|
|
20
|
+
});
|
|
21
|
+
parseProject(YAML.stringify(out), `project ${out.project}`); // validate
|
|
22
|
+
return out;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function rememberedProjects() {
|
|
26
|
+
let names = [];
|
|
27
|
+
try { names = readdirSync(stateDir()).filter((f) => f.endsWith('.json')).map((f) => f.slice(0, -5)); } catch {}
|
|
28
|
+
return names.sort().map((n) => ({ name: n, meta: readMeta(n) })).filter(({ meta }) => meta?.file && !meta.share && existsSync(meta.file));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function buildBundle(filter = []) {
|
|
32
|
+
const shares = shareNames();
|
|
33
|
+
const asked = filter.filter((f) => shares.includes(f));
|
|
34
|
+
if (asked.length) {
|
|
35
|
+
throw new Error(`${asked.join(', ')}: temporary share(s) from "burrow share" can't be exported; share again on the other machine.`);
|
|
36
|
+
}
|
|
37
|
+
const projects = [];
|
|
38
|
+
for (const { name, meta } of rememberedProjects()) {
|
|
39
|
+
if (filter.length && !filter.includes(name)) continue;
|
|
40
|
+
projects.push(cleanProject(YAML.parse(readFileSync(meta.file, 'utf8'))));
|
|
41
|
+
}
|
|
42
|
+
const missing = filter.filter((f) => !projects.some((p) => p.project === f));
|
|
43
|
+
if (missing.length) throw new Error(`Unknown project(s): ${missing.join(', ')}`);
|
|
44
|
+
return { burrow: 'projects', version: 1, exportedAt: new Date().toISOString(), projects };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export async function exportProjects(file, opts = {}) {
|
|
48
|
+
const filter = (opts.project || '').split(',').map((s) => s.trim()).filter(Boolean);
|
|
49
|
+
const bundle = buildBundle(filter);
|
|
50
|
+
// Shares are throwaway hostnames tied to this machine, so they're never exported.
|
|
51
|
+
const skipped = filter.length ? [] : shareNames();
|
|
52
|
+
const shareNote = skipped.length
|
|
53
|
+
? `${skipped.length} temporary share(s) not exported (${skipped.join(', ')}); shares only live on the machine that created them.`
|
|
54
|
+
: '';
|
|
55
|
+
if (shareNote) log(`Note: ${shareNote}`);
|
|
56
|
+
const asJson = opts.json || /\.json$/i.test(file || '');
|
|
57
|
+
const text = asJson
|
|
58
|
+
? JSON.stringify(bundle, null, 2) + '\n'
|
|
59
|
+
: '# burrow project export. Contains tunnel.yml settings only, no tokens or passwords.\n' +
|
|
60
|
+
(shareNote ? `# ${shareNote}\n` : '') + YAML.stringify(bundle, { lineWidth: 0 });
|
|
61
|
+
if (!file || file === '-') { process.stdout.write(text); return bundle; }
|
|
62
|
+
writeFileSync(resolve(file), text);
|
|
63
|
+
log(`Exported ${bundle.projects.length} project(s) to ${resolve(file)}: ${bundle.projects.map((p) => p.project).join(', ')}`);
|
|
64
|
+
return bundle;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export const defaultImportDir = () => join(dirname(configPath()), 'projects');
|
|
68
|
+
|
|
69
|
+
// A parsed, checked export bundle (YAML or JSON text).
|
|
70
|
+
export function parseBundle(text, source = 'the file') {
|
|
71
|
+
let bundle;
|
|
72
|
+
try { bundle = YAML.parse(String(text)); } catch (e) { throw new Error(`${source} is not valid YAML/JSON: ${e.message}`); }
|
|
73
|
+
if (bundle?.burrow !== 'projects' || bundle.version !== 1 || !Array.isArray(bundle.projects)) {
|
|
74
|
+
throw new Error(`${source} is not a burrow export (expected "burrow: projects" and "version: 1")`);
|
|
75
|
+
}
|
|
76
|
+
return bundle;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// What importing would do, per project: { project, dest, status: new | exists | known,
|
|
80
|
+
// knownAt, proj, error }. "exists": dest is already there; "known": the project is
|
|
81
|
+
// remembered at another path. Both need force to be replaced.
|
|
82
|
+
export function planImport(bundle, opts = {}) {
|
|
83
|
+
const dir = resolve(opts.dir || defaultImportDir());
|
|
84
|
+
return bundle.projects.map((raw, i) => {
|
|
85
|
+
let proj;
|
|
86
|
+
try { proj = cleanProject(raw); } catch (e) { return { project: String(raw?.project ?? `#${i + 1}`), status: 'invalid', error: e.message }; }
|
|
87
|
+
const dest = join(dir, `${proj.project}.tunnel.yml`);
|
|
88
|
+
const meta = readMeta(proj.project);
|
|
89
|
+
const known = meta?.file && existsSync(meta.file) && resolve(meta.file) !== dest;
|
|
90
|
+
const status = known ? 'known' : existsSync(dest) ? 'exists' : 'new';
|
|
91
|
+
return { project: proj.project, dest, status, ...(known ? { knownAt: meta.file } : {}), proj };
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Write one planned entry (see planImport).
|
|
96
|
+
export function writeImported(p) {
|
|
97
|
+
const meta = readMeta(p.project);
|
|
98
|
+
mkdirSync(dirname(p.dest), { recursive: true });
|
|
99
|
+
writeFileSync(p.dest, `# imported by burrow on ${new Date().toISOString()}\n` + YAML.stringify(p.proj, { lineWidth: 0 }));
|
|
100
|
+
saveMeta(p.project, { ...(meta || {}), project: p.project, file: p.dest });
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export async function importProjects(file, opts = {}) {
|
|
104
|
+
const text = file === '-' ? readFileSync(0, 'utf8') : readFileSync(resolve(file), 'utf8');
|
|
105
|
+
const bundle = parseBundle(text, file);
|
|
106
|
+
const results = { written: [], skipped: [] };
|
|
107
|
+
for (const p of planImport(bundle, opts)) {
|
|
108
|
+
if (p.status === 'invalid') throw new Error(p.error);
|
|
109
|
+
const { proj, dest } = p;
|
|
110
|
+
const meta = readMeta(proj.project);
|
|
111
|
+
const known = p.status === 'known';
|
|
112
|
+
if (!opts.force && p.status !== 'new') {
|
|
113
|
+
log(`skip ${proj.project}: already ${known ? `known at ${meta.file}` : `at ${dest}`} (use --force to replace)`);
|
|
114
|
+
results.skipped.push(proj.project);
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
if (opts.dryRun) { log(`[dry-run] would write ${dest}`); results.written.push(proj.project); continue; }
|
|
118
|
+
writeImported(p);
|
|
119
|
+
log(`imported ${proj.project} -> ${dest}`);
|
|
120
|
+
results.written.push(proj.project);
|
|
121
|
+
}
|
|
122
|
+
log(`${results.written.length} imported, ${results.skipped.length} skipped. Bring one up with: burrow up <project>`);
|
|
123
|
+
return results;
|
|
124
|
+
}
|
package/src/update.js
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { existsSync, readFileSync, realpathSync } from 'node:fs';
|
|
3
|
+
import { basename, dirname, join, resolve } from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
|
|
6
|
+
const log = (...a) => console.log(...a);
|
|
7
|
+
export const PACKAGE_ROOT = resolve(fileURLToPath(new URL('..', import.meta.url)));
|
|
8
|
+
const GIT_TIMEOUT = 60_000;
|
|
9
|
+
const PULL_TIMEOUT = 180_000;
|
|
10
|
+
const NPM_TIMEOUT = 600_000;
|
|
11
|
+
const gitBin = () => process.env.BURROW_GIT || 'git';
|
|
12
|
+
const npmBin = () => process.env.BURROW_NPM || 'npm';
|
|
13
|
+
|
|
14
|
+
// Every child gets a timeout, and git never waits for a password prompt.
|
|
15
|
+
function run(bin, args, { cwd, timeout = GIT_TIMEOUT, inherit = false } = {}) {
|
|
16
|
+
const env = { ...process.env, GIT_TERMINAL_PROMPT: '0' };
|
|
17
|
+
if (!env.GIT_SSH_COMMAND) env.GIT_SSH_COMMAND = 'ssh -o BatchMode=yes';
|
|
18
|
+
const r = spawnSync(bin, args, {
|
|
19
|
+
cwd, env, encoding: 'utf8', timeout, killSignal: 'SIGKILL', stdio: inherit ? ['ignore', 'inherit', 'inherit'] : 'pipe',
|
|
20
|
+
});
|
|
21
|
+
if (r.error?.code === 'ETIMEDOUT') throw new Error(`${bin} ${args.join(' ')} timed out after ${timeout / 1000}s`);
|
|
22
|
+
if (r.error) throw new Error(`Could not run ${bin}: ${r.error.message}`);
|
|
23
|
+
return { ok: r.status === 0, out: (r.stdout || '').trim(), err: (r.stderr || '').trim(), status: r.status };
|
|
24
|
+
}
|
|
25
|
+
function must(bin, args, opts) {
|
|
26
|
+
const r = run(bin, args, opts);
|
|
27
|
+
if (!r.ok) throw new Error(`${bin} ${args.join(' ')} failed: ${r.err || r.out || `exit ${r.status}`}`);
|
|
28
|
+
return r.out;
|
|
29
|
+
}
|
|
30
|
+
const git = (cwd, ...args) => must(gitBin(), args, { cwd });
|
|
31
|
+
const short = (sha) => String(sha || '').slice(0, 7);
|
|
32
|
+
const readPkg = (root) => JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
|
|
33
|
+
|
|
34
|
+
// How is this copy installed?
|
|
35
|
+
// git: a git checkout (git pull --ff-only + npm install)
|
|
36
|
+
// npm: <prefix>/lib/node_modules/<package> from `npm install -g` (reinstall with npm).
|
|
37
|
+
// `registry` is true for installs from the npm registry, false for git sources.
|
|
38
|
+
// unknown: anything else
|
|
39
|
+
export function detectInstall(root = PACKAGE_ROOT) {
|
|
40
|
+
root = resolve(root);
|
|
41
|
+
const pkg = readPkg(root);
|
|
42
|
+
if (existsSync(join(root, '.git'))) {
|
|
43
|
+
const top = run(gitBin(), ['rev-parse', '--show-toplevel'], { cwd: root });
|
|
44
|
+
if (top.ok && realpathSync(top.out) === realpathSync(root)) return { mode: 'git', root, pkg };
|
|
45
|
+
}
|
|
46
|
+
const nm = dirname(root);
|
|
47
|
+
if (basename(nm) === 'node_modules') {
|
|
48
|
+
const prefix = basename(dirname(nm)) === 'lib' ? dirname(dirname(nm)) : dirname(nm);
|
|
49
|
+
let resolved = null;
|
|
50
|
+
try {
|
|
51
|
+
const lock = JSON.parse(readFileSync(join(nm, '.package-lock.json'), 'utf8'));
|
|
52
|
+
resolved = lock.packages?.[`node_modules/${pkg.name}`]?.resolved || null;
|
|
53
|
+
} catch {}
|
|
54
|
+
// Installed from the npm registry (a tarball URL) rather than from a git source.
|
|
55
|
+
const registry = /^https?:\/\//.test(resolved || '') && !process.env.BURROW_UPDATE_SOURCE;
|
|
56
|
+
return { mode: 'npm', root, pkg, prefix, resolved, registry };
|
|
57
|
+
}
|
|
58
|
+
return { mode: 'unknown', root, pkg };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// A git URL for `git ls-remote`, plus an optional ref, from an npm-style spec:
|
|
62
|
+
// github:owner/repo, owner/repo, git+ssh://…, git+https://…, file:///…, /a/path, with an optional #ref.
|
|
63
|
+
export function gitUrl(spec) {
|
|
64
|
+
let s = String(spec || '').trim();
|
|
65
|
+
let ref = null;
|
|
66
|
+
const hash = s.indexOf('#');
|
|
67
|
+
if (hash >= 0) { ref = s.slice(hash + 1) || null; s = s.slice(0, hash); }
|
|
68
|
+
let m;
|
|
69
|
+
if ((m = s.match(/^github:([\w.-]+\/[\w.-]+?)(?:\.git)?$/)) || (m = s.match(/^([\w.-]+\/[\w.-]+?)(?:\.git)?$/))) {
|
|
70
|
+
return { url: `https://github.com/${m[1]}.git`, ref };
|
|
71
|
+
}
|
|
72
|
+
if (s.startsWith('git+')) s = s.slice(4);
|
|
73
|
+
return { url: s, ref };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const isGitSpec = (s) => /^(git\+|github:|git@|git:\/\/)/.test(String(s || ''));
|
|
77
|
+
const isSha = (s) => /^[0-9a-f]{7,40}$/.test(String(s || ''));
|
|
78
|
+
|
|
79
|
+
// Where updates come from: BURROW_UPDATE_SOURCE, else the git URL npm recorded at install
|
|
80
|
+
// time, else "repository" in package.json.
|
|
81
|
+
export function updateSource(info, env = process.env) {
|
|
82
|
+
let spec = env.BURROW_UPDATE_SOURCE || '';
|
|
83
|
+
let installed = null;
|
|
84
|
+
if (info.resolved && isGitSpec(info.resolved)) {
|
|
85
|
+
const { url, ref } = gitUrl(info.resolved);
|
|
86
|
+
if (isSha(ref)) installed = ref;
|
|
87
|
+
if (!spec) spec = info.resolved.startsWith('git+') ? `git+${url}` : url;
|
|
88
|
+
}
|
|
89
|
+
if (!spec) {
|
|
90
|
+
const repo = info.pkg.repository;
|
|
91
|
+
spec = typeof repo === 'string' ? repo : repo?.url || '';
|
|
92
|
+
}
|
|
93
|
+
if (!spec) throw new Error('No update source: set BURROW_UPDATE_SOURCE (e.g. github:zfir-dev/burrow-cli).');
|
|
94
|
+
const { url, ref } = gitUrl(spec);
|
|
95
|
+
return { spec, url, ref: isSha(ref) ? null : ref, installed };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function checkGit(info) {
|
|
99
|
+
const cwd = info.root;
|
|
100
|
+
const branch = git(cwd, 'rev-parse', '--abbrev-ref', 'HEAD');
|
|
101
|
+
const up = run(gitBin(), ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'], { cwd });
|
|
102
|
+
if (!up.ok) throw new Error(`Branch ${branch} in ${cwd} has no upstream. Set one with: git branch -u origin/${branch}`);
|
|
103
|
+
git(cwd, 'fetch', '--quiet');
|
|
104
|
+
const head = git(cwd, 'rev-parse', 'HEAD');
|
|
105
|
+
const remote = git(cwd, 'rev-parse', '@{u}');
|
|
106
|
+
const behind = Number(git(cwd, 'rev-list', '--count', 'HEAD..@{u}'));
|
|
107
|
+
const ahead = Number(git(cwd, 'rev-list', '--count', '@{u}..HEAD'));
|
|
108
|
+
const commits = behind ? git(cwd, 'log', '--oneline', '--no-decorate', '-n', '10', 'HEAD..@{u}').split('\n') : [];
|
|
109
|
+
let remoteVersion = null;
|
|
110
|
+
try { remoteVersion = JSON.parse(git(cwd, 'show', '@{u}:package.json')).version; } catch {}
|
|
111
|
+
return { branch, upstream: up.out, head, remote, behind, ahead, commits, version: info.pkg.version, remoteVersion };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// Newer-than for plain x.y.z versions (prerelease tags are ignored).
|
|
115
|
+
export function newerVersion(a, b) {
|
|
116
|
+
const n = (v) => String(v).split('-')[0].split('.').map((x) => Number(x) || 0);
|
|
117
|
+
const [x, y] = [n(a), n(b)];
|
|
118
|
+
for (let i = 0; i < 3; i++) { if ((x[i] || 0) !== (y[i] || 0)) return (x[i] || 0) > (y[i] || 0); }
|
|
119
|
+
return false;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// The latest version on the npm registry (`npm view <name> version`).
|
|
123
|
+
export function checkRegistry(info) {
|
|
124
|
+
const name = info.pkg.name;
|
|
125
|
+
const latest = must(npmBin(), ['view', name, 'version'], { timeout: GIT_TIMEOUT }).split('\n').pop().trim();
|
|
126
|
+
if (!/^\d+\.\d+\.\d+/.test(latest)) throw new Error(`npm view ${name} version returned "${latest}"`);
|
|
127
|
+
return { name, latest, version: info.pkg.version, upToDate: !newerVersion(latest, info.pkg.version) };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export function checkNpm(info) {
|
|
131
|
+
if (info.registry) throw new Error('registry install: use checkRegistry');
|
|
132
|
+
const src = updateSource(info);
|
|
133
|
+
const out = must(gitBin(), ['ls-remote', src.url, src.ref || 'HEAD']);
|
|
134
|
+
const latest = out.split('\n')[0]?.split(/\s+/)[0] || null;
|
|
135
|
+
if (!latest) throw new Error(`${src.url} has no ${src.ref || 'HEAD'}`);
|
|
136
|
+
return { ...src, latest, upToDate: src.installed ? latest.startsWith(src.installed) : null, version: info.pkg.version };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function reportGit(c, info) {
|
|
140
|
+
log(`burrow ${c.version}: git checkout ${info.root} (branch ${c.branch})`);
|
|
141
|
+
if (!c.behind) {
|
|
142
|
+
log(`Up to date with ${c.upstream} (${short(c.head)})${c.ahead ? `, ${c.ahead} local commit(s) not pushed` : ''}.`);
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
log(`${c.behind} new commit(s) on ${c.upstream} (${short(c.head)} -> ${short(c.remote)}):`);
|
|
146
|
+
for (const l of c.commits) log(` ${l}`);
|
|
147
|
+
if (c.behind > c.commits.length) log(` … and ${c.behind - c.commits.length} more`);
|
|
148
|
+
if (c.remoteVersion && c.remoteVersion !== c.version) log(`Version: ${c.version} -> ${c.remoteVersion}`);
|
|
149
|
+
log('Run "burrow update" to install them.');
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function reportNpm(c, info) {
|
|
153
|
+
log(`burrow ${c.version}: global npm install in ${info.prefix}`);
|
|
154
|
+
if (c.upToDate === true) { log(`Up to date (${short(c.latest)} from ${c.url}).`); return; }
|
|
155
|
+
if (c.upToDate === false) log(`Newer commit available: ${short(c.installed)} -> ${short(c.latest)} (${c.url}).`);
|
|
156
|
+
else log(`Installed commit unknown (not installed from git); latest is ${short(c.latest)} on ${c.url}.`);
|
|
157
|
+
log('Run "burrow update" to install it.');
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function updateGit(info, opts) {
|
|
161
|
+
const cwd = info.root;
|
|
162
|
+
if (git(cwd, 'status', '--porcelain', '--untracked-files=no')) {
|
|
163
|
+
throw new Error(`${cwd} has local changes. Commit or stash them, then run burrow update again.`);
|
|
164
|
+
}
|
|
165
|
+
const c = checkGit(info);
|
|
166
|
+
if (!c.behind) { log(`Already up to date (${short(c.head)} on ${c.branch}).`); return; }
|
|
167
|
+
if (c.ahead) throw new Error(`${c.branch} has ${c.ahead} local commit(s) that ${c.upstream} doesn't; a fast-forward pull isn't possible.`);
|
|
168
|
+
if (opts.dryRun) {
|
|
169
|
+
log(`[dry-run] ${c.behind} new commit(s). Would run in ${cwd}: git pull --ff-only, then ${npmBin()} install`);
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
must(gitBin(), ['pull', '--ff-only', '--quiet'], { cwd, timeout: PULL_TIMEOUT });
|
|
173
|
+
const now = git(cwd, 'rev-parse', 'HEAD');
|
|
174
|
+
log(`Pulled ${c.behind} commit(s): ${short(c.head)} -> ${short(now)}`);
|
|
175
|
+
log(`Running ${npmBin()} install…`);
|
|
176
|
+
must(npmBin(), ['install', '--no-audit', '--no-fund'], { cwd, timeout: NPM_TIMEOUT, inherit: true });
|
|
177
|
+
log(`burrow is now ${readPkg(cwd).version} (${short(now)}).`);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function reportRegistry(c, info) {
|
|
181
|
+
log(`burrow ${c.version}: global npm install of ${c.name} in ${info.prefix}`);
|
|
182
|
+
if (c.upToDate) { log(`Up to date (latest on npm is ${c.latest}).`); return; }
|
|
183
|
+
log(`Newer version on npm: ${c.version} -> ${c.latest}.`);
|
|
184
|
+
log('Run "burrow update" to install it.');
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function updateRegistry(info, opts) {
|
|
188
|
+
const name = info.pkg.name;
|
|
189
|
+
if (!opts.force) {
|
|
190
|
+
let c = null;
|
|
191
|
+
try { c = checkRegistry(info); } catch (e) { log(`Couldn't check npm (${e.message}); reinstalling anyway.`); }
|
|
192
|
+
if (c?.upToDate) { log(`Already up to date (${c.version}). Use --force to reinstall.`); return; }
|
|
193
|
+
}
|
|
194
|
+
const args = ['install', '-g', `${name}@latest`, '--prefix', info.prefix, '--no-audit', '--no-fund'];
|
|
195
|
+
if (opts.dryRun) { log(`[dry-run] would run: ${npmBin()} ${args.join(' ')}`); return; }
|
|
196
|
+
log(`Running: ${npmBin()} ${args.join(' ')}`);
|
|
197
|
+
must(npmBin(), args, { timeout: NPM_TIMEOUT, inherit: true });
|
|
198
|
+
let version = '?';
|
|
199
|
+
try { version = readPkg(info.root).version; } catch {}
|
|
200
|
+
log(`burrow is now ${version}.`);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function updateNpm(info, opts) {
|
|
204
|
+
if (info.registry) return updateRegistry(info, opts);
|
|
205
|
+
const src = updateSource(info);
|
|
206
|
+
if (!opts.force) {
|
|
207
|
+
let c = null;
|
|
208
|
+
try { c = checkNpm(info); } catch (e) { log(`Couldn't check ${src.url} (${e.message}); reinstalling anyway.`); }
|
|
209
|
+
if (c?.upToDate) { log(`Already up to date (${short(c.latest)}). Use --force to reinstall.`); return; }
|
|
210
|
+
}
|
|
211
|
+
const args = ['install', '-g', src.spec, '--prefix', info.prefix, '--no-audit', '--no-fund'];
|
|
212
|
+
if (opts.dryRun) { log(`[dry-run] would run: ${npmBin()} ${args.join(' ')}`); return; }
|
|
213
|
+
log(`Running: ${npmBin()} ${args.join(' ')}`);
|
|
214
|
+
must(npmBin(), args, { timeout: NPM_TIMEOUT, inherit: true });
|
|
215
|
+
let version = '?';
|
|
216
|
+
try { version = readPkg(info.root).version; } catch {}
|
|
217
|
+
log(`burrow is now ${version}.`);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// One object for `update --check --json`: is something newer available, and what.
|
|
221
|
+
export function checkSummary(info) {
|
|
222
|
+
const base = { mode: info.mode, version: info.pkg.version, checkedAt: new Date().toISOString() };
|
|
223
|
+
if (info.mode === 'git') {
|
|
224
|
+
const c = checkGit(info);
|
|
225
|
+
return {
|
|
226
|
+
...base, available: c.behind > 0, branch: c.branch, upstream: c.upstream, head: short(c.head), latest: short(c.remote),
|
|
227
|
+
behind: c.behind, ahead: c.ahead, commits: c.commits, remoteVersion: c.remoteVersion,
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
if (info.registry) {
|
|
231
|
+
const r = checkRegistry(info);
|
|
232
|
+
return { ...base, available: !r.upToDate, latest: r.latest, source: 'npm' };
|
|
233
|
+
}
|
|
234
|
+
const c = checkNpm(info);
|
|
235
|
+
return { ...base, available: c.upToDate === null ? null : !c.upToDate, head: short(c.installed), latest: short(c.latest), source: c.url };
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
export async function update(opts = {}) {
|
|
239
|
+
const info = detectInstall();
|
|
240
|
+
if (info.mode === 'unknown') {
|
|
241
|
+
let hint = 'npm install -g burrow-cli';
|
|
242
|
+
try { hint = `npm install -g ${updateSource(info).spec}`; } catch {}
|
|
243
|
+
if (opts.json) { console.log(JSON.stringify({ mode: 'unknown', version: info.pkg.version, available: null, checkedAt: new Date().toISOString() })); return; }
|
|
244
|
+
throw new Error(`Can't tell how burrow at ${info.root} was installed (not a git checkout or a global npm install). Reinstall with: ${hint}`);
|
|
245
|
+
}
|
|
246
|
+
if (opts.json) {
|
|
247
|
+
if (!opts.check) throw new Error('--json only works with --check');
|
|
248
|
+
console.log(JSON.stringify(checkSummary(info)));
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
if (info.mode === 'git') return opts.check ? reportGit(checkGit(info), info) : updateGit(info, opts);
|
|
252
|
+
if (info.registry && opts.check) return reportRegistry(checkRegistry(info), info);
|
|
253
|
+
return opts.check ? reportNpm(checkNpm(info), info) : updateNpm(info, opts);
|
|
254
|
+
}
|
package/src/uptime.js
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// Uptime timeline: turn the event history (up/down/restart/destroy from the CLI and the
|
|
2
|
+
// dashboard, health transitions from `burrow watch`, or from the dashboard when watch isn't
|
|
3
|
+
// running: see health-observer.js) into per-project segments.
|
|
4
|
+
// Statuses: up | degraded | down (not on purpose) | stopped (on purpose) | unknown.
|
|
5
|
+
import { readFileSync } from 'node:fs';
|
|
6
|
+
import { readEvents } from './history.js';
|
|
7
|
+
import { watchStateFile } from './watch.js';
|
|
8
|
+
import { healthState } from './health-observer.js';
|
|
9
|
+
|
|
10
|
+
export const WINDOWS = { '1h': 3600e3, '24h': 24 * 3600e3, '7d': 7 * 24 * 3600e3 };
|
|
11
|
+
|
|
12
|
+
// The status an event leaves a project in, or null when it says nothing about it.
|
|
13
|
+
export function statusAfter(e) {
|
|
14
|
+
const a = String(e.action || '');
|
|
15
|
+
if (a === 'health') {
|
|
16
|
+
const m = String(e.detail || '').match(/^(ok|degraded|down)\b/);
|
|
17
|
+
return m ? (m[1] === 'ok' ? 'up' : m[1]) : null;
|
|
18
|
+
}
|
|
19
|
+
if (a === 'up' || a === 'restart' || a === 'autostart' || a === 'dashboard up') return e.ok ? 'up' : 'down';
|
|
20
|
+
if (a === 'down' || a === 'destroy' || a === 'rename' || a === 'dashboard down') return e.ok ? 'stopped' : null;
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function readWatchState() {
|
|
25
|
+
try { return JSON.parse(readFileSync(watchStateFile(), 'utf8')); } catch { return {}; }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// events: oldest first, for one project. current: status now (from the watch state or the
|
|
29
|
+
// process), or null to keep the last event's status. Returns segments clipped to the window.
|
|
30
|
+
export function buildTimeline(events, { now = Date.now(), windowMs = WINDOWS['24h'], current = null, currentSince = null } = {}) {
|
|
31
|
+
const start = now - windowMs;
|
|
32
|
+
const points = [];
|
|
33
|
+
let status = 'unknown';
|
|
34
|
+
for (const e of events) {
|
|
35
|
+
const s = statusAfter(e);
|
|
36
|
+
if (!s) continue;
|
|
37
|
+
const at = Date.parse(e.at);
|
|
38
|
+
if (!Number.isFinite(at) || at > now) continue;
|
|
39
|
+
if (at <= start) { status = s; continue; }
|
|
40
|
+
points.push({ at, status: s, event: e });
|
|
41
|
+
}
|
|
42
|
+
const segments = [];
|
|
43
|
+
let from = start;
|
|
44
|
+
const push = (to, st) => {
|
|
45
|
+
if (to <= from) return;
|
|
46
|
+
const last = segments[segments.length - 1];
|
|
47
|
+
if (last && last.status === st) last.to = to;
|
|
48
|
+
else segments.push({ from, to, status: st });
|
|
49
|
+
from = to;
|
|
50
|
+
};
|
|
51
|
+
for (const p of points) { push(p.at, status); status = p.status; }
|
|
52
|
+
// What the project is doing now wins over the last event (a crash isn't an event), from
|
|
53
|
+
// `currentSince` (the watch state) when known. A stopped project that isn't running is just stopped.
|
|
54
|
+
if (current && current !== status && !(status === 'stopped' && current === 'down')) {
|
|
55
|
+
if (Number.isFinite(currentSince) && currentSince > from && currentSince < now) push(currentSince, status);
|
|
56
|
+
status = current;
|
|
57
|
+
}
|
|
58
|
+
push(now, status);
|
|
59
|
+
const known = segments.filter((s) => s.status !== 'unknown' && s.status !== 'stopped');
|
|
60
|
+
const total = known.reduce((n, s) => n + (s.to - s.from), 0);
|
|
61
|
+
const upMs = known.filter((s) => s.status === 'up').reduce((n, s) => n + (s.to - s.from), 0);
|
|
62
|
+
const incidents = points.filter((p) => p.status === 'down' || p.status === 'degraded')
|
|
63
|
+
.map((p) => ({ at: new Date(p.at).toISOString(), status: p.status, detail: p.event.detail || p.event.action, source: p.event.source }))
|
|
64
|
+
.reverse();
|
|
65
|
+
return {
|
|
66
|
+
segments: segments.map((s) => ({ ...s, pct: ((s.to - s.from) / windowMs) * 100 })),
|
|
67
|
+
uptimePct: total ? Math.round((upMs / total) * 10000) / 100 : null,
|
|
68
|
+
incidents,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// { project: timeline } for [{ project, running, startedAt, crashed }] (crashed: a pid file but no process).
|
|
73
|
+
export function timelines(projects, { now = Date.now(), windowMs = WINDOWS['24h'] } = {}) {
|
|
74
|
+
const all = readEvents({ limit: 5000 }).reverse();
|
|
75
|
+
const watch = healthState(now); // burrow watch's state, or the dashboard's observations without it
|
|
76
|
+
const out = {};
|
|
77
|
+
for (const p of projects) {
|
|
78
|
+
const evs = all.filter((e) => e.project === p.project);
|
|
79
|
+
const w = watch[p.project];
|
|
80
|
+
let current = null;
|
|
81
|
+
let currentSince = null;
|
|
82
|
+
if (p.running === false) {
|
|
83
|
+
current = p.crashed ? 'down' : 'stopped';
|
|
84
|
+
if (p.crashed && w?.status === 'down') currentSince = w.since;
|
|
85
|
+
}
|
|
86
|
+
else if (w?.status) { current = w.status === 'ok' ? 'up' : w.status; currentSince = w.since; }
|
|
87
|
+
else if (p.running) { current = 'up'; currentSince = p.startedAt; }
|
|
88
|
+
out[p.project] = buildTimeline(evs, { now, windowMs, current, currentSince });
|
|
89
|
+
}
|
|
90
|
+
return out;
|
|
91
|
+
}
|