Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,8 @@ RPC_URL_8453=https://example-rpc
RPC_URL_42161=https://example-rpc
RPC_URL_80094=https://example-rpc
RPC_URL_747474=https://example-rpc
# OpenTelemetry error reporting. Leave the endpoint unset to disable.
# Point at any OTLP/HTTP backend (Sentry OTLP, Grafana, Honeycomb, an OTel Collector, ...).
OTEL_EXPORTER_OTLP_ENDPOINT=
OTEL_EXPORTER_OTLP_HEADERS=
OTEL_SERVICE_NAME=yearn-prices
2 changes: 2 additions & 0 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { createPool } from './db'
import { readEdgeCache, writeEdgeCache } from './edge-cache'
import { ApiError, jsonError } from './errors'
import { optionsResponse, withCors } from './http'
import { captureError } from './observability'
import { handleHealth } from './routes/health'
import { handleBatchHistorical, handleHistorical, handleRangeHistorical, handleSpot, notFoundErrorHeaders } from './routes/prices'
import type { Env } from './types'
Expand Down Expand Up @@ -110,6 +111,7 @@ export default {
error: error instanceof Error ? error.message : String(error),
}),
)
captureError(ctx, env, error)
return jsonError(new ApiError('INTERNAL_ERROR', 'Unexpected internal error'), withCors({ 'cache-control': CACHE_CONTROL_NO_STORE }))
}
},
Expand Down
69 changes: 69 additions & 0 deletions src/observability.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import type { Env } from './types'

// Cloudflare Workers can't run the OpenTelemetry Node SDK, so errors are sent as
// OTLP/HTTP JSON log records via fetch. Vendor-neutral: point
// OTEL_EXPORTER_OTLP_ENDPOINT at any OTLP backend (Sentry OTLP, Grafana, a Collector, ...).
const SERVICE_NAME = 'yearn-prices'
const SEVERITY_ERROR = 17 // OTLP severityNumber for ERROR

type OtlpAttribute = { key: string; value: { stringValue: string } }

function attr(key: string, value: string): OtlpAttribute {
return { key, value: { stringValue: value } }
}

// OTEL_EXPORTER_OTLP_HEADERS format: "key1=value1,key2=value2".
function parseHeaders(raw?: string): Record<string, string> {
const headers: Record<string, string> = { 'content-type': 'application/json' }
if (!raw) return headers
for (const pair of raw.split(',')) {
const idx = pair.indexOf('=')
if (idx > 0) headers[pair.slice(0, idx).trim()] = pair.slice(idx + 1).trim()
}
return headers
}

function buildPayload(serviceName: string, err: Error): unknown {
const attributes = [attr('exception.type', err.name), attr('exception.message', err.message)]
if (err.stack) attributes.push(attr('exception.stacktrace', err.stack))

return {
resourceLogs: [
{
resource: { attributes: [attr('service.name', serviceName)] },
scopeLogs: [
{
scope: { name: serviceName },
logRecords: [
{
timeUnixNano: String(Date.now() * 1_000_000),
severityNumber: SEVERITY_ERROR,
severityText: 'ERROR',
body: { stringValue: err.message },
attributes,
},
],
},
],
},
],
}
}

export function captureError(ctx: ExecutionContext, env: Env, error: unknown): void {
const endpoint = env.OTEL_EXPORTER_OTLP_ENDPOINT
if (!endpoint) return

const err = error instanceof Error ? error : new Error(String(error))
const url = `${endpoint.replace(/\/$/, '')}/v1/logs`
const body = JSON.stringify(buildPayload(env.OTEL_SERVICE_NAME || SERVICE_NAME, err))

// waitUntil lets the export finish after the response is returned (no added latency).
ctx.waitUntil(
fetch(url, {
method: 'POST',
headers: parseHeaders(env.OTEL_EXPORTER_OTLP_HEADERS),
body,
}).catch(() => {}),
)
}
3 changes: 3 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ export type PriceSource = (typeof SOURCE_PRIORITY)[number]
export interface Env {
DATABASE_URL: string
ENSO_API_KEY?: string
OTEL_EXPORTER_OTLP_ENDPOINT?: string
OTEL_EXPORTER_OTLP_HEADERS?: string
OTEL_SERVICE_NAME?: string
[key: string]: string | undefined
}

Expand Down
Loading