-
Notifications
You must be signed in to change notification settings - Fork 676
feat(js): add open telementry fetch provider #4820
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,127 @@ | ||||||||||||||||||||||||||
| /** | ||||||||||||||||||||||||||
| * Copyright 2024 Google LLC | ||||||||||||||||||||||||||
| * | ||||||||||||||||||||||||||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||||||||||||||||||||||||||
| * you may not use this file except in compliance with the License. | ||||||||||||||||||||||||||
| * You may obtain a copy of the License at | ||||||||||||||||||||||||||
| * | ||||||||||||||||||||||||||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||||||||||||||||||||||||||
| * | ||||||||||||||||||||||||||
| * Unless required by applicable law or agreed to in writing, software | ||||||||||||||||||||||||||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||||||||||||||||||||||||||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||||||||||||||||||||||||||
| * See the License for the specific language governing permissions and | ||||||||||||||||||||||||||
| * limitations under the License. | ||||||||||||||||||||||||||
| */ | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| import { context, trace } from '@opentelemetry/api'; | ||||||||||||||||||||||||||
| import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks'; | ||||||||||||||||||||||||||
| import { | ||||||||||||||||||||||||||
| BasicTracerProvider, | ||||||||||||||||||||||||||
| BatchSpanProcessor, | ||||||||||||||||||||||||||
| SimpleSpanProcessor, | ||||||||||||||||||||||||||
| type SpanProcessor, | ||||||||||||||||||||||||||
| } from '@opentelemetry/sdk-trace-base'; | ||||||||||||||||||||||||||
| import type { TelemetryConfig } from '../telemetryTypes.js'; | ||||||||||||||||||||||||||
| import type { TelemetryProvider } from '../tracing.js'; | ||||||||||||||||||||||||||
| import { TraceServerExporter, setTelemetryServerUrl } from './exporter.js'; | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| /** | ||||||||||||||||||||||||||
| * Options for the fetch-compatible telemetry provider. | ||||||||||||||||||||||||||
| * Uses only fetch and standard APIs (no Node.js SDK), suitable for workers. | ||||||||||||||||||||||||||
| */ | ||||||||||||||||||||||||||
| export interface FetchTelemetryProviderOptions { | ||||||||||||||||||||||||||
| /** | ||||||||||||||||||||||||||
| * URL of the Genkit telemetry server (e.g. from dev UI or your own collector). | ||||||||||||||||||||||||||
| * If not set, GENKIT_TELEMETRY_SERVER env var is used when enableTelemetry runs. | ||||||||||||||||||||||||||
| */ | ||||||||||||||||||||||||||
| serverUrl?: string; | ||||||||||||||||||||||||||
| /** | ||||||||||||||||||||||||||
| * If true, use SimpleSpanProcessor for more real-time export (e.g. in dev). | ||||||||||||||||||||||||||
| * Default: false (BatchSpanProcessor for production). | ||||||||||||||||||||||||||
| */ | ||||||||||||||||||||||||||
| realtime?: boolean; | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| /** | ||||||||||||||||||||||||||
| * Telemetry provider that uses only fetch-compatible APIs. | ||||||||||||||||||||||||||
| * Use this in worker environments (Cloudflare Workers, Vercel Edge, etc.) where | ||||||||||||||||||||||||||
| * the Node.js OpenTelemetry SDK is not available. | ||||||||||||||||||||||||||
| * | ||||||||||||||||||||||||||
| * When the runtime has AsyncLocalStorage (e.g. Cloudflare Workers with `nodejs_compat`), | ||||||||||||||||||||||||||
| * OTel context propagation is enabled so parent-child span links are preserved across | ||||||||||||||||||||||||||
| * async boundaries and traces are fully hierarchical. | ||||||||||||||||||||||||||
| * | ||||||||||||||||||||||||||
| * Set via runtime config before any other genkit imports: | ||||||||||||||||||||||||||
| * | ||||||||||||||||||||||||||
| * @example | ||||||||||||||||||||||||||
| * ```ts | ||||||||||||||||||||||||||
| * import { setGenkitRuntimeConfig } from 'genkit'; | ||||||||||||||||||||||||||
| * import { FetchTelemetryProvider } from 'genkit/tracing'; | ||||||||||||||||||||||||||
| * | ||||||||||||||||||||||||||
| * setGenkitRuntimeConfig({ | ||||||||||||||||||||||||||
| * jsonSchemaMode: 'interpret', | ||||||||||||||||||||||||||
| * sandboxedRuntime: true, | ||||||||||||||||||||||||||
| * telemetry: new FetchTelemetryProvider({ | ||||||||||||||||||||||||||
| * serverUrl: 'https://your-telemetry-server.example.com', | ||||||||||||||||||||||||||
| * }), | ||||||||||||||||||||||||||
| * }); | ||||||||||||||||||||||||||
| * | ||||||||||||||||||||||||||
| * // Then import flows/actions | ||||||||||||||||||||||||||
| * import { flow, run } from 'genkit'; | ||||||||||||||||||||||||||
| * ``` | ||||||||||||||||||||||||||
| */ | ||||||||||||||||||||||||||
| export class FetchTelemetryProvider implements TelemetryProvider { | ||||||||||||||||||||||||||
| private readonly options: FetchTelemetryProviderOptions; | ||||||||||||||||||||||||||
| private spanProcessors: SpanProcessor[] = []; | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| constructor(options: FetchTelemetryProviderOptions = {}) { | ||||||||||||||||||||||||||
| this.options = options; | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| async enableTelemetry( | ||||||||||||||||||||||||||
| telemetryConfig: TelemetryConfig | Promise<TelemetryConfig> | ||||||||||||||||||||||||||
| ): Promise<void> { | ||||||||||||||||||||||||||
| const config = | ||||||||||||||||||||||||||
| telemetryConfig instanceof Promise | ||||||||||||||||||||||||||
| ? await telemetryConfig | ||||||||||||||||||||||||||
| : telemetryConfig; | ||||||||||||||||||||||||||
| const serverUrl = | ||||||||||||||||||||||||||
| this.options.serverUrl ?? | ||||||||||||||||||||||||||
| (typeof process !== 'undefined' && process.env?.GENKIT_TELEMETRY_SERVER); | ||||||||||||||||||||||||||
| if (typeof serverUrl === 'string') { | ||||||||||||||||||||||||||
| setTelemetryServerUrl(serverUrl); | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
|
Comment on lines
+89
to
+94
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The logic to determine
Suggested change
|
||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| const exporter = new TraceServerExporter(); | ||||||||||||||||||||||||||
| const processor: SpanProcessor = this.options.realtime | ||||||||||||||||||||||||||
| ? new SimpleSpanProcessor(exporter) | ||||||||||||||||||||||||||
| : new BatchSpanProcessor(exporter); | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| this.spanProcessors = [processor]; | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| if (config?.spanProcessors?.length) { | ||||||||||||||||||||||||||
| this.spanProcessors.push(...config.spanProcessors); | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| // When AsyncLocalStorage is available (e.g. Node, Cloudflare Workers with nodejs_compat), | ||||||||||||||||||||||||||
| // enable OTel context propagation so parent-child span links work across await. | ||||||||||||||||||||||||||
| try { | ||||||||||||||||||||||||||
| const contextManager = new AsyncLocalStorageContextManager(); | ||||||||||||||||||||||||||
| contextManager.enable(); | ||||||||||||||||||||||||||
| context.setGlobalContextManager(contextManager); | ||||||||||||||||||||||||||
| } catch { | ||||||||||||||||||||||||||
| // No async_hooks / AsyncLocalStorage (e.g. some edge runtimes); spans still work, hierarchy may be flat. | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| const provider = new BasicTracerProvider(); | ||||||||||||||||||||||||||
| for (const p of this.spanProcessors) { | ||||||||||||||||||||||||||
| provider.addSpanProcessor(p); | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
| trace.setGlobalTracerProvider(provider); | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| async flushTracing(): Promise<void> { | ||||||||||||||||||||||||||
| await Promise.all(this.spanProcessors.map((p) => p.forceFlush())); | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,103 @@ | ||
| /** | ||
| * Copyright 2024 Google LLC | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| * | ||
| * Run just this file: | ||
| * npm test -- --test-name-pattern FetchTelemetryProvider | ||
| * Or from repo js/core: | ||
| * node --import tsx --test tests/fetch_telemetry_provider_test.ts | ||
| * | ||
| * Manual test with dev UI: set GENKIT_TELEMETRY_SERVER to your telemetry server URL | ||
| * (e.g. from `genkit start`), use FetchTelemetryProvider in your app, run a flow, | ||
| * then open the dev UI and confirm the trace appears. | ||
| */ | ||
|
|
||
| import { trace } from '@opentelemetry/api'; | ||
| import * as assert from 'node:assert'; | ||
| import { afterEach, beforeEach, describe, it } from 'node:test'; | ||
| import { FetchTelemetryProvider } from '../src/tracing/fetch-telemetry-provider.js'; | ||
| import { sleep } from './utils.js'; | ||
|
|
||
| describe('FetchTelemetryProvider', () => { | ||
| const capturedRequests: { url: string; body: unknown }[] = []; | ||
| let originalFetch: typeof globalThis.fetch; | ||
|
|
||
| beforeEach(() => { | ||
| capturedRequests.length = 0; | ||
| originalFetch = globalThis.fetch; | ||
| globalThis.fetch = async ( | ||
| url: string | URL | Request, | ||
| init?: RequestInit | ||
| ) => { | ||
| const req = url instanceof Request ? url : new Request(url, init); | ||
| const urlStr = req.url; | ||
| if (urlStr.includes('/api/traces')) { | ||
| const body = | ||
| req.method === 'POST' && req.body | ||
| ? JSON.parse(await req.text()) | ||
| : undefined; | ||
| capturedRequests.push({ url: urlStr, body }); | ||
| return new Response('OK', { status: 200 }); | ||
| } | ||
| return originalFetch(url, init); | ||
| }; | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| globalThis.fetch = originalFetch; | ||
| }); | ||
|
|
||
| it('enables telemetry and exports spans via fetch when serverUrl is set', async () => { | ||
| const serverUrl = 'http://telemetry.test'; | ||
| const provider = new FetchTelemetryProvider({ | ||
| serverUrl, | ||
| realtime: true, // SimpleSpanProcessor so export happens on span end | ||
| }); | ||
|
|
||
| await provider.enableTelemetry({}); | ||
|
|
||
| const tracer = trace.getTracer('test', '1.0'); | ||
| tracer.startActiveSpan('testSpan', {}, (span) => { | ||
| span.end(); | ||
| }); | ||
|
|
||
| await provider.flushTracing(); | ||
| // Export is async (fire-and-forget from processor); poll for the request. | ||
| for (let i = 0; i < 50; i++) { | ||
| if (capturedRequests.length >= 1) break; | ||
| await sleep(20); | ||
| } | ||
| assert.ok( | ||
| capturedRequests.length >= 1, | ||
| `expected at least 1 request to /api/traces, got ${capturedRequests.length}` | ||
| ); | ||
| const last = capturedRequests[capturedRequests.length - 1]; | ||
| assert.ok( | ||
| last.url.startsWith(serverUrl), | ||
| `url should start with serverUrl: ${last.url}` | ||
| ); | ||
| assert.ok( | ||
| last.url.endsWith('/api/traces'), | ||
| `url should end with /api/traces: ${last.url}` | ||
| ); | ||
| assert.strictEqual(typeof (last.body as any)?.traceId, 'string'); | ||
| assert.ok(typeof (last.body as any)?.spans === 'object'); | ||
| }); | ||
|
|
||
| it('enableTelemetry does not throw when serverUrl is omitted', async () => { | ||
| const provider = new FetchTelemetryProvider({}); | ||
| await assert.doesNotReject(provider.enableTelemetry({})); | ||
| await assert.doesNotReject(provider.flushTracing()); | ||
| }); | ||
| }); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There's a potential robustness issue here. If
telemetryProviderInitializer()is called but fails to setglobal[telemetryProviderKey](e.g., due to an internal error), this function will returnundefined, likely causing aTypeErrorin the calling code. It's safer to re-check for the provider after the initializer runs and fall through to the error if it's still not present.