event-storage 1.4.1 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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,114 @@ 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 interface Commit {
38
+ commitId: number;
39
+ committedAt: number;
40
+ streamName: string;
41
+ streamVersion: number;
42
+ events: any[];
43
+ [metadata: string]: unknown;
44
+ }
45
+
46
+ export type CommitCallback = (commit: Commit) => void;
47
+
48
+ export interface Serializer {
49
+ serialize(document: any): string | Buffer;
50
+ deserialize(data: string | Buffer): any;
51
+ }
52
+
53
+ export interface LockOwner {
54
+ pid: number;
55
+ hostname: string;
56
+ pidNamespace: string | null;
57
+ lockedAt: string;
58
+ }
59
+
60
+ export interface StorageConfig {
61
+ /** Directory for partition (event) files. Defaults to `storageDirectory`. */
62
+ dataDirectory?: string;
63
+ /** Directory for index files. Defaults to `streamsDirectory`. */
64
+ indexDirectory?: string;
65
+ /** File name of the primary index. Default `'{storeName}.index'`. */
66
+ indexFile?: string;
67
+ /** Returns the partition (file) name for a document. */
68
+ partitioner?: (document: any, sequenceNumber: number) => string;
69
+ /** Custom serialization or compression. Default JSON. */
70
+ serializer?: Serializer;
71
+ /** Read buffer size in bytes. Default 4096. */
72
+ readBufferSize?: number;
73
+ /** Write buffer size in bytes. Default 16384. */
74
+ writeBufferSize?: number;
75
+ /** Flush after this many buffered documents. Default 0 (unlimited). */
76
+ maxWriteBufferDocuments?: number;
77
+ /** Call fsync on every flush. Default false. */
78
+ syncOnFlush?: boolean;
79
+ /** Group commit: fsync each partition at most every this many ms and only then invoke the commit callbacks. Default 0 (off). */
80
+ syncInterval?: number;
81
+ /** Let the writer read events that are still in the write buffer. Default true. */
82
+ dirtyReads?: boolean;
83
+ /** How to handle an existing lock on open: `LOCK_AUTO` (default), `LOCK_THROW` or `LOCK_RECLAIM`. */
84
+ lock?: number;
85
+ /** Secret used to verify persisted function matchers. */
86
+ hmacSecret?: string;
87
+ /** Metadata written to each partition header. */
88
+ metadata?: Record<string, unknown> | ((partitionName: string) => Record<string, unknown>);
89
+ /** Document paths used for O(1) routing of writes to indexes. Default `['stream', 'payload.type']`. */
90
+ matcherProperties?: string[];
91
+ /** Maximum open partition file descriptors (0 = unlimited). Default 1024. */
92
+ maxOpenPartitions?: number;
93
+ /** Maximum open index file descriptors (0 = unlimited). Default 1024. */
94
+ maxOpenIndexes?: number;
95
+ /** Options passed to every index on construction. */
96
+ indexOptions?: Record<string, unknown>;
97
+ }
98
+
99
+ export interface StreamSource {
100
+ /** Dot-notation path into the event payload. */
101
+ path: string;
102
+ /** Builds the stream name from the value at `path`. */
103
+ nameBuilder: (value: string) => string;
104
+ }
105
+
106
+ export interface EventStoreConfig {
107
+ /** Directory for data files. Default `'./data'`. */
108
+ storageDirectory?: string;
109
+ /** Directory for stream index files. Default `'{storageDirectory}/streams'`. */
110
+ streamsDirectory?: string;
111
+ /** Open the store in read-only mode. Default false. */
112
+ readOnly?: boolean;
113
+ /** Dot-notation path to the event type; maintains one stream per type value. */
114
+ typeAccessor?: string;
115
+ /** Dot-notation path to an array of tag strings; maintains one stream `tags/<tag>` per tag value. */
116
+ tagsAccessor?: string;
117
+ /** Generic automatically maintained streams. */
118
+ streamSources?: StreamSource[];
119
+ /** Metadata stored once per stream at creation. */
120
+ streamMetadata?: Record<string, Record<string, unknown>> | ((streamName: string) => Record<string, unknown>);
121
+ /** Storage options. */
122
+ storageConfig?: StorageConfig;
123
+ }
124
+
25
125
  export class CommitCondition {
26
- constructor(types: string[], matcher: EventMatcher | null | undefined, noneMatchAfter: number, raw?: boolean);
27
- types: string[];
126
+ constructor(selector: StreamSelector | string, matcher: EventMatcher | null | undefined, noneMatchAfter: number, raw?: boolean);
127
+ selector: StreamSelector | string;
28
128
  matcher: EventMatcher | null;
29
129
  raw: boolean;
30
130
  noneMatchAfter: number;
131
+ /** A narrowed condition at the same position that ignores new events in the given streams (e.g. event types). */
132
+ without(...streams: Array<string | string[]>): CommitCondition;
31
133
  }
