@duraxis/storage-disk 0.1.0 → 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 CHANGED
@@ -1,4 +1,10 @@
1
1
  # @duraxis/storage-disk changelog
2
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
+
3
9
  This file is maintained by Changesets. Future releases will add versioned
4
10
  entries automatically.
package/README.md CHANGED
@@ -1,9 +1,9 @@
1
1
  # @duraxis/storage-disk
2
2
 
3
- Driver assíncrono de filesystem para Duraxis. Ele armazena objetos e journal em um diretório
4
- local e exige posse exclusiva desse diretório enquanto estiver aberto.
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
5
 
6
- ## Instalação
6
+ ## Installation
7
7
 
8
8
  ```bash
9
9
  pnpm add @duraxis/storage-disk
@@ -11,6 +11,10 @@ npm install @duraxis/storage-disk
11
11
  yarn add @duraxis/storage-disk
12
12
  ```
13
13
 
14
+ Node.js 22.12 or newer is required.
15
+
16
+ ## Basic use
17
+
14
18
  ```ts
15
19
  import { AsyncDiskStorageDriver } from "@duraxis/storage-disk";
16
20
 
@@ -24,10 +28,144 @@ try {
24
28
  }
25
29
  ```
26
30
 
27
- A API exporta `AsyncDiskStorageDriver` e os tipos de opção, capacidades de durabilidade,
28
- injeção de falhas e recuperação de posse. A recuperação de uma trava abandonada exige a
29
- confirmação explícita definida pela API e só deve ocorrer após verificar acesso exclusivo.
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.
30
168
 
31
- O driver integra-se a `@duraxis/core` por meio do contrato de `@duraxis/storage`. Ele não oferece
32
- coordenação entre hosts e as garantias frente a perda de energia dependem do suporte do sistema
33
- operacional a sincronização de arquivos e diretórios. Requer Node.js 22.12+.
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.
@@ -1,5 +1,6 @@
1
1
  import { type DeleteOptions, type DeleteResult, type StorageDriver, type StorageDriverMetrics, type StorageObject, type StorageObjectInfo, type WriteOptions, type WriteResult } from "@duraxis/storage";
2
- declare const OWNERSHIP_CONFIRMATION = "I_HAVE_VERIFIED_EXCLUSIVE_ACCESS";
2
+ import { type OwnershipRecoveryOptions, type RecoverOwnershipOptions } from "./ownership.js";
3
+ export type { OwnershipRecoveryOptions, RecoverOwnershipOptions } from "./ownership.js";
3
4
  export type DiskFaultPoint = "after-object-sync" | "after-object-publish" | "after-object-directory-sync" | "after-journal-write" | "after-journal-sync" | "after-journal-rotation";
4
5
  export interface DiskFaultContext {
5
6
  readonly operation: "put" | "delete" | "compact";
@@ -7,16 +8,13 @@ export interface DiskFaultContext {
7
8
  }
8
9
  export interface AsyncDiskStorageOptions {
9
10
  readonly directory: string;
11
+ readonly ownershipRecovery?: OwnershipRecoveryOptions;
10
12
  readonly maxKeyBytes?: number;
11
13
  readonly maxObjectBytes?: number;
12
14
  readonly maxJournalBytes?: number;
13
15
  readonly nodeCacheHint?: number;
14
16
  readonly faultInjector?: (point: DiskFaultPoint, context: DiskFaultContext) => void | Promise<void>;
15
17
  }
16
- export interface RecoverOwnershipOptions {
17
- readonly directory: string;
18
- readonly confirmation: typeof OWNERSHIP_CONFIRMATION;
19
- }
20
18
  export interface DiskDurabilityCapabilities {
21
19
  readonly fileDataSync: true;
22
20
  readonly directoryEntrySync: boolean;
@@ -30,16 +28,17 @@ export declare class AsyncDiskStorageDriver implements StorageDriver {
30
28
  private readonly options;
31
29
  private static readonly activeDirectories;
32
30
  private readonly entries;
33
- private readonly ownerId;
31
+ private readonly ownership;
34
32
  private readonly metrics;
35
33
  private operationTail;
36
34
  private journal;
37
- private lockHandle;
38
35
  private journalBytes;
39
36
  private sequence;
40
37
  private directorySync;
41
38
  private closed;
42
39
  private closing;
40
+ private resourcesClosed;
41
+ private closePromise?;
43
42
  private poisoned;
44
43
  private constructor();
45
44
  static open(options: AsyncDiskStorageOptions): Promise<AsyncDiskStorageDriver>;
@@ -57,6 +56,7 @@ export declare class AsyncDiskStorageDriver implements StorageDriver {
57
56
  private append;
58
57
  compact(): Promise<void>;
59
58
  close(): Promise<void>;
59
+ private closeAttempt;
60
60
  private objectPath;
61
61
  private assertCurrentObjectsExist;
62
62
  private cleanupPhysicalObjects;
@@ -67,4 +67,3 @@ export declare class AsyncDiskStorageDriver implements StorageDriver {
67
67
  private static syncDirectoryStatic;
68
68
  private cleanupFailedOpen;
69
69
  }
70
- export {};