import { Application } from 'egg' ; import { getClassName , IPC_EVENT_NAME , IpcEventType } from './Helper' ; import { EventHandlerMap } from './EventHandlerMap' ; import { AppPluginBase } from '../../basic/AppPluginBase' ; export class AppEventManager extends AppPluginBase < null > { private oneHandlerMap : EventHandlerMap ; private allHandlerMap : EventHandlerMap ; constructor ( config , app ) { super ( config , app ) ; this . oneHandlerMap = new EventHandlerMap ( ) ; this . allHandlerMap = new EventHandlerMap ( ) ; this . app . messenger . on ( IPC_EVENT_NAME , ( e ) => { this . consume ( e . className , e . type , e . payload ) ; } ) ; } public async onReady ( ) { } public async onStart ( ) { } public async onClose ( ) { } public subscribeOne < T > ( constructor , func ) { const className = getClassName ( constructor ) ; this . oneHandlerMap . add ( className , func ) ; } public unsubscribeOne < T > ( constructor , func ) { const className = getClassName ( constructor ) ; this . oneHandlerMap . remove ( className , func ) ; } public subscribeAll < T > ( constructor , func ) { const className = getClassName ( constructor ) ; this . allHandlerMap . add ( className , func ) ; } public publish < T > ( type , constructor , param ) { const p = { type , className : getClassName ( constructor ) , payload : param , from : 'worker' , } ; switch ( type ) { case 'worker' : this . app . messenger . sendToAgent ( IPC_EVENT_NAME , p ) ; break ; case 'workers' : this . app . messenger . sendToApp ( IPC_EVENT_NAME , p ) ; break ; case 'agent' : this . app . messenger . sendToAgent ( IPC_EVENT_NAME , p ) ; break ; case 'all' : this . app . messenger . broadcast ( IPC_EVENT_NAME , p ) ; this . app . messenger . sendToAgent ( IPC_EVENT_NAME , { ... p , type : 'worker' , } ) ; break ; default : break ; } } private async consume < T > ( className , type , param ) { const p = param as any ; if ( Number . isInteger ( p . installationId ) && p . fullName ) { const client = await this . app . installation . getClient ( p . installationId , p . fullName ) ; if ( client ) client . eventService . consume ( className , type , p ) ; } else { switch ( type ) { case 'worker' : try { await this . oneHandlerMap . exec ( className , param ) ; } catch ( e ) { this . logger . error ( `Error processing handlers, className=${ className }, e=` , e ) ; } break ; case 'workers' : case 'all' : try { await this . allHandlerMap . exec ( className , param ) ; } catch ( e ) { this . logger . error ( `Error processing handlers, className=${ className }, e=` , e ) ; } break ; case 'agent' : this . logger . error ( `Worker recieve agent event. className=${ className }` ) ; break ; default : break ; } } } } type EventHandler < T > = ( event : T ) => Promise < void > ;