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