-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserviceBase.ts
166 lines (134 loc) · 4.11 KB
/
serviceBase.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
import { CodeGenerator } from '@paradoxical-io/common';
import chalk from 'chalk';
import { currentEnvironment, isLocal } from '../env';
import { log, Logger } from '../logger';
import { globalKeys, Metrics, monitorNodeMetrics, shutdownMetrics } from '../metrics';
import { prompt, signals } from '../process';
export function validateUTCSet() {
if (new Date().getTimezoneOffset() !== 0) {
throw new Error(
`Must run the application in UTC timezone. For local applications please add a .env and set "TZ='UTC'"`
);
}
}
/**
* Wrapper around console log to avoid lint since we _do_ want to log cli here
* @param s
*/
function cli(s: unknown) {
// eslint-disable-next-line no-console
console.log(s);
}
/**
* AppBase provides default hooks for all services
*/
export abstract class ServiceBase {
abstract name: string;
constructor() {
process.on('uncaughtException', (error: Error) => {
log.error('uncaught exception. exiting', error);
Metrics.instance.increment(globalKeys.crash);
shutdownMetrics()
.catch(() => {})
.finally(() => {
process.exit(1);
})
.catch(() => {});
});
process.on('unhandledRejection', reason => {
if (reason instanceof Error) {
log.error('unhandled rejection', reason);
} else {
cli(reason);
}
log.error('exiting!');
Metrics.instance.increment(globalKeys.crash);
shutdownMetrics()
.catch(e => {
// eslint-disable-next-line no-console
console.log('Error shutting down metrics', e);
})
.finally(() => {
process.exit(1);
})
.catch(() => {});
});
process.on('warning', warning => {
log.error('node warning', warning);
});
signals.onShutdown(() => shutdownMetrics());
// if for some reason someone didn't run the service using the safe wrappers below, validate again
validateUTCSet();
// monitor the event loop every 100ms
monitorNodeMetrics({ frequencyMS: 1000 });
if (isLocal && currentEnvironment() !== 'local') {
cli(chalk.red('!!!!!!!WARNING WARNING WARNING!!!!!!\n'));
cli(
chalk.red(`Running against remote resources in environment '${currentEnvironment()}' on a local machine!!\n`)
);
cli(chalk.red("To use your local environment set PARADOX_ENV to 'local'"));
cli(chalk.red('\nPlease be very careful!\n'));
cli(chalk.red('!!!!!!!WARNING WARNING WARNING!!!!!!\n'));
} else {
log.with({ env: currentEnvironment() }).info('Booting up!');
}
if (!isLocal) {
Logger.highjackConsole();
}
}
async run(): Promise<void> {
if (isLocal && currentEnvironment() === 'prod') {
cli(chalk.yellow('Please verify the following code to run in prod. '));
while (true) {
const code = new CodeGenerator().alpha(6);
const result = await prompt(chalk.yellow(`Please repeat this code ${code}: `));
if (result === code) {
cli(chalk.green('Be careful....'));
break;
} else {
cli(chalk.red('Try again'));
}
}
}
await this.start();
}
abstract start(): Promise<void>;
}
/**
* Utility to run an app and safely emit metrics on crash
* @param block
*/
export function safe<T>(block: () => T): void {
try {
validateUTCSet();
block();
} catch (e) {
log.error('Unable to run app! Hard failing', e);
Metrics.instance.increment(globalKeys.crash);
shutdownMetrics()
.catch(e => {
// eslint-disable-next-line no-console
console.log('Error shutting down metrics', e);
})
.finally(() => {
process.exit(1);
})
.catch(() => {});
}
}
/**
* Utility to run an app and safely emit metrics on crash for promise based apps
* @param app The app
*/
export async function app(app: ServiceBase): Promise<void> {
try {
validateUTCSet();
log.info(`starting ${app.name}`);
await app.run();
} catch (e) {
log.error('Unable to run app! Hard failing', e);
Metrics.instance.increment(globalKeys.crash);
await shutdownMetrics();
process.exit(1);
}
}