Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a timeout getter to HandlerContext and export createHandlerContext #632

Merged
merged 3 commits into from
May 15, 2023

Conversation

timostamm
Copy link
Member

@timostamm timostamm commented May 15, 2023

Following #591, this adds a method timeoutMs() to the handler context for true deadline propagation:

import type { HandlerContext } from "@bufbuild/connect";

const say = async (req: SayRequest, ctx: HandlerContext) => {
  
  // If a timeout was set on the call to this service, the timeout() method 
  // returns the remaining time in milliseconds. 
  // Passing the value to an upstream client call propagates the timeout.
  await client.someCall({}, { timeoutMs: ctx.timeoutMs() });

  return new SayResponse({sentence: `You said: ${req.sentence}`});
};

This is an alternative to passing ctx.signal to upstream client calls. Passing ctx.signal works for any operation you might want to call (as long as the API supports it). For RPC calls, passing the timeout is preferable because it is more efficient and robust - you have a guarantee that the peer is aware of the deadline, regardless of network issues.

We now also export createHandlerContext() from @bufbuild/connect. If you want to run unit tests against your service implementations, you now have a convenient function to create a HandlerContext if your services rely on it.

This PR also enables the test case cancel_after_first_response, refactors the code for deadlines so that it can be used on the client-side in a follow-up, and adds more test coverage

@timostamm timostamm merged commit 59bd4fc into main May 15, 2023
3 checks passed
@timostamm timostamm deleted the tstamm/refactor-deadlines branch May 15, 2023 21:03
@timostamm timostamm changed the title Add a timeout getter to the handler context and export createHandlerContext Add a timeout getter to HandlerContext and export createHandlerContext May 17, 2023
@timostamm timostamm mentioned this pull request May 17, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants