gotham-rs / gotham

A flexible web framework that promotes stability, safety, security and speed.

Home Page:https://gotham.rs

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Use complex type as shared state (across endpoints)

kahlil29 opened this issue · comments

The examples have made it quite clear on how to use a simple data type like an integer as a shared (mutable) counter across endpoints (via arc, middleware, pipelines).

I need to load a Tensorflow Graph into memory and share that across endpoints (it takes time to load the graph and I cannot load it into memory for each request).
The definition (docs) of the Graph data type is here : https://docs.rs/tensorflow/0.14.0/tensorflow/struct.Graph.html

If I try to do the same as what's in the Shared State example,
I write the following line of code :
let middleware = StateMiddleware::new(tfGraph);

I get the following error:

the trait bound `std::result::Result<food_scoring_inference::tensorflow::Graph, std::io::Error>: gotham::state::StateData` is not satisfied

the trait `gotham::state::StateData` is not implemented for `std::result::Result<food_scoring_inference::tensorflow::Graph, std::io::Error>`

note: required by `gotham::middleware::state::StateMiddleware`

I think I understand the cause of the error.
Incase I do need to write trait instances/implementations, I would need some guidance or help on how to do that, or could you suggest a good way to share the data across endpoints so that it can be reused?

@kahlil29 you have to create a wrapper struct that can implement the StateData trait; for example, see here. Based on your error, it's because you aren't implementing that (marker) trait.

@whitfin thanks so much for telling me that and pointing me to the example! It works as expected now (after a bit of wrestling with the borrow checker).
Thanks a lot 😄

It's really nice to have responsive maintainers who are prompt to reply and friendly 👍
As someone fairly new to Rust (ecosystem and community), you guys make it awesome for people like me 🥇