relayrunner 0.11.0 → 0.13.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/README.md +4 -0
- package/bin/relayrunner.js +40 -0
- package/package.json +10 -21
- package/dist/cli.js +0 -4325
package/dist/cli.js
DELETED
|
@@ -1,4325 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import * as clack from "@clack/prompts";
|
|
3
|
-
import { defineCommand, runMain } from "citty";
|
|
4
|
-
import { z } from "zod";
|
|
5
|
-
import { arch, availableParallelism, cpus, homedir, hostname, networkInterfaces, platform, release, tmpdir, totalmem } from "node:os";
|
|
6
|
-
import { basename, dirname, join, resolve } from "node:path";
|
|
7
|
-
import { appendFileSync, chmodSync, constants, cpSync, createWriteStream, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
|
8
|
-
import { execFile, spawn, spawnSync } from "node:child_process";
|
|
9
|
-
import { createHash } from "node:crypto";
|
|
10
|
-
import { Readable, Transform } from "node:stream";
|
|
11
|
-
import { pipeline } from "node:stream/promises";
|
|
12
|
-
import { styleText } from "node:util";
|
|
13
|
-
import { Scalar, YAMLSeq, isMap, isScalar, isSeq, parseDocument } from "yaml";
|
|
14
|
-
const version$1 = z.literal(1);
|
|
15
|
-
const routeId = z.string().min(1);
|
|
16
|
-
const DeviceKind = z.enum([
|
|
17
|
-
"laptop",
|
|
18
|
-
"desktop",
|
|
19
|
-
"server",
|
|
20
|
-
"vm",
|
|
21
|
-
"unknown"
|
|
22
|
-
]);
|
|
23
|
-
const text = z.string().trim().min(1).max(120);
|
|
24
|
-
const Device = z.object({
|
|
25
|
-
kind: DeviceKind,
|
|
26
|
-
model: text.optional(),
|
|
27
|
-
modelId: text.optional(),
|
|
28
|
-
chip: text.optional(),
|
|
29
|
-
cpuCores: z.number().int().positive().max(1e5).optional(),
|
|
30
|
-
memoryMb: z.number().int().positive().max(1e9).optional(),
|
|
31
|
-
osVersion: text.optional()
|
|
32
|
-
});
|
|
33
|
-
const os = z.enum([
|
|
34
|
-
"linux",
|
|
35
|
-
"macos",
|
|
36
|
-
"windows"
|
|
37
|
-
]);
|
|
38
|
-
const arch$1 = z.enum([
|
|
39
|
-
"x64",
|
|
40
|
-
"arm64",
|
|
41
|
-
"arm"
|
|
42
|
-
]);
|
|
43
|
-
const HelloMessage = z.object({
|
|
44
|
-
v: version$1,
|
|
45
|
-
type: z.literal("hello"),
|
|
46
|
-
machineId: z.string().min(1),
|
|
47
|
-
os,
|
|
48
|
-
arch: arch$1,
|
|
49
|
-
runnerVersion: z.string().min(1),
|
|
50
|
-
cliVersion: z.string().trim().min(1).max(40).optional(),
|
|
51
|
-
device: Device.optional().catch(void 0),
|
|
52
|
-
rotatesToken: z.boolean().optional(),
|
|
53
|
-
slots: z.number().int().positive().max(1e3).optional(),
|
|
54
|
-
isolated: z.object({
|
|
55
|
-
os,
|
|
56
|
-
arch: arch$1
|
|
57
|
-
}).optional(),
|
|
58
|
-
vm: z.object({
|
|
59
|
-
cpus: z.number().int().positive().max(1e4),
|
|
60
|
-
memoryGb: z.number().int().positive().max(1e5)
|
|
61
|
-
}).optional().catch(void 0)
|
|
62
|
-
});
|
|
63
|
-
const StatusMessage = z.object({
|
|
64
|
-
v: version$1,
|
|
65
|
-
type: z.literal("status"),
|
|
66
|
-
state: z.enum(["idle", "busy"]),
|
|
67
|
-
running: z.number().int().nonnegative().max(1e3).optional(),
|
|
68
|
-
runnerVersion: z.string().min(1).optional()
|
|
69
|
-
});
|
|
70
|
-
const JobUsage = z.object({
|
|
71
|
-
cpuP95: z.number().min(0).max(1),
|
|
72
|
-
cpuPeak: z.number().min(0).max(1),
|
|
73
|
-
memoryP95Mb: z.number().int().nonnegative(),
|
|
74
|
-
memoryPeakMb: z.number().int().nonnegative(),
|
|
75
|
-
cpus: z.number().int().positive().max(1e5),
|
|
76
|
-
memoryMb: z.number().int().positive().max(1e9),
|
|
77
|
-
samples: z.number().int().positive()
|
|
78
|
-
});
|
|
79
|
-
const JobMessage = z.object({
|
|
80
|
-
v: version$1,
|
|
81
|
-
type: z.literal("job"),
|
|
82
|
-
routeId,
|
|
83
|
-
state: z.enum([
|
|
84
|
-
"started",
|
|
85
|
-
"finished",
|
|
86
|
-
"failed"
|
|
87
|
-
]),
|
|
88
|
-
message: z.string().optional(),
|
|
89
|
-
usage: JobUsage.optional().catch(void 0)
|
|
90
|
-
});
|
|
91
|
-
const TokenSavedMessage = z.object({
|
|
92
|
-
v: version$1,
|
|
93
|
-
type: z.literal("token_saved")
|
|
94
|
-
});
|
|
95
|
-
z.discriminatedUnion("type", [
|
|
96
|
-
HelloMessage,
|
|
97
|
-
StatusMessage,
|
|
98
|
-
JobMessage,
|
|
99
|
-
TokenSavedMessage
|
|
100
|
-
]);
|
|
101
|
-
const RunMessage = z.object({
|
|
102
|
-
v: version$1,
|
|
103
|
-
type: z.literal("run"),
|
|
104
|
-
routeId,
|
|
105
|
-
jitConfig: z.string().min(1),
|
|
106
|
-
isolated: z.boolean().optional()
|
|
107
|
-
});
|
|
108
|
-
const ErrorMessage = z.object({
|
|
109
|
-
v: version$1,
|
|
110
|
-
type: z.literal("error"),
|
|
111
|
-
code: z.enum(["version_mismatch", "invalid_message"]),
|
|
112
|
-
message: z.string()
|
|
113
|
-
});
|
|
114
|
-
const PausedMessage = z.object({
|
|
115
|
-
v: version$1,
|
|
116
|
-
type: z.literal("paused"),
|
|
117
|
-
paused: z.boolean(),
|
|
118
|
-
by: z.string().nullable()
|
|
119
|
-
});
|
|
120
|
-
const TokenMessage = z.object({
|
|
121
|
-
v: version$1,
|
|
122
|
-
type: z.literal("token"),
|
|
123
|
-
token: z.string().min(1)
|
|
124
|
-
});
|
|
125
|
-
const GatewayMessage = z.discriminatedUnion("type", [
|
|
126
|
-
RunMessage,
|
|
127
|
-
ErrorMessage,
|
|
128
|
-
PausedMessage,
|
|
129
|
-
TokenMessage
|
|
130
|
-
]);
|
|
131
|
-
function parseGatewayMessage(frame) {
|
|
132
|
-
return parse$1(GatewayMessage, frame);
|
|
133
|
-
}
|
|
134
|
-
function encodeMessage(message) {
|
|
135
|
-
return JSON.stringify(message);
|
|
136
|
-
}
|
|
137
|
-
function parse$1(schema, frame) {
|
|
138
|
-
let data;
|
|
139
|
-
try {
|
|
140
|
-
data = JSON.parse(frame);
|
|
141
|
-
} catch (error) {
|
|
142
|
-
return {
|
|
143
|
-
ok: false,
|
|
144
|
-
reason: "invalid_json",
|
|
145
|
-
error: String(error)
|
|
146
|
-
};
|
|
147
|
-
}
|
|
148
|
-
const v = typeof data === "object" && data !== null ? data.v : void 0;
|
|
149
|
-
if (v !== 1) return {
|
|
150
|
-
ok: false,
|
|
151
|
-
reason: "version_mismatch",
|
|
152
|
-
error: `expected protocol version 1, got ${JSON.stringify(v) ?? "none"}`
|
|
153
|
-
};
|
|
154
|
-
const result = schema.safeParse(data);
|
|
155
|
-
if (!result.success) return {
|
|
156
|
-
ok: false,
|
|
157
|
-
reason: "invalid_message",
|
|
158
|
-
error: z.prettifyError(result.error)
|
|
159
|
-
};
|
|
160
|
-
return {
|
|
161
|
-
ok: true,
|
|
162
|
-
message: result.data
|
|
163
|
-
};
|
|
164
|
-
}
|
|
165
|
-
// ../../packages/machine-protocol/src/runner-name.ts
|
|
166
|
-
/** Whether `runnerName` is a machineRunnerName() for `routeId`, whatever the machine is called. */
|
|
167
|
-
function isRunnerForRoute(runnerName, routeId) {
|
|
168
|
-
return runnerName.endsWith(`-${routeId}`);
|
|
169
|
-
}
|
|
170
|
-
// ../../packages/machine-protocol/src/cli-version.ts
|
|
171
|
-
/** Whether `candidate` is a newer release than `current`. Only plain x.y.z releases count, so a prerelease never reads as newer. */
|
|
172
|
-
function isNewerVersion(candidate, current) {
|
|
173
|
-
const a = parse(candidate);
|
|
174
|
-
const b = parse(current);
|
|
175
|
-
if (!a || !b) return false;
|
|
176
|
-
for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i];
|
|
177
|
-
return false;
|
|
178
|
-
}
|
|
179
|
-
function parse(version) {
|
|
180
|
-
const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version.trim());
|
|
181
|
-
return match ? [
|
|
182
|
-
Number(match[1]),
|
|
183
|
-
Number(match[2]),
|
|
184
|
-
Number(match[3])
|
|
185
|
-
] : null;
|
|
186
|
-
}
|
|
187
|
-
// version.ts
|
|
188
|
-
const cliVersion = "0.11.0";
|
|
189
|
-
// paths.ts
|
|
190
|
-
function relayrunnerHome() {
|
|
191
|
-
return resolve(process.env.RELAYRUNNER_HOME || join(homedir(), ".relayrunner"));
|
|
192
|
-
}
|
|
193
|
-
function runnersDir() {
|
|
194
|
-
return join(relayrunnerHome(), "runner");
|
|
195
|
-
}
|
|
196
|
-
const userAgent = `relayrunner-cli/${cliVersion}`;
|
|
197
|
-
const CLOSE_POLICY = 1008;
|
|
198
|
-
const NodeWebSocket = WebSocket;
|
|
199
|
-
function connectUrl(server) {
|
|
200
|
-
const url = new URL("/api/machines/connect", server);
|
|
201
|
-
url.protocol = url.protocol === "http:" ? "ws:" : "wss:";
|
|
202
|
-
return url.toString();
|
|
203
|
-
}
|
|
204
|
-
function backoff(attempt, min, max, random = Math.random) {
|
|
205
|
-
const base = Math.min(max, min * 2 ** Math.max(0, attempt - 1));
|
|
206
|
-
return Math.round(base * (.75 + random() * .5));
|
|
207
|
-
}
|
|
208
|
-
async function connect(options) {
|
|
209
|
-
const heartbeatMs = options.heartbeatMs ?? 3e4;
|
|
210
|
-
const minBackoffMs = options.minBackoffMs ?? 1e3;
|
|
211
|
-
const maxBackoffMs = options.maxBackoffMs ?? 3e4;
|
|
212
|
-
const reconnectSpreadMs = options.reconnectSpreadMs ?? 1e4;
|
|
213
|
-
const emit = options.onEvent ?? (() => {});
|
|
214
|
-
const signal = options.signal;
|
|
215
|
-
const slots = options.slots ?? 1;
|
|
216
|
-
const busy = /* @__PURE__ */ new Set();
|
|
217
|
-
let socket = null;
|
|
218
|
-
let token = options.token;
|
|
219
|
-
const pending = [];
|
|
220
|
-
let gatewayError = "";
|
|
221
|
-
const send = (message) => {
|
|
222
|
-
if (socket?.readyState === WebSocket.OPEN) socket.send(encodeMessage(message));
|
|
223
|
-
else if (message.type === "job") pending.push(message);
|
|
224
|
-
};
|
|
225
|
-
const runnerVersion = () => options.runnerVersion?.() ?? options.hello.runnerVersion;
|
|
226
|
-
let saidVersion = "";
|
|
227
|
-
const sendStatus = () => {
|
|
228
|
-
const version = runnerVersion();
|
|
229
|
-
const changed = version !== saidVersion && socket?.readyState === WebSocket.OPEN;
|
|
230
|
-
send({
|
|
231
|
-
v: 1,
|
|
232
|
-
type: "status",
|
|
233
|
-
state: busy.size > 0 ? "busy" : "idle",
|
|
234
|
-
running: busy.size,
|
|
235
|
-
...changed && { runnerVersion: version }
|
|
236
|
-
});
|
|
237
|
-
if (changed) saidVersion = version;
|
|
238
|
-
};
|
|
239
|
-
const saveToken = (next) => {
|
|
240
|
-
if (!options.saveToken) return;
|
|
241
|
-
try {
|
|
242
|
-
options.saveToken(next);
|
|
243
|
-
} catch (error) {
|
|
244
|
-
emit({
|
|
245
|
-
type: "token-not-saved",
|
|
246
|
-
message: error instanceof Error ? error.message : String(error)
|
|
247
|
-
});
|
|
248
|
-
return;
|
|
249
|
-
}
|
|
250
|
-
token = next;
|
|
251
|
-
send({
|
|
252
|
-
v: 1,
|
|
253
|
-
type: "token_saved"
|
|
254
|
-
});
|
|
255
|
-
};
|
|
256
|
-
const startJob = (run) => {
|
|
257
|
-
let slot = 1;
|
|
258
|
-
while (busy.has(slot)) slot++;
|
|
259
|
-
if (slot > slots) {
|
|
260
|
-
emit({
|
|
261
|
-
type: "run-refused",
|
|
262
|
-
routeId: run.routeId,
|
|
263
|
-
running: busy.size
|
|
264
|
-
});
|
|
265
|
-
const update = {
|
|
266
|
-
routeId: run.routeId,
|
|
267
|
-
state: "failed",
|
|
268
|
-
message: busy.size === 1 ? "The machine is already running a job." : `The machine is already running ${busy.size} jobs.`
|
|
269
|
-
};
|
|
270
|
-
send({
|
|
271
|
-
v: 1,
|
|
272
|
-
type: "job",
|
|
273
|
-
...update
|
|
274
|
-
});
|
|
275
|
-
return;
|
|
276
|
-
}
|
|
277
|
-
emit({
|
|
278
|
-
type: "run",
|
|
279
|
-
routeId: run.routeId,
|
|
280
|
-
slot
|
|
281
|
-
});
|
|
282
|
-
busy.add(slot);
|
|
283
|
-
sendStatus();
|
|
284
|
-
options.runJob(run, slot, (update) => {
|
|
285
|
-
emit({
|
|
286
|
-
type: "job",
|
|
287
|
-
update,
|
|
288
|
-
slot
|
|
289
|
-
});
|
|
290
|
-
send({
|
|
291
|
-
v: 1,
|
|
292
|
-
type: "job",
|
|
293
|
-
...update
|
|
294
|
-
});
|
|
295
|
-
}).finally(() => {
|
|
296
|
-
busy.delete(slot);
|
|
297
|
-
sendStatus();
|
|
298
|
-
});
|
|
299
|
-
};
|
|
300
|
-
const session = () => new Promise((resolve) => {
|
|
301
|
-
let opened = false;
|
|
302
|
-
let heartbeat;
|
|
303
|
-
const ws = new NodeWebSocket(connectUrl(options.server), { headers: {
|
|
304
|
-
authorization: `Bearer ${token}`,
|
|
305
|
-
"user-agent": userAgent
|
|
306
|
-
} });
|
|
307
|
-
socket = ws;
|
|
308
|
-
let settled = false;
|
|
309
|
-
const finish = (code, reason) => {
|
|
310
|
-
if (settled) return;
|
|
311
|
-
settled = true;
|
|
312
|
-
clearInterval(heartbeat);
|
|
313
|
-
signal?.removeEventListener("abort", onAbort);
|
|
314
|
-
if (socket === ws) socket = null;
|
|
315
|
-
resolve({
|
|
316
|
-
opened,
|
|
317
|
-
code,
|
|
318
|
-
reason
|
|
319
|
-
});
|
|
320
|
-
};
|
|
321
|
-
const onAbort = () => {
|
|
322
|
-
ws.close(1e3, "machine going offline");
|
|
323
|
-
finish(1e3, "machine going offline");
|
|
324
|
-
};
|
|
325
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
326
|
-
ws.addEventListener("open", () => {
|
|
327
|
-
opened = true;
|
|
328
|
-
emit({ type: "connected" });
|
|
329
|
-
const rotatesToken = options.saveToken ? true : void 0;
|
|
330
|
-
saidVersion = runnerVersion();
|
|
331
|
-
ws.send(encodeMessage({
|
|
332
|
-
v: 1,
|
|
333
|
-
type: "hello",
|
|
334
|
-
...options.hello,
|
|
335
|
-
runnerVersion: saidVersion,
|
|
336
|
-
slots,
|
|
337
|
-
rotatesToken
|
|
338
|
-
}));
|
|
339
|
-
sendStatus();
|
|
340
|
-
for (const message of pending.splice(0)) send(message);
|
|
341
|
-
heartbeat = setInterval(sendStatus, heartbeatMs);
|
|
342
|
-
});
|
|
343
|
-
ws.addEventListener("message", (event) => {
|
|
344
|
-
if (typeof event.data !== "string") return;
|
|
345
|
-
const parsed = parseGatewayMessage(event.data);
|
|
346
|
-
if (!parsed.ok) {
|
|
347
|
-
emit({
|
|
348
|
-
type: "gateway-error",
|
|
349
|
-
code: parsed.reason,
|
|
350
|
-
message: parsed.error
|
|
351
|
-
});
|
|
352
|
-
return;
|
|
353
|
-
}
|
|
354
|
-
const message = parsed.message;
|
|
355
|
-
if (message.type === "run") startJob(message);
|
|
356
|
-
else if (message.type === "paused") emit({
|
|
357
|
-
type: "paused",
|
|
358
|
-
paused: message.paused,
|
|
359
|
-
by: message.by
|
|
360
|
-
});
|
|
361
|
-
else if (message.type === "token") saveToken(message.token);
|
|
362
|
-
else {
|
|
363
|
-
gatewayError = message.message;
|
|
364
|
-
emit({
|
|
365
|
-
type: "gateway-error",
|
|
366
|
-
code: message.code,
|
|
367
|
-
message: message.message
|
|
368
|
-
});
|
|
369
|
-
}
|
|
370
|
-
});
|
|
371
|
-
ws.addEventListener("close", (event) => finish(event.code, event.reason));
|
|
372
|
-
ws.addEventListener("error", () => {
|
|
373
|
-
if (!opened) finish(1006, "");
|
|
374
|
-
});
|
|
375
|
-
});
|
|
376
|
-
const tokenRejected = () => fetch(new URL("/api/machines/connect", options.server), {
|
|
377
|
-
headers: {
|
|
378
|
-
authorization: `Bearer ${token}`,
|
|
379
|
-
"user-agent": userAgent
|
|
380
|
-
},
|
|
381
|
-
signal: AbortSignal.timeout(1e4)
|
|
382
|
-
}).then(async (response) => {
|
|
383
|
-
await response.body?.cancel();
|
|
384
|
-
return response.status === 401;
|
|
385
|
-
}, () => false);
|
|
386
|
-
let attempt = 0;
|
|
387
|
-
while (!signal?.aborted) {
|
|
388
|
-
attempt++;
|
|
389
|
-
emit({
|
|
390
|
-
type: "connecting",
|
|
391
|
-
attempt
|
|
392
|
-
});
|
|
393
|
-
const { opened, code, reason } = await session();
|
|
394
|
-
if (signal?.aborted) break;
|
|
395
|
-
if (opened) attempt = 1;
|
|
396
|
-
if (code === 4001) return { reason: "revoked" };
|
|
397
|
-
if (code === 4002) return { reason: "replaced" };
|
|
398
|
-
if (code === CLOSE_POLICY) return {
|
|
399
|
-
reason: "rejected",
|
|
400
|
-
message: gatewayError || reason || "protocol error"
|
|
401
|
-
};
|
|
402
|
-
if (!opened && await tokenRejected()) return { reason: "revoked" };
|
|
403
|
-
const retryInMs = opened ? Math.round(Math.random() * reconnectSpreadMs) : backoff(attempt, minBackoffMs, maxBackoffMs);
|
|
404
|
-
emit({
|
|
405
|
-
type: "disconnected",
|
|
406
|
-
code,
|
|
407
|
-
reason,
|
|
408
|
-
retryInMs
|
|
409
|
-
});
|
|
410
|
-
await delay(retryInMs, signal);
|
|
411
|
-
}
|
|
412
|
-
return { reason: "stopped" };
|
|
413
|
-
}
|
|
414
|
-
function delay(ms, signal) {
|
|
415
|
-
return new Promise((resolve) => {
|
|
416
|
-
const timer = setTimeout(done, ms);
|
|
417
|
-
signal?.addEventListener("abort", done, { once: true });
|
|
418
|
-
function done() {
|
|
419
|
-
clearTimeout(timer);
|
|
420
|
-
signal?.removeEventListener("abort", done);
|
|
421
|
-
resolve();
|
|
422
|
-
}
|
|
423
|
-
});
|
|
424
|
-
}
|
|
425
|
-
// install.ts
|
|
426
|
-
var RunnerError = class extends Error {
|
|
427
|
-
code;
|
|
428
|
-
constructor(code, message) {
|
|
429
|
-
super(message);
|
|
430
|
-
this.code = code;
|
|
431
|
-
}
|
|
432
|
-
};
|
|
433
|
-
const LATEST_RELEASE = "https://api.github.com/repos/actions/runner/releases/latest";
|
|
434
|
-
const ARCHIVE_URL = /^https:\/\/github\.com\/actions\/runner\/releases\/download\/v[\d.]+\/actions-runner-[\w.-]+\.tar\.gz$/;
|
|
435
|
-
const SHA256 = /^[a-f\d]{64}$/;
|
|
436
|
-
const Release = z.object({
|
|
437
|
-
tag_name: z.string().regex(/^v\d+\.\d+\.\d+$/),
|
|
438
|
-
body: z.string().nullish(),
|
|
439
|
-
assets: z.array(z.object({
|
|
440
|
-
name: z.string(),
|
|
441
|
-
browser_download_url: z.string(),
|
|
442
|
-
digest: z.string().nullish()
|
|
443
|
-
}))
|
|
444
|
-
});
|
|
445
|
-
function runnerPlatform() {
|
|
446
|
-
const system = platform();
|
|
447
|
-
const os = system === "darwin" ? "osx" : system;
|
|
448
|
-
const architecture = arch();
|
|
449
|
-
if (os !== "osx" && os !== "linux" || architecture !== "x64" && architecture !== "arm64" || process.getuid?.() === 0) throw new RunnerError("UNSUPPORTED_MACHINE", "Run as a regular user on macOS or Linux (x64 or arm64).");
|
|
450
|
-
return {
|
|
451
|
-
os,
|
|
452
|
-
arch: architecture
|
|
453
|
-
};
|
|
454
|
-
}
|
|
455
|
-
function pickDownload(release, target) {
|
|
456
|
-
const parsed = Release.safeParse(release);
|
|
457
|
-
if (!parsed.success) throw new RunnerError("RUNNER_DOWNLOAD", "GitHub returned an unexpected runner release.");
|
|
458
|
-
const { tag_name, body, assets } = parsed.data;
|
|
459
|
-
const version = tag_name.slice(1);
|
|
460
|
-
const name = `actions-runner-${target.os}-${target.arch}-${version}.tar.gz`;
|
|
461
|
-
const asset = assets.find((item) => item.name === name);
|
|
462
|
-
const key = `${target.os}-${target.arch}`;
|
|
463
|
-
const fromNotes = body?.match(new RegExp(`<!-- BEGIN SHA ${key} -->\\s*([a-fA-F\\d]{64})\\s*<!-- END SHA ${key} -->`))?.[1]?.toLowerCase();
|
|
464
|
-
const fromDigest = asset?.digest?.match(/^sha256:([a-fA-F\d]{64})$/)?.[1]?.toLowerCase();
|
|
465
|
-
const sha256 = fromDigest ?? fromNotes;
|
|
466
|
-
if (!asset || !ARCHIVE_URL.test(asset.browser_download_url) || !sha256 || !SHA256.test(sha256) || fromDigest && fromNotes && fromDigest !== fromNotes) throw new RunnerError("RUNNER_DOWNLOAD", `GitHub did not provide a ${name} archive with a SHA-256 checksum.`);
|
|
467
|
-
return {
|
|
468
|
-
version,
|
|
469
|
-
url: asset.browser_download_url,
|
|
470
|
-
sha256
|
|
471
|
-
};
|
|
472
|
-
}
|
|
473
|
-
async function latestRelease() {
|
|
474
|
-
const response = await fetch(LATEST_RELEASE, { headers: {
|
|
475
|
-
accept: "application/vnd.github+json",
|
|
476
|
-
"user-agent": userAgent
|
|
477
|
-
} });
|
|
478
|
-
if (!response.ok) throw new RunnerError("RUNNER_DOWNLOAD", `Could not look up the latest actions/runner release (HTTP ${response.status}).`);
|
|
479
|
-
return response.json();
|
|
480
|
-
}
|
|
481
|
-
async function latestRunnerVersion(log = () => {}) {
|
|
482
|
-
try {
|
|
483
|
-
return Release.parse(await latestRelease()).tag_name.slice(1);
|
|
484
|
-
} catch (error) {
|
|
485
|
-
const [newest] = installedRunners();
|
|
486
|
-
if (!newest) throw error;
|
|
487
|
-
log(`Couldn't check for a newer runner (${error.message}). Using ${newest.version}.`);
|
|
488
|
-
return newest.version;
|
|
489
|
-
}
|
|
490
|
-
}
|
|
491
|
-
function installedRunners(root = runnersDir()) {
|
|
492
|
-
if (!existsSync(root)) return [];
|
|
493
|
-
return readdirSync(root).filter((name) => /^\d+\.\d+\.\d+$/.test(name) && existsSync(join(root, name, "run.sh"))).sort((a, b) => compareVersions(b, a)).map((version) => ({
|
|
494
|
-
version,
|
|
495
|
-
dir: join(root, version)
|
|
496
|
-
}));
|
|
497
|
-
}
|
|
498
|
-
function compareVersions(a, b) {
|
|
499
|
-
const [x, y] = [a, b].map((v) => v.split(".").map(Number));
|
|
500
|
-
for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] - y[i];
|
|
501
|
-
return 0;
|
|
502
|
-
}
|
|
503
|
-
async function ensureRunner(options = {}) {
|
|
504
|
-
const root = options.root ?? runnersDir();
|
|
505
|
-
const log = options.log ?? (() => {});
|
|
506
|
-
const target = runnerPlatform();
|
|
507
|
-
let download;
|
|
508
|
-
try {
|
|
509
|
-
download = pickDownload(await latestRelease(), target);
|
|
510
|
-
} catch (error) {
|
|
511
|
-
const [newest] = installedRunners(root);
|
|
512
|
-
if (newest) {
|
|
513
|
-
log(`Couldn't check for a newer runner (${error.message}). Using ${newest.version}.`);
|
|
514
|
-
return newest;
|
|
515
|
-
}
|
|
516
|
-
throw error;
|
|
517
|
-
}
|
|
518
|
-
const dir = join(root, download.version);
|
|
519
|
-
if (existsSync(join(dir, "run.sh"))) return {
|
|
520
|
-
version: download.version,
|
|
521
|
-
dir
|
|
522
|
-
};
|
|
523
|
-
log(`Downloading GitHub's official runner (actions/runner ${download.version})…`);
|
|
524
|
-
await install(root, download);
|
|
525
|
-
log(`Installed actions/runner ${download.version} in ${dir}`);
|
|
526
|
-
return {
|
|
527
|
-
version: download.version,
|
|
528
|
-
dir
|
|
529
|
-
};
|
|
530
|
-
}
|
|
531
|
-
async function install(root, download, fetcher = fetch) {
|
|
532
|
-
mkdirSync(root, {
|
|
533
|
-
recursive: true,
|
|
534
|
-
mode: 448
|
|
535
|
-
});
|
|
536
|
-
const temp = mkdtempSync(join(root, ".install-"));
|
|
537
|
-
try {
|
|
538
|
-
const archive = join(temp, "runner.tar.gz");
|
|
539
|
-
const response = await fetcher(download.url, {
|
|
540
|
-
headers: { "user-agent": userAgent },
|
|
541
|
-
signal: AbortSignal.timeout(6e5)
|
|
542
|
-
});
|
|
543
|
-
if (!response.ok || !response.body) throw new RunnerError("RUNNER_DOWNLOAD", `Runner download failed (HTTP ${response.status}). Check network access.`);
|
|
544
|
-
const hash = createHash("sha256");
|
|
545
|
-
await pipeline(Readable.fromWeb(response.body), new Transform({ transform(chunk, _encoding, done) {
|
|
546
|
-
hash.update(chunk);
|
|
547
|
-
done(null, chunk);
|
|
548
|
-
} }), createWriteStream(archive, { mode: 384 }));
|
|
549
|
-
if (hash.digest("hex") !== download.sha256) throw new RunnerError("RUNNER_CHECKSUM", "The runner archive failed SHA-256 verification.");
|
|
550
|
-
const unpacked = join(temp, "runner");
|
|
551
|
-
mkdirSync(unpacked, { mode: 448 });
|
|
552
|
-
if (await exitCode("tar", [
|
|
553
|
-
"-xzf",
|
|
554
|
-
archive,
|
|
555
|
-
"-C",
|
|
556
|
-
unpacked
|
|
557
|
-
]) !== 0) throw new RunnerError("RUNNER_EXTRACT", "Could not unpack the runner archive. Check tar and available disk space.");
|
|
558
|
-
try {
|
|
559
|
-
renameSync(unpacked, join(root, download.version));
|
|
560
|
-
} catch (error) {
|
|
561
|
-
const code = error.code;
|
|
562
|
-
if (code !== "EEXIST" && code !== "ENOTEMPTY") throw error;
|
|
563
|
-
}
|
|
564
|
-
} finally {
|
|
565
|
-
rmSync(temp, {
|
|
566
|
-
recursive: true,
|
|
567
|
-
force: true
|
|
568
|
-
});
|
|
569
|
-
}
|
|
570
|
-
}
|
|
571
|
-
function exitCode(command, args) {
|
|
572
|
-
return new Promise((resolve) => {
|
|
573
|
-
const child = spawn(command, args, { stdio: "ignore" });
|
|
574
|
-
child.once("error", () => resolve(null));
|
|
575
|
-
child.once("exit", (code) => resolve(code));
|
|
576
|
-
});
|
|
577
|
-
}
|
|
578
|
-
// server.ts
|
|
579
|
-
/** The URL's origin. Throws a USAGE RunnerError for anything but https, or http to localhost. */
|
|
580
|
-
function normalizeServer(value) {
|
|
581
|
-
let url;
|
|
582
|
-
try {
|
|
583
|
-
url = new URL(value);
|
|
584
|
-
if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error();
|
|
585
|
-
} catch {
|
|
586
|
-
throw new RunnerError("USAGE", `Not a valid RelayRunner URL: ${value}`);
|
|
587
|
-
}
|
|
588
|
-
if (!sendsTokenSafely(url)) throw new RunnerError("USAGE", `${url.origin} isn't https. RelayRunner only uses plain http for localhost, since the machine token is sent on every connect.`);
|
|
589
|
-
return url.origin;
|
|
590
|
-
}
|
|
591
|
-
/**
|
|
592
|
-
* The machine token goes out on every connect, so plain http is only for a gateway on this
|
|
593
|
-
* computer (local development). Credentials saved for any other http gateway aren't read either.
|
|
594
|
-
*/
|
|
595
|
-
function sendsTokenSafely(url) {
|
|
596
|
-
return url.protocol === "https:" || url.protocol === "http:" && isLoopback(url.hostname);
|
|
597
|
-
}
|
|
598
|
-
function isLoopback(hostname) {
|
|
599
|
-
return hostname === "localhost" || hostname === "[::1]" || /^127(\.\d{1,3}){3}$/.test(hostname);
|
|
600
|
-
}
|
|
601
|
-
// credentials.ts
|
|
602
|
-
const Credentials = z.object({
|
|
603
|
-
server: z.url().refine((server) => sendsTokenSafely(new URL(server))),
|
|
604
|
-
machine: z.object({
|
|
605
|
-
id: z.string().min(1),
|
|
606
|
-
name: z.string()
|
|
607
|
-
}),
|
|
608
|
-
workspace: z.object({
|
|
609
|
-
id: z.string().min(1),
|
|
610
|
-
name: z.string(),
|
|
611
|
-
slug: z.string().nullish()
|
|
612
|
-
}).optional(),
|
|
613
|
-
token: z.string().min(1)
|
|
614
|
-
});
|
|
615
|
-
function credentialsPath(home = relayrunnerHome()) {
|
|
616
|
-
return join(home, "machine.json");
|
|
617
|
-
}
|
|
618
|
-
function readCredentials(path = credentialsPath()) {
|
|
619
|
-
let text;
|
|
620
|
-
try {
|
|
621
|
-
text = readFileSync(path, "utf8");
|
|
622
|
-
} catch (error) {
|
|
623
|
-
if (error.code === "ENOENT") return null;
|
|
624
|
-
throw error;
|
|
625
|
-
}
|
|
626
|
-
try {
|
|
627
|
-
const parsed = Credentials.safeParse(JSON.parse(text));
|
|
628
|
-
return parsed.success ? parsed.data : null;
|
|
629
|
-
} catch {
|
|
630
|
-
return null;
|
|
631
|
-
}
|
|
632
|
-
}
|
|
633
|
-
function writeCredentials(credentials, path = credentialsPath()) {
|
|
634
|
-
const dir = join(path, "..");
|
|
635
|
-
mkdirSync(dir, {
|
|
636
|
-
recursive: true,
|
|
637
|
-
mode: 448
|
|
638
|
-
});
|
|
639
|
-
const temp = `${path}.${process.pid}.tmp`;
|
|
640
|
-
writeFileSync(temp, `${JSON.stringify(credentials, null, 2)}\n`, { mode: 384 });
|
|
641
|
-
chmodSync(temp, 384);
|
|
642
|
-
renameSync(temp, path);
|
|
643
|
-
}
|
|
644
|
-
function deleteCredentials(path = credentialsPath()) {
|
|
645
|
-
rmSync(path, { force: true });
|
|
646
|
-
}
|
|
647
|
-
/** Whether two sign-ins are the same machine on the same gateway (the token may differ). */
|
|
648
|
-
function sameMachine(a, b) {
|
|
649
|
-
return a.machine.id === b.machine.id && a.server === b.server;
|
|
650
|
-
}
|
|
651
|
-
/**
|
|
652
|
-
* Calls the gateway with the saved token, and once more with the file's token when it was
|
|
653
|
-
* rejected and has changed since `credentials` was read: a running `connect` rotates the token, so
|
|
654
|
-
* one read just before a rotation goes stale.
|
|
655
|
-
*/
|
|
656
|
-
async function withCurrentToken(credentials, call, path = credentialsPath()) {
|
|
657
|
-
const first = await call(credentials.token);
|
|
658
|
-
if (first.status !== "revoked") return first;
|
|
659
|
-
const now = readCredentials(path);
|
|
660
|
-
if (!now || now.token === credentials.token || !sameMachine(now, credentials)) return first;
|
|
661
|
-
return call(now.token);
|
|
662
|
-
}
|
|
663
|
-
/**
|
|
664
|
-
* Saves a token the gateway rotated, for the sign-in `credentials` holds. Throws, saving nothing,
|
|
665
|
-
* when the file now holds another sign-in (`relayrunner login` ran meanwhile) or is gone.
|
|
666
|
-
*/
|
|
667
|
-
function saveRotatedToken(credentials, token, path = credentialsPath()) {
|
|
668
|
-
const now = readCredentials(path);
|
|
669
|
-
if (!now) throw new Error("machine.json was removed");
|
|
670
|
-
if (!sameMachine(now, credentials)) throw new Error("machine.json now holds another sign-in");
|
|
671
|
-
writeCredentials({
|
|
672
|
-
...now,
|
|
673
|
-
token
|
|
674
|
-
}, path);
|
|
675
|
-
}
|
|
676
|
-
// device.ts
|
|
677
|
-
const run = (command, args) => new Promise((resolve) => {
|
|
678
|
-
execFile(command, args, {
|
|
679
|
-
timeout: 3e3,
|
|
680
|
-
encoding: "utf8"
|
|
681
|
-
}, (error, stdout) => {
|
|
682
|
-
resolve(error ? null : stdout.trim() || null);
|
|
683
|
-
});
|
|
684
|
-
});
|
|
685
|
-
const read = (path) => {
|
|
686
|
-
try {
|
|
687
|
-
return readFileSync(path, "utf8").replaceAll("\0", "").trim() || null;
|
|
688
|
-
} catch {
|
|
689
|
-
return null;
|
|
690
|
-
}
|
|
691
|
-
};
|
|
692
|
-
function defaultSources() {
|
|
693
|
-
const list = cpus();
|
|
694
|
-
return {
|
|
695
|
-
run,
|
|
696
|
-
read,
|
|
697
|
-
cpuModel: list[0]?.model,
|
|
698
|
-
cpuCount: list.length,
|
|
699
|
-
totalMemory: totalmem()
|
|
700
|
-
};
|
|
701
|
-
}
|
|
702
|
-
/** This machine's device, or undefined on a platform it can't read. Never throws. */
|
|
703
|
-
async function detectDevice(sources = defaultSources()) {
|
|
704
|
-
try {
|
|
705
|
-
const system = platform();
|
|
706
|
-
const found = system === "darwin" ? await macDevice(sources) : system === "linux" ? await linuxDevice(sources) : void 0;
|
|
707
|
-
return found && compact(found);
|
|
708
|
-
} catch {
|
|
709
|
-
return;
|
|
710
|
-
}
|
|
711
|
-
}
|
|
712
|
-
/** The specs every platform reads the same way. */
|
|
713
|
-
function commonSpecs(sources) {
|
|
714
|
-
return {
|
|
715
|
-
chip: cleanChip(sources.cpuModel),
|
|
716
|
-
cpuCores: sources.cpuCount > 0 ? sources.cpuCount : void 0,
|
|
717
|
-
memoryMb: sources.totalMemory > 0 ? Math.round(sources.totalMemory / 1024 / 1024) : void 0
|
|
718
|
-
};
|
|
719
|
-
}
|
|
720
|
-
async function macDevice(sources) {
|
|
721
|
-
const [modelId, profile, virtual, version] = await Promise.all([
|
|
722
|
-
sources.run("sysctl", ["-n", "hw.model"]),
|
|
723
|
-
sources.run("system_profiler", ["SPHardwareDataType", "-json"]),
|
|
724
|
-
sources.run("sysctl", ["-n", "kern.hv_vmm_present"]),
|
|
725
|
-
sources.run("sw_vers", ["-productVersion"])
|
|
726
|
-
]);
|
|
727
|
-
const model = profileModel(profile) ?? macModelFromId(modelId);
|
|
728
|
-
const isVm = virtual === "1" || Boolean(modelId?.startsWith("VirtualMac"));
|
|
729
|
-
return {
|
|
730
|
-
kind: isVm ? "vm" : macKind(model),
|
|
731
|
-
model: isVm ? void 0 : model,
|
|
732
|
-
modelId: modelId ?? void 0,
|
|
733
|
-
...commonSpecs(sources),
|
|
734
|
-
osVersion: version ? `macOS ${version}` : void 0
|
|
735
|
-
};
|
|
736
|
-
}
|
|
737
|
-
function profileModel(json) {
|
|
738
|
-
if (!json) return void 0;
|
|
739
|
-
try {
|
|
740
|
-
const name = JSON.parse(json).SPHardwareDataType?.[0]?.machine_name;
|
|
741
|
-
return typeof name === "string" && name.trim() ? name.trim() : void 0;
|
|
742
|
-
} catch {
|
|
743
|
-
return;
|
|
744
|
-
}
|
|
745
|
-
}
|
|
746
|
-
const MAC_FAMILIES = [
|
|
747
|
-
["MacBookPro", "MacBook Pro"],
|
|
748
|
-
["MacBookAir", "MacBook Air"],
|
|
749
|
-
["MacBook", "MacBook"],
|
|
750
|
-
["Macmini", "Mac mini"],
|
|
751
|
-
["MacPro", "Mac Pro"],
|
|
752
|
-
["iMacPro", "iMac Pro"],
|
|
753
|
-
["iMac", "iMac"]
|
|
754
|
-
];
|
|
755
|
-
function macModelFromId(modelId) {
|
|
756
|
-
if (!modelId) return void 0;
|
|
757
|
-
return MAC_FAMILIES.find(([prefix]) => modelId.startsWith(prefix))?.[1];
|
|
758
|
-
}
|
|
759
|
-
function macKind(model) {
|
|
760
|
-
if (!model) return "unknown";
|
|
761
|
-
if (model.startsWith("MacBook")) return "laptop";
|
|
762
|
-
if (/^(iMac|Mac mini|Mac Studio|Mac Pro)/.test(model)) return "desktop";
|
|
763
|
-
return "unknown";
|
|
764
|
-
}
|
|
765
|
-
async function linuxDevice(sources) {
|
|
766
|
-
const dmi = (name) => sources.read(`/sys/class/dmi/id/${name}`);
|
|
767
|
-
const vendor = dmi("sys_vendor");
|
|
768
|
-
const product = dmi("product_name");
|
|
769
|
-
const lenovoName = vendor?.toUpperCase() === "LENOVO" ? dmi("product_version") : null;
|
|
770
|
-
const boardModel = sources.read("/proc/device-tree/model");
|
|
771
|
-
const rawModel = realName(lenovoName) ?? realName(product) ?? realName(boardModel);
|
|
772
|
-
return {
|
|
773
|
-
kind: await isLinuxVm(sources, vendor, product) ? "vm" : chassisKind(dmi("chassis_type")),
|
|
774
|
-
model: rawModel,
|
|
775
|
-
modelId: product ?? boardModel ?? void 0,
|
|
776
|
-
...commonSpecs(sources),
|
|
777
|
-
osVersion: osRelease(sources.read("/etc/os-release"))
|
|
778
|
-
};
|
|
779
|
-
}
|
|
780
|
-
const VM_VENDORS = /qemu|kvm|vmware|virtualbox|innotek|xen|bochs|parallels|amazon ec2|google/i;
|
|
781
|
-
async function isLinuxVm(sources, vendor, product) {
|
|
782
|
-
const virt = await sources.run("systemd-detect-virt", ["--vm"]);
|
|
783
|
-
if (virt && virt !== "none") return true;
|
|
784
|
-
if (vendor && VM_VENDORS.test(vendor)) return true;
|
|
785
|
-
if (product && /virtual machine|vmware|virtualbox|kvm|hvm domu/i.test(product)) return true;
|
|
786
|
-
return /^flags\s*:.*\bhypervisor\b/m.test(sources.read("/proc/cpuinfo") ?? "");
|
|
787
|
-
}
|
|
788
|
-
const CHASSIS = {
|
|
789
|
-
3: "desktop",
|
|
790
|
-
4: "desktop",
|
|
791
|
-
5: "desktop",
|
|
792
|
-
6: "desktop",
|
|
793
|
-
7: "desktop",
|
|
794
|
-
8: "laptop",
|
|
795
|
-
9: "laptop",
|
|
796
|
-
10: "laptop",
|
|
797
|
-
13: "desktop",
|
|
798
|
-
14: "laptop",
|
|
799
|
-
15: "desktop",
|
|
800
|
-
16: "desktop",
|
|
801
|
-
17: "server",
|
|
802
|
-
23: "server",
|
|
803
|
-
24: "desktop",
|
|
804
|
-
25: "server",
|
|
805
|
-
28: "server",
|
|
806
|
-
29: "server",
|
|
807
|
-
31: "laptop",
|
|
808
|
-
32: "laptop",
|
|
809
|
-
35: "desktop",
|
|
810
|
-
36: "desktop"
|
|
811
|
-
};
|
|
812
|
-
function chassisKind(chassisType) {
|
|
813
|
-
return CHASSIS[Number(chassisType)] ?? "unknown";
|
|
814
|
-
}
|
|
815
|
-
const PLACEHOLDERS = [
|
|
816
|
-
/^to be filled by o\.?e\.?m\.?$/i,
|
|
817
|
-
/^system product name$/i,
|
|
818
|
-
/^system version$/i,
|
|
819
|
-
/^default string$/i,
|
|
820
|
-
/^not (specified|applicable)$/i,
|
|
821
|
-
/^o\.?e\.?m\.?$/i,
|
|
822
|
-
/^none$/i,
|
|
823
|
-
/^unknown$/i,
|
|
824
|
-
/^standard pc\b/i,
|
|
825
|
-
/^\d+$/
|
|
826
|
-
];
|
|
827
|
-
/** A model name worth showing, or undefined for a placeholder. */
|
|
828
|
-
function realName(name) {
|
|
829
|
-
const trimmed = name?.trim();
|
|
830
|
-
if (!trimmed || PLACEHOLDERS.some((pattern) => pattern.test(trimmed))) return void 0;
|
|
831
|
-
return trimmed;
|
|
832
|
-
}
|
|
833
|
-
/** "Intel(R) Xeon(R) Gold 6338 CPU @ 2.00GHz" → "Intel Xeon Gold 6338". */
|
|
834
|
-
function cleanChip(model) {
|
|
835
|
-
const cleaned = model?.replace(/\((R|TM|C)\)/gi, "").replace(/\s+CPU\s*@.*$/i, "").replace(/\s+@\s*[\d.]+\s*GHz$/i, "").replace(/\s+\d+-Core Processor$/i, "").replace(/\s+/g, " ").trim();
|
|
836
|
-
return cleaned && cleaned.toLowerCase() !== "unknown" ? cleaned : void 0;
|
|
837
|
-
}
|
|
838
|
-
/** PRETTY_NAME from /etc/os-release, such as "Ubuntu 24.04.1 LTS". */
|
|
839
|
-
function osRelease(text) {
|
|
840
|
-
return (text?.split("\n").find((l) => l.startsWith("PRETTY_NAME=")))?.slice(12).trim().replace(/^["']|["']$/g, "") || void 0;
|
|
841
|
-
}
|
|
842
|
-
function compact(device) {
|
|
843
|
-
const out = {};
|
|
844
|
-
for (const [key, value] of Object.entries(device)) {
|
|
845
|
-
if (value === void 0 || value === null || value === "") continue;
|
|
846
|
-
out[key] = typeof value === "string" ? value.slice(0, 120) : value;
|
|
847
|
-
}
|
|
848
|
-
return out;
|
|
849
|
-
}
|
|
850
|
-
// list-file.ts
|
|
851
|
-
function readList(path) {
|
|
852
|
-
try {
|
|
853
|
-
const value = JSON.parse(readFileSync(path, "utf8"));
|
|
854
|
-
return Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : [];
|
|
855
|
-
} catch {
|
|
856
|
-
return [];
|
|
857
|
-
}
|
|
858
|
-
}
|
|
859
|
-
function writeList(path, list) {
|
|
860
|
-
mkdirSync(dirname(path), {
|
|
861
|
-
recursive: true,
|
|
862
|
-
mode: 448
|
|
863
|
-
});
|
|
864
|
-
writeFileSync(path, `${JSON.stringify(list, null, 2)}\n`);
|
|
865
|
-
}
|
|
866
|
-
// declined.ts
|
|
867
|
-
function declinedPath(home = relayrunnerHome()) {
|
|
868
|
-
return join(home, "declined-repos.json");
|
|
869
|
-
}
|
|
870
|
-
function isDeclined(repo, path = declinedPath()) {
|
|
871
|
-
return readList(path).includes(repo);
|
|
872
|
-
}
|
|
873
|
-
function rememberDeclined(repo, path = declinedPath()) {
|
|
874
|
-
const repos = readList(path);
|
|
875
|
-
if (!repos.includes(repo)) writeList(path, [...repos, repo]);
|
|
876
|
-
}
|
|
877
|
-
// diff.ts
|
|
878
|
-
function unifiedDiff(before, after, file, context = 2) {
|
|
879
|
-
const a = before.split("\n");
|
|
880
|
-
const b = after.split("\n");
|
|
881
|
-
const lcs = Array.from({ length: a.length + 1 }, () => Array.from({ length: b.length + 1 }).fill(0));
|
|
882
|
-
for (let i = a.length - 1; i >= 0; i--) for (let j = b.length - 1; j >= 0; j--) lcs[i][j] = a[i] === b[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
|
|
883
|
-
const lines = [];
|
|
884
|
-
let i = 0;
|
|
885
|
-
let j = 0;
|
|
886
|
-
while (i < a.length || j < b.length) if (i < a.length && j < b.length && a[i] === b[j]) lines.push({
|
|
887
|
-
kind: " ",
|
|
888
|
-
text: a[i],
|
|
889
|
-
a: i++,
|
|
890
|
-
b: j++
|
|
891
|
-
});
|
|
892
|
-
else if (i < a.length && (j >= b.length || lcs[i + 1][j] >= lcs[i][j + 1])) lines.push({
|
|
893
|
-
kind: "-",
|
|
894
|
-
text: a[i],
|
|
895
|
-
a: i++,
|
|
896
|
-
b: j
|
|
897
|
-
});
|
|
898
|
-
else lines.push({
|
|
899
|
-
kind: "+",
|
|
900
|
-
text: b[j],
|
|
901
|
-
a: i,
|
|
902
|
-
b: j++
|
|
903
|
-
});
|
|
904
|
-
const changed = lines.flatMap((line, index) => line.kind === " " ? [] : [index]);
|
|
905
|
-
if (!changed.length) return "";
|
|
906
|
-
const out = [`--- a/${file}`, `+++ b/${file}`];
|
|
907
|
-
let start = 0;
|
|
908
|
-
while (start < changed.length) {
|
|
909
|
-
let end = start;
|
|
910
|
-
while (end + 1 < changed.length && changed[end + 1] - changed[end] <= context * 2 + 1) end++;
|
|
911
|
-
const from = Math.max(0, changed[start] - context);
|
|
912
|
-
const to = Math.min(lines.length - 1, changed[end] + context);
|
|
913
|
-
const hunk = lines.slice(from, to + 1);
|
|
914
|
-
const aCount = hunk.filter((line) => line.kind !== "+").length;
|
|
915
|
-
const bCount = hunk.filter((line) => line.kind !== "-").length;
|
|
916
|
-
out.push(`@@ -${hunk[0].a + 1},${aCount} +${hunk[0].b + 1},${bCount} @@`);
|
|
917
|
-
for (const line of hunk) out.push(`${line.kind}${line.text}`);
|
|
918
|
-
start = end + 1;
|
|
919
|
-
}
|
|
920
|
-
return out.join("\n");
|
|
921
|
-
}
|
|
922
|
-
// jit-config.ts
|
|
923
|
-
const GITHUB_HOSTS = [
|
|
924
|
-
/^github\.com$/,
|
|
925
|
-
/\.github\.com$/,
|
|
926
|
-
/\.githubusercontent\.com$/
|
|
927
|
-
];
|
|
928
|
-
const FILES = [
|
|
929
|
-
".runner",
|
|
930
|
-
".credentials",
|
|
931
|
-
".credentials_rsaparams"
|
|
932
|
-
];
|
|
933
|
-
const URL_FIELDS = /* @__PURE__ */ new Set([
|
|
934
|
-
"serverurl",
|
|
935
|
-
"serverurlv2",
|
|
936
|
-
"githuburl",
|
|
937
|
-
"authorizationurl"
|
|
938
|
-
]);
|
|
939
|
-
function checkJitConfig(encoded, routeId) {
|
|
940
|
-
let files;
|
|
941
|
-
try {
|
|
942
|
-
files = decodeJson(encoded);
|
|
943
|
-
if (!files || typeof files !== "object") throw new Error();
|
|
944
|
-
} catch {
|
|
945
|
-
return {
|
|
946
|
-
ok: false,
|
|
947
|
-
reason: "it isn't a runner config"
|
|
948
|
-
};
|
|
949
|
-
}
|
|
950
|
-
const names = Object.keys(files);
|
|
951
|
-
if (names.length !== FILES.length || !FILES.every((name) => names.includes(name))) return {
|
|
952
|
-
ok: false,
|
|
953
|
-
reason: `it holds ${names.join(", ") || "nothing"}, not GitHub's files`
|
|
954
|
-
};
|
|
955
|
-
const decoded = {};
|
|
956
|
-
for (const [name, value] of Object.entries(files)) {
|
|
957
|
-
if (typeof value !== "string") return {
|
|
958
|
-
ok: false,
|
|
959
|
-
reason: `${name} isn't a file`
|
|
960
|
-
};
|
|
961
|
-
try {
|
|
962
|
-
decoded[name] = decodeJson(value);
|
|
963
|
-
} catch {
|
|
964
|
-
return {
|
|
965
|
-
ok: false,
|
|
966
|
-
reason: `${name} isn't JSON`
|
|
967
|
-
};
|
|
968
|
-
}
|
|
969
|
-
}
|
|
970
|
-
const runner = decoded[".runner"];
|
|
971
|
-
if (!runner || typeof runner !== "object") return {
|
|
972
|
-
ok: false,
|
|
973
|
-
reason: "it has no .runner"
|
|
974
|
-
};
|
|
975
|
-
const duplicate = duplicateKey(decoded);
|
|
976
|
-
if (duplicate) return {
|
|
977
|
-
ok: false,
|
|
978
|
-
reason: `it has ${duplicate} twice`
|
|
979
|
-
};
|
|
980
|
-
for (const url of urls(decoded)) {
|
|
981
|
-
const parsed = URL.canParse(url) ? new URL(url) : null;
|
|
982
|
-
if (!parsed) return {
|
|
983
|
-
ok: false,
|
|
984
|
-
reason: `it names a URL that doesn't parse: ${url}`
|
|
985
|
-
};
|
|
986
|
-
if (parsed.protocol !== "https:" || !GITHUB_HOSTS.some((host) => host.test(parsed.hostname))) return {
|
|
987
|
-
ok: false,
|
|
988
|
-
reason: `it points the runner at ${parsed.origin}, not GitHub`
|
|
989
|
-
};
|
|
990
|
-
}
|
|
991
|
-
const field = (key) => {
|
|
992
|
-
const entry = Object.entries(runner).find(([name]) => name.toLowerCase() === key);
|
|
993
|
-
return typeof entry?.[1] === "string" ? entry[1] : null;
|
|
994
|
-
};
|
|
995
|
-
if (!field("serverurl") && !field("serverurlv2")) return {
|
|
996
|
-
ok: false,
|
|
997
|
-
reason: "it doesn't say which GitHub server to use"
|
|
998
|
-
};
|
|
999
|
-
const runnerName = field("agentname");
|
|
1000
|
-
if (!runnerName || !isRunnerForRoute(runnerName, routeId)) return {
|
|
1001
|
-
ok: false,
|
|
1002
|
-
reason: `its runner ${runnerName ?? "(no name)"} isn't for job ${routeId}`
|
|
1003
|
-
};
|
|
1004
|
-
return {
|
|
1005
|
-
ok: true,
|
|
1006
|
-
target: target(field("githuburl"))
|
|
1007
|
-
};
|
|
1008
|
-
}
|
|
1009
|
-
function target(url) {
|
|
1010
|
-
if (!url || !URL.canParse(url)) return null;
|
|
1011
|
-
const path = new URL(url).pathname.split("/").filter(Boolean).slice(0, 2);
|
|
1012
|
-
return path.length ? path.join("/") : null;
|
|
1013
|
-
}
|
|
1014
|
-
function urls(value, found = [], key = "") {
|
|
1015
|
-
if (typeof value === "string") {
|
|
1016
|
-
const text = value.trim();
|
|
1017
|
-
if (text && (URL_FIELDS.has(key.toLowerCase()) || /^[a-z][a-z0-9+.-]*:/i.test(text))) found.push(text);
|
|
1018
|
-
} else if (Array.isArray(value)) for (const item of value) urls(item, found);
|
|
1019
|
-
else if (value && typeof value === "object") for (const [name, item] of Object.entries(value)) urls(item, found, name);
|
|
1020
|
-
return found;
|
|
1021
|
-
}
|
|
1022
|
-
function duplicateKey(value) {
|
|
1023
|
-
if (Array.isArray(value)) for (const item of value) {
|
|
1024
|
-
const found = duplicateKey(item);
|
|
1025
|
-
if (found) return found;
|
|
1026
|
-
}
|
|
1027
|
-
else if (value && typeof value === "object") {
|
|
1028
|
-
const seen = /* @__PURE__ */ new Set();
|
|
1029
|
-
for (const [name, item] of Object.entries(value)) {
|
|
1030
|
-
if (seen.has(name.toLowerCase())) return name;
|
|
1031
|
-
seen.add(name.toLowerCase());
|
|
1032
|
-
const found = duplicateKey(item);
|
|
1033
|
-
if (found) return found;
|
|
1034
|
-
}
|
|
1035
|
-
}
|
|
1036
|
-
return null;
|
|
1037
|
-
}
|
|
1038
|
-
function decodeJson(base64) {
|
|
1039
|
-
return JSON.parse(Buffer.from(base64, "base64").toString("utf8").replace(/^/, ""));
|
|
1040
|
-
}
|
|
1041
|
-
// usage.ts
|
|
1042
|
-
const SAMPLE_MS = 5e3;
|
|
1043
|
-
const MB = 1048576;
|
|
1044
|
-
/**
|
|
1045
|
-
* Reads `source` every few seconds until stop(), which resolves with the job's usage, or
|
|
1046
|
-
* undefined when nothing was read (a job too short to sample, or a source that never answered).
|
|
1047
|
-
* Calling stop() again resolves with the same answer.
|
|
1048
|
-
*/
|
|
1049
|
-
function sampleUsage(source, intervalMs = SAMPLE_MS) {
|
|
1050
|
-
const readings = [];
|
|
1051
|
-
let pending = Promise.resolve();
|
|
1052
|
-
let stopped;
|
|
1053
|
-
const timer = setInterval(() => {
|
|
1054
|
-
pending = pending.then(() => source.read().then((reading) => void (reading && readings.push(reading)), () => void 0));
|
|
1055
|
-
}, intervalMs);
|
|
1056
|
-
return { stop() {
|
|
1057
|
-
clearInterval(timer);
|
|
1058
|
-
return stopped ??= pending.then(() => summarize(readings, source));
|
|
1059
|
-
} };
|
|
1060
|
-
}
|
|
1061
|
-
function summarize(readings, capacity) {
|
|
1062
|
-
if (readings.length === 0) return void 0;
|
|
1063
|
-
const cpu = readings.map((reading) => Math.min(Math.max(reading.cpu, 0), 1));
|
|
1064
|
-
const memory = readings.map((reading) => Math.round(reading.memoryBytes / MB));
|
|
1065
|
-
return {
|
|
1066
|
-
cpuP95: round(p95(cpu)),
|
|
1067
|
-
cpuPeak: round(Math.max(...cpu)),
|
|
1068
|
-
memoryP95Mb: p95(memory),
|
|
1069
|
-
memoryPeakMb: Math.max(...memory),
|
|
1070
|
-
cpus: capacity.cpus,
|
|
1071
|
-
memoryMb: capacity.memoryMb,
|
|
1072
|
-
samples: readings.length
|
|
1073
|
-
};
|
|
1074
|
-
}
|
|
1075
|
-
function p95(values) {
|
|
1076
|
-
const sorted = [...values].sort((a, b) => a - b);
|
|
1077
|
-
return sorted[Math.ceil(sorted.length * .95) - 1];
|
|
1078
|
-
}
|
|
1079
|
-
const round = (share) => Math.round(share * 1e3) / 1e3;
|
|
1080
|
-
/**
|
|
1081
|
-
* A job in the VM `name`, read with `container stats`, which reports the cores the VM is busy
|
|
1082
|
-
* on right now (it samples for about two seconds per call).
|
|
1083
|
-
*/
|
|
1084
|
-
function vmUsage(name, size, command = "container") {
|
|
1085
|
-
return {
|
|
1086
|
-
cpus: size.cpus,
|
|
1087
|
-
memoryMb: size.memoryGb * 1024,
|
|
1088
|
-
async read() {
|
|
1089
|
-
const output = await run(command, [
|
|
1090
|
-
"stats",
|
|
1091
|
-
"--format",
|
|
1092
|
-
"json",
|
|
1093
|
-
"--no-stream",
|
|
1094
|
-
name
|
|
1095
|
-
]);
|
|
1096
|
-
if (!output) return null;
|
|
1097
|
-
const [stats] = JSON.parse(output);
|
|
1098
|
-
if (typeof stats?.cpuUtilization !== "number" || typeof stats.memoryUsageBytes !== "number") return null;
|
|
1099
|
-
return {
|
|
1100
|
-
cpu: stats.cpuUtilization / size.cpus,
|
|
1101
|
-
memoryBytes: stats.memoryUsageBytes
|
|
1102
|
-
};
|
|
1103
|
-
}
|
|
1104
|
-
};
|
|
1105
|
-
}
|
|
1106
|
-
/**
|
|
1107
|
-
* A job running on this machine, read from `ps` as the runner process `pid` and everything under
|
|
1108
|
-
* it. Rougher than a VM's reading: a process the job hands work to outside its tree (Docker
|
|
1109
|
-
* Desktop, a simulator) isn't counted, and `ps` reports each process's recent CPU, not exact use.
|
|
1110
|
-
*/
|
|
1111
|
-
function processTreeUsage(pid) {
|
|
1112
|
-
const cores = cpus().length;
|
|
1113
|
-
return {
|
|
1114
|
-
cpus: cores,
|
|
1115
|
-
memoryMb: Math.round(totalmem() / MB),
|
|
1116
|
-
async read() {
|
|
1117
|
-
const output = await run("ps", [
|
|
1118
|
-
"-A",
|
|
1119
|
-
"-o",
|
|
1120
|
-
"pid=,ppid=,%cpu=,rss="
|
|
1121
|
-
]);
|
|
1122
|
-
return output ? treeReading(output, pid, cores) : null;
|
|
1123
|
-
}
|
|
1124
|
-
};
|
|
1125
|
-
}
|
|
1126
|
-
/** Sums `ps -o pid=,ppid=,%cpu=,rss=` output over `root` and its descendants. */
|
|
1127
|
-
function treeReading(output, root, cores) {
|
|
1128
|
-
const children = /* @__PURE__ */ new Map();
|
|
1129
|
-
const usage = /* @__PURE__ */ new Map();
|
|
1130
|
-
for (const line of output.split("\n")) {
|
|
1131
|
-
const [pid, ppid, cpu, rss] = line.trim().split(/\s+/).map(Number);
|
|
1132
|
-
if (!Number.isFinite(pid) || !Number.isFinite(ppid)) continue;
|
|
1133
|
-
usage.set(pid, {
|
|
1134
|
-
cpu: cpu || 0,
|
|
1135
|
-
rssKb: rss || 0
|
|
1136
|
-
});
|
|
1137
|
-
const siblings = children.get(ppid);
|
|
1138
|
-
if (siblings) siblings.push(pid);
|
|
1139
|
-
else children.set(ppid, [pid]);
|
|
1140
|
-
}
|
|
1141
|
-
if (!usage.has(root)) return null;
|
|
1142
|
-
let percent = 0;
|
|
1143
|
-
let rssKb = 0;
|
|
1144
|
-
const stack = [root];
|
|
1145
|
-
for (let pid = stack.pop(); pid !== void 0; pid = stack.pop()) {
|
|
1146
|
-
const own = usage.get(pid);
|
|
1147
|
-
percent += own.cpu;
|
|
1148
|
-
rssKb += own.rssKb;
|
|
1149
|
-
stack.push(...children.get(pid) ?? []);
|
|
1150
|
-
}
|
|
1151
|
-
return {
|
|
1152
|
-
cpu: percent / 100 / cores,
|
|
1153
|
-
memoryBytes: rssKb * 1024
|
|
1154
|
-
};
|
|
1155
|
-
}
|
|
1156
|
-
// job.ts
|
|
1157
|
-
const runnerEnv = () => Object.fromEntries([
|
|
1158
|
-
"HOME",
|
|
1159
|
-
"USER",
|
|
1160
|
-
"LOGNAME",
|
|
1161
|
-
"PATH",
|
|
1162
|
-
"LANG",
|
|
1163
|
-
"LC_ALL",
|
|
1164
|
-
"TMPDIR",
|
|
1165
|
-
"SHELL"
|
|
1166
|
-
].flatMap((key) => process.env[key] === void 0 ? [] : [[key, process.env[key]]]));
|
|
1167
|
-
async function runJob(run, options) {
|
|
1168
|
-
const { launcher, report } = options;
|
|
1169
|
-
const { routeId } = run;
|
|
1170
|
-
const output = options.output ?? ((chunk, stream) => (stream === "stdout" ? process.stdout : process.stderr).write(chunk));
|
|
1171
|
-
const finish = (update) => {
|
|
1172
|
-
report(update);
|
|
1173
|
-
return update;
|
|
1174
|
-
};
|
|
1175
|
-
const failed = (message, usage) => finish({
|
|
1176
|
-
routeId,
|
|
1177
|
-
state: "failed",
|
|
1178
|
-
message,
|
|
1179
|
-
usage
|
|
1180
|
-
});
|
|
1181
|
-
const checked = checkJitConfig(run.jitConfig, routeId);
|
|
1182
|
-
if (!checked.ok) return failed(`Refused the job's runner config: ${checked.reason}.`);
|
|
1183
|
-
options.onChecked?.(checked.target);
|
|
1184
|
-
let clean = false;
|
|
1185
|
-
let sampler;
|
|
1186
|
-
try {
|
|
1187
|
-
const child = launcher.start(run);
|
|
1188
|
-
child.stdout.on("data", (chunk) => output(chunk, "stdout"));
|
|
1189
|
-
child.stderr.on("data", (chunk) => output(chunk, "stderr"));
|
|
1190
|
-
const started = await new Promise((resolve) => {
|
|
1191
|
-
child.once("spawn", () => resolve(null));
|
|
1192
|
-
child.once("error", resolve);
|
|
1193
|
-
});
|
|
1194
|
-
if (started) return failed(`Could not start the runner: ${started.message}`);
|
|
1195
|
-
report({
|
|
1196
|
-
routeId,
|
|
1197
|
-
state: "started"
|
|
1198
|
-
});
|
|
1199
|
-
if (launcher.usage) sampler = sampleUsage(launcher.usage(run, child));
|
|
1200
|
-
const [code, signal] = await new Promise((resolve) => child.once("close", (code, signal) => resolve([code, signal])));
|
|
1201
|
-
const usage = await sampler?.stop();
|
|
1202
|
-
clean = code === 0;
|
|
1203
|
-
if (clean) return finish({
|
|
1204
|
-
routeId,
|
|
1205
|
-
state: "finished",
|
|
1206
|
-
usage
|
|
1207
|
-
});
|
|
1208
|
-
return failed(signal ? `The runner was stopped by ${signal}` : `The runner exited with ${code}`, usage);
|
|
1209
|
-
} catch (error) {
|
|
1210
|
-
return failed(error instanceof Error ? error.message : String(error));
|
|
1211
|
-
} finally {
|
|
1212
|
-
sampler?.stop();
|
|
1213
|
-
await launcher.cleanup(run, clean);
|
|
1214
|
-
}
|
|
1215
|
-
}
|
|
1216
|
-
const JOB_STATE = [
|
|
1217
|
-
"_work",
|
|
1218
|
-
".runner",
|
|
1219
|
-
".credentials",
|
|
1220
|
-
".credentials_rsaparams"
|
|
1221
|
-
];
|
|
1222
|
-
function hostLauncher(dir) {
|
|
1223
|
-
const lock = join(dir, "job.lock");
|
|
1224
|
-
let locked = false;
|
|
1225
|
-
return {
|
|
1226
|
-
start(run) {
|
|
1227
|
-
locked = takeLock(lock);
|
|
1228
|
-
if (!locked) throw new Error(`Another job is using the runner in ${dir}.`);
|
|
1229
|
-
clean(dir);
|
|
1230
|
-
return spawn(join(dir, "run.sh"), ["--jitconfig", run.jitConfig], {
|
|
1231
|
-
cwd: dir,
|
|
1232
|
-
env: runnerEnv(),
|
|
1233
|
-
stdio: [
|
|
1234
|
-
"ignore",
|
|
1235
|
-
"pipe",
|
|
1236
|
-
"pipe"
|
|
1237
|
-
]
|
|
1238
|
-
});
|
|
1239
|
-
},
|
|
1240
|
-
usage: (_run, child) => processTreeUsage(child.pid),
|
|
1241
|
-
cleanup() {
|
|
1242
|
-
if (!locked) return;
|
|
1243
|
-
clean(dir);
|
|
1244
|
-
rmSync(lock, { force: true });
|
|
1245
|
-
locked = false;
|
|
1246
|
-
}
|
|
1247
|
-
};
|
|
1248
|
-
}
|
|
1249
|
-
function clean(dir) {
|
|
1250
|
-
for (const name of JOB_STATE) rmSync(join(dir, name), {
|
|
1251
|
-
recursive: true,
|
|
1252
|
-
force: true
|
|
1253
|
-
});
|
|
1254
|
-
}
|
|
1255
|
-
function takeLock(lock) {
|
|
1256
|
-
for (let attempt = 0; attempt < 2; attempt++) try {
|
|
1257
|
-
symlinkSync(String(process.pid), lock);
|
|
1258
|
-
return true;
|
|
1259
|
-
} catch (error) {
|
|
1260
|
-
if (error.code !== "EEXIST") throw error;
|
|
1261
|
-
if (isAlive(Number(readlinkSync(lock)))) return false;
|
|
1262
|
-
rmSync(lock, { force: true });
|
|
1263
|
-
}
|
|
1264
|
-
return false;
|
|
1265
|
-
}
|
|
1266
|
-
function isAlive(pid) {
|
|
1267
|
-
if (!Number.isSafeInteger(pid) || pid <= 0) return false;
|
|
1268
|
-
try {
|
|
1269
|
-
process.kill(pid, 0);
|
|
1270
|
-
return true;
|
|
1271
|
-
} catch (error) {
|
|
1272
|
-
return error.code === "EPERM";
|
|
1273
|
-
}
|
|
1274
|
-
}
|
|
1275
|
-
function prefixLines(prefix, write) {
|
|
1276
|
-
const partial = {
|
|
1277
|
-
stdout: "",
|
|
1278
|
-
stderr: ""
|
|
1279
|
-
};
|
|
1280
|
-
const output = (chunk, stream) => {
|
|
1281
|
-
const text = partial[stream] + chunk.toString();
|
|
1282
|
-
const end = text.lastIndexOf("\n") + 1;
|
|
1283
|
-
partial[stream] = text.slice(end);
|
|
1284
|
-
if (end === 0) return;
|
|
1285
|
-
const lines = text.slice(0, end).replace(/^(?=.)/gm, prefix);
|
|
1286
|
-
write(Buffer.from(lines), stream);
|
|
1287
|
-
};
|
|
1288
|
-
const flush = () => {
|
|
1289
|
-
for (const stream of ["stdout", "stderr"]) {
|
|
1290
|
-
if (partial[stream]) write(Buffer.from(`${prefix}${partial[stream]}\n`), stream);
|
|
1291
|
-
partial[stream] = "";
|
|
1292
|
-
}
|
|
1293
|
-
};
|
|
1294
|
-
return {
|
|
1295
|
-
output,
|
|
1296
|
-
flush
|
|
1297
|
-
};
|
|
1298
|
-
}
|
|
1299
|
-
// isolated.ts
|
|
1300
|
-
const RUNNER_IMAGE = "ghcr.io/actions/actions-runner";
|
|
1301
|
-
const RELEASES = "https://github.com/apple/container/releases";
|
|
1302
|
-
function unsupportedReason(system = platform(), chip = arch(), darwin = release()) {
|
|
1303
|
-
if (system !== "darwin") return "Running jobs in VMs needs a Mac with Apple silicon and macOS 26 or later.";
|
|
1304
|
-
if (chip !== "arm64") return "Running jobs in VMs needs a Mac with Apple silicon. This one has an Intel chip.";
|
|
1305
|
-
if (Number.parseInt(darwin, 10) < 25) return "Running jobs in VMs needs macOS 26 or later. Update macOS, then try again.";
|
|
1306
|
-
return null;
|
|
1307
|
-
}
|
|
1308
|
-
async function isolationState(command = "container", reason = unsupportedReason()) {
|
|
1309
|
-
if (reason !== null) return "unsupported";
|
|
1310
|
-
const status = await call(command, ["system", "status"], NO_LOG, true);
|
|
1311
|
-
if (status === null) return "missing";
|
|
1312
|
-
return status === 0 ? "ready" : "stopped";
|
|
1313
|
-
}
|
|
1314
|
-
function setupHint(state) {
|
|
1315
|
-
if (state !== "missing" && state !== "stopped") return null;
|
|
1316
|
-
return `Jobs run on this Mac itself, where they can read your files. To run each job in its own Linux VM, ${state === "missing" ? `install Apple's container tool from ${RELEASES} and run \`container system start\`` : "run `container system start`"}.`;
|
|
1317
|
-
}
|
|
1318
|
-
function debugLog(path = join(relayrunnerHome(), "isolated.log")) {
|
|
1319
|
-
const home = homedir();
|
|
1320
|
-
const write = (text, flag = "a") => {
|
|
1321
|
-
try {
|
|
1322
|
-
const stamped = `${(/* @__PURE__ */ new Date()).toISOString()} ${text.trimEnd().replaceAll(home, "~")}\n`;
|
|
1323
|
-
if (flag === "w") {
|
|
1324
|
-
rmSync(path, { force: true });
|
|
1325
|
-
writeFileSync(path, stamped, { mode: 384 });
|
|
1326
|
-
} else appendFileSync(path, stamped);
|
|
1327
|
-
} catch {}
|
|
1328
|
-
};
|
|
1329
|
-
try {
|
|
1330
|
-
mkdirSync(dirname(path), { recursive: true });
|
|
1331
|
-
} catch {}
|
|
1332
|
-
write(`relayrunner ${cliVersion}, ${platform()} ${release()} ${arch()}, ${availableParallelism()} cores, ${Math.round(totalmem() / 1024 ** 3)} GB`, "w");
|
|
1333
|
-
return {
|
|
1334
|
-
path,
|
|
1335
|
-
write
|
|
1336
|
-
};
|
|
1337
|
-
}
|
|
1338
|
-
const NO_LOG = {
|
|
1339
|
-
path: "",
|
|
1340
|
-
write: () => {}
|
|
1341
|
-
};
|
|
1342
|
-
const START_SCRIPT = `#!/bin/sh
|
|
1343
|
-
set -eu
|
|
1344
|
-
drop=""
|
|
1345
|
-
if [ "\${RELAYRUNNER_LOCAL_NETWORK:-}" != 1 ]; then
|
|
1346
|
-
drop="--bounding-set -net_admin,-net_raw"
|
|
1347
|
-
dns=$(awk '$1 == "nameserver" && $2 ~ /^[0-9.]+$/ { printf "%s%s", sep, $2; sep = ", " }' /etc/resolv.conf)
|
|
1348
|
-
allow_dns=""
|
|
1349
|
-
[ -z "$dns" ] || allow_dns="ip daddr { $dns } meta l4proto { tcp, udp } th dport 53 accept"
|
|
1350
|
-
nft -f - <<EOF
|
|
1351
|
-
table inet relayrunner {
|
|
1352
|
-
chain private {
|
|
1353
|
-
oifname { "lo", "docker0" } accept
|
|
1354
|
-
oifname "br-*" accept
|
|
1355
|
-
$allow_dns
|
|
1356
|
-
ip daddr { 10.0.0.0/8, 100.64.0.0/10, 169.254.0.0/16, 172.16.0.0/12, 192.168.0.0/16 } drop
|
|
1357
|
-
meta nfproto ipv6 drop
|
|
1358
|
-
}
|
|
1359
|
-
chain out {
|
|
1360
|
-
type filter hook output priority 0; policy accept;
|
|
1361
|
-
jump private
|
|
1362
|
-
}
|
|
1363
|
-
chain forward {
|
|
1364
|
-
type filter hook forward priority 0; policy accept;
|
|
1365
|
-
jump private
|
|
1366
|
-
}
|
|
1367
|
-
}
|
|
1368
|
-
EOF
|
|
1369
|
-
fi
|
|
1370
|
-
# Docker sets kernel network settings under /proc/sys, which starts read-only. A job without
|
|
1371
|
-
# Docker loses nothing if it can't start, so failures here only reach the Docker log.
|
|
1372
|
-
if command -v dockerd >/dev/null 2>&1; then
|
|
1373
|
-
mount -o remount,rw /proc/sys 2>/dev/null || true
|
|
1374
|
-
dockerd >/var/log/dockerd.log 2>&1 &
|
|
1375
|
-
tries=0
|
|
1376
|
-
until docker info >/dev/null 2>&1 || [ "$tries" -ge 50 ]; do
|
|
1377
|
-
tries=$((tries + 1))
|
|
1378
|
-
sleep 0.2
|
|
1379
|
-
done
|
|
1380
|
-
fi
|
|
1381
|
-
# A new VM's DNS answers nothing for its first 2 seconds or so, and a lookup sent then waits 5
|
|
1382
|
-
# seconds to ask again. So the runner starts once a lookup gets through, or after 5 tries.
|
|
1383
|
-
tries=0
|
|
1384
|
-
until RES_OPTIONS="timeout:1 attempts:1" getent hosts github.com >/dev/null 2>&1 || [ "$tries" -ge 4 ]; do
|
|
1385
|
-
tries=$((tries + 1))
|
|
1386
|
-
done
|
|
1387
|
-
cd /home/runner
|
|
1388
|
-
# With arguments, runs them in place of the runner, to check the VM by hand.
|
|
1389
|
-
[ $# -gt 0 ] || set -- ./run.sh --jitconfig "$RUNNER_JIT_CONFIG"
|
|
1390
|
-
exec setpriv --reuid runner --regid runner --init-groups $drop \\
|
|
1391
|
-
env HOME=/home/runner USER=runner LOGNAME=runner "$@"
|
|
1392
|
-
`;
|
|
1393
|
-
const START_PATH = "/usr/local/bin/relayrunner-start";
|
|
1394
|
-
const TOOLS = [
|
|
1395
|
-
"build-essential pkg-config cmake",
|
|
1396
|
-
"python3-pip python3-venv python-is-python3",
|
|
1397
|
-
"zip xz-utils zstd bzip2",
|
|
1398
|
-
"wget rsync file gettext-base bc time",
|
|
1399
|
-
"git-lfs sqlite3",
|
|
1400
|
-
"docker-compose-v2",
|
|
1401
|
-
"netcat-openbsd iputils-ping dnsutils iproute2",
|
|
1402
|
-
"libssl-dev",
|
|
1403
|
-
"gh"
|
|
1404
|
-
].join(" ");
|
|
1405
|
-
const GH_KEYRING = "/usr/share/keyrings/githubcli-archive-keyring.gpg";
|
|
1406
|
-
function dockerfile(base, tools = true) {
|
|
1407
|
-
const install = `RUN curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg -o ${GH_KEYRING} \\
|
|
1408
|
-
&& echo "deb [arch=$(dpkg --print-architecture) signed-by=${GH_KEYRING}] https://cli.github.com/packages stable main" > /etc/apt/sources.list.d/github-cli.list \\
|
|
1409
|
-
&& apt-get update && apt-get install -y --no-install-recommends ${TOOLS} \\
|
|
1410
|
-
&& apt-get clean && rm -rf /var/lib/apt/lists/*
|
|
1411
|
-
RUN node=$(ls -d /home/runner/externals/node[0-9]* 2>/dev/null | sort -V | tail -n 1) \\
|
|
1412
|
-
&& { [ -z "$node" ] || { ln -sf "$node"/bin/* /usr/local/bin/ \\
|
|
1413
|
-
&& echo prefix=/usr/local > "$node"/lib/node_modules/npm/npmrc \\
|
|
1414
|
-
&& mkdir -p /usr/local/lib/node_modules \\
|
|
1415
|
-
&& chown runner /usr/local/bin /usr/local/lib/node_modules; }; }
|
|
1416
|
-
`;
|
|
1417
|
-
return `FROM ${base}
|
|
1418
|
-
USER root
|
|
1419
|
-
RUN apt-get update && apt-get install -y --no-install-recommends iptables nftables && apt-get clean
|
|
1420
|
-
${tools ? install : ""}COPY --chmod=755 start.sh ${START_PATH}
|
|
1421
|
-
`;
|
|
1422
|
-
}
|
|
1423
|
-
function jobImage(base, tools = true) {
|
|
1424
|
-
return `relayrunner-runner:${createHash("sha256").update(dockerfile(base, tools)).update(START_SCRIPT).digest("hex").slice(0, 12)}`;
|
|
1425
|
-
}
|
|
1426
|
-
function parseVmSize(cpus, memory, cores = availableParallelism(), memoryBytes = totalmem()) {
|
|
1427
|
-
const whole = (flag, value, most, unit) => {
|
|
1428
|
-
if (value === void 0 || value === "") return void 0;
|
|
1429
|
-
const n = Number(value);
|
|
1430
|
-
if (!/^\d+$/.test(value.trim()) || n < 1) throw new RunnerError("USAGE", `${flag} takes a whole number, not "${value}".`);
|
|
1431
|
-
if (n > most) throw new RunnerError("USAGE", `${flag} ${n} is more than this machine's ${most} ${unit}.`);
|
|
1432
|
-
return n;
|
|
1433
|
-
};
|
|
1434
|
-
return {
|
|
1435
|
-
cpus: whole("--cpus", cpus, cores, "CPU cores"),
|
|
1436
|
-
memoryGb: whole("--memory", memory, Math.floor(memoryBytes / 1024 ** 3), "GB of memory")
|
|
1437
|
-
};
|
|
1438
|
-
}
|
|
1439
|
-
function slotsFor(size, cores = availableParallelism(), memoryBytes = totalmem()) {
|
|
1440
|
-
if (size.cpus === void 0 && size.memoryGb === void 0) return void 0;
|
|
1441
|
-
const gb = memoryBytes / 1024 ** 3;
|
|
1442
|
-
const byCpu = size.cpus ? Math.floor(cores / size.cpus) : Infinity;
|
|
1443
|
-
const byMemory = size.memoryGb ? Math.floor(gb / 2 / size.memoryGb) : Infinity;
|
|
1444
|
-
return Math.max(1, Math.min(byCpu, byMemory));
|
|
1445
|
-
}
|
|
1446
|
-
function checkFits(size, slots, memoryBytes = totalmem()) {
|
|
1447
|
-
const gb = Math.floor(memoryBytes / 1024 ** 3);
|
|
1448
|
-
if (size.memoryGb !== void 0 && size.memoryGb * slots > gb) throw new RunnerError("USAGE", `${slots} jobs with ${size.memoryGb} GB each is more than this machine's ${gb} GB of memory. Lower --concurrency or --memory.`);
|
|
1449
|
-
}
|
|
1450
|
-
function vmSize(slots, wanted = {}, cores = availableParallelism(), memoryBytes = totalmem()) {
|
|
1451
|
-
const gb = memoryBytes / 1024 ** 3;
|
|
1452
|
-
return {
|
|
1453
|
-
cpus: wanted.cpus ?? Math.max(2, Math.floor(cores / slots)),
|
|
1454
|
-
memoryGb: wanted.memoryGb ?? Math.min(16, Math.max(2, Math.floor(gb / 2 / slots)))
|
|
1455
|
-
};
|
|
1456
|
-
}
|
|
1457
|
-
const NO_DNS = 3;
|
|
1458
|
-
const DNS_CHECK = `for try in 1 2 3 4 5; do
|
|
1459
|
-
RES_OPTIONS="timeout:1 attempts:1" getent ahostsv4 github.com >/dev/null && exit 0
|
|
1460
|
-
done
|
|
1461
|
-
exit ${NO_DNS}`;
|
|
1462
|
-
const DNS_FAILURE = /Temporary failure resolving|Could not resolve host|Name or service not known/;
|
|
1463
|
-
function dnsMessage(base) {
|
|
1464
|
-
return `Linux VMs on this Mac can't look up hostnames, though the Mac itself can.
|
|
1465
|
-
VPN or DNS filtering software often causes this, even when it's disconnected or its app is closed. Quit it fully, then run \`relayrunner connect\` again.
|
|
1466
|
-
|
|
1467
|
-
To check, this should print an address:
|
|
1468
|
-
container run --rm ${base} getent ahostsv4 github.com
|
|
1469
|
-
|
|
1470
|
-
To run jobs on the Mac without VMs for now, use \`relayrunner connect --no-isolated\`.`;
|
|
1471
|
-
}
|
|
1472
|
-
async function prepareIsolation(options) {
|
|
1473
|
-
const command = options.command ?? "container";
|
|
1474
|
-
const log = options.log ?? (() => {});
|
|
1475
|
-
const debug = options.debug ?? NO_LOG;
|
|
1476
|
-
const localNetwork = options.localNetwork ?? false;
|
|
1477
|
-
const tool = (args) => call(command, args, debug);
|
|
1478
|
-
const hasImage = async (image) => await call(command, [
|
|
1479
|
-
"image",
|
|
1480
|
-
"inspect",
|
|
1481
|
-
image
|
|
1482
|
-
], debug, true) === 0;
|
|
1483
|
-
const fail = (code, message) => new RunnerError(code, debug.path ? `${message} Details are in ${debug.path}.` : message);
|
|
1484
|
-
const latest = options.runnerVersion ? Promise.resolve(options.runnerVersion) : latestRunnerVersion(log);
|
|
1485
|
-
latest.catch(() => {});
|
|
1486
|
-
const [status] = await Promise.all([tool(["system", "status"]), tool(["--version"])]);
|
|
1487
|
-
if (status === null) throw new RunnerError("ISOLATED_SETUP", `Running jobs in VMs needs Apple's container tool. Install it from ${RELEASES}, then run \`container system start\`.`);
|
|
1488
|
-
if (status !== 0) throw fail("ISOLATED_SETUP", "Apple's container tool isn't running. Run `container system start`, then try again.");
|
|
1489
|
-
const runnerVersion = await latest;
|
|
1490
|
-
const base = options.image ?? `${RUNNER_IMAGE}:${runnerVersion}`;
|
|
1491
|
-
const mine = [];
|
|
1492
|
-
if (!await hasImage(base)) {
|
|
1493
|
-
log(`Downloading ${base}. This happens once per runner version…`);
|
|
1494
|
-
if (await tool([
|
|
1495
|
-
"image",
|
|
1496
|
-
"pull",
|
|
1497
|
-
base
|
|
1498
|
-
]) !== 0) throw fail("ISOLATED_IMAGE", `Could not download ${base}.`);
|
|
1499
|
-
if (!options.image) mine.push(base);
|
|
1500
|
-
}
|
|
1501
|
-
const noDns = () => fail("ISOLATED_DNS", dnsMessage(base));
|
|
1502
|
-
if (await tool([
|
|
1503
|
-
"run",
|
|
1504
|
-
"--rm",
|
|
1505
|
-
base,
|
|
1506
|
-
"sh",
|
|
1507
|
-
"-c",
|
|
1508
|
-
DNS_CHECK
|
|
1509
|
-
]) === NO_DNS) throw noDns();
|
|
1510
|
-
const image = jobImage(base, !options.image);
|
|
1511
|
-
mine.push(image);
|
|
1512
|
-
if (!await hasImage(image)) {
|
|
1513
|
-
log(`Building the job image from ${base}. This happens once per runner version…`);
|
|
1514
|
-
const context = mkdtempSync(join(tmpdir(), "relayrunner-image-"));
|
|
1515
|
-
try {
|
|
1516
|
-
writeFileSync(join(context, "Dockerfile"), dockerfile(base, !options.image));
|
|
1517
|
-
writeFileSync(join(context, "start.sh"), START_SCRIPT);
|
|
1518
|
-
const build = await capture(command, [
|
|
1519
|
-
"build",
|
|
1520
|
-
"--progress",
|
|
1521
|
-
"plain",
|
|
1522
|
-
"--tag",
|
|
1523
|
-
image,
|
|
1524
|
-
context
|
|
1525
|
-
], debug);
|
|
1526
|
-
if (build.code !== 0 && DNS_FAILURE.test(build.output)) throw noDns();
|
|
1527
|
-
if (build.code !== 0) throw fail("ISOLATED_IMAGE", `Could not build the job image from ${base}.`);
|
|
1528
|
-
} finally {
|
|
1529
|
-
rmSync(context, {
|
|
1530
|
-
recursive: true,
|
|
1531
|
-
force: true
|
|
1532
|
-
});
|
|
1533
|
-
await tool(["builder", "stop"]);
|
|
1534
|
-
await tool(["builder", "delete"]);
|
|
1535
|
-
}
|
|
1536
|
-
}
|
|
1537
|
-
await pruneImages(options.managed ?? managedImagesFile(), [
|
|
1538
|
-
base,
|
|
1539
|
-
image,
|
|
1540
|
-
...options.keep ?? []
|
|
1541
|
-
], mine, tool, log);
|
|
1542
|
-
return {
|
|
1543
|
-
command,
|
|
1544
|
-
base,
|
|
1545
|
-
image,
|
|
1546
|
-
localNetwork,
|
|
1547
|
-
debug,
|
|
1548
|
-
runnerVersion,
|
|
1549
|
-
...vmSize(options.slots, options.size)
|
|
1550
|
-
};
|
|
1551
|
-
}
|
|
1552
|
-
function managedImagesFile() {
|
|
1553
|
-
return join(relayrunnerHome(), "isolated-images.json");
|
|
1554
|
-
}
|
|
1555
|
-
async function pruneImages(file, inUse, mine, tool, log) {
|
|
1556
|
-
const recorded = readList(file);
|
|
1557
|
-
for (const image of recorded) {
|
|
1558
|
-
if (inUse.includes(image)) continue;
|
|
1559
|
-
if (await tool([
|
|
1560
|
-
"image",
|
|
1561
|
-
"delete",
|
|
1562
|
-
image
|
|
1563
|
-
]) === 0) log(`Removed the old image ${image}.`);
|
|
1564
|
-
}
|
|
1565
|
-
try {
|
|
1566
|
-
writeList(file, inUse.filter((image) => recorded.includes(image) || mine.includes(image)));
|
|
1567
|
-
} catch {}
|
|
1568
|
-
}
|
|
1569
|
-
function containerName(routeId) {
|
|
1570
|
-
return `relayrunner-${routeId.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;
|
|
1571
|
-
}
|
|
1572
|
-
function runArgs(routeId, isolation) {
|
|
1573
|
-
return [
|
|
1574
|
-
"run",
|
|
1575
|
-
"--rm",
|
|
1576
|
-
"--name",
|
|
1577
|
-
containerName(routeId),
|
|
1578
|
-
"--cpus",
|
|
1579
|
-
String(isolation.cpus),
|
|
1580
|
-
"--memory",
|
|
1581
|
-
`${isolation.memoryGb}g`,
|
|
1582
|
-
"--progress",
|
|
1583
|
-
"none",
|
|
1584
|
-
"-e",
|
|
1585
|
-
"RUNNER_JIT_CONFIG",
|
|
1586
|
-
"-e",
|
|
1587
|
-
"ACTIONS_RUNNER_PRINT_LOG_TO_STDOUT=false",
|
|
1588
|
-
...isolation.localNetwork ? ["-e", "RELAYRUNNER_LOCAL_NETWORK=1"] : [],
|
|
1589
|
-
"--user",
|
|
1590
|
-
"0",
|
|
1591
|
-
"--cap-add",
|
|
1592
|
-
"ALL",
|
|
1593
|
-
isolation.image,
|
|
1594
|
-
START_PATH
|
|
1595
|
-
];
|
|
1596
|
-
}
|
|
1597
|
-
function isolatedLauncher(isolation) {
|
|
1598
|
-
const { command, debug } = isolation;
|
|
1599
|
-
return {
|
|
1600
|
-
start(run) {
|
|
1601
|
-
const name = containerName(run.routeId);
|
|
1602
|
-
const args = runArgs(run.routeId, isolation);
|
|
1603
|
-
debug.write(`$ ${command} ${args.join(" ")}`);
|
|
1604
|
-
const child = spawn(command, args, {
|
|
1605
|
-
env: {
|
|
1606
|
-
...runnerEnv(),
|
|
1607
|
-
RUNNER_JIT_CONFIG: run.jitConfig
|
|
1608
|
-
},
|
|
1609
|
-
stdio: [
|
|
1610
|
-
"ignore",
|
|
1611
|
-
"pipe",
|
|
1612
|
-
"pipe"
|
|
1613
|
-
]
|
|
1614
|
-
});
|
|
1615
|
-
child.once("error", (error) => debug.write(`${name}: ${error.message}`));
|
|
1616
|
-
child.once("close", (code, signal) => debug.write(`${name}: exit ${signal ?? code}`));
|
|
1617
|
-
return child;
|
|
1618
|
-
},
|
|
1619
|
-
usage: (run) => vmUsage(containerName(run.routeId), isolation, command),
|
|
1620
|
-
async cleanup(run, clean) {
|
|
1621
|
-
if (clean) return;
|
|
1622
|
-
const args = [
|
|
1623
|
-
"delete",
|
|
1624
|
-
"--force",
|
|
1625
|
-
containerName(run.routeId)
|
|
1626
|
-
];
|
|
1627
|
-
if (await call(command, args, debug) !== 0) await call(command, args, debug);
|
|
1628
|
-
}
|
|
1629
|
-
};
|
|
1630
|
-
}
|
|
1631
|
-
async function call(command, args, debug, quiet = false) {
|
|
1632
|
-
return (await capture(command, args, debug, quiet)).code;
|
|
1633
|
-
}
|
|
1634
|
-
function capture(command, args, debug, quiet = false) {
|
|
1635
|
-
return new Promise((resolve) => {
|
|
1636
|
-
const child = spawn(command, args, { stdio: [
|
|
1637
|
-
"ignore",
|
|
1638
|
-
"pipe",
|
|
1639
|
-
"pipe"
|
|
1640
|
-
] });
|
|
1641
|
-
let output = "";
|
|
1642
|
-
const keep = (chunk) => {
|
|
1643
|
-
if (!quiet) output += chunk.toString();
|
|
1644
|
-
};
|
|
1645
|
-
child.stdout.on("data", keep);
|
|
1646
|
-
child.stderr.on("data", keep);
|
|
1647
|
-
const done = (code, extra = "") => {
|
|
1648
|
-
debug.write(`$ ${command} ${args.join(" ")}\n${output}${extra}exit ${code}`);
|
|
1649
|
-
resolve({
|
|
1650
|
-
code,
|
|
1651
|
-
output
|
|
1652
|
-
});
|
|
1653
|
-
};
|
|
1654
|
-
child.once("error", (error) => done(null, `${error.message}\n`));
|
|
1655
|
-
child.once("close", (code) => done(code));
|
|
1656
|
-
});
|
|
1657
|
-
}
|
|
1658
|
-
// repo.ts
|
|
1659
|
-
const WORKFLOWS_DIR = ".github/workflows";
|
|
1660
|
-
/** The nearest directory at or above `from` that holds a `.git`, or null outside a checkout. */
|
|
1661
|
-
function findRepoRoot(from = process.cwd()) {
|
|
1662
|
-
let dir = resolve(from);
|
|
1663
|
-
for (;;) {
|
|
1664
|
-
if (existsSync(join(dir, ".git"))) return dir;
|
|
1665
|
-
const parent = dirname(dir);
|
|
1666
|
-
if (parent === dir) return null;
|
|
1667
|
-
dir = parent;
|
|
1668
|
-
}
|
|
1669
|
-
}
|
|
1670
|
-
function readWorkflowFiles(root) {
|
|
1671
|
-
const dir = join(root, WORKFLOWS_DIR);
|
|
1672
|
-
if (!existsSync(dir)) return [];
|
|
1673
|
-
return readdirSync(dir).filter((name) => /\.ya?ml$/.test(name)).sort().map((name) => ({
|
|
1674
|
-
file: `${WORKFLOWS_DIR}/${name}`,
|
|
1675
|
-
source: readFileSync(join(dir, name), "utf8")
|
|
1676
|
-
}));
|
|
1677
|
-
}
|
|
1678
|
-
/** `owner/name` from a GitHub remote URL (https or ssh), or null for anything else. */
|
|
1679
|
-
function parseGitHubRemote(url) {
|
|
1680
|
-
const match = /^(?:https?:\/\/(?:[^@/]+@)?github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/.exec(url.trim());
|
|
1681
|
-
return match ? `${match[1]}/${match[2]}` : null;
|
|
1682
|
-
}
|
|
1683
|
-
function originRepo(root) {
|
|
1684
|
-
return new Promise((done) => {
|
|
1685
|
-
execFile("git", [
|
|
1686
|
-
"-C",
|
|
1687
|
-
root,
|
|
1688
|
-
"remote",
|
|
1689
|
-
"get-url",
|
|
1690
|
-
"origin"
|
|
1691
|
-
], {
|
|
1692
|
-
timeout: 3e3,
|
|
1693
|
-
encoding: "utf8"
|
|
1694
|
-
}, (error, stdout) => done(error ? null : parseGitHubRemote(stdout)));
|
|
1695
|
-
});
|
|
1696
|
-
}
|
|
1697
|
-
/**
|
|
1698
|
-
* Asks GitHub without signing in. A public repo answers; a private one (or one that doesn't exist)
|
|
1699
|
-
* is a 404 to an anonymous caller. Anything else, such as no network or a rate limit, is unknown.
|
|
1700
|
-
*/
|
|
1701
|
-
async function repoVisibility(repo, fetcher = fetch) {
|
|
1702
|
-
try {
|
|
1703
|
-
const response = await fetcher(`https://api.github.com/repos/${repo}`, {
|
|
1704
|
-
headers: {
|
|
1705
|
-
accept: "application/vnd.github+json",
|
|
1706
|
-
"user-agent": userAgent
|
|
1707
|
-
},
|
|
1708
|
-
signal: AbortSignal.timeout(5e3)
|
|
1709
|
-
});
|
|
1710
|
-
if (response.status === 404) return "private";
|
|
1711
|
-
if (!response.ok) return "unknown";
|
|
1712
|
-
return (await response.json()).private === false ? "public" : "private";
|
|
1713
|
-
} catch {
|
|
1714
|
-
return "unknown";
|
|
1715
|
-
}
|
|
1716
|
-
}
|
|
1717
|
-
// ../../packages/providers/src/prices.ts
|
|
1718
|
-
/** A provider's rates, and what one minute of each is per. */
|
|
1719
|
-
const RATES = {
|
|
1720
|
-
blacksmith: {
|
|
1721
|
-
linux: "vcpu",
|
|
1722
|
-
arm: "vcpu",
|
|
1723
|
-
windows: "vcpu",
|
|
1724
|
-
macos: "vcpu"
|
|
1725
|
-
},
|
|
1726
|
-
depot: {
|
|
1727
|
-
linux: "vcpu",
|
|
1728
|
-
arm: "vcpu",
|
|
1729
|
-
windows: "vcpu",
|
|
1730
|
-
macos: "vcpu"
|
|
1731
|
-
},
|
|
1732
|
-
warpbuild: {
|
|
1733
|
-
linux: "vcpu",
|
|
1734
|
-
arm: "vcpu",
|
|
1735
|
-
windows: "vcpu",
|
|
1736
|
-
macos: "vcpu"
|
|
1737
|
-
},
|
|
1738
|
-
ubicloud: {
|
|
1739
|
-
standard: "vcpu",
|
|
1740
|
-
premium: "vcpu"
|
|
1741
|
-
},
|
|
1742
|
-
github: {
|
|
1743
|
-
"linux-1-core": "runner",
|
|
1744
|
-
"linux-2-core": "runner",
|
|
1745
|
-
"linux-arm-2-core": "runner",
|
|
1746
|
-
"windows-2-core": "runner",
|
|
1747
|
-
"windows-arm-2-core": "runner",
|
|
1748
|
-
macos: "runner"
|
|
1749
|
-
}
|
|
1750
|
-
};
|
|
1751
|
-
/**
|
|
1752
|
-
* The `runs-on` label GitHub's docs give each standard runner, the name people know it by. Where
|
|
1753
|
-
* one runner has several labels (`ubuntu-latest`, `ubuntu-24.04`), this is the first one listed.
|
|
1754
|
-
* macOS has none: one rate covers several images (`macos-latest`, `macos-15-intel`), so it stays
|
|
1755
|
-
* "macOS". https://docs.github.com/en/actions/reference/runners/github-hosted-runners
|
|
1756
|
-
*/
|
|
1757
|
-
const GITHUB_LABELS = {
|
|
1758
|
-
"linux-1-core": "ubuntu-slim",
|
|
1759
|
-
"linux-2-core": "ubuntu-latest",
|
|
1760
|
-
"linux-arm-2-core": "ubuntu-24.04-arm",
|
|
1761
|
-
"windows-2-core": "windows-latest",
|
|
1762
|
-
"windows-arm-2-core": "windows-11-arm"
|
|
1763
|
-
};
|
|
1764
|
-
/** The one rate a provider operators added has: a minute of any of its runners. */
|
|
1765
|
-
const ADDED_RATE = "runner";
|
|
1766
|
-
/**
|
|
1767
|
-
* Whether a provider has this rate: one RATES lists, or the per-runner rate of a provider RATES
|
|
1768
|
-
* doesn't price (the admin only records that one for providers operators added).
|
|
1769
|
-
*/
|
|
1770
|
-
const isRate = (provider, rate) => Object.hasOwn(RATES, provider) ? Object.hasOwn(RATES[provider], rate) : rate === ADDED_RATE;
|
|
1771
|
-
const vcpu = (perRunner, vcpus) => perRunner / vcpus;
|
|
1772
|
-
const BASE_PRICES = [
|
|
1773
|
-
{
|
|
1774
|
-
provider: "blacksmith",
|
|
1775
|
-
rate: "linux",
|
|
1776
|
-
usd: vcpu(.004, 2),
|
|
1777
|
-
from: "2026-11-11"
|
|
1778
|
-
},
|
|
1779
|
-
{
|
|
1780
|
-
provider: "blacksmith",
|
|
1781
|
-
rate: "arm",
|
|
1782
|
-
usd: vcpu(.0025, 2),
|
|
1783
|
-
from: "2026-11-11"
|
|
1784
|
-
},
|
|
1785
|
-
{
|
|
1786
|
-
provider: "blacksmith",
|
|
1787
|
-
rate: "windows",
|
|
1788
|
-
usd: vcpu(.008, 2),
|
|
1789
|
-
from: "2026-11-11"
|
|
1790
|
-
},
|
|
1791
|
-
{
|
|
1792
|
-
provider: "blacksmith",
|
|
1793
|
-
rate: "macos",
|
|
1794
|
-
usd: vcpu(.08, 6),
|
|
1795
|
-
from: "2026-11-11"
|
|
1796
|
-
},
|
|
1797
|
-
{
|
|
1798
|
-
provider: "depot",
|
|
1799
|
-
rate: "linux",
|
|
1800
|
-
usd: vcpu(.006, 2),
|
|
1801
|
-
from: "2026-11-11"
|
|
1802
|
-
},
|
|
1803
|
-
{
|
|
1804
|
-
provider: "depot",
|
|
1805
|
-
rate: "arm",
|
|
1806
|
-
usd: vcpu(.006, 2),
|
|
1807
|
-
from: "2026-11-11"
|
|
1808
|
-
},
|
|
1809
|
-
{
|
|
1810
|
-
provider: "depot",
|
|
1811
|
-
rate: "windows",
|
|
1812
|
-
usd: vcpu(.008, 2),
|
|
1813
|
-
from: "2026-11-11"
|
|
1814
|
-
},
|
|
1815
|
-
{
|
|
1816
|
-
provider: "depot",
|
|
1817
|
-
rate: "macos",
|
|
1818
|
-
usd: vcpu(.08, 8),
|
|
1819
|
-
from: "2026-11-11"
|
|
1820
|
-
},
|
|
1821
|
-
{
|
|
1822
|
-
provider: "warpbuild",
|
|
1823
|
-
rate: "linux",
|
|
1824
|
-
usd: vcpu(.004, 2),
|
|
1825
|
-
from: "2026-11-11"
|
|
1826
|
-
},
|
|
1827
|
-
{
|
|
1828
|
-
provider: "warpbuild",
|
|
1829
|
-
rate: "arm",
|
|
1830
|
-
usd: vcpu(.003, 2),
|
|
1831
|
-
from: "2026-11-11"
|
|
1832
|
-
},
|
|
1833
|
-
{
|
|
1834
|
-
provider: "warpbuild",
|
|
1835
|
-
rate: "windows",
|
|
1836
|
-
usd: vcpu(.016, 4),
|
|
1837
|
-
from: "2026-11-11"
|
|
1838
|
-
},
|
|
1839
|
-
{
|
|
1840
|
-
provider: "warpbuild",
|
|
1841
|
-
rate: "macos",
|
|
1842
|
-
usd: vcpu(.08, 6),
|
|
1843
|
-
from: "2026-11-11"
|
|
1844
|
-
},
|
|
1845
|
-
{
|
|
1846
|
-
provider: "ubicloud",
|
|
1847
|
-
rate: "standard",
|
|
1848
|
-
usd: vcpu(8e-4, 2),
|
|
1849
|
-
from: "2023-01-01"
|
|
1850
|
-
},
|
|
1851
|
-
{
|
|
1852
|
-
provider: "ubicloud",
|
|
1853
|
-
rate: "standard",
|
|
1854
|
-
usd: vcpu(.001, 2),
|
|
1855
|
-
from: "2026-05-01"
|
|
1856
|
-
},
|
|
1857
|
-
{
|
|
1858
|
-
provider: "ubicloud",
|
|
1859
|
-
rate: "standard",
|
|
1860
|
-
usd: vcpu(.00125, 2),
|
|
1861
|
-
from: "2026-09-01"
|
|
1862
|
-
},
|
|
1863
|
-
{
|
|
1864
|
-
provider: "ubicloud",
|
|
1865
|
-
rate: "premium",
|
|
1866
|
-
usd: vcpu(.0016, 2),
|
|
1867
|
-
from: "2025-05-01"
|
|
1868
|
-
},
|
|
1869
|
-
{
|
|
1870
|
-
provider: "ubicloud",
|
|
1871
|
-
rate: "premium",
|
|
1872
|
-
usd: vcpu(.002, 2),
|
|
1873
|
-
from: "2026-09-01"
|
|
1874
|
-
},
|
|
1875
|
-
{
|
|
1876
|
-
provider: "github",
|
|
1877
|
-
rate: "linux-1-core",
|
|
1878
|
-
usd: .002,
|
|
1879
|
-
from: "2026-11-11"
|
|
1880
|
-
},
|
|
1881
|
-
{
|
|
1882
|
-
provider: "github",
|
|
1883
|
-
rate: "linux-2-core",
|
|
1884
|
-
usd: .006,
|
|
1885
|
-
from: "2026-11-11"
|
|
1886
|
-
},
|
|
1887
|
-
{
|
|
1888
|
-
provider: "github",
|
|
1889
|
-
rate: "linux-arm-2-core",
|
|
1890
|
-
usd: .005,
|
|
1891
|
-
from: "2026-11-11"
|
|
1892
|
-
},
|
|
1893
|
-
{
|
|
1894
|
-
provider: "github",
|
|
1895
|
-
rate: "windows-2-core",
|
|
1896
|
-
usd: .01,
|
|
1897
|
-
from: "2026-11-11"
|
|
1898
|
-
},
|
|
1899
|
-
{
|
|
1900
|
-
provider: "github",
|
|
1901
|
-
rate: "windows-arm-2-core",
|
|
1902
|
-
usd: .01,
|
|
1903
|
-
from: "2026-11-11"
|
|
1904
|
-
},
|
|
1905
|
-
{
|
|
1906
|
-
provider: "github",
|
|
1907
|
-
rate: "macos",
|
|
1908
|
-
usd: .062,
|
|
1909
|
-
from: "2026-11-11"
|
|
1910
|
-
}
|
|
1911
|
-
];
|
|
1912
|
-
/** A UTC day (YYYY-MM-DD) as epoch ms at its midnight. */
|
|
1913
|
-
const dayMs = (day) => Date.parse(`${day}T00:00:00Z`);
|
|
1914
|
-
/**
|
|
1915
|
-
* Looks up price rows, leaving out any for a rate RATES doesn't list. Rows for the same rate and
|
|
1916
|
-
* day replace earlier ones in the list, so rows added on top of BASE_PRICES win.
|
|
1917
|
-
*/
|
|
1918
|
-
function priceBook(rows) {
|
|
1919
|
-
const byRate = /* @__PURE__ */ new Map();
|
|
1920
|
-
for (const row of rows) {
|
|
1921
|
-
if (!isRate(row.provider, row.rate)) continue;
|
|
1922
|
-
const key = `${row.provider}:${row.rate}`;
|
|
1923
|
-
const days = byRate.get(key) ?? /* @__PURE__ */ new Map();
|
|
1924
|
-
days.set(row.from, row);
|
|
1925
|
-
byRate.set(key, days);
|
|
1926
|
-
}
|
|
1927
|
-
const histories = new Map([...byRate].map(([key, days]) => [key, [...days.values()].sort((a, b) => a.from.localeCompare(b.from))]));
|
|
1928
|
-
const changes = /* @__PURE__ */ new Set();
|
|
1929
|
-
for (const history of histories.values()) for (const row of history.slice(1)) changes.add(dayMs(row.from));
|
|
1930
|
-
const history = (provider, rate) => histories.get(`${provider}:${rate}`) ?? [];
|
|
1931
|
-
return {
|
|
1932
|
-
usd(provider, rate, at) {
|
|
1933
|
-
let usd = null;
|
|
1934
|
-
for (const [i, row] of history(provider, rate).entries()) if (i === 0 || dayMs(row.from) <= at) usd = row.usd;
|
|
1935
|
-
return usd;
|
|
1936
|
-
},
|
|
1937
|
-
history,
|
|
1938
|
-
changes: [...changes].sort((a, b) => a - b)
|
|
1939
|
-
};
|
|
1940
|
-
}
|
|
1941
|
-
({ ...GITHUB_LABELS });
|
|
1942
|
-
priceBook(BASE_PRICES);
|
|
1943
|
-
// ../../packages/providers/src/index.ts
|
|
1944
|
-
/**
|
|
1945
|
-
* The hosted runner services a relay can send a job to. Each runs a job under the customer's own
|
|
1946
|
-
* account through its own GitHub App, which picks up any job queued with one of its labels, so
|
|
1947
|
-
* routing to one only means answering one of its labels. Each is a step in the runner order and an
|
|
1948
|
-
* input on the relay, both named by its id.
|
|
1949
|
-
*/
|
|
1950
|
-
const HOSTED_PROVIDER_IDS = [
|
|
1951
|
-
"blacksmith",
|
|
1952
|
-
"depot",
|
|
1953
|
-
"namespace",
|
|
1954
|
-
"warpbuild",
|
|
1955
|
-
"ubicloud",
|
|
1956
|
-
"runs-on"
|
|
1957
|
-
];
|
|
1958
|
-
const LABEL_PREFIXES = {
|
|
1959
|
-
blacksmith: ["blacksmith-"],
|
|
1960
|
-
depot: ["depot-"],
|
|
1961
|
-
namespace: ["namespace-profile-", "nscloud-"],
|
|
1962
|
-
warpbuild: ["warp-"],
|
|
1963
|
-
ubicloud: ["ubicloud-"],
|
|
1964
|
-
"runs-on": ["runs-on=", "runs-on/"]
|
|
1965
|
-
};
|
|
1966
|
-
/** Whether a lowercase label starts with one of `prefixes`, or is the bare name one ends in `-`. */
|
|
1967
|
-
const matchesPrefix = (prefixes, lower) => prefixes.some((prefix) => lower.startsWith(prefix) || prefix.endsWith("-") && lower === prefix.slice(0, -1));
|
|
1968
|
-
const matches = (provider, lower) => matchesPrefix(LABEL_PREFIXES[provider], lower);
|
|
1969
|
-
/** The hosted provider whose runners a label asks for, or null. */
|
|
1970
|
-
function hostedProviderOf(label) {
|
|
1971
|
-
const lower = label.toLowerCase();
|
|
1972
|
-
return HOSTED_PROVIDER_IDS.find((id) => matches(id, lower)) ?? null;
|
|
1973
|
-
}
|
|
1974
|
-
// workflows.ts
|
|
1975
|
-
/** The relay version `init` writes. Bump it with each relayrunner/actions release. */
|
|
1976
|
-
const RELAY_REF = "v1.0.0-beta.5";
|
|
1977
|
-
const RELAY_WORKFLOW = "relayrunner/actions/.github/workflows/relay.yml";
|
|
1978
|
-
const DEPLOY_SECRET = /\bsecrets\.(?!GITHUB_TOKEN\b)[A-Za-z_][A-Za-z0-9_]*/;
|
|
1979
|
-
const LINUX_PACKAGE_MANAGER = /(^|[\s;&|(])(sudo\s+)?(apt-get|apt|yum|dnf|apk)\s+(install|update|add)\b/m;
|
|
1980
|
-
function analyzeWorkflows(files, options = {}) {
|
|
1981
|
-
const jobs = [];
|
|
1982
|
-
const errors = [];
|
|
1983
|
-
for (const { file, source } of files) {
|
|
1984
|
-
const doc = parseDocument(source);
|
|
1985
|
-
if (doc.errors.length) {
|
|
1986
|
-
errors.push({
|
|
1987
|
-
file,
|
|
1988
|
-
message: doc.errors[0].message.split("\n")[0]
|
|
1989
|
-
});
|
|
1990
|
-
continue;
|
|
1991
|
-
}
|
|
1992
|
-
const workflow = doc.toJS();
|
|
1993
|
-
if (!workflow || typeof workflow !== "object") continue;
|
|
1994
|
-
const all = workflow.jobs;
|
|
1995
|
-
if (!all || typeof all !== "object") continue;
|
|
1996
|
-
const relays = new Set(Object.entries(all).filter(([, job]) => isRelayJob(job)).map(([id]) => id));
|
|
1997
|
-
const reusableOnly = onlyWorkflowCall(workflow.on);
|
|
1998
|
-
for (const [id, raw] of Object.entries(all)) {
|
|
1999
|
-
if (!raw || typeof raw !== "object") continue;
|
|
2000
|
-
const job = raw;
|
|
2001
|
-
if (relays.has(id)) continue;
|
|
2002
|
-
jobs.push(judge(file, id, job, workflow, relays, reusableOnly, options));
|
|
2003
|
-
}
|
|
2004
|
-
}
|
|
2005
|
-
return {
|
|
2006
|
-
jobs,
|
|
2007
|
-
errors
|
|
2008
|
-
};
|
|
2009
|
-
}
|
|
2010
|
-
/** True when any job already runs where a relay sends it. */
|
|
2011
|
-
function isSetUp(jobs) {
|
|
2012
|
-
return jobs.some((job) => job.verdict === "routed");
|
|
2013
|
-
}
|
|
2014
|
-
function judge(file, id, job, workflow, relays, reusableOnly, options) {
|
|
2015
|
-
const base = {
|
|
2016
|
-
file,
|
|
2017
|
-
job: id,
|
|
2018
|
-
warnings: []
|
|
2019
|
-
};
|
|
2020
|
-
const skip = (reason) => ({
|
|
2021
|
-
...base,
|
|
2022
|
-
verdict: "skipped",
|
|
2023
|
-
reason
|
|
2024
|
-
});
|
|
2025
|
-
if (typeof job.uses === "string") return skip("calls a reusable workflow");
|
|
2026
|
-
if (reusableOnly) return skip("part of a reusable workflow; it runs wherever the calling workflow sends it");
|
|
2027
|
-
const runsOn = job["runs-on"];
|
|
2028
|
-
if (runsOn === void 0) return skip("has no runs-on");
|
|
2029
|
-
if (typeof runsOn !== "string") return skip("runs-on is a list of labels or a runner group");
|
|
2030
|
-
if (runsOn.includes("${{")) {
|
|
2031
|
-
const relay = /^\$\{\{\s*needs\.([\w-]+)\.outputs\.runner\s*\}\}$/.exec(runsOn.trim())?.[1];
|
|
2032
|
-
if (relay && relays.has(relay)) return {
|
|
2033
|
-
...base,
|
|
2034
|
-
verdict: "routed"
|
|
2035
|
-
};
|
|
2036
|
-
return skip("runs-on is an expression");
|
|
2037
|
-
}
|
|
2038
|
-
if (hasMatrix(job)) return skip("uses a matrix, and one relay can't serve every leg");
|
|
2039
|
-
const deploy = deploySignal(job, workflow);
|
|
2040
|
-
if (deploy) return skip(`looks like a deploy job (${deploy})`);
|
|
2041
|
-
const label = runsOn.trim();
|
|
2042
|
-
const lower = label.toLowerCase();
|
|
2043
|
-
let provider;
|
|
2044
|
-
let machine = "self-hosted";
|
|
2045
|
-
const hosted = hostedProviderOf(lower);
|
|
2046
|
-
if (/(^|-)windows-/.test(lower)) return skip("Windows jobs can't run on machines yet");
|
|
2047
|
-
if (hosted) {
|
|
2048
|
-
provider = hosted;
|
|
2049
|
-
if (lower.includes("macos")) machine = "macOS";
|
|
2050
|
-
} else if (/^(ubuntu|macos)-/.test(lower)) {
|
|
2051
|
-
provider = "github";
|
|
2052
|
-
if (lower.startsWith("macos-")) machine = "macOS";
|
|
2053
|
-
} else if (lower === "relayrunner") return skip("already runs on RelayRunner");
|
|
2054
|
-
else if (lower === "self-hosted") return skip("already runs on a self-hosted runner");
|
|
2055
|
-
else return skip(`${label} isn't a GitHub-hosted or hosted provider label`);
|
|
2056
|
-
const warnings = jobWarnings(job, options);
|
|
2057
|
-
return {
|
|
2058
|
-
...base,
|
|
2059
|
-
verdict: "ready",
|
|
2060
|
-
provider,
|
|
2061
|
-
label,
|
|
2062
|
-
machine,
|
|
2063
|
-
warnings
|
|
2064
|
-
};
|
|
2065
|
-
}
|
|
2066
|
-
function isRelayJob(job) {
|
|
2067
|
-
return typeof job?.uses === "string" && job.uses.split("@")[0] === "relayrunner/actions/.github/workflows/relay.yml";
|
|
2068
|
-
}
|
|
2069
|
-
function onlyWorkflowCall(on) {
|
|
2070
|
-
if (on === "workflow_call") return true;
|
|
2071
|
-
if (Array.isArray(on)) return on.length > 0 && on.every((event) => event === "workflow_call");
|
|
2072
|
-
if (on && typeof on === "object") {
|
|
2073
|
-
const events = Object.keys(on);
|
|
2074
|
-
return events.length > 0 && events.every((event) => event === "workflow_call");
|
|
2075
|
-
}
|
|
2076
|
-
return false;
|
|
2077
|
-
}
|
|
2078
|
-
function hasMatrix(job) {
|
|
2079
|
-
const strategy = job.strategy;
|
|
2080
|
-
return !!strategy && typeof strategy === "object" && strategy.matrix !== void 0;
|
|
2081
|
-
}
|
|
2082
|
-
function deploySignal(job, workflow) {
|
|
2083
|
-
if (job.environment !== void 0) return "environment";
|
|
2084
|
-
const permissions = job.permissions ?? workflow.permissions;
|
|
2085
|
-
if (permissions === "write-all") return "write-all permissions";
|
|
2086
|
-
if (permissions && typeof permissions === "object" && permissions["id-token"] === "write") return "id-token: write";
|
|
2087
|
-
const secret = DEPLOY_SECRET.exec(JSON.stringify(job))?.[0];
|
|
2088
|
-
if (secret) return `uses ${secret}`;
|
|
2089
|
-
return null;
|
|
2090
|
-
}
|
|
2091
|
-
function jobWarnings(job, options) {
|
|
2092
|
-
const warnings = [];
|
|
2093
|
-
const docker = !options.vm;
|
|
2094
|
-
if (docker && job.services !== void 0) warnings.push("uses services, which need Docker on the machine");
|
|
2095
|
-
if (docker && job.container !== void 0) warnings.push("runs in a container, which needs Docker on the machine");
|
|
2096
|
-
const steps = Array.isArray(job.steps) ? job.steps : [];
|
|
2097
|
-
const providerActions = /* @__PURE__ */ new Set();
|
|
2098
|
-
let packages = false;
|
|
2099
|
-
for (const step of steps) {
|
|
2100
|
-
if (!step || typeof step !== "object") continue;
|
|
2101
|
-
if (typeof step.run === "string" && LINUX_PACKAGE_MANAGER.test(step.run)) packages = true;
|
|
2102
|
-
if (typeof step.uses === "string") {
|
|
2103
|
-
const action = step.uses.split("@")[0];
|
|
2104
|
-
if (action.startsWith("useblacksmith/")) providerActions.add(action);
|
|
2105
|
-
if (docker && action.startsWith("docker://")) warnings.push("runs a Docker action, which needs Docker on the machine");
|
|
2106
|
-
}
|
|
2107
|
-
}
|
|
2108
|
-
if (packages && !options.vm && options.hostOs !== "linux") warnings.push(options.hostOs === "macos" ? "installs Linux packages (apt-get, yum or apk), which macOS doesn't have" : "installs Linux packages (apt-get, yum or apk)");
|
|
2109
|
-
for (const action of providerActions) warnings.push(`uses ${action}, which is made for Blacksmith runners`);
|
|
2110
|
-
return warnings;
|
|
2111
|
-
}
|
|
2112
|
-
/**
|
|
2113
|
-
* Routes the given jobs of one workflow file through the relay. Returns the new file contents.
|
|
2114
|
-
* Each job must have come back `ready` from analyzeWorkflows for this same source.
|
|
2115
|
-
*/
|
|
2116
|
-
function routeJobs(source, jobs) {
|
|
2117
|
-
const doc = parseDocument(source);
|
|
2118
|
-
const all = doc.get("jobs");
|
|
2119
|
-
if (!isMap(all)) throw new Error("This workflow has no jobs map.");
|
|
2120
|
-
for (const job of jobs) {
|
|
2121
|
-
if (job.verdict !== "ready" || !job.provider || !job.label) throw new Error(`${job.job} isn't ready to route.`);
|
|
2122
|
-
routeJob(doc, all, job);
|
|
2123
|
-
}
|
|
2124
|
-
return doc.toString({
|
|
2125
|
-
lineWidth: 0,
|
|
2126
|
-
flowCollectionPadding: false
|
|
2127
|
-
});
|
|
2128
|
-
}
|
|
2129
|
-
function routeJob(doc, all, job) {
|
|
2130
|
-
const index = all.items.findIndex((pair) => isScalar(pair.key) && pair.key.value === job.job);
|
|
2131
|
-
const pair = all.items[index];
|
|
2132
|
-
if (!pair || !isMap(pair.value)) throw new Error(`No job ${job.job} in this workflow.`);
|
|
2133
|
-
const node = pair.value;
|
|
2134
|
-
const relayId = freeId(all, `relay-${job.job}`);
|
|
2135
|
-
const relay = doc.createNode({
|
|
2136
|
-
uses: `${RELAY_WORKFLOW}@${RELAY_REF}`,
|
|
2137
|
-
with: {
|
|
2138
|
-
machine: job.machine ?? "self-hosted",
|
|
2139
|
-
[job.provider]: job.label
|
|
2140
|
-
}
|
|
2141
|
-
});
|
|
2142
|
-
const key = new Scalar(relayId);
|
|
2143
|
-
const jobKey = pair.key;
|
|
2144
|
-
key.spaceBefore = jobKey.spaceBefore;
|
|
2145
|
-
if (key.spaceBefore === void 0 && index > 0) key.spaceBefore = true;
|
|
2146
|
-
key.commentBefore = jobKey.commentBefore;
|
|
2147
|
-
jobKey.commentBefore = void 0;
|
|
2148
|
-
jobKey.spaceBefore = true;
|
|
2149
|
-
all.items.splice(index, 0, doc.createPair(key, relay));
|
|
2150
|
-
const runsOn = node.get("runs-on", true);
|
|
2151
|
-
const target = `\${{ needs.${relayId}.outputs.runner }}`;
|
|
2152
|
-
if (isScalar(runsOn)) {
|
|
2153
|
-
runsOn.value = target;
|
|
2154
|
-
runsOn.type = Scalar.PLAIN;
|
|
2155
|
-
} else node.set("runs-on", target);
|
|
2156
|
-
const needs = node.get("needs", true);
|
|
2157
|
-
if (needs === void 0) {
|
|
2158
|
-
const at = node.items.findIndex((item) => isScalar(item.key) && item.key.value === "runs-on");
|
|
2159
|
-
node.items.splice(Math.max(at, 0), 0, doc.createPair("needs", relayId));
|
|
2160
|
-
} else if (isSeq(needs)) needs.add(doc.createNode(relayId));
|
|
2161
|
-
else if (isScalar(needs)) {
|
|
2162
|
-
const list = new YAMLSeq();
|
|
2163
|
-
list.flow = true;
|
|
2164
|
-
list.add(doc.createNode(needs.value));
|
|
2165
|
-
list.add(doc.createNode(relayId));
|
|
2166
|
-
node.set("needs", list);
|
|
2167
|
-
}
|
|
2168
|
-
}
|
|
2169
|
-
function freeId(all, wanted) {
|
|
2170
|
-
const taken = new Set(all.items.map((pair) => isScalar(pair.key) ? String(pair.key.value) : ""));
|
|
2171
|
-
if (!taken.has(wanted)) return wanted;
|
|
2172
|
-
for (let n = 2;; n++) if (!taken.has(`${wanted}-${n}`)) return `${wanted}-${n}`;
|
|
2173
|
-
}
|
|
2174
|
-
// init.ts
|
|
2175
|
-
var InitError = class extends Error {};
|
|
2176
|
-
async function planInit(cwd = process.cwd(), options = {}) {
|
|
2177
|
-
const root = findRepoRoot(cwd);
|
|
2178
|
-
if (!root) throw new InitError("Not in a git checkout. Run `relayrunner init` inside a repo.");
|
|
2179
|
-
const repo = await originRepo(root);
|
|
2180
|
-
const visibility = repo ? await repoVisibility(repo, options.fetcher) : "unknown";
|
|
2181
|
-
const files = readWorkflowFiles(root);
|
|
2182
|
-
const { jobs, errors } = analyzeWorkflows(files, options.hostOs ? options : {
|
|
2183
|
-
hostOs: hostOs(),
|
|
2184
|
-
vm: await isolationState() === "ready"
|
|
2185
|
-
});
|
|
2186
|
-
return {
|
|
2187
|
-
root,
|
|
2188
|
-
repo,
|
|
2189
|
-
visibility,
|
|
2190
|
-
files,
|
|
2191
|
-
jobs,
|
|
2192
|
-
errors
|
|
2193
|
-
};
|
|
2194
|
-
}
|
|
2195
|
-
/** Picks jobs by `job`, `file:job` or `all`. Throws when a name is unknown, ambiguous or not ready. */
|
|
2196
|
-
function selectJobs(jobs, names) {
|
|
2197
|
-
const ready = jobs.filter((job) => job.verdict === "ready");
|
|
2198
|
-
if (names.length === 1 && names[0] === "all") return ready;
|
|
2199
|
-
const picked = /* @__PURE__ */ new Map();
|
|
2200
|
-
for (const name of names) {
|
|
2201
|
-
const [file, id] = name.includes(":") ? name.split(/:(?=[^:]*$)/) : [void 0, name];
|
|
2202
|
-
const matches = jobs.filter((job) => job.job === id && (!file || job.file === file || shortFile(job.file) === file));
|
|
2203
|
-
if (!matches.length) throw new InitError(`No job named ${name}.`);
|
|
2204
|
-
if (matches.length > 1) throw new InitError(`${name} is in more than one workflow. Name it as ${matches.map((job) => `${job.file}:${job.job}`).join(" or ")}.`);
|
|
2205
|
-
const job = matches[0];
|
|
2206
|
-
if (job.verdict === "routed") throw new InitError(`${name} is already routed.`);
|
|
2207
|
-
if (job.verdict === "skipped") throw new InitError(`${name} can't be routed: ${job.reason}.`);
|
|
2208
|
-
picked.set(`${job.file}:${job.job}`, job);
|
|
2209
|
-
}
|
|
2210
|
-
return [...picked.values()];
|
|
2211
|
-
}
|
|
2212
|
-
/** The new contents of each workflow file the chosen jobs live in. */
|
|
2213
|
-
function changesFor(plan, chosen) {
|
|
2214
|
-
const byFile = /* @__PURE__ */ new Map();
|
|
2215
|
-
for (const job of chosen) byFile.set(job.file, [...byFile.get(job.file) ?? [], job]);
|
|
2216
|
-
return [...byFile].map(([file, jobs]) => {
|
|
2217
|
-
const before = plan.files.find((entry) => entry.file === file).source;
|
|
2218
|
-
return {
|
|
2219
|
-
file,
|
|
2220
|
-
jobs,
|
|
2221
|
-
before,
|
|
2222
|
-
after: routeJobs(before, jobs)
|
|
2223
|
-
};
|
|
2224
|
-
});
|
|
2225
|
-
}
|
|
2226
|
-
function writeChanges(root, changes) {
|
|
2227
|
-
for (const change of changes) writeFileSync(join(root, change.file), change.after);
|
|
2228
|
-
}
|
|
2229
|
-
function hostOs() {
|
|
2230
|
-
if (process.platform === "darwin") return "macos";
|
|
2231
|
-
if (process.platform === "linux") return "linux";
|
|
2232
|
-
}
|
|
2233
|
-
const PUBLIC_REPO = "This repo is public, and machines never take jobs from public repos. There's nothing for init to set up here.";
|
|
2234
|
-
const initCommand = defineCommand({
|
|
2235
|
-
meta: {
|
|
2236
|
-
name: "init",
|
|
2237
|
-
description: "Route this repo's GitHub Actions jobs through RelayRunner, so they run on your machine when it's online. Edits workflow files; never commits."
|
|
2238
|
-
},
|
|
2239
|
-
args: {
|
|
2240
|
-
plan: {
|
|
2241
|
-
type: "boolean",
|
|
2242
|
-
description: "List every job and whether it can be routed. Changes nothing."
|
|
2243
|
-
},
|
|
2244
|
-
apply: {
|
|
2245
|
-
type: "string",
|
|
2246
|
-
description: "Route these jobs without prompting: comma-separated ids or file:job, or `all` for every ready job"
|
|
2247
|
-
},
|
|
2248
|
-
json: {
|
|
2249
|
-
type: "boolean",
|
|
2250
|
-
description: "Print the result as JSON (with --plan or --apply)"
|
|
2251
|
-
}
|
|
2252
|
-
},
|
|
2253
|
-
async run({ args }) {
|
|
2254
|
-
try {
|
|
2255
|
-
const plan = await planInit();
|
|
2256
|
-
if (args.apply !== void 0) return apply(plan, args.apply, !!args.json);
|
|
2257
|
-
if (args.plan || args.json) return printPlan(plan, !!args.json);
|
|
2258
|
-
if (!process.stdin.isTTY) {
|
|
2259
|
-
printPlan(plan, false);
|
|
2260
|
-
console.log("\nRun `relayrunner init --apply <jobs>` to route jobs without prompts.");
|
|
2261
|
-
return;
|
|
2262
|
-
}
|
|
2263
|
-
await interactive(plan);
|
|
2264
|
-
} catch (error) {
|
|
2265
|
-
if (!(error instanceof InitError)) throw error;
|
|
2266
|
-
if (args.json) console.log(JSON.stringify({ error: error.message }, null, 2));
|
|
2267
|
-
else console.error(error.message);
|
|
2268
|
-
process.exitCode = 1;
|
|
2269
|
-
}
|
|
2270
|
-
}
|
|
2271
|
-
});
|
|
2272
|
-
function planJson(plan) {
|
|
2273
|
-
return {
|
|
2274
|
-
repo: plan.repo,
|
|
2275
|
-
visibility: plan.visibility,
|
|
2276
|
-
relay: RELAY_REF,
|
|
2277
|
-
setUp: isSetUp(plan.jobs),
|
|
2278
|
-
...plan.visibility === "public" ? { refused: "public_repo" } : {},
|
|
2279
|
-
jobs: plan.jobs,
|
|
2280
|
-
errors: plan.errors
|
|
2281
|
-
};
|
|
2282
|
-
}
|
|
2283
|
-
function printPlan(plan, json) {
|
|
2284
|
-
if (json) return console.log(JSON.stringify(planJson(plan), null, 2));
|
|
2285
|
-
console.log(describeRepo(plan));
|
|
2286
|
-
if (plan.visibility === "public") return console.log(PUBLIC_REPO);
|
|
2287
|
-
if (!plan.files.length) return console.log("No workflows in .github/workflows.");
|
|
2288
|
-
for (const [title, verdict] of [
|
|
2289
|
-
["Ready to route", "ready"],
|
|
2290
|
-
["Already routed", "routed"],
|
|
2291
|
-
["Skipped", "skipped"]
|
|
2292
|
-
]) {
|
|
2293
|
-
const jobs = plan.jobs.filter((job) => job.verdict === verdict);
|
|
2294
|
-
if (!jobs.length) continue;
|
|
2295
|
-
console.log(`\n${title}`);
|
|
2296
|
-
for (const job of jobs) console.log(` ${jobLine(job)}`);
|
|
2297
|
-
}
|
|
2298
|
-
for (const error of plan.errors) console.log(`\nCouldn't read ${error.file}: ${error.message}`);
|
|
2299
|
-
}
|
|
2300
|
-
function apply(plan, list, json) {
|
|
2301
|
-
if (plan.visibility === "public") throw new InitError(PUBLIC_REPO);
|
|
2302
|
-
const names = list.split(",").map((name) => name.trim()).filter(Boolean);
|
|
2303
|
-
if (!names.length) throw new InitError("Name the jobs to route, or `all`.");
|
|
2304
|
-
const chosen = selectJobs(plan.jobs, names);
|
|
2305
|
-
if (!chosen.length) throw new InitError("No jobs are ready to route.");
|
|
2306
|
-
const changes = changesFor(plan, chosen);
|
|
2307
|
-
writeChanges(plan.root, changes);
|
|
2308
|
-
const routed = chosen.map(({ file, job, warnings }) => ({
|
|
2309
|
-
file,
|
|
2310
|
-
job,
|
|
2311
|
-
warnings
|
|
2312
|
-
}));
|
|
2313
|
-
if (json) return console.log(JSON.stringify({
|
|
2314
|
-
relay: RELAY_REF,
|
|
2315
|
-
routed
|
|
2316
|
-
}, null, 2));
|
|
2317
|
-
for (const change of changes) console.log(`Updated ${change.file} (${change.jobs.map((job) => job.job).join(", ")})`);
|
|
2318
|
-
console.log("Commit and push to start routing.");
|
|
2319
|
-
}
|
|
2320
|
-
async function interactive(plan) {
|
|
2321
|
-
clack.intro("RelayRunner init");
|
|
2322
|
-
clack.log.info(describeRepo(plan));
|
|
2323
|
-
if (plan.visibility === "public") return clack.outro(PUBLIC_REPO);
|
|
2324
|
-
if (plan.visibility === "unknown") clack.log.warn("Couldn't check whether this repo is public. Machines only take jobs from private repos.");
|
|
2325
|
-
for (const error of plan.errors) clack.log.warn(`Couldn't read ${error.file}: ${error.message}`);
|
|
2326
|
-
if (!plan.files.length) return clack.outro("No workflows in .github/workflows.");
|
|
2327
|
-
await chooseAndWrite(plan, (message) => clack.outro(message));
|
|
2328
|
-
}
|
|
2329
|
-
/** Lists the jobs, lets the user pick, shows the diff and writes it. `finish` gets the last line. */
|
|
2330
|
-
async function chooseAndWrite(plan, finish) {
|
|
2331
|
-
const routed = plan.jobs.filter((job) => job.verdict === "routed");
|
|
2332
|
-
const skipped = plan.jobs.filter((job) => job.verdict === "skipped");
|
|
2333
|
-
const ready = plan.jobs.filter((job) => job.verdict === "ready");
|
|
2334
|
-
if (routed.length) clack.note(routed.map(jobLine).join("\n"), "Already routed");
|
|
2335
|
-
if (skipped.length) clack.note(skipped.map(jobLine).join("\n"), "Skipped");
|
|
2336
|
-
if (!ready.length) return finish("No other jobs to route.");
|
|
2337
|
-
const picked = await clack.multiselect({
|
|
2338
|
-
message: "Route these jobs through RelayRunner?",
|
|
2339
|
-
options: ready.map((job) => ({
|
|
2340
|
-
value: job,
|
|
2341
|
-
label: `${shortFile(job.file)} › ${job.job}`,
|
|
2342
|
-
hint: [`${job.label} when your machine is offline`, ...job.warnings].join("; ")
|
|
2343
|
-
})),
|
|
2344
|
-
initialValues: ready,
|
|
2345
|
-
required: false
|
|
2346
|
-
});
|
|
2347
|
-
if (clack.isCancel(picked) || !picked.length) return finish("Nothing changed.");
|
|
2348
|
-
const changes = changesFor(plan, picked);
|
|
2349
|
-
for (const change of changes) console.log(`${colorDiff(unifiedDiff(change.before, change.after, change.file))}\n`);
|
|
2350
|
-
const ok = await clack.confirm({ message: `Write ${changes.length === 1 ? "this change" : `these ${changes.length} changes`}?` });
|
|
2351
|
-
if (clack.isCancel(ok) || !ok) return finish("Nothing changed.");
|
|
2352
|
-
writeChanges(plan.root, changes);
|
|
2353
|
-
const warned = picked.filter((job) => job.warnings.length);
|
|
2354
|
-
if (warned.length) clack.note(warned.map((job) => `${job.job}: ${job.warnings.join("; ")}`).join("\n"), "Check before it runs on your machine");
|
|
2355
|
-
finish(`Updated ${changes.map((change) => change.file).join(", ")}. Commit and push to start routing.`);
|
|
2356
|
-
}
|
|
2357
|
-
/**
|
|
2358
|
-
* Whether `connect` should offer to set up this checkout: it's not public, nothing in it is routed
|
|
2359
|
-
* yet, and at least one job could be.
|
|
2360
|
-
*/
|
|
2361
|
-
function shouldOfferSetup(plan) {
|
|
2362
|
-
return plan.visibility !== "public" && !isSetUp(plan.jobs) && plan.jobs.some((job) => job.verdict === "ready");
|
|
2363
|
-
}
|
|
2364
|
-
/**
|
|
2365
|
-
* Run by `connect` before it goes online. Inside a repo that could use RelayRunner but doesn't
|
|
2366
|
-
* yet, asks once whether to set it up (default no) and runs the same picker as `init`. A "no" is
|
|
2367
|
-
* remembered for that repo, so later runs don't ask again; `relayrunner init` still works. Never
|
|
2368
|
-
* throws: setup is a convenience, and `connect` goes online either way.
|
|
2369
|
-
*/
|
|
2370
|
-
async function offerSetup(cwd = process.cwd()) {
|
|
2371
|
-
try {
|
|
2372
|
-
const plan = await planInit(cwd).catch((error) => {
|
|
2373
|
-
if (error instanceof InitError) return null;
|
|
2374
|
-
throw error;
|
|
2375
|
-
});
|
|
2376
|
-
if (!plan || !shouldOfferSetup(plan)) return;
|
|
2377
|
-
const key = plan.repo ?? plan.root;
|
|
2378
|
-
if (isDeclined(key)) return;
|
|
2379
|
-
const answer = await clack.confirm({
|
|
2380
|
-
message: `Set up ${plan.repo ?? basename(plan.root)} to run its CI on this machine?`,
|
|
2381
|
-
initialValue: false
|
|
2382
|
-
});
|
|
2383
|
-
if (clack.isCancel(answer)) return;
|
|
2384
|
-
if (!answer) {
|
|
2385
|
-
rememberDeclined(key);
|
|
2386
|
-
clack.log.info("Not now. Run `relayrunner init` in this repo any time to set it up.");
|
|
2387
|
-
return;
|
|
2388
|
-
}
|
|
2389
|
-
await chooseAndWrite(plan, (message) => clack.log.success(message));
|
|
2390
|
-
} catch (error) {
|
|
2391
|
-
clack.log.warn(`Couldn't check this repo's workflows: ${error instanceof Error ? error.message : String(error)}`);
|
|
2392
|
-
}
|
|
2393
|
-
}
|
|
2394
|
-
function describeRepo(plan) {
|
|
2395
|
-
if (!plan.repo) return `${plan.root} (no GitHub remote named origin)`;
|
|
2396
|
-
return plan.visibility === "unknown" ? plan.repo : `${plan.repo} (${plan.visibility})`;
|
|
2397
|
-
}
|
|
2398
|
-
function jobLine(job) {
|
|
2399
|
-
const name = `${shortFile(job.file)} › ${job.job}`;
|
|
2400
|
-
if (job.verdict === "skipped") return `${name}: ${job.reason}`;
|
|
2401
|
-
if (job.verdict === "routed") return name;
|
|
2402
|
-
return `${name}: ${[`falls back to ${job.label}`, ...job.warnings].join("; ")}`;
|
|
2403
|
-
}
|
|
2404
|
-
function shortFile(file) {
|
|
2405
|
-
return file.replace(/^\.github\/workflows\//, "");
|
|
2406
|
-
}
|
|
2407
|
-
function colorDiff(diff) {
|
|
2408
|
-
return diff.split("\n").map((line) => line.startsWith("+") && !line.startsWith("+++") ? styleText("green", line) : line.startsWith("-") && !line.startsWith("---") ? styleText("red", line) : styleText("dim", line)).join("\n");
|
|
2409
|
-
}
|
|
2410
|
-
// machine-name.ts
|
|
2411
|
-
const MAX_LENGTH = 64;
|
|
2412
|
-
async function defaultMachineName(run$1 = run, system = platform(), host = hostname()) {
|
|
2413
|
-
const names = [];
|
|
2414
|
-
if (system === "darwin") for (const key of [
|
|
2415
|
-
"HostName",
|
|
2416
|
-
"ComputerName",
|
|
2417
|
-
"LocalHostName"
|
|
2418
|
-
]) names.push(await run$1("scutil", ["--get", key]));
|
|
2419
|
-
names.push(host.replace(/\.local$/i, ""));
|
|
2420
|
-
return (names.find((name) => name?.trim()) ?? "").trim().slice(0, MAX_LENGTH);
|
|
2421
|
-
}
|
|
2422
|
-
// runner-update.ts
|
|
2423
|
-
const RUNNER_CHECK_MS = 216e5;
|
|
2424
|
-
const BUSY_RETRY_MS = 6e5;
|
|
2425
|
-
const MAX_WAIT_MS = 864e5;
|
|
2426
|
-
function keepRunnerUpdated(options) {
|
|
2427
|
-
const checkMs = options.checkMs ?? RUNNER_CHECK_MS;
|
|
2428
|
-
const busyRetryMs = options.busyRetryMs ?? BUSY_RETRY_MS;
|
|
2429
|
-
const maxWaitMs = options.maxWaitMs ?? MAX_WAIT_MS;
|
|
2430
|
-
const latest = options.latest ?? (() => latestRunnerVersion());
|
|
2431
|
-
let dueAt = Date.now() + checkMs;
|
|
2432
|
-
let timer;
|
|
2433
|
-
let stopped = false;
|
|
2434
|
-
const schedule = (ms) => {
|
|
2435
|
-
if (stopped) return;
|
|
2436
|
-
timer = setTimeout(check, ms);
|
|
2437
|
-
timer.unref();
|
|
2438
|
-
};
|
|
2439
|
-
const check = async () => {
|
|
2440
|
-
if (options.running() > 0 && Date.now() - dueAt < maxWaitMs) return schedule(busyRetryMs);
|
|
2441
|
-
try {
|
|
2442
|
-
const version = await latest();
|
|
2443
|
-
const current = options.current();
|
|
2444
|
-
if (!stopped && isNewerVersion(version, current)) {
|
|
2445
|
-
options.log(`Updating the runner to actions/runner ${version}…`);
|
|
2446
|
-
await options.update(version);
|
|
2447
|
-
const running = options.running();
|
|
2448
|
-
options.log(running > 0 ? `New jobs run on actions/runner ${version}. Jobs already running finish on ${current}.` : `Jobs now run on actions/runner ${version}.`);
|
|
2449
|
-
}
|
|
2450
|
-
} catch (error) {
|
|
2451
|
-
options.log(`Couldn't update the runner (${error instanceof Error ? error.message : String(error)}). Trying again later.`);
|
|
2452
|
-
}
|
|
2453
|
-
dueAt = Date.now() + checkMs;
|
|
2454
|
-
schedule(checkMs);
|
|
2455
|
-
};
|
|
2456
|
-
schedule(checkMs);
|
|
2457
|
-
return () => {
|
|
2458
|
-
stopped = true;
|
|
2459
|
-
clearTimeout(timer);
|
|
2460
|
-
};
|
|
2461
|
-
}
|
|
2462
|
-
// live.ts
|
|
2463
|
-
const INITIAL_STATE = {
|
|
2464
|
-
link: "connecting",
|
|
2465
|
-
paused: false,
|
|
2466
|
-
jobs: []
|
|
2467
|
-
};
|
|
2468
|
-
/** The state after a connection event. */
|
|
2469
|
-
function nextState(state, event) {
|
|
2470
|
-
switch (event.type) {
|
|
2471
|
-
case "connecting": return {
|
|
2472
|
-
...state,
|
|
2473
|
-
link: state.link === "online" ? "reconnecting" : state.link
|
|
2474
|
-
};
|
|
2475
|
-
case "connected": return {
|
|
2476
|
-
...state,
|
|
2477
|
-
link: "online"
|
|
2478
|
-
};
|
|
2479
|
-
case "disconnected": return {
|
|
2480
|
-
...state,
|
|
2481
|
-
link: "reconnecting"
|
|
2482
|
-
};
|
|
2483
|
-
case "run": return {
|
|
2484
|
-
...state,
|
|
2485
|
-
jobs: [...state.jobs, event.routeId]
|
|
2486
|
-
};
|
|
2487
|
-
case "job": return event.update.state === "started" || !state.jobs.includes(event.update.routeId) ? state : {
|
|
2488
|
-
...state,
|
|
2489
|
-
jobs: state.jobs.filter((id) => id !== event.update.routeId)
|
|
2490
|
-
};
|
|
2491
|
-
case "paused": return {
|
|
2492
|
-
...state,
|
|
2493
|
-
paused: event.paused
|
|
2494
|
-
};
|
|
2495
|
-
default: return state;
|
|
2496
|
-
}
|
|
2497
|
-
}
|
|
2498
|
-
/**
|
|
2499
|
-
* The terminal title for a state, such as "RelayRunner · M3P0 · Waiting for jobs". It leads with
|
|
2500
|
-
* the product so the tab says what's running in it, and ends with the part that changes.
|
|
2501
|
-
*/
|
|
2502
|
-
function titleFor(state, machine) {
|
|
2503
|
-
return `RelayRunner · ${machine} · ${statusText(state)}`;
|
|
2504
|
-
}
|
|
2505
|
-
function statusText({ link, paused, jobs }) {
|
|
2506
|
-
const running = jobs.length === 1 ? "Running a job" : `Running ${jobs.length} jobs`;
|
|
2507
|
-
if (link === "connecting") return "Connecting…";
|
|
2508
|
-
if (link === "reconnecting") return jobs.length ? `${running}, reconnecting…` : "Reconnecting…";
|
|
2509
|
-
if (jobs.length) return paused ? `${running}, then paused` : running;
|
|
2510
|
-
return paused ? "Paused" : "Waiting for jobs";
|
|
2511
|
-
}
|
|
2512
|
-
const ESC = "\x1B";
|
|
2513
|
-
const BEL = "\x07";
|
|
2514
|
-
const SAVE_TITLE = `${ESC}[22;0t`;
|
|
2515
|
-
const RESTORE_TITLE = `${ESC}[23;0t`;
|
|
2516
|
-
function titleSequence(title) {
|
|
2517
|
-
return `${ESC}]0;${title.replace(/[\u0000-\u001f\u007f]/g, "")}${BEL}`;
|
|
2518
|
-
}
|
|
2519
|
-
/** What a key pressed in the terminal asks for. */
|
|
2520
|
-
function keyAction(key) {
|
|
2521
|
-
if (key === "") return "interrupt";
|
|
2522
|
-
if (key === "p" || key === "P") return "toggle-pause";
|
|
2523
|
-
return null;
|
|
2524
|
-
}
|
|
2525
|
-
/**
|
|
2526
|
-
* Starts the live title (when stdout is a terminal) and the keys (when stdin is one): `p` calls
|
|
2527
|
-
* onTogglePause, and Ctrl-C is sent on as SIGINT, since raw mode stops the terminal doing that.
|
|
2528
|
-
*/
|
|
2529
|
-
function startLive(options) {
|
|
2530
|
-
const { stdin, stdout } = process;
|
|
2531
|
-
const showTitle = stdout.isTTY;
|
|
2532
|
-
const keys = stdin.isTTY;
|
|
2533
|
-
let state = INITIAL_STATE;
|
|
2534
|
-
let title = titleFor(state, options.machine);
|
|
2535
|
-
let ended = false;
|
|
2536
|
-
if (showTitle) stdout.write(SAVE_TITLE + titleSequence(title));
|
|
2537
|
-
const onKey = (key) => {
|
|
2538
|
-
const action = keyAction(key);
|
|
2539
|
-
if (action === "toggle-pause") options.onTogglePause(state);
|
|
2540
|
-
else if (action === "interrupt") try {
|
|
2541
|
-
process.kill(0, "SIGINT");
|
|
2542
|
-
} catch {
|
|
2543
|
-
process.emit("SIGINT", "SIGINT");
|
|
2544
|
-
}
|
|
2545
|
-
};
|
|
2546
|
-
if (keys) {
|
|
2547
|
-
stdin.setRawMode(true);
|
|
2548
|
-
stdin.setEncoding("utf8");
|
|
2549
|
-
stdin.on("data", onKey);
|
|
2550
|
-
stdin.resume();
|
|
2551
|
-
}
|
|
2552
|
-
return {
|
|
2553
|
-
get state() {
|
|
2554
|
-
return state;
|
|
2555
|
-
},
|
|
2556
|
-
onEvent(event) {
|
|
2557
|
-
if (keys && event.type === "connected" && state.link === "connecting") clack.log.message("Press p to pause or resume, Ctrl-C to go offline.");
|
|
2558
|
-
state = nextState(state, event);
|
|
2559
|
-
const next = titleFor(state, options.machine);
|
|
2560
|
-
if (showTitle && next !== title) stdout.write(titleSequence(next));
|
|
2561
|
-
title = next;
|
|
2562
|
-
},
|
|
2563
|
-
end() {
|
|
2564
|
-
if (ended) return;
|
|
2565
|
-
ended = true;
|
|
2566
|
-
if (showTitle) stdout.write(RESTORE_TITLE);
|
|
2567
|
-
if (keys) {
|
|
2568
|
-
stdin.off("data", onKey);
|
|
2569
|
-
stdin.setRawMode(false);
|
|
2570
|
-
stdin.pause();
|
|
2571
|
-
}
|
|
2572
|
-
}
|
|
2573
|
-
};
|
|
2574
|
-
}
|
|
2575
|
-
// update-check.ts
|
|
2576
|
-
const CHECK_INTERVAL_MS = 864e5;
|
|
2577
|
-
const REGISTRY_URL = "https://registry.npmjs.org/relayrunner/latest";
|
|
2578
|
-
const TIMEOUT_MS = 3e3;
|
|
2579
|
-
const Cache = z.object({
|
|
2580
|
-
checkedAt: z.number(),
|
|
2581
|
-
latest: z.string()
|
|
2582
|
-
});
|
|
2583
|
-
/** The newer version npm has, or null when this CLI is current or the check couldn't tell. */
|
|
2584
|
-
async function checkForUpdate(options = {}) {
|
|
2585
|
-
const now = options.now ?? Date.now();
|
|
2586
|
-
const current = options.current ?? cliVersion;
|
|
2587
|
-
let cache = readCache();
|
|
2588
|
-
if (!cache || now - cache.checkedAt >= 864e5) {
|
|
2589
|
-
const latest = await fetchLatest(options.fetch ?? fetch);
|
|
2590
|
-
if (latest) {
|
|
2591
|
-
cache = {
|
|
2592
|
-
checkedAt: now,
|
|
2593
|
-
latest
|
|
2594
|
-
};
|
|
2595
|
-
writeCache(cache);
|
|
2596
|
-
}
|
|
2597
|
-
}
|
|
2598
|
-
return cache && isNewerVersion(cache.latest, current) ? cache.latest : null;
|
|
2599
|
-
}
|
|
2600
|
-
/** The line to print for a newer version, with the command that updates the way this one runs. */
|
|
2601
|
-
function updateNotice(latest, current = cliVersion, argv1 = process.argv[1] ?? "") {
|
|
2602
|
-
return `relayrunner ${latest} is available (you have ${current}). Update with \`${/[\\/]_npx[\\/]/.test(argv1) ? "npx relayrunner@latest connect" : "npm install --global relayrunner@latest"}\`.`;
|
|
2603
|
-
}
|
|
2604
|
-
async function fetchLatest(fetcher) {
|
|
2605
|
-
try {
|
|
2606
|
-
const response = await fetcher(REGISTRY_URL, {
|
|
2607
|
-
headers: {
|
|
2608
|
-
accept: "application/json",
|
|
2609
|
-
"user-agent": userAgent
|
|
2610
|
-
},
|
|
2611
|
-
signal: AbortSignal.timeout(TIMEOUT_MS)
|
|
2612
|
-
});
|
|
2613
|
-
if (!response.ok) {
|
|
2614
|
-
await response.body?.cancel();
|
|
2615
|
-
return null;
|
|
2616
|
-
}
|
|
2617
|
-
const body = z.object({ version: z.string() }).safeParse(await response.json());
|
|
2618
|
-
return body.success ? body.data.version : null;
|
|
2619
|
-
} catch {
|
|
2620
|
-
return null;
|
|
2621
|
-
}
|
|
2622
|
-
}
|
|
2623
|
-
function cachePath() {
|
|
2624
|
-
return join(relayrunnerHome(), "update-check.json");
|
|
2625
|
-
}
|
|
2626
|
-
function readCache() {
|
|
2627
|
-
try {
|
|
2628
|
-
const parsed = Cache.safeParse(JSON.parse(readFileSync(cachePath(), "utf8")));
|
|
2629
|
-
return parsed.success ? parsed.data : null;
|
|
2630
|
-
} catch {
|
|
2631
|
-
return null;
|
|
2632
|
-
}
|
|
2633
|
-
}
|
|
2634
|
-
function writeCache(cache) {
|
|
2635
|
-
try {
|
|
2636
|
-
mkdirSync(relayrunnerHome(), { recursive: true });
|
|
2637
|
-
writeFileSync(cachePath(), `${JSON.stringify(cache)}\n`);
|
|
2638
|
-
} catch {}
|
|
2639
|
-
}
|
|
2640
|
-
// workspaces.ts
|
|
2641
|
-
const Workspace = z.object({
|
|
2642
|
-
id: z.string().min(1),
|
|
2643
|
-
name: z.string(),
|
|
2644
|
-
slug: z.string().nullish(),
|
|
2645
|
-
memberCount: z.number().int().nonnegative().optional()
|
|
2646
|
-
});
|
|
2647
|
-
const WorkspaceFields = {
|
|
2648
|
-
workspace: Workspace.nullish(),
|
|
2649
|
-
workspaces: z.array(Workspace).optional()
|
|
2650
|
-
};
|
|
2651
|
-
/** The machine's workspaces, from the list or else the single `workspace` an older gateway sends. */
|
|
2652
|
-
function readWorkspaces(body) {
|
|
2653
|
-
return body.workspaces ?? (body.workspace ? [body.workspace] : []);
|
|
2654
|
-
}
|
|
2655
|
-
/** Whether anyone else is in one of them, so teammates' jobs could run on the machine. */
|
|
2656
|
-
function hasTeammates(workspaces) {
|
|
2657
|
-
return workspaces.some((workspace) => (workspace.memberCount ?? 0) > 1);
|
|
2658
|
-
}
|
|
2659
|
-
/** "Acme", "Acme and atticoos", "Acme, Beta and atticoos". */
|
|
2660
|
-
function workspaceNames(workspaces) {
|
|
2661
|
-
const names = workspaces.map((workspace) => workspace.name);
|
|
2662
|
-
if (names.length <= 1) return names.join("");
|
|
2663
|
-
return `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`;
|
|
2664
|
-
}
|
|
2665
|
-
/** What "anyone" reaches: the one workspace by name, or "your workspaces". */
|
|
2666
|
-
function sharingScope(workspaces) {
|
|
2667
|
-
return workspaces.length === 1 ? workspaces[0].name : "your workspaces";
|
|
2668
|
-
}
|
|
2669
|
-
/** Said after signing in when the machine isn't in any workspace yet. */
|
|
2670
|
-
function noWorkspaceYet(machine, server) {
|
|
2671
|
-
return [`${machine} isn't in a workspace yet. It takes jobs once RelayRunner is installed on a GitHub account or org you belong to, or once an org owner accepts your install request.`, `Install: ${new URL("/api/github/install", server)}`].join("\n");
|
|
2672
|
-
}
|
|
2673
|
-
// ../../packages/errors/src/codes.ts
|
|
2674
|
-
/**
|
|
2675
|
-
* Every error code the API can return. A code never changes once it ships; its message can.
|
|
2676
|
-
* Feature-specific codes read `DOMAIN_FAILURE`, so the code alone names the feature and what
|
|
2677
|
-
* went wrong. Add a code here before returning it: apps/site builds the errors page and the
|
|
2678
|
-
* OpenAPI enum from this list.
|
|
2679
|
-
*/
|
|
2680
|
-
const ERRORS = {
|
|
2681
|
-
INVALID_REQUEST: {
|
|
2682
|
-
status: 400,
|
|
2683
|
-
message: "The request isn't valid."
|
|
2684
|
-
},
|
|
2685
|
-
PAYLOAD_TOO_LARGE: {
|
|
2686
|
-
status: 413,
|
|
2687
|
-
message: "The request body is too large."
|
|
2688
|
-
},
|
|
2689
|
-
NOT_FOUND: {
|
|
2690
|
-
status: 404,
|
|
2691
|
-
message: "Not found."
|
|
2692
|
-
},
|
|
2693
|
-
METHOD_NOT_ALLOWED: {
|
|
2694
|
-
status: 405,
|
|
2695
|
-
message: "That method isn't allowed here."
|
|
2696
|
-
},
|
|
2697
|
-
RATE_LIMITED: {
|
|
2698
|
-
status: 429,
|
|
2699
|
-
message: "Too many requests. Try again shortly."
|
|
2700
|
-
},
|
|
2701
|
-
INTERNAL_ERROR: {
|
|
2702
|
-
status: 500,
|
|
2703
|
-
message: "Something went wrong on our side."
|
|
2704
|
-
},
|
|
2705
|
-
UNAUTHENTICATED: {
|
|
2706
|
-
status: 401,
|
|
2707
|
-
message: "Sign in first."
|
|
2708
|
-
},
|
|
2709
|
-
INVALID_TOKEN: {
|
|
2710
|
-
status: 401,
|
|
2711
|
-
message: "The token is invalid, expired or revoked."
|
|
2712
|
-
},
|
|
2713
|
-
FORBIDDEN: {
|
|
2714
|
-
status: 403,
|
|
2715
|
-
message: "You don't have access to that."
|
|
2716
|
-
},
|
|
2717
|
-
AGENT_NOT_ALLOWED: {
|
|
2718
|
-
status: 403,
|
|
2719
|
-
message: "Agent tokens can't call this route."
|
|
2720
|
-
},
|
|
2721
|
-
NOT_A_MEMBER: {
|
|
2722
|
-
status: 403,
|
|
2723
|
-
message: "You aren't a member of that workspace."
|
|
2724
|
-
},
|
|
2725
|
-
LEGAL_TERMS_OUTDATED: {
|
|
2726
|
-
status: 409,
|
|
2727
|
-
message: "The terms changed since you opened this page. Reload it to read the new version."
|
|
2728
|
-
},
|
|
2729
|
-
NO_ACTIVE_WORKSPACE: {
|
|
2730
|
-
status: 409,
|
|
2731
|
-
message: "Pick a workspace first."
|
|
2732
|
-
},
|
|
2733
|
-
WORKSPACE_REQUIRED: {
|
|
2734
|
-
status: 409,
|
|
2735
|
-
message: "This token reads more than one workspace. Name one with the x-relayrunner-workspace header."
|
|
2736
|
-
},
|
|
2737
|
-
CANNOT_DEMOTE_SELF: {
|
|
2738
|
-
status: 400,
|
|
2739
|
-
message: "You can't remove your own operator role."
|
|
2740
|
-
},
|
|
2741
|
-
CANNOT_DELETE_SELF: {
|
|
2742
|
-
status: 400,
|
|
2743
|
-
message: "You can't delete your own account here."
|
|
2744
|
-
},
|
|
2745
|
-
USER_HAS_SHARED_WORKSPACES: {
|
|
2746
|
-
status: 409,
|
|
2747
|
-
message: "The user is in workspaces with other members. Remove them from those first."
|
|
2748
|
-
},
|
|
2749
|
-
MACHINE_NOT_OWNED: {
|
|
2750
|
-
status: 403,
|
|
2751
|
-
message: "Only a machine with an owner can do this."
|
|
2752
|
-
},
|
|
2753
|
-
DEVICE_CODE_INVALID: {
|
|
2754
|
-
status: 400,
|
|
2755
|
-
message: "That code doesn't match a sign-in request. Check it against your terminal."
|
|
2756
|
-
},
|
|
2757
|
-
DEVICE_CODE_EXPIRED: {
|
|
2758
|
-
status: 400,
|
|
2759
|
-
message: "That code has expired. Run `relayrunner connect` again for a new one."
|
|
2760
|
-
},
|
|
2761
|
-
DEVICE_CODE_USED: {
|
|
2762
|
-
status: 409,
|
|
2763
|
-
message: "That code has already been used."
|
|
2764
|
-
},
|
|
2765
|
-
DEVICE_CODE_CLAIMED: {
|
|
2766
|
-
status: 403,
|
|
2767
|
-
message: "Another account already approved or denied this request. Run `relayrunner connect` again for a new code."
|
|
2768
|
-
},
|
|
2769
|
-
WEBSOCKET_REQUIRED: {
|
|
2770
|
-
status: 426,
|
|
2771
|
-
message: "Connect with a WebSocket upgrade."
|
|
2772
|
-
},
|
|
2773
|
-
RUNNER_ORDER_INVALID: {
|
|
2774
|
-
status: 400,
|
|
2775
|
-
message: "The runner order isn't valid."
|
|
2776
|
-
},
|
|
2777
|
-
PROVIDER_UNKNOWN: {
|
|
2778
|
-
status: 400,
|
|
2779
|
-
message: "There's no provider with that id."
|
|
2780
|
-
},
|
|
2781
|
-
PROVIDER_INVALID: {
|
|
2782
|
-
status: 400,
|
|
2783
|
-
message: "Fill in a name, summary and labels, and use https:// links."
|
|
2784
|
-
},
|
|
2785
|
-
PROVIDER_ID_INVALID: {
|
|
2786
|
-
status: 400,
|
|
2787
|
-
message: "Use lowercase letters, numbers and dashes for the id."
|
|
2788
|
-
},
|
|
2789
|
-
PROVIDER_PREFIXES_INVALID: {
|
|
2790
|
-
status: 400,
|
|
2791
|
-
message: "Add at least one label prefix, three or more characters each."
|
|
2792
|
-
},
|
|
2793
|
-
PROVIDER_EXISTS: {
|
|
2794
|
-
status: 409,
|
|
2795
|
-
message: "There's already a provider with that id."
|
|
2796
|
-
},
|
|
2797
|
-
PROVIDER_PREFIX_TAKEN: {
|
|
2798
|
-
status: 409,
|
|
2799
|
-
message: "Another provider, or GitHub's own runners, already use labels like that."
|
|
2800
|
-
},
|
|
2801
|
-
PROVIDER_NOT_CONNECTED: {
|
|
2802
|
-
status: 404,
|
|
2803
|
-
message: "That provider isn't connected."
|
|
2804
|
-
},
|
|
2805
|
-
PROVIDER_TOKEN_REJECTED: {
|
|
2806
|
-
status: 400,
|
|
2807
|
-
message: "The provider didn't accept that token. Check it and its scope."
|
|
2808
|
-
},
|
|
2809
|
-
PROVIDER_UNREACHABLE: {
|
|
2810
|
-
status: 502,
|
|
2811
|
-
message: "The provider's API didn't answer. Try again shortly."
|
|
2812
|
-
},
|
|
2813
|
-
PRICE_INVALID: {
|
|
2814
|
-
status: 400,
|
|
2815
|
-
message: "Check the price and date."
|
|
2816
|
-
},
|
|
2817
|
-
PRICE_EXISTS: {
|
|
2818
|
-
status: 409,
|
|
2819
|
-
message: "That rate already has a price from that day. Remove it first to correct it."
|
|
2820
|
-
},
|
|
2821
|
-
TOKEN_STORAGE_UNAVAILABLE: {
|
|
2822
|
-
status: 503,
|
|
2823
|
-
message: "Saving provider tokens isn't set up on this server yet."
|
|
2824
|
-
},
|
|
2825
|
-
TELEMETRY_ENDPOINT_INVALID: {
|
|
2826
|
-
status: 400,
|
|
2827
|
-
message: "Use an https URL on the internet, like https://api.honeycomb.io."
|
|
2828
|
-
},
|
|
2829
|
-
TELEMETRY_HEADER_MISSING: {
|
|
2830
|
-
status: 400,
|
|
2831
|
-
message: "Enter a value for each header."
|
|
2832
|
-
},
|
|
2833
|
-
TELEMETRY_NOT_CONFIGURED: {
|
|
2834
|
-
status: 404,
|
|
2835
|
-
message: "Telemetry isn't set up for this workspace."
|
|
2836
|
-
},
|
|
2837
|
-
WEBHOOK_SIGNATURE_INVALID: {
|
|
2838
|
-
status: 401,
|
|
2839
|
-
message: "The webhook signature is missing or doesn't match the App's secret."
|
|
2840
|
-
},
|
|
2841
|
-
WEBHOOK_SECRET_NOT_CONFIGURED: {
|
|
2842
|
-
status: 500,
|
|
2843
|
-
message: "The webhook secret for this App isn't set up on this server."
|
|
2844
|
-
},
|
|
2845
|
-
WEBHOOK_ENQUEUE_FAILED: {
|
|
2846
|
-
status: 503,
|
|
2847
|
-
message: "The delivery couldn't be queued. Redeliver it from the App's settings."
|
|
2848
|
-
},
|
|
2849
|
-
GITHUB_UNAVAILABLE: {
|
|
2850
|
-
status: 502,
|
|
2851
|
-
message: "GitHub didn't answer. Try again shortly."
|
|
2852
|
-
},
|
|
2853
|
-
GITHUB_RATE_LIMITED: {
|
|
2854
|
-
status: 503,
|
|
2855
|
-
message: "GitHub's API limit was reached. Try again shortly."
|
|
2856
|
-
},
|
|
2857
|
-
GITHUB_APP_NOT_CONFIGURED: {
|
|
2858
|
-
status: 500,
|
|
2859
|
-
message: "The GitHub App isn't set up."
|
|
2860
|
-
}
|
|
2861
|
-
};
|
|
2862
|
-
function isErrorCode(code) {
|
|
2863
|
-
return typeof code === "string" && Object.hasOwn(ERRORS, code);
|
|
2864
|
-
}
|
|
2865
|
-
// ../../packages/errors/src/app-error.ts
|
|
2866
|
-
/**
|
|
2867
|
-
* A failure with a stable code. Throw it from an API route and the API's error handler answers
|
|
2868
|
-
* with the code's status and an {@link ErrorBody}; clients get one back from {@link parseError}.
|
|
2869
|
-
*/
|
|
2870
|
-
var AppError = class extends Error {
|
|
2871
|
-
/** A string rather than ErrorCode: a client can receive codes added after it was built. */
|
|
2872
|
-
code;
|
|
2873
|
-
status;
|
|
2874
|
-
details;
|
|
2875
|
-
retryAfter;
|
|
2876
|
-
constructor(code, options = {}) {
|
|
2877
|
-
super(options.message ?? ERRORS[code].message, { cause: options.cause });
|
|
2878
|
-
this.name = "AppError";
|
|
2879
|
-
this.code = code;
|
|
2880
|
-
this.status = ERRORS[code].status;
|
|
2881
|
-
this.details = options.details;
|
|
2882
|
-
this.retryAfter = options.retryAfter;
|
|
2883
|
-
}
|
|
2884
|
-
toJSON() {
|
|
2885
|
-
return { error: {
|
|
2886
|
-
code: this.code,
|
|
2887
|
-
message: this.message,
|
|
2888
|
-
...this.details === void 0 ? {} : { details: this.details }
|
|
2889
|
-
} };
|
|
2890
|
-
}
|
|
2891
|
-
};
|
|
2892
|
-
/** Whether a response body is an {@link ErrorBody}. */
|
|
2893
|
-
function isErrorBody(body) {
|
|
2894
|
-
const error = body?.error;
|
|
2895
|
-
return typeof error === "object" && error !== null && typeof error.code === "string" && typeof error.message === "string";
|
|
2896
|
-
}
|
|
2897
|
-
/**
|
|
2898
|
-
* Reads a non-2xx response body as an AppError. Never throws: a body that isn't an
|
|
2899
|
-
* {@link ErrorBody} (a proxy's HTML page, an empty body) keeps the status with a generic message.
|
|
2900
|
-
*/
|
|
2901
|
-
function parseError(body, status) {
|
|
2902
|
-
const { code, message, details } = isErrorBody(body) ? body.error : {
|
|
2903
|
-
code: "INTERNAL_ERROR",
|
|
2904
|
-
message: `The request failed with status ${status}.`,
|
|
2905
|
-
details: void 0
|
|
2906
|
-
};
|
|
2907
|
-
const parsed = new AppError(isErrorCode(code) ? code : "INTERNAL_ERROR", {
|
|
2908
|
-
message,
|
|
2909
|
-
details
|
|
2910
|
-
});
|
|
2911
|
-
return Object.assign(parsed, {
|
|
2912
|
-
status,
|
|
2913
|
-
code
|
|
2914
|
-
});
|
|
2915
|
-
}
|
|
2916
|
-
/** An error in one line for an agent or a terminal: "Not found (NOT_FOUND)". */
|
|
2917
|
-
function describeError(error) {
|
|
2918
|
-
return `${error.message.replace(/\.$/, "")} (${error.code})`;
|
|
2919
|
-
}
|
|
2920
|
-
// api-error.ts
|
|
2921
|
-
/**
|
|
2922
|
-
* Why a request to the gateway failed, for "Couldn't …: <reason>.": the API's message and error
|
|
2923
|
-
* code when it sent one (@relayrunner/errors), else the HTTP status.
|
|
2924
|
-
*/
|
|
2925
|
-
function failureReason(server, status, body) {
|
|
2926
|
-
return isErrorBody(body) ? describeError(parseError(body, status)) : `${server} answered HTTP ${status}`;
|
|
2927
|
-
}
|
|
2928
|
-
// login.ts
|
|
2929
|
-
const CLIENT_ID = "relayrunner-cli";
|
|
2930
|
-
const DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
|
|
2931
|
-
var LoginError = class extends Error {
|
|
2932
|
-
code;
|
|
2933
|
-
constructor(code, message) {
|
|
2934
|
-
super(message);
|
|
2935
|
-
this.code = code;
|
|
2936
|
-
}
|
|
2937
|
-
};
|
|
2938
|
-
const CodeResponse = z.object({
|
|
2939
|
-
device_code: z.string().min(1),
|
|
2940
|
-
user_code: z.string().min(1),
|
|
2941
|
-
verification_uri: z.string(),
|
|
2942
|
-
verification_uri_complete: z.string().optional(),
|
|
2943
|
-
expires_in: z.number().positive(),
|
|
2944
|
-
interval: z.number().positive().optional()
|
|
2945
|
-
});
|
|
2946
|
-
const TokenResponse = z.object({ access_token: z.string().min(1) });
|
|
2947
|
-
const OAuthError = z.object({
|
|
2948
|
-
error: z.string(),
|
|
2949
|
-
error_description: z.string().optional()
|
|
2950
|
-
});
|
|
2951
|
-
const ClaimResponse = z.object({
|
|
2952
|
-
machine: z.object({
|
|
2953
|
-
id: z.string().min(1),
|
|
2954
|
-
name: z.string()
|
|
2955
|
-
}),
|
|
2956
|
-
...WorkspaceFields,
|
|
2957
|
-
token: z.string().min(1)
|
|
2958
|
-
});
|
|
2959
|
-
async function login(options) {
|
|
2960
|
-
const fetcher = options.fetcher ?? fetch;
|
|
2961
|
-
const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
2962
|
-
const now = options.now ?? Date.now;
|
|
2963
|
-
const api = (path) => new URL(path, options.server).toString();
|
|
2964
|
-
const post = (path, body, headers = {}) => fetcher(api(path), {
|
|
2965
|
-
method: "POST",
|
|
2966
|
-
headers: {
|
|
2967
|
-
"content-type": "application/json",
|
|
2968
|
-
"user-agent": userAgent,
|
|
2969
|
-
...headers
|
|
2970
|
-
},
|
|
2971
|
-
body: JSON.stringify(body)
|
|
2972
|
-
});
|
|
2973
|
-
const codeResponse = await post("/api/auth/device/code", { client_id: CLIENT_ID }).catch((error) => {
|
|
2974
|
-
const cause = error.cause?.message;
|
|
2975
|
-
throw new LoginError("UNREACHABLE", `Couldn't reach RelayRunner at ${options.server}${cause ? ` (${cause})` : ""}.`);
|
|
2976
|
-
});
|
|
2977
|
-
if (!codeResponse.ok) throw new LoginError("CODE_FAILED", `The gateway at ${options.server} wouldn't start a sign-in (HTTP ${codeResponse.status}).`);
|
|
2978
|
-
const code = CodeResponse.parse(await codeResponse.json());
|
|
2979
|
-
const url = new URL(code.verification_uri_complete ?? code.verification_uri);
|
|
2980
|
-
if (!url.searchParams.has("user_code")) url.searchParams.set("user_code", code.user_code);
|
|
2981
|
-
url.searchParams.set("name", options.name);
|
|
2982
|
-
const expiresAt = now() + code.expires_in * 1e3;
|
|
2983
|
-
await options.onCode({
|
|
2984
|
-
userCode: code.user_code,
|
|
2985
|
-
url: url.toString(),
|
|
2986
|
-
expiresAt
|
|
2987
|
-
});
|
|
2988
|
-
let interval = (code.interval ?? 5) * 1e3;
|
|
2989
|
-
let accessToken;
|
|
2990
|
-
while (!accessToken) {
|
|
2991
|
-
if (now() >= expiresAt) throw new LoginError("EXPIRED", "The sign-in code expired before it was approved.");
|
|
2992
|
-
await sleep(interval);
|
|
2993
|
-
let response;
|
|
2994
|
-
try {
|
|
2995
|
-
response = await post("/api/auth/device/token", {
|
|
2996
|
-
grant_type: DEVICE_GRANT,
|
|
2997
|
-
device_code: code.device_code,
|
|
2998
|
-
client_id: CLIENT_ID
|
|
2999
|
-
});
|
|
3000
|
-
} catch {
|
|
3001
|
-
continue;
|
|
3002
|
-
}
|
|
3003
|
-
const body = await response.json().catch(() => null);
|
|
3004
|
-
if (response.ok) {
|
|
3005
|
-
accessToken = TokenResponse.parse(body).access_token;
|
|
3006
|
-
break;
|
|
3007
|
-
}
|
|
3008
|
-
const error = OAuthError.safeParse(body);
|
|
3009
|
-
switch (error.success ? error.data.error : void 0) {
|
|
3010
|
-
case "authorization_pending": continue;
|
|
3011
|
-
case "slow_down":
|
|
3012
|
-
interval += 5e3;
|
|
3013
|
-
continue;
|
|
3014
|
-
case "access_denied": throw new LoginError("DENIED", "The sign-in was denied in the browser.");
|
|
3015
|
-
case "expired_token": throw new LoginError("EXPIRED", "The sign-in code expired before it was approved.");
|
|
3016
|
-
default:
|
|
3017
|
-
if (response.status >= 500) continue;
|
|
3018
|
-
throw new LoginError("TOKEN_FAILED", `Signing in failed: ${error.success ? error.data.error_description ?? error.data.error : `HTTP ${response.status}`}.`);
|
|
3019
|
-
}
|
|
3020
|
-
}
|
|
3021
|
-
const claimResponse = await post("/api/machines/claim", {
|
|
3022
|
-
deviceCode: code.device_code,
|
|
3023
|
-
...options.platform
|
|
3024
|
-
}, { authorization: `Bearer ${accessToken}` });
|
|
3025
|
-
if (!claimResponse.ok) {
|
|
3026
|
-
const body = await claimResponse.json().catch(() => null);
|
|
3027
|
-
throw new LoginError("CLAIM_FAILED", `The gateway approved the sign-in but wouldn't enroll this machine: ${failureReason(options.server, claimResponse.status, body)}.`);
|
|
3028
|
-
}
|
|
3029
|
-
const claimed = ClaimResponse.parse(await claimResponse.json());
|
|
3030
|
-
return {
|
|
3031
|
-
credentials: {
|
|
3032
|
-
server: new URL(options.server).origin,
|
|
3033
|
-
machine: {
|
|
3034
|
-
id: claimed.machine.id,
|
|
3035
|
-
name: claimed.machine.name
|
|
3036
|
-
},
|
|
3037
|
-
token: claimed.token
|
|
3038
|
-
},
|
|
3039
|
-
workspaces: readWorkspaces(claimed)
|
|
3040
|
-
};
|
|
3041
|
-
}
|
|
3042
|
-
function openBrowser(url) {
|
|
3043
|
-
const [command, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", [
|
|
3044
|
-
"/c",
|
|
3045
|
-
"start",
|
|
3046
|
-
"",
|
|
3047
|
-
url
|
|
3048
|
-
]] : ["xdg-open", [url]];
|
|
3049
|
-
try {
|
|
3050
|
-
const child = spawn(command, args, {
|
|
3051
|
-
stdio: "ignore",
|
|
3052
|
-
detached: true
|
|
3053
|
-
});
|
|
3054
|
-
child.on("error", () => {});
|
|
3055
|
-
child.unref();
|
|
3056
|
-
} catch {}
|
|
3057
|
-
}
|
|
3058
|
-
// pause.ts
|
|
3059
|
-
const PauseResponse = z.object({ machine: z.object({
|
|
3060
|
-
name: z.string(),
|
|
3061
|
-
paused: z.object({ by: z.string().nullable() }).nullable(),
|
|
3062
|
-
status: z.object({ state: z.string().nullable() }).optional()
|
|
3063
|
-
}) });
|
|
3064
|
-
async function setPaused(options) {
|
|
3065
|
-
const fetcher = options.fetcher ?? fetch;
|
|
3066
|
-
const action = options.paused ? "pause" : "resume";
|
|
3067
|
-
let response;
|
|
3068
|
-
try {
|
|
3069
|
-
response = await fetcher(new URL(`/api/machines/me/${action}`, options.server), {
|
|
3070
|
-
method: "POST",
|
|
3071
|
-
headers: {
|
|
3072
|
-
authorization: `Bearer ${options.token}`,
|
|
3073
|
-
"user-agent": userAgent
|
|
3074
|
-
}
|
|
3075
|
-
});
|
|
3076
|
-
} catch (error) {
|
|
3077
|
-
const cause = error.cause?.message;
|
|
3078
|
-
return {
|
|
3079
|
-
status: "failed",
|
|
3080
|
-
reason: `couldn't reach ${options.server}${cause ? ` (${cause})` : ""}`
|
|
3081
|
-
};
|
|
3082
|
-
}
|
|
3083
|
-
if (response.status === 401) return { status: "revoked" };
|
|
3084
|
-
const body = await response.json().catch(() => null);
|
|
3085
|
-
if (!response.ok) return {
|
|
3086
|
-
status: "failed",
|
|
3087
|
-
reason: failureReason(options.server, response.status, body)
|
|
3088
|
-
};
|
|
3089
|
-
const parsed = PauseResponse.safeParse(body);
|
|
3090
|
-
if (!parsed.success) return {
|
|
3091
|
-
status: "failed",
|
|
3092
|
-
reason: `${options.server} sent an unexpected response`
|
|
3093
|
-
};
|
|
3094
|
-
return {
|
|
3095
|
-
status: "ok",
|
|
3096
|
-
paused: parsed.data.machine.paused !== null,
|
|
3097
|
-
busy: parsed.data.machine.status?.state === "busy"
|
|
3098
|
-
};
|
|
3099
|
-
}
|
|
3100
|
-
/** setPaused with the machine's saved token, retrying with a newer one if it was rotated. */
|
|
3101
|
-
function pauseMachine(credentials, paused) {
|
|
3102
|
-
return withCurrentToken(credentials, (token) => setPaused({
|
|
3103
|
-
server: credentials.server,
|
|
3104
|
-
token,
|
|
3105
|
-
paused
|
|
3106
|
-
}));
|
|
3107
|
-
}
|
|
3108
|
-
// slots.ts
|
|
3109
|
-
const MAX_SLOTS = 1e3;
|
|
3110
|
-
function defaultConcurrency(cores = availableParallelism()) {
|
|
3111
|
-
return cores >= 8 ? 2 : 1;
|
|
3112
|
-
}
|
|
3113
|
-
function parseConcurrency(value, cores) {
|
|
3114
|
-
if (value === void 0 || value === "") return defaultConcurrency(cores);
|
|
3115
|
-
const n = Number(value);
|
|
3116
|
-
if (!/^\d+$/.test(value.trim()) || !Number.isSafeInteger(n) || n < 1 || n > 1e3) throw new Error(`--concurrency takes a whole number from 1 to ${MAX_SLOTS}, not "${value}".`);
|
|
3117
|
-
return n;
|
|
3118
|
-
}
|
|
3119
|
-
function slotDir(runner, slot) {
|
|
3120
|
-
return join(runner.dir, `slot-${slot}`);
|
|
3121
|
-
}
|
|
3122
|
-
function ensureSlots(runner, count, log = () => {}) {
|
|
3123
|
-
const dirs = [];
|
|
3124
|
-
const missing = [];
|
|
3125
|
-
for (let slot = 1; slot <= count; slot++) {
|
|
3126
|
-
const dir = slotDir(runner, slot);
|
|
3127
|
-
dirs.push(dir);
|
|
3128
|
-
if (!existsSync(join(dir, "run.sh"))) missing.push(slot);
|
|
3129
|
-
}
|
|
3130
|
-
if (missing.length > 0) log(missing.length === 1 ? `Setting up runner slot ${missing[0]}…` : `Setting up ${missing.length} runner slots…`);
|
|
3131
|
-
for (const slot of missing) copySlot(runner.dir, slotDir(runner, slot));
|
|
3132
|
-
return dirs;
|
|
3133
|
-
}
|
|
3134
|
-
const SKIP = /^(slot-\d+|\.slot-.*|_work|_diag|\.runner|\.credentials.*|job\.lock)$/;
|
|
3135
|
-
function copySlot(source, dir) {
|
|
3136
|
-
rmSync(dir, {
|
|
3137
|
-
recursive: true,
|
|
3138
|
-
force: true
|
|
3139
|
-
});
|
|
3140
|
-
const temp = mkdtempSync(join(source, `.${basename(dir)}-`));
|
|
3141
|
-
try {
|
|
3142
|
-
for (const name of readdirSync(source)) {
|
|
3143
|
-
if (SKIP.test(name)) continue;
|
|
3144
|
-
cpSync(join(source, name), join(temp, name), {
|
|
3145
|
-
recursive: true,
|
|
3146
|
-
mode: constants.COPYFILE_FICLONE,
|
|
3147
|
-
verbatimSymlinks: true,
|
|
3148
|
-
preserveTimestamps: true
|
|
3149
|
-
});
|
|
3150
|
-
}
|
|
3151
|
-
try {
|
|
3152
|
-
renameSync(temp, dir);
|
|
3153
|
-
} catch (error) {
|
|
3154
|
-
const code = error.code;
|
|
3155
|
-
if (code !== "EEXIST" && code !== "ENOTEMPTY") throw error;
|
|
3156
|
-
}
|
|
3157
|
-
} finally {
|
|
3158
|
-
rmSync(temp, {
|
|
3159
|
-
recursive: true,
|
|
3160
|
-
force: true
|
|
3161
|
-
});
|
|
3162
|
-
}
|
|
3163
|
-
}
|
|
3164
|
-
// share.ts
|
|
3165
|
-
const SHARE_CHOICES = ["only-me", "anyone"];
|
|
3166
|
-
const MachineSharing = z.enum(["only_me", "anyone"]);
|
|
3167
|
-
function parseShareChoice(value) {
|
|
3168
|
-
return SHARE_CHOICES.includes(value) ? value : null;
|
|
3169
|
-
}
|
|
3170
|
-
const toSharing = (choice) => choice === "only-me" ? "only_me" : "anyone";
|
|
3171
|
-
const toChoice = (sharing) => sharing === "only_me" ? "only-me" : "anyone";
|
|
3172
|
-
function sharingMeaning(sharing, scope = "your workspaces") {
|
|
3173
|
-
return sharing === "only_me" ? "runs only jobs you started" : `runs any job in ${scope}, including teammates' and bots'`;
|
|
3174
|
-
}
|
|
3175
|
-
function describeSharing(sharing, scope) {
|
|
3176
|
-
return `${toChoice(sharing)}: ${sharingMeaning(sharing, scope)}`;
|
|
3177
|
-
}
|
|
3178
|
-
const SharingResponse = z.object({ machine: z.object({ sharing: MachineSharing }) });
|
|
3179
|
-
async function setSharing(options) {
|
|
3180
|
-
const fetcher = options.fetcher ?? fetch;
|
|
3181
|
-
let response;
|
|
3182
|
-
try {
|
|
3183
|
-
response = await fetcher(new URL("/api/machines/me/sharing", options.server), {
|
|
3184
|
-
method: "PUT",
|
|
3185
|
-
headers: {
|
|
3186
|
-
authorization: `Bearer ${options.token}`,
|
|
3187
|
-
"content-type": "application/json",
|
|
3188
|
-
"user-agent": userAgent
|
|
3189
|
-
},
|
|
3190
|
-
body: JSON.stringify({ sharing: options.sharing })
|
|
3191
|
-
});
|
|
3192
|
-
} catch (error) {
|
|
3193
|
-
const cause = error.cause?.message;
|
|
3194
|
-
return {
|
|
3195
|
-
status: "failed",
|
|
3196
|
-
reason: `couldn't reach ${options.server}${cause ? ` (${cause})` : ""}`
|
|
3197
|
-
};
|
|
3198
|
-
}
|
|
3199
|
-
if (response.status === 401) return { status: "revoked" };
|
|
3200
|
-
if (response.status === 404 || response.status === 405) return {
|
|
3201
|
-
status: "failed",
|
|
3202
|
-
reason: `${options.server} doesn't support sharing yet`
|
|
3203
|
-
};
|
|
3204
|
-
const body = await response.json().catch(() => null);
|
|
3205
|
-
if (!response.ok) return {
|
|
3206
|
-
status: "failed",
|
|
3207
|
-
reason: failureReason(options.server, response.status, body)
|
|
3208
|
-
};
|
|
3209
|
-
const parsed = SharingResponse.safeParse(body);
|
|
3210
|
-
if (!parsed.success) return {
|
|
3211
|
-
status: "failed",
|
|
3212
|
-
reason: `${options.server} sent an unexpected response`
|
|
3213
|
-
};
|
|
3214
|
-
return {
|
|
3215
|
-
status: "ok",
|
|
3216
|
-
sharing: parsed.data.machine.sharing
|
|
3217
|
-
};
|
|
3218
|
-
}
|
|
3219
|
-
// firewall.ts
|
|
3220
|
-
const ANCHOR = "com.apple/relayrunner";
|
|
3221
|
-
const LABEL = "app.relayrunner.firewall";
|
|
3222
|
-
const RULES_FILE = "/etc/pf.anchors/app.relayrunner";
|
|
3223
|
-
const DAEMON_FILE = `/Library/LaunchDaemons/${LABEL}.plist`;
|
|
3224
|
-
const VM_NETWORK = "192.168.64.0/24";
|
|
3225
|
-
const VM_GATEWAY = "192.168.64.1";
|
|
3226
|
-
const DEFAULT_INTERFACE = "bridge100";
|
|
3227
|
-
function vmInterface(interfaces = networkInterfaces()) {
|
|
3228
|
-
for (const [name, addresses] of Object.entries(interfaces)) if (addresses?.some((address) => address.address === VM_GATEWAY)) return name;
|
|
3229
|
-
return DEFAULT_INTERFACE;
|
|
3230
|
-
}
|
|
3231
|
-
function firewallRules(iface) {
|
|
3232
|
-
return `pass in quick on ${iface} proto udp from any port 68 to any port 67
|
|
3233
|
-
block drop in quick on ${iface} inet from ! ${VM_NETWORK} to any
|
|
3234
|
-
pass in quick on ${iface} proto { udp, tcp } from ${VM_NETWORK} to ${VM_GATEWAY} port 53
|
|
3235
|
-
block drop in quick on ${iface} inet to { 10.0.0.0/8, 100.64.0.0/10, 169.254.0.0/16, 172.16.0.0/12, 192.168.0.0/16 }
|
|
3236
|
-
pass in quick on ${iface} inet6 proto icmp6 icmp6-type { neighbrsol, neighbradv, routersol }
|
|
3237
|
-
block drop in quick on ${iface} inet6 all
|
|
3238
|
-
`;
|
|
3239
|
-
}
|
|
3240
|
-
const LOAD = `/sbin/pfctl -q -a ${ANCHOR} -f ${RULES_FILE}; /sbin/pfctl -s info 2>/dev/null | /usr/bin/grep -q "Status: Enabled" || /sbin/pfctl -q -E`;
|
|
3241
|
-
function daemonPlist() {
|
|
3242
|
-
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
3243
|
-
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
3244
|
-
<plist version="1.0">
|
|
3245
|
-
<dict>
|
|
3246
|
-
<key>Label</key>
|
|
3247
|
-
<string>${LABEL}</string>
|
|
3248
|
-
<key>ProgramArguments</key>
|
|
3249
|
-
<array>
|
|
3250
|
-
<string>/bin/sh</string>
|
|
3251
|
-
<string>-c</string>
|
|
3252
|
-
<string>${LOAD.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">")}</string>
|
|
3253
|
-
</array>
|
|
3254
|
-
<key>RunAtLoad</key>
|
|
3255
|
-
<true/>
|
|
3256
|
-
<key>StartInterval</key>
|
|
3257
|
-
<integer>300</integer>
|
|
3258
|
-
</dict>
|
|
3259
|
-
</plist>
|
|
3260
|
-
`;
|
|
3261
|
-
}
|
|
3262
|
-
function onScript(rules, plist) {
|
|
3263
|
-
return [
|
|
3264
|
-
"set -e",
|
|
3265
|
-
`install -m 644 -o root -g wheel "${rules}" ${RULES_FILE}`,
|
|
3266
|
-
`install -m 644 -o root -g wheel "${plist}" ${DAEMON_FILE}`,
|
|
3267
|
-
`launchctl bootout system/${LABEL} 2>/dev/null || true`,
|
|
3268
|
-
`launchctl bootstrap system ${DAEMON_FILE}`,
|
|
3269
|
-
LOAD
|
|
3270
|
-
].join("\n");
|
|
3271
|
-
}
|
|
3272
|
-
function offScript() {
|
|
3273
|
-
return [
|
|
3274
|
-
`launchctl bootout system/${LABEL} 2>/dev/null || true`,
|
|
3275
|
-
`rm -f ${DAEMON_FILE} ${RULES_FILE}`,
|
|
3276
|
-
`/sbin/pfctl -q -a ${ANCHOR} -F all 2>/dev/null || true`
|
|
3277
|
-
].join("\n");
|
|
3278
|
-
}
|
|
3279
|
-
function firewallInstalled(exists = existsSync) {
|
|
3280
|
-
return exists("/etc/pf.anchors/app.relayrunner") && exists("/Library/LaunchDaemons/app.relayrunner.firewall.plist");
|
|
3281
|
-
}
|
|
3282
|
-
function sudo(script) {
|
|
3283
|
-
console.log("This needs your password, to change the Mac's firewall.");
|
|
3284
|
-
return spawnSync("sudo", [
|
|
3285
|
-
"/bin/sh",
|
|
3286
|
-
"-c",
|
|
3287
|
-
script
|
|
3288
|
-
], { stdio: "inherit" }).status === 0;
|
|
3289
|
-
}
|
|
3290
|
-
function status() {
|
|
3291
|
-
if (!firewallInstalled()) {
|
|
3292
|
-
console.log("The firewall on this Mac is off. Isolated jobs rely on the firewall inside each VM, which a job using Docker can remove.\nTurn it on with `relayrunner firewall on`.");
|
|
3293
|
-
return;
|
|
3294
|
-
}
|
|
3295
|
-
console.log("The firewall on this Mac is on. Isolated jobs can reach the internet, not this Mac or your local network.\nTurn it off with `relayrunner firewall off`.");
|
|
3296
|
-
}
|
|
3297
|
-
const firewallCommand = defineCommand({
|
|
3298
|
-
meta: {
|
|
3299
|
-
name: "firewall",
|
|
3300
|
-
description: "Show or change the firewall on this Mac that keeps isolated jobs off the Mac and your local network."
|
|
3301
|
-
},
|
|
3302
|
-
args: { state: {
|
|
3303
|
-
type: "positional",
|
|
3304
|
-
required: false,
|
|
3305
|
-
description: "on or off; leave out to show the current setting"
|
|
3306
|
-
} },
|
|
3307
|
-
run({ args }) {
|
|
3308
|
-
const fail = (message) => {
|
|
3309
|
-
console.error(message);
|
|
3310
|
-
process.exitCode = 1;
|
|
3311
|
-
};
|
|
3312
|
-
const unsupported = unsupportedReason();
|
|
3313
|
-
if (unsupported) return fail(unsupported.replace("Running jobs in VMs needs", "The firewall needs"));
|
|
3314
|
-
if (!args.state) return status();
|
|
3315
|
-
if (args.state === "off") {
|
|
3316
|
-
if (!sudo(offScript())) return fail("Couldn't turn the firewall off.");
|
|
3317
|
-
console.log("The firewall on this Mac is off.");
|
|
3318
|
-
return;
|
|
3319
|
-
}
|
|
3320
|
-
if (args.state !== "on") return fail("Use `relayrunner firewall on` or `relayrunner firewall off`.");
|
|
3321
|
-
const dir = mkdtempSync(join(tmpdir(), "relayrunner-firewall-"));
|
|
3322
|
-
try {
|
|
3323
|
-
const rules = join(dir, "rules");
|
|
3324
|
-
const plist = join(dir, "daemon.plist");
|
|
3325
|
-
writeFileSync(rules, firewallRules(vmInterface()));
|
|
3326
|
-
writeFileSync(plist, daemonPlist());
|
|
3327
|
-
if (!sudo(onScript(rules, plist))) return fail("Couldn't turn the firewall on.");
|
|
3328
|
-
} finally {
|
|
3329
|
-
rmSync(dir, {
|
|
3330
|
-
recursive: true,
|
|
3331
|
-
force: true
|
|
3332
|
-
});
|
|
3333
|
-
}
|
|
3334
|
-
console.log("The firewall on this Mac is on. Isolated jobs can reach the internet, not this Mac or your local network.\nIt also applies to other VMs that use Apple's shared VM network. Turn it off with `relayrunner firewall off`.");
|
|
3335
|
-
}
|
|
3336
|
-
});
|
|
3337
|
-
// whoami.ts
|
|
3338
|
-
const WhoamiResponse = z.object({
|
|
3339
|
-
machine: z.object({
|
|
3340
|
-
id: z.string().min(1),
|
|
3341
|
-
name: z.string(),
|
|
3342
|
-
os: z.string().nullable(),
|
|
3343
|
-
arch: z.string().nullable(),
|
|
3344
|
-
createdAt: z.union([z.string(), z.number()]),
|
|
3345
|
-
lastSeenAt: z.union([z.string(), z.number()]).nullable(),
|
|
3346
|
-
status: z.object({
|
|
3347
|
-
online: z.boolean(),
|
|
3348
|
-
state: z.string().nullable()
|
|
3349
|
-
}),
|
|
3350
|
-
paused: z.object({ by: z.string().nullable() }).nullish(),
|
|
3351
|
-
sharing: z.enum(["only_me", "anyone"]).optional()
|
|
3352
|
-
}),
|
|
3353
|
-
...WorkspaceFields,
|
|
3354
|
-
enrolledBy: z.object({
|
|
3355
|
-
name: z.string(),
|
|
3356
|
-
email: z.string()
|
|
3357
|
-
}).nullable()
|
|
3358
|
-
});
|
|
3359
|
-
async function whoami(options) {
|
|
3360
|
-
const fetcher = options.fetcher ?? fetch;
|
|
3361
|
-
let response;
|
|
3362
|
-
try {
|
|
3363
|
-
response = await fetcher(new URL("/api/machines/me", options.server), { headers: {
|
|
3364
|
-
authorization: `Bearer ${options.token}`,
|
|
3365
|
-
"user-agent": userAgent
|
|
3366
|
-
} });
|
|
3367
|
-
} catch (error) {
|
|
3368
|
-
const cause = error.cause?.message;
|
|
3369
|
-
return {
|
|
3370
|
-
status: "unverified",
|
|
3371
|
-
reason: `Couldn't reach ${options.server}${cause ? ` (${cause})` : ""}`
|
|
3372
|
-
};
|
|
3373
|
-
}
|
|
3374
|
-
if (response.status === 401) return { status: "revoked" };
|
|
3375
|
-
const body = await response.json().catch(() => null);
|
|
3376
|
-
if (!response.ok) return {
|
|
3377
|
-
status: "unverified",
|
|
3378
|
-
reason: failureReason(options.server, response.status, body)
|
|
3379
|
-
};
|
|
3380
|
-
const parsed = WhoamiResponse.safeParse(body);
|
|
3381
|
-
if (!parsed.success) return {
|
|
3382
|
-
status: "unverified",
|
|
3383
|
-
reason: `${options.server} sent an unexpected response`
|
|
3384
|
-
};
|
|
3385
|
-
return {
|
|
3386
|
-
status: "ok",
|
|
3387
|
-
identity: parsed.data
|
|
3388
|
-
};
|
|
3389
|
-
}
|
|
3390
|
-
// machine-workspaces.ts
|
|
3391
|
-
const Choice = z.object({
|
|
3392
|
-
id: z.string().min(1),
|
|
3393
|
-
name: z.string(),
|
|
3394
|
-
slug: z.string().nullish()
|
|
3395
|
-
});
|
|
3396
|
-
const MachineWorkspaces = z.object({
|
|
3397
|
-
machine: z.object({
|
|
3398
|
-
id: z.string().min(1),
|
|
3399
|
-
name: z.string(),
|
|
3400
|
-
sharing: z.enum(["only_me", "anyone"])
|
|
3401
|
-
}),
|
|
3402
|
-
workspaces: z.array(Choice),
|
|
3403
|
-
others: z.array(Choice)
|
|
3404
|
-
});
|
|
3405
|
-
/** GET the machine's workspaces, or PUT/DELETE one of them when `change` is given. */
|
|
3406
|
-
async function machineWorkspaces(options) {
|
|
3407
|
-
const fetcher = options.fetcher ?? fetch;
|
|
3408
|
-
const { change } = options;
|
|
3409
|
-
const path = change ? `/api/machines/me/workspaces/${encodeURIComponent(change.workspaceId)}` : "/api/machines/me/workspaces";
|
|
3410
|
-
let response;
|
|
3411
|
-
try {
|
|
3412
|
-
response = await fetcher(new URL(path, options.server), {
|
|
3413
|
-
method: change ? change.action === "add" ? "PUT" : "DELETE" : "GET",
|
|
3414
|
-
headers: {
|
|
3415
|
-
authorization: `Bearer ${options.token}`,
|
|
3416
|
-
"user-agent": userAgent
|
|
3417
|
-
}
|
|
3418
|
-
});
|
|
3419
|
-
} catch (error) {
|
|
3420
|
-
const cause = error.cause?.message;
|
|
3421
|
-
return {
|
|
3422
|
-
status: "failed",
|
|
3423
|
-
reason: `couldn't reach ${options.server}${cause ? ` (${cause})` : ""}`
|
|
3424
|
-
};
|
|
3425
|
-
}
|
|
3426
|
-
if (response.status === 401) return { status: "revoked" };
|
|
3427
|
-
const body = await response.json().catch(() => null);
|
|
3428
|
-
if (change && response.status === 404 && isErrorBody(body) && body.error.code === "NOT_FOUND") return { status: "not_found" };
|
|
3429
|
-
if (response.status === 404 || response.status === 405) return {
|
|
3430
|
-
status: "failed",
|
|
3431
|
-
reason: `${options.server} doesn't support choosing workspaces yet`
|
|
3432
|
-
};
|
|
3433
|
-
if (response.status === 403) return {
|
|
3434
|
-
status: "failed",
|
|
3435
|
-
reason: "only the machine's owner can change its workspaces"
|
|
3436
|
-
};
|
|
3437
|
-
if (!response.ok) return {
|
|
3438
|
-
status: "failed",
|
|
3439
|
-
reason: failureReason(options.server, response.status, body)
|
|
3440
|
-
};
|
|
3441
|
-
const parsed = MachineWorkspaces.safeParse(body);
|
|
3442
|
-
if (!parsed.success) return {
|
|
3443
|
-
status: "failed",
|
|
3444
|
-
reason: `${options.server} sent an unexpected response`
|
|
3445
|
-
};
|
|
3446
|
-
return {
|
|
3447
|
-
status: "ok",
|
|
3448
|
-
choice: parsed.data
|
|
3449
|
-
};
|
|
3450
|
-
}
|
|
3451
|
-
/** The workspace `query` names: its id, or its name or slug in any case. */
|
|
3452
|
-
function matchWorkspace(workspaces, query) {
|
|
3453
|
-
const byId = workspaces.find((workspace) => workspace.id === query);
|
|
3454
|
-
if (byId) return {
|
|
3455
|
-
status: "one",
|
|
3456
|
-
workspace: byId
|
|
3457
|
-
};
|
|
3458
|
-
const wanted = query.trim().toLowerCase();
|
|
3459
|
-
const found = workspaces.filter((workspace) => workspace.name.toLowerCase() === wanted || workspace.slug?.toLowerCase() === wanted);
|
|
3460
|
-
if (found.length === 1) return {
|
|
3461
|
-
status: "one",
|
|
3462
|
-
workspace: found[0]
|
|
3463
|
-
};
|
|
3464
|
-
return found.length ? {
|
|
3465
|
-
status: "several",
|
|
3466
|
-
workspaces: found
|
|
3467
|
-
} : { status: "none" };
|
|
3468
|
-
}
|
|
3469
|
-
/** "Acme (acme)" for listing, so two workspaces with the same name can be told apart. */
|
|
3470
|
-
function labelWorkspace(workspace, withId = false) {
|
|
3471
|
-
const slug = workspace.slug && workspace.slug !== workspace.name ? ` (${workspace.slug})` : "";
|
|
3472
|
-
return `${workspace.name}${slug}${withId ? ` ${workspace.id}` : ""}`;
|
|
3473
|
-
}
|
|
3474
|
-
/** What `relayrunner workspaces` prints. */
|
|
3475
|
-
function describeMachineWorkspaces({ machine, workspaces, others }) {
|
|
3476
|
-
const lines = [];
|
|
3477
|
-
if (!workspaces.length && !others.length) {
|
|
3478
|
-
lines.push(`${machine.name} isn't in a workspace yet. It takes jobs once RelayRunner is installed on a GitHub account or org you belong to.`);
|
|
3479
|
-
return lines.join("\n");
|
|
3480
|
-
}
|
|
3481
|
-
lines.push(`${machine.name} runs jobs in:`);
|
|
3482
|
-
if (workspaces.length) for (const w of workspaces) lines.push(` ✓ ${labelWorkspace(w)}`);
|
|
3483
|
-
else lines.push(" (none: it takes no jobs)");
|
|
3484
|
-
if (others.length) {
|
|
3485
|
-
lines.push("", "Not in:");
|
|
3486
|
-
for (const w of others) lines.push(` · ${labelWorkspace(w)}`);
|
|
3487
|
-
}
|
|
3488
|
-
lines.push("", `Sharing: ${toChoice(machine.sharing)}: ${sharingMeaning(machine.sharing, "these workspaces")}`);
|
|
3489
|
-
if (others.length) lines.push("Add one with `relayrunner workspaces add <name>`.");
|
|
3490
|
-
else if (workspaces.length) lines.push("Remove one with `relayrunner workspaces remove <name>`.");
|
|
3491
|
-
return lines.join("\n");
|
|
3492
|
-
}
|
|
3493
|
-
/** Said when `add` puts a machine that runs anyone's jobs into another workspace. */
|
|
3494
|
-
function anyoneWarning(machine, workspace) {
|
|
3495
|
-
return `${machine} is set to run anyone's jobs, so anyone who can push to ${workspace}'s private repos can run jobs on it. Use \`relayrunner share only-me\` to limit it to jobs you started.`;
|
|
3496
|
-
}
|
|
3497
|
-
// workspaces-command.ts
|
|
3498
|
-
function signedIn() {
|
|
3499
|
-
const credentials = readCredentials();
|
|
3500
|
-
if (!credentials) {
|
|
3501
|
-
console.error("Not signed in. Run `relayrunner login` or `relayrunner connect` to sign in.");
|
|
3502
|
-
process.exitCode = 1;
|
|
3503
|
-
}
|
|
3504
|
-
return credentials;
|
|
3505
|
-
}
|
|
3506
|
-
function revoked(name) {
|
|
3507
|
-
console.error(`${name} was removed or its token is no longer valid.\nRun \`relayrunner connect\` to sign in again.`);
|
|
3508
|
-
process.exitCode = 1;
|
|
3509
|
-
}
|
|
3510
|
-
const listCommand = defineCommand({
|
|
3511
|
-
meta: {
|
|
3512
|
-
name: "list",
|
|
3513
|
-
description: "List your workspaces, showing which ones this machine runs jobs in."
|
|
3514
|
-
},
|
|
3515
|
-
args: { json: {
|
|
3516
|
-
type: "boolean",
|
|
3517
|
-
description: "Print the result as JSON"
|
|
3518
|
-
} },
|
|
3519
|
-
async run({ args }) {
|
|
3520
|
-
const credentials = signedIn();
|
|
3521
|
-
if (!credentials) return;
|
|
3522
|
-
const result = await withCurrentToken(credentials, (token) => machineWorkspaces({
|
|
3523
|
-
server: credentials.server,
|
|
3524
|
-
token
|
|
3525
|
-
}));
|
|
3526
|
-
if (result.status === "revoked") return revoked(credentials.machine.name);
|
|
3527
|
-
if (result.status !== "ok") {
|
|
3528
|
-
console.error(`Couldn't list workspaces for ${credentials.machine.name}: ${result.status === "failed" ? result.reason : "not found"}.`);
|
|
3529
|
-
process.exitCode = 1;
|
|
3530
|
-
return;
|
|
3531
|
-
}
|
|
3532
|
-
console.log(args.json ? JSON.stringify(result.choice, null, 2) : describeMachineWorkspaces(result.choice));
|
|
3533
|
-
}
|
|
3534
|
-
});
|
|
3535
|
-
function changeCommand(action) {
|
|
3536
|
-
const adding = action === "add";
|
|
3537
|
-
return defineCommand({
|
|
3538
|
-
meta: {
|
|
3539
|
-
name: action,
|
|
3540
|
-
description: adding ? "Run jobs from one more of your workspaces on this machine." : "Stop running jobs from one of your workspaces on this machine. It keeps running jobs in the others."
|
|
3541
|
-
},
|
|
3542
|
-
args: { workspace: {
|
|
3543
|
-
type: "positional",
|
|
3544
|
-
required: false,
|
|
3545
|
-
description: "The workspace's name, slug or id; leave out to pick from a list"
|
|
3546
|
-
} },
|
|
3547
|
-
async run({ args }) {
|
|
3548
|
-
const credentials = signedIn();
|
|
3549
|
-
if (!credentials) return;
|
|
3550
|
-
const { server, machine } = credentials;
|
|
3551
|
-
const current = await withCurrentToken(credentials, (token) => machineWorkspaces({
|
|
3552
|
-
server,
|
|
3553
|
-
token
|
|
3554
|
-
}));
|
|
3555
|
-
if (current.status === "revoked") return revoked(machine.name);
|
|
3556
|
-
if (current.status !== "ok") {
|
|
3557
|
-
console.error(`Couldn't ${action} a workspace for ${machine.name}: ${current.status === "failed" ? current.reason : "not found"}.`);
|
|
3558
|
-
process.exitCode = 1;
|
|
3559
|
-
return;
|
|
3560
|
-
}
|
|
3561
|
-
const { workspaces, others } = current.choice;
|
|
3562
|
-
const picked = await pick(adding ? others : workspaces, args.workspace, {
|
|
3563
|
-
action,
|
|
3564
|
-
machine: machine.name,
|
|
3565
|
-
elsewhere: adding ? workspaces : others,
|
|
3566
|
-
noWorkspaces: !workspaces.length && !others.length,
|
|
3567
|
-
server
|
|
3568
|
-
});
|
|
3569
|
-
if (!picked) return;
|
|
3570
|
-
const result = await withCurrentToken(credentials, (token) => machineWorkspaces({
|
|
3571
|
-
server,
|
|
3572
|
-
token,
|
|
3573
|
-
change: {
|
|
3574
|
-
action,
|
|
3575
|
-
workspaceId: picked.id
|
|
3576
|
-
}
|
|
3577
|
-
}));
|
|
3578
|
-
if (result.status === "revoked") return revoked(machine.name);
|
|
3579
|
-
if (result.status === "not_found") {
|
|
3580
|
-
console.error(`You're no longer a member of ${picked.name}.`);
|
|
3581
|
-
process.exitCode = 1;
|
|
3582
|
-
return;
|
|
3583
|
-
}
|
|
3584
|
-
if (result.status === "failed") {
|
|
3585
|
-
console.error(`Couldn't ${action} ${picked.name}: ${result.reason}.`);
|
|
3586
|
-
process.exitCode = 1;
|
|
3587
|
-
return;
|
|
3588
|
-
}
|
|
3589
|
-
const now = result.choice;
|
|
3590
|
-
if (adding) {
|
|
3591
|
-
console.log(`${machine.name} now runs jobs in ${workspaceNames(now.workspaces)}.`);
|
|
3592
|
-
if (now.machine.sharing === "anyone") console.warn(`Warning: ${anyoneWarning(machine.name, picked.name)}`);
|
|
3593
|
-
} else if (now.workspaces.length) console.log(`${machine.name} no longer runs jobs in ${picked.name}. It still runs jobs in ${workspaceNames(now.workspaces)}.`);
|
|
3594
|
-
else {
|
|
3595
|
-
console.log(`${machine.name} no longer runs jobs in ${picked.name}.`);
|
|
3596
|
-
console.warn(`${machine.name} isn't in any workspace now, so it takes no jobs. Add one with \`relayrunner workspaces add <name>\`.`);
|
|
3597
|
-
}
|
|
3598
|
-
}
|
|
3599
|
-
});
|
|
3600
|
-
}
|
|
3601
|
-
/** The workspace to add or remove: named on the command line, or picked from a list in a terminal. */
|
|
3602
|
-
async function pick(candidates, query, context) {
|
|
3603
|
-
const fail = (message) => {
|
|
3604
|
-
console.error(message);
|
|
3605
|
-
process.exitCode = 1;
|
|
3606
|
-
return null;
|
|
3607
|
-
};
|
|
3608
|
-
if (context.noWorkspaces) return fail(noWorkspaceYet(context.machine, context.server));
|
|
3609
|
-
const adding = context.action === "add";
|
|
3610
|
-
if (query) {
|
|
3611
|
-
const match = matchWorkspace(candidates, query);
|
|
3612
|
-
if (match.status === "one") return match.workspace;
|
|
3613
|
-
if (match.status === "several") return fail([`More than one workspace is called ${JSON.stringify(query)}. Name it by id:`, ...match.workspaces.map((w) => ` ${labelWorkspace(w, true)}`)].join("\n"));
|
|
3614
|
-
const other = matchWorkspace(context.elsewhere, query);
|
|
3615
|
-
if (other.status !== "none") {
|
|
3616
|
-
const name = other.status === "one" ? other.workspace.name : query;
|
|
3617
|
-
console.log(adding ? `${context.machine} already runs jobs in ${name}.` : `${context.machine} doesn't run jobs in ${name}.`);
|
|
3618
|
-
return null;
|
|
3619
|
-
}
|
|
3620
|
-
return fail([`None of your workspaces is called ${JSON.stringify(query)}.`, ...candidates.length ? [adding ? "Workspaces you can add:" : "Workspaces you can remove:", ...candidates.map((w) => ` ${labelWorkspace(w)}`)] : []].join("\n"));
|
|
3621
|
-
}
|
|
3622
|
-
if (!candidates.length) {
|
|
3623
|
-
console.log(adding ? `${context.machine} already runs jobs in all your workspaces.` : `${context.machine} isn't in any workspace.`);
|
|
3624
|
-
return null;
|
|
3625
|
-
}
|
|
3626
|
-
if (!process.stdin.isTTY || !process.stdout.isTTY) return fail(`Name the workspace: \`relayrunner workspaces ${context.action} <name>\`.`);
|
|
3627
|
-
const choice = await clack.select({
|
|
3628
|
-
message: adding ? `Which workspace should ${context.machine} run jobs in too?` : `Which workspace should ${context.machine} stop running jobs in?`,
|
|
3629
|
-
options: candidates.map((w) => ({
|
|
3630
|
-
value: w.id,
|
|
3631
|
-
label: w.name,
|
|
3632
|
-
...w.slug && w.slug !== w.name && { hint: w.slug }
|
|
3633
|
-
}))
|
|
3634
|
-
});
|
|
3635
|
-
if (clack.isCancel(choice)) return null;
|
|
3636
|
-
return candidates.find((w) => w.id === choice) ?? null;
|
|
3637
|
-
}
|
|
3638
|
-
const workspacesCommand = defineCommand({
|
|
3639
|
-
meta: {
|
|
3640
|
-
name: "workspaces",
|
|
3641
|
-
description: "Show or change which of your workspaces this machine runs jobs in: `list` (the default), `add <name>`, `remove <name>`."
|
|
3642
|
-
},
|
|
3643
|
-
default: "list",
|
|
3644
|
-
subCommands: {
|
|
3645
|
-
list: listCommand,
|
|
3646
|
-
add: changeCommand("add"),
|
|
3647
|
-
remove: changeCommand("remove")
|
|
3648
|
-
}
|
|
3649
|
-
});
|
|
3650
|
-
/**
|
|
3651
|
-
* Why a machine has no workspaces, for `connect` and `whoami`: its owner has none yet (install
|
|
3652
|
-
* RelayRunner), or the machine just isn't in any of theirs (`relayrunner workspaces add`).
|
|
3653
|
-
*/
|
|
3654
|
-
async function emptyWorkspacesNotice(credentials) {
|
|
3655
|
-
const { server, machine } = credentials;
|
|
3656
|
-
const result = await withCurrentToken(credentials, (token) => machineWorkspaces({
|
|
3657
|
-
server,
|
|
3658
|
-
token
|
|
3659
|
-
}));
|
|
3660
|
-
if (result.status === "ok" && result.choice.others.length) return `${machine.name} isn't in any of your workspaces, so it takes no jobs. Add one with \`relayrunner workspaces add <name>\` (${workspaceNames(result.choice.others)}).`;
|
|
3661
|
-
return noWorkspaceYet(machine.name, server);
|
|
3662
|
-
}
|
|
3663
|
-
// cli.ts
|
|
3664
|
-
const DEFAULT_SERVER = "https://app.relayrunner.app";
|
|
3665
|
-
const connectCommand = defineCommand({
|
|
3666
|
-
meta: {
|
|
3667
|
-
name: "connect",
|
|
3668
|
-
description: "Put this machine online for your workspaces and run the jobs the gateway sends it. Signs in on first run; Ctrl-C takes the machine offline."
|
|
3669
|
-
},
|
|
3670
|
-
args: {
|
|
3671
|
-
server: {
|
|
3672
|
-
type: "string",
|
|
3673
|
-
description: `RelayRunner URL (default: $RELAYRUNNER_URL or ${DEFAULT_SERVER})`
|
|
3674
|
-
},
|
|
3675
|
-
name: {
|
|
3676
|
-
type: "string",
|
|
3677
|
-
description: "Suggested machine name when signing in (default: this computer's name)"
|
|
3678
|
-
},
|
|
3679
|
-
share: {
|
|
3680
|
-
type: "string",
|
|
3681
|
-
description: "Who can run jobs on this machine: only-me (jobs you started) or anyone in your workspaces. Skips the question."
|
|
3682
|
-
},
|
|
3683
|
-
concurrency: {
|
|
3684
|
-
type: "string",
|
|
3685
|
-
description: "How many jobs to run at once (default: 2 with 8 or more CPU cores, otherwise 1; with --cpus or --memory, as many as fit)"
|
|
3686
|
-
},
|
|
3687
|
-
isolated: {
|
|
3688
|
-
type: "boolean",
|
|
3689
|
-
description: "Run each job in its own Linux VM, away from your files. The default on a Mac with Apple silicon and Apple's container tool.",
|
|
3690
|
-
negativeDescription: "Run jobs on this machine itself, where they can read your files."
|
|
3691
|
-
},
|
|
3692
|
-
macos: {
|
|
3693
|
-
type: "boolean",
|
|
3694
|
-
description: "Also take macOS jobs, which run on this Mac itself. Linux jobs still run in a VM."
|
|
3695
|
-
},
|
|
3696
|
-
cpus: {
|
|
3697
|
-
type: "string",
|
|
3698
|
-
description: "CPUs for each job's VM (default: an even share of this Mac's cores)"
|
|
3699
|
-
},
|
|
3700
|
-
memory: {
|
|
3701
|
-
type: "string",
|
|
3702
|
-
description: "Memory for each job's VM, in GB (default: an even share of half this Mac's)"
|
|
3703
|
-
},
|
|
3704
|
-
image: {
|
|
3705
|
-
type: "string",
|
|
3706
|
-
description: "Your own runner image for the VMs (default: GitHub's, with everyday tools)"
|
|
3707
|
-
},
|
|
3708
|
-
"local-network": {
|
|
3709
|
-
type: "boolean",
|
|
3710
|
-
description: "Let jobs in VMs reach this Mac and your local network. They can't by default."
|
|
3711
|
-
}
|
|
3712
|
-
},
|
|
3713
|
-
async run({ args }) {
|
|
3714
|
-
clack.intro("RelayRunner");
|
|
3715
|
-
let concurrency;
|
|
3716
|
-
let size;
|
|
3717
|
-
try {
|
|
3718
|
-
size = parseVmSize(args.cpus, args.memory);
|
|
3719
|
-
concurrency = args.concurrency ? parseConcurrency(args.concurrency) : slotsFor(size) ?? parseConcurrency(void 0);
|
|
3720
|
-
checkFits(size, concurrency);
|
|
3721
|
-
} catch (error) {
|
|
3722
|
-
clack.log.error(error.message);
|
|
3723
|
-
process.exitCode = 1;
|
|
3724
|
-
return;
|
|
3725
|
-
}
|
|
3726
|
-
try {
|
|
3727
|
-
await connectMachine({
|
|
3728
|
-
...args,
|
|
3729
|
-
concurrency,
|
|
3730
|
-
size
|
|
3731
|
-
});
|
|
3732
|
-
} catch (error) {
|
|
3733
|
-
if (!(error instanceof LoginError || error instanceof RunnerError)) throw error;
|
|
3734
|
-
clack.log.error(error.message);
|
|
3735
|
-
process.exitCode = 1;
|
|
3736
|
-
}
|
|
3737
|
-
}
|
|
3738
|
-
});
|
|
3739
|
-
async function connectMachine(args) {
|
|
3740
|
-
const share = shareArg(args.share);
|
|
3741
|
-
const vmFlag = [
|
|
3742
|
-
"macos",
|
|
3743
|
-
"image",
|
|
3744
|
-
"local-network"
|
|
3745
|
-
].find((flag) => args[flag]) ?? (args.size.cpus !== void 0 ? "cpus" : args.size.memoryGb !== void 0 ? "memory" : null);
|
|
3746
|
-
if (args.isolated === false && vmFlag) throw new RunnerError("USAGE", `--${vmFlag} doesn't go with --no-isolated.`);
|
|
3747
|
-
const host = machinePlatform();
|
|
3748
|
-
const asked = args.isolated === true || Boolean(vmFlag);
|
|
3749
|
-
const unsupported = asked ? unsupportedReason() : null;
|
|
3750
|
-
if (unsupported) throw new RunnerError("ISOLATED_UNSUPPORTED", unsupported);
|
|
3751
|
-
const state = asked || args.isolated === false ? null : await isolationState();
|
|
3752
|
-
const isolated = asked || state === "ready";
|
|
3753
|
-
const vm = {
|
|
3754
|
-
os: "linux",
|
|
3755
|
-
arch: host.arch
|
|
3756
|
-
};
|
|
3757
|
-
const platform = !isolated ? host : args.macos ? {
|
|
3758
|
-
...host,
|
|
3759
|
-
isolated: vm
|
|
3760
|
-
} : vm;
|
|
3761
|
-
let credentials = readCredentials();
|
|
3762
|
-
const server = serverFor(args.server, credentials);
|
|
3763
|
-
if (credentials && credentials.server !== server) {
|
|
3764
|
-
clack.log.warn(`This machine is enrolled with ${credentials.server}, not ${server}. Signing in again.`);
|
|
3765
|
-
credentials = null;
|
|
3766
|
-
}
|
|
3767
|
-
if (!credentials) credentials = await enroll(server, args.name, platform, share);
|
|
3768
|
-
else {
|
|
3769
|
-
clack.log.info(`Machine ${credentials.machine.name} (${credentials.server})`);
|
|
3770
|
-
if (share) await applySharing(credentials, share, null);
|
|
3771
|
-
}
|
|
3772
|
-
if (process.stdin.isTTY && process.stdout.isTTY) await offerSetup();
|
|
3773
|
-
let updateTimer;
|
|
3774
|
-
if (process.stdout.isTTY && !process.env.CI) {
|
|
3775
|
-
const notifyUpdate = () => void checkForUpdate().then((latest) => {
|
|
3776
|
-
if (latest) clack.log.warn(updateNotice(latest));
|
|
3777
|
-
});
|
|
3778
|
-
notifyUpdate();
|
|
3779
|
-
updateTimer = setInterval(notifyUpdate, CHECK_INTERVAL_MS);
|
|
3780
|
-
updateTimer.unref();
|
|
3781
|
-
}
|
|
3782
|
-
const slots = args.concurrency;
|
|
3783
|
-
const log = (line) => clack.log.info(line);
|
|
3784
|
-
const onHost = !isolated || args.macos ? ensureRunner({ log }) : void 0;
|
|
3785
|
-
onHost?.catch(() => {});
|
|
3786
|
-
let runnerVersion = "";
|
|
3787
|
-
let isolation;
|
|
3788
|
-
let launchers = [];
|
|
3789
|
-
let vmLauncher;
|
|
3790
|
-
let isolatedOnly;
|
|
3791
|
-
let vmSize;
|
|
3792
|
-
const useRunner = (runner) => {
|
|
3793
|
-
launchers = ensureSlots(runner, slots, log).map(hostLauncher);
|
|
3794
|
-
runnerVersion = runner.version;
|
|
3795
|
-
};
|
|
3796
|
-
const useIsolation = (next) => {
|
|
3797
|
-
const launcher = isolatedLauncher(next);
|
|
3798
|
-
if (args.macos) vmLauncher = launcher;
|
|
3799
|
-
else {
|
|
3800
|
-
launchers = Array.from({ length: slots }, () => isolatedOnly = launcher);
|
|
3801
|
-
runnerVersion = next.runnerVersion;
|
|
3802
|
-
}
|
|
3803
|
-
};
|
|
3804
|
-
const firewall = isolated && firewallInstalled();
|
|
3805
|
-
const isolationOptions = {
|
|
3806
|
-
slots,
|
|
3807
|
-
size: args.size,
|
|
3808
|
-
image: args.image,
|
|
3809
|
-
localNetwork: args["local-network"] && !firewall,
|
|
3810
|
-
log,
|
|
3811
|
-
debug: isolated ? debugLog() : void 0
|
|
3812
|
-
};
|
|
3813
|
-
if (isolated) {
|
|
3814
|
-
if (firewall) log(args["local-network"] ? "The firewall on this Mac is on, so --local-network has no effect. Turn it off with `relayrunner firewall off`." : "The firewall on this Mac is on.");
|
|
3815
|
-
isolation = await prepareIsolation(isolationOptions);
|
|
3816
|
-
useIsolation(isolation);
|
|
3817
|
-
vmSize = {
|
|
3818
|
-
cpus: isolation.cpus,
|
|
3819
|
-
memoryGb: isolation.memoryGb
|
|
3820
|
-
};
|
|
3821
|
-
log(`Each job runs in its own Linux VM with ${vmSize.cpus} CPUs and ${vmSize.memoryGb} GB of memory.`);
|
|
3822
|
-
if (isolation.localNetwork) log("Jobs can reach this Mac and your local network.");
|
|
3823
|
-
if (isolation.debug.path) log(`If something goes wrong, ${isolation.debug.path} has the details.`);
|
|
3824
|
-
if (!args.macos) log("Jobs run in a Linux VM on this Mac. To take macOS jobs too, run `relayrunner connect --macos`.");
|
|
3825
|
-
}
|
|
3826
|
-
if (onHost) {
|
|
3827
|
-
useRunner(await onHost);
|
|
3828
|
-
const hint = !isolated && state ? setupHint(state) : null;
|
|
3829
|
-
if (hint) clack.log.warn(hint);
|
|
3830
|
-
if (args.macos) clack.log.warn("Linux jobs run in a VM. macOS jobs run on this Mac itself, where they can read your files. Only take macOS jobs from repos you trust.");
|
|
3831
|
-
else if (args.isolated === false) clack.log.warn("Jobs run on this machine itself, where they can read your files. Only take jobs from repos you trust.");
|
|
3832
|
-
}
|
|
3833
|
-
clack.log.info(slots === 1 ? "Running 1 job at a time. Change with --concurrency." : `Running up to ${slots} jobs at once. Change with --concurrency.`);
|
|
3834
|
-
const device = await detectDevice();
|
|
3835
|
-
let running = 0;
|
|
3836
|
-
const stopUpdating = onHost || isolation && !args.image ? keepRunnerUpdated({
|
|
3837
|
-
current: () => runnerVersion,
|
|
3838
|
-
running: () => running,
|
|
3839
|
-
log,
|
|
3840
|
-
update: async (version) => {
|
|
3841
|
-
const [vm, runner] = await Promise.all([isolation && !args.image && prepareIsolation({
|
|
3842
|
-
...isolationOptions,
|
|
3843
|
-
runnerVersion: version,
|
|
3844
|
-
keep: [isolation.base, isolation.image]
|
|
3845
|
-
}), onHost && ensureRunner({ log })]);
|
|
3846
|
-
if (vm) useIsolation(isolation = vm);
|
|
3847
|
-
if (runner) useRunner(runner);
|
|
3848
|
-
}
|
|
3849
|
-
}) : void 0;
|
|
3850
|
-
const stop = new AbortController();
|
|
3851
|
-
const enrolled = credentials;
|
|
3852
|
-
let toggling = false;
|
|
3853
|
-
const live = startLive({
|
|
3854
|
-
machine: enrolled.machine.name,
|
|
3855
|
-
onTogglePause: async ({ paused }) => {
|
|
3856
|
-
if (toggling || stop.signal.aborted) return;
|
|
3857
|
-
toggling = true;
|
|
3858
|
-
const result = await pauseMachine(enrolled, !paused);
|
|
3859
|
-
toggling = false;
|
|
3860
|
-
if (result.status === "failed") clack.log.error(`Couldn't ${paused ? "resume" : "pause"}: ${result.reason}.`);
|
|
3861
|
-
}
|
|
3862
|
-
});
|
|
3863
|
-
const onInterrupt = () => {
|
|
3864
|
-
if (stop.signal.aborted) {
|
|
3865
|
-
live.end();
|
|
3866
|
-
process.exit(130);
|
|
3867
|
-
}
|
|
3868
|
-
stop.abort();
|
|
3869
|
-
};
|
|
3870
|
-
process.on("SIGINT", onInterrupt);
|
|
3871
|
-
let online = false;
|
|
3872
|
-
let end;
|
|
3873
|
-
try {
|
|
3874
|
-
end = await connect({
|
|
3875
|
-
server: credentials.server,
|
|
3876
|
-
token: credentials.token,
|
|
3877
|
-
hello: {
|
|
3878
|
-
machineId: credentials.machine.id,
|
|
3879
|
-
...platform,
|
|
3880
|
-
runnerVersion,
|
|
3881
|
-
cliVersion,
|
|
3882
|
-
device,
|
|
3883
|
-
...vmSize && { vm: vmSize }
|
|
3884
|
-
},
|
|
3885
|
-
runnerVersion: () => runnerVersion,
|
|
3886
|
-
slots,
|
|
3887
|
-
runJob: async (run, slot, report) => {
|
|
3888
|
-
const prefixed = slots > 1 ? prefixLines(`[slot ${slot}] `, (chunk, stream) => (stream === "stdout" ? process.stdout : process.stderr).write(chunk)) : void 0;
|
|
3889
|
-
const launcher = run.isolated ? vmLauncher ?? isolatedOnly : launchers[slot - 1];
|
|
3890
|
-
if (!launcher) {
|
|
3891
|
-
const update = {
|
|
3892
|
-
routeId: run.routeId,
|
|
3893
|
-
state: "failed",
|
|
3894
|
-
message: "The job was sent for a VM, and this machine isn't running jobs in one."
|
|
3895
|
-
};
|
|
3896
|
-
report(update);
|
|
3897
|
-
return update;
|
|
3898
|
-
}
|
|
3899
|
-
running++;
|
|
3900
|
-
try {
|
|
3901
|
-
return await runJob(run, {
|
|
3902
|
-
launcher,
|
|
3903
|
-
report,
|
|
3904
|
-
output: prefixed?.output,
|
|
3905
|
-
onChecked: (target) => {
|
|
3906
|
-
if (target) clack.log.info(`${(/* @__PURE__ */ new Date()).toLocaleTimeString()} Job ${run.routeId}${slots > 1 ? ` (slot ${slot})` : ""} is from ${target}`);
|
|
3907
|
-
}
|
|
3908
|
-
});
|
|
3909
|
-
} finally {
|
|
3910
|
-
running--;
|
|
3911
|
-
prefixed?.flush();
|
|
3912
|
-
}
|
|
3913
|
-
},
|
|
3914
|
-
saveToken: (token) => saveRotatedToken(credentials, token),
|
|
3915
|
-
onEvent: (event) => {
|
|
3916
|
-
if (event.type === "connected") online = true;
|
|
3917
|
-
show(event, slots > 1);
|
|
3918
|
-
live.onEvent(event);
|
|
3919
|
-
},
|
|
3920
|
-
signal: stop.signal
|
|
3921
|
-
});
|
|
3922
|
-
} finally {
|
|
3923
|
-
clearInterval(updateTimer);
|
|
3924
|
-
stopUpdating?.();
|
|
3925
|
-
live.end();
|
|
3926
|
-
process.off("SIGINT", onInterrupt);
|
|
3927
|
-
}
|
|
3928
|
-
switch (end.reason) {
|
|
3929
|
-
case "stopped":
|
|
3930
|
-
clack.outro("Offline.");
|
|
3931
|
-
break;
|
|
3932
|
-
case "revoked":
|
|
3933
|
-
deleteCredentials();
|
|
3934
|
-
if (!online) {
|
|
3935
|
-
clack.log.warn("This machine was removed or its token is no longer valid. If you didn't remove it, another copy of its token may have signed in elsewhere: check the Runners page. Signing in again.");
|
|
3936
|
-
return connectMachine({
|
|
3937
|
-
...args,
|
|
3938
|
-
server: credentials.server
|
|
3939
|
-
});
|
|
3940
|
-
}
|
|
3941
|
-
clack.log.error("This machine was removed or its token is no longer valid. If you didn't remove it, another copy of its token may have signed in elsewhere: check the Runners page and revoke it if so.");
|
|
3942
|
-
clack.outro("Run `relayrunner connect` again to sign in.");
|
|
3943
|
-
process.exitCode = 1;
|
|
3944
|
-
break;
|
|
3945
|
-
case "replaced":
|
|
3946
|
-
clack.log.warn(["Another `relayrunner connect` signed in as this machine and took over.", `If that wasn't you, someone has this machine's token: revoke it at ${credentials.server}/runners, then run \`relayrunner connect\` to sign in again.`].join("\n"));
|
|
3947
|
-
clack.outro("Offline here.");
|
|
3948
|
-
process.exitCode = 1;
|
|
3949
|
-
break;
|
|
3950
|
-
case "rejected":
|
|
3951
|
-
clack.log.error(`The gateway rejected this CLI: ${end.message}`);
|
|
3952
|
-
clack.outro("Update it with `npx relayrunner@latest connect`.");
|
|
3953
|
-
process.exitCode = 1;
|
|
3954
|
-
}
|
|
3955
|
-
}
|
|
3956
|
-
async function askSharing(workspaces) {
|
|
3957
|
-
const picked = await clack.select({
|
|
3958
|
-
message: "Who can run jobs on this machine?",
|
|
3959
|
-
options: [{
|
|
3960
|
-
value: "only-me",
|
|
3961
|
-
label: "Only me",
|
|
3962
|
-
hint: "jobs you started"
|
|
3963
|
-
}, {
|
|
3964
|
-
value: "anyone",
|
|
3965
|
-
label: `Anyone in ${sharingScope(workspaces)}`,
|
|
3966
|
-
hint: "teammates' and bots' jobs too, from repos you can open"
|
|
3967
|
-
}],
|
|
3968
|
-
initialValue: "only-me"
|
|
3969
|
-
});
|
|
3970
|
-
if (clack.isCancel(picked)) {
|
|
3971
|
-
clack.log.info("Keeping only-me. Change it any time with `relayrunner share`.");
|
|
3972
|
-
return null;
|
|
3973
|
-
}
|
|
3974
|
-
return picked;
|
|
3975
|
-
}
|
|
3976
|
-
async function applySharing(credentials, choice, workspaces) {
|
|
3977
|
-
const result = await withCurrentToken(credentials, (token) => setSharing({
|
|
3978
|
-
server: credentials.server,
|
|
3979
|
-
token,
|
|
3980
|
-
sharing: toSharing(choice)
|
|
3981
|
-
}));
|
|
3982
|
-
switch (result.status) {
|
|
3983
|
-
case "ok":
|
|
3984
|
-
clack.log.info(`Sharing: ${describeSharing(result.sharing, workspaces ? sharingScope(workspaces) : void 0)}`);
|
|
3985
|
-
break;
|
|
3986
|
-
case "revoked": break;
|
|
3987
|
-
case "failed": clack.log.warn(`Couldn't set sharing: ${result.reason}. Run \`relayrunner share ${choice}\` to try again.`);
|
|
3988
|
-
}
|
|
3989
|
-
}
|
|
3990
|
-
const loginCommand = defineCommand({
|
|
3991
|
-
meta: {
|
|
3992
|
-
name: "login",
|
|
3993
|
-
description: "Sign this machine in without putting it online. You pick its workspaces when you approve it. Run `relayrunner connect` afterwards to take jobs."
|
|
3994
|
-
},
|
|
3995
|
-
args: {
|
|
3996
|
-
server: {
|
|
3997
|
-
type: "string",
|
|
3998
|
-
description: `RelayRunner URL (default: $RELAYRUNNER_URL or ${DEFAULT_SERVER})`
|
|
3999
|
-
},
|
|
4000
|
-
name: {
|
|
4001
|
-
type: "string",
|
|
4002
|
-
description: "Suggested machine name (default: this computer's name)"
|
|
4003
|
-
},
|
|
4004
|
-
share: {
|
|
4005
|
-
type: "string",
|
|
4006
|
-
description: "Who can run jobs on this machine: only-me (jobs you started) or anyone in your workspaces. Skips the question."
|
|
4007
|
-
}
|
|
4008
|
-
},
|
|
4009
|
-
async run({ args }) {
|
|
4010
|
-
clack.intro("RelayRunner");
|
|
4011
|
-
try {
|
|
4012
|
-
const share = shareArg(args.share);
|
|
4013
|
-
const saved = readCredentials();
|
|
4014
|
-
const server = serverFor(args.server, saved);
|
|
4015
|
-
if (saved && saved.server === server) {
|
|
4016
|
-
const result = await withCurrentToken(saved, (token) => whoami({
|
|
4017
|
-
server,
|
|
4018
|
-
token
|
|
4019
|
-
}));
|
|
4020
|
-
if (result.status !== "revoked") {
|
|
4021
|
-
const workspaces = result.status === "ok" ? readWorkspaces(result.identity) : null;
|
|
4022
|
-
if (share) await applySharing(saved, share, workspaces);
|
|
4023
|
-
const where = workspaces?.length ? ` in ${workspaceNames(workspaces)}` : "";
|
|
4024
|
-
clack.outro(`Already signed in as ${saved.machine.name}${where}. Run \`relayrunner connect\` to go online.`);
|
|
4025
|
-
return;
|
|
4026
|
-
}
|
|
4027
|
-
clack.log.warn(`${saved.machine.name} is no longer signed in. Signing in again.`);
|
|
4028
|
-
} else if (saved) clack.log.warn(`This machine is enrolled with ${saved.server}, not ${server}. Signing in again.`);
|
|
4029
|
-
await enroll(server, args.name, machinePlatform(), share);
|
|
4030
|
-
clack.outro("Run `relayrunner connect` to put this machine online.");
|
|
4031
|
-
} catch (error) {
|
|
4032
|
-
if (!(error instanceof LoginError || error instanceof RunnerError)) throw error;
|
|
4033
|
-
clack.log.error(error.message);
|
|
4034
|
-
process.exitCode = 1;
|
|
4035
|
-
}
|
|
4036
|
-
}
|
|
4037
|
-
});
|
|
4038
|
-
function shareArg(value) {
|
|
4039
|
-
const share = value ? parseShareChoice(value) : null;
|
|
4040
|
-
if (value && !share) throw new RunnerError("USAGE", `--share takes ${SHARE_CHOICES.join(" or ")}, not ${JSON.stringify(value)}.`);
|
|
4041
|
-
return share;
|
|
4042
|
-
}
|
|
4043
|
-
/** An explicit --server or RELAYRUNNER_URL wins; otherwise the gateway this machine enrolled with. */
|
|
4044
|
-
function serverFor(requested, saved) {
|
|
4045
|
-
return normalizeServer(requested || process.env.RELAYRUNNER_URL || saved?.server || DEFAULT_SERVER);
|
|
4046
|
-
}
|
|
4047
|
-
function machinePlatform() {
|
|
4048
|
-
const target = runnerPlatform();
|
|
4049
|
-
return {
|
|
4050
|
-
os: target.os === "osx" ? "macos" : "linux",
|
|
4051
|
-
arch: target.arch
|
|
4052
|
-
};
|
|
4053
|
-
}
|
|
4054
|
-
/** Signs in through the browser, saves the machine token, and settles who can run jobs here. */
|
|
4055
|
-
async function enroll(server, name, platform, share) {
|
|
4056
|
-
const { credentials, workspaces } = await signIn(server, name || await defaultMachineName(), platform);
|
|
4057
|
-
writeCredentials(credentials);
|
|
4058
|
-
clack.log.success(`Enrolled as ${credentials.machine.name}. Token saved to ${credentialsPath()}.`);
|
|
4059
|
-
if (workspaces.length) clack.log.info(`Runs jobs in ${workspaceNames(workspaces)}.\nChange with: relayrunner workspaces`);
|
|
4060
|
-
else clack.log.warn(await emptyWorkspacesNotice(credentials));
|
|
4061
|
-
let choice = share;
|
|
4062
|
-
if (!choice && hasTeammates(workspaces)) {
|
|
4063
|
-
if (process.stdin.isTTY && process.stdout.isTTY) choice = await askSharing(workspaces);
|
|
4064
|
-
else clack.log.info("Only jobs you started run here. `relayrunner share anyone` lets teammates' jobs run here too.");
|
|
4065
|
-
}
|
|
4066
|
-
if (choice) await applySharing(credentials, choice, workspaces);
|
|
4067
|
-
return credentials;
|
|
4068
|
-
}
|
|
4069
|
-
async function signIn(server, name, platform) {
|
|
4070
|
-
const waiting = clack.spinner();
|
|
4071
|
-
try {
|
|
4072
|
-
const credentials = await login({
|
|
4073
|
-
server,
|
|
4074
|
-
name,
|
|
4075
|
-
platform,
|
|
4076
|
-
onCode: ({ userCode, url }) => {
|
|
4077
|
-
clack.note(`${url}\n\nConfirm the code ${userCode} matches the one in your browser.`, "Sign in");
|
|
4078
|
-
openBrowser(url);
|
|
4079
|
-
waiting.start("Waiting for approval in the browser");
|
|
4080
|
-
}
|
|
4081
|
-
});
|
|
4082
|
-
waiting.stop("Approved");
|
|
4083
|
-
return credentials;
|
|
4084
|
-
} catch (error) {
|
|
4085
|
-
waiting.error("Sign-in failed");
|
|
4086
|
-
throw error;
|
|
4087
|
-
}
|
|
4088
|
-
}
|
|
4089
|
-
function show(event, slotted) {
|
|
4090
|
-
const at = (/* @__PURE__ */ new Date()).toLocaleTimeString();
|
|
4091
|
-
switch (event.type) {
|
|
4092
|
-
case "connecting":
|
|
4093
|
-
if (event.attempt === 1) clack.log.step(`${at} Connecting…`);
|
|
4094
|
-
break;
|
|
4095
|
-
case "connected":
|
|
4096
|
-
clack.log.success(`${at} Online. Waiting for jobs.`);
|
|
4097
|
-
break;
|
|
4098
|
-
case "disconnected":
|
|
4099
|
-
clack.log.warn(`${at} Disconnected (${event.code}${event.reason ? ` ${event.reason}` : ""}). Retrying in ${Math.ceil(event.retryInMs / 1e3)}s.`);
|
|
4100
|
-
break;
|
|
4101
|
-
case "gateway-error":
|
|
4102
|
-
clack.log.error(`${at} Gateway: ${event.message}`);
|
|
4103
|
-
break;
|
|
4104
|
-
case "run":
|
|
4105
|
-
clack.log.step(`${at} Starting job ${event.routeId}${slotted ? ` in slot ${event.slot}` : ""}`);
|
|
4106
|
-
break;
|
|
4107
|
-
case "paused":
|
|
4108
|
-
if (event.paused) clack.log.warn(`${at} Paused${event.by ? ` by ${event.by}` : ""}. Staying online, but new jobs skip this machine until it's resumed.${process.stdin.isTTY ? " Press p to resume." : ""}`);
|
|
4109
|
-
else clack.log.success(`${at} Resumed${event.by ? ` by ${event.by}` : ""}. Waiting for jobs.`);
|
|
4110
|
-
break;
|
|
4111
|
-
case "token-not-saved":
|
|
4112
|
-
clack.log.warn(`${at} Couldn't save the machine's new token (${event.message}). Keeping the old one.`);
|
|
4113
|
-
break;
|
|
4114
|
-
case "run-refused":
|
|
4115
|
-
clack.log.warn(`${at} Turned down job ${event.routeId}: already running ${event.running === 1 ? "one" : `${event.running}`}.`);
|
|
4116
|
-
break;
|
|
4117
|
-
case "job": {
|
|
4118
|
-
const { routeId, state, message } = event.update;
|
|
4119
|
-
const line = `${at} Job ${routeId}${slotted ? ` (slot ${event.slot})` : ""} ${state}${message ? `: ${message}` : ""}`;
|
|
4120
|
-
if (state === "failed") clack.log.error(line);
|
|
4121
|
-
else if (state === "finished") clack.log.success(line);
|
|
4122
|
-
else clack.log.info(line);
|
|
4123
|
-
break;
|
|
4124
|
-
}
|
|
4125
|
-
}
|
|
4126
|
-
}
|
|
4127
|
-
const whoamiCommand = defineCommand({
|
|
4128
|
-
meta: {
|
|
4129
|
-
name: "whoami",
|
|
4130
|
-
description: "Show which machine this computer is signed in as and the workspaces it's in, checked with the gateway."
|
|
4131
|
-
},
|
|
4132
|
-
args: {
|
|
4133
|
-
server: {
|
|
4134
|
-
type: "string",
|
|
4135
|
-
description: "Only report a sign-in for this RelayRunner URL (default: the saved one)"
|
|
4136
|
-
},
|
|
4137
|
-
json: {
|
|
4138
|
-
type: "boolean",
|
|
4139
|
-
description: "Print the result as JSON"
|
|
4140
|
-
}
|
|
4141
|
-
},
|
|
4142
|
-
async run({ args }) {
|
|
4143
|
-
const print = (human, json) => console.log(args.json ? JSON.stringify(json, null, 2) : human);
|
|
4144
|
-
const credentials = readCredentials();
|
|
4145
|
-
const requested = args.server || process.env.RELAYRUNNER_URL;
|
|
4146
|
-
const server = requested ? normalizeServer(requested) : credentials?.server;
|
|
4147
|
-
if (!credentials || credentials.server !== server) {
|
|
4148
|
-
print(credentials ? `Not signed in to ${server}. This machine is enrolled with ${credentials.server}.` : "Not signed in. Run `relayrunner login` or `relayrunner connect` to sign in.", {
|
|
4149
|
-
status: "signed_out",
|
|
4150
|
-
server: server ?? null
|
|
4151
|
-
});
|
|
4152
|
-
process.exitCode = 1;
|
|
4153
|
-
return;
|
|
4154
|
-
}
|
|
4155
|
-
const saved = {
|
|
4156
|
-
server: credentials.server,
|
|
4157
|
-
machine: credentials.machine
|
|
4158
|
-
};
|
|
4159
|
-
const result = await withCurrentToken(credentials, (token) => whoami({
|
|
4160
|
-
server: credentials.server,
|
|
4161
|
-
token
|
|
4162
|
-
}));
|
|
4163
|
-
switch (result.status) {
|
|
4164
|
-
case "ok":
|
|
4165
|
-
print(describeIdentity(credentials.server, result.identity, !args.json && !readWorkspaces(result.identity).length ? await emptyWorkspacesNotice(credentials) : void 0), {
|
|
4166
|
-
status: "ok",
|
|
4167
|
-
server: credentials.server,
|
|
4168
|
-
...result.identity
|
|
4169
|
-
});
|
|
4170
|
-
break;
|
|
4171
|
-
case "revoked":
|
|
4172
|
-
print(`${credentials.machine.name} was removed or its token is no longer valid.\nRun \`relayrunner connect\` to sign in again.`, {
|
|
4173
|
-
status: "revoked",
|
|
4174
|
-
...saved
|
|
4175
|
-
});
|
|
4176
|
-
process.exitCode = 1;
|
|
4177
|
-
break;
|
|
4178
|
-
case "unverified": print(`${describeSaved(saved)}\n\nUnverified: ${result.reason}. This is what's saved in ${credentialsPath()}.`, {
|
|
4179
|
-
status: "unverified",
|
|
4180
|
-
reason: result.reason,
|
|
4181
|
-
...saved
|
|
4182
|
-
});
|
|
4183
|
-
}
|
|
4184
|
-
}
|
|
4185
|
-
});
|
|
4186
|
-
function describeIdentity(server, identity, emptyNotice) {
|
|
4187
|
-
const { machine, enrolledBy } = identity;
|
|
4188
|
-
const workspaces = readWorkspaces(identity);
|
|
4189
|
-
const status = (machine.status.online ? `online${machine.status.state ? `, ${machine.status.state}` : ""}` : "offline") + (machine.paused ? `, paused${machine.paused.by ? ` by ${machine.paused.by}` : ""}` : "");
|
|
4190
|
-
const enrolled = [enrolledBy && `by ${enrolledBy.name} <${enrolledBy.email}>`, `on ${new Date(machine.createdAt).toLocaleDateString()}`].filter(Boolean).join(" ");
|
|
4191
|
-
const details = table(`${machine.name} (${machine.id})`, [
|
|
4192
|
-
["Workspaces", workspaces.length ? workspaceNames(workspaces) : "none"],
|
|
4193
|
-
["Platform", [machine.os, machine.arch].filter(Boolean).join(" ") || "unknown"],
|
|
4194
|
-
["Enrolled", enrolled],
|
|
4195
|
-
["Status", status],
|
|
4196
|
-
...machine.sharing ? [["Sharing", describeSharing(machine.sharing, sharingScope(workspaces))]] : [],
|
|
4197
|
-
["Gateway", server]
|
|
4198
|
-
]);
|
|
4199
|
-
return emptyNotice ? `${details}\n\n${emptyNotice}` : details;
|
|
4200
|
-
}
|
|
4201
|
-
function describeSaved(saved) {
|
|
4202
|
-
return table(`${saved.machine.name} (${saved.machine.id})`, [["Gateway", saved.server]]);
|
|
4203
|
-
}
|
|
4204
|
-
function table(title, rows) {
|
|
4205
|
-
const width = Math.max(...rows.map(([label]) => label.length));
|
|
4206
|
-
return [title, ...rows.map(([label, value]) => ` ${label.padEnd(width)} ${value}`)].join("\n");
|
|
4207
|
-
}
|
|
4208
|
-
function pauseCommand(paused) {
|
|
4209
|
-
return defineCommand({
|
|
4210
|
-
meta: {
|
|
4211
|
-
name: paused ? "pause" : "resume",
|
|
4212
|
-
description: paused ? "Stop new jobs routing to this machine. It stays connected and finishes a job it's running." : "Let jobs route to this machine again after `relayrunner pause`."
|
|
4213
|
-
},
|
|
4214
|
-
async run() {
|
|
4215
|
-
const credentials = readCredentials();
|
|
4216
|
-
if (!credentials) {
|
|
4217
|
-
console.error("Not signed in. Run `relayrunner login` or `relayrunner connect` to sign in.");
|
|
4218
|
-
process.exitCode = 1;
|
|
4219
|
-
return;
|
|
4220
|
-
}
|
|
4221
|
-
const result = await pauseMachine(credentials, paused);
|
|
4222
|
-
const name = credentials.machine.name;
|
|
4223
|
-
switch (result.status) {
|
|
4224
|
-
case "ok":
|
|
4225
|
-
console.log(paused ? `Paused ${name}. It stays connected, and new jobs will skip it.${result.busy ? "\nIt finishes the job it's running first." : ""}\nRun \`relayrunner resume\` to take jobs again.` : `Resumed ${name}. Jobs can route here again.`);
|
|
4226
|
-
break;
|
|
4227
|
-
case "revoked":
|
|
4228
|
-
console.error(`${name} was removed or its token is no longer valid.\nRun \`relayrunner connect\` to sign in again.`);
|
|
4229
|
-
process.exitCode = 1;
|
|
4230
|
-
break;
|
|
4231
|
-
case "failed":
|
|
4232
|
-
console.error(`Couldn't ${paused ? "pause" : "resume"} ${name}: ${result.reason}.`);
|
|
4233
|
-
process.exitCode = 1;
|
|
4234
|
-
}
|
|
4235
|
-
}
|
|
4236
|
-
});
|
|
4237
|
-
}
|
|
4238
|
-
const shareCommand = defineCommand({
|
|
4239
|
-
meta: {
|
|
4240
|
-
name: "share",
|
|
4241
|
-
description: "Show or change who can run jobs on this machine: only-me (jobs you started) or anyone in your workspaces."
|
|
4242
|
-
},
|
|
4243
|
-
args: { who: {
|
|
4244
|
-
type: "positional",
|
|
4245
|
-
required: false,
|
|
4246
|
-
description: `${SHARE_CHOICES.join(" or ")}; leave out to show the current setting`
|
|
4247
|
-
} },
|
|
4248
|
-
async run({ args }) {
|
|
4249
|
-
const credentials = readCredentials();
|
|
4250
|
-
if (!credentials) {
|
|
4251
|
-
console.error("Not signed in. Run `relayrunner login` or `relayrunner connect` to sign in.");
|
|
4252
|
-
process.exitCode = 1;
|
|
4253
|
-
return;
|
|
4254
|
-
}
|
|
4255
|
-
const { name } = credentials.machine;
|
|
4256
|
-
const revoked = () => {
|
|
4257
|
-
console.error(`${name} was removed or its token is no longer valid.\nRun \`relayrunner connect\` to sign in again.`);
|
|
4258
|
-
process.exitCode = 1;
|
|
4259
|
-
};
|
|
4260
|
-
if (args.who) {
|
|
4261
|
-
const choice = parseShareChoice(args.who);
|
|
4262
|
-
if (!choice) {
|
|
4263
|
-
console.error(`Use \`relayrunner share ${SHARE_CHOICES.join("` or `relayrunner share ")}\`.`);
|
|
4264
|
-
process.exitCode = 1;
|
|
4265
|
-
return;
|
|
4266
|
-
}
|
|
4267
|
-
const result = await withCurrentToken(credentials, (token) => setSharing({
|
|
4268
|
-
server: credentials.server,
|
|
4269
|
-
token,
|
|
4270
|
-
sharing: toSharing(choice)
|
|
4271
|
-
}));
|
|
4272
|
-
if (result.status === "revoked") return revoked();
|
|
4273
|
-
if (result.status === "failed") {
|
|
4274
|
-
console.error(`Couldn't change sharing for ${name}: ${result.reason}.`);
|
|
4275
|
-
process.exitCode = 1;
|
|
4276
|
-
return;
|
|
4277
|
-
}
|
|
4278
|
-
console.log(`${name} now ${sharingMeaning(result.sharing)}.`);
|
|
4279
|
-
return;
|
|
4280
|
-
}
|
|
4281
|
-
const result = await withCurrentToken(credentials, (token) => whoami({
|
|
4282
|
-
server: credentials.server,
|
|
4283
|
-
token
|
|
4284
|
-
}));
|
|
4285
|
-
if (result.status === "revoked") return revoked();
|
|
4286
|
-
if (result.status === "unverified") {
|
|
4287
|
-
console.error(`Couldn't check sharing for ${name}: ${result.reason}.`);
|
|
4288
|
-
process.exitCode = 1;
|
|
4289
|
-
return;
|
|
4290
|
-
}
|
|
4291
|
-
const { sharing } = result.identity.machine;
|
|
4292
|
-
if (!sharing) {
|
|
4293
|
-
console.error(`${credentials.server} doesn't support sharing yet.`);
|
|
4294
|
-
process.exitCode = 1;
|
|
4295
|
-
return;
|
|
4296
|
-
}
|
|
4297
|
-
const other = sharing === "only_me" ? "anyone" : "only-me";
|
|
4298
|
-
const workspaces = readWorkspaces(result.identity);
|
|
4299
|
-
const lines = [`${name} ${sharingMeaning(sharing, sharingScope(workspaces))} (${toChoice(sharing)}).`];
|
|
4300
|
-
if (!workspaces.length) lines.push(`${name} isn't in a workspace yet, so this matters once it is.`);
|
|
4301
|
-
else if (workspaces.every((workspace) => workspace.memberCount === 1)) lines.push(`Nobody else is in ${sharingScope(workspaces)} yet, so this matters once a teammate joins.`);
|
|
4302
|
-
lines.push(`Change it with \`relayrunner share ${other}\`.`);
|
|
4303
|
-
console.log(lines.join("\n"));
|
|
4304
|
-
}
|
|
4305
|
-
});
|
|
4306
|
-
const main = defineCommand({
|
|
4307
|
-
meta: {
|
|
4308
|
-
name: "relayrunner",
|
|
4309
|
-
version: cliVersion,
|
|
4310
|
-
description: "Run GitHub Actions jobs on your machine through the RelayRunner gateway."
|
|
4311
|
-
},
|
|
4312
|
-
subCommands: {
|
|
4313
|
-
connect: connectCommand,
|
|
4314
|
-
login: loginCommand,
|
|
4315
|
-
whoami: whoamiCommand,
|
|
4316
|
-
init: initCommand,
|
|
4317
|
-
pause: pauseCommand(true),
|
|
4318
|
-
resume: pauseCommand(false),
|
|
4319
|
-
share: shareCommand,
|
|
4320
|
-
workspaces: workspacesCommand,
|
|
4321
|
-
firewall: firewallCommand
|
|
4322
|
-
}
|
|
4323
|
-
});
|
|
4324
|
-
runMain(main);
|
|
4325
|
-
export {};
|