|
| 1 | +import type { PeriodicJobDependencies } from '@lokalise/background-jobs-common' |
| 2 | +import { AbstractPeriodicJob, type JobExecutionContext } from '@lokalise/background-jobs-common' |
| 3 | +import type { |
| 4 | + CommonEventDefinition, |
| 5 | + CommonEventDefinitionPublisherSchemaType, |
| 6 | + ConsumerMessageMetadataType, |
| 7 | + DomainEventEmitter, |
| 8 | +} from '@message-queue-toolkit/core' |
| 9 | +import { PromisePool } from '@supercharge/promise-pool' |
| 10 | +import { uuidv7 } from 'uuidv7' |
| 11 | +import type { OutboxAccumulator } from './accumulators' |
| 12 | +import type { OutboxEntry } from './objects' |
| 13 | +import type { OutboxStorage } from './storage' |
| 14 | + |
| 15 | +export type OutboxDependencies<SupportedEvents extends CommonEventDefinition[]> = { |
| 16 | + outboxStorage: OutboxStorage<SupportedEvents> |
| 17 | + outboxAccumulator: OutboxAccumulator<SupportedEvents> |
| 18 | + eventEmitter: DomainEventEmitter<SupportedEvents> |
| 19 | +} |
| 20 | + |
| 21 | +export type OutboxProcessorConfiguration = { |
| 22 | + maxRetryCount: number |
| 23 | + emitBatchSize: number |
| 24 | +} |
| 25 | + |
| 26 | +export type OutboxConfiguration = { |
| 27 | + jobIntervalInMs: number |
| 28 | +} & OutboxProcessorConfiguration |
| 29 | + |
| 30 | +/** |
| 31 | + * Main logic for handling outbox entries. |
| 32 | + * |
| 33 | + * If entry is rejected, it is NOT going to be handled during the same execution. Next execution will pick it up. |
| 34 | + */ |
| 35 | +export class OutboxProcessor<SupportedEvents extends CommonEventDefinition[]> { |
| 36 | + constructor( |
| 37 | + private readonly outboxDependencies: OutboxDependencies<SupportedEvents>, |
| 38 | + private readonly outboxProcessorConfiguration: OutboxProcessorConfiguration, |
| 39 | + ) {} |
| 40 | + |
| 41 | + public async processOutboxEntries(context: JobExecutionContext) { |
| 42 | + const { outboxStorage, eventEmitter, outboxAccumulator } = this.outboxDependencies |
| 43 | + |
| 44 | + const entries = await outboxStorage.getEntries(this.outboxProcessorConfiguration.maxRetryCount) |
| 45 | + |
| 46 | + const filteredEntries = |
| 47 | + entries.length === 0 ? entries : await this.getFilteredEntries(entries, outboxAccumulator) |
| 48 | + |
| 49 | + await PromisePool.for(filteredEntries) |
| 50 | + .withConcurrency(this.outboxProcessorConfiguration.emitBatchSize) |
| 51 | + .process(async (entry) => { |
| 52 | + try { |
| 53 | + await eventEmitter.emit(entry.event, entry.data, entry.precedingMessageMetadata) |
| 54 | + await outboxAccumulator.add(entry) |
| 55 | + } catch (e) { |
| 56 | + context.logger.error({ error: e }, 'Failed to process outbox entry.') |
| 57 | + |
| 58 | + await outboxAccumulator.addFailure(entry) |
| 59 | + } |
| 60 | + }) |
| 61 | + |
| 62 | + await outboxStorage.flush(outboxAccumulator) |
| 63 | + await outboxAccumulator.clear() |
| 64 | + } |
| 65 | + |
| 66 | + private async getFilteredEntries( |
| 67 | + entries: OutboxEntry<SupportedEvents[number]>[], |
| 68 | + outboxAccumulator: OutboxAccumulator<SupportedEvents>, |
| 69 | + ) { |
| 70 | + const currentEntriesInAccumulator = new Set( |
| 71 | + (await outboxAccumulator.getEntries()).map((entry) => entry.id), |
| 72 | + ) |
| 73 | + return entries.filter((entry) => !currentEntriesInAccumulator.has(entry.id)) |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +/** |
| 78 | + * Periodic job that processes outbox entries every "intervalInMs". If processing takes longer than defined interval, another subsequent job WILL NOT be started. |
| 79 | + * |
| 80 | + * When event is published, and then entry is accumulated into SUCCESS group. If processing fails, entry is accumulated as FAILED and will be retried. |
| 81 | + * |
| 82 | + * Max retry count is defined by the user. |
| 83 | + */ |
| 84 | +/* c8 ignore start */ |
| 85 | +export class OutboxPeriodicJob< |
| 86 | + SupportedEvents extends CommonEventDefinition[], |
| 87 | +> extends AbstractPeriodicJob { |
| 88 | + private readonly outboxProcessor: OutboxProcessor<SupportedEvents> |
| 89 | + |
| 90 | + constructor( |
| 91 | + outboxDependencies: OutboxDependencies<SupportedEvents>, |
| 92 | + outboxConfiguration: OutboxConfiguration, |
| 93 | + dependencies: PeriodicJobDependencies, |
| 94 | + ) { |
| 95 | + super( |
| 96 | + { |
| 97 | + jobId: 'OutboxJob', |
| 98 | + schedule: { |
| 99 | + intervalInMs: outboxConfiguration.jobIntervalInMs, |
| 100 | + }, |
| 101 | + singleConsumerMode: { |
| 102 | + enabled: true, |
| 103 | + }, |
| 104 | + }, |
| 105 | + { |
| 106 | + redis: dependencies.redis, |
| 107 | + logger: dependencies.logger, |
| 108 | + transactionObservabilityManager: dependencies.transactionObservabilityManager, |
| 109 | + errorReporter: dependencies.errorReporter, |
| 110 | + scheduler: dependencies.scheduler, |
| 111 | + }, |
| 112 | + ) |
| 113 | + |
| 114 | + this.outboxProcessor = new OutboxProcessor<SupportedEvents>( |
| 115 | + outboxDependencies, |
| 116 | + outboxConfiguration, |
| 117 | + ) |
| 118 | + } |
| 119 | + |
| 120 | + protected async processInternal(context: JobExecutionContext): Promise<void> { |
| 121 | + await this.outboxProcessor.processOutboxEntries(context) |
| 122 | + } |
| 123 | +} |
| 124 | +/* c8 ignore stop */ |
| 125 | + |
| 126 | +export class OutboxEventEmitter<SupportedEvents extends CommonEventDefinition[]> { |
| 127 | + constructor(private storage: OutboxStorage<SupportedEvents>) {} |
| 128 | + |
| 129 | + /** |
| 130 | + * Persists outbox entry in persistence layer, later it will be picked up by outbox job. |
| 131 | + * @param supportedEvent |
| 132 | + * @param data |
| 133 | + * @param precedingMessageMetadata |
| 134 | + */ |
| 135 | + public async emit<SupportedEvent extends SupportedEvents[number]>( |
| 136 | + supportedEvent: SupportedEvent, |
| 137 | + data: Omit<CommonEventDefinitionPublisherSchemaType<SupportedEvent>, 'type'>, |
| 138 | + precedingMessageMetadata?: Partial<ConsumerMessageMetadataType>, |
| 139 | + ) { |
| 140 | + await this.storage.createEntry({ |
| 141 | + id: uuidv7(), |
| 142 | + event: supportedEvent, |
| 143 | + data, |
| 144 | + precedingMessageMetadata, |
| 145 | + status: 'CREATED', |
| 146 | + created: new Date(), |
| 147 | + retryCount: 0, |
| 148 | + }) |
| 149 | + } |
| 150 | +} |
0 commit comments