Skip to content

Commit b4a9970

Browse files
authored
feat(cloudflare): instrument scheduled handler (#13114)
This PR adds instrumentation for the [`scheduled` handler](https://developers.cloudflare.com/workers/runtime-apis/handlers/scheduled/) in cloudflare workers. This is used for cron triggers. I elected to not do automatic cron instrumentation for now. Instead I added manual instrumentation docs to the README, this will get copied to the sentry docs eventually.
1 parent a7fbe01 commit b4a9970

File tree

8 files changed

+364
-76
lines changed

8 files changed

+364
-76
lines changed

Diff for: packages/cloudflare/README.md

+44-2
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
- [Official SDK Docs](https://docs.sentry.io/quickstart/)
1616
- [TypeDoc](http://getsentry.github.io/sentry-javascript/)
1717

18-
**Note: This SDK is unreleased. Please follow the
18+
**Note: This SDK is in an alpha state. Please follow the
1919
[tracking GH issue](https://github.com/getsentry/sentry-javascript/issues/12620) for updates.**
2020

2121
## Install
@@ -143,8 +143,50 @@ You can use the `instrumentD1WithSentry` method to instrument [Cloudflare D1](ht
143143
Cloudflare's serverless SQL database with Sentry.
144144

145145
```javascript
146+
import * as Sentry from '@sentry/cloudflare';
147+
146148
// env.DB is the D1 DB binding configured in your `wrangler.toml`
147-
const db = instrumentD1WithSentry(env.DB);
149+
const db = Sentry.instrumentD1WithSentry(env.DB);
148150
// Now you can use the database as usual
149151
await db.prepare('SELECT * FROM table WHERE id = ?').bind(1).run();
150152
```
153+
154+
## Cron Monitoring (Cloudflare Workers)
155+
156+
[Sentry Crons](https://docs.sentry.io/product/crons/) allows you to monitor the uptime and performance of any scheduled,
157+
recurring job in your application.
158+
159+
To instrument your cron triggers, use the `Sentry.withMonitor` API in your
160+
[`Scheduled` handler](https://developers.cloudflare.com/workers/runtime-apis/handlers/scheduled/).
161+
162+
```js
163+
export default {
164+
async scheduled(event, env, ctx) {
165+
ctx.waitUntil(
166+
Sentry.withMonitor('your-cron-name', () => {
167+
return doSomeTaskOnASchedule();
168+
}),
169+
);
170+
},
171+
};
172+
```
173+
174+
You can also use supply a monitor config to upsert cron monitors with additional metadata:
175+
176+
```js
177+
const monitorConfig = {
178+
schedule: {
179+
type: 'crontab',
180+
value: '* * * * *',
181+
},
182+
checkinMargin: 2, // In minutes. Optional.
183+
maxRuntime: 10, // In minutes. Optional.
184+
timezone: 'America/Los_Angeles', // Optional.
185+
};
186+
187+
export default {
188+
async scheduled(event, env, ctx) {
189+
Sentry.withMonitor('your-cron-name', () => doSomeTaskOnASchedule(), monitorConfig);
190+
},
191+
};
192+
```

Diff for: packages/cloudflare/package.json

+2-3
Original file line numberDiff line numberDiff line change
@@ -47,10 +47,9 @@
4747
"@cloudflare/workers-types": "^4.x"
4848
},
4949
"devDependencies": {
50-
"@cloudflare/workers-types": "^4.20240722.0",
50+
"@cloudflare/workers-types": "^4.20240725.0",
5151
"@types/node": "^14.18.0",
52-
"miniflare": "^3.20240718.0",
53-
"wrangler": "^3.65.1"
52+
"wrangler": "^3.67.1"
5453
},
5554
"scripts": {
5655
"build": "run-p build:transpile build:types",

Diff for: packages/cloudflare/src/handler.ts

+64-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,21 @@
1-
import type { ExportedHandler, ExportedHandlerFetchHandler } from '@cloudflare/workers-types';
2-
import type { Options } from '@sentry/types';
1+
import type {
2+
ExportedHandler,
3+
ExportedHandlerFetchHandler,
4+
ExportedHandlerScheduledHandler,
5+
} from '@cloudflare/workers-types';
6+
import {
7+
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
8+
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
9+
captureException,
10+
flush,
11+
startSpan,
12+
withIsolationScope,
13+
} from '@sentry/core';
314
import { setAsyncLocalStorageAsyncContextStrategy } from './async';
15+
import type { CloudflareOptions } from './client';
416
import { wrapRequestHandler } from './request';
17+
import { addCloudResourceContext } from './scope-utils';
18+
import { init } from './sdk';
519

620
/**
721
* Extract environment generic from exported handler.
@@ -21,7 +35,7 @@ type ExtractEnv<P> = P extends ExportedHandler<infer Env> ? Env : never;
2135
*/
2236
// eslint-disable-next-line @typescript-eslint/no-explicit-any
2337
export function withSentry<E extends ExportedHandler<any>>(
24-
optionsCallback: (env: ExtractEnv<E>) => Options,
38+
optionsCallback: (env: ExtractEnv<E>) => CloudflareOptions,
2539
handler: E,
2640
): E {
2741
setAsyncLocalStorageAsyncContextStrategy();
@@ -40,5 +54,52 @@ export function withSentry<E extends ExportedHandler<any>>(
4054
(handler.fetch as any).__SENTRY_INSTRUMENTED__ = true;
4155
}
4256

57+
if (
58+
'scheduled' in handler &&
59+
typeof handler.scheduled === 'function' &&
60+
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
61+
!(handler.scheduled as any).__SENTRY_INSTRUMENTED__
62+
) {
63+
handler.scheduled = new Proxy(handler.scheduled, {
64+
apply(target, thisArg, args: Parameters<ExportedHandlerScheduledHandler<ExtractEnv<E>>>) {
65+
const [event, env, context] = args;
66+
return withIsolationScope(isolationScope => {
67+
const options = optionsCallback(env);
68+
const client = init(options);
69+
isolationScope.setClient(client);
70+
71+
addCloudResourceContext(isolationScope);
72+
73+
return startSpan(
74+
{
75+
op: 'faas.cron',
76+
name: `Scheduled Cron ${event.cron}`,
77+
attributes: {
78+
'faas.cron': event.cron,
79+
'faas.time': new Date(event.scheduledTime).toISOString(),
80+
'faas.trigger': 'timer',
81+
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare',
82+
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'task',
83+
},
84+
},
85+
async () => {
86+
try {
87+
return await (target.apply(thisArg, args) as ReturnType<typeof target>);
88+
} catch (e) {
89+
captureException(e, { mechanism: { handled: false, type: 'cloudflare' } });
90+
throw e;
91+
} finally {
92+
context.waitUntil(flush(2000));
93+
}
94+
},
95+
);
96+
});
97+
},
98+
});
99+
100+
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
101+
(handler.scheduled as any).__SENTRY_INSTRUMENTED__ = true;
102+
}
103+
43104
return handler;
44105
}

Diff for: packages/cloudflare/src/request.ts

+3-27
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,10 @@ import {
1111
startSpan,
1212
withIsolationScope,
1313
} from '@sentry/core';
14-
import type { Scope, SpanAttributes } from '@sentry/types';
15-
import { stripUrlQueryAndFragment, winterCGRequestToRequestData } from '@sentry/utils';
14+
import type { SpanAttributes } from '@sentry/types';
15+
import { stripUrlQueryAndFragment } from '@sentry/utils';
1616
import type { CloudflareOptions } from './client';
17+
import { addCloudResourceContext, addCultureContext, addRequest } from './scope-utils';
1718
import { init } from './sdk';
1819

1920
interface RequestHandlerWrapperOptions {
@@ -96,28 +97,3 @@ export function wrapRequestHandler(
9697
);
9798
});
9899
}
99-
100-
/**
101-
* Set cloud resource context on scope.
102-
*/
103-
function addCloudResourceContext(scope: Scope): void {
104-
scope.setContext('cloud_resource', {
105-
'cloud.provider': 'cloudflare',
106-
});
107-
}
108-
109-
/**
110-
* Set culture context on scope
111-
*/
112-
function addCultureContext(scope: Scope, cf: IncomingRequestCfProperties): void {
113-
scope.setContext('culture', {
114-
timezone: cf.timezone,
115-
});
116-
}
117-
118-
/**
119-
* Set request data on scope
120-
*/
121-
function addRequest(scope: Scope, request: Request): void {
122-
scope.setSDKProcessingMetadata({ request: winterCGRequestToRequestData(request) });
123-
}

Diff for: packages/cloudflare/src/scope-utils.ts

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import type { IncomingRequestCfProperties } from '@cloudflare/workers-types';
2+
3+
import type { Scope } from '@sentry/types';
4+
import { winterCGRequestToRequestData } from '@sentry/utils';
5+
6+
/**
7+
* Set cloud resource context on scope.
8+
*/
9+
export function addCloudResourceContext(scope: Scope): void {
10+
scope.setContext('cloud_resource', {
11+
'cloud.provider': 'cloudflare',
12+
});
13+
}
14+
15+
/**
16+
* Set culture context on scope
17+
*/
18+
export function addCultureContext(scope: Scope, cf: IncomingRequestCfProperties): void {
19+
scope.setContext('culture', {
20+
timezone: cf.timezone,
21+
});
22+
}
23+
24+
/**
25+
* Set request data on scope
26+
*/
27+
export function addRequest(scope: Scope, request: Request): void {
28+
scope.setSDKProcessingMetadata({ request: winterCGRequestToRequestData(request) });
29+
}

Diff for: packages/cloudflare/src/sdk.ts

+4-4
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,17 @@ import {
77
linkedErrorsIntegration,
88
requestDataIntegration,
99
} from '@sentry/core';
10-
import type { Integration, Options } from '@sentry/types';
10+
import type { Integration } from '@sentry/types';
1111
import { stackParserFromStackParserOptions } from '@sentry/utils';
12-
import type { CloudflareClientOptions } from './client';
12+
import type { CloudflareClientOptions, CloudflareOptions } from './client';
1313
import { CloudflareClient } from './client';
1414

1515
import { fetchIntegration } from './integrations/fetch';
1616
import { makeCloudflareTransport } from './transport';
1717
import { defaultStackParser } from './vendor/stacktrace';
1818

1919
/** Get the default integrations for the Cloudflare SDK. */
20-
export function getDefaultIntegrations(options: Options): Integration[] {
20+
export function getDefaultIntegrations(options: CloudflareOptions): Integration[] {
2121
const sendDefaultPii = options.sendDefaultPii ?? false;
2222
return [
2323
dedupeIntegration(),
@@ -32,7 +32,7 @@ export function getDefaultIntegrations(options: Options): Integration[] {
3232
/**
3333
* Initializes the cloudflare SDK.
3434
*/
35-
export function init(options: Options): CloudflareClient | undefined {
35+
export function init(options: CloudflareOptions): CloudflareClient | undefined {
3636
if (options.defaultIntegrations === undefined) {
3737
options.defaultIntegrations = getDefaultIntegrations(options);
3838
}

0 commit comments

Comments
 (0)