event-storage 1.4.1 → 1.5.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/README.md +12 -88
- package/index.d.ts +116 -10
- package/index.js +2 -1
- package/package.json +10 -3
- package/projections.d.ts +40 -0
- package/projections.js +1 -0
- package/src/Consumer.js +18 -29
- package/src/EventStore.js +24 -3
- package/src/Index/ReadOnlyIndex.js +3 -3
- package/src/Index/ReadableIndex.js +147 -102
- package/src/Index/WritableIndex.js +73 -23
- package/src/JoinEventStream.js +23 -83
- package/src/Partition/ReadablePartition.js +31 -8
- package/src/Partition/WritablePartition.js +58 -2
- package/src/Projection.js +164 -0
- package/src/Storage/ReadOnlyStorage.js +12 -13
- package/src/Storage/ReadableStorage.js +6 -11
- package/src/Storage/StorageLock.js +185 -0
- package/src/Storage/WritableStorage.js +86 -45
- package/src/Storage.js +3 -2
- package/src/utils/dcbUtil.js +18 -1
- package/src/utils/fsUtil.js +57 -1
- package/src/utils/indexUtil.js +85 -116
- package/src/utils/metadataUtil.js +23 -1
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import os from 'os';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import { assert } from '../utils/util.js';
|
|
5
|
+
|
|
6
|
+
const LOCK_RECLAIM = 0x1;
|
|
7
|
+
const LOCK_THROW = 0x2;
|
|
8
|
+
const LOCK_AUTO = 0x4;
|
|
9
|
+
|
|
10
|
+
// Ends in `.lock` so that partition scans, also those of earlier versions, skip it like the lock directory itself.
|
|
11
|
+
const OWNER_FILE = 'owner.lock';
|
|
12
|
+
const RECLAIM_MARKER = 'reclaim.lock';
|
|
13
|
+
|
|
14
|
+
class StorageLockedError extends Error {}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Containers sharing a host name can not see each other's processes, so a pid is only comparable within one pid namespace.
|
|
18
|
+
*
|
|
19
|
+
* @returns {string|null} The pid namespace of this process on Linux, null elsewhere.
|
|
20
|
+
*/
|
|
21
|
+
function currentPidNamespace() {
|
|
22
|
+
try {
|
|
23
|
+
return fs.readlinkSync('/proc/self/ns/pid');
|
|
24
|
+
/* c8 ignore next 3 */
|
|
25
|
+
} catch (e) {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* @param {number} pid
|
|
32
|
+
* @returns {boolean}
|
|
33
|
+
*/
|
|
34
|
+
function isProcessRunning(pid) {
|
|
35
|
+
try {
|
|
36
|
+
process.kill(pid, 0);
|
|
37
|
+
return true;
|
|
38
|
+
} catch (e) {
|
|
39
|
+
return e.code === 'EPERM';
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The single-writer lock of a storage: a directory that only one writer can create, holding a file that names its owner
|
|
45
|
+
* process, so that the lock of a crashed writer can be told apart from the lock of a running one.
|
|
46
|
+
*/
|
|
47
|
+
class StorageLock {
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* @param {string} directory The path of the lock directory.
|
|
51
|
+
* @param {string} storageName The storage name used in error messages.
|
|
52
|
+
* @param {number} [mode] One of the LOCK_* constants. Default LOCK_AUTO.
|
|
53
|
+
*/
|
|
54
|
+
constructor(directory, storageName, mode = LOCK_AUTO) {
|
|
55
|
+
this.directory = directory;
|
|
56
|
+
this.storageName = storageName;
|
|
57
|
+
this.mode = mode;
|
|
58
|
+
this.held = false;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Remove a lock left behind by another writer: always with LOCK_RECLAIM, with LOCK_AUTO only when its owner is gone.
|
|
63
|
+
*
|
|
64
|
+
* @returns {boolean} True if such a lock was removed, which means the storage needs to be repaired.
|
|
65
|
+
*/
|
|
66
|
+
reclaimOrphaned() {
|
|
67
|
+
if (this.held) {
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
if (this.mode === LOCK_RECLAIM) {
|
|
71
|
+
return this.release();
|
|
72
|
+
}
|
|
73
|
+
return this.mode === LOCK_AUTO && this.isOwnerGone() && this.removeStaleLock();
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Two writers starting at the same time may both find the owner gone. Without a claim, the slower one would delete
|
|
78
|
+
* the lock the faster one has just acquired. The claim is a directory inside the stale lock that only one of them
|
|
79
|
+
* can create, and the owner is checked again while holding it.
|
|
80
|
+
*
|
|
81
|
+
* @private
|
|
82
|
+
* @returns {boolean} True if the stale lock was removed by this instance.
|
|
83
|
+
*/
|
|
84
|
+
removeStaleLock() {
|
|
85
|
+
const marker = path.join(this.directory, RECLAIM_MARKER);
|
|
86
|
+
try {
|
|
87
|
+
fs.mkdirSync(marker);
|
|
88
|
+
} catch (e) {
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
if (!this.isOwnerGone()) {
|
|
92
|
+
fs.rmdirSync(marker);
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
fs.rmSync(this.directory, { recursive: true, force: true });
|
|
96
|
+
return true;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* @returns {boolean} True if the lock was acquired or false if this instance already holds it.
|
|
101
|
+
* @throws {StorageLockedError} If another writer holds the lock.
|
|
102
|
+
*/
|
|
103
|
+
acquire() {
|
|
104
|
+
if (this.held) {
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
try {
|
|
108
|
+
fs.mkdirSync(this.directory);
|
|
109
|
+
} catch (e) {
|
|
110
|
+
/* c8 ignore next */
|
|
111
|
+
assert(e.code === 'EEXIST', `Error creating lock for storage ${this.storageName}: ` + e.message);
|
|
112
|
+
throw new StorageLockedError(this.describeHolder());
|
|
113
|
+
}
|
|
114
|
+
this.held = true;
|
|
115
|
+
StorageLock.heldByThisProcess.add(this.directory);
|
|
116
|
+
const owner = { pid: process.pid, hostname: os.hostname(), pidNamespace: currentPidNamespace(), lockedAt: new Date().toISOString() };
|
|
117
|
+
fs.writeFileSync(path.join(this.directory, OWNER_FILE), JSON.stringify(owner));
|
|
118
|
+
return true;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Remove the lock, no matter which writer holds it.
|
|
123
|
+
*
|
|
124
|
+
* @returns {boolean} True if a lock not held by this instance was removed.
|
|
125
|
+
*/
|
|
126
|
+
release() {
|
|
127
|
+
const exists = fs.existsSync(this.directory);
|
|
128
|
+
const orphaned = exists && !this.held;
|
|
129
|
+
if (exists) {
|
|
130
|
+
fs.rmSync(this.directory, { recursive: true, force: true });
|
|
131
|
+
}
|
|
132
|
+
if (this.held) {
|
|
133
|
+
StorageLock.heldByThisProcess.delete(this.directory);
|
|
134
|
+
}
|
|
135
|
+
this.held = false;
|
|
136
|
+
return orphaned;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* @returns {{pid: number, hostname: string, pidNamespace: string|null, lockedAt: string}|null} The process holding
|
|
141
|
+
* the lock, or null if there is no lock or it carries no owner information.
|
|
142
|
+
*/
|
|
143
|
+
readOwner() {
|
|
144
|
+
try {
|
|
145
|
+
const owner = JSON.parse(fs.readFileSync(path.join(this.directory, OWNER_FILE), 'utf8'));
|
|
146
|
+
return Number.isInteger(owner.pid) ? owner : null;
|
|
147
|
+
} catch (e) {
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Only an owner that provably ran in this process table (same host, same pid namespace) and no longer runs counts
|
|
154
|
+
* as gone. Anything else, including a lock without owner information, is treated as held.
|
|
155
|
+
*
|
|
156
|
+
* @private
|
|
157
|
+
* @returns {boolean}
|
|
158
|
+
*/
|
|
159
|
+
isOwnerGone() {
|
|
160
|
+
const owner = this.readOwner();
|
|
161
|
+
if (owner === null || owner.hostname !== os.hostname() || owner.pidNamespace !== currentPidNamespace()) {
|
|
162
|
+
return false;
|
|
163
|
+
}
|
|
164
|
+
if (owner.pid === process.pid) {
|
|
165
|
+
return !StorageLock.heldByThisProcess.has(this.directory);
|
|
166
|
+
}
|
|
167
|
+
return !isProcessRunning(owner.pid);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* @private
|
|
172
|
+
* @returns {string}
|
|
173
|
+
*/
|
|
174
|
+
describeHolder() {
|
|
175
|
+
const owner = this.readOwner();
|
|
176
|
+
const holder = owner === null ? 'another process' : `process ${owner.pid} on ${owner.hostname} (locked at ${owner.lockedAt})`;
|
|
177
|
+
return `Storage ${this.storageName} is locked by ${holder}. If that process is no longer running, open the storage with LOCK_RECLAIM.`;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// Lock directories held in this process, to tell an own live lock from one left by an earlier process with the same pid.
|
|
182
|
+
StorageLock.heldByThisProcess = new Set();
|
|
183
|
+
|
|
184
|
+
export default StorageLock;
|
|
185
|
+
export { StorageLockedError, LOCK_THROW, LOCK_RECLAIM, LOCK_AUTO };
|
|
@@ -3,17 +3,19 @@ import path from 'path';
|
|
|
3
3
|
import WritablePartition from '../Partition/WritablePartition.js';
|
|
4
4
|
import WritableIndex, { Entry as WritableIndexEntry } from '../Index/WritableIndex.js';
|
|
5
5
|
import ReadableStorage from './ReadableStorage.js';
|
|
6
|
+
import StorageLock, { StorageLockedError, LOCK_THROW, LOCK_RECLAIM, LOCK_AUTO } from './StorageLock.js';
|
|
6
7
|
import { assert } from '../utils/util.js';
|
|
7
8
|
import { ensureDirectory } from '../utils/fsUtil.js';
|
|
8
9
|
import { matches, buildMetadataForMatcher, buildMatcherFromMetadata } from '../utils/metadataUtil.js';
|
|
9
10
|
import { normalizeNamedCtorArgs } from '../utils/apiHelpers.js';
|
|
10
11
|
|
|
11
|
-
const
|
|
12
|
+
const PARTITION_PROBE_SEPARATOR = '~';
|
|
13
|
+
const PROBE_SUFFIX_PATTERN = new RegExp(PARTITION_PROBE_SEPARATOR + '\\d+$');
|
|
12
14
|
|
|
13
|
-
const
|
|
14
|
-
const LOCK_THROW = 0x2;
|
|
15
|
+
const DEFAULT_WRITE_BUFFER_SIZE = 16 * 1024;
|
|
15
16
|
|
|
16
|
-
|
|
17
|
+
// Index entries and document headers store sequence numbers, file positions and sizes as unsigned 32-bit integers.
|
|
18
|
+
const MAX_UINT32 = 0xFFFFFFFF;
|
|
17
19
|
|
|
18
20
|
/**
|
|
19
21
|
* @typedef {object|function(object):boolean} Matcher
|
|
@@ -38,11 +40,12 @@ class WritableStorage extends ReadableStorage {
|
|
|
38
40
|
* @param {number} [config.writeBufferSize] Size of the write buffer in bytes. Default 16384.
|
|
39
41
|
* @param {number} [config.maxWriteBufferDocuments] How many documents to have in the write buffer at max. 0 means as much as possible. Default 0.
|
|
40
42
|
* @param {boolean} [config.syncOnFlush] If fsync should be called on write buffer flush. Set this if you need strict durability. Defaults to false.
|
|
43
|
+
* @param {number} [config.syncInterval] Group commit: fsync each partition at most every this many ms and only then invoke write callbacks. Ignored when `syncOnFlush` is set. Defaults to 0 (off).
|
|
41
44
|
* @param {boolean} [config.dirtyReads] If dirty reads should be allowed. This means that writes that are in write buffer but not yet flushed can be read. Defaults to true.
|
|
42
45
|
* @param {function(object, number): string} [config.partitioner] A function that takes a document and sequence number and returns a partition name that the document should be stored in. Defaults to write all documents to the primary partition.
|
|
43
46
|
* @param {object} [config.indexOptions] An options object that should be passed to all indexes on construction.
|
|
44
47
|
* @param {string} [config.hmacSecret] A private key that is used to verify matchers retrieved from indexes.
|
|
45
|
-
* @param {number} [config.lock] One of LOCK_* constants that defines how an existing lock should be handled.
|
|
48
|
+
* @param {number} [config.lock] One of LOCK_* constants that defines how an existing lock should be handled. Default LOCK_AUTO.
|
|
46
49
|
*/
|
|
47
50
|
constructor(storageName = 'storage', config = {}) {
|
|
48
51
|
({ name: storageName, options: config } = normalizeNamedCtorArgs(storageName, config));
|
|
@@ -51,24 +54,27 @@ class WritableStorage extends ReadableStorage {
|
|
|
51
54
|
writeBufferSize: DEFAULT_WRITE_BUFFER_SIZE,
|
|
52
55
|
maxWriteBufferDocuments: 0,
|
|
53
56
|
syncOnFlush: false,
|
|
57
|
+
syncInterval: 0,
|
|
54
58
|
dirtyReads: true,
|
|
55
|
-
dataDirectory: '.'
|
|
59
|
+
dataDirectory: '.',
|
|
60
|
+
lock: LOCK_AUTO
|
|
56
61
|
};
|
|
57
62
|
config = Object.assign(defaults, config);
|
|
58
|
-
config.
|
|
63
|
+
assert(Number.isInteger(config.syncInterval) && config.syncInterval >= 0, 'syncInterval must be a non-negative integer.');
|
|
64
|
+
config.indexOptions = Object.assign({ syncOnFlush: config.syncOnFlush, syncInterval: config.syncInterval }, config.indexOptions);
|
|
59
65
|
ensureDirectory(config.dataDirectory);
|
|
60
66
|
super(storageName, config);
|
|
61
67
|
|
|
62
68
|
this.lockFile = path.resolve(this.dataDirectory, this.storageFile + '.lock');
|
|
63
|
-
this.
|
|
69
|
+
this.storageLock = new StorageLock(this.lockFile, this.storageFile, config.lock);
|
|
64
70
|
this.partitioner = config.partitioner;
|
|
65
71
|
this.partitionIds = {};
|
|
66
72
|
}
|
|
67
73
|
|
|
68
74
|
/**
|
|
69
75
|
* Acquires the write lock synchronously.
|
|
70
|
-
*
|
|
71
|
-
* repair runs after the primary index is open, before `'opened'` is emitted.
|
|
76
|
+
* Removes an orphaned lock first (always with LOCK_RECLAIM, with LOCK_AUTO only when its owner process is gone);
|
|
77
|
+
* torn-write repair then runs after the primary index is open, before `'opened'` is emitted.
|
|
72
78
|
*
|
|
73
79
|
* @param {function(): void} [callback] Called after indexes open, before `'opened'` is emitted.
|
|
74
80
|
* Can be used as a synchronous alternative to listening to the `'opened'` event.
|
|
@@ -76,7 +82,7 @@ class WritableStorage extends ReadableStorage {
|
|
|
76
82
|
* @throws {StorageLockedError} If this storage is locked by another process.
|
|
77
83
|
*/
|
|
78
84
|
open(callback) {
|
|
79
|
-
const needsRepair = this.
|
|
85
|
+
const needsRepair = this.storageLock.reclaimOrphaned();
|
|
80
86
|
|
|
81
87
|
if (!this.lock()) {
|
|
82
88
|
return true;
|
|
@@ -214,6 +220,22 @@ class WritableStorage extends ReadableStorage {
|
|
|
214
220
|
this.flush();
|
|
215
221
|
}
|
|
216
222
|
|
|
223
|
+
/**
|
|
224
|
+
* @api
|
|
225
|
+
* @returns {{pid: number, hostname: string, pidNamespace: string|null, lockedAt: string}|null} The process holding
|
|
226
|
+
* the lock, or null if the storage is not locked or the lock carries no owner information.
|
|
227
|
+
*/
|
|
228
|
+
readLockOwner() {
|
|
229
|
+
return this.storageLock.readOwner();
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* @returns {boolean} If this writer holds the storage lock.
|
|
234
|
+
*/
|
|
235
|
+
get locked() {
|
|
236
|
+
return this.storageLock.held;
|
|
237
|
+
}
|
|
238
|
+
|
|
217
239
|
/**
|
|
218
240
|
* Attempt to lock this storage by means of a lock directory.
|
|
219
241
|
* @returns {boolean} True if the lock was created or false if the lock is already in place.
|
|
@@ -221,35 +243,16 @@ class WritableStorage extends ReadableStorage {
|
|
|
221
243
|
* @throws {Error} If the lock could not be created.
|
|
222
244
|
*/
|
|
223
245
|
lock() {
|
|
224
|
-
|
|
225
|
-
return false;
|
|
226
|
-
}
|
|
227
|
-
try {
|
|
228
|
-
fs.mkdirSync(this.lockFile);
|
|
229
|
-
this.locked = true;
|
|
230
|
-
} catch (e) {
|
|
231
|
-
/* c8 ignore next */
|
|
232
|
-
assert(e.code === 'EEXIST', `Error creating lock for storage ${this.storageFile}: ` + e.message)
|
|
233
|
-
|
|
234
|
-
throw new StorageLockedError(`Storage ${this.storageFile} is locked by another process`);
|
|
235
|
-
}
|
|
236
|
-
return true;
|
|
246
|
+
return this.storageLock.acquire();
|
|
237
247
|
}
|
|
238
248
|
|
|
239
249
|
/**
|
|
240
250
|
* Unlock this storage, no matter if it was previously locked by this writer.
|
|
241
251
|
* Only use this if you are sure there is no other process still having a writer open.
|
|
242
|
-
* Current implementation just deletes a lock file that is named like the storage.
|
|
243
252
|
* @returns {boolean} True if an orphaned lock from another process was removed.
|
|
244
253
|
*/
|
|
245
254
|
unlock() {
|
|
246
|
-
|
|
247
|
-
const orphaned = lockExists && !this.locked;
|
|
248
|
-
if (lockExists) {
|
|
249
|
-
fs.rmdirSync(this.lockFile);
|
|
250
|
-
}
|
|
251
|
-
this.locked = false;
|
|
252
|
-
return orphaned;
|
|
255
|
+
return this.storageLock.release();
|
|
253
256
|
}
|
|
254
257
|
|
|
255
258
|
/**
|
|
@@ -263,6 +266,21 @@ class WritableStorage extends ReadableStorage {
|
|
|
263
266
|
super.close();
|
|
264
267
|
}
|
|
265
268
|
|
|
269
|
+
/**
|
|
270
|
+
* Reject a write that the index format can not record, before anything is written. Otherwise the document would
|
|
271
|
+
* land in the partition and the index entry would fail afterwards, leaving data and index diverged.
|
|
272
|
+
*
|
|
273
|
+
* @private
|
|
274
|
+
* @param {WritablePartition} partition The partition the document will be written to.
|
|
275
|
+
* @throws {Error} if the storage or the partition is full.
|
|
276
|
+
*/
|
|
277
|
+
assertWithinLimits(partition) {
|
|
278
|
+
assert(this.index.length < MAX_UINT32,
|
|
279
|
+
`Storage is full: it can hold at most ${MAX_UINT32} documents.`);
|
|
280
|
+
assert(partition.size <= MAX_UINT32,
|
|
281
|
+
`Partition ${partition.name} is full: documents must start within the first 4 GiB of a partition. Use a partitioner that spreads the documents over more partitions.`);
|
|
282
|
+
}
|
|
283
|
+
|
|
266
284
|
/**
|
|
267
285
|
* Add an index entry for the given document at the position and size.
|
|
268
286
|
*
|
|
@@ -309,10 +327,33 @@ class WritableStorage extends ReadableStorage {
|
|
|
309
327
|
this.on('preCommit', hook);
|
|
310
328
|
}
|
|
311
329
|
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
330
|
+
/**
|
|
331
|
+
* Resolve the id and file name of the partition for a partition name.
|
|
332
|
+
*
|
|
333
|
+
* A partition id is the 32-bit hash of the partition file name, both here and when readers scan the files.
|
|
334
|
+
* If that id is already taken by a partition with a different file name (hash collision), the partition is
|
|
335
|
+
* stored in the file `<partitionName>~1` instead, and so on. The probing is deterministic, so the same
|
|
336
|
+
* name always resolves to the same file, and readers derive the same id from the file name.
|
|
337
|
+
*
|
|
338
|
+
* @private
|
|
339
|
+
* @param {string} partitionShortName The partition name returned by the partitioner.
|
|
340
|
+
* @param {string} partitionName The partition file name without probe suffix.
|
|
341
|
+
* @returns {{ id: number, fileName: string }}
|
|
342
|
+
*/
|
|
343
|
+
resolvePartition(partitionShortName, partitionName) {
|
|
344
|
+
const cached = this.partitionIds[partitionShortName];
|
|
345
|
+
if (cached !== undefined) {
|
|
346
|
+
return cached;
|
|
347
|
+
}
|
|
348
|
+
let fileName = partitionName;
|
|
349
|
+
let partitionId = WritablePartition.idFor(fileName);
|
|
350
|
+
for (let probe = 1; partitionId in this.partitions && this.partitions[partitionId].name !== fileName; probe++) {
|
|
351
|
+
fileName = partitionName + PARTITION_PROBE_SEPARATOR + probe;
|
|
352
|
+
partitionId = WritablePartition.idFor(fileName);
|
|
353
|
+
}
|
|
354
|
+
const resolved = { id: partitionId, fileName };
|
|
355
|
+
this.partitionIds[partitionShortName] = resolved;
|
|
356
|
+
return resolved;
|
|
316
357
|
}
|
|
317
358
|
|
|
318
359
|
buildPartitionConfig(partitionShortName) {
|
|
@@ -333,6 +374,8 @@ class WritableStorage extends ReadableStorage {
|
|
|
333
374
|
if (partitionId in this.partitions) {
|
|
334
375
|
return;
|
|
335
376
|
}
|
|
377
|
+
assert(!PROBE_SUFFIX_PATTERN.test(partitionShortName),
|
|
378
|
+
`Invalid partition name "${partitionShortName}". Names ending in "${PARTITION_PROBE_SEPARATOR}<number>" are reserved.`);
|
|
336
379
|
const partitionConfig = this.buildPartitionConfig(partitionShortName);
|
|
337
380
|
this.ensurePartitionDirectory(partitionName);
|
|
338
381
|
this.partitions[partitionId] = this.createPartition(partitionName, partitionConfig);
|
|
@@ -355,8 +398,9 @@ class WritableStorage extends ReadableStorage {
|
|
|
355
398
|
if (typeof partitionIdentifier === 'string') {
|
|
356
399
|
const partitionShortName = partitionIdentifier;
|
|
357
400
|
const partitionName = this.storageFile + (partitionIdentifier.length ? '.' + partitionIdentifier : '');
|
|
358
|
-
|
|
359
|
-
this.createNamedPartition(
|
|
401
|
+
const { id, fileName } = this.resolvePartition(partitionShortName, partitionName);
|
|
402
|
+
this.createNamedPartition(id, fileName, partitionShortName);
|
|
403
|
+
partitionIdentifier = id;
|
|
360
404
|
}
|
|
361
405
|
return super.getPartition(partitionIdentifier);
|
|
362
406
|
}
|
|
@@ -373,6 +417,7 @@ class WritableStorage extends ReadableStorage {
|
|
|
373
417
|
|
|
374
418
|
const partitionName = this.partitioner(document, this.index.length + 1);
|
|
375
419
|
const partition = this.getPartition(partitionName);
|
|
420
|
+
this.assertWithinLimits(partition);
|
|
376
421
|
this.emit('preCommit', document, partition.metadata);
|
|
377
422
|
|
|
378
423
|
const position = partition.write(data, this.length, callback);
|
|
@@ -486,12 +531,8 @@ class WritableStorage extends ReadableStorage {
|
|
|
486
531
|
return;
|
|
487
532
|
}
|
|
488
533
|
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
return;
|
|
492
|
-
}
|
|
493
|
-
|
|
494
|
-
this.forEachDistinctPartitionOf(entries, entry => this.getPartition(entry.partition).truncate(entry.position));
|
|
534
|
+
// We need the first entry that is cut off in each partition.
|
|
535
|
+
this.forEachDistinctPartitionOf(this.index.range(after + 1), entry => this.getPartition(entry.partition).truncate(entry.position));
|
|
495
536
|
}
|
|
496
537
|
|
|
497
538
|
/**
|
|
@@ -574,4 +615,4 @@ class WritableStorage extends ReadableStorage {
|
|
|
574
615
|
}
|
|
575
616
|
|
|
576
617
|
export default WritableStorage;
|
|
577
|
-
export { StorageLockedError, LOCK_THROW, LOCK_RECLAIM };
|
|
618
|
+
export { StorageLockedError, LOCK_THROW, LOCK_RECLAIM, LOCK_AUTO };
|
package/src/Storage.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import WritableStorage, { StorageLockedError, LOCK_THROW, LOCK_RECLAIM } from './Storage/WritableStorage.js';
|
|
1
|
+
import WritableStorage, { StorageLockedError, LOCK_THROW, LOCK_RECLAIM, LOCK_AUTO } from './Storage/WritableStorage.js';
|
|
2
2
|
import ReadOnlyStorage from './Storage/ReadOnlyStorage.js';
|
|
3
3
|
|
|
4
4
|
WritableStorage.ReadOnly = ReadOnlyStorage;
|
|
5
5
|
WritableStorage.StorageLockedError = StorageLockedError;
|
|
6
6
|
WritableStorage.LOCK_THROW = LOCK_THROW;
|
|
7
7
|
WritableStorage.LOCK_RECLAIM = LOCK_RECLAIM;
|
|
8
|
+
WritableStorage.LOCK_AUTO = LOCK_AUTO;
|
|
8
9
|
|
|
9
10
|
export default WritableStorage;
|
|
10
|
-
export { ReadOnlyStorage as ReadOnly, StorageLockedError, LOCK_THROW, LOCK_RECLAIM };
|
|
11
|
+
export { ReadOnlyStorage as ReadOnly, StorageLockedError, LOCK_THROW, LOCK_RECLAIM, LOCK_AUTO };
|
package/src/utils/dcbUtil.js
CHANGED
|
@@ -67,4 +67,21 @@ function compileDcbItem(item, resolveType, resolveTag) {
|
|
|
67
67
|
return terms; // inner array = AND level
|
|
68
68
|
}
|
|
69
69
|
|
|
70
|
-
|
|
70
|
+
/**
|
|
71
|
+
* Check in memory whether an event with the given type and tags matches a {@link DcbQuery}.
|
|
72
|
+
* Mirrors the semantics of {@link compileDcbQuery}: items are ORed, tags within an item are ANDed,
|
|
73
|
+
* types within an item are ORed, and a missing/empty `types` or `tags` constraint matches anything.
|
|
74
|
+
*
|
|
75
|
+
* @param {object} query A DcbQuery with an `items` array.
|
|
76
|
+
* @param {string|undefined} type The event type.
|
|
77
|
+
* @param {string[]} tags The event tags (empty array when the event has none).
|
|
78
|
+
* @returns {boolean}
|
|
79
|
+
*/
|
|
80
|
+
function matchesDcbQuery(query, type, tags) {
|
|
81
|
+
return query.items.some(item =>
|
|
82
|
+
(!item.types?.length || item.types.includes(type)) &&
|
|
83
|
+
(item.tags ?? []).every(tag => tags.includes(tag))
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export {isDcbQuery, compileDcbQuery, matchesDcbQuery};
|
package/src/utils/fsUtil.js
CHANGED
|
@@ -14,6 +14,59 @@ function resolvePath(fileOrDirectory, ...directories) {
|
|
|
14
14
|
return path.resolve(fileOrDirectory, ...directories);
|
|
15
15
|
}
|
|
16
16
|
|
|
17
|
+
/**
|
|
18
|
+
* Unlink a file, ignoring the error if it does not exist.
|
|
19
|
+
* @param {string} fileName
|
|
20
|
+
* @throws {Error} For any error other than ENOENT.
|
|
21
|
+
*/
|
|
22
|
+
function safeUnlink(fileName) {
|
|
23
|
+
try {
|
|
24
|
+
fs.unlinkSync(fileName);
|
|
25
|
+
} catch (e) {
|
|
26
|
+
if (e.code !== 'ENOENT') {
|
|
27
|
+
throw e;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Replace a file atomically: write to a temporary file, then rename it over the target.
|
|
34
|
+
* A failed or interrupted write never leaves a partially written target file behind.
|
|
35
|
+
*
|
|
36
|
+
* @param {string} fileName Target file.
|
|
37
|
+
* @param {string|Buffer} data
|
|
38
|
+
* @param {string} [tmpFileName] Temporary file to write first. Defaults to `fileName + '.tmp'`.
|
|
39
|
+
* @throws {Error} When writing or renaming fails; the temporary file is removed in that case.
|
|
40
|
+
*/
|
|
41
|
+
function writeFileAtomic(fileName, data, tmpFileName = fileName + '.tmp') {
|
|
42
|
+
try {
|
|
43
|
+
fs.writeFileSync(tmpFileName, data);
|
|
44
|
+
fs.renameSync(tmpFileName, fileName);
|
|
45
|
+
} catch (e) {
|
|
46
|
+
safeUnlink(tmpFileName);
|
|
47
|
+
throw e;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* A new file is only guaranteed to survive a power loss once its directory entry is synced as well.
|
|
53
|
+
* Platforms that can not open a directory for syncing (Windows) are skipped silently.
|
|
54
|
+
*
|
|
55
|
+
* @param {string} dirName
|
|
56
|
+
*/
|
|
57
|
+
function syncDirectory(dirName) {
|
|
58
|
+
let fd;
|
|
59
|
+
try {
|
|
60
|
+
fd = fs.openSync(dirName, 'r');
|
|
61
|
+
fs.fsyncSync(fd);
|
|
62
|
+
} catch (e) {
|
|
63
|
+
} finally {
|
|
64
|
+
if (fd !== undefined) {
|
|
65
|
+
fs.closeSync(fd);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
17
70
|
/**
|
|
18
71
|
* Ensure that the given directory exists.
|
|
19
72
|
* @param {string} dirName Target directory.
|
|
@@ -150,5 +203,8 @@ export {
|
|
|
150
203
|
resolvePath,
|
|
151
204
|
ensureDirectory,
|
|
152
205
|
scanForFiles,
|
|
153
|
-
isSameOrParentDirectory
|
|
206
|
+
isSameOrParentDirectory,
|
|
207
|
+
safeUnlink,
|
|
208
|
+
syncDirectory,
|
|
209
|
+
writeFileAtomic
|
|
154
210
|
};
|