keyframe-store 3.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2020-present Jimmy Chen
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,111 @@
1
+ # keyframe-store
2
+
3
+ [![Apache-2.0 licensed][badge-license]][url-license]
4
+ [![NPM version][badge-npm-version]][url-npm]
5
+ [![NPM downloads][badge-npm-downloads]][url-npm]
6
+ [![NPM Unpacked Size (with version)][badge-npm-unpacked-size]][url-npm]
7
+
8
+ Content-addressed version storage for documents handed over whole. Every version is stored as a zstd **keyframe** — compressed on its own — or as a **delta** compressed against exactly one keyframe, using that keyframe's plaintext as the dictionary. Reconstructing any version is at most two reads, a version whose content is already held costs nothing, and the backend is anything that can store bytes by key.
9
+
10
+ ## Table of Contents
11
+
12
+ - 🚀 [Getting Started](#getting-started)
13
+ - 📖 [Documentation](#documentation)
14
+ - ⚖️ [License](#license)
15
+
16
+ ---
17
+
18
+ ## <a name="getting-started">🚀 Getting Started</a>
19
+
20
+ ```bash
21
+ pnpm i keyframe-store
22
+ ```
23
+
24
+ ```ts
25
+ import { createKeyframeStore } from "keyframe-store";
26
+
27
+ const objects = new Map<string, Uint8Array>();
28
+ const keyframeStore = createKeyframeStore({
29
+ delete: async (keys) => {
30
+ for (const key of keys) objects.delete(key);
31
+ },
32
+ read: async (key) => objects.get(key),
33
+ // Create-only: false tells the store another writer of the same content landed first
34
+ write: async (key, bytes) => {
35
+ if (objects.has(key)) return false;
36
+
37
+ objects.set(key, bytes);
38
+ return true;
39
+ },
40
+ });
41
+
42
+ // Every operation is a neverthrow ResultAsync. The first version of a lineage has no keyframe yet
43
+ const first = await keyframeStore.write(Buffer.from(JSON.stringify(document)), { anchoredBytes: 0, hash: "" }).match(
44
+ (writtenVersion) => writtenVersion,
45
+ (error) => {
46
+ throw error;
47
+ },
48
+ );
49
+ // first.baseHash === "" — it became the keyframe, so the lineage's anchor is its hash
50
+ const second = await keyframeStore
51
+ .write(Buffer.from(JSON.stringify(editedDocument)), { anchoredBytes: 0, hash: first.hash })
52
+ .match(
53
+ (writtenVersion) => writtenVersion,
54
+ (error) => {
55
+ throw error;
56
+ },
57
+ );
58
+ // second.baseHash === first.hash and second.storedBytes is roughly the size of the edit
59
+ const plaintext = await keyframeStore.read(second.hash).match(
60
+ (bytes) => bytes,
61
+ (error) => {
62
+ throw error;
63
+ },
64
+ );
65
+ ```
66
+
67
+ ## <a name="documentation">📖 Documentation</a>
68
+
69
+ We highly recommend you take a look at the [documentation](https://esposter.com/docs/api/modules/keyframe-store.html) to level up.
70
+
71
+ ### How it works
72
+
73
+ - **Addressing.** An object's key is the hex SHA-256 of its plaintext, so two versions with identical content resolve to one object whichever keyframe either would have been encoded against. The store is write-once: a write of content it already holds records nothing and reports itself deduplicated.
74
+ - **Encoding.** Each write compresses the plaintext standalone and, when the lineage has a keyframe, again with that keyframe's plaintext as the dictionary. The delta is kept only if it is at most the **promotion ratio** of the standalone size _and_ the bytes already anchored to the keyframe plus this delta fit the **segment budget**; otherwise the standalone form is written and this version becomes the lineage's next keyframe.
75
+ - **Reading.** A keyframe is one read and one decompression; a delta fetches the keyframe its own header names, decompresses it, then decompresses the delta against it. Every result is hashed and compared with the key, so a truncated, altered or misfiled object is a refused read rather than a plausible document.
76
+ - **Collection.** An object survives while any record names it, as its own hash or as its base. The caller answers that from its own records — `collect` takes the hashes an eviction released and the hashes still named, deletes the difference, and returns what it deleted.
77
+ - **The anchor is the caller's.** The store holds no notion of a lineage: a caller derives one anchor per history — the newest keyframe's hash, and the bytes anchored to it — and resets both whenever a write reports an empty base.
78
+
79
+ ### Key exports
80
+
81
+ | Export | Role |
82
+ | ---------------------- | --------------------------------------------------------------------------------------------------- |
83
+ | `createKeyframeStore` | The factory, taking an `ObjectStore` and optional `KeyframeStoreOptions` |
84
+ | `ObjectStore` | The backend interface — `read`, `write`, `delete` by key |
85
+ | `KeyframeStore` | `write(plaintext, anchor)`, `read(hash)`, `collect(released, retained)` — every one a `ResultAsync` |
86
+ | `VersionAnchor` | What a lineage passes to a write: its keyframe's hash and the bytes anchored to it |
87
+ | `WrittenVersion` | What a write reports: the hash, its base, both sizes and whether it was deduplicated |
88
+ | `KeyframeStoreOptions` | `compressionLevel`, `promotionRatio`, `segmentBudgetRatio`, each defaulted from `constants` |
89
+
90
+ ### Commands
91
+
92
+ Run from `packages/keyframe-store/`:
93
+
94
+ ```bash
95
+ pnpm build # compile to dist/
96
+ pnpm test # vitest watch mode (coverage is run from the repo root)
97
+ pnpm bench # the codec benchmark, writing the colocated *.bench.md
98
+ pnpm lint:fix # auto-fix lint
99
+ pnpm typecheck # type check
100
+ ```
101
+
102
+ ## <a name="license">⚖️ License</a>
103
+
104
+ This project is licensed under the [Apache-2.0 license](https://github.com/Esposter/Esposter/blob/main/LICENSE).
105
+
106
+ [badge-license]: https://img.shields.io/github/license/Esposter/Esposter.svg?color=blue
107
+ [url-license]: https://github.com/Esposter/Esposter/blob/main/LICENSE
108
+ [badge-npm-version]: https://img.shields.io/npm/v/keyframe-store/latest?color=brightgreen
109
+ [url-npm]: https://www.npmjs.com/package/keyframe-store/v/latest
110
+ [badge-npm-unpacked-size]: https://img.shields.io/npm/unpacked-size/keyframe-store/latest?label=npm
111
+ [badge-npm-downloads]: https://img.shields.io/npm/dm/keyframe-store.svg
@@ -0,0 +1,88 @@
1
+ import { InvalidOperationError } from "@esposter/shared";
2
+ import { ResultAsync } from "neverthrow";
3
+ //#region src/constants.d.ts
4
+ export declare const OBJECT_MAGIC: Uint8Array;
5
+ export declare const OBJECT_FORMAT_VERSION = 1;
6
+ export declare const OBJECT_VERSION_OFFSET = 4;
7
+ export declare const OBJECT_FLAGS_OFFSET = 5;
8
+ export declare const OBJECT_WINDOW_LOG_OFFSET = 6;
9
+ export declare const OBJECT_HEADER_BYTE_COUNT = 8;
10
+ export declare const KEYFRAME_FLAG = 0;
11
+ export declare const DELTA_FLAG = 1;
12
+ export declare const HASH_BYTE_COUNT = 32;
13
+ export declare const DELTA_HEADER_BYTE_COUNT: number;
14
+ export declare const DEFAULT_COMPRESSION_LEVEL = 12;
15
+ export declare const MIN_WINDOW_LOG = 10;
16
+ export declare const MAX_WINDOW_LOG = 27;
17
+ export declare const DEFAULT_PROMOTION_RATIO: number;
18
+ export declare const DEFAULT_SEGMENT_BUDGET_RATIO = 1;
19
+ //#endregion
20
+ //#region src/models/VersionAnchor.d.ts
21
+ export interface VersionAnchor {
22
+ anchoredBytes: number;
23
+ hash: string;
24
+ }
25
+ //#endregion
26
+ //#region src/models/WrittenVersion.d.ts
27
+ export interface WrittenVersion {
28
+ baseHash: string;
29
+ hash: string;
30
+ isDeduplicated: boolean;
31
+ plaintextBytes: number;
32
+ storedBytes: number;
33
+ }
34
+ //#endregion
35
+ //#region src/models/KeyframeStore.d.ts
36
+ export interface KeyframeStore {
37
+ collect: (releasedHashes: string[], retainedHashes: string[]) => ResultAsync<string[], Error>;
38
+ read: (hash: string) => ResultAsync<Uint8Array, Error>;
39
+ write: (plaintext: Uint8Array, anchor: VersionAnchor) => ResultAsync<WrittenVersion, Error>;
40
+ }
41
+ //#endregion
42
+ //#region src/models/KeyframeStoreOptions.d.ts
43
+ export interface KeyframeStoreOptions {
44
+ compressionLevel?: number;
45
+ promotionRatio?: number;
46
+ segmentBudgetRatio?: number;
47
+ }
48
+ //#endregion
49
+ //#region src/models/ObjectStore.d.ts
50
+ export interface ObjectStore {
51
+ delete: (keys: string[]) => Promise<void>;
52
+ read: (key: string) => Promise<Uint8Array | undefined>;
53
+ write: (key: string, bytes: Uint8Array) => Promise<boolean>;
54
+ }
55
+ //#endregion
56
+ //#region src/createKeyframeStore.d.ts
57
+ export declare const createKeyframeStore: (objectStore: ObjectStore, { compressionLevel, promotionRatio, segmentBudgetRatio }?: KeyframeStoreOptions) => KeyframeStore;
58
+ //#endregion
59
+ //#region src/models/ObjectNotStoredError.d.ts
60
+ export declare class ObjectNotStoredError extends InvalidOperationError {
61
+ constructor(hash: string, message: string);
62
+ }
63
+ //#endregion
64
+ //#region src/models/ParsedObject.d.ts
65
+ export interface ParsedObject {
66
+ baseHash: string;
67
+ payload: Uint8Array;
68
+ windowLog: number;
69
+ }
70
+ //#endregion
71
+ //#region src/services/decodeObject.d.ts
72
+ export declare const decodeObject: (parsedObject: ParsedObject, basePlaintext?: Uint8Array) => Promise<Buffer>;
73
+ //#endregion
74
+ //#region src/services/encodeObject.d.ts
75
+ export declare const encodeObject: (plaintext: Uint8Array, compressionLevel: number, base?: {
76
+ hash: string;
77
+ plaintext: Uint8Array;
78
+ }) => Promise<Uint8Array>;
79
+ //#endregion
80
+ //#region src/services/getContentAddress.d.ts
81
+ export declare const getContentAddress: (plaintext: Uint8Array) => string;
82
+ //#endregion
83
+ //#region src/services/getWindowLog.d.ts
84
+ export declare const getWindowLog: (dictionaryByteCount: number, inputByteCount: number) => number;
85
+ //#endregion
86
+ //#region src/services/parseObject.d.ts
87
+ export declare const parseObject: (hash: string, bytes: Uint8Array) => ParsedObject;
88
+ //#endregion
package/dist/index.js ADDED
@@ -0,0 +1,180 @@
1
+ import { InvalidOperationError, Operation, getResultAsync } from "@esposter/shared";
2
+ import { promisify } from "node:util";
3
+ import { constants, zstdCompress, zstdDecompress } from "node:zlib";
4
+ import { createHash } from "node:crypto";
5
+ //#region src/constants.ts
6
+ const OBJECT_MAGIC = new Uint8Array([
7
+ 75,
8
+ 70,
9
+ 83,
10
+ 84
11
+ ]);
12
+ const OBJECT_FORMAT_VERSION = 1;
13
+ const OBJECT_VERSION_OFFSET = 4;
14
+ const OBJECT_FLAGS_OFFSET = 5;
15
+ const OBJECT_WINDOW_LOG_OFFSET = 6;
16
+ const OBJECT_HEADER_BYTE_COUNT = 8;
17
+ const KEYFRAME_FLAG = 0;
18
+ const DELTA_FLAG = 1;
19
+ const HASH_BYTE_COUNT = 32;
20
+ const DELTA_HEADER_BYTE_COUNT = 40;
21
+ const DEFAULT_COMPRESSION_LEVEL = 12;
22
+ const MIN_WINDOW_LOG = 10;
23
+ const MAX_WINDOW_LOG = 27;
24
+ const DEFAULT_PROMOTION_RATIO = 1 / 3;
25
+ const DEFAULT_SEGMENT_BUDGET_RATIO = 1;
26
+ //#endregion
27
+ //#region src/models/ObjectNotStoredError.ts
28
+ var ObjectNotStoredError = class extends InvalidOperationError {
29
+ constructor(hash, message) {
30
+ super(Operation.Read, hash, message);
31
+ this.name = "ObjectNotStoredError";
32
+ }
33
+ };
34
+ //#endregion
35
+ //#region src/services/decodeObject.ts
36
+ const decompress = promisify(zstdDecompress);
37
+ const decodeObject = (parsedObject, basePlaintext) => decompress(parsedObject.payload, {
38
+ ...basePlaintext ? { dictionary: basePlaintext } : {},
39
+ params: { [constants.ZSTD_d_windowLogMax]: parsedObject.windowLog }
40
+ });
41
+ //#endregion
42
+ //#region src/services/getWindowLog.ts
43
+ const getWindowLog = (dictionaryByteCount, inputByteCount) => Math.min(27, Math.max(10, Math.ceil(Math.log2(dictionaryByteCount + inputByteCount + 1))));
44
+ //#endregion
45
+ //#region src/services/encodeObject.ts
46
+ const compress = promisify(zstdCompress);
47
+ const encodeObject = async (plaintext, compressionLevel, base) => {
48
+ const windowLog = getWindowLog(base?.plaintext.byteLength ?? 0, plaintext.byteLength);
49
+ const payload = await compress(plaintext, {
50
+ ...base ? { dictionary: base.plaintext } : {},
51
+ params: {
52
+ [constants.ZSTD_c_compressionLevel]: compressionLevel,
53
+ [constants.ZSTD_c_windowLog]: windowLog
54
+ }
55
+ });
56
+ const headerByteCount = base ? 40 : 8;
57
+ const bytes = new Uint8Array(headerByteCount + payload.byteLength);
58
+ bytes.set(OBJECT_MAGIC);
59
+ bytes[4] = 1;
60
+ bytes[5] = base ? 1 : 0;
61
+ bytes[6] = windowLog;
62
+ if (base) bytes.set(Buffer.from(base.hash, "hex").subarray(0, 32), 8);
63
+ bytes.set(payload, headerByteCount);
64
+ return bytes;
65
+ };
66
+ //#endregion
67
+ //#region src/services/getContentAddress.ts
68
+ const getContentAddress = (plaintext) => createHash("sha256").update(plaintext).digest("hex");
69
+ //#endregion
70
+ //#region src/services/parseObject.ts
71
+ const parseObject = (hash, bytes) => {
72
+ if (!(bytes.byteLength >= 8 && OBJECT_MAGIC.every((byte, index) => bytes[index] === byte))) throw new InvalidOperationError(Operation.Read, hash, "not a keyframe store object");
73
+ else if (bytes[4] !== 1) throw new InvalidOperationError(Operation.Read, hash, `unknown object format version ${bytes[4]}`);
74
+ const windowLog = bytes[6] ?? 0;
75
+ const flags = bytes[5];
76
+ if (flags === 0) return {
77
+ baseHash: "",
78
+ payload: bytes.subarray(8),
79
+ windowLog
80
+ };
81
+ else if (flags !== 1) throw new InvalidOperationError(Operation.Read, hash, `unknown object flags ${flags}`);
82
+ else if (bytes.byteLength < 40) throw new InvalidOperationError(Operation.Read, hash, "delta object is truncated before its base hash");
83
+ return {
84
+ baseHash: Buffer.from(bytes.subarray(8, 40)).toString("hex"),
85
+ payload: bytes.subarray(40),
86
+ windowLog
87
+ };
88
+ };
89
+ //#endregion
90
+ //#region src/createKeyframeStore.ts
91
+ const verifyContentAddress = (hash, plaintext) => {
92
+ if (getContentAddress(plaintext) !== hash) throw new InvalidOperationError(Operation.Read, hash, "object does not hash to its key");
93
+ return plaintext;
94
+ };
95
+ const createKeyframeStore = (objectStore, { compressionLevel = 12, promotionRatio = DEFAULT_PROMOTION_RATIO, segmentBudgetRatio = 1 } = {}) => {
96
+ const readKeyframe = async (hash) => {
97
+ const bytes = await objectStore.read(hash);
98
+ if (!bytes) return void 0;
99
+ const parsedObject = parseObject(hash, bytes);
100
+ if (parsedObject.baseHash) throw new InvalidOperationError(Operation.Read, hash, `is a delta against ${parsedObject.baseHash}, not a keyframe`);
101
+ return {
102
+ plaintext: verifyContentAddress(hash, await decodeObject(parsedObject)),
103
+ storedBytes: bytes.byteLength
104
+ };
105
+ };
106
+ const readStoredObject = async (hash) => {
107
+ const bytes = await objectStore.read(hash);
108
+ if (!bytes) return void 0;
109
+ const parsedObject = parseObject(hash, bytes);
110
+ if (!parsedObject.baseHash) return {
111
+ baseHash: "",
112
+ plaintext: verifyContentAddress(hash, await decodeObject(parsedObject))
113
+ };
114
+ const keyframe = await readKeyframe(parsedObject.baseHash);
115
+ if (!keyframe) throw new ObjectNotStoredError(hash, `keyframe ${parsedObject.baseHash} is not stored`);
116
+ return {
117
+ baseHash: parsedObject.baseHash,
118
+ plaintext: verifyContentAddress(hash, await decodeObject(parsedObject, keyframe.plaintext))
119
+ };
120
+ };
121
+ return {
122
+ collect: (releasedHashes, retainedHashes) => getResultAsync(async () => {
123
+ const retainedHashSet = new Set(retainedHashes);
124
+ const collectableHashes = [...new Set(releasedHashes)].filter((hash) => !retainedHashSet.has(hash));
125
+ if (collectableHashes.length > 0) await objectStore.delete(collectableHashes);
126
+ return collectableHashes;
127
+ }),
128
+ read: (hash) => getResultAsync(async () => {
129
+ const storedObject = await readStoredObject(hash);
130
+ if (!storedObject) throw new ObjectNotStoredError(hash, "object is not stored");
131
+ return storedObject.plaintext;
132
+ }),
133
+ write: (plaintext, anchor) => getResultAsync(async () => {
134
+ const hash = getContentAddress(plaintext);
135
+ const plaintextBytes = plaintext.byteLength;
136
+ const adoptStored = (baseHash) => ({
137
+ baseHash,
138
+ hash,
139
+ isDeduplicated: true,
140
+ plaintextBytes,
141
+ storedBytes: 0
142
+ });
143
+ const storedObject = await readStoredObject(hash);
144
+ if (storedObject) return adoptStored(storedObject.baseHash);
145
+ const writeObject = async (bytes, baseHash) => {
146
+ if (await objectStore.write(hash, bytes)) return {
147
+ baseHash,
148
+ hash,
149
+ isDeduplicated: false,
150
+ plaintextBytes,
151
+ storedBytes: bytes.byteLength
152
+ };
153
+ const twinObject = await readStoredObject(hash);
154
+ if (!twinObject) throw new InvalidOperationError(Operation.Create, hash, "refused as already stored, but nothing is stored");
155
+ return adoptStored(twinObject.baseHash);
156
+ };
157
+ const encodeDelta = async () => {
158
+ const keyframe = await readKeyframe(anchor.hash);
159
+ if (!keyframe) return void 0;
160
+ return {
161
+ bytes: await encodeObject(plaintext, compressionLevel, {
162
+ hash: anchor.hash,
163
+ plaintext: keyframe.plaintext
164
+ }),
165
+ keyframeStoredBytes: keyframe.storedBytes
166
+ };
167
+ };
168
+ const keyframeEncoding = encodeObject(plaintext, compressionLevel);
169
+ const deltaEncoding = anchor.hash ? encodeDelta() : void 0;
170
+ const [keyframeBytes, delta] = await Promise.all([keyframeEncoding, deltaEncoding]);
171
+ if (!delta) return writeObject(keyframeBytes, "");
172
+ const isWithinPromotionRatio = delta.bytes.byteLength <= keyframeBytes.byteLength * promotionRatio;
173
+ const isWithinSegmentBudget = anchor.anchoredBytes + delta.bytes.byteLength <= delta.keyframeStoredBytes * segmentBudgetRatio;
174
+ if (!isWithinPromotionRatio || !isWithinSegmentBudget) return writeObject(keyframeBytes, "");
175
+ return writeObject(delta.bytes, anchor.hash);
176
+ })
177
+ };
178
+ };
179
+ //#endregion
180
+ export { DEFAULT_COMPRESSION_LEVEL, DEFAULT_PROMOTION_RATIO, DEFAULT_SEGMENT_BUDGET_RATIO, DELTA_FLAG, DELTA_HEADER_BYTE_COUNT, HASH_BYTE_COUNT, KEYFRAME_FLAG, MAX_WINDOW_LOG, MIN_WINDOW_LOG, OBJECT_FLAGS_OFFSET, OBJECT_FORMAT_VERSION, OBJECT_HEADER_BYTE_COUNT, OBJECT_MAGIC, OBJECT_VERSION_OFFSET, OBJECT_WINDOW_LOG_OFFSET, ObjectNotStoredError, createKeyframeStore, decodeObject, encodeObject, getContentAddress, getWindowLog, parseObject };
package/package.json ADDED
@@ -0,0 +1,69 @@
1
+ {
2
+ "name": "keyframe-store",
3
+ "version": "3.2.0",
4
+ "description": "Content-addressed version storage — every version is a zstd keyframe or a delta against one, over any backend that can store bytes by key.",
5
+ "keywords": [
6
+ "compression",
7
+ "content-addressed",
8
+ "deduplication",
9
+ "delta",
10
+ "history",
11
+ "keyframe",
12
+ "node",
13
+ "storage",
14
+ "typescript",
15
+ "version",
16
+ "zstd"
17
+ ],
18
+ "homepage": "https://github.com/Esposter/Esposter/blob/main/packages/keyframe-store#readme",
19
+ "bugs": {
20
+ "url": "https://github.com/Esposter/Esposter/issues"
21
+ },
22
+ "license": "Apache-2.0",
23
+ "author": "Jimmy Chen",
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/Esposter/Esposter.git"
27
+ },
28
+ "files": [
29
+ "dist"
30
+ ],
31
+ "type": "module",
32
+ "sideEffects": false,
33
+ "types": "dist/index.d.ts",
34
+ "imports": {
35
+ "#src/*": "./src/*.ts"
36
+ },
37
+ "exports": {
38
+ ".": "./dist/index.js",
39
+ "./package.json": "./package.json"
40
+ },
41
+ "publishConfig": {
42
+ "access": "public"
43
+ },
44
+ "scripts": {
45
+ "bench": "vitest bench --run",
46
+ "build": "tsdown",
47
+ "export:gen": "generate-exports",
48
+ "format": "oxfmt",
49
+ "format:check": "oxfmt --check",
50
+ "lint": "eslint .",
51
+ "lint:fix": "eslint --fix .",
52
+ "test": "vitest",
53
+ "typecheck": "tsc"
54
+ },
55
+ "dependencies": {
56
+ "@esposter/shared": "3.2.0",
57
+ "neverthrow": "^8.2.0"
58
+ },
59
+ "devDependencies": {
60
+ "@arethetypeswrong/core": "^0.18.5",
61
+ "@esposter/configuration": "3.2.0",
62
+ "@esposter/shared-node": "3.2.0",
63
+ "@types/node": "^26.6.1",
64
+ "publint": "^0.3.24",
65
+ "tsdown": "^0.23.0",
66
+ "vitest": "^5.0.1"
67
+ },
68
+ "gitHead": "bc055ed2f154eff219a355016a6b586962dbfa9c"
69
+ }