如何使用 gRPC 服务器流检测 Cloud 运行 中的 cancelled/lost/closed 连接?

How to detect a cancelled/lost/closed connection in Cloud Run with gRPC server streaming?

我在 Google 云 运行 上托管了一个 server-side streaming RPC

具有以下原型定义:

syntax = "proto3";

package test.v1;

service MyService {
    // Subscribe to a stream of events.
    rpc Subscribe (SubscribeRequest) returns (stream SubscribeResponse) {}
}

message SubscribeRequest {
}

message SubscribeResponse {
}

使用 BloomRPC/grpcurl,当我停止方法时,我得到一个 stream.Context().Done() 事件,我可以用它来优雅地停止某些任务。这是订阅方法的示例:

func (s *myService) Subscribe(req *pb.SubscribeRequest, stream pb.Instruments_SubscribeServer) error {
    
    // Create a channel for this client.
    ch := make(chan *pb.SubscribeResponse)
    
    // Add the channel object 'ch' to a Global list of channels where we have a 'broadcaster' sending
    // messages to all connected clients.
    // TODO: pass to broadcaster client list.
    
    for {
        select {
        case <-stream.Context().Done():
            close(ch)
            fmt.Println("Removed client from global list of channels")
            return nil
        case res := <-ch:
            _ = stream.Send(res)
        }
    }
}

在客户端,当我在本地测试服务时(即 运行 Golang 中的本地 gRPC 服务器),使用 BloomRPC/grpcurl 我在 stream.Context().Done() 通道上收到一条消息我停止 BloomRPC/grpcurl 连接。这是预期的行为。

但是,运行 Cloud 运行 上的完全相同的代码以相同的方式(通过 BloomRPC/grpcurl),我没有收到 stream.Context().Done() 消息 - 任何为什么在 Google Cloud 运行 上会有所不同?查看 Cloud 运行 日志,调用 Subscribe 方法本质上 'hangs' 直到请求超时。

我需要 enable HTTP/2 Connections in Cloud Run 才能正常工作。