dagger_sdk/
client.rs

1use std::sync::Arc;
2
3use crate::core::config::Config;
4use crate::core::engine::Engine as DaggerEngine;
5use crate::core::graphql_client::DefaultGraphQLClient;
6
7use crate::errors::ConnectError;
8use crate::gen::Query;
9use crate::logging::StdLogger;
10use crate::querybuilder::query;
11
12pub type DaggerConn = Query;
13
14pub async fn connect<F, Fut>(dagger: F) -> Result<(), ConnectError>
15where
16    F: FnOnce(DaggerConn) -> Fut + 'static,
17    Fut: futures::Future<Output = eyre::Result<()>> + 'static,
18{
19    let cfg = Config::new(None, None, None, None, Some(Arc::new(StdLogger::default())));
20
21    connect_opts(cfg, dagger).await
22}
23
24pub async fn connect_opts<F, Fut>(cfg: Config, dagger: F) -> Result<(), ConnectError>
25where
26    F: FnOnce(DaggerConn) -> Fut + 'static,
27    Fut: futures::Future<Output = eyre::Result<()>> + 'static,
28{
29    let (conn, proc) = DaggerEngine::new()
30        .start(&cfg)
31        .await
32        .map_err(ConnectError::FailedToConnect)?;
33
34    let proc = proc.map(Arc::new);
35
36    let client = Query {
37        proc: proc.clone(),
38        selection: query(),
39        graphql_client: Arc::new(DefaultGraphQLClient::new(&conn)),
40    };
41
42    dagger(client).await.map_err(ConnectError::DaggerContext)?;
43
44    if let Some(proc) = &proc {
45        proc.shutdown()
46            .await
47            .map_err(ConnectError::FailedToShutdown)?;
48    }
49
50    Ok(())
51}
52
53// Conn will automatically close on drop of proc
54
55#[cfg(test)]
56mod test {
57    use super::connect;
58
59    #[tokio::test]
60    async fn test_connect() -> eyre::Result<()> {
61        tracing_subscriber::fmt::init();
62
63        connect(|client| async move {
64            client
65                .container()
66                .from("alpine:latest")
67                .with_exec(vec!["echo", "1"])
68                .sync()
69                .await?;
70
71            Ok(())
72        })
73        .await?;
74
75        Ok(())
76    }
77}