0

I have a validate endpoint, which takes in a JWT that's POSTed to it, and that works fine. Currently set up like this in the application setup:

let server = HttpServer::new(|| {
        App::new()
            .wrap(Logger::default())
            .route("/ping", web::get().to(health_check))
            .route("/validate", web::post().to(validate))
    })

I'm now looking to provide some JWKs, which I've done via a provider-style setup, where the calling code can just call get_key and the provider should handle caching and refreshing that cache automatically every X minutes so that I don't have to call the endpoint that provides the JWKs on each request. However, obviously that will only work if I can maintain the same instance of the provider object.

What would be the best way of doing this? Could I create an instance of the provider at the same level as the server creation code and pass in the results of provider.get_key through the app_data method that actix provides? Or perhaps do the same via middleware somehow?

I've tried passing the entire provider instance through the app_data method but can't get this to work (I think because my struct can't implement Copy due to containing a Vec), so I'm trying to find alternate methods of doing it!

dantdj
  • 1,237
  • 3
  • 19
  • 40
  • I'm not sure I fully understand your setup, are you just asking how to use global state with multithreading? Have you tried using good ol' `Arc`, `Mutex`, `lazy_static`, etc.? – Coder-256 Sep 01 '21 at 00:30
  • Basically, yeah - I think actix_web wraps up anything passed through app_data() into an Arc, but I couldn't figure out how to actually access the object inside, various traits weren't fulfilled and I had no idea how to actually satisfy them. I may get rid of this question and spin up a new one based around how to actually do that :) – dantdj Sep 01 '21 at 14:41
  • Sounds good! Just curious, what is the reason behind using `app_data` rather than e.g. `lazy_static`/`Lazy`/`SyncLazy`? – Coder-256 Sep 01 '21 at 16:18
  • It seems to be the way to do it in actix-web - see the "Shared Mutable State" heading on this page: https://actix.rs/docs/application/ – dantdj Sep 01 '21 at 17:36

0 Answers0