event-storage 1.4.0 → 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 CHANGED
@@ -10,7 +10,7 @@
10
10
 
11
11
  An optimized embedded event store for modern node.js, written in ES6.
12
12
 
13
- 📖 **[Full documentation on readthedocs.io](https://node-event-storage.readthedocs.io/en/latest/)**
13
+ 📖 **[Full documentation on readthedocs.io](https://node-event-storage.readthedocs.io/en/stable/)**
14
14
 
15
15
  ---
16
16
 
@@ -32,7 +32,7 @@ There is currently only a single other embedded event store for node/javascript:
32
32
  npm install event-storage
33
33
  ```
34
34
 
35
- > **CommonJS / `require()` users:** version 1.0 is ESM-only. If your project uses `require()` and migrating to ESM is not an option, install the 0.x series (`npm install event-storage@0`) which is functionally equivalent and retains full CJS support.
35
+ > **CommonJS / `require()` users:** version 1.0 is ESM-only. If your project uses `require()` and migrating to ESM is not an option, install the 0.x series (`npm install event-storage@0`), which supports CommonJS but lacks the features added in 1.x.
36
36
 
37
37
 
38
38
  ## Quick Start
@@ -56,14 +56,6 @@ eventstore.on('ready', () => {
56
56
  });
57
57
  ```
58
58
 
59
- ## Common Usage at a Glance
60
-
61
- - **Append events** with optimistic concurrency via `commit(stream, events, expectedVersion, cb)`.
62
- - **Read streams** with `getEventStream()` and fluent options for revision/range/direction.
63
- - **Run cross-stream queries** with `query(types, matcher)` and commit with its returned `condition` for DCB.
64
- - **Build projections** with `fromStreams()` (joined streams) and `createStream()` for persistent filtered streams.
65
- - **Consume reliably** with `createConsumer()` for durable at-least-once (or exactly-once with state) processing.
66
-
67
59
  ## Key Features
68
60
 
69
61
  | Feature | Summary |
@@ -71,102 +63,34 @@ eventstore.on('ready', () => {
71
63
  | **Optimistic concurrency** | Pass `expectedVersion` to `commit()` to guarantee conflict-free writes. |
72
64
  | **Flexible stream reading** | Range queries, reverse iteration, and a fluent builder API. |
73
65
  | **Joined and derived streams** | Combine any number of streams with a nested OR/AND selector tree into one globally-ordered virtual stream; filter events into reusable derived projection streams. |
74
- | **Object matchers** | Support nested equality, array values (OR semantics), scalar operators (`$gt` / `$gte` / `$lt` / `$lte` / `$eq` / `$ne`), plus array-containment operators (`$has` / `$hasAny`), while still benefiting from O(1) discriminant routing on writes. |
66
+ | **Object matchers** | Support nested equality, array values (OR semantics), scalar operators (`$gt` / `$gte` / `$lt` / `$lte` / `$eq` / `$ne`), string prefixes (`$startsWith`), plus array-containment operators (`$has` / `$hasAny`), while still benefiting from O(1) discriminant routing on writes. |
75
67
  | **DCB** | Configure `typeAccessor` to have per-type stream indexes maintained automatically, and use `query()` / `Condition` for fine-grained, query-scoped optimistic concurrency (Dynamic Consistency Boundaries). |
76
68
  | **Stream categories** | Name streams `<category>-<id>` and query the whole category at once. |
77
69
  | **Durable consumers** | At-least-once (and exactly-once with `setState`) event delivery with automatic position tracking. |
78
70
  | **Consistency guards** | Build aggregates that enforce business invariants with built-in snapshotting. |
79
71
  | **Read-only mode** | Open the store from a second process to build projections without touching the writer. |
80
- | **Crash safety** | Torn writes detected and truncated on startup; automatic index repair via `LOCK_RECLAIM`; bounded, predictable data loss validated by a dedicated stress test. |
72
+ | **Crash safety** | Torn writes detected and truncated on startup; automatic lock reclaim and index repair after a crashed writer; bounded, predictable data loss validated by a dedicated stress test. |
81
73
  | **Custom serialization** | Plug in msgpack, protobuf, or any other codec. |
82
74
  | **Compression** | Apply LZ4, zstd, or any other compression via the `serializer` option. |
83
75
  | **Access control hooks** | `preCommit` / `preRead` hooks with per-stream metadata for authorization. |
84
76
 
85
77
  ---
86
78
 
87
- ## Joining Streams
88
-
89
- Merge events from multiple streams in global insertion order with `fromStreams`. The selector tree alternates: OR at even depths, AND at odd depths:
90
-
91
- ```javascript
92
- // OR: all events from either stream, in insertion order
93
- const joined = eventstore.fromStreams('view', ['orders', 'payments']);
94
-
95
- // AND: only events indexed in both streams (intersection)
96
- const matched = eventstore.fromStreams('view', [['customer-42', 'OrderPlaced']]);
97
-
98
- // Nested — (stream-a AND stream-b) OR (stream-c AND stream-d)
99
- const complex = eventstore.fromStreams('view', [
100
- ['stream-a', 'stream-b'],
101
- ['stream-c', 'stream-d']
102
- ]);
103
- ```
104
-
105
- See [Event Streams](https://node-event-storage.readthedocs.io/en/latest/streams/) for the full selector algebra, categories, and derived projection streams.
106
-
107
- ---
108
-
109
- ## DCB Example
110
-
111
- ```javascript
112
- const { stream, condition } = store.query(['OrderPlaced'], { payload: { customerId: 'cust-1' } });
113
- const hasOpenOrder = stream.some((event) => event.status === 'open');
114
-
115
- if (!hasOpenOrder) {
116
- store.commit('orders-cust-1', [{ type: 'OrderPlaced', customerId: 'cust-1' }], condition);
117
- }
118
- ```
119
-
120
- ---
121
-
122
- ## Object Matcher Syntax
123
-
124
- Object matchers support nested equality, array values, scalar operators (`$gt`, `$gte`, `$lt`, `$lte`, `$eq`, `$ne`), and array-containment operators (`$has`, `$hasAny`).
125
-
126
- - Scalar operators can be combined on one field (AND semantics), e.g. `{ $gte: 100, $lt: 1000 }`.
127
- - `$has` / `$hasAny` target array-valued fields and must be used on their own for that field.
128
-
129
- For hot paths, reuse the same matcher object reference across calls when possible (instead of recreating equivalent objects each time) so matcher compilation and cache-based optimization paths can be reused.
130
-
131
- ```javascript
132
- { payload: { type: ['OrderPlaced', 'OrderCancelled'] } }
133
- { payload: { amount: { $gte: 100, $lt: 1000 } } }
134
- { payload: { tags: { $has: 'featured' } } }
135
- { payload: { tags: { $hasAny: ['featured', 'priority'] } } }
136
- ```
137
-
138
- ---
139
-
140
- ## HTTP API
141
-
142
- To expose an event store over HTTP, see the companion package **[event-storage-http](https://github.com/albe/node-event-storage-http)**:
143
-
144
- ```bash
145
- npm install event-storage-http
146
- ```
147
-
148
- ```javascript
149
- import EventStore from 'event-storage';
150
- import { createEventStoreHttpServer } from 'event-storage-http';
151
-
152
- const eventStore = new EventStore('my-store', { storageDirectory: './data' });
153
- const server = createEventStoreHttpServer(eventStore);
154
- server.listen(3000);
155
- ```
79
+ ## Companion Packages
156
80
 
157
- The package exposes NDJSON stream endpoints, durable consumer management, and an `HttpEventStream` client helper for consuming event streams over fetch.
81
+ - **[event-storage-http](https://github.com/albe/node-event-storage-http)** exposes a store over HTTP (NDJSON streams, consumer management, `HttpEventStream` client).
82
+ - **[event-storage-ui](https://github.com/albe/node-event-storage-ui)** is an admin dashboard for inspecting a running store on the same machine.
158
83
 
159
84
  ---
160
85
 
161
86
  ## Documentation
162
87
 
163
- The full documentation is hosted at **<https://node-event-storage.readthedocs.io/en/latest/>** and covers:
88
+ The full documentation is hosted at **<https://node-event-storage.readthedocs.io/en/stable/>**:
164
89
 
165
- - [Getting Started](https://node-event-storage.readthedocs.io/en/latest/getting-started/) — installation, constructor options, basic usage.
166
- - [Event Streams](https://node-event-storage.readthedocs.io/en/latest/streams/) — writing, reading, optimistic concurrency, fluent API, joining streams, categories, and event metadata.
167
- - [Dynamic Consistency Boundaries (DCB)](https://node-event-storage.readthedocs.io/en/latest/dcb/) — `typeAccessor`, query matchers, consistency tokens, and the full DCB workflow.
168
- - [Consumers](https://node-event-storage.readthedocs.io/en/latest/consumers/) — at-least-once and exactly-once delivery, consumer state, consistency guards, and read-only mode.
169
- - [Advanced Topics](https://node-event-storage.readthedocs.io/en/latest/advanced/) — ACID properties, reliability and crash-safety guarantees, storage configuration, partitioning, custom serialization, compression, security, and access control hooks.
90
+ - **New to event sourcing?** [Event Sourcing in 5 Minutes](https://node-event-storage.readthedocs.io/en/stable/event-sourcing/), [When to Use](https://node-event-storage.readthedocs.io/en/stable/when-to-use/), [Getting Started](https://node-event-storage.readthedocs.io/en/stable/getting-started/).
91
+ - **Guides:** [Writing and Reading Events](https://node-event-storage.readthedocs.io/en/stable/reading-writing/), [Organizing Streams](https://node-event-storage.readthedocs.io/en/stable/organizing-streams/), [Matchers](https://node-event-storage.readthedocs.io/en/stable/matchers/), [DCB](https://node-event-storage.readthedocs.io/en/stable/dcb/), [Consumers](https://node-event-storage.readthedocs.io/en/stable/consumers/), [Multiple Processes](https://node-event-storage.readthedocs.io/en/stable/multi-process/), [Customization](https://node-event-storage.readthedocs.io/en/stable/customization/), [Operations](https://node-event-storage.readthedocs.io/en/stable/operations/).
92
+ - **Evaluating the implementation?** [Guarantees](https://node-event-storage.readthedocs.io/en/stable/guarantees/), [Storage Format](https://node-event-storage.readthedocs.io/en/stable/storage-format/), [Implementation Architecture](https://node-event-storage.readthedocs.io/en/stable/architecture/), [Performance](https://node-event-storage.readthedocs.io/en/stable/performance/), [Limitations](https://node-event-storage.readthedocs.io/en/stable/limitations/), [Verify It Yourself](https://node-event-storage.readthedocs.io/en/stable/verify/).
93
+ - **Reference:** [API](https://node-event-storage.readthedocs.io/en/stable/api/), [Configuration](https://node-event-storage.readthedocs.io/en/stable/configuration/), [Changelog](https://node-event-storage.readthedocs.io/en/stable/changelog/), [Upgrading](https://node-event-storage.readthedocs.io/en/stable/upgrading/).
170
94
 
171
95
  ---
172
96
 
package/index.d.ts CHANGED
@@ -22,12 +22,105 @@ export interface StreamInfo {
22
22
  closed?: boolean;
23
23
  }
24
24
 
25
+ /** Stream selector tree: depth 0 = OR, depth 1 = AND, depth 2 = OR, ... */
26
+ export type StreamSelector = Array<string | StreamSelector>;
27
+
28
+ export interface DcbQueryItem {
29
+ types?: string[];
30
+ tags?: string[];
31
+ }
32
+
33
+ export interface DcbQuery {
34
+ items: DcbQueryItem[];
35
+ }
36
+
37
+ export type CommitCallback = (commit: Record<string, unknown>) => void;
38
+
39
+ export interface Serializer {
40
+ serialize(document: any): string | Buffer;
41
+ deserialize(data: string | Buffer): any;
42
+ }
43
+
44
+ export interface LockOwner {
45
+ pid: number;
46
+ hostname: string;
47
+ pidNamespace: string | null;
48
+ lockedAt: string;
49
+ }
50
+
51
+ export interface StorageConfig {
52
+ /** Directory for partition (event) files. Defaults to `storageDirectory`. */
53
+ dataDirectory?: string;
54
+ /** Directory for index files. Defaults to `streamsDirectory`. */
55
+ indexDirectory?: string;
56
+ /** File name of the primary index. Default `'{storeName}.index'`. */
57
+ indexFile?: string;
58
+ /** Returns the partition (file) name for a document. */
59
+ partitioner?: (document: any, sequenceNumber: number) => string;
60
+ /** Custom serialization or compression. Default JSON. */
61
+ serializer?: Serializer;
62
+ /** Read buffer size in bytes. Default 4096. */
63
+ readBufferSize?: number;
64
+ /** Write buffer size in bytes. Default 16384. */
65
+ writeBufferSize?: number;
66
+ /** Flush after this many buffered documents. Default 0 (unlimited). */
67
+ maxWriteBufferDocuments?: number;
68
+ /** Call fsync on every flush. Default false. */
69
+ syncOnFlush?: boolean;
70
+ /** Group commit: fsync each partition at most every this many ms and only then invoke the commit callbacks. Default 0 (off). */
71
+ syncInterval?: number;
72
+ /** Let the writer read events that are still in the write buffer. Default true. */
73
+ dirtyReads?: boolean;
74
+ /** How to handle an existing lock on open: `LOCK_AUTO` (default), `LOCK_THROW` or `LOCK_RECLAIM`. */
75
+ lock?: number;
76
+ /** Secret used to verify persisted function matchers. */
77
+ hmacSecret?: string;
78
+ /** Metadata written to each partition header. */
79
+ metadata?: Record<string, unknown> | ((partitionName: string) => Record<string, unknown>);
80
+ /** Document paths used for O(1) routing of writes to indexes. Default `['stream', 'payload.type']`. */
81
+ matcherProperties?: string[];
82
+ /** Maximum open partition file descriptors (0 = unlimited). Default 1024. */
83
+ maxOpenPartitions?: number;
84
+ /** Maximum open index file descriptors (0 = unlimited). Default 1024. */
85
+ maxOpenIndexes?: number;
86
+ /** Options passed to every index on construction. */
87
+ indexOptions?: Record<string, unknown>;
88
+ }
89
+
90
+ export interface StreamSource {
91
+ /** Dot-notation path into the event payload. */
92
+ path: string;
93
+ /** Builds the stream name from the value at `path`. */
94
+ nameBuilder: (value: string) => string;
95
+ }
96
+
97
+ export interface EventStoreConfig {
98
+ /** Directory for data files. Default `'./data'`. */
99
+ storageDirectory?: string;
100
+ /** Directory for stream index files. Default `'{storageDirectory}/streams'`. */
101
+ streamsDirectory?: string;
102
+ /** Open the store in read-only mode. Default false. */
103
+ readOnly?: boolean;
104
+ /** Dot-notation path to the event type; maintains one stream per type value. */
105
+ typeAccessor?: string;
106
+ /** Dot-notation path to an array of tag strings; maintains one stream `tags/<tag>` per tag value. */
107
+ tagsAccessor?: string;
108
+ /** Generic automatically maintained streams. */
109
+ streamSources?: StreamSource[];
110
+ /** Metadata stored once per stream at creation. */
111
+ streamMetadata?: Record<string, Record<string, unknown>> | ((streamName: string) => Record<string, unknown>);
112
+ /** Storage options. */
113
+ storageConfig?: StorageConfig;
114
+ }
115
+
25
116
  export class CommitCondition {
26
- constructor(types: string[], matcher: EventMatcher | null | undefined, noneMatchAfter: number, raw?: boolean);
27
- types: string[];
117
+ constructor(selector: StreamSelector | string, matcher: EventMatcher | null | undefined, noneMatchAfter: number, raw?: boolean);
118
+ selector: StreamSelector | string;
28
119
  matcher: EventMatcher | null;
29
120
  raw: boolean;
30
121
  noneMatchAfter: number;
122
+ /** A narrowed condition at the same position that ignores new events in the given streams (e.g. event types). */
123
+ without(...streams: Array<string | string[]>): CommitCondition;
31
124
  }
32
125
 
33
126
  export class OptimisticConcurrencyError extends Error {}
@@ -64,6 +157,7 @@ export class EventStream extends Readable {
64
157
  options: { concurrency?: number; signal?: AbortSignal }
65
158
  ): Readable;
66
159
  next(): any | false;
160
+ [Symbol.iterator](): Iterator<any>;
67
161
  }
68
162
 
69
163
  export class Consumer extends Readable {
@@ -74,7 +168,7 @@ export class Consumer extends Readable {
74
168
  start(): this;
75
169
  stop(): void;
76
170
  reset(initialState?: Record<string, unknown>, startFrom?: number): this;
77
- setState(state: Record<string, unknown>): this;
171
+ setState(state: Record<string, unknown> | ((state: Record<string, unknown>) => Record<string, unknown>), persist?: boolean): void;
78
172
  }
79
173
 
80
174
  export class Storage extends EventEmitter {
@@ -82,11 +176,18 @@ export class Storage extends EventEmitter {
82
176
  static StorageLockedError: typeof StorageLockedError;
83
177
  static LOCK_THROW: number;
84
178
  static LOCK_RECLAIM: number;
179
+ static LOCK_AUTO: number;
180
+
181
+ constructor(storageName?: string, config?: StorageConfig);
182
+ constructor(config: StorageConfig);
85
183
 
86
184
  initialized: boolean | null;
87
185
  length: number;
88
186
  indexDirectory: string;
89
187
  storageFile: string;
188
+
189
+ /** The process holding the lock, or null if the storage is not locked or the lock has no owner information. */
190
+ readLockOwner(): LockOwner | null;
90
191
  }
91
192
 
92
193
  export class StorageLockedError extends Error {}
@@ -109,7 +210,8 @@ export class EventStore extends EventEmitter {
109
210
  consumers: Map<string, Consumer>;
110
211
  length: number;
111
212
 
112
- constructor(storeName?: string, config?: Record<string, unknown>);
213
+ constructor(storeName?: string, config?: EventStoreConfig);
214
+ constructor(config: EventStoreConfig);
113
215
 
114
216
  open(callback?: (err?: Error | null) => void): void;
115
217
  close(callback?: (err?: Error | null) => void): void;
@@ -117,19 +219,22 @@ export class EventStore extends EventEmitter {
117
219
  getStreamVersion(streamName: string): number;
118
220
  getEventStream(streamName: string, minRevision?: number, maxRevision?: number, predicate?: EventPredicate, raw?: boolean): EventStream | false;
119
221
  getAllEvents(minRevision?: number, maxRevision?: number, predicate?: EventPredicate, raw?: boolean): EventStream;
120
- fromStreams(streamName: string, streamNames: string[], minRevision?: number, maxRevision?: number, predicate?: EventPredicate, raw?: boolean): EventStream;
222
+ fromStreams(streamName: string, streamNames: StreamSelector, minRevision?: number, maxRevision?: number, predicate?: EventPredicate, raw?: boolean): EventStream;
121
223
  getEventStreamForCategory(categoryName: string, minRevision?: number, maxRevision?: number, predicate?: EventPredicate, raw?: boolean): EventStream;
122
224
 
123
- query(types: string[], matcher?: EventMatcher | null, minRevision?: number, raw?: boolean): { stream: EventStream; condition: CommitCondition };
225
+ query(selectorOrDcbQuery: StreamSelector | DcbQuery, matcher?: EventMatcher | null, minRevision?: number, raw?: boolean): { stream: EventStream; condition: CommitCondition };
124
226
  createEventStream(streamName: string, matcher: EventMatcher, reindex?: boolean): EventStream;
125
227
 
126
228
  commit(
127
229
  streamName: string,
128
- events: any[],
129
- expectedVersion: number | CommitCondition,
130
- metadata: Record<string, unknown>,
131
- callback: (error: Error | null, commit?: Record<string, unknown>) => void
230
+ events: any | any[],
231
+ expectedVersion?: number | CommitCondition,
232
+ metadata?: Record<string, unknown>,
233
+ callback?: CommitCallback
132
234
  ): void;
235
+ commit(streamName: string, events: any | any[], expectedVersion: number | CommitCondition, callback: CommitCallback): void;
236
+ commit(streamName: string, events: any | any[], metadata: Record<string, unknown>, callback?: CommitCallback): void;
237
+ commit(streamName: string, events: any | any[], callback: CommitCallback): void;
133
238
 
134
239
  getConsumer(streamName: string, identifier: string, initialState?: Record<string, unknown>, since?: number): Consumer;
135
240
  getConsumer(identifier: string): Consumer | null;
@@ -141,6 +246,7 @@ export class EventStore extends EventEmitter {
141
246
 
142
247
  export const LOCK_THROW: number;
143
248
  export const LOCK_RECLAIM: number;
249
+ export const LOCK_AUTO: number;
144
250
 
145
251
  export function matches(document: Record<string, unknown>, matcher: Record<string, unknown>): boolean;
146
252
  export function buildRawBufferMatcher(matcher: Record<string, unknown>): (buffer: Buffer, startOffset?: number) => boolean;
package/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import packageJson from './package.json' with { type: 'json' };
2
- import EventStore, { ExpectedVersion, OptimisticConcurrencyError, CommitCondition, LOCK_THROW, LOCK_RECLAIM } from './src/EventStore.js';
2
+ import EventStore, { ExpectedVersion, OptimisticConcurrencyError, CommitCondition, LOCK_THROW, LOCK_RECLAIM, LOCK_AUTO } from './src/EventStore.js';
3
3
  import EventStream from './src/EventStream.js';
4
4
  import Storage, { StorageLockedError } from './src/Storage.js';
5
5
  import Index from './src/Index.js';
@@ -17,6 +17,7 @@ export {
17
17
  CommitCondition,
18
18
  LOCK_THROW,
19
19
  LOCK_RECLAIM,
20
+ LOCK_AUTO,
20
21
  VERSION,
21
22
  EventStream,
22
23
  Storage,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "event-storage",
3
- "version": "1.4.0",
3
+ "version": "1.5.0",
4
4
  "type": "module",
5
5
  "description": "An optimized embedded event store for node.js",
6
6
  "keywords": [
@@ -22,7 +22,11 @@
22
22
  "url": "https://github.com/albe/node-event-storage/issues"
23
23
  },
24
24
  "exports": {
25
- ".": "./index.js"
25
+ ".": "./index.js",
26
+ "./projections": {
27
+ "types": "./projections.d.ts",
28
+ "default": "./projections.js"
29
+ }
26
30
  },
27
31
  "types": "./index.d.ts",
28
32
  "scripts": {
@@ -39,6 +43,7 @@
39
43
  "src/JoinEventStream*.js",
40
44
  "src/Partition*.js",
41
45
  "src/Storage*.js",
46
+ "src/FileHandlePool.js",
42
47
  "src/Watcher*.js",
43
48
  "src/Clock*.js",
44
49
  "src/Index/*.js",
@@ -47,7 +52,10 @@
47
52
  "src/WatchesFile.js",
48
53
  "index.js",
49
54
  "index.d.ts",
50
- "src/utils/*.js"
55
+ "src/utils/*.js",
56
+ "src/Projection.js",
57
+ "projections.js",
58
+ "projections.d.ts"
51
59
  ],
52
60
  "license": "MIT",
53
61
  "maintainers": [
@@ -67,6 +75,6 @@
67
75
  "coveralls-next": "^6.0.1",
68
76
  "expect.js": "^0.3.1",
69
77
  "fs-extra": "^11.3.4",
70
- "mocha": "^11.7.5"
78
+ "mocha": "^12.0.0"
71
79
  }
72
80
  }
@@ -0,0 +1,40 @@
1
+ import type { CommitCondition, DcbQuery, EventStore, EventStream } from './index.js';
2
+
3
+ /** Pure reducer for one event type. Must not have side effects. */
4
+ export type ProjectionHandler<S, E = any> = (state: S, event: E, metadata: Record<string, any>) => S;
5
+
6
+ export interface ProjectionDefinition<S> {
7
+ initialState: S;
8
+ /** Reducers keyed by event type. The keys are the event types the projection reads. */
9
+ when: Record<string, ProjectionHandler<S>>;
10
+ /** Tags every handled event must carry (AND). */
11
+ tagFilter?: string[];
12
+ }
13
+
14
+ export interface Projection<S> {
15
+ readonly initialState: S;
16
+ /** The DcbQuery selecting all events this projection needs. */
17
+ readonly query: DcbQuery;
18
+ /** Apply one event. Events that do not match `query` return `state` unchanged. */
19
+ apply(state: S, event: any, metadata: Record<string, any>, context: { type: string; tags: string[] }): S;
20
+ }
21
+
22
+ export type ProjectionState<P> = P extends Projection<infer S> ? S : never;
23
+ export type ComposedState<M extends Record<string, Projection<any>>> = { [K in keyof M]: ProjectionState<M[K]> };
24
+
25
+ export function createProjection<S>(definition: ProjectionDefinition<S>): Projection<S>;
26
+
27
+ export function composeProjections<M extends Record<string, Projection<any>>>(projections: M): Projection<ComposedState<M>>;
28
+
29
+ /** Projection state at a known store position plus the condition protecting a decision on it. Immutable. */
30
+ export class DecisionModel<S> {
31
+ readonly state: S;
32
+ readonly commitCondition: CommitCondition;
33
+ /** Events matching `condition` (default: `commitCondition`) committed after this model was built, i.e. those that block a commit. */
34
+ since(condition?: CommitCondition): EventStream;
35
+ /** Apply only the events committed since this model was built. Returns this model when nothing is new. */
36
+ update(): DecisionModel<S>;
37
+ }
38
+
39
+ export function buildDecisionModel<S>(eventStore: EventStore, projection: Projection<S>): DecisionModel<S>;
40
+ export function buildDecisionModel<M extends Record<string, Projection<any>>>(eventStore: EventStore, projections: M): DecisionModel<ComposedState<M>>;
package/projections.js ADDED
@@ -0,0 +1 @@
1
+ export { createProjection, composeProjections, buildDecisionModel, DecisionModel } from './src/Projection.js';
package/src/Consumer.js CHANGED
@@ -2,25 +2,11 @@ import stream from 'stream';
2
2
  import fs from 'fs';
3
3
  import path from 'path';
4
4
  import { assert } from './utils/util.js';
5
- import { ensureDirectory } from './utils/fsUtil.js';
5
+ import { ensureDirectory, isSameOrParentDirectory, safeUnlink, writeFileAtomic } from './utils/fsUtil.js';
6
6
  import { normalizeConsumerStateArgs } from './utils/apiHelpers.js';
7
7
  import Storage from './Storage/ReadableStorage.js';
8
8
  const MAX_CATCHUP_BATCH = 10;
9
-
10
- /**
11
- * Safely unlink a file and ignore if it doesn't exist.
12
- * @param {string} filename
13
- */
14
- const safeUnlink = (filename) => {
15
- /* c8 ignore next */
16
- try {
17
- fs.unlinkSync(filename);
18
- } catch (e) {
19
- if (e.code !== "ENOENT") {
20
- throw e;
21
- }
22
- }
23
- };
9
+ const TMP_FILE_SUFFIX = /^\d+\.tmp$/;
24
10
 
25
11
  /**
26
12
  * Implements an event-driven durable Consumer that provides at-least-once delivery semantics or exactly-once processing semantics if only using setState().
@@ -59,13 +45,18 @@ class Consumer extends stream.Readable {
59
45
  this.indexName = indexName;
60
46
  const consumerDirectory = path.join(this.storage.indexDirectory, 'consumers');
61
47
  this.fileName = path.join(consumerDirectory, this.storage.storageFile + '.' + indexName + '.' + identifier);
62
- if (ensureDirectory(consumerDirectory)) {
48
+ assert(isSameOrParentDirectory(consumerDirectory, path.dirname(this.fileName)),
49
+ `Consumer "${identifier}" for index "${indexName}" would be stored outside of the consumers directory.`);
50
+ // Hierarchical stream names (e.g. "tags/course/c1") place the consumer file in a subdirectory.
51
+ if (ensureDirectory(path.dirname(this.fileName))) {
63
52
  this.cleanUpFailedWrites();
64
53
  }
65
54
  }
66
55
 
67
56
  /**
68
- * Iterate over all files in the directory of this consumer and unlink any file that starts with the filename followed by a dot.
57
+ * Unlink temporary files of this consumer that were left behind by an interrupted persist.
58
+ * Only `<fileName>.<position>.tmp` files are removed, so the state files of other consumers whose
59
+ * identifier or stream name extends this one (e.g. `orders` and `orders.archive`) stay untouched.
69
60
  * @private
70
61
  */
71
62
  cleanUpFailedWrites() {
@@ -73,7 +64,7 @@ class Consumer extends stream.Readable {
73
64
  const consumerDirectory = path.dirname(this.fileName);
74
65
  const files = fs.readdirSync(consumerDirectory);
75
66
  for (let file of files) {
76
- if (file.startsWith(consumerNamePrefix)) {
67
+ if (file.startsWith(consumerNamePrefix) && TMP_FILE_SUFFIX.test(file.slice(consumerNamePrefix.length))) {
77
68
  safeUnlink(path.join(consumerDirectory, file));
78
69
  }
79
70
  }
@@ -92,7 +83,7 @@ class Consumer extends stream.Readable {
92
83
  ({ initialState, startFrom } = normalizeConsumerStateArgs(initialState, startFrom));
93
84
  try {
94
85
  const consumerData = fs.readFileSync(this.fileName);
95
- this.position = consumerData.readInt32LE(0);
86
+ this.position = consumerData.readUInt32LE(0);
96
87
  this.state = JSON.parse(consumerData.toString('utf8', 4));
97
88
  } catch (e) {
98
89
  this.position = startFrom;
@@ -163,23 +154,21 @@ class Consumer extends stream.Readable {
163
154
  }
164
155
  this.persisting = setImmediate(() => {
165
156
  const consumerState = JSON.stringify(this.state);
166
- const consumerData = Buffer.allocUnsafe(4 + consumerState.length);
167
- consumerData.writeInt32LE(this.position, 0);
168
- consumerData.write(consumerState, 4, consumerState.length, 'utf-8');
169
- const tmpFile = this.fileName + '.' + this.position;
157
+ const consumerData = Buffer.allocUnsafe(4 + Buffer.byteLength(consumerState, 'utf8'));
158
+ consumerData.writeUInt32LE(this.position, 0);
159
+ consumerData.write(consumerState, 4, 'utf8');
160
+ const tmpFile = this.fileName + '.' + this.position + '.tmp';
170
161
  this.persisting = null;
171
162
  /* c8 ignore next 3 */
172
163
  if (fs.existsSync(tmpFile)) {
173
164
  throw new Error(`Trying to update consumer ${this.name} concurrently. Keep each single consumer within a single process.`);
174
165
  }
175
166
  try {
176
- fs.writeFileSync(tmpFile, consumerData);
177
- // If the write fails (half-way), the consumer state file will not be corrupted
178
- fs.renameSync(tmpFile, this.fileName);
167
+ writeFileAtomic(this.fileName, consumerData, tmpFile);
179
168
  this.emit('persisted', consumerState);
169
+ /* c8 ignore next 3 */
180
170
  } catch (e) {
181
- /* c8 ignore next */
182
- safeUnlink(tmpFile);
171
+ // The previous state file is still intact; the next persist will try again.
183
172
  }
184
173
  });
185
174
  }
package/src/EventStore.js CHANGED
@@ -3,13 +3,13 @@ import JoinEventStream from './JoinEventStream.js';
3
3
  import fs from 'fs';
4
4
  import path from 'path';
5
5
  import events from 'events';
6
- import Storage, { ReadOnly as ReadOnlyStorage, LOCK_THROW, LOCK_RECLAIM } from './Storage.js';
6
+ import Storage, { ReadOnly as ReadOnlyStorage, LOCK_THROW, LOCK_RECLAIM, LOCK_AUTO } from './Storage.js';
7
7
  import Index from './Index.js';
8
8
  import Consumer from './Consumer.js';
9
9
  import { assert } from './utils/util.js';
10
10
  import { ensureDirectory, resolvePath, scanForFiles } from './utils/fsUtil.js';
11
11
  import { fixCommitArgumentTypes, parseStreamFromIndexName, normalizePredicateRaw } from './utils/apiHelpers.js';
12
- import { normalizeSelector, buildStreamSource } from "./utils/indexUtil.js";
12
+ import { normalizeSelector, buildStreamSource, excludeStreams } from "./utils/indexUtil.js";
13
13
  import { isDcbQuery, compileDcbQuery } from "./utils/dcbUtil.js";
14
14
 
15
15
  const ExpectedVersion = {
@@ -68,6 +68,27 @@ class CommitCondition {
68
68
  this.raw = raw;
69
69
  this.noneMatchAfter = noneMatchAfter;
70
70
  }
71
+
72
+ /**
73
+ * Narrow this condition so that new events in the given streams no longer cause a conflict, e.g. because the
74
+ * decision only depends on part of the queried events: a concurrent unsubscribe cannot invalidate a new
75
+ * subscription, even though the decision model counts it.
76
+ *
77
+ * The streams are treated as empty: they are removed from OR levels, and an AND level containing one of them is
78
+ * removed as a whole. The condition therefore never gets wider. Event types address their type streams, which
79
+ * are named like the type when `typeAccessor` is configured.
80
+ *
81
+ * @api
82
+ * @param {...(string|string[])} streams The stream names (e.g. event types) to ignore in the conflict check.
83
+ * @returns {CommitCondition} A new condition at the same position.
84
+ * @throws {Error} When no stream would be left to check.
85
+ */
86
+ without(...streams) {
87
+ const selector = excludeStreams(this.selector, new Set(streams.flat()));
88
+ assert(selector !== null, 'without() would leave no streams to check. Commit without a condition instead.');
89
+ const normalized = normalizeSelector(selector);
90
+ return new CommitCondition(Array.isArray(normalized) ? normalized : [normalized], this.matcher, this.noneMatchAfter, this.raw);
91
+ }
71
92
  }
72
93
 
73
94
  /**
@@ -105,6 +126,7 @@ class EventStore extends events.EventEmitter {
105
126
  */
106
127
  constructor(storeName = 'eventstore', config = {}) {
107
128
  super();
129
+ this.setMaxListeners(0);
108
130
  if (typeof storeName !== 'string') {
109
131
  config = storeName;
110
132
  storeName = 'eventstore';
@@ -899,4 +921,4 @@ EventStore.Storage = Storage;
899
921
  EventStore.Index = Index;
900
922
 
901
923
  export default EventStore;
902
- export { ExpectedVersion, OptimisticConcurrencyError, CommitCondition, LOCK_THROW, LOCK_RECLAIM };
924
+ export { ExpectedVersion, OptimisticConcurrencyError, CommitCondition, LOCK_THROW, LOCK_RECLAIM, LOCK_AUTO };