import {AwareOfContainerLifecycle, Inject, Injectable, StaticInstantiable} from '../../di' import {BusSubscriber, Event, EventBus, EventHandler, EventHandlerReturn, EventHandlerSubscription} from './types' import {Awaitable, Collection, ifDebugging, Pipeline, uuid4} from '../../util' import {Logging} from '../../service/Logging' import {Bus, BusInternalSubscription} from './Bus' import {getEventName} from './getEventName' import {CanonicalItemClass} from '../CanonicalReceiver' /** * Non-connectable event bus implementation. Can forward events to the main Bus instance. */ @Injectable() export class LocalBus extends CanonicalItemClass implements EventBus, AwareOfContainerLifecycle { awareOfContainerLifecycle = true as const @Inject() protected readonly logging!: Logging @Inject() protected readonly bus!: Bus public readonly uuid = uuid4() /** Local listeners subscribed to events on this bus. */ protected subscribers: Collection> = new Collection() protected subscriptions: Collection = new Collection() /** True if the bus has been initialized. */ private isUp = false /** * Push an event onto the bus. * @param event */ async push(event: TEvent): Promise { if ( event.originBusUuid === this.uuid ) { return } if ( !event.originBusUuid ) { event.originBusUuid = this.uuid } if ( await this.callSubscribers(event) ) { // One of the subscribers halted propagation of the event return } if ( await this.shouldBroadcast(event) ) { await this.bus.push(event) } } /** Returns true if the given event should be pushed to connected event busses. */ protected async shouldBroadcast(event: TEvent): Promise { if ( typeof event.shouldBroadcast === 'function' ) { return event.shouldBroadcast() } return Boolean(event.shouldBroadcast) } /** * Call all local listeners for the given event. Returns true if the propagation * of the event should be halted. * @param event * @protected */ protected async callSubscribers(event: TEvent): Promise { return this.subscribers .filter(sub => event instanceof sub.eventKey) .pluck('handler') .toAsync() .some(handler => handler(event)) } /** Register a pipeline as an event handler. */ pipe(eventKey: StaticInstantiable, line: Pipeline): Awaitable { return this.subscribe(eventKey, event => line.apply(event)) } /** * Subscribe to an event on the bus. * @param eventKey * @param handler */ async subscribe(eventKey: StaticInstantiable, handler: EventHandler): Promise { const uuid = uuid4() this.subscribers.push({ eventName: getEventName(eventKey), handler, eventKey, uuid, } as unknown as BusSubscriber) return { unsubscribe: async () => { this.subscribers = this.subscribers.where('uuid', '!=', uuid) await this.subscriptions .where('subscriberUuid', '=', uuid) .tap(trashed => this.subscriptions.diffInPlace(trashed)) .pluck('subscription') .awaitMapCall('unsubscribe') }, } } async up(): Promise { if ( this.isUp ) { this.logging.warn('Attempted to boot more than once. Skipping.') ifDebugging('extollo.bus', () => { throw new Error('Attempted to boot more than once. Skipping.') }) return } this.isUp = true } isConnected(): boolean { return this.isUp } /** Clean up this event bus. */ async down(): Promise { if ( !this.isUp ) { this.logging.warn('Attempted to shut down but was never properly booted. Skipping.') return } await this.subscriptions .pluck('subscription') .awaitMapCall('unsubscribe') this.isUp = false } onContainerRelease(): Awaitable { if ( this.isUp ) { this.down() } } }