hammerkit 2.0.0-next.8 → 2.0.0-next.9
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/kubernetes/follow-pod-logs.js +5 -3
- package/dist/parser/read-build-file.js +8 -3
- package/dist/planner/utils/template-value.js +20 -4
- package/dist/schema/schema-parser.js +46 -2
- package/dist/server/kubernetes-sandbox-storage.js +14 -4
- package/dist/server/sandbox-files.js +107 -16
- package/dist/server/sandbox-patch.js +43 -17
- package/dist/server/sandboxes.js +57 -23
- package/dist/server/sources.js +68 -11
- package/dist/utils/buffer-context.js +30 -20
- package/dist/utils/read-lines.js +65 -0
- package/package.json +1 -1
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.followPodLogs = void 0;
|
|
3
|
+
exports.followPodLogs = exports.MAX_LOG_LINE_CHARS = void 0;
|
|
4
4
|
const stream_1 = require("stream");
|
|
5
|
-
const readline_1 = require("readline");
|
|
6
5
|
const log_1 = require("../log");
|
|
6
|
+
const read_lines_1 = require("../utils/read-lines");
|
|
7
7
|
// what is read of an instance of a container that already ended
|
|
8
8
|
const MAX_ENDED_LOG_BYTES = 1024 * 1024;
|
|
9
9
|
// how often in a row the log of one instance is read again after its reading broke off at once
|
|
10
10
|
const MAX_READS = 20;
|
|
11
|
+
// the most of one line of a followed log that is held, its timestamp included
|
|
12
|
+
exports.MAX_LOG_LINE_CHARS = 64 * 1024;
|
|
11
13
|
// `timestamps: true` puts the time a line was written before it (RFC3339 with up to nine
|
|
12
14
|
// digits of a second), which says where a log that broke off got to
|
|
13
15
|
const TIMESTAMPED = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?Z(?: (.*))?$/;
|
|
@@ -137,7 +139,7 @@ function followPodLogs(instance, namespace, labelSelector, container, onLine, op
|
|
|
137
139
|
end();
|
|
138
140
|
}));
|
|
139
141
|
output.on('end', end);
|
|
140
|
-
(0,
|
|
142
|
+
(0, read_lines_1.readLines)(output, exports.MAX_LOG_LINE_CHARS, reader(position));
|
|
141
143
|
streaming++;
|
|
142
144
|
let controller;
|
|
143
145
|
try {
|
|
@@ -1,12 +1,17 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.read = exports.write = void 0;
|
|
3
|
+
exports.readSized = exports.read = exports.write = void 0;
|
|
4
4
|
const yaml_1 = require("yaml");
|
|
5
5
|
async function write(filename, content, context) {
|
|
6
6
|
await context.file.writeFile(filename, (0, yaml_1.stringify)(content));
|
|
7
7
|
}
|
|
8
8
|
exports.write = write;
|
|
9
9
|
async function read(fileName, context) {
|
|
10
|
+
return (await readSized(fileName, context)).value;
|
|
11
|
+
}
|
|
12
|
+
exports.read = read;
|
|
13
|
+
// The parsed file and the bytes it took.
|
|
14
|
+
async function readSized(fileName, context) {
|
|
10
15
|
context.status.context({ type: 'cli', name: 'hammerkit' }).write('debug', `read ${fileName} build file`);
|
|
11
16
|
let content;
|
|
12
17
|
try {
|
|
@@ -16,7 +21,7 @@ async function read(fileName, context) {
|
|
|
16
21
|
throw new Error(`unable to read ${fileName}`);
|
|
17
22
|
}
|
|
18
23
|
try {
|
|
19
|
-
return (0, yaml_1.parse)(content);
|
|
24
|
+
return { value: (0, yaml_1.parse)(content), bytes: Buffer.byteLength(content, 'utf8') };
|
|
20
25
|
}
|
|
21
26
|
catch (e) {
|
|
22
27
|
if (e instanceof Error) {
|
|
@@ -27,5 +32,5 @@ async function read(fileName, context) {
|
|
|
27
32
|
}
|
|
28
33
|
}
|
|
29
34
|
}
|
|
30
|
-
exports.
|
|
35
|
+
exports.readSized = readSized;
|
|
31
36
|
//# sourceMappingURL=read-build-file.js.map
|
|
@@ -5,11 +5,27 @@ function templateValue(value, envs) {
|
|
|
5
5
|
if (!value || !envs) {
|
|
6
6
|
return value;
|
|
7
7
|
}
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
8
|
+
// A name is matched as the text it is, in any case; when two names match the same `$`, the
|
|
9
|
+
// one listed first wins. One pass over the value: a value put in is not read again.
|
|
10
|
+
const names = Object.keys(envs.variables).filter((name) => name.length > 0);
|
|
11
|
+
if (names.length === 0) {
|
|
12
|
+
return value;
|
|
13
|
+
}
|
|
14
|
+
const values = new Map();
|
|
15
|
+
for (const name of names) {
|
|
16
|
+
const key = name.toLowerCase();
|
|
17
|
+
if (!values.has(key)) {
|
|
18
|
+
values.set(key, envs.variables[name]);
|
|
19
|
+
}
|
|
11
20
|
}
|
|
12
|
-
|
|
21
|
+
const alternatives = names.map(escapeRegExp).join('|');
|
|
22
|
+
const pattern = new RegExp(`\\$\\{(${alternatives})\\}|\\$(${alternatives})`, 'gi');
|
|
23
|
+
return value.replace(pattern, (match, braced, bare) => {
|
|
24
|
+
return values.get((braced ?? bare ?? '').toLowerCase()) ?? match;
|
|
25
|
+
});
|
|
13
26
|
}
|
|
14
27
|
exports.templateValue = templateValue;
|
|
28
|
+
function escapeRegExp(text) {
|
|
29
|
+
return text.replace(/[\\^$.*+?()[\]{}|/-]/g, '\\$&');
|
|
30
|
+
}
|
|
15
31
|
//# sourceMappingURL=template-value.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.appendBuildFile = exports.createParseContext = void 0;
|
|
3
|
+
exports.appendBuildFile = exports.MAX_BUILD_FILE_ITEMS = exports.MAX_BUILD_FILE_BYTES = exports.MAX_INCLUDE_INPUT_BYTES = exports.MAX_BUILD_FILES = exports.MAX_INCLUDE_DEPTH = exports.createParseContext = void 0;
|
|
4
4
|
const build_file_schema_1 = require("./build-file-schema");
|
|
5
5
|
const read_build_file_1 = require("../parser/read-build-file");
|
|
6
6
|
const path_1 = require("path");
|
|
@@ -20,6 +20,17 @@ async function createParseContext(fileName, environment, options) {
|
|
|
20
20
|
return { ctx, scope };
|
|
21
21
|
}
|
|
22
22
|
exports.createParseContext = createParseContext;
|
|
23
|
+
// How deep includes and references may nest, how many build files one parse may read (a
|
|
24
|
+
// file included with other inputs counts again), and how large the inputs one include
|
|
25
|
+
// passes on may be. A file that includes itself with inputs that change each time ends at
|
|
26
|
+
// these instead of reading on without end.
|
|
27
|
+
exports.MAX_INCLUDE_DEPTH = 32;
|
|
28
|
+
exports.MAX_BUILD_FILES = 1000;
|
|
29
|
+
exports.MAX_INCLUDE_INPUT_BYTES = 64 * 1024;
|
|
30
|
+
// What the build files of one parse may take together, and how many tasks and services they
|
|
31
|
+
// may declare, a file included again counted again.
|
|
32
|
+
exports.MAX_BUILD_FILE_BYTES = 16 * 1024 * 1024;
|
|
33
|
+
exports.MAX_BUILD_FILE_ITEMS = 10000;
|
|
23
34
|
async function appendBuildFile(cwd, ctx, environment, fileName, namePrefix, remote, inputs,
|
|
24
35
|
// on a server: the file is included with `publish: false`, or below such an include
|
|
25
36
|
leftOut = false) {
|
|
@@ -30,12 +41,26 @@ leftOut = false) {
|
|
|
30
41
|
if (ctx.files[key]) {
|
|
31
42
|
return ctx.files[key];
|
|
32
43
|
}
|
|
33
|
-
|
|
44
|
+
if (namePrefix.length > exports.MAX_INCLUDE_DEPTH) {
|
|
45
|
+
throw new Error(`${relativeName} (${fileName}) is included ${namePrefix.length} levels deep, at most ${exports.MAX_INCLUDE_DEPTH} are read`);
|
|
46
|
+
}
|
|
47
|
+
if (Object.keys(ctx.files).length >= exports.MAX_BUILD_FILES) {
|
|
48
|
+
throw new Error(`${relativeName} (${fileName}): the build file includes more than ${exports.MAX_BUILD_FILES} files, counting a file included with other inputs again`);
|
|
49
|
+
}
|
|
50
|
+
if (inputs && Buffer.byteLength(JSON.stringify(inputs), 'utf8') > exports.MAX_INCLUDE_INPUT_BYTES) {
|
|
51
|
+
throw new Error(`${relativeName} (${fileName}): the inputs passed to it take more than ${exports.MAX_INCLUDE_INPUT_BYTES} bytes`);
|
|
52
|
+
}
|
|
53
|
+
const input = await readCounted(ctx, fileName, environment, relativeName);
|
|
34
54
|
(0, removed_properties_1.assertNoRemovedProperties)(input, fileName);
|
|
35
55
|
const result = await build_file_schema_1.buildFileSchema.safeParseAsync(input);
|
|
36
56
|
if (!result.success) {
|
|
37
57
|
throw new parse_error_1.ParseError(result.error, fileName);
|
|
38
58
|
}
|
|
59
|
+
const read = readOf(ctx);
|
|
60
|
+
read.items += Object.keys(result.data.tasks ?? {}).length + Object.keys(result.data.services ?? {}).length;
|
|
61
|
+
if (read.items > exports.MAX_BUILD_FILE_ITEMS) {
|
|
62
|
+
throw new Error(`${relativeName} (${fileName}): the build file declares more than ${exports.MAX_BUILD_FILE_ITEMS} tasks and services, counting a file included with other inputs again`);
|
|
63
|
+
}
|
|
39
64
|
const scope = {
|
|
40
65
|
fileName,
|
|
41
66
|
cwd,
|
|
@@ -77,6 +102,25 @@ leftOut = false) {
|
|
|
77
102
|
return scope;
|
|
78
103
|
}
|
|
79
104
|
exports.appendBuildFile = appendBuildFile;
|
|
105
|
+
// A build file, parsed once per parse and counted each time it is read.
|
|
106
|
+
async function readCounted(ctx, fileName, environment, relativeName) {
|
|
107
|
+
const read = readOf(ctx);
|
|
108
|
+
let parsed = read.parsed.get(fileName);
|
|
109
|
+
if (!parsed) {
|
|
110
|
+
parsed = await (0, read_build_file_1.readSized)(fileName, environment);
|
|
111
|
+
read.parsed.set(fileName, parsed);
|
|
112
|
+
}
|
|
113
|
+
read.bytes += parsed.bytes;
|
|
114
|
+
if (read.bytes > exports.MAX_BUILD_FILE_BYTES) {
|
|
115
|
+
throw new Error(`${relativeName} (${fileName}): the build file includes more than ${exports.MAX_BUILD_FILE_BYTES} bytes of build files, counting a file included with other inputs again`);
|
|
116
|
+
}
|
|
117
|
+
// every scope gets a value of its own
|
|
118
|
+
return structuredClone(parsed.value);
|
|
119
|
+
}
|
|
120
|
+
function readOf(ctx) {
|
|
121
|
+
ctx.read ?? (ctx.read = { bytes: 0, items: 0, parsed: new Map() });
|
|
122
|
+
return ctx.read;
|
|
123
|
+
}
|
|
80
124
|
// The scope of a git source a server does not fetch, see ParseScope.notFetched
|
|
81
125
|
function notFetched(cwd, namePrefix, include) {
|
|
82
126
|
return {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.getPushRefusal = exports.KubernetesSandboxStorage = exports.getSandboxNames = void 0;
|
|
3
|
+
exports.AnswerReader = exports.getPushRefusal = exports.KubernetesSandboxStorage = exports.getSandboxNames = void 0;
|
|
4
4
|
const crypto_1 = require("crypto");
|
|
5
5
|
const promises_1 = require("fs/promises");
|
|
6
6
|
const path_1 = require("path");
|
|
@@ -542,7 +542,9 @@ class KubernetesSandboxStorage {
|
|
|
542
542
|
// the process ends when the server stops waiting for it: closing the connection does
|
|
543
543
|
// not end a command in a pod
|
|
544
544
|
const seconds = Math.ceil((['create', 'fetch', 'move', 'archive'].includes(request.op) ? FETCH_TIMEOUT_MS : REQUEST_TIMEOUT_MS) / 1000);
|
|
545
|
-
const done = this.withPod(key, (pod) => this.exec(pod, ['timeout', String(seconds), 'hammerkit', 'server-sandbox', CLAIM_PATH], stream_1.Readable.from([Buffer.from(JSON.stringify(encoded))]), reader,
|
|
545
|
+
const done = this.withPod(key, (pod) => this.exec(pod, ['timeout', String(seconds), 'hammerkit', 'server-sandbox', CLAIM_PATH], stream_1.Readable.from([Buffer.from(JSON.stringify(encoded))]), reader,
|
|
546
|
+
// a request that failed (an answer too large) stops the command too
|
|
547
|
+
AbortSignal.any([signal, reader.stopped])));
|
|
546
548
|
done.then(() => reader.complete(), (e) => reader.fail(e));
|
|
547
549
|
const answer = await reader.answer;
|
|
548
550
|
if (!answer.header.ok) {
|
|
@@ -911,16 +913,22 @@ function holdBack(socket, stdout) {
|
|
|
911
913
|
* memory, unless the first line says it is a stream: then it is passed on as it comes.
|
|
912
914
|
*/
|
|
913
915
|
class AnswerReader extends stream_1.Writable {
|
|
914
|
-
constructor(body) {
|
|
916
|
+
constructor(body, maxBytes = MAX_ANSWER_BYTES) {
|
|
915
917
|
super();
|
|
916
918
|
this.body = body;
|
|
919
|
+
this.maxBytes = maxBytes;
|
|
917
920
|
this.chunks = [];
|
|
918
921
|
this.size = 0;
|
|
922
|
+
this.stop = new AbortController();
|
|
923
|
+
// aborted once the answer failed: nothing reads the rest
|
|
924
|
+
this.stopped = this.stop.signal;
|
|
919
925
|
this.answer = new Promise((resolve, reject) => {
|
|
920
926
|
this.resolveAnswer = resolve;
|
|
921
927
|
this.rejectAnswer = reject;
|
|
922
928
|
});
|
|
923
929
|
this.answer.catch(() => undefined);
|
|
930
|
+
// an answer that is too large or no answer at all fails the request, not the server
|
|
931
|
+
this.on('error', (e) => this.fail(e));
|
|
924
932
|
}
|
|
925
933
|
_write(chunk, _encoding, callback) {
|
|
926
934
|
if (this.stream) {
|
|
@@ -933,7 +941,7 @@ class AnswerReader extends stream_1.Writable {
|
|
|
933
941
|
return;
|
|
934
942
|
}
|
|
935
943
|
this.size += chunk.length;
|
|
936
|
-
if (this.size >
|
|
944
|
+
if (this.size > this.maxBytes) {
|
|
937
945
|
callback(new Error('the answer of the pod of the sandbox is too large'));
|
|
938
946
|
return;
|
|
939
947
|
}
|
|
@@ -986,6 +994,7 @@ class AnswerReader extends stream_1.Writable {
|
|
|
986
994
|
}
|
|
987
995
|
}
|
|
988
996
|
fail(e) {
|
|
997
|
+
this.stop.abort();
|
|
989
998
|
const error = e instanceof Error ? e : new Error(String(e));
|
|
990
999
|
if (this.stream) {
|
|
991
1000
|
this.stream.destroy(error);
|
|
@@ -993,6 +1002,7 @@ class AnswerReader extends stream_1.Writable {
|
|
|
993
1002
|
this.rejectAnswer(error);
|
|
994
1003
|
}
|
|
995
1004
|
}
|
|
1005
|
+
exports.AnswerReader = AnswerReader;
|
|
996
1006
|
// The files of a sandbox on a cluster: each call is a request to the pod of its files.
|
|
997
1007
|
class KubernetesSandboxFiles {
|
|
998
1008
|
constructor(request, rawFile) {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.HostSandboxFiles = exports.isRunState = exports.RUN_STATE_DIRECTORY = exports.deniedPath = exports.checkPath = exports.SandboxFileError = exports.MAX_CHANGES_BYTES = exports.READ_LINES = exports.MAX_FILE_BYTES = void 0;
|
|
3
|
+
exports.HostSandboxFiles = exports.isRunState = exports.RUN_STATE_DIRECTORY = exports.deniedPath = exports.checkPath = exports.SandboxFileError = exports.MAX_EDIT_SERVER_BYTES = exports.MAX_EDIT_BATCH_WORK = exports.MAX_EDIT_BATCH_BYTES = exports.MAX_CHANGES_BYTES = exports.READ_LINES = exports.MAX_FILE_BYTES = void 0;
|
|
4
4
|
const child_process_1 = require("child_process");
|
|
5
5
|
const crypto_1 = require("crypto");
|
|
6
6
|
const fs_1 = require("fs");
|
|
@@ -25,6 +25,21 @@ const SEARCH_COUNT = 20000;
|
|
|
25
25
|
const SEARCH_TIMEOUT_MS = 60000;
|
|
26
26
|
// the most a diff or patch of the changes may take
|
|
27
27
|
exports.MAX_CHANGES_BYTES = 64 * 1024 * 1024;
|
|
28
|
+
// What one batch of edits may hold in memory, the files it reads and the files it would
|
|
29
|
+
// write together: a batch over it is refused before it reads or makes more.
|
|
30
|
+
exports.MAX_EDIT_BATCH_BYTES = 256 * 1024 * 1024;
|
|
31
|
+
// What one batch may process: the text it decodes, scans and makes, read files counted
|
|
32
|
+
// each time an operation reads them. A batch over it is refused, as one that holds too much.
|
|
33
|
+
exports.MAX_EDIT_BATCH_WORK = 1024 * 1024 * 1024;
|
|
34
|
+
// What all batches being planned on this server may hold in memory together.
|
|
35
|
+
exports.MAX_EDIT_SERVER_BYTES = 512 * 1024 * 1024;
|
|
36
|
+
const SERVER_EDITS = { held: 0, max: exports.MAX_EDIT_SERVER_BYTES };
|
|
37
|
+
const DEFAULT_EDIT_LIMITS = {
|
|
38
|
+
bytes: exports.MAX_EDIT_BATCH_BYTES,
|
|
39
|
+
work: exports.MAX_EDIT_BATCH_WORK,
|
|
40
|
+
compared: sandbox_patch_1.MAX_COMPARED_LINES,
|
|
41
|
+
server: SERVER_EDITS,
|
|
42
|
+
};
|
|
28
43
|
class SandboxFileError extends Error {
|
|
29
44
|
constructor(status, message, details = {}) {
|
|
30
45
|
super(message);
|
|
@@ -183,11 +198,14 @@ class HostSandboxFiles {
|
|
|
183
198
|
// the environment of ripgrep: the variables runs see
|
|
184
199
|
env,
|
|
185
200
|
// the most a diff or patch of the changes may take
|
|
186
|
-
maxChangesBytes = exports.MAX_CHANGES_BYTES
|
|
201
|
+
maxChangesBytes = exports.MAX_CHANGES_BYTES,
|
|
202
|
+
// what one batch of edits may hold and process
|
|
203
|
+
editLimits = {}) {
|
|
187
204
|
this.root = root;
|
|
188
205
|
this.git = git;
|
|
189
206
|
this.env = env;
|
|
190
207
|
this.maxChangesBytes = maxChangesBytes;
|
|
208
|
+
this.editLimits = editLimits;
|
|
191
209
|
}
|
|
192
210
|
absolute(path) {
|
|
193
211
|
return (0, path_1.join)(this.root, ...path.split('/'));
|
|
@@ -706,8 +724,21 @@ class HostSandboxFiles {
|
|
|
706
724
|
});
|
|
707
725
|
}
|
|
708
726
|
async plan(ops) {
|
|
709
|
-
const batch = new EditBatch(this);
|
|
727
|
+
const batch = new EditBatch(this, { ...DEFAULT_EDIT_LIMITS, ...this.editLimits });
|
|
728
|
+
try {
|
|
729
|
+
return await this.planBatch(batch, ops);
|
|
730
|
+
}
|
|
731
|
+
finally {
|
|
732
|
+
// the plan is written right after it is made, under the same lock of the sandbox
|
|
733
|
+
batch.release();
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
async planBatch(batch, ops) {
|
|
710
737
|
for (const [index, op] of ops.entries()) {
|
|
738
|
+
if (index > 0) {
|
|
739
|
+
// the other requests of the server get their turn between two operations
|
|
740
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
741
|
+
}
|
|
711
742
|
try {
|
|
712
743
|
await batch.apply(op);
|
|
713
744
|
}
|
|
@@ -841,13 +872,57 @@ class HostSandboxFiles {
|
|
|
841
872
|
}
|
|
842
873
|
}
|
|
843
874
|
exports.HostSandboxFiles = HostSandboxFiles;
|
|
875
|
+
function tooLarge(path, bytes) {
|
|
876
|
+
if (bytes > exports.MAX_FILE_BYTES) {
|
|
877
|
+
throw new SandboxFileError(413, `${path} would take ${bytes} bytes, more than ${exports.MAX_FILE_BYTES}`);
|
|
878
|
+
}
|
|
879
|
+
}
|
|
844
880
|
// The edits of one request, applied to what the files would hold after them, before any
|
|
845
881
|
// of it is written.
|
|
846
882
|
class EditBatch {
|
|
847
|
-
constructor(files) {
|
|
883
|
+
constructor(files, limits) {
|
|
848
884
|
this.files = files;
|
|
885
|
+
this.limits = limits;
|
|
849
886
|
this.before = new Map();
|
|
850
887
|
this.after = new Map();
|
|
888
|
+
// the bytes of the files read and made so far
|
|
889
|
+
this.held = 0;
|
|
890
|
+
// the bytes of text decoded, scanned and made so far
|
|
891
|
+
this.worked = 0;
|
|
892
|
+
this.budget = new sandbox_patch_1.PatchBudget(limits.compared);
|
|
893
|
+
}
|
|
894
|
+
hold(bytes) {
|
|
895
|
+
if (this.held + bytes > this.limits.bytes) {
|
|
896
|
+
throw new SandboxFileError(413, `the edits of this batch read and write more than ${this.limits.bytes} bytes, send them in smaller batches`);
|
|
897
|
+
}
|
|
898
|
+
const server = this.limits.server;
|
|
899
|
+
if (bytes > 0 && server.held + bytes > server.max) {
|
|
900
|
+
throw new SandboxFileError(503, 'the server is busy with other edits, send the batch again in a moment');
|
|
901
|
+
}
|
|
902
|
+
this.held += bytes;
|
|
903
|
+
server.held += bytes;
|
|
904
|
+
}
|
|
905
|
+
free(bytes) {
|
|
906
|
+
this.held -= bytes;
|
|
907
|
+
this.limits.server.held -= bytes;
|
|
908
|
+
}
|
|
909
|
+
// What this batch holds no longer counts against the server.
|
|
910
|
+
release() {
|
|
911
|
+
this.limits.server.held -= this.held;
|
|
912
|
+
this.held = 0;
|
|
913
|
+
}
|
|
914
|
+
work(bytes) {
|
|
915
|
+
this.worked += bytes;
|
|
916
|
+
if (this.worked > this.limits.work) {
|
|
917
|
+
throw new SandboxFileError(413, `the edits of this batch process more than ${this.limits.work} bytes of text, send them in smaller batches`);
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
// A file's content, counted once when it is read.
|
|
921
|
+
async content(path, state) {
|
|
922
|
+
if (!state.content) {
|
|
923
|
+
this.hold(state.size);
|
|
924
|
+
}
|
|
925
|
+
return this.files.content(path, state);
|
|
851
926
|
}
|
|
852
927
|
async current(path) {
|
|
853
928
|
const changed = this.after.get(path);
|
|
@@ -862,7 +937,9 @@ class EditBatch {
|
|
|
862
937
|
return original;
|
|
863
938
|
}
|
|
864
939
|
async text(path, state) {
|
|
865
|
-
|
|
940
|
+
const content = await this.content(path, state);
|
|
941
|
+
this.work(content.length);
|
|
942
|
+
return decodeText(path, content);
|
|
866
943
|
}
|
|
867
944
|
async file(path, verb) {
|
|
868
945
|
const state = await this.current(path);
|
|
@@ -882,7 +959,7 @@ class EditBatch {
|
|
|
882
959
|
return;
|
|
883
960
|
}
|
|
884
961
|
const state = await this.current(path);
|
|
885
|
-
const actual = state.kind === 'file' ? sha256(await this.
|
|
962
|
+
const actual = state.kind === 'file' ? sha256(await this.content(path, state)) : undefined;
|
|
886
963
|
if (actual !== ifHash.toLowerCase()) {
|
|
887
964
|
throw new SandboxFileError(412, actual
|
|
888
965
|
? `${path} changed since you read it (sha256 ${actual}), read it again`
|
|
@@ -911,9 +988,11 @@ class EditBatch {
|
|
|
911
988
|
return state;
|
|
912
989
|
}
|
|
913
990
|
set(path, content, exec) {
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
991
|
+
tooLarge(path, content.length);
|
|
992
|
+
const replaced = this.after.get(path);
|
|
993
|
+
// what an earlier edit of the batch made for the path is not kept
|
|
994
|
+
this.free(replaced?.kind === 'file' ? replaced.content?.length ?? 0 : 0);
|
|
995
|
+
this.hold(content.length);
|
|
917
996
|
this.after.set(path, { kind: 'file', size: content.length, exec, content });
|
|
918
997
|
}
|
|
919
998
|
async apply(op) {
|
|
@@ -931,17 +1010,28 @@ class EditBatch {
|
|
|
931
1010
|
if (op.old_string === op.new_string) {
|
|
932
1011
|
throw new SandboxFileError(422, 'old_string and new_string are the same, nothing would change');
|
|
933
1012
|
}
|
|
1013
|
+
// the first places are kept to name their lines, the others counted
|
|
934
1014
|
const at = [];
|
|
1015
|
+
let count = 0;
|
|
935
1016
|
for (let found = text.indexOf(op.old_string); found >= 0; found = text.indexOf(op.old_string, found + op.old_string.length)) {
|
|
936
|
-
at.
|
|
1017
|
+
if (at.length < 10) {
|
|
1018
|
+
at.push(found);
|
|
1019
|
+
}
|
|
1020
|
+
count++;
|
|
937
1021
|
}
|
|
938
|
-
if (
|
|
1022
|
+
if (count === 0) {
|
|
939
1023
|
throw new SandboxFileError(422, `old_string is not in ${path}; it has to match the file exactly, whitespace and indentation included: read the file again`);
|
|
940
1024
|
}
|
|
941
|
-
if (
|
|
942
|
-
const lines = at.
|
|
943
|
-
throw new SandboxFileError(422, `old_string is ${
|
|
1025
|
+
if (count > 1 && !op.replace_all) {
|
|
1026
|
+
const lines = at.map((offset) => text.slice(0, offset).split('\n').length);
|
|
1027
|
+
throw new SandboxFileError(422, `old_string is ${count} times in ${path}, at lines ${lines.join(', ')}${count > 10 ? ', …' : ''}: add lines around it until it is there once, or set replace_all`, { lines });
|
|
944
1028
|
}
|
|
1029
|
+
// the size of the result, before it is made
|
|
1030
|
+
const size = Buffer.byteLength(text, 'utf8') +
|
|
1031
|
+
count * (Buffer.byteLength(op.new_string, 'utf8') - Buffer.byteLength(op.old_string, 'utf8'));
|
|
1032
|
+
tooLarge(path, size);
|
|
1033
|
+
// the scan, and the result that is made
|
|
1034
|
+
this.work(text.length + size);
|
|
945
1035
|
const replaced = op.replace_all
|
|
946
1036
|
? text.split(op.old_string).join(op.new_string)
|
|
947
1037
|
: text.slice(0, at[0]) + op.new_string + text.slice(at[0] + op.old_string.length);
|
|
@@ -967,7 +1057,7 @@ class EditBatch {
|
|
|
967
1057
|
else {
|
|
968
1058
|
const to = checkPath(op.to);
|
|
969
1059
|
const state = await this.file(path, 'move');
|
|
970
|
-
const content = await this.
|
|
1060
|
+
const content = await this.content(path, state);
|
|
971
1061
|
const target = await this.writable(to);
|
|
972
1062
|
if (target.kind !== 'absent') {
|
|
973
1063
|
throw new SandboxFileError(409, `${to} exists, delete it first`);
|
|
@@ -997,7 +1087,8 @@ class EditBatch {
|
|
|
997
1087
|
throw new SandboxFileError(409, `${to} exists, the patch ${from ? 'moves a file onto' : 'adds'} it`);
|
|
998
1088
|
}
|
|
999
1089
|
}
|
|
1000
|
-
const result = file.apply(content);
|
|
1090
|
+
const result = file.apply(content, this.budget);
|
|
1091
|
+
this.work(content.length + result.length);
|
|
1001
1092
|
if (to === undefined) {
|
|
1002
1093
|
if (from !== undefined && result !== '') {
|
|
1003
1094
|
throw new sandbox_patch_1.PatchError(`${from}: the patch deletes it, but its lines are not what the file holds`);
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* file, and each file is changed in memory, so a batch of edits applies fully or not at all.
|
|
7
7
|
*/
|
|
8
8
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
-
exports.MAX_COMPARED_LINES = exports.parsePatch = exports.PatchError = void 0;
|
|
9
|
+
exports.MAX_HUNK_LINE = exports.PatchBudget = exports.MAX_COMPARED_LINES = exports.parsePatch = exports.PatchError = void 0;
|
|
10
10
|
class PatchError extends Error {
|
|
11
11
|
}
|
|
12
12
|
exports.PatchError = PatchError;
|
|
@@ -57,16 +57,25 @@ function splice(file, at, block) {
|
|
|
57
57
|
function oldSide(block) {
|
|
58
58
|
return block.filter((line) => line.kind !== '+').map((line) => line.text);
|
|
59
59
|
}
|
|
60
|
-
// Lines one
|
|
61
|
-
// file would otherwise be compared with every place in it, its whole length at each.
|
|
60
|
+
// Lines the patches of one batch may compare to place their hunks. A hunk that is nowhere in
|
|
61
|
+
// a large file would otherwise be compared with every place in it, its whole length at each.
|
|
62
62
|
exports.MAX_COMPARED_LINES = 20000000;
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
63
|
+
// The comparisons the patches of one batch made so far.
|
|
64
|
+
class PatchBudget {
|
|
65
|
+
constructor(max = exports.MAX_COMPARED_LINES) {
|
|
66
|
+
this.max = max;
|
|
67
|
+
this.compared = 0;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
exports.PatchBudget = PatchBudget;
|
|
71
|
+
// the budget of the patch being applied: applying one is synchronous, so only one is
|
|
72
|
+
let current = new PatchBudget();
|
|
73
|
+
function startComparing(budget) {
|
|
74
|
+
current = budget ?? new PatchBudget();
|
|
66
75
|
}
|
|
67
76
|
function compare(path) {
|
|
68
|
-
if (++compared >
|
|
69
|
-
throw new PatchError(`${path}: the
|
|
77
|
+
if (++current.compared > current.max) {
|
|
78
|
+
throw new PatchError(`${path}: the patches of this batch were compared with the files ${current.max} times without finding their place; give their hunks more lines of context or the line numbers of the files as they are`);
|
|
70
79
|
}
|
|
71
80
|
}
|
|
72
81
|
function matchesAt(path, lines, at, wanted, same = (a, b) => stripCr(a) === stripCr(b)) {
|
|
@@ -176,14 +185,15 @@ function parseHunks(lines, start, path) {
|
|
|
176
185
|
break;
|
|
177
186
|
}
|
|
178
187
|
const hunk = {
|
|
179
|
-
oldStart:
|
|
180
|
-
oldLength: header[2] === undefined ? 1 :
|
|
188
|
+
oldStart: lineNumber(header[1], path, hunks.length),
|
|
189
|
+
oldLength: header[2] === undefined ? 1 : lineNumber(header[2], path, hunks.length),
|
|
181
190
|
lines: [],
|
|
182
191
|
oldNoNewline: false,
|
|
183
192
|
newNoNewline: false,
|
|
184
193
|
};
|
|
194
|
+
lineNumber(header[3], path, hunks.length);
|
|
185
195
|
let oldLeft = hunk.oldLength;
|
|
186
|
-
let newLeft = header[4] === undefined ? 1 :
|
|
196
|
+
let newLeft = header[4] === undefined ? 1 : lineNumber(header[4], path, hunks.length);
|
|
187
197
|
i++;
|
|
188
198
|
while (oldLeft > 0 || newLeft > 0) {
|
|
189
199
|
if (i >= lines.length) {
|
|
@@ -220,12 +230,22 @@ function parseHunks(lines, start, path) {
|
|
|
220
230
|
}
|
|
221
231
|
return [hunks, i];
|
|
222
232
|
}
|
|
233
|
+
// The largest line number or line count a hunk header may name. A file an edit reads has
|
|
234
|
+
// at most MAX_FILE_BYTES, so no file has more lines than that.
|
|
235
|
+
exports.MAX_HUNK_LINE = 1000000000;
|
|
236
|
+
function lineNumber(digits, path, index) {
|
|
237
|
+
const value = Number(digits);
|
|
238
|
+
if (!Number.isSafeInteger(value) || value > exports.MAX_HUNK_LINE) {
|
|
239
|
+
throw new PatchError(`${path}: hunk ${index + 1} names line ${digits.length > 20 ? `${digits.slice(0, 20)}…` : digits}, more than a file has`);
|
|
240
|
+
}
|
|
241
|
+
return value;
|
|
242
|
+
}
|
|
223
243
|
function filePatch(header, hunks) {
|
|
224
244
|
const path = header.to ?? header.from ?? '';
|
|
225
245
|
return {
|
|
226
246
|
...header,
|
|
227
|
-
apply(content) {
|
|
228
|
-
startComparing();
|
|
247
|
+
apply(content, budget) {
|
|
248
|
+
startComparing(budget);
|
|
229
249
|
const file = splitLines(content);
|
|
230
250
|
let delta = 0;
|
|
231
251
|
let cursor = 0;
|
|
@@ -255,8 +275,14 @@ function nominal(hunk) {
|
|
|
255
275
|
}
|
|
256
276
|
// The match closest to `expected` at or after `from`, the way git apply moves a hunk
|
|
257
277
|
// whose lines moved.
|
|
258
|
-
function findNear(path, lines, wanted,
|
|
278
|
+
function findNear(path, lines, wanted, wantedAt, from) {
|
|
259
279
|
const last = lines.length - wanted.length;
|
|
280
|
+
if (last < from) {
|
|
281
|
+
return -1;
|
|
282
|
+
}
|
|
283
|
+
// a line number past the end of the file looks from the end: every place it could be is
|
|
284
|
+
// between `from` and `last`, so the search never walks past them
|
|
285
|
+
const expected = Math.min(Math.max(wantedAt, from), last);
|
|
260
286
|
for (let distance = 0; expected - distance >= from || expected + distance <= last; distance++) {
|
|
261
287
|
if (expected - distance >= from && matchesAt(path, lines, expected - distance, wanted)) {
|
|
262
288
|
return expected - distance;
|
|
@@ -414,7 +440,7 @@ function parseApplyPatch(text) {
|
|
|
414
440
|
}
|
|
415
441
|
chunks[chunks.length - 1].lines.push({ kind, text: current.slice(1) });
|
|
416
442
|
}
|
|
417
|
-
files.push({ from: path, to, apply: (content) => applyChunks(path, content, chunks) });
|
|
443
|
+
files.push({ from: path, to, apply: (content, budget) => applyChunks(path, content, chunks, budget) });
|
|
418
444
|
}
|
|
419
445
|
else {
|
|
420
446
|
throw new PatchError(`"${line.slice(0, 80)}" is not an apply_patch line: expected *** Add File:, *** Update File:, *** Delete File: or *** End Patch`);
|
|
@@ -430,8 +456,8 @@ const trailing = (a, b) => a.trimEnd() === b.trimEnd();
|
|
|
430
456
|
const trimmed = (a, b) => a.trim() === b.trim();
|
|
431
457
|
// The way apply_patch finds its lines: after the chunk before it, exactly, then with
|
|
432
458
|
// trailing and then all surrounding whitespace ignored.
|
|
433
|
-
function applyChunks(path, content, chunks) {
|
|
434
|
-
startComparing();
|
|
459
|
+
function applyChunks(path, content, chunks, budget) {
|
|
460
|
+
startComparing(budget);
|
|
435
461
|
const file = splitLines(content);
|
|
436
462
|
let cursor = 0;
|
|
437
463
|
chunks.forEach((chunk, index) => {
|
package/dist/server/sandboxes.js
CHANGED
|
@@ -32,6 +32,9 @@ class SandboxRegistry {
|
|
|
32
32
|
// bytes they take once they were measured
|
|
33
33
|
this.creating = new Map();
|
|
34
34
|
this.deleting = new Set();
|
|
35
|
+
// the bytes edits take while they are written, so edits of two sandboxes at once both
|
|
36
|
+
// count against their owner's limit and the server's
|
|
37
|
+
this.reserved = new Map();
|
|
35
38
|
// the measures of runs that are over, which a run's result does not wait for
|
|
36
39
|
this.measuring = new Map();
|
|
37
40
|
this.locks = new Map();
|
|
@@ -114,9 +117,10 @@ class SandboxRegistry {
|
|
|
114
117
|
usage(owner) {
|
|
115
118
|
const mine = this.list(owner);
|
|
116
119
|
const creating = [...this.creating.values()].filter((create) => owns(owner, create.owner));
|
|
120
|
+
const reserved = [...this.reserved.values()].filter((reservation) => owns(owner, reservation.owner));
|
|
117
121
|
return {
|
|
118
122
|
count: mine.length + creating.length,
|
|
119
|
-
bytes: [...mine, ...creating].reduce((sum, sandbox) => sum + sandbox.bytes, 0),
|
|
123
|
+
bytes: [...mine, ...creating, ...reserved].reduce((sum, sandbox) => sum + sandbox.bytes, 0),
|
|
120
124
|
};
|
|
121
125
|
}
|
|
122
126
|
// Waits for the measures of the owner's runs that are over, so their limits hold.
|
|
@@ -139,6 +143,9 @@ class SandboxRegistry {
|
|
|
139
143
|
* caller's to decide (`decideSandbox`); this checks the limits.
|
|
140
144
|
*/
|
|
141
145
|
async create(owner, repo, ref) {
|
|
146
|
+
return this.growing(owner, () => this.createGrowing(owner, repo, ref));
|
|
147
|
+
}
|
|
148
|
+
async createGrowing(owner, repo, ref) {
|
|
142
149
|
const { limits, storage, repos } = this.options;
|
|
143
150
|
await this.measured(owner);
|
|
144
151
|
const usage = this.usage(owner);
|
|
@@ -211,28 +218,47 @@ class SandboxRegistry {
|
|
|
211
218
|
if (!state.clean) {
|
|
212
219
|
throw new SandboxError(409, `the sandbox ${id} has changes, a fetch would mix them with another commit`);
|
|
213
220
|
}
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
const credentials = await repos.credentials(sandbox.repo);
|
|
218
|
-
try {
|
|
219
|
-
sandbox.commit = await storage.fetch(keyOf(sandbox), {
|
|
220
|
-
url: repos.url(sandbox.repo),
|
|
221
|
-
ref,
|
|
222
|
-
env: credentials.env,
|
|
223
|
-
signal,
|
|
224
|
-
});
|
|
225
|
-
}
|
|
226
|
-
catch (e) {
|
|
227
|
-
throw new SandboxError(502, repos.scrub(e, credentials.values).message);
|
|
228
|
-
}
|
|
229
|
-
sandbox.ref = ref;
|
|
230
|
-
sandbox.bytes = await storage.usage(keyOf(sandbox));
|
|
231
|
-
sandbox.lastUsedAt = this.timestamp();
|
|
232
|
-
await this.save(sandbox);
|
|
233
|
-
return copy(sandbox);
|
|
221
|
+
// a fetch can make the sandbox larger: not while the owner or the server is full, and
|
|
222
|
+
// one create or fetch of an owner at a time, so fetches at once can not pass it together
|
|
223
|
+
return this.growing(owner, () => this.fetchGrowing(owner, sandbox, ref));
|
|
234
224
|
});
|
|
235
225
|
}
|
|
226
|
+
async fetchGrowing(owner, sandbox, ref) {
|
|
227
|
+
const { limits } = this.options;
|
|
228
|
+
await this.measured(owner);
|
|
229
|
+
const used = this.usage(owner).bytes;
|
|
230
|
+
if (used >= limits.bytes) {
|
|
231
|
+
throw new SandboxError(413, `your sandboxes take ${(0, units_1.formatSize)(used)}, your limit is ${(0, units_1.formatSize)(limits.bytes)}: delete one`);
|
|
232
|
+
}
|
|
233
|
+
if (this.total() >= limits.total) {
|
|
234
|
+
throw new SandboxError(507, 'the server has no room for a fetch');
|
|
235
|
+
}
|
|
236
|
+
const { storage, repos } = this.options;
|
|
237
|
+
const signal = AbortSignal.timeout(FETCH_TIMEOUT_MS);
|
|
238
|
+
await this.resolve(sandbox.repo, ref, signal);
|
|
239
|
+
const credentials = await repos.credentials(sandbox.repo);
|
|
240
|
+
try {
|
|
241
|
+
sandbox.commit = await storage.fetch(keyOf(sandbox), {
|
|
242
|
+
url: repos.url(sandbox.repo),
|
|
243
|
+
ref,
|
|
244
|
+
env: credentials.env,
|
|
245
|
+
signal,
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
catch (e) {
|
|
249
|
+
throw new SandboxError(502, repos.scrub(e, credentials.values).message);
|
|
250
|
+
}
|
|
251
|
+
sandbox.ref = ref;
|
|
252
|
+
sandbox.bytes = await storage.usage(keyOf(sandbox));
|
|
253
|
+
sandbox.lastUsedAt = this.timestamp();
|
|
254
|
+
await this.save(sandbox);
|
|
255
|
+
return copy(sandbox);
|
|
256
|
+
}
|
|
257
|
+
// One create or fetch of an owner at a time: what one adds is measured before the next
|
|
258
|
+
// checks the limit.
|
|
259
|
+
growing(owner, fn) {
|
|
260
|
+
return this.withLock(`owner:${JSON.stringify([owner.iss, owner.sub])}`, fn);
|
|
261
|
+
}
|
|
236
262
|
/**
|
|
237
263
|
* Commits the changes of a sandbox as its owner and pushes them to a branch the operator
|
|
238
264
|
* allows (`sources[].push.branches`). The branch must not exist yet, or be one this
|
|
@@ -392,6 +418,7 @@ class SandboxRegistry {
|
|
|
392
418
|
if (dryRun || plan.files.length === 0) {
|
|
393
419
|
return plan.files;
|
|
394
420
|
}
|
|
421
|
+
const reservation = Symbol(id);
|
|
395
422
|
if (plan.bytes > 0) {
|
|
396
423
|
const { limits } = this.options;
|
|
397
424
|
const used = this.usage(owner).bytes;
|
|
@@ -401,8 +428,15 @@ class SandboxRegistry {
|
|
|
401
428
|
if (this.total() + plan.bytes > limits.total) {
|
|
402
429
|
throw new SandboxError(507, 'the server has no room for these edits');
|
|
403
430
|
}
|
|
431
|
+
// taken before anything else can check: no await between the check and this
|
|
432
|
+
this.reserved.set(reservation, { owner: { iss: owner.iss, sub: owner.sub }, bytes: plan.bytes });
|
|
433
|
+
}
|
|
434
|
+
try {
|
|
435
|
+
await plan.commit();
|
|
436
|
+
}
|
|
437
|
+
finally {
|
|
438
|
+
this.reserved.delete(reservation);
|
|
404
439
|
}
|
|
405
|
-
await plan.commit();
|
|
406
440
|
sandbox.bytes = Math.max(0, sandbox.bytes + plan.bytes);
|
|
407
441
|
sandbox.lastUsedAt = this.timestamp();
|
|
408
442
|
await this.save(sandbox);
|
|
@@ -483,7 +517,7 @@ class SandboxRegistry {
|
|
|
483
517
|
}
|
|
484
518
|
}
|
|
485
519
|
total() {
|
|
486
|
-
return [...this.sandboxes.values(), ...this.creating.values()].reduce((sum, sandbox) => sum + sandbox.bytes, 0);
|
|
520
|
+
return [...this.sandboxes.values(), ...this.creating.values(), ...this.reserved.values()].reduce((sum, sandbox) => sum + sandbox.bytes, 0);
|
|
487
521
|
}
|
|
488
522
|
withLock(id, fn) {
|
|
489
523
|
const previous = this.locks.get(id) ?? Promise.resolve();
|
package/dist/server/sources.js
CHANGED
|
@@ -15,7 +15,11 @@ class SourceError extends Error {
|
|
|
15
15
|
}
|
|
16
16
|
}
|
|
17
17
|
exports.SourceError = SourceError;
|
|
18
|
-
exports.DEFAULT_SOURCE_LIMITS = {
|
|
18
|
+
exports.DEFAULT_SOURCE_LIMITS = {
|
|
19
|
+
subjectBytes: 4 * 1024 * 1024 * 1024,
|
|
20
|
+
subjectManifests: 1000,
|
|
21
|
+
subjectManifestBytes: 64 * 1024 * 1024,
|
|
22
|
+
};
|
|
19
23
|
// The directory name of a caller: the issuer and subject, hashed.
|
|
20
24
|
function subjectKey(principal) {
|
|
21
25
|
return (0, crypto_1.createHash)('sha256')
|
|
@@ -35,11 +39,11 @@ exports.subjectKey = subjectKey;
|
|
|
35
39
|
* what other people work on.
|
|
36
40
|
*/
|
|
37
41
|
class SourceStore {
|
|
38
|
-
constructor(directory, limits =
|
|
42
|
+
constructor(directory, limits = {}, now = Date.now) {
|
|
39
43
|
this.directory = directory;
|
|
40
|
-
this.limits = limits;
|
|
41
44
|
this.now = now;
|
|
42
45
|
this.subjects = new Map();
|
|
46
|
+
this.limits = { ...exports.DEFAULT_SOURCE_LIMITS, ...limits };
|
|
43
47
|
}
|
|
44
48
|
// Announces a tree. Answers what has to be sent to complete it.
|
|
45
49
|
async announce(principal, manifest) {
|
|
@@ -70,9 +74,27 @@ class SourceStore {
|
|
|
70
74
|
sizes.set(file.sha256, file.size);
|
|
71
75
|
}
|
|
72
76
|
const stored = { manifest, createdAt: new Date(this.now()).toISOString() };
|
|
73
|
-
|
|
74
|
-
|
|
77
|
+
const content = JSON.stringify(stored);
|
|
78
|
+
const bytes = Buffer.byteLength(content, 'utf8');
|
|
79
|
+
if (subject.manifests.size >= this.limits.subjectManifests) {
|
|
80
|
+
throw new SourceError(413, `the server keeps at most ${this.limits.subjectManifests} trees for you, delete one with DELETE /v1/sources/<snapshot>`);
|
|
81
|
+
}
|
|
82
|
+
const manifestBytes = [...subject.manifestBytes.values()].reduce((sum, size) => sum + size, 0);
|
|
83
|
+
if (manifestBytes + bytes > this.limits.subjectManifestBytes) {
|
|
84
|
+
throw new SourceError(413, `the server keeps at most ${this.limits.subjectManifestBytes} bytes of trees for you, delete one with DELETE /v1/sources/<snapshot>`);
|
|
85
|
+
}
|
|
86
|
+
// taken before the write, so announcements at once can not pass the limits together
|
|
75
87
|
subject.manifests.set(snapshot, stored);
|
|
88
|
+
subject.manifestBytes.set(snapshot, bytes);
|
|
89
|
+
try {
|
|
90
|
+
await (0, promises_1.mkdir)((0, path_1.join)(this.directory, key, 'manifests'), { recursive: true });
|
|
91
|
+
await this.write((0, path_1.join)(this.directory, key, 'manifests', `${snapshot.slice('sha256:'.length)}.json`), content);
|
|
92
|
+
}
|
|
93
|
+
catch (e) {
|
|
94
|
+
subject.manifests.delete(snapshot);
|
|
95
|
+
subject.manifestBytes.delete(snapshot);
|
|
96
|
+
throw e;
|
|
97
|
+
}
|
|
76
98
|
for (const [digest, size] of sizes) {
|
|
77
99
|
subject.wanted.set(digest, size);
|
|
78
100
|
}
|
|
@@ -91,14 +113,38 @@ class SourceStore {
|
|
|
91
113
|
throw new SourceError(400, 'this file is not part of a tree you announced');
|
|
92
114
|
}
|
|
93
115
|
const target = this.blob(key, digest);
|
|
116
|
+
// the same file sent twice at once is received once: the second waits for the first
|
|
117
|
+
for (let pending = subject.sending.get(digest); pending; pending = subject.sending.get(digest)) {
|
|
118
|
+
await pending;
|
|
119
|
+
}
|
|
94
120
|
if (await exists(target)) {
|
|
95
121
|
body.resume();
|
|
96
122
|
return 'exists';
|
|
97
123
|
}
|
|
98
|
-
|
|
124
|
+
// a send that came in while this one looked waits for this one
|
|
125
|
+
if (subject.sending.has(digest)) {
|
|
126
|
+
return this.put(principal, digest, body);
|
|
127
|
+
}
|
|
128
|
+
// files being received count too: uploads at once can not pass the limit together
|
|
129
|
+
if (subject.stored + subject.receiving + size > this.limits.subjectBytes) {
|
|
99
130
|
body.resume();
|
|
100
131
|
throw new SourceError(413, `the server keeps at most ${this.limits.subjectBytes} bytes of files for you`);
|
|
101
132
|
}
|
|
133
|
+
subject.receiving += size;
|
|
134
|
+
const received = this.receive(subject, key, digest, size, target, body);
|
|
135
|
+
const settled = received.then(() => undefined, () => undefined);
|
|
136
|
+
subject.sending.set(digest, settled);
|
|
137
|
+
try {
|
|
138
|
+
return await received;
|
|
139
|
+
}
|
|
140
|
+
finally {
|
|
141
|
+
subject.receiving -= size;
|
|
142
|
+
if (subject.sending.get(digest) === settled) {
|
|
143
|
+
subject.sending.delete(digest);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
async receive(subject, key, digest, size, target, body) {
|
|
102
148
|
await (0, promises_1.mkdir)((0, path_1.join)(this.directory, key, 'blobs'), { recursive: true });
|
|
103
149
|
const temporary = `${target}.${(0, crypto_2.randomBytes)(8).toString('hex')}.tmp`;
|
|
104
150
|
const hash = (0, crypto_1.createHash)('sha256');
|
|
@@ -166,6 +212,7 @@ class SourceStore {
|
|
|
166
212
|
if (!subject.manifests.delete(snapshot)) {
|
|
167
213
|
return false;
|
|
168
214
|
}
|
|
215
|
+
subject.manifestBytes.delete(snapshot);
|
|
169
216
|
await (0, promises_1.rm)((0, path_1.join)(this.directory, key, 'manifests', `${snapshot.slice('sha256:'.length)}.json`), { force: true });
|
|
170
217
|
const kept = new Map();
|
|
171
218
|
for (const stored of subject.manifests.values()) {
|
|
@@ -202,9 +249,9 @@ class SourceStore {
|
|
|
202
249
|
blob(key, digest) {
|
|
203
250
|
return (0, path_1.join)(this.directory, key, 'blobs', digest);
|
|
204
251
|
}
|
|
205
|
-
async write(file,
|
|
252
|
+
async write(file, content) {
|
|
206
253
|
const temporary = `${file}.${(0, crypto_2.randomBytes)(8).toString('hex')}.tmp`;
|
|
207
|
-
await (0, promises_1.writeFile)(temporary,
|
|
254
|
+
await (0, promises_1.writeFile)(temporary, content, { flag: 'wx' });
|
|
208
255
|
await (0, promises_1.rename)(temporary, file);
|
|
209
256
|
}
|
|
210
257
|
// Reads what is kept for one caller the first time they are seen.
|
|
@@ -217,7 +264,14 @@ class SourceStore {
|
|
|
217
264
|
return loaded;
|
|
218
265
|
}
|
|
219
266
|
async load(key) {
|
|
220
|
-
const subject = {
|
|
267
|
+
const subject = {
|
|
268
|
+
wanted: new Map(),
|
|
269
|
+
stored: 0,
|
|
270
|
+
receiving: 0,
|
|
271
|
+
sending: new Map(),
|
|
272
|
+
manifests: new Map(),
|
|
273
|
+
manifestBytes: new Map(),
|
|
274
|
+
};
|
|
221
275
|
const manifests = (0, path_1.join)(this.directory, key, 'manifests');
|
|
222
276
|
let names = [];
|
|
223
277
|
try {
|
|
@@ -227,8 +281,11 @@ class SourceStore {
|
|
|
227
281
|
return subject;
|
|
228
282
|
}
|
|
229
283
|
for (const name of names.filter((n) => n.endsWith('.json'))) {
|
|
230
|
-
const
|
|
231
|
-
|
|
284
|
+
const content = await (0, promises_1.readFile)((0, path_1.join)(manifests, name), 'utf8');
|
|
285
|
+
const stored = JSON.parse(content);
|
|
286
|
+
const snapshot = (0, source_manifest_1.hashSource)(stored.manifest);
|
|
287
|
+
subject.manifests.set(snapshot, stored);
|
|
288
|
+
subject.manifestBytes.set(snapshot, Buffer.byteLength(content, 'utf8'));
|
|
232
289
|
for (const file of stored.manifest.files) {
|
|
233
290
|
subject.wanted.set(file.sha256, file.size);
|
|
234
291
|
}
|
|
@@ -1,42 +1,52 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.BufferContext = void 0;
|
|
4
|
+
// The last `limit` entries of each id, and all of those in the order they came. An entry an id
|
|
5
|
+
// no longer keeps leaves both; the list of all of them drops what left now and then, so an
|
|
6
|
+
// entry costs the same however many ids there are.
|
|
4
7
|
class BufferContext {
|
|
5
8
|
constructor(limit) {
|
|
6
9
|
this.limit = limit;
|
|
7
|
-
this.scopedBuffer =
|
|
10
|
+
this.scopedBuffer = new Map();
|
|
8
11
|
this.buffer = [];
|
|
12
|
+
this.dropped = 0;
|
|
9
13
|
}
|
|
10
14
|
add(id, data) {
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
const bufferIndex = this.buffer.indexOf(removedBuffer);
|
|
18
|
-
if (bufferIndex >= 0) {
|
|
19
|
-
this.buffer.splice(bufferIndex, 1);
|
|
20
|
-
}
|
|
21
|
-
}
|
|
15
|
+
const entry = { data, kept: true };
|
|
16
|
+
this.buffer.push(entry);
|
|
17
|
+
let scopedBuffer = this.scopedBuffer.get(id);
|
|
18
|
+
if (!scopedBuffer) {
|
|
19
|
+
scopedBuffer = [];
|
|
20
|
+
this.scopedBuffer.set(id, scopedBuffer);
|
|
22
21
|
}
|
|
23
|
-
|
|
24
|
-
|
|
22
|
+
scopedBuffer.push(entry);
|
|
23
|
+
if (scopedBuffer.length > this.limit) {
|
|
24
|
+
const removed = scopedBuffer.shift();
|
|
25
|
+
removed.kept = false;
|
|
26
|
+
this.dropped++;
|
|
27
|
+
if (this.dropped * 2 > this.buffer.length) {
|
|
28
|
+
this.compact();
|
|
29
|
+
}
|
|
25
30
|
}
|
|
26
31
|
}
|
|
27
32
|
current(id) {
|
|
28
|
-
|
|
33
|
+
const value = this.scopedBuffer.get(id);
|
|
34
|
+
if (!value || value.length === 0) {
|
|
29
35
|
return null;
|
|
30
36
|
}
|
|
31
|
-
|
|
32
|
-
return value[value.length - 1];
|
|
37
|
+
return value[value.length - 1].data;
|
|
33
38
|
}
|
|
34
39
|
get(id) {
|
|
35
40
|
if (id) {
|
|
36
|
-
return this.scopedBuffer
|
|
41
|
+
return (this.scopedBuffer.get(id) ?? []).map((entry) => entry.data);
|
|
37
42
|
}
|
|
38
|
-
|
|
39
|
-
|
|
43
|
+
this.compact();
|
|
44
|
+
return this.buffer.map((entry) => entry.data);
|
|
45
|
+
}
|
|
46
|
+
compact() {
|
|
47
|
+
if (this.dropped > 0) {
|
|
48
|
+
this.buffer = this.buffer.filter((entry) => entry.kept);
|
|
49
|
+
this.dropped = 0;
|
|
40
50
|
}
|
|
41
51
|
}
|
|
42
52
|
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.readLines = void 0;
|
|
4
|
+
const string_decoder_1 = require("string_decoder");
|
|
5
|
+
/**
|
|
6
|
+
* Calls `onLine` with each line of `input` as readline does: a line ends at a line feed, a CR
|
|
7
|
+
* or both. It holds at most `maxChars` of a line: a longer line is cut there and says so, the
|
|
8
|
+
* rest of it up to the end of the line is passed over.
|
|
9
|
+
*/
|
|
10
|
+
function readLines(input, maxChars, onLine) {
|
|
11
|
+
const decoder = new string_decoder_1.StringDecoder('utf8');
|
|
12
|
+
let pending = '';
|
|
13
|
+
let cut = false;
|
|
14
|
+
// the last line ended with a CR, so a line feed right after it ends no other line
|
|
15
|
+
let afterCr = false;
|
|
16
|
+
const emit = () => {
|
|
17
|
+
onLine(cut ? `${pending} … [cut at ${maxChars} characters]` : pending);
|
|
18
|
+
pending = '';
|
|
19
|
+
cut = false;
|
|
20
|
+
};
|
|
21
|
+
const take = (text) => {
|
|
22
|
+
let start = 0;
|
|
23
|
+
if (afterCr && text.length > 0) {
|
|
24
|
+
afterCr = false;
|
|
25
|
+
if (text[0] === '\n') {
|
|
26
|
+
start = 1;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
const ends = /[\r\n]/g;
|
|
30
|
+
for (;;) {
|
|
31
|
+
ends.lastIndex = start;
|
|
32
|
+
const end = ends.exec(text);
|
|
33
|
+
if (!cut) {
|
|
34
|
+
pending += text.slice(start, end ? end.index : undefined);
|
|
35
|
+
if (pending.length > maxChars) {
|
|
36
|
+
pending = pending.slice(0, maxChars);
|
|
37
|
+
cut = true;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
if (!end) {
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
emit();
|
|
44
|
+
start = end.index + 1;
|
|
45
|
+
if (end[0] === '\r') {
|
|
46
|
+
if (start === text.length) {
|
|
47
|
+
afterCr = true;
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
if (text[start] === '\n') {
|
|
51
|
+
start++;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
input.on('data', (chunk) => take(typeof chunk === 'string' ? chunk : decoder.write(chunk)));
|
|
57
|
+
input.on('end', () => {
|
|
58
|
+
take(decoder.end());
|
|
59
|
+
if (pending.length > 0 || cut) {
|
|
60
|
+
emit();
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
exports.readLines = readLines;
|
|
65
|
+
//# sourceMappingURL=read-lines.js.map
|
package/package.json
CHANGED