use std::collections::BTreeMap;
use std::fmt;
use std::ops::Not;
use std::time::Duration;
use reqwest::Method;
use serde::{Deserialize, Serialize};
use super::{idempotency_key, sandbox_path};
use crate::client::{with_idempotency_key, with_json};
use crate::error::Error;
use crate::time_portal::TimePortal;
use crate::wire::{bytes_b64, duration_param, segment, serialize_duration};
#[derive(Clone, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct ExecStartRequest {
pub argv: Vec<String>,
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
pub env: BTreeMap<String, String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cwd: Option<String>,
#[serde(
skip_serializing_if = "Option::is_none",
serialize_with = "serialize_duration"
)]
pub timeout: Option<Duration>,
#[serde(
rename = "stdin_b64",
skip_serializing_if = "Vec::is_empty",
with = "bytes_b64"
)]
pub stdin: Vec<u8>,
#[serde(skip_serializing_if = "Not::not")]
pub stdin_open: bool,
#[serde(skip)]
pub idempotency_key: Option<String>,
}
impl ExecStartRequest {
pub fn new<I, S>(argv: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
ExecStartRequest {
argv: argv.into_iter().map(Into::into).collect(),
env: BTreeMap::new(),
cwd: None,
timeout: None,
stdin: Vec::new(),
stdin_open: false,
idempotency_key: None,
}
}
}
impl fmt::Debug for ExecStartRequest {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ExecStartRequest")
.field("argv", &self.argv)
.field("env", &self.env.keys().collect::<Vec<_>>())
.field("cwd", &self.cwd)
.field("timeout", &self.timeout)
.field("stdin", &self.stdin.len())
.field("stdin_open", &self.stdin_open)
.field("idempotency_key", &self.idempotency_key)
.finish()
}
}
#[derive(Deserialize)]
struct Started {
id: String,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct ExecOutputRequest {
pub stdout_offset: u64,
pub stderr_offset: u64,
pub wait: Option<Duration>,
pub max_bytes: Option<u64>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Stream {
Stdout,
Stderr,
#[serde(other)]
Unknown,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "reason", rename_all = "snake_case")]
#[non_exhaustive]
pub enum ExecExit {
Exited {
code: i32,
},
Signaled {
signal: i32,
},
OutOfMemory,
Timeout,
SandboxEnded,
Lost,
#[serde(other)]
Unknown,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ExecOutput {
pub frames: Vec<ExecFrame>,
#[serde(default)]
pub exit: Option<ExecExit>,
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ExecFrame {
pub stream: Stream,
pub offset: u64,
#[serde(rename = "data_b64", with = "bytes_b64")]
pub data: Vec<u8>,
}
impl fmt::Debug for ExecFrame {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ExecFrame")
.field("stream", &self.stream)
.field("offset", &self.offset)
.field("len", &self.data.len())
.finish()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ExecInput {
Data(Vec<u8>),
Eof,
Signal(i32),
}
#[derive(Serialize)]
struct InputBody {
seq: u64,
#[serde(skip_serializing_if = "Option::is_none")]
data_b64: Option<String>,
#[serde(skip_serializing_if = "Not::not")]
eof: bool,
#[serde(skip_serializing_if = "Option::is_none")]
signal: Option<i32>,
}
#[derive(Deserialize)]
struct Ack {
next_seq: u64,
}
impl TimePortal {
pub async fn start_exec(&self, id: &str, request: &ExecStartRequest) -> Result<String, Error> {
if request.argv.first().is_none_or(String::is_empty) {
return Err(Error::InvalidArgument("argv must name a program".into()));
}
let key = request
.idempotency_key
.clone()
.unwrap_or_else(idempotency_key);
let http = self.request(Method::POST, &sandbox_path(id, "/execs")?);
let http = with_idempotency_key(http, &key);
let started: Started = self.client.json(with_json(http, request)?).await?;
Ok(started.id)
}
pub async fn read_exec_output(
&self,
id: &str,
exec: &str,
request: &ExecOutputRequest,
) -> Result<ExecOutput, Error> {
let mut query = vec![
("stdout_offset", request.stdout_offset.to_string()),
("stderr_offset", request.stderr_offset.to_string()),
];
if let Some(wait) = request.wait {
query.push(("wait", duration_param(wait)?));
}
if let Some(max_bytes) = request.max_bytes {
query.push(("max_bytes", max_bytes.to_string()));
}
let path = exec_path(id, exec, "/output")?;
self.client
.json(self.request(Method::GET, &path).query(&query))
.await
}
pub async fn send_exec_input(
&self,
id: &str,
exec: &str,
seq: u64,
input: &ExecInput,
) -> Result<u64, Error> {
let mut body = InputBody {
seq,
data_b64: None,
eof: false,
signal: None,
};
match input {
ExecInput::Data(data) => body.data_b64 = Some(bytes_b64::encode(data)),
ExecInput::Eof => body.eof = true,
ExecInput::Signal(signal) => body.signal = Some(*signal),
}
let http = self.request(Method::POST, &exec_path(id, exec, "/input")?);
let ack: Ack = self.client.json(with_json(http, &body)?).await?;
Ok(ack.next_seq)
}
}
fn exec_path(id: &str, exec: &str, rest: &str) -> Result<String, Error> {
sandbox_path(id, &format!("/execs/{}{rest}", segment(exec)?))
}