将上下文从 gRPC 端点传递到 goroutine 收到上下文取消错误

ada*_*amc 5 go goroutine grpc

我试图将上下文从传入的 gRPC 端点传递到 goroutine,该 goroutine 负责向外部服务发送另一个请求,但我正在Error occurred: context canceledctxhttp.Getgoroutine 内的函数调用接收消息:

package main

import (
  "fmt"
  "net"
  "net/http"
  "os"
  "sync"

  "golang.org/x/net/context/ctxhttp"

  dummy_service "github.com/myorg/testing-apps/dummy-proto/gogenproto/dummy/service"
  "github.com/myorg/testing-apps/dummy-proto/gogenproto/dummy/service/status"
  "golang.org/x/net/context"

  "google.golang.org/grpc"
  "google.golang.org/grpc/reflection"
)

func main() {
  var err error

  grpcServer := grpc.NewServer()

  server := NewServer()
  dummy_service.RegisterDummyServer(grpcServer, server)
  reflection.Register(grpcServer)

  lis, err := net.Listen("tcp", ":9020")
  if err != nil {
    fmt.Printf("Failed to listen: %+v", err)
    os.Exit(-1)
  }
  defer lis.Close()

  wg := sync.WaitGroup{}

  wg.Add(1)
  go func() {
    defer wg.Done()
    fmt.Println("Starting gRPC Server")
    if err := grpcServer.Serve(lis); err != nil {
      fmt.Printf("Failed to serve gRPC: %+v", err)
      os.Exit(-1)
    }
  }()

  wg.Wait()
}

type server struct{}

func NewServer() server {
  return server{}
}

func (s server) Status(ctx context.Context, in *status.StatusRequest) (*status.StatusResponse, error) {
  go func(ctx context.Context) {
    client := http.Client{}

    // it's important to send the ctx from the parent function here because it contains
    // a correlation-id which was inserted using grpc middleware, and the external service
    // prints this value in the logs to tie everything together
    if _, err := ctxhttp.Get(ctx, &client, "http://localhost:4567"); err != nil {
      fmt.Println("Error encountered:", err)
      return
    }

    fmt.Println("No error encountered")
  }(ctx)

  response := status.StatusResponse{
    Status: status.StatusResponse_SUCCESS,
  }


  // if I enable the following, everything works, and I get "No error encountered"
  // time.Sleep(10 * time.Millisecond)

  return &response, nil
}
Run Code Online (Sandbox Code Playgroud)

如果我time.Sleep()在调用函数中添加 a ,则 goroutine 会按预期成功并且不会收到任何错误。似乎父函数的上下文一返回就被取消,并且由于父函数在 goroutine 之前结束,因此传递给 goroutine 的上下文正在接收错误context canceled

我意识到我可以通过让调用函数等待 goroutine 完成来解决这个问题,这将防止上下文被取消,但我不想这样做,因为我希望函数立即返回,以便客户端点击端点尽快得到响应,而 goroutine 继续在后台处理。

我也可以通过不使用传入的值ctx而是context.Background()在我的 goroutine 中使用来解决这个问题,但是,我想使用传入的值ctx,因为它包含一个correlation-id由 grpc 中间件插入的值,并且需要作为传出请求的一部分传递Goroutine 创建,以便下一个服务器可以correlation-id在其日志消息中打印此内容,以将请求捆绑在一起。

我最终通过correlation-id从传入上下文中提取 并将其插入到context.Background()goroutine 中的新内容中解决了这个问题,但我想避免这种情况,因为它在 goroutine 发出的每个传出请求周围添加了一堆样板代码,而不是只是能够传递上下文。

谁能向我解释为什么上下文被取消,并让我知道是否有针对这种情况的“最佳实践”解决方案?是否无法在 gRPC 的 goroutine 中使用从调用函数传入的上下文?

小智 2

@adamc如果你还没有找到任何其他方法。

我最终得到了这个解决方案(这也不完美)只是为了复制完整的上下文。但我更喜欢手动将原始上下文中的值添加到context.Background

md, _ := metadata.FromIncomingContext(ctx)
copiedCtx := metadata.NewOutgoingContext(context.Background(), md)
Run Code Online (Sandbox Code Playgroud)