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
34 changes: 31 additions & 3 deletions bun.lock

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

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@
"@opentelemetry/sdk-logs": "^0.213.0",
"@opentelemetry/sdk-metrics": "^2.6.0",
"@opentelemetry/sdk-trace-base": "^2.6.0",
"@opentelemetry/semantic-conventions": "^1.40.0"
"@opentelemetry/semantic-conventions": "^1.40.0",
"http-proxy-agent": "^9.1.0",
"https-proxy-agent": "^9.1.0"
},
"description": "OpenTelemetry telemetry plugin for opencode CLI",
"devDependencies": {
Expand Down
5 changes: 5 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export type PluginConfig = {
metricPrefix: string
otlpHeaders: string | undefined
otlpHeadersHelper: string | undefined
otlpProxyUrl: string | undefined
resourceAttributes: string | undefined
spanAttributes: string | undefined
traceparent: string | undefined
Expand Down Expand Up @@ -71,6 +72,7 @@ export type OtelPluginOptions = {
metricPrefix?: string
otlpHeaders?: string
otlpHeadersHelper?: string
otlpProxyUrl?: string
resourceAttributes?: string
spanAttributes?: string
traceparent?: string
Expand Down Expand Up @@ -155,6 +157,8 @@ export function loadConfig(options: OtelPluginOptions = {}): PluginConfig {
const resolvedOptions = typeof options === "object" && options !== null ? options : {}
const otlpHeaders = pickString(resolvedOptions.otlpHeaders) ?? process.env["OPENCODE_OTLP_HEADERS"]
const otlpHeadersHelper = pickString(resolvedOptions.otlpHeadersHelper) ?? process.env["OPENCODE_OTLP_HEADERS_HELPER"]
const otlpProxyUrl = pickString(resolvedOptions.otlpProxyUrl)
?? (hasNonEmptyEnv("OPENCODE_OTLP_PROXY_URL") ? process.env["OPENCODE_OTLP_PROXY_URL"] : undefined)
const resourceAttributes = pickString(resolvedOptions.resourceAttributes) ?? process.env["OPENCODE_RESOURCE_ATTRIBUTES"]
const spanAttributes = pickString(resolvedOptions.spanAttributes) ?? process.env["OPENCODE_SPAN_ATTRIBUTES"]
const traceparent = pickString(resolvedOptions.traceparent) ?? process.env["OPENCODE_TRACEPARENT"]
Expand Down Expand Up @@ -210,6 +214,7 @@ export function loadConfig(options: OtelPluginOptions = {}): PluginConfig {
metricPrefix: pickString(resolvedOptions.metricPrefix) ?? process.env["OPENCODE_METRIC_PREFIX"] ?? "opencode.",
otlpHeaders,
otlpHeadersHelper,
otlpProxyUrl,
resourceAttributes,
spanAttributes,
traceparent,
Expand Down
54 changes: 48 additions & 6 deletions src/otel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,34 @@ export function buildResource(version: string, resourceAttributes = process.env[
return resourceFromAttributes(attrs)
}

export function proxyBypassed(
endpoint: string,
noProxy: string | undefined = process.env["NO_PROXY"] ?? process.env["no_proxy"],
): boolean {
let hostname: string
let hostWithPort: string
try {
const url = new URL(endpoint)
hostname = url.hostname.toLowerCase()
const defaultPort = url.protocol === "https:" ? "443" : url.protocol === "http:" ? "80" : ""
const port = url.port || defaultPort
hostWithPort = port ? `${hostname}:${port}` : hostname
} catch {
return false
}
if (hostname === "localhost" || hostname === "::1" || hostname === "[::1]" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(hostname)) return true
if (!noProxy) return false
for (const entry of noProxy.split(",")) {
const pattern = entry.trim().toLowerCase()
if (!pattern) continue
if (pattern === "*") return true
const normalized = pattern.startsWith(".") ? pattern.slice(1) : pattern
if (hostWithPort === normalized || hostWithPort.endsWith("." + normalized)) return true
if (hostname === normalized || hostname.endsWith("." + normalized)) return true
}
return false
}

/** Handles returned by `setupOtel`, used for graceful shutdown. */
export type OtelProviders = {
meterProvider: MeterProvider
Expand Down Expand Up @@ -104,13 +132,27 @@ export async function setupOtel(
version: string,
otlpHeaders?: string,
otlpHeadersHelper?: string,
otlpProxyUrl?: string,
resourceAttributes?: string,
metricsTemporality?: MetricsTemporality,
): Promise<OtelProviders> {
const resource = buildResource(version, resourceAttributes ?? "")
const staticHeaders = parseOtlpHeaders(otlpHeaders)
const dynamicHeaders = new DynamicHeaders(staticHeaders, otlpHeadersHelper)
const temporalityPreference = metricTemporalityPreference(metricsTemporality)
const effectiveProxyUrl = otlpProxyUrl && !proxyBypassed(endpoint) ? otlpProxyUrl : undefined
const agentOptions = effectiveProxyUrl
? {
httpAgentOptions: ((protocol: string) => {
if (protocol === "http:") {
const { HttpProxyAgent } = require("http-proxy-agent") as typeof import("http-proxy-agent")
return new HttpProxyAgent(effectiveProxyUrl)
}
const { HttpsProxyAgent } = require("https-proxy-agent") as typeof import("https-proxy-agent")
return new HttpsProxyAgent(effectiveProxyUrl)
Comment thread
enternal111 marked this conversation as resolved.
Resolved
}) as import("@opentelemetry/otlp-exporter-base").OTLPExporterNodeConfigBase["httpAgentOptions"],
}
: {}
if (otlpHeadersHelper) {
try {
await dynamicHeaders.refresh()
Expand All @@ -119,19 +161,19 @@ export async function setupOtel(
}
}
const makeMetricExporter = (headers: HeadersMap) => withoutOtlpHeaderEnvironment(() => protocol === "http/protobuf"
? new OTLPProtoMetricExporter({ url: buildHttpSignalUrl(endpoint, "metrics"), headers, temporalityPreference })
? new OTLPProtoMetricExporter({ url: buildHttpSignalUrl(endpoint, "metrics"), headers, temporalityPreference, ...agentOptions })
: protocol === "http/json"
? new OTLPHttpMetricExporter({ url: buildHttpSignalUrl(endpoint, "metrics"), headers, temporalityPreference })
? new OTLPHttpMetricExporter({ url: buildHttpSignalUrl(endpoint, "metrics"), headers, temporalityPreference, ...agentOptions })
: new OTLPMetricExporter({ url: endpoint, metadata: createGrpcMetadata(headers), temporalityPreference }))
const makeLogExporter = (headers: HeadersMap) => withoutOtlpHeaderEnvironment(() => protocol === "http/protobuf"
? new OTLPProtoLogExporter({ url: buildHttpSignalUrl(endpoint, "logs"), headers })
? new OTLPProtoLogExporter({ url: buildHttpSignalUrl(endpoint, "logs"), headers, ...agentOptions })
: protocol === "http/json"
? new OTLPHttpLogExporter({ url: buildHttpSignalUrl(endpoint, "logs"), headers })
? new OTLPHttpLogExporter({ url: buildHttpSignalUrl(endpoint, "logs"), headers, ...agentOptions })
: new OTLPLogExporter({ url: endpoint, metadata: createGrpcMetadata(headers) }))
const makeTraceExporter = (headers: HeadersMap) => withoutOtlpHeaderEnvironment(() => protocol === "http/protobuf"
? new OTLPProtoTraceExporter({ url: buildHttpSignalUrl(endpoint, "traces"), headers })
? new OTLPProtoTraceExporter({ url: buildHttpSignalUrl(endpoint, "traces"), headers, ...agentOptions })
: protocol === "http/json"
? new OTLPHttpTraceExporter({ url: buildHttpSignalUrl(endpoint, "traces"), headers })
? new OTLPHttpTraceExporter({ url: buildHttpSignalUrl(endpoint, "traces"), headers, ...agentOptions })
: new OTLPTraceExporter({ url: endpoint, metadata: createGrpcMetadata(headers) }))
const metricExporter = otlpHeadersHelper
? new RefreshingMetricExporter(makeMetricExporter, dynamicHeaders)
Expand Down
7 changes: 5 additions & 2 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { ROOT_CONTEXT } from "@opentelemetry/api"
import pkg from "../package.json" with { type: "json" }
import { loadConfig, parseAttributePairs, resolveHelperPath, resolveLogLevel, type OtelPluginOptions } from "./config.ts"
import { probeEndpoint } from "./probe.ts"
import { forceFlushOtel } from "./otel.ts"
import { forceFlushOtel, proxyBypassed } from "./otel.ts"
import { remoteParentContext } from "./trace-context.ts"
import { acquireSharedOtel, acquireTracingState, createFlushScheduler, flushSharedOtel, releaseSharedOtel } from "./state.ts"
import { LEVELS, type HandlerContext, type Level, type OpenCodeContext, type OpenCodeEvent } from "./types.ts"
Expand Down Expand Up @@ -66,7 +66,10 @@ export async function setup(ctx: OpenCodeContext): Promise<() => Promise<void>>
headersHelperSet: !!config.otlpHeadersHelper,
})

const probe = await probeEndpoint(config.endpoint)
const probeTarget = config.otlpProxyUrl && config.protocol !== "grpc" && !proxyBypassed(config.endpoint)
? config.otlpProxyUrl
: config.endpoint
const probe = await probeEndpoint(probeTarget)
if (probe.ok) {
await log("info", "OTLP endpoint reachable", { endpoint: config.endpoint, ms: probe.ms })
} else {
Expand Down
1 change: 1 addition & 0 deletions src/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ export async function acquireSharedOtel(config: PluginConfig, version: string):
version,
config.otlpHeaders,
config.otlpHeadersHelper,
config.otlpProxyUrl,
config.resourceAttributes,
config.metricsTemporality,
)
Expand Down
Loading
Loading