32
134
 
33
135
  export class OptimisticConcurrencyError extends Error {}
@@ -64,6 +166,7 @@ export class EventStream extends Readable {
64
166
  options: { concurrency?: number; signal?: AbortSignal }
65
167
  ): Readable;
66
168
  next(): any | false;
169
+ [Symbol.iterator](): Iterator<any>;
67
170
  }
68
171
 
69
172
  export class Consumer extends Readable {
@@ -74,7 +177,7 @@ export class Consumer extends Readable {
74
177
  start(): this;
75
178
  stop(): void;
76
179
  reset(initialState?: Record<string, unknown>, startFrom?: number): this;
77
- setState(state: Record<string, unknown>): this;
180
+ setState(state: Record<string, unknown> | ((state: Record<string, unknown>) => Record<string, unknown>), persist?: boolean): void;
78
181
  }
79
182
 
80
183
  export class Storage extends EventEmitter {
@@ -82,11 +185,18 @@ export class Storage extends EventEmitter {
82
185
  static StorageLockedError: typeof StorageLockedError;
83
186
  static LOCK_THROW: number;
84
187
  static LOCK_RECLAIM: number;
188
+ static LOCK_AUTO: number;
189
+
190
+ constructor(storageName?: string, config?: StorageConfig);
191
+ constructor(config: StorageConfig);
85
192
 
86
193
  initialized: boolean | null;
87
194
  length: number;
88
195
  indexDirectory: string;
89
196
  storageFile: string;
197
+
198
+ /** The process holding the lock, or null if the storage is not locked or the lock has no owner information. */
199
+ readLockOwner(): LockOwner | null;
90
200
  }
91
201
 
92
202
  export class StorageLockedError extends Error {}
@@ -109,7 +219,8 @@ export class EventStore extends EventEmitter {
109
219
  consumers: Map<string, Consumer>;
110
220
  length: number;
111
221
 
112
- constructor(storeName?: string, config?: Record<string, unknown>);
222
+ constructor(storeName?: string, config?: EventStoreConfig);
223
+ constructor(config: EventStoreConfig);
113
224
 
114
225
  open(callback?: (err?: Error | null) => void): void;
115
226
  close(callback?: (err?: Error | null) => void): void;
@@ -117,19 +228,22 @@ export class EventStore extends EventEmitter {
117
228
  getStreamVersion(streamName: string): number;
118
229
  getEventStream(streamName: string, minRevision?: number, maxRevision?: number, predicate?: EventPredicate, raw?: boolean): EventStream | false;
119
230
  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;
231
+ fromStreams(streamName: string, streamNames: StreamSelector, minRevision?: number, maxRevision?: number, predicate?: EventPredicate, raw?: boolean): EventStream;
121
232
  getEventStreamForCategory(categoryName: string, minRevision?: number, maxRevision?: number, predicate?: EventPredicate, raw?: boolean): EventStream;
122
233
 
123
- query(types: string[], matcher?: EventMatcher | null, minRevision?: number, raw?: boolean): { stream: EventStream; condition: CommitCondition };
234
+ query(selectorOrDcbQuery: StreamSelector | DcbQuery, matcher?: EventMatcher | null, minRevision?: number, raw?: boolean): { stream: EventStream; condition: CommitCondition };
124
235
  createEventStream(streamName: string, matcher: EventMatcher, reindex?: boolean): EventStream;
125
236
 
126
237
  commit(
127
238
  streamName: string,
128
- events: any[],
129
- expectedVersion: number | CommitCondition,
130
- metadata: Record<string, unknown>,
131
- callback: (error: Error | null, commit?: Record<string, unknown>) => void
132
- ): void;
239
+ events: any | any[],
240
+ expectedVersion?: number | CommitCondition,
241
+ metadata?: Record<string, unknown>,
242
+ callback?: CommitCallback
243
+ ): Commit;
244
+ commit(streamName: string, events: any | any[], expectedVersion: number | CommitCondition, callback: CommitCallback): Commit;
245
+ commit(streamName: string, events: any | any[], metadata: Record<string, unknown>, callback?: CommitCallback): Commit;
246
+ commit(streamName: string, events: any | any[], callback: CommitCallback): Commit;
133
247
 
134
248
  getConsumer(streamName: string, identifier: string, initialState?: Record<string, unknown>, since?: number): Consumer;
135
249
  getConsumer(identifier: string): Consumer | null;
@@ -141,6 +255,7 @@ export class EventStore extends EventEmitter {
141
255
 
142
256
  export const LOCK_THROW: number;
143
257
  export const LOCK_RECLAIM: number;
258
+ export const LOCK_AUTO: number;
144
259
 
145
260
  export function matches(document: Record<string, unknown>, matcher: Record<string, unknown>): boolean;
146
261
  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.1",
3
+ "version": "1.5.1",
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": {
@@ -40,6 +44,7 @@
40
44
  "src/Partition*.js",
41
45
  "src/Storage*.js",
42
46
  "src/FileHandlePool.js",
47
+ "src/SyncScheduler.js",
43
48
  "src/Watcher*.js",
44
49
  "src/Clock*.js",
45
50
  "src/Index/*.js",
@@ -48,7 +53,10 @@
48
53
  "src/WatchesFile.js",
49
54
  "index.js",
50
55
  "index.d.ts",
51
- "src/utils/*.js"
56
+ "src/utils/*.js",
57
+ "src/Projection.js",
58
+ "projections.js",
59
+ "projections.d.ts"
52
60
  ],
53
61
  "license": "MIT",
54
62
  "maintainers": [
@@ -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
  /**
@@ -495,6 +516,7 @@ class EventStore extends events.EventEmitter {
495
516
  * stream version number, or a {@link CommitCondition} obtained from {@link EventStore#query}.
496
517
  * @param {object} [metadata] The commit metadata to use as base. Useful for replication and adding storage metadata.
497
518
  * @param {function} [callback] A function that will be executed when all events have been committed.
519
+ * @returns {object} The commit, which already holds its position in the log. The events are not durable before the callback fires.
498
520
  * @throws {OptimisticConcurrencyError} if the stream is not at the expected version, or if a
499
521
  * {@link CommitCondition} was provided and conflicting events have been committed since it was obtained.
500
522
  */
@@ -559,6 +581,7 @@ class EventStore extends events.EventEmitter {
559
581
  commit.events.push(event);
560
582
  this.storage.write(storedEvent, commitVersion !== events.length ? undefined : commitCallback);
561
583
  }
584
+ return commit;
562
585
  }
563
586
 
564
587
  /**
@@ -900,4 +923,4 @@ EventStore.Storage = Storage;
900
923
  EventStore.Index = Index;
901
924
 
902
925
  export default EventStore;
903
- export { ExpectedVersion, OptimisticConcurrencyError, CommitCondition, LOCK_THROW, LOCK_RECLAIM };
926
+ export { ExpectedVersion, OptimisticConcurrencyError, CommitCondition, LOCK_THROW, LOCK_RECLAIM, LOCK_AUTO };
@@ -39,8 +39,8 @@ class EventStream extends stream.Readable {
39
39
  if (eventStore.streams[name]) {
40
40
  this.streamIndex = eventStore.streams[name].index;
41
41
  this.minRevision = normalizeRevision(minRevision, this.streamIndex.length);
42
- this.maxRevision = normalizeRevision(maxRevision, this.streamIndex.length);
43
- this.version = normalizeMaxRevision(this.streamIndex.length, maxRevision);
42
+ this.maxRevision = normalizeMaxRevision(this.streamIndex.length, maxRevision);
43
+ this.version = this.maxRevision;
44
44
  this._iterator = null;
45
45
  this.fetch = () => eventStore.storage.readRange(this.minRevision, this.maxRevision, this.streamIndex, raw);
46
46
  } else {
@@ -66,8 +66,8 @@ class EventStream extends stream.Readable {
66
66
  * @returns {EventStream}
67
67
  */
68
68
  until(revision) {
69
- this.maxRevision = normalizeRevision(revision, this.streamIndex.length);
70
- this.version = normalizeMaxRevision(this.streamIndex.length, this.maxRevision);
69
+ this.maxRevision = normalizeMaxRevision(this.streamIndex.length, revision);
70
+ this.version = this.maxRevision;
71
71
  return this;
72
72
  }
73
73