diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 1fc85176963d..cf00b5d00435 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -174,7 +174,7 @@ jobs: pull-requests: write steps: - name: PR is opened against master - uses: mshick/add-pr-comment@dd126dd8c253650d181ad9538d8b4fa218fc31e8 + uses: mshick/add-pr-comment@e7516d74559b5514092f5b096ed29a629a1237c6 if: ${{ github.base_ref == 'master' && !startsWith(github.head_ref, 'prepare-release/') }} with: message: | diff --git a/.github/workflows/changelog-preview.yml b/.github/workflows/changelog-preview.yml index b1a0e4f25b05..9aabf51e1070 100644 --- a/.github/workflows/changelog-preview.yml +++ b/.github/workflows/changelog-preview.yml @@ -15,5 +15,5 @@ permissions: jobs: changelog-preview: - uses: getsentry/craft/.github/workflows/changelog-preview.yml@2.24.1 + uses: getsentry/craft/.github/workflows/changelog-preview.yml@2.25.2 secrets: inherit diff --git a/.github/workflows/validate-pr.yml b/.github/workflows/validate-pr.yml index 44da67faa43e..10fe894067a0 100644 --- a/.github/workflows/validate-pr.yml +++ b/.github/workflows/validate-pr.yml @@ -10,7 +10,7 @@ jobs: permissions: pull-requests: write steps: - - uses: getsentry/github-workflows/validate-pr@0b52fc6a867b744dcbdf5d25c18bc8d1c95710e1 + - uses: getsentry/github-workflows/validate-pr@71588ddf95134f804e82c5970a8098588e2eaecd with: app-id: ${{ vars.SDK_MAINTAINER_BOT_APP_ID }} private-key: ${{ secrets.SDK_MAINTAINER_BOT_PRIVATE_KEY }} diff --git a/.oxlintrc.base.json b/.oxlintrc.base.json new file mode 100644 index 000000000000..96122ee95b3e --- /dev/null +++ b/.oxlintrc.base.json @@ -0,0 +1,139 @@ +{ + "$schema": "./node_modules/oxlint/configuration_schema.json", + "plugins": ["typescript", "import", "jsdoc", "vitest"], + "rules": { + "no-unused-vars": [ + "warn", + { "argsIgnorePattern": "^_", "varsIgnorePattern": "^_", "caughtErrorsIgnorePattern": "^_" } + ], + + // === Base rules from eslint-config-sdk/base.js === + "no-console": "error", + "no-alert": "error", + "no-param-reassign": "error", + "prefer-template": "error", + "no-bitwise": "error", + "complexity": ["error", { "max": 33 }], + "no-unused-expressions": ["error", { "allowShortCircuit": true }], + "guard-for-in": "error", + "array-callback-return": ["error", { "allowImplicit": true }], + "quotes": ["error", "single", { "avoidEscape": true }], + "no-return-await": "error", + "max-lines": ["error", { "max": 300, "skipComments": true, "skipBlankLines": true }], + + // === Import rules === + "import/namespace": "off", + "import/no-unresolved": "off", + + // === Rules turned off (not enforced in ESLint or causing false positives) === + "no-control-regex": "off", + "jsdoc/check-tag-names": "off", + "jsdoc/require-yields": "off", + "no-useless-rename": "off", + "no-constant-binary-expression": "off", + "vitest/hoisted-apis-on-top": "off", + "vitest/no-conditional-tests": "off", + "no-unsafe-optional-chaining": "off", + "no-eval": "off", + "no-import-assign": "off", + "typescript/no-duplicate-type-constituents": "off" + }, + "overrides": [ + { + "files": ["**/*.ts", "**/*.tsx", "**/*.d.ts"], + "rules": { + "typescript/ban-ts-comment": "error", + "typescript/consistent-type-imports": "error", + "typescript/no-unnecessary-type-assertion": "error", + "typescript/prefer-for-of": "error", + "typescript/no-floating-promises": ["error", { "ignoreVoid": true }], + "typescript/no-dynamic-delete": "error", + "typescript/no-unsafe-member-access": "error", + "typescript/unbound-method": "error", + "typescript/no-explicit-any": "error", + "typescript/no-empty-function": "off", + "typescript/prefer-optional-chain": ["error"], + "typescript/no-redundant-type-constituents": "off", + "typescript/restrict-template-expressions": "off", + "typescript/await-thenable": "warn", + "typescript/no-base-to-string": "off" + } + }, + { + "files": ["**/*.js", "**/*.mjs", "**/*.cjs"], + "rules": { + "typescript/ban-ts-comment": "off", + "typescript/consistent-type-imports": "off", + "typescript/prefer-optional-chain": "off", + "typescript/no-unnecessary-type-assertion": "off", + "typescript/prefer-for-of": "off", + "typescript/no-floating-promises": "off", + "typescript/no-dynamic-delete": "off", + "typescript/no-unsafe-member-access": "off", + "typescript/unbound-method": "off", + "typescript/no-explicit-any": "off" + } + }, + { + "files": [ + "**/*.test.ts", + "**/*.test.tsx", + "**/*.test.js", + "**/*.test.jsx", + "**/test/**", + "**/tests/**", + "**/suites/**", + "**/loader-suites/**" + ], + "rules": { + "typescript/explicit-function-return-type": "off", + "no-unused-expressions": "off", + "typescript/no-unused-expressions": "off", + "typescript/no-unnecessary-type-assertion": "off", + "typescript/no-unsafe-member-access": "off", + "typescript/no-explicit-any": "off", + "typescript/no-non-null-assertion": "off", + "typescript/no-floating-promises": "off", + "typescript/unbound-method": "off", + "max-lines": "off", + "complexity": "off", + "typescript/prefer-optional-chain": "off", + "typescript/no-misused-spread": "off", + "typescript/require-array-sort-compare": "off", + "typescript/no-base-to-string": "off", + "typescript/await-thenable": "off" + } + }, + { + "files": ["*.tsx"], + "rules": { + "jsdoc/require-jsdoc": "off" + } + }, + { + "files": ["*.config.js", "*.config.mjs", "*.config.ts", "vite.config.ts", ".size-limit.js"], + "rules": { + "no-console": "off", + "max-lines": "off" + } + }, + { + "files": [ + "**/scenarios/**", + "**/rollup-utils/**", + "**/bundle-analyzer-scenarios/**", + "**/bundle-analyzer-scenarios/*.cjs", + "**/bundle-analyzer-scenarios/*.js" + ], + "rules": { + "no-console": "off" + } + }, + { + "files": ["**/src/**"], + "rules": { + "no-restricted-globals": ["error", "window", "document", "location", "navigator"] + } + } + ] +} diff --git a/.oxlintrc.json b/.oxlintrc.json index e65745736664..83ff1674daf4 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -1,6 +1,9 @@ { "$schema": "./node_modules/oxlint/configuration_schema.json", - "plugins": ["typescript", "import", "jsdoc", "vitest"], + "extends": ["./.oxlintrc.base.json"], + "options": { + "typeAware": true + }, "jsPlugins": [ { "name": "sdk", @@ -9,140 +12,12 @@ ], "categories": {}, "rules": { - "no-unused-vars": [ - "warn", - { "argsIgnorePattern": "^_", "varsIgnorePattern": "^_", "caughtErrorsIgnorePattern": "^_" } - ], - - // === Base rules from eslint-config-sdk/base.js === - "no-console": "error", - "no-alert": "error", - "no-param-reassign": "error", - "prefer-template": "error", - "no-bitwise": "error", - "complexity": ["error", { "max": 33 }], - "no-unused-expressions": ["error", { "allowShortCircuit": true }], - "guard-for-in": "error", - "array-callback-return": ["error", { "allowImplicit": true }], - "quotes": ["error", "single", { "avoidEscape": true }], - "no-return-await": "error", - "max-lines": ["error", { "max": 300, "skipComments": true, "skipBlankLines": true }], - - // === Import rules === - "import/namespace": "off", - "import/no-unresolved": "off", - - // === Rules turned off (not enforced in ESLint or causing false positives) === - "no-control-regex": "off", - "jsdoc/check-tag-names": "off", - "jsdoc/require-yields": "off", - "no-useless-rename": "off", - "no-constant-binary-expression": "off", - "vitest/hoisted-apis-on-top": "off", - "vitest/no-conditional-tests": "off", - "no-unsafe-optional-chaining": "off", - "no-eval": "off", - "no-import-assign": "off", - "typescript/no-duplicate-type-constituents": "off", - - // === Custom SDK rules (via JS plugin) === "sdk/no-eq-empty": "error" }, "overrides": [ - { - "files": ["**/*.ts", "**/*.tsx", "**/*.d.ts"], - "rules": { - "typescript/ban-ts-comment": "error", - "typescript/consistent-type-imports": "error", - "typescript/no-unnecessary-type-assertion": "error", - "typescript/prefer-for-of": "error", - "typescript/no-floating-promises": ["error", { "ignoreVoid": true }], - "typescript/no-dynamic-delete": "error", - "typescript/no-unsafe-member-access": "error", - "typescript/unbound-method": "error", - "typescript/no-explicit-any": "error", - "typescript/no-empty-function": "off", - "typescript/prefer-optional-chain": ["error"], - "typescript/no-redundant-type-constituents": "off", - "typescript/restrict-template-expressions": "off", - "typescript/await-thenable": "warn", - "typescript/no-base-to-string": "off" - } - }, - { - "files": ["**/*.js", "**/*.mjs", "**/*.cjs"], - "rules": { - "typescript/ban-ts-comment": "off", - "typescript/consistent-type-imports": "off", - "typescript/prefer-optional-chain": "off", - "typescript/no-unnecessary-type-assertion": "off", - "typescript/prefer-for-of": "off", - "typescript/no-floating-promises": "off", - "typescript/no-dynamic-delete": "off", - "typescript/no-unsafe-member-access": "off", - "typescript/unbound-method": "off", - "typescript/no-explicit-any": "off" - } - }, - { - "files": [ - "**/*.test.ts", - "**/*.test.tsx", - "**/*.test.js", - "**/*.test.jsx", - "**/test/**", - "**/tests/**", - "**/suites/**", - "**/loader-suites/**" - ], - "rules": { - "typescript/explicit-function-return-type": "off", - "no-unused-expressions": "off", - "typescript/no-unused-expressions": "off", - "typescript/no-unnecessary-type-assertion": "off", - "typescript/no-unsafe-member-access": "off", - "typescript/no-explicit-any": "off", - "typescript/no-non-null-assertion": "off", - "typescript/no-floating-promises": "off", - "typescript/unbound-method": "off", - "max-lines": "off", - "complexity": "off", - "typescript/prefer-optional-chain": "off", - "typescript/no-misused-spread": "off", - "typescript/require-array-sort-compare": "off", - "typescript/no-base-to-string": "off", - "typescript/await-thenable": "off" - } - }, - { - "files": ["*.tsx"], - "rules": { - "jsdoc/require-jsdoc": "off" - } - }, - { - "files": ["*.config.js", "*.config.mjs", "*.config.ts", "vite.config.ts", ".size-limit.js"], - "rules": { - "no-console": "off", - "max-lines": "off" - } - }, - { - "files": [ - "**/scenarios/**", - "**/rollup-utils/**", - "**/bundle-analyzer-scenarios/**", - "**/bundle-analyzer-scenarios/*.cjs", - "**/bundle-analyzer-scenarios/*.js" - ], - "rules": { - "no-console": "off" - } - }, { "files": ["**/src/**"], "rules": { - "no-restricted-globals": ["error", "window", "document", "location", "navigator"], "sdk/no-class-field-initializers": "error", "sdk/no-regexp-constructor": "error" } diff --git a/.size-limit.js b/.size-limit.js index fcc455808948..1e6e8d951464 100644 --- a/.size-limit.js +++ b/.size-limit.js @@ -15,7 +15,7 @@ module.exports = [ path: 'packages/browser/build/npm/esm/prod/index.js', import: createImport('init'), gzip: true, - limit: '24.5 KB', + limit: '25 KB', modifyWebpackConfig: function (config) { const webpack = require('webpack'); @@ -103,7 +103,7 @@ module.exports = [ path: 'packages/browser/build/npm/esm/prod/index.js', import: createImport('init', 'sendFeedback'), gzip: true, - limit: '31 KB', + limit: '32 KB', }, { name: '@sentry/browser (incl. FeedbackAsync)', @@ -117,7 +117,7 @@ module.exports = [ path: 'packages/browser/build/npm/esm/prod/index.js', import: createImport('init', 'metrics'), gzip: true, - limit: '27 KB', + limit: '28 KB', }, { name: '@sentry/browser (incl. Logs)', @@ -148,7 +148,7 @@ module.exports = [ import: createImport('init', 'ErrorBoundary', 'reactRouterV6BrowserTracingIntegration'), ignore: ['react/jsx-runtime'], gzip: true, - limit: '45.1 KB', + limit: '46 KB', }, // Vue SDK (ESM) { @@ -220,13 +220,13 @@ module.exports = [ name: 'CDN Bundle (incl. Tracing, Replay, Feedback)', path: createCDNPath('bundle.tracing.replay.feedback.min.js'), gzip: true, - limit: '86 KB', + limit: '87 KB', }, { name: 'CDN Bundle (incl. Tracing, Replay, Feedback, Logs, Metrics)', path: createCDNPath('bundle.tracing.replay.feedback.logs.metrics.min.js'), gzip: true, - limit: '87 KB', + limit: '88 KB', }, // browser CDN bundles (non-gzipped) { @@ -241,7 +241,7 @@ module.exports = [ path: createCDNPath('bundle.tracing.min.js'), gzip: false, brotli: false, - limit: '129 KB', + limit: '130 KB', }, { name: 'CDN Bundle (incl. Logs, Metrics) - uncompressed', @@ -255,7 +255,7 @@ module.exports = [ path: createCDNPath('bundle.tracing.logs.metrics.min.js'), gzip: false, brotli: false, - limit: '132 KB', + limit: '134 KB', }, { name: 'CDN Bundle (incl. Replay, Logs, Metrics) - uncompressed', @@ -269,7 +269,7 @@ module.exports = [ path: createCDNPath('bundle.tracing.replay.min.js'), gzip: false, brotli: false, - limit: '246 KB', + limit: '247 KB', }, { name: 'CDN Bundle (incl. Tracing, Replay, Logs, Metrics) - uncompressed', @@ -317,7 +317,7 @@ module.exports = [ import: createImport('init'), ignore: [...builtinModules, ...nodePrefixedBuiltinModules], gzip: true, - limit: '57 KB', + limit: '59 KB', }, // Node SDK (ESM) { @@ -326,14 +326,14 @@ module.exports = [ import: createImport('init'), ignore: [...builtinModules, ...nodePrefixedBuiltinModules], gzip: true, - limit: '176 KB', + limit: '177 KB', }, { name: '@sentry/node - without tracing', path: 'packages/node/build/esm/index.js', import: createImport('initWithoutDefaultIntegrations', 'getDefaultIntegrationsWithoutPerformance'), gzip: true, - limit: '98 KB', + limit: '100 KB', ignore: [...builtinModules, ...nodePrefixedBuiltinModules], modifyWebpackConfig: function (config) { const webpack = require('webpack'); @@ -356,7 +356,7 @@ module.exports = [ import: createImport('init'), ignore: [...builtinModules, ...nodePrefixedBuiltinModules], gzip: true, - limit: '114 KB', + limit: '117 KB', }, ]; diff --git a/CHANGELOG.md b/CHANGELOG.md index 25792ba2ce11..8141da2e6276 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,115 @@ ## Unreleased -- "You miss 100 percent of the chances you don't take. — Wayne Gretzky" — Michael Scott +## 10.48.0 + +### Important Changes + +- **feat(aws-serverless): Ship Lambda extension in npm package for container image Lambdas ([#20133](https://github.com/getsentry/sentry-javascript/pull/20133))** + + The Sentry Lambda extension is now included in the npm package, enabling container image-based Lambda functions to use it. Copy the extension files into your Docker image and set the `tunnel` option: + + ```dockerfile + RUN mkdir -p /opt/sentry-extension + COPY node_modules/@sentry/aws-serverless/build/lambda-extension/sentry-extension /opt/extensions/sentry-extension + COPY node_modules/@sentry/aws-serverless/build/lambda-extension/index.mjs /opt/sentry-extension/index.mjs + RUN chmod +x /opt/extensions/sentry-extension /opt/sentry-extension/index.mjs + ``` + + ```js + Sentry.init({ + dsn: '__DSN__', + tunnel: 'http://localhost:9000/envelope', + }); + ``` + + This works with any Sentry SDK (`@sentry/aws-serverless`, `@sentry/sveltekit`, `@sentry/node`, etc.). + +- **feat(cloudflare): Support basic WorkerEntrypoint ([#19884](https://github.com/getsentry/sentry-javascript/pull/19884))** + + `withSentry` now supports instrumenting classes extending Cloudflare's `WorkerEntrypoint`. This instruments `fetch`, `scheduled`, `queue`, and `tail` handlers. + + ```ts + import * as Sentry from '@sentry/cloudflare'; + import { WorkerEntrypoint } from 'cloudflare:workers'; + + class MyWorker extends WorkerEntrypoint { + async fetch(request: Request): Promise { + return new Response('Hello World!'); + } + } + + export default Sentry.withSentry(env => ({ dsn: env.SENTRY_DSN, tracesSampleRate: 1.0 }), MyWorker); + ``` + +- **ref(core): Unify .do\* span ops to `gen_ai.generate_content` ([#20074](https://github.com/getsentry/sentry-javascript/pull/20074))** + + All Vercel AI `do*` spans (`ai.generateText.doGenerate`, `ai.streamText.doStream`, `ai.generateObject.doGenerate`, `ai.streamObject.doStream`) now use a single unified span op `gen_ai.generate_content` instead of separate ops like `gen_ai.generate_text`, `gen_ai.stream_text`, `gen_ai.generate_object`, and `gen_ai.stream_object`. + +- **ref(core): Remove provider-specific AI span attributes in favor of `gen_ai` attributes in sentry conventions ([#20011](https://github.com/getsentry/sentry-javascript/pull/20011))** + + The following provider-specific span attributes have been removed from the OpenAI and Anthropic AI integrations. Use the standardized `gen_ai.*` equivalents instead: + + | Removed attribute | Replacement | + | -------------------------------- | ---------------------------- | + | `openai.response.id` | `gen_ai.response.id` | + | `openai.response.model` | `gen_ai.response.model` | + | `openai.usage.prompt_tokens` | `gen_ai.usage.input_tokens` | + | `openai.usage.completion_tokens` | `gen_ai.usage.output_tokens` | + | `openai.response.timestamp` | _(removed, no replacement)_ | + | `anthropic.response.timestamp` | _(removed, no replacement)_ | + + If you reference these attributes in hooks (e.g. `beforeSendTransaction`), update them to the `gen_ai.*` equivalents. + +- **feat(core): Support embeddings in LangChain ([#20017](https://github.com/getsentry/sentry-javascript/pull/20017))** + + Adds instrumentation for LangChain embeddings (`embedQuery`, `embedDocuments`), creating `gen_ai.embeddings` spans. In Node.js, embedding classes from `@langchain/openai`, `@langchain/google-genai`, `@langchain/mistralai`, and `@langchain/google-vertexai` are auto-instrumented. For other runtimes, use the new `instrumentLangChainEmbeddings` API: + + ```javascript + import * as Sentry from '@sentry/cloudflare'; + import { OpenAIEmbeddings } from '@langchain/openai'; + + const embeddings = Sentry.instrumentLangChainEmbeddings(new OpenAIEmbeddings({ model: 'text-embedding-3-small' })); + + await embeddings.embedQuery('Hello world'); + ``` + +### Other Changes + +- feat(core): Support registerTool/registerResource/registerPrompt in MCP integration ([#20071](https://github.com/getsentry/sentry-javascript/pull/20071)) +- feat(core, node): Portable Express integration ([#19928](https://github.com/getsentry/sentry-javascript/pull/19928)) +- feat(deno): Add `denoRuntimeMetricsIntegration` ([#20023](https://github.com/getsentry/sentry-javascript/pull/20023)) +- feat(deps): Bump bundler plugins to `5.2.0` ([#20122](https://github.com/getsentry/sentry-javascript/pull/20122)) +- feat(deps): bump @hapi/content from 6.0.0 to 6.0.1 ([#20102](https://github.com/getsentry/sentry-javascript/pull/20102)) +- feat(node, bun): Enforce minimum collection interval in runtime metrics integrations ([#20068](https://github.com/getsentry/sentry-javascript/pull/20068)) +- feat(nuxt): Exclude tracing meta tags on cached pages in Nuxt 5 ([#20168](https://github.com/getsentry/sentry-javascript/pull/20168)) +- feat(react-router): Export `sentryOnError` ([#20120](https://github.com/getsentry/sentry-javascript/pull/20120)) +- fix(aws-serverless): Add timeout to \_endSpan forceFlush to prevent Lambda hanging ([#20064](https://github.com/getsentry/sentry-javascript/pull/20064)) +- fix(cloudflare): Ensure every request instruments functions ([#20044](https://github.com/getsentry/sentry-javascript/pull/20044)) +- fix(core): Only attach `flags` context to error events ([#20116](https://github.com/getsentry/sentry-javascript/pull/20116)) +- fix(core): Replace regex with string check in stack parser to prevent main thread blocking ([#20089](https://github.com/getsentry/sentry-javascript/pull/20089)) +- fix(core): set span.status to error when MCP tool returns JSON-RPC error response ([#20082](https://github.com/getsentry/sentry-javascript/pull/20082)) +- fix(gatsby): Fix errorHandler signature to match bundler-plugin-core API ([#20048](https://github.com/getsentry/sentry-javascript/pull/20048)) +- ref(core): Do not emit spans for chats.create in google-genai ([#19990](https://github.com/getsentry/sentry-javascript/pull/19990)) + +
+ Internal Changes + +- chore: Remove unused `tsconfig-template` folder ([#20067](https://github.com/getsentry/sentry-javascript/pull/20067)) +- chore: Update validate-pr workflow ([#20072](https://github.com/getsentry/sentry-javascript/pull/20072)) +- chore(deps-dev): Bump effect from 3.20.0 to 3.21.0 ([#19999](https://github.com/getsentry/sentry-javascript/pull/19999)) +- chore(deps): Bump @xmldom/xmldom from 0.8.3 to 0.8.12 ([#20066](https://github.com/getsentry/sentry-javascript/pull/20066)) +- chore(deps): Bump lodash.template from 4.5.0 to 4.18.1 ([#20085](https://github.com/getsentry/sentry-javascript/pull/20085)) +- chore(oxlint): Add typeawareness into oxlintrc ([#20075](https://github.com/getsentry/sentry-javascript/pull/20075)) +- ci(deps): Bump getsentry/craft/.github/workflows/changelog-preview.yml from 2.24.1 to 2.25.2 ([#20081](https://github.com/getsentry/sentry-javascript/pull/20081)) +- ci(deps): Bump `mshick/add-pr-comment` ([#20078](https://github.com/getsentry/sentry-javascript/pull/20078)) +- ref(core): Extract shared endStreamSpan for AI integrations ([#20021](https://github.com/getsentry/sentry-javascript/pull/20021)) +- ref(core): Simplify addResponseAttributes in openai integration ([#20013](https://github.com/getsentry/sentry-javascript/pull/20013)) +- test(angular): Bump TypeScript to ~6.0.0 in angular-21 E2E test app ([#20134](https://github.com/getsentry/sentry-javascript/pull/20134)) +- test(nuxt): Make Nuxt 5 (nightly) E2E optional ([#20113](https://github.com/getsentry/sentry-javascript/pull/20113)) +- tests(node): Add node integration tests for Vercel `ToolLoopAgent` ([#20087](https://github.com/getsentry/sentry-javascript/pull/20087)) + +
## 10.47.0 diff --git a/dev-packages/.oxlintrc.json b/dev-packages/.oxlintrc.json index 72497867a535..d8fc364e7886 100644 --- a/dev-packages/.oxlintrc.json +++ b/dev-packages/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../node_modules/oxlint/configuration_schema.json", - "extends": ["../.oxlintrc.json"], + "extends": ["../.oxlintrc.base.json"], "rules": { "typescript/no-explicit-any": "off", "max-lines": "off", diff --git a/dev-packages/browser-integration-tests/suites/public-api/beforeSendSpan-streamed/init.js b/dev-packages/browser-integration-tests/suites/public-api/beforeSendSpan-streamed/init.js new file mode 100644 index 000000000000..f099c1f61c3e --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/public-api/beforeSendSpan-streamed/init.js @@ -0,0 +1,28 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [Sentry.browserTracingIntegration(), Sentry.spanStreamingIntegration()], + tracesSampleRate: 1, + beforeSendSpan: Sentry.withStreamedSpan(span => { + if (span.attributes['sentry.op'] === 'pageload') { + span.name = 'customPageloadSpanName'; + span.links = [ + { + context: { + traceId: '123', + spanId: '456', + }, + attributes: { + 'sentry.link.type': 'custom_link', + }, + }, + ]; + span.attributes['sentry.custom_attribute'] = 'customAttributeValue'; + span.status = 'something'; + } + return span; + }), +}); diff --git a/dev-packages/browser-integration-tests/suites/public-api/beforeSendSpan-streamed/test.ts b/dev-packages/browser-integration-tests/suites/public-api/beforeSendSpan-streamed/test.ts new file mode 100644 index 000000000000..ce07297c0a04 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/public-api/beforeSendSpan-streamed/test.ts @@ -0,0 +1,35 @@ +import { expect } from '@playwright/test'; +import { sentryTest } from '../../../utils/fixtures'; +import { shouldSkipTracingTest, testingCdnBundle } from '../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpan } from '../../../utils/spanUtils'; + +sentryTest('beforeSendSpan applies changes to streamed span', async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + const pageloadSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'pageload'); + + await page.goto(url); + + const pageloadSpan = await pageloadSpanPromise; + + expect(pageloadSpan.name).toBe('customPageloadSpanName'); + expect(pageloadSpan.links).toEqual([ + { + context: { + traceId: '123', + spanId: '456', + }, + attributes: { + 'sentry.link.type': { type: 'string', value: 'custom_link' }, + }, + }, + ]); + expect(pageloadSpan.attributes?.['sentry.custom_attribute']).toEqual({ + type: 'string', + value: 'customAttributeValue', + }); + // we allow overriding any kinds of fields on the span, so we have to expect invalid values + expect(pageloadSpan.status).toBe('something'); +}); diff --git a/dev-packages/browser-integration-tests/suites/public-api/startSpan/streamed/init.js b/dev-packages/browser-integration-tests/suites/public-api/startSpan/streamed/init.js new file mode 100644 index 000000000000..aaafd3396f14 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/public-api/startSpan/streamed/init.js @@ -0,0 +1,10 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [Sentry.spanStreamingIntegration()], + tracesSampleRate: 1.0, + debug: true, +}); diff --git a/dev-packages/browser-integration-tests/suites/public-api/startSpan/streamed/subject.js b/dev-packages/browser-integration-tests/suites/public-api/startSpan/streamed/subject.js new file mode 100644 index 000000000000..7e4395e06708 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/public-api/startSpan/streamed/subject.js @@ -0,0 +1,13 @@ +Sentry.startSpan({ name: 'test-span', op: 'test' }, () => { + Sentry.startSpan({ name: 'test-child-span', op: 'test-child' }, () => { + // noop + }); + + const inactiveSpan = Sentry.startInactiveSpan({ name: 'test-inactive-span' }); + inactiveSpan.end(); + + Sentry.startSpanManual({ name: 'test-manual-span' }, span => { + // noop + span.end(); + }); +}); diff --git a/dev-packages/browser-integration-tests/suites/public-api/startSpan/streamed/test.ts b/dev-packages/browser-integration-tests/suites/public-api/startSpan/streamed/test.ts new file mode 100644 index 000000000000..b5f8f41ab4b4 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/public-api/startSpan/streamed/test.ts @@ -0,0 +1,217 @@ +import { expect } from '@playwright/test'; +import { + SDK_VERSION, + SEMANTIC_ATTRIBUTE_SENTRY_OP, + SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, + SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, + SEMANTIC_ATTRIBUTE_SENTRY_SDK_NAME, + SEMANTIC_ATTRIBUTE_SENTRY_SDK_VERSION, + SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID, + SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME, + SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, +} from '@sentry/core'; +import { sentryTest } from '../../../../utils/fixtures'; +import { shouldSkipTracingTest, testingCdnBundle } from '../../../../utils/helpers'; +import { waitForStreamedSpanEnvelope } from '../../../../utils/spanUtils'; + +sentryTest( + 'sends a streamed span envelope if spanStreamingIntegration is enabled', + async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const spanEnvelopePromise = waitForStreamedSpanEnvelope(page); + + const url = await getLocalTestUrl({ testDir: __dirname }); + await page.goto(url); + + const spanEnvelope = await spanEnvelopePromise; + + const envelopeHeader = spanEnvelope[0]; + const envelopeItem = spanEnvelope[1]; + const spans = envelopeItem[0][1].items; + + expect(envelopeHeader).toEqual({ + sdk: { + name: 'sentry.javascript.browser', + version: SDK_VERSION, + }, + sent_at: expect.any(String), + trace: { + environment: 'production', + public_key: 'public', + sample_rand: expect.any(String), + sample_rate: '1', + sampled: 'true', + trace_id: expect.stringMatching(/^[\da-f]{32}$/), + transaction: 'test-span', + }, + }); + + const numericSampleRand = parseFloat(envelopeHeader.trace!.sample_rand!); + const traceId = envelopeHeader.trace!.trace_id; + + expect(Number.isNaN(numericSampleRand)).toBe(false); + + expect(envelopeItem).toEqual([ + [ + { content_type: 'application/vnd.sentry.items.span.v2+json', item_count: 4, type: 'span' }, + { + items: expect.any(Array), + }, + ], + ]); + + const segmentSpanId = spans.find(s => !!s.is_segment)?.span_id; + expect(segmentSpanId).toBeDefined(); + + expect(spans).toEqual([ + { + attributes: { + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: { + type: 'string', + value: 'test-child', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: { + type: 'string', + value: 'manual', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_NAME]: { + type: 'string', + value: 'sentry.javascript.browser', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_VERSION]: { + type: 'string', + value: SDK_VERSION, + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID]: { + type: 'string', + value: segmentSpanId, + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME]: { + type: 'string', + value: 'test-span', + }, + }, + end_timestamp: expect.any(Number), + is_segment: false, + name: 'test-child-span', + parent_span_id: segmentSpanId, + span_id: expect.stringMatching(/^[\da-f]{16}$/), + start_timestamp: expect.any(Number), + status: 'ok', + trace_id: traceId, + }, + { + attributes: { + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: { + type: 'string', + value: 'manual', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_NAME]: { + type: 'string', + value: 'sentry.javascript.browser', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_VERSION]: { + type: 'string', + value: SDK_VERSION, + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID]: { + type: 'string', + value: segmentSpanId, + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME]: { + type: 'string', + value: 'test-span', + }, + }, + end_timestamp: expect.any(Number), + is_segment: false, + name: 'test-inactive-span', + parent_span_id: segmentSpanId, + span_id: expect.stringMatching(/^[\da-f]{16}$/), + start_timestamp: expect.any(Number), + status: 'ok', + trace_id: traceId, + }, + { + attributes: { + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: { + type: 'string', + value: 'manual', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_NAME]: { + type: 'string', + value: 'sentry.javascript.browser', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_VERSION]: { + type: 'string', + value: SDK_VERSION, + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID]: { + type: 'string', + value: segmentSpanId, + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME]: { + type: 'string', + value: 'test-span', + }, + }, + end_timestamp: expect.any(Number), + is_segment: false, + name: 'test-manual-span', + parent_span_id: segmentSpanId, + span_id: expect.stringMatching(/^[\da-f]{16}$/), + start_timestamp: expect.any(Number), + status: 'ok', + trace_id: traceId, + }, + { + attributes: { + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: { + type: 'string', + value: 'test', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: { + type: 'string', + value: 'manual', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: { + type: 'integer', + value: 1, + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_NAME]: { + type: 'string', + value: 'sentry.javascript.browser', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_VERSION]: { + type: 'string', + value: SDK_VERSION, + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID]: { + type: 'string', + value: segmentSpanId, + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME]: { + type: 'string', + value: 'test-span', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: { + type: 'string', + value: 'custom', + }, + 'sentry.span.source': { + type: 'string', + value: 'custom', + }, + }, + end_timestamp: expect.any(Number), + is_segment: true, + name: 'test-span', + span_id: segmentSpanId, + start_timestamp: expect.any(Number), + status: 'ok', + trace_id: traceId, + }, + ]); + }, +); diff --git a/dev-packages/browser-integration-tests/suites/tracing/ai-providers/google-genai/test.ts b/dev-packages/browser-integration-tests/suites/tracing/ai-providers/google-genai/test.ts index c5c269d435e3..c6c9001b3e45 100644 --- a/dev-packages/browser-integration-tests/suites/tracing/ai-providers/google-genai/test.ts +++ b/dev-packages/browser-integration-tests/suites/tracing/ai-providers/google-genai/test.ts @@ -20,7 +20,7 @@ sentryTest('manual Google GenAI instrumentation sends gen_ai transactions', asyn const eventData = envelopeRequestParser(req); // Verify it's a gen_ai transaction - expect(eventData.transaction).toBe('chat gemini-1.5-pro create'); + expect(eventData.transaction).toBe('chat gemini-1.5-pro'); expect(eventData.contexts?.trace?.op).toBe('gen_ai.chat'); expect(eventData.contexts?.trace?.origin).toBe('auto.ai.google_genai'); expect(eventData.contexts?.trace?.data).toMatchObject({ diff --git a/dev-packages/browser-integration-tests/suites/tracing/ai-providers/langchain/mocks.js b/dev-packages/browser-integration-tests/suites/tracing/ai-providers/langchain/mocks.js index e7d4dbf00961..4661e66f5652 100644 --- a/dev-packages/browser-integration-tests/suites/tracing/ai-providers/langchain/mocks.js +++ b/dev-packages/browser-integration-tests/suites/tracing/ai-providers/langchain/mocks.js @@ -1,3 +1,21 @@ +// Mock LangChain Embeddings for browser testing +export class MockOpenAIEmbeddings { + constructor(params) { + this.model = params.model; + this.dimensions = params.dimensions; + } + + async embedQuery(_text) { + await new Promise(resolve => setTimeout(resolve, 10)); + return [0.1, 0.2, 0.3]; + } + + async embedDocuments(documents) { + await new Promise(resolve => setTimeout(resolve, 10)); + return documents.map(() => [0.1, 0.2, 0.3]); + } +} + // Mock LangChain Chat Model for browser testing export class MockChatAnthropic { constructor(params) { diff --git a/dev-packages/browser-integration-tests/suites/tracing/ai-providers/langchain/subject.js b/dev-packages/browser-integration-tests/suites/tracing/ai-providers/langchain/subject.js index 3df04acd505b..73e62ab18516 100644 --- a/dev-packages/browser-integration-tests/suites/tracing/ai-providers/langchain/subject.js +++ b/dev-packages/browser-integration-tests/suites/tracing/ai-providers/langchain/subject.js @@ -1,5 +1,6 @@ import { createLangChainCallbackHandler } from '@sentry/browser'; -import { MockChatAnthropic } from './mocks.js'; +import { instrumentLangChainEmbeddings } from '@sentry/browser'; +import { MockChatAnthropic, MockOpenAIEmbeddings } from './mocks.js'; const callbackHandler = createLangChainCallbackHandler({ recordInputs: false, @@ -20,3 +21,11 @@ const response = await chatModel.invoke('What is the capital of France?', { }); console.log('Received response', response); + +// Test embeddings instrumentation +const embeddings = instrumentLangChainEmbeddings( + new MockOpenAIEmbeddings({ model: 'text-embedding-3-small', dimensions: 1536 }), +); + +const embedding = await embeddings.embedQuery('Hello world'); +console.log('Received embedding', embedding); diff --git a/dev-packages/browser-integration-tests/suites/tracing/ai-providers/langchain/test.ts b/dev-packages/browser-integration-tests/suites/tracing/ai-providers/langchain/test.ts index 9cc1cc9ff98b..e60f53b063a2 100644 --- a/dev-packages/browser-integration-tests/suites/tracing/ai-providers/langchain/test.ts +++ b/dev-packages/browser-integration-tests/suites/tracing/ai-providers/langchain/test.ts @@ -35,3 +35,29 @@ sentryTest('manual LangChain instrumentation sends gen_ai transactions', async ( 'gen_ai.usage.total_tokens': 25, }); }); + +sentryTest( + 'manual LangChain embeddings instrumentation sends gen_ai transactions', + async ({ getLocalTestUrl, page }) => { + const transactionPromise = waitForTransactionRequest(page, event => { + return !!event.transaction?.includes('text-embedding-3-small'); + }); + + const url = await getLocalTestUrl({ testDir: __dirname }); + await page.goto(url); + + const req = await transactionPromise; + + const eventData = envelopeRequestParser(req); + + expect(eventData.transaction).toBe('embeddings text-embedding-3-small'); + expect(eventData.contexts?.trace?.op).toBe('gen_ai.embeddings'); + expect(eventData.contexts?.trace?.origin).toBe('auto.ai.langchain'); + expect(eventData.contexts?.trace?.data).toMatchObject({ + 'gen_ai.operation.name': 'embeddings', + 'gen_ai.system': 'openai', + 'gen_ai.request.model': 'text-embedding-3-small', + 'gen_ai.request.dimensions': 1536, + }); + }, +); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/backgroundtab-pageload-streamed/init.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/backgroundtab-pageload-streamed/init.js new file mode 100644 index 000000000000..749560a5c459 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/backgroundtab-pageload-streamed/init.js @@ -0,0 +1,10 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [Sentry.browserTracingIntegration(), Sentry.spanStreamingIntegration()], + tracesSampleRate: 1, + debug: true, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/backgroundtab-pageload-streamed/subject.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/backgroundtab-pageload-streamed/subject.js new file mode 100644 index 000000000000..b657f38ac009 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/backgroundtab-pageload-streamed/subject.js @@ -0,0 +1,8 @@ +document.getElementById('go-background').addEventListener('click', () => { + setTimeout(() => { + Object.defineProperty(document, 'hidden', { value: true, writable: true }); + const ev = document.createEvent('Event'); + ev.initEvent('visibilitychange'); + document.dispatchEvent(ev); + }, 250); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/backgroundtab-pageload-streamed/template.html b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/backgroundtab-pageload-streamed/template.html new file mode 100644 index 000000000000..8083ddc80694 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/backgroundtab-pageload-streamed/template.html @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/backgroundtab-pageload-streamed/test.ts b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/backgroundtab-pageload-streamed/test.ts new file mode 100644 index 000000000000..10e58acb81ad --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/backgroundtab-pageload-streamed/test.ts @@ -0,0 +1,18 @@ +import { expect } from '@playwright/test'; +import { sentryTest } from '../../../../utils/fixtures'; +import { shouldSkipTracingTest, testingCdnBundle } from '../../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpan } from '../../../../utils/spanUtils'; + +sentryTest('finishes streamed pageload span when the page goes background', async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + const url = await getLocalTestUrl({ testDir: __dirname }); + const pageloadSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'pageload'); + + await page.goto(url); + await page.locator('#go-background').click(); + const pageloadSpan = await pageloadSpanPromise; + + // TODO: Is this what we want? + expect(pageloadSpan.status).toBe('ok'); + expect(pageloadSpan.attributes?.['sentry.cancellation_reason']?.value).toBe('document.hidden'); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/http-timings-streamed/init.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/http-timings-streamed/init.js new file mode 100644 index 000000000000..7eff1a54e9ff --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/http-timings-streamed/init.js @@ -0,0 +1,19 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [ + Sentry.browserTracingIntegration({ + idleTimeout: 1000, + _experiments: { + enableHTTPTimings: true, + }, + }), + Sentry.spanStreamingIntegration(), + ], + tracesSampleRate: 1, + traceLifecycle: 'stream', + debug: true, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/http-timings-streamed/subject.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/http-timings-streamed/subject.js new file mode 100644 index 000000000000..e19cc07e28f5 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/http-timings-streamed/subject.js @@ -0,0 +1,3 @@ +fetch('http://sentry-test-site.example/0').then( + fetch('http://sentry-test-site.example/1').then(fetch('http://sentry-test-site.example/2')), +); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/http-timings-streamed/test.ts b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/http-timings-streamed/test.ts new file mode 100644 index 000000000000..25d4ac497992 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/http-timings-streamed/test.ts @@ -0,0 +1,63 @@ +import { expect } from '@playwright/test'; +import { sentryTest } from '../../../../utils/fixtures'; +import { shouldSkipTracingTest, testingCdnBundle } from '../../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpans } from '../../../../utils/spanUtils'; + +sentryTest( + 'adds http timing to http.client spans in span streaming mode', + async ({ browserName, getLocalTestUrl, page }) => { + const supportedBrowsers = ['chromium', 'firefox']; + + sentryTest.skip(shouldSkipTracingTest() || !supportedBrowsers.includes(browserName) || testingCdnBundle()); + + await page.route('http://sentry-test-site.example/*', async route => { + const request = route.request(); + const postData = await request.postDataJSON(); + + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify(Object.assign({ id: 1 }, postData)), + }); + }); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + const spansPromise = waitForStreamedSpans(page, spans => spans.some(s => getSpanOp(s) === 'http.client')); + await page.goto(url); + + const requestSpans = (await spansPromise).filter(s => getSpanOp(s) === 'http.client'); + const pageloadSpan = (await spansPromise).find(s => getSpanOp(s) === 'pageload'); + + expect(pageloadSpan).toBeDefined(); + expect(requestSpans).toHaveLength(3); + + requestSpans?.forEach((span, index) => + expect(span).toMatchObject({ + name: `GET http://sentry-test-site.example/${index}`, + parent_span_id: pageloadSpan?.span_id, + span_id: expect.stringMatching(/[a-f\d]{16}/), + start_timestamp: expect.any(Number), + end_timestamp: expect.any(Number), + trace_id: pageloadSpan?.trace_id, + status: 'ok', + attributes: expect.objectContaining({ + 'http.request.redirect_start': expect.any(Object), + 'http.request.redirect_end': expect.any(Object), + 'http.request.worker_start': expect.any(Object), + 'http.request.fetch_start': expect.any(Object), + 'http.request.domain_lookup_start': expect.any(Object), + 'http.request.domain_lookup_end': expect.any(Object), + 'http.request.connect_start': expect.any(Object), + 'http.request.secure_connection_start': expect.any(Object), + 'http.request.connection_end': expect.any(Object), + 'http.request.request_start': expect.any(Object), + 'http.request.response_start': expect.any(Object), + 'http.request.response_end': expect.any(Object), + 'http.request.time_to_first_byte': expect.any(Object), + 'network.protocol.version': expect.any(Object), + }), + }), + ); + }, +); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/interactions-streamed/init.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/interactions-streamed/init.js new file mode 100644 index 000000000000..385e9ed6b6cf --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/interactions-streamed/init.js @@ -0,0 +1,18 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [ + Sentry.browserTracingIntegration({ + idleTimeout: 1000, + enableLongTask: false, + _experiments: { + enableInteractions: true, + }, + }), + Sentry.spanStreamingIntegration(), + ], + tracesSampleRate: 1, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/interactions-streamed/subject.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/interactions-streamed/subject.js new file mode 100644 index 000000000000..ff9057926396 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/interactions-streamed/subject.js @@ -0,0 +1,16 @@ +const blockUI = e => { + const startTime = Date.now(); + + function getElapsed() { + const time = Date.now(); + return time - startTime; + } + + while (getElapsed() < 70) { + // + } + + e.target.classList.add('clicked'); +}; + +document.querySelector('[data-test-id=interaction-button]').addEventListener('click', blockUI); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/interactions-streamed/template.html b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/interactions-streamed/template.html new file mode 100644 index 000000000000..64e944054632 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/interactions-streamed/template.html @@ -0,0 +1,14 @@ + + + + + + +
Rendered Before Long Task
+ + + + + diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/interactions-streamed/test.ts b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/interactions-streamed/test.ts new file mode 100644 index 000000000000..fd384d0d3ff9 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/interactions-streamed/test.ts @@ -0,0 +1,134 @@ +import { expect } from '@playwright/test'; +import { + SDK_VERSION, + SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON, + SEMANTIC_ATTRIBUTE_SENTRY_OP, + SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, + SEMANTIC_ATTRIBUTE_SENTRY_SDK_NAME, + SEMANTIC_ATTRIBUTE_SENTRY_SDK_VERSION, + SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID, + SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME, + SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, +} from '@sentry/core'; +import { sentryTest } from '../../../../utils/fixtures'; +import { shouldSkipTracingTest, testingCdnBundle } from '../../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpan, waitForStreamedSpans } from '../../../../utils/spanUtils'; + +sentryTest('captures streamed interaction span tree. @firefox', async ({ browserName, getLocalTestUrl, page }) => { + const supportedBrowsers = ['chromium', 'firefox']; + + sentryTest.skip(shouldSkipTracingTest() || !supportedBrowsers.includes(browserName) || testingCdnBundle()); + const url = await getLocalTestUrl({ testDir: __dirname }); + + const interactionSpansPromise = waitForStreamedSpans(page, spans => + spans.some(span => getSpanOp(span) === 'ui.action.click'), + ); + + const pageloadSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'pageload'); + + await page.goto(url); + + // wait for pageload span to finish before clicking the interaction button + const pageloadSpan = await pageloadSpanPromise; + + await page.locator('[data-test-id=interaction-button]').click(); + await page.locator('.clicked[data-test-id=interaction-button]').isVisible(); + + const interactionSpanTree = await interactionSpansPromise; + + const interactionSegmentSpan = interactionSpanTree.find(span => !!span.is_segment); + + expect(interactionSegmentSpan).toEqual({ + attributes: { + [SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON]: { + type: 'string', + value: 'idleTimeout', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: { + type: 'string', + value: 'ui.action.click', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: { + type: 'string', + value: 'manual', // TODO: This is incorrect but not from span streaming. + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_NAME]: { + type: 'string', + value: 'sentry.javascript.browser', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_VERSION]: { + type: 'string', + value: SDK_VERSION, + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID]: { + type: 'string', + value: interactionSegmentSpan!.span_id, + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME]: { + type: 'string', + value: '/index.html', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: { + type: 'string', + value: 'url', + }, + 'sentry.span.source': { + type: 'string', + value: 'url', + }, + }, + end_timestamp: expect.any(Number), + is_segment: true, + name: '/index.html', + span_id: interactionSegmentSpan!.span_id, + start_timestamp: expect.any(Number), + status: 'ok', + trace_id: pageloadSpan.trace_id, // same trace id as pageload + }); + + const loAFSpans = interactionSpanTree.filter(span => getSpanOp(span)?.startsWith('ui.long-animation-frame')); + expect(loAFSpans).toHaveLength(1); + + const interactionSpan = interactionSpanTree.find(span => getSpanOp(span) === 'ui.interaction.click'); + expect(interactionSpan).toEqual({ + attributes: { + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: { + type: 'string', + value: 'ui.interaction.click', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: { + type: 'string', + value: 'auto.ui.browser.metrics', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_NAME]: { + type: 'string', + value: 'sentry.javascript.browser', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_VERSION]: { + type: 'string', + value: SDK_VERSION, + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID]: { + type: 'string', + value: interactionSegmentSpan!.span_id, + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME]: { + type: 'string', + value: '/index.html', + }, + }, + end_timestamp: expect.any(Number), + is_segment: false, + name: 'body > button.clicked', + parent_span_id: interactionSegmentSpan!.span_id, + span_id: expect.stringMatching(/^[\da-f]{16}$/), + start_timestamp: expect.any(Number), + status: 'ok', + trace_id: pageloadSpan.trace_id, // same trace id as pageload + }); + + const interactionSpanDuration = (interactionSpan!.end_timestamp - interactionSpan!.start_timestamp) * 1000; + expect(interactionSpanDuration).toBeGreaterThan(65); + expect(interactionSpanDuration).toBeLessThan(200); + expect(interactionSpan?.status).toBe('ok'); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/default/init.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/default/init.js new file mode 100644 index 000000000000..63afee65329a --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/default/init.js @@ -0,0 +1,22 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [ + Sentry.browserTracingIntegration({ + linkPreviousTrace: 'in-memory', + consistentTraceSampling: true, + }), + Sentry.spanStreamingIntegration(), + ], + tracePropagationTargets: ['sentry-test-external.io'], + tracesSampler: ctx => { + if (ctx.attributes && ctx.attributes['sentry.origin'] === 'auto.pageload.browser') { + return 1; + } + return ctx.inheritOrSampleWith(0); + }, + debug: true, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/default/subject.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/default/subject.js new file mode 100644 index 000000000000..de60904fab3a --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/default/subject.js @@ -0,0 +1,17 @@ +const btn1 = document.getElementById('btn1'); + +const btn2 = document.getElementById('btn2'); + +btn1.addEventListener('click', () => { + Sentry.startNewTrace(() => { + Sentry.startSpan({ name: 'custom root span 1', op: 'custom' }, () => {}); + }); +}); + +btn2.addEventListener('click', () => { + Sentry.startNewTrace(() => { + Sentry.startSpan({ name: 'custom root span 2', op: 'custom' }, async () => { + await fetch('http://sentry-test-external.io'); + }); + }); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/default/template.html b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/default/template.html new file mode 100644 index 000000000000..f26a602c7c6f --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/default/template.html @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/default/test.ts b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/default/test.ts new file mode 100644 index 000000000000..a97e13a4890a --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/default/test.ts @@ -0,0 +1,153 @@ +import { expect } from '@playwright/test'; +import { extractTraceparentData, parseBaggageHeader, SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE } from '@sentry/core'; +import { sentryTest } from '../../../../../../utils/fixtures'; +import { shouldSkipTracingTest, testingCdnBundle, waitForTracingHeadersOnUrl } from '../../../../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpanEnvelope } from '../../../../../../utils/spanUtils'; + +sentryTest.describe('When `consistentTraceSampling` is `true`', () => { + sentryTest('continues sampling decision from initial pageload span', async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + const { pageloadSpan, pageloadSampleRand } = await sentryTest.step('Initial pageload', async () => { + const pageloadEnvelopePromise = waitForStreamedSpanEnvelope( + page, + env => !!env[1][0][1].items.find(s => getSpanOp(s) === 'pageload'), + ); + await page.goto(url); + + const envelope = await pageloadEnvelopePromise; + const pageloadSampleRand = Number(envelope[0].trace?.sample_rand); + const pageloadSpan = envelope[1][0][1].items.find(s => getSpanOp(s) === 'pageload')!; + + expect(pageloadSpan.attributes?.['sentry.sample_rate']?.value).toBe(1); + expect(Number.isNaN(pageloadSampleRand)).toBe(false); + expect(pageloadSampleRand).toBeGreaterThanOrEqual(0); + expect(pageloadSampleRand).toBeLessThanOrEqual(1); + + return { pageloadSpan, pageloadSampleRand }; + }); + + const customTraceSpan = await sentryTest.step('Custom trace', async () => { + const customEnvelopePromise = waitForStreamedSpanEnvelope( + page, + env => !!env[1][0][1].items.find(s => getSpanOp(s) === 'custom'), + ); + await page.locator('#btn1').click(); + const envelope = await customEnvelopePromise; + const span = envelope[1][0][1].items.find(s => getSpanOp(s) === 'custom')!; + + expect(span.trace_id).not.toEqual(pageloadSpan.trace_id); + // although we "continue the trace" from pageload, this is actually a root span, + // so there must not be a parent span id + expect(span.parent_span_id).toBeUndefined(); + + expect(Number(envelope[0].trace?.sample_rand)).toBe(pageloadSampleRand); + + return span; + }); + + await sentryTest.step('Navigation', async () => { + const navigationEnvelopePromise = waitForStreamedSpanEnvelope( + page, + env => !!env[1][0][1].items.find(s => getSpanOp(s) === 'navigation'), + ); + await page.goto(`${url}#foo`); + const envelope = await navigationEnvelopePromise; + const navSpan = envelope[1][0][1].items.find(s => getSpanOp(s) === 'navigation')!; + + expect(navSpan.trace_id).not.toEqual(customTraceSpan.trace_id); + expect(navSpan.trace_id).not.toEqual(pageloadSpan.trace_id); + + expect(navSpan.links).toEqual([ + { + trace_id: customTraceSpan.trace_id, + span_id: customTraceSpan.span_id, + sampled: true, + attributes: { + [SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE]: { + type: 'string', + value: 'previous_trace', + }, + }, + }, + ]); + expect(navSpan.parent_span_id).toBeUndefined(); + + expect(Number(envelope[0].trace?.sample_rand)).toBe(pageloadSampleRand); + }); + }); + + sentryTest('Propagates continued sampling decision to outgoing requests', async ({ page, getLocalTestUrl }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + const { pageloadSpan, pageloadSampleRand } = await sentryTest.step('Initial pageload', async () => { + const pageloadEnvelopePromise = waitForStreamedSpanEnvelope( + page, + env => !!env[1][0][1].items.find(s => getSpanOp(s) === 'pageload'), + ); + await page.goto(url); + + const envelope = await pageloadEnvelopePromise; + const pageloadSampleRand = Number(envelope[0].trace?.sample_rand); + + expect(Number(envelope[0].trace?.sample_rand)).toBe(pageloadSampleRand); + expect(pageloadSampleRand).toBeGreaterThanOrEqual(0); + expect(pageloadSampleRand).toBeLessThanOrEqual(1); + expect(Number.isNaN(pageloadSampleRand)).toBe(false); + + const pageloadSpan = envelope[1][0][1].items.find(s => getSpanOp(s) === 'pageload')!; + + expect(pageloadSpan.attributes?.['sentry.sample_rate']?.value).toBe(1); + + return { pageloadSpan, pageloadSampleRand }; + }); + + await sentryTest.step('Make fetch request', async () => { + const fetchEnvelopePromise = waitForStreamedSpanEnvelope( + page, + env => !!env[1][0][1].items.find(s => getSpanOp(s) === 'custom'), + ); + const tracingHeadersPromise = waitForTracingHeadersOnUrl(page, 'http://sentry-test-external.io'); + + await page.locator('#btn2').click(); + + const { baggage, sentryTrace } = await tracingHeadersPromise; + const fetchEnvelope = await fetchEnvelopePromise; + + const fetchTraceSampleRand = Number(fetchEnvelope[0].trace?.sample_rand); + const fetchTraceSpans = fetchEnvelope[1][0][1].items; + const fetchTraceSpan = fetchTraceSpans.find(s => getSpanOp(s) === 'custom')!; + const httpClientSpan = fetchTraceSpans.find(s => getSpanOp(s) === 'http.client'); + + expect(fetchTraceSampleRand).toBe(pageloadSampleRand); + + expect(fetchTraceSpan.attributes?.['sentry.sample_rate']?.value).toEqual( + pageloadSpan.attributes?.['sentry.sample_rate']?.value, + ); + expect(fetchTraceSpan.trace_id).not.toEqual(pageloadSpan.trace_id); + + expect(sentryTrace).toBeDefined(); + expect(baggage).toBeDefined(); + + expect(extractTraceparentData(sentryTrace)).toEqual({ + traceId: fetchTraceSpan.trace_id, + parentSpanId: httpClientSpan?.span_id, + parentSampled: true, + }); + + expect(parseBaggageHeader(baggage)).toEqual({ + 'sentry-environment': 'production', + 'sentry-public_key': 'public', + 'sentry-sample_rand': `${pageloadSampleRand}`, + 'sentry-sample_rate': '1', + 'sentry-sampled': 'true', + 'sentry-trace_id': fetchTraceSpan.trace_id, + 'sentry-transaction': 'custom root span 2', + }); + }); + }); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta-negative/init.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta-negative/init.js new file mode 100644 index 000000000000..d570ac45144c --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta-negative/init.js @@ -0,0 +1,19 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [ + Sentry.browserTracingIntegration({ + linkPreviousTrace: 'in-memory', + consistentTraceSampling: true, + }), + Sentry.spanStreamingIntegration(), + ], + traceLifecycle: 'stream', + tracePropagationTargets: ['sentry-test-external.io'], + tracesSampleRate: 1, + debug: true, + sendClientReports: true, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta-negative/subject.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta-negative/subject.js new file mode 100644 index 000000000000..de60904fab3a --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta-negative/subject.js @@ -0,0 +1,17 @@ +const btn1 = document.getElementById('btn1'); + +const btn2 = document.getElementById('btn2'); + +btn1.addEventListener('click', () => { + Sentry.startNewTrace(() => { + Sentry.startSpan({ name: 'custom root span 1', op: 'custom' }, () => {}); + }); +}); + +btn2.addEventListener('click', () => { + Sentry.startNewTrace(() => { + Sentry.startSpan({ name: 'custom root span 2', op: 'custom' }, async () => { + await fetch('http://sentry-test-external.io'); + }); + }); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta-negative/template.html b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta-negative/template.html new file mode 100644 index 000000000000..6347fa37fc00 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta-negative/template.html @@ -0,0 +1,13 @@ + + + + + + + + + + diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta-negative/test.ts b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta-negative/test.ts new file mode 100644 index 000000000000..ea50f09f2361 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta-negative/test.ts @@ -0,0 +1,99 @@ +import { expect } from '@playwright/test'; +import type { ClientReport } from '@sentry/core'; +import { extractTraceparentData, parseBaggageHeader } from '@sentry/core'; +import type { SerializedStreamedSpan } from '@sentry/core/src'; +import { sentryTest } from '../../../../../../utils/fixtures'; +import { + envelopeRequestParser, + hidePage, + shouldSkipTracingTest, + testingCdnBundle, + waitForClientReportRequest, + waitForTracingHeadersOnUrl, +} from '../../../../../../utils/helpers'; +import { observeStreamedSpan } from '../../../../../../utils/spanUtils'; + +const metaTagSampleRand = 0.9; +const metaTagSampleRate = 0.2; +const metaTagTraceId = '12345678901234567890123456789012'; + +sentryTest.describe('When `consistentTraceSampling` is `true` and page contains tags', () => { + sentryTest( + 'Continues negative sampling decision from meta tag across all traces and downstream propagations', + async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + const spansReceived: SerializedStreamedSpan[] = []; + observeStreamedSpan(page, span => { + spansReceived.push(span); + return false; + }); + + const clientReportPromise = waitForClientReportRequest(page); + + await sentryTest.step('Initial pageload', async () => { + await page.goto(url); + expect(spansReceived).toHaveLength(0); + }); + + await sentryTest.step('Custom instrumented button click', async () => { + await page.locator('#btn1').click(); + expect(spansReceived).toHaveLength(0); + }); + + await sentryTest.step('Navigation', async () => { + await page.goto(`${url}#foo`); + expect(spansReceived).toHaveLength(0); + }); + + await sentryTest.step('Make fetch request', async () => { + const tracingHeadersPromise = waitForTracingHeadersOnUrl(page, 'http://sentry-test-external.io'); + + await page.locator('#btn2').click(); + const { baggage, sentryTrace } = await tracingHeadersPromise; + + expect(sentryTrace).toBeDefined(); + expect(baggage).toBeDefined(); + + expect(extractTraceparentData(sentryTrace)).toEqual({ + traceId: expect.not.stringContaining(metaTagTraceId), + parentSpanId: expect.stringMatching(/^[\da-f]{16}$/), + parentSampled: false, + }); + + expect(parseBaggageHeader(baggage)).toEqual({ + 'sentry-environment': 'production', + 'sentry-public_key': 'public', + 'sentry-sample_rand': `${metaTagSampleRand}`, + 'sentry-sample_rate': `${metaTagSampleRate}`, + 'sentry-sampled': 'false', + 'sentry-trace_id': expect.not.stringContaining(metaTagTraceId), + 'sentry-transaction': 'custom root span 2', + }); + + expect(spansReceived).toHaveLength(0); + }); + + await sentryTest.step('Client report', async () => { + await hidePage(page); + const clientReport = envelopeRequestParser(await clientReportPromise); + expect(clientReport).toEqual({ + timestamp: expect.any(Number), + discarded_events: [ + { + category: 'span', + quantity: expect.any(Number), + reason: 'sample_rate', + }, + ], + }); + // exact number depends on performance observer emissions + expect(clientReport.discarded_events[0].quantity).toBeGreaterThanOrEqual(10); + }); + + expect(spansReceived).toHaveLength(0); + }, + ); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta-precedence/init.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta-precedence/init.js new file mode 100644 index 000000000000..177fe4c4aeaf --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta-precedence/init.js @@ -0,0 +1,20 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [ + Sentry.browserTracingIntegration({ + linkPreviousTrace: 'session-storage', + consistentTraceSampling: true, + }), + Sentry.spanStreamingIntegration(), + ], + tracePropagationTargets: ['sentry-test-external.io'], + tracesSampler: ({ inheritOrSampleWith }) => { + return inheritOrSampleWith(0); + }, + debug: true, + sendClientReports: true, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta-precedence/page-1.html b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta-precedence/page-1.html new file mode 100644 index 000000000000..9a0719b7e505 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta-precedence/page-1.html @@ -0,0 +1,15 @@ + + + + + + + + +

Another Page

+ Go To the next page + + diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta-precedence/page-2.html b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta-precedence/page-2.html new file mode 100644 index 000000000000..27cd47bba7c1 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta-precedence/page-2.html @@ -0,0 +1,10 @@ + + + + + + +

Another Page

+ Go To the next page + + diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta-precedence/subject.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta-precedence/subject.js new file mode 100644 index 000000000000..ec0264fa49ef --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta-precedence/subject.js @@ -0,0 +1,17 @@ +const btn1 = document.getElementById('btn1'); + +const btn2 = document.getElementById('btn2'); + +btn1?.addEventListener('click', () => { + Sentry.startNewTrace(() => { + Sentry.startSpan({ name: 'custom root span 1', op: 'custom' }, () => {}); + }); +}); + +btn2?.addEventListener('click', () => { + Sentry.startNewTrace(() => { + Sentry.startSpan({ name: 'custom root span 2', op: 'custom' }, async () => { + await fetch('http://sentry-test-external.io'); + }); + }); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta-precedence/template.html b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta-precedence/template.html new file mode 100644 index 000000000000..eab1fecca6c4 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta-precedence/template.html @@ -0,0 +1,14 @@ + + + + + + + + Go To another page + + + diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta-precedence/test.ts b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta-precedence/test.ts new file mode 100644 index 000000000000..367b48e70eda --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta-precedence/test.ts @@ -0,0 +1,118 @@ +import { expect } from '@playwright/test'; +import type { ClientReport } from '@sentry/core'; +import { extractTraceparentData, parseBaggageHeader } from '@sentry/core'; +import { sentryTest } from '../../../../../../utils/fixtures'; +import { + envelopeRequestParser, + hidePage, + shouldSkipTracingTest, + testingCdnBundle, + waitForClientReportRequest, + waitForTracingHeadersOnUrl, +} from '../../../../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpanEnvelope } from '../../../../../../utils/spanUtils'; + +const metaTagSampleRand = 0.9; +const metaTagSampleRate = 0.2; +const metaTagTraceIdIndex = '12345678901234567890123456789012'; +const metaTagTraceIdPage1 = 'a2345678901234567890123456789012'; + +sentryTest.describe('When `consistentTraceSampling` is `true` and page contains tags', () => { + sentryTest( + 'meta tag decision has precedence over sampling decision from previous trace in session storage', + async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + const clientReportPromise = waitForClientReportRequest(page); + + await sentryTest.step('Initial pageload', async () => { + // negative sampling decision -> no pageload span + await page.goto(url); + }); + + await sentryTest.step('Make fetch request', async () => { + // The fetch requests starts a new trace on purpose. So we only want the + // sampling decision and rand to be the same as from the meta tag but not the trace id or DSC + const tracingHeadersPromise = waitForTracingHeadersOnUrl(page, 'http://sentry-test-external.io'); + + await page.locator('#btn2').click(); + + const { baggage, sentryTrace } = await tracingHeadersPromise; + + expect(sentryTrace).toBeDefined(); + expect(baggage).toBeDefined(); + + expect(extractTraceparentData(sentryTrace)).toEqual({ + traceId: expect.not.stringContaining(metaTagTraceIdIndex), + parentSpanId: expect.stringMatching(/^[\da-f]{16}$/), + parentSampled: false, + }); + + expect(parseBaggageHeader(baggage)).toEqual({ + 'sentry-environment': 'production', + 'sentry-public_key': 'public', + 'sentry-sample_rand': `${metaTagSampleRand}`, + 'sentry-sample_rate': `${metaTagSampleRate}`, + 'sentry-sampled': 'false', + 'sentry-trace_id': expect.not.stringContaining(metaTagTraceIdIndex), + 'sentry-transaction': 'custom root span 2', + }); + }); + + await sentryTest.step('Client report', async () => { + await hidePage(page); + + const clientReport = envelopeRequestParser(await clientReportPromise); + expect(clientReport).toEqual({ + timestamp: expect.any(Number), + discarded_events: [ + { + category: 'span', + quantity: expect.any(Number), + reason: 'sample_rate', + }, + ], + }); + // exact number depends on performance observer emissions + expect(clientReport.discarded_events[0].quantity).toBeGreaterThanOrEqual(3); + }); + + await sentryTest.step('Navigate to another page with meta tags', async () => { + const page1PageloadEnvelopePromise = waitForStreamedSpanEnvelope( + page, + env => !!env[1][0][1].items.find(s => getSpanOp(s) === 'pageload' && s.trace_id === metaTagTraceIdPage1), + ); + await page.locator('a').click(); + + const envelope = await page1PageloadEnvelopePromise; + const pageloadSpan = envelope[1][0][1].items.find(s => getSpanOp(s) === 'pageload')!; + + expect(Number(envelope[0].trace?.sample_rand)).toBe(0.12); + expect(Number(envelope[0].trace?.sample_rate)).toBe(0.2); + expect(pageloadSpan.trace_id).toEqual(metaTagTraceIdPage1); + }); + + await sentryTest.step('Navigate to another page without meta tags', async () => { + const page2PageloadEnvelopePromise = waitForStreamedSpanEnvelope( + page, + env => + !!env[1][0][1].items.find( + s => + getSpanOp(s) === 'pageload' && s.trace_id !== metaTagTraceIdPage1 && s.trace_id !== metaTagTraceIdIndex, + ), + ); + await page.locator('a').click(); + + const envelope = await page2PageloadEnvelopePromise; + const pageloadSpan = envelope[1][0][1].items.find(s => getSpanOp(s) === 'pageload')!; + + expect(Number(envelope[0].trace?.sample_rand)).toBe(0.12); + expect(Number(envelope[0].trace?.sample_rate)).toBe(0.2); + expect(pageloadSpan.trace_id).not.toEqual(metaTagTraceIdPage1); + expect(pageloadSpan.trace_id).not.toEqual(metaTagTraceIdIndex); + }); + }, + ); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta/init.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta/init.js new file mode 100644 index 000000000000..a1ddc5465950 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta/init.js @@ -0,0 +1,18 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [ + Sentry.browserTracingIntegration({ + linkPreviousTrace: 'in-memory', + consistentTraceSampling: true, + }), + Sentry.spanStreamingIntegration(), + ], + tracePropagationTargets: ['sentry-test-external.io'], + // only take into account sampling from meta tag; otherwise sample negatively + tracesSampleRate: 0, + debug: true, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta/subject.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta/subject.js new file mode 100644 index 000000000000..de60904fab3a --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta/subject.js @@ -0,0 +1,17 @@ +const btn1 = document.getElementById('btn1'); + +const btn2 = document.getElementById('btn2'); + +btn1.addEventListener('click', () => { + Sentry.startNewTrace(() => { + Sentry.startSpan({ name: 'custom root span 1', op: 'custom' }, () => {}); + }); +}); + +btn2.addEventListener('click', () => { + Sentry.startNewTrace(() => { + Sentry.startSpan({ name: 'custom root span 2', op: 'custom' }, async () => { + await fetch('http://sentry-test-external.io'); + }); + }); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta/template.html b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta/template.html new file mode 100644 index 000000000000..7ceca6fec2a3 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta/template.html @@ -0,0 +1,13 @@ + + + + + + + + + + diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta/test.ts b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta/test.ts new file mode 100644 index 000000000000..08cee9111b8a --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/meta/test.ts @@ -0,0 +1,171 @@ +import { expect } from '@playwright/test'; +import { + extractTraceparentData, + parseBaggageHeader, + SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE, +} from '@sentry/core'; +import { sentryTest } from '../../../../../../utils/fixtures'; +import { shouldSkipTracingTest, testingCdnBundle, waitForTracingHeadersOnUrl } from '../../../../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpanEnvelope } from '../../../../../../utils/spanUtils'; + +const metaTagSampleRand = 0.051121; +const metaTagSampleRate = 0.2; + +sentryTest.describe('When `consistentTraceSampling` is `true` and page contains tags', () => { + sentryTest('Continues sampling decision across all traces from meta tag', async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + const pageloadSpan = await sentryTest.step('Initial pageload', async () => { + const pageloadEnvelopePromise = waitForStreamedSpanEnvelope( + page, + env => !!env[1][0][1].items.find(s => getSpanOp(s) === 'pageload'), + ); + + await page.goto(url); + + const envelope = await pageloadEnvelopePromise; + const span = envelope[1][0][1].items.find(s => getSpanOp(s) === 'pageload')!; + + expect(Number(envelope[0].trace?.sample_rand)).toBe(metaTagSampleRand); + expect(Number(envelope[0].trace?.sample_rate)).toBe(metaTagSampleRate); + + // since the local sample rate was not applied, the sample rate attribute shouldn't be set + expect(span.attributes?.['sentry.sample_rate']).toBeUndefined(); + expect(span.attributes?.[SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE]).toBeUndefined(); + + return span; + }); + + const customTraceSpan = await sentryTest.step('Custom trace', async () => { + const customEnvelopePromise = waitForStreamedSpanEnvelope( + page, + env => !!env[1][0][1].items.find(s => getSpanOp(s) === 'custom'), + ); + + await page.locator('#btn1').click(); + + const envelope = await customEnvelopePromise; + const span = envelope[1][0][1].items.find(s => getSpanOp(s) === 'custom')!; + + expect(span.trace_id).not.toEqual(pageloadSpan.trace_id); + expect(span.parent_span_id).toBeUndefined(); + + expect(Number(envelope[0].trace?.sample_rand)).toBe(metaTagSampleRand); + expect(Number(envelope[0].trace?.sample_rate)).toBe(metaTagSampleRate); + expect(envelope[0].trace?.sampled).toBe('true'); + + // since the local sample rate was not applied, the sample rate attribute shouldn't be set + expect(span.attributes?.['sentry.sample_rate']).toBeUndefined(); + + // but we need to set this attribute to still be able to correctly add the sample rate to the DSC (checked above in trace header) + expect(span.attributes?.[SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE]?.value).toBe(metaTagSampleRate); + + return span; + }); + + await sentryTest.step('Navigation', async () => { + const navigationEnvelopePromise = waitForStreamedSpanEnvelope( + page, + env => !!env[1][0][1].items.find(s => getSpanOp(s) === 'navigation'), + ); + + await page.goto(`${url}#foo`); + + const envelope = await navigationEnvelopePromise; + const navSpan = envelope[1][0][1].items.find(s => getSpanOp(s) === 'navigation')!; + + expect(navSpan.trace_id).not.toEqual(pageloadSpan.trace_id); + expect(navSpan.trace_id).not.toEqual(customTraceSpan.trace_id); + + expect(navSpan.parent_span_id).toBeUndefined(); + + expect(Number(envelope[0].trace?.sample_rand)).toEqual(metaTagSampleRand); + expect(Number(envelope[0].trace?.sample_rate)).toEqual(metaTagSampleRate); + expect(envelope[0].trace?.sampled).toEqual('true'); + + // since the local sample rate was not applied, the sample rate attribute shouldn't be set + expect(navSpan.attributes?.['sentry.sample_rate']).toBeUndefined(); + + // but we need to set this attribute to still be able to correctly add the sample rate to the DSC (checked above in trace header) + expect(navSpan.attributes?.[SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE]?.value).toBe(metaTagSampleRate); + }); + }); + + sentryTest( + 'Propagates continued tag sampling decision to outgoing requests', + async ({ page, getLocalTestUrl }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + const pageloadSpan = await sentryTest.step('Initial pageload', async () => { + const pageloadEnvelopePromise = waitForStreamedSpanEnvelope( + page, + env => !!env[1][0][1].items.find(s => getSpanOp(s) === 'pageload'), + ); + + await page.goto(url); + + const envelope = await pageloadEnvelopePromise; + const span = envelope[1][0][1].items.find(s => getSpanOp(s) === 'pageload')!; + + expect(Number(envelope[0].trace?.sample_rand)).toBe(metaTagSampleRand); + expect(Number(envelope[0].trace?.sample_rate)).toBe(metaTagSampleRate); + + // since the local sample rate was not applied, the sample rate attribute shouldn't be set + expect(span.attributes?.['sentry.sample_rate']).toBeUndefined(); + expect(span.attributes?.[SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE]).toBeUndefined(); + + return span; + }); + + await sentryTest.step('Make fetch request', async () => { + const fetchEnvelopePromise = waitForStreamedSpanEnvelope( + page, + env => !!env[1][0][1].items.find(s => getSpanOp(s) === 'custom'), + ); + const tracingHeadersPromise = waitForTracingHeadersOnUrl(page, 'http://sentry-test-external.io'); + + await page.locator('#btn2').click(); + + const { baggage, sentryTrace } = await tracingHeadersPromise; + const fetchEnvelope = await fetchEnvelopePromise; + + const fetchTraceSampleRand = Number(fetchEnvelope[0].trace?.sample_rand); + const fetchTraceSpans = fetchEnvelope[1][0][1].items; + const fetchTraceSpan = fetchTraceSpans.find(s => getSpanOp(s) === 'custom')!; + const httpClientSpan = fetchTraceSpans.find(s => getSpanOp(s) === 'http.client'); + + expect(fetchTraceSampleRand).toEqual(metaTagSampleRand); + + expect(fetchTraceSpan.attributes?.['sentry.sample_rate']).toBeUndefined(); + expect(fetchTraceSpan.attributes?.[SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE]?.value).toBe( + metaTagSampleRate, + ); + + expect(fetchTraceSpan.trace_id).not.toEqual(pageloadSpan.trace_id); + + expect(sentryTrace).toBeDefined(); + expect(baggage).toBeDefined(); + + expect(extractTraceparentData(sentryTrace)).toEqual({ + traceId: fetchTraceSpan.trace_id, + parentSpanId: httpClientSpan?.span_id, + parentSampled: true, + }); + + expect(parseBaggageHeader(baggage)).toEqual({ + 'sentry-environment': 'production', + 'sentry-public_key': 'public', + 'sentry-sample_rand': `${metaTagSampleRand}`, + 'sentry-sample_rate': `${metaTagSampleRate}`, + 'sentry-sampled': 'true', + 'sentry-trace_id': fetchTraceSpan.trace_id, + 'sentry-transaction': 'custom root span 2', + }); + }); + }, + ); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/tracesSampler-precedence/init.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/tracesSampler-precedence/init.js new file mode 100644 index 000000000000..623db0ecc028 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/tracesSampler-precedence/init.js @@ -0,0 +1,29 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [ + Sentry.browserTracingIntegration({ + linkPreviousTrace: 'in-memory', + consistentTraceSampling: true, + enableInp: false, + }), + Sentry.spanStreamingIntegration(), + ], + tracePropagationTargets: ['sentry-test-external.io'], + tracesSampler: ctx => { + if (ctx.attributes && ctx.attributes['sentry.origin'] === 'auto.pageload.browser') { + return 1; + } + if (ctx.name === 'custom root span 1') { + return 0; + } + if (ctx.name === 'custom root span 2') { + return 1; + } + return ctx.inheritOrSampleWith(0); + }, + debug: true, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/tracesSampler-precedence/subject.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/tracesSampler-precedence/subject.js new file mode 100644 index 000000000000..de60904fab3a --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/tracesSampler-precedence/subject.js @@ -0,0 +1,17 @@ +const btn1 = document.getElementById('btn1'); + +const btn2 = document.getElementById('btn2'); + +btn1.addEventListener('click', () => { + Sentry.startNewTrace(() => { + Sentry.startSpan({ name: 'custom root span 1', op: 'custom' }, () => {}); + }); +}); + +btn2.addEventListener('click', () => { + Sentry.startNewTrace(() => { + Sentry.startSpan({ name: 'custom root span 2', op: 'custom' }, async () => { + await fetch('http://sentry-test-external.io'); + }); + }); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/tracesSampler-precedence/template.html b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/tracesSampler-precedence/template.html new file mode 100644 index 000000000000..f26a602c7c6f --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/tracesSampler-precedence/template.html @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/tracesSampler-precedence/test.ts b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/tracesSampler-precedence/test.ts new file mode 100644 index 000000000000..d661a4548e94 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/consistent-sampling/tracesSampler-precedence/test.ts @@ -0,0 +1,152 @@ +import { expect } from '@playwright/test'; +import { SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE } from '@sentry/browser'; +import type { ClientReport } from '@sentry/core'; +import { SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE } from '@sentry/core'; +import { sentryTest } from '../../../../../../utils/fixtures'; +import { + envelopeRequestParser, + hidePage, + shouldSkipTracingTest, + testingCdnBundle, + waitForClientReportRequest, +} from '../../../../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpanEnvelope } from '../../../../../../utils/spanUtils'; + +/** + * This test demonstrates that: + * - explicit sampling decisions in `tracesSampler` has precedence over consistent sampling + * - despite consistentTraceSampling being activated, there are still a lot of cases where the trace chain can break + */ +sentryTest.describe('When `consistentTraceSampling` is `true`', () => { + sentryTest('explicit sampling decisions in `tracesSampler` have precedence', async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + const { pageloadSpan } = await sentryTest.step('Initial pageload', async () => { + const pageloadEnvelopePromise = waitForStreamedSpanEnvelope( + page, + env => !!env[1][0][1].items.find(s => getSpanOp(s) === 'pageload'), + ); + await page.goto(url); + + const envelope = await pageloadEnvelopePromise; + const pageloadSpan = envelope[1][0][1].items.find(s => getSpanOp(s) === 'pageload')!; + + expect(pageloadSpan.attributes?.[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]?.value).toBe(1); + expect(Number(envelope[0].trace?.sample_rand)).toBeGreaterThanOrEqual(0); + + return { pageloadSpan }; + }); + + await sentryTest.step('Custom trace is sampled negatively (explicitly in tracesSampler)', async () => { + const clientReportPromise = waitForClientReportRequest(page); + + await page.locator('#btn1').click(); + + await page.waitForTimeout(500); + await hidePage(page); + + const clientReport = envelopeRequestParser(await clientReportPromise); + + expect(clientReport).toEqual({ + timestamp: expect.any(Number), + discarded_events: [ + { + category: 'span', + quantity: 1, + reason: 'sample_rate', + }, + ], + }); + }); + + await sentryTest.step('Subsequent navigation trace is also sampled negatively', async () => { + const clientReportPromise = waitForClientReportRequest(page); + + await page.goto(`${url}#foo`); + + await page.waitForTimeout(500); + + await hidePage(page); + + const clientReport = envelopeRequestParser(await clientReportPromise); + + expect(clientReport).toEqual({ + timestamp: expect.any(Number), + discarded_events: [ + { + category: 'span', + quantity: 1, + reason: 'sample_rate', + }, + ], + }); + }); + + const { customTrace2Span } = await sentryTest.step( + 'Custom trace 2 is sampled positively (explicitly in tracesSampler)', + async () => { + const customEnvelopePromise = waitForStreamedSpanEnvelope( + page, + env => !!env[1][0][1].items.find(s => getSpanOp(s) === 'custom'), + ); + + await page.locator('#btn2').click(); + + const envelope = await customEnvelopePromise; + const customTrace2Span = envelope[1][0][1].items.find(s => getSpanOp(s) === 'custom')!; + + expect(customTrace2Span.attributes?.[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]?.value).toBe(1); + expect(customTrace2Span.trace_id).not.toEqual(pageloadSpan.trace_id); + expect(customTrace2Span.parent_span_id).toBeUndefined(); + + expect(customTrace2Span.links).toEqual([ + { + attributes: { + [SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE]: { + type: 'string', + value: 'previous_trace', + }, + }, + sampled: false, + span_id: expect.stringMatching(/^[\da-f]{16}$/), + trace_id: expect.stringMatching(/^[\da-f]{32}$/), + }, + ]); + + return { customTrace2Span }; + }, + ); + + await sentryTest.step('Navigation trace is sampled positively (inherited from previous trace)', async () => { + const navigationEnvelopePromise = waitForStreamedSpanEnvelope( + page, + env => env[0].trace?.sampled === 'true' && !!env[1][0][1].items.find(s => getSpanOp(s) === 'navigation'), + ); + + await page.goto(`${url}#bar`); + + const envelope = await navigationEnvelopePromise; + const navigationSpan = envelope[1][0][1].items.find(s => getSpanOp(s) === 'navigation')!; + + expect(navigationSpan.attributes?.[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]?.value).toBe(1); + expect(navigationSpan.trace_id).not.toEqual(customTrace2Span.trace_id); + expect(navigationSpan.parent_span_id).toBeUndefined(); + + expect(navigationSpan.links).toEqual([ + { + attributes: { + [SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE]: { + type: 'string', + value: 'previous_trace', + }, + }, + sampled: true, + span_id: customTrace2Span.span_id, + trace_id: customTrace2Span.trace_id, + }, + ]); + }); + }); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/custom-trace/subject.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/custom-trace/subject.js new file mode 100644 index 000000000000..2a929a7e5083 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/custom-trace/subject.js @@ -0,0 +1,14 @@ +const btn1 = document.getElementById('btn1'); +const btn2 = document.getElementById('btn2'); + +btn1.addEventListener('click', () => { + Sentry.startNewTrace(() => { + Sentry.startSpan({ name: 'custom root span 1', op: 'custom' }, () => {}); + }); +}); + +btn2.addEventListener('click', () => { + Sentry.startNewTrace(() => { + Sentry.startSpan({ name: 'custom root span 2', op: 'custom' }, () => {}); + }); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/custom-trace/template.html b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/custom-trace/template.html new file mode 100644 index 000000000000..f26a602c7c6f --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/custom-trace/template.html @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/custom-trace/test.ts b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/custom-trace/test.ts new file mode 100644 index 000000000000..d6e45901f959 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/custom-trace/test.ts @@ -0,0 +1,63 @@ +import { expect } from '@playwright/test'; +import { SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE } from '@sentry/core'; +import { sentryTest } from '../../../../../utils/fixtures'; +import { shouldSkipTracingTest, testingCdnBundle } from '../../../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpan } from '../../../../../utils/spanUtils'; + +sentryTest('manually started custom traces are linked correctly in the chain', async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + const pageloadSpan = await sentryTest.step('Initial pageload', async () => { + const pageloadSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'pageload'); + await page.goto(url); + return pageloadSpanPromise; + }); + + const customTraceSpan = await sentryTest.step('Custom trace', async () => { + const customSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'custom'); + await page.locator('#btn1').click(); + const span = await customSpanPromise; + + expect(span.trace_id).not.toEqual(pageloadSpan.trace_id); + expect(span.links).toEqual([ + { + trace_id: pageloadSpan.trace_id, + span_id: pageloadSpan.span_id, + sampled: true, + attributes: { + [SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE]: { + type: 'string', + value: 'previous_trace', + }, + }, + }, + ]); + + return span; + }); + + await sentryTest.step('Navigation', async () => { + const navigationSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'navigation'); + await page.goto(`${url}#foo`); + const navSpan = await navigationSpanPromise; + + expect(navSpan.trace_id).not.toEqual(customTraceSpan.trace_id); + expect(navSpan.trace_id).not.toEqual(pageloadSpan.trace_id); + + expect(navSpan.links).toEqual([ + { + trace_id: customTraceSpan.trace_id, + span_id: customTraceSpan.span_id, + sampled: true, + attributes: { + [SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE]: { + type: 'string', + value: 'previous_trace', + }, + }, + }, + ]); + }); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/default/test.ts b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/default/test.ts new file mode 100644 index 000000000000..80e500437f79 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/default/test.ts @@ -0,0 +1,95 @@ +import { expect } from '@playwright/test'; +import { SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE } from '@sentry/core'; +import { sentryTest } from '../../../../../utils/fixtures'; +import { shouldSkipTracingTest, testingCdnBundle } from '../../../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpan } from '../../../../../utils/spanUtils'; + +sentryTest("navigation spans link back to previous trace's root span", async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + const pageloadSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'pageload'); + await page.goto(url); + const pageloadSpan = await pageloadSpanPromise; + + const navigation1SpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'navigation'); + await page.goto(`${url}#foo`); + const navigation1Span = await navigation1SpanPromise; + + const navigation2SpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'navigation'); + await page.goto(`${url}#bar`); + const navigation2Span = await navigation2SpanPromise; + + const pageloadTraceId = pageloadSpan.trace_id; + const navigation1TraceId = navigation1Span.trace_id; + const navigation2TraceId = navigation2Span.trace_id; + + expect(pageloadSpan.links).toBeUndefined(); + + expect(navigation1Span.links).toEqual([ + { + trace_id: pageloadTraceId, + span_id: pageloadSpan.span_id, + sampled: true, + attributes: { + [SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE]: { + type: 'string', + value: 'previous_trace', + }, + }, + }, + ]); + + expect(navigation1Span.attributes?.['sentry.previous_trace']).toEqual({ + type: 'string', + value: `${pageloadTraceId}-${pageloadSpan.span_id}-1`, + }); + + expect(navigation2Span.links).toEqual([ + { + trace_id: navigation1TraceId, + span_id: navigation1Span.span_id, + sampled: true, + attributes: { + [SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE]: { + type: 'string', + value: 'previous_trace', + }, + }, + }, + ]); + + expect(navigation2Span.attributes?.['sentry.previous_trace']).toEqual({ + type: 'string', + value: `${navigation1TraceId}-${navigation1Span.span_id}-1`, + }); + + expect(pageloadTraceId).not.toEqual(navigation1TraceId); + expect(navigation1TraceId).not.toEqual(navigation2TraceId); + expect(pageloadTraceId).not.toEqual(navigation2TraceId); +}); + +sentryTest("doesn't link between hard page reloads by default", async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + await sentryTest.step('First pageload', async () => { + const pageloadSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'pageload'); + await page.goto(url); + const pageload1Span = await pageloadSpanPromise; + + expect(pageload1Span).toBeDefined(); + expect(pageload1Span.links).toBeUndefined(); + }); + + await sentryTest.step('Second pageload', async () => { + const pageloadSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'pageload'); + await page.reload(); + const pageload2Span = await pageloadSpanPromise; + + expect(pageload2Span).toBeDefined(); + expect(pageload2Span.links).toBeUndefined(); + }); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/init.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/init.js new file mode 100644 index 000000000000..749560a5c459 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/init.js @@ -0,0 +1,10 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [Sentry.browserTracingIntegration(), Sentry.spanStreamingIntegration()], + tracesSampleRate: 1, + debug: true, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/interaction-spans/init.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/interaction-spans/init.js new file mode 100644 index 000000000000..f07f76ecd692 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/interaction-spans/init.js @@ -0,0 +1,12 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + tracesSampleRate: 1, + integrations: [ + Sentry.browserTracingIntegration({ _experiments: { enableInteractions: true } }), + Sentry.spanStreamingIntegration(), + ], +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/interaction-spans/template.html b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/interaction-spans/template.html new file mode 100644 index 000000000000..7f6845239468 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/interaction-spans/template.html @@ -0,0 +1,7 @@ + + + + + + + diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/interaction-spans/test.ts b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/interaction-spans/test.ts new file mode 100644 index 000000000000..c34aba99dbdd --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/interaction-spans/test.ts @@ -0,0 +1,79 @@ +import { expect } from '@playwright/test'; +import { SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE } from '@sentry/core'; +import { sentryTest } from '../../../../../utils/fixtures'; +import { shouldSkipTracingTest, testingCdnBundle } from '../../../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpan } from '../../../../../utils/spanUtils'; + +/* + This is quite peculiar behavior but it's a result of the route-based trace lifetime. + Once we shortened trace lifetime, this whole scenario will change as the interaction + spans will be their own trace. So most likely, we can replace this test with a new one + that covers the new default behavior. +*/ +sentryTest( + 'only the first root spans in the trace link back to the previous trace', + async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + const pageloadSpan = await sentryTest.step('Initial pageload', async () => { + const pageloadSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'pageload'); + await page.goto(url); + const span = await pageloadSpanPromise; + + expect(span).toBeDefined(); + expect(span.links).toBeUndefined(); + + return span; + }); + + await sentryTest.step('Click Before navigation', async () => { + const interactionSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'ui.action.click'); + await page.click('#btn'); + const interactionSpan = await interactionSpanPromise; + + // sanity check: route-based trace lifetime means the trace_id should be the same + expect(interactionSpan.trace_id).toBe(pageloadSpan.trace_id); + + // no links yet as previous root span belonged to same trace + expect(interactionSpan.links).toBeUndefined(); + }); + + const navigationSpan = await sentryTest.step('Navigation', async () => { + const navigationSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'navigation'); + await page.goto(`${url}#foo`); + const span = await navigationSpanPromise; + + expect(getSpanOp(span)).toBe('navigation'); + expect(span.links).toEqual([ + { + trace_id: pageloadSpan.trace_id, + span_id: pageloadSpan.span_id, + sampled: true, + attributes: { + [SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE]: { + type: 'string', + value: 'previous_trace', + }, + }, + }, + ]); + + expect(span.trace_id).not.toEqual(span.links![0].trace_id); + return span; + }); + + await sentryTest.step('Click After navigation', async () => { + const interactionSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'ui.action.click'); + await page.click('#btn'); + const interactionSpan = await interactionSpanPromise; + + // sanity check: route-based trace lifetime means the trace_id should be the same + expect(interactionSpan.trace_id).toBe(navigationSpan.trace_id); + + // since this is the second root span in the trace, it doesn't link back to the previous trace + expect(interactionSpan.links).toBeUndefined(); + }); + }, +); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/meta/template.html b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/meta/template.html new file mode 100644 index 000000000000..2221bd0fee1d --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/meta/template.html @@ -0,0 +1,11 @@ + + + + + + + + diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/meta/test.ts b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/meta/test.ts new file mode 100644 index 000000000000..cbcc231593ea --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/meta/test.ts @@ -0,0 +1,50 @@ +import { expect } from '@playwright/test'; +import { SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE } from '@sentry/core'; +import { sentryTest } from '../../../../../utils/fixtures'; +import { shouldSkipTracingTest, testingCdnBundle } from '../../../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpan } from '../../../../../utils/spanUtils'; + +sentryTest( + "links back to previous trace's local root span if continued from meta tags", + async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + const metaTagTraceId = '12345678901234567890123456789012'; + + const pageloadSpan = await sentryTest.step('Initial pageload', async () => { + const pageloadSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'pageload'); + await page.goto(url); + const span = await pageloadSpanPromise; + + // sanity check + expect(span.trace_id).toBe(metaTagTraceId); + expect(span.links).toBeUndefined(); + + return span; + }); + + const navigationSpan = await sentryTest.step('Navigation', async () => { + const navigationSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'navigation'); + await page.goto(`${url}#foo`); + return navigationSpanPromise; + }); + + expect(navigationSpan.links).toEqual([ + { + trace_id: metaTagTraceId, + span_id: pageloadSpan.span_id, + sampled: true, + attributes: { + [SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE]: { + type: 'string', + value: 'previous_trace', + }, + }, + }, + ]); + + expect(navigationSpan.trace_id).not.toEqual(metaTagTraceId); + }, +); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/negatively-sampled/init.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/negatively-sampled/init.js new file mode 100644 index 000000000000..778092cf026b --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/negatively-sampled/init.js @@ -0,0 +1,15 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + // We want to ignore redirects for this test + integrations: [Sentry.browserTracingIntegration({ detectRedirects: false }), Sentry.spanStreamingIntegration()], + tracesSampler: ctx => { + if (ctx.attributes['sentry.origin'] === 'auto.pageload.browser') { + return 0; + } + return 1; + }, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/negatively-sampled/test.ts b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/negatively-sampled/test.ts new file mode 100644 index 000000000000..06366eb9921a --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/negatively-sampled/test.ts @@ -0,0 +1,44 @@ +import { expect } from '@playwright/test'; +import { SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE } from '@sentry/core'; +import { sentryTest } from '../../../../../utils/fixtures'; +import { shouldSkipTracingTest, testingCdnBundle } from '../../../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpan } from '../../../../../utils/spanUtils'; + +sentryTest('includes a span link to a previously negatively sampled span', async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + await sentryTest.step('Initial pageload', async () => { + // No span envelope expected here because this pageload span is sampled negatively! + await page.goto(url); + }); + + await sentryTest.step('Navigation', async () => { + const navigationSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'navigation'); + await page.goto(`${url}#foo`); + const navigationSpan = await navigationSpanPromise; + + expect(getSpanOp(navigationSpan)).toBe('navigation'); + expect(navigationSpan.links).toEqual([ + { + trace_id: expect.stringMatching(/[a-f\d]{32}/), + span_id: expect.stringMatching(/[a-f\d]{16}/), + sampled: false, + attributes: { + [SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE]: { + type: 'string', + value: 'previous_trace', + }, + }, + }, + ]); + + expect(navigationSpan.attributes?.['sentry.previous_trace']).toEqual({ + type: 'string', + value: expect.stringMatching(/[a-f\d]{32}-[a-f\d]{16}-0/), + }); + + expect(navigationSpan.trace_id).not.toEqual(navigationSpan.links![0].trace_id); + }); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/session-storage/init.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/session-storage/init.js new file mode 100644 index 000000000000..e51af56c2a9d --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/session-storage/init.js @@ -0,0 +1,12 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [ + Sentry.browserTracingIntegration({ linkPreviousTrace: 'session-storage' }), + Sentry.spanStreamingIntegration(), + ], + tracesSampleRate: 1, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/session-storage/test.ts b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/session-storage/test.ts new file mode 100644 index 000000000000..96a5bbeacc6d --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/linked-traces-streamed/session-storage/test.ts @@ -0,0 +1,42 @@ +import { expect } from '@playwright/test'; +import { SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE } from '@sentry/core'; +import { sentryTest } from '../../../../../utils/fixtures'; +import { shouldSkipTracingTest, testingCdnBundle } from '../../../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpan } from '../../../../../utils/spanUtils'; + +sentryTest('adds link between hard page reloads when opting into sessionStorage', async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + const pageload1Span = await sentryTest.step('First pageload', async () => { + const pageloadSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'pageload'); + await page.goto(url); + const span = await pageloadSpanPromise; + expect(span).toBeDefined(); + expect(span.links).toBeUndefined(); + return span; + }); + + const pageload2Span = await sentryTest.step('Hard page reload', async () => { + const pageloadSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'pageload'); + await page.reload(); + return pageloadSpanPromise; + }); + + expect(pageload2Span.links).toEqual([ + { + trace_id: pageload1Span.trace_id, + span_id: pageload1Span.span_id, + sampled: true, + attributes: { + [SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE]: { + type: 'string', + value: 'previous_trace', + }, + }, + }, + ]); + + expect(pageload1Span.trace_id).not.toEqual(pageload2Span.trace_id); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-before-navigation-streamed/init.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-before-navigation-streamed/init.js new file mode 100644 index 000000000000..ee197adaa33c --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-before-navigation-streamed/init.js @@ -0,0 +1,18 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [ + Sentry.browserTracingIntegration({ + idleTimeout: 2000, + enableLongTask: false, + enableLongAnimationFrame: true, + instrumentPageLoad: false, + enableInp: false, + }), + Sentry.spanStreamingIntegration(), + ], + tracesSampleRate: 1, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-before-navigation-streamed/subject.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-before-navigation-streamed/subject.js new file mode 100644 index 000000000000..b02ed6efa33b --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-before-navigation-streamed/subject.js @@ -0,0 +1,18 @@ +function getElapsed(startTime) { + const time = Date.now(); + return time - startTime; +} + +function handleClick() { + const startTime = Date.now(); + while (getElapsed(startTime) < 105) { + // + } + window.history.pushState({}, '', `#myHeading`); +} + +const button = document.getElementById('clickme'); + +console.log('button', button); + +button.addEventListener('click', handleClick); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-before-navigation-streamed/template.html b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-before-navigation-streamed/template.html new file mode 100644 index 000000000000..6a6a89752f20 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-before-navigation-streamed/template.html @@ -0,0 +1,11 @@ + + + + + + + + +

My Heading

+ + diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-before-navigation-streamed/test.ts b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-before-navigation-streamed/test.ts new file mode 100644 index 000000000000..3054c1c84bcb --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-before-navigation-streamed/test.ts @@ -0,0 +1,25 @@ +import { expect } from '@playwright/test'; +import { sentryTest } from '../../../../utils/fixtures'; +import { shouldSkipTracingTest, testingCdnBundle } from '../../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpans } from '../../../../utils/spanUtils'; + +sentryTest( + "doesn't capture long animation frame that starts before a navigation.", + async ({ browserName, getLocalTestUrl, page }) => { + // Long animation frames only work on chrome + sentryTest.skip(shouldSkipTracingTest() || browserName !== 'chromium' || testingCdnBundle()); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + const navigationSpansPromise = waitForStreamedSpans(page, spans => spans.some(s => getSpanOp(s) === 'navigation')); + + await page.goto(url); + + await page.locator('#clickme').click(); + + const spans = await navigationSpansPromise; + + const loafSpans = spans.filter(s => getSpanOp(s)?.startsWith('ui.long-animation-frame')); + expect(loafSpans).toHaveLength(0); + }, +); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-disabled-streamed/assets/script.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-disabled-streamed/assets/script.js new file mode 100644 index 000000000000..195a094070be --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-disabled-streamed/assets/script.js @@ -0,0 +1,12 @@ +(() => { + const startTime = Date.now(); + + function getElapsed() { + const time = Date.now(); + return time - startTime; + } + + while (getElapsed() < 101) { + // + } +})(); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-disabled-streamed/init.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-disabled-streamed/init.js new file mode 100644 index 000000000000..965613d5464e --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-disabled-streamed/init.js @@ -0,0 +1,12 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [ + Sentry.browserTracingIntegration({ enableLongTask: false, enableLongAnimationFrame: false, idleTimeout: 2000 }), + Sentry.spanStreamingIntegration(), + ], + tracesSampleRate: 1, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-disabled-streamed/template.html b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-disabled-streamed/template.html new file mode 100644 index 000000000000..62aed26413f8 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-disabled-streamed/template.html @@ -0,0 +1,10 @@ + + + + + + +
Rendered Before Long Animation Frame
+ + + diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-disabled-streamed/test.ts b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-disabled-streamed/test.ts new file mode 100644 index 000000000000..7ba1dddd0c90 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-disabled-streamed/test.ts @@ -0,0 +1,28 @@ +import type { Route } from '@playwright/test'; +import { expect } from '@playwright/test'; +import { sentryTest } from '../../../../utils/fixtures'; +import { shouldSkipTracingTest, testingCdnBundle } from '../../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpans } from '../../../../utils/spanUtils'; + +sentryTest( + 'does not capture long animation frame when flag is disabled.', + async ({ browserName, getLocalTestUrl, page }) => { + // Long animation frames only work on chrome + sentryTest.skip(shouldSkipTracingTest() || browserName !== 'chromium' || testingCdnBundle()); + + await page.route('**/path/to/script.js', (route: Route) => + route.fulfill({ path: `${__dirname}/assets/script.js` }), + ); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + const spansPromise = waitForStreamedSpans(page, spans => spans.some(s => getSpanOp(s) === 'pageload')); + + await page.goto(url); + + const spans = await spansPromise; + const uiSpans = spans.filter(s => getSpanOp(s)?.startsWith('ui')); + + expect(uiSpans.length).toBe(0); + }, +); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-enabled-streamed/assets/script.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-enabled-streamed/assets/script.js new file mode 100644 index 000000000000..10552eeb5bd5 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-enabled-streamed/assets/script.js @@ -0,0 +1,25 @@ +function getElapsed(startTime) { + const time = Date.now(); + return time - startTime; +} + +function handleClick() { + const startTime = Date.now(); + while (getElapsed(startTime) < 105) { + // + } +} + +function start() { + const startTime = Date.now(); + while (getElapsed(startTime) < 105) { + // + } +} + +// trigger 2 long-animation-frame events +// one from the top-level and the other from an event-listener +start(); + +const button = document.getElementById('clickme'); +button.addEventListener('click', handleClick); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-enabled-streamed/init.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-enabled-streamed/init.js new file mode 100644 index 000000000000..1f6cc0a8f463 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-enabled-streamed/init.js @@ -0,0 +1,16 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [ + Sentry.browserTracingIntegration({ + idleTimeout: 2000, + enableLongTask: false, + enableLongAnimationFrame: true, + }), + Sentry.spanStreamingIntegration(), + ], + tracesSampleRate: 1, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-enabled-streamed/template.html b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-enabled-streamed/template.html new file mode 100644 index 000000000000..c157aa80cb8d --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-enabled-streamed/template.html @@ -0,0 +1,11 @@ + + + + + + +
Rendered Before Long Animation Frame
+ + + + diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-enabled-streamed/test.ts b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-enabled-streamed/test.ts new file mode 100644 index 000000000000..c1e7efa5e8d8 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-animation-frame-enabled-streamed/test.ts @@ -0,0 +1,109 @@ +import type { Route } from '@playwright/test'; +import { expect } from '@playwright/test'; +import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '@sentry/browser'; +import { SEMANTIC_ATTRIBUTE_SENTRY_OP } from '@sentry/core'; +import { sentryTest } from '../../../../utils/fixtures'; +import { shouldSkipTracingTest, testingCdnBundle } from '../../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpans } from '../../../../utils/spanUtils'; + +sentryTest( + 'captures long animation frame span for top-level script.', + async ({ browserName, getLocalTestUrl, page }) => { + // Long animation frames only work on chrome + sentryTest.skip(shouldSkipTracingTest() || browserName !== 'chromium' || testingCdnBundle()); + + await page.route('**/path/to/script.js', (route: Route) => + route.fulfill({ path: `${__dirname}/assets/script.js` }), + ); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + const spansPromise = waitForStreamedSpans(page, spans => spans.some(s => getSpanOp(s) === 'pageload')); + + await page.goto(url); + + const spans = await spansPromise; + const pageloadSpan = spans.find(s => getSpanOp(s) === 'pageload')!; + + const uiSpans = spans.filter(s => getSpanOp(s)?.startsWith('ui.long-animation-frame')); + + expect(uiSpans.length).toBeGreaterThanOrEqual(1); + + const topLevelUISpan = uiSpans.find( + s => s.attributes?.['browser.script.invoker']?.value === 'https://sentry-test-site.example/path/to/script.js', + )!; + + expect(topLevelUISpan).toEqual( + expect.objectContaining({ + name: 'Main UI thread blocked', + parent_span_id: pageloadSpan.span_id, + attributes: expect.objectContaining({ + 'code.filepath': { type: 'string', value: 'https://sentry-test-site.example/path/to/script.js' }, + 'browser.script.source_char_position': expect.objectContaining({ value: 0 }), + 'browser.script.invoker': { + type: 'string', + value: 'https://sentry-test-site.example/path/to/script.js', + }, + 'browser.script.invoker_type': { type: 'string', value: 'classic-script' }, + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: { type: 'string', value: 'ui.long-animation-frame' }, + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: { type: 'string', value: 'auto.ui.browser.metrics' }, + }), + }), + ); + + const start = topLevelUISpan.start_timestamp ?? 0; + const end = topLevelUISpan.end_timestamp ?? 0; + const duration = end - start; + + expect(duration).toBeGreaterThanOrEqual(0.1); + expect(duration).toBeLessThanOrEqual(0.15); + }, +); + +sentryTest('captures long animation frame span for event listener.', async ({ browserName, getLocalTestUrl, page }) => { + // Long animation frames only work on chrome + sentryTest.skip(shouldSkipTracingTest() || browserName !== 'chromium' || testingCdnBundle()); + + await page.route('**/path/to/script.js', (route: Route) => route.fulfill({ path: `${__dirname}/assets/script.js` })); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + const spansPromise = waitForStreamedSpans(page, spans => spans.some(s => getSpanOp(s) === 'pageload')); + + await page.goto(url); + + // trigger long animation frame function + await page.getByRole('button').click(); + + const spans = await spansPromise; + const pageloadSpan = spans.find(s => getSpanOp(s) === 'pageload')!; + + const uiSpans = spans.filter(s => getSpanOp(s)?.startsWith('ui.long-animation-frame')); + + expect(uiSpans.length).toBeGreaterThanOrEqual(2); + + const eventListenerUISpan = uiSpans.find( + s => s.attributes?.['browser.script.invoker']?.value === 'BUTTON#clickme.onclick', + )!; + + expect(eventListenerUISpan).toEqual( + expect.objectContaining({ + name: 'Main UI thread blocked', + parent_span_id: pageloadSpan.span_id, + attributes: expect.objectContaining({ + 'browser.script.invoker': { type: 'string', value: 'BUTTON#clickme.onclick' }, + 'browser.script.invoker_type': { type: 'string', value: 'event-listener' }, + 'code.filepath': { type: 'string', value: 'https://sentry-test-site.example/path/to/script.js' }, + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: { type: 'string', value: 'ui.long-animation-frame' }, + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: { type: 'string', value: 'auto.ui.browser.metrics' }, + }), + }), + ); + + const start = eventListenerUISpan.start_timestamp ?? 0; + const end = eventListenerUISpan.end_timestamp ?? 0; + const duration = end - start; + + expect(duration).toBeGreaterThanOrEqual(0.1); + expect(duration).toBeLessThanOrEqual(0.15); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-and-animation-frame-enabled-streamed/assets/script.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-and-animation-frame-enabled-streamed/assets/script.js new file mode 100644 index 000000000000..10552eeb5bd5 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-and-animation-frame-enabled-streamed/assets/script.js @@ -0,0 +1,25 @@ +function getElapsed(startTime) { + const time = Date.now(); + return time - startTime; +} + +function handleClick() { + const startTime = Date.now(); + while (getElapsed(startTime) < 105) { + // + } +} + +function start() { + const startTime = Date.now(); + while (getElapsed(startTime) < 105) { + // + } +} + +// trigger 2 long-animation-frame events +// one from the top-level and the other from an event-listener +start(); + +const button = document.getElementById('clickme'); +button.addEventListener('click', handleClick); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-and-animation-frame-enabled-streamed/init.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-and-animation-frame-enabled-streamed/init.js new file mode 100644 index 000000000000..3e3eedaf49b7 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-and-animation-frame-enabled-streamed/init.js @@ -0,0 +1,16 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [ + Sentry.browserTracingIntegration({ + idleTimeout: 2000, + enableLongTask: true, + enableLongAnimationFrame: true, + }), + Sentry.spanStreamingIntegration(), + ], + tracesSampleRate: 1, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-and-animation-frame-enabled-streamed/template.html b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-and-animation-frame-enabled-streamed/template.html new file mode 100644 index 000000000000..c157aa80cb8d --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-and-animation-frame-enabled-streamed/template.html @@ -0,0 +1,11 @@ + + + + + + +
Rendered Before Long Animation Frame
+ + + + diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-and-animation-frame-enabled-streamed/test.ts b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-and-animation-frame-enabled-streamed/test.ts new file mode 100644 index 000000000000..4f9207fa1e34 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-and-animation-frame-enabled-streamed/test.ts @@ -0,0 +1,111 @@ +import type { Route } from '@playwright/test'; +import { expect } from '@playwright/test'; +import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '@sentry/browser'; +import { SEMANTIC_ATTRIBUTE_SENTRY_OP } from '@sentry/core'; +import { sentryTest } from '../../../../utils/fixtures'; +import { shouldSkipTracingTest, testingCdnBundle } from '../../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpans } from '../../../../utils/spanUtils'; + +sentryTest( + 'captures long animation frame span for top-level script.', + async ({ browserName, getLocalTestUrl, page }) => { + // Long animation frames only work on chrome + sentryTest.skip(shouldSkipTracingTest() || browserName !== 'chromium' || testingCdnBundle()); + + // Long animation frame should take priority over long tasks + + await page.route('**/path/to/script.js', (route: Route) => + route.fulfill({ path: `${__dirname}/assets/script.js` }), + ); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + const spansPromise = waitForStreamedSpans(page, spans => spans.some(s => getSpanOp(s) === 'pageload')); + + await page.goto(url); + + const spans = await spansPromise; + const pageloadSpan = spans.find(s => getSpanOp(s) === 'pageload')!; + + const uiSpans = spans.filter(s => getSpanOp(s)?.startsWith('ui.long-animation-frame')); + + expect(uiSpans.length).toBeGreaterThanOrEqual(1); + + const topLevelUISpan = uiSpans.find( + s => s.attributes?.['browser.script.invoker']?.value === 'https://sentry-test-site.example/path/to/script.js', + )!; + + expect(topLevelUISpan).toEqual( + expect.objectContaining({ + name: 'Main UI thread blocked', + parent_span_id: pageloadSpan.span_id, + attributes: expect.objectContaining({ + 'code.filepath': { type: 'string', value: 'https://sentry-test-site.example/path/to/script.js' }, + 'browser.script.source_char_position': expect.objectContaining({ value: 0 }), + 'browser.script.invoker': { + type: 'string', + value: 'https://sentry-test-site.example/path/to/script.js', + }, + 'browser.script.invoker_type': { type: 'string', value: 'classic-script' }, + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: { type: 'string', value: 'ui.long-animation-frame' }, + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: { type: 'string', value: 'auto.ui.browser.metrics' }, + }), + }), + ); + + const start = topLevelUISpan.start_timestamp ?? 0; + const end = topLevelUISpan.end_timestamp ?? 0; + const duration = end - start; + + expect(duration).toBeGreaterThanOrEqual(0.1); + expect(duration).toBeLessThanOrEqual(0.15); + }, +); + +sentryTest('captures long animation frame span for event listener.', async ({ browserName, getLocalTestUrl, page }) => { + // Long animation frames only work on chrome + sentryTest.skip(shouldSkipTracingTest() || browserName !== 'chromium' || testingCdnBundle()); + + await page.route('**/path/to/script.js', (route: Route) => route.fulfill({ path: `${__dirname}/assets/script.js` })); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + const spansPromise = waitForStreamedSpans(page, spans => spans.some(s => getSpanOp(s) === 'pageload')); + + await page.goto(url); + + // trigger long animation frame function + await page.getByRole('button').click(); + + const spans = await spansPromise; + const pageloadSpan = spans.find(s => getSpanOp(s) === 'pageload')!; + + const uiSpans = spans.filter(s => getSpanOp(s)?.startsWith('ui.long-animation-frame')); + + expect(uiSpans.length).toBeGreaterThanOrEqual(2); + + const eventListenerUISpan = uiSpans.find( + s => s.attributes?.['browser.script.invoker']?.value === 'BUTTON#clickme.onclick', + )!; + + expect(eventListenerUISpan).toEqual( + expect.objectContaining({ + name: 'Main UI thread blocked', + parent_span_id: pageloadSpan.span_id, + attributes: expect.objectContaining({ + 'browser.script.invoker': { type: 'string', value: 'BUTTON#clickme.onclick' }, + 'browser.script.invoker_type': { type: 'string', value: 'event-listener' }, + 'code.filepath': { type: 'string', value: 'https://sentry-test-site.example/path/to/script.js' }, + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: { type: 'string', value: 'ui.long-animation-frame' }, + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: { type: 'string', value: 'auto.ui.browser.metrics' }, + }), + }), + ); + + const start = eventListenerUISpan.start_timestamp ?? 0; + const end = eventListenerUISpan.end_timestamp ?? 0; + const duration = end - start; + + expect(duration).toBeGreaterThanOrEqual(0.1); + expect(duration).toBeLessThanOrEqual(0.15); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-before-navigation-streamed/init.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-before-navigation-streamed/init.js new file mode 100644 index 000000000000..f6e5ce777e06 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-before-navigation-streamed/init.js @@ -0,0 +1,19 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [ + Sentry.browserTracingIntegration({ + idleTimeout: 2000, + enableLongAnimationFrame: false, + instrumentPageLoad: false, + instrumentNavigation: true, + enableInp: false, + enableLongTask: true, + }), + Sentry.spanStreamingIntegration(), + ], + tracesSampleRate: 1, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-before-navigation-streamed/subject.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-before-navigation-streamed/subject.js new file mode 100644 index 000000000000..d814f8875715 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-before-navigation-streamed/subject.js @@ -0,0 +1,17 @@ +const longTaskButton = document.getElementById('myButton'); + +longTaskButton?.addEventListener('click', () => { + const startTime = Date.now(); + + function getElapsed() { + const time = Date.now(); + return time - startTime; + } + + while (getElapsed() < 500) { + // + } + + // trigger a navigation in the same event loop tick + window.history.pushState({}, '', '#myHeading'); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-before-navigation-streamed/template.html b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-before-navigation-streamed/template.html new file mode 100644 index 000000000000..c2cb2a8129fe --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-before-navigation-streamed/template.html @@ -0,0 +1,12 @@ + + + + + + +
Rendered Before Long Task
+ + +

Heading

+ + diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-before-navigation-streamed/test.ts b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-before-navigation-streamed/test.ts new file mode 100644 index 000000000000..74ce32706584 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-before-navigation-streamed/test.ts @@ -0,0 +1,29 @@ +import { expect } from '@playwright/test'; +import { sentryTest } from '../../../../utils/fixtures'; +import { shouldSkipTracingTest, testingCdnBundle } from '../../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpans } from '../../../../utils/spanUtils'; + +sentryTest( + "doesn't capture long task spans starting before a navigation in the navigation transaction", + async ({ browserName, getLocalTestUrl, page }) => { + // Long tasks only work on chrome + sentryTest.skip(shouldSkipTracingTest() || browserName !== 'chromium' || testingCdnBundle()); + const url = await getLocalTestUrl({ testDir: __dirname }); + + await page.route('**/path/to/script.js', route => route.fulfill({ path: `${__dirname}/assets/script.js` })); + + const navigationSpansPromise = waitForStreamedSpans(page, spans => spans.some(s => getSpanOp(s) === 'navigation')); + + await page.goto(url); + + await page.locator('#myButton').click(); + + const spans = await navigationSpansPromise; + + const navigationSpan = spans.find(s => getSpanOp(s) === 'navigation'); + expect(navigationSpan).toBeDefined(); + + const longTaskSpans = spans.filter(s => getSpanOp(s) === 'ui.long-task'); + expect(longTaskSpans).toHaveLength(0); + }, +); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-disabled-streamed/assets/script.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-disabled-streamed/assets/script.js new file mode 100644 index 000000000000..195a094070be --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-disabled-streamed/assets/script.js @@ -0,0 +1,12 @@ +(() => { + const startTime = Date.now(); + + function getElapsed() { + const time = Date.now(); + return time - startTime; + } + + while (getElapsed() < 101) { + // + } +})(); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-disabled-streamed/init.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-disabled-streamed/init.js new file mode 100644 index 000000000000..965613d5464e --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-disabled-streamed/init.js @@ -0,0 +1,12 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [ + Sentry.browserTracingIntegration({ enableLongTask: false, enableLongAnimationFrame: false, idleTimeout: 2000 }), + Sentry.spanStreamingIntegration(), + ], + tracesSampleRate: 1, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-disabled-streamed/template.html b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-disabled-streamed/template.html new file mode 100644 index 000000000000..b03231da2c65 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-disabled-streamed/template.html @@ -0,0 +1,10 @@ + + + + + + +
Rendered Before Long Task
+ + + diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-disabled-streamed/test.ts b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-disabled-streamed/test.ts new file mode 100644 index 000000000000..83600f5d4a6a --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-disabled-streamed/test.ts @@ -0,0 +1,23 @@ +import type { Route } from '@playwright/test'; +import { expect } from '@playwright/test'; +import { sentryTest } from '../../../../utils/fixtures'; +import { shouldSkipTracingTest, testingCdnBundle } from '../../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpans } from '../../../../utils/spanUtils'; + +sentryTest("doesn't capture long task spans when flag is disabled.", async ({ browserName, getLocalTestUrl, page }) => { + // Long tasks only work on chrome + sentryTest.skip(shouldSkipTracingTest() || browserName !== 'chromium' || testingCdnBundle()); + + await page.route('**/path/to/script.js', (route: Route) => route.fulfill({ path: `${__dirname}/assets/script.js` })); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + const spansPromise = waitForStreamedSpans(page, spans => spans.some(s => getSpanOp(s) === 'pageload')); + + await page.goto(url); + + const spans = await spansPromise; + const uiSpans = spans.filter(s => getSpanOp(s)?.startsWith('ui')); + + expect(uiSpans.length).toBe(0); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-enabled-streamed/assets/script.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-enabled-streamed/assets/script.js new file mode 100644 index 000000000000..b61592e05943 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-enabled-streamed/assets/script.js @@ -0,0 +1,12 @@ +(() => { + const startTime = Date.now(); + + function getElapsed() { + const time = Date.now(); + return time - startTime; + } + + while (getElapsed() < 105) { + // + } +})(); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-enabled-streamed/init.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-enabled-streamed/init.js new file mode 100644 index 000000000000..484350c14fcf --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-enabled-streamed/init.js @@ -0,0 +1,15 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [ + Sentry.browserTracingIntegration({ + idleTimeout: 2000, + enableLongAnimationFrame: false, + }), + Sentry.spanStreamingIntegration(), + ], + tracesSampleRate: 1, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-enabled-streamed/template.html b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-enabled-streamed/template.html new file mode 100644 index 000000000000..b03231da2c65 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-enabled-streamed/template.html @@ -0,0 +1,10 @@ + + + + + + +
Rendered Before Long Task
+ + + diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-enabled-streamed/test.ts b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-enabled-streamed/test.ts new file mode 100644 index 000000000000..8b73aa91dff6 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/long-tasks-enabled-streamed/test.ts @@ -0,0 +1,42 @@ +import type { Route } from '@playwright/test'; +import { expect } from '@playwright/test'; +import { sentryTest } from '../../../../utils/fixtures'; +import { shouldSkipTracingTest, testingCdnBundle } from '../../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpans } from '../../../../utils/spanUtils'; + +sentryTest('captures long task.', async ({ browserName, getLocalTestUrl, page }) => { + // Long tasks only work on chrome + sentryTest.skip(shouldSkipTracingTest() || browserName !== 'chromium' || testingCdnBundle()); + + await page.route('**/path/to/script.js', (route: Route) => route.fulfill({ path: `${__dirname}/assets/script.js` })); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + const spansPromise = waitForStreamedSpans(page, spans => spans.some(s => getSpanOp(s) === 'pageload')); + + await page.goto(url); + + const spans = await spansPromise; + const pageloadSpan = spans.find(s => getSpanOp(s) === 'pageload')!; + + const uiSpans = spans.filter(s => getSpanOp(s)?.startsWith('ui')); + expect(uiSpans.length).toBeGreaterThan(0); + + const [firstUISpan] = uiSpans; + expect(firstUISpan).toEqual( + expect.objectContaining({ + name: 'Main UI thread blocked', + parent_span_id: pageloadSpan.span_id, + attributes: expect.objectContaining({ + 'sentry.op': { type: 'string', value: 'ui.long-task' }, + }), + }), + ); + + const start = firstUISpan.start_timestamp ?? 0; + const end = firstUISpan.end_timestamp ?? 0; + const duration = end - start; + + expect(duration).toBeGreaterThanOrEqual(0.1); + expect(duration).toBeLessThanOrEqual(0.15); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/navigation-streamed/init.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/navigation-streamed/init.js new file mode 100644 index 000000000000..a93fc742bafb --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/navigation-streamed/init.js @@ -0,0 +1,9 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [Sentry.browserTracingIntegration(), Sentry.spanStreamingIntegration()], + tracesSampleRate: 1, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/navigation-streamed/test.ts b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/navigation-streamed/test.ts new file mode 100644 index 000000000000..7128d2d5ecce --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/navigation-streamed/test.ts @@ -0,0 +1,219 @@ +import { expect } from '@playwright/test'; +import { + SDK_VERSION, + SEMANTIC_ATTRIBUTE_SENTRY_OP, + SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, + SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, + SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, +} from '@sentry/core'; +import { sentryTest } from '../../../../utils/fixtures'; +import { shouldSkipTracingTest, testingCdnBundle } from '../../../../utils/helpers'; +import { + getSpanOp, + getSpansFromEnvelope, + waitForStreamedSpan, + waitForStreamedSpanEnvelope, +} from '../../../../utils/spanUtils'; + +sentryTest('starts a streamed navigation span on page navigation', async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const pageloadSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'pageload'); + const navigationSpanEnvelopePromise = waitForStreamedSpanEnvelope( + page, + env => !!getSpansFromEnvelope(env).find(s => getSpanOp(s) === 'navigation'), + ); + + const url = await getLocalTestUrl({ testDir: __dirname }); + await page.goto(url); + + const pageloadSpan = await pageloadSpanPromise; + + // simulate navigation + page.goto(`${url}#foo`); + + const navigationSpanEnvelope = await navigationSpanEnvelopePromise; + + const navigationSpanEnvelopeHeader = navigationSpanEnvelope[0]; + const navigationSpanEnvelopeItem = navigationSpanEnvelope[1]; + const navigationSpans = navigationSpanEnvelopeItem[0][1].items; + const navigationSpan = navigationSpans.find(s => getSpanOp(s) === 'navigation')!; + + expect(navigationSpanEnvelopeHeader).toEqual({ + sent_at: expect.any(String), + trace: { + trace_id: expect.stringMatching(/^[\da-f]{32}$/), + environment: 'production', + public_key: 'public', + sample_rand: expect.any(String), + sample_rate: '1', + sampled: 'true', + }, + sdk: { + name: 'sentry.javascript.browser', + version: SDK_VERSION, + }, + }); + + const numericSampleRand = parseFloat(navigationSpanEnvelopeHeader.trace!.sample_rand!); + expect(Number.isNaN(numericSampleRand)).toBe(false); + + const pageloadTraceId = pageloadSpan.trace_id; + const navigationTraceId = navigationSpan.trace_id; + + expect(pageloadTraceId).toBeDefined(); + expect(navigationTraceId).toBeDefined(); + expect(pageloadTraceId).not.toEqual(navigationTraceId); + + expect(pageloadSpan.name).toEqual('/index.html'); + + expect(navigationSpan).toEqual({ + attributes: { + effectiveConnectionType: { + type: 'string', + value: expect.any(String), + }, + hardwareConcurrency: { + type: 'string', + value: expect.any(String), + }, + 'sentry.idle_span_finish_reason': { + type: 'string', + value: 'idleTimeout', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: { + type: 'string', + value: 'navigation', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: { + type: 'string', + value: 'auto.navigation.browser', + }, + 'sentry.previous_trace': { + type: 'string', + value: `${pageloadTraceId}-${pageloadSpan.span_id}-1`, + }, + 'sentry.sample_rate': { + type: 'integer', + value: 1, + }, + 'sentry.sdk.name': { + type: 'string', + value: 'sentry.javascript.browser', + }, + 'sentry.sdk.version': { + type: 'string', + value: SDK_VERSION, + }, + 'sentry.segment.id': { + type: 'string', + value: navigationSpan.span_id, + }, + 'sentry.segment.name': { + type: 'string', + value: '/index.html', + }, + 'sentry.source': { + type: 'string', + value: 'url', + }, + 'sentry.span.source': { + type: 'string', + value: 'url', + }, + }, + end_timestamp: expect.any(Number), + is_segment: true, + links: [ + { + attributes: { + 'sentry.link.type': { + type: 'string', + value: 'previous_trace', + }, + }, + sampled: true, + span_id: pageloadSpan.span_id, + trace_id: pageloadTraceId, + }, + ], + name: '/index.html', + span_id: navigationSpan.span_id, + start_timestamp: expect.any(Number), + status: 'ok', + trace_id: navigationTraceId, + }); +}); + +sentryTest('handles pushState with full URL', async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + const pageloadSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'pageload'); + const navigationSpan1Promise = waitForStreamedSpan( + page, + span => getSpanOp(span) === 'navigation' && span.name === '/sub-page', + ); + const navigationSpan2Promise = waitForStreamedSpan( + page, + span => getSpanOp(span) === 'navigation' && span.name === '/sub-page-2', + ); + + await page.goto(url); + await pageloadSpanPromise; + + await page.evaluate("window.history.pushState({}, '', `${window.location.origin}/sub-page`);"); + + const navigationSpan1 = await navigationSpan1Promise; + + expect(navigationSpan1.name).toEqual('/sub-page'); + + expect(navigationSpan1.attributes).toMatchObject({ + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: { + type: 'string', + value: 'auto.navigation.browser', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: { + type: 'integer', + value: 1, + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: { + type: 'string', + value: 'url', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: { + type: 'string', + value: 'navigation', + }, + }); + + await page.evaluate("window.history.pushState({}, '', `${window.location.origin}/sub-page-2`);"); + + const navigationSpan2 = await navigationSpan2Promise; + + expect(navigationSpan2.name).toEqual('/sub-page-2'); + + expect(navigationSpan2.attributes).toMatchObject({ + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: { + type: 'string', + value: 'auto.navigation.browser', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: { + type: 'integer', + value: 1, + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: { + type: 'string', + value: 'url', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: { + type: 'string', + value: 'navigation', + }, + ['sentry.idle_span_finish_reason']: { + type: 'string', + value: 'idleTimeout', + }, + }); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/pageload-streamed/init.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/pageload-streamed/init.js new file mode 100644 index 000000000000..bd3b6ed17872 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/pageload-streamed/init.js @@ -0,0 +1,11 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; +window._testBaseTimestamp = performance.timeOrigin / 1000; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [Sentry.browserTracingIntegration(), Sentry.spanStreamingIntegration()], + traceLifecycle: 'stream', + tracesSampleRate: 1, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/pageload-streamed/test.ts b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/pageload-streamed/test.ts new file mode 100644 index 000000000000..47d9e00d4307 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/pageload-streamed/test.ts @@ -0,0 +1,131 @@ +import { expect } from '@playwright/test'; +import { + SDK_VERSION, + SEMANTIC_ATTRIBUTE_SENTRY_OP, + SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, + SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, + SEMANTIC_ATTRIBUTE_SENTRY_SDK_NAME, + SEMANTIC_ATTRIBUTE_SENTRY_SDK_VERSION, + SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID, + SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME, + SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, +} from '@sentry/core'; +import { sentryTest } from '../../../../utils/fixtures'; +import { shouldSkipTracingTest, testingCdnBundle } from '../../../../utils/helpers'; +import { getSpanOp, getSpansFromEnvelope, waitForStreamedSpanEnvelope } from '../../../../utils/spanUtils'; + +sentryTest( + 'creates a pageload streamed span envelope with url as pageload span name source', + async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const spanEnvelopePromise = waitForStreamedSpanEnvelope( + page, + env => !!getSpansFromEnvelope(env).find(s => getSpanOp(s) === 'pageload'), + ); + + const url = await getLocalTestUrl({ testDir: __dirname }); + await page.goto(url); + + const spanEnvelope = await spanEnvelopePromise; + const envelopeHeader = spanEnvelope[0]; + const envelopeItem = spanEnvelope[1]; + const spans = envelopeItem[0][1].items; + const pageloadSpan = spans.find(s => getSpanOp(s) === 'pageload'); + + const timeOrigin = await page.evaluate('window._testBaseTimestamp'); + + expect(envelopeHeader).toEqual({ + sdk: { + name: 'sentry.javascript.browser', + version: SDK_VERSION, + }, + sent_at: expect.any(String), + trace: { + environment: 'production', + public_key: 'public', + sample_rand: expect.any(String), + sample_rate: '1', + sampled: 'true', + trace_id: expect.stringMatching(/^[\da-f]{32}$/), + }, + }); + + const numericSampleRand = parseFloat(envelopeHeader.trace!.sample_rand!); + const traceId = envelopeHeader.trace!.trace_id; + + expect(Number.isNaN(numericSampleRand)).toBe(false); + + expect(envelopeItem[0][0].item_count).toBeGreaterThan(1); + + expect(pageloadSpan?.start_timestamp).toBeCloseTo(timeOrigin, 1); + + expect(pageloadSpan).toEqual({ + attributes: { + effectiveConnectionType: { + type: 'string', + value: expect.any(String), + }, + hardwareConcurrency: { + type: 'string', + value: expect.any(String), + }, + 'performance.activationStart': { + type: 'integer', + value: expect.any(Number), + }, + 'performance.timeOrigin': { + type: 'double', + value: expect.any(Number), + }, + 'sentry.idle_span_finish_reason': { + type: 'string', + value: 'idleTimeout', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: { + type: 'string', + value: 'pageload', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: { + type: 'string', + value: 'auto.pageload.browser', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: { + type: 'integer', + value: 1, + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_NAME]: { + type: 'string', + value: 'sentry.javascript.browser', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_VERSION]: { + type: 'string', + value: SDK_VERSION, + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID]: { + type: 'string', + value: pageloadSpan?.span_id, + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME]: { + type: 'string', + value: '/index.html', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: { + type: 'string', + value: 'url', + }, + 'sentry.span.source': { + type: 'string', + value: 'url', + }, + }, + end_timestamp: expect.any(Number), + is_segment: true, + name: '/index.html', + span_id: expect.stringMatching(/^[\da-f]{16}$/), + start_timestamp: expect.any(Number), + status: 'ok', + trace_id: traceId, + }); + }, +); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/reportPageLoaded-streamed/default/init.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/reportPageLoaded-streamed/default/init.js new file mode 100644 index 000000000000..ded3ca204b6b --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/reportPageLoaded-streamed/default/init.js @@ -0,0 +1,15 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; +window._testBaseTimestamp = performance.timeOrigin / 1000; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [Sentry.browserTracingIntegration({ enableReportPageLoaded: true }), Sentry.spanStreamingIntegration()], + tracesSampleRate: 1, + debug: true, +}); + +setTimeout(() => { + Sentry.reportPageLoaded(); +}, 2500); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/reportPageLoaded-streamed/default/test.ts b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/reportPageLoaded-streamed/default/test.ts new file mode 100644 index 000000000000..fb6fa3ab2393 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/reportPageLoaded-streamed/default/test.ts @@ -0,0 +1,41 @@ +import { expect } from '@playwright/test'; +import { + SEMANTIC_ATTRIBUTE_SENTRY_OP, + SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, + SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, + SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, +} from '@sentry/browser'; +import { SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON } from '@sentry/core'; +import { sentryTest } from '../../../../../utils/fixtures'; +import { shouldSkipTracingTest, testingCdnBundle } from '../../../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpan } from '../../../../../utils/spanUtils'; + +sentryTest( + 'waits for Sentry.reportPageLoaded() to be called when `enableReportPageLoaded` is true', + async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + const pageloadSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'pageload'); + + await page.goto(url); + + const pageloadSpan = await pageloadSpanPromise; + + const spanDurationSeconds = pageloadSpan.end_timestamp - pageloadSpan.start_timestamp; + + expect(pageloadSpan.attributes).toMatchObject({ + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: { type: 'string', value: 'auto.pageload.browser' }, + [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: expect.objectContaining({ value: 1 }), + [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: { type: 'string', value: 'url' }, + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: { type: 'string', value: 'pageload' }, + [SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON]: { type: 'string', value: 'reportPageLoaded' }, + }); + + // We wait for 2.5 seconds before calling Sentry.reportPageLoaded() + // the margins are to account for timing weirdness in CI to avoid flakes + expect(spanDurationSeconds).toBeGreaterThan(2); + expect(spanDurationSeconds).toBeLessThan(3); + }, +); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/reportPageLoaded-streamed/finalTimeout/init.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/reportPageLoaded-streamed/finalTimeout/init.js new file mode 100644 index 000000000000..b1c19f779713 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/reportPageLoaded-streamed/finalTimeout/init.js @@ -0,0 +1,16 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; +window._testBaseTimestamp = performance.timeOrigin / 1000; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [ + Sentry.browserTracingIntegration({ enableReportPageLoaded: true, finalTimeout: 3000 }), + Sentry.spanStreamingIntegration(), + ], + tracesSampleRate: 1, + debug: true, +}); + +// not calling Sentry.reportPageLoaded() on purpose! diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/reportPageLoaded-streamed/finalTimeout/test.ts b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/reportPageLoaded-streamed/finalTimeout/test.ts new file mode 100644 index 000000000000..79df6a902e45 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/reportPageLoaded-streamed/finalTimeout/test.ts @@ -0,0 +1,40 @@ +import { expect } from '@playwright/test'; +import { + SEMANTIC_ATTRIBUTE_SENTRY_OP, + SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, + SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, + SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, +} from '@sentry/browser'; +import { sentryTest } from '../../../../../utils/fixtures'; +import { shouldSkipTracingTest, testingCdnBundle } from '../../../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpan } from '../../../../../utils/spanUtils'; + +sentryTest( + 'final timeout cancels the pageload span even if `enableReportPageLoaded` is true', + async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + const pageloadSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'pageload'); + + await page.goto(url); + + const pageloadSpan = await pageloadSpanPromise; + + const spanDurationSeconds = pageloadSpan.end_timestamp - pageloadSpan.start_timestamp; + + expect(pageloadSpan.attributes).toMatchObject({ + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: { type: 'string', value: 'auto.pageload.browser' }, + [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: expect.objectContaining({ value: 1 }), + [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: { type: 'string', value: 'url' }, + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: { type: 'string', value: 'pageload' }, + 'sentry.idle_span_finish_reason': { type: 'string', value: 'finalTimeout' }, + }); + + // We wait for 3 seconds before calling Sentry.reportPageLoaded() + // the margins are to account for timing weirdness in CI to avoid flakes + expect(spanDurationSeconds).toBeGreaterThan(2.5); + expect(spanDurationSeconds).toBeLessThan(3.5); + }, +); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/reportPageLoaded-streamed/navigation/init.js b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/reportPageLoaded-streamed/navigation/init.js new file mode 100644 index 000000000000..ac42880742a3 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/reportPageLoaded-streamed/navigation/init.js @@ -0,0 +1,22 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; +window._testBaseTimestamp = performance.timeOrigin / 1000; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [ + Sentry.browserTracingIntegration({ enableReportPageLoaded: true, instrumentNavigation: false }), + Sentry.spanStreamingIntegration(), + ], + tracesSampleRate: 1, + debug: true, +}); + +setTimeout(() => { + Sentry.startBrowserTracingNavigationSpan(Sentry.getClient(), { name: 'custom_navigation' }); +}, 1000); + +setTimeout(() => { + Sentry.reportPageLoaded(); +}, 2500); diff --git a/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/reportPageLoaded-streamed/navigation/test.ts b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/reportPageLoaded-streamed/navigation/test.ts new file mode 100644 index 000000000000..77f138f34053 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/browserTracingIntegration/reportPageLoaded-streamed/navigation/test.ts @@ -0,0 +1,38 @@ +import { expect } from '@playwright/test'; +import { + SEMANTIC_ATTRIBUTE_SENTRY_OP, + SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, + SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, + SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, +} from '@sentry/browser'; +import { sentryTest } from '../../../../../utils/fixtures'; +import { shouldSkipTracingTest, testingCdnBundle } from '../../../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpan } from '../../../../../utils/spanUtils'; + +sentryTest( + 'starting a navigation span cancels the pageload span even if `enableReportPageLoaded` is true', + async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + const pageloadSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'pageload'); + + await page.goto(url); + + const pageloadSpan = await pageloadSpanPromise; + + const spanDurationSeconds = pageloadSpan.end_timestamp - pageloadSpan.start_timestamp; + + expect(pageloadSpan.attributes).toMatchObject({ + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: { type: 'string', value: 'auto.pageload.browser' }, + [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: expect.objectContaining({ value: 1 }), + [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: { type: 'string', value: 'url' }, + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: { type: 'string', value: 'pageload' }, + 'sentry.idle_span_finish_reason': { type: 'string', value: 'cancelled' }, + }); + + // ending span after 1s but adding a margin of 0.5s to account for timing weirdness in CI to avoid flakes + expect(spanDurationSeconds).toBeLessThan(1.5); + }, +); diff --git a/dev-packages/browser-integration-tests/suites/tracing/ignoreSpans-streamed/child/init.js b/dev-packages/browser-integration-tests/suites/tracing/ignoreSpans-streamed/child/init.js new file mode 100644 index 000000000000..086383ccdd54 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/ignoreSpans-streamed/child/init.js @@ -0,0 +1,11 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [Sentry.spanStreamingIntegration()], + ignoreSpans: [/ignore/, { op: 'ignored-op' }], + parentSpanIsAlwaysRootSpan: false, + tracesSampleRate: 1, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/ignoreSpans-streamed/child/subject.js b/dev-packages/browser-integration-tests/suites/tracing/ignoreSpans-streamed/child/subject.js new file mode 100644 index 000000000000..47c336e973cd --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/ignoreSpans-streamed/child/subject.js @@ -0,0 +1,31 @@ +Sentry.startSpan({ name: 'parent-span' }, () => { + Sentry.startSpan({ name: 'keep-me' }, () => {}); + + // This child matches ignoreSpans —> dropped + Sentry.startSpan({ name: 'ignore-child' }, () => { + // dropped + Sentry.startSpan({ name: 'ignore-grandchild-1' }, () => { + // kept + Sentry.startSpan({ name: 'great-grandchild-1' }, () => { + // dropped + Sentry.startSpan({ name: 'ignore-great-great-grandchild-1' }, () => { + // kept + Sentry.startSpan({ name: 'great-great-great-grandchild-1' }, () => {}); + }); + }); + }); + // Grandchild is reparented to 'parent-span' —> kept + Sentry.startSpan({ name: 'grandchild-2' }, () => {}); + }); + + // both dropped + Sentry.startSpan({ name: 'name-passes-but-op-not-span-1', op: 'ignored-op' }, () => {}); + Sentry.startSpan( + // sentry.op attribute has precedence over top op argument + { name: 'name-passes-but-op-not-span-2', op: 'keep', attributes: { 'sentry.op': 'ignored-op' } }, + () => {}, + ); + + // kept + Sentry.startSpan({ name: 'another-keeper' }, () => {}); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/ignoreSpans-streamed/child/test.ts b/dev-packages/browser-integration-tests/suites/tracing/ignoreSpans-streamed/child/test.ts new file mode 100644 index 000000000000..967ef101092d --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/ignoreSpans-streamed/child/test.ts @@ -0,0 +1,59 @@ +import { expect } from '@playwright/test'; +import { sentryTest } from '../../../../utils/fixtures'; +import { + envelopeRequestParser, + hidePage, + shouldSkipTracingTest, + testingCdnBundle, + waitForClientReportRequest, +} from '../../../../utils/helpers'; +import { waitForStreamedSpans } from '../../../../utils/spanUtils'; +import type { ClientReport } from '@sentry/core'; + +sentryTest('ignored child spans are dropped and their children are reparented', async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const spansPromise = waitForStreamedSpans(page, spans => !!spans?.find(s => s.name === 'parent-span')); + + const clientReportPromise = waitForClientReportRequest(page); + + const url = await getLocalTestUrl({ testDir: __dirname }); + await page.goto(url); + + const spans = await spansPromise; + + await hidePage(page); + + const clientReport = envelopeRequestParser(await clientReportPromise); + + const segmentSpanId = spans.find(s => s.name === 'parent-span')?.span_id; + + expect(spans.length).toBe(6); + + expect(spans.some(s => s.name === 'keep-me')).toBe(true); + expect(spans.some(s => s.name === 'another-keeper')).toBe(true); + + expect(spans.some(s => s.name?.includes('ignore'))).toBe(false); + + const greatGrandChild1 = spans.find(s => s.name === 'great-grandchild-1'); + const grandchild2 = spans.find(s => s.name === 'grandchild-2'); + const greatGreatGreatGrandChild1 = spans.find(s => s.name === 'great-great-great-grandchild-1'); + + expect(greatGrandChild1).toBeDefined(); + expect(grandchild2).toBeDefined(); + expect(greatGreatGreatGrandChild1).toBeDefined(); + + expect(greatGrandChild1?.parent_span_id).toBe(segmentSpanId); + expect(grandchild2?.parent_span_id).toBe(segmentSpanId); + expect(greatGreatGreatGrandChild1?.parent_span_id).toBe(greatGrandChild1?.span_id); + + expect(spans.every(s => s.name === 'parent-span' || !s.is_segment)).toBe(true); + + expect(clientReport.discarded_events).toEqual([ + { + category: 'span', + quantity: 5, // 5 ignored child spans + reason: 'ignored', + }, + ]); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/ignoreSpans-streamed/segment/init.js b/dev-packages/browser-integration-tests/suites/tracing/ignoreSpans-streamed/segment/init.js new file mode 100644 index 000000000000..3a710324f0e1 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/ignoreSpans-streamed/segment/init.js @@ -0,0 +1,11 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [Sentry.spanStreamingIntegration()], + ignoreSpans: [/ignore/], + tracesSampleRate: 1, + debug: true, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/ignoreSpans-streamed/segment/subject.js b/dev-packages/browser-integration-tests/suites/tracing/ignoreSpans-streamed/segment/subject.js new file mode 100644 index 000000000000..645668376b36 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/ignoreSpans-streamed/segment/subject.js @@ -0,0 +1,11 @@ +// This segment span matches ignoreSpans — should NOT produce a transaction +Sentry.startSpan({ name: 'ignore-segment' }, () => { + Sentry.startSpan({ name: 'child-of-ignored-segment' }, () => {}); +}); + +setTimeout(() => { + // This segment span does NOT match — should produce a transaction + Sentry.startSpan({ name: 'normal-segment' }, () => { + Sentry.startSpan({ name: 'child-span' }, () => {}); + }); +}, 1000); diff --git a/dev-packages/browser-integration-tests/suites/tracing/ignoreSpans-streamed/segment/test.ts b/dev-packages/browser-integration-tests/suites/tracing/ignoreSpans-streamed/segment/test.ts new file mode 100644 index 000000000000..93042cc5469e --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/ignoreSpans-streamed/segment/test.ts @@ -0,0 +1,44 @@ +import { expect } from '@playwright/test'; +import { sentryTest } from '../../../../utils/fixtures'; +import { + envelopeRequestParser, + hidePage, + shouldSkipTracingTest, + testingCdnBundle, + waitForClientReportRequest, +} from '../../../../utils/helpers'; +import { observeStreamedSpan, waitForStreamedSpans } from '../../../../utils/spanUtils'; +import type { ClientReport } from '@sentry/core'; + +sentryTest('ignored segment span drops entire trace', async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + observeStreamedSpan(page, span => { + if (span.name === 'ignore-segment' || span.name === 'child-of-ignored-segment') { + throw new Error('Ignored span found'); + } + return false; // means we keep on looking for unwanted spans + }); + + const spansPromise = waitForStreamedSpans(page, spans => !!spans?.find(s => s.name === 'normal-segment')); + + const clientReportPromise = waitForClientReportRequest(page); + + await page.goto(url); + + expect((await spansPromise)?.length).toBe(2); + + await hidePage(page); + + const clientReport = envelopeRequestParser(await clientReportPromise); + + expect(clientReport.discarded_events).toEqual([ + { + category: 'span', + quantity: 2, // segment + child span + reason: 'ignored', + }, + ]); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/linking-addLink-streamed/init.js b/dev-packages/browser-integration-tests/suites/tracing/linking-addLink-streamed/init.js new file mode 100644 index 000000000000..9afcee48dc4a --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/linking-addLink-streamed/init.js @@ -0,0 +1,9 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [Sentry.spanStreamingIntegration()], + tracesSampleRate: 1, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/linking-addLink-streamed/subject.js b/dev-packages/browser-integration-tests/suites/tracing/linking-addLink-streamed/subject.js new file mode 100644 index 000000000000..510fb07540ad --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/linking-addLink-streamed/subject.js @@ -0,0 +1,28 @@ +// REGULAR --- +const rootSpan1 = Sentry.startInactiveSpan({ name: 'rootSpan1' }); +rootSpan1.end(); + +Sentry.startSpan({ name: 'rootSpan2' }, rootSpan2 => { + rootSpan2.addLink({ + context: rootSpan1.spanContext(), + attributes: { 'sentry.link.type': 'previous_trace' }, + }); +}); + +// NESTED --- +Sentry.startSpan({ name: 'rootSpan3' }, async rootSpan3 => { + Sentry.startSpan({ name: 'childSpan3.1' }, async childSpan1 => { + childSpan1.addLink({ + context: rootSpan1.spanContext(), + attributes: { 'sentry.link.type': 'previous_trace' }, + }); + + childSpan1.end(); + }); + + Sentry.startSpan({ name: 'childSpan3.2' }, async childSpan2 => { + childSpan2.addLink({ context: rootSpan3.spanContext() }); + + childSpan2.end(); + }); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/linking-addLink-streamed/test.ts b/dev-packages/browser-integration-tests/suites/tracing/linking-addLink-streamed/test.ts new file mode 100644 index 000000000000..dc35f0c8fcf1 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/linking-addLink-streamed/test.ts @@ -0,0 +1,66 @@ +import { expect } from '@playwright/test'; +import { sentryTest } from '../../../utils/fixtures'; +import { shouldSkipTracingTest, testingCdnBundle } from '../../../utils/helpers'; +import { waitForStreamedSpan, waitForStreamedSpans } from '../../../utils/spanUtils'; + +sentryTest('links spans with addLink() in trace context', async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const rootSpan1Promise = waitForStreamedSpan(page, s => s.name === 'rootSpan1' && !!s.is_segment); + const rootSpan2Promise = waitForStreamedSpan(page, s => s.name === 'rootSpan2' && !!s.is_segment); + + const url = await getLocalTestUrl({ testDir: __dirname }); + await page.goto(url); + + const rootSpan1 = await rootSpan1Promise; + const rootSpan2 = await rootSpan2Promise; + + expect(rootSpan1.name).toBe('rootSpan1'); + expect(rootSpan1.links).toBeUndefined(); + + expect(rootSpan2.name).toBe('rootSpan2'); + expect(rootSpan2.links).toHaveLength(1); + expect(rootSpan2.links?.[0]).toMatchObject({ + attributes: { 'sentry.link.type': { type: 'string', value: 'previous_trace' } }, + sampled: true, + span_id: rootSpan1.span_id, + trace_id: rootSpan1.trace_id, + }); +}); + +sentryTest('links spans with addLink() in nested startSpan() calls', async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const rootSpan1Promise = waitForStreamedSpan(page, s => s.name === 'rootSpan1' && !!s.is_segment); + const rootSpan3SpansPromise = waitForStreamedSpans(page, spans => + spans.some(s => s.name === 'rootSpan3' && s.is_segment), + ); + + const url = await getLocalTestUrl({ testDir: __dirname }); + await page.goto(url); + + const rootSpan1 = await rootSpan1Promise; + const rootSpan3Spans = await rootSpan3SpansPromise; + + const rootSpan3 = rootSpan3Spans.find(s => s.name === 'rootSpan3')!; + const childSpan1 = rootSpan3Spans.find(s => s.name === 'childSpan3.1')!; + const childSpan2 = rootSpan3Spans.find(s => s.name === 'childSpan3.2')!; + + expect(rootSpan3.name).toBe('rootSpan3'); + + expect(childSpan1.name).toBe('childSpan3.1'); + expect(childSpan1.links).toHaveLength(1); + expect(childSpan1.links?.[0]).toMatchObject({ + attributes: { 'sentry.link.type': { type: 'string', value: 'previous_trace' } }, + sampled: true, + span_id: rootSpan1.span_id, + trace_id: rootSpan1.trace_id, + }); + + expect(childSpan2.name).toBe('childSpan3.2'); + expect(childSpan2.links?.[0]).toMatchObject({ + sampled: true, + span_id: rootSpan3.span_id, + trace_id: rootSpan3.trace_id, + }); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/request/fetch-streamed/init.js b/dev-packages/browser-integration-tests/suites/tracing/request/fetch-streamed/init.js new file mode 100644 index 000000000000..c4c8791cf32c --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/request/fetch-streamed/init.js @@ -0,0 +1,11 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [Sentry.browserTracingIntegration(), Sentry.spanStreamingIntegration()], + tracePropagationTargets: ['http://sentry-test-site.example'], + tracesSampleRate: 1, + autoSessionTracking: false, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/request/fetch-streamed/subject.js b/dev-packages/browser-integration-tests/suites/tracing/request/fetch-streamed/subject.js new file mode 100644 index 000000000000..482a738009c2 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/request/fetch-streamed/subject.js @@ -0,0 +1,5 @@ +fetch('http://sentry-test-site.example/0').then( + fetch('http://sentry-test-site.example/1', { headers: { 'X-Test-Header': 'existing-header' } }).then( + fetch('http://sentry-test-site.example/2'), + ), +); diff --git a/dev-packages/browser-integration-tests/suites/tracing/request/fetch-streamed/test.ts b/dev-packages/browser-integration-tests/suites/tracing/request/fetch-streamed/test.ts new file mode 100644 index 000000000000..201c3e4979f2 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/request/fetch-streamed/test.ts @@ -0,0 +1,43 @@ +import { expect } from '@playwright/test'; +import { sentryTest } from '../../../../utils/fixtures'; +import { shouldSkipTracingTest, testingCdnBundle } from '../../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpans } from '../../../../utils/spanUtils'; + +sentryTest('creates spans for fetch requests', async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + await page.route('http://sentry-test-site.example/*', route => route.fulfill({ body: 'ok' })); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + const spansPromise = waitForStreamedSpans( + page, + spans => spans.filter(s => getSpanOp(s) === 'http.client').length >= 3, + ); + + await page.goto(url); + + const allSpans = await spansPromise; + const pageloadSpan = allSpans.find(s => getSpanOp(s) === 'pageload'); + const requestSpans = allSpans.filter(s => getSpanOp(s) === 'http.client'); + + expect(requestSpans).toHaveLength(3); + + requestSpans.forEach((span, index) => + expect(span).toMatchObject({ + name: `GET http://sentry-test-site.example/${index}`, + parent_span_id: pageloadSpan?.span_id, + span_id: expect.stringMatching(/[a-f\d]{16}/), + start_timestamp: expect.any(Number), + end_timestamp: expect.any(Number), + trace_id: pageloadSpan?.trace_id, + attributes: expect.objectContaining({ + 'http.method': { type: 'string', value: 'GET' }, + 'http.url': { type: 'string', value: `http://sentry-test-site.example/${index}` }, + url: { type: 'string', value: `http://sentry-test-site.example/${index}` }, + 'server.address': { type: 'string', value: 'sentry-test-site.example' }, + type: { type: 'string', value: 'fetch' }, + }), + }), + ); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/request/xhr-streamed/init.js b/dev-packages/browser-integration-tests/suites/tracing/request/xhr-streamed/init.js new file mode 100644 index 000000000000..c4c8791cf32c --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/request/xhr-streamed/init.js @@ -0,0 +1,11 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [Sentry.browserTracingIntegration(), Sentry.spanStreamingIntegration()], + tracePropagationTargets: ['http://sentry-test-site.example'], + tracesSampleRate: 1, + autoSessionTracking: false, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/request/xhr-streamed/subject.js b/dev-packages/browser-integration-tests/suites/tracing/request/xhr-streamed/subject.js new file mode 100644 index 000000000000..9c584bf743cb --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/request/xhr-streamed/subject.js @@ -0,0 +1,12 @@ +const xhr_1 = new XMLHttpRequest(); +xhr_1.open('GET', 'http://sentry-test-site.example/0'); +xhr_1.send(); + +const xhr_2 = new XMLHttpRequest(); +xhr_2.open('GET', 'http://sentry-test-site.example/1'); +xhr_2.setRequestHeader('X-Test-Header', 'existing-header'); +xhr_2.send(); + +const xhr_3 = new XMLHttpRequest(); +xhr_3.open('GET', 'http://sentry-test-site.example/2'); +xhr_3.send(); diff --git a/dev-packages/browser-integration-tests/suites/tracing/request/xhr-streamed/test.ts b/dev-packages/browser-integration-tests/suites/tracing/request/xhr-streamed/test.ts new file mode 100644 index 000000000000..d3f20fd36453 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/request/xhr-streamed/test.ts @@ -0,0 +1,43 @@ +import { expect } from '@playwright/test'; +import { sentryTest } from '../../../../utils/fixtures'; +import { shouldSkipTracingTest, testingCdnBundle } from '../../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpans } from '../../../../utils/spanUtils'; + +sentryTest('creates spans for XHR requests', async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + await page.route('http://sentry-test-site.example/*', route => route.fulfill({ body: 'ok' })); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + const spansPromise = waitForStreamedSpans( + page, + spans => spans.filter(s => getSpanOp(s) === 'http.client').length >= 3, + ); + + await page.goto(url); + + const allSpans = await spansPromise; + const pageloadSpan = allSpans.find(s => getSpanOp(s) === 'pageload'); + const requestSpans = allSpans.filter(s => getSpanOp(s) === 'http.client'); + + expect(requestSpans).toHaveLength(3); + + requestSpans.forEach((span, index) => + expect(span).toMatchObject({ + name: `GET http://sentry-test-site.example/${index}`, + parent_span_id: pageloadSpan?.span_id, + span_id: expect.stringMatching(/[a-f\d]{16}/), + start_timestamp: expect.any(Number), + end_timestamp: expect.any(Number), + trace_id: pageloadSpan?.trace_id, + attributes: expect.objectContaining({ + 'http.method': { type: 'string', value: 'GET' }, + 'http.url': { type: 'string', value: `http://sentry-test-site.example/${index}` }, + url: { type: 'string', value: `http://sentry-test-site.example/${index}` }, + 'server.address': { type: 'string', value: 'sentry-test-site.example' }, + type: { type: 'string', value: 'xhr' }, + }), + }), + ); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/setSpanActive-streamed/default/init.js b/dev-packages/browser-integration-tests/suites/tracing/setSpanActive-streamed/default/init.js new file mode 100644 index 000000000000..9afcee48dc4a --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/setSpanActive-streamed/default/init.js @@ -0,0 +1,9 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [Sentry.spanStreamingIntegration()], + tracesSampleRate: 1, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/setSpanActive-streamed/default/subject.js b/dev-packages/browser-integration-tests/suites/tracing/setSpanActive-streamed/default/subject.js new file mode 100644 index 000000000000..0ce39588eb1b --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/setSpanActive-streamed/default/subject.js @@ -0,0 +1,14 @@ +const checkoutSpan = Sentry.startInactiveSpan({ name: 'checkout-flow' }); +Sentry.setActiveSpanInBrowser(checkoutSpan); + +Sentry.startSpan({ name: 'checkout-step-1' }, () => { + Sentry.startSpan({ name: 'checkout-step-1-1' }, () => { + // ... ` + }); +}); + +Sentry.startSpan({ name: 'checkout-step-2' }, () => { + // ... ` +}); + +checkoutSpan.end(); diff --git a/dev-packages/browser-integration-tests/suites/tracing/setSpanActive-streamed/default/test.ts b/dev-packages/browser-integration-tests/suites/tracing/setSpanActive-streamed/default/test.ts new file mode 100644 index 000000000000..a144e171a93a --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/setSpanActive-streamed/default/test.ts @@ -0,0 +1,35 @@ +import { expect } from '@playwright/test'; +import { sentryTest } from '../../../../utils/fixtures'; +import { shouldSkipTracingTest, testingCdnBundle } from '../../../../utils/helpers'; +import { waitForStreamedSpans } from '../../../../utils/spanUtils'; + +sentryTest('sets an inactive span active and adds child spans to it', async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const spansPromise = waitForStreamedSpans(page, spans => spans.some(s => s.name === 'checkout-flow' && s.is_segment)); + + const url = await getLocalTestUrl({ testDir: __dirname }); + await page.goto(url); + + const spans = await spansPromise; + const checkoutSpan = spans.find(s => s.name === 'checkout-flow'); + const checkoutSpanId = checkoutSpan?.span_id; + expect(checkoutSpanId).toMatch(/[a-f\d]{16}/); + + expect(spans.filter(s => !s.is_segment)).toHaveLength(3); + + const checkoutStep1 = spans.find(s => s.name === 'checkout-step-1'); + const checkoutStep11 = spans.find(s => s.name === 'checkout-step-1-1'); + const checkoutStep2 = spans.find(s => s.name === 'checkout-step-2'); + + expect(checkoutStep1).toBeDefined(); + expect(checkoutStep11).toBeDefined(); + expect(checkoutStep2).toBeDefined(); + + expect(checkoutStep1?.parent_span_id).toBe(checkoutSpanId); + expect(checkoutStep2?.parent_span_id).toBe(checkoutSpanId); + + // despite 1-1 being called within 1, it's still parented to the root span + // due to this being default behaviour in browser environments + expect(checkoutStep11?.parent_span_id).toBe(checkoutSpanId); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/setSpanActive-streamed/nested-parentAlwaysRoot/init.js b/dev-packages/browser-integration-tests/suites/tracing/setSpanActive-streamed/nested-parentAlwaysRoot/init.js new file mode 100644 index 000000000000..5b4cff73e95d --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/setSpanActive-streamed/nested-parentAlwaysRoot/init.js @@ -0,0 +1,10 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [Sentry.spanStreamingIntegration()], + tracesSampleRate: 1, + parentSpanIsAlwaysRootSpan: false, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/setSpanActive-streamed/nested-parentAlwaysRoot/subject.js b/dev-packages/browser-integration-tests/suites/tracing/setSpanActive-streamed/nested-parentAlwaysRoot/subject.js new file mode 100644 index 000000000000..dc601cbf4d30 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/setSpanActive-streamed/nested-parentAlwaysRoot/subject.js @@ -0,0 +1,22 @@ +const checkoutSpan = Sentry.startInactiveSpan({ name: 'checkout-flow' }); +Sentry.setActiveSpanInBrowser(checkoutSpan); + +Sentry.startSpan({ name: 'checkout-step-1' }, () => {}); + +const checkoutStep2 = Sentry.startInactiveSpan({ name: 'checkout-step-2' }); +Sentry.setActiveSpanInBrowser(checkoutStep2); + +Sentry.startSpan({ name: 'checkout-step-2-1' }, () => { + // ... ` +}); +checkoutStep2.end(); + +Sentry.startSpan({ name: 'checkout-step-3' }, () => {}); + +checkoutSpan.end(); + +Sentry.startSpan({ name: 'post-checkout' }, () => { + Sentry.startSpan({ name: 'post-checkout-1' }, () => { + // ... ` + }); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/setSpanActive-streamed/nested-parentAlwaysRoot/test.ts b/dev-packages/browser-integration-tests/suites/tracing/setSpanActive-streamed/nested-parentAlwaysRoot/test.ts new file mode 100644 index 000000000000..8f5e54e1fba0 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/setSpanActive-streamed/nested-parentAlwaysRoot/test.ts @@ -0,0 +1,58 @@ +import { expect } from '@playwright/test'; +import { sentryTest } from '../../../../utils/fixtures'; +import { shouldSkipTracingTest, testingCdnBundle } from '../../../../utils/helpers'; +import { waitForStreamedSpans } from '../../../../utils/spanUtils'; + +sentryTest( + 'nested calls to setActiveSpanInBrowser with parentSpanIsAlwaysRootSpan=false result in correct parenting', + async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const checkoutSpansPromise = waitForStreamedSpans(page, spans => + spans.some(s => s.name === 'checkout-flow' && s.is_segment), + ); + + const url = await getLocalTestUrl({ testDir: __dirname }); + await page.goto(url); + + const checkoutSpans = await checkoutSpansPromise; + + const checkoutSpan = checkoutSpans.find(s => s.name === 'checkout-flow'); + const postCheckoutSpan = checkoutSpans.find(s => s.name === 'post-checkout'); + + const checkoutSpanId = checkoutSpan?.span_id; + const postCheckoutSpanId = postCheckoutSpan?.span_id; + + expect(checkoutSpanId).toMatch(/[a-f\d]{16}/); + expect(postCheckoutSpanId).toMatch(/[a-f\d]{16}/); + + expect(checkoutSpans.filter(s => !s.is_segment)).toHaveLength(5); + + const checkoutStep1 = checkoutSpans.find(s => s.name === 'checkout-step-1'); + const checkoutStep2 = checkoutSpans.find(s => s.name === 'checkout-step-2'); + const checkoutStep21 = checkoutSpans.find(s => s.name === 'checkout-step-2-1'); + const checkoutStep3 = checkoutSpans.find(s => s.name === 'checkout-step-3'); + + expect(checkoutStep1).toBeDefined(); + expect(checkoutStep2).toBeDefined(); + expect(checkoutStep21).toBeDefined(); + expect(checkoutStep3).toBeDefined(); + + expect(checkoutStep1?.parent_span_id).toBe(checkoutSpanId); + expect(checkoutStep2?.parent_span_id).toBe(checkoutSpanId); + + // with parentSpanIsAlwaysRootSpan=false, 2-1 is parented to 2 because + // 2 was the active span when 2-1 was started + expect(checkoutStep21?.parent_span_id).toBe(checkoutStep2?.span_id); + + // since the parent of three is `checkoutSpan`, we correctly reset + // the active span to `checkoutSpan` after 2 ended + expect(checkoutStep3?.parent_span_id).toBe(checkoutSpanId); + + // post-checkout trace is started as a new trace because ending checkoutSpan removes the active + // span on the scope + const postCheckoutStep1 = checkoutSpans.find(s => s.name === 'post-checkout-1'); + expect(postCheckoutStep1).toBeDefined(); + expect(postCheckoutStep1?.parent_span_id).toBe(postCheckoutSpanId); + }, +); diff --git a/dev-packages/browser-integration-tests/suites/tracing/setSpanActive-streamed/nested/init.js b/dev-packages/browser-integration-tests/suites/tracing/setSpanActive-streamed/nested/init.js new file mode 100644 index 000000000000..9afcee48dc4a --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/setSpanActive-streamed/nested/init.js @@ -0,0 +1,9 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [Sentry.spanStreamingIntegration()], + tracesSampleRate: 1, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/setSpanActive-streamed/nested/subject.js b/dev-packages/browser-integration-tests/suites/tracing/setSpanActive-streamed/nested/subject.js new file mode 100644 index 000000000000..dc601cbf4d30 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/setSpanActive-streamed/nested/subject.js @@ -0,0 +1,22 @@ +const checkoutSpan = Sentry.startInactiveSpan({ name: 'checkout-flow' }); +Sentry.setActiveSpanInBrowser(checkoutSpan); + +Sentry.startSpan({ name: 'checkout-step-1' }, () => {}); + +const checkoutStep2 = Sentry.startInactiveSpan({ name: 'checkout-step-2' }); +Sentry.setActiveSpanInBrowser(checkoutStep2); + +Sentry.startSpan({ name: 'checkout-step-2-1' }, () => { + // ... ` +}); +checkoutStep2.end(); + +Sentry.startSpan({ name: 'checkout-step-3' }, () => {}); + +checkoutSpan.end(); + +Sentry.startSpan({ name: 'post-checkout' }, () => { + Sentry.startSpan({ name: 'post-checkout-1' }, () => { + // ... ` + }); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/setSpanActive-streamed/nested/test.ts b/dev-packages/browser-integration-tests/suites/tracing/setSpanActive-streamed/nested/test.ts new file mode 100644 index 000000000000..1b04553090bc --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/setSpanActive-streamed/nested/test.ts @@ -0,0 +1,53 @@ +import { expect } from '@playwright/test'; +import { sentryTest } from '../../../../utils/fixtures'; +import { shouldSkipTracingTest, testingCdnBundle } from '../../../../utils/helpers'; +import { waitForStreamedSpans } from '../../../../utils/spanUtils'; + +sentryTest( + 'nested calls to setActiveSpanInBrowser still parent to root span by default', + async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const checkoutSpansPromise = waitForStreamedSpans(page, spans => + spans.some(s => s.name === 'checkout-flow' && s.is_segment), + ); + + const url = await getLocalTestUrl({ testDir: __dirname }); + await page.goto(url); + + const checkoutSpans = await checkoutSpansPromise; + + const checkoutSpan = checkoutSpans.find(s => s.name === 'checkout-flow'); + const postCheckoutSpan = checkoutSpans.find(s => s.name === 'post-checkout'); + + const checkoutSpanId = checkoutSpan?.span_id; + const postCheckoutSpanId = postCheckoutSpan?.span_id; + + expect(checkoutSpanId).toMatch(/[a-f\d]{16}/); + expect(postCheckoutSpanId).toMatch(/[a-f\d]{16}/); + + expect(checkoutSpans.filter(s => !s.is_segment)).toHaveLength(5); + + const checkoutStep1 = checkoutSpans.find(s => s.name === 'checkout-step-1'); + const checkoutStep2 = checkoutSpans.find(s => s.name === 'checkout-step-2'); + const checkoutStep21 = checkoutSpans.find(s => s.name === 'checkout-step-2-1'); + const checkoutStep3 = checkoutSpans.find(s => s.name === 'checkout-step-3'); + + expect(checkoutStep1).toBeDefined(); + expect(checkoutStep2).toBeDefined(); + expect(checkoutStep21).toBeDefined(); + expect(checkoutStep3).toBeDefined(); + + expect(checkoutStep1?.parent_span_id).toBe(checkoutSpanId); + expect(checkoutStep2?.parent_span_id).toBe(checkoutSpanId); + expect(checkoutStep3?.parent_span_id).toBe(checkoutSpanId); + + // despite 2-1 being called within 2 AND setting 2 as active span, it's still parented to the + // root span due to this being default behaviour in browser environments + expect(checkoutStep21?.parent_span_id).toBe(checkoutSpanId); + + const postCheckoutStep1 = checkoutSpans.find(s => s.name === 'post-checkout-1'); + expect(postCheckoutStep1).toBeDefined(); + expect(postCheckoutStep1?.parent_span_id).toBe(postCheckoutSpanId); + }, +); diff --git a/dev-packages/browser-integration-tests/suites/tracing/trace-lifetime/navigation-streamed/init.js b/dev-packages/browser-integration-tests/suites/tracing/trace-lifetime/navigation-streamed/init.js new file mode 100644 index 000000000000..3dd77207e103 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/trace-lifetime/navigation-streamed/init.js @@ -0,0 +1,12 @@ +import * as Sentry from '@sentry/browser'; +// Import this separately so that generatePlugin can handle it for CDN scenarios +import { feedbackIntegration } from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [Sentry.browserTracingIntegration(), feedbackIntegration(), Sentry.spanStreamingIntegration()], + tracePropagationTargets: ['http://sentry-test-site.example'], + tracesSampleRate: 1, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/trace-lifetime/navigation-streamed/test.ts b/dev-packages/browser-integration-tests/suites/tracing/trace-lifetime/navigation-streamed/test.ts new file mode 100644 index 000000000000..28f3e5039910 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/trace-lifetime/navigation-streamed/test.ts @@ -0,0 +1,318 @@ +import { expect } from '@playwright/test'; +import type { Event } from '@sentry/core'; +import { sentryTest } from '../../../../utils/fixtures'; +import type { EventAndTraceHeader } from '../../../../utils/helpers'; +import { + eventAndTraceHeaderRequestParser, + getFirstSentryEnvelopeRequest, + shouldSkipFeedbackTest, + shouldSkipTracingTest, + testingCdnBundle, +} from '../../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpan, waitForStreamedSpanEnvelope } from '../../../../utils/spanUtils'; + +sentryTest('creates a new trace and sample_rand on each navigation', async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + // Wait for and skip the initial pageload span + const pageloadSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'pageload'); + await page.goto(url); + await pageloadSpanPromise; + + const navigation1SpanEnvelopePromise = waitForStreamedSpanEnvelope( + page, + env => !!env[1][0][1].items.find(s => getSpanOp(s) === 'navigation'), + ); + await page.goto(`${url}#foo`); + const navigation1SpanEnvelope = await navigation1SpanEnvelopePromise; + + const navigation2SpanEnvelopePromise = waitForStreamedSpanEnvelope( + page, + env => !!env[1][0][1].items.find(s => getSpanOp(s) === 'navigation'), + ); + await page.goto(`${url}#bar`); + const navigation2SpanEnvelope = await navigation2SpanEnvelopePromise; + + const navigation1TraceId = navigation1SpanEnvelope[0].trace?.trace_id; + const navigation1SampleRand = navigation1SpanEnvelope[0].trace?.sample_rand; + const navigation2TraceId = navigation2SpanEnvelope[0].trace?.trace_id; + const navigation2SampleRand = navigation2SpanEnvelope[0].trace?.sample_rand; + + const navigation1Span = navigation1SpanEnvelope[1][0][1].items.find(s => getSpanOp(s) === 'navigation')!; + const navigation2Span = navigation2SpanEnvelope[1][0][1].items.find(s => getSpanOp(s) === 'navigation')!; + + expect(getSpanOp(navigation1Span)).toEqual('navigation'); + expect(navigation1TraceId).toMatch(/^[\da-f]{32}$/); + expect(navigation1Span.span_id).toMatch(/^[\da-f]{16}$/); + expect(navigation1Span.parent_span_id).toBeUndefined(); + + expect(navigation1SpanEnvelope[0].trace).toEqual({ + environment: 'production', + public_key: 'public', + sample_rate: '1', + sampled: 'true', + trace_id: navigation1TraceId, + sample_rand: expect.any(String), + }); + + expect(getSpanOp(navigation2Span)).toEqual('navigation'); + expect(navigation2TraceId).toMatch(/^[\da-f]{32}$/); + expect(navigation2Span.span_id).toMatch(/^[\da-f]{16}$/); + expect(navigation2Span.parent_span_id).toBeUndefined(); + + expect(navigation2SpanEnvelope[0].trace).toEqual({ + environment: 'production', + public_key: 'public', + sample_rate: '1', + sampled: 'true', + trace_id: navigation2TraceId, + sample_rand: expect.any(String), + }); + + expect(navigation1TraceId).not.toEqual(navigation2TraceId); + expect(navigation1SampleRand).not.toEqual(navigation2SampleRand); +}); + +sentryTest('error after navigation has navigation traceId', async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + // ensure pageload span is finished + const pageloadSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'pageload'); + await page.goto(url); + await pageloadSpanPromise; + + const navigationSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'navigation'); + const navigationSpanEnvelopePromise = waitForStreamedSpanEnvelope( + page, + env => !!env[1][0][1].items.find(s => getSpanOp(s) === 'navigation'), + ); + await page.goto(`${url}#foo`); + const [navigationSpan, navigationSpanEnvelope] = await Promise.all([ + navigationSpanPromise, + navigationSpanEnvelopePromise, + ]); + + const navigationTraceId = navigationSpan.trace_id; + + expect(getSpanOp(navigationSpan)).toEqual('navigation'); + expect(navigationTraceId).toMatch(/^[\da-f]{32}$/); + expect(navigationSpan.span_id).toMatch(/^[\da-f]{16}$/); + expect(navigationSpan.parent_span_id).toBeUndefined(); + + expect(navigationSpanEnvelope[0].trace).toEqual({ + environment: 'production', + public_key: 'public', + sample_rate: '1', + sampled: 'true', + trace_id: navigationTraceId, + sample_rand: expect.any(String), + }); + + const errorEventPromise = getFirstSentryEnvelopeRequest( + page, + undefined, + eventAndTraceHeaderRequestParser, + ); + await page.locator('#errorBtn').click(); + const [errorEvent, errorTraceHeader] = await errorEventPromise; + + expect(errorEvent.type).toEqual(undefined); + + const errorTraceContext = errorEvent.contexts?.trace; + expect(errorTraceContext).toEqual({ + trace_id: navigationTraceId, + span_id: expect.stringMatching(/^[\da-f]{16}$/), + }); + expect(errorTraceHeader).toEqual({ + environment: 'production', + public_key: 'public', + sample_rate: '1', + sampled: 'true', + trace_id: navigationTraceId, + sample_rand: expect.any(String), + }); +}); + +sentryTest('error during navigation has new navigation traceId', async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + // ensure pageload span is finished + const pageloadSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'pageload'); + await page.goto(url); + await pageloadSpanPromise; + + const navigationSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'navigation'); + const errorEventPromise = getFirstSentryEnvelopeRequest( + page, + undefined, + eventAndTraceHeaderRequestParser, + ); + + await page.goto(`${url}#foo`); + await page.locator('#errorBtn').click(); + const [navigationSpan, [errorEvent, errorTraceHeader]] = await Promise.all([ + navigationSpanPromise, + errorEventPromise, + ]); + + expect(getSpanOp(navigationSpan)).toEqual('navigation'); + expect(errorEvent.type).toEqual(undefined); + + const navigationTraceId = navigationSpan.trace_id; + expect(navigationTraceId).toMatch(/^[\da-f]{32}$/); + expect(navigationSpan.span_id).toMatch(/^[\da-f]{16}$/); + expect(navigationSpan.parent_span_id).toBeUndefined(); + + const errorTraceContext = errorEvent?.contexts?.trace; + expect(errorTraceContext).toEqual({ + trace_id: navigationTraceId, + span_id: expect.stringMatching(/^[\da-f]{16}$/), + }); + + expect(errorTraceHeader).toEqual({ + environment: 'production', + public_key: 'public', + sample_rate: '1', + sampled: 'true', + trace_id: navigationTraceId, + sample_rand: expect.any(String), + }); +}); + +sentryTest( + 'outgoing fetch request during navigation has navigation traceId in headers', + async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + await page.route('http://sentry-test-site.example/**', route => { + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({}), + }); + }); + + // ensure pageload span is finished + const pageloadSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'pageload'); + await page.goto(url); + await pageloadSpanPromise; + + const navigationSpanEnvelopePromise = waitForStreamedSpanEnvelope( + page, + env => !!env[1][0][1].items.find(s => getSpanOp(s) === 'navigation'), + ); + const requestPromise = page.waitForRequest('http://sentry-test-site.example/*'); + await page.goto(`${url}#foo`); + await page.locator('#fetchBtn').click(); + const [navigationSpanEnvelope, request] = await Promise.all([navigationSpanEnvelopePromise, requestPromise]); + + const navigationTraceId = navigationSpanEnvelope[0].trace?.trace_id; + const sampleRand = navigationSpanEnvelope[0].trace?.sample_rand; + + expect(navigationTraceId).toMatch(/^[\da-f]{32}$/); + + const headers = request.headers(); + + // sampling decision is propagated from active span sampling decision + expect(headers['sentry-trace']).toMatch(new RegExp(`^${navigationTraceId}-[0-9a-f]{16}-1$`)); + expect(headers['baggage']).toEqual( + `sentry-environment=production,sentry-public_key=public,sentry-trace_id=${navigationTraceId},sentry-sampled=true,sentry-sample_rand=${sampleRand},sentry-sample_rate=1`, + ); + }, +); + +sentryTest( + 'outgoing XHR request during navigation has navigation traceId in headers', + async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + await page.route('http://sentry-test-site.example/**', route => { + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({}), + }); + }); + + // ensure navigation span is finished + const pageloadSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'pageload'); + await page.goto(url); + await pageloadSpanPromise; + + const navigationSpanEnvelopePromise = waitForStreamedSpanEnvelope( + page, + env => !!env[1][0][1].items.find(s => getSpanOp(s) === 'navigation'), + ); + const requestPromise = page.waitForRequest('http://sentry-test-site.example/*'); + await page.goto(`${url}#foo`); + await page.locator('#xhrBtn').click(); + const [navigationSpanEnvelope, request] = await Promise.all([navigationSpanEnvelopePromise, requestPromise]); + + const navigationTraceId = navigationSpanEnvelope[0].trace?.trace_id; + const sampleRand = navigationSpanEnvelope[0].trace?.sample_rand; + + expect(navigationTraceId).toMatch(/^[\da-f]{32}$/); + + const headers = request.headers(); + + // sampling decision is propagated from active span sampling decision + expect(headers['sentry-trace']).toMatch(new RegExp(`^${navigationTraceId}-[0-9a-f]{16}-1$`)); + expect(headers['baggage']).toEqual( + `sentry-environment=production,sentry-public_key=public,sentry-trace_id=${navigationTraceId},sentry-sampled=true,sentry-sample_rand=${sampleRand},sentry-sample_rate=1`, + ); + }, +); + +sentryTest( + 'user feedback event after navigation has navigation traceId in headers', + async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || shouldSkipFeedbackTest() || testingCdnBundle()); + + const url = await getLocalTestUrl({ testDir: __dirname, handleLazyLoadedFeedback: true }); + + // ensure pageload span is finished + const pageloadSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'pageload'); + await page.goto(url); + await pageloadSpanPromise; + + const navigationSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'navigation'); + await page.goto(`${url}#foo`); + const navigationSpan = await navigationSpanPromise; + + const navigationTraceId = navigationSpan.trace_id; + expect(getSpanOp(navigationSpan)).toEqual('navigation'); + expect(navigationTraceId).toMatch(/^[\da-f]{32}$/); + expect(navigationSpan.span_id).toMatch(/^[\da-f]{16}$/); + expect(navigationSpan.parent_span_id).toBeUndefined(); + + const feedbackEventPromise = getFirstSentryEnvelopeRequest(page); + + await page.getByText('Report a Bug').click(); + expect(await page.locator(':visible:text-is("Report a Bug")').count()).toEqual(1); + await page.locator('[name="name"]').fill('Jane Doe'); + await page.locator('[name="email"]').fill('janedoe@example.org'); + await page.locator('[name="message"]').fill('my example feedback'); + await page.locator('[data-sentry-feedback] .btn--primary').click(); + + const feedbackEvent = await feedbackEventPromise; + + expect(feedbackEvent.type).toEqual('feedback'); + + const feedbackTraceContext = feedbackEvent.contexts?.trace; + + expect(feedbackTraceContext).toMatchObject({ + trace_id: navigationTraceId, + span_id: expect.stringMatching(/^[\da-f]{16}$/), + }); + }, +); diff --git a/dev-packages/browser-integration-tests/suites/tracing/trace-lifetime/pageload-streamed/init.js b/dev-packages/browser-integration-tests/suites/tracing/trace-lifetime/pageload-streamed/init.js new file mode 100644 index 000000000000..3dd77207e103 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/trace-lifetime/pageload-streamed/init.js @@ -0,0 +1,12 @@ +import * as Sentry from '@sentry/browser'; +// Import this separately so that generatePlugin can handle it for CDN scenarios +import { feedbackIntegration } from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [Sentry.browserTracingIntegration(), feedbackIntegration(), Sentry.spanStreamingIntegration()], + tracePropagationTargets: ['http://sentry-test-site.example'], + tracesSampleRate: 1, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/trace-lifetime/pageload-streamed/test.ts b/dev-packages/browser-integration-tests/suites/tracing/trace-lifetime/pageload-streamed/test.ts new file mode 100644 index 000000000000..1b4458991559 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/trace-lifetime/pageload-streamed/test.ts @@ -0,0 +1,238 @@ +import { expect } from '@playwright/test'; +import type { Event } from '@sentry/core'; +import { sentryTest } from '../../../../utils/fixtures'; +import type { EventAndTraceHeader } from '../../../../utils/helpers'; +import { + eventAndTraceHeaderRequestParser, + getFirstSentryEnvelopeRequest, + shouldSkipFeedbackTest, + shouldSkipTracingTest, + testingCdnBundle, +} from '../../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpan, waitForStreamedSpanEnvelope } from '../../../../utils/spanUtils'; + +sentryTest('creates a new trace for a navigation after the initial pageload', async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const pageloadSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'pageload'); + const navigationSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'navigation'); + + const url = await getLocalTestUrl({ testDir: __dirname }); + await page.goto(url); + + const pageloadSpan = await pageloadSpanPromise; + + page.goto(`${url}#foo`); + + const navigationSpan = await navigationSpanPromise; + + expect(getSpanOp(pageloadSpan)).toEqual('pageload'); + expect(pageloadSpan.trace_id).toMatch(/^[\da-f]{32}$/); + expect(pageloadSpan.span_id).toMatch(/^[\da-f]{16}$/); + expect(pageloadSpan.parent_span_id).toBeUndefined(); + + expect(getSpanOp(navigationSpan)).toEqual('navigation'); + expect(navigationSpan.trace_id).toMatch(/^[\da-f]{32}$/); + expect(navigationSpan.span_id).toMatch(/^[\da-f]{16}$/); + expect(navigationSpan.parent_span_id).toBeUndefined(); + + expect(pageloadSpan.span_id).not.toEqual(navigationSpan.span_id); + expect(pageloadSpan.trace_id).not.toEqual(navigationSpan.trace_id); +}); + +sentryTest('error after pageload has pageload traceId', async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const pageloadSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'pageload'); + + const url = await getLocalTestUrl({ testDir: __dirname }); + await page.goto(url); + + const pageloadSpan = await pageloadSpanPromise; + const pageloadTraceId = pageloadSpan.trace_id; + + expect(getSpanOp(pageloadSpan)).toEqual('pageload'); + expect(pageloadTraceId).toMatch(/^[\da-f]{32}$/); + expect(pageloadSpan.span_id).toMatch(/^[\da-f]{16}$/); + expect(pageloadSpan.parent_span_id).toBeUndefined(); + + const errorEventPromise = getFirstSentryEnvelopeRequest( + page, + undefined, + eventAndTraceHeaderRequestParser, + ); + await page.locator('#errorBtn').click(); + const [errorEvent, errorTraceHeader] = await errorEventPromise; + + const errorTraceContext = errorEvent.contexts?.trace; + expect(errorEvent.type).toEqual(undefined); + + expect(errorTraceContext).toEqual({ + trace_id: pageloadTraceId, + span_id: expect.stringMatching(/^[\da-f]{16}$/), + }); + + expect(errorTraceHeader).toEqual({ + environment: 'production', + public_key: 'public', + sample_rate: '1', + sampled: 'true', + trace_id: pageloadTraceId, + sample_rand: expect.any(String), + }); +}); + +sentryTest('error during pageload has pageload traceId', async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + const pageloadSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'pageload'); + const errorEventPromise = getFirstSentryEnvelopeRequest( + page, + undefined, + eventAndTraceHeaderRequestParser, + ); + + await page.goto(url); + await page.locator('#errorBtn').click(); + const [pageloadSpan, [errorEvent, errorTraceHeader]] = await Promise.all([pageloadSpanPromise, errorEventPromise]); + + const pageloadTraceId = pageloadSpan.trace_id; + + expect(getSpanOp(pageloadSpan)).toEqual('pageload'); + expect(pageloadTraceId).toMatch(/^[\da-f]{32}$/); + expect(pageloadSpan.span_id).toMatch(/^[\da-f]{16}$/); + expect(pageloadSpan.parent_span_id).toBeUndefined(); + + const errorTraceContext = errorEvent?.contexts?.trace; + expect(errorEvent.type).toEqual(undefined); + + expect(errorTraceContext).toEqual({ + trace_id: pageloadTraceId, + span_id: expect.stringMatching(/^[\da-f]{16}$/), + }); + + expect(errorTraceHeader).toEqual({ + environment: 'production', + public_key: 'public', + sample_rate: '1', + sampled: 'true', + trace_id: pageloadTraceId, + sample_rand: expect.any(String), + }); +}); + +sentryTest( + 'outgoing fetch request during pageload has pageload traceId in headers', + async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + await page.route('http://sentry-test-site.example/**', route => { + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({}), + }); + }); + + const pageloadSpanEnvelopePromise = waitForStreamedSpanEnvelope( + page, + env => !!env[1][0][1].items.find(s => getSpanOp(s) === 'pageload'), + ); + const requestPromise = page.waitForRequest('http://sentry-test-site.example/*'); + await page.goto(url); + await page.locator('#fetchBtn').click(); + const [pageloadSpanEnvelope, request] = await Promise.all([pageloadSpanEnvelopePromise, requestPromise]); + + const pageloadTraceId = pageloadSpanEnvelope[0].trace?.trace_id; + const sampleRand = pageloadSpanEnvelope[0].trace?.sample_rand; + + expect(pageloadTraceId).toMatch(/^[\da-f]{32}$/); + + const headers = request.headers(); + + // sampling decision is propagated from active span sampling decision + expect(headers['sentry-trace']).toMatch(new RegExp(`^${pageloadTraceId}-[0-9a-f]{16}-1$`)); + expect(headers['baggage']).toBe( + `sentry-environment=production,sentry-public_key=public,sentry-trace_id=${pageloadTraceId},sentry-sampled=true,sentry-sample_rand=${sampleRand},sentry-sample_rate=1`, + ); + }, +); + +sentryTest( + 'outgoing XHR request during pageload has pageload traceId in headers', + async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + await page.route('http://sentry-test-site.example/**', route => { + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({}), + }); + }); + + const pageloadSpanEnvelopePromise = waitForStreamedSpanEnvelope( + page, + env => !!env[1][0][1].items.find(s => getSpanOp(s) === 'pageload'), + ); + const requestPromise = page.waitForRequest('http://sentry-test-site.example/*'); + await page.goto(url); + await page.locator('#xhrBtn').click(); + const [pageloadSpanEnvelope, request] = await Promise.all([pageloadSpanEnvelopePromise, requestPromise]); + + const pageloadTraceId = pageloadSpanEnvelope[0].trace?.trace_id; + const sampleRand = pageloadSpanEnvelope[0].trace?.sample_rand; + + expect(pageloadTraceId).toMatch(/^[\da-f]{32}$/); + + const headers = request.headers(); + + // sampling decision is propagated from active span sampling decision + expect(headers['sentry-trace']).toMatch(new RegExp(`^${pageloadTraceId}-[0-9a-f]{16}-1$`)); + expect(headers['baggage']).toBe( + `sentry-environment=production,sentry-public_key=public,sentry-trace_id=${pageloadTraceId},sentry-sampled=true,sentry-sample_rand=${sampleRand},sentry-sample_rate=1`, + ); + }, +); + +sentryTest('user feedback event after pageload has pageload traceId in headers', async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || shouldSkipFeedbackTest() || testingCdnBundle()); + + const url = await getLocalTestUrl({ testDir: __dirname, handleLazyLoadedFeedback: true }); + + const pageloadSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'pageload'); + await page.goto(url); + const pageloadSpan = await pageloadSpanPromise; + const pageloadTraceId = pageloadSpan.trace_id; + + expect(getSpanOp(pageloadSpan)).toEqual('pageload'); + expect(pageloadTraceId).toMatch(/^[\da-f]{32}$/); + expect(pageloadSpan.span_id).toMatch(/^[\da-f]{16}$/); + expect(pageloadSpan.parent_span_id).toBeUndefined(); + + const feedbackEventPromise = getFirstSentryEnvelopeRequest(page); + + await page.getByText('Report a Bug').click(); + expect(await page.locator(':visible:text-is("Report a Bug")').count()).toEqual(1); + await page.locator('[name="name"]').fill('Jane Doe'); + await page.locator('[name="email"]').fill('janedoe@example.org'); + await page.locator('[name="message"]').fill('my example feedback'); + await page.locator('[data-sentry-feedback] .btn--primary').click(); + + const feedbackEvent = await feedbackEventPromise; + + expect(feedbackEvent.type).toEqual('feedback'); + + const feedbackTraceContext = feedbackEvent.contexts?.trace; + + expect(feedbackTraceContext).toMatchObject({ + trace_id: pageloadTraceId, + span_id: expect.stringMatching(/^[\da-f]{16}$/), + }); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/trace-lifetime/startNewTrace-streamed/init.js b/dev-packages/browser-integration-tests/suites/tracing/trace-lifetime/startNewTrace-streamed/init.js new file mode 100644 index 000000000000..187e07624fdf --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/trace-lifetime/startNewTrace-streamed/init.js @@ -0,0 +1,10 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [Sentry.browserTracingIntegration(), Sentry.spanStreamingIntegration()], + tracePropagationTargets: ['http://sentry-test-site.example'], + tracesSampleRate: 1, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/trace-lifetime/startNewTrace-streamed/subject.js b/dev-packages/browser-integration-tests/suites/tracing/trace-lifetime/startNewTrace-streamed/subject.js new file mode 100644 index 000000000000..3bb1e489ccb6 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/trace-lifetime/startNewTrace-streamed/subject.js @@ -0,0 +1,15 @@ +const newTraceBtn = document.getElementById('newTrace'); +newTraceBtn.addEventListener('click', async () => { + Sentry.startNewTrace(() => { + Sentry.startSpan({ op: 'ui.interaction.click', name: 'new-trace' }, async () => { + await fetch('http://sentry-test-site.example'); + }); + }); +}); + +const oldTraceBtn = document.getElementById('oldTrace'); +oldTraceBtn.addEventListener('click', async () => { + Sentry.startSpan({ op: 'ui.interaction.click', name: 'old-trace' }, async () => { + await fetch('http://sentry-test-site.example'); + }); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/trace-lifetime/startNewTrace-streamed/template.html b/dev-packages/browser-integration-tests/suites/tracing/trace-lifetime/startNewTrace-streamed/template.html new file mode 100644 index 000000000000..f78960343dd0 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/trace-lifetime/startNewTrace-streamed/template.html @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/dev-packages/browser-integration-tests/suites/tracing/trace-lifetime/startNewTrace-streamed/test.ts b/dev-packages/browser-integration-tests/suites/tracing/trace-lifetime/startNewTrace-streamed/test.ts new file mode 100644 index 000000000000..d294efcd2e3b --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/trace-lifetime/startNewTrace-streamed/test.ts @@ -0,0 +1,44 @@ +import { expect } from '@playwright/test'; +import { sentryTest } from '../../../../utils/fixtures'; +import { shouldSkipTracingTest, testingCdnBundle } from '../../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpan } from '../../../../utils/spanUtils'; + +sentryTest( + 'creates a new trace if `startNewTrace` is called and leaves old trace valid outside the callback', + async ({ getLocalTestUrl, page }) => { + sentryTest.skip(shouldSkipTracingTest() || testingCdnBundle()); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + await page.route('http://sentry-test-site.example/**', route => { + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({}), + }); + }); + + const pageloadSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'pageload'); + await page.goto(url); + const pageloadSpan = await pageloadSpanPromise; + + const newTraceSpanPromise = waitForStreamedSpan(page, span => span.name === 'new-trace'); + const oldTraceSpanPromise = waitForStreamedSpan(page, span => span.name === 'old-trace'); + + await page.locator('#newTrace').click(); + await page.locator('#oldTrace').click(); + + const [newTraceSpan, oldTraceSpan] = await Promise.all([newTraceSpanPromise, oldTraceSpanPromise]); + + expect(getSpanOp(newTraceSpan)).toEqual('ui.interaction.click'); + expect(newTraceSpan.trace_id).toMatch(/^[\da-f]{32}$/); + expect(newTraceSpan.span_id).toMatch(/^[\da-f]{16}$/); + + expect(getSpanOp(oldTraceSpan)).toEqual('ui.interaction.click'); + expect(oldTraceSpan.trace_id).toMatch(/^[\da-f]{32}$/); + expect(oldTraceSpan.span_id).toMatch(/^[\da-f]{16}$/); + + expect(oldTraceSpan.trace_id).toEqual(pageloadSpan.trace_id); + expect(newTraceSpan.trace_id).not.toEqual(pageloadSpan.trace_id); + }, +); diff --git a/dev-packages/browser-integration-tests/utils/generatePlugin.ts b/dev-packages/browser-integration-tests/utils/generatePlugin.ts index 9da79bf15b0b..72d93bdabf33 100644 --- a/dev-packages/browser-integration-tests/utils/generatePlugin.ts +++ b/dev-packages/browser-integration-tests/utils/generatePlugin.ts @@ -42,6 +42,7 @@ const IMPORTED_INTEGRATION_CDN_BUNDLE_PATHS: Record = { instrumentGoogleGenAIClient: 'instrumentgooglegenaiclient', instrumentLangGraph: 'instrumentlanggraph', createLangChainCallbackHandler: 'createlangchaincallbackhandler', + instrumentLangChainEmbeddings: 'instrumentlangchainembeddings', // technically, this is not an integration, but let's add it anyway for simplicity makeMultiplexedTransport: 'multiplexedtransport', }; diff --git a/dev-packages/browser-integration-tests/utils/helpers.ts b/dev-packages/browser-integration-tests/utils/helpers.ts index 879e672b6c87..ff0398d6b209 100644 --- a/dev-packages/browser-integration-tests/utils/helpers.ts +++ b/dev-packages/browser-integration-tests/utils/helpers.ts @@ -64,7 +64,7 @@ export const eventAndTraceHeaderRequestParser = (request: Request | null): Event return getEventAndTraceHeader(envelope); }; -const properFullEnvelopeParser = (request: Request | null): T => { +export const properFullEnvelopeParser = (request: Request | null): T => { // https://develop.sentry.dev/sdk/envelopes/ const envelope = request?.postData() || ''; diff --git a/dev-packages/browser-integration-tests/utils/spanUtils.ts b/dev-packages/browser-integration-tests/utils/spanUtils.ts new file mode 100644 index 000000000000..67b5798b66f1 --- /dev/null +++ b/dev-packages/browser-integration-tests/utils/spanUtils.ts @@ -0,0 +1,133 @@ +import type { Page } from '@playwright/test'; +import type { SerializedStreamedSpan, StreamedSpanEnvelope } from '@sentry/core'; +import { properFullEnvelopeParser } from './helpers'; + +/** + * Wait for a full span v2 envelope + * Useful for testing the entire envelope shape + */ +export async function waitForStreamedSpanEnvelope( + page: Page, + callback?: (spanEnvelope: StreamedSpanEnvelope) => boolean, +): Promise { + const req = await page.waitForRequest(req => { + const postData = req.postData(); + if (!postData) { + return false; + } + + try { + const spanEnvelope = properFullEnvelopeParser(req); + + const envelopeItemHeader = spanEnvelope[1][0][0]; + + if ( + envelopeItemHeader?.type !== 'span' || + envelopeItemHeader?.content_type !== 'application/vnd.sentry.items.span.v2+json' + ) { + return false; + } + + if (callback) { + return callback(spanEnvelope); + } + + return true; + } catch { + return false; + } + }); + + return properFullEnvelopeParser(req); +} + +/** + * Wait for v2 spans sent in one envelope. + * Useful for testing multiple spans in one envelope. + * @param page + * @param callback - Callback being called with all spans + */ +export async function waitForStreamedSpans( + page: Page, + callback?: (spans: SerializedStreamedSpan[]) => boolean, +): Promise { + const spanEnvelope = await waitForStreamedSpanEnvelope(page, envelope => { + if (callback) { + return callback(envelope[1][0][1].items); + } + return true; + }); + return spanEnvelope[1][0][1].items; +} + +export async function waitForStreamedSpan( + page: Page, + callback: (span: SerializedStreamedSpan) => boolean, +): Promise { + const spanEnvelope = await waitForStreamedSpanEnvelope(page, envelope => { + if (callback) { + const spans = envelope[1][0][1].items; + return spans.some(span => callback(span)); + } + return true; + }); + const firstMatchingSpan = spanEnvelope[1][0][1].items.find(span => callback(span)); + if (!firstMatchingSpan) { + throw new Error( + 'No matching span found but envelope search matched previously. Something is likely off with this function. Debug me.', + ); + } + return firstMatchingSpan; +} + +/** + * Observes outgoing requests and looks for sentry envelope requests. If an envelope request is found, it applies + * @param callback to check for a matching span. + * + * Important: This function only observes requests and does not block the test when it ends. Use this primarily to + * throw errors if you encounter unwanted spans. You most likely want to use {@link waitForStreamedSpan} or {@link waitForStreamedSpans} instead! + */ +export async function observeStreamedSpan( + page: Page, + callback: (span: SerializedStreamedSpan) => boolean, +): Promise { + page.on('request', request => { + const postData = request.postData(); + if (!postData) { + return; + } + + try { + const spanEnvelope = properFullEnvelopeParser(request); + + const envelopeItemHeader = spanEnvelope[1][0][0]; + + if ( + envelopeItemHeader?.type !== 'span' || + envelopeItemHeader?.content_type !== 'application/vnd.sentry.items.span.v2+json' + ) { + return false; + } + + const spans = spanEnvelope[1][0][1].items; + + for (const span of spans) { + if (callback(span)) { + return true; + } + } + + return false; + } catch { + return false; + } + }); +} + +export function getSpanOp(span: SerializedStreamedSpan): string | undefined { + return span.attributes?.['sentry.op']?.type === 'string' ? span.attributes?.['sentry.op']?.value : undefined; +} + +export function getSpansFromEnvelope(envelope: StreamedSpanEnvelope): SerializedStreamedSpan[] { + return envelope[1][0][1].items; +} diff --git a/dev-packages/cloudflare-integration-tests/suites/double-instrumentation/index.ts b/dev-packages/cloudflare-integration-tests/suites/double-instrumentation/index.ts new file mode 100644 index 000000000000..0844a32ddbd4 --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/double-instrumentation/index.ts @@ -0,0 +1,21 @@ +import * as Sentry from '@sentry/cloudflare'; + +interface Env { + SENTRY_DSN: string; +} + +const handler = { + async fetch(request: Request, _env: Env, _ctx: ExecutionContext) { + if (request.url.includes('/error')) { + throw new Error('Test error from double-instrumented worker'); + } + return new Response('ok'); + }, +}; + +// Deliberately call withSentry twice on the same handler object. +// This simulates scenarios where the module is re-evaluated or the handler +// is wrapped multiple times. The SDK should handle this gracefully +// without double-wrapping (which would cause duplicate error reports). +const once = Sentry.withSentry((env: Env) => ({ dsn: env.SENTRY_DSN }), handler); +export default Sentry.withSentry((env: Env) => ({ dsn: env.SENTRY_DSN }), once); diff --git a/dev-packages/cloudflare-integration-tests/suites/double-instrumentation/test.ts b/dev-packages/cloudflare-integration-tests/suites/double-instrumentation/test.ts new file mode 100644 index 000000000000..b5cba3bd5b08 --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/double-instrumentation/test.ts @@ -0,0 +1,38 @@ +import { expect, it } from 'vitest'; +import { eventEnvelope } from '../../expect'; +import { createRunner } from '../../runner'; + +it('Only sends one error event when withSentry is called twice', async ({ signal }) => { + const runner = createRunner(__dirname) + .expect( + eventEnvelope({ + level: 'error', + exception: { + values: [ + { + type: 'Error', + value: 'Test error from double-instrumented worker', + stacktrace: { + frames: expect.any(Array), + }, + mechanism: { type: 'auto.http.cloudflare', handled: false }, + }, + ], + }, + request: { + headers: expect.any(Object), + method: 'GET', + url: expect.any(String), + }, + }), + ) + .start(signal); + await runner.makeRequest('get', '/error', { expectError: true }); + await runner.completed(); +}); + +it('Successful response works when withSentry is called twice', async ({ signal }) => { + const runner = createRunner(__dirname).start(signal); + const response = await runner.makeRequest('get', '/'); + expect(response).toBe('ok'); +}); diff --git a/dev-packages/cloudflare-integration-tests/suites/double-instrumentation/wrangler.jsonc b/dev-packages/cloudflare-integration-tests/suites/double-instrumentation/wrangler.jsonc new file mode 100644 index 000000000000..d6be01281f0c --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/double-instrumentation/wrangler.jsonc @@ -0,0 +1,6 @@ +{ + "name": "worker-name", + "compatibility_date": "2025-06-17", + "main": "index.ts", + "compatibility_flags": ["nodejs_compat"], +} diff --git a/dev-packages/cloudflare-integration-tests/suites/tracing/durableobject-spans/index.ts b/dev-packages/cloudflare-integration-tests/suites/tracing/durableobject-spans/index.ts new file mode 100644 index 000000000000..a7729d8af7f8 --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/tracing/durableobject-spans/index.ts @@ -0,0 +1,46 @@ +import * as Sentry from '@sentry/cloudflare'; +import { DurableObject } from 'cloudflare:workers'; + +interface Env { + SENTRY_DSN: string; + TEST_DURABLE_OBJECT: DurableObjectNamespace; +} + +class TestDurableObjectBase extends DurableObject { + public constructor(ctx: DurableObjectState, env: Env) { + super(ctx, env); + } + + // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility + async doWork(): Promise { + const results: string[] = []; + + for (let i = 1; i <= 5; i++) { + await Sentry.startSpan({ name: `task-${i}`, op: 'task' }, async () => { + // Simulate async work + await new Promise(resolve => setTimeout(resolve, 1)); + results.push(`done-${i}`); + }); + } + + return results.join(','); + } +} + +export const TestDurableObject = Sentry.instrumentDurableObjectWithSentry( + (env: Env) => ({ + dsn: env.SENTRY_DSN, + tracesSampleRate: 1.0, + instrumentPrototypeMethods: true, + }), + TestDurableObjectBase, +); + +export default { + async fetch(_request: Request, env: Env): Promise { + const id: DurableObjectId = env.TEST_DURABLE_OBJECT.idFromName('test'); + const stub = env.TEST_DURABLE_OBJECT.get(id) as unknown as TestDurableObjectBase; + const result = await stub.doWork(); + return new Response(result); + }, +}; diff --git a/dev-packages/cloudflare-integration-tests/suites/tracing/durableobject-spans/test.ts b/dev-packages/cloudflare-integration-tests/suites/tracing/durableobject-spans/test.ts new file mode 100644 index 000000000000..795eb03e27c2 --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/tracing/durableobject-spans/test.ts @@ -0,0 +1,54 @@ +import { expect, it } from 'vitest'; +import { createRunner } from '../../../runner'; + +// Regression test for https://github.com/getsentry/sentry-javascript/issues/20030 +// When a Durable Object method calls Sentry.startSpan multiple times, those spans +// must appear as children of the DO transaction. The first invocation always worked; +// the second invocation on the same DO instance previously lost its child spans +// because the client was disposed after the first call. +it('sends child spans on repeated Durable Object calls', async ({ signal }) => { + function assertDoWorkEnvelope(envelope: unknown): void { + const transactionEvent = (envelope as any)[1]?.[0]?.[1]; + + expect(transactionEvent).toEqual( + expect.objectContaining({ + transaction: 'doWork', + contexts: expect.objectContaining({ + trace: expect.objectContaining({ + op: 'rpc', + origin: 'auto.faas.cloudflare.durable_object', + }), + }), + }), + ); + + // All 5 child spans should be present + expect(transactionEvent.spans).toHaveLength(5); + expect(transactionEvent.spans).toEqual( + expect.arrayContaining([ + expect.objectContaining({ description: 'task-1', op: 'task' }), + expect.objectContaining({ description: 'task-2', op: 'task' }), + expect.objectContaining({ description: 'task-3', op: 'task' }), + expect.objectContaining({ description: 'task-4', op: 'task' }), + expect.objectContaining({ description: 'task-5', op: 'task' }), + ]), + ); + + // All child spans share the root trace_id + const rootTraceId = transactionEvent.contexts?.trace?.trace_id; + expect(rootTraceId).toBeDefined(); + for (const span of transactionEvent.spans) { + expect(span.trace_id).toBe(rootTraceId); + } + } + + // Expect 5 transaction envelopes — one per call. + const runner = createRunner(__dirname).expectN(5, assertDoWorkEnvelope).start(signal); + + await runner.makeRequest('get', '/'); + await runner.makeRequest('get', '/'); + await runner.makeRequest('get', '/'); + await runner.makeRequest('get', '/'); + await runner.makeRequest('get', '/'); + await runner.completed(); +}); diff --git a/dev-packages/cloudflare-integration-tests/suites/tracing/durableobject-spans/wrangler.jsonc b/dev-packages/cloudflare-integration-tests/suites/tracing/durableobject-spans/wrangler.jsonc new file mode 100644 index 000000000000..8a544e1bdf6b --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/tracing/durableobject-spans/wrangler.jsonc @@ -0,0 +1,20 @@ +{ + "name": "worker-name", + "main": "index.ts", + "compatibility_date": "2025-06-17", + "migrations": [ + { + "new_sqlite_classes": ["TestDurableObject"], + "tag": "v1", + }, + ], + "durable_objects": { + "bindings": [ + { + "class_name": "TestDurableObject", + "name": "TEST_DURABLE_OBJECT", + }, + ], + }, + "compatibility_flags": ["nodejs_als"], +} diff --git a/dev-packages/cloudflare-integration-tests/suites/tracing/durableobject/wrangler.jsonc b/dev-packages/cloudflare-integration-tests/suites/tracing/durableobject/wrangler.jsonc index 31cf0ff361ea..8a544e1bdf6b 100644 --- a/dev-packages/cloudflare-integration-tests/suites/tracing/durableobject/wrangler.jsonc +++ b/dev-packages/cloudflare-integration-tests/suites/tracing/durableobject/wrangler.jsonc @@ -17,7 +17,4 @@ ], }, "compatibility_flags": ["nodejs_als"], - "vars": { - "SENTRY_DSN": "https://932e620ee3921c3b4a61c72558ad88ce@o447951.ingest.us.sentry.io/4509553159831552", - }, } diff --git a/dev-packages/cloudflare-integration-tests/suites/tracing/google-genai/test.ts b/dev-packages/cloudflare-integration-tests/suites/tracing/google-genai/test.ts index 7172366a54c5..5194e3d3a581 100644 --- a/dev-packages/cloudflare-integration-tests/suites/tracing/google-genai/test.ts +++ b/dev-packages/cloudflare-integration-tests/suites/tracing/google-genai/test.ts @@ -27,23 +27,7 @@ it('traces Google GenAI chat creation and message sending', async () => { expect(transactionEvent.transaction).toBe('GET /'); expect(transactionEvent.spans).toEqual( expect.arrayContaining([ - // First span - chats.create - expect.objectContaining({ - data: expect.objectContaining({ - [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'chat', - [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.chat', - [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ai.google_genai', - [GEN_AI_SYSTEM_ATTRIBUTE]: 'google_genai', - [GEN_AI_REQUEST_MODEL_ATTRIBUTE]: 'gemini-1.5-pro', - [GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE]: 0.8, - [GEN_AI_REQUEST_TOP_P_ATTRIBUTE]: 0.9, - [GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE]: 150, - }), - description: 'chat gemini-1.5-pro create', - op: 'gen_ai.chat', - origin: 'auto.ai.google_genai', - }), - // Second span - chat.sendMessage + // chat.sendMessage expect.objectContaining({ data: expect.objectContaining({ [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'chat', @@ -59,7 +43,7 @@ it('traces Google GenAI chat creation and message sending', async () => { op: 'gen_ai.chat', origin: 'auto.ai.google_genai', }), - // Third span - models.generateContent + // models.generateContent expect.objectContaining({ data: expect.objectContaining({ [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', @@ -78,7 +62,7 @@ it('traces Google GenAI chat creation and message sending', async () => { op: 'gen_ai.generate_content', origin: 'auto.ai.google_genai', }), - // Fourth span - models.embedContent + // models.embedContent expect.objectContaining({ data: expect.objectContaining({ [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'embeddings', diff --git a/dev-packages/cloudflare-integration-tests/suites/tracing/worker-service-binding/wrangler-sub-worker.jsonc b/dev-packages/cloudflare-integration-tests/suites/tracing/worker-service-binding/wrangler-sub-worker.jsonc index 30bd95322560..2ba9611e4c48 100644 --- a/dev-packages/cloudflare-integration-tests/suites/tracing/worker-service-binding/wrangler-sub-worker.jsonc +++ b/dev-packages/cloudflare-integration-tests/suites/tracing/worker-service-binding/wrangler-sub-worker.jsonc @@ -3,7 +3,4 @@ "main": "index-sub-worker.ts", "compatibility_date": "2025-06-17", "compatibility_flags": ["nodejs_als"], - "vars": { - "SENTRY_DSN": "https://932e620ee3921c3b4a61c72558ad88ce@o447951.ingest.us.sentry.io/4509553159831552", - }, } diff --git a/dev-packages/cloudflare-integration-tests/suites/tracing/worker-service-binding/wrangler.jsonc b/dev-packages/cloudflare-integration-tests/suites/tracing/worker-service-binding/wrangler.jsonc index 69bc9f6e6e99..a2d52620d268 100644 --- a/dev-packages/cloudflare-integration-tests/suites/tracing/worker-service-binding/wrangler.jsonc +++ b/dev-packages/cloudflare-integration-tests/suites/tracing/worker-service-binding/wrangler.jsonc @@ -3,9 +3,6 @@ "main": "index.ts", "compatibility_date": "2025-06-17", "compatibility_flags": ["nodejs_als"], - "vars": { - "SENTRY_DSN": "https://932e620ee3921c3b4a61c72558ad88ce@o447951.ingest.us.sentry.io/4509553159831552", - }, "services": [ { "binding": "ANOTHER_WORKER", diff --git a/dev-packages/e2e-tests/test-applications/angular-21/package.json b/dev-packages/e2e-tests/test-applications/angular-21/package.json index fddd7708d936..0558d370e2c5 100644 --- a/dev-packages/e2e-tests/test-applications/angular-21/package.json +++ b/dev-packages/e2e-tests/test-applications/angular-21/package.json @@ -44,7 +44,7 @@ "karma-coverage": "~2.2.0", "karma-jasmine": "~5.1.0", "karma-jasmine-html-reporter": "~2.1.0", - "typescript": "~5.9.0" + "typescript": "~6.0.0" }, "volta": { "node": "22.22.0", diff --git a/dev-packages/e2e-tests/test-applications/browser-webworker-vite/package.json b/dev-packages/e2e-tests/test-applications/browser-webworker-vite/package.json index 3dee05b829d6..f6aae0e57df3 100644 --- a/dev-packages/e2e-tests/test-applications/browser-webworker-vite/package.json +++ b/dev-packages/e2e-tests/test-applications/browser-webworker-vite/package.json @@ -19,7 +19,7 @@ }, "dependencies": { "@sentry/browser": "latest || *", - "@sentry/vite-plugin": "^5.1.0" + "@sentry/vite-plugin": "^5.2.0" }, "volta": { "node": "20.19.2", diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-mcp/src/env.d.ts b/dev-packages/e2e-tests/test-applications/cloudflare-mcp/src/env.d.ts index 1701ed9f621a..39722170441c 100644 --- a/dev-packages/e2e-tests/test-applications/cloudflare-mcp/src/env.d.ts +++ b/dev-packages/e2e-tests/test-applications/cloudflare-mcp/src/env.d.ts @@ -1,7 +1,9 @@ // Generated by Wrangler on Mon Jul 29 2024 21:44:31 GMT-0400 (Eastern Daylight Time) // by running `wrangler types` - -interface Env { - E2E_TEST_DSN: ''; - MY_DURABLE_OBJECT: DurableObjectNamespace; +declare namespace Cloudflare { + interface Env { + E2E_TEST_DSN: ''; + MY_DURABLE_OBJECT: DurableObjectNamespace; + } } +interface Env extends Cloudflare.Env {} diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/.gitignore b/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/.gitignore new file mode 100644 index 000000000000..e71378008bf1 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/.gitignore @@ -0,0 +1 @@ +.wrangler diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/.npmrc b/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/.npmrc new file mode 100644 index 000000000000..070f80f05092 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/.npmrc @@ -0,0 +1,2 @@ +@sentry:registry=http://127.0.0.1:4873 +@sentry-internal:registry=http://127.0.0.1:4873 diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/package.json b/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/package.json new file mode 100644 index 000000000000..a0a1b020df86 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/package.json @@ -0,0 +1,38 @@ +{ + "name": "cloudflare-workersentrypoint", + "version": "0.0.0", + "private": true, + "scripts": { + "deploy": "wrangler deploy", + "dev": "wrangler dev --var \"E2E_TEST_DSN:$E2E_TEST_DSN\" --log-level=$(test $CI && echo 'none' || echo 'log')", + "build": "wrangler deploy --dry-run", + "test": "vitest --run", + "typecheck": "tsc --noEmit", + "cf-typegen": "wrangler types --strict-vars false", + "test:build": "pnpm install && pnpm build", + "test:assert": "pnpm typecheck && pnpm test:dev && pnpm test:prod", + "test:prod": "TEST_ENV=production playwright test", + "test:dev": "TEST_ENV=development playwright test" + }, + "dependencies": { + "@sentry/cloudflare": "latest || *" + }, + "devDependencies": { + "@playwright/test": "~1.56.0", + "@cloudflare/vitest-pool-workers": "^0.8.19", + "@cloudflare/workers-types": "^4.20240725.0", + "@sentry-internal/test-utils": "link:../../../test-utils", + "typescript": "^5.5.2", + "vitest": "~3.2.0", + "wrangler": "^4.61.0", + "ws": "^8.18.3" + }, + "volta": { + "extends": "../../package.json" + }, + "pnpm": { + "overrides": { + "strip-literal": "~2.0.0" + } + } +} diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/playwright.config.ts b/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/playwright.config.ts new file mode 100644 index 000000000000..73abbd951b90 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/playwright.config.ts @@ -0,0 +1,22 @@ +import { getPlaywrightConfig } from '@sentry-internal/test-utils'; +const testEnv = process.env.TEST_ENV; + +if (!testEnv) { + throw new Error('No test env defined'); +} + +const APP_PORT = 38787; + +const config = getPlaywrightConfig( + { + startCommand: `pnpm dev --port ${APP_PORT}`, + port: APP_PORT, + }, + { + // This comes with the risk of tests leaking into each other but the tests run quite slow so we should parallelize + workers: '100%', + retries: 0, + }, +); + +export default config; diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/src/index.ts b/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/src/index.ts new file mode 100644 index 000000000000..9c0159b26327 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/src/index.ts @@ -0,0 +1,123 @@ +/** + * Welcome to Cloudflare Workers! This is your first worker. + * + * - Run `npm run dev` in your terminal to start a development server + * - Open a browser tab at http://localhost:8787/ to see your worker in action + * - Run `npm run deploy` to publish your worker + * + * Bind resources to your worker in `wrangler.toml`. After adding bindings, a type definition for the + * `Env` object can be regenerated with `npm run cf-typegen`. + * + * Learn more at https://developers.cloudflare.com/workers/ + */ +import * as Sentry from '@sentry/cloudflare'; +import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers'; + +class MyDurableObjectBase extends DurableObject { + private throwOnExit = new WeakMap(); + async throwException(): Promise { + throw new Error('Should be recorded in Sentry.'); + } + + async fetch(request: Request) { + const url = new URL(request.url); + switch (url.pathname) { + case '/throwException': { + await this.throwException(); + break; + } + case '/ws': { + const webSocketPair = new WebSocketPair(); + const [client, server] = Object.values(webSocketPair); + this.ctx.acceptWebSocket(server); + return new Response(null, { status: 101, webSocket: client }); + } + case '/storage/put': { + await this.ctx.storage.put('test-key', 'test-value'); + return new Response('Stored'); + } + case '/storage/get': { + const value = await this.ctx.storage.get('test-key'); + return new Response(`Got: ${value}`); + } + } + return new Response('DO is fine'); + } + + webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): void | Promise { + if (message === 'throwException') { + throw new Error('Should be recorded in Sentry: webSocketMessage'); + } else if (message === 'throwOnExit') { + this.throwOnExit.set(ws, new Error('Should be recorded in Sentry: webSocketClose')); + } + } + + webSocketClose(ws: WebSocket): void | Promise { + if (this.throwOnExit.has(ws)) { + const error = this.throwOnExit.get(ws)!; + this.throwOnExit.delete(ws); + throw error; + } + } +} + +export const MyDurableObject = Sentry.instrumentDurableObjectWithSentry( + (env: Env) => ({ + dsn: env.E2E_TEST_DSN, + environment: 'qa', // dynamic sampling bias to keep transactions + tunnel: `http://localhost:3031/`, // proxy server + tracesSampleRate: 1.0, + sendDefaultPii: true, + transportOptions: { + // We are doing a lot of events at once in this test + bufferSize: 1000, + }, + instrumentPrototypeMethods: true, + }), + MyDurableObjectBase, +); + +class MyWorker extends WorkerEntrypoint { + async fetch(request: Request) { + const url = new URL(request.url); + switch (url.pathname) { + case '/rpc/throwException': + { + const id = this.env.MY_DURABLE_OBJECT.idFromName('foo'); + const stub = this.env.MY_DURABLE_OBJECT.get(id) as DurableObjectStub; + try { + await stub.throwException(); + } catch (e) { + //We will catch this to be sure not to log inside withSentry + return new Response(null, { status: 500 }); + } + } + break; + case '/throwException': + throw new Error('To be recorded in Sentry.'); + default: + if (url.pathname.startsWith('/pass-to-object/')) { + const id = this.env.MY_DURABLE_OBJECT.idFromName('foo'); + const stub = this.env.MY_DURABLE_OBJECT.get(id) as DurableObjectStub; + url.pathname = url.pathname.replace('/pass-to-object/', ''); + return stub.fetch(new Request(url, request)); + } + } + return new Response('Hello World!'); + } +} + +export default Sentry.withSentry( + env => ({ + dsn: env.E2E_TEST_DSN, + environment: 'qa', // dynamic sampling bias to keep transactions + tunnel: `http://localhost:3031/`, // proxy server + tracesSampleRate: 1.0, + sendDefaultPii: true, + transportOptions: { + // We are doing a lot of events at once in this test + bufferSize: 1000, + }, + }), + MyWorker, +); diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/start-event-proxy.mjs b/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/start-event-proxy.mjs new file mode 100644 index 000000000000..e2e2145bf43e --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/start-event-proxy.mjs @@ -0,0 +1,6 @@ +import { startEventProxyServer } from '@sentry-internal/test-utils'; + +startEventProxyServer({ + port: 3031, + proxyServerName: 'cloudflare-workersentrypoint', +}); diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/tests/index.test.ts b/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/tests/index.test.ts new file mode 100644 index 000000000000..8bfb8362b4a7 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/tests/index.test.ts @@ -0,0 +1,101 @@ +import { expect, test } from '@playwright/test'; +import { waitForError, waitForRequest, waitForTransaction } from '@sentry-internal/test-utils'; +import { SDK_VERSION } from '@sentry/cloudflare'; +import { WebSocket } from 'ws'; + +test('Index page', async ({ baseURL }) => { + const result = await fetch(baseURL!); + expect(result.status).toBe(200); + await expect(result.text()).resolves.toBe('Hello World!'); +}); + +test("worker's withSentry", async ({ baseURL }) => { + const eventWaiter = waitForError('cloudflare-workersentrypoint', event => { + return event.exception?.values?.[0]?.mechanism?.type === 'auto.http.cloudflare'; + }); + const response = await fetch(`${baseURL}/throwException`); + expect(response.status).toBe(500); + const event = await eventWaiter; + expect(event.exception?.values?.[0]?.value).toBe('To be recorded in Sentry.'); +}); + +test('RPC method which throws an exception to be logged to sentry', async ({ baseURL }) => { + const eventWaiter = waitForError('cloudflare-workersentrypoint', event => { + return event.exception?.values?.[0]?.mechanism?.type === 'auto.faas.cloudflare.durable_object'; + }); + const response = await fetch(`${baseURL}/rpc/throwException`); + expect(response.status).toBe(500); + const event = await eventWaiter; + expect(event.exception?.values?.[0]?.value).toBe('Should be recorded in Sentry.'); +}); + +test("Request processed by DurableObject's fetch is recorded", async ({ baseURL }) => { + const eventWaiter = waitForError('cloudflare-workersentrypoint', event => { + return event.exception?.values?.[0]?.mechanism?.type === 'auto.faas.cloudflare.durable_object'; + }); + const response = await fetch(`${baseURL}/pass-to-object/throwException`); + expect(response.status).toBe(500); + const event = await eventWaiter; + expect(event.exception?.values?.[0]?.value).toBe('Should be recorded in Sentry.'); +}); + +test('Websocket.webSocketMessage', async ({ baseURL }) => { + const eventWaiter = waitForError('cloudflare-workersentrypoint', event => { + return !!event.exception?.values?.[0]; + }); + const url = new URL('/pass-to-object/ws', baseURL); + url.protocol = url.protocol.replace('http', 'ws'); + const socket = new WebSocket(url.toString()); + socket.addEventListener('open', () => { + socket.send('throwException'); + }); + const event = await eventWaiter; + socket.close(); + expect(event.exception?.values?.[0]?.value).toBe('Should be recorded in Sentry: webSocketMessage'); + expect(event.exception?.values?.[0]?.mechanism?.type).toBe('auto.faas.cloudflare.durable_object'); +}); + +test('Websocket.webSocketClose', async ({ baseURL }) => { + const eventWaiter = waitForError('cloudflare-workersentrypoint', event => { + return !!event.exception?.values?.[0]; + }); + const url = new URL('/pass-to-object/ws', baseURL); + url.protocol = url.protocol.replace('http', 'ws'); + const socket = new WebSocket(url.toString()); + socket.addEventListener('open', () => { + socket.send('throwOnExit'); + socket.close(); + }); + const event = await eventWaiter; + expect(event.exception?.values?.[0]?.value).toBe('Should be recorded in Sentry: webSocketClose'); + expect(event.exception?.values?.[0]?.mechanism?.type).toBe('auto.faas.cloudflare.durable_object'); +}); + +test('sends user-agent header with SDK name and version in envelope requests', async ({ baseURL }) => { + const requestPromise = waitForRequest('cloudflare-workersentrypoint', () => true); + + await fetch(`${baseURL}/throwException`); + + const request = await requestPromise; + + expect(request.rawProxyRequestHeaders).toMatchObject({ + 'user-agent': `sentry.javascript.cloudflare/${SDK_VERSION}`, + }); +}); + +test('Storage operations create spans in Durable Object transactions', async ({ baseURL }) => { + const transactionWaiter = waitForTransaction('cloudflare-workersentrypoint', event => { + return event.spans?.some(span => span.op === 'db' && span.description === 'durable_object_storage_put') ?? false; + }); + + const response = await fetch(`${baseURL}/pass-to-object/storage/put`); + expect(response.status).toBe(200); + + const transaction = await transactionWaiter; + const putSpan = transaction.spans?.find(span => span.description === 'durable_object_storage_put'); + + expect(putSpan).toBeDefined(); + expect(putSpan?.op).toBe('db'); + expect(putSpan?.data?.['db.system.name']).toBe('cloudflare.durable_object.storage'); + expect(putSpan?.data?.['db.operation.name']).toBe('put'); +}); diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/tests/tsconfig.json b/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/tests/tsconfig.json new file mode 100644 index 000000000000..80bfbd97acc1 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/tests/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "types": ["@cloudflare/vitest-pool-workers"] + }, + "include": ["./**/*.ts"], + "exclude": [] +} diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/tsconfig.json b/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/tsconfig.json new file mode 100644 index 000000000000..cebf06ef0b43 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/tsconfig.json @@ -0,0 +1,43 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig.json to read more about this file */ + + /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + "target": "es2021", + /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + "lib": ["es2021"], + /* Specify what JSX code is generated. */ + "jsx": "react-jsx", + + /* Specify what module code is generated. */ + "module": "es2022", + /* Specify how TypeScript looks up a file from a given module specifier. */ + "moduleResolution": "Bundler", + /* Enable importing .json files */ + "resolveJsonModule": true, + + /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */ + "allowJs": true, + /* Enable error reporting in type-checked JavaScript files. */ + "checkJs": false, + + /* Disable emitting files from a compilation. */ + "noEmit": true, + + /* Ensure that each file can be safely transpiled without relying on other imports. */ + "isolatedModules": true, + /* Allow 'import x from y' when a module doesn't have a default export. */ + "allowSyntheticDefaultImports": true, + /* Ensure that casing is correct in imports. */ + "forceConsistentCasingInFileNames": true, + + /* Enable all strict type-checking options. */ + "strict": true, + + /* Skip type checking all .d.ts files. */ + "skipLibCheck": true, + "types": ["./worker-configuration.d.ts"] + }, + "exclude": ["test"], + "include": ["src/**/*.ts"] +} diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/vitest.config.mts b/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/vitest.config.mts new file mode 100644 index 000000000000..931e5113e0c2 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/vitest.config.mts @@ -0,0 +1,11 @@ +import { defineWorkersConfig } from '@cloudflare/vitest-pool-workers/config'; + +export default defineWorkersConfig({ + test: { + poolOptions: { + workers: { + wrangler: { configPath: './wrangler.toml' }, + }, + }, + }, +}); diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/worker-configuration.d.ts b/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/worker-configuration.d.ts new file mode 100644 index 000000000000..daaa5eeb9992 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/worker-configuration.d.ts @@ -0,0 +1,12975 @@ +/* eslint-disable */ +// Generated by Wrangler by running `wrangler types --strict-vars false` (hash: 44dcd54d04da8ecd558ac0adbefb74d7) +// Runtime types generated with workerd@1.20260317.1 2024-07-25 nodejs_compat +declare namespace Cloudflare { + interface GlobalProps { + mainModule: typeof import('./src/index'); + durableNamespaces: 'MyDurableObject'; + } + interface Env { + E2E_TEST_DSN: string; + MY_DURABLE_OBJECT: DurableObjectNamespace; + } +} +interface Env extends Cloudflare.Env {} + +// Begin runtime types +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +declare var onmessage: never; +/** + * The **`DOMException`** interface represents an abnormal event (called an **exception**) that occurs as a result of calling a method or accessing a property of a web API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException) + */ +declare class DOMException extends Error { + constructor(message?: string, name?: string); + /** + * The **`message`** read-only property of the a message or description associated with the given error name. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) + */ + readonly message: string; + /** + * The **`name`** read-only property of the one of the strings associated with an error name. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) + */ + readonly name: string; + /** + * The **`code`** read-only property of the DOMException interface returns one of the legacy error code constants, or `0` if none match. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; + get stack(): any; + set stack(value: any); +} +type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +declare abstract class WorkerGlobalScope extends EventTarget { + EventTarget: typeof EventTarget; +} +/* The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox). * + * The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) + */ +interface Console { + 'assert'(condition?: boolean, ...data: any[]): void; + /** + * The **`console.clear()`** static method clears the console if possible. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) + */ + clear(): void; + /** + * The **`console.count()`** static method logs the number of times that this particular call to `count()` has been called. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) + */ + count(label?: string): void; + /** + * The **`console.countReset()`** static method resets counter used with console/count_static. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) + */ + countReset(label?: string): void; + /** + * The **`console.debug()`** static method outputs a message to the console at the 'debug' log level. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) + */ + debug(...data: any[]): void; + /** + * The **`console.dir()`** static method displays a list of the properties of the specified JavaScript object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) + */ + dir(item?: any, options?: any): void; + /** + * The **`console.dirxml()`** static method displays an interactive tree of the descendant elements of the specified XML/HTML element. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) + */ + dirxml(...data: any[]): void; + /** + * The **`console.error()`** static method outputs a message to the console at the 'error' log level. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) + */ + error(...data: any[]): void; + /** + * The **`console.group()`** static method creates a new inline group in the Web console log, causing any subsequent console messages to be indented by an additional level, until console/groupEnd_static is called. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) + */ + group(...data: any[]): void; + /** + * The **`console.groupCollapsed()`** static method creates a new inline group in the console. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) + */ + groupCollapsed(...data: any[]): void; + /** + * The **`console.groupEnd()`** static method exits the current inline group in the console. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) + */ + groupEnd(): void; + /** + * The **`console.info()`** static method outputs a message to the console at the 'info' log level. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) + */ + info(...data: any[]): void; + /** + * The **`console.log()`** static method outputs a message to the console. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) + */ + log(...data: any[]): void; + /** + * The **`console.table()`** static method displays tabular data as a table. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) + */ + table(tabularData?: any, properties?: string[]): void; + /** + * The **`console.time()`** static method starts a timer you can use to track how long an operation takes. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) + */ + time(label?: string): void; + /** + * The **`console.timeEnd()`** static method stops a timer that was previously started by calling console/time_static. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) + */ + timeEnd(label?: string): void; + /** + * The **`console.timeLog()`** static method logs the current value of a timer that was previously started by calling console/time_static. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) + */ + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + /** + * The **`console.trace()`** static method outputs a stack trace to the console. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) + */ + trace(...data: any[]): void; + /** + * The **`console.warn()`** static method outputs a warning message to the console at the 'warning' log level. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) + */ + warn(...data: any[]): void; +} +declare const console: Console; +type BufferSource = ArrayBufferView | ArrayBuffer; +type TypedArray = + | Int8Array + | Uint8Array + | Uint8ClampedArray + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | Float32Array + | Float64Array + | BigInt64Array + | BigUint64Array; +declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = 'anyfunc' | 'externref' | 'f32' | 'f64' | 'i32' | 'i64' | 'v128'; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record; + type Imports = Record; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = 'function' | 'global' | 'memory' | 'table'; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = 'anyfunc' | 'externref'; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise; + function validate(bytes: BufferSource): boolean; +} +/** + * The **`ServiceWorkerGlobalScope`** interface of the Service Worker API represents the global execution context of a service worker. + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) + */ +interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone(value: T, options?: StructuredSerializeOptions): T; + reportError(error: any): void; + fetch(input: RequestInfo | URL, init?: RequestInit): Promise; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + Cloudflare: Cloudflare; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + CustomEvent: typeof CustomEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ErrorEvent: typeof ErrorEvent; + EventSource: typeof EventSource; + ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; + ReadableStreamDefaultController: typeof ReadableStreamDefaultController; + ReadableByteStreamController: typeof ReadableByteStreamController; + WritableStreamDefaultController: typeof WritableStreamDefaultController; + TransformStreamDefaultController: typeof TransformStreamDefaultController; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; +} +declare function addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, +): void; +declare function removeEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | boolean, +): void; +/** + * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ +declare function dispatchEvent(event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap]): boolean; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/btoa) */ +declare function btoa(data: string): string; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/atob) */ +declare function atob(data: string): string; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */ +declare function setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */ +declare function setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearTimeout) */ +declare function clearTimeout(timeoutId: number | null): void; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */ +declare function setInterval(callback: (...args: any[]) => void, msDelay?: number): number; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */ +declare function setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearInterval) */ +declare function clearInterval(timeoutId: number | null): void; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/queueMicrotask) */ +declare function queueMicrotask(task: Function): void; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/structuredClone) */ +declare function structuredClone(value: T, options?: StructuredSerializeOptions): T; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/reportError) */ +declare function reportError(error: any): void; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) */ +declare function fetch(input: RequestInfo | URL, init?: RequestInit): Promise; +declare const self: ServiceWorkerGlobalScope; +/** + * The Web Crypto API provides a set of low-level functions for common cryptographic tasks. + * The Workers runtime implements the full surface of this API, but with some differences in + * the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) + * compared to those implemented in most browsers. + * + * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) + */ +declare const crypto: Crypto; +/** + * The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. + * + * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) + */ +declare const caches: CacheStorage; +declare const scheduler: Scheduler; +/** + * The Workers runtime supports a subset of the Performance API, used to measure timing and performance, + * as well as timing of subrequests and other operations. + * + * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) + */ +declare const performance: Performance; +declare const Cloudflare: Cloudflare; +declare const origin: string; +declare const navigator: Navigator; +interface TestController {} +interface ExecutionContext { + waitUntil(promise: Promise): void; + passThroughOnException(): void; + readonly props: Props; +} +type ExportedHandlerFetchHandler = ( + request: Request>, + env: Env, + ctx: ExecutionContext, +) => Response | Promise; +type ExportedHandlerTailHandler = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +type ExportedHandlerTraceHandler = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise; +type ExportedHandlerTailStreamHandler = ( + event: TailStream.TailEvent, + env: Env, + ctx: ExecutionContext, +) => TailStream.TailEventHandlerType | Promise; +type ExportedHandlerScheduledHandler = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +type ExportedHandlerQueueHandler = ( + batch: MessageBatch, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +type ExportedHandlerTestHandler = ( + controller: TestController, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +interface ExportedHandler { + fetch?: ExportedHandlerFetchHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + tailStream?: ExportedHandlerTailStreamHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; +} +interface StructuredSerializeOptions { + transfer?: any[]; +} +declare abstract class Navigator { + sendBeacon(url: string, body?: BodyInit): boolean; + readonly userAgent: string; + readonly hardwareConcurrency: number; +} +interface AlarmInvocationInfo { + readonly isRetry: boolean; + readonly retryCount: number; +} +interface Cloudflare { + readonly compatibilityFlags: Record; +} +interface DurableObject { + fetch(request: Request): Response | Promise; + alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise; + webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise; + webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; +} +type DurableObjectStub = Fetcher< + T, + 'alarm' | 'webSocketMessage' | 'webSocketClose' | 'webSocketError' +> & { + readonly id: DurableObjectId; + readonly name?: string; +}; +interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +declare abstract class DurableObjectNamespace { + newUniqueId(options?: DurableObjectNamespaceNewUniqueIdOptions): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get(id: DurableObjectId, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub; + getByName(name: string, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub; + jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; +} +type DurableObjectJurisdiction = 'eu' | 'fedramp' | 'fedramp-high'; +interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +type DurableObjectLocationHint = 'wnam' | 'enam' | 'sam' | 'weur' | 'eeur' | 'apac' | 'oc' | 'afr' | 'me'; +type DurableObjectRoutingMode = 'primary-only'; +interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; + routingMode?: DurableObjectRoutingMode; +} +interface DurableObjectClass<_T extends Rpc.DurableObjectBranded | undefined = undefined> {} +interface DurableObjectState { + waitUntil(promise: Promise): void; + readonly props: Props; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + container?: Container; + blockConcurrencyWhile(callback: () => Promise): Promise; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; + setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; + getHibernatableWebSocketEventTimeout(): number | null; + getTags(ws: WebSocket): string[]; + abort(reason?: string): void; +} +interface DurableObjectTransaction { + get(key: string, options?: DurableObjectGetOptions): Promise; + get(keys: string[], options?: DurableObjectGetOptions): Promise>; + list(options?: DurableObjectListOptions): Promise>; + put(key: string, value: T, options?: DurableObjectPutOptions): Promise; + put(entries: Record, options?: DurableObjectPutOptions): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; +} +interface DurableObjectStorage { + get(key: string, options?: DurableObjectGetOptions): Promise; + get(keys: string[], options?: DurableObjectGetOptions): Promise>; + list(options?: DurableObjectListOptions): Promise>; + put(key: string, value: T, options?: DurableObjectPutOptions): Promise; + put(entries: Record, options?: DurableObjectPutOptions): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + deleteAll(options?: DurableObjectPutOptions): Promise; + transaction(closure: (txn: DurableObjectTransaction) => Promise): Promise; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + sync(): Promise; + sql: SqlStorage; + kv: SyncKvStorage; + transactionSync(closure: () => T): T; + getCurrentBookmark(): Promise; + getBookmarkForTime(timestamp: number | Date): Promise; + onNextSessionRestoreBookmark(bookmark: string): Promise; +} +interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +/** + * The **`Event`** interface represents an event which takes place on an `EventTarget`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event) + */ +declare class Event { + constructor(type: string, init?: EventInit); + /** + * The **`type`** read-only property of the Event interface returns a string containing the event's type. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) + */ + get type(): string; + /** + * The **`eventPhase`** read-only property of the being evaluated. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + get eventPhase(): number; + /** + * The read-only **`composed`** property of the or not the event will propagate across the shadow DOM boundary into the standard DOM. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) + */ + get composed(): boolean; + /** + * The **`bubbles`** read-only property of the Event interface indicates whether the event bubbles up through the DOM tree or not. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) + */ + get bubbles(): boolean; + /** + * The **`cancelable`** read-only property of the Event interface indicates whether the event can be canceled, and therefore prevented as if the event never happened. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) + */ + get cancelable(): boolean; + /** + * The **`defaultPrevented`** read-only property of the Event interface returns a boolean value indicating whether or not the call to Event.preventDefault() canceled the event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) + */ + get defaultPrevented(): boolean; + /** + * The Event property **`returnValue`** indicates whether the default action for this event has been prevented or not. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) + */ + get returnValue(): boolean; + /** + * The **`currentTarget`** read-only property of the Event interface identifies the element to which the event handler has been attached. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) + */ + get currentTarget(): EventTarget | undefined; + /** + * The read-only **`target`** property of the dispatched. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/target) + */ + get target(): EventTarget | undefined; + /** + * The deprecated **`Event.srcElement`** is an alias for the Event.target property. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) + */ + get srcElement(): EventTarget | undefined; + /** + * The **`timeStamp`** read-only property of the Event interface returns the time (in milliseconds) at which the event was created. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) + */ + get timeStamp(): number; + /** + * The **`isTrusted`** read-only property of the when the event was generated by the user agent (including via user actions and programmatic methods such as HTMLElement.focus()), and `false` when the event was dispatched via The only exception is the `click` event, which initializes the `isTrusted` property to `false` in user agents. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) + */ + get isTrusted(): boolean; + /** + * The **`cancelBubble`** property of the Event interface is deprecated. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + get cancelBubble(): boolean; + /** + * The **`cancelBubble`** property of the Event interface is deprecated. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + set cancelBubble(value: boolean); + /** + * The **`stopImmediatePropagation()`** method of the If several listeners are attached to the same element for the same event type, they are called in the order in which they were added. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) + */ + stopImmediatePropagation(): void; + /** + * The **`preventDefault()`** method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) + */ + preventDefault(): void; + /** + * The **`stopPropagation()`** method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) + */ + stopPropagation(): void; + /** + * The **`composedPath()`** method of the Event interface returns the event's path which is an array of the objects on which listeners will be invoked. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) + */ + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +type EventListener = (event: EventType) => void; +interface EventListenerObject { + handleEvent(event: EventType): void; +} +type EventListenerOrEventListenerObject = + | EventListener + | EventListenerObject; +/** + * The **`EventTarget`** interface is implemented by objects that can receive events and may have listeners for them. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget) + */ +declare class EventTarget = Record> { + constructor(); + /** + * The **`addEventListener()`** method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) + */ + addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, + ): void; + /** + * The **`removeEventListener()`** method of the EventTarget interface removes an event listener previously registered with EventTarget.addEventListener() from the target. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | boolean, + ): void; + /** + * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +interface EventTargetEventListenerOptions { + capture?: boolean; +} +interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +/** + * The **`AbortController`** interface represents a controller object that allows you to abort one or more Web requests as and when desired. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController) + */ +declare class AbortController { + constructor(); + /** + * The **`signal`** read-only property of the AbortController interface returns an AbortSignal object instance, which can be used to communicate with/abort an asynchronous operation as desired. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) + */ + get signal(): AbortSignal; + /** + * The **`abort()`** method of the AbortController interface aborts an asynchronous operation before it has completed. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) + */ + abort(reason?: any): void; +} +/** + * The **`AbortSignal`** interface represents a signal object that allows you to communicate with an asynchronous operation (such as a fetch request) and abort it if required via an AbortController object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal) + */ +declare abstract class AbortSignal extends EventTarget { + /** + * The **`AbortSignal.abort()`** static method returns an AbortSignal that is already set as aborted (and which does not trigger an AbortSignal/abort_event event). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) + */ + static abort(reason?: any): AbortSignal; + /** + * The **`AbortSignal.timeout()`** static method returns an AbortSignal that will automatically abort after a specified time. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) + */ + static timeout(delay: number): AbortSignal; + /** + * The **`AbortSignal.any()`** static method takes an iterable of abort signals and returns an AbortSignal. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/any_static) + */ + static any(signals: AbortSignal[]): AbortSignal; + /** + * The **`aborted`** read-only property returns a value that indicates whether the asynchronous operations the signal is communicating with are aborted (`true`) or not (`false`). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) + */ + get aborted(): boolean; + /** + * The **`reason`** read-only property returns a JavaScript value that indicates the abort reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) + */ + get reason(): any; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + get onabort(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + set onabort(value: any | null); + /** + * The **`throwIfAborted()`** method throws the signal's abort AbortSignal.reason if the signal has been aborted; otherwise it does nothing. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) + */ + throwIfAborted(): void; +} +interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; +} +interface SchedulerWaitOptions { + signal?: AbortSignal; +} +/** + * The **`ExtendableEvent`** interface extends the lifetime of the `install` and `activate` events dispatched on the global scope as part of the service worker lifecycle. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent) + */ +declare abstract class ExtendableEvent extends Event { + /** + * The **`ExtendableEvent.waitUntil()`** method tells the event dispatcher that work is ongoing. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) + */ + waitUntil(promise: Promise): void; +} +/** + * The **`CustomEvent`** interface represents events initialized by an application for any purpose. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent) + */ +declare class CustomEvent extends Event { + constructor(type: string, init?: CustomEventCustomEventInit); + /** + * The read-only **`detail`** property of the CustomEvent interface returns any data passed when initializing the event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) + */ + get detail(): T; +} +interface CustomEventCustomEventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + detail?: any; +} +/** + * The **`Blob`** interface represents a blob, which is a file-like object of immutable, raw data; they can be read as text or binary data, or converted into a ReadableStream so its methods can be used for processing the data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob) + */ +declare class Blob { + constructor(type?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], options?: BlobOptions); + /** + * The **`size`** read-only property of the Blob interface returns the size of the Blob or File in bytes. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) + */ + get size(): number; + /** + * The **`type`** read-only property of the Blob interface returns the MIME type of the file. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) + */ + get type(): string; + /** + * The **`slice()`** method of the Blob interface creates and returns a new `Blob` object which contains data from a subset of the blob on which it's called. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) + */ + slice(start?: number, end?: number, type?: string): Blob; + /** + * The **`arrayBuffer()`** method of the Blob interface returns a Promise that resolves with the contents of the blob as binary data contained in an ArrayBuffer. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) + */ + arrayBuffer(): Promise; + /** + * The **`bytes()`** method of the Blob interface returns a Promise that resolves with a Uint8Array containing the contents of the blob as an array of bytes. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/bytes) + */ + bytes(): Promise; + /** + * The **`text()`** method of the string containing the contents of the blob, interpreted as UTF-8. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) + */ + text(): Promise; + /** + * The **`stream()`** method of the Blob interface returns a ReadableStream which upon reading returns the data contained within the `Blob`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) + */ + stream(): ReadableStream; +} +interface BlobOptions { + type?: string; +} +/** + * The **`File`** interface provides information about files and allows JavaScript in a web page to access their content. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File) + */ +declare class File extends Blob { + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions, + ); + /** + * The **`name`** read-only property of the File interface returns the name of the file represented by a File object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) + */ + get name(): string; + /** + * The **`lastModified`** read-only property of the File interface provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) + */ + get lastModified(): number; +} +interface FileOptions { + type?: string; + lastModified?: number; +} +/** + * The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. + * + * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) + */ +declare abstract class CacheStorage { + /** + * The **`open()`** method of the the Cache object matching the `cacheName`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) + */ + open(cacheName: string): Promise; + readonly default: Cache; +} +/** + * The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. + * + * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) + */ +declare abstract class Cache { + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#delete) */ + delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#match) */ + match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#put) */ + put(request: RequestInfo | URL, response: Response): Promise; +} +interface CacheQueryOptions { + ignoreMethod?: boolean; +} +/** + * The Web Crypto API provides a set of low-level functions for common cryptographic tasks. + * The Workers runtime implements the full surface of this API, but with some differences in + * the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) + * compared to those implemented in most browsers. + * + * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) + */ +declare abstract class Crypto { + /** + * The **`Crypto.subtle`** read-only property returns a cryptographic operations. + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) + */ + get subtle(): SubtleCrypto; + /** + * The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) + */ + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array, + >(buffer: T): T; + /** + * The **`randomUUID()`** method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator. + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) + */ + randomUUID(): string; + DigestStream: typeof DigestStream; +} +/** + * The **`SubtleCrypto`** interface of the Web Crypto API provides a number of low-level cryptographic functions. + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto) + */ +declare abstract class SubtleCrypto { + /** + * The **`encrypt()`** method of the SubtleCrypto interface encrypts data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/encrypt) + */ + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView, + ): Promise; + /** + * The **`decrypt()`** method of the SubtleCrypto interface decrypts some encrypted data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/decrypt) + */ + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView, + ): Promise; + /** + * The **`sign()`** method of the SubtleCrypto interface generates a digital signature. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/sign) + */ + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + /** + * The **`verify()`** method of the SubtleCrypto interface verifies a digital signature. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/verify) + */ + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView, + ): Promise; + /** + * The **`digest()`** method of the SubtleCrypto interface generates a _digest_ of the given data, using the specified hash function. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest) + */ + digest(algorithm: string | SubtleCryptoHashAlgorithm, data: ArrayBuffer | ArrayBufferView): Promise; + /** + * The **`generateKey()`** method of the SubtleCrypto interface is used to generate a new key (for symmetric algorithms) or key pair (for public-key algorithms). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) + */ + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + /** + * The **`deriveKey()`** method of the SubtleCrypto interface can be used to derive a secret key from a master key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) + */ + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + /** + * The **`deriveBits()`** method of the key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveBits) + */ + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length?: number | null, + ): Promise; + /** + * The **`importKey()`** method of the SubtleCrypto interface imports a key: that is, it takes as input a key in an external, portable format and gives you a CryptoKey object that you can use in the Web Crypto API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) + */ + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + /** + * The **`exportKey()`** method of the SubtleCrypto interface exports a key: that is, it takes as input a CryptoKey object and gives you the key in an external, portable format. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/exportKey) + */ + exportKey(format: string, key: CryptoKey): Promise; + /** + * The **`wrapKey()`** method of the SubtleCrypto interface 'wraps' a key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/wrapKey) + */ + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + ): Promise; + /** + * The **`unwrapKey()`** method of the SubtleCrypto interface 'unwraps' a key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) + */ + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise; + timingSafeEqual(a: ArrayBuffer | ArrayBufferView, b: ArrayBuffer | ArrayBufferView): boolean; +} +/** + * The **`CryptoKey`** interface of the Web Crypto API represents a cryptographic key obtained from one of the SubtleCrypto methods SubtleCrypto.generateKey, SubtleCrypto.deriveKey, SubtleCrypto.importKey, or SubtleCrypto.unwrapKey. + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey) + */ +declare abstract class CryptoKey { + /** + * The read-only **`type`** property of the CryptoKey interface indicates which kind of key is represented by the object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) + */ + readonly type: string; + /** + * The read-only **`extractable`** property of the CryptoKey interface indicates whether or not the key may be extracted using `SubtleCrypto.exportKey()` or `SubtleCrypto.wrapKey()`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) + */ + readonly extractable: boolean; + /** + * The read-only **`algorithm`** property of the CryptoKey interface returns an object describing the algorithm for which this key can be used, and any associated extra parameters. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) + */ + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm; + /** + * The read-only **`usages`** property of the CryptoKey interface indicates what can be done with the key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) + */ + readonly usages: string[]; +} +interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: ArrayBuffer | ArrayBufferView; + iterations?: number; + hash?: string | SubtleCryptoHashAlgorithm; + $public?: CryptoKey; + info?: ArrayBuffer | ArrayBufferView; +} +interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: ArrayBuffer | ArrayBufferView; + additionalData?: ArrayBuffer | ArrayBufferView; + tagLength?: number; + counter?: ArrayBuffer | ArrayBufferView; + length?: number; + label?: ArrayBuffer | ArrayBufferView; +} +interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer | ArrayBufferView; + length?: number; + namedCurve?: string; +} +interface SubtleCryptoHashAlgorithm { + name: string; +} +interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; +} +interface SubtleCryptoSignAlgorithm { + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; +} +interface CryptoKeyKeyAlgorithm { + name: string; +} +interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer | ArrayBufferView; + hash?: CryptoKeyKeyAlgorithm; +} +interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +declare class DigestStream extends WritableStream { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + readonly digest: Promise; + get bytesWritten(): number | bigint; +} +/** + * The **`TextDecoder`** interface represents a decoder for a specific text encoding, such as `UTF-8`, `ISO-8859-2`, `KOI8-R`, `GBK`, etc. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder) + */ +declare class TextDecoder { + constructor(label?: string, options?: TextDecoderConstructorOptions); + /** + * The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) + */ + decode(input?: ArrayBuffer | ArrayBufferView, options?: TextDecoderDecodeOptions): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +/** + * The **`TextEncoder`** interface takes a stream of code points as input and emits a stream of UTF-8 bytes. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder) + */ +declare class TextEncoder { + constructor(); + /** + * The **`TextEncoder.encode()`** method takes a string as input, and returns a Global_Objects/Uint8Array containing the text given in parameters encoded with the specific method for that TextEncoder object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) + */ + encode(input?: string): Uint8Array; + /** + * The **`TextEncoder.encodeInto()`** method takes a string to encode and a destination Uint8Array to put resulting UTF-8 encoded text into, and returns a dictionary object indicating the progress of the encoding. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) + */ + encodeInto(input: string, buffer: Uint8Array): TextEncoderEncodeIntoResult; + get encoding(): string; +} +interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +interface TextDecoderDecodeOptions { + stream: boolean; +} +interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +/** + * The **`ErrorEvent`** interface represents events providing information related to errors in scripts or in files. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent) + */ +declare class ErrorEvent extends Event { + constructor(type: string, init?: ErrorEventErrorEventInit); + /** + * The **`filename`** read-only property of the ErrorEvent interface returns a string containing the name of the script file in which the error occurred. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) + */ + get filename(): string; + /** + * The **`message`** read-only property of the ErrorEvent interface returns a string containing a human-readable error message describing the problem. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) + */ + get message(): string; + /** + * The **`lineno`** read-only property of the ErrorEvent interface returns an integer containing the line number of the script file on which the error occurred. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) + */ + get lineno(): number; + /** + * The **`colno`** read-only property of the ErrorEvent interface returns an integer containing the column number of the script file on which the error occurred. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) + */ + get colno(): number; + /** + * The **`error`** read-only property of the ErrorEvent interface returns a JavaScript value, such as an Error or DOMException, representing the error associated with this event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) + */ + get error(): any; +} +interface ErrorEventErrorEventInit { + message?: string; + filename?: string; + lineno?: number; + colno?: number; + error?: any; +} +/** + * The **`MessageEvent`** interface represents a message received by a target object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent) + */ +declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + /** + * The **`data`** read-only property of the The data sent by the message emitter; this can be any data type, depending on what originated this event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/data) + */ + readonly data: any; + /** + * The **`origin`** read-only property of the origin of the message emitter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/origin) + */ + readonly origin: string | null; + /** + * The **`lastEventId`** read-only property of the unique ID for the event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/lastEventId) + */ + readonly lastEventId: string; + /** + * The **`source`** read-only property of the a WindowProxy, MessagePort, or a `MessageEventSource` (which can be a WindowProxy, message emitter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/source) + */ + readonly source: MessagePort | null; + /** + * The **`ports`** read-only property of the containing all MessagePort objects sent with the message, in order. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/ports) + */ + readonly ports: MessagePort[]; +} +interface MessageEventInit { + data: ArrayBuffer | string; +} +/** + * The **`PromiseRejectionEvent`** interface represents events which are sent to the global script context when JavaScript Promises are rejected. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent) + */ +declare abstract class PromiseRejectionEvent extends Event { + /** + * The PromiseRejectionEvent interface's **`promise`** read-only property indicates the JavaScript rejected. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) + */ + readonly promise: Promise; + /** + * The PromiseRejectionEvent **`reason`** read-only property is any JavaScript value or Object which provides the reason passed into Promise.reject(). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) + */ + readonly reason: any; +} +/** + * The **`FormData`** interface provides a way to construct a set of key/value pairs representing form fields and their values, which can be sent using the Window/fetch, XMLHttpRequest.send() or navigator.sendBeacon() methods. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData) + */ +declare class FormData { + constructor(); + /** + * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) + */ + append(name: string, value: string | Blob): void; + /** + * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) + */ + append(name: string, value: string): void; + /** + * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) + */ + append(name: string, value: Blob, filename?: string): void; + /** + * The **`delete()`** method of the FormData interface deletes a key and its value(s) from a `FormData` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/delete) + */ + delete(name: string): void; + /** + * The **`get()`** method of the FormData interface returns the first value associated with a given key from within a `FormData` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/get) + */ + get(name: string): (File | string) | null; + /** + * The **`getAll()`** method of the FormData interface returns all the values associated with a given key from within a `FormData` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/getAll) + */ + getAll(name: string): (File | string)[]; + /** + * The **`has()`** method of the FormData interface returns whether a `FormData` object contains a certain key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has) + */ + has(name: string): boolean; + /** + * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) + */ + set(name: string, value: string | Blob): void; + /** + * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) + */ + set(name: string, value: string): void; + /** + * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) + */ + set(name: string, value: Blob, filename?: string): void; + /* Returns an array of key, value pairs for every entry in the list. */ + entries(): IterableIterator<[key: string, value: File | string]>; + /* Returns a list of keys in the list. */ + keys(): IterableIterator; + /* Returns a list of values in the list. */ + values(): IterableIterator; + forEach( + callback: (this: This, value: File | string, key: string, parent: FormData) => void, + thisArg?: This, + ): void; + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]>; +} +interface ContentOptions { + html?: boolean; +} +declare class HTMLRewriter { + constructor(); + on(selector: string, handlers: HTMLRewriterElementContentHandlers): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise; + comments?(comment: Comment): void | Promise; + text?(element: Text): void | Promise; +} +interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise; + comments?(comment: Comment): void | Promise; + text?(text: Text): void | Promise; + end?(end: DocumentEnd): void | Promise; +} +interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +interface Element { + tagName: string; + readonly attributes: IterableIterator; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string | ReadableStream | Response, options?: ContentOptions): Element; + after(content: string | ReadableStream | Response, options?: ContentOptions): Element; + prepend(content: string | ReadableStream | Response, options?: ContentOptions): Element; + append(content: string | ReadableStream | Response, options?: ContentOptions): Element; + replace(content: string | ReadableStream | Response, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string | ReadableStream | Response, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise): void; +} +interface EndTag { + name: string; + before(content: string | ReadableStream | Response, options?: ContentOptions): EndTag; + after(content: string | ReadableStream | Response, options?: ContentOptions): EndTag; + remove(): EndTag; +} +interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string | ReadableStream | Response, options?: ContentOptions): Text; + after(content: string | ReadableStream | Response, options?: ContentOptions): Text; + replace(content: string | ReadableStream | Response, options?: ContentOptions): Text; + remove(): Text; +} +interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +/** + * This is the event type for `fetch` events dispatched on the ServiceWorkerGlobalScope. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent) + */ +declare abstract class FetchEvent extends ExtendableEvent { + /** + * The **`request`** read-only property of the the event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) + */ + readonly request: Request; + /** + * The **`respondWith()`** method of allows you to provide a promise for a Response yourself. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) + */ + respondWith(promise: Response | Promise): void; + passThroughOnException(): void; +} +type HeadersInit = Headers | Iterable> | Record; +/** + * The **`Headers`** interface of the Fetch API allows you to perform various actions on HTTP request and response headers. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers) + */ +declare class Headers { + constructor(init?: HeadersInit); + /** + * The **`get()`** method of the Headers interface returns a byte string of all the values of a header within a `Headers` object with a given name. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/get) + */ + get(name: string): string | null; + getAll(name: string): string[]; + /** + * The **`getSetCookie()`** method of the Headers interface returns an array containing the values of all Set-Cookie headers associated with a response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/getSetCookie) + */ + getSetCookie(): string[]; + /** + * The **`has()`** method of the Headers interface returns a boolean stating whether a `Headers` object contains a certain header. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/has) + */ + has(name: string): boolean; + /** + * The **`set()`** method of the Headers interface sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/set) + */ + set(name: string, value: string): void; + /** + * The **`append()`** method of the Headers interface appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/append) + */ + append(name: string, value: string): void; + /** + * The **`delete()`** method of the Headers interface deletes a header from the current `Headers` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/delete) + */ + delete(name: string): void; + forEach( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This, + ): void; + /* Returns an iterator allowing to go through all key/value pairs contained in this object. */ + entries(): IterableIterator<[key: string, value: string]>; + /* Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ + keys(): IterableIterator; + /* Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +type BodyInit = ReadableStream | string | ArrayBuffer | ArrayBufferView | Blob | URLSearchParams | FormData; +declare abstract class Body { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body) */ + get body(): ReadableStream | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bodyUsed) */ + get bodyUsed(): boolean; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/arrayBuffer) */ + arrayBuffer(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bytes) */ + bytes(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/text) */ + text(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json) */ + json(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData) */ + formData(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/blob) */ + blob(): Promise; +} +/** + * The **`Response`** interface of the Fetch API represents the response to a request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) + */ +declare var Response: { + prototype: Response; + new (body?: BodyInit | null, init?: ResponseInit): Response; + error(): Response; + redirect(url: string, status?: number): Response; + json(any: any, maybeInit?: ResponseInit | Response): Response; +}; +/** + * The **`Response`** interface of the Fetch API represents the response to a request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) + */ +interface Response extends Body { + /** + * The **`clone()`** method of the Response interface creates a clone of a response object, identical in every way, but stored in a different variable. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) + */ + clone(): Response; + /** + * The **`status`** read-only property of the Response interface contains the HTTP status codes of the response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) + */ + status: number; + /** + * The **`statusText`** read-only property of the Response interface contains the status message corresponding to the HTTP status code in Response.status. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) + */ + statusText: string; + /** + * The **`headers`** read-only property of the with the response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) + */ + headers: Headers; + /** + * The **`ok`** read-only property of the Response interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) + */ + ok: boolean; + /** + * The **`redirected`** read-only property of the Response interface indicates whether or not the response is the result of a request you made which was redirected. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) + */ + redirected: boolean; + /** + * The **`url`** read-only property of the Response interface contains the URL of the response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) + */ + url: string; + webSocket: WebSocket | null; + cf: any | undefined; + /** + * The **`type`** read-only property of the Response interface contains the type of the response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/type) + */ + type: 'default' | 'error'; +} +interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: 'automatic' | 'manual'; +} +type RequestInfo> = Request | string; +/** + * The **`Request`** interface of the Fetch API represents a resource request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) + */ +declare var Request: { + prototype: Request; + new >( + input: RequestInfo | URL, + init?: RequestInit, + ): Request; +}; +/** + * The **`Request`** interface of the Fetch API represents a resource request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) + */ +interface Request> extends Body { + /** + * The **`clone()`** method of the Request interface creates a copy of the current `Request` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) + */ + clone(): Request; + /** + * The **`method`** read-only property of the `POST`, etc.) A String indicating the method of the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) + */ + method: string; + /** + * The **`url`** read-only property of the Request interface contains the URL of the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) + */ + url: string; + /** + * The **`headers`** read-only property of the with the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) + */ + headers: Headers; + /** + * The **`redirect`** read-only property of the Request interface contains the mode for how redirects are handled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) + */ + redirect: string; + fetcher: Fetcher | null; + /** + * The read-only **`signal`** property of the Request interface returns the AbortSignal associated with the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) + */ + signal: AbortSignal; + cf?: Cf; + /** + * The **`integrity`** read-only property of the Request interface contains the subresource integrity value of the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) + */ + integrity: string; + /** + * The **`keepalive`** read-only property of the Request interface contains the request's `keepalive` setting (`true` or `false`), which indicates whether the browser will keep the associated request alive if the page that initiated it is unloaded before the request is complete. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) + */ + keepalive: boolean; +} +interface RequestInit { + /* A string to set request's method. */ + method?: string; + /* A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /* A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /* A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect?: string; + fetcher?: Fetcher | null; + cf?: Cf; + /* A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /* An AbortSignal to set request's signal. */ + signal?: AbortSignal | null; + encodeResponseBody?: 'automatic' | 'manual'; +} +type Service< + T extends + | (new (...args: any[]) => Rpc.WorkerEntrypointBranded) + | Rpc.WorkerEntrypointBranded + | ExportedHandler + | undefined = undefined, +> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded + ? Fetcher> + : T extends Rpc.WorkerEntrypointBranded + ? Fetcher + : T extends Exclude + ? never + : Fetcher; +type Fetcher< + T extends Rpc.EntrypointBranded | undefined = undefined, + Reserved extends string = never, +> = (T extends Rpc.EntrypointBranded ? Rpc.Provider : unknown) & { + fetch(input: RequestInfo | URL, init?: RequestInit): Promise; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +}; +interface KVNamespaceListKey { + name: Key; + expiration?: number; + metadata?: Metadata; +} +type KVNamespaceListResult = + | { + list_complete: false; + keys: KVNamespaceListKey[]; + cursor: string; + cacheStatus: string | null; + } + | { + list_complete: true; + keys: KVNamespaceListKey[]; + cacheStatus: string | null; + }; +interface KVNamespace { + get(key: Key, options?: Partial>): Promise; + get(key: Key, type: 'text'): Promise; + get(key: Key, type: 'json'): Promise; + get(key: Key, type: 'arrayBuffer'): Promise; + get(key: Key, type: 'stream'): Promise; + get(key: Key, options?: KVNamespaceGetOptions<'text'>): Promise; + get(key: Key, options?: KVNamespaceGetOptions<'json'>): Promise; + get(key: Key, options?: KVNamespaceGetOptions<'arrayBuffer'>): Promise; + get(key: Key, options?: KVNamespaceGetOptions<'stream'>): Promise; + get(key: Array, type: 'text'): Promise>; + get(key: Array, type: 'json'): Promise>; + get(key: Array, options?: Partial>): Promise>; + get(key: Array, options?: KVNamespaceGetOptions<'text'>): Promise>; + get( + key: Array, + options?: KVNamespaceGetOptions<'json'>, + ): Promise>; + list(options?: KVNamespaceListOptions): Promise>; + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions, + ): Promise; + getWithMetadata( + key: Key, + options?: Partial>, + ): Promise>; + getWithMetadata( + key: Key, + type: 'text', + ): Promise>; + getWithMetadata( + key: Key, + type: 'json', + ): Promise>; + getWithMetadata( + key: Key, + type: 'arrayBuffer', + ): Promise>; + getWithMetadata( + key: Key, + type: 'stream', + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<'text'>, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<'json'>, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<'arrayBuffer'>, + ): Promise>; + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<'stream'>, + ): Promise>; + getWithMetadata( + key: Array, + type: 'text', + ): Promise>>; + getWithMetadata( + key: Array, + type: 'json', + ): Promise>>; + getWithMetadata( + key: Array, + options?: Partial>, + ): Promise>>; + getWithMetadata( + key: Array, + options?: KVNamespaceGetOptions<'text'>, + ): Promise>>; + getWithMetadata( + key: Array, + options?: KVNamespaceGetOptions<'json'>, + ): Promise>>; + delete(key: Key): Promise; +} +interface KVNamespaceListOptions { + limit?: number; + prefix?: string | null; + cursor?: string | null; +} +interface KVNamespaceGetOptions { + type: Type; + cacheTtl?: number; +} +interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: any | null; +} +interface KVNamespaceGetWithMetadataResult { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +type QueueContentType = 'text' | 'bytes' | 'json' | 'v8'; +interface Queue { + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch(messages: Iterable>, options?: QueueSendBatchOptions): Promise; +} +interface QueueSendOptions { + contentType?: QueueContentType; + delaySeconds?: number; +} +interface QueueSendBatchOptions { + delaySeconds?: number; +} +interface MessageSendRequest { + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; +} +interface QueueRetryOptions { + delaySeconds?: number; +} +interface Message { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + readonly attempts: number; + retry(options?: QueueRetryOptions): void; + ack(): void; +} +interface QueueEvent extends ExtendableEvent { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +interface MessageBatch { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; + include?: ('httpMetadata' | 'customMetadata')[]; +} +declare abstract class R2Bucket { + head(key: string): Promise; + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + get(key: string, options?: R2GetOptions): Promise; + put( + key: string, + value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + }, + ): Promise; + put( + key: string, + value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, + options?: R2PutOptions, + ): Promise; + createMultipartUpload(key: string, options?: R2MultipartOptions): Promise; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise; + list(options?: R2ListOptions): Promise; +} +interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, + options?: R2UploadPartOptions, + ): Promise; + abort(): Promise; + complete(uploadedParts: R2UploadedPart[]): Promise; +} +interface R2UploadedPart { + partNumber: number; + etag: string; +} +declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record; + readonly range?: R2Range; + readonly storageClass: string; + readonly ssecKeyMd5?: string; + writeHttpMetadata(headers: Headers): void; +} +interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + bytes(): Promise; + text(): Promise; + json(): Promise; + blob(): Promise; +} +type R2Range = + | { + offset: number; + length?: number; + } + | { + offset?: number; + length: number; + } + | { + suffix: number; + }; +interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +interface R2GetOptions { + onlyIf?: R2Conditional | Headers; + range?: R2Range | Headers; + ssecKey?: ArrayBuffer | string; +} +interface R2PutOptions { + onlyIf?: R2Conditional | Headers; + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + md5?: (ArrayBuffer | ArrayBufferView) | string; + sha1?: (ArrayBuffer | ArrayBufferView) | string; + sha256?: (ArrayBuffer | ArrayBufferView) | string; + sha384?: (ArrayBuffer | ArrayBufferView) | string; + sha512?: (ArrayBuffer | ArrayBufferView) | string; + storageClass?: string; + ssecKey?: ArrayBuffer | string; +} +interface R2MultipartOptions { + httpMetadata?: R2HTTPMetadata | Headers; + customMetadata?: Record; + storageClass?: string; + ssecKey?: ArrayBuffer | string; +} +interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); +interface R2UploadPartOptions { + ssecKey?: ArrayBuffer | string; +} +declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +interface QueuingStrategy { + highWaterMark?: number | bigint; + size?: (chunk: T) => number | bigint; +} +interface UnderlyingSink { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise; + write?: (chunk: W, controller: WritableStreamDefaultController) => void | Promise; + abort?: (reason: any) => void | Promise; + close?: () => void | Promise; +} +interface UnderlyingByteSource { + type: 'bytes'; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise; + pull?: (controller: ReadableByteStreamController) => void | Promise; + cancel?: (reason: any) => void | Promise; +} +interface UnderlyingSource { + type?: '' | undefined; + start?: (controller: ReadableStreamDefaultController) => void | Promise; + pull?: (controller: ReadableStreamDefaultController) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number | bigint; +} +interface Transformer { + readableType?: string; + writableType?: string; + start?: (controller: TransformStreamDefaultController) => void | Promise; + transform?: (chunk: I, controller: TransformStreamDefaultController) => void | Promise; + flush?: (controller: TransformStreamDefaultController) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number; +} +interface StreamPipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; + /** + * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate as follows: + * + * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination. + * + * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source. + * + * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. + * + * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. + * + * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. + */ + preventClose?: boolean; + signal?: AbortSignal; +} +type ReadableStreamReadResult = + | { + done: false; + value: R; + } + | { + done: true; + value?: undefined; + }; +/** + * The `ReadableStream` interface of the Streams API represents a readable stream of byte data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + */ +interface ReadableStream { + /** + * The **`locked`** read-only property of the ReadableStream interface returns whether or not the readable stream is locked to a reader. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) + */ + get locked(): boolean; + /** + * The **`cancel()`** method of the ReadableStream interface returns a Promise that resolves when the stream is canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) + */ + cancel(reason?: any): Promise; + /** + * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) + */ + getReader(): ReadableStreamDefaultReader; + /** + * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) + */ + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + /** + * The **`pipeThrough()`** method of the ReadableStream interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) + */ + pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; + /** + * The **`pipeTo()`** method of the ReadableStream interface pipes the current `ReadableStream` to a given WritableStream and returns a Promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) + */ + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + /** + * The **`tee()`** method of the two-element array containing the two resulting branches as new ReadableStream instances. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) + */ + tee(): [ReadableStream, ReadableStream]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; + [Symbol.asyncIterator](options?: ReadableStreamValuesOptions): AsyncIterableIterator; +} +/** + * The `ReadableStream` interface of the Streams API represents a readable stream of byte data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + */ +declare const ReadableStream: { + prototype: ReadableStream; + new (underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; + new (underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; +}; +/** + * The **`ReadableStreamDefaultReader`** interface of the Streams API represents a default reader that can be used to read stream data supplied from a network (such as a fetch request). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader) + */ +declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** + * The **`read()`** method of the ReadableStreamDefaultReader interface returns a Promise providing access to the next chunk in the stream's internal queue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) + */ + read(): Promise>; + /** + * The **`releaseLock()`** method of the ReadableStreamDefaultReader interface releases the reader's lock on the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) + */ + releaseLock(): void; +} +/** + * The `ReadableStreamBYOBReader` interface of the Streams API defines a reader for a ReadableStream that supports zero-copy reading from an underlying byte source. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) + */ +declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** + * The **`read()`** method of the ReadableStreamBYOBReader interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) + */ + read(view: T): Promise>; + /** + * The **`releaseLock()`** method of the ReadableStreamBYOBReader interface releases the reader's lock on the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) + */ + releaseLock(): void; + readAtLeast(minElements: number, view: T): Promise>; +} +interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { + min?: number; +} +interface ReadableStreamGetReaderOptions { + /** + * Creates a ReadableStreamBYOBReader and locks the stream to the new reader. + * + * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode: 'byob'; +} +/** + * The **`ReadableStreamBYOBRequest`** interface of the Streams API represents a 'pull request' for data from an underlying source that will made as a zero-copy transfer to a consumer (bypassing the stream's internal queues). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) + */ +declare abstract class ReadableStreamBYOBRequest { + /** + * The **`view`** getter property of the ReadableStreamBYOBRequest interface returns the current view. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) + */ + get view(): Uint8Array | null; + /** + * The **`respond()`** method of the ReadableStreamBYOBRequest interface is used to signal to the associated readable byte stream that the specified number of bytes were written into the ReadableStreamBYOBRequest.view. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) + */ + respond(bytesWritten: number): void; + /** + * The **`respondWithNewView()`** method of the ReadableStreamBYOBRequest interface specifies a new view that the consumer of the associated readable byte stream should write to instead of ReadableStreamBYOBRequest.view. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) + */ + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + get atLeast(): number | null; +} +/** + * The **`ReadableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a ReadableStream's state and internal queue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) + */ +declare abstract class ReadableStreamDefaultController { + /** + * The **`desiredSize`** read-only property of the required to fill the stream's internal queue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) + */ + get desiredSize(): number | null; + /** + * The **`close()`** method of the ReadableStreamDefaultController interface closes the associated stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) + */ + close(): void; + /** + * The **`enqueue()`** method of the ```js-nolint enqueue(chunk) ``` - `chunk` - : The chunk to enqueue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) + */ + enqueue(chunk?: R): void; + /** + * The **`error()`** method of the with the associated stream to error. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) + */ + error(reason: any): void; +} +/** + * The **`ReadableByteStreamController`** interface of the Streams API represents a controller for a readable byte stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) + */ +declare abstract class ReadableByteStreamController { + /** + * The **`byobRequest`** read-only property of the ReadableByteStreamController interface returns the current BYOB request, or `null` if there are no pending requests. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) + */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /** + * The **`desiredSize`** read-only property of the ReadableByteStreamController interface returns the number of bytes required to fill the stream's internal queue to its 'desired size'. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) + */ + get desiredSize(): number | null; + /** + * The **`close()`** method of the ReadableByteStreamController interface closes the associated stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) + */ + close(): void; + /** + * The **`enqueue()`** method of the ReadableByteStreamController interface enqueues a given chunk on the associated readable byte stream (the chunk is copied into the stream's internal queues). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) + */ + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + /** + * The **`error()`** method of the ReadableByteStreamController interface causes any future interactions with the associated stream to error with the specified reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) + */ + error(reason: any): void; +} +/** + * The **`WritableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a WritableStream's state. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController) + */ +declare abstract class WritableStreamDefaultController { + /** + * The read-only **`signal`** property of the WritableStreamDefaultController interface returns the AbortSignal associated with the controller. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) + */ + get signal(): AbortSignal; + /** + * The **`error()`** method of the with the associated stream to error. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) + */ + error(reason?: any): void; +} +/** + * The **`TransformStreamDefaultController`** interface of the Streams API provides methods to manipulate the associated ReadableStream and WritableStream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) + */ +declare abstract class TransformStreamDefaultController { + /** + * The **`desiredSize`** read-only property of the TransformStreamDefaultController interface returns the desired size to fill the queue of the associated ReadableStream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) + */ + get desiredSize(): number | null; + /** + * The **`enqueue()`** method of the TransformStreamDefaultController interface enqueues the given chunk in the readable side of the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) + */ + enqueue(chunk?: O): void; + /** + * The **`error()`** method of the TransformStreamDefaultController interface errors both sides of the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) + */ + error(reason: any): void; + /** + * The **`terminate()`** method of the TransformStreamDefaultController interface closes the readable side and errors the writable side of the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) + */ + terminate(): void; +} +interface ReadableWritablePair { + readable: ReadableStream; + /** + * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + writable: WritableStream; +} +/** + * The **`WritableStream`** interface of the Streams API provides a standard abstraction for writing streaming data to a destination, known as a sink. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream) + */ +declare class WritableStream { + constructor(underlyingSink?: UnderlyingSink, queuingStrategy?: QueuingStrategy); + /** + * The **`locked`** read-only property of the WritableStream interface returns a boolean indicating whether the `WritableStream` is locked to a writer. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) + */ + get locked(): boolean; + /** + * The **`abort()`** method of the WritableStream interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) + */ + abort(reason?: any): Promise; + /** + * The **`close()`** method of the WritableStream interface closes the associated stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) + */ + close(): Promise; + /** + * The **`getWriter()`** method of the WritableStream interface returns a new instance of WritableStreamDefaultWriter and locks the stream to that instance. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) + */ + getWriter(): WritableStreamDefaultWriter; +} +/** + * The **`WritableStreamDefaultWriter`** interface of the Streams API is the object returned by WritableStream.getWriter() and once created locks the writer to the `WritableStream` ensuring that no other streams can write to the underlying sink. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter) + */ +declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /** + * The **`closed`** read-only property of the the stream errors or the writer's lock is released. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) + */ + get closed(): Promise; + /** + * The **`ready`** read-only property of the that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) + */ + get ready(): Promise; + /** + * The **`desiredSize`** read-only property of the to fill the stream's internal queue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) + */ + get desiredSize(): number | null; + /** + * The **`abort()`** method of the the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) + */ + abort(reason?: any): Promise; + /** + * The **`close()`** method of the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) + */ + close(): Promise; + /** + * The **`write()`** method of the operation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) + */ + write(chunk?: W): Promise; + /** + * The **`releaseLock()`** method of the corresponding stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) + */ + releaseLock(): void; +} +/** + * The **`TransformStream`** interface of the Streams API represents a concrete implementation of the pipe chain _transform stream_ concept. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream) + */ +declare class TransformStream { + constructor( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ); + /** + * The **`readable`** read-only property of the TransformStream interface returns the ReadableStream instance controlled by this `TransformStream`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) + */ + get readable(): ReadableStream; + /** + * The **`writable`** read-only property of the TransformStream interface returns the WritableStream instance controlled by this `TransformStream`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) + */ + get writable(): WritableStream; +} +declare class FixedLengthStream extends IdentityTransformStream { + constructor(expectedLength: number | bigint, queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +declare class IdentityTransformStream extends TransformStream { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: number | bigint; +} +interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +/** + * The **`CompressionStream`** interface of the Compression Streams API is an API for compressing a stream of data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream) + */ +declare class CompressionStream extends TransformStream { + constructor(format: 'gzip' | 'deflate' | 'deflate-raw'); +} +/** + * The **`DecompressionStream`** interface of the Compression Streams API is an API for decompressing a stream of data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DecompressionStream) + */ +declare class DecompressionStream extends TransformStream { + constructor(format: 'gzip' | 'deflate' | 'deflate-raw'); +} +/** + * The **`TextEncoderStream`** interface of the Encoding API converts a stream of strings into bytes in the UTF-8 encoding. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoderStream) + */ +declare class TextEncoderStream extends TransformStream { + constructor(); + get encoding(): string; +} +/** + * The **`TextDecoderStream`** interface of the Encoding API converts a stream of text in a binary encoding, such as UTF-8 etc., to a stream of strings. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoderStream) + */ +declare class TextDecoderStream extends TransformStream { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; + ignoreBOM?: boolean; +} +/** + * The **`ByteLengthQueuingStrategy`** interface of the Streams API provides a built-in byte length queuing strategy that can be used when constructing streams. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy) + */ +declare class ByteLengthQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + /** + * The read-only **`ByteLengthQueuingStrategy.highWaterMark`** property returns the total number of bytes that can be contained in the internal queue before backpressure is applied. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) + */ + get highWaterMark(): number; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +/** + * The **`CountQueuingStrategy`** interface of the Streams API provides a built-in chunk counting queuing strategy that can be used when constructing streams. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy) + */ +declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + /** + * The read-only **`CountQueuingStrategy.highWaterMark`** property returns the total number of chunks that can be contained in the internal queue before backpressure is applied. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) + */ + get highWaterMark(): number; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water mark. + * + * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw. + */ + highWaterMark: number; +} +interface ScriptVersion { + id?: string; + tag?: string; + message?: string; +} +declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +interface TraceItem { + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemJsRpcEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemTailEventInfo + | TraceItemCustomEventInfo + | TraceItemHibernatableWebSocketEventInfo + ) + | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly entrypoint?: string; + readonly scriptVersion?: ScriptVersion; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly durableObjectId?: string; + readonly outcome: string; + readonly executionModel: string; + readonly truncated: boolean; + readonly cpuTime: number; + readonly wallTime: number; +} +interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +interface TraceItemCustomEventInfo {} +interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +interface TraceItemTailEventInfo { + readonly consumedEvents: TraceItemTailEventInfoTailItem[]; +} +interface TraceItemTailEventInfoTailItem { + readonly scriptName: string | null; +} +interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +interface TraceItemJsRpcEventInfo { + readonly rpcMethod: string; +} +interface TraceItemHibernatableWebSocketEventInfo { + readonly getWebSocketEvent: + | TraceItemHibernatableWebSocketEventInfoMessage + | TraceItemHibernatableWebSocketEventInfoClose + | TraceItemHibernatableWebSocketEventInfoError; +} +interface TraceItemHibernatableWebSocketEventInfoMessage { + readonly webSocketEventType: string; +} +interface TraceItemHibernatableWebSocketEventInfoClose { + readonly webSocketEventType: string; + readonly code: number; + readonly wasClean: boolean; +} +interface TraceItemHibernatableWebSocketEventInfoError { + readonly webSocketEventType: string; +} +interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; + readonly stack?: string; +} +interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +/** + * The **`URL`** interface is used to parse, construct, normalize, and encode URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL) + */ +declare class URL { + constructor(url: string | URL, base?: string | URL); + /** + * The **`origin`** read-only property of the URL interface returns a string containing the Unicode serialization of the origin of the represented URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) + */ + get origin(): string; + /** + * The **`href`** property of the URL interface is a string containing the whole URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) + */ + get href(): string; + /** + * The **`href`** property of the URL interface is a string containing the whole URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) + */ + set href(value: string); + /** + * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final `':'`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) + */ + get protocol(): string; + /** + * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final `':'`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) + */ + set protocol(value: string); + /** + * The **`username`** property of the URL interface is a string containing the username component of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) + */ + get username(): string; + /** + * The **`username`** property of the URL interface is a string containing the username component of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) + */ + set username(value: string); + /** + * The **`password`** property of the URL interface is a string containing the password component of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) + */ + get password(): string; + /** + * The **`password`** property of the URL interface is a string containing the password component of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) + */ + set password(value: string); + /** + * The **`host`** property of the URL interface is a string containing the host, which is the URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) + */ + get host(): string; + /** + * The **`host`** property of the URL interface is a string containing the host, which is the URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) + */ + set host(value: string); + /** + * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) + */ + get hostname(): string; + /** + * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) + */ + set hostname(value: string); + /** + * The **`port`** property of the URL interface is a string containing the port number of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) + */ + get port(): string; + /** + * The **`port`** property of the URL interface is a string containing the port number of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) + */ + set port(value: string); + /** + * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) + */ + get pathname(): string; + /** + * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) + */ + set pathname(value: string); + /** + * The **`search`** property of the URL interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) + */ + get search(): string; + /** + * The **`search`** property of the URL interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) + */ + set search(value: string); + /** + * The **`hash`** property of the URL interface is a string containing a `'#'` followed by the fragment identifier of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) + */ + get hash(): string; + /** + * The **`hash`** property of the URL interface is a string containing a `'#'` followed by the fragment identifier of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) + */ + set hash(value: string); + /** + * The **`searchParams`** read-only property of the access to the [MISSING: httpmethod('GET')] decoded query arguments contained in the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) + */ + get searchParams(): URLSearchParams; + /** + * The **`toJSON()`** method of the URL interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as ```js-nolint toJSON() ``` None. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) + */ + toJSON(): string; + /*function toString() { [native code] }*/ + toString(): string; + /** + * The **`URL.canParse()`** static method of the URL interface returns a boolean indicating whether or not an absolute URL, or a relative URL combined with a base URL, are parsable and valid. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) + */ + static canParse(url: string, base?: string): boolean; + /** + * The **`URL.parse()`** static method of the URL interface returns a newly created URL object representing the URL defined by the parameters. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/parse_static) + */ + static parse(url: string, base?: string): URL | null; + /** + * The **`createObjectURL()`** static method of the URL interface creates a string containing a URL representing the object given in the parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static) + */ + static createObjectURL(object: File | Blob): string; + /** + * The **`revokeObjectURL()`** static method of the URL interface releases an existing object URL which was previously created by calling Call this method when you've finished using an object URL to let the browser know not to keep the reference to the file any longer. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static) + */ + static revokeObjectURL(object_url: string): void; +} +/** + * The **`URLSearchParams`** interface defines utility methods to work with the query string of a URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams) + */ +declare class URLSearchParams { + constructor(init?: Iterable> | Record | string); + /** + * The **`size`** read-only property of the URLSearchParams interface indicates the total number of search parameter entries. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/size) + */ + get size(): number; + /** + * The **`append()`** method of the URLSearchParams interface appends a specified key/value pair as a new search parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/append) + */ + append(name: string, value: string): void; + /** + * The **`delete()`** method of the URLSearchParams interface deletes specified parameters and their associated value(s) from the list of all search parameters. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/delete) + */ + delete(name: string, value?: string): void; + /** + * The **`get()`** method of the URLSearchParams interface returns the first value associated to the given search parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/get) + */ + get(name: string): string | null; + /** + * The **`getAll()`** method of the URLSearchParams interface returns all the values associated with a given search parameter as an array. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/getAll) + */ + getAll(name: string): string[]; + /** + * The **`has()`** method of the URLSearchParams interface returns a boolean value that indicates whether the specified parameter is in the search parameters. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/has) + */ + has(name: string, value?: string): boolean; + /** + * The **`set()`** method of the URLSearchParams interface sets the value associated with a given search parameter to the given value. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/set) + */ + set(name: string, value: string): void; + /** + * The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns `undefined`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/sort) + */ + sort(): void; + /* Returns an array of key, value pairs for every entry in the search params. */ + entries(): IterableIterator<[key: string, value: string]>; + /* Returns a list of keys in the search params. */ + keys(): IterableIterator; + /* Returns a list of values in the search params. */ + values(): IterableIterator; + forEach( + callback: (this: This, value: string, key: string, parent: URLSearchParams) => void, + thisArg?: This, + ): void; + /*function toString() { [native code] }*/ + toString(): string; + [Symbol.iterator](): IterableIterator<[key: string, value: string]>; +} +declare class URLPattern { + constructor( + input?: string | URLPatternInit, + baseURL?: string | URLPatternOptions, + patternOptions?: URLPatternOptions, + ); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + test(input?: string | URLPatternInit, baseURL?: string): boolean; + exec(input?: string | URLPatternInit, baseURL?: string): URLPatternResult | null; +} +interface URLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +interface URLPatternComponentResult { + input: string; + groups: Record; +} +interface URLPatternResult { + inputs: (string | URLPatternInit)[]; + protocol: URLPatternComponentResult; + username: URLPatternComponentResult; + password: URLPatternComponentResult; + hostname: URLPatternComponentResult; + port: URLPatternComponentResult; + pathname: URLPatternComponentResult; + search: URLPatternComponentResult; + hash: URLPatternComponentResult; +} +interface URLPatternOptions { + ignoreCase?: boolean; +} +/** + * A `CloseEvent` is sent to clients using WebSockets when the connection is closed. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent) + */ +declare class CloseEvent extends Event { + constructor(type: string, initializer?: CloseEventInit); + /** + * The **`code`** read-only property of the CloseEvent interface returns a WebSocket connection close code indicating the reason the connection was closed. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) + */ + readonly code: number; + /** + * The **`reason`** read-only property of the CloseEvent interface returns the WebSocket connection close reason the server gave for closing the connection; that is, a concise human-readable prose explanation for the closure. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) + */ + readonly reason: string; + /** + * The **`wasClean`** read-only property of the CloseEvent interface returns `true` if the connection closed cleanly. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) + */ + readonly wasClean: boolean; +} +interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +/** + * The `WebSocket` object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) + */ +declare var WebSocket: { + prototype: WebSocket; + new (url: string, protocols?: string[] | string): WebSocket; + readonly READY_STATE_CONNECTING: number; + readonly CONNECTING: number; + readonly READY_STATE_OPEN: number; + readonly OPEN: number; + readonly READY_STATE_CLOSING: number; + readonly CLOSING: number; + readonly READY_STATE_CLOSED: number; + readonly CLOSED: number; +}; +/** + * The `WebSocket` object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) + */ +interface WebSocket extends EventTarget { + accept(options?: WebSocketAcceptOptions): void; + /** + * The **`WebSocket.send()`** method enqueues the specified data to be transmitted to the server over the WebSocket connection, increasing the value of `bufferedAmount` by the number of bytes needed to contain the data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) + */ + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + /** + * The **`WebSocket.close()`** method closes the already `CLOSED`, this method does nothing. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) + */ + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + /** + * The **`WebSocket.readyState`** read-only property returns the current state of the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) + */ + readyState: number; + /** + * The **`WebSocket.url`** read-only property returns the absolute URL of the WebSocket as resolved by the constructor. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) + */ + url: string | null; + /** + * The **`WebSocket.protocol`** read-only property returns the name of the sub-protocol the server selected; this will be one of the strings specified in the `protocols` parameter when creating the WebSocket object, or the empty string if no connection is established. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) + */ + protocol: string | null; + /** + * The **`WebSocket.extensions`** read-only property returns the extensions selected by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) + */ + extensions: string | null; + /** + * The **`WebSocket.binaryType`** property controls the type of binary data being received over the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/binaryType) + */ + binaryType: 'blob' | 'arraybuffer'; +} +interface WebSocketAcceptOptions { + /** + * When set to `true`, receiving a server-initiated WebSocket Close frame will not + * automatically send a reciprocal Close frame, leaving the connection in a half-open + * state. This is useful for proxying scenarios where you need to coordinate closing + * both sides independently. Defaults to `false` when the + * `no_web_socket_half_open_by_default` compatibility flag is enabled. + */ + allowHalfOpen?: boolean; +} +declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +interface SqlStorage { + exec>(query: string, ...bindings: any[]): SqlStorageCursor; + get databaseSize(): number; + Cursor: typeof SqlStorageCursor; + Statement: typeof SqlStorageStatement; +} +declare abstract class SqlStorageStatement {} +type SqlStorageValue = ArrayBuffer | string | number | null; +declare abstract class SqlStorageCursor> { + next(): + | { + done?: false; + value: T; + } + | { + done: true; + value?: never; + }; + toArray(): T[]; + one(): T; + raw(): IterableIterator; + columnNames: string[]; + get rowsRead(): number; + get rowsWritten(): number; + [Symbol.iterator](): IterableIterator; +} +interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise; + get opened(): Promise; + get upgraded(): boolean; + get secureTransport(): 'on' | 'off' | 'starttls'; + close(): Promise; + startTls(options?: TlsOptions): Socket; +} +interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; + highWaterMark?: number | bigint; +} +interface SocketAddress { + hostname: string; + port: number; +} +interface TlsOptions { + expectedServerHostname?: string; +} +interface SocketInfo { + remoteAddress?: string; + localAddress?: string; +} +/** + * The **`EventSource`** interface is web content's interface to server-sent events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource) + */ +declare class EventSource extends EventTarget { + constructor(url: string, init?: EventSourceEventSourceInit); + /** + * The **`close()`** method of the EventSource interface closes the connection, if one is made, and sets the ```js-nolint close() ``` None. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) + */ + close(): void; + /** + * The **`url`** read-only property of the URL of the source. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) + */ + get url(): string; + /** + * The **`withCredentials`** read-only property of the the `EventSource` object was instantiated with CORS credentials set. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) + */ + get withCredentials(): boolean; + /** + * The **`readyState`** read-only property of the connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) + */ + get readyState(): number; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + get onopen(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + set onopen(value: any | null); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + get onmessage(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + set onmessage(value: any | null); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + get onerror(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + set onerror(value: any | null); + static readonly CONNECTING: number; + static readonly OPEN: number; + static readonly CLOSED: number; + static from(stream: ReadableStream): EventSource; +} +interface EventSourceEventSourceInit { + withCredentials?: boolean; + fetcher?: Fetcher; +} +interface Container { + get running(): boolean; + start(options?: ContainerStartupOptions): void; + monitor(): Promise; + destroy(error?: any): Promise; + signal(signo: number): void; + getTcpPort(port: number): Fetcher; + setInactivityTimeout(durationMs: number | bigint): Promise; + interceptOutboundHttp(addr: string, binding: Fetcher): Promise; + interceptAllOutboundHttp(binding: Fetcher): Promise; +} +interface ContainerStartupOptions { + entrypoint?: string[]; + enableInternet: boolean; + env?: Record; + hardTimeout?: number | bigint; +} +/** + * The **`MessagePort`** interface of the Channel Messaging API represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort) + */ +declare abstract class MessagePort extends EventTarget { + /** + * The **`postMessage()`** method of the transfers ownership of objects to other browsing contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/postMessage) + */ + postMessage(data?: any, options?: any[] | MessagePortPostMessageOptions): void; + /** + * The **`close()`** method of the MessagePort interface disconnects the port, so it is no longer active. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/close) + */ + close(): void; + /** + * The **`start()`** method of the MessagePort interface starts the sending of messages queued on the port. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/start) + */ + start(): void; + get onmessage(): any | null; + set onmessage(value: any | null); +} +interface MessagePortPostMessageOptions { + transfer?: any[]; +} +type LoopbackForExport< + T extends (new (...args: any[]) => Rpc.EntrypointBranded) | ExportedHandler | undefined = undefined, +> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded + ? LoopbackServiceStub> + : T extends new (...args: any[]) => Rpc.DurableObjectBranded + ? LoopbackDurableObjectClass> + : T extends ExportedHandler + ? LoopbackServiceStub + : undefined; +type LoopbackServiceStub = Fetcher & + (T extends CloudflareWorkersModule.WorkerEntrypoint + ? (opts: { props?: Props }) => Fetcher + : (opts: { props?: any }) => Fetcher); +type LoopbackDurableObjectClass = DurableObjectClass & + (T extends CloudflareWorkersModule.DurableObject + ? (opts: { props?: Props }) => DurableObjectClass + : (opts: { props?: any }) => DurableObjectClass); +interface SyncKvStorage { + get(key: string): T | undefined; + list(options?: SyncKvListOptions): Iterable<[string, T]>; + put(key: string, value: T): void; + delete(key: string): boolean; +} +interface SyncKvListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; +} +interface WorkerStub { + getEntrypoint( + name?: string, + options?: WorkerStubEntrypointOptions, + ): Fetcher; +} +interface WorkerStubEntrypointOptions { + props?: any; +} +interface WorkerLoader { + get(name: string | null, getCode: () => WorkerLoaderWorkerCode | Promise): WorkerStub; + load(code: WorkerLoaderWorkerCode): WorkerStub; +} +interface WorkerLoaderModule { + js?: string; + cjs?: string; + text?: string; + data?: ArrayBuffer; + json?: any; + py?: string; + wasm?: ArrayBuffer; +} +interface WorkerLoaderWorkerCode { + compatibilityDate: string; + compatibilityFlags?: string[]; + allowExperimental?: boolean; + mainModule: string; + modules: Record; + env?: any; + globalOutbound?: Fetcher | null; + tails?: Fetcher[]; + streamingTails?: Fetcher[]; +} +/** + * The Workers runtime supports a subset of the Performance API, used to measure timing and performance, + * as well as timing of subrequests and other operations. + * + * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) + */ +declare abstract class Performance { + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancetimeorigin) */ + get timeOrigin(): number; + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancenow) */ + now(): number; + /** + * The **`toJSON()`** method of the Performance interface is a Serialization; it returns a JSON representation of the Performance object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/toJSON) + */ + toJSON(): object; +} +// AI Search V2 API Error Interfaces +interface AiSearchInternalError extends Error {} +interface AiSearchNotFoundError extends Error {} +interface AiSearchNameNotSetError extends Error {} +// AI Search V2 Request Types +type AiSearchSearchRequest = { + messages: Array<{ + role: 'system' | 'developer' | 'user' | 'assistant' | 'tool'; + content: string | null; + }>; + ai_search_options?: { + retrieval?: { + retrieval_type?: 'vector' | 'keyword' | 'hybrid'; + /** Match threshold (0-1, default 0.4) */ + match_threshold?: number; + /** Maximum number of results (1-50, default 10) */ + max_num_results?: number; + filters?: VectorizeVectorMetadataFilter; + /** Context expansion (0-3, default 0) */ + context_expansion?: number; + [key: string]: unknown; + }; + query_rewrite?: { + enabled?: boolean; + model?: string; + rewrite_prompt?: string; + [key: string]: unknown; + }; + reranking?: { + /** Enable reranking (default false) */ + enabled?: boolean; + model?: '@cf/baai/bge-reranker-base' | ''; + /** Match threshold (0-1, default 0.4) */ + match_threshold?: number; + [key: string]: unknown; + }; + [key: string]: unknown; + }; +}; +type AiSearchChatCompletionsRequest = { + messages: Array<{ + role: 'system' | 'developer' | 'user' | 'assistant' | 'tool'; + content: string | null; + }>; + model?: string; + stream?: boolean; + ai_search_options?: { + retrieval?: { + retrieval_type?: 'vector' | 'keyword' | 'hybrid'; + match_threshold?: number; + max_num_results?: number; + filters?: VectorizeVectorMetadataFilter; + context_expansion?: number; + [key: string]: unknown; + }; + query_rewrite?: { + enabled?: boolean; + model?: string; + rewrite_prompt?: string; + [key: string]: unknown; + }; + reranking?: { + enabled?: boolean; + model?: '@cf/baai/bge-reranker-base' | ''; + match_threshold?: number; + [key: string]: unknown; + }; + [key: string]: unknown; + }; + [key: string]: unknown; +}; +// AI Search V2 Response Types +type AiSearchSearchResponse = { + search_query: string; + chunks: Array<{ + id: string; + type: string; + /** Match score (0-1) */ + score: number; + text: string; + item: { + timestamp?: number; + key: string; + metadata?: Record; + }; + scoring_details?: { + /** Keyword match score (0-1) */ + keyword_score?: number; + /** Vector similarity score (0-1) */ + vector_score?: number; + }; + }>; +}; +type AiSearchListResponse = Array<{ + id: string; + internal_id?: string; + account_id?: string; + account_tag?: string; + /** Whether the instance is enabled (default true) */ + enable?: boolean; + type?: 'r2' | 'web-crawler'; + source?: string; + [key: string]: unknown; +}>; +type AiSearchConfig = { + /** Instance ID (1-32 chars, pattern: ^[a-z0-9_]+(?:-[a-z0-9_]+)*$) */ + id: string; + type: 'r2' | 'web-crawler'; + source: string; + source_params?: object; + /** Token ID (UUID format) */ + token_id?: string; + ai_gateway_id?: string; + /** Enable query rewriting (default false) */ + rewrite_query?: boolean; + /** Enable reranking (default false) */ + reranking?: boolean; + embedding_model?: string; + ai_search_model?: string; +}; +type AiSearchInstance = { + id: string; + enable?: boolean; + type?: 'r2' | 'web-crawler'; + source?: string; + [key: string]: unknown; +}; +// AI Search Instance Service - Instance-level operations +declare abstract class AiSearchInstanceService { + /** + * Search the AI Search instance for relevant chunks. + * @param params Search request with messages and AI search options + * @returns Search response with matching chunks + */ + search(params: AiSearchSearchRequest): Promise; + /** + * Generate chat completions with AI Search context. + * @param params Chat completions request with optional streaming + * @returns Response object (if streaming) or chat completion result + */ + chatCompletions(params: AiSearchChatCompletionsRequest): Promise; + /** + * Delete this AI Search instance. + */ + delete(): Promise; +} +// AI Search Account Service - Account-level operations +declare abstract class AiSearchAccountService { + /** + * List all AI Search instances in the account. + * @returns Array of AI Search instances + */ + list(): Promise; + /** + * Get an AI Search instance by ID. + * @param name Instance ID + * @returns Instance service for performing operations + */ + get(name: string): AiSearchInstanceService; + /** + * Create a new AI Search instance. + * @param config Instance configuration + * @returns Instance service for performing operations + */ + create(config: AiSearchConfig): Promise; +} +type AiImageClassificationInput = { + image: number[]; +}; +type AiImageClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiImageClassification { + inputs: AiImageClassificationInput; + postProcessedOutputs: AiImageClassificationOutput; +} +type AiImageToTextInput = { + image: number[]; + prompt?: string; + max_tokens?: number; + temperature?: number; + top_p?: number; + top_k?: number; + seed?: number; + repetition_penalty?: number; + frequency_penalty?: number; + presence_penalty?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +type AiImageToTextOutput = { + description: string; +}; +declare abstract class BaseAiImageToText { + inputs: AiImageToTextInput; + postProcessedOutputs: AiImageToTextOutput; +} +type AiImageTextToTextInput = { + image: string; + prompt?: string; + max_tokens?: number; + temperature?: number; + ignore_eos?: boolean; + top_p?: number; + top_k?: number; + seed?: number; + repetition_penalty?: number; + frequency_penalty?: number; + presence_penalty?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +type AiImageTextToTextOutput = { + description: string; +}; +declare abstract class BaseAiImageTextToText { + inputs: AiImageTextToTextInput; + postProcessedOutputs: AiImageTextToTextOutput; +} +type AiMultimodalEmbeddingsInput = { + image: string; + text: string[]; +}; +type AiIMultimodalEmbeddingsOutput = { + data: number[][]; + shape: number[]; +}; +declare abstract class BaseAiMultimodalEmbeddings { + inputs: AiImageTextToTextInput; + postProcessedOutputs: AiImageTextToTextOutput; +} +type AiObjectDetectionInput = { + image: number[]; +}; +type AiObjectDetectionOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiObjectDetection { + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; +} +type AiSentenceSimilarityInput = { + source: string; + sentences: string[]; +}; +type AiSentenceSimilarityOutput = number[]; +declare abstract class BaseAiSentenceSimilarity { + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; +} +type AiAutomaticSpeechRecognitionInput = { + audio: number[]; +}; +type AiAutomaticSpeechRecognitionOutput = { + text?: string; + words?: { + word: string; + start: number; + end: number; + }[]; + vtt?: string; +}; +declare abstract class BaseAiAutomaticSpeechRecognition { + inputs: AiAutomaticSpeechRecognitionInput; + postProcessedOutputs: AiAutomaticSpeechRecognitionOutput; +} +type AiSummarizationInput = { + input_text: string; + max_length?: number; +}; +type AiSummarizationOutput = { + summary: string; +}; +declare abstract class BaseAiSummarization { + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; +} +type AiTextClassificationInput = { + text: string; +}; +type AiTextClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiTextClassification { + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; +} +type AiTextEmbeddingsInput = { + text: string | string[]; +}; +type AiTextEmbeddingsOutput = { + shape: number[]; + data: number[][]; +}; +declare abstract class BaseAiTextEmbeddings { + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; +} +type RoleScopedChatInput = { + role: 'user' | 'assistant' | 'system' | 'tool' | (string & NonNullable); + content: string; + name?: string; +}; +type AiTextGenerationToolLegacyInput = { + name: string; + description: string; + parameters?: { + type: 'object' | (string & NonNullable); + properties: { + [key: string]: { + type: string; + description?: string; + }; + }; + required: string[]; + }; +}; +type AiTextGenerationToolInput = { + type: 'function' | (string & NonNullable); + function: { + name: string; + description: string; + parameters?: { + type: 'object' | (string & NonNullable); + properties: { + [key: string]: { + type: string; + description?: string; + }; + }; + required: string[]; + }; + }; +}; +type AiTextGenerationFunctionsInput = { + name: string; + code: string; +}; +type AiTextGenerationResponseFormat = { + type: string; + json_schema?: any; +}; +type AiTextGenerationInput = { + prompt?: string; + raw?: boolean; + stream?: boolean; + max_tokens?: number; + temperature?: number; + top_p?: number; + top_k?: number; + seed?: number; + repetition_penalty?: number; + frequency_penalty?: number; + presence_penalty?: number; + messages?: RoleScopedChatInput[]; + response_format?: AiTextGenerationResponseFormat; + tools?: AiTextGenerationToolInput[] | AiTextGenerationToolLegacyInput[] | (object & NonNullable); + functions?: AiTextGenerationFunctionsInput[]; +}; +type AiTextGenerationToolLegacyOutput = { + name: string; + arguments: unknown; +}; +type AiTextGenerationToolOutput = { + id: string; + type: 'function'; + function: { + name: string; + arguments: string; + }; +}; +type UsageTags = { + prompt_tokens: number; + completion_tokens: number; + total_tokens: number; +}; +type AiTextGenerationOutput = { + response?: string; + tool_calls?: AiTextGenerationToolLegacyOutput[] & AiTextGenerationToolOutput[]; + usage?: UsageTags; +}; +declare abstract class BaseAiTextGeneration { + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; +} +type AiTextToSpeechInput = { + prompt: string; + lang?: string; +}; +type AiTextToSpeechOutput = + | Uint8Array + | { + audio: string; + }; +declare abstract class BaseAiTextToSpeech { + inputs: AiTextToSpeechInput; + postProcessedOutputs: AiTextToSpeechOutput; +} +type AiTextToImageInput = { + prompt: string; + negative_prompt?: string; + height?: number; + width?: number; + image?: number[]; + image_b64?: string; + mask?: number[]; + num_steps?: number; + strength?: number; + guidance?: number; + seed?: number; +}; +type AiTextToImageOutput = ReadableStream; +declare abstract class BaseAiTextToImage { + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; +} +type AiTranslationInput = { + text: string; + target_lang: string; + source_lang?: string; +}; +type AiTranslationOutput = { + translated_text?: string; +}; +declare abstract class BaseAiTranslation { + inputs: AiTranslationInput; + postProcessedOutputs: AiTranslationOutput; +} +/** + * Workers AI support for OpenAI's Responses API + * Reference: https://github.com/openai/openai-node/blob/master/src/resources/responses/responses.ts + * + * It's a stripped down version from its source. + * It currently supports basic function calling, json mode and accepts images as input. + * + * It does not include types for WebSearch, CodeInterpreter, FileInputs, MCP, CustomTools. + * We plan to add those incrementally as model + platform capabilities evolve. + */ +type ResponsesInput = { + background?: boolean | null; + conversation?: string | ResponseConversationParam | null; + include?: Array | null; + input?: string | ResponseInput; + instructions?: string | null; + max_output_tokens?: number | null; + parallel_tool_calls?: boolean | null; + previous_response_id?: string | null; + prompt_cache_key?: string; + reasoning?: Reasoning | null; + safety_identifier?: string; + service_tier?: 'auto' | 'default' | 'flex' | 'scale' | 'priority' | null; + stream?: boolean | null; + stream_options?: StreamOptions | null; + temperature?: number | null; + text?: ResponseTextConfig; + tool_choice?: ToolChoiceOptions | ToolChoiceFunction; + tools?: Array; + top_p?: number | null; + truncation?: 'auto' | 'disabled' | null; +}; +type ResponsesOutput = { + id?: string; + created_at?: number; + output_text?: string; + error?: ResponseError | null; + incomplete_details?: ResponseIncompleteDetails | null; + instructions?: string | Array | null; + object?: 'response'; + output?: Array; + parallel_tool_calls?: boolean; + temperature?: number | null; + tool_choice?: ToolChoiceOptions | ToolChoiceFunction; + tools?: Array; + top_p?: number | null; + max_output_tokens?: number | null; + previous_response_id?: string | null; + prompt?: ResponsePrompt | null; + reasoning?: Reasoning | null; + safety_identifier?: string; + service_tier?: 'auto' | 'default' | 'flex' | 'scale' | 'priority' | null; + status?: ResponseStatus; + text?: ResponseTextConfig; + truncation?: 'auto' | 'disabled' | null; + usage?: ResponseUsage; +}; +type EasyInputMessage = { + content: string | ResponseInputMessageContentList; + role: 'user' | 'assistant' | 'system' | 'developer'; + type?: 'message'; +}; +type ResponsesFunctionTool = { + name: string; + parameters: { + [key: string]: unknown; + } | null; + strict: boolean | null; + type: 'function'; + description?: string | null; +}; +type ResponseIncompleteDetails = { + reason?: 'max_output_tokens' | 'content_filter'; +}; +type ResponsePrompt = { + id: string; + variables?: { + [key: string]: string | ResponseInputText | ResponseInputImage; + } | null; + version?: string | null; +}; +type Reasoning = { + effort?: ReasoningEffort | null; + generate_summary?: 'auto' | 'concise' | 'detailed' | null; + summary?: 'auto' | 'concise' | 'detailed' | null; +}; +type ResponseContent = + | ResponseInputText + | ResponseInputImage + | ResponseOutputText + | ResponseOutputRefusal + | ResponseContentReasoningText; +type ResponseContentReasoningText = { + text: string; + type: 'reasoning_text'; +}; +type ResponseConversationParam = { + id: string; +}; +type ResponseCreatedEvent = { + response: Response; + sequence_number: number; + type: 'response.created'; +}; +type ResponseCustomToolCallOutput = { + call_id: string; + output: string | Array; + type: 'custom_tool_call_output'; + id?: string; +}; +type ResponseError = { + code: + | 'server_error' + | 'rate_limit_exceeded' + | 'invalid_prompt' + | 'vector_store_timeout' + | 'invalid_image' + | 'invalid_image_format' + | 'invalid_base64_image' + | 'invalid_image_url' + | 'image_too_large' + | 'image_too_small' + | 'image_parse_error' + | 'image_content_policy_violation' + | 'invalid_image_mode' + | 'image_file_too_large' + | 'unsupported_image_media_type' + | 'empty_image_file' + | 'failed_to_download_image' + | 'image_file_not_found'; + message: string; +}; +type ResponseErrorEvent = { + code: string | null; + message: string; + param: string | null; + sequence_number: number; + type: 'error'; +}; +type ResponseFailedEvent = { + response: Response; + sequence_number: number; + type: 'response.failed'; +}; +type ResponseFormatText = { + type: 'text'; +}; +type ResponseFormatJSONObject = { + type: 'json_object'; +}; +type ResponseFormatTextConfig = ResponseFormatText | ResponseFormatTextJSONSchemaConfig | ResponseFormatJSONObject; +type ResponseFormatTextJSONSchemaConfig = { + name: string; + schema: { + [key: string]: unknown; + }; + type: 'json_schema'; + description?: string; + strict?: boolean | null; +}; +type ResponseFunctionCallArgumentsDeltaEvent = { + delta: string; + item_id: string; + output_index: number; + sequence_number: number; + type: 'response.function_call_arguments.delta'; +}; +type ResponseFunctionCallArgumentsDoneEvent = { + arguments: string; + item_id: string; + name: string; + output_index: number; + sequence_number: number; + type: 'response.function_call_arguments.done'; +}; +type ResponseFunctionCallOutputItem = ResponseInputTextContent | ResponseInputImageContent; +type ResponseFunctionCallOutputItemList = Array; +type ResponseFunctionToolCall = { + arguments: string; + call_id: string; + name: string; + type: 'function_call'; + id?: string; + status?: 'in_progress' | 'completed' | 'incomplete'; +}; +interface ResponseFunctionToolCallItem extends ResponseFunctionToolCall { + id: string; +} +type ResponseFunctionToolCallOutputItem = { + id: string; + call_id: string; + output: string | Array; + type: 'function_call_output'; + status?: 'in_progress' | 'completed' | 'incomplete'; +}; +type ResponseIncludable = 'message.input_image.image_url' | 'message.output_text.logprobs'; +type ResponseIncompleteEvent = { + response: Response; + sequence_number: number; + type: 'response.incomplete'; +}; +type ResponseInput = Array; +type ResponseInputContent = ResponseInputText | ResponseInputImage; +type ResponseInputImage = { + detail: 'low' | 'high' | 'auto'; + type: 'input_image'; + /** + * Base64 encoded image + */ + image_url?: string | null; +}; +type ResponseInputImageContent = { + type: 'input_image'; + detail?: 'low' | 'high' | 'auto' | null; + /** + * Base64 encoded image + */ + image_url?: string | null; +}; +type ResponseInputItem = + | EasyInputMessage + | ResponseInputItemMessage + | ResponseOutputMessage + | ResponseFunctionToolCall + | ResponseInputItemFunctionCallOutput + | ResponseReasoningItem; +type ResponseInputItemFunctionCallOutput = { + call_id: string; + output: string | ResponseFunctionCallOutputItemList; + type: 'function_call_output'; + id?: string | null; + status?: 'in_progress' | 'completed' | 'incomplete' | null; +}; +type ResponseInputItemMessage = { + content: ResponseInputMessageContentList; + role: 'user' | 'system' | 'developer'; + status?: 'in_progress' | 'completed' | 'incomplete'; + type?: 'message'; +}; +type ResponseInputMessageContentList = Array; +type ResponseInputMessageItem = { + id: string; + content: ResponseInputMessageContentList; + role: 'user' | 'system' | 'developer'; + status?: 'in_progress' | 'completed' | 'incomplete'; + type?: 'message'; +}; +type ResponseInputText = { + text: string; + type: 'input_text'; +}; +type ResponseInputTextContent = { + text: string; + type: 'input_text'; +}; +type ResponseItem = + | ResponseInputMessageItem + | ResponseOutputMessage + | ResponseFunctionToolCallItem + | ResponseFunctionToolCallOutputItem; +type ResponseOutputItem = ResponseOutputMessage | ResponseFunctionToolCall | ResponseReasoningItem; +type ResponseOutputItemAddedEvent = { + item: ResponseOutputItem; + output_index: number; + sequence_number: number; + type: 'response.output_item.added'; +}; +type ResponseOutputItemDoneEvent = { + item: ResponseOutputItem; + output_index: number; + sequence_number: number; + type: 'response.output_item.done'; +}; +type ResponseOutputMessage = { + id: string; + content: Array; + role: 'assistant'; + status: 'in_progress' | 'completed' | 'incomplete'; + type: 'message'; +}; +type ResponseOutputRefusal = { + refusal: string; + type: 'refusal'; +}; +type ResponseOutputText = { + text: string; + type: 'output_text'; + logprobs?: Array; +}; +type ResponseReasoningItem = { + id: string; + summary: Array; + type: 'reasoning'; + content?: Array; + encrypted_content?: string | null; + status?: 'in_progress' | 'completed' | 'incomplete'; +}; +type ResponseReasoningSummaryItem = { + text: string; + type: 'summary_text'; +}; +type ResponseReasoningContentItem = { + text: string; + type: 'reasoning_text'; +}; +type ResponseReasoningTextDeltaEvent = { + content_index: number; + delta: string; + item_id: string; + output_index: number; + sequence_number: number; + type: 'response.reasoning_text.delta'; +}; +type ResponseReasoningTextDoneEvent = { + content_index: number; + item_id: string; + output_index: number; + sequence_number: number; + text: string; + type: 'response.reasoning_text.done'; +}; +type ResponseRefusalDeltaEvent = { + content_index: number; + delta: string; + item_id: string; + output_index: number; + sequence_number: number; + type: 'response.refusal.delta'; +}; +type ResponseRefusalDoneEvent = { + content_index: number; + item_id: string; + output_index: number; + refusal: string; + sequence_number: number; + type: 'response.refusal.done'; +}; +type ResponseStatus = 'completed' | 'failed' | 'in_progress' | 'cancelled' | 'queued' | 'incomplete'; +type ResponseStreamEvent = + | ResponseCompletedEvent + | ResponseCreatedEvent + | ResponseErrorEvent + | ResponseFunctionCallArgumentsDeltaEvent + | ResponseFunctionCallArgumentsDoneEvent + | ResponseFailedEvent + | ResponseIncompleteEvent + | ResponseOutputItemAddedEvent + | ResponseOutputItemDoneEvent + | ResponseReasoningTextDeltaEvent + | ResponseReasoningTextDoneEvent + | ResponseRefusalDeltaEvent + | ResponseRefusalDoneEvent + | ResponseTextDeltaEvent + | ResponseTextDoneEvent; +type ResponseCompletedEvent = { + response: Response; + sequence_number: number; + type: 'response.completed'; +}; +type ResponseTextConfig = { + format?: ResponseFormatTextConfig; + verbosity?: 'low' | 'medium' | 'high' | null; +}; +type ResponseTextDeltaEvent = { + content_index: number; + delta: string; + item_id: string; + logprobs: Array; + output_index: number; + sequence_number: number; + type: 'response.output_text.delta'; +}; +type ResponseTextDoneEvent = { + content_index: number; + item_id: string; + logprobs: Array; + output_index: number; + sequence_number: number; + text: string; + type: 'response.output_text.done'; +}; +type Logprob = { + token: string; + logprob: number; + top_logprobs?: Array; +}; +type TopLogprob = { + token?: string; + logprob?: number; +}; +type ResponseUsage = { + input_tokens: number; + output_tokens: number; + total_tokens: number; +}; +type Tool = ResponsesFunctionTool; +type ToolChoiceFunction = { + name: string; + type: 'function'; +}; +type ToolChoiceOptions = 'none'; +type ReasoningEffort = 'minimal' | 'low' | 'medium' | 'high' | null; +type StreamOptions = { + include_obfuscation?: boolean; +}; +type Ai_Cf_Baai_Bge_Base_En_V1_5_Input = + | { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: 'mean' | 'cls'; + } + | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: 'mean' | 'cls'; + }[]; + }; +type Ai_Cf_Baai_Bge_Base_En_V1_5_Output = + | { + shape?: number[]; + /** + * Embeddings of the requested text values + */ + data?: number[][]; + /** + * The pooling method used in the embedding process. + */ + pooling?: 'mean' | 'cls'; + } + | Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse; +interface Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Baai_Bge_Base_En_V1_5 { + inputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Output; +} +type Ai_Cf_Openai_Whisper_Input = + | string + | { + /** + * An array of integers that represent the audio data constrained to 8-bit unsigned integer values + */ + audio: number[]; + }; +interface Ai_Cf_Openai_Whisper_Output { + /** + * The transcription + */ + text: string; + word_count?: number; + words?: { + word?: string; + /** + * The second this word begins in the recording + */ + start?: number; + /** + * The ending second when the word completes + */ + end?: number; + }[]; + vtt?: string; +} +declare abstract class Base_Ai_Cf_Openai_Whisper { + inputs: Ai_Cf_Openai_Whisper_Input; + postProcessedOutputs: Ai_Cf_Openai_Whisper_Output; +} +type Ai_Cf_Meta_M2M100_1_2B_Input = + | { + /** + * The text to be translated + */ + text: string; + /** + * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified + */ + source_lang?: string; + /** + * The language code to translate the text into (e.g., 'es' for Spanish) + */ + target_lang: string; + } + | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { + /** + * The text to be translated + */ + text: string; + /** + * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified + */ + source_lang?: string; + /** + * The language code to translate the text into (e.g., 'es' for Spanish) + */ + target_lang: string; + }[]; + }; +type Ai_Cf_Meta_M2M100_1_2B_Output = + | { + /** + * The translated text in the target language + */ + translated_text?: string; + } + | Ai_Cf_Meta_M2M100_1_2B_AsyncResponse; +interface Ai_Cf_Meta_M2M100_1_2B_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Meta_M2M100_1_2B { + inputs: Ai_Cf_Meta_M2M100_1_2B_Input; + postProcessedOutputs: Ai_Cf_Meta_M2M100_1_2B_Output; +} +type Ai_Cf_Baai_Bge_Small_En_V1_5_Input = + | { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: 'mean' | 'cls'; + } + | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: 'mean' | 'cls'; + }[]; + }; +type Ai_Cf_Baai_Bge_Small_En_V1_5_Output = + | { + shape?: number[]; + /** + * Embeddings of the requested text values + */ + data?: number[][]; + /** + * The pooling method used in the embedding process. + */ + pooling?: 'mean' | 'cls'; + } + | Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse; +interface Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Baai_Bge_Small_En_V1_5 { + inputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Output; +} +type Ai_Cf_Baai_Bge_Large_En_V1_5_Input = + | { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: 'mean' | 'cls'; + } + | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: 'mean' | 'cls'; + }[]; + }; +type Ai_Cf_Baai_Bge_Large_En_V1_5_Output = + | { + shape?: number[]; + /** + * Embeddings of the requested text values + */ + data?: number[][]; + /** + * The pooling method used in the embedding process. + */ + pooling?: 'mean' | 'cls'; + } + | Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse; +interface Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Baai_Bge_Large_En_V1_5 { + inputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Output; +} +type Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input = + | string + | { + /** + * The input text prompt for the model to generate a response. + */ + prompt?: string; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; + image: number[] | (string & NonNullable); + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + }; +interface Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output { + description?: string; +} +declare abstract class Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M { + inputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input; + postProcessedOutputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output; +} +type Ai_Cf_Openai_Whisper_Tiny_En_Input = + | string + | { + /** + * An array of integers that represent the audio data constrained to 8-bit unsigned integer values + */ + audio: number[]; + }; +interface Ai_Cf_Openai_Whisper_Tiny_En_Output { + /** + * The transcription + */ + text: string; + word_count?: number; + words?: { + word?: string; + /** + * The second this word begins in the recording + */ + start?: number; + /** + * The ending second when the word completes + */ + end?: number; + }[]; + vtt?: string; +} +declare abstract class Base_Ai_Cf_Openai_Whisper_Tiny_En { + inputs: Ai_Cf_Openai_Whisper_Tiny_En_Input; + postProcessedOutputs: Ai_Cf_Openai_Whisper_Tiny_En_Output; +} +interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input { + /** + * Base64 encoded value of the audio data. + */ + audio: string; + /** + * Supported tasks are 'translate' or 'transcribe'. + */ + task?: string; + /** + * The language of the audio being transcribed or translated. + */ + language?: string; + /** + * Preprocess the audio with a voice activity detection model. + */ + vad_filter?: boolean; + /** + * A text prompt to help provide context to the model on the contents of the audio. + */ + initial_prompt?: string; + /** + * The prefix it appended the the beginning of the output of the transcription and can guide the transcription result. + */ + prefix?: string; +} +interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output { + transcription_info?: { + /** + * The language of the audio being transcribed or translated. + */ + language?: string; + /** + * The confidence level or probability of the detected language being accurate, represented as a decimal between 0 and 1. + */ + language_probability?: number; + /** + * The total duration of the original audio file, in seconds. + */ + duration?: number; + /** + * The duration of the audio after applying Voice Activity Detection (VAD) to remove silent or irrelevant sections, in seconds. + */ + duration_after_vad?: number; + }; + /** + * The complete transcription of the audio. + */ + text: string; + /** + * The total number of words in the transcription. + */ + word_count?: number; + segments?: { + /** + * The starting time of the segment within the audio, in seconds. + */ + start?: number; + /** + * The ending time of the segment within the audio, in seconds. + */ + end?: number; + /** + * The transcription of the segment. + */ + text?: string; + /** + * The temperature used in the decoding process, controlling randomness in predictions. Lower values result in more deterministic outputs. + */ + temperature?: number; + /** + * The average log probability of the predictions for the words in this segment, indicating overall confidence. + */ + avg_logprob?: number; + /** + * The compression ratio of the input to the output, measuring how much the text was compressed during the transcription process. + */ + compression_ratio?: number; + /** + * The probability that the segment contains no speech, represented as a decimal between 0 and 1. + */ + no_speech_prob?: number; + words?: { + /** + * The individual word transcribed from the audio. + */ + word?: string; + /** + * The starting time of the word within the audio, in seconds. + */ + start?: number; + /** + * The ending time of the word within the audio, in seconds. + */ + end?: number; + }[]; + }[]; + /** + * The transcription in WebVTT format, which includes timing and text information for use in subtitles. + */ + vtt?: string; +} +declare abstract class Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo { + inputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input; + postProcessedOutputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output; +} +type Ai_Cf_Baai_Bge_M3_Input = + | Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts + | Ai_Cf_Baai_Bge_M3_Input_Embedding + | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: (Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 | Ai_Cf_Baai_Bge_M3_Input_Embedding_1)[]; + }; +interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts { + /** + * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts + */ + query?: string; + /** + * List of provided contexts. Note that the index in this array is important, as the response will refer to it. + */ + contexts: { + /** + * One of the provided context content + */ + text?: string; + }[]; + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean; +} +interface Ai_Cf_Baai_Bge_M3_Input_Embedding { + text: string | string[]; + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean; +} +interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 { + /** + * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts + */ + query?: string; + /** + * List of provided contexts. Note that the index in this array is important, as the response will refer to it. + */ + contexts: { + /** + * One of the provided context content + */ + text?: string; + }[]; + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean; +} +interface Ai_Cf_Baai_Bge_M3_Input_Embedding_1 { + text: string | string[]; + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean; +} +type Ai_Cf_Baai_Bge_M3_Output = + | Ai_Cf_Baai_Bge_M3_Ouput_Query + | Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts + | Ai_Cf_Baai_Bge_M3_Ouput_Embedding + | Ai_Cf_Baai_Bge_M3_AsyncResponse; +interface Ai_Cf_Baai_Bge_M3_Ouput_Query { + response?: { + /** + * Index of the context in the request + */ + id?: number; + /** + * Score of the context under the index. + */ + score?: number; + }[]; +} +interface Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts { + response?: number[][]; + shape?: number[]; + /** + * The pooling method used in the embedding process. + */ + pooling?: 'mean' | 'cls'; +} +interface Ai_Cf_Baai_Bge_M3_Ouput_Embedding { + shape?: number[]; + /** + * Embeddings of the requested text values + */ + data?: number[][]; + /** + * The pooling method used in the embedding process. + */ + pooling?: 'mean' | 'cls'; +} +interface Ai_Cf_Baai_Bge_M3_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Baai_Bge_M3 { + inputs: Ai_Cf_Baai_Bge_M3_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_M3_Output; +} +interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input { + /** + * A text description of the image you want to generate. + */ + prompt: string; + /** + * The number of diffusion steps; higher values can improve quality but take longer. + */ + steps?: number; +} +interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output { + /** + * The generated image in Base64 format. + */ + image?: string; +} +declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell { + inputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input; + postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output; +} +type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input = + | Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt + | Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages; +interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + image?: number[] | (string & NonNullable); + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; +} +interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + /** + * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: + | string + | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] + | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + image?: number[] | (string & NonNullable); + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ( + | { + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } + | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + } + )[]; + /** + * If true, the response will be streamed back incrementally. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output = { + /** + * The generated text response from the model + */ + response?: string; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +}; +declare abstract class Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct { + inputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input; + postProcessedOutputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output; +} +type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input = + | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt + | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages + | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch; +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode { + type?: 'json_object' | 'json_schema'; + json_schema?: unknown; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ( + | { + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } + | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + } + )[]; + response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1 { + type?: 'json_object' | 'json_schema'; + json_schema?: unknown; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch { + requests?: { + /** + * User-supplied reference. This field will be present in the response as well it can be used to reference the request and response. It's NOT validated to be unique. + */ + external_reference?: string; + /** + * Prompt for the text generation model + */ + prompt?: string; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; + response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2; + }[]; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2 { + type?: 'json_object' | 'json_schema'; + json_schema?: unknown; +} +type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = + | { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; + } + | string + | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse; +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast { + inputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input; + postProcessedOutputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output; +} +interface Ai_Cf_Meta_Llama_Guard_3_8B_Input { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender must alternate between 'user' and 'assistant'. + */ + role: 'user' | 'assistant'; + /** + * The content of the message as a string. + */ + content: string; + }[]; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Dictate the output format of the generated response. + */ + response_format?: { + /** + * Set to json_object to process and output generated text as JSON. + */ + type?: string; + }; +} +interface Ai_Cf_Meta_Llama_Guard_3_8B_Output { + response?: + | string + | { + /** + * Whether the conversation is safe or not. + */ + safe?: boolean; + /** + * A list of what hazard categories predicted for the conversation, if the conversation is deemed unsafe. + */ + categories?: string[]; + }; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; +} +declare abstract class Base_Ai_Cf_Meta_Llama_Guard_3_8B { + inputs: Ai_Cf_Meta_Llama_Guard_3_8B_Input; + postProcessedOutputs: Ai_Cf_Meta_Llama_Guard_3_8B_Output; +} +interface Ai_Cf_Baai_Bge_Reranker_Base_Input { + /** + * A query you wish to perform against the provided contexts. + */ + /** + * Number of returned results starting with the best score. + */ + top_k?: number; + /** + * List of provided contexts. Note that the index in this array is important, as the response will refer to it. + */ + contexts: { + /** + * One of the provided context content + */ + text?: string; + }[]; +} +interface Ai_Cf_Baai_Bge_Reranker_Base_Output { + response?: { + /** + * Index of the context in the request + */ + id?: number; + /** + * Score of the context under the index. + */ + score?: number; + }[]; +} +declare abstract class Base_Ai_Cf_Baai_Bge_Reranker_Base { + inputs: Ai_Cf_Baai_Bge_Reranker_Base_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_Reranker_Base_Output; +} +type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input = + | Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt + | Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages; +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode { + type?: 'json_object' | 'json_schema'; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ( + | { + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } + | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + } + )[]; + response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1 { + type?: 'json_object' | 'json_schema'; + json_schema?: unknown; +} +type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +}; +declare abstract class Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct { + inputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output; +} +type Ai_Cf_Qwen_Qwq_32B_Input = Ai_Cf_Qwen_Qwq_32B_Prompt | Ai_Cf_Qwen_Qwq_32B_Messages; +interface Ai_Cf_Qwen_Qwq_32B_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwq_32B_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + /** + * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: + | string + | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] + | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ( + | { + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } + | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + } + )[]; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +type Ai_Cf_Qwen_Qwq_32B_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +}; +declare abstract class Base_Ai_Cf_Qwen_Qwq_32B { + inputs: Ai_Cf_Qwen_Qwq_32B_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwq_32B_Output; +} +type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input = + | Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt + | Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages; +interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + /** + * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: + | string + | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] + | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ( + | { + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } + | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + } + )[]; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +}; +declare abstract class Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct { + inputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input; + postProcessedOutputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output; +} +type Ai_Cf_Google_Gemma_3_12B_It_Input = Ai_Cf_Google_Gemma_3_12B_It_Prompt | Ai_Cf_Google_Gemma_3_12B_It_Messages; +interface Ai_Cf_Google_Gemma_3_12B_It_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Google_Gemma_3_12B_It_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + content?: + | string + | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[]; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ( + | { + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } + | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + } + )[]; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +type Ai_Cf_Google_Gemma_3_12B_It_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +}; +declare abstract class Base_Ai_Cf_Google_Gemma_3_12B_It { + inputs: Ai_Cf_Google_Gemma_3_12B_It_Input; + postProcessedOutputs: Ai_Cf_Google_Gemma_3_12B_It_Output; +} +type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input = + | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt + | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages + | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch; +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode { + type?: 'json_object' | 'json_schema'; + json_schema?: unknown; +} +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + /** + * The tool call id. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: + | string + | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] + | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ( + | { + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } + | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + } + )[]; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch { + requests: ( + | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner + | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner + )[]; +} +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + /** + * The tool call id. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: + | string + | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] + | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ( + | { + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } + | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + } + )[]; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The tool call id. + */ + id?: string; + /** + * Specifies the type of tool (e.g., 'function'). + */ + type?: string; + /** + * Details of the function tool. + */ + function?: { + /** + * The name of the tool to be called + */ + name?: string; + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + }; + }[]; +}; +declare abstract class Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct { + inputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input; + postProcessedOutputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output; +} +type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input = + | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt + | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages + | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch; +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode { + type?: 'json_object' | 'json_schema'; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ( + | { + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } + | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + } + )[]; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1 { + type?: 'json_object' | 'json_schema'; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch { + requests: (Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1)[]; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2 { + type?: 'json_object' | 'json_schema'; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1 { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ( + | { + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } + | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + } + )[]; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3 { + type?: 'json_object' | 'json_schema'; + json_schema?: unknown; +} +type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output = + | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response + | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response + | string + | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse; +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: 'chat.completion'; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index?: number; + /** + * The message generated by the model + */ + message?: { + /** + * Role of the message author + */ + role: string; + /** + * The content of the message + */ + content: string; + /** + * Internal reasoning content (if available) + */ + reasoning_content?: string; + /** + * Tool calls made by the assistant + */ + tool_calls?: { + /** + * Unique identifier for the tool call + */ + id: string; + /** + * Type of tool call + */ + type: 'function'; + function: { + /** + * Name of the function to call + */ + name: string; + /** + * JSON string of arguments for the function + */ + arguments: string; + }; + }[]; + }; + /** + * Reason why the model stopped generating + */ + finish_reason?: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: 'text_completion'; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index: number; + /** + * The generated text completion + */ + text: string; + /** + * Reason why the model stopped generating + */ + finish_reason: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8 { + inputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output; +} +interface Ai_Cf_Deepgram_Nova_3_Input { + audio: { + body: object; + contentType: string; + }; + /** + * Sets how the model will interpret strings submitted to the custom_topic param. When strict, the model will only return topics submitted using the custom_topic param. When extended, the model will return its own detected topics in addition to those submitted using the custom_topic param. + */ + custom_topic_mode?: 'extended' | 'strict'; + /** + * Custom topics you want the model to detect within your input audio or text if present Submit up to 100 + */ + custom_topic?: string; + /** + * Sets how the model will interpret intents submitted to the custom_intent param. When strict, the model will only return intents submitted using the custom_intent param. When extended, the model will return its own detected intents in addition those submitted using the custom_intents param + */ + custom_intent_mode?: 'extended' | 'strict'; + /** + * Custom intents you want the model to detect within your input audio if present + */ + custom_intent?: string; + /** + * Identifies and extracts key entities from content in submitted audio + */ + detect_entities?: boolean; + /** + * Identifies the dominant language spoken in submitted audio + */ + detect_language?: boolean; + /** + * Recognize speaker changes. Each word in the transcript will be assigned a speaker number starting at 0 + */ + diarize?: boolean; + /** + * Identify and extract key entities from content in submitted audio + */ + dictation?: boolean; + /** + * Specify the expected encoding of your submitted audio + */ + encoding?: 'linear16' | 'flac' | 'mulaw' | 'amr-nb' | 'amr-wb' | 'opus' | 'speex' | 'g729'; + /** + * Arbitrary key-value pairs that are attached to the API response for usage in downstream processing + */ + extra?: string; + /** + * Filler Words can help transcribe interruptions in your audio, like 'uh' and 'um' + */ + filler_words?: boolean; + /** + * Key term prompting can boost or suppress specialized terminology and brands. + */ + keyterm?: string; + /** + * Keywords can boost or suppress specialized terminology and brands. + */ + keywords?: string; + /** + * The BCP-47 language tag that hints at the primary spoken language. Depending on the Model and API endpoint you choose only certain languages are available. + */ + language?: string; + /** + * Spoken measurements will be converted to their corresponding abbreviations. + */ + measurements?: boolean; + /** + * Opts out requests from the Deepgram Model Improvement Program. Refer to our Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip. + */ + mip_opt_out?: boolean; + /** + * Mode of operation for the model representing broad area of topic that will be talked about in the supplied audio + */ + mode?: 'general' | 'medical' | 'finance'; + /** + * Transcribe each audio channel independently. + */ + multichannel?: boolean; + /** + * Numerals converts numbers from written format to numerical format. + */ + numerals?: boolean; + /** + * Splits audio into paragraphs to improve transcript readability. + */ + paragraphs?: boolean; + /** + * Profanity Filter looks for recognized profanity and converts it to the nearest recognized non-profane word or removes it from the transcript completely. + */ + profanity_filter?: boolean; + /** + * Add punctuation and capitalization to the transcript. + */ + punctuate?: boolean; + /** + * Redaction removes sensitive information from your transcripts. + */ + redact?: string; + /** + * Search for terms or phrases in submitted audio and replaces them. + */ + replace?: string; + /** + * Search for terms or phrases in submitted audio. + */ + search?: string; + /** + * Recognizes the sentiment throughout a transcript or text. + */ + sentiment?: boolean; + /** + * Apply formatting to transcript output. When set to true, additional formatting will be applied to transcripts to improve readability. + */ + smart_format?: boolean; + /** + * Detect topics throughout a transcript or text. + */ + topics?: boolean; + /** + * Segments speech into meaningful semantic units. + */ + utterances?: boolean; + /** + * Seconds to wait before detecting a pause between words in submitted audio. + */ + utt_split?: number; + /** + * The number of channels in the submitted audio + */ + channels?: number; + /** + * Specifies whether the streaming endpoint should provide ongoing transcription updates as more audio is received. When set to true, the endpoint sends continuous updates, meaning transcription results may evolve over time. Note: Supported only for webosockets. + */ + interim_results?: boolean; + /** + * Indicates how long model will wait to detect whether a speaker has finished speaking or pauses for a significant period of time. When set to a value, the streaming endpoint immediately finalizes the transcription for the processed time range and returns the transcript with a speech_final parameter set to true. Can also be set to false to disable endpointing + */ + endpointing?: string; + /** + * Indicates that speech has started. You'll begin receiving Speech Started messages upon speech starting. Note: Supported only for webosockets. + */ + vad_events?: boolean; + /** + * Indicates how long model will wait to send an UtteranceEnd message after a word has been transcribed. Use with interim_results. Note: Supported only for webosockets. + */ + utterance_end_ms?: boolean; +} +interface Ai_Cf_Deepgram_Nova_3_Output { + results?: { + channels?: { + alternatives?: { + confidence?: number; + transcript?: string; + words?: { + confidence?: number; + end?: number; + start?: number; + word?: string; + }[]; + }[]; + }[]; + summary?: { + result?: string; + short?: string; + }; + sentiments?: { + segments?: { + text?: string; + start_word?: number; + end_word?: number; + sentiment?: string; + sentiment_score?: number; + }[]; + average?: { + sentiment?: string; + sentiment_score?: number; + }; + }; + }; +} +declare abstract class Base_Ai_Cf_Deepgram_Nova_3 { + inputs: Ai_Cf_Deepgram_Nova_3_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Nova_3_Output; +} +interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input { + queries?: string | string[]; + /** + * Optional instruction for the task + */ + instruction?: string; + documents?: string | string[]; + text?: string | string[]; +} +interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output { + data?: number[][]; + shape?: number[]; +} +declare abstract class Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B { + inputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output; +} +type Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input = + | { + /** + * readable stream with audio data and content-type specified for that data + */ + audio: { + body: object; + contentType: string; + }; + /** + * type of data PCM data that's sent to the inference server as raw array + */ + dtype?: 'uint8' | 'float32' | 'float64'; + } + | { + /** + * base64 encoded audio data + */ + audio: string; + /** + * type of data PCM data that's sent to the inference server as raw array + */ + dtype?: 'uint8' | 'float32' | 'float64'; + }; +interface Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output { + /** + * if true, end-of-turn was detected + */ + is_complete?: boolean; + /** + * probability of the end-of-turn detection + */ + probability?: number; +} +declare abstract class Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2 { + inputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input; + postProcessedOutputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output; +} +declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_120B { + inputs: ResponsesInput; + postProcessedOutputs: ResponsesOutput; +} +declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_20B { + inputs: ResponsesInput; + postProcessedOutputs: ResponsesOutput; +} +interface Ai_Cf_Leonardo_Phoenix_1_0_Input { + /** + * A text description of the image you want to generate. + */ + prompt: string; + /** + * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt + */ + guidance?: number; + /** + * Random seed for reproducibility of the image generation + */ + seed?: number; + /** + * The height of the generated image in pixels + */ + height?: number; + /** + * The width of the generated image in pixels + */ + width?: number; + /** + * The number of diffusion steps; higher values can improve quality but take longer + */ + num_steps?: number; + /** + * Specify what to exclude from the generated images + */ + negative_prompt?: string; +} +/** + * The generated image in JPEG format + */ +type Ai_Cf_Leonardo_Phoenix_1_0_Output = string; +declare abstract class Base_Ai_Cf_Leonardo_Phoenix_1_0 { + inputs: Ai_Cf_Leonardo_Phoenix_1_0_Input; + postProcessedOutputs: Ai_Cf_Leonardo_Phoenix_1_0_Output; +} +interface Ai_Cf_Leonardo_Lucid_Origin_Input { + /** + * A text description of the image you want to generate. + */ + prompt: string; + /** + * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt + */ + guidance?: number; + /** + * Random seed for reproducibility of the image generation + */ + seed?: number; + /** + * The height of the generated image in pixels + */ + height?: number; + /** + * The width of the generated image in pixels + */ + width?: number; + /** + * The number of diffusion steps; higher values can improve quality but take longer + */ + num_steps?: number; + /** + * The number of diffusion steps; higher values can improve quality but take longer + */ + steps?: number; +} +interface Ai_Cf_Leonardo_Lucid_Origin_Output { + /** + * The generated image in Base64 format. + */ + image?: string; +} +declare abstract class Base_Ai_Cf_Leonardo_Lucid_Origin { + inputs: Ai_Cf_Leonardo_Lucid_Origin_Input; + postProcessedOutputs: Ai_Cf_Leonardo_Lucid_Origin_Output; +} +interface Ai_Cf_Deepgram_Aura_1_Input { + /** + * Speaker used to produce the audio. + */ + speaker?: + | 'angus' + | 'asteria' + | 'arcas' + | 'orion' + | 'orpheus' + | 'athena' + | 'luna' + | 'zeus' + | 'perseus' + | 'helios' + | 'hera' + | 'stella'; + /** + * Encoding of the output audio. + */ + encoding?: 'linear16' | 'flac' | 'mulaw' | 'alaw' | 'mp3' | 'opus' | 'aac'; + /** + * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. + */ + container?: 'none' | 'wav' | 'ogg'; + /** + * The text content to be converted to speech + */ + text: string; + /** + * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable + */ + sample_rate?: number; + /** + * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. + */ + bit_rate?: number; +} +/** + * The generated audio in MP3 format + */ +type Ai_Cf_Deepgram_Aura_1_Output = string; +declare abstract class Base_Ai_Cf_Deepgram_Aura_1 { + inputs: Ai_Cf_Deepgram_Aura_1_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Aura_1_Output; +} +interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input { + /** + * Input text to translate. Can be a single string or a list of strings. + */ + text: string | string[]; + /** + * Target language to translate to + */ + target_language: + | 'asm_Beng' + | 'awa_Deva' + | 'ben_Beng' + | 'bho_Deva' + | 'brx_Deva' + | 'doi_Deva' + | 'eng_Latn' + | 'gom_Deva' + | 'gon_Deva' + | 'guj_Gujr' + | 'hin_Deva' + | 'hne_Deva' + | 'kan_Knda' + | 'kas_Arab' + | 'kas_Deva' + | 'kha_Latn' + | 'lus_Latn' + | 'mag_Deva' + | 'mai_Deva' + | 'mal_Mlym' + | 'mar_Deva' + | 'mni_Beng' + | 'mni_Mtei' + | 'npi_Deva' + | 'ory_Orya' + | 'pan_Guru' + | 'san_Deva' + | 'sat_Olck' + | 'snd_Arab' + | 'snd_Deva' + | 'tam_Taml' + | 'tel_Telu' + | 'urd_Arab' + | 'unr_Deva'; +} +interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output { + /** + * Translated texts + */ + translations: string[]; +} +declare abstract class Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B { + inputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input; + postProcessedOutputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output; +} +type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input = + | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt + | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages + | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch; +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode { + type?: 'json_object' | 'json_schema'; + json_schema?: unknown; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ( + | { + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } + | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + } + )[]; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1 { + type?: 'json_object' | 'json_schema'; + json_schema?: unknown; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch { + requests: ( + | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 + | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1 + )[]; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2 { + type?: 'json_object' | 'json_schema'; + json_schema?: unknown; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1 { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ( + | { + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } + | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + } + )[]; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3 { + type?: 'json_object' | 'json_schema'; + json_schema?: unknown; +} +type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output = + | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response + | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response + | string + | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse; +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: 'chat.completion'; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index?: number; + /** + * The message generated by the model + */ + message?: { + /** + * Role of the message author + */ + role: string; + /** + * The content of the message + */ + content: string; + /** + * Internal reasoning content (if available) + */ + reasoning_content?: string; + /** + * Tool calls made by the assistant + */ + tool_calls?: { + /** + * Unique identifier for the tool call + */ + id: string; + /** + * Type of tool call + */ + type: 'function'; + function: { + /** + * Name of the function to call + */ + name: string; + /** + * JSON string of arguments for the function + */ + arguments: string; + }; + }[]; + }; + /** + * Reason why the model stopped generating + */ + finish_reason?: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: 'text_completion'; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index: number; + /** + * The generated text completion + */ + text: string; + /** + * Reason why the model stopped generating + */ + finish_reason: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It { + inputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input; + postProcessedOutputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output; +} +interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Input { + /** + * Input text to embed. Can be a single string or a list of strings. + */ + text: string | string[]; +} +interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Output { + /** + * Embedding vectors, where each vector is a list of floats. + */ + data: number[][]; + /** + * Shape of the embedding data as [number_of_embeddings, embedding_dimension]. + * + * @minItems 2 + * @maxItems 2 + */ + shape: [number, number]; +} +declare abstract class Base_Ai_Cf_Pfnet_Plamo_Embedding_1B { + inputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Input; + postProcessedOutputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Output; +} +interface Ai_Cf_Deepgram_Flux_Input { + /** + * Encoding of the audio stream. Currently only supports raw signed little-endian 16-bit PCM. + */ + encoding: 'linear16'; + /** + * Sample rate of the audio stream in Hz. + */ + sample_rate: string; + /** + * End-of-turn confidence required to fire an eager end-of-turn event. When set, enables EagerEndOfTurn and TurnResumed events. Valid Values 0.3 - 0.9. + */ + eager_eot_threshold?: string; + /** + * End-of-turn confidence required to finish a turn. Valid Values 0.5 - 0.9. + */ + eot_threshold?: string; + /** + * A turn will be finished when this much time has passed after speech, regardless of EOT confidence. + */ + eot_timeout_ms?: string; + /** + * Keyterm prompting can improve recognition of specialized terminology. Pass multiple keyterm query parameters to boost multiple keyterms. + */ + keyterm?: string; + /** + * Opts out requests from the Deepgram Model Improvement Program. Refer to Deepgram Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip + */ + mip_opt_out?: 'true' | 'false'; + /** + * Label your requests for the purpose of identification during usage reporting + */ + tag?: string; +} +/** + * Output will be returned as websocket messages. + */ +interface Ai_Cf_Deepgram_Flux_Output { + /** + * The unique identifier of the request (uuid) + */ + request_id?: string; + /** + * Starts at 0 and increments for each message the server sends to the client. + */ + sequence_id?: number; + /** + * The type of event being reported. + */ + event?: 'Update' | 'StartOfTurn' | 'EagerEndOfTurn' | 'TurnResumed' | 'EndOfTurn'; + /** + * The index of the current turn + */ + turn_index?: number; + /** + * Start time in seconds of the audio range that was transcribed + */ + audio_window_start?: number; + /** + * End time in seconds of the audio range that was transcribed + */ + audio_window_end?: number; + /** + * Text that was said over the course of the current turn + */ + transcript?: string; + /** + * The words in the transcript + */ + words?: { + /** + * The individual punctuated, properly-cased word from the transcript + */ + word: string; + /** + * Confidence that this word was transcribed correctly + */ + confidence: number; + }[]; + /** + * Confidence that no more speech is coming in this turn + */ + end_of_turn_confidence?: number; +} +declare abstract class Base_Ai_Cf_Deepgram_Flux { + inputs: Ai_Cf_Deepgram_Flux_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Flux_Output; +} +interface Ai_Cf_Deepgram_Aura_2_En_Input { + /** + * Speaker used to produce the audio. + */ + speaker?: + | 'amalthea' + | 'andromeda' + | 'apollo' + | 'arcas' + | 'aries' + | 'asteria' + | 'athena' + | 'atlas' + | 'aurora' + | 'callista' + | 'cora' + | 'cordelia' + | 'delia' + | 'draco' + | 'electra' + | 'harmonia' + | 'helena' + | 'hera' + | 'hermes' + | 'hyperion' + | 'iris' + | 'janus' + | 'juno' + | 'jupiter' + | 'luna' + | 'mars' + | 'minerva' + | 'neptune' + | 'odysseus' + | 'ophelia' + | 'orion' + | 'orpheus' + | 'pandora' + | 'phoebe' + | 'pluto' + | 'saturn' + | 'thalia' + | 'theia' + | 'vesta' + | 'zeus'; + /** + * Encoding of the output audio. + */ + encoding?: 'linear16' | 'flac' | 'mulaw' | 'alaw' | 'mp3' | 'opus' | 'aac'; + /** + * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. + */ + container?: 'none' | 'wav' | 'ogg'; + /** + * The text content to be converted to speech + */ + text: string; + /** + * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable + */ + sample_rate?: number; + /** + * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. + */ + bit_rate?: number; +} +/** + * The generated audio in MP3 format + */ +type Ai_Cf_Deepgram_Aura_2_En_Output = string; +declare abstract class Base_Ai_Cf_Deepgram_Aura_2_En { + inputs: Ai_Cf_Deepgram_Aura_2_En_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_En_Output; +} +interface Ai_Cf_Deepgram_Aura_2_Es_Input { + /** + * Speaker used to produce the audio. + */ + speaker?: + | 'sirio' + | 'nestor' + | 'carina' + | 'celeste' + | 'alvaro' + | 'diana' + | 'aquila' + | 'selena' + | 'estrella' + | 'javier'; + /** + * Encoding of the output audio. + */ + encoding?: 'linear16' | 'flac' | 'mulaw' | 'alaw' | 'mp3' | 'opus' | 'aac'; + /** + * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. + */ + container?: 'none' | 'wav' | 'ogg'; + /** + * The text content to be converted to speech + */ + text: string; + /** + * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable + */ + sample_rate?: number; + /** + * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. + */ + bit_rate?: number; +} +/** + * The generated audio in MP3 format + */ +type Ai_Cf_Deepgram_Aura_2_Es_Output = string; +declare abstract class Base_Ai_Cf_Deepgram_Aura_2_Es { + inputs: Ai_Cf_Deepgram_Aura_2_Es_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_Es_Output; +} +interface AiModels { + '@cf/huggingface/distilbert-sst-2-int8': BaseAiTextClassification; + '@cf/stabilityai/stable-diffusion-xl-base-1.0': BaseAiTextToImage; + '@cf/runwayml/stable-diffusion-v1-5-inpainting': BaseAiTextToImage; + '@cf/runwayml/stable-diffusion-v1-5-img2img': BaseAiTextToImage; + '@cf/lykon/dreamshaper-8-lcm': BaseAiTextToImage; + '@cf/bytedance/stable-diffusion-xl-lightning': BaseAiTextToImage; + '@cf/myshell-ai/melotts': BaseAiTextToSpeech; + '@cf/google/embeddinggemma-300m': BaseAiTextEmbeddings; + '@cf/microsoft/resnet-50': BaseAiImageClassification; + '@cf/meta/llama-2-7b-chat-int8': BaseAiTextGeneration; + '@cf/mistral/mistral-7b-instruct-v0.1': BaseAiTextGeneration; + '@cf/meta/llama-2-7b-chat-fp16': BaseAiTextGeneration; + '@hf/thebloke/llama-2-13b-chat-awq': BaseAiTextGeneration; + '@hf/thebloke/mistral-7b-instruct-v0.1-awq': BaseAiTextGeneration; + '@hf/thebloke/zephyr-7b-beta-awq': BaseAiTextGeneration; + '@hf/thebloke/openhermes-2.5-mistral-7b-awq': BaseAiTextGeneration; + '@hf/thebloke/neural-chat-7b-v3-1-awq': BaseAiTextGeneration; + '@hf/thebloke/llamaguard-7b-awq': BaseAiTextGeneration; + '@hf/thebloke/deepseek-coder-6.7b-base-awq': BaseAiTextGeneration; + '@hf/thebloke/deepseek-coder-6.7b-instruct-awq': BaseAiTextGeneration; + '@cf/deepseek-ai/deepseek-math-7b-instruct': BaseAiTextGeneration; + '@cf/defog/sqlcoder-7b-2': BaseAiTextGeneration; + '@cf/openchat/openchat-3.5-0106': BaseAiTextGeneration; + '@cf/tiiuae/falcon-7b-instruct': BaseAiTextGeneration; + '@cf/thebloke/discolm-german-7b-v1-awq': BaseAiTextGeneration; + '@cf/qwen/qwen1.5-0.5b-chat': BaseAiTextGeneration; + '@cf/qwen/qwen1.5-7b-chat-awq': BaseAiTextGeneration; + '@cf/qwen/qwen1.5-14b-chat-awq': BaseAiTextGeneration; + '@cf/tinyllama/tinyllama-1.1b-chat-v1.0': BaseAiTextGeneration; + '@cf/microsoft/phi-2': BaseAiTextGeneration; + '@cf/qwen/qwen1.5-1.8b-chat': BaseAiTextGeneration; + '@cf/mistral/mistral-7b-instruct-v0.2-lora': BaseAiTextGeneration; + '@hf/nousresearch/hermes-2-pro-mistral-7b': BaseAiTextGeneration; + '@hf/nexusflow/starling-lm-7b-beta': BaseAiTextGeneration; + '@hf/google/gemma-7b-it': BaseAiTextGeneration; + '@cf/meta-llama/llama-2-7b-chat-hf-lora': BaseAiTextGeneration; + '@cf/google/gemma-2b-it-lora': BaseAiTextGeneration; + '@cf/google/gemma-7b-it-lora': BaseAiTextGeneration; + '@hf/mistral/mistral-7b-instruct-v0.2': BaseAiTextGeneration; + '@cf/meta/llama-3-8b-instruct': BaseAiTextGeneration; + '@cf/fblgit/una-cybertron-7b-v2-bf16': BaseAiTextGeneration; + '@cf/meta/llama-3-8b-instruct-awq': BaseAiTextGeneration; + '@cf/meta/llama-3.1-8b-instruct-fp8': BaseAiTextGeneration; + '@cf/meta/llama-3.1-8b-instruct-awq': BaseAiTextGeneration; + '@cf/meta/llama-3.2-3b-instruct': BaseAiTextGeneration; + '@cf/meta/llama-3.2-1b-instruct': BaseAiTextGeneration; + '@cf/deepseek-ai/deepseek-r1-distill-qwen-32b': BaseAiTextGeneration; + '@cf/ibm-granite/granite-4.0-h-micro': BaseAiTextGeneration; + '@cf/facebook/bart-large-cnn': BaseAiSummarization; + '@cf/llava-hf/llava-1.5-7b-hf': BaseAiImageToText; + '@cf/baai/bge-base-en-v1.5': Base_Ai_Cf_Baai_Bge_Base_En_V1_5; + '@cf/openai/whisper': Base_Ai_Cf_Openai_Whisper; + '@cf/meta/m2m100-1.2b': Base_Ai_Cf_Meta_M2M100_1_2B; + '@cf/baai/bge-small-en-v1.5': Base_Ai_Cf_Baai_Bge_Small_En_V1_5; + '@cf/baai/bge-large-en-v1.5': Base_Ai_Cf_Baai_Bge_Large_En_V1_5; + '@cf/unum/uform-gen2-qwen-500m': Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M; + '@cf/openai/whisper-tiny-en': Base_Ai_Cf_Openai_Whisper_Tiny_En; + '@cf/openai/whisper-large-v3-turbo': Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo; + '@cf/baai/bge-m3': Base_Ai_Cf_Baai_Bge_M3; + '@cf/black-forest-labs/flux-1-schnell': Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell; + '@cf/meta/llama-3.2-11b-vision-instruct': Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct; + '@cf/meta/llama-3.3-70b-instruct-fp8-fast': Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast; + '@cf/meta/llama-guard-3-8b': Base_Ai_Cf_Meta_Llama_Guard_3_8B; + '@cf/baai/bge-reranker-base': Base_Ai_Cf_Baai_Bge_Reranker_Base; + '@cf/qwen/qwen2.5-coder-32b-instruct': Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct; + '@cf/qwen/qwq-32b': Base_Ai_Cf_Qwen_Qwq_32B; + '@cf/mistralai/mistral-small-3.1-24b-instruct': Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct; + '@cf/google/gemma-3-12b-it': Base_Ai_Cf_Google_Gemma_3_12B_It; + '@cf/meta/llama-4-scout-17b-16e-instruct': Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct; + '@cf/qwen/qwen3-30b-a3b-fp8': Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8; + '@cf/deepgram/nova-3': Base_Ai_Cf_Deepgram_Nova_3; + '@cf/qwen/qwen3-embedding-0.6b': Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B; + '@cf/pipecat-ai/smart-turn-v2': Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2; + '@cf/openai/gpt-oss-120b': Base_Ai_Cf_Openai_Gpt_Oss_120B; + '@cf/openai/gpt-oss-20b': Base_Ai_Cf_Openai_Gpt_Oss_20B; + '@cf/leonardo/phoenix-1.0': Base_Ai_Cf_Leonardo_Phoenix_1_0; + '@cf/leonardo/lucid-origin': Base_Ai_Cf_Leonardo_Lucid_Origin; + '@cf/deepgram/aura-1': Base_Ai_Cf_Deepgram_Aura_1; + '@cf/ai4bharat/indictrans2-en-indic-1B': Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B; + '@cf/aisingapore/gemma-sea-lion-v4-27b-it': Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It; + '@cf/pfnet/plamo-embedding-1b': Base_Ai_Cf_Pfnet_Plamo_Embedding_1B; + '@cf/deepgram/flux': Base_Ai_Cf_Deepgram_Flux; + '@cf/deepgram/aura-2-en': Base_Ai_Cf_Deepgram_Aura_2_En; + '@cf/deepgram/aura-2-es': Base_Ai_Cf_Deepgram_Aura_2_Es; +} +type AiOptions = { + /** + * Send requests as an asynchronous batch job, only works for supported models + * https://developers.cloudflare.com/workers-ai/features/batch-api + */ + queueRequest?: boolean; + /** + * Establish websocket connections, only works for supported models + */ + websocket?: boolean; + /** + * Tag your requests to group and view them in Cloudflare dashboard. + * + * Rules: + * Tags must only contain letters, numbers, and the symbols: : - . / @ + * Each tag can have maximum 50 characters. + * Maximum 5 tags are allowed each request. + * Duplicate tags will removed. + */ + tags?: string[]; + gateway?: GatewayOptions; + returnRawResponse?: boolean; + prefix?: string; + extraHeaders?: object; +}; +type AiModelsSearchParams = { + author?: string; + hide_experimental?: boolean; + page?: number; + per_page?: number; + search?: string; + source?: number; + task?: string; +}; +type AiModelsSearchObject = { + id: string; + source: number; + name: string; + description: string; + task: { + id: string; + name: string; + description: string; + }; + tags: string[]; + properties: { + property_id: string; + value: string; + }[]; +}; +interface InferenceUpstreamError extends Error {} +interface AiInternalError extends Error {} +type AiModelListType = Record; +declare abstract class Ai { + aiGatewayLogId: string | null; + gateway(gatewayId: string): AiGateway; + /** + * Access the AI Search API for managing AI-powered search instances. + * + * This is the new API that replaces AutoRAG with better namespace separation: + * - Account-level operations: `list()`, `create()` + * - Instance-level operations: `get(id).search()`, `get(id).chatCompletions()`, `get(id).delete()` + * + * @example + * ```typescript + * // List all AI Search instances + * const instances = await env.AI.aiSearch.list(); + * + * // Search an instance + * const results = await env.AI.aiSearch.get('my-search').search({ + * messages: [{ role: 'user', content: 'What is the policy?' }], + * ai_search_options: { + * retrieval: { max_num_results: 10 } + * } + * }); + * + * // Generate chat completions with AI Search context + * const response = await env.AI.aiSearch.get('my-search').chatCompletions({ + * messages: [{ role: 'user', content: 'What is the policy?' }], + * model: '@cf/meta/llama-3.3-70b-instruct-fp8-fast' + * }); + * ``` + */ + aiSearch(): AiSearchAccountService; + /** + * @deprecated AutoRAG has been replaced by AI Search. + * Use `env.AI.aiSearch` instead for better API design and new features. + * + * Migration guide: + * - `env.AI.autorag().list()` → `env.AI.aiSearch.list()` + * - `env.AI.autorag('id').search({ query: '...' })` → `env.AI.aiSearch.get('id').search({ messages: [{ role: 'user', content: '...' }] })` + * - `env.AI.autorag('id').aiSearch(...)` → `env.AI.aiSearch.get('id').chatCompletions(...)` + * + * Note: The old API continues to work for backwards compatibility, but new projects should use AI Search. + * + * @see AiSearchAccountService + * @param autoragId Optional instance ID (omit for account-level operations) + */ + autorag(autoragId: string): AutoRAG; + run( + model: Name, + inputs: InputOptions, + options?: Options, + ): Promise< + Options extends + | { + returnRawResponse: true; + } + | { + websocket: true; + } + ? Response + : InputOptions extends { + stream: true; + } + ? ReadableStream + : AiModelList[Name]['postProcessedOutputs'] + >; + models(params?: AiModelsSearchParams): Promise; + toMarkdown(): ToMarkdownService; + toMarkdown(files: MarkdownDocument[], options?: ConversionRequestOptions): Promise; + toMarkdown(files: MarkdownDocument, options?: ConversionRequestOptions): Promise; +} +type GatewayRetries = { + maxAttempts?: 1 | 2 | 3 | 4 | 5; + retryDelayMs?: number; + backoff?: 'constant' | 'linear' | 'exponential'; +}; +type GatewayOptions = { + id: string; + cacheKey?: string; + cacheTtl?: number; + skipCache?: boolean; + metadata?: Record; + collectLog?: boolean; + eventId?: string; + requestTimeoutMs?: number; + retries?: GatewayRetries; +}; +type UniversalGatewayOptions = Exclude & { + /** + ** @deprecated + */ + id?: string; +}; +type AiGatewayPatchLog = { + score?: number | null; + feedback?: -1 | 1 | null; + metadata?: Record | null; +}; +type AiGatewayLog = { + id: string; + provider: string; + model: string; + model_type?: string; + path: string; + duration: number; + request_type?: string; + request_content_type?: string; + status_code: number; + response_content_type?: string; + success: boolean; + cached: boolean; + tokens_in?: number; + tokens_out?: number; + metadata?: Record; + step?: number; + cost?: number; + custom_cost?: boolean; + request_size: number; + request_head?: string; + request_head_complete: boolean; + response_size: number; + response_head?: string; + response_head_complete: boolean; + created_at: Date; +}; +type AIGatewayProviders = + | 'workers-ai' + | 'anthropic' + | 'aws-bedrock' + | 'azure-openai' + | 'google-vertex-ai' + | 'huggingface' + | 'openai' + | 'perplexity-ai' + | 'replicate' + | 'groq' + | 'cohere' + | 'google-ai-studio' + | 'mistral' + | 'grok' + | 'openrouter' + | 'deepseek' + | 'cerebras' + | 'cartesia' + | 'elevenlabs' + | 'adobe-firefly'; +type AIGatewayHeaders = { + 'cf-aig-metadata': Record | string; + 'cf-aig-custom-cost': + | { + per_token_in?: number; + per_token_out?: number; + } + | { + total_cost?: number; + } + | string; + 'cf-aig-cache-ttl': number | string; + 'cf-aig-skip-cache': boolean | string; + 'cf-aig-cache-key': string; + 'cf-aig-event-id': string; + 'cf-aig-request-timeout': number | string; + 'cf-aig-max-attempts': number | string; + 'cf-aig-retry-delay': number | string; + 'cf-aig-backoff': string; + 'cf-aig-collect-log': boolean | string; + Authorization: string; + 'Content-Type': string; + [key: string]: string | number | boolean | object; +}; +type AIGatewayUniversalRequest = { + provider: AIGatewayProviders | string; // eslint-disable-line + endpoint: string; + headers: Partial; + query: unknown; +}; +interface AiGatewayInternalError extends Error {} +interface AiGatewayLogNotFound extends Error {} +declare abstract class AiGateway { + patchLog(logId: string, data: AiGatewayPatchLog): Promise; + getLog(logId: string): Promise; + run( + data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[], + options?: { + gateway?: UniversalGatewayOptions; + extraHeaders?: object; + }, + ): Promise; + getUrl(provider?: AIGatewayProviders | string): Promise; // eslint-disable-line +} +/** + * @deprecated AutoRAG has been replaced by AI Search. Use AiSearchInternalError instead. + * @see AiSearchInternalError + */ +interface AutoRAGInternalError extends Error {} +/** + * @deprecated AutoRAG has been replaced by AI Search. Use AiSearchNotFoundError instead. + * @see AiSearchNotFoundError + */ +interface AutoRAGNotFoundError extends Error {} +/** + * @deprecated This error type is no longer used in the AI Search API. + */ +interface AutoRAGUnauthorizedError extends Error {} +/** + * @deprecated AutoRAG has been replaced by AI Search. Use AiSearchNameNotSetError instead. + * @see AiSearchNameNotSetError + */ +interface AutoRAGNameNotSetError extends Error {} +type ComparisonFilter = { + key: string; + type: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte'; + value: string | number | boolean; +}; +type CompoundFilter = { + type: 'and' | 'or'; + filters: ComparisonFilter[]; +}; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use AiSearchSearchRequest with the new API instead. + * @see AiSearchSearchRequest + */ +type AutoRagSearchRequest = { + query: string; + filters?: CompoundFilter | ComparisonFilter; + max_num_results?: number; + ranking_options?: { + ranker?: string; + score_threshold?: number; + }; + reranking?: { + enabled?: boolean; + model?: string; + }; + rewrite_query?: boolean; +}; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use AiSearchChatCompletionsRequest with the new API instead. + * @see AiSearchChatCompletionsRequest + */ +type AutoRagAiSearchRequest = AutoRagSearchRequest & { + stream?: boolean; + system_prompt?: string; +}; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use AiSearchChatCompletionsRequest with stream: true instead. + * @see AiSearchChatCompletionsRequest + */ +type AutoRagAiSearchRequestStreaming = Omit & { + stream: true; +}; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use AiSearchSearchResponse with the new API instead. + * @see AiSearchSearchResponse + */ +type AutoRagSearchResponse = { + object: 'vector_store.search_results.page'; + search_query: string; + data: { + file_id: string; + filename: string; + score: number; + attributes: Record; + content: { + type: 'text'; + text: string; + }[]; + }[]; + has_more: boolean; + next_page: string | null; +}; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use AiSearchListResponse with the new API instead. + * @see AiSearchListResponse + */ +type AutoRagListResponse = { + id: string; + enable: boolean; + type: string; + source: string; + vectorize_name: string; + paused: boolean; + status: string; +}[]; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * The new API returns different response formats for chat completions. + */ +type AutoRagAiSearchResponse = AutoRagSearchResponse & { + response: string; +}; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use the new AI Search API instead: `env.AI.aiSearch` + * + * Migration guide: + * - `env.AI.autorag().list()` → `env.AI.aiSearch.list()` + * - `env.AI.autorag('id').search(...)` → `env.AI.aiSearch.get('id').search(...)` + * - `env.AI.autorag('id').aiSearch(...)` → `env.AI.aiSearch.get('id').chatCompletions(...)` + * + * @see AiSearchAccountService + * @see AiSearchInstanceService + */ +declare abstract class AutoRAG { + /** + * @deprecated Use `env.AI.aiSearch.list()` instead. + * @see AiSearchAccountService.list + */ + list(): Promise; + /** + * @deprecated Use `env.AI.aiSearch.get(id).search(...)` instead. + * Note: The new API uses a messages array instead of a query string. + * @see AiSearchInstanceService.search + */ + search(params: AutoRagSearchRequest): Promise; + /** + * @deprecated Use `env.AI.aiSearch.get(id).chatCompletions(...)` instead. + * @see AiSearchInstanceService.chatCompletions + */ + aiSearch(params: AutoRagAiSearchRequestStreaming): Promise; + /** + * @deprecated Use `env.AI.aiSearch.get(id).chatCompletions(...)` instead. + * @see AiSearchInstanceService.chatCompletions + */ + aiSearch(params: AutoRagAiSearchRequest): Promise; + /** + * @deprecated Use `env.AI.aiSearch.get(id).chatCompletions(...)` instead. + * @see AiSearchInstanceService.chatCompletions + */ + aiSearch(params: AutoRagAiSearchRequest): Promise; +} +interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + * - squeeze: Stretches and deforms to the width and height given, even if it + * breaks aspect ratio + */ + fit?: 'scale-down' | 'contain' | 'cover' | 'crop' | 'pad' | 'squeeze'; + /** + * Image segmentation using artificial intelligence models. Sets pixels not + * within selected segment area to transparent e.g "foreground" sets every + * background pixel as transparent. + */ + segment?: 'foreground'; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | 'face' + | 'left' + | 'right' + | 'top' + | 'bottom' + | 'center' + | 'auto' + | 'entropy' + | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +interface BasicImageTransformationsGravityCoordinates { + x?: number; + y?: number; + mode?: 'remainder' | 'box-center'; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +interface RequestInitCfProperties extends Record { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: 'lossy' | 'lossless' | 'off'; + r2?: RequestInitCfPropertiesR2; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +interface RequestInitCfPropertiesImageDraw extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | 'x' | 'y'; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +interface RequestInitCfPropertiesImage extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in . + */ + dpr?: number; + /** + * Allows you to trim your image. Takes dpr into account and is performed before + * resizing or rotation. + * + * It can be used as: + * - left, top, right, bottom - it will specify the number of pixels to cut + * off each side + * - width, height - the width/height you'd like to end up with - can be used + * in combination with the properties above + * - border - this will automatically trim the surroundings of an image based on + * it's color. It consists of three properties: + * - color: rgb or hex representation of the color you wish to trim (todo: verify the rgba bit) + * - tolerance: difference from color to treat as color + * - keep: the number of pixels of border to keep + */ + trim?: + | 'border' + | { + top?: number; + bottom?: number; + left?: number; + right?: number; + width?: number; + height?: number; + border?: + | boolean + | { + color?: string; + tolerance?: number; + keep?: number; + }; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number | 'low' | 'medium-low' | 'medium-high' | 'high'; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: 'avif' | 'webp' | 'json' | 'jpeg' | 'png' | 'baseline-jpeg' | 'png-force' | 'svg'; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: 'keep' | 'copyright' | 'none'; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + 'origin-auth'?: 'share-publicly'; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string; + width: number; + } + | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + saturation?: number; + /** + * Flips the images horizontally, vertically, or both. Flipping is applied before + * rotation, so if you apply flip=h,rotate=90 then the image will be flipped + * horizontally, then rotated by 90 degrees. + */ + flip?: 'h' | 'v' | 'hv'; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: 'fast'; +} +interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +interface RequestInitCfPropertiesR2 { + /** + * Colo id of bucket that an object is stored in + */ + bucketColoId?: number; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +type IncomingRequestCfProperties = IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +interface IncomingRequestCfPropertiesBase extends Record { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn?: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization?: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. + */ + staticResource: boolean; + /** + * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). + */ + detectionIds: number[]; +} +interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +interface IncomingRequestCfPropertiesBotManagementEnterprise extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata?: HostMetadata; +} +interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: IncomingRequestCfPropertiesTLSClientAuth | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | 'T1'; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: '1'; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: '1'; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: '1' | '0'; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: '0'; + certVerified: 'NONE'; + certRevoked: '0'; + certIssuerDN: ''; + certSubjectDN: ''; + certIssuerDNRFC2253: ''; + certSubjectDNRFC2253: ''; + certIssuerDNLegacy: ''; + certSubjectDNLegacy: ''; + certSerial: ''; + certIssuerSerial: ''; + certSKI: ''; + certIssuerSKI: ''; + certFingerprintSHA1: ''; + certFingerprintSHA256: ''; + certNotBefore: ''; + certNotAfter: ''; +} +/** Possible outcomes of TLS verification */ +declare type CertVerificationStatus = + /** Authentication succeeded */ + | 'SUCCESS' + /** No certificate was presented */ + | 'NONE' + /** Failed because the certificate was self-signed */ + | 'FAILED:self signed certificate' + /** Failed because the certificate failed a trust chain check */ + | 'FAILED:unable to verify the first certificate' + /** Failed because the certificate not yet valid */ + | 'FAILED:certificate is not yet valid' + /** Failed because the certificate is expired */ + | 'FAILED:certificate has expired' + /** Failed for another unspecified reason */ + | 'FAILED'; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +declare type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = + | 0 /** Unknown */ + | 1 /** no keepalives (not found) */ + | 2 /** no connection re-use, opening keepalive connection failed */ + | 3 /** no connection re-use, keepalive accepted and saved */ + | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ + | 5; /** connection re-use, accepted by the origin server */ +/** ISO 3166-1 Alpha-2 codes */ +declare type Iso3166Alpha2Code = + | 'AD' + | 'AE' + | 'AF' + | 'AG' + | 'AI' + | 'AL' + | 'AM' + | 'AO' + | 'AQ' + | 'AR' + | 'AS' + | 'AT' + | 'AU' + | 'AW' + | 'AX' + | 'AZ' + | 'BA' + | 'BB' + | 'BD' + | 'BE' + | 'BF' + | 'BG' + | 'BH' + | 'BI' + | 'BJ' + | 'BL' + | 'BM' + | 'BN' + | 'BO' + | 'BQ' + | 'BR' + | 'BS' + | 'BT' + | 'BV' + | 'BW' + | 'BY' + | 'BZ' + | 'CA' + | 'CC' + | 'CD' + | 'CF' + | 'CG' + | 'CH' + | 'CI' + | 'CK' + | 'CL' + | 'CM' + | 'CN' + | 'CO' + | 'CR' + | 'CU' + | 'CV' + | 'CW' + | 'CX' + | 'CY' + | 'CZ' + | 'DE' + | 'DJ' + | 'DK' + | 'DM' + | 'DO' + | 'DZ' + | 'EC' + | 'EE' + | 'EG' + | 'EH' + | 'ER' + | 'ES' + | 'ET' + | 'FI' + | 'FJ' + | 'FK' + | 'FM' + | 'FO' + | 'FR' + | 'GA' + | 'GB' + | 'GD' + | 'GE' + | 'GF' + | 'GG' + | 'GH' + | 'GI' + | 'GL' + | 'GM' + | 'GN' + | 'GP' + | 'GQ' + | 'GR' + | 'GS' + | 'GT' + | 'GU' + | 'GW' + | 'GY' + | 'HK' + | 'HM' + | 'HN' + | 'HR' + | 'HT' + | 'HU' + | 'ID' + | 'IE' + | 'IL' + | 'IM' + | 'IN' + | 'IO' + | 'IQ' + | 'IR' + | 'IS' + | 'IT' + | 'JE' + | 'JM' + | 'JO' + | 'JP' + | 'KE' + | 'KG' + | 'KH' + | 'KI' + | 'KM' + | 'KN' + | 'KP' + | 'KR' + | 'KW' + | 'KY' + | 'KZ' + | 'LA' + | 'LB' + | 'LC' + | 'LI' + | 'LK' + | 'LR' + | 'LS' + | 'LT' + | 'LU' + | 'LV' + | 'LY' + | 'MA' + | 'MC' + | 'MD' + | 'ME' + | 'MF' + | 'MG' + | 'MH' + | 'MK' + | 'ML' + | 'MM' + | 'MN' + | 'MO' + | 'MP' + | 'MQ' + | 'MR' + | 'MS' + | 'MT' + | 'MU' + | 'MV' + | 'MW' + | 'MX' + | 'MY' + | 'MZ' + | 'NA' + | 'NC' + | 'NE' + | 'NF' + | 'NG' + | 'NI' + | 'NL' + | 'NO' + | 'NP' + | 'NR' + | 'NU' + | 'NZ' + | 'OM' + | 'PA' + | 'PE' + | 'PF' + | 'PG' + | 'PH' + | 'PK' + | 'PL' + | 'PM' + | 'PN' + | 'PR' + | 'PS' + | 'PT' + | 'PW' + | 'PY' + | 'QA' + | 'RE' + | 'RO' + | 'RS' + | 'RU' + | 'RW' + | 'SA' + | 'SB' + | 'SC' + | 'SD' + | 'SE' + | 'SG' + | 'SH' + | 'SI' + | 'SJ' + | 'SK' + | 'SL' + | 'SM' + | 'SN' + | 'SO' + | 'SR' + | 'SS' + | 'ST' + | 'SV' + | 'SX' + | 'SY' + | 'SZ' + | 'TC' + | 'TD' + | 'TF' + | 'TG' + | 'TH' + | 'TJ' + | 'TK' + | 'TL' + | 'TM' + | 'TN' + | 'TO' + | 'TR' + | 'TT' + | 'TV' + | 'TW' + | 'TZ' + | 'UA' + | 'UG' + | 'UM' + | 'US' + | 'UY' + | 'UZ' + | 'VA' + | 'VC' + | 'VE' + | 'VG' + | 'VI' + | 'VN' + | 'VU' + | 'WF' + | 'WS' + | 'YE' + | 'YT' + | 'ZA' + | 'ZM' + | 'ZW'; +/** The 2-letter continent codes Cloudflare uses */ +declare type ContinentCode = 'AF' | 'AN' | 'AS' | 'EU' | 'NA' | 'OC' | 'SA'; +type CfProperties = IncomingRequestCfProperties | RequestInitCfProperties; +interface D1Meta { + duration: number; + size_after: number; + rows_read: number; + rows_written: number; + last_row_id: number; + changed_db: boolean; + changes: number; + /** + * The region of the database instance that executed the query. + */ + served_by_region?: string; + /** + * The three letters airport code of the colo that executed the query. + */ + served_by_colo?: string; + /** + * True if-and-only-if the database instance that executed the query was the primary. + */ + served_by_primary?: boolean; + timings?: { + /** + * The duration of the SQL query execution by the database instance. It doesn't include any network time. + */ + sql_duration_ms: number; + }; + /** + * Number of total attempts to execute the query, due to automatic retries. + * Note: All other fields in the response like `timings` only apply to the last attempt. + */ + total_attempts?: number; +} +interface D1Response { + success: true; + meta: D1Meta & Record; + error?: never; +} +type D1Result = D1Response & { + results: T[]; +}; +interface D1ExecResult { + count: number; + duration: number; +} +type D1SessionConstraint = + // Indicates that the first query should go to the primary, and the rest queries + // using the same D1DatabaseSession will go to any replica that is consistent with + // the bookmark maintained by the session (returned by the first query). + | 'first-primary' + // Indicates that the first query can go anywhere (primary or replica), and the rest queries + // using the same D1DatabaseSession will go to any replica that is consistent with + // the bookmark maintained by the session (returned by the first query). + | 'first-unconstrained'; +type D1SessionBookmark = string; +declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + batch(statements: D1PreparedStatement[]): Promise[]>; + exec(query: string): Promise; + /** + * Creates a new D1 Session anchored at the given constraint or the bookmark. + * All queries executed using the created session will have sequential consistency, + * meaning that all writes done through the session will be visible in subsequent reads. + * + * @param constraintOrBookmark Either the session constraint or the explicit bookmark to anchor the created session. + */ + withSession(constraintOrBookmark?: D1SessionBookmark | D1SessionConstraint): D1DatabaseSession; + /** + * @deprecated dump() will be removed soon, only applies to deprecated alpha v1 databases. + */ + dump(): Promise; +} +declare abstract class D1DatabaseSession { + prepare(query: string): D1PreparedStatement; + batch(statements: D1PreparedStatement[]): Promise[]>; + /** + * @returns The latest session bookmark across all executed queries on the session. + * If no query has been executed yet, `null` is returned. + */ + getBookmark(): D1SessionBookmark | null; +} +declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first(colName: string): Promise; + first>(): Promise; + run>(): Promise>; + all>(): Promise>; + raw(options: { columnNames: true }): Promise<[string[], ...T[]]>; + raw(options?: { columnNames?: false }): Promise; +} +// `Disposable` was added to TypeScript's standard lib types in version 5.2. +// To support older TypeScript versions, define an empty `Disposable` interface. +// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2, +// but this will ensure type checking on older versions still passes. +// TypeScript's interface merging will ensure our empty interface is effectively +// ignored when `Disposable` is included in the standard lib. +interface Disposable {} +/** + * The returned data after sending an email + */ +interface EmailSendResult { + /** + * The Email Message ID + */ + messageId: string; +} +/** + * An email message that can be sent from a Worker. + */ +interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise; + /** + * Reply to the sender of this email message with a new EmailMessage object. + * @param message The reply message. + * @returns A promise that resolves when the email message is replied. + */ + reply(message: EmailMessage): Promise; +} +/** A file attachment for an email message */ +type EmailAttachment = + | { + disposition: 'inline'; + contentId: string; + filename: string; + type: string; + content: string | ArrayBuffer | ArrayBufferView; + } + | { + disposition: 'attachment'; + contentId?: undefined; + filename: string; + type: string; + content: string | ArrayBuffer | ArrayBufferView; + }; +/** An Email Address */ +interface EmailAddress { + name: string; + email: string; +} +/** + * A binding that allows a Worker to send email messages. + */ +interface SendEmail { + send(message: EmailMessage): Promise; + send(builder: { + from: string | EmailAddress; + to: string | string[]; + subject: string; + replyTo?: string | EmailAddress; + cc?: string | string[]; + bcc?: string | string[]; + headers?: Record; + text?: string; + html?: string; + attachments?: EmailAttachment[]; + }): Promise; +} +declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +declare type EmailExportedHandler = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext, +) => void | Promise; +declare module 'cloudflare:email' { + let _EmailMessage: { + prototype: EmailMessage; + new (from: string, to: string, raw: ReadableStream | string): EmailMessage; + }; + export { _EmailMessage as EmailMessage }; +} +/** + * Hello World binding to serve as an explanatory example. DO NOT USE + */ +interface HelloWorldBinding { + /** + * Retrieve the current stored value + */ + get(): Promise<{ + value: string; + ms?: number; + }>; + /** + * Set a new stored value + */ + set(value: string): Promise; +} +interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an identical socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: number; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +// Copyright (c) 2024 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +type ImageInfoResponse = + | { + format: 'image/svg+xml'; + } + | { + format: string; + fileSize: number; + width: number; + height: number; + }; +type ImageTransform = { + width?: number; + height?: number; + background?: string; + blur?: number; + border?: + | { + color?: string; + width?: number; + } + | { + top?: number; + bottom?: number; + left?: number; + right?: number; + }; + brightness?: number; + contrast?: number; + fit?: 'scale-down' | 'contain' | 'pad' | 'squeeze' | 'cover' | 'crop'; + flip?: 'h' | 'v' | 'hv'; + gamma?: number; + segment?: 'foreground'; + gravity?: + | 'face' + | 'left' + | 'right' + | 'top' + | 'bottom' + | 'center' + | 'auto' + | 'entropy' + | { + x?: number; + y?: number; + mode: 'remainder' | 'box-center'; + }; + rotate?: 0 | 90 | 180 | 270; + saturation?: number; + sharpen?: number; + trim?: + | 'border' + | { + top?: number; + bottom?: number; + left?: number; + right?: number; + width?: number; + height?: number; + border?: + | boolean + | { + color?: string; + tolerance?: number; + keep?: number; + }; + }; +}; +type ImageDrawOptions = { + opacity?: number; + repeat?: boolean | string; + top?: number; + left?: number; + bottom?: number; + right?: number; +}; +type ImageInputOptions = { + encoding?: 'base64'; +}; +type ImageOutputOptions = { + format: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp' | 'image/avif' | 'rgb' | 'rgba'; + quality?: number; + background?: string; + anim?: boolean; +}; +interface ImageMetadata { + id: string; + filename?: string; + uploaded?: string; + requireSignedURLs: boolean; + meta?: Record; + variants: string[]; + draft?: boolean; + creator?: string; +} +interface ImageUploadOptions { + id?: string; + filename?: string; + requireSignedURLs?: boolean; + metadata?: Record; + creator?: string; + encoding?: 'base64'; +} +interface ImageUpdateOptions { + requireSignedURLs?: boolean; + metadata?: Record; + creator?: string; +} +interface ImageListOptions { + limit?: number; + cursor?: string; + sortOrder?: 'asc' | 'desc'; + creator?: string; +} +interface ImageList { + images: ImageMetadata[]; + cursor?: string; + listComplete: boolean; +} +interface HostedImagesBinding { + /** + * Get detailed metadata for a hosted image + * @param imageId The ID of the image (UUID or custom ID) + * @returns Image metadata, or null if not found + */ + details(imageId: string): Promise; + /** + * Get the raw image data for a hosted image + * @param imageId The ID of the image (UUID or custom ID) + * @returns ReadableStream of image bytes, or null if not found + */ + image(imageId: string): Promise | null>; + /** + * Upload a new hosted image + * @param image The image file to upload + * @param options Upload configuration + * @returns Metadata for the uploaded image + * @throws {@link ImagesError} if upload fails + */ + upload(image: ReadableStream | ArrayBuffer, options?: ImageUploadOptions): Promise; + /** + * Update hosted image metadata + * @param imageId The ID of the image + * @param options Properties to update + * @returns Updated image metadata + * @throws {@link ImagesError} if update fails + */ + update(imageId: string, options: ImageUpdateOptions): Promise; + /** + * Delete a hosted image + * @param imageId The ID of the image + * @returns True if deleted, false if not found + */ + delete(imageId: string): Promise; + /** + * List hosted images with pagination + * @param options List configuration + * @returns List of images with pagination info + * @throws {@link ImagesError} if list fails + */ + list(options?: ImageListOptions): Promise; +} +interface ImagesBinding { + /** + * Get image metadata (type, width and height) + * @throws {@link ImagesError} with code 9412 if input is not an image + * @param stream The image bytes + */ + info(stream: ReadableStream, options?: ImageInputOptions): Promise; + /** + * Begin applying a series of transformations to an image + * @param stream The image bytes + * @returns A transform handle + */ + input(stream: ReadableStream, options?: ImageInputOptions): ImageTransformer; + /** + * Access hosted images CRUD operations + */ + readonly hosted: HostedImagesBinding; +} +interface ImageTransformer { + /** + * Apply transform next, returning a transform handle. + * You can then apply more transformations, draw, or retrieve the output. + * @param transform + */ + transform(transform: ImageTransform): ImageTransformer; + /** + * Draw an image on this transformer, returning a transform handle. + * You can then apply more transformations, draw, or retrieve the output. + * @param image The image (or transformer that will give the image) to draw + * @param options The options configuring how to draw the image + */ + draw(image: ReadableStream | ImageTransformer, options?: ImageDrawOptions): ImageTransformer; + /** + * Retrieve the image that results from applying the transforms to the + * provided input + * @param options Options that apply to the output e.g. output format + */ + output(options: ImageOutputOptions): Promise; +} +type ImageTransformationOutputOptions = { + encoding?: 'base64'; +}; +interface ImageTransformationResult { + /** + * The image as a response, ready to store in cache or return to users + */ + response(): Response; + /** + * The content type of the returned image + */ + contentType(): string; + /** + * The bytes of the response + */ + image(options?: ImageTransformationOutputOptions): ReadableStream; +} +interface ImagesError extends Error { + readonly code: number; + readonly message: string; + readonly stack?: string; +} +/** + * Media binding for transforming media streams. + * Provides the entry point for media transformation operations. + */ +interface MediaBinding { + /** + * Creates a media transformer from an input stream. + * @param media - The input media bytes + * @returns A MediaTransformer instance for applying transformations + */ + input(media: ReadableStream): MediaTransformer; +} +/** + * Media transformer for applying transformation operations to media content. + * Handles sizing, fitting, and other input transformation parameters. + */ +interface MediaTransformer { + /** + * Applies transformation options to the media content. + * @param transform - Configuration for how the media should be transformed + * @returns A generator for producing the transformed media output + */ + transform(transform?: MediaTransformationInputOptions): MediaTransformationGenerator; + /** + * Generates the final media output with specified options. + * @param output - Configuration for the output format and parameters + * @returns The final transformation result containing the transformed media + */ + output(output?: MediaTransformationOutputOptions): MediaTransformationResult; +} +/** + * Generator for producing media transformation results. + * Configures the output format and parameters for the transformed media. + */ +interface MediaTransformationGenerator { + /** + * Generates the final media output with specified options. + * @param output - Configuration for the output format and parameters + * @returns The final transformation result containing the transformed media + */ + output(output?: MediaTransformationOutputOptions): MediaTransformationResult; +} +/** + * Result of a media transformation operation. + * Provides multiple ways to access the transformed media content. + */ +interface MediaTransformationResult { + /** + * Returns the transformed media as a readable stream of bytes. + * @returns A promise containing a readable stream with the transformed media + */ + media(): Promise>; + /** + * Returns the transformed media as an HTTP response object. + * @returns The transformed media as a Promise, ready to store in cache or return to users + */ + response(): Promise; + /** + * Returns the MIME type of the transformed media. + * @returns A promise containing the content type string (e.g., 'image/jpeg', 'video/mp4') + */ + contentType(): Promise; +} +/** + * Configuration options for transforming media input. + * Controls how the media should be resized and fitted. + */ +type MediaTransformationInputOptions = { + /** How the media should be resized to fit the specified dimensions */ + fit?: 'contain' | 'cover' | 'scale-down'; + /** Target width in pixels */ + width?: number; + /** Target height in pixels */ + height?: number; +}; +/** + * Configuration options for Media Transformations output. + * Controls the format, timing, and type of the generated output. + */ +type MediaTransformationOutputOptions = { + /** + * Output mode determining the type of media to generate + */ + mode?: 'video' | 'spritesheet' | 'frame' | 'audio'; + /** Whether to include audio in the output */ + audio?: boolean; + /** + * Starting timestamp for frame extraction or start time for clips. (e.g. '2s'). + */ + time?: string; + /** + * Duration for video clips, audio extraction, and spritesheet generation (e.g. '5s'). + */ + duration?: string; + /** + * Number of frames in the spritesheet. + */ + imageCount?: number; + /** + * Output format for the generated media. + */ + format?: 'jpg' | 'png' | 'm4a'; +}; +/** + * Error object for media transformation operations. + * Extends the standard Error interface with additional media-specific information. + */ +interface MediaError extends Error { + readonly code: number; + readonly message: string; + readonly stack?: string; +} +declare module 'cloudflare:node' { + interface NodeStyleServer { + listen(...args: unknown[]): this; + address(): { + port?: number | null | undefined; + }; + } + export function httpServerHandler(port: number): ExportedHandler; + export function httpServerHandler(options: { port: number }): ExportedHandler; + export function httpServerHandler(server: NodeStyleServer): ExportedHandler; +} +type Params

= Record; +type EventContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; +}; +type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, +> = (context: EventContext) => Response | Promise; +type EventPluginContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; + pluginArgs: PluginArgs; +}; +type PagesPluginFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, + PluginArgs = unknown, +> = (context: EventPluginContext) => Response | Promise; +declare module 'assets:*' { + export const onRequest: PagesFunction; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +declare module 'cloudflare:pipelines' { + export abstract class PipelineTransformationEntrypoint< + Env = unknown, + I extends PipelineRecord = PipelineRecord, + O extends PipelineRecord = PipelineRecord, + > { + protected env: Env; + protected ctx: ExecutionContext; + constructor(ctx: ExecutionContext, env: Env); + /** + * run receives an array of PipelineRecord which can be + * transformed and returned to the pipeline + * @param records Incoming records from the pipeline to be transformed + * @param metadata Information about the specific pipeline calling the transformation entrypoint + * @returns A promise containing the transformed PipelineRecord array + */ + public run(records: I[], metadata: PipelineBatchMetadata): Promise; + } + export type PipelineRecord = Record; + export type PipelineBatchMetadata = { + pipelineId: string; + pipelineName: string; + }; + export interface Pipeline { + /** + * The Pipeline interface represents the type of a binding to a Pipeline + * + * @param records The records to send to the pipeline + */ + send(records: T[]): Promise; + } +} +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +interface RateLimitOptions { + key: string; +} +interface RateLimitOutcome { + success: boolean; +} +interface RateLimit { + /** + * Rate limit a request based on the provided options. + * @see https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/ + * @returns A promise that resolves with the outcome of the rate limit. + */ + limit(options: RateLimitOptions): Promise; +} +// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need +// to referenced by `Fetcher`. This is included in the "importable" version of the types which +// strips all `module` blocks. +declare namespace Rpc { + // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. + // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. + // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to + // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) + export const __RPC_STUB_BRAND: '__RPC_STUB_BRAND'; + export const __RPC_TARGET_BRAND: '__RPC_TARGET_BRAND'; + export const __WORKER_ENTRYPOINT_BRAND: '__WORKER_ENTRYPOINT_BRAND'; + export const __DURABLE_OBJECT_BRAND: '__DURABLE_OBJECT_BRAND'; + export const __WORKFLOW_ENTRYPOINT_BRAND: '__WORKFLOW_ENTRYPOINT_BRAND'; + export interface RpcTargetBranded { + [__RPC_TARGET_BRAND]: never; + } + export interface WorkerEntrypointBranded { + [__WORKER_ENTRYPOINT_BRAND]: never; + } + export interface DurableObjectBranded { + [__DURABLE_OBJECT_BRAND]: never; + } + export interface WorkflowEntrypointBranded { + [__WORKFLOW_ENTRYPOINT_BRAND]: never; + } + export type EntrypointBranded = WorkerEntrypointBranded | DurableObjectBranded | WorkflowEntrypointBranded; + // Types that can be used through `Stub`s + export type Stubable = RpcTargetBranded | ((...args: any[]) => any); + // Types that can be passed over RPC + // The reason for using a generic type here is to build a serializable subset of structured + // cloneable composite types. This allows types defined with the "interface" keyword to pass the + // serializable check as well. Otherwise, only types defined with the "type" keyword would pass. + type Serializable = + // Structured cloneables + | BaseType + // Structured cloneable composites + | Map< + T extends Map ? Serializable : never, + T extends Map ? Serializable : never + > + | Set ? Serializable : never> + | ReadonlyArray ? Serializable : never> + | { + [K in keyof T]: K extends number | string ? Serializable : never; + } + // Special types + | Stub + // Serialized as stubs, see `Stubify` + | Stubable; + // Base type for all RPC stubs, including common memory management methods. + // `T` is used as a marker type for unwrapping `Stub`s later. + interface StubBase extends Disposable { + [__RPC_STUB_BRAND]: T; + dup(): this; + } + export type Stub = Provider & StubBase; + // This represents all the types that can be sent as-is over an RPC boundary + type BaseType = + | void + | undefined + | null + | boolean + | number + | bigint + | string + | TypedArray + | ArrayBuffer + | DataView + | Date + | Error + | RegExp + | ReadableStream + | WritableStream + | Request + | Response + | Headers; + // Recursively rewrite all `Stubable` types with `Stub`s + // prettier-ignore + type Stubify = T extends Stubable ? Stub : T extends Map ? Map, Stubify> : T extends Set ? Set> : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { + [key: string | number]: any; + } ? { + [K in keyof T]: Stubify; + } : T; + // Recursively rewrite all `Stub`s with the corresponding `T`s. + // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: + // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. + // prettier-ignore + type Unstubify = T extends StubBase ? V : T extends Map ? Map, Unstubify> : T extends Set ? Set> : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { + [key: string | number]: unknown; + } ? { + [K in keyof T]: Unstubify; + } : T; + type UnstubifyAll = { + [I in keyof A]: Unstubify; + }; + // Utility type for adding `Provider`/`Disposable`s to `object` types only. + // Note `unknown & T` is equivalent to `T`. + type MaybeProvider = T extends object ? Provider : unknown; + type MaybeDisposable = T extends object ? Disposable : unknown; + // Type for method return or property on an RPC interface. + // - Stubable types are replaced by stubs. + // - Serializable types are passed by value, with stubable types replaced by stubs + // and a top-level `Disposer`. + // Everything else can't be passed over PRC. + // Technically, we use custom thenables here, but they quack like `Promise`s. + // Intersecting with `(Maybe)Provider` allows pipelining. + // prettier-ignore + type Result = R extends Stubable ? Promise> & Provider : R extends Serializable ? Promise & MaybeDisposable> & MaybeProvider : never; + // Type for method or property on an RPC interface. + // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. + // Unwrapping `Stub`s allows calling with `Stubable` arguments. + // For properties, rewrite types to be `Result`s. + // In each case, unwrap `Promise`s. + type MethodOrProperty = V extends (...args: infer P) => infer R + ? (...args: UnstubifyAll

) => Result> + : Result>; + // Type for the callable part of an `Provider` if `T` is callable. + // This is intersected with methods/properties. + type MaybeCallableProvider = T extends (...args: any[]) => any ? MethodOrProperty : unknown; + // Base type for all other types providing RPC-like interfaces. + // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. + // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. + export type Provider = MaybeCallableProvider & + Pick< + { + [K in keyof T]: MethodOrProperty; + }, + Exclude> + >; +} +declare namespace Cloudflare { + // Type of `env`. + // + // The specific project can extend `Env` by redeclaring it in project-specific files. Typescript + // will merge all declarations. + // + // You can use `wrangler types` to generate the `Env` type automatically. + interface Env {} + // Project-specific parameters used to inform types. + // + // This interface is, again, intended to be declared in project-specific files, and then that + // declaration will be merged with this one. + // + // A project should have a declaration like this: + // + // interface GlobalProps { + // // Declares the main module's exports. Used to populate Cloudflare.Exports aka the type + // // of `ctx.exports`. + // mainModule: typeof import("my-main-module"); + // + // // Declares which of the main module's exports are configured with durable storage, and + // // thus should behave as Durable Object namsepace bindings. + // durableNamespaces: "MyDurableObject" | "AnotherDurableObject"; + // } + // + // You can use `wrangler types` to generate `GlobalProps` automatically. + interface GlobalProps {} + // Evaluates to the type of a property in GlobalProps, defaulting to `Default` if it is not + // present. + type GlobalProp = K extends keyof GlobalProps ? GlobalProps[K] : Default; + // The type of the program's main module exports, if known. Requires `GlobalProps` to declare the + // `mainModule` property. + type MainModule = GlobalProp<'mainModule', {}>; + // The type of ctx.exports, which contains loopback bindings for all top-level exports. + type Exports = { + [K in keyof MainModule]: LoopbackForExport & + // If the export is listed in `durableNamespaces`, then it is also a + // DurableObjectNamespace. + (K extends GlobalProp<'durableNamespaces', never> + ? MainModule[K] extends new (...args: any[]) => infer DoInstance + ? DoInstance extends Rpc.DurableObjectBranded + ? DurableObjectNamespace + : DurableObjectNamespace + : DurableObjectNamespace + : {}); + }; +} +declare namespace CloudflareWorkersModule { + export type RpcStub = Rpc.Stub; + export const RpcStub: { + new (value: T): Rpc.Stub; + }; + export abstract class RpcTarget implements Rpc.RpcTargetBranded { + [Rpc.__RPC_TARGET_BRAND]: never; + } + // `protected` fields don't appear in `keyof`s, so can't be accessed over RPC + export abstract class WorkerEntrypoint implements Rpc.WorkerEntrypointBranded { + [Rpc.__WORKER_ENTRYPOINT_BRAND]: never; + protected ctx: ExecutionContext; + protected env: Env; + constructor(ctx: ExecutionContext, env: Env); + email?(message: ForwardableEmailMessage): void | Promise; + fetch?(request: Request): Response | Promise; + queue?(batch: MessageBatch): void | Promise; + scheduled?(controller: ScheduledController): void | Promise; + tail?(events: TraceItem[]): void | Promise; + tailStream?( + event: TailStream.TailEvent, + ): TailStream.TailEventHandlerType | Promise; + test?(controller: TestController): void | Promise; + trace?(traces: TraceItem[]): void | Promise; + } + export abstract class DurableObject implements Rpc.DurableObjectBranded { + [Rpc.__DURABLE_OBJECT_BRAND]: never; + protected ctx: DurableObjectState; + protected env: Env; + constructor(ctx: DurableObjectState, env: Env); + alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise; + fetch?(request: Request): Response | Promise; + webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise; + webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; + } + export type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; + export type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number; + export type WorkflowDelayDuration = WorkflowSleepDuration; + export type WorkflowTimeoutDuration = WorkflowSleepDuration; + export type WorkflowRetentionDuration = WorkflowSleepDuration; + export type WorkflowBackoff = 'constant' | 'linear' | 'exponential'; + export type WorkflowStepConfig = { + retries?: { + limit: number; + delay: WorkflowDelayDuration | number; + backoff?: WorkflowBackoff; + }; + timeout?: WorkflowTimeoutDuration | number; + }; + export type WorkflowEvent = { + payload: Readonly; + timestamp: Date; + instanceId: string; + }; + export type WorkflowStepEvent = { + payload: Readonly; + timestamp: Date; + type: string; + }; + export type WorkflowStepContext = { + attempt: number; + }; + export abstract class WorkflowStep { + do>(name: string, callback: (ctx: WorkflowStepContext) => Promise): Promise; + do>( + name: string, + config: WorkflowStepConfig, + callback: (ctx: WorkflowStepContext) => Promise, + ): Promise; + sleep: (name: string, duration: WorkflowSleepDuration) => Promise; + sleepUntil: (name: string, timestamp: Date | number) => Promise; + waitForEvent>( + name: string, + options: { + type: string; + timeout?: WorkflowTimeoutDuration | number; + }, + ): Promise>; + } + export type WorkflowInstanceStatus = + | 'queued' + | 'running' + | 'paused' + | 'errored' + | 'terminated' + | 'complete' + | 'waiting' + | 'waitingForPause' + | 'unknown'; + export abstract class WorkflowEntrypoint | unknown = unknown> + implements Rpc.WorkflowEntrypointBranded + { + [Rpc.__WORKFLOW_ENTRYPOINT_BRAND]: never; + protected ctx: ExecutionContext; + protected env: Env; + constructor(ctx: ExecutionContext, env: Env); + run(event: Readonly>, step: WorkflowStep): Promise; + } + export function waitUntil(promise: Promise): void; + export function withEnv(newEnv: unknown, fn: () => unknown): unknown; + export function withExports(newExports: unknown, fn: () => unknown): unknown; + export function withEnvAndExports(newEnv: unknown, newExports: unknown, fn: () => unknown): unknown; + export const env: Cloudflare.Env; + export const exports: Cloudflare.Exports; +} +declare module 'cloudflare:workers' { + export = CloudflareWorkersModule; +} +interface SecretsStoreSecret { + /** + * Get a secret from the Secrets Store, returning a string of the secret value + * if it exists, or throws an error if it does not exist + */ + get(): Promise; +} +declare module 'cloudflare:sockets' { + function _connect(address: string | SocketAddress, options?: SocketOptions): Socket; + export { _connect as connect }; +} +/** + * Binding entrypoint for Cloudflare Stream. + * + * Usage: + * - Binding-level operations: + * `await env.STREAM.videos.upload` + * `await env.STREAM.videos.createDirectUpload` + * `await env.STREAM.videos.*` + * `await env.STREAM.watermarks.*` + * - Per-video operations: + * `await env.STREAM.video(id).downloads.*` + * `await env.STREAM.video(id).captions.*` + * + * Example usage: + * ```ts + * await env.STREAM.video(id).downloads.generate(); + * + * const video = env.STREAM.video(id) + * const captions = video.captions.list(); + * const videoDetails = video.details() + * ``` + */ +interface StreamBinding { + /** + * Returns a handle scoped to a single video for per-video operations. + * @param id The unique identifier for the video. + * @returns A handle for per-video operations. + */ + video(id: string): StreamVideoHandle; + /** + * Uploads a new video from a File. + * @param file The video file to upload. + * @returns The uploaded video details. + * @throws {BadRequestError} if the upload parameter is invalid + * @throws {QuotaReachedError} if the account storage capacity is exceeded + * @throws {MaxFileSizeError} if the file size is too large + * @throws {RateLimitedError} if the server received too many requests + * @throws {InternalError} if an unexpected error occurs + */ + upload(file: File): Promise; + /** + * Uploads a new video from a provided URL. + * @param url The URL to upload from. + * @param params Optional upload parameters. + * @returns The uploaded video details. + * @throws {BadRequestError} if the upload parameter is invalid or the URL is invalid + * @throws {QuotaReachedError} if the account storage capacity is exceeded + * @throws {MaxFileSizeError} if the file size is too large + * @throws {RateLimitedError} if the server received too many requests + * @throws {AlreadyUploadedError} if a video was already uploaded to this URL + * @throws {InternalError} if an unexpected error occurs + */ + upload(url: string, params?: StreamUrlUploadParams): Promise; + /** + * Creates a direct upload that allows video uploads without an API key. + * @param params Parameters for the direct upload + * @returns The direct upload details. + * @throws {BadRequestError} if the parameters are invalid + * @throws {RateLimitedError} if the server received too many requests + * @throws {InternalError} if an unexpected error occurs + */ + createDirectUpload(params: StreamDirectUploadCreateParams): Promise; + videos: StreamVideos; + watermarks: StreamWatermarks; +} +/** + * Handle for operations scoped to a single Stream video. + */ +interface StreamVideoHandle { + /** + * The unique identifier for the video. + */ + id: string; + /** + * Get a full videos details + * @returns The full video details. + * @throws {NotFoundError} if the video is not found + * @throws {InternalError} if an unexpected error occurs + */ + details(): Promise; + /** + * Update details for a single video. + * @param params The fields to update for the video. + * @returns The updated video details. + * @throws {NotFoundError} if the video is not found + * @throws {BadRequestError} if the parameters are invalid + * @throws {InternalError} if an unexpected error occurs + */ + update(params: StreamUpdateVideoParams): Promise; + /** + * Deletes a video and its copies from Cloudflare Stream. + * @returns A promise that resolves when deletion completes. + * @throws {NotFoundError} if the video is not found + * @throws {InternalError} if an unexpected error occurs + */ + delete(): Promise; + /** + * Creates a signed URL token for a video. + * @returns The signed token that was created. + * @throws {InternalError} if the signing key cannot be retrieved or the token cannot be signed + */ + generateToken(): Promise; + downloads: StreamScopedDownloads; + captions: StreamScopedCaptions; +} +interface StreamVideo { + /** + * The unique identifier for the video. + */ + id: string; + /** + * A user-defined identifier for the media creator. + */ + creator: string | null; + /** + * The thumbnail URL for the video. + */ + thumbnail: string; + /** + * The thumbnail timestamp percentage. + */ + thumbnailTimestampPct: number; + /** + * Indicates whether the video is ready to stream. + */ + readyToStream: boolean; + /** + * The date and time the video became ready to stream. + */ + readyToStreamAt: string | null; + /** + * Processing status information. + */ + status: StreamVideoStatus; + /** + * A user modifiable key-value store. + */ + meta: Record; + /** + * The date and time the video was created. + */ + created: string; + /** + * The date and time the video was last modified. + */ + modified: string; + /** + * The date and time at which the video will be deleted. + */ + scheduledDeletion: string | null; + /** + * The size of the video in bytes. + */ + size: number; + /** + * The preview URL for the video. + */ + preview?: string; + /** + * Origins allowed to display the video. + */ + allowedOrigins: Array; + /** + * Indicates whether signed URLs are required. + */ + requireSignedURLs: boolean | null; + /** + * The date and time the video was uploaded. + */ + uploaded: string | null; + /** + * The date and time when the upload URL expires. + */ + uploadExpiry: string | null; + /** + * The maximum size in bytes for direct uploads. + */ + maxSizeBytes: number | null; + /** + * The maximum duration in seconds for direct uploads. + */ + maxDurationSeconds: number | null; + /** + * The video duration in seconds. -1 indicates unknown. + */ + duration: number; + /** + * Input metadata for the original upload. + */ + input: StreamVideoInput; + /** + * Playback URLs for the video. + */ + hlsPlaybackUrl: string; + dashPlaybackUrl: string; + /** + * The watermark applied to the video, if any. + */ + watermark: StreamWatermark | null; + /** + * The live input id associated with the video, if any. + */ + liveInputId?: string | null; + /** + * The source video id if this is a clip. + */ + clippedFromId: string | null; + /** + * Public details associated with the video. + */ + publicDetails: StreamPublicDetails | null; +} +type StreamVideoStatus = { + /** + * The current processing state. + */ + state: string; + /** + * The current processing step. + */ + step?: string; + /** + * The percent complete as a string. + */ + pctComplete?: string; + /** + * An error reason code, if applicable. + */ + errorReasonCode: string; + /** + * An error reason text, if applicable. + */ + errorReasonText: string; +}; +type StreamVideoInput = { + /** + * The input width in pixels. + */ + width: number; + /** + * The input height in pixels. + */ + height: number; +}; +type StreamPublicDetails = { + /** + * The public title for the video. + */ + title: string | null; + /** + * The public share link. + */ + share_link: string | null; + /** + * The public channel link. + */ + channel_link: string | null; + /** + * The public logo URL. + */ + logo: string | null; +}; +type StreamDirectUpload = { + /** + * The URL an unauthenticated upload can use for a single multipart request. + */ + uploadURL: string; + /** + * A Cloudflare-generated unique identifier for a media item. + */ + id: string; + /** + * The watermark profile applied to the upload. + */ + watermark: StreamWatermark | null; + /** + * The scheduled deletion time, if any. + */ + scheduledDeletion: string | null; +}; +type StreamDirectUploadCreateParams = { + /** + * The maximum duration in seconds for a video upload. + */ + maxDurationSeconds: number; + /** + * The date and time after upload when videos will not be accepted. + */ + expiry?: string; + /** + * A user-defined identifier for the media creator. + */ + creator?: string; + /** + * A user modifiable key-value store used to reference other systems of record for + * managing videos. + */ + meta?: Record; + /** + * Lists the origins allowed to display the video. + */ + allowedOrigins?: Array; + /** + * Indicates whether the video can be accessed using the id. When set to `true`, + * a signed token must be generated with a signing key to view the video. + */ + requireSignedURLs?: boolean; + /** + * The thumbnail timestamp percentage. + */ + thumbnailTimestampPct?: number; + /** + * The date and time at which the video will be deleted. Include `null` to remove + * a scheduled deletion. + */ + scheduledDeletion?: string | null; + /** + * The watermark profile to apply. + */ + watermark?: StreamDirectUploadWatermark; +}; +type StreamDirectUploadWatermark = { + /** + * The unique identifier for the watermark profile. + */ + id: string; +}; +type StreamUrlUploadParams = { + /** + * Lists the origins allowed to display the video. Enter allowed origin + * domains in an array and use `*` for wildcard subdomains. Empty arrays allow the + * video to be viewed on any origin. + */ + allowedOrigins?: Array; + /** + * A user-defined identifier for the media creator. + */ + creator?: string; + /** + * A user modifiable key-value store used to reference other systems of + * record for managing videos. + */ + meta?: Record; + /** + * Indicates whether the video can be a accessed using the id. When + * set to `true`, a signed token must be generated with a signing key to view the + * video. + */ + requireSignedURLs?: boolean; + /** + * Indicates the date and time at which the video will be deleted. Omit + * the field to indicate no change, or include with a `null` value to remove an + * existing scheduled deletion. If specified, must be at least 30 days from upload + * time. + */ + scheduledDeletion?: string | null; + /** + * The timestamp for a thumbnail image calculated as a percentage value + * of the video's duration. To convert from a second-wise timestamp to a + * percentage, divide the desired timestamp by the total duration of the video. If + * this value is not set, the default thumbnail image is taken from 0s of the + * video. + */ + thumbnailTimestampPct?: number; + /** + * The identifier for the watermark profile + */ + watermarkId?: string; +}; +interface StreamScopedCaptions { + /** + * Uploads the caption or subtitle file to the endpoint for a specific BCP47 language. + * One caption or subtitle file per language is allowed. + * @param language The BCP 47 language tag for the caption or subtitle. + * @param file The caption or subtitle file to upload. + * @returns The created caption entry. + * @throws {NotFoundError} if the video is not found + * @throws {BadRequestError} if the language or file is invalid + * @throws {MaxFileSizeError} if the file size is too large + * @throws {InternalError} if an unexpected error occurs + */ + upload(language: string, file: File): Promise; + /** + * Generate captions or subtitles for the provided language via AI. + * @param language The BCP 47 language tag to generate. + * @returns The generated caption entry. + * @throws {NotFoundError} if the video is not found + * @throws {BadRequestError} if the language is invalid + * @throws {StreamError} if a generated caption already exists + * @throws {StreamError} if the video duration is too long + * @throws {StreamError} if the video is missing audio + * @throws {StreamError} if the requested language is not supported + * @throws {InternalError} if an unexpected error occurs + */ + generate(language: string): Promise; + /** + * Lists the captions or subtitles. + * Use the language parameter to filter by a specific language. + * @param language The optional BCP 47 language tag to filter by. + * @returns The list of captions or subtitles. + * @throws {NotFoundError} if the video or caption is not found + * @throws {InternalError} if an unexpected error occurs + */ + list(language?: string): Promise; + /** + * Removes the captions or subtitles from a video. + * @param language The BCP 47 language tag to remove. + * @returns A promise that resolves when deletion completes. + * @throws {NotFoundError} if the video or caption is not found + * @throws {InternalError} if an unexpected error occurs + */ + delete(language: string): Promise; +} +interface StreamScopedDownloads { + /** + * Generates a download for a video when a video is ready to view. Available + * types are `default` and `audio`. Defaults to `default` when omitted. + * @param downloadType The download type to create. + * @returns The current downloads for the video. + * @throws {NotFoundError} if the video is not found + * @throws {BadRequestError} if the download type is invalid + * @throws {StreamError} if the video duration is too long to generate a download + * @throws {StreamError} if the video is not ready to stream + * @throws {InternalError} if an unexpected error occurs + */ + generate(downloadType?: StreamDownloadType): Promise; + /** + * Lists the downloads created for a video. + * @returns The current downloads for the video. + * @throws {NotFoundError} if the video or downloads are not found + * @throws {InternalError} if an unexpected error occurs + */ + get(): Promise; + /** + * Delete the downloads for a video. Available types are `default` and `audio`. + * Defaults to `default` when omitted. + * @param downloadType The download type to delete. + * @returns A promise that resolves when deletion completes. + * @throws {NotFoundError} if the video or downloads are not found + * @throws {InternalError} if an unexpected error occurs + */ + delete(downloadType?: StreamDownloadType): Promise; +} +interface StreamVideos { + /** + * Lists all videos in a users account. + * @returns The list of videos. + * @throws {BadRequestError} if the parameters are invalid + * @throws {InternalError} if an unexpected error occurs + */ + list(params?: StreamVideosListParams): Promise; +} +interface StreamWatermarks { + /** + * Generate a new watermark profile + * @param file The image file to upload + * @param params The watermark creation parameters. + * @returns The created watermark profile. + * @throws {BadRequestError} if the parameters are invalid + * @throws {InvalidURLError} if the URL is invalid + * @throws {MaxFileSizeError} if the file size is too large + * @throws {TooManyWatermarksError} if the number of allowed watermarks is reached + * @throws {InternalError} if an unexpected error occurs + */ + generate(file: File, params: StreamWatermarkCreateParams): Promise; + /** + * Generate a new watermark profile + * @param url The image url to upload + * @param params The watermark creation parameters. + * @returns The created watermark profile. + * @throws {BadRequestError} if the parameters are invalid + * @throws {InvalidURLError} if the URL is invalid + * @throws {MaxFileSizeError} if the file size is too large + * @throws {TooManyWatermarksError} if the number of allowed watermarks is reached + * @throws {InternalError} if an unexpected error occurs + */ + generate(url: string, params: StreamWatermarkCreateParams): Promise; + /** + * Lists all watermark profiles for an account. + * @returns The list of watermark profiles. + * @throws {InternalError} if an unexpected error occurs + */ + list(): Promise; + /** + * Retrieves details for a single watermark profile. + * @param watermarkId The watermark profile identifier. + * @returns The watermark profile details. + * @throws {NotFoundError} if the watermark is not found + * @throws {InternalError} if an unexpected error occurs + */ + get(watermarkId: string): Promise; + /** + * Deletes a watermark profile. + * @param watermarkId The watermark profile identifier. + * @returns A promise that resolves when deletion completes. + * @throws {NotFoundError} if the watermark is not found + * @throws {InternalError} if an unexpected error occurs + */ + delete(watermarkId: string): Promise; +} +type StreamUpdateVideoParams = { + /** + * Lists the origins allowed to display the video. Enter allowed origin + * domains in an array and use `*` for wildcard subdomains. Empty arrays allow the + * video to be viewed on any origin. + */ + allowedOrigins?: Array; + /** + * A user-defined identifier for the media creator. + */ + creator?: string; + /** + * The maximum duration in seconds for a video upload. Can be set for a + * video that is not yet uploaded to limit its duration. Uploads that exceed the + * specified duration will fail during processing. A value of `-1` means the value + * is unknown. + */ + maxDurationSeconds?: number; + /** + * A user modifiable key-value store used to reference other systems of + * record for managing videos. + */ + meta?: Record; + /** + * Indicates whether the video can be a accessed using the id. When + * set to `true`, a signed token must be generated with a signing key to view the + * video. + */ + requireSignedURLs?: boolean; + /** + * Indicates the date and time at which the video will be deleted. Omit + * the field to indicate no change, or include with a `null` value to remove an + * existing scheduled deletion. If specified, must be at least 30 days from upload + * time. + */ + scheduledDeletion?: string | null; + /** + * The timestamp for a thumbnail image calculated as a percentage value + * of the video's duration. To convert from a second-wise timestamp to a + * percentage, divide the desired timestamp by the total duration of the video. If + * this value is not set, the default thumbnail image is taken from 0s of the + * video. + */ + thumbnailTimestampPct?: number; +}; +type StreamCaption = { + /** + * Whether the caption was generated via AI. + */ + generated?: boolean; + /** + * The language label displayed in the native language to users. + */ + label: string; + /** + * The language tag in BCP 47 format. + */ + language: string; + /** + * The status of a generated caption. + */ + status?: 'ready' | 'inprogress' | 'error'; +}; +type StreamDownloadStatus = 'ready' | 'inprogress' | 'error'; +type StreamDownloadType = 'default' | 'audio'; +type StreamDownload = { + /** + * Indicates the progress as a percentage between 0 and 100. + */ + percentComplete: number; + /** + * The status of a generated download. + */ + status: StreamDownloadStatus; + /** + * The URL to access the generated download. + */ + url?: string; +}; +/** + * An object with download type keys. Each key is optional and only present if that + * download type has been created. + */ +type StreamDownloadGetResponse = { + /** + * The audio-only download. Only present if this download type has been created. + */ + audio?: StreamDownload; + /** + * The default video download. Only present if this download type has been created. + */ + default?: StreamDownload; +}; +type StreamWatermarkPosition = 'upperRight' | 'upperLeft' | 'lowerLeft' | 'lowerRight' | 'center'; +type StreamWatermark = { + /** + * The unique identifier for a watermark profile. + */ + id: string; + /** + * The size of the image in bytes. + */ + size: number; + /** + * The height of the image in pixels. + */ + height: number; + /** + * The width of the image in pixels. + */ + width: number; + /** + * The date and a time a watermark profile was created. + */ + created: string; + /** + * The source URL for a downloaded image. If the watermark profile was created via + * direct upload, this field is null. + */ + downloadedFrom: string | null; + /** + * A short description of the watermark profile. + */ + name: string; + /** + * The translucency of the image. A value of `0.0` makes the image completely + * transparent, and `1.0` makes the image completely opaque. Note that if the image + * is already semi-transparent, setting this to `1.0` will not make the image + * completely opaque. + */ + opacity: number; + /** + * The whitespace between the adjacent edges (determined by position) of the video + * and the image. `0.0` indicates no padding, and `1.0` indicates a fully padded + * video width or length, as determined by the algorithm. + */ + padding: number; + /** + * The size of the image relative to the overall size of the video. This parameter + * will adapt to horizontal and vertical videos automatically. `0.0` indicates no + * scaling (use the size of the image as-is), and `1.0 `fills the entire video. + */ + scale: number; + /** + * The location of the image. Valid positions are: `upperRight`, `upperLeft`, + * `lowerLeft`, `lowerRight`, and `center`. Note that `center` ignores the + * `padding` parameter. + */ + position: StreamWatermarkPosition; +}; +type StreamWatermarkCreateParams = { + /** + * A short description of the watermark profile. + */ + name?: string; + /** + * The translucency of the image. A value of `0.0` makes the image completely + * transparent, and `1.0` makes the image completely opaque. Note that if the + * image is already semi-transparent, setting this to `1.0` will not make the + * image completely opaque. + */ + opacity?: number; + /** + * The whitespace between the adjacent edges (determined by position) of the + * video and the image. `0.0` indicates no padding, and `1.0` indicates a fully + * padded video width or length, as determined by the algorithm. + */ + padding?: number; + /** + * The size of the image relative to the overall size of the video. This + * parameter will adapt to horizontal and vertical videos automatically. `0.0` + * indicates no scaling (use the size of the image as-is), and `1.0 `fills the + * entire video. + */ + scale?: number; + /** + * The location of the image. + */ + position?: StreamWatermarkPosition; +}; +type StreamVideosListParams = { + /** + * The maximum number of videos to return. + */ + limit?: number; + /** + * Return videos created before this timestamp. + * (RFC3339/RFC3339Nano) + */ + before?: string; + /** + * Comparison operator for the `before` field. + * @default 'lt' + */ + beforeComp?: StreamPaginationComparison; + /** + * Return videos created after this timestamp. + * (RFC3339/RFC3339Nano) + */ + after?: string; + /** + * Comparison operator for the `after` field. + * @default 'gte' + */ + afterComp?: StreamPaginationComparison; +}; +type StreamPaginationComparison = 'eq' | 'gt' | 'gte' | 'lt' | 'lte'; +/** + * Error object for Stream binding operations. + */ +interface StreamError extends Error { + readonly code: number; + readonly statusCode: number; + readonly message: string; + readonly stack?: string; +} +interface InternalError extends StreamError { + name: 'InternalError'; +} +interface BadRequestError extends StreamError { + name: 'BadRequestError'; +} +interface NotFoundError extends StreamError { + name: 'NotFoundError'; +} +interface ForbiddenError extends StreamError { + name: 'ForbiddenError'; +} +interface RateLimitedError extends StreamError { + name: 'RateLimitedError'; +} +interface QuotaReachedError extends StreamError { + name: 'QuotaReachedError'; +} +interface MaxFileSizeError extends StreamError { + name: 'MaxFileSizeError'; +} +interface InvalidURLError extends StreamError { + name: 'InvalidURLError'; +} +interface AlreadyUploadedError extends StreamError { + name: 'AlreadyUploadedError'; +} +interface TooManyWatermarksError extends StreamError { + name: 'TooManyWatermarksError'; +} +type MarkdownDocument = { + name: string; + blob: Blob; +}; +type ConversionResponse = + | { + id: string; + name: string; + mimeType: string; + format: 'markdown'; + tokens: number; + data: string; + } + | { + id: string; + name: string; + mimeType: string; + format: 'error'; + error: string; + }; +type ImageConversionOptions = { + descriptionLanguage?: 'en' | 'es' | 'fr' | 'it' | 'pt' | 'de'; +}; +type EmbeddedImageConversionOptions = ImageConversionOptions & { + convert?: boolean; + maxConvertedImages?: number; +}; +type ConversionOptions = { + html?: { + images?: EmbeddedImageConversionOptions & { + convertOGImage?: boolean; + }; + hostname?: string; + cssSelector?: string; + }; + docx?: { + images?: EmbeddedImageConversionOptions; + }; + image?: ImageConversionOptions; + pdf?: { + images?: EmbeddedImageConversionOptions; + metadata?: boolean; + }; +}; +type ConversionRequestOptions = { + gateway?: GatewayOptions; + extraHeaders?: object; + conversionOptions?: ConversionOptions; +}; +type SupportedFileFormat = { + mimeType: string; + extension: string; +}; +declare abstract class ToMarkdownService { + transform(files: MarkdownDocument[], options?: ConversionRequestOptions): Promise; + transform(files: MarkdownDocument, options?: ConversionRequestOptions): Promise; + supported(): Promise; +} +declare namespace TailStream { + interface Header { + readonly name: string; + readonly value: string; + } + interface FetchEventInfo { + readonly type: 'fetch'; + readonly method: string; + readonly url: string; + readonly cfJson?: object; + readonly headers: Header[]; + } + interface JsRpcEventInfo { + readonly type: 'jsrpc'; + } + interface ScheduledEventInfo { + readonly type: 'scheduled'; + readonly scheduledTime: Date; + readonly cron: string; + } + interface AlarmEventInfo { + readonly type: 'alarm'; + readonly scheduledTime: Date; + } + interface QueueEventInfo { + readonly type: 'queue'; + readonly queueName: string; + readonly batchSize: number; + } + interface EmailEventInfo { + readonly type: 'email'; + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; + } + interface TraceEventInfo { + readonly type: 'trace'; + readonly traces: (string | null)[]; + } + interface HibernatableWebSocketEventInfoMessage { + readonly type: 'message'; + } + interface HibernatableWebSocketEventInfoError { + readonly type: 'error'; + } + interface HibernatableWebSocketEventInfoClose { + readonly type: 'close'; + readonly code: number; + readonly wasClean: boolean; + } + interface HibernatableWebSocketEventInfo { + readonly type: 'hibernatableWebSocket'; + readonly info: + | HibernatableWebSocketEventInfoClose + | HibernatableWebSocketEventInfoError + | HibernatableWebSocketEventInfoMessage; + } + interface CustomEventInfo { + readonly type: 'custom'; + } + interface FetchResponseInfo { + readonly type: 'fetch'; + readonly statusCode: number; + } + type EventOutcome = + | 'ok' + | 'canceled' + | 'exception' + | 'unknown' + | 'killSwitch' + | 'daemonDown' + | 'exceededCpu' + | 'exceededMemory' + | 'loadShed' + | 'responseStreamDisconnected' + | 'scriptNotFound'; + interface ScriptVersion { + readonly id: string; + readonly tag?: string; + readonly message?: string; + } + interface Onset { + readonly type: 'onset'; + readonly attributes: Attribute[]; + // id for the span being opened by this Onset event. + readonly spanId: string; + readonly dispatchNamespace?: string; + readonly entrypoint?: string; + readonly executionModel: string; + readonly scriptName?: string; + readonly scriptTags?: string[]; + readonly scriptVersion?: ScriptVersion; + readonly info: + | FetchEventInfo + | JsRpcEventInfo + | ScheduledEventInfo + | AlarmEventInfo + | QueueEventInfo + | EmailEventInfo + | TraceEventInfo + | HibernatableWebSocketEventInfo + | CustomEventInfo; + } + interface Outcome { + readonly type: 'outcome'; + readonly outcome: EventOutcome; + readonly cpuTime: number; + readonly wallTime: number; + } + interface SpanOpen { + readonly type: 'spanOpen'; + readonly name: string; + // id for the span being opened by this SpanOpen event. + readonly spanId: string; + readonly info?: FetchEventInfo | JsRpcEventInfo | Attributes; + } + interface SpanClose { + readonly type: 'spanClose'; + readonly outcome: EventOutcome; + } + interface DiagnosticChannelEvent { + readonly type: 'diagnosticChannel'; + readonly channel: string; + readonly message: any; + } + interface Exception { + readonly type: 'exception'; + readonly name: string; + readonly message: string; + readonly stack?: string; + } + interface Log { + readonly type: 'log'; + readonly level: 'debug' | 'error' | 'info' | 'log' | 'warn'; + readonly message: object; + } + interface DroppedEventsDiagnostic { + readonly diagnosticsType: 'droppedEvents'; + readonly count: number; + } + interface StreamDiagnostic { + readonly type: 'streamDiagnostic'; + // To add new diagnostic types, define a new interface and add it to this union type. + readonly diagnostic: DroppedEventsDiagnostic; + } + // This marks the worker handler return information. + // This is separate from Outcome because the worker invocation can live for a long time after + // returning. For example - Websockets that return an http upgrade response but then continue + // streaming information or SSE http connections. + interface Return { + readonly type: 'return'; + readonly info?: FetchResponseInfo; + } + interface Attribute { + readonly name: string; + readonly value: string | string[] | boolean | boolean[] | number | number[] | bigint | bigint[]; + } + interface Attributes { + readonly type: 'attributes'; + readonly info: Attribute[]; + } + type EventType = + | Onset + | Outcome + | SpanOpen + | SpanClose + | DiagnosticChannelEvent + | Exception + | Log + | StreamDiagnostic + | Return + | Attributes; + // Context in which this trace event lives. + interface SpanContext { + // Single id for the entire top-level invocation + // This should be a new traceId for the first worker stage invoked in the eyeball request and then + // same-account service-bindings should reuse the same traceId but cross-account service-bindings + // should use a new traceId. + readonly traceId: string; + // spanId in which this event is handled + // for Onset and SpanOpen events this would be the parent span id + // for Outcome and SpanClose these this would be the span id of the opening Onset and SpanOpen events + // For Hibernate and Mark this would be the span under which they were emitted. + // spanId is not set ONLY if: + // 1. This is an Onset event + // 2. We are not inheriting any SpanContext. (e.g. this is a cross-account service binding or a new top-level invocation) + readonly spanId?: string; + } + interface TailEvent { + // invocation id of the currently invoked worker stage. + // invocation id will always be unique to every Onset event and will be the same until the Outcome event. + readonly invocationId: string; + // Inherited spanContext for this event. + readonly spanContext: SpanContext; + readonly timestamp: Date; + readonly sequence: number; + readonly event: Event; + } + type TailEventHandler = (event: TailEvent) => void | Promise; + type TailEventHandlerObject = { + outcome?: TailEventHandler; + spanOpen?: TailEventHandler; + spanClose?: TailEventHandler; + diagnosticChannel?: TailEventHandler; + exception?: TailEventHandler; + log?: TailEventHandler; + return?: TailEventHandler; + attributes?: TailEventHandler; + }; + type TailEventHandlerType = TailEventHandler | TailEventHandlerObject; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Data types supported for holding vector metadata. + */ +type VectorizeVectorMetadataValue = string | number | boolean | string[]; +/** + * Additional information to associate with a vector. + */ +type VectorizeVectorMetadata = VectorizeVectorMetadataValue | Record; +type VectorFloatArray = Float32Array | Float64Array; +interface VectorizeError { + code?: number; + error: string; +} +/** + * Comparison logic/operation to use for metadata filtering. + * + * This list is expected to grow as support for more operations are released. + */ +type VectorizeVectorMetadataFilterOp = '$eq' | '$ne' | '$lt' | '$lte' | '$gt' | '$gte'; +type VectorizeVectorMetadataFilterCollectionOp = '$in' | '$nin'; +/** + * Filter criteria for vector metadata used to limit the retrieved query result set. + */ +type VectorizeVectorMetadataFilter = { + [field: string]: + | Exclude + | null + | { + [Op in VectorizeVectorMetadataFilterOp]?: Exclude | null; + } + | { + [Op in VectorizeVectorMetadataFilterCollectionOp]?: Exclude[]; + }; +}; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +type VectorizeDistanceMetric = 'euclidean' | 'cosine' | 'dot-product'; +/** + * Metadata return levels for a Vectorize query. + * + * Default to "none". + * + * @property all Full metadata for the vector return set, including all fields (including those un-indexed) without truncation. This is a more expensive retrieval, as it requires additional fetching & reading of un-indexed data. + * @property indexed Return all metadata fields configured for indexing in the vector return set. This level of retrieval is "free" in that no additional overhead is incurred returning this data. However, note that indexed metadata is subject to truncation (especially for larger strings). + * @property none No indexed metadata will be returned. + */ +type VectorizeMetadataRetrievalLevel = 'all' | 'indexed' | 'none'; +interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnValues?: boolean; + returnMetadata?: boolean | VectorizeMetadataRetrievalLevel; + filter?: VectorizeVectorMetadataFilter; +} +/** + * Information about the configuration of an index. + */ +type VectorizeIndexConfig = + | { + dimensions: number; + metric: VectorizeDistanceMetric; + } + | { + preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity + }; +/** + * Metadata about an existing index. + * + * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released. + * See {@link VectorizeIndexInfo} for its post-beta equivalent. + */ +interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Metadata about an existing index. + */ +interface VectorizeIndexInfo { + /** The number of records containing vectors within the index. */ + vectorCount: number; + /** Number of dimensions the index has been configured for. */ + dimensions: number; + /** ISO 8601 datetime of the last processed mutation on in the index. All changes before this mutation will be reflected in the index state. */ + processedUpToDatetime: number; + /** UUIDv4 of the last mutation processed by the index. All changes before this mutation will be reflected in the index state. */ + processedUpToMutation: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +interface VectorizeVector { + /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the vector. Includes the values of other fields and potentially additional details. */ + metadata?: Record; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +type VectorizeMatch = Pick, 'values'> & + Omit & { + /** The score or rank for similarity, when returned as a result */ + score: number; + }; +/** + * A set of matching {@link VectorizeMatch} for a particular query. + */ +interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + * + * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released. + * See {@link VectorizeAsyncMutation} for its post-beta equivalent. + */ +interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +/** + * Result type indicating a mutation on the Vectorize Index. + * Actual mutations are processed async where the `mutationId` is the unique identifier for the operation. + */ +interface VectorizeAsyncMutation { + /** The unique identifier for the async mutation operation containing the changeset. */ + mutationId: string; +} +/** + * A Vectorize Vector Search Index for querying vectors/embeddings. + * + * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released. + * See {@link Vectorize} for its new implementation. + */ +declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query(vector: VectorFloatArray | number[], options?: VectorizeQueryOptions): Promise; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise; +} +/** + * A Vectorize Vector Search Index for querying vectors/embeddings. + * + * Mutations in this version are async, returning a mutation id. + */ +declare abstract class Vectorize { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query(vector: VectorFloatArray | number[], options?: VectorizeQueryOptions): Promise; + /** + * Use the provided vector-id to perform a similarity search across the index. + * @param vectorId Id for a vector in the index against which the index should be queried. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public queryById(vectorId: string, options?: VectorizeQueryOptions): Promise; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with a unique identifier of a mutation containing the insert changeset. + */ + public insert(vectors: VectorizeVector[]): Promise; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with a unique identifier of a mutation containing the upsert changeset. + */ + public upsert(vectors: VectorizeVector[]): Promise; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with a unique identifier of a mutation containing the delete changeset. + */ + public deleteByIds(ids: string[]): Promise; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise; +} +/** + * The interface for "version_metadata" binding + * providing metadata about the Worker Version using this binding. + */ +type WorkerVersionMetadata = { + /** The ID of the Worker Version using this binding */ + id: string; + /** The tag of the Worker Version using this binding */ + tag: string; + /** The timestamp of when the Worker Version was uploaded */ + timestamp: string; +}; +interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any; + }, + options?: DynamicDispatchOptions, + ): Fetcher; +} +declare module 'cloudflare:workflows' { + /** + * NonRetryableError allows for a user to throw a fatal error + * that makes a Workflow instance fail immediately without triggering a retry + */ + export class NonRetryableError extends Error { + public constructor(message: string, name?: string); + } +} +declare abstract class Workflow { + /** + * Get a handle to an existing instance of the Workflow. + * @param id Id for the instance of this Workflow + * @returns A promise that resolves with a handle for the Instance + */ + public get(id: string): Promise; + /** + * Create a new instance and return a handle to it. If a provided id exists, an error will be thrown. + * @param options Options when creating an instance including id and params + * @returns A promise that resolves with a handle for the Instance + */ + public create(options?: WorkflowInstanceCreateOptions): Promise; + /** + * Create a batch of instances and return handle for all of them. If a provided id exists, an error will be thrown. + * `createBatch` is limited at 100 instances at a time or when the RPC limit for the batch (1MiB) is reached. + * @param batch List of Options when creating an instance including name and params + * @returns A promise that resolves with a list of handles for the created instances. + */ + public createBatch(batch: WorkflowInstanceCreateOptions[]): Promise; +} +type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; +type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number; +type WorkflowRetentionDuration = WorkflowSleepDuration; +interface WorkflowInstanceCreateOptions { + /** + * An id for your Workflow instance. Must be unique within the Workflow. + */ + id?: string; + /** + * The event payload the Workflow instance is triggered with + */ + params?: PARAMS; + /** + * The retention policy for Workflow instance. + * Defaults to the maximum retention period available for the owner's account. + */ + retention?: { + successRetention?: WorkflowRetentionDuration; + errorRetention?: WorkflowRetentionDuration; + }; +} +type InstanceStatus = { + status: + | 'queued' // means that instance is waiting to be started (see concurrency limits) + | 'running' + | 'paused' + | 'errored' + | 'terminated' // user terminated the instance while it was running + | 'complete' + | 'waiting' // instance is hibernating and waiting for sleep or event to finish + | 'waitingForPause' // instance is finishing the current work to pause + | 'unknown'; + error?: { + name: string; + message: string; + }; + output?: unknown; +}; +interface WorkflowError { + code?: number; + message: string; +} +declare abstract class WorkflowInstance { + public id: string; + /** + * Pause the instance. + */ + public pause(): Promise; + /** + * Resume the instance. If it is already running, an error will be thrown. + */ + public resume(): Promise; + /** + * Terminate the instance. If it is errored, terminated or complete, an error will be thrown. + */ + public terminate(): Promise; + /** + * Restart the instance. + */ + public restart(): Promise; + /** + * Returns the current status of the instance. + */ + public status(): Promise; + /** + * Send an event to this instance. + */ + public sendEvent({ type, payload }: { type: string; payload: unknown }): Promise; +} diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/wrangler.toml b/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/wrangler.toml new file mode 100644 index 000000000000..fe9a7e9c1204 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/cloudflare-workersentrypoint/wrangler.toml @@ -0,0 +1,111 @@ +#:schema node_modules/wrangler/config-schema.json +name = "cloudflare-workersentrypoint" +main = "src/index.ts" +compatibility_date = "2024-07-25" +compatibility_flags = ["nodejs_compat"] + +[vars] +E2E_TEST_DSN = "" + +# Automatically place your workloads in an optimal location to minimize latency. +# If you are running back-end logic in a Worker, running it closer to your back-end infrastructure +# rather than the end user may result in better performance. +# Docs: https://developers.cloudflare.com/workers/configuration/smart-placement/#smart-placement +# [placement] +# mode = "smart" + +# Variable bindings. These are arbitrary, plaintext strings (similar to environment variables) +# Docs: +# - https://developers.cloudflare.com/workers/wrangler/configuration/#environment-variables +# Note: Use secrets to store sensitive data. +# - https://developers.cloudflare.com/workers/configuration/secrets/ +# [vars] +# MY_VARIABLE = "production_value" + +# Bind the Workers AI model catalog. Run machine learning models, powered by serverless GPUs, on Cloudflare’s global network +# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#workers-ai +# [ai] +# binding = "AI" + +# Bind an Analytics Engine dataset. Use Analytics Engine to write analytics within your Pages Function. +# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#analytics-engine-datasets +# [[analytics_engine_datasets]] +# binding = "MY_DATASET" + +# Bind a headless browser instance running on Cloudflare's global network. +# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#browser-rendering +# [browser] +# binding = "MY_BROWSER" + +# Bind a D1 database. D1 is Cloudflare’s native serverless SQL database. +# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#d1-databases +# [[d1_databases]] +# binding = "MY_DB" +# database_name = "my-database" +# database_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" + +# Bind a dispatch namespace. Use Workers for Platforms to deploy serverless functions programmatically on behalf of your customers. +# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#dispatch-namespace-bindings-workers-for-platforms +# [[dispatch_namespaces]] +# binding = "MY_DISPATCHER" +# namespace = "my-namespace" + +# Bind a Durable Object. Durable objects are a scale-to-zero compute primitive based on the actor model. +# Durable Objects can live for as long as needed. Use these when you need a long-running "server", such as in realtime apps. +# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#durable-objects +[[durable_objects.bindings]] +name = "MY_DURABLE_OBJECT" +class_name = "MyDurableObject" + +# Durable Object migrations. +# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#migrations +[[migrations]] +tag = "v1" +new_sqlite_classes = ["MyDurableObject"] + +# Bind a Hyperdrive configuration. Use to accelerate access to your existing databases from Cloudflare Workers. +# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#hyperdrive +# [[hyperdrive]] +# binding = "MY_HYPERDRIVE" +# id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + +# Bind a KV Namespace. Use KV as persistent storage for small key-value pairs. +# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#kv-namespaces +# [[kv_namespaces]] +# binding = "MY_KV_NAMESPACE" +# id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + +# Bind an mTLS certificate. Use to present a client certificate when communicating with another service. +# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#mtls-certificates +# [[mtls_certificates]] +# binding = "MY_CERTIFICATE" +# certificate_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" + +# Bind a Queue producer. Use this binding to schedule an arbitrary task that may be processed later by a Queue consumer. +# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#queues +# [[queues.producers]] +# binding = "MY_QUEUE" +# queue = "my-queue" + +# Bind a Queue consumer. Queue Consumers can retrieve tasks scheduled by Producers to act on them. +# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#queues +# [[queues.consumers]] +# queue = "my-queue" + +# Bind an R2 Bucket. Use R2 to store arbitrarily large blobs of data, such as files. +# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#r2-buckets +# [[r2_buckets]] +# binding = "MY_BUCKET" +# bucket_name = "my-bucket" + +# Bind another Worker service. Use this binding to call another Worker without network overhead. +# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#service-bindings +# [[services]] +# binding = "MY_SERVICE" +# service = "my-service" + +# Bind a Vectorize index. Use to store and query vector embeddings for semantic search, classification and other vector search use-cases. +# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#vectorize-indexes +# [[vectorize]] +# binding = "MY_INDEX" +# index_name = "my-index" diff --git a/dev-packages/e2e-tests/test-applications/debug-id-sourcemaps/package.json b/dev-packages/e2e-tests/test-applications/debug-id-sourcemaps/package.json index 65e97c7c5954..4a0d90942367 100644 --- a/dev-packages/e2e-tests/test-applications/debug-id-sourcemaps/package.json +++ b/dev-packages/e2e-tests/test-applications/debug-id-sourcemaps/package.json @@ -15,7 +15,7 @@ "devDependencies": { "rollup": "^4.35.0", "vitest": "^0.34.6", - "@sentry/rollup-plugin": "^5.1.0" + "@sentry/rollup-plugin": "^5.2.0" }, "volta": { "extends": "../../package.json" diff --git a/dev-packages/e2e-tests/test-applications/deno/tests/ai.test.ts b/dev-packages/e2e-tests/test-applications/deno/tests/ai.test.ts index 102ef00c6cd1..d0b824bf9b2f 100644 --- a/dev-packages/e2e-tests/test-applications/deno/tests/ai.test.ts +++ b/dev-packages/e2e-tests/test-applications/deno/tests/ai.test.ts @@ -31,7 +31,7 @@ test('should create AI pipeline spans with Vercel AI SDK', async ({ baseURL }) = const aiSpans = spans.filter( (span: any) => span.op === 'gen_ai.invoke_agent' || - span.op === 'gen_ai.generate_text' || + span.op === 'gen_ai.generate_content' || span.op === 'otel.span' || span.description?.includes('ai.generateText'), ); diff --git a/dev-packages/e2e-tests/test-applications/hydrogen-react-router-7/app/entry.client.tsx b/dev-packages/e2e-tests/test-applications/hydrogen-react-router-7/app/entry.client.tsx index 9c48e56befe8..bd606bbe7c08 100644 --- a/dev-packages/e2e-tests/test-applications/hydrogen-react-router-7/app/entry.client.tsx +++ b/dev-packages/e2e-tests/test-applications/hydrogen-react-router-7/app/entry.client.tsx @@ -16,7 +16,7 @@ startTransition(() => { hydrateRoot( document, - + , ); }); diff --git a/dev-packages/e2e-tests/test-applications/hydrogen-react-router-7/app/root.tsx b/dev-packages/e2e-tests/test-applications/hydrogen-react-router-7/app/root.tsx index afa85270e045..e45feb5dd576 100644 --- a/dev-packages/e2e-tests/test-applications/hydrogen-react-router-7/app/root.tsx +++ b/dev-packages/e2e-tests/test-applications/hydrogen-react-router-7/app/root.tsx @@ -1,4 +1,3 @@ -import * as Sentry from '@sentry/react-router/cloudflare'; import { type LoaderFunctionArgs } from '@shopify/remix-oxygen'; import { Outlet, @@ -160,8 +159,6 @@ export function ErrorBoundary({ error }: { error: unknown }) { let errorMessage = 'Unknown error'; let errorStatus = 500; - const eventId = Sentry.captureException(error); - if (isRouteErrorResponse(error)) { errorMessage = error?.data?.message ?? error.data; errorStatus = error.status; @@ -178,11 +175,6 @@ export function ErrorBoundary({ error }: { error: unknown }) {

{errorMessage}
)} - {eventId && ( -

- Sentry Event ID: {eventId} -

- )} ); } diff --git a/dev-packages/e2e-tests/test-applications/hydrogen-react-router-7/package.json b/dev-packages/e2e-tests/test-applications/hydrogen-react-router-7/package.json index 36c1d9039ba4..87c67b61f195 100644 --- a/dev-packages/e2e-tests/test-applications/hydrogen-react-router-7/package.json +++ b/dev-packages/e2e-tests/test-applications/hydrogen-react-router-7/package.json @@ -16,7 +16,7 @@ "dependencies": { "@sentry/cloudflare": "latest || *", "@sentry/react-router": "latest || *", - "@sentry/vite-plugin": "^5.1.0", + "@sentry/vite-plugin": "^5.2.0", "@shopify/hydrogen": "2025.5.0", "@shopify/remix-oxygen": "^3.0.0", "graphql": "^16.10.0", diff --git a/dev-packages/e2e-tests/test-applications/nestjs-11/tests/transactions.test.ts b/dev-packages/e2e-tests/test-applications/nestjs-11/tests/transactions.test.ts index a8b8f25e46c1..375c56a845d6 100644 --- a/dev-packages/e2e-tests/test-applications/nestjs-11/tests/transactions.test.ts +++ b/dev-packages/e2e-tests/test-applications/nestjs-11/tests/transactions.test.ts @@ -61,7 +61,7 @@ test('Sends an API route transaction', async ({ baseURL }) => { 'express.name': '/test-transaction', 'express.type': 'request_handler', 'http.route': '/test-transaction', - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'request_handler.express', }, op: 'request_handler.express', @@ -72,7 +72,7 @@ test('Sends an API route transaction', async ({ baseURL }) => { status: 'ok', timestamp: expect.any(Number), trace_id: expect.stringMatching(/[a-f0-9]{32}/), - origin: 'auto.http.otel.express', + origin: 'auto.http.express', }, { data: { diff --git a/dev-packages/e2e-tests/test-applications/nestjs-8/tests/transactions.test.ts b/dev-packages/e2e-tests/test-applications/nestjs-8/tests/transactions.test.ts index 862f730636c0..7270ad211909 100644 --- a/dev-packages/e2e-tests/test-applications/nestjs-8/tests/transactions.test.ts +++ b/dev-packages/e2e-tests/test-applications/nestjs-8/tests/transactions.test.ts @@ -65,7 +65,7 @@ test('Sends an API route transaction', async ({ baseURL }) => { 'express.name': '/test-transaction', 'express.type': 'request_handler', 'http.route': '/test-transaction', - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'request_handler.express', }, op: 'request_handler.express', @@ -76,7 +76,7 @@ test('Sends an API route transaction', async ({ baseURL }) => { status: 'ok', timestamp: expect.any(Number), trace_id: expect.stringMatching(/[a-f0-9]{32}/), - origin: 'auto.http.otel.express', + origin: 'auto.http.express', }, { data: { diff --git a/dev-packages/e2e-tests/test-applications/nestjs-basic/tests/transactions.test.ts b/dev-packages/e2e-tests/test-applications/nestjs-basic/tests/transactions.test.ts index 440a1391556a..a1c1e80762c0 100644 --- a/dev-packages/e2e-tests/test-applications/nestjs-basic/tests/transactions.test.ts +++ b/dev-packages/e2e-tests/test-applications/nestjs-basic/tests/transactions.test.ts @@ -61,7 +61,7 @@ test('Sends an API route transaction', async ({ baseURL }) => { 'express.name': '/test-transaction', 'express.type': 'request_handler', 'http.route': '/test-transaction', - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'request_handler.express', }, op: 'request_handler.express', @@ -72,7 +72,7 @@ test('Sends an API route transaction', async ({ baseURL }) => { status: 'ok', timestamp: expect.any(Number), trace_id: expect.stringMatching(/[a-f0-9]{32}/), - origin: 'auto.http.otel.express', + origin: 'auto.http.express', }, { data: { diff --git a/dev-packages/e2e-tests/test-applications/nestjs-with-submodules-decorator/tests/transactions.test.ts b/dev-packages/e2e-tests/test-applications/nestjs-with-submodules-decorator/tests/transactions.test.ts index 380e5fdc018e..9ca18ec0888f 100644 --- a/dev-packages/e2e-tests/test-applications/nestjs-with-submodules-decorator/tests/transactions.test.ts +++ b/dev-packages/e2e-tests/test-applications/nestjs-with-submodules-decorator/tests/transactions.test.ts @@ -61,7 +61,7 @@ test('Sends an API route transaction from module', async ({ baseURL }) => { 'express.name': '/example-module/transaction', 'express.type': 'request_handler', 'http.route': '/example-module/transaction', - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'request_handler.express', }, op: 'request_handler.express', @@ -72,7 +72,7 @@ test('Sends an API route transaction from module', async ({ baseURL }) => { status: 'ok', timestamp: expect.any(Number), trace_id: expect.stringMatching(/[a-f0-9]{32}/), - origin: 'auto.http.otel.express', + origin: 'auto.http.express', }, { data: { diff --git a/dev-packages/e2e-tests/test-applications/nestjs-with-submodules/tests/transactions.test.ts b/dev-packages/e2e-tests/test-applications/nestjs-with-submodules/tests/transactions.test.ts index 416ff72e946b..ddfcb1192edf 100644 --- a/dev-packages/e2e-tests/test-applications/nestjs-with-submodules/tests/transactions.test.ts +++ b/dev-packages/e2e-tests/test-applications/nestjs-with-submodules/tests/transactions.test.ts @@ -61,7 +61,7 @@ test('Sends an API route transaction from module', async ({ baseURL }) => { 'express.name': '/example-module/transaction', 'express.type': 'request_handler', 'http.route': '/example-module/transaction', - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'request_handler.express', }, op: 'request_handler.express', @@ -72,7 +72,7 @@ test('Sends an API route transaction from module', async ({ baseURL }) => { status: 'ok', timestamp: expect.any(Number), trace_id: expect.stringMatching(/[a-f0-9]{32}/), - origin: 'auto.http.otel.express', + origin: 'auto.http.express', }, { data: { diff --git a/dev-packages/e2e-tests/test-applications/nextjs-15/tests/ai-error.test.ts b/dev-packages/e2e-tests/test-applications/nextjs-15/tests/ai-error.test.ts index 32fd12ee0ed5..a8c39ec032ec 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-15/tests/ai-error.test.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-15/tests/ai-error.test.ts @@ -26,7 +26,7 @@ test('should create AI spans with correct attributes and error linking', async ( // because of this, only spans that are manually opted-in at call time will be captured // this may be fixed by https://github.com/vercel/ai/pull/6716 in the future const aiPipelineSpans = spans.filter(span => span.op === 'gen_ai.invoke_agent'); - const aiGenerateSpans = spans.filter(span => span.op === 'gen_ai.generate_text'); + const aiGenerateSpans = spans.filter(span => span.op === 'gen_ai.generate_content'); const toolCallSpans = spans.filter(span => span.op === 'gen_ai.execute_tool'); expect(aiPipelineSpans.length).toBeGreaterThanOrEqual(1); diff --git a/dev-packages/e2e-tests/test-applications/nextjs-15/tests/ai-test.test.ts b/dev-packages/e2e-tests/test-applications/nextjs-15/tests/ai-test.test.ts index a53f8986512a..42c21e4f8c80 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-15/tests/ai-test.test.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-15/tests/ai-test.test.ts @@ -22,7 +22,7 @@ test('should create AI spans with correct attributes', async ({ page }) => { // because of this, only spans that are manually opted-in at call time will be captured // this may be fixed by https://github.com/vercel/ai/pull/6716 in the future const aiPipelineSpans = spans.filter(span => span.op === 'gen_ai.invoke_agent'); - const aiGenerateSpans = spans.filter(span => span.op === 'gen_ai.generate_text'); + const aiGenerateSpans = spans.filter(span => span.op === 'gen_ai.generate_content'); const toolCallSpans = spans.filter(span => span.op === 'gen_ai.execute_tool'); expect(aiPipelineSpans.length).toBeGreaterThanOrEqual(1); diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16/tests/ai-error.test.ts b/dev-packages/e2e-tests/test-applications/nextjs-16/tests/ai-error.test.ts index 65f118165702..39e76bab0dde 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16/tests/ai-error.test.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-16/tests/ai-error.test.ts @@ -26,7 +26,7 @@ test('should create AI spans with correct attributes and error linking', async ( // because of this, only spans that are manually opted-in at call time will be captured // this may be fixed by https://github.com/vercel/ai/pull/6716 in the future const aiPipelineSpans = spans.filter(span => span.op === 'gen_ai.invoke_agent'); - const aiGenerateSpans = spans.filter(span => span.op === 'gen_ai.generate_text'); + const aiGenerateSpans = spans.filter(span => span.op === 'gen_ai.generate_content'); const toolCallSpans = spans.filter(span => span.op === 'gen_ai.execute_tool'); expect(aiPipelineSpans.length).toBeGreaterThanOrEqual(1); diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16/tests/ai-test.test.ts b/dev-packages/e2e-tests/test-applications/nextjs-16/tests/ai-test.test.ts index 5c519cb89a03..dcd129020035 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16/tests/ai-test.test.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-16/tests/ai-test.test.ts @@ -22,7 +22,7 @@ test('should create AI spans with correct attributes', async ({ page }) => { // because of this, only spans that are manually opted-in at call time will be captured // this may be fixed by https://github.com/vercel/ai/pull/6716 in the future const aiPipelineSpans = spans.filter(span => span.op === 'gen_ai.invoke_agent'); - const aiGenerateSpans = spans.filter(span => span.op === 'gen_ai.generate_text'); + const aiGenerateSpans = spans.filter(span => span.op === 'gen_ai.generate_content'); const toolCallSpans = spans.filter(span => span.op === 'gen_ai.execute_tool'); expect(aiPipelineSpans.length).toBeGreaterThanOrEqual(1); diff --git a/dev-packages/e2e-tests/test-applications/node-exports-test-app/scripts/consistentExports.ts b/dev-packages/e2e-tests/test-applications/node-exports-test-app/scripts/consistentExports.ts index e762909c9173..6ae689b80da3 100644 --- a/dev-packages/e2e-tests/test-applications/node-exports-test-app/scripts/consistentExports.ts +++ b/dev-packages/e2e-tests/test-applications/node-exports-test-app/scripts/consistentExports.ts @@ -21,6 +21,8 @@ const NODE_EXPORTS_IGNORE = [ 'SentryContextManager', 'validateOpenTelemetrySetup', 'preloadOpenTelemetry', + // Internal helper only needed within integrations (e.g. bunRuntimeMetricsIntegration) + '_INTERNAL_normalizeCollectionInterval', ]; const nodeExports = Object.keys(SentryNode).filter(e => !NODE_EXPORTS_IGNORE.includes(e)); diff --git a/dev-packages/e2e-tests/test-applications/node-express-cjs-preload/tests/server.test.ts b/dev-packages/e2e-tests/test-applications/node-express-cjs-preload/tests/server.test.ts index a403a23bebda..df5ba8e47352 100644 --- a/dev-packages/e2e-tests/test-applications/node-express-cjs-preload/tests/server.test.ts +++ b/dev-packages/e2e-tests/test-applications/node-express-cjs-preload/tests/server.test.ts @@ -65,12 +65,12 @@ test('Should record a transaction for route with parameters', async ({ request } data: { 'express.name': 'query', 'express.type': 'middleware', - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'middleware.express', }, op: 'middleware.express', description: 'query', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), @@ -83,12 +83,12 @@ test('Should record a transaction for route with parameters', async ({ request } data: { 'express.name': 'expressInit', 'express.type': 'middleware', - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'middleware.express', }, op: 'middleware.express', description: 'expressInit', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), @@ -102,12 +102,12 @@ test('Should record a transaction for route with parameters', async ({ request } 'express.name': '/test-transaction/:param', 'express.type': 'request_handler', 'http.route': '/test-transaction/:param', - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'request_handler.express', }, op: 'request_handler.express', description: '/test-transaction/:param', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), diff --git a/dev-packages/e2e-tests/test-applications/node-express-esm-loader/tests/server.test.ts b/dev-packages/e2e-tests/test-applications/node-express-esm-loader/tests/server.test.ts index d919c75ea61b..e6337bf7ba83 100644 --- a/dev-packages/e2e-tests/test-applications/node-express-esm-loader/tests/server.test.ts +++ b/dev-packages/e2e-tests/test-applications/node-express-esm-loader/tests/server.test.ts @@ -65,12 +65,12 @@ test('Should record a transaction for route with parameters', async ({ request } data: { 'express.name': 'query', 'express.type': 'middleware', - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'middleware.express', }, op: 'middleware.express', description: 'query', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), @@ -83,12 +83,12 @@ test('Should record a transaction for route with parameters', async ({ request } data: { 'express.name': 'expressInit', 'express.type': 'middleware', - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'middleware.express', }, op: 'middleware.express', description: 'expressInit', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), @@ -102,12 +102,12 @@ test('Should record a transaction for route with parameters', async ({ request } 'express.name': '/test-transaction/:param', 'express.type': 'request_handler', 'http.route': '/test-transaction/:param', - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'request_handler.express', }, op: 'request_handler.express', description: '/test-transaction/:param', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), diff --git a/dev-packages/e2e-tests/test-applications/node-express-esm-preload/tests/server.test.ts b/dev-packages/e2e-tests/test-applications/node-express-esm-preload/tests/server.test.ts index 706fe1b4460f..937f2b7acc27 100644 --- a/dev-packages/e2e-tests/test-applications/node-express-esm-preload/tests/server.test.ts +++ b/dev-packages/e2e-tests/test-applications/node-express-esm-preload/tests/server.test.ts @@ -65,12 +65,12 @@ test('Should record a transaction for route with parameters', async ({ request } data: { 'express.name': 'query', 'express.type': 'middleware', - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'middleware.express', }, op: 'middleware.express', description: 'query', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), @@ -83,12 +83,12 @@ test('Should record a transaction for route with parameters', async ({ request } data: { 'express.name': 'expressInit', 'express.type': 'middleware', - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'middleware.express', }, op: 'middleware.express', description: 'expressInit', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), @@ -102,12 +102,12 @@ test('Should record a transaction for route with parameters', async ({ request } 'express.name': '/test-transaction/:param', 'express.type': 'request_handler', 'http.route': '/test-transaction/:param', - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'request_handler.express', }, op: 'request_handler.express', description: '/test-transaction/:param', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), diff --git a/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/.npmrc b/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/.npmrc new file mode 100644 index 000000000000..070f80f05092 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/.npmrc @@ -0,0 +1,2 @@ +@sentry:registry=http://127.0.0.1:4873 +@sentry-internal:registry=http://127.0.0.1:4873 diff --git a/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/instrument.mjs b/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/instrument.mjs new file mode 100644 index 000000000000..f3dd95215d03 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/instrument.mjs @@ -0,0 +1,9 @@ +import * as Sentry from '@sentry/node'; + +Sentry.init({ + environment: 'qa', // dynamic sampling bias to keep transactions + dsn: process.env.E2E_TEST_DSN, + debug: !!process.env.DEBUG, + tunnel: `http://localhost:3031/`, // proxy server + tracesSampleRate: 1, +}); diff --git a/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/package.json b/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/package.json new file mode 100644 index 000000000000..6a5a293b956d --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/package.json @@ -0,0 +1,37 @@ +{ + "name": "node-express-mcp-v2-app", + "version": "1.0.0", + "private": true, + "scripts": { + "build": "tsc", + "start": "node --import ./instrument.mjs dist/app.js", + "test": "playwright test", + "clean": "npx rimraf node_modules pnpm-lock.yaml", + "test:build": "pnpm install && pnpm build", + "test:assert": "pnpm test" + }, + "dependencies": { + "@cfworker/json-schema": "^4.0.0", + "@modelcontextprotocol/server": "2.0.0-alpha.2", + "@modelcontextprotocol/node": "2.0.0-alpha.2", + "@sentry/node": "latest || *", + "@types/express": "^4.17.21", + "@types/node": "^18.19.1", + "express": "^4.21.2", + "typescript": "~5.0.0", + "zod": "^4.0.0" + }, + "devDependencies": { + "@modelcontextprotocol/client": "2.0.0-alpha.2", + "@playwright/test": "~1.56.0", + "@sentry-internal/test-utils": "link:../../../test-utils", + "@sentry/core": "latest || *" + }, + "type": "module", + "volta": { + "extends": "../../package.json" + }, + "sentryTest": { + "optional": true + } +} diff --git a/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/playwright.config.mjs b/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/playwright.config.mjs new file mode 100644 index 000000000000..31f2b913b58b --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/playwright.config.mjs @@ -0,0 +1,7 @@ +import { getPlaywrightConfig } from '@sentry-internal/test-utils'; + +const config = getPlaywrightConfig({ + startCommand: `pnpm start`, +}); + +export default config; diff --git a/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/src/app.ts b/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/src/app.ts new file mode 100644 index 000000000000..0fa1366dd2d6 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/src/app.ts @@ -0,0 +1,19 @@ +import * as Sentry from '@sentry/node'; +import express from 'express'; +import { mcpRouter } from './mcp.js'; + +const app = express(); +const port = 3030; + +app.use(express.json()); +app.use(mcpRouter); + +app.get('/test-success', function (_req, res) { + res.send({ version: 'v1' }); +}); + +Sentry.setupExpressErrorHandler(app); + +app.listen(port, () => { + console.log(`Example app listening on port ${port}`); +}); diff --git a/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/src/mcp.ts b/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/src/mcp.ts new file mode 100644 index 000000000000..6034032b46df --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/src/mcp.ts @@ -0,0 +1,125 @@ +import { randomUUID } from 'node:crypto'; +import express from 'express'; +import { McpServer, ResourceTemplate } from '@modelcontextprotocol/server'; +import { NodeStreamableHTTPServerTransport } from '@modelcontextprotocol/node'; +import { z } from 'zod'; +import { wrapMcpServerWithSentry } from '@sentry/node'; + +const mcpRouter = express.Router(); + +const server = wrapMcpServerWithSentry( + new McpServer({ + name: 'Echo-V2', + version: '2.0.0', + }), +); + +server.registerResource( + 'echo', + new ResourceTemplate('echo://{message}', { list: undefined }), + { title: 'Echo Resource' }, + async (uri, { message }) => ({ + contents: [ + { + uri: uri.href, + text: `Resource echo: ${message}`, + }, + ], + }), +); + +server.registerTool( + 'echo', + { description: 'Echo tool', inputSchema: z.object({ message: z.string() }) }, + async ({ message }) => ({ + content: [{ type: 'text', text: `Tool echo: ${message}` }], + }), +); + +server.registerPrompt( + 'echo', + { description: 'Echo prompt', argsSchema: z.object({ message: z.string() }) }, + ({ message }) => ({ + messages: [ + { + role: 'user', + content: { + type: 'text', + text: `Please process this message: ${message}`, + }, + }, + ], + }), +); + +server.registerTool('always-error', {}, async () => { + throw new Error('intentional error for span status testing'); +}); + +const transports: Record = {}; + +mcpRouter.post('/mcp', async (req, res) => { + const sessionId = req.headers['mcp-session-id'] as string | undefined; + + try { + let transport: NodeStreamableHTTPServerTransport; + + if (sessionId && transports[sessionId]) { + transport = transports[sessionId]; + } else if (!sessionId && req.body?.method === 'initialize') { + transport = new NodeStreamableHTTPServerTransport({ + sessionIdGenerator: () => randomUUID(), + onsessioninitialized: sid => { + transports[sid] = transport; + }, + }); + + transport.onclose = () => { + const sid = transport.sessionId; + if (sid && transports[sid]) { + delete transports[sid]; + } + }; + + await server.connect(transport); + } else { + res.status(400).json({ + jsonrpc: '2.0', + error: { code: -32000, message: 'Bad Request: No valid session ID provided' }, + id: null, + }); + return; + } + + await transport.handleRequest(req, res, req.body); + } catch (error) { + console.error('Error handling MCP request:', error); + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + error: { code: -32603, message: 'Internal server error' }, + id: null, + }); + } + } +}); + +mcpRouter.get('/mcp', async (req, res) => { + const sessionId = req.headers['mcp-session-id'] as string | undefined; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + await transports[sessionId].handleRequest(req, res); +}); + +mcpRouter.delete('/mcp', async (req, res) => { + const sessionId = req.headers['mcp-session-id'] as string | undefined; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + await transports[sessionId].handleRequest(req, res); +}); + +export { mcpRouter }; diff --git a/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/start-event-proxy.mjs b/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/start-event-proxy.mjs new file mode 100644 index 000000000000..7e4303f958d8 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/start-event-proxy.mjs @@ -0,0 +1,6 @@ +import { startEventProxyServer } from '@sentry-internal/test-utils'; + +startEventProxyServer({ + port: 3031, + proxyServerName: 'node-express-mcp-v2', +}); diff --git a/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/tests/mcp.test.ts b/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/tests/mcp.test.ts new file mode 100644 index 000000000000..776725c11cf2 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/tests/mcp.test.ts @@ -0,0 +1,129 @@ +import { expect, test } from '@playwright/test'; +import { waitForTransaction } from '@sentry-internal/test-utils'; +import { Client } from '@modelcontextprotocol/client'; +import { StreamableHTTPClientTransport } from '@modelcontextprotocol/client'; + +test('Should record transactions for MCP handlers using @modelcontextprotocol/sdk v2 (register* API)', async ({ + baseURL, +}) => { + const transport = new StreamableHTTPClientTransport(new URL(`${baseURL}/mcp`)); + + const client = new Client({ + name: 'test-client-v2', + version: '1.0.0', + }); + + const initializeTransactionPromise = waitForTransaction('node-express-mcp-v2', transactionEvent => { + return transactionEvent.transaction === 'initialize'; + }); + + await client.connect(transport); + + await test.step('initialize handshake', async () => { + const initializeTransaction = await initializeTransactionPromise; + expect(initializeTransaction).toBeDefined(); + expect(initializeTransaction.contexts?.trace?.op).toEqual('mcp.server'); + expect(initializeTransaction.contexts?.trace?.data?.['mcp.method.name']).toEqual('initialize'); + expect(initializeTransaction.contexts?.trace?.data?.['mcp.client.name']).toEqual('test-client-v2'); + expect(initializeTransaction.contexts?.trace?.data?.['mcp.server.name']).toEqual('Echo-V2'); + expect(initializeTransaction.contexts?.trace?.data?.['mcp.transport']).toMatch(/StreamableHTTPServerTransport/); + }); + + await test.step('registerTool handler', async () => { + const toolTransactionPromise = waitForTransaction('node-express-mcp-v2', transactionEvent => { + return transactionEvent.transaction === 'tools/call echo'; + }); + + const toolResult = await client.callTool({ + name: 'echo', + arguments: { + message: 'foobar', + }, + }); + + expect(toolResult).toMatchObject({ + content: [ + { + text: 'Tool echo: foobar', + type: 'text', + }, + ], + }); + + const toolTransaction = await toolTransactionPromise; + expect(toolTransaction).toBeDefined(); + expect(toolTransaction.contexts?.trace?.op).toEqual('mcp.server'); + expect(toolTransaction.contexts?.trace?.data?.['mcp.method.name']).toEqual('tools/call'); + expect(toolTransaction.contexts?.trace?.data?.['mcp.tool.name']).toEqual('echo'); + // Proves span was completed with results (span correlation worked end-to-end) + expect(toolTransaction.contexts?.trace?.data?.['mcp.tool.result.content_count']).toEqual(1); + }); + + await test.step('registerResource handler', async () => { + const resourceTransactionPromise = waitForTransaction('node-express-mcp-v2', transactionEvent => { + return transactionEvent.transaction === 'resources/read echo://foobar'; + }); + + const resourceResult = await client.readResource({ + uri: 'echo://foobar', + }); + + expect(resourceResult).toMatchObject({ + contents: [{ text: 'Resource echo: foobar', uri: 'echo://foobar' }], + }); + + const resourceTransaction = await resourceTransactionPromise; + expect(resourceTransaction).toBeDefined(); + expect(resourceTransaction.contexts?.trace?.op).toEqual('mcp.server'); + expect(resourceTransaction.contexts?.trace?.data?.['mcp.method.name']).toEqual('resources/read'); + }); + + await test.step('registerPrompt handler', async () => { + const promptTransactionPromise = waitForTransaction('node-express-mcp-v2', transactionEvent => { + return transactionEvent.transaction === 'prompts/get echo'; + }); + + const promptResult = await client.getPrompt({ + name: 'echo', + arguments: { + message: 'foobar', + }, + }); + + expect(promptResult).toMatchObject({ + messages: [ + { + content: { + text: 'Please process this message: foobar', + type: 'text', + }, + role: 'user', + }, + ], + }); + + const promptTransaction = await promptTransactionPromise; + expect(promptTransaction).toBeDefined(); + expect(promptTransaction.contexts?.trace?.op).toEqual('mcp.server'); + expect(promptTransaction.contexts?.trace?.data?.['mcp.method.name']).toEqual('prompts/get'); + }); + + await test.step('error tool sets span status to internal_error', async () => { + const toolTransactionPromise = waitForTransaction('node-express-mcp-v2', transactionEvent => { + return transactionEvent.transaction === 'tools/call always-error'; + }); + + try { + await client.callTool({ name: 'always-error', arguments: {} }); + } catch { + // Expected: MCP SDK throws when the tool returns a JSON-RPC error + } + + const toolTransaction = await toolTransactionPromise; + expect(toolTransaction).toBeDefined(); + expect(toolTransaction.contexts?.trace?.op).toEqual('mcp.server'); + expect(toolTransaction.contexts?.trace?.status).toEqual('internal_error'); + }); + + await client.close(); +}); diff --git a/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/tsconfig.json b/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/tsconfig.json new file mode 100644 index 000000000000..21ecf1357722 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/node-express-mcp-v2/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "types": ["node"], + "esModuleInterop": true, + "lib": ["es2020"], + "module": "NodeNext", + "moduleResolution": "NodeNext", + "strict": true, + "outDir": "dist", + "skipLibCheck": true + }, + "include": ["src/**/*.ts"] +} diff --git a/dev-packages/e2e-tests/test-applications/node-express-v5/src/mcp.ts b/dev-packages/e2e-tests/test-applications/node-express-v5/src/mcp.ts index a819858c8f37..09472a9288be 100644 --- a/dev-packages/e2e-tests/test-applications/node-express-v5/src/mcp.ts +++ b/dev-packages/e2e-tests/test-applications/node-express-v5/src/mcp.ts @@ -35,6 +35,14 @@ server.tool('echo', { message: z.string() }, async ({ message }, rest) => { }; }); +server.registerTool( + 'echo-register', + { description: 'Echo tool (register API)', inputSchema: { message: z.string() } }, + async ({ message }) => ({ + content: [{ type: 'text', text: `registerTool echo: ${message}` }], + }), +); + server.prompt('echo', { message: z.string() }, ({ message }, extra) => ({ messages: [ { @@ -47,6 +55,10 @@ server.prompt('echo', { message: z.string() }, ({ message }, extra) => ({ ], })); +server.tool('always-error', {}, async () => { + throw new Error('intentional error for span status testing'); +}); + const transports: Record = {}; mcpRouter.get('/sse', async (_, res) => { @@ -103,6 +115,14 @@ streamableServer.tool('echo', { message: z.string() }, async ({ message }) => { }; }); +streamableServer.registerTool( + 'echo-register', + { description: 'Echo tool (register API)', inputSchema: { message: z.string() } }, + async ({ message }) => ({ + content: [{ type: 'text', text: `registerTool echo: ${message}` }], + }), +); + streamableServer.prompt('echo', { message: z.string() }, ({ message }) => ({ messages: [ { diff --git a/dev-packages/e2e-tests/test-applications/node-express-v5/tests/mcp.test.ts b/dev-packages/e2e-tests/test-applications/node-express-v5/tests/mcp.test.ts index 73dfc1d69432..c943ebfd4ab1 100644 --- a/dev-packages/e2e-tests/test-applications/node-express-v5/tests/mcp.test.ts +++ b/dev-packages/e2e-tests/test-applications/node-express-v5/tests/mcp.test.ts @@ -60,6 +60,38 @@ test('Should record transactions for mcp handlers', async ({ baseURL }) => { // TODO: When https://github.com/modelcontextprotocol/typescript-sdk/pull/358 is released check for trace id equality between the post transaction and the handler transaction }); + await test.step('registerTool handler', async () => { + const postTransactionPromise = waitForTransaction('node-express-v5', transactionEvent => { + return transactionEvent.transaction === 'POST /messages'; + }); + const toolTransactionPromise = waitForTransaction('node-express-v5', transactionEvent => { + return transactionEvent.transaction === 'tools/call echo-register'; + }); + + const toolResult = await client.callTool({ + name: 'echo-register', + arguments: { + message: 'foobar', + }, + }); + + expect(toolResult).toMatchObject({ + content: [ + { + text: 'registerTool echo: foobar', + type: 'text', + }, + ], + }); + + const postTransaction = await postTransactionPromise; + expect(postTransaction).toBeDefined(); + + const toolTransaction = await toolTransactionPromise; + expect(toolTransaction).toBeDefined(); + expect(toolTransaction.contexts?.trace?.data?.['mcp.tool.name']).toEqual('echo-register'); + }); + await test.step('resource handler', async () => { const postTransactionPromise = waitForTransaction('node-express-v5', transactionEvent => { return transactionEvent.transaction === 'POST /messages'; @@ -120,6 +152,23 @@ test('Should record transactions for mcp handlers', async ({ baseURL }) => { // TODO: When https://github.com/modelcontextprotocol/typescript-sdk/pull/358 is released check for trace id equality between the post transaction and the handler transaction }); + + await test.step('error tool sets span status to internal_error', async () => { + const toolTransactionPromise = waitForTransaction('node-express-v5', transactionEvent => { + return transactionEvent.transaction === 'tools/call always-error'; + }); + + try { + await client.callTool({ name: 'always-error', arguments: {} }); + } catch { + // Expected: MCP SDK throws when the tool returns a JSON-RPC error + } + + const toolTransaction = await toolTransactionPromise; + expect(toolTransaction).toBeDefined(); + expect(toolTransaction.contexts?.trace?.op).toEqual('mcp.server'); + expect(toolTransaction.contexts?.trace?.status).toEqual('internal_error'); + }); }); /** diff --git a/dev-packages/e2e-tests/test-applications/node-express-v5/tests/transactions.test.ts b/dev-packages/e2e-tests/test-applications/node-express-v5/tests/transactions.test.ts index 048f70a1aba8..ba9632aaf952 100644 --- a/dev-packages/e2e-tests/test-applications/node-express-v5/tests/transactions.test.ts +++ b/dev-packages/e2e-tests/test-applications/node-express-v5/tests/transactions.test.ts @@ -85,7 +85,7 @@ test('Sends an API route transaction', async ({ baseURL }) => { // auto instrumented span expect(spans).toContainEqual({ data: { - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'request_handler.express', 'http.route': '/test-transaction', 'express.name': '/test-transaction', @@ -93,7 +93,7 @@ test('Sends an API route transaction', async ({ baseURL }) => { }, description: '/test-transaction', op: 'request_handler.express', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), diff --git a/dev-packages/e2e-tests/test-applications/node-express/src/mcp.ts b/dev-packages/e2e-tests/test-applications/node-express/src/mcp.ts index 638462423d11..72c4535a3d6f 100644 --- a/dev-packages/e2e-tests/test-applications/node-express/src/mcp.ts +++ b/dev-packages/e2e-tests/test-applications/node-express/src/mcp.ts @@ -35,6 +35,14 @@ server.tool('echo', { message: z.string() }, async ({ message }, rest) => { }; }); +server.registerTool( + 'echo-register', + { description: 'Echo tool (register API)', inputSchema: { message: z.string() } }, + async ({ message }) => ({ + content: [{ type: 'text', text: `registerTool echo: ${message}` }], + }), +); + server.prompt('echo', { message: z.string() }, ({ message }, extra) => ({ messages: [ { @@ -47,6 +55,10 @@ server.prompt('echo', { message: z.string() }, ({ message }, extra) => ({ ], })); +server.tool('always-error', {}, async () => { + throw new Error('intentional error for span status testing'); +}); + const transports: Record = {}; mcpRouter.get('/sse', async (_, res) => { @@ -103,6 +115,14 @@ streamableServer.tool('echo', { message: z.string() }, async ({ message }) => { }; }); +streamableServer.registerTool( + 'echo-register', + { description: 'Echo tool (register API)', inputSchema: { message: z.string() } }, + async ({ message }) => ({ + content: [{ type: 'text', text: `registerTool echo: ${message}` }], + }), +); + streamableServer.prompt('echo', { message: z.string() }, ({ message }) => ({ messages: [ { diff --git a/dev-packages/e2e-tests/test-applications/node-express/tests/mcp.test.ts b/dev-packages/e2e-tests/test-applications/node-express/tests/mcp.test.ts index 143867c773e6..504bfaffcd27 100644 --- a/dev-packages/e2e-tests/test-applications/node-express/tests/mcp.test.ts +++ b/dev-packages/e2e-tests/test-applications/node-express/tests/mcp.test.ts @@ -62,6 +62,41 @@ test('Should record transactions for mcp handlers', async ({ baseURL }) => { // TODO: When https://github.com/modelcontextprotocol/typescript-sdk/pull/358 is released check for trace id equality between the post transaction and the handler transaction }); + await test.step('registerTool handler', async () => { + const postTransactionPromise = waitForTransaction('node-express', transactionEvent => { + return transactionEvent.transaction === 'POST /messages'; + }); + const toolTransactionPromise = waitForTransaction('node-express', transactionEvent => { + return transactionEvent.transaction === 'tools/call echo-register'; + }); + + const toolResult = await client.callTool({ + name: 'echo-register', + arguments: { + message: 'foobar', + }, + }); + + expect(toolResult).toMatchObject({ + content: [ + { + text: 'registerTool echo: foobar', + type: 'text', + }, + ], + }); + + const postTransaction = await postTransactionPromise; + expect(postTransaction).toBeDefined(); + expect(postTransaction.contexts?.trace?.op).toEqual('http.server'); + + const toolTransaction = await toolTransactionPromise; + expect(toolTransaction).toBeDefined(); + expect(toolTransaction.contexts?.trace?.op).toEqual('mcp.server'); + expect(toolTransaction.contexts?.trace?.data?.['mcp.method.name']).toEqual('tools/call'); + expect(toolTransaction.contexts?.trace?.data?.['mcp.tool.name']).toEqual('echo-register'); + }); + await test.step('resource handler', async () => { const postTransactionPromise = waitForTransaction('node-express', transactionEvent => { return transactionEvent.transaction === 'POST /messages'; @@ -126,6 +161,23 @@ test('Should record transactions for mcp handlers', async ({ baseURL }) => { expect(promptTransaction.contexts?.trace?.data?.['mcp.method.name']).toEqual('prompts/get'); // TODO: When https://github.com/modelcontextprotocol/typescript-sdk/pull/358 is released check for trace id equality between the post transaction and the handler transaction }); + + await test.step('error tool sets span status to internal_error', async () => { + const toolTransactionPromise = waitForTransaction('node-express', transactionEvent => { + return transactionEvent.transaction === 'tools/call always-error'; + }); + + try { + await client.callTool({ name: 'always-error', arguments: {} }); + } catch { + // Expected: MCP SDK throws when the tool returns a JSON-RPC error + } + + const toolTransaction = await toolTransactionPromise; + expect(toolTransaction).toBeDefined(); + expect(toolTransaction.contexts?.trace?.op).toEqual('mcp.server'); + expect(toolTransaction.contexts?.trace?.status).toEqual('internal_error'); + }); }); /** diff --git a/dev-packages/e2e-tests/test-applications/node-express/tests/transactions.test.ts b/dev-packages/e2e-tests/test-applications/node-express/tests/transactions.test.ts index 7784d7fbe3fe..c0c286da3345 100644 --- a/dev-packages/e2e-tests/test-applications/node-express/tests/transactions.test.ts +++ b/dev-packages/e2e-tests/test-applications/node-express/tests/transactions.test.ts @@ -85,14 +85,14 @@ test('Sends an API route transaction', async ({ baseURL }) => { // auto instrumented spans expect(spans).toContainEqual({ data: { - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'middleware.express', 'express.name': 'query', 'express.type': 'middleware', }, description: 'query', op: 'middleware.express', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), @@ -103,14 +103,14 @@ test('Sends an API route transaction', async ({ baseURL }) => { expect(spans).toContainEqual({ data: { - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'middleware.express', 'express.name': 'expressInit', 'express.type': 'middleware', }, description: 'expressInit', op: 'middleware.express', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), @@ -121,7 +121,7 @@ test('Sends an API route transaction', async ({ baseURL }) => { expect(spans).toContainEqual({ data: { - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'request_handler.express', 'http.route': '/test-transaction', 'express.name': '/test-transaction', @@ -129,7 +129,7 @@ test('Sends an API route transaction', async ({ baseURL }) => { }, description: '/test-transaction', op: 'request_handler.express', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), @@ -161,14 +161,14 @@ test('Sends an API route transaction for an errored route', async ({ baseURL }) expect(spans).toContainEqual({ data: { - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'middleware.express', 'express.name': 'query', 'express.type': 'middleware', }, description: 'query', op: 'middleware.express', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), @@ -179,14 +179,14 @@ test('Sends an API route transaction for an errored route', async ({ baseURL }) expect(spans).toContainEqual({ data: { - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'middleware.express', 'express.name': 'expressInit', 'express.type': 'middleware', }, description: 'expressInit', op: 'middleware.express', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), @@ -197,7 +197,7 @@ test('Sends an API route transaction for an errored route', async ({ baseURL }) expect(spans).toContainEqual({ data: { - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'request_handler.express', 'http.route': '/test-exception/:id', 'express.name': '/test-exception/:id', @@ -205,14 +205,13 @@ test('Sends an API route transaction for an errored route', async ({ baseURL }) }, description: '/test-exception/:id', op: 'request_handler.express', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), status: 'internal_error', timestamp: expect.any(Number), trace_id: expect.stringMatching(/[a-f0-9]{32}/), - measurements: {}, }); }); diff --git a/dev-packages/e2e-tests/test-applications/node-otel-custom-sampler/tests/sampling.test.ts b/dev-packages/e2e-tests/test-applications/node-otel-custom-sampler/tests/sampling.test.ts index 84d783b1d567..49d35cb9e85f 100644 --- a/dev-packages/e2e-tests/test-applications/node-otel-custom-sampler/tests/sampling.test.ts +++ b/dev-packages/e2e-tests/test-applications/node-otel-custom-sampler/tests/sampling.test.ts @@ -55,7 +55,7 @@ test('Sends a sampled API route transaction', async ({ baseURL }) => { span_id: expect.stringMatching(/[a-f0-9]{16}/), trace_id: expect.stringMatching(/[a-f0-9]{32}/), data: { - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'middleware.express', 'express.name': 'query', 'express.type': 'middleware', @@ -66,14 +66,14 @@ test('Sends a sampled API route transaction', async ({ baseURL }) => { timestamp: expect.any(Number), status: 'ok', op: 'middleware.express', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', }); expect(transactionEvent.spans).toContainEqual({ span_id: expect.stringMatching(/[a-f0-9]{16}/), trace_id: expect.stringMatching(/[a-f0-9]{32}/), data: { - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'middleware.express', 'express.name': 'expressInit', 'express.type': 'middleware', @@ -84,14 +84,14 @@ test('Sends a sampled API route transaction', async ({ baseURL }) => { timestamp: expect.any(Number), status: 'ok', op: 'middleware.express', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', }); expect(transactionEvent.spans).toContainEqual({ span_id: expect.stringMatching(/[a-f0-9]{16}/), trace_id: expect.stringMatching(/[a-f0-9]{32}/), data: { - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'request_handler.express', 'http.route': '/task', 'express.name': '/task', @@ -103,7 +103,7 @@ test('Sends a sampled API route transaction', async ({ baseURL }) => { timestamp: expect.any(Number), status: 'ok', op: 'request_handler.express', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', }); expect(transactionEvent.spans).toContainEqual({ diff --git a/dev-packages/e2e-tests/test-applications/node-otel-sdk-node/tests/transactions.test.ts b/dev-packages/e2e-tests/test-applications/node-otel-sdk-node/tests/transactions.test.ts index f724eee3fc64..299d3c2b80ec 100644 --- a/dev-packages/e2e-tests/test-applications/node-otel-sdk-node/tests/transactions.test.ts +++ b/dev-packages/e2e-tests/test-applications/node-otel-sdk-node/tests/transactions.test.ts @@ -79,14 +79,14 @@ test('Sends an API route transaction', async ({ baseURL }) => { expect(spans).toContainEqual({ data: { - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'middleware.express', 'express.name': 'query', 'express.type': 'middleware', }, description: 'query', op: 'middleware.express', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), @@ -97,14 +97,14 @@ test('Sends an API route transaction', async ({ baseURL }) => { expect(spans).toContainEqual({ data: { - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'middleware.express', 'express.name': 'expressInit', 'express.type': 'middleware', }, description: 'expressInit', op: 'middleware.express', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), @@ -115,7 +115,7 @@ test('Sends an API route transaction', async ({ baseURL }) => { expect(spans).toContainEqual({ data: { - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'request_handler.express', 'http.route': '/test-transaction', 'express.name': '/test-transaction', @@ -123,7 +123,7 @@ test('Sends an API route transaction', async ({ baseURL }) => { }, description: '/test-transaction', op: 'request_handler.express', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), @@ -155,14 +155,14 @@ test('Sends an API route transaction for an errored route', async ({ baseURL }) expect(spans).toContainEqual({ data: { - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'middleware.express', 'express.name': 'query', 'express.type': 'middleware', }, description: 'query', op: 'middleware.express', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), @@ -173,14 +173,14 @@ test('Sends an API route transaction for an errored route', async ({ baseURL }) expect(spans).toContainEqual({ data: { - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'middleware.express', 'express.name': 'expressInit', 'express.type': 'middleware', }, description: 'expressInit', op: 'middleware.express', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), @@ -191,7 +191,7 @@ test('Sends an API route transaction for an errored route', async ({ baseURL }) expect(spans).toContainEqual({ data: { - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'request_handler.express', 'http.route': '/test-exception/:id', 'express.name': '/test-exception/:id', @@ -199,13 +199,12 @@ test('Sends an API route transaction for an errored route', async ({ baseURL }) }, description: '/test-exception/:id', op: 'request_handler.express', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), status: 'internal_error', timestamp: expect.any(Number), trace_id: expect.stringMatching(/[a-f0-9]{32}/), - measurements: {}, }); }); diff --git a/dev-packages/e2e-tests/test-applications/node-otel/tests/transactions.test.ts b/dev-packages/e2e-tests/test-applications/node-otel/tests/transactions.test.ts index 8a561e91a76a..ba77e6a3b294 100644 --- a/dev-packages/e2e-tests/test-applications/node-otel/tests/transactions.test.ts +++ b/dev-packages/e2e-tests/test-applications/node-otel/tests/transactions.test.ts @@ -79,14 +79,14 @@ test('Sends an API route transaction', async ({ baseURL }) => { expect(spans).toContainEqual({ data: { - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'middleware.express', 'express.name': 'query', 'express.type': 'middleware', }, description: 'query', op: 'middleware.express', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), @@ -97,14 +97,14 @@ test('Sends an API route transaction', async ({ baseURL }) => { expect(spans).toContainEqual({ data: { - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'middleware.express', 'express.name': 'expressInit', 'express.type': 'middleware', }, description: 'expressInit', op: 'middleware.express', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), @@ -115,7 +115,7 @@ test('Sends an API route transaction', async ({ baseURL }) => { expect(spans).toContainEqual({ data: { - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'request_handler.express', 'http.route': '/test-transaction', 'express.name': '/test-transaction', @@ -123,7 +123,7 @@ test('Sends an API route transaction', async ({ baseURL }) => { }, description: '/test-transaction', op: 'request_handler.express', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), @@ -155,14 +155,14 @@ test('Sends an API route transaction for an errored route', async ({ baseURL }) expect(spans).toContainEqual({ data: { - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'middleware.express', 'express.name': 'query', 'express.type': 'middleware', }, description: 'query', op: 'middleware.express', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), @@ -173,14 +173,14 @@ test('Sends an API route transaction for an errored route', async ({ baseURL }) expect(spans).toContainEqual({ data: { - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'middleware.express', 'express.name': 'expressInit', 'express.type': 'middleware', }, description: 'expressInit', op: 'middleware.express', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), @@ -191,7 +191,7 @@ test('Sends an API route transaction for an errored route', async ({ baseURL }) expect(spans).toContainEqual({ data: { - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'request_handler.express', 'http.route': '/test-exception/:id', 'express.name': '/test-exception/:id', @@ -199,13 +199,12 @@ test('Sends an API route transaction for an errored route', async ({ baseURL }) }, description: '/test-exception/:id', op: 'request_handler.express', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), status: 'internal_error', timestamp: expect.any(Number), trace_id: expect.stringMatching(/[a-f0-9]{32}/), - measurements: {}, }); }); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/package.json b/dev-packages/e2e-tests/test-applications/nuxt-5/package.json index ad5b209a6b22..aa8296bc3314 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-5/package.json +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/package.json @@ -31,6 +31,9 @@ "@playwright/test": "~1.56.0", "@sentry-internal/test-utils": "link:../../../test-utils" }, + "sentryTest": { + "optional": true + }, "volta": { "extends": "../../package.json", "node": "22.20.0" diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/tracing.cached-html.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/tracing.cached-html.test.ts index 7c7d51af4d4f..3a6614f5cb4d 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/tracing.cached-html.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/tracing.cached-html.test.ts @@ -14,13 +14,11 @@ test.describe('Rendering Modes with Cached HTML', () => { await testChangingTracingMetaTagsOnISRPage(page, '/rendering-modes/isr-1h-cached-page', 'ISR 1h Cached Page'); }); - // TODO: Make test work with Nuxt 5 - test.skip('exclude tracing meta tags on SWR-cached page', async ({ page }) => { + test('exclude tracing meta tags on SWR-cached page', async ({ page }) => { await testExcludeTracingMetaTagsOnCachedPage(page, '/rendering-modes/swr-cached-page', 'SWR Cached Page'); }); - // TODO: Make test work with Nuxt 5 - test.skip('exclude tracing meta tags on SWR 1h cached page', async ({ page }) => { + test('exclude tracing meta tags on SWR 1h cached page', async ({ page }) => { await testExcludeTracingMetaTagsOnCachedPage(page, '/rendering-modes/swr-1h-cached-page', 'SWR 1h Cached Page'); }); diff --git a/dev-packages/e2e-tests/test-applications/react-router-7-framework-custom/app/entry.client.tsx b/dev-packages/e2e-tests/test-applications/react-router-7-framework-custom/app/entry.client.tsx index 925c1e6ab143..005268b40ad0 100644 --- a/dev-packages/e2e-tests/test-applications/react-router-7-framework-custom/app/entry.client.tsx +++ b/dev-packages/e2e-tests/test-applications/react-router-7-framework-custom/app/entry.client.tsx @@ -17,7 +17,7 @@ startTransition(() => { hydrateRoot( document, - + , ); }); diff --git a/dev-packages/e2e-tests/test-applications/react-router-7-framework-custom/app/root.tsx b/dev-packages/e2e-tests/test-applications/react-router-7-framework-custom/app/root.tsx index 227c08f7730c..bc1b8f1236c0 100644 --- a/dev-packages/e2e-tests/test-applications/react-router-7-framework-custom/app/root.tsx +++ b/dev-packages/e2e-tests/test-applications/react-router-7-framework-custom/app/root.tsx @@ -1,4 +1,3 @@ -import * as Sentry from '@sentry/react-router'; import { Links, Meta, Outlet, Scripts, ScrollRestoration, isRouteErrorResponse } from 'react-router'; import type { Route } from './+types/root'; import stylesheet from './app.css?url'; @@ -48,7 +47,6 @@ export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) { message = error.status === 404 ? '404' : 'Error'; details = error.status === 404 ? 'The requested page could not be found.' : error.statusText || details; } else if (error && error instanceof Error) { - Sentry.captureException(error); if (import.meta.env.DEV) { details = error.message; stack = error.stack; diff --git a/dev-packages/e2e-tests/test-applications/react-router-7-framework-custom/tests/errors/errors.client.test.ts b/dev-packages/e2e-tests/test-applications/react-router-7-framework-custom/tests/errors/errors.client.test.ts index d6c80924c121..c1a7de46f1b6 100644 --- a/dev-packages/e2e-tests/test-applications/react-router-7-framework-custom/tests/errors/errors.client.test.ts +++ b/dev-packages/e2e-tests/test-applications/react-router-7-framework-custom/tests/errors/errors.client.test.ts @@ -100,7 +100,8 @@ test.describe('client-side errors', () => { type: 'Error', value: errorMessage, mechanism: { - handled: true, + handled: false, + type: 'auto.function.react_router.on_error', }, }, ], @@ -127,7 +128,8 @@ test.describe('client-side errors', () => { type: 'Error', value: errorMessage, mechanism: { - handled: true, + handled: false, + type: 'auto.function.react_router.on_error', }, }, ], diff --git a/dev-packages/e2e-tests/test-applications/react-router-7-framework-instrumentation/app/entry.client.tsx b/dev-packages/e2e-tests/test-applications/react-router-7-framework-instrumentation/app/entry.client.tsx index c8bd9df2ba99..9c9ccd812edd 100644 --- a/dev-packages/e2e-tests/test-applications/react-router-7-framework-instrumentation/app/entry.client.tsx +++ b/dev-packages/e2e-tests/test-applications/react-router-7-framework-instrumentation/app/entry.client.tsx @@ -27,7 +27,7 @@ startTransition(() => { document, {/* unstable_instrumentations is React Router 7.x's prop name (will become `instrumentations` in v8) */} - + , ); }); diff --git a/dev-packages/e2e-tests/test-applications/react-router-7-framework-instrumentation/app/root.tsx b/dev-packages/e2e-tests/test-applications/react-router-7-framework-instrumentation/app/root.tsx index 227c08f7730c..bc1b8f1236c0 100644 --- a/dev-packages/e2e-tests/test-applications/react-router-7-framework-instrumentation/app/root.tsx +++ b/dev-packages/e2e-tests/test-applications/react-router-7-framework-instrumentation/app/root.tsx @@ -1,4 +1,3 @@ -import * as Sentry from '@sentry/react-router'; import { Links, Meta, Outlet, Scripts, ScrollRestoration, isRouteErrorResponse } from 'react-router'; import type { Route } from './+types/root'; import stylesheet from './app.css?url'; @@ -48,7 +47,6 @@ export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) { message = error.status === 404 ? '404' : 'Error'; details = error.status === 404 ? 'The requested page could not be found.' : error.statusText || details; } else if (error && error instanceof Error) { - Sentry.captureException(error); if (import.meta.env.DEV) { details = error.message; stack = error.stack; diff --git a/dev-packages/e2e-tests/test-applications/react-router-7-framework-node-20-18/app/entry.client.tsx b/dev-packages/e2e-tests/test-applications/react-router-7-framework-node-20-18/app/entry.client.tsx index 925c1e6ab143..005268b40ad0 100644 --- a/dev-packages/e2e-tests/test-applications/react-router-7-framework-node-20-18/app/entry.client.tsx +++ b/dev-packages/e2e-tests/test-applications/react-router-7-framework-node-20-18/app/entry.client.tsx @@ -17,7 +17,7 @@ startTransition(() => { hydrateRoot( document, - + , ); }); diff --git a/dev-packages/e2e-tests/test-applications/react-router-7-framework-node-20-18/app/root.tsx b/dev-packages/e2e-tests/test-applications/react-router-7-framework-node-20-18/app/root.tsx index 227c08f7730c..bc1b8f1236c0 100644 --- a/dev-packages/e2e-tests/test-applications/react-router-7-framework-node-20-18/app/root.tsx +++ b/dev-packages/e2e-tests/test-applications/react-router-7-framework-node-20-18/app/root.tsx @@ -1,4 +1,3 @@ -import * as Sentry from '@sentry/react-router'; import { Links, Meta, Outlet, Scripts, ScrollRestoration, isRouteErrorResponse } from 'react-router'; import type { Route } from './+types/root'; import stylesheet from './app.css?url'; @@ -48,7 +47,6 @@ export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) { message = error.status === 404 ? '404' : 'Error'; details = error.status === 404 ? 'The requested page could not be found.' : error.statusText || details; } else if (error && error instanceof Error) { - Sentry.captureException(error); if (import.meta.env.DEV) { details = error.message; stack = error.stack; diff --git a/dev-packages/e2e-tests/test-applications/react-router-7-framework-node-20-18/tests/errors/errors.client.test.ts b/dev-packages/e2e-tests/test-applications/react-router-7-framework-node-20-18/tests/errors/errors.client.test.ts index d6c80924c121..c1a7de46f1b6 100644 --- a/dev-packages/e2e-tests/test-applications/react-router-7-framework-node-20-18/tests/errors/errors.client.test.ts +++ b/dev-packages/e2e-tests/test-applications/react-router-7-framework-node-20-18/tests/errors/errors.client.test.ts @@ -100,7 +100,8 @@ test.describe('client-side errors', () => { type: 'Error', value: errorMessage, mechanism: { - handled: true, + handled: false, + type: 'auto.function.react_router.on_error', }, }, ], @@ -127,7 +128,8 @@ test.describe('client-side errors', () => { type: 'Error', value: errorMessage, mechanism: { - handled: true, + handled: false, + type: 'auto.function.react_router.on_error', }, }, ], diff --git a/dev-packages/e2e-tests/test-applications/react-router-7-framework-spa-node-20-18/app/entry.client.tsx b/dev-packages/e2e-tests/test-applications/react-router-7-framework-spa-node-20-18/app/entry.client.tsx index 223c8e6129dd..f9e8c5139d22 100644 --- a/dev-packages/e2e-tests/test-applications/react-router-7-framework-spa-node-20-18/app/entry.client.tsx +++ b/dev-packages/e2e-tests/test-applications/react-router-7-framework-spa-node-20-18/app/entry.client.tsx @@ -17,7 +17,7 @@ startTransition(() => { hydrateRoot( document, - + , ); }); diff --git a/dev-packages/e2e-tests/test-applications/react-router-7-framework-spa-node-20-18/app/root.tsx b/dev-packages/e2e-tests/test-applications/react-router-7-framework-spa-node-20-18/app/root.tsx index 194d91eea422..2a3279aed365 100644 --- a/dev-packages/e2e-tests/test-applications/react-router-7-framework-spa-node-20-18/app/root.tsx +++ b/dev-packages/e2e-tests/test-applications/react-router-7-framework-spa-node-20-18/app/root.tsx @@ -2,7 +2,6 @@ import { isRouteErrorResponse, Links, Meta, Outlet, Scripts, ScrollRestoration } import type { Route } from './+types/root'; import './app.css'; -import * as Sentry from '@sentry/react-router'; export function Layout({ children }: { children: React.ReactNode }) { return ( @@ -35,8 +34,6 @@ export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) { message = error.status === 404 ? '404' : 'Error'; details = error.status === 404 ? 'The requested page could not be found.' : error.statusText || details; } else if (error && error instanceof Error) { - Sentry.captureException(error); - details = error.message; stack = error.stack; } diff --git a/dev-packages/e2e-tests/test-applications/react-router-7-framework-spa-node-20-18/tests/errors/errors.client.test.ts b/dev-packages/e2e-tests/test-applications/react-router-7-framework-spa-node-20-18/tests/errors/errors.client.test.ts index d6c80924c121..c1a7de46f1b6 100644 --- a/dev-packages/e2e-tests/test-applications/react-router-7-framework-spa-node-20-18/tests/errors/errors.client.test.ts +++ b/dev-packages/e2e-tests/test-applications/react-router-7-framework-spa-node-20-18/tests/errors/errors.client.test.ts @@ -100,7 +100,8 @@ test.describe('client-side errors', () => { type: 'Error', value: errorMessage, mechanism: { - handled: true, + handled: false, + type: 'auto.function.react_router.on_error', }, }, ], @@ -127,7 +128,8 @@ test.describe('client-side errors', () => { type: 'Error', value: errorMessage, mechanism: { - handled: true, + handled: false, + type: 'auto.function.react_router.on_error', }, }, ], diff --git a/dev-packages/e2e-tests/test-applications/react-router-7-framework-spa/app/entry.client.tsx b/dev-packages/e2e-tests/test-applications/react-router-7-framework-spa/app/entry.client.tsx index 7448ebe7bfe2..249e18d27c08 100644 --- a/dev-packages/e2e-tests/test-applications/react-router-7-framework-spa/app/entry.client.tsx +++ b/dev-packages/e2e-tests/test-applications/react-router-7-framework-spa/app/entry.client.tsx @@ -17,7 +17,7 @@ startTransition(() => { hydrateRoot( document, - + , ); }); diff --git a/dev-packages/e2e-tests/test-applications/react-router-7-framework-spa/app/root.tsx b/dev-packages/e2e-tests/test-applications/react-router-7-framework-spa/app/root.tsx index 194d91eea422..2a3279aed365 100644 --- a/dev-packages/e2e-tests/test-applications/react-router-7-framework-spa/app/root.tsx +++ b/dev-packages/e2e-tests/test-applications/react-router-7-framework-spa/app/root.tsx @@ -2,7 +2,6 @@ import { isRouteErrorResponse, Links, Meta, Outlet, Scripts, ScrollRestoration } import type { Route } from './+types/root'; import './app.css'; -import * as Sentry from '@sentry/react-router'; export function Layout({ children }: { children: React.ReactNode }) { return ( @@ -35,8 +34,6 @@ export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) { message = error.status === 404 ? '404' : 'Error'; details = error.status === 404 ? 'The requested page could not be found.' : error.statusText || details; } else if (error && error instanceof Error) { - Sentry.captureException(error); - details = error.message; stack = error.stack; } diff --git a/dev-packages/e2e-tests/test-applications/react-router-7-framework-spa/tests/errors/errors.client.test.ts b/dev-packages/e2e-tests/test-applications/react-router-7-framework-spa/tests/errors/errors.client.test.ts index d6c80924c121..c1a7de46f1b6 100644 --- a/dev-packages/e2e-tests/test-applications/react-router-7-framework-spa/tests/errors/errors.client.test.ts +++ b/dev-packages/e2e-tests/test-applications/react-router-7-framework-spa/tests/errors/errors.client.test.ts @@ -100,7 +100,8 @@ test.describe('client-side errors', () => { type: 'Error', value: errorMessage, mechanism: { - handled: true, + handled: false, + type: 'auto.function.react_router.on_error', }, }, ], @@ -127,7 +128,8 @@ test.describe('client-side errors', () => { type: 'Error', value: errorMessage, mechanism: { - handled: true, + handled: false, + type: 'auto.function.react_router.on_error', }, }, ], diff --git a/dev-packages/e2e-tests/test-applications/react-router-7-framework/app/entry.client.tsx b/dev-packages/e2e-tests/test-applications/react-router-7-framework/app/entry.client.tsx index 925c1e6ab143..005268b40ad0 100644 --- a/dev-packages/e2e-tests/test-applications/react-router-7-framework/app/entry.client.tsx +++ b/dev-packages/e2e-tests/test-applications/react-router-7-framework/app/entry.client.tsx @@ -17,7 +17,7 @@ startTransition(() => { hydrateRoot( document, - + , ); }); diff --git a/dev-packages/e2e-tests/test-applications/react-router-7-framework/app/root.tsx b/dev-packages/e2e-tests/test-applications/react-router-7-framework/app/root.tsx index 227c08f7730c..bc1b8f1236c0 100644 --- a/dev-packages/e2e-tests/test-applications/react-router-7-framework/app/root.tsx +++ b/dev-packages/e2e-tests/test-applications/react-router-7-framework/app/root.tsx @@ -1,4 +1,3 @@ -import * as Sentry from '@sentry/react-router'; import { Links, Meta, Outlet, Scripts, ScrollRestoration, isRouteErrorResponse } from 'react-router'; import type { Route } from './+types/root'; import stylesheet from './app.css?url'; @@ -48,7 +47,6 @@ export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) { message = error.status === 404 ? '404' : 'Error'; details = error.status === 404 ? 'The requested page could not be found.' : error.statusText || details; } else if (error && error instanceof Error) { - Sentry.captureException(error); if (import.meta.env.DEV) { details = error.message; stack = error.stack; diff --git a/dev-packages/e2e-tests/test-applications/react-router-7-framework/tests/errors/errors.client.test.ts b/dev-packages/e2e-tests/test-applications/react-router-7-framework/tests/errors/errors.client.test.ts index d6c80924c121..c1a7de46f1b6 100644 --- a/dev-packages/e2e-tests/test-applications/react-router-7-framework/tests/errors/errors.client.test.ts +++ b/dev-packages/e2e-tests/test-applications/react-router-7-framework/tests/errors/errors.client.test.ts @@ -100,7 +100,8 @@ test.describe('client-side errors', () => { type: 'Error', value: errorMessage, mechanism: { - handled: true, + handled: false, + type: 'auto.function.react_router.on_error', }, }, ], @@ -127,7 +128,8 @@ test.describe('client-side errors', () => { type: 'Error', value: errorMessage, mechanism: { - handled: true, + handled: false, + type: 'auto.function.react_router.on_error', }, }, ], diff --git a/dev-packages/e2e-tests/test-applications/remix-hydrogen/package.json b/dev-packages/e2e-tests/test-applications/remix-hydrogen/package.json index f108507033fa..8a35edaca3fb 100644 --- a/dev-packages/e2e-tests/test-applications/remix-hydrogen/package.json +++ b/dev-packages/e2e-tests/test-applications/remix-hydrogen/package.json @@ -19,7 +19,7 @@ "@remix-run/cloudflare-pages": "^2.17.4", "@sentry/cloudflare": "latest || *", "@sentry/remix": "latest || *", - "@sentry/vite-plugin": "^5.1.0", + "@sentry/vite-plugin": "^5.2.0", "@shopify/hydrogen": "2025.4.0", "@shopify/remix-oxygen": "2.0.10", "graphql": "^16.6.0", diff --git a/dev-packages/e2e-tests/test-applications/tsx-express/src/mcp.ts b/dev-packages/e2e-tests/test-applications/tsx-express/src/mcp.ts index b3b401ac294c..71a3d810dc1c 100644 --- a/dev-packages/e2e-tests/test-applications/tsx-express/src/mcp.ts +++ b/dev-packages/e2e-tests/test-applications/tsx-express/src/mcp.ts @@ -35,6 +35,14 @@ server.tool('echo', { message: z.string() }, async ({ message }, rest) => { }; }); +server.registerTool( + 'echo-register', + { description: 'Echo tool (register API)', inputSchema: { message: z.string() } }, + async ({ message }) => ({ + content: [{ type: 'text', text: `registerTool echo: ${message}` }], + }), +); + server.prompt('echo', { message: z.string() }, ({ message }, extra) => ({ messages: [ { @@ -47,6 +55,10 @@ server.prompt('echo', { message: z.string() }, ({ message }, extra) => ({ ], })); +server.tool('always-error', {}, async () => { + throw new Error('intentional error for span status testing'); +}); + const transports: Record = {}; mcpRouter.get('/sse', async (_, res) => { @@ -103,6 +115,14 @@ streamableServer.tool('echo', { message: z.string() }, async ({ message }) => { }; }); +streamableServer.registerTool( + 'echo-register', + { description: 'Echo tool (register API)', inputSchema: { message: z.string() } }, + async ({ message }) => ({ + content: [{ type: 'text', text: `registerTool echo: ${message}` }], + }), +); + streamableServer.prompt('echo', { message: z.string() }, ({ message }) => ({ messages: [ { diff --git a/dev-packages/e2e-tests/test-applications/tsx-express/tests/mcp.test.ts b/dev-packages/e2e-tests/test-applications/tsx-express/tests/mcp.test.ts index a89cfcaa11c6..f85eedf74b99 100644 --- a/dev-packages/e2e-tests/test-applications/tsx-express/tests/mcp.test.ts +++ b/dev-packages/e2e-tests/test-applications/tsx-express/tests/mcp.test.ts @@ -63,6 +63,40 @@ test('Records transactions for mcp handlers', async ({ baseURL }) => { // TODO: When https://github.com/modelcontextprotocol/typescript-sdk/pull/358 is released check for trace id equality between the post transaction and the handler transaction }); + await test.step('registerTool handler', async () => { + const postTransactionPromise = waitForTransaction('tsx-express', transactionEvent => { + return transactionEvent.transaction === 'POST /messages'; + }); + const toolTransactionPromise = waitForTransaction('tsx-express', transactionEvent => { + return transactionEvent.transaction === 'tools/call echo-register'; + }); + + const toolResult = await client.callTool({ + name: 'echo-register', + arguments: { + message: 'foobar', + }, + }); + + expect(toolResult).toMatchObject({ + content: [ + { + text: 'registerTool echo: foobar', + type: 'text', + }, + ], + }); + + const postTransaction = await postTransactionPromise; + expect(postTransaction).toBeDefined(); + + const toolTransaction = await toolTransactionPromise; + expect(toolTransaction).toBeDefined(); + expect(toolTransaction.contexts?.trace?.op).toEqual('mcp.server'); + expect(toolTransaction.contexts?.trace?.data?.['mcp.method.name']).toEqual('tools/call'); + expect(toolTransaction.contexts?.trace?.data?.['mcp.tool.name']).toEqual('echo-register'); + }); + await test.step('resource handler', async () => { const postTransactionPromise = waitForTransaction('tsx-express', transactionEvent => { return transactionEvent.transaction === 'POST /messages'; @@ -123,6 +157,23 @@ test('Records transactions for mcp handlers', async ({ baseURL }) => { // TODO: When https://github.com/modelcontextprotocol/typescript-sdk/pull/358 is released check for trace id equality between the post transaction and the handler transaction }); + + await test.step('error tool sets span status to internal_error', async () => { + const toolTransactionPromise = waitForTransaction('tsx-express', transactionEvent => { + return transactionEvent.transaction === 'tools/call always-error'; + }); + + try { + await client.callTool({ name: 'always-error', arguments: {} }); + } catch { + // Expected: MCP SDK throws when the tool returns a JSON-RPC error + } + + const toolTransaction = await toolTransactionPromise; + expect(toolTransaction).toBeDefined(); + expect(toolTransaction.contexts?.trace?.op).toEqual('mcp.server'); + expect(toolTransaction.contexts?.trace?.status).toEqual('internal_error'); + }); }); /** diff --git a/dev-packages/e2e-tests/test-applications/tsx-express/tests/transactions.test.ts b/dev-packages/e2e-tests/test-applications/tsx-express/tests/transactions.test.ts index 5957dbfd9738..35fe8f17bd94 100644 --- a/dev-packages/e2e-tests/test-applications/tsx-express/tests/transactions.test.ts +++ b/dev-packages/e2e-tests/test-applications/tsx-express/tests/transactions.test.ts @@ -71,14 +71,14 @@ test('Sends an API route transaction', async ({ baseURL }) => { expect(spans).toContainEqual({ data: { - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'middleware.express', 'express.name': 'query', 'express.type': 'middleware', }, description: 'query', op: 'middleware.express', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), @@ -89,14 +89,14 @@ test('Sends an API route transaction', async ({ baseURL }) => { expect(spans).toContainEqual({ data: { - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'middleware.express', 'express.name': 'expressInit', 'express.type': 'middleware', }, description: 'expressInit', op: 'middleware.express', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), @@ -107,7 +107,7 @@ test('Sends an API route transaction', async ({ baseURL }) => { expect(spans).toContainEqual({ data: { - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'request_handler.express', 'http.route': '/test-transaction', 'express.name': '/test-transaction', @@ -115,7 +115,7 @@ test('Sends an API route transaction', async ({ baseURL }) => { }, description: '/test-transaction', op: 'request_handler.express', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), @@ -147,14 +147,14 @@ test('Sends an API route transaction for an errored route', async ({ baseURL }) expect(spans).toContainEqual({ data: { - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'middleware.express', 'express.name': 'query', 'express.type': 'middleware', }, description: 'query', op: 'middleware.express', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), @@ -165,14 +165,14 @@ test('Sends an API route transaction for an errored route', async ({ baseURL }) expect(spans).toContainEqual({ data: { - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'middleware.express', 'express.name': 'expressInit', 'express.type': 'middleware', }, description: 'expressInit', op: 'middleware.express', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), @@ -183,7 +183,7 @@ test('Sends an API route transaction for an errored route', async ({ baseURL }) expect(spans).toContainEqual({ data: { - 'sentry.origin': 'auto.http.otel.express', + 'sentry.origin': 'auto.http.express', 'sentry.op': 'request_handler.express', 'http.route': '/test-exception/:id', 'express.name': '/test-exception/:id', @@ -191,12 +191,11 @@ test('Sends an API route transaction for an errored route', async ({ baseURL }) }, description: '/test-exception/:id', op: 'request_handler.express', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), start_timestamp: expect.any(Number), status: 'internal_error', - measurements: {}, timestamp: expect.any(Number), trace_id: expect.stringMatching(/[a-f0-9]{32}/), }); diff --git a/dev-packages/node-core-integration-tests/suites/public-api/beforeSendSpan-streamed/scenario.ts b/dev-packages/node-core-integration-tests/suites/public-api/beforeSendSpan-streamed/scenario.ts new file mode 100644 index 000000000000..bd85d6b9776d --- /dev/null +++ b/dev-packages/node-core-integration-tests/suites/public-api/beforeSendSpan-streamed/scenario.ts @@ -0,0 +1,42 @@ +import * as Sentry from '@sentry/node-core'; +import { loggingTransport } from '@sentry-internal/node-integration-tests'; +import { setupOtel } from '../../../utils/setupOtel'; + +const client = Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + tracesSampleRate: 1.0, + traceLifecycle: 'stream', + transport: loggingTransport, + release: '1.0.0', + beforeSendSpan: Sentry.withStreamedSpan(span => { + if (span.name === 'test-child-span') { + span.name = 'customChildSpanName'; + if (!span.attributes) { + span.attributes = {}; + } + span.attributes['sentry.custom_attribute'] = 'customAttributeValue'; + // @ts-ignore - technically this is something we have to expect, despite types saying it's invalid + span.status = 'something'; + span.links = [ + { + trace_id: '123', + span_id: '456', + attributes: { + 'sentry.link.type': 'custom_link', + }, + }, + ]; + } + return span; + }), +}); + +setupOtel(client); + +Sentry.startSpan({ name: 'test-span', op: 'test' }, () => { + Sentry.startSpan({ name: 'test-child-span', op: 'test-child' }, () => { + // noop + }); +}); + +void Sentry.flush(); diff --git a/dev-packages/node-core-integration-tests/suites/public-api/beforeSendSpan-streamed/test.ts b/dev-packages/node-core-integration-tests/suites/public-api/beforeSendSpan-streamed/test.ts new file mode 100644 index 000000000000..0de0f732f552 --- /dev/null +++ b/dev-packages/node-core-integration-tests/suites/public-api/beforeSendSpan-streamed/test.ts @@ -0,0 +1,32 @@ +import { expect, test } from 'vitest'; +import { createRunner } from '../../../utils/runner'; + +test('beforeSendSpan applies changes to streamed span', async () => { + await createRunner(__dirname, 'scenario.ts') + .expect({ + span: container => { + const spans = container.items; + expect(spans.length).toBe(2); + + const customChildSpan = spans.find(s => s.name === 'customChildSpanName'); + + expect(customChildSpan).toBeDefined(); + expect(customChildSpan!.attributes?.['sentry.custom_attribute']).toEqual({ + type: 'string', + value: 'customAttributeValue', + }); + expect(customChildSpan!.status).toBe('something'); + expect(customChildSpan!.links).toEqual([ + { + trace_id: '123', + span_id: '456', + attributes: { + 'sentry.link.type': { type: 'string', value: 'custom_link' }, + }, + }, + ]); + }, + }) + .start() + .completed(); +}); diff --git a/dev-packages/node-core-integration-tests/suites/public-api/startSpan/basic-usage-streamed/scenario.ts b/dev-packages/node-core-integration-tests/suites/public-api/startSpan/basic-usage-streamed/scenario.ts new file mode 100644 index 000000000000..cf8c1be967f4 --- /dev/null +++ b/dev-packages/node-core-integration-tests/suites/public-api/startSpan/basic-usage-streamed/scenario.ts @@ -0,0 +1,30 @@ +import * as Sentry from '@sentry/node-core'; +import { loggingTransport } from '@sentry-internal/node-integration-tests'; +import { setupOtel } from '../../../../utils/setupOtel'; + +const client = Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + tracesSampleRate: 1.0, + traceLifecycle: 'stream', + integrations: [Sentry.spanStreamingIntegration()], + transport: loggingTransport, + release: '1.0.0', +}); + +setupOtel(client); + +Sentry.startSpan({ name: 'test-span', op: 'test' }, segmentSpan => { + Sentry.startSpan({ name: 'test-child-span', op: 'test-child' }, () => { + // noop + }); + + const inactiveSpan = Sentry.startInactiveSpan({ name: 'test-inactive-span' }); + inactiveSpan.addLink({ context: segmentSpan.spanContext(), attributes: { 'sentry.link.type': 'some_relation' } }); + inactiveSpan.end(); + + Sentry.startSpanManual({ name: 'test-manual-span' }, span => { + span.end(); + }); +}); + +void Sentry.flush(); diff --git a/dev-packages/node-core-integration-tests/suites/public-api/startSpan/basic-usage-streamed/test.ts b/dev-packages/node-core-integration-tests/suites/public-api/startSpan/basic-usage-streamed/test.ts new file mode 100644 index 000000000000..3184aae69d64 --- /dev/null +++ b/dev-packages/node-core-integration-tests/suites/public-api/startSpan/basic-usage-streamed/test.ts @@ -0,0 +1,148 @@ +import { + SDK_VERSION, + SEMANTIC_ATTRIBUTE_SENTRY_OP, + SEMANTIC_ATTRIBUTE_SENTRY_RELEASE, + SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, + SEMANTIC_ATTRIBUTE_SENTRY_SDK_NAME, + SEMANTIC_ATTRIBUTE_SENTRY_SDK_VERSION, + SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID, + SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME, +} from '@sentry/core'; +import { expect, test } from 'vitest'; +import { createRunner } from '../../../../utils/runner'; + +test('sends a streamed span envelope with correct envelope header', async () => { + await createRunner(__dirname, 'scenario.ts') + .expectHeader({ + span: { + sent_at: expect.any(String), + sdk: { + name: 'sentry.javascript.node-core', + version: SDK_VERSION, + }, + trace: expect.objectContaining({ + public_key: 'public', + sample_rate: '1', + sampled: 'true', + trace_id: expect.stringMatching(/^[\da-f]{32}$/), + transaction: 'test-span', + }), + }, + }) + .start() + .completed(); +}); + +test('sends a streamed span envelope with correct spans for a manually started span with children', async () => { + await createRunner(__dirname, 'scenario.ts') + .expect({ + span: container => { + const spans = container.items; + expect(spans.length).toBe(4); + + const segmentSpan = spans.find(s => !!s.is_segment); + expect(segmentSpan).toBeDefined(); + + const segmentSpanId = segmentSpan!.span_id; + const traceId = segmentSpan!.trace_id; + + const childSpan = spans.find(s => s.name === 'test-child-span'); + expect(childSpan).toBeDefined(); + expect(childSpan).toEqual({ + attributes: { + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: { + type: 'string', + value: 'test-child', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_NAME]: { type: 'string', value: 'sentry.javascript.node-core' }, + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_VERSION]: { type: 'string', value: SDK_VERSION }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID]: { type: 'string', value: segmentSpanId }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME]: { type: 'string', value: 'test-span' }, + [SEMANTIC_ATTRIBUTE_SENTRY_RELEASE]: { type: 'string', value: '1.0.0' }, + }, + name: 'test-child-span', + is_segment: false, + parent_span_id: segmentSpanId, + trace_id: traceId, + span_id: expect.stringMatching(/^[\da-f]{16}$/), + start_timestamp: expect.any(Number), + end_timestamp: expect.any(Number), + status: 'ok', + }); + + const inactiveSpan = spans.find(s => s.name === 'test-inactive-span'); + expect(inactiveSpan).toBeDefined(); + expect(inactiveSpan).toEqual({ + attributes: { + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_NAME]: { type: 'string', value: 'sentry.javascript.node-core' }, + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_VERSION]: { type: 'string', value: SDK_VERSION }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID]: { type: 'string', value: segmentSpanId }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME]: { type: 'string', value: 'test-span' }, + [SEMANTIC_ATTRIBUTE_SENTRY_RELEASE]: { type: 'string', value: '1.0.0' }, + }, + links: [ + { + attributes: { + 'sentry.link.type': { + type: 'string', + value: 'some_relation', + }, + }, + sampled: true, + span_id: segmentSpanId, + trace_id: traceId, + }, + ], + name: 'test-inactive-span', + is_segment: false, + parent_span_id: segmentSpanId, + trace_id: traceId, + span_id: expect.stringMatching(/^[\da-f]{16}$/), + start_timestamp: expect.any(Number), + end_timestamp: expect.any(Number), + status: 'ok', + }); + + const manualSpan = spans.find(s => s.name === 'test-manual-span'); + expect(manualSpan).toBeDefined(); + expect(manualSpan).toEqual({ + attributes: { + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_NAME]: { type: 'string', value: 'sentry.javascript.node-core' }, + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_VERSION]: { type: 'string', value: SDK_VERSION }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID]: { type: 'string', value: segmentSpanId }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME]: { type: 'string', value: 'test-span' }, + [SEMANTIC_ATTRIBUTE_SENTRY_RELEASE]: { type: 'string', value: '1.0.0' }, + }, + name: 'test-manual-span', + is_segment: false, + parent_span_id: segmentSpanId, + trace_id: traceId, + span_id: expect.stringMatching(/^[\da-f]{16}$/), + start_timestamp: expect.any(Number), + end_timestamp: expect.any(Number), + status: 'ok', + }); + + expect(segmentSpan).toEqual({ + attributes: { + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: { type: 'string', value: 'test' }, + [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: { type: 'integer', value: 1 }, + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_NAME]: { type: 'string', value: 'sentry.javascript.node-core' }, + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_VERSION]: { type: 'string', value: SDK_VERSION }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID]: { type: 'string', value: segmentSpanId }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME]: { type: 'string', value: 'test-span' }, + [SEMANTIC_ATTRIBUTE_SENTRY_RELEASE]: { type: 'string', value: '1.0.0' }, + }, + name: 'test-span', + is_segment: true, + trace_id: traceId, + span_id: segmentSpanId, + start_timestamp: expect.any(Number), + end_timestamp: expect.any(Number), + status: 'ok', + }); + }, + }) + .start() + .completed(); +}); diff --git a/dev-packages/node-core-integration-tests/suites/public-api/startSpan/parallel-root-spans-streamed/scenario.ts b/dev-packages/node-core-integration-tests/suites/public-api/startSpan/parallel-root-spans-streamed/scenario.ts new file mode 100644 index 000000000000..048b06f29178 --- /dev/null +++ b/dev-packages/node-core-integration-tests/suites/public-api/startSpan/parallel-root-spans-streamed/scenario.ts @@ -0,0 +1,36 @@ +import * as Sentry from '@sentry/node-core'; +import { loggingTransport } from '@sentry-internal/node-core-integration-tests'; +import { setupOtel } from '../../../../utils/setupOtel'; + +const client = Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + release: '1.0', + tracesSampleRate: 1.0, + traceLifecycle: 'stream', + transport: loggingTransport, +}); + +setupOtel(client); + +Sentry.getCurrentScope().setPropagationContext({ + parentSpanId: '1234567890123456', + traceId: '12345678901234567890123456789012', + sampleRand: Math.random(), +}); + +const spanIdTraceId = Sentry.startSpan( + { + name: 'test_span_1', + }, + span1 => span1.spanContext().traceId, +); + +Sentry.startSpan( + { + name: 'test_span_2', + attributes: { spanIdTraceId }, + }, + () => undefined, +); + +Sentry.flush(); diff --git a/dev-packages/node-core-integration-tests/suites/public-api/startSpan/parallel-root-spans-streamed/test.ts b/dev-packages/node-core-integration-tests/suites/public-api/startSpan/parallel-root-spans-streamed/test.ts new file mode 100644 index 000000000000..f332715bbc42 --- /dev/null +++ b/dev-packages/node-core-integration-tests/suites/public-api/startSpan/parallel-root-spans-streamed/test.ts @@ -0,0 +1,32 @@ +import { afterAll, expect, test } from 'vitest'; +import { cleanupChildProcesses, createRunner } from '../../../../utils/runner'; + +afterAll(() => { + cleanupChildProcesses(); +}); + +test('sends manually started streamed parallel root spans in root context', async () => { + expect.assertions(7); + + await createRunner(__dirname, 'scenario.ts') + .expect({ span: { items: [{ name: 'test_span_1' }] } }) + .expect({ + span: spanContainer => { + expect(spanContainer).toBeDefined(); + const traceId = spanContainer.items[0]!.trace_id; + expect(traceId).toMatch(/^[0-9a-f]{32}$/); + + // It ignores propagation context of the root context + expect(traceId).not.toBe('12345678901234567890123456789012'); + expect(spanContainer.items[0]!.parent_span_id).toBeUndefined(); + + // Different trace ID than the first span + const trace1Id = spanContainer.items[0]!.attributes?.spanIdTraceId?.value; + expect(trace1Id).toMatch(/^[0-9a-f]{32}$/); + + expect(trace1Id).not.toBe(traceId); + }, + }) + .start() + .completed(); +}); diff --git a/dev-packages/node-core-integration-tests/suites/public-api/startSpan/parallel-spans-in-scope-streamed/scenario.ts b/dev-packages/node-core-integration-tests/suites/public-api/startSpan/parallel-spans-in-scope-streamed/scenario.ts new file mode 100644 index 000000000000..fd283637b0b6 --- /dev/null +++ b/dev-packages/node-core-integration-tests/suites/public-api/startSpan/parallel-spans-in-scope-streamed/scenario.ts @@ -0,0 +1,32 @@ +import * as Sentry from '@sentry/node-core'; +import { loggingTransport } from '@sentry-internal/node-core-integration-tests'; +import { setupOtel } from '../../../../utils/setupOtel'; + +const client = Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + release: '1.0', + tracesSampleRate: 1.0, + traceLifecycle: 'stream', + transport: loggingTransport, +}); + +setupOtel(client); + +Sentry.withScope(() => { + const spanIdTraceId = Sentry.startSpan( + { + name: 'test_span_1', + }, + span1 => span1.spanContext().traceId, + ); + + Sentry.startSpan( + { + name: 'test_span_2', + attributes: { spanIdTraceId }, + }, + () => undefined, + ); +}); + +Sentry.flush(); diff --git a/dev-packages/node-core-integration-tests/suites/public-api/startSpan/parallel-spans-in-scope-streamed/test.ts b/dev-packages/node-core-integration-tests/suites/public-api/startSpan/parallel-spans-in-scope-streamed/test.ts new file mode 100644 index 000000000000..02456c9e93b2 --- /dev/null +++ b/dev-packages/node-core-integration-tests/suites/public-api/startSpan/parallel-spans-in-scope-streamed/test.ts @@ -0,0 +1,29 @@ +import { afterAll, expect, test } from 'vitest'; +import { cleanupChildProcesses, createRunner } from '../../../../utils/runner'; + +afterAll(() => { + cleanupChildProcesses(); +}); + +test('sends manually started streamed parallel root spans outside of root context', async () => { + expect.assertions(6); + + await createRunner(__dirname, 'scenario.ts') + .expect({ span: { items: [{ name: 'test_span_1' }] } }) + .expect({ + span: spanContainer => { + expect(spanContainer).toBeDefined(); + const traceId = spanContainer.items[0]!.trace_id; + expect(traceId).toMatch(/^[0-9a-f]{32}$/); + expect(spanContainer.items[0]!.parent_span_id).toBeUndefined(); + + const trace1Id = spanContainer.items[0]!.attributes?.spanIdTraceId?.value; + expect(trace1Id).toMatch(/^[0-9a-f]{32}$/); + + // Different trace ID as the first span + expect(trace1Id).not.toBe(traceId); + }, + }) + .start() + .completed(); +}); diff --git a/dev-packages/node-core-integration-tests/suites/public-api/startSpan/parallel-spans-in-scope-with-parentSpanId-streamed/scenario.ts b/dev-packages/node-core-integration-tests/suites/public-api/startSpan/parallel-spans-in-scope-with-parentSpanId-streamed/scenario.ts new file mode 100644 index 000000000000..367ce6eda6fa --- /dev/null +++ b/dev-packages/node-core-integration-tests/suites/public-api/startSpan/parallel-spans-in-scope-with-parentSpanId-streamed/scenario.ts @@ -0,0 +1,38 @@ +import * as Sentry from '@sentry/node-core'; +import { loggingTransport } from '@sentry-internal/node-core-integration-tests'; +import { setupOtel } from '../../../../utils/setupOtel'; + +const client = Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + release: '1.0', + tracesSampleRate: 1.0, + traceLifecycle: 'stream', + transport: loggingTransport, +}); + +setupOtel(client); + +Sentry.withScope(scope => { + scope.setPropagationContext({ + parentSpanId: '1234567890123456', + traceId: '12345678901234567890123456789012', + sampleRand: Math.random(), + }); + + const spanIdTraceId = Sentry.startSpan( + { + name: 'test_span_1', + }, + span1 => span1.spanContext().traceId, + ); + + Sentry.startSpan( + { + name: 'test_span_2', + attributes: { spanIdTraceId }, + }, + () => undefined, + ); +}); + +Sentry.flush(); diff --git a/dev-packages/node-core-integration-tests/suites/public-api/startSpan/parallel-spans-in-scope-with-parentSpanId-streamed/test.ts b/dev-packages/node-core-integration-tests/suites/public-api/startSpan/parallel-spans-in-scope-with-parentSpanId-streamed/test.ts new file mode 100644 index 000000000000..325f0f0d5d42 --- /dev/null +++ b/dev-packages/node-core-integration-tests/suites/public-api/startSpan/parallel-spans-in-scope-with-parentSpanId-streamed/test.ts @@ -0,0 +1,29 @@ +import { afterAll, expect, test } from 'vitest'; +import { cleanupChildProcesses, createRunner } from '../../../../utils/runner'; + +afterAll(() => { + cleanupChildProcesses(); +}); + +test('sends manually started streamed parallel root spans outside of root context with parentSpanId', async () => { + expect.assertions(6); + + await createRunner(__dirname, 'scenario.ts') + .expect({ span: { items: [{ name: 'test_span_1' }] } }) + .expect({ + span: spanContainer => { + expect(spanContainer).toBeDefined(); + const traceId = spanContainer.items[0]!.trace_id; + expect(traceId).toMatch(/^[0-9a-f]{32}$/); + expect(spanContainer.items[0]!.parent_span_id).toBeUndefined(); + + const trace1Id = spanContainer.items[0]!.attributes?.spanIdTraceId?.value; + expect(trace1Id).toMatch(/^[0-9a-f]{32}$/); + + // Different trace ID as the first span + expect(trace1Id).not.toBe(traceId); + }, + }) + .start() + .completed(); +}); diff --git a/dev-packages/node-core-integration-tests/suites/public-api/startSpan/updateName-method-streamed/scenario.ts b/dev-packages/node-core-integration-tests/suites/public-api/startSpan/updateName-method-streamed/scenario.ts new file mode 100644 index 000000000000..8512fb954b8e --- /dev/null +++ b/dev-packages/node-core-integration-tests/suites/public-api/startSpan/updateName-method-streamed/scenario.ts @@ -0,0 +1,22 @@ +import * as Sentry from '@sentry/node-core'; +import { loggingTransport } from '@sentry-internal/node-integration-tests'; +import { setupOtel } from '../../../../utils/setupOtel'; + +const client = Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + release: '1.0', + tracesSampleRate: 1.0, + traceLifecycle: 'stream', + transport: loggingTransport, +}); + +setupOtel(client); + +Sentry.startSpan( + { name: 'test_span', attributes: { [Sentry.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url' } }, + (span: Sentry.Span) => { + span.updateName('new name'); + }, +); + +void Sentry.flush(); diff --git a/dev-packages/node-core-integration-tests/suites/public-api/startSpan/updateName-method-streamed/test.ts b/dev-packages/node-core-integration-tests/suites/public-api/startSpan/updateName-method-streamed/test.ts new file mode 100644 index 000000000000..09cc140278ed --- /dev/null +++ b/dev-packages/node-core-integration-tests/suites/public-api/startSpan/updateName-method-streamed/test.ts @@ -0,0 +1,26 @@ +import { SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/node-core'; +import { afterAll, test } from 'vitest'; +import { cleanupChildProcesses, createRunner } from '../../../../utils/runner'; + +afterAll(() => { + cleanupChildProcesses(); +}); + +test('updates the span name when calling `span.updateName` (streamed)', async () => { + await createRunner(__dirname, 'scenario.ts') + .expect({ + span: { + items: [ + { + name: 'new name', + is_segment: true, + attributes: { + [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: { type: 'string', value: 'url' }, + }, + }, + ], + }, + }) + .start() + .completed(); +}); diff --git a/dev-packages/node-core-integration-tests/suites/public-api/startSpan/updateSpanName-function-streamed/scenario.ts b/dev-packages/node-core-integration-tests/suites/public-api/startSpan/updateSpanName-function-streamed/scenario.ts new file mode 100644 index 000000000000..34892b20d692 --- /dev/null +++ b/dev-packages/node-core-integration-tests/suites/public-api/startSpan/updateSpanName-function-streamed/scenario.ts @@ -0,0 +1,22 @@ +import * as Sentry from '@sentry/node-core'; +import { loggingTransport } from '@sentry-internal/node-integration-tests'; +import { setupOtel } from '../../../../utils/setupOtel'; + +const client = Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + release: '1.0', + tracesSampleRate: 1.0, + traceLifecycle: 'stream', + transport: loggingTransport, +}); + +setupOtel(client); + +Sentry.startSpan( + { name: 'test_span', attributes: { [Sentry.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url' } }, + (span: Sentry.Span) => { + Sentry.updateSpanName(span, 'new name'); + }, +); + +void Sentry.flush(); diff --git a/dev-packages/node-core-integration-tests/suites/public-api/startSpan/updateSpanName-function-streamed/test.ts b/dev-packages/node-core-integration-tests/suites/public-api/startSpan/updateSpanName-function-streamed/test.ts new file mode 100644 index 000000000000..8ff4b71ed5e6 --- /dev/null +++ b/dev-packages/node-core-integration-tests/suites/public-api/startSpan/updateSpanName-function-streamed/test.ts @@ -0,0 +1,26 @@ +import { SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/node-core'; +import { afterAll, test } from 'vitest'; +import { cleanupChildProcesses, createRunner } from '../../../../utils/runner'; + +afterAll(() => { + cleanupChildProcesses(); +}); + +test('updates the span name and source when calling `updateSpanName` (streamed)', async () => { + await createRunner(__dirname, 'scenario.ts') + .expect({ + span: { + items: [ + { + name: 'new name', + is_segment: true, + attributes: { + [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: { type: 'string', value: 'custom' }, + }, + }, + ], + }, + }) + .start() + .completed(); +}); diff --git a/dev-packages/node-core-integration-tests/utils/assertions.ts b/dev-packages/node-core-integration-tests/utils/assertions.ts index 00c6019fab0c..4f08141d9f93 100644 --- a/dev-packages/node-core-integration-tests/utils/assertions.ts +++ b/dev-packages/node-core-integration-tests/utils/assertions.ts @@ -6,12 +6,19 @@ import type { SerializedLogContainer, SerializedMetricContainer, SerializedSession, + SerializedStreamedSpanContainer, SessionAggregates, TransactionEvent, } from '@sentry/core'; import { SDK_VERSION } from '@sentry/core'; import { expect } from 'vitest'; +export type DeepPartial = T extends object + ? { + [P in keyof T]?: DeepPartial; + } + : T; + /** * Asserts against a Sentry Event ignoring non-deterministic properties * @@ -86,6 +93,16 @@ export function assertSentryMetricContainer( }); } +export function assertSentrySpanContainer( + actual: SerializedStreamedSpanContainer, + expected: DeepPartial, +): void { + expect(actual).toMatchObject({ + items: expect.any(Array), + ...expected, + }); +} + export function assertEnvelopeHeader(actual: Envelope[0], expected: Partial): void { expect(actual).toEqual({ event_id: expect.any(String), @@ -97,3 +114,14 @@ export function assertEnvelopeHeader(actual: Envelope[0], expected: Partial): void { + expect(actual).toEqual({ + sent_at: expect.any(String), + sdk: { + name: 'sentry.javascript.node-core', + version: SDK_VERSION, + }, + ...expected, + }); +} diff --git a/dev-packages/node-core-integration-tests/utils/runner.ts b/dev-packages/node-core-integration-tests/utils/runner.ts index 416d55d803a1..d27c65fc81be 100644 --- a/dev-packages/node-core-integration-tests/utils/runner.ts +++ b/dev-packages/node-core-integration-tests/utils/runner.ts @@ -9,6 +9,7 @@ import type { SerializedLogContainer, SerializedMetricContainer, SerializedSession, + SerializedStreamedSpanContainer, SessionAggregates, TransactionEvent, } from '@sentry/core'; @@ -17,6 +18,7 @@ import { execSync, spawn, spawnSync } from 'child_process'; import { existsSync, readFileSync, unlinkSync, writeFileSync } from 'fs'; import { join } from 'path'; import { afterAll, beforeAll, describe, test } from 'vitest'; +import type { DeepPartial } from './assertions'; import { assertEnvelopeHeader, assertSentryCheckIn, @@ -26,7 +28,9 @@ import { assertSentryMetricContainer, assertSentrySession, assertSentrySessions, + assertSentrySpanContainer, assertSentryTransaction, + assertSpanEnvelopeHeader, } from './assertions'; import { createBasicSentryServer } from './server'; @@ -125,6 +129,9 @@ type ExpectedCheckIn = Partial | ((event: SerializedCheckIn) type ExpectedClientReport = Partial | ((event: ClientReport) => void); type ExpectedLogContainer = Partial | ((event: SerializedLogContainer) => void); type ExpectedMetricContainer = Partial | ((event: SerializedMetricContainer) => void); +type ExpectedSpanContainer = + | DeepPartial + | ((container: SerializedStreamedSpanContainer) => void); type Expected = | { @@ -150,6 +157,9 @@ type Expected = } | { trace_metric: ExpectedMetricContainer; + } + | { + span: ExpectedSpanContainer; }; type ExpectedEnvelopeHeader = @@ -157,7 +167,8 @@ type ExpectedEnvelopeHeader = | { transaction: Partial } | { session: Partial } | { sessions: Partial } - | { log: Partial }; + | { log: Partial } + | { span: Partial }; type StartResult = { completed(): Promise; @@ -360,7 +371,11 @@ export function createRunner(...paths: string[]) { return; } - assertEnvelopeHeader(header, expected); + if (envelopeItemType === 'span') { + assertSpanEnvelopeHeader(header, expected); + } else { + assertEnvelopeHeader(header, expected); + } expectCallbackCalled(); } catch (e) { @@ -412,6 +427,9 @@ export function createRunner(...paths: string[]) { } else if ('trace_metric' in expected) { expectMetric(item[1] as SerializedMetricContainer, expected.trace_metric); expectCallbackCalled(); + } else if ('span' in expected) { + expectSpanContainer(item[1] as SerializedStreamedSpanContainer, expected.span); + expectCallbackCalled(); } else { throw new Error( `Unhandled expected envelope item type: ${JSON.stringify(expected)}\nItem: ${JSON.stringify(item)}`, @@ -666,6 +684,14 @@ function expectMetric(item: SerializedMetricContainer, expected: ExpectedMetricC } } +function expectSpanContainer(item: SerializedStreamedSpanContainer, expected: ExpectedSpanContainer): void { + if (typeof expected === 'function') { + expected(item); + } else { + assertSentrySpanContainer(item, expected); + } +} + /** * Converts ESM import statements to CommonJS require statements * @param content The content of an ESM file diff --git a/dev-packages/node-integration-tests/package.json b/dev-packages/node-integration-tests/package.json index 0bf39f21b7bf..5504fd197985 100644 --- a/dev-packages/node-integration-tests/package.json +++ b/dev-packages/node-integration-tests/package.json @@ -32,6 +32,7 @@ "@hono/node-server": "^1.19.10", "@langchain/anthropic": "^0.3.10", "@langchain/core": "^0.3.80", + "@langchain/openai": "^0.5.0", "@langchain/langgraph": "^0.2.32", "@nestjs/common": "^11", "@nestjs/core": "^11", diff --git a/dev-packages/node-integration-tests/suites/bun-runtime-metrics/scenario-all.ts b/dev-packages/node-integration-tests/suites/bun-runtime-metrics/scenario-all.ts index f82385c4c16e..6ec4ca0c1244 100644 --- a/dev-packages/node-integration-tests/suites/bun-runtime-metrics/scenario-all.ts +++ b/dev-packages/node-integration-tests/suites/bun-runtime-metrics/scenario-all.ts @@ -9,7 +9,7 @@ Sentry.init({ transport: loggingTransport, integrations: [ bunRuntimeMetricsIntegration({ - collectionIntervalMs: 100, + collectionIntervalMs: 1000, collect: { cpuTime: true, memExternal: true, @@ -19,7 +19,7 @@ Sentry.init({ }); async function run(): Promise { - await new Promise(resolve => setTimeout(resolve, 250)); + await new Promise(resolve => setTimeout(resolve, 1100)); await Sentry.flush(); } diff --git a/dev-packages/node-integration-tests/suites/bun-runtime-metrics/scenario-opt-out.ts b/dev-packages/node-integration-tests/suites/bun-runtime-metrics/scenario-opt-out.ts index d3aa0f309893..8987865e277d 100644 --- a/dev-packages/node-integration-tests/suites/bun-runtime-metrics/scenario-opt-out.ts +++ b/dev-packages/node-integration-tests/suites/bun-runtime-metrics/scenario-opt-out.ts @@ -9,7 +9,7 @@ Sentry.init({ transport: loggingTransport, integrations: [ bunRuntimeMetricsIntegration({ - collectionIntervalMs: 100, + collectionIntervalMs: 1000, collect: { cpuUtilization: false, cpuTime: false, @@ -21,7 +21,7 @@ Sentry.init({ }); async function run(): Promise { - await new Promise(resolve => setTimeout(resolve, 250)); + await new Promise(resolve => setTimeout(resolve, 1100)); await Sentry.flush(); } diff --git a/dev-packages/node-integration-tests/suites/bun-runtime-metrics/scenario.ts b/dev-packages/node-integration-tests/suites/bun-runtime-metrics/scenario.ts index 1948ddfa6c23..92e248cccc6e 100644 --- a/dev-packages/node-integration-tests/suites/bun-runtime-metrics/scenario.ts +++ b/dev-packages/node-integration-tests/suites/bun-runtime-metrics/scenario.ts @@ -9,13 +9,13 @@ Sentry.init({ transport: loggingTransport, integrations: [ bunRuntimeMetricsIntegration({ - collectionIntervalMs: 100, + collectionIntervalMs: 1000, }), ], }); async function run(): Promise { - await new Promise(resolve => setTimeout(resolve, 250)); + await new Promise(resolve => setTimeout(resolve, 1100)); await Sentry.flush(); } diff --git a/dev-packages/node-integration-tests/suites/express/tracing/test.ts b/dev-packages/node-integration-tests/suites/express/tracing/test.ts index 759df300181a..62f827440522 100644 --- a/dev-packages/node-integration-tests/suites/express/tracing/test.ts +++ b/dev-packages/node-integration-tests/suites/express/tracing/test.ts @@ -32,7 +32,7 @@ describe('express tracing', () => { }), description: 'corsMiddleware', op: 'middleware.express', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', }), expect.objectContaining({ data: expect.objectContaining({ @@ -41,7 +41,7 @@ describe('express tracing', () => { }), description: '/test/express', op: 'request_handler.express', - origin: 'auto.http.otel.express', + origin: 'auto.http.express', }), ]), }, diff --git a/dev-packages/node-integration-tests/suites/node-runtime-metrics/scenario-all.ts b/dev-packages/node-integration-tests/suites/node-runtime-metrics/scenario-all.ts index e995482fafbf..94a7161fe00c 100644 --- a/dev-packages/node-integration-tests/suites/node-runtime-metrics/scenario-all.ts +++ b/dev-packages/node-integration-tests/suites/node-runtime-metrics/scenario-all.ts @@ -8,7 +8,7 @@ Sentry.init({ transport: loggingTransport, integrations: [ Sentry.nodeRuntimeMetricsIntegration({ - collectionIntervalMs: 100, + collectionIntervalMs: 1000, collect: { cpuTime: true, memExternal: true, @@ -22,7 +22,7 @@ Sentry.init({ }); async function run(): Promise { - await new Promise(resolve => setTimeout(resolve, 250)); + await new Promise(resolve => setTimeout(resolve, 1100)); await Sentry.flush(); } diff --git a/dev-packages/node-integration-tests/suites/node-runtime-metrics/scenario-opt-out.ts b/dev-packages/node-integration-tests/suites/node-runtime-metrics/scenario-opt-out.ts index 423e478ed1f8..e838df6e9408 100644 --- a/dev-packages/node-integration-tests/suites/node-runtime-metrics/scenario-opt-out.ts +++ b/dev-packages/node-integration-tests/suites/node-runtime-metrics/scenario-opt-out.ts @@ -8,7 +8,7 @@ Sentry.init({ transport: loggingTransport, integrations: [ Sentry.nodeRuntimeMetricsIntegration({ - collectionIntervalMs: 100, + collectionIntervalMs: 1000, collect: { cpuUtilization: false, cpuTime: false, @@ -22,7 +22,7 @@ Sentry.init({ }); async function run(): Promise { - await new Promise(resolve => setTimeout(resolve, 250)); + await new Promise(resolve => setTimeout(resolve, 1100)); await Sentry.flush(); } diff --git a/dev-packages/node-integration-tests/suites/node-runtime-metrics/scenario.ts b/dev-packages/node-integration-tests/suites/node-runtime-metrics/scenario.ts index b862634c719a..1e174e5c29cc 100644 --- a/dev-packages/node-integration-tests/suites/node-runtime-metrics/scenario.ts +++ b/dev-packages/node-integration-tests/suites/node-runtime-metrics/scenario.ts @@ -8,14 +8,14 @@ Sentry.init({ transport: loggingTransport, integrations: [ Sentry.nodeRuntimeMetricsIntegration({ - collectionIntervalMs: 100, + collectionIntervalMs: 1000, }), ], }); async function run(): Promise { // Wait long enough for the collection interval to fire at least once. - await new Promise(resolve => setTimeout(resolve, 250)); + await new Promise(resolve => setTimeout(resolve, 1100)); await Sentry.flush(); } diff --git a/dev-packages/node-integration-tests/suites/public-api/startSpan/basic-usage-streamed/scenario.ts b/dev-packages/node-integration-tests/suites/public-api/startSpan/basic-usage-streamed/scenario.ts new file mode 100644 index 000000000000..ce3f914d51b8 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/public-api/startSpan/basic-usage-streamed/scenario.ts @@ -0,0 +1,29 @@ +import * as Sentry from '@sentry/node'; +import { loggingTransport } from '@sentry-internal/node-integration-tests'; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + tracesSampleRate: 1.0, + traceLifecycle: 'stream', + integrations: [Sentry.spanStreamingIntegration()], + transport: loggingTransport, + release: '1.0.0', +}); + +Sentry.startSpan({ name: 'test-span', op: 'test' }, segmentSpan => { + Sentry.startSpan({ name: 'test-child-span', op: 'test-child' }, () => { + // noop + }); + + const inactiveSpan = Sentry.startInactiveSpan({ + name: 'test-inactive-span', + links: [{ context: segmentSpan.spanContext(), attributes: { 'sentry.link.type': 'some_relation' } }], + }); + inactiveSpan.end(); + + Sentry.startSpanManual({ name: 'test-manual-span' }, span => { + span.end(); + }); +}); + +void Sentry.flush(); diff --git a/dev-packages/node-integration-tests/suites/public-api/startSpan/basic-usage-streamed/test.ts b/dev-packages/node-integration-tests/suites/public-api/startSpan/basic-usage-streamed/test.ts new file mode 100644 index 000000000000..b31ca320df53 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/public-api/startSpan/basic-usage-streamed/test.ts @@ -0,0 +1,148 @@ +import { + SDK_VERSION, + SEMANTIC_ATTRIBUTE_SENTRY_OP, + SEMANTIC_ATTRIBUTE_SENTRY_RELEASE, + SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, + SEMANTIC_ATTRIBUTE_SENTRY_SDK_NAME, + SEMANTIC_ATTRIBUTE_SENTRY_SDK_VERSION, + SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID, + SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME, +} from '@sentry/core'; +import { expect, test } from 'vitest'; +import { createRunner } from '../../../../utils/runner'; + +test('sends a streamed span envelope with correct envelope header', async () => { + await createRunner(__dirname, 'scenario.ts') + .expectHeader({ + span: { + sent_at: expect.any(String), + sdk: { + name: 'sentry.javascript.node', + version: SDK_VERSION, + }, + trace: expect.objectContaining({ + public_key: 'public', + sample_rate: '1', + sampled: 'true', + trace_id: expect.stringMatching(/^[\da-f]{32}$/), + transaction: 'test-span', + }), + }, + }) + .start() + .completed(); +}); + +test('sends a streamed span envelope with correct spans for a manually started span with children', async () => { + await createRunner(__dirname, 'scenario.ts') + .expect({ + span: container => { + const spans = container.items; + expect(spans.length).toBe(4); + + const segmentSpan = spans.find(s => !!s.is_segment); + expect(segmentSpan).toBeDefined(); + + const segmentSpanId = segmentSpan!.span_id; + const traceId = segmentSpan!.trace_id; + + const childSpan = spans.find(s => s.name === 'test-child-span'); + expect(childSpan).toBeDefined(); + expect(childSpan).toEqual({ + attributes: { + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: { + type: 'string', + value: 'test-child', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_NAME]: { type: 'string', value: 'sentry.javascript.node' }, + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_VERSION]: { type: 'string', value: SDK_VERSION }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID]: { type: 'string', value: segmentSpanId }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME]: { type: 'string', value: 'test-span' }, + [SEMANTIC_ATTRIBUTE_SENTRY_RELEASE]: { type: 'string', value: '1.0.0' }, + }, + name: 'test-child-span', + is_segment: false, + parent_span_id: segmentSpanId, + trace_id: traceId, + span_id: expect.stringMatching(/^[\da-f]{16}$/), + start_timestamp: expect.any(Number), + end_timestamp: expect.any(Number), + status: 'ok', + }); + + const inactiveSpan = spans.find(s => s.name === 'test-inactive-span'); + expect(inactiveSpan).toBeDefined(); + expect(inactiveSpan).toEqual({ + attributes: { + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_NAME]: { type: 'string', value: 'sentry.javascript.node' }, + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_VERSION]: { type: 'string', value: SDK_VERSION }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID]: { type: 'string', value: segmentSpanId }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME]: { type: 'string', value: 'test-span' }, + [SEMANTIC_ATTRIBUTE_SENTRY_RELEASE]: { type: 'string', value: '1.0.0' }, + }, + links: [ + { + attributes: { + 'sentry.link.type': { + type: 'string', + value: 'some_relation', + }, + }, + sampled: true, + span_id: segmentSpanId, + trace_id: traceId, + }, + ], + name: 'test-inactive-span', + is_segment: false, + parent_span_id: segmentSpanId, + trace_id: traceId, + span_id: expect.stringMatching(/^[\da-f]{16}$/), + start_timestamp: expect.any(Number), + end_timestamp: expect.any(Number), + status: 'ok', + }); + + const manualSpan = spans.find(s => s.name === 'test-manual-span'); + expect(manualSpan).toBeDefined(); + expect(manualSpan).toEqual({ + attributes: { + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_NAME]: { type: 'string', value: 'sentry.javascript.node' }, + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_VERSION]: { type: 'string', value: SDK_VERSION }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID]: { type: 'string', value: segmentSpanId }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME]: { type: 'string', value: 'test-span' }, + [SEMANTIC_ATTRIBUTE_SENTRY_RELEASE]: { type: 'string', value: '1.0.0' }, + }, + name: 'test-manual-span', + is_segment: false, + parent_span_id: segmentSpanId, + trace_id: traceId, + span_id: expect.stringMatching(/^[\da-f]{16}$/), + start_timestamp: expect.any(Number), + end_timestamp: expect.any(Number), + status: 'ok', + }); + + expect(segmentSpan).toEqual({ + attributes: { + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: { type: 'string', value: 'test' }, + [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: { type: 'integer', value: 1 }, + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_NAME]: { type: 'string', value: 'sentry.javascript.node' }, + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_VERSION]: { type: 'string', value: SDK_VERSION }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID]: { type: 'string', value: segmentSpanId }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME]: { type: 'string', value: 'test-span' }, + [SEMANTIC_ATTRIBUTE_SENTRY_RELEASE]: { type: 'string', value: '1.0.0' }, + }, + name: 'test-span', + is_segment: true, + trace_id: traceId, + span_id: segmentSpanId, + start_timestamp: expect.any(Number), + end_timestamp: expect.any(Number), + status: 'ok', + }); + }, + }) + .start() + .completed(); +}); diff --git a/dev-packages/node-integration-tests/suites/public-api/startSpan/parallel-root-spans-streamed/scenario.ts b/dev-packages/node-integration-tests/suites/public-api/startSpan/parallel-root-spans-streamed/scenario.ts new file mode 100644 index 000000000000..5e8aedc0458a --- /dev/null +++ b/dev-packages/node-integration-tests/suites/public-api/startSpan/parallel-root-spans-streamed/scenario.ts @@ -0,0 +1,33 @@ +import * as Sentry from '@sentry/node'; +import { loggingTransport } from '@sentry-internal/node-integration-tests'; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + release: '1.0', + tracesSampleRate: 1.0, + traceLifecycle: 'stream', + transport: loggingTransport, +}); + +Sentry.getCurrentScope().setPropagationContext({ + parentSpanId: '1234567890123456', + traceId: '12345678901234567890123456789012', + sampleRand: Math.random(), +}); + +const spanIdTraceId = Sentry.startSpan( + { + name: 'test_span_1', + }, + span1 => span1.spanContext().traceId, +); + +Sentry.startSpan( + { + name: 'test_span_2', + attributes: { spanIdTraceId }, + }, + () => undefined, +); + +Sentry.flush(); diff --git a/dev-packages/node-integration-tests/suites/public-api/startSpan/parallel-root-spans-streamed/test.ts b/dev-packages/node-integration-tests/suites/public-api/startSpan/parallel-root-spans-streamed/test.ts new file mode 100644 index 000000000000..f332715bbc42 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/public-api/startSpan/parallel-root-spans-streamed/test.ts @@ -0,0 +1,32 @@ +import { afterAll, expect, test } from 'vitest'; +import { cleanupChildProcesses, createRunner } from '../../../../utils/runner'; + +afterAll(() => { + cleanupChildProcesses(); +}); + +test('sends manually started streamed parallel root spans in root context', async () => { + expect.assertions(7); + + await createRunner(__dirname, 'scenario.ts') + .expect({ span: { items: [{ name: 'test_span_1' }] } }) + .expect({ + span: spanContainer => { + expect(spanContainer).toBeDefined(); + const traceId = spanContainer.items[0]!.trace_id; + expect(traceId).toMatch(/^[0-9a-f]{32}$/); + + // It ignores propagation context of the root context + expect(traceId).not.toBe('12345678901234567890123456789012'); + expect(spanContainer.items[0]!.parent_span_id).toBeUndefined(); + + // Different trace ID than the first span + const trace1Id = spanContainer.items[0]!.attributes?.spanIdTraceId?.value; + expect(trace1Id).toMatch(/^[0-9a-f]{32}$/); + + expect(trace1Id).not.toBe(traceId); + }, + }) + .start() + .completed(); +}); diff --git a/dev-packages/node-integration-tests/suites/public-api/startSpan/parallel-spans-in-scope-streamed/scenario.ts b/dev-packages/node-integration-tests/suites/public-api/startSpan/parallel-spans-in-scope-streamed/scenario.ts new file mode 100644 index 000000000000..d688d3c3adf7 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/public-api/startSpan/parallel-spans-in-scope-streamed/scenario.ts @@ -0,0 +1,29 @@ +import * as Sentry from '@sentry/node'; +import { loggingTransport } from '@sentry-internal/node-integration-tests'; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + release: '1.0', + tracesSampleRate: 1.0, + traceLifecycle: 'stream', + transport: loggingTransport, +}); + +Sentry.withScope(() => { + const spanIdTraceId = Sentry.startSpan( + { + name: 'test_span_1', + }, + span1 => span1.spanContext().traceId, + ); + + Sentry.startSpan( + { + name: 'test_span_2', + attributes: { spanIdTraceId }, + }, + () => undefined, + ); +}); + +Sentry.flush(); diff --git a/dev-packages/node-integration-tests/suites/public-api/startSpan/parallel-spans-in-scope-streamed/test.ts b/dev-packages/node-integration-tests/suites/public-api/startSpan/parallel-spans-in-scope-streamed/test.ts new file mode 100644 index 000000000000..02456c9e93b2 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/public-api/startSpan/parallel-spans-in-scope-streamed/test.ts @@ -0,0 +1,29 @@ +import { afterAll, expect, test } from 'vitest'; +import { cleanupChildProcesses, createRunner } from '../../../../utils/runner'; + +afterAll(() => { + cleanupChildProcesses(); +}); + +test('sends manually started streamed parallel root spans outside of root context', async () => { + expect.assertions(6); + + await createRunner(__dirname, 'scenario.ts') + .expect({ span: { items: [{ name: 'test_span_1' }] } }) + .expect({ + span: spanContainer => { + expect(spanContainer).toBeDefined(); + const traceId = spanContainer.items[0]!.trace_id; + expect(traceId).toMatch(/^[0-9a-f]{32}$/); + expect(spanContainer.items[0]!.parent_span_id).toBeUndefined(); + + const trace1Id = spanContainer.items[0]!.attributes?.spanIdTraceId?.value; + expect(trace1Id).toMatch(/^[0-9a-f]{32}$/); + + // Different trace ID as the first span + expect(trace1Id).not.toBe(traceId); + }, + }) + .start() + .completed(); +}); diff --git a/dev-packages/node-integration-tests/suites/public-api/startSpan/parallel-spans-in-scope-with-parentSpanId-streamed/scenario.ts b/dev-packages/node-integration-tests/suites/public-api/startSpan/parallel-spans-in-scope-with-parentSpanId-streamed/scenario.ts new file mode 100644 index 000000000000..64f194549572 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/public-api/startSpan/parallel-spans-in-scope-with-parentSpanId-streamed/scenario.ts @@ -0,0 +1,35 @@ +import * as Sentry from '@sentry/node'; +import { loggingTransport } from '@sentry-internal/node-integration-tests'; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + release: '1.0', + tracesSampleRate: 1.0, + traceLifecycle: 'stream', + transport: loggingTransport, +}); + +Sentry.withScope(scope => { + scope.setPropagationContext({ + parentSpanId: '1234567890123456', + traceId: '12345678901234567890123456789012', + sampleRand: Math.random(), + }); + + const spanIdTraceId = Sentry.startSpan( + { + name: 'test_span_1', + }, + span1 => span1.spanContext().traceId, + ); + + Sentry.startSpan( + { + name: 'test_span_2', + attributes: { spanIdTraceId }, + }, + () => undefined, + ); +}); + +Sentry.flush(); diff --git a/dev-packages/node-integration-tests/suites/public-api/startSpan/parallel-spans-in-scope-with-parentSpanId-streamed/test.ts b/dev-packages/node-integration-tests/suites/public-api/startSpan/parallel-spans-in-scope-with-parentSpanId-streamed/test.ts new file mode 100644 index 000000000000..325f0f0d5d42 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/public-api/startSpan/parallel-spans-in-scope-with-parentSpanId-streamed/test.ts @@ -0,0 +1,29 @@ +import { afterAll, expect, test } from 'vitest'; +import { cleanupChildProcesses, createRunner } from '../../../../utils/runner'; + +afterAll(() => { + cleanupChildProcesses(); +}); + +test('sends manually started streamed parallel root spans outside of root context with parentSpanId', async () => { + expect.assertions(6); + + await createRunner(__dirname, 'scenario.ts') + .expect({ span: { items: [{ name: 'test_span_1' }] } }) + .expect({ + span: spanContainer => { + expect(spanContainer).toBeDefined(); + const traceId = spanContainer.items[0]!.trace_id; + expect(traceId).toMatch(/^[0-9a-f]{32}$/); + expect(spanContainer.items[0]!.parent_span_id).toBeUndefined(); + + const trace1Id = spanContainer.items[0]!.attributes?.spanIdTraceId?.value; + expect(trace1Id).toMatch(/^[0-9a-f]{32}$/); + + // Different trace ID as the first span + expect(trace1Id).not.toBe(traceId); + }, + }) + .start() + .completed(); +}); diff --git a/dev-packages/node-integration-tests/suites/public-api/startSpan/updateName-method-streamed/scenario.ts b/dev-packages/node-integration-tests/suites/public-api/startSpan/updateName-method-streamed/scenario.ts new file mode 100644 index 000000000000..2cbbaef888ae --- /dev/null +++ b/dev-packages/node-integration-tests/suites/public-api/startSpan/updateName-method-streamed/scenario.ts @@ -0,0 +1,19 @@ +import * as Sentry from '@sentry/node'; +import { loggingTransport } from '@sentry-internal/node-integration-tests'; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + release: '1.0', + tracesSampleRate: 1.0, + traceLifecycle: 'stream', + transport: loggingTransport, +}); + +Sentry.startSpan( + { name: 'test_span', attributes: { [Sentry.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url' } }, + (span: Sentry.Span) => { + span.updateName('new name'); + }, +); + +void Sentry.flush(); diff --git a/dev-packages/node-integration-tests/suites/public-api/startSpan/updateName-method-streamed/test.ts b/dev-packages/node-integration-tests/suites/public-api/startSpan/updateName-method-streamed/test.ts new file mode 100644 index 000000000000..f9d15cf60e30 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/public-api/startSpan/updateName-method-streamed/test.ts @@ -0,0 +1,26 @@ +import { SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/node'; +import { afterAll, test } from 'vitest'; +import { cleanupChildProcesses, createRunner } from '../../../../utils/runner'; + +afterAll(() => { + cleanupChildProcesses(); +}); + +test('updates the span name when calling `span.updateName` (streamed)', async () => { + await createRunner(__dirname, 'scenario.ts') + .expect({ + span: { + items: [ + { + name: 'new name', + is_segment: true, + attributes: { + [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: { type: 'string', value: 'url' }, + }, + }, + ], + }, + }) + .start() + .completed(); +}); diff --git a/dev-packages/node-integration-tests/suites/public-api/startSpan/updateSpanName-function-streamed/scenario.ts b/dev-packages/node-integration-tests/suites/public-api/startSpan/updateSpanName-function-streamed/scenario.ts new file mode 100644 index 000000000000..93d653d107aa --- /dev/null +++ b/dev-packages/node-integration-tests/suites/public-api/startSpan/updateSpanName-function-streamed/scenario.ts @@ -0,0 +1,19 @@ +import * as Sentry from '@sentry/node'; +import { loggingTransport } from '@sentry-internal/node-integration-tests'; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + release: '1.0', + tracesSampleRate: 1.0, + traceLifecycle: 'stream', + transport: loggingTransport, +}); + +Sentry.startSpan( + { name: 'test_span', attributes: { [Sentry.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url' } }, + (span: Sentry.Span) => { + Sentry.updateSpanName(span, 'new name'); + }, +); + +void Sentry.flush(); diff --git a/dev-packages/node-integration-tests/suites/public-api/startSpan/updateSpanName-function-streamed/test.ts b/dev-packages/node-integration-tests/suites/public-api/startSpan/updateSpanName-function-streamed/test.ts new file mode 100644 index 000000000000..ace2f0ca0d76 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/public-api/startSpan/updateSpanName-function-streamed/test.ts @@ -0,0 +1,26 @@ +import { SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/node'; +import { afterAll, test } from 'vitest'; +import { cleanupChildProcesses, createRunner } from '../../../../utils/runner'; + +afterAll(() => { + cleanupChildProcesses(); +}); + +test('updates the span name and source when calling `updateSpanName` (streamed)', async () => { + await createRunner(__dirname, 'scenario.ts') + .expect({ + span: { + items: [ + { + name: 'new name', + is_segment: true, + attributes: { + [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: { type: 'string', value: 'custom' }, + }, + }, + ], + }, + }) + .start() + .completed(); +}); diff --git a/dev-packages/node-integration-tests/suites/tracing/anthropic/test.ts b/dev-packages/node-integration-tests/suites/tracing/anthropic/test.ts index fb520e5e09b6..3241adfc161d 100644 --- a/dev-packages/node-integration-tests/suites/tracing/anthropic/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/anthropic/test.ts @@ -1,7 +1,6 @@ import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '@sentry/core'; import { afterAll, describe, expect } from 'vitest'; import { - ANTHROPIC_AI_RESPONSE_TIMESTAMP_ATTRIBUTE, GEN_AI_INPUT_MESSAGES_ATTRIBUTE, GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE, GEN_AI_OPERATION_NAME_ATTRIBUTE, @@ -84,7 +83,6 @@ describe('Anthropic integration', () => { // Fourth span - models.retrieve expect.objectContaining({ data: expect.objectContaining({ - [ANTHROPIC_AI_RESPONSE_TIMESTAMP_ATTRIBUTE]: '2024-05-08T05:20:00.000Z', [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'models', [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.models', [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ai.anthropic', @@ -212,7 +210,6 @@ describe('Anthropic integration', () => { // Fourth - models.retrieve with PII expect.objectContaining({ data: expect.objectContaining({ - [ANTHROPIC_AI_RESPONSE_TIMESTAMP_ATTRIBUTE]: '2024-05-08T05:20:00.000Z', [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'models', [GEN_AI_REQUEST_MODEL_ATTRIBUTE]: 'claude-3-haiku-20240307', [GEN_AI_RESPONSE_ID_ATTRIBUTE]: 'claude-3-haiku-20240307', diff --git a/dev-packages/node-integration-tests/suites/tracing/google-genai/test.ts b/dev-packages/node-integration-tests/suites/tracing/google-genai/test.ts index 91784a2de0e5..5d79cdf94202 100644 --- a/dev-packages/node-integration-tests/suites/tracing/google-genai/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/google-genai/test.ts @@ -32,24 +32,7 @@ describe('Google GenAI integration', () => { const EXPECTED_TRANSACTION_DEFAULT_PII_FALSE = { transaction: 'main', spans: expect.arrayContaining([ - // First span - chats.create - expect.objectContaining({ - data: { - [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'chat', - [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.chat', - [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ai.google_genai', - [GEN_AI_SYSTEM_ATTRIBUTE]: 'google_genai', - [GEN_AI_REQUEST_MODEL_ATTRIBUTE]: 'gemini-1.5-pro', - [GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE]: 0.8, - [GEN_AI_REQUEST_TOP_P_ATTRIBUTE]: 0.9, - [GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE]: 150, - }, - description: 'chat gemini-1.5-pro create', - op: 'gen_ai.chat', - origin: 'auto.ai.google_genai', - status: 'ok', - }), - // Second span - chat.sendMessage (should get model from context) + // chat.sendMessage (should get model from context) expect.objectContaining({ data: { [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'chat', @@ -66,7 +49,7 @@ describe('Google GenAI integration', () => { origin: 'auto.ai.google_genai', status: 'ok', }), - // Third span - models.generateContent + // models.generateContent expect.objectContaining({ data: { [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', @@ -86,7 +69,7 @@ describe('Google GenAI integration', () => { origin: 'auto.ai.google_genai', status: 'ok', }), - // Fourth span - error handling + // error handling expect.objectContaining({ data: { [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', @@ -106,25 +89,7 @@ describe('Google GenAI integration', () => { const EXPECTED_TRANSACTION_DEFAULT_PII_TRUE = { transaction: 'main', spans: expect.arrayContaining([ - // First span - chats.create with PII - expect.objectContaining({ - data: expect.objectContaining({ - [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'chat', - [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.chat', - [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ai.google_genai', - [GEN_AI_SYSTEM_ATTRIBUTE]: 'google_genai', - [GEN_AI_REQUEST_MODEL_ATTRIBUTE]: 'gemini-1.5-pro', - [GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE]: 0.8, - [GEN_AI_REQUEST_TOP_P_ATTRIBUTE]: 0.9, - [GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE]: 150, - [GEN_AI_INPUT_MESSAGES_ATTRIBUTE]: '[{"role":"user","parts":[{"text":"Hello, how are you?"}]}]', - }), - description: 'chat gemini-1.5-pro create', - op: 'gen_ai.chat', - origin: 'auto.ai.google_genai', - status: 'ok', - }), - // Second span - chat.sendMessage with PII + // chat.sendMessage with PII expect.objectContaining({ data: expect.objectContaining({ [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'chat', @@ -143,7 +108,7 @@ describe('Google GenAI integration', () => { origin: 'auto.ai.google_genai', status: 'ok', }), - // Third span - models.generateContent with PII + // models.generateContent with PII expect.objectContaining({ data: expect.objectContaining({ [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', @@ -165,7 +130,7 @@ describe('Google GenAI integration', () => { origin: 'auto.ai.google_genai', status: 'ok', }), - // Fourth span - error handling with PII + // error handling with PII expect.objectContaining({ data: expect.objectContaining({ [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', @@ -309,7 +274,7 @@ describe('Google GenAI integration', () => { const EXPECTED_TRANSACTION_STREAMING = { transaction: 'main', spans: expect.arrayContaining([ - // First span - models.generateContentStream (streaming) + // models.generateContentStream (streaming) expect.objectContaining({ data: expect.objectContaining({ [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', @@ -333,24 +298,7 @@ describe('Google GenAI integration', () => { origin: 'auto.ai.google_genai', status: 'ok', }), - // Second span - chat.create - expect.objectContaining({ - data: expect.objectContaining({ - [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'chat', - [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.chat', - [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ai.google_genai', - [GEN_AI_SYSTEM_ATTRIBUTE]: 'google_genai', - [GEN_AI_REQUEST_MODEL_ATTRIBUTE]: 'gemini-1.5-pro', - [GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE]: 0.8, - [GEN_AI_REQUEST_TOP_P_ATTRIBUTE]: 0.9, - [GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE]: 150, - }), - description: 'chat gemini-1.5-pro create', - op: 'gen_ai.chat', - origin: 'auto.ai.google_genai', - status: 'ok', - }), - // Third span - chat.sendMessageStream (streaming) + // chat.sendMessageStream (streaming) expect.objectContaining({ data: expect.objectContaining({ [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'chat', @@ -367,7 +315,7 @@ describe('Google GenAI integration', () => { origin: 'auto.ai.google_genai', status: 'ok', }), - // Fourth span - blocked content streaming + // blocked content streaming expect.objectContaining({ data: expect.objectContaining({ [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', @@ -379,7 +327,7 @@ describe('Google GenAI integration', () => { origin: 'auto.ai.google_genai', status: 'internal_error', }), - // Fifth span - error handling for streaming + // error handling for streaming expect.objectContaining({ data: expect.objectContaining({ [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', @@ -397,7 +345,7 @@ describe('Google GenAI integration', () => { const EXPECTED_TRANSACTION_STREAMING_PII_TRUE = { transaction: 'main', spans: expect.arrayContaining([ - // First span - models.generateContentStream (streaming) with PII + // models.generateContentStream (streaming) with PII expect.objectContaining({ data: expect.objectContaining({ [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', @@ -422,24 +370,7 @@ describe('Google GenAI integration', () => { origin: 'auto.ai.google_genai', status: 'ok', }), - // Second span - chat.create - expect.objectContaining({ - data: expect.objectContaining({ - [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'chat', - [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.chat', - [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ai.google_genai', - [GEN_AI_SYSTEM_ATTRIBUTE]: 'google_genai', - [GEN_AI_REQUEST_MODEL_ATTRIBUTE]: 'gemini-1.5-pro', - [GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE]: 0.8, - [GEN_AI_REQUEST_TOP_P_ATTRIBUTE]: 0.9, - [GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE]: 150, - }), - description: 'chat gemini-1.5-pro create', - op: 'gen_ai.chat', - origin: 'auto.ai.google_genai', - status: 'ok', - }), - // Third span - chat.sendMessageStream (streaming) with PII + // chat.sendMessageStream (streaming) with PII expect.objectContaining({ data: expect.objectContaining({ [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'chat', @@ -461,7 +392,7 @@ describe('Google GenAI integration', () => { origin: 'auto.ai.google_genai', status: 'ok', }), - // Fourth span - blocked content stream with PII + // blocked content stream with PII expect.objectContaining({ data: expect.objectContaining({ [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', @@ -478,7 +409,7 @@ describe('Google GenAI integration', () => { origin: 'auto.ai.google_genai', status: 'internal_error', }), - // Fifth span - error handling for streaming with PII + // error handling for streaming with PII expect.objectContaining({ data: expect.objectContaining({ [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', diff --git a/dev-packages/node-integration-tests/suites/tracing/ignoreSpans-streamed/children/instrument.mjs b/dev-packages/node-integration-tests/suites/tracing/ignoreSpans-streamed/children/instrument.mjs new file mode 100644 index 000000000000..266ffdc4f52c --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/ignoreSpans-streamed/children/instrument.mjs @@ -0,0 +1,12 @@ +import * as Sentry from '@sentry/node'; +import { loggingTransport } from '@sentry-internal/node-integration-tests'; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + release: '1.0', + tracesSampleRate: 1.0, + transport: loggingTransport, + traceLifecycle: 'stream', + ignoreSpans: ['expressInit', /custom-to-drop/, { op: 'ignored-op' }], + clientReportFlushInterval: 1_000, +}); diff --git a/dev-packages/node-integration-tests/suites/tracing/ignoreSpans-streamed/children/server.mjs b/dev-packages/node-integration-tests/suites/tracing/ignoreSpans-streamed/children/server.mjs new file mode 100644 index 000000000000..e8af8b8c92c6 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/ignoreSpans-streamed/children/server.mjs @@ -0,0 +1,51 @@ +import express from 'express'; +import cors from 'cors'; +import * as Sentry from '@sentry/node'; +import { startExpressServerAndSendPortToRunner } from '@sentry-internal/node-integration-tests'; + +const app = express(); + +app.use(cors()); + +app.get('/test/express', (_req, res) => { + Sentry.startSpan( + { + name: 'custom-to-drop', + op: 'custom', + }, + () => { + Sentry.startSpan( + { + name: 'custom', + op: 'custom', + }, + () => { + Sentry.startSpan({ name: 'custom-grandchild', op: 'custom' }, () => { + Sentry.startSpan({ name: 'custom-to-drop-grand-grandchild', op: 'custom' }, () => { + Sentry.startSpan({ name: 'custom-grand-grand-grandchild', op: 'custom' }, () => {}); + }); + }); + Sentry.startSpan({ name: 'custom-grandchild-2', op: 'custom' }, () => {}); + }, + ); + }, + ); + + Sentry.startSpan({ name: 'name-passes-but-op-not-span-1', op: 'ignored-op' }, () => {}); + Sentry.startSpan( + // sentry.op attribute has precedence over top op argument + { name: 'name-passes-but-op-not-span-2', op: 'keep', attributes: { 'sentry.op': 'ignored-op' } }, + () => {}, + ); + res.send({ response: 'response 1' }); + + setTimeout(() => { + // flush to avoid waiting for the span buffer timeout to send spans + // but defer it to the next tick to let the SDK finish the http.server span first. + Sentry.flush(); + }); +}); + +Sentry.setupExpressErrorHandler(app); + +startExpressServerAndSendPortToRunner(app); diff --git a/dev-packages/node-integration-tests/suites/tracing/ignoreSpans-streamed/children/test.ts b/dev-packages/node-integration-tests/suites/tracing/ignoreSpans-streamed/children/test.ts new file mode 100644 index 000000000000..263f8f74c1c3 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/ignoreSpans-streamed/children/test.ts @@ -0,0 +1,69 @@ +import { afterAll, describe, expect } from 'vitest'; +import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../../utils/runner'; +import { SEMANTIC_ATTRIBUTE_SENTRY_OP } from '@sentry/core'; + +describe('filtering child spans with ignoreSpans (streaming)', () => { + afterAll(() => { + cleanupChildProcesses(); + }); + + createEsmAndCjsTests(__dirname, 'server.mjs', 'instrument.mjs', (createRunner, test) => { + test('child spans are dropped and remaining spans correctly parented', async () => { + const runner = createRunner() + .unignore('client_report') + .expect({ + client_report: { + discarded_events: [ + { + category: 'span', + quantity: 5, + reason: 'ignored', + }, + ], + }, + }) + .expect({ + span: container => { + // 5 spans: 1 root, 2 middleware, 1 request handler, 1 custom + // Would be 7 if we didn't ignore the 'middleware - expressInit' and 'custom-to-drop' spans + expect(container.items).toHaveLength(8); + const getSpan = (name: string, op: string) => + container.items.find( + item => item.name === name && item.attributes?.[SEMANTIC_ATTRIBUTE_SENTRY_OP]?.value === op, + ); + const queryMiddlewareSpan = getSpan('query', 'middleware.express'); + const corsMiddlewareSpan = getSpan('corsMiddleware', 'middleware.express'); + const requestHandlerSpan = getSpan('/test/express', 'request_handler.express'); + const httpServerSpan = getSpan('GET /test/express', 'http.server'); + const customSpan = getSpan('custom', 'custom'); + const customGrandchildSpan = getSpan('custom-grandchild', 'custom'); + const customGrandchild2Span = getSpan('custom-grandchild-2', 'custom'); + const customGrandGrandGrandChildSpan = getSpan('custom-grand-grand-grandchild', 'custom'); + + expect(queryMiddlewareSpan).toBeDefined(); + expect(corsMiddlewareSpan).toBeDefined(); + expect(requestHandlerSpan).toBeDefined(); + expect(httpServerSpan).toBeDefined(); + expect(customSpan).toBeDefined(); + expect(customGrandchildSpan).toBeDefined(); + expect(customGrandchild2Span).toBeDefined(); + expect(customGrandGrandGrandChildSpan).toBeDefined(); + + expect(customGrandchildSpan?.parent_span_id).toBe(customSpan?.span_id); + expect(customGrandchild2Span?.parent_span_id).toBe(customSpan?.span_id); + expect(customGrandGrandGrandChildSpan?.parent_span_id).toBe(customGrandchildSpan?.span_id); + expect(customSpan?.parent_span_id).toBe(requestHandlerSpan?.span_id); + expect(requestHandlerSpan?.parent_span_id).toBe(httpServerSpan?.span_id); + expect(queryMiddlewareSpan?.parent_span_id).toBe(httpServerSpan?.span_id); + expect(corsMiddlewareSpan?.parent_span_id).toBe(httpServerSpan?.span_id); + expect(httpServerSpan?.parent_span_id).toBeUndefined(); + }, + }) + .start(); + + runner.makeRequest('get', '/test/express'); + + await runner.completed(); + }); + }); +}); diff --git a/dev-packages/node-integration-tests/suites/tracing/ignoreSpans-streamed/segments/instrument.mjs b/dev-packages/node-integration-tests/suites/tracing/ignoreSpans-streamed/segments/instrument.mjs new file mode 100644 index 000000000000..4d14e615745b --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/ignoreSpans-streamed/segments/instrument.mjs @@ -0,0 +1,12 @@ +import * as Sentry from '@sentry/node'; +import { loggingTransport } from '@sentry-internal/node-integration-tests'; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + release: '1.0', + tracesSampleRate: 1.0, + transport: loggingTransport, + traceLifecycle: 'stream', + ignoreSpans: [/\/health/], + clientReportFlushInterval: 1_000, +}); diff --git a/dev-packages/node-integration-tests/suites/tracing/ignoreSpans-streamed/segments/server.mjs b/dev-packages/node-integration-tests/suites/tracing/ignoreSpans-streamed/segments/server.mjs new file mode 100644 index 000000000000..b9ff3398b158 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/ignoreSpans-streamed/segments/server.mjs @@ -0,0 +1,25 @@ +import express from 'express'; +import cors from 'cors'; +import * as Sentry from '@sentry/node'; +import { startExpressServerAndSendPortToRunner } from '@sentry-internal/node-integration-tests'; + +const app = express(); + +app.use(cors()); + +app.get('/health', (_req, res) => { + res.send({ status: 'ok-health' }); +}); + +app.get('/ok', (_req, res) => { + res.send({ status: 'ok' }); + setTimeout(() => { + // flush to avoid waiting for the span buffer timeout to send spans + // but defer it to the next tick to let the SDK finish the http.server span first. + Sentry.flush(); + }); +}); + +Sentry.setupExpressErrorHandler(app); + +startExpressServerAndSendPortToRunner(app); diff --git a/dev-packages/node-integration-tests/suites/tracing/ignoreSpans-streamed/segments/test.ts b/dev-packages/node-integration-tests/suites/tracing/ignoreSpans-streamed/segments/test.ts new file mode 100644 index 000000000000..538c9c77a532 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/ignoreSpans-streamed/segments/test.ts @@ -0,0 +1,45 @@ +import { afterAll, describe, expect } from 'vitest'; +import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../../utils/runner'; + +describe('filtering segment spans with ignoreSpans (streaming)', () => { + afterAll(() => { + cleanupChildProcesses(); + }); + + createEsmAndCjsTests(__dirname, 'server.mjs', 'instrument.mjs', (createRunner, test) => { + test('segment spans matching ignoreSpans are dropped including all children', async () => { + const runner = createRunner() + .unignore('client_report') + .expect({ + client_report: { + discarded_events: [ + { + category: 'span', + quantity: 5, // 1 segment ignored + 4 child spans (implicitly ignored) + reason: 'ignored', + }, + ], + }, + }) + .expect({ + span: container => { + expect(container.items).toHaveLength(5); + const segmentSpan = container.items.find(s => s.name === 'GET /ok' && !!s.is_segment); + + expect(segmentSpan).toBeDefined(); + expect(container.items.every(s => s.trace_id === segmentSpan!.trace_id)).toBe(true); + }, + }) + + .start(); + + const res = await runner.makeRequest('get', '/health'); + expect((res as { status: string }).status).toBe('ok-health'); + + const res2 = await runner.makeRequest('get', '/ok'); // contains all spans + expect((res2 as { status: string }).status).toBe('ok'); + + await runner.completed(); + }); + }); +}); diff --git a/dev-packages/node-integration-tests/suites/tracing/langchain/instrument-with-pii.mjs b/dev-packages/node-integration-tests/suites/tracing/langchain/instrument-with-pii.mjs index cb68a6f7683e..84212d887ee7 100644 --- a/dev-packages/node-integration-tests/suites/tracing/langchain/instrument-with-pii.mjs +++ b/dev-packages/node-integration-tests/suites/tracing/langchain/instrument-with-pii.mjs @@ -9,7 +9,7 @@ Sentry.init({ transport: loggingTransport, beforeSendTransaction: event => { // Filter out mock express server transactions - if (event.transaction.includes('/v1/messages')) { + if (event.transaction.includes('/v1/messages') || event.transaction.includes('/v1/embeddings')) { return null; } return event; diff --git a/dev-packages/node-integration-tests/suites/tracing/langchain/instrument.mjs b/dev-packages/node-integration-tests/suites/tracing/langchain/instrument.mjs index b4ce44f3e91a..1fb023b535d4 100644 --- a/dev-packages/node-integration-tests/suites/tracing/langchain/instrument.mjs +++ b/dev-packages/node-integration-tests/suites/tracing/langchain/instrument.mjs @@ -9,7 +9,7 @@ Sentry.init({ transport: loggingTransport, beforeSendTransaction: event => { // Filter out mock express server transactions - if (event.transaction.includes('/v1/messages')) { + if (event.transaction.includes('/v1/messages') || event.transaction.includes('/v1/embeddings')) { return null; } return event; diff --git a/dev-packages/node-integration-tests/suites/tracing/langchain/scenario-embeddings.mjs b/dev-packages/node-integration-tests/suites/tracing/langchain/scenario-embeddings.mjs new file mode 100644 index 000000000000..c6cf4c0bd1a1 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/langchain/scenario-embeddings.mjs @@ -0,0 +1,82 @@ +import { OpenAIEmbeddings } from '@langchain/openai'; +import * as Sentry from '@sentry/node'; +import express from 'express'; + +function startMockOpenAIServer() { + const app = express(); + app.use(express.json()); + + app.post('/v1/embeddings', (req, res) => { + const { model, input } = req.body; + + if (model === 'error-model') { + res.status(400).json({ + error: { + message: 'Model not found', + type: 'invalid_request_error', + }, + }); + return; + } + + const inputs = Array.isArray(input) ? input : [input]; + res.json({ + object: 'list', + data: inputs.map((_, i) => ({ + object: 'embedding', + embedding: [0.1, 0.2, 0.3], + index: i, + })), + model: model, + usage: { + prompt_tokens: 10, + total_tokens: 10, + }, + }); + }); + + return new Promise(resolve => { + const server = app.listen(0, () => { + resolve(server); + }); + }); +} + +async function run() { + const server = await startMockOpenAIServer(); + const baseUrl = `http://localhost:${server.address().port}/v1`; + + await Sentry.startSpan({ op: 'function', name: 'main' }, async () => { + // Test 1: embedQuery + const embeddings = new OpenAIEmbeddings({ + model: 'text-embedding-3-small', + dimensions: 1536, + apiKey: 'mock-api-key', + configuration: { baseURL: baseUrl }, + }); + + await embeddings.embedQuery('Hello world'); + + // Test 2: embedDocuments + await embeddings.embedDocuments(['First document', 'Second document']); + + // Test 3: Error handling + const errorEmbeddings = new OpenAIEmbeddings({ + model: 'error-model', + apiKey: 'mock-api-key', + configuration: { baseURL: baseUrl }, + }); + + try { + await errorEmbeddings.embedQuery('This will fail'); + } catch { + // Expected error + } + }); + + await Sentry.flush(2000); + + server.close(); +} + +run(); diff --git a/dev-packages/node-integration-tests/suites/tracing/langchain/test.ts b/dev-packages/node-integration-tests/suites/tracing/langchain/test.ts index 07cd93d331b7..39127c7e3055 100644 --- a/dev-packages/node-integration-tests/suites/tracing/langchain/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/langchain/test.ts @@ -1,9 +1,12 @@ import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '@sentry/core'; import { afterAll, describe, expect } from 'vitest'; import { + GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE, + GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE, GEN_AI_INPUT_MESSAGES_ATTRIBUTE, GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE, GEN_AI_OPERATION_NAME_ATTRIBUTE, + GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE, GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE, GEN_AI_REQUEST_MODEL_ATTRIBUTE, GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE, @@ -430,4 +433,120 @@ describe('LangChain integration', () => { .completed(); }); }); + + // ========================================================================= + // Embeddings tests + // ========================================================================= + + const EXPECTED_TRANSACTION_EMBEDDINGS = { + transaction: 'main', + spans: expect.arrayContaining([ + // embedQuery span + expect.objectContaining({ + data: expect.objectContaining({ + [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'embeddings', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE, + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ai.langchain', + [GEN_AI_SYSTEM_ATTRIBUTE]: 'openai', + [GEN_AI_REQUEST_MODEL_ATTRIBUTE]: 'text-embedding-3-small', + [GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE]: 1536, + }), + description: 'embeddings text-embedding-3-small', + op: GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE, + origin: 'auto.ai.langchain', + status: 'ok', + }), + // embedDocuments span + expect.objectContaining({ + data: expect.objectContaining({ + [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'embeddings', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE, + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ai.langchain', + [GEN_AI_SYSTEM_ATTRIBUTE]: 'openai', + [GEN_AI_REQUEST_MODEL_ATTRIBUTE]: 'text-embedding-3-small', + }), + description: 'embeddings text-embedding-3-small', + op: GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE, + origin: 'auto.ai.langchain', + status: 'ok', + }), + // Error span + expect.objectContaining({ + data: expect.objectContaining({ + [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'embeddings', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE, + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ai.langchain', + [GEN_AI_SYSTEM_ATTRIBUTE]: 'openai', + [GEN_AI_REQUEST_MODEL_ATTRIBUTE]: 'error-model', + }), + description: 'embeddings error-model', + op: GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE, + origin: 'auto.ai.langchain', + status: 'internal_error', + }), + ]), + }; + + const EXPECTED_TRANSACTION_EMBEDDINGS_PII = { + transaction: 'main', + spans: expect.arrayContaining([ + // embedQuery span with input recorded + expect.objectContaining({ + data: expect.objectContaining({ + [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'embeddings', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE, + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ai.langchain', + [GEN_AI_SYSTEM_ATTRIBUTE]: 'openai', + [GEN_AI_REQUEST_MODEL_ATTRIBUTE]: 'text-embedding-3-small', + [GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE]: 'Hello world', + }), + description: 'embeddings text-embedding-3-small', + op: GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE, + origin: 'auto.ai.langchain', + status: 'ok', + }), + // embedDocuments span with input recorded + expect.objectContaining({ + data: expect.objectContaining({ + [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'embeddings', + [GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE]: JSON.stringify(['First document', 'Second document']), + }), + description: 'embeddings text-embedding-3-small', + op: GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE, + origin: 'auto.ai.langchain', + status: 'ok', + }), + ]), + }; + + createEsmAndCjsTests(__dirname, 'scenario-embeddings.mjs', 'instrument.mjs', (createRunner, test) => { + test('creates embedding spans with sendDefaultPii: false', async () => { + await createRunner().ignore('event').expect({ transaction: EXPECTED_TRANSACTION_EMBEDDINGS }).start().completed(); + }); + + test('does not create duplicate embedding spans from double module patching', async () => { + await createRunner() + .ignore('event') + .expect({ + transaction: event => { + const spans = event.spans || []; + const embeddingSpans = spans.filter(span => span.op === GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE); + // The scenario makes 3 embedding calls (2 successful + 1 error). + expect(embeddingSpans).toHaveLength(3); + }, + }) + .start() + .completed(); + }); + }); + + createEsmAndCjsTests(__dirname, 'scenario-embeddings.mjs', 'instrument-with-pii.mjs', (createRunner, test) => { + test('creates embedding spans with sendDefaultPii: true', async () => { + await createRunner() + .ignore('event') + .expect({ transaction: EXPECTED_TRANSACTION_EMBEDDINGS_PII }) + .start() + .completed(); + }); + }); }); diff --git a/dev-packages/node-integration-tests/suites/tracing/openai/openai-tool-calls/test.ts b/dev-packages/node-integration-tests/suites/tracing/openai/openai-tool-calls/test.ts index 5c61ec320c57..c66f5cb65c6b 100644 --- a/dev-packages/node-integration-tests/suites/tracing/openai/openai-tool-calls/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/openai/openai-tool-calls/test.ts @@ -17,11 +17,6 @@ import { GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE, - OPENAI_RESPONSE_ID_ATTRIBUTE, - OPENAI_RESPONSE_MODEL_ATTRIBUTE, - OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE, - OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE, - OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE, } from '../../../../../../packages/core/src/tracing/ai/gen-ai-attributes'; import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../../utils/runner'; @@ -99,11 +94,6 @@ describe('OpenAI Tool Calls integration', () => { [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 15, [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 25, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 40, - [OPENAI_RESPONSE_ID_ATTRIBUTE]: 'chatcmpl-tools-123', - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'gpt-4', - [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: '2023-03-01T06:31:40.000Z', - [OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: 25, - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 15, }, description: 'chat gpt-4', op: 'gen_ai.chat', @@ -127,11 +117,6 @@ describe('OpenAI Tool Calls integration', () => { [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 15, [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 25, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 40, - [OPENAI_RESPONSE_ID_ATTRIBUTE]: 'chatcmpl-stream-tools-123', - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'gpt-4', - [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: '2023-03-01T06:31:45.000Z', - [OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: 25, - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 15, }, description: 'chat gpt-4', op: 'gen_ai.chat', @@ -153,11 +138,6 @@ describe('OpenAI Tool Calls integration', () => { [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 8, [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 12, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 20, - [OPENAI_RESPONSE_ID_ATTRIBUTE]: 'resp_tools_789', - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'gpt-4', - [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: '2023-03-01T06:32:00.000Z', - [OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: 12, - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 8, }, description: 'chat gpt-4', op: 'gen_ai.chat', @@ -181,11 +161,6 @@ describe('OpenAI Tool Calls integration', () => { [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 8, [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 12, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 20, - [OPENAI_RESPONSE_ID_ATTRIBUTE]: 'resp_stream_tools_789', - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'gpt-4', - [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: '2023-03-01T06:31:50.000Z', - [OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: 12, - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 8, }, description: 'chat gpt-4', op: 'gen_ai.chat', @@ -217,11 +192,6 @@ describe('OpenAI Tool Calls integration', () => { [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 15, [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 25, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 40, - [OPENAI_RESPONSE_ID_ATTRIBUTE]: 'chatcmpl-tools-123', - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'gpt-4', - [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: '2023-03-01T06:31:40.000Z', - [OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: 25, - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 15, }, description: 'chat gpt-4', op: 'gen_ai.chat', @@ -248,11 +218,6 @@ describe('OpenAI Tool Calls integration', () => { [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 15, [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 25, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 40, - [OPENAI_RESPONSE_ID_ATTRIBUTE]: 'chatcmpl-stream-tools-123', - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'gpt-4', - [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: '2023-03-01T06:31:45.000Z', - [OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: 25, - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 15, }, description: 'chat gpt-4', op: 'gen_ai.chat', @@ -277,11 +242,6 @@ describe('OpenAI Tool Calls integration', () => { [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 8, [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 12, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 20, - [OPENAI_RESPONSE_ID_ATTRIBUTE]: 'resp_tools_789', - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'gpt-4', - [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: '2023-03-01T06:32:00.000Z', - [OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: 12, - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 8, }, description: 'chat gpt-4', op: 'gen_ai.chat', @@ -308,11 +268,6 @@ describe('OpenAI Tool Calls integration', () => { [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 8, [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 12, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 20, - [OPENAI_RESPONSE_ID_ATTRIBUTE]: 'resp_stream_tools_789', - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'gpt-4', - [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: '2023-03-01T06:31:50.000Z', - [OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: 12, - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 8, }, description: 'chat gpt-4', op: 'gen_ai.chat', diff --git a/dev-packages/node-integration-tests/suites/tracing/openai/test.ts b/dev-packages/node-integration-tests/suites/tracing/openai/test.ts index 9e7a1722db11..ae7715e9852c 100644 --- a/dev-packages/node-integration-tests/suites/tracing/openai/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/openai/test.ts @@ -21,11 +21,6 @@ import { GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE, - OPENAI_RESPONSE_ID_ATTRIBUTE, - OPENAI_RESPONSE_MODEL_ATTRIBUTE, - OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE, - OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE, - OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE, } from '../../../../../packages/core/src/tracing/ai/gen-ai-attributes'; import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../utils/runner'; @@ -52,11 +47,6 @@ describe('OpenAI integration', () => { [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 10, [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 15, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 25, - [OPENAI_RESPONSE_ID_ATTRIBUTE]: 'chatcmpl-mock123', - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'gpt-3.5-turbo', - [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: '2023-03-01T06:31:28.000Z', - [OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: 15, - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 10, }, description: 'chat gpt-3.5-turbo', op: 'gen_ai.chat', @@ -77,11 +67,6 @@ describe('OpenAI integration', () => { [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 5, [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 8, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 13, - [OPENAI_RESPONSE_ID_ATTRIBUTE]: 'resp_mock456', - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'gpt-3.5-turbo', - [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: '2023-03-01T06:31:30.000Z', - [OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: 8, - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 5, }, description: 'chat gpt-3.5-turbo', op: 'gen_ai.chat', @@ -118,12 +103,7 @@ describe('OpenAI integration', () => { [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 12, [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 18, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 30, - [OPENAI_RESPONSE_ID_ATTRIBUTE]: 'chatcmpl-stream-123', - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'gpt-4', [GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true, - [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: '2023-03-01T06:31:40.000Z', - [OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: 18, - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 12, }, description: 'chat gpt-4', op: 'gen_ai.chat', @@ -145,12 +125,7 @@ describe('OpenAI integration', () => { [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 6, [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 10, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 16, - [OPENAI_RESPONSE_ID_ATTRIBUTE]: 'resp_stream_456', - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'gpt-4', [GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true, - [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: '2023-03-01T06:31:50.000Z', - [OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: 10, - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 6, }, description: 'chat gpt-4', op: 'gen_ai.chat', @@ -199,11 +174,6 @@ describe('OpenAI integration', () => { [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 10, [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 15, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 25, - [OPENAI_RESPONSE_ID_ATTRIBUTE]: 'chatcmpl-mock123', - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'gpt-3.5-turbo', - [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: '2023-03-01T06:31:28.000Z', - [OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: 15, - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 10, }, description: 'chat gpt-3.5-turbo', op: 'gen_ai.chat', @@ -227,11 +197,6 @@ describe('OpenAI integration', () => { [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 5, [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 8, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 13, - [OPENAI_RESPONSE_ID_ATTRIBUTE]: 'resp_mock456', - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'gpt-3.5-turbo', - [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: '2023-03-01T06:31:30.000Z', - [OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: 8, - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 5, }, description: 'chat gpt-3.5-turbo', op: 'gen_ai.chat', @@ -276,12 +241,7 @@ describe('OpenAI integration', () => { [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 12, [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 18, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 30, - [OPENAI_RESPONSE_ID_ATTRIBUTE]: 'chatcmpl-stream-123', - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'gpt-4', [GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true, - [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: '2023-03-01T06:31:40.000Z', - [OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: 18, - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 12, }), description: 'chat gpt-4', op: 'gen_ai.chat', @@ -307,12 +267,7 @@ describe('OpenAI integration', () => { [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 6, [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 10, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 16, - [OPENAI_RESPONSE_ID_ATTRIBUTE]: 'resp_stream_456', - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'gpt-4', [GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true, - [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: '2023-03-01T06:31:50.000Z', - [OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: 10, - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 6, }), description: 'chat gpt-4', op: 'gen_ai.chat', @@ -406,8 +361,6 @@ describe('OpenAI integration', () => { [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: 'text-embedding-3-small', [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 10, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 10, - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'text-embedding-3-small', - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 10, }, description: 'embeddings text-embedding-3-small', op: 'gen_ai.embeddings', @@ -448,8 +401,6 @@ describe('OpenAI integration', () => { [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: 'text-embedding-3-small', [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 10, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 10, - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'text-embedding-3-small', - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 10, }, description: 'embeddings text-embedding-3-small', op: 'gen_ai.embeddings', @@ -483,8 +434,6 @@ describe('OpenAI integration', () => { [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: 'text-embedding-3-small', [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 10, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 10, - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'text-embedding-3-small', - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 10, }, description: 'embeddings text-embedding-3-small', op: 'gen_ai.embeddings', @@ -542,11 +491,6 @@ describe('OpenAI integration', () => { [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 10, [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 15, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 25, - [OPENAI_RESPONSE_ID_ATTRIBUTE]: 'chatcmpl-mock123', - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'gpt-3.5-turbo', - [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: '2023-03-01T06:31:28.000Z', - [OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: 15, - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 10, }, op: 'gen_ai.chat', origin: 'auto.ai.openai', @@ -589,11 +533,6 @@ describe('OpenAI integration', () => { [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 10, [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 15, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 25, - [OPENAI_RESPONSE_ID_ATTRIBUTE]: 'chatcmpl-mock123', - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'gpt-3.5-turbo', - [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: '2023-03-01T06:31:28.000Z', - [OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: 15, - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 10, }, op: 'gen_ai.chat', origin: 'auto.ai.openai', diff --git a/dev-packages/node-integration-tests/suites/tracing/openai/v6/test.ts b/dev-packages/node-integration-tests/suites/tracing/openai/v6/test.ts index 626e53248e66..b282282305eb 100644 --- a/dev-packages/node-integration-tests/suites/tracing/openai/v6/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/openai/v6/test.ts @@ -20,11 +20,6 @@ import { GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE, - OPENAI_RESPONSE_ID_ATTRIBUTE, - OPENAI_RESPONSE_MODEL_ATTRIBUTE, - OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE, - OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE, - OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE, } from '../../../../../../packages/core/src/tracing/ai/gen-ai-attributes'; import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../../utils/runner'; @@ -51,11 +46,6 @@ describe('OpenAI integration (V6)', () => { [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 10, [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 15, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 25, - [OPENAI_RESPONSE_ID_ATTRIBUTE]: 'chatcmpl-mock123', - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'gpt-3.5-turbo', - [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: '2023-03-01T06:31:28.000Z', - [OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: 15, - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 10, }, description: 'chat gpt-3.5-turbo', op: 'gen_ai.chat', @@ -76,11 +66,6 @@ describe('OpenAI integration (V6)', () => { [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 5, [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 8, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 13, - [OPENAI_RESPONSE_ID_ATTRIBUTE]: 'resp_mock456', - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'gpt-3.5-turbo', - [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: '2023-03-01T06:31:30.000Z', - [OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: 8, - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 5, }, description: 'chat gpt-3.5-turbo', op: 'gen_ai.chat', @@ -117,12 +102,7 @@ describe('OpenAI integration (V6)', () => { [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 12, [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 18, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 30, - [OPENAI_RESPONSE_ID_ATTRIBUTE]: 'chatcmpl-stream-123', - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'gpt-4', [GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true, - [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: '2023-03-01T06:31:40.000Z', - [OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: 18, - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 12, }, description: 'chat gpt-4', op: 'gen_ai.chat', @@ -144,12 +124,7 @@ describe('OpenAI integration (V6)', () => { [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 6, [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 10, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 16, - [OPENAI_RESPONSE_ID_ATTRIBUTE]: 'resp_stream_456', - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'gpt-4', [GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true, - [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: '2023-03-01T06:31:50.000Z', - [OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: 10, - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 6, }, description: 'chat gpt-4', op: 'gen_ai.chat', @@ -196,11 +171,6 @@ describe('OpenAI integration (V6)', () => { [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 10, [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 15, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 25, - [OPENAI_RESPONSE_ID_ATTRIBUTE]: 'chatcmpl-mock123', - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'gpt-3.5-turbo', - [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: '2023-03-01T06:31:28.000Z', - [OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: 15, - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 10, }, description: 'chat gpt-3.5-turbo', op: 'gen_ai.chat', @@ -224,11 +194,6 @@ describe('OpenAI integration (V6)', () => { [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 5, [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 8, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 13, - [OPENAI_RESPONSE_ID_ATTRIBUTE]: 'resp_mock456', - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'gpt-3.5-turbo', - [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: '2023-03-01T06:31:30.000Z', - [OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: 8, - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 5, }, description: 'chat gpt-3.5-turbo', op: 'gen_ai.chat', @@ -271,12 +236,7 @@ describe('OpenAI integration (V6)', () => { [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 12, [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 18, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 30, - [OPENAI_RESPONSE_ID_ATTRIBUTE]: 'chatcmpl-stream-123', - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'gpt-4', [GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true, - [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: '2023-03-01T06:31:40.000Z', - [OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: 18, - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 12, }), description: 'chat gpt-4', op: 'gen_ai.chat', @@ -302,12 +262,7 @@ describe('OpenAI integration (V6)', () => { [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 6, [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 10, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 16, - [OPENAI_RESPONSE_ID_ATTRIBUTE]: 'resp_stream_456', - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'gpt-4', [GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true, - [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: '2023-03-01T06:31:50.000Z', - [OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: 10, - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 6, }), description: 'chat gpt-4', op: 'gen_ai.chat', @@ -375,8 +330,6 @@ describe('OpenAI integration (V6)', () => { [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: 'text-embedding-3-small', [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 10, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 10, - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'text-embedding-3-small', - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 10, }, description: 'embeddings text-embedding-3-small', op: 'gen_ai.embeddings', @@ -417,8 +370,6 @@ describe('OpenAI integration (V6)', () => { [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: 'text-embedding-3-small', [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 10, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 10, - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'text-embedding-3-small', - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 10, }, description: 'embeddings text-embedding-3-small', op: 'gen_ai.embeddings', @@ -452,8 +403,6 @@ describe('OpenAI integration (V6)', () => { [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: 'text-embedding-3-small', [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 10, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 10, - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'text-embedding-3-small', - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 10, }, description: 'embeddings text-embedding-3-small', op: 'gen_ai.embeddings', @@ -596,11 +545,6 @@ describe('OpenAI integration (V6)', () => { [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 10, [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 15, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 25, - [OPENAI_RESPONSE_ID_ATTRIBUTE]: 'chatcmpl-mock123', - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'gpt-3.5-turbo', - [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: '2023-03-01T06:31:28.000Z', - [OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: 15, - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 10, }, op: 'gen_ai.chat', origin: 'auto.ai.openai', @@ -654,11 +598,6 @@ describe('OpenAI integration (V6)', () => { [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 10, [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 15, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 25, - [OPENAI_RESPONSE_ID_ATTRIBUTE]: 'chatcmpl-mock123', - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: 'gpt-3.5-turbo', - [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: '2023-03-01T06:31:28.000Z', - [OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: 15, - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: 10, }, op: 'gen_ai.chat', origin: 'auto.ai.openai', diff --git a/dev-packages/node-integration-tests/suites/tracing/sampling-static/instrument.mjs b/dev-packages/node-integration-tests/suites/tracing/sampling-static/instrument.mjs new file mode 100644 index 000000000000..cbf0bbf2e2fc --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/sampling-static/instrument.mjs @@ -0,0 +1,15 @@ +import * as Sentry from '@sentry/node'; +import { loggingTransport } from '@sentry-internal/node-integration-tests'; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + release: '1.0', + tracesSampler: ({ inheritOrSampleWith, name }) => { + if (name === 'GET /health') { + return inheritOrSampleWith(0); + } + return inheritOrSampleWith(1); + }, + transport: loggingTransport, + clientReportFlushInterval: 1_000, +}); diff --git a/dev-packages/node-integration-tests/suites/tracing/sampling-static/server.mjs b/dev-packages/node-integration-tests/suites/tracing/sampling-static/server.mjs new file mode 100644 index 000000000000..f9c7f136aef2 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/sampling-static/server.mjs @@ -0,0 +1,20 @@ +import express from 'express'; +import cors from 'cors'; +import * as Sentry from '@sentry/node'; +import { startExpressServerAndSendPortToRunner } from '@sentry-internal/node-integration-tests'; + +const app = express(); + +app.use(cors()); + +app.get('/health', (_req, res) => { + res.send({ status: 'ok-health' }); +}); + +app.get('/ok', (_req, res) => { + res.send({ status: 'ok' }); +}); + +Sentry.setupExpressErrorHandler(app); + +startExpressServerAndSendPortToRunner(app); diff --git a/dev-packages/node-integration-tests/suites/tracing/sampling-static/test.ts b/dev-packages/node-integration-tests/suites/tracing/sampling-static/test.ts new file mode 100644 index 000000000000..8eb57ccdd54e --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/sampling-static/test.ts @@ -0,0 +1,40 @@ +import { afterAll, describe, expect } from 'vitest'; +import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../utils/runner'; + +describe('negative sampling (static)', () => { + afterAll(() => { + cleanupChildProcesses(); + }); + + createEsmAndCjsTests(__dirname, 'server.mjs', 'instrument.mjs', (createRunner, test) => { + test('records sample_rate outcome for root span/transaction', async () => { + const runner = createRunner() + .unignore('client_report') + .expect({ + transaction: { + transaction: 'GET /ok', + }, + }) + .expect({ + client_report: { + discarded_events: [ + { + category: 'transaction', + quantity: 1, + reason: 'sample_rate', + }, + ], + }, + }) + .start(); + + const res = await runner.makeRequest('get', '/health'); + expect((res as { status: string }).status).toBe('ok-health'); + + const res2 = await runner.makeRequest('get', '/ok'); // contains all spans + expect((res2 as { status: string }).status).toBe('ok'); + + await runner.completed(); + }); + }); +}); diff --git a/dev-packages/node-integration-tests/suites/tracing/sampling-streamed/instrument.mjs b/dev-packages/node-integration-tests/suites/tracing/sampling-streamed/instrument.mjs new file mode 100644 index 000000000000..713a676ede3d --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/sampling-streamed/instrument.mjs @@ -0,0 +1,16 @@ +import * as Sentry from '@sentry/node'; +import { loggingTransport } from '@sentry-internal/node-integration-tests'; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + release: '1.0', + tracesSampler: ({ inheritOrSampleWith, name }) => { + if (name === 'GET /health') { + return inheritOrSampleWith(0); + } + return inheritOrSampleWith(1); + }, + transport: loggingTransport, + traceLifecycle: 'stream', + clientReportFlushInterval: 1_000, +}); diff --git a/dev-packages/node-integration-tests/suites/tracing/sampling-streamed/server.mjs b/dev-packages/node-integration-tests/suites/tracing/sampling-streamed/server.mjs new file mode 100644 index 000000000000..f9c7f136aef2 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/sampling-streamed/server.mjs @@ -0,0 +1,20 @@ +import express from 'express'; +import cors from 'cors'; +import * as Sentry from '@sentry/node'; +import { startExpressServerAndSendPortToRunner } from '@sentry-internal/node-integration-tests'; + +const app = express(); + +app.use(cors()); + +app.get('/health', (_req, res) => { + res.send({ status: 'ok-health' }); +}); + +app.get('/ok', (_req, res) => { + res.send({ status: 'ok' }); +}); + +Sentry.setupExpressErrorHandler(app); + +startExpressServerAndSendPortToRunner(app); diff --git a/dev-packages/node-integration-tests/suites/tracing/sampling-streamed/test.ts b/dev-packages/node-integration-tests/suites/tracing/sampling-streamed/test.ts new file mode 100644 index 000000000000..d98d2f82afb0 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/sampling-streamed/test.ts @@ -0,0 +1,44 @@ +import { afterAll, describe, expect } from 'vitest'; +import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../utils/runner'; + +describe('negative sampling (streaming)', () => { + afterAll(() => { + cleanupChildProcesses(); + }); + + createEsmAndCjsTests(__dirname, 'server.mjs', 'instrument.mjs', (createRunner, test) => { + test('records sample_rate outcome for segment and child spans of negatively sampled segment', async () => { + const runner = createRunner() + .unignore('client_report') + .expect({ + client_report: { + discarded_events: [ + { + category: 'span', + quantity: 5, // 1 segment ignored + 4 child spans (implicitly ignored) + reason: 'sample_rate', + }, + ], + }, + }) + .expect({ + span: container => { + expect(container.items).toHaveLength(5); + const segmentSpan = container.items.find(s => s.name === 'GET /ok' && !!s.is_segment); + + expect(segmentSpan).toBeDefined(); + expect(container.items.every(s => s.trace_id === segmentSpan!.trace_id)).toBe(true); + }, + }) + .start(); + + const res = await runner.makeRequest('get', '/health'); + expect((res as { status: string }).status).toBe('ok-health'); + + const res2 = await runner.makeRequest('get', '/ok'); // contains all spans + expect((res2 as { status: string }).status).toBe('ok'); + + await runner.completed(); + }); + }); +}); diff --git a/dev-packages/node-integration-tests/suites/tracing/vercelai/test-generate-object.ts b/dev-packages/node-integration-tests/suites/tracing/vercelai/test-generate-object.ts index 3156a19bb806..39e13d5425c2 100644 --- a/dev-packages/node-integration-tests/suites/tracing/vercelai/test-generate-object.ts +++ b/dev-packages/node-integration-tests/suites/tracing/vercelai/test-generate-object.ts @@ -37,7 +37,7 @@ describe('Vercel AI integration - generateObject', () => { expect.objectContaining({ data: expect.objectContaining({ 'sentry.origin': 'auto.vercelai.otel', - 'sentry.op': 'gen_ai.generate_object', + 'sentry.op': 'gen_ai.generate_content', 'gen_ai.operation.name': 'generate_content', 'vercel.ai.operationId': 'ai.generateObject.doGenerate', 'vercel.ai.model.provider': 'mock-provider', @@ -52,7 +52,7 @@ describe('Vercel AI integration - generateObject', () => { 'gen_ai.usage.total_tokens': 40, }), description: 'generate_content mock-model-id', - op: 'gen_ai.generate_object', + op: 'gen_ai.generate_content', origin: 'auto.vercelai.otel', status: 'ok', }), diff --git a/dev-packages/node-integration-tests/suites/tracing/vercelai/test.ts b/dev-packages/node-integration-tests/suites/tracing/vercelai/test.ts index 6b0b0a45fcf8..673887737ee6 100644 --- a/dev-packages/node-integration-tests/suites/tracing/vercelai/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/vercelai/test.ts @@ -70,7 +70,7 @@ describe('Vercel AI integration', () => { [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 20, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 30, [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', - [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_text', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_content', [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.vercelai.otel', 'vercel.ai.model.provider': 'mock-provider', 'vercel.ai.operationId': 'ai.generateText.doGenerate', @@ -83,7 +83,7 @@ describe('Vercel AI integration', () => { 'vercel.ai.streaming': false, }, description: 'generate_content mock-model-id', - op: 'gen_ai.generate_text', + op: 'gen_ai.generate_content', origin: 'auto.vercelai.otel', status: 'ok', }), @@ -132,7 +132,7 @@ describe('Vercel AI integration', () => { [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 20, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 30, [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', - [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_text', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_content', [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.vercelai.otel', 'vercel.ai.model.provider': 'mock-provider', 'vercel.ai.operationId': 'ai.generateText.doGenerate', @@ -146,7 +146,7 @@ describe('Vercel AI integration', () => { 'vercel.ai.streaming': false, }, description: 'generate_content mock-model-id', - op: 'gen_ai.generate_text', + op: 'gen_ai.generate_content', origin: 'auto.vercelai.otel', status: 'ok', }), @@ -186,7 +186,7 @@ describe('Vercel AI integration', () => { [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 25, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 40, [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', - [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_text', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_content', [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.vercelai.otel', 'vercel.ai.model.provider': 'mock-provider', 'vercel.ai.operationId': 'ai.generateText.doGenerate', @@ -199,7 +199,7 @@ describe('Vercel AI integration', () => { 'vercel.ai.streaming': false, }, description: 'generate_content mock-model-id', - op: 'gen_ai.generate_text', + op: 'gen_ai.generate_content', origin: 'auto.vercelai.otel', status: 'ok', }), @@ -280,7 +280,7 @@ describe('Vercel AI integration', () => { [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 20, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 30, [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', - [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_text', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_content', [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.vercelai.otel', 'vercel.ai.model.provider': 'mock-provider', 'vercel.ai.operationId': 'ai.generateText.doGenerate', @@ -294,7 +294,7 @@ describe('Vercel AI integration', () => { 'vercel.ai.streaming': false, }, description: 'generate_content mock-model-id', - op: 'gen_ai.generate_text', + op: 'gen_ai.generate_content', origin: 'auto.vercelai.otel', status: 'ok', parent_span_id: expect.any(String), @@ -353,7 +353,7 @@ describe('Vercel AI integration', () => { [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 20, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 30, [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', - [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_text', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_content', [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.vercelai.otel', 'vercel.ai.model.provider': 'mock-provider', 'vercel.ai.operationId': 'ai.generateText.doGenerate', @@ -367,7 +367,7 @@ describe('Vercel AI integration', () => { 'vercel.ai.streaming': false, }, description: 'generate_content mock-model-id', - op: 'gen_ai.generate_text', + op: 'gen_ai.generate_content', origin: 'auto.vercelai.otel', status: 'ok', parent_span_id: expect.any(String), @@ -427,7 +427,7 @@ describe('Vercel AI integration', () => { [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 25, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 40, [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', - [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_text', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_content', [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.vercelai.otel', 'vercel.ai.model.provider': 'mock-provider', 'vercel.ai.operationId': 'ai.generateText.doGenerate', @@ -442,7 +442,7 @@ describe('Vercel AI integration', () => { 'vercel.ai.streaming': false, }, description: 'generate_content mock-model-id', - op: 'gen_ai.generate_text', + op: 'gen_ai.generate_content', origin: 'auto.vercelai.otel', status: 'ok', parent_span_id: expect.any(String), @@ -528,7 +528,7 @@ describe('Vercel AI integration', () => { [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 25, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 40, [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', - [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_text', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_content', [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.vercelai.otel', 'vercel.ai.model.provider': 'mock-provider', 'vercel.ai.operationId': 'ai.generateText.doGenerate', @@ -541,7 +541,7 @@ describe('Vercel AI integration', () => { 'vercel.ai.streaming': false, }, description: 'generate_content mock-model-id', - op: 'gen_ai.generate_text', + op: 'gen_ai.generate_content', origin: 'auto.vercelai.otel', status: 'ok', }), @@ -648,7 +648,7 @@ describe('Vercel AI integration', () => { [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 25, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 40, [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', - [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_text', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_content', [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.vercelai.otel', 'vercel.ai.model.provider': 'mock-provider', 'vercel.ai.operationId': 'ai.generateText.doGenerate', @@ -661,7 +661,7 @@ describe('Vercel AI integration', () => { 'vercel.ai.streaming': false, }, description: 'generate_content mock-model-id', - op: 'gen_ai.generate_text', + op: 'gen_ai.generate_content', origin: 'auto.vercelai.otel', status: 'ok', }), @@ -757,11 +757,11 @@ describe('Vercel AI integration', () => { // The doGenerate span - name stays as 'generateText.doGenerate' since model ID is missing expect.objectContaining({ description: 'generateText.doGenerate', - op: 'gen_ai.generate_text', + op: 'gen_ai.generate_content', origin: 'auto.vercelai.otel', status: 'ok', data: expect.objectContaining({ - [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_text', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_content', [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.vercelai.otel', [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', }), @@ -938,7 +938,7 @@ describe('Vercel AI integration', () => { }), }), expect.objectContaining({ - op: 'gen_ai.generate_text', + op: 'gen_ai.generate_content', data: expect.objectContaining({ 'gen_ai.conversation.id': 'conv-a', }), diff --git a/dev-packages/node-integration-tests/suites/tracing/vercelai/v5/test.ts b/dev-packages/node-integration-tests/suites/tracing/vercelai/v5/test.ts index a84b80e9abc5..e59a5545d7cf 100644 --- a/dev-packages/node-integration-tests/suites/tracing/vercelai/v5/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/vercelai/v5/test.ts @@ -59,7 +59,7 @@ describe('Vercel AI integration (V5)', () => { expect.objectContaining({ data: { [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.vercelai.otel', - [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_text', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_content', [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', 'vercel.ai.operationId': 'ai.generateText.doGenerate', 'vercel.ai.model.provider': 'mock-provider', @@ -80,7 +80,7 @@ describe('Vercel AI integration (V5)', () => { [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 30, }, description: 'generate_content mock-model-id', - op: 'gen_ai.generate_text', + op: 'gen_ai.generate_content', origin: 'auto.vercelai.otel', status: 'ok', }), @@ -116,7 +116,7 @@ describe('Vercel AI integration (V5)', () => { expect.objectContaining({ data: { [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.vercelai.otel', - [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_text', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_content', [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', 'vercel.ai.operationId': 'ai.generateText.doGenerate', 'vercel.ai.model.provider': 'mock-provider', @@ -141,7 +141,7 @@ describe('Vercel AI integration (V5)', () => { [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 30, }, description: 'generate_content mock-model-id', - op: 'gen_ai.generate_text', + op: 'gen_ai.generate_content', origin: 'auto.vercelai.otel', status: 'ok', }), @@ -189,11 +189,11 @@ describe('Vercel AI integration (V5)', () => { [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 25, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 40, [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', - [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_text', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_content', [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.vercelai.otel', }, description: 'generate_content mock-model-id', - op: 'gen_ai.generate_text', + op: 'gen_ai.generate_content', origin: 'auto.vercelai.otel', status: 'ok', }), @@ -277,11 +277,11 @@ describe('Vercel AI integration (V5)', () => { [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 20, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 30, [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', - [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_text', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_content', [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.vercelai.otel', }, description: 'generate_content mock-model-id', - op: 'gen_ai.generate_text', + op: 'gen_ai.generate_content', origin: 'auto.vercelai.otel', status: 'ok', }), @@ -317,7 +317,7 @@ describe('Vercel AI integration (V5)', () => { expect.objectContaining({ data: { [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.vercelai.otel', - [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_text', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_content', [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', 'vercel.ai.operationId': 'ai.generateText.doGenerate', 'vercel.ai.model.provider': 'mock-provider', @@ -342,7 +342,7 @@ describe('Vercel AI integration (V5)', () => { [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 30, }, description: 'generate_content mock-model-id', - op: 'gen_ai.generate_text', + op: 'gen_ai.generate_content', origin: 'auto.vercelai.otel', status: 'ok', }), @@ -401,11 +401,11 @@ describe('Vercel AI integration (V5)', () => { [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 25, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 40, [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', - [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_text', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_content', [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.vercelai.otel', }), description: 'generate_content mock-model-id', - op: 'gen_ai.generate_text', + op: 'gen_ai.generate_content', origin: 'auto.vercelai.otel', status: 'ok', }), @@ -513,11 +513,11 @@ describe('Vercel AI integration (V5)', () => { [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 25, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 40, [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', - [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_text', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_content', [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.vercelai.otel', }, description: 'generate_content mock-model-id', - op: 'gen_ai.generate_text', + op: 'gen_ai.generate_content', origin: 'auto.vercelai.otel', status: 'ok', }), diff --git a/dev-packages/node-integration-tests/suites/tracing/vercelai/v6/scenario-tool-loop-agent.mjs b/dev-packages/node-integration-tests/suites/tracing/vercelai/v6/scenario-tool-loop-agent.mjs new file mode 100644 index 000000000000..fe485ce29a90 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/vercelai/v6/scenario-tool-loop-agent.mjs @@ -0,0 +1,61 @@ +import * as Sentry from '@sentry/node'; +import { ToolLoopAgent, stepCountIs, tool } from 'ai'; +import { MockLanguageModelV3 } from 'ai/test'; +import { z } from 'zod'; + +async function run() { + await Sentry.startSpan({ op: 'function', name: 'main' }, async () => { + let callCount = 0; + + const agent = new ToolLoopAgent({ + experimental_telemetry: { isEnabled: true }, + model: new MockLanguageModelV3({ + doGenerate: async () => { + if (callCount++ === 0) { + return { + finishReason: { unified: 'tool-calls', raw: 'tool_calls' }, + usage: { + inputTokens: { total: 10, noCache: 10, cached: 0 }, + outputTokens: { total: 20, noCache: 20, cached: 0 }, + totalTokens: { total: 30, noCache: 30, cached: 0 }, + }, + content: [ + { + type: 'tool-call', + toolCallId: 'call-1', + toolName: 'getWeather', + input: JSON.stringify({ location: 'San Francisco' }), + }, + ], + warnings: [], + }; + } + return { + finishReason: { unified: 'stop', raw: 'stop' }, + usage: { + inputTokens: { total: 15, noCache: 15, cached: 0 }, + outputTokens: { total: 25, noCache: 25, cached: 0 }, + totalTokens: { total: 40, noCache: 40, cached: 0 }, + }, + content: [{ type: 'text', text: 'The weather in San Francisco is sunny, 72°F.' }], + warnings: [], + }; + }, + }), + tools: { + getWeather: tool({ + description: 'Get the current weather for a location', + inputSchema: z.object({ location: z.string() }), + execute: async ({ location }) => `Weather in ${location}: Sunny, 72°F`, + }), + }, + stopWhen: stepCountIs(3), + }); + + await agent.generate({ + prompt: 'What is the weather in San Francisco?', + }); + }); +} + +run(); diff --git a/dev-packages/node-integration-tests/suites/tracing/vercelai/v6/test.ts b/dev-packages/node-integration-tests/suites/tracing/vercelai/v6/test.ts index 39ee00254373..2c07366423cf 100644 --- a/dev-packages/node-integration-tests/suites/tracing/vercelai/v6/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/vercelai/v6/test.ts @@ -59,7 +59,7 @@ describe('Vercel AI integration (V6)', () => { expect.objectContaining({ data: expect.objectContaining({ [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.vercelai.otel', - [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_text', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_content', [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', 'vercel.ai.operationId': 'ai.generateText.doGenerate', 'vercel.ai.model.provider': 'mock-provider', @@ -81,7 +81,7 @@ describe('Vercel AI integration (V6)', () => { [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 30, }), description: 'generate_content mock-model-id', - op: 'gen_ai.generate_text', + op: 'gen_ai.generate_content', origin: 'auto.vercelai.otel', status: 'ok', }), @@ -117,7 +117,7 @@ describe('Vercel AI integration (V6)', () => { expect.objectContaining({ data: expect.objectContaining({ [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.vercelai.otel', - [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_text', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_content', [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', 'vercel.ai.operationId': 'ai.generateText.doGenerate', 'vercel.ai.model.provider': 'mock-provider', @@ -142,7 +142,7 @@ describe('Vercel AI integration (V6)', () => { [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 30, }), description: 'generate_content mock-model-id', - op: 'gen_ai.generate_text', + op: 'gen_ai.generate_content', origin: 'auto.vercelai.otel', status: 'ok', }), @@ -192,11 +192,11 @@ describe('Vercel AI integration (V6)', () => { [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 25, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 40, [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', - [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_text', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_content', [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.vercelai.otel', }), description: 'generate_content mock-model-id', - op: 'gen_ai.generate_text', + op: 'gen_ai.generate_content', origin: 'auto.vercelai.otel', status: 'ok', }), @@ -280,11 +280,11 @@ describe('Vercel AI integration (V6)', () => { [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 20, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 30, [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', - [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_text', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_content', [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.vercelai.otel', }), description: 'generate_content mock-model-id', - op: 'gen_ai.generate_text', + op: 'gen_ai.generate_content', origin: 'auto.vercelai.otel', status: 'ok', }), @@ -320,7 +320,7 @@ describe('Vercel AI integration (V6)', () => { expect.objectContaining({ data: expect.objectContaining({ [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.vercelai.otel', - [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_text', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_content', [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', 'vercel.ai.operationId': 'ai.generateText.doGenerate', 'vercel.ai.model.provider': 'mock-provider', @@ -345,7 +345,7 @@ describe('Vercel AI integration (V6)', () => { [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 30, }), description: 'generate_content mock-model-id', - op: 'gen_ai.generate_text', + op: 'gen_ai.generate_content', origin: 'auto.vercelai.otel', status: 'ok', }), @@ -404,11 +404,11 @@ describe('Vercel AI integration (V6)', () => { [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 25, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 40, [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', - [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_text', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_content', [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.vercelai.otel', }), description: 'generate_content mock-model-id', - op: 'gen_ai.generate_text', + op: 'gen_ai.generate_content', origin: 'auto.vercelai.otel', status: 'ok', }), @@ -518,11 +518,11 @@ describe('Vercel AI integration (V6)', () => { [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 25, [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: 40, [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', - [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_text', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_content', [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.vercelai.otel', }), description: 'generate_content mock-model-id', - op: 'gen_ai.generate_text', + op: 'gen_ai.generate_content', origin: 'auto.vercelai.otel', status: 'ok', }), @@ -601,4 +601,81 @@ describe('Vercel AI integration (V6)', () => { }, }, ); + + createEsmAndCjsTests( + __dirname, + 'scenario-tool-loop-agent.mjs', + 'instrument.mjs', + (createRunner, test) => { + test('creates spans for ToolLoopAgent with tool calls', async () => { + const expectedTransaction = { + transaction: 'main', + spans: expect.arrayContaining([ + // ToolLoopAgent outer span + expect.objectContaining({ + data: expect.objectContaining({ + [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'invoke_agent', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.invoke_agent', + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.vercelai.otel', + [GEN_AI_REQUEST_MODEL_ATTRIBUTE]: 'mock-model-id', + }), + op: 'gen_ai.invoke_agent', + origin: 'auto.vercelai.otel', + status: 'ok', + }), + // First doGenerate span (returns tool-calls) + expect.objectContaining({ + data: expect.objectContaining({ + [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_content', + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.vercelai.otel', + [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 10, + [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 20, + [GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE]: ['tool-calls'], + }), + op: 'gen_ai.generate_content', + origin: 'auto.vercelai.otel', + status: 'ok', + }), + // Tool execution span + expect.objectContaining({ + data: expect.objectContaining({ + [GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: 'call-1', + [GEN_AI_TOOL_NAME_ATTRIBUTE]: 'getWeather', + [GEN_AI_TOOL_TYPE_ATTRIBUTE]: 'function', + [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'execute_tool', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.execute_tool', + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.vercelai.otel', + }), + description: 'execute_tool getWeather', + op: 'gen_ai.execute_tool', + origin: 'auto.vercelai.otel', + status: 'ok', + }), + // Second doGenerate span (returns final text) + expect.objectContaining({ + data: expect.objectContaining({ + [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'generate_content', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.generate_content', + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.vercelai.otel', + [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: 15, + [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: 25, + [GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE]: ['stop'], + }), + op: 'gen_ai.generate_content', + origin: 'auto.vercelai.otel', + status: 'ok', + }), + ]), + }; + + await createRunner().expect({ transaction: expectedTransaction }).start().completed(); + }); + }, + { + additionalDependencies: { + ai: '^6.0.0', + }, + }, + ); }); diff --git a/dev-packages/node-integration-tests/utils/assertions.ts b/dev-packages/node-integration-tests/utils/assertions.ts index 8d9fb5f2251f..b6c45ebc043c 100644 --- a/dev-packages/node-integration-tests/utils/assertions.ts +++ b/dev-packages/node-integration-tests/utils/assertions.ts @@ -6,12 +6,19 @@ import type { SerializedLogContainer, SerializedMetricContainer, SerializedSession, + SerializedStreamedSpanContainer, SessionAggregates, TransactionEvent, } from '@sentry/core'; import { SDK_VERSION } from '@sentry/core'; import { expect } from 'vitest'; +export type DeepPartial = T extends object + ? { + [P in keyof T]?: DeepPartial; + } + : T; + /** * Asserts against a Sentry Event ignoring non-deterministic properties * @@ -86,6 +93,16 @@ export function assertSentryMetricContainer( }); } +export function assertSentrySpanContainer( + actual: SerializedStreamedSpanContainer, + expected: DeepPartial, +): void { + expect(actual).toMatchObject({ + items: expect.any(Array), + ...expected, + }); +} + export function assertEnvelopeHeader(actual: Envelope[0], expected: Partial): void { expect(actual).toEqual({ event_id: expect.any(String), @@ -97,3 +114,14 @@ export function assertEnvelopeHeader(actual: Envelope[0], expected: Partial): void { + expect(actual).toEqual({ + sent_at: expect.any(String), + sdk: { + name: 'sentry.javascript.node', + version: SDK_VERSION, + }, + ...expected, + }); +} diff --git a/dev-packages/node-integration-tests/utils/runner.ts b/dev-packages/node-integration-tests/utils/runner.ts index ee2fae0bc06b..7690fa40ee8b 100644 --- a/dev-packages/node-integration-tests/utils/runner.ts +++ b/dev-packages/node-integration-tests/utils/runner.ts @@ -9,6 +9,7 @@ import type { SerializedLogContainer, SerializedMetricContainer, SerializedSession, + SerializedStreamedSpanContainer, SessionAggregates, TransactionEvent, } from '@sentry/core'; @@ -20,6 +21,7 @@ import { cp, mkdir, readFile, rm, writeFile } from 'fs/promises'; import { basename, join } from 'path'; import { inspect, promisify } from 'util'; import { afterAll, beforeAll, describe, test } from 'vitest'; +import type { DeepPartial } from './assertions'; import { assertEnvelopeHeader, assertSentryCheckIn, @@ -29,7 +31,9 @@ import { assertSentryMetricContainer, assertSentrySession, assertSentrySessions, + assertSentrySpanContainer, assertSentryTransaction, + assertSpanEnvelopeHeader, } from './assertions'; const execPromise = promisify(exec); @@ -135,6 +139,9 @@ type ExpectedCheckIn = Partial | ((event: SerializedCheckIn) type ExpectedClientReport = Partial | ((event: ClientReport) => void); type ExpectedLogContainer = Partial | ((event: SerializedLogContainer) => void); type ExpectedMetricContainer = Partial | ((event: SerializedMetricContainer) => void); +type ExpectedSpanContainer = + | DeepPartial + | ((container: SerializedStreamedSpanContainer) => void); type Expected = | { @@ -160,6 +167,9 @@ type Expected = } | { trace_metric: ExpectedMetricContainer; + } + | { + span: ExpectedSpanContainer; }; type ExpectedEnvelopeHeader = @@ -167,7 +177,8 @@ type ExpectedEnvelopeHeader = | { transaction: Partial } | { session: Partial } | { sessions: Partial } - | { log: Partial }; + | { log: Partial } + | { span: Partial }; type StartResult = { completed(): Promise; @@ -479,7 +490,11 @@ export function createRunner(...paths: string[]) { return; } - assertEnvelopeHeader(header, expected); + if (envelopeItemType === 'span') { + assertSpanEnvelopeHeader(header, expected); + } else { + assertEnvelopeHeader(header, expected); + } expectCallbackCalled(); } catch (e) { @@ -531,6 +546,9 @@ export function createRunner(...paths: string[]) { } else if ('trace_metric' in expected) { expectMetric(item[1] as SerializedMetricContainer, expected.trace_metric); expectCallbackCalled(); + } else if ('span' in expected) { + expectSpanContainer(item[1] as SerializedStreamedSpanContainer, expected.span); + expectCallbackCalled(); } else { throw new Error( `Unhandled expected envelope item type: ${JSON.stringify(expected)}\nItem: ${JSON.stringify(item)}`, @@ -797,6 +815,14 @@ function expectMetric(item: SerializedMetricContainer, expected: ExpectedMetricC } } +function expectSpanContainer(item: SerializedStreamedSpanContainer, expected: ExpectedSpanContainer): void { + if (typeof expected === 'function') { + expected(item); + } else { + assertSentrySpanContainer(item, expected); + } +} + /** * Converts ESM import statements to CommonJS require statements * @param content The content of an ESM file diff --git a/docs/creating-a-new-sdk.md b/docs/creating-a-new-sdk.md index 986450b92b06..c3acd9c56bff 100644 --- a/docs/creating-a-new-sdk.md +++ b/docs/creating-a-new-sdk.md @@ -21,6 +21,17 @@ As a rule of thumb, we should follow these two ideas: 2. Instrumentation should follow common patterns for a specific platform. No config is always preferred, but if config is unavoidable, it should feel as native as possible to users of the given framework. +### Boilerplate Files + +Make sure all the boilerplate for your package is set up correctly. This can include, depending on the package: + +- `tsconfig.json`, `tsconfig.test.json`, `tsconfig.types.json`, `test/tsconfig.json` +- `oxlintsc.json` +- `rollup.*.config.mjs` +- `LICENSE` +- `README.md` +- `vite.config.ts` + ## 1. Browser SDKs A purely browser SDK generally should cover the following things: diff --git a/package.json b/package.json index ccb2f051319a..d05b71e7fdbc 100644 --- a/package.json +++ b/package.json @@ -25,8 +25,8 @@ "format:check": "oxfmt . --check", "verify": "run-s format:check lint", "fix": "run-s format lint:fix", - "lint": "OXLINT_TSGOLINT_DANGEROUSLY_SUPPRESS_PROGRAM_DIAGNOSTICS=true oxlint . --type-aware", - "lint:fix": "OXLINT_TSGOLINT_DANGEROUSLY_SUPPRESS_PROGRAM_DIAGNOSTICS=true oxlint . --fix --type-aware", + "lint": "OXLINT_TSGOLINT_DANGEROUSLY_SUPPRESS_PROGRAM_DIAGNOSTICS=true oxlint .", + "lint:fix": "OXLINT_TSGOLINT_DANGEROUSLY_SUPPRESS_PROGRAM_DIAGNOSTICS=true oxlint . --fix", "lint:es-compatibility": "nx run-many -t lint:es-compatibility", "dedupe-deps:check": "yarn-deduplicate yarn.lock --list --fail", "dedupe-deps:fix": "yarn-deduplicate yarn.lock", diff --git a/packages/angular/.oxlintrc.json b/packages/angular/.oxlintrc.json index f87f394ed3b6..e068a79fa654 100644 --- a/packages/angular/.oxlintrc.json +++ b/packages/angular/.oxlintrc.json @@ -1,6 +1,12 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], + "jsPlugins": [ + { + "name": "sdk", + "specifier": "@sentry-internal/eslint-plugin-sdk" + } + ], "env": { "browser": true }, diff --git a/packages/astro/.oxlintrc.json b/packages/astro/.oxlintrc.json index 28d9e2d390f2..9623aa8dfd5a 100644 --- a/packages/astro/.oxlintrc.json +++ b/packages/astro/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], "env": { "browser": true, "node": true diff --git a/packages/astro/package.json b/packages/astro/package.json index dea803d6e9df..1dc54c957ab1 100644 --- a/packages/astro/package.json +++ b/packages/astro/package.json @@ -59,7 +59,7 @@ "@sentry/browser": "10.47.0", "@sentry/core": "10.47.0", "@sentry/node": "10.47.0", - "@sentry/vite-plugin": "^5.1.0" + "@sentry/vite-plugin": "^5.2.0" }, "devDependencies": { "astro": "^3.5.0", diff --git a/packages/astro/src/index.server.ts b/packages/astro/src/index.server.ts index f19f82391a5f..b4fc6fccbee3 100644 --- a/packages/astro/src/index.server.ts +++ b/packages/astro/src/index.server.ts @@ -154,6 +154,7 @@ export { instrumentOpenAiClient, instrumentAnthropicAiClient, instrumentGoogleGenAIClient, + instrumentLangChainEmbeddings, instrumentLangGraph, instrumentStateGraphCompile, zodErrorsIntegration, @@ -172,6 +173,8 @@ export { statsigIntegration, unleashIntegration, growthbookIntegration, + spanStreamingIntegration, + withStreamedSpan, metrics, } from '@sentry/node'; diff --git a/packages/astro/src/index.types.ts b/packages/astro/src/index.types.ts index 2e51ab1b0f1e..0c8a5cca7bb6 100644 --- a/packages/astro/src/index.types.ts +++ b/packages/astro/src/index.types.ts @@ -20,6 +20,8 @@ export declare function init(options: Options | clientSdk.BrowserOptions | NodeO export declare const linkedErrorsIntegration: typeof clientSdk.linkedErrorsIntegration; export declare const contextLinesIntegration: typeof clientSdk.contextLinesIntegration; +export declare const spanStreamingIntegration: typeof clientSdk.spanStreamingIntegration; +export declare const withStreamedSpan: typeof clientSdk.withStreamedSpan; export declare const getDefaultIntegrations: (options: Options) => Integration[]; export declare const defaultStackParser: StackParser; diff --git a/packages/aws-serverless/.oxlintrc.json b/packages/aws-serverless/.oxlintrc.json index 8ca250cb7e99..f079a7bc588c 100644 --- a/packages/aws-serverless/.oxlintrc.json +++ b/packages/aws-serverless/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], "env": { "node": true } diff --git a/packages/aws-serverless/README.md b/packages/aws-serverless/README.md index 81372f2178d2..bf25bb74f177 100644 --- a/packages/aws-serverless/README.md +++ b/packages/aws-serverless/README.md @@ -73,6 +73,50 @@ export const handler = (event, context, callback) => { }; ``` +## Container Image-based Lambda Functions + +When using container image-based Lambda functions (e.g., with [Lambda Web Adapter](https://github.com/awslabs/aws-lambda-web-adapter) for frameworks like SvelteKit, Next.js, or Remix), Lambda layers cannot be attached. Instead, you can install the Sentry Lambda extension directly into your Docker image. The extension tunnels Sentry events through a local proxy, improving event delivery reliability during Lambda freezes. + +### Setup + +1. Install `@sentry/aws-serverless` as a dependency — even if you use a different Sentry SDK in your application (e.g., `@sentry/sveltekit`), this package contains the extension files needed for the Docker image. + +2. Copy the extension files from the npm package into your Docker image: + +```dockerfile +FROM public.ecr.aws/lambda/nodejs:22 + +# Copy the Sentry Lambda extension +RUN mkdir -p /opt/sentry-extension +COPY node_modules/@sentry/aws-serverless/build/lambda-extension/sentry-extension /opt/extensions/sentry-extension +COPY node_modules/@sentry/aws-serverless/build/lambda-extension/index.mjs /opt/sentry-extension/index.mjs +RUN chmod +x /opt/extensions/sentry-extension /opt/sentry-extension/index.mjs + +# ... rest of your Dockerfile +``` + +3. Point your Sentry SDK at the extension using the `tunnel` option. The extension always listens on `http://localhost:9000/envelope` — this URL is fixed and must be used exactly as shown: + +```js +import * as Sentry from '@sentry/aws-serverless'; + +Sentry.init({ + dsn: '__DSN__', + tunnel: 'http://localhost:9000/envelope', +}); +``` + +This works with any Sentry SDK: + +```js +import * as Sentry from '@sentry/sveltekit'; + +Sentry.init({ + dsn: '__DSN__', + tunnel: 'http://localhost:9000/envelope', +}); +``` + ## Integrate Sentry using the Sentry Lambda layer Another much simpler way to integrate Sentry to your AWS Lambda function is to add the official layer. diff --git a/packages/aws-serverless/package.json b/packages/aws-serverless/package.json index 961b3258e88c..123453c72ee3 100644 --- a/packages/aws-serverless/package.json +++ b/packages/aws-serverless/package.json @@ -12,7 +12,8 @@ "files": [ "/build/npm", "/build/import-hook.mjs", - "/build/loader-hook.mjs" + "/build/loader-hook.mjs", + "/build/lambda-extension" ], "main": "build/npm/cjs/index.js", "module": "build/npm/esm/index.js", @@ -79,8 +80,9 @@ "@vercel/nft": "^1.3.0" }, "scripts": { - "build": "run-p build:transpile build:types && run-s build:layer", - "build:layer": "rimraf build/aws && rollup -c rollup.lambda-extension.config.mjs && yarn ts-node scripts/buildLambdaLayer.ts", + "build": "run-p build:transpile build:types build:extension && run-s build:layer", + "build:extension": "rollup -c rollup.lambda-extension.config.mjs && yarn ts-node scripts/buildLambdaExtension.ts", + "build:layer": "rimraf build/aws && yarn ts-node scripts/buildLambdaLayer.ts", "build:dev": "run-p build:transpile build:types", "build:transpile": "rollup -c rollup.npm.config.mjs", "build:types": "run-s build:types:core build:types:downlevel", @@ -118,13 +120,26 @@ "{projectRoot}/build/npm/cjs" ] }, + "build:extension": { + "inputs": [ + "production", + "^production" + ], + "dependsOn": [ + "^build:transpile" + ], + "outputs": [ + "{projectRoot}/build/lambda-extension" + ] + }, "build:layer": { "inputs": [ "production", "^production" ], "dependsOn": [ - "build:transpile" + "build:transpile", + "build:extension" ], "outputs": [ "{projectRoot}/build/aws" diff --git a/packages/aws-serverless/rollup.lambda-extension.config.mjs b/packages/aws-serverless/rollup.lambda-extension.config.mjs index cf7f369d9175..8a63778be7af 100644 --- a/packages/aws-serverless/rollup.lambda-extension.config.mjs +++ b/packages/aws-serverless/rollup.lambda-extension.config.mjs @@ -7,7 +7,7 @@ export default [ outputFileBase: 'index.mjs', packageSpecificConfig: { output: { - dir: 'build/aws/dist-serverless/sentry-extension', + dir: 'build/lambda-extension', sourcemap: false, }, }, diff --git a/packages/aws-serverless/scripts/buildLambdaExtension.ts b/packages/aws-serverless/scripts/buildLambdaExtension.ts new file mode 100644 index 000000000000..508d7934e725 --- /dev/null +++ b/packages/aws-serverless/scripts/buildLambdaExtension.ts @@ -0,0 +1,16 @@ +import * as fs from 'fs'; + +// Copy the bash wrapper script into the rollup output directory +// so the npm package ships both the compiled extension and the wrapper. +const targetDir = './build/lambda-extension'; +const source = './src/lambda-extension/sentry-extension'; +const target = `${targetDir}/sentry-extension`; + +fs.mkdirSync(targetDir, { recursive: true }); + +fs.copyFileSync(source, target); + +// The wrapper must be executable because AWS Lambda discovers extensions by +// scanning /opt/extensions/ for executable files. If the file isn't executable, +// Lambda won't register it as an extension. +fs.chmodSync(target, 0o755); diff --git a/packages/aws-serverless/scripts/buildLambdaLayer.ts b/packages/aws-serverless/scripts/buildLambdaLayer.ts index cae52eb44eeb..cca3b739bf6b 100644 --- a/packages/aws-serverless/scripts/buildLambdaLayer.ts +++ b/packages/aws-serverless/scripts/buildLambdaLayer.ts @@ -54,10 +54,18 @@ async function buildLambdaLayer(): Promise { replaceSDKSource(); + // Copy the Lambda extension from the shared build output into the layer structure. + // build/lambda-extension/ contains both index.mjs and the sentry-extension wrapper. + // Lambda requires the wrapper to be in /opt/extensions/ for auto-discovery, + // so it gets copied there separately. + fs.cpSync('./build/lambda-extension', './build/aws/dist-serverless/sentry-extension', { recursive: true }); + fs.chmodSync('./build/aws/dist-serverless/sentry-extension/index.mjs', 0o755); fsForceMkdirSync('./build/aws/dist-serverless/extensions'); - fs.copyFileSync('./src/lambda-extension/sentry-extension', './build/aws/dist-serverless/extensions/sentry-extension'); + fs.copyFileSync( + './build/aws/dist-serverless/sentry-extension/sentry-extension', + './build/aws/dist-serverless/extensions/sentry-extension', + ); fs.chmodSync('./build/aws/dist-serverless/extensions/sentry-extension', 0o755); - fs.chmodSync('./build/aws/dist-serverless/sentry-extension/index.mjs', 0o755); const zipFilename = `sentry-node-serverless-${version}.zip`; // Only include these directories in the zip file diff --git a/packages/aws-serverless/src/index.ts b/packages/aws-serverless/src/index.ts index 00b14ed59235..0cbc893b4601 100644 --- a/packages/aws-serverless/src/index.ts +++ b/packages/aws-serverless/src/index.ts @@ -44,6 +44,7 @@ export { getSentryRelease, createGetModuleFromFilename, createLangChainCallbackHandler, + instrumentLangChainEmbeddings, httpHeadersToSpanAttributes, winterCGHeadersToDict, // eslint-disable-next-line deprecation/deprecation @@ -159,6 +160,8 @@ export { unleashIntegration, growthbookIntegration, metrics, + spanStreamingIntegration, + withStreamedSpan, } from '@sentry/node'; export { diff --git a/packages/aws-serverless/src/integration/instrumentation-aws-lambda/instrumentation.ts b/packages/aws-serverless/src/integration/instrumentation-aws-lambda/instrumentation.ts index a3809408cfe6..c564a8dc583a 100644 --- a/packages/aws-serverless/src/integration/instrumentation-aws-lambda/instrumentation.ts +++ b/packages/aws-serverless/src/integration/instrumentation-aws-lambda/instrumentation.ts @@ -504,7 +504,18 @@ export class AwsLambdaInstrumentation extends InstrumentationBase; + const timeoutPromise = new Promise(resolve => { + timeoutId = setTimeout(resolve, FORCE_FLUSH_TIMEOUT_MS); + timeoutId.unref(); + }); + Promise.race([Promise.all(flushers), timeoutPromise]) + .catch(() => {}) + .finally(() => { + clearTimeout(timeoutId); + callback(); + }); } /** diff --git a/packages/aws-serverless/test/instrumentation.test.ts b/packages/aws-serverless/test/instrumentation.test.ts new file mode 100644 index 000000000000..db4dcbf66ccf --- /dev/null +++ b/packages/aws-serverless/test/instrumentation.test.ts @@ -0,0 +1,99 @@ +import { SpanStatusCode } from '@opentelemetry/api'; +import { afterEach, describe, expect, test, vi } from 'vitest'; +import { AwsLambdaInstrumentation } from '../src/integration/instrumentation-aws-lambda/instrumentation'; + +function createMockTracerProvider(forceFlushImpl: () => Promise) { + return { + getTracer: () => ({ + startSpan: vi.fn(), + startActiveSpan: vi.fn(), + }), + forceFlush: forceFlushImpl, + }; +} + +describe('AwsLambdaInstrumentation', () => { + describe('_endSpan', () => { + afterEach(() => { + vi.useRealTimers(); + }); + + test('callback fires even when tracerProvider.forceFlush() never resolves', async () => { + vi.useFakeTimers(); + + const instrumentation = new AwsLambdaInstrumentation(); + + const hangingProvider = createMockTracerProvider(() => new Promise(() => {})); + instrumentation.setTracerProvider(hangingProvider as any); + + const mockSpan = { + end: vi.fn(), + recordException: vi.fn(), + setStatus: vi.fn(), + }; + + const callback = vi.fn(); + + (instrumentation as any)._endSpan(mockSpan, undefined, callback); + + // Advance past any reasonable timeout (e.g. 5s) — the callback should fire + // within a bounded time even if forceFlush() hangs forever. + await vi.advanceTimersByTimeAsync(5_000); + + expect(mockSpan.end).toHaveBeenCalled(); + expect(callback).toHaveBeenCalledTimes(1); + + vi.useRealTimers(); + }); + + test('callback fires promptly when tracerProvider.forceFlush() resolves', async () => { + const instrumentation = new AwsLambdaInstrumentation(); + + const normalProvider = createMockTracerProvider(() => Promise.resolve()); + instrumentation.setTracerProvider(normalProvider as any); + + const mockSpan = { + end: vi.fn(), + recordException: vi.fn(), + setStatus: vi.fn(), + }; + + const callback = vi.fn(); + + (instrumentation as any)._endSpan(mockSpan, undefined, callback); + + await new Promise(resolve => setTimeout(resolve, 10)); + + expect(callback).toHaveBeenCalledTimes(1); + expect(mockSpan.end).toHaveBeenCalled(); + }); + + test('error information is set on span before flush attempt', async () => { + const instrumentation = new AwsLambdaInstrumentation(); + + const normalProvider = createMockTracerProvider(() => Promise.resolve()); + instrumentation.setTracerProvider(normalProvider as any); + + const mockSpan = { + end: vi.fn(), + recordException: vi.fn(), + setStatus: vi.fn(), + }; + + const error = new Error('lambda failure'); + const callback = vi.fn(); + + (instrumentation as any)._endSpan(mockSpan, error, callback); + + await new Promise(resolve => setTimeout(resolve, 10)); + + expect(mockSpan.recordException).toHaveBeenCalledWith(error); + expect(mockSpan.setStatus).toHaveBeenCalledWith({ + code: SpanStatusCode.ERROR, + message: 'lambda failure', + }); + expect(mockSpan.end).toHaveBeenCalled(); + expect(callback).toHaveBeenCalledTimes(1); + }); + }); +}); diff --git a/packages/browser-utils/.oxlintrc.json b/packages/browser-utils/.oxlintrc.json index 220599004174..a0967ad5a718 100644 --- a/packages/browser-utils/.oxlintrc.json +++ b/packages/browser-utils/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], "env": { "browser": true }, diff --git a/packages/browser/.oxlintrc.json b/packages/browser/.oxlintrc.json index a17777df77bf..28df8e880028 100644 --- a/packages/browser/.oxlintrc.json +++ b/packages/browser/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], "env": { "browser": true }, diff --git a/packages/browser/rollup.bundle.config.mjs b/packages/browser/rollup.bundle.config.mjs index ccba37ebc1c7..2a70d25dac77 100644 --- a/packages/browser/rollup.bundle.config.mjs +++ b/packages/browser/rollup.bundle.config.mjs @@ -18,6 +18,7 @@ const reexportedPluggableIntegrationFiles = [ 'instrumentgooglegenaiclient', 'instrumentlanggraph', 'createlangchaincallbackhandler', + 'instrumentlangchainembeddings', ]; browserPluggableIntegrationFiles.forEach(integrationName => { diff --git a/packages/browser/src/exports.ts b/packages/browser/src/exports.ts index e77465a87b39..322cc0b3c8db 100644 --- a/packages/browser/src/exports.ts +++ b/packages/browser/src/exports.ts @@ -70,6 +70,7 @@ export { spanToTraceHeader, spanToBaggageHeader, updateSpanName, + withStreamedSpan, metrics, } from '@sentry/core'; diff --git a/packages/browser/src/index.ts b/packages/browser/src/index.ts index dbf39482e3e2..25415f99894f 100644 --- a/packages/browser/src/index.ts +++ b/packages/browser/src/index.ts @@ -42,6 +42,7 @@ export { export { elementTimingIntegration } from '@sentry-internal/browser-utils'; export { reportPageLoaded } from './tracing/reportPageLoaded'; export { setActiveSpanInBrowser } from './tracing/setActiveSpan'; +export { spanStreamingIntegration } from './integrations/spanstreaming'; export type { RequestInstrumentationOptions } from './tracing/request'; export { @@ -70,6 +71,7 @@ export { instrumentGoogleGenAIClient, instrumentLangGraph, createLangChainCallbackHandler, + instrumentLangChainEmbeddings, logger, } from '@sentry/core'; export type { Span, FeatureFlagsIntegration } from '@sentry/core'; diff --git a/packages/browser/src/integrations-bundle/index.instrumentlangchainembeddings.ts b/packages/browser/src/integrations-bundle/index.instrumentlangchainembeddings.ts new file mode 100644 index 000000000000..644b8a2ef570 --- /dev/null +++ b/packages/browser/src/integrations-bundle/index.instrumentlangchainembeddings.ts @@ -0,0 +1 @@ +export { instrumentLangChainEmbeddings } from '@sentry/core'; diff --git a/packages/browser/src/integrations/spanstreaming.ts b/packages/browser/src/integrations/spanstreaming.ts new file mode 100644 index 000000000000..4225b9342fca --- /dev/null +++ b/packages/browser/src/integrations/spanstreaming.ts @@ -0,0 +1,71 @@ +import type { IntegrationFn } from '@sentry/core'; +import { + captureSpan, + debug, + defineIntegration, + hasSpanStreamingEnabled, + isStreamedBeforeSendSpanCallback, + SpanBuffer, + spanIsSampled, +} from '@sentry/core'; +import { DEBUG_BUILD } from '../debug-build'; + +export const spanStreamingIntegration = defineIntegration(() => { + return { + name: 'SpanStreaming', + + beforeSetup(client) { + // If users only set spanStreamingIntegration, without traceLifecycle, we set it to "stream" for them. + // This avoids the classic double-opt-in problem we'd otherwise have in the browser SDK. + const clientOptions = client.getOptions(); + if (!clientOptions.traceLifecycle) { + DEBUG_BUILD && debug.log('[SpanStreaming] set `traceLifecycle` to "stream"'); + clientOptions.traceLifecycle = 'stream'; + } + }, + + setup(client) { + const initialMessage = 'SpanStreaming integration requires'; + const fallbackMsg = 'Falling back to static trace lifecycle.'; + const clientOptions = client.getOptions(); + + if (!hasSpanStreamingEnabled(client)) { + clientOptions.traceLifecycle = 'static'; + DEBUG_BUILD && debug.warn(`${initialMessage} \`traceLifecycle\` to be set to "stream"! ${fallbackMsg}`); + return; + } + + const beforeSendSpan = clientOptions.beforeSendSpan; + // If users misconfigure their SDK by opting into span streaming but + // using an incompatible beforeSendSpan callback, we fall back to the static trace lifecycle. + if (beforeSendSpan && !isStreamedBeforeSendSpanCallback(beforeSendSpan)) { + clientOptions.traceLifecycle = 'static'; + DEBUG_BUILD && + debug.warn(`${initialMessage} a beforeSendSpan callback using \`withStreamedSpan\`! ${fallbackMsg}`); + return; + } + + const buffer = new SpanBuffer(client); + + client.on('afterSpanEnd', span => { + // Negatively sampled spans must not be captured. + // This happens because OTel and we create non-recording spans for negatively sampled spans + // that go through the same life cycle as recording spans. + if (!spanIsSampled(span)) { + return; + } + buffer.add(captureSpan(span, client)); + }); + + // In addition to capturing the span, we also flush the trace when the segment + // span ends to ensure things are sent timely. We never know when the browser + // is closed, users navigate away, etc. + client.on('afterSegmentSpanEnd', segmentSpan => { + const traceId = segmentSpan.spanContext().traceId; + setTimeout(() => { + buffer.flush(traceId); + }, 500); + }); + }, + }; +}) satisfies IntegrationFn; diff --git a/packages/browser/src/tracing/request.ts b/packages/browser/src/tracing/request.ts index 85faf0871a55..6211cf72947a 100644 --- a/packages/browser/src/tracing/request.ts +++ b/packages/browser/src/tracing/request.ts @@ -1,3 +1,4 @@ +/* eslint-disable max-lines */ import type { Client, HandlerDataXhr, @@ -5,6 +6,7 @@ import type { ResponseHookInfo, SentryWrappedXMLHttpRequest, Span, + SpanTimeInput, } from '@sentry/core'; import { addFetchEndInstrumentationHandler, @@ -14,6 +16,7 @@ import { getLocationHref, getTraceData, hasSpansEnabled, + hasSpanStreamingEnabled, instrumentFetchRequest, parseUrl, SEMANTIC_ATTRIBUTE_SENTRY_OP, @@ -25,6 +28,7 @@ import { stringMatchesSomePattern, stripDataUrlContent, stripUrlQueryAndFragment, + timestampInSeconds, } from '@sentry/core'; import type { XhrHint } from '@sentry-internal/browser-utils'; import { @@ -205,7 +209,7 @@ export function instrumentOutgoingRequests(client: Client, _options?: Partial { + // Clean up the performance observer and other resources + // We have to wait here because otherwise this cleans itself up before it is fully done. + // Default (non-streaming): just deregister the observer. + let onEntryFound = (): void => void setTimeout(unsubscribePerformanceObsever); + + // For streamed spans, we have to artificially delay the ending of the span until we + // either receive the timing data, or HTTP_TIMING_WAIT_MS elapses. + if (hasSpanStreamingEnabled(client)) { + const originalEnd = span.end.bind(span); + + span.end = (endTimestamp?: SpanTimeInput) => { + const capturedEndTimestamp = endTimestamp ?? timestampInSeconds(); + let isEnded = false; + + const endSpanAndCleanup = (): void => { + if (isEnded) { + return; + } + isEnded = true; + setTimeout(unsubscribePerformanceObsever); + originalEnd(capturedEndTimestamp); + clearTimeout(fallbackTimeout); + }; + + onEntryFound = endSpanAndCleanup; + + // Fallback: always end the span after HTTP_TIMING_WAIT_MS even if no + // PerformanceResourceTiming entry arrives (e.g. cross-origin without + // Timing-Allow-Origin, or the browser didn't fire the observer in time). + const fallbackTimeout = setTimeout(endSpanAndCleanup, HTTP_TIMING_WAIT_MS); + }; + } + + const unsubscribePerformanceObsever = addPerformanceInstrumentationHandler('resource', ({ entries }) => { entries.forEach(entry => { if (isPerformanceResourceTiming(entry) && entry.name.endsWith(url)) { span.setAttributes(resourceTimingToSpanAttributes(entry)); - // In the next tick, clean this handler up - // We have to wait here because otherwise this cleans itself up before it is fully done - setTimeout(cleanup); + onEntryFound(); } }); }); diff --git a/packages/browser/src/utils/lazyLoadIntegration.ts b/packages/browser/src/utils/lazyLoadIntegration.ts index ec0b11f099c0..a24da592faff 100644 --- a/packages/browser/src/utils/lazyLoadIntegration.ts +++ b/packages/browser/src/utils/lazyLoadIntegration.ts @@ -28,6 +28,7 @@ const LAZY_LOADABLE_NAMES = [ 'instrumentGoogleGenAIClient', 'instrumentLangGraph', 'createLangChainCallbackHandler', + 'instrumentLangChainEmbeddings', ] as const; type ElementOf = T[number]; diff --git a/packages/browser/test/integrations/spanstreaming.test.ts b/packages/browser/test/integrations/spanstreaming.test.ts new file mode 100644 index 000000000000..1d5d587290a3 --- /dev/null +++ b/packages/browser/test/integrations/spanstreaming.test.ts @@ -0,0 +1,199 @@ +import * as SentryCore from '@sentry/core'; +import { debug } from '@sentry/core'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { BrowserClient, spanStreamingIntegration } from '../../src'; +import { getDefaultBrowserClientOptions } from '../helper/browser-client-options'; + +// Mock SpanBuffer as a class that can be instantiated +const mockSpanBufferInstance = vi.hoisted(() => ({ + flush: vi.fn(), + add: vi.fn(), + drain: vi.fn(), +})); + +const MockSpanBuffer = vi.hoisted(() => { + return vi.fn(() => mockSpanBufferInstance); +}); + +vi.mock('@sentry/core', async () => { + const original = await vi.importActual('@sentry/core'); + return { + ...original, + SpanBuffer: MockSpanBuffer, + }; +}); + +describe('spanStreamingIntegration', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('has the correct hooks', () => { + const integration = spanStreamingIntegration(); + expect(integration.name).toBe('SpanStreaming'); + // eslint-disable-next-line @typescript-eslint/unbound-method + expect(integration.beforeSetup).toBeDefined(); + // eslint-disable-next-line @typescript-eslint/unbound-method + expect(integration.setup).toBeDefined(); + }); + + it('sets traceLifecycle to "stream" if not set', () => { + const client = new BrowserClient({ + ...getDefaultBrowserClientOptions(), + dsn: 'https://username@domain/123', + integrations: [spanStreamingIntegration()], + }); + + SentryCore.setCurrentClient(client); + client.init(); + + expect(client.getOptions().traceLifecycle).toBe('stream'); + }); + + it.each(['static', 'somethingElse'])( + 'logs a warning if traceLifecycle is not set to "stream" but to %s', + traceLifecycle => { + const debugSpy = vi.spyOn(debug, 'warn').mockImplementation(() => {}); + const client = new BrowserClient({ + ...getDefaultBrowserClientOptions(), + dsn: 'https://username@domain/123', + integrations: [spanStreamingIntegration()], + // @ts-expect-error - we want to test the warning for invalid traceLifecycle values + traceLifecycle, + }); + + SentryCore.setCurrentClient(client); + client.init(); + + expect(debugSpy).toHaveBeenCalledWith( + 'SpanStreaming integration requires `traceLifecycle` to be set to "stream"! Falling back to static trace lifecycle.', + ); + debugSpy.mockRestore(); + + expect(client.getOptions().traceLifecycle).toBe('static'); + }, + ); + + it('falls back to static trace lifecycle if beforeSendSpan is not compatible with span streaming', () => { + const debugSpy = vi.spyOn(debug, 'warn').mockImplementation(() => {}); + const client = new BrowserClient({ + ...getDefaultBrowserClientOptions(), + dsn: 'https://username@domain/123', + integrations: [spanStreamingIntegration()], + traceLifecycle: 'stream', + beforeSendSpan: (span: Span) => span, + }); + + SentryCore.setCurrentClient(client); + client.init(); + + expect(debugSpy).toHaveBeenCalledWith( + 'SpanStreaming integration requires a beforeSendSpan callback using `withStreamedSpan`! Falling back to static trace lifecycle.', + ); + debugSpy.mockRestore(); + + expect(client.getOptions().traceLifecycle).toBe('static'); + }); + + it('does nothing if traceLifecycle set to "stream"', () => { + const client = new BrowserClient({ + ...getDefaultBrowserClientOptions(), + dsn: 'https://username@domain/123', + integrations: [spanStreamingIntegration()], + traceLifecycle: 'stream', + }); + + SentryCore.setCurrentClient(client); + client.init(); + + expect(client.getOptions().traceLifecycle).toBe('stream'); + }); + + it('enqueues a span into the buffer when the span ends', () => { + const client = new BrowserClient({ + ...getDefaultBrowserClientOptions(), + dsn: 'https://username@domain/123', + integrations: [spanStreamingIntegration()], + tracesSampleRate: 1, + }); + + SentryCore.setCurrentClient(client); + client.init(); + + const span = new SentryCore.SentrySpan({ name: 'test', sampled: true }); + client.emit('afterSpanEnd', span); + + expect(mockSpanBufferInstance.add).toHaveBeenCalledWith({ + _segmentSpan: span, + trace_id: span.spanContext().traceId, + span_id: span.spanContext().spanId, + end_timestamp: expect.any(Number), + is_segment: true, + name: 'test', + start_timestamp: expect.any(Number), + status: 'ok', + attributes: { + 'sentry.origin': { + type: 'string', + value: 'manual', + }, + 'sentry.sdk.name': { + type: 'string', + value: 'sentry.javascript.browser', + }, + 'sentry.sdk.version': { + type: 'string', + value: expect.any(String), + }, + 'sentry.segment.id': { + type: 'string', + value: span.spanContext().spanId, + }, + 'sentry.segment.name': { + type: 'string', + value: 'test', + }, + }, + }); + }); + + it('does not enqueue a span into the buffer when the span is not sampled', () => { + const client = new BrowserClient({ + ...getDefaultBrowserClientOptions(), + dsn: 'https://username@domain/123', + integrations: [spanStreamingIntegration()], + tracesSampleRate: 1, + }); + + SentryCore.setCurrentClient(client); + client.init(); + + const span = new SentryCore.SentrySpan({ name: 'test', sampled: false }); + client.emit('afterSpanEnd', span); + + expect(mockSpanBufferInstance.add).not.toHaveBeenCalled(); + expect(mockSpanBufferInstance.flush).not.toHaveBeenCalled(); + }); + + it('flushes the trace when the segment span ends after a delay for close to finished child spans', () => { + vi.useFakeTimers(); + const client = new BrowserClient({ + ...getDefaultBrowserClientOptions(), + dsn: 'https://username@domain/123', + integrations: [spanStreamingIntegration()], + traceLifecycle: 'stream', + }); + + SentryCore.setCurrentClient(client); + client.init(); + + const span = new SentryCore.SentrySpan({ name: 'test' }); + client.emit('afterSegmentSpanEnd', span); + + vi.advanceTimersByTime(500); + + expect(mockSpanBufferInstance.flush).toHaveBeenCalledWith(span.spanContext().traceId); + + vi.useRealTimers(); + }); +}); diff --git a/packages/bun/.oxlintrc.json b/packages/bun/.oxlintrc.json index 5d561466a55b..d774a8e7bfa0 100644 --- a/packages/bun/.oxlintrc.json +++ b/packages/bun/.oxlintrc.json @@ -1,6 +1,12 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], + "jsPlugins": [ + { + "name": "sdk", + "specifier": "@sentry-internal/eslint-plugin-sdk" + } + ], "env": { "node": true }, diff --git a/packages/bun/src/index.ts b/packages/bun/src/index.ts index 41f5b3cf5c52..c44742a0e2d3 100644 --- a/packages/bun/src/index.ts +++ b/packages/bun/src/index.ts @@ -67,6 +67,7 @@ export { getSentryRelease, createGetModuleFromFilename, createLangChainCallbackHandler, + instrumentLangChainEmbeddings, httpHeadersToSpanAttributes, winterCGHeadersToDict, // eslint-disable-next-line deprecation/deprecation @@ -177,6 +178,8 @@ export { statsigIntegration, unleashIntegration, metrics, + spanStreamingIntegration, + withStreamedSpan, } from '@sentry/node'; export { diff --git a/packages/bun/src/integrations/bunRuntimeMetrics.ts b/packages/bun/src/integrations/bunRuntimeMetrics.ts index 7646eb23568b..5bd4e87adbf4 100644 --- a/packages/bun/src/integrations/bunRuntimeMetrics.ts +++ b/packages/bun/src/integrations/bunRuntimeMetrics.ts @@ -1,6 +1,6 @@ import { performance } from 'perf_hooks'; import { _INTERNAL_safeDateNow, _INTERNAL_safeUnref, defineIntegration, metrics } from '@sentry/core'; -import type { NodeRuntimeMetricsOptions } from '@sentry/node'; +import { _INTERNAL_normalizeCollectionInterval, type NodeRuntimeMetricsOptions } from '@sentry/node'; const INTEGRATION_NAME = 'BunRuntimeMetrics'; const DEFAULT_INTERVAL_MS = 30_000; @@ -44,7 +44,9 @@ export interface BunRuntimeMetricsOptions { collect?: BunCollectOptions; /** * How often to collect metrics, in milliseconds. + * Minimum allowed value is 1000ms. * @default 30000 + * @minimum 1000 */ collectionIntervalMs?: number; } @@ -62,7 +64,11 @@ export interface BunRuntimeMetricsOptions { * ``` */ export const bunRuntimeMetricsIntegration = defineIntegration((options: BunRuntimeMetricsOptions = {}) => { - const collectionIntervalMs = options.collectionIntervalMs ?? DEFAULT_INTERVAL_MS; + const collectionIntervalMs = _INTERNAL_normalizeCollectionInterval( + options.collectionIntervalMs ?? DEFAULT_INTERVAL_MS, + INTEGRATION_NAME, + DEFAULT_INTERVAL_MS, + ); const collect = { // Default on cpuUtilization: true, diff --git a/packages/bun/test/integrations/bunRuntimeMetrics.test.ts b/packages/bun/test/integrations/bunRuntimeMetrics.test.ts index 6264905db41e..a03b07ffe760 100644 --- a/packages/bun/test/integrations/bunRuntimeMetrics.test.ts +++ b/packages/bun/test/integrations/bunRuntimeMetrics.test.ts @@ -212,4 +212,39 @@ describe('bunRuntimeMetricsIntegration', () => { expect(countSpy).not.toHaveBeenCalledWith('bun.runtime.process.uptime', expect.anything(), expect.anything()); }); }); + + describe('collectionIntervalMs minimum', () => { + it('enforces minimum of 1000ms and warns', () => { + const warnSpy = spyOn(globalThis.console, 'warn').mockImplementation(() => {}); + + const integration = bunRuntimeMetricsIntegration({ collectionIntervalMs: 100 }); + integration.setup(); + + expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('collectionIntervalMs')); + expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('1000')); + + // Should fire at minimum 1000ms, not at 100ms + jest.advanceTimersByTime(100); + expect(gaugeSpy).not.toHaveBeenCalled(); + + jest.advanceTimersByTime(900); + expect(gaugeSpy).toHaveBeenCalled(); + }); + + it('falls back to default when NaN', () => { + const warnSpy = spyOn(globalThis.console, 'warn').mockImplementation(() => {}); + + const integration = bunRuntimeMetricsIntegration({ collectionIntervalMs: NaN }); + integration.setup(); + + expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('collectionIntervalMs')); + + // Should fire at the default 30000ms, not at 1000ms + jest.advanceTimersByTime(1000); + expect(gaugeSpy).not.toHaveBeenCalled(); + + jest.advanceTimersByTime(29_000); + expect(gaugeSpy).toHaveBeenCalled(); + }); + }); }); diff --git a/packages/cloudflare/.oxlintrc.json b/packages/cloudflare/.oxlintrc.json index 5d561466a55b..d774a8e7bfa0 100644 --- a/packages/cloudflare/.oxlintrc.json +++ b/packages/cloudflare/.oxlintrc.json @@ -1,6 +1,12 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], + "jsPlugins": [ + { + "name": "sdk", + "specifier": "@sentry-internal/eslint-plugin-sdk" + } + ], "env": { "node": true }, diff --git a/packages/cloudflare/src/durableobject.ts b/packages/cloudflare/src/durableobject.ts index fc07cb46ca00..af60ab5e59e0 100644 --- a/packages/cloudflare/src/durableobject.ts +++ b/packages/cloudflare/src/durableobject.ts @@ -3,7 +3,7 @@ import { captureException } from '@sentry/core'; import type { DurableObject } from 'cloudflare:workers'; import { setAsyncLocalStorageAsyncContextStrategy } from './async'; import type { CloudflareOptions } from './client'; -import { isInstrumented, markAsInstrumented } from './instrument'; +import { ensureInstrumented, getInstrumented, markAsInstrumented } from './instrument'; import { getFinalOptions } from './options'; import { wrapRequestHandler } from './request'; import { instrumentContext } from './utils/instrumentContext'; @@ -67,16 +67,18 @@ export function instrumentDurableObjectWithSentry< // Any other public methods on the Durable Object instance are RPC calls. - if (obj.fetch && typeof obj.fetch === 'function' && !isInstrumented(obj.fetch)) { - obj.fetch = new Proxy(obj.fetch, { - apply(target, thisArg, args) { - return wrapRequestHandler({ options, request: args[0], context }, () => - Reflect.apply(target, thisArg, args), - ); - }, - }); - - markAsInstrumented(obj.fetch); + if (obj.fetch && typeof obj.fetch === 'function') { + obj.fetch = ensureInstrumented( + obj.fetch, + original => + new Proxy(original, { + apply(target, thisArg, args) { + return wrapRequestHandler({ options, request: args[0], context }, () => { + return Reflect.apply(target, thisArg, args); + }); + }, + }), + ); } if (obj.alarm && typeof obj.alarm === 'function') { @@ -177,7 +179,18 @@ function instrumentPrototype(target: T, methodsToInst methodNames.forEach(methodName => { const originalMethod = (proto as Record)[methodName]; - if (!originalMethod || isInstrumented(originalMethod)) { + if (!originalMethod) { + return; + } + + const existingInstrumented = getInstrumented(originalMethod); + if (existingInstrumented) { + Object.defineProperty(proto, methodName, { + value: existingInstrumented, + enumerable: false, + writable: true, + configurable: true, + }); return; } @@ -216,6 +229,11 @@ function instrumentPrototype(target: T, methodsToInst return wrapper.apply(this, args); }; + // Only mark wrappedMethod as instrumented (not originalMethod → wrappedMethod). + // originalMethod must stay unmapped because wrappedMethod calls + // wrapMethodWithSentry(options, originalMethod) on each invocation to create + // a per-instance proxy. If originalMethod mapped to wrappedMethod, that call + // would return wrappedMethod itself, causing infinite recursion. markAsInstrumented(wrappedMethod); // Replace the prototype method diff --git a/packages/cloudflare/src/index.ts b/packages/cloudflare/src/index.ts index affb4a4f0b45..f69978064277 100644 --- a/packages/cloudflare/src/index.ts +++ b/packages/cloudflare/src/index.ts @@ -102,10 +102,12 @@ export { consoleLoggingIntegration, createConsolaReporter, createLangChainCallbackHandler, + instrumentLangChainEmbeddings, featureFlagsIntegration, growthbookIntegration, logger, metrics, + withStreamedSpan, instrumentLangGraph, } from '@sentry/core'; diff --git a/packages/cloudflare/src/instrument.ts b/packages/cloudflare/src/instrument.ts index 1ebe4262644a..5a3a472b306e 100644 --- a/packages/cloudflare/src/instrument.ts +++ b/packages/cloudflare/src/instrument.ts @@ -1,25 +1,84 @@ -type SentryInstrumented = T & { - __SENTRY_INSTRUMENTED__?: boolean; -}; +// Use a global WeakMap to track instrumented objects across module instances. +// This is important for Cloudflare Workers where the module may be bundled +// separately for workers and Durable Objects, but they share the same global scope. +// The WeakMap stores original -> instrumented mappings so we can retrieve the +// instrumented version even if we only have a reference to the original. +const GLOBAL_KEY = '__SENTRY_INSTRUMENTED_MAP__' as const; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function getInstrumentedMap(): WeakMap { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const globalObj = globalThis as typeof globalThis & { [GLOBAL_KEY]?: WeakMap }; + if (!globalObj[GLOBAL_KEY]) { + globalObj[GLOBAL_KEY] = new WeakMap(); + } + return globalObj[GLOBAL_KEY]; +} /** - * Mark an object as instrumented. + * Check if a value can be used as a WeakMap key. + * WeakMap keys must be objects or non-registered symbols. */ -export function markAsInstrumented(obj: T): void { +function isWeakMapKey(value: unknown): value is object { + return (typeof value === 'object' && value !== null) || typeof value === 'function'; +} + +/** + * Mark an object as instrumented, storing the instrumented version. + * @param original The original uninstrumented object + * @param instrumented The instrumented version (defaults to original if not provided) + */ +export function markAsInstrumented(original: T, instrumented?: T): void { try { - (obj as SentryInstrumented).__SENTRY_INSTRUMENTED__ = true; + if (isWeakMapKey(original)) { + // Store mapping from original to instrumented version + // If instrumented is not provided, store original (for backwards compat) + getInstrumentedMap().set(original, instrumented ?? original); + } + // Also mark the instrumented version itself so we recognize it + if (isWeakMapKey(instrumented) && instrumented !== original) { + getInstrumentedMap().set(instrumented, instrumented); + } } catch { // ignore errors here } } /** - * Check if an object is instrumented. + * Get the instrumented version of an object, if available. + * Returns the instrumented version if the object was previously instrumented, + * or undefined if not found. */ -export function isInstrumented(obj: T): boolean | undefined { +export function getInstrumented(obj: T): T | undefined { try { - return (obj as SentryInstrumented).__SENTRY_INSTRUMENTED__; + if (isWeakMapKey(obj)) { + return getInstrumentedMap().get(obj) as T | undefined; + } + + return undefined; } catch { - return false; + return undefined; + } +} + +/** + * Returns the already-instrumented version of `original` if one exists, + * otherwise calls `instrumentFn` to create it, marks the mapping, and returns it. + * + * @param noMark - If true, skips storing the original→instrumented mapping. + */ +export function ensureInstrumented(original: T, instrumentFn: (original: T) => T, noMark?: boolean): T { + const existing = getInstrumented(original); + + if (existing) { + return existing; } + + const instrumented = instrumentFn(original); + + if (!noMark) { + markAsInstrumented(original, instrumented); + } + + return instrumented; } diff --git a/packages/cloudflare/src/instrumentations/instrumentWorkerEntrypoint.ts b/packages/cloudflare/src/instrumentations/instrumentWorkerEntrypoint.ts new file mode 100644 index 000000000000..6a9daf83ec1c --- /dev/null +++ b/packages/cloudflare/src/instrumentations/instrumentWorkerEntrypoint.ts @@ -0,0 +1,103 @@ +import { setAsyncLocalStorageAsyncContextStrategy } from '../async'; +import type { env as cloudflareEnv, WorkerEntrypoint } from 'cloudflare:workers'; +import type { CloudflareOptions } from '../client'; +import { instrumentWorkerEntrypointFetch } from './worker/instrumentFetch'; +import { instrumentWorkerEntrypointQueue } from './worker/instrumentQueue'; +import { instrumentWorkerEntrypointScheduled } from './worker/instrumentScheduled'; +import { instrumentWorkerEntrypointTail } from './worker/instrumentTail'; +import { getFinalOptions } from '../options'; +import { instrumentContext } from '../utils/instrumentContext'; + +export type WorkerEntrypointConstructor = new ( + ctx: ExecutionContext, + env: typeof cloudflareEnv, +) => InstanceType>; + +/** + * Instruments a WorkerEntrypoint class to capture errors and performance data. + * + * Instruments the following methods (same as `withSentry` for ExportedHandler): + * - fetch (HTTP requests) + * - scheduled (cron triggers) + * - queue (queue consumers) + * - email (email handlers) + * - tail (tail workers) + * + * as well as any other public RPC methods on the WorkerEntrypoint instance. + * + * @param optionsCallback Function that returns the options for the SDK initialization. + * @param WorkerEntrypointClass The WorkerEntrypoint class to instrument. + * @returns The instrumented WorkerEntrypoint class. + * + * @example + * ```ts + * class MyWorkerBase extends WorkerEntrypoint { + * async fetch(request: Request): Promise { + * return new Response('Hello World!'); + * } + * + * async myRpcMethod(arg: string): Promise { + * return `Hello ${arg}!`; + * } + * } + * + * export default instrumentWorkerEntrypoint( + * env => ({ + * dsn: env.SENTRY_DSN, + * tracesSampleRate: 1.0, + * }), + * MyWorkerBase, + * ); + * ``` + */ +export function instrumentWorkerEntrypoint( + optionsCallback: (env: typeof cloudflareEnv) => CloudflareOptions | undefined, + WorkerEntrypointClass: T, +): T { + // Set up AsyncLocalStorage strategy ONCE at instrumentation time, not per-request + // This is critical - calling this per-request would create a new AsyncLocalStorage + // each time, breaking scope isolation for concurrent requests + setAsyncLocalStorageAsyncContextStrategy(); + + return new Proxy(WorkerEntrypointClass, { + construct(target, [ctx, env]) { + const context = instrumentContext(ctx); + const options = getFinalOptions(optionsCallback(env), env); + const obj = new target(context, env); + + // Override this.ctx to ensure the instrumented context is used + // This is necessary because the base WorkerEntrypoint class sets this.ctx + // from the constructor parameter, but we want users accessing this.ctx + // to get the instrumented version + if ('ctx' in obj) { + Object.defineProperty(obj, 'ctx', { + value: context, + writable: true, + enumerable: true, + configurable: true, + }); + } + + Object.defineProperty(obj, '__SENTRY_CONTEXT__', { + value: context, + enumerable: false, + writable: false, + configurable: false, + }); + + Object.defineProperty(obj, '__SENTRY_OPTIONS__', { + value: options, + enumerable: false, + writable: false, + configurable: false, + }); + + instrumentWorkerEntrypointFetch(obj, options, context); + instrumentWorkerEntrypointScheduled(obj, options, context); + instrumentWorkerEntrypointQueue(obj, options, context); + instrumentWorkerEntrypointTail(obj, options, context); + + return obj; + }, + }); +} diff --git a/packages/cloudflare/src/instrumentations/worker/instrumentEmail.ts b/packages/cloudflare/src/instrumentations/worker/instrumentEmail.ts index 8c91bf2cb3d2..0fe140c79beb 100644 --- a/packages/cloudflare/src/instrumentations/worker/instrumentEmail.ts +++ b/packages/cloudflare/src/instrumentations/worker/instrumentEmail.ts @@ -1,4 +1,5 @@ import type { EmailMessage, ExportedHandler } from '@cloudflare/workers-types'; +import type { env as cloudflareEnv } from 'cloudflare:workers'; import { captureException, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, @@ -8,7 +9,7 @@ import { } from '@sentry/core'; import type { CloudflareOptions } from '../../client'; import { flushAndDispose } from '../../flush'; -import { isInstrumented, markAsInstrumented } from '../../instrument'; +import { ensureInstrumented } from '../../instrument'; import { getFinalOptions } from '../../options'; import { addCloudResourceContext } from '../../scope-utils'; import { init } from '../../sdk'; @@ -61,23 +62,25 @@ function wrapEmailHandler( // eslint-disable-next-line @typescript-eslint/no-explicit-any export function instrumentExportedHandlerEmail>( handler: T, - optionsCallback: (env: Parameters>[1]) => CloudflareOptions | undefined, + optionsCallback: (env: typeof cloudflareEnv) => CloudflareOptions | undefined, ): void { - if (!('email' in handler) || typeof handler.email !== 'function' || isInstrumented(handler.email)) { + if (!('email' in handler) || typeof handler.email !== 'function') { return; } - handler.email = new Proxy(handler.email, { - apply(target, thisArg, args: Parameters>) { - const [emailMessage, env, ctx] = args; - const context = instrumentContext(ctx); - args[2] = context; + handler.email = ensureInstrumented( + handler.email, + original => + new Proxy(original, { + apply(target, thisArg, args: Parameters>) { + const [emailMessage, env, ctx] = args; + const context = instrumentContext(ctx); + args[2] = context; - const options = getFinalOptions(optionsCallback(env), env); + const options = getFinalOptions(optionsCallback(env), env); - return wrapEmailHandler(emailMessage, options, context, () => target.apply(thisArg, args)); - }, - }); - - markAsInstrumented(handler.email); + return wrapEmailHandler(emailMessage, options, context, () => target.apply(thisArg, args)); + }, + }), + ); } diff --git a/packages/cloudflare/src/instrumentations/worker/instrumentFetch.ts b/packages/cloudflare/src/instrumentations/worker/instrumentFetch.ts index be58fa07e18f..d584a7d5d453 100644 --- a/packages/cloudflare/src/instrumentations/worker/instrumentFetch.ts +++ b/packages/cloudflare/src/instrumentations/worker/instrumentFetch.ts @@ -1,6 +1,7 @@ import type { ExportedHandler } from '@cloudflare/workers-types'; +import type { env as cloudflareEnv, WorkerEntrypoint } from 'cloudflare:workers'; import type { CloudflareOptions } from '../../client'; -import { isInstrumented, markAsInstrumented } from '../../instrument'; +import { ensureInstrumented } from '../../instrument'; import { getFinalOptions } from '../../options'; import { wrapRequestHandler } from '../../request'; import { instrumentContext } from '../../utils/instrumentContext'; @@ -11,23 +12,47 @@ import { instrumentContext } from '../../utils/instrumentContext'; // eslint-disable-next-line @typescript-eslint/no-explicit-any export function instrumentExportedHandlerFetch>( handler: T, - optionsCallback: (env: Parameters>[1]) => CloudflareOptions | undefined, + optionsCallback: (env: typeof cloudflareEnv) => CloudflareOptions | undefined, ): void { - if (!('fetch' in handler) || typeof handler.fetch !== 'function' || isInstrumented(handler.fetch)) { + if (!('fetch' in handler) || typeof handler.fetch !== 'function') { return; } - handler.fetch = new Proxy(handler.fetch, { - apply(target, thisArg, args: Parameters>) { - const [request, env, ctx] = args; - const context = instrumentContext(ctx); - args[2] = context; + handler.fetch = ensureInstrumented( + handler.fetch, + original => + new Proxy(original, { + apply(target, thisArg, args: Parameters>) { + const [request, env, ctx] = args; + const context = instrumentContext(ctx); + args[2] = context; - const options = getFinalOptions(optionsCallback(env), env); + const options = getFinalOptions(optionsCallback(env), env); - return wrapRequestHandler({ options, request, context }, () => target.apply(thisArg, args)); + return wrapRequestHandler({ options, request, context }, () => target.apply(thisArg, args)); + }, + }), + ); +} + +/** + * Instruments a fetch method for WorkerEntrypoint (options/context already available). + */ +export function instrumentWorkerEntrypointFetch( + instance: T, + options: CloudflareOptions, + context: ExecutionContext, +): void { + if (!instance.fetch) { + return; + } + + const original = instance.fetch.bind(instance); + instance.fetch = new Proxy(original, { + apply(target, thisArg, args: [Request]) { + const [request] = args; + + return wrapRequestHandler({ options, request, context }, () => Reflect.apply(target, thisArg, args)); }, }); - - markAsInstrumented(handler.fetch); } diff --git a/packages/cloudflare/src/instrumentations/worker/instrumentQueue.ts b/packages/cloudflare/src/instrumentations/worker/instrumentQueue.ts index 366fb7e98f51..df41a4afc8b3 100644 --- a/packages/cloudflare/src/instrumentations/worker/instrumentQueue.ts +++ b/packages/cloudflare/src/instrumentations/worker/instrumentQueue.ts @@ -1,4 +1,5 @@ import type { ExportedHandler, MessageBatch } from '@cloudflare/workers-types'; +import type { env as cloudflareEnv, WorkerEntrypoint } from 'cloudflare:workers'; import { captureException, SEMANTIC_ATTRIBUTE_SENTRY_OP, @@ -9,7 +10,7 @@ import { } from '@sentry/core'; import type { CloudflareOptions } from '../../client'; import { flushAndDispose } from '../../flush'; -import { isInstrumented, markAsInstrumented } from '../../instrument'; +import { ensureInstrumented } from '../../instrument'; import { getFinalOptions } from '../../options'; import { addCloudResourceContext } from '../../scope-utils'; import { init } from '../../sdk'; @@ -67,23 +68,47 @@ function wrapQueueHandler( // eslint-disable-next-line @typescript-eslint/no-explicit-any export function instrumentExportedHandlerQueue>( handler: T, - optionsCallback: (env: Parameters>[1]) => CloudflareOptions | undefined, + optionsCallback: (env: typeof cloudflareEnv) => CloudflareOptions | undefined, ): void { - if (!('queue' in handler) || typeof handler.queue !== 'function' || isInstrumented(handler.queue)) { + if (!('queue' in handler) || typeof handler.queue !== 'function') { return; } - handler.queue = new Proxy(handler.queue, { - apply(target, thisArg, args: Parameters>) { - const [batch, env, ctx] = args; - const context = instrumentContext(ctx); - args[2] = context; + handler.queue = ensureInstrumented( + handler.queue, + original => + new Proxy(original, { + apply(target, thisArg, args: Parameters>) { + const [batch, env, ctx] = args; + const context = instrumentContext(ctx); + args[2] = context; - const options = getFinalOptions(optionsCallback(env), env); + const options = getFinalOptions(optionsCallback(env), env); - return wrapQueueHandler(batch, options, context, () => target.apply(thisArg, args)); + return wrapQueueHandler(batch, options, context, () => target.apply(thisArg, args)); + }, + }), + ); +} + +/** + * Instruments a queue method for WorkerEntrypoint (options/context already available). + */ +export function instrumentWorkerEntrypointQueue( + instance: T, + options: CloudflareOptions, + context: ExecutionContext, +): void { + if (!instance.queue) { + return; + } + + const original = instance.queue.bind(instance); + instance.queue = new Proxy(original, { + apply(target, thisArg, args: [MessageBatch]) { + const [batch] = args; + + return wrapQueueHandler(batch, options, context, () => Reflect.apply(target, thisArg, args)); }, }); - - markAsInstrumented(handler.queue); } diff --git a/packages/cloudflare/src/instrumentations/worker/instrumentScheduled.ts b/packages/cloudflare/src/instrumentations/worker/instrumentScheduled.ts index 2ef682829bcb..d76c980ed621 100644 --- a/packages/cloudflare/src/instrumentations/worker/instrumentScheduled.ts +++ b/packages/cloudflare/src/instrumentations/worker/instrumentScheduled.ts @@ -1,4 +1,5 @@ import type { ExportedHandler, ScheduledController } from '@cloudflare/workers-types'; +import type { env as cloudflareEnv, WorkerEntrypoint } from 'cloudflare:workers'; import { captureException, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, @@ -8,15 +9,12 @@ import { } from '@sentry/core'; import type { CloudflareOptions } from '../../client'; import { flushAndDispose } from '../../flush'; -import { isInstrumented, markAsInstrumented } from '../../instrument'; +import { ensureInstrumented } from '../../instrument'; import { getFinalOptions } from '../../options'; import { addCloudResourceContext } from '../../scope-utils'; import { init } from '../../sdk'; import { instrumentContext } from '../../utils/instrumentContext'; -/** - * Core scheduled handler logic - wraps execution with Sentry instrumentation. - */ function wrapScheduledHandler( controller: ScheduledController, options: CloudflareOptions, @@ -63,23 +61,47 @@ function wrapScheduledHandler( // eslint-disable-next-line @typescript-eslint/no-explicit-any export function instrumentExportedHandlerScheduled>( handler: T, - optionsCallback: (env: Parameters>[1]) => CloudflareOptions | undefined, + optionsCallback: (env: typeof cloudflareEnv) => CloudflareOptions | undefined, ): void { - if (!('scheduled' in handler) || typeof handler.scheduled !== 'function' || isInstrumented(handler.scheduled)) { + if (!('scheduled' in handler) || typeof handler.scheduled !== 'function') { return; } - handler.scheduled = new Proxy(handler.scheduled, { - apply(target, thisArg, args: Parameters>) { - const [controller, env, ctx] = args; - const context = instrumentContext(ctx); - args[2] = context; + handler.scheduled = ensureInstrumented( + handler.scheduled, + original => + new Proxy(original, { + apply(target, thisArg, args: Parameters>) { + const [controller, env, ctx] = args; + const context = instrumentContext(ctx); + args[2] = context; - const options = getFinalOptions(optionsCallback(env), env); + const options = getFinalOptions(optionsCallback(env), env); + + return wrapScheduledHandler(controller, options, context, () => target.apply(thisArg, args)); + }, + }), + ); +} - return wrapScheduledHandler(controller, options, context, () => target.apply(thisArg, args)); +/** + * Instruments a scheduled method for WorkerEntrypoint (options/context already available). + */ +export function instrumentWorkerEntrypointScheduled( + instance: T, + options: CloudflareOptions, + context: ExecutionContext, +): void { + if (!instance.scheduled) { + return; + } + + const original = instance.scheduled.bind(instance); + instance.scheduled = new Proxy(original, { + apply(target, thisArg, args: [ScheduledController]) { + const [controller] = args; + + return wrapScheduledHandler(controller, options, context, () => Reflect.apply(target, thisArg, args)); }, }); - - markAsInstrumented(handler.scheduled); } diff --git a/packages/cloudflare/src/instrumentations/worker/instrumentTail.ts b/packages/cloudflare/src/instrumentations/worker/instrumentTail.ts index f6b2e4492106..38abfcc0e777 100644 --- a/packages/cloudflare/src/instrumentations/worker/instrumentTail.ts +++ b/packages/cloudflare/src/instrumentations/worker/instrumentTail.ts @@ -1,8 +1,9 @@ -import type { ExportedHandler } from '@cloudflare/workers-types'; +import type { ExportedHandler, TraceItem } from '@cloudflare/workers-types'; +import type { env as cloudflareEnv, WorkerEntrypoint } from 'cloudflare:workers'; import { captureException, withIsolationScope } from '@sentry/core'; import type { CloudflareOptions } from '../../client'; import { flushAndDispose } from '../../flush'; -import { isInstrumented, markAsInstrumented } from '../../instrument'; +import { ensureInstrumented } from '../../instrument'; import { getFinalOptions } from '../../options'; import { addCloudResourceContext } from '../../scope-utils'; import { init } from '../../sdk'; @@ -38,23 +39,45 @@ function wrapTailHandler(options: CloudflareOptions, context: ExecutionContext, // eslint-disable-next-line @typescript-eslint/no-explicit-any export function instrumentExportedHandlerTail>( handler: T, - optionsCallback: (env: Parameters>[1]) => CloudflareOptions | undefined, + optionsCallback: (env: typeof cloudflareEnv) => CloudflareOptions | undefined, ): void { - if (!('tail' in handler) || typeof handler.tail !== 'function' || isInstrumented(handler.tail)) { + if (!('tail' in handler) || typeof handler.tail !== 'function') { return; } - handler.tail = new Proxy(handler.tail, { - apply(target, thisArg, args: Parameters>) { - const [, env, ctx] = args; - const context = instrumentContext(ctx); - args[2] = context; + handler.tail = ensureInstrumented( + handler.tail, + original => + new Proxy(original, { + apply(target, thisArg, args: Parameters>) { + const [, env, ctx] = args; + const context = instrumentContext(ctx); + args[2] = context; - const options = getFinalOptions(optionsCallback(env), env); + const options = getFinalOptions(optionsCallback(env), env); - return wrapTailHandler(options, context, () => target.apply(thisArg, args)); + return wrapTailHandler(options, context, () => target.apply(thisArg, args)); + }, + }), + ); +} + +/** + * Instruments a tail method for WorkerEntrypoint (options/context already available). + */ +export function instrumentWorkerEntrypointTail( + instance: T, + options: CloudflareOptions, + context: ExecutionContext, +): void { + if (!instance.tail) { + return; + } + + const original = instance.tail.bind(instance); + instance.tail = new Proxy(original, { + apply(target, thisArg, args: [TraceItem[]]) { + return wrapTailHandler(options, context, () => Reflect.apply(target, thisArg, args)); }, }); - - markAsInstrumented(handler.tail); } diff --git a/packages/cloudflare/src/request.ts b/packages/cloudflare/src/request.ts index 9d8d63eab8c1..05e870ff5d81 100644 --- a/packages/cloudflare/src/request.ts +++ b/packages/cloudflare/src/request.ts @@ -1,4 +1,4 @@ -import type { ExecutionContext, IncomingRequestCfProperties } from '@cloudflare/workers-types'; +import type { CfProperties, ExecutionContext, IncomingRequestCfProperties } from '@cloudflare/workers-types'; import { captureException, continueTrace, @@ -20,8 +20,8 @@ import { classifyResponseStreaming } from './utils/streaming'; interface RequestHandlerWrapperOptions { options: CloudflareOptions; - request: Request>; - context: ExecutionContext; + request: Request | CfProperties>; + context: ExecutionContext | undefined; /** * If true, errors will be captured, rethrown and sent to Sentry. * Otherwise, errors are rethrown but not captured. @@ -44,11 +44,7 @@ export function wrapRequestHandler( ): Promise { return withIsolationScope(async isolationScope => { const { options, request, captureErrors = true } = wrapperOptions; - - // In certain situations, the passed context can become undefined. - // For example, for Astro while prerendering pages at build time. - // see: https://github.com/getsentry/sentry-javascript/issues/13217 - const context = wrapperOptions.context as ExecutionContext | undefined; + const context = wrapperOptions.context; const waitUntil = context?.waitUntil?.bind?.(context); @@ -82,7 +78,10 @@ export function wrapRequestHandler( addRequest(isolationScope, request); if (request.cf) { addCultureContext(isolationScope, request.cf); - attributes['network.protocol.name'] = request.cf.httpProtocol; + + if (typeof request.cf.httpProtocol === 'string') { + attributes['network.protocol.name'] = request.cf.httpProtocol; + } } // Do not capture spans for OPTIONS and HEAD requests diff --git a/packages/cloudflare/src/scope-utils.ts b/packages/cloudflare/src/scope-utils.ts index 9a3f7d286dfc..7c46e8af1001 100644 --- a/packages/cloudflare/src/scope-utils.ts +++ b/packages/cloudflare/src/scope-utils.ts @@ -1,4 +1,4 @@ -import type { IncomingRequestCfProperties } from '@cloudflare/workers-types'; +import type { CfProperties, IncomingRequestCfProperties } from '@cloudflare/workers-types'; import type { Scope } from '@sentry/core'; import { winterCGRequestToRequestData } from '@sentry/core'; @@ -14,7 +14,7 @@ export function addCloudResourceContext(scope: Scope): void { /** * Set culture context on scope */ -export function addCultureContext(scope: Scope, cf: IncomingRequestCfProperties): void { +export function addCultureContext(scope: Scope, cf: IncomingRequestCfProperties | CfProperties): void { scope.setContext('culture', { timezone: cf.timezone, }); diff --git a/packages/cloudflare/src/utils/isCloudflareClass.ts b/packages/cloudflare/src/utils/isCloudflareClass.ts new file mode 100644 index 000000000000..40ee8a3fd1a5 --- /dev/null +++ b/packages/cloudflare/src/utils/isCloudflareClass.ts @@ -0,0 +1,61 @@ +import type { DurableObject, WorkflowEntrypoint } from 'cloudflare:workers'; +import type { WorkerEntrypointConstructor } from '../instrumentations/instrumentWorkerEntrypoint'; +type CloudflareClassName = 'WorkerEntrypoint' | 'DurableObject' | 'WorkflowEntrypoint'; + +/** + * Checks if a class constructor extends a specific Cloudflare base class. + * + * Uses prototype chain walking with constructor names rather than instanceof, + * so it works in Node at build time without requiring the cloudflare:workers + * module (which only exists in the Workers runtime). + * + * This is used to differentiate between different Cloudflare worker types: + * - WorkerEntrypoint: Class-based workers (used with instrumentWorkerEntrypoint) + * - DurableObject: Durable Object classes + * - Workflow: Workflow classes + * + * For ExportedHandler (plain objects), this will return false for all types. + * + * @param value - The value to check (typically a class constructor) + * @param className - The Cloudflare base class name to check against + * @returns true if the value is a class that extends the specified Cloudflare class + * + * @example + * ```ts + * isCloudflareClass(MyWorker, 'WorkerEntrypoint') // true if MyWorker extends WorkerEntrypoint + * isCloudflareClass(MyDO, 'DurableObject') // true if MyDO extends DurableObject + * ``` + */ +export function isCloudflareClass(value: unknown, className: 'WorkerEntrypoint'): value is WorkerEntrypointConstructor; +export function isCloudflareClass( + value: unknown, + className: 'DurableObject', +): value is new (...args: unknown[]) => DurableObject; +export function isCloudflareClass( + value: unknown, + className: 'WorkflowEntrypoint', +): value is new (...args: unknown[]) => WorkflowEntrypoint; +export function isCloudflareClass(value: unknown, className: CloudflareClassName): boolean { + if (!value || typeof value !== 'function') { + return false; + } + + if (value.name === className) { + return false; + } + + let proto: object | null = value.prototype; + + while (proto) { + const ctor = (proto as { constructor?: { name?: string } }).constructor; + const constructorName = ctor?.name; + + if (constructorName === className) { + return true; + } + + proto = Object.getPrototypeOf(proto); + } + + return false; +} diff --git a/packages/cloudflare/src/withSentry.ts b/packages/cloudflare/src/withSentry.ts index 4655ab1a154d..554e5d9cbf9b 100644 --- a/packages/cloudflare/src/withSentry.ts +++ b/packages/cloudflare/src/withSentry.ts @@ -1,13 +1,18 @@ -import type { env } from 'cloudflare:workers'; +import type { env as cloudflareEnv } from 'cloudflare:workers'; import { setAsyncLocalStorageAsyncContextStrategy } from './async'; import type { CloudflareOptions } from './client'; -import { isInstrumented, markAsInstrumented } from './instrument'; +import { ensureInstrumented } from './instrument'; import { instrumentExportedHandlerEmail } from './instrumentations/worker/instrumentEmail'; import { instrumentExportedHandlerFetch } from './instrumentations/worker/instrumentFetch'; import { instrumentExportedHandlerQueue } from './instrumentations/worker/instrumentQueue'; import { instrumentExportedHandlerScheduled } from './instrumentations/worker/instrumentScheduled'; import { instrumentExportedHandlerTail } from './instrumentations/worker/instrumentTail'; import { getHonoIntegration } from './integrations/hono'; +import { isCloudflareClass } from './utils/isCloudflareClass'; +import { + instrumentWorkerEntrypoint, + type WorkerEntrypointConstructor, +} from './instrumentations/instrumentWorkerEntrypoint'; /** * Wrapper for Cloudflare handlers. @@ -20,25 +25,37 @@ import { getHonoIntegration } from './integrations/hono'; * @param handler {ExportedHandler} The handler to wrap. * @returns The wrapped handler. */ +// TODO(v11): The generic types need to be rewritten to following to improve type safety: +// T extends ExportedHandler | WorkerEntrypointConstructor export function withSentry< - Env = typeof env, + Env = typeof cloudflareEnv, QueueHandlerMessage = unknown, CfHostMetadata = unknown, - T extends ExportedHandler = ExportedHandler< + T extends ExportedHandler | WorkerEntrypointConstructor = ExportedHandler< Env, QueueHandlerMessage, CfHostMetadata >, >(optionsCallback: (env: Env) => CloudflareOptions | undefined, handler: T): T { + if (isCloudflareClass(handler, 'WorkerEntrypoint')) { + // oxlint-disable-next-line typescript/no-explicit-any + return instrumentWorkerEntrypoint(optionsCallback as any, handler); + } + setAsyncLocalStorageAsyncContextStrategy(); try { - instrumentExportedHandlerFetch(handler, optionsCallback); + // oxlint-disable-next-line typescript/no-explicit-any + instrumentExportedHandlerFetch(handler, optionsCallback as any); instrumentHonoErrorHandler(handler); - instrumentExportedHandlerScheduled(handler, optionsCallback); - instrumentExportedHandlerEmail(handler, optionsCallback); - instrumentExportedHandlerQueue(handler, optionsCallback); - instrumentExportedHandlerTail(handler, optionsCallback); + // oxlint-disable-next-line typescript/no-explicit-any + instrumentExportedHandlerScheduled(handler, optionsCallback as any); + // oxlint-disable-next-line typescript/no-explicit-any + instrumentExportedHandlerEmail(handler, optionsCallback as any); + // oxlint-disable-next-line typescript/no-explicit-any + instrumentExportedHandlerQueue(handler, optionsCallback as any); + // oxlint-disable-next-line typescript/no-explicit-any + instrumentExportedHandlerTail(handler, optionsCallback as any); // This is here because Miniflare sometimes cannot get instrumented } catch { // Do not console anything here, we don't want to spam the console with errors @@ -49,22 +66,19 @@ export function withSentry< // eslint-disable-next-line @typescript-eslint/no-explicit-any function instrumentHonoErrorHandler>(handler: T): void { - if ( - 'onError' in handler && - 'errorHandler' in handler && - typeof handler.errorHandler === 'function' && - !isInstrumented(handler.errorHandler) - ) { - handler.errorHandler = new Proxy(handler.errorHandler, { - apply(target, thisArg, args) { - const [err, context] = args; - - getHonoIntegration()?.handleHonoException(err, context); + if ('onError' in handler && 'errorHandler' in handler && typeof handler.errorHandler === 'function') { + handler.errorHandler = ensureInstrumented( + handler.errorHandler, + original => + new Proxy(original, { + apply(target, thisArg, args) { + const [err, context] = args; - return Reflect.apply(target, thisArg, args); - }, - }); + getHonoIntegration()?.handleHonoException(err, context); - markAsInstrumented(handler.errorHandler); + return Reflect.apply(target, thisArg, args); + }, + }), + ); } } diff --git a/packages/cloudflare/src/wrapMethodWithSentry.ts b/packages/cloudflare/src/wrapMethodWithSentry.ts index 2361ee5b718d..4080017526a2 100644 --- a/packages/cloudflare/src/wrapMethodWithSentry.ts +++ b/packages/cloudflare/src/wrapMethodWithSentry.ts @@ -12,7 +12,7 @@ import { } from '@sentry/core'; import type { CloudflareOptions } from './client'; import { flushAndDispose } from './flush'; -import { isInstrumented, markAsInstrumented } from './instrument'; +import { ensureInstrumented } from './instrument'; import { init } from './sdk'; /** Extended DurableObjectState with originalStorage exposed by instrumentContext */ @@ -46,126 +46,126 @@ export function wrapMethodWithSentry( callback?: (...args: Parameters) => void, noMark?: true, ): T { - if (isInstrumented(handler)) { - return handler; - } - - if (!noMark) { - markAsInstrumented(handler); - } - - return new Proxy(handler, { - apply(target, thisArg, args: Parameters) { - const currentClient = getClient(); - // if a client is already set, use withScope, otherwise use withIsolationScope - const sentryWithScope = currentClient ? withScope : withIsolationScope; - - const wrappedFunction = (scope: Scope): unknown => { - // In certain situations, the passed context can become undefined. - // For example, for Astro while prerendering pages at build time. - // see: https://github.com/getsentry/sentry-javascript/issues/13217 - const context = wrapperOptions.context as InstrumentedDurableObjectState | undefined; - - const waitUntil = context?.waitUntil?.bind?.(context); - - let currentClient = scope.getClient(); - // Check if client exists AND is still usable (transport not disposed) - // This handles the case where a previous handler disposed the client - // but the scope still holds a reference to it (e.g., alarm handlers in Durable Objects) - if (!currentClient?.getTransport()) { - const client = init({ ...wrapperOptions.options, ctx: context as unknown as ExecutionContext | undefined }); - scope.setClient(client); - currentClient = client; - } + return ensureInstrumented( + handler, + original => + new Proxy(original, { + apply(target, thisArg, args: Parameters) { + const currentClient = getClient(); + // if a client is already set, use withScope, otherwise use withIsolationScope + const sentryWithScope = currentClient ? withScope : withIsolationScope; + + const wrappedFunction = (scope: Scope): unknown => { + // In certain situations, the passed context can become undefined. + // For example, for Astro while prerendering pages at build time. + // see: https://github.com/getsentry/sentry-javascript/issues/13217 + const context = wrapperOptions.context as InstrumentedDurableObjectState | undefined; + + const waitUntil = context?.waitUntil?.bind?.(context); + + let currentClient = scope.getClient(); + // Check if client exists AND is still usable (transport not disposed) + // This handles the case where a previous handler disposed the client + // but the scope still holds a reference to it (e.g., alarm handlers in Durable Objects) + if (!currentClient?.getTransport()) { + const client = init({ + ...wrapperOptions.options, + ctx: context as unknown as ExecutionContext | undefined, + }); + scope.setClient(client); + currentClient = client; + } - const clientToDispose = currentClient; + const clientToDispose = currentClient; - if (!wrapperOptions.spanName) { - try { - if (callback) { - callback(...args); - } - const result = Reflect.apply(target, thisArg, args); + if (!wrapperOptions.spanName) { + try { + if (callback) { + callback(...args); + } + const result = Reflect.apply(target, thisArg, args); - if (isThenable(result)) { - return result.then( - (res: unknown) => { - waitUntil?.(flushAndDispose(clientToDispose)); - return res; - }, - (e: unknown) => { - captureException(e, { - mechanism: { - type: 'auto.faas.cloudflare.durable_object', - handled: false, + if (isThenable(result)) { + return result.then( + (res: unknown) => { + waitUntil?.(flushAndDispose(clientToDispose)); + return res; }, - }); + (e: unknown) => { + captureException(e, { + mechanism: { + type: 'auto.faas.cloudflare.durable_object', + handled: false, + }, + }); + waitUntil?.(flushAndDispose(clientToDispose)); + throw e; + }, + ); + } else { waitUntil?.(flushAndDispose(clientToDispose)); - throw e; - }, - ); - } else { - waitUntil?.(flushAndDispose(clientToDispose)); - return result; - } - } catch (e) { - captureException(e, { - mechanism: { - type: 'auto.faas.cloudflare.durable_object', - handled: false, - }, - }); - waitUntil?.(flushAndDispose(clientToDispose)); - throw e; - } - } - - const attributes = wrapperOptions.spanOp - ? { - [SEMANTIC_ATTRIBUTE_SENTRY_OP]: wrapperOptions.spanOp, - [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.durable_object', + return result; + } + } catch (e) { + captureException(e, { + mechanism: { + type: 'auto.faas.cloudflare.durable_object', + handled: false, + }, + }); + waitUntil?.(flushAndDispose(clientToDispose)); + throw e; + } } - : {}; - return startSpan({ name: wrapperOptions.spanName, attributes }, () => { - try { - const result = Reflect.apply(target, thisArg, args); - - if (isThenable(result)) { - return result.then( - (res: unknown) => { - waitUntil?.(flushAndDispose(clientToDispose)); - return res; - }, - (e: unknown) => { - captureException(e, { - mechanism: { - type: 'auto.faas.cloudflare.durable_object', - handled: false, + const attributes = wrapperOptions.spanOp + ? { + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: wrapperOptions.spanOp, + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.durable_object', + } + : {}; + + return startSpan({ name: wrapperOptions.spanName, attributes }, () => { + try { + const result = Reflect.apply(target, thisArg, args); + + if (isThenable(result)) { + return result.then( + (res: unknown) => { + waitUntil?.(flushAndDispose(clientToDispose)); + return res; }, - }); + (e: unknown) => { + captureException(e, { + mechanism: { + type: 'auto.faas.cloudflare.durable_object', + handled: false, + }, + }); + waitUntil?.(flushAndDispose(clientToDispose)); + throw e; + }, + ); + } else { waitUntil?.(flushAndDispose(clientToDispose)); - throw e; - }, - ); - } else { - waitUntil?.(flushAndDispose(clientToDispose)); - return result; - } - } catch (e) { - captureException(e, { - mechanism: { - type: 'auto.faas.cloudflare.durable_object', - handled: false, - }, + return result; + } + } catch (e) { + captureException(e, { + mechanism: { + type: 'auto.faas.cloudflare.durable_object', + handled: false, + }, + }); + waitUntil?.(flushAndDispose(clientToDispose)); + throw e; + } }); - waitUntil?.(flushAndDispose(clientToDispose)); - throw e; - } - }); - }; + }; - return sentryWithScope(wrappedFunction); - }, - }); + return sentryWithScope(wrappedFunction); + }, + }), + noMark, + ); } diff --git a/packages/cloudflare/test/durableobject.test.ts b/packages/cloudflare/test/durableobject.test.ts index d665abf95c86..efce592a6cdd 100644 --- a/packages/cloudflare/test/durableobject.test.ts +++ b/packages/cloudflare/test/durableobject.test.ts @@ -2,7 +2,7 @@ import type { ExecutionContext } from '@cloudflare/workers-types'; import * as SentryCore from '@sentry/core'; import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest'; import { instrumentDurableObjectWithSentry } from '../src'; -import { isInstrumented } from '../src/instrument'; +import { getInstrumented } from '../src/instrument'; describe('instrumentDurableObjectWithSentry', () => { afterEach(() => { @@ -111,7 +111,7 @@ describe('instrumentDurableObjectWithSentry', () => { 'webSocketError', 'rpcMethod', ]) { - expect(isInstrumented((obj as any)[method_name]), `Method ${method_name} is instrumented`).toBeTruthy(); + expect(getInstrumented((obj as any)[method_name]), `Method ${method_name} is instrumented`).toBeTruthy(); } }); @@ -176,7 +176,7 @@ describe('instrumentDurableObjectWithSentry', () => { const instrumented = instrumentDurableObjectWithSentry(options, testClass as any); const obj = Reflect.construct(instrumented, []); - expect(isInstrumented(obj.prototypeMethod)).toBeFalsy(); + expect(getInstrumented(obj.prototypeMethod)).toBeFalsy(); }); it('does not instrument prototype methods when option is false', () => { @@ -189,7 +189,7 @@ describe('instrumentDurableObjectWithSentry', () => { const instrumented = instrumentDurableObjectWithSentry(options, testClass as any); const obj = Reflect.construct(instrumented, []); - expect(isInstrumented(obj.prototypeMethod)).toBeFalsy(); + expect(getInstrumented(obj.prototypeMethod)).toBeFalsy(); }); it('instruments all prototype methods when option is true', () => { @@ -205,8 +205,8 @@ describe('instrumentDurableObjectWithSentry', () => { const instrumented = instrumentDurableObjectWithSentry(options, testClass as any); const obj = Reflect.construct(instrumented, []); - expect(isInstrumented(obj.methodOne)).toBeTruthy(); - expect(isInstrumented(obj.methodTwo)).toBeTruthy(); + expect(getInstrumented(obj.methodOne)).toBeTruthy(); + expect(getInstrumented(obj.methodTwo)).toBeTruthy(); }); it('instruments only specified methods when option is array', () => { @@ -225,9 +225,9 @@ describe('instrumentDurableObjectWithSentry', () => { const instrumented = instrumentDurableObjectWithSentry(options, testClass as any); const obj = Reflect.construct(instrumented, []); - expect(isInstrumented(obj.methodOne)).toBeTruthy(); - expect(isInstrumented(obj.methodTwo)).toBeFalsy(); - expect(isInstrumented(obj.methodThree)).toBeTruthy(); + expect(getInstrumented(obj.methodOne)).toBeTruthy(); + expect(getInstrumented(obj.methodTwo)).toBeFalsy(); + expect(getInstrumented(obj.methodThree)).toBeTruthy(); }); it('still instruments instance methods regardless of prototype option', () => { @@ -245,12 +245,12 @@ describe('instrumentDurableObjectWithSentry', () => { const obj = Reflect.construct(instrumented, []); // Instance methods should still be instrumented - expect(isInstrumented(obj.propertyFunction)).toBeTruthy(); - expect(isInstrumented(obj.fetch)).toBeTruthy(); - expect(isInstrumented(obj.alarm)).toBeTruthy(); - expect(isInstrumented(obj.webSocketMessage)).toBeTruthy(); - expect(isInstrumented(obj.webSocketClose)).toBeTruthy(); - expect(isInstrumented(obj.webSocketError)).toBeTruthy(); + expect(getInstrumented(obj.propertyFunction)).toBeTruthy(); + expect(getInstrumented(obj.fetch)).toBeTruthy(); + expect(getInstrumented(obj.alarm)).toBeTruthy(); + expect(getInstrumented(obj.webSocketMessage)).toBeTruthy(); + expect(getInstrumented(obj.webSocketClose)).toBeTruthy(); + expect(getInstrumented(obj.webSocketError)).toBeTruthy(); }); }); }); diff --git a/packages/cloudflare/test/instrument.test.ts b/packages/cloudflare/test/instrument.test.ts new file mode 100644 index 000000000000..659fdeec6374 --- /dev/null +++ b/packages/cloudflare/test/instrument.test.ts @@ -0,0 +1,196 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { getInstrumented, markAsInstrumented } from '../src/instrument'; + +// Clean up the global WeakMap between tests to avoid cross-test pollution +const GLOBAL_KEY = '__SENTRY_INSTRUMENTED_MAP__' as const; + +describe('instrument', () => { + beforeEach(() => { + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete (globalThis as Record)[GLOBAL_KEY]; + }); + + afterEach(() => { + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete (globalThis as Record)[GLOBAL_KEY]; + }); + + describe('markAsInstrumented', () => { + it('marks an object with itself when no instrumented version is provided', () => { + const obj = { name: 'test' }; + markAsInstrumented(obj); + + expect(getInstrumented(obj)).toBe(obj); + }); + + it('stores original -> instrumented mapping', () => { + const original = { name: 'original' }; + const instrumented = { name: 'instrumented' }; + markAsInstrumented(original, instrumented); + + expect(getInstrumented(original)).toBe(instrumented); + }); + + it('also marks the instrumented version as instrumented', () => { + const original = { name: 'original' }; + const instrumented = { name: 'instrumented' }; + markAsInstrumented(original, instrumented); + + expect(getInstrumented(instrumented)).toBe(instrumented); + }); + + it('works with functions', () => { + const original = function () {}; + const instrumented = function () {}; + markAsInstrumented(original, instrumented); + + expect(getInstrumented(original)).toBe(instrumented); + expect(getInstrumented(instrumented)).toBe(instrumented); + }); + + it('works with arrow functions', () => { + const original = () => {}; + const instrumented = () => {}; + markAsInstrumented(original, instrumented); + + expect(getInstrumented(original)).toBe(instrumented); + }); + + it('works with Proxy objects wrapping functions', () => { + const original = () => 'original'; + const proxy = new Proxy(original, { + apply(target, thisArg, args) { + return Reflect.apply(target, thisArg, args); + }, + }); + markAsInstrumented(original, proxy); + + expect(getInstrumented(original)).toBe(proxy); + }); + + it('ignores primitive values', () => { + // These should not throw + markAsInstrumented(null as unknown); + markAsInstrumented(undefined as unknown); + markAsInstrumented(42 as unknown); + markAsInstrumented('string' as unknown); + markAsInstrumented(true as unknown); + }); + }); + + describe('getInstrumented', () => { + it('returns undefined for unknown objects', () => { + expect(getInstrumented({ name: 'unknown' })).toBeUndefined(); + }); + + it('returns undefined for unknown functions', () => { + expect(getInstrumented(() => {})).toBeUndefined(); + }); + + it('returns the instrumented version for a marked original', () => { + const original = () => {}; + const instrumented = () => {}; + markAsInstrumented(original, instrumented); + + expect(getInstrumented(original)).toBe(instrumented); + }); + + it('returns itself for the instrumented version', () => { + const original = () => {}; + const instrumented = () => {}; + markAsInstrumented(original, instrumented); + + expect(getInstrumented(instrumented)).toBe(instrumented); + }); + + it('returns the object itself when marked without instrumented version', () => { + const obj = { name: 'test' }; + markAsInstrumented(obj); + expect(getInstrumented(obj)).toBe(obj); + }); + + it('returns undefined for null', () => { + expect(getInstrumented(null)).toBeUndefined(); + }); + + it('returns undefined for undefined', () => { + expect(getInstrumented(undefined)).toBeUndefined(); + }); + + it('returns undefined for primitives', () => { + expect(getInstrumented(42)).toBeUndefined(); + expect(getInstrumented('string')).toBeUndefined(); + }); + }); + + describe('WeakMap global isolation', () => { + it('uses a global WeakMap stored on globalThis', () => { + const obj = { name: 'test' }; + markAsInstrumented(obj); + + // The global key should exist + expect((globalThis as Record)[GLOBAL_KEY]).toBeDefined(); + expect((globalThis as Record)[GLOBAL_KEY]).toBeInstanceOf(WeakMap); + }); + + it('reuses the same WeakMap across calls', () => { + const obj1 = { name: 'test1' }; + const obj2 = { name: 'test2' }; + markAsInstrumented(obj1); + markAsInstrumented(obj2); + + expect(getInstrumented(obj1)).toBeDefined(); + expect(getInstrumented(obj2)).toBeDefined(); + }); + + it('uses existing WeakMap if already on globalThis', () => { + const existingMap = new WeakMap(); + const obj = { name: 'pre-existing' }; + existingMap.set(obj, obj); + (globalThis as Record)[GLOBAL_KEY] = existingMap; + + // Should find the pre-existing entry + expect(getInstrumented(obj)).toBeDefined(); + + // Adding new entries should use the same map + const newObj = { name: 'new' }; + markAsInstrumented(newObj); + expect(existingMap.has(newObj)).toBe(true); + }); + }); + + describe('double instrumentation prevention', () => { + it('getInstrumented returns cached proxy when original is re-encountered', () => { + const original = () => 'original'; + const proxy = new Proxy(original, { + apply(target, thisArg, args) { + return Reflect.apply(target, thisArg, args); + }, + }); + markAsInstrumented(original, proxy); + + // Simulates a second request encountering the same original + const cached = getInstrumented(original); + expect(cached).toBe(proxy); + + // The proxy should also be recognized + const cachedProxy = getInstrumented(proxy); + expect(cachedProxy).toBe(proxy); + }); + + it('prevents double-wrapping by recognizing instrumented functions', () => { + const original = () => 'original'; + const proxy = new Proxy(original, { + apply(target, thisArg, args) { + return Reflect.apply(target, thisArg, args); + }, + }); + markAsInstrumented(original, proxy); + + // Simulating the simplified handler pattern: + // if getInstrumented returns something, use it; otherwise create new proxy + const existing = getInstrumented(proxy); + expect(existing).toBe(proxy); + }); + }); +}); diff --git a/packages/cloudflare/test/instrumentations/instrumentWorkerEntrypoint.test.ts b/packages/cloudflare/test/instrumentations/instrumentWorkerEntrypoint.test.ts new file mode 100644 index 000000000000..a6a3e6a64cfd --- /dev/null +++ b/packages/cloudflare/test/instrumentations/instrumentWorkerEntrypoint.test.ts @@ -0,0 +1,284 @@ +import type { ExecutionContext } from '@cloudflare/workers-types'; +import * as SentryCore from '@sentry/core'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { getInstrumented } from '../../src/instrument'; +import { + instrumentWorkerEntrypoint, + type WorkerEntrypointConstructor, +} from '../../src/instrumentations/instrumentWorkerEntrypoint'; + +function createMockExecutionContext(): ExecutionContext { + return { + waitUntil: vi.fn(), + passThroughOnException: vi.fn(), + props: {}, + }; +} + +class WorkerEntrypoint {} + +describe('instrumentWorkerEntrypoint', () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('Generic functionality', () => { + const options = vi.fn().mockReturnValue({}); + const instrumented = instrumentWorkerEntrypoint(options, vi.fn()); + expect(instrumented).toBeTypeOf('function'); + expect(() => Reflect.construct(instrumented, [])).not.toThrow(); + expect(options).toHaveBeenCalledOnce(); + }); + + it('Instruments sync prototype methods and defines implementation in the object', () => { + const TestClass = class extends WorkerEntrypoint { + method() { + return 'sync-result'; + } + }; + const obj = Reflect.construct( + instrumentWorkerEntrypoint(vi.fn().mockReturnValue({}), TestClass as unknown as WorkerEntrypointConstructor), + [], + ); + expect(obj.method).toBe(obj.method); + + const result = obj.method(); + expect(result).not.toBeInstanceOf(Promise); + expect(result).toEqual('sync-result'); + }); + + it('Instruments async prototype methods and returns a promise', async () => { + const TestClass = class extends WorkerEntrypoint { + async asyncMethod() { + return 'async-result'; + } + }; + const obj = Reflect.construct( + instrumentWorkerEntrypoint(vi.fn().mockReturnValue({}), TestClass as unknown as WorkerEntrypointConstructor), + [], + ); + expect(obj.asyncMethod).toBe(obj.asyncMethod); + + const result = obj.asyncMethod(); + expect(result).toBeInstanceOf(Promise); + expect(await result).toBe('async-result'); + }); + + it('Calls options callback per instance with env', () => { + const mockContext = createMockExecutionContext(); + const mockEnv1: Record = { SENTRY_DSN: 'dsn1' }; + const mockEnv2: Record = { SENTRY_DSN: 'dsn2' }; + const options = vi.fn().mockReturnValueOnce({ dsn: 'dsn1' }).mockReturnValueOnce({ dsn: 'dsn2' }); + const TestClass = class extends WorkerEntrypoint { + fetch() { + return new Response('ok'); + } + }; + const instrumented = instrumentWorkerEntrypoint(options, TestClass as unknown as WorkerEntrypointConstructor); + + Reflect.construct(instrumented, [mockContext, mockEnv1]); + Reflect.construct(instrumented, [mockContext, mockEnv2]); + + expect(options).toHaveBeenCalledWith(mockEnv1); + expect(options).toHaveBeenCalledWith(mockEnv2); + }); + + it('Instruments fetch, scheduled, queue, tail handler methods', async () => { + const TestClass = class extends WorkerEntrypoint { + fetch(_request: Request) { + return new Response('ok'); + } + scheduled() {} + queue() {} + tail() {} + }; + const mockContext = createMockExecutionContext(); + const instrumented = instrumentWorkerEntrypoint( + vi.fn().mockReturnValue({}), + TestClass as unknown as WorkerEntrypointConstructor, + ); + const obj = Reflect.construct(instrumented, [mockContext, {}]); + + expect(typeof obj.fetch).toBe('function'); + expect(typeof obj.scheduled).toBe('function'); + expect(typeof obj.queue).toBe('function'); + expect(typeof obj.tail).toBe('function'); + + const response = await obj.fetch(new Request('https://example.com')); + expect(response).toBeInstanceOf(Response); + expect(await response.text()).toBe('ok'); + }); + + it('Does not instrument ctx and env properties', () => { + const mockContext = createMockExecutionContext(); + const mockEnv = {}; + const TestClass = class extends WorkerEntrypoint { + ctx = {}; + env = {}; + }; + const instrumented = instrumentWorkerEntrypoint( + vi.fn().mockReturnValue({}), + TestClass as unknown as WorkerEntrypointConstructor, + ); + const obj = Reflect.construct(instrumented, [mockContext, mockEnv]); + + expect(getInstrumented(obj.ctx)).toBeFalsy(); + expect(getInstrumented(obj.env)).toBeFalsy(); + }); + + it('Overrides obj.ctx with instrumented context so user code using this.ctx.waitUntil works', async () => { + const mockContext = createMockExecutionContext(); + const mockEnv = {}; + const TestClass = class extends WorkerEntrypoint { + ctx = createMockExecutionContext(); + env = {}; + fetch() { + this.ctx.waitUntil(Promise.resolve()); + return new Response('ok'); + } + }; + const instrumented = instrumentWorkerEntrypoint( + vi.fn().mockReturnValue({}), + TestClass as unknown as WorkerEntrypointConstructor, + ); + const obj = Reflect.construct(instrumented, [mockContext, mockEnv]); + + expect(obj.ctx).not.toBe(mockContext); + expect(typeof obj.ctx.waitUntil).toBe('function'); + const response = await obj.fetch(new Request('https://example.com')); + expect(response).toBeInstanceOf(Response); + expect(mockContext.waitUntil).toHaveBeenCalled(); + }); + + it('Uses instrumentContext so context passed to handlers has overridable waitUntil', () => { + const rawCtx = createMockExecutionContext(); + const TestClass = class extends WorkerEntrypoint { + ctx = {}; + env = {}; + fetch() { + return new Response('ok'); + } + }; + const instrumented = instrumentWorkerEntrypoint( + vi.fn().mockReturnValue({}), + TestClass as unknown as WorkerEntrypointConstructor, + ); + const obj = Reflect.construct(instrumented, [rawCtx, {}]); + + expect(obj.ctx).toBeDefined(); + expect(obj.ctx).not.toBe(rawCtx); + expect(obj.__SENTRY_CONTEXT__).toBeDefined(); + expect(obj.__SENTRY_CONTEXT__).not.toBe(rawCtx); + expect(obj.__SENTRY_CONTEXT__).toBe(obj.ctx); + }); + + it('Calls setAsyncLocalStorageAsyncContextStrategy outside Proxy (at instrumentation time), not inside construct', async () => { + const asyncModule = await import('../../src/async'); + const setStrategy = vi.spyOn(asyncModule, 'setAsyncLocalStorageAsyncContextStrategy'); + const mockContext = createMockExecutionContext(); + const TestClass = class extends WorkerEntrypoint { + fetch() { + return new Response('ok'); + } + }; + + const instrumented = instrumentWorkerEntrypoint( + vi.fn().mockReturnValue({}), + TestClass as unknown as WorkerEntrypointConstructor, + ); + expect(setStrategy).toHaveBeenCalledTimes(1); + + Reflect.construct(instrumented, [mockContext, {}]); + Reflect.construct(instrumented, [mockContext, {}]); + expect(setStrategy).toHaveBeenCalledTimes(1); + setStrategy.mockRestore(); + }); + + it('flush performs after all waitUntil promises are finished', async () => { + let testClientFlushCount = 0; + let testClient: SentryCore.Client | undefined; + + vi.spyOn(SentryCore.Client.prototype, 'flush').mockImplementation(function (this: SentryCore.Client) { + if (this === testClient) { + testClientFlushCount++; + } + return Promise.resolve(true); + }); + + let resolveWaitUntil!: () => void; + const deferred = new Promise(res => { + resolveWaitUntil = res; + }); + + const waitUntil = vi.fn(); + const TestClass = vi.fn((context: ExecutionContext) => ({ + fetch: () => { + context.waitUntil(deferred); + return new Response('test'); + }, + })); + const instrumented = instrumentWorkerEntrypoint(vi.fn(), TestClass as unknown as WorkerEntrypointConstructor); + const context = { ...createMockExecutionContext(), waitUntil }; + const worker = Reflect.construct(instrumented, [context, {}]); + + const responsePromise = worker.fetch(new Request('https://example.com')); + testClient = SentryCore.getClient(); + + const response = await responsePromise; + await response.text(); + + expect(waitUntil).toHaveBeenCalled(); + + resolveWaitUntil(); + await Promise.all(waitUntil.mock.calls.map(([p]) => p)); + + expect(testClientFlushCount).toBe(1); + }); + + describe('instrumentPrototypeMethods option', () => { + it('does not instrument prototype methods when option is not set', () => { + const TestClass = class Hello extends WorkerEntrypoint { + prototypeMethod() { + return 'prototype-result'; + } + }; + const options = vi.fn().mockReturnValue({}); + const instrumented = instrumentWorkerEntrypoint(options, TestClass as unknown as WorkerEntrypointConstructor); + const obj = Reflect.construct(instrumented, []); + + expect(getInstrumented(obj.prototypeMethod)).toBeFalsy(); + }); + + it('does not instrument prototype methods when option is false', () => { + const TestClass = class extends WorkerEntrypoint { + prototypeMethod() { + return 'prototype-result'; + } + }; + const options = vi.fn().mockReturnValue({ instrumentPrototypeMethods: false }); + const instrumented = instrumentWorkerEntrypoint(options, TestClass as unknown as WorkerEntrypointConstructor); + const obj = Reflect.construct(instrumented, []); + + expect(getInstrumented(obj.prototypeMethod)).toBeFalsy(); + }); + + it('does not instrument prototype methods when option is true (instrumentWorkerEntrypoint does not support instrumentPrototypeMethods)', () => { + const TestClass = class extends WorkerEntrypoint { + methodOne() { + return 'one'; + } + methodTwo() { + return 'two'; + } + }; + const options = vi.fn().mockReturnValue({ instrumentPrototypeMethods: true }); + const instrumented = instrumentWorkerEntrypoint(options, TestClass as unknown as WorkerEntrypointConstructor); + const obj = Reflect.construct(instrumented, [createMockExecutionContext(), {}]); + + expect(getInstrumented(obj.methodOne)).toBeFalsy(); + expect(getInstrumented(obj.methodTwo)).toBeFalsy(); + expect(obj.methodOne()).toBe('one'); + expect(obj.methodTwo()).toBe('two'); + }); + }); +}); diff --git a/packages/cloudflare/test/instrumentations/worker/instrumentEmail.test.ts b/packages/cloudflare/test/instrumentations/worker/instrumentEmail.test.ts index 5d2f01b428df..5deb79d7d1c1 100644 --- a/packages/cloudflare/test/instrumentations/worker/instrumentEmail.test.ts +++ b/packages/cloudflare/test/instrumentations/worker/instrumentEmail.test.ts @@ -46,6 +46,23 @@ describe('instrumentEmail', () => { vi.clearAllMocks(); }); + test('does not double-wrap when withSentry is called twice', async () => { + const originalEmail = vi.fn(); + const handler = { + email: originalEmail, + } satisfies ExportedHandler; + + const optionsCallback = vi.fn().mockReturnValue({ dsn: MOCK_ENV.SENTRY_DSN }); + + const wrappedHandler1 = withSentry(optionsCallback, handler); + const firstEmail = wrappedHandler1.email; + + const wrappedHandler2 = withSentry(optionsCallback, handler); + const secondEmail = wrappedHandler2.email; + + expect(firstEmail).toBe(secondEmail); + }); + test('executes options callback with env', async () => { const handler = { email(_message, _env, _context) { diff --git a/packages/cloudflare/test/instrumentations/worker/instrumentFetch.test.ts b/packages/cloudflare/test/instrumentations/worker/instrumentFetch.test.ts index 1ae4b965d238..5486addb405c 100644 --- a/packages/cloudflare/test/instrumentations/worker/instrumentFetch.test.ts +++ b/packages/cloudflare/test/instrumentations/worker/instrumentFetch.test.ts @@ -32,6 +32,25 @@ describe('instrumentFetch', () => { vi.clearAllMocks(); }); + test('does not double-wrap when withSentry is called twice', async () => { + const originalFetch = vi.fn().mockReturnValue(new Response('test')); + const handler = { + fetch: originalFetch, + } satisfies ExportedHandler; + + const optionsCallback = vi.fn().mockReturnValue({ dsn: MOCK_ENV.SENTRY_DSN }); + + // First call instruments the handler + const wrappedHandler1 = withSentry(optionsCallback, handler); + const firstFetch = wrappedHandler1.fetch; + + // Second call should reuse the instrumented version + const wrappedHandler2 = withSentry(optionsCallback, handler); + const secondFetch = wrappedHandler2.fetch; + + expect(firstFetch).toBe(secondFetch); + }); + test('executes options callback with env', async () => { const handler = { fetch(_request, _env, _context) { diff --git a/packages/cloudflare/test/instrumentations/worker/instrumentQueue.test.ts b/packages/cloudflare/test/instrumentations/worker/instrumentQueue.test.ts index a38a8f24d79e..6930ff7180df 100644 --- a/packages/cloudflare/test/instrumentations/worker/instrumentQueue.test.ts +++ b/packages/cloudflare/test/instrumentations/worker/instrumentQueue.test.ts @@ -59,6 +59,23 @@ describe('instrumentQueue', () => { vi.clearAllMocks(); }); + test('does not double-wrap when withSentry is called twice', async () => { + const originalQueue = vi.fn(); + const handler = { + queue: originalQueue, + } satisfies ExportedHandler; + + const optionsCallback = vi.fn().mockReturnValue({ dsn: MOCK_ENV.SENTRY_DSN }); + + const wrappedHandler1 = withSentry(optionsCallback, handler); + const firstQueue = wrappedHandler1.queue; + + const wrappedHandler2 = withSentry(optionsCallback, handler); + const secondQueue = wrappedHandler2.queue; + + expect(firstQueue).toBe(secondQueue); + }); + test('executes options callback with env', async () => { const handler = { queue(_batch, _env, _context) { diff --git a/packages/cloudflare/test/instrumentations/worker/instrumentScheduled.test.ts b/packages/cloudflare/test/instrumentations/worker/instrumentScheduled.test.ts index 64833d70ddfb..6b0107a68aef 100644 --- a/packages/cloudflare/test/instrumentations/worker/instrumentScheduled.test.ts +++ b/packages/cloudflare/test/instrumentations/worker/instrumentScheduled.test.ts @@ -41,6 +41,23 @@ describe('instrumentScheduled', () => { vi.clearAllMocks(); }); + test('does not double-wrap when withSentry is called twice', async () => { + const originalScheduled = vi.fn(); + const handler = { + scheduled: originalScheduled, + } satisfies ExportedHandler; + + const optionsCallback = vi.fn().mockReturnValue({ dsn: MOCK_ENV.SENTRY_DSN }); + + const wrappedHandler1 = withSentry(optionsCallback, handler); + const firstScheduled = wrappedHandler1.scheduled; + + const wrappedHandler2 = withSentry(optionsCallback, handler); + const secondScheduled = wrappedHandler2.scheduled; + + expect(firstScheduled).toBe(secondScheduled); + }); + test('executes options callback with env', async () => { const handler = { scheduled(_controller, _env, _context) { diff --git a/packages/cloudflare/test/instrumentations/worker/instrumentTail.test.ts b/packages/cloudflare/test/instrumentations/worker/instrumentTail.test.ts index f85507e2c734..4f47dc3c62c7 100644 --- a/packages/cloudflare/test/instrumentations/worker/instrumentTail.test.ts +++ b/packages/cloudflare/test/instrumentations/worker/instrumentTail.test.ts @@ -60,6 +60,23 @@ describe('instrumentTail', () => { vi.clearAllMocks(); }); + test('does not double-wrap when withSentry is called twice', async () => { + const originalTail = vi.fn(); + const handler = { + tail: originalTail, + } satisfies ExportedHandler; + + const optionsCallback = vi.fn().mockReturnValue({ dsn: MOCK_ENV.SENTRY_DSN }); + + const wrappedHandler1 = withSentry(optionsCallback, handler); + const firstTail = wrappedHandler1.tail; + + const wrappedHandler2 = withSentry(optionsCallback, handler); + const secondTail = wrappedHandler2.tail; + + expect(firstTail).toBe(secondTail); + }); + test('executes options callback with env', async () => { const handler = { tail(_event, _env, _context) { diff --git a/packages/cloudflare/test/utils/isCloudflareClass.test.ts b/packages/cloudflare/test/utils/isCloudflareClass.test.ts new file mode 100644 index 000000000000..4e09765a5742 --- /dev/null +++ b/packages/cloudflare/test/utils/isCloudflareClass.test.ts @@ -0,0 +1,110 @@ +import { describe, expect, it } from 'vitest'; +import { isCloudflareClass } from '../../src/utils/isCloudflareClass'; + +class WorkerEntrypoint {} +class DurableObject {} +class WorkflowEntrypoint {} + +describe('isCloudflareClass', () => { + describe('WorkerEntrypoint', () => { + it('returns true for a class that directly extends WorkerEntrypoint', () => { + class MyWorker extends WorkerEntrypoint {} + expect(isCloudflareClass(MyWorker, 'WorkerEntrypoint')).toBe(true); + }); + + it('returns true for a class that indirectly extends WorkerEntrypoint', () => { + class BaseWorker extends WorkerEntrypoint {} + class MyWorker extends BaseWorker {} + expect(isCloudflareClass(MyWorker, 'WorkerEntrypoint')).toBe(true); + }); + + it('returns false for a plain class that does not extend WorkerEntrypoint', () => { + class PlainClass {} + expect(isCloudflareClass(PlainClass, 'WorkerEntrypoint')).toBe(false); + }); + + it('returns false for a plain object (ExportedHandler style)', () => { + const handler = { + fetch() { + return new Response('Hello'); + }, + }; + expect(isCloudflareClass(handler, 'WorkerEntrypoint')).toBe(false); + }); + + it('returns false for WorkerEntrypoint itself (not a subclass)', () => { + expect(isCloudflareClass(WorkerEntrypoint, 'WorkerEntrypoint')).toBe(false); + }); + + it('returns true for deeply nested inheritance', () => { + class Level1 extends WorkerEntrypoint {} + class Level2 extends Level1 {} + class Level3 extends Level2 {} + expect(isCloudflareClass(Level3, 'WorkerEntrypoint')).toBe(true); + }); + + it('returns false for a class that extends DurableObject', () => { + class MyDurableObject extends DurableObject {} + expect(isCloudflareClass(MyDurableObject, 'WorkerEntrypoint')).toBe(false); + }); + }); + + describe('DurableObject', () => { + it('returns true for a class that directly extends DurableObject', () => { + class MyDO extends DurableObject {} + expect(isCloudflareClass(MyDO, 'DurableObject')).toBe(true); + }); + + it('returns true for a class that indirectly extends DurableObject', () => { + class BaseDO extends DurableObject {} + class MyDO extends BaseDO {} + expect(isCloudflareClass(MyDO, 'DurableObject')).toBe(true); + }); + + it('returns false for DurableObject itself', () => { + expect(isCloudflareClass(DurableObject, 'DurableObject')).toBe(false); + }); + + it('returns false for a class that extends WorkerEntrypoint', () => { + class MyWorker extends WorkerEntrypoint {} + expect(isCloudflareClass(MyWorker, 'DurableObject')).toBe(false); + }); + }); + + describe('WorkflowEntrypoint', () => { + it('returns true for a class that directly extends WorkflowEntrypoint', () => { + class MyWorkflow extends WorkflowEntrypoint {} + expect(isCloudflareClass(MyWorkflow, 'WorkflowEntrypoint')).toBe(true); + }); + + it('returns false for WorkflowEntrypoint itself', () => { + expect(isCloudflareClass(WorkflowEntrypoint, 'WorkflowEntrypoint')).toBe(false); + }); + + it('returns false for a class that extends WorkerEntrypoint', () => { + class MyWorker extends WorkerEntrypoint {} + expect(isCloudflareClass(MyWorker, 'WorkflowEntrypoint')).toBe(false); + }); + }); + + describe('edge cases', () => { + it('returns false for null', () => { + expect(isCloudflareClass(null, 'WorkerEntrypoint')).toBe(false); + }); + + it('returns false for undefined', () => { + expect(isCloudflareClass(undefined, 'WorkerEntrypoint')).toBe(false); + }); + + it('returns false for a function that is not a class', () => { + function regularFunction() {} + expect(isCloudflareClass(regularFunction, 'WorkerEntrypoint')).toBe(false); + }); + + it('returns false for primitive values', () => { + expect(isCloudflareClass(42, 'WorkerEntrypoint')).toBe(false); + expect(isCloudflareClass('string', 'WorkerEntrypoint')).toBe(false); + expect(isCloudflareClass(true, 'WorkerEntrypoint')).toBe(false); + }); + }); +}); diff --git a/packages/cloudflare/test/withSentry.test.ts b/packages/cloudflare/test/withSentry.test.ts index 95f312c9ec54..c4e1ed789d9f 100644 --- a/packages/cloudflare/test/withSentry.test.ts +++ b/packages/cloudflare/test/withSentry.test.ts @@ -102,5 +102,25 @@ describe('withSentry', () => { honoApp.errorHandler?.(error); expect(captureExceptionSpy).not.toHaveBeenCalled(); }); + + test('does not double-wrap errorHandler when withSentry is called twice', async () => { + const honoApp: HonoLikeApp = { + fetch(_request, _env, _context) { + return new Response('test'); + }, + onError() {}, + errorHandler(err: Error) { + return new Response(`Error: ${err.message}`, { status: 500 }); + }, + }; + + withSentry(env => ({ dsn: env.SENTRY_DSN }), honoApp); + const firstErrorHandler = honoApp.errorHandler; + + withSentry(env => ({ dsn: env.SENTRY_DSN }), honoApp); + const secondErrorHandler = honoApp.errorHandler; + + expect(firstErrorHandler).toBe(secondErrorHandler); + }); }); }); diff --git a/packages/cloudflare/test/wrapMethodWithSentry.test.ts b/packages/cloudflare/test/wrapMethodWithSentry.test.ts index 6c530da521c5..fdd3475d24c4 100644 --- a/packages/cloudflare/test/wrapMethodWithSentry.test.ts +++ b/packages/cloudflare/test/wrapMethodWithSentry.test.ts @@ -1,6 +1,6 @@ import * as sentryCore from '@sentry/core'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { isInstrumented } from '../src/instrument'; +import { getInstrumented } from '../src/instrument'; import * as sdk from '../src/sdk'; import { wrapMethodWithSentry } from '../src/wrapMethodWithSentry'; @@ -115,11 +115,11 @@ describe('wrapMethodWithSentry', () => { context: createMockContext(), }; - expect(isInstrumented(handler)).toBeUndefined(); + expect(getInstrumented(handler)).toBe(undefined); wrapMethodWithSentry(options, handler); - expect(isInstrumented(handler)).toBe(true); + expect(getInstrumented(handler)).toBeDefined(); }); it('does not re-wrap already instrumented handler', () => { @@ -134,6 +134,7 @@ describe('wrapMethodWithSentry', () => { // Should return the same wrapped function expect(wrapped2).toBe(wrapped1); + expect(getInstrumented(handler)).toBe(wrapped1); }); it('does not mark handler when noMark is true', () => { @@ -145,7 +146,7 @@ describe('wrapMethodWithSentry', () => { wrapMethodWithSentry(options, handler, undefined, true); - expect(isInstrumented(handler)).toBeFalsy(); + expect(getInstrumented(handler)).toBeUndefined(); }); }); diff --git a/packages/core/.oxlintrc.json b/packages/core/.oxlintrc.json index 3fd23c75834a..05b86efa950b 100644 --- a/packages/core/.oxlintrc.json +++ b/packages/core/.oxlintrc.json @@ -1,6 +1,12 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], + "jsPlugins": [ + { + "name": "sdk", + "specifier": "@sentry-internal/eslint-plugin-sdk" + } + ], "rules": { "sdk/no-unsafe-random-apis": "error" }, diff --git a/packages/core/src/attributes.ts b/packages/core/src/attributes.ts index d3255d76b0e9..1f4a6638f577 100644 --- a/packages/core/src/attributes.ts +++ b/packages/core/src/attributes.ts @@ -1,4 +1,6 @@ import type { DurationUnit, FractionUnit, InformationUnit } from './types-hoist/measurement'; +import type { Primitive } from './types-hoist/misc'; +import { isPrimitive } from './utils/is'; export type RawAttributes = T & ValidatedAttributes; // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -127,6 +129,46 @@ export function serializeAttributes( return serializedAttributes; } +/** + * Estimates the serialized byte size of {@link Attributes}, + * with a couple of heuristics for performance. + */ +export function estimateTypedAttributesSizeInBytes(attributes: Attributes | undefined): number { + if (!attributes) { + return 0; + } + let weight = 0; + for (const [key, attr] of Object.entries(attributes)) { + weight += key.length * 2; + weight += attr.type.length * 2; + weight += (attr.unit?.length ?? 0) * 2; + const val = attr.value; + + if (Array.isArray(val)) { + // Assumption: Individual array items have the same type and roughly the same size + // probably not always true but allows us to cut down on runtime + weight += estimatePrimitiveSizeInBytes(val[0]) * val.length; + } else if (isPrimitive(val)) { + weight += estimatePrimitiveSizeInBytes(val); + } else { + // default fallback for anything else (objects) + weight += 100; + } + } + return weight; +} + +function estimatePrimitiveSizeInBytes(value: Primitive): number { + if (typeof value === 'string') { + return value.length * 2; + } else if (typeof value === 'boolean') { + return 4; + } else if (typeof value === 'number') { + return 8; + } + return 0; +} + /** * NOTE: We intentionally do not return anything for non-primitive values: * - array support will come in the future but if we stringify arrays now, diff --git a/packages/core/src/client.ts b/packages/core/src/client.ts index 8d69411aacfd..6c3ca949f38e 100644 --- a/packages/core/src/client.ts +++ b/packages/core/src/client.ts @@ -11,6 +11,7 @@ import { _INTERNAL_flushMetricsBuffer } from './metrics/internal'; import type { Scope } from './scope'; import { updateSession } from './session'; import { getDynamicSamplingContextFromScope } from './tracing/dynamicSamplingContext'; +import { isStreamedBeforeSendSpanCallback } from './tracing/spans/beforeSendSpan'; import { DEFAULT_TRANSPORT_BUFFER_SIZE } from './transports/base'; import type { Breadcrumb, BreadcrumbHint, FetchBreadcrumbHint, XhrBreadcrumbHint } from './types-hoist/breadcrumb'; import type { CheckIn, MonitorConfig } from './types-hoist/checkin'; @@ -31,7 +32,7 @@ import type { RequestEventData } from './types-hoist/request'; import type { SdkMetadata } from './types-hoist/sdkmetadata'; import type { Session, SessionAggregates } from './types-hoist/session'; import type { SeverityLevel } from './types-hoist/severity'; -import type { Span, SpanAttributes, SpanContextData, SpanJSON } from './types-hoist/span'; +import type { Span, SpanAttributes, SpanContextData, SpanJSON, StreamedSpanJSON } from './types-hoist/span'; import type { StartSpanOptions } from './types-hoist/startSpanOptions'; import type { Transport, TransportMakeRequestResponse } from './types-hoist/transport'; import { createClientReportEnvelope } from './utils/clientreport'; @@ -503,6 +504,10 @@ export abstract class Client { public addIntegration(integration: Integration): void { const isAlreadyInstalled = this._integrations[integration.name]; + if (!isAlreadyInstalled && integration.beforeSetup) { + integration.beforeSetup(this); + } + // This hook takes care of only installing if not already installed setupIntegration(this, integration, this._integrations); // Here we need to check manually to make sure to not run this multiple times @@ -613,6 +618,28 @@ export abstract class Client { */ public on(hook: 'spanEnd', callback: (span: Span) => void): () => void; + /** + * Register a callback for after a span is ended and the `spanEnd` hook has run. + * NOTE: The span cannot be mutated anymore in this callback. + */ + public on(hook: 'afterSpanEnd', callback: (immutableSegmentSpan: Readonly) => void): () => void; + + /** + * Register a callback for after a segment span is ended and the `segmentSpanEnd` hook has run. + * NOTE: The segment span cannot be mutated anymore in this callback. + */ + public on(hook: 'afterSegmentSpanEnd', callback: (immutableSegmentSpan: Readonly) => void): () => void; + + /** + * Register a callback for when a span JSON is processed, to add some data to the span JSON. + */ + public on(hook: 'processSpan', callback: (streamedSpanJSON: StreamedSpanJSON) => void): () => void; + + /** + * Register a callback for when a segment span JSON is processed, to add some data to the segment span JSON. + */ + public on(hook: 'processSegmentSpan', callback: (streamedSpanJSON: StreamedSpanJSON) => void): () => void; + /** * Register a callback for when an idle span is allowed to auto-finish. * @returns {() => void} A function that, when executed, removes the registered callback. @@ -885,6 +912,26 @@ export abstract class Client { /** Fire a hook whenever a span ends. */ public emit(hook: 'spanEnd', span: Span): void; + /** + * Fire a hook event after a span ends and the `spanEnd` hook has run. + */ + public emit(hook: 'afterSpanEnd', immutableSpan: Readonly): void; + + /** + * Fire a hook event after a segment span ends and the `spanEnd` hook has run. + */ + public emit(hook: 'afterSegmentSpanEnd', immutableSegmentSpan: Readonly): void; + + /** + * Fire a hook event when a span JSON is processed, to add some data to the span JSON. + */ + public emit(hook: 'processSpan', streamedSpanJSON: StreamedSpanJSON): void; + + /** + * Fire a hook event for when a segment span JSON is processed, to add some data to the segment span JSON. + */ + public emit(hook: 'processSegmentSpan', streamedSpanJSON: StreamedSpanJSON): void; + /** * Fire a hook indicating that an idle span is allowed to auto finish. */ @@ -1513,7 +1560,9 @@ function processBeforeSend( event: Event, hint: EventHint, ): PromiseLike | Event | null { - const { beforeSend, beforeSendTransaction, beforeSendSpan, ignoreSpans } = options; + const { beforeSend, beforeSendTransaction, ignoreSpans } = options; + const beforeSendSpan = !isStreamedBeforeSendSpanCallback(options.beforeSendSpan) && options.beforeSendSpan; + let processedEvent = event; if (isErrorEvent(processedEvent) && beforeSend) { diff --git a/packages/core/src/envelope.ts b/packages/core/src/envelope.ts index 875056890e0e..dd91d077f45c 100644 --- a/packages/core/src/envelope.ts +++ b/packages/core/src/envelope.ts @@ -1,6 +1,7 @@ import type { Client } from './client'; import { getDynamicSamplingContextFromSpan } from './tracing/dynamicSamplingContext'; import type { SentrySpan } from './tracing/sentrySpan'; +import { isStreamedBeforeSendSpanCallback } from './tracing/spans/beforeSendSpan'; import type { LegacyCSPReport } from './types-hoist/csp'; import type { DsnComponents } from './types-hoist/dsn'; import type { @@ -152,7 +153,7 @@ export function createSpanEnvelope(spans: [SentrySpan, ...SentrySpan[]], client? const convertToSpanJSON = beforeSendSpan ? (span: SentrySpan) => { const spanJson = spanToJSON(span); - const processedSpan = beforeSendSpan(spanJson); + const processedSpan = !isStreamedBeforeSendSpanCallback(beforeSendSpan) ? beforeSendSpan(spanJson) : spanJson; if (!processedSpan) { showSpanDropWarning(); diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index d155da8adf72..7d531e43b26e 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -71,6 +71,8 @@ export { prepareEvent } from './utils/prepareEvent'; export type { ExclusiveEventHintOrCaptureContext } from './utils/prepareEvent'; export { createCheckInEnvelope } from './checkin'; export { hasSpansEnabled } from './utils/hasSpansEnabled'; +export { withStreamedSpan } from './tracing/spans/beforeSendSpan'; +export { isStreamedBeforeSendSpanCallback } from './tracing/spans/beforeSendSpan'; export { isSentryRequestUrl } from './utils/isSentryRequestUrl'; export { handleCallbackErrors } from './utils/handleCallbackErrors'; export { parameterize, fmt } from './utils/parameterize'; @@ -84,11 +86,13 @@ export { convertSpanLinksForEnvelope, spanToTraceHeader, spanToJSON, + spanToStreamedSpanJSON, spanIsSampled, spanToTraceContext, getSpanDescendants, getStatusMessage, getRootSpan, + INTERNAL_getSegmentSpan, getActiveSpan, addChildSpanToSpan, spanTimeInputToSeconds, @@ -101,6 +105,7 @@ export { getTraceData } from './utils/traceData'; export { shouldPropagateTraceForUrl } from './utils/tracePropagationTargets'; export { getTraceMetaTags } from './utils/meta'; export { debounce } from './utils/debounce'; +export { shouldIgnoreSpan } from './utils/should-ignore-span'; export { winterCGHeadersToDict, winterCGRequestToRequestData, @@ -119,6 +124,13 @@ export { linkedErrorsIntegration } from './integrations/linkederrors'; export { moduleMetadataIntegration } from './integrations/moduleMetadata'; export { requestDataIntegration } from './integrations/requestdata'; export { captureConsoleIntegration } from './integrations/captureconsole'; +export { patchExpressModule, setupExpressErrorHandler, expressErrorHandler } from './integrations/express/index'; +export type { + ExpressIntegrationOptions, + ExpressHandlerOptions, + ExpressMiddleware, + ExpressErrorMiddleware, +} from './integrations/express/types'; export { dedupeIntegration } from './integrations/dedupe'; export { extraErrorDataIntegration } from './integrations/extraerrordata'; export { rewriteFramesIntegration } from './integrations/rewriteframes'; @@ -161,7 +173,7 @@ export { ANTHROPIC_AI_INTEGRATION_NAME } from './tracing/anthropic-ai/constants' export { instrumentGoogleGenAIClient } from './tracing/google-genai'; export { GOOGLE_GENAI_INTEGRATION_NAME } from './tracing/google-genai/constants'; export type { GoogleGenAIResponse } from './tracing/google-genai/types'; -export { createLangChainCallbackHandler } from './tracing/langchain'; +export { createLangChainCallbackHandler, instrumentLangChainEmbeddings } from './tracing/langchain'; export { LANGCHAIN_INTEGRATION_NAME } from './tracing/langchain/constants'; export type { LangChainOptions, LangChainIntegration } from './tracing/langchain/types'; export { instrumentStateGraphCompile, instrumentLangGraph } from './tracing/langgraph'; @@ -180,6 +192,11 @@ export type { GoogleGenAIOptions, GoogleGenAIIstrumentedMethod, } from './tracing/google-genai/types'; + +export { SpanBuffer } from './tracing/spans/spanBuffer'; +export { hasSpanStreamingEnabled } from './tracing/spans/hasSpanStreamingEnabled'; +export { spanStreamingIntegration } from './integrations/spanStreaming'; + export type { FeatureFlag } from './utils/featureFlags'; export { @@ -394,6 +411,7 @@ export type { ProfileChunkEnvelope, ProfileChunkItem, SpanEnvelope, + StreamedSpanEnvelope, SpanItem, LogEnvelope, MetricEnvelope, @@ -461,6 +479,9 @@ export type { SpanJSON, SpanContextData, TraceFlag, + SerializedStreamedSpan, + SerializedStreamedSpanContainer, + StreamedSpanJSON, } from './types-hoist/span'; export type { SpanStatus } from './types-hoist/spanStatus'; export type { Log, LogSeverityLevel } from './types-hoist/log'; diff --git a/packages/core/src/integration.ts b/packages/core/src/integration.ts index 892228476824..b8e7240cf748 100644 --- a/packages/core/src/integration.ts +++ b/packages/core/src/integration.ts @@ -76,6 +76,12 @@ export function getIntegrationsToSetup( export function setupIntegrations(client: Client, integrations: Integration[]): IntegrationIndex { const integrationIndex: IntegrationIndex = {}; + integrations.forEach((integration: Integration | undefined) => { + if (integration?.beforeSetup) { + integration.beforeSetup(client); + } + }); + integrations.forEach((integration: Integration | undefined) => { // guard against empty provided integrations if (integration) { diff --git a/packages/core/src/integrations/express/index.ts b/packages/core/src/integrations/express/index.ts new file mode 100644 index 000000000000..4b2d5e2f0677 --- /dev/null +++ b/packages/core/src/integrations/express/index.ts @@ -0,0 +1,224 @@ +/** + * Platform-portable Express tracing integration. + * + * @module + * + * This Sentry integration is a derivative work based on the OpenTelemetry + * Express instrumentation. + * + * + * + * Extended under the terms of the Apache 2.0 license linked below: + * + * ---- + * + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { debug } from '../../utils/debug-logger'; +import { captureException } from '../../exports'; +import { DEBUG_BUILD } from '../../debug-build'; +import type { + ExpressApplication, + ExpressErrorMiddleware, + ExpressExport, + ExpressHandlerOptions, + ExpressIntegrationOptions, + ExpressLayer, + ExpressMiddleware, + ExpressModuleExport, + ExpressRequest, + ExpressResponse, + ExpressRouter, + ExpressRouterv4, + ExpressRouterv5, + MiddlewareError, +} from './types'; +import { + defaultShouldHandleError, + getLayerPath, + hasDefaultProp, + isExpressWithoutRouterPrototype, + isExpressWithRouterPrototype, +} from './utils'; +import { wrapMethod } from '../../utils/object'; +import { patchLayer } from './patch-layer'; +import { setSDKProcessingMetadata } from './set-sdk-processing-metadata'; + +const getExpressExport = (express: ExpressModuleExport): ExpressExport => + hasDefaultProp(express) ? express.default : (express as ExpressExport); + +/** + * This is a portable instrumentatiton function that works in any environment + * where Express can be loaded, without depending on OpenTelemetry. + * + * @example + * ```javascript + * import express from 'express'; + * import * as Sentry from '@sentry/deno'; // or any SDK that extends core + * + * Sentry.patchExpressModule({ express }) + */ +export const patchExpressModule = (options: ExpressIntegrationOptions) => { + // pass in the require() or import() result of express + const express = getExpressExport(options.express); + const routerProto: ExpressRouterv4 | ExpressRouterv5 | undefined = isExpressWithRouterPrototype(express) + ? express.Router.prototype // Express v5 + : isExpressWithoutRouterPrototype(express) + ? express.Router // Express v4 + : undefined; + + if (!routerProto) { + throw new TypeError('no valid Express route function to instrument'); + } + + // oxlint-disable-next-line @typescript-eslint/unbound-method + const originalRouteMethod = routerProto.route; + try { + wrapMethod( + routerProto, + 'route', + function routeTrace(this: ExpressRouter, ...args: Parameters[]) { + const route = originalRouteMethod.apply(this, args); + const layer = this.stack[this.stack.length - 1] as ExpressLayer; + patchLayer(options, layer, getLayerPath(args)); + return route; + }, + ); + } catch (e) { + DEBUG_BUILD && debug.error('Failed to patch express route method:', e); + } + + // oxlint-disable-next-line @typescript-eslint/unbound-method + const originalRouterUse = routerProto.use; + try { + wrapMethod( + routerProto, + 'use', + function useTrace(this: ExpressApplication, ...args: Parameters) { + const route = originalRouterUse.apply(this, args); + const layer = this.stack[this.stack.length - 1]; + if (!layer) { + return route; + } + patchLayer(options, layer, getLayerPath(args)); + return route; + }, + ); + } catch (e) { + DEBUG_BUILD && debug.error('Failed to patch express use method:', e); + } + + const { application } = express; + const originalApplicationUse = application.use; + try { + wrapMethod( + application, + 'use', + function appUseTrace( + this: ExpressApplication & { + _router?: ExpressRouter; + router?: ExpressRouter; + }, + ...args: Parameters + ) { + // If we access app.router in express 4.x we trigger an assertion error. + // This property existed in v3, was removed in v4 and then re-added in v5. + const route = originalApplicationUse.apply(this, args); + const router = isExpressWithRouterPrototype(express) ? this.router : this._router; + if (router) { + const layer = router.stack[router.stack.length - 1]; + if (layer) { + patchLayer(options, layer, getLayerPath(args)); + } + } + return route; + }, + ); + } catch (e) { + DEBUG_BUILD && debug.error('Failed to patch express application.use method:', e); + } + + return express; +}; + +/** + * An Express-compatible error handler, used by setupExpressErrorHandler + */ +export function expressErrorHandler(options?: ExpressHandlerOptions): ExpressErrorMiddleware { + return function sentryErrorMiddleware( + error: MiddlewareError, + request: ExpressRequest, + res: ExpressResponse, + next: (error: MiddlewareError) => void, + ): void { + // When an error happens, the `expressRequestHandler` middleware does not run, so we set it here too + setSDKProcessingMetadata(request); + const shouldHandleError = options?.shouldHandleError || defaultShouldHandleError; + + if (shouldHandleError(error)) { + const eventId = captureException(error, { + mechanism: { type: 'auto.middleware.express', handled: false }, + }); + (res as { sentry?: string }).sentry = eventId; + } + + next(error); + }; +} + +/** + * Add an Express error handler to capture errors to Sentry. + * + * The error handler must be before any other middleware and after all controllers. + * + * @param app The Express instances + * @param options {ExpressHandlerOptions} Configuration options for the handler + * + * @example + * ```javascript + * import * as Sentry from 'sentry/deno'; // or any other @sentry/ + * import * as express from 'express'; + * + * Sentry.instrumentExpress(express); + * + * const app = express(); + * + * // Add your routes, etc. + * + * // Add this after all routes, + * // but before any and other error-handling middlewares are defined + * Sentry.setupExpressErrorHandler(app); + * + * app.listen(3000); + * ``` + */ +export function setupExpressErrorHandler( + app: { + //oxlint-disable-next-line no-explicit-any + use: (middleware: any) => unknown; + }, + options?: ExpressHandlerOptions, +): void { + app.use(expressRequestHandler()); + app.use(expressErrorHandler(options)); +} + +function expressRequestHandler(): ExpressMiddleware { + return function sentryRequestMiddleware(request: ExpressRequest, _res: ExpressResponse, next: () => void): void { + setSDKProcessingMetadata(request); + next(); + }; +} diff --git a/packages/core/src/integrations/express/patch-layer.ts b/packages/core/src/integrations/express/patch-layer.ts new file mode 100644 index 000000000000..5f537e403524 --- /dev/null +++ b/packages/core/src/integrations/express/patch-layer.ts @@ -0,0 +1,265 @@ +/** + * Platform-portable Express tracing integration. + * + * @module + * + * This Sentry integration is a derivative work based on the OpenTelemetry + * Express instrumentation. + * + * + * + * Extended under the terms of the Apache 2.0 license linked below: + * + * ---- + * + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { DEBUG_BUILD } from '../../debug-build'; +import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '../../semanticAttributes'; +import { SPAN_STATUS_ERROR, startSpanManual, withActiveSpan } from '../../tracing'; +import { debug } from '../../utils/debug-logger'; +import type { SpanAttributes } from '../../types-hoist/span'; +import { getActiveSpan } from '../../utils/spanUtils'; +import { getStoredLayers, storeLayer } from './request-layer-store'; +import { + type ExpressRequest, + type ExpressResponse, + type ExpressIntegrationOptions, + type ExpressLayer, + ATTR_HTTP_ROUTE, + ATTR_EXPRESS_TYPE, + ATTR_EXPRESS_NAME, + ExpressLayerType_ROUTER, +} from './types'; +import { + asErrorAndMessage, + getActualMatchedRoute, + getConstructedRoute, + getLayerMetadata, + isLayerIgnored, +} from './utils'; +import { getIsolationScope } from '../../currentScopes'; +import { getDefaultIsolationScope } from '../../defaultScopes'; +import { getOriginalFunction, markFunctionWrapped } from '../../utils/object'; +import { setSDKProcessingMetadata } from './set-sdk-processing-metadata'; + +export type ExpressPatchLayerOptions = Pick< + ExpressIntegrationOptions, + 'onRouteResolved' | 'ignoreLayers' | 'ignoreLayersType' +>; + +export function patchLayer(options: ExpressPatchLayerOptions, maybeLayer?: ExpressLayer, layerPath?: string): void { + if (!maybeLayer?.handle) { + return; + } + const layer = maybeLayer; + + const layerHandleOriginal = layer.handle; + + // avoid patching multiple times the same layer + if (getOriginalFunction(layerHandleOriginal)) { + return; + } + + if (layerHandleOriginal.length === 4) { + // todo: instrument error handlers + return; + } + + function layerHandlePatched( + this: ExpressLayer, + req: ExpressRequest, + res: ExpressResponse, + //oxlint-disable-next-line no-explicit-any + ...otherArgs: any[] + ) { + // Set normalizedRequest here because expressRequestHandler middleware + // (registered via setupExpressErrorHandler) is added after routes and + // therefore never runs for successful requests — route handlers typically + // send a response without calling next(). It would be safe to set this + // multiple times, since the data is identical, but more performant not to. + setSDKProcessingMetadata(req); + + // Only create spans when there's an active parent span + // Without a parent span, this request is being ignored, so skip it + const parentSpan = getActiveSpan(); + if (!parentSpan) { + return layerHandleOriginal.apply(this, [req, res, ...otherArgs]); + } + + if (layerPath) { + storeLayer(req, layerPath); + } + const storedLayers = getStoredLayers(req); + const isLayerPathStored = !!layerPath; + + const constructedRoute = getConstructedRoute(req); + const actualMatchedRoute = getActualMatchedRoute(req, constructedRoute); + + options.onRouteResolved?.(actualMatchedRoute); + + const metadata = getLayerMetadata(constructedRoute, layer, layerPath); + const name = metadata.attributes[ATTR_EXPRESS_NAME]; + const type = metadata.attributes[ATTR_EXPRESS_TYPE]; + const attributes: SpanAttributes = Object.assign(metadata.attributes, { + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.express', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: `${type}.express`, + }); + if (actualMatchedRoute) { + attributes[ATTR_HTTP_ROUTE] = actualMatchedRoute; + } + + // verify against the config if the layer should be ignored + if (isLayerIgnored(metadata.attributes[ATTR_EXPRESS_NAME], type, options)) { + // XXX: the isLayerPathStored guard here is *not* present in the + // original @opentelemetry/instrumentation-express impl, but was + // suggested by the Sentry code review bot. It appears to correctly + // prevent improper layer calculation in the case where there's a + // middleware without a layerPath argument. It's unclear whether + // that's possible, or if any existing code depends on that "bug". + if (isLayerPathStored) { + storedLayers.pop(); + } + return layerHandleOriginal.apply(this, [req, res, ...otherArgs]); + } + + const currentScope = getIsolationScope(); + if (currentScope !== getDefaultIsolationScope()) { + if (type === 'request_handler') { + // type cast b/c Otel unfortunately types info.request as any :( + const method = req.method ? req.method.toUpperCase() : 'GET'; + currentScope.setTransactionName(`${method} ${constructedRoute}`); + } + } else { + DEBUG_BUILD && debug.warn('Isolation scope is still default isolation scope - skipping setting transactionName'); + } + + return startSpanManual({ name, attributes }, span => { + let spanHasEnded = false; + // TODO: Fix router spans (getRouterPath does not work properly) to + // have useful names before removing this branch + if (metadata.attributes[ATTR_EXPRESS_TYPE] === ExpressLayerType_ROUTER) { + span.end(); + spanHasEnded = true; + } + // listener for response.on('finish') + const onResponseFinish = () => { + if (!spanHasEnded) { + spanHasEnded = true; + span.end(); + } + }; + + // verify we have a callback + for (let i = 0; i < otherArgs.length; i++) { + const callback = otherArgs[i] as Function; + if (typeof callback !== 'function') { + continue; + } + + //oxlint-disable-next-line no-explicit-any + otherArgs[i] = function (...args: any[]) { + // express considers anything but an empty value, "route" or "router" + // passed to its callback to be an error + const maybeError = args[0]; + const isError = !!maybeError && maybeError !== 'route' && maybeError !== 'router'; + if (!spanHasEnded && isError) { + const [_, message] = asErrorAndMessage(maybeError); + // intentionally do not record the exception here, because + // the error handler we assign does that, provided the user + // correctly calls setupExpressErrorHandler. + // TODO: A future enhancement can automatically attach + // the error handler if we detect that it has not been added. + span.setStatus({ + code: SPAN_STATUS_ERROR, + message, + }); + } + + if (!spanHasEnded) { + spanHasEnded = true; + res.removeListener('finish', onResponseFinish); + span.end(); + } + if (!(req.route && isError) && isLayerPathStored) { + storedLayers.pop(); + } + // execute the callback back in the parent's scope, so that + // we bubble up each level as next() is called. + return withActiveSpan(parentSpan, () => callback.apply(this, args)); + }; + break; + } + + try { + return layerHandleOriginal.apply(this, [req, res, ...otherArgs]); + } catch (anyError) { + const [_, message] = asErrorAndMessage(anyError); + // intentionally do not record the exception here, because + // the error handler we assign does that, provided the user + // correctly calls setupExpressErrorHandler. + // TODO: A future enhancement can automatically attach + // the error handler if we detect that it has not been added. + span.setStatus({ + code: SPAN_STATUS_ERROR, + message, + }); + throw anyError; + /* v8 ignore next - it sees the block end at the throw */ + } finally { + // At this point if the callback wasn't called, that means + // either the layer is asynchronous (so it will call the + // callback later on) or that the layer directly ends the + // http response, so we'll hook into the "finish" event to + // handle the later case. + if (!spanHasEnded) { + res.once('finish', onResponseFinish); + } + } + }); + } + + // `handle` isn't just a regular function in some cases. It also contains + // some properties holding metadata and state so we need to proxy them + // through through patched function. Use a for-in to also pick up properties + // that other libraries might add to the prototype before we instrument. + // ref: https://github.com/open-telemetry/opentelemetry-js-contrib/issues/1950 + // ref: https://github.com/open-telemetry/opentelemetry-js-contrib/issues/2271 + // oxlint-disable-next-line guard-for-in + for (const key in layerHandleOriginal as Function & Record) { + // skip standard function prototype fields that both have + if (key in layerHandlePatched) { + continue; + } + Object.defineProperty(layerHandlePatched, key, { + get() { + return layerHandleOriginal[key]; + }, + set(value) { + layerHandleOriginal[key] = value; + }, + }); + } + + markFunctionWrapped(layerHandlePatched, layerHandleOriginal); + + Object.defineProperty(layer, 'handle', { + enumerable: true, + configurable: true, + writable: true, + value: layerHandlePatched, + }); +} diff --git a/packages/core/src/integrations/express/request-layer-store.ts b/packages/core/src/integrations/express/request-layer-store.ts new file mode 100644 index 000000000000..3408c2405e1b --- /dev/null +++ b/packages/core/src/integrations/express/request-layer-store.ts @@ -0,0 +1,50 @@ +/** + * Platform-portable Express tracing integration. + * + * @module + * + * This Sentry integration is a derivative work based on the OpenTelemetry + * Express instrumentation. + * + * + * + * Extended under the terms of the Apache 2.0 license linked below: + * + * ---- + * + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { ExpressRequest } from './types'; + +// map of patched request objects to stored layers +const requestLayerStore = new WeakMap(); +export const storeLayer = (req: ExpressRequest, layer: string) => { + const store = requestLayerStore.get(req); + if (!store) { + requestLayerStore.set(req, [layer]); + } else { + store.push(layer); + } +}; + +export const getStoredLayers = (req: ExpressRequest) => { + let store = requestLayerStore.get(req); + if (!store) { + store = []; + requestLayerStore.set(req, store); + } + return store; +}; diff --git a/packages/core/src/integrations/express/set-sdk-processing-metadata.ts b/packages/core/src/integrations/express/set-sdk-processing-metadata.ts new file mode 100644 index 000000000000..0b694a40a360 --- /dev/null +++ b/packages/core/src/integrations/express/set-sdk-processing-metadata.ts @@ -0,0 +1,47 @@ +/** + * Platform-portable Express tracing integration. + * + * @module + * + * This Sentry integration is a derivative work based on the OpenTelemetry + * Express instrumentation. + * + * + * + * Extended under the terms of the Apache 2.0 license linked below: + * + * ---- + * + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Abstract this out because we call it in multiple places, and it's cheaper to + * only do one time for any given request. + */ + +import type { ExpressRequest } from './types'; +import { getIsolationScope } from '../../currentScopes'; +import { httpRequestToRequestData } from '../../utils/request'; + +// TODO: consider moving this into a core util, eg +// setSDKProcessingMetadataFromRequest(..), if other integrations need it. +export function setSDKProcessingMetadata(request: ExpressRequest) { + const sdkProcMeta = getIsolationScope()?.getScopeData()?.sdkProcessingMetadata; + if (!sdkProcMeta?.normalizedRequest) { + const normalizedRequest = httpRequestToRequestData(request); + getIsolationScope().setSDKProcessingMetadata({ normalizedRequest }); + } +} diff --git a/packages/core/src/integrations/express/types.ts b/packages/core/src/integrations/express/types.ts new file mode 100644 index 000000000000..66d6f1de3c9e --- /dev/null +++ b/packages/core/src/integrations/express/types.ts @@ -0,0 +1,186 @@ +/** + * Platform-portable Express tracing integration. + * + * @module + * + * This Sentry integration is a derivative work based on the OpenTelemetry + * Express instrumentation. + * + * + * + * Extended under the terms of the Apache 2.0 license linked below: + * + * ---- + * + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { RequestEventData } from '../../types-hoist/request'; +import type { SpanAttributes } from '../../types-hoist/span'; + +export const ATTR_EXPRESS_NAME = 'express.name'; +export const ATTR_HTTP_ROUTE = 'http.route'; +export const ATTR_EXPRESS_TYPE = 'express.type'; + +export type ExpressExport = { + Router: ExpressRouterv5 | ExpressRouterv4; + application: ExpressApplication; +}; + +export type ExpressExportv5 = ExpressExport & { + Router: ExpressRouterv5; +}; + +export type ExpressExportv4 = ExpressExport & { + Router: ExpressRouterv4; +}; + +export type ExpressModuleExport = ExpressExport | { default: ExpressExport }; + +export interface ExpressRequest extends RequestEventData { + originalUrl: string; + route: unknown; + // Note: req.res is typed as optional (only present after middleware init). + // mark optional to preserve compat with express v4 types. + res?: ExpressResponse; +} + +// just a minimum type def for what we need, since this also needs to +// work in environments lacking node:http +export interface ExpressResponse { + once(ev: string, listener: Function): this; + removeListener(ev: string, listener?: Function): this; + emit(ev: string, ...data: unknown[]): this; +} + +export interface NextFunction { + (err?: unknown): void; + /** + * "Break-out" of a router by calling {next('router')}; + * @see {https://expressjs.com/en/guide/using-middleware.html#middleware.router} + */ + (deferToNext: 'router'): void; + /** + * "Break-out" of a route by calling {next('route')}; + * @see {https://expressjs.com/en/guide/using-middleware.html#middleware.application} + */ + (deferToNext: 'route'): void; +} + +// Need to mark this as `any` so they don't conflict with the actual express +//oxlint-disable-next-line no-explicit-any +export type ExpressApplicationRequestHandler = (...handlers: any[]) => any; + +export type ExpressRequestInfo = { + /** An express request object */ + request: T; + route: string; + layerType: ExpressLayerType; +}; + +export type ExpressLayerType = 'router' | 'middleware' | 'request_handler'; +export const ExpressLayerType_ROUTER = 'router'; +export const ExpressLayerType_MIDDLEWARE = 'middleware'; +export const ExpressLayerType_REQUEST_HANDLER = 'request_handler'; + +export type PathParams = string | RegExp | Array; +export type LayerPathSegment = string | RegExp | number; + +export interface ExpressRoute { + path: string; + stack: ExpressLayer[]; +} + +export type ExpressRouterv4 = ExpressRouter; + +export interface ExpressRouterv5 { + prototype: ExpressRouter; +} + +// https://github.com/expressjs/express/blob/main/lib/router/layer.js#L33 +export type ExpressLayer = { + handle: Function & + Record & { + stack?: ExpressLayer[]; + }; + name: string; + params: { [key: string]: string }; + path?: string; + regexp: RegExp; + route?: ExpressLayer; +}; + +export type ExpressRouter = { + params: { [key: string]: string }; + _params: string[]; + caseSensitive: boolean; + mergeParams: boolean; + strict: boolean; + stack: ExpressLayer[]; + route(prefix: PathParams): ExpressRoute; + use(...handlers: unknown[]): unknown; +}; + +export type IgnoreMatcher = string | RegExp | ((name: string) => boolean); + +export type ExpressIntegrationOptions = { + express: ExpressModuleExport; //Express + /** Ignore specific based on their name */ + ignoreLayers?: IgnoreMatcher[]; + /** Ignore specific layers based on their type */ + ignoreLayersType?: ExpressLayerType[]; + /** + * Optional callback invoked each time a layer resolves the matched HTTP route. + * Platform-specific integrations (e.g. Node.js) use this to propagate the + * resolved route to the underlying transport layer (e.g. OTel RPCMetadata). + */ + onRouteResolved?: (route: string | undefined) => void; +}; + +export type LayerMetadata = { + attributes: SpanAttributes; + name: string; +}; + +export interface ExpressApplication { + stack: ExpressLayer[]; + use: ExpressApplicationRequestHandler; +} + +export interface MiddlewareError extends Error { + status?: number | string; + statusCode?: number | string; + status_code?: number | string; + output?: { + statusCode?: number | string; + }; +} + +export type ExpressMiddleware = (req: ExpressRequest, res: ExpressResponse, next: () => void) => void; + +export type ExpressErrorMiddleware = ( + error: MiddlewareError, + req: ExpressRequest, + res: ExpressResponse, + next: (error: MiddlewareError) => void, +) => void; + +export interface ExpressHandlerOptions { + /** + * Callback method deciding whether error should be captured and sent to Sentry + * @param error Captured middleware error + */ + shouldHandleError?(this: void, error: MiddlewareError): boolean; +} diff --git a/packages/core/src/integrations/express/utils.ts b/packages/core/src/integrations/express/utils.ts new file mode 100644 index 000000000000..c3473bbab18a --- /dev/null +++ b/packages/core/src/integrations/express/utils.ts @@ -0,0 +1,274 @@ +/** + * Platform-portable Express tracing integration. + * + * @module + * + * This Sentry integration is a derivative work based on the OpenTelemetry + * Express instrumentation. + * + * + * + * Extended under the terms of the Apache 2.0 license linked below: + * + * ---- + * + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { SpanAttributes } from '../../types-hoist/span'; +import { getStoredLayers } from './request-layer-store'; +import type { + ExpressExport, + ExpressIntegrationOptions, + ExpressLayer, + ExpressLayerType, + ExpressRequest, + LayerPathSegment, + MiddlewareError, + ExpressRouterv4, + ExpressExportv5, + ExpressExportv4, +} from './types'; +import { + ATTR_EXPRESS_NAME, + ATTR_EXPRESS_TYPE, + ExpressLayerType_MIDDLEWARE, + ExpressLayerType_REQUEST_HANDLER, + ExpressLayerType_ROUTER, +} from './types'; +import { stringMatchesSomePattern } from '../../utils/string'; + +/** + * Converts a user-provided error value into an error and error message pair + * + * @param error - User-provided error value + * @returns Both an Error or string representation of the value and an error message + */ +export const asErrorAndMessage = (error: unknown): [string | Error, string] => + error instanceof Error ? [error, error.message] : [String(error), String(error)]; + +/** + * Checks if a route contains parameter patterns (e.g., :id, :userId) + * which are valid even if they don't exactly match the original URL + */ +export function isRoutePattern(route: string): boolean { + return route.includes(':') || route.includes('*'); +} + +/** + * Parse express layer context to retrieve a name and attributes. + * @param route The route of the layer + * @param layer Express layer + * @param [layerPath] if present, the path on which the layer has been mounted + */ +export const getLayerMetadata = ( + route: string, + layer: ExpressLayer, + layerPath?: string, +): { + attributes: SpanAttributes & { [ATTR_EXPRESS_NAME]: string; [ATTR_EXPRESS_TYPE]: ExpressLayerType }; + name: string; +} => { + if (layer.name === 'router') { + const maybeRouterPath = getRouterPath('', layer); + const extractedRouterPath = maybeRouterPath ? maybeRouterPath : layerPath || route || '/'; + + return { + attributes: { + [ATTR_EXPRESS_NAME]: extractedRouterPath, + [ATTR_EXPRESS_TYPE]: ExpressLayerType_ROUTER, + }, + name: `router - ${extractedRouterPath}`, + }; + } else if (layer.name === 'bound dispatch' || layer.name === 'handle') { + return { + attributes: { + [ATTR_EXPRESS_NAME]: (route || layerPath) ?? 'request handler', + [ATTR_EXPRESS_TYPE]: ExpressLayerType_REQUEST_HANDLER, + }, + name: `request handler${layer.path ? ` - ${route || layerPath}` : ''}`, + }; + } else { + return { + attributes: { + [ATTR_EXPRESS_NAME]: layer.name, + [ATTR_EXPRESS_TYPE]: ExpressLayerType_MIDDLEWARE, + }, + name: `middleware - ${layer.name}`, + }; + } +}; + +/** + * Recursively search the router path from layer stack + * @param path The path to reconstruct + * @param layer The layer to reconstruct from + * @returns The reconstructed path + */ +export const getRouterPath = (path: string, layer: ExpressLayer): string => { + const stackLayer = Array.isArray(layer.handle?.stack) ? layer.handle?.stack?.[0] : undefined; + + if (stackLayer?.route?.path) { + return `${path}${stackLayer.route.path}`; + } + + if (stackLayer && Array.isArray(stackLayer?.handle?.stack)) { + return getRouterPath(path, stackLayer); + } + + return path; +}; + +/** + * Check whether the given request is ignored by configuration + * It will not re-throw exceptions from `list` provided by the client + * @param constant e.g URL of request + * @param [list] List of ignore patterns + * @param [onException] callback for doing something when an exception has + * occurred + */ +export type ExpressIsLayerIgnoredOptions = Pick; +export const isLayerIgnored = ( + name: string, + type: ExpressLayerType, + config?: ExpressIsLayerIgnoredOptions, +): boolean => { + if (Array.isArray(config?.ignoreLayersType) && config?.ignoreLayersType?.includes(type)) { + return true; + } + if (!Array.isArray(config?.ignoreLayers)) { + return false; + } + try { + return stringMatchesSomePattern(name, config.ignoreLayers, true); + } catch {} + + return false; +}; + +/** + * Extracts the actual matched route from Express request for OpenTelemetry instrumentation. + * Returns the route that should be used as the http.route attribute. + * + * @param req - The Express request object with layers store + * @param constructedRoute - The constructed route from `getConstructedRoute` + * @returns The matched route string or undefined if no valid route is found + */ +export function getActualMatchedRoute(req: ExpressRequest, constructedRoute: string): string | undefined { + const layersStore = getStoredLayers(req); + + // If no layers are stored, no route can be determined + if (layersStore.length === 0) { + return undefined; + } + + // Handle root path case - if all paths are root, only return root if originalUrl is also root + // The layer store also includes root paths in case a non-existing url was requested + if (layersStore.every(path => path === '/')) { + return req.originalUrl === '/' ? '/' : undefined; + } + + if (constructedRoute === '*') { + return constructedRoute; + } + + // For RegExp routes or route arrays, return the constructed route + // This handles the case where the route is defined using RegExp or an array + if ( + constructedRoute.includes('/') && + (constructedRoute.includes(',') || + constructedRoute.includes('\\') || + constructedRoute.includes('*') || + constructedRoute.includes('[')) + ) { + return constructedRoute; + } + + // Ensure route starts with '/' if it doesn't already + const normalizedRoute = constructedRoute.startsWith('/') ? constructedRoute : `/${constructedRoute}`; + + // Validate that this appears to be a matched route + // A route is considered matched if: + // 1. We have a constructed route + // 2. The original URL matches or starts with our route pattern + const isValidRoute = + normalizedRoute.length > 0 && + (req.originalUrl === normalizedRoute || + req.originalUrl.startsWith(normalizedRoute) || + isRoutePattern(normalizedRoute)); + + return isValidRoute ? normalizedRoute : undefined; +} + +export function getConstructedRoute(req: ExpressRequest) { + const layersStore: string[] = getStoredLayers(req); + + let constructedRoute: string = ''; + for (const path of layersStore) { + if (path === '/' || path === '/*') { + continue; + } + constructedRoute += !constructedRoute || constructedRoute.endsWith('/') ? path : `/${path}`; + } + + return constructedRoute.replace(/\/{2,}/g, '/'); +} + +export const getLayerPath = (args: unknown[]): string | undefined => { + const firstArg = args[0]; + + if (Array.isArray(firstArg)) { + return firstArg.map(arg => extractLayerPathSegment(arg) || '').join(','); + } + + return extractLayerPathSegment(firstArg as LayerPathSegment); +}; + +const extractLayerPathSegment = (arg: LayerPathSegment): string | undefined => + typeof arg === 'string' ? arg : arg instanceof RegExp || typeof arg === 'number' ? String(arg) : undefined; + +// v5 we instrument Router.prototype +// v4 we instrument Router itself +export const isExpressWithRouterPrototype = (express: unknown): express is ExpressExportv5 => + isExpressRouterPrototype((express as ExpressExportv5)?.Router?.prototype); + +// In Express v4, Router is a function (not a plain object), so we need to accept both +const isExpressRouterPrototype = (routerProto?: unknown): routerProto is ExpressRouterv4 => + (typeof routerProto === 'object' || typeof routerProto === 'function') && + !!routerProto && + 'route' in routerProto && + typeof (routerProto as ExpressRouterv4).route === 'function'; + +export const isExpressWithoutRouterPrototype = (express: unknown): express is ExpressExportv4 => + isExpressRouterPrototype((express as ExpressExportv4).Router) && !isExpressWithRouterPrototype(express); + +// dynamic puts the default on .default, require or normal import are fine +export const hasDefaultProp = ( + express: unknown, +): express is { + [k: string]: unknown; + default: ExpressExport; +} => !!express && typeof express === 'object' && 'default' in express && typeof express.default === 'function'; + +function getStatusCodeFromResponse(error: MiddlewareError): number { + const statusCode = error.status || error.statusCode || error.status_code || error.output?.statusCode; + return statusCode ? parseInt(statusCode as string, 10) : 500; +} + +/** Returns true if response code is internal server error */ +export function defaultShouldHandleError(error: MiddlewareError): boolean { + const status = getStatusCodeFromResponse(error); + return status >= 500; +} diff --git a/packages/core/src/integrations/mcp-server/correlation.ts b/packages/core/src/integrations/mcp-server/correlation.ts index b47f0f9b4a69..a831a822039c 100644 --- a/packages/core/src/integrations/mcp-server/correlation.ts +++ b/packages/core/src/integrations/mcp-server/correlation.ts @@ -81,19 +81,23 @@ export function storeSpanForRequest(transport: MCPTransport, requestId: RequestI * @param requestId - Request identifier * @param result - Execution result for attribute extraction * @param options - Resolved MCP options + * @param hasError - Whether the JSON-RPC response contained an error */ export function completeSpanWithResults( transport: MCPTransport, requestId: RequestId, result: unknown, options: ResolvedMcpOptions, + hasError = false, ): void { const spanMap = getOrCreateSpanMap(transport); const spanData = spanMap.get(requestId); if (spanData) { const { span, method } = spanData; - if (method === 'initialize') { + if (hasError) { + span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' }); + } else if (method === 'initialize') { const sessionData = extractSessionDataFromInitializeResponse(result); const serverAttributes = buildServerAttributesFromInfo(sessionData.serverInfo); diff --git a/packages/core/src/integrations/mcp-server/handlers.ts b/packages/core/src/integrations/mcp-server/handlers.ts index dd8e0296a95e..5ac0d0e0722a 100644 --- a/packages/core/src/integrations/mcp-server/handlers.ts +++ b/packages/core/src/integrations/mcp-server/handlers.ts @@ -96,7 +96,7 @@ function captureHandlerError(error: Error, methodName: keyof MCPServerInstance, try { const extraData: Record = {}; - if (methodName === 'tool') { + if (methodName === 'tool' || methodName === 'registerTool') { extraData.tool_name = handlerName; if ( @@ -114,10 +114,10 @@ function captureHandlerError(error: Error, methodName: keyof MCPServerInstance, } else { captureError(error, 'tool_execution', extraData); } - } else if (methodName === 'resource') { + } else if (methodName === 'resource' || methodName === 'registerResource') { extraData.resource_uri = handlerName; captureError(error, 'resource_execution', extraData); - } else if (methodName === 'prompt') { + } else if (methodName === 'prompt' || methodName === 'registerPrompt') { extraData.prompt_name = handlerName; captureError(error, 'prompt_execution', extraData); } @@ -127,31 +127,39 @@ function captureHandlerError(error: Error, methodName: keyof MCPServerInstance, } /** - * Wraps tool handlers to associate them with request spans + * Wraps tool handlers to associate them with request spans. + * Instruments both `tool` (legacy API) and `registerTool` (new API) if present. * @param serverInstance - MCP server instance */ export function wrapToolHandlers(serverInstance: MCPServerInstance): void { - wrapMethodHandler(serverInstance, 'tool'); + if (typeof serverInstance.tool === 'function') wrapMethodHandler(serverInstance, 'tool'); + if (typeof serverInstance.registerTool === 'function') wrapMethodHandler(serverInstance, 'registerTool'); } /** - * Wraps resource handlers to associate them with request spans + * Wraps resource handlers to associate them with request spans. + * Instruments both `resource` (legacy API) and `registerResource` (new API) if present. * @param serverInstance - MCP server instance */ export function wrapResourceHandlers(serverInstance: MCPServerInstance): void { - wrapMethodHandler(serverInstance, 'resource'); + if (typeof serverInstance.resource === 'function') wrapMethodHandler(serverInstance, 'resource'); + if (typeof serverInstance.registerResource === 'function') wrapMethodHandler(serverInstance, 'registerResource'); } /** - * Wraps prompt handlers to associate them with request spans + * Wraps prompt handlers to associate them with request spans. + * Instruments both `prompt` (legacy API) and `registerPrompt` (new API) if present. * @param serverInstance - MCP server instance */ export function wrapPromptHandlers(serverInstance: MCPServerInstance): void { - wrapMethodHandler(serverInstance, 'prompt'); + if (typeof serverInstance.prompt === 'function') wrapMethodHandler(serverInstance, 'prompt'); + if (typeof serverInstance.registerPrompt === 'function') wrapMethodHandler(serverInstance, 'registerPrompt'); } /** - * Wraps all MCP handler types (tool, resource, prompt) for span correlation + * Wraps all MCP handler types for span correlation. + * Supports both the legacy API (`tool`, `resource`, `prompt`) and the newer API + * (`registerTool`, `registerResource`, `registerPrompt`), instrumenting whichever methods are present. * @param serverInstance - MCP server instance */ export function wrapAllMCPHandlers(serverInstance: MCPServerInstance): void { diff --git a/packages/core/src/integrations/mcp-server/index.ts b/packages/core/src/integrations/mcp-server/index.ts index 5698cd445834..b4ef87f0fa0a 100644 --- a/packages/core/src/integrations/mcp-server/index.ts +++ b/packages/core/src/integrations/mcp-server/index.ts @@ -14,7 +14,8 @@ const wrappedMcpServerInstances = new WeakSet(); /** * Wraps a MCP Server instance from the `@modelcontextprotocol/sdk` package with Sentry instrumentation. * - * Compatible with versions `^1.9.0` of the `@modelcontextprotocol/sdk` package. + * Compatible with versions `^1.9.0` of the `@modelcontextprotocol/sdk` package (legacy `tool`/`resource`/`prompt` API) + * and versions that expose the newer `registerTool`/`registerResource`/`registerPrompt` API (introduced in 1.x, sole API in 2.x). * Automatically instruments transport methods and handler functions for comprehensive monitoring. * * @example diff --git a/packages/core/src/integrations/mcp-server/transport.ts b/packages/core/src/integrations/mcp-server/transport.ts index 5e4fd6e75c23..4b04a78f43b0 100644 --- a/packages/core/src/integrations/mcp-server/transport.ts +++ b/packages/core/src/integrations/mcp-server/transport.ts @@ -121,7 +121,7 @@ export function wrapTransportSend(transport: MCPTransport, options: ResolvedMcpO } } - completeSpanWithResults(this, message.id, message.result, options); + completeSpanWithResults(this, message.id, message.result, options, !!message.error); } } diff --git a/packages/core/src/integrations/mcp-server/types.ts b/packages/core/src/integrations/mcp-server/types.ts index 35dbcffcabb0..e6fd873fa4fa 100644 --- a/packages/core/src/integrations/mcp-server/types.ts +++ b/packages/core/src/integrations/mcp-server/types.ts @@ -87,17 +87,53 @@ export type JsonRpcMessage = JsonRpcRequest | JsonRpcNotification | JsonRpcRespo /** * MCP server instance interface - * @description MCP server methods for registering handlers + * @description MCP server methods for registering handlers. + * Supports both the legacy API (`tool`, `resource`, `prompt`) used in SDK 1.x + * and the newer API (`registerTool`, `registerResource`, `registerPrompt`) introduced in SDK 1.x + * and made the only option in SDK 2.x. */ export interface MCPServerInstance { - /** Register a resource handler */ - resource: (name: string, ...args: unknown[]) => void; + /** + * Register a resource handler. + * Supported in `@modelcontextprotocol/sdk` v1.x alongside `registerResource`. + * @deprecated Removed in `@modelcontextprotocol/sdk` v2.0.0 — use `registerResource` instead. + */ + resource?: (name: string, ...args: unknown[]) => void; + + /** + * Register a tool handler. + * Supported in `@modelcontextprotocol/sdk` v1.x alongside `registerTool`. + * @deprecated Removed in `@modelcontextprotocol/sdk` v2.0.0 — use `registerTool` instead. + */ + tool?: (name: string, ...args: unknown[]) => void; - /** Register a tool handler */ - tool: (name: string, ...args: unknown[]) => void; + /** + * Register a prompt handler. + * Supported in `@modelcontextprotocol/sdk` v1.x alongside `registerPrompt`. + * @deprecated Removed in `@modelcontextprotocol/sdk` v2.0.0 — use `registerPrompt` instead. + */ + prompt?: (name: string, ...args: unknown[]) => void; - /** Register a prompt handler */ - prompt: (name: string, ...args: unknown[]) => void; + /** + * Register a resource handler. + * Available in `@modelcontextprotocol/sdk` v1.x (alongside the legacy `resource` method) + * and the only supported form in v2.0.0+. + */ + registerResource?: (name: string, ...args: unknown[]) => void; + + /** + * Register a tool handler. + * Available in `@modelcontextprotocol/sdk` v1.x (alongside the legacy `tool` method) + * and the only supported form in v2.0.0+. + */ + registerTool?: (name: string, ...args: unknown[]) => void; + + /** + * Register a prompt handler. + * Available in `@modelcontextprotocol/sdk` v1.x (alongside the legacy `prompt` method) + * and the only supported form in v2.0.0+. + */ + registerPrompt?: (name: string, ...args: unknown[]) => void; /** Connect the server to a transport */ connect(transport: MCPTransport): Promise; diff --git a/packages/core/src/integrations/mcp-server/validation.ts b/packages/core/src/integrations/mcp-server/validation.ts index 9ed21b290728..15fb27f9c803 100644 --- a/packages/core/src/integrations/mcp-server/validation.ts +++ b/packages/core/src/integrations/mcp-server/validation.ts @@ -57,7 +57,10 @@ export function isJsonRpcResponse(message: unknown): message is JsonRpcResponse } /** - * Validates MCP server instance with type checking + * Validates MCP server instance with type checking. + * Accepts both the legacy API (`tool`, `resource`, `prompt`) used in SDK 1.x + * and the newer API (`registerTool`, `registerResource`, `registerPrompt`) introduced + * alongside the legacy API in SDK 1.x and made the only option in SDK 2.x. * @param instance - Object to validate as MCP server instance * @returns True if instance has required MCP server methods */ @@ -65,10 +68,9 @@ export function validateMcpServerInstance(instance: unknown): boolean { if ( typeof instance === 'object' && instance !== null && - 'resource' in instance && - 'tool' in instance && - 'prompt' in instance && - 'connect' in instance + 'connect' in instance && + (('tool' in instance && 'resource' in instance && 'prompt' in instance) || + ('registerTool' in instance && 'registerResource' in instance && 'registerPrompt' in instance)) ) { return true; } diff --git a/packages/core/src/integrations/spanStreaming.ts b/packages/core/src/integrations/spanStreaming.ts new file mode 100644 index 000000000000..541be6b7f5e9 --- /dev/null +++ b/packages/core/src/integrations/spanStreaming.ts @@ -0,0 +1,44 @@ +import type { IntegrationFn } from '../types-hoist/integration'; +import { DEBUG_BUILD } from '../debug-build'; +import { defineIntegration } from '../integration'; +import { isStreamedBeforeSendSpanCallback } from '../tracing/spans/beforeSendSpan'; +import { captureSpan } from '../tracing/spans/captureSpan'; +import { hasSpanStreamingEnabled } from '../tracing/spans/hasSpanStreamingEnabled'; +import { SpanBuffer } from '../tracing/spans/spanBuffer'; +import { debug } from '../utils/debug-logger'; +import { spanIsSampled } from '../utils/spanUtils'; + +export const spanStreamingIntegration = defineIntegration(() => { + return { + name: 'SpanStreaming', + + setup(client) { + const initialMessage = 'SpanStreaming integration requires'; + const fallbackMsg = 'Falling back to static trace lifecycle.'; + const clientOptions = client.getOptions(); + + if (!hasSpanStreamingEnabled(client)) { + clientOptions.traceLifecycle = 'static'; + DEBUG_BUILD && debug.warn(`${initialMessage} \`traceLifecycle\` to be set to "stream"! ${fallbackMsg}`); + return; + } + + const beforeSendSpan = clientOptions.beforeSendSpan; + if (beforeSendSpan && !isStreamedBeforeSendSpanCallback(beforeSendSpan)) { + clientOptions.traceLifecycle = 'static'; + DEBUG_BUILD && + debug.warn(`${initialMessage} a beforeSendSpan callback using \`withStreamedSpan\`! ${fallbackMsg}`); + return; + } + + const buffer = new SpanBuffer(client); + + client.on('afterSpanEnd', span => { + if (!spanIsSampled(span)) { + return; + } + buffer.add(captureSpan(span, client)); + }); + }, + }; +}) satisfies IntegrationFn; diff --git a/packages/core/src/semanticAttributes.ts b/packages/core/src/semanticAttributes.ts index 88b0f470dfa3..02b6a4ec08a6 100644 --- a/packages/core/src/semanticAttributes.ts +++ b/packages/core/src/semanticAttributes.ts @@ -1,7 +1,7 @@ /** - * Use this attribute to represent the source of a span. - * Should be one of: custom, url, route, view, component, task, unknown - * + * Use this attribute to represent the source of a span name. + * Must be one of: custom, url, route, view, component, task + * TODO(v11): rename this to sentry.span.source' */ export const SEMANTIC_ATTRIBUTE_SENTRY_SOURCE = 'sentry.source'; @@ -40,6 +40,28 @@ export const SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT = 'sentry.measurement_un /** The value of a measurement, which may be stored as a TimedEvent. */ export const SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE = 'sentry.measurement_value'; +/** The release version of the application */ +export const SEMANTIC_ATTRIBUTE_SENTRY_RELEASE = 'sentry.release'; +/** The environment name (e.g., "production", "staging", "development") */ +export const SEMANTIC_ATTRIBUTE_SENTRY_ENVIRONMENT = 'sentry.environment'; +/** The segment name (e.g., "GET /users") */ +export const SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME = 'sentry.segment.name'; +/** The id of the segment that this span belongs to. */ +export const SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID = 'sentry.segment.id'; +/** The name of the Sentry SDK (e.g., "sentry.php", "sentry.javascript") */ +export const SEMANTIC_ATTRIBUTE_SENTRY_SDK_NAME = 'sentry.sdk.name'; +/** The version of the Sentry SDK */ +export const SEMANTIC_ATTRIBUTE_SENTRY_SDK_VERSION = 'sentry.sdk.version'; + +/** The user ID (gated by sendDefaultPii) */ +export const SEMANTIC_ATTRIBUTE_USER_ID = 'user.id'; +/** The user email (gated by sendDefaultPii) */ +export const SEMANTIC_ATTRIBUTE_USER_EMAIL = 'user.email'; +/** The user IP address (gated by sendDefaultPii) */ +export const SEMANTIC_ATTRIBUTE_USER_IP_ADDRESS = 'user.ip_address'; +/** The user username (gated by sendDefaultPii) */ +export const SEMANTIC_ATTRIBUTE_USER_USERNAME = 'user.name'; + /** * A custom span name set by users guaranteed to be taken over any automatically * inferred name. This attribute is removed before the span is sent. diff --git a/packages/core/src/tracing/ai/gen-ai-attributes.ts b/packages/core/src/tracing/ai/gen-ai-attributes.ts index 5c740142b4f0..288e5ad9eeb8 100644 --- a/packages/core/src/tracing/ai/gen-ai-attributes.ts +++ b/packages/core/src/tracing/ai/gen-ai-attributes.ts @@ -207,24 +207,9 @@ export const GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE = 'gen_ai.usage.input_to export const GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE = 'gen_ai.invoke_agent'; /** - * The span operation name for generating text + * The span operation name for generating content */ -export const GEN_AI_GENERATE_TEXT_DO_GENERATE_OPERATION_ATTRIBUTE = 'gen_ai.generate_text'; - -/** - * The span operation name for streaming text - */ -export const GEN_AI_STREAM_TEXT_DO_STREAM_OPERATION_ATTRIBUTE = 'gen_ai.stream_text'; - -/** - * The span operation name for generating object - */ -export const GEN_AI_GENERATE_OBJECT_DO_GENERATE_OPERATION_ATTRIBUTE = 'gen_ai.generate_object'; - -/** - * The span operation name for streaming object - */ -export const GEN_AI_STREAM_OBJECT_DO_STREAM_OPERATION_ATTRIBUTE = 'gen_ai.stream_object'; +export const GEN_AI_GENERATE_CONTENT_OPERATION_ATTRIBUTE = 'gen_ai.generate_content'; /** * The embeddings input @@ -232,6 +217,11 @@ export const GEN_AI_STREAM_OBJECT_DO_STREAM_OPERATION_ATTRIBUTE = 'gen_ai.stream */ export const GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE = 'gen_ai.embeddings.input'; +/** + * The span operation for embeddings + */ +export const GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE = 'gen_ai.embeddings'; + /** * The span operation name for embedding */ @@ -282,41 +272,3 @@ export const GEN_AI_TOOL_OUTPUT_ATTRIBUTE = 'gen_ai.tool.output'; * @see https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/#gen-ai-tool-description */ export const GEN_AI_TOOL_DESCRIPTION_ATTRIBUTE = 'gen_ai.tool.description'; - -// ============================================================================= -// OPENAI-SPECIFIC ATTRIBUTES -// ============================================================================= - -/** - * The response ID from OpenAI - */ -export const OPENAI_RESPONSE_ID_ATTRIBUTE = 'openai.response.id'; - -/** - * The response model from OpenAI - */ -export const OPENAI_RESPONSE_MODEL_ATTRIBUTE = 'openai.response.model'; - -/** - * The response timestamp from OpenAI (ISO string) - */ -export const OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE = 'openai.response.timestamp'; - -/** - * The number of completion tokens used - */ -export const OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE = 'openai.usage.completion_tokens'; - -/** - * The number of prompt tokens used - */ -export const OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE = 'openai.usage.prompt_tokens'; - -// ============================================================================= -// ANTHROPIC AI OPERATIONS -// ============================================================================= - -/** - * The response timestamp from Anthropic AI (ISO string) - */ -export const ANTHROPIC_AI_RESPONSE_TIMESTAMP_ATTRIBUTE = 'anthropic.response.timestamp'; diff --git a/packages/core/src/tracing/ai/utils.ts b/packages/core/src/tracing/ai/utils.ts index d9628e3c75e2..601807cc194d 100644 --- a/packages/core/src/tracing/ai/utils.ts +++ b/packages/core/src/tracing/ai/utils.ts @@ -6,6 +6,12 @@ import { getClient } from '../../currentScopes'; import type { Span } from '../../types-hoist/span'; import { isThenable } from '../../utils/is'; import { + GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE, + GEN_AI_RESPONSE_ID_ATTRIBUTE, + GEN_AI_RESPONSE_MODEL_ATTRIBUTE, + GEN_AI_RESPONSE_STREAMING_ATTRIBUTE, + GEN_AI_RESPONSE_TEXT_ATTRIBUTE, + GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE, GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE, @@ -22,10 +28,12 @@ export interface AIRecordingOptions { * which gen_ai operation it maps to and whether it is intrinsically streaming. */ export interface InstrumentedMethodEntry { - /** Operation name (e.g. 'chat', 'embeddings', 'generate_content') */ - operation: string; + /** Operation name (e.g. 'chat', 'embeddings', 'generate_content'). Omit for factory methods that only need result proxying. */ + operation?: string; /** True if the method itself is always streaming (not param-based) */ streaming?: boolean; + /** When set, the method's return value is re-proxied with this as the base path */ + proxyResultPath?: string; } /** @@ -99,6 +107,68 @@ export function setTokenUsageAttributes( } } +export interface StreamResponseState { + responseId?: string; + responseModel?: string; + finishReasons: string[]; + responseTexts: string[]; + toolCalls: unknown[]; + promptTokens?: number; + completionTokens?: number; + totalTokens?: number; + cacheCreationInputTokens?: number; + cacheReadInputTokens?: number; +} + +/** + * Ends a streaming span by setting all accumulated response attributes and ending the span. + * Shared across OpenAI, Anthropic, and Google GenAI streaming implementations. + */ +export function endStreamSpan(span: Span, state: StreamResponseState, recordOutputs: boolean): void { + if (!span.isRecording()) { + return; + } + + const attrs: Record = { + [GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true, + }; + + if (state.responseId) attrs[GEN_AI_RESPONSE_ID_ATTRIBUTE] = state.responseId; + if (state.responseModel) attrs[GEN_AI_RESPONSE_MODEL_ATTRIBUTE] = state.responseModel; + + if (state.promptTokens !== undefined) attrs[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE] = state.promptTokens; + if (state.completionTokens !== undefined) attrs[GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE] = state.completionTokens; + + // Use explicit total if provided (OpenAI, Google), otherwise compute from cache tokens (Anthropic) + if (state.totalTokens !== undefined) { + attrs[GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE] = state.totalTokens; + } else if ( + state.promptTokens !== undefined || + state.completionTokens !== undefined || + state.cacheCreationInputTokens !== undefined || + state.cacheReadInputTokens !== undefined + ) { + attrs[GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE] = + (state.promptTokens ?? 0) + + (state.completionTokens ?? 0) + + (state.cacheCreationInputTokens ?? 0) + + (state.cacheReadInputTokens ?? 0); + } + + if (state.finishReasons.length) { + attrs[GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE] = JSON.stringify(state.finishReasons); + } + if (recordOutputs && state.responseTexts.length) { + attrs[GEN_AI_RESPONSE_TEXT_ATTRIBUTE] = state.responseTexts.join(''); + } + if (recordOutputs && state.toolCalls.length) { + attrs[GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE] = JSON.stringify(state.toolCalls); + } + + span.setAttributes(attrs); + span.end(); +} + /** * Get the truncated JSON string for a string or array of strings. * diff --git a/packages/core/src/tracing/anthropic-ai/index.ts b/packages/core/src/tracing/anthropic-ai/index.ts index 226aa8e1d544..14cc44d6d6be 100644 --- a/packages/core/src/tracing/anthropic-ai/index.ts +++ b/packages/core/src/tracing/anthropic-ai/index.ts @@ -4,7 +4,6 @@ import { SPAN_STATUS_ERROR } from '../../tracing'; import { startSpan, startSpanManual } from '../../tracing/trace'; import type { Span, SpanAttributeValue } from '../../types-hoist/span'; import { - ANTHROPIC_AI_RESPONSE_TIMESTAMP_ATTRIBUTE, GEN_AI_OPERATION_NAME_ATTRIBUTE, GEN_AI_PROMPT_ATTRIBUTE, GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE, @@ -128,17 +127,6 @@ function addMetadataAttributes(span: Span, response: AnthropicAiResponse): void [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: response.model, }); - if ('created' in response && typeof response.created === 'number') { - span.setAttributes({ - [ANTHROPIC_AI_RESPONSE_TIMESTAMP_ATTRIBUTE]: new Date(response.created * 1000).toISOString(), - }); - } - if ('created_at' in response && typeof response.created_at === 'number') { - span.setAttributes({ - [ANTHROPIC_AI_RESPONSE_TIMESTAMP_ATTRIBUTE]: new Date(response.created_at * 1000).toISOString(), - }); - } - if ('usage' in response && response.usage) { setTokenUsageAttributes( span, @@ -265,7 +253,7 @@ function instrumentMethod( ): (...args: T) => R | Promise { return new Proxy(originalMethod, { apply(target, thisArg, args: T): R | Promise { - const operationName = instrumentedMethod.operation; + const operationName = instrumentedMethod.operation || 'unknown'; const requestAttributes = extractRequestAttributes(args, methodPath, operationName); const model = requestAttributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] ?? 'unknown'; diff --git a/packages/core/src/tracing/anthropic-ai/streaming.ts b/packages/core/src/tracing/anthropic-ai/streaming.ts index 940ec53e8030..6e649b32253a 100644 --- a/packages/core/src/tracing/anthropic-ai/streaming.ts +++ b/packages/core/src/tracing/anthropic-ai/streaming.ts @@ -1,15 +1,7 @@ import { captureException } from '../../exports'; import { SPAN_STATUS_ERROR } from '../../tracing'; import type { Span } from '../../types-hoist/span'; -import { - GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE, - GEN_AI_RESPONSE_ID_ATTRIBUTE, - GEN_AI_RESPONSE_MODEL_ATTRIBUTE, - GEN_AI_RESPONSE_STREAMING_ATTRIBUTE, - GEN_AI_RESPONSE_TEXT_ATTRIBUTE, - GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE, -} from '../ai/gen-ai-attributes'; -import { setTokenUsageAttributes } from '../ai/utils'; +import { endStreamSpan } from '../ai/utils'; import type { AnthropicAiStreamingEvent } from './types'; import { mapAnthropicErrorToStatusMessage } from './utils'; @@ -208,60 +200,6 @@ function processEvent( handleContentBlockStop(event, state); } -/** - * Finalizes span attributes when stream processing completes - */ -function finalizeStreamSpan(state: StreamingState, span: Span, recordOutputs: boolean): void { - if (!span.isRecording()) { - return; - } - - // Set common response attributes if available - if (state.responseId) { - span.setAttributes({ - [GEN_AI_RESPONSE_ID_ATTRIBUTE]: state.responseId, - }); - } - if (state.responseModel) { - span.setAttributes({ - [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: state.responseModel, - }); - } - - setTokenUsageAttributes( - span, - state.promptTokens, - state.completionTokens, - state.cacheCreationInputTokens, - state.cacheReadInputTokens, - ); - - span.setAttributes({ - [GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true, - }); - - if (state.finishReasons.length > 0) { - span.setAttributes({ - [GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE]: JSON.stringify(state.finishReasons), - }); - } - - if (recordOutputs && state.responseTexts.length > 0) { - span.setAttributes({ - [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: state.responseTexts.join(''), - }); - } - - // Set tool calls if any were captured - if (recordOutputs && state.toolCalls.length > 0) { - span.setAttributes({ - [GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(state.toolCalls), - }); - } - - span.end(); -} - /** * Instruments an async iterable stream of Anthropic events, updates the span with * streaming attributes and (optionally) the aggregated output text, and yields @@ -291,50 +229,7 @@ export async function* instrumentAsyncIterableStream( yield event; } } finally { - // Set common response attributes if available - if (state.responseId) { - span.setAttributes({ - [GEN_AI_RESPONSE_ID_ATTRIBUTE]: state.responseId, - }); - } - if (state.responseModel) { - span.setAttributes({ - [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: state.responseModel, - }); - } - - setTokenUsageAttributes( - span, - state.promptTokens, - state.completionTokens, - state.cacheCreationInputTokens, - state.cacheReadInputTokens, - ); - - span.setAttributes({ - [GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true, - }); - - if (state.finishReasons.length > 0) { - span.setAttributes({ - [GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE]: JSON.stringify(state.finishReasons), - }); - } - - if (recordOutputs && state.responseTexts.length > 0) { - span.setAttributes({ - [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: state.responseTexts.join(''), - }); - } - - // Set tool calls if any were captured - if (recordOutputs && state.toolCalls.length > 0) { - span.setAttributes({ - [GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(state.toolCalls), - }); - } - - span.end(); + endStreamSpan(span, state, recordOutputs); } } @@ -366,7 +261,7 @@ export function instrumentMessageStream // The event fired when a message is done being streamed by the API. Corresponds to the message_stop SSE event. // @see https://github.com/anthropics/anthropic-sdk-typescript/blob/d3be31f5a4e6ebb4c0a2f65dbb8f381ae73a9166/helpers.md?plain=1#L42-L44 stream.on('message', () => { - finalizeStreamSpan(state, span, recordOutputs); + endStreamSpan(span, state, recordOutputs); }); stream.on('error', (error: unknown) => { diff --git a/packages/core/src/tracing/dynamicSamplingContext.ts b/packages/core/src/tracing/dynamicSamplingContext.ts index 47d5657a7d87..7cf79e53d07b 100644 --- a/packages/core/src/tracing/dynamicSamplingContext.ts +++ b/packages/core/src/tracing/dynamicSamplingContext.ts @@ -119,7 +119,8 @@ export function getDynamicSamplingContextFromSpan(span: Span): Readonly( context: unknown, options: GoogleGenAIOptions, ): (...args: T) => R | Promise { - const isSyncCreate = methodPath === CHATS_CREATE_METHOD; const isEmbeddings = instrumentedMethod.operation === 'embeddings'; return new Proxy(originalMethod, { apply(target, _, args: T): R | Promise { - const operationName = instrumentedMethod.operation; + const operationName = instrumentedMethod.operation || 'unknown'; const params = args[0] as Record | undefined; const requestAttributes = extractRequestAttributes(operationName, params, context); const model = requestAttributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] ?? 'unknown'; @@ -308,7 +307,7 @@ function instrumentMethod( // Single span for both sync and async operations return startSpan( { - name: isSyncCreate ? `${operationName} ${model} create` : `${operationName} ${model}`, + name: `${operationName} ${model}`, op: `gen_ai.${operationName}`, attributes: requestAttributes, }, @@ -326,8 +325,8 @@ function instrumentMethod( }, () => {}, result => { - // Only add response attributes for content-producing methods, not for chats.create or embeddings - if (!isSyncCreate && !isEmbeddings) { + // Only add response attributes for content-producing methods, not for embeddings + if (!isEmbeddings) { addResponseAttributes(span, result, options.recordOutputs); } }, @@ -348,34 +347,29 @@ function createDeepProxy(target: T, currentPath = '', options: const value = Reflect.get(t, prop, receiver); const methodPath = buildMethodPath(currentPath, String(prop)); - const instrumentedMethod = GOOGLE_GENAI_METHOD_REGISTRY[methodPath as keyof typeof GOOGLE_GENAI_METHOD_REGISTRY]; + const instrumentedMethod: InstrumentedMethodEntry | undefined = + GOOGLE_GENAI_METHOD_REGISTRY[methodPath as keyof typeof GOOGLE_GENAI_METHOD_REGISTRY]; if (typeof value === 'function' && instrumentedMethod) { - // Special case: chats.create is synchronous but needs both instrumentation AND result proxying - if (methodPath === CHATS_CREATE_METHOD) { - const wrappedMethod = instrumentMethod( - value as (...args: unknown[]) => unknown, - methodPath, - instrumentedMethod, - t, - options, - ); - return function instrumentedAndProxiedCreate(...args: unknown[]): unknown { - const result = wrappedMethod(...args); - // If the result is an object (like a chat instance), proxy it too - if (result && typeof result === 'object') { - return createDeepProxy(result, CHAT_PATH, options); - } - return result; - }; + // If an operation is specified, we need to instrument the method itself + const wrappedMethod = instrumentedMethod.operation + ? instrumentMethod(value as (...args: unknown[]) => unknown, methodPath, instrumentedMethod, t, options) + : value.bind(t); + + if (!instrumentedMethod.proxyResultPath) { + return wrappedMethod; } - return instrumentMethod( - value as (...args: unknown[]) => Promise, - methodPath, - instrumentedMethod, - t, - options, - ); + // If a proxyResultPath is specified, we need to proxy the result of the method. + // Note: This currently only properly handles synchronous methods. For async methods, + // the Promise itself would be proxied instead of the resolved value. Currently we + // don't have a case where this is needed, so I'll keep it simple for now. + return function (...args: unknown[]): unknown { + const result = wrappedMethod(...args); + if (result && typeof result === 'object') { + return createDeepProxy(result as object, instrumentedMethod.proxyResultPath, options); + } + return result; + }; } if (typeof value === 'function') { diff --git a/packages/core/src/tracing/google-genai/streaming.ts b/packages/core/src/tracing/google-genai/streaming.ts index d3f6598b8fd7..4a308d922eb9 100644 --- a/packages/core/src/tracing/google-genai/streaming.ts +++ b/packages/core/src/tracing/google-genai/streaming.ts @@ -1,17 +1,7 @@ import { captureException } from '../../exports'; import { SPAN_STATUS_ERROR } from '../../tracing'; -import type { Span, SpanAttributeValue } from '../../types-hoist/span'; -import { - GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE, - GEN_AI_RESPONSE_ID_ATTRIBUTE, - GEN_AI_RESPONSE_MODEL_ATTRIBUTE, - GEN_AI_RESPONSE_STREAMING_ATTRIBUTE, - GEN_AI_RESPONSE_TEXT_ATTRIBUTE, - GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE, - GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE, - GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE, - GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE, -} from '../ai/gen-ai-attributes'; +import type { Span } from '../../types-hoist/span'; +import { endStreamSpan } from '../ai/utils'; import type { GoogleGenAIResponse } from './types'; /** @@ -137,27 +127,6 @@ export async function* instrumentStream( yield chunk; } } finally { - const attrs: Record = { - [GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true, - }; - - if (state.responseId) attrs[GEN_AI_RESPONSE_ID_ATTRIBUTE] = state.responseId; - if (state.responseModel) attrs[GEN_AI_RESPONSE_MODEL_ATTRIBUTE] = state.responseModel; - if (state.promptTokens !== undefined) attrs[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE] = state.promptTokens; - if (state.completionTokens !== undefined) attrs[GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE] = state.completionTokens; - if (state.totalTokens !== undefined) attrs[GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE] = state.totalTokens; - - if (state.finishReasons.length) { - attrs[GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE] = JSON.stringify(state.finishReasons); - } - if (recordOutputs && state.responseTexts.length) { - attrs[GEN_AI_RESPONSE_TEXT_ATTRIBUTE] = state.responseTexts.join(''); - } - if (recordOutputs && state.toolCalls.length) { - attrs[GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE] = JSON.stringify(state.toolCalls); - } - - span.setAttributes(attrs); - span.end(); + endStreamSpan(span, state, recordOutputs); } } diff --git a/packages/core/src/tracing/index.ts b/packages/core/src/tracing/index.ts index 9997cab3519b..3d3736876015 100644 --- a/packages/core/src/tracing/index.ts +++ b/packages/core/src/tracing/index.ts @@ -23,3 +23,6 @@ export { export { setMeasurement, timedEventsToMeasurements } from './measurement'; export { sampleSpan } from './sampling'; export { logSpanEnd, logSpanStart } from './logSpans'; + +// Span Streaming +export { captureSpan } from './spans/captureSpan'; diff --git a/packages/core/src/tracing/langchain/embeddings.ts b/packages/core/src/tracing/langchain/embeddings.ts new file mode 100644 index 000000000000..b1afb94b9f17 --- /dev/null +++ b/packages/core/src/tracing/langchain/embeddings.ts @@ -0,0 +1,136 @@ +import { captureException } from '../../exports'; +import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '../../semanticAttributes'; +import { startSpan } from '../../tracing/trace'; +import type { SpanAttributeValue } from '../../types-hoist/span'; +import { + GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE, + GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE, + GEN_AI_OPERATION_NAME_ATTRIBUTE, + GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE, + GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE, + GEN_AI_REQUEST_MODEL_ATTRIBUTE, + GEN_AI_SYSTEM_ATTRIBUTE, +} from '../ai/gen-ai-attributes'; +import { resolveAIRecordingOptions } from '../ai/utils'; +import { LANGCHAIN_ORIGIN } from './constants'; +import type { LangChainOptions } from './types'; + +/** + * Infers the AI provider system name from the embedding class instance. + */ +function inferSystemFromInstance(instance: Record): string { + const name = (instance.constructor as { name?: string })?.name ?? ''; + if (name.includes('OpenAI')) return 'openai'; + if (name.includes('Google')) return 'google_genai'; + if (name.includes('Mistral')) return 'mistralai'; + if (name.includes('Vertex')) return 'google_vertexai'; + if (name.includes('Bedrock')) return 'aws_bedrock'; + if (name.includes('Ollama')) return 'ollama'; + if (name.includes('Cloudflare')) return 'cloudflare'; + if (name.includes('Cohere')) return 'cohere'; + return 'langchain'; +} + +/** + * Extracts span attributes from a LangChain embedding class instance. + */ +function extractEmbeddingAttributes(instance: unknown): Record { + const embeddingsInstance = (instance ?? {}) as Record; + + const attributes: Record = { + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: LANGCHAIN_ORIGIN, + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE, + [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'embeddings', + [GEN_AI_REQUEST_MODEL_ATTRIBUTE]: embeddingsInstance.model ?? 'unknown', + }; + + attributes[GEN_AI_SYSTEM_ATTRIBUTE] = inferSystemFromInstance(embeddingsInstance); + if ('dimensions' in embeddingsInstance) { + attributes[GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE] = embeddingsInstance.dimensions; + } + if ('encodingFormat' in embeddingsInstance) { + attributes[GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE] = embeddingsInstance.encodingFormat; + } + + return attributes; +} + +/** + * Wraps a LangChain embedding method (embedQuery or embedDocuments) to create Sentry spans. + * + * Used internally by the Node.js auto-instrumentation to patch embedding class prototypes. + */ +export function instrumentEmbeddingMethod( + originalMethod: (...args: unknown[]) => Promise, + options: LangChainOptions = {}, +): (...args: unknown[]) => Promise { + const { recordInputs } = resolveAIRecordingOptions(options); + + return new Proxy(originalMethod, { + apply(target, thisArg, args: unknown[]): Promise { + const attributes = extractEmbeddingAttributes(thisArg); + const modelName = attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] || 'unknown'; + + if (recordInputs) { + const input = args[0]; + if (input != null) { + attributes[GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE] = typeof input === 'string' ? input : JSON.stringify(input); + } + } + + return startSpan( + { + name: `embeddings ${modelName}`, + op: GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE, + attributes: attributes as Record, + }, + () => { + return Reflect.apply(target, thisArg, args).then(undefined, error => { + captureException(error, { + mechanism: { handled: false, type: 'auto.ai.langchain' }, + }); + throw error; + }); + }, + ); + }, + }) as (...args: unknown[]) => Promise; +} + +/** + * Wraps a LangChain embeddings instance to create Sentry spans for `embedQuery` and `embedDocuments` calls. + * + * Use this in non-Node runtimes (Cloudflare, browser, etc.) where auto-instrumentation is not available. + * + * @example + * ```javascript + * import * as Sentry from '@sentry/cloudflare'; + * import { OpenAIEmbeddings } from '@langchain/openai'; + * + * const embeddings = Sentry.instrumentLangChainEmbeddings( + * new OpenAIEmbeddings({ model: 'text-embedding-3-small' }) + * ); + * + * await embeddings.embedQuery('Hello world'); + * await embeddings.embedDocuments(['doc1', 'doc2']); + * ``` + */ +export function instrumentLangChainEmbeddings(instance: T, options?: LangChainOptions): T { + const embeddingsInstance = instance as Record; + + if (typeof embeddingsInstance.embedQuery === 'function') { + embeddingsInstance.embedQuery = instrumentEmbeddingMethod( + embeddingsInstance.embedQuery as (...args: unknown[]) => Promise, + options, + ); + } + + if (typeof embeddingsInstance.embedDocuments === 'function') { + embeddingsInstance.embedDocuments = instrumentEmbeddingMethod( + embeddingsInstance.embedDocuments as (...args: unknown[]) => Promise, + options, + ); + } + + return instance; +} diff --git a/packages/core/src/tracing/langchain/index.ts b/packages/core/src/tracing/langchain/index.ts index 0984131e4296..16257acebbd7 100644 --- a/packages/core/src/tracing/langchain/index.ts +++ b/packages/core/src/tracing/langchain/index.ts @@ -334,3 +334,5 @@ export function createLangChainCallbackHandler(options: LangChainOptions = {}): return handler; } + +export { instrumentLangChainEmbeddings } from './embeddings'; diff --git a/packages/core/src/tracing/openai/index.ts b/packages/core/src/tracing/openai/index.ts index 0f83bf2cd3eb..dc728cbe806f 100644 --- a/packages/core/src/tracing/openai/index.ts +++ b/packages/core/src/tracing/openai/index.ts @@ -12,7 +12,6 @@ import { GEN_AI_OPERATION_NAME_ATTRIBUTE, GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE, GEN_AI_REQUEST_MODEL_ATTRIBUTE, - GEN_AI_RESPONSE_TEXT_ATTRIBUTE, GEN_AI_SYSTEM_ATTRIBUTE, GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE, } from '../ai/gen-ai-attributes'; @@ -26,18 +25,8 @@ import { } from '../ai/utils'; import { OPENAI_METHOD_REGISTRY } from './constants'; import { instrumentStream } from './streaming'; -import type { ChatCompletionChunk, OpenAiOptions, OpenAiResponse, OpenAIStream, ResponseStreamingEvent } from './types'; -import { - addChatCompletionAttributes, - addConversationAttributes, - addEmbeddingsAttributes, - addResponsesApiAttributes, - extractRequestParameters, - isChatCompletionResponse, - isConversationResponse, - isEmbeddingsResponse, - isResponsesApiResponse, -} from './utils'; +import type { ChatCompletionChunk, OpenAiOptions, OpenAIStream, ResponseStreamingEvent } from './types'; +import { addResponseAttributes, extractRequestParameters } from './utils'; /** * Extract available tools from request parameters @@ -88,33 +77,6 @@ function extractRequestAttributes(args: unknown[], operationName: string): Recor return attributes; } -/** - * Add response attributes to spans - * This supports Chat Completion, Responses API, Embeddings, and Conversations API responses - */ -function addResponseAttributes(span: Span, result: unknown, recordOutputs?: boolean): void { - if (!result || typeof result !== 'object') return; - - const response = result as OpenAiResponse; - - if (isChatCompletionResponse(response)) { - addChatCompletionAttributes(span, response, recordOutputs); - if (recordOutputs && response.choices?.length) { - const responseTexts = response.choices.map(choice => choice.message?.content || ''); - span.setAttributes({ [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: JSON.stringify(responseTexts) }); - } - } else if (isResponsesApiResponse(response)) { - addResponsesApiAttributes(span, response, recordOutputs); - if (recordOutputs && response.output_text) { - span.setAttributes({ [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: response.output_text }); - } - } else if (isEmbeddingsResponse(response)) { - addEmbeddingsAttributes(span, response); - } else if (isConversationResponse(response)) { - addConversationAttributes(span, response); - } -} - // Extract and record AI request inputs, if present. This is intentionally separate from response attributes. function addRequestAttributes(span: Span, params: Record, operationName: string): void { // Store embeddings input on a separate attribute and do not truncate it @@ -180,7 +142,7 @@ function instrumentMethod( options: OpenAiOptions, ): (...args: T) => Promise { return function instrumentedCall(...args: T): Promise { - const operationName = instrumentedMethod.operation; + const operationName = instrumentedMethod.operation || 'unknown'; const requestAttributes = extractRequestAttributes(args, operationName); const model = (requestAttributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] as string) || 'unknown'; diff --git a/packages/core/src/tracing/openai/streaming.ts b/packages/core/src/tracing/openai/streaming.ts index 3a5634df34dd..d51c47cad228 100644 --- a/packages/core/src/tracing/openai/streaming.ts +++ b/packages/core/src/tracing/openai/streaming.ts @@ -1,12 +1,7 @@ import { captureException } from '../../exports'; import { SPAN_STATUS_ERROR } from '../../tracing'; import type { Span } from '../../types-hoist/span'; -import { - GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE, - GEN_AI_RESPONSE_STREAMING_ATTRIBUTE, - GEN_AI_RESPONSE_TEXT_ATTRIBUTE, - GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE, -} from '../ai/gen-ai-attributes'; +import { endStreamSpan } from '../ai/utils'; import { RESPONSE_EVENT_TYPES } from './constants'; import type { ChatCompletionChunk, @@ -15,12 +10,7 @@ import type { ResponseFunctionCall, ResponseStreamingEvent, } from './types'; -import { - isChatCompletionChunk, - isResponsesApiStreamEvent, - setCommonResponseAttributes, - setTokenUsageAttributes, -} from './utils'; +import { isChatCompletionChunk, isResponsesApiStreamEvent } from './utils'; /** * State object used to accumulate information from a stream of OpenAI events/chunks. @@ -36,8 +26,6 @@ interface StreamingState { responseId: string; /** The model name. */ responseModel: string; - /** The timestamp of the response. */ - responseTimestamp: number; /** Number of prompt/input tokens used. */ promptTokens: number | undefined; /** Number of completion/output tokens used. */ @@ -99,7 +87,6 @@ function processChatCompletionToolCalls(toolCalls: ChatCompletionToolCall[], sta function processChatCompletionChunk(chunk: ChatCompletionChunk, state: StreamingState, recordOutputs: boolean): void { state.responseId = chunk.id ?? state.responseId; state.responseModel = chunk.model ?? state.responseModel; - state.responseTimestamp = chunk.created ?? state.responseTimestamp; if (chunk.usage) { // For stream responses, the input tokens remain constant across all events in the stream. @@ -183,7 +170,6 @@ function processResponsesApiEvent( const { response } = event as { response: OpenAIResponseObject }; state.responseId = response.id ?? state.responseId; state.responseModel = response.model ?? state.responseModel; - state.responseTimestamp = response.created_at ?? state.responseTimestamp; if (response.usage) { // For stream responses, the input tokens remain constant across all events in the stream. @@ -227,7 +213,6 @@ export async function* instrumentStream( finishReasons: [], responseId: '', responseModel: '', - responseTimestamp: 0, promptTokens: undefined, completionTokens: undefined, totalTokens: undefined, @@ -245,35 +230,7 @@ export async function* instrumentStream( yield event; } } finally { - setCommonResponseAttributes(span, state.responseId, state.responseModel, state.responseTimestamp); - setTokenUsageAttributes(span, state.promptTokens, state.completionTokens, state.totalTokens); - - span.setAttributes({ - [GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true, - }); - - if (state.finishReasons.length) { - span.setAttributes({ - [GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE]: JSON.stringify(state.finishReasons), - }); - } - - if (recordOutputs && state.responseTexts.length) { - span.setAttributes({ - [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: state.responseTexts.join(''), - }); - } - - // Set tool calls attribute if any were accumulated - const chatCompletionToolCallsArray = Object.values(state.chatCompletionToolCalls); - const allToolCalls = [...chatCompletionToolCallsArray, ...state.responsesApiToolCalls]; - - if (allToolCalls.length > 0) { - span.setAttributes({ - [GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(allToolCalls), - }); - } - - span.end(); + const allToolCalls = [...Object.values(state.chatCompletionToolCalls), ...state.responsesApiToolCalls]; + endStreamSpan(span, { ...state, toolCalls: allToolCalls }, recordOutputs); } } diff --git a/packages/core/src/tracing/openai/utils.ts b/packages/core/src/tracing/openai/utils.ts index e7ad110e00bb..ded7b3ff0e3b 100644 --- a/packages/core/src/tracing/openai/utils.ts +++ b/packages/core/src/tracing/openai/utils.ts @@ -1,4 +1,5 @@ import type { Span } from '../../types-hoist/span'; +import type { SpanAttributeValue } from '../../types-hoist/span'; import { GEN_AI_CONVERSATION_ID_ATTRIBUTE, GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE, @@ -12,76 +13,13 @@ import { GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE, GEN_AI_RESPONSE_ID_ATTRIBUTE, GEN_AI_RESPONSE_MODEL_ATTRIBUTE, + GEN_AI_RESPONSE_TEXT_ATTRIBUTE, GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE, GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE, - OPENAI_RESPONSE_ID_ATTRIBUTE, - OPENAI_RESPONSE_MODEL_ATTRIBUTE, - OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE, - OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE, - OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE, } from '../ai/gen-ai-attributes'; -import type { - ChatCompletionChunk, - OpenAiChatCompletionObject, - OpenAIConversationObject, - OpenAICreateEmbeddingsObject, - OpenAIResponseObject, - ResponseStreamingEvent, -} from './types'; - -/** - * Check if response is a Chat Completion object - */ -export function isChatCompletionResponse(response: unknown): response is OpenAiChatCompletionObject { - return ( - response !== null && - typeof response === 'object' && - 'object' in response && - (response as Record).object === 'chat.completion' - ); -} - -/** - * Check if response is a Responses API object - */ -export function isResponsesApiResponse(response: unknown): response is OpenAIResponseObject { - return ( - response !== null && - typeof response === 'object' && - 'object' in response && - (response as Record).object === 'response' - ); -} - -/** - * Check if response is an Embeddings API object - */ -export function isEmbeddingsResponse(response: unknown): response is OpenAICreateEmbeddingsObject { - if (response === null || typeof response !== 'object' || !('object' in response)) { - return false; - } - const responseObject = response as Record; - return ( - responseObject.object === 'list' && - typeof responseObject.model === 'string' && - responseObject.model.toLowerCase().includes('embedding') - ); -} - -/** - * Check if response is a Conversations API object - * @see https://platform.openai.com/docs/api-reference/conversations - */ -export function isConversationResponse(response: unknown): response is OpenAIConversationObject { - return ( - response !== null && - typeof response === 'object' && - 'object' in response && - (response as Record).object === 'conversation' - ); -} +import type { ChatCompletionChunk, ResponseStreamingEvent } from './types'; /** * Check if streaming event is from the Responses API @@ -109,173 +47,108 @@ export function isChatCompletionChunk(event: unknown): event is ChatCompletionCh } /** - * Add attributes for Chat Completion responses + * Add response attributes to a span using duck-typing. + * Works for Chat Completions, Responses API, Embeddings, and Conversations API responses. */ -export function addChatCompletionAttributes( - span: Span, - response: OpenAiChatCompletionObject, - recordOutputs?: boolean, -): void { - setCommonResponseAttributes(span, response.id, response.model, response.created); - if (response.usage) { - setTokenUsageAttributes( - span, - response.usage.prompt_tokens, - response.usage.completion_tokens, - response.usage.total_tokens, - ); +export function addResponseAttributes(span: Span, result: unknown, recordOutputs?: boolean): void { + if (!result || typeof result !== 'object') return; + + const response = result as Record; + const attrs: Record = {}; + + // Response ID + if (typeof response.id === 'string') { + attrs[GEN_AI_RESPONSE_ID_ATTRIBUTE] = response.id; + } + + // Response model + if (typeof response.model === 'string') { + attrs[GEN_AI_RESPONSE_MODEL_ATTRIBUTE] = response.model; + } + + // Conversation ID (conversation objects use id as conversation link) + if (response.object === 'conversation' && typeof response.id === 'string') { + attrs[GEN_AI_CONVERSATION_ID_ATTRIBUTE] = response.id; } + + // Token usage — supports both naming conventions (chat: prompt_tokens/completion_tokens, responses: input_tokens/output_tokens) + if (response.usage && typeof response.usage === 'object') { + const usage = response.usage as Record; + + const inputTokens = usage.prompt_tokens ?? usage.input_tokens; + if (typeof inputTokens === 'number') { + attrs[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE] = inputTokens; + } + + const outputTokens = usage.completion_tokens ?? usage.output_tokens; + if (typeof outputTokens === 'number') { + attrs[GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE] = outputTokens; + } + + if (typeof usage.total_tokens === 'number') { + attrs[GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE] = usage.total_tokens; + } + } + + // Finish reasons from choices (chat completions) if (Array.isArray(response.choices)) { - const finishReasons = response.choices + const choices = response.choices as Array>; + const finishReasons = choices .map(choice => choice.finish_reason) - .filter((reason): reason is string => reason !== null); + .filter((reason): reason is string => typeof reason === 'string'); if (finishReasons.length > 0) { - span.setAttributes({ - [GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE]: JSON.stringify(finishReasons), - }); + attrs[GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE] = JSON.stringify(finishReasons); } - // Extract tool calls from all choices (only if recordOutputs is true) if (recordOutputs) { - const toolCalls = response.choices - .map(choice => choice.message?.tool_calls) + // Response text from choices + const responseTexts = choices.map(choice => { + const message = choice.message as Record | undefined; + return (message?.content as string) || ''; + }); + attrs[GEN_AI_RESPONSE_TEXT_ATTRIBUTE] = JSON.stringify(responseTexts); + + // Tool calls from choices + const toolCalls = choices + .map(choice => { + const message = choice.message as Record | undefined; + return message?.tool_calls; + }) .filter(calls => Array.isArray(calls) && calls.length > 0) .flat(); if (toolCalls.length > 0) { - span.setAttributes({ - [GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(toolCalls), - }); + attrs[GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE] = JSON.stringify(toolCalls); } } } -} -/** - * Add attributes for Responses API responses - */ -export function addResponsesApiAttributes(span: Span, response: OpenAIResponseObject, recordOutputs?: boolean): void { - setCommonResponseAttributes(span, response.id, response.model, response.created_at); - if (response.status) { - span.setAttributes({ - [GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE]: JSON.stringify([response.status]), - }); - } - if (response.usage) { - setTokenUsageAttributes( - span, - response.usage.input_tokens, - response.usage.output_tokens, - response.usage.total_tokens, - ); + // Finish reason from status (responses API) + if (typeof response.status === 'string') { + // Only set if not already set from choices + if (!attrs[GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE]) { + attrs[GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE] = JSON.stringify([response.status]); + } } - // Extract function calls from output (only if recordOutputs is true) if (recordOutputs) { - const responseWithOutput = response as OpenAIResponseObject & { output?: unknown[] }; - if (Array.isArray(responseWithOutput.output) && responseWithOutput.output.length > 0) { - // Filter for function_call type objects in the output array - const functionCalls = responseWithOutput.output.filter( - (item): unknown => - // oxlint-disable-next-line typescript/prefer-optional-chain - typeof item === 'object' && item !== null && (item as Record).type === 'function_call', - ); + // Response text from output_text (responses API) + if (typeof response.output_text === 'string' && !attrs[GEN_AI_RESPONSE_TEXT_ATTRIBUTE]) { + attrs[GEN_AI_RESPONSE_TEXT_ATTRIBUTE] = response.output_text; + } + // Tool calls from output array (responses API) + if (Array.isArray(response.output) && response.output.length > 0 && !attrs[GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]) { + const functionCalls = (response.output as Array>).filter( + item => item?.type === 'function_call', + ); if (functionCalls.length > 0) { - span.setAttributes({ - [GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(functionCalls), - }); + attrs[GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE] = JSON.stringify(functionCalls); } } } -} - -/** - * Add attributes for Embeddings API responses - */ -export function addEmbeddingsAttributes(span: Span, response: OpenAICreateEmbeddingsObject): void { - span.setAttributes({ - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: response.model, - [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: response.model, - }); - - if (response.usage) { - setTokenUsageAttributes(span, response.usage.prompt_tokens, undefined, response.usage.total_tokens); - } -} - -/** - * Add attributes for Conversations API responses - * @see https://platform.openai.com/docs/api-reference/conversations - */ -export function addConversationAttributes(span: Span, response: OpenAIConversationObject): void { - const { id, created_at } = response; - - span.setAttributes({ - [OPENAI_RESPONSE_ID_ATTRIBUTE]: id, - [GEN_AI_RESPONSE_ID_ATTRIBUTE]: id, - // The conversation id is used to link messages across API calls - [GEN_AI_CONVERSATION_ID_ATTRIBUTE]: id, - }); - - if (created_at) { - span.setAttributes({ - [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: new Date(created_at * 1000).toISOString(), - }); - } -} - -/** - * Set token usage attributes - * @param span - The span to add attributes to - * @param promptTokens - The number of prompt tokens - * @param completionTokens - The number of completion tokens - * @param totalTokens - The number of total tokens - */ -export function setTokenUsageAttributes( - span: Span, - promptTokens?: number, - completionTokens?: number, - totalTokens?: number, -): void { - if (promptTokens !== undefined) { - span.setAttributes({ - [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: promptTokens, - [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: promptTokens, - }); - } - if (completionTokens !== undefined) { - span.setAttributes({ - [OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: completionTokens, - [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: completionTokens, - }); - } - if (totalTokens !== undefined) { - span.setAttributes({ - [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: totalTokens, - }); - } -} -/** - * Set common response attributes - * @param span - The span to add attributes to - * @param id - The response id - * @param model - The response model - * @param timestamp - The response timestamp - */ -export function setCommonResponseAttributes(span: Span, id: string, model: string, timestamp: number): void { - span.setAttributes({ - [OPENAI_RESPONSE_ID_ATTRIBUTE]: id, - [GEN_AI_RESPONSE_ID_ATTRIBUTE]: id, - }); - span.setAttributes({ - [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: model, - [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: model, - }); - span.setAttributes({ - [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: new Date(timestamp * 1000).toISOString(), - }); + span.setAttributes(attrs); } /** diff --git a/packages/core/src/tracing/sentryNonRecordingSpan.ts b/packages/core/src/tracing/sentryNonRecordingSpan.ts index 2f65e0eb8c08..c1f01182b248 100644 --- a/packages/core/src/tracing/sentryNonRecordingSpan.ts +++ b/packages/core/src/tracing/sentryNonRecordingSpan.ts @@ -1,3 +1,4 @@ +import type { EventDropReason } from '../types-hoist/clientreport'; import type { SentrySpanArguments, Span, @@ -10,6 +11,10 @@ import type { SpanStatus } from '../types-hoist/spanStatus'; import { generateSpanId, generateTraceId } from '../utils/propagationContext'; import { TRACE_FLAG_NONE } from '../utils/spanUtils'; +interface SentryNonRecordingSpanArguments extends SentrySpanArguments { + dropReason?: EventDropReason; +} + /** * A Sentry Span that is non-recording, meaning it will not be sent to Sentry. */ @@ -17,9 +22,17 @@ export class SentryNonRecordingSpan implements Span { private _traceId: string; private _spanId: string; - public constructor(spanContext: SentrySpanArguments = {}) { + /** + * Reason why this span was dropped, if applicable ('ignored' or 'sample_rate'). + * Used to propagate the correct client report outcome to descendant spans + * when span streaming is enabled. + */ + public dropReason?: EventDropReason; + + public constructor(spanContext: SentryNonRecordingSpanArguments = {}) { this._traceId = spanContext.traceId || generateTraceId(); this._spanId = spanContext.spanId || generateSpanId(); + this.dropReason = spanContext.dropReason; } /** @inheritdoc */ diff --git a/packages/core/src/tracing/sentrySpan.ts b/packages/core/src/tracing/sentrySpan.ts index 9bd98b9741c6..d9ab115b94cd 100644 --- a/packages/core/src/tracing/sentrySpan.ts +++ b/packages/core/src/tracing/sentrySpan.ts @@ -1,3 +1,4 @@ +/* eslint-disable max-lines */ import { getClient, getCurrentScope } from '../currentScopes'; import { DEBUG_BUILD } from '../debug-build'; import { createSpanEnvelope } from '../envelope'; @@ -21,6 +22,7 @@ import type { SpanJSON, SpanOrigin, SpanTimeInput, + StreamedSpanJSON, } from '../types-hoist/span'; import type { SpanStatus } from '../types-hoist/spanStatus'; import type { TimedEvent } from '../types-hoist/timedEvent'; @@ -29,8 +31,10 @@ import { generateSpanId, generateTraceId } from '../utils/propagationContext'; import { convertSpanLinksForEnvelope, getRootSpan, + getSimpleStatusMessage, getSpanDescendants, getStatusMessage, + getStreamedSpanLinks, spanTimeInputToSeconds, spanToJSON, spanToTransactionTraceContext, @@ -41,6 +45,7 @@ import { timestampInSeconds } from '../utils/time'; import { getDynamicSamplingContextFromSpan } from './dynamicSamplingContext'; import { logSpanEnd } from './logSpans'; import { timedEventsToMeasurements } from './measurement'; +import { hasSpanStreamingEnabled } from './spans/hasSpanStreamingEnabled'; import { getCapturedScopesOnSpan } from './utils'; const MAX_SPAN_COUNT = 1000; @@ -241,6 +246,30 @@ export class SentrySpan implements Span { }; } + /** + * Get {@link StreamedSpanJSON} representation of this span. + * + * @hidden + * @internal This method is purely for internal purposes and should not be used outside + * of SDK code. If you need to get a JSON representation of a span, + * use `spanToStreamedSpanJSON(span)` instead. + */ + public getStreamedSpanJSON(): StreamedSpanJSON { + return { + name: this._name ?? '', + span_id: this._spanId, + trace_id: this._traceId, + parent_span_id: this._parentSpanId, + start_timestamp: this._startTime, + // just in case _endTime is not set, we use the start time (i.e. duration 0) + end_timestamp: this._endTime ?? this._startTime, + is_segment: this._isStandaloneSpan || this === getRootSpan(this), + status: getSimpleStatusMessage(this._status), + attributes: this._attributes, + links: getStreamedSpanLinks(this._links), + }; + } + /** @inheritdoc */ public isRecording(): boolean { return !this._endTime && !!this._sampled; @@ -287,6 +316,14 @@ export class SentrySpan implements Span { const client = getClient(); if (client) { client.emit('spanEnd', this); + // Guarding sending standalone v1 spans as v2 streamed spans for now. + // Otherwise they'd be sent once as v1 spans and again as streamed spans. + // We'll migrate CLS and LCP spans to streamed spans in a later PR and + // INP spans in the next major of the SDK. At that point, we can fully remove + // standalone v1 spans <3 + if (!this._isStandaloneSpan) { + client.emit('afterSpanEnd', this); + } } // A segment span is basically the root span of a local span tree. @@ -310,6 +347,10 @@ export class SentrySpan implements Span { } } return; + } else if (client && hasSpanStreamingEnabled(client)) { + // TODO (spans): Remove standalone span custom logic in favor of sending simple v2 web vital spans + client.emit('afterSegmentSpanEnd', this); + return; } const transactionEvent = this._convertSpanToTransaction(); diff --git a/packages/core/src/tracing/spans/README.md b/packages/core/src/tracing/spans/README.md new file mode 100644 index 000000000000..fa40e8a0ff11 --- /dev/null +++ b/packages/core/src/tracing/spans/README.md @@ -0,0 +1,2 @@ +For now, all span streaming related tracing code is in this sub directory. +Once we get rid of transaction-based tracing, we can clean up and flatten the entire tracing directory. diff --git a/packages/core/src/tracing/spans/beforeSendSpan.ts b/packages/core/src/tracing/spans/beforeSendSpan.ts new file mode 100644 index 000000000000..28b1849c7779 --- /dev/null +++ b/packages/core/src/tracing/spans/beforeSendSpan.ts @@ -0,0 +1,42 @@ +import type { CoreOptions } from '../../types-hoist/options'; +import type { BeforeSendStreamedSpanCallback } from '../../types-hoist/options'; +import type { StreamedSpanJSON } from '../../types-hoist/span'; +import { addNonEnumerableProperty } from '../../utils/object'; + +type StaticBeforeSendSpanCallback = CoreOptions['beforeSendSpan']; + +/** + * A wrapper to use the new span format in your `beforeSendSpan` callback. + * + * When using `traceLifecycle: 'stream'`, wrap your callback with this function + * to receive and return {@link StreamedSpanJSON} instead of the standard {@link SpanJSON}. + * + * @example + * + * Sentry.init({ + * traceLifecycle: 'stream', + * beforeSendSpan: withStreamedSpan((span) => { + * // span is of type StreamedSpanJSON + * return span; + * }), + * }); + * + * @param callback - The callback function that receives and returns a {@link StreamedSpanJSON}. + * @returns A callback that is compatible with the `beforeSendSpan` option when using `traceLifecycle: 'stream'`. + */ +export function withStreamedSpan( + callback: (span: StreamedSpanJSON) => StreamedSpanJSON, +): StaticBeforeSendSpanCallback & { _streamed: true } { + addNonEnumerableProperty(callback, '_streamed', true); + return callback as unknown as StaticBeforeSendSpanCallback & { _streamed: true }; +} + +/** + * Typesafe check to identify if a `beforeSendSpan` callback expects the streamed span JSON format. + * + * @param callback - The `beforeSendSpan` callback to check. + * @returns `true` if the callback was wrapped with {@link withStreamedSpan}. + */ +export function isStreamedBeforeSendSpanCallback(callback: unknown): callback is BeforeSendStreamedSpanCallback { + return !!callback && typeof callback === 'function' && '_streamed' in callback && !!callback._streamed; +} diff --git a/packages/core/src/tracing/spans/captureSpan.ts b/packages/core/src/tracing/spans/captureSpan.ts new file mode 100644 index 000000000000..979c7b460af1 --- /dev/null +++ b/packages/core/src/tracing/spans/captureSpan.ts @@ -0,0 +1,150 @@ +import type { RawAttributes } from '../../attributes'; +import type { Client } from '../../client'; +import type { ScopeData } from '../../scope'; +import { + SEMANTIC_ATTRIBUTE_SENTRY_ENVIRONMENT, + SEMANTIC_ATTRIBUTE_SENTRY_RELEASE, + SEMANTIC_ATTRIBUTE_SENTRY_SDK_NAME, + SEMANTIC_ATTRIBUTE_SENTRY_SDK_VERSION, + SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID, + SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME, + SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, + SEMANTIC_ATTRIBUTE_USER_EMAIL, + SEMANTIC_ATTRIBUTE_USER_ID, + SEMANTIC_ATTRIBUTE_USER_IP_ADDRESS, + SEMANTIC_ATTRIBUTE_USER_USERNAME, +} from '../../semanticAttributes'; +import type { SerializedStreamedSpan, Span, StreamedSpanJSON } from '../../types-hoist/span'; +import { getCombinedScopeData } from '../../utils/scopeData'; +import { + INTERNAL_getSegmentSpan, + showSpanDropWarning, + spanToStreamedSpanJSON, + streamedSpanJsonToSerializedSpan, +} from '../../utils/spanUtils'; +import { getCapturedScopesOnSpan } from '../utils'; +import { isStreamedBeforeSendSpanCallback } from './beforeSendSpan'; + +export type SerializedStreamedSpanWithSegmentSpan = SerializedStreamedSpan & { + _segmentSpan: Span; +}; + +/** + * Captures a span and returns a JSON representation to be enqueued for sending. + * + * IMPORTANT: This function converts the span to JSON immediately to avoid writing + * to an already-ended OTel span instance (which is blocked by the OTel Span class). + * + * @returns the final serialized span with a reference to its segment span. This reference + * is needed later on to compute the DSC for the span envelope. + */ +export function captureSpan(span: Span, client: Client): SerializedStreamedSpanWithSegmentSpan { + // Convert to JSON FIRST - we cannot write to an already-ended span + const spanJSON = spanToStreamedSpanJSON(span); + + const segmentSpan = INTERNAL_getSegmentSpan(span); + const serializedSegmentSpan = spanToStreamedSpanJSON(segmentSpan); + + const { isolationScope: spanIsolationScope, scope: spanScope } = getCapturedScopesOnSpan(span); + + const finalScopeData = getCombinedScopeData(spanIsolationScope, spanScope); + + applyCommonSpanAttributes(spanJSON, serializedSegmentSpan, client, finalScopeData); + + if (spanJSON.is_segment) { + applyScopeToSegmentSpan(spanJSON, finalScopeData); + // Allow hook subscribers to mutate the segment span JSON + client.emit('processSegmentSpan', spanJSON); + } + + // Allow hook subscribers to mutate the span JSON + client.emit('processSpan', spanJSON); + + const { beforeSendSpan } = client.getOptions(); + const processedSpan = + beforeSendSpan && isStreamedBeforeSendSpanCallback(beforeSendSpan) + ? applyBeforeSendSpanCallback(spanJSON, beforeSendSpan) + : spanJSON; + + // Backfill sentry.span.source from sentry.source. Only `sentry.span.source` is respected by Sentry. + // TODO(v11): Remove this backfill once we renamed SEMANTIC_ATTRIBUTE_SENTRY_SOURCE to sentry.span.source + const spanNameSource = processedSpan.attributes?.[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]; + if (spanNameSource) { + safeSetSpanJSONAttributes(processedSpan, { + // Purposefully not using a constant defined here like in other attributes: + // This will be the name for SEMANTIC_ATTRIBUTE_SENTRY_SOURCE in v11 + 'sentry.span.source': spanNameSource, + }); + } + + return { + ...streamedSpanJsonToSerializedSpan(processedSpan), + _segmentSpan: segmentSpan, + }; +} + +function applyScopeToSegmentSpan(_segmentSpanJSON: StreamedSpanJSON, _scopeData: ScopeData): void { + // TODO: Apply all scope and request data from auto instrumentation (contexts, request) to segment span + // This will follow in a separate PR +} + +function applyCommonSpanAttributes( + spanJSON: StreamedSpanJSON, + serializedSegmentSpan: StreamedSpanJSON, + client: Client, + scopeData: ScopeData, +): void { + const sdk = client.getSdkMetadata(); + const { release, environment, sendDefaultPii } = client.getOptions(); + + // avoid overwriting any previously set attributes (from users or potentially our SDK instrumentation) + safeSetSpanJSONAttributes(spanJSON, { + [SEMANTIC_ATTRIBUTE_SENTRY_RELEASE]: release, + [SEMANTIC_ATTRIBUTE_SENTRY_ENVIRONMENT]: environment, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME]: serializedSegmentSpan.name, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID]: serializedSegmentSpan.span_id, + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_NAME]: sdk?.sdk?.name, + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_VERSION]: sdk?.sdk?.version, + ...(sendDefaultPii + ? { + [SEMANTIC_ATTRIBUTE_USER_ID]: scopeData.user?.id, + [SEMANTIC_ATTRIBUTE_USER_EMAIL]: scopeData.user?.email, + [SEMANTIC_ATTRIBUTE_USER_IP_ADDRESS]: scopeData.user?.ip_address, + [SEMANTIC_ATTRIBUTE_USER_USERNAME]: scopeData.user?.username, + } + : {}), + ...scopeData.attributes, + }); +} + +/** + * Apply a user-provided beforeSendSpan callback to a span JSON. + */ +export function applyBeforeSendSpanCallback( + span: StreamedSpanJSON, + beforeSendSpan: (span: StreamedSpanJSON) => StreamedSpanJSON, +): StreamedSpanJSON { + const modifedSpan = beforeSendSpan(span); + if (!modifedSpan) { + showSpanDropWarning(); + return span; + } + return modifedSpan; +} + +/** + * Safely set attributes on a span JSON. + * If an attribute already exists, it will not be overwritten. + */ +export function safeSetSpanJSONAttributes( + spanJSON: StreamedSpanJSON, + newAttributes: RawAttributes>, +): void { + const originalAttributes = spanJSON.attributes ?? (spanJSON.attributes = {}); + + Object.entries(newAttributes).forEach(([key, value]) => { + if (value != null && !(key in originalAttributes)) { + originalAttributes[key] = value; + } + }); +} diff --git a/packages/core/src/tracing/spans/envelope.ts b/packages/core/src/tracing/spans/envelope.ts new file mode 100644 index 000000000000..8429b22d7e1c --- /dev/null +++ b/packages/core/src/tracing/spans/envelope.ts @@ -0,0 +1,36 @@ +import type { Client } from '../../client'; +import type { DynamicSamplingContext, SpanContainerItem, StreamedSpanEnvelope } from '../../types-hoist/envelope'; +import type { SerializedStreamedSpan } from '../../types-hoist/span'; +import { dsnToString } from '../../utils/dsn'; +import { createEnvelope, getSdkMetadataForEnvelopeHeader } from '../../utils/envelope'; + +/** + * Creates a span v2 span streaming envelope + */ +export function createStreamedSpanEnvelope( + serializedSpans: Array, + dsc: Partial, + client: Client, +): StreamedSpanEnvelope { + const dsn = client.getDsn(); + const tunnel = client.getOptions().tunnel; + const sdk = getSdkMetadataForEnvelopeHeader(client.getOptions()._metadata); + + const headers: StreamedSpanEnvelope[0] = { + sent_at: new Date().toISOString(), + ...(dscHasRequiredProps(dsc) && { trace: dsc }), + ...(sdk && { sdk }), + ...(!!tunnel && dsn && { dsn: dsnToString(dsn) }), + }; + + const spanContainer: SpanContainerItem = [ + { type: 'span', item_count: serializedSpans.length, content_type: 'application/vnd.sentry.items.span.v2+json' }, + { items: serializedSpans }, + ]; + + return createEnvelope(headers, [spanContainer]); +} + +function dscHasRequiredProps(dsc: Partial): dsc is DynamicSamplingContext { + return !!dsc.trace_id && !!dsc.public_key; +} diff --git a/packages/core/src/tracing/spans/estimateSize.ts b/packages/core/src/tracing/spans/estimateSize.ts new file mode 100644 index 000000000000..7d5781862d62 --- /dev/null +++ b/packages/core/src/tracing/spans/estimateSize.ts @@ -0,0 +1,37 @@ +import { estimateTypedAttributesSizeInBytes } from '../../attributes'; +import type { SerializedStreamedSpan } from '../../types-hoist/span'; + +/** + * Estimates the serialized byte size of a {@link SerializedStreamedSpan}. + * + * Uses 2 bytes per character as a UTF-16 approximation, and 8 bytes per number. + * The estimate is intentionally conservative and may be slightly lower than the + * actual byte size on the wire. + * We compensate for this by setting the span buffers internal limit well below the limit + * of how large an actual span v2 envelope may be. + */ +export function estimateSerializedSpanSizeInBytes(span: SerializedStreamedSpan): number { + /* + * Fixed-size fields are pre-computed as a constant for performance: + * - two timestamps (8 bytes each = 16) + * - is_segment boolean (5 bytes, assumed false for most spans) + * - trace_id – always 32 hex chars (64 bytes) + * - span_id – always 16 hex chars (32 bytes) + * - parent_span_id – 16 hex chars, assumed present for most spans (32 bytes) + * - status "ok" – most common value (8 bytes) + * = 156 bytes total base + */ + let weight = 156; + weight += span.name.length * 2; + weight += estimateTypedAttributesSizeInBytes(span.attributes); + if (span.links && span.links.length > 0) { + // Assumption: Links are roughly equal in number of attributes + // probably not always true but allows us to cut down on runtime + const firstLink = span.links[0]; + const attributes = firstLink?.attributes; + // Fixed size 100 due to span_id, trace_id and sampled flag (see above) + const linkWeight = 100 + (attributes ? estimateTypedAttributesSizeInBytes(attributes) : 0); + weight += linkWeight * span.links.length; + } + return weight; +} diff --git a/packages/core/src/tracing/spans/hasSpanStreamingEnabled.ts b/packages/core/src/tracing/spans/hasSpanStreamingEnabled.ts new file mode 100644 index 000000000000..7d5fa2861c21 --- /dev/null +++ b/packages/core/src/tracing/spans/hasSpanStreamingEnabled.ts @@ -0,0 +1,8 @@ +import type { Client } from '../../client'; + +/** + * Determines if span streaming is enabled for the given client + */ +export function hasSpanStreamingEnabled(client: Client): boolean { + return client.getOptions().traceLifecycle === 'stream'; +} diff --git a/packages/core/src/tracing/spans/spanBuffer.ts b/packages/core/src/tracing/spans/spanBuffer.ts new file mode 100644 index 000000000000..cd011df5ac49 --- /dev/null +++ b/packages/core/src/tracing/spans/spanBuffer.ts @@ -0,0 +1,195 @@ +import type { Client } from '../../client'; +import { DEBUG_BUILD } from '../../debug-build'; +import type { SerializedStreamedSpan } from '../../types-hoist/span'; +import { debug } from '../../utils/debug-logger'; +import { safeUnref } from '../../utils/timer'; +import { getDynamicSamplingContextFromSpan } from '../dynamicSamplingContext'; +import type { SerializedStreamedSpanWithSegmentSpan } from './captureSpan'; +import { createStreamedSpanEnvelope } from './envelope'; +import { estimateSerializedSpanSizeInBytes } from './estimateSize'; + +/** + * We must not send more than 1000 spans in one envelope. + * Otherwise the envelope is dropped by Relay. + */ +const MAX_SPANS_PER_ENVELOPE = 1000; + +const MAX_TRACE_WEIGHT_IN_BYTES = 5_000_000; + +interface TraceBucket { + spans: Set; + size: number; + timeout: ReturnType; +} + +export interface SpanBufferOptions { + /** + * Max spans per trace before auto-flush + * Must not exceed 1000. + * + * @default 1_000 + */ + maxSpanLimit?: number; + + /** + * Per-trace flush timeout in ms. A timeout is started when a trace bucket is first created + * and fires flush() for that specific trace when it expires. + * Must be greater than 0. + * + * @default 5_000 + */ + flushInterval?: number; + + /** + * Max accumulated byte weight of spans per trace before auto-flush. + * Size is estimated, not exact. Uses 2 bytes per character for strings (UTF-16). + * + * @default 5_000_000 (5 MB) + */ + maxTraceWeightInBytes?: number; +} + +/** + * A buffer for serialized streamed span JSON objects that flushes them to Sentry in Span v2 envelopes. + * Handles per-trace timeout-based flushing, size thresholds, and graceful shutdown. + * Also handles computation of the Dynamic Sampling Context (DSC) for the trace, if it wasn't yet + * frozen onto the segment span. + * + * For this, we need the reference to the segment span instance, from + * which we compute the DSC. Doing this in the buffer ensures that we compute the DSC as late as possible, + * allowing span name and data updates up to this point. Worth noting here that the segment span is likely + * still active and modifyable when child spans are added to the buffer. + */ +export class SpanBuffer { + /* Bucket spans by their trace id, along with accumulated size and a per-trace flush timeout */ + private _traceBuckets: Map; + + private _client: Client; + private _maxSpanLimit: number; + private _flushInterval: number; + private _maxTraceWeight: number; + + public constructor(client: Client, options?: SpanBufferOptions) { + this._traceBuckets = new Map(); + this._client = client; + + const { maxSpanLimit, flushInterval, maxTraceWeightInBytes } = options ?? {}; + + this._maxSpanLimit = + maxSpanLimit && maxSpanLimit > 0 && maxSpanLimit <= MAX_SPANS_PER_ENVELOPE + ? maxSpanLimit + : MAX_SPANS_PER_ENVELOPE; + this._flushInterval = flushInterval && flushInterval > 0 ? flushInterval : 5_000; + this._maxTraceWeight = + maxTraceWeightInBytes && maxTraceWeightInBytes > 0 ? maxTraceWeightInBytes : MAX_TRACE_WEIGHT_IN_BYTES; + + this._client.on('flush', () => { + this.drain(); + }); + + this._client.on('close', () => { + // No need to drain the buffer here as `Client.close()` internally already calls `Client.flush()` + // which already invokes the `flush` hook and thus drains the buffer. + this._traceBuckets.forEach(bucket => { + clearTimeout(bucket.timeout); + }); + this._traceBuckets.clear(); + }); + } + + /** + * Add a span to the buffer. + */ + public add(spanJSON: SerializedStreamedSpanWithSegmentSpan): void { + const traceId = spanJSON.trace_id; + let bucket = this._traceBuckets.get(traceId); + + if (!bucket) { + bucket = { + spans: new Set(), + size: 0, + timeout: safeUnref( + setTimeout(() => { + this.flush(traceId); + }, this._flushInterval), + ), + }; + this._traceBuckets.set(traceId, bucket); + } + + bucket.spans.add(spanJSON); + bucket.size += estimateSerializedSpanSizeInBytes(spanJSON); + + if (bucket.spans.size >= this._maxSpanLimit || bucket.size >= this._maxTraceWeight) { + this.flush(traceId); + } + } + + /** + * Drain and flush all buffered traces. + */ + public drain(): void { + if (!this._traceBuckets.size) { + return; + } + + DEBUG_BUILD && debug.log(`Flushing span tree map with ${this._traceBuckets.size} traces`); + + this._traceBuckets.forEach((_, traceId) => { + this.flush(traceId); + }); + } + + /** + * Flush spans of a specific trace. + * In contrast to {@link SpanBuffer.drain}, this method does not flush all traces, but only the one with the given traceId. + */ + public flush(traceId: string): void { + const bucket = this._traceBuckets.get(traceId); + if (!bucket) { + return; + } + + if (!bucket.spans.size) { + // we should never get here, given we always add a span when we create a new bucket + // and delete the bucket once we flush out the trace + this._removeTrace(traceId); + return; + } + + const spans = Array.from(bucket.spans); + + const segmentSpan = spans[0]?._segmentSpan; + if (!segmentSpan) { + DEBUG_BUILD && debug.warn('No segment span reference found on span JSON, cannot compute DSC'); + this._removeTrace(traceId); + return; + } + + const dsc = getDynamicSamplingContextFromSpan(segmentSpan); + + const cleanedSpans: SerializedStreamedSpan[] = spans.map(spanJSON => { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const { _segmentSpan, ...cleanSpanJSON } = spanJSON; + return cleanSpanJSON; + }); + + const envelope = createStreamedSpanEnvelope(cleanedSpans, dsc, this._client); + + DEBUG_BUILD && debug.log(`Sending span envelope for trace ${traceId} with ${cleanedSpans.length} spans`); + + this._client.sendEnvelope(envelope).then(null, reason => { + DEBUG_BUILD && debug.error('Error while sending streamed span envelope:', reason); + }); + + this._removeTrace(traceId); + } + + private _removeTrace(traceId: string): void { + const bucket = this._traceBuckets.get(traceId); + if (bucket) { + clearTimeout(bucket.timeout); + } + this._traceBuckets.delete(traceId); + } +} diff --git a/packages/core/src/tracing/trace.ts b/packages/core/src/tracing/trace.ts index d3043808260f..5d40a0a30ebe 100644 --- a/packages/core/src/tracing/trace.ts +++ b/packages/core/src/tracing/trace.ts @@ -6,7 +6,11 @@ import { getMainCarrier } from '../carrier'; import { getClient, getCurrentScope, getIsolationScope, withScope } from '../currentScopes'; import { DEBUG_BUILD } from '../debug-build'; import type { Scope } from '../scope'; -import { SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '../semanticAttributes'; +import { + SEMANTIC_ATTRIBUTE_SENTRY_OP, + SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, + SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, +} from '../semanticAttributes'; import type { DynamicSamplingContext } from '../types-hoist/envelope'; import type { ClientOptions } from '../types-hoist/options'; import type { SentrySpanArguments, Span, SpanTimeInput } from '../types-hoist/span'; @@ -15,6 +19,8 @@ import { baggageHeaderToDynamicSamplingContext } from '../utils/baggage'; import { debug } from '../utils/debug-logger'; import { handleCallbackErrors } from '../utils/handleCallbackErrors'; import { hasSpansEnabled } from '../utils/hasSpansEnabled'; +import { shouldIgnoreSpan } from '../utils/should-ignore-span'; +import { hasSpanStreamingEnabled } from './spans/hasSpanStreamingEnabled'; import { parseSampleRate } from '../utils/parseSampleRate'; import { generateTraceId } from '../utils/propagationContext'; import { safeMathRandom } from '../utils/randomSafeContext'; @@ -28,6 +34,7 @@ import { SentryNonRecordingSpan } from './sentryNonRecordingSpan'; import { SentrySpan } from './sentrySpan'; import { SPAN_STATUS_ERROR } from './spanstatus'; import { setCapturedScopesOnSpan } from './utils'; +import type { Client } from '../client'; const SUPPRESS_TRACING_KEY = '__SENTRY_SUPPRESS_TRACING__'; @@ -72,7 +79,12 @@ export function startSpan(options: StartSpanOptions, callback: (span: Span) = scope, }); - _setSpanForScope(scope, activeSpan); + // Ignored root spans still need to be set on scope so that `getActiveSpan()` returns them + // and descendants are also non-recording. Ignored child spans don't need this because + // the parent span is already on scope. + if (!_isIgnoredSpan(activeSpan) || !parentSpan) { + _setSpanForScope(scope, activeSpan); + } return handleCallbackErrors( () => callback(activeSpan), @@ -130,7 +142,11 @@ export function startSpanManual(options: StartSpanOptions, callback: (span: S scope, }); - _setSpanForScope(scope, activeSpan); + // We don't set ignored child spans onto the scope because there likely is an active, + // unignored span on the scope already. + if (!_isIgnoredSpan(activeSpan) || !parentSpan) { + _setSpanForScope(scope, activeSpan); + } return handleCallbackErrors( // We pass the `finish` function to the callback, so the user can finish the span manually @@ -335,6 +351,20 @@ function createChildOrRootSpan({ return span; } + const client = getClient(); + if (_shouldIgnoreStreamedSpan(client, spanArguments)) { + if (!_isTracingSuppressed(scope)) { + // if tracing is actively suppressed (Sentry.suppressTracing(...)), + // we don't want to record a client outcome for the ignored span + client?.recordDroppedEvent('ignored', 'span'); + } + + return new SentryNonRecordingSpan({ + dropReason: 'ignored', + traceId: parentSpan?.spanContext().traceId ?? scope.getPropagationContext().traceId, + }); + } + const isolationScope = getIsolationScope(); let span: Span; @@ -434,9 +464,9 @@ function _startRootSpan(spanArguments: SentrySpanArguments, scope: Scope, parent const finalAttributes = mutableSpanSamplingData.spanAttributes; const currentPropagationContext = scope.getPropagationContext(); - const [sampled, sampleRate, localSampleRateWasApplied] = scope.getScopeData().sdkProcessingMetadata[ - SUPPRESS_TRACING_KEY - ] + const isTracingSuppressed = _isTracingSuppressed(scope); + + const [sampled, sampleRate, localSampleRateWasApplied] = isTracingSuppressed ? [false] : sampleSpan( options, @@ -460,9 +490,9 @@ function _startRootSpan(spanArguments: SentrySpanArguments, scope: Scope, parent sampled, }); - if (!sampled && client) { + if (!sampled && client && !isTracingSuppressed) { DEBUG_BUILD && debug.log('[Tracing] Discarding root span because its trace was not chosen to be sampled.'); - client.recordDroppedEvent('sample_rate', 'transaction'); + client.recordDroppedEvent('sample_rate', hasSpanStreamingEnabled(client) ? 'span' : 'transaction'); } if (client) { @@ -478,7 +508,8 @@ function _startRootSpan(spanArguments: SentrySpanArguments, scope: Scope, parent */ function _startChildSpan(parentSpan: Span, scope: Scope, spanArguments: SentrySpanArguments): Span { const { spanId, traceId } = parentSpan.spanContext(); - const sampled = scope.getScopeData().sdkProcessingMetadata[SUPPRESS_TRACING_KEY] ? false : spanIsSampled(parentSpan); + const isTracingSuppressed = _isTracingSuppressed(scope); + const sampled = isTracingSuppressed ? false : spanIsSampled(parentSpan); const childSpan = sampled ? new SentrySpan({ @@ -492,14 +523,33 @@ function _startChildSpan(parentSpan: Span, scope: Scope, spanArguments: SentrySp addChildSpanToSpan(parentSpan, childSpan); const client = getClient(); - if (client) { - client.emit('spanStart', childSpan); - // If it has an endTimestamp, it's already ended - if (spanArguments.endTimestamp) { - client.emit('spanEnd', childSpan); + + if (!client) { + return childSpan; + } + + if (hasSpanStreamingEnabled(client) && childSpan instanceof SentryNonRecordingSpan) { + if (parentSpan instanceof SentryNonRecordingSpan && parentSpan.dropReason) { + // We land here if the parent span was a segment span that was ignored (`ignoreSpans`). + // In this case, the child was also ignored (see `sampled` above) but we need to + // record a client outcome for the child. + childSpan.dropReason = parentSpan.dropReason; + client.recordDroppedEvent(parentSpan.dropReason, 'span'); + } else if (!isTracingSuppressed) { + // Otherwise, the child is not sampled due to sampling of the parent span, + // hence we record a sample_rate client outcome for the child. + childSpan.dropReason = 'sample_rate'; + client.recordDroppedEvent('sample_rate', 'span'); } } + client.emit('spanStart', childSpan); + // If it has an endTimestamp, it's already ended + if (spanArguments.endTimestamp) { + client.emit('spanEnd', childSpan); + client.emit('afterSpanEnd', childSpan); + } + return childSpan; } @@ -536,3 +586,28 @@ function getActiveSpanWrapper(parentSpan: Span | undefined | null): (callback } : (callback: () => T) => callback(); } + +/* Checks if `ignoreSpans` applies (extracted for bundle size)*/ +function _shouldIgnoreStreamedSpan(client: Client | undefined, spanArguments: SentrySpanArguments): boolean { + const ignoreSpans = client?.getOptions().ignoreSpans; + + if (!client || !hasSpanStreamingEnabled(client) || !ignoreSpans?.length) { + return false; + } + + return shouldIgnoreSpan( + { + description: spanArguments.name || '', + op: spanArguments.attributes?.[SEMANTIC_ATTRIBUTE_SENTRY_OP] || spanArguments.op, + }, + ignoreSpans, + ); +} + +function _isIgnoredSpan(span: Span): span is SentryNonRecordingSpan { + return span instanceof SentryNonRecordingSpan && span.dropReason === 'ignored'; +} + +function _isTracingSuppressed(scope: Scope): boolean { + return scope.getScopeData().sdkProcessingMetadata[SUPPRESS_TRACING_KEY] === true; +} diff --git a/packages/core/src/tracing/vercel-ai/utils.ts b/packages/core/src/tracing/vercel-ai/utils.ts index e72efde75e18..2a715deab764 100644 --- a/packages/core/src/tracing/vercel-ai/utils.ts +++ b/packages/core/src/tracing/vercel-ai/utils.ts @@ -4,15 +4,12 @@ import { GEN_AI_EMBED_DO_EMBED_OPERATION_ATTRIBUTE, GEN_AI_EMBED_MANY_DO_EMBED_OPERATION_ATTRIBUTE, GEN_AI_EXECUTE_TOOL_OPERATION_ATTRIBUTE, - GEN_AI_GENERATE_OBJECT_DO_GENERATE_OPERATION_ATTRIBUTE, - GEN_AI_GENERATE_TEXT_DO_GENERATE_OPERATION_ATTRIBUTE, + GEN_AI_GENERATE_CONTENT_OPERATION_ATTRIBUTE, GEN_AI_INPUT_MESSAGES_ATTRIBUTE, GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE, GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE, GEN_AI_RERANK_DO_RERANK_OPERATION_ATTRIBUTE, GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE, - GEN_AI_STREAM_OBJECT_DO_STREAM_OPERATION_ATTRIBUTE, - GEN_AI_STREAM_TEXT_DO_STREAM_OPERATION_ATTRIBUTE, GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE, GEN_AI_TOOL_DESCRIPTION_ATTRIBUTE, GEN_AI_TOOL_NAME_ATTRIBUTE, @@ -295,13 +292,10 @@ export function getSpanOpFromName(name: string): string | undefined { case 'ai.streamObject': return GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE; case 'ai.generateText.doGenerate': - return GEN_AI_GENERATE_TEXT_DO_GENERATE_OPERATION_ATTRIBUTE; case 'ai.streamText.doStream': - return GEN_AI_STREAM_TEXT_DO_STREAM_OPERATION_ATTRIBUTE; case 'ai.generateObject.doGenerate': - return GEN_AI_GENERATE_OBJECT_DO_GENERATE_OPERATION_ATTRIBUTE; case 'ai.streamObject.doStream': - return GEN_AI_STREAM_OBJECT_DO_STREAM_OPERATION_ATTRIBUTE; + return GEN_AI_GENERATE_CONTENT_OPERATION_ATTRIBUTE; case 'ai.embed.doEmbed': return GEN_AI_EMBED_DO_EMBED_OPERATION_ATTRIBUTE; case 'ai.embedMany.doEmbed': diff --git a/packages/core/src/types-hoist/envelope.ts b/packages/core/src/types-hoist/envelope.ts index 272f8cde9f62..d8b8a1822b04 100644 --- a/packages/core/src/types-hoist/envelope.ts +++ b/packages/core/src/types-hoist/envelope.ts @@ -11,7 +11,7 @@ import type { Profile, ProfileChunk } from './profiling'; import type { ReplayEvent, ReplayRecordingData } from './replay'; import type { SdkInfo } from './sdkinfo'; import type { SerializedSession, SessionAggregates } from './session'; -import type { SpanJSON } from './span'; +import type { SerializedStreamedSpanContainer, SpanJSON } from './span'; // Based on: https://develop.sentry.dev/sdk/envelopes/ @@ -91,6 +91,21 @@ type CheckInItemHeaders = { type: 'check_in' }; type ProfileItemHeaders = { type: 'profile' }; type ProfileChunkItemHeaders = { type: 'profile_chunk' }; type SpanItemHeaders = { type: 'span' }; +type SpanContainerItemHeaders = { + /** + * Same as v1 span item type but this envelope is distinguished by {@link SpanContainerItemHeaders.content_type}. + */ + type: 'span'; + /** + * The number of span items in the container. This must be the same as the number of span items in the payload. + */ + item_count: number; + /** + * The content type of the span items. This must be `application/vnd.sentry.items.span.v2+json`. + * (the presence of this field also distinguishes the span item from the v1 span item) + */ + content_type: 'application/vnd.sentry.items.span.v2+json'; +}; type LogContainerItemHeaders = { type: 'log'; /** @@ -123,6 +138,7 @@ export type FeedbackItem = BaseEnvelopeItem; export type ProfileItem = BaseEnvelopeItem; export type ProfileChunkItem = BaseEnvelopeItem; export type SpanItem = BaseEnvelopeItem>; +export type SpanContainerItem = BaseEnvelopeItem; export type LogContainerItem = BaseEnvelopeItem; export type MetricContainerItem = BaseEnvelopeItem; export type RawSecurityItem = BaseEnvelopeItem; @@ -133,6 +149,7 @@ type CheckInEnvelopeHeaders = { trace?: DynamicSamplingContext }; type ClientReportEnvelopeHeaders = BaseEnvelopeHeaders; type ReplayEnvelopeHeaders = BaseEnvelopeHeaders; type SpanEnvelopeHeaders = BaseEnvelopeHeaders & { trace?: DynamicSamplingContext }; +type StreamedSpanEnvelopeHeaders = BaseEnvelopeHeaders & { trace?: DynamicSamplingContext }; type LogEnvelopeHeaders = BaseEnvelopeHeaders; type MetricEnvelopeHeaders = BaseEnvelopeHeaders; export type EventEnvelope = BaseEnvelope< @@ -144,6 +161,7 @@ export type ClientReportEnvelope = BaseEnvelope; export type SpanEnvelope = BaseEnvelope; +export type StreamedSpanEnvelope = BaseEnvelope; export type ProfileChunkEnvelope = BaseEnvelope; export type RawSecurityEnvelope = BaseEnvelope; export type LogEnvelope = BaseEnvelope; @@ -157,6 +175,7 @@ export type Envelope = | ReplayEnvelope | CheckInEnvelope | SpanEnvelope + | StreamedSpanEnvelope | RawSecurityEnvelope | LogEnvelope | MetricEnvelope; diff --git a/packages/core/src/types-hoist/integration.ts b/packages/core/src/types-hoist/integration.ts index 120cb1acc884..fc80cf3f524a 100644 --- a/packages/core/src/types-hoist/integration.ts +++ b/packages/core/src/types-hoist/integration.ts @@ -14,6 +14,15 @@ export interface Integration { */ setupOnce?(): void; + /** + * Called before the `setup` hook of any integration is called. + * This is useful if an integration needs to e.g. modify client options prior to other integrations + * reading client options. + * + * @param client + */ + beforeSetup?(client: Client): void; + /** * Set up an integration for the given client. * Receives the client as argument. diff --git a/packages/core/src/types-hoist/link.ts b/packages/core/src/types-hoist/link.ts index a330dc108b00..9a117258200b 100644 --- a/packages/core/src/types-hoist/link.ts +++ b/packages/core/src/types-hoist/link.ts @@ -22,9 +22,9 @@ export interface SpanLink { * Link interface for the event envelope item. It's a flattened representation of `SpanLink`. * Can include additional fields defined by OTel. */ -export interface SpanLinkJSON extends Record { +export interface SpanLinkJSON extends Record { span_id: string; trace_id: string; sampled?: boolean; - attributes?: SpanLinkAttributes; + attributes?: TAttributes; } diff --git a/packages/core/src/types-hoist/options.ts b/packages/core/src/types-hoist/options.ts index 92292f8e6e3d..4f3df1f6365a 100644 --- a/packages/core/src/types-hoist/options.ts +++ b/packages/core/src/types-hoist/options.ts @@ -6,7 +6,7 @@ import type { Log } from './log'; import type { Metric } from './metric'; import type { TracesSamplerSamplingContext } from './samplingcontext'; import type { SdkMetadata } from './sdkmetadata'; -import type { SpanJSON } from './span'; +import type { SpanJSON, StreamedSpanJSON } from './span'; import type { StackLineParser, StackParser } from './stacktrace'; import type { TracePropagationTargets } from './tracing'; import type { BaseTransportOptions, Transport } from './transport'; @@ -500,6 +500,14 @@ export interface ClientOptions SpanJSON; + beforeSendSpan?: ((span: SpanJSON) => SpanJSON) & { _streamed?: true }; /** * An event-processing callback for transaction events, guaranteed to be invoked after all other event @@ -615,6 +626,19 @@ export interface ClientOptions Breadcrumb | null; } +/** + * A callback for processing streamed spans before they are sent. + * + * @see {@link StreamedSpanJSON} for the streamed span format used with `traceLifecycle: 'stream'` + */ +export type BeforeSendStreamedSpanCallback = ((span: StreamedSpanJSON) => StreamedSpanJSON) & { + /** + * When true, indicates this callback is designed to handle the {@link StreamedSpanJSON} format + * used with `traceLifecycle: 'stream'`. Set this by wrapping your callback with `withStreamedSpan`. + */ + _streamed?: true; +}; + /** Base configuration options for every SDK. */ export interface CoreOptions extends Omit< Partial>, diff --git a/packages/core/src/types-hoist/span.ts b/packages/core/src/types-hoist/span.ts index d82463768b7f..a918cc57859c 100644 --- a/packages/core/src/types-hoist/span.ts +++ b/packages/core/src/types-hoist/span.ts @@ -1,3 +1,4 @@ +import type { Attributes, RawAttributes } from '../attributes'; import type { SpanLink, SpanLinkJSON } from './link'; import type { Measurements } from './measurement'; import type { HrTime } from './opentelemetry'; @@ -34,6 +35,43 @@ export type SpanAttributes = Partial<{ /** This type is aligned with the OpenTelemetry TimeInput type. */ export type SpanTimeInput = HrTime | number | Date; +/** + * Intermediate JSON reporesentation of a v2 span, which users and our SDK integrations will interact with. + * This is NOT the final serialized JSON span, but an intermediate step still holding raw attributes. + * The final, serialized span is a {@link SerializedStreamedSpan}. + * Main reason: Make it easier and safer for users to work with attributes. + */ +export interface StreamedSpanJSON { + trace_id: string; + parent_span_id?: string; + span_id: string; + name: string; + start_timestamp: number; + end_timestamp: number; + status: 'ok' | 'error'; + is_segment: boolean; + attributes?: RawAttributes>; + links?: SpanLinkJSON>>[]; +} + +/** + * Serialized span item. + * This is the final, serialized span format that is sent to Sentry. + * The intermediate representation is {@link StreamedSpanJSON}. + * Main difference: Attributes are converted to {@link Attributes}, thus including the `type` annotation. + */ +export type SerializedStreamedSpan = Omit & { + attributes?: Attributes; + links?: SpanLinkJSON[]; +}; + +/** + * Envelope span item container. + */ +export type SerializedStreamedSpanContainer = { + items: Array; +}; + /** A JSON representation of a span. */ export interface SpanJSON { data: SpanAttributes; diff --git a/packages/core/src/utils/featureFlags.ts b/packages/core/src/utils/featureFlags.ts index 4fa3cdc5ac8d..c7551c379d3c 100644 --- a/packages/core/src/utils/featureFlags.ts +++ b/packages/core/src/utils/featureFlags.ts @@ -28,6 +28,12 @@ const SPAN_FLAG_ATTRIBUTE_PREFIX = 'flag.evaluation.'; * Copies feature flags that are in current scope context to the event context */ export function _INTERNAL_copyFlagsFromScopeToEvent(event: Event): Event { + if (event.type) { + // No need to add the flags context to transaction events. + // Spans already get the flag.evaluation attributes. + return event; + } + const scope = getCurrentScope(); const flagContext = scope.getScopeData().contexts.flags; const flagBuffer = flagContext ? flagContext.values : []; diff --git a/packages/core/src/utils/object.ts b/packages/core/src/utils/object.ts index 1ffabca10bb2..787a66ac8525 100644 --- a/packages/core/src/utils/object.ts +++ b/packages/core/src/utils/object.ts @@ -18,6 +18,7 @@ import { isElement, isError, isEvent, isInstanceOf, isPrimitive } from './is'; * args>)` or `origMethod.apply(this, [])` (rather than being called directly), again to preserve `this`. * @returns void */ + export function fill(source: { [key: string]: any }, name: string, replacementFactory: (...args: any[]) => any): void { if (!(name in source)) { return; @@ -80,6 +81,37 @@ export function markFunctionWrapped(wrapped: WrappedFunction, original: WrappedF } catch {} // eslint-disable-line no-empty } +/** + * Wrap a method on an object by name, only if it is not already wrapped. + * + * Note: to set the wrapped method as a non-enumerable property, pass + * false as the `enumerable` argument. This could be detected, but only + * by either walking up the prototype chain, or iterating over all fields + * in a `for(in)` loop. Neither are an acceptable performance impact for + * the rare case where we might patch a non-enumerable method. + */ +export function wrapMethod( + obj: O, + field: T, + wrapped: WrappedFunction, + enumerable: boolean = true, +): void { + const original = obj[field]; + if (typeof original !== 'function') { + throw new Error(`Cannot wrap method: ${field} is not a function`); + } + if (getOriginalFunction(original)) { + throw new Error(`Attempting to wrap method ${field} multiple times`); + } + markFunctionWrapped(wrapped, original); + Object.defineProperty(obj, field, { + writable: true, + configurable: true, + enumerable, + value: wrapped, + }); +} + /** * This extracts the original function if available. See * `markFunctionWrapped` for more information. diff --git a/packages/core/src/utils/spanUtils.ts b/packages/core/src/utils/spanUtils.ts index d7c261ecd73c..248f0d89dfba 100644 --- a/packages/core/src/utils/spanUtils.ts +++ b/packages/core/src/utils/spanUtils.ts @@ -1,4 +1,6 @@ import { getAsyncContextStrategy } from '../asyncContext'; +import type { RawAttributes } from '../attributes'; +import { serializeAttributes } from '../attributes'; import { getMainCarrier } from '../carrier'; import { getCurrentScope } from '../currentScopes'; import { @@ -12,7 +14,15 @@ import { SPAN_STATUS_OK, SPAN_STATUS_UNSET } from '../tracing/spanstatus'; import { getCapturedScopesOnSpan } from '../tracing/utils'; import type { TraceContext } from '../types-hoist/context'; import type { SpanLink, SpanLinkJSON } from '../types-hoist/link'; -import type { Span, SpanAttributes, SpanJSON, SpanOrigin, SpanTimeInput } from '../types-hoist/span'; +import type { + SerializedStreamedSpan, + Span, + SpanAttributes, + SpanJSON, + SpanOrigin, + SpanTimeInput, + StreamedSpanJSON, +} from '../types-hoist/span'; import type { SpanStatus } from '../types-hoist/spanStatus'; import { addNonEnumerableProperty } from '../utils/object'; import { generateSpanId } from '../utils/propagationContext'; @@ -105,6 +115,26 @@ export function convertSpanLinksForEnvelope(links?: SpanLink[]): SpanLinkJSON[] } } +/** + * Converts the span links array to a flattened version with serialized attributes for V2 spans. + * + * If the links array is empty, it returns `undefined` so the empty value can be dropped before it's sent. + */ +export function getStreamedSpanLinks( + links?: SpanLink[], +): SpanLinkJSON>>[] | undefined { + if (links?.length) { + return links.map(({ context: { spanId, traceId, traceFlags }, attributes }) => ({ + span_id: spanId, + trace_id: traceId, + sampled: traceFlags === TRACE_FLAG_SAMPLED, + attributes, + })); + } else { + return undefined; + } +} + /** * Convert a span time input into a timestamp in seconds. */ @@ -150,23 +180,12 @@ export function spanToJSON(span: Span): SpanJSON { if (spanIsOpenTelemetrySdkTraceBaseSpan(span)) { const { attributes, startTime, name, endTime, status, links } = span; - // In preparation for the next major of OpenTelemetry, we want to support - // looking up the parent span id according to the new API - // In OTel v1, the parent span id is accessed as `parentSpanId` - // In OTel v2, the parent span id is accessed as `spanId` on the `parentSpanContext` - const parentSpanId = - 'parentSpanId' in span - ? span.parentSpanId - : 'parentSpanContext' in span - ? (span.parentSpanContext as { spanId?: string } | undefined)?.spanId - : undefined; - return { span_id, trace_id, data: attributes, description: name, - parent_span_id: parentSpanId, + parent_span_id: getOtelParentSpanId(span), start_timestamp: spanTimeInputToSeconds(startTime), // This is [0,0] by default in OTEL, in which case we want to interpret this as no end time timestamp: spanTimeInputToSeconds(endTime) || undefined, @@ -187,6 +206,77 @@ export function spanToJSON(span: Span): SpanJSON { }; } +/** + * Convert a span to the intermediate {@link StreamedSpanJSON} representation. + */ +export function spanToStreamedSpanJSON(span: Span): StreamedSpanJSON { + if (spanIsSentrySpan(span)) { + return span.getStreamedSpanJSON(); + } + + const { spanId: span_id, traceId: trace_id } = span.spanContext(); + + // Handle a span from @opentelemetry/sdk-base-trace's `Span` class + if (spanIsOpenTelemetrySdkTraceBaseSpan(span)) { + const { attributes, startTime, name, endTime, status, links } = span; + + return { + name, + span_id, + trace_id, + parent_span_id: getOtelParentSpanId(span), + start_timestamp: spanTimeInputToSeconds(startTime), + end_timestamp: spanTimeInputToSeconds(endTime), + is_segment: span === INTERNAL_getSegmentSpan(span), + status: getSimpleStatusMessage(status), + attributes, + links: getStreamedSpanLinks(links), + }; + } + + // Finally, as a fallback, at least we have `spanContext()`.... + // This should not actually happen in reality, but we need to handle it for type safety. + return { + span_id, + trace_id, + start_timestamp: 0, + name: '', + end_timestamp: 0, + status: 'ok', + is_segment: span === INTERNAL_getSegmentSpan(span), + }; +} + +/** + * In preparation for the next major of OpenTelemetry, we want to support + * looking up the parent span id according to the new API + * In OTel v1, the parent span id is accessed as `parentSpanId` + * In OTel v2, the parent span id is accessed as `spanId` on the `parentSpanContext` + */ +function getOtelParentSpanId(span: OpenTelemetrySdkTraceBaseSpan): string | undefined { + return 'parentSpanId' in span + ? span.parentSpanId + : 'parentSpanContext' in span + ? (span.parentSpanContext as { spanId?: string } | undefined)?.spanId + : undefined; +} + +/** + * Converts a {@link StreamedSpanJSON} to a {@link SerializedSpan}. + * This is the final serialized span format that is sent to Sentry. + * The returned serilaized spans must not be consumed by users or SDK integrations. + */ +export function streamedSpanJsonToSerializedSpan(spanJson: StreamedSpanJSON): SerializedStreamedSpan { + return { + ...spanJson, + attributes: serializeAttributes(spanJson.attributes), + links: spanJson.links?.map(link => ({ + ...link, + attributes: serializeAttributes(link.attributes), + })), + }; +} + function spanIsOpenTelemetrySdkTraceBaseSpan(span: Span): span is OpenTelemetrySdkTraceBaseSpan { const castSpan = span as Partial; return !!castSpan.attributes && !!castSpan.startTime && !!castSpan.name && !!castSpan.endTime && !!castSpan.status; @@ -237,6 +327,18 @@ export function getStatusMessage(status: SpanStatus | undefined): string | undef return status.message || 'internal_error'; } +/** + * Convert the various statuses to the simple onces expected by Sentry for steamed spans ('ok' is default). + */ +export function getSimpleStatusMessage(status: SpanStatus | undefined): 'ok' | 'error' { + return !status || + status.code === SPAN_STATUS_OK || + status.code === SPAN_STATUS_UNSET || + status.message === 'cancelled' + ? 'ok' + : 'error'; +} + const CHILD_SPANS_FIELD = '_sentryChildSpans'; const ROOT_SPAN_FIELD = '_sentryRootSpan'; @@ -298,7 +400,12 @@ export function getSpanDescendants(span: SpanWithPotentialChildren): Span[] { /** * Returns the root span of a given span. */ -export function getRootSpan(span: SpanWithPotentialChildren): Span { +export const getRootSpan = INTERNAL_getSegmentSpan; + +/** + * Returns the segment span of a given span. + */ +export function INTERNAL_getSegmentSpan(span: SpanWithPotentialChildren): Span { return span[ROOT_SPAN_FIELD] || span; } diff --git a/packages/core/src/utils/stacktrace.ts b/packages/core/src/utils/stacktrace.ts index 16a32ede4e58..cc79da1cc211 100644 --- a/packages/core/src/utils/stacktrace.ts +++ b/packages/core/src/utils/stacktrace.ts @@ -39,7 +39,9 @@ export function createStackParser(...parsers: StackLineParser[]): StackParser { // https://github.com/getsentry/sentry-javascript/issues/7813 // Skip Error: lines - if (cleanedLine.match(/\S*Error: /)) { + // Using includes() instead of a regex to avoid O(n²) backtracking on long lines + // https://github.com/getsentry/sentry-javascript/issues/20052 + if (cleanedLine.includes('Error: ')) { continue; } diff --git a/packages/core/src/utils/string.ts b/packages/core/src/utils/string.ts index fe28ef24c46a..df548370823f 100644 --- a/packages/core/src/utils/string.ts +++ b/packages/core/src/utils/string.ts @@ -104,7 +104,7 @@ export function safeJoin(input: unknown[], delimiter?: string): string { */ export function isMatchingPattern( value: string, - pattern: RegExp | string, + pattern: RegExp | string | ((value: string) => boolean), requireExactStringMatch: boolean = false, ): boolean { if (!isString(value)) { @@ -117,6 +117,9 @@ export function isMatchingPattern( if (isString(pattern)) { return requireExactStringMatch ? value === pattern : value.includes(pattern); } + if (typeof pattern === 'function') { + return pattern(value); + } return false; } @@ -133,7 +136,7 @@ export function isMatchingPattern( */ export function stringMatchesSomePattern( testString: string, - patterns: Array = [], + patterns: Array boolean)> = [], requireExactStringMatch: boolean = false, ): boolean { return patterns.some(pattern => isMatchingPattern(testString, pattern, requireExactStringMatch)); diff --git a/packages/core/test/integrations/spanStreaming.test.ts b/packages/core/test/integrations/spanStreaming.test.ts new file mode 100644 index 000000000000..8b2badf575ff --- /dev/null +++ b/packages/core/test/integrations/spanStreaming.test.ts @@ -0,0 +1,139 @@ +import * as SentryCore from '../../src'; +import { debug } from '../../src'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { spanStreamingIntegration } from '../../src/integrations/spanStreaming'; +import { TestClient, getDefaultTestClientOptions } from '../mocks/client'; + +const mockSpanBufferInstance = vi.hoisted(() => ({ + flush: vi.fn(), + add: vi.fn(), + drain: vi.fn(), +})); + +const MockSpanBuffer = vi.hoisted(() => { + return vi.fn(() => mockSpanBufferInstance); +}); + +vi.mock('../../src/tracing/spans/spanBuffer', async () => { + const original = await vi.importActual('../../src/tracing/spans/spanBuffer'); + return { + ...original, + SpanBuffer: MockSpanBuffer, + }; +}); + +describe('spanStreamingIntegration (core)', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('has the correct name and setup hook', () => { + const integration = spanStreamingIntegration(); + expect(integration.name).toBe('SpanStreaming'); + // eslint-disable-next-line @typescript-eslint/unbound-method + expect(integration.setup).toBeDefined(); + }); + + it.each(['static', 'somethingElse'])( + 'logs a warning if traceLifecycle is not set to "stream" but to %s', + traceLifecycle => { + const debugSpy = vi.spyOn(debug, 'warn').mockImplementation(() => {}); + const client = new TestClient({ + ...getDefaultTestClientOptions(), + dsn: 'https://username@domain/123', + integrations: [spanStreamingIntegration()], + // @ts-expect-error - we want to test the warning for invalid traceLifecycle values + traceLifecycle, + }); + + SentryCore.setCurrentClient(client); + client.init(); + + expect(debugSpy).toHaveBeenCalledWith( + 'SpanStreaming integration requires `traceLifecycle` to be set to "stream"! Falling back to static trace lifecycle.', + ); + debugSpy.mockRestore(); + + expect(client.getOptions().traceLifecycle).toBe('static'); + }, + ); + + it('falls back to static trace lifecycle if beforeSendSpan is not compatible with span streaming', () => { + const debugSpy = vi.spyOn(debug, 'warn').mockImplementation(() => {}); + const client = new TestClient({ + ...getDefaultTestClientOptions(), + dsn: 'https://username@domain/123', + integrations: [spanStreamingIntegration()], + traceLifecycle: 'stream', + beforeSendSpan: (span: SentryCore.SpanJSON) => span, + }); + + SentryCore.setCurrentClient(client); + client.init(); + + expect(debugSpy).toHaveBeenCalledWith( + 'SpanStreaming integration requires a beforeSendSpan callback using `withStreamedSpan`! Falling back to static trace lifecycle.', + ); + debugSpy.mockRestore(); + + expect(client.getOptions().traceLifecycle).toBe('static'); + }); + + it('sets up buffer when traceLifecycle is "stream"', () => { + const client = new TestClient({ + ...getDefaultTestClientOptions(), + dsn: 'https://username@domain/123', + integrations: [spanStreamingIntegration()], + traceLifecycle: 'stream', + }); + + SentryCore.setCurrentClient(client); + client.init(); + + expect(MockSpanBuffer).toHaveBeenCalledWith(client); + expect(client.getOptions().traceLifecycle).toBe('stream'); + }); + + it('enqueues a span into the buffer when the span ends', () => { + const client = new TestClient({ + ...getDefaultTestClientOptions(), + dsn: 'https://username@domain/123', + integrations: [spanStreamingIntegration()], + traceLifecycle: 'stream', + tracesSampleRate: 1, + }); + + SentryCore.setCurrentClient(client); + client.init(); + + const span = new SentryCore.SentrySpan({ name: 'test', sampled: true }); + client.emit('afterSpanEnd', span); + + expect(mockSpanBufferInstance.add).toHaveBeenCalledWith( + expect.objectContaining({ + _segmentSpan: span, + trace_id: span.spanContext().traceId, + span_id: span.spanContext().spanId, + name: 'test', + }), + ); + }); + + it('does not enqueue a span into the buffer when the span is not sampled', () => { + const client = new TestClient({ + ...getDefaultTestClientOptions(), + dsn: 'https://username@domain/123', + integrations: [spanStreamingIntegration()], + traceLifecycle: 'stream', + tracesSampleRate: 1, + }); + + SentryCore.setCurrentClient(client); + client.init(); + + const span = new SentryCore.SentrySpan({ name: 'test', sampled: false }); + client.emit('afterSpanEnd', span); + + expect(mockSpanBufferInstance.add).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/core/test/lib/integrations/express/index.test.ts b/packages/core/test/lib/integrations/express/index.test.ts new file mode 100644 index 000000000000..55fe442efb22 --- /dev/null +++ b/packages/core/test/lib/integrations/express/index.test.ts @@ -0,0 +1,359 @@ +import { + patchExpressModule, + expressErrorHandler, + setupExpressErrorHandler, +} from '../../../../src/integrations/express/index'; + +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import type { Mock } from 'vitest'; +import type { + ExpressIntegrationOptions, + ExpressExportv5, + ExpressExportv4, + ExpressLayer, + ExpressModuleExport, + ExpressRoute, + ExpressRouterv4, + ExpressRouterv5, + ExpressResponse, + ExpressRequest, + ExpressMiddleware, + ExpressErrorMiddleware, + ExpressHandlerOptions, +} from '../../../../src/integrations/express/types'; +import type { WrappedFunction } from '../../../../src/types-hoist/wrappedfunction'; + +const sdkProcessingMetadata: unknown[] = []; +const isolationScope = { + _scopeData: {} as { sdkProcessingMetadata?: unknown }, + getScopeData() { + return this._scopeData; + }, + setSDKProcessingMetadata({ normalizedRequest }: { normalizedRequest: unknown }) { + sdkProcessingMetadata.push(normalizedRequest); + }, +}; + +vi.mock('../../../../src/currentScopes', () => ({ + getIsolationScope() { + return isolationScope; + }, +})); + +const capturedExceptions: [unknown, unknown][] = []; +vi.mock('../../../../src/exports', () => ({ + captureException(error: unknown, hint: unknown) { + capturedExceptions.push([error, hint]); + return 'eventId'; + }, +})); + +vi.mock('../../../../src/debug-build', () => ({ + DEBUG_BUILD: true, +})); +const debugErrors: [string, Error][] = []; +vi.mock('../../../../src/utils/debug-logger', () => ({ + debug: { + error: (msg: string, er: Error) => { + debugErrors.push([msg, er]); + }, + }, +})); + +beforeEach(() => (patchLayerCalls.length = 0)); +const patchLayerCalls: [options: ExpressIntegrationOptions, layer: ExpressLayer, layerPath?: string][] = []; + +vi.mock('../../../../src/integrations/express/patch-layer', () => ({ + patchLayer: (options: ExpressIntegrationOptions, layer?: ExpressLayer, layerPath?: string) => { + if (layer) { + patchLayerCalls.push([options, layer, layerPath]); + } + }, +})); + +type ExpressSpies = Record<'routerUse' | 'routerRoute' | 'appUse', Mock<() => void>>; + +// get a fresh copy of a mock Express version 4 export +function getExpress4(): ExpressExportv4 & { spies: ExpressSpies } { + const routerRoute = vi.fn(); + const routerUse = vi.fn(); + const appUse = vi.fn(); + const spies = { + routerRoute, + routerUse, + appUse, + } as const; + const express = Object.assign(function express() {}, { + spies, + application: { use: appUse }, + Router: Object.assign(function Router() {}, { + route: routerRoute, + use: routerUse, + stack: [{ name: 'layer0' }, { name: 'layer1' }, { name: 'layerFinal' }], + }), + }) as unknown as ExpressExportv4 & { spies: ExpressSpies }; + Object.assign(express.application, { _router: express.Router }); + + return express; +} + +// get a fresh copy of a mock Express version 5 export +function getExpress5(): ExpressExportv5 & { spies: ExpressSpies } { + const routerRoute = vi.fn(); + const routerUse = vi.fn(); + const appUse = vi.fn(); + const spies = { + routerRoute, + routerUse, + appUse, + } as const; + const expressv5 = Object.assign(function express() {}, { + spies, + application: { use: appUse }, + Router: class Router { + stack: ExpressLayer[] = []; + route(...args: unknown[]) { + return routerRoute(...args); + } + use(...args: unknown[]) { + return routerUse(...args); + } + }, + }) as unknown as ExpressExportv5 & { spies: ExpressSpies }; + const stack = [{ name: 'layer0' }, { name: 'layer1' }, { name: 'layerFinal' }]; + Object.assign(expressv5.application, { + router: { stack }, + }); + + return expressv5; +} + +describe('patchExpressModule', () => { + it('throws trying to patch/unpatch the wrong thing', () => { + expect(() => { + patchExpressModule({ + express: {} as unknown as ExpressModuleExport, + } as unknown as ExpressIntegrationOptions); + }).toThrowError('no valid Express route function to instrument'); + }); + + it('can patch and restore expressv4 style module', () => { + for (const useDefault of [false, true]) { + const express = getExpress4(); + const module = useDefault ? { default: express } : express; + const r = express.Router as ExpressRouterv4; + const a = express.application; + const options = { express: module } as unknown as ExpressIntegrationOptions; + expect((r.use as WrappedFunction).__sentry_original__).toBe(undefined); + expect((r.route as WrappedFunction).__sentry_original__).toBe(undefined); + expect((a.use as WrappedFunction).__sentry_original__).toBe(undefined); + + patchExpressModule(options); + + expect(typeof (r.use as WrappedFunction).__sentry_original__).toBe('function'); + expect(typeof (r.route as WrappedFunction).__sentry_original__).toBe('function'); + expect(typeof (a.use as WrappedFunction).__sentry_original__).toBe('function'); + } + }); + + it('can patch and restore expressv5 style module', () => { + for (const useDefault of [false, true]) { + const express = getExpress5(); + const r = express.Router as ExpressRouterv5; + const a = express.application; + const module = useDefault ? { default: express } : express; + const options = { express: module } as unknown as ExpressIntegrationOptions; + expect((r.prototype.use as WrappedFunction).__sentry_original__).toBe(undefined); + expect((r.prototype.route as WrappedFunction).__sentry_original__).toBe(undefined); + expect((a.use as WrappedFunction).__sentry_original__).toBe(undefined); + + patchExpressModule(options); + + expect(typeof (r.prototype.use as WrappedFunction).__sentry_original__).toBe('function'); + expect(typeof (r.prototype.route as WrappedFunction).__sentry_original__).toBe('function'); + expect(typeof (a.use as WrappedFunction).__sentry_original__).toBe('function'); + } + }); + + it('calls patched and original Router.route', () => { + const expressv4 = getExpress4(); + const { spies } = expressv4; + const options = { express: expressv4 }; + patchExpressModule(options); + expressv4.Router.route('a'); + expect(spies.routerRoute).toHaveBeenCalledExactlyOnceWith('a'); + }); + + it('calls patched and original Router.use', () => { + const expressv4 = getExpress4(); + const { spies } = expressv4; + const options = { express: expressv4 }; + patchExpressModule(options); + expressv4.Router.use('a'); + expect(patchLayerCalls).toStrictEqual([[options, { name: 'layerFinal' }, 'a']]); + expect(spies.routerUse).toHaveBeenCalledExactlyOnceWith('a'); + }); + + it('skips patchLayer call in Router.use if no layer in the stack', () => { + const expressv4 = getExpress4(); + const { spies } = expressv4; + const options = { express: expressv4 }; + patchExpressModule(options); + const { stack } = expressv4.Router; + expressv4.Router.stack = []; + expressv4.Router.use('a'); + expressv4.Router.stack = stack; + expect(patchLayerCalls).toStrictEqual([]); + expect(spies.routerUse).toHaveBeenCalledExactlyOnceWith('a'); + }); + + it('calls patched and original application.use', () => { + const expressv4 = getExpress4(); + const { spies } = expressv4; + const options = { express: expressv4 }; + patchExpressModule(options); + expressv4.application.use('a'); + expect(patchLayerCalls).toStrictEqual([[options, { name: 'layerFinal' }, 'a']]); + expect(spies.appUse).toHaveBeenCalledExactlyOnceWith('a'); + }); + + it('calls patched and original application.use on express v5', () => { + const expressv5 = getExpress5(); + const { spies } = expressv5; + const options = { express: expressv5 }; + patchExpressModule(options); + expressv5.application.use('a'); + expect(patchLayerCalls).toStrictEqual([[options, { name: 'layerFinal' }, 'a']]); + expect(spies.appUse).toHaveBeenCalledExactlyOnceWith('a'); + }); + + it('skips patchLayer on application.use if no router found', () => { + const expressv4 = getExpress4(); + const { spies } = expressv4; + const options = { express: expressv4 }; + patchExpressModule(options); + const app = expressv4.application as { + _router?: ExpressRoute; + }; + const { _router } = app; + delete app._router; + expressv4.application.use('a'); + app._router = _router; + // no router, so no layers to patch! + expect(patchLayerCalls).toStrictEqual([]); + expect(spies.appUse).toHaveBeenCalledExactlyOnceWith('a'); + }); + + it('debug error when patching fails', () => { + const expressv5 = getExpress5(); + patchExpressModule({ express: expressv5 }); + patchExpressModule({ express: expressv5 }); + expect(debugErrors).toStrictEqual([ + ['Failed to patch express route method:', new Error('Attempting to wrap method route multiple times')], + ['Failed to patch express use method:', new Error('Attempting to wrap method use multiple times')], + ['Failed to patch express application.use method:', new Error('Attempting to wrap method use multiple times')], + ]); + }); +}); + +describe('expressErrorHandler', () => { + it('handles the error if it should', () => { + const errorMiddleware = expressErrorHandler(); + const res = { status: 500 } as unknown as ExpressResponse; + const next = vi.fn(); + const err = new Error('err'); + const req = { headers: { request: 'headers' } } as unknown as ExpressRequest; + errorMiddleware(err, req, res, next); + expect((res as unknown as { sentry: string }).sentry).toBe('eventId'); + expect(capturedExceptions).toStrictEqual([ + [ + new Error('err'), + { + mechanism: { + handled: false, + type: 'auto.middleware.express', + }, + }, + ], + ]); + capturedExceptions.length = 0; + expect(sdkProcessingMetadata).toStrictEqual([ + { + url: undefined, + method: undefined, + query_string: undefined, + headers: Object.assign(Object.create(null), { request: 'headers' }), + cookies: undefined, + data: undefined, + }, + ]); + sdkProcessingMetadata.length = 0; + expect(next).toHaveBeenCalledExactlyOnceWith(err); + next.mockReset(); + }); + + it('does not the error if it should not', () => { + const errorMiddleware = expressErrorHandler({ + shouldHandleError: () => false, + }); + const res = { status: 500 } as unknown as ExpressResponse; + const req = { headers: { request: 'headers' } } as unknown as ExpressRequest; + const next = vi.fn(); + const err = new Error('err'); + errorMiddleware(err, req, res, next); + expect((res as unknown as { sentry?: string }).sentry).toBe(undefined); + expect(capturedExceptions).toStrictEqual([]); + expect(sdkProcessingMetadata).toStrictEqual([ + { + url: undefined, + method: undefined, + query_string: undefined, + headers: Object.assign(Object.create(null), { request: 'headers' }), + cookies: undefined, + data: undefined, + }, + ]); + sdkProcessingMetadata.length = 0; + expect(next).toHaveBeenCalledExactlyOnceWith(err); + next.mockReset(); + }); +}); + +describe('setupExpressErrorHandler', () => { + const appUseCalls: unknown[] = []; + const app = { + use: vi.fn((fn: unknown) => appUseCalls.push(fn)) as ( + middleware: ExpressMiddleware | ExpressErrorMiddleware, + ) => unknown, + }; + const options = {} as ExpressHandlerOptions; + it('should have a test here lolz', () => { + setupExpressErrorHandler(app, options); + expect(app.use).toHaveBeenCalledTimes(2); + const reqHandler = appUseCalls[0]; + expect(typeof reqHandler).toBe('function'); + const next = vi.fn(); + (reqHandler as (request: ExpressRequest, _res: ExpressResponse, next: () => void) => void)( + { + method: 'GET', + headers: { request: 'headers' }, + } as unknown as ExpressRequest, + {} as unknown as ExpressResponse, + next, + ); + expect(next).toHaveBeenCalledOnce(); + expect(sdkProcessingMetadata).toStrictEqual([ + { + cookies: undefined, + data: undefined, + headers: Object.assign(Object.create(null), { + request: 'headers', + }), + method: 'GET', + query_string: undefined, + url: undefined, + }, + ]); + sdkProcessingMetadata.length = 0; + }); +}); diff --git a/packages/core/test/lib/integrations/express/patch-layer.test.ts b/packages/core/test/lib/integrations/express/patch-layer.test.ts new file mode 100644 index 000000000000..254ffb79edde --- /dev/null +++ b/packages/core/test/lib/integrations/express/patch-layer.test.ts @@ -0,0 +1,649 @@ +import { describe, beforeEach, it, expect, vi } from 'vitest'; +import { type ExpressPatchLayerOptions, patchLayer } from '../../../../src/integrations/express/patch-layer'; +import { + type ExpressRequest, + type ExpressLayer, + type ExpressResponse, +} from '../../../../src/integrations/express/types'; +import { getStoredLayers, storeLayer } from '../../../../src/integrations/express/request-layer-store'; +import { type StartSpanOptions } from '../../../../src/types-hoist/startSpanOptions'; +import { type Span } from '../../../../src/types-hoist/span'; +import { EventEmitter } from 'node:events'; +import { getOriginalFunction, markFunctionWrapped } from '../../../../src'; + +let DEBUG_BUILD = false; +beforeEach(() => (DEBUG_BUILD = true)); +vi.mock('../../../../src/debug-build', () => ({ + get DEBUG_BUILD() { + return DEBUG_BUILD; + }, +})); + +const warnings: string[] = []; +beforeEach(() => (warnings.length = 0)); +vi.mock('../../../../src/utils/debug-logger', () => ({ + debug: { + warn(msg: string) { + warnings.push(msg); + }, + }, +})); + +let inDefaultIsolationScope = false; +beforeEach(() => (inDefaultIsolationScope = false)); +const transactionNames: string[] = []; +const notDefaultIsolationScope = { + _scopeData: {} as { sdkProcessingMetadata?: unknown }, + getScopeData() { + return this._scopeData; + }, + setTransactionName(name: string) { + transactionNames.push(name); + }, + setSDKProcessingMetadata() {}, +}; +const defaultIsolationScope = { + _scopeData: {} as { sdkProcessingMetadata?: unknown }, + getScopeData() { + return this._scopeData; + }, + setSDKProcessingMetadata(data: unknown) { + this._scopeData.sdkProcessingMetadata = data; + }, +}; +vi.mock('../../../../src/currentScopes', () => ({ + getIsolationScope() { + return inDefaultIsolationScope ? defaultIsolationScope : notDefaultIsolationScope; + }, +})); +vi.mock('../../../../src/defaultScopes', () => ({ + getDefaultIsolationScope() { + return defaultIsolationScope; + }, +})); + +const mockSpans: MockSpan[] = []; +beforeEach(() => (mockSpans.length = 0)); +class MockSpan { + ended = false; + status: { code: number; message: string } = { code: 0, message: 'OK' }; + attributes: Record; + name: string; + + constructor(options: StartSpanOptions) { + this.name = options.name; + this.attributes = options.attributes ?? {}; + } + + updateName(name: string) { + this.name = name; + return this; + } + + setStatus(status: { code: number; message: string }) { + this.status = status; + } + + setAttributes(o: Record) { + for (const [k, v] of Object.entries(o)) { + this.setAttribute(k, v); + } + } + + setAttribute(key: string, value: unknown) { + this.attributes[key] = value; + } + + end() { + if (this.ended) { + throw new Error('ended span multiple times!'); + } + this.ended = true; + } + getSpanJSON(): MockSpanJSON { + // not the whole thing obviously, just enough to know we called it + return { + status: this.status, + data: this.attributes, + description: this.name, + }; + } +} +type MockSpanJSON = { + status?: { code: number; message: string }; + description: string; + data: Record; +}; + +/** verify we get all the expected spans and no more */ +const checkSpans = (expectations: Partial[]) => { + for (const exp of expectations) { + const span = mockSpans.pop()?.getSpanJSON(); + expect(span).toMatchObject(exp); + } + expect(mockSpans.map(m => m.getSpanJSON())).toStrictEqual([]); +}; + +let hasActiveSpan = true; +const parentSpan = {}; +vi.mock('../../../../src/utils/spanUtils', async () => ({ + ...(await import('../../../../src/utils/spanUtils')), + getActiveSpan() { + return hasActiveSpan ? parentSpan : undefined; + }, +})); + +vi.mock('../../../../src/tracing', () => ({ + SPAN_STATUS_ERROR: 2, + withActiveSpan(span: unknown, cb: Function) { + expect(span).toBe(parentSpan); + return cb(); + }, + startSpanManual(options: StartSpanOptions, callback: (span: Span) => T): T { + const span = new MockSpan(options); + mockSpans.push(span); + return callback(span as unknown as Span); + }, +})); + +describe('patchLayer', () => { + describe('no-ops', () => { + it('if layer is missing', () => { + // mostly for coverage, verifying it doesn't throw or anything + patchLayer({}); + }); + + it('if layer.handle is missing', () => { + // mostly for coverage, verifying it doesn't throw or anything + patchLayer({}, { handle: null } as unknown as ExpressLayer); + }); + + it('if layer already patched', () => { + // mostly for coverage, verifying it doesn't throw or anything + function wrapped() {} + function original() {} + markFunctionWrapped(wrapped, original); + const layer = { + handle: wrapped, + } as unknown as ExpressLayer; + patchLayer({}, layer); + expect(layer.handle).toBe(wrapped); + }); + + it('if layer handler of length 4', () => { + // TODO: this should be expanded when we instrument error handlers + function original(_1: unknown, _2: unknown, _3: unknown, _4: unknown) {} + + const layer = { + handle: original, + } as unknown as ExpressLayer; + patchLayer({}, layer); + expect(layer.handle).toBe(original); + }); + + it('wraps the function', () => { + // mostly a gut-check that we actually do mark wrapped + function original(_1: unknown, _2: unknown, _3: unknown) {} + + const layer = { + handle: original, + } as unknown as ExpressLayer; + patchLayer({}, layer); + expect(getOriginalFunction(layer.handle)).toBe(original); + }); + }); + + it('ignores when no parent span has been started', () => { + hasActiveSpan = false; + const options: ExpressPatchLayerOptions = {}; + const req = Object.assign(new EventEmitter(), { + originalUrl: '/a/b/c', + }) as unknown as ExpressRequest; + + const layerHandleOriginal = vi.fn(); + const layer = { + name: 'mw', + handle: layerHandleOriginal, + } as unknown as ExpressLayer; + + const res = Object.assign(new EventEmitter(), {}) as unknown as ExpressResponse; + + storeLayer(req, 'a'); + storeLayer(req, '/:boo'); + storeLayer(req, '/:car'); + + patchLayer(options, layer); + layer.handle(req, res); + expect(layerHandleOriginal).toHaveBeenCalledOnce(); + + // should not have emitted any spans, it was ignored. + checkSpans([]); + + hasActiveSpan = true; + }); + + it('ignores layers that should be ignored, runs otherwise', () => { + const onRouteResolved = vi.fn(); + const options: ExpressPatchLayerOptions = { + onRouteResolved, + ignoreLayersType: ['middleware'], + }; + const req = Object.assign(new EventEmitter(), { + originalUrl: '/a/b/c/layerPath', + }) as unknown as ExpressRequest; + + const layerHandleOriginal = vi.fn(); + const layer = { + name: 'mw', + handle: layerHandleOriginal, + } as unknown as ExpressLayer; + + const res = Object.assign(new EventEmitter(), {}) as unknown as ExpressResponse; + + storeLayer(req, 'a'); + storeLayer(req, '/:boo'); + storeLayer(req, '/:car'); + + patchLayer(options, layer, '/layerPath'); + layer.handle(req, res); + expect(onRouteResolved).toHaveBeenCalledExactlyOnceWith('/a/:boo/:car/layerPath'); + expect(layerHandleOriginal).toHaveBeenCalledOnce(); + + // should not have emitted any spans, it was ignored. + checkSpans([]); + options.ignoreLayersType = []; + layer.handle(req, res); + const span = mockSpans[0]; + expect(span?.ended).toBe(false); + checkSpans([ + { + status: { code: 0, message: 'OK' }, + data: { + 'express.name': 'mw', + 'express.type': 'middleware', + 'http.route': '/a/:boo/:car/layerPath', + 'sentry.op': 'middleware.express', + 'sentry.origin': 'auto.http.express', + }, + description: 'mw', + }, + ]); + res.emit('finish'); + expect(span?.ended).toBe(true); + checkSpans([]); + }); + + it('pops storedLayers when ignoring router or request_handler type layers', () => { + for (const type of ['router', 'request_handler'] as const) { + const options: ExpressPatchLayerOptions = { ignoreLayersType: [type] }; + const req = Object.assign(new EventEmitter(), { + originalUrl: '/a/b/c/layerPath', + }) as unknown as ExpressRequest; + + // simulate layers already stored for previous path segments + storeLayer(req, '/a'); + storeLayer(req, '/b'); + + // patch a layer of the ignored type with a layerPath + const layerHandleOriginal = vi.fn(); + // layer.name must match what getLayerMetadata uses to classify each type: + // 'router' → router, 'bound dispatch' → request_handler, other → middleware + const layerName = type === 'router' ? 'router' : 'bound dispatch'; + const layer = { name: layerName, handle: layerHandleOriginal } as unknown as ExpressLayer; + patchLayer(options, layer, '/c'); + + // storeLayer('/c') happens inside the patched handle, before being popped + // after handle returns, storedLayers should be back to ['/a', '/b'] + layer.handle(req, Object.assign(new EventEmitter(), {}) as unknown as ExpressResponse); + + // the ignored layer's path must be cleaned up so subsequent layers see the correct route + expect(getStoredLayers(req)).toStrictEqual(['/a', '/b']); + } + }); + + it('warns about not setting name in default isolation scope', async () => { + inDefaultIsolationScope = true; + DEBUG_BUILD = true; + const options: ExpressPatchLayerOptions = {}; + const req = Object.assign(new EventEmitter(), { + originalUrl: '/a/b/c/layerPath', + }) as unknown as ExpressRequest; + + const layerHandleOriginal = Object.assign(vi.fn(), { + x: true, + // a field that the wrapped one will have, so we skip it. + toString() { + return 'x'; + }, + }); + const layer = { + name: 'handle', + handle: layerHandleOriginal, + } as unknown as ExpressLayer; + + const res = Object.assign(new EventEmitter(), {}) as unknown as ExpressResponse; + + storeLayer(req, 'a'); + storeLayer(req, '/:boo'); + storeLayer(req, '/:car'); + + patchLayer(options, layer, '/layerPath'); + expect(getOriginalFunction(layer.handle)).toBe(layerHandleOriginal); + expect(layer.handle.x).toBe(true); + layer.handle.x = false; + expect(layerHandleOriginal.x).toBe(false); + + warnings.length = 0; + layer.handle(req, res); + expect(warnings).toStrictEqual([ + 'Isolation scope is still default isolation scope - skipping setting transactionName', + ]); + expect(layerHandleOriginal).toHaveBeenCalledOnce(); + + // should not have emitted any spans, it was ignored. + checkSpans([ + { + status: { code: 0, message: 'OK' }, + data: { + 'express.name': 'a/:boo/:car/layerPath', + 'express.type': 'request_handler', + 'http.route': '/a/:boo/:car/layerPath', + 'sentry.op': 'request_handler.express', + 'sentry.origin': 'auto.http.express', + }, + description: 'a/:boo/:car/layerPath', + }, + ]); + res.emit('finish'); + checkSpans([]); + }); + + it('sets tx name in isolation scope', async () => { + DEBUG_BUILD = true; + expect( + (await import('../../../../src/currentScopes')).getIsolationScope() === + (await import('../../../../src/defaultScopes')).getDefaultIsolationScope(), + ).toBe(false); + + const options: ExpressPatchLayerOptions = {}; + const req = Object.assign(new EventEmitter(), { + originalUrl: '/a/b/c/layerPath', + }) as unknown as ExpressRequest; + + const layerHandleOriginal = vi.fn(); + const layer = { + name: 'handle', + handle: layerHandleOriginal, + } as unknown as ExpressLayer; + + const res = Object.assign(new EventEmitter(), {}) as unknown as ExpressResponse; + + storeLayer(req, 'a'); + storeLayer(req, '/:boo'); + storeLayer(req, '/:car'); + + patchLayer(options, layer); + expect(getOriginalFunction(layer.handle)).toBe(layerHandleOriginal); + warnings.length = 0; + layer.handle(req, res); + + req.method = 'put'; + layer.handle(req, res); + expect(warnings).toStrictEqual([]); + + expect(transactionNames).toStrictEqual(['GET a/:boo/:car', 'PUT a/:boo/:car']); + expect(layerHandleOriginal).toHaveBeenCalledTimes(2); + + // should not have emitted any spans, it was ignored. + checkSpans([ + { + status: { code: 0, message: 'OK' }, + data: { + 'express.name': 'a/:boo/:car', + 'express.type': 'request_handler', + 'http.route': '/a/:boo/:car', + 'sentry.op': 'request_handler.express', + 'sentry.origin': 'auto.http.express', + }, + description: 'a/:boo/:car', + }, + { + status: { code: 0, message: 'OK' }, + data: { + 'express.name': 'a/:boo/:car', + 'express.type': 'request_handler', + 'http.route': '/a/:boo/:car', + 'sentry.op': 'request_handler.express', + 'sentry.origin': 'auto.http.express', + }, + description: 'a/:boo/:car', + }, + ]); + res.emit('finish'); + checkSpans([]); + }); + + it('works with layerPath field', () => { + const onRouteResolved = vi.fn(); + const options: ExpressPatchLayerOptions = { onRouteResolved }; + const req = Object.assign(new EventEmitter(), { + originalUrl: '/a/b/c/d', + }) as unknown as ExpressRequest; + + const layerHandleOriginal = vi.fn(); + const layer = { + name: 'mw', + handle: layerHandleOriginal, + } as unknown as ExpressLayer; + + const res = Object.assign(new EventEmitter(), {}) as unknown as ExpressResponse; + + storeLayer(req, '/a'); + storeLayer(req, '/b'); + + patchLayer(options, layer, '/c'); + layer.handle(req, res); + expect(onRouteResolved).toHaveBeenCalledExactlyOnceWith('/a/b/c'); + const span = mockSpans[0]; + checkSpans([ + { + status: { code: 0, message: 'OK' }, + data: { + 'express.name': 'mw', + 'express.type': 'middleware', + 'http.route': '/a/b/c', + 'sentry.op': 'middleware.express', + 'sentry.origin': 'auto.http.express', + }, + description: 'mw', + }, + ]); + expect(span?.ended).toBe(false); + res.emit('finish'); + expect(span?.ended).toBe(true); + checkSpans([]); + }); + + it('handles case when route does not match url', () => { + const onRouteResolved = vi.fn(); + const options: ExpressPatchLayerOptions = { onRouteResolved }; + const req = Object.assign(new EventEmitter(), { + originalUrl: '/abcdef', + }) as unknown as ExpressRequest; + + const layerHandleOriginal = vi.fn(); + const layer = { + name: 'router', + handle: layerHandleOriginal, + } as unknown as ExpressLayer; + + const res = Object.assign(new EventEmitter(), {}) as unknown as ExpressResponse; + + storeLayer(req, '/a'); + storeLayer(req, '/b'); + + patchLayer(options, layer, '/c'); + layer.handle(req, res); + expect(onRouteResolved).toHaveBeenCalledExactlyOnceWith(undefined); + const span = mockSpans[0]; + checkSpans([ + { + status: { code: 0, message: 'OK' }, + data: { + 'express.name': '/c', + 'express.type': 'router', + 'sentry.op': 'router.express', + 'sentry.origin': 'auto.http.express', + }, + description: '/c', + }, + ]); + expect(span?.ended).toBe(true); + checkSpans([]); + }); + + it('wraps the callback', () => { + const options: ExpressPatchLayerOptions = {}; + + const layerHandleOriginal = vi.fn((...args) => { + expect(getStoredLayers(req)).toStrictEqual(['/a', '/b', '/c']); + (args[3] as Function)(); + // removes the added layer when the cb indicates it's done + expect(getStoredLayers(req)).toStrictEqual(['/a', '/b']); + }); + + const layer = { + name: 'mw', + handle: layerHandleOriginal, + } as unknown as ExpressLayer; + + const res = Object.assign(new EventEmitter(), {}) as unknown as ExpressResponse; + const req = Object.assign(new EventEmitter(), { + originalUrl: '/a/b/c', + res, + route: {}, + }) as unknown as ExpressRequest; + + storeLayer(req, '/a'); + storeLayer(req, '/b'); + patchLayer(options, layer, '/c'); + + expect(getStoredLayers(req)).toStrictEqual(['/a', '/b']); + const callback = vi.fn(() => { + expect(getStoredLayers(req)).toStrictEqual(['/a', '/b']); + }); + layer.handle(req, res, 'random', callback, 'whatever'); + expect(getStoredLayers(req)).toStrictEqual(['/a', '/b']); + + const span = mockSpans[0]; + checkSpans([ + { + status: { code: 0, message: 'OK' }, + data: { + 'express.name': 'mw', + 'express.type': 'middleware', + 'sentry.op': 'middleware.express', + 'sentry.origin': 'auto.http.express', + }, + description: 'mw', + }, + ]); + expect(span?.ended).toBe(true); + checkSpans([]); + }); + + it('handles callback being called with an error', () => { + const options: ExpressPatchLayerOptions = {}; + + const layerHandleOriginal = vi.fn((...args) => { + expect(getStoredLayers(req)).toStrictEqual(['/a', '/b', '/c']); + (args[3] as Function)(new Error('oopsie')); + // do not remove extra layer if this is where it failed though! + expect(getStoredLayers(req)).toStrictEqual(['/a', '/b', '/c']); + }); + + const layer = { + name: 'mw', + handle: layerHandleOriginal, + } as unknown as ExpressLayer; + + const res = Object.assign(new EventEmitter(), {}) as unknown as ExpressResponse; + const req = Object.assign(new EventEmitter(), { + originalUrl: '/a/b/c', + res, + route: {}, + }) as unknown as ExpressRequest; + + storeLayer(req, '/a'); + storeLayer(req, '/b'); + patchLayer(options, layer, '/c'); + + expect(getStoredLayers(req)).toStrictEqual(['/a', '/b']); + const callback = vi.fn(() => { + expect(getStoredLayers(req)).toStrictEqual(['/a', '/b', '/c']); + }); + layer.handle(req, res, 'random', callback, 'whatever'); + expect(getStoredLayers(req)).toStrictEqual(['/a', '/b', '/c']); + + const span = mockSpans[0]; + checkSpans([ + { + status: { code: 2, message: 'oopsie' }, + data: { + 'express.name': 'mw', + 'express.type': 'middleware', + 'sentry.op': 'middleware.express', + 'sentry.origin': 'auto.http.express', + }, + description: 'mw', + }, + ]); + expect(span?.ended).toBe(true); + checkSpans([]); + }); + + it('handles throws in layer.handle', () => { + const onRouteResolved = vi.fn(); + const options: ExpressPatchLayerOptions = { onRouteResolved }; + const req = Object.assign(new EventEmitter(), { + originalUrl: '/a/b/c/d', + }) as unknown as ExpressRequest; + + const layerHandleOriginal = vi.fn(() => { + throw new Error('yur head asplode'); + }); + const layer = { + name: 'mw', + handle: layerHandleOriginal, + } as unknown as ExpressLayer; + + const res = Object.assign(new EventEmitter(), {}) as unknown as ExpressResponse; + + storeLayer(req, '/a'); + storeLayer(req, '/b'); + + patchLayer(options, layer, '/c'); + expect(() => { + layer.handle(req, res); + }).toThrowError('yur head asplode'); + expect(onRouteResolved).toHaveBeenCalledExactlyOnceWith('/a/b/c'); + const span = mockSpans[0]; + checkSpans([ + { + status: { code: 2, message: 'yur head asplode' }, + data: { + 'express.name': 'mw', + 'express.type': 'middleware', + 'http.route': '/a/b/c', + 'sentry.op': 'middleware.express', + 'sentry.origin': 'auto.http.express', + }, + description: 'mw', + }, + ]); + expect(span?.ended).toBe(false); + res.emit('finish'); + expect(span?.ended).toBe(true); + checkSpans([]); + }); +}); diff --git a/packages/core/test/lib/integrations/express/request-layer-store.test.ts b/packages/core/test/lib/integrations/express/request-layer-store.test.ts new file mode 100644 index 000000000000..c2f58ac0e6f4 --- /dev/null +++ b/packages/core/test/lib/integrations/express/request-layer-store.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from 'vitest'; +import type { ExpressRequest } from '../../../../src/integrations/express/types'; +import { getStoredLayers, storeLayer } from '../../../../src/integrations/express/request-layer-store'; + +describe('storeLayer', () => { + it('handles case when nothing stored yet', () => { + const req = {} as unknown as ExpressRequest; + const empty = getStoredLayers(req); + expect(empty).toStrictEqual([]); + expect(getStoredLayers(req)).toStrictEqual([]); + }); + it('stores layer for a request', () => { + const req = {} as unknown as ExpressRequest; + storeLayer(req, 'a'); + storeLayer(req, 'b'); + expect(getStoredLayers(req)).toStrictEqual(['a', 'b']); + }); +}); diff --git a/packages/core/test/lib/integrations/express/set-sdk-processing-metadata.test.ts b/packages/core/test/lib/integrations/express/set-sdk-processing-metadata.test.ts new file mode 100644 index 000000000000..21a6810b4279 --- /dev/null +++ b/packages/core/test/lib/integrations/express/set-sdk-processing-metadata.test.ts @@ -0,0 +1,48 @@ +import { vi, beforeEach, describe, it, expect } from 'vitest'; +import { setSDKProcessingMetadata } from '../../../../src/integrations/express/set-sdk-processing-metadata'; + +const sdkProcessingMetadatas: unknown[] = []; +beforeEach(() => (sdkProcessingMetadatas.length = 0)); +const isolationScope = { + _scopeData: {} as { sdkProcessingMetadata?: unknown }, + getScopeData() { + return this._scopeData; + }, + setSDKProcessingMetadata(data: unknown) { + this._scopeData.sdkProcessingMetadata = data; + sdkProcessingMetadatas.push(data); + }, +}; +vi.mock('../../../../src/currentScopes', () => ({ + getIsolationScope() { + return isolationScope; + }, +})); + +describe('setSDKProcessingMetadata', () => { + it('sets the normalized request data', () => { + const request = { + originalUrl: '/a/b/c', + route: '/a/:boo/:car', + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + }, + }; + setSDKProcessingMetadata(request); + // call it again to cover no-op branch + setSDKProcessingMetadata(request); + expect(JSON.stringify(sdkProcessingMetadatas)).toBe( + JSON.stringify([ + { + normalizedRequest: { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + }, + }, + }, + ]), + ); + }); +}); diff --git a/packages/core/test/lib/integrations/express/types.test.ts b/packages/core/test/lib/integrations/express/types.test.ts new file mode 100644 index 000000000000..12fe68864b3d --- /dev/null +++ b/packages/core/test/lib/integrations/express/types.test.ts @@ -0,0 +1,18 @@ +import * as types from '../../../../src/integrations/express/types'; +import { describe, it, expect } from 'vitest'; + +// this is mostly just a types-bag, but it does have some constant keys +describe('types', () => { + it('exports several constants', () => { + // spread so it's a normal object + const { ...vals } = types; + expect(vals).toStrictEqual({ + ATTR_EXPRESS_NAME: 'express.name', + ATTR_HTTP_ROUTE: 'http.route', + ATTR_EXPRESS_TYPE: 'express.type', + ExpressLayerType_ROUTER: 'router', + ExpressLayerType_MIDDLEWARE: 'middleware', + ExpressLayerType_REQUEST_HANDLER: 'request_handler', + }); + }); +}); diff --git a/packages/core/test/lib/integrations/express/utils.test.ts b/packages/core/test/lib/integrations/express/utils.test.ts new file mode 100644 index 000000000000..b41d89076900 --- /dev/null +++ b/packages/core/test/lib/integrations/express/utils.test.ts @@ -0,0 +1,440 @@ +import { storeLayer } from '../../../../src/integrations/express/request-layer-store'; +import { + ATTR_EXPRESS_NAME, + ATTR_EXPRESS_TYPE, + type MiddlewareError, + type ExpressIntegrationOptions, + type ExpressLayer, + type ExpressRequest, +} from '../../../../src/integrations/express/types'; +import { + asErrorAndMessage, + defaultShouldHandleError, + getActualMatchedRoute, + getConstructedRoute, + getLayerMetadata, + getLayerPath, + getRouterPath, + hasDefaultProp, + isExpressWithoutRouterPrototype, + isExpressWithRouterPrototype, + isLayerIgnored, + isRoutePattern, +} from '../../../../src/integrations/express/utils'; + +import { describe, it, expect } from 'vitest'; + +describe('asErrorAndMessage', () => { + it('returns an Error with its message', () => { + const er = new Error('message'); + expect(asErrorAndMessage(er)).toStrictEqual([er, 'message']); + }); + it('returns an non-Error cast to string', () => { + const er = { + toString() { + return 'message'; + }, + }; + expect(asErrorAndMessage(er)).toStrictEqual(['message', 'message']); + }); +}); + +describe('isRoutePattern', () => { + it('searches for : and *', () => { + expect(isRoutePattern('a:b')).toBe(true); + expect(isRoutePattern('abc*')).toBe(true); + expect(isRoutePattern('abc')).toBe(false); + }); +}); + +describe('getRouterPath', () => { + it('reconstructs returns path if layer is empty', () => { + expect(getRouterPath('/a', {} as unknown as ExpressLayer)).toBe('/a'); + expect( + getRouterPath('/a', { + handle: {}, + } as unknown as ExpressLayer), + ).toBe('/a'); + expect( + getRouterPath('/a', { + handle: { stack: [] }, + } as unknown as ExpressLayer), + ).toBe('/a'); + expect( + getRouterPath('/a', { + handle: { + stack: [ + { + handle: { + stack: [ + { + handle: { + stack: [], + }, + }, + ], + }, + }, + ], + }, + } as unknown as ExpressLayer), + ).toBe('/a'); + }); + + it('uses the stackLayer route path if present', () => { + expect( + getRouterPath('/a', { + handle: { + stack: [{ route: { path: '/b' } }], + }, + } as unknown as ExpressLayer), + ).toBe('/a/b'); + }); + + it('recurses to search layer stack', () => { + expect( + getRouterPath('/a', { + handle: { + stack: [ + { + handle: { + stack: [ + { + handle: { + stack: [{ route: { path: '/b' } }], + }, + }, + ], + }, + }, + ], + }, + } as unknown as ExpressLayer), + ).toBe('/a/b'); + }); +}); + +describe('getLayerMetadata', () => { + it('returns the metadata from router layer', () => { + expect( + getLayerMetadata('/a', { + name: 'router', + route: { path: '/b' }, + } as unknown as ExpressLayer), + ).toStrictEqual({ + attributes: { + [ATTR_EXPRESS_NAME]: '/a', + [ATTR_EXPRESS_TYPE]: 'router', + }, + name: 'router - /a', + }); + expect( + getLayerMetadata( + '/a', + { + name: 'router', + route: {}, + } as unknown as ExpressLayer, + '/c', + ), + ).toStrictEqual({ + attributes: { + [ATTR_EXPRESS_NAME]: '/c', + [ATTR_EXPRESS_TYPE]: 'router', + }, + name: 'router - /c', + }); + expect( + getLayerMetadata('/a', { + name: 'router', + route: {}, + } as unknown as ExpressLayer), + ).toStrictEqual({ + attributes: { + [ATTR_EXPRESS_NAME]: '/a', + [ATTR_EXPRESS_TYPE]: 'router', + }, + name: 'router - /a', + }); + expect( + getLayerMetadata('', { + name: 'router', + route: {}, + } as unknown as ExpressLayer), + ).toStrictEqual({ + attributes: { + [ATTR_EXPRESS_NAME]: '/', + [ATTR_EXPRESS_TYPE]: 'router', + }, + name: 'router - /', + }); + expect( + getLayerMetadata('', { + name: 'router', + handle: { + stack: [{ route: { path: '/b' } }], + }, + } as unknown as ExpressLayer), + ).toStrictEqual({ + attributes: { + [ATTR_EXPRESS_NAME]: '/b', + [ATTR_EXPRESS_TYPE]: 'router', + }, + name: 'router - /b', + }); + expect( + getLayerMetadata('', { + name: 'bound dispatch', + handle: { + stack: [{ route: { path: '/b' } }], + }, + } as unknown as ExpressLayer), + ).toStrictEqual({ + attributes: { + [ATTR_EXPRESS_NAME]: 'request handler', + [ATTR_EXPRESS_TYPE]: 'request_handler', + }, + name: 'request handler', + }); + expect( + getLayerMetadata('/r', { + name: 'handle', + path: '/l', + handle: { + stack: [{ route: { path: '/b' } }], + }, + } as unknown as ExpressLayer), + ).toStrictEqual({ + attributes: { + [ATTR_EXPRESS_NAME]: '/r', + [ATTR_EXPRESS_TYPE]: 'request_handler', + }, + name: 'request handler - /r', + }); + expect( + getLayerMetadata( + '', + { + name: 'handle', + path: '/l', + handle: { + stack: [{ route: { path: '/b' } }], + }, + } as unknown as ExpressLayer, + '/x', + ), + ).toStrictEqual({ + attributes: { + [ATTR_EXPRESS_NAME]: '/x', + [ATTR_EXPRESS_TYPE]: 'request_handler', + }, + name: 'request handler - /x', + }); + expect( + getLayerMetadata( + '', + { + name: 'some_other_thing', + path: '/l', + handle: { + stack: [{ route: { path: '/b' } }], + }, + } as unknown as ExpressLayer, + '/x', + ), + ).toStrictEqual({ + attributes: { + [ATTR_EXPRESS_NAME]: 'some_other_thing', + [ATTR_EXPRESS_TYPE]: 'middleware', + }, + name: 'middleware - some_other_thing', + }); + }); +}); + +describe('isLayerIgnored', () => { + it('ignores layers that include the ignored type', () => { + expect( + isLayerIgnored('x', 'router', { + ignoreLayersType: ['router'], + } as unknown as ExpressIntegrationOptions), + ).toBe(true); + + expect( + isLayerIgnored('x', 'router', { + ignoreLayers: [/^x$/], + } as unknown as ExpressIntegrationOptions), + ).toBe(true); + + expect( + isLayerIgnored('x', 'router', { + ignoreLayers: ['x'], + } as unknown as ExpressIntegrationOptions), + ).toBe(true); + expect( + isLayerIgnored('x', 'router', { + ignoreLayers: [() => true], + } as unknown as ExpressIntegrationOptions), + ).toBe(true); + + expect(isLayerIgnored('x', 'router', {} as unknown as ExpressIntegrationOptions)).toBe(false); + expect( + isLayerIgnored('x', 'router', { + ignoreLayersType: ['middleware'], + } as unknown as ExpressIntegrationOptions), + ).toBe(false); + expect( + isLayerIgnored('x', 'router', { + ignoreLayers: [() => false], + } as unknown as ExpressIntegrationOptions), + ).toBe(false); + expect( + isLayerIgnored('x', 'router', { + ignoreLayers: [ + () => { + throw new Error('x'); + }, + ], + } as unknown as ExpressIntegrationOptions), + ).toBe(false); + }); +}); + +describe('getActualMatchedRoute', () => { + it('handles empty layersStore', () => { + const req = {} as unknown as ExpressRequest; + expect(getActualMatchedRoute(req, getConstructedRoute(req))).toBe(undefined); + }); + + it('handles case when all stored layers are /', () => { + const req = { originalUrl: '/' } as unknown as ExpressRequest; + storeLayer(req, '/'); + expect(getActualMatchedRoute(req, getConstructedRoute(req))).toBe('/'); + req.originalUrl = '/other-thing'; + expect(getActualMatchedRoute(req, getConstructedRoute(req))).toBe(undefined); + }); + + it('returns constructed route if *', () => { + const req = { originalUrl: '/xyz' } as unknown as ExpressRequest; + storeLayer(req, '*'); + expect(getActualMatchedRoute(req, getConstructedRoute(req))).toBe('*'); + }); + + it('returns constructed route when it looks regexp-ish', () => { + const req = { originalUrl: '/xyz' } as unknown as ExpressRequest; + storeLayer(req, '/\\,[*]/'); + expect(getActualMatchedRoute(req, getConstructedRoute(req))).toBe('/\\,[*]/'); + }); + + it('ensures constructed route starts with /', () => { + const req = { originalUrl: '/a/b' } as unknown as ExpressRequest; + storeLayer(req, 'a'); + storeLayer(req, '/b'); + expect(getActualMatchedRoute(req, getConstructedRoute(req))).toBe('/a/b'); + }); + + it('allows routes that contain *', () => { + const req = { originalUrl: '/a/b' } as unknown as ExpressRequest; + storeLayer(req, 'a'); + storeLayer(req, '/:boo'); + expect(getActualMatchedRoute(req, getConstructedRoute(req))).toBe('/a/:boo'); + }); + + it('returns undefined if invalid', () => { + const req = { originalUrl: '/a/b' } as unknown as ExpressRequest; + storeLayer(req, '/a'); + storeLayer(req, '/c'); + expect(getActualMatchedRoute(req, getConstructedRoute(req))).toBe(undefined); + }); +}); + +describe('getConstructedRoute', () => { + it('returns * when the only meaningful path', () => { + const req = {} as unknown as ExpressRequest; + storeLayer(req, '*'); + // not-meaningful paths + storeLayer(req, '/'); + storeLayer(req, '/*'); + expect(getConstructedRoute(req)).toBe('*'); + }); + + it('joins meaningful paths together', () => { + const req = {} as unknown as ExpressRequest; + storeLayer(req, '/a'); + storeLayer(req, '/b/'); + storeLayer(req, '/*'); + storeLayer(req, '/c'); + expect(getConstructedRoute(req)).toBe('/a/b/c'); + }); +}); + +describe('hasDefaultProp', () => { + it('returns detects the presence of a default function prop', () => { + expect(hasDefaultProp({ default: function express() {} })).toBe(true); + expect(hasDefaultProp({ default: 'other thing' })).toBe(false); + expect(hasDefaultProp({})).toBe(false); + }); +}); + +describe('isExpressWith(out)RouterPrototype', () => { + it('detects what kind of express this is', () => { + expect(isExpressWithoutRouterPrototype({})).toBe(false); + expect( + isExpressWithoutRouterPrototype( + Object.assign(function express() {}, { + Router: Object.assign(function Router() {}, { + route() {}, + }), + }), + ), + ).toBe(true); + expect( + isExpressWithoutRouterPrototype( + Object.assign(function express() {}, { + Router: class Router { + route() {} + }, + }), + ), + ).toBe(false); + expect(isExpressWithRouterPrototype({})).toBe(false); + expect( + isExpressWithRouterPrototype({ + Router: Object.assign(function Router() {}, { + route() {}, + }), + }), + ).toBe(false); + expect( + isExpressWithRouterPrototype({ + Router: class Router { + route() {} + }, + }), + ).toBe(true); + }); +}); + +describe('getLayerPath', () => { + it('extracts the layer path segment from first arg', () => { + expect(getLayerPath(['/x'])).toBe('/x'); + expect(getLayerPath([['/x', '/y']])).toBe('/x,/y'); + expect(getLayerPath([['/x', null, 1, /z/i, '/y']])).toBe('/x,,1,/z/i,/y'); + }); +}); + +describe('defaultShouldHandleError', () => { + it('returns true if the response status code is 500', () => { + // just a wrapper to not have to type this out each time. + const _ = (o: unknown): MiddlewareError => o as MiddlewareError; + expect(defaultShouldHandleError(_({ status: 500 }))).toBe(true); + expect(defaultShouldHandleError(_({ statusCode: 500 }))).toBe(true); + expect(defaultShouldHandleError(_({ status_code: 500 }))).toBe(true); + expect(defaultShouldHandleError(_({ output: { statusCode: 500 } }))).toBe(true); + expect(defaultShouldHandleError(_({}))).toBe(true); + expect(defaultShouldHandleError(_({ status: 200 }))).toBe(false); + expect(defaultShouldHandleError(_({ statusCode: 200 }))).toBe(false); + expect(defaultShouldHandleError(_({ status_code: 200 }))).toBe(false); + expect(defaultShouldHandleError(_({ output: { statusCode: 200 } }))).toBe(false); + }); +}); diff --git a/packages/core/test/lib/integrations/mcp-server/mcpServerWrapper.test.ts b/packages/core/test/lib/integrations/mcp-server/mcpServerWrapper.test.ts index c277162017aa..3fc48a2e0b47 100644 --- a/packages/core/test/lib/integrations/mcp-server/mcpServerWrapper.test.ts +++ b/packages/core/test/lib/integrations/mcp-server/mcpServerWrapper.test.ts @@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import * as currentScopes from '../../../../src/currentScopes'; import { wrapMcpServerWithSentry } from '../../../../src/integrations/mcp-server'; import * as tracingModule from '../../../../src/tracing'; -import { createMockMcpServer } from './testUtils'; +import { createMockMcpServer, createMockMcpServerWithRegisterApi } from './testUtils'; describe('wrapMcpServerWithSentry', () => { const startSpanSpy = vi.spyOn(tracingModule, 'startSpan'); @@ -45,6 +45,19 @@ describe('wrapMcpServerWithSentry', () => { expect(startInactiveSpanSpy).not.toHaveBeenCalled(); }); + it('should accept a server with only the new register* API (no legacy methods)', () => { + const mockServer = createMockMcpServerWithRegisterApi(); + const result = wrapMcpServerWithSentry(mockServer); + expect(result).toBe(mockServer); + }); + + it('should reject a server with neither legacy nor register* methods', () => { + const invalidServer = { connect: vi.fn() }; + const result = wrapMcpServerWithSentry(invalidServer); + expect(result).toBe(invalidServer); + expect(startSpanSpy).not.toHaveBeenCalled(); + }); + it('should not wrap the same instance twice', () => { const mockMcpServer = createMockMcpServer(); @@ -77,6 +90,19 @@ describe('wrapMcpServerWithSentry', () => { expect(wrappedMcpServer.prompt).not.toBe(originalPrompt); }); + it('should wrap handler methods (registerTool, registerResource, registerPrompt)', () => { + const mockServer = createMockMcpServerWithRegisterApi(); + const originalRegisterTool = mockServer.registerTool; + const originalRegisterResource = mockServer.registerResource; + const originalRegisterPrompt = mockServer.registerPrompt; + + const wrapped = wrapMcpServerWithSentry(mockServer); + + expect(wrapped.registerTool).not.toBe(originalRegisterTool); + expect(wrapped.registerResource).not.toBe(originalRegisterResource); + expect(wrapped.registerPrompt).not.toBe(originalRegisterPrompt); + }); + describe('Handler Wrapping', () => { let mockMcpServer: ReturnType; let wrappedMcpServer: ReturnType; @@ -118,4 +144,38 @@ describe('wrapMcpServerWithSentry', () => { }).not.toThrow(); }); }); + + describe('Handler Wrapping (register* API)', () => { + let mockServer: ReturnType; + let wrappedServer: ReturnType; + + beforeEach(() => { + mockServer = createMockMcpServerWithRegisterApi(); + wrappedServer = wrapMcpServerWithSentry(mockServer); + }); + + it('should register tool handlers via registerTool without throwing errors', () => { + const toolHandler = vi.fn(); + + expect(() => { + wrappedServer.registerTool('test-tool', {}, toolHandler); + }).not.toThrow(); + }); + + it('should register resource handlers via registerResource without throwing errors', () => { + const resourceHandler = vi.fn(); + + expect(() => { + wrappedServer.registerResource('test-resource', 'res://test', {}, resourceHandler); + }).not.toThrow(); + }); + + it('should register prompt handlers via registerPrompt without throwing errors', () => { + const promptHandler = vi.fn(); + + expect(() => { + wrappedServer.registerPrompt('test-prompt', {}, promptHandler); + }).not.toThrow(); + }); + }); }); diff --git a/packages/core/test/lib/integrations/mcp-server/testUtils.ts b/packages/core/test/lib/integrations/mcp-server/testUtils.ts index 782f03a78e35..23b9ee6ff51b 100644 --- a/packages/core/test/lib/integrations/mcp-server/testUtils.ts +++ b/packages/core/test/lib/integrations/mcp-server/testUtils.ts @@ -1,7 +1,7 @@ import { vi } from 'vitest'; /** - * Create a mock MCP server instance for testing + * Create a mock MCP server instance for testing (legacy API: tool/resource/prompt) */ export function createMockMcpServer() { return { @@ -15,6 +15,21 @@ export function createMockMcpServer() { }; } +/** + * Create a mock MCP server instance using the new register* API (SDK >=1.x / 2.x) + */ +export function createMockMcpServerWithRegisterApi() { + return { + registerResource: vi.fn(), + registerTool: vi.fn(), + registerPrompt: vi.fn(), + connect: vi.fn().mockResolvedValue(undefined), + server: { + setRequestHandler: vi.fn(), + }, + }; +} + /** * Create a mock HTTP transport (StreamableHTTPServerTransport) * Uses exact naming pattern from the official SDK diff --git a/packages/core/test/lib/integrations/mcp-server/transportInstrumentation.test.ts b/packages/core/test/lib/integrations/mcp-server/transportInstrumentation.test.ts index c720512cb97b..71590fd17712 100644 --- a/packages/core/test/lib/integrations/mcp-server/transportInstrumentation.test.ts +++ b/packages/core/test/lib/integrations/mcp-server/transportInstrumentation.test.ts @@ -182,6 +182,68 @@ describe('MCP Server Transport Instrumentation', () => { // Trigger onclose - should not throw expect(() => mockTransport.onclose?.()).not.toThrow(); }); + + it('should set span status to error when JSON-RPC error response is sent', async () => { + const mockSpan = { + setAttributes: vi.fn(), + setStatus: vi.fn(), + end: vi.fn(), + isRecording: vi.fn().mockReturnValue(true), + }; + startInactiveSpanSpy.mockReturnValue(mockSpan as any); + + await wrappedMcpServer.connect(mockTransport); + + // Simulate an incoming tools/call request + const jsonRpcRequest = { + jsonrpc: '2.0', + method: 'tools/call', + id: 'req-err-1', + params: { name: 'always-error' }, + }; + mockTransport.onmessage?.(jsonRpcRequest, {}); + + // Simulate the MCP SDK sending back a JSON-RPC error response + const jsonRpcErrorResponse = { + jsonrpc: '2.0', + id: 'req-err-1', + error: { code: -32603, message: 'Internal error: tool threw an exception' }, + }; + await mockTransport.send?.(jsonRpcErrorResponse as any); + + expect(mockSpan.setStatus).toHaveBeenCalledWith({ code: 2, message: 'internal_error' }); + expect(mockSpan.end).toHaveBeenCalled(); + }); + + it('should not set error span status for successful JSON-RPC responses', async () => { + const mockSpan = { + setAttributes: vi.fn(), + setStatus: vi.fn(), + end: vi.fn(), + isRecording: vi.fn().mockReturnValue(true), + }; + startInactiveSpanSpy.mockReturnValue(mockSpan as any); + + await wrappedMcpServer.connect(mockTransport); + + const jsonRpcRequest = { + jsonrpc: '2.0', + method: 'tools/call', + id: 'req-ok-1', + params: { name: 'echo' }, + }; + mockTransport.onmessage?.(jsonRpcRequest, {}); + + const jsonRpcSuccessResponse = { + jsonrpc: '2.0', + id: 'req-ok-1', + result: { content: [{ type: 'text', text: 'hello' }] }, + }; + await mockTransport.send?.(jsonRpcSuccessResponse as any); + + expect(mockSpan.setStatus).not.toHaveBeenCalled(); + expect(mockSpan.end).toHaveBeenCalled(); + }); }); describe('Stdio Transport Tests', () => { diff --git a/packages/core/test/lib/integrations/third-party-errors-filter.test.ts b/packages/core/test/lib/integrations/third-party-errors-filter.test.ts index e519cfd2564c..dd93847baf63 100644 --- a/packages/core/test/lib/integrations/third-party-errors-filter.test.ts +++ b/packages/core/test/lib/integrations/third-party-errors-filter.test.ts @@ -672,4 +672,37 @@ describe('ThirdPartyErrorFilter', () => { }); }); }); + + // Regression test for https://github.com/getsentry/sentry-javascript/issues/20052 + // The thirdPartyErrorFilterIntegration triggers addMetadataToStackFrames on every error event, + // which calls ensureMetadataStacksAreParsed to parse all _sentryModuleMetadata stack keys. + // This test verifies that metadata is correctly resolved even when the module metadata stacks + // contain long lines (e.g. from minified bundles with long URLs/identifiers). + describe('metadata stack parsing with long stack lines', () => { + it('resolves metadata for frames whose filenames appear in module metadata stacks with long URLs', () => { + const longFilename = `https://example.com/_next/static/chunks/${'a'.repeat(200)}.js`; + + // Simulate a module metadata entry with a realistic stack containing a long filename + const fakeStack = [`Error: Sentry Module Metadata`, ` at Object. (${longFilename}:1:1)`].join('\n'); + GLOBAL_OBJ._sentryModuleMetadata![fakeStack] = { '_sentryBundlerPluginAppKey:long-url-key': true }; + + const event: Event = { + exception: { + values: [ + { + stacktrace: { + frames: [{ filename: longFilename, function: 'test', lineno: 1, colno: 1 }], + }, + }, + ], + }, + }; + + addMetadataToStackFrames(stackParser, event); + + // The frame should have module_metadata attached from the parsed metadata stack + const frame = event.exception!.values![0]!.stacktrace!.frames![0]!; + expect(frame.module_metadata).toEqual({ '_sentryBundlerPluginAppKey:long-url-key': true }); + }); + }); }); diff --git a/packages/core/test/lib/tracing/langchain-embeddings.test.ts b/packages/core/test/lib/tracing/langchain-embeddings.test.ts new file mode 100644 index 000000000000..f1bed062b4b2 --- /dev/null +++ b/packages/core/test/lib/tracing/langchain-embeddings.test.ts @@ -0,0 +1,134 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { + GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE, + GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE, + GEN_AI_OPERATION_NAME_ATTRIBUTE, + GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE, + GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE, + GEN_AI_REQUEST_MODEL_ATTRIBUTE, + GEN_AI_SYSTEM_ATTRIBUTE, +} from '../../../src/tracing/ai/gen-ai-attributes'; +import { instrumentEmbeddingMethod, instrumentLangChainEmbeddings } from '../../../src/tracing/langchain/embeddings'; + +vi.mock('../../../src/tracing/ai/utils', () => ({ + resolveAIRecordingOptions: (options: { recordInputs?: boolean; recordOutputs?: boolean } = {}) => ({ + recordInputs: options.recordInputs ?? false, + recordOutputs: options.recordOutputs ?? false, + }), +})); + +let capturedSpanConfig: { name: string; op: string; attributes: Record } | undefined; + +vi.mock('../../../src/tracing/trace', () => ({ + startSpan: ( + config: { name: string; op: string; attributes: Record }, + callback: (span: unknown) => unknown, + ) => { + capturedSpanConfig = config; + return callback({ setAttribute: vi.fn() }); + }, +})); + +import { captureException } from '../../../src/exports'; + +vi.mock('../../../src/exports', () => ({ + captureException: vi.fn(), +})); + +describe('instrumentEmbeddingMethod', () => { + beforeEach(() => { + capturedSpanConfig = undefined; + }); + + it('creates a span with correct attributes', async () => { + const original = vi.fn().mockResolvedValue([0.1, 0.2, 0.3]); + const wrapped = instrumentEmbeddingMethod(original); + + const instance = { + constructor: { name: 'OpenAIEmbeddings' }, + model: 'text-embedding-3-small', + dimensions: 1536, + encodingFormat: 'float', + }; + await wrapped.call(instance, 'Hello world'); + + expect(capturedSpanConfig).toBeDefined(); + expect(capturedSpanConfig!.name).toBe('embeddings text-embedding-3-small'); + expect(capturedSpanConfig!.op).toBe(GEN_AI_EMBEDDINGS_OPERATION_ATTRIBUTE); + expect(capturedSpanConfig!.attributes[GEN_AI_OPERATION_NAME_ATTRIBUTE]).toBe('embeddings'); + expect(capturedSpanConfig!.attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE]).toBe('text-embedding-3-small'); + expect(capturedSpanConfig!.attributes[GEN_AI_SYSTEM_ATTRIBUTE]).toBe('openai'); + expect(capturedSpanConfig!.attributes[GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE]).toBe(1536); + expect(capturedSpanConfig!.attributes[GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE]).toBe('float'); + expect(original).toHaveBeenCalledWith('Hello world'); + }); + + it('records input when recordInputs is true', async () => { + const original = vi.fn().mockResolvedValue([0.1]); + const instance = { constructor: { name: 'OpenAIEmbeddings' }, model: 'text-embedding-3-small' }; + + const wrapped = instrumentEmbeddingMethod(original, { recordInputs: true }); + await wrapped.call(instance, 'Hello world'); + expect(capturedSpanConfig!.attributes[GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE]).toBe('Hello world'); + + await wrapped.call(instance, ['doc1', 'doc2']); + expect(capturedSpanConfig!.attributes[GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE]).toBe('["doc1","doc2"]'); + }); + + it('captures exception on failure', async () => { + const error = new Error('API error'); + const original = vi.fn().mockRejectedValue(error); + const wrapped = instrumentEmbeddingMethod(original); + + const instance = { constructor: { name: 'OpenAIEmbeddings' }, model: 'error-model' }; + await expect(wrapped.call(instance, 'test')).rejects.toThrow('API error'); + + expect(captureException).toHaveBeenCalledWith(error, { + mechanism: { handled: false, type: 'auto.ai.langchain' }, + }); + }); + + it('infers system from class name', async () => { + const original = vi.fn().mockResolvedValue([0.1]); + const wrapped = instrumentEmbeddingMethod(original); + + await wrapped.call({ constructor: { name: 'GoogleGenerativeAIEmbeddings' }, model: 'test' }, 'test'); + expect(capturedSpanConfig!.attributes[GEN_AI_SYSTEM_ATTRIBUTE]).toBe('google_genai'); + }); + + it('handles missing instance properties gracefully', async () => { + const original = vi.fn().mockResolvedValue([0.1]); + const wrapped = instrumentEmbeddingMethod(original); + + await wrapped.call({}, 'test'); + + expect(capturedSpanConfig!.name).toBe('embeddings unknown'); + expect(capturedSpanConfig!.attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE]).toBe('unknown'); + expect(capturedSpanConfig!.attributes[GEN_AI_SYSTEM_ATTRIBUTE]).toBe('langchain'); + expect(capturedSpanConfig!.attributes[GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE]).toBeUndefined(); + }); +}); + +describe('instrumentLangChainEmbeddings', () => { + beforeEach(() => { + capturedSpanConfig = undefined; + }); + + it('wraps both embedQuery and embedDocuments on an instance', async () => { + const instance = { + constructor: { name: 'OpenAIEmbeddings' }, + model: 'text-embedding-3-small', + embedQuery: vi.fn().mockResolvedValue([0.1]), + embedDocuments: vi.fn().mockResolvedValue([[0.1]]), + }; + + const wrapped = instrumentLangChainEmbeddings(instance); + expect(wrapped).toBe(instance); + + await wrapped.embedQuery('test'); + expect(capturedSpanConfig!.attributes[GEN_AI_OPERATION_NAME_ATTRIBUTE]).toBe('embeddings'); + + await wrapped.embedDocuments(['doc1']); + expect(capturedSpanConfig!.attributes[GEN_AI_OPERATION_NAME_ATTRIBUTE]).toBe('embeddings'); + }); +}); diff --git a/packages/core/test/lib/tracing/spans/beforeSendSpan.test.ts b/packages/core/test/lib/tracing/spans/beforeSendSpan.test.ts new file mode 100644 index 000000000000..79fd838a1b27 --- /dev/null +++ b/packages/core/test/lib/tracing/spans/beforeSendSpan.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it, vi } from 'vitest'; +import { withStreamedSpan } from '../../../../src'; +import { isStreamedBeforeSendSpanCallback } from '../../../../src/tracing/spans/beforeSendSpan'; + +describe('beforeSendSpan for span streaming', () => { + describe('withStreamedSpan', () => { + it('should be able to modify the span', () => { + const beforeSendSpan = vi.fn(); + const wrapped = withStreamedSpan(beforeSendSpan); + expect(wrapped._streamed).toBe(true); + }); + }); + + describe('isStreamedBeforeSendSpanCallback', () => { + it('returns true if the callback is wrapped with withStreamedSpan', () => { + const beforeSendSpan = vi.fn(); + const wrapped = withStreamedSpan(beforeSendSpan); + expect(isStreamedBeforeSendSpanCallback(wrapped)).toBe(true); + }); + + it('returns false if the callback is not wrapped with withStreamedSpan', () => { + const beforeSendSpan = vi.fn(); + expect(isStreamedBeforeSendSpanCallback(beforeSendSpan)).toBe(false); + }); + }); +}); diff --git a/packages/core/test/lib/tracing/spans/captureSpan.test.ts b/packages/core/test/lib/tracing/spans/captureSpan.test.ts new file mode 100644 index 000000000000..d429d50714a2 --- /dev/null +++ b/packages/core/test/lib/tracing/spans/captureSpan.test.ts @@ -0,0 +1,485 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { StreamedSpanJSON } from '../../../../src'; +import { + captureSpan, + SEMANTIC_ATTRIBUTE_SENTRY_ENVIRONMENT, + SEMANTIC_ATTRIBUTE_SENTRY_OP, + SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, + SEMANTIC_ATTRIBUTE_SENTRY_RELEASE, + SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, + SEMANTIC_ATTRIBUTE_SENTRY_SDK_NAME, + SEMANTIC_ATTRIBUTE_SENTRY_SDK_VERSION, + SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID, + SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME, + SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, + SEMANTIC_ATTRIBUTE_USER_EMAIL, + SEMANTIC_ATTRIBUTE_USER_ID, + SEMANTIC_ATTRIBUTE_USER_IP_ADDRESS, + SEMANTIC_ATTRIBUTE_USER_USERNAME, + startInactiveSpan, + startSpan, + withScope, + withStreamedSpan, +} from '../../../../src'; +import { safeSetSpanJSONAttributes } from '../../../../src/tracing/spans/captureSpan'; +import { getDefaultTestClientOptions, TestClient } from '../../../mocks/client'; + +describe('captureSpan', () => { + it('captures user attributes iff sendDefaultPii is true', () => { + const client = new TestClient( + getDefaultTestClientOptions({ + dsn: 'https://dsn@ingest.f00.f00/1', + tracesSampleRate: 1, + release: '1.0.0', + environment: 'staging', + sendDefaultPii: true, + }), + ); + + const span = withScope(scope => { + scope.setClient(client); + scope.setUser({ + id: '123', + email: 'user@example.com', + username: 'testuser', + ip_address: '127.0.0.1', + }); + + const span = startInactiveSpan({ name: 'my-span', attributes: { 'sentry.op': 'http.client' } }); + span.end(); + + return span; + }); + + const serializedSpan = captureSpan(span, client); + + expect(serializedSpan).toStrictEqual({ + span_id: expect.stringMatching(/^[\da-f]{16}$/), + trace_id: expect.stringMatching(/^[\da-f]{32}$/), + parent_span_id: undefined, + links: undefined, + start_timestamp: expect.any(Number), + name: 'my-span', + end_timestamp: expect.any(Number), + status: 'ok', + is_segment: true, + attributes: { + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: { + type: 'string', + value: 'http.client', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: { + type: 'string', + value: 'manual', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: { + type: 'integer', + value: 1, + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME]: { + value: 'my-span', + type: 'string', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID]: { + value: span.spanContext().spanId, + type: 'string', + }, + 'sentry.span.source': { + value: 'custom', + type: 'string', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: { + value: 'custom', + type: 'string', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_RELEASE]: { + value: '1.0.0', + type: 'string', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_ENVIRONMENT]: { + value: 'staging', + type: 'string', + }, + [SEMANTIC_ATTRIBUTE_USER_ID]: { + value: '123', + type: 'string', + }, + [SEMANTIC_ATTRIBUTE_USER_EMAIL]: { + value: 'user@example.com', + type: 'string', + }, + [SEMANTIC_ATTRIBUTE_USER_USERNAME]: { + value: 'testuser', + type: 'string', + }, + [SEMANTIC_ATTRIBUTE_USER_IP_ADDRESS]: { + value: '127.0.0.1', + type: 'string', + }, + }, + _segmentSpan: span, + }); + }); + + it.each([false, undefined])("doesn't capture user attributes if sendDefaultPii is %s", sendDefaultPii => { + const client = new TestClient( + getDefaultTestClientOptions({ + dsn: 'https://dsn@ingest.f00.f00/1', + tracesSampleRate: 1, + release: '1.0.0', + environment: 'staging', + sendDefaultPii, + }), + ); + + const span = withScope(scope => { + scope.setClient(client); + scope.setUser({ + id: '123', + email: 'user@example.com', + username: 'testuser', + ip_address: '127.0.0.1', + }); + + const span = startInactiveSpan({ name: 'my-span', attributes: { 'sentry.op': 'http.client' } }); + span.end(); + + return span; + }); + + expect(captureSpan(span, client)).toStrictEqual({ + span_id: expect.stringMatching(/^[\da-f]{16}$/), + trace_id: expect.stringMatching(/^[\da-f]{32}$/), + parent_span_id: undefined, + links: undefined, + start_timestamp: expect.any(Number), + name: 'my-span', + end_timestamp: expect.any(Number), + status: 'ok', + is_segment: true, + attributes: { + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: { + type: 'string', + value: 'http.client', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: { + type: 'string', + value: 'manual', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: { + type: 'integer', + value: 1, + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME]: { + value: 'my-span', + type: 'string', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID]: { + value: span.spanContext().spanId, + type: 'string', + }, + 'sentry.span.source': { + value: 'custom', + type: 'string', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: { + value: 'custom', + type: 'string', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_RELEASE]: { + value: '1.0.0', + type: 'string', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_ENVIRONMENT]: { + value: 'staging', + type: 'string', + }, + }, + _segmentSpan: span, + }); + }); + + it('captures sdk name and version if available', () => { + const client = new TestClient( + getDefaultTestClientOptions({ + dsn: 'https://dsn@ingest.f00.f00/1', + tracesSampleRate: 1, + release: '1.0.0', + environment: 'staging', + _metadata: { + sdk: { + name: 'sentry.javascript.node', + version: '1.0.0', + integrations: ['UnhandledRejection', 'Dedupe'], + }, + }, + }), + ); + + const span = withScope(scope => { + scope.setClient(client); + scope.setUser({ + id: '123', + email: 'user@example.com', + username: 'testuser', + ip_address: '127.0.0.1', + }); + + const span = startInactiveSpan({ name: 'my-span', attributes: { 'sentry.op': 'http.client' } }); + span.end(); + + return span; + }); + + expect(captureSpan(span, client)).toStrictEqual({ + span_id: expect.stringMatching(/^[\da-f]{16}$/), + trace_id: expect.stringMatching(/^[\da-f]{32}$/), + parent_span_id: undefined, + links: undefined, + start_timestamp: expect.any(Number), + name: 'my-span', + end_timestamp: expect.any(Number), + status: 'ok', + is_segment: true, + attributes: { + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: { + type: 'string', + value: 'http.client', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: { + type: 'string', + value: 'manual', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: { + type: 'integer', + value: 1, + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME]: { + value: 'my-span', + type: 'string', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_ID]: { + value: span.spanContext().spanId, + type: 'string', + }, + 'sentry.span.source': { + value: 'custom', + type: 'string', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: { + value: 'custom', + type: 'string', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_RELEASE]: { + value: '1.0.0', + type: 'string', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_ENVIRONMENT]: { + value: 'staging', + type: 'string', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_NAME]: { + value: 'sentry.javascript.node', + type: 'string', + }, + [SEMANTIC_ATTRIBUTE_SENTRY_SDK_VERSION]: { + value: '1.0.0', + type: 'string', + }, + }, + _segmentSpan: span, + }); + }); + + describe('client hooks', () => { + it('calls processSpan and processSegmentSpan hooks for a segment span', () => { + const client = new TestClient( + getDefaultTestClientOptions({ + dsn: 'https://dsn@ingest.f00.f00/1', + tracesSampleRate: 1, + release: '1.0.0', + environment: 'staging', + }), + ); + + const processSpanFn = vi.fn(); + const processSegmentSpanFn = vi.fn(); + client.on('processSpan', processSpanFn); + client.on('processSegmentSpan', processSegmentSpanFn); + + const span = startInactiveSpan({ name: 'my-span', attributes: { 'sentry.op': 'http.client' } }); + + captureSpan(span, client); + + expect(processSpanFn).toHaveBeenCalledWith(expect.objectContaining({ span_id: span.spanContext().spanId })); + expect(processSegmentSpanFn).toHaveBeenCalledWith( + expect.objectContaining({ span_id: span.spanContext().spanId }), + ); + }); + + it('only calls processSpan hook for a child span', () => { + const client = new TestClient( + getDefaultTestClientOptions({ + dsn: 'https://dsn@ingest.f00.f00/1', + tracesSampleRate: 1, + release: '1.0.0', + environment: 'staging', + sendDefaultPii: true, + }), + ); + + const processSpanFn = vi.fn(); + const processSegmentSpanFn = vi.fn(); + client.on('processSpan', processSpanFn); + client.on('processSegmentSpan', processSegmentSpanFn); + + const serializedChildSpan = withScope(scope => { + scope.setClient(client); + scope.setUser({ + id: '123', + email: 'user@example.com', + username: 'testuser', + ip_address: '127.0.0.1', + }); + + return startSpan({ name: 'segment' }, () => { + const childSpan = startInactiveSpan({ name: 'child' }); + childSpan.end(); + return captureSpan(childSpan, client); + }); + }); + + expect(serializedChildSpan?.name).toBe('child'); + expect(serializedChildSpan?.is_segment).toBe(false); + + expect(processSpanFn).toHaveBeenCalledWith(expect.objectContaining({ span_id: serializedChildSpan?.span_id })); + expect(processSegmentSpanFn).not.toHaveBeenCalled(); + }); + }); + + describe('beforeSendSpan', () => { + it('applies beforeSendSpan if it is a span streaming compatible callback', () => { + const beforeSendSpan = withStreamedSpan(vi.fn(span => span)); + + const client = new TestClient( + getDefaultTestClientOptions({ + dsn: 'https://dsn@ingest.f00.f00/1', + tracesSampleRate: 1, + release: '1.0.0', + environment: 'staging', + beforeSendSpan, + }), + ); + + const span = startInactiveSpan({ name: 'my-span', attributes: { 'sentry.op': 'http.client' } }); + span.end(); + + captureSpan(span, client); + + expect(beforeSendSpan).toHaveBeenCalledWith(expect.objectContaining({ span_id: span.spanContext().spanId })); + }); + + it("doesn't apply beforeSendSpan if it is not a span streaming compatible callback", () => { + const beforeSendSpan = vi.fn(span => span); + + const client = new TestClient( + getDefaultTestClientOptions({ + dsn: 'https://dsn@ingest.f00.f00/1', + tracesSampleRate: 1, + release: '1.0.0', + environment: 'staging', + beforeSendSpan, + }), + ); + + const span = startInactiveSpan({ name: 'my-span', attributes: { 'sentry.op': 'http.client' } }); + span.end(); + + captureSpan(span, client); + + expect(beforeSendSpan).not.toHaveBeenCalled(); + }); + + it('logs a warning if the beforeSendSpan callback returns null', () => { + const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + // @ts-expect-error - the types dissallow returning null but this is javascript, so we need to test it + const beforeSendSpan = withStreamedSpan(() => null); + + const client = new TestClient( + getDefaultTestClientOptions({ + dsn: 'https://dsn@ingest.f00.f00/1', + tracesSampleRate: 1, + release: '1.0.0', + environment: 'staging', + beforeSendSpan, + }), + ); + + const span = startInactiveSpan({ name: 'my-span', attributes: { 'sentry.op': 'http.client' } }); + span.end(); + + captureSpan(span, client); + + expect(consoleWarnSpy).toHaveBeenCalledWith( + '[Sentry] Returning null from `beforeSendSpan` is disallowed. To drop certain spans, configure the respective integrations directly or use `ignoreSpans`.', + ); + + consoleWarnSpy.mockRestore(); + }); + }); +}); + +describe('safeSetSpanJSONAttributes', () => { + it('sets attributes that do not exist', () => { + const spanJSON = { attributes: { a: 1, b: 2 } }; + + // @ts-expect-error - only passing a partial object for this test + safeSetSpanJSONAttributes(spanJSON, { c: 3 }); + + expect(spanJSON.attributes).toEqual({ a: 1, b: 2, c: 3 }); + }); + + it("doesn't set attributes that already exist", () => { + const spanJSON = { attributes: { a: 1, b: 2 } }; + // @ts-expect-error - only passing a partial object for this test + safeSetSpanJSONAttributes(spanJSON, { a: 3 }); + + expect(spanJSON.attributes).toEqual({ a: 1, b: 2 }); + }); + + it.each([null, undefined])("doesn't overwrite attributes previously set to %s", val => { + const spanJSON = { attributes: { a: val, b: 2 } }; + + // @ts-expect-error - only passing a partial object for this test + safeSetSpanJSONAttributes(spanJSON, { a: 1 }); + + expect(spanJSON.attributes).toEqual({ a: val, b: 2 }); + }); + + it("doesn't overwrite falsy attribute values (%s)", () => { + const spanJSON = { attributes: { a: false, b: '', c: 0 } }; + + // @ts-expect-error - only passing a partial object for this test + safeSetSpanJSONAttributes(spanJSON, { a: 1, b: 'test', c: 1 }); + + expect(spanJSON.attributes).toEqual({ a: false, b: '', c: 0 }); + }); + + it('handles an undefined attributes property', () => { + const spanJSON: Partial = {}; + + // @ts-expect-error - only passing a partial object for this test + safeSetSpanJSONAttributes(spanJSON, { a: 1 }); + + expect(spanJSON.attributes).toEqual({ a: 1 }); + }); + + it("doesn't apply undefined or null values to attributes", () => { + const spanJSON = { attributes: {} }; + + // @ts-expect-error - only passing a partial object for this test + safeSetSpanJSONAttributes(spanJSON, { a: undefined, b: null }); + + expect(spanJSON.attributes).toEqual({}); + }); +}); diff --git a/packages/core/test/lib/tracing/spans/envelope.test.ts b/packages/core/test/lib/tracing/spans/envelope.test.ts new file mode 100644 index 000000000000..197b7ed40365 --- /dev/null +++ b/packages/core/test/lib/tracing/spans/envelope.test.ts @@ -0,0 +1,232 @@ +import { describe, expect, it } from 'vitest'; +import { createStreamedSpanEnvelope } from '../../../../src/tracing/spans/envelope'; +import type { DynamicSamplingContext } from '../../../../src/types-hoist/envelope'; +import type { SerializedStreamedSpan } from '../../../../src/types-hoist/span'; +import { getDefaultTestClientOptions, TestClient } from '../../../mocks/client'; + +function createMockSerializedSpan(overrides: Partial = {}): SerializedStreamedSpan { + return { + trace_id: 'abc123', + span_id: 'def456', + name: 'test-span', + start_timestamp: 1713859200, + end_timestamp: 1713859201, + status: 'ok', + is_segment: false, + ...overrides, + }; +} + +describe('createStreamedSpanEnvelope', () => { + describe('envelope headers', () => { + it('creates an envelope with sent_at header', () => { + const mockSpan = createMockSerializedSpan(); + const mockClient = new TestClient(getDefaultTestClientOptions()); + const dsc: Partial = {}; + + const result = createStreamedSpanEnvelope([mockSpan], dsc, mockClient); + + expect(result[0]).toHaveProperty('sent_at', expect.any(String)); + }); + + it('includes trace header when DSC has required props (trace_id and public_key)', () => { + const mockSpan = createMockSerializedSpan(); + const mockClient = new TestClient(getDefaultTestClientOptions()); + const dsc: DynamicSamplingContext = { + trace_id: 'trace-123', + public_key: 'public-key-abc', + sample_rate: '1.0', + release: 'v1.0.0', + }; + + const result = createStreamedSpanEnvelope([mockSpan], dsc, mockClient); + + expect(result[0]).toHaveProperty('trace', dsc); + }); + + it("does't include trace header when DSC is missing trace_id", () => { + const mockSpan = createMockSerializedSpan(); + const mockClient = new TestClient(getDefaultTestClientOptions()); + const dsc: Partial = { + public_key: 'public-key-abc', + }; + + const result = createStreamedSpanEnvelope([mockSpan], dsc, mockClient); + + expect(result[0]).not.toHaveProperty('trace'); + }); + + it("does't include trace header when DSC is missing public_key", () => { + const mockSpan = createMockSerializedSpan(); + const mockClient = new TestClient(getDefaultTestClientOptions()); + const dsc: Partial = { + trace_id: 'trace-123', + }; + + const result = createStreamedSpanEnvelope([mockSpan], dsc, mockClient); + + expect(result[0]).not.toHaveProperty('trace'); + }); + + it('includes SDK info when available in client options', () => { + const mockSpan = createMockSerializedSpan(); + const mockClient = new TestClient( + getDefaultTestClientOptions({ + _metadata: { + sdk: { name: 'sentry.javascript.browser', version: '8.0.0' }, + }, + }), + ); + const dsc: Partial = {}; + + const result = createStreamedSpanEnvelope([mockSpan], dsc, mockClient); + + expect(result[0]).toHaveProperty('sdk', { name: 'sentry.javascript.browser', version: '8.0.0' }); + }); + + it("does't include SDK info when not available", () => { + const mockSpan = createMockSerializedSpan(); + const mockClient = new TestClient(getDefaultTestClientOptions()); + const dsc: Partial = {}; + + const result = createStreamedSpanEnvelope([mockSpan], dsc, mockClient); + + expect(result[0]).not.toHaveProperty('sdk'); + }); + + it('includes DSN when tunnel and DSN are configured', () => { + const mockSpan = createMockSerializedSpan(); + const mockClient = new TestClient( + getDefaultTestClientOptions({ + dsn: 'https://abc123@example.sentry.io/456', + tunnel: 'https://tunnel.example.com', + }), + ); + const dsc: Partial = {}; + + const result = createStreamedSpanEnvelope([mockSpan], dsc, mockClient); + + expect(result[0]).toHaveProperty('dsn', 'https://abc123@example.sentry.io/456'); + }); + + it("does't include DSN when tunnel is not configured", () => { + const mockSpan = createMockSerializedSpan(); + const mockClient = new TestClient( + getDefaultTestClientOptions({ + dsn: 'https://abc123@example.sentry.io/456', + }), + ); + const dsc: Partial = {}; + + const result = createStreamedSpanEnvelope([mockSpan], dsc, mockClient); + + expect(result[0]).not.toHaveProperty('dsn'); + }); + + it("does't include DSN when DSN is not available", () => { + const mockSpan = createMockSerializedSpan(); + const mockClient = new TestClient( + getDefaultTestClientOptions({ + tunnel: 'https://tunnel.example.com', + }), + ); + const dsc: Partial = {}; + + const result = createStreamedSpanEnvelope([mockSpan], dsc, mockClient); + + expect(result[0]).not.toHaveProperty('dsn'); + }); + + it('includes all headers when all options are provided', () => { + const mockSpan = createMockSerializedSpan(); + const mockClient = new TestClient( + getDefaultTestClientOptions({ + dsn: 'https://abc123@example.sentry.io/456', + tunnel: 'https://tunnel.example.com', + _metadata: { + sdk: { name: 'sentry.javascript.node', version: '10.38.0' }, + }, + }), + ); + const dsc: DynamicSamplingContext = { + trace_id: 'trace-123', + public_key: 'public-key-abc', + environment: 'production', + }; + + const result = createStreamedSpanEnvelope([mockSpan], dsc, mockClient); + + expect(result[0]).toEqual({ + sent_at: expect.any(String), + trace: dsc, + sdk: { name: 'sentry.javascript.node', version: '10.38.0' }, + dsn: 'https://abc123@example.sentry.io/456', + }); + }); + }); + + describe('envelope item', () => { + it('creates a span container item with correct structure', () => { + const mockSpan = createMockSerializedSpan({ name: 'span-1' }); + const mockClient = new TestClient(getDefaultTestClientOptions()); + const dsc: Partial = {}; + + const envelopeItems = createStreamedSpanEnvelope([mockSpan], dsc, mockClient)[1]; + + expect(envelopeItems).toEqual([ + [ + { + content_type: 'application/vnd.sentry.items.span.v2+json', + item_count: 1, + type: 'span', + }, + { + items: [mockSpan], + }, + ], + ]); + }); + + it('sets correct item_count for multiple spans', () => { + const mockSpan1 = createMockSerializedSpan({ span_id: 'span-1' }); + const mockSpan2 = createMockSerializedSpan({ span_id: 'span-2' }); + const mockSpan3 = createMockSerializedSpan({ span_id: 'span-3' }); + const mockClient = new TestClient(getDefaultTestClientOptions()); + const dsc: Partial = {}; + + const envelopeItems = createStreamedSpanEnvelope([mockSpan1, mockSpan2, mockSpan3], dsc, mockClient)[1]; + + expect(envelopeItems).toEqual([ + [ + { type: 'span', item_count: 3, content_type: 'application/vnd.sentry.items.span.v2+json' }, + { items: [mockSpan1, mockSpan2, mockSpan3] }, + ], + ]); + }); + + it('handles empty spans array', () => { + const mockClient = new TestClient(getDefaultTestClientOptions()); + const dsc: Partial = {}; + + const result = createStreamedSpanEnvelope([], dsc, mockClient); + + expect(result).toEqual([ + { + sent_at: expect.any(String), + }, + [ + [ + { + content_type: 'application/vnd.sentry.items.span.v2+json', + item_count: 0, + type: 'span', + }, + { + items: [], + }, + ], + ], + ]); + }); + }); +}); diff --git a/packages/core/test/lib/tracing/spans/estimateSize.test.ts b/packages/core/test/lib/tracing/spans/estimateSize.test.ts new file mode 100644 index 000000000000..35d569691dea --- /dev/null +++ b/packages/core/test/lib/tracing/spans/estimateSize.test.ts @@ -0,0 +1,177 @@ +import { describe, expect, it } from 'vitest'; +import { estimateSerializedSpanSizeInBytes } from '../../../../src/tracing/spans/estimateSize'; +import type { SerializedStreamedSpan } from '../../../../src/types-hoist/span'; + +// Produces a realistic trace_id (32 hex chars) and span_id (16 hex chars) +const TRACE_ID = 'a1b2c3d4e5f607189a0b1c2d3e4f5060'; +const SPAN_ID = 'a1b2c3d4e5f60718'; + +describe('estimateSerializedSpanSizeInBytes', () => { + it('estimates a minimal span (no attributes, no links, no parent) within a reasonable range of JSON.stringify', () => { + const span: SerializedStreamedSpan = { + trace_id: TRACE_ID, + span_id: SPAN_ID, + name: 'GET /api/users', + start_timestamp: 1740000000.123, + end_timestamp: 1740000001.456, + status: 'ok', + is_segment: true, + }; + + const estimate = estimateSerializedSpanSizeInBytes(span); + const actual = JSON.stringify(span).length; + + expect(estimate).toBe(184); + expect(actual).toBe(196); + + expect(estimate).toBeLessThanOrEqual(actual * 1.2); + expect(estimate).toBeGreaterThanOrEqual(actual * 0.8); + }); + + it('estimates a span with a parent_span_id within a reasonable range', () => { + const span: SerializedStreamedSpan = { + trace_id: TRACE_ID, + span_id: SPAN_ID, + parent_span_id: 'b2c3d4e5f6071890', + name: 'db.query', + start_timestamp: 1740000000.0, + end_timestamp: 1740000000.05, + status: 'ok', + is_segment: false, + }; + + const estimate = estimateSerializedSpanSizeInBytes(span); + const actual = JSON.stringify(span).length; + + expect(estimate).toBe(172); + expect(actual).toBe(222); + + expect(estimate).toBeLessThanOrEqual(actual * 1.1); + expect(estimate).toBeGreaterThanOrEqual(actual * 0.7); + }); + + it('estimates a span with string attributes within a reasonable range', () => { + const span: SerializedStreamedSpan = { + trace_id: TRACE_ID, + span_id: SPAN_ID, + name: 'GET /api/users', + start_timestamp: 1740000000.0, + end_timestamp: 1740000000.1, + status: 'ok', + is_segment: false, + attributes: { + 'http.method': { type: 'string', value: 'GET' }, + 'http.url': { type: 'string', value: 'https://example.com/api/users?page=1&limit=100' }, + 'http.status_code': { type: 'integer', value: 200 }, + 'db.statement': { type: 'string', value: 'SELECT * FROM users WHERE id = $1' }, + 'sentry.origin': { type: 'string', value: 'auto.http.fetch' }, + }, + }; + + const estimate = estimateSerializedSpanSizeInBytes(span); + const actual = JSON.stringify(span).length; + + expect(estimate).toBeLessThanOrEqual(actual * 1.2); + expect(estimate).toBeGreaterThanOrEqual(actual * 0.8); + }); + + it('estimates a span with numeric attributes within a reasonable range', () => { + const span: SerializedStreamedSpan = { + trace_id: TRACE_ID, + span_id: SPAN_ID, + name: 'process.task', + start_timestamp: 1740000000.0, + end_timestamp: 1740000005.0, + status: 'ok', + is_segment: false, + attributes: { + 'items.count': { type: 'integer', value: 42 }, + 'duration.ms': { type: 'double', value: 5000.5 }, + 'retry.count': { type: 'integer', value: 3 }, + }, + }; + + const estimate = estimateSerializedSpanSizeInBytes(span); + const actual = JSON.stringify(span).length; + + expect(estimate).toBeLessThanOrEqual(actual * 1.2); + expect(estimate).toBeGreaterThanOrEqual(actual * 0.8); + }); + + it('estimates a span with boolean attributes within a reasonable range', () => { + const span: SerializedStreamedSpan = { + trace_id: TRACE_ID, + span_id: SPAN_ID, + name: 'cache.get', + start_timestamp: 1740000000.0, + end_timestamp: 1740000000.002, + status: 'ok', + is_segment: false, + attributes: { + 'cache.hit': { type: 'boolean', value: true }, + 'cache.miss': { type: 'boolean', value: false }, + }, + }; + + const estimate = estimateSerializedSpanSizeInBytes(span); + const actual = JSON.stringify(span).length; + + expect(estimate).toBeLessThanOrEqual(actual * 1.2); + expect(estimate).toBeGreaterThanOrEqual(actual * 0.8); + }); + + it('estimates a span with array attributes within a reasonable range', () => { + const span: SerializedStreamedSpan = { + trace_id: TRACE_ID, + span_id: SPAN_ID, + name: 'batch.process', + start_timestamp: 1740000000.0, + end_timestamp: 1740000002.0, + status: 'ok', + is_segment: false, + attributes: { + 'item.ids': { type: 'string[]', value: ['id-001', 'id-002', 'id-003', 'id-004', 'id-005'] }, + scores: { type: 'double[]', value: [1.1, 2.2, 3.3, 4.4] }, + flags: { type: 'boolean[]', value: [true, false, true] }, + }, + }; + + const estimate = estimateSerializedSpanSizeInBytes(span); + const actual = JSON.stringify(span).length; + + expect(estimate).toBeLessThanOrEqual(actual * 1.2); + expect(estimate).toBeGreaterThanOrEqual(actual * 0.8); + }); + + it('estimates a span with links within a reasonable range', () => { + const span: SerializedStreamedSpan = { + trace_id: TRACE_ID, + span_id: SPAN_ID, + name: 'linked.operation', + start_timestamp: 1740000000.0, + end_timestamp: 1740000001.0, + status: 'ok', + is_segment: true, + links: [ + { + trace_id: 'b2c3d4e5f607189a0b1c2d3e4f506070', + span_id: 'c3d4e5f607189a0b', + sampled: true, + attributes: { + 'sentry.link.type': { type: 'string', value: 'previous_trace' }, + }, + }, + { + trace_id: 'c3d4e5f607189a0b1c2d3e4f50607080', + span_id: 'd4e5f607189a0b1c', + }, + ], + }; + + const estimate = estimateSerializedSpanSizeInBytes(span); + const actual = JSON.stringify(span).length; + + expect(estimate).toBeLessThanOrEqual(actual * 1.2); + expect(estimate).toBeGreaterThanOrEqual(actual * 0.8); + }); +}); diff --git a/packages/core/test/lib/tracing/spans/spanBuffer.test.ts b/packages/core/test/lib/tracing/spans/spanBuffer.test.ts new file mode 100644 index 000000000000..cbcb1bf7ea59 --- /dev/null +++ b/packages/core/test/lib/tracing/spans/spanBuffer.test.ts @@ -0,0 +1,359 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { Client, StreamedSpanEnvelope } from '../../../../src'; +import { SentrySpan, setCurrentClient, SpanBuffer } from '../../../../src'; +import type { SerializedStreamedSpanWithSegmentSpan } from '../../../../src/tracing/spans/captureSpan'; +import { getDefaultTestClientOptions, TestClient } from '../../../mocks/client'; + +describe('SpanBuffer', () => { + let client: TestClient; + let sendEnvelopeSpy: ReturnType; + + let sentEnvelopes: Array = []; + + beforeEach(() => { + vi.useFakeTimers(); + sentEnvelopes = []; + sendEnvelopeSpy = vi.fn().mockImplementation(e => { + sentEnvelopes.push(e); + return Promise.resolve(); + }); + + client = new TestClient( + getDefaultTestClientOptions({ + dsn: 'https://username@domain/123', + tracesSampleRate: 1.0, + }), + ); + client.sendEnvelope = sendEnvelopeSpy; + client.init(); + setCurrentClient(client as Client); + }); + + afterEach(() => { + vi.useRealTimers(); + vi.clearAllMocks(); + }); + + it('flushes all traces on drain()', () => { + const buffer = new SpanBuffer(client); + + const segmentSpan1 = new SentrySpan({ name: 'segment', sampled: true, traceId: 'trace123' }); + const segmentSpan2 = new SentrySpan({ name: 'segment', sampled: true, traceId: 'trace456' }); + + buffer.add({ + trace_id: 'trace123', + span_id: 'span1', + name: 'test span', + start_timestamp: Date.now() / 1000, + end_timestamp: Date.now() / 1000, + status: 'ok', + is_segment: false, + _segmentSpan: segmentSpan1, + }); + + buffer.add({ + trace_id: 'trace456', + span_id: 'span2', + name: 'test span', + start_timestamp: Date.now() / 1000, + end_timestamp: Date.now() / 1000, + status: 'ok', + is_segment: false, + _segmentSpan: segmentSpan2, + }); + + buffer.drain(); + + expect(sendEnvelopeSpy).toHaveBeenCalledTimes(2); + expect(sentEnvelopes).toHaveLength(2); + expect(sentEnvelopes[0]?.[1]?.[0]?.[1]?.items[0]?.trace_id).toBe('trace123'); + expect(sentEnvelopes[1]?.[1]?.[0]?.[1]?.items[0]?.trace_id).toBe('trace456'); + }); + + it('flushes trace after per-trace timeout', () => { + const buffer = new SpanBuffer(client, { flushInterval: 1000 }); + + const segmentSpan1 = new SentrySpan({ name: 'segment', sampled: true }); + const span1 = { + trace_id: 'trace123', + span_id: 'span1', + name: 'test span', + start_timestamp: Date.now() / 1000, + end_timestamp: Date.now() / 1000, + status: 'ok', + is_segment: false, + _segmentSpan: segmentSpan1, + }; + + const segmentSpan2 = new SentrySpan({ name: 'segment2', sampled: true }); + const span2 = { + trace_id: 'trace123', + span_id: 'span2', + name: 'test span', + start_timestamp: Date.now() / 1000, + end_timestamp: Date.now() / 1000, + status: 'ok', + is_segment: false, + _segmentSpan: segmentSpan2, + }; + + buffer.add(span1 as SerializedStreamedSpanWithSegmentSpan); + buffer.add(span2 as SerializedStreamedSpanWithSegmentSpan); + + expect(sendEnvelopeSpy).not.toHaveBeenCalled(); + + vi.advanceTimersByTime(1000); + + expect(sendEnvelopeSpy).toHaveBeenCalledTimes(1); + + // the trace bucket was removed after flushing, so no timeout remains and no further sends occur + vi.advanceTimersByTime(1000); + expect(sendEnvelopeSpy).toHaveBeenCalledTimes(1); + }); + + it('flushes when maxSpanLimit is reached', () => { + const buffer = new SpanBuffer(client, { maxSpanLimit: 2 }); + + const segmentSpan = new SentrySpan({ name: 'segment', sampled: true }); + + buffer.add({ + trace_id: 'trace123', + span_id: 'span1', + name: 'test span 1', + start_timestamp: Date.now() / 1000, + end_timestamp: Date.now() / 1000, + status: 'ok', + is_segment: false, + _segmentSpan: segmentSpan, + }); + + expect(sendEnvelopeSpy).not.toHaveBeenCalled(); + + buffer.add({ + trace_id: 'trace123', + span_id: 'span2', + name: 'test span 2', + start_timestamp: Date.now() / 1000, + end_timestamp: Date.now() / 1000, + status: 'ok', + is_segment: false, + _segmentSpan: segmentSpan, + }); + + expect(sendEnvelopeSpy).toHaveBeenCalledTimes(1); + + buffer.add({ + trace_id: 'trace123', + span_id: 'span3', + name: 'test span 3', + start_timestamp: Date.now() / 1000, + end_timestamp: Date.now() / 1000, + status: 'ok', + is_segment: false, + _segmentSpan: segmentSpan, + }); + + // we added another span after flushing but neither limit nor time interval should have been reached + expect(sendEnvelopeSpy).toHaveBeenCalledTimes(1); + + // draining will flush out the remaining span + buffer.drain(); + expect(sendEnvelopeSpy).toHaveBeenCalledTimes(2); + }); + + it('flushes on client flush event', () => { + const buffer = new SpanBuffer(client); + + const segmentSpan = new SentrySpan({ name: 'segment', sampled: true }); + + buffer.add({ + trace_id: 'trace123', + span_id: 'span1', + name: 'test span', + start_timestamp: Date.now() / 1000, + end_timestamp: Date.now() / 1000, + status: 'ok', + is_segment: false, + _segmentSpan: segmentSpan, + }); + + expect(sendEnvelopeSpy).not.toHaveBeenCalled(); + + client.emit('flush'); + + expect(sendEnvelopeSpy).toHaveBeenCalledTimes(1); + }); + + it('groups spans by traceId', () => { + const buffer = new SpanBuffer(client); + + const segmentSpan1 = new SentrySpan({ name: 'segment1', sampled: true }); + const segmentSpan2 = new SentrySpan({ name: 'segment2', sampled: true }); + + buffer.add({ + trace_id: 'trace1', + span_id: 'span1', + name: 'test span 1', + start_timestamp: Date.now() / 1000, + end_timestamp: Date.now() / 1000, + status: 'ok', + is_segment: false, + _segmentSpan: segmentSpan1, + }); + + buffer.add({ + trace_id: 'trace2', + span_id: 'span2', + name: 'test span 2', + start_timestamp: Date.now() / 1000, + end_timestamp: Date.now() / 1000, + status: 'ok', + is_segment: false, + _segmentSpan: segmentSpan2, + }); + + buffer.drain(); + + // Should send 2 envelopes, one for each trace + expect(sendEnvelopeSpy).toHaveBeenCalledTimes(2); + }); + + it('flushes a specific trace on flush(traceId)', () => { + const buffer = new SpanBuffer(client); + + const segmentSpan1 = new SentrySpan({ name: 'segment1', sampled: true }); + const segmentSpan2 = new SentrySpan({ name: 'segment2', sampled: true }); + + buffer.add({ + trace_id: 'trace1', + span_id: 'span1', + name: 'test span 1', + start_timestamp: Date.now() / 1000, + end_timestamp: Date.now() / 1000, + status: 'ok', + is_segment: false, + _segmentSpan: segmentSpan1, + }); + + buffer.add({ + trace_id: 'trace2', + span_id: 'span2', + name: 'test span 2', + start_timestamp: Date.now() / 1000, + end_timestamp: Date.now() / 1000, + status: 'ok', + is_segment: false, + _segmentSpan: segmentSpan2, + }); + + buffer.flush('trace1'); + + expect(sendEnvelopeSpy).toHaveBeenCalledTimes(1); + expect(sentEnvelopes[0]?.[1]?.[0]?.[1]?.items[0]?.trace_id).toBe('trace1'); + }); + + it('handles flushing a non-existing trace', () => { + const buffer = new SpanBuffer(client); + + buffer.flush('trace1'); + + expect(sendEnvelopeSpy).not.toHaveBeenCalled(); + }); + + describe('weight-based flushing', () => { + function makeSpan( + traceId: string, + spanId: string, + segmentSpan: InstanceType, + overrides: Partial = {}, + ): SerializedStreamedSpanWithSegmentSpan { + return { + trace_id: traceId, + span_id: spanId, + name: 'test span', + start_timestamp: Date.now() / 1000, + end_timestamp: Date.now() / 1000, + status: 'ok', + is_segment: false, + _segmentSpan: segmentSpan, + ...overrides, + }; + } + + it('flushes a trace when its weight limit is exceeded', () => { + // Use a very small weight threshold so a single span with attributes tips it over + const buffer = new SpanBuffer(client, { maxTraceWeightInBytes: 200 }); + const segmentSpan = new SentrySpan({ name: 'segment', sampled: true }); + + // First span: small, under threshold + buffer.add(makeSpan('trace1', 'span1', segmentSpan, { name: 'a' })); + expect(sendEnvelopeSpy).not.toHaveBeenCalled(); + + // Second span: has a large name that pushes it over 200 bytes + buffer.add(makeSpan('trace1', 'span2', segmentSpan, { name: 'a'.repeat(80) })); + expect(sendEnvelopeSpy).toHaveBeenCalledTimes(1); + }); + + it('does not flush when weight stays below the threshold', () => { + const buffer = new SpanBuffer(client, { maxTraceWeightInBytes: 10_000 }); + const segmentSpan = new SentrySpan({ name: 'segment', sampled: true }); + + buffer.add(makeSpan('trace1', 'span1', segmentSpan)); + buffer.add(makeSpan('trace1', 'span2', segmentSpan)); + + expect(sendEnvelopeSpy).not.toHaveBeenCalled(); + }); + + it('resets weight tracking after a weight-triggered flush so new spans accumulate fresh weight', () => { + // Base estimate per span is 152 bytes. With threshold 400: + // - big span ('a' * 200): 152 + 200*2 = 552 bytes → exceeds 400, triggers flush + // - small span (name 'b'): 152 + 1*2 = 154 bytes + // - two small spans combined: 308 bytes < 400 → no second flush + const buffer = new SpanBuffer(client, { maxTraceWeightInBytes: 400 }); + const segmentSpan = new SentrySpan({ name: 'segment', sampled: true }); + + buffer.add(makeSpan('trace1', 'span1', segmentSpan, { name: 'a'.repeat(200) })); + expect(sendEnvelopeSpy).toHaveBeenCalledTimes(1); + + buffer.add(makeSpan('trace1', 'span2', segmentSpan, { name: 'b' })); + buffer.add(makeSpan('trace1', 'span3', segmentSpan, { name: 'c' })); + expect(sendEnvelopeSpy).toHaveBeenCalledTimes(1); + }); + + it('tracks weight independently per trace', () => { + const buffer = new SpanBuffer(client, { maxTraceWeightInBytes: 200 }); + const segmentSpan1 = new SentrySpan({ name: 'segment1', sampled: true }); + const segmentSpan2 = new SentrySpan({ name: 'segment2', sampled: true }); + + // trace1 gets a heavy span that exceeds the limit + buffer.add(makeSpan('trace1', 'span1', segmentSpan1, { name: 'a'.repeat(80) })); + expect(sendEnvelopeSpy).toHaveBeenCalledTimes(1); + expect((sentEnvelopes[0]?.[1]?.[0]?.[1] as { items: Array<{ trace_id: string }> })?.items[0]?.trace_id).toBe( + 'trace1', + ); + + // trace2 only has a small span and should not be flushed + buffer.add(makeSpan('trace2', 'span2', segmentSpan2, { name: 'b' })); + expect(sendEnvelopeSpy).toHaveBeenCalledTimes(1); + }); + + it('estimates spans with attributes as heavier than bare spans', () => { + // Use a threshold that a bare span cannot reach but an attributed span can + const buffer = new SpanBuffer(client, { maxTraceWeightInBytes: 300 }); + const segmentSpan = new SentrySpan({ name: 'segment', sampled: true }); + + // A span with many string attributes should tip it over + buffer.add( + makeSpan('trace1', 'span1', segmentSpan, { + attributes: { + 'http.method': { type: 'string', value: 'GET' }, + 'http.url': { type: 'string', value: 'https://example.com/api/v1/users?page=1&limit=100' }, + 'db.statement': { type: 'string', value: 'SELECT * FROM users WHERE id = 1' }, + }, + }), + ); + + expect(sendEnvelopeSpy).toHaveBeenCalledTimes(1); + }); + }); +}); diff --git a/packages/core/test/lib/tracing/trace.test.ts b/packages/core/test/lib/tracing/trace.test.ts index 6be1bf0577f3..0481f7f42687 100644 --- a/packages/core/test/lib/tracing/trace.test.ts +++ b/packages/core/test/lib/tracing/trace.test.ts @@ -573,12 +573,15 @@ describe('startSpan', () => { describe('onlyIfParent', () => { it('starts a non recording span if there is no parent', () => { + const spyOnDroppedEvent = vi.spyOn(client, 'recordDroppedEvent'); + const span = startSpan({ name: 'test span', onlyIfParent: true }, span => { return span; }); expect(span).toBeDefined(); expect(span).toBeInstanceOf(SentryNonRecordingSpan); + expect(spyOnDroppedEvent).not.toHaveBeenCalled(); }); it('creates a span if there is a parent', () => { @@ -2305,7 +2308,7 @@ describe('suppressTracing', () => { vi.clearAllMocks(); }); - it('works for a root span', () => { + it('suppresses a root span', () => { const span = suppressTracing(() => { return startInactiveSpan({ name: 'span' }); }); @@ -2314,7 +2317,7 @@ describe('suppressTracing', () => { expect(spanIsSampled(span)).toBe(false); }); - it('works for a child span', () => { + it('suppresses a child span', () => { startSpan({ name: 'outer' }, span => { expect(span.isRecording()).toBe(true); expect(spanIsSampled(span)).toBe(true); @@ -2333,7 +2336,7 @@ describe('suppressTracing', () => { }); }); - it('works for a child span with forceTransaction=true', () => { + it('suppresses a child span with forceTransaction=true', () => { startSpan({ name: 'outer' }, span => { expect(span.isRecording()).toBe(true); expect(spanIsSampled(span)).toBe(true); @@ -2347,6 +2350,42 @@ describe('suppressTracing', () => { }); }); + it("doesn't record a client outcome for suppressed spans", () => { + getCurrentScope().clear(); + getIsolationScope().clear(); + getGlobalScope().clear(); + + setAsyncContextStrategy(undefined); + + const options = getDefaultTestClientOptions({ tracesSampleRate: 1, traceLifecycle: 'stream' }); + client = new TestClient(options); + setCurrentClient(client); + client.init(); + + const spyOnDroppedEvent = vi.spyOn(client, 'recordDroppedEvent'); + + const span1 = suppressTracing(() => { + return startInactiveSpan({ name: 'span' }); + }); + + expect(span1.isRecording()).toBe(false); + expect(spanIsSampled(span1)).toBe(false); + + startSpan({ name: 'outer' }, span => { + expect(span.isRecording()).toBe(true); + expect(spanIsSampled(span)).toBe(true); + + const child = suppressTracing(() => { + return startInactiveSpan({ name: 'span' }); + }); + + expect(child.isRecording()).toBe(false); + expect(spanIsSampled(child)).toBe(false); + }); + + expect(spyOnDroppedEvent).not.toHaveBeenCalled(); + }); + it('works with parallel processes', async () => { const span = suppressTracing(() => { return startInactiveSpan({ name: 'span' }); @@ -2410,3 +2449,332 @@ describe('startNewTrace', () => { }); }); }); + +describe('ignoreSpans (core path, streaming)', () => { + beforeEach(() => { + registerSpanErrorInstrumentation(); + getCurrentScope().clear(); + getIsolationScope().clear(); + getGlobalScope().clear(); + setAsyncContextStrategy(undefined); + }); + + afterEach(() => { + vi.clearAllMocks(); + }); + + it('returns SentryNonRecordingSpan for root span matching ignoreSpans', () => { + const options = getDefaultTestClientOptions({ + tracesSampleRate: 1, + traceLifecycle: 'stream', + ignoreSpans: ['GET /health'], + }); + client = new TestClient(options); + setCurrentClient(client); + client.init(); + const spyOnDroppedEvent = vi.spyOn(client, 'recordDroppedEvent'); + + startSpan({ name: 'GET /health' }, span => { + expect(span).toBeInstanceOf(SentryNonRecordingSpan); + expect(spanIsSampled(span)).toBe(false); + startSpan({ name: 'child' }, childSpan => { + expect(childSpan).toBeInstanceOf(SentryNonRecordingSpan); + expect(spanIsSampled(childSpan)).toBe(false); + }); + }); + + expect(spyOnDroppedEvent).toHaveBeenCalledWith('ignored', 'span'); + }); + + it('returns SentryNonRecordingSpan for child span matching ignoreSpans', () => { + const options = getDefaultTestClientOptions({ + tracesSampleRate: 1, + traceLifecycle: 'stream', + ignoreSpans: ['ignored-child'], + }); + client = new TestClient(options); + setCurrentClient(client); + client.init(); + const spyOnDroppedEvent = vi.spyOn(client, 'recordDroppedEvent'); + + startSpan({ name: 'root' }, () => { + startSpan({ name: 'ignored-child' }, span => { + expect(span).toBeInstanceOf(SentryNonRecordingSpan); + }); + }); + + expect(spyOnDroppedEvent).toHaveBeenCalledWith('ignored', 'span'); + }); + + it('children of ignored child spans parent to grandparent', () => { + const options = getDefaultTestClientOptions({ + tracesSampleRate: 1, + traceLifecycle: 'stream', + ignoreSpans: ['ignored-span'], + }); + client = new TestClient(options); + setCurrentClient(client); + client.init(); + + startSpan({ name: 'root' }, rootSpan => { + startSpan({ name: 'ignored-span' }, () => { + expect(getActiveSpan()).toBe(rootSpan); + + startSpan({ name: 'grandchild' }, grandchildSpan => { + const json = spanToJSON(grandchildSpan); + expect(json.parent_span_id).toBe(rootSpan.spanContext().spanId); + }); + }); + }); + }); + + it('does not ignore non-matching spans', () => { + const options = getDefaultTestClientOptions({ + tracesSampleRate: 1, + traceLifecycle: 'stream', + ignoreSpans: ['GET /health'], + }); + client = new TestClient(options); + setCurrentClient(client); + client.init(); + + startSpan({ name: 'GET /users' }, span => { + expect(span).toBeInstanceOf(SentrySpan); + expect(spanIsSampled(span)).toBe(true); + }); + }); + + it('returns SentryNonRecordingSpan for startInactiveSpan matching ignoreSpans', () => { + const options = getDefaultTestClientOptions({ + tracesSampleRate: 1, + traceLifecycle: 'stream', + ignoreSpans: ['ignored-span'], + }); + client = new TestClient(options); + setCurrentClient(client); + client.init(); + + const span = startInactiveSpan({ name: 'ignored-span' }); + expect(span).toBeInstanceOf(SentryNonRecordingSpan); + }); + + it('does not apply ignoreSpans on the static (non-streaming) path', () => { + const options = getDefaultTestClientOptions({ + tracesSampleRate: 1, + ignoreSpans: ['GET /health'], + }); + client = new TestClient(options); + setCurrentClient(client); + client.init(); + + startSpan({ name: 'GET /health' }, span => { + expect(span).toBeInstanceOf(SentrySpan); + expect(spanIsSampled(span)).toBe(true); + }); + }); + + it('records ignored outcome for root span and all child spans', () => { + const options = getDefaultTestClientOptions({ + tracesSampleRate: 1, + traceLifecycle: 'stream', + ignoreSpans: ['GET /health'], + }); + client = new TestClient(options); + setCurrentClient(client); + client.init(); + const spyOnDroppedEvent = vi.spyOn(client, 'recordDroppedEvent'); + + startSpan({ name: 'GET /health' }, () => { + startSpan({ name: 'db.query' }, () => { + startSpan({ name: 'cache.lookup' }, () => {}); + }); + }); + + expect(spyOnDroppedEvent).toHaveBeenCalledTimes(3); + expect(spyOnDroppedEvent).toHaveBeenNthCalledWith(1, 'ignored', 'span'); + expect(spyOnDroppedEvent).toHaveBeenNthCalledWith(2, 'ignored', 'span'); + expect(spyOnDroppedEvent).toHaveBeenNthCalledWith(3, 'ignored', 'span'); + }); + + it('records sample_rate outcome for unsampled root span and all child spans when streaming', () => { + const options = getDefaultTestClientOptions({ + tracesSampleRate: 0, + traceLifecycle: 'stream', + }); + client = new TestClient(options); + setCurrentClient(client); + client.init(); + const spyOnDroppedEvent = vi.spyOn(client, 'recordDroppedEvent'); + + startSpan({ name: 'GET /foo' }, () => { + startSpan({ name: 'db.query' }, () => {}); + }); + + expect(spyOnDroppedEvent).toHaveBeenCalledTimes(2); + expect(spyOnDroppedEvent).toHaveBeenNthCalledWith(1, 'sample_rate', 'span'); + expect(spyOnDroppedEvent).toHaveBeenNthCalledWith(2, 'sample_rate', 'span'); + }); + + it('records sample_rate/transaction for unsampled root span on static path', () => { + const options = getDefaultTestClientOptions({ + tracesSampleRate: 0, + }); + client = new TestClient(options); + setCurrentClient(client); + client.init(); + const spyOnDroppedEvent = vi.spyOn(client, 'recordDroppedEvent'); + + startSpan({ name: 'GET /foo' }, () => { + startSpan({ name: 'db.query' }, () => {}); + }); + + expect(spyOnDroppedEvent).toHaveBeenCalledTimes(1); + expect(spyOnDroppedEvent).toHaveBeenCalledWith('sample_rate', 'transaction'); + }); + + it('records only one ignored outcome for directly ignored child span', () => { + const options = getDefaultTestClientOptions({ + tracesSampleRate: 1, + traceLifecycle: 'stream', + ignoreSpans: ['ignored-child'], + }); + client = new TestClient(options); + setCurrentClient(client); + client.init(); + const spyOnDroppedEvent = vi.spyOn(client, 'recordDroppedEvent'); + + startSpan({ name: 'root' }, () => { + startSpan({ name: 'ignored-child' }, () => {}); + startSpan({ name: 'normal-child' }, normalChild => { + expect(normalChild).toBeInstanceOf(SentrySpan); + }); + }); + + expect(spyOnDroppedEvent).toHaveBeenCalledTimes(1); + expect(spyOnDroppedEvent).toHaveBeenCalledWith('ignored', 'span'); + }); + + it('sets ignored segment span onto the scope', () => { + const options = getDefaultTestClientOptions({ + tracesSampleRate: 1, + traceLifecycle: 'stream', + ignoreSpans: ['ignored'], + }); + client = new TestClient(options); + setCurrentClient(client); + client.init(); + + startSpan({ name: 'ignored-segment' }, ignoredSegmentSpan => { + expect(ignoredSegmentSpan).toBeInstanceOf(SentryNonRecordingSpan); + expect(getActiveSpan()).toBe(ignoredSegmentSpan); + + startSpan({ name: 'child' }, () => { + expect(getActiveSpan()).toBe(ignoredSegmentSpan); + }); + }); + }); + + it("doesn't set ignored child span onto the scope", () => { + const options = getDefaultTestClientOptions({ + tracesSampleRate: 1, + traceLifecycle: 'stream', + ignoreSpans: ['ignored'], + }); + client = new TestClient(options); + setCurrentClient(client); + client.init(); + + startSpan({ name: 'segment' }, segmentSpan => { + expect(getActiveSpan()).toBe(segmentSpan); + + startSpan({ name: 'ignored-child' }, () => { + expect(getActiveSpan()).toBe(segmentSpan); + + startSpan({ name: 'ignored-child-2' }, () => { + expect(getActiveSpan()).toBe(segmentSpan); + + startSpan({ name: 'normal-child-2' }, normalChild2Span => { + expect(getActiveSpan()).toBe(normalChild2Span); + }); + }); + + startSpan({ name: 'normal-child' }, normalChildSpan => { + expect(getActiveSpan()).toBe(normalChildSpan); + }); + }); + }); + }); + + it("assigns the parent span's trace id to the ignored segment span", () => { + const options = getDefaultTestClientOptions({ + tracesSampleRate: 1, + traceLifecycle: 'stream', + ignoreSpans: ['ignored'], + }); + client = new TestClient(options); + setCurrentClient(client); + client.init(); + + startSpan({ name: 'ignored-segment' }, ignoredSegmentSpan => { + startSpan({ name: 'child' }, childSpan => { + expect(childSpan.spanContext().traceId).toBe(ignoredSegmentSpan.spanContext().traceId); + }); + }); + }); + + it("doesn't set inactive ignored segment spans onto the scope", () => { + const options = getDefaultTestClientOptions({ + tracesSampleRate: 1, + traceLifecycle: 'stream', + ignoreSpans: ['ignored'], + }); + client = new TestClient(options); + setCurrentClient(client); + client.init(); + + const span = startInactiveSpan({ name: 'ignored-segment' }); + expect(getActiveSpan()).toBeUndefined(); + + span.end(); + + expect(getActiveSpan()).toBeUndefined(); + }); + + it("doesn't record a client outcome for a suppressed and ignored span", () => { + const options = getDefaultTestClientOptions({ + tracesSampleRate: 1, + traceLifecycle: 'stream', + ignoreSpans: ['ignored'], + }); + + client = new TestClient(options); + setCurrentClient(client); + client.init(); + const spyOnDroppedEvent = vi.spyOn(client, 'recordDroppedEvent'); + + suppressTracing(() => { + startInactiveSpan({ name: 'ignored-inactive-span' }); + startSpan({ name: 'ignored-active-span' }, () => {}); + startSpanManual({ name: 'ignored-manual-span' }, () => {}); + }); + + expect(spyOnDroppedEvent).not.toHaveBeenCalled(); + }); + + it('sets the propagation context trace on ignored segment spans', () => { + const options = getDefaultTestClientOptions({ + tracesSampleRate: 1, + traceLifecycle: 'stream', + ignoreSpans: ['ignored'], + }); + client = new TestClient(options); + setCurrentClient(client); + client.init(); + + getCurrentScope().setPropagationContext({ traceId: 'abc', propagationSpanId: 'xxx', sampleRand: 0.5 }); + + const span = startInactiveSpan({ name: 'ignored-segment' }); + expect(span.spanContext().traceId).toBe(getCurrentScope().getPropagationContext().traceId); + expect(span.spanContext().traceId).toBe('abc'); + }); +}); diff --git a/packages/core/test/lib/utils/featureFlags.test.ts b/packages/core/test/lib/utils/featureFlags.test.ts index 7813452ad419..534285b4f9f4 100644 --- a/packages/core/test/lib/utils/featureFlags.test.ts +++ b/packages/core/test/lib/utils/featureFlags.test.ts @@ -2,11 +2,15 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { getCurrentScope } from '../../../src/currentScopes'; import { debug } from '../../../src/utils/debug-logger'; import { + _INTERNAL_copyFlagsFromScopeToEvent, _INTERNAL_insertFlagToScope, _INTERNAL_insertToFlagBuffer, type FeatureFlag, } from '../../../src/utils/featureFlags'; +import * as currentScopeModule from '../../../src/currentScopes'; +import type { Event } from '../../../src/types-hoist/event'; + describe('flags', () => { describe('insertFlagToScope()', () => { it('adds flags to the current scope context', () => { @@ -109,4 +113,82 @@ describe('flags', () => { ]); }); }); + + describe('copyFlagsFromScopeToEvent()', () => { + it.each(['transaction', 'replay_event', 'feedback', 'profile'])('does not add flags context to %s events', type => { + vi.spyOn(currentScopeModule, 'getCurrentScope').mockReturnValue({ + // @ts-expect-error - only returning partial scope data + getScopeData: () => ({ + contexts: { + flags: { values: [{ flag: 'feat1', result: true }] }, + }, + }), + }); + + const event = { + type: type, + spans: [], + } as Event; + + const result = _INTERNAL_copyFlagsFromScopeToEvent(event); + + expect(result).toEqual(event); + expect(getCurrentScope).not.toHaveBeenCalled(); + }); + + it('adds add flags context to error events', () => { + vi.spyOn(currentScopeModule, 'getCurrentScope').mockReturnValue({ + // @ts-expect-error - only returning partial scope data + getScopeData: () => ({ + contexts: { + flags: { + values: [ + { flag: 'feat1', result: true }, + { flag: 'feat2', result: false }, + ], + }, + }, + }), + }); + + const event: Event = { + exception: { + values: [ + { + type: 'Error', + value: 'error message', + }, + ], + }, + }; + + const result = _INTERNAL_copyFlagsFromScopeToEvent(event); + + expect(result).toEqual({ + contexts: { + flags: { + values: [ + { + flag: 'feat1', + result: true, + }, + { + flag: 'feat2', + result: false, + }, + ], + }, + }, + exception: { + values: [ + { + type: 'Error', + value: 'error message', + }, + ], + }, + }); + expect(getCurrentScope).toHaveBeenCalled(); + }); + }); }); diff --git a/packages/core/test/lib/utils/object.test.ts b/packages/core/test/lib/utils/object.test.ts index e34260edef50..a2405614f461 100644 --- a/packages/core/test/lib/utils/object.test.ts +++ b/packages/core/test/lib/utils/object.test.ts @@ -11,6 +11,7 @@ import { fill, markFunctionWrapped, objectify, + wrapMethod, } from '../../../src/utils/object'; import { testOnlyIfNodeVersionAtLeast } from '../../testutils'; @@ -455,3 +456,47 @@ describe('markFunctionWrapped', () => { expect(originalFunc).not.toHaveBeenCalled(); }); }); + +describe('wrapMethod', () => { + it('can wrap a method on an object', () => { + const wrappedEnumerable = () => {}; + const originalEnumerable = () => {}; + const wrappedNotEnumerable = () => {}; + const originalNotEnumerable = () => {}; + const obj: Record = { + enumerable: originalEnumerable, + }; + Object.defineProperty(obj, 'notEnumerable', { + writable: true, + configurable: true, + enumerable: false, + value: originalNotEnumerable, + }); + wrapMethod(obj, 'notEnumerable', wrappedNotEnumerable, false); + wrapMethod(obj, 'enumerable', wrappedEnumerable); + // does not change enumerability + expect(Object.keys(obj)).toStrictEqual(['enumerable']); + expect(obj.notEnumerable).toBe(wrappedNotEnumerable); + expect((obj.notEnumerable as WrappedFunction).__sentry_original__).toBe(originalNotEnumerable); + expect(obj.enumerable).toBe(wrappedEnumerable); + expect((obj.enumerable as WrappedFunction).__sentry_original__).toBe(originalEnumerable); + }); + + it('throws if misused', () => { + const wrapped = () => {}; + const original = () => {}; + const obj = { + get m() { + return original; + }, + }; + wrapMethod(obj, 'm', wrapped); + expect(() => { + //@ts-expect-error verify type checking prevents this mistake + wrapMethod(obj, 'foo', wrapped); + }).toThrowError('Cannot wrap method: foo is not a function'); + expect(() => { + wrapMethod(obj, 'm', wrapped); + }).toThrowError('Attempting to wrap method m multiple times'); + }); +}); diff --git a/packages/core/test/lib/utils/openai-utils.test.ts b/packages/core/test/lib/utils/openai-utils.test.ts index 3f8fd0045f2e..5af1ac635264 100644 --- a/packages/core/test/lib/utils/openai-utils.test.ts +++ b/packages/core/test/lib/utils/openai-utils.test.ts @@ -1,12 +1,6 @@ import { describe, expect, it } from 'vitest'; import { buildMethodPath } from '../../../src/tracing/ai/utils'; -import { - isChatCompletionChunk, - isChatCompletionResponse, - isConversationResponse, - isResponsesApiResponse, - isResponsesApiStreamEvent, -} from '../../../src/tracing/openai/utils'; +import { isChatCompletionChunk, isResponsesApiStreamEvent } from '../../../src/tracing/openai/utils'; describe('openai-utils', () => { describe('buildMethodPath', () => { @@ -17,50 +11,6 @@ describe('openai-utils', () => { }); }); - describe('isChatCompletionResponse', () => { - it('should return true for valid chat completion responses', () => { - const validResponse = { - object: 'chat.completion', - id: 'chatcmpl-123', - model: 'gpt-4', - choices: [], - }; - expect(isChatCompletionResponse(validResponse)).toBe(true); - }); - - it('should return false for invalid responses', () => { - expect(isChatCompletionResponse(null)).toBe(false); - expect(isChatCompletionResponse(undefined)).toBe(false); - expect(isChatCompletionResponse('string')).toBe(false); - expect(isChatCompletionResponse(123)).toBe(false); - expect(isChatCompletionResponse({})).toBe(false); - expect(isChatCompletionResponse({ object: 'different' })).toBe(false); - expect(isChatCompletionResponse({ object: null })).toBe(false); - }); - }); - - describe('isResponsesApiResponse', () => { - it('should return true for valid responses API responses', () => { - const validResponse = { - object: 'response', - id: 'resp_123', - model: 'gpt-4', - choices: [], - }; - expect(isResponsesApiResponse(validResponse)).toBe(true); - }); - - it('should return false for invalid responses', () => { - expect(isResponsesApiResponse(null)).toBe(false); - expect(isResponsesApiResponse(undefined)).toBe(false); - expect(isResponsesApiResponse('string')).toBe(false); - expect(isResponsesApiResponse(123)).toBe(false); - expect(isResponsesApiResponse({})).toBe(false); - expect(isResponsesApiResponse({ object: 'different' })).toBe(false); - expect(isResponsesApiResponse({ object: null })).toBe(false); - }); - }); - describe('isResponsesApiStreamEvent', () => { it('should return true for valid responses API stream events', () => { expect(isResponsesApiStreamEvent({ type: 'response.created' })).toBe(true); @@ -103,36 +53,4 @@ describe('openai-utils', () => { expect(isChatCompletionChunk({ object: null })).toBe(false); }); }); - - describe('isConversationResponse', () => { - it('should return true for valid conversation responses', () => { - const validConversation = { - object: 'conversation', - id: 'conv_689667905b048191b4740501625afd940c7533ace33a2dab', - created_at: 1704067200, - }; - expect(isConversationResponse(validConversation)).toBe(true); - }); - - it('should return true for conversation with metadata', () => { - const conversationWithMetadata = { - object: 'conversation', - id: 'conv_123', - created_at: 1704067200, - metadata: { user_id: 'user_123' }, - }; - expect(isConversationResponse(conversationWithMetadata)).toBe(true); - }); - - it('should return false for invalid responses', () => { - expect(isConversationResponse(null)).toBe(false); - expect(isConversationResponse(undefined)).toBe(false); - expect(isConversationResponse('string')).toBe(false); - expect(isConversationResponse(123)).toBe(false); - expect(isConversationResponse({})).toBe(false); - expect(isConversationResponse({ object: 'thread' })).toBe(false); - expect(isConversationResponse({ object: 'response' })).toBe(false); - expect(isConversationResponse({ object: null })).toBe(false); - }); - }); }); diff --git a/packages/core/test/lib/utils/should-ignore-span.test.ts b/packages/core/test/lib/utils/should-ignore-span.test.ts index dc03d6e032ea..a9aa3953b458 100644 --- a/packages/core/test/lib/utils/should-ignore-span.test.ts +++ b/packages/core/test/lib/utils/should-ignore-span.test.ts @@ -89,6 +89,20 @@ describe('shouldIgnoreSpan', () => { expect(shouldIgnoreSpan(span12, ignoreSpans)).toBe(false); }); + it('matches inferred HTTP span names', () => { + expect(shouldIgnoreSpan({ description: 'GET /health', op: 'http.server' }, ['GET /health'])).toBe(true); + }); + + it('matches middleware span names with regex', () => { + expect( + shouldIgnoreSpan({ description: 'middleware - expressInit', op: 'middleware.express' }, [/middleware/]), + ).toBe(true); + }); + + it('matches IgnoreSpanFilter with op only', () => { + expect(shouldIgnoreSpan({ description: 'GET /health', op: 'http.server' }, [{ op: 'http.server' }])).toBe(true); + }); + it('emits a debug log when a span is ignored', () => { const debugLogSpy = vi.spyOn(debug, 'log'); const span = { description: 'testDescription', op: 'testOp' }; diff --git a/packages/core/test/lib/utils/spanUtils.test.ts b/packages/core/test/lib/utils/spanUtils.test.ts index bca9a406dd50..e4a0b31990d7 100644 --- a/packages/core/test/lib/utils/spanUtils.test.ts +++ b/packages/core/test/lib/utils/spanUtils.test.ts @@ -4,6 +4,7 @@ import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, + SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE, SentrySpan, setCurrentClient, SPAN_STATUS_ERROR, @@ -16,7 +17,7 @@ import { TRACEPARENT_REGEXP, } from '../../../src'; import type { SpanLink } from '../../../src/types-hoist/link'; -import type { Span, SpanAttributes, SpanTimeInput } from '../../../src/types-hoist/span'; +import type { Span, SpanAttributes, SpanTimeInput, StreamedSpanJSON } from '../../../src/types-hoist/span'; import type { SpanStatus } from '../../../src/types-hoist/spanStatus'; import type { OpenTelemetrySdkTraceBaseSpan } from '../../../src/utils/spanUtils'; import { @@ -24,7 +25,9 @@ import { spanIsSampled, spanTimeInputToSeconds, spanToJSON, + spanToStreamedSpanJSON, spanToTraceContext, + streamedSpanJsonToSerializedSpan, TRACE_FLAG_NONE, TRACE_FLAG_SAMPLED, updateSpanName, @@ -41,6 +44,7 @@ function createMockedOtelSpan({ status = { code: SPAN_STATUS_UNSET }, endTime = Date.now(), parentSpanId, + links = undefined, }: { spanId: string; traceId: string; @@ -51,6 +55,7 @@ function createMockedOtelSpan({ status?: SpanStatus; endTime?: SpanTimeInput; parentSpanId?: string; + links?: SpanLink[]; }): Span { return { spanContext: () => { @@ -66,6 +71,7 @@ function createMockedOtelSpan({ status, endTime, parentSpanId, + links, } as OpenTelemetrySdkTraceBaseSpan; } @@ -409,6 +415,233 @@ describe('spanToJSON', () => { }); }); + describe('spanToStreamedSpanJSON', () => { + describe('SentrySpan', () => { + it('converts a minimal span', () => { + const span = new SentrySpan(); + expect(spanToStreamedSpanJSON(span)).toEqual({ + span_id: expect.stringMatching(/^[0-9a-f]{16}$/), + trace_id: expect.stringMatching(/^[0-9a-f]{32}$/), + name: '', + start_timestamp: expect.any(Number), + end_timestamp: expect.any(Number), + status: 'ok', + is_segment: true, + attributes: { + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'manual', + }, + }); + }); + + it('converts a full span', () => { + const span = new SentrySpan({ + op: 'test op', + name: 'test name', + parentSpanId: '1234', + spanId: '5678', + traceId: 'abcd', + startTimestamp: 123, + endTimestamp: 456, + attributes: { + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto', + attr1: 'value1', + attr2: 2, + attr3: true, + }, + links: [ + { + context: { + spanId: 'span1', + traceId: 'trace1', + traceFlags: TRACE_FLAG_SAMPLED, + }, + attributes: { + 'sentry.link.type': 'previous_trace', + }, + }, + ], + }); + span.setStatus({ code: SPAN_STATUS_OK }); + span.setAttribute('attr4', [1, 2, 3]); + + expect(spanToStreamedSpanJSON(span)).toEqual({ + name: 'test name', + parent_span_id: '1234', + span_id: '5678', + trace_id: 'abcd', + start_timestamp: 123, + end_timestamp: 456, + status: 'ok', + is_segment: true, + attributes: { + attr1: 'value1', + attr2: 2, + attr3: true, + attr4: [1, 2, 3], + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'test op', + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto', + }, + links: [ + { + span_id: 'span1', + trace_id: 'trace1', + sampled: true, + attributes: { + [SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE]: 'previous_trace', + }, + }, + ], + }); + }); + }); + describe('OpenTelemetry Span', () => { + it('converts a simple span', () => { + const span = createMockedOtelSpan({ + spanId: 'SPAN-1', + traceId: 'TRACE-1', + name: 'test span', + startTime: 123, + endTime: [0, 0], + attributes: {}, + status: { code: SPAN_STATUS_UNSET }, + }); + + expect(spanToStreamedSpanJSON(span)).toEqual({ + span_id: 'SPAN-1', + trace_id: 'TRACE-1', + parent_span_id: undefined, + start_timestamp: 123, + end_timestamp: 0, + name: 'test span', + is_segment: true, + status: 'ok', + attributes: {}, + }); + }); + + it('converts a full span', () => { + const span = createMockedOtelSpan({ + spanId: 'SPAN-1', + traceId: 'TRACE-1', + parentSpanId: 'PARENT-1', + name: 'test span', + startTime: 123, + endTime: 456, + attributes: { + attr1: 'value1', + attr2: 2, + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'test op', + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto', + }, + links: [ + { + context: { + spanId: 'span1', + traceId: 'trace1', + traceFlags: TRACE_FLAG_SAMPLED, + }, + attributes: { + [SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE]: 'previous_trace', + }, + }, + ], + status: { code: SPAN_STATUS_ERROR, message: 'unknown_error' }, + }); + + expect(spanToStreamedSpanJSON(span)).toEqual({ + span_id: 'SPAN-1', + trace_id: 'TRACE-1', + parent_span_id: 'PARENT-1', + start_timestamp: 123, + end_timestamp: 456, + name: 'test span', + is_segment: true, + status: 'error', + attributes: { + attr1: 'value1', + attr2: 2, + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'test op', + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto', + }, + links: [ + { + span_id: 'span1', + trace_id: 'trace1', + sampled: true, + attributes: { + [SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE]: 'previous_trace', + }, + }, + ], + }); + }); + }); + }); + + describe('streamedSpanJsonToSerializedSpan', () => { + it('converts a streamed span JSON with links to a serialized span', () => { + const spanJson: StreamedSpanJSON = { + name: 'test name', + parent_span_id: '1234', + span_id: '5678', + trace_id: 'abcd', + start_timestamp: 123, + end_timestamp: 456, + status: 'ok', + is_segment: true, + attributes: { + attr1: 'value1', + attr2: 2, + attr3: true, + attr4: [1, 2, 3], + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'test op', + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto', + }, + links: [ + { + span_id: 'span1', + trace_id: 'trace1', + sampled: true, + attributes: { + [SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE]: 'previous_trace', + }, + }, + ], + }; + + expect(streamedSpanJsonToSerializedSpan(spanJson)).toEqual({ + name: 'test name', + parent_span_id: '1234', + span_id: '5678', + trace_id: 'abcd', + start_timestamp: 123, + end_timestamp: 456, + status: 'ok', + is_segment: true, + attributes: { + attr1: { type: 'string', value: 'value1' }, + attr2: { type: 'integer', value: 2 }, + attr3: { type: 'boolean', value: true }, + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: { type: 'string', value: 'test op' }, + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: { type: 'string', value: 'auto' }, + // notice the absence of `attr4`! + // for now, we don't yet serialize array attributes. This test will fail + // once we allow serializing them. + }, + links: [ + { + span_id: 'span1', + trace_id: 'trace1', + sampled: true, + attributes: { + [SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE]: { type: 'string', value: 'previous_trace' }, + }, + }, + ], + }); + }); + }); + it('returns minimal object for unknown span implementation', () => { const span = { // This is the minimal interface we require from a span diff --git a/packages/core/test/lib/utils/stacktrace.test.ts b/packages/core/test/lib/utils/stacktrace.test.ts index 49ea7fcc0ba5..2a1700b262a7 100644 --- a/packages/core/test/lib/utils/stacktrace.test.ts +++ b/packages/core/test/lib/utils/stacktrace.test.ts @@ -1,8 +1,72 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { nodeStackLineParser } from '../../../src/utils/node-stack-trace'; -import { stripSentryFramesAndReverse } from '../../../src/utils/stacktrace'; +import { createStackParser, stripSentryFramesAndReverse } from '../../../src/utils/stacktrace'; describe('Stacktrace', () => { + describe('createStackParser()', () => { + it('skips lines that contain "Error: " (e.g. "TypeError: foo")', () => { + const mockParser = vi.fn().mockReturnValue({ filename: 'test.js', function: 'test', lineno: 1, colno: 1 }); + const parser = createStackParser([0, mockParser]); + + const stack = ['TypeError: foo is not a function', ' at test (test.js:1:1)'].join('\n'); + + const frames = parser(stack); + + // The parser should only be called for the frame line, not the Error line + expect(mockParser).toHaveBeenCalledTimes(1); + expect(frames).toHaveLength(1); + }); + + it('skips various Error type lines', () => { + const mockParser = vi.fn().mockReturnValue({ filename: 'test.js', function: 'test', lineno: 1, colno: 1 }); + const parser = createStackParser([0, mockParser]); + + const stack = [ + 'Error: something went wrong', + 'TypeError: foo is not a function', + 'RangeError: Maximum call stack size exceeded', + 'SomeCustomError: custom message', + ' at test (test.js:1:1)', + ].join('\n'); + + const frames = parser(stack); + + // Only the frame line should be parsed, all Error lines should be skipped + expect(mockParser).toHaveBeenCalledTimes(1); + expect(frames).toHaveLength(1); + }); + + // Regression test for https://github.com/getsentry/sentry-javascript/issues/20052 + it('processes long non-whitespace lines without hanging', () => { + const mockParser = vi.fn().mockReturnValue(undefined); + const parser = createStackParser([0, mockParser]); + + // Long non-whitespace lines (e.g. minified URLs) previously caused O(n²) backtracking + const longLine = 'a'.repeat(2000); + const stack = [longLine, ' at test (test.js:1:1)'].join('\n'); + + // Should complete without hanging (line gets truncated to 1024 chars internally) + parser(stack); + expect(mockParser).toHaveBeenCalledTimes(2); + }); + + it('does not skip lines that do not contain "Error: "', () => { + const mockParser = vi.fn().mockReturnValue({ filename: 'test.js', function: 'test', lineno: 1, colno: 1 }); + const parser = createStackParser([0, mockParser]); + + const stack = [ + ' at foo (test.js:1:1)', + ' at bar (test.js:2:1)', + 'ResizeObserver loop completed with undelivered notifications.', + ].join('\n'); + + parser(stack); + + // All lines should be attempted by the parser (none contain "Error: ") + expect(mockParser).toHaveBeenCalledTimes(3); + }); + }); + describe('stripSentryFramesAndReverse()', () => { describe('removed top frame if its internally reserved word (public API)', () => { it('reserved captureException', () => { diff --git a/packages/core/test/lib/utils/string.test.ts b/packages/core/test/lib/utils/string.test.ts index b3d166568163..b566bd62116f 100644 --- a/packages/core/test/lib/utils/string.test.ts +++ b/packages/core/test/lib/utils/string.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, test } from 'vitest'; +import { describe, expect, test, vi } from 'vitest'; import { isMatchingPattern, stringMatchesSomePattern, truncate } from '../../../src/utils/string'; describe('truncate()', () => { @@ -57,6 +57,15 @@ describe('isMatchingPattern()', () => { expect(isMatchingPattern('', '')).toEqual(true); }); + test('should call a method that returns boolean result', () => { + const testTrue = vi.fn(() => true); + const testFalse = vi.fn(() => false); + expect(isMatchingPattern('x', testTrue)).toEqual(true); + expect(testTrue).toHaveBeenCalledExactlyOnceWith('x'); + expect(isMatchingPattern('y', testFalse)).toEqual(false); + expect(testFalse).toHaveBeenCalledExactlyOnceWith('y'); + }); + test('should bail out with false when given non-string value', () => { expect(isMatchingPattern(null as any, 'foo')).toEqual(false); expect(isMatchingPattern(undefined as any, 'foo')).toEqual(false); diff --git a/packages/deno/.oxlintrc.json b/packages/deno/.oxlintrc.json index 75164516b719..d29725f59d80 100644 --- a/packages/deno/.oxlintrc.json +++ b/packages/deno/.oxlintrc.json @@ -1,6 +1,12 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], + "jsPlugins": [ + { + "name": "sdk", + "specifier": "@sentry-internal/eslint-plugin-sdk" + } + ], "overrides": [ { "files": ["**/src/**"], diff --git a/packages/deno/src/index.ts b/packages/deno/src/index.ts index e6fdde530c81..18bb26f06a4f 100644 --- a/packages/deno/src/index.ts +++ b/packages/deno/src/index.ts @@ -94,6 +94,7 @@ export { wrapMcpServerWithSentry, featureFlagsIntegration, metrics, + withStreamedSpan, logger, consoleLoggingIntegration, } from '@sentry/core'; @@ -109,3 +110,4 @@ export { contextLinesIntegration } from './integrations/contextlines'; export { denoCronIntegration } from './integrations/deno-cron'; export { breadcrumbsIntegration } from './integrations/breadcrumbs'; export { vercelAIIntegration } from './integrations/tracing/vercelai'; +export { denoRuntimeMetricsIntegration, type DenoRuntimeMetricsOptions } from './integrations/denoRuntimeMetrics'; diff --git a/packages/deno/src/integrations/denoRuntimeMetrics.ts b/packages/deno/src/integrations/denoRuntimeMetrics.ts new file mode 100644 index 000000000000..54d162132db8 --- /dev/null +++ b/packages/deno/src/integrations/denoRuntimeMetrics.ts @@ -0,0 +1,135 @@ +import { _INTERNAL_safeDateNow, defineIntegration, metrics } from '@sentry/core'; + +const INTEGRATION_NAME = 'DenoRuntimeMetrics'; +const DEFAULT_INTERVAL_MS = 30_000; +const MIN_INTERVAL_MS = 1_000; + +export interface DenoRuntimeMetricsOptions { + /** + * Which metrics to collect. + * + * Default on (4 metrics): + * - `memRss` — Resident Set Size (actual memory footprint) + * - `memHeapUsed` — V8 heap currently in use + * - `memHeapTotal` — total V8 heap allocated + * - `uptime` — process uptime (detect restarts/crashes) + * + * Default off (opt-in): + * - `memExternal` — external memory (JS objects outside the V8 isolate) + * + * Note: CPU utilization and event loop metrics are not available in Deno. + */ + collect?: { + memRss?: boolean; + memHeapUsed?: boolean; + memHeapTotal?: boolean; + memExternal?: boolean; + uptime?: boolean; + }; + /** + * How often to collect metrics, in milliseconds. + * Minimum allowed value is 1000ms. + * @default 30000 + * @minimum 1000 + */ + collectionIntervalMs?: number; +} + +/** + * Automatically collects Deno runtime metrics and emits them to Sentry. + * + * @example + * ```ts + * Sentry.init({ + * integrations: [ + * Sentry.denoRuntimeMetricsIntegration(), + * ], + * }); + * ``` + */ +export const denoRuntimeMetricsIntegration = defineIntegration((options: DenoRuntimeMetricsOptions = {}) => { + const rawInterval = options.collectionIntervalMs ?? DEFAULT_INTERVAL_MS; + let collectionIntervalMs: number; + if (!Number.isFinite(rawInterval)) { + // eslint-disable-next-line no-console + console.warn( + `[Sentry] denoRuntimeMetricsIntegration: collectionIntervalMs (${rawInterval}) is invalid. Using default of ${DEFAULT_INTERVAL_MS}ms.`, + ); + collectionIntervalMs = DEFAULT_INTERVAL_MS; + } else if (rawInterval < MIN_INTERVAL_MS) { + // eslint-disable-next-line no-console + console.warn( + `[Sentry] denoRuntimeMetricsIntegration: collectionIntervalMs (${rawInterval}) is below the minimum of ${MIN_INTERVAL_MS}ms. Using minimum of ${MIN_INTERVAL_MS}ms.`, + ); + collectionIntervalMs = MIN_INTERVAL_MS; + } else { + collectionIntervalMs = rawInterval; + } + const collect = { + // Default on + memRss: true, + memHeapUsed: true, + memHeapTotal: true, + uptime: true, + // Default off + memExternal: false, + ...options.collect, + }; + + let intervalId: number | undefined; + let prevFlushTime: number = 0; + + const METRIC_ATTRIBUTES_BYTE = { unit: 'byte', attributes: { 'sentry.origin': 'auto.deno.runtime_metrics' } }; + const METRIC_ATTRIBUTES_SECOND = { unit: 'second', attributes: { 'sentry.origin': 'auto.deno.runtime_metrics' } }; + + function collectMetrics(): void { + const now = _INTERNAL_safeDateNow(); + const elapsed = now - prevFlushTime; + + if (collect.memRss || collect.memHeapUsed || collect.memHeapTotal || collect.memExternal) { + const mem = Deno.memoryUsage(); + if (collect.memRss) { + metrics.gauge('deno.runtime.mem.rss', mem.rss, METRIC_ATTRIBUTES_BYTE); + } + if (collect.memHeapUsed) { + metrics.gauge('deno.runtime.mem.heap_used', mem.heapUsed, METRIC_ATTRIBUTES_BYTE); + } + if (collect.memHeapTotal) { + metrics.gauge('deno.runtime.mem.heap_total', mem.heapTotal, METRIC_ATTRIBUTES_BYTE); + } + if (collect.memExternal) { + metrics.gauge('deno.runtime.mem.external', mem.external, METRIC_ATTRIBUTES_BYTE); + } + } + + if (collect.uptime && elapsed > 0) { + metrics.count('deno.runtime.process.uptime', elapsed / 1000, METRIC_ATTRIBUTES_SECOND); + } + + prevFlushTime = now; + } + + return { + name: INTEGRATION_NAME, + + setup(): void { + prevFlushTime = _INTERNAL_safeDateNow(); + + // Guard against double setup (e.g. re-init). + if (intervalId) { + clearInterval(intervalId); + } + // setInterval in Deno returns a number at runtime (global API, not node:timers). + // @types/node in the monorepo overrides the global type to NodeJS.Timeout, so we cast. + intervalId = setInterval(collectMetrics, collectionIntervalMs) as unknown as number; + Deno.unrefTimer(intervalId); + }, + + teardown(): void { + if (intervalId) { + clearInterval(intervalId); + intervalId = undefined; + } + }, + }; +}); diff --git a/packages/deno/test/deno-runtime-metrics.test.ts b/packages/deno/test/deno-runtime-metrics.test.ts new file mode 100644 index 000000000000..48435279a954 --- /dev/null +++ b/packages/deno/test/deno-runtime-metrics.test.ts @@ -0,0 +1,152 @@ +// + +import type { Envelope } from '@sentry/core'; +import { createStackParser, forEachEnvelopeItem, nodeStackLineParser } from '@sentry/core'; +import { assertEquals, assertNotEquals, assertStringIncludes } from 'https://deno.land/std@0.212.0/assert/mod.ts'; +import { + DenoClient, + denoRuntimeMetricsIntegration, + getCurrentScope, + getDefaultIntegrations, +} from '../build/esm/index.js'; +import { makeTestTransport } from './transport.ts'; + +const DSN = 'https://233a45e5efe34c47a3536797ce15dafa@nothing.here/5650507'; + +function delay(ms: number): Promise { + return new Promise(resolve => setTimeout(resolve, ms)); +} + +// deno-lint-ignore no-explicit-any +type MetricItem = { name: string; type: string; value: number; unit?: string; attributes?: Record }; + +async function collectMetrics( + integrationOptions: Parameters[0] = {}, +): Promise { + const envelopes: Envelope[] = []; + + // Hold a reference so we can call teardown() to stop the interval before the test ends. + const metricsIntegration = denoRuntimeMetricsIntegration({ collectionIntervalMs: 1000, ...integrationOptions }); + + const client = new DenoClient({ + dsn: DSN, + integrations: [...getDefaultIntegrations({}), metricsIntegration], + stackParser: createStackParser(nodeStackLineParser()), + transport: makeTestTransport(envelope => { + envelopes.push(envelope); + }), + }); + + client.init(); + getCurrentScope().setClient(client); + + await delay(2500); + await client.flush(2000); + + // Stop the collection interval so Deno's leak detector doesn't flag it. + metricsIntegration.teardown?.(); + + const items: MetricItem[] = []; + for (const envelope of envelopes) { + forEachEnvelopeItem(envelope, item => { + const [headers, body] = item; + if (headers.type === 'trace_metric') { + // deno-lint-ignore no-explicit-any + items.push(...(body as any).items); + } + }); + } + + return items; +} + +Deno.test('denoRuntimeMetricsIntegration has the correct name', () => { + const integration = denoRuntimeMetricsIntegration(); + assertEquals(integration.name, 'DenoRuntimeMetrics'); +}); + +Deno.test('emits default memory metrics with correct shape', async () => { + const items = await collectMetrics(); + const names = items.map(i => i.name); + + assertEquals(names.includes('deno.runtime.mem.rss'), true); + assertEquals(names.includes('deno.runtime.mem.heap_used'), true); + assertEquals(names.includes('deno.runtime.mem.heap_total'), true); + + const rss = items.find(i => i.name === 'deno.runtime.mem.rss'); + assertEquals(rss?.type, 'gauge'); + assertEquals(rss?.unit, 'byte'); + assertEquals(typeof rss?.value, 'number'); +}); + +Deno.test('emits uptime counter', async () => { + const items = await collectMetrics(); + const uptime = items.find(i => i.name === 'deno.runtime.process.uptime'); + + assertNotEquals(uptime, undefined); + assertEquals(uptime?.type, 'counter'); + assertEquals(uptime?.unit, 'second'); +}); + +Deno.test('does not emit mem.external by default', async () => { + const items = await collectMetrics(); + const names = items.map(i => i.name); + assertEquals(names.includes('deno.runtime.mem.external'), false); +}); + +Deno.test('emits mem.external when opted in', async () => { + const items = await collectMetrics({ collect: { memExternal: true } }); + const external = items.find(i => i.name === 'deno.runtime.mem.external'); + + assertNotEquals(external, undefined); + assertEquals(external?.type, 'gauge'); + assertEquals(external?.unit, 'byte'); +}); + +Deno.test('respects opt-out: skips uptime when disabled', async () => { + const items = await collectMetrics({ collect: { uptime: false } }); + const names = items.map(i => i.name); + + assertEquals(names.includes('deno.runtime.mem.rss'), true); + assertEquals(names.includes('deno.runtime.process.uptime'), false); +}); + +Deno.test('attaches correct sentry.origin attribute', async () => { + const items = await collectMetrics(); + const rss = items.find(i => i.name === 'deno.runtime.mem.rss'); + + // Attributes in the serialized envelope are { type, value } objects. + assertEquals(rss?.attributes?.['sentry.origin']?.value, 'auto.deno.runtime_metrics'); +}); + +Deno.test('warns and enforces minimum collectionIntervalMs', () => { + const warnings: string[] = []; + const originalWarn = globalThis.console.warn; + globalThis.console.warn = (msg: string) => warnings.push(msg); + + try { + denoRuntimeMetricsIntegration({ collectionIntervalMs: 100 }); + } finally { + globalThis.console.warn = originalWarn; + } + + assertEquals(warnings.length, 1); + assertStringIncludes(warnings[0]!, 'collectionIntervalMs'); + assertStringIncludes(warnings[0]!, '1000'); +}); + +Deno.test('warns and falls back to default when collectionIntervalMs is NaN', () => { + const warnings: string[] = []; + const originalWarn = globalThis.console.warn; + globalThis.console.warn = (msg: string) => warnings.push(msg); + + try { + denoRuntimeMetricsIntegration({ collectionIntervalMs: NaN }); + } finally { + globalThis.console.warn = originalWarn; + } + + assertEquals(warnings.length, 1); + assertStringIncludes(warnings[0]!, 'collectionIntervalMs'); + assertStringIncludes(warnings[0]!, 'invalid'); +}); diff --git a/packages/effect/package.json b/packages/effect/package.json index 588e76185b7e..33d5930882b8 100644 --- a/packages/effect/package.json +++ b/packages/effect/package.json @@ -71,7 +71,7 @@ }, "devDependencies": { "@effect/vitest": "^0.23.9", - "effect": "^3.20.0" + "effect": "^3.21.0" }, "scripts": { "build": "run-p build:transpile build:types", diff --git a/packages/effect/src/index.types.ts b/packages/effect/src/index.types.ts index e0a6e9512eeb..153f7eba465e 100644 --- a/packages/effect/src/index.types.ts +++ b/packages/effect/src/index.types.ts @@ -21,6 +21,8 @@ export declare function effectLayer( export declare function init(options: Options | clientSdk.BrowserOptions | serverSdk.NodeOptions): Client | undefined; export declare const linkedErrorsIntegration: typeof clientSdk.linkedErrorsIntegration; export declare const contextLinesIntegration: typeof clientSdk.contextLinesIntegration; +export declare const spanStreamingIntegration: typeof clientSdk.spanStreamingIntegration; +export declare const withStreamedSpan: typeof clientSdk.withStreamedSpan; export declare const getDefaultIntegrations: (options: Options) => Integration[]; export declare const defaultStackParser: StackParser; export declare const logger: typeof clientSdk.logger | typeof serverSdk.logger; diff --git a/packages/elysia/.oxlintrc.json b/packages/elysia/.oxlintrc.json index d38bbcf5c769..4cd4930fa802 100644 --- a/packages/elysia/.oxlintrc.json +++ b/packages/elysia/.oxlintrc.json @@ -1,4 +1,4 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"] + "extends": ["../../.oxlintrc.base.json"] } diff --git a/packages/elysia/src/index.ts b/packages/elysia/src/index.ts index 8a5c5e622de1..55542acfc55f 100644 --- a/packages/elysia/src/index.ts +++ b/packages/elysia/src/index.ts @@ -45,6 +45,7 @@ export { getSentryRelease, createGetModuleFromFilename, createLangChainCallbackHandler, + instrumentLangChainEmbeddings, httpHeadersToSpanAttributes, winterCGHeadersToDict, // eslint-disable-next-line deprecation/deprecation @@ -154,6 +155,8 @@ export { statsigIntegration, unleashIntegration, metrics, + spanStreamingIntegration, + withStreamedSpan, bunServerIntegration, makeFetchTransport, } from '@sentry/bun'; diff --git a/packages/ember/.oxlintrc.json b/packages/ember/.oxlintrc.json index 9f0633da4a03..9c0c3060af0f 100644 --- a/packages/ember/.oxlintrc.json +++ b/packages/ember/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], "overrides": [ { "files": ["vendor/**/*.js"], diff --git a/packages/eslint-plugin-sdk/.oxlintrc.json b/packages/eslint-plugin-sdk/.oxlintrc.json index d38bbcf5c769..4cd4930fa802 100644 --- a/packages/eslint-plugin-sdk/.oxlintrc.json +++ b/packages/eslint-plugin-sdk/.oxlintrc.json @@ -1,4 +1,4 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"] + "extends": ["../../.oxlintrc.base.json"] } diff --git a/packages/feedback/.oxlintrc.json b/packages/feedback/.oxlintrc.json index d38bbcf5c769..4cd4930fa802 100644 --- a/packages/feedback/.oxlintrc.json +++ b/packages/feedback/.oxlintrc.json @@ -1,4 +1,4 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"] + "extends": ["../../.oxlintrc.base.json"] } diff --git a/packages/gatsby/.oxlintrc.json b/packages/gatsby/.oxlintrc.json index 5b04f7d7779b..82e1187d7863 100644 --- a/packages/gatsby/.oxlintrc.json +++ b/packages/gatsby/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], "env": { "browser": true, "node": true diff --git a/packages/gatsby/gatsby-node.js b/packages/gatsby/gatsby-node.js index 7b96ab049d26..85b968d1771e 100644 --- a/packages/gatsby/gatsby-node.js +++ b/packages/gatsby/gatsby-node.js @@ -41,7 +41,7 @@ exports.onCreateWebpackConfig = ({ getConfig, actions }, options) => { }, // Handle sentry-cli configuration errors when the user has not done it not to break // the build. - errorHandler(err, invokeErr) { + errorHandler(err) { const message = (err.message && err.message.toLowerCase()) || ''; if (message.includes('organization slug is required') || message.includes('project slug is required')) { // eslint-disable-next-line no-console @@ -55,7 +55,7 @@ exports.onCreateWebpackConfig = ({ getConfig, actions }, options) => { console.warn('Sentry [Warn]: Cannot upload source maps due to missing SENTRY_AUTH_TOKEN env variable.'); return; } - invokeErr(err); + throw err; }, }), ], diff --git a/packages/gatsby/package.json b/packages/gatsby/package.json index ed21adb80726..357933f567c6 100644 --- a/packages/gatsby/package.json +++ b/packages/gatsby/package.json @@ -47,7 +47,7 @@ "dependencies": { "@sentry/core": "10.47.0", "@sentry/react": "10.47.0", - "@sentry/webpack-plugin": "^5.1.0" + "@sentry/webpack-plugin": "^5.2.0" }, "peerDependencies": { "gatsby": "^3.0.0 || ^4.0.0 || ^5.0.0", diff --git a/packages/gatsby/test/gatsby-node.test.ts b/packages/gatsby/test/gatsby-node.test.ts index 262ea4cec55b..76e04f60cd14 100644 --- a/packages/gatsby/test/gatsby-node.test.ts +++ b/packages/gatsby/test/gatsby-node.test.ts @@ -65,6 +65,47 @@ describe('onCreateWebpackConfig', () => { expect(actions.setWebpackConfig).toHaveBeenCalledTimes(0); }); + describe('errorHandler', () => { + function getErrorHandler(): (err: Error) => void { + const actions = { setWebpackConfig: vi.fn() }; + const getConfig = vi.fn().mockReturnValue({ devtool: 'source-map' }); + + onCreateWebpackConfig({ actions, getConfig }, {}); + + const pluginOptions = sentryWebpackPlugin.mock.calls[0][0]; + return pluginOptions.errorHandler; + } + + afterEach(() => { + vi.clearAllMocks(); + }); + + it('accepts a single error argument (bundler-plugin-core v5 API)', () => { + const errorHandler = getErrorHandler(); + expect(() => errorHandler(new Error('some error'))).toThrow('some error'); + }); + + it('does not throw for missing organization slug', () => { + const errorHandler = getErrorHandler(); + expect(() => errorHandler(new Error('Organization slug is required'))).not.toThrow(); + }); + + it('does not throw for missing project slug', () => { + const errorHandler = getErrorHandler(); + expect(() => errorHandler(new Error('Project slug is required'))).not.toThrow(); + }); + + it('does not throw for missing auth token', () => { + const errorHandler = getErrorHandler(); + expect(() => errorHandler(new Error('Authentication credentials were not provided'))).not.toThrow(); + }); + + it('re-throws unknown errors', () => { + const errorHandler = getErrorHandler(); + expect(() => errorHandler(new Error('Something unexpected'))).toThrow('Something unexpected'); + }); + }); + describe('delete source maps after upload', () => { beforeEach(() => { vi.clearAllMocks(); diff --git a/packages/google-cloud-serverless/.oxlintrc.json b/packages/google-cloud-serverless/.oxlintrc.json index 8ca250cb7e99..f079a7bc588c 100644 --- a/packages/google-cloud-serverless/.oxlintrc.json +++ b/packages/google-cloud-serverless/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], "env": { "node": true } diff --git a/packages/google-cloud-serverless/src/index.ts b/packages/google-cloud-serverless/src/index.ts index 004c785b6ca5..2662ef4720a0 100644 --- a/packages/google-cloud-serverless/src/index.ts +++ b/packages/google-cloud-serverless/src/index.ts @@ -44,6 +44,7 @@ export { getSentryRelease, createGetModuleFromFilename, createLangChainCallbackHandler, + instrumentLangChainEmbeddings, httpHeadersToSpanAttributes, winterCGHeadersToDict, // eslint-disable-next-line deprecation/deprecation @@ -159,6 +160,8 @@ export { statsigIntegration, unleashIntegration, metrics, + spanStreamingIntegration, + withStreamedSpan, } from '@sentry/node'; export { diff --git a/packages/hono/.oxlintrc.json b/packages/hono/.oxlintrc.json index 5d561466a55b..d774a8e7bfa0 100644 --- a/packages/hono/.oxlintrc.json +++ b/packages/hono/.oxlintrc.json @@ -1,6 +1,12 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], + "jsPlugins": [ + { + "name": "sdk", + "specifier": "@sentry-internal/eslint-plugin-sdk" + } + ], "env": { "node": true }, diff --git a/packages/integration-shims/.oxlintrc.json b/packages/integration-shims/.oxlintrc.json index d38bbcf5c769..4cd4930fa802 100644 --- a/packages/integration-shims/.oxlintrc.json +++ b/packages/integration-shims/.oxlintrc.json @@ -1,4 +1,4 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"] + "extends": ["../../.oxlintrc.base.json"] } diff --git a/packages/nestjs/.oxlintrc.json b/packages/nestjs/.oxlintrc.json index 8ca250cb7e99..f079a7bc588c 100644 --- a/packages/nestjs/.oxlintrc.json +++ b/packages/nestjs/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], "env": { "node": true } diff --git a/packages/nextjs/.oxlintrc.json b/packages/nextjs/.oxlintrc.json index 1c483ce8e3b3..1aab7272e6d2 100644 --- a/packages/nextjs/.oxlintrc.json +++ b/packages/nextjs/.oxlintrc.json @@ -1,6 +1,12 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], + "jsPlugins": [ + { + "name": "sdk", + "specifier": "@sentry-internal/eslint-plugin-sdk" + } + ], "env": { "browser": true, "node": true diff --git a/packages/nextjs/package.json b/packages/nextjs/package.json index 797167fb2787..662e5039130f 100644 --- a/packages/nextjs/package.json +++ b/packages/nextjs/package.json @@ -80,13 +80,13 @@ "@opentelemetry/semantic-conventions": "^1.40.0", "@rollup/plugin-commonjs": "28.0.1", "@sentry-internal/browser-utils": "10.47.0", - "@sentry/bundler-plugin-core": "^5.1.0", + "@sentry/bundler-plugin-core": "^5.2.0", "@sentry/core": "10.47.0", "@sentry/node": "10.47.0", "@sentry/opentelemetry": "10.47.0", "@sentry/react": "10.47.0", "@sentry/vercel-edge": "10.47.0", - "@sentry/webpack-plugin": "^5.1.0", + "@sentry/webpack-plugin": "^5.2.0", "rollup": "^4.35.0", "stacktrace-parser": "^0.1.11" }, diff --git a/packages/nextjs/src/index.types.ts b/packages/nextjs/src/index.types.ts index 7c92fecd7834..2ae03ae3f204 100644 --- a/packages/nextjs/src/index.types.ts +++ b/packages/nextjs/src/index.types.ts @@ -23,6 +23,8 @@ export declare function init( export declare const linkedErrorsIntegration: typeof clientSdk.linkedErrorsIntegration; export declare const contextLinesIntegration: typeof clientSdk.contextLinesIntegration; +export declare const spanStreamingIntegration: typeof clientSdk.spanStreamingIntegration; +export declare const withStreamedSpan: typeof clientSdk.withStreamedSpan; // Different implementation in server and worker export declare const vercelAIIntegration: typeof serverSdk.vercelAIIntegration; diff --git a/packages/node-core/.oxlintrc.json b/packages/node-core/.oxlintrc.json index 714725dd1b45..7828795e480e 100644 --- a/packages/node-core/.oxlintrc.json +++ b/packages/node-core/.oxlintrc.json @@ -1,6 +1,12 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], + "jsPlugins": [ + { + "name": "sdk", + "specifier": "@sentry-internal/eslint-plugin-sdk" + } + ], "env": { "node": true }, diff --git a/packages/node-core/src/common-exports.ts b/packages/node-core/src/common-exports.ts index d6d1e070ef85..1c724d2c29f6 100644 --- a/packages/node-core/src/common-exports.ts +++ b/packages/node-core/src/common-exports.ts @@ -12,7 +12,11 @@ import * as logger from './logs/exports'; // Node-core integrations (not OTel-dependent) export { nodeContextIntegration } from './integrations/context'; -export { nodeRuntimeMetricsIntegration, type NodeRuntimeMetricsOptions } from './integrations/nodeRuntimeMetrics'; +export { + nodeRuntimeMetricsIntegration, + type NodeRuntimeMetricsOptions, + _INTERNAL_normalizeCollectionInterval, +} from './integrations/nodeRuntimeMetrics'; export { contextLinesIntegration } from './integrations/contextlines'; export { localVariablesIntegration } from './integrations/local-variables'; export { modulesIntegration } from './integrations/modules'; @@ -116,6 +120,8 @@ export { consoleIntegration, wrapMcpServerWithSentry, featureFlagsIntegration, + spanStreamingIntegration, + withStreamedSpan, metrics, envToBool, } from '@sentry/core'; diff --git a/packages/node-core/src/integrations/nodeRuntimeMetrics.ts b/packages/node-core/src/integrations/nodeRuntimeMetrics.ts index c2ae72f04f77..5d6ab5ea7ca0 100644 --- a/packages/node-core/src/integrations/nodeRuntimeMetrics.ts +++ b/packages/node-core/src/integrations/nodeRuntimeMetrics.ts @@ -3,8 +3,37 @@ import { _INTERNAL_safeDateNow, _INTERNAL_safeUnref, defineIntegration, metrics const INTEGRATION_NAME = 'NodeRuntimeMetrics'; const DEFAULT_INTERVAL_MS = 30_000; +const MIN_COLLECTION_INTERVAL_MS = 1_000; const EVENT_LOOP_DELAY_RESOLUTION_MS = 10; +/** + * Normalizes a `collectionIntervalMs` value, enforcing a minimum of 1000ms. + * - Non-finite values (NaN, Infinity): warns and falls back to `defaultInterval`. + * - Values below the minimum: warns and clamps to 1000ms. + * @internal + */ +export function _INTERNAL_normalizeCollectionInterval( + rawInterval: number, + integrationName: string, + defaultInterval: number, +): number { + if (!Number.isFinite(rawInterval)) { + // eslint-disable-next-line no-console + console.warn( + `[Sentry] ${integrationName}: collectionIntervalMs (${rawInterval}) is invalid. Using default of ${defaultInterval}ms.`, + ); + return defaultInterval; + } + if (rawInterval < MIN_COLLECTION_INTERVAL_MS) { + // eslint-disable-next-line no-console + console.warn( + `[Sentry] ${integrationName}: collectionIntervalMs (${rawInterval}) is below the minimum of ${MIN_COLLECTION_INTERVAL_MS}ms. Using minimum of ${MIN_COLLECTION_INTERVAL_MS}ms.`, + ); + return MIN_COLLECTION_INTERVAL_MS; + } + return rawInterval; +} + export interface NodeRuntimeMetricsOptions { /** * Which metrics to collect. @@ -44,7 +73,9 @@ export interface NodeRuntimeMetricsOptions { }; /** * How often to collect metrics, in milliseconds. + * Minimum allowed value is 1000ms. * @default 30000 + * @minimum 1000 */ collectionIntervalMs?: number; } @@ -62,7 +93,11 @@ export interface NodeRuntimeMetricsOptions { * ``` */ export const nodeRuntimeMetricsIntegration = defineIntegration((options: NodeRuntimeMetricsOptions = {}) => { - const collectionIntervalMs = options.collectionIntervalMs ?? DEFAULT_INTERVAL_MS; + const collectionIntervalMs = _INTERNAL_normalizeCollectionInterval( + options.collectionIntervalMs ?? DEFAULT_INTERVAL_MS, + INTEGRATION_NAME, + DEFAULT_INTERVAL_MS, + ); const collect = { // Default on cpuUtilization: true, diff --git a/packages/node-core/src/light/sdk.ts b/packages/node-core/src/light/sdk.ts index ef9229f28de6..77b62e9ab2f9 100644 --- a/packages/node-core/src/light/sdk.ts +++ b/packages/node-core/src/light/sdk.ts @@ -12,6 +12,7 @@ import { linkedErrorsIntegration, propagationContextFromHeaders, requestDataIntegration, + spanStreamingIntegration, stackParserFromStackParserOptions, } from '@sentry/core'; import { DEBUG_BUILD } from '../debug-build'; @@ -162,12 +163,18 @@ function getClientOptions( const integrations = options.integrations; const defaultIntegrations = options.defaultIntegrations ?? getDefaultIntegrationsImpl(mergedOptions); + const resolvedIntegrations = getIntegrationsToSetup({ + defaultIntegrations, + integrations, + }); + + if (mergedOptions.traceLifecycle === 'stream' && !resolvedIntegrations.some(i => i.name === 'SpanStreaming')) { + resolvedIntegrations.push(spanStreamingIntegration()); + } + return { ...mergedOptions, - integrations: getIntegrationsToSetup({ - defaultIntegrations, - integrations, - }), + integrations: resolvedIntegrations, }; } diff --git a/packages/node-core/src/sdk/index.ts b/packages/node-core/src/sdk/index.ts index de1569135cfd..5ae840e6e976 100644 --- a/packages/node-core/src/sdk/index.ts +++ b/packages/node-core/src/sdk/index.ts @@ -14,6 +14,7 @@ import { linkedErrorsIntegration, propagationContextFromHeaders, requestDataIntegration, + spanStreamingIntegration, stackParserFromStackParserOptions, } from '@sentry/core'; import { @@ -212,12 +213,18 @@ function getClientOptions( const integrations = options.integrations; const defaultIntegrations = options.defaultIntegrations ?? getDefaultIntegrationsImpl(mergedOptions); + const resolvedIntegrations = getIntegrationsToSetup({ + defaultIntegrations, + integrations, + }); + + if (mergedOptions.traceLifecycle === 'stream' && !resolvedIntegrations.some(i => i.name === 'SpanStreaming')) { + resolvedIntegrations.push(spanStreamingIntegration()); + } + return { ...mergedOptions, - integrations: getIntegrationsToSetup({ - defaultIntegrations, - integrations, - }), + integrations: resolvedIntegrations, }; } diff --git a/packages/node-core/src/utils/ensureIsWrapped.ts b/packages/node-core/src/utils/ensureIsWrapped.ts index 921d01da8207..7c10c1c9cfe7 100644 --- a/packages/node-core/src/utils/ensureIsWrapped.ts +++ b/packages/node-core/src/utils/ensureIsWrapped.ts @@ -1,5 +1,13 @@ import { isWrapped } from '@opentelemetry/instrumentation'; -import { consoleSandbox, getClient, getGlobalScope, hasSpansEnabled, isEnabled } from '@sentry/core'; +import { + consoleSandbox, + getClient, + getOriginalFunction, + getGlobalScope, + hasSpansEnabled, + isEnabled, + type WrappedFunction, +} from '@sentry/core'; import type { NodeClient } from '../sdk/client'; import { createMissingInstrumentationContext } from './createMissingInstrumentationContext'; import { isCjs } from './detection'; @@ -14,7 +22,10 @@ export function ensureIsWrapped( const clientOptions = getClient()?.getOptions(); if ( !clientOptions?.disableInstrumentationWarnings && - !isWrapped(maybeWrappedFunction) && + !( + isWrapped(maybeWrappedFunction) || + typeof getOriginalFunction(maybeWrappedFunction as WrappedFunction) === 'function' + ) && isEnabled() && hasSpansEnabled(clientOptions) ) { diff --git a/packages/node-core/test/integrations/nodeRuntimeMetrics.test.ts b/packages/node-core/test/integrations/nodeRuntimeMetrics.test.ts index fe1de568304a..f5dd76edf779 100644 --- a/packages/node-core/test/integrations/nodeRuntimeMetrics.test.ts +++ b/packages/node-core/test/integrations/nodeRuntimeMetrics.test.ts @@ -329,5 +329,42 @@ describe('nodeRuntimeMetricsIntegration', () => { expect(countSpy).not.toHaveBeenCalledWith('node.runtime.process.uptime', expect.anything(), expect.anything()); }); + + it('enforces minimum collectionIntervalMs of 1000ms and warns', () => { + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + + const integration = nodeRuntimeMetricsIntegration({ collectionIntervalMs: 100 }); + integration.setup(); + + expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('collectionIntervalMs')); + expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('1000')); + + // Should fire at the minimum 1000ms, not at 100ms + vi.advanceTimersByTime(100); + expect(gaugeSpy).not.toHaveBeenCalled(); + + vi.advanceTimersByTime(900); + expect(gaugeSpy).toHaveBeenCalled(); + + warnSpy.mockRestore(); + }); + + it('falls back to default when collectionIntervalMs is NaN', () => { + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + + const integration = nodeRuntimeMetricsIntegration({ collectionIntervalMs: NaN }); + integration.setup(); + + expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('collectionIntervalMs')); + + // Should fire at the default 30000ms, not at 1000ms + vi.advanceTimersByTime(1000); + expect(gaugeSpy).not.toHaveBeenCalled(); + + vi.advanceTimersByTime(29_000); + expect(gaugeSpy).toHaveBeenCalled(); + + warnSpy.mockRestore(); + }); }); }); diff --git a/packages/node-core/test/light/sdk.test.ts b/packages/node-core/test/light/sdk.test.ts index 8b0ef03700d9..48cac52022b0 100644 --- a/packages/node-core/test/light/sdk.test.ts +++ b/packages/node-core/test/light/sdk.test.ts @@ -106,6 +106,39 @@ describe('Light Mode | SDK', () => { expect(integrationNames).toContain('NodeFetch'); }); + + it('does not include spanStreaming integration', () => { + const integrations = Sentry.getDefaultIntegrations({ traceLifecycle: 'stream' }); + const integrationNames = integrations.map(i => i.name); + + expect(integrationNames).not.toContain('SpanStreaming'); + }); + }); + + describe('spanStreamingIntegration', () => { + it('installs spanStreaming integration when traceLifecycle is "stream"', () => { + const client = mockLightSdkInit({ traceLifecycle: 'stream' }); + const integrationNames = client?.getOptions().integrations.map(i => i.name); + + expect(integrationNames).toContain('SpanStreaming'); + }); + + it('does not install spanStreaming integration when traceLifecycle is not "stream"', () => { + const client = mockLightSdkInit(); + const integrationNames = client?.getOptions().integrations.map(i => i.name); + + expect(integrationNames).not.toContain('SpanStreaming'); + }); + + it('installs spanStreaming integration even with custom defaultIntegrations', () => { + const client = mockLightSdkInit({ + traceLifecycle: 'stream', + defaultIntegrations: [], + }); + const integrationNames = client?.getOptions().integrations.map(i => i.name); + + expect(integrationNames).toContain('SpanStreaming'); + }); }); describe('isInitialized', () => { diff --git a/packages/node-core/test/sdk/init.test.ts b/packages/node-core/test/sdk/init.test.ts index 144ff3e2dc37..6ee986c3be75 100644 --- a/packages/node-core/test/sdk/init.test.ts +++ b/packages/node-core/test/sdk/init.test.ts @@ -81,6 +81,39 @@ describe('init()', () => { expect(mockIntegrations[1]?.setupOnce as Mock).toHaveBeenCalledTimes(1); }); + it('installs spanStreaming integration when traceLifecycle is "stream"', () => { + init({ dsn: PUBLIC_DSN, traceLifecycle: 'stream' }); + const client = getClient(); + + expect(client?.getOptions()).toEqual( + expect.objectContaining({ + integrations: expect.arrayContaining([expect.objectContaining({ name: 'SpanStreaming' })]), + }), + ); + }); + + it("doesn't install spanStreaming integration when traceLifecycle is not 'stream'", () => { + init({ dsn: PUBLIC_DSN }); + const client = getClient(); + + expect(client?.getOptions()).toEqual( + expect.objectContaining({ + integrations: expect.not.arrayContaining([expect.objectContaining({ name: 'SpanStreaming' })]), + }), + ); + }); + + it('installs spanStreaming integration even with custom defaultIntegrations', () => { + init({ dsn: PUBLIC_DSN, traceLifecycle: 'stream', defaultIntegrations: [] }); + const client = getClient(); + + expect(client?.getOptions()).toEqual( + expect.objectContaining({ + integrations: expect.arrayContaining([expect.objectContaining({ name: 'SpanStreaming' })]), + }), + ); + }); + it('installs integrations returned from a callback function', () => { const mockDefaultIntegrations = [ new MockIntegration('Some mock integration 3.1'), diff --git a/packages/node-core/test/utils/ensureIsWrapped.test.ts b/packages/node-core/test/utils/ensureIsWrapped.test.ts index 890b913a4cb2..d636ed0c69d3 100644 --- a/packages/node-core/test/utils/ensureIsWrapped.test.ts +++ b/packages/node-core/test/utils/ensureIsWrapped.test.ts @@ -1,6 +1,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { ensureIsWrapped } from '../../src/utils/ensureIsWrapped'; import { cleanupOtel, mockSdkInit, resetGlobals } from '../helpers/mockSdkInit'; +import { markFunctionWrapped } from '@sentry/core'; const unwrappedFunction = () => {}; @@ -69,4 +70,24 @@ describe('ensureIsWrapped', () => { expect(spyWarn).toHaveBeenCalledTimes(0); }); + + it('does not warn when the method is wrapped by @sentry/core', () => { + const spyWarn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + + mockSdkInit({ tracesSampleRate: 1 }); + + function original() { + return 'i am original'; + } + + function sentryWrapped() { + return original(); + } + + markFunctionWrapped(sentryWrapped, original); + + ensureIsWrapped(sentryWrapped, 'express'); + + expect(spyWarn).toHaveBeenCalledTimes(0); + }); }); diff --git a/packages/node-native/.oxlintrc.json b/packages/node-native/.oxlintrc.json index 3d79070be500..3452decc312f 100644 --- a/packages/node-native/.oxlintrc.json +++ b/packages/node-native/.oxlintrc.json @@ -1,6 +1,12 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], + "jsPlugins": [ + { + "name": "sdk", + "specifier": "@sentry-internal/eslint-plugin-sdk" + } + ], "env": { "node": true }, diff --git a/packages/node/.oxlintrc.json b/packages/node/.oxlintrc.json index 714725dd1b45..7828795e480e 100644 --- a/packages/node/.oxlintrc.json +++ b/packages/node/.oxlintrc.json @@ -1,6 +1,12 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], + "jsPlugins": [ + { + "name": "sdk", + "specifier": "@sentry-internal/eslint-plugin-sdk" + } + ], "env": { "node": true }, diff --git a/packages/node/package.json b/packages/node/package.json index 39b438052daa..13230e707f90 100644 --- a/packages/node/package.json +++ b/packages/node/package.json @@ -72,7 +72,6 @@ "@opentelemetry/instrumentation-amqplib": "0.61.0", "@opentelemetry/instrumentation-connect": "0.57.0", "@opentelemetry/instrumentation-dataloader": "0.31.0", - "@opentelemetry/instrumentation-express": "0.62.0", "@opentelemetry/instrumentation-fs": "0.33.0", "@opentelemetry/instrumentation-generic-pool": "0.57.0", "@opentelemetry/instrumentation-graphql": "0.62.0", diff --git a/packages/node/src/index.ts b/packages/node/src/index.ts index 67fe97e59300..ce9458079980 100644 --- a/packages/node/src/index.ts +++ b/packages/node/src/index.ts @@ -140,7 +140,9 @@ export { consoleIntegration, wrapMcpServerWithSentry, featureFlagsIntegration, + spanStreamingIntegration, createLangChainCallbackHandler, + instrumentLangChainEmbeddings, instrumentLangGraph, instrumentStateGraphCompile, } from '@sentry/core'; @@ -203,4 +205,6 @@ export { cron, NODE_VERSION, validateOpenTelemetrySetup, + withStreamedSpan, + _INTERNAL_normalizeCollectionInterval, } from '@sentry/node-core'; diff --git a/packages/node/src/integrations/tracing/express.ts b/packages/node/src/integrations/tracing/express.ts index e645cc24d31e..eb396b81a6ee 100644 --- a/packages/node/src/integrations/tracing/express.ts +++ b/packages/node/src/integrations/tracing/express.ts @@ -1,197 +1,82 @@ -import type * as http from 'node:http'; -import type { Span } from '@opentelemetry/api'; -import type { ExpressRequestInfo } from '@opentelemetry/instrumentation-express'; -import { ExpressInstrumentation } from '@opentelemetry/instrumentation-express'; -import type { IntegrationFn } from '@sentry/core'; +// Automatic istrumentation for Express using OTel +import type { InstrumentationConfig } from '@opentelemetry/instrumentation'; +import { InstrumentationBase, InstrumentationNodeModuleDefinition } from '@opentelemetry/instrumentation'; +import { context } from '@opentelemetry/api'; +import { getRPCMetadata, RPCType } from '@opentelemetry/core'; + +import { ensureIsWrapped, generateInstrumentOnce } from '@sentry/node-core'; import { - captureException, + type ExpressIntegrationOptions, + type IntegrationFn, debug, + patchExpressModule, + SDK_VERSION, defineIntegration, - getDefaultIsolationScope, - getIsolationScope, - httpRequestToRequestData, - SEMANTIC_ATTRIBUTE_SENTRY_OP, - spanToJSON, + setupExpressErrorHandler as coreSetupExpressErrorHandler, + type ExpressHandlerOptions, } from '@sentry/core'; -import { addOriginToSpan, ensureIsWrapped, generateInstrumentOnce } from '@sentry/node-core'; +export { expressErrorHandler } from '@sentry/core'; import { DEBUG_BUILD } from '../../debug-build'; const INTEGRATION_NAME = 'Express'; +const SUPPORTED_VERSIONS = ['>=4.0.0 <6']; -function requestHook(span: Span): void { - addOriginToSpan(span, 'auto.http.otel.express'); - - const attributes = spanToJSON(span).data; - // this is one of: middleware, request_handler, router - const type = attributes['express.type']; - - if (type) { - span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, `${type}.express`); - } - - // Also update the name, we don't need to "middleware - " prefix - const name = attributes['express.name']; - if (typeof name === 'string') { - span.updateName(name); - } +export function setupExpressErrorHandler( + //oxlint-disable-next-line no-explicit-any + app: { use: (middleware: any) => unknown }, + options?: ExpressHandlerOptions, +): void { + coreSetupExpressErrorHandler(app, options); + ensureIsWrapped(app.use, 'express'); } -function spanNameHook(info: ExpressRequestInfo, defaultName: string): string { - if (getIsolationScope() === getDefaultIsolationScope()) { - DEBUG_BUILD && debug.warn('Isolation scope is still default isolation scope - skipping setting transactionName'); - return defaultName; - } - if (info.layerType === 'request_handler') { - // type cast b/c Otel unfortunately types info.request as any :( - const req = info.request as { method?: string }; - const method = req.method ? req.method.toUpperCase() : 'GET'; - getIsolationScope().setTransactionName(`${method} ${info.route}`); - } - return defaultName; -} +export type ExpressInstrumentationConfig = InstrumentationConfig & + Omit; export const instrumentExpress = generateInstrumentOnce( INTEGRATION_NAME, - () => - new ExpressInstrumentation({ - requestHook: span => requestHook(span), - spanNameHook: (info, defaultName) => spanNameHook(info, defaultName), - }), + (options?: ExpressInstrumentationConfig) => new ExpressInstrumentation(options), ); -const _expressIntegration = (() => { +export class ExpressInstrumentation extends InstrumentationBase { + public constructor(config: ExpressInstrumentationConfig = {}) { + super('sentry-express', SDK_VERSION, config); + } + public init(): InstrumentationNodeModuleDefinition { + const module = new InstrumentationNodeModuleDefinition( + 'express', + SUPPORTED_VERSIONS, + express => { + try { + patchExpressModule({ + ...this.getConfig(), + express, + onRouteResolved(route) { + const rpcMetadata = getRPCMetadata(context.active()); + if (route && rpcMetadata?.type === RPCType.HTTP) { + rpcMetadata.route = route; + } + }, + }); + } catch (e) { + DEBUG_BUILD && debug.error('Failed to patch express module:', e); + } + return express; + }, + // we do not ever actually unpatch in our SDKs + express => express, + ); + return module; + } +} + +const _expressInstrumentation = ((options?: ExpressInstrumentationConfig) => { return { name: INTEGRATION_NAME, setupOnce() { - instrumentExpress(); + instrumentExpress(options); }, }; }) satisfies IntegrationFn; -/** - * Adds Sentry tracing instrumentation for [Express](https://expressjs.com/). - * - * If you also want to capture errors, you need to call `setupExpressErrorHandler(app)` after you set up your Express server. - * - * For more information, see the [express documentation](https://docs.sentry.io/platforms/javascript/guides/express/). - * - * @example - * ```javascript - * const Sentry = require('@sentry/node'); - * - * Sentry.init({ - * integrations: [Sentry.expressIntegration()], - * }) - * ``` - */ -export const expressIntegration = defineIntegration(_expressIntegration); - -interface MiddlewareError extends Error { - status?: number | string; - statusCode?: number | string; - status_code?: number | string; - output?: { - statusCode?: number | string; - }; -} - -type ExpressMiddleware = (req: http.IncomingMessage, res: http.ServerResponse, next: () => void) => void; - -type ExpressErrorMiddleware = ( - error: MiddlewareError, - req: http.IncomingMessage, - res: http.ServerResponse, - next: (error: MiddlewareError) => void, -) => void; - -interface ExpressHandlerOptions { - /** - * Callback method deciding whether error should be captured and sent to Sentry - * @param error Captured middleware error - */ - shouldHandleError?(this: void, error: MiddlewareError): boolean; -} - -/** - * An Express-compatible error handler. - */ -export function expressErrorHandler(options?: ExpressHandlerOptions): ExpressErrorMiddleware { - return function sentryErrorMiddleware( - error: MiddlewareError, - request: http.IncomingMessage, - res: http.ServerResponse, - next: (error: MiddlewareError) => void, - ): void { - const normalizedRequest = httpRequestToRequestData(request); - // Ensure we use the express-enhanced request here, instead of the plain HTTP one - // When an error happens, the `expressRequestHandler` middleware does not run, so we set it here too - getIsolationScope().setSDKProcessingMetadata({ normalizedRequest }); - - const shouldHandleError = options?.shouldHandleError || defaultShouldHandleError; - - if (shouldHandleError(error)) { - const eventId = captureException(error, { mechanism: { type: 'auto.middleware.express', handled: false } }); - (res as { sentry?: string }).sentry = eventId; - } - - next(error); - }; -} - -function expressRequestHandler(): ExpressMiddleware { - return function sentryRequestMiddleware( - request: http.IncomingMessage, - _res: http.ServerResponse, - next: () => void, - ): void { - const normalizedRequest = httpRequestToRequestData(request); - // Ensure we use the express-enhanced request here, instead of the plain HTTP one - getIsolationScope().setSDKProcessingMetadata({ normalizedRequest }); - - next(); - }; -} - -/** - * Add an Express error handler to capture errors to Sentry. - * - * The error handler must be before any other middleware and after all controllers. - * - * @param app The Express instances - * @param options {ExpressHandlerOptions} Configuration options for the handler - * - * @example - * ```javascript - * const Sentry = require('@sentry/node'); - * const express = require("express"); - * - * const app = express(); - * - * // Add your routes, etc. - * - * // Add this after all routes, - * // but before any and other error-handling middlewares are defined - * Sentry.setupExpressErrorHandler(app); - * - * app.listen(3000); - * ``` - */ -export function setupExpressErrorHandler( - app: { use: (middleware: ExpressMiddleware | ExpressErrorMiddleware) => unknown }, - options?: ExpressHandlerOptions, -): void { - app.use(expressRequestHandler()); - app.use(expressErrorHandler(options)); - ensureIsWrapped(app.use, 'express'); -} - -function getStatusCodeFromResponse(error: MiddlewareError): number { - const statusCode = error.status || error.statusCode || error.status_code || error.output?.statusCode; - return statusCode ? parseInt(statusCode as string, 10) : 500; -} - -/** Returns true if response code is internal server error */ -function defaultShouldHandleError(error: MiddlewareError): boolean { - const status = getStatusCodeFromResponse(error); - return status >= 500; -} +export const expressIntegration = defineIntegration(_expressInstrumentation); diff --git a/packages/node/src/integrations/tracing/fastify/fastify-otel/.oxlintrc.json b/packages/node/src/integrations/tracing/fastify/fastify-otel/.oxlintrc.json index b7cd1ae58cb7..40e6ea6709c1 100644 --- a/packages/node/src/integrations/tracing/fastify/fastify-otel/.oxlintrc.json +++ b/packages/node/src/integrations/tracing/fastify/fastify-otel/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../../../../../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../../../../../../.oxlintrc.json"], + "extends": ["../../../../../../../.oxlintrc.base.json"], "env": { "node": true } diff --git a/packages/node/src/integrations/tracing/langchain/index.ts b/packages/node/src/integrations/tracing/langchain/index.ts index cbc7bae8c63d..279b8f8fc1c4 100644 --- a/packages/node/src/integrations/tracing/langchain/index.ts +++ b/packages/node/src/integrations/tracing/langchain/index.ts @@ -103,9 +103,10 @@ const _langChainIntegration = ((options: LangChainOptions = {}) => { * ## Supported Events * * The integration captures the following LangChain lifecycle events: - * - LLM/Chat Model: start, end, error - * - Chain: start, end, error - * - Tool: start, end, error + * - LLM/Chat Model: start, end, error (via callbacks) + * - Chain: start, end, error (via callbacks) + * - Tool: start, end, error (via callbacks) + * - Embeddings: embedQuery, embedDocuments (via direct method wrapping) * */ export const langChainIntegration = defineIntegration(_langChainIntegration); diff --git a/packages/node/src/integrations/tracing/langchain/instrumentation.ts b/packages/node/src/integrations/tracing/langchain/instrumentation.ts index 38f469f70db1..fb3e80b48583 100644 --- a/packages/node/src/integrations/tracing/langchain/instrumentation.ts +++ b/packages/node/src/integrations/tracing/langchain/instrumentation.ts @@ -11,6 +11,7 @@ import { ANTHROPIC_AI_INTEGRATION_NAME, createLangChainCallbackHandler, GOOGLE_GENAI_INTEGRATION_NAME, + instrumentLangChainEmbeddings, OPENAI_INTEGRATION_NAME, SDK_VERSION, } from '@sentry/core'; @@ -165,7 +166,7 @@ export class SentryLangChainInstrumentation extends InstrumentationBase; + + for (const exp of Object.values(exportsToPatch)) { + if (typeof exp !== 'function' || !exp.prototype) { + continue; + } + const proto = exp.prototype as Record; + if (typeof proto.embedQuery !== 'function' || typeof proto.embedDocuments !== 'function') { + continue; + } + if (proto.__sentry_patched__) { + continue; + } + proto.__sentry_patched__ = true; + + instrumentLangChainEmbeddings(proto, options); + } + } } diff --git a/packages/node/test/sdk/init.test.ts b/packages/node/test/sdk/init.test.ts index a6a76a4439bd..26fe2d9933e6 100644 --- a/packages/node/test/sdk/init.test.ts +++ b/packages/node/test/sdk/init.test.ts @@ -143,6 +143,39 @@ describe('init()', () => { }), ); }); + + it('installs spanStreaming integration when traceLifecycle is "stream"', () => { + init({ dsn: PUBLIC_DSN, traceLifecycle: 'stream' }); + const client = getClient(); + + expect(client?.getOptions()).toEqual( + expect.objectContaining({ + integrations: expect.arrayContaining([expect.objectContaining({ name: 'SpanStreaming' })]), + }), + ); + }); + + it("doesn't install spanStreaming integration when traceLifecycle is not 'stream'", () => { + init({ dsn: PUBLIC_DSN }); + + const client = getClient(); + expect(client?.getOptions()).toEqual( + expect.objectContaining({ + integrations: expect.not.arrayContaining([expect.objectContaining({ name: 'SpanStreaming' })]), + }), + ); + }); + + it('installs spanStreaming integration even with custom defaultIntegrations', () => { + init({ dsn: PUBLIC_DSN, traceLifecycle: 'stream', defaultIntegrations: [] }); + const client = getClient(); + + expect(client?.getOptions()).toEqual( + expect.objectContaining({ + integrations: expect.arrayContaining([expect.objectContaining({ name: 'SpanStreaming' })]), + }), + ); + }); }); describe('OpenTelemetry', () => { diff --git a/packages/nuxt/.oxlintrc.json b/packages/nuxt/.oxlintrc.json index 28d9e2d390f2..9623aa8dfd5a 100644 --- a/packages/nuxt/.oxlintrc.json +++ b/packages/nuxt/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], "env": { "browser": true, "node": true diff --git a/packages/nuxt/package.json b/packages/nuxt/package.json index bdbb117acd5c..bdb5b508818a 100644 --- a/packages/nuxt/package.json +++ b/packages/nuxt/package.json @@ -60,8 +60,8 @@ "@sentry/core": "10.47.0", "@sentry/node": "10.47.0", "@sentry/node-core": "10.47.0", - "@sentry/rollup-plugin": "^5.1.1", - "@sentry/vite-plugin": "^5.1.0", + "@sentry/rollup-plugin": "^5.2.0", + "@sentry/vite-plugin": "^5.2.0", "@sentry/vue": "10.47.0", "local-pkg": "^1.1.2" }, diff --git a/packages/nuxt/src/index.types.ts b/packages/nuxt/src/index.types.ts index 7109e7ad9c78..e058e0bfd099 100644 --- a/packages/nuxt/src/index.types.ts +++ b/packages/nuxt/src/index.types.ts @@ -16,6 +16,8 @@ export * from './index.server'; export declare function init(options: Options | SentryNuxtClientOptions | SentryNuxtServerOptions): Client | undefined; export declare const linkedErrorsIntegration: typeof clientSdk.linkedErrorsIntegration; export declare const contextLinesIntegration: typeof clientSdk.contextLinesIntegration; +export declare const spanStreamingIntegration: typeof clientSdk.spanStreamingIntegration; +export declare const withStreamedSpan: typeof clientSdk.withStreamedSpan; export declare const getDefaultIntegrations: (options: Options) => Integration[]; export declare const defaultStackParser: StackParser; diff --git a/packages/nuxt/src/runtime/plugins/sentry.server.ts b/packages/nuxt/src/runtime/plugins/sentry.server.ts index 63b4f6c107be..516dda7d8781 100644 --- a/packages/nuxt/src/runtime/plugins/sentry.server.ts +++ b/packages/nuxt/src/runtime/plugins/sentry.server.ts @@ -21,7 +21,9 @@ export default (nitroApp => { !!(event as any).res?.headers?.has?.('x-nitro-prerender'); // oxlint-disable-next-line typescript-oxlint/no-unsafe-member-access - const isSWRCachedPage = event?.context?.cache?.options?.swr as boolean | undefined; + const isSWRCachedPage = /* Nitro v2 */ (event?.context?.cache?.options?.swr || + // oxlint-disable-next-line typescript-oxlint/no-unsafe-member-access + /* Nitro v3 */ event?.context?.routeRules?.swr) as boolean; if (!isPreRenderedPage && !isSWRCachedPage) { addSentryTracingMetaTags(html.head); diff --git a/packages/opentelemetry/.oxlintrc.json b/packages/opentelemetry/.oxlintrc.json index 6b15cbd9576d..37af3a80b799 100644 --- a/packages/opentelemetry/.oxlintrc.json +++ b/packages/opentelemetry/.oxlintrc.json @@ -1,6 +1,12 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], + "jsPlugins": [ + { + "name": "sdk", + "specifier": "@sentry-internal/eslint-plugin-sdk" + } + ], "env": { "node": true }, diff --git a/packages/opentelemetry/src/constants.ts b/packages/opentelemetry/src/constants.ts index 375e42dfdd00..699868e3290a 100644 --- a/packages/opentelemetry/src/constants.ts +++ b/packages/opentelemetry/src/constants.ts @@ -9,6 +9,20 @@ export const SENTRY_TRACE_STATE_URL = 'sentry.url'; export const SENTRY_TRACE_STATE_SAMPLE_RAND = 'sentry.sample_rand'; export const SENTRY_TRACE_STATE_SAMPLE_RATE = 'sentry.sample_rate'; +/** + * A flag marking a context as ignored because the span associated with the context + * is ignored (`ignoreSpans` filter). + */ +export const SENTRY_TRACE_STATE_CHILD_IGNORED = 'sentry.ignored'; + +/** + * A flag marking a segment span as ignored because it matched the `ignoreSpans` filter. + * Unlike `SENTRY_TRACE_STATE_CHILD_IGNORED` (used for child spans), this flag is NOT consumed + * by the context manager for re-parenting. Instead, it propagates to child spans so they + * can record the correct client report outcome (`ignored` instead of `sample_rate`). + */ +export const SENTRY_TRACE_STATE_SEGMENT_IGNORED = 'sentry.segment_ignored'; + export const SENTRY_SCOPES_CONTEXT_KEY = createContextKey('sentry_scopes'); export const SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY = createContextKey('sentry_fork_isolation_scope'); diff --git a/packages/opentelemetry/src/contextManager.ts b/packages/opentelemetry/src/contextManager.ts index ac8b2eab5c9b..f5a137397978 100644 --- a/packages/opentelemetry/src/contextManager.ts +++ b/packages/opentelemetry/src/contextManager.ts @@ -1,5 +1,6 @@ import type { AsyncLocalStorage } from 'node:async_hooks'; import type { Context, ContextManager } from '@opentelemetry/api'; +import { trace } from '@opentelemetry/api'; import type { Scope } from '@sentry/core'; import { getCurrentScope, getIsolationScope } from '@sentry/core'; import { @@ -7,6 +8,7 @@ import { SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY, SENTRY_FORK_SET_SCOPE_CONTEXT_KEY, SENTRY_SCOPES_CONTEXT_KEY, + SENTRY_TRACE_STATE_CHILD_IGNORED, } from './constants'; import { getScopesFromContext, setContextOnScope, setScopesOnContext } from './utils/contextData'; import { setIsSetup } from './utils/setupCheck'; @@ -57,20 +59,36 @@ export function wrapContextManagerClass, ...args: A ): ReturnType { - const currentScopes = getScopesFromContext(context); + // Remove ignored spans from context and restore the parent span so children + // naturally parent to the grandparent instead of starting a new trace. + // At this point, this.active() still holds the outer context (before super.with() + // updates AsyncLocalStorage), which has the grandparent span we want to restore. + const span = trace.getSpan(context); + let effectiveContext: Context; + if (span?.spanContext().traceState?.get(SENTRY_TRACE_STATE_CHILD_IGNORED) === '1') { + const contextWithoutSpan = trace.deleteSpan(context); + const parentSpan = trace.getSpan(this.active()); + effectiveContext = parentSpan ? trace.setSpan(contextWithoutSpan, parentSpan) : contextWithoutSpan; + } else { + effectiveContext = context; + } + + const currentScopes = getScopesFromContext(effectiveContext); const currentScope = currentScopes?.scope || getCurrentScope(); const currentIsolationScope = currentScopes?.isolationScope || getIsolationScope(); - const shouldForkIsolationScope = context.getValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY) === true; - const scope = context.getValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY) as Scope | undefined; - const isolationScope = context.getValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY) as Scope | undefined; + const shouldForkIsolationScope = effectiveContext.getValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY) === true; + const scope = effectiveContext.getValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY) as Scope | undefined; + const isolationScope = effectiveContext.getValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY) as + | Scope + | undefined; const newCurrentScope = scope || currentScope.clone(); const newIsolationScope = isolationScope || (shouldForkIsolationScope ? currentIsolationScope.clone() : currentIsolationScope); const scopes = { scope: newCurrentScope, isolationScope: newIsolationScope }; - const ctx1 = setScopesOnContext(context, scopes); + const ctx1 = setScopesOnContext(effectiveContext, scopes); // Remove the unneeded values again const ctx2 = ctx1 diff --git a/packages/opentelemetry/src/index.ts b/packages/opentelemetry/src/index.ts index e0112812dc69..f5260dc852c5 100644 --- a/packages/opentelemetry/src/index.ts +++ b/packages/opentelemetry/src/index.ts @@ -48,5 +48,7 @@ export { SentrySampler, wrapSamplingDecision } from './sampler'; export { openTelemetrySetupCheck } from './utils/setupCheck'; +export { withStreamedSpan } from '@sentry/core'; + // Legacy export { getClient } from '@sentry/core'; diff --git a/packages/opentelemetry/src/sampler.ts b/packages/opentelemetry/src/sampler.ts index 7f7edd441612..5c0c47423284 100644 --- a/packages/opentelemetry/src/sampler.ts +++ b/packages/opentelemetry/src/sampler.ts @@ -16,16 +16,20 @@ import { baggageHeaderToDynamicSamplingContext, debug, hasSpansEnabled, + hasSpanStreamingEnabled, parseSampleRate, sampleSpan, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, + shouldIgnoreSpan, } from '@sentry/core'; import { SENTRY_TRACE_STATE_DSC, + SENTRY_TRACE_STATE_CHILD_IGNORED, SENTRY_TRACE_STATE_SAMPLE_RAND, SENTRY_TRACE_STATE_SAMPLE_RATE, SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING, + SENTRY_TRACE_STATE_SEGMENT_IGNORED, SENTRY_TRACE_STATE_URL, } from './constants'; import { DEBUG_BUILD } from './debug-build'; @@ -39,9 +43,11 @@ import { setIsSetup } from './utils/setupCheck'; */ export class SentrySampler implements Sampler { private _client: Client; + private _isSpanStreaming: boolean; public constructor(client: Client) { this._client = client; + this._isSpanStreaming = hasSpanStreamingEnabled(client); setIsSetup('SentrySampler'); } @@ -55,6 +61,7 @@ export class SentrySampler implements Sampler { _links: unknown, ): SamplingResult { const options = this._client.getOptions(); + const { ignoreSpans } = options; const parentSpan = getValidSpan(context); const parentContext = parentSpan?.spanContext(); @@ -79,6 +86,36 @@ export class SentrySampler implements Sampler { // We only sample based on parameters (like tracesSampleRate or tracesSampler) for root spans (which is done in sampleSpan). // Non-root-spans simply inherit the sampling decision from their parent. if (!isRootSpan) { + if (this._isSpanStreaming) { + // `ignoreSpans` is only applied at span start for streamed spans. + // Static spans/transactions get filtered at transaction end. + // Likewise, we only record client outcomes for child spans when streaming + if (parentSampled) { + if (ignoreSpans?.length) { + const { description: inferredChildName, op: childOp } = inferSpanData(spanName, spanAttributes, spanKind); + if ( + shouldIgnoreSpan( + { description: inferredChildName, op: spanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] ?? childOp }, + ignoreSpans, + ) + ) { + this._client.recordDroppedEvent('ignored', 'span'); + return wrapSamplingDecision({ + decision: SamplingDecision.NOT_RECORD, + context, + spanAttributes, + ignoredChildSpan: true, + }); + } + } + } + + if (!parentSampled) { + const parentSegmentIgnored = parentContext?.traceState?.get(SENTRY_TRACE_STATE_SEGMENT_IGNORED) === '1'; + this._client.recordDroppedEvent(parentSegmentIgnored ? 'ignored' : 'sample_rate', 'span'); + } + } + return wrapSamplingDecision({ decision: parentSampled ? SamplingDecision.RECORD_AND_SAMPLED : SamplingDecision.NOT_RECORD, context, @@ -102,6 +139,23 @@ export class SentrySampler implements Sampler { mergedAttributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] = op; } + if ( + this._isSpanStreaming && + ignoreSpans?.length && + shouldIgnoreSpan( + { description: inferredSpanName, op: mergedAttributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] ?? op }, + ignoreSpans, + ) + ) { + this._client.recordDroppedEvent('ignored', 'span'); + return wrapSamplingDecision({ + decision: SamplingDecision.NOT_RECORD, + context, + spanAttributes, + ignoredSegmentSpan: true, + }); + } + const mutableSamplingDecision = { decision: true }; this._client.emit( 'beforeSampling', @@ -155,7 +209,7 @@ export class SentrySampler implements Sampler { parentSampled === undefined ) { DEBUG_BUILD && debug.log('[Tracing] Discarding root span because its trace was not chosen to be sampled.'); - this._client.recordDroppedEvent('sample_rate', 'transaction'); + this._client.recordDroppedEvent('sample_rate', this._isSpanStreaming ? 'span' : 'transaction'); } return { @@ -211,12 +265,17 @@ export function wrapSamplingDecision({ spanAttributes, sampleRand, downstreamTraceSampleRate, + ignoredChildSpan, + ignoredSegmentSpan, }: { decision: SamplingDecision | undefined; context: Context; spanAttributes: SpanAttributes; sampleRand?: number; downstreamTraceSampleRate?: number; + // flags for ignored streamed spans (only set for span streaming) + ignoredChildSpan?: boolean; + ignoredSegmentSpan?: boolean; }): SamplingResult { let traceState = getBaseTraceState(context, spanAttributes); @@ -232,6 +291,14 @@ export function wrapSamplingDecision({ traceState = traceState.set(SENTRY_TRACE_STATE_SAMPLE_RAND, `${sampleRand}`); } + if (ignoredChildSpan) { + traceState = traceState.set(SENTRY_TRACE_STATE_CHILD_IGNORED, '1'); + } + + if (ignoredSegmentSpan) { + traceState = traceState.set(SENTRY_TRACE_STATE_SEGMENT_IGNORED, '1'); + } + // If the decision is undefined, we treat it as NOT_RECORDING, but we don't propagate this decision to downstream SDKs // Which is done by not setting `SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING` traceState if (decision == undefined) { diff --git a/packages/opentelemetry/src/spanProcessor.ts b/packages/opentelemetry/src/spanProcessor.ts index 3430456caaee..b4b913c5535e 100644 --- a/packages/opentelemetry/src/spanProcessor.ts +++ b/packages/opentelemetry/src/spanProcessor.ts @@ -6,6 +6,7 @@ import { getClient, getDefaultCurrentScope, getDefaultIsolationScope, + hasSpanStreamingEnabled, logSpanEnd, logSpanStart, setCapturedScopesOnSpan, @@ -14,50 +15,6 @@ import { SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE } from './semanticAttributes import { SentrySpanExporter } from './spanExporter'; import { getScopesFromContext } from './utils/contextData'; import { setIsSetup } from './utils/setupCheck'; - -function onSpanStart(span: Span, parentContext: Context): void { - // This is a reliable way to get the parent span - because this is exactly how the parent is identified in the OTEL SDK - const parentSpan = trace.getSpan(parentContext); - - let scopes = getScopesFromContext(parentContext); - - // We need access to the parent span in order to be able to move up the span tree for breadcrumbs - if (parentSpan && !parentSpan.spanContext().isRemote) { - addChildSpanToSpan(parentSpan, span); - } - - // We need this in the span exporter - if (parentSpan?.spanContext().isRemote) { - span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE, true); - } - - // The root context does not have scopes stored, so we check for this specifically - // As fallback we attach the global scopes - if (parentContext === ROOT_CONTEXT) { - scopes = { - scope: getDefaultCurrentScope(), - isolationScope: getDefaultIsolationScope(), - }; - } - - // We need the scope at time of span creation in order to apply it to the event when the span is finished - if (scopes) { - setCapturedScopesOnSpan(span, scopes.scope, scopes.isolationScope); - } - - logSpanStart(span); - - const client = getClient(); - client?.emit('spanStart', span); -} - -function onSpanEnd(span: Span): void { - logSpanEnd(span); - - const client = getClient(); - client?.emit('spanEnd', span); -} - /** * Converts OpenTelemetry Spans to Sentry Spans and sends them to Sentry via * the Sentry SDK. @@ -88,13 +45,52 @@ export class SentrySpanProcessor implements SpanProcessorInterface { * @inheritDoc */ public onStart(span: Span, parentContext: Context): void { - onSpanStart(span, parentContext); + // This is a reliable way to get the parent span - because this is exactly how the parent is identified in the OTEL SDK + const parentSpan = trace.getSpan(parentContext); + + let scopes = getScopesFromContext(parentContext); + + // We need access to the parent span in order to be able to move up the span tree for breadcrumbs + if (parentSpan && !parentSpan.spanContext().isRemote) { + addChildSpanToSpan(parentSpan, span); + } + + // We need this in the span exporter + if (parentSpan?.spanContext().isRemote) { + span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE, true); + } + + // The root context does not have scopes stored, so we check for this specifically + // As fallback we attach the global scopes + if (parentContext === ROOT_CONTEXT) { + scopes = { + scope: getDefaultCurrentScope(), + isolationScope: getDefaultIsolationScope(), + }; + } + + // We need the scope at time of span creation in order to apply it to the event when the span is finished + if (scopes) { + setCapturedScopesOnSpan(span, scopes.scope, scopes.isolationScope); + } + + logSpanStart(span); + + const client = getClient(); + client?.emit('spanStart', span); } /** @inheritDoc */ public onEnd(span: Span & ReadableSpan): void { - onSpanEnd(span); + logSpanEnd(span); + + const client = getClient(); + client?.emit('spanEnd', span); - this._exporter.export(span); + if (client && hasSpanStreamingEnabled(client)) { + client.emit('afterSpanEnd', span); + } else { + this._exporter.export(span); + } } } diff --git a/packages/opentelemetry/test/contextManager.test.ts b/packages/opentelemetry/test/contextManager.test.ts new file mode 100644 index 000000000000..4b871ac3e7bb --- /dev/null +++ b/packages/opentelemetry/test/contextManager.test.ts @@ -0,0 +1,48 @@ +import { context, trace, TraceFlags } from '@opentelemetry/api'; +import { TraceState } from '@opentelemetry/core'; +import { afterEach, describe, expect, it } from 'vitest'; +import { SENTRY_TRACE_STATE_CHILD_IGNORED } from '../src/constants'; +import { cleanupOtel, mockSdkInit } from './helpers/mockSdkInit'; + +describe('SentryContextManager', () => { + afterEach(async () => { + await cleanupOtel(); + }); + + it('removes ignored spans from context so children parent to grandparent', () => { + mockSdkInit({ tracesSampleRate: 1 }); + + const ignoredTraceState = new TraceState().set(SENTRY_TRACE_STATE_CHILD_IGNORED, '1'); + const ignoredSpanContext = { + traceId: '00000000000000000000000000000001', + spanId: '0000000000000001', + traceFlags: TraceFlags.NONE, + traceState: ignoredTraceState, + }; + + const ctxWithIgnored = trace.setSpanContext(context.active(), ignoredSpanContext); + + context.with(ctxWithIgnored, () => { + const activeSpan = trace.getSpan(context.active()); + expect(activeSpan).toBeUndefined(); + }); + }); + + it('preserves non-ignored spans in context', () => { + mockSdkInit({ tracesSampleRate: 1 }); + + const normalSpanContext = { + traceId: '00000000000000000000000000000001', + spanId: '0000000000000001', + traceFlags: TraceFlags.SAMPLED, + }; + + const ctxWithSpan = trace.setSpanContext(context.active(), normalSpanContext); + + context.with(ctxWithSpan, () => { + const activeSpan = trace.getSpan(context.active()); + expect(activeSpan).toBeDefined(); + expect(activeSpan?.spanContext().spanId).toBe('0000000000000001'); + }); + }); +}); diff --git a/packages/opentelemetry/test/sampler.test.ts b/packages/opentelemetry/test/sampler.test.ts index b7ffd9522837..654d96be91c4 100644 --- a/packages/opentelemetry/test/sampler.test.ts +++ b/packages/opentelemetry/test/sampler.test.ts @@ -1,10 +1,14 @@ -import { context, SpanKind, trace } from '@opentelemetry/api'; +import { context, SpanKind, trace, TraceFlags } from '@opentelemetry/api'; import { TraceState } from '@opentelemetry/core'; import { SamplingDecision } from '@opentelemetry/sdk-trace-base'; import { ATTR_HTTP_REQUEST_METHOD } from '@opentelemetry/semantic-conventions'; import { generateSpanId, generateTraceId } from '@sentry/core'; import { afterEach, describe, expect, it, vi } from 'vitest'; -import { SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING } from '../src/constants'; +import { + SENTRY_TRACE_STATE_CHILD_IGNORED, + SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING, + SENTRY_TRACE_STATE_SEGMENT_IGNORED, +} from '../src/constants'; import { SentrySampler } from '../src/sampler'; import { cleanupOtel } from './helpers/mockSdkInit'; import { getDefaultTestClientOptions, TestClient } from './helpers/TestClient'; @@ -14,7 +18,7 @@ describe('SentrySampler', () => { await cleanupOtel(); }); - it('works with tracesSampleRate=0', () => { + it('samples negatively with tracesSampleRate=0 and records a sample_rate outcome', () => { const client = new TestClient(getDefaultTestClientOptions({ tracesSampleRate: 0 })); const spyOnDroppedEvent = vi.spyOn(client, 'recordDroppedEvent'); const sampler = new SentrySampler(client); @@ -41,7 +45,7 @@ describe('SentrySampler', () => { spyOnDroppedEvent.mockReset(); }); - it('works with tracesSampleRate=0 & for a child span', () => { + it('samples a child span negatively based on tracesSampleRate=0', () => { const client = new TestClient(getDefaultTestClientOptions({ tracesSampleRate: 0 })); const spyOnDroppedEvent = vi.spyOn(client, 'recordDroppedEvent'); const sampler = new SentrySampler(client); @@ -63,12 +67,13 @@ describe('SentrySampler', () => { decision: SamplingDecision.NOT_RECORD, traceState: new TraceState().set(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING, '1'), }); - expect(spyOnDroppedEvent).toHaveBeenCalledTimes(0); + // Does not record a client outcome for child spans when in static trace lifecycle (i.e. transactions) + expect(spyOnDroppedEvent).not.toHaveBeenCalled(); spyOnDroppedEvent.mockReset(); }); - it('works with tracesSampleRate=1', () => { + it('samples positively with tracesSampleRate=1', () => { const client = new TestClient(getDefaultTestClientOptions({ tracesSampleRate: 1 })); const spyOnDroppedEvent = vi.spyOn(client, 'recordDroppedEvent'); const sampler = new SentrySampler(client); @@ -93,7 +98,7 @@ describe('SentrySampler', () => { spyOnDroppedEvent.mockReset(); }); - it('works with traceSampleRate=undefined', () => { + it('defers sampling with traceSampleRate=undefined', () => { const client = new TestClient(getDefaultTestClientOptions({ tracesSampleRate: undefined })); const spyOnDroppedEvent = vi.spyOn(client, 'recordDroppedEvent'); const sampler = new SentrySampler(client); @@ -138,4 +143,209 @@ describe('SentrySampler', () => { spyOnDroppedEvent.mockReset(); }); + + describe('when span streaming is enabled', () => { + /* + For span streaming, we use the Sampler to "sample" spans based on `ignoreSpans`. In reality though, + we don't apply sampling options (rate, traces_sampler) but just filter spans via `ignoreSpans`. + The sampler allows us to modify context and tracestate to correctly propagate filtering decisions + to potential child spans (e.g. when a segment is ignored, so that all its children are also ignored). + */ + it('returns NOT_RECORD for root span matching ignoreSpans string pattern', () => { + const client = new TestClient( + getDefaultTestClientOptions({ tracesSampleRate: 1, traceLifecycle: 'stream', ignoreSpans: ['GET /health'] }), + ); + const spyOnDroppedEvent = vi.spyOn(client, 'recordDroppedEvent'); + const sampler = new SentrySampler(client); + + const ctx = context.active(); + const traceId = generateTraceId(); + const spanName = 'GET /health'; + const spanKind = SpanKind.SERVER; + const spanAttributes = {}; + + const actual = sampler.shouldSample(ctx, traceId, spanName, spanKind, spanAttributes, undefined); + expect(actual.decision).toBe(SamplingDecision.NOT_RECORD); + expect(spyOnDroppedEvent).toHaveBeenCalledWith('ignored', 'span'); + expect(spyOnDroppedEvent).toHaveBeenCalledOnce(); + }); + + it('returns NOT_RECORD for root span matching ignoreSpans regex pattern', () => { + const client = new TestClient( + getDefaultTestClientOptions({ tracesSampleRate: 1, traceLifecycle: 'stream', ignoreSpans: [/health/] }), + ); + const spyOnDroppedEvent = vi.spyOn(client, 'recordDroppedEvent'); + const sampler = new SentrySampler(client); + + const ctx = context.active(); + const traceId = generateTraceId(); + const spanName = 'GET /healthcheck'; + const spanKind = SpanKind.SERVER; + const spanAttributes = {}; + + const actual = sampler.shouldSample(ctx, traceId, spanName, spanKind, spanAttributes, undefined); + expect(actual.decision).toBe(SamplingDecision.NOT_RECORD); + expect(spyOnDroppedEvent).toHaveBeenCalledWith('ignored', 'span'); + expect(spyOnDroppedEvent).toHaveBeenCalledOnce(); + }); + + it('returns NOT_RECORD for root span matching ignoreSpans IgnoreSpanFilter with name and op', () => { + const client = new TestClient( + getDefaultTestClientOptions({ + tracesSampleRate: 1, + traceLifecycle: 'stream', + ignoreSpans: [{ name: 'GET /health', op: 'http.server' }], + }), + ); + const spyOnDroppedEvent = vi.spyOn(client, 'recordDroppedEvent'); + const sampler = new SentrySampler(client); + + const ctx = context.active(); + const traceId = generateTraceId(); + const spanName = 'GET /health'; + const spanKind = SpanKind.SERVER; + const spanAttributes = { [ATTR_HTTP_REQUEST_METHOD]: 'GET' }; + + const actual = sampler.shouldSample(ctx, traceId, spanName, spanKind, spanAttributes, undefined); + expect(actual.decision).toBe(SamplingDecision.NOT_RECORD); + expect(spyOnDroppedEvent).toHaveBeenCalledWith('ignored', 'span'); + expect(spyOnDroppedEvent).toHaveBeenCalledOnce(); + }); + + it("doesn't ignore root span that does not match ignoreSpans", () => { + const client = new TestClient( + getDefaultTestClientOptions({ tracesSampleRate: 1, traceLifecycle: 'stream', ignoreSpans: ['GET /health'] }), + ); + const spyOnDroppedEvent = vi.spyOn(client, 'recordDroppedEvent'); + const sampler = new SentrySampler(client); + + const ctx = context.active(); + const traceId = generateTraceId(); + const spanName = 'GET /users'; + const spanKind = SpanKind.SERVER; + const spanAttributes = {}; + + const actual = sampler.shouldSample(ctx, traceId, spanName, spanKind, spanAttributes, undefined); + expect(actual.decision).toBe(SamplingDecision.RECORD_AND_SAMPLED); + expect(spyOnDroppedEvent).not.toHaveBeenCalled(); + }); + + it('returns NOT_RECORD with sentry.ignored traceState for child span matching ignoreSpans', () => { + const client = new TestClient( + getDefaultTestClientOptions({ + tracesSampleRate: 1, + traceLifecycle: 'stream', + ignoreSpans: ['middleware - expressInit'], + }), + ); + const spyOnDroppedEvent = vi.spyOn(client, 'recordDroppedEvent'); + const sampler = new SentrySampler(client); + + const traceId = generateTraceId(); + const ctx = trace.setSpanContext(context.active(), { + traceId, + spanId: generateSpanId(), + traceFlags: TraceFlags.SAMPLED, + isRemote: false, + }); + + const actual = sampler.shouldSample(ctx, traceId, 'middleware - expressInit', SpanKind.INTERNAL, {}, undefined); + + expect(actual.decision).toBe(SamplingDecision.NOT_RECORD); + expect(actual.traceState?.get(SENTRY_TRACE_STATE_CHILD_IGNORED)).toBe('1'); + expect(spyOnDroppedEvent).toHaveBeenCalledWith('ignored', 'span'); + expect(spyOnDroppedEvent).toHaveBeenCalledOnce(); + }); + + it("doesn't set SENTRY_TRACE_STATE_CHILD_IGNORED for child span not matching ignoreSpans", () => { + const client = new TestClient( + getDefaultTestClientOptions({ + tracesSampleRate: 1, + traceLifecycle: 'stream', + ignoreSpans: ['middleware - expressInit'], + }), + ); + const spyOnDroppedEvent = vi.spyOn(client, 'recordDroppedEvent'); + const sampler = new SentrySampler(client); + + const traceId = generateTraceId(); + const ctx = trace.setSpanContext(context.active(), { + traceId, + spanId: generateSpanId(), + traceFlags: TraceFlags.SAMPLED, + isRemote: false, + }); + + const actual = sampler.shouldSample(ctx, traceId, 'db.query SELECT 1', SpanKind.CLIENT, {}, undefined); + + expect(actual.decision).toBe(SamplingDecision.RECORD_AND_SAMPLED); + expect(actual.traceState?.get(SENTRY_TRACE_STATE_CHILD_IGNORED)).toBeUndefined(); + expect(spyOnDroppedEvent).not.toHaveBeenCalled(); + }); + + it('sets sentry.segment_ignored traceState for a segment span matching ignoreSpans', () => { + const client = new TestClient( + getDefaultTestClientOptions({ tracesSampleRate: 1, traceLifecycle: 'stream', ignoreSpans: ['GET /health'] }), + ); + const spyOnDroppedEvent = vi.spyOn(client, 'recordDroppedEvent'); + const sampler = new SentrySampler(client); + + const ctx = context.active(); + const traceId = generateTraceId(); + const spanName = 'GET /health'; + const spanKind = SpanKind.SERVER; + const spanAttributes = {}; + + const actual = sampler.shouldSample(ctx, traceId, spanName, spanKind, spanAttributes, undefined); + expect(actual.decision).toBe(SamplingDecision.NOT_RECORD); + expect(actual.traceState?.get(SENTRY_TRACE_STATE_SEGMENT_IGNORED)).toBe('1'); + expect(actual.traceState?.get(SENTRY_TRACE_STATE_CHILD_IGNORED)).toBeUndefined(); + expect(spyOnDroppedEvent).toHaveBeenCalledWith('ignored', 'span'); + expect(spyOnDroppedEvent).toHaveBeenCalledOnce(); + }); + + it('records ignored outcome for child span of ignored segment', () => { + const client = new TestClient( + getDefaultTestClientOptions({ tracesSampleRate: 1, traceLifecycle: 'stream', ignoreSpans: ['GET /health'] }), + ); + const spyOnDroppedEvent = vi.spyOn(client, 'recordDroppedEvent'); + const sampler = new SentrySampler(client); + + const traceId = generateTraceId(); + const ctx = trace.setSpanContext(context.active(), { + spanId: generateSpanId(), + traceId, + traceFlags: 0, + traceState: new TraceState() + .set(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING, '1') + .set(SENTRY_TRACE_STATE_SEGMENT_IGNORED, '1'), + }); + + const actual = sampler.shouldSample(ctx, traceId, 'db.query SELECT 1', SpanKind.CLIENT, {}, undefined); + expect(actual.decision).toBe(SamplingDecision.NOT_RECORD); + expect(spyOnDroppedEvent).toHaveBeenCalledOnce(); + expect(spyOnDroppedEvent).toHaveBeenCalledWith('ignored', 'span'); + }); + + it('records sample_rate outcome for child span of negatively sampled segment', () => { + // For span streaming, we also record a sample_rate outcome for a child span of a negatively sampled trace. + + const client = new TestClient(getDefaultTestClientOptions({ tracesSampleRate: 0, traceLifecycle: 'stream' })); + const spyOnDroppedEvent = vi.spyOn(client, 'recordDroppedEvent'); + const sampler = new SentrySampler(client); + + const traceId = generateTraceId(); + const ctx = trace.setSpanContext(context.active(), { + spanId: generateSpanId(), + traceId, + traceFlags: 0, + traceState: new TraceState().set(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING, '1'), + }); + + const actual = sampler.shouldSample(ctx, traceId, 'db.query SELECT 1', SpanKind.CLIENT, {}, undefined); + expect(actual.decision).toBe(SamplingDecision.NOT_RECORD); + expect(spyOnDroppedEvent).toHaveBeenCalledTimes(1); + expect(spyOnDroppedEvent).toHaveBeenCalledWith('sample_rate', 'span'); + }); + }); }); diff --git a/packages/opentelemetry/test/spanProcessor.test.ts b/packages/opentelemetry/test/spanProcessor.test.ts new file mode 100644 index 000000000000..2e3b0b5b999e --- /dev/null +++ b/packages/opentelemetry/test/spanProcessor.test.ts @@ -0,0 +1,57 @@ +import { getClient, startInactiveSpan } from '@sentry/core'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { SentrySpanExporter } from '../src/spanExporter'; +import { cleanupOtel, mockSdkInit } from './helpers/mockSdkInit'; + +const exportSpy = vi.spyOn(SentrySpanExporter.prototype, 'export'); + +describe('SentrySpanProcessor', () => { + beforeEach(() => { + exportSpy.mockClear(); + }); + + describe('with traceLifecycle: static (default)', () => { + beforeEach(() => { + mockSdkInit({ tracesSampleRate: 1 }); + }); + + afterEach(async () => { + await cleanupOtel(); + }); + + it('exports spans via the exporter', () => { + const span = startInactiveSpan({ name: 'test' }); + span.end(); + + expect(exportSpy).toHaveBeenCalled(); + }); + }); + + describe('with traceLifecycle: stream', () => { + beforeEach(() => { + mockSdkInit({ tracesSampleRate: 1, traceLifecycle: 'stream' }); + }); + + afterEach(async () => { + await cleanupOtel(); + }); + + it('does not export spans via the exporter', () => { + const span = startInactiveSpan({ name: 'test' }); + span.end(); + + expect(exportSpy).not.toHaveBeenCalled(); + }); + + it('emits afterSpanEnd', () => { + const afterSpanEndCallback = vi.fn(); + const client = getClient()!; + client.on('afterSpanEnd', afterSpanEndCallback); + + const span = startInactiveSpan({ name: 'test' }); + span.end(); + + expect(afterSpanEndCallback).toHaveBeenCalledWith(span); + }); + }); +}); diff --git a/packages/profiling-node/.oxlintrc.json b/packages/profiling-node/.oxlintrc.json index 2ae976eabb62..3a49bb14b11d 100644 --- a/packages/profiling-node/.oxlintrc.json +++ b/packages/profiling-node/.oxlintrc.json @@ -1,6 +1,12 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], + "jsPlugins": [ + { + "name": "sdk", + "specifier": "@sentry-internal/eslint-plugin-sdk" + } + ], "env": { "node": true }, diff --git a/packages/react-router/.oxlintrc.json b/packages/react-router/.oxlintrc.json index 28d9e2d390f2..9623aa8dfd5a 100644 --- a/packages/react-router/.oxlintrc.json +++ b/packages/react-router/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], "env": { "browser": true, "node": true diff --git a/packages/react-router/package.json b/packages/react-router/package.json index 4a10b0b045d8..998f1c2a3449 100644 --- a/packages/react-router/package.json +++ b/packages/react-router/package.json @@ -54,7 +54,7 @@ "@sentry/core": "10.47.0", "@sentry/node": "10.47.0", "@sentry/react": "10.47.0", - "@sentry/vite-plugin": "^5.1.0", + "@sentry/vite-plugin": "^5.2.0", "glob": "^13.0.6" }, "devDependencies": { diff --git a/packages/react-router/src/client/index.ts b/packages/react-router/src/client/index.ts index 6734b21c8583..24431843710c 100644 --- a/packages/react-router/src/client/index.ts +++ b/packages/react-router/src/client/index.ts @@ -31,3 +31,5 @@ export { isNavigateHookInvoked, type CreateSentryClientInstrumentationOptions, } from './createClientInstrumentation'; + +export { sentryOnError } from './sentryOnError'; diff --git a/packages/react-router/src/client/sentryOnError.ts b/packages/react-router/src/client/sentryOnError.ts new file mode 100644 index 000000000000..bf6d8108565d --- /dev/null +++ b/packages/react-router/src/client/sentryOnError.ts @@ -0,0 +1,36 @@ +import { captureException } from '@sentry/core'; +import { captureReactException } from '@sentry/react'; + +/** + * A handler function for React Router's `onError` prop on `HydratedRouter`. + * + * Reports errors to Sentry. + * + * @example (entry.client.tsx) + * ```tsx + * import { sentryOnError } from '@sentry/react-router'; + * + * startTransition(() => { + * hydrateRoot( + * document, + * + * ); + * }); + * ``` + */ +export function sentryOnError( + error: unknown, + { + errorInfo, + }: { + errorInfo?: React.ErrorInfo; + }, +): void { + const mechanism = { handled: false, type: 'auto.function.react_router.on_error' }; + + if (errorInfo) { + captureReactException(error, errorInfo, { mechanism }); + } else { + captureException(error, { mechanism }); + } +} diff --git a/packages/react-router/src/index.types.ts b/packages/react-router/src/index.types.ts index c9c5cb371763..e7fb4382d0f2 100644 --- a/packages/react-router/src/index.types.ts +++ b/packages/react-router/src/index.types.ts @@ -16,6 +16,8 @@ export declare function init(options: Options | clientSdk.BrowserOptions | serve export declare const contextLinesIntegration: typeof clientSdk.contextLinesIntegration; export declare const linkedErrorsIntegration: typeof clientSdk.linkedErrorsIntegration; +export declare const spanStreamingIntegration: typeof clientSdk.spanStreamingIntegration; +export declare const withStreamedSpan: typeof clientSdk.withStreamedSpan; export declare const defaultStackParser: StackParser; export declare const getDefaultIntegrations: (options: Options) => Integration[]; diff --git a/packages/react-router/test/client/sentryOnError.test.ts b/packages/react-router/test/client/sentryOnError.test.ts new file mode 100644 index 000000000000..33df01858288 --- /dev/null +++ b/packages/react-router/test/client/sentryOnError.test.ts @@ -0,0 +1,38 @@ +import * as SentryCore from '@sentry/core'; +import * as SentryReact from '@sentry/react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { sentryOnError } from '../../src/client/sentryOnError'; + +const captureReactExceptionSpy = vi.spyOn(SentryReact, 'captureReactException').mockReturnValue('mock-event-id'); +const captureExceptionSpy = vi.spyOn(SentryCore, 'captureException').mockReturnValue('mock-event-id'); + +describe('sentryOnError', () => { + afterEach(() => { + vi.clearAllMocks(); + }); + + it('calls captureReactException when errorInfo is provided', () => { + const error = new Error('test error'); + const errorInfo = { componentStack: '\n' }; + + sentryOnError(error, { + errorInfo, + }); + + expect(captureReactExceptionSpy).toHaveBeenCalledWith(error, errorInfo, { + mechanism: { handled: false, type: 'auto.function.react_router.on_error' }, + }); + expect(captureExceptionSpy).not.toHaveBeenCalled(); + }); + + it('calls captureException when errorInfo is undefined', () => { + const error = new Error('loader error'); + + sentryOnError(error, {}); + + expect(captureExceptionSpy).toHaveBeenCalledWith(error, { + mechanism: { handled: false, type: 'auto.function.react_router.on_error' }, + }); + expect(captureReactExceptionSpy).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/react/.oxlintrc.json b/packages/react/.oxlintrc.json index 9b4ad8ffaf10..ad747b8e6922 100644 --- a/packages/react/.oxlintrc.json +++ b/packages/react/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], "plugins": ["react"], "env": { "browser": true diff --git a/packages/remix/.oxlintrc.json b/packages/remix/.oxlintrc.json index a1ce14a978f3..5e5f2bb0ae99 100644 --- a/packages/remix/.oxlintrc.json +++ b/packages/remix/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], "env": { "browser": true, "node": true diff --git a/packages/remix/src/cloudflare/index.ts b/packages/remix/src/cloudflare/index.ts index ede127a694ce..97f2609bf10d 100644 --- a/packages/remix/src/cloudflare/index.ts +++ b/packages/remix/src/cloudflare/index.ts @@ -114,5 +114,6 @@ export { spanToTraceHeader, spanToBaggageHeader, updateSpanName, + withStreamedSpan, featureFlagsIntegration, } from '@sentry/core'; diff --git a/packages/remix/src/index.types.ts b/packages/remix/src/index.types.ts index 61d4f7e0b9bb..1a54068ae019 100644 --- a/packages/remix/src/index.types.ts +++ b/packages/remix/src/index.types.ts @@ -18,6 +18,8 @@ export declare function init(options: RemixOptions): Client | undefined; export declare const browserTracingIntegration: typeof clientSdk.browserTracingIntegration; export declare const linkedErrorsIntegration: typeof clientSdk.linkedErrorsIntegration; export declare const contextLinesIntegration: typeof clientSdk.contextLinesIntegration; +export declare const spanStreamingIntegration: typeof clientSdk.spanStreamingIntegration; +export declare const withStreamedSpan: typeof clientSdk.withStreamedSpan; export declare const getDefaultIntegrations: (options: Options) => Integration[]; export declare const defaultStackParser: StackParser; diff --git a/packages/remix/src/server/index.ts b/packages/remix/src/server/index.ts index cafec61ac9af..cc5f92bc2948 100644 --- a/packages/remix/src/server/index.ts +++ b/packages/remix/src/server/index.ts @@ -131,6 +131,8 @@ export { consoleLoggingIntegration, createConsolaReporter, createSentryWinstonTransport, + spanStreamingIntegration, + withStreamedSpan, } from '@sentry/node'; // Keeping the `*` exports for backwards compatibility and types diff --git a/packages/replay-canvas/.oxlintrc.json b/packages/replay-canvas/.oxlintrc.json index d38bbcf5c769..4cd4930fa802 100644 --- a/packages/replay-canvas/.oxlintrc.json +++ b/packages/replay-canvas/.oxlintrc.json @@ -1,4 +1,4 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"] + "extends": ["../../.oxlintrc.base.json"] } diff --git a/packages/replay-internal/.oxlintrc.json b/packages/replay-internal/.oxlintrc.json index c747c30f7d40..21ef9701c095 100644 --- a/packages/replay-internal/.oxlintrc.json +++ b/packages/replay-internal/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], "overrides": [ { "files": ["test.setup.ts", "vitest.config.ts"], diff --git a/packages/replay-worker/.oxlintrc.json b/packages/replay-worker/.oxlintrc.json index 32424a5a0979..280567c4e7fc 100644 --- a/packages/replay-worker/.oxlintrc.json +++ b/packages/replay-worker/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], "ignorePatterns": ["examples/worker.js"], "overrides": [ { diff --git a/packages/solid/.oxlintrc.json b/packages/solid/.oxlintrc.json index fa79cc1dcc7f..ed17064b99bc 100644 --- a/packages/solid/.oxlintrc.json +++ b/packages/solid/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], "env": { "browser": true } diff --git a/packages/solidstart/.oxlintrc.json b/packages/solidstart/.oxlintrc.json index 28d9e2d390f2..9623aa8dfd5a 100644 --- a/packages/solidstart/.oxlintrc.json +++ b/packages/solidstart/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], "env": { "browser": true, "node": true diff --git a/packages/solidstart/package.json b/packages/solidstart/package.json index 3a1fb4fedd5c..0c387baae74e 100644 --- a/packages/solidstart/package.json +++ b/packages/solidstart/package.json @@ -69,7 +69,7 @@ "@sentry/core": "10.47.0", "@sentry/node": "10.47.0", "@sentry/solid": "10.47.0", - "@sentry/vite-plugin": "^5.1.0" + "@sentry/vite-plugin": "^5.2.0" }, "devDependencies": { "@solidjs/router": "^0.15.0", diff --git a/packages/solidstart/src/index.types.ts b/packages/solidstart/src/index.types.ts index 4c5ff491c740..d984e1384a93 100644 --- a/packages/solidstart/src/index.types.ts +++ b/packages/solidstart/src/index.types.ts @@ -18,6 +18,8 @@ export declare function init(options: Options | clientSdk.BrowserOptions | serve export declare const linkedErrorsIntegration: typeof clientSdk.linkedErrorsIntegration; export declare const contextLinesIntegration: typeof clientSdk.contextLinesIntegration; +export declare const spanStreamingIntegration: typeof clientSdk.spanStreamingIntegration; +export declare const withStreamedSpan: typeof clientSdk.withStreamedSpan; export declare const getDefaultIntegrations: (options: Options) => Integration[]; export declare const defaultStackParser: StackParser; diff --git a/packages/solidstart/src/server/index.ts b/packages/solidstart/src/server/index.ts index 6e2bc1cb9f61..06c95b7bbc8b 100644 --- a/packages/solidstart/src/server/index.ts +++ b/packages/solidstart/src/server/index.ts @@ -130,6 +130,8 @@ export { consoleLoggingIntegration, createConsolaReporter, createSentryWinstonTransport, + spanStreamingIntegration, + withStreamedSpan, } from '@sentry/node'; // We can still leave this for the carrier init and type exports diff --git a/packages/svelte/.oxlintrc.json b/packages/svelte/.oxlintrc.json index fa79cc1dcc7f..ed17064b99bc 100644 --- a/packages/svelte/.oxlintrc.json +++ b/packages/svelte/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], "env": { "browser": true } diff --git a/packages/sveltekit/.oxlintrc.json b/packages/sveltekit/.oxlintrc.json index 28d9e2d390f2..9623aa8dfd5a 100644 --- a/packages/sveltekit/.oxlintrc.json +++ b/packages/sveltekit/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], "env": { "browser": true, "node": true diff --git a/packages/sveltekit/package.json b/packages/sveltekit/package.json index 25b3b1fae63f..d1a4290612ba 100644 --- a/packages/sveltekit/package.json +++ b/packages/sveltekit/package.json @@ -51,7 +51,7 @@ "@sentry/core": "10.47.0", "@sentry/node": "10.47.0", "@sentry/svelte": "10.47.0", - "@sentry/vite-plugin": "^5.1.0", + "@sentry/vite-plugin": "^5.2.0", "@sveltejs/acorn-typescript": "^1.0.9", "acorn": "^8.14.0", "magic-string": "~0.30.0", diff --git a/packages/sveltekit/src/index.types.ts b/packages/sveltekit/src/index.types.ts index d46e88e720ed..1f4bbae0b4a9 100644 --- a/packages/sveltekit/src/index.types.ts +++ b/packages/sveltekit/src/index.types.ts @@ -47,6 +47,8 @@ export declare function wrapLoadWithSentry any>(orig export declare const linkedErrorsIntegration: typeof clientSdk.linkedErrorsIntegration; export declare const contextLinesIntegration: typeof clientSdk.contextLinesIntegration; +export declare const spanStreamingIntegration: typeof clientSdk.spanStreamingIntegration; +export declare const withStreamedSpan: typeof clientSdk.withStreamedSpan; // Different implementation in server and worker export declare const vercelAIIntegration: typeof serverSdk.vercelAIIntegration; diff --git a/packages/sveltekit/src/server/index.ts b/packages/sveltekit/src/server/index.ts index d42975ef7876..4bd05d6f4657 100644 --- a/packages/sveltekit/src/server/index.ts +++ b/packages/sveltekit/src/server/index.ts @@ -135,6 +135,8 @@ export { createSentryWinstonTransport, vercelAIIntegration, metrics, + spanStreamingIntegration, + withStreamedSpan, } from '@sentry/node'; // We can still leave this for the carrier init and type exports diff --git a/packages/sveltekit/src/worker/index.ts b/packages/sveltekit/src/worker/index.ts index 8e4645741456..89beca6d718f 100644 --- a/packages/sveltekit/src/worker/index.ts +++ b/packages/sveltekit/src/worker/index.ts @@ -80,6 +80,7 @@ export { withIsolationScope, withMonitor, withScope, + withStreamedSpan, supabaseIntegration, instrumentSupabaseClient, zodErrorsIntegration, diff --git a/packages/tanstackstart-react/.oxlintrc.json b/packages/tanstackstart-react/.oxlintrc.json index 28d9e2d390f2..9623aa8dfd5a 100644 --- a/packages/tanstackstart-react/.oxlintrc.json +++ b/packages/tanstackstart-react/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], "env": { "browser": true, "node": true diff --git a/packages/tanstackstart-react/package.json b/packages/tanstackstart-react/package.json index efeeee17e3dd..3a0fe8ec8951 100644 --- a/packages/tanstackstart-react/package.json +++ b/packages/tanstackstart-react/package.json @@ -69,7 +69,7 @@ "@sentry/core": "10.47.0", "@sentry/node": "10.47.0", "@sentry/react": "10.47.0", - "@sentry/vite-plugin": "^5.1.0" + "@sentry/vite-plugin": "^5.2.0" }, "devDependencies": { "vite": "^5.4.11" diff --git a/packages/tanstackstart-react/src/index.types.ts b/packages/tanstackstart-react/src/index.types.ts index 7ab05bfc3831..76e4ced73c92 100644 --- a/packages/tanstackstart-react/src/index.types.ts +++ b/packages/tanstackstart-react/src/index.types.ts @@ -18,6 +18,8 @@ export declare function init(options: Options | clientSdk.BrowserOptions | serve export declare const linkedErrorsIntegration: typeof clientSdk.linkedErrorsIntegration; export declare const contextLinesIntegration: typeof clientSdk.contextLinesIntegration; +export declare const spanStreamingIntegration: typeof clientSdk.spanStreamingIntegration; +export declare const withStreamedSpan: typeof clientSdk.withStreamedSpan; export declare const getDefaultIntegrations: (options: Options) => Integration[]; export declare const defaultStackParser: StackParser; diff --git a/packages/tanstackstart/.oxlintrc.json b/packages/tanstackstart/.oxlintrc.json index 28d9e2d390f2..9623aa8dfd5a 100644 --- a/packages/tanstackstart/.oxlintrc.json +++ b/packages/tanstackstart/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], "env": { "browser": true, "node": true diff --git a/packages/types/.oxlintrc.json b/packages/types/.oxlintrc.json index 92a92888f2cb..ad51a29efc6d 100644 --- a/packages/types/.oxlintrc.json +++ b/packages/types/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], "env": { "node": false, "browser": false diff --git a/packages/vercel-edge/.oxlintrc.json b/packages/vercel-edge/.oxlintrc.json index 714725dd1b45..7828795e480e 100644 --- a/packages/vercel-edge/.oxlintrc.json +++ b/packages/vercel-edge/.oxlintrc.json @@ -1,6 +1,12 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], + "jsPlugins": [ + { + "name": "sdk", + "specifier": "@sentry-internal/eslint-plugin-sdk" + } + ], "env": { "node": true }, diff --git a/packages/vercel-edge/src/index.ts b/packages/vercel-edge/src/index.ts index 8ece38279732..c10ca12ebecb 100644 --- a/packages/vercel-edge/src/index.ts +++ b/packages/vercel-edge/src/index.ts @@ -98,9 +98,11 @@ export { consoleLoggingIntegration, createConsolaReporter, createLangChainCallbackHandler, + instrumentLangChainEmbeddings, featureFlagsIntegration, logger, metrics, + withStreamedSpan, } from '@sentry/core'; export { VercelEdgeClient } from './client'; diff --git a/packages/vue/.oxlintrc.json b/packages/vue/.oxlintrc.json index fa79cc1dcc7f..ed17064b99bc 100644 --- a/packages/vue/.oxlintrc.json +++ b/packages/vue/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"], + "extends": ["../../.oxlintrc.base.json"], "env": { "browser": true } diff --git a/packages/wasm/.oxlintrc.json b/packages/wasm/.oxlintrc.json index d38bbcf5c769..4cd4930fa802 100644 --- a/packages/wasm/.oxlintrc.json +++ b/packages/wasm/.oxlintrc.json @@ -1,4 +1,4 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.json"] + "extends": ["../../.oxlintrc.base.json"] } diff --git a/tsconfig-templates/README.md b/tsconfig-templates/README.md deleted file mode 100644 index f1b29fb1b3e9..000000000000 --- a/tsconfig-templates/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# `tsconfig` Templates - -Every package should get its own copy of the three files in this directory and the one in `test/` (which should go in an -analogous spot in the package). Package-specific options should go in `tsconfig.json` and test-specific options in -`tsconfig.test.json`. The `types` file shouldn't need to be modified, and only exists because tsconfigs don't support -multiple inheritance. The same goes for the file in `test/`, which only exists because VSCode only knows to look for a -file named (exactly) `tsconfig.json`. diff --git a/tsconfig-templates/tsconfig.json b/tsconfig-templates/tsconfig.json deleted file mode 100644 index bf45a09f2d71..000000000000 --- a/tsconfig-templates/tsconfig.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "extends": "../../tsconfig.json", - - "include": ["src/**/*"], - - "compilerOptions": { - // package-specific options - } -} diff --git a/tsconfig-templates/tsconfig.test.json b/tsconfig-templates/tsconfig.test.json deleted file mode 100644 index 1141567cdfec..000000000000 --- a/tsconfig-templates/tsconfig.test.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "extends": "./tsconfig.json", - - "include": ["test/**/*"], - - "compilerOptions": { - // should include all types from `./tsconfig.json` plus types for all test frameworks used - "types": [] - - // other package-specific, test-specific options - } -} diff --git a/tsconfig-templates/tsconfig.types.json b/tsconfig-templates/tsconfig.types.json deleted file mode 100644 index 65455f66bd75..000000000000 --- a/tsconfig-templates/tsconfig.types.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "extends": "./tsconfig.json", - - "compilerOptions": { - "declaration": true, - "declarationMap": true, - "emitDeclarationOnly": true, - "outDir": "build/types" - } -} diff --git a/yarn.lock b/yarn.lock index 9991a4549bca..112148abcbac 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4710,9 +4710,9 @@ "@hapi/validate" "^2.0.1" "@hapi/content@^6.0.0": - version "6.0.0" - resolved "https://registry.yarnpkg.com/@hapi/content/-/content-6.0.0.tgz#2427af3bac8a2f743512fce2a70cbdc365af29df" - integrity sha512-CEhs7j+H0iQffKfe5Htdak5LBOz/Qc8TRh51cF+BFv0qnuph3Em4pjGVzJMkI2gfTDdlJKWJISGWS1rK34POGA== + version "6.0.1" + resolved "https://registry.yarnpkg.com/@hapi/content/-/content-6.0.1.tgz#b0afe7523c9f754726852204dd2d32ec1578cb64" + integrity sha512-lQ2vOoFMNYxwKVnKf+3Pi3PfoviM4EJYlT9JbrBPfEc0xKMiVDqqXF8UTE1S1oKhHQliWSP5t6zTKNlmaXBGcQ== dependencies: "@hapi/boom" "^10.0.0" @@ -5295,6 +5295,15 @@ "@langchain/langgraph-sdk" "~1.0.0" uuid "^10.0.0" +"@langchain/openai@^0.5.0": + version "0.5.18" + resolved "https://registry.yarnpkg.com/@langchain/openai/-/openai-0.5.18.tgz#59ebbf48044d711ce9503d3b9854a3533cb54683" + integrity sha512-CX1kOTbT5xVFNdtLjnM0GIYNf+P7oMSu+dGCFxxWRa3dZwWiuyuBXCm+dToUGxDLnsHuV1bKBtIzrY1mLq/A1Q== + dependencies: + js-tiktoken "^1.0.12" + openai "^5.3.0" + zod "^3.25.32" + "@leichtgewicht/ip-codec@^2.0.1": version "2.0.4" resolved "https://registry.yarnpkg.com/@leichtgewicht/ip-codec/-/ip-codec-2.0.4.tgz#b2ac626d6cb9c8718ab459166d4bb405b8ffa78b" @@ -6276,15 +6285,6 @@ dependencies: "@opentelemetry/instrumentation" "^0.214.0" -"@opentelemetry/instrumentation-express@0.62.0": - version "0.62.0" - resolved "https://registry.yarnpkg.com/@opentelemetry/instrumentation-express/-/instrumentation-express-0.62.0.tgz#c03e353caf04b7074004ce899faf759dec210b8d" - integrity sha512-Tvx+vgAZKEQxU3Rx+xWLiR0mLxHwmk69/8ya04+VsV9WYh8w6Lhx5hm5yAMvo1wy0KqWgFKBLwSeo3sHCwdOww== - dependencies: - "@opentelemetry/core" "^2.0.0" - "@opentelemetry/instrumentation" "^0.214.0" - "@opentelemetry/semantic-conventions" "^1.27.0" - "@opentelemetry/instrumentation-fs@0.33.0": version "0.33.0" resolved "https://registry.yarnpkg.com/@opentelemetry/instrumentation-fs/-/instrumentation-fs-0.33.0.tgz#75f2ccf653b772801b398cc2ad0974e8785f2e3d" @@ -7818,36 +7818,18 @@ fflate "^0.4.4" mitt "^3.0.0" -"@sentry/babel-plugin-component-annotate@5.1.0": - version "5.1.0" - resolved "https://registry.yarnpkg.com/@sentry/babel-plugin-component-annotate/-/babel-plugin-component-annotate-5.1.0.tgz#59a9f203d07f4f17876c9a70ca6604ae28f4ebb0" - integrity sha512-deEZGTxPMiVNcHXzYMcKEp2uGGU3Q+055nVH6vPHnzuxGoRNZRe2YZ5B1yP9gFD+LJGku8dJ4y3bs1iJrLGPtQ== - -"@sentry/babel-plugin-component-annotate@5.1.1": - version "5.1.1" - resolved "https://registry.yarnpkg.com/@sentry/babel-plugin-component-annotate/-/babel-plugin-component-annotate-5.1.1.tgz#9eeef63099011155691a5ee59b0f796c141e8f85" - integrity sha512-x2wEpBHwsTyTF2rWsLKJlzrRF1TTIGOfX+ngdE+Yd5DBkoS58HwQv824QOviPGQRla4/ypISqAXzjdDPL/zalg== - -"@sentry/bundler-plugin-core@5.1.0": - version "5.1.0" - resolved "https://registry.yarnpkg.com/@sentry/bundler-plugin-core/-/bundler-plugin-core-5.1.0.tgz#01bef91543eb42cd370288573291b9a02b240e84" - integrity sha512-/GDzz+UbT7fO3AbvquHDWuqYXWKv2tzCQZddzMYNv36P9wpof5SFELGG6HnfqFb5l2PeHNrVTtp2rrPBQO/OXw== - dependencies: - "@babel/core" "^7.18.5" - "@sentry/babel-plugin-component-annotate" "5.1.0" - "@sentry/cli" "^2.58.5" - dotenv "^16.3.1" - find-up "^5.0.0" - glob "^13.0.6" - magic-string "0.30.8" +"@sentry/babel-plugin-component-annotate@5.2.0": + version "5.2.0" + resolved "https://registry.yarnpkg.com/@sentry/babel-plugin-component-annotate/-/babel-plugin-component-annotate-5.2.0.tgz#6d6f3c47d7f795f5dfbb9b59abef6ab33e5e7f2d" + integrity sha512-8LbOI5Kzb5F0+7LVQPi2+zGz1iPiRRFhM+7uZ/ZQ33L9BmDOYNIy3xWxCfMw2JCuMXXaxF47XCjGmR22/B0WPg== -"@sentry/bundler-plugin-core@5.1.1", "@sentry/bundler-plugin-core@^5.1.0": - version "5.1.1" - resolved "https://registry.yarnpkg.com/@sentry/bundler-plugin-core/-/bundler-plugin-core-5.1.1.tgz#d02cd1f70878936f22efb02765b01dcbf04d8483" - integrity sha512-F+itpwR9DyQR7gEkrXd2tigREPTvtF5lC8qu6e4anxXYRTui1+dVR0fXNwjpyAZMhIesLfXRN7WY7ggdj7hi0Q== +"@sentry/bundler-plugin-core@5.2.0", "@sentry/bundler-plugin-core@^5.2.0": + version "5.2.0" + resolved "https://registry.yarnpkg.com/@sentry/bundler-plugin-core/-/bundler-plugin-core-5.2.0.tgz#805ab7820b23d21ba5267e97db7300df35aede88" + integrity sha512-+C0x4gEIJRgoMwyRFGx+TFiJ1Po2BZlT1v61+PnouiaprKL5qtZG8n5PXx/5LPLDsVjSIcXjnDrTz9aSm8SJ3w== dependencies: "@babel/core" "^7.18.5" - "@sentry/babel-plugin-component-annotate" "5.1.1" + "@sentry/babel-plugin-component-annotate" "5.2.0" "@sentry/cli" "^2.58.5" dotenv "^16.3.1" find-up "^5.0.0" @@ -7914,37 +7896,28 @@ "@sentry/cli-win32-i686" "2.58.5" "@sentry/cli-win32-x64" "2.58.5" -"@sentry/rollup-plugin@5.1.0": - version "5.1.0" - resolved "https://registry.yarnpkg.com/@sentry/rollup-plugin/-/rollup-plugin-5.1.0.tgz#16109d796dc3ed49dfeda53c804792b9e4d0fd36" - integrity sha512-4U0rZVNM6/2CazVeb3ZlwPcl+R6W+5PbXvuTf3Wf+IRVU5BfpRs2cPgXgKVdorZLskG1Ot38PHk7H3f51qqUSg== - dependencies: - "@sentry/bundler-plugin-core" "5.1.0" - magic-string "0.30.8" - -"@sentry/rollup-plugin@^5.1.1": - version "5.1.1" - resolved "https://registry.yarnpkg.com/@sentry/rollup-plugin/-/rollup-plugin-5.1.1.tgz#0504fc89736fef515a7e52c03634f0aafb634118" - integrity sha512-1d5NkdRR6aKWBP7czkY8sFFWiKnfmfRpQOj+m9bJTsyTjbMiEQJst6315w5pCVlRItPhBqpAraqAhutZFgvyVg== +"@sentry/rollup-plugin@5.2.0", "@sentry/rollup-plugin@^5.2.0": + version "5.2.0" + resolved "https://registry.yarnpkg.com/@sentry/rollup-plugin/-/rollup-plugin-5.2.0.tgz#41601fa35fdcf9a43cff9807cdca012780d2fd5b" + integrity sha512-a8LfpvcYMFtFSroro5MpCcOoS528LeLfUHzxWURnpofOnY+Aso9Si4y4dFlna+RKqxCXjmFbn6CLnfI+YrHysQ== dependencies: - "@sentry/bundler-plugin-core" "5.1.1" + "@sentry/bundler-plugin-core" "5.2.0" magic-string "~0.30.8" -"@sentry/vite-plugin@^5.1.0": - version "5.1.0" - resolved "https://registry.yarnpkg.com/@sentry/vite-plugin/-/vite-plugin-5.1.0.tgz#217e9115ea643b6c92b846576f9eede6c8da2f55" - integrity sha512-J7tLUMGzYIKz2gCvG46vrgTE8VszPbqI7hGv7fr4rbLrU+OvetR6Du9qrgK4rniUK1g2niKK6wflNUreoAuEPQ== +"@sentry/vite-plugin@^5.2.0": + version "5.2.0" + resolved "https://registry.yarnpkg.com/@sentry/vite-plugin/-/vite-plugin-5.2.0.tgz#eca4c5eebe00696ded98e055f185faf846886f19" + integrity sha512-4Jo3ixBspso5HY81PDvZdRXkH9wYGVmcw/0a2IX9ejbyKBdHqkYg4IhAtNqGUAyGuHwwRS9Y1S+sCMvrXv6htw== dependencies: - "@sentry/bundler-plugin-core" "5.1.0" - "@sentry/rollup-plugin" "5.1.0" + "@sentry/bundler-plugin-core" "5.2.0" + "@sentry/rollup-plugin" "5.2.0" -"@sentry/webpack-plugin@^5.1.0": - version "5.1.0" - resolved "https://registry.yarnpkg.com/@sentry/webpack-plugin/-/webpack-plugin-5.1.0.tgz#cda8bd69efaed342180da6d6482ec188bf439e5a" - integrity sha512-GTLnr32ZIu6Gliy0z1J8N2S+WgWl5V1QeQj2BCpqA04hBOG1KK+dOX9z8yUKv2e5jvSQzpoyNNg3fBn08952cg== +"@sentry/webpack-plugin@^5.2.0": + version "5.2.0" + resolved "https://registry.yarnpkg.com/@sentry/webpack-plugin/-/webpack-plugin-5.2.0.tgz#6d190986198545c4b3046205f99ffcc601e8d936" + integrity sha512-ssV/uJK3ixf8UHBrNdLBXcnprUwppJNilbFv+19I81KTH4gVwzKXsVTMO91j6lyAXtk2mORwmEFwxZqScFfc7g== dependencies: - "@sentry/bundler-plugin-core" "5.1.0" - uuid "^9.0.0" + "@sentry/bundler-plugin-core" "5.2.0" "@shikijs/core@1.29.2": version "1.29.2" @@ -10958,9 +10931,9 @@ tslib "^2.6.3" "@xmldom/xmldom@^0.8.0": - version "0.8.3" - resolved "https://registry.yarnpkg.com/@xmldom/xmldom/-/xmldom-0.8.3.tgz#beaf980612532aa9a3004aff7e428943aeaa0711" - integrity sha512-Lv2vySXypg4nfa51LY1nU8yDAGo/5YwF+EY/rUZgIbfvwVARcd67ttCM8SMsTeJy51YhHYavEq+FS6R0hW9PFQ== + version "0.8.12" + resolved "https://registry.yarnpkg.com/@xmldom/xmldom/-/xmldom-0.8.12.tgz#cf488a5435fa06c7374ad1449c69cea0f823624b" + integrity sha512-9k/gHF6n/pAi/9tqr3m3aqkuiNosYTurLLUtc7xQ9sxB/wm7WPygCv8GYa6mS0fLJEHhqMC1ATYhz++U/lRHqg== "@xstate/fsm@^1.4.0": version "1.6.5" @@ -15181,10 +15154,10 @@ effect@3.16.12: "@standard-schema/spec" "^1.0.0" fast-check "^3.23.1" -effect@^3.20.0: - version "3.20.0" - resolved "https://registry.yarnpkg.com/effect/-/effect-3.20.0.tgz#827752d2c90f0a12562f1fdac3bf0197d067fd6a" - integrity sha512-qMLfDJscrNG8p/aw+IkT9W7fgj50Z4wG5bLBy0Txsxz8iUHjDIkOgO3SV0WZfnQbNG2VJYb0b+rDLMrhM4+Krw== +effect@^3.21.0: + version "3.21.0" + resolved "https://registry.yarnpkg.com/effect/-/effect-3.21.0.tgz#ce222ce8f785b9e63f104b9a4ead985e7965f2c0" + integrity sha512-PPN80qRokCd1f015IANNhrwOnLO7GrrMQfk4/lnZRE/8j7UPWrNNjPV0uBrZutI/nHzernbW+J0hdqQysHiSnQ== dependencies: "@standard-schema/spec" "^1.0.0" fast-check "^3.23.1" @@ -21168,9 +21141,9 @@ lodash.sortby@^4.7.0: integrity sha512-HDWXG8isMntAyRF5vZ7xKuEvOhT4AhlRt/3czTSjvGUxjYCBVRQY48ViDHyfYz9VIoBkW4TMGQNapx+l3RUwdA== lodash.template@^4.5.0: - version "4.5.0" - resolved "https://registry.yarnpkg.com/lodash.template/-/lodash.template-4.5.0.tgz#f976195cf3f347d0d5f52483569fe8031ccce8ab" - integrity sha512-84vYFxIkmidUiFxidA/KjjH9pAycqW+h980j7Fuz5qxRtO9pgB7MDFTdys1N7A5mcucRiDyEq4fusljItR1T/A== + version "4.18.1" + resolved "https://registry.yarnpkg.com/lodash.template/-/lodash.template-4.18.1.tgz#9968d00568070d03e358505b5a28b0cbd8fbfd5f" + integrity sha512-5urZrLnV/VD6zHK5KsVtZgt7H19v51mIzoS0aBNH8yp3I8tbswrEjOABOPY8m8uB7NuibubLrMX+Y0PXsU9X+w== dependencies: lodash._reinterpolate "^3.0.0" lodash.templatesettings "^4.0.0" @@ -21368,13 +21341,6 @@ magic-string@0.26.2: dependencies: sourcemap-codec "^1.4.8" -magic-string@0.30.8: - version "0.30.8" - resolved "https://registry.yarnpkg.com/magic-string/-/magic-string-0.30.8.tgz#14e8624246d2bedba70d5462aa99ac9681844613" - integrity sha512-ISQTe55T2ao7XtlAStud6qwYPZjE4GK1S/BeVPus4jrq6JuOnQ00YKQC581RWhR122W7msZV263KzVeLoqidyQ== - dependencies: - "@jridgewell/sourcemap-codec" "^1.4.15" - magic-string@^0.25.7: version "0.25.9" resolved "https://registry.yarnpkg.com/magic-string/-/magic-string-0.25.9.tgz#de7f9faf91ef8a1c91d02c2e5314c8277dbcdd1c" @@ -23802,6 +23768,11 @@ openai@5.18.1: resolved "https://registry.yarnpkg.com/openai/-/openai-5.18.1.tgz#1c4884aefcada7ec684771e03c860c381f1902c1" integrity sha512-iXSOfLlOL+jgnFr5CGrB2SEZw5C92o1nrFW2SasoAXj4QxGhfeJPgg8zkX+vaCfX80cT6CWjgaGnq7z9XzbyRw== +openai@^5.3.0: + version "5.23.2" + resolved "https://registry.yarnpkg.com/openai/-/openai-5.23.2.tgz#f13e2dc2ef6b88aab6a9b97cdc68d41a1d083c68" + integrity sha512-MQBzmTulj+MM5O8SKEk/gL8a7s5mktS9zUtAkU257WjvobGc9nKcBuVwjyEEcb9SI8a8Y2G/mzn3vm9n1Jlleg== + opener@^1.5.2: version "1.5.2" resolved "https://registry.yarnpkg.com/opener/-/opener-1.5.2.tgz#5d37e1f35077b9dcac4301372271afdeb2a13598" @@ -28586,6 +28557,7 @@ stylus@0.59.0, stylus@^0.59.0: sucrase@^3.27.0, sucrase@^3.35.0, sucrase@getsentry/sucrase#es2020-polyfills: version "3.36.0" + uid fd682f6129e507c00bb4e6319cc5d6b767e36061 resolved "https://codeload.github.com/getsentry/sucrase/tar.gz/fd682f6129e507c00bb4e6319cc5d6b767e36061" dependencies: "@jridgewell/gen-mapping" "^0.3.2"