7

Usually, the client can cancel the gRPC call with:

(requestObserver as ClientCallStreamObserver<Request>)
    .cancel("Cancelled", null)

However, it is shown in the Javadoc:

CancellableContext withCancellation = Context.current().withCancellation();
// do stuff
withCancellation.cancel(t);

Which one is the "correct" way of cancelling a client call, and letting the server know?

Edit:

To make matters more confusing, there's also ManagedChannel.shutdown*.

Abhijit Sarkar
  • 21,927
  • 20
  • 110
  • 219

1 Answers1

1

Both are acceptable and appropriate.

clientCallStreamObserver.cancel() is generally easier as it has less boilerplate. It should generally be preferred. However, it is not thread-safe; it is like normal sending on the StreamObserver. It also requires direct awareness with the RPC; you can't have higher-level code orchestrate the cancellation as it may not even be aware of the RPC.

Use Context cancellation for thread-safe cancellation and less RPC-aware cancellation. Context cancellation could be used in circumstances similar to thread interruption or Future cancellation. Not that CancellableContexts should be treated as a resource and must be cancelled eventually to avoid leaking memory. (context.cancel(null) can be used when the context reaches its "normal" end of life.)

Eric Anderson
  • 24,057
  • 5
  • 55
  • 76
  • `clientCallStreamObserver.cancel` may not be available if using a library that doesn't expose it; see this [discussion](https://github.com/grpc/grpc-kotlin/issues/32#issuecomment-668483982). Also, what about `channel.shutdown` (see edit)? – Abhijit Sarkar Aug 04 '20 at 18:45
  • 2
    grpc-kotlin does not use the StreamObserver API at all; it uses the lower-level ClientCall directly for its stubs (which is appropriate). That's simply, "you aren't using the grpc-java stubs." `channel.shutdown()` does not cancel RPCs. `shutdownNow()` does, but it would be _very_ poor for cancelling individual RPCs. – Eric Anderson Aug 05 '20 at 14:23
  • "it uses the lower-level ClientCall " - Yes, I saw that in their code. It seems to be more of a pet project than a serious effort, questions and issues going unattended for days. – Abhijit Sarkar Aug 05 '20 at 18:49