@auriclabs/events 0.1.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/.turbo/turbo-build.log +39 -0
- package/README.md +228 -0
- package/dist/index.cjs +314 -0
- package/dist/index.d.cts +377 -0
- package/dist/index.d.cts.map +1 -0
- package/dist/index.d.mts +377 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +304 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +59 -0
- package/src/context.test.ts +60 -0
- package/src/context.ts +19 -0
- package/src/create-dispatch.test.ts +233 -0
- package/src/create-dispatch.ts +71 -0
- package/src/create-event-listener.test.ts +246 -0
- package/src/create-event-listener.ts +54 -0
- package/src/dispatch-event.test.ts +226 -0
- package/src/dispatch-event.ts +34 -0
- package/src/dispatch-events.test.ts +72 -0
- package/src/dispatch-events.ts +18 -0
- package/src/event-service.test.ts +357 -0
- package/src/event-service.ts +228 -0
- package/src/index.ts +9 -0
- package/src/init.test.ts +55 -0
- package/src/init.ts +14 -0
- package/src/stream-handler.test.ts +309 -0
- package/src/stream-handler.ts +108 -0
- package/src/types.ts +65 -0
- package/tsconfig.json +17 -0
- package/vitest.config.ts +2 -0
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
import { normalizePaginationResponse } from "@auriclabs/pagination";
|
|
2
|
+
import { ConditionalCheckFailedException, DynamoDBClient } from "@aws-sdk/client-dynamodb";
|
|
3
|
+
import { DynamoDBDocumentClient, GetCommand, QueryCommand, TransactWriteCommand } from "@aws-sdk/lib-dynamodb";
|
|
4
|
+
import { retry } from "@auriclabs/api-core";
|
|
5
|
+
import { logger } from "@auriclabs/logger";
|
|
6
|
+
import { ulid } from "ulid";
|
|
7
|
+
import { EventBridgeClient, PutEventsCommand } from "@aws-sdk/client-eventbridge";
|
|
8
|
+
import { SQSClient, SendMessageBatchCommand } from "@aws-sdk/client-sqs";
|
|
9
|
+
import { unmarshall } from "@aws-sdk/util-dynamodb";
|
|
10
|
+
import { kebabCase } from "lodash-es";
|
|
11
|
+
//#region src/event-service.ts
|
|
12
|
+
const ddb = DynamoDBDocumentClient.from(new DynamoDBClient(), { marshallOptions: { removeUndefinedValues: true } });
|
|
13
|
+
const pad = (n, w = 9) => String(n).padStart(w, "0");
|
|
14
|
+
const pkFor = (aggregateType, aggregateId) => `AGG#${aggregateType}#${aggregateId}`;
|
|
15
|
+
function createEventService(tableName) {
|
|
16
|
+
const TABLE = tableName;
|
|
17
|
+
return {
|
|
18
|
+
async appendEvent(args) {
|
|
19
|
+
const { aggregateType, aggregateId, expectedVersion, idempotencyKey, eventId, eventType, occurredAt, source, payload, schemaVersion, correlationId, causationId, actorId } = args;
|
|
20
|
+
const pk = pkFor(aggregateType, aggregateId);
|
|
21
|
+
const nextVersion = expectedVersion + 1;
|
|
22
|
+
const sk = `EVT#${pad(nextVersion)}`;
|
|
23
|
+
const nowIso = (/* @__PURE__ */ new Date()).toISOString();
|
|
24
|
+
const eventOccurredAt = occurredAt ?? nowIso;
|
|
25
|
+
try {
|
|
26
|
+
await ddb.send(new TransactWriteCommand({ TransactItems: [{ Update: {
|
|
27
|
+
TableName: TABLE,
|
|
28
|
+
Key: {
|
|
29
|
+
pk,
|
|
30
|
+
sk: "HEAD"
|
|
31
|
+
},
|
|
32
|
+
UpdateExpression: "SET currentVersion = :next, lastEventId = :eid, lastIdemKey = :idem, updatedAt = :now, aggregateId = if_not_exists(aggregateId, :aid), aggregateType = if_not_exists(aggregateType, :atype)",
|
|
33
|
+
ConditionExpression: "(attribute_not_exists(currentVersion) AND :expected = :zero) OR currentVersion = :expected OR lastIdemKey = :idem",
|
|
34
|
+
ExpressionAttributeValues: {
|
|
35
|
+
":zero": 0,
|
|
36
|
+
":expected": expectedVersion,
|
|
37
|
+
":next": nextVersion,
|
|
38
|
+
":eid": eventId,
|
|
39
|
+
":idem": idempotencyKey,
|
|
40
|
+
":now": nowIso,
|
|
41
|
+
":aid": aggregateId,
|
|
42
|
+
":atype": aggregateType
|
|
43
|
+
}
|
|
44
|
+
} }, { Put: {
|
|
45
|
+
TableName: TABLE,
|
|
46
|
+
Item: {
|
|
47
|
+
pk,
|
|
48
|
+
sk,
|
|
49
|
+
itemType: "event",
|
|
50
|
+
source,
|
|
51
|
+
aggregateId,
|
|
52
|
+
aggregateType,
|
|
53
|
+
version: nextVersion,
|
|
54
|
+
eventId,
|
|
55
|
+
eventType,
|
|
56
|
+
schemaVersion: schemaVersion ?? 1,
|
|
57
|
+
occurredAt: eventOccurredAt,
|
|
58
|
+
correlationId,
|
|
59
|
+
causationId,
|
|
60
|
+
actorId,
|
|
61
|
+
payload
|
|
62
|
+
},
|
|
63
|
+
ConditionExpression: "attribute_not_exists(pk) OR eventId = :eid",
|
|
64
|
+
ExpressionAttributeValues: { ":eid": eventId }
|
|
65
|
+
} }] }));
|
|
66
|
+
} catch (err) {
|
|
67
|
+
if (err instanceof ConditionalCheckFailedException) throw new Error(`OCC failed for aggregate ${aggregateType}/${aggregateId}: expectedVersion=${expectedVersion}`);
|
|
68
|
+
throw err;
|
|
69
|
+
}
|
|
70
|
+
return {
|
|
71
|
+
pk,
|
|
72
|
+
sk,
|
|
73
|
+
version: nextVersion
|
|
74
|
+
};
|
|
75
|
+
},
|
|
76
|
+
async getHead(aggregateType, aggregateId) {
|
|
77
|
+
const pk = pkFor(aggregateType, aggregateId);
|
|
78
|
+
return (await ddb.send(new GetCommand({
|
|
79
|
+
TableName: TABLE,
|
|
80
|
+
Key: {
|
|
81
|
+
pk,
|
|
82
|
+
sk: "HEAD"
|
|
83
|
+
}
|
|
84
|
+
}))).Item;
|
|
85
|
+
},
|
|
86
|
+
async getEvent(aggregateType, aggregateId, version) {
|
|
87
|
+
const pk = pkFor(aggregateType, aggregateId);
|
|
88
|
+
const sk = `EVT#${pad(version)}`;
|
|
89
|
+
return (await ddb.send(new GetCommand({
|
|
90
|
+
TableName: TABLE,
|
|
91
|
+
Key: {
|
|
92
|
+
pk,
|
|
93
|
+
sk
|
|
94
|
+
}
|
|
95
|
+
}))).Item;
|
|
96
|
+
},
|
|
97
|
+
async listEvents(params) {
|
|
98
|
+
const pk = pkFor(params.aggregateType, params.aggregateId);
|
|
99
|
+
const fromSk = params.fromVersionExclusive != null ? `EVT#${pad(params.fromVersionExclusive + 1)}` : "EVT#000000000";
|
|
100
|
+
const toSk = params.toVersionInclusive != null ? `EVT#${pad(params.toVersionInclusive)}` : "EVT#999999999";
|
|
101
|
+
const res = await ddb.send(new QueryCommand({
|
|
102
|
+
TableName: TABLE,
|
|
103
|
+
KeyConditionExpression: "pk = :pk AND sk BETWEEN :from AND :to",
|
|
104
|
+
ExpressionAttributeValues: {
|
|
105
|
+
":pk": pk,
|
|
106
|
+
":from": fromSk,
|
|
107
|
+
":to": toSk
|
|
108
|
+
},
|
|
109
|
+
ScanIndexForward: true,
|
|
110
|
+
Limit: params.limit
|
|
111
|
+
}));
|
|
112
|
+
return normalizePaginationResponse({
|
|
113
|
+
data: res.Items ?? [],
|
|
114
|
+
cursor: res.LastEvaluatedKey && res.LastEvaluatedKey.sk
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
//#endregion
|
|
120
|
+
//#region src/init.ts
|
|
121
|
+
let _eventService;
|
|
122
|
+
function initEvents(config) {
|
|
123
|
+
_eventService = createEventService(config.tableName);
|
|
124
|
+
}
|
|
125
|
+
function getEventService() {
|
|
126
|
+
if (!_eventService) throw new Error("Call initEvents() before using events");
|
|
127
|
+
return _eventService;
|
|
128
|
+
}
|
|
129
|
+
//#endregion
|
|
130
|
+
//#region src/context.ts
|
|
131
|
+
let context = {};
|
|
132
|
+
const setEventContext = (newContext) => {
|
|
133
|
+
context = { ...newContext };
|
|
134
|
+
};
|
|
135
|
+
const getEventContext = () => context;
|
|
136
|
+
const resetEventContext = () => {
|
|
137
|
+
context = {};
|
|
138
|
+
};
|
|
139
|
+
const appendEventContext = (event) => {
|
|
140
|
+
context = {
|
|
141
|
+
...context,
|
|
142
|
+
...event
|
|
143
|
+
};
|
|
144
|
+
};
|
|
145
|
+
//#endregion
|
|
146
|
+
//#region src/dispatch-event.ts
|
|
147
|
+
const dispatchEvent = async (event) => {
|
|
148
|
+
const eventService = getEventService();
|
|
149
|
+
const eventId = event.eventId ?? `evt-${ulid()}`;
|
|
150
|
+
const occurredAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
151
|
+
const idempotencyKey = event.idempotencyKey ?? eventId;
|
|
152
|
+
return retry(async () => {
|
|
153
|
+
const head = await eventService.getHead(event.aggregateType, event.aggregateId);
|
|
154
|
+
logger.debug({ event }, "Dispatching event");
|
|
155
|
+
return eventService.appendEvent({
|
|
156
|
+
...getEventContext(),
|
|
157
|
+
...event,
|
|
158
|
+
eventId,
|
|
159
|
+
expectedVersion: head?.currentVersion ?? 0,
|
|
160
|
+
schemaVersion: 1,
|
|
161
|
+
occurredAt,
|
|
162
|
+
idempotencyKey
|
|
163
|
+
});
|
|
164
|
+
});
|
|
165
|
+
};
|
|
166
|
+
//#endregion
|
|
167
|
+
//#region src/dispatch-events.ts
|
|
168
|
+
const dispatchEvents = async (events, { inOrder = false } = {}) => {
|
|
169
|
+
if (inOrder) for (const event of events) await dispatchEvent(event);
|
|
170
|
+
else await Promise.all(events.map((event) => dispatchEvent(event)));
|
|
171
|
+
};
|
|
172
|
+
//#endregion
|
|
173
|
+
//#region src/create-dispatch.ts
|
|
174
|
+
function createDispatch(record, optionsOrFactory) {
|
|
175
|
+
return Object.fromEntries(Object.entries(record).map(([key, value]) => [key, (...args) => {
|
|
176
|
+
const eventId = `evt-${ulid()}`;
|
|
177
|
+
const result = value(...args);
|
|
178
|
+
const context = {
|
|
179
|
+
eventId,
|
|
180
|
+
...getEventContext()
|
|
181
|
+
};
|
|
182
|
+
const executeValueFn = (value) => typeof value === "function" ? value(context) : value;
|
|
183
|
+
const parseResponse = (result) => Object.fromEntries(Object.entries(result).map(([key, value]) => [key, executeValueFn(value)]));
|
|
184
|
+
Object.assign(context, typeof result === "function" ? result(context) : parseResponse(result));
|
|
185
|
+
Object.assign(context, typeof optionsOrFactory === "function" ? optionsOrFactory(context) : parseResponse(optionsOrFactory));
|
|
186
|
+
return dispatchEvent(context);
|
|
187
|
+
}]));
|
|
188
|
+
}
|
|
189
|
+
//#endregion
|
|
190
|
+
//#region src/create-event-listener.ts
|
|
191
|
+
const createEventListener = (eventHandlers, { debug = false } = {}) => async (sqsEvent) => {
|
|
192
|
+
const response = { batchItemFailures: [] };
|
|
193
|
+
let hasFailed = false;
|
|
194
|
+
for (const record of sqsEvent.Records) {
|
|
195
|
+
if (hasFailed) {
|
|
196
|
+
response.batchItemFailures.push({ itemIdentifier: record.messageId });
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
let event;
|
|
200
|
+
try {
|
|
201
|
+
event = JSON.parse(record.body);
|
|
202
|
+
if (debug) logger.debug({ event }, "Processing event");
|
|
203
|
+
let handler = eventHandlers[event.eventType];
|
|
204
|
+
while (typeof handler === "string") handler = eventHandlers[handler];
|
|
205
|
+
if (typeof handler === "function") {
|
|
206
|
+
setEventContext({
|
|
207
|
+
causationId: event.eventId,
|
|
208
|
+
correlationId: event.correlationId,
|
|
209
|
+
actorId: event.actorId
|
|
210
|
+
});
|
|
211
|
+
await handler(event);
|
|
212
|
+
}
|
|
213
|
+
} catch (error) {
|
|
214
|
+
hasFailed = true;
|
|
215
|
+
logger.error({
|
|
216
|
+
error,
|
|
217
|
+
event,
|
|
218
|
+
body: record.body
|
|
219
|
+
}, "Error processing event");
|
|
220
|
+
response.batchItemFailures.push({ itemIdentifier: record.messageId });
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
return response;
|
|
224
|
+
};
|
|
225
|
+
//#endregion
|
|
226
|
+
//#region src/stream-handler.ts
|
|
227
|
+
const BATCH_SIZE = 10;
|
|
228
|
+
/**
|
|
229
|
+
* Creates a Lambda handler for DynamoDB stream events.
|
|
230
|
+
* Processes INSERT events from the event store table and forwards them to SQS queues and EventBridge.
|
|
231
|
+
*/
|
|
232
|
+
function createStreamHandler(config) {
|
|
233
|
+
const sqsClient = new SQSClient();
|
|
234
|
+
const eventBridge = new EventBridgeClient({});
|
|
235
|
+
function chunkArray(array, chunkSize) {
|
|
236
|
+
const chunks = [];
|
|
237
|
+
for (let i = 0; i < array.length; i += chunkSize) chunks.push(array.slice(i, i + chunkSize));
|
|
238
|
+
return chunks;
|
|
239
|
+
}
|
|
240
|
+
async function sendToQueuesBatch(eventRecords) {
|
|
241
|
+
await Promise.all(config.queueUrls.map((queue) => sendToQueueBatch(eventRecords, queue)));
|
|
242
|
+
}
|
|
243
|
+
async function sendToQueueBatch(eventRecords, queue) {
|
|
244
|
+
const batches = chunkArray(eventRecords, BATCH_SIZE);
|
|
245
|
+
for (const batch of batches) try {
|
|
246
|
+
const entries = batch.map((eventRecord, index) => ({
|
|
247
|
+
Id: `${eventRecord.eventId}-${index}`,
|
|
248
|
+
MessageBody: JSON.stringify(eventRecord),
|
|
249
|
+
MessageGroupId: eventRecord.aggregateId,
|
|
250
|
+
MessageDeduplicationId: eventRecord.eventId
|
|
251
|
+
}));
|
|
252
|
+
await sqsClient.send(new SendMessageBatchCommand({
|
|
253
|
+
QueueUrl: queue,
|
|
254
|
+
Entries: entries
|
|
255
|
+
}));
|
|
256
|
+
} catch (error) {
|
|
257
|
+
logger.error({
|
|
258
|
+
error,
|
|
259
|
+
batch,
|
|
260
|
+
queue
|
|
261
|
+
}, "Error sending batch to queue");
|
|
262
|
+
throw error;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
async function sendToBusBatch(eventRecords) {
|
|
266
|
+
const batches = chunkArray(eventRecords, BATCH_SIZE);
|
|
267
|
+
for (const batch of batches) try {
|
|
268
|
+
const entries = batch.map((eventRecord) => {
|
|
269
|
+
return {
|
|
270
|
+
Source: eventRecord.source ?? kebabCase(eventRecord.aggregateType.split(".")[0]),
|
|
271
|
+
DetailType: eventRecord.eventType,
|
|
272
|
+
Detail: JSON.stringify(eventRecord),
|
|
273
|
+
EventBusName: config.busName
|
|
274
|
+
};
|
|
275
|
+
});
|
|
276
|
+
await eventBridge.send(new PutEventsCommand({ Entries: entries }));
|
|
277
|
+
} catch (error) {
|
|
278
|
+
logger.error({
|
|
279
|
+
error,
|
|
280
|
+
batch
|
|
281
|
+
}, "Error sending batch to bus");
|
|
282
|
+
throw error;
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
return async (event) => {
|
|
286
|
+
const eventRecords = event.Records.filter((record) => record.eventName === "INSERT").map((record) => {
|
|
287
|
+
try {
|
|
288
|
+
const data = record.dynamodb?.NewImage;
|
|
289
|
+
return unmarshall(data);
|
|
290
|
+
} catch (error) {
|
|
291
|
+
logger.error({
|
|
292
|
+
error,
|
|
293
|
+
record
|
|
294
|
+
}, "Error unmarshalling event record");
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
}).filter((eventRecord) => eventRecord?.itemType === "event");
|
|
298
|
+
if (eventRecords.length > 0) await Promise.all([sendToBusBatch(eventRecords), sendToQueuesBatch(eventRecords)]);
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
//#endregion
|
|
302
|
+
export { appendEventContext, createDispatch, createEventListener, createEventService, createStreamHandler, dispatchEvent, dispatchEvents, getEventContext, getEventService, initEvents, resetEventContext, setEventContext };
|
|
303
|
+
|
|
304
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/event-service.ts","../src/init.ts","../src/context.ts","../src/dispatch-event.ts","../src/dispatch-events.ts","../src/create-dispatch.ts","../src/create-event-listener.ts","../src/stream-handler.ts"],"sourcesContent":["import { normalizePaginationResponse, PaginationResponse } from '@auriclabs/pagination';\nimport { DynamoDBClient, ConditionalCheckFailedException } from '@aws-sdk/client-dynamodb';\nimport {\n DynamoDBDocumentClient,\n TransactWriteCommand,\n GetCommand,\n QueryCommand,\n} from '@aws-sdk/lib-dynamodb';\n\nimport type {\n EventRecord,\n AggregateHead,\n AggregatePK,\n EventId,\n AggregateId,\n AggregateType,\n EventSK,\n Source,\n} from './types';\n\nconst ddb = DynamoDBDocumentClient.from(new DynamoDBClient(), {\n marshallOptions: {\n removeUndefinedValues: true,\n },\n});\n\nconst pad = (n: number, w = 9): EventId => String(n).padStart(w, '0') as EventId;\nconst pkFor = (aggregateType: string, aggregateId: string): AggregatePK =>\n `AGG#${aggregateType}#${aggregateId}`;\n\nexport interface AppendArgs<P = unknown> {\n aggregateType: string;\n aggregateId: string;\n source: string;\n /** Version you observed before appending (0 for brand new) */\n expectedVersion: number;\n /** Required for idempotent retries (e.g., the command id) */\n idempotencyKey: string;\n\n // Event properties (flattened)\n eventId: string; // ULID/UUID – must be stable across retries\n eventType: string;\n occurredAt?: string; // default: now ISO\n payload?: Readonly<P>;\n schemaVersion?: number; // optional but recommended\n\n // Optional metadata\n correlationId?: string;\n causationId?: string;\n actorId?: string;\n}\n\nexport interface AppendEventResult {\n pk: string;\n sk: string;\n version: number;\n}\n\nexport interface EventService {\n appendEvent<P = unknown>(args: AppendArgs<P>): Promise<AppendEventResult>;\n getHead(aggregateType: string, aggregateId: string): Promise<AggregateHead | undefined>;\n getEvent(\n aggregateType: string,\n aggregateId: string,\n version: number,\n ): Promise<EventRecord | undefined>;\n listEvents(params: {\n aggregateType: string;\n aggregateId: string;\n fromVersionExclusive?: number;\n toVersionInclusive?: number;\n limit?: number;\n }): Promise<PaginationResponse<EventRecord>>;\n}\n\nexport function createEventService(tableName: string): EventService {\n const TABLE = tableName;\n\n return {\n async appendEvent<P = unknown>(args: AppendArgs<P>): Promise<AppendEventResult> {\n const {\n aggregateType,\n aggregateId,\n expectedVersion,\n idempotencyKey,\n eventId,\n eventType,\n occurredAt,\n source,\n payload,\n schemaVersion,\n correlationId,\n causationId,\n actorId,\n } = args;\n\n const pk = pkFor(aggregateType, aggregateId);\n const nextVersion = expectedVersion + 1;\n const sk = `EVT#${pad(nextVersion)}` as EventSK;\n const nowIso = new Date().toISOString();\n const eventOccurredAt = occurredAt ?? nowIso;\n\n try {\n await ddb.send(\n new TransactWriteCommand({\n TransactItems: [\n {\n Update: {\n TableName: TABLE,\n Key: { pk, sk: 'HEAD' },\n UpdateExpression:\n 'SET currentVersion = :next, lastEventId = :eid, lastIdemKey = :idem, updatedAt = :now, aggregateId = if_not_exists(aggregateId, :aid), aggregateType = if_not_exists(aggregateType, :atype)',\n ConditionExpression:\n '(attribute_not_exists(currentVersion) AND :expected = :zero) ' +\n 'OR currentVersion = :expected ' +\n 'OR lastIdemKey = :idem',\n ExpressionAttributeValues: {\n ':zero': 0,\n ':expected': expectedVersion,\n ':next': nextVersion,\n ':eid': eventId,\n ':idem': idempotencyKey,\n ':now': nowIso,\n ':aid': aggregateId,\n ':atype': aggregateType,\n },\n },\n },\n {\n Put: {\n TableName: TABLE,\n Item: {\n pk,\n sk,\n itemType: 'event',\n source: source as Source,\n aggregateId: aggregateId as AggregateId,\n aggregateType: aggregateType as AggregateType,\n version: nextVersion,\n\n eventId: eventId as EventId,\n eventType: eventType,\n schemaVersion: schemaVersion ?? 1,\n occurredAt: eventOccurredAt,\n\n correlationId,\n causationId,\n actorId,\n\n payload: payload as Readonly<unknown>,\n } satisfies EventRecord,\n ConditionExpression: 'attribute_not_exists(pk) OR eventId = :eid',\n ExpressionAttributeValues: { ':eid': eventId },\n },\n },\n ],\n }),\n );\n } catch (err) {\n if (err instanceof ConditionalCheckFailedException) {\n throw new Error(\n `OCC failed for aggregate ${aggregateType}/${aggregateId}: expectedVersion=${expectedVersion}`,\n );\n }\n throw err;\n }\n\n return { pk, sk, version: nextVersion };\n },\n\n async getHead(\n aggregateType: string,\n aggregateId: string,\n ): Promise<AggregateHead | undefined> {\n const pk = pkFor(aggregateType, aggregateId);\n const res = await ddb.send(new GetCommand({ TableName: TABLE, Key: { pk, sk: 'HEAD' } }));\n return res.Item as AggregateHead | undefined;\n },\n\n async getEvent(\n aggregateType: string,\n aggregateId: string,\n version: number,\n ): Promise<EventRecord | undefined> {\n const pk = pkFor(aggregateType, aggregateId);\n const sk = `EVT#${pad(version)}`;\n const res = await ddb.send(new GetCommand({ TableName: TABLE, Key: { pk, sk } }));\n return res.Item as EventRecord | undefined;\n },\n\n async listEvents(params: {\n aggregateType: string;\n aggregateId: string;\n fromVersionExclusive?: number;\n toVersionInclusive?: number;\n limit?: number;\n }): Promise<PaginationResponse<EventRecord>> {\n const pk = pkFor(params.aggregateType, params.aggregateId);\n const fromSk =\n params.fromVersionExclusive != null\n ? `EVT#${pad(params.fromVersionExclusive + 1)}`\n : 'EVT#000000000';\n const toSk =\n params.toVersionInclusive != null\n ? `EVT#${pad(params.toVersionInclusive)}`\n : 'EVT#999999999';\n\n const res = await ddb.send(\n new QueryCommand({\n TableName: TABLE,\n KeyConditionExpression: 'pk = :pk AND sk BETWEEN :from AND :to',\n ExpressionAttributeValues: {\n ':pk': pk,\n ':from': fromSk,\n ':to': toSk,\n },\n ScanIndexForward: true,\n Limit: params.limit,\n }),\n );\n\n return normalizePaginationResponse({\n data: (res.Items ?? []) as EventRecord[],\n cursor: res.LastEvaluatedKey && (res.LastEvaluatedKey as { pk: string; sk: string }).sk,\n });\n },\n };\n}\n","import { createEventService, EventService } from './event-service';\n\nlet _eventService: EventService | undefined;\n\nexport function initEvents(config: { tableName: string }): void {\n _eventService = createEventService(config.tableName);\n}\n\nexport function getEventService(): EventService {\n if (!_eventService) {\n throw new Error('Call initEvents() before using events');\n }\n return _eventService;\n}\n","import { AppendArgs } from './event-service';\n\nexport type EventContext = Partial<AppendArgs>;\n\nlet context: EventContext = {};\n\nexport const setEventContext = (newContext: EventContext) => {\n context = { ...newContext };\n};\n\nexport const getEventContext = () => context;\n\nexport const resetEventContext = () => {\n context = {};\n};\n\nexport const appendEventContext = (event: EventContext) => {\n context = { ...context, ...event };\n};\n","import { retry } from '@auriclabs/api-core';\nimport { logger } from '@auriclabs/logger';\nimport { ulid } from 'ulid';\n\nimport { AppendArgs, AppendEventResult } from './event-service';\nimport { getEventService } from './init';\nimport { getEventContext } from './context';\n\nexport type DispatchEventArgs = Omit<\n AppendArgs,\n 'eventId' | 'expectedVersion' | 'schemaVersion' | 'occurredAt' | 'idempotencyKey'\n> &\n Partial<Pick<AppendArgs, 'idempotencyKey' | 'eventId'>>;\n\nexport const dispatchEvent = async (event: DispatchEventArgs): Promise<AppendEventResult> => {\n const eventService = getEventService();\n const eventId = event.eventId ?? `evt-${ulid()}`;\n const occurredAt = new Date().toISOString();\n const idempotencyKey = event.idempotencyKey ?? eventId;\n\n return retry(async () => {\n const head = await eventService.getHead(event.aggregateType, event.aggregateId);\n logger.debug({ event }, 'Dispatching event');\n return eventService.appendEvent({\n ...getEventContext(),\n ...event,\n eventId,\n expectedVersion: head?.currentVersion ?? 0,\n schemaVersion: 1,\n occurredAt,\n idempotencyKey,\n });\n });\n};\n","import { dispatchEvent, DispatchEventArgs } from './dispatch-event';\n\nexport interface DispatchEventsArgs {\n inOrder?: boolean;\n}\n\nexport const dispatchEvents = async (\n events: DispatchEventArgs[],\n { inOrder = false }: DispatchEventsArgs = {},\n) => {\n if (inOrder) {\n for (const event of events) {\n await dispatchEvent(event);\n }\n } else {\n await Promise.all(events.map((event) => dispatchEvent(event)));\n }\n};\n","import { ulid } from 'ulid';\n\nimport { EventContext, getEventContext } from './context';\nimport { dispatchEvent, DispatchEventArgs } from './dispatch-event';\nimport { AppendEventResult } from './event-service';\n\nexport type MakePartial<T, O> = Omit<T, keyof O> & Partial<O>;\n\nexport type DispatchRecord<\n Options extends Partial<DispatchEventArgs> = Partial<DispatchEventArgs>,\n> = Record<\n string,\n (\n ...args: any[]\n ) =>\n | ValueOrFactoryRecord<MakePartial<DispatchEventArgs, Options>>\n | DispatchEventArgsFactory<Options>\n>;\n\nexport type ValueOrFactory<T> = T | ((context: EventContext) => T);\nexport type ValueOrFactoryRecord<T> = {\n [K in keyof T]: ValueOrFactory<T[K]>;\n};\n\nexport type DispatchEventArgsFactory<Options extends Partial<DispatchEventArgs>> = (\n context: EventContext,\n) => MakePartial<DispatchEventArgs, Options>;\n\nexport type DispatchRecordResponse<\n R extends DispatchRecord<O>,\n O extends Partial<DispatchEventArgs>,\n> = {\n [K in keyof R]: (...args: Parameters<R[K]>) => Promise<AppendEventResult>;\n};\n\nexport function createDispatch<DR extends DispatchRecord<O>, O extends Partial<DispatchEventArgs>>(\n record: DR,\n optionsOrFactory?: ValueOrFactoryRecord<O> | ((context: EventContext) => O),\n): DispatchRecordResponse<DR, O> {\n return Object.fromEntries(\n Object.entries(record).map(([key, value]) => [\n key,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (...args: any[]) => {\n const eventId = `evt-${ulid()}`;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n const result = value(...args);\n const context: EventContext = { eventId, ...getEventContext() };\n const executeValueFn = (value: any) =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call\n typeof value === 'function' ? value(context) : value;\n const parseResponse = (result: any) =>\n Object.fromEntries(\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n Object.entries(result).map(([key, value]) => [key, executeValueFn(value)]),\n );\n Object.assign(\n context,\n typeof result === 'function' ? result(context) : parseResponse(result),\n );\n Object.assign(\n context,\n typeof optionsOrFactory === 'function'\n ? optionsOrFactory(context)\n : parseResponse(optionsOrFactory),\n );\n return dispatchEvent(context as DispatchEventArgs);\n },\n ]),\n ) as DispatchRecordResponse<DR, O>;\n}\n","import { logger } from '@auriclabs/logger';\nimport { SQSBatchResponse, SQSEvent } from 'aws-lambda';\n\nimport { setEventContext } from './context';\nimport { EventHandlers, EventRecord } from './types';\n\nexport interface CreateEventListenerOptions {\n debug?: boolean;\n}\n\nexport const createEventListener =\n (eventHandlers: EventHandlers, { debug = false }: CreateEventListenerOptions = {}) =>\n async (sqsEvent: SQSEvent) => {\n const response: SQSBatchResponse = {\n batchItemFailures: [],\n };\n let hasFailed = false;\n for (const record of sqsEvent.Records) {\n // skip the job if it has failed\n if (hasFailed) {\n response.batchItemFailures.push({\n itemIdentifier: record.messageId,\n });\n continue;\n }\n\n let event: EventRecord | undefined;\n try {\n event = JSON.parse(record.body) as EventRecord;\n if (debug) {\n logger.debug({ event }, 'Processing event');\n }\n let handler = eventHandlers[event.eventType];\n while (typeof handler === 'string') {\n handler = eventHandlers[handler];\n }\n if (typeof handler === 'function') {\n setEventContext({\n causationId: event.eventId,\n correlationId: event.correlationId,\n actorId: event.actorId,\n });\n await handler(event);\n }\n } catch (error) {\n hasFailed = true;\n logger.error({ error, event, body: record.body }, 'Error processing event');\n response.batchItemFailures.push({\n itemIdentifier: record.messageId,\n });\n }\n }\n return response;\n };\n","import { logger } from '@auriclabs/logger';\nimport { AttributeValue } from '@aws-sdk/client-dynamodb';\nimport { EventBridgeClient, PutEventsCommand } from '@aws-sdk/client-eventbridge';\nimport { SendMessageBatchCommand, SQSClient } from '@aws-sdk/client-sqs';\nimport { unmarshall } from '@aws-sdk/util-dynamodb';\nimport { DynamoDBStreamEvent } from 'aws-lambda';\nimport { kebabCase } from 'lodash-es';\n\nimport { AggregateHead, EventRecord } from './types';\n\nconst BATCH_SIZE = 10;\n\nexport interface CreateStreamHandlerConfig {\n busName: string;\n queueUrls: string[];\n}\n\n/**\n * Creates a Lambda handler for DynamoDB stream events.\n * Processes INSERT events from the event store table and forwards them to SQS queues and EventBridge.\n */\nexport function createStreamHandler(config: CreateStreamHandlerConfig) {\n const sqsClient = new SQSClient();\n const eventBridge = new EventBridgeClient({});\n\n function chunkArray<T>(array: T[], chunkSize: number): T[][] {\n const chunks: T[][] = [];\n for (let i = 0; i < array.length; i += chunkSize) {\n chunks.push(array.slice(i, i + chunkSize));\n }\n return chunks;\n }\n\n async function sendToQueuesBatch(eventRecords: EventRecord[]) {\n await Promise.all(config.queueUrls.map((queue) => sendToQueueBatch(eventRecords, queue)));\n }\n\n async function sendToQueueBatch(eventRecords: EventRecord[], queue: string) {\n const batches = chunkArray(eventRecords, BATCH_SIZE);\n\n for (const batch of batches) {\n try {\n const entries = batch.map((eventRecord, index) => ({\n Id: `${eventRecord.eventId}-${index}`,\n MessageBody: JSON.stringify(eventRecord),\n MessageGroupId: eventRecord.aggregateId,\n MessageDeduplicationId: eventRecord.eventId,\n }));\n\n await sqsClient.send(\n new SendMessageBatchCommand({\n QueueUrl: queue,\n Entries: entries,\n }),\n );\n } catch (error) {\n logger.error({ error, batch, queue }, 'Error sending batch to queue');\n throw error;\n }\n }\n }\n\n async function sendToBusBatch(eventRecords: EventRecord[]) {\n const batches = chunkArray(eventRecords, BATCH_SIZE);\n\n for (const batch of batches) {\n try {\n const entries = batch.map((eventRecord) => {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const source = eventRecord.source ?? kebabCase(eventRecord.aggregateType.split('.')[0]);\n return {\n Source: source,\n DetailType: eventRecord.eventType,\n Detail: JSON.stringify(eventRecord),\n EventBusName: config.busName,\n };\n });\n\n await eventBridge.send(\n new PutEventsCommand({\n Entries: entries,\n }),\n );\n } catch (error) {\n logger.error({ error, batch }, 'Error sending batch to bus');\n throw error;\n }\n }\n }\n\n return async (event: DynamoDBStreamEvent): Promise<void> => {\n const eventRecords = event.Records.filter((record) => record.eventName === 'INSERT')\n .map((record) => {\n try {\n const data = record.dynamodb?.NewImage;\n return unmarshall(data as Record<string, AttributeValue>) as EventRecord | AggregateHead;\n } catch (error) {\n logger.error({ error, record }, 'Error unmarshalling event record');\n return undefined;\n }\n })\n .filter((eventRecord): eventRecord is EventRecord => eventRecord?.itemType === 'event');\n\n if (eventRecords.length > 0) {\n await Promise.all([sendToBusBatch(eventRecords), sendToQueuesBatch(eventRecords)]);\n }\n };\n}\n"],"mappings":";;;;;;;;;;;AAoBA,MAAM,MAAM,uBAAuB,KAAK,IAAI,gBAAgB,EAAE,EAC5D,iBAAiB,EACf,uBAAuB,MACxB,EACF,CAAC;AAEF,MAAM,OAAO,GAAW,IAAI,MAAe,OAAO,E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1
|
+
{
|
|
2
|
+
"name": "@auriclabs/events",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Event sourcing runtime utilities for DynamoDB-backed event stores",
|
|
5
|
+
"prettier": "@auriclabs/prettier-config",
|
|
6
|
+
"main": "dist/index.cjs",
|
|
7
|
+
"module": "dist/index.mjs",
|
|
8
|
+
"types": "dist/index.d.mts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.mts",
|
|
12
|
+
"import": "./dist/index.mjs",
|
|
13
|
+
"require": "./dist/index.cjs"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"keywords": [],
|
|
17
|
+
"author": "",
|
|
18
|
+
"type": "module",
|
|
19
|
+
"license": "ISC",
|
|
20
|
+
"dependencies": {
|
|
21
|
+
"lodash-es": "4.17.21",
|
|
22
|
+
"ulid": "^2.3.0"
|
|
23
|
+
},
|
|
24
|
+
"devDependencies": {
|
|
25
|
+
"@types/aws-lambda": "^8.10.148",
|
|
26
|
+
"@types/lodash-es": "4.17.12",
|
|
27
|
+
"@auriclabs/api-core": "0.1.0",
|
|
28
|
+
"@auriclabs/logger": "0.1.0",
|
|
29
|
+
"@auriclabs/pagination": "1.0.0"
|
|
30
|
+
},
|
|
31
|
+
"peerDependencies": {
|
|
32
|
+
"@auriclabs/api-core": "^0.1.0",
|
|
33
|
+
"@auriclabs/logger": "^0.1.0",
|
|
34
|
+
"@auriclabs/pagination": "^0.1.0",
|
|
35
|
+
"@aws-sdk/client-dynamodb": "^3.0.0",
|
|
36
|
+
"@aws-sdk/lib-dynamodb": "^3.0.0",
|
|
37
|
+
"@aws-sdk/client-eventbridge": "^3.0.0",
|
|
38
|
+
"@aws-sdk/client-sqs": "^3.0.0",
|
|
39
|
+
"@aws-sdk/util-dynamodb": "^3.0.0"
|
|
40
|
+
},
|
|
41
|
+
"publishConfig": {
|
|
42
|
+
"registry": "https://registry.npmjs.org/"
|
|
43
|
+
},
|
|
44
|
+
"repository": {
|
|
45
|
+
"type": "git",
|
|
46
|
+
"url": "https://github.com/auriclabs/packages.git",
|
|
47
|
+
"directory": "packages/events"
|
|
48
|
+
},
|
|
49
|
+
"scripts": {
|
|
50
|
+
"build": "tsdown src/index.ts --format cjs,esm --dts --no-hash",
|
|
51
|
+
"dev": "concurrently \"pnpm build --watch\" \"pnpm:y:watch\"",
|
|
52
|
+
"y:watch": "chokidar dist --initial --silent -c \"yalc publish --push\"",
|
|
53
|
+
"lint": "eslint .",
|
|
54
|
+
"lint:fix": "eslint . --fix",
|
|
55
|
+
"typecheck": "ts-config-typecheck",
|
|
56
|
+
"test": "vitest run --passWithNoTests",
|
|
57
|
+
"test:watch": "vitest"
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { setEventContext, getEventContext, resetEventContext, appendEventContext } from './context';
|
|
2
|
+
|
|
3
|
+
describe('context', () => {
|
|
4
|
+
afterEach(() => {
|
|
5
|
+
resetEventContext();
|
|
6
|
+
});
|
|
7
|
+
|
|
8
|
+
describe('getEventContext', () => {
|
|
9
|
+
it('returns empty object by default', () => {
|
|
10
|
+
expect(getEventContext()).toEqual({});
|
|
11
|
+
});
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
describe('setEventContext', () => {
|
|
15
|
+
it('sets the context', () => {
|
|
16
|
+
setEventContext({ aggregateType: 'order', aggregateId: '123' });
|
|
17
|
+
expect(getEventContext()).toEqual({ aggregateType: 'order', aggregateId: '123' });
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
it('replaces the entire context', () => {
|
|
21
|
+
setEventContext({ aggregateType: 'order' });
|
|
22
|
+
setEventContext({ aggregateId: '456' });
|
|
23
|
+
expect(getEventContext()).toEqual({ aggregateId: '456' });
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
it('creates a shallow copy (does not hold reference to input)', () => {
|
|
27
|
+
const input = { aggregateType: 'order' };
|
|
28
|
+
setEventContext(input);
|
|
29
|
+
input.aggregateType = 'changed';
|
|
30
|
+
expect(getEventContext()).toEqual({ aggregateType: 'order' });
|
|
31
|
+
});
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
describe('resetEventContext', () => {
|
|
35
|
+
it('resets to empty object', () => {
|
|
36
|
+
setEventContext({ aggregateType: 'order', aggregateId: '123' });
|
|
37
|
+
resetEventContext();
|
|
38
|
+
expect(getEventContext()).toEqual({});
|
|
39
|
+
});
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
describe('appendEventContext', () => {
|
|
43
|
+
it('merges into existing context', () => {
|
|
44
|
+
setEventContext({ aggregateType: 'order' });
|
|
45
|
+
appendEventContext({ aggregateId: '123' });
|
|
46
|
+
expect(getEventContext()).toEqual({ aggregateType: 'order', aggregateId: '123' });
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it('overwrites existing keys', () => {
|
|
50
|
+
setEventContext({ aggregateType: 'order', aggregateId: '111' });
|
|
51
|
+
appendEventContext({ aggregateId: '222' });
|
|
52
|
+
expect(getEventContext()).toEqual({ aggregateType: 'order', aggregateId: '222' });
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it('works on empty context', () => {
|
|
56
|
+
appendEventContext({ source: 'test-source' });
|
|
57
|
+
expect(getEventContext()).toEqual({ source: 'test-source' });
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
});
|
package/src/context.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { AppendArgs } from './event-service';
|
|
2
|
+
|
|
3
|
+
export type EventContext = Partial<AppendArgs>;
|
|
4
|
+
|
|
5
|
+
let context: EventContext = {};
|
|
6
|
+
|
|
7
|
+
export const setEventContext = (newContext: EventContext) => {
|
|
8
|
+
context = { ...newContext };
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
export const getEventContext = () => context;
|
|
12
|
+
|
|
13
|
+
export const resetEventContext = () => {
|
|
14
|
+
context = {};
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export const appendEventContext = (event: EventContext) => {
|
|
18
|
+
context = { ...context, ...event };
|
|
19
|
+
};
|