Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .size-limit.js
Original file line number Diff line number Diff line change
Expand Up @@ -480,7 +480,7 @@ module.exports = [
ignore: [...builtinModules, ...nodePrefixedBuiltinModules],
gzip: false,
brotli: false,
limit: '480 KiB',
limit: '490 KiB',
disablePlugins: ['@size-limit/webpack'],
webpack: false,
modifyEsbuildConfig: function (config) {
Expand Down
12 changes: 12 additions & 0 deletions packages/cloudflare/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,18 @@ interface BaseCloudflareOptions {
* @default false
*/
instrumentPrototypeMethods?: boolean | string[];

/**
* If you use Spotlight by Sentry during development, use
* this option to forward captured Sentry events to Spotlight.
*
* Either set it to true, or provide a specific Spotlight Sidecar URL.
*
* More details: https://spotlightjs.com/
*
* IMPORTANT: Only set this option to `true` while developing, not in production!
*/
spotlight?: boolean | string;
}

/**
Expand Down
1 change: 1 addition & 0 deletions packages/cloudflare/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ export { getDefaultIntegrations } from './sdk';

export { httpServerIntegration } from './integrations/httpServer';
export { fetchIntegration } from './integrations/fetch';
export { spotlightIntegration } from './integrations/spotlight';
export { vercelAIIntegration } from './integrations/tracing/vercelai';
// eslint-disable-next-line typescript/no-deprecated
export { honoIntegration } from './integrations/hono';
Expand Down
89 changes: 89 additions & 0 deletions packages/cloudflare/src/integrations/spotlight.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import type { Client, Envelope, IntegrationFn } from '@sentry/core';
import { debug, defineIntegration, serializeEnvelope, suppressTracing } from '@sentry/core';
import { DEBUG_BUILD } from '../debug-build';

type SpotlightConnectionOptions = {
/**
* Set this if the Spotlight Sidecar is not running on localhost:8969.
* By default, the URL is set to http://localhost:8969/stream
*/
sidecarUrl?: string;
};

export const INTEGRATION_NAME = 'Spotlight' as const;

const _spotlightIntegration = ((options: Partial<SpotlightConnectionOptions> = {}) => {
const sidecarUrl = options.sidecarUrl || 'http://localhost:8969/stream';

return {
name: INTEGRATION_NAME,
setup(client) {
DEBUG_BUILD && debug.log('[Spotlight] Using Sidecar URL', sidecarUrl);
setupSidecarForwarding(client, sidecarUrl);
},
};
}) satisfies IntegrationFn;

/**
* Use this integration to send errors and transactions to Spotlight.
*
* Learn more about spotlight at https://spotlightjs.com
*
* Important: This integration is intended for local development only.
* Each forwarded envelope counts as a Worker subrequest (50 free / 1000 paid
* per invocation), so it should not be enabled in production.
*/
export const spotlightIntegration = defineIntegration(_spotlightIntegration);

function setupSidecarForwarding(client: Client, sidecarUrl: string): void {
const parsedUrl = parseSidecarUrl(sidecarUrl);
if (!parsedUrl) {
return;
}

let failCount = 0;

client.on('beforeEnvelope', (envelope: Envelope) => {
if (failCount > 3) {
DEBUG_BUILD && debug.warn('[Spotlight] Disabled Sentry -> Spotlight forwarding due to too many failed requests');
return;
}

const body = serializeEnvelope(envelope);

suppressTracing(() => {
fetch(parsedUrl.href, {
method: 'POST',
body,
headers: {
'Content-Type': 'application/x-sentry-envelope',
},
}).then(
res => {
// Consume the response body to satisfy Cloudflare Workers' requirement
// that all fetch response bodies are read or cancelled.
res.text().catch(() => {
// no-op
});

if (res.status >= 200 && res.status < 400) {
failCount = 0;
}
},
Comment on lines +70 to +72

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: The Spotlight integration's circuit breaker does not trigger on HTTP 4xx/5xx errors, only on network failures, preventing it from disabling requests to a failing but reachable sidecar.
Severity: LOW

Suggested Fix

Modify the fetch() success callback to check the response status. If the status is outside the 200-399 range, increment the failCount. This ensures that both network errors and HTTP error responses contribute to triggering the circuit breaker, aligning with its intended purpose of handling all failure modes.

Prompt for AI Agent
Review the code at the location below. A potential bug has been identified by an AI
agent. Verify if this is a real issue. If it is, propose a fix; if not, explain why it's
not valid.

Location: packages/cloudflare/src/integrations/spotlight.ts#L70-L72

Potential issue: The circuit-breaker logic in `spotlight.ts` is designed to stop sending
data to the Spotlight sidecar after repeated failures. However, it only increments the
`failCount` when the `fetch()` call is rejected (e.g., a network error). It does not
increment the count for successful `fetch` calls that result in an HTTP 4xx or 5xx
status code. As a result, if the sidecar is reachable but consistently returning errors,
the `failCount` will never increase, and the circuit breaker will fail to engage. This
leads to the integration continuously sending requests to a broken endpoint.

Did we get this right? 👍 / 👎 to inform future reviews.

() => {
failCount++;
DEBUG_BUILD && debug.warn('[Spotlight] Failed to send envelope to Spotlight Sidecar');
},
);
});
});
}

function parseSidecarUrl(url: string): URL | undefined {
try {
return new URL(url);
} catch {
DEBUG_BUILD && debug.warn(`[Spotlight] Invalid sidecar URL: ${url}`);
return undefined;
}
}
34 changes: 34 additions & 0 deletions packages/cloudflare/src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,12 @@ export function getFinalOptions(userOptions: CloudflareOptions = {}, env: unknow
const tracesSampleRate =
userOptions.tracesSampleRate ?? parseFloat(getEnvVar(env, 'SENTRY_TRACES_SAMPLE_RATE') ?? '');

// Spotlight precedence (mirrors node-core's getSpotlightConfig):
// - false or explicit string from options: use as-is
// - true: enable, but prefer a custom URL from the env var if set
// - undefined: defer entirely to the env var (bool or URL)
const spotlight = getSpotlightFromEnv(userOptions.spotlight, getEnvVar(env, 'SENTRY_SPOTLIGHT'));

return {
release,
...userOptions,
Expand All @@ -62,5 +68,33 @@ export function getFinalOptions(userOptions: CloudflareOptions = {}, env: unknow
tracesSampleRate: isFinite(tracesSampleRate) ? tracesSampleRate : undefined,
debug: userOptions.debug ?? envToBool(getEnvVar(env, 'SENTRY_DEBUG')),
tunnel: userOptions.tunnel ?? getEnvVar(env, 'SENTRY_TUNNEL'),
spotlight,
};
}

/**
* Resolve the spotlight option from a user-supplied value and an env binding string.
* Mirrors node-core's `getSpotlightConfig` precedence:
* - `false` or explicit string from options → use as-is
* - `true` → enable, but prefer a custom URL from the env var if set
* - `undefined` → defer entirely to the env var (bool or URL)
*/
function getSpotlightFromEnv(
optionsSpotlight: boolean | string | undefined,
envVar: string | undefined,
): boolean | string | undefined {
if (optionsSpotlight === false) {
return false;
}
if (typeof optionsSpotlight === 'string') {
return optionsSpotlight;
}

// optionsSpotlight is true or undefined
const envBool = envToBool(envVar, { strict: true });
const envUrl = envBool === null && envVar ? envVar : undefined;

return optionsSpotlight === true
? (envUrl ?? true) // true: use env URL if present, otherwise true
: (envBool ?? envUrl); // undefined: use env var (bool or URL)
}
9 changes: 9 additions & 0 deletions packages/cloudflare/src/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { makeFlushLock } from './flush';
import { httpServerIntegration } from './integrations/httpServer';
import { fetchIntegration } from './integrations/fetch';
import { honoIntegration } from './integrations/hono';
import { INTEGRATION_NAME as SPOTLIGHT_INTEGRATION_NAME, spotlightIntegration } from './integrations/spotlight';
import { setupOpenTelemetryTracer } from './opentelemetry/tracer';
import { makeCloudflareTransport } from './transport';
import { defaultStackParser } from './vendor/stacktrace';
Expand Down Expand Up @@ -91,6 +92,14 @@ export function init(options: CloudflareOptions): CloudflareClient | undefined {
flushLock,
};

if (options.spotlight && !clientOptions.integrations.some(({ name }) => name === SPOTLIGHT_INTEGRATION_NAME)) {
clientOptions.integrations.push(
spotlightIntegration({
sidecarUrl: typeof options.spotlight === 'string' ? options.spotlight : undefined,
}),
);
}

/**
* The Cloudflare SDK is not OpenTelemetry native, however, we set up some OpenTelemetry compatibility
* via a custom trace provider.
Expand Down
Loading
Loading