thesis/grpc-server 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

thesis/grpc-server

Composer 安装命令:

composer require thesis/grpc-server

包简介

Async gRPC server for PHP with HTTP/2 transport, unary and streaming RPC handlers, interceptors, and graceful shutdown.

README 文档

README

Read-only subtree split from https://github.com/thesis-php/grpc.

Do not open issues/PRs here. Use the monorepo:

Async gRPC server for PHP with HTTP/2 transport, unary and streaming RPC handlers, interceptors, and graceful shutdown.

Contents

Installation

composer require thesis/grpc-server

Requirements

To generate gRPC server interfaces and registries from .proto, use:

Implementing a service

use Amp\Cancellation;
use Auth\Api\V1\AuthenticateRequest;
use Auth\Api\V1\AuthenticateResponse;
use Auth\Api\V1\AuthenticationServiceServer;
use Thesis\Grpc\Metadata;

final readonly class AuthenticationServer implements AuthenticationServiceServer
{
    public function authenticate(AuthenticateRequest $request, Metadata $md, Cancellation $cancellation): AuthenticateResponse
    {
        return new AuthenticateResponse('supertoken');
    }
}

Starting the server

use Auth\Api\V1\AuthenticationServiceServerRegistry;
use Thesis\Grpc\Server;
use function Amp\trapSignal;

$server = new Server\Builder()
    ->withServices(new AuthenticationServiceServerRegistry(new AuthenticationServer()))
    ->build();

$server->start();
trapSignal([\SIGINT, \SIGTERM]);
$server->stop();

Default bind address: 0.0.0.0:50051.

Use withAddresses() to override bind addresses:

$server = new Server\Builder()
    ->withAddresses('0.0.0.0:8080')
    ->build();

TLS and mTLS

use Amp\Socket\Certificate;
use Thesis\Grpc\Server;

$server = new Server\Builder()
    ->withTransportCredentials(
        new Server\TransportCredentials()
            ->withDefaultCertificate(new Certificate('/certs/server.crt', '/certs/server.key'))
            ->withCaCert('/certs/ca.crt')
            ->withVerifyPeer(), // optional (mTLS)
    )
    ->build();

Practical recommendations:

  • Ensure server certificate SAN (DNS / IP) matches what clients pass via withPeerName().
  • For mTLS, use certificates with correct extendedKeyUsage (serverAuth for server, clientAuth for client).
  • Prefer certificates signed by a trusted CA and modern algorithms (for example, SHA-256).

Compression

Register one or more compressors on the server:

use Thesis\Grpc\Compression\GzipCompressor;

$server = new Server\Builder()
    ->withCompressors(new GzipCompressor())
    ->build();

Interceptors

Interceptors let you apply cross-cutting server logic like auth, audit, tracing, and request validation around every RPC.

use Amp\Cancellation;
use Thesis\Grpc\Metadata;
use Thesis\Grpc\Server;
use Thesis\Grpc\Server\StreamInfo;
use Thesis\Grpc\ServerStream;

final readonly class ServerAuthInterceptor implements Server\Interceptor
{
    public function intercept(ServerStream $stream, StreamInfo $info, Metadata $md, Cancellation $cancellation, callable $next): void
    {
        $next($stream, $info, $md, $cancellation);
    }
}

RPC types

Generated server interfaces expose all four gRPC RPC models directly:

  • unary request/response
  • client streaming
  • server streaming
  • bidirectional streaming

Unary example:

use Amp\Cancellation;
use Echos\Api\V1\EchoRequest;
use Echos\Api\V1\EchoResponse;
use Echos\Api\V1\EchoServiceServer;
use Thesis\Grpc\Metadata;

final readonly class EchoServer implements EchoServiceServer
{
    public function echo(EchoRequest $request, Metadata $md, Cancellation $cancellation): EchoResponse
    {
        return new EchoResponse($request->sentence);
    }
}

Client streaming example:

use Amp\Cancellation;
use File\Api\V1\Chunk;
use File\Api\V1\FileInfo;
use File\Api\V1\FileServiceServer;
use Thesis\Grpc\Metadata;
use Thesis\Grpc\Server;

final readonly class FileServer implements FileServiceServer
{
    public function upload(Server\ClientStreamChannel $stream, Metadata $md, Cancellation $cancellation): FileInfo
    {
        $size = 0;

        /** @var Chunk $chunk */
        foreach ($stream as $chunk) {
            $size += \strlen($chunk->content);
        }

        return new FileInfo($size);
    }
}

Server streaming example:

use Amp\Cancellation;
use Topic\Api\V1\Event;
use Topic\Api\V1\SubscribeRequest;
use Topic\Api\V1\TopicServiceServer;
use Thesis\Grpc\Metadata;

final readonly class TopicServer implements TopicServiceServer
{
    public function subscribe(SubscribeRequest $request, Metadata $md, Cancellation $cancellation): iterable
    {
        yield new Event('event-1', '{"id":1}');
        yield new Event('event-2', '{"id":2}');
    }
}

Bidirectional streaming example:

use Amp\Cancellation;
use Chat\Api\V1\Message;
use Chat\Api\V1\MessengerServiceServer;
use Thesis\Grpc\Metadata;
use Thesis\Grpc\Server;

final readonly class MessengerServer implements MessengerServiceServer
{
    public function chat(Server\BidirectionalStreamChannel $stream, Metadata $md, Cancellation $cancellation): void
    {
        foreach ($stream as $message) {
            $stream->send(new Message("echo: {$message->text}"));
        }

        $stream->close();
    }
}

Stream decorators

If you need per-message interception (not just per-RPC), decorate server streams.

use Psr\Log\LoggerInterface;
use Thesis\Grpc\Server;
use Thesis\Grpc\ServerStream;

/**
 * @template-covariant In of object
 * @template Out of object
 * @template-extends Server\DecoratedStream<In, Out>
 */
final class LoggingServerStream extends Server\DecoratedStream
{
    public function __construct(
        ServerStream $stream,
        private readonly LoggerInterface $logger,
    ) {
        parent::__construct($stream);
    }

    public function send(object $message): void
    {
        $this->logger->info('sent {type}', ['type' => $message::class]);
        parent::send($message);
    }

    public function receive(): object
    {
        $message = parent::receive();
        $this->logger->info('recv {type}', ['type' => $message::class]);

        return $message;
    }
}

Graceful shutdown

Server::stop() stops accepting new requests and waits for active handlers. You can pass TimeoutCancellation to bound wait time. Handlers receive Cancellation; they should respect it so shutdown can finish promptly.

use Amp\TimeoutCancellation;

$server->stop(new TimeoutCancellation(30));

thesis/grpc-server 适用场景与选型建议

thesis/grpc-server 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 17 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 04 月 10 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 thesis/grpc-server 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 thesis/grpc-server 我们能提供哪些服务?
定制开发 / 二次开发

基于 thesis/grpc-server 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 17
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 9
  • 依赖项目数: 2
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-04-10