|
| 1 | +/** @import { Attributes, Span, Tracer } from '@opentelemetry/api' */ |
| 2 | +import { HttpError, Redirect } from '../control.js'; |
| 3 | +import { load_status_code } from './load_otel.js'; |
| 4 | +import { noop_span } from './noop.js'; |
| 5 | + |
| 6 | +/** |
| 7 | + * @template T |
| 8 | + * @param {Object} options |
| 9 | + * @param {string} options.name |
| 10 | + * @param {Tracer} options.tracer |
| 11 | + * @param {Attributes} options.attributes |
| 12 | + * @param {function(Span): Promise<T>} options.fn |
| 13 | + * @returns {Promise<T>} |
| 14 | + */ |
| 15 | +export async function record_span({ name, tracer, attributes, fn }) { |
| 16 | + const SpanStatusCode = await load_status_code(); |
| 17 | + if (SpanStatusCode === null) { |
| 18 | + return fn(noop_span); |
| 19 | + } |
| 20 | + |
| 21 | + return tracer.startActiveSpan(name, { attributes }, async (span) => { |
| 22 | + try { |
| 23 | + const result = await fn(span); |
| 24 | + span.end(); |
| 25 | + return result; |
| 26 | + } catch (error) { |
| 27 | + if (error instanceof HttpError) { |
| 28 | + span.setAttributes({ |
| 29 | + [`${name}.result.type`]: 'known_error', |
| 30 | + [`${name}.result.status`]: error.status, |
| 31 | + [`${name}.result.message`]: error.body.message |
| 32 | + }); |
| 33 | + span.recordException({ |
| 34 | + name: 'HttpError', |
| 35 | + message: error.body.message |
| 36 | + }); |
| 37 | + span.setStatus({ |
| 38 | + code: SpanStatusCode.ERROR, |
| 39 | + message: error.body.message |
| 40 | + }); |
| 41 | + } else if (error instanceof Redirect) { |
| 42 | + span.setAttributes({ |
| 43 | + [`${name}.result.type`]: 'redirect', |
| 44 | + [`${name}.result.status`]: error.status, |
| 45 | + [`${name}.result.location`]: error.location |
| 46 | + }); |
| 47 | + } else if (error instanceof Error) { |
| 48 | + span.setAttributes({ |
| 49 | + [`${name}.result.type`]: 'unknown_error' |
| 50 | + }); |
| 51 | + span.recordException({ |
| 52 | + name: error.name, |
| 53 | + message: error.message, |
| 54 | + stack: error.stack |
| 55 | + }); |
| 56 | + span.setStatus({ |
| 57 | + code: SpanStatusCode.ERROR, |
| 58 | + message: error.message |
| 59 | + }); |
| 60 | + } else { |
| 61 | + span.setAttributes({ |
| 62 | + [`${name}.result.type`]: 'unknown_error' |
| 63 | + }); |
| 64 | + span.setStatus({ code: SpanStatusCode.ERROR }); |
| 65 | + } |
| 66 | + span.end(); |
| 67 | + |
| 68 | + throw error; |
| 69 | + } |
| 70 | + }); |
| 71 | +} |
0 commit comments