@ardrive/turbo-sdk 1.42.0-alpha.13 → 1.42.0-alpha.14
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/lib/cjs/common/folderIndex.js +394 -0
- package/lib/cjs/common/index.js +1 -0
- package/lib/cjs/common/upload.js +267 -17
- package/lib/cjs/node/folderIndex.js +132 -0
- package/lib/cjs/node/index.js +1 -0
- package/lib/cjs/node/upload.js +7 -0
- package/lib/cjs/utils/folderIndex.js +88 -0
- package/lib/esm/common/folderIndex.js +389 -0
- package/lib/esm/common/index.js +1 -0
- package/lib/esm/common/upload.js +268 -18
- package/lib/esm/node/folderIndex.js +129 -0
- package/lib/esm/node/index.js +1 -0
- package/lib/esm/node/upload.js +7 -0
- package/lib/esm/utils/folderIndex.js +81 -0
- package/lib/types/common/folderIndex.d.ts +54 -0
- package/lib/types/common/folderIndex.d.ts.map +1 -0
- package/lib/types/common/index.d.ts +1 -0
- package/lib/types/common/index.d.ts.map +1 -1
- package/lib/types/common/upload.d.ts +41 -0
- package/lib/types/common/upload.d.ts.map +1 -1
- package/lib/types/node/folderIndex.d.ts +28 -0
- package/lib/types/node/folderIndex.d.ts.map +1 -0
- package/lib/types/node/index.d.ts +1 -0
- package/lib/types/node/index.d.ts.map +1 -1
- package/lib/types/node/upload.d.ts +1 -0
- package/lib/types/node/upload.d.ts.map +1 -1
- package/lib/types/types.d.ts +163 -0
- package/lib/types/types.d.ts.map +1 -1
- package/lib/types/utils/folderIndex.d.ts +47 -0
- package/lib/types/utils/folderIndex.d.ts.map +1 -0
- package/package.json +1 -1
package/lib/cjs/common/upload.js
CHANGED
|
@@ -22,6 +22,7 @@ const types_js_1 = require("../types.js");
|
|
|
22
22
|
const common_js_1 = require("../utils/common.js");
|
|
23
23
|
const errors_js_1 = require("../utils/errors.js");
|
|
24
24
|
const errors_js_2 = require("../utils/errors.js");
|
|
25
|
+
const folderIndex_js_1 = require("../utils/folderIndex.js");
|
|
25
26
|
const chunked_js_1 = require("./chunked.js");
|
|
26
27
|
const events_js_1 = require("./events.js");
|
|
27
28
|
const http_js_1 = require("./http.js");
|
|
@@ -370,6 +371,193 @@ class TurboAuthenticatedBaseUploadService extends TurboUnauthenticatedUploadServ
|
|
|
370
371
|
};
|
|
371
372
|
return manifest;
|
|
372
373
|
}
|
|
374
|
+
/**
|
|
375
|
+
* The sha-256 of a file's bytes, as lowercase hex. The key of a
|
|
376
|
+
* {@link TurboFolderUploadIndex}.
|
|
377
|
+
*
|
|
378
|
+
* This default consumes the file's stream and digests it with the platform
|
|
379
|
+
* WebCrypto implementation, which serves the browser. NodeJS overrides it
|
|
380
|
+
* with a streaming digest so a large file is never held in memory.
|
|
381
|
+
*/
|
|
382
|
+
async computeContentHash(file) {
|
|
383
|
+
const stream = this.getFileStreamForFile(file);
|
|
384
|
+
const chunks = [];
|
|
385
|
+
if ('getReader' in stream) {
|
|
386
|
+
const reader = stream.getReader();
|
|
387
|
+
for (;;) {
|
|
388
|
+
const { done, value } = await reader.read();
|
|
389
|
+
if (done)
|
|
390
|
+
break;
|
|
391
|
+
chunks.push(value);
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
else {
|
|
395
|
+
for await (const chunk of stream) {
|
|
396
|
+
chunks.push(new Uint8Array(chunk));
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
const digest = await crypto.subtle.digest('SHA-256', Buffer.concat(chunks));
|
|
400
|
+
return Buffer.from(digest).toString('hex');
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* The exact tag set a folder upload writes for one file. Shared by the
|
|
404
|
+
* planner and the uploader, so that the tags a folder index key is computed
|
|
405
|
+
* from are, without question, the tags the data item ends up carrying.
|
|
406
|
+
*/
|
|
407
|
+
folderFileTags({ file, dataItemOpts, contentHash, hashTagName = folderIndex_js_1.contentHashTagName, }) {
|
|
408
|
+
return [
|
|
409
|
+
...(dataItemOpts?.tags?.filter((tag) => tag.name !== 'Content-Type' &&
|
|
410
|
+
// Only stripped when this upload is going to write its own. Without a
|
|
411
|
+
// folder index, a caller's File-SHA256 tag is theirs to keep.
|
|
412
|
+
(contentHash === undefined || tag.name !== hashTagName)) ?? []),
|
|
413
|
+
{
|
|
414
|
+
name: 'Content-Type',
|
|
415
|
+
value: this.getContentType(file, dataItemOpts),
|
|
416
|
+
},
|
|
417
|
+
...(contentHash !== undefined
|
|
418
|
+
? [{ name: hashTagName, value: contentHash }]
|
|
419
|
+
: []),
|
|
420
|
+
];
|
|
421
|
+
}
|
|
422
|
+
/**
|
|
423
|
+
* A folder index is a cache, so a layer that is unreachable must mean a miss
|
|
424
|
+
* and not an aborted deploy. The write side is forgiving for the same reason.
|
|
425
|
+
*/
|
|
426
|
+
async readFolderIndex(folderIndex, keys, signal) {
|
|
427
|
+
const knownIds = new Map();
|
|
428
|
+
const unresolved = [];
|
|
429
|
+
for (const key of keys) {
|
|
430
|
+
let id;
|
|
431
|
+
try {
|
|
432
|
+
id = await folderIndex.get(key);
|
|
433
|
+
}
|
|
434
|
+
catch (error) {
|
|
435
|
+
this.logger.error('Failed to read from folder index', error);
|
|
436
|
+
}
|
|
437
|
+
if (id !== undefined && (0, common_js_1.isValidArweaveBase64URL)(id)) {
|
|
438
|
+
knownIds.set(key, id);
|
|
439
|
+
}
|
|
440
|
+
else {
|
|
441
|
+
unresolved.push(key);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
if (unresolved.length > 0 && folderIndex.resolve !== undefined) {
|
|
445
|
+
try {
|
|
446
|
+
const resolved = await folderIndex.resolve(unresolved, { signal });
|
|
447
|
+
for (const [key, id] of Object.entries(resolved)) {
|
|
448
|
+
if ((0, common_js_1.isValidArweaveBase64URL)(id)) {
|
|
449
|
+
knownIds.set(key, id);
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
catch (error) {
|
|
454
|
+
this.logger.error('Failed to resolve from folder index', error);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
return knownIds;
|
|
458
|
+
}
|
|
459
|
+
/**
|
|
460
|
+
* Hashes every file and derives its folder index key, then works out which of
|
|
461
|
+
* those keys already have a data item id -- from the index, or from an
|
|
462
|
+
* identical file earlier in this same folder.
|
|
463
|
+
*/
|
|
464
|
+
async planFolderIndex({ files, folderIndex, dataItemOpts, limit, signal, }) {
|
|
465
|
+
const contentHashes = new Map();
|
|
466
|
+
const itemKeys = new Map();
|
|
467
|
+
await Promise.all(files.map((file) => limit(async () => {
|
|
468
|
+
const contentHash = await this.computeContentHash(file);
|
|
469
|
+
contentHashes.set(file, contentHash);
|
|
470
|
+
itemKeys.set(file, await (0, folderIndex_js_1.folderIndexKey)({
|
|
471
|
+
contentHash,
|
|
472
|
+
tags: this.folderFileTags({
|
|
473
|
+
file,
|
|
474
|
+
dataItemOpts,
|
|
475
|
+
contentHash,
|
|
476
|
+
hashTagName: folderIndex.hashTagName,
|
|
477
|
+
}),
|
|
478
|
+
}));
|
|
479
|
+
})));
|
|
480
|
+
const knownIds = await this.readFolderIndex(folderIndex, [...new Set(itemKeys.values())], signal);
|
|
481
|
+
// Two files that would produce the same data item share a single upload, so
|
|
482
|
+
// the plan deduplicates within the folder as well as against the index.
|
|
483
|
+
const claimed = new Set();
|
|
484
|
+
const filesToUpload = files.filter((file) => {
|
|
485
|
+
const key = itemKeys.get(file);
|
|
486
|
+
if (knownIds.has(key) || claimed.has(key)) {
|
|
487
|
+
return false;
|
|
488
|
+
}
|
|
489
|
+
claimed.add(key);
|
|
490
|
+
return true;
|
|
491
|
+
});
|
|
492
|
+
this.logger.debug('Planned folder index', {
|
|
493
|
+
folderIndex: folderIndex.name,
|
|
494
|
+
totalFiles: files.length,
|
|
495
|
+
filesToUpload: filesToUpload.length,
|
|
496
|
+
});
|
|
497
|
+
await this.warnOnStaleTagMisses({ folderIndex, itemKeys, knownIds });
|
|
498
|
+
return { contentHashes, itemKeys, knownIds, filesToUpload };
|
|
499
|
+
}
|
|
500
|
+
/**
|
|
501
|
+
* A key covers the tags on a file as well as its bytes, so a tag in
|
|
502
|
+
* `dataItemOpts` that changes between deploys re-uploads the whole folder at
|
|
503
|
+
* full price. That is the right answer -- a reused data item is never one
|
|
504
|
+
* this call would not have made -- but on its own it is a silent cost cliff:
|
|
505
|
+
* a successful deploy, a full bill, and nothing saying why.
|
|
506
|
+
*
|
|
507
|
+
* The signature of that mistake is exact, and it is already in hand. A key is
|
|
508
|
+
* `<bytes>.<tags>`, so a file whose *bytes half* the index knows under some
|
|
509
|
+
* other tags half is a file whose content is already paid for and whose tags
|
|
510
|
+
* moved. Nothing else produces that: a folder the index has never seen has
|
|
511
|
+
* unknown bytes, and a layer that could not be reached reports nothing known.
|
|
512
|
+
* It also catches one file in a hundred, not just all of them.
|
|
513
|
+
*/
|
|
514
|
+
async warnOnStaleTagMisses({ folderIndex, itemKeys, knownIds, }) {
|
|
515
|
+
if (folderIndex.knownContentHashes === undefined) {
|
|
516
|
+
return;
|
|
517
|
+
}
|
|
518
|
+
// Counted in files, not in keys: the message is about a bill, and the bill
|
|
519
|
+
// is per file. Two files that share a key are one upload but the reader is
|
|
520
|
+
// looking for their own file count.
|
|
521
|
+
const filesPerKey = new Map();
|
|
522
|
+
for (const key of itemKeys.values()) {
|
|
523
|
+
filesPerKey.set(key, (filesPerKey.get(key) ?? 0) + 1);
|
|
524
|
+
}
|
|
525
|
+
const missed = [...filesPerKey.keys()].filter((key) => !knownIds.has(key));
|
|
526
|
+
if (missed.length === 0) {
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
529
|
+
const filesFor = (keys) => keys.reduce((count, key) => count + (filesPerKey.get(key) ?? 0), 0);
|
|
530
|
+
const missedFiles = filesFor(missed);
|
|
531
|
+
const missedByContentHash = new Map();
|
|
532
|
+
for (const key of missed) {
|
|
533
|
+
const contentHash = (0, folderIndex_js_1.contentHashFromFolderIndexKey)(key);
|
|
534
|
+
missedByContentHash.set(contentHash, [
|
|
535
|
+
...(missedByContentHash.get(contentHash) ?? []),
|
|
536
|
+
key,
|
|
537
|
+
]);
|
|
538
|
+
}
|
|
539
|
+
let staleTagged = [];
|
|
540
|
+
try {
|
|
541
|
+
staleTagged =
|
|
542
|
+
(await folderIndex.knownContentHashes([
|
|
543
|
+
...missedByContentHash.keys(),
|
|
544
|
+
])) ?? [];
|
|
545
|
+
}
|
|
546
|
+
catch (error) {
|
|
547
|
+
this.logger.error('Failed to read from folder index', error);
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
const affected = staleTagged.reduce((count, contentHash) => count + filesFor(missedByContentHash.get(contentHash) ?? []), 0);
|
|
551
|
+
if (affected === 0) {
|
|
552
|
+
return;
|
|
553
|
+
}
|
|
554
|
+
this.logger.warn(`${affected} of the ${missedFiles} file(s) this run is about to upload are already on Arweave byte for byte, under a different set of tags. ` +
|
|
555
|
+
'Their content has not changed but their tags have, so they are being paid for again. A folder index key covers the tags ' +
|
|
556
|
+
'on a file as well as its bytes. That is usually a tag in dataItemOpts whose value changes between deploys -- a commit ' +
|
|
557
|
+
'sha, a build number, a timestamp -- in which case move it to manifestDataItemOpts rather than paying for these files ' +
|
|
558
|
+
'again. It can also be a file that kept its content but changed its Content-Type, through a rename or a new extension, ' +
|
|
559
|
+
'which is expected and costs one upload.');
|
|
560
|
+
}
|
|
373
561
|
getContentType(file, dataItemOpts) {
|
|
374
562
|
const userDefinedContentType = dataItemOpts?.tags?.find((tag) => tag.name === 'Content-Type')?.value;
|
|
375
563
|
if (userDefinedContentType !== undefined) {
|
|
@@ -379,7 +567,7 @@ class TurboAuthenticatedBaseUploadService extends TurboUnauthenticatedUploadServ
|
|
|
379
567
|
}
|
|
380
568
|
async uploadFolder(params) {
|
|
381
569
|
this.logger.debug('Uploading folder...', { params });
|
|
382
|
-
const { dataItemOpts, signal, manifestOptions = {}, maxConcurrentUploads = 1, throwOnFailure = true, maxChunkConcurrency, chunkByteCount, chunkingMode, fundingMode = new types_js_1.ExistingBalanceFunding(), maxFinalizeMs, events = {}, } = params;
|
|
570
|
+
const { dataItemOpts, manifestDataItemOpts = dataItemOpts, folderIndex, signal, manifestOptions = {}, maxConcurrentUploads = 1, throwOnFailure = true, maxChunkConcurrency, chunkByteCount, chunkingMode, fundingMode = new types_js_1.ExistingBalanceFunding(), maxFinalizeMs, events = {}, } = params;
|
|
383
571
|
const { disableManifest, indexFile, fallbackFile } = manifestOptions;
|
|
384
572
|
// Create event emitter from events parameter
|
|
385
573
|
const emitter = new events_js_1.TurboEventEmitter(events);
|
|
@@ -388,15 +576,37 @@ class TurboAuthenticatedBaseUploadService extends TurboUnauthenticatedUploadServ
|
|
|
388
576
|
fileResponses: [],
|
|
389
577
|
};
|
|
390
578
|
const errors = [];
|
|
579
|
+
const limit = (0, plimit_lit_1.pLimit)(maxConcurrentUploads);
|
|
391
580
|
// Get files and calculate total bytes upfront for progress tracking
|
|
392
581
|
const files = await this.getFiles(params);
|
|
393
|
-
|
|
582
|
+
// With an index, only the files whose bytes are not already on Arweave are
|
|
583
|
+
// signed, uploaded and paid for. Progress totals cover that subset, since
|
|
584
|
+
// it is all this call actually does.
|
|
585
|
+
let contentHashes = new Map();
|
|
586
|
+
let itemKeys = new Map();
|
|
587
|
+
let knownIds = new Map();
|
|
588
|
+
let filesToUpload = files;
|
|
589
|
+
if (folderIndex !== undefined) {
|
|
590
|
+
({ contentHashes, itemKeys, knownIds, filesToUpload } =
|
|
591
|
+
await this.planFolderIndex({
|
|
592
|
+
files,
|
|
593
|
+
folderIndex,
|
|
594
|
+
dataItemOpts,
|
|
595
|
+
limit,
|
|
596
|
+
signal,
|
|
597
|
+
}));
|
|
598
|
+
}
|
|
599
|
+
const totalFiles = filesToUpload.length;
|
|
394
600
|
let totalBytes = 0;
|
|
601
|
+
let folderBytes = 0;
|
|
395
602
|
const fileSizes = new Map();
|
|
396
603
|
files.forEach((file) => {
|
|
397
604
|
const size = this.getFileSize(file);
|
|
398
605
|
fileSizes.set(file, size);
|
|
399
|
-
|
|
606
|
+
folderBytes += size;
|
|
607
|
+
});
|
|
608
|
+
filesToUpload.forEach((file) => {
|
|
609
|
+
totalBytes += fileSizes.get(file) ?? 0;
|
|
400
610
|
});
|
|
401
611
|
// Track progress across all files
|
|
402
612
|
let processedFiles = 0;
|
|
@@ -411,13 +621,15 @@ class TurboAuthenticatedBaseUploadService extends TurboUnauthenticatedUploadServ
|
|
|
411
621
|
fileIndex,
|
|
412
622
|
totalFiles,
|
|
413
623
|
});
|
|
414
|
-
const
|
|
624
|
+
const contentHash = contentHashes.get(file);
|
|
415
625
|
const dataItemOptsWithContentType = {
|
|
416
626
|
...dataItemOpts,
|
|
417
|
-
tags:
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
627
|
+
tags: this.folderFileTags({
|
|
628
|
+
file,
|
|
629
|
+
dataItemOpts,
|
|
630
|
+
contentHash,
|
|
631
|
+
hashTagName: folderIndex?.hashTagName,
|
|
632
|
+
}),
|
|
421
633
|
};
|
|
422
634
|
try {
|
|
423
635
|
const result = await this.uploadFile({
|
|
@@ -462,8 +674,24 @@ class TurboAuthenticatedBaseUploadService extends TurboUnauthenticatedUploadServ
|
|
|
462
674
|
},
|
|
463
675
|
fundingMode,
|
|
464
676
|
});
|
|
465
|
-
const
|
|
466
|
-
|
|
677
|
+
const itemKey = itemKeys.get(file);
|
|
678
|
+
if (itemKey !== undefined) {
|
|
679
|
+
// Recorded before anything else can fail, so a run that is killed
|
|
680
|
+
// part way through never loses a file it has already paid for.
|
|
681
|
+
knownIds.set(itemKey, result.id);
|
|
682
|
+
try {
|
|
683
|
+
await folderIndex?.set(itemKey, result.id);
|
|
684
|
+
}
|
|
685
|
+
catch (error) {
|
|
686
|
+
// A failed index write costs the next run a re-upload; it must not
|
|
687
|
+
// fail this one, which has already paid for and landed the bytes.
|
|
688
|
+
this.logger.error('Failed to write to folder index', error);
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
else {
|
|
692
|
+
const relativePath = this.getRelativePath(file, params);
|
|
693
|
+
paths[relativePath] = { id: result.id };
|
|
694
|
+
}
|
|
467
695
|
response.fileResponses.push(result);
|
|
468
696
|
// Update processed counts after file completes
|
|
469
697
|
processedFiles++;
|
|
@@ -499,10 +727,9 @@ class TurboAuthenticatedBaseUploadService extends TurboUnauthenticatedUploadServ
|
|
|
499
727
|
errors.push(error);
|
|
500
728
|
}
|
|
501
729
|
};
|
|
502
|
-
const limit = (0, plimit_lit_1.pLimit)(maxConcurrentUploads);
|
|
503
730
|
let cryptoFundResult;
|
|
504
731
|
if (fundingMode instanceof types_js_1.OnDemandFunding) {
|
|
505
|
-
const totalByteCount =
|
|
732
|
+
const totalByteCount = filesToUpload.reduce((acc, file) => {
|
|
506
733
|
return acc + this.getFileSize(file) + 1200; // allow extra per file for ANS-104 headers
|
|
507
734
|
}, 0);
|
|
508
735
|
cryptoFundResult = await this.onDemand({
|
|
@@ -510,15 +737,36 @@ class TurboAuthenticatedBaseUploadService extends TurboUnauthenticatedUploadServ
|
|
|
510
737
|
onDemandFunding: fundingMode,
|
|
511
738
|
});
|
|
512
739
|
}
|
|
513
|
-
await Promise.all(
|
|
740
|
+
await Promise.all(filesToUpload.map((file, index) => limit(() => uploadFile(file, index))));
|
|
514
741
|
this.logger.debug('Finished uploading files', {
|
|
515
|
-
numFiles:
|
|
742
|
+
numFiles: filesToUpload.length,
|
|
516
743
|
numErrors: errors.length,
|
|
517
744
|
results: response.fileResponses,
|
|
518
745
|
});
|
|
519
746
|
if (errors.length > 0) {
|
|
520
747
|
response.errors = errors;
|
|
521
748
|
}
|
|
749
|
+
if (folderIndex !== undefined) {
|
|
750
|
+
// Built in folder order rather than in completion order, so an unchanged
|
|
751
|
+
// folder produces byte identical manifest bytes -- and therefore an
|
|
752
|
+
// identical manifest data item id -- run after run.
|
|
753
|
+
for (const file of files) {
|
|
754
|
+
const id = knownIds.get(itemKeys.get(file));
|
|
755
|
+
if (id !== undefined) {
|
|
756
|
+
paths[this.getRelativePath(file, params)] = { id };
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
response.folderIndexSummary = {
|
|
760
|
+
totalFiles: files.length,
|
|
761
|
+
totalBytes: folderBytes,
|
|
762
|
+
// What landed, not what was planned. With throwOnFailure: false a file
|
|
763
|
+
// can be planned, paid for nothing, and never arrive.
|
|
764
|
+
uploadedFiles: processedFiles,
|
|
765
|
+
uploadedBytes: processedBytes,
|
|
766
|
+
reusedFiles: files.length - filesToUpload.length,
|
|
767
|
+
reusedBytes: folderBytes - totalBytes,
|
|
768
|
+
};
|
|
769
|
+
}
|
|
522
770
|
if (disableManifest) {
|
|
523
771
|
emitter.emit('folder-success');
|
|
524
772
|
return response;
|
|
@@ -537,8 +785,7 @@ class TurboAuthenticatedBaseUploadService extends TurboUnauthenticatedUploadServ
|
|
|
537
785
|
fallbackFile,
|
|
538
786
|
});
|
|
539
787
|
const tagsWithManifestContentType = [
|
|
540
|
-
...(
|
|
541
|
-
[]),
|
|
788
|
+
...(manifestDataItemOpts?.tags?.filter((tag) => tag.name !== 'Content-Type') ?? []),
|
|
542
789
|
{ name: 'Content-Type', value: 'application/x.arweave-manifest+json' },
|
|
543
790
|
];
|
|
544
791
|
const manifestBuffer = Buffer.from(JSON.stringify(manifest));
|
|
@@ -548,7 +795,10 @@ class TurboAuthenticatedBaseUploadService extends TurboUnauthenticatedUploadServ
|
|
|
548
795
|
fileStreamFactory: () => this.createManifestStream(manifestBuffer),
|
|
549
796
|
fileSizeFactory: () => manifestBuffer.byteLength,
|
|
550
797
|
signal,
|
|
551
|
-
dataItemOpts: {
|
|
798
|
+
dataItemOpts: {
|
|
799
|
+
...manifestDataItemOpts,
|
|
800
|
+
tags: tagsWithManifestContentType,
|
|
801
|
+
},
|
|
552
802
|
chunkByteCount,
|
|
553
803
|
maxChunkConcurrency,
|
|
554
804
|
maxFinalizeMs,
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createFileFolderIndex = createFileFolderIndex;
|
|
4
|
+
/**
|
|
5
|
+
* Copyright (C) 2022-2024 Permanent Data Solutions, Inc.
|
|
6
|
+
*
|
|
7
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
8
|
+
* you may not use this file except in compliance with the License.
|
|
9
|
+
* You may obtain a copy of the License at
|
|
10
|
+
*
|
|
11
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
12
|
+
*
|
|
13
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
14
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
15
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
16
|
+
* See the License for the specific language governing permissions and
|
|
17
|
+
* limitations under the License.
|
|
18
|
+
*/
|
|
19
|
+
const node_fs_1 = require("node:fs");
|
|
20
|
+
const node_path_1 = require("node:path");
|
|
21
|
+
const common_js_1 = require("../utils/common.js");
|
|
22
|
+
const folderIndex_js_1 = require("../utils/folderIndex.js");
|
|
23
|
+
const fileFolderIndexVersion = 2;
|
|
24
|
+
/**
|
|
25
|
+
* A local record of folder index key to data item id, for uploads on a machine
|
|
26
|
+
* that keeps its working directory between deploys.
|
|
27
|
+
*
|
|
28
|
+
* The file is an append-only log, one JSON record per line, compacted when it
|
|
29
|
+
* is loaded. That shape falls out of two requirements pulling against each
|
|
30
|
+
* other:
|
|
31
|
+
*
|
|
32
|
+
* - It has to be written after every single upload, not once at the end of the
|
|
33
|
+
* run. An upload that has been paid for but forgotten is money burnt, and a
|
|
34
|
+
* deploy killed part way through is the normal case rather than the
|
|
35
|
+
* exceptional one.
|
|
36
|
+
* - Rewriting the whole file per upload is quadratic. A first deploy or a
|
|
37
|
+
* migration of a few thousand files spends minutes and gigabytes of writes on
|
|
38
|
+
* nothing but bookkeeping.
|
|
39
|
+
*
|
|
40
|
+
* Appending one line is constant work, and it is *more* crash safe than a
|
|
41
|
+
* rewrite rather than less: a process killed mid write can only damage the last
|
|
42
|
+
* line, which is dropped on load, where a torn rewrite loses every id in the
|
|
43
|
+
* file. Compaction happens once per load, through a temp file and a rename, so
|
|
44
|
+
* the readable file is never the partial one.
|
|
45
|
+
*
|
|
46
|
+
* Malformed records are dropped. A hand edited index must never be able to
|
|
47
|
+
* publish a manifest pointing at nothing.
|
|
48
|
+
*/
|
|
49
|
+
function createFileFolderIndex({ filePath, logger, }) {
|
|
50
|
+
const absolutePath = (0, node_path_1.resolve)(filePath);
|
|
51
|
+
const tempPath = `${absolutePath}.tmp`;
|
|
52
|
+
const map = new Map();
|
|
53
|
+
const record = (key, id) => `${JSON.stringify({ k: key, i: id })}\n`;
|
|
54
|
+
const header = `${JSON.stringify({ folderIndex: fileFolderIndexVersion })}\n`;
|
|
55
|
+
/** Rewrites the log as one record per live entry, atomically. */
|
|
56
|
+
const compact = () => {
|
|
57
|
+
(0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(absolutePath), { recursive: true });
|
|
58
|
+
const body = [...map]
|
|
59
|
+
// Code units, not `localeCompare`, for the same reason the key encoding
|
|
60
|
+
// avoids it: it is not a total order over distinct strings and depends on
|
|
61
|
+
// the host's ICU data. Only the file's readability rides on this one, but
|
|
62
|
+
// a sort that can call two distinct keys equal has no business here.
|
|
63
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
|
|
64
|
+
.map(([key, id]) => record(key, id))
|
|
65
|
+
.join('');
|
|
66
|
+
try {
|
|
67
|
+
(0, node_fs_1.writeFileSync)(tempPath, `${header}${body}`);
|
|
68
|
+
(0, node_fs_1.renameSync)(tempPath, absolutePath);
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
(0, node_fs_1.rmSync)(tempPath, { force: true });
|
|
72
|
+
throw error;
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
let lineCount = 0;
|
|
76
|
+
if ((0, node_fs_1.existsSync)(absolutePath)) {
|
|
77
|
+
let malformed = 0;
|
|
78
|
+
// A line at a time, so a truncated tail costs one entry rather than all of
|
|
79
|
+
// them.
|
|
80
|
+
for (const line of (0, node_fs_1.readFileSync)(absolutePath, 'utf-8').split('\n')) {
|
|
81
|
+
if (line.length === 0) {
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
lineCount++;
|
|
85
|
+
try {
|
|
86
|
+
const parsed = JSON.parse(line);
|
|
87
|
+
if (parsed?.folderIndex !== undefined) {
|
|
88
|
+
continue; // header
|
|
89
|
+
}
|
|
90
|
+
if ((0, folderIndex_js_1.isValidFolderIndexKey)(parsed?.k) &&
|
|
91
|
+
(0, common_js_1.isValidArweaveBase64URL)(parsed?.i)) {
|
|
92
|
+
map.set(parsed.k, parsed.i); // last write wins
|
|
93
|
+
}
|
|
94
|
+
else {
|
|
95
|
+
malformed++;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
malformed++;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
if (malformed > 0) {
|
|
103
|
+
logger?.warn(`Dropped ${malformed} unreadable record(s) from the folder index at ${absolutePath}`);
|
|
104
|
+
}
|
|
105
|
+
// Only worth rewriting when the log has actually accumulated slack.
|
|
106
|
+
if (lineCount > map.size + 1) {
|
|
107
|
+
try {
|
|
108
|
+
compact();
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
logger?.warn(`Could not compact the folder index at ${absolutePath}`, error);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return {
|
|
116
|
+
name: `file:${absolutePath}`,
|
|
117
|
+
get: (key) => map.get(key),
|
|
118
|
+
set: (key, id) => {
|
|
119
|
+
map.set(key, id);
|
|
120
|
+
(0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(absolutePath), { recursive: true });
|
|
121
|
+
if (!(0, node_fs_1.existsSync)(absolutePath)) {
|
|
122
|
+
(0, node_fs_1.writeFileSync)(absolutePath, header);
|
|
123
|
+
}
|
|
124
|
+
(0, node_fs_1.appendFileSync)(absolutePath, record(key, id));
|
|
125
|
+
},
|
|
126
|
+
knownContentHashes: (contentHashes) => {
|
|
127
|
+
const known = new Set([...map.keys()].map(folderIndex_js_1.contentHashFromFolderIndexKey));
|
|
128
|
+
return contentHashes.filter((contentHash) => known.has(contentHash));
|
|
129
|
+
},
|
|
130
|
+
entries: () => Object.fromEntries(map),
|
|
131
|
+
};
|
|
132
|
+
}
|
package/lib/cjs/node/index.js
CHANGED
|
@@ -30,6 +30,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
30
30
|
* limitations under the License.
|
|
31
31
|
*/
|
|
32
32
|
__exportStar(require("./factory.js"), exports);
|
|
33
|
+
__exportStar(require("./folderIndex.js"), exports);
|
|
33
34
|
__exportStar(require("./signer.js"), exports);
|
|
34
35
|
__exportStar(require("./upload.js"), exports);
|
|
35
36
|
__exportStar(require("../types.js"), exports);
|
package/lib/cjs/node/upload.js
CHANGED
|
@@ -18,6 +18,8 @@ exports.TurboAuthenticatedUploadService = void 0;
|
|
|
18
18
|
*/
|
|
19
19
|
const fs_1 = require("fs");
|
|
20
20
|
const mime_types_1 = require("mime-types");
|
|
21
|
+
const node_crypto_1 = require("node:crypto");
|
|
22
|
+
const promises_1 = require("node:stream/promises");
|
|
21
23
|
const path_1 = require("path");
|
|
22
24
|
const stream_1 = require("stream");
|
|
23
25
|
const upload_js_1 = require("../common/upload.js");
|
|
@@ -87,5 +89,10 @@ class TurboAuthenticatedUploadService extends upload_js_1.TurboAuthenticatedBase
|
|
|
87
89
|
createManifestStream(manifestBuffer) {
|
|
88
90
|
return stream_1.Readable.from(manifestBuffer);
|
|
89
91
|
}
|
|
92
|
+
async computeContentHash(file) {
|
|
93
|
+
const hash = (0, node_crypto_1.createHash)('sha256');
|
|
94
|
+
await (0, promises_1.pipeline)((0, fs_1.createReadStream)(file), hash);
|
|
95
|
+
return hash.digest('hex');
|
|
96
|
+
}
|
|
90
97
|
}
|
|
91
98
|
exports.TurboAuthenticatedUploadService = TurboAuthenticatedUploadService;
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Copyright (C) 2022-2024 Permanent Data Solutions, Inc.
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
|
+
exports.contentHashTagName = void 0;
|
|
19
|
+
exports.isValidContentHash = isValidContentHash;
|
|
20
|
+
exports.isValidFolderIndexKey = isValidFolderIndexKey;
|
|
21
|
+
exports.contentHashFromFolderIndexKey = contentHashFromFolderIndexKey;
|
|
22
|
+
exports.folderIndexKey = folderIndexKey;
|
|
23
|
+
/**
|
|
24
|
+
* Internals shared by the folder index layers and by `uploadFolder`. Not part
|
|
25
|
+
* of the package's public surface.
|
|
26
|
+
*/
|
|
27
|
+
/** Tag carrying the sha-256 of a file's own bytes, as lowercase hex. */
|
|
28
|
+
exports.contentHashTagName = 'File-SHA256';
|
|
29
|
+
const contentHashRegex = /^[0-9a-f]{64}$/;
|
|
30
|
+
const folderIndexKeyRegex = /^[0-9a-f]{64}\.[0-9a-f]{64}$/;
|
|
31
|
+
/** True for a lowercase hex sha-256 digest of a file's bytes. */
|
|
32
|
+
function isValidContentHash(hash) {
|
|
33
|
+
return hash !== undefined && contentHashRegex.test(hash);
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* A folder index key is `<sha-256 of the bytes>.<sha-256 of the tags>`.
|
|
37
|
+
*
|
|
38
|
+
* Both halves matter. Keying on the bytes alone would reuse an item whose tags
|
|
39
|
+
* are not the ones the caller asked for: an empty `a.css` and an empty `b.js`
|
|
40
|
+
* hash identically, and reusing one for the other would serve JavaScript as
|
|
41
|
+
* `text/css`. Keying on the tags as well means a reused data item is always
|
|
42
|
+
* exactly the data item this call would otherwise have created.
|
|
43
|
+
*
|
|
44
|
+
* The bytes half is kept in the clear so a layer that queries a gateway can
|
|
45
|
+
* recover it and filter on the `File-SHA256` tag.
|
|
46
|
+
*/
|
|
47
|
+
function isValidFolderIndexKey(key) {
|
|
48
|
+
return key !== undefined && folderIndexKeyRegex.test(key);
|
|
49
|
+
}
|
|
50
|
+
/** The bytes half of a folder index key. */
|
|
51
|
+
function contentHashFromFolderIndexKey(key) {
|
|
52
|
+
return key.slice(0, 64);
|
|
53
|
+
}
|
|
54
|
+
async function sha256Hex(data) {
|
|
55
|
+
const digest = await crypto.subtle.digest('SHA-256', data);
|
|
56
|
+
return Buffer.from(digest).toString('hex');
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Canonical encoding of a tag set: the same tags in a different order encode
|
|
60
|
+
* identically, because two data items that differ only in tag order are the
|
|
61
|
+
* same item as far as reuse goes.
|
|
62
|
+
*
|
|
63
|
+
* The sort compares code units rather than using `localeCompare`, which is not
|
|
64
|
+
* a total order over distinct strings and depends on the host's ICU data --
|
|
65
|
+
* NFC and NFD spellings of the same word compare equal without being equal, and
|
|
66
|
+
* two locales disagree on where an accented letter sorts. Either would let one
|
|
67
|
+
* tag set hash differently on two machines, which costs a reuse.
|
|
68
|
+
*
|
|
69
|
+
* The encoding has to be injective, not merely stable. An ANS-104 tag name and
|
|
70
|
+
* value are arbitrary byte arrays, so a delimiter-joined string collides: with
|
|
71
|
+
* a 0x00/0x01 join, a single tag whose value embeds both delimiters encodes
|
|
72
|
+
* exactly like two separate tags. A collision here is a wrong reuse, which is
|
|
73
|
+
* the one failure the composite key exists to make impossible. JSON escapes
|
|
74
|
+
* the delimiters, so no value can forge a record boundary.
|
|
75
|
+
*/
|
|
76
|
+
function canonicalTags(tags) {
|
|
77
|
+
const pairs = tags
|
|
78
|
+
.map((tag) => [tag.name, tag.value])
|
|
79
|
+
.sort(([aName, aValue], [bName, bValue]) => {
|
|
80
|
+
const [a, b] = aName === bName ? [aValue, bValue] : [aName, bName];
|
|
81
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
82
|
+
});
|
|
83
|
+
return new TextEncoder().encode(JSON.stringify(pairs));
|
|
84
|
+
}
|
|
85
|
+
/** The folder index key for a file with these bytes and these final tags. */
|
|
86
|
+
async function folderIndexKey({ contentHash, tags, }) {
|
|
87
|
+
return `${contentHash}.${await sha256Hex(canonicalTags(tags))}`;
|
|
88
|
+
}
|