-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
feat(cloudflare): Instrument Cloudflare rate limiter bindings #22035
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
Open
PeterWadie
wants to merge
2
commits into
getsentry:develop
Choose a base branch
from
PeterWadie:feat/cloudflare-rate-limit-instrumentation
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+307
−3
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
26 changes: 26 additions & 0 deletions
26
dev-packages/cloudflare-integration-tests/suites/ratelimit/index.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| import type { RateLimit } from '@cloudflare/workers-types'; | ||
| import * as Sentry from '@sentry/cloudflare'; | ||
|
|
||
| interface Env { | ||
| SENTRY_DSN: string; | ||
| MY_RATE_LIMITER: RateLimit; | ||
| } | ||
|
|
||
| export default Sentry.withSentry( | ||
| (env: Env) => ({ | ||
| dsn: env.SENTRY_DSN, | ||
| tracesSampleRate: 1, | ||
| }), | ||
| { | ||
| async fetch(request, env) { | ||
| const url = new URL(request.url); | ||
|
|
||
| if (url.pathname === '/ratelimit/limit') { | ||
| const outcome = await env.MY_RATE_LIMITER.limit({ key: 'test-key' }); | ||
| return new Response(JSON.stringify(outcome)); | ||
| } | ||
|
|
||
| return new Response('not found', { status: 404 }); | ||
| }, | ||
| } as ExportedHandler<Env>, | ||
| ); |
48 changes: 48 additions & 0 deletions
48
dev-packages/cloudflare-integration-tests/suites/ratelimit/test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| import type { Envelope } from '@sentry/core'; | ||
| import { expect, it } from 'vitest'; | ||
| import { createRunner } from '../../runner'; | ||
|
|
||
| function envelopeItemType(envelope: Envelope): string | undefined { | ||
| return envelope[1][0]?.[0]?.type as string | undefined; | ||
| } | ||
|
|
||
| function envelopeItem(envelope: Envelope): Record<string, unknown> { | ||
| return envelope[1][0]![1] as Record<string, unknown>; | ||
| } | ||
|
|
||
| function findSpans(envelope: Envelope, description: string): Array<Record<string, unknown>> { | ||
| if (envelopeItemType(envelope) !== 'transaction') return []; | ||
| const tx = envelopeItem(envelope); | ||
| const spans = (tx.spans as Array<Record<string, unknown>>) || []; | ||
| return spans.filter(s => s.description === description); | ||
| } | ||
|
|
||
| function spanData(span: Record<string, unknown>): Record<string, unknown> { | ||
| return span.data as Record<string, unknown>; | ||
| } | ||
|
|
||
| it('emits a ratelimit span with the binding name and success outcome', async ({ signal }) => { | ||
| const runner = createRunner(__dirname) | ||
| .expect((envelope: Envelope) => { | ||
| const spans = findSpans(envelope, 'rate_limit MY_RATE_LIMITER'); | ||
| expect(spans).toHaveLength(1); | ||
| const data = spanData(spans[0]!); | ||
| expect({ | ||
| op: spans[0]!.op, | ||
| description: spans[0]!.description, | ||
| 'cloudflare.rate_limit.binding': data['cloudflare.rate_limit.binding'], | ||
| 'cloudflare.rate_limit.success': data['cloudflare.rate_limit.success'], | ||
| 'sentry.origin': data['sentry.origin'], | ||
| }).toEqual({ | ||
| op: 'ratelimit', | ||
| description: 'rate_limit MY_RATE_LIMITER', | ||
| 'cloudflare.rate_limit.binding': 'MY_RATE_LIMITER', | ||
| 'cloudflare.rate_limit.success': true, | ||
| 'sentry.origin': 'auto.faas.cloudflare.rate_limit', | ||
| }); | ||
| }) | ||
| .start(signal); | ||
|
|
||
| await runner.makeRequest('get', '/ratelimit/limit'); | ||
| await runner.completed(); | ||
| }); |
13 changes: 13 additions & 0 deletions
13
dev-packages/cloudflare-integration-tests/suites/ratelimit/wrangler.jsonc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| { | ||
| "name": "worker-name", | ||
| "compatibility_date": "2025-06-17", | ||
| "main": "index.ts", | ||
| "compatibility_flags": ["nodejs_als"], | ||
| "ratelimits": [ | ||
| { | ||
| "name": "MY_RATE_LIMITER", | ||
| "namespace_id": "1001", | ||
| "simple": { "limit": 100, "period": 60 }, | ||
| }, | ||
| ], | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
45 changes: 45 additions & 0 deletions
45
packages/cloudflare/src/instrumentations/worker/instrumentRateLimit.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| import type { RateLimit, RateLimitOptions, RateLimitOutcome } from '@cloudflare/workers-types'; | ||
| import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, startSpan } from '@sentry/core'; | ||
|
|
||
| const ORIGIN = 'auto.faas.cloudflare.rate_limit'; | ||
| const OP = 'ratelimit'; | ||
|
|
||
| /** | ||
| * Wraps a Cloudflare rate limiter binding to create a span on each `limit()` call. | ||
| * | ||
| * A `success: false` outcome means the request was rate limited. That is an | ||
| * expected result rather than an error, so it is recorded as a span attribute | ||
| * instead of setting an error status on the span. The rate limit `key` is | ||
| * intentionally not recorded because it frequently carries user-identifying | ||
| * data (e.g. an IP address or user id). | ||
| */ | ||
| export function instrumentRateLimit<T extends RateLimit>(rateLimit: T, bindingName: string): T { | ||
| return new Proxy(rateLimit, { | ||
| get(target, prop, receiver) { | ||
| if (prop === 'limit') { | ||
| const original = Reflect.get(target, prop, receiver) as RateLimit['limit']; | ||
|
|
||
| return function (this: unknown, options: RateLimitOptions): Promise<RateLimitOutcome> { | ||
| return startSpan( | ||
| { | ||
| op: OP, | ||
| name: `rate_limit ${bindingName}`, | ||
| attributes: { | ||
| 'cloudflare.rate_limit.binding': bindingName, | ||
| [SEMANTIC_ATTRIBUTE_SENTRY_OP]: OP, | ||
| [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: ORIGIN, | ||
| }, | ||
| }, | ||
| async span => { | ||
| const outcome = await Reflect.apply(original, target, [options]); | ||
| span.setAttribute('cloudflare.rate_limit.success', outcome.success); | ||
| return outcome; | ||
| }, | ||
| ); | ||
| }; | ||
| } | ||
|
|
||
| return Reflect.get(target, prop, receiver); | ||
| }, | ||
| }); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
86 changes: 86 additions & 0 deletions
86
packages/cloudflare/test/instrumentations/worker/instrumentRateLimit.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| import type { RateLimit } from '@cloudflare/workers-types'; | ||
| import * as SentryCore from '@sentry/core'; | ||
| import { beforeEach, describe, expect, test, vi } from 'vitest'; | ||
| import { instrumentRateLimit } from '../../../src/instrumentations/worker/instrumentRateLimit'; | ||
|
|
||
| function createMockRateLimit(success = true): RateLimit { | ||
| return { | ||
| limit: vi.fn().mockResolvedValue({ success }), | ||
| } as unknown as RateLimit; | ||
| } | ||
|
|
||
| describe('instrumentRateLimit', () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| }); | ||
|
|
||
| const startSpanSpy = vi.spyOn(SentryCore, 'startSpan'); | ||
|
|
||
|
Comment on lines
+1
to
+18
|
||
| describe('limit', () => { | ||
| test('forwards the call and returns the outcome', async () => { | ||
| const rateLimit = createMockRateLimit(true); | ||
| const wrapped = instrumentRateLimit(rateLimit, 'MY_RATE_LIMITER'); | ||
|
|
||
| const outcome = await wrapped.limit({ key: 'user-123' }); | ||
|
|
||
| expect(outcome).toEqual({ success: true }); | ||
| expect(rateLimit.limit).toHaveBeenCalledTimes(1); | ||
| expect(rateLimit.limit).toHaveBeenCalledWith({ key: 'user-123' }); | ||
| }); | ||
|
|
||
| test('returns an unsuccessful (rate-limited) outcome unchanged', async () => { | ||
| const wrapped = instrumentRateLimit(createMockRateLimit(false), 'MY_RATE_LIMITER'); | ||
|
|
||
| const outcome = await wrapped.limit({ key: 'user-123' }); | ||
|
|
||
| expect(outcome).toEqual({ success: false }); | ||
| }); | ||
|
|
||
| test('starts a span with correct attributes', async () => { | ||
| const wrapped = instrumentRateLimit(createMockRateLimit(true), 'MY_RATE_LIMITER'); | ||
| await wrapped.limit({ key: 'user-123' }); | ||
|
|
||
| expect(startSpanSpy).toHaveBeenCalledTimes(1); | ||
| expect(startSpanSpy).toHaveBeenLastCalledWith( | ||
| expect.objectContaining({ | ||
| op: 'ratelimit', | ||
| name: 'rate_limit MY_RATE_LIMITER', | ||
| attributes: expect.objectContaining({ | ||
| 'cloudflare.rate_limit.binding': 'MY_RATE_LIMITER', | ||
| 'sentry.op': 'ratelimit', | ||
| 'sentry.origin': 'auto.faas.cloudflare.rate_limit', | ||
| }), | ||
| }), | ||
| expect.any(Function), | ||
| ); | ||
| }); | ||
|
|
||
| test('does not record the rate limit key (avoids leaking PII)', async () => { | ||
| const wrapped = instrumentRateLimit(createMockRateLimit(true), 'MY_RATE_LIMITER'); | ||
| await wrapped.limit({ key: 'super-secret-user-id' }); | ||
|
|
||
| const attributes = startSpanSpy.mock.calls[0]![0].attributes!; | ||
| expect(JSON.stringify(attributes)).not.toContain('super-secret-user-id'); | ||
| }); | ||
|
|
||
| test('records the outcome success on the span', async () => { | ||
| const setAttribute = vi.fn(); | ||
| startSpanSpy.mockImplementationOnce(((_options: unknown, callback: (span: unknown) => unknown) => | ||
| callback({ setAttribute })) as unknown as typeof SentryCore.startSpan); | ||
|
|
||
| const wrapped = instrumentRateLimit(createMockRateLimit(false), 'MY_RATE_LIMITER'); | ||
| await wrapped.limit({ key: 'user-123' }); | ||
|
|
||
| expect(setAttribute).toHaveBeenCalledWith('cloudflare.rate_limit.success', false); | ||
| }); | ||
| }); | ||
|
|
||
| test('forwards unknown property accesses transparently', () => { | ||
| const rateLimit = Object.assign(createMockRateLimit(), { | ||
| customMethod: vi.fn().mockReturnValue('hi'), | ||
| }) as unknown as RateLimit & { customMethod: () => string }; | ||
| const wrapped = instrumentRateLimit(rateLimit, 'MY_RATE_LIMITER') as RateLimit & { customMethod: () => string }; | ||
|
|
||
| expect(wrapped.customMethod()).toBe('hi'); | ||
| }); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.