@sentry/server-utils 11.14.0 → 11.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/cjs/chunks/exports.js +604 -219
- package/build/cjs/chunks/exports.js.map +1 -1
- package/build/cjs/index.js +1028 -120
- package/build/cjs/index.js.map +1 -1
- package/build/cjs/index.request-handler.js +1 -0
- package/build/cjs/index.request-handler.js.map +1 -1
- package/build/esm/ai/anthropic-ai/index.js +32 -56
- package/build/esm/ai/anthropic-ai/index.js.map +1 -1
- package/build/esm/ai/anthropic-ai/streaming.js +10 -6
- package/build/esm/ai/anthropic-ai/streaming.js.map +1 -1
- package/build/esm/ai/anthropic-ai/tool-runner.js +18 -3
- package/build/esm/ai/anthropic-ai/tool-runner.js.map +1 -1
- package/build/esm/ai/anthropic-ai/utils.js +41 -3
- package/build/esm/ai/anthropic-ai/utils.js.map +1 -1
- package/build/esm/ai/core/span-hooks.js +23 -0
- package/build/esm/ai/core/span-hooks.js.map +1 -0
- package/build/esm/ai/core/time-to-first-chunk.js +14 -0
- package/build/esm/ai/core/time-to-first-chunk.js.map +1 -0
- package/build/esm/ai/core/utils.js +29 -3
- package/build/esm/ai/core/utils.js.map +1 -1
- package/build/esm/ai/flue/index.js +15 -12
- package/build/esm/ai/flue/index.js.map +1 -1
- package/build/esm/ai/flue/utils.js +25 -17
- package/build/esm/ai/flue/utils.js.map +1 -1
- package/build/esm/ai/google-genai/decisions.js +29 -1
- package/build/esm/ai/google-genai/decisions.js.map +1 -1
- package/build/esm/ai/google-genai/index.js +21 -8
- package/build/esm/ai/google-genai/index.js.map +1 -1
- package/build/esm/ai/google-genai/streaming.js +6 -2
- package/build/esm/ai/google-genai/streaming.js.map +1 -1
- package/build/esm/ai/langchain/embeddings.js +5 -2
- package/build/esm/ai/langchain/embeddings.js.map +1 -1
- package/build/esm/ai/langchain/index.js +82 -24
- package/build/esm/ai/langchain/index.js.map +1 -1
- package/build/esm/ai/langchain/utils.js +9 -1
- package/build/esm/ai/langchain/utils.js.map +1 -1
- package/build/esm/ai/langgraph/agent-span.js +13 -5
- package/build/esm/ai/langgraph/agent-span.js.map +1 -1
- package/build/esm/ai/langgraph/index.js +13 -15
- package/build/esm/ai/langgraph/index.js.map +1 -1
- package/build/esm/ai/langgraph/stream.js +4 -3
- package/build/esm/ai/langgraph/stream.js.map +1 -1
- package/build/esm/ai/langgraph/utils.js +17 -8
- package/build/esm/ai/langgraph/utils.js.map +1 -1
- package/build/esm/ai/mastra/classifier-evaluation.js.map +1 -1
- package/build/esm/ai/mastra/index.js +33 -16
- package/build/esm/ai/mastra/index.js.map +1 -1
- package/build/esm/ai/mastra/utils.js +3 -5
- package/build/esm/ai/mastra/utils.js.map +1 -1
- package/build/esm/ai/mistral/index.js +21 -7
- package/build/esm/ai/mistral/index.js.map +1 -1
- package/build/esm/ai/mistral/streaming.js +4 -2
- package/build/esm/ai/mistral/streaming.js.map +1 -1
- package/build/esm/ai/openai/index.js +19 -8
- package/build/esm/ai/openai/index.js.map +1 -1
- package/build/esm/ai/openai/mapping.js +48 -1
- package/build/esm/ai/openai/mapping.js.map +1 -1
- package/build/esm/ai/openai/streaming.js +7 -2
- package/build/esm/ai/openai/streaming.js.map +1 -1
- package/build/esm/ai/pi-ai/chat.js +18 -1
- package/build/esm/ai/pi-ai/chat.js.map +1 -1
- package/build/esm/ai/pi-ai/recording.js +34 -15
- package/build/esm/ai/pi-ai/recording.js.map +1 -1
- package/build/esm/ai/pi-durable/index.js +7 -2
- package/build/esm/ai/pi-durable/index.js.map +1 -1
- package/build/esm/ai/pi-durable/runs.js.map +1 -1
- package/build/esm/ai/pi-durable/tools.js +18 -3
- package/build/esm/ai/pi-durable/tools.js.map +1 -1
- package/build/esm/ai/typesafe/index.js +14 -6
- package/build/esm/ai/typesafe/index.js.map +1 -1
- package/build/esm/ai/workers-ai/index.js +26 -9
- package/build/esm/ai/workers-ai/index.js.map +1 -1
- package/build/esm/ai/workers-ai/streaming.js +6 -4
- package/build/esm/ai/workers-ai/streaming.js.map +1 -1
- package/build/esm/cron/common.js +16 -0
- package/build/esm/cron/common.js.map +1 -0
- package/build/esm/cron/cron.js +82 -0
- package/build/esm/cron/cron.js.map +1 -0
- package/build/esm/cron/index.js +13 -0
- package/build/esm/cron/index.js.map +1 -0
- package/build/esm/cron/node-cron.js +66 -0
- package/build/esm/cron/node-cron.js.map +1 -0
- package/build/esm/cron/node-schedule.js +43 -0
- package/build/esm/cron/node-schedule.js.map +1 -0
- package/build/esm/index.js +6 -2
- package/build/esm/index.js.map +1 -1
- package/build/esm/integrations/anthropic.js +25 -16
- package/build/esm/integrations/anthropic.js.map +1 -1
- package/build/esm/integrations/aws-sdk/index.js +1 -0
- package/build/esm/integrations/aws-sdk/index.js.map +1 -1
- package/build/esm/integrations/aws-sdk/services/ServicesExtensions.js +3 -0
- package/build/esm/integrations/aws-sdk/services/ServicesExtensions.js.map +1 -1
- package/build/esm/integrations/aws-sdk/services/bedrock-runtime.js +45 -12
- package/build/esm/integrations/aws-sdk/services/bedrock-runtime.js.map +1 -1
- package/build/esm/integrations/bullmq/contextManager.js +45 -0
- package/build/esm/integrations/bullmq/contextManager.js.map +1 -0
- package/build/esm/integrations/bullmq/index.js +44 -0
- package/build/esm/integrations/bullmq/index.js.map +1 -0
- package/build/esm/integrations/bullmq/meter.js +86 -0
- package/build/esm/integrations/bullmq/meter.js.map +1 -0
- package/build/esm/integrations/bullmq/span.js +114 -0
- package/build/esm/integrations/bullmq/span.js.map +1 -0
- package/build/esm/integrations/bullmq/tracer.js +62 -0
- package/build/esm/integrations/bullmq/tracer.js.map +1 -0
- package/build/esm/integrations/express/instrumentation.js +10 -1
- package/build/esm/integrations/express/instrumentation.js.map +1 -1
- package/build/esm/integrations/google-genai.js +17 -9
- package/build/esm/integrations/google-genai.js.map +1 -1
- package/build/esm/integrations/langgraph.js +5 -7
- package/build/esm/integrations/langgraph.js.map +1 -1
- package/build/esm/integrations/mastra-classifier.js +1 -1
- package/build/esm/integrations/mastra-classifier.js.map +1 -1
- package/build/esm/integrations/mistral.js +13 -4
- package/build/esm/integrations/mistral.js.map +1 -1
- package/build/esm/integrations/openai-compatible.js +16 -8
- package/build/esm/integrations/openai-compatible.js.map +1 -1
- package/build/esm/integrations/openai.js +16 -8
- package/build/esm/integrations/openai.js.map +1 -1
- package/build/esm/integrations/pi-ai.js +39 -18
- package/build/esm/integrations/pi-ai.js.map +1 -1
- package/build/esm/integrations/pino.js +131 -0
- package/build/esm/integrations/pino.js.map +1 -0
- package/build/esm/integrations/typesafe.js +17 -3
- package/build/esm/integrations/typesafe.js.map +1 -1
- package/build/esm/integrations/vercel-ai/index.js.map +1 -1
- package/build/esm/integrations/vercel-ai/util.js +3 -2
- package/build/esm/integrations/vercel-ai/util.js.map +1 -1
- package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js +44 -17
- package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -1
- package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js +22 -16
- package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js.map +1 -1
- package/build/esm/integrations/winston.js +90 -0
- package/build/esm/integrations/winston.js.map +1 -0
- package/build/esm/orchestrion/detect.js +1 -1
- package/build/esm/orchestrion/detect.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/esm/utils/wrapServerRequestHandler.js +2 -1
- package/build/esm/utils/wrapServerRequestHandler.js.map +1 -1
- package/build/types/ai/anthropic-ai/index.d.ts +1 -5
- package/build/types/ai/anthropic-ai/index.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/streaming.d.ts +3 -2
- package/build/types/ai/anthropic-ai/streaming.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/tool-runner.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/types.d.ts +24 -3
- package/build/types/ai/anthropic-ai/types.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/utils.d.ts +2 -3
- package/build/types/ai/anthropic-ai/utils.d.ts.map +1 -1
- package/build/types/ai/core/span-hooks.d.ts +31 -0
- package/build/types/ai/core/span-hooks.d.ts.map +1 -0
- package/build/types/ai/core/time-to-first-chunk.d.ts +7 -0
- package/build/types/ai/core/time-to-first-chunk.d.ts.map +1 -0
- package/build/types/ai/core/utils.d.ts +30 -1
- package/build/types/ai/core/utils.d.ts.map +1 -1
- package/build/types/ai/flue/index.d.ts +13 -5
- package/build/types/ai/flue/index.d.ts.map +1 -1
- package/build/types/ai/flue/types.d.ts +20 -2
- package/build/types/ai/flue/types.d.ts.map +1 -1
- package/build/types/ai/flue/utils.d.ts +5 -9
- package/build/types/ai/flue/utils.d.ts.map +1 -1
- package/build/types/ai/google-genai/decisions.d.ts.map +1 -1
- package/build/types/ai/google-genai/index.d.ts.map +1 -1
- package/build/types/ai/google-genai/streaming.d.ts +2 -1
- package/build/types/ai/google-genai/streaming.d.ts.map +1 -1
- package/build/types/ai/google-genai/types.d.ts +17 -3
- package/build/types/ai/google-genai/types.d.ts.map +1 -1
- package/build/types/ai/langchain/index.d.ts.map +1 -1
- package/build/types/ai/langchain/types.d.ts +49 -3
- package/build/types/ai/langchain/types.d.ts.map +1 -1
- package/build/types/ai/langchain/utils.d.ts +6 -0
- package/build/types/ai/langchain/utils.d.ts.map +1 -1
- package/build/types/ai/langgraph/agent-span.d.ts +4 -1
- package/build/types/ai/langgraph/agent-span.d.ts.map +1 -1
- package/build/types/ai/langgraph/index.d.ts +1 -1
- package/build/types/ai/langgraph/index.d.ts.map +1 -1
- package/build/types/ai/langgraph/stream.d.ts.map +1 -1
- package/build/types/ai/langgraph/types.d.ts +14 -3
- package/build/types/ai/langgraph/types.d.ts.map +1 -1
- package/build/types/ai/langgraph/utils.d.ts +3 -0
- package/build/types/ai/langgraph/utils.d.ts.map +1 -1
- package/build/types/ai/mastra/classifier-evaluation.d.ts +3 -3
- package/build/types/ai/mastra/classifier-evaluation.d.ts.map +1 -1
- package/build/types/ai/mastra/index.d.ts +17 -3
- package/build/types/ai/mastra/index.d.ts.map +1 -1
- package/build/types/ai/mastra/types.d.ts +2 -0
- package/build/types/ai/mastra/types.d.ts.map +1 -1
- package/build/types/ai/mastra/utils.d.ts.map +1 -1
- package/build/types/ai/mistral/index.d.ts.map +1 -1
- package/build/types/ai/mistral/streaming.d.ts +2 -1
- package/build/types/ai/mistral/streaming.d.ts.map +1 -1
- package/build/types/ai/mistral/types.d.ts +14 -3
- package/build/types/ai/mistral/types.d.ts.map +1 -1
- package/build/types/ai/openai/index.d.ts.map +1 -1
- package/build/types/ai/openai/mapping.d.ts.map +1 -1
- package/build/types/ai/openai/streaming.d.ts +3 -1
- package/build/types/ai/openai/streaming.d.ts.map +1 -1
- package/build/types/ai/openai/types.d.ts +14 -3
- package/build/types/ai/openai/types.d.ts.map +1 -1
- package/build/types/ai/pi-ai/chat.d.ts +7 -1
- package/build/types/ai/pi-ai/chat.d.ts.map +1 -1
- package/build/types/ai/pi-ai/recording.d.ts +21 -9
- package/build/types/ai/pi-ai/recording.d.ts.map +1 -1
- package/build/types/ai/pi-ai/types.d.ts +16 -0
- package/build/types/ai/pi-ai/types.d.ts.map +1 -1
- package/build/types/ai/pi-durable/index.d.ts +12 -3
- package/build/types/ai/pi-durable/index.d.ts.map +1 -1
- package/build/types/ai/pi-durable/runs.d.ts +2 -0
- package/build/types/ai/pi-durable/runs.d.ts.map +1 -1
- package/build/types/ai/pi-durable/tools.d.ts +4 -3
- package/build/types/ai/pi-durable/tools.d.ts.map +1 -1
- package/build/types/ai/pi-durable/types.d.ts +15 -0
- package/build/types/ai/pi-durable/types.d.ts.map +1 -1
- package/build/types/ai/types.d.ts +1 -1
- package/build/types/ai/types.d.ts.map +1 -1
- package/build/types/ai/typesafe/index.d.ts +10 -2
- package/build/types/ai/typesafe/index.d.ts.map +1 -1
- package/build/types/ai/workers-ai/index.d.ts.map +1 -1
- package/build/types/ai/workers-ai/streaming.d.ts +2 -1
- package/build/types/ai/workers-ai/streaming.d.ts.map +1 -1
- package/build/types/ai/workers-ai/types.d.ts +18 -3
- package/build/types/ai/workers-ai/types.d.ts.map +1 -1
- package/build/types/cron/common.d.ts +8 -0
- package/build/types/cron/common.d.ts.map +1 -0
- package/build/types/cron/cron.d.ts +45 -0
- package/build/types/cron/cron.d.ts.map +1 -0
- package/build/types/cron/index.d.ts +10 -0
- package/build/types/cron/index.d.ts.map +1 -0
- package/build/types/cron/node-cron.d.ts +33 -0
- package/build/types/cron/node-cron.d.ts.map +1 -0
- package/build/types/cron/node-schedule.d.ts +19 -0
- package/build/types/cron/node-schedule.d.ts.map +1 -0
- package/build/types/index.d.ts +5 -2
- package/build/types/index.d.ts.map +1 -1
- package/build/types/integrations/anthropic.d.ts +2 -1
- package/build/types/integrations/anthropic.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/index.d.ts +3 -3
- package/build/types/integrations/aws-sdk/index.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/services/ServiceExtension.d.ts +1 -0
- package/build/types/integrations/aws-sdk/services/ServiceExtension.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/services/ServicesExtensions.d.ts +3 -2
- package/build/types/integrations/aws-sdk/services/ServicesExtensions.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/services/bedrock-runtime.d.ts +25 -4
- package/build/types/integrations/aws-sdk/services/bedrock-runtime.d.ts.map +1 -1
- package/build/types/integrations/bullmq/contextManager.d.ts +13 -0
- package/build/types/integrations/bullmq/contextManager.d.ts.map +1 -0
- package/build/types/integrations/bullmq/index.d.ts +43 -0
- package/build/types/integrations/bullmq/index.d.ts.map +1 -0
- package/build/types/integrations/bullmq/meter.d.ts +7 -0
- package/build/types/integrations/bullmq/meter.d.ts.map +1 -0
- package/build/types/integrations/bullmq/span.d.ts +35 -0
- package/build/types/integrations/bullmq/span.d.ts.map +1 -0
- package/build/types/integrations/bullmq/tracer.d.ts +5 -0
- package/build/types/integrations/bullmq/tracer.d.ts.map +1 -0
- package/build/types/integrations/bullmq/types.d.ts +72 -0
- package/build/types/integrations/bullmq/types.d.ts.map +1 -0
- package/build/types/integrations/express/types.d.ts +1 -0
- package/build/types/integrations/express/types.d.ts.map +1 -1
- package/build/types/integrations/flue.d.ts +2 -1
- package/build/types/integrations/flue.d.ts.map +1 -1
- package/build/types/integrations/google-genai.d.ts +2 -1
- package/build/types/integrations/google-genai.d.ts.map +1 -1
- package/build/types/integrations/groq.d.ts +1 -1
- package/build/types/integrations/langchain.d.ts +2 -1
- package/build/types/integrations/langchain.d.ts.map +1 -1
- package/build/types/integrations/langgraph.d.ts +2 -1
- package/build/types/integrations/langgraph.d.ts.map +1 -1
- package/build/types/integrations/mistral.d.ts +2 -1
- package/build/types/integrations/mistral.d.ts.map +1 -1
- package/build/types/integrations/openai-compatible.d.ts.map +1 -1
- package/build/types/integrations/openai.d.ts +2 -1
- package/build/types/integrations/openai.d.ts.map +1 -1
- package/build/types/integrations/pi-ai.d.ts +6 -3
- package/build/types/integrations/pi-ai.d.ts.map +1 -1
- package/build/types/integrations/pi-durable.d.ts +2 -1
- package/build/types/integrations/pi-durable.d.ts.map +1 -1
- package/build/types/integrations/pino.d.ts +61 -0
- package/build/types/integrations/pino.d.ts.map +1 -0
- package/build/types/integrations/together-ai.d.ts +1 -1
- package/build/types/integrations/typesafe.d.ts +2 -2
- package/build/types/integrations/typesafe.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/index.d.ts +3 -3
- package/build/types/integrations/vercel-ai/index.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/util.d.ts +2 -1
- package/build/types/integrations/vercel-ai/util.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts +20 -4
- package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.d.ts.map +1 -1
- package/build/types/integrations/winston.d.ts +55 -0
- package/build/types/integrations/winston.d.ts.map +1 -0
- package/build/types/utils/wrapServerRequestHandler.d.ts.map +1 -1
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/ai/typesafe/index.ts"],"sourcesContent":["import {\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_OUTPUT_MESSAGES,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_DECIDE } from '@sentry/conventions/op';\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport { isObjectLike, SPAN_STATUS_ERROR, startInactiveSpan, withActiveSpan } from '@sentry/core';\nimport type {
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/ai/typesafe/index.ts"],"sourcesContent":["import {\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_OUTPUT_MESSAGES,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_DECIDE } from '@sentry/conventions/op';\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport { isObjectLike, SPAN_STATUS_ERROR, startInactiveSpan, withActiveSpan } from '@sentry/core';\nimport type { GenAiSpanHooks } from '../core/span-hooks';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport type { GenAiCallOptions } from '../core/utils';\nimport { getEvaluationInputMessages, getEvaluationOutputMessages, resolveGenAiCallRecording } from '../core/utils';\nimport { TYPESAFE_ORIGIN, TYPESAFE_PROVIDER_NAME } from './constants';\n\n/** The call that `recordInputs`/`recordOutputs` decide on, and that the span hooks get. */\nexport interface TypeSafeCallInfo {\n /** The request, the first argument of `systemOne` as passed. */\n request: unknown;\n}\n\n/** Options for the TypeSafe integration. `onSpanEnd` gets the parsed `systemOne` result. */\nexport type TypeSafeOptions = GenAiCallOptions<TypeSafeCallInfo> & GenAiSpanHooks<TypeSafeCallInfo>;\n\n/**\n * Start the span for a `systemOne(request)` call. The request model falls back to the client's\n * `defaultModel`, the same way the SDK resolves it.\n */\nexport function startDecideSpan(\n request: unknown,\n client: unknown,\n recordInputs: boolean,\n attributes?: SpanAttributes,\n): Span {\n const params = isObjectLike(request) ? request : {};\n const defaultModel = isObjectLike(client) ? client.defaultModel : undefined;\n const model =\n typeof params.model === 'string' ? params.model : typeof defaultModel === 'string' ? defaultModel : undefined;\n\n return startInactiveSpan({\n name: model ? `decide ${model}` : 'decide',\n // oxlint-disable-next-line typescript/no-deprecated -- the rename to `gen_ai.decide` comes in a follow-up\n op: GEN_AI_DECIDE,\n // Extra attributes (e.g. another integration's origin) are set at start, so samplers see them.\n attributes: { ...getRequestAttributes(params, model, recordInputs), ...attributes },\n });\n}\n\nfunction getRequestAttributes(\n request: Record<string, unknown>,\n model: string | undefined,\n recordInputs: boolean,\n): SpanAttributes {\n return {\n [SENTRY_ORIGIN]: TYPESAFE_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'decide',\n [GEN_AI_PROVIDER_NAME]: TYPESAFE_PROVIDER_NAME,\n [GEN_AI_REQUEST_MODEL]: model,\n ...(recordInputs ? { [GEN_AI_INPUT_MESSAGES]: getEvaluationInputMessages(request) } : {}),\n };\n}\n\n/**\n * Add the response model, token usage and (optionally) the answers of a `systemOne` result.\n * Also used for TypeSafe models on Workers AI.\n */\nexport function addResponseAttributes(span: Span, result: unknown, recordOutputs: boolean): void {\n if (!isObjectLike(result)) {\n return;\n }\n\n if (typeof result.model === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, result.model);\n }\n\n const usage = isObjectLike(result.usage) ? result.usage : undefined;\n const inputTokens = typeof usage?.input_tokens === 'number' ? usage.input_tokens : undefined;\n const outputTokens = typeof usage?.output_tokens === 'number' ? usage.output_tokens : undefined;\n if (inputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, inputTokens);\n }\n if (outputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, outputTokens);\n }\n if (inputTokens !== undefined && outputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS, inputTokens + outputTokens);\n }\n\n if (recordOutputs && result.answers !== undefined) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, getEvaluationOutputMessages(result.answers));\n }\n}\n\n/**\n * `systemOne` returns a lazy `APIPromise` before the request settles, and parses the body on the first\n * `.then()`. Wait on `asResponse()` (the raw fetch, which does not parse the body) and read a clone of\n * the body, so the caller's own parse is unaffected. Call this before the caller can await the result,\n * so the clone is taken first. Returns `false` when `result` is not an `APIPromise`.\n */\nexport function onSystemOneResponse(\n result: unknown,\n onBody: (body: unknown) => void,\n onError: (error: unknown) => void,\n): boolean {\n if (!isObjectLike(result) || typeof result.asResponse !== 'function') {\n return false;\n }\n\n (result.asResponse() as Promise<Response>).then(\n response =>\n response\n .clone()\n .json()\n .then(\n body => onBody(body),\n () => onBody(undefined),\n ),\n error => onError(error),\n );\n\n return true;\n}\n\n/**\n * Instrument a TypeSafe client (`@typesafe-ai/sdk`) with Sentry tracing.\n */\nexport function instrumentTypeSafeClient<T extends object>(client: T, options?: TypeSafeOptions): T {\n return new Proxy(client, {\n get(target, prop) {\n // Read with the real client as receiver: the SDK keeps its API key in a private class field.\n const value: unknown = Reflect.get(target, prop, target);\n if (typeof value !== 'function') {\n return value;\n }\n if (prop === 'systemOne') {\n return (...args: unknown[]) =>\n instrumentSystemOne(value as (...args: unknown[]) => unknown, target, args, options ?? {});\n }\n return value.bind(target);\n },\n });\n}\n\nfunction instrumentSystemOne(\n systemOne: (...args: unknown[]) => unknown,\n client: object,\n args: unknown[],\n options: TypeSafeOptions,\n): unknown {\n const call: TypeSafeCallInfo = { request: args[0] };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);\n const span = startDecideSpan(args[0], client, recordInputs);\n runGenAiSpanStart(options, span, call);\n const endWithError = (error: unknown): void => {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n runGenAiSpanEnd(options, span, call, { error });\n span.end();\n };\n\n let result: unknown;\n try {\n result = withActiveSpan(span, () => systemOne.apply(client, args));\n } catch (error) {\n endWithError(error);\n throw error;\n }\n\n const waiting = onSystemOneResponse(\n result,\n body => {\n addResponseAttributes(span, body, recordOutputs);\n runGenAiSpanEnd(options, span, call, { response: body });\n span.end();\n },\n endWithError,\n );\n if (!waiting) {\n runGenAiSpanEnd(options, span, call, { response: result });\n span.end();\n }\n\n return result;\n}\n"],"mappings":";;;;;;;;;;;AAkCA,SAAgB,gBACd,SACA,QACA,cACA,YACM;CACN,MAAM,SAAS,aAAa,OAAO,IAAI,UAAU,CAAC;CAClD,MAAM,eAAe,aAAa,MAAM,IAAI,OAAO,eAAe,KAAA;CAClE,MAAM,QACJ,OAAO,OAAO,UAAU,WAAW,OAAO,QAAQ,OAAO,iBAAiB,WAAW,eAAe,KAAA;CAEtG,OAAO,kBAAkB;EACvB,MAAM,QAAQ,UAAU,UAAU;EAElC,IAAI;EAEJ,YAAY;GAAE,GAAG,qBAAqB,QAAQ,OAAO,YAAY;GAAG,GAAG;EAAW;CACpF,CAAC;AACH;AAEA,SAAS,qBACP,SACA,OACA,cACgB;CAChB,OAAO;GACJ,gBAAgB;GAChB,wBAAwB;GACxB,uBAAuB;GACvB,uBAAuB;EACxB,GAAI,eAAe,GAAG,wBAAwB,2BAA2B,OAAO,EAAE,IAAI,CAAC;CACzF;AACF;;;;;AAMA,SAAgB,sBAAsB,MAAY,QAAiB,eAA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,oBACP,WACA,QACA,MACA,SACS;CACT,MAAM,OAAyB,EAAE,SAAS,KAAK,GAAG;CAClD,MAAM,EAAE,cAAc,kBAAkB,0BAA0B,SAAS,IAAI;CAC/E,MAAM,OAAO,gBAAgB,KAAK,IAAI,QAAQ,YAAY;CAC1D,kBAAkB,SAAS,MAAM,IAAI;CACrC,MAAM,gBAAgB,UAAyB;EAC7C,KAAK,UAAU;GAAE,MAAM;GAAmB,SAAS;EAAiB,CAAC;EACrE,gBAAgB,SAAS,MAAM,MAAM,EAAE,MAAM,CAAC;EAC9C,KAAK,IAAI;CACX;CAEA,IAAI;CACJ,IAAI;EACF,SAAS,eAAe,YAAY,UAAU,MAAM,QAAQ,IAAI,CAAC;CACnE,SAAS,OAAO;EACd,aAAa,KAAK;EAClB,MAAM;CACR;CAWA,IAAI,CATY,oBACd,SACA,SAAQ;EACN,sBAAsB,MAAM,MAAM,aAAa;EAC/C,gBAAgB,SAAS,MAAM,MAAM,EAAE,UAAU,KAAK,CAAC;EACvD,KAAK,IAAI;CACX,GACA,YAES,GAAG;EACZ,gBAAgB,SAAS,MAAM,MAAM,EAAE,UAAU,OAAO,CAAC;EACzD,KAAK,IAAI;CACX;CAEA,OAAO;AACT"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { getErrorStatus, getRequestSignal, isReadableStream,
|
|
1
|
+
import { getErrorStatus, getRequestSignal, isReadableStream, resolveGenAiCallRecording } from "../core/utils.js";
|
|
2
|
+
import { runGenAiSpanEnd, runGenAiSpanStart } from "../core/span-hooks.js";
|
|
2
3
|
import { shouldSkipAiProviderSpan } from "../pi-ai/providers.js";
|
|
3
4
|
import "./constants.js";
|
|
4
5
|
import { instrumentWorkersAiStream } from "./streaming.js";
|
|
@@ -6,6 +7,7 @@ import { WORKERS_AI_OPERATION_SPAN_OPS, addRequestAttributes, addResponseAttribu
|
|
|
6
7
|
import { SENTRY_OP } from "@sentry/conventions/attributes";
|
|
7
8
|
import { getClient, hasSpanStreamingEnabled, startSpan, startSpanManual } from "@sentry/core";
|
|
8
9
|
// src/ai/workers-ai/index.ts
|
|
10
|
+
const originalClients = /* @__PURE__ */ new WeakMap();
|
|
9
11
|
/**
|
|
10
12
|
* Wrap the `run` method of the Workers AI binding with Sentry tracing.
|
|
11
13
|
*/
|
|
@@ -14,6 +16,13 @@ function instrumentRun(originalRun, context, options) {
|
|
|
14
16
|
if (shouldSkipAiProviderSpan("WorkersAI")) return originalRun.apply(context, args);
|
|
15
17
|
const [model, inputs, runOptions] = args;
|
|
16
18
|
const operationName = getOperationName(model, inputs);
|
|
19
|
+
const call = {
|
|
20
|
+
operation: operationName,
|
|
21
|
+
model,
|
|
22
|
+
inputs,
|
|
23
|
+
options: runOptions
|
|
24
|
+
};
|
|
25
|
+
const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);
|
|
17
26
|
const requestAttributes = extractRequestAttributes(model, inputs, operationName);
|
|
18
27
|
const modelName = typeof model === "string" && model ? model : "unknown";
|
|
19
28
|
const abortSignal = getRequestSignal(runOptions);
|
|
@@ -30,6 +39,7 @@ function instrumentRun(originalRun, context, options) {
|
|
|
30
39
|
if (isStreamRequested && !returnsRawResponse) return startSpanManual(spanConfig, (span) => {
|
|
31
40
|
const handleError = (error) => {
|
|
32
41
|
span.setStatus(getErrorStatus(abortSignal));
|
|
42
|
+
runGenAiSpanEnd(options, span, call, { error });
|
|
33
43
|
span.end();
|
|
34
44
|
throw error;
|
|
35
45
|
};
|
|
@@ -39,22 +49,27 @@ function instrumentRun(originalRun, context, options) {
|
|
|
39
49
|
} catch (error) {
|
|
40
50
|
return handleError(error);
|
|
41
51
|
}
|
|
42
|
-
if (
|
|
52
|
+
if (recordInputs) addRequestAttributes(span, inputs, operationName);
|
|
53
|
+
runGenAiSpanStart(options, span, call);
|
|
43
54
|
return originalResult.then((result) => {
|
|
44
|
-
if (isReadableStream(result)) return instrumentWorkersAiStream(result, span,
|
|
45
|
-
addResponseAttributes(span, result,
|
|
55
|
+
if (isReadableStream(result)) return instrumentWorkersAiStream(result, span, recordOutputs, abortSignal, (streamResult) => runGenAiSpanEnd(options, span, call, streamResult));
|
|
56
|
+
addResponseAttributes(span, result, recordOutputs, operationName);
|
|
57
|
+
runGenAiSpanEnd(options, span, call, { response: result });
|
|
46
58
|
span.end();
|
|
47
59
|
return result;
|
|
48
60
|
}, handleError);
|
|
49
61
|
});
|
|
50
62
|
return startSpan(spanConfig, (span) => {
|
|
51
63
|
const originalResult = originalRun.apply(context, args);
|
|
52
|
-
if (
|
|
64
|
+
if (recordInputs) addRequestAttributes(span, inputs, operationName);
|
|
65
|
+
runGenAiSpanStart(options, span, call);
|
|
53
66
|
return originalResult.then((result) => {
|
|
54
|
-
if (!returnsRawResponse) addResponseAttributes(span, result,
|
|
67
|
+
if (!returnsRawResponse) addResponseAttributes(span, result, recordOutputs, operationName);
|
|
68
|
+
runGenAiSpanEnd(options, span, call, { response: result });
|
|
55
69
|
return result;
|
|
56
70
|
}, (error) => {
|
|
57
71
|
span.setStatus(getErrorStatus(abortSignal));
|
|
72
|
+
runGenAiSpanEnd(options, span, call, { error });
|
|
58
73
|
throw error;
|
|
59
74
|
});
|
|
60
75
|
});
|
|
@@ -76,12 +91,14 @@ function instrumentRun(originalRun, context, options) {
|
|
|
76
91
|
* ```
|
|
77
92
|
*/
|
|
78
93
|
function instrumentWorkersAiClient(client, options) {
|
|
79
|
-
const
|
|
80
|
-
|
|
94
|
+
const original = originalClients.get(client) ?? client;
|
|
95
|
+
const instrumented = new Proxy(original, { get(target, prop, receiver) {
|
|
81
96
|
const value = Reflect.get(target, prop, receiver);
|
|
82
|
-
if (prop === "run" && typeof value === "function") return instrumentRun(value, target,
|
|
97
|
+
if (prop === "run" && typeof value === "function") return instrumentRun(value, target, options ?? {});
|
|
83
98
|
return typeof value === "function" ? value.bind(target) : value;
|
|
84
99
|
} });
|
|
100
|
+
originalClients.set(instrumented, original);
|
|
101
|
+
return instrumented;
|
|
85
102
|
}
|
|
86
103
|
export { instrumentWorkersAiClient };
|
|
87
104
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/ai/workers-ai/index.ts"],"sourcesContent":["import { SENTRY_OP } from '@sentry/conventions/attributes';\nimport { getClient, hasSpanStreamingEnabled, startSpan, startSpanManual } from '@sentry/core';\nimport type { Span } from '@sentry/core';\nimport { getErrorStatus, getRequestSignal, isReadableStream,
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/ai/workers-ai/index.ts"],"sourcesContent":["import { SENTRY_OP } from '@sentry/conventions/attributes';\nimport { getClient, hasSpanStreamingEnabled, startSpan, startSpanManual } from '@sentry/core';\nimport type { Span } from '@sentry/core';\nimport { getErrorStatus, getRequestSignal, isReadableStream, resolveGenAiCallRecording } from '../core/utils';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport { shouldSkipAiProviderSpan } from '../pi-ai/providers';\nimport { WORKERS_AI_INTEGRATION_NAME } from './constants';\nimport { instrumentWorkersAiStream } from './streaming';\nimport type { WorkersAiCallInfo, WorkersAiOptions } from './types';\nimport {\n addRequestAttributes,\n addResponseAttributes,\n extractRequestAttributes,\n getOperationName,\n WORKERS_AI_OPERATION_SPAN_OPS,\n} from './utils';\n\nconst originalClients = new WeakMap<object, object>();\n\n/**\n * Wrap the `run` method of the Workers AI binding with Sentry tracing.\n */\nfunction instrumentRun(\n originalRun: (...args: unknown[]) => Promise<unknown>,\n context: unknown,\n options: WorkersAiOptions,\n): (...args: unknown[]) => Promise<unknown> {\n return function instrumentedRun(...args: unknown[]): Promise<unknown> {\n if (shouldSkipAiProviderSpan(WORKERS_AI_INTEGRATION_NAME)) {\n return originalRun.apply(context, args);\n }\n\n const [model, inputs, runOptions] = args as [unknown, unknown, Record<string, unknown> | undefined];\n\n const operationName = getOperationName(model, inputs);\n const call: WorkersAiCallInfo = { operation: operationName, model, inputs, options: runOptions };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);\n const requestAttributes = extractRequestAttributes(model, inputs, operationName);\n const modelName = typeof model === 'string' && model ? model : 'unknown';\n const abortSignal = getRequestSignal(runOptions);\n const client = getClient();\n\n const isStreamRequested =\n !!inputs && typeof inputs === 'object' && (inputs as { stream?: unknown }).stream === true;\n const returnsRawResponse =\n !!runOptions &&\n typeof runOptions === 'object' &&\n (runOptions.returnRawResponse === true || runOptions.websocket === true);\n\n const spanConfig = {\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name:\n modelName !== 'unknown' || !(client && hasSpanStreamingEnabled(client))\n ? `${operationName} ${modelName}`\n : operationName,\n attributes: {\n [SENTRY_OP]: WORKERS_AI_OPERATION_SPAN_OPS[operationName],\n ...requestAttributes,\n },\n };\n\n if (isStreamRequested && !returnsRawResponse) {\n return startSpanManual(spanConfig, (span: Span) => {\n // `startSpanManual` does not auto-end the span, so we must end it on every exit path,\n // including a synchronous throw from `run`.\n const handleError = (error: unknown): never => {\n span.setStatus(getErrorStatus(abortSignal));\n runGenAiSpanEnd(options, span, call, { error });\n span.end();\n throw error;\n };\n\n let originalResult: Promise<unknown>;\n\n try {\n originalResult = originalRun.apply(context, args) as Promise<unknown>;\n } catch (error) {\n return handleError(error);\n }\n\n if (recordInputs) {\n addRequestAttributes(span, inputs, operationName);\n }\n runGenAiSpanStart(options, span, call);\n\n return originalResult.then(result => {\n if (isReadableStream<Uint8Array>(result)) {\n return instrumentWorkersAiStream(result, span, recordOutputs, abortSignal, streamResult =>\n runGenAiSpanEnd(options, span, call, streamResult),\n );\n }\n\n // The model did not actually return a stream — finalize the span eagerly.\n addResponseAttributes(span, result, recordOutputs, operationName);\n runGenAiSpanEnd(options, span, call, { response: result });\n span.end();\n return result;\n }, handleError);\n });\n }\n\n return startSpan(spanConfig, (span: Span) => {\n const originalResult = originalRun.apply(context, args) as Promise<unknown>;\n\n if (recordInputs) {\n addRequestAttributes(span, inputs, operationName);\n }\n runGenAiSpanStart(options, span, call);\n\n return originalResult.then(\n result => {\n if (!returnsRawResponse) {\n addResponseAttributes(span, result, recordOutputs, operationName);\n }\n runGenAiSpanEnd(options, span, call, { response: result });\n return result;\n },\n error => {\n span.setStatus(getErrorStatus(abortSignal));\n runGenAiSpanEnd(options, span, call, { error });\n throw error;\n },\n );\n });\n };\n}\n\n/**\n * Instrument a Cloudflare Workers AI binding (`env.AI`) with Sentry tracing.\n *\n * This wraps the binding's `run` method to create `gen_ai` spans following the\n * Sentry AI Agents conventions. All other methods are passed through untouched.\n *\n * In `@sentry/cloudflare`, the `env.AI` binding is instrumented automatically —\n * wrapping manually is only needed to pass custom options.\n *\n * @example\n * ```javascript\n * const ai = Sentry.instrumentWorkersAiClient(env.AI, { recordInputs: true, recordOutputs: true });\n * const result = await ai.run('@cf/meta/llama-3.1-8b-instruct', { prompt: 'Hello' });\n * ```\n */\nexport function instrumentWorkersAiClient<T extends object>(client: T, options?: WorkersAiOptions): T {\n // `@sentry/cloudflare` already wraps `env.AI`. Wrapping that proxy again would nest a second span\n // that ignores these options, so wrap the original binding instead.\n const original = (originalClients.get(client) ?? client) as T;\n\n const instrumented = new Proxy(original, {\n get(target: object, prop: string | symbol, receiver: unknown): unknown {\n const value = Reflect.get(target, prop, receiver);\n\n if (prop === 'run' && typeof value === 'function') {\n return instrumentRun(value as (...args: unknown[]) => Promise<unknown>, target, options ?? {});\n }\n\n // Bind passed-through functions to the original target to preserve `this` (e.g. private fields).\n return typeof value === 'function' ? (value as (...args: unknown[]) => unknown).bind(target) : value;\n },\n }) as T;\n\n originalClients.set(instrumented, original);\n return instrumented;\n}\n"],"mappings":";;;;;;;;;AAiBA,MAAM,kCAAkB,IAAI,QAAwB;;;;AAKpD,SAAS,cACP,aACA,SACA,SAC0C;CAC1C,OAAO,SAAS,gBAAgB,GAAG,MAAmC;EACpE,IAAI,yBAAA,WAAoD,GACtD,OAAO,YAAY,MAAM,SAAS,IAAI;EAGxC,MAAM,CAAC,OAAO,QAAQ,cAAc;EAEpC,MAAM,gBA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AE,UAAU,OAAO,CAAC;IACzD,KAAK,IAAI;IACT,OAAO;GACT,GAAG,WAAW;EAChB,CAAC;EAGH,OAAO,UAAU,aAAa,SAAe;GAC3C,MAAM,iBAAiB,YAAY,MAAM,SAAS,IAAI;GAEtD,IAAI,cACF,qBAAqB,MAAM,QAAQ,aAAa;GAElD,kBAAkB,SAAS,MAAM,IAAI;GAErC,OAAO,eAAe,MACpB,WAAU;IACR,IAAI,CAAC,oBACH,sBAAsB,MAAM,QAAQ,eAAe,aAAa;IAElE,gBAAgB,SAAS,MAAM,MAAM,EAAE,UAAU,OAAO,CAAC;IACzD,OAAO;GACT,IACA,UAAS;IACP,KAAK,UAAU,eAAe,WAAW,CAAC;IAC1C,gBAAgB,SAAS,MAAM,MAAM,EAAE,MAAM,CAAC;IAC9C,MAAM;GACR,CACF;EACF,CAAC;CACH;AACF;;;;;;;;;;;;;;;;AAiBA,SAAgB,0BAA4C,QAAW,SAA+B;CAGpG,MAAM,WAAY,gBAAgB,IAAI,MAAM,KAAK;CAEjD,MAAM,eAAe,IAAI,MAAM,UAAU,EACvC,IAAI,QAAgB,MAAuB,UAA4B;EACrE,MAAM,QAAQ,QAAQ,IAAI,QAAQ,MAAM,QAAQ;EAEhD,IAAI,SAAS,SAAS,OAAO,UAAU,YACrC,OAAO,cAAc,OAAmD,QAAQ,WAAW,CAAC,CAAC;EAI/F,OAAO,OAAO,UAAU,aAAc,MAA0C,KAAK,MAAM,IAAI;CACjG,EACF,CAAC;CAED,gBAAgB,IAAI,cAAc,QAAQ;CAC1C,OAAO;AACT"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { getToolCallKey } from "../core/streaming-tool-calls.js";
|
|
2
2
|
import { endStreamSpan, getErrorStatus, setOutputMessagesAttribute } from "../core/utils.js";
|
|
3
|
+
import { recordTimeToFirstChunk } from "../core/time-to-first-chunk.js";
|
|
3
4
|
import "./utils.js";
|
|
4
5
|
// src/ai/workers-ai/streaming.ts
|
|
5
6
|
/**
|
|
@@ -70,7 +71,7 @@ function processLine(line, state, recordOutputs, toolCallAccumulator) {
|
|
|
70
71
|
*
|
|
71
72
|
* The span is ended once the consumer finishes reading (or cancels) the stream.
|
|
72
73
|
*/
|
|
73
|
-
function instrumentWorkersAiStream(stream, span, recordOutputs, abortSignal) {
|
|
74
|
+
function instrumentWorkersAiStream(stream, span, recordOutputs, abortSignal, beforeSpanEnd) {
|
|
74
75
|
const reader = stream.getReader();
|
|
75
76
|
const decoder = new TextDecoder();
|
|
76
77
|
const state = {
|
|
@@ -89,7 +90,7 @@ function instrumentWorkersAiStream(stream, span, recordOutputs, abortSignal) {
|
|
|
89
90
|
};
|
|
90
91
|
let buffer = "";
|
|
91
92
|
let spanEnded = false;
|
|
92
|
-
const finish = () => {
|
|
93
|
+
const finish = (result = {}) => {
|
|
93
94
|
if (spanEnded) return;
|
|
94
95
|
spanEnded = true;
|
|
95
96
|
if (recordOutputs) {
|
|
@@ -101,7 +102,7 @@ function instrumentWorkersAiStream(stream, span, recordOutputs, abortSignal) {
|
|
|
101
102
|
finishReason: state.finishReasons[0]
|
|
102
103
|
});
|
|
103
104
|
}
|
|
104
|
-
endStreamSpan(span, state, recordOutputs);
|
|
105
|
+
endStreamSpan(span, state, recordOutputs, () => beforeSpanEnd?.(result));
|
|
105
106
|
};
|
|
106
107
|
const flushBuffer = (isDone) => {
|
|
107
108
|
const lines = buffer.split("\n");
|
|
@@ -119,12 +120,13 @@ function instrumentWorkersAiStream(stream, span, recordOutputs, abortSignal) {
|
|
|
119
120
|
controller.close();
|
|
120
121
|
return;
|
|
121
122
|
}
|
|
123
|
+
recordTimeToFirstChunk(span);
|
|
122
124
|
buffer += decoder.decode(value, { stream: true });
|
|
123
125
|
flushBuffer(false);
|
|
124
126
|
controller.enqueue(value);
|
|
125
127
|
} catch (error) {
|
|
126
128
|
span.setStatus(getErrorStatus(abortSignal));
|
|
127
|
-
finish();
|
|
129
|
+
finish({ error });
|
|
128
130
|
controller.error(error);
|
|
129
131
|
}
|
|
130
132
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"streaming.js","names":[],"sources":["../../../../src/ai/workers-ai/streaming.ts"],"sourcesContent":["import type { Span } from '@sentry/core';\nimport { getToolCallKey } from '../core/streaming-tool-calls';\nimport { endStreamSpan, getErrorStatus, type StreamResponseState } from '../core/utils';\nimport type { WorkersAiUsage } from './types';\nimport { setOutputMessagesAttribute } from './utils';\n\ninterface WorkersAiStreamingToolCall {\n index?: number | null;\n id?: string;\n type?: string;\n function?: { name?: string; arguments?: string };\n // Some Workers AI models stream tool calls with the name/arguments at the top\n // level of the tool-call object instead of nested under `function`.\n name?: string;\n arguments?: string;\n}\n\ninterface WorkersAiStreamChunk {\n // Native Workers AI streaming shape (`env.AI.run` with `stream: true`).\n response?: unknown;\n tool_calls?: unknown[];\n // OpenAI-compatible streaming shape emitted for models routed through the\n // OpenAI-compatible endpoint (e.g. via `workers-ai-provider`).\n id?: unknown;\n model?: unknown;\n choices?: Array<{\n delta?: { content?: unknown; tool_calls?: WorkersAiStreamingToolCall[] };\n finish_reason?: unknown;\n }>;\n usage?: WorkersAiUsage & { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number };\n}\n\n/**\n * Tool calls accumulated from a stream, keyed in the order they were opened (so output order is arrival order).\n */\ninterface ToolCallAccumulator {\n calls: Map<string, WorkersAiStreamingToolCall>;\n /** Key of the latest call, which argument fragments with neither `index`, `id` nor name continue. */\n lastKey?: string;\n /** Key of the call currently open for a reported `index`, when a new `id` reused that index. */\n keyByIndex: Map<number, string>;\n}\n\n/**\n * Accumulate a fragmented OpenAI-compatible tool call (delivered across multiple\n * `choices[].delta.tool_calls` chunks) into the accumulator.\n */\nfunction accumulateStreamingToolCalls(toolCalls: WorkersAiStreamingToolCall[], accumulator: ToolCallAccumulator): void {\n for (const toolCall of toolCalls) {\n // Normalize both shapes: name/arguments nested under `function`, or at the top level.\n const name = toolCall.function?.name ?? toolCall.name;\n const args = toolCall.function?.arguments ?? toolCall.arguments;\n\n // A tool call must carry at least a name or argument fragment to be meaningful.\n if (name == null && args == null) {\n continue;\n }\n\n const key = getToolCallKey(toolCall, name, accumulator);\n const existing = accumulator.calls.get(key);\n\n if (!existing) {\n accumulator.calls.set(key, {\n index: toolCall.index,\n id: toolCall.id,\n type: toolCall.type,\n function: {\n name,\n arguments: args ?? '',\n },\n });\n } else if (existing.function) {\n if (name && !existing.function.name) {\n existing.function.name = name;\n }\n if (args) {\n existing.function.arguments = `${existing.function.arguments ?? ''}${args}`;\n }\n }\n accumulator.lastKey = key;\n }\n}\n\n/**\n * Parse a single SSE line (`data: {...}`) and accumulate its data into the streaming state.\n *\n * Handles both the native Workers AI shape (top-level `response`/`tool_calls`) and the\n * OpenAI-compatible shape (`choices[].delta.content`/`choices[].delta.tool_calls`), because\n * the same `run()` call transparently yields either format depending on the model.\n */\nfunction processLine(\n line: string,\n state: StreamResponseState,\n recordOutputs: boolean,\n toolCallAccumulator: ToolCallAccumulator,\n): void {\n const trimmed = line.trim();\n if (!trimmed.startsWith('data:')) {\n return;\n }\n\n const data = trimmed.slice('data:'.length).trim();\n if (!data || data === '[DONE]') {\n return;\n }\n\n let parsed: WorkersAiStreamChunk;\n try {\n parsed = JSON.parse(data) as WorkersAiStreamChunk;\n } catch {\n return;\n }\n\n if (parsed.usage) {\n if (typeof parsed.usage.prompt_tokens === 'number') {\n state.promptTokens = parsed.usage.prompt_tokens;\n }\n if (typeof parsed.usage.completion_tokens === 'number') {\n state.completionTokens = parsed.usage.completion_tokens;\n }\n if (typeof parsed.usage.total_tokens === 'number') {\n state.totalTokens = parsed.usage.total_tokens;\n }\n }\n\n if (recordOutputs && typeof parsed.response === 'string') {\n state.responseTexts.push(parsed.response);\n }\n\n if (recordOutputs && Array.isArray(parsed.tool_calls) && parsed.tool_calls.length > 0) {\n state.toolCalls.push(...parsed.tool_calls);\n }\n\n if (Array.isArray(parsed.choices)) {\n if (typeof parsed.id === 'string') {\n state.responseId = parsed.id;\n }\n if (typeof parsed.model === 'string') {\n state.responseModel = parsed.model;\n }\n\n for (const choice of parsed.choices) {\n if (recordOutputs && typeof choice.delta?.content === 'string' && choice.delta.content) {\n state.responseTexts.push(choice.delta.content);\n }\n if (recordOutputs && Array.isArray(choice.delta?.tool_calls)) {\n accumulateStreamingToolCalls(choice.delta.tool_calls, toolCallAccumulator);\n }\n if (typeof choice.finish_reason === 'string') {\n state.finishReasons.push(choice.finish_reason);\n }\n }\n }\n}\n\n/**\n * Wrap a Workers AI streaming response (a server-sent-events `ReadableStream`) so we can\n * accumulate the response text and token usage while passing the original bytes through untouched.\n *\n * The span is ended once the consumer finishes reading (or cancels) the stream.\n */\nexport function instrumentWorkersAiStream(\n stream: ReadableStream<Uint8Array>,\n span: Span,\n recordOutputs: boolean,\n abortSignal?: AbortSignal,\n): ReadableStream<Uint8Array> {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n\n const state: StreamResponseState = {\n responseId: '',\n responseModel: '',\n finishReasons: [],\n responseTexts: [],\n toolCalls: [],\n promptTokens: undefined,\n completionTokens: undefined,\n totalTokens: undefined,\n };\n\n // OpenAI-compatible tool calls arrive fragmented across chunks and are keyed by index;\n // accumulate them here and flatten into `state.toolCalls` once the stream ends.\n const toolCallAccumulator: ToolCallAccumulator = { calls: new Map(), keyByIndex: new Map() };\n\n let buffer = '';\n let spanEnded = false;\n\n const finish = (): void => {\n if (spanEnded) {\n return;\n }\n spanEnded = true;\n\n if (recordOutputs) {\n const accumulatedToolCalls = [...toolCallAccumulator.calls.values()];\n if (accumulatedToolCalls.length > 0) {\n state.toolCalls.push(...accumulatedToolCalls);\n }\n\n // Set the authoritative `gen_ai.output.messages` alongside the deprecated response\n // attributes `endStreamSpan` writes, so tool calls survive Relay's lossy migration.\n setOutputMessagesAttribute(span, {\n responseText: state.responseTexts.join(''),\n toolCalls: state.toolCalls,\n finishReason: state.finishReasons[0],\n });\n }\n\n endStreamSpan(span, state, recordOutputs);\n };\n\n const flushBuffer = (isDone: boolean): void => {\n const lines = buffer.split('\\n');\n // Keep the last (potentially incomplete) line in the buffer unless the stream is done.\n buffer = isDone ? '' : (lines.pop() ?? '');\n for (const line of lines) {\n processLine(line, state, recordOutputs, toolCallAccumulator);\n }\n };\n\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n\n if (done) {\n buffer += decoder.decode();\n flushBuffer(true);\n finish();\n controller.close();\n return;\n }\n\n buffer += decoder.decode(value, { stream: true });\n flushBuffer(false);\n controller.enqueue(value);\n } catch (error) {\n span.setStatus(getErrorStatus(abortSignal));\n finish();\n controller.error(error);\n }\n },\n async cancel(reason) {\n finish();\n await reader.cancel(reason);\n },\n });\n}\n"],"mappings":";;;;;;;;AA+CA,SAAS,6BAA6B,WAAyC,aAAwC;CACrH,KAAK,MAAM,YAAY,WAAW;EAEhC,MAAM,OAAO,SAAS,UAAU,QAAQ,SAAS;EACjD,MAAM,OAAO,SAAS,UAAU,aAAa,SAAS;EAGtD,IAAI,QAAQ,QAAQ,QAAQ,MAC1B;EAGF,MAAM,MAAM,eAAe,UAAU,MAAM,WAAW;EACtD,MAAM,WAAW,YAAY,MAAM,IAAI,GAAG;EAE1C,IAAI,CAAC,UACH,YAAY,MAAM,IAAI,KAAK;GACzB,OAAO,SAAS;GAChB,IAAI,SAAS;GACb,MAAM,SAAS;GACf,UAAU;IACR;IACA,WAAW,QAAQ;GACrB;EACF,CAAC;OACI,IAAI,SAAS,UAAU;GAC5B,IAAI,QAAQ,CAAC,SAAS,SAAS,MAC7B,SAAS,SAAS,OAAO;GAE3B,IAAI,MACF,SAAS,SAAS,YAAY,GAAG,SAAS,SAAS,aAAa,KAAK;EAEzE;EACA,YAAY,UAAU;CACxB;AACF;;;;;;;;AASA,SAAS,YACP,MACA,OACA,eACA,qBACM;CACN,MAAM,UAAU,KAAK,KAAK;CAC1B,IAAI,CAAC,QAAQ,WAAW,OAAO,GAC7B;CAGF,MAAM,OAAO,QAAQ,MAAM,CAAc,CAA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3,"file":"streaming.js","names":[],"sources":["../../../../src/ai/workers-ai/streaming.ts"],"sourcesContent":["import type { Span } from '@sentry/core';\nimport type { GenAiSpanResult } from '../core/span-hooks';\nimport { getToolCallKey } from '../core/streaming-tool-calls';\nimport { endStreamSpan, getErrorStatus, type StreamResponseState } from '../core/utils';\nimport { recordTimeToFirstChunk } from '../core/time-to-first-chunk';\nimport type { WorkersAiUsage } from './types';\nimport { setOutputMessagesAttribute } from './utils';\n\ninterface WorkersAiStreamingToolCall {\n index?: number | null;\n id?: string;\n type?: string;\n function?: { name?: string; arguments?: string };\n // Some Workers AI models stream tool calls with the name/arguments at the top\n // level of the tool-call object instead of nested under `function`.\n name?: string;\n arguments?: string;\n}\n\ninterface WorkersAiStreamChunk {\n // Native Workers AI streaming shape (`env.AI.run` with `stream: true`).\n response?: unknown;\n tool_calls?: unknown[];\n // OpenAI-compatible streaming shape emitted for models routed through the\n // OpenAI-compatible endpoint (e.g. via `workers-ai-provider`).\n id?: unknown;\n model?: unknown;\n choices?: Array<{\n delta?: { content?: unknown; tool_calls?: WorkersAiStreamingToolCall[] };\n finish_reason?: unknown;\n }>;\n usage?: WorkersAiUsage & { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number };\n}\n\n/**\n * Tool calls accumulated from a stream, keyed in the order they were opened (so output order is arrival order).\n */\ninterface ToolCallAccumulator {\n calls: Map<string, WorkersAiStreamingToolCall>;\n /** Key of the latest call, which argument fragments with neither `index`, `id` nor name continue. */\n lastKey?: string;\n /** Key of the call currently open for a reported `index`, when a new `id` reused that index. */\n keyByIndex: Map<number, string>;\n}\n\n/**\n * Accumulate a fragmented OpenAI-compatible tool call (delivered across multiple\n * `choices[].delta.tool_calls` chunks) into the accumulator.\n */\nfunction accumulateStreamingToolCalls(toolCalls: WorkersAiStreamingToolCall[], accumulator: ToolCallAccumulator): void {\n for (const toolCall of toolCalls) {\n // Normalize both shapes: name/arguments nested under `function`, or at the top level.\n const name = toolCall.function?.name ?? toolCall.name;\n const args = toolCall.function?.arguments ?? toolCall.arguments;\n\n // A tool call must carry at least a name or argument fragment to be meaningful.\n if (name == null && args == null) {\n continue;\n }\n\n const key = getToolCallKey(toolCall, name, accumulator);\n const existing = accumulator.calls.get(key);\n\n if (!existing) {\n accumulator.calls.set(key, {\n index: toolCall.index,\n id: toolCall.id,\n type: toolCall.type,\n function: {\n name,\n arguments: args ?? '',\n },\n });\n } else if (existing.function) {\n if (name && !existing.function.name) {\n existing.function.name = name;\n }\n if (args) {\n existing.function.arguments = `${existing.function.arguments ?? ''}${args}`;\n }\n }\n accumulator.lastKey = key;\n }\n}\n\n/**\n * Parse a single SSE line (`data: {...}`) and accumulate its data into the streaming state.\n *\n * Handles both the native Workers AI shape (top-level `response`/`tool_calls`) and the\n * OpenAI-compatible shape (`choices[].delta.content`/`choices[].delta.tool_calls`), because\n * the same `run()` call transparently yields either format depending on the model.\n */\nfunction processLine(\n line: string,\n state: StreamResponseState,\n recordOutputs: boolean,\n toolCallAccumulator: ToolCallAccumulator,\n): void {\n const trimmed = line.trim();\n if (!trimmed.startsWith('data:')) {\n return;\n }\n\n const data = trimmed.slice('data:'.length).trim();\n if (!data || data === '[DONE]') {\n return;\n }\n\n let parsed: WorkersAiStreamChunk;\n try {\n parsed = JSON.parse(data) as WorkersAiStreamChunk;\n } catch {\n return;\n }\n\n if (parsed.usage) {\n if (typeof parsed.usage.prompt_tokens === 'number') {\n state.promptTokens = parsed.usage.prompt_tokens;\n }\n if (typeof parsed.usage.completion_tokens === 'number') {\n state.completionTokens = parsed.usage.completion_tokens;\n }\n if (typeof parsed.usage.total_tokens === 'number') {\n state.totalTokens = parsed.usage.total_tokens;\n }\n }\n\n if (recordOutputs && typeof parsed.response === 'string') {\n state.responseTexts.push(parsed.response);\n }\n\n if (recordOutputs && Array.isArray(parsed.tool_calls) && parsed.tool_calls.length > 0) {\n state.toolCalls.push(...parsed.tool_calls);\n }\n\n if (Array.isArray(parsed.choices)) {\n if (typeof parsed.id === 'string') {\n state.responseId = parsed.id;\n }\n if (typeof parsed.model === 'string') {\n state.responseModel = parsed.model;\n }\n\n for (const choice of parsed.choices) {\n if (recordOutputs && typeof choice.delta?.content === 'string' && choice.delta.content) {\n state.responseTexts.push(choice.delta.content);\n }\n if (recordOutputs && Array.isArray(choice.delta?.tool_calls)) {\n accumulateStreamingToolCalls(choice.delta.tool_calls, toolCallAccumulator);\n }\n if (typeof choice.finish_reason === 'string') {\n state.finishReasons.push(choice.finish_reason);\n }\n }\n }\n}\n\n/**\n * Wrap a Workers AI streaming response (a server-sent-events `ReadableStream`) so we can\n * accumulate the response text and token usage while passing the original bytes through untouched.\n *\n * The span is ended once the consumer finishes reading (or cancels) the stream.\n */\nexport function instrumentWorkersAiStream(\n stream: ReadableStream<Uint8Array>,\n span: Span,\n recordOutputs: boolean,\n abortSignal?: AbortSignal,\n beforeSpanEnd?: (result: GenAiSpanResult<never>) => void,\n): ReadableStream<Uint8Array> {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n\n const state: StreamResponseState = {\n responseId: '',\n responseModel: '',\n finishReasons: [],\n responseTexts: [],\n toolCalls: [],\n promptTokens: undefined,\n completionTokens: undefined,\n totalTokens: undefined,\n };\n\n // OpenAI-compatible tool calls arrive fragmented across chunks and are keyed by index;\n // accumulate them here and flatten into `state.toolCalls` once the stream ends.\n const toolCallAccumulator: ToolCallAccumulator = { calls: new Map(), keyByIndex: new Map() };\n\n let buffer = '';\n let spanEnded = false;\n\n const finish = (result: GenAiSpanResult<never> = {}): void => {\n if (spanEnded) {\n return;\n }\n spanEnded = true;\n\n if (recordOutputs) {\n const accumulatedToolCalls = [...toolCallAccumulator.calls.values()];\n if (accumulatedToolCalls.length > 0) {\n state.toolCalls.push(...accumulatedToolCalls);\n }\n\n // Set the authoritative `gen_ai.output.messages` alongside the deprecated response\n // attributes `endStreamSpan` writes, so tool calls survive Relay's lossy migration.\n setOutputMessagesAttribute(span, {\n responseText: state.responseTexts.join(''),\n toolCalls: state.toolCalls,\n finishReason: state.finishReasons[0],\n });\n }\n\n endStreamSpan(span, state, recordOutputs, () => beforeSpanEnd?.(result));\n };\n\n const flushBuffer = (isDone: boolean): void => {\n const lines = buffer.split('\\n');\n // Keep the last (potentially incomplete) line in the buffer unless the stream is done.\n buffer = isDone ? '' : (lines.pop() ?? '');\n for (const line of lines) {\n processLine(line, state, recordOutputs, toolCallAccumulator);\n }\n };\n\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n\n if (done) {\n buffer += decoder.decode();\n flushBuffer(true);\n finish();\n controller.close();\n return;\n }\n\n recordTimeToFirstChunk(span);\n buffer += decoder.decode(value, { stream: true });\n flushBuffer(false);\n controller.enqueue(value);\n } catch (error) {\n span.setStatus(getErrorStatus(abortSignal));\n finish({ error });\n controller.error(error);\n }\n },\n async cancel(reason) {\n finish();\n await reader.cancel(reason);\n },\n });\n}\n"],"mappings":";;;;;;;;;AAiDA,SAAS,6BAA6B,WAAyC,aAAwC;CACrH,KAAK,MAAM,YAAY,WAAW;EAEhC,MAAM,OAAO,SAAS,UAAU,QAAQ,SAAS;EACjD,MAAM,OAAO,SAAS,UAAU,aAAa,SAAS;EAGtD,IAAI,QAAQ,QAAQ,QAAQ,MAC1B;EAGF,MAAM,MAAM,eAAe,UAAU,MAAM,WAAW;EACtD,MAAM,WAAW,YAAY,MAAM,IAAI,GAAG;EAE1C,IAAI,CAAC,UACH,YAAY,MAAM,IAAI,KAAK;GACzB,OAAO,SAAS;GAChB,IAAI,SAAS;GACb,MAAM,SAAS;GACf,UAAU;IACR;IACA,WAAW,QAAQ;GACrB;EACF,CAAC;OACI,IAAI,SAAS,UAAU;GAC5B,IAAI,QAAQ,CAAC,SAAS,SAAS,MAC7B,SAAS,SAAS,OAAO;GAE3B,IAAI,MACF,SAAS,SAAS,YAAY,GAAG,SAAS,SAAS,aAAa,KAAK;EAEzE;EACA,YAAY,UAAU;CACxB;AACF;;;;;;;;AASA,SAAS,YACP,MACA,OACA,eACA,qBAC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,KAAK,UAAU,eAAe,WAAW,CAAC;IAC1C,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,MAAM,KAAK;GACxB;EACF;EACA,MAAM,OAAO,QAAQ;GACnB,OAAO;GACP,MAAM,OAAO,OAAO,MAAM;EAC5B;CACF,CAAC;AACH"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { DEBUG_BUILD } from "../debug-build.js";
|
|
2
|
+
import { cronExpressionToMonitorConfig } from "../utils/cronMonitoring.js";
|
|
3
|
+
import { debug } from "@sentry/core";
|
|
4
|
+
// src/cron/common.ts
|
|
5
|
+
/**
|
|
6
|
+
* The monitor config for a cron expression, or `undefined` if Sentry would read the expression differently than the
|
|
7
|
+
* scheduler runs it.
|
|
8
|
+
*/
|
|
9
|
+
function getCronMonitorConfig(expression, timezone, dialect, isReadAlike = () => true) {
|
|
10
|
+
const monitorConfig = isReadAlike(expression) ? cronExpressionToMonitorConfig(expression, timezone, dialect) : void 0;
|
|
11
|
+
if (!monitorConfig) DEBUG_BUILD && debug.warn(`[Cron] Can't convert "${expression}" to a Sentry schedule, sending check-ins without a monitor config.`);
|
|
12
|
+
return monitorConfig;
|
|
13
|
+
}
|
|
14
|
+
export { getCronMonitorConfig };
|
|
15
|
+
|
|
16
|
+
//# sourceMappingURL=common.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"common.js","names":[],"sources":["../../../src/cron/common.ts"],"sourcesContent":["import type { MonitorConfig } from '@sentry/core';\nimport { debug } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { CronDialect } from '../utils/cronMonitoring';\nimport { cronExpressionToMonitorConfig } from '../utils/cronMonitoring';\n\n/**\n * The monitor config for a cron expression, or `undefined` if Sentry would read the expression differently than the\n * scheduler runs it.\n */\nexport function getCronMonitorConfig(\n expression: string,\n timezone: unknown,\n dialect: CronDialect,\n isReadAlike: (expression: string) => boolean = () => true,\n): MonitorConfig | undefined {\n const monitorConfig = isReadAlike(expression)\n ? cronExpressionToMonitorConfig(expression, timezone, dialect)\n : undefined;\n if (!monitorConfig) {\n DEBUG_BUILD &&\n debug.warn(\n `[Cron] Can't convert \"${expression}\" to a Sentry schedule, sending check-ins without a monitor config.`,\n );\n }\n return monitorConfig;\n}\n"],"mappings":";;;;;;;;AAUA,SAAgB,qBACd,YACA,UACA,SACA,oBAAqD,MAC1B;CAC3B,MAAM,gBAAgB,YAAY,UAAU,IACxC,8BAA8B,YAAY,UAAU,OAAO,IAC3D,KAAA;CACJ,IAAI,CAAC,eACH,eACE,MAAM,KACJ,yBAAyB,WAAW,oEACtC;CAEJ,OAAO;AACT"}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { getCronMonitorConfig } from "./common.js";
|
|
2
|
+
import { addNonEnumerableProperty, captureException, withMonitor } from "@sentry/core";
|
|
3
|
+
// src/cron/cron.ts
|
|
4
|
+
const MONITORED = Symbol.for("sentry.cron.monitored");
|
|
5
|
+
const ERROR_TEXT = "Automatic instrumentation of CronJob only supports crontab string";
|
|
6
|
+
/**
|
|
7
|
+
* Instruments the `cron` library to send a check-in event to Sentry for each job execution.
|
|
8
|
+
*
|
|
9
|
+
* ```ts
|
|
10
|
+
* import * as Sentry from '@sentry/node';
|
|
11
|
+
* import { CronJob } from 'cron';
|
|
12
|
+
*
|
|
13
|
+
* const CronJobWithCheckIn = Sentry.cron.instrumentCron(CronJob, 'my-cron-job');
|
|
14
|
+
*
|
|
15
|
+
* // use the constructor
|
|
16
|
+
* const job = new CronJobWithCheckIn('* * * * *', () => {
|
|
17
|
+
* console.log('You will see this message every minute');
|
|
18
|
+
* });
|
|
19
|
+
*
|
|
20
|
+
* // or from
|
|
21
|
+
* const job = CronJobWithCheckIn.from({ cronTime: '* * * * *', onTick: () => {
|
|
22
|
+
* console.log('You will see this message every minute');
|
|
23
|
+
* });
|
|
24
|
+
* ```
|
|
25
|
+
*
|
|
26
|
+
* @deprecated Use `cronJobIntegration` instead.
|
|
27
|
+
*/
|
|
28
|
+
function instrumentCron(lib, monitorSlug) {
|
|
29
|
+
let jobScheduled = false;
|
|
30
|
+
return new Proxy(lib, {
|
|
31
|
+
construct(target, args) {
|
|
32
|
+
const [cronTime, onTick, onComplete, start, timeZone, ...rest] = args;
|
|
33
|
+
if (typeof cronTime !== "string") throw new Error(ERROR_TEXT);
|
|
34
|
+
if (jobScheduled) throw new Error(`A job named '${monitorSlug}' has already been scheduled`);
|
|
35
|
+
jobScheduled = true;
|
|
36
|
+
const monitorConfig = args[7] == null ? getCronMonitorConfig(cronTime, timeZone, "cron") : void 0;
|
|
37
|
+
async function monitoredTick(context, onComplete) {
|
|
38
|
+
return withMonitor(monitorSlug, async () => {
|
|
39
|
+
try {
|
|
40
|
+
await onTick(context, onComplete);
|
|
41
|
+
} catch (e) {
|
|
42
|
+
captureException(e, { mechanism: {
|
|
43
|
+
handled: false,
|
|
44
|
+
type: "auto.function.cron.instrumentCron"
|
|
45
|
+
} });
|
|
46
|
+
throw e;
|
|
47
|
+
}
|
|
48
|
+
}, monitorConfig);
|
|
49
|
+
}
|
|
50
|
+
addNonEnumerableProperty(monitoredTick, MONITORED, true);
|
|
51
|
+
return new target(cronTime, monitoredTick, onComplete, start, timeZone, ...rest);
|
|
52
|
+
},
|
|
53
|
+
get(target, prop) {
|
|
54
|
+
if (prop === "from") return (param) => {
|
|
55
|
+
const { cronTime, onTick, timeZone, utcOffset } = param;
|
|
56
|
+
if (typeof cronTime !== "string") throw new Error(ERROR_TEXT);
|
|
57
|
+
if (jobScheduled) throw new Error(`A job named '${monitorSlug}' has already been scheduled`);
|
|
58
|
+
jobScheduled = true;
|
|
59
|
+
const monitorConfig = utcOffset == null ? getCronMonitorConfig(cronTime, timeZone, "cron") : void 0;
|
|
60
|
+
param.onTick = async (context, onComplete) => {
|
|
61
|
+
return withMonitor(monitorSlug, async () => {
|
|
62
|
+
try {
|
|
63
|
+
await onTick(context, onComplete);
|
|
64
|
+
} catch (e) {
|
|
65
|
+
captureException(e, { mechanism: {
|
|
66
|
+
handled: false,
|
|
67
|
+
type: "auto.function.cron.instrumentCron"
|
|
68
|
+
} });
|
|
69
|
+
throw e;
|
|
70
|
+
}
|
|
71
|
+
}, monitorConfig);
|
|
72
|
+
};
|
|
73
|
+
addNonEnumerableProperty(param.onTick, MONITORED, true);
|
|
74
|
+
return target.from(param);
|
|
75
|
+
};
|
|
76
|
+
else return target[prop];
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
export { instrumentCron };
|
|
81
|
+
|
|
82
|
+
//# sourceMappingURL=cron.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cron.js","names":[],"sources":["../../../src/cron/cron.ts"],"sourcesContent":["import { addNonEnumerableProperty, captureException, withMonitor } from '@sentry/core';\nimport { getCronMonitorConfig } from './common';\n\nexport type CronJobParams = {\n cronTime: string | Date;\n onTick: (context: unknown, onComplete?: unknown) => void | Promise<void>;\n onComplete?: () => void | Promise<void>;\n start?: boolean | null;\n context?: unknown;\n runOnInit?: boolean | null;\n unrefTimeout?: boolean | null;\n} & (\n | {\n timeZone?: string | null;\n utcOffset?: never;\n }\n | {\n timeZone?: never;\n utcOffset?: number | null;\n }\n);\n\nexport type CronJob = {\n //\n};\n\nexport type CronJobConstructor = {\n from: (param: CronJobParams) => CronJob;\n\n new (\n cronTime: CronJobParams['cronTime'],\n onTick: CronJobParams['onTick'],\n onComplete?: CronJobParams['onComplete'],\n start?: CronJobParams['start'],\n timeZone?: CronJobParams['timeZone'],\n context?: CronJobParams['context'],\n runOnInit?: CronJobParams['runOnInit'],\n utcOffset?: null,\n unrefTimeout?: CronJobParams['unrefTimeout'],\n ): CronJob;\n new (\n cronTime: CronJobParams['cronTime'],\n onTick: CronJobParams['onTick'],\n onComplete?: CronJobParams['onComplete'],\n start?: CronJobParams['start'],\n timeZone?: null,\n context?: CronJobParams['context'],\n runOnInit?: CronJobParams['runOnInit'],\n utcOffset?: CronJobParams['utcOffset'],\n unrefTimeout?: CronJobParams['unrefTimeout'],\n ): CronJob;\n};\n\nconst MONITORED = Symbol.for('sentry.cron.monitored');\n\nconst ERROR_TEXT = 'Automatic instrumentation of CronJob only supports crontab string';\n\n/**\n * Instruments the `cron` library to send a check-in event to Sentry for each job execution.\n *\n * ```ts\n * import * as Sentry from '@sentry/node';\n * import { CronJob } from 'cron';\n *\n * const CronJobWithCheckIn = Sentry.cron.instrumentCron(CronJob, 'my-cron-job');\n *\n * // use the constructor\n * const job = new CronJobWithCheckIn('* * * * *', () => {\n * console.log('You will see this message every minute');\n * });\n *\n * // or from\n * const job = CronJobWithCheckIn.from({ cronTime: '* * * * *', onTick: () => {\n * console.log('You will see this message every minute');\n * });\n * ```\n *\n * @deprecated Use `cronJobIntegration` instead.\n */\nexport function instrumentCron<T>(lib: T & CronJobConstructor, monitorSlug: string): T {\n let jobScheduled = false;\n\n return new Proxy(lib, {\n construct(target, args: ConstructorParameters<CronJobConstructor>) {\n const [cronTime, onTick, onComplete, start, timeZone, ...rest] = args;\n\n if (typeof cronTime !== 'string') {\n throw new Error(ERROR_TEXT);\n }\n\n if (jobScheduled) {\n throw new Error(`A job named '${monitorSlug}' has already been scheduled`);\n }\n\n jobScheduled = true;\n\n const utcOffset = args[7];\n const monitorConfig = utcOffset == null ? getCronMonitorConfig(cronTime, timeZone, 'cron') : undefined;\n\n async function monitoredTick(context: unknown, onComplete?: unknown): Promise<void> {\n return withMonitor(\n monitorSlug,\n async () => {\n try {\n await onTick(context, onComplete);\n } catch (e) {\n captureException(e, {\n mechanism: {\n handled: false,\n type: 'auto.function.cron.instrumentCron',\n },\n });\n throw e;\n }\n },\n monitorConfig,\n );\n }\n\n // Tells `cronJobIntegration` that this job is already monitored.\n addNonEnumerableProperty(monitoredTick, MONITORED, true);\n\n return new target(cronTime, monitoredTick, onComplete, start, timeZone, ...rest);\n },\n get(target, prop: keyof CronJobConstructor) {\n if (prop === 'from') {\n return (param: CronJobParams) => {\n const { cronTime, onTick, timeZone, utcOffset } = param;\n\n if (typeof cronTime !== 'string') {\n throw new Error(ERROR_TEXT);\n }\n\n if (jobScheduled) {\n throw new Error(`A job named '${monitorSlug}' has already been scheduled`);\n }\n\n jobScheduled = true;\n\n const monitorConfig = utcOffset == null ? getCronMonitorConfig(cronTime, timeZone, 'cron') : undefined;\n\n param.onTick = async (context: unknown, onComplete?: unknown) => {\n return withMonitor(\n monitorSlug,\n async () => {\n try {\n await onTick(context, onComplete);\n } catch (e) {\n captureException(e, {\n mechanism: {\n handled: false,\n type: 'auto.function.cron.instrumentCron',\n },\n });\n throw e;\n }\n },\n monitorConfig,\n );\n };\n\n addNonEnumerableProperty(param.onTick, MONITORED, true);\n\n return target.from(param);\n };\n } else {\n return target[prop];\n }\n },\n });\n}\n"],"mappings":";;;AAqDA,MAAM,YAAY,OAAO,IAAI,uBAAuB;AAEpD,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;AAwBnB,SAAgB,eAAkB,KAA6B,aAAwB;CACrF,IAAI,eAAe;CAEnB,OAAO,IAAI,MAAM,KAAK;EACpB,UAAU,QAAQ,MAAiD;GACjE,MAAM,CAAC,UAAU,QAAQ,YAAY,OAAO,UAAU,GAAG,QAAQ;GAEjE,IAAI,OAAO,aAAa,UACtB,MAAM,IAAI,MAAM,UAAU;GAG5B,IAAI,cACF,MAAM,IAAI,MAAM,gBAAgB,YAAY,6BAA6B;GAG3E,eAAe;GAGf,MAAM,gBADY,KAAK,MACY,OAAO,qBAAqB,UAAU,UAAU,MAAM,IAAI,KAAA;GAE7F,eAAe,cAAc,SAAkB,YAAqC;IAClF,OAAO,YACL,aACA,YAAY;KACV,IAAI;MACF,MAAM,OAAO,SAAS,UAAU;KAClC,SAAS,GAAG;MACV,iBAAiB,GAAG,EAClB,WAAW;OACT,SAAS;OACT,MAAM;MACR,EACF,CAAC;MACD,MAAM;KACR;IACF,GACA,aACF;GACF;GAGA,yBAAyB,eAAe,WAAW,IAAI;GAEvD,OAAO,IAAI,OAAO,UAAU,eAAe,YAAY,OAAO,UAAU,GAAG,IAAI;EACjF;EACA,IAAI,QAAQ,MAAgC;GAC1C,IAAI,SAAS,QACX,QAAQ,UAAyB;IAC/B,MAAM,EAAE,UAAU,QAAQ,UAAU,cAAc;IAElD,IAAI,OAAO,aAAa,UACtB,MAAM,IAAI,MAAM,UAAU;IAG5B,IAAI,cACF,MAAM,IAAI,MAAM,gBAAgB,YAAY,6BAA6B;IAG3E,eAAe;IAEf,MAAM,gBAAgB,aAAa,OAAO,qBAAqB,UAAU,UAAU,MAAM,IAAI,KAAA;IAE7F,MAAM,SAAS,OAAO,SAAkB,eAAyB;KAC/D,OAAO,YACL,aACA,YAAY;MACV,IAAI;OACF,MAAM,OAAO,SAAS,UAAU;MAClC,SAAS,GAAG;OACV,iBAAiB,GAAG,EAClB,WAAW;QACT,SAAS;QACT,MAAM;OACR,EACF,CAAC;OACD,MAAM;MACR;KACF,GACA,aACF;IACF;IAEA,yBAAyB,MAAM,QAAQ,WAAW,IAAI;IAEtD,OAAO,OAAO,KAAK,KAAK;GAC1B;QAEA,OAAO,OAAO;EAElB;CACF,CAAC;AACH"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { instrumentCron } from "./cron.js";
|
|
2
|
+
import { instrumentNodeCron } from "./node-cron.js";
|
|
3
|
+
import { instrumentNodeSchedule } from "./node-schedule.js";
|
|
4
|
+
// src/cron/index.ts
|
|
5
|
+
/** Methods to instrument cron libraries for Sentry check-ins */
|
|
6
|
+
const cron = {
|
|
7
|
+
instrumentCron,
|
|
8
|
+
instrumentNodeCron,
|
|
9
|
+
instrumentNodeSchedule
|
|
10
|
+
};
|
|
11
|
+
export { cron };
|
|
12
|
+
|
|
13
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../src/cron/index.ts"],"sourcesContent":["import { instrumentCron } from './cron';\nimport { instrumentNodeCron } from './node-cron';\nimport { instrumentNodeSchedule } from './node-schedule';\n\n/** Methods to instrument cron libraries for Sentry check-ins */\nexport const cron = {\n // oxlint-disable-next-line typescript/no-deprecated\n instrumentCron,\n // oxlint-disable-next-line typescript/no-deprecated\n instrumentNodeCron,\n instrumentNodeSchedule,\n};\n"],"mappings":";;;;;AAKA,MAAa,OAAO;CAElB;CAEA;CACA;AACF"}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { isReadAlikeByNodeCron3 } from "../integrations/node-cron.js";
|
|
2
|
+
import { getCronMonitorConfig } from "./common.js";
|
|
3
|
+
import { addNonEnumerableProperty, captureException, startNewTrace, withMonitor } from "@sentry/core";
|
|
4
|
+
// src/cron/node-cron.ts
|
|
5
|
+
/**
|
|
6
|
+
* Wraps the `node-cron` library with check-in monitoring.
|
|
7
|
+
*
|
|
8
|
+
* ```ts
|
|
9
|
+
* import * as Sentry from "@sentry/node";
|
|
10
|
+
* import * as cron from "node-cron";
|
|
11
|
+
*
|
|
12
|
+
* const cronWithCheckIn = Sentry.cron.instrumentNodeCron(cron);
|
|
13
|
+
*
|
|
14
|
+
* cronWithCheckIn.schedule(
|
|
15
|
+
* "* * * * *",
|
|
16
|
+
* () => {
|
|
17
|
+
* console.log("running a task every minute");
|
|
18
|
+
* },
|
|
19
|
+
* { name: "my-cron-job" },
|
|
20
|
+
* );
|
|
21
|
+
* ```
|
|
22
|
+
*
|
|
23
|
+
* On node-cron 4, steps on `*` in the day-of-month or month field (such as every second day) aren't sent as a
|
|
24
|
+
* schedule, because this wrapper can't tell the node-cron version. `nodeCronIntegration` can.
|
|
25
|
+
*
|
|
26
|
+
* @deprecated Use `nodeCronIntegration` instead.
|
|
27
|
+
*/
|
|
28
|
+
function instrumentNodeCron(lib, monitorConfig = {}) {
|
|
29
|
+
return new Proxy(lib, { get(target, prop) {
|
|
30
|
+
if (prop === "schedule" && target.schedule) return new Proxy(target.schedule, { apply(target, thisArg, argArray) {
|
|
31
|
+
const [expression, callback, options] = argArray;
|
|
32
|
+
const name = options?.name;
|
|
33
|
+
const timezone = options?.timezone;
|
|
34
|
+
if (!name) throw new Error("Missing \"name\" for scheduled job. A name is required for Sentry check-in monitoring.");
|
|
35
|
+
const cronConfig = getCronMonitorConfig(expression, timezone, "node-cron", isReadAlikeByNodeCron3);
|
|
36
|
+
const upsertMonitorConfig = cronConfig && {
|
|
37
|
+
...cronConfig,
|
|
38
|
+
...monitorConfig
|
|
39
|
+
};
|
|
40
|
+
const monitoredCallback = async (...args) => {
|
|
41
|
+
const runWithMonitor = () => withMonitor(name, async () => {
|
|
42
|
+
try {
|
|
43
|
+
return await callback(...args);
|
|
44
|
+
} catch (e) {
|
|
45
|
+
captureException(e, { mechanism: {
|
|
46
|
+
handled: false,
|
|
47
|
+
type: "auto.function.node-cron.instrumentNodeCron"
|
|
48
|
+
} });
|
|
49
|
+
throw e;
|
|
50
|
+
}
|
|
51
|
+
}, upsertMonitorConfig);
|
|
52
|
+
return !upsertMonitorConfig && monitorConfig.isolateTrace ? startNewTrace(runWithMonitor) : runWithMonitor();
|
|
53
|
+
};
|
|
54
|
+
addNonEnumerableProperty(monitoredCallback, Symbol.for("sentry.cron.monitored"), true);
|
|
55
|
+
return target.apply(thisArg, [
|
|
56
|
+
expression,
|
|
57
|
+
monitoredCallback,
|
|
58
|
+
options
|
|
59
|
+
]);
|
|
60
|
+
} });
|
|
61
|
+
else return target[prop];
|
|
62
|
+
} });
|
|
63
|
+
}
|
|
64
|
+
export { instrumentNodeCron };
|
|
65
|
+
|
|
66
|
+
//# sourceMappingURL=node-cron.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"node-cron.js","names":[],"sources":["../../../src/cron/node-cron.ts"],"sourcesContent":["import {\n addNonEnumerableProperty,\n captureException,\n type MonitorConfig,\n startNewTrace,\n withMonitor,\n} from '@sentry/core';\nimport { isReadAlikeByNodeCron3 } from '../integrations/node-cron';\nimport { getCronMonitorConfig } from './common';\n\nexport interface NodeCronOptions {\n name: string;\n timezone?: string;\n}\n\nexport interface NodeCron {\n schedule: (\n cronExpression: string,\n callback: (context?: unknown) => void,\n options: NodeCronOptions | undefined,\n ) => unknown;\n}\n\n/**\n * Wraps the `node-cron` library with check-in monitoring.\n *\n * ```ts\n * import * as Sentry from \"@sentry/node\";\n * import * as cron from \"node-cron\";\n *\n * const cronWithCheckIn = Sentry.cron.instrumentNodeCron(cron);\n *\n * cronWithCheckIn.schedule(\n * \"* * * * *\",\n * () => {\n * console.log(\"running a task every minute\");\n * },\n * { name: \"my-cron-job\" },\n * );\n * ```\n *\n * On node-cron 4, steps on `*` in the day-of-month or month field (such as every second day) aren't sent as a\n * schedule, because this wrapper can't tell the node-cron version. `nodeCronIntegration` can.\n *\n * @deprecated Use `nodeCronIntegration` instead.\n */\nexport function instrumentNodeCron<T>(\n lib: Partial<NodeCron> & T,\n monitorConfig: Pick<MonitorConfig, 'isolateTrace'> = {},\n): T {\n return new Proxy(lib, {\n get(target, prop) {\n if (prop === 'schedule' && target.schedule) {\n // When 'get' is called for schedule, return a proxied version of the schedule function\n return new Proxy(target.schedule, {\n apply(target, thisArg, argArray: Parameters<NodeCron['schedule']>) {\n const [expression, callback, options] = argArray;\n\n const name = options?.name;\n const timezone = options?.timezone;\n\n if (!name) {\n throw new Error('Missing \"name\" for scheduled job. A name is required for Sentry check-in monitoring.');\n }\n\n // The node-cron version is unknown here, so check for node-cron 3 quirks, which include those before 4.6.\n const cronConfig = getCronMonitorConfig(expression, timezone, 'node-cron', isReadAlikeByNodeCron3);\n const upsertMonitorConfig = cronConfig && { ...cronConfig, ...monitorConfig };\n\n const monitoredCallback = async (...args: Parameters<typeof callback>): Promise<void> => {\n const runWithMonitor = (): Promise<void> =>\n withMonitor(\n name,\n async () => {\n // We have to manually catch here and capture the exception because node-cron swallows errors\n // https://github.com/node-cron/node-cron/issues/399\n try {\n // oxlint-disable-next-line typescript/await-thenable, typescript/return-await -- callback may be async at runtime; awaiting inside the try lets us capture its rejection\n return await callback(...args);\n } catch (e) {\n captureException(e, {\n mechanism: {\n handled: false,\n type: 'auto.function.node-cron.instrumentNodeCron',\n },\n });\n throw e;\n }\n },\n upsertMonitorConfig,\n );\n // `withMonitor` reads `isolateTrace` from the monitor config, which is not sent without a schedule.\n return !upsertMonitorConfig && monitorConfig.isolateTrace\n ? startNewTrace(runWithMonitor)\n : runWithMonitor();\n };\n\n // Tells `nodeCronIntegration` that this task is already monitored.\n addNonEnumerableProperty(monitoredCallback, Symbol.for('sentry.cron.monitored'), true);\n\n return target.apply(thisArg, [expression, monitoredCallback, options]);\n },\n });\n } else {\n return target[prop as keyof T];\n }\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,SAAgB,mBACd,KACA,gBAAqD,CAAC,GACnD;CACH,OAAO,IAAI,MAAM,KAAK,EACpB,IAAI,QAAQ,MAAM;EAChB,IAAI,SAAS,cAAc,OAAO,UAEhC,OAAO,IAAI,MAAM,OAAO,UAAU,EAChC,MAAM,QAAQ,SAAS,UAA4C;GACjE,MAAM,CAAC,YAAY,UAAU,WAAW;GAExC,MAAM,OAAO,SAAS;GACtB,MAAM,WAAW,SAAS;GAE1B,IAAI,CAAC,MACH,MAAM,IAAI,MAAM,wFAAsF;GAIxG,MAAM,aAAa,qBAAqB,YAAY,UAAU,aAAa,sBAAsB;GACjG,MAAM,sBAAsB,cAAc;IAAE,GAAG;IAAY,GAAG;GAAc;GAE5E,MAAM,oBAAoB,OAAO,GAAG,SAAqD;IACvF,MAAM,uBACJ,YACE,MACA,YAAY;KAGV,IAAI;MAEF,OAAO,MAAM,SAAS,GAAG,IAAI;KAC/B,SAAS,GAAG;MACV,iBAAiB,GAAG,EAClB,WAAW;OACT,SAAS;OACT,MAAM;MACR,EACF,CAAC;MACD,MAAM;KACR;IACF,GACA,mBACF;IAEF,OAAO,CAAC,uBAAuB,cAAc,eACzC,cAAc,cAAc,IAC5B,eAAe;GACrB;GAGA,yBAAyB,mBAAmB,OAAO,IAAI,uBAAuB,GAAG,IAAI;GAErF,OAAO,OAAO,MAAM,SAAS;IAAC;IAAY;IAAmB;GAAO,CAAC;EACvE,EACF,CAAC;OAED,OAAO,OAAO;CAElB,EACF,CAAC;AACH"}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { getCronMonitorConfig } from "./common.js";
|
|
2
|
+
import { addNonEnumerableProperty, withMonitor } from "@sentry/core";
|
|
3
|
+
// src/cron/node-schedule.ts
|
|
4
|
+
/**
|
|
5
|
+
* Instruments the `node-schedule` library to send a check-in event to Sentry for each job execution.
|
|
6
|
+
*
|
|
7
|
+
* ```ts
|
|
8
|
+
* import * as Sentry from '@sentry/node';
|
|
9
|
+
* import * as schedule from 'node-schedule';
|
|
10
|
+
*
|
|
11
|
+
* const scheduleWithCheckIn = Sentry.cron.instrumentNodeSchedule(schedule);
|
|
12
|
+
*
|
|
13
|
+
* const job = scheduleWithCheckIn.scheduleJob('my-cron-job', '* * * * *', () => {
|
|
14
|
+
* console.log('You will see this message every minute');
|
|
15
|
+
* });
|
|
16
|
+
* ```
|
|
17
|
+
*/
|
|
18
|
+
function instrumentNodeSchedule(lib) {
|
|
19
|
+
return new Proxy(lib, { get(target, prop) {
|
|
20
|
+
if (prop === "scheduleJob") return new Proxy(target.scheduleJob, { apply(target, thisArg, argArray) {
|
|
21
|
+
const [nameOrExpression, expressionOrCallback, callback] = argArray;
|
|
22
|
+
if (typeof nameOrExpression !== "string" || typeof expressionOrCallback !== "string" || typeof callback !== "function") throw new Error("Automatic instrumentation of 'node-schedule' requires the first parameter of 'scheduleJob' to be a job name string and the second parameter to be a crontab string");
|
|
23
|
+
const monitorSlug = nameOrExpression;
|
|
24
|
+
const expression = expressionOrCallback;
|
|
25
|
+
const monitorConfig = getCronMonitorConfig(expression, void 0, "cron-parser");
|
|
26
|
+
async function monitoredCallback() {
|
|
27
|
+
return withMonitor(monitorSlug, async () => {
|
|
28
|
+
await callback?.();
|
|
29
|
+
}, monitorConfig);
|
|
30
|
+
}
|
|
31
|
+
addNonEnumerableProperty(monitoredCallback, Symbol.for("sentry.cron.monitored"), true);
|
|
32
|
+
return target.apply(thisArg, [
|
|
33
|
+
monitorSlug,
|
|
34
|
+
expression,
|
|
35
|
+
monitoredCallback
|
|
36
|
+
]);
|
|
37
|
+
} });
|
|
38
|
+
return target[prop];
|
|
39
|
+
} });
|
|
40
|
+
}
|
|
41
|
+
export { instrumentNodeSchedule };
|
|
42
|
+
|
|
43
|
+
//# sourceMappingURL=node-schedule.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"node-schedule.js","names":[],"sources":["../../../src/cron/node-schedule.ts"],"sourcesContent":["import { addNonEnumerableProperty, withMonitor } from '@sentry/core';\nimport { getCronMonitorConfig } from './common';\n\nexport interface NodeSchedule {\n scheduleJob(\n nameOrExpression: string | Date | object,\n expressionOrCallback: string | Date | object | (() => void),\n callback?: () => void,\n ): unknown;\n}\n\n/**\n * Instruments the `node-schedule` library to send a check-in event to Sentry for each job execution.\n *\n * ```ts\n * import * as Sentry from '@sentry/node';\n * import * as schedule from 'node-schedule';\n *\n * const scheduleWithCheckIn = Sentry.cron.instrumentNodeSchedule(schedule);\n *\n * const job = scheduleWithCheckIn.scheduleJob('my-cron-job', '* * * * *', () => {\n * console.log('You will see this message every minute');\n * });\n * ```\n */\nexport function instrumentNodeSchedule<T>(lib: T & NodeSchedule): T {\n return new Proxy(lib, {\n get(target, prop: keyof NodeSchedule) {\n if (prop === 'scheduleJob') {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n return new Proxy(target.scheduleJob, {\n apply(target, thisArg, argArray: Parameters<NodeSchedule['scheduleJob']>) {\n const [nameOrExpression, expressionOrCallback, callback] = argArray;\n\n if (\n typeof nameOrExpression !== 'string' ||\n typeof expressionOrCallback !== 'string' ||\n typeof callback !== 'function'\n ) {\n throw new Error(\n \"Automatic instrumentation of 'node-schedule' requires the first parameter of 'scheduleJob' to be a job name string and the second parameter to be a crontab string\",\n );\n }\n\n const monitorSlug = nameOrExpression;\n const expression = expressionOrCallback;\n const monitorConfig = getCronMonitorConfig(expression, undefined, 'cron-parser');\n\n async function monitoredCallback(): Promise<void> {\n return withMonitor(\n monitorSlug,\n async () => {\n // oxlint-disable-next-line typescript/await-thenable -- callback may be async at runtime\n await callback?.();\n },\n monitorConfig,\n );\n }\n\n // Tells `nodeScheduleIntegration` that this job is already monitored.\n addNonEnumerableProperty(monitoredCallback, Symbol.for('sentry.cron.monitored'), true);\n\n return target.apply(thisArg, [monitorSlug, expression, monitoredCallback]);\n },\n });\n }\n\n return target[prop];\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAyBA,SAAgB,uBAA0B,KAA0B;CAClE,OAAO,IAAI,MAAM,KAAK,EACpB,IAAI,QAAQ,MAA0B;EACpC,IAAI,SAAS,eAEX,OAAO,IAAI,MAAM,OAAO,aAAa,EACnC,MAAM,QAAQ,SAAS,UAAmD;GACxE,MAAM,CAAC,kBAAkB,sBAAsB,YAAY;GAE3D,IACE,OAAO,qBAAqB,YAC5B,OAAO,yBAAyB,YAChC,OAAO,aAAa,YAEpB,MAAM,IAAI,MACR,oKACF;GAGF,MAAM,cAAc;GACpB,MAAM,aAAa;GACnB,MAAM,gBAAgB,qBAAqB,YAAY,KAAA,GAAW,aAAa;GAE/E,eAAe,oBAAmC;IAChD,OAAO,YACL,aACA,YAAY;KAEV,MAAM,WAAW;IACnB,GACA,aACF;GACF;GAGA,yBAAyB,mBAAmB,OAAO,IAAI,uBAAuB,GAAG,IAAI;GAErF,OAAO,OAAO,MAAM,SAAS;IAAC;IAAa;IAAY;GAAiB,CAAC;EAC3E,EACF,CAAC;EAGH,OAAO,OAAO;CAChB,EACF,CAAC;AACH"}
|
package/build/esm/index.js
CHANGED
|
@@ -32,9 +32,11 @@ import { awsIntegration } from "./integrations/aws-sdk/index.js";
|
|
|
32
32
|
import { dataloaderIntegration } from "./integrations/dataloader.js";
|
|
33
33
|
import { genericPoolIntegration } from "./integrations/generic-pool.js";
|
|
34
34
|
import { cronJobIntegration } from "./integrations/cron.js";
|
|
35
|
-
import {
|
|
35
|
+
import { nodeCronIntegration } from "./integrations/node-cron.js";
|
|
36
36
|
import { nodeScheduleIntegration } from "./integrations/node-schedule.js";
|
|
37
37
|
import { cronExpressionToMonitorConfig } from "./utils/cronMonitoring.js";
|
|
38
|
+
import { cron } from "./cron/index.js";
|
|
39
|
+
import { BullMQTelemetry } from "./integrations/bullmq/index.js";
|
|
38
40
|
import { googleGenAIIntegration } from "./integrations/google-genai.js";
|
|
39
41
|
import { graphqlIntegration } from "./integrations/graphql/index.js";
|
|
40
42
|
import { hapiIntegration } from "./integrations/hapi/index.js";
|
|
@@ -64,6 +66,8 @@ import { togetherAIIntegration } from "./integrations/together-ai.js";
|
|
|
64
66
|
import { typesafeIntegration } from "./integrations/typesafe.js";
|
|
65
67
|
import { mysqlIntegration } from "./integrations/mysql.js";
|
|
66
68
|
import { mysql2Integration } from "./integrations/mysql2/index.js";
|
|
69
|
+
import { pinoIntegration } from "./integrations/pino.js";
|
|
70
|
+
import { createSentryWinstonTransport } from "./integrations/winston.js";
|
|
67
71
|
import { openAIIntegration } from "./integrations/openai.js";
|
|
68
72
|
import { postgresIntegration } from "./integrations/pg.js";
|
|
69
73
|
import { postgresJsIntegration } from "./integrations/postgresjs/index.js";
|
|
@@ -80,6 +84,6 @@ import { getErrorIntegrations, getTracingIntegrations } from "./integrations/ind
|
|
|
80
84
|
* @deprecated This is a temporary export to avoid breaking changes. It will be removed in the next major version.
|
|
81
85
|
*/
|
|
82
86
|
const attachHapiErrorHandler = attachHapiErrorHandler$1;
|
|
83
|
-
export { SentryMastraExporter, cronExpressionToMonitorConfig as _INTERNAL_cronExpressionToMonitorConfig, instrumentTunnelServer as _INTERNAL_instrumentTunnelServer, instrumentTunnelServers as _INTERNAL_instrumentTunnelServers,
|
|
87
|
+
export { BullMQTelemetry, SentryMastraExporter, cronExpressionToMonitorConfig as _INTERNAL_cronExpressionToMonitorConfig, instrumentTunnelServer as _INTERNAL_instrumentTunnelServer, instrumentTunnelServers as _INTERNAL_instrumentTunnelServers, amqplibIntegration, anthropicAIIntegration, applyHonoPatches, attachHapiErrorHandler, attachKoaErrorHandler, awsIntegration, bindTracingChannelToSpan, createFlueInstrumentation, createHonoRequestMiddleware, createLangChainCallbackHandler, createSentryWinstonTransport, cron, cronJobIntegration, dataloaderIntegration, detectOrchestrionSetup, tracingChannel as diagnosticsTracingChannel, earlyPatchHono, eveConversationHook, eveIntegration, eveTracePolicy, expressErrorHandler, expressIntegration, fastifyIntegration, firebaseIntegration, flueIntegration, genericPoolIntegration, getErrorIntegrations, getInstrumentedModuleNames, getOtlpTracesEndpoint, getSqlQueryAttributes, getSqlQuerySummary, getSqlSpanName, getTracingIntegrations, googleGenAIIntegration, graphqlIntegration, groqIntegration, hapiIntegration, honoIntegration, honoMiddleware, instrumentAnthropicAiClient, instrumentCreateReactAgent, instrumentGoogleGenAIClient, instrumentLangChainEmbeddings, instrumentMistralAiClient, instrumentOpenAiClient, instrumentPostgresJsSql, instrumentStateGraph, instrumentStateGraphCompile, instrumentTypeSafeClient, instrumentWorkersAiClient, isBun, isCloudflareWorkers, isDeno, kafkaIntegration, knexIntegration, koaIntegration, langChainIntegration, langGraphIntegration, lruMemoizerIntegration, makeServeTunnelIntegration, mastraIntegration, mcpServerIntegration, mistralAIIntegration, mongoIntegration, mongooseIntegration, mysql2Integration, mysqlIntegration, neonIntegration, nitroIntegration, nodeCronIntegration, nodeScheduleIntegration, openAIIntegration, openTelemetryIntegration, orchestrionModuleInjected, piAiIntegration, piDurableIntegration, pinoIntegration, postgresIntegration, postgresJsIntegration, prismaIntegration, redisIntegration, sanitizeSqlQuery, setAsyncLocalStorageAsyncContextStrategy, setHttpServerSpanRouteAttribute, setupExpressErrorHandler, setupFastifyErrorHandler, subscribe as subscribeDiagnosticsChannel, tediousIntegration, togetherAIIntegration, typesafeIntegration, vercelAIIntegration };
|
|
84
88
|
|
|
85
89
|
//# sourceMappingURL=index.js.map
|