filecafe 0.3.3 → 0.3.4
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/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { a as updateCachePath, d as normalizeBaseUrl, f as readConfig, l as configPath, m as writeConfig, n as fetchLatestVersion, o as updateUpdateCache, p as resolveSettings, r as readUpdateCache, s as VERSION, t as CHECK_INTERVAL_MS, u as deleteConfig } from "./update-cache-
|
|
2
|
+
import { a as updateCachePath, d as normalizeBaseUrl, f as readConfig, l as configPath, m as writeConfig, n as fetchLatestVersion, o as updateUpdateCache, p as resolveSettings, r as readUpdateCache, s as VERSION, t as CHECK_INTERVAL_MS, u as deleteConfig } from "./update-cache-BOFin4Gp.js";
|
|
3
3
|
import { Command } from "commander";
|
|
4
4
|
import { homedir, hostname, tmpdir } from "node:os";
|
|
5
5
|
import { realpath, stat } from "node:fs/promises";
|
|
@@ -607,18 +607,22 @@ function guessMimeType(filename) {
|
|
|
607
607
|
/** An error while transferring bytes to the upload server. */
|
|
608
608
|
var TransferError = class extends Error {
|
|
609
609
|
status;
|
|
610
|
-
|
|
611
|
-
restartUpload;
|
|
612
|
-
constructor(message, status, restartUpload = false) {
|
|
610
|
+
constructor(message, status) {
|
|
613
611
|
super(message);
|
|
614
612
|
this.name = "TransferError";
|
|
615
613
|
this.status = status;
|
|
616
|
-
this.restartUpload = restartUpload;
|
|
617
614
|
}
|
|
618
615
|
};
|
|
619
616
|
const DEFAULT_CONCURRENCY = 4;
|
|
620
617
|
const DEFAULT_PART_RETRIES = 3;
|
|
621
618
|
const DEFAULT_PART_TIMEOUT_MS = 9e5;
|
|
619
|
+
/**
|
|
620
|
+
* Multipart uploads use the start response's URLs for the first batch of parts and fetch each
|
|
621
|
+
* later batch just before uploading it, so a long upload never sends a part to an expired URL.
|
|
622
|
+
*/
|
|
623
|
+
const PART_URL_BATCH_SIZE = 50;
|
|
624
|
+
/** Fetch a batch's URLs again once they are this old. file.cafe signs them for two hours. */
|
|
625
|
+
const PART_URL_MAX_AGE_MS = 36e5;
|
|
622
626
|
function isRecord(value) {
|
|
623
627
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
624
628
|
}
|
|
@@ -660,19 +664,31 @@ function describeFetchError(error) {
|
|
|
660
664
|
}
|
|
661
665
|
return String(error);
|
|
662
666
|
}
|
|
663
|
-
/** PUT one byte range, retrying network errors and 5xx responses.
|
|
667
|
+
/** PUT one byte range, retrying network errors and 5xx responses. */
|
|
664
668
|
async function putPart(target, body, options) {
|
|
665
669
|
for (let attempt = 0;; attempt++) {
|
|
666
670
|
options.signal.throwIfAborted();
|
|
671
|
+
let sent = 0;
|
|
672
|
+
const counted = body.stream().pipeThrough(new TransformStream({ transform(chunk, controller) {
|
|
673
|
+
sent += chunk.byteLength;
|
|
674
|
+
options.onBytes?.(chunk.byteLength);
|
|
675
|
+
controller.enqueue(chunk);
|
|
676
|
+
} }));
|
|
677
|
+
const failed = () => options.onBytes?.(-sent);
|
|
667
678
|
let response;
|
|
668
679
|
try {
|
|
669
680
|
response = await options.fetch(target.url, {
|
|
670
681
|
method: "PUT",
|
|
671
|
-
headers:
|
|
672
|
-
|
|
682
|
+
headers: {
|
|
683
|
+
...target.headers,
|
|
684
|
+
"Content-Length": String(body.size)
|
|
685
|
+
},
|
|
686
|
+
body: counted,
|
|
687
|
+
duplex: "half",
|
|
673
688
|
signal: AbortSignal.any([options.signal, AbortSignal.timeout(options.timeoutMs)])
|
|
674
689
|
});
|
|
675
690
|
} catch (error) {
|
|
691
|
+
failed();
|
|
676
692
|
if (options.signal.aborted) throw options.signal.reason;
|
|
677
693
|
if (attempt < options.maxRetries) {
|
|
678
694
|
await options.sleep(1e3 * 2 ** attempt);
|
|
@@ -680,14 +696,12 @@ async function putPart(target, body, options) {
|
|
|
680
696
|
}
|
|
681
697
|
throw new TransferError(`Upload of ${options.label} failed: network error (${describeFetchError(error)}).`, null);
|
|
682
698
|
}
|
|
683
|
-
if (response.ok) {
|
|
699
|
+
if (response.ok || response.status === 412 && attempt > 0) {
|
|
684
700
|
await response.body?.cancel();
|
|
685
|
-
|
|
686
|
-
if (!receipt && options.requireReceipt) throw new TransferError(`Upload of ${options.label} succeeded but the server did not return an upload receipt.`, response.status);
|
|
687
|
-
return receipt;
|
|
701
|
+
return;
|
|
688
702
|
}
|
|
703
|
+
failed();
|
|
689
704
|
const detail = (await response.text().catch(() => "")).trim().slice(0, 500);
|
|
690
|
-
if (response.status === 412) throw new TransferError(`Upload of ${options.label} failed: the file already exists and its receipt was lost.`, 412, true);
|
|
691
705
|
if (response.status >= 500 && attempt < options.maxRetries) {
|
|
692
706
|
await options.sleep(1e3 * 2 ** attempt);
|
|
693
707
|
continue;
|
|
@@ -716,8 +730,14 @@ async function runPool(count, concurrency, controller, worker) {
|
|
|
716
730
|
await Promise.all(Array.from({ length: Math.max(1, Math.min(concurrency, count)) }, runner));
|
|
717
731
|
if (firstError !== null) throw firstError;
|
|
718
732
|
}
|
|
719
|
-
|
|
733
|
+
/**
|
|
734
|
+
* Upload one file: start the upload, PUT each part (in parallel for multipart), then complete
|
|
735
|
+
* it. file.cafe checks the stored file when completing, so nothing else needs to be sent back.
|
|
736
|
+
*/
|
|
737
|
+
async function uploadFile(options) {
|
|
720
738
|
const { client, size } = options;
|
|
739
|
+
const blob = await openAsBlob(options.path);
|
|
740
|
+
if (blob.size !== size) throw new Error(`${options.path} changed size while uploading. Please retry.`);
|
|
721
741
|
const started = await client.request("POST", "/api/v1/uploads", {
|
|
722
742
|
filename: options.filename,
|
|
723
743
|
size,
|
|
@@ -725,48 +745,73 @@ async function transferOnce(options, blob) {
|
|
|
725
745
|
...options.collectionId ? { collection_id: options.collectionId } : {}
|
|
726
746
|
});
|
|
727
747
|
const { targets, partSize } = planTransfer(started, size);
|
|
728
|
-
const
|
|
729
|
-
const receipts = new Array(targets.length).fill(null);
|
|
748
|
+
const partUrls = createPartUrls(options, started, targets);
|
|
730
749
|
const controller = new AbortController();
|
|
731
750
|
let uploadedBytes = 0;
|
|
732
751
|
options.onProgress?.(0, size);
|
|
733
752
|
await runPool(targets.length, options.concurrency ?? DEFAULT_CONCURRENCY, controller, async (index) => {
|
|
734
753
|
const start = index * partSize;
|
|
735
754
|
const end = Math.min(start + partSize, size);
|
|
736
|
-
|
|
737
|
-
receipts[index] = await putPart(target, blob.slice(start, end), {
|
|
755
|
+
await putPart(await partUrls.target(index), blob.slice(start, end), {
|
|
738
756
|
fetch: options.fetch,
|
|
739
757
|
sleep: options.sleep,
|
|
740
758
|
maxRetries: options.maxPartRetries ?? DEFAULT_PART_RETRIES,
|
|
741
759
|
timeoutMs: options.partTimeoutMs ?? DEFAULT_PART_TIMEOUT_MS,
|
|
742
760
|
signal: controller.signal,
|
|
743
|
-
|
|
744
|
-
|
|
761
|
+
label: targets.length > 1 ? `part ${index + 1}/${targets.length}` : options.filename,
|
|
762
|
+
onBytes: (bytes) => {
|
|
763
|
+
uploadedBytes += bytes;
|
|
764
|
+
options.onProgress?.(uploadedBytes, size);
|
|
765
|
+
}
|
|
745
766
|
});
|
|
746
|
-
uploadedBytes += end - start;
|
|
747
|
-
options.onProgress?.(uploadedBytes, size);
|
|
748
767
|
});
|
|
749
|
-
return client.request("PUT", `/api/v1/uploads/${encodeURIComponent(started.id)}`, {
|
|
750
|
-
token: started.token,
|
|
751
|
-
receipts: receipts.filter((receipt) => receipt !== null)
|
|
752
|
-
}, { idempotent: true });
|
|
768
|
+
return client.request("PUT", `/api/v1/uploads/${encodeURIComponent(started.id)}`, { token: partUrls.token() }, { idempotent: true });
|
|
753
769
|
}
|
|
754
770
|
/**
|
|
755
|
-
*
|
|
756
|
-
*
|
|
771
|
+
* The URL for each part of an upload, in batches of PART_URL_BATCH_SIZE. The first batch comes
|
|
772
|
+
* from the start response; later ones, and any batch older than PART_URL_MAX_AGE_MS, are fetched
|
|
773
|
+
* when a part in them is about to be uploaded. Each fetch also renews the upload ticket, so the
|
|
774
|
+
* latest token is the one to complete with.
|
|
757
775
|
*/
|
|
758
|
-
|
|
759
|
-
const
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
}
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
}
|
|
768
|
-
|
|
769
|
-
|
|
776
|
+
function createPartUrls(options, started, targets) {
|
|
777
|
+
const now = options.now ?? Date.now;
|
|
778
|
+
const batches = /* @__PURE__ */ new Map([[0, {
|
|
779
|
+
fetchedAt: now(),
|
|
780
|
+
targets: Promise.resolve(targets.slice(0, PART_URL_BATCH_SIZE))
|
|
781
|
+
}]]);
|
|
782
|
+
let token = started.token;
|
|
783
|
+
const fetchBatch = async (batch) => {
|
|
784
|
+
const first = batch * PART_URL_BATCH_SIZE + 1;
|
|
785
|
+
const partNumbers = Array.from({ length: Math.min(PART_URL_BATCH_SIZE, targets.length - first + 1) }, (_, i) => first + i);
|
|
786
|
+
const response = await options.client.request("POST", `/api/v1/uploads/${encodeURIComponent(started.id)}/parts`, {
|
|
787
|
+
token,
|
|
788
|
+
part_numbers: partNumbers
|
|
789
|
+
}, { idempotent: true });
|
|
790
|
+
const parts = isRecord(response) && Array.isArray(response.parts) ? response.parts : [];
|
|
791
|
+
const fresh = partNumbers.map((partNumber) => parts.find((part) => isRecord(part) && part.part_number === partNumber));
|
|
792
|
+
if (!isRecord(response) || typeof response.token !== "string" || !fresh.every(isSignedTarget)) throw new ApiError("Unexpected response when fetching upload URLs.", null);
|
|
793
|
+
token = response.token;
|
|
794
|
+
return fresh.map((part) => ({
|
|
795
|
+
url: part.url,
|
|
796
|
+
headers: part.headers
|
|
797
|
+
}));
|
|
798
|
+
};
|
|
799
|
+
return {
|
|
800
|
+
async target(index) {
|
|
801
|
+
if (!("parts" in started)) return targets[index];
|
|
802
|
+
const batch = Math.floor(index / PART_URL_BATCH_SIZE);
|
|
803
|
+
let entry = batches.get(batch);
|
|
804
|
+
if (!entry || now() - entry.fetchedAt > PART_URL_MAX_AGE_MS) {
|
|
805
|
+
entry = {
|
|
806
|
+
fetchedAt: now(),
|
|
807
|
+
targets: fetchBatch(batch)
|
|
808
|
+
};
|
|
809
|
+
batches.set(batch, entry);
|
|
810
|
+
}
|
|
811
|
+
return (await entry.targets)[index % PART_URL_BATCH_SIZE];
|
|
812
|
+
},
|
|
813
|
+
token: () => token
|
|
814
|
+
};
|
|
770
815
|
}
|
|
771
816
|
// src/commands/upload.ts
|
|
772
817
|
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
@@ -877,6 +922,7 @@ async function uploadCommand(files, options, globals, context) {
|
|
|
877
922
|
else {
|
|
878
923
|
const filename = uploadFilename(file);
|
|
879
924
|
progress.update(`Uploading ${err.bold(filename)} (${formatBytes(size)})...`);
|
|
925
|
+
let lastDrawn = -Infinity;
|
|
880
926
|
try {
|
|
881
927
|
const completed = await uploadFile({
|
|
882
928
|
client,
|
|
@@ -888,8 +934,10 @@ async function uploadCommand(files, options, globals, context) {
|
|
|
888
934
|
mimeType: guessMimeType(filename),
|
|
889
935
|
collectionId: options.collection,
|
|
890
936
|
concurrency: options.concurrency,
|
|
891
|
-
|
|
937
|
+
now: context.now,
|
|
892
938
|
onProgress: (uploaded, total) => {
|
|
939
|
+
if (uploaded < total && context.now() - lastDrawn < 100) return;
|
|
940
|
+
lastDrawn = context.now();
|
|
893
941
|
if (uploaded > 0 && total > 0) {
|
|
894
942
|
const percent = Math.floor(uploaded / total * 100);
|
|
895
943
|
progress.update(`Uploading ${err.bold(filename)} ${err.cyan(`${percent}%`)} (${formatBytes(uploaded)} / ${formatBytes(total)})`);
|
|
@@ -108,7 +108,7 @@ async function resolveSettings(environment, urlOption) {
|
|
|
108
108
|
};
|
|
109
109
|
}
|
|
110
110
|
// src/version.ts
|
|
111
|
-
const VERSION = "0.3.
|
|
111
|
+
const VERSION = "0.3.4";
|
|
112
112
|
// src/update-cache.ts
|
|
113
113
|
const REGISTRY_URL = "https://registry.npmjs.org/filecafe/latest";
|
|
114
114
|
/** Ask npm at most once a day. */
|
package/dist/update-worker.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as refreshUpdateCache, s as VERSION } from "./update-cache-
|
|
1
|
+
import { i as refreshUpdateCache, s as VERSION } from "./update-cache-BOFin4Gp.js";
|
|
2
2
|
// src/update-worker.ts
|
|
3
3
|
/**
|
|
4
4
|
* Spawned detached by the CLI to refresh the update cache, so no command ever waits on npm.
|