Skip to main content

chainguard_sandbox/workspaces/
sessions.rs

1//! Session resources: create, get, list, resolve, delete, park, heartbeat.
2
3use std::time::Duration;
4
5use super::pb::{
6    CreateSessionRequest, DeleteSessionRequest, GetSessionRequest, HeartbeatSessionRequest,
7    IdlePolicy, ListSessionsRequest, Provenance, Source, UpdateSessionRequest, Workspace, session,
8};
9use super::{Client, Session, exec::duration, repourl};
10use crate::{Error, Result};
11
12/// "instances/{id}"; an already-qualified name is returned unchanged.
13pub fn instance_name(id: &str) -> String {
14    if id.starts_with("instances/") {
15        id.to_string()
16    } else {
17        format!("instances/{id}")
18    }
19}
20
21/// Whether s is a full resource name "instances/{instance}/sessions/{session}".
22pub fn is_session_name(s: &str) -> bool {
23    let p: Vec<&str> = s.split('/').collect();
24    p.len() == 4
25        && p[0] == "instances"
26        && p[2] == "sessions"
27        && !p[1].is_empty()
28        && !p[3].is_empty()
29}
30
31/// The environment document chainctl 0.2.398 uses for a directory without
32/// .chainguard/develop.yaml or ci.yaml. Its check is named "develop".
33pub const DEFAULT_ENVIRONMENT: &[u8] = include_bytes!("default_environment.yaml");
34
35/// Describes a session opened from a repository URL, like `chainctl develop github.com/org/repo`:
36/// the repository as `https://github.com/owner/repo`, idle AUTO_HOLD, and [`DEFAULT_ENVIRONMENT`] as
37/// the fallback for repositories without .chainguard/ files. `revision` pins a commit (empty =
38/// unpinned).
39pub fn repository_session(repository: &str, revision: &str) -> Session {
40    Session {
41        idle: IdlePolicy::AutoHold as i32,
42        environment: Some(session::Environment::Source(Source {
43            repository: repository_url(repository),
44            revision: revision.into(),
45            fallback_document: DEFAULT_ENVIRONMENT.to_vec(),
46            ..Default::default()
47        })),
48        ..Default::default()
49    }
50}
51
52/// Normalizes "github.com/o/r", "git@github.com:o/r.git", "ssh://git@github.com:22/o/r" and
53/// similar to `https://github.com/o/r`. Other URLs keep their scheme (credentials stripped);
54/// scp-style remotes on other hosts are returned unchanged; a bare "host/path" gets https://.
55pub fn repository_url(repo: &str) -> String {
56    let u = repourl::normalize_github_url(repo);
57    if u.contains("://") || repourl::is_scp_like(&u) {
58        u
59    } else {
60        format!("https://{u}")
61    }
62}
63
64/// Describes a session whose /work tree is uploaded on the first attach (see
65/// [`Client::complete_first_attach`]): `label` identifies the workspace (the sandbox API uses
66/// `/chainguard-sandbox/<name>`); `repository` and `revision` are optional metadata; `document` is
67/// the environment document (YAML), `None` using [`DEFAULT_ENVIRONMENT`] with provenance
68/// SYNTHESIZED. The idle policy is AUTO_HOLD, chainctl's default.
69pub fn workspace_session(
70    label: &str,
71    repository: &str,
72    revision: &str,
73    document: Option<Vec<u8>>,
74) -> Session {
75    let (document, prov) = match document {
76        Some(d) => (d, Provenance::Authored),
77        None => (DEFAULT_ENVIRONMENT.to_vec(), Provenance::Synthesized),
78    };
79    Session {
80        idle: IdlePolicy::AutoHold as i32,
81        environment: Some(session::Environment::Workspace(Workspace {
82            label: label.into(),
83            repository: repository.into(),
84            revision: revision.into(),
85            document,
86            provenance: prov as i32,
87        })),
88        ..Default::default()
89    }
90}
91
92/// Filters [`Client::list`].
93#[derive(Debug, Clone, Default)]
94pub struct ListOptions {
95    /// Lists another user's sessions (needs the owner role); empty means the caller's own.
96    pub owner: String,
97    pub page_size: i32,
98}
99
100impl Client {
101    /// Creates a session in the client's instance.
102    pub async fn create(&self, s: Session) -> Result<Session> {
103        let parent = self.parent()?;
104        let r = self
105            .request(CreateSessionRequest {
106                parent,
107                session: Some(s),
108            })
109            .await?;
110        Ok(self.check(self.raw().create_session(r).await)?.into_inner())
111    }
112
113    /// Fetches a session by full resource name.
114    pub async fn get(&self, name: &str) -> Result<Session> {
115        let r = self
116            .request(GetSessionRequest { name: name.into() })
117            .await?;
118        Ok(self.check(self.raw().get_session(r).await)?.into_inner())
119    }
120
121    /// Every session in the instance, following page tokens.
122    pub async fn list(&self, o: &ListOptions) -> Result<Vec<Session>> {
123        let parent = self.parent()?;
124        let mut out = Vec::new();
125        let mut req = ListSessionsRequest {
126            parent,
127            page_size: o.page_size,
128            owner: o.owner.clone(),
129            ..Default::default()
130        };
131        loop {
132            let r = self.request(req.clone()).await?;
133            let resp = self.check(self.raw().list_sessions(r).await)?.into_inner();
134            out.extend(resp.sessions);
135            if resp.next_page_token.is_empty() {
136                return Ok(out);
137            }
138            req.page_token = resp.next_page_token;
139        }
140    }
141
142    /// Finds a session the way chainctl's SESSION argument does: a full resource name, a short ID,
143    /// or a display name ("quiet-harbor", "app/quiet-harbor", "acme/app/quiet-harbor"). No match
144    /// is [`Error::NotFound`] (what "session"); several are [`Error::Ambiguous`].
145    pub async fn resolve(&self, reference: &str) -> Result<Session> {
146        if is_session_name(reference) {
147            return self.get(reference).await;
148        }
149        let all = self.list(&ListOptions::default()).await?;
150        // Exact matches (resource ID, short ID, display name, or owner/display-name as chainctl
151        // prints it) win over suffix matches.
152        let (mut exact, mut suffix) = (Vec::new(), Vec::new());
153        for s in all {
154            match match_kind(&s, reference) {
155                Match::Exact => exact.push(s),
156                Match::Suffix => suffix.push(s),
157                Match::None => {}
158            }
159        }
160        let mut hits = if exact.is_empty() { suffix } else { exact };
161        match hits.len() {
162            0 => Err(Error::NotFound {
163                what: "session".into(),
164                name: reference.into(),
165            }),
166            1 => Ok(hits.remove(0)),
167            _ => Err(Error::Ambiguous {
168                reference: reference.into(),
169            }),
170        }
171    }
172
173    /// Tears down the guest and discards its snapshot (or removes a reaped tombstone).
174    pub async fn delete(&self, name: &str) -> Result<()> {
175        let r = self
176            .request(DeleteSessionRequest { name: name.into() })
177            .await?;
178        self.check(self.raw().delete_session(r).await)?;
179        Ok(())
180    }
181
182    /// Applies a field-masked update, e.g. paths "display_name".
183    pub async fn update(&self, s: Session, paths: &[&str]) -> Result<Session> {
184        let mask = prost_types::FieldMask {
185            paths: paths.iter().map(|p| p.to_string()).collect(),
186        };
187        let r = self
188            .request(UpdateSessionRequest {
189                session: Some(s),
190                update_mask: Some(mask),
191            })
192            .await?;
193        Ok(self.check(self.raw().update_session(r).await)?.into_inner())
194    }
195
196    /// Asks the plane to snapshot and stop the VM ("Park now" in the menu).
197    pub async fn park(&self, name: &str) -> Result<Session> {
198        let s = Session {
199            name: name.into(),
200            park_request: session::ParkRequest::Park as i32,
201            ..Default::default()
202        };
203        self.update(s, &["park_request"]).await
204    }
205
206    /// Marks the session in use; a non-zero `hold_for` keeps it running that long after detach
207    /// (`--keep 8h`).
208    pub async fn heartbeat(&self, name: &str, hold_for: Duration) -> Result<Session> {
209        let req = HeartbeatSessionRequest {
210            name: name.into(),
211            hold_for: (!hold_for.is_zero()).then(|| duration(hold_for)),
212        };
213        let r = self.request(req).await?;
214        Ok(self
215            .check(self.raw().heartbeat_session(r).await)?
216            .into_inner())
217    }
218}
219
220enum Match {
221    None,
222    Suffix,
223    Exact,
224}
225
226fn match_kind(s: &Session, reference: &str) -> Match {
227    if reference.is_empty() {
228        return Match::None;
229    }
230    if s.short_id == reference || s.name.rsplit('/').next() == Some(reference) {
231        return Match::Exact;
232    }
233    let dn = &s.display_name;
234    if dn.is_empty() {
235        return Match::None;
236    }
237    if dn == reference {
238        return Match::Exact;
239    }
240    // chainctl prints display names owner-qualified ("acme/app/quiet-harbor" for display name
241    // "app/quiet-harbor"): one extra leading segment.
242    if let Some((owner, rest)) = reference.split_once('/')
243        && !owner.is_empty()
244        && rest == dn
245    {
246        return Match::Exact;
247    }
248    if dn.ends_with(&format!("/{reference}")) {
249        return Match::Suffix;
250    }
251    Match::None
252}