8000 Example code: Encapsulate arbitrary caller-provided layers in library code · Issue #806 · tower-rs/tower · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
Example code: Encapsulate arbitrary caller-provided layers in library code #806
Open
@jlizen

Description

@jlizen

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0