hammerkit 2.1.0-next.18 → 2.1.0-next.19
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/harness/sandbox-client.js +1 -0
- package/dist/harness/service-tools.js +11 -2
- package/dist/kubernetes/sync-changes.js +180 -0
- package/dist/planner/work-runtime-kubernetes.js +20 -0
- package/dist/server/executor.js +41 -7
- package/dist/server/kubernetes-backend.js +7 -4
- package/dist/server/run-request.js +11 -0
- package/dist/server/run-worker.js +145 -6
- package/dist/server/runs.js +20 -0
- package/dist/server/sandbox-follow.js +54 -0
- package/dist/server/sandbox-sync.js +357 -0
- package/dist/server/sandboxes.js +14 -0
- package/dist/server/server.js +39 -7
- package/package.json +1 -1
|
@@ -233,6 +233,7 @@ class SandboxClient {
|
|
|
233
233
|
...(request.ttl ? { ttl: request.ttl } : {}),
|
|
234
234
|
...(request.sleepTtl ? { sleepTtl: request.sleepTtl } : {}),
|
|
235
235
|
...(request.name ? { name: request.name } : {}),
|
|
236
|
+
...(request.restart?.length ? { restart: request.restart } : {}),
|
|
236
237
|
source: request.branch
|
|
237
238
|
? { type: 'ref', repo: this.sandbox.repo, ref: request.branch }
|
|
238
239
|
: { type: 'sandbox', id: this.id },
|
|
@@ -71,8 +71,11 @@ exports.SERVICE_TOOLS = [
|
|
|
71
71
|
description: 'Start services of the published build file on the hammerkit server, with the files of the sandbox (or of ' +
|
|
72
72
|
'a branch), and keep them up for a person to look at: each endpoint (service:port) gets an address of its ' +
|
|
73
73
|
'own behind the sign-in of the server. Answers once they are up, with the addresses and until when they ' +
|
|
74
|
-
'stay. A second start with the same name replaces the first, so its addresses stay the same.
|
|
75
|
-
'Kubernetes
|
|
74
|
+
'stay. A second start with the same name replaces the first, so its addresses stay the same. Services from ' +
|
|
75
|
+
'the sandbox on a Kubernetes server follow its edits a few seconds after each one: the changed files go into ' +
|
|
76
|
+
'the services that watch their files (continuous), and the others keep the files they started with, unless ' +
|
|
77
|
+
'restart names them, which starts them again with the new files. On a host the services run on the sandbox ' +
|
|
78
|
+
'files themselves, so there is nothing to follow and restart is refused.',
|
|
76
79
|
parameters: {
|
|
77
80
|
services: { type: 'string[]', description: 'The services to start, as the build file names them' },
|
|
78
81
|
endpoints: { type: 'string[]', description: 'The ports to publish, as service:port, such as web:8080' },
|
|
@@ -93,6 +96,11 @@ exports.SERVICE_TOOLS = [
|
|
|
93
96
|
type: 'string',
|
|
94
97
|
description: 'Start from this pushed branch of the repository instead of the files of the sandbox',
|
|
95
98
|
},
|
|
99
|
+
restart: {
|
|
100
|
+
type: 'string[]',
|
|
101
|
+
description: 'The services that start again with the files of the sandbox after an edit of it; the others keep ' +
|
|
102
|
+
'the files they started with. Only with the sandbox, not with branch',
|
|
103
|
+
},
|
|
96
104
|
},
|
|
97
105
|
required: ['services'],
|
|
98
106
|
async call(client, args, signal) {
|
|
@@ -103,6 +111,7 @@ exports.SERVICE_TOOLS = [
|
|
|
103
111
|
sleepTtl: args.sleepTtl || undefined,
|
|
104
112
|
name: args.name || undefined,
|
|
105
113
|
branch: args.branch || undefined,
|
|
114
|
+
restart: args.restart?.length ? args.restart : undefined,
|
|
106
115
|
}, { signal });
|
|
107
116
|
return describeServiceRun(followed.run);
|
|
108
117
|
},
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.restartPods = exports.syncChangedFiles = exports.SYNC_CHANGES = exports.getChangeTarget = exports.CHANGES_STAGING_DIR = void 0;
|
|
4
|
+
const fs_1 = require("fs");
|
|
5
|
+
const stream_1 = require("stream");
|
|
6
|
+
const path_1 = require("path");
|
|
7
|
+
const volumes_1 = require("./volumes");
|
|
8
|
+
const ensure_persistent_data_1 = require("./ensure-persistent-data");
|
|
9
|
+
const transfer_tools_1 = require("./transfer-tools");
|
|
10
|
+
const tar_1 = require("../utils/tar");
|
|
11
|
+
const resources_1 = require("./resources");
|
|
12
|
+
// The folder of the claim the changed files of a sandbox are uploaded to, before they are
|
|
13
|
+
// applied to the folder of the service (SYNC_CHANGES). It is not a folder of a state, so the
|
|
14
|
+
// removal of other states leaves it be.
|
|
15
|
+
exports.CHANGES_STAGING_DIR = '.hammerkit-sync';
|
|
16
|
+
/**
|
|
17
|
+
* Where the changed files of a service of a service run go, and whether its Deployment starts
|
|
18
|
+
* again with them. A service that watches its files (`live`) gets them into the folder its
|
|
19
|
+
* pod mounts, and keeps running. One that doesn't keeps the files it started with, unless it
|
|
20
|
+
* restarts: then they go into the folder of its state, the one its pod mounts, and its pods
|
|
21
|
+
* start again. Undefined for a service that takes nothing.
|
|
22
|
+
*/
|
|
23
|
+
function getChangeTarget(live, restart, stateDir) {
|
|
24
|
+
if (live) {
|
|
25
|
+
return { dir: volumes_1.LIVE_FILES_DIR, rollout: restart };
|
|
26
|
+
}
|
|
27
|
+
return restart ? { dir: stateDir, rollout: true } : undefined;
|
|
28
|
+
}
|
|
29
|
+
exports.getChangeTarget = getChangeTarget;
|
|
30
|
+
/**
|
|
31
|
+
* Applies the staged batch at `$1` to the folder `$2`. Its `deleted` file lists the paths that
|
|
32
|
+
* are gone, NUL-separated, and its `files` folder the files that changed. The paths after `$2`
|
|
33
|
+
* are the ones pods mount from the folder: a deleted one of them stays.
|
|
34
|
+
* - Deletions come first. Then each file is written in place, only where its content or mode
|
|
35
|
+
* differs, so a file a pod mounts keeps its inode.
|
|
36
|
+
* - Nothing is written or removed through a link, or where a file is in the way of a folder:
|
|
37
|
+
* each folder on the way is checked from `$2` down, one component at a time. Such a path, and
|
|
38
|
+
* one with a `.` or `..` segment or a leading `/`, is skipped and reported as `skipped <path>: <why>`.
|
|
39
|
+
* The staged folder goes at the end.
|
|
40
|
+
*/
|
|
41
|
+
exports.SYNC_CHANGES = `src="$1"
|
|
42
|
+
dst="$2"
|
|
43
|
+
shift 2
|
|
44
|
+
mkdir -p "$src" "$dst" || exit 1
|
|
45
|
+
if [ -L "$dst" ]; then echo "skipped $dst: it is a link" >&2; exit 1; fi
|
|
46
|
+
# checks the folders of the relative path $1 under $dst: none may be a link or a file, and with
|
|
47
|
+
# $2 set the missing ones are made. False when one is a link or a file on the way.
|
|
48
|
+
walk() {
|
|
49
|
+
cur="$dst"
|
|
50
|
+
rest="$1"
|
|
51
|
+
while [ "$rest" != "\${rest#*/}" ]; do
|
|
52
|
+
comp="\${rest%%/*}"
|
|
53
|
+
rest="\${rest#*/}"
|
|
54
|
+
cur="$cur/$comp"
|
|
55
|
+
if [ -L "$cur" ]; then return 1; fi
|
|
56
|
+
if [ -e "$cur" ]; then
|
|
57
|
+
if [ ! -d "$cur" ]; then return 1; fi
|
|
58
|
+
elif [ -n "$2" ]; then
|
|
59
|
+
mkdir "$cur" || return 1
|
|
60
|
+
else
|
|
61
|
+
return 0
|
|
62
|
+
fi
|
|
63
|
+
done
|
|
64
|
+
return 0
|
|
65
|
+
}
|
|
66
|
+
if [ -f "$src/deleted" ]; then
|
|
67
|
+
tr '\\0' '\\n' < "$src/deleted" | while IFS= read -r p || [ -n "$p" ]; do
|
|
68
|
+
if [ -z "$p" ]; then continue; fi
|
|
69
|
+
case "$p" in
|
|
70
|
+
/*|.|./*|*/.|*/./*|..|../*|*/..|*/../*) echo "skipped $p: not a path of the sandbox"; continue ;;
|
|
71
|
+
esac
|
|
72
|
+
keep=
|
|
73
|
+
for m in "$@"; do
|
|
74
|
+
if [ "$p" = "$m" ]; then keep=1; fi
|
|
75
|
+
done
|
|
76
|
+
if [ -n "$keep" ]; then continue; fi
|
|
77
|
+
if ! walk "$p"; then echo "skipped $p: a link or a file is in its way"; continue; fi
|
|
78
|
+
rm -rf "$dst/$p" || exit 1
|
|
79
|
+
done || exit 1
|
|
80
|
+
fi
|
|
81
|
+
if [ -d "$src/files" ]; then
|
|
82
|
+
find "$src/files" -type f | while IFS= read -r s; do
|
|
83
|
+
f="\${s#"$src/files/"}"
|
|
84
|
+
case "$f" in
|
|
85
|
+
/*|.|./*|*/.|*/./*|..|../*|*/..|*/../*) echo "skipped $f: not a path of the sandbox"; continue ;;
|
|
86
|
+
esac
|
|
87
|
+
if ! walk "$f" yes; then echo "skipped $f: a link or a file is in its way"; continue; fi
|
|
88
|
+
t="$dst/$f"
|
|
89
|
+
if [ -L "$t" ] || [ -d "$t" ]; then rm -rf "$t" || exit 1; fi
|
|
90
|
+
if [ -e "$t" ]; then
|
|
91
|
+
if ! cmp -s "$s" "$t"; then cat "$s" > "$t" || exit 1; fi
|
|
92
|
+
else
|
|
93
|
+
cp -p "$s" "$t" || exit 1
|
|
94
|
+
fi
|
|
95
|
+
m=$(stat -c %a "$s") || exit 1
|
|
96
|
+
if [ "$(stat -c %a "$t")" != "$m" ]; then chmod "$m" "$t" || exit 1; fi
|
|
97
|
+
done || exit 1
|
|
98
|
+
fi
|
|
99
|
+
rm -rf "$src" || exit 1
|
|
100
|
+
exit 0`;
|
|
101
|
+
// The paths of the folder `dir` that the pods of the service mount, relative to it
|
|
102
|
+
function mountedUnder(persistence, dir) {
|
|
103
|
+
return persistence.mounts.flatMap(({ mount }) => mount.subPath?.startsWith(`${dir}/`) ? [mount.subPath.slice(dir.length + 1)] : []);
|
|
104
|
+
}
|
|
105
|
+
// Uploads the entries of the batch folder `batch` into `target` of the upload pod `pod`
|
|
106
|
+
async function uploadStaged(instance, env, pod, batch, target) {
|
|
107
|
+
const entries = (0, fs_1.readdirSync)(batch);
|
|
108
|
+
const data = stream_1.Readable.from((0, tar_1.packArchive)({ cwd: batch }, entries));
|
|
109
|
+
const res = await instance.exec.exec(env.namespace, pod, 'volume', (0, transfer_tools_1.inTransferPod)(['tar', 'xf', '-', '-C', target]), process.stdout, process.stderr, data, false);
|
|
110
|
+
await new Promise((resolve, reject) => {
|
|
111
|
+
res.on('error', reject);
|
|
112
|
+
res.on('close', () => resolve());
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
// Runs `command` in the upload pod `pod`: what failed (null when it went well), and what it printed
|
|
116
|
+
async function execCapturing(instance, env, pod, command) {
|
|
117
|
+
let failure = null;
|
|
118
|
+
let output = '';
|
|
119
|
+
const out = new stream_1.PassThrough();
|
|
120
|
+
out.on('data', (chunk) => (output += chunk.toString('utf8')));
|
|
121
|
+
const res = await instance.exec.exec(env.namespace, pod, 'volume', (0, transfer_tools_1.inTransferPod)(command), out, process.stderr, null, false, (status) => {
|
|
122
|
+
if (status.status !== 'Success') {
|
|
123
|
+
failure = status.message ?? status.reason ?? 'unknown';
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
await new Promise((resolve, reject) => {
|
|
127
|
+
res.on('error', reject);
|
|
128
|
+
res.on('close', () => resolve());
|
|
129
|
+
});
|
|
130
|
+
return { failure, output };
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Syncs the changed files of a sandbox into the folder `dir` of the claim of `service`: only
|
|
134
|
+
* what changed is uploaded and applied, nothing else of the service is touched. The batch
|
|
135
|
+
* folder of the changes (`dirname` of `changes.dir`) gets its `deleted` list here, NUL-separated.
|
|
136
|
+
* Returns the paths the pod skipped (see SYNC_CHANGES).
|
|
137
|
+
*/
|
|
138
|
+
async function syncChangedFiles(instance, env, service, persistence, dir, changes) {
|
|
139
|
+
const root = `/dev/hammerkit/${service.id()}`;
|
|
140
|
+
const staging = `${root}/${exports.CHANGES_STAGING_DIR}`;
|
|
141
|
+
const mounted = mountedUnder(persistence, dir);
|
|
142
|
+
const batch = (0, path_1.dirname)(changes.dir);
|
|
143
|
+
(0, fs_1.writeFileSync)((0, path_1.join)(batch, 'deleted'), changes.deleted.join('\0'));
|
|
144
|
+
const skipped = [];
|
|
145
|
+
await (0, ensure_persistent_data_1.getPodForPersistence)(instance, env, service, persistence, 'write', undefined, async (pod) => {
|
|
146
|
+
const cleared = await execCapturing(instance, env, pod, ['sh', '-c', 'rm -rf "$1" && mkdir -p "$1"', 'sh', staging]);
|
|
147
|
+
if (cleared.failure) {
|
|
148
|
+
throw new Error(`unable to stage the changes of ${service.name} in ${pod}: ${cleared.failure}`);
|
|
149
|
+
}
|
|
150
|
+
await uploadStaged(instance, env, pod, batch, staging);
|
|
151
|
+
const { failure, output } = await execCapturing(instance, env, pod, [
|
|
152
|
+
'sh',
|
|
153
|
+
'-c',
|
|
154
|
+
exports.SYNC_CHANGES,
|
|
155
|
+
'sh',
|
|
156
|
+
staging,
|
|
157
|
+
`${root}/${dir}`,
|
|
158
|
+
...mounted,
|
|
159
|
+
]);
|
|
160
|
+
skipped.push(...output.split('\n').filter((line) => line.startsWith('skipped ')));
|
|
161
|
+
if (failure) {
|
|
162
|
+
throw new Error(`unable to sync the changed files of ${service.name} into ${dir}: ${failure}`);
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
return skipped;
|
|
166
|
+
}
|
|
167
|
+
exports.syncChangedFiles = syncChangedFiles;
|
|
168
|
+
/**
|
|
169
|
+
* Starts the pods of a service again: its Deployment makes new ones from its template, which
|
|
170
|
+
* mount the folder the files were synced into. A service that keeps its files is down for the
|
|
171
|
+
* time the new pods take to start.
|
|
172
|
+
*/
|
|
173
|
+
async function restartPods(instance, env, service) {
|
|
174
|
+
await instance.coreApi.deleteCollectionNamespacedPod({
|
|
175
|
+
namespace: env.namespace,
|
|
176
|
+
labelSelector: (0, resources_1.getItemSelector)(service, env),
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
exports.restartPods = restartPods;
|
|
180
|
+
//# sourceMappingURL=sync-changes.js.map
|
|
@@ -20,6 +20,7 @@ const ensure_persistent_data_1 = require("../kubernetes/ensure-persistent-data")
|
|
|
20
20
|
const network_gate_1 = require("../kubernetes/network-gate");
|
|
21
21
|
const await_running_state_1 = require("../kubernetes/await-running-state");
|
|
22
22
|
const volumes_1 = require("../kubernetes/volumes");
|
|
23
|
+
const sync_changes_1 = require("../kubernetes/sync-changes");
|
|
23
24
|
const service_rollouts_1 = require("../kubernetes/service-rollouts");
|
|
24
25
|
const resources_1 = require("../kubernetes/resources");
|
|
25
26
|
const ensure_http_route_1 = require("../kubernetes/ensure-http-route");
|
|
@@ -784,6 +785,25 @@ function kubernetesServiceRuntime(service, kubernetes) {
|
|
|
784
785
|
remote: null,
|
|
785
786
|
});
|
|
786
787
|
},
|
|
788
|
+
// The files of the sandbox changed while the service of a service run is up (FileChanges):
|
|
789
|
+
// synced into the folder its pod mounts, which the service sees, and its pods start again
|
|
790
|
+
// when it restarts. A service that keeps its files takes nothing.
|
|
791
|
+
async syncFiles(changes) {
|
|
792
|
+
const stateDir = kubernetes.server?.serviceRun ? (0, volumes_1.getItemFilesDir)(service, undefined) : undefined;
|
|
793
|
+
const target = stateDir
|
|
794
|
+
? (0, sync_changes_1.getChangeTarget)((0, volumes_1.isLiveService)(service, kubernetes), changes.restart, stateDir)
|
|
795
|
+
: undefined;
|
|
796
|
+
if (!target) {
|
|
797
|
+
return;
|
|
798
|
+
}
|
|
799
|
+
const persistence = await (0, volumes_1.getKubernetesPersistence)(service, kubernetes);
|
|
800
|
+
for (const line of await (0, sync_changes_1.syncChangedFiles)(instance, kubernetes, service, persistence, target.dir, changes)) {
|
|
801
|
+
service.status.write('info', line);
|
|
802
|
+
}
|
|
803
|
+
if (target.rollout) {
|
|
804
|
+
await (0, sync_changes_1.restartPods)(instance, kubernetes, service);
|
|
805
|
+
}
|
|
806
|
+
},
|
|
787
807
|
async restore(environment, path) {
|
|
788
808
|
await (0, restore_kubernetes_data_1.restoreKubernetesData)(service, kubernetes, instance, environment, path);
|
|
789
809
|
},
|
package/dist/server/executor.js
CHANGED
|
@@ -131,6 +131,22 @@ class HostExecutor {
|
|
|
131
131
|
this.options = options;
|
|
132
132
|
// the directories of the executions that run now
|
|
133
133
|
this.directories = new Set();
|
|
134
|
+
// the processes of the runs that run now, by run id, while they take input
|
|
135
|
+
this.children = new Map();
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Hands the changed files of a sandbox to the process of a service run that is up here, which
|
|
139
|
+
* syncs them into its services (see run-worker). False when no process of the run runs here.
|
|
140
|
+
*/
|
|
141
|
+
syncChildFiles(runId, changes) {
|
|
142
|
+
const child = this.children.get(runId);
|
|
143
|
+
const staging = this.options.sandboxes?.staging;
|
|
144
|
+
if (!child?.stdin || !staging) {
|
|
145
|
+
return false;
|
|
146
|
+
}
|
|
147
|
+
// the worker removes the batch folder only inside the staging folder of the run it is in
|
|
148
|
+
child.stdin.write(`sync ${JSON.stringify({ staging: (0, path_1.join)(staging, runId), changes })}\n`);
|
|
149
|
+
return true;
|
|
134
150
|
}
|
|
135
151
|
// the docker daemon the runs' services are on, as their processes reach it
|
|
136
152
|
docker() {
|
|
@@ -256,12 +272,21 @@ class HostExecutor {
|
|
|
256
272
|
// does a run that was approved: what was approved is those files, and the sandbox has
|
|
257
273
|
// more (its ignored files, node_modules, outputs), which its owner and their runs write
|
|
258
274
|
// while the run waits and runs.
|
|
259
|
-
|
|
275
|
+
// A service run from a sandbox on a cluster gets a copy of the files too: its pods mount no
|
|
276
|
+
// claim of the sandbox, and the files of later edits reach it by a move (RunRegistry.follow)
|
|
277
|
+
const approved = (run.approvals?.length ?? 0) > 0;
|
|
278
|
+
const onCluster = !!run.up && !!this.options.placement;
|
|
279
|
+
const copied = source.type === 'sandbox' && (source.check || approved || onCluster);
|
|
260
280
|
// (`source.type` again: TypeScript narrows `source` by it, not by `copied`)
|
|
261
281
|
if (source.type === 'sandbox' && copied) {
|
|
262
|
-
const { registry, network } = sandboxes;
|
|
263
|
-
const
|
|
264
|
-
if (
|
|
282
|
+
const { registry, network, started } = sandboxes;
|
|
283
|
+
const kind = source.check ? 'check' : approved ? 'approved run' : 'service run';
|
|
284
|
+
if (onCluster) {
|
|
285
|
+
// before the copy: a change from here on is one the services have not got
|
|
286
|
+
await started?.(run);
|
|
287
|
+
}
|
|
288
|
+
const what = `the ${kind}`;
|
|
289
|
+
if (!source.check && approved) {
|
|
265
290
|
// what was approved is what runs: the files may have changed since, by a run
|
|
266
291
|
// before this one on the sandbox (the copy checks it again, under the sandbox's lock)
|
|
267
292
|
const state = await registry.state(source.id, abortCtrl.signal);
|
|
@@ -283,7 +308,7 @@ class HostExecutor {
|
|
|
283
308
|
type: 'log',
|
|
284
309
|
task: 'hammerkit',
|
|
285
310
|
stream: 'stdout',
|
|
286
|
-
text: `${
|
|
311
|
+
text: `${kind} of sandbox ${source.id} of ${source.repo}: files ${source.tree}, fetched at ${source.commit}`,
|
|
287
312
|
});
|
|
288
313
|
// the tasks see the published build files in place of the sandbox's own
|
|
289
314
|
await this.writeBundle(work, bundle.files);
|
|
@@ -373,12 +398,13 @@ class HostExecutor {
|
|
|
373
398
|
up: {
|
|
374
399
|
services: run.up.services,
|
|
375
400
|
endpoints: run.up.endpoints.map(({ service, port }) => ({ service, port })),
|
|
401
|
+
...(run.up.restart ? { restart: run.up.restart } : {}),
|
|
376
402
|
},
|
|
377
403
|
}
|
|
378
404
|
: {}),
|
|
379
405
|
...(placed ? { kubernetes: placed.kubernetes } : {}),
|
|
380
406
|
...(!placed && this.options.capabilityRuntime ? { capabilityRuntime: this.options.capabilityRuntime } : {}),
|
|
381
|
-
}, published, { ...(0, run_source_environment_1.withRunSource)(this.processEnvironment(home, cache), run.source), ...placed?.env }, context, abortCtrl.signal, !!placed);
|
|
407
|
+
}, published, { ...(0, run_source_environment_1.withRunSource)(this.processEnvironment(home, cache), run.source), ...placed?.env }, context, abortCtrl.signal, !!placed, run.id);
|
|
382
408
|
}
|
|
383
409
|
finally {
|
|
384
410
|
if (placement && placed) {
|
|
@@ -396,6 +422,9 @@ class HostExecutor {
|
|
|
396
422
|
finally {
|
|
397
423
|
context.signal.removeEventListener('abort', abort);
|
|
398
424
|
attachment?.release?.();
|
|
425
|
+
if (run.up && this.options.placement) {
|
|
426
|
+
await sandboxes?.ended?.(run);
|
|
427
|
+
}
|
|
399
428
|
await this.removeRunDirectory(run, root, context);
|
|
400
429
|
this.directories.delete(root);
|
|
401
430
|
if (source.type === 'sandbox') {
|
|
@@ -459,7 +488,7 @@ class HostExecutor {
|
|
|
459
488
|
// A run that the server leaves to the next one (RunContext.detached) and whose tasks are on
|
|
460
489
|
// a cluster: the process is killed at once, so its Jobs and services stay. One whose tasks
|
|
461
490
|
// are on this machine stops them as a cancel does, in less time.
|
|
462
|
-
runInProcess(command, input, cwd, env, context, signal, onCluster) {
|
|
491
|
+
runInProcess(command, input, cwd, env, context, signal, onCluster, runId) {
|
|
463
492
|
return new Promise((resolvePromise, reject) => {
|
|
464
493
|
const child = (0, child_process_1.spawn)(command[0], command.slice(1), {
|
|
465
494
|
cwd,
|
|
@@ -470,6 +499,7 @@ class HostExecutor {
|
|
|
470
499
|
child.stdin.on('error', () => undefined);
|
|
471
500
|
// the run first, so a cancel comes after it; kept open, it is how a cancel reaches the process
|
|
472
501
|
child.stdin.write(`${JSON.stringify(input)}\n`);
|
|
502
|
+
this.children.set(runId, child);
|
|
473
503
|
let result;
|
|
474
504
|
let stderr = '';
|
|
475
505
|
let killTimer;
|
|
@@ -506,6 +536,7 @@ class HostExecutor {
|
|
|
506
536
|
else if (message.kind === 'result') {
|
|
507
537
|
result = message;
|
|
508
538
|
// nothing left to tell the process
|
|
539
|
+
this.children.delete(runId);
|
|
509
540
|
child.stdin.end();
|
|
510
541
|
}
|
|
511
542
|
}
|
|
@@ -524,6 +555,9 @@ class HostExecutor {
|
|
|
524
555
|
child.on('close', (code, killed) => {
|
|
525
556
|
signal.removeEventListener('abort', stop);
|
|
526
557
|
clearTimeout(killTimer);
|
|
558
|
+
if (this.children.get(runId) === child) {
|
|
559
|
+
this.children.delete(runId);
|
|
560
|
+
}
|
|
527
561
|
if (result?.ok) {
|
|
528
562
|
resolvePromise();
|
|
529
563
|
}
|
|
@@ -404,10 +404,8 @@ class KubernetesExecutor {
|
|
|
404
404
|
}
|
|
405
405
|
async executeOn(run, context) {
|
|
406
406
|
if (run.up) {
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
}
|
|
410
|
-
// in a namespace of its own, apart from the caller's runs and their claims
|
|
407
|
+
// in a namespace of its own, apart from the caller's runs and their claims, from a branch
|
|
408
|
+
// or from the files of a sandbox (copied, see HostExecutor.execute)
|
|
411
409
|
return this.host.execute(run, context);
|
|
412
410
|
}
|
|
413
411
|
// it executes: its objects are kept from a tidy as those of any run that executes
|
|
@@ -438,6 +436,11 @@ class KubernetesExecutor {
|
|
|
438
436
|
}
|
|
439
437
|
}
|
|
440
438
|
}
|
|
439
|
+
// The changed files of a sandbox for the services of a service run here: they are synced in
|
|
440
|
+
// place, nothing of the run moves (see RunExecutor.syncFiles)
|
|
441
|
+
syncFiles(run, changes) {
|
|
442
|
+
return !!run.up && this.host.syncChildFiles(run.id, changes);
|
|
443
|
+
}
|
|
441
444
|
// A service run moves to another commit in its namespace: unchanged services stay, the
|
|
442
445
|
// others roll to their new pods (see kubernetesServiceRuntime)
|
|
443
446
|
movesBeside(run) {
|
|
@@ -124,6 +124,9 @@ exports.runRequestSchema = zod_1.z
|
|
|
124
124
|
.array(zod_1.z.object({ service: name, port: zod_1.z.number().int().min(1).max(65535) }).strict())
|
|
125
125
|
.max(exports.MAX_ENDPOINTS)
|
|
126
126
|
.default([]),
|
|
127
|
+
// the services that start again with the files of their sandbox after an edit of it; the
|
|
128
|
+
// others keep the files they started with (see ServiceRunSpec.restart)
|
|
129
|
+
restart: zod_1.z.array(name).max(20).optional(),
|
|
127
130
|
})
|
|
128
131
|
.strict()
|
|
129
132
|
.refine((request) => request.services.length > 0 || request.tasks.length > 0 || (request.options.filter ?? []).length > 0, {
|
|
@@ -145,6 +148,14 @@ exports.runRequestSchema = zod_1.z
|
|
|
145
148
|
request.sleepTtl === undefined &&
|
|
146
149
|
request.name === undefined &&
|
|
147
150
|
request.endpoints.length === 0), { message: 'ttl, sleepTtl, name and endpoints are for a run of services', path: ['services'] })
|
|
151
|
+
.refine((request) => (request.restart ?? []).every((service) => request.services.includes(service)), {
|
|
152
|
+
message: 'restart names services the run starts',
|
|
153
|
+
path: ['restart'],
|
|
154
|
+
})
|
|
155
|
+
.refine((request) => !request.restart?.length || request.source.type === 'sandbox', {
|
|
156
|
+
message: 'restart is for a service run from a sandbox, which changes with its files',
|
|
157
|
+
path: ['restart'],
|
|
158
|
+
})
|
|
148
159
|
.refine((request) => new Set(request.endpoints.map((endpoint) => `${endpoint.service}:${endpoint.port}`)).size ===
|
|
149
160
|
request.endpoints.length, { message: 'an endpoint is named twice', path: ['endpoints'] })
|
|
150
161
|
.refine((request) => (request.options.args ?? []).length === 0 || request.tasks.length === 1, {
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.workerMain = exports.readInput = exports.taskCommands = exports.taskCauses = exports.describeFailures = exports.failedTasks = exports.runTasks = exports.relayStatus = exports.removeCommandsOfRun = exports.getRunnerCommands = exports.getLogEvent = exports.getEndpointTargets = exports.publishEndpoints = exports.getRunNetwork = exports.workerInputSchema = void 0;
|
|
3
|
+
exports.workerMain = exports.readInput = exports.ChangeQueue = exports.applyChanges = exports.isInside = exports.syncLine = exports.syncServices = exports.taskCommands = exports.taskCauses = exports.describeFailures = exports.failedTasks = exports.runTasks = exports.relayStatus = exports.removeCommandsOfRun = exports.getRunnerCommands = exports.getLogEvent = exports.getEndpointTargets = exports.publishEndpoints = exports.getRunNetwork = exports.workerInputSchema = void 0;
|
|
4
4
|
const readline_1 = require("readline");
|
|
5
|
+
const promises_1 = require("fs/promises");
|
|
6
|
+
const path_1 = require("path");
|
|
5
7
|
const zod_1 = require("zod");
|
|
6
8
|
const cli_1 = require("../cli");
|
|
7
9
|
const get_file_context_1 = require("../file/get-file-context");
|
|
@@ -79,6 +81,7 @@ exports.workerInputSchema = zod_1.z
|
|
|
79
81
|
.object({
|
|
80
82
|
services: zod_1.z.array(zod_1.z.string()).min(1),
|
|
81
83
|
endpoints: zod_1.z.array(zod_1.z.object({ service: zod_1.z.string(), port: zod_1.z.number().int() }).strict()),
|
|
84
|
+
restart: zod_1.z.array(zod_1.z.string()).optional(),
|
|
82
85
|
})
|
|
83
86
|
.strict()
|
|
84
87
|
.optional(),
|
|
@@ -252,7 +255,10 @@ cancelled, emit,
|
|
|
252
255
|
// a service run: its services are ready, at these addresses
|
|
253
256
|
up,
|
|
254
257
|
// its commands in a sandbox's runner
|
|
255
|
-
commands = getRunnerCommands(input, emit)
|
|
258
|
+
commands = getRunnerCommands(input, emit),
|
|
259
|
+
// a service run: hands the changed files of its sandbox to the services that are up while
|
|
260
|
+
// they are up (undefined once they are not)
|
|
261
|
+
register) {
|
|
256
262
|
const secrets = (0, redact_1.createSecretRegistry)();
|
|
257
263
|
const status = (0, work_item_status_1.statusConsole)((0, empty_writable_1.emptyWritable)(), secrets);
|
|
258
264
|
// the process starts in a directory of the server, the tasks work on the run's files
|
|
@@ -342,6 +348,10 @@ commands = getRunnerCommands(input, emit)) {
|
|
|
342
348
|
const execution = input.up
|
|
343
349
|
? cli.up({ ...execOptions, workers: cli.defaultWorkers(), daemon: false, wait: 'ready' })
|
|
344
350
|
: cli.exec({ ...execOptions, workers: cli.defaultWorkers() });
|
|
351
|
+
if (input.up) {
|
|
352
|
+
const up = input.up;
|
|
353
|
+
register?.((changes) => syncServices(workTree, up, changes));
|
|
354
|
+
}
|
|
345
355
|
const seen = new Map();
|
|
346
356
|
const failedServices = new Set();
|
|
347
357
|
let ready = false;
|
|
@@ -405,6 +415,9 @@ commands = getRunnerCommands(input, emit)) {
|
|
|
405
415
|
}
|
|
406
416
|
finally {
|
|
407
417
|
watch.close();
|
|
418
|
+
if (input.up) {
|
|
419
|
+
register?.(undefined);
|
|
420
|
+
}
|
|
408
421
|
if (input.up && input.kubernetes?.server?.serviceRun && !ready && service_rollouts_1.serviceRollouts.size > 0) {
|
|
409
422
|
// a move (or a start) whose services did not all get up: the run stays where it was
|
|
410
423
|
await service_rollouts_1.serviceRollouts.undo((0, kubernetes_instance_1.createKubernetesInstances)(input.kubernetes), (text) => emit({ type: 'log', task: 'hammerkit', stream: 'stderr', text }));
|
|
@@ -600,11 +613,126 @@ redact) {
|
|
|
600
613
|
}
|
|
601
614
|
}
|
|
602
615
|
}
|
|
616
|
+
/**
|
|
617
|
+
* Hands the files of a sandbox that changed to the services of a service run that are up:
|
|
618
|
+
* each one that takes files (its runtime says so) syncs them, and starts again when the run
|
|
619
|
+
* lists it in `restart`. The other services are not touched.
|
|
620
|
+
*/
|
|
621
|
+
async function syncServices(workTree, up, changes) {
|
|
622
|
+
// one service that fails does not hold back the others: they are all tried, and the failures
|
|
623
|
+
// are said together
|
|
624
|
+
const failed = [];
|
|
625
|
+
for (const service of Object.values(workTree.services)) {
|
|
626
|
+
if (!up.services.includes(service.name)) {
|
|
627
|
+
continue;
|
|
628
|
+
}
|
|
629
|
+
try {
|
|
630
|
+
await service.runtime.syncFiles?.({ ...changes, restart: (up.restart ?? []).includes(service.name) });
|
|
631
|
+
}
|
|
632
|
+
catch (e) {
|
|
633
|
+
failed.push(`${service.name}: ${(0, log_1.getErrorMessage)(e)}`);
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
if (failed.length > 0) {
|
|
637
|
+
throw new Error(`the changed files were not synced to ${failed.join('; ')}`);
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
exports.syncServices = syncServices;
|
|
641
|
+
// The line `sync <json>` the server writes for a batch of changes: the folder the batch is
|
|
642
|
+
// staged in (`staging`), which the batch folder must be inside to be removed after it
|
|
643
|
+
exports.syncLine = zod_1.z
|
|
644
|
+
.object({
|
|
645
|
+
staging: zod_1.z.string(),
|
|
646
|
+
changes: zod_1.z
|
|
647
|
+
.object({
|
|
648
|
+
dir: zod_1.z.string(),
|
|
649
|
+
written: zod_1.z.array(zod_1.z.string()),
|
|
650
|
+
deleted: zod_1.z.array(zod_1.z.string()),
|
|
651
|
+
restart: zod_1.z.boolean(),
|
|
652
|
+
})
|
|
653
|
+
.strict(),
|
|
654
|
+
})
|
|
655
|
+
.strict();
|
|
656
|
+
// The staging folder and the batch of a sync line, as far as they are named: what a refused line
|
|
657
|
+
// still names, so its batch can be removed (see applyChanges)
|
|
658
|
+
const batchOf = zod_1.z.object({ staging: zod_1.z.string(), changes: zod_1.z.object({ dir: zod_1.z.string() }) });
|
|
659
|
+
// Whether `path` is a folder inside `root`, not `root` itself
|
|
660
|
+
function isInside(root, path) {
|
|
661
|
+
const rel = (0, path_1.relative)((0, path_1.resolve)(root), (0, path_1.resolve)(path));
|
|
662
|
+
return rel !== '' && rel.split(path_1.sep)[0] !== '..' && !(0, path_1.isAbsolute)(rel);
|
|
663
|
+
}
|
|
664
|
+
exports.isInside = isInside;
|
|
665
|
+
/**
|
|
666
|
+
* Applies one batch of changes to the services that are up (`sync`). The batch folder goes
|
|
667
|
+
* afterwards, whatever came of it, but only when it is inside the staging folder. A line that
|
|
668
|
+
* does not parse is logged and nothing else is done.
|
|
669
|
+
*/
|
|
670
|
+
async function applyChanges(request, sync, log) {
|
|
671
|
+
let json;
|
|
672
|
+
try {
|
|
673
|
+
json = JSON.parse(request);
|
|
674
|
+
}
|
|
675
|
+
catch {
|
|
676
|
+
json = undefined;
|
|
677
|
+
}
|
|
678
|
+
const parsed = exports.syncLine.safeParse(json);
|
|
679
|
+
if (!parsed.success) {
|
|
680
|
+
log('the changed files of the sandbox could not be read');
|
|
681
|
+
// the batch is still the server's to see gone: a line that does not match names it loosely
|
|
682
|
+
const named = batchOf.safeParse(json);
|
|
683
|
+
if (named.success) {
|
|
684
|
+
await removeBatch(named.data.staging, (0, path_1.dirname)(named.data.changes.dir), log);
|
|
685
|
+
}
|
|
686
|
+
return;
|
|
687
|
+
}
|
|
688
|
+
const { staging, changes } = parsed.data;
|
|
689
|
+
const batch = (0, path_1.dirname)(changes.dir);
|
|
690
|
+
try {
|
|
691
|
+
if (!sync) {
|
|
692
|
+
log('no service of the run is up to take the changed files of the sandbox');
|
|
693
|
+
return;
|
|
694
|
+
}
|
|
695
|
+
await sync(changes);
|
|
696
|
+
}
|
|
697
|
+
catch (e) {
|
|
698
|
+
log(`the changed files of the sandbox could not be synced: ${(0, log_1.getErrorMessage)(e)}`);
|
|
699
|
+
}
|
|
700
|
+
finally {
|
|
701
|
+
await removeBatch(staging, batch, log);
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
exports.applyChanges = applyChanges;
|
|
705
|
+
// Removes a batch folder once it was applied or refused, when it is inside the staging folder
|
|
706
|
+
// of its run. Outside, it is left where it is: it is not the server's to remove.
|
|
707
|
+
async function removeBatch(staging, batch, log) {
|
|
708
|
+
if (!isInside(staging, batch)) {
|
|
709
|
+
log(`${batch} is not in the staging folder of the run, it is left where it is`);
|
|
710
|
+
return;
|
|
711
|
+
}
|
|
712
|
+
await (0, promises_1.rm)(batch, { recursive: true, force: true }).catch((e) => log(`${batch} could not be removed: ${(0, log_1.getErrorMessage)(e)}`));
|
|
713
|
+
}
|
|
714
|
+
/**
|
|
715
|
+
* The batches of changes of a run, applied one after another in the order they came. A batch
|
|
716
|
+
* that fails does not stop the ones after it.
|
|
717
|
+
*/
|
|
718
|
+
class ChangeQueue {
|
|
719
|
+
constructor(apply, fail) {
|
|
720
|
+
this.apply = apply;
|
|
721
|
+
this.fail = fail;
|
|
722
|
+
this.last = Promise.resolve();
|
|
723
|
+
}
|
|
724
|
+
push(request) {
|
|
725
|
+
this.last = this.last.then(() => this.apply(request)).catch((e) => this.fail(e));
|
|
726
|
+
return this.last;
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
exports.ChangeQueue = ChangeQueue;
|
|
603
730
|
// The run is the first line of the standard input. The server keeps it open and writes
|
|
604
731
|
// `cancel` on it to stop the run: that works the same on every platform, where a signal
|
|
605
|
-
// on Windows ends the process without letting it stop its tasks.
|
|
732
|
+
// on Windows ends the process without letting it stop its tasks. It writes `sync <json>` on
|
|
733
|
+
// it for the files of a sandbox that changed (FileChanges), which `sync` takes.
|
|
606
734
|
// `onEnd` is told when the input ends before the run does: the server is gone.
|
|
607
|
-
function readInput(stdin, cancel) {
|
|
735
|
+
function readInput(stdin, cancel, sync = () => undefined) {
|
|
608
736
|
const lines = (0, readline_1.createInterface)({ input: stdin, crlfDelay: Infinity });
|
|
609
737
|
let first;
|
|
610
738
|
let closing = false;
|
|
@@ -619,6 +747,9 @@ function readInput(stdin, cancel) {
|
|
|
619
747
|
else if (line.trim() === 'cancel') {
|
|
620
748
|
cancel();
|
|
621
749
|
}
|
|
750
|
+
else if (line.startsWith('sync ')) {
|
|
751
|
+
sync(line.slice('sync '.length));
|
|
752
|
+
}
|
|
622
753
|
});
|
|
623
754
|
lines.on('close', () => {
|
|
624
755
|
resolve(first ?? '');
|
|
@@ -658,7 +789,13 @@ async function workerMain(stdin, stdout, processEnvs, cwd, abortCtrl) {
|
|
|
658
789
|
};
|
|
659
790
|
const signals = ['SIGINT', 'SIGTERM', 'SIGHUP'];
|
|
660
791
|
signals.forEach((signal) => process.on(signal, stop));
|
|
661
|
-
|
|
792
|
+
// the changes of the sandbox, one batch after the other, for the services that are up
|
|
793
|
+
let sync;
|
|
794
|
+
const logLine = (text) => say({ kind: 'event', event: { type: 'log', task: 'hammerkit', stream: 'stderr', text } });
|
|
795
|
+
const batches = new ChangeQueue((request) => applyChanges(request, sync, logLine), (e) => logLine(`the changed files of the sandbox could not be synced: ${(0, log_1.getErrorMessage)(e)}`));
|
|
796
|
+
const reader = readInput(stdin, stop, (request) => {
|
|
797
|
+
void batches.push(request);
|
|
798
|
+
});
|
|
662
799
|
let input;
|
|
663
800
|
try {
|
|
664
801
|
input = exports.workerInputSchema.parse(JSON.parse(await reader.input));
|
|
@@ -684,7 +821,9 @@ async function workerMain(stdin, stdout, processEnvs, cwd, abortCtrl) {
|
|
|
684
821
|
try {
|
|
685
822
|
let result;
|
|
686
823
|
try {
|
|
687
|
-
await runTasks(input, cwd, processEnvs, abortCtrl, () => cancelled, emit, (targets) => say({ kind: 'up', targets }), commands)
|
|
824
|
+
await runTasks(input, cwd, processEnvs, abortCtrl, () => cancelled, emit, (targets) => say({ kind: 'up', targets }), commands, (handler) => {
|
|
825
|
+
sync = handler;
|
|
826
|
+
});
|
|
688
827
|
result = { kind: 'result', ok: true };
|
|
689
828
|
}
|
|
690
829
|
catch (e) {
|
package/dist/server/runs.js
CHANGED
|
@@ -711,6 +711,26 @@ class RunRegistry {
|
|
|
711
711
|
entry.run.state !== 'up' &&
|
|
712
712
|
entry.run.state !== 'asleep')?.run.id;
|
|
713
713
|
}
|
|
714
|
+
// The service runs of a sandbox that take its changed files: up, and not replaced or stopped
|
|
715
|
+
// (a run of the same name that replaces one stops it, and it is still up until it ended, so
|
|
716
|
+
// only the newest of a name syncs). A host's executor takes none: its sandbox's files are live.
|
|
717
|
+
upOn(sandbox) {
|
|
718
|
+
if (!this.options.executor.syncFiles) {
|
|
719
|
+
return [];
|
|
720
|
+
}
|
|
721
|
+
return [...this.entries.values()]
|
|
722
|
+
.filter((entry) => entry.run.state === 'up' && !entry.run.stoppedBy && onSandbox(entry.run, sandbox))
|
|
723
|
+
.map((entry) => this.copy(entry.run));
|
|
724
|
+
}
|
|
725
|
+
// Hands the changed files of a sandbox to the services of a service run that is up. False when
|
|
726
|
+
// the run is not known here, is stopped, or its executor can not take them.
|
|
727
|
+
syncFiles(id, changes) {
|
|
728
|
+
const entry = this.entries.get(id);
|
|
729
|
+
if (!entry || entry.run.stoppedBy) {
|
|
730
|
+
return false;
|
|
731
|
+
}
|
|
732
|
+
return this.options.executor.syncFiles?.(this.copy(entry.run), changes) ?? false;
|
|
733
|
+
}
|
|
714
734
|
// Cancels every run on a sandbox and resolves when none of them runs anymore.
|
|
715
735
|
async stopSandbox(sandbox, reason) {
|
|
716
736
|
const on = () => [...this.entries.values()].filter((entry) => onSandbox(entry.run, sandbox));
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SandboxFollow = void 0;
|
|
4
|
+
const log_1 = require("../log");
|
|
5
|
+
// How long a sandbox must stay unchanged before its service runs follow it, and how long
|
|
6
|
+
// they may wait while its files keep changing.
|
|
7
|
+
const DELAY_MS = 1000;
|
|
8
|
+
const MAX_WAIT_MS = 5000;
|
|
9
|
+
/**
|
|
10
|
+
* Batches the changes of each sandbox: a burst of edits (or of runs that wrote) makes one
|
|
11
|
+
* call of `follow` once the sandbox was quiet for `delay`, and at the latest `maxWait` after its
|
|
12
|
+
* first change, so a sandbox that never stops changing is still followed. Each sandbox has
|
|
13
|
+
* its own batch.
|
|
14
|
+
*/
|
|
15
|
+
class SandboxFollow {
|
|
16
|
+
constructor(options) {
|
|
17
|
+
this.options = options;
|
|
18
|
+
// per sandbox, the timer of its batch and when the batch began
|
|
19
|
+
this.batches = new Map();
|
|
20
|
+
this.closed = false;
|
|
21
|
+
this.delay = options.delay ?? DELAY_MS;
|
|
22
|
+
this.maxWait = options.maxWait ?? MAX_WAIT_MS;
|
|
23
|
+
}
|
|
24
|
+
changed(sandbox) {
|
|
25
|
+
if (this.closed) {
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
const now = Date.now();
|
|
29
|
+
const batch = this.batches.get(sandbox);
|
|
30
|
+
const since = batch?.since ?? now;
|
|
31
|
+
clearTimeout(batch?.timer);
|
|
32
|
+
const wait = Math.min(this.delay, since + this.maxWait - now);
|
|
33
|
+
const timer = setTimeout(() => this.run(sandbox), wait);
|
|
34
|
+
this.batches.set(sandbox, { timer, since });
|
|
35
|
+
}
|
|
36
|
+
close() {
|
|
37
|
+
this.closed = true;
|
|
38
|
+
for (const { timer } of this.batches.values()) {
|
|
39
|
+
clearTimeout(timer);
|
|
40
|
+
}
|
|
41
|
+
this.batches.clear();
|
|
42
|
+
}
|
|
43
|
+
async run(sandbox) {
|
|
44
|
+
this.batches.delete(sandbox);
|
|
45
|
+
try {
|
|
46
|
+
await this.options.follow(sandbox);
|
|
47
|
+
}
|
|
48
|
+
catch (e) {
|
|
49
|
+
this.options.log?.(`follow ${sandbox}: ${(0, log_1.getErrorMessage)(e)}`);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
exports.SandboxFollow = SandboxFollow;
|
|
54
|
+
//# sourceMappingURL=sandbox-follow.js.map
|
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SandboxSync = exports.unsafePath = exports.nextRetryMs = exports.MAX_BATCH_FILES = exports.MAX_BATCH_BYTES = void 0;
|
|
4
|
+
const fs_1 = require("fs");
|
|
5
|
+
const promises_1 = require("fs/promises");
|
|
6
|
+
const path_1 = require("path");
|
|
7
|
+
const promises_2 = require("stream/promises");
|
|
8
|
+
const log_1 = require("../log");
|
|
9
|
+
// the most bytes of files one batch stages; a larger change is not synced, and the log says so
|
|
10
|
+
exports.MAX_BATCH_BYTES = 128 * 1024 * 1024;
|
|
11
|
+
// the most files one batch stages
|
|
12
|
+
exports.MAX_BATCH_FILES = 10000;
|
|
13
|
+
// how deep a walk of the files of a sandbox goes (the API takes at most this)
|
|
14
|
+
const WALK_DEPTH = 64;
|
|
15
|
+
// how long a sync waits before it is tried again while a run has a batch its worker did not
|
|
16
|
+
// apply: the first wait, doubled on each try up to RETRY_MAX_MS
|
|
17
|
+
const RETRY_MS = 500;
|
|
18
|
+
const RETRY_MAX_MS = 10000;
|
|
19
|
+
// a batch staged that long ago and still not applied is stuck: it is removed, and sent again
|
|
20
|
+
const PENDING_MAX_MS = 5 * 60 * 1000;
|
|
21
|
+
/**
|
|
22
|
+
* How long the next retry of a sync waits, after one that waited `previous` ms (undefined for
|
|
23
|
+
* the first): `base` at first, then doubled up to RETRY_MAX_MS.
|
|
24
|
+
*/
|
|
25
|
+
function nextRetryMs(previous, base) {
|
|
26
|
+
return previous === undefined ? Math.min(base, RETRY_MAX_MS) : Math.min(previous * 2, RETRY_MAX_MS);
|
|
27
|
+
}
|
|
28
|
+
exports.nextRetryMs = nextRetryMs;
|
|
29
|
+
// a batch with more than MAX_BATCH_BYTES or MAX_BATCH_FILES is not staged at all
|
|
30
|
+
class BatchTooLargeError extends Error {
|
|
31
|
+
constructor() {
|
|
32
|
+
super(`the changes are more than ${exports.MAX_BATCH_FILES} files or ${exports.MAX_BATCH_BYTES} bytes, the services keep their files`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Why a path of the sandbox can not be a path of a service's folder, or none. A name with a
|
|
37
|
+
* control character (a newline in particular), an absolute path or a `.` or `..` segment is refused.
|
|
38
|
+
*/
|
|
39
|
+
function unsafePath(path) {
|
|
40
|
+
if (path === '') {
|
|
41
|
+
return 'it is empty';
|
|
42
|
+
}
|
|
43
|
+
if ([...path].some((char) => char.charCodeAt(0) < 0x20 || char.charCodeAt(0) === 0x7f)) {
|
|
44
|
+
return 'it has a control character';
|
|
45
|
+
}
|
|
46
|
+
if (path.startsWith('/') || /^[A-Za-z]:/.test(path)) {
|
|
47
|
+
return 'it is not relative to the sandbox';
|
|
48
|
+
}
|
|
49
|
+
if (path.split('/').some((segment) => segment === '..' || segment === '.')) {
|
|
50
|
+
return 'it has a . or .. segment';
|
|
51
|
+
}
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
exports.unsafePath = unsafePath;
|
|
55
|
+
/**
|
|
56
|
+
* Keeps the services of the service runs on a sandbox in step with its files. Each change of the
|
|
57
|
+
* sandbox (batched by SandboxFollow) goes to each run that is up, as the files that changed: the
|
|
58
|
+
* ones that differ from the commit now, and the ones that differed when the services last got
|
|
59
|
+
* their files, which may be back at the commit by now. A run without that record (the server
|
|
60
|
+
* started since it did) gets every file of the sandbox once. Nothing else of the services is
|
|
61
|
+
* touched, and nothing is restarted here.
|
|
62
|
+
*/
|
|
63
|
+
class SandboxSync {
|
|
64
|
+
constructor(options) {
|
|
65
|
+
this.options = options;
|
|
66
|
+
// per run, the paths that may differ from the commit since the services last got the files
|
|
67
|
+
this.differing = new Map();
|
|
68
|
+
// the batches of each sandbox, one after another
|
|
69
|
+
this.queues = new Map();
|
|
70
|
+
// the batch of each sandbox that waits to start: it reads the files when it starts, so a
|
|
71
|
+
// change that comes meanwhile is in it too
|
|
72
|
+
this.waiting = new Map();
|
|
73
|
+
this.batch = 0;
|
|
74
|
+
// the retry of a sandbox's sync that waits for a batch a run did not apply yet, and how long
|
|
75
|
+
// the last one waited
|
|
76
|
+
this.retries = new Map();
|
|
77
|
+
this.retryDelays = new Map();
|
|
78
|
+
// the runs that were told their changed files are over the cap, once each
|
|
79
|
+
this.overCap = new Set();
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* A service run starts from a copy of the files now: what differs from the commit in the copy
|
|
83
|
+
* is what the services have from the start, and what a later change has to include.
|
|
84
|
+
*/
|
|
85
|
+
async started(run) {
|
|
86
|
+
if (run.source.type !== 'sandbox') {
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
this.differing.set(run.id, await this.changedOf(this.options.files(run.owner, run.source.id)));
|
|
90
|
+
}
|
|
91
|
+
// Stops the retries of the syncs that wait for a batch to be applied: nothing is synced after it
|
|
92
|
+
close() {
|
|
93
|
+
for (const timer of this.retries.values()) {
|
|
94
|
+
clearTimeout(timer);
|
|
95
|
+
}
|
|
96
|
+
this.retries.clear();
|
|
97
|
+
this.retryDelays.clear();
|
|
98
|
+
}
|
|
99
|
+
// A run that ended: nothing is synced for it any more, and what was staged for it goes
|
|
100
|
+
async forget(run) {
|
|
101
|
+
this.differing.delete(run);
|
|
102
|
+
for (const key of [...this.overCap]) {
|
|
103
|
+
if (key.startsWith(`${run}/`)) {
|
|
104
|
+
this.overCap.delete(key);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
await this.remove((0, path_1.join)(this.options.stagingRoot, run));
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* At server start: what a server that stopped staged is no batch of any run now, so the
|
|
111
|
+
* staging folder goes.
|
|
112
|
+
*/
|
|
113
|
+
async sweep() {
|
|
114
|
+
await this.remove(this.options.stagingRoot);
|
|
115
|
+
}
|
|
116
|
+
// The batch of changes of a sandbox, after the ones before it. One that waits already has the
|
|
117
|
+
// newest files when it starts, so a second one is not queued behind it.
|
|
118
|
+
follow(sandbox) {
|
|
119
|
+
const waiting = this.waiting.get(sandbox);
|
|
120
|
+
if (waiting) {
|
|
121
|
+
return waiting;
|
|
122
|
+
}
|
|
123
|
+
const previous = this.queues.get(sandbox) ?? Promise.resolve();
|
|
124
|
+
const next = previous
|
|
125
|
+
.then(() => {
|
|
126
|
+
this.waiting.delete(sandbox);
|
|
127
|
+
return this.sync(sandbox);
|
|
128
|
+
})
|
|
129
|
+
.catch((e) => this.log(`sync sandbox ${sandbox}: ${(0, log_1.getErrorMessage)(e)}`));
|
|
130
|
+
this.waiting.set(sandbox, next);
|
|
131
|
+
this.queues.set(sandbox, next);
|
|
132
|
+
void next.then(() => {
|
|
133
|
+
if (this.queues.get(sandbox) === next) {
|
|
134
|
+
this.queues.delete(sandbox);
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
return next;
|
|
138
|
+
}
|
|
139
|
+
async sync(sandbox) {
|
|
140
|
+
const runs = this.options.upOn(sandbox);
|
|
141
|
+
if (runs.length === 0) {
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
// the files of a sandbox are one owner's: a run of another owner would read them as theirs
|
|
145
|
+
const [{ owner }] = runs;
|
|
146
|
+
if (runs.some((run) => run.owner.iss !== owner.iss || run.owner.sub !== owner.sub)) {
|
|
147
|
+
throw new Error(`the service runs on ${sandbox} have more than one owner, their changes are not synced`);
|
|
148
|
+
}
|
|
149
|
+
const files = this.options.files(owner, sandbox);
|
|
150
|
+
const changed = await this.changedOf(files);
|
|
151
|
+
for (const run of runs) {
|
|
152
|
+
const known = this.differing.get(run.id);
|
|
153
|
+
if (await this.pending(run.id)) {
|
|
154
|
+
// the worker has not applied the last batch of the run: these paths go with the next one
|
|
155
|
+
if (known) {
|
|
156
|
+
this.differing.set(run.id, new Set([...known, ...changed]));
|
|
157
|
+
}
|
|
158
|
+
this.retryLater(sandbox);
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
await this.sendTo(run, sandbox, files, known, changed);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Whether the worker of a run has not applied a batch yet: the worker removes a batch once it
|
|
166
|
+
* applied it. A batch staged longer than PENDING_MAX_MS ago is stuck (a worker that failed to
|
|
167
|
+
* remove it): it is removed here, and the changes are sent again with a fresh batch.
|
|
168
|
+
*/
|
|
169
|
+
async pending(run) {
|
|
170
|
+
const folder = (0, path_1.join)(this.options.stagingRoot, run);
|
|
171
|
+
let pending = false;
|
|
172
|
+
for (const batch of await (0, promises_1.readdir)(folder).catch(() => [])) {
|
|
173
|
+
const path = (0, path_1.join)(folder, batch);
|
|
174
|
+
const modified = await (0, promises_1.stat)(path).then((found) => found.mtimeMs, () => Date.now());
|
|
175
|
+
if (Date.now() - modified > PENDING_MAX_MS) {
|
|
176
|
+
this.log(`the batch ${batch} of ${run} was not applied in five minutes, it is removed and sent again`);
|
|
177
|
+
await this.remove(path);
|
|
178
|
+
}
|
|
179
|
+
else {
|
|
180
|
+
pending = true;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
return pending;
|
|
184
|
+
}
|
|
185
|
+
// Tries the sync of a sandbox again later, once: the batch of a run that is pending goes then.
|
|
186
|
+
// Each try waits longer than the one before, up to RETRY_MAX_MS, until a batch is sent.
|
|
187
|
+
retryLater(sandbox) {
|
|
188
|
+
if (this.retries.has(sandbox)) {
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
const delay = nextRetryMs(this.retryDelays.get(sandbox), this.options.retryMs ?? RETRY_MS);
|
|
192
|
+
this.retryDelays.set(sandbox, delay);
|
|
193
|
+
const timer = setTimeout(() => {
|
|
194
|
+
this.retries.delete(sandbox);
|
|
195
|
+
void this.follow(sandbox);
|
|
196
|
+
}, delay);
|
|
197
|
+
timer.unref?.();
|
|
198
|
+
this.retries.set(sandbox, timer);
|
|
199
|
+
}
|
|
200
|
+
// Says once per run and kind that its changed files are over the cap
|
|
201
|
+
logOverCap(run, kind, line) {
|
|
202
|
+
const key = `${run}/${kind}`;
|
|
203
|
+
if (!this.overCap.has(key)) {
|
|
204
|
+
this.overCap.add(key);
|
|
205
|
+
this.log(line);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Stages and sends the batch of one run. Without a record of what the services have, every
|
|
210
|
+
* file of the sandbox goes. A batch over the caps is not staged: then only the changed paths
|
|
211
|
+
* go, which may leave a file reverted to the commit stale, and they are the record from now.
|
|
212
|
+
*/
|
|
213
|
+
async sendTo(run, sandbox, files, known, changed) {
|
|
214
|
+
// no record of what the services have: every file may differ from what they got
|
|
215
|
+
let paths = known ? new Set([...known, ...changed]) : new Set([...(await this.allFiles(files)), ...changed]);
|
|
216
|
+
let changes;
|
|
217
|
+
try {
|
|
218
|
+
changes = await this.stage(run.id, files, [...paths]);
|
|
219
|
+
}
|
|
220
|
+
catch (e) {
|
|
221
|
+
if (!(e instanceof BatchTooLargeError)) {
|
|
222
|
+
this.log(`the changes of ${sandbox} are not synced to ${run.id}: ${(0, log_1.getErrorMessage)(e)}`);
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
this.logOverCap(run.id, 'more', `the files of ${sandbox} are more than a batch takes, ${run.id} gets the changed files only: a file reverted to the commit may be stale`);
|
|
226
|
+
paths = changed;
|
|
227
|
+
try {
|
|
228
|
+
changes = await this.stage(run.id, files, [...paths]);
|
|
229
|
+
}
|
|
230
|
+
catch (again) {
|
|
231
|
+
if (!(again instanceof BatchTooLargeError)) {
|
|
232
|
+
this.log(`the changes of ${sandbox} are not synced to ${run.id}: ${(0, log_1.getErrorMessage)(again)}`);
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
// the changed files alone are over the cap: they are the record from now, and nothing is sent
|
|
236
|
+
this.logOverCap(run.id, 'alone', `the changed files of ${sandbox} alone are more than a batch takes: ${run.id} gets none of them, they are its baseline`);
|
|
237
|
+
this.differing.set(run.id, changed);
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
if (!changes) {
|
|
242
|
+
this.differing.set(run.id, changed);
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
if (this.options.send(run.id, changes)) {
|
|
246
|
+
this.differing.set(run.id, changed);
|
|
247
|
+
// a batch went: the next wait starts short again
|
|
248
|
+
this.retryDelays.delete(sandbox);
|
|
249
|
+
}
|
|
250
|
+
else {
|
|
251
|
+
// the services did not take them: the next batch has them still
|
|
252
|
+
this.differing.set(run.id, paths);
|
|
253
|
+
await this.remove((0, path_1.dirname)(changes.dir));
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
log(line) {
|
|
257
|
+
this.options.log?.(line);
|
|
258
|
+
}
|
|
259
|
+
async remove(path) {
|
|
260
|
+
await (0, promises_1.rm)(path, { recursive: true, force: true }).catch((e) => this.log(`the staged changes in ${path} could not be removed: ${(0, log_1.getErrorMessage)(e)}`));
|
|
261
|
+
}
|
|
262
|
+
async changedOf(files) {
|
|
263
|
+
const paths = new Set();
|
|
264
|
+
for (const change of await files.changes()) {
|
|
265
|
+
paths.add(change.path);
|
|
266
|
+
if (change.from) {
|
|
267
|
+
paths.add(change.from);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
return paths;
|
|
271
|
+
}
|
|
272
|
+
// every file of the sandbox, page by page
|
|
273
|
+
async allFiles(files) {
|
|
274
|
+
const paths = [];
|
|
275
|
+
let cursor;
|
|
276
|
+
do {
|
|
277
|
+
const page = await files.tree({ depth: WALK_DEPTH, limit: 1000, cursor });
|
|
278
|
+
for (const entry of page.entries) {
|
|
279
|
+
if (entry.type === 'file') {
|
|
280
|
+
paths.push(entry.path);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
cursor = page.truncated && page.cursor ? page.cursor : undefined;
|
|
284
|
+
} while (cursor);
|
|
285
|
+
return paths;
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Writes the files of `paths` that are there now into a folder of the batch, and says which
|
|
289
|
+
* paths are gone. A path that is unsafe, or whose file can not be read, is skipped and logged;
|
|
290
|
+
* the rest is synced. Undefined when none of the paths is left to say. Throws when the batch is
|
|
291
|
+
* too large, before anything is written: the sizes are summed first.
|
|
292
|
+
*/
|
|
293
|
+
async stage(run, files, paths) {
|
|
294
|
+
const writes = [];
|
|
295
|
+
const deleted = [];
|
|
296
|
+
let bytes = 0;
|
|
297
|
+
for (const path of paths) {
|
|
298
|
+
const problem = unsafePath(path);
|
|
299
|
+
if (problem) {
|
|
300
|
+
this.log(`skipped ${JSON.stringify(path)} of the sandbox: ${problem}`);
|
|
301
|
+
continue;
|
|
302
|
+
}
|
|
303
|
+
try {
|
|
304
|
+
const stat = await files.stat(path);
|
|
305
|
+
if (stat?.type !== 'file') {
|
|
306
|
+
deleted.push(path);
|
|
307
|
+
continue;
|
|
308
|
+
}
|
|
309
|
+
bytes += stat.size;
|
|
310
|
+
writes.push({ path, exec: stat.exec });
|
|
311
|
+
}
|
|
312
|
+
catch (e) {
|
|
313
|
+
this.log(`skipped ${JSON.stringify(path)} of the sandbox: ${(0, log_1.getErrorMessage)(e)}`);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
if (writes.length > exports.MAX_BATCH_FILES || bytes > exports.MAX_BATCH_BYTES) {
|
|
317
|
+
throw new BatchTooLargeError();
|
|
318
|
+
}
|
|
319
|
+
const folder = (0, path_1.join)(this.options.stagingRoot, run, `${++this.batch}`);
|
|
320
|
+
const dir = (0, path_1.join)(folder, 'files');
|
|
321
|
+
const written = [];
|
|
322
|
+
try {
|
|
323
|
+
for (const { path, exec } of writes) {
|
|
324
|
+
try {
|
|
325
|
+
const raw = await files.raw(path);
|
|
326
|
+
const target = (0, path_1.join)(dir, path);
|
|
327
|
+
await (0, promises_1.mkdir)((0, path_1.dirname)(target), { recursive: true });
|
|
328
|
+
if (raw.content) {
|
|
329
|
+
await (0, promises_1.writeFile)(target, raw.content);
|
|
330
|
+
}
|
|
331
|
+
else if (raw.stream) {
|
|
332
|
+
await (0, promises_2.pipeline)(raw.stream, (0, fs_1.createWriteStream)(target));
|
|
333
|
+
}
|
|
334
|
+
// the exec bit is kept: a script the services run is still executable after the sync
|
|
335
|
+
await (0, promises_1.chmod)(target, exec ? 0o755 : 0o644);
|
|
336
|
+
written.push(path);
|
|
337
|
+
}
|
|
338
|
+
catch (e) {
|
|
339
|
+
// a file that changed or can not be read: the next batch brings it
|
|
340
|
+
this.log(`skipped ${JSON.stringify(path)} of the sandbox: ${(0, log_1.getErrorMessage)(e)}`);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
if (written.length + deleted.length === 0) {
|
|
344
|
+
await this.remove(folder);
|
|
345
|
+
return undefined;
|
|
346
|
+
}
|
|
347
|
+
await (0, promises_1.mkdir)(dir, { recursive: true });
|
|
348
|
+
return { dir, written, deleted, restart: false };
|
|
349
|
+
}
|
|
350
|
+
catch (e) {
|
|
351
|
+
await this.remove(folder);
|
|
352
|
+
throw e;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
exports.SandboxSync = SandboxSync;
|
|
357
|
+
//# sourceMappingURL=sandbox-sync.js.map
|
package/dist/server/sandboxes.js
CHANGED
|
@@ -41,6 +41,8 @@ class SandboxRegistry {
|
|
|
41
41
|
// the measures of runs that are over, which a run's result does not wait for
|
|
42
42
|
this.measuring = new Map();
|
|
43
43
|
this.locks = new Map();
|
|
44
|
+
// what hears of the files of a sandbox changing: an edit, or a run that wrote to them
|
|
45
|
+
this.listeners = new Set();
|
|
44
46
|
this.runs = { holder: () => undefined, stop: async () => undefined };
|
|
45
47
|
this.now = options.now ?? Date.now;
|
|
46
48
|
}
|
|
@@ -48,6 +50,16 @@ class SandboxRegistry {
|
|
|
48
50
|
useRuns(runs) {
|
|
49
51
|
this.runs = runs;
|
|
50
52
|
}
|
|
53
|
+
// Calls `listener` with the id of a sandbox whose files may have changed: after each edit,
|
|
54
|
+
// and after each run that wrote to them (measure). It may come when nothing changed.
|
|
55
|
+
onChange(listener) {
|
|
56
|
+
this.listeners.add(listener);
|
|
57
|
+
}
|
|
58
|
+
changed(id) {
|
|
59
|
+
for (const listener of this.listeners) {
|
|
60
|
+
listener(id);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
51
63
|
get limits() {
|
|
52
64
|
return this.options.limits;
|
|
53
65
|
}
|
|
@@ -460,6 +472,7 @@ class SandboxRegistry {
|
|
|
460
472
|
sandbox.bytes = Math.max(0, sandbox.bytes + plan.bytes);
|
|
461
473
|
sandbox.lastUsedAt = this.timestamp();
|
|
462
474
|
await this.save(sandbox);
|
|
475
|
+
this.changed(id);
|
|
463
476
|
return plan.files;
|
|
464
477
|
});
|
|
465
478
|
}
|
|
@@ -493,6 +506,7 @@ class SandboxRegistry {
|
|
|
493
506
|
}
|
|
494
507
|
sandbox.bytes = await this.options.storage.usage(keyOf(sandbox));
|
|
495
508
|
await this.save(sandbox);
|
|
509
|
+
this.changed(id);
|
|
496
510
|
});
|
|
497
511
|
const settled = measure.catch(() => undefined);
|
|
498
512
|
this.measuring.set(id, settled);
|
package/dist/server/server.js
CHANGED
|
@@ -35,6 +35,8 @@ const proposals_api_1 = require("./proposals-api");
|
|
|
35
35
|
const proposals_1 = require("./proposals");
|
|
36
36
|
const sources_1 = require("./sources");
|
|
37
37
|
const sources_api_1 = require("./sources-api");
|
|
38
|
+
const sandbox_follow_1 = require("./sandbox-follow");
|
|
39
|
+
const sandbox_sync_1 = require("./sandbox-sync");
|
|
38
40
|
const sandboxes_1 = require("./sandboxes");
|
|
39
41
|
const sandbox_storage_1 = require("./sandbox-storage");
|
|
40
42
|
const kubernetes_sandbox_storage_1 = require("./kubernetes-sandbox-storage");
|
|
@@ -480,6 +482,14 @@ async function startRun(config, registry, definitions, sources, sandboxes, plann
|
|
|
480
482
|
(0, http_2.send)(res, 400, { error: 'sleepTtl: a service run from a sandbox does not sleep, start it from a branch' });
|
|
481
483
|
return;
|
|
482
484
|
}
|
|
485
|
+
// only a Kubernetes backend syncs the changed files of a sandbox into the services; a host
|
|
486
|
+
// runs them on the sandbox's own files, so a restart would do nothing there
|
|
487
|
+
if (request.restart?.length && config.backend.type !== 'kubernetes') {
|
|
488
|
+
(0, http_2.send)(res, 400, {
|
|
489
|
+
error: `restart: this server (backend ${config.backend.type}) has no file sync, a host's services run on the sandbox's files`,
|
|
490
|
+
});
|
|
491
|
+
return;
|
|
492
|
+
}
|
|
483
493
|
const sleepTtlText = request.source.type === 'ref' ? request.sleepTtl ?? config.runs.up.sleepTtl : undefined;
|
|
484
494
|
const sleepTtl = request.services.length > 0 && sleepTtlText ? (0, units_1.parseDuration)(sleepTtlText) : undefined;
|
|
485
495
|
const argued = (request.options.args ?? []).length > 0 ? request.tasks[0] : undefined;
|
|
@@ -503,12 +513,6 @@ async function startRun(config, registry, definitions, sources, sandboxes, plann
|
|
|
503
513
|
return;
|
|
504
514
|
}
|
|
505
515
|
}
|
|
506
|
-
if (request.services.length > 0 && request.source.type === 'sandbox' && config.backend.type === 'kubernetes') {
|
|
507
|
-
(0, http_2.send)(res, 400, {
|
|
508
|
-
error: 'on a cluster a service run starts from a branch, push the sandbox and start it from there',
|
|
509
|
-
});
|
|
510
|
-
return;
|
|
511
|
-
}
|
|
512
516
|
const sandbox = request.source.type === 'sandbox' ? sandboxes.registry.get(principal, request.source.id) : undefined;
|
|
513
517
|
if (request.source.type === 'sandbox') {
|
|
514
518
|
if (!sandbox) {
|
|
@@ -659,6 +663,7 @@ async function startRun(config, registry, definitions, sources, sandboxes, plann
|
|
|
659
663
|
...(sleepTtl ? { sleepTtl } : {}),
|
|
660
664
|
name: serviceName,
|
|
661
665
|
endpoints: (0, service_runs_1.toRunEndpoints)(request.endpoints, (0, service_runs_1.getEndpointHosts)(serviceName, principal, request.endpoints), endpointUrl),
|
|
666
|
+
...(request.restart?.length ? { restart: request.restart } : {}),
|
|
662
667
|
}
|
|
663
668
|
: undefined;
|
|
664
669
|
// a run that may sleep keeps what its owner is entitled by, for the check of a wake
|
|
@@ -1001,6 +1006,18 @@ async function startServer(config, environment, options = {}) {
|
|
|
1001
1006
|
}
|
|
1002
1007
|
// a local task of a host runs as the user of this server: what it can write is never served
|
|
1003
1008
|
const localTasksOnHost = config.backend.type === 'host' && config.runtimes.includes('local');
|
|
1009
|
+
// a service run from a sandbox on a cluster gets the changed files of the sandbox into its
|
|
1010
|
+
// services, batched (SandboxFollow), as the changes that differ from the commit
|
|
1011
|
+
const sandboxSyncStaging = (0, path_1.join)(storage, 'sandboxes', 'sync');
|
|
1012
|
+
const sandboxSync = new sandbox_sync_1.SandboxSync({
|
|
1013
|
+
files: (owner, id) => sandboxes.registry.files(owner, id),
|
|
1014
|
+
upOn: (id) => registry.upOn(id),
|
|
1015
|
+
send: (run, changes) => registry.syncFiles(run, changes),
|
|
1016
|
+
stagingRoot: sandboxSyncStaging,
|
|
1017
|
+
log,
|
|
1018
|
+
});
|
|
1019
|
+
// what a server that stopped staged is no batch of any run now
|
|
1020
|
+
await sandboxSync.sweep();
|
|
1004
1021
|
const executorOptions = {
|
|
1005
1022
|
definitions,
|
|
1006
1023
|
planning,
|
|
@@ -1008,7 +1025,13 @@ async function startServer(config, environment, options = {}) {
|
|
|
1008
1025
|
directory: (0, path_1.join)(storage, 'runs'),
|
|
1009
1026
|
cache: (0, path_1.join)(storage, 'cache'),
|
|
1010
1027
|
worker: options.worker,
|
|
1011
|
-
sandboxes: {
|
|
1028
|
+
sandboxes: {
|
|
1029
|
+
...sandboxes,
|
|
1030
|
+
network: config.sandboxes.network,
|
|
1031
|
+
started: async (run) => sandboxSync.started(run),
|
|
1032
|
+
ended: async (run) => sandboxSync.forget(run.id),
|
|
1033
|
+
staging: sandboxSyncStaging,
|
|
1034
|
+
},
|
|
1012
1035
|
localTasksOnHost,
|
|
1013
1036
|
...(config.backend.type === 'host' && config.backend.capabilities
|
|
1014
1037
|
? { capabilityRuntime: config.backend.capabilities.runtime }
|
|
@@ -1132,6 +1155,13 @@ async function startServer(config, environment, options = {}) {
|
|
|
1132
1155
|
holder: (id) => registry.holder(id),
|
|
1133
1156
|
stop: (id) => registry.stopSandbox(id, 'the sandbox was deleted'),
|
|
1134
1157
|
});
|
|
1158
|
+
// A service run from a sandbox follows the files of the sandbox: a burst of edits or runs that
|
|
1159
|
+
// wrote is synced once, when the sandbox has been quiet for a moment (SandboxFollow)
|
|
1160
|
+
const follower = new sandbox_follow_1.SandboxFollow({
|
|
1161
|
+
follow: (id) => sandboxSync.follow(id),
|
|
1162
|
+
log: (line) => log(`follow ${line}`),
|
|
1163
|
+
});
|
|
1164
|
+
sandboxes.registry.onChange((id) => follower.changed(id));
|
|
1135
1165
|
const listener = (req, res) => {
|
|
1136
1166
|
handle(api, verifier, req, res).catch((e) => {
|
|
1137
1167
|
if (e instanceof http_2.HttpError) {
|
|
@@ -1227,6 +1257,8 @@ async function startServer(config, environment, options = {}) {
|
|
|
1227
1257
|
clearInterval(sweeping);
|
|
1228
1258
|
clearInterval(sweepingArtifacts);
|
|
1229
1259
|
proposals.close();
|
|
1260
|
+
follower.close();
|
|
1261
|
+
sandboxSync.close();
|
|
1230
1262
|
await registry.close();
|
|
1231
1263
|
await new Promise((resolve, reject) => {
|
|
1232
1264
|
server.close((err) => (err ? reject(err) : resolve()));
|
package/package.json
CHANGED