2021-08-15 21:26:02 +02:00
|
|
|
import retry from 'next/dist/compiled/async-retry'
|
|
|
|
import { randomBytes } from 'crypto'
|
|
|
|
import fetch from 'node-fetch'
|
|
|
|
import * as Log from '../../../build/output/log'
|
2021-08-17 09:18:47 +02:00
|
|
|
// Jaeger uses Zipkin's reporting
|
|
|
|
import { batcher } from './to-zipkin'
|
2021-08-15 21:26:02 +02:00
|
|
|
|
|
|
|
let traceId = process.env.TRACE_ID
|
|
|
|
let batch: ReturnType<typeof batcher> | undefined
|
|
|
|
|
|
|
|
const localEndpoint = {
|
|
|
|
serviceName: 'nextjs',
|
|
|
|
ipv4: '127.0.0.1',
|
|
|
|
port: 9411,
|
|
|
|
}
|
|
|
|
// Jaeger supports Zipkin's reporting API
|
|
|
|
const zipkinUrl = `http://${localEndpoint.ipv4}:${localEndpoint.port}`
|
|
|
|
const jaegerWebUiUrl = `http://${localEndpoint.ipv4}:16686`
|
|
|
|
const zipkinAPI = `${zipkinUrl}/api/v2/spans`
|
|
|
|
|
2021-08-17 09:18:47 +02:00
|
|
|
function logWebUrl() {
|
|
|
|
Log.info(
|
|
|
|
`Jaeger trace will be available on ${jaegerWebUiUrl}/trace/${traceId}`
|
|
|
|
)
|
2021-08-15 21:26:02 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
const reportToLocalHost = (
|
|
|
|
name: string,
|
|
|
|
duration: number,
|
|
|
|
timestamp: number,
|
|
|
|
id: string,
|
|
|
|
parentId?: string,
|
|
|
|
attrs?: Object
|
|
|
|
) => {
|
|
|
|
if (!traceId) {
|
|
|
|
traceId = process.env.TRACE_ID = randomBytes(8).toString('hex')
|
2021-08-17 09:18:47 +02:00
|
|
|
logWebUrl()
|
2021-08-15 21:26:02 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
if (!batch) {
|
|
|
|
batch = batcher((events) => {
|
2021-08-17 09:18:47 +02:00
|
|
|
const eventsJson = JSON.stringify(events)
|
2021-08-15 21:26:02 +02:00
|
|
|
// Ensure ECONNRESET error is retried 3 times before erroring out
|
2021-08-17 09:18:47 +02:00
|
|
|
return retry(
|
2021-08-15 21:26:02 +02:00
|
|
|
() =>
|
|
|
|
// Send events to zipkin
|
|
|
|
fetch(zipkinAPI, {
|
|
|
|
method: 'POST',
|
|
|
|
headers: { 'Content-Type': 'application/json' },
|
2021-08-17 09:18:47 +02:00
|
|
|
body: eventsJson,
|
2021-08-15 21:26:02 +02:00
|
|
|
}),
|
|
|
|
{ minTimeout: 500, retries: 3, factor: 1 }
|
2021-08-17 09:18:47 +02:00
|
|
|
)
|
|
|
|
.then(async (res: any) => {
|
|
|
|
if (res.status !== 202) {
|
|
|
|
console.log({
|
|
|
|
status: res.status,
|
|
|
|
body: await res.text(),
|
|
|
|
events: eventsJson,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.catch(console.log)
|
2021-08-15 21:26:02 +02:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2021-08-17 09:18:47 +02:00
|
|
|
batch.report({
|
2021-08-15 21:26:02 +02:00
|
|
|
traceId,
|
|
|
|
parentId,
|
|
|
|
name,
|
|
|
|
id,
|
|
|
|
timestamp,
|
|
|
|
duration,
|
|
|
|
localEndpoint,
|
|
|
|
tags: attrs,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2021-08-17 09:18:47 +02:00
|
|
|
export default {
|
|
|
|
flushAll: () =>
|
|
|
|
batch ? batch.flushAll().then(() => logWebUrl()) : undefined,
|
|
|
|
report: reportToLocalHost,
|
|
|
|
}
|