diff --git a/src/libs/telemetry/middlewares/index.ts b/src/libs/telemetry/middlewares/index.ts index 290a2855995e..ad212f8af0a6 100644 --- a/src/libs/telemetry/middlewares/index.ts +++ b/src/libs/telemetry/middlewares/index.ts @@ -2,10 +2,11 @@ import type {EventHint, TransactionEvent} from '@sentry/core'; import emailDomainFilter from './emailDomainFilter'; import firebasePerformanceFilter from './firebasePerformanceFilter'; import minDurationFilter from './minDurationFilter'; +import scopeTagsEnricher from './scopeTagsEnricher'; type TelemetryBeforeSend = (event: TransactionEvent, hint: EventHint) => TransactionEvent | null | Promise; -const middlewares: TelemetryBeforeSend[] = [emailDomainFilter, firebasePerformanceFilter, minDurationFilter]; +const middlewares: TelemetryBeforeSend[] = [emailDomainFilter, firebasePerformanceFilter, minDurationFilter, scopeTagsEnricher]; function processBeforeSendTransactions(event: TransactionEvent, hint: EventHint): Promise { return middlewares.reduce( diff --git a/src/libs/telemetry/middlewares/scopeTagsEnricher.ts b/src/libs/telemetry/middlewares/scopeTagsEnricher.ts new file mode 100644 index 000000000000..4edfb1227079 --- /dev/null +++ b/src/libs/telemetry/middlewares/scopeTagsEnricher.ts @@ -0,0 +1,38 @@ +import type {TransactionEvent} from '@sentry/core'; +import * as Sentry from '@sentry/react-native'; +import CONST from '@src/CONST'; +import type {TelemetryBeforeSend} from './index'; + +/** + * Enriches transaction with tags and contexts from the current Sentry scope. + * This ensures that tags set asynchronously (e.g. nudge_migration_cohort) + * are included in transactions that were created before the tags were set. + * This middleware applies the tag at send-time, ensuring early spans get the tags. + */ +const scopeTagsEnricher: TelemetryBeforeSend = (event: TransactionEvent): TransactionEvent => { + const scope = Sentry.getCurrentScope(); + const scopeData = scope.getScopeData(); + + const enrichedEvent = { + ...event, + tags: { + ...event.tags, + ...(scopeData.tags?.[CONST.TELEMETRY.TAG_NUDGE_MIGRATION_COHORT] && { + [CONST.TELEMETRY.TAG_NUDGE_MIGRATION_COHORT]: scopeData.tags[CONST.TELEMETRY.TAG_NUDGE_MIGRATION_COHORT], + }), + ...(scopeData.tags?.[CONST.TELEMETRY.TAG_ACTIVE_POLICY] && { + [CONST.TELEMETRY.TAG_ACTIVE_POLICY]: scopeData.tags[CONST.TELEMETRY.TAG_ACTIVE_POLICY], + }), + }, + contexts: { + ...event.contexts, + ...(scopeData.contexts?.[CONST.TELEMETRY.CONTEXT_POLICIES] && { + [CONST.TELEMETRY.CONTEXT_POLICIES]: scopeData.contexts[CONST.TELEMETRY.CONTEXT_POLICIES], + }), + }, + }; + + return enrichedEvent; +}; + +export default scopeTagsEnricher;