-
Notifications
You must be signed in to change notification settings - Fork 18
/
app.ts
335 lines (303 loc) · 9.48 KB
/
app.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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
import { EventEmitter } from 'node:events'
import type http from 'node:http'
import type { ServerZoneType } from '@amplitude/analytics-types'
import fastifyAuth from '@fastify/auth'
import { diContainer, fastifyAwilixPlugin } from '@fastify/awilix'
import { fastifyCors } from '@fastify/cors'
import fastifyHelmet from '@fastify/helmet'
import type { Secret } from '@fastify/jwt'
import fastifyJWT from '@fastify/jwt'
import fastifySchedule from '@fastify/schedule'
import fastifySwagger from '@fastify/swagger'
import {
amplitudePlugin,
bugsnagPlugin,
getRequestIdFastifyAppConfig,
metricsPlugin,
newrelicTransactionManagerPlugin,
publicHealthcheckPlugin,
requestContextProviderPlugin,
} from '@lokalise/fastify-extras'
import { type CommonLogger, resolveLogger } from '@lokalise/node-core'
import { resolveGlobalErrorLogObject } from '@lokalise/node-core'
import scalarFastifyApiReference from '@scalar/fastify-api-reference'
import { type AwilixContainer, asFunction } from 'awilix'
import fastify from 'fastify'
import type { FastifyInstance } from 'fastify'
import customHealthCheck from 'fastify-custom-healthcheck'
import fastifyGracefulShutdown from 'fastify-graceful-shutdown'
import fastifyNoIcon from 'fastify-no-icon'
import {
createJsonSchemaTransform,
serializerCompiler,
validatorCompiler,
} from 'fastify-type-provider-zod'
import type { ZodTypeProvider } from 'fastify-type-provider-zod'
import { merge } from 'ts-deepmerge'
import type { PartialDeep } from 'type-fest'
import { type Config, getConfig, isDevelopment } from './infrastructure/config.js'
import { errorHandler } from './infrastructure/errors/errorHandler.js'
import {
dbHealthCheck,
redisHealthCheck,
registerHealthChecks,
} from './infrastructure/healthchecks/healthchecksWrappers.js'
import { SINGLETON_CONFIG, registerDependencies } from './infrastructure/parentDiConfig.js'
import type { DependencyOverrides } from './infrastructure/parentDiConfig.js'
import { getRoutes } from './modules/routes.js'
import { jwtTokenPlugin } from './plugins/jwtTokenPlugin.js'
EventEmitter.defaultMaxListeners = 12
const GRACEFUL_SHUTDOWN_TIMEOUT_IN_MSECS = 10000
export type AppInstance = FastifyInstance<
http.Server,
http.IncomingMessage,
http.ServerResponse,
CommonLogger
>
export type ConfigOverrides = {
diContainer?: AwilixContainer
jwtKeys?: {
public: Secret
private: Secret
}
queuesEnabled?: boolean | string[]
jobsEnabled?: boolean | string[]
healthchecksEnabled?: boolean
monitoringEnabled?: boolean
} & PartialDeep<Config>
// do not delete // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: This is intentional. Don't remove.
export async function getApp(
configOverrides: ConfigOverrides = {},
dependencyOverrides: DependencyOverrides = {},
): Promise<AppInstance> {
const config = getConfig()
const appConfig = config.app
const logger = resolveLogger(appConfig)
const enableRequestLogging = ['debug', 'trace'].includes(appConfig.logLevel)
const app = fastify<http.Server, http.IncomingMessage, http.ServerResponse, CommonLogger>({
...getRequestIdFastifyAppConfig(),
loggerInstance: logger,
disableRequestLogging: !enableRequestLogging,
})
app.setValidatorCompiler(validatorCompiler)
app.setSerializerCompiler(serializerCompiler)
// In production this should ideally be handled outside of application, e. g.
// on nginx or kubernetes level, but for local development it is convenient
// to have these headers set by application.
// If this service is never called from the browser, this entire block can be removed.
if (isDevelopment()) {
await app.register(fastifyCors, {
origin: '*',
credentials: true,
methods: ['GET', 'PUT', 'PATCH', 'POST', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Origin', 'X-Requested-With', 'Accept', 'Content-Type', 'Authorization'],
exposedHeaders: [
'Access-Control-Allow-Origin',
'Access-Control-Allow-Methods',
'Access-Control-Allow-Headers',
],
})
}
await app.register(
fastifyHelmet,
isDevelopment()
? {
contentSecurityPolicy: false,
}
: {},
)
if (!isDevelopment()) {
await app.register(fastifyGracefulShutdown, {
resetHandlersOnInit: true,
timeout: GRACEFUL_SHUTDOWN_TIMEOUT_IN_MSECS,
})
}
await app.register(fastifyNoIcon)
await app.register(fastifyAuth)
await app.register(fastifySwagger, {
transform: createJsonSchemaTransform({
skipList: [
'/documentation/',
'/documentation/initOAuth',
'/documentation/json',
'/documentation/uiConfig',
'/documentation/yaml',
'/documentation/*',
'/documentation/static/*',
'*',
],
}),
openapi: {
info: {
title: 'SampleApi',
description: 'Sample backend service',
version: '1.0.0',
},
servers: [
{
url:
appConfig.baseUrl ||
`http://${
appConfig.bindAddress === '0.0.0.0' ? 'localhost' : appConfig.bindAddress
}:${appConfig.port}`,
},
],
components: {
securitySchemes: {
bearerAuth: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
},
},
},
},
})
await app.register(scalarFastifyApiReference, {
routePrefix: '/documentation',
})
app.get('/documentation/json', { schema: { hide: true } }, () => {
return app.swagger()
})
await app.register(fastifyAwilixPlugin, {
disposeOnClose: true,
asyncDispose: true,
asyncInit: true,
eagerInject: true,
disposeOnResponse: false,
})
await app.register(fastifySchedule)
await app.register(fastifyJWT, {
secret: configOverrides.jwtKeys ?? {
private: '-', // Private key blank, as this service won't create JWT tokens, only verify them
public: appConfig.jwtPublicKey,
},
})
await app.register(jwtTokenPlugin, {
skipList: new Set([
'/favicon.ico',
'/login',
'/access-token',
'/refresh-token',
'/documentation',
'/documentation/json',
'/documentation/@scalar/fastify-api-reference/js/browser.js',
'/',
'/health',
'/metrics',
]),
})
app.setErrorHandler(errorHandler)
const dependencies: DependencyOverrides = configOverrides
? {
...dependencyOverrides,
config: asFunction(() => {
return merge(getConfig(), configOverrides) as Config
}, SINGLETON_CONFIG),
}
: dependencyOverrides
registerDependencies(
configOverrides.diContainer ?? diContainer,
{
app,
logger: app.log,
},
dependencies,
/**
* Running consumers and jobs introduces additional overhead and fragility when running tests,
* so we avoid doing that unless we intend to actually use them
*/
{
queuesEnabled: !!configOverrides.queuesEnabled,
jobsEnabled: !!configOverrides.jobsEnabled,
},
)
if (configOverrides.monitoringEnabled) {
await app.register(metricsPlugin, {
bindAddress: appConfig.bindAddress,
errorObjectResolver: resolveGlobalErrorLogObject,
logger,
disablePrometheusRequestLogging: true,
})
}
if (configOverrides.healthchecksEnabled !== false) {
await app.register(customHealthCheck, {
path: '/',
logLevel: 'warn',
info: {
env: appConfig.nodeEnv,
app_version: appConfig.appVersion,
git_commit_sha: appConfig.gitCommitSha,
},
schema: false,
exposeFailure: false,
})
await app.register(publicHealthcheckPlugin, {
url: '/health',
healthChecks: [
{
name: 'postgres',
isMandatory: true,
checker: dbHealthCheck,
},
{
name: 'redis',
isMandatory: true,
checker: redisHealthCheck,
},
],
responsePayload: {
version: appConfig.appVersion,
gitCommitSha: appConfig.gitCommitSha,
},
})
}
await app.register(requestContextProviderPlugin)
// Vendor-specific plugins
await app.register(newrelicTransactionManagerPlugin, {
isEnabled: config.vendors.newrelic.isEnabled,
})
await app.register(bugsnagPlugin, {
isEnabled: config.vendors.bugsnag.isEnabled,
bugsnag: {
apiKey: config.vendors.bugsnag.apiKey ?? '',
releaseStage: appConfig.appEnv,
appVersion: appConfig.appVersion,
...(config.vendors.bugsnag.appType && { appType: config.vendors.bugsnag.appType }),
},
})
await app.register(amplitudePlugin, {
isEnabled: config.vendors.amplitude.isEnabled,
apiKey: config.vendors.amplitude.apiKey,
options: {
serverZone: config.vendors.amplitude.serverZone as ServerZoneType,
flushIntervalMillis: config.vendors.amplitude.flushIntervalMillis,
flushMaxRetries: config.vendors.amplitude.flushMaxRetries,
flushQueueSize: config.vendors.amplitude.flushQueueSize,
},
})
app.after(() => {
// Register routes
const { routes } = getRoutes()
for (const route of routes) {
app.withTypeProvider<ZodTypeProvider>().route(route)
}
// Graceful shutdown hook
if (!isDevelopment()) {
app.gracefulShutdown((_signal) => {
app.log.info('Starting graceful shutdown')
return Promise.resolve()
})
}
if (configOverrides.healthchecksEnabled !== false) {
registerHealthChecks(app)
}
})
try {
await app.ready()
} catch (err) {
app.log.error('Error while initializing app: ', err)
throw err
}
return app
}