Interceptors: middleware для gRPC
Interceptors: middleware для gRPC
Interceptors - аналог HTTP middleware для gRPC. Они оборачивают каждый RPC-вызов и решают cross-cutting concerns: логирование, аутентификация, метрики, recovery от паник, rate limiting, tracing. Без них код handler-ов превращается в копипасту boilerplate.
Unary interceptor - сигнатура
type UnaryServerInterceptor func(
ctx context.Context,
req any,
info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler,
) (any, error)
info.FullMethod даёт имя метода (/user.UserService/CreateUser). handler - следующий шаг в цепочке (либо следующий interceptor, либо собственно метод сервиса).
<?php
declare(strict_types=1);
namespace App\Grpc\Interceptor;
use Spiral\Interceptors\Context\CallContextInterface;
use Spiral\Interceptors\HandlerInterface;
use Spiral\Interceptors\InterceptorInterface;
interface LoggingInterceptorContract extends InterceptorInterface
{
// Сигнатура из spiral/interceptors:
// public function intercept(CallContextInterface $context, HandlerInterface $handler): mixed;
}
В PHP/RoadRunner interceptors реализуются через InterceptorInterface из spiral/roadrunner-grpc. Это middleware-цепочка, идейно такая же, как в Symfony Messenger или PSR-15.
Аналогия с Go: CallContextInterface ~ (ctx, req, info), HandlerInterface::handle() ~ вызов handler(ctx, req). Цепочка соответствует ChainUnaryInterceptor.
# grpc_interceptors/base.py
import abc
from typing import Any, Callable
import grpc
# Сигнатура «следующего звена»: метод сервиса или следующий interceptor.
UnaryHandler = Callable[[Any, grpc.ServicerContext], Any]
class UnaryServerInterceptor(grpc.ServerInterceptor, abc.ABC):
"""Сводит низкоуровневый grpc.ServerInterceptor к сигнатуре, как в Go.
В grpcio перехватчик получает не вызов, а описание метода
(handler_call_details) и должен вернуть RpcMethodHandler. Чтобы
обернуть сам вызов, подменяем функцию unary_unary у этого handler-а.
"""
@abc.abstractmethod
def intercept(
self,
request: Any,
context: grpc.ServicerContext,
method: str,
handler: UnaryHandler,
) -> Any: ...
def intercept_service(
self,
continuation: Callable[[grpc.HandlerCallDetails], grpc.RpcMethodHandler | None],
handler_call_details: grpc.HandlerCallDetails,
) -> grpc.RpcMethodHandler | None:
rpc = continuation(handler_call_details)
if rpc is None or rpc.unary_unary is None:
return rpc # стримы пропускаем как есть - для них см. раздел ниже
method = handler_call_details.method # /user.UserService/CreateUser
inner = rpc.unary_unary
def wrapped(request: Any, context: grpc.ServicerContext) -> Any:
return self.intercept(request, context, method, inner)
return grpc.unary_unary_rpc_method_handler(
wrapped,
request_deserializer=rpc.request_deserializer,
response_serializer=rpc.response_serializer,
)
handler_call_details.method даёт имя метода (/user.UserService/CreateUser), continuation - следующий шаг в цепочке. Низкоуровневый API grpc.ServerInterceptor оборачивает не вызов, а регистрацию handler-а, поэтому один раз пишется базовый класс с привычной сигнатурой intercept(request, context, method, handler); все interceptor-ы ниже наследуются от него. Готовый вариант такой обёртки есть в пакете grpc-interceptor.
Logging Interceptor
В проде обычно логируют не всё: на success - debug, на error - info/warn. Чувствительные поля req не пишут (пароли, токены).
func loggingInterceptor(
ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler,
) (any, error) {
start := time.Now()
resp, err := handler(ctx, req)
slog.Info("gRPC call",
"method", info.FullMethod,
"duration", time.Since(start),
"code", status.Code(err),
)
return resp, err
}
<?php
declare(strict_types=1);
namespace App\Grpc\Interceptor;
use Psr\Log\LoggerInterface;
use Spiral\Interceptors\Context\CallContextInterface;
use Spiral\Interceptors\HandlerInterface;
use Spiral\Interceptors\InterceptorInterface;
use Throwable;
final readonly class LoggingInterceptor implements InterceptorInterface
{
public function __construct(
private LoggerInterface $logger,
) {}
public function intercept(CallContextInterface $context, HandlerInterface $handler): mixed
{
$startedAt = hrtime(true);
$method = $context->getTarget()->getPath();
$code = 'OK';
try {
return $handler->handle($context);
} catch (Throwable $e) {
$code = 'ERROR';
throw $e;
} finally {
$durationMs = (int)((hrtime(true) - $startedAt) / 1_000_000);
$this->logger->info('gRPC call', [
'method' => implode('/', $method),
'duration' => $durationMs,
'code' => $code,
]);
}
}
}
import logging
import time
from typing import Any
import grpc
from grpc_interceptors.base import UnaryHandler, UnaryServerInterceptor
logger = logging.getLogger("grpc")
class LoggingInterceptor(UnaryServerInterceptor):
def intercept(self, request: Any, context: grpc.ServicerContext, method: str, handler: UnaryHandler) -> Any:
start = time.perf_counter()
try:
return handler(request, context)
finally:
# context.abort(...) завершает вызов исключением, код остаётся в context.code()
code = context.code() or grpc.StatusCode.OK
logger.info("gRPC call", extra={
"method": method,
"duration": time.perf_counter() - start,
"code": code.name,
})
Auth Interceptor
func authInterceptor(
ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler,
) (any, error) {
// Healthcheck без авторизации
if strings.HasPrefix(info.FullMethod, "/grpc.health.v1.") {
return handler(ctx, req)
}
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, status.Error(codes.Unauthenticated, "no metadata")
}
tokens := md.Get("authorization")
if len(tokens) == 0 {
return nil, status.Error(codes.Unauthenticated, "no token")
}
userID, err := validateToken(tokens[0])
if err != nil {
return nil, status.Error(codes.Unauthenticated, "invalid token")
}
// Прокидываем user_id в context для handler-ов
ctx = context.WithValue(ctx, userIDKey, userID)
return handler(ctx, req)
}
<?php
declare(strict_types=1);
namespace App\Grpc\Interceptor;
use App\Auth\TokenValidator;
use Spiral\Interceptors\Context\CallContextInterface;
use Spiral\Interceptors\HandlerInterface;
use Spiral\Interceptors\InterceptorInterface;
use Spiral\RoadRunner\GRPC\Exception\GRPCException;
use Spiral\RoadRunner\GRPC\StatusCode;
use Throwable;
final readonly class AuthInterceptor implements InterceptorInterface
{
public function __construct(
private TokenValidator $validator,
) {}
public function intercept(CallContextInterface $context, HandlerInterface $handler): mixed
{
$path = implode('/', $context->getTarget()->getPath());
if (str_starts_with($path, 'grpc.health.v1.')) {
return $handler->handle($context);
}
$ctx = $context->getArguments()[0]; // ContextInterface gRPC
$tokens = $ctx->getValue('authorization') ?? [];
$token = $tokens[0] ?? null;
if ($token === null) {
throw new GRPCException('no token', StatusCode::UNAUTHENTICATED);
}
try {
$userId = $this->validator->validate($token);
} catch (Throwable) {
throw new GRPCException('invalid token', StatusCode::UNAUTHENTICATED);
}
// Кладём user_id в attributes контекста для handler-ов
return $handler->handle($context->withAttribute('user_id', $userId));
}
}
from contextvars import ContextVar
from typing import Any, Callable
import grpc
from grpc_interceptors.base import UnaryHandler, UnaryServerInterceptor
# Аналог context.WithValue: handler-ы читают current_user_id.get().
# Каждый RPC выполняется в своём потоке пула, значение не утекает между вызовами.
current_user_id: ContextVar[str] = ContextVar("current_user_id")
class AuthInterceptor(UnaryServerInterceptor):
def __init__(self, validate_token: Callable[[str], str]) -> None:
self._validate_token = validate_token
def intercept(self, request: Any, context: grpc.ServicerContext, method: str, handler: UnaryHandler) -> Any:
# Healthcheck без авторизации
if method.startswith("/grpc.health.v1."):
return handler(request, context)
tokens = [value for key, value in context.invocation_metadata() if key == "authorization"]
if not tokens:
context.abort(grpc.StatusCode.UNAUTHENTICATED, "no token")
try:
user_id = self._validate_token(tokens[0])
except ValueError:
context.abort(grpc.StatusCode.UNAUTHENTICATED, "invalid token")
# Прокидываем user_id в context для handler-ов
token = current_user_id.set(user_id)
try:
return handler(request, context)
finally:
current_user_id.reset(token)
Стандартная практика: проверка токена один раз в interceptor, user_id - в context. Все handler-ы читают user_id из context, не повторяя auth-логику.
Recovery Interceptor
func recoveryInterceptor(
ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler,
) (resp any, err error) {
defer func() {
if r := recover(); r != nil {
slog.Error("panic recovered",
"method", info.FullMethod,
"recovered", r,
"stack", string(debug.Stack()),
)
err = status.Error(codes.Internal, "internal error")
}
}()
return handler(ctx, req)
}
<?php
declare(strict_types=1);
namespace App\Grpc\Interceptor;
use Psr\Log\LoggerInterface;
use Spiral\Interceptors\Context\CallContextInterface;
use Spiral\Interceptors\HandlerInterface;
use Spiral\Interceptors\InterceptorInterface;
use Spiral\RoadRunner\GRPC\Exception\GRPCException;
use Spiral\RoadRunner\GRPC\StatusCode;
use Throwable;
final readonly class RecoveryInterceptor implements InterceptorInterface
{
public function __construct(
private LoggerInterface $logger,
) {}
public function intercept(CallContextInterface $context, HandlerInterface $handler): mixed
{
try {
return $handler->handle($context);
} catch (GRPCException $e) {
throw $e; // явные gRPC-ошибки пропускаем
} catch (Throwable $e) {
$this->logger->error('panic recovered', [
'method' => implode('/', $context->getTarget()->getPath()),
'message' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
throw new GRPCException('internal error', StatusCode::INTERNAL);
}
}
}
В PHP recover() не нужен - есть try/catch. Превращаем любое неотловленное исключение в Internal.
import logging
import traceback
from typing import Any
import grpc
from grpc_interceptors.base import UnaryHandler, UnaryServerInterceptor
logger = logging.getLogger("grpc")
class RecoveryInterceptor(UnaryServerInterceptor):
def intercept(self, request: Any, context: grpc.ServicerContext, method: str, handler: UnaryHandler) -> Any:
try:
return handler(request, context)
except Exception as err:
if context.code() is not None:
raise # явный context.abort(...) - статус уже выставлен, пропускаем
logger.error("panic recovered", extra={
"method": method,
"recovered": repr(err),
"stack": traceback.format_exc(),
})
context.abort(grpc.StatusCode.INTERNAL, "internal error")
recover() не нужен - есть try/except. Нюанс grpcio: context.abort() сам реализован через исключение, поэтому «ошибку со статусом» от настоящего падения отличаем по context.code(). Без такого interceptor-а необработанное исключение grpcio превращает в Unknown с текстом исключения - сервер не упадёт, но детали утекут клиенту.
Без recovery panic в одном handler-е роняет весь сервер. Это первый interceptor в цепочке - должен обернуть всё.
Rate Limiting Interceptor
func rateLimitInterceptor(limiter *rate.Limiter) grpc.UnaryServerInterceptor {
return func(
ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler,
) (any, error) {
if !limiter.Allow() {
return nil, status.Error(codes.ResourceExhausted, "rate limit exceeded")
}
return handler(ctx, req)
}
}
golang.org/x/time/rate даёт token bucket из коробки. Для per-IP лимитирования держат map[ip]*rate.Limiter с TTL-cleanup.
<?php
declare(strict_types=1);
namespace App\Grpc\Interceptor;
use Spiral\Interceptors\Context\CallContextInterface;
use Spiral\Interceptors\HandlerInterface;
use Spiral\Interceptors\InterceptorInterface;
use Spiral\RoadRunner\GRPC\Exception\GRPCException;
use Spiral\RoadRunner\GRPC\StatusCode;
use Symfony\Component\RateLimiter\LimiterInterface;
final readonly class RateLimitInterceptor implements InterceptorInterface
{
public function __construct(
private LimiterInterface $limiter,
) {}
public function intercept(CallContextInterface $context, HandlerInterface $handler): mixed
{
if (!$this->limiter->consume(1)->isAccepted()) {
throw new GRPCException('rate limit exceeded', StatusCode::RESOURCE_EXHAUSTED);
}
return $handler->handle($context);
}
}
В PHP token bucket удобно сделать на symfony/rate-limiter.
import threading
import time
from typing import Any
import grpc
from grpc_interceptors.base import UnaryHandler, UnaryServerInterceptor
class TokenBucket:
"""Минимальный token bucket; готовые - пакеты pyrate-limiter или limits."""
def __init__(self, rate: float, burst: int) -> None:
self._rate = rate
self._capacity = burst
self._tokens = float(burst)
self._updated = time.monotonic()
self._lock = threading.Lock()
def allow(self) -> bool:
with self._lock:
now = time.monotonic()
self._tokens = min(self._capacity, self._tokens + (now - self._updated) * self._rate)
self._updated = now
if self._tokens < 1:
return False
self._tokens -= 1
return True
class RateLimitInterceptor(UnaryServerInterceptor):
def __init__(self, limiter: TokenBucket) -> None:
self._limiter = limiter
def intercept(self, request: Any, context: grpc.ServicerContext, method: str, handler: UnaryHandler) -> Any:
if not self._limiter.allow():
context.abort(grpc.StatusCode.RESOURCE_EXHAUSTED, "rate limit exceeded")
return handler(request, context)
В stdlib token bucket нет, поэтому он выписан руками (lock нужен: пул потоков сервера зовёт allow() параллельно). Для per-IP лимитирования держат dict[ip, TokenBucket] с TTL-cleanup.
Metrics Interceptor
var (
rpcDuration = prometheus.NewHistogramVec(
prometheus.HistogramOpts{Name: "grpc_server_duration_seconds"},
[]string{"method", "code"},
)
)
func metricsInterceptor(
ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler,
) (any, error) {
start := time.Now()
resp, err := handler(ctx, req)
rpcDuration.WithLabelValues(info.FullMethod, status.Code(err).String()).
Observe(time.Since(start).Seconds())
return resp, err
}
Готовая библиотека - github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus - даёт стандартные метрики из коробки (старый пакет go-grpc-prometheus заархивирован, метрики переехали туда).
<?php
declare(strict_types=1);
namespace App\Grpc\Interceptor;
use Prometheus\Histogram;
use Spiral\Interceptors\Context\CallContextInterface;
use Spiral\Interceptors\HandlerInterface;
use Spiral\Interceptors\InterceptorInterface;
use Spiral\RoadRunner\GRPC\Exception\GRPCException;
use Throwable;
final readonly class MetricsInterceptor implements InterceptorInterface
{
public function __construct(
private Histogram $rpcDuration,
) {}
public function intercept(CallContextInterface $context, HandlerInterface $handler): mixed
{
$startedAt = hrtime(true);
$method = implode('/', $context->getTarget()->getPath());
$code = 'OK';
try {
return $handler->handle($context);
} catch (GRPCException $e) {
$code = (string)$e->getCode();
throw $e;
} catch (Throwable $e) {
$code = 'INTERNAL';
throw $e;
} finally {
$durationSec = (hrtime(true) - $startedAt) / 1_000_000_000;
$this->rpcDuration->observe($durationSec, [$method, $code]);
}
}
}
PHP-эквивалент - promphp/prometheus_client_php плюс interceptor.
import time
from typing import Any
import grpc
from prometheus_client import Histogram
from grpc_interceptors.base import UnaryHandler, UnaryServerInterceptor
rpc_duration = Histogram(
"grpc_server_duration_seconds",
"gRPC server call duration",
["method", "code"],
)
class MetricsInterceptor(UnaryServerInterceptor):
def intercept(self, request: Any, context: grpc.ServicerContext, method: str, handler: UnaryHandler) -> Any:
start = time.perf_counter()
try:
return handler(request, context)
finally:
code = context.code() or grpc.StatusCode.OK
rpc_duration.labels(method, code.name).observe(time.perf_counter() - start)
Готовая библиотека - py-grpc-prometheus (PromServerInterceptor) - даёт стандартные метрики из коробки.
Цепочка interceptors
grpcServer := grpc.NewServer(
// Tracing в актуальном otelgrpc подключается не interceptor-ом, а stats handler-ом:
// он видит весь вызов целиком, раньше любого interceptor-а.
// (otelgrpc.UnaryServerInterceptor из старых статей удалён из библиотеки.)
grpc.StatsHandler(otelgrpc.NewServerHandler()),
grpc.ChainUnaryInterceptor(
recoveryInterceptor, // 1. защита от panic
metricsInterceptor, // 2. метрики
loggingInterceptor, // 3. логирование
authInterceptor, // 4. auth
rateLimitInterceptor(limiter), // 5. rate limit (после auth - лимитируем по user)
),
)
<?php
declare(strict_types=1);
use App\Grpc\Interceptor\AuthInterceptor;
use App\Grpc\Interceptor\LoggingInterceptor;
use App\Grpc\Interceptor\MetricsInterceptor;
use App\Grpc\Interceptor\RateLimitInterceptor;
use App\Grpc\Interceptor\RecoveryInterceptor;
use App\Grpc\Interceptor\TracingInterceptor;
use Spiral\Interceptors\PipelineBuilder;
$pipeline = (new PipelineBuilder())
->withInterceptors(
$container->get(RecoveryInterceptor::class), // 1. ловим всё
$container->get(TracingInterceptor::class), // 2. tracing - перед остальным
$container->get(MetricsInterceptor::class), // 3. метрики
$container->get(LoggingInterceptor::class), // 4. логи
$container->get(AuthInterceptor::class), // 5. auth
$container->get(RateLimitInterceptor::class), // 6. rate limit
)
->build($finalHandler);
В RoadRunner цепочка собирается из списка InterceptorInterface через PipelineBuilder.
from concurrent import futures
import grpc
# pip install opentelemetry-instrumentation-grpc
from opentelemetry.instrumentation.grpc import server_interceptor
grpc_server = grpc.server(
futures.ThreadPoolExecutor(max_workers=10),
interceptors=[
RecoveryInterceptor(), # 1. защита от необработанных исключений
server_interceptor(), # 2. tracing - раньше всего, чтобы видеть в трейсе
MetricsInterceptor(), # 3. метрики
LoggingInterceptor(), # 4. логирование
AuthInterceptor(validate_token), # 5. auth
RateLimitInterceptor(TokenBucket(rate=100, burst=200)), # 6. rate limit (после auth - лимитируем по user)
],
)
Цепочка передаётся аргументом interceptors= в grpc.server(); первый в списке - внешний, как в ChainUnaryInterceptor.
Interceptors выполняются в порядке передачи в ChainUnaryInterceptor, как матрёшка: первый - самый внешний слой, его код до вызова handler выполняется первым, а после - последним. Порядок важен: recovery обёртывает всё (включая последующие interceptors), tracing идёт рано чтобы покрыть весь обработчик (в Go это делает stats handler, он снаружи всей цепочки), auth/rate limit ближе к handler-у.
Stream interceptors
type StreamServerInterceptor func(
srv any,
ss grpc.ServerStream,
info *grpc.StreamServerInfo,
handler grpc.StreamHandler,
) error
Сложнее unary: нужно обернуть ServerStream в proxy-объект, чтобы перехватывать Send/Recv. Например, для логирования каждого сообщения в stream-е.
Unary-версия тут не подойдёт: она вызывается один раз на весь стрим, а сообщений в server-, client- и bidirectional-стримах может быть тысячи, и считать их надо по одному.
type wrappedStream struct {
grpc.ServerStream
logger *slog.Logger
}
func (w *wrappedStream) RecvMsg(m any) error {
err := w.ServerStream.RecvMsg(m)
w.logger.Debug("recv", "msg", m, "err", err)
return err
}
В PHP stream-interceptor-ов нет, потому что оборачивать нечего: gRPC-сервер на RoadRunner обслуживает только unary-методы (подробнее в уроке про стриминг). Для unary хватает обычного InterceptorInterface из примеров выше. Если стримы нужны, их обслуживает сервис на Go, и stream-interceptor пишется там.
# Отдельной сигнатуры под stream нет: тот же grpc.ServerInterceptor,
# но у RpcMethodHandler заполнено одно из полей unary_stream,
# stream_unary или stream_stream вместо unary_unary.
class StreamLoggingInterceptor(grpc.ServerInterceptor):
def intercept_service(
self,
continuation: Callable[[grpc.HandlerCallDetails], grpc.RpcMethodHandler | None],
handler_call_details: grpc.HandlerCallDetails,
) -> grpc.RpcMethodHandler | None:
rpc = continuation(handler_call_details)
if rpc is None or rpc.stream_unary is None:
return rpc
...
Сложнее unary: входящие сообщения приходят итератором, поэтому для перехвата Recv заворачивают request_iterator в свой генератор (аналог proxy-объекта над ServerStream). Например, для логирования каждого сообщения в stream-е.
Unary-версия тут не подойдёт: она вызывается один раз на весь стрим, а сообщений в server-, client- и bidirectional-стримах может быть тысячи, и считать их надо по одному.
import logging
from collections.abc import Iterator
from typing import Any, Callable
import grpc
logger = logging.getLogger("grpc")
def _wrap_recv(request_iterator: Iterator[Any]) -> Iterator[Any]:
for msg in request_iterator:
logger.debug("recv", extra={"msg": msg})
yield msg
class StreamLoggingInterceptor(grpc.ServerInterceptor):
def intercept_service(
self,
continuation: Callable[[grpc.HandlerCallDetails], grpc.RpcMethodHandler | None],
handler_call_details: grpc.HandlerCallDetails,
) -> grpc.RpcMethodHandler | None:
rpc = continuation(handler_call_details)
if rpc is None or rpc.stream_unary is None:
return rpc
inner = rpc.stream_unary
# Подменяем stream_unary обёрткой: handler получит итератор с логированием
def wrapped(request_iterator: Iterator[Any], context: grpc.ServicerContext) -> Any:
return inner(_wrap_recv(request_iterator), context)
return grpc.stream_unary_rpc_method_handler(
wrapped,
request_deserializer=rpc.request_deserializer,
response_serializer=rpc.response_serializer,
)
Client-side interceptors
Симметричны server-side: тоже Unary и Stream варианты, оборачивают исходящие RPC. Применяются для retry, добавления auth-токена, метрик клиента.
conn, err := grpc.NewClient(addr,
grpc.WithStatsHandler(otelgrpc.NewClientHandler()), // tracing
grpc.WithChainUnaryInterceptor(retryInterceptor(3)), // свой retry, логика как в PHP/Python ниже
)
if err != nil {
log.Fatal(err)
}
Ловушка: два вызова grpc.WithUnaryInterceptor подряд цепочку не образуют - второй молча перезаписывает первый. Несколько клиентских interceptor-ов передают только через grpc.WithChainUnaryInterceptor.
<?php
declare(strict_types=1);
namespace App\Grpc\Client;
use Grpc\UnaryCall;
use User\UserServiceClient;
// Константы ext-grpc импортируются через use const; обычный use импортирует класс
use const Grpc\STATUS_DEADLINE_EXCEEDED;
use const Grpc\STATUS_UNAVAILABLE;
final class RetryingUserServiceClient extends UserServiceClient
{
public function __construct(
string $hostname,
array $opts,
private readonly int $maxAttempts = 3,
) {
parent::__construct($hostname, $opts);
}
protected function _simpleRequest(
string $method,
$argument,
$deserialize,
array $metadata = [],
array $options = []
): UnaryCall {
$attempt = 0;
while (true) {
$call = parent::_simpleRequest($method, $argument, $deserialize, $metadata, $options);
[$response, $status] = $call->wait();
$retryable = in_array(
$status->code,
[STATUS_UNAVAILABLE, STATUS_DEADLINE_EXCEEDED],
true,
);
if (!$retryable || ++$attempt >= $this->maxAttempts) {
return $call;
}
usleep(100_000 * $attempt); // линейный backoff
}
}
}
В PHP client-side interceptors реализуются переопределением BaseStub::_simpleRequest в потомке или декорированием stub-а на уровне DI. Symfony Messenger middleware - точная аналогия паттерна.
import time
from typing import Any, Callable
import grpc
from opentelemetry.instrumentation.grpc import client_interceptor
RETRYABLE = {grpc.StatusCode.UNAVAILABLE, grpc.StatusCode.DEADLINE_EXCEEDED}
class RetryInterceptor(grpc.UnaryUnaryClientInterceptor):
def __init__(self, max_attempts: int = 3) -> None:
self._max_attempts = max_attempts
def intercept_unary_unary(
self,
continuation: Callable[[grpc.ClientCallDetails, Any], grpc.Call],
client_call_details: grpc.ClientCallDetails,
request: Any,
) -> grpc.Call:
attempt = 0
while True:
# continuation выполняет вызов; результат - объект Call (и Future), ошибка не бросается
call = continuation(client_call_details, request)
attempt += 1
if call.code() not in RETRYABLE or attempt >= self._max_attempts:
return call
time.sleep(0.1 * attempt) # линейный backoff
channel = grpc.intercept_channel(
grpc.insecure_channel(addr),
client_interceptor(), # tracing
RetryInterceptor(3),
)
client = pb_grpc.UserServiceStub(channel)
Осторожно с повторами. Повторять безопасно только идемпотентные методы (чтение, или запись с idempotency key). DEADLINE_EXCEEDED особенно коварен: сервер мог уже выполнить операцию (например, CreateUser), и повтор создаст дубль. Кроме того, общий deadline должен покрывать все попытки, а не выдаваться каждой заново. Это правило касается любого retry-interceptor-а, на каком бы языке он ни был написан.
Клиентские перехватчики - классы grpc.UnaryUnaryClientInterceptor (и StreamUnary..., UnaryStream..., StreamStream...), навешиваются через grpc.intercept_channel. В отличие от серверной стороны, здесь continuation оборачивает именно вызов, так что базовый класс не нужен.
Circuit Breaker (client-side)
Retry без circuit breaker = «retry storm»: упавший downstream-сервис добивается лавиной повторов. Circuit breaker «размыкает цепь» на N секунд после порога ошибок - даёт сервису восстановиться, а текущим запросам быстрый fail вместо таймаута.
import (
"github.com/sony/gobreaker"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func circuitBreakerInterceptor(cb *gobreaker.CircuitBreaker) grpc.UnaryClientInterceptor {
return func(
ctx context.Context, method string, req, reply any,
cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption,
) error {
_, err := cb.Execute(func() (any, error) {
return nil, invoker(ctx, method, req, reply, cc, opts...)
})
return err
}
}
cb := gobreaker.NewCircuitBreaker(gobreaker.Settings{
Name: "user-service",
MaxRequests: 3, // полуоткрытое состояние: 3 пробных запроса
Interval: 60 * time.Second,
Timeout: 30 * time.Second, // как долго быть «открытым»
ReadyToTrip: func(c gobreaker.Counts) bool {
return c.ConsecutiveFailures >= 5 // открыть после 5 подряд ошибок
},
// Отказом считаем только «сервис болен»; NotFound, InvalidArgument и т.п. -
// нормальный ответ на плохой запрос, breaker их засчитывает как успех.
IsSuccessful: func(err error) bool {
switch status.Code(err) {
case codes.Unavailable, codes.DeadlineExceeded, codes.Internal:
return false
}
return true
},
})
<?php
declare(strict_types=1);
namespace App\Grpc\Client;
use Ackintosh\Ganesha;
use Grpc\UnaryCall;
use User\UserServiceClient;
use RuntimeException;
use const Grpc\STATUS_DEADLINE_EXCEEDED;
use const Grpc\STATUS_INTERNAL;
use const Grpc\STATUS_UNAVAILABLE;
final class CircuitBreakerUserServiceClient extends UserServiceClient
{
private const SERVICE = 'user-service';
public function __construct(
string $hostname,
array $opts,
private readonly Ganesha $ganesha,
) {
parent::__construct($hostname, $opts);
}
protected function _simpleRequest(
string $method,
$argument,
$deserialize,
array $metadata = [],
array $options = []
): UnaryCall {
if (!$this->ganesha->isAvailable(self::SERVICE)) {
throw new RuntimeException('circuit open: user-service');
}
$call = parent::_simpleRequest($method, $argument, $deserialize, $metadata, $options);
[$response, $status] = $call->wait();
$isFailure = in_array(
$status->code,
[STATUS_UNAVAILABLE, STATUS_DEADLINE_EXCEEDED, STATUS_INTERNAL],
true,
);
$isFailure
? $this->ganesha->failure(self::SERVICE)
: $this->ganesha->success(self::SERVICE);
return $call;
}
}
В PHP можно взять ackintosh/ganesha - готовый circuit breaker с in-memory или Redis-storage. Декорируем gRPC-stub.
# pip install pybreaker
from typing import Any, Callable
import grpc
import pybreaker
FAILURE_CODES = {
grpc.StatusCode.UNAVAILABLE,
grpc.StatusCode.DEADLINE_EXCEEDED,
grpc.StatusCode.INTERNAL,
}
class CircuitBreakerInterceptor(grpc.UnaryUnaryClientInterceptor):
def __init__(self, breaker: pybreaker.CircuitBreaker) -> None:
self._breaker = breaker
def intercept_unary_unary(
self,
continuation: Callable[[grpc.ClientCallDetails, Any], grpc.Call],
client_call_details: grpc.ClientCallDetails,
request: Any,
) -> grpc.Call:
def invoke() -> grpc.Call:
call = continuation(client_call_details, request)
if call.code() in FAILURE_CODES:
call.result() # бросит RpcError - breaker засчитает ошибку
return call
# В открытом состоянии call() сразу бросает pybreaker.CircuitBreakerError
return self._breaker.call(invoke)
breaker = pybreaker.CircuitBreaker(
name="user-service",
fail_max=5, # открыть после 5 подряд ошибок
reset_timeout=30, # как долго быть «открытым», секунд
)
Здесь взят pybreaker. NotFound и InvalidArgument в FAILURE_CODES не входят - такие вызовы breaker считает успешными. В half-open состоянии pybreaker пропускает один пробный запрос (у gobreaker их число настраивается через MaxRequests).
Состояния: Поведение
──────────────── ─────────────────────────────────────
closed (норма) все запросы летят к сервису
open (сработал) запросы сразу fail (ErrOpenState),
сервис не нагружается
half-open (проба) пускаем N пробных; OK - закрываем,
fail - снова open
Какие коды считать «ошибкой»: Unavailable, DeadlineExceeded, Internal - да. NotFound, InvalidArgument - нет (это не «сервис упал», это правильный ответ на плохой запрос).
Error model: status.Error, codes, error wrapping
gRPC использует отдельный механизм ошибок - не возвращайте обычные Go errors из handler-ов. Какой код за что отвечает и почему Unavailable считается кодом, который безопасно повторить (сам повтор настраивается retryPolicy в service config или retry-interceptor-ом выше), разобрано в таблице gRPC-кодов. Если перед сервисом стоит gRPC-Gateway, выбранный код заодно превратится в HTTP-статус для REST-клиента: поставил Internal вместо NotFound - и браузер увидит 500 там, где ждал 404.
// Плохо: клиент получит code=Unknown с непонятным сообщением
func (s *server) Get(ctx context.Context, req *pb.GetReq) (*pb.GetResp, error) {
if req.Id == "" {
return nil, errors.New("id is required")
}
user, err := s.repo.Get(ctx, req.Id)
if err != nil {
return nil, err // утечёт текст SQL-ошибки!
}
return &pb.GetResp{User: user}, nil
}
// Хорошо: статусы и понятные коды
func (s *server) Get(ctx context.Context, req *pb.GetReq) (*pb.GetResp, error) {
if req.Id == "" {
return nil, status.Error(codes.InvalidArgument, "id is required")
}
user, err := s.repo.Get(ctx, req.Id)
switch {
case errors.Is(err, repo.ErrNotFound):
return nil, status.Error(codes.NotFound, "user not found")
case err != nil:
slog.Error("repo.Get failed", "err", err) // детали - в лог
return nil, status.Error(codes.Internal, "internal error") // клиенту - обобщённо
}
return &pb.GetResp{User: user}, nil
}
Что приходит клиенту Это
────────────────────────── ────────────────────────────────────────
err из вызова RPC Go error; работает errors.Is/As
status.FromError(err) *status.Status - code, message, details
st.Code() codes.NotFound, codes.Internal, ...
status.Code(err) удобный шорткат → codes.Code
st.Details() структурированные детали (BadRequest и др.)
<?php
declare(strict_types=1);
namespace App\Grpc;
use App\Domain\Exception\UserNotFoundException;
use App\Domain\UserRepository;
use Psr\Log\LoggerInterface;
use Spiral\RoadRunner\GRPC\ContextInterface;
use Spiral\RoadRunner\GRPC\Exception\GRPCException;
use Spiral\RoadRunner\GRPC\StatusCode;
use Throwable;
use User\GetReq;
use User\GetResp;
final readonly class UserGetHandler
{
public function __construct(
private UserRepository $repo,
private LoggerInterface $logger,
) {}
public function Get(ContextInterface $ctx, GetReq $req): GetResp
{
if ($req->getId() === '') {
throw new GRPCException('id is required', StatusCode::INVALID_ARGUMENT);
}
try {
$user = $this->repo->get($req->getId());
} catch (UserNotFoundException) {
throw new GRPCException('user not found', StatusCode::NOT_FOUND);
} catch (Throwable $e) {
$this->logger->error('repo.get failed', ['err' => $e->getMessage()]);
throw new GRPCException('internal error', StatusCode::INTERNAL);
}
return (new GetResp())->setUser($user);
}
}
В PHP та же логика - доменные исключения транслируем в GRPCException с явным StatusCode.
import logging
import grpc
logger = logging.getLogger(__name__)
# Плохо: клиент получит code=Unknown с непонятным сообщением
class UserServer(pb_grpc.UserServiceServicer):
def Get(self, request: pb.GetReq, context: grpc.ServicerContext) -> pb.GetResp:
if request.id == "":
raise ValueError("id is required")
user = self._repo.get(request.id) # исключение репозитория утечёт: текст SQL-ошибки!
return pb.GetResp(user=user)
# Хорошо: статусы и понятные коды
class UserServer(pb_grpc.UserServiceServicer):
def Get(self, request: pb.GetReq, context: grpc.ServicerContext) -> pb.GetResp:
if request.id == "":
context.abort(grpc.StatusCode.INVALID_ARGUMENT, "id is required")
try:
user = self._repo.get(request.id)
except repo.NotFoundError:
context.abort(grpc.StatusCode.NOT_FOUND, "user not found")
except Exception as err:
logger.error("repo.get failed", extra={"err": str(err)}) # детали - в лог
context.abort(grpc.StatusCode.INTERNAL, "internal error") # клиенту - обобщённо
return pb.GetResp(user=user)
Что приходит клиенту Это
────────────────────────── ────────────────────────────────────────
except grpc.RpcError as err исключение; одновременно grpc.Call
err.code() grpc.StatusCode.NOT_FOUND, .INTERNAL, ...
err.details() сообщение статуса (строка)
rpc_status.from_call(err) google.rpc.Status с полем details
(BadRequest и др., пакет grpcio-status)
Маппинг доменных ошибок в gRPC-коды - задача handler-а или error mapping interceptor-а:
func errorMapInterceptor(
ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler,
) (any, error) {
resp, err := handler(ctx, req)
if err == nil {
return resp, nil
}
if _, ok := status.FromError(err); ok {
return nil, err // уже status - пропускаем
}
switch {
case errors.Is(err, domain.ErrNotFound):
return nil, status.Error(codes.NotFound, err.Error())
case errors.Is(err, domain.ErrValidation):
return nil, status.Error(codes.InvalidArgument, err.Error())
case errors.Is(err, context.DeadlineExceeded):
return nil, status.Error(codes.DeadlineExceeded, "request timed out")
default:
slog.Error("unhandled", "method", info.FullMethod, "err", err)
return nil, status.Error(codes.Internal, "internal error")
}
}
<?php
declare(strict_types=1);
namespace App\Grpc\Interceptor;
use App\Domain\Exception\DomainException;
use App\Domain\Exception\NotFoundException;
use App\Domain\Exception\ValidationException;
use Psr\Log\LoggerInterface;
use Spiral\Interceptors\Context\CallContextInterface;
use Spiral\Interceptors\HandlerInterface;
use Spiral\Interceptors\InterceptorInterface;
use Spiral\RoadRunner\GRPC\Exception\GRPCException;
use Spiral\RoadRunner\GRPC\StatusCode;
use Throwable;
final readonly class ErrorMapInterceptor implements InterceptorInterface
{
public function __construct(
private LoggerInterface $logger,
) {}
public function intercept(CallContextInterface $context, HandlerInterface $handler): mixed
{
try {
return $handler->handle($context);
} catch (GRPCException $e) {
throw $e; // уже gRPC - пропускаем
} catch (DomainException $e) {
throw new GRPCException($e->getMessage(), match (true) {
$e instanceof NotFoundException => StatusCode::NOT_FOUND,
$e instanceof ValidationException => StatusCode::INVALID_ARGUMENT,
default => StatusCode::INTERNAL,
});
} catch (Throwable $e) {
$this->logger->error('unhandled', [
'method' => implode('/', $context->getTarget()->getPath()),
'err' => $e->getMessage(),
]);
throw new GRPCException('internal error', StatusCode::INTERNAL);
}
}
}
PHP-эквивалент - отдельный interceptor, который ловит доменные исключения и маппит их в gRPC-коды через match.
import logging
from typing import Any
import grpc
import domain
from grpc_interceptors.base import UnaryHandler, UnaryServerInterceptor
logger = logging.getLogger("grpc")
class ErrorMapInterceptor(UnaryServerInterceptor):
def intercept(self, request: Any, context: grpc.ServicerContext, method: str, handler: UnaryHandler) -> Any:
try:
return handler(request, context)
except Exception as err:
if context.code() is not None:
raise # уже status (context.abort) - пропускаем
match err:
case domain.NotFoundError():
context.abort(grpc.StatusCode.NOT_FOUND, str(err))
case domain.ValidationError():
context.abort(grpc.StatusCode.INVALID_ARGUMENT, str(err))
case TimeoutError():
context.abort(grpc.StatusCode.DEADLINE_EXCEEDED, "request timed out")
case _:
logger.error("unhandled", extra={"method": method, "err": str(err)})
context.abort(grpc.StatusCode.INTERNAL, "internal error")
Доменные исключения ловятся одним except и маппятся в gRPC-коды через match по классу исключения.
Так handler-ы возвращают доменные ошибки (domain.ErrNotFound), а перевод в gRPC-семантику централизован.
Готовые библиотеки
github.com/grpc-ecosystem/go-grpc-middleware - коллекция готовых interceptors: auth (jwt, oauth), logging (zap, logrus, zerolog), validator (proto-gen-validate), recovery, ratelimit, retry. В большинстве случаев свой interceptor писать не нужно - берите готовый.
Мини-практика
Напиши цепочку interceptors, без которых gRPC-сервер не стоит выпускать наружу: recovery от паники с логом стека, OpenTelemetry tracing, Prometheus метрики (RPS, latency histogram, error rate по коду), JWT-auth с прокидыванием user_id в context, rate limiting per-user (100 RPC/мин). Покрой тестами panic-recovery и unauthorized-кейсы.