omics-os 0.0.1 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +664 -0
- package/README.md +384 -4
- package/package.json +34 -12
- package/packages/cli/dist/index.js +154 -0
- package/packages/cloud-client/dist/agents.d.ts +20 -0
- package/packages/cloud-client/dist/agents.js +69 -0
- package/packages/cloud-client/dist/apiClient.d.ts +44 -0
- package/packages/cloud-client/dist/apiClient.js +368 -0
- package/packages/cloud-client/dist/auth.d.ts +76 -0
- package/packages/cloud-client/dist/auth.js +462 -0
- package/packages/cloud-client/dist/biovault/approval.d.ts +40 -0
- package/packages/cloud-client/dist/biovault/approval.js +38 -0
- package/packages/cloud-client/dist/biovault/assurance.d.ts +10 -0
- package/packages/cloud-client/dist/biovault/assurance.js +14 -0
- package/packages/cloud-client/dist/biovault/client.d.ts +76 -0
- package/packages/cloud-client/dist/biovault/client.js +212 -0
- package/packages/cloud-client/dist/biovault/compat.d.ts +29 -0
- package/packages/cloud-client/dist/biovault/compat.js +90 -0
- package/packages/cloud-client/dist/biovault/entries.d.ts +143 -0
- package/packages/cloud-client/dist/biovault/entries.js +359 -0
- package/packages/cloud-client/dist/biovault/errors.d.ts +18 -0
- package/packages/cloud-client/dist/biovault/errors.js +90 -0
- package/packages/cloud-client/dist/biovault/fields.d.ts +7 -0
- package/packages/cloud-client/dist/biovault/fields.js +42 -0
- package/packages/cloud-client/dist/biovault/identity.d.ts +10 -0
- package/packages/cloud-client/dist/biovault/identity.js +43 -0
- package/packages/cloud-client/dist/biovault/index.d.ts +15 -0
- package/packages/cloud-client/dist/biovault/index.js +16 -0
- package/packages/cloud-client/dist/biovault/instructionMatch.d.ts +32 -0
- package/packages/cloud-client/dist/biovault/instructionMatch.js +118 -0
- package/packages/cloud-client/dist/biovault/pending.d.ts +41 -0
- package/packages/cloud-client/dist/biovault/pending.js +208 -0
- package/packages/cloud-client/dist/biovault/preCommit.d.ts +10 -0
- package/packages/cloud-client/dist/biovault/preCommit.js +10 -0
- package/packages/cloud-client/dist/biovault/provenance.d.ts +45 -0
- package/packages/cloud-client/dist/biovault/provenance.js +55 -0
- package/packages/cloud-client/dist/biovault/vendor/packageDeliveryV1.generated.d.ts +3981 -0
- package/packages/cloud-client/dist/biovault/vendor/packageDeliveryV1.generated.js +3632 -0
- package/packages/cloud-client/dist/biovault/vendor/runV1.generated.d.ts +2326 -0
- package/packages/cloud-client/dist/biovault/vendor/runV1.generated.js +491 -0
- package/packages/cloud-client/dist/biovault/wireShape.d.ts +25 -0
- package/packages/cloud-client/dist/biovault/wireShape.js +88 -0
- package/packages/cloud-client/dist/bootstrap.d.ts +4 -0
- package/packages/cloud-client/dist/bootstrap.js +19 -0
- package/packages/cloud-client/dist/config.d.ts +44 -0
- package/packages/cloud-client/dist/config.js +309 -0
- package/packages/cloud-client/dist/credentials.d.ts +96 -0
- package/packages/cloud-client/dist/credentials.js +395 -0
- package/packages/cloud-client/dist/editor.d.ts +77 -0
- package/packages/cloud-client/dist/editor.js +278 -0
- package/packages/cloud-client/dist/errors.d.ts +27 -0
- package/packages/cloud-client/dist/errors.js +102 -0
- package/packages/cloud-client/dist/exports.d.ts +19 -0
- package/packages/cloud-client/dist/exports.js +85 -0
- package/packages/cloud-client/dist/featureFlags.d.ts +10 -0
- package/packages/cloud-client/dist/featureFlags.js +36 -0
- package/packages/cloud-client/dist/files.d.ts +35 -0
- package/packages/cloud-client/dist/files.js +109 -0
- package/packages/cloud-client/dist/index.d.ts +29 -0
- package/packages/cloud-client/dist/index.js +22 -0
- package/packages/cloud-client/dist/multipartUpload.d.ts +99 -0
- package/packages/cloud-client/dist/multipartUpload.js +624 -0
- package/packages/cloud-client/dist/projects.d.ts +42 -0
- package/packages/cloud-client/dist/projects.js +119 -0
- package/packages/cloud-client/dist/resources.d.ts +8 -0
- package/packages/cloud-client/dist/resources.js +26 -0
- package/packages/cloud-client/dist/sessions.d.ts +67 -0
- package/packages/cloud-client/dist/sessions.js +187 -0
- package/packages/cloud-client/dist/templates.d.ts +4 -0
- package/packages/cloud-client/dist/templates.js +12 -0
- package/packages/cloud-client/dist/types.d.ts +431 -0
- package/packages/cloud-client/dist/types.js +94 -0
- package/packages/cloud-client/dist/uploads.d.ts +93 -0
- package/packages/cloud-client/dist/uploads.js +61 -0
- package/packages/cloud-client/dist/vault.d.ts +20 -0
- package/packages/cloud-client/dist/vault.js +43 -0
- package/packages/cloud-client/dist/vectorSearch.d.ts +3 -0
- package/packages/cloud-client/dist/vectorSearch.js +12 -0
- package/packages/tui/dist/lobster.mjs +273 -0
- package/skills/omics-os-cloud/SKILL.md +24 -0
- package/skills/omics-os-lobster/SKILL.md +24 -0
- package/bin/omics-os.js +0 -5
|
@@ -0,0 +1,624 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resumable upload of one local file into a project's data, at its relative path.
|
|
3
|
+
*
|
|
4
|
+
* The bytes go straight to presigned S3 part URLs with node:http(s) and a
|
|
5
|
+
* stream pipeline, so memory stays bounded whatever the file size (fetch with a
|
|
6
|
+
* stream body buffers the whole file). Each part is read twice: once to hash
|
|
7
|
+
* it (S3 checks the SHA-256 the URL is signed for), once to send it.
|
|
8
|
+
*
|
|
9
|
+
* Resume state lives on the server: start (C1) finds the open upload for the
|
|
10
|
+
* same project, path, size and fingerprint, and status (C3) lists the parts S3
|
|
11
|
+
* holds. Listed parts are trusted on that match (as DNAnexus and tus do), unless
|
|
12
|
+
* the mtime stored with the upload differs from the file's: then each listed part
|
|
13
|
+
* is re-hashed and compared first. A file whose size or mtime changes during the
|
|
14
|
+
* run is not completed.
|
|
15
|
+
*
|
|
16
|
+
* One path holds one current file: a different file already there is refused
|
|
17
|
+
* (file_exists) unless `replace`, and the server's other refusals of one file
|
|
18
|
+
* come back as an UploadFailure with the server's words.
|
|
19
|
+
*/
|
|
20
|
+
import { createHash } from "node:crypto";
|
|
21
|
+
import { open, stat } from "node:fs/promises";
|
|
22
|
+
import http from "node:http";
|
|
23
|
+
import https from "node:https";
|
|
24
|
+
import { ApiError, RateLimitError, UnknownOutcomeError } from "./types.js";
|
|
25
|
+
import { abortUpload, completeUpload, getUpload, signUploadParts, startUpload, uploadErrorCode, MAX_SIGN_BATCH, } from "./uploads.js";
|
|
26
|
+
const MiB = 1024 * 1024;
|
|
27
|
+
const FINGERPRINT_EDGE = 8 * MiB;
|
|
28
|
+
const READ_CHUNK = MiB;
|
|
29
|
+
export const DEFAULT_UPLOAD_CONCURRENCY = 4;
|
|
30
|
+
export const MAX_UPLOAD_CONCURRENCY = 16;
|
|
31
|
+
/** Re-sign a part URL this long before the server says it expires. */
|
|
32
|
+
const RESIGN_MARGIN_MS = 60_000;
|
|
33
|
+
/** Wait this long for "100 Continue" before sending the body anyway. */
|
|
34
|
+
const CONTINUE_WAIT_MS = 3_000;
|
|
35
|
+
const MAX_ERROR_BODY = 16 * 1024;
|
|
36
|
+
/** Headers a part PUT never carries, whatever the server returns. */
|
|
37
|
+
const NEVER_SEND = new Set(["authorization", "x-api-key", "cookie", "proxy-authorization", "host", "content-length"]);
|
|
38
|
+
/** A file could not be uploaded. The message is fit to show; `reason` is for scripts. */
|
|
39
|
+
export class UploadFailure extends Error {
|
|
40
|
+
reason;
|
|
41
|
+
/** On not_current: the version this upload created, kept as a noncurrent version. */
|
|
42
|
+
versionId;
|
|
43
|
+
constructor(reason, message, options) {
|
|
44
|
+
super(message, options);
|
|
45
|
+
this.reason = reason;
|
|
46
|
+
this.name = "UploadFailure";
|
|
47
|
+
if (options?.versionId)
|
|
48
|
+
this.versionId = options.versionId;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/** Server codes that refuse one file; the run goes on with the others. */
|
|
52
|
+
const FILE_REFUSALS = new Set(["file_exists", "upload_in_progress", "quota_exceeded", "upload_too_large", "not_current", "complete_conflict"]);
|
|
53
|
+
/** A refusal of this one file, in the server's words, or the error unchanged. */
|
|
54
|
+
function asFileRefusal(error) {
|
|
55
|
+
if (!(error instanceof ApiError))
|
|
56
|
+
return error;
|
|
57
|
+
const code = uploadErrorCode(error);
|
|
58
|
+
// The server owns the path rules (length, `..`, `.trash`); a 400 on start is one of them.
|
|
59
|
+
const reason = code && FILE_REFUSALS.has(code) ? code : error.status === 400 && error.path === "/uploads" ? "invalid_path" : undefined;
|
|
60
|
+
if (!reason)
|
|
61
|
+
return error;
|
|
62
|
+
const versionId = typeof error.body?.version_id === "string" ? error.body.version_id : undefined;
|
|
63
|
+
return new UploadFailure(reason, error.detail || error.message, { cause: error, ...(versionId ? { versionId } : {}) });
|
|
64
|
+
}
|
|
65
|
+
/** S3 refused a part PUT. */
|
|
66
|
+
export class PartPutError extends Error {
|
|
67
|
+
status;
|
|
68
|
+
s3Code;
|
|
69
|
+
constructor(status, s3Code, message) {
|
|
70
|
+
super(message);
|
|
71
|
+
this.status = status;
|
|
72
|
+
this.s3Code = s3Code;
|
|
73
|
+
this.name = "PartPutError";
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
export function createLimiter(size) {
|
|
77
|
+
let active = 0;
|
|
78
|
+
const waiting = [];
|
|
79
|
+
return {
|
|
80
|
+
async run(task) {
|
|
81
|
+
if (active >= size)
|
|
82
|
+
await new Promise((resolve) => waiting.push(resolve));
|
|
83
|
+
active++;
|
|
84
|
+
try {
|
|
85
|
+
return await task();
|
|
86
|
+
}
|
|
87
|
+
finally {
|
|
88
|
+
active--;
|
|
89
|
+
waiting.shift()?.();
|
|
90
|
+
}
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
function partRange(g, part) {
|
|
95
|
+
const start = (part - 1) * g.partSize;
|
|
96
|
+
const endExclusive = Math.min(g.size, part * g.partSize);
|
|
97
|
+
return { start, end: endExclusive - 1, length: endExclusive - start };
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Read bytes start..end (inclusive) into one reused buffer, handing each filled slice to `use` and
|
|
101
|
+
* waiting for it before the buffer is read into again. A stream would allocate a new buffer per
|
|
102
|
+
* read, and at disk speed that churn alone held ~200 MB of RSS on a 10 GB file.
|
|
103
|
+
*/
|
|
104
|
+
async function readRange(path, start, end, use, signal) {
|
|
105
|
+
const file = await open(path, "r");
|
|
106
|
+
try {
|
|
107
|
+
const buffer = Buffer.allocUnsafe(Math.min(READ_CHUNK, end - start + 1));
|
|
108
|
+
for (let at = start; at <= end;) {
|
|
109
|
+
signal?.throwIfAborted();
|
|
110
|
+
const { bytesRead } = await file.read(buffer, 0, Math.min(buffer.length, end - at + 1), at);
|
|
111
|
+
if (bytesRead === 0)
|
|
112
|
+
throw new UploadFailure("file_changed", "the file got shorter while it was being read");
|
|
113
|
+
await use(buffer.subarray(0, bytesRead));
|
|
114
|
+
at += bytesRead;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
finally {
|
|
118
|
+
await file.close().catch(() => { });
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
function hashInto(hash, path, start, end, signal, onBytes) {
|
|
122
|
+
return readRange(path, start, end, (chunk) => { hash.update(chunk); onBytes?.(chunk.length); }, signal);
|
|
123
|
+
}
|
|
124
|
+
/** Hex SHA-256 over the first and last 8 MiB and the size (the whole file and the size up to 16 MiB). */
|
|
125
|
+
export async function fingerprintFile(path, size, signal) {
|
|
126
|
+
const hash = createHash("sha256");
|
|
127
|
+
if (size <= 2 * FINGERPRINT_EDGE) {
|
|
128
|
+
if (size > 0)
|
|
129
|
+
await hashInto(hash, path, 0, size - 1, signal);
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
await hashInto(hash, path, 0, FINGERPRINT_EDGE - 1, signal);
|
|
133
|
+
await hashInto(hash, path, size - FINGERPRINT_EDGE, size - 1, signal);
|
|
134
|
+
}
|
|
135
|
+
hash.update(String(size));
|
|
136
|
+
return hash.digest("hex");
|
|
137
|
+
}
|
|
138
|
+
/** Base64 SHA-256 of one byte range, the form S3 uses for x-amz-checksum-sha256. */
|
|
139
|
+
export async function hashRange(path, start, end, signal, onBytes) {
|
|
140
|
+
const hash = createHash("sha256");
|
|
141
|
+
await hashInto(hash, path, start, end, signal, onBytes);
|
|
142
|
+
return hash.digest("base64");
|
|
143
|
+
}
|
|
144
|
+
function allowedPartUrl(raw) {
|
|
145
|
+
let url;
|
|
146
|
+
try {
|
|
147
|
+
url = new URL(raw);
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
throw new UploadFailure("server", "The server returned an unreadable upload link.");
|
|
151
|
+
}
|
|
152
|
+
const loopback = url.hostname === "127.0.0.1" || url.hostname === "localhost" || url.hostname === "[::1]";
|
|
153
|
+
if (url.protocol === "https:" || (url.protocol === "http:" && loopback))
|
|
154
|
+
return url;
|
|
155
|
+
throw new UploadFailure("server", "The server returned an upload link that is not HTTPS; nothing was sent.");
|
|
156
|
+
}
|
|
157
|
+
function partHeaders(signed, length) {
|
|
158
|
+
const headers = {};
|
|
159
|
+
for (const [key, value] of Object.entries(signed.headers ?? {})) {
|
|
160
|
+
if (!NEVER_SEND.has(key.toLowerCase()))
|
|
161
|
+
headers[key] = value;
|
|
162
|
+
}
|
|
163
|
+
headers["Content-Length"] = String(length);
|
|
164
|
+
headers.Expect = "100-continue";
|
|
165
|
+
return headers;
|
|
166
|
+
}
|
|
167
|
+
function s3Code(body) {
|
|
168
|
+
return /<Code>([^<]{1,64})<\/Code>/.exec(body)?.[1];
|
|
169
|
+
}
|
|
170
|
+
/** PUT one byte range to a presigned URL. Resolves with the ETag. Never follows a redirect. */
|
|
171
|
+
function putPart(signed, path, range, agent, signal, idleTimeoutMs, onBytes) {
|
|
172
|
+
const url = allowedPartUrl(signed.url);
|
|
173
|
+
const transport = url.protocol === "https:" ? https : http;
|
|
174
|
+
return new Promise((resolve, reject) => {
|
|
175
|
+
let settled = false;
|
|
176
|
+
const finish = (error, etag) => {
|
|
177
|
+
if (settled)
|
|
178
|
+
return;
|
|
179
|
+
settled = true;
|
|
180
|
+
clearTimeout(continueTimer);
|
|
181
|
+
if (error) {
|
|
182
|
+
req.destroy();
|
|
183
|
+
reject(error);
|
|
184
|
+
}
|
|
185
|
+
else
|
|
186
|
+
resolve(etag);
|
|
187
|
+
};
|
|
188
|
+
const req = transport.request(url, { method: "PUT", headers: partHeaders(signed, range.length), agent, signal });
|
|
189
|
+
let started = false;
|
|
190
|
+
let continueTimer;
|
|
191
|
+
// Resolves once the chunk is handed to the socket, so the read buffer can be reused.
|
|
192
|
+
const write = (chunk) => new Promise((done, fail) => {
|
|
193
|
+
if (settled) {
|
|
194
|
+
fail(new Error("part transfer ended"));
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
const closed = () => fail(new Error("connection closed"));
|
|
198
|
+
req.once("close", closed);
|
|
199
|
+
req.write(chunk, (error) => {
|
|
200
|
+
req.off("close", closed);
|
|
201
|
+
if (error)
|
|
202
|
+
fail(error);
|
|
203
|
+
else {
|
|
204
|
+
onBytes(chunk.length);
|
|
205
|
+
done();
|
|
206
|
+
}
|
|
207
|
+
});
|
|
208
|
+
});
|
|
209
|
+
const sendBody = () => {
|
|
210
|
+
if (started || settled)
|
|
211
|
+
return;
|
|
212
|
+
started = true;
|
|
213
|
+
clearTimeout(continueTimer);
|
|
214
|
+
readRange(path, range.start, range.end, write)
|
|
215
|
+
.then(() => { if (!settled)
|
|
216
|
+
req.end(); })
|
|
217
|
+
// A refusal can close the socket mid-body; let its response win.
|
|
218
|
+
.catch((error) => setTimeout(() => finish(error), 100));
|
|
219
|
+
};
|
|
220
|
+
req.setTimeout(idleTimeoutMs, () => finish(new Error(`no progress for ${Math.round(idleTimeoutMs / 1000)} s`)));
|
|
221
|
+
req.on("continue", sendBody);
|
|
222
|
+
req.on("error", (error) => setTimeout(() => finish(error), 100));
|
|
223
|
+
req.on("response", (res) => {
|
|
224
|
+
const status = res.statusCode ?? 0;
|
|
225
|
+
if (status === 200) {
|
|
226
|
+
res.resume();
|
|
227
|
+
res.on("end", () => {
|
|
228
|
+
const etag = res.headers.etag;
|
|
229
|
+
if (typeof etag === "string" && etag)
|
|
230
|
+
finish(undefined, etag);
|
|
231
|
+
else
|
|
232
|
+
finish(new PartPutError(status, undefined, "storage accepted a part without an ETag"));
|
|
233
|
+
});
|
|
234
|
+
res.on("error", (error) => finish(error));
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
let body = "";
|
|
238
|
+
res.setEncoding("utf8");
|
|
239
|
+
res.on("data", (chunk) => { if (body.length < MAX_ERROR_BODY)
|
|
240
|
+
body += chunk; });
|
|
241
|
+
const refuse = () => {
|
|
242
|
+
const code = s3Code(body);
|
|
243
|
+
finish(new PartPutError(status, code, `storage answered ${status}${code ? ` ${code}` : ""}`));
|
|
244
|
+
};
|
|
245
|
+
res.on("end", refuse);
|
|
246
|
+
res.on("error", refuse);
|
|
247
|
+
});
|
|
248
|
+
req.flushHeaders();
|
|
249
|
+
continueTimer = setTimeout(sendBody, CONTINUE_WAIT_MS);
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
const RETRYABLE_S3 = new Set(["RequestTimeout", "SlowDown", "InternalError", "ServiceUnavailable"]);
|
|
253
|
+
const DIGEST_S3 = new Set(["BadDigest", "InvalidDigest", "XAmzContentSHA256Mismatch", "XAmzContentChecksumMismatch"]);
|
|
254
|
+
function backoff(attempt, baseMs, signal) {
|
|
255
|
+
const ms = Math.min(60_000, baseMs * 2 ** attempt) * (0.75 + Math.random() * 0.5);
|
|
256
|
+
return new Promise((resolve, reject) => {
|
|
257
|
+
if (signal.aborted) {
|
|
258
|
+
reject(signal.reason);
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
const abort = () => { clearTimeout(timer); reject(signal.reason); };
|
|
262
|
+
const timer = setTimeout(() => { signal.removeEventListener("abort", abort); resolve(); }, ms);
|
|
263
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* Start, sign and complete run once per file against per-minute server limits, so a folder of small files meets
|
|
268
|
+
* them. A 429 means the server did nothing: pause and ask again instead of failing the file. Without
|
|
269
|
+
* Retry-After the window is unknown, so each pause is at least 5 × the retry base (5 s); 24 pauses outlast a minute.
|
|
270
|
+
* A 409 complete_in_progress (another Complete of this upload is running) is waited out the same way, but for the
|
|
271
|
+
* server's grace (15 min) rather than 24 pauses: asking stops 960 × the retry base (16 min) after the first one.
|
|
272
|
+
*/
|
|
273
|
+
const RATE_LIMIT_PAUSES = 24;
|
|
274
|
+
const COMPLETE_WAIT_BASES = 960;
|
|
275
|
+
async function patiently(call, retryBaseMs, signal) {
|
|
276
|
+
let limited = 0;
|
|
277
|
+
let completeDeadline;
|
|
278
|
+
for (;;) {
|
|
279
|
+
try {
|
|
280
|
+
return await call();
|
|
281
|
+
}
|
|
282
|
+
catch (error) {
|
|
283
|
+
if (uploadErrorCode(error) === "complete_in_progress") {
|
|
284
|
+
completeDeadline ??= Date.now() + COMPLETE_WAIT_BASES * retryBaseMs;
|
|
285
|
+
if (Date.now() >= completeDeadline)
|
|
286
|
+
throw error;
|
|
287
|
+
}
|
|
288
|
+
else if (!(error instanceof RateLimitError) || limited++ >= RATE_LIMIT_PAUSES) {
|
|
289
|
+
throw error;
|
|
290
|
+
}
|
|
291
|
+
await backoff(0, Math.max(error.retryAfterMs ?? 0, 5 * retryBaseMs), signal);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
async function mapLimit(items, limit, fn) {
|
|
296
|
+
const out = new Array(items.length);
|
|
297
|
+
let next = 0;
|
|
298
|
+
const worker = async () => {
|
|
299
|
+
while (next < items.length) {
|
|
300
|
+
const i = next++;
|
|
301
|
+
out[i] = await fn(items[i]);
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
|
305
|
+
return out;
|
|
306
|
+
}
|
|
307
|
+
/** Upload one file; resumes an earlier upload of the same file when the server still holds it. */
|
|
308
|
+
export function uploadProjectFile(config, options) {
|
|
309
|
+
return uploadFile(config, options).catch((error) => { throw asFileRefusal(error); });
|
|
310
|
+
}
|
|
311
|
+
async function uploadFile(config, options) {
|
|
312
|
+
const concurrency = options.concurrency ?? DEFAULT_UPLOAD_CONCURRENCY;
|
|
313
|
+
if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > MAX_UPLOAD_CONCURRENCY) {
|
|
314
|
+
throw new RangeError(`concurrency must be 1–${MAX_UPLOAD_CONCURRENCY}`);
|
|
315
|
+
}
|
|
316
|
+
const outer = options.signal ?? new AbortController().signal;
|
|
317
|
+
outer.throwIfAborted();
|
|
318
|
+
const before = await stat(options.path);
|
|
319
|
+
if (!before.isFile())
|
|
320
|
+
throw new UploadFailure("not_regular", "not a regular file");
|
|
321
|
+
if (before.size === 0)
|
|
322
|
+
throw new UploadFailure("empty", "empty file");
|
|
323
|
+
const size = before.size;
|
|
324
|
+
const mtimeMs = Math.floor(before.mtimeMs);
|
|
325
|
+
const fingerprint = await fingerprintFile(options.path, size, outer);
|
|
326
|
+
let replace = false;
|
|
327
|
+
/** When the caller asked to overwrite and the path is taken: start again with replace, once. */
|
|
328
|
+
const overwrite = (error) => {
|
|
329
|
+
const code = uploadErrorCode(error);
|
|
330
|
+
return options.replace === true && !replace && (code === "file_exists" || code === "upload_in_progress");
|
|
331
|
+
};
|
|
332
|
+
let replaced = false;
|
|
333
|
+
let restarted;
|
|
334
|
+
// A restart happens when a resume finds changed parts, the upload expired or vanished, or its completion conflicted.
|
|
335
|
+
for (let round = 0; round < 4; round++) {
|
|
336
|
+
let start;
|
|
337
|
+
try {
|
|
338
|
+
start = await patiently(() => startUpload(config, {
|
|
339
|
+
project_id: options.projectId, relative_path: options.relativePath, size_bytes: size,
|
|
340
|
+
fingerprint, client_sha256: null, mtime_ms: mtimeMs, ...(replace ? { replace: true } : {}),
|
|
341
|
+
}, outer), options.retryBaseMs ?? 1000, outer);
|
|
342
|
+
}
|
|
343
|
+
catch (error) {
|
|
344
|
+
if (!overwrite(error))
|
|
345
|
+
throw error;
|
|
346
|
+
replace = true;
|
|
347
|
+
continue;
|
|
348
|
+
}
|
|
349
|
+
if (start.state === "completed") {
|
|
350
|
+
if (replaced)
|
|
351
|
+
throw new UploadFailure("server", "the server kept answering 'already uploaded' after a replace; stopped");
|
|
352
|
+
return {
|
|
353
|
+
outcome: "skipped", relativePath: start.relative_path ?? options.relativePath, sizeBytes: size, partsSent: 0, partsReused: 0,
|
|
354
|
+
...(start.version_id ? { versionId: start.version_id } : {}), ...(start.match ? { match: start.match } : {}),
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
if (replace)
|
|
358
|
+
replaced = true;
|
|
359
|
+
if (!start.upload_id)
|
|
360
|
+
throw new UploadFailure("server", "the server started an upload without an id");
|
|
361
|
+
const geometry = { size, partSize: start.part_size_bytes, partCount: start.part_count };
|
|
362
|
+
if (!(geometry.partSize > 0) || geometry.partCount !== Math.ceil(size / geometry.partSize)) {
|
|
363
|
+
throw new UploadFailure("server", "the server's part layout does not fit the file size");
|
|
364
|
+
}
|
|
365
|
+
const uploadId = start.upload_id;
|
|
366
|
+
let reused = [];
|
|
367
|
+
let trust = "none";
|
|
368
|
+
let done;
|
|
369
|
+
let missing;
|
|
370
|
+
try {
|
|
371
|
+
if (start.state === "open" || start.state === "completing") {
|
|
372
|
+
// Like DNAnexus and tus: trust the server's match on path, size and fingerprint. Only when the
|
|
373
|
+
// stored mtime differs (the file was touched or copied) are the sent parts read and compared.
|
|
374
|
+
const recheck = typeof start.mtime_ms === "number" && start.mtime_ms !== mtimeMs;
|
|
375
|
+
const verdict = start.state === "completing" ? "completing" : await serverParts(config, uploadId, options, geometry, recheck, outer);
|
|
376
|
+
if (verdict === "restart") {
|
|
377
|
+
// Changed or foreign parts: drop this upload. If it completed meanwhile, the next start must replace it.
|
|
378
|
+
try {
|
|
379
|
+
await abortUpload(config, uploadId, outer);
|
|
380
|
+
}
|
|
381
|
+
catch (error) {
|
|
382
|
+
if (uploadErrorCode(error) !== "upload_completed")
|
|
383
|
+
throw error;
|
|
384
|
+
if (replaced)
|
|
385
|
+
throw new UploadFailure("file_changed", "the file differs from its completed upload and a replace did not take; stopped", { cause: error });
|
|
386
|
+
replace = true;
|
|
387
|
+
}
|
|
388
|
+
continue;
|
|
389
|
+
}
|
|
390
|
+
// An earlier run sent every part and asked to complete (still running, or its answer was lost): complete
|
|
391
|
+
// again, never abort. The server answers with the outcome of that Complete.
|
|
392
|
+
reused = verdict === "completing" ? Array.from({ length: geometry.partCount }, (_, i) => i + 1) : verdict;
|
|
393
|
+
if (reused.length)
|
|
394
|
+
trust = recheck ? "rehash" : typeof start.mtime_ms === "number" ? "fingerprint+mtime" : "fingerprint";
|
|
395
|
+
}
|
|
396
|
+
const have = new Set(reused);
|
|
397
|
+
missing = [];
|
|
398
|
+
for (let part = 1; part <= geometry.partCount; part++)
|
|
399
|
+
if (!have.has(part))
|
|
400
|
+
missing.push(part);
|
|
401
|
+
await sendParts(config, uploadId, options, geometry, missing, reused, concurrency, outer);
|
|
402
|
+
const after = await stat(options.path);
|
|
403
|
+
if (after.size !== before.size || after.mtimeMs !== before.mtimeMs) {
|
|
404
|
+
await abortUpload(config, uploadId, outer).catch(() => { });
|
|
405
|
+
throw new UploadFailure("file_changed", "the file changed while it was being uploaded; run the command again");
|
|
406
|
+
}
|
|
407
|
+
done = await complete(config, uploadId, outer, options.retryBaseMs ?? 1000, trust);
|
|
408
|
+
}
|
|
409
|
+
catch (error) {
|
|
410
|
+
// The server dropped the unfinished upload (it expired), or aborted it after a conflicting write
|
|
411
|
+
// raced its completion: send the file again from the start. Once per file, whatever the cause.
|
|
412
|
+
const code = uploadErrorCode(error);
|
|
413
|
+
const cause = code === "complete_conflict" ? "complete_conflict"
|
|
414
|
+
: code === "upload_expired" || code === "upload_not_found" || (error instanceof UploadFailure && error.reason === "expired") ? "expired"
|
|
415
|
+
: undefined;
|
|
416
|
+
if (cause && !restarted) {
|
|
417
|
+
restarted = cause;
|
|
418
|
+
continue;
|
|
419
|
+
}
|
|
420
|
+
// Another file became current while this one was sent; the upload stays open, so replace completes it.
|
|
421
|
+
if (overwrite(error)) {
|
|
422
|
+
replace = true;
|
|
423
|
+
continue;
|
|
424
|
+
}
|
|
425
|
+
throw error;
|
|
426
|
+
}
|
|
427
|
+
return {
|
|
428
|
+
outcome: reused.length ? "resumed" : "sent", relativePath: done.relative_path ?? options.relativePath, sizeBytes: done.size_bytes,
|
|
429
|
+
partsSent: missing.length, partsReused: reused.length,
|
|
430
|
+
...(done.version_id ? { versionId: done.version_id } : {}),
|
|
431
|
+
...(restarted ? { restarted } : {}),
|
|
432
|
+
...(done.resume_trust ? { resumeTrust: done.resume_trust } : {}),
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
throw new UploadFailure("server", "the upload had to restart too often; stopped");
|
|
436
|
+
}
|
|
437
|
+
/**
|
|
438
|
+
* Part numbers already on the server, or "restart" when the upload's layout or a part does not fit.
|
|
439
|
+
* With `recheck`, each part is also read again and its SHA-256 compared with the server's.
|
|
440
|
+
*/
|
|
441
|
+
async function serverParts(config, uploadId, options, g, recheck, signal) {
|
|
442
|
+
const status = await getUpload(config, uploadId, signal);
|
|
443
|
+
if (status.status === "completing")
|
|
444
|
+
return "completing";
|
|
445
|
+
if (status.status !== "open" || status.part_size_bytes !== g.partSize || status.part_count !== g.partCount)
|
|
446
|
+
return "restart";
|
|
447
|
+
const parts = status.parts ?? [];
|
|
448
|
+
const fits = (p) => Number.isInteger(p.part_number) && p.part_number >= 1 &&
|
|
449
|
+
p.part_number <= g.partCount && p.size_bytes === partRange(g, p.part_number).length;
|
|
450
|
+
if (!recheck)
|
|
451
|
+
return parts.every(fits) ? parts.map((p) => p.part_number) : "restart";
|
|
452
|
+
let checked = 0;
|
|
453
|
+
const total = parts.reduce((sum, p) => sum + (p.size_bytes > 0 ? p.size_bytes : 0), 0);
|
|
454
|
+
const report = (n) => { checked += n; options.onProgress?.({ phase: "verify", bytes: checked, total }); };
|
|
455
|
+
const matches = await mapLimit(parts, 4, async (p) => {
|
|
456
|
+
if (!fits(p) || !p.checksum_sha256)
|
|
457
|
+
return false;
|
|
458
|
+
const range = partRange(g, p.part_number);
|
|
459
|
+
return (await hashRange(options.path, range.start, range.end, signal, report)) === p.checksum_sha256;
|
|
460
|
+
});
|
|
461
|
+
if (matches.includes(false))
|
|
462
|
+
return "restart";
|
|
463
|
+
return parts.map((p) => p.part_number);
|
|
464
|
+
}
|
|
465
|
+
async function sendParts(config, uploadId, options, g, missing, reused, concurrency, outer) {
|
|
466
|
+
const internal = new AbortController();
|
|
467
|
+
const signal = AbortSignal.any([outer, internal.signal]);
|
|
468
|
+
const limiter = options.limiter ?? createLimiter(concurrency);
|
|
469
|
+
const agent = new https.Agent({ keepAlive: true, maxSockets: concurrency });
|
|
470
|
+
const plainAgent = new http.Agent({ keepAlive: true, maxSockets: concurrency });
|
|
471
|
+
const retryBase = options.retryBaseMs ?? 1000;
|
|
472
|
+
const maxAttempts = options.maxAttempts ?? 8;
|
|
473
|
+
const idle = options.idleTimeoutMs ?? 120_000;
|
|
474
|
+
const batch = Math.min(MAX_SIGN_BATCH, Math.max(8, concurrency * 4));
|
|
475
|
+
let doneBytes = reused.reduce((sum, part) => sum + partRange(g, part).length, 0);
|
|
476
|
+
let inflight = 0;
|
|
477
|
+
const report = () => options.onProgress?.({ phase: "send", bytes: doneBytes + inflight, total: g.size });
|
|
478
|
+
report();
|
|
479
|
+
const sign = async (items) => {
|
|
480
|
+
const signed = await patiently(() => signUploadParts(config, uploadId, items.map((i) => ({ part_number: i.part, checksum_sha256: i.checksum })), signal), retryBase, signal);
|
|
481
|
+
const byPart = new Map(signed.map((s) => [s.part_number, s]));
|
|
482
|
+
return items.map((i) => {
|
|
483
|
+
const s = byPart.get(i.part);
|
|
484
|
+
if (!s)
|
|
485
|
+
throw new UploadFailure("server", `the server did not sign part ${i.part}`);
|
|
486
|
+
return { part: i.part, checksum: i.checksum, signed: s };
|
|
487
|
+
});
|
|
488
|
+
};
|
|
489
|
+
const hashPart = (part) => {
|
|
490
|
+
const r = partRange(g, part);
|
|
491
|
+
return hashRange(options.path, r.start, r.end, signal);
|
|
492
|
+
};
|
|
493
|
+
// Hash and sign ahead in batches, so URLs are fresh and sign calls stay few.
|
|
494
|
+
const queue = [...missing];
|
|
495
|
+
const ready = [];
|
|
496
|
+
let preparing = null;
|
|
497
|
+
let failure;
|
|
498
|
+
const refill = () => {
|
|
499
|
+
if (!preparing && queue.length && failure === undefined) {
|
|
500
|
+
const take = queue.splice(0, batch);
|
|
501
|
+
preparing = mapLimit(take, Math.min(concurrency, 4), async (part) => ({ part, checksum: await hashPart(part) }))
|
|
502
|
+
.then(sign)
|
|
503
|
+
.then((prepared) => { ready.push(...prepared); })
|
|
504
|
+
.catch((error) => { failure ??= error; })
|
|
505
|
+
.finally(() => { preparing = null; });
|
|
506
|
+
}
|
|
507
|
+
return preparing ?? Promise.resolve();
|
|
508
|
+
};
|
|
509
|
+
const next = async () => {
|
|
510
|
+
for (;;) {
|
|
511
|
+
if (failure !== undefined)
|
|
512
|
+
throw failure;
|
|
513
|
+
const item = ready.shift();
|
|
514
|
+
if (item) {
|
|
515
|
+
if (ready.length < batch / 2)
|
|
516
|
+
void refill();
|
|
517
|
+
return item;
|
|
518
|
+
}
|
|
519
|
+
if (!queue.length && !preparing)
|
|
520
|
+
return undefined;
|
|
521
|
+
await refill();
|
|
522
|
+
}
|
|
523
|
+
};
|
|
524
|
+
const sendOne = async (item) => {
|
|
525
|
+
const range = partRange(g, item.part);
|
|
526
|
+
let resigns = 0;
|
|
527
|
+
let rehashed = false;
|
|
528
|
+
for (let attempt = 0;; attempt++) {
|
|
529
|
+
signal.throwIfAborted();
|
|
530
|
+
if (Date.parse(item.signed.expires_at) - Date.now() < RESIGN_MARGIN_MS) {
|
|
531
|
+
item = (await sign([{ part: item.part, checksum: item.checksum }]))[0];
|
|
532
|
+
}
|
|
533
|
+
let sent = 0;
|
|
534
|
+
try {
|
|
535
|
+
const agentFor = item.signed.url.startsWith("https:") ? agent : plainAgent;
|
|
536
|
+
await limiter.run(() => putPart(item.signed, options.path, range, agentFor, signal, idle, (n) => {
|
|
537
|
+
sent += n;
|
|
538
|
+
inflight += n;
|
|
539
|
+
report();
|
|
540
|
+
}));
|
|
541
|
+
inflight -= sent;
|
|
542
|
+
doneBytes += range.length;
|
|
543
|
+
report();
|
|
544
|
+
return;
|
|
545
|
+
}
|
|
546
|
+
catch (error) {
|
|
547
|
+
inflight -= sent;
|
|
548
|
+
report();
|
|
549
|
+
signal.throwIfAborted();
|
|
550
|
+
if (error instanceof UploadFailure)
|
|
551
|
+
throw error;
|
|
552
|
+
if (error instanceof PartPutError) {
|
|
553
|
+
if (error.status === 403 && resigns < 2) {
|
|
554
|
+
resigns++;
|
|
555
|
+
item = (await sign([{ part: item.part, checksum: item.checksum }]))[0];
|
|
556
|
+
continue;
|
|
557
|
+
}
|
|
558
|
+
// The server aborted the upload (expired) after this URL was signed.
|
|
559
|
+
if (error.s3Code === "NoSuchUpload") {
|
|
560
|
+
throw new UploadFailure("expired", "the unfinished upload expired on the server", { cause: error });
|
|
561
|
+
}
|
|
562
|
+
if (error.s3Code && DIGEST_S3.has(error.s3Code)) {
|
|
563
|
+
if (rehashed)
|
|
564
|
+
throw new UploadFailure("file_changed", "the file changed while it was being uploaded; run the command again", { cause: error });
|
|
565
|
+
rehashed = true;
|
|
566
|
+
item = (await sign([{ part: item.part, checksum: await hashPart(item.part) }]))[0];
|
|
567
|
+
continue;
|
|
568
|
+
}
|
|
569
|
+
// A 200 without an ETag (rclone #9822) is retried like a server error.
|
|
570
|
+
const retryable = error.status >= 500 || error.status === 408 || error.status === 429 || error.status === 200 ||
|
|
571
|
+
(error.s3Code !== undefined && RETRYABLE_S3.has(error.s3Code));
|
|
572
|
+
if (!retryable || attempt + 1 >= maxAttempts) {
|
|
573
|
+
throw new UploadFailure("part_failed", `part ${item.part} failed: ${error.message}`, { cause: error });
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
else if (attempt + 1 >= maxAttempts) {
|
|
577
|
+
throw new UploadFailure("part_failed", `part ${item.part} failed after ${maxAttempts} attempts: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
578
|
+
}
|
|
579
|
+
await backoff(attempt, retryBase, signal);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
};
|
|
583
|
+
const worker = async () => {
|
|
584
|
+
for (let item = await next(); item; item = await next())
|
|
585
|
+
await sendOne(item);
|
|
586
|
+
};
|
|
587
|
+
try {
|
|
588
|
+
const results = await Promise.allSettled(Array.from({ length: concurrency }, async () => {
|
|
589
|
+
try {
|
|
590
|
+
await worker();
|
|
591
|
+
}
|
|
592
|
+
catch (error) {
|
|
593
|
+
failure ??= error;
|
|
594
|
+
internal.abort(error);
|
|
595
|
+
throw error;
|
|
596
|
+
}
|
|
597
|
+
}));
|
|
598
|
+
outer.throwIfAborted();
|
|
599
|
+
const rejected = results.find((r) => r.status === "rejected");
|
|
600
|
+
if (rejected)
|
|
601
|
+
throw failure ?? rejected.reason;
|
|
602
|
+
}
|
|
603
|
+
finally {
|
|
604
|
+
agent.destroy();
|
|
605
|
+
plainAgent.destroy();
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
/** C4, re-read and resent on an unknown outcome: the server answers a repeat with its stored outcome. */
|
|
609
|
+
async function complete(config, uploadId, signal, retryBaseMs, trust) {
|
|
610
|
+
for (let attempt = 0;; attempt++) {
|
|
611
|
+
try {
|
|
612
|
+
return await patiently(() => completeUpload(config, uploadId, signal, trust), retryBaseMs, signal);
|
|
613
|
+
}
|
|
614
|
+
catch (error) {
|
|
615
|
+
signal.throwIfAborted();
|
|
616
|
+
if (!(error instanceof UnknownOutcomeError) || attempt >= 2)
|
|
617
|
+
throw error;
|
|
618
|
+
await backoff(attempt, retryBaseMs, signal);
|
|
619
|
+
const status = await getUpload(config, uploadId, signal);
|
|
620
|
+
if (status.status === "aborted")
|
|
621
|
+
throw new UploadFailure("expired", "the upload was aborted on the server before it completed");
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/** Projects & datasets REST API. */
|
|
2
|
+
import type { AppConfig, Project } from "./types.js";
|
|
3
|
+
interface DatasetFilesResponse {
|
|
4
|
+
files: Array<{
|
|
5
|
+
name: string;
|
|
6
|
+
size_bytes: number;
|
|
7
|
+
url: string;
|
|
8
|
+
}>;
|
|
9
|
+
}
|
|
10
|
+
/** List all projects for the current user. Rejects on any request failure; an empty list means no projects. */
|
|
11
|
+
export declare function listProjects(config: AppConfig): Promise<Project[]>;
|
|
12
|
+
/** Upload a file to a dataset. */
|
|
13
|
+
export declare function pushFile(config: AppConfig, datasetId: string, filePath: string, fileContent: ArrayBuffer): Promise<string>;
|
|
14
|
+
/** List files in a dataset (for pull). Rejects on any request failure. */
|
|
15
|
+
export declare function listDatasetFiles(config: AppConfig, datasetId: string): Promise<DatasetFilesResponse["files"]>;
|
|
16
|
+
/** Stream one file of an org project's shared data (GET /org/projects/{id}/data/{filename}). */
|
|
17
|
+
export declare function downloadProjectDataFile(config: AppConfig, projectId: string, filename: string): Promise<ReadableStream<Uint8Array>>;
|
|
18
|
+
/** Project files above this size download through the link route, so a long transfer never holds an API task. */
|
|
19
|
+
export declare const PROJECT_DATA_LINK_BYTES: number;
|
|
20
|
+
/**
|
|
21
|
+
* Stream one large project file straight from storage: the link route returns a presigned GET
|
|
22
|
+
* (`{url, expires_at, size_bytes}`), fetched with no Omics credentials and no redirects. A link
|
|
23
|
+
* that is not HTTPS is refused before anything is requested from it.
|
|
24
|
+
*/
|
|
25
|
+
export declare function downloadProjectDataLink(config: AppConfig, projectId: string, filename: string): Promise<ReadableStream<Uint8Array>>;
|
|
26
|
+
/** Read one project (owner, organisation admin or assigned member). A refusal or a missing project is said in words. */
|
|
27
|
+
export declare function getProject(config: AppConfig, projectId: string): Promise<Project>;
|
|
28
|
+
/**
|
|
29
|
+
* Create a project, as the web app does: the login's host decides where it lives. On an organisation's host
|
|
30
|
+
* (login --tenant) it belongs to that organisation and you own it; on the platform host it is personal.
|
|
31
|
+
*/
|
|
32
|
+
export declare function createProject(config: AppConfig, project: {
|
|
33
|
+
name: string;
|
|
34
|
+
description?: string;
|
|
35
|
+
}): Promise<Project>;
|
|
36
|
+
/**
|
|
37
|
+
* An upload the project itself refused, which holds for every file of the run: 404 `project_not_found` (no such
|
|
38
|
+
* project in this login's organisation, or a personal one) or a 403 without a code (the server's one access refusal;
|
|
39
|
+
* it checks again on sign and complete). The words to show, or undefined.
|
|
40
|
+
*/
|
|
41
|
+
export declare function uploadProjectRefusal(error: unknown, projectId: string): string | undefined;
|
|
42
|
+
export {};
|