@harperfast/rocksdb-js 2.2.0 → 2.4.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/dist/index.mjs CHANGED
@@ -1,9 +1,9 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { execSync } from "node:child_process";
3
- import { closeSync, openSync, readFileSync, readSync, readdirSync, statSync } from "node:fs";
3
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, statSync } from "node:fs";
4
4
  import { dirname, join, resolve } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
- import { mkdir } from "node:fs/promises";
6
+ import { access, cp, mkdir, readdir, rm } from "node:fs/promises";
7
7
  import * as orderedBinary from "ordered-binary";
8
8
  import { ExtendedIterable } from "@harperfast/extended-iterable";
9
9
  import { Encoder } from "msgpackr";
@@ -89,6 +89,21 @@ const coolTransactionLogs = binding.coolTransactionLogs;
89
89
  * the underlying mapping rather than leaving it retained.
90
90
  */
91
91
  const transactionLogMapCount = binding.transactionLogMapCount;
92
+ /**
93
+ * Creates a native file lock using the specified file path (`flock` on POSIX,
94
+ * `LockFileEx` on Windows). Returns an opaque non-zero token to pass to
95
+ * `fileLockRelease`, or `0` if another holder — in any process, container, or
96
+ * worker thread — currently has it. Throws if `file` is missing or on a hard
97
+ * error. The OS handle is owned entirely in native code (no fd crosses into
98
+ * JS), and the kernel releases the lock when the handle closes, including on
99
+ * process death.
100
+ */
101
+ const tryFileLock = binding.tryFileLock;
102
+ /**
103
+ * Releases a file lock acquired via `tryFileLock`. A no-op for
104
+ * token `0` or an unknown token.
105
+ */
106
+ const fileLockRelease = binding.fileLockRelease;
92
107
  const nativeBackupRestore = binding.backupRestore;
93
108
  const nativeBackupList = binding.backupList;
94
109
  const nativeBackupDelete = binding.backupDelete;
@@ -99,6 +114,126 @@ const version = binding.version;
99
114
 
100
115
  //#endregion
101
116
  //#region src/backup.ts
117
+ /** Subdirectory (under a backup directory) holding per-backup transaction log snapshots. */
118
+ const TRANSACTION_LOGS_DIRNAME = "transaction_logs";
119
+ /** Non-blocking existence check (`fs.existsSync` would block the event loop). */
120
+ async function exists(path) {
121
+ try {
122
+ await access(path);
123
+ return true;
124
+ } catch {
125
+ return false;
126
+ }
127
+ }
128
+ /**
129
+ * Runs `fn` while holding a native file lock for `backupDir`, releasing it when
130
+ * `fn` settles. Used by the writable-engine operations `backups.delete` and
131
+ * `backups.purge`; backup creation (`Store.backup`) takes the same lock on the
132
+ * same file natively inside `Database::Backup` (see `runCreateBackup` in
133
+ * `src/binding/database/backup.cpp`), where the backup directory is also
134
+ * created. Throws immediately (without running `fn`) if another writer holds
135
+ * the directory lock.
136
+ *
137
+ * Read-only operations (`list`, `verify`, and a restore's source read) use
138
+ * `BackupEngineReadOnly` and are not locked: concurrent readers are safe.
139
+ * Running a reader concurrently with a `delete`/`purge` on the same directory is
140
+ * a caller-managed hazard, matching RocksDB's one-writable-engine-per-dir model.
141
+ *
142
+ * RocksDB only serializes work within a single `BackupEngine` instance and has
143
+ * no lock on the backup directory itself. Two writable engines — in any
144
+ * processes — creating/deleting/purging backups in the same directory
145
+ * concurrently race on the per-backup staging directory and both fail,
146
+ * potentially leaving the directory with no usable backup. An in-memory lock
147
+ * cannot prevent this across processes, so the lock lives on disk: a kernel
148
+ * advisory lock (`flock` on POSIX, `LockFileEx` on Windows) held on a
149
+ * `.backup.lock` file at the directory root.
150
+ *
151
+ * The lock is taken entirely in native code (`tryFileLock`), which opens,
152
+ * locks, and later closes the file's OS handle without ever exposing a
153
+ * descriptor to JS — the addon statically links its own C runtime, so a
154
+ * Node/libuv fd is not usable across that boundary. The kernel owning the lock
155
+ * buys two properties a pidfile cannot:
156
+ *
157
+ * - No staleness heuristic. The lock is released when the holder's handle closes
158
+ * — normal release, crash, `kill -9`, container exit — so there is nothing to
159
+ * reclaim and no liveness check.
160
+ * - True cross-context exclusion. The lock conflicts across processes, containers
161
+ * sharing a volume (same kernel), and `worker_threads`.
162
+ *
163
+ * The lock file is never deleted, only locked and unlocked; an unlocked, empty
164
+ * `.backup.lock` at the directory root is the steady state.
165
+ */
166
+ async function withBackupDirLock(backupDir, fn) {
167
+ const token = tryFileLock(join(backupDir, ".backup.lock"));
168
+ if (token === 0) throw new Error(`Backup directory is locked: ${backupDir}`);
169
+ try {
170
+ return await fn();
171
+ } finally {
172
+ fileLockRelease(token);
173
+ }
174
+ }
175
+ /**
176
+ * Removes `<backupDir>/transaction_logs/<id>` subtrees whose backup id no longer
177
+ * corresponds to a surviving backup. Called after a `purge` (which holds the
178
+ * backup-dir lock); a no-op when no transaction logs were backed up. Self-healing:
179
+ * it drops every log subtree without a live backup. Note the surviving set comes
180
+ * from `nativeBackupList`, which omits corrupt backups — a still-present but
181
+ * corrupt backup's logs may be pruned (acceptable: it cannot be restored anyway).
182
+ * This also sweeps `.staging-*` leftovers from a crashed backup process (a
183
+ * staging name never matches a live backup id); backup creation sweeps them
184
+ * natively as well, under the backup-dir lock.
185
+ */
186
+ async function pruneOrphanedTransactionLogs(backupDir) {
187
+ const logsRoot = join(backupDir, TRANSACTION_LOGS_DIRNAME);
188
+ let ids;
189
+ try {
190
+ ids = await readdir(logsRoot);
191
+ } catch (err) {
192
+ if (err.code === "ENOENT") return;
193
+ throw err;
194
+ }
195
+ const list = await new Promise((resolve, reject) => nativeBackupList(resolve, reject, backupDir));
196
+ const surviving = new Set(list.map((info) => String(info.backupId)));
197
+ await Promise.all(ids.filter((id) => !surviving.has(id)).map((id) => rm(join(logsRoot, id), {
198
+ recursive: true,
199
+ force: true
200
+ })));
201
+ }
202
+ /**
203
+ * Restores the transaction log snapshot for the restored backup into
204
+ * `<dbDir>/transaction_logs/`, wiping the destination first so that restoring an
205
+ * older backup over a newer one cannot leave stale (newer) log files behind.
206
+ *
207
+ * Only acts when THIS backup actually captured logs: if the restored id has no
208
+ * snapshot, the destination is left untouched. Wiping unconditionally would
209
+ * destroy on-disk logs that a mixed-mode (`transactionLogs:false`) backup never
210
+ * managed.
211
+ *
212
+ * Offline only: the files are picked up when the database is next opened. mtimes
213
+ * are preserved because the store derives file age (rotation/retention) from
214
+ * mtime — a fresh mtime would break retention.
215
+ */
216
+ async function restoreTransactionLogs(backupDir, dbDir, backupId) {
217
+ const logsRoot = join(backupDir, TRANSACTION_LOGS_DIRNAME);
218
+ if (!await exists(logsRoot)) return;
219
+ let id = backupId;
220
+ if (id === void 0) {
221
+ const list = await new Promise((resolve, reject) => nativeBackupList(resolve, reject, backupDir));
222
+ if (list.length === 0) return;
223
+ id = Math.max(...list.map((info) => info.backupId));
224
+ }
225
+ const logsSrc = join(logsRoot, String(id));
226
+ if (!await exists(logsSrc)) return;
227
+ const logsDest = join(dbDir, TRANSACTION_LOGS_DIRNAME);
228
+ await rm(logsDest, {
229
+ recursive: true,
230
+ force: true
231
+ });
232
+ await cp(logsSrc, logsDest, {
233
+ recursive: true,
234
+ preserveTimestamps: true
235
+ });
236
+ }
102
237
  /**
103
238
  * Backup management operations that act on a backup directory and do not
104
239
  * require an open database. To create a backup, use the `db.backup()` instance
@@ -124,11 +259,12 @@ const backups = {
124
259
  const walDir = options?.walDir ?? dbDir;
125
260
  await mkdir(dbDir, { recursive: true });
126
261
  if (walDir !== dbDir) await mkdir(walDir, { recursive: true });
127
- return new Promise((resolve, reject) => nativeBackupRestore(resolve, reject, backupDir, dbDir, walDir, {
262
+ await new Promise((resolve, reject) => nativeBackupRestore(resolve, reject, backupDir, dbDir, walDir, {
128
263
  backupId: options?.backupId,
129
264
  keepLogFiles: options?.keepLogFiles,
130
265
  mode: options?.mode
131
266
  }));
267
+ await restoreTransactionLogs(backupDir, dbDir, options?.backupId);
132
268
  },
133
269
  /**
134
270
  * Lists the non-corrupt backups in a backup directory, ordered by id.
@@ -140,14 +276,27 @@ const backups = {
140
276
  * Deletes a specific backup. Shared files are reference-counted and only
141
277
  * removed once no remaining backup references them.
142
278
  */
