|
| 1 | +import type { |
| 2 | + ExportedHandler, |
| 3 | + ExportedHandlerFetchHandler, |
| 4 | + IncomingRequestCfProperties, |
| 5 | +} from '@cloudflare/workers-types'; |
| 6 | +import { |
| 7 | + SEMANTIC_ATTRIBUTE_SENTRY_OP, |
| 8 | + SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, |
| 9 | + SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, |
| 10 | + captureException, |
| 11 | + continueTrace, |
| 12 | + flush, |
| 13 | + setHttpStatus, |
| 14 | + startSpan, |
| 15 | + withIsolationScope, |
| 16 | +} from '@sentry/core'; |
| 17 | +import type { Options, Scope, SpanAttributes } from '@sentry/types'; |
| 18 | +import { stripUrlQueryAndFragment, winterCGRequestToRequestData } from '@sentry/utils'; |
| 19 | +import { setAsyncLocalStorageAsyncContextStrategy } from './async'; |
| 20 | +import { init } from './sdk'; |
| 21 | + |
| 22 | +/** |
| 23 | + * Extract environment generic from exported handler. |
| 24 | + */ |
| 25 | +type ExtractEnv<P> = P extends ExportedHandler<infer Env> ? Env : never; |
| 26 | + |
| 27 | +/** |
| 28 | + * Wrapper for Cloudflare handlers. |
| 29 | + * |
| 30 | + * Initializes the SDK and wraps the handler with Sentry instrumentation. |
| 31 | + * |
| 32 | + * Automatically instruments the `fetch` method of the handler. |
| 33 | + * |
| 34 | + * @param optionsCallback Function that returns the options for the SDK initialization. |
| 35 | + * @param handler {ExportedHandler} The handler to wrap. |
| 36 | + * @returns The wrapped handler. |
| 37 | + */ |
| 38 | +// eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 39 | +export function withSentry<E extends ExportedHandler<any>>( |
| 40 | + optionsCallback: (env: ExtractEnv<E>) => Options, |
| 41 | + handler: E, |
| 42 | +): E { |
| 43 | + setAsyncLocalStorageAsyncContextStrategy(); |
| 44 | + |
| 45 | + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any |
| 46 | + if ('fetch' in handler && typeof handler.fetch === 'function' && !(handler.fetch as any).__SENTRY_INSTRUMENTED__) { |
| 47 | + handler.fetch = new Proxy(handler.fetch, { |
| 48 | + apply(target, thisArg, args: Parameters<ExportedHandlerFetchHandler<ExtractEnv<E>>>) { |
| 49 | + const [request, env, context] = args; |
| 50 | + return withIsolationScope(isolationScope => { |
| 51 | + const options = optionsCallback(env); |
| 52 | + const client = init(options); |
| 53 | + isolationScope.setClient(client); |
| 54 | + |
| 55 | + const attributes: SpanAttributes = { |
| 56 | + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.cloudflare-worker', |
| 57 | + [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url', |
| 58 | + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.server', |
| 59 | + ['http.request.method']: request.method, |
| 60 | + ['url.full']: request.url, |
| 61 | + }; |
| 62 | + |
| 63 | + const contentLength = request.headers.get('content-length'); |
| 64 | + if (contentLength) { |
| 65 | + attributes['http.request.body.size'] = parseInt(contentLength, 10); |
| 66 | + } |
| 67 | + |
| 68 | + let pathname = ''; |
| 69 | + try { |
| 70 | + const url = new URL(request.url); |
| 71 | + pathname = url.pathname; |
| 72 | + attributes['server.address'] = url.hostname; |
| 73 | + attributes['url.scheme'] = url.protocol.replace(':', ''); |
| 74 | + } catch { |
| 75 | + // skip |
| 76 | + } |
| 77 | + |
| 78 | + addRequest(isolationScope, request); |
| 79 | + addCloudResourceContext(isolationScope); |
| 80 | + if (request.cf) { |
| 81 | + addCultureContext(isolationScope, request.cf); |
| 82 | + attributes['network.protocol.name'] = request.cf.httpProtocol; |
| 83 | + } |
| 84 | + |
| 85 | + const routeName = `${request.method} ${pathname ? stripUrlQueryAndFragment(pathname) : '/'}`; |
| 86 | + |
| 87 | + return continueTrace( |
| 88 | + { sentryTrace: request.headers.get('sentry-trace') || '', baggage: request.headers.get('baggage') }, |
| 89 | + () => { |
| 90 | + // Note: This span will not have a duration unless I/O happens in the handler. This is |
| 91 | + // because of how the cloudflare workers runtime works. |
| 92 | + // See: https://developers.cloudflare.com/workers/runtime-apis/performance/ |
| 93 | + return startSpan( |
| 94 | + { |
| 95 | + name: routeName, |
| 96 | + attributes, |
| 97 | + }, |
| 98 | + async span => { |
| 99 | + try { |
| 100 | + const res = await (target.apply(thisArg, args) as ReturnType<typeof target>); |
| 101 | + setHttpStatus(span, res.status); |
| 102 | + return res; |
| 103 | + } catch (e) { |
| 104 | + captureException(e, { mechanism: { handled: false, type: 'cloudflare' } }); |
| 105 | + throw e; |
| 106 | + } finally { |
| 107 | + context.waitUntil(flush(2000)); |
| 108 | + } |
| 109 | + }, |
| 110 | + ); |
| 111 | + }, |
| 112 | + ); |
| 113 | + }); |
| 114 | + }, |
| 115 | + }); |
| 116 | + |
| 117 | + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any |
| 118 | + (handler.fetch as any).__SENTRY_INSTRUMENTED__ = true; |
| 119 | + } |
| 120 | + |
| 121 | + return handler; |
| 122 | +} |
| 123 | + |
| 124 | +function addCloudResourceContext(isolationScope: Scope): void { |
| 125 | + isolationScope.setContext('cloud_resource', { |
| 126 | + 'cloud.provider': 'cloudflare', |
| 127 | + }); |
| 128 | +} |
| 129 | + |
| 130 | +function addCultureContext(isolationScope: Scope, cf: IncomingRequestCfProperties): void { |
| 131 | + isolationScope.setContext('culture', { |
| 132 | + timezone: cf.timezone, |
| 133 | + }); |
| 134 | +} |
| 135 | + |
| 136 | +function addRequest(isolationScope: Scope, request: Request): void { |
| 137 | + isolationScope.setSDKProcessingMetadata({ request: winterCGRequestToRequestData(request) }); |
| 138 | +} |
0 commit comments