-
Notifications
You must be signed in to change notification settings - Fork 54
/
RunnableModule.ts
93 lines (80 loc) · 2.56 KB
/
RunnableModule.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { CustomError } from 'ts-custom-error';
import { Logger } from 'ts-log';
import { contextLogger } from './logging';
export class InvalidModuleState<ModuleState> extends CustomError {
public constructor(moduleName: string, methodName: string, requiredState: ModuleState) {
super();
this.message = `${methodName} cannot be called unless ${moduleName} is ${requiredState}`;
}
}
export type RunnableModuleState = null | 'initializing' | 'initialized' | 'starting' | 'running' | 'stopping';
export abstract class RunnableModule {
public state: RunnableModuleState;
protected abstract initializeImpl(): Promise<void>;
protected abstract startImpl(): Promise<void>;
protected abstract shutdownImpl(): Promise<void>;
logger: Logger;
name: string;
constructor(name: string, logger: Logger) {
this.state = null;
this.logger = contextLogger(logger, name);
this.name = name;
}
async initialize() {
this.initializeBefore();
await this.initializeImpl();
this.initializeAfter();
}
async start() {
this.startBefore();
await this.startImpl();
this.startAfter();
}
async shutdown() {
this.shutdownBefore();
await this.shutdownImpl();
this.shutdownAfter();
}
initializeBefore() {
if (this.state !== null) {
throw new InvalidModuleState<RunnableModuleState>(this.name, 'initializeBefore', null);
}
this.state = 'initializing';
this.logger.info('Initializing...');
}
initializeAfter() {
if (this.state !== 'initializing') {
throw new InvalidModuleState<RunnableModuleState>(this.name, 'initializeAfter', 'initializing');
}
this.state = 'initialized';
this.logger.info('Initialized');
}
startBefore() {
if (this.state !== 'initialized') {
throw new InvalidModuleState<RunnableModuleState>(this.name, 'start', 'initialized');
}
this.state = 'starting';
this.logger.info('Starting...');
}
startAfter() {
if (this.state !== 'starting') {
throw new InvalidModuleState<RunnableModuleState>(this.name, 'start', 'starting');
}
this.state = 'running';
this.logger.info('Started');
}
shutdownBefore() {
if (this.state !== 'running') {
throw new InvalidModuleState<RunnableModuleState>(this.name, 'shutdown', 'running');
}
this.state = 'stopping';
this.logger.info('Stopping...');
}
shutdownAfter() {
if (this.state !== 'stopping') {
throw new InvalidModuleState<RunnableModuleState>(this.name, 'shutdown', 'stopping');
}
this.state = 'initialized';
this.logger.info('Shutdown complete');
}
}