Skip to content

Commit 219558c

Browse files
committed
feat(google-api-core): add reactive UNAUTHENTICATED recovery to _RotatingGrpcChannel
1 parent 3b0f3b7 commit 219558c

2 files changed

Lines changed: 922 additions & 38 deletions

File tree

‎packages/google-api-core/google/api_core/grpc_helpers.py‎

Lines changed: 251 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,11 @@
1515
"""Helpers for :mod:`grpc`."""
1616

1717
import collections
18+
import contextlib
1819
import functools
1920
import os
2021
import threading
22+
import time
2123
import urllib.parse
2224
import warnings
2325
import weakref
@@ -890,6 +892,143 @@ def close(self):
890892
pass
891893

892894

895+
class _RotatingCall(grpc.Call, grpc.Future):
896+
"""Call and Future proxy that runs the rotation check when the call fails."""
897+
898+
def __init__(
899+
self,
900+
rotating_channel: "_RotatingGrpcChannel",
901+
channel: grpc.Channel,
902+
call: Any,
903+
attempt_gen: int,
904+
reopen_fn: Optional[Callable[[], Tuple[grpc.Channel, Any, int]]] = None,
905+
) -> None:
906+
self._rotating_channel = rotating_channel
907+
# Keep the inner channel alive for the lifetime of this call. With
908+
# grpcio's single-threaded unary-stream option, nothing else holds a
909+
# reference to it, and a garbage-collected channel cancels its calls.
910+
self._channel = channel
911+
self._call = call
912+
self._attempt_gen = attempt_gen
913+
self._reopen_fn = reopen_fn
914+
self._rotated: Optional[bool] = None
915+
916+
def _check_rotation(self, code: Optional[grpc.StatusCode]) -> bool:
917+
# Check at most once per attempt. result(), code() and the callbacks can
918+
# all see the same failure, and each check may reload the certificate.
919+
if code != grpc.StatusCode.UNAUTHENTICATED:
920+
return False
921+
if self._rotated is None:
922+
self._rotated = self._rotating_channel._rotate_on_unauthenticated(
923+
code, self._attempt_gen
924+
)
925+
return self._rotated
926+
927+
def __iter__(self) -> "_RotatingCall":
928+
return self
929+
930+
def __next__(self) -> Any:
931+
try:
932+
item = next(self._call)
933+
self._reopen_fn = None
934+
return item
935+
except grpc.RpcError as exc:
936+
reopen_fn = self._reopen_fn
937+
self._reopen_fn = None
938+
if self._check_rotation(exc.code()) and reopen_fn is not None:
939+
self._channel, self._call, self._attempt_gen = reopen_fn()
940+
self._rotated = None
941+
return next(self._call)
942+
raise
943+
944+
def cancel(self) -> Any:
945+
return self._call.cancel()
946+
947+
def cancelled(self) -> Any:
948+
return self._call.cancelled()
949+
950+
def running(self) -> Any:
951+
return self._call.running()
952+
953+
def done(self) -> Any:
954+
return self._call.done()
955+
956+
def result(self, timeout: Optional[float] = None) -> Any:
957+
try:
958+
return self._call.result(timeout=timeout)
959+
except grpc.RpcError as exc:
960+
self._check_rotation(exc.code())
961+
raise
962+
963+
def exception(self, timeout: Optional[float] = None) -> Any:
964+
exc = self._call.exception(timeout=timeout)
965+
if isinstance(exc, grpc.RpcError):
966+
self._check_rotation(exc.code())
967+
return exc
968+
969+
def traceback(self, timeout: Optional[float] = None) -> Any:
970+
return self._call.traceback(timeout=timeout)
971+
972+
def _check_rotation_from_callback(self, call: Any) -> None:
973+
# A unary-stream reopen replaces self._call only after checking the old
974+
# attempt, so skip callbacks from the replaced call.
975+
if call is not self._call:
976+
return
977+
# Callbacks run on grpcio's channel thread, where an exception would
978+
# skip the caller's callback (and, for add_callback, stop the thread).
979+
# A failed swap is retried by the next RPC's pre-call check.
980+
with contextlib.suppress(Exception):
981+
self._check_rotation(call.code())
982+
983+
def add_done_callback(self, fn: Callable[[Any], None]) -> Any:
984+
def _done_callback(future: Any) -> None:
985+
self._check_rotation_from_callback(future)
986+
# Pass grpcio's future, not self: bidi recovery needs a grpc.RpcError.
987+
fn(future)
988+
989+
return self._call.add_done_callback(_done_callback)
990+
991+
def add_callback(self, callback: Callable[[], None]) -> Any:
992+
call = self._call
993+
994+
def _callback() -> None:
995+
self._check_rotation_from_callback(call)
996+
callback()
997+
998+
# grpcio logs callbacks that raise via their .func attribute, so wrap
999+
# in a partial to keep that working.
1000+
return call.add_callback(functools.partial(_callback))
1001+
1002+
def is_active(self) -> Any:
1003+
return self._call.is_active()
1004+
1005+
def time_remaining(self) -> Any:
1006+
return self._call.time_remaining()
1007+
1008+
def code(self) -> Any:
1009+
status_code = self._call.code()
1010+
self._check_rotation(status_code)
1011+
return status_code
1012+
1013+
def details(self) -> Any:
1014+
return self._call.details()
1015+
1016+
def debug_error_string(self) -> Any:
1017+
return self._call.debug_error_string()
1018+
1019+
def initial_metadata(self) -> Any:
1020+
return self._call.initial_metadata()
1021+
1022+
def trailing_metadata(self) -> Any:
1023+
return self._call.trailing_metadata()
1024+
1025+
1026+
def _remaining_timeout(timeout: Optional[float], start_time: float) -> Optional[float]:
1027+
if timeout is None:
1028+
return None
1029+
return max(0.0, timeout - (time.monotonic() - start_time))
1030+
1031+
8931032
class _BaseRotatingMultiCallable:
8941033
"""Base helper for MultiCallable proxies bound to a _RotatingGrpcChannel."""
8951034

@@ -961,15 +1100,33 @@ def with_call(
9611100
wait_for_ready: Optional[bool] = None,
9621101
compression: Optional[grpc.Compression] = None,
9631102
) -> Tuple[Any, grpc.Call]:
964-
channel, _ = self._rotating_channel._get_active_channel_and_generation()
965-
return self._callable(channel).with_call(
966-
request,
967-
timeout=timeout,
968-
metadata=metadata,
969-
credentials=credentials,
970-
wait_for_ready=wait_for_ready,
971-
compression=compression,
1103+
start_time = time.monotonic()
1104+
channel, attempt_gen = (
1105+
self._rotating_channel._get_active_channel_and_generation()
9721106
)
1107+
try:
1108+
return self._callable(channel).with_call(
1109+
request,
1110+
timeout=timeout,
1111+
metadata=metadata,
1112+
credentials=credentials,
1113+
wait_for_ready=wait_for_ready,
1114+
compression=compression,
1115+
)
1116+
except grpc.RpcError as exc:
1117+
if not self._rotating_channel._rotate_on_unauthenticated(
1118+
exc.code(), attempt_gen
1119+
):
1120+
raise
1121+
new_channel, _ = self._rotating_channel._get_active_channel_and_generation()
1122+
return self._callable(new_channel).with_call(
1123+
request,
1124+
timeout=_remaining_timeout(timeout, start_time),
1125+
metadata=metadata,
1126+
credentials=credentials,
1127+
wait_for_ready=wait_for_ready,
1128+
compression=compression,
1129+
)
9731130

9741131
def future(
9751132
self,
@@ -979,16 +1136,19 @@ def future(
9791136
credentials: Optional[grpc.CallCredentials] = None,
9801137
wait_for_ready: Optional[bool] = None,
9811138
compression: Optional[grpc.Compression] = None,
982-
) -> grpc.Future:
983-
channel, _ = self._rotating_channel._get_active_channel_and_generation()
984-
return self._callable(channel).future(
1139+
) -> _RotatingCall:
1140+
channel, attempt_gen = (
1141+
self._rotating_channel._get_active_channel_and_generation()
1142+
)
1143+
call = self._callable(channel).future(
9851144
request,
9861145
timeout=timeout,
9871146
metadata=metadata,
9881147
credentials=credentials,
9891148
wait_for_ready=wait_for_ready,
9901149
compression=compression,
9911150
)
1151+
return _RotatingCall(self._rotating_channel, channel, call, attempt_gen)
9921152

9931153

9941154
class _RotatingUnaryStreamMultiCallable(
@@ -1006,15 +1166,31 @@ def __call__(
10061166
credentials: Optional[grpc.CallCredentials] = None,
10071167
wait_for_ready: Optional[bool] = None,
10081168
compression: Optional[grpc.Compression] = None,
1009-
) -> Any:
1010-
channel, _ = self._rotating_channel._get_active_channel_and_generation()
1011-
return self._callable(channel)(
1012-
request,
1013-
timeout=timeout,
1014-
metadata=metadata,
1015-
credentials=credentials,
1016-
wait_for_ready=wait_for_ready,
1017-
compression=compression,
1169+
) -> _RotatingCall:
1170+
def _start(
1171+
attempt_timeout: Optional[float],
1172+
) -> Tuple[grpc.Channel, Any, int]:
1173+
channel, attempt_gen = (
1174+
self._rotating_channel._get_active_channel_and_generation()
1175+
)
1176+
call = self._callable(channel)(
1177+
request,
1178+
timeout=attempt_timeout,
1179+
metadata=metadata,
1180+
credentials=credentials,
1181+
wait_for_ready=wait_for_ready,
1182+
compression=compression,
1183+
)
1184+
return channel, call, attempt_gen
1185+
1186+
start_time = time.monotonic()
1187+
channel, call, attempt_gen = _start(timeout)
1188+
return _RotatingCall(
1189+
self._rotating_channel,
1190+
channel,
1191+
call,
1192+
attempt_gen,
1193+
reopen_fn=lambda: _start(_remaining_timeout(timeout, start_time)),
10181194
)
10191195

10201196

@@ -1053,15 +1229,21 @@ def with_call(
10531229
wait_for_ready: Optional[bool] = None,
10541230
compression: Optional[grpc.Compression] = None,
10551231
) -> Tuple[Any, grpc.Call]:
1056-
channel, _ = self._rotating_channel._get_active_channel_and_generation()
1057-
return self._callable(channel).with_call(
1058-
request_iterator,
1059-
timeout=timeout,
1060-
metadata=metadata,
1061-
credentials=credentials,
1062-
wait_for_ready=wait_for_ready,
1063-
compression=compression,
1232+
channel, attempt_gen = (
1233+
self._rotating_channel._get_active_channel_and_generation()
10641234
)
1235+
try:
1236+
return self._callable(channel).with_call(
1237+
request_iterator,
1238+
timeout=timeout,
1239+
metadata=metadata,
1240+
credentials=credentials,
1241+
wait_for_ready=wait_for_ready,
1242+
compression=compression,
1243+
)
1244+
except grpc.RpcError as exc:
1245+
self._rotating_channel._rotate_on_unauthenticated(exc.code(), attempt_gen)
1246+
raise
10651247

10661248
def future(
10671249
self,
@@ -1071,16 +1253,19 @@ def future(
10711253
credentials: Optional[grpc.CallCredentials] = None,
10721254
wait_for_ready: Optional[bool] = None,
10731255
compression: Optional[grpc.Compression] = None,
1074-
) -> grpc.Future:
1075-
channel, _ = self._rotating_channel._get_active_channel_and_generation()
1076-
return self._callable(channel).future(
1256+
) -> _RotatingCall:
1257+
channel, attempt_gen = (
1258+
self._rotating_channel._get_active_channel_and_generation()
1259+
)
1260+
call = self._callable(channel).future(
10771261
request_iterator,
10781262
timeout=timeout,
10791263
metadata=metadata,
10801264
credentials=credentials,
10811265
wait_for_ready=wait_for_ready,
10821266
compression=compression,
10831267
)
1268+
return _RotatingCall(self._rotating_channel, channel, call, attempt_gen)
10841269

10851270

10861271
class _RotatingStreamStreamMultiCallable(
@@ -1098,16 +1283,19 @@ def __call__(
10981283
credentials: Optional[grpc.CallCredentials] = None,
10991284
wait_for_ready: Optional[bool] = None,
11001285
compression: Optional[grpc.Compression] = None,
1101-
) -> Any:
1102-
channel, _ = self._rotating_channel._get_active_channel_and_generation()
1103-
return self._callable(channel)(
1286+
) -> _RotatingCall:
1287+
channel, attempt_gen = (
1288+
self._rotating_channel._get_active_channel_and_generation()
1289+
)
1290+
call = self._callable(channel)(
11041291
request_iterator,
11051292
timeout=timeout,
11061293
metadata=metadata,
11071294
credentials=credentials,
11081295
wait_for_ready=wait_for_ready,
11091296
compression=compression,
11101297
)
1298+
return _RotatingCall(self._rotating_channel, channel, call, attempt_gen)
11111299

11121300

11131301
class _RotatingGrpcChannel(grpc.Channel):
@@ -1214,12 +1402,16 @@ def swap_channel(self, new_channel: Optional[grpc.Channel] = None) -> grpc.Chann
12141402
new_channel, generation = self._build_channel()
12151403
return self._install_channel_locked(new_channel, generation)
12161404

1217-
def _replace_stale_channel_locked(self) -> None:
1218-
"""Install a channel built with the current certificate if needed."""
1405+
def _replace_stale_channel_locked(self) -> bool:
1406+
"""Install a channel built with the current certificate if needed.
1407+
1408+
Returns ``False`` if the channel was closed.
1409+
"""
12191410
if self._closed:
1220-
return
1411+
return False
12211412
if self._cert_manager.generation_id > self._channel_generation_id:
12221413
self._install_channel_locked(*self._build_channel())
1414+
return True
12231415

12241416
def _get_active_channel_and_generation(self) -> Tuple[grpc.Channel, int]:
12251417
gen = self._channel_generation_id
@@ -1230,6 +1422,28 @@ def _get_active_channel_and_generation(self) -> Tuple[grpc.Channel, int]:
12301422
self._replace_stale_channel_locked()
12311423
return self._channel, self._channel_generation_id
12321424

1425+
def _rotate_on_unauthenticated(
1426+
self, code: Optional[grpc.StatusCode], attempt_gen: int
1427+
) -> bool:
1428+
"""Swap channels if a call failed because the certificate rotated.
1429+
1430+
Returns ``True`` if the certificate generation advanced past
1431+
``attempt_gen`` and the channel is still open, meaning the call can be
1432+
retried on the active channel.
1433+
"""
1434+
if (
1435+
code != grpc.StatusCode.UNAUTHENTICATED
1436+
or self._cert_manager is None
1437+
or self._closed
1438+
):
1439+
return False
1440+
if self._cert_manager.generation_id <= attempt_gen:
1441+
self._cert_manager.refresh(expected_generation=attempt_gen)
1442+
if self._cert_manager.generation_id <= attempt_gen:
1443+
return False
1444+
with self._lock:
1445+
return self._replace_stale_channel_locked()
1446+
12331447
def unary_unary(
12341448
self,
12351449
method: str,

0 commit comments

Comments
 (0)