GetInstance returns or creates an instance for the given context and labels
(ctx any, labels any)
| 21 | |
| 22 | // GetInstance returns or creates an instance for the given context and labels |
| 23 | func (s *CollectorState) GetInstance(ctx any, labels any) *Instance { |
| 24 | // Extract context metadata including label order |
| 25 | contextMeta := extractContextMetadata(ctx) |
| 26 | if contextMeta == nil { |
| 27 | return nil |
| 28 | } |
| 29 | |
| 30 | // Extract context name |
| 31 | contextName := contextMeta.Name |
| 32 | |
| 33 | // Generate instance key |
| 34 | var key string |
| 35 | var labelMap map[string]string |
| 36 | |
| 37 | if labels != nil { |
| 38 | // Always convert to map for storage |
| 39 | labelMap = structToMap(labels) |
| 40 | |
| 41 | // Use the InstanceID method if available |
| 42 | if labeler, ok := labels.(interface{ InstanceID(string) string }); ok { |
| 43 | key = labeler.InstanceID(contextName) |
| 44 | } else { |
| 45 | // Fallback to manual generation |
| 46 | key = generateInstanceKeyWithOrder(contextName, contextMeta.LabelOrder, labelMap) |
| 47 | } |
| 48 | } else { |
| 49 | // No labels, just use context name |
| 50 | key = contextName |
| 51 | labelMap = make(map[string]string) |
| 52 | } |
| 53 | |
| 54 | // Get or create instance |
| 55 | instance, exists := s.instances[key] |
| 56 | if !exists { |
| 57 | instance = &Instance{ |
| 58 | key: key, |
| 59 | contextName: contextName, |
| 60 | labels: labelMap, |
| 61 | lastSeen: time.Now(), |
| 62 | } |
| 63 | s.instances[key] = instance |
| 64 | } |
| 65 | |
| 66 | instance.lastSeen = time.Now() |
| 67 | return instance |
| 68 | } |
| 69 | |
| 70 | // SetMetricsForGeneratedCode is ONLY for use by code generated by metricgen. |
| 71 | // DO NOT call this method directly in hand-written code. |
no test coverage detected