Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/redis/observability/recorder.py: 12%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

367 statements  

1""" 

2Simple, clean API for recording observability metrics. 

3 

4This module provides a straightforward interface for Redis core code to record 

5metrics without needing to know about OpenTelemetry internals. 

6 

7Usage in Redis core code: 

8 from redis.observability.recorder import record_operation_duration 

9 

10 start_time = time.monotonic() 

11 # ... execute Redis command ... 

12 record_operation_duration( 

13 command_name='SET', 

14 duration_seconds=time.monotonic() - start_time, 

15 server_address='localhost', 

16 server_port=6379, 

17 db_namespace='0', 

18 error=None 

19 ) 

20""" 

21 

22from datetime import datetime 

23from typing import TYPE_CHECKING, Callable, List, Optional 

24 

25from redis.observability.attributes import ( 

26 AttributeBuilder, 

27 ConnectionState, 

28 CSCReason, 

29 CSCResult, 

30 GeoFailoverReason, 

31 PubSubDirection, 

32) 

33from redis.observability.metrics import CloseReason, RedisMetricsCollector 

34from redis.observability.providers import ( 

35 _register_reset_hook, 

36 get_observability_instance, 

37) 

38from redis.observability.registry import get_observables_registry_instance 

39from redis.utils import deprecated_args, deprecated_function, str_if_bytes 

40 

41if TYPE_CHECKING: 

42 from redis.connection import ConnectionPoolInterface 

43 from redis.multidb.database import SyncDatabase 

44 from redis.observability.config import OTelConfig 

45 

46# Global metrics collector instance (lazy-initialized) 

47_metrics_collector: Optional[RedisMetricsCollector] = None 

48# Whether the collector above has been looked up already. A *miss* is cached 

49# too: resolving it walks the observability singleton, and while observability 

50# is disabled the helpers below run on every command. ObservabilityInstance. 

51# init() clears both this flag and the collector, so enabling observability 

52# after a recording call still starts collecting. The helpers check the 

53# collector and this flag inline and only then call _get_or_create_collector(), 

54# so the disabled path never pays for a call. 

55_collector_resolved = False 

56# Bumped by reset_collector() every time the caches below are dropped. A 

57# resolution that spans a reset can see the fields it owns cleared underneath 

58# it, so it records the generation it started from and hands the cache back 

59# rather than publishing an answer that belongs to the configuration the 

60# reset replaced. 

61_collector_generation = 0 

62 

63CSC_ITEMS_REGISTRY_KEY = "csc_items" 

64CONNECTION_COUNT_REGISTRY_KEY = "connection_count" 

65 

66 

67@deprecated_args( 

68 args_to_warn=["batch_size"], 

69 reason="The batch_size argument is no longer used and will be removed in the next major version.", 

70 version="7.2.1", 

71) 

72def record_operation_duration( 

73 command_name: str, 

74 duration_seconds: float, 

75 server_address: Optional[str] = None, 

76 server_port: Optional[int] = None, 

77 db_namespace: Optional[str] = None, 

78 error: Optional[Exception] = None, 

79 is_blocking: Optional[bool] = None, 

80 batch_size: Optional[int] = None, # noqa 

81 retry_attempts: Optional[int] = None, 

82) -> None: 

83 """ 

84 Record a Redis command execution duration. 

85 

86 This is a simple, clean API that Redis core code can call directly. 

87 If observability is not enabled, this returns immediately with zero overhead. 

88 

89 Args: 

90 command_name: Redis command name (e.g., 'GET', 'SET') 

91 duration_seconds: Command execution time in seconds 

92 server_address: Redis server address 

93 server_port: Redis server port 

94 db_namespace: Redis database index 

95 error: Exception if command failed, None if successful 

96 is_blocking: Whether the operation is a blocking command 

97 batch_size: Number of commands in batch (for pipelines/transactions) 

98 retry_attempts: Number of retry attempts made 

99 

100 Example: 

101 >>> start = time.monotonic() 

102 >>> # ... execute command ... 

103 >>> record_operation_duration('SET', time.monotonic() - start, 'localhost', 6379, '0') 

104 """ 

105 collector = _metrics_collector 

106 if collector is None: 

107 if _collector_resolved: 

