@duraxis/storage-disk 0.1.1 → 0.2.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/CHANGELOG.md +33 -0
- package/README.md +5 -1
- package/dist/async-disk-storage.driver.d.ts +18 -1
- package/dist/disk-format.d.ts +8 -0
- package/dist/index.cjs +140 -45
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +143 -48
- package/dist/index.js.map +1 -1
- package/dist/ownership.d.ts +1 -2
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
-
import { dirname, join, resolve } from "node:path";
|
|
3
|
-
import { mkdir, open,
|
|
4
|
-
import { StorageError, assertStorageKey } from "@duraxis/storage";
|
|
2
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
3
|
+
import { mkdir, open, opendir, readFile, readlink, realpath, rename, rm, stat, statfs, truncate, unlink } from "node:fs/promises";
|
|
4
|
+
import { StorageError, assertStorageKey, assertWriteCondition } from "@duraxis/storage";
|
|
5
5
|
import { hostname } from "node:os";
|
|
6
6
|
// src/disk-format.ts
|
|
7
7
|
var OBJECT_MAGIC = Buffer.from("DXOBJ001", "ascii");
|
|
@@ -112,28 +112,37 @@ function decodeFrame(bytes, expectedSequence) {
|
|
|
112
112
|
if (sha256(JSON.stringify(payload)) != record.checksum) throw corruption("Storage journal integrity check failed");
|
|
113
113
|
return payload;
|
|
114
114
|
}
|
|
115
|
-
function
|
|
116
|
-
const
|
|
115
|
+
async function replayJournal(handle, maxBytes, consume) {
|
|
116
|
+
const info = await handle.stat();
|
|
117
|
+
if (info.size > maxBytes) throw new StorageError("Storage journal exceeds configured limit", "RESOURCE_LIMIT");
|
|
117
118
|
let offset = 0;
|
|
118
119
|
let sequence = 1;
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
120
|
+
const read = async (buffer, position) => {
|
|
121
|
+
let received = 0;
|
|
122
|
+
while (received < buffer.byteLength) {
|
|
123
|
+
const result = await handle.read(buffer, received, buffer.byteLength - received, position + received);
|
|
124
|
+
if (!result.bytesRead) break;
|
|
125
|
+
received += result.bytesRead;
|
|
126
|
+
}
|
|
127
|
+
return received;
|
|
128
|
+
};
|
|
129
|
+
while (offset < info.size) {
|
|
130
|
+
const header = /* @__PURE__ */ new Uint8Array(4);
|
|
131
|
+
if (await read(header, offset) != 4) return {
|
|
122
132
|
validBytes: offset,
|
|
123
133
|
incompleteTail: true
|
|
124
134
|
};
|
|
125
|
-
const length = new DataView(
|
|
126
|
-
if (length
|
|
127
|
-
|
|
128
|
-
|
|
135
|
+
const length = new DataView(header.buffer).getUint32(0, false);
|
|
136
|
+
if (!length || length > 65536) throw corruption("Invalid storage journal frame length");
|
|
137
|
+
const payload = new Uint8Array(length);
|
|
138
|
+
if (await read(payload, offset + 4) != length) return {
|
|
129
139
|
validBytes: offset,
|
|
130
140
|
incompleteTail: true
|
|
131
141
|
};
|
|
132
|
-
|
|
142
|
+
consume(decodeFrame(payload, sequence++));
|
|
133
143
|
offset += 4 + length;
|
|
134
144
|
}
|
|
135
145
|
return {
|
|
136
|
-
frames,
|
|
137
146
|
validBytes: offset,
|
|
138
147
|
incompleteTail: false
|
|
139
148
|
};
|
|
@@ -509,6 +518,19 @@ var DirectoryOwnership = class {
|
|
|
509
518
|
this.#owned = true;
|
|
510
519
|
});
|
|
511
520
|
}
|
|
521
|
+
async verify() {
|
|
522
|
+
if (!this.#owned) throw ownershipConflict("Storage directory is not owned");
|
|
523
|
+
await withGuard(this.root, async () => {
|
|
524
|
+
const observed = await observe(join(this.root, LOCK_FILE));
|
|
525
|
+
if (!observed) throw ownershipConflict("Storage owner lock is missing");
|
|
526
|
+
try {
|
|
527
|
+
if (parseOwner(observed.bytes).ownerId != this.#ownerId) throw ownershipConflict("Storage ownership changed");
|
|
528
|
+
await assertObservedUnchanged(observed);
|
|
529
|
+
} finally {
|
|
530
|
+
await observed.handle.close();
|
|
531
|
+
}
|
|
532
|
+
});
|
|
533
|
+
}
|
|
512
534
|
async release() {
|
|
513
535
|
if (!this.#owned) return;
|
|
514
536
|
await withGuard(this.root, async () => {
|
|
@@ -549,6 +571,9 @@ var JOURNAL_FILE = "journal.log";
|
|
|
549
571
|
var PREVIOUS_JOURNAL = "journal.previous";
|
|
550
572
|
var NEXT_JOURNAL = "journal.next";
|
|
551
573
|
var OBJECTS_DIRECTORY = "objects";
|
|
574
|
+
var MAX_KEY_BYTES = 4096;
|
|
575
|
+
var MAX_OBJECT_BYTES = 268435456;
|
|
576
|
+
var MAX_JOURNAL_BYTES = 1073741824;
|
|
552
577
|
function nodeErrorCode(error) {
|
|
553
578
|
return error && typeof error == "object" && "code" in error ? String(error.code) : void 0;
|
|
554
579
|
}
|
|
@@ -588,6 +613,7 @@ var AsyncDiskStorageDriver = class AsyncDiskStorageDriver {
|
|
|
588
613
|
root;
|
|
589
614
|
registryKey;
|
|
590
615
|
options;
|
|
616
|
+
capabilities = Object.freeze({ boundedReads: true });
|
|
591
617
|
static activeDirectories = /* @__PURE__ */ new Set();
|
|
592
618
|
entries = /* @__PURE__ */ new Map();
|
|
593
619
|
ownership;
|
|
@@ -600,6 +626,8 @@ var AsyncDiskStorageDriver = class AsyncDiskStorageDriver {
|
|
|
600
626
|
bytesWritten: 0,
|
|
601
627
|
synchronizationWaitMs: 0
|
|
602
628
|
};
|
|
629
|
+
metadataBytes = 0;
|
|
630
|
+
queuedOperations = 0;
|
|
603
631
|
operationTail = Promise.resolve();
|
|
604
632
|
journal;
|
|
605
633
|
journalBytes = 0;
|
|
@@ -618,13 +646,14 @@ var AsyncDiskStorageDriver = class AsyncDiskStorageDriver {
|
|
|
618
646
|
}
|
|
619
647
|
static async open(options) {
|
|
620
648
|
if (!options || typeof options.directory != "string" || options.directory.trim() == "") throw new TypeError("A storage directory is required");
|
|
621
|
-
const maxKeyBytes = options.maxKeyBytes ??
|
|
622
|
-
const maxObjectBytes = options.maxObjectBytes ??
|
|
623
|
-
const maxJournalBytes = options.maxJournalBytes ??
|
|
649
|
+
const maxKeyBytes = options.maxKeyBytes ?? MAX_KEY_BYTES;
|
|
650
|
+
const maxObjectBytes = options.maxObjectBytes ?? MAX_OBJECT_BYTES;
|
|
651
|
+
const maxJournalBytes = options.maxJournalBytes ?? MAX_JOURNAL_BYTES;
|
|
624
652
|
const ownershipRecovery = normalizeOwnershipRecovery(options.ownershipRecovery);
|
|
625
653
|
if (!Number.isSafeInteger(maxKeyBytes) || maxKeyBytes < 64 || maxKeyBytes > 65536) throw new RangeError("Invalid maximum storage key size");
|
|
626
|
-
if (!Number.isSafeInteger(maxObjectBytes) || maxObjectBytes < 0 || maxObjectBytes >
|
|
654
|
+
if (!Number.isSafeInteger(maxObjectBytes) || maxObjectBytes < 0 || maxObjectBytes > MAX_JOURNAL_BYTES) throw new RangeError("Invalid maximum object size");
|
|
627
655
|
if (!Number.isSafeInteger(maxJournalBytes) || maxJournalBytes < 1048576) throw new RangeError("Invalid maximum journal size");
|
|
656
|
+
for (const value of [options.maxMetadataBytes, options.maxQueuedOperations]) if (value !== void 0 && (!Number.isSafeInteger(value) || value < 1)) throw new RangeError("Invalid storage resource limit");
|
|
628
657
|
const requested = resolve(options.directory);
|
|
629
658
|
await mkdir(requested, { recursive: true });
|
|
630
659
|
const root = await realpath(requested);
|
|
@@ -681,19 +710,22 @@ var AsyncDiskStorageDriver = class AsyncDiskStorageDriver {
|
|
|
681
710
|
await syncAndClose(await open(journalPath, "wx", 384), "New storage journal");
|
|
682
711
|
await this.syncDirectory(this.root);
|
|
683
712
|
}
|
|
684
|
-
const
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
713
|
+
const input = await open(journalPath, "r");
|
|
714
|
+
let decoded;
|
|
715
|
+
try {
|
|
716
|
+
decoded = await replayJournal(input, this.options.maxJournalBytes, (frame) => {
|
|
717
|
+
this.validateKey(frame.key);
|
|
718
|
+
this.sequence = frame.sequence;
|
|
719
|
+
if (frame.op == "put") this.setEntry(frame.key, {
|
|
720
|
+
version: frame.version,
|
|
721
|
+
createdAt: frame.createdAt,
|
|
722
|
+
size: frame.size,
|
|
723
|
+
digest: frame.digest
|
|
724
|
+
});
|
|
725
|
+
else this.deleteEntry(frame.key);
|
|
695
726
|
});
|
|
696
|
-
|
|
727
|
+
} finally {
|
|
728
|
+
await input.close();
|
|
697
729
|
}
|
|
698
730
|
if (decoded.incompleteTail) {
|
|
699
731
|
await truncate(journalPath, decoded.validBytes);
|
|
@@ -704,6 +736,15 @@ var AsyncDiskStorageDriver = class AsyncDiskStorageDriver {
|
|
|
704
736
|
await this.assertCurrentObjectsExist();
|
|
705
737
|
await this.cleanupPhysicalObjects();
|
|
706
738
|
}
|
|
739
|
+
setEntry(key, value) {
|
|
740
|
+
const size = this.entries.has(key) ? 0 : key.length * 2 + 256;
|
|
741
|
+
if (this.metadataBytes + size > (this.options.maxMetadataBytes ?? 67108864)) throw new StorageError("Resident storage metadata limit exceeded", "RESOURCE_LIMIT");
|
|
742
|
+
this.metadataBytes += size;
|
|
743
|
+
this.entries.set(key, value);
|
|
744
|
+
}
|
|
745
|
+
deleteEntry(key) {
|
|
746
|
+
if (this.entries.delete(key)) this.metadataBytes -= key.length * 2 + 256;
|
|
747
|
+
}
|
|
707
748
|
validateKey(key) {
|
|
708
749
|
assertStorageKey(key);
|
|
709
750
|
if (Buffer.byteLength(key, "utf8") > this.options.maxKeyBytes) throw new StorageError("Storage key exceeds configured byte limit", "INVALID_KEY");
|
|
@@ -714,6 +755,8 @@ var AsyncDiskStorageDriver = class AsyncDiskStorageDriver {
|
|
|
714
755
|
}
|
|
715
756
|
async exclusive(operation) {
|
|
716
757
|
this.assertUsable();
|
|
758
|
+
if (this.queuedOperations >= (this.options.maxQueuedOperations ?? 256)) throw new StorageError("Storage operation admission limit exceeded", "RESOURCE_LIMIT");
|
|
759
|
+
this.queuedOperations++;
|
|
717
760
|
const before = performance.now();
|
|
718
761
|
const previous = this.operationTail;
|
|
719
762
|
let release;
|
|
@@ -726,15 +769,18 @@ var AsyncDiskStorageDriver = class AsyncDiskStorageDriver {
|
|
|
726
769
|
this.assertUsable();
|
|
727
770
|
return await operation();
|
|
728
771
|
} finally {
|
|
772
|
+
this.queuedOperations--;
|
|
729
773
|
release();
|
|
730
774
|
}
|
|
731
775
|
}
|
|
732
|
-
get(key) {
|
|
776
|
+
get(key, options = {}) {
|
|
733
777
|
return this.exclusive(async () => {
|
|
734
778
|
this.validateKey(key);
|
|
779
|
+
options.signal?.throwIfAborted();
|
|
735
780
|
this.metrics.reads++;
|
|
736
781
|
const metadata = this.entries.get(key);
|
|
737
782
|
if (!metadata) return null;
|
|
783
|
+
if (metadata.size > (options.maxBytes ?? this.options.maxObjectBytes)) throw new StorageError("Storage read exceeds byte limit", "RESOURCE_LIMIT");
|
|
738
784
|
const path = this.objectPath(key, metadata.version);
|
|
739
785
|
let info;
|
|
740
786
|
try {
|
|
@@ -744,7 +790,7 @@ var AsyncDiskStorageDriver = class AsyncDiskStorageDriver {
|
|
|
744
790
|
throw error;
|
|
745
791
|
}
|
|
746
792
|
if (info.size > this.options.maxObjectBytes + 32768) throw new StorageError("Physical object exceeds configured size", "CORRUPTION");
|
|
747
|
-
const physical = await readFile(path);
|
|
793
|
+
const physical = await readFile(path, { signal: options.signal });
|
|
748
794
|
this.metrics.bytesRead += physical.byteLength;
|
|
749
795
|
return {
|
|
750
796
|
data: decodePhysicalObject(physical, key, metadata),
|
|
@@ -757,11 +803,13 @@ var AsyncDiskStorageDriver = class AsyncDiskStorageDriver {
|
|
|
757
803
|
this.validateKey(key);
|
|
758
804
|
if (!(data instanceof Uint8Array)) throw new TypeError("Storage data must be a Uint8Array");
|
|
759
805
|
if (data.byteLength > this.options.maxObjectBytes) throw new StorageError("Storage object exceeds configured byte limit", "RESOURCE_LIMIT");
|
|
806
|
+
assertWriteCondition(options?.condition);
|
|
760
807
|
const current = this.entries.get(key);
|
|
761
808
|
if (options.condition.type == "if-absent" ? current != null : current == null || current.version != options.condition.version) return {
|
|
762
809
|
success: false,
|
|
763
810
|
reason: "conflict"
|
|
764
811
|
};
|
|
812
|
+
if (!this.entries.has(key) && this.metadataBytes + key.length * 2 + 256 > (this.options.maxMetadataBytes ?? 67108864)) throw new StorageError("Resident storage metadata limit exceeded", "RESOURCE_LIMIT");
|
|
765
813
|
this.metrics.writes++;
|
|
766
814
|
const metadata = {
|
|
767
815
|
version: randomUUID(),
|
|
@@ -809,7 +857,7 @@ var AsyncDiskStorageDriver = class AsyncDiskStorageDriver {
|
|
|
809
857
|
digest: metadata.digest
|
|
810
858
|
};
|
|
811
859
|
await this.append(frame);
|
|
812
|
-
this.
|
|
860
|
+
this.setEntry(key, metadata);
|
|
813
861
|
this.sequence = frame.sequence;
|
|
814
862
|
this.metrics.bytesWritten += physical.byteLength;
|
|
815
863
|
if (current) await this.removeObsolete(this.objectPath(key, current.version));
|
|
@@ -826,6 +874,7 @@ var AsyncDiskStorageDriver = class AsyncDiskStorageDriver {
|
|
|
826
874
|
delete(key, options) {
|
|
827
875
|
return this.exclusive(async () => {
|
|
828
876
|
this.validateKey(key);
|
|
877
|
+
assertWriteCondition(options?.condition);
|
|
829
878
|
const current = this.entries.get(key);
|
|
830
879
|
if (options.condition.type == "if-absent") return current ? {
|
|
831
880
|
success: false,
|
|
@@ -843,21 +892,61 @@ var AsyncDiskStorageDriver = class AsyncDiskStorageDriver {
|
|
|
843
892
|
key
|
|
844
893
|
};
|
|
845
894
|
await this.append(frame);
|
|
846
|
-
this.
|
|
895
|
+
this.deleteEntry(key);
|
|
847
896
|
this.sequence = frame.sequence;
|
|
848
897
|
await this.removeObsolete(this.objectPath(key, current.version));
|
|
849
898
|
return { success: true };
|
|
850
899
|
});
|
|
851
900
|
}
|
|
901
|
+
verifyExclusiveOwnership() {
|
|
902
|
+
return this.exclusive(() => this.ownership.verify());
|
|
903
|
+
}
|
|
904
|
+
async *iterate(prefix, options = {}) {
|
|
905
|
+
if (typeof prefix != "string" || prefix.includes("\0")) throw new StorageError("Invalid storage prefix", "INVALID_KEY");
|
|
906
|
+
const size = options.pageSize ?? 256;
|
|
907
|
+
if (!Number.isSafeInteger(size) || size < 1 || size > 1e3) throw new RangeError("Invalid listing page size");
|
|
908
|
+
const iterator = this.entries.entries();
|
|
909
|
+
let done = false;
|
|
910
|
+
while (!done) {
|
|
911
|
+
options.signal?.throwIfAborted();
|
|
912
|
+
const page = await this.exclusive(async () => {
|
|
913
|
+
const entries = [];
|
|
914
|
+
let visited = 0;
|
|
915
|
+
while (visited++ < size) {
|
|
916
|
+
const next = iterator.next();
|
|
917
|
+
if (next.done) {
|
|
918
|
+
done = true;
|
|
919
|
+
break;
|
|
920
|
+
}
|
|
921
|
+
const [key, value] = next.value;
|
|
922
|
+
if (key.startsWith(prefix)) entries.push({
|
|
923
|
+
key,
|
|
924
|
+
version: value.version,
|
|
925
|
+
createdAt: value.createdAt
|
|
926
|
+
});
|
|
927
|
+
}
|
|
928
|
+
return entries;
|
|
929
|
+
});
|
|
930
|
+
for (const entry of page) {
|
|
931
|
+
options.signal?.throwIfAborted();
|
|
932
|
+
yield entry;
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
}
|
|
852
936
|
list(prefix) {
|
|
853
937
|
return this.exclusive(async () => {
|
|
854
938
|
if (typeof prefix != "string" || prefix.includes("\0") || Buffer.byteLength(prefix, "utf8") > this.options.maxKeyBytes) throw new StorageError("Invalid storage prefix", "INVALID_KEY");
|
|
855
939
|
this.metrics.lists++;
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
940
|
+
const result = [];
|
|
941
|
+
for (const [key, value] of this.entries) if (key.startsWith(prefix)) {
|
|
942
|
+
if (result.length >= 1e5) throw new StorageError("Legacy listing limit exceeded; use iterate()", "RESOURCE_LIMIT");
|
|
943
|
+
result.push({
|
|
944
|
+
key,
|
|
945
|
+
version: value.version,
|
|
946
|
+
createdAt: value.createdAt
|
|
947
|
+
});
|
|
948
|
+
}
|
|
949
|
+
return result.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
|
|
861
950
|
});
|
|
862
951
|
}
|
|
863
952
|
async append(frame) {
|
|
@@ -893,7 +982,7 @@ var AsyncDiskStorageDriver = class AsyncDiskStorageDriver {
|
|
|
893
982
|
let offset = 0;
|
|
894
983
|
let sequence = 0;
|
|
895
984
|
try {
|
|
896
|
-
for (const [key, metadata] of
|
|
985
|
+
for (const [key, metadata] of this.entries) {
|
|
897
986
|
const bytes = encodeJournalFrame({
|
|
898
987
|
format: 1,
|
|
899
988
|
sequence: ++sequence,
|
|
@@ -904,6 +993,7 @@ var AsyncDiskStorageDriver = class AsyncDiskStorageDriver {
|
|
|
904
993
|
size: metadata.size,
|
|
905
994
|
digest: metadata.digest
|
|
906
995
|
});
|
|
996
|
+
if (offset + bytes.byteLength > this.options.maxJournalBytes) throw new StorageError("Compacted journal exceeds configured limit", "RESOURCE_LIMIT");
|
|
907
997
|
await writeAll(next, bytes, offset);
|
|
908
998
|
offset += bytes.byteLength;
|
|
909
999
|
}
|
|
@@ -974,19 +1064,20 @@ var AsyncDiskStorageDriver = class AsyncDiskStorageDriver {
|
|
|
974
1064
|
}
|
|
975
1065
|
}
|
|
976
1066
|
async cleanupPhysicalObjects() {
|
|
977
|
-
const referenced =
|
|
1067
|
+
const referenced = /* @__PURE__ */ new Map();
|
|
1068
|
+
for (const [key, metadata] of this.entries) referenced.set(sha256(new TextEncoder().encode(key)), metadata.version);
|
|
978
1069
|
const walk = async (directory) => {
|
|
979
1070
|
let items;
|
|
980
1071
|
try {
|
|
981
|
-
items = await
|
|
1072
|
+
items = await opendir(directory);
|
|
982
1073
|
} catch (error) {
|
|
983
1074
|
if (nodeErrorCode(error) == "ENOENT") return;
|
|
984
1075
|
throw error;
|
|
985
1076
|
}
|
|
986
|
-
for (const item of items) {
|
|
1077
|
+
for await (const item of items) {
|
|
987
1078
|
const path = join(directory, item.name);
|
|
988
1079
|
if (item.isDirectory()) await walk(path);
|
|
989
|
-
else if (item.isFile() && (item.name.endsWith(".tmp") || item.name.endsWith(".obj") &&
|
|
1080
|
+
else if (item.isFile() && (item.name.endsWith(".tmp") || item.name.endsWith(".obj") && referenced.get(basename(dirname(path))) + ".obj" != item.name)) await this.removeObsolete(path);
|
|
990
1081
|
}
|
|
991
1082
|
};
|
|
992
1083
|
await walk(join(this.root, OBJECTS_DIRECTORY));
|
|
@@ -1002,11 +1093,15 @@ var AsyncDiskStorageDriver = class AsyncDiskStorageDriver {
|
|
|
1002
1093
|
if (hasNext) await rename(next, current);
|
|
1003
1094
|
else if (hasPrevious) await rename(previous, current);
|
|
1004
1095
|
} else if (hasPrevious) try {
|
|
1005
|
-
|
|
1096
|
+
const input = await open(current, "r");
|
|
1097
|
+
try {
|
|
1098
|
+
await replayJournal(input, this.options.maxJournalBytes, () => {});
|
|
1099
|
+
} finally {
|
|
1100
|
+
await input.close();
|
|
1101
|
+
}
|
|
1006
1102
|
await this.removeObsolete(previous);
|
|
1007
|
-
} catch {
|
|
1008
|
-
|
|
1009
|
-
await rename(previous, current);
|
|
1103
|
+
} catch (cause) {
|
|
1104
|
+
throw new StorageError("Cannot establish journal rotation outcome; refusing to restore stale journal", "CORRUPTION", { cause });
|
|
1010
1105
|
}
|
|
1011
1106
|
if (await exists(current) && await exists(next)) await this.removeObsolete(next);
|
|
1012
1107
|
if (await exists(current) && await exists(previous)) await this.removeObsolete(previous);
|