Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 29 additions & 6 deletions packages/shared/src/telemetry/evaluation-event.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,20 @@
import { ErrorCode, StandardResolutionReasons, type EvaluationDetails, type FlagValue } from '../evaluation/evaluation';
import type { HookContext } from '../hooks/hooks';
import { ErrorCode, StandardResolutionReasons, type EvaluationDetails, type FlagValue } from '../evaluation';
import type { HookContext } from '../hooks';
import { TelemetryAttribute } from './attributes';
import { TelemetryFlagMetadata } from './flag-metadata';

/**
* Attribute types for OpenTelemetry.
* @see https://github.com/open-telemetry/opentelemetry-js/blob/fbbce6e1c0de86e4c504b5788d876fae4d3bc254/api/src/common/Attributes.ts#L35
*/
export declare type AttributeValue =
| string
| number
| boolean
| Array<null | undefined | string>
| Array<null | undefined | number>
| Array<null | undefined | boolean>;

type EvaluationEvent = {
/**
* The name of the feature flag evaluation event.
Expand All @@ -13,7 +25,7 @@ type EvaluationEvent = {
* @experimental The attributes are subject to change.
* @see https://opentelemetry.io/docs/specs/semconv/feature-flags/feature-flags-logs/
*/
attributes: Record<string, string | number | boolean | FlagValue>;
attributes: Record<string, AttributeValue | undefined>;
};

const FLAG_EVALUATION_EVENT_NAME = 'feature_flag.evaluation';
Expand All @@ -36,12 +48,23 @@ export function createEvaluationEvent(

if (evaluationDetails.variant) {
attributes[TelemetryAttribute.VARIANT] = evaluationDetails.variant;
} else {
attributes[TelemetryAttribute.VALUE] = evaluationDetails.value;
}

if (evaluationDetails.value !== null) {
if (typeof evaluationDetails.value !== 'object') {
attributes[TelemetryAttribute.VALUE] = evaluationDetails.value;
} else {
try {
// Objects are not valid attribute values, so we convert them to a JSON string
attributes[TelemetryAttribute.VALUE] = JSON.stringify(evaluationDetails.value);
} catch {
// We ignore non serializable values
}
}
}

const contextId =
evaluationDetails.flagMetadata[TelemetryFlagMetadata.CONTEXT_ID] || hookContext.context.targetingKey;
evaluationDetails.flagMetadata[TelemetryFlagMetadata.CONTEXT_ID] ?? hookContext.context.targetingKey;
if (contextId) {
attributes[TelemetryAttribute.CONTEXT_ID] = contextId;
}
Expand Down
Loading