use bytes::Bytes;
use reqwest::header::{CONTENT_RANGE, CONTENT_TYPE, HeaderMap, RANGE};
use reqwest::{Method, StatusCode};
use serde::de::Error as _;
use serde::{Deserialize, Serialize};
use super::sandbox_path;
use crate::error::{Error, failure, transport};
use crate::time_portal::TimePortal;
const FILES: &str = "/files";
const OCTETS: &str = "application/octet-stream";
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum FileType {
File,
Directory,
Symlink,
#[serde(other)]
Other,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct FileStat {
pub path: String,
#[serde(rename = "type")]
pub file_type: FileType,
pub size: u64,
pub mode: u32,
#[serde(default)]
pub mtime: Option<String>,
#[serde(default)]
pub link_target: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct FileList {
pub entries: Vec<FileStat>,
#[serde(default)]
pub next_cursor: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct FileListRequest {
pub path: String,
pub recursive: bool,
pub cursor: Option<String>,
pub limit: Option<u32>,
}
impl FileListRequest {
pub fn new(path: impl Into<String>) -> Self {
FileListRequest {
path: path.into(),
recursive: false,
cursor: None,
limit: None,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct FileRange {
pub start: u64,
pub data: Vec<u8>,
pub total: Option<u64>,
}
impl TimePortal {
pub async fn stat_file(&self, id: &str, path: &str) -> Result<FileStat, Error> {
let http = self
.request(Method::GET, &sandbox_path(id, "/files/stat")?)
.query(&[("path", path)]);
self.client.json(http).await
}
pub async fn list_files(&self, id: &str, request: &FileListRequest) -> Result<FileList, Error> {
let mut query = vec![("path", request.path.clone())];
if request.recursive {
query.push(("recursive", true.to_string()));
}
if let Some(cursor) = &request.cursor {
query.push(("cursor", cursor.clone()));
}
if let Some(limit) = request.limit {
query.push(("limit", limit.to_string()));
}
let http = self.request(Method::GET, &sandbox_path(id, "/files/list")?);
self.client.json(http.query(&query)).await
}
pub async fn read_file(
&self,
id: &str,
path: &str,
offset: u64,
len: Option<u64>,
) -> Result<FileRange, Error> {
let range = match len {
Some(0) => {
return Err(Error::InvalidArgument(
"a read must ask for at least one byte".into(),
));
}
Some(len) => format!("bytes={offset}-{}", offset.saturating_add(len - 1)),
None => format!("bytes={offset}-"),
};
let http = self
.request(Method::GET, &sandbox_path(id, FILES)?)
.query(&[("path", path)])
.header(RANGE, range);
let resp = self.client.send_any(http).await?;
let status = resp.status();
let (start, total) = content_range(resp.headers());
match status {
StatusCode::RANGE_NOT_SATISFIABLE => Ok(FileRange {
start: offset,
data: Vec::new(),
total,
}),
StatusCode::PARTIAL_CONTENT => Ok(FileRange {
start: start.unwrap_or(offset),
data: resp.bytes().await.map_err(transport)?.into(),
total,
}),
StatusCode::OK => Ok(FileRange {
start: 0,
data: resp.bytes().await.map_err(transport)?.into(),
total,
}),
_ if !status.is_success() => Err(failure(resp).await),
_ => Err(Error::Decode(serde_json::Error::custom(format!(
"{path}: a range read answered HTTP {status}"
)))),
}
}
pub async fn write_file(
&self,
id: &str,
path: &str,
offset: u64,
data: impl Into<Bytes>,
) -> Result<FileStat, Error> {
let http = self
.request(Method::PUT, &sandbox_path(id, FILES)?)
.query(&[("path", path), ("offset", &offset.to_string())])
.header(CONTENT_TYPE, OCTETS)
.body(data.into());
self.client.json(http).await
}
pub async fn remove_file(&self, id: &str, path: &str, recursive: bool) -> Result<(), Error> {
let mut query = vec![("path", path.to_owned())];
if recursive {
query.push(("recursive", true.to_string()));
}
let http = self.request(Method::DELETE, &sandbox_path(id, FILES)?);
self.client.send(http.query(&query)).await?;
Ok(())
}
}
fn content_range(headers: &HeaderMap) -> (Option<u64>, Option<u64>) {
let Some(value) = headers.get(CONTENT_RANGE).and_then(|v| v.to_str().ok()) else {
return (None, None);
};
let Some((span, size)) = value.trim_start_matches("bytes ").rsplit_once('/') else {
return (None, None);
};
let first = span
.split_once('-')
.and_then(|(first, _)| first.parse().ok());
(first, size.parse().ok())
}