Unverified Commit 7c33a217 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Add batching to zipkin reporter (#27082)

parent ad56e81f
import retry from 'next/dist/compiled/async-retry'
import { randomBytes } from 'crypto' import { randomBytes } from 'crypto'
import fetch from 'node-fetch' import fetch from 'node-fetch'
import * as Log from '../../../build/output/log' import * as Log from '../../../build/output/log'
let traceId = process.env.TRACE_ID let traceId = process.env.TRACE_ID
let batch: ReturnType<typeof batcher> | undefined
const localEndpoint = { const localEndpoint = {
serviceName: 'nextjs', serviceName: 'nextjs',
...@@ -12,6 +14,34 @@ const localEndpoint = { ...@@ -12,6 +14,34 @@ const localEndpoint = {
const zipkinUrl = `http://${localEndpoint.ipv4}:${localEndpoint.port}` const zipkinUrl = `http://${localEndpoint.ipv4}:${localEndpoint.port}`
const zipkinAPI = `${zipkinUrl}/api/v2/spans` const zipkinAPI = `${zipkinUrl}/api/v2/spans`
type Event = {
traceId: string
parentId?: string
name: string
id: string
timestamp: number
duration: number
localEndpoint: typeof localEndpoint
tags?: Object
}
// Batch events as zipkin allows for multiple events to be sent in one go
function batcher(reportEvents: (evts: Event[]) => void) {
const events: Event[] = []
let timeout: ReturnType<typeof setTimeout> | undefined
return (event: Event) => {
events.push(event)
// setTimeout is used instead of setInterval to ensure events sending does not block exiting the program
if (!timeout) {
timeout = setTimeout(() => {
reportEvents(events.slice())
events.length = 0
timeout = undefined
}, 1500)
}
}
}
const reportToLocalHost = ( const reportToLocalHost = (
name: string, name: string,
duration: number, duration: number,
...@@ -26,25 +56,33 @@ const reportToLocalHost = ( ...@@ -26,25 +56,33 @@ const reportToLocalHost = (
`Zipkin trace will be available on ${zipkinUrl}/zipkin/traces/${traceId}` `Zipkin trace will be available on ${zipkinUrl}/zipkin/traces/${traceId}`
) )
} }
const body = [
{ if (!batch) {
traceId, batch = batcher((events) => {
parentId, // Ensure ECONNRESET error is retried 3 times before erroring out
name, retry(
id, () =>
timestamp, // Send events to zipkin
duration, fetch(zipkinAPI, {
localEndpoint, method: 'POST',
tags: attrs, headers: { 'Content-Type': 'application/json' },
}, body: JSON.stringify(events),
] }),
{ minTimeout: 500, retries: 3, factor: 1 }
// We intentionally do not block on I/O here. ).catch(console.log)
fetch(zipkinAPI, { })
method: 'POST', }
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body), batch({
}).catch(console.log) traceId,
parentId,
name,
id,
timestamp,
duration,
localEndpoint,
tags: attrs,
})
} }
export default reportToLocalHost export default reportToLocalHost
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment