Coverage for ivatar/telemetry_utils.py: 100%

33 statements  

« prev     ^ index     » next       coverage.py v7.11.0, created at 2025-11-04 00:07 +0000

1""" 

2Utility functions for OpenTelemetry instrumentation with graceful degradation. 

3 

4This module provides a safe way to import and use OpenTelemetry decorators and metrics 

5that gracefully degrades when OpenTelemetry packages are not installed. 

6""" 

7 

8 

9# Define no-op implementations first (always available for testing) 

10def _no_op_trace_decorator(operation_name): 

11 """No-op decorator when OpenTelemetry is not available""" 

12 

13 def decorator(func): 

14 return func 

15 

16 return decorator 

17 

18 

19class NoOpMetrics: 

20 """No-op metrics class when OpenTelemetry is not available""" 

21 

22 def record_avatar_generated(self, *args, **kwargs): 

23 pass 

24 

25 def record_avatar_request(self, *args, **kwargs): 

26 pass 

27 

28 def record_cache_hit(self, *args, **kwargs): 

29 pass 

30 

31 def record_cache_miss(self, *args, **kwargs): 

32 pass 

33 

34 def record_external_request(self, *args, **kwargs): 

35 pass 

36 

37 def record_file_upload(self, *args, **kwargs): 

38 pass 

39 

40 

41# Safe import pattern for OpenTelemetry 

42try: 

43 from .opentelemetry_middleware import ( 

44 trace_avatar_operation, 

45 trace_file_upload, 

46 trace_authentication, 

47 get_avatar_metrics, 

48 ) 

49 

50 # Get the actual metrics instance 

51 avatar_metrics = get_avatar_metrics() 

52 

53 # OpenTelemetry is available 

54 TELEMETRY_AVAILABLE = True 

55 

56except ImportError: 

57 # OpenTelemetry packages not installed - use no-op implementations 

58 trace_avatar_operation = _no_op_trace_decorator 

59 trace_file_upload = _no_op_trace_decorator 

60 trace_authentication = _no_op_trace_decorator 

61 

62 avatar_metrics = NoOpMetrics() 

63 

64 # OpenTelemetry is not available 

65 TELEMETRY_AVAILABLE = False 

66 

67 

68def get_telemetry_decorators(): 

69 """ 

70 Get all telemetry decorators in a single call. 

71 

72 Returns: 

73 tuple: (trace_avatar_operation, trace_file_upload, trace_authentication) 

74 """ 

75 return trace_avatar_operation, trace_file_upload, trace_authentication 

76 

77 

78def get_telemetry_metrics(): 

79 """ 

80 Get the telemetry metrics instance. 

81 

82 Returns: 

83 AvatarMetrics or NoOpMetrics: The metrics instance 

84 """ 

85 return avatar_metrics 

86 

87 

88def is_telemetry_available(): 

89 """ 

90 Check if OpenTelemetry is available and working. 

91 

92 Returns: 

93 bool: True if OpenTelemetry is available, False otherwise 

94 """ 

95 # Check the actual metrics instance type rather than relying on 

96 # the module-level variable which can be affected by test mocking 

97 return not isinstance(avatar_metrics, NoOpMetrics)