event-storage 1.3.1 → 1.3.3
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/index.d.ts +10 -0
- package/index.js +28 -6
- package/package.json +3 -3
- package/src/EventStore.js +54 -19
- package/src/Index/ReadOnlyIndex.js +13 -0
- package/src/Index/ReadableIndex.js +3 -2
- package/src/Partition/ReadablePartition.js +3 -1
- package/src/Storage/ReadOnlyStorage.js +92 -18
- package/src/Storage/ReadableStorage.js +27 -7
- package/src/Storage/WritableStorage.js +2 -1
- package/src/Watcher.js +207 -62
- package/src/WatchesFile.js +4 -1
- package/src/utils/fsUtil.js +27 -0
package/index.d.ts
CHANGED
|
@@ -4,9 +4,16 @@ import { Readable } from 'node:stream';
|
|
|
4
4
|
export type EventMatcher = Record<string, unknown> | ((payload: any, metadata?: any) => boolean);
|
|
5
5
|
export type EventPredicate = EventMatcher | ((buffer: Buffer) => boolean) | null;
|
|
6
6
|
|
|
7
|
+
export interface IndexEntry {
|
|
8
|
+
number: number;
|
|
9
|
+
position: number;
|
|
10
|
+
size: number;
|
|
11
|
+
partition: number;
|
|
12
|
+
}
|
|
7
13
|
export interface StreamIndexInfo {
|
|
8
14
|
length: number;
|
|
9
15
|
metadata?: Record<string, unknown> | null;
|
|
16
|
+
lastEntry: IndexEntry;
|
|
10
17
|
}
|
|
11
18
|
|
|
12
19
|
export interface StreamInfo {
|
|
@@ -30,6 +37,8 @@ export const ExpectedVersion: {
|
|
|
30
37
|
EmptyStream: 0;
|
|
31
38
|
};
|
|
32
39
|
|
|
40
|
+
export const VERSION: string;
|
|
41
|
+
|
|
33
42
|
export class EventStream extends Readable {
|
|
34
43
|
constructor(name: string, eventStore: EventStore, minRevision?: number, maxRevision?: number, predicate?: EventPredicate, raw?: boolean);
|
|
35
44
|
name: string;
|
|
@@ -93,6 +102,7 @@ export class Index {
|
|
|
93
102
|
export class EventStore extends EventEmitter {
|
|
94
103
|
static Storage: typeof Storage;
|
|
95
104
|
static Index: typeof Index;
|
|
105
|
+
static VERSION: string;
|
|
96
106
|
|
|
97
107
|
storage: Storage;
|
|
98
108
|
streams: Record<string, StreamInfo>;
|
package/index.js
CHANGED
|
@@ -1,6 +1,28 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
1
|
+
import packageJson from './package.json' with { type: 'json' };
|
|
2
|
+
import EventStore, { ExpectedVersion, OptimisticConcurrencyError, CommitCondition, LOCK_THROW, LOCK_RECLAIM } from './src/EventStore.js';
|
|
3
|
+
import EventStream from './src/EventStream.js';
|
|
4
|
+
import Storage, { StorageLockedError } from './src/Storage.js';
|
|
5
|
+
import Index from './src/Index.js';
|
|
6
|
+
import Consumer from './src/Consumer.js';
|
|
7
|
+
import { matches, buildRawBufferMatcher } from './src/utils/metadataUtil.js';
|
|
8
|
+
|
|
9
|
+
const VERSION = packageJson.version;
|
|
10
|
+
EventStore.VERSION = VERSION;
|
|
11
|
+
|
|
12
|
+
export {
|
|
13
|
+
EventStore,
|
|
14
|
+
EventStore as default,
|
|
15
|
+
ExpectedVersion,
|
|
16
|
+
OptimisticConcurrencyError,
|
|
17
|
+
CommitCondition,
|
|
18
|
+
LOCK_THROW,
|
|
19
|
+
LOCK_RECLAIM,
|
|
20
|
+
VERSION,
|
|
21
|
+
EventStream,
|
|
22
|
+
Storage,
|
|
23
|
+
StorageLockedError,
|
|
24
|
+
Index,
|
|
25
|
+
Consumer,
|
|
26
|
+
matches,
|
|
27
|
+
buildRawBufferMatcher
|
|
28
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "event-storage",
|
|
3
|
-
"version": "1.3.
|
|
3
|
+
"version": "1.3.3",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "An optimized embedded event store for node.js",
|
|
6
6
|
"keywords": [
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
"types": "./index.d.ts",
|
|
28
28
|
"scripts": {
|
|
29
29
|
"test": "c8 --reporter=lcov --reporter=text mocha test/*.spec.js",
|
|
30
|
-
"test:grep": "
|
|
30
|
+
"test:grep": "mocha test/*.spec.js --grep",
|
|
31
31
|
"coverage": "c8 report --reporter=text-lcov | coveralls"
|
|
32
32
|
},
|
|
33
33
|
"files": [
|
|
@@ -57,7 +57,7 @@
|
|
|
57
57
|
}
|
|
58
58
|
],
|
|
59
59
|
"engines": {
|
|
60
|
-
"node": ">=
|
|
60
|
+
"node": ">=20.0"
|
|
61
61
|
},
|
|
62
62
|
"dependencies": {
|
|
63
63
|
"mkdirp": "^3.0.1"
|
package/src/EventStore.js
CHANGED
|
@@ -7,7 +7,7 @@ import Storage, { ReadOnly as ReadOnlyStorage, LOCK_THROW, LOCK_RECLAIM } from '
|
|
|
7
7
|
import Index from './Index.js';
|
|
8
8
|
import Consumer from './Consumer.js';
|
|
9
9
|
import { assert, getPropertyAtPath } from './utils/util.js';
|
|
10
|
-
import { ensureDirectory, scanForFiles } from './utils/fsUtil.js';
|
|
10
|
+
import { ensureDirectory, resolvePath, scanForFiles } from './utils/fsUtil.js';
|
|
11
11
|
import { buildTypeMatcherFn } from './utils/metadataUtil.js';
|
|
12
12
|
import { fixCommitArgumentTypes, parseStreamFromIndexName, normalizePredicateRaw } from './utils/apiHelpers.js';
|
|
13
13
|
|
|
@@ -90,7 +90,7 @@ class EventStore extends events.EventEmitter {
|
|
|
90
90
|
this.typeMatcherFn = null;
|
|
91
91
|
}
|
|
92
92
|
|
|
93
|
-
this.storageDirectory =
|
|
93
|
+
this.storageDirectory = resolvePath(config.storageDirectory || /* istanbul ignore next */ './data');
|
|
94
94
|
let defaults = {
|
|
95
95
|
dataDirectory: this.storageDirectory,
|
|
96
96
|
indexDirectory: config.streamsDirectory || path.join(this.storageDirectory, 'streams'),
|
|
@@ -129,24 +129,36 @@ class EventStore extends events.EventEmitter {
|
|
|
129
129
|
* @param {object} storageConfig
|
|
130
130
|
*/
|
|
131
131
|
initialize(storeName, storageConfig) {
|
|
132
|
-
this.
|
|
133
|
-
|
|
132
|
+
this.storageConfig = storageConfig;
|
|
133
|
+
this.streamsDirectory = resolvePath(storageConfig.indexDirectory);
|
|
134
134
|
this.storeName = storeName;
|
|
135
|
-
this.storage = (storageConfig.readOnly === true) ?
|
|
136
|
-
new ReadOnlyStorage(storeName, storageConfig)
|
|
137
|
-
: new Storage(storeName, storageConfig);
|
|
138
|
-
this.streams = Object.create(null);
|
|
139
|
-
this.streams._all = { index: this.storage.index };
|
|
140
135
|
this.consumers = new Map();
|
|
141
136
|
|
|
142
|
-
|
|
137
|
+
const storage = storageConfig.readOnly === true
|
|
138
|
+
? new ReadOnlyStorage(storeName, storageConfig)
|
|
139
|
+
: new Storage(storeName, storageConfig);
|
|
143
140
|
|
|
144
|
-
this.storage
|
|
145
|
-
|
|
141
|
+
this.mountStorage(storage, () => {
|
|
142
|
+
if (storageConfig.readOnly !== true) {
|
|
143
|
+
this.checkUnfinishedCommits();
|
|
144
|
+
}
|
|
146
145
|
this.emit('ready');
|
|
147
146
|
});
|
|
147
|
+
}
|
|
148
148
|
|
|
149
|
-
|
|
149
|
+
/**
|
|
150
|
+
* Wire up a storage instance: reset the streams map, attach the index-created listener,
|
|
151
|
+
* register a one-shot opened handler, then open the storage.
|
|
152
|
+
* @private
|
|
153
|
+
* @param {ReadableStorage} storage
|
|
154
|
+
* @param {function} [onOpened] Called once when the storage is opened.
|
|
155
|
+
*/
|
|
156
|
+
mountStorage(storage, onOpened) {
|
|
157
|
+
this.storage = storage;
|
|
158
|
+
this.streams = Object.create(null);
|
|
159
|
+
this.streams._all = { index: this.storage.index };
|
|
160
|
+
this.storage.on('index-created', this.registerStream.bind(this));
|
|
161
|
+
this.storage.open(onOpened);
|
|
150
162
|
}
|
|
151
163
|
|
|
152
164
|
/**
|
|
@@ -231,6 +243,35 @@ class EventStore extends events.EventEmitter {
|
|
|
231
243
|
this.storage.close();
|
|
232
244
|
}
|
|
233
245
|
|
|
246
|
+
/**
|
|
247
|
+
* Flush all pending writes, then re-open the store in read-only mode.
|
|
248
|
+
* Any registered consumers are stopped. The `callback` is invoked once the
|
|
249
|
+
* new read-only storage has finished opening.
|
|
250
|
+
*
|
|
251
|
+
* Does not re-emit `'ready'` — use the callback to react to the transition.
|
|
252
|
+
*
|
|
253
|
+
* @api
|
|
254
|
+
* @param {function} [callback] Called when the store is ready in read-only mode.
|
|
255
|
+
*/
|
|
256
|
+
makeReadOnly(callback) {
|
|
257
|
+
if (this.storage instanceof ReadOnlyStorage) {
|
|
258
|
+
callback?.();
|
|
259
|
+
return
|
|
260
|
+
}
|
|
261
|
+
for (const consumer of this.consumers.values()) {
|
|
262
|
+
consumer.stop();
|
|
263
|
+
}
|
|
264
|
+
this.consumers.clear();
|
|
265
|
+
|
|
266
|
+
this.storage.flush();
|
|
267
|
+
this.storage.close();
|
|
268
|
+
|
|
269
|
+
const readOnlyConfig = Object.assign({}, this.storageConfig, { readOnly: true });
|
|
270
|
+
this.storageConfig = readOnlyConfig;
|
|
271
|
+
|
|
272
|
+
this.mountStorage(new ReadOnlyStorage(this.storeName, readOnlyConfig), callback);
|
|
273
|
+
}
|
|
274
|
+
|
|
234
275
|
/**
|
|
235
276
|
* Override EventEmitter.on() to delegate 'preCommit' and 'preRead' event registrations
|
|
236
277
|
* to the underlying storage, so that `eventstore.on('preCommit', handler)` works naturally.
|
|
@@ -614,12 +655,6 @@ class EventStore extends events.EventEmitter {
|
|
|
614
655
|
assert(stream in this.streams, `Stream "${stream}" does not exist.`);
|
|
615
656
|
}
|
|
616
657
|
|
|
617
|
-
if (streamNames.length === 1) {
|
|
618
|
-
const stream = new EventStream(streamNames[0], this, minRevision, maxRevision, predicate, raw);
|
|
619
|
-
stream.name = streamName;
|
|
620
|
-
return stream;
|
|
621
|
-
}
|
|
622
|
-
|
|
623
658
|
return new JoinEventStream(streamName, streamNames, this, minRevision, maxRevision, predicate, raw);
|
|
624
659
|
}
|
|
625
660
|
|
|
@@ -13,6 +13,19 @@ class ReadOnlyIndex extends watchesFile(ReadableIndex) {
|
|
|
13
13
|
*/
|
|
14
14
|
constructor(name, options) {
|
|
15
15
|
super(name, options);
|
|
16
|
+
this.syncOnMissingWatchFilename = !!options?.syncOnMissingWatchFilename;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @private
|
|
21
|
+
* @param {string} filename
|
|
22
|
+
* @returns {boolean}
|
|
23
|
+
*/
|
|
24
|
+
watchFileFilter(filename) {
|
|
25
|
+
if (!filename) {
|
|
26
|
+
return this.syncOnMissingWatchFilename && this.readFileLength() !== this.data.length;
|
|
27
|
+
}
|
|
28
|
+
return filename === this.name;
|
|
16
29
|
}
|
|
17
30
|
|
|
18
31
|
/**
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import fs from 'fs';
|
|
2
|
-
import path from 'path';
|
|
3
2
|
import events from 'events';
|
|
4
3
|
import Entry, { assertValidEntryClass } from '../IndexEntry.js';
|
|
5
4
|
import { assert, wrapAndCheck, binarySearch } from '../utils/util.js';
|
|
6
5
|
import { normalizeNamedCtorArgs } from '../utils/apiHelpers.js';
|
|
6
|
+
import { resolvePath } from "../utils/fsUtil.js";
|
|
7
7
|
|
|
8
8
|
// node-event-store-index V01
|
|
9
9
|
const HEADER_MAGIC = "nesidx01";
|
|
@@ -69,7 +69,7 @@ class ReadableIndex extends events.EventEmitter {
|
|
|
69
69
|
this.fileMode = 'r';
|
|
70
70
|
this.EntryClass = options.EntryClass;
|
|
71
71
|
this.dataDirectory = options.dataDirectory;
|
|
72
|
-
this.fileName =
|
|
72
|
+
this.fileName = resolvePath(options.dataDirectory, this.name);
|
|
73
73
|
this.readBuffer = Buffer.allocUnsafe(Math.max(options.EntryClass.size, options.writeBufferSize > 0 ? options.writeBufferSize : 4096));
|
|
74
74
|
|
|
75
75
|
if (options.metadata) {
|
|
@@ -128,6 +128,7 @@ class ReadableIndex extends events.EventEmitter {
|
|
|
128
128
|
stat.size -= this.readMetadata();
|
|
129
129
|
assert(stat.size >= 0, 'Invalid index file!');
|
|
130
130
|
|
|
131
|
+
this.crtime = stat.birthtimeMs;
|
|
131
132
|
const length = Math.floor(stat.size / this.EntryClass.size);
|
|
132
133
|
assert(stat.size === length * this.EntryClass.size, 'Index file is corrupt!', CorruptedIndexErrorFactory(length));
|
|
133
134
|
|
|
@@ -2,6 +2,7 @@ import fs from 'fs';
|
|
|
2
2
|
import path from 'path';
|
|
3
3
|
import events from 'events';
|
|
4
4
|
import { assert, alignTo, hash, binarySearch } from '../utils/util.js';
|
|
5
|
+
import { resolvePath } from "../utils/fsUtil.js";
|
|
5
6
|
|
|
6
7
|
|
|
7
8
|
|
|
@@ -50,7 +51,7 @@ class ReadablePartition extends events.EventEmitter {
|
|
|
50
51
|
readBufferSize: DEFAULT_READ_BUFFER_SIZE
|
|
51
52
|
};
|
|
52
53
|
config = Object.assign(defaults, config);
|
|
53
|
-
this.dataDirectory =
|
|
54
|
+
this.dataDirectory = resolvePath(config.dataDirectory);
|
|
54
55
|
|
|
55
56
|
this.name = name;
|
|
56
57
|
this.id = ReadablePartition.idFor(name);
|
|
@@ -155,6 +156,7 @@ class ReadablePartition extends events.EventEmitter {
|
|
|
155
156
|
*/
|
|
156
157
|
readFileSize() {
|
|
157
158
|
const stat = fs.statSync(this.fileName);
|
|
159
|
+
this.crtime = stat.birthtimeMs;
|
|
158
160
|
return stat.size - this.headerSize;
|
|
159
161
|
}
|
|
160
162
|
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import ReadableStorage from './ReadableStorage.js';
|
|
2
|
-
import ReadablePartition from '../Partition/ReadablePartition.js';
|
|
3
2
|
import Watcher from '../Watcher.js';
|
|
4
3
|
|
|
4
|
+
const DEFAULT_SCAN_DELAY_MS = 10;
|
|
5
|
+
|
|
5
6
|
/**
|
|
6
7
|
* An append-only storage with highly performant positional range scans.
|
|
7
8
|
* It's highly optimized for an event-store and hence does not support compaction or data-rewrite, nor any querying
|
|
@@ -23,7 +24,10 @@ class ReadOnlyStorage extends ReadableStorage {
|
|
|
23
24
|
* @returns {boolean}
|
|
24
25
|
*/
|
|
25
26
|
storageFilesFilter(filename) {
|
|
26
|
-
|
|
27
|
+
if (!filename) {
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
30
|
+
return !filename.endsWith('.branch') && (filename === this.storageFile || filename.substring(0, this.storageFile.length + 1) === this.storageFile + '.');
|
|
27
31
|
}
|
|
28
32
|
|
|
29
33
|
/**
|
|
@@ -31,14 +35,41 @@ class ReadOnlyStorage extends ReadableStorage {
|
|
|
31
35
|
* Will emit an 'opened' event if finished.
|
|
32
36
|
*
|
|
33
37
|
* @api
|
|
38
|
+
* @param {function(): void} [callback] Called after indexes open, before `'opened'` is emitted.
|
|
39
|
+
* Can be used as a synchronous alternative to listening to the `'opened'` event.
|
|
34
40
|
* @returns {boolean}
|
|
35
41
|
*/
|
|
36
|
-
open() {
|
|
42
|
+
open(callback) {
|
|
37
43
|
if (!this.watcher) {
|
|
38
44
|
this.watcher = new Watcher([this.dataDirectory, this.indexDirectory], this.storageFilesFilter);
|
|
39
45
|
this.watcher.on('rename', this.onStorageFileChanged);
|
|
46
|
+
// Emit change events without filename as a signal to resync
|
|
47
|
+
this.watcher.on('change', (filename) => !filename && this.scheduleScan());
|
|
48
|
+
}
|
|
49
|
+
return super.open(callback);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Schedule a fresh scan of the filesystem to get the ReadOnly instance in sync.
|
|
54
|
+
* Scheduling will be throttled so multiple calls will not cause multiple scan operations.
|
|
55
|
+
* Note though that the callback will not be deduplicated, so calling this repeatedly with the same callback will
|
|
56
|
+
* lead to this callback being executed multiple times once the scan is finished.
|
|
57
|
+
*
|
|
58
|
+
* @param {function} [callback] If provided, will be added to the callbacks invoked after the next full scan.
|
|
59
|
+
* @param {number} [time=SCAN_DELAY_MS] The delay in ms to schedule the scan for
|
|
60
|
+
*/
|
|
61
|
+
scheduleScan(callback, time = DEFAULT_SCAN_DELAY_MS) {
|
|
62
|
+
if (typeof callback === 'function') {
|
|
63
|
+
this.onScanFinished = this.onScanFinished || [];
|
|
64
|
+
this.onScanFinished.push(callback);
|
|
40
65
|
}
|
|
41
|
-
|
|
66
|
+
this.scanSchedule = this.scanSchedule || setTimeout(() =>
|
|
67
|
+
this.scanFiles(() => {
|
|
68
|
+
this.scanSchedule = null;
|
|
69
|
+
const callbacks = this.onScanFinished || [];
|
|
70
|
+
this.onScanFinished = [];
|
|
71
|
+
callbacks.forEach(callback => callback());
|
|
72
|
+
}), typeof callback === 'number' ? callback : time);
|
|
42
73
|
}
|
|
43
74
|
|
|
44
75
|
/**
|
|
@@ -46,6 +77,9 @@ class ReadOnlyStorage extends ReadableStorage {
|
|
|
46
77
|
* @param {string} filename
|
|
47
78
|
*/
|
|
48
79
|
onStorageFileChanged(filename) {
|
|
80
|
+
if (!filename) {
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
49
83
|
if (filename.endsWith('.index')) {
|
|
50
84
|
const indexName = filename.substring(this.storageFile.length + 1, filename.length - 6);
|
|
51
85
|
// New indexes are not automatically opened in the reader
|
|
@@ -53,12 +87,7 @@ class ReadOnlyStorage extends ReadableStorage {
|
|
|
53
87
|
return;
|
|
54
88
|
}
|
|
55
89
|
|
|
56
|
-
|
|
57
|
-
if (!this.partitions.has(partitionId)) {
|
|
58
|
-
const partition = this.createPartition(filename, this.partitionConfig);
|
|
59
|
-
this.partitions.add(partition.id, partition);
|
|
60
|
-
this.emit('partition-created', partition.id);
|
|
61
|
-
}
|
|
90
|
+
this.registerPartitionFile(filename);
|
|
62
91
|
}
|
|
63
92
|
|
|
64
93
|
/**
|
|
@@ -69,6 +98,11 @@ class ReadOnlyStorage extends ReadableStorage {
|
|
|
69
98
|
* @returns void
|
|
70
99
|
*/
|
|
71
100
|
close() {
|
|
101
|
+
if (this.scanSchedule) {
|
|
102
|
+
clearTimeout(this.scanSchedule);
|
|
103
|
+
this.scanSchedule = null;
|
|
104
|
+
}
|
|
105
|
+
this.onScanFinished = [];
|
|
72
106
|
if (this.watcher) {
|
|
73
107
|
this.watcher.close();
|
|
74
108
|
this.watcher = null;
|
|
@@ -95,14 +129,7 @@ class ReadOnlyStorage extends ReadableStorage {
|
|
|
95
129
|
if (entries === false) {
|
|
96
130
|
return;
|
|
97
131
|
}
|
|
98
|
-
|
|
99
|
-
const document = this.readFrom(entry.partition, entry.position, entry.size);
|
|
100
|
-
if (index === this.index) {
|
|
101
|
-
this.emit('wrote', document, entry, entry.position);
|
|
102
|
-
} else {
|
|
103
|
-
this.emit('index-add', indexShortName, entry.number, document);
|
|
104
|
-
}
|
|
105
|
-
}
|
|
132
|
+
this.processAppendedEntries(index, indexShortName, entries);
|
|
106
133
|
});
|
|
107
134
|
index.on('truncate', (prevLength, newLength) => {
|
|
108
135
|
if (index === this.index) {
|
|
@@ -111,6 +138,53 @@ class ReadOnlyStorage extends ReadableStorage {
|
|
|
111
138
|
});
|
|
112
139
|
return { index };
|
|
113
140
|
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Emit `'wrote'` / `'index-add'` for each appended index entry.
|
|
144
|
+
*
|
|
145
|
+
* If an entry references a partition that has not been registered yet (the partition-creation
|
|
146
|
+
* watch event is still pending), the remaining entries are re-processed on the next tick instead
|
|
147
|
+
* of throwing a hard `Partition #… does not exist.` error out of the synchronous emit path.
|
|
148
|
+
*
|
|
149
|
+
* @private
|
|
150
|
+
* @param {ReadableIndex} index
|
|
151
|
+
* @param {string} indexShortName
|
|
152
|
+
* @param {IndexEntry[]} entries
|
|
153
|
+
* @param {number} [startIndex] The entry offset to resume from on a retry.
|
|
154
|
+
*/
|
|
155
|
+
processAppendedEntries(index, indexShortName, entries, startIndex = 0) {
|
|
156
|
+
for (let i = startIndex; i < entries.length; i++) {
|
|
157
|
+
const entry = entries[i];
|
|
158
|
+
if (!this.partitions.has(entry.partition)) {
|
|
159
|
+
this.scheduleScan(() => {
|
|
160
|
+
this.processAppendedEntries(index, indexShortName, entries, i);
|
|
161
|
+
});
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
this.emitAppendedEntry(index, indexShortName, entry);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Read a single appended entry and emit the corresponding event.
|
|
170
|
+
* A read failure is surfaced as an `'error'` event (when observed) rather than crashing the reader.
|
|
171
|
+
* @private
|
|
172
|
+
*/
|
|
173
|
+
emitAppendedEntry(index, indexShortName, entry) {
|
|
174
|
+
let document;
|
|
175
|
+
try {
|
|
176
|
+
document = this.readFrom(entry.partition, entry.position, entry.size);
|
|
177
|
+
} catch (error) {
|
|
178
|
+
/* c8 ignore next */
|
|
179
|
+
this.emit('error', error);
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
if (index === this.index) {
|
|
183
|
+
this.emit('wrote', document, entry, entry.position);
|
|
184
|
+
} else {
|
|
185
|
+
this.emit('index-add', indexShortName, entry.number, document);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
114
188
|
}
|
|
115
189
|
|
|
116
190
|
export default ReadOnlyStorage;
|
|
@@ -4,11 +4,12 @@ import events from 'events';
|
|
|
4
4
|
import { ReadOnly as ReadOnlyPartition } from '../Partition.js';
|
|
5
5
|
import { ReadOnly as ReadOnlyIndex } from '../Index.js';
|
|
6
6
|
import { assert, wrapAndCheck, iterate, kWayMerge } from '../utils/util.js';
|
|
7
|
-
import { scanForFiles } from '../utils/fsUtil.js';
|
|
7
|
+
import { resolvePath, scanForFiles } from '../utils/fsUtil.js';
|
|
8
8
|
import { createHmac, matches, buildMetadataForMatcher } from '../utils/metadataUtil.js';
|
|
9
9
|
import { normalizeNamedCtorArgs } from '../utils/apiHelpers.js';
|
|
10
10
|
import IndexMatcher from '../IndexMatcher.js';
|
|
11
11
|
import PartitionPool from '../PartitionPool.js';
|
|
12
|
+
import ReadablePartition from "../Partition/ReadablePartition.js";
|
|
12
13
|
|
|
13
14
|
const DEFAULT_READ_BUFFER_SIZE = 4 * 1024;
|
|
14
15
|
|
|
@@ -78,7 +79,7 @@ class ReadableStorage extends events.EventEmitter {
|
|
|
78
79
|
|
|
79
80
|
this.hmac = createHmac(config.hmacSecret);
|
|
80
81
|
|
|
81
|
-
this.dataDirectory =
|
|
82
|
+
this.dataDirectory = resolvePath(config.dataDirectory);
|
|
82
83
|
|
|
83
84
|
const partitionDefaults = { readBufferSize: DEFAULT_READ_BUFFER_SIZE };
|
|
84
85
|
this.partitionConfig = Object.assign(partitionDefaults, config);
|
|
@@ -120,13 +121,13 @@ class ReadableStorage extends events.EventEmitter {
|
|
|
120
121
|
* @returns void
|
|
121
122
|
*/
|
|
122
123
|
initializeIndexes(config) {
|
|
123
|
-
this.indexDirectory =
|
|
124
|
+
this.indexDirectory = resolvePath(config.indexDirectory || this.dataDirectory);
|
|
124
125
|
|
|
125
126
|
this.indexOptions = config.indexOptions;
|
|
126
127
|
this.indexOptions.dataDirectory = this.indexDirectory;
|
|
127
128
|
// Safety precaution to prevent accidentally restricting main index
|
|
128
129
|
delete this.indexOptions.matcher;
|
|
129
|
-
const { index } = this.createIndex(config.indexFile, this.indexOptions);
|
|
130
|
+
const { index } = this.createIndex(config.indexFile, Object.assign({}, this.indexOptions, { syncOnMissingWatchFilename: true }));
|
|
130
131
|
this.index = index;
|
|
131
132
|
this.secondaryIndexes = {};
|
|
132
133
|
this.readonlyIndexes = {};
|
|
@@ -143,6 +144,24 @@ class ReadableStorage extends events.EventEmitter {
|
|
|
143
144
|
return this.index.length;
|
|
144
145
|
}
|
|
145
146
|
|
|
147
|
+
/**
|
|
148
|
+
* Register a partition by its relative file name if it is not already known.
|
|
149
|
+
* Shared by the file-watch path and the initial scan so both stay consistent.
|
|
150
|
+
*
|
|
151
|
+
* @protected
|
|
152
|
+
* @param {string} filename
|
|
153
|
+
* @returns {number} The id of the (now registered) partition.
|
|
154
|
+
*/
|
|
155
|
+
registerPartitionFile(filename) {
|
|
156
|
+
const partitionId = ReadablePartition.idFor(filename);
|
|
157
|
+
if (!this.partitions.has(partitionId)) {
|
|
158
|
+
const partition = this.createPartition(filename, this.partitionConfig);
|
|
159
|
+
this.partitions.add(partition.id, partition);
|
|
160
|
+
this.emit('partition-created', partition.id);
|
|
161
|
+
}
|
|
162
|
+
return partitionId;
|
|
163
|
+
}
|
|
164
|
+
|
|
146
165
|
/**
|
|
147
166
|
* Scan partitions and secondary index files; emit 'index-created' for each found index.
|
|
148
167
|
* @param {function} done Called when both scans finish.
|
|
@@ -152,8 +171,7 @@ class ReadableStorage extends events.EventEmitter {
|
|
|
152
171
|
const partitionPattern = new RegExp(`^(${escaped}.*)$`);
|
|
153
172
|
scanForFiles(this.dataDirectory, partitionPattern, (file) => {
|
|
154
173
|
if (file.endsWith('.index') || file.endsWith('.branch') || file.endsWith('.lock')) return;
|
|
155
|
-
|
|
156
|
-
this.partitions.add(partition.id, partition);
|
|
174
|
+
this.registerPartitionFile(file);
|
|
157
175
|
}, (partErr) => {
|
|
158
176
|
/* c8 ignore next */
|
|
159
177
|
if (partErr) throw partErr;
|
|
@@ -167,7 +185,9 @@ class ReadableStorage extends events.EventEmitter {
|
|
|
167
185
|
}
|
|
168
186
|
const indexPattern = new RegExp(`^${escaped}\\.(.+)\\.index$`);
|
|
169
187
|
scanForFiles(this.indexDirectory, indexPattern, (name) => {
|
|
170
|
-
this.
|
|
188
|
+
if (!(name in this.secondaryIndexes)) {
|
|
189
|
+
this.emit('index-created', name);
|
|
190
|
+
}
|
|
171
191
|
}, (indexErr) => {
|
|
172
192
|
// The directory could disappear between existsSync and readdir (e.g. test cleanup).
|
|
173
193
|
/* c8 ignore next */
|
|
@@ -66,11 +66,12 @@ class WritableStorage extends ReadableStorage {
|
|
|
66
66
|
}
|
|
67
67
|
|
|
68
68
|
/**
|
|
69
|
-
* @inheritDoc
|
|
70
69
|
* Acquires the write lock synchronously.
|
|
71
70
|
* For LOCK_RECLAIM, removes any orphaned lock before trying to acquire our own; torn-write
|
|
72
71
|
* repair runs after the primary index is open, before `'opened'` is emitted.
|
|
73
72
|
*
|
|
73
|
+
* @param {function(): void} [callback] Called after indexes open, before `'opened'` is emitted.
|
|
74
|
+
* Can be used as a synchronous alternative to listening to the `'opened'` event.
|
|
74
75
|
* @returns {boolean}
|
|
75
76
|
* @throws {StorageLockedError} If this storage is locked by another process.
|
|
76
77
|
*/
|
package/src/Watcher.js
CHANGED
|
@@ -2,6 +2,7 @@ import fs from 'fs';
|
|
|
2
2
|
import path from 'path';
|
|
3
3
|
import events from 'events';
|
|
4
4
|
import { assert } from './utils/util.js';
|
|
5
|
+
import { isSameOrParentDirectory } from "./utils/fsUtil.js";
|
|
5
6
|
|
|
6
7
|
/** @type {Map<string, DirectoryWatcher>} */
|
|
7
8
|
const directoryWatchers = new Map();
|
|
@@ -10,7 +11,91 @@ const directoryWatchers = new Map();
|
|
|
10
11
|
* A reference counting singleton nodejs watcher for directories.
|
|
11
12
|
* Emits events 'change' and 'rename' with the file name as argument.
|
|
12
13
|
*/
|
|
13
|
-
class DirectoryWatcher
|
|
14
|
+
class DirectoryWatcher {
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Register a handler with optional filename resolver.
|
|
18
|
+
*
|
|
19
|
+
* @param {function(string, string): void} handler
|
|
20
|
+
* @param {function(string, string): string|null} [filenameResolver]
|
|
21
|
+
*/
|
|
22
|
+
registerHandler(handler, filenameResolver = null) {
|
|
23
|
+
this.subscriptions.set(handler, typeof filenameResolver === 'function' ? filenameResolver : null);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Unregister a previously added handler.
|
|
28
|
+
*
|
|
29
|
+
* @param {function(string, string): void} handler
|
|
30
|
+
*/
|
|
31
|
+
unregisterHandler(handler) {
|
|
32
|
+
this.subscriptions.delete(handler);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Dispatch an fs event to matching subscribers.
|
|
37
|
+
*
|
|
38
|
+
* @private
|
|
39
|
+
* @param {'change'|'rename'} eventType
|
|
40
|
+
* @param {string} filename
|
|
41
|
+
*/
|
|
42
|
+
dispatch(eventType, filename) {
|
|
43
|
+
for (const [handler, filenameResolver] of this.subscriptions) {
|
|
44
|
+
const resolvedFilename = filenameResolver ? filenameResolver(filename, eventType) : filename;
|
|
45
|
+
if (resolvedFilename === null || resolvedFilename === undefined) {
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
handler(eventType, resolvedFilename);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Normalize fs.watch filenames to be relative to the watched directory.
|
|
54
|
+
* On Windows recursive watches may yield absolute `\\?\` names or directory names.
|
|
55
|
+
*
|
|
56
|
+
* @private
|
|
57
|
+
* @param {string|Buffer|null} filename
|
|
58
|
+
* @returns {string}
|
|
59
|
+
*/
|
|
60
|
+
normalizeFilename(filename) {
|
|
61
|
+
if (!filename) return '';
|
|
62
|
+
if (Buffer.isBuffer(filename)) {
|
|
63
|
+
filename = filename.toString();
|
|
64
|
+
}
|
|
65
|
+
if (typeof filename !== 'string' || filename.length === 0) {
|
|
66
|
+
return '';
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const stripped = filename
|
|
70
|
+
.replace(/^\\\\\?\\UNC\\/i, '\\\\')
|
|
71
|
+
.replace(/^\\\\\?\\/, '');
|
|
72
|
+
filename = path.normalize(stripped);
|
|
73
|
+
|
|
74
|
+
if (path.isAbsolute(filename)) {
|
|
75
|
+
filename = path.relative(this.directory, filename);
|
|
76
|
+
}
|
|
77
|
+
if (!filename || filename === '.') {
|
|
78
|
+
return '';
|
|
79
|
+
}
|
|
80
|
+
return filename.replace(/\\/g, '/');
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Forward fs.watch events with normalized filenames.
|
|
85
|
+
*
|
|
86
|
+
* @private
|
|
87
|
+
* @param {string} eventType
|
|
88
|
+
* @param {string|Buffer|null} filename
|
|
89
|
+
*/
|
|
90
|
+
onFsEvent(eventType, filename) {
|
|
91
|
+
const normalized = this.normalizeFilename(filename);
|
|
92
|
+
if (eventType === 'rename' && !filename) {
|
|
93
|
+
// Close if the watched directory was removed
|
|
94
|
+
this.close();
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
this.dispatch(eventType, normalized);
|
|
98
|
+
}
|
|
14
99
|
|
|
15
100
|
/**
|
|
16
101
|
* @param {string} directory
|
|
@@ -18,20 +103,22 @@ class DirectoryWatcher extends events.EventEmitter {
|
|
|
18
103
|
* @returns {DirectoryWatcher}
|
|
19
104
|
*/
|
|
20
105
|
constructor(directory, options = {}) {
|
|
21
|
-
|
|
106
|
+
const watchOptions = Object.assign({ recursive: true }, options);
|
|
107
|
+
const watcherKey = `${directory}|r:${watchOptions.recursive}`;
|
|
22
108
|
|
|
23
|
-
if (directoryWatchers.has(
|
|
24
|
-
const watcher = directoryWatchers.get(
|
|
109
|
+
if (directoryWatchers.has(watcherKey)) {
|
|
110
|
+
const watcher = directoryWatchers.get(watcherKey);
|
|
25
111
|
watcher.references++;
|
|
26
112
|
return watcher;
|
|
27
113
|
}
|
|
28
114
|
assert(fs.existsSync(directory), `Can not watch a non-existing directory "${directory}".`);
|
|
29
115
|
assert(fs.statSync(directory).isDirectory(), `Can only watch directories, but "${directory}" is none.`);
|
|
30
|
-
|
|
31
|
-
this.
|
|
32
|
-
directoryWatchers.set(directory, this);
|
|
116
|
+
directoryWatchers.set(watcherKey, this);
|
|
117
|
+
this.watcherKey = watcherKey;
|
|
33
118
|
this.directory = directory;
|
|
34
|
-
this.
|
|
119
|
+
this.subscriptions = new Map();
|
|
120
|
+
this.onFsEvent = this.onFsEvent.bind(this);
|
|
121
|
+
this.watcher = fs.watch(directory, watchOptions, this.onFsEvent);
|
|
35
122
|
this.references = 1;
|
|
36
123
|
}
|
|
37
124
|
|
|
@@ -44,91 +131,150 @@ class DirectoryWatcher extends events.EventEmitter {
|
|
|
44
131
|
if (this.references === 0 && this.watcher) {
|
|
45
132
|
this.watcher.close();
|
|
46
133
|
this.watcher = null;
|
|
47
|
-
directoryWatchers.delete(this.
|
|
134
|
+
directoryWatchers.delete(this.watcherKey);
|
|
48
135
|
}
|
|
49
136
|
}
|
|
50
137
|
|
|
51
138
|
}
|
|
52
139
|
|
|
140
|
+
const VALID_WATCH_EVENT_TYPES = ['change', 'rename'];
|
|
141
|
+
|
|
53
142
|
/**
|
|
54
143
|
* A watcher for a single file or a directory, with the possibility to provide a filter method for file names to watch.
|
|
55
144
|
*/
|
|
56
|
-
class Watcher {
|
|
145
|
+
class Watcher extends events.EventEmitter {
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Remove redundant nested directories so each tree is watched only once.
|
|
149
|
+
*
|
|
150
|
+
* @private
|
|
151
|
+
* @param {string[]} directories
|
|
152
|
+
* @param {boolean} recursive
|
|
153
|
+
* @returns {[string[], string[]]} Tuple of [watchedDirectories, removedRelativePrefixes]
|
|
154
|
+
*/
|
|
155
|
+
static deduplicateDirectories(directories, recursive = true) {
|
|
156
|
+
const normalized = [...new Set(directories)];
|
|
157
|
+
if (!recursive) {
|
|
158
|
+
return [normalized, []];
|
|
159
|
+
}
|
|
160
|
+
normalized.sort((a, b) => a.length - b.length);
|
|
161
|
+
const deduplicated = [];
|
|
162
|
+
const removedRelativePrefixes = new Set();
|
|
163
|
+
for (const directory of normalized) {
|
|
164
|
+
const parent = deduplicated.find(current => isSameOrParentDirectory(current, directory));
|
|
165
|
+
if (parent) {
|
|
166
|
+
const relative = path.relative(parent, directory).replace(/\\/g, '/');
|
|
167
|
+
if (relative && relative !== '.') {
|
|
168
|
+
removedRelativePrefixes.add(relative);
|
|
169
|
+
}
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
deduplicated.push(directory);
|
|
173
|
+
}
|
|
174
|
+
return [deduplicated, [...removedRelativePrefixes]];
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Resolve a filename to a path relative to the longest matching watched prefix.
|
|
179
|
+
*
|
|
180
|
+
* @private
|
|
181
|
+
* @param {string} filename
|
|
182
|
+
* @returns {string}
|
|
183
|
+
*/
|
|
184
|
+
resolveRelativeFilename(filename) {
|
|
185
|
+
filename = path.normalize(filename).replace(/\\/g, '/');
|
|
186
|
+
for (const prefix of this.relativePrefixes) {
|
|
187
|
+
if (filename === prefix) {
|
|
188
|
+
return '';
|
|
189
|
+
}
|
|
190
|
+
const withSeparator = prefix + '/';
|
|
191
|
+
if (filename.startsWith(withSeparator)) {
|
|
192
|
+
return filename.slice(withSeparator.length);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
return filename;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Resolve the final filename used for matching and emitting.
|
|
200
|
+
* Returns `null` when the filename is filtered out.
|
|
201
|
+
*
|
|
202
|
+
* @private
|
|
203
|
+
* @param {string} filename
|
|
204
|
+
* @returns {string|null}
|
|
205
|
+
*/
|
|
206
|
+
resolveFilename(filename) {
|
|
207
|
+
if (!filename) {
|
|
208
|
+
if (!this.fileFilter(filename)) {
|
|
209
|
+
return null;
|
|
210
|
+
}
|
|
211
|
+
return this.fixedFilename || '';
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
filename = this.resolveRelativeFilename(filename);
|
|
215
|
+
|
|
216
|
+
if (!this.fileFilter(filename)) {
|
|
217
|
+
return null;
|
|
218
|
+
}
|
|
219
|
+
return filename;
|
|
220
|
+
}
|
|
57
221
|
|
|
58
222
|
/**
|
|
59
223
|
* @param {string|string[]} fileOrDirectory The filename or directory or list of directories to watch
|
|
60
|
-
* @param {function(string): boolean} [fileFilter] A filter that will receive a filename and needs to return true if this watcher should be invoked.
|
|
224
|
+
* @param {function(string): boolean} [fileFilter] A filter that will receive a filename and needs to return true if this watcher should be invoked.
|
|
225
|
+
* @param {object|null} [options] Internal watcher options.
|
|
226
|
+
* @param {boolean} [options.recursive=true] Whether directories are watched recursively.
|
|
227
|
+
* @param {string} [options.rootDirectory] Root directory used to relativize single-file watcher events.
|
|
61
228
|
* @returns {Watcher}
|
|
62
229
|
*/
|
|
63
|
-
constructor(fileOrDirectory, fileFilter = null) {
|
|
230
|
+
constructor(fileOrDirectory, fileFilter = null, options = null) {
|
|
231
|
+
super();
|
|
232
|
+
const watchOptions = Object.assign({ recursive: true }, options);
|
|
233
|
+
delete watchOptions.rootDirectory;
|
|
234
|
+
this.relativePrefixes = [];
|
|
64
235
|
let directories;
|
|
65
236
|
if (typeof fileOrDirectory === 'string') {
|
|
66
237
|
directories = [fileOrDirectory];
|
|
67
238
|
if (!fs.statSync(fileOrDirectory).isDirectory()) {
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
239
|
+
const rootDirectory = options?.rootDirectory || path.dirname(fileOrDirectory);
|
|
240
|
+
|
|
241
|
+
directories = [rootDirectory];
|
|
242
|
+
this.fixedFilename = path.relative(rootDirectory, fileOrDirectory).replace(/\\/g, '/');
|
|
243
|
+
if (fileFilter === null) {
|
|
244
|
+
fileFilter = changedFilename => changedFilename === this.fixedFilename;
|
|
245
|
+
}
|
|
71
246
|
}
|
|
72
247
|
} else {
|
|
73
|
-
|
|
248
|
+
this.fixedFilename = null;
|
|
249
|
+
const [deduplicatedDirectories, removedRelativePrefixes] = Watcher.deduplicateDirectories(fileOrDirectory, watchOptions.recursive);
|
|
250
|
+
directories = deduplicatedDirectories;
|
|
251
|
+
this.relativePrefixes = removedRelativePrefixes.sort((a, b) => b.length - a.length);
|
|
74
252
|
}
|
|
75
253
|
|
|
76
|
-
this.watchers = directories.map(dir => new DirectoryWatcher(dir));
|
|
254
|
+
this.watchers = directories.map(dir => new DirectoryWatcher(dir, watchOptions));
|
|
77
255
|
|
|
78
256
|
if (fileFilter === null) {
|
|
79
257
|
fileFilter = () => true;
|
|
80
258
|
}
|
|
81
259
|
|
|
82
260
|
this.fileFilter = fileFilter;
|
|
83
|
-
this.
|
|
84
|
-
this.
|
|
261
|
+
this.resolveFilename = this.resolveFilename.bind(this);
|
|
262
|
+
this.emitHandler = this.emit.bind(this);
|
|
85
263
|
this.watchers.forEach(watcher => {
|
|
86
|
-
watcher.
|
|
87
|
-
watcher.on('rename', this.onRename);
|
|
264
|
+
watcher.registerHandler(this.emitHandler, this.resolveFilename);
|
|
88
265
|
});
|
|
89
|
-
this.handlers = { change: [], rename: [] };
|
|
90
266
|
}
|
|
91
267
|
|
|
92
268
|
/**
|
|
93
|
-
*
|
|
269
|
+
* Override to validate against allowed event types.
|
|
270
|
+
* @override
|
|
94
271
|
* @param {string} eventType
|
|
95
|
-
* @param {function
|
|
96
|
-
* @
|
|
97
|
-
*/
|
|
98
|
-
on(eventType, handler) {
|
|
99
|
-
assert(eventType in this.handlers, `Event type ${eventType} is unknown. Only 'change' and 'rename' are supported.`);
|
|
100
|
-
|
|
101
|
-
this.handlers[eventType].push(handler);
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
/**
|
|
105
|
-
* @private
|
|
106
|
-
* @param {string} filename
|
|
107
|
-
*/
|
|
108
|
-
onChange(filename) {
|
|
109
|
-
if (this.handlers.change.length === 0) {
|
|
110
|
-
return;
|
|
111
|
-
}
|
|
112
|
-
if (!filename || !this.fileFilter(filename)) {
|
|
113
|
-
return;
|
|
114
|
-
}
|
|
115
|
-
this.handlers.change
|
|
116
|
-
.forEach((handler) => handler(filename));
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
/**
|
|
120
|
-
* @private
|
|
121
|
-
* @param {string} filename
|
|
272
|
+
* @param {function} listener
|
|
273
|
+
* @returns {Watcher}
|
|
122
274
|
*/
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
}
|
|
127
|
-
if (!filename || !this.fileFilter(filename)) {
|
|
128
|
-
return;
|
|
129
|
-
}
|
|
130
|
-
this.handlers.rename
|
|
131
|
-
.forEach((handler) => handler(filename));
|
|
275
|
+
on(eventType, listener) {
|
|
276
|
+
assert(VALID_WATCH_EVENT_TYPES.includes(eventType), `Event type ${eventType} is unknown. Only 'change' and 'rename' are supported.`);
|
|
277
|
+
return super.on(eventType, listener);
|
|
132
278
|
}
|
|
133
279
|
|
|
134
280
|
/**
|
|
@@ -137,12 +283,11 @@ class Watcher {
|
|
|
137
283
|
*/
|
|
138
284
|
close() {
|
|
139
285
|
this.watchers.forEach(watcher => {
|
|
140
|
-
watcher.
|
|
141
|
-
watcher.removeListener('rename', this.onRename);
|
|
286
|
+
watcher.unregisterHandler(this.emitHandler);
|
|
142
287
|
watcher.close();
|
|
143
288
|
});
|
|
144
289
|
this.watchers = [];
|
|
145
|
-
this.
|
|
290
|
+
this.removeAllListeners();
|
|
146
291
|
}
|
|
147
292
|
|
|
148
293
|
}
|
package/src/WatchesFile.js
CHANGED
|
@@ -14,7 +14,10 @@ const WatchesFile = Base => class extends Base {
|
|
|
14
14
|
*/
|
|
15
15
|
watchFile() {
|
|
16
16
|
this.stopWatching();
|
|
17
|
-
|
|
17
|
+
const fileFilter = typeof this.watchFileFilter === 'function'
|
|
18
|
+
? this.watchFileFilter.bind(this)
|
|
19
|
+
: null;
|
|
20
|
+
this.watcher = new Watcher(this.fileName, fileFilter, { rootDirectory: this.dataDirectory });
|
|
18
21
|
this.watcher.on('change', this.onChange.bind(this));
|
|
19
22
|
this.watcher.on('rename', this.onRename.bind(this));
|
|
20
23
|
}
|
package/src/utils/fsUtil.js
CHANGED
|
@@ -1,7 +1,19 @@
|
|
|
1
1
|
import fs from 'fs';
|
|
2
|
+
import os from "os";
|
|
2
3
|
import path from 'path';
|
|
3
4
|
import { mkdirpSync } from 'mkdirp';
|
|
4
5
|
|
|
6
|
+
/**
|
|
7
|
+
* Resolve a file or directory path, supporting `~/` for the user's home directory and joining with additional path segments.
|
|
8
|
+
* @param {string} fileOrDirectory
|
|
9
|
+
* @param {string} [directories]
|
|
10
|
+
* @returns {string} The normalized path, with resolved relative and home directory references.
|
|
11
|
+
*/
|
|
12
|
+
function resolvePath(fileOrDirectory, ...directories) {
|
|
13
|
+
fileOrDirectory = fileOrDirectory.replace(/^~\//, os.homedir() + '/');
|
|
14
|
+
return path.resolve(fileOrDirectory, ...directories);
|
|
15
|
+
}
|
|
16
|
+
|
|
5
17
|
/**
|
|
6
18
|
* Ensure that the given directory exists.
|
|
7
19
|
* @param {string} dirName Target directory.
|
|
@@ -121,7 +133,22 @@ function scanForFiles(directory, regexPattern, onEach, onDone) {
|
|
|
121
133
|
scanDir(directory, '', true, regexPattern, onEach, onDone);
|
|
122
134
|
}
|
|
123
135
|
|
|
136
|
+
/**
|
|
137
|
+
* Return true when both paths are equal or `child` is nested inside `parent`.
|
|
138
|
+
*
|
|
139
|
+
* @private
|
|
140
|
+
* @param {string} parent
|
|
141
|
+
* @param {string} child
|
|
142
|
+
* @returns {boolean}
|
|
143
|
+
*/
|
|
144
|
+
function isSameOrParentDirectory(parent, child) {
|
|
145
|
+
const relative = path.relative(parent, child);
|
|
146
|
+
return !relative || (!relative.startsWith('..') && !path.isAbsolute(relative));
|
|
147
|
+
}
|
|
148
|
+
|
|
124
149
|
export {
|
|
150
|
+
resolvePath,
|
|
125
151
|
ensureDirectory,
|
|
126
152
|
scanForFiles,
|
|
153
|
+
isSameOrParentDirectory
|
|
127
154
|
};
|