|
| 1 | +import { Message } from '@node-ts/bus-messages' |
| 2 | +import { DefaultHandlerRegistry, Handler } from '../handler' |
| 3 | +import { HandlerDefinition, isClassHandler } from '../handler/handler' |
| 4 | +import { JsonSerializer, Serializer } from '../serialization' |
| 5 | +import { MemoryQueue, Transport, TransportMessage } from '../transport' |
| 6 | +import { ClassConstructor, CoreDependencies, Middleware, MiddlewareDispatcher } from '../util' |
| 7 | +import { BusInstance } from './bus-instance' |
| 8 | +import { Persistence, Workflow, WorkflowState } from '../workflow' |
| 9 | +import { WorkflowRegistry } from '../workflow/registry/workflow-registry' |
| 10 | +import { BusAlreadyInitialized } from './error' |
| 11 | +import { ContainerAdapter } from '../container' |
| 12 | +import { defaultLoggerFactory, LoggerFactory } from '../logger' |
| 13 | +import { ContainerNotRegistered } from '../error' |
| 14 | +import { MessageSerializer } from '../serialization/message-serializer' |
| 15 | +import { InMemoryPersistence } from '../workflow/persistence' |
| 16 | + |
| 17 | +export interface BusInitializeOptions { |
| 18 | + /** |
| 19 | + * If true, will initialize the bus in send only mode. |
| 20 | + * This will provide a bus instance that is capable of sending/publishing |
| 21 | + * messages only and won't handle incoming messages or workflows |
| 22 | + * @default false |
| 23 | + */ |
| 24 | + sendOnly: boolean |
| 25 | +} |
| 26 | + |
| 27 | +const defaultBusInitializeOptions: BusInitializeOptions = { |
| 28 | + sendOnly: false |
| 29 | +} |
| 30 | + |
| 31 | +export class BusConfiguration { |
| 32 | + |
| 33 | + private configuredTransport: Transport | undefined |
| 34 | + private concurrency = 1 |
| 35 | + private busInstance: BusInstance | undefined |
| 36 | + private container: ContainerAdapter | undefined |
| 37 | + private workflowRegistry = new WorkflowRegistry() |
| 38 | + private handlerRegistry = new DefaultHandlerRegistry() |
| 39 | + private loggerFactory: LoggerFactory = defaultLoggerFactory |
| 40 | + private serializer = new JsonSerializer() |
| 41 | + private persistence: Persistence = new InMemoryPersistence() |
| 42 | + private messageReadMiddlewares = new MiddlewareDispatcher<TransportMessage<unknown>>() |
| 43 | + |
| 44 | + /** |
| 45 | + * Initializes the bus with the provided configuration |
| 46 | + * @param options Changes the default startup mode of the bus |
| 47 | + */ |
| 48 | + async initialize (options = defaultBusInitializeOptions): Promise<BusInstance> { |
| 49 | + const { sendOnly } = options |
| 50 | + const logger = this.loggerFactory('@node-ts/bus-core:bus') |
| 51 | + logger.debug('Initializing bus', { sendOnly }) |
| 52 | + |
| 53 | + if (!!this.busInstance) { |
| 54 | + throw new BusAlreadyInitialized() |
| 55 | + } |
| 56 | + |
| 57 | + const coreDependencies: CoreDependencies = { |
| 58 | + container: this.container, |
| 59 | + handlerRegistry: this.handlerRegistry, |
| 60 | + loggerFactory: this.loggerFactory, |
| 61 | + serializer: this.serializer, |
| 62 | + messageSerializer: new MessageSerializer(this.serializer, this.handlerRegistry) |
| 63 | + } |
| 64 | + |
| 65 | + if (!sendOnly) { |
| 66 | + this.persistence?.prepare(coreDependencies) |
| 67 | + this.workflowRegistry.prepare(coreDependencies, this.persistence) |
| 68 | + await this.workflowRegistry.initialize(this.handlerRegistry, this.container) |
| 69 | + |
| 70 | + const classHandlers = this.handlerRegistry.getClassHandlers() |
| 71 | + if (!this.container && classHandlers.length) { |
| 72 | + throw new ContainerNotRegistered(classHandlers[0].constructor.name) |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + const transport: Transport = this.configuredTransport || new MemoryQueue() |
| 77 | + transport.prepare(coreDependencies) |
| 78 | + if (transport.connect) { |
| 79 | + await transport.connect() |
| 80 | + } |
| 81 | + if (!sendOnly && transport.initialize) { |
| 82 | + await transport.initialize(this.handlerRegistry) |
| 83 | + } |
| 84 | + this.busInstance = new BusInstance( |
| 85 | + transport, |
| 86 | + this.concurrency, |
| 87 | + this.workflowRegistry, |
| 88 | + coreDependencies, |
| 89 | + this.messageReadMiddlewares |
| 90 | + ) |
| 91 | + |
| 92 | + logger.debug('Bus initialized', { sendOnly, registeredMessages: this.handlerRegistry.getMessageNames() }) |
| 93 | + |
| 94 | + return this.busInstance |
| 95 | + } |
| 96 | + |
| 97 | + |
| 98 | + /** |
| 99 | + * Register a handler for a specific message type. When Bus is initialized it will configure |
| 100 | + * the transport to subscribe to this type of message and upon receipt will forward the message |
| 101 | + * through to the provided message handler |
| 102 | + * @param messageType Which message will be subscribed to and routed to the handler |
| 103 | + * @param messageHandler A callback that will be invoked when the message is received |
| 104 | + * @param customResolver Subscribe to a topic that's created and maintained outside of the application |
| 105 | + */ |
| 106 | + withHandler (classHandler: ClassConstructor<Handler<Message>>): this |
| 107 | + withHandler <MessageType extends (Message | object)>( |
| 108 | + functionHandler: { |
| 109 | + messageType: ClassConstructor<MessageType>, |
| 110 | + messageHandler: HandlerDefinition<MessageType> |
| 111 | + } |
| 112 | + ): this |
| 113 | + withHandler <MessageType extends (Message | object)>( |
| 114 | + handler: ClassConstructor<Handler<Message>> | { |
| 115 | + messageType: ClassConstructor<MessageType>, |
| 116 | + messageHandler: HandlerDefinition<MessageType> |
| 117 | + }): this |
| 118 | + { |
| 119 | + if (!!this.busInstance) { |
| 120 | + throw new BusAlreadyInitialized() |
| 121 | + } |
| 122 | + |
| 123 | + if ('messageHandler' in handler) { |
| 124 | + this.handlerRegistry.register( |
| 125 | + handler.messageType, |
| 126 | + handler.messageHandler |
| 127 | + ) |
| 128 | + } else if (isClassHandler(handler)) { |
| 129 | + const handlerInstance = new handler() |
| 130 | + this.handlerRegistry.register( |
| 131 | + handlerInstance.messageType, |
| 132 | + handler |
| 133 | + ) |
| 134 | + } |
| 135 | + |
| 136 | + |
| 137 | + return this |
| 138 | + } |
| 139 | + |
| 140 | + /** |
| 141 | + * Registers a custom handler that receives messages from external systems, or messages that don't implement the |
| 142 | + * Message interface from @node-ts/bus-messages |
| 143 | + * @param messageHandler A handler that receives the custom message |
| 144 | + * @param customResolver A discriminator that determines if an incoming message should be mapped to this handler. |
| 145 | + */ |
| 146 | + withCustomHandler<MessageType extends (Message | object)> ( |
| 147 | + messageHandler: HandlerDefinition<MessageType>, |
| 148 | + customResolver: { |
| 149 | + resolveWith: ((message: MessageType) => boolean), |
| 150 | + topicIdentifier?: string |
| 151 | + } |
| 152 | + ): this |
| 153 | + { |
| 154 | + if (!!this.busInstance) { |
| 155 | + throw new BusAlreadyInitialized() |
| 156 | + } |
| 157 | + |
| 158 | + this.handlerRegistry.registerCustom( |
| 159 | + messageHandler, |
| 160 | + customResolver |
| 161 | + ) |
| 162 | + return this |
| 163 | + } |
| 164 | + |
| 165 | + /** |
| 166 | + * Register a workflow definition so that all of the messages it depends on will be subscribed to |
| 167 | + * and forwarded to the handlers inside the workflow |
| 168 | + */ |
| 169 | + withWorkflow<TWorkflowState extends WorkflowState> (workflow: ClassConstructor<Workflow<TWorkflowState>>): this { |
| 170 | + if (!!this.busInstance) { |
| 171 | + throw new BusAlreadyInitialized() |
| 172 | + } |
| 173 | + |
| 174 | + this.workflowRegistry.register( |
| 175 | + workflow |
| 176 | + ) |
| 177 | + return this |
| 178 | + } |
| 179 | + |
| 180 | + /** |
| 181 | + * Configures Bus to use a different transport than the default MemoryQueue |
| 182 | + */ |
| 183 | + withTransport (transportConfiguration: Transport): this { |
| 184 | + if (!!this.busInstance) { |
| 185 | + throw new BusAlreadyInitialized() |
| 186 | + } |
| 187 | + |
| 188 | + this.configuredTransport = transportConfiguration |
| 189 | + return this |
| 190 | + } |
| 191 | + |
| 192 | + /** |
| 193 | + * Configures Bus to use a different logging provider than the default console logger |
| 194 | + */ |
| 195 | + withLogger (loggerFactory: LoggerFactory): this { |
| 196 | + if (!!this.busInstance) { |
| 197 | + throw new BusAlreadyInitialized() |
| 198 | + } |
| 199 | + |
| 200 | + this.loggerFactory = loggerFactory |
| 201 | + return this |
| 202 | + } |
| 203 | + |
| 204 | + /** |
| 205 | + * Configures Bus to use a different serialization provider. The provider is responsible for |
| 206 | + * transforming messages to/from a serialized representation, as well as ensuring all object |
| 207 | + * properties are a strong type |
| 208 | + */ |
| 209 | + withSerializer (serializer: Serializer): this { |
| 210 | + if (!!this.busInstance) { |
| 211 | + throw new BusAlreadyInitialized() |
| 212 | + } |
| 213 | + |
| 214 | + this.serializer = serializer |
| 215 | + return this |
| 216 | + } |
| 217 | + |
| 218 | + /** |
| 219 | + * Configures Bus to use a different persistence provider than the default InMemoryPersistence provider. |
| 220 | + * This is used to persist workflow data and is unused if not using workflows. |
| 221 | + */ |
| 222 | + withPersistence (persistence: Persistence): this { |
| 223 | + if (!!this.busInstance) { |
| 224 | + throw new BusAlreadyInitialized() |
| 225 | + } |
| 226 | + |
| 227 | + this.persistence = persistence |
| 228 | + return this |
| 229 | + } |
| 230 | + |
| 231 | + /** |
| 232 | + * Sets the message handling concurrency beyond the default value of 1, which will increase the number of messages |
| 233 | + * handled in parallel. |
| 234 | + */ |
| 235 | + withConcurrency (concurrency: number): this { |
| 236 | + if (concurrency < 1) { |
| 237 | + throw new Error('Invalid concurrency setting. Must be set to 1 or greater') |
| 238 | + } |
| 239 | + |
| 240 | + this.concurrency = concurrency |
| 241 | + return this |
| 242 | + } |
| 243 | + |
| 244 | + /** |
| 245 | + * Use a local dependency injection/IoC container to resolve handlers |
| 246 | + * and workflows. |
| 247 | + * @param container An adapter to an existing DI container to fetch class instances from |
| 248 | + */ |
| 249 | + withContainer (container: { get <T>(type: ClassConstructor<T>): T }): this { |
| 250 | + this.container = container |
| 251 | + return this |
| 252 | + } |
| 253 | + |
| 254 | + /** |
| 255 | + * Register optional middlewares that will run for each message that is polled from the transport |
| 256 | + * Note these middlewares only run when polling successfully pulls a message off the Transports queue |
| 257 | + * After all the user defined middlewares have registered. |
| 258 | + */ |
| 259 | + withMessageReadMiddleware<TransportMessageType = unknown> ( |
| 260 | + messageReadMiddleware: Middleware<TransportMessage<TransportMessageType>> |
| 261 | + ): this { |
| 262 | + this.messageReadMiddlewares.use(messageReadMiddleware) |
| 263 | + return this |
| 264 | + } |
| 265 | +} |
0 commit comments