-
-
Notifications
You must be signed in to change notification settings - Fork 37
feat: MongoDB Consumer based on MongoDB ChangeStream subscription #258
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
arturwojnar
wants to merge
18
commits into
event-driven-io:main
Choose a base branch
from
arturwojnar:feat/subscriptions
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
8c6af5c
feat: mongodb processor and subscription
arturwojnar bb80bf3
feat: receiving updates on messages
arturwojnar bb1ebfe
refactor: removed the esdb copy-paste leftovers
arturwojnar ae79330
fix: revert the processors type back to generic MessageProcessor
arturwojnar 753103c
fix: removed onHandleStart
arturwojnar 592a866
refactor: to mongoDbEventsConsumer renamed to mongoDBMessagesConsumer
arturwojnar 30fa044
feat: databaseName as parameter for the readProcessorCheckpoint
arturwojnar 2de9d86
test: storeProcessorCheckpoint and readProcessorCheckpoint tests
arturwojnar fc53348
refactor: storeProcessorCheckpoint
arturwojnar 847580d
chore: eslint fix
arturwojnar fa8cb43
feat: handling an unknown Position
arturwojnar 4c03a71
feat: starting from the earliest position
arturwojnar e4d5904
fix: eslint all fixed
arturwojnar ead380c
feat: processing messages one by one
arturwojnar 13afb1e
fix: removed incorrect change
arturwojnar 811bc97
Merge remote-tracking branch 'upstream/main' into feat/subscriptions
arturwojnar 6f78760
test: fix
arturwojnar 57fcd84
test: tests, eslint, ts fixed
arturwojnar File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
63 changes: 63 additions & 0 deletions
63
src/packages/emmett-mongodb/src/eventStore/consumers/CancellablePromise.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
import assert from 'assert'; | ||
|
||
export class CancellationPromise<T = unknown> extends Promise<T> { | ||
private _resolve: (value: T | PromiseLike<T>) => void; | ||
private _reject: (reason?: unknown) => void; | ||
private _state: 'resolved' | 'rejected' | 'pending' = 'pending'; | ||
|
||
constructor( | ||
executor: ( | ||
resolve: (value: T | PromiseLike<T>) => void, | ||
reject: (reason?: unknown) => void, | ||
) => void = () => null, | ||
) { | ||
let _resolve: ((value: T | PromiseLike<T>) => void) | undefined = undefined; | ||
let _reject: ((reason?: unknown) => void) | undefined = undefined; | ||
|
||
super((resolve, reject) => { | ||
executor(resolve, reject); | ||
_resolve = resolve; | ||
_reject = reject; | ||
}); | ||
|
||
assert(_resolve); | ||
assert(_reject); | ||
|
||
this._resolve = _resolve; | ||
this._reject = _reject; | ||
} | ||
|
||
reject(reason?: unknown): void { | ||
this._state = 'rejected'; | ||
this._reject(reason); | ||
} | ||
|
||
resolve(value?: T): void { | ||
this._state = 'resolved'; | ||
this._resolve(value as T); | ||
} | ||
|
||
get isResolved() { | ||
return this._state === 'resolved'; | ||
} | ||
|
||
get isRejected() { | ||
return this._state === 'rejected'; | ||
} | ||
|
||
get isPending() { | ||
return this._state === 'pending'; | ||
} | ||
|
||
static resolved<R = unknown>(value?: R) { | ||
const promise = new CancellationPromise<R>(); | ||
promise.resolve(value as R); | ||
return promise; | ||
} | ||
|
||
static rejected<R extends Error = Error>(value: R) { | ||
const promise = new CancellationPromise<R>(); | ||
promise.reject(value); | ||
return promise; | ||
} | ||
} |
282 changes: 282 additions & 0 deletions
282
src/packages/emmett-mongodb/src/eventStore/consumers/mongoDBEventsConsumer.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,282 @@ | ||
import { | ||
EmmettError, | ||
MessageProcessor, | ||
type AnyEvent, | ||
type AnyMessage, | ||
type AsyncRetryOptions, | ||
type DefaultRecord, | ||
type GlobalPositionTypeOfRecordedMessageMetadata, | ||
type Message, | ||
type MessageConsumer, | ||
type RecordedMessage, | ||
} from '@event-driven-io/emmett'; | ||
import { MongoClient, type MongoClientOptions } from 'mongodb'; | ||
import { v4 as uuid } from 'uuid'; | ||
import type { MongoDBRecordedMessageMetadata } from '../event'; | ||
import type { MongoDBReadEventMetadata } from '../mongoDBEventStore'; | ||
import { CancellationPromise } from './CancellablePromise'; | ||
import { | ||
changeStreamReactor, | ||
mongoDBProjector, | ||
type MongoDBProcessor, | ||
type MongoDBProcessorOptions, | ||
type MongoDBProjectorOptions, | ||
} from './mongoDBProcessor'; | ||
import { | ||
generateVersionPolicies, | ||
mongoDBSubscription, | ||
zipMongoDBMessageBatchPullerStartFrom, | ||
type ChangeStreamFullDocumentValuePolicy, | ||
type MongoDBSubscription, | ||
} from './subscriptions'; | ||
import type { MongoDBResumeToken } from './subscriptions/types'; | ||
|
||
export type MessageConsumerOptions< | ||
MessageType extends Message = AnyMessage, | ||
MessageMetadataType extends | ||
MongoDBReadEventMetadata = MongoDBRecordedMessageMetadata, | ||
HandlerContext extends DefaultRecord | undefined = undefined, | ||
CheckpointType = GlobalPositionTypeOfRecordedMessageMetadata<MessageMetadataType>, | ||
> = { | ||
consumerId?: string; | ||
|
||
processors?: MessageProcessor< | ||
MessageType, | ||
MessageMetadataType, | ||
HandlerContext, | ||
CheckpointType | ||
>[]; | ||
}; | ||
|
||
export type MongoDBEventStoreConsumerConfig< | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
ConsumerMessageType extends Message = any, | ||
MessageMetadataType extends | ||
MongoDBReadEventMetadata = MongoDBRecordedMessageMetadata, | ||
HandlerContext extends DefaultRecord | undefined = undefined, | ||
CheckpointType = GlobalPositionTypeOfRecordedMessageMetadata<MessageMetadataType>, | ||
> = MessageConsumerOptions< | ||
ConsumerMessageType, | ||
MessageMetadataType, | ||
HandlerContext, | ||
CheckpointType | ||
> & { | ||
// from?: any; | ||
// pulling?: { | ||
// batchSize?: number; | ||
// }; | ||
resilience?: { | ||
resubscribeOptions?: AsyncRetryOptions; | ||
}; | ||
changeStreamFullDocumentPolicy: ChangeStreamFullDocumentValuePolicy; | ||
}; | ||
|
||
export type MongoDBConsumerOptions< | ||
ConsumerEventType extends Message = Message, | ||
MessageMetadataType extends | ||
MongoDBReadEventMetadata = MongoDBRecordedMessageMetadata, | ||
HandlerContext extends DefaultRecord | undefined = undefined, | ||
CheckpointType = GlobalPositionTypeOfRecordedMessageMetadata<MessageMetadataType>, | ||
> = MongoDBEventStoreConsumerConfig< | ||
ConsumerEventType, | ||
MessageMetadataType, | ||
HandlerContext, | ||
CheckpointType | ||
> & | ||
( | ||
| { | ||
connectionString: string; | ||
clientOptions?: MongoClientOptions; | ||
client?: never; | ||
} | ||
| { | ||
client: MongoClient; | ||
connectionString?: never; | ||
clientOptions?: never; | ||
} | ||
); | ||
|
||
export type MongoDBEventStoreConsumer< | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
ConsumerMessageType extends AnyMessage = any, | ||
> = MessageConsumer<ConsumerMessageType> & | ||
Readonly<{ | ||
reactor: <MessageType extends AnyMessage = ConsumerMessageType>( | ||
options: MongoDBProcessorOptions<MessageType>, | ||
) => MongoDBProcessor<MessageType>; | ||
}> & | ||
(AnyEvent extends ConsumerMessageType | ||
? Readonly<{ | ||
projector: < | ||
EventType extends AnyEvent = ConsumerMessageType & AnyEvent, | ||
>( | ||
options: MongoDBProjectorOptions<EventType>, | ||
) => MongoDBProcessor<EventType>; | ||
}> | ||
: object); | ||
|
||
export type MongoDBConsumerHandlerContext = { | ||
client?: MongoClient; | ||
}; | ||
|
||
export const mongoDBMessagesConsumer = < | ||
ConsumerMessageType extends Message = AnyMessage, | ||
MessageMetadataType extends | ||
MongoDBReadEventMetadata = MongoDBRecordedMessageMetadata, | ||
HandlerContext extends | ||
MongoDBConsumerHandlerContext = MongoDBConsumerHandlerContext, | ||
CheckpointType = MongoDBResumeToken, | ||
>( | ||
options: MongoDBConsumerOptions< | ||
ConsumerMessageType, | ||
MessageMetadataType, | ||
HandlerContext, | ||
CheckpointType | ||
>, | ||
): MongoDBEventStoreConsumer<ConsumerMessageType> => { | ||
let start: Promise<void>; | ||
let stream: MongoDBSubscription<CheckpointType>; | ||
let isRunning = false; | ||
let runningPromise = new CancellationPromise<null>(); | ||
const client = | ||
'client' in options && options.client | ||
? options.client | ||
: new MongoClient(options.connectionString, options.clientOptions); | ||
const processors = options.processors ?? []; | ||
|
||
return { | ||
consumerId: options.consumerId ?? uuid(), | ||
get isRunning() { | ||
return isRunning; | ||
}, | ||
processors, | ||
reactor: <MessageType extends AnyMessage = ConsumerMessageType>( | ||
options: MongoDBProcessorOptions<MessageType>, | ||
): MongoDBProcessor<MessageType> => { | ||
const processor = changeStreamReactor(options); | ||
|
||
processors.push( | ||
processor as unknown as MessageProcessor< | ||
ConsumerMessageType, | ||
MessageMetadataType, | ||
HandlerContext, | ||
CheckpointType | ||
>, | ||
); | ||
|
||
return processor; | ||
}, | ||
projector: <EventType extends AnyEvent = ConsumerMessageType & AnyEvent>( | ||
options: MongoDBProjectorOptions<EventType>, | ||
): MongoDBProcessor<EventType> => { | ||
const processor = mongoDBProjector(options); | ||
|
||
processors.push( | ||
processor as unknown as MessageProcessor< | ||
ConsumerMessageType, | ||
MessageMetadataType, | ||
HandlerContext, | ||
CheckpointType | ||
>, | ||
); | ||
|
||
return processor; | ||
}, | ||
start: () => { | ||
start = (async () => { | ||
if (processors.length === 0) | ||
return Promise.reject( | ||
new EmmettError( | ||
'Cannot start consumer without at least a single processor', | ||
), | ||
); | ||
|
||
isRunning = true; | ||
|
||
runningPromise = new CancellationPromise<null>(); | ||
|
||
const positions = await Promise.all( | ||
processors.map((o) => o.start({ client } as Partial<HandlerContext>)), | ||
); | ||
const startFrom = | ||
zipMongoDBMessageBatchPullerStartFrom<CheckpointType>(positions); | ||
|
||
stream = mongoDBSubscription< | ||
ConsumerMessageType, | ||
MessageMetadataType, | ||
CheckpointType | ||
>({ | ||
client, | ||
from: startFrom, | ||
eachBatch: async ( | ||
messages: RecordedMessage< | ||
ConsumerMessageType, | ||
MessageMetadataType | ||
>[], | ||
) => { | ||
for (const processor of processors.filter( | ||
({ isActive }) => isActive, | ||
)) { | ||
await processor.handle(messages, { | ||
client, | ||
} as Partial<HandlerContext>); | ||
} | ||
}, | ||
}); | ||
|
||
const db = options.client?.db?.(); | ||
|
||
if (!db) { | ||
throw new EmmettError('MongoDB client is not connected'); | ||
} | ||
|
||
// TODO: Remember to fix. | ||
const versionPolicies = await generateVersionPolicies(db); | ||
const policy = versionPolicies.changeStreamFullDocumentValuePolicy; | ||
|
||
await stream.start({ | ||
getFullDocumentValue: policy, | ||
startFrom, | ||
}); | ||
})(); | ||
|
||
return start; | ||
}, | ||
stop: async () => { | ||
if (stream.isRunning) { | ||
await stream.stop(); | ||
isRunning = false; | ||
runningPromise.resolve(null); | ||
} | ||
}, | ||
close: async () => { | ||
if (stream.isRunning) { | ||
await stream.stop(); | ||
isRunning = false; | ||
runningPromise.resolve(null); | ||
} | ||
}, | ||
}; | ||
}; | ||
|
||
export const mongoDBChangeStreamMessagesConsumer = < | ||
ConsumerMessageType extends Message = AnyMessage, | ||
MessageMetadataType extends | ||
MongoDBReadEventMetadata = MongoDBRecordedMessageMetadata, | ||
HandlerContext extends | ||
MongoDBConsumerHandlerContext = MongoDBConsumerHandlerContext, | ||
CheckpointType = GlobalPositionTypeOfRecordedMessageMetadata<MessageMetadataType>, | ||
>( | ||
options: MongoDBConsumerOptions< | ||
ConsumerMessageType, | ||
MessageMetadataType, | ||
HandlerContext, | ||
CheckpointType | ||
>, | ||
): MongoDBEventStoreConsumer<ConsumerMessageType> => | ||
mongoDBMessagesConsumer< | ||
ConsumerMessageType, | ||
MessageMetadataType, | ||
HandlerContext, | ||
CheckpointType | ||
>(options); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
it's not the case for the esdb..
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@oskardudycz