-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
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
Request-Local State Cache #654
Comments
Here's the document I wrote up for this feature: Request-Local State CacheMotivationWhen we have routes that forward to each-other with guards that access the same data, it's unfortunate that the data has to be retrieved for each guard and each route during request processing. For instance, if there are two routes, the first with an DesignThe request-local state cache will be accessible anywhere an Accessing (setting and retrieving) request-local cached state is accomplished via a single method on impl<'r> Request<'r> {
/// Retrieves the cached value for type `T` from the request-local cached
/// state of `self`. If no such value has previously been cached for
/// this request, `f` is called to produce the value which is subsequently
/// returned.
fn local_cache<T, F>(&self, f: F) -> &T
where T: Send + 'r,
F: FnOnce(&Request) -> T;
} Note that there are no failure modes for this method. The method places a ImplementationThe implementation is straight-forward:
The To start, the latter will suffice, but the former should be implemented before public release. |
Going to re-open this to track guide documentation (in the state guide) for this feature. |
Rocket doesn't currently support "per request cache". Usually this is done with middlewares (#55) on other frameworks (and Go does this with
Context
). Such functionality is usually used to store (as an example) loadedUser
object to the context of current request. This way, if the user object is needed in multiple places in the request handling path, the same object can be used.Here's an simple example of such use case: https://gist.github.com/vhakulinen/5f72f380d5959b7f00435fc473b2c1e3. In the
cargo run
file, you can see that the user object is being loaded multiple times, and this cannot currently be avoided in any non-hacky way.That said, I'm interested in implementing this feature, as I said earlier in Matrix. I don't yet have any plan yet other that to extend the
Request
orRequestState
to havecontext
property which would act as a cache. This is so that both fairings and request guards have access to the per request cache.Example usage (for request guard) would be following:
I'm quite new to rust, so there probably is more 'rust' way to do this. I was wondering if something like the
request.guard::<User>()
could be implemented for the per request cache, but that would be limiting in some ways: for example, you'd be limited to have one cachedUser
object per request.The text was updated successfully, but these errors were encountered: