Skip to content
Draft
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { getCloudflareContext } from '@opennextjs/cloudflare';
import { NextResponse } from 'next/server';

export const dynamic = 'force-dynamic';

type Env = { DB: { prepare(query: string): { all(): Promise<{ results: unknown[] }> } } };

export async function GET() {
const { env } = await getCloudflareContext({ async: true });
const { results } = await (env as unknown as Env).DB.prepare('SELECT 1 AS one').all();
return NextResponse.json(results);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { context, createContextKey, trace } from '@opentelemetry/api';
import { NextResponse } from 'next/server';

export const dynamic = 'force-dynamic';

const E2E_CONTEXT_KEY = createContextKey('e2e.context.key');

export async function GET() {
const tracer = trace.getTracer('e2e');

context.with(context.active().setValue(E2E_CONTEXT_KEY, 'e2e-value'), () => {
tracer.startActiveSpan('otel-context-outer', outer => {
// An explicit context, as OpenTelemetry instrumentations pass it.
const inner = tracer.startSpan('otel-context-inner', {}, context.active());
inner.setAttribute('e2e.context.value', String(context.active().getValue(E2E_CONTEXT_KEY)));
inner.end();
outer.end();
});
});

return NextResponse.json({ ok: true });
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"scripts": {
"dev": "next dev",
"cf:build": "opennextjs-cloudflare build",
"cf:preview": "opennextjs-cloudflare preview",
"cf:preview": "opennextjs-cloudflare preview --var \"E2E_TEST_DSN:$E2E_TEST_DSN\"",
"build": "next build",
"clean": "npx rimraf node_modules pnpm-lock.yaml .tmp_dev_server_logs",
"start": "pnpm cf:preview",
Expand All @@ -17,6 +17,7 @@
"test:assert": "pnpm test:prod"
},
"dependencies": {
"@opentelemetry/api": "^1.9.1",
"@opennextjs/cloudflare": "^1.14.9",
"@sentry/nextjs": "file:../../packed/sentry-nextjs-packed.tgz",
"@sentry/core": "file:../../packed/sentry-core-packed.tgz",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,7 @@
import * as Sentry from '@sentry/nextjs';

// Only hands over the build release: `withSentry` from `@sentry/nextjs/cloudflare` in worker.ts creates the client and
// holds the options.
Sentry.init({
environment: 'qa', // dynamic sampling bias to keep transactions
dsn: process.env.NEXT_PUBLIC_E2E_TEST_DSN,
tunnel: `http://localhost:3031/`, // proxy server
tracesSampler: samplingContext => {
if (samplingContext.attributes?.['next.span_type'] === 'Middleware.execute') {
// Only keep the middleware transaction when `normalizedRequest` was available at sampling time.
// Test times out and fails when transaction is dropped
const { normalizedRequest } = samplingContext;
return Boolean(normalizedRequest?.url && normalizedRequest?.method);
}

return 1.0;
},
// debug: true,
});
Original file line number Diff line number Diff line change
@@ -1,15 +1,7 @@
import * as Sentry from '@sentry/nextjs';
import { Log } from '@sentry/nextjs';

// Only hands over the build release and adds the global Next.js event processors and the turbopack tag: `withSentry`
// from `@sentry/nextjs/cloudflare` in worker.ts creates the client and holds the options.
Sentry.init({
environment: 'qa', // dynamic sampling bias to keep transactions
dsn: process.env.NEXT_PUBLIC_E2E_TEST_DSN,
tunnel: `http://localhost:3031/`, // proxy server
tracesSampleRate: 1.0,
// debug: true,
integrations: [Sentry.vercelAIIntegration()],
// Verify Log type is available
beforeSendLog(log: Log) {
return log;
},
});
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ test.describe('Cloudflare Runtime', () => {
expect(errorEvent.contexts?.runtime).toEqual({
name: 'cloudflare',
});
expect(errorEvent.tags?.turbopack).toBe(true);

// The SDK info should include cloudflare in the packages
expect(errorEvent.sdk?.packages).toEqual(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { expect, test } from '@playwright/test';
import { collectStreamedSpansUntilSegment, getSpanOp } from '@sentry-internal/test-utils';

// `withSentry` passes an instrumented `env` to the OpenNext handler, which `getCloudflareContext()` returns.
test('Should create a span for a D1 query through the `env` of `getCloudflareContext`', async ({ request }) => {
const spansPromise = collectStreamedSpansUntilSegment('nextjs-16-cf-workers', 'GET /api/d1');

const response = await request.get('/api/d1');
expect(await response.json()).toStrictEqual([{ one: 1 }]);

const spans = await spansPromise;
const d1Span = spans.find(span => getSpanOp(span) === 'db.query')!;

expect(d1Span.is_segment).toBe(false);
expect(d1Span.attributes).toMatchObject({
'db.system.name': { value: 'cloudflare-d1', type: 'string' },
'db.query.text': { value: 'SELECT ? AS one', type: 'string' },
'sentry.origin': { value: 'auto.db.cloudflare.d1', type: 'string' },
});
});
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import { expect, test } from '@playwright/test';
import { waitForMetric } from '@sentry-internal/test-utils';

// Metrics are not currently supported on Cloudflare Workers
// TODO: Investigate and enable when metrics support is added for CF Workers
test.skip('Should emit metrics from server and client', async ({ request, page }) => {
test('Should emit metrics from server and client', async ({ request, page }) => {
const clientCountPromise = waitForMetric('nextjs-16-cf-workers', async metric => {
return metric.name === 'test.page.count';
});
Expand Down Expand Up @@ -92,7 +90,6 @@ test.skip('Should emit metrics from server and client', async ({ request, page }
type: 'counter',
value: 1,
attributes: {
'server.address': { value: expect.any(String), type: 'string' },
'random.attribute': { value: 'Potatoes', type: 'string' },
endpoint: { value: '/metrics/route-handler', type: 'string' },
'sentry.environment': { value: 'qa', type: 'string' },
Expand All @@ -108,7 +105,6 @@ test.skip('Should emit metrics from server and client', async ({ request, page }
type: 'distribution',
value: 100,
attributes: {
'server.address': { value: expect.any(String), type: 'string' },
'random.attribute': { value: 'Patatas', type: 'string' },
endpoint: { value: '/metrics/route-handler', type: 'string' },
'sentry.environment': { value: 'qa', type: 'string' },
Expand All @@ -124,7 +120,6 @@ test.skip('Should emit metrics from server and client', async ({ request, page }
type: 'gauge',
value: 200,
attributes: {
'server.address': { value: expect.any(String), type: 'string' },
'random.attribute': { value: 'Patate', type: 'string' },
endpoint: { value: '/metrics/route-handler', type: 'string' },
'sentry.environment': { value: 'qa', type: 'string' },
Expand Down
Original file line number Diff line number Diff line change
@@ -1,61 +1,55 @@
import { expect, test } from '@playwright/test';
import { collectStreamedSpans, getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils';
import { collectStreamedSpans, collectStreamedSpansUntilSegment, getSpanOp } from '@sentry-internal/test-utils';
import { isDevMode } from './isDevMode';

// TODO: Skipped until the Cloudflare Workers edge middleware setup emits middleware spans reliably.
test.skip('tracesSampler receives normalizedRequest for edge middleware', async ({ request }) => {
const middlewareSpanPromise = waitForStreamedSpan('nextjs-16-cf-workers', span => {
return span.name === 'middleware GET' && span.is_segment;
});

await request.get('/api/endpoint-behind-middleware');

const middlewareSpan = await middlewareSpanPromise;

expect(String(middlewareSpan.attributes['http.target']?.value)).toContain('/api/endpoint-behind-middleware');
expect(middlewareSpan.attributes['http.request.method']?.value).toBe('GET');
});

// TODO: Middleware tests need SDK adjustments for Cloudflare Workers edge runtime
test.skip('Should create a span for middleware', async ({ request }) => {
const middlewareSpanPromise = waitForStreamedSpan('nextjs-16-cf-workers', span => {
return span.name === 'middleware GET' && span.is_segment;
});
// `withSentry` from `@sentry/nextjs/cloudflare` wraps the Worker entry, so middleware runs inside the request's
// `http.server` segment and its span is a child of it rather than a segment of its own.
test('Should create a span for middleware inside the request segment', async ({ request }) => {
const spansPromise = collectStreamedSpansUntilSegment('nextjs-16-cf-workers', 'GET /api/endpoint-behind-middleware');

const response = await request.get('/api/endpoint-behind-middleware');
expect(await response.json()).toStrictEqual({ name: 'John Doe' });

const middlewareSpan = await middlewareSpanPromise;

const spans = await spansPromise;
const segmentSpan = spans.find(span => span.is_segment)!;
const middlewareSpan = spans.find(span => span.name === 'middleware GET')!;

expect(segmentSpan.attributes['url.path']?.value).toBe('/api/endpoint-behind-middleware');
expect(segmentSpan.attributes['sentry.segment.name.source']?.value).toBe('route');
expect(segmentSpan.attributes['isolation_scope.is_default']).toEqual({ value: false, type: 'boolean' });
expect(middlewareSpan.is_segment).toBe(false);
expect(spans.some(span => span.span_id === middlewareSpan.parent_span_id)).toBe(true);
expect(middlewareSpan.status).toBe('ok');
expect(getSpanOp(middlewareSpan)).toBe('middleware');
expect(middlewareSpan.attributes['sentry.segment.name.source']?.value).toBe('route');

// Assert that isolation scope works properly
// expect(middlewareSpan.attributes['isolation_scope.is_default']).toEqual({ value: false, type: 'boolean' });
});

// TODO: Middleware tests need SDK adjustments for Cloudflare Workers edge runtime
test.skip('Faulty middlewares', async ({ request }) => {
test('Faulty middlewares', async ({ request }) => {
test.skip(isDevMode, 'Throwing crashes the dev server atm'); // https://github.com/vercel/next.js/issues/85261
const middlewareSpanPromise = waitForStreamedSpan('nextjs-16-cf-workers', span => {
return span.name === 'middleware GET' && span.is_segment;
});
// The middleware throws, so the request span of `withSentry` keeps the middleware name, like the middleware segment
// of Node.js.
const spansPromise = collectStreamedSpans(
'nextjs-16-cf-workers',
spans =>
spans.some(span => span.is_segment && span.name === 'middleware GET') &&
spans.some(span => !span.is_segment && span.name === 'middleware GET'),
);

request.get('/api/endpoint-behind-middleware', { headers: { 'x-should-throw': '1' } }).catch(() => {
// Noop
});

await test.step('should record spans', async () => {
const middlewareSpan = await middlewareSpanPromise;
expect(middlewareSpan.status).toBe('error');
expect(getSpanOp(middlewareSpan)).toBe('middleware');
expect(middlewareSpan.attributes['sentry.segment.name.source']?.value).toBe('route');
});
const spans = await spansPromise;
const segmentSpan = spans.find(span => span.is_segment)!;
const middlewareSpan = spans.find(span => !span.is_segment && span.name === 'middleware GET')!;

expect(segmentSpan.status).toBe('error');
expect(segmentSpan.attributes['sentry.segment.name.source']?.value).toBe('route');
expect(middlewareSpan.parent_span_id).toBe(segmentSpan.span_id);
expect(middlewareSpan.status).toBe('error');
expect(getSpanOp(middlewareSpan)).toBe('middleware');
});

// TODO: Middleware tests need SDK adjustments for Cloudflare Workers edge runtime
test.skip('Should trace outgoing fetch requests inside middleware', async ({ request }) => {
test('Should trace outgoing fetch requests inside middleware', async ({ request }) => {
test.skip(isDevMode, 'The fetch requests ends up in a separate tx in dev atm');

// `http.client` span names are low cardinality under span streaming, hence `GET localhost` rather
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { expect, test } from '@playwright/test';
import { waitForError, waitForStreamedSpan } from '@sentry-internal/test-utils';

// TODO: Flakey on CI
test.skip('Should capture errors from nested server components when `Sentry.captureRequestError` is added to the `onRequestError` hook', async ({
test('Should capture errors from nested server components when `Sentry.captureRequestError` is added to the `onRequestError` hook', async ({
page,
}) => {
const errorEventPromise = waitForError('nextjs-16-cf-workers', errorEvent => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { expect, test } from '@playwright/test';
import { collectStreamedSpansUntilSegment } from '@sentry-internal/test-utils';

test('Keeps OpenTelemetry context values and parents', async ({ request }) => {
const spansPromise = collectStreamedSpansUntilSegment('nextjs-16-cf-workers', 'GET /api/otel-context');

const response = await request.get('/api/otel-context');
expect(await response.json()).toStrictEqual({ ok: true });

const spans = await spansPromise;
const segmentSpan = spans.find(span => span.is_segment)!;
const outerSpan = spans.find(span => span.name === 'otel-context-outer')!;
const innerSpan = spans.find(span => span.name === 'otel-context-inner')!;

expect(spans.some(span => span.span_id === outerSpan.parent_span_id)).toBe(true);
expect(innerSpan.parent_span_id).toBe(outerSpan.span_id);
expect(innerSpan.trace_id).toBe(segmentSpan.trace_id);
expect(innerSpan.attributes['e2e.context.value']?.value).toBe('e2e-value');
});
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { expect, test } from '@playwright/test';
import { getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils';

// TODO: Flakey on CI
test.skip('App router spans should be attached to the pageload request span', async ({ page }) => {
test('App router spans should be attached to the pageload request span', async ({ page }) => {
const serverSpanPromise = waitForStreamedSpan('nextjs-16-cf-workers', span => {
return span.name === 'GET /pageload-tracing' && span.is_segment;
});
Expand All @@ -19,8 +18,7 @@ test.skip('App router spans should be attached to the pageload request span', as
expect(serverSpan.trace_id).toBe(pageloadSpan.trace_id);
});

// TODO: HTTP request headers are not extracted as span attributes on Cloudflare Workers
test.skip('extracts HTTP request headers as span attributes', async ({ baseURL }) => {
test('extracts HTTP request headers as span attributes', async ({ baseURL }) => {
const serverSpanPromise = waitForStreamedSpan('nextjs-16-cf-workers', span => {
const requestId = span.attributes['http.request.header.x-request-id'];
return (
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import test, { expect } from '@playwright/test';
import { getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils';

test.skip('Should create a span for node route handlers', async ({ request }) => {
test('Should create a span for node route handlers', async ({ request }) => {
const routehandlerSpanPromise = waitForStreamedSpan('nextjs-16-cf-workers', span => {
return span.name === 'GET /route-handler/[xoxo]/node' && span.is_segment;
});
Expand All @@ -13,15 +13,11 @@ test.skip('Should create a span for node route handlers', async ({ request }) =>

expect(routehandlerSpan.status).toBe('ok');
expect(getSpanOp(routehandlerSpan)).toBe('http.server');

// Custom headers are not captured on Cloudflare Workers
// This assertion is skipped for CF Workers environment
expect(routehandlerSpan.attributes['http.request.header.x-charly']?.value).toEqual(['gomez']);
});

test('Should create a span for edge route handlers', async ({ request }) => {
// This test only works for webpack builds on non-async param extraction
// todo: check if we can set request headers for edge on sdkProcessingMetadata
test.skip();
test.skip(true, 'OpenNext does not support the Edge runtime');
const routehandlerSpanPromise = waitForStreamedSpan('nextjs-16-cf-workers', span => {
return span.name === 'GET /route-handler/[xoxo]/edge' && span.is_segment;
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { expect, test } from '@playwright/test';
import { waitForError, waitForStreamedSpan } from '@sentry-internal/test-utils';

test.skip('Should handle server action redirect without capturing errors', async ({ page }) => {
test('Should handle server action redirect without capturing errors', async ({ page }) => {
// Wait for the initial pageload span
const pageLoadSpanPromise = waitForStreamedSpan('nextjs-16-cf-workers', span => {
return span.name === '/redirect/origin' && span.is_segment;
Expand Down
Loading
Loading