fix: clean up otlp export request listeners (#3782)
This commit is contained in:
@@ -0,0 +1,101 @@
|
||||
import { EventEmitter } from 'node:events'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { RedactableSpan } from './redactor'
|
||||
|
||||
const { httpRequestMock, httpsRequestMock } = vi.hoisted(() => ({
|
||||
httpRequestMock: vi.fn(),
|
||||
httpsRequestMock: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('node:http', () => ({ request: httpRequestMock }))
|
||||
vi.mock('node:https', () => ({ request: httpsRequestMock }))
|
||||
|
||||
import { createOtlpExporter } from './otlp-exporter'
|
||||
|
||||
class FakeRequest extends EventEmitter {
|
||||
destroy = vi.fn()
|
||||
end = vi.fn()
|
||||
write = vi.fn()
|
||||
}
|
||||
|
||||
class FakeResponse extends EventEmitter {
|
||||
statusCode = 204
|
||||
resume = vi.fn()
|
||||
}
|
||||
|
||||
function span(): RedactableSpan {
|
||||
return {
|
||||
name: 'unit',
|
||||
traceId: 'a'.repeat(32),
|
||||
spanId: 'b'.repeat(16),
|
||||
kind: 'internal',
|
||||
startTimeUnixNano: '1000',
|
||||
endTimeUnixNano: '2000',
|
||||
durationMs: 1,
|
||||
attributes: {},
|
||||
events: [],
|
||||
exit: { _tag: 'Success' }
|
||||
}
|
||||
}
|
||||
|
||||
describe('otlp exporter HTTP cleanup', () => {
|
||||
it('removes request listeners after a successful export response', async () => {
|
||||
const request = new FakeRequest()
|
||||
const response = new FakeResponse()
|
||||
let responseCallback: ((response: FakeResponse) => void) | null = null
|
||||
httpRequestMock.mockImplementationOnce(
|
||||
(_options: unknown, callback: (response: FakeResponse) => void) => {
|
||||
responseCallback = callback
|
||||
return request
|
||||
}
|
||||
)
|
||||
|
||||
const exporter = createOtlpExporter({
|
||||
tracesUrl: 'http://collector.example/v1/traces',
|
||||
serviceName: 'orca-test',
|
||||
timeoutMs: 1000
|
||||
})
|
||||
exporter.exportSpan(span())
|
||||
const flush = exporter.flush()
|
||||
|
||||
expect(request.listenerCount('error')).toBe(1)
|
||||
expect(request.listenerCount('timeout')).toBe(1)
|
||||
const respond = responseCallback as ((response: FakeResponse) => void) | null
|
||||
if (!respond) {
|
||||
throw new Error('HTTP response callback was not registered')
|
||||
}
|
||||
respond(response)
|
||||
|
||||
await flush
|
||||
exporter.close()
|
||||
expect(response.resume).toHaveBeenCalledTimes(1)
|
||||
expect(request.listenerCount('error')).toBe(0)
|
||||
expect(request.listenerCount('timeout')).toBe(0)
|
||||
})
|
||||
|
||||
it('removes request listeners after an export timeout', async () => {
|
||||
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
try {
|
||||
const request = new FakeRequest()
|
||||
httpRequestMock.mockReturnValueOnce(request)
|
||||
|
||||
const exporter = createOtlpExporter({
|
||||
tracesUrl: 'http://collector.example/v1/traces',
|
||||
serviceName: 'orca-test',
|
||||
timeoutMs: 1000
|
||||
})
|
||||
exporter.exportSpan(span())
|
||||
const flush = exporter.flush()
|
||||
|
||||
request.emit('timeout')
|
||||
|
||||
await flush
|
||||
exporter.close()
|
||||
expect(request.destroy).toHaveBeenCalledTimes(1)
|
||||
expect(request.listenerCount('error')).toBe(0)
|
||||
expect(request.listenerCount('timeout')).toBe(0)
|
||||
} finally {
|
||||
warnSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -21,7 +21,7 @@
|
||||
// (~80 KB of transitive deps) for a feature gated entirely on an env var
|
||||
// the typical user will never set.
|
||||
|
||||
import { request as httpRequest } from 'node:http'
|
||||
import { request as httpRequest, type ClientRequest } from 'node:http'
|
||||
import { request as httpsRequest } from 'node:https'
|
||||
import { URL } from 'node:url'
|
||||
import { redactSpan, type RedactableSpan, type SpanEvent } from './redactor'
|
||||
@@ -298,6 +298,33 @@ function encodeOtlpPayload(serviceName: string, spans: RedactableSpan[]): OtlpPa
|
||||
|
||||
function postJson(url: string, body: unknown, timeoutMs: number): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let settled = false
|
||||
let req: ClientRequest | null = null
|
||||
const cleanupListeners = (): void => {
|
||||
req?.off('error', onError)
|
||||
req?.off('timeout', onTimeout)
|
||||
}
|
||||
const resolveOnce = (): void => {
|
||||
if (settled) {
|
||||
return
|
||||
}
|
||||
settled = true
|
||||
cleanupListeners()
|
||||
resolve()
|
||||
}
|
||||
const rejectOnce = (error: Error, options?: { destroy?: boolean }): void => {
|
||||
if (settled) {
|
||||
return
|
||||
}
|
||||
settled = true
|
||||
if (options?.destroy) {
|
||||
req?.destroy()
|
||||
}
|
||||
cleanupListeners()
|
||||
reject(error)
|
||||
}
|
||||
const onError = (error: Error): void => rejectOnce(error)
|
||||
const onTimeout = (): void => rejectOnce(new Error('OTLP timeout'), { destroy: true })
|
||||
let parsed: URL
|
||||
try {
|
||||
parsed = new URL(url)
|
||||
@@ -307,7 +334,7 @@ function postJson(url: string, body: unknown, timeoutMs: number): Promise<void>
|
||||
}
|
||||
const data = JSON.stringify(body)
|
||||
const protocol = parsed.protocol === 'https:' ? httpsRequest : httpRequest
|
||||
const req = protocol(
|
||||
req = protocol(
|
||||
{
|
||||
protocol: parsed.protocol,
|
||||
hostname: parsed.hostname,
|
||||
@@ -326,16 +353,14 @@ function postJson(url: string, body: unknown, timeoutMs: number): Promise<void>
|
||||
res.resume()
|
||||
const status = res.statusCode ?? 0
|
||||
if (status >= 200 && status < 300) {
|
||||
resolve()
|
||||
resolveOnce()
|
||||
} else {
|
||||
reject(new Error(`OTLP HTTP ${status}`))
|
||||
rejectOnce(new Error(`OTLP HTTP ${status}`))
|
||||
}
|
||||
}
|
||||
)
|
||||
req.on('error', reject)
|
||||
req.on('timeout', () => {
|
||||
req.destroy(new Error('OTLP timeout'))
|
||||
})
|
||||
req.on('error', onError)
|
||||
req.on('timeout', onTimeout)
|
||||
req.write(data)
|
||||
req.end()
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user