@duraxis/storage-disk 0.0.0-stage → 0.1.1

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 ADDED
@@ -0,0 +1,10 @@
1
+ # @duraxis/storage-disk changelog
2
+
3
+ ## 0.1.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 0b272bd: Improve disk storage ownership recovery and NestJS lifecycle management to safely handle abandoned locks and application restarts
8
+
9
+ This file is maintained by Changesets. Future releases will add versioned
10
+ entries automatically.
package/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2026 João Paulo Dias
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
+ PERFORMANCE OF THIS SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,171 @@
1
- # Temporary Holding Version
1
+ # @duraxis/storage-disk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Asynchronous local-filesystem `StorageDriver` for Duraxis. It persists immutable object payloads
4
+ and a checksummed journal while holding exclusive ownership of the database directory.
5
+
6
+ ## Installation
7
+
8
+ ```bash
9
+ pnpm add @duraxis/storage-disk
10
+ npm install @duraxis/storage-disk
11
+ yarn add @duraxis/storage-disk
12
+ ```
13
+
14
+ Node.js 22.12 or newer is required.
15
+
16
+ ## Basic use
17
+
18
+ ```ts
19
+ import { AsyncDiskStorageDriver } from "@duraxis/storage-disk";
20
+
21
+ const storage = await AsyncDiskStorageDriver.open({ directory: "./data/duraxis" });
22
+ try {
23
+ await storage.put("example", new TextEncoder().encode("value"), {
24
+ condition: { type: "if-absent" },
25
+ });
26
+ } finally {
27
+ await storage.close();
28
+ }
29
+ ```
30
+
31
+ The package exports `AsyncDiskStorageDriver`, its options and durability types, and the
32
+ `OwnershipRecoveryOptions` and `RecoverOwnershipOptions` types. It implements the contract from
33
+ `@duraxis/storage` and is normally consumed through `@duraxis/core`, `@duraxis/orm`, or
34
+ `@duraxis/nestjs`.
35
+
36
+ ## Exclusive directory ownership
37
+
38
+ Opening a driver atomically creates `.duraxis-owner.lock`. A second driver cannot begin journal
39
+ recovery or database operations while that lock exists. A unique per-process owner token prevents
40
+ `close()` and failed-initialization cleanup from deleting a replacement lock. Repeated or
41
+ concurrent `close()` calls share the same shutdown attempt and only the current owner may release
42
+ the lock.
43
+
44
+ All participating acquire, recovery, and release operations are serialized by an exclusively
45
+ created `.duraxis-owner.recovery` guard. The guard is checked by file identity, token, checksum,
46
+ and exact contents before it is removed. Duraxis never guesses that an existing guard is stale:
47
+ an interrupted guard operation therefore requires operator investigation.
48
+
49
+ Ownership metadata format 2 records the owner token, PID, hostname, application identity, Linux
50
+ PID namespace, creation time, and checksum. Older format-1 locks remain compatible with explicit
51
+ manual recovery, but are never reclaimed automatically because they do not contain sufficient
52
+ process identity.
53
+
54
+ ## Recovery modes
55
+
56
+ The default remains conservative and backward-compatible:
57
+
58
+ ```ts
59
+ await AsyncDiskStorageDriver.open({
60
+ directory: "./data/duraxis",
61
+ ownershipRecovery: { mode: "manual" }, // also the default when omitted
62
+ });
63
+ ```
64
+
65
+ After an unexpected termination, manual recovery requires an operational check that no process
66
+ can still use the directory:
67
+
68
+ ```ts
69
+ await AsyncDiskStorageDriver.recoverAbandonedOwnership({
70
+ directory: "./data/duraxis",
71
+ confirmation: "I_HAVE_VERIFIED_EXCLUSIVE_ACCESS",
72
+ });
73
+ ```
74
+
75
+ The confirmation is deliberately explicit; the method does not prove that the old process is
76
+ dead. Stop all application replicas and inspect the host before using it. Recovery only removes
77
+ ownership metadata. It does not erase objects, reset the journal, or truncate committed data.
78
+ Normal journal recovery runs after the replacement owner has acquired the directory.
79
+
80
+ For a supported local Linux deployment, conservative automatic recovery can be enabled:
81
+
82
+ ```ts
83
+ const storage = await AsyncDiskStorageDriver.open({
84
+ directory: "/var/lib/my-service/duraxis",
85
+ ownershipRecovery: {
86
+ mode: "dead-process",
87
+ applicationId: "com.example.my-service",
88
+ },
89
+ });
90
+ ```
91
+
92
+ Use one stable `applicationId` for the application across restarts. It must be 1-128 characters
93
+ using letters, digits, `.`, `_`, `:`, `/`, or `-`; it is an identifier, not a secret. Matching
94
+ application IDs never prove owner death by themselves.
95
+
96
+ Automatic recovery occurs only when all of these checks succeed:
97
+
98
+ - the lock is valid format 2 and its checksum and required fields are valid;
99
+ - application ID, hostname, and Linux PID namespace exactly match the current process;
100
+ - the directory is on an explicitly recognized local filesystem;
101
+ - `process.kill(recordedPid, 0)` reports `ESRCH` in that same process namespace; and
102
+ - the recovery guard is acquired and the observed lock remains byte-for-byte and inode-identical.
103
+
104
+ A live PID, PID reuse, `EPERM`, corrupt or truncated metadata, another hostname or namespace, an
105
+ unknown filesystem, or any inconclusive result produces `OWNERSHIP_CONFLICT` without modifying the
106
+ owner lock. Lock age is never used as proof of death.
107
+
108
+ ### Supported environments and limitations
109
+
110
+ Automatic recovery is currently enabled only on Linux with `/proc` PID namespaces and these
111
+ recognized local filesystem types: ext2/3/4, XFS, Btrfs, ZFS, tmpfs, ramfs, and overlayfs. Network
112
+ filesystems, FUSE/unknown filesystems, Windows, and macOS fail closed; use manual mode there.
113
+ Container replacement commonly changes the PID namespace even when the hostname is reused, so it
114
+ also requires manual recovery. A matching hostname does not imply a shared PID namespace.
115
+
116
+ This mechanism is not a distributed lock, lease, heartbeat, or fencing service. Do not share a
117
+ database directory between hosts or independent containers. Filesystem power-loss guarantees still
118
+ depend on the operating system and storage device honoring file and directory synchronization.
119
+
120
+ If `.duraxis-owner.recovery` exists after an interrupted ownership operation, Duraxis will not
121
+ remove it. First stop every possible owner/recovery process, verify the directory is not mounted or
122
+ used elsewhere, preserve the files for diagnosis, and only then remove the guard manually. Run the
123
+ explicit recovery method for the owner lock afterward. Never automate this operator procedure.
124
+
125
+ ## NestJS factory integration
126
+
127
+ Use a driver factory so `DuraxisModule` owns and closes the disk driver. A supplied driver instance
128
+ is externally owned by default and is not closed unless `closeStorage: true` is set.
129
+
130
+ ```ts
131
+ import { Module } from "@nestjs/common";
132
+ import { DuraxisModule } from "@duraxis/nestjs";
133
+ import { AsyncDiskStorageDriver } from "@duraxis/storage-disk";
134
+ import { User } from "./user.entity.js";
135
+
136
+ @Module({
137
+ imports: [
138
+ DuraxisModule.forRootAsync({
139
+ useFactory: async () => ({
140
+ driver: () =>
141
+ AsyncDiskStorageDriver.open({
142
+ directory: "/var/lib/my-service/duraxis",
143
+ ownershipRecovery: {
144
+ mode: "dead-process",
145
+ applicationId: "com.example.my-service",
146
+ },
147
+ }),
148
+ entities: [User],
149
+ schema: { mode: "validate" },
150
+ }),
151
+ }),
152
+ DuraxisModule.forFeature([User]),
153
+ ],
154
+ })
155
+ export class AppModule {}
156
+ ```
157
+
158
+ Nest application shutdown awaits the factory-owned driver. Graceful shutdown removes the owner
159
+ lock, and the same directory can then be reopened with its persisted data intact.
160
+
161
+ ## Operational notes
162
+
163
+ - Place the database on a local filesystem and grant the application exclusive directory access.
164
+ - Always await `close()` during graceful shutdown.
165
+ - Treat `OWNERSHIP_CONFLICT` as a safety decision; do not add an unsafe force-unlock loop.
166
+ - Back up and inspect the database before manual intervention after a crash.
167
+ - `durability` reports whether directory-entry synchronization is available on the current host.
168
+
169
+ The driver does not coordinate multiple hosts. It preserves atomic storage operations, journal
170
+ recovery, object versions, and checksummed physical formats, but should be evaluated against the
171
+ failure model and storage stack of each deployment.
@@ -0,0 +1,69 @@
1
+ import { type DeleteOptions, type DeleteResult, type StorageDriver, type StorageDriverMetrics, type StorageObject, type StorageObjectInfo, type WriteOptions, type WriteResult } from "@duraxis/storage";
2
+ import { type OwnershipRecoveryOptions, type RecoverOwnershipOptions } from "./ownership.js";
3
+ export type { OwnershipRecoveryOptions, RecoverOwnershipOptions } from "./ownership.js";
4
+ export type DiskFaultPoint = "after-object-sync" | "after-object-publish" | "after-object-directory-sync" | "after-journal-write" | "after-journal-sync" | "after-journal-rotation";
5
+ export interface DiskFaultContext {
6
+ readonly operation: "put" | "delete" | "compact";
7
+ readonly key?: string;
8
+ }
9
+ export interface AsyncDiskStorageOptions {
10
+ readonly directory: string;
11
+ readonly ownershipRecovery?: OwnershipRecoveryOptions;
12
+ readonly maxKeyBytes?: number;
13
+ readonly maxObjectBytes?: number;
14
+ readonly maxJournalBytes?: number;
15
+ readonly nodeCacheHint?: number;
16
+ readonly faultInjector?: (point: DiskFaultPoint, context: DiskFaultContext) => void | Promise<void>;
17
+ }
18
+ export interface DiskDurabilityCapabilities {
19
+ readonly fileDataSync: true;
20
+ readonly directoryEntrySync: boolean;
21
+ readonly ownership: "exclusive-directory";
22
+ readonly processCrashRecovery: true;
23
+ readonly powerLossGuarantee: "file-and-directory-sync" | "file-sync-only";
24
+ }
25
+ export declare class AsyncDiskStorageDriver implements StorageDriver {
26
+ private readonly root;
27
+ private readonly registryKey;
28
+ private readonly options;
29
+ private static readonly activeDirectories;
30
+ private readonly entries;
31
+ private readonly ownership;
32
+ private readonly metrics;
33
+ private operationTail;
34
+ private journal;
35
+ private journalBytes;
36
+ private sequence;
37
+ private directorySync;
38
+ private closed;
39
+ private closing;
40
+ private resourcesClosed;
41
+ private closePromise?;
42
+ private poisoned;
43
+ private constructor();
44
+ static open(options: AsyncDiskStorageOptions): Promise<AsyncDiskStorageDriver>;
45
+ static recoverAbandonedOwnership(options: RecoverOwnershipOptions): Promise<void>;
46
+ get durability(): DiskDurabilityCapabilities;
47
+ getMetrics(): Readonly<StorageDriverMetrics>;
48
+ private initialize;
49
+ private validateKey;
50
+ private assertUsable;
51
+ private exclusive;
52
+ get(key: string): Promise<StorageObject | null>;
53
+ put(key: string, data: Uint8Array, options: WriteOptions): Promise<WriteResult>;
54
+ delete(key: string, options: DeleteOptions): Promise<DeleteResult>;
55
+ list(prefix: string): Promise<readonly StorageObjectInfo[]>;
56
+ private append;
57
+ compact(): Promise<void>;
58
+ close(): Promise<void>;
59
+ private closeAttempt;
60
+ private objectPath;
61
+ private assertCurrentObjectsExist;
62
+ private cleanupPhysicalObjects;
63
+ private recoverJournalRotation;
64
+ private fault;
65
+ private removeObsolete;
66
+ private syncDirectory;
67
+ private static syncDirectoryStatic;
68
+ private cleanupFailedOpen;
69
+ }
@@ -0,0 +1,28 @@
1
+ export declare const MAX_JOURNAL_FRAME_BYTES: number;
2
+ export interface StoredMetadata {
3
+ readonly version: string;
4
+ readonly createdAt: number;
5
+ readonly size: number;
6
+ readonly digest: string;
7
+ }
8
+ export type JournalPayload = ({
9
+ readonly format: 1;
10
+ readonly sequence: number;
11
+ readonly op: "put";
12
+ readonly key: string;
13
+ } & StoredMetadata) | {
14
+ readonly format: 1;
15
+ readonly sequence: number;
16
+ readonly op: "delete";
17
+ readonly key: string;
18
+ };
19
+ export interface DecodedJournal {
20
+ readonly frames: readonly JournalPayload[];
21
+ readonly validBytes: number;
22
+ readonly incompleteTail: boolean;
23
+ }
24
+ export declare function sha256(data: Uint8Array | string): string;
25
+ export declare function encodePhysicalObject(key: string, metadata: StoredMetadata, data: Uint8Array): Uint8Array;
26
+ export declare function decodePhysicalObject(bytes: Uint8Array, expectedKey: string, expected: StoredMetadata): Uint8Array;
27
+ export declare function encodeJournalFrame(payload: JournalPayload): Uint8Array;
28
+ export declare function decodeJournal(bytes: Uint8Array): DecodedJournal;