108 return # Observability not enabled 

109 collector = _get_or_create_collector() 

110 if collector is None: 

111 return # Observability not enabled 

112 

113 # Record the metric 

114 try: 

115 collector.record_operation_duration( 

116 command_name=command_name, 

117 duration_seconds=duration_seconds, 

118 server_address=server_address, 

119 server_port=server_port, 

120 db_namespace=db_namespace, 

121 error_type=error, 

122 network_peer_address=server_address, 

123 network_peer_port=server_port, 

124 is_blocking=is_blocking, 

125 retry_attempts=retry_attempts, 

126 ) 

127 except Exception: 

128 # Don't let metric recording errors break Redis operations 

129 pass 

130 

131 

132def record_connection_create_time( 

133 connection_pool: "ConnectionPoolInterface", 

134 duration_seconds: float, 

135) -> None: 

136 """ 

137 Record connection creation time. 

138 

139 Args: 

140 connection_pool: Connection pool implementation 

141 duration_seconds: Time taken to create connection in seconds 

142 

143 Example: 

144 >>> start = time.monotonic() 

145 >>> # ... create connection ... 

146 >>> record_connection_create_time('ConnectionPool<localhost:6379>', time.monotonic() - start) 

147 """ 

148 collector = _metrics_collector 

149 if collector is None: 

150 if _collector_resolved: 

151 return 

152 collector = _get_or_create_collector() 

153 if collector is None: 

154 return 

155 

156 try: 

157 collector.record_connection_create_time( 

158 connection_pool=connection_pool, 

159 duration_seconds=duration_seconds, 

160 ) 

161 except Exception: 

162 pass 

163 

164 

165def record_connection_count( 

166 pool_name: str, 

167 connection_state: ConnectionState, 

168 counter: int = 1, 

169) -> None: 

170 """ 

171 Record a connection count change for a single state. 

172 

173 Args: 

174 pool_name: Connection pool identifier 

175 connection_state: State to update (IDLE or USED) 

176 counter: Number to add (positive) or subtract (negative) 

177 

178 Example: 

179 # New connection created (goes to IDLE first) 

180 >>> record_connection_count('pool_abc123', ConnectionState.IDLE, 1) 

181 

182 # Acquire from pool (transition) 

183 >>> record_connection_count('pool_abc123', ConnectionState.IDLE, -1) 

184 >>> record_connection_count('pool_abc123', ConnectionState.USED, 1) 

185 

186 # Release to pool (transition) 

187 >>> record_connection_count('pool_abc123', ConnectionState.USED, -1) 

188 >>> record_connection_count('pool_abc123', ConnectionState.IDLE, 1) 

189 

190 # Pool disconnect 5 idle connections 

191 >>> record_connection_count('pool_abc123', ConnectionState.IDLE, -5) 

192 """ 

193 collector = _metrics_collector 

194 if collector is None: 

195 if _collector_resolved: 

196 return 

197 collector = _get_or_create_collector() 

198 if collector is None: 

199 return 

200 

201 try: 

202 collector.record_connection_count( 

203 pool_name=pool_name, 

204 connection_state=connection_state, 

205 counter=counter, 

206 ) 

207 except Exception: 

208 pass 

209 

210 

211@deprecated_function( 

212 reason="Connection count is now tracked via record_connection_count(). " 

213 "This functionality will be removed in the next major version", 

214 version="7.4.0", 

215) 

216def init_connection_count() -> None: 

217 """ 

218 Initialize observable gauge for connection count metric. 

219 """ 

220 collector = _metrics_collector 

221 if collector is None: 

222 if _collector_resolved: 

223 return 

224 collector = _get_or_create_collector() 

225 if collector is None: 

226 return 

227 

228 def observable_callback(__): 

229 observables_registry = get_observables_registry_instance() 

230 callbacks = observables_registry.get(CONNECTION_COUNT_REGISTRY_KEY) 

231 observations = [] 

232 

233 for callback in callbacks: 

234 observations.extend(callback()) 

235 

236 return observations 

237 

238 try: 

239 collector.init_connection_count( 

240 callback=observable_callback, 

241 ) 

242 except Exception: 

243 pass 

244 

245 

