hammerkit 2.1.0-next.11 → 2.1.0-next.13
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/dist/executer/archive-task-entry.js +1 -1
- package/dist/executer/deadline.js +63 -10
- package/dist/executer/event-cache.js +5 -1
- package/dist/executer/execute-work-task.js +15 -3
- package/dist/file/get-file-context.js +4 -7
- package/dist/harness/connect.js +10 -7
- package/dist/harness/reconnect.js +137 -0
- package/dist/harness/sandbox-client.js +117 -25
- package/dist/kubernetes/cluster-state.js +48 -14
- package/dist/kubernetes/ensure-persistent-data.js +14 -3
- package/dist/kubernetes/resources.js +5 -1
- package/dist/kubernetes/store-kubernetes-data.js +18 -3
- package/dist/planner/work-runtime-aggregate.js +1 -0
- package/dist/planner/work-runtime-docker.js +9 -5
- package/dist/planner/work-runtime-kubernetes.js +6 -4
- package/dist/planner/work-runtime-local.js +8 -4
- package/dist/remote/annotations.js +29 -3
- package/dist/remote/bundle.js +2 -6
- package/dist/remote/collect-bundle.js +3 -2
- package/dist/remote/remote-work-commands.js +179 -15
- package/dist/server/artifacts-api.js +56 -0
- package/dist/server/executor.js +17 -0
- package/dist/server/http.js +4 -1
- package/dist/server/keep-artifacts.js +230 -0
- package/dist/server/run-access.js +24 -0
- package/dist/server/run-artifacts.js +171 -0
- package/dist/server/run-worker.js +29 -0
- package/dist/server/runs.js +18 -2
- package/dist/server/sandbox-files.js +2 -7
- package/dist/server/server-config.js +14 -0
- package/dist/server/server.js +49 -15
- package/dist/utils/project-path.js +20 -0
- package/dist/utils/tar.js +37 -1
- package/package.json +1 -1
|
@@ -16,7 +16,7 @@ stateKey = work.state.current.stateKey) {
|
|
|
16
16
|
const cacheDir = (0, get_cache_directory_1.getCacheDirectory)((0, work_instance_id_1.getWorkInstanceId)(work));
|
|
17
17
|
const { stats } = await (0, get_work_cache_stats_1.getWorkItemCacheStats)(work, environment);
|
|
18
18
|
await (0, cache_metadata_1.writeCacheMetadata)(environment, work, stats, (0, work_task_cache_description_1.getWorkTaskCacheDescription)(work));
|
|
19
|
-
await work.runtime.archive(environment, cacheDir, stateKey ?? undefined);
|
|
19
|
+
await work.runtime.archive(environment, cacheDir, { stateKey: stateKey ?? undefined });
|
|
20
20
|
return cacheDir;
|
|
21
21
|
}
|
|
22
22
|
exports.archiveTaskEntry = archiveTaskEntry;
|
|
@@ -18,23 +18,76 @@ const MAX_TIMER_MS = 2 ** 31 - 1;
|
|
|
18
18
|
// An abort signal that follows `parent` and additionally fires after `timeout`
|
|
19
19
|
// ms, so a task deadline reuses the runtimes' existing abort/cleanup path. A
|
|
20
20
|
// timeout beyond what a timer can wait (about 24.8 days) sets no deadline.
|
|
21
|
+
// `pause` stops the clock and `resume` starts it again with what was left, so a
|
|
22
|
+
// wait that is not the task's to count (its pod refused by the quota) does not use it.
|
|
23
|
+
// The pauses together may last `timeout` as well: then it fires and `waitedOut` says so.
|
|
21
24
|
function withDeadline(parent, timeout) {
|
|
22
25
|
const controller = new AbortController();
|
|
23
|
-
let expired = false;
|
|
24
26
|
const parentListener = (0, abort_event_1.listenOnAbort)(parent, () => controller.abort());
|
|
25
|
-
const
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
27
|
+
const limit = timeout !== null && timeout <= MAX_TIMER_MS ? timeout : null;
|
|
28
|
+
// what is left of the time to run, and of the time to wait in pauses
|
|
29
|
+
let left = limit ?? 0;
|
|
30
|
+
let pauseLeft = limit ?? 0;
|
|
31
|
+
let paused = false;
|
|
32
|
+
let closed = false;
|
|
33
|
+
let ended = null;
|
|
34
|
+
let since = performance.now();
|
|
35
|
+
let timer = null;
|
|
36
|
+
// ends the current stretch: what it took comes off its budget
|
|
37
|
+
const stopClock = () => {
|
|
38
|
+
if (timer) {
|
|
39
|
+
clearTimeout(timer);
|
|
40
|
+
timer = null;
|
|
41
|
+
}
|
|
42
|
+
if (limit === null || ended) {
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
const took = performance.now() - since;
|
|
46
|
+
if (paused) {
|
|
47
|
+
pauseLeft = Math.min(limit, Math.max(0, pauseLeft - took));
|
|
48
|
+
}
|
|
49
|
+
else {
|
|
50
|
+
left = Math.min(limit, Math.max(0, left - took));
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
const startClock = () => {
|
|
54
|
+
since = performance.now();
|
|
55
|
+
if (limit === null || controller.signal.aborted) {
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
const end = paused ? 'waited-out' : 'expired';
|
|
59
|
+
timer = setTimeout(() => {
|
|
60
|
+
timer = null;
|
|
61
|
+
ended = end;
|
|
29
62
|
controller.abort();
|
|
30
|
-
},
|
|
63
|
+
}, paused ? pauseLeft : left);
|
|
64
|
+
};
|
|
65
|
+
startClock();
|
|
31
66
|
return {
|
|
32
67
|
signal: controller.signal,
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
68
|
+
// it ran for its timeout
|
|
69
|
+
expired: () => ended === 'expired',
|
|
70
|
+
// its pauses together lasted its timeout
|
|
71
|
+
waitedOut: () => ended === 'waited-out',
|
|
72
|
+
pause() {
|
|
73
|
+
if (closed || paused || ended) {
|
|
74
|
+
return;
|
|
37
75
|
}
|
|
76
|
+
stopClock();
|
|
77
|
+
paused = true;
|
|
78
|
+
startClock();
|
|
79
|
+
},
|
|
80
|
+
resume() {
|
|
81
|
+
if (closed || !paused || ended) {
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
stopClock();
|
|
85
|
+
paused = false;
|
|
86
|
+
startClock();
|
|
87
|
+
},
|
|
88
|
+
clear() {
|
|
89
|
+
stopClock();
|
|
90
|
+
closed = true;
|
|
38
91
|
parentListener.close();
|
|
39
92
|
},
|
|
40
93
|
};
|
|
@@ -35,7 +35,8 @@ async function restoreCache(environment, path, workTree) {
|
|
|
35
35
|
}
|
|
36
36
|
}
|
|
37
37
|
exports.restoreCache = restoreCache;
|
|
38
|
-
|
|
38
|
+
// `only`: the paths of the outputs to archive of a task, every one when left out
|
|
39
|
+
function* getArchivePaths(task, path, only) {
|
|
39
40
|
if (task.type === 'container-service') {
|
|
40
41
|
for (const volume of task.volumes.filter((v) => !v.inherited)) {
|
|
41
42
|
yield {
|
|
@@ -59,6 +60,9 @@ function* getArchivePaths(task, path) {
|
|
|
59
60
|
}
|
|
60
61
|
}
|
|
61
62
|
for (const { generate, rel } of generates) {
|
|
63
|
+
if (only && !only.includes(generate.path)) {
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
62
66
|
let generateId = rel.split(path_1.posix.sep).join('-');
|
|
63
67
|
if (holders.get(generateId) !== rel) {
|
|
64
68
|
generateId += '-' + (0, crypto_1.createHash)('sha256').update(rel).digest('hex').slice(0, 12);
|
|
@@ -117,19 +117,31 @@ dependents = null) {
|
|
|
117
117
|
daemon: options.daemon,
|
|
118
118
|
publishPorts: false,
|
|
119
119
|
waitForReady: true,
|
|
120
|
-
onQuotaRefused: (refused) =>
|
|
120
|
+
onQuotaRefused: (refused) => {
|
|
121
|
+
// the timeout counts the time it runs, not its wait for room under the quota;
|
|
122
|
+
// that wait may last as long as the timeout in all, besides QUOTA_TIMEOUT
|
|
123
|
+
if (refused) {
|
|
124
|
+
deadline.pause();
|
|
125
|
+
}
|
|
126
|
+
else {
|
|
127
|
+
deadline.resume();
|
|
128
|
+
}
|
|
129
|
+
options.processManager.quotaRefused(work, refused);
|
|
130
|
+
},
|
|
121
131
|
});
|
|
122
132
|
}
|
|
123
133
|
finally {
|
|
124
134
|
deadline.clear();
|
|
125
135
|
}
|
|
126
|
-
if (deadline.expired() && timeout !== null) {
|
|
136
|
+
if ((deadline.expired() || deadline.waitedOut()) && timeout !== null) {
|
|
127
137
|
// the runtime saw an abort and cleaned up; report it as a failure
|
|
128
138
|
// (never a cancellation) and stop the run like any failing task
|
|
129
139
|
work.state.set({
|
|
130
140
|
type: 'error',
|
|
131
141
|
stateKey: cacheState.stateKey,
|
|
132
|
-
errorMessage:
|
|
142
|
+
errorMessage: deadline.waitedOut()
|
|
143
|
+
? `gave up waiting for room under the quota of the namespace after ${(0, units_1.formatDuration)(timeout)}, its timeout`
|
|
144
|
+
: `timed out after ${(0, units_1.formatDuration)(timeout)}`,
|
|
133
145
|
});
|
|
134
146
|
if (!options.watch) {
|
|
135
147
|
environment.abortCtrl.abort();
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.getFileContext = void 0;
|
|
4
|
+
const promises_1 = require("stream/promises");
|
|
4
5
|
const fs_1 = require("fs");
|
|
5
6
|
const path_1 = require("path");
|
|
6
7
|
const chokidar_1 = require("chokidar");
|
|
@@ -58,14 +59,10 @@ function getFileContext(cwd) {
|
|
|
58
59
|
writeFile(path, content) {
|
|
59
60
|
return handleCallback((cb) => (0, fs_1.writeFile)(getAbsolutePath(cwd, path), content, cb));
|
|
60
61
|
},
|
|
62
|
+
// a pipeline, so that an error of the stream (a limit it runs into, a broken source) rejects
|
|
63
|
+
// the write as well, and the file is closed
|
|
61
64
|
async writeStream(path, stream) {
|
|
62
|
-
|
|
63
|
-
await new Promise((resolve, reject) => {
|
|
64
|
-
stream
|
|
65
|
-
.pipe(writeStream)
|
|
66
|
-
.on('error', (err) => reject(err))
|
|
67
|
-
.on('close', () => resolve());
|
|
68
|
-
});
|
|
65
|
+
await (0, promises_1.pipeline)(stream, (0, fs_1.createWriteStream)(path));
|
|
69
66
|
},
|
|
70
67
|
createWriteStream(path) {
|
|
71
68
|
return (0, fs_1.createWriteStream)(path);
|
package/dist/harness/connect.js
CHANGED
|
@@ -7,7 +7,6 @@ const work_item_status_1 = require("../planner/work-item-status");
|
|
|
7
7
|
const host_config_1 = require("../remote/host-config");
|
|
8
8
|
const redact_1 = require("../utils/redact");
|
|
9
9
|
const empty_writable_1 = require("../utils/empty-writable");
|
|
10
|
-
const token_source_1 = require("../remote/token-source");
|
|
11
10
|
const bundle_1 = require("../remote/bundle");
|
|
12
11
|
const sandbox_client_1 = require("./sandbox-client");
|
|
13
12
|
exports.DEFAULT_SHELL_TASK = 'sh';
|
|
@@ -34,7 +33,9 @@ exports.hasShell = hasShell;
|
|
|
34
33
|
* The registered server a harness works on and the published version it runs, checked:
|
|
35
34
|
* what the clients need to list the tasks of the version before they take a sandbox.
|
|
36
35
|
*/
|
|
37
|
-
async function connectServer(environment, options
|
|
36
|
+
async function connectServer(environment, options,
|
|
37
|
+
// where the connection says that it reconnects; stderr when left out
|
|
38
|
+
say) {
|
|
38
39
|
const config = await (0, host_config_1.readHostConfig)(environment);
|
|
39
40
|
const name = (0, host_config_1.chooseServer)(config, options.server || undefined, 'with HAMMERKIT_SERVER or --server');
|
|
40
41
|
if (!options.build) {
|
|
@@ -45,11 +46,13 @@ async function connectServer(environment, options) {
|
|
|
45
46
|
throw new Error(`${options.build} is not the hash of a published version (sha256:...), name it as hammerkit remote publish printed it (HAMMERKIT_BUILD or --build)`);
|
|
46
47
|
}
|
|
47
48
|
const server = (0, host_config_1.getRegisteredServer)(config, name);
|
|
48
|
-
return { name, connection:
|
|
49
|
+
return { name, connection: (0, sandbox_client_1.getServerConnection)(environment, name, server, say), build: options.build };
|
|
49
50
|
}
|
|
50
51
|
exports.connectServer = connectServer;
|
|
51
|
-
async function connectSandbox(environment, options, log
|
|
52
|
-
|
|
52
|
+
async function connectSandbox(environment, options, log) {
|
|
53
|
+
// the environment of a harness that loads hammerkit as a plugin writes nowhere: what the
|
|
54
|
+
// connection says goes where the harness shows what happens
|
|
55
|
+
const { name, connection, build } = await connectServer(environment, options, log);
|
|
53
56
|
let sandbox;
|
|
54
57
|
if (options.sandbox) {
|
|
55
58
|
sandbox = await sandbox_client_1.SandboxClient.get(connection, options.sandbox);
|
|
@@ -57,11 +60,11 @@ async function connectSandbox(environment, options, log = () => undefined) {
|
|
|
57
60
|
else if (options.repo && options.ref) {
|
|
58
61
|
sandbox = await reuseSandbox(connection, options.repo, options.ref);
|
|
59
62
|
if (sandbox) {
|
|
60
|
-
log(`took sandbox ${sandbox.id} of ${sandbox.repo} at ${sandbox.commit} on ${name}, it had no changes`);
|
|
63
|
+
log?.(`took sandbox ${sandbox.id} of ${sandbox.repo} at ${sandbox.commit} on ${name}, it had no changes`);
|
|
61
64
|
}
|
|
62
65
|
else {
|
|
63
66
|
sandbox = await sandbox_client_1.SandboxClient.create(connection, options.repo, options.ref);
|
|
64
|
-
log(`created sandbox ${sandbox.id} of ${sandbox.repo} at ${sandbox.commit} on ${name}, ` +
|
|
67
|
+
log?.(`created sandbox ${sandbox.id} of ${sandbox.repo} at ${sandbox.commit} on ${name}, ` +
|
|
65
68
|
`set HAMMERKIT_SANDBOX=${sandbox.id} to come back to it`);
|
|
66
69
|
}
|
|
67
70
|
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Reconnecting = exports.showUrl = exports.RECONNECT_TIMING = void 0;
|
|
4
|
+
const http_1 = require("../server/http");
|
|
5
|
+
const units_1 = require("../utils/units");
|
|
6
|
+
// a restart of the server takes a few minutes while its new pod starts
|
|
7
|
+
exports.RECONNECT_TIMING = { windowMs: 10 * 60000, firstDelayMs: 1000, maxDelayMs: 15000 };
|
|
8
|
+
// what a proxy or the server answers while the server is away or shuts down
|
|
9
|
+
const AWAY_STATUSES = [502, 503, 504];
|
|
10
|
+
// the call never got to the server. A connect timeout is one: the connection was never
|
|
11
|
+
// made, so nothing of the request was sent.
|
|
12
|
+
const NOT_SENT = ['ECONNREFUSED', 'EAI_AGAIN', 'ENETUNREACH', 'EHOSTUNREACH', 'UND_ERR_CONNECT_TIMEOUT'];
|
|
13
|
+
// the connection broke or timed out, maybe after the server took the call
|
|
14
|
+
const LOST = [
|
|
15
|
+
'ECONNRESET',
|
|
16
|
+
'ECONNABORTED',
|
|
17
|
+
'EPIPE',
|
|
18
|
+
'ETIMEDOUT',
|
|
19
|
+
'UND_ERR_SOCKET',
|
|
20
|
+
'UND_ERR_HEADERS_TIMEOUT',
|
|
21
|
+
'UND_ERR_BODY_TIMEOUT',
|
|
22
|
+
];
|
|
23
|
+
// The codes of the error a fetch failed with: node's fetch keeps it as the cause, with one
|
|
24
|
+
// error for each address it tried when a name has several.
|
|
25
|
+
function failureCodes(e) {
|
|
26
|
+
if (e instanceof Error && e.name === 'TimeoutError') {
|
|
27
|
+
return ['ETIMEDOUT'];
|
|
28
|
+
}
|
|
29
|
+
const cause = e?.cause;
|
|
30
|
+
const codes = cause?.errors?.length ? cause.errors.map((error) => error?.code) : [cause?.code];
|
|
31
|
+
return codes.map((code) => (typeof code === 'string' ? code : ''));
|
|
32
|
+
}
|
|
33
|
+
function isAway(response) {
|
|
34
|
+
return AWAY_STATUSES.includes(response.status);
|
|
35
|
+
}
|
|
36
|
+
function mayRepeat(attempt, repeat) {
|
|
37
|
+
if ('response' in attempt) {
|
|
38
|
+
return repeat === 'always'
|
|
39
|
+
? isAway(attempt.response)
|
|
40
|
+
: attempt.response.status === 503 && attempt.response.headers.get(http_1.RETRY_HEADER) === 'safe';
|
|
41
|
+
}
|
|
42
|
+
const codes = failureCodes(attempt.error);
|
|
43
|
+
return repeat === 'always'
|
|
44
|
+
? codes.some((code) => NOT_SENT.includes(code) || LOST.includes(code))
|
|
45
|
+
: codes.every((code) => NOT_SENT.includes(code));
|
|
46
|
+
}
|
|
47
|
+
// The address of a server as it is said, without a user or password it may hold.
|
|
48
|
+
function showUrl(url) {
|
|
49
|
+
try {
|
|
50
|
+
const parsed = new URL(url);
|
|
51
|
+
if (!parsed.username && !parsed.password) {
|
|
52
|
+
return url;
|
|
53
|
+
}
|
|
54
|
+
parsed.username = '';
|
|
55
|
+
parsed.password = '';
|
|
56
|
+
return url.endsWith('/') ? parsed.toString() : parsed.toString().replace(/\/$/, '');
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return url;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
exports.showUrl = showUrl;
|
|
63
|
+
/**
|
|
64
|
+
* The window of one call: every send of it, a send again after a new token included, waits
|
|
65
|
+
* for the server at most the window, counted from the start of the first try that failed.
|
|
66
|
+
*/
|
|
67
|
+
class Reconnecting {
|
|
68
|
+
constructor(options) {
|
|
69
|
+
this.options = options;
|
|
70
|
+
this.away = false;
|
|
71
|
+
this.delay = options.timing.firstDelayMs;
|
|
72
|
+
}
|
|
73
|
+
// the window ran out
|
|
74
|
+
get exhausted() {
|
|
75
|
+
return this.deadline !== undefined && this.deadline <= Date.now();
|
|
76
|
+
}
|
|
77
|
+
// how long the next try may take: no longer than what is left of the window, once it started
|
|
78
|
+
timeoutMs(own) {
|
|
79
|
+
return this.deadline === undefined ? own : Math.max(1, Math.min(own, this.deadline - Date.now()));
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Sends a call until the server answers it, as long as it may be sent again and the server
|
|
83
|
+
* comes back within the window: an answer other than one of a server that is away is the
|
|
84
|
+
* caller's, an error that is no sign of one fails at once.
|
|
85
|
+
*/
|
|
86
|
+
async send(send, repeat) {
|
|
87
|
+
const { url, timing, say, signal, fail } = this.options;
|
|
88
|
+
const shown = showUrl(url);
|
|
89
|
+
for (;;) {
|
|
90
|
+
const started = Date.now();
|
|
91
|
+
const attempt = await send();
|
|
92
|
+
if (!mayRepeat(attempt, repeat)) {
|
|
93
|
+
if ('response' in attempt) {
|
|
94
|
+
if (this.away && !isAway(attempt.response)) {
|
|
95
|
+
this.away = false;
|
|
96
|
+
say?.(`${shown} is back`);
|
|
97
|
+
}
|
|
98
|
+
return attempt.response;
|
|
99
|
+
}
|
|
100
|
+
throw fail(attempt.message);
|
|
101
|
+
}
|
|
102
|
+
const reason = 'response' in attempt ? `${shown} answered ${attempt.response.status}` : attempt.message;
|
|
103
|
+
if ('response' in attempt) {
|
|
104
|
+
await attempt.response.body?.cancel().catch(() => undefined);
|
|
105
|
+
}
|
|
106
|
+
const window = (0, units_1.formatDuration)(timing.windowMs);
|
|
107
|
+
this.deadline ?? (this.deadline = started + timing.windowMs);
|
|
108
|
+
if (!this.away) {
|
|
109
|
+
this.away = true;
|
|
110
|
+
say?.(`${reason}, reconnecting for up to ${window}`);
|
|
111
|
+
}
|
|
112
|
+
const left = this.deadline - Date.now();
|
|
113
|
+
if (left <= 0) {
|
|
114
|
+
throw fail(`${shown} did not come back within ${window}: ${reason}`);
|
|
115
|
+
}
|
|
116
|
+
if (signal?.aborted || !(await pause(Math.min(this.delay, left), signal))) {
|
|
117
|
+
throw fail(reason);
|
|
118
|
+
}
|
|
119
|
+
this.delay = Math.min(this.delay * 2, timing.maxDelayMs);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
exports.Reconnecting = Reconnecting;
|
|
124
|
+
// false when the signal ended the pause
|
|
125
|
+
function pause(ms, signal) {
|
|
126
|
+
return new Promise((resolve) => {
|
|
127
|
+
const done = (waited) => {
|
|
128
|
+
clearTimeout(timer);
|
|
129
|
+
signal?.removeEventListener('abort', aborted);
|
|
130
|
+
resolve(waited);
|
|
131
|
+
};
|
|
132
|
+
const aborted = () => done(false);
|
|
133
|
+
const timer = setTimeout(() => done(true), ms);
|
|
134
|
+
signal?.addEventListener('abort', aborted, { once: true });
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
//# sourceMappingURL=reconnect.js.map
|
|
@@ -1,10 +1,18 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.quotePosix = exports.fetchFailure = exports.toSandboxPath = exports.checkSandboxPath = exports.exitCodeOf = exports.readRunLog = exports.getRun = exports.followRun = exports.getMoveTarget = exports.submitRun = exports.FINAL_RUN_STATES = exports.readTextUpTo = exports.oneAtATime = exports.SandboxClient = exports.listPublishedTasks = exports.runCheck = exports.CHECK_DESCRIPTION = exports.SandboxClientError = exports.MAX_ENDPOINT_BYTES = void 0;
|
|
3
|
+
exports.quotePosix = exports.fetchFailure = exports.toSandboxPath = exports.checkSandboxPath = exports.exitCodeOf = exports.readRunLog = exports.downloadRunArtifact = exports.getRunArtifacts = exports.getRun = exports.followRun = exports.getMoveTarget = exports.lookupChecks = exports.submitRun = exports.FINAL_RUN_STATES = exports.readTextUpTo = exports.oneAtATime = exports.SandboxClient = exports.listPublishedTasks = exports.runCheck = exports.CHECK_DESCRIPTION = exports.getServerConnection = exports.SandboxClientError = exports.MAX_ENDPOINT_BYTES = void 0;
|
|
4
4
|
const path_1 = require("path");
|
|
5
5
|
const token_source_1 = require("../remote/token-source");
|
|
6
|
+
const reconnect_1 = require("./reconnect");
|
|
7
|
+
const fs_1 = require("fs");
|
|
8
|
+
const stream_1 = require("stream");
|
|
9
|
+
const promises_1 = require("stream/promises");
|
|
6
10
|
// a write carries up to 32 MiB
|
|
7
11
|
const TIMEOUT_MS = 60000;
|
|
12
|
+
// an output of a run carries up to runs.artifacts.maxBytes, 256 MiB by default: 30 minutes is
|
|
13
|
+
// what that takes at about 150 KiB/s, the slowest link the default still downloads over. A
|
|
14
|
+
// server with a larger maxBytes needs a longer timeout, as the download is not split up.
|
|
15
|
+
const DOWNLOAD_TIMEOUT_MS = 30 * 60000;
|
|
8
16
|
// a run is asked for this long at a time, the log is read in between
|
|
9
17
|
const POLL_WAIT = '1s';
|
|
10
18
|
// a cancelled run waits this long for the server to take the cancel, before it gives up
|
|
@@ -19,6 +27,17 @@ class SandboxClientError extends Error {
|
|
|
19
27
|
}
|
|
20
28
|
}
|
|
21
29
|
exports.SandboxClientError = SandboxClientError;
|
|
30
|
+
// A connection to a registered server, which says when it reconnects, on stderr unless told
|
|
31
|
+
// where else, and stops when the command is stopped.
|
|
32
|
+
function getServerConnection(environment, name, server, say = (line) => environment.stderr.write(`${line}\n`)) {
|
|
33
|
+
return {
|
|
34
|
+
url: server.url,
|
|
35
|
+
...(0, token_source_1.getTokenSource)(environment, name, server),
|
|
36
|
+
say,
|
|
37
|
+
signal: environment.abortCtrl.signal,
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
exports.getServerConnection = getServerConnection;
|
|
22
41
|
// What the agent is told of a check, on each harness.
|
|
23
42
|
exports.CHECK_DESCRIPTION = 'Run a task as a check before you push, such as test or e2e: it runs on a copy of the files a push ' +
|
|
24
43
|
'would commit (what .gitignore leaves out is not there, so dependencies are installed by the tasks ' +
|
|
@@ -92,9 +111,12 @@ class SandboxClient {
|
|
|
92
111
|
static async list(connection) {
|
|
93
112
|
return (await json(await call(connection, 'GET', '/v1/sandboxes'))).sandboxes;
|
|
94
113
|
}
|
|
95
|
-
// checks out the ref again, what changed in the sandbox is gone
|
|
114
|
+
// checks out the ref again, what changed in the sandbox is gone: the same however often it comes
|
|
96
115
|
static async fetch(connection, id, ref) {
|
|
97
|
-
return json(await call(connection, 'POST', `/v1/sandboxes/${encodeURIComponent(id)}/fetch`, {
|
|
116
|
+
return json(await call(connection, 'POST', `/v1/sandboxes/${encodeURIComponent(id)}/fetch`, {
|
|
117
|
+
body: { ref },
|
|
118
|
+
repeat: 'always',
|
|
119
|
+
}));
|
|
98
120
|
}
|
|
99
121
|
async stat(path) {
|
|
100
122
|
if (checkSandboxPath(path) === '') {
|
|
@@ -122,11 +144,15 @@ class SandboxClient {
|
|
|
122
144
|
return json(await call(this.connection, 'GET', `${this.base()}/tree`, { query: { ...query } }));
|
|
123
145
|
}
|
|
124
146
|
async search(query) {
|
|
125
|
-
return json(await call(this.connection, 'POST', `${this.base()}/search`, { body: query }));
|
|
147
|
+
return json(await call(this.connection, 'POST', `${this.base()}/search`, { body: query, repeat: 'always' }));
|
|
126
148
|
}
|
|
127
|
-
// all or nothing
|
|
149
|
+
// all or nothing; a replace or a patch sent again would not find what it changed, so only a
|
|
150
|
+
// dry run is sent again on a broken connection
|
|
128
151
|
async edit(ops, dryRun = false) {
|
|
129
|
-
const answer = await call(this.connection, 'POST', `${this.base()}/edits`, {
|
|
152
|
+
const answer = await call(this.connection, 'POST', `${this.base()}/edits`, {
|
|
153
|
+
body: { dryRun, ops },
|
|
154
|
+
repeat: dryRun ? 'always' : 'unsent',
|
|
155
|
+
});
|
|
130
156
|
return (await json(answer)).files;
|
|
131
157
|
}
|
|
132
158
|
async changes() {
|
|
@@ -210,9 +236,9 @@ class SandboxClient {
|
|
|
210
236
|
});
|
|
211
237
|
return followRun(this.connection, submitted, { signal: options.signal, untilUp: true });
|
|
212
238
|
}
|
|
213
|
-
// Stops a run: a service run takes its services and endpoints down.
|
|
239
|
+
// Stops a run: a service run takes its services and endpoints down. The same however often it comes.
|
|
214
240
|
async stop(id) {
|
|
215
|
-
return json(await call(this.connection, 'POST', `/v1/runs/${encodeURIComponent(id)}/cancel
|
|
241
|
+
return json(await call(this.connection, 'POST', `/v1/runs/${encodeURIComponent(id)}/cancel`, { repeat: 'always' }));
|
|
216
242
|
}
|
|
217
243
|
/**
|
|
218
244
|
* A page of an endpoint of a service run, as the caller sees it: only at an address the
|
|
@@ -346,6 +372,12 @@ async function submitRun(connection, request) {
|
|
|
346
372
|
return json(await call(connection, 'POST', '/v1/runs', { body: request }));
|
|
347
373
|
}
|
|
348
374
|
exports.submitRun = submitRun;
|
|
375
|
+
// The newest passed run of each check key, as `POST /v1/checks/lookup` answers it: a read,
|
|
376
|
+
// asked again while the server is away.
|
|
377
|
+
async function lookupChecks(connection, repo, keys) {
|
|
378
|
+
return json(await call(connection, 'POST', '/v1/checks/lookup', { body: { repo, keys }, repeat: 'always' }));
|
|
379
|
+
}
|
|
380
|
+
exports.lookupChecks = lookupChecks;
|
|
349
381
|
/**
|
|
350
382
|
* Follows a run to its end: its log as it grows, and its state. A signal cancels the run
|
|
351
383
|
* on the server and fails the follow. A service run that moved to another commit is followed
|
|
@@ -372,14 +404,21 @@ function isThere(run, submitted) {
|
|
|
372
404
|
}
|
|
373
405
|
async function followRun(connection, submitted, options = {}) {
|
|
374
406
|
const path = `/v1/runs/${encodeURIComponent(submitted.id)}`;
|
|
407
|
+
// the stop of the follow, or of the command when it names none
|
|
408
|
+
const signal = options.signal ?? connection.signal;
|
|
375
409
|
let cancelling;
|
|
376
410
|
const cancel = () => {
|
|
377
411
|
if (!submitted.moved) {
|
|
378
|
-
|
|
412
|
+
// the same however often it comes, and waited for only as long as the follow waits for it
|
|
413
|
+
cancelling ?? (cancelling = call(connection, 'POST', `${path}/cancel`, {
|
|
414
|
+
repeat: 'always',
|
|
415
|
+
reconnectMs: CANCEL_WAIT_MS,
|
|
416
|
+
signal: null,
|
|
417
|
+
}).catch(() => undefined));
|
|
379
418
|
}
|
|
380
419
|
};
|
|
381
420
|
if (!options.detach) {
|
|
382
|
-
|
|
421
|
+
signal?.addEventListener('abort', cancel, { once: true });
|
|
383
422
|
}
|
|
384
423
|
const lines = [];
|
|
385
424
|
let from = submitted.moved?.logFrom ?? 1;
|
|
@@ -388,9 +427,23 @@ async function followRun(connection, submitted, options = {}) {
|
|
|
388
427
|
lines.push(line);
|
|
389
428
|
options.onLine?.(line);
|
|
390
429
|
};
|
|
430
|
+
// a server that is away is waited for until the signal stops the follow, which goes on then
|
|
431
|
+
// as a stopped one
|
|
432
|
+
const stoppable = (read) => read.catch((e) => {
|
|
433
|
+
if (signal?.aborted) {
|
|
434
|
+
return undefined;
|
|
435
|
+
}
|
|
436
|
+
throw e;
|
|
437
|
+
});
|
|
391
438
|
const readLog = async () => {
|
|
392
439
|
for (;;) {
|
|
393
|
-
const page = await
|
|
440
|
+
const page = await stoppable(call(connection, 'GET', `${path}/logs`, {
|
|
441
|
+
query: { task: options.task, from, limit: 1000 },
|
|
442
|
+
signal,
|
|
443
|
+
}).then(json));
|
|
444
|
+
if (!page) {
|
|
445
|
+
return;
|
|
446
|
+
}
|
|
394
447
|
truncated = page.truncated;
|
|
395
448
|
for (const line of page.lines) {
|
|
396
449
|
add(line);
|
|
@@ -405,10 +458,10 @@ async function followRun(connection, submitted, options = {}) {
|
|
|
405
458
|
let run = submitted;
|
|
406
459
|
let waitingSaid = false;
|
|
407
460
|
for (;;) {
|
|
408
|
-
if (
|
|
461
|
+
if (signal?.aborted && options.detach) {
|
|
409
462
|
break;
|
|
410
463
|
}
|
|
411
|
-
if (
|
|
464
|
+
if (signal?.aborted) {
|
|
412
465
|
// the process may exit after this, so the cancel has to reach the server first
|
|
413
466
|
cancel();
|
|
414
467
|
let timer;
|
|
@@ -424,7 +477,8 @@ async function followRun(connection, submitted, options = {}) {
|
|
|
424
477
|
if (exports.FINAL_RUN_STATES.includes(run.state) || (options.untilUp && isThere(run, submitted))) {
|
|
425
478
|
break;
|
|
426
479
|
}
|
|
427
|
-
run =
|
|
480
|
+
run =
|
|
481
|
+
(await stoppable(call(connection, 'GET', path, { query: { wait: POLL_WAIT }, signal }).then(json))) ?? run;
|
|
428
482
|
}
|
|
429
483
|
if (truncated) {
|
|
430
484
|
truncatedEnd(run, options.task).forEach(add);
|
|
@@ -432,7 +486,7 @@ async function followRun(connection, submitted, options = {}) {
|
|
|
432
486
|
return { run, lines, truncated };
|
|
433
487
|
}
|
|
434
488
|
finally {
|
|
435
|
-
|
|
489
|
+
signal?.removeEventListener('abort', cancel);
|
|
436
490
|
}
|
|
437
491
|
}
|
|
438
492
|
exports.followRun = followRun;
|
|
@@ -459,6 +513,26 @@ async function getRun(connection, id) {
|
|
|
459
513
|
return response.status === 404 ? null : json(response);
|
|
460
514
|
}
|
|
461
515
|
exports.getRun = getRun;
|
|
516
|
+
// null when the caller may not see the run (or the server keeps none of it)
|
|
517
|
+
async function getRunArtifacts(connection, id) {
|
|
518
|
+
const response = await call(connection, 'GET', `/v1/runs/${encodeURIComponent(id)}/artifacts`, { missing: true });
|
|
519
|
+
return response.status === 404 ? null : json(response);
|
|
520
|
+
}
|
|
521
|
+
exports.getRunArtifacts = getRunArtifacts;
|
|
522
|
+
/**
|
|
523
|
+
* Writes the archive of one output of a run to `file`: a gzipped tar of its paths in the
|
|
524
|
+
* project. It may be large, so it is written as it comes and may take longer than a call.
|
|
525
|
+
*/
|
|
526
|
+
async function downloadRunArtifact(connection, id, output, file) {
|
|
527
|
+
const response = await call(connection, 'GET', `/v1/runs/${encodeURIComponent(id)}/artifacts/${output}`, {
|
|
528
|
+
timeoutMs: DOWNLOAD_TIMEOUT_MS,
|
|
529
|
+
});
|
|
530
|
+
if (!response.body) {
|
|
531
|
+
throw new SandboxClientError(`${connection.url} answered without the archive`);
|
|
532
|
+
}
|
|
533
|
+
await (0, promises_1.pipeline)(stream_1.Readable.fromWeb(response.body), (0, fs_1.createWriteStream)(file));
|
|
534
|
+
}
|
|
535
|
+
exports.downloadRunArtifact = downloadRunArtifact;
|
|
462
536
|
/**
|
|
463
537
|
* Reads the log of a run as it is now, every line or the last `tail` of them, of one task or
|
|
464
538
|
* of all: also of a run that ended, as long as the server keeps it.
|
|
@@ -572,12 +646,25 @@ async function call(connection, method, path, options = {}) {
|
|
|
572
646
|
url.searchParams.set(key, String(value));
|
|
573
647
|
}
|
|
574
648
|
}
|
|
575
|
-
const
|
|
649
|
+
const shown = (0, reconnect_1.showUrl)(connection.url);
|
|
650
|
+
// the stop of the command, unless the call names its own or none
|
|
651
|
+
const stop = options.signal === undefined ? connection.signal : options.signal ?? undefined;
|
|
652
|
+
const timing = connection.reconnect ?? reconnect_1.RECONNECT_TIMING;
|
|
653
|
+
const reconnecting = new reconnect_1.Reconnecting({
|
|
654
|
+
url: connection.url,
|
|
655
|
+
timing: options.reconnectMs !== undefined ? { ...timing, windowMs: options.reconnectMs } : timing,
|
|
656
|
+
say: connection.say,
|
|
657
|
+
signal: stop,
|
|
658
|
+
fail: (message) => new SandboxClientError(message),
|
|
659
|
+
});
|
|
660
|
+
const attempt = async () => {
|
|
576
661
|
const token = await connection.token();
|
|
577
662
|
if (!(0, token_source_1.isToken)(token)) {
|
|
578
663
|
// a header refuses such a value and would quote it whole in its error
|
|
579
664
|
throw new SandboxClientError('the token is not a single line of visible characters');
|
|
580
665
|
}
|
|
666
|
+
// a try after one that failed takes no longer than what is left of the window
|
|
667
|
+
const timeout = AbortSignal.timeout(reconnecting.timeoutMs(options.timeoutMs ?? TIMEOUT_MS));
|
|
581
668
|
return fetch(url, {
|
|
582
669
|
method,
|
|
583
670
|
headers: {
|
|
@@ -586,17 +673,22 @@ async function call(connection, method, path, options = {}) {
|
|
|
586
673
|
...(options.raw !== undefined ? { 'content-type': 'application/octet-stream' } : {}),
|
|
587
674
|
},
|
|
588
675
|
body: options.body !== undefined ? JSON.stringify(options.body) : options.raw,
|
|
589
|
-
signal: AbortSignal.timeout
|
|
676
|
+
signal: stop ? AbortSignal.any([timeout, stop]) : timeout,
|
|
590
677
|
// an answer from anywhere else is not the server's, and a PUT would send its file on
|
|
591
678
|
redirect: 'error',
|
|
592
|
-
}).
|
|
593
|
-
|
|
594
|
-
|
|
679
|
+
}).then((response) => ({ response }), (e) => ({
|
|
680
|
+
error: e,
|
|
681
|
+
message: stop?.aborted
|
|
682
|
+
? `stopped while asking ${shown}`
|
|
683
|
+
: `unable to reach ${shown}: ${redact(fetchFailure(e), token)}`,
|
|
684
|
+
}));
|
|
595
685
|
};
|
|
596
|
-
|
|
597
|
-
|
|
686
|
+
const repeat = options.repeat ?? (method === 'GET' || method === 'PUT' ? 'always' : 'unsent');
|
|
687
|
+
let response = await reconnecting.send(attempt, repeat);
|
|
688
|
+
// a new token is asked for within the window the call has left, not after it ran out
|
|
689
|
+
if (response.status === 401 && connection.renew && !reconnecting.exhausted) {
|
|
598
690
|
await connection.renew();
|
|
599
|
-
response = await send();
|
|
691
|
+
response = await reconnecting.send(attempt, repeat);
|
|
600
692
|
}
|
|
601
693
|
if (response.ok || (options.missing && response.status === 404)) {
|
|
602
694
|
return response;
|
|
@@ -610,8 +702,8 @@ async function call(connection, method, path, options = {}) {
|
|
|
610
702
|
// no JSON
|
|
611
703
|
}
|
|
612
704
|
if (response.status === 401) {
|
|
613
|
-
throw new SandboxClientError(`${
|
|
705
|
+
throw new SandboxClientError(`${shown} did not accept the token`, 401);
|
|
614
706
|
}
|
|
615
|
-
throw new SandboxClientError(said || `${
|
|
707
|
+
throw new SandboxClientError(said || `${shown} answered ${response.status}`, response.status);
|
|
616
708
|
}
|
|
617
709
|
//# sourceMappingURL=sandbox-client.js.map
|