@eventualize/dynamodb-storage-adapter 1.0.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/dist/DynamoDbClient.d.ts +3 -0
- package/dist/DynamoDbClient.js +30 -0
- package/dist/DynamoDbClient.js.map +1 -0
- package/dist/EvDBDynamoDBAdmin.d.ts +17 -0
- package/dist/EvDBDynamoDBAdmin.js +101 -0
- package/dist/EvDBDynamoDBAdmin.js.map +1 -0
- package/dist/EvDbDynamoDbStorageAdapter.d.ts +86 -0
- package/dist/EvDbDynamoDbStorageAdapter.js +160 -0
- package/dist/EvDbDynamoDbStorageAdapter.js.map +1 -0
- package/dist/EvDbDynamoDbStorageAdapterQueries.d.ts +39 -0
- package/dist/EvDbDynamoDbStorageAdapterQueries.js +159 -0
- package/dist/EvDbDynamoDbStorageAdapterQueries.js.map +1 -0
- package/models/events-table-schema.json +50 -0
- package/models/messages-table-schema.json +24 -0
- package/models/snapshots-table-schema.json +24 -0
- package/package.json +29 -0
- package/src/DynamoDbClient.ts +32 -0
- package/src/EvDBDynamoDBAdmin.ts +115 -0
- package/src/EvDbDynamoDbStorageAdapter.ts +250 -0
- package/src/EvDbDynamoDbStorageAdapterQueries.ts +210 -0
- package/src/dbModel.json +215 -0
- package/tsconfig.json +21 -0
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
{
|
|
2
|
+
"TableName": "events",
|
|
3
|
+
"AttributeDefinitions": [
|
|
4
|
+
{
|
|
5
|
+
"AttributeName": "stream_address",
|
|
6
|
+
"AttributeType": "S"
|
|
7
|
+
},
|
|
8
|
+
{
|
|
9
|
+
"AttributeName": "offset",
|
|
10
|
+
"AttributeType": "N"
|
|
11
|
+
},
|
|
12
|
+
{
|
|
13
|
+
"AttributeName": "event_type",
|
|
14
|
+
"AttributeType": "S"
|
|
15
|
+
},
|
|
16
|
+
{
|
|
17
|
+
"AttributeName": "captured_at",
|
|
18
|
+
"AttributeType": "S"
|
|
19
|
+
}
|
|
20
|
+
],
|
|
21
|
+
"KeySchema": [
|
|
22
|
+
{
|
|
23
|
+
"AttributeName": "stream_address",
|
|
24
|
+
"KeyType": "HASH"
|
|
25
|
+
},
|
|
26
|
+
{
|
|
27
|
+
"AttributeName": "offset",
|
|
28
|
+
"KeyType": "RANGE"
|
|
29
|
+
}
|
|
30
|
+
],
|
|
31
|
+
"BillingMode": "PAY_PER_REQUEST",
|
|
32
|
+
"GlobalSecondaryIndexes": [
|
|
33
|
+
{
|
|
34
|
+
"IndexName": "event_type__captured_at",
|
|
35
|
+
"KeySchema": [
|
|
36
|
+
{
|
|
37
|
+
"AttributeName": "event_type",
|
|
38
|
+
"KeyType": "HASH"
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
"AttributeName": "captured_at",
|
|
42
|
+
"KeyType": "RANGE"
|
|
43
|
+
}
|
|
44
|
+
],
|
|
45
|
+
"Projection": {
|
|
46
|
+
"ProjectionType": "ALL"
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
]
|
|
50
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
{
|
|
2
|
+
"TableName": "messages",
|
|
3
|
+
"AttributeDefinitions": [
|
|
4
|
+
{
|
|
5
|
+
"AttributeName": "message_addres",
|
|
6
|
+
"AttributeType": "S"
|
|
7
|
+
},
|
|
8
|
+
{
|
|
9
|
+
"AttributeName": "captured_at",
|
|
10
|
+
"AttributeType": "S"
|
|
11
|
+
}
|
|
12
|
+
],
|
|
13
|
+
"KeySchema": [
|
|
14
|
+
{
|
|
15
|
+
"AttributeName": "message_addres",
|
|
16
|
+
"KeyType": "HASH"
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
"AttributeName": "captured_at",
|
|
20
|
+
"KeyType": "RANGE"
|
|
21
|
+
}
|
|
22
|
+
],
|
|
23
|
+
"BillingMode": "PAY_PER_REQUEST"
|
|
24
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
{
|
|
2
|
+
"TableName": "snapshots",
|
|
3
|
+
"AttributeDefinitions": [
|
|
4
|
+
{
|
|
5
|
+
"AttributeName": "view_address",
|
|
6
|
+
"AttributeType": "S"
|
|
7
|
+
},
|
|
8
|
+
{
|
|
9
|
+
"AttributeName": "offset",
|
|
10
|
+
"AttributeType": "N"
|
|
11
|
+
}
|
|
12
|
+
],
|
|
13
|
+
"KeySchema": [
|
|
14
|
+
{
|
|
15
|
+
"AttributeName": "view_address",
|
|
16
|
+
"KeyType": "HASH"
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
"AttributeName": "offset",
|
|
20
|
+
"KeyType": "RANGE"
|
|
21
|
+
}
|
|
22
|
+
],
|
|
23
|
+
"BillingMode": "PAY_PER_REQUEST"
|
|
24
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@eventualize/dynamodb-storage-adapter",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"types": "dist/index.d.ts",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"import": "./dist/index.js",
|
|
10
|
+
"types": "./dist/index.d.ts"
|
|
11
|
+
},
|
|
12
|
+
"./*": "./dist/*.js"
|
|
13
|
+
},
|
|
14
|
+
"scripts": {
|
|
15
|
+
"build": "tsc --build",
|
|
16
|
+
"clean": "rimraf dist",
|
|
17
|
+
"rebuild": "npm run clean && npm run build",
|
|
18
|
+
"test": "echo not tests implemented yet."
|
|
19
|
+
},
|
|
20
|
+
"license": "ISC",
|
|
21
|
+
"type": "module",
|
|
22
|
+
"devDependencies": {
|
|
23
|
+
"@types/node": "^24.10.1"
|
|
24
|
+
},
|
|
25
|
+
"dependencies": {
|
|
26
|
+
"@aws-sdk/client-dynamodb": "^3.948.0",
|
|
27
|
+
"@aws-sdk/util-dynamodb": "^3.948.0"
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// src/dynamo-client.ts
|
|
2
|
+
import { DynamoDBClient, DynamoDBClientConfig, ListTablesCommand } from "@aws-sdk/client-dynamodb";
|
|
3
|
+
|
|
4
|
+
export async function listTables(client: DynamoDBClient) {
|
|
5
|
+
try {
|
|
6
|
+
const command = new ListTablesCommand({});
|
|
7
|
+
const response = await client.send(command);
|
|
8
|
+
console.log("Tables in DynamoDB Local:", response.TableNames);
|
|
9
|
+
return response.TableNames;
|
|
10
|
+
} catch (error) {
|
|
11
|
+
console.error("Error listing tables:", error);
|
|
12
|
+
throw error;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function createDynamoDBClient(): DynamoDBClient {
|
|
17
|
+
const endpoint = process.env.DYNAMODB_URL;
|
|
18
|
+
const accessKeyId = process.env.AWS_ACCESS_KEY_ID;
|
|
19
|
+
const secretAccessKey = process.env.AWS_SECRET_ACCESS_KEY;
|
|
20
|
+
const region = process.env.AWS_REGION || 'us-east-1';
|
|
21
|
+
|
|
22
|
+
if (!endpoint || !accessKeyId || !secretAccessKey) {
|
|
23
|
+
const envVars = { endpoint, accessKeyId, secretAccessKey };
|
|
24
|
+
throw new Error("AWS credentials are not set in environment variables: " + JSON.stringify(envVars));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const config: DynamoDBClientConfig = {};
|
|
28
|
+
config.endpoint = endpoint;
|
|
29
|
+
config.credentials = { accessKeyId, secretAccessKey };
|
|
30
|
+
config.region = region;
|
|
31
|
+
return new DynamoDBClient(config);
|
|
32
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { AttributeValue, BatchWriteItemCommand, DynamoDBClient, ScanCommand, WriteRequest } from "@aws-sdk/client-dynamodb";
|
|
2
|
+
import IEvDbStorageAdmin from "@eventualize/types/IEvDbStorageAdmin";
|
|
3
|
+
import { createDynamoDBClient } from "./DynamoDbClient.js";
|
|
4
|
+
|
|
5
|
+
export default class EvDbDynamoDbAdmin implements IEvDbStorageAdmin {
|
|
6
|
+
private dynamoDbClient: DynamoDBClient
|
|
7
|
+
constructor() {
|
|
8
|
+
this.dynamoDbClient = createDynamoDBClient();
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
// Helper function to extract keys in raw DynamoDB format
|
|
12
|
+
private extractKeys(tableName: string, items: Record<string, AttributeValue>[]): WriteRequest[] {
|
|
13
|
+
return items.map(item => {
|
|
14
|
+
const deleteRequest: WriteRequest = {
|
|
15
|
+
DeleteRequest: {
|
|
16
|
+
Key: {} // Must build the Key object manually
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
if (tableName === "events") {
|
|
21
|
+
deleteRequest.DeleteRequest!.Key!["stream_address"] = item["stream_address"];
|
|
22
|
+
deleteRequest.DeleteRequest!.Key!["offset"] = item["offset"];
|
|
23
|
+
} else if (tableName === "snapshots") {
|
|
24
|
+
deleteRequest.DeleteRequest!.Key!["view_address"] = item["view_address"];
|
|
25
|
+
deleteRequest.DeleteRequest!.Key!["offset"] = item["offset"];
|
|
26
|
+
} else if (tableName === "messages") {
|
|
27
|
+
// Assuming the schema typo was fixed to message_address
|
|
28
|
+
deleteRequest.DeleteRequest!.Key!["message_address"] = item["message_address"];
|
|
29
|
+
deleteRequest.DeleteRequest!.Key!["captured_at"] = item["captured_at"];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
return deleteRequest;
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Scans a table for all items and deletes them in batches of 25.
|
|
38
|
+
* @param tableName The name of the table to clear.
|
|
39
|
+
*/
|
|
40
|
+
private async clearTableItems(tableName: string): Promise<void> {
|
|
41
|
+
let items;
|
|
42
|
+
let exclusiveStartKey: Record<string, AttributeValue> | undefined = undefined;
|
|
43
|
+
const BATCH_SIZE = 25;
|
|
44
|
+
|
|
45
|
+
do {
|
|
46
|
+
// Define ProjectionExpression and ExpressionAttributeNames dynamically
|
|
47
|
+
let projectionExpression: string;
|
|
48
|
+
let expressionAttributeNames: Record<string, string> | undefined = undefined;
|
|
49
|
+
|
|
50
|
+
if (tableName === "events") {
|
|
51
|
+
projectionExpression = "stream_address, #o";
|
|
52
|
+
expressionAttributeNames = { "#o": "offset" };
|
|
53
|
+
} else if (tableName === "snapshots") {
|
|
54
|
+
projectionExpression = "view_address, #o";
|
|
55
|
+
expressionAttributeNames = { "#o": "offset" };
|
|
56
|
+
} else { // "messages" table
|
|
57
|
+
projectionExpression = "message_address, captured_at";
|
|
58
|
+
// No offset in the projection for messages table, so no #o alias is needed
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const scanCommand: ScanCommand = new ScanCommand({
|
|
62
|
+
TableName: tableName,
|
|
63
|
+
ProjectionExpression: projectionExpression,
|
|
64
|
+
ExpressionAttributeNames: expressionAttributeNames, // Pass the dynamic object
|
|
65
|
+
|
|
66
|
+
Limit: BATCH_SIZE,
|
|
67
|
+
ExclusiveStartKey: exclusiveStartKey,
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
// ... (rest of the function for scanning and batch writing remains the same) ...
|
|
71
|
+
const scanResult = await this.dynamoDbClient.send(scanCommand);
|
|
72
|
+
items = scanResult.Items;
|
|
73
|
+
|
|
74
|
+
if (items && items.length > 0) {
|
|
75
|
+
const deleteRequests = this.extractKeys(tableName, items);
|
|
76
|
+
|
|
77
|
+
const batchWriteCommand = new BatchWriteItemCommand({
|
|
78
|
+
RequestItems: {
|
|
79
|
+
[tableName]: deleteRequests
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
await this.dynamoDbClient.send(batchWriteCommand);
|
|
83
|
+
console.log(`Deleted ${items.length} items from ${tableName}.`);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
exclusiveStartKey = scanResult.LastEvaluatedKey;
|
|
87
|
+
|
|
88
|
+
} while (exclusiveStartKey);
|
|
89
|
+
|
|
90
|
+
console.log(`Finished item deletion for table: ${tableName}`);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
createEnvironmentAsync(): Promise<void> {
|
|
94
|
+
throw new Error("Method not implemented.");
|
|
95
|
+
}
|
|
96
|
+
destroyEnvironmentAsync(): Promise<void> {
|
|
97
|
+
throw new Error("Method not implemented.");
|
|
98
|
+
}
|
|
99
|
+
public async clearEnvironmentAsync(): Promise<void> {
|
|
100
|
+
await this.clearTableItems("events");
|
|
101
|
+
await this.clearTableItems("snapshots");
|
|
102
|
+
await this.clearTableItems("messages");
|
|
103
|
+
}
|
|
104
|
+
dispose?(): void {
|
|
105
|
+
throw new Error("Method not implemented.");
|
|
106
|
+
}
|
|
107
|
+
disposeAsync(): Promise<void> {
|
|
108
|
+
throw new Error("Method not implemented.");
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
public async close(): Promise<void> {
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
}
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
import { unmarshall } from "@aws-sdk/util-dynamodb";
|
|
2
|
+
|
|
3
|
+
import { IEvDbPayloadData } from '@eventualize/types/IEvDbEventPayload';
|
|
4
|
+
import IEvDbEventMetadata from '@eventualize/types/IEvDbEventMetadata';
|
|
5
|
+
import EvDbStreamCursor from '@eventualize/types/EvDbStreamCursor';
|
|
6
|
+
import EvDbMessage from '@eventualize/types/EvDbMessage';
|
|
7
|
+
import IEvDbStorageSnapshotAdapter from '@eventualize/types/IEvDbStorageSnapshotAdapter';
|
|
8
|
+
import IEvDbStorageStreamAdapter from '@eventualize/types/IEvDbStorageStreamAdapter';
|
|
9
|
+
import EvDbStreamAddress from '@eventualize/types/EvDbStreamAddress';
|
|
10
|
+
import EvDbViewAddress from '@eventualize/types/EvDbViewAddress';
|
|
11
|
+
import { EvDbStoredSnapshotResultRaw } from '@eventualize/types/EvDbStoredSnapshotResult';
|
|
12
|
+
import { EvDbStoredSnapshotData } from '@eventualize/types/EvDbStoredSnapshotData';
|
|
13
|
+
import EvDbEvent from '@eventualize/types/EvDbEvent';
|
|
14
|
+
import StreamStoreAffected from '@eventualize/types/StreamStoreAffected';
|
|
15
|
+
import EvDbContinuousFetchOptions from '@eventualize/types/EvDbContinuousFetchOptions';
|
|
16
|
+
import EvDbMessageFilter from '@eventualize/types/EvDbMessageFilter';
|
|
17
|
+
import { EvDbShardName } from '@eventualize/types/primitiveTypes';
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
import { createDynamoDBClient, listTables } from './DynamoDbClient.js';
|
|
21
|
+
import QueryProvider, { deserializeStreamAddress, EventRecord, MessageRecord } from './EvDbDynamoDbStorageAdapterQueries.js'
|
|
22
|
+
import { DynamoDBClient, TransactionCanceledException, TransactWriteItemsCommand } from '@aws-sdk/client-dynamodb';
|
|
23
|
+
|
|
24
|
+
// Type definitions for records
|
|
25
|
+
export interface EvDbEventRecord extends IEvDbEventMetadata {
|
|
26
|
+
id: string;
|
|
27
|
+
payload: IEvDbPayloadData;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface EvDbSnapshotRecord {
|
|
31
|
+
id: string;
|
|
32
|
+
streamType: string;
|
|
33
|
+
streamId: string;
|
|
34
|
+
viewName: string;
|
|
35
|
+
offset: bigint;
|
|
36
|
+
state: IEvDbPayloadData;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface IEvDbOutboxTransformer {
|
|
40
|
+
transform(message: EvDbMessage): EvDbMessage;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface EvDbStorageContext {
|
|
44
|
+
schema?: string;
|
|
45
|
+
shortId: string;
|
|
46
|
+
id: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const serializePayload = (payload: IEvDbPayloadData) => Buffer.from(JSON.stringify(payload), 'utf-8');
|
|
50
|
+
const deserializePayload = (payload: any): IEvDbPayloadData => {
|
|
51
|
+
if (!!payload && typeof payload == 'object') {
|
|
52
|
+
return payload;
|
|
53
|
+
}
|
|
54
|
+
return {};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Prisma-based storage adapter for EvDb
|
|
59
|
+
* Replaces SQL Server-specific adapter with database-agnostic Prisma implementation
|
|
60
|
+
*/
|
|
61
|
+
export default class EvDbDynamoDbStorageAdapter implements IEvDbStorageSnapshotAdapter, IEvDbStorageStreamAdapter {
|
|
62
|
+
constructor(private dynamoDbClient: DynamoDBClient = createDynamoDBClient()) {
|
|
63
|
+
}
|
|
64
|
+
getFromOutbox(filter: EvDbMessageFilter, options?: EvDbContinuousFetchOptions | null): Promise<AsyncIterable<EvDbMessage>> {
|
|
65
|
+
throw new Error('Method not implemented.');
|
|
66
|
+
}
|
|
67
|
+
getFromOutboxAsync(shard: EvDbShardName, filter: EvDbMessageFilter, options?: EvDbContinuousFetchOptions | null, cancellation?: AbortSignal): AsyncIterable<EvDbMessage> {
|
|
68
|
+
throw new Error('Method not implemented.');
|
|
69
|
+
}
|
|
70
|
+
getRecordsFromOutboxAsync(filter: EvDbMessageFilter, options?: EvDbContinuousFetchOptions | null, cancellation?: AbortSignal): AsyncIterable<EvDbMessage>;
|
|
71
|
+
getRecordsFromOutboxAsync(shard: EvDbShardName, filter: EvDbMessageFilter, options?: EvDbContinuousFetchOptions | null, cancellation?: AbortSignal): AsyncIterable<EvDbMessage>;
|
|
72
|
+
getRecordsFromOutboxAsync(shard: unknown, filter?: unknown, options?: unknown, cancellation?: unknown): AsyncIterable<EvDbMessage> {
|
|
73
|
+
throw new Error('Method not implemented.');
|
|
74
|
+
}
|
|
75
|
+
subscribeToMessageAsync(handler: (message: EvDbMessage) => Promise<void>, filter: EvDbMessageFilter, options?: EvDbContinuousFetchOptions | null): Promise<void>;
|
|
76
|
+
subscribeToMessageAsync(handler: (message: EvDbMessage) => Promise<void>, shard: EvDbShardName, filter: EvDbMessageFilter, options?: EvDbContinuousFetchOptions | null): Promise<void>;
|
|
77
|
+
subscribeToMessageAsync(handler: unknown, shard: unknown, filter?: unknown, options?: unknown): Promise<void> {
|
|
78
|
+
throw new Error('Method not implemented.');
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Store stream events in a transaction
|
|
83
|
+
*/
|
|
84
|
+
async storeStreamAsync(
|
|
85
|
+
events: ReadonlyArray<EvDbEvent>,
|
|
86
|
+
messages: ReadonlyArray<EvDbMessage>,
|
|
87
|
+
): Promise<StreamStoreAffected> {
|
|
88
|
+
try {
|
|
89
|
+
await listTables(this.dynamoDbClient);
|
|
90
|
+
const eventsToInsert: EventRecord[] = events.map((event) =>
|
|
91
|
+
EventRecord.createFromEvent(event));
|
|
92
|
+
|
|
93
|
+
const messagesToInsert: MessageRecord[] = messages.map(message => {
|
|
94
|
+
return {
|
|
95
|
+
id: crypto.randomUUID(),
|
|
96
|
+
stream_cursor: message.streamCursor,
|
|
97
|
+
channel: message.channel,
|
|
98
|
+
message_type: message.messageType,
|
|
99
|
+
event_type: message.eventType,
|
|
100
|
+
captured_by: message.capturedBy,
|
|
101
|
+
captured_at: message.capturedAt,
|
|
102
|
+
payload: message.payload,
|
|
103
|
+
}
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
const storeEventsQuery = QueryProvider.saveEvents(eventsToInsert);
|
|
107
|
+
const storeMessagesQuery = QueryProvider.saveMessages(messagesToInsert);
|
|
108
|
+
|
|
109
|
+
const transactItems = { TransactItems: [...storeEventsQuery, ...storeMessagesQuery] };
|
|
110
|
+
|
|
111
|
+
const command = new TransactWriteItemsCommand(transactItems)
|
|
112
|
+
await this.dynamoDbClient.send(command);
|
|
113
|
+
|
|
114
|
+
const numEvents = eventsToInsert.length;
|
|
115
|
+
const numMessages = messagesToInsert
|
|
116
|
+
.reduce((prev, { message_type: t }) =>
|
|
117
|
+
Object.assign(prev, { [t]: (prev[t] ?? 0) + 1 }), {} as Record<string, number>);
|
|
118
|
+
return new StreamStoreAffected(numEvents, new Map(Object.entries(numMessages)));
|
|
119
|
+
} catch (error) {
|
|
120
|
+
if (this.isOccException(error)) {
|
|
121
|
+
throw new Error('OPTIMISTIC_CONCURRENCY_VIOLATION');
|
|
122
|
+
}
|
|
123
|
+
throw error;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Store outbox messages in a transaction
|
|
129
|
+
*/
|
|
130
|
+
async storeOutboxMessagesAsync(
|
|
131
|
+
shardName: EvDbShardName,
|
|
132
|
+
records: EvDbMessage[],
|
|
133
|
+
): Promise<number> {
|
|
134
|
+
throw new Error('Method not implemented.');
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Get the last offset for a stream
|
|
139
|
+
*/
|
|
140
|
+
async getLastOffsetAsync(
|
|
141
|
+
streamAddress: EvDbStreamAddress
|
|
142
|
+
): Promise<number> {
|
|
143
|
+
const query = QueryProvider.getLastOffset(streamAddress);
|
|
144
|
+
const response = await this.dynamoDbClient.send(query);
|
|
145
|
+
if (!response.Items) {
|
|
146
|
+
return -1;
|
|
147
|
+
}
|
|
148
|
+
return parseInt(response.Items[0]?.offset.N ?? '-1', 10);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Get events for a stream since a specific offset
|
|
153
|
+
*/
|
|
154
|
+
async *getEventsAsync(
|
|
155
|
+
streamCursor: EvDbStreamCursor,
|
|
156
|
+
pageSize: number = 100
|
|
157
|
+
): AsyncGenerator<EvDbEvent, void, undefined> {
|
|
158
|
+
let queryCursor: Record<string, any> | undefined = undefined;
|
|
159
|
+
|
|
160
|
+
do {
|
|
161
|
+
const getEventsCommand = QueryProvider.getEvents(streamCursor);
|
|
162
|
+
const response = await this.dynamoDbClient.send(getEventsCommand);
|
|
163
|
+
|
|
164
|
+
if (response.Items && response.Items.length > 0) {
|
|
165
|
+
for (const item of response.Items) {
|
|
166
|
+
const res = unmarshall(item);
|
|
167
|
+
const streamAddress = deserializeStreamAddress(res.stream_address)
|
|
168
|
+
const r: EventRecord = new EventRecord(
|
|
169
|
+
crypto.randomUUID(),
|
|
170
|
+
new EvDbStreamCursor(streamAddress.streamType, streamAddress.streamId, res.offset),
|
|
171
|
+
res.event_type,
|
|
172
|
+
res.captured_by,
|
|
173
|
+
new Date(res.captured_at),
|
|
174
|
+
res.payload,
|
|
175
|
+
new Date(res.stored_at)
|
|
176
|
+
);
|
|
177
|
+
yield r.toEvDbEvent();
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
queryCursor = response.LastEvaluatedKey;
|
|
182
|
+
|
|
183
|
+
} while (queryCursor)
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Get snapshot for a stream view
|
|
188
|
+
*/
|
|
189
|
+
async getSnapshotAsync(
|
|
190
|
+
viewAddress: EvDbViewAddress
|
|
191
|
+
): Promise<EvDbStoredSnapshotResultRaw> {
|
|
192
|
+
const { streamType, streamId, viewName } = viewAddress;
|
|
193
|
+
try {
|
|
194
|
+
const query = QueryProvider.getSnapshot(viewAddress);
|
|
195
|
+
const response = await this.dynamoDbClient.send(query);
|
|
196
|
+
|
|
197
|
+
if (!response.Items) {
|
|
198
|
+
return EvDbStoredSnapshotResultRaw.Empty;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const snapshot = unmarshall(response.Items[0]);
|
|
202
|
+
|
|
203
|
+
return new EvDbStoredSnapshotResultRaw(
|
|
204
|
+
snapshot.offset,
|
|
205
|
+
new Date(Number(snapshot.stored_at)),
|
|
206
|
+
snapshot.state,
|
|
207
|
+
);
|
|
208
|
+
} catch (error) {
|
|
209
|
+
throw error;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Save a snapshot
|
|
215
|
+
*/
|
|
216
|
+
async storeSnapshotAsync(record: EvDbStoredSnapshotData): Promise<void> {
|
|
217
|
+
try {
|
|
218
|
+
const command = QueryProvider.saveSnapshot(record);
|
|
219
|
+
await this.dynamoDbClient.send(command);
|
|
220
|
+
|
|
221
|
+
} catch (error) {
|
|
222
|
+
throw error;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Check if an exception is an optimistic concurrency conflict
|
|
228
|
+
*/
|
|
229
|
+
private isOccException(error: unknown): boolean {
|
|
230
|
+
if (!(error instanceof TransactionCanceledException)) {
|
|
231
|
+
return false;
|
|
232
|
+
}
|
|
233
|
+
return !!(error as TransactionCanceledException)
|
|
234
|
+
.CancellationReasons?.some(({ Code }) => Code === 'ConditionalCheckFailed')
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Get table name for shard
|
|
239
|
+
*/
|
|
240
|
+
private getTableNameForShard(shardName: EvDbShardName): string {
|
|
241
|
+
throw new Error('Method not implemented.');
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Close the database connection
|
|
246
|
+
*/
|
|
247
|
+
async close(): Promise<void> {
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
}
|