246@deprecated_function( 

247 reason="Connection count is now tracked via record_connection_count(). " 

248 "This functionality will be removed in the next major version", 

249 version="7.4.0", 

250) 

251def register_pools_connection_count( 

252 connection_pools: List["ConnectionPoolInterface"], 

253) -> None: 

254 """ 

255 Add connection pools to connection count observable registry. 

256 """ 

257 collector = _metrics_collector 

258 if collector is None: 

259 if _collector_resolved: 

260 return 

261 collector = _get_or_create_collector() 

262 if collector is None: 

263 return 

264 

265 try: 

266 # Lazy import 

267 from opentelemetry.metrics import Observation 

268 

269 def connection_count_callback(): 

270 observations = [] 

271 for connection_pool in connection_pools: 

272 for count, attributes in connection_pool.get_connection_count(): 

273 observations.append(Observation(count, attributes=attributes)) 

274 return observations 

275 

276 observables_registry = get_observables_registry_instance() 

277 observables_registry.register( 

278 CONNECTION_COUNT_REGISTRY_KEY, connection_count_callback 

279 ) 

280 except Exception: 

281 pass 

282 

283 

284def record_connection_timeout( 

285 pool_name: str, 

286) -> None: 

287 """ 

288 Record a connection timeout event. 

289 

290 Args: 

291 pool_name: Connection pool identifier 

292 

293 Example: 

294 >>> record_connection_timeout('ConnectionPool<localhost:6379>') 

295 """ 

296 collector = _metrics_collector 

297 if collector is None: 

298 if _collector_resolved: 

299 return 

300 collector = _get_or_create_collector() 

301 if collector is None: 

302 return 

303 

304 try: 

305 collector.record_connection_timeout( 

306 pool_name=pool_name, 

307 ) 

308 except Exception: 

309 pass 

310 

311 

312def record_connection_wait_time( 

313 pool_name: str, 

314 duration_seconds: float, 

315) -> None: 

316 """ 

317 Record time taken to obtain a connection from the pool. 

318 

319 Args: 

320 pool_name: Connection pool identifier 

321 duration_seconds: Wait time in seconds 

322 

323 Example: 

324 >>> start = time.monotonic() 

325 >>> # ... wait for connection from pool ... 

326 >>> record_connection_wait_time('ConnectionPool<localhost:6379>', time.monotonic() - start) 

327 """ 

328 collector = _metrics_collector 

329 if collector is None: 

330 if _collector_resolved: 

331 return 

332 collector = _get_or_create_collector() 

333 if collector is None: 

334 return 

335 

336 try: 

337 collector.record_connection_wait_time( 

338 pool_name=pool_name, 

339 duration_seconds=duration_seconds, 

340 ) 

341 except Exception: 

342 pass 

343 

344 

345def record_connection_closed( 

346 close_reason: Optional[CloseReason] = None, 

347 error_type: Optional[Exception] = None, 

348) -> None: 

349 """ 

350 Record a connection closed event. 

351 

352 Args: 

353 close_reason: Reason for closing (e.g. 'error', 'application_close') 

354 error_type: Error type if closed due to error 

355 

356 Example: 

357 >>> record_connection_closed('ConnectionPool<localhost:6379>', 'idle_timeout') 

358 """ 

359 collector = _metrics_collector 

360 if collector is None: 

361 if _collector_resolved: 

362 return 

363 collector = _get_or_create_collector() 

364 if collector is None: 

365 return 

366 

367 try: 

368 collector.record_connection_closed( 

369 close_reason=close_reason, 

370 error_type=error_type, 

371 ) 

372 except Exception: 

373 pass 

374 

375 

376def record_connection_relaxed_timeout( 

377 connection_name: str, 

378 maint_notification: str, 

379 relaxed: bool, 

380) -> None: 

381 """ 

382 Record a connection timeout relaxation event. 

383 

384 Args: 

385 connection_name: Connection identifier 

386 maint_notification: Maintenance notification type 

387 relaxed: True to count up (relaxed), False to count down (unrelaxed) 

388 

389 Example: 

390 >>> record_connection_relaxed_timeout('localhost:6379_a1b2c3d4', 'MOVING', True) 

391 """ 

392 collector = _metrics_collector 

