chainguard_sandbox/workspaces/
firstattach.rs1use 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
13pub const FIRST_ATTACH_TIMEOUT: Duration = Duration::from_secs(120);
15
16const 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 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 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 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 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 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}