Spawning a child thread that has access to state that outlives the parent route #1930
-
Hi, I'm building an http microservice where users can submit jobs using a particular end point and later query the results of that job which are stored in state. That job is likely to take ~5+ minutes which is too long to wait for a response. So i want to return some kind of 'job accepted' response and then let the user query another endpoint to check for when the job is done. I've done this before in python where the gc takes care of memory management, so my approach is to basically spawn a child thread which will do the processing while the parent route just returns. i.e. something like (in pseudo code) #[post("/create/<job_name>", format = "application/json", data = "<job_data>")]
pub async fn create_job(job_name: &str, data: Data<'_>, some_state: &State<Arc<SomeStruct>){
let parsed_data = parse_data(data);
tokio::spawn(async move {
some_state.mutate(parsed_data, job_name);
})
} The issue here is that Changing So is there a way to do this? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
The answer to this is #[post("/create/<job_name>", format = "application/json", data = "<job_data>")]
pub async fn create_job(job_name: &str, data: Data<'_>, some_state: &State<Arc<SomeStruct>){
let parsed_data = parse_data(data);
let state_clone = some_state.inner().clone()
tokio::spawn(async move {
state_clone.mutate(parsed_data, job_name);
})
} i.e. using inner to access the |
Beta Was this translation helpful? Give feedback.
The answer to this is
i.e. using inner to access the
Arc
sans theState
to extend the lifetime beyond'__r