143
- delete(backupDir, backupId) {
144
- return new Promise((resolve, reject) => nativeBackupDelete(resolve, reject, backupDir, backupId));
279
+ async delete(backupDir, backupId) {
280
+ return withBackupDirLock(backupDir, async () => {
281
+ await new Promise((resolve, reject) => nativeBackupDelete(resolve, reject, backupDir, backupId));
282
+ try {
283
+ await rm(join(backupDir, TRANSACTION_LOGS_DIRNAME, String(backupId)), {
284
+ recursive: true,
285
+ force: true
286
+ });
287
+ } catch {}
288
+ });
145
289
  },
146
290
  /**
147
291
  * Deletes all but the newest `keepCount` backups.
148
292
  */
149
- purge(backupDir, keepCount) {
150
- return new Promise((resolve, reject) => nativeBackupPurge(resolve, reject, backupDir, keepCount));
293
+ async purge(backupDir, keepCount) {
294
+ return withBackupDirLock(backupDir, async () => {
295
+ await new Promise((resolve, reject) => nativeBackupPurge(resolve, reject, backupDir, keepCount));
296
+ try {
297
+ await pruneOrphanedTransactionLogs(backupDir);
298
+ } catch {}
299
+ });
151
300
  },
152
301
  /**
153
302
  * Verifies a backup's file sizes, and optionally their checksums (which
@@ -518,6 +667,258 @@ var DBI = class DBI {
518
667
  }
519
668
  };
520
669
 
670
+ //#endregion
671
+ //#region src/tar.ts
672
+ /**
673
+ * A minimal, dependency-free streaming USTAR (POSIX tar) encoder.
674
+ *
675
+ * Built for streaming whole-database backups: the set of live RocksDB files
676
+ * (SSTs, blobs, MANIFEST, CURRENT, OPTIONS, WAL) is serialized into a single
677
+ * tar byte stream that can be piped to any destination and unpacked with
678
+ * standard tools (`tar -xf`). The encoder never buffers a whole file — each
679
+ * entry's payload is streamed through in chunks — so peak memory stays flat
680
+ * regardless of database size.
681
+ *
682
+ * Backpressure is the caller's lever: every method `await`s the {@link TarSink},
683
+ * so wiring the sink to a stream writer's `write()` naturally paces production
684
+ * to the consumer.
685
+ *
686
+ * Only what a RocksDB backup needs is implemented: regular files. Paths longer
687
+ * than USTAR's 100-byte `name` field are split across the `name` and `prefix`
688
+ * fields (~255 bytes total), which covers `transaction_logs/<store>/<file>`
689
+ * entries; GNU/pax long-name extensions are not implemented, so a path that
690
+ * still doesn't fit throws rather than being silently truncated. File sizes
691
+ * larger than the octal `size` field can hold (~8 GiB) fall back to the GNU
692
+ * base-256 encoding.
693
+ */
694
+ /** Size of a tar block. Every header and the archive length are multiples of this. */
695
+ const BLOCK_SIZE = 512;
696
+ /** Maximum bytes for the USTAR `name` field. */
697
+ const MAX_NAME_LENGTH = 100;
698
+ /** Maximum bytes for the USTAR `prefix` field (holds the leading directories). */
699
+ const MAX_PREFIX_LENGTH = 155;
700
+ const textEncoder = new TextEncoder();
701
+ const textDecoder = new TextDecoder();
702
+ /**
703
+ * Writes a UTF-8 string into a fixed-width header field, left-justified and
704
+ * NUL-padded (the block is already zero-filled, so nothing else is needed).
705
+ * Throws if the encoded value does not fit — tar fields are silently lossy
706
+ * otherwise, which corrupts the archive.
707
+ */
708
+ function writeField(block, value, offset, length) {
709
+ const bytes = textEncoder.encode(value);
710
+ if (bytes.length > length) throw new RangeError(`tar field value ${JSON.stringify(value)} exceeds ${length} bytes`);
711
+ block.set(bytes, offset);
712
+ }
713
+ /**
714
+ * Writes a non-negative integer as a NUL-terminated, zero-padded octal string
715
+ * into a `length`-byte field (so `length - 1` octal digits). Values too large
716
+ * for octal fall back to the GNU base-256 extension, where the high bit of the
717
+ * first byte is set and the magnitude is stored big-endian in the remainder.
718
+ */
719
+ function writeOctal(block, value, offset, length) {
720
+ const digits = length - 1;
721
+ if (value > 8 ** digits - 1) {
722
+ let v = value;
723
+ for (let i = offset + length - 1; i > offset; i--) {
724
+ block[i] = v & 255;
725
+ v = Math.floor(v / 256);
726
+ }
727
+ block[offset] = 128;
728
+ return;
729
+ }
730
+ const str = value.toString(8).padStart(digits, "0");
731
+ for (let i = 0; i < digits; i++) block[offset + i] = str.charCodeAt(i);
732
+ }
733
+ /**
734
+ * Computes and writes the USTAR header checksum: the unsigned sum of all 512
735
+ * header bytes with the checksum field itself taken as ASCII spaces. Stored as
736
+ * six octal digits, a NUL, then a space (the conventional encoding).
737
+ */
738
+ function writeChecksum(block) {
739
+ for (let i = 148; i < 156; i++) block[i] = 32;
740
+ let sum = 0;
741
+ for (let i = 0; i < BLOCK_SIZE; i++) sum += block[i];
742
+ const str = sum.toString(8).padStart(6, "0");
743
+ for (let i = 0; i < 6; i++) block[148 + i] = str.charCodeAt(i);
744
+ block[154] = 0;
745
+ block[155] = 32;
746
+ }
747
+ /**
748
+ * Splits a path into USTAR `name` (<=100 bytes) and `prefix` (<=155 bytes)
749
+ * fields at a `/` boundary; a reader rejoins them as `prefix + "/" + name`.
750
+ * Returns an empty prefix when the whole path fits in `name`. Throws when the
751
+ * path cannot be represented — a trailing component over 100 bytes, or leading
752
+ * directories that don't fit in 155. RocksDB and transaction-log filenames never
753
+ * hit this; only a pathological log-store name would.
754
+ */
755
+ function splitTarName(path) {
756
+ const encoded = textEncoder.encode(path);
757
+ if (encoded.length <= MAX_NAME_LENGTH) return {
758
+ name: path,
759
+ prefix: ""
760
+ };
761
+ let best = -1;
762
+ for (let i = 0; i < encoded.length; i++) {
763
+ if (encoded[i] !== 47) continue;
764
+ const prefixLength = i;
765
+ const nameLength = encoded.length - i - 1;
766
+ if (nameLength > 0 && nameLength <= MAX_NAME_LENGTH && prefixLength <= MAX_PREFIX_LENGTH) best = i;
767
+ }
768
+ if (best === -1) throw new RangeError(`tar entry name ${JSON.stringify(path)} does not fit the USTAR name (<=${MAX_NAME_LENGTH}) + prefix (<=${MAX_PREFIX_LENGTH}) fields`);
769
+ return {
770
+ name: textDecoder.decode(encoded.subarray(best + 1)),
771
+ prefix: textDecoder.decode(encoded.subarray(0, best))
772
+ };
773
+ }
774
+ /**
775
+ * Builds a single 512-byte USTAR header block for a regular file. Long paths are
776
+ * split across the `name` and `prefix` fields (see {@link splitTarName}).
777
+ */
778
+ function buildHeader(name, size, mode, mtime) {
779
+ const block = new Uint8Array(BLOCK_SIZE);
780
+ const split = splitTarName(name);
781
+ writeField(block, split.name, 0, MAX_NAME_LENGTH);
782
+ writeOctal(block, mode & 4095, 100, 8);
783
+ writeOctal(block, 0, 108, 8);
784
+ writeOctal(block, 0, 116, 8);
785
+ writeOctal(block, size, 124, 12);
786
+ writeOctal(block, Math.floor(mtime), 136, 12);
787
+ block[156] = 48;
788
+ writeField(block, "ustar", 257, 6);
789
+ block[263] = 48;
790
+ block[264] = 48;
791
+ if (split.prefix.length > 0) writeField(block, split.prefix, 345, MAX_PREFIX_LENGTH);
792
+ writeChecksum(block);
793
+ return block;
794
+ }
795
+ /**
796
+ * Streaming USTAR encoder. Usage is a strict sequence per file —
797
+ * {@link TarEncoder.addFile} once, then {@link TarEncoder.writeData} until the
798
+ * declared size is reached — followed by a single {@link TarEncoder.finalize}:
799
+ *
800
+ * ```ts
801
+ * const tar = new TarEncoder((chunk) => writer.write(chunk));
802
+ * await tar.addFile('CURRENT', current.length);
803
+ * await tar.writeData(current);
804
+ * await tar.addFile('000123.sst', sstSize);
805
+ * for await (const chunk of sstChunks) await tar.writeData(chunk);
806
+ * await tar.finalize();
807
+ * ```
808
+ *
809
+ * The size passed to `addFile` is authoritative: tar records it in the header
810
+ * before any payload, so it must be known up front (it is — RocksDB's
811
+ * `GetLiveFilesStorageInfo` returns each file's exact size). Writing more or
812
+ * fewer bytes than declared throws.
813
+ */
814
+ var TarEncoder = class {
815
+ #sink;
816
+ /** Payload bytes still expected for the current entry. */
817
+ #remaining = 0;
818
+ /** Zero-padding bytes owed after the current entry's payload reaches a block boundary. */
819
+ #pad = 0;
820
+ #finalized = false;
821
+ constructor(sink) {
822
+ this.#sink = sink;
823
+ }
824
+ /**
825
+ * Emits the header for a new file entry. Must be preceded by completing any
826
+ * prior entry's payload. After this, exactly `size` bytes must be supplied
827
+ * via {@link TarEncoder.writeData} before the next `addFile` or `finalize`.
828
+ */
829
+ async addFile(name, size, options) {
830
+ if (this.#finalized) throw new Error("TarEncoder already finalized");
831
+ if (this.#remaining !== 0) throw new Error(`previous tar entry incomplete: ${this.#remaining} byte(s) unwritten`);
832
+ if (!Number.isInteger(size) || size < 0) throw new RangeError("tar entry size must be a non-negative integer");
833
+ const header = buildHeader(name, size, options?.mode ?? 420, options?.mtime ?? 0);
834
+ this.#remaining = size;
835
+ this.#pad = (BLOCK_SIZE - size % BLOCK_SIZE) % BLOCK_SIZE;
836
+ await this.#sink(header);
837
+ }
838
+ /**
839
+ * Streams a chunk of the current entry's payload. Chunks may be any size; the
840
+ * total across all `writeData` calls for an entry must equal the size passed
841
+ * to {@link TarEncoder.addFile}. Block padding is emitted automatically once
842
+ * the final byte of an entry is written.
843
+ */
844
+ async writeData(chunk) {
845
+ if (this.#finalized) throw new Error("TarEncoder already finalized");
846
+ if (chunk.length === 0) return;
847
+ if (chunk.length > this.#remaining) throw new RangeError(`tar data overruns entry size by ${chunk.length - this.#remaining} byte(s)`);
848
+ this.#remaining -= chunk.length;
849
+ await this.#sink(chunk);
850
+ if (this.#remaining === 0 && this.#pad > 0) {
851
+ const pad = this.#pad;
852
+ this.#pad = 0;
853
+ await this.#sink(new Uint8Array(pad));
854
+ }
855
+ }
856
+ /**
857
+ * Convenience for an entry whose contents are already fully in memory (e.g.
858
+ * the small `CURRENT`/`OPTIONS` files RocksDB returns inline).
859
+ */
860
+ async addFileData(name, data, options) {
861
+ await this.addFile(name, data.length, options);
862
+ await this.writeData(data);
863
+ }
864
+ /**
865
+ * Writes the two zero-filled blocks that mark end-of-archive. The encoder is
866
+ * unusable afterward. Throws if the current entry is not fully written, so a
867
+ * truncated stream cannot be silently finalized into a valid-looking archive.
868
+ */
869
+ async finalize() {
870
+ if (this.#finalized) throw new Error("TarEncoder already finalized");
871
+ if (this.#remaining !== 0) throw new Error(`cannot finalize: current tar entry has ${this.#remaining} byte(s) unwritten`);
872
+ this.#finalized = true;
873
+ await this.#sink(new Uint8Array(BLOCK_SIZE * 2));
874
+ }
875
+ };
876
+
877
+ //#endregion
878
+ //#region src/backup-stream.ts
879
+ /** Native event discriminator: a new file header (vs. a payload chunk). */
880
+ const EVENT_FILE = 0;
881
+ /**
882
+ * Streams a consistent snapshot of the database to a `WritableStream` as a tar
883
+ * archive, with no intermediate copy on disk. The set of live RocksDB files is
884
+ * enumerated and read natively; each file header and payload chunk is framed
885
+ * into the {@link TarEncoder} here in JS and written to `stream`.
886
+ *
887
+ * Backpressure flows end to end: the encoder awaits each `writer.write()`, and
888
+ * the native producer awaits each `emit()` before reading the next chunk, so a
889
+ * slow consumer paces the entire pipeline rather than buffering in memory.
890
+ *
891
+ * The resulting archive can be unpacked with any tar tool (`tar -xf`) into a
892
+ * directory that opens directly as a RocksDB database.
893
+ */
894
+ async function backupToStream(db, stream, options) {
895
+ let tarDestination;
896
+ let piped;
897
+ if (options?.gzip) {
898
+ const gzip = new CompressionStream("gzip");
899
+ piped = gzip.readable.pipeTo(stream);
900
+ tarDestination = gzip.writable;
901
+ } else tarDestination = stream;
902
+ const writer = tarDestination.getWriter();
903
+ const tar = new TarEncoder((chunk) => writer.write(chunk));
904
+ const emit = async (kind, data, size, mtime) => {
905
+ if (kind === EVENT_FILE) await tar.addFile(data, size, { mtime });
906
+ else await tar.writeData(data);
907
+ };
908
+ try {
909
+ await new Promise((resolve, reject) => {
910
+ db.backupStream(resolve, reject, emit, options);
911
+ });
912
+ await tar.finalize();
913
+ await writer.close();
914
+ if (piped) await piped;
915
+ } catch (err) {
916
+ await writer.abort(err).catch(() => {});
917
+ if (piped) await piped.catch(() => {});
918
+ throw err;
919
+ }
920
+ }
921
+
521
922
  //#endregion
522
923
  //#region src/dbi-iterator.ts
523
924
  const { ITERATOR_RESULT_DONE, ITERATOR_RESULT_FAST } = constants;
@@ -900,19 +1301,9 @@ var Store = class {
900
1301
  }
901
1302
  return new Promise((resolve, reject) => this.db.compact(resolve, reject, startBuffer, endBuffer));
902
1303
  }
903
- /**
904
- * Creates a backup of the entire database (all column families) into the
905
- * given directory and resolves with the new backup id. Parent directories
906
- * are created as needed. See `backups` for restore and management.
907
- *
908
- * @example
909
- * ```typescript
910
- * const id = await db.backup('/path/to/backups');
911
- * ```
912
- */
913
- async backup(backupDir, options) {
914
- await mkdir(backupDir, { recursive: true });
915
- return new Promise((resolve, reject) => this.db.backup(resolve, reject, backupDir, options));
1304
+ async backup(target, options) {
1305
+ if (typeof target !== "string" && typeof target?.getWriter === "function") return backupToStream(this.db, target, options);
1306
+ return new Promise((resolve, reject) => this.db.backup(resolve, reject, target, options));
916
1307
  }
917
1308
  /**
918
1309
  * Compacts the entire key range of the database synchronously.
@@ -1481,25 +1872,43 @@ var RocksDatabase = class RocksDatabase extends DBI {
1481
1872
  compact(options) {
1482
1873
  return this.store.compact(options);
1483
1874
  }
1875
+ backup(target, options) {
1876
+ if (typeof target === "string") return this.store.backup(target, options);
1877
+ return this.store.backup(target, options);
1878
+ }
1484
1879
  /**
1485
- * Creates a backup of the entire database (all column families) into the
1486
- * given directory, creating parent directories as needed, and resolves with
1487
- * the new backup id. Use the `backups` namespace to restore, list, delete,
1488
- * purge, or verify backups.
1880
+ * Creates a hardlinked, point-in-time, fully independent copy of the entire
1881
+ * database (all column families) at `targetPath` and resolves once written.
1489
1882
  *
1490
- * When the database was opened with `disableWAL`, the memtable is flushed
1491
- * before the backup by default so unflushed data is not lost.
1883
+ * Unlike a backup, a checkpoint is a normal, writable sibling database: open
1884
+ * it with {@link RocksDatabase.open} and it diverges independently from the
1885
+ * source. SST and blob files are hardlinked when `targetPath` is on the same
1886
+ * filesystem as the database and copied otherwise (other files such as the
1887
+ * MANIFEST are always copied), so the operation is near-instant on the same
1888
+ * filesystem. The memtable is flushed so the checkpoint includes the latest
1889
+ * writes even when the WAL is disabled.
1890
+ *
1891
+ * Parent directories are created as needed. `targetPath` itself must not
1892
+ * already exist (RocksDB creates the checkpoint directory) and rejects with
1893
+ * `Create checkpoint failed: target path exists` if it does. The caller is
1894
+ * responsible for eventual cleanup of the directory.
1492
1895
  *
1493
1896
  * @example
1494
1897
  * ```typescript
1495
- * import { backups } from '@harperfast/rocksdb-js';
1496
- *
1497
1898
  * const db = RocksDatabase.open('/path/to/database');
1498
- * const id = await db.backup('/path/to/backups');
1899
+ * await db.createCheckpoint('/path/to/checkpoint');
1900
+ * const branch = RocksDatabase.open('/path/to/checkpoint');
1499
1901
  * ```
1500
1902
  */
1501
- backup(backupDir, options) {
1502
- return this.store.backup(backupDir, options);
1903
+ createCheckpoint(targetPath) {
1904
+ return new Promise((resolve, reject) => {
1905
+ if (existsSync(targetPath)) {
1906
+ reject(/* @__PURE__ */ new Error("Create checkpoint failed: target path exists"));
1907
+ return;
1908
+ }
1909
+ mkdirSync(dirname(targetPath), { recursive: true });
1910
+ this.store.db.createCheckpoint(resolve, reject, targetPath);
1911
+ });
1503
1912
  }
1504
1913
  /**
1505
1914
  * Compacts the entire key range of the database synchronously.
@@ -2350,9 +2759,9 @@ function loadLastPosition(transactionLog, readUncommitted) {
2350
2759
  //#region src/index.ts
2351
2760
  const versions = {
2352
2761
  rocksdb: version,
2353
- "rocksdb-js": "2.2.0"
2762
+ "rocksdb-js": "2.4.0"
2354
2763
  };
2355
2764
 
2356
2765
  //#endregion
2357
- export { DBI, DBIterator, RocksDatabase, Store, Transaction, TransactionLog, backups, constants, coolTransactionLogs, currentThreadId, parseTransactionLog, registryStatus, shutdown, stats, versions };
2766
+ export { DBI, DBIterator, RocksDatabase, Store, Transaction, TransactionLog, backups, constants, coolTransactionLogs, currentThreadId, fileLockRelease, parseTransactionLog, registryStatus, shutdown, stats, tryFileLock, versions };
2358
2767
  //# sourceMappingURL=index.mjs.map