Coverage for app/backend/src/couchers/bfc.py: 100%
24 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-16 22:03 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-16 22:03 +0000
1import time
2from functools import cache
4import grpc
6from couchers import metrics
7from couchers.config import config
8from couchers.proto.bfc import bfc_pb2, bfc_pb2_grpc
10TIMEOUT_SECONDS = 1.0
11CHANNEL_OPTIONS = [
12 ("grpc.max_reconnect_backoff_ms", 5_000),
13 ("grpc.keepalive_time_ms", 30_000),
14 ("grpc.keepalive_timeout_ms", 10_000),
15 ("grpc.keepalive_permit_without_calls", 1),
16 ("grpc.http2.max_pings_without_data", 0),
17]
20def is_configured() -> bool:
21 return bool(config.BFC_ADDRESS)
24# created on first use rather than at import, because a channel doesn't survive the fork into the API workers
25@cache
26def _stub(address: str) -> bfc_pb2_grpc.BFCStub:
27 return bfc_pb2_grpc.BFCStub(grpc.insecure_channel(address, options=CHANNEL_OPTIONS))
30def _call[Req, Res](method: str, fn: grpc.UnaryUnaryMultiCallable[Req, Res], request: Req) -> Res:
31 start = time.perf_counter()
32 try:
33 response = fn(request, timeout=TIMEOUT_SECONDS)
34 except grpc.RpcError as e:
35 metrics.observe_bfc_rpc(method, e.code().name, time.perf_counter() - start)
36 raise
37 metrics.observe_bfc_rpc(method, grpc.StatusCode.OK.name, time.perf_counter() - start)
38 return response
41def user_search(request: bfc_pb2.UserSearchReq) -> bfc_pb2.UserSearchRes:
42 return _call("UserSearch", _stub(config.BFC_ADDRESS).UserSearch, request)