-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathid_gen.py
More file actions
64 lines (44 loc) · 1.63 KB
/
Copy pathid_gen.py
File metadata and controls
64 lines (44 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import secrets
import uuid
from abc import ABC, abstractmethod
from .env import BraintrustEnv
def get_id_generator():
"""Factory function that creates a new ID generator instance each time.
This eliminates global state and makes tests parallelizable.
Each caller gets their own generator instance.
Defaults to OpenTelemetry-compatible hex IDs. Set BRAINTRUST_LEGACY_IDS
to opt back into legacy UUID-based IDs.
"""
return UUIDGenerator() if BraintrustEnv.LEGACY_IDS else OTELIDGenerator()
class IDGenerator(ABC):
"""Abstract base class for ID generators."""
@abstractmethod
def get_span_id(self):
pass
@abstractmethod
def get_trace_id(self):
pass
@abstractmethod
def share_root_span_id(self):
"""Return True if the generator should use span_id as root_span_id for backwards compatibility."""
pass
class UUIDGenerator(IDGenerator):
"""ID generator that uses UUID4 for both span and trace IDs."""
def get_span_id(self):
return str(uuid.uuid4())
def get_trace_id(self):
return str(uuid.uuid4())
def share_root_span_id(self):
return True
class OTELIDGenerator(IDGenerator):
"""ID generator that generates OpenTelemetry-compatible IDs. We use this to have ids that can
seamlessly flow between Braintrust and OpenTelemetry.
"""
def get_span_id(self):
# Generate 8 random bytes and convert to hex
return secrets.token_hex(8)
def get_trace_id(self):
# Generate 16 random bytes and convert to hex
return secrets.token_hex(16)
def share_root_span_id(self):
return False