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

Example code: Encapsulate arbitrary caller-provided layers in library code #806

Open
jlizen opened this issue Dec 23, 2024 · 0 comments
Open

Comments

@jlizen
Copy link
Contributor

jlizen commented Dec 23, 2024

TLDR:

Questions:

  • do we want an example showing a library encapsulating user-provided tower layers for an internal service, with type erasure
  • do we want an example showing the same, but with generics?

Happy to contribute either or both, just gauging interest first :)


A common pattern I've beaten my head up against with tower is, having a library that exposes an tower service, and allows a caller to specify layers.

I recently cut a change to reqwest that does this, and I'm wondering if it would be useful to include something like this as a tower example.

The simple way to do this is to allow the caller to wrap the entire server or client and then continue to refer to it by the concretely-named layer stack. This is a pretty unpleasant API though. It also means that the tower stack needs to be relevant to the entire API call, not just a portion of it.

What I frequently want to do is instead to encapsulate the tower stack inside of the library so that the caller doesn't need to keep specifying it. That way the library can interact with it under the hood and also keep the caller API cleaner.

We have a way to do this fairly ergonomically with BoxService/BoxCloneService/BoxCloneSyncService, but the approach isn't obvious. This is the approach taken in the above reqwest PR. That's what I'm offering to document.

There is also a way to do this with generics to avoid dynamic dispatch (at least on the input end, optionally the composed stack as well). I do have a working impl of that too on an early draft of the reqwest PR - ref. It's even trickier to arrive at, but it's also more nice. Possibly worth documenting as well.

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

No branches or pull requests

1 participant