How do I .await a future in multiple places?

Hi, I am trying to build a session management in my web application. However, I am struggling with something... some unexplored areas in the dungeon called Asynchronous Rust.

So here's my try to share it with fellow rustaceans :sunglasses:

what do you want to build...?
I am trying to build a session management for my todo app, and it will be :sparkles:super-duper special and irregular :sparkles: todo app, don't worry .
So, once a user established a websocket connection to the server, a session will be created for them. The session will be destroyed once the user disconnects. They can have multiple websocket connection to the server, in multiple devices.

w- what's the problem?
When the server creates or destroys a user's session, they need some amount of time to do it. What if the user established another websocket while the server is still creating/destroying the user's session?

Well, of course, I need to make them wait until the server finished creating/destroying the user's session.

what is your current, thinkable solution to the problem?
In order to solve the problem, I need:

  • Something to make the user wait while the server is creating/destroying their session.
  • Something to notify the user when the server is finished creating/destroying their session.
async fn test_func() { }

async fn main() {
  let f = test_func();
  tokio::spawn(async { f.await });
  tokio::spawn(async { f.await });

Obviously the code above won't compile, it's just for illustration purpose.

It doesn't have to be ".await-ing a Future in multiple places", it can be anything similar, or probably, super duper better alternatives.

I appreciate any help :)
Regards, thebluetropics from Indonesia.

maybe futures::Shared can help you?

1 Like

You need some means of synchronization. Where is the user session stored? Are you using some sort of shared state? Like a HashMap<UserId, UserSession>? In which case wrapping your state in a Mutex or RwLock would be enough to make sure only one thread can read or write the UserSession at the same time.

1 Like

Tokio offers some synchronization primitives such as Mutex and RwLock that you can await.

1 Like

This is exactly what I wanted in the illustration above.

It will be be in a server, not distributed server. In a multithreaded asynchronous (tokio) server to be exact.

Yes. Mutex<HashMap<Uuid, Session>>. A master lock to the map.

If there's 1k user session (i.e 1k async Mutex), will there be some sort of overhead that I can worry about?

I wouldn't be bothered if the application will be handling 1K user sessions. It's not a significant load for modern hardware.

1 Like