Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 1.8k
feat(cloudflare): Add cloudflare sdk scaffolding#12953
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
Uh oh!
There was an error while loading. Please reload this page.
Changes from all commits
File filter
Filter by extension
Conversations
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| import { getDefaultCurrentScope, getDefaultIsolationScope, setAsyncContextStrategy } from '@sentry/core'; | ||
| import type { Scope } from '@sentry/types'; | ||
| // Need to use node: prefix for cloudflare workers compatibility | ||
| // Note: Because we are using node:async_hooks, we need to set `node_compat` in the wrangler.toml | ||
| import { AsyncLocalStorage } from 'node:async_hooks'; | ||
| /** | ||
| * Sets the async context strategy to use AsyncLocalStorage. | ||
| * | ||
| * AsyncLocalStorage is only avalaible in the cloudflare workers runtime if you set | ||
| * compatibility_flags = ["nodejs_compat"] or compatibility_flags = ["nodejs_als"] | ||
| */ | ||
| export function setAsyncLocalStorageAsyncContextStrategy(): void { | ||
| const asyncStorage = new AsyncLocalStorage<{ | ||
| scope: Scope; | ||
| isolationScope: Scope; | ||
| }>(); | ||
| function getScopes(): { scope: Scope; isolationScope: Scope } { | ||
| const scopes = asyncStorage.getStore(); | ||
| if (scopes) { | ||
| return scopes; | ||
| } | ||
| // fallback behavior: | ||
| // if, for whatever reason, we can't find scopes on the context here, we have to fix this somehow | ||
| return { | ||
| scope: getDefaultCurrentScope(), | ||
| isolationScope: getDefaultIsolationScope(), | ||
| }; | ||
| } | ||
| function withScope<T>(callback: (scope: Scope) => T): T { | ||
| const scope = getScopes().scope.clone(); | ||
| const isolationScope = getScopes().isolationScope; | ||
| return asyncStorage.run({ scope, isolationScope }, () => { | ||
| return callback(scope); | ||
| }); | ||
| } | ||
| function withSetScope<T>(scope: Scope, callback: (scope: Scope) => T): T { | ||
| const isolationScope = getScopes().isolationScope.clone(); | ||
| return asyncStorage.run({ scope, isolationScope }, () => { | ||
| return callback(scope); | ||
| }); | ||
| } | ||
| function withIsolationScope<T>(callback: (isolationScope: Scope) => T): T { | ||
| const scope = getScopes().scope; | ||
| const isolationScope = getScopes().isolationScope.clone(); | ||
| return asyncStorage.run({ scope, isolationScope }, () => { | ||
| return callback(isolationScope); | ||
| }); | ||
| } | ||
| function withSetIsolationScope<T>(isolationScope: Scope, callback: (isolationScope: Scope) => T): T { | ||
| const scope = getScopes().scope; | ||
| return asyncStorage.run({ scope, isolationScope }, () => { | ||
| return callback(isolationScope); | ||
| }); | ||
| } | ||
| setAsyncContextStrategy({ | ||
| withScope, | ||
| withSetScope, | ||
| withIsolationScope, | ||
| withSetIsolationScope, | ||
| getCurrentScope: () => getScopes().scope, | ||
| getIsolationScope: () => getScopes().isolationScope, | ||
| }); | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| import type { ServerRuntimeClientOptions } from '@sentry/core'; | ||
| import { ServerRuntimeClient, applySdkMetadata } from '@sentry/core'; | ||
| import type { ClientOptions, Options } from '@sentry/types'; | ||
| import type { CloudflareTransportOptions } from './transport'; | ||
| /** | ||
| * The Sentry Cloudflare SDK Client. | ||
| * | ||
| * @see CloudflareClientOptions for documentation on configuration options. | ||
| * @see ServerRuntimeClient for usage documentation. | ||
| */ | ||
| export class CloudflareClient extends ServerRuntimeClient<CloudflareClientOptions> { | ||
| /** | ||
| * Creates a new Cloudflare SDK instance. | ||
| * @param options Configuration options for this SDK. | ||
| */ | ||
| public constructor(options: CloudflareClientOptions) { | ||
| applySdkMetadata(options, 'options'); | ||
| options._metadata = options._metadata || {}; | ||
| const clientOptions: ServerRuntimeClientOptions = { | ||
| ...options, | ||
| platform: 'javascript', | ||
| // TODO: Grab version information | ||
| runtime: { name: 'cloudflare' }, | ||
| // TODO: Add server name | ||
| }; | ||
| super(clientOptions); | ||
| } | ||
| } | ||
| // eslint-disable-next-line @typescript-eslint/no-empty-interface | ||
| interface BaseCloudflareOptions {} | ||
| /** | ||
| * Configuration options for the Sentry Cloudflare SDK | ||
| * | ||
| * @see @sentry/types Options for more information. | ||
| */ | ||
| export interface CloudflareOptions extends Options<CloudflareTransportOptions>, BaseCloudflareOptions {} | ||
| /** | ||
| * Configuration options for the Sentry Cloudflare SDK Client class | ||
| * | ||
| * @see CloudflareClient for more information. | ||
| */ | ||
| export interface CloudflareClientOptions extends ClientOptions<CloudflareTransportOptions>, BaseCloudflareOptions {} |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,90 @@ | ||
| export {}; | ||
| export type { | ||
| Breadcrumb, | ||
| BreadcrumbHint, | ||
| PolymorphicRequest, | ||
| Request, | ||
| SdkInfo, | ||
| Event, | ||
| EventHint, | ||
| ErrorEvent, | ||
| Exception, | ||
| Session, | ||
| SeverityLevel, | ||
| Span, | ||
| StackFrame, | ||
| Stacktrace, | ||
| Thread, | ||
| User, | ||
| } from '@sentry/types'; | ||
| export type { AddRequestDataToEventOptions } from '@sentry/utils'; | ||
| export type { CloudflareOptions } from './client'; | ||
| export { | ||
| addEventProcessor, | ||
| addBreadcrumb, | ||
| addIntegration, | ||
| captureException, | ||
| captureEvent, | ||
| captureMessage, | ||
| captureFeedback, | ||
| close, | ||
| createTransport, | ||
| lastEventId, | ||
| flush, | ||
| getClient, | ||
| isInitialized, | ||
| getCurrentScope, | ||
| getGlobalScope, | ||
| getIsolationScope, | ||
| setCurrentClient, | ||
| Scope, | ||
| SDK_VERSION, | ||
| setContext, | ||
| setExtra, | ||
| setExtras, | ||
| setTag, | ||
| setTags, | ||
| setUser, | ||
| getSpanStatusFromHttpCode, | ||
| setHttpStatus, | ||
| withScope, | ||
| withIsolationScope, | ||
| captureCheckIn, | ||
| withMonitor, | ||
| setMeasurement, | ||
| getActiveSpan, | ||
| getRootSpan, | ||
| startSpan, | ||
| startInactiveSpan, | ||
| startSpanManual, | ||
| startNewTrace, | ||
| withActiveSpan, | ||
| getSpanDescendants, | ||
| continueTrace, | ||
| metrics, | ||
| functionToStringIntegration, | ||
| inboundFiltersIntegration, | ||
| linkedErrorsIntegration, | ||
| requestDataIntegration, | ||
| extraErrorDataIntegration, | ||
| debugIntegration, | ||
| dedupeIntegration, | ||
| rewriteFramesIntegration, | ||
| captureConsoleIntegration, | ||
| moduleMetadataIntegration, | ||
| zodErrorsIntegration, | ||
| SEMANTIC_ATTRIBUTE_SENTRY_OP, | ||
| SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, | ||
| SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, | ||
| SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, | ||
| trpcMiddleware, | ||
| spanToJSON, | ||
| spanToTraceHeader, | ||
| spanToBaggageHeader, | ||
| } from '@sentry/core'; | ||
| export { CloudflareClient } from './client'; | ||
| export { getDefaultIntegrations } from './sdk'; | ||
| export { fetchIntegration } from './integrations/fetch'; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,162 @@ | ||
| import { addBreadcrumb, defineIntegration, getClient, instrumentFetchRequest, isSentryRequestUrl } from '@sentry/core'; | ||
| import type { | ||
| Client, | ||
| FetchBreadcrumbData, | ||
| FetchBreadcrumbHint, | ||
| HandlerDataFetch, | ||
| IntegrationFn, | ||
| Span, | ||
| } from '@sentry/types'; | ||
| import { LRUMap, addFetchInstrumentationHandler, stringMatchesSomePattern } from '@sentry/utils'; | ||
| const INTEGRATION_NAME = 'Fetch'; | ||
| const HAS_CLIENT_MAP = new WeakMap<Client, boolean>(); | ||
| export interface Options { | ||
| /** | ||
| * Whether breadcrumbs should be recorded for requests | ||
| * Defaults to true | ||
| */ | ||
| breadcrumbs: boolean; | ||
| /** | ||
| * Function determining whether or not to create spans to track outgoing requests to the given URL. | ||
| * By default, spans will be created for all outgoing requests. | ||
| */ | ||
| shouldCreateSpanForRequest?: (url: string) => boolean; | ||
| } | ||
| const _fetchIntegration = ((options: Partial<Options> = {}) => { | ||
| const breadcrumbs = options.breadcrumbs === undefined ? true : options.breadcrumbs; | ||
| const shouldCreateSpanForRequest = options.shouldCreateSpanForRequest; | ||
| const _createSpanUrlMap = new LRUMap<string, boolean>(100); | ||
| const _headersUrlMap = new LRUMap<string, boolean>(100); | ||
| const spans: Record<string, Span> = {}; | ||
| /** Decides whether to attach trace data to the outgoing fetch request */ | ||
| function _shouldAttachTraceData(url: string): boolean { | ||
| const client = getClient(); | ||
| if (!client) { | ||
| return false; | ||
| } | ||
| const clientOptions = client.getOptions(); | ||
| if (clientOptions.tracePropagationTargets === undefined) { | ||
| return true; | ||
| } | ||
| const cachedDecision = _headersUrlMap.get(url); | ||
| if (cachedDecision !== undefined) { | ||
| return cachedDecision; | ||
| } | ||
Comment on lines
+53
to
+56
Member 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. l: could extract the cache decision logic into a helper function and reuse it in ContributorAuthor 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. Will do this in a follow-up PR | ||
| const decision = stringMatchesSomePattern(url, clientOptions.tracePropagationTargets); | ||
| _headersUrlMap.set(url, decision); | ||
| return decision; | ||
| } | ||
| /** Helper that wraps shouldCreateSpanForRequest option */ | ||
| function _shouldCreateSpan(url: string): boolean { | ||
| if (shouldCreateSpanForRequest === undefined) { | ||
| return true; | ||
| } | ||
| const cachedDecision = _createSpanUrlMap.get(url); | ||
| if (cachedDecision !== undefined) { | ||
| return cachedDecision; | ||
| } | ||
| const decision = shouldCreateSpanForRequest(url); | ||
| _createSpanUrlMap.set(url, decision); | ||
| return decision; | ||
| } | ||
| return { | ||
| name: INTEGRATION_NAME, | ||
| setupOnce() { | ||
| addFetchInstrumentationHandler(handlerData => { | ||
| const client = getClient(); | ||
| if (!client || !HAS_CLIENT_MAP.get(client)) { | ||
| return; | ||
| } | ||
| if (isSentryRequestUrl(handlerData.fetchData.url, client)) { | ||
| return; | ||
| } | ||
| instrumentFetchRequest( | ||
| handlerData, | ||
| _shouldCreateSpan, | ||
| _shouldAttachTraceData, | ||
| spans, | ||
| 'auto.http.wintercg_fetch', | ||
| ); | ||
| if (breadcrumbs) { | ||
| createBreadcrumb(handlerData); | ||
| } | ||
| }); | ||
| }, | ||
| setup(client) { | ||
| HAS_CLIENT_MAP.set(client, true); | ||
| }, | ||
| }; | ||
| }) satisfies IntegrationFn; | ||
| /** | ||
| * Creates spans and attaches tracing headers to fetch requests. | ||
| */ | ||
| export const fetchIntegration = defineIntegration(_fetchIntegration); | ||
| function createBreadcrumb(handlerData: HandlerDataFetch): void { | ||
| const { startTimestamp, endTimestamp } = handlerData; | ||
| // We only capture complete fetch requests | ||
| if (!endTimestamp) { | ||
| return; | ||
| } | ||
| if (handlerData.error) { | ||
| const data = handlerData.fetchData; | ||
| const hint: FetchBreadcrumbHint = { | ||
| data: handlerData.error, | ||
| input: handlerData.args, | ||
| startTimestamp, | ||
| endTimestamp, | ||
| }; | ||
| addBreadcrumb( | ||
| { | ||
| category: 'fetch', | ||
| data, | ||
| level: 'error', | ||
| type: 'http', | ||
| }, | ||
| hint, | ||
| ); | ||
| } else { | ||
| const data: FetchBreadcrumbData = { | ||
| ...handlerData.fetchData, | ||
| status_code: handlerData.response && handlerData.response.status, | ||
| }; | ||
| const hint: FetchBreadcrumbHint = { | ||
| input: handlerData.args, | ||
| response: handlerData.response, | ||
| startTimestamp, | ||
| endTimestamp, | ||
| }; | ||
| addBreadcrumb( | ||
| { | ||
| category: 'fetch', | ||
| data, | ||
| type: 'http', | ||
| }, | ||
| hint, | ||
| ); | ||
| } | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.
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.
Just to understand it better, how did you come up with cache size 100?
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.
This was arbitrary, it matches the implementation for
vercel-edgefetch integration. We can always adjust this in the future.