393 if collector is None: 

394 if _collector_resolved: 

395 return 

396 collector = _get_or_create_collector() 

397 if collector is None: 

398 return 

399 

400 try: 

401 collector.record_connection_relaxed_timeout( 

402 connection_name=connection_name, 

403 maint_notification=maint_notification, 

404 relaxed=relaxed, 

405 ) 

406 except Exception: 

407 pass 

408 

409 

410def record_connection_handoff( 

411 pool_name: str, 

412) -> None: 

413 """ 

414 Record a connection handoff event (e.g., after MOVING notification). 

415 

416 Args: 

417 pool_name: Connection pool identifier 

418 

419 Example: 

420 >>> record_connection_handoff('ConnectionPool<localhost:6379>') 

421 """ 

422 collector = _metrics_collector 

423 if collector is None: 

424 if _collector_resolved: 

425 return 

426 collector = _get_or_create_collector() 

427 if collector is None: 

428 return 

429 

430 try: 

431 collector.record_connection_handoff( 

432 pool_name=pool_name, 

433 ) 

434 except Exception: 

435 pass 

436 

437 

438def record_error_count( 

439 server_address: Optional[str] = None, 

440 server_port: Optional[int] = None, 

441 network_peer_address: Optional[str] = None, 

442 network_peer_port: Optional[int] = None, 

443 error_type: Optional[Exception] = None, 

444 retry_attempts: Optional[int] = None, 

445 is_internal: bool = True, 

446) -> None: 

447 """ 

448 Record error count. 

449 

450 Args: 

451 server_address: Server address 

452 server_port: Server port 

453 network_peer_address: Network peer address 

454 network_peer_port: Network peer port 

455 error_type: Error type (Exception) 

456 retry_attempts: Retry attempts 

457 is_internal: Whether the error is internal (e.g., timeout, network error) 

458 

459 Example: 

460 >>> record_error_count('localhost', 6379, 'localhost', 6379, ConnectionError(), 3) 

461 """ 

462 collector = _metrics_collector 

463 if collector is None: 

464 if _collector_resolved: 

465 return 

466 collector = _get_or_create_collector() 

467 if collector is None: 

468 return 

469 

470 try: 

471 collector.record_error_count( 

472 server_address=server_address, 

473 server_port=server_port, 

474 network_peer_address=network_peer_address, 

475 network_peer_port=network_peer_port, 

476 error_type=error_type, 

477 retry_attempts=retry_attempts, 

478 is_internal=is_internal, 

479 ) 

480 except Exception: 

481 pass 

482 

483 

484def record_pubsub_message( 

485 direction: PubSubDirection, 

486 channel: Optional[str] = None, 

487 sharded: Optional[bool] = None, 

488) -> None: 

489 """ 

490 Record a PubSub message (published or received). 

491 

492 Args: 

493 direction: Message direction ('publish' or 'receive') 

494 channel: Pub/Sub channel name 

495 sharded: True if sharded Pub/Sub channel 

496 

497 Example: 

498 >>> record_pubsub_message(PubSubDirection.PUBLISH, 'channel', False) 

499 """ 

500 collector = _metrics_collector 

501 if collector is None: 

502 if _collector_resolved: 

503 return 

504 collector = _get_or_create_collector() 

505 if collector is None: 

506 return 

507 

508 # Check if channel names should be hidden 

509 effective_channel = channel 

510 if channel is not None: 

511 config = _get_config() 

512 if config is not None and config.hide_pubsub_channel_names: 

513 effective_channel = None 

514 

515 try: 

516 collector.record_pubsub_message( 

517 direction=direction, 

518 channel=effective_channel, 

519 sharded=sharded, 

520 ) 

521 except Exception: 

522 pass 

523 

524 

525@deprecated_args( 

526 args_to_warn=["consumer_name"], 

527 reason="The consumer_name argument is no longer used and will be removed in the next major version.", 

528 version="7.2.1", 

529) 

530def record_streaming_lag( 

531 lag_seconds: float, 

532 stream_name: Optional[str] = None, 

533 consumer_group: Optional[str] = None, 

534 consumer_name: Optional[str] = None, # noqa 

535) -> None: 

