use std::collections::BTreeMap;
use std::time::Duration;
use reqwest::Method;
use serde::{Deserialize, Serialize};
use crate::client::{with_idempotency_key, with_json};
use crate::error::Error;
use crate::time_portal::TimePortal;
use crate::wire::{deserialize_duration, duration_param, segment, serialize_duration};
mod exec;
mod files;
pub use crate::client::idempotency_key;
pub use exec::{
ExecExit, ExecFrame, ExecInput, ExecOutput, ExecOutputRequest, ExecStartRequest, Stream,
};
pub use files::{FileList, FileListRequest, FileRange, FileStat, FileType};
const SANDBOXES: &str = "/sandbox";
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub enum Network {
None,
TimePortal,
#[serde(other, skip_serializing)]
Unknown,
}
#[derive(Clone, Default, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct SandboxCreateRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub network: Option<Network>,
#[serde(skip_serializing_if = "Option::is_none")]
pub vcpus: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub memory_gib: Option<u32>,
#[serde(
skip_serializing_if = "Option::is_none",
serialize_with = "serialize_duration"
)]
pub timeout: Option<Duration>,
#[serde(
skip_serializing_if = "Option::is_none",
serialize_with = "serialize_duration"
)]
pub idle_timeout: Option<Duration>,
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
pub env: BTreeMap<String, String>,
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
pub metadata: BTreeMap<String, String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub apps: Vec<String>,
#[serde(skip)]
pub idempotency_key: Option<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum SandboxState {
Creating,
Live,
Ended,
Failed,
#[serde(other, skip_serializing)]
Unknown,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ApiFailure {
#[serde(rename = "type")]
pub kind: String,
pub message: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct SandboxInfo {
pub id: String,
pub state: SandboxState,
pub as_of: String,
pub network: Network,
pub vcpus: u32,
pub memory_gib: u32,
#[serde(
deserialize_with = "deserialize_duration",
serialize_with = "serialize_duration"
)]
pub timeout: Duration,
#[serde(
deserialize_with = "deserialize_duration",
serialize_with = "serialize_duration"
)]
pub idle_timeout: Duration,
pub created_at: String,
#[serde(default)]
pub booted_at: Option<String>,
#[serde(default)]
pub expires_at: Option<String>,
#[serde(default)]
pub ended_at: Option<String>,
#[serde(default)]
pub error: Option<ApiFailure>,
#[serde(default)]
pub metadata: BTreeMap<String, String>,
#[serde(default)]
pub apps: Vec<SandboxApp>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct SandboxApp {
pub name: String,
pub version: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct SandboxListRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub state: Option<SandboxState>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cursor: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub limit: Option<u32>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct SandboxList {
pub sandboxes: Vec<SandboxInfo>,
#[serde(default)]
pub next_cursor: Option<String>,
}
impl TimePortal {
pub async fn create_sandbox(
&self,
request: &SandboxCreateRequest,
) -> Result<SandboxInfo, Error> {
let key = request
.idempotency_key
.clone()
.unwrap_or_else(idempotency_key);
let http = with_idempotency_key(self.held(Method::POST, SANDBOXES), &key);
self.client.json(with_json(http, request)?).await
}
pub async fn get_sandbox(
&self,
id: &str,
wait: Option<Duration>,
) -> Result<SandboxInfo, Error> {
let mut http = self.request(Method::GET, &sandbox_path(id, "")?);
if let Some(wait) = wait {
http = http.query(&[("wait", duration_param(wait)?)]);
}
self.client.json(http).await
}
pub async fn list_sandboxes(&self, request: &SandboxListRequest) -> Result<SandboxList, Error> {
if request.state == Some(SandboxState::Unknown) {
return Err(Error::InvalidArgument(
"SandboxState::Unknown is not a filter".into(),
));
}
let http = self.request(Method::GET, SANDBOXES).query(request);
self.client.json(http).await
}
pub async fn terminate_sandbox(&self, id: &str) -> Result<(), Error> {
self.client
.send(self.request(Method::DELETE, &sandbox_path(id, "")?))
.await?;
Ok(())
}
}
fn sandbox_path(id: &str, rest: &str) -> Result<String, Error> {
Ok(format!("{SANDBOXES}/{}{rest}", segment(id)?))
}