@emmett-community/emmett-google-firestore 0.5.0 → 0.7.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 +57 -2
- package/dist/index.d.mts +58 -3
- package/dist/index.d.ts +58 -3
- package/dist/index.js +77 -17
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +77 -17
- package/dist/index.mjs.map +1 -1
- package/dist/testing.d.mts +107 -0
- package/dist/testing.d.ts +107 -0
- package/dist/testing.js +299 -0
- package/dist/testing.js.map +1 -0
- package/dist/testing.mjs +297 -0
- package/dist/testing.mjs.map +1 -0
- package/package.json +11 -1
package/README.md
CHANGED
|
@@ -88,7 +88,7 @@ Events are stored using a **subcollection pattern** for optimal performance:
|
|
|
88
88
|
- ✅ No document size limits (Firestore 1MB limit doesn't apply to subcollections)
|
|
89
89
|
- ✅ Natural isolation per stream
|
|
90
90
|
- ✅ Automatic ordering (document IDs sort naturally)
|
|
91
|
-
- ✅ No composite indexes needed
|
|
91
|
+
- ✅ No composite indexes needed (only `readByGlobalPosition` needs a collection group index, see its section)
|
|
92
92
|
- ✅ Efficient queries
|
|
93
93
|
|
|
94
94
|
### Optimistic Concurrency
|
|
@@ -135,6 +135,7 @@ Creates a Firestore event store instance.
|
|
|
135
135
|
- `collections`: Custom collection names
|
|
136
136
|
- `streams`: Stream collection name (default: `"streams"`)
|
|
137
137
|
- `counters`: Counter collection name (default: `"_counters"`)
|
|
138
|
+
- `hooks`: Extension points (see [Append hooks](#append-hooks))
|
|
138
139
|
|
|
139
140
|
**Returns:** `FirestoreEventStore`
|
|
140
141
|
|
|
@@ -147,6 +148,24 @@ const eventStore = getFirestoreEventStore(firestore, {
|
|
|
147
148
|
});
|
|
148
149
|
```
|
|
149
150
|
|
|
151
|
+
### Append hooks
|
|
152
|
+
|
|
153
|
+
`hooks.beforeCommit` runs inside the transaction of an append, after the events are written to it. It receives the transaction and the appended events, each with its `messageId`, stream and positions. What it writes on the transaction commits together with the events, and an error it throws aborts the append. This is how to keep something atomic with the events, such as a transactional outbox.
|
|
154
|
+
|
|
155
|
+
```typescript
|
|
156
|
+
const eventStore = getFirestoreEventStore(firestore, {
|
|
157
|
+
hooks: {
|
|
158
|
+
beforeCommit: (transaction, events) => {
|
|
159
|
+
for (const event of events) {
|
|
160
|
+
transaction.set(firestore.collection('audit').doc(event.messageId), { type: event.type });
|
|
161
|
+
}
|
|
162
|
+
},
|
|
163
|
+
},
|
|
164
|
+
});
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
Firestore can run a transaction more than once when it conflicts, so the hook can run more than once for one append, with new ids each time. Only the writes of the attempt that commits are kept, so the hook must only write to the transaction, with no other side effect. It must not read, because Firestore rejects a read after a write in a transaction.
|
|
168
|
+
|
|
150
169
|
### `asEventStore(firestoreEventStore)`
|
|
151
170
|
|
|
152
171
|
Wraps a `FirestoreEventStore` instance in Emmett's `EventStore` interface so it can be passed into helpers that expect the canonical contract (CommandHandlers, workflows, etc.).
|
|
@@ -167,7 +186,7 @@ Appends events to a stream.
|
|
|
167
186
|
- `options`: Optional append options
|
|
168
187
|
- `expectedStreamVersion`: Version constraint
|
|
169
188
|
|
|
170
|
-
**Returns:** `Promise<AppendToStreamResult
|
|
189
|
+
**Returns:** `Promise<AppendToStreamResult>`, with `nextExpectedStreamVersion`, `createdNewStream` and `messageIds`, the `messageId` stored on each event, in the order of the events given.
|
|
171
190
|
|
|
172
191
|
```typescript
|
|
173
192
|
const result = await eventStore.appendToStream(
|
|
@@ -213,6 +232,42 @@ const events = await eventStore.readStream('User-123', {
|
|
|
213
232
|
});
|
|
214
233
|
```
|
|
215
234
|
|
|
235
|
+
### `eventStore.readByGlobalPosition(options?)`
|
|
236
|
+
|
|
237
|
+
Reads events of every stream in global order.
|
|
238
|
+
|
|
239
|
+
**Parameters:**
|
|
240
|
+
|
|
241
|
+
- `options`: Optional read options
|
|
242
|
+
- `after`: Return only events with a global position greater than this one (defaults to the start)
|
|
243
|
+
- `maxCount`: Maximum number of events to read
|
|
244
|
+
|
|
245
|
+
```typescript
|
|
246
|
+
// Read every event of every stream
|
|
247
|
+
const all = await eventStore.readByGlobalPosition();
|
|
248
|
+
|
|
249
|
+
// Read what happened after a known position
|
|
250
|
+
const next = await eventStore.readByGlobalPosition({ after: 10n, maxCount: 100 });
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
**Required Firestore index:** this method runs a collection group query over `events` ordered by `globalPosition`, so a real Firestore project needs a collection group index on that field. Without it the query fails with `FAILED_PRECONDITION: The query requires an index`. The Firestore Emulator does not enforce indexes, so the error only shows up against a real project. Add this to your `firestore.indexes.json` and deploy it with `firebase deploy --only firestore:indexes`:
|
|
254
|
+
|
|
255
|
+
```json
|
|
256
|
+
{
|
|
257
|
+
"indexes": [],
|
|
258
|
+
"fieldOverrides": [
|
|
259
|
+
{
|
|
260
|
+
"collectionGroup": "events",
|
|
261
|
+
"fieldPath": "globalPosition",
|
|
262
|
+
"indexes": [
|
|
263
|
+
{ "order": "ASCENDING", "queryScope": "COLLECTION" },
|
|
264
|
+
{ "order": "ASCENDING", "queryScope": "COLLECTION_GROUP" }
|
|
265
|
+
]
|
|
266
|
+
}
|
|
267
|
+
]
|
|
268
|
+
}
|
|
269
|
+
```
|
|
270
|
+
|
|
216
271
|
### `eventStore.aggregateStream(streamName, evolve, initialState, options?)`
|
|
217
272
|
|
|
218
273
|
Aggregates stream events into state.
|
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Transaction, Timestamp, Firestore } from '@google-cloud/firestore';
|
|
2
2
|
import { Event, ReadEvent, ReadEventMetadataWithGlobalPosition, ExpectedStreamVersion as ExpectedStreamVersion$1, STREAM_DOES_NOT_EXIST, EventStore } from '@event-driven-io/emmett';
|
|
3
3
|
export { NO_CONCURRENCY_CHECK, STREAM_DOES_NOT_EXIST, STREAM_EXISTS } from '@event-driven-io/emmett';
|
|
4
4
|
|
|
@@ -81,6 +81,8 @@ interface AppendToStreamOptions {
|
|
|
81
81
|
interface AppendToStreamResult {
|
|
82
82
|
nextExpectedStreamVersion: bigint;
|
|
83
83
|
createdNewStream: boolean;
|
|
84
|
+
/** The `messageId` set on each appended event, in the order of the events given. */
|
|
85
|
+
messageIds: string[];
|
|
84
86
|
}
|
|
85
87
|
/**
|
|
86
88
|
* Options for reading events from a stream
|
|
@@ -109,6 +111,11 @@ interface EventDocument {
|
|
|
109
111
|
timestamp: Timestamp;
|
|
110
112
|
globalPosition: number;
|
|
111
113
|
streamVersion: number;
|
|
114
|
+
/**
|
|
115
|
+
* Unique id of the event (UUID). Absent on events written before it was introduced;
|
|
116
|
+
* reads derive a stable id for those.
|
|
117
|
+
*/
|
|
118
|
+
messageId?: string;
|
|
112
119
|
}
|
|
113
120
|
/**
|
|
114
121
|
* Firestore-specific read event metadata
|
|
@@ -117,6 +124,16 @@ interface FirestoreReadEventMetadata extends ReadEventMetadataWithGlobalPosition
|
|
|
117
124
|
streamName: string;
|
|
118
125
|
streamVersion: bigint;
|
|
119
126
|
timestamp: Date;
|
|
127
|
+
messageId: string;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Options for reading events in global order
|
|
131
|
+
*/
|
|
132
|
+
interface ReadByGlobalPositionOptions {
|
|
133
|
+
/** Return only events with a global position greater than this one. Defaults to the start. */
|
|
134
|
+
after?: bigint;
|
|
135
|
+
/** Maximum number of events to return. */
|
|
136
|
+
maxCount?: number;
|
|
120
137
|
}
|
|
121
138
|
/**
|
|
122
139
|
* Firestore read event
|
|
@@ -129,12 +146,40 @@ interface CollectionConfig {
|
|
|
129
146
|
streams: string;
|
|
130
147
|
counters: string;
|
|
131
148
|
}
|
|
149
|
+
/**
|
|
150
|
+
* An event as it is being appended, handed to the store hooks
|
|
151
|
+
*/
|
|
152
|
+
interface AppendedEvent {
|
|
153
|
+
type: string;
|
|
154
|
+
data: Record<string, unknown>;
|
|
155
|
+
metadata?: Record<string, unknown>;
|
|
156
|
+
messageId: string;
|
|
157
|
+
streamName: string;
|
|
158
|
+
streamVersion: number;
|
|
159
|
+
globalPosition: number;
|
|
160
|
+
timestamp: Timestamp;
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Extension points of the event store
|
|
164
|
+
*/
|
|
165
|
+
interface FirestoreEventStoreHooks {
|
|
166
|
+
/**
|
|
167
|
+
* Runs inside the transaction of an append, after the events are written to it. Writes made
|
|
168
|
+
* on `transaction` commit together with the events, and an error aborts the append.
|
|
169
|
+
*
|
|
170
|
+
* Firestore can run a transaction more than once when it conflicts, so the hook can run more
|
|
171
|
+
* than once for one append: it must only write to the transaction, with no other side effect.
|
|
172
|
+
* It must not read, because Firestore rejects a read after a write in a transaction.
|
|
173
|
+
*/
|
|
174
|
+
beforeCommit?: (transaction: Transaction, events: AppendedEvent[]) => void | Promise<void>;
|
|
175
|
+
}
|
|
132
176
|
/**
|
|
133
177
|
* Firestore event store options
|
|
134
178
|
*/
|
|
135
179
|
interface FirestoreEventStoreOptions {
|
|
136
180
|
collections?: Partial<CollectionConfig>;
|
|
137
181
|
observability?: ObservabilityOptions;
|
|
182
|
+
hooks?: FirestoreEventStoreHooks;
|
|
138
183
|
}
|
|
139
184
|
/**
|
|
140
185
|
* Firestore event store interface
|
|
@@ -152,6 +197,11 @@ interface FirestoreEventStore {
|
|
|
152
197
|
* Read events from a stream
|
|
153
198
|
*/
|
|
154
199
|
readStream<EventType extends Event>(streamName: string, options?: ReadStreamOptions): Promise<FirestoreReadEvent<EventType>[]>;
|
|
200
|
+
/**
|
|
201
|
+
* Read events of every stream in global order. Needs the collection group index
|
|
202
|
+
* on `events.globalPosition` (see the README for the index definition).
|
|
203
|
+
*/
|
|
204
|
+
readByGlobalPosition<EventType extends Event>(options?: ReadByGlobalPositionOptions): Promise<FirestoreReadEvent<EventType>[]>;
|
|
155
205
|
/**
|
|
156
206
|
* Aggregate stream by applying events to state
|
|
157
207
|
*/
|
|
@@ -170,12 +220,17 @@ interface FirestoreEventStore {
|
|
|
170
220
|
appendToStream<EventType extends Event>(streamName: string, events: EventType[], options?: AppendToStreamOptions): Promise<AppendToStreamResult>;
|
|
171
221
|
}
|
|
172
222
|
/**
|
|
173
|
-
* Error thrown when expected version doesn't match current version
|
|
223
|
+
* Error thrown when expected version doesn't match current version.
|
|
224
|
+
*
|
|
225
|
+
* Carries HTTP status 412 (Precondition Failed) in `statusCode` and, following the Emmett
|
|
226
|
+
* error convention, in `errorCode`, so an HTTP layer can map it without importing this class.
|
|
174
227
|
*/
|
|
175
228
|
declare class ExpectedVersionConflictError extends Error {
|
|
176
229
|
readonly streamName: string;
|
|
177
230
|
readonly expected: ExpectedStreamVersion;
|
|
178
231
|
readonly actual: bigint | typeof STREAM_DOES_NOT_EXIST;
|
|
232
|
+
readonly statusCode = 412;
|
|
233
|
+
readonly errorCode = 412;
|
|
179
234
|
constructor(streamName: string, expected: ExpectedStreamVersion, actual: bigint | typeof STREAM_DOES_NOT_EXIST);
|
|
180
235
|
}
|
|
181
236
|
|
|
@@ -258,4 +313,4 @@ declare function getCurrentStreamVersion(streamExists: boolean, version?: number
|
|
|
258
313
|
*/
|
|
259
314
|
declare function calculateNextVersion(currentVersion: bigint | typeof STREAM_DOES_NOT_EXIST, eventCount: number): bigint;
|
|
260
315
|
|
|
261
|
-
export { type AppendToStreamOptions, type AppendToStreamResult, type CollectionConfig, type EventDocument, type ExpectedStreamVersion, ExpectedVersionConflictError, type FirestoreEventStore, type FirestoreEventStoreOptions, type FirestoreReadEvent, type FirestoreReadEventMetadata, type Logger, type ObservabilityOptions, type ReadStreamOptions, type StreamMetadata, asEventStore, assertExpectedVersionMatchesCurrent, calculateNextVersion, getCurrentStreamVersion, getFirestoreEventStore, padVersion, parseStreamName, timestampToDate };
|
|
316
|
+
export { type AppendToStreamOptions, type AppendToStreamResult, type AppendedEvent, type CollectionConfig, type EventDocument, type ExpectedStreamVersion, ExpectedVersionConflictError, type FirestoreEventStore, type FirestoreEventStoreHooks, type FirestoreEventStoreOptions, type FirestoreReadEvent, type FirestoreReadEventMetadata, type Logger, type ObservabilityOptions, type ReadByGlobalPositionOptions, type ReadStreamOptions, type StreamMetadata, asEventStore, assertExpectedVersionMatchesCurrent, calculateNextVersion, getCurrentStreamVersion, getFirestoreEventStore, padVersion, parseStreamName, timestampToDate };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Transaction, Timestamp, Firestore } from '@google-cloud/firestore';
|
|
2
2
|
import { Event, ReadEvent, ReadEventMetadataWithGlobalPosition, ExpectedStreamVersion as ExpectedStreamVersion$1, STREAM_DOES_NOT_EXIST, EventStore } from '@event-driven-io/emmett';
|
|
3
3
|
export { NO_CONCURRENCY_CHECK, STREAM_DOES_NOT_EXIST, STREAM_EXISTS } from '@event-driven-io/emmett';
|
|
4
4
|
|
|
@@ -81,6 +81,8 @@ interface AppendToStreamOptions {
|
|
|
81
81
|
interface AppendToStreamResult {
|
|
82
82
|
nextExpectedStreamVersion: bigint;
|
|
83
83
|
createdNewStream: boolean;
|
|
84
|
+
/** The `messageId` set on each appended event, in the order of the events given. */
|
|
85
|
+
messageIds: string[];
|
|
84
86
|
}
|
|
85
87
|
/**
|
|
86
88
|
* Options for reading events from a stream
|
|
@@ -109,6 +111,11 @@ interface EventDocument {
|
|
|
109
111
|
timestamp: Timestamp;
|
|
110
112
|
globalPosition: number;
|
|
111
113
|
streamVersion: number;
|
|
114
|
+
/**
|
|
115
|
+
* Unique id of the event (UUID). Absent on events written before it was introduced;
|
|
116
|
+
* reads derive a stable id for those.
|
|
117
|
+
*/
|
|
118
|
+
messageId?: string;
|
|
112
119
|
}
|
|
113
120
|
/**
|
|
114
121
|
* Firestore-specific read event metadata
|
|
@@ -117,6 +124,16 @@ interface FirestoreReadEventMetadata extends ReadEventMetadataWithGlobalPosition
|
|
|
117
124
|
streamName: string;
|
|
118
125
|
streamVersion: bigint;
|
|
119
126
|
timestamp: Date;
|
|
127
|
+
messageId: string;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Options for reading events in global order
|
|
131
|
+
*/
|
|
132
|
+
interface ReadByGlobalPositionOptions {
|
|
133
|
+
/** Return only events with a global position greater than this one. Defaults to the start. */
|
|
134
|
+
after?: bigint;
|
|
135
|
+
/** Maximum number of events to return. */
|
|
136
|
+
maxCount?: number;
|
|
120
137
|
}
|
|
121
138
|
/**
|
|
122
139
|
* Firestore read event
|
|
@@ -129,12 +146,40 @@ interface CollectionConfig {
|
|
|
129
146
|
streams: string;
|
|
130
147
|
counters: string;
|
|
131
148
|
}
|
|
149
|
+
/**
|
|
150
|
+
* An event as it is being appended, handed to the store hooks
|
|
151
|
+
*/
|
|
152
|
+
interface AppendedEvent {
|
|
153
|
+
type: string;
|
|
154
|
+
data: Record<string, unknown>;
|
|
155
|
+
metadata?: Record<string, unknown>;
|
|
156
|
+
messageId: string;
|
|
157
|
+
streamName: string;
|
|
158
|
+
streamVersion: number;
|
|
159
|
+
globalPosition: number;
|
|
160
|
+
timestamp: Timestamp;
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Extension points of the event store
|
|
164
|
+
*/
|
|
165
|
+
interface FirestoreEventStoreHooks {
|
|
166
|
+
/**
|
|
167
|
+
* Runs inside the transaction of an append, after the events are written to it. Writes made
|
|
168
|
+
* on `transaction` commit together with the events, and an error aborts the append.
|
|
169
|
+
*
|
|
170
|
+
* Firestore can run a transaction more than once when it conflicts, so the hook can run more
|
|
171
|
+
* than once for one append: it must only write to the transaction, with no other side effect.
|
|
172
|
+
* It must not read, because Firestore rejects a read after a write in a transaction.
|
|
173
|
+
*/
|
|
174
|
+
beforeCommit?: (transaction: Transaction, events: AppendedEvent[]) => void | Promise<void>;
|
|
175
|
+
}
|
|
132
176
|
/**
|
|
133
177
|
* Firestore event store options
|
|
134
178
|
*/
|
|
135
179
|
interface FirestoreEventStoreOptions {
|
|
136
180
|
collections?: Partial<CollectionConfig>;
|
|
137
181
|
observability?: ObservabilityOptions;
|
|
182
|
+
hooks?: FirestoreEventStoreHooks;
|
|
138
183
|
}
|
|
139
184
|
/**
|
|
140
185
|
* Firestore event store interface
|
|
@@ -152,6 +197,11 @@ interface FirestoreEventStore {
|
|
|
152
197
|
* Read events from a stream
|
|
153
198
|
*/
|
|
154
199
|
readStream<EventType extends Event>(streamName: string, options?: ReadStreamOptions): Promise<FirestoreReadEvent<EventType>[]>;
|
|
200
|
+
/**
|
|
201
|
+
* Read events of every stream in global order. Needs the collection group index
|
|
202
|
+
* on `events.globalPosition` (see the README for the index definition).
|
|
203
|
+
*/
|
|
204
|
+
readByGlobalPosition<EventType extends Event>(options?: ReadByGlobalPositionOptions): Promise<FirestoreReadEvent<EventType>[]>;
|
|
155
205
|
/**
|
|
156
206
|
* Aggregate stream by applying events to state
|
|
157
207
|
*/
|
|
@@ -170,12 +220,17 @@ interface FirestoreEventStore {
|
|
|
170
220
|
appendToStream<EventType extends Event>(streamName: string, events: EventType[], options?: AppendToStreamOptions): Promise<AppendToStreamResult>;
|
|
171
221
|
}
|
|
172
222
|
/**
|
|
173
|
-
* Error thrown when expected version doesn't match current version
|
|
223
|
+
* Error thrown when expected version doesn't match current version.
|
|
224
|
+
*
|
|
225
|
+
* Carries HTTP status 412 (Precondition Failed) in `statusCode` and, following the Emmett
|
|
226
|
+
* error convention, in `errorCode`, so an HTTP layer can map it without importing this class.
|
|
174
227
|
*/
|
|
175
228
|
declare class ExpectedVersionConflictError extends Error {
|
|
176
229
|
readonly streamName: string;
|
|
177
230
|
readonly expected: ExpectedStreamVersion;
|
|
178
231
|
readonly actual: bigint | typeof STREAM_DOES_NOT_EXIST;
|
|
232
|
+
readonly statusCode = 412;
|
|
233
|
+
readonly errorCode = 412;
|
|
179
234
|
constructor(streamName: string, expected: ExpectedStreamVersion, actual: bigint | typeof STREAM_DOES_NOT_EXIST);
|
|
180
235
|
}
|
|
181
236
|
|
|
@@ -258,4 +313,4 @@ declare function getCurrentStreamVersion(streamExists: boolean, version?: number
|
|
|
258
313
|
*/
|
|
259
314
|
declare function calculateNextVersion(currentVersion: bigint | typeof STREAM_DOES_NOT_EXIST, eventCount: number): bigint;
|
|
260
315
|
|
|
261
|
-
export { type AppendToStreamOptions, type AppendToStreamResult, type CollectionConfig, type EventDocument, type ExpectedStreamVersion, ExpectedVersionConflictError, type FirestoreEventStore, type FirestoreEventStoreOptions, type FirestoreReadEvent, type FirestoreReadEventMetadata, type Logger, type ObservabilityOptions, type ReadStreamOptions, type StreamMetadata, asEventStore, assertExpectedVersionMatchesCurrent, calculateNextVersion, getCurrentStreamVersion, getFirestoreEventStore, padVersion, parseStreamName, timestampToDate };
|
|
316
|
+
export { type AppendToStreamOptions, type AppendToStreamResult, type AppendedEvent, type CollectionConfig, type EventDocument, type ExpectedStreamVersion, ExpectedVersionConflictError, type FirestoreEventStore, type FirestoreEventStoreHooks, type FirestoreEventStoreOptions, type FirestoreReadEvent, type FirestoreReadEventMetadata, type Logger, type ObservabilityOptions, type ReadByGlobalPositionOptions, type ReadStreamOptions, type StreamMetadata, asEventStore, assertExpectedVersionMatchesCurrent, calculateNextVersion, getCurrentStreamVersion, getFirestoreEventStore, padVersion, parseStreamName, timestampToDate };
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
var crypto = require('crypto');
|
|
3
4
|
var api = require('@opentelemetry/api');
|
|
4
5
|
var emmett = require('@event-driven-io/emmett');
|
|
5
6
|
|
|
@@ -15,6 +16,8 @@ var ExpectedVersionConflictError = class _ExpectedVersionConflictError extends E
|
|
|
15
16
|
this.name = "ExpectedVersionConflictError";
|
|
16
17
|
Object.setPrototypeOf(this, _ExpectedVersionConflictError.prototype);
|
|
17
18
|
}
|
|
19
|
+
statusCode = 412;
|
|
20
|
+
errorCode = 412;
|
|
18
21
|
};
|
|
19
22
|
|
|
20
23
|
// src/eventStore/utils.ts
|
|
@@ -120,6 +123,21 @@ var safeLog = {
|
|
|
120
123
|
logger.error(normalizeErrorContext(error), msg);
|
|
121
124
|
}
|
|
122
125
|
};
|
|
126
|
+
function toReadEvent(streamName, data) {
|
|
127
|
+
return {
|
|
128
|
+
type: data.type,
|
|
129
|
+
data: data.data,
|
|
130
|
+
metadata: {
|
|
131
|
+
...data.metadata,
|
|
132
|
+
messageId: data.messageId ?? `${streamName}:${data.streamVersion}`,
|
|
133
|
+
streamName,
|
|
134
|
+
streamVersion: BigInt(data.streamVersion),
|
|
135
|
+
streamPosition: BigInt(data.streamVersion),
|
|
136
|
+
globalPosition: BigInt(data.globalPosition),
|
|
137
|
+
timestamp: timestampToDate(data.timestamp)
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
}
|
|
123
141
|
var DEFAULT_COLLECTIONS = {
|
|
124
142
|
streams: "streams",
|
|
125
143
|
counters: "_counters"
|
|
@@ -127,6 +145,7 @@ var DEFAULT_COLLECTIONS = {
|
|
|
127
145
|
var FirestoreEventStoreImpl = class {
|
|
128
146
|
constructor(firestore, options = {}) {
|
|
129
147
|
this.firestore = firestore;
|
|
148
|
+
this.hooks = options.hooks ?? {};
|
|
130
149
|
this.collections = {
|
|
131
150
|
...DEFAULT_COLLECTIONS,
|
|
132
151
|
...options.collections
|
|
@@ -136,6 +155,7 @@ var FirestoreEventStoreImpl = class {
|
|
|
136
155
|
}
|
|
137
156
|
collections;
|
|
138
157
|
logger;
|
|
158
|
+
hooks;
|
|
139
159
|
/**
|
|
140
160
|
* Read events from a stream
|
|
141
161
|
*/
|
|
@@ -164,21 +184,9 @@ var FirestoreEventStoreImpl = class {
|
|
|
164
184
|
query = query.limit(maxCountLimit);
|
|
165
185
|
}
|
|
166
186
|
const snapshot = await query.get();
|
|
167
|
-
const events = snapshot.docs.map(
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
type: data.type,
|
|
171
|
-
data: data.data,
|
|
172
|
-
metadata: {
|
|
173
|
-
...data.metadata,
|
|
174
|
-
streamName,
|
|
175
|
-
streamVersion: BigInt(data.streamVersion),
|
|
176
|
-
streamPosition: BigInt(data.streamVersion),
|
|
177
|
-
globalPosition: BigInt(data.globalPosition),
|
|
178
|
-
timestamp: timestampToDate(data.timestamp)
|
|
179
|
-
}
|
|
180
|
-
};
|
|
181
|
-
});
|
|
187
|
+
const events = snapshot.docs.map(
|
|
188
|
+
(doc) => toReadEvent(streamName, doc.data())
|
|
189
|
+
);
|
|
182
190
|
span.setAttribute("emmett.event_count", events.length);
|
|
183
191
|
span.setStatus({ code: api.SpanStatusCode.OK });
|
|
184
192
|
safeLog.debug(this.logger, "Stream read completed", {
|
|
@@ -198,6 +206,43 @@ var FirestoreEventStoreImpl = class {
|
|
|
198
206
|
span.end();
|
|
199
207
|
}
|
|
200
208
|
}
|
|
209
|
+
/**
|
|
210
|
+
* Read events of every stream in global order.
|
|
211
|
+
*
|
|
212
|
+
* Uses a collection group query over `events`, so it needs a collection group index on
|
|
213
|
+
* `globalPosition` (see the README for the index definition).
|
|
214
|
+
*/
|
|
215
|
+
async readByGlobalPosition(options = {}) {
|
|
216
|
+
const span = tracer.startSpan("emmett.firestore.read_by_global_position");
|
|
217
|
+
try {
|
|
218
|
+
const { after, maxCount } = options;
|
|
219
|
+
safeLog.debug(this.logger, "Reading by global position", {
|
|
220
|
+
after: after?.toString(),
|
|
221
|
+
maxCount
|
|
222
|
+
});
|
|
223
|
+
let query = this.firestore.collectionGroup("events").orderBy("globalPosition", "asc");
|
|
224
|
+
if (after !== void 0) {
|
|
225
|
+
query = query.where("globalPosition", ">", Number(after));
|
|
226
|
+
}
|
|
227
|
+
if (maxCount !== void 0 && maxCount > 0) {
|
|
228
|
+
query = query.limit(maxCount);
|
|
229
|
+
}
|
|
230
|
+
const snapshot = await query.get();
|
|
231
|
+
const events = snapshot.docs.map(
|
|
232
|
+
(doc) => toReadEvent(doc.ref.parent.parent.id, doc.data())
|
|
233
|
+
);
|
|
234
|
+
span.setAttribute("emmett.event_count", events.length);
|
|
235
|
+
span.setStatus({ code: api.SpanStatusCode.OK });
|
|
236
|
+
return events;
|
|
237
|
+
} catch (error) {
|
|
238
|
+
span.recordException(error);
|
|
239
|
+
span.setStatus({ code: api.SpanStatusCode.ERROR });
|
|
240
|
+
safeLog.error(this.logger, "Failed to read by global position", { error });
|
|
241
|
+
throw error;
|
|
242
|
+
} finally {
|
|
243
|
+
span.end();
|
|
244
|
+
}
|
|
245
|
+
}
|
|
201
246
|
/**
|
|
202
247
|
* Aggregate stream by applying events to state
|
|
203
248
|
*/
|
|
@@ -303,19 +348,32 @@ var FirestoreEventStoreImpl = class {
|
|
|
303
348
|
const baseVersion = currentVersion === emmett.STREAM_DOES_NOT_EXIST ? -1 : Number(currentVersion);
|
|
304
349
|
const TimestampClass = this.firestore.constructor;
|
|
305
350
|
const now = TimestampClass.Timestamp.now();
|
|
351
|
+
const appendedEvents = [];
|
|
306
352
|
events.forEach((event, index) => {
|
|
307
353
|
const eventVersion = baseVersion + 1 + index;
|
|
308
354
|
const eventRef = streamRef.collection("events").doc(padVersion(eventVersion));
|
|
309
355
|
const metadata = event.metadata;
|
|
356
|
+
const messageId = crypto.randomUUID();
|
|
310
357
|
const eventDocument = {
|
|
311
358
|
type: event.type,
|
|
312
359
|
data: event.data,
|
|
313
360
|
...metadata && { metadata },
|
|
314
361
|
timestamp: now,
|
|
315
362
|
globalPosition: globalPosition++,
|
|
316
|
-
streamVersion: eventVersion
|
|
363
|
+
streamVersion: eventVersion,
|
|
364
|
+
messageId
|
|
317
365
|
};
|
|
318
366
|
transaction.set(eventRef, eventDocument);
|
|
367
|
+
appendedEvents.push({
|
|
368
|
+
type: eventDocument.type,
|
|
369
|
+
data: eventDocument.data,
|
|
370
|
+
...metadata && { metadata },
|
|
371
|
+
messageId,
|
|
372
|
+
streamName,
|
|
373
|
+
streamVersion: eventVersion,
|
|
374
|
+
globalPosition: eventDocument.globalPosition,
|
|
375
|
+
timestamp: now
|
|
376
|
+
});
|
|
319
377
|
});
|
|
320
378
|
const newVersion = baseVersion + events.length;
|
|
321
379
|
const updatedMetadata = {
|
|
@@ -333,9 +391,11 @@ var FirestoreEventStoreImpl = class {
|
|
|
333
391
|
count: events.length,
|
|
334
392
|
newVersion
|
|
335
393
|
});
|
|
394
|
+
await this.hooks.beforeCommit?.(transaction, appendedEvents);
|
|
336
395
|
return {
|
|
337
396
|
nextExpectedStreamVersion: BigInt(newVersion),
|
|
338
|
-
createdNewStream: !streamExists
|
|
397
|
+
createdNewStream: !streamExists,
|
|
398
|
+
messageIds: appendedEvents.map((event) => event.messageId)
|
|
339
399
|
};
|
|
340
400
|
}
|
|
341
401
|
};
|