Skip to content

Commit

Permalink
Merge pull request #3 from zazuko/next-otel
Browse files Browse the repository at this point in the history
OpenTelemetry tracing
  • Loading branch information
bergos authored Jul 26, 2021
2 parents c0978a1 + e6f997a commit 387634c
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 4 deletions.
15 changes: 13 additions & 2 deletions packages/http/lib/fetch.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,21 @@
import { SpanStatusCode } from '@opentelemetry/api'
import toReadable from 'duplex-to/readable.js'
import nodeFetch from 'node-fetch'
import tracer from './tracer.js'

async function fetch ({ method = 'GET', url, ...options } = {}) {
const response = await nodeFetch(url, { method, ...options })
return await tracer.startActiveSpan('fetch', async span => {
try {
const response = await nodeFetch(url, { method, ...options })

return toReadable(response.body)
return toReadable(response.body)
} catch (e) {
span.recordException(e)
span.setStatus({ code: SpanStatusCode.ERROR, message: e.message })
} finally {
span.end()
}
})
}

export default fetch
6 changes: 6 additions & 0 deletions packages/http/lib/tracer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { trace } from '@opentelemetry/api'

// TODO: set library version here
const tracer = trace.getTracer('barnard59-http')

export default tracer
7 changes: 5 additions & 2 deletions packages/http/lib/writableFetch.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
import duplexify from 'duplexify'
import nodeFetch from 'node-fetch'
import { PassThrough } from 'readable-stream'
import tracer from './tracer.js'

async function fetch ({ method = 'POST', url, ...options } = {}) {
const inputStream = new PassThrough()
const outputStream = new PassThrough()

setTimeout(async () => {
tracer.startActiveSpan('writableFetch', span => setTimeout(async () => {
try {
const response = await nodeFetch(url, { method, body: inputStream, ...options })

response.body.pipe(outputStream)
} catch (err) {
outputStream.emit('error', err)
} finally {
span.end()
}
}, 0)
}, 0))

return duplexify(inputStream, outputStream)
}
Expand Down
1 change: 1 addition & 0 deletions packages/http/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
},
"homepage": "https://github.com/zazuko/barnard59-http",
"dependencies": {
"@opentelemetry/api": "^1.0.1",
"duplex-to": "^1.0.1",
"duplexify": "^4.0.0",
"node-fetch": "^2.6.1",
Expand Down

0 comments on commit 387634c

Please sign in to comment.