Tonic mutable state

Hello, fellow rustaceans. I very recently started using tonic (part of the tokio project) and I am trying to create a simple server. My problem is thus:


use entity_service_server::*;
use nvcore::ecs::EntityManager;
use tonic::{transport::Server, Request, Response, Status};

pub struct EntityManagerService {
    entity_manager: EntityManager,
}
impl EntityManagerService {
    fn new() -> EntityManagerService {
        EntityManagerService {
            entity_manager: EntityManager::new(),
        }
    }
}
#[tonic::async_trait]
impl EntityService for EntityManagerService {
    async fn create(&self, request: Request<Name>) -> Result<Response<EntityId>, Status> {
        println!("create");
        let res = EntityId {
            id: self
                .entity_manager
                .create_entity(request.into_inner().name)
                .to_string(),
        };
        Ok(Response::new(res))
    }
}

In the create message, I need to modify the state of the EntityManagerService, but when tonic generates the stubs, the borrow is immutable...how should I get around this? Full disclosure, I am very new to rust in general, and very very new to tonic specifically (I started yesterday, as a matter of fact).
I am experimenting with writing a backend+ui application where the backend manages all of the data, and any number of light weight, ephemeral ui clients can make queries about the current state/ask the backend to change some state and display this data as they see fit. Ideally, I want to be able to implement these frontends in any language/framework (rust's current UI situation is still quite infantile) I am not sure if using something like tonic is the best route, so any input towards a better solution would be appreciated.

You will need to wrap it the fields you wish to modify in a mutex or similar.

Ah...I suppose that makes sense. But from my understanding tokio (upon which tonic runs ) is single-threaded and used 'green threads', so there shouldn't be the possibility of locking...
I'll try it, though.

Tokio will, by default, use a number of threads equal to your number of CPU cores, though it can be configured to be single threaded.

Okay. That makes sense.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.