536 """ 

537 Record the lag of a streaming message. 

538 

539 Args: 

540 lag_seconds: Lag in seconds 

541 stream_name: Stream name 

542 consumer_group: Consumer group name 

543 consumer_name: Consumer name 

544 """ 

545 collector = _metrics_collector 

546 if collector is None: 

547 if _collector_resolved: 

548 return 

549 collector = _get_or_create_collector() 

550 if collector is None: 

551 return 

552 

553 # Check if stream names should be hidden 

554 effective_stream_name = stream_name 

555 if stream_name is not None: 

556 config = _get_config() 

557 if config is not None and config.hide_stream_names: 

558 effective_stream_name = None 

559 

560 try: 

561 collector.record_streaming_lag( 

562 lag_seconds=lag_seconds, 

563 stream_name=effective_stream_name, 

564 consumer_group=consumer_group, 

565 ) 

566 except Exception: 

567 pass 

568 

569 

570@deprecated_args( 

571 args_to_warn=["consumer_name"], 

572 reason="The consumer_name argument is no longer used and will be removed in the next major version.", 

573 version="7.2.1", 

574) 

575def record_streaming_lag_from_response( 

576 response, 

577 consumer_group: Optional[str] = None, 

578 consumer_name: Optional[str] = None, # noqa 

579) -> None: 

580 """ 

581 Record streaming lag from XREAD/XREADGROUP response. 

582 

583 Parses the response and calculates lag for each message based on message ID timestamp. 

584 

585 Args: 

586 response: Response from XREAD/XREADGROUP command 

587 consumer_group: Consumer group name (for XREADGROUP) 

588 consumer_name: Consumer name (for XREADGROUP) 

589 """ 

590 

591 collector = _metrics_collector 

592 if collector is None: 

593 if _collector_resolved: 

594 return 

595 collector = _get_or_create_collector() 

596 if collector is None: 

597 return 

598 

599 if not response: 

600 return 

601 

602 try: 

603 now = datetime.now().timestamp() 

604 

605 # Check if stream names should be hidden 

606 config = _get_config() 

607 hide_stream_names = config is not None and config.hide_stream_names 

608 

609 # RESP3 format: dict 

610 if isinstance(response, dict): 

611 for stream_name, stream_messages in response.items(): 

612 effective_stream_name = ( 

613 None if hide_stream_names else str_if_bytes(stream_name) 

614 ) 

615 # Unified responses omit the legacy RESP3 wrapper around entries. 

616 if stream_messages and isinstance(stream_messages[0], tuple): 

617 stream_messages = [stream_messages] 

618 for messages in stream_messages: 

619 for message in messages: 

620 timestamp, _ = str_if_bytes(message[0]).split("-") 

621 # Ensure lag is non-negative (clock skew can cause negative values) 

622 lag_seconds = max(0.0, now - int(timestamp) / 1000) 

623 

624 collector.record_streaming_lag( 

625 lag_seconds=lag_seconds, 

626 stream_name=effective_stream_name, 

627 consumer_group=consumer_group, 

628 ) 

629 else: 

630 # RESP2 format: list 

631 for stream_entry in response: 

632 stream_name = str_if_bytes(stream_entry[0]) 

633 effective_stream_name = None if hide_stream_names else stream_name 

634 

635 for message in stream_entry[1]: 

636 timestamp, _ = str_if_bytes(message[0]).split("-") 

637 # Ensure lag is non-negative (clock skew can cause negative values) 

638 lag_seconds = max(0.0, now - int(timestamp) / 1000) 

639 

640 collector.record_streaming_lag( 

641 lag_seconds=lag_seconds, 

642 stream_name=effective_stream_name, 

643 consumer_group=consumer_group, 

644 ) 

645 except Exception: 

646 pass 

647 

648 

649def record_maint_notification_count( 

650 server_address: str, 

651 server_port: int, 

652 network_peer_address: str, 

653 network_peer_port: int, 

654 maint_notification: str, 

655) -> None: 

656 """ 

657 Record a maintenance notification count. 

658 

659 Args: 

660 server_address: Server address 

661 server_port: Server port 

662 network_peer_address: Network peer address 

663 network_peer_port: Network peer port 

664 maint_notification: Maintenance notification type (e.g., 'MOVING', 'MIGRATING') 

665 

666 Example: 

667 >>> record_maint_notification_count('localhost', 6379, 'localhost', 6379, 'MOVING') 

668 """ 

