Skip to main content

chainguard_sandbox/workspaces/
firstattach.rs

1//! Completing a new workspace session's first attach.
2
3use std::io::Write as _;
4use std::time::Duration;
5
6use tokio::sync::mpsc;
7use tokio_stream::wrappers::ReceiverStream;
8
9use super::Client;
10use super::pb::{AttachRequest, AttachResponse, attach_request, attach_response};
11use crate::{Error, Result};
12
13/// Bounds [`Client::complete_first_attach`].
14pub const FIRST_ATTACH_TIMEOUT: Duration = Duration::from_secs(120);
15
16/// An empty tar archive: the 1 KiB end-of-archive marker.
17const EMPTY_TAR: [u8; 1024] = [0; 1024];
18
19fn ended() -> Error {
20    Error::other("workspaces: the attach ended before the workspace was ready")
21}
22
23impl Client {
24    /// Completes a new workspace session's first attach, which the plane requires before it
25    /// allows Exec (until then Exec fails with FailedPrecondition "attach with a shell first to
26    /// upload the workspace").
27    ///
28    /// It opens one AttachSession stream with a shell, and if the plane reports
29    /// workspace_pending, uploads an empty tree: a single FULL_TAR chunk holding an empty tar
30    /// archive (gzip'd when the plane offers GZIP). It waits for WorkspaceReady and then detaches
31    /// by canceling the stream. A session that isn't pending is left as it is. It gives up after
32    /// [`FIRST_ATTACH_TIMEOUT`] (an [`Error::Timeout`] with op "start").
33    pub async fn complete_first_attach(&self, name: &str) -> Result<()> {
34        match tokio::time::timeout(FIRST_ATTACH_TIMEOUT, self.first_attach(name)).await {
35            Ok(r) => r,
36            Err(_) => Err(Error::Timeout {
37                op: "start".into(),
38                detail: "the first attach did not complete".into(),
39                result: None,
40            }),
41        }
42    }
43
44    async fn first_attach(&self, name: &str) -> Result<()> {
45        let (tx, rx) = mpsc::channel::<AttachRequest>(4);
46        let open = AttachRequest {
47            input: Some(attach_request::Input::Open(attach_request::Open {
48                name: name.into(),
49                // An empty Resume is sent, as chainctl does.
50                resume: Some(attach_request::Resume::default()),
51            })),
52        };
53        tx.send(open).await.map_err(|_| ended())?;
54        let r = self.request(ReceiverStream::new(rx)).await?;
55        // Dropping the response stream and the sender is the detach.
56        let mut stream = self.check(self.raw().attach_session(r).await)?.into_inner();
57        loop {
58            let resp: AttachResponse = match stream.message().await {
59                Ok(Some(m)) => m,
60                Ok(None) => return Err(ended()),
61                Err(s) => return Err(self.status(s)),
62            };
63            match resp.output {
64                Some(attach_response::Output::Opened(o)) => {
65                    if !o.workspace_pending {
66                        return Ok(());
67                    }
68                    let chunk = empty_workspace_chunk(&o.workspace_encodings)?;
69                    let req = AttachRequest {
70                        input: Some(attach_request::Input::WorkspaceChunk(chunk)),
71                    };
72                    if tx.send(req).await.is_err() {
73                        // The stream closed: its status arrives on the next reads.
74                        loop {
75                            match stream.message().await {
76                                Ok(Some(_)) => continue,
77                                Ok(None) => return Err(ended()),
78                                Err(s) => return Err(self.status(s)),
79                            }
80                        }
81                    }
82                }
83                Some(attach_response::Output::WorkspaceReady(_)) => return Ok(()),
84                Some(attach_response::Output::Detached(_)) => return Err(Error::Detached),
85                // Anything else the plane sends on a shell attach (terminal output, for one)
86                // isn't in this SDK's protocol subset and arrives with no output set: skipped.
87                None => {}
88            }
89        }
90    }
91}
92
93fn empty_workspace_chunk(encodings: &[i32]) -> Result<attach_request::WorkspaceChunk> {
94    use attach_request::workspace_chunk::{Encoding, Format};
95    let mut chunk = attach_request::WorkspaceChunk {
96        data: EMPTY_TAR.to_vec(),
97        last: true,
98        format: Format::FullTar as i32,
99        encoding: Encoding::Unspecified as i32,
100    };
101    if encodings.contains(&(Encoding::Gzip as i32)) {
102        let mut zw = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
103        zw.write_all(&EMPTY_TAR).map_err(|e| Error::io("gzip", e))?;
104        chunk.data = zw.finish().map_err(|e| Error::io("gzip", e))?;
105        chunk.encoding = Encoding::Gzip as i32;
106    }
107    Ok(chunk)
108}