luckyframework / lucky

A full-featured Crystal web framework that catches bugs for you, runs incredibly fast, and helps you write code that lasts.
https://luckyframework.org
MIT License
2.61k stars 158 forks source link

Handle current fiber data per request #1668

Open jwoertink opened 2 years ago

jwoertink commented 2 years ago

Related: https://github.com/luckyframework/avram/issues/804

It's not always the case, but it is technically possible for 2 requests to use the same Fiber instance. Breeze also patches Fiber

https://github.com/luckyframework/breeze/blob/52d6e8152121e624dcf4fc2f40d5c50a192586a2/src/charms/fiber.cr#L5

This is used so we can track information per request to store in Breeze.

One nice thing that Athena is doing is creating this object inside of a handler to ensure each request sets that value on the current fiber regardless of if the fiber is the same from the previous request.

https://github.com/athena-framework/athena/blob/fb9d23d6717539f98312188a23de9bec213264bf/src/components/framework/src/athena.cr#L152-L153

I think we should create something similar, and then any time we need to patch Fiber, we would actually just patch this "container" object. Then that would be set in some handler to guarantee it's consistent. Maybe the request id handler could be merged, and then stored on this thing? :man_shrugging:

jwoertink commented 2 years ago

Looking in to this issue, I noticed that with Avram, we patch Fiber because Fiber will always exist even outside of a Web context.

https://github.com/luckyframework/avram/blob/ef8bad1cef0ce1e29ce6e7b38e355a05269ba323/src/avram/queryable.cr#L274-L276

However, if we created a Lucky::RequestContainer, then from Avram that wouldn't really exist, or be instantiated at any point. You would end up having to set all of that boilerplate up each time you wanted to use Avram outside of Lucky.

jwoertink commented 2 years ago

From Discord:

rob — Today at 4:12 PM
what if the request id is just added to the cache key?
idk how your cache key invalidation works -- often there are ways to partially match keys for invalidation
but if the key was uuid-whatever-model-user-id-3 and you can invalidate based on model-user-id-3
that would give you some caching but it would only be per-request 

With Lucky being an extension in Avram, maybe Avram just has to have a way to prepend all cache keys with something, then the Lucky extension could pull this value from the request ID that's created in the handler...