-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
316 lines (279 loc) · 11 KB
/
index.js
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
/*
* Copyright 2018 Mia srl
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict'
const fastifyEnv = require('@fastify/env')
const fp = require('fastify-plugin')
const fastifyFormbody = require('@fastify/formbody')
const Ajv = require('ajv')
const path = require('path')
const { name, description, version } = require(path.join(process.cwd(), 'package.json'))
const addRawCustomPlugin = require('./lib/rawCustomPlugin')
const addPreDecorator = require('./lib/preDecorator')
const addPostDecorator = require('./lib/postDecorator')
const ajvSetup = require('./lib/ajvSetup')
const HttpClient = require('./lib/httpClient')
const { extraHeadersKeys } = require('./lib/util')
const USERID_HEADER_KEY = 'USERID_HEADER_KEY'
const USER_PROPERTIES_HEADER_KEY = 'USER_PROPERTIES_HEADER_KEY'
const GROUPS_HEADER_KEY = 'GROUPS_HEADER_KEY'
const CLIENTTYPE_HEADER_KEY = 'CLIENTTYPE_HEADER_KEY'
const BACKOFFICE_HEADER_KEY = 'BACKOFFICE_HEADER_KEY'
const MICROSERVICE_GATEWAY_SERVICE_NAME = 'MICROSERVICE_GATEWAY_SERVICE_NAME'
const ADDITIONAL_HEADERS_TO_PROXY = 'ADDITIONAL_HEADERS_TO_PROXY'
const ENABLE_HTTP_CLIENT_METRICS = 'ENABLE_HTTP_CLIENT_METRICS'
const baseSchema = {
type: 'object',
required: [
USERID_HEADER_KEY,
GROUPS_HEADER_KEY,
CLIENTTYPE_HEADER_KEY,
BACKOFFICE_HEADER_KEY,
MICROSERVICE_GATEWAY_SERVICE_NAME,
],
properties: {
[USERID_HEADER_KEY]: {
type: 'string',
description: 'the header key to get the user id',
minLength: 1,
},
[USER_PROPERTIES_HEADER_KEY]: {
type: 'string',
description: 'the header key to get the user permissions',
minLength: 1,
default: 'miauserproperties',
},
[GROUPS_HEADER_KEY]: {
type: 'string',
description: 'the header key to get the groups comma separated list',
minLength: 1,
},
[CLIENTTYPE_HEADER_KEY]: {
type: 'string',
description: 'the header key to get the client type',
minLength: 1,
},
[BACKOFFICE_HEADER_KEY]: {
type: 'string',
description: 'the header key to get if the request is from backoffice (any truly string is true!!!)',
minLength: 1,
},
[MICROSERVICE_GATEWAY_SERVICE_NAME]: {
type: 'string',
description: 'the service name of the microservice gateway',
pattern: '^(?=.{1,253}.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*.?$',
},
[ADDITIONAL_HEADERS_TO_PROXY]: {
type: 'string',
default: '',
description: 'comma separated list of additional headers to proxy',
},
[ENABLE_HTTP_CLIENT_METRICS]: {
type: 'boolean',
default: false,
description: 'flag to enable the httpClient metrics',
},
},
}
function mergeObjectOrArrayProperty(toBeMergedValues, alreadyMergedValues, isArray) {
return isArray ? [
...toBeMergedValues ?? [],
...alreadyMergedValues,
] : {
...toBeMergedValues ?? {},
...alreadyMergedValues,
}
}
// WARNING: including any first level properties other than the ones already declared
// may have undesired effects on the result of the merge
function mergeWithDefaultJsonSchema(schema) {
const defaultSchema = {
...baseSchema,
}
Object.keys(schema).forEach(key => {
defaultSchema[key] = typeof schema[key] === 'object'
? mergeObjectOrArrayProperty(defaultSchema[key], schema[key], Array.isArray(schema[key]))
: schema[key]
})
return defaultSchema
}
function getOverlappingKeys(properties, otherProperties) {
if (!otherProperties) {
return []
}
const propertiesNames = Object.keys(properties)
const otherPropertiesNames = Object.keys(otherProperties)
const overlappingProperties = propertiesNames.filter(propertyName =>
otherPropertiesNames.includes(propertyName)
)
return overlappingProperties
}
function getCustomHeaders(headersKeyToProxy, headers) {
return headersKeyToProxy.reduce((acc, headerKey) => {
if (!{}.hasOwnProperty.call(headers, headerKey)) {
return acc
}
const headerValue = headers[headerKey]
return {
...acc,
[headerKey]: headerValue,
}
}, {})
}
function getBaseOptionsDecorated(headersKeyToProxy, baseOptions, headers) {
return {
...baseOptions,
headers: {
...getCustomHeaders(headersKeyToProxy, headers),
...baseOptions.headers,
},
}
}
function getMiaHeaders() {
const userId = this.getUserId()
const userProperties = this.getUserProperties()
const groups = this.getGroups().join(',')
const clientType = this.getClientType()
const fromBackoffice = this.isFromBackOffice() ? '1' : ''
return {
...userId !== null ? { [this.USERID_HEADER_KEY]: userId } : {},
...userProperties !== null ? { [this.USER_PROPERTIES_HEADER_KEY]: JSON.stringify(userProperties) } : {},
...groups ? { [this.GROUPS_HEADER_KEY]: groups } : {},
...clientType !== null ? { [this.CLIENTTYPE_HEADER_KEY]: clientType } : {},
...fromBackoffice ? { [this.BACKOFFICE_HEADER_KEY]: fromBackoffice } : {},
}
}
function getOriginalRequestHeaders() {
return this.headers
}
function getHttpClientFromRequest(url, baseOptions = {}) {
const requestHeaders = this.getOriginalRequestHeaders()
const extraHeaders = getCustomHeaders(extraHeadersKeys, requestHeaders)
const options = getBaseOptionsDecorated(this[ADDITIONAL_HEADERS_TO_PROXY], baseOptions, requestHeaders)
const serviceHeaders = { ...this.getMiaHeaders(), ...extraHeaders }
return new HttpClient(url, serviceHeaders, options, this.httpClientMetrics)
}
function getHttpClient(url, baseOptions = {}, httpClientMetrics = {}) {
return new HttpClient(url, {}, baseOptions, httpClientMetrics)
}
function getHttpClientFastifyDecoration(url, baseOptions = {}) {
return getHttpClient(url, baseOptions, this.httpClientMetrics)
}
function getHeadersToProxy({ isMiaHeaderInjected = true } = {}) {
const requestHeaders = this.getOriginalRequestHeaders()
const miaHeaders = this.getMiaHeaders()
const extraMiaHeaders = getCustomHeaders(extraHeadersKeys, requestHeaders)
const customHeaders = getCustomHeaders(this[ADDITIONAL_HEADERS_TO_PROXY], requestHeaders)
return {
...isMiaHeaderInjected ? miaHeaders : {},
...isMiaHeaderInjected ? extraMiaHeaders : {},
...customHeaders,
}
}
function decorateFastify(fastify) {
const { config } = fastify
const httpClientMetrics = config[ENABLE_HTTP_CLIENT_METRICS] ? getHttpClientMetrics(fastify) : {}
fastify.decorateRequest(USERID_HEADER_KEY, config[USERID_HEADER_KEY])
fastify.decorateRequest(USER_PROPERTIES_HEADER_KEY, config[USER_PROPERTIES_HEADER_KEY])
fastify.decorateRequest(GROUPS_HEADER_KEY, config[GROUPS_HEADER_KEY])
fastify.decorateRequest(CLIENTTYPE_HEADER_KEY, config[CLIENTTYPE_HEADER_KEY])
fastify.decorateRequest(BACKOFFICE_HEADER_KEY, config[BACKOFFICE_HEADER_KEY])
fastify.decorateRequest(MICROSERVICE_GATEWAY_SERVICE_NAME, config[MICROSERVICE_GATEWAY_SERVICE_NAME])
fastify.decorateRequest(ADDITIONAL_HEADERS_TO_PROXY, {
getter() {
return config[ADDITIONAL_HEADERS_TO_PROXY].split(',').filter(header => header)
},
})
fastify.decorateRequest('getMiaHeaders', getMiaHeaders)
fastify.decorateRequest('getOriginalRequestHeaders', getOriginalRequestHeaders)
fastify.decorateRequest('getHeadersToProxy', getHeadersToProxy)
fastify.decorateRequest('getHttpClient', getHttpClientFromRequest)
fastify.decorateRequest('httpClientMetrics', { getter: () => httpClientMetrics })
fastify.decorate(MICROSERVICE_GATEWAY_SERVICE_NAME, config[MICROSERVICE_GATEWAY_SERVICE_NAME])
fastify.decorate('addRawCustomPlugin', addRawCustomPlugin)
fastify.decorate('addPreDecorator', addPreDecorator)
fastify.decorate('addPostDecorator', addPostDecorator)
fastify.decorate('getHttpClient', getHttpClientFastifyDecoration)
fastify.decorate('httpClientMetrics', httpClientMetrics)
}
async function decorateRequestAndFastifyInstance(fastify, { asyncInitFunction, serviceOptions = {} }) {
const { ajv: ajvServiceOptions } = serviceOptions
const ajv = new Ajv({ coerceTypes: true, useDefaults: true })
ajvSetup(ajv, ajvServiceOptions)
fastify.setValidatorCompiler(({ schema }) => ajv.compile(schema))
fastify.decorate('addValidatorSchema', (schema) => {
ajv.addSchema(schema)
fastify.addSchema(schema)
})
fastify.decorate('getValidatorSchema', ajv.getSchema.bind(ajv))
decorateFastify(fastify)
fastify.register(fp(asyncInitFunction))
fastify.setErrorHandler(function errorHandler(error, request, reply) {
if (reply.raw.statusCode === 500 && !error.statusCode) {
request.log.error(error)
reply.send(new Error('Something went wrong'))
return
}
reply.send(error)
})
fastify.setSchemaErrorFormatter((errors, dataVar) => {
const [{ instancePath, message }] = errors
const objectPath = `${dataVar}${instancePath.replace(/\//g, '.')}`
const customErr = new Error(`${objectPath} ${message}`)
customErr.statusCode = 400
return customErr
})
}
function initCustomServiceEnvironment(envSchema) {
return function customService(asyncInitFunction, serviceOptions) {
async function index(fastify, opts) {
const overlappingPropertiesNames = getOverlappingKeys(baseSchema.properties, envSchema?.properties)
if (overlappingPropertiesNames.length > 0) {
throw new Error(`The provided Environment JSON Schema includes properties declared in the Base JSON Schema of the custom-plugin-lib, please remove them from your schema. The properties to remove are: ${overlappingPropertiesNames.join(', ')}`)
}
const schema = envSchema ? mergeWithDefaultJsonSchema(envSchema) : baseSchema
fastify.register(fastifyEnv, { schema, data: opts })
fastify.register(fastifyFormbody)
fastify.register(fp(decorateRequestAndFastifyInstance), { asyncInitFunction, serviceOptions })
}
index.options = {
errorHandler: false,
trustProxy: process.env.TRUSTED_PROXIES,
}
index.swaggerDefinition = {
info: {
title: name,
description,
version,
},
consumes: ['application/json', 'application/x-www-form-urlencoded'],
produces: ['application/json'],
}
return index
}
}
function getHttpClientMetrics(fastify) {
if (fastify.metrics?.client) {
const requestDuration = new fastify.metrics.client.Histogram({
name: 'http_request_duration_milliseconds',
help: 'request duration histogram',
labelNames: ['baseUrl', 'url', 'method', 'statusCode'],
buckets: [5, 10, 50, 100, 500, 1000, 5000, 10000],
})
return { requestDuration }
}
}
module.exports = initCustomServiceEnvironment
module.exports.getHttpClient = getHttpClient