-
-
Notifications
You must be signed in to change notification settings - Fork 68
/
parsers.js
392 lines (372 loc) · 9.52 KB
/
parsers.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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
const { EventEmitter } = require('events')
const { QrynError } = require('./lib/handlers/errors')
const StreamArray = require('stream-json/streamers/StreamArray')
const { parser: jsonlParser } = require('stream-json/jsonl/Parser')
const yaml = require('yaml')
let snappy = null
try {
snappy = require('snappyjs')
} catch (e) {}
const stream = require('stream')
const protobufjs = require('protobufjs')
const path = require('path')
const WriteRequest = protobufjs.loadSync(path.join(__dirname, 'lib', 'prompb.proto')).lookupType('WriteRequest')
const PushRequest = protobufjs.loadSync(path.join(__dirname, 'lib', 'loki.proto')).lookupType('PushRequest')
const OTLPTraceData = protobufjs.loadSync(path.join(__dirname, 'lib', 'otlp.proto')).lookupType('TracesData')
const OTLPLogsData = protobufjs.loadSync(path.join(__dirname, 'lib', 'otlp.proto')).lookupType('LogsData')
const { parse: queryParser } = require('fast-querystring')
/**
*
* @param req {FastifyRequest}
* @param payload {Stream}
* @returns {any}
*/
const wwwFormParser = async (req, payload) => {
return queryParser(await getContentBody(req, payload))
}
/**
*
* @param req {FastifyRequest}
* @param payload {Stream}
*/
const lokiPushJSONParser = async (req, payload) => {
try {
const length = getContentLength(req, 1e9)
if (length > 5 * 1024 * 1024) {
return
}
await shaper.register(length)
const body = await getContentBody(req, payload)
return JSON.parse(body)
} catch (err) {
err.statusCode = 400
throw err
}
}
/**
*
* @param req {FastifyRequest}
* @param payload {Stream}
* @returns {any}
*/
async function tempoPushNDJSONParser (req, payload) {
const parser = payload.pipe(jsonlParser())
parser.on('error', err => { parser.error = err })
return parser
}
/**
* @param req {FastifyRequest}
* @param payload {Stream}
* @returns {any}
*/
async function jsonParser (req, payload) {
return JSON.parse(await getContentBody(req, payload))
}
/**
* @param req {FastifyRequest}
* @param payload {Stream}
* @returns {any}
*/
async function yamlParser (req, payload) {
return yaml.parse(await getContentBody(req, payload))
}
/**
*
* @param req {FastifyRequest}
* @param payload {Stream}
* @returns {any}
*/
async function tempoPushParser (req, payload) {
const firstData = await new Promise((resolve, reject) => {
req.raw.once('data', resolve)
req.raw.once('error', reject)
req.raw.once('close', () => resolve(null))
req.raw.once('end', () => resolve(null))
})
const parser = StreamArray.withParser()
parser.on('error', err => { parser.error = err })
parser.write(firstData || '[]')
if (!firstData) {
parser.end()
return parser
}
req.raw.pipe(parser)
return parser
}
/**
* @param req {FastifyRequest}
* @param payload {Stream}
*/
async function rawStringParser (req, payload) {
return await getContentBody(req, payload)
}
/**
* @param req {FastifyRequest}
* @param payload {Stream}
*/
async function lokiPushProtoParser (req, payload) {
if (!snappy) {
throw new Error('snappy not found')
}
const length = getContentLength(req, 5e6)
await shaper.register(length)
const body = []
req.raw.on('data', (data) => {
body.push(data)
})
await new Promise(resolve => req.raw.once('end', resolve))
let _data = await snappy.uncompress(Buffer.concat(body))
_data = PushRequest.decode(_data)
_data.streams = _data.streams.map(s => ({
...s,
entries: s.entries.map(e => {
const ts = e.timestamp
? BigInt(e.timestamp.seconds) * BigInt(1e9) + BigInt(e.timestamp.nanos)
: BigInt(Date.now().toString() + '000000')
return {
...e,
timestamp: ts
}
})
}))
return _data.streams
}
/**
* @param req {FastifyRequest}
* @param payload {Stream}
*/
async function prometheusPushProtoParser (req, payload) {
if (!snappy) {
throw new Error('snappy not found')
}
const length = getContentLength(req, 5e6)
await shaper.register(length)
const body = []
req.raw.on('data', (data) => {
body.push(data)
})
await new Promise(resolve => req.raw.once('end', resolve))
let _data = await snappy.uncompress(Buffer.concat(body))
_data = WriteRequest.decode(_data)
_data.timeseries = _data.timeseries.map(s => ({
...s,
samples: s.samples.map(e => {
const nanos = e.timestamp + '000000'
return {
...e,
timestamp: nanos
}
})
}))
return _data
}
/**
* @param req {FastifyRequest}
* @param payload {Stream} zlib.Gunzip
*/
async function otlpPushProtoParser (req, payload) {
const length = getContentLength(req, 5e6)
await shaper.register(length)
let body = []
const otelStream = stream.Readable.from(payload)
otelStream.on('data', data => {
body.push(data)
})
await new Promise(resolve => otelStream.once('end', resolve))
body = Buffer.concat(body)
body = OTLPTraceData.toObject(OTLPTraceData.decode(body), {
longs: String,
bytes: String
})
return body
}
/**
*
* @param req {FastifyRequest}
* @param payload {Stream}
* @returns {*}
*/
function tempoNDJsonParser (req, payload) {
const parser = req.raw.pipe(jsonlParser())
parser.on('error', err => { parser.error = err })
return parser
}
/**
*
* @param req {FastifyRequest}
* @param payload {Stream}
* @returns {*}
*/
async function otlpLogsDataParser (req, payload) {
const length = getContentLength(req, 5e6)
await shaper.register(length)
let body = []
const otelStream = stream.Readable.from(payload)
otelStream.on('data', data => {
body.push(data)
})
await new Promise(resolve => otelStream.once('end', resolve))
body = Buffer.concat(body)
body = OTLPLogsData.toObject(OTLPLogsData.decode(body), {
longs: String,
bytes: String
})
return body
}
/**
*
* @param subparsers {function(FastifyRequest): Promise<*|undefined>}
* @returns {function(FastifyRequest): Promise<*|undefined>}
*/
function combinedParser (...subparsers) {
/**
*
* @param req {FastifyRequest}
* @returns {any}
*/
return async (req, payload) => {
for (const p of subparsers) {
try {
return await p(req, payload)
} catch (e) {}
}
return undefined
}
}
const parsers = {
_parsers: {},
/**
*
* @param fastify {Fastify}
*/
init: (fastify) => {
for (const type of Object.keys(parsers._parsers)) {
fastify.addContentTypeParser(type, parsers.parse(type))
}
return fastify
},
/**
*
* @param contentType {string}
* @returns {function(FastifyRequest, Stream): Promise<*>}
*/
parse: (contentType) =>
/**
*
* @param req {FastifyRequest}
* @param payload {Stream}
*/
async (req, payload) => {
const find = (obj, path) => {
for (const p of path) {
if (!obj[p]) {
return null
}
obj = obj[p]
}
return obj
}
const parser = find(parsers._parsers, [contentType, req.routeOptions.method, req.routeOptions.url]) ||
find(parsers._parsers, ['*', req.routeOptions.method, req.routeOptions.url])
if (!parser) {
throw new Error(`undefined parser for ${contentType} ${req.routeOptions.method} ${req.routeOptions.url}`)
}
return await parser(req, payload)
},
/**
*
* @param method {string}
* @param route {string}
* @param contentType {string}
* @param parser {function(FastifyRequest): Promise<any>}
*/
register: (method, route, contentType, parser) => {
parsers._parsers[contentType] = parsers._parsers[contentType] || {}
parsers._parsers[contentType][method.toUpperCase()] = parsers._parsers[contentType][method.toUpperCase()] || {}
parsers._parsers[contentType][method.toUpperCase()][route] = parser
}
}
const shaper = {
onParse: 0,
onParsed: new EventEmitter(),
shapeInterval: setInterval(() => {
shaper.onParse = 0
shaper.onParsed.emit('parsed')
}, 1000),
/**
*
* @param size {number}
* @returns {Promise<void>}
*/
register: async (size) => {
while (shaper.onParse + size > 50e6) {
await new Promise(resolve => { shaper.onParsed.once('parsed', resolve) })
}
shaper.onParse += size
},
stop: () => {
shaper.shapeInterval && clearInterval(shaper.shapeInterval)
shaper.shapeInterval = null
shaper.onParsed.removeAllListeners('parsed')
shaper.onParsed = null
}
}
/**
*
* @param req {FastifyRequest}
* @param limit {number}
* @returns {number}
*/
function getContentLength (req, limit) {
if (!req.headers['content-length'] || isNaN(parseInt(req.headers['content-length']))) {
return 5 * 1024 * 1024
}
const res = parseInt(req.headers['content-length'])
if (limit && res > limit) {
throw new QrynError(400, 'Request is too big')
}
return res
}
/**
*
* @param req {FastifyRequest}
* @param payload {Stream}
* @returns {Promise<string>}
*/
async function getContentBody (req, payload) {
if (req._rawBody) {
return req._rawBody
}
const body = []
payload.on('data', data => {
body.push(data)// += data.toString()
})
if (payload.isPaused && payload.isPaused()) {
payload.resume()
}
await new Promise(resolve => {
payload.on('end', resolve)
payload.on('close', resolve)
})
req._rawBody = Buffer.concat(body).toString()
return Buffer.concat(body).toString()
}
module.exports = {
getContentBody,
getContentLength,
shaper,
lokiPushJSONParser,
tempoPushParser,
tempoPushNDJSONParser,
jsonParser,
yamlParser,
combinedParser,
rawStringParser,
lokiPushProtoParser,
prometheusPushProtoParser,
tempoNDJsonParser,
otlpPushProtoParser,
wwwFormParser,
parsers,
otlpLogsDataParser
}