|
| 1 | +// Unless explicitly stated otherwise all files in this repository are licensed |
| 2 | +// under the Apache License Version 2.0. |
| 3 | +// This product includes software developed at Datadog (https://www.datadoghq.com/). |
| 4 | +// Copyright 2026 Datadog, Inc. |
| 5 | + |
| 6 | +package openfeature |
| 7 | + |
| 8 | +import ( |
| 9 | + "crypto/sha256" |
| 10 | + "encoding/base64" |
| 11 | + "encoding/hex" |
| 12 | + "encoding/json" |
| 13 | + "slices" |
| 14 | + "sync" |
| 15 | + |
| 16 | + "github.com/DataDog/dd-trace-go/v2/internal/log" |
| 17 | +) |
| 18 | + |
| 19 | +// FeatureFlagEvaluation represents a single feature flag evaluation to be |
| 20 | +// recorded in span enrichment. |
| 21 | +type FeatureFlagEvaluation struct { |
| 22 | + FlagKey string |
| 23 | + // SerialId is the optional serial ID from flag metadata. Nil for runtime defaults. |
| 24 | + SerialID *uint32 |
| 25 | + // Subject is the targeting key / subject of experiment. Non-empty only when evaluation |
| 26 | + // should be logged (doLog=true). |
| 27 | + Subject string |
| 28 | + // DefaultValue is the default value used. Non-nil only when a runtime default was used. |
| 29 | + DefaultValue any |
| 30 | +} |
| 31 | + |
| 32 | +const ( |
| 33 | + spanEnrichmentMaxSerialIDs = 200 |
| 34 | + spanEnrichmentMaxSubjects = 10 |
| 35 | + spanEnrichmentMaxSerialIDsPerSubject = 20 |
| 36 | + spanEnrichmentMaxRuntimeDefaults = 5 |
| 37 | + spanEnrichmentMaxDefaultValueLen = 64 |
| 38 | +) |
| 39 | + |
| 40 | +// SpanEnrichment accumulates feature flag evaluations to be encoded as span tags. |
| 41 | +type SpanEnrichment struct { |
| 42 | + mu sync.Mutex |
| 43 | + serialIDs map[uint32]struct{} |
| 44 | + subjects map[string]map[uint32]struct{} |
| 45 | + runtimeDefaults map[string]string |
| 46 | +} |
| 47 | + |
| 48 | +func NewSpanEnrichment() *SpanEnrichment { |
| 49 | + return &SpanEnrichment{ |
| 50 | + serialIDs: make(map[uint32]struct{}, spanEnrichmentMaxSerialIDs), |
| 51 | + subjects: make(map[string]map[uint32]struct{}, spanEnrichmentMaxSubjects), |
| 52 | + runtimeDefaults: make(map[string]string, spanEnrichmentMaxRuntimeDefaults), |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +func (se *SpanEnrichment) AddEvaluation(eval *FeatureFlagEvaluation) { |
| 57 | + if eval == nil { |
| 58 | + return |
| 59 | + } |
| 60 | + |
| 61 | + se.mu.Lock() |
| 62 | + defer se.mu.Unlock() |
| 63 | + |
| 64 | + if eval.SerialID != nil { |
| 65 | + se.addSerialID(*eval.SerialID) |
| 66 | + if eval.Subject != "" { |
| 67 | + se.addSubject(eval.Subject, *eval.SerialID) |
| 68 | + } |
| 69 | + } else if eval.DefaultValue != nil { |
| 70 | + se.addRuntimeDefault(eval.FlagKey, eval.DefaultValue) |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +// Must be called with se.mu held. |
| 75 | +func (se *SpanEnrichment) addSerialID(sid uint32) { |
| 76 | + if _, exists := se.serialIDs[sid]; !exists { |
| 77 | + if len(se.serialIDs) >= spanEnrichmentMaxSerialIDs { |
| 78 | + log.Debug("openfeature: span enrichment: too many flag serial IDs, dropping (max %d)", spanEnrichmentMaxSerialIDs) |
| 79 | + return |
| 80 | + } |
| 81 | + se.serialIDs[sid] = struct{}{} |
| 82 | + } |
| 83 | +} |
| 84 | + |
| 85 | +// Must be called with se.mu held. |
| 86 | +func (se *SpanEnrichment) addSubject(subject string, sid uint32) { |
| 87 | + subjectIDs, ok := se.subjects[subject] |
| 88 | + if !ok { |
| 89 | + if len(se.subjects) >= spanEnrichmentMaxSubjects { |
| 90 | + log.Debug("openfeature: span enrichment: too many targeting keys, dropping (max %d)", spanEnrichmentMaxSubjects) |
| 91 | + return |
| 92 | + } |
| 93 | + subjectIDs = make(map[uint32]struct{}, spanEnrichmentMaxSerialIDsPerSubject) |
| 94 | + se.subjects[subject] = subjectIDs |
| 95 | + } |
| 96 | + if len(subjectIDs) >= spanEnrichmentMaxSerialIDsPerSubject { |
| 97 | + log.Debug("openfeature: span enrichment: too many experiments for subject %q, dropping (max %d)", subject, spanEnrichmentMaxSerialIDsPerSubject) |
| 98 | + return |
| 99 | + } |
| 100 | + subjectIDs[sid] = struct{}{} |
| 101 | +} |
| 102 | + |
| 103 | +// Must be called with se.mu held. |
| 104 | +func (se *SpanEnrichment) addRuntimeDefault(flagKey string, defaultValue any) { |
| 105 | + if _, exists := se.runtimeDefaults[flagKey]; exists { |
| 106 | + return |
| 107 | + } |
| 108 | + if len(se.runtimeDefaults) >= spanEnrichmentMaxRuntimeDefaults { |
| 109 | + log.Debug("openfeature: span enrichment: too many runtime defaults, dropping (max %d)", spanEnrichmentMaxRuntimeDefaults) |
| 110 | + return |
| 111 | + } |
| 112 | + var valueStr string |
| 113 | + if v, ok := defaultValue.(string); ok { |
| 114 | + valueStr = v |
| 115 | + } else if b, err := json.Marshal(defaultValue); err == nil { |
| 116 | + valueStr = string(b) |
| 117 | + } else { |
| 118 | + log.Debug("openfeature: span enrichment: failed to marshal runtime default value for key %q: %v", flagKey, err.Error()) |
| 119 | + return |
| 120 | + } |
| 121 | + if len(valueStr) > spanEnrichmentMaxDefaultValueLen { |
| 122 | + log.Debug("openfeature: span enrichment: runtime default value for key %q exceeds max length (%d), truncating", flagKey, spanEnrichmentMaxDefaultValueLen) |
| 123 | + valueStr = valueStr[:spanEnrichmentMaxDefaultValueLen] |
| 124 | + } |
| 125 | + se.runtimeDefaults[flagKey] = valueStr |
| 126 | +} |
| 127 | + |
| 128 | +// GetSpanTags returns span tags encoding accumulated feature flag evaluations. |
| 129 | +func (se *SpanEnrichment) GetSpanTags() map[string]string { |
| 130 | + se.mu.Lock() |
| 131 | + defer se.mu.Unlock() |
| 132 | + |
| 133 | + tags := make(map[string]string, 3) |
| 134 | + |
| 135 | + if len(se.serialIDs) > 0 { |
| 136 | + tags["ffe_flags_enc"] = encodeSerialIDs(se.serialIDs) |
| 137 | + } |
| 138 | + |
| 139 | + if len(se.subjects) > 0 { |
| 140 | + subjects := make(map[string]string, len(se.subjects)) |
| 141 | + for key, ids := range se.subjects { |
| 142 | + sum := sha256.Sum256([]byte(key)) |
| 143 | + hashKey := hex.EncodeToString(sum[:]) |
| 144 | + subjects[hashKey] = encodeSerialIDs(ids) |
| 145 | + } |
| 146 | + if b, err := json.Marshal(subjects); err == nil { |
| 147 | + tags["ffe_subjects_enc"] = string(b) |
| 148 | + } else { |
| 149 | + log.Debug("openfeature: span enrichment: failed to marshal subjects: %v", err.Error()) |
| 150 | + } |
| 151 | + } |
| 152 | + |
| 153 | + if len(se.runtimeDefaults) > 0 { |
| 154 | + defaults := se.runtimeDefaults |
| 155 | + if b, err := json.Marshal(defaults); err == nil { |
| 156 | + tags["ffe_runtime_defaults"] = string(b) |
| 157 | + } else { |
| 158 | + log.Debug("openfeature: span enrichment: failed to marshal runtime defaults: %v", err.Error()) |
| 159 | + } |
| 160 | + } |
| 161 | + |
| 162 | + return tags |
| 163 | +} |
| 164 | + |
| 165 | +// Encode a set of serial ids using unsigned LEB128 delta encoding, wrapped in base64. |
| 166 | +func encodeSerialIDs(ids map[uint32]struct{}) string { |
| 167 | + seq := make([]uint32, 0, len(ids)) |
| 168 | + for id := range ids { |
| 169 | + seq = append(seq, id) |
| 170 | + } |
| 171 | + |
| 172 | + slices.Sort(seq) |
| 173 | + |
| 174 | + b := make([]byte, 0, 5*len(seq)) // 5 bytes is absolute max to encode an id |
| 175 | + var prevID uint32 = 0 |
| 176 | + for _, id := range seq { |
| 177 | + diff := id - prevID |
| 178 | + prevID = id |
| 179 | + |
| 180 | + // Unsigned LEB128 encoding. |
| 181 | + for diff > 0x7f { |
| 182 | + b = append(b, byte((diff&0x7f)|0x80)) |
| 183 | + diff >>= 7 |
| 184 | + } |
| 185 | + b = append(b, byte(diff&0x7f)) |
| 186 | + } |
| 187 | + |
| 188 | + return base64.StdEncoding.EncodeToString(b) |
| 189 | +} |
0 commit comments