#Axum FromRef and trait coherence

2 messages · Page 1 of 1 (latest)

faint anchor
#

I'm using a Rust workspace. I've set up an app that uses axum in a crate let's call app. In the same crate it defines a struct say AppState that is used for passing state to the route handlers. That state struct contains a field of type say ServiceA from crate service_a. Also in crate service_a there is a route handling method say method_a that extracts State<ServiceA>. See https://docs.rs/axum/latest/axum/extract/struct.State.html#substates for the pattern. My code is roughly in app:

    .route("/", get(|| async { "Hello, World!" }))
    .route("/service_a/method_a", post(service_a::method_a))
            .with_state(app_state);

And in service_a:

pub async fn method_a(
    State(svc): State<ServiceA>,
    Json(request): Json<MethodARequest>,
) -> Response {
    match svc.method_a(request).await {
        Ok(res) => (StatusCode::OK, Json(res)).into_response(),
        Err(err) => (StatusCode::INTERNAL_SERVER_ERROR, Json(err)).into_response(),
    }
}

Workspace Cargo.toml:

members = ["app", "service_a"]

[workspace.dependencies]
app = { path = "./app" }
service_a = { path = "./service_a" }

And in app/Cargo.toml:

service_a = { workspace = true }

It seems to compile and work fine, but how come I did not encounter any trait coherence issues? I didn't expect to be able to define the following in the app crate because ServiceA struct is defined in the service_a crate:

    fn from_ref(app_state: &AppState) -> ServiceA {
        app_state.service_a.clone()
    }
}```

Does it have something to do with the fact there isn't a `self` parameter? I'd expect to have to do something like `impl ToRef<ServiceA> for AppState` in the `app` crate to not have any crate circular dependency nor trait coherence issues.
velvet gorge