669 collector = _metrics_collector 

670 if collector is None: 

671 if _collector_resolved: 

672 return 

673 collector = _get_or_create_collector() 

674 if collector is None: 

675 return 

676 

677 try: 

678 collector.record_maint_notification_count( 

679 server_address=server_address, 

680 server_port=server_port, 

681 network_peer_address=network_peer_address, 

682 network_peer_port=network_peer_port, 

683 maint_notification=maint_notification, 

684 ) 

685 except Exception: 

686 pass 

687 

688 

689def record_csc_request( 

690 result: Optional[CSCResult] = None, 

691): 

692 """ 

693 Record a Client Side Caching (CSC) request. 

694 

695 Args: 

696 result: CSC result ('hit' or 'miss') 

697 """ 

698 collector = _metrics_collector 

699 if collector is None: 

700 if _collector_resolved: 

701 return 

702 collector = _get_or_create_collector() 

703 if collector is None: 

704 return 

705 

706 try: 

707 collector.record_csc_request( 

708 result=result, 

709 ) 

710 except Exception: 

711 pass 

712 

713 

714def init_csc_items() -> None: 

715 """ 

716 Initialize observable gauge for CSC items metric. 

717 """ 

718 collector = _metrics_collector 

719 if collector is None: 

720 if _collector_resolved: 

721 return 

722 collector = _get_or_create_collector() 

723 if collector is None: 

724 return 

725 

726 def observable_callback(__): 

727 observables_registry = get_observables_registry_instance() 

728 callbacks = observables_registry.get(CSC_ITEMS_REGISTRY_KEY) 

729 observations = [] 

730 

731 for callback in callbacks: 

732 observations.extend(callback()) 

733 

734 return observations 

735 

736 try: 

737 collector.init_csc_items( 

738 callback=observable_callback, 

739 ) 

740 except Exception: 

741 pass 

742 

743 

744def register_csc_items_callback( 

745 callback: Callable, 

746 pool_name: Optional[str] = None, 

747) -> None: 

748 """ 

749 Adds given callback to CSC items observable registry. 

750 

751 Args: 

752 callback: Callback function that returns the cache size 

753 pool_name: Connection pool name for observability 

754 """ 

755 collector = _metrics_collector 

756 if collector is None: 

757 if _collector_resolved: 

758 return 

759 collector = _get_or_create_collector() 

760 if collector is None: 

761 return 

762 

763 # Lazy import 

764 from opentelemetry.metrics import Observation 

765 

766 def csc_items_callback(): 

767 return [ 

768 Observation( 

769 callback(), 

770 attributes=AttributeBuilder.build_csc_attributes(pool_name=pool_name), 

771 ) 

772 ] 

773 

774 try: 

775 observables_registry = get_observables_registry_instance() 

776 observables_registry.register(CSC_ITEMS_REGISTRY_KEY, csc_items_callback) 

777 except Exception: 

778 pass 

779 

780 

781def record_csc_eviction( 

782 count: int, 

783 reason: Optional[CSCReason] = None, 

784) -> None: 

785 """ 

786 Record a Client Side Caching (CSC) eviction. 

787 

788 Args: 

789 count: Number of evictions 

790 reason: Reason for eviction 

791 """ 

792 collector = _metrics_collector 

793 if collector is None: 

794 if _collector_resolved: 

795 return 

796 collector = _get_or_create_collector() 

797 if collector is None: 

798 return 

799 

800 try: 

801 collector.record_csc_eviction( 

802 count=count, 

803 reason=reason, 

804 ) 

805 except Exception: 

806 pass 

807 

808 

809def record_csc_network_saved( 

810 bytes_saved: int, 

811) -> None: 

812 """ 

813 Record the number of bytes saved by using Client Side Caching (CSC). 

814 

815 Args: 

816 bytes_saved: Number of bytes saved 

817 """ 

818 collector = _metrics_collector 

819 if collector is None: 

820 if _collector_resolved: 

821 return 

822 collector = _get_or_create_collector() 

823 if collector is None: 

824 return 

825 

826 try: 

827 collector.record_csc_network_saved( 

828 bytes_saved=bytes_saved, 

829 ) 

830 except Exception: 

831 pass 

832 

833 

834def record_geo_failover( 

835 fail_from: "SyncDatabase", 

836 fail_to: "SyncDatabase", 

837 reason: GeoFailoverReason, 

838) -> None: 

839 """ 

840 Record a geo failover. 

841 

842 Args: 

843 fail_from: Database failed from 

844 fail_to: Database failed to 

845 reason: Reason for the failover 

846 """ 

847 collector = _metrics_collector 

848 if collector is None: 

849 if _collector_resolved: 

850 return 

851 collector = _get_or_create_collector() 

852 if collector is None: 

853 return 

854 

855 try: 

856 collector.record_geo_failover( 

857 fail_from=fail_from, 

858 fail_to=fail_to, 

859 reason=reason, 

860 ) 

861 except Exception: 

862 pass 

863 

864 

865def _get_or_create_collector() -> Optional[RedisMetricsCollector]: 

866 """ 

867 Get or create the global metrics collector. 

868 

869 Called only from the unresolved-miss branch of a recording helper, or from 

870 is_enabled(). The "resolved" flag is set *before* the lookup and the global 

871 is assigned only on a hit, so a lookup that races 

872 ``ObservabilityInstance.init()`` cannot publish a stale miss over the caches 

873 ``init()`` just reset: if the race is lost, the outcome is one completed 

874 lookup that returns ``None`` while observability is in fact enabled, and the 

875 next call resolves again. This mirrors 

876 ``redis.asyncio.observability.recorder._get_or_create_collector``. 

877 

878 Returns: 

879 RedisMetricsCollector instance if observability is enabled, None otherwise 

880 """ 

881 global _metrics_collector, _collector_resolved, _collector_generation 

882 

883 if _metrics_collector is not None: 

884 return _metrics_collector 

885 if _collector_resolved: 

886 # A previous lookup found observability disabled; keep the miss cached 

887 return None 

888 

889 generation = _collector_generation 

890 _collector_resolved = True 

891 

892 try: 

893 manager = get_observability_instance().get_provider_manager() 

894 if manager is None or not manager.config.enabled_telemetry: 

895 return None 

896 

897 # Get meter from the global MeterProvider 

898 meter = manager.get_meter_provider().get_meter( 

899 RedisMetricsCollector.METER_NAME, RedisMetricsCollector.METER_VERSION 

900 ) 

901 

902 _metrics_collector = RedisMetricsCollector(meter, manager.config) 

903 if _collector_generation != generation: 

904 # A reset landed while this resolution was in flight: the value 

905 # above describes the configuration that was just replaced, so 

906 # hand the cache back instead of publishing it. 

907 _metrics_collector = None 

908 _collector_resolved = False 

909 return _metrics_collector 

910 

911 except ImportError: 

912 # Observability module not available 

913 return None 

914 except Exception: 

915 # Any other error - don't break Redis operations 

916 return None 

917 

918 

919def _get_config() -> Optional["OTelConfig"]: 

920 """ 

921 Get the OTel configuration from the observability manager. 

922 

923 Returns: 

924 OTelConfig instance if observability is enabled, None otherwise 

925 """ 

926 try: 

927 manager = get_observability_instance().get_provider_manager() 

928 if manager is None: 

929 return None 

930 return manager.config 

931 except Exception: 

932 return None 

933 

934 

935def reset_collector() -> None: 

936 """ 

937 Reset the global collector (used for testing or re-initialization). 

938 """ 

939 global _metrics_collector, _collector_resolved, _collector_generation 

940 

941 _metrics_collector = None 

942 _collector_resolved = False 

943 _collector_generation += 1 

944 

945 

946def is_enabled() -> bool: 

947 """ 

948 Check if observability is enabled. 

949 

950 Returns: 

951 True if metrics are being collected, False otherwise 

952 """ 

953 return _get_or_create_collector() is not None 

954 

955 

956# Register this module's cache invalidation with the observability singleton, so 

957# ObservabilityInstance.init() drops the cached collector (see providers.py). 

958_register_reset_hook(reset_collector)