@emmett-community/emmett-google-firestore 0.4.0 → 0.6.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 +60 -11
- package/dist/index.d.mts +30 -3
- package/dist/index.d.ts +30 -3
- package/dist/index.js +111 -23
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +111 -24
- package/dist/index.mjs.map +1 -1
- package/dist/testing.d.mts +104 -0
- package/dist/testing.d.ts +104 -0
- package/dist/testing.js +287 -0
- package/dist/testing.js.map +1 -0
- package/dist/testing.mjs +285 -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
|
|
@@ -147,6 +147,15 @@ const eventStore = getFirestoreEventStore(firestore, {
|
|
|
147
147
|
});
|
|
148
148
|
```
|
|
149
149
|
|
|
150
|
+
### `asEventStore(firestoreEventStore)`
|
|
151
|
+
|
|
152
|
+
Wraps a `FirestoreEventStore` instance in Emmett's `EventStore` interface so it can be passed into helpers that expect the canonical contract (CommandHandlers, workflows, etc.).
|
|
153
|
+
|
|
154
|
+
```typescript
|
|
155
|
+
const firestoreEventStore = getFirestoreEventStore(firestore);
|
|
156
|
+
const eventStore = asEventStore(firestoreEventStore);
|
|
157
|
+
```
|
|
158
|
+
|
|
150
159
|
### `eventStore.appendToStream(streamName, events, options?)`
|
|
151
160
|
|
|
152
161
|
Appends events to a stream.
|
|
@@ -204,6 +213,42 @@ const events = await eventStore.readStream('User-123', {
|
|
|
204
213
|
});
|
|
205
214
|
```
|
|
206
215
|
|
|
216
|
+
### `eventStore.readByGlobalPosition(options?)`
|
|
217
|
+
|
|
218
|
+
Reads events of every stream in global order.
|
|
219
|
+
|
|
220
|
+
**Parameters:**
|
|
221
|
+
|
|
222
|
+
- `options`: Optional read options
|
|
223
|
+
- `after`: Return only events with a global position greater than this one (defaults to the start)
|
|
224
|
+
- `maxCount`: Maximum number of events to read
|
|
225
|
+
|
|
226
|
+
```typescript
|
|
227
|
+
// Read every event of every stream
|
|
228
|
+
const all = await eventStore.readByGlobalPosition();
|
|
229
|
+
|
|
230
|
+
// Read what happened after a known position
|
|
231
|
+
const next = await eventStore.readByGlobalPosition({ after: 10n, maxCount: 100 });
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
**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`:
|
|
235
|
+
|
|
236
|
+
```json
|
|
237
|
+
{
|
|
238
|
+
"indexes": [],
|
|
239
|
+
"fieldOverrides": [
|
|
240
|
+
{
|
|
241
|
+
"collectionGroup": "events",
|
|
242
|
+
"fieldPath": "globalPosition",
|
|
243
|
+
"indexes": [
|
|
244
|
+
{ "order": "ASCENDING", "queryScope": "COLLECTION" },
|
|
245
|
+
{ "order": "ASCENDING", "queryScope": "COLLECTION_GROUP" }
|
|
246
|
+
]
|
|
247
|
+
}
|
|
248
|
+
]
|
|
249
|
+
}
|
|
250
|
+
```
|
|
251
|
+
|
|
207
252
|
### `eventStore.aggregateStream(streamName, evolve, initialState, options?)`
|
|
208
253
|
|
|
209
254
|
Aggregates stream events into state.
|
|
@@ -560,16 +605,6 @@ import type {
|
|
|
560
605
|
- **Emmett**: ^0.39.0
|
|
561
606
|
- **Firestore**: ^7.10.0
|
|
562
607
|
|
|
563
|
-
## Contributing
|
|
564
|
-
|
|
565
|
-
Contributions are welcome! Please:
|
|
566
|
-
|
|
567
|
-
1. Fork the repository
|
|
568
|
-
2. Create a feature branch
|
|
569
|
-
3. Add tests for new functionality
|
|
570
|
-
4. Ensure all tests pass
|
|
571
|
-
5. Submit a pull request
|
|
572
|
-
|
|
573
608
|
## Development
|
|
574
609
|
|
|
575
610
|
```bash
|
|
@@ -589,6 +624,16 @@ npm run lint
|
|
|
589
624
|
npm run format
|
|
590
625
|
```
|
|
591
626
|
|
|
627
|
+
## Contributing
|
|
628
|
+
|
|
629
|
+
Contributions are welcome! Please:
|
|
630
|
+
|
|
631
|
+
1. Fork the repository
|
|
632
|
+
2. Create a feature branch
|
|
633
|
+
3. Add tests for new functionality
|
|
634
|
+
4. Ensure all tests pass
|
|
635
|
+
5. Submit a pull request
|
|
636
|
+
|
|
592
637
|
## License
|
|
593
638
|
|
|
594
639
|
MIT © Emmett Community
|
|
@@ -611,3 +656,7 @@ MIT © Emmett Community
|
|
|
611
656
|
- Built for the [Emmett](https://event-driven-io.github.io/emmett/) framework by [Oskar Dudycz](https://github.com/oskardudycz)
|
|
612
657
|
- Inspired by [emmett-mongodb](https://github.com/event-driven-io/emmett/tree/main/src/packages/emmett-mongodb)
|
|
613
658
|
- Part of the [Emmett Community](https://github.com/emmett-community)
|
|
659
|
+
|
|
660
|
+
---
|
|
661
|
+
|
|
662
|
+
Made with ❤️ by the Emmett Community
|
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Firestore, Timestamp } from '@google-cloud/firestore';
|
|
2
|
-
import { Event, ReadEvent, ReadEventMetadataWithGlobalPosition, ExpectedStreamVersion as ExpectedStreamVersion$1, STREAM_DOES_NOT_EXIST } from '@event-driven-io/emmett';
|
|
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
|
|
|
5
5
|
/**
|
|
@@ -84,6 +84,7 @@ interface AppendToStreamResult {
|
|
|
84
84
|
}
|
|
85
85
|
/**
|
|
86
86
|
* Options for reading events from a stream
|
|
87
|
+
* Reuses the canonical `ReadStreamOptions` shape from the Emmett core types.
|
|
87
88
|
*/
|
|
88
89
|
interface ReadStreamOptions {
|
|
89
90
|
from?: bigint;
|
|
@@ -108,6 +109,11 @@ interface EventDocument {
|
|
|
108
109
|
timestamp: Timestamp;
|
|
109
110
|
globalPosition: number;
|
|
110
111
|
streamVersion: number;
|
|
112
|
+
/**
|
|
113
|
+
* Unique id of the event (UUID). Absent on events written before it was introduced;
|
|
114
|
+
* reads derive a stable id for those.
|
|
115
|
+
*/
|
|
116
|
+
messageId?: string;
|
|
111
117
|
}
|
|
112
118
|
/**
|
|
113
119
|
* Firestore-specific read event metadata
|
|
@@ -116,6 +122,16 @@ interface FirestoreReadEventMetadata extends ReadEventMetadataWithGlobalPosition
|
|
|
116
122
|
streamName: string;
|
|
117
123
|
streamVersion: bigint;
|
|
118
124
|
timestamp: Date;
|
|
125
|
+
messageId: string;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Options for reading events in global order
|
|
129
|
+
*/
|
|
130
|
+
interface ReadByGlobalPositionOptions {
|
|
131
|
+
/** Return only events with a global position greater than this one. Defaults to the start. */
|
|
132
|
+
after?: bigint;
|
|
133
|
+
/** Maximum number of events to return. */
|
|
134
|
+
maxCount?: number;
|
|
119
135
|
}
|
|
120
136
|
/**
|
|
121
137
|
* Firestore read event
|
|
@@ -151,6 +167,11 @@ interface FirestoreEventStore {
|
|
|
151
167
|
* Read events from a stream
|
|
152
168
|
*/
|
|
153
169
|
readStream<EventType extends Event>(streamName: string, options?: ReadStreamOptions): Promise<FirestoreReadEvent<EventType>[]>;
|
|
170
|
+
/**
|
|
171
|
+
* Read events of every stream in global order. Needs the collection group index
|
|
172
|
+
* on `events.globalPosition` (see the README for the index definition).
|
|
173
|
+
*/
|
|
174
|
+
readByGlobalPosition<EventType extends Event>(options?: ReadByGlobalPositionOptions): Promise<FirestoreReadEvent<EventType>[]>;
|
|
154
175
|
/**
|
|
155
176
|
* Aggregate stream by applying events to state
|
|
156
177
|
*/
|
|
@@ -169,15 +190,21 @@ interface FirestoreEventStore {
|
|
|
169
190
|
appendToStream<EventType extends Event>(streamName: string, events: EventType[], options?: AppendToStreamOptions): Promise<AppendToStreamResult>;
|
|
170
191
|
}
|
|
171
192
|
/**
|
|
172
|
-
* Error thrown when expected version doesn't match current version
|
|
193
|
+
* Error thrown when expected version doesn't match current version.
|
|
194
|
+
*
|
|
195
|
+
* Carries HTTP status 412 (Precondition Failed) in `statusCode` and, following the Emmett
|
|
196
|
+
* error convention, in `errorCode`, so an HTTP layer can map it without importing this class.
|
|
173
197
|
*/
|
|
174
198
|
declare class ExpectedVersionConflictError extends Error {
|
|
175
199
|
readonly streamName: string;
|
|
176
200
|
readonly expected: ExpectedStreamVersion;
|
|
177
201
|
readonly actual: bigint | typeof STREAM_DOES_NOT_EXIST;
|
|
202
|
+
readonly statusCode = 412;
|
|
203
|
+
readonly errorCode = 412;
|
|
178
204
|
constructor(streamName: string, expected: ExpectedStreamVersion, actual: bigint | typeof STREAM_DOES_NOT_EXIST);
|
|
179
205
|
}
|
|
180
206
|
|
|
207
|
+
declare function asEventStore(store: FirestoreEventStore): EventStore<FirestoreReadEventMetadata>;
|
|
181
208
|
/**
|
|
182
209
|
* Factory function to create a Firestore event store
|
|
183
210
|
*
|
|
@@ -256,4 +283,4 @@ declare function getCurrentStreamVersion(streamExists: boolean, version?: number
|
|
|
256
283
|
*/
|
|
257
284
|
declare function calculateNextVersion(currentVersion: bigint | typeof STREAM_DOES_NOT_EXIST, eventCount: number): bigint;
|
|
258
285
|
|
|
259
|
-
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, assertExpectedVersionMatchesCurrent, calculateNextVersion, getCurrentStreamVersion, getFirestoreEventStore, padVersion, parseStreamName, timestampToDate };
|
|
286
|
+
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 ReadByGlobalPositionOptions, type ReadStreamOptions, type StreamMetadata, asEventStore, assertExpectedVersionMatchesCurrent, calculateNextVersion, getCurrentStreamVersion, getFirestoreEventStore, padVersion, parseStreamName, timestampToDate };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Firestore, Timestamp } from '@google-cloud/firestore';
|
|
2
|
-
import { Event, ReadEvent, ReadEventMetadataWithGlobalPosition, ExpectedStreamVersion as ExpectedStreamVersion$1, STREAM_DOES_NOT_EXIST } from '@event-driven-io/emmett';
|
|
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
|
|
|
5
5
|
/**
|
|
@@ -84,6 +84,7 @@ interface AppendToStreamResult {
|
|
|
84
84
|
}
|
|
85
85
|
/**
|
|
86
86
|
* Options for reading events from a stream
|
|
87
|
+
* Reuses the canonical `ReadStreamOptions` shape from the Emmett core types.
|
|
87
88
|
*/
|
|
88
89
|
interface ReadStreamOptions {
|
|
89
90
|
from?: bigint;
|
|
@@ -108,6 +109,11 @@ interface EventDocument {
|
|
|
108
109
|
timestamp: Timestamp;
|
|
109
110
|
globalPosition: number;
|
|
110
111
|
streamVersion: number;
|
|
112
|
+
/**
|
|
113
|
+
* Unique id of the event (UUID). Absent on events written before it was introduced;
|
|
114
|
+
* reads derive a stable id for those.
|
|
115
|
+
*/
|
|
116
|
+
messageId?: string;
|
|
111
117
|
}
|
|
112
118
|
/**
|
|
113
119
|
* Firestore-specific read event metadata
|
|
@@ -116,6 +122,16 @@ interface FirestoreReadEventMetadata extends ReadEventMetadataWithGlobalPosition
|
|
|
116
122
|
streamName: string;
|
|
117
123
|
streamVersion: bigint;
|
|
118
124
|
timestamp: Date;
|
|
125
|
+
messageId: string;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Options for reading events in global order
|
|
129
|
+
*/
|
|
130
|
+
interface ReadByGlobalPositionOptions {
|
|
131
|
+
/** Return only events with a global position greater than this one. Defaults to the start. */
|
|
132
|
+
after?: bigint;
|
|
133
|
+
/** Maximum number of events to return. */
|
|
134
|
+
maxCount?: number;
|
|
119
135
|
}
|
|
120
136
|
/**
|
|
121
137
|
* Firestore read event
|
|
@@ -151,6 +167,11 @@ interface FirestoreEventStore {
|
|
|
151
167
|
* Read events from a stream
|
|
152
168
|
*/
|
|
153
169
|
readStream<EventType extends Event>(streamName: string, options?: ReadStreamOptions): Promise<FirestoreReadEvent<EventType>[]>;
|
|
170
|
+
/**
|
|
171
|
+
* Read events of every stream in global order. Needs the collection group index
|
|
172
|
+
* on `events.globalPosition` (see the README for the index definition).
|
|
173
|
+
*/
|
|
174
|
+
readByGlobalPosition<EventType extends Event>(options?: ReadByGlobalPositionOptions): Promise<FirestoreReadEvent<EventType>[]>;
|
|
154
175
|
/**
|
|
155
176
|
* Aggregate stream by applying events to state
|
|
156
177
|
*/
|
|
@@ -169,15 +190,21 @@ interface FirestoreEventStore {
|
|
|
169
190
|
appendToStream<EventType extends Event>(streamName: string, events: EventType[], options?: AppendToStreamOptions): Promise<AppendToStreamResult>;
|
|
170
191
|
}
|
|
171
192
|
/**
|
|
172
|
-
* Error thrown when expected version doesn't match current version
|
|
193
|
+
* Error thrown when expected version doesn't match current version.
|
|
194
|
+
*
|
|
195
|
+
* Carries HTTP status 412 (Precondition Failed) in `statusCode` and, following the Emmett
|
|
196
|
+
* error convention, in `errorCode`, so an HTTP layer can map it without importing this class.
|
|
173
197
|
*/
|
|
174
198
|
declare class ExpectedVersionConflictError extends Error {
|
|
175
199
|
readonly streamName: string;
|
|
176
200
|
readonly expected: ExpectedStreamVersion;
|
|
177
201
|
readonly actual: bigint | typeof STREAM_DOES_NOT_EXIST;
|
|
202
|
+
readonly statusCode = 412;
|
|
203
|
+
readonly errorCode = 412;
|
|
178
204
|
constructor(streamName: string, expected: ExpectedStreamVersion, actual: bigint | typeof STREAM_DOES_NOT_EXIST);
|
|
179
205
|
}
|
|
180
206
|
|
|
207
|
+
declare function asEventStore(store: FirestoreEventStore): EventStore<FirestoreReadEventMetadata>;
|
|
181
208
|
/**
|
|
182
209
|
* Factory function to create a Firestore event store
|
|
183
210
|
*
|
|
@@ -256,4 +283,4 @@ declare function getCurrentStreamVersion(streamExists: boolean, version?: number
|
|
|
256
283
|
*/
|
|
257
284
|
declare function calculateNextVersion(currentVersion: bigint | typeof STREAM_DOES_NOT_EXIST, eventCount: number): bigint;
|
|
258
285
|
|
|
259
|
-
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, assertExpectedVersionMatchesCurrent, calculateNextVersion, getCurrentStreamVersion, getFirestoreEventStore, padVersion, parseStreamName, timestampToDate };
|
|
286
|
+
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 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"
|
|
@@ -139,18 +157,20 @@ var FirestoreEventStoreImpl = class {
|
|
|
139
157
|
/**
|
|
140
158
|
* Read events from a stream
|
|
141
159
|
*/
|
|
142
|
-
async readStream(streamName, options
|
|
160
|
+
async readStream(streamName, options) {
|
|
143
161
|
const span = tracer.startSpan("emmett.firestore.read_stream", {
|
|
144
162
|
attributes: { "emmett.stream_name": streamName }
|
|
145
163
|
});
|
|
146
164
|
try {
|
|
165
|
+
const from = options && "from" in options ? options.from : void 0;
|
|
166
|
+
const to = options && "to" in options ? options.to : void 0;
|
|
167
|
+
const maxCountLimit = options && "maxCount" in options && options.maxCount !== void 0 ? Number(options.maxCount) : void 0;
|
|
147
168
|
safeLog.debug(this.logger, "Reading stream", {
|
|
148
169
|
streamName,
|
|
149
|
-
from:
|
|
150
|
-
to:
|
|
151
|
-
maxCount:
|
|
170
|
+
from: from?.toString(),
|
|
171
|
+
to: to?.toString(),
|
|
172
|
+
maxCount: maxCountLimit
|
|
152
173
|
});
|
|
153
|
-
const { from, to, maxCount } = options;
|
|
154
174
|
let query = this.firestore.collection(this.collections.streams).doc(streamName).collection("events").orderBy("streamVersion", "asc");
|
|
155
175
|
if (from !== void 0) {
|
|
156
176
|
query = query.where("streamVersion", ">=", Number(from));
|
|
@@ -158,25 +178,13 @@ var FirestoreEventStoreImpl = class {
|
|
|
158
178
|
if (to !== void 0) {
|
|
159
179
|
query = query.where("streamVersion", "<=", Number(to));
|
|
160
180
|
}
|
|
161
|
-
if (
|
|
162
|
-
query = query.limit(
|
|
181
|
+
if (maxCountLimit !== void 0 && maxCountLimit > 0) {
|
|
182
|
+
query = query.limit(maxCountLimit);
|
|
163
183
|
}
|
|
164
184
|
const snapshot = await query.get();
|
|
165
|
-
const events = snapshot.docs.map(
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
type: data.type,
|
|
169
|
-
data: data.data,
|
|
170
|
-
metadata: {
|
|
171
|
-
...data.metadata,
|
|
172
|
-
streamName,
|
|
173
|
-
streamVersion: BigInt(data.streamVersion),
|
|
174
|
-
streamPosition: BigInt(data.streamVersion),
|
|
175
|
-
globalPosition: BigInt(data.globalPosition),
|
|
176
|
-
timestamp: timestampToDate(data.timestamp)
|
|
177
|
-
}
|
|
178
|
-
};
|
|
179
|
-
});
|
|
185
|
+
const events = snapshot.docs.map(
|
|
186
|
+
(doc) => toReadEvent(streamName, doc.data())
|
|
187
|
+
);
|
|
180
188
|
span.setAttribute("emmett.event_count", events.length);
|
|
181
189
|
span.setStatus({ code: api.SpanStatusCode.OK });
|
|
182
190
|
safeLog.debug(this.logger, "Stream read completed", {
|
|
@@ -196,6 +204,43 @@ var FirestoreEventStoreImpl = class {
|
|
|
196
204
|
span.end();
|
|
197
205
|
}
|
|
198
206
|
}
|
|
207
|
+
/**
|
|
208
|
+
* Read events of every stream in global order.
|
|
209
|
+
*
|
|
210
|
+
* Uses a collection group query over `events`, so it needs a collection group index on
|
|
211
|
+
* `globalPosition` (see the README for the index definition).
|
|
212
|
+
*/
|
|
213
|
+
async readByGlobalPosition(options = {}) {
|
|
214
|
+
const span = tracer.startSpan("emmett.firestore.read_by_global_position");
|
|
215
|
+
try {
|
|
216
|
+
const { after, maxCount } = options;
|
|
217
|
+
safeLog.debug(this.logger, "Reading by global position", {
|
|
218
|
+
after: after?.toString(),
|
|
219
|
+
maxCount
|
|
220
|
+
});
|
|
221
|
+
let query = this.firestore.collectionGroup("events").orderBy("globalPosition", "asc");
|
|
222
|
+
if (after !== void 0) {
|
|
223
|
+
query = query.where("globalPosition", ">", Number(after));
|
|
224
|
+
}
|
|
225
|
+
if (maxCount !== void 0 && maxCount > 0) {
|
|
226
|
+
query = query.limit(maxCount);
|
|
227
|
+
}
|
|
228
|
+
const snapshot = await query.get();
|
|
229
|
+
const events = snapshot.docs.map(
|
|
230
|
+
(doc) => toReadEvent(doc.ref.parent.parent.id, doc.data())
|
|
231
|
+
);
|
|
232
|
+
span.setAttribute("emmett.event_count", events.length);
|
|
233
|
+
span.setStatus({ code: api.SpanStatusCode.OK });
|
|
234
|
+
return events;
|
|
235
|
+
} catch (error) {
|
|
236
|
+
span.recordException(error);
|
|
237
|
+
span.setStatus({ code: api.SpanStatusCode.ERROR });
|
|
238
|
+
safeLog.error(this.logger, "Failed to read by global position", { error });
|
|
239
|
+
throw error;
|
|
240
|
+
} finally {
|
|
241
|
+
span.end();
|
|
242
|
+
}
|
|
243
|
+
}
|
|
199
244
|
/**
|
|
200
245
|
* Aggregate stream by applying events to state
|
|
201
246
|
*/
|
|
@@ -311,7 +356,8 @@ var FirestoreEventStoreImpl = class {
|
|
|
311
356
|
...metadata && { metadata },
|
|
312
357
|
timestamp: now,
|
|
313
358
|
globalPosition: globalPosition++,
|
|
314
|
-
streamVersion: eventVersion
|
|
359
|
+
streamVersion: eventVersion,
|
|
360
|
+
messageId: crypto.randomUUID()
|
|
315
361
|
};
|
|
316
362
|
transaction.set(eventRef, eventDocument);
|
|
317
363
|
});
|
|
@@ -337,6 +383,47 @@ var FirestoreEventStoreImpl = class {
|
|
|
337
383
|
};
|
|
338
384
|
}
|
|
339
385
|
};
|
|
386
|
+
function normalizeReadOptions(options) {
|
|
387
|
+
if (!options) return void 0;
|
|
388
|
+
const result = {};
|
|
389
|
+
if ("from" in options) {
|
|
390
|
+
result.from = options.from;
|
|
391
|
+
if ("maxCount" in options && options.maxCount !== void 0) {
|
|
392
|
+
result.maxCount = Number(options.maxCount);
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
if ("to" in options) {
|
|
396
|
+
result.to = options.to;
|
|
397
|
+
}
|
|
398
|
+
return result;
|
|
399
|
+
}
|
|
400
|
+
function asEventStore(store) {
|
|
401
|
+
async function readStream(streamName, options) {
|
|
402
|
+
const events = await store.readStream(streamName, normalizeReadOptions(options));
|
|
403
|
+
const streamExists = events.length > 0;
|
|
404
|
+
const currentStreamVersion = streamExists ? events[events.length - 1].metadata.streamVersion : BigInt(0);
|
|
405
|
+
return {
|
|
406
|
+
currentStreamVersion,
|
|
407
|
+
events,
|
|
408
|
+
streamExists
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
function aggregateStream(streamName, options) {
|
|
412
|
+
return store.aggregateStream(streamName, {
|
|
413
|
+
evolve: options.evolve,
|
|
414
|
+
initialState: options.initialState,
|
|
415
|
+
read: normalizeReadOptions(options.read)
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
function appendToStream(streamName, events, options) {
|
|
419
|
+
return store.appendToStream(streamName, events, options);
|
|
420
|
+
}
|
|
421
|
+
return {
|
|
422
|
+
readStream,
|
|
423
|
+
aggregateStream,
|
|
424
|
+
appendToStream
|
|
425
|
+
};
|
|
426
|
+
}
|
|
340
427
|
function getFirestoreEventStore(firestore, options) {
|
|
341
428
|
return new FirestoreEventStoreImpl(firestore, options);
|
|
342
429
|
}
|
|
@@ -354,6 +441,7 @@ Object.defineProperty(exports, "STREAM_EXISTS", {
|
|
|
354
441
|
get: function () { return emmett.STREAM_EXISTS; }
|
|
355
442
|
});
|
|
356
443
|
exports.ExpectedVersionConflictError = ExpectedVersionConflictError;
|
|
444
|
+
exports.asEventStore = asEventStore;
|
|
357
445
|
exports.assertExpectedVersionMatchesCurrent = assertExpectedVersionMatchesCurrent;
|
|
358
446
|
exports.calculateNextVersion = calculateNextVersion;
|
|
359
447
|
exports.getCurrentStreamVersion = getCurrentStreamVersion;
|