use serde::Serialize;
use serde_json::{json, Value};
use time::OffsetDateTime;
use crate::error::SailError;
use crate::http::{HttpCore, IdempotencyKey, Method, RequestSpec};
use crate::retry::DEFAULT_RETRY_POLICY;
#[derive(Debug, Clone, Serialize)]
pub struct App {
pub id: String,
pub name: String,
#[serde(with = "time::serde::timestamp")]
pub created_at: OffsetDateTime,
}
impl App {
fn from_json(row: &Value) -> App {
App {
id: row
.get("id")
.and_then(Value::as_str)
.unwrap_or("")
.to_string(),
name: row
.get("name")
.and_then(Value::as_str)
.unwrap_or("")
.to_string(),
created_at: OffsetDateTime::from_unix_timestamp(
row.get("created_at").and_then(Value::as_i64).unwrap_or(0),
)
.unwrap_or(OffsetDateTime::UNIX_EPOCH),
}
}
}
pub async fn find_app(
api_http: &HttpCore,
name: &str,
mint_if_missing: bool,
) -> Result<App, SailError> {
let body = json!({ "name": name, "mint_if_missing": mint_if_missing });
let bytes = serde_json::to_vec(&body).map_err(|e| SailError::Internal {
message: format!("failed to serialize request body: {e}"),
})?;
let (status, data) = api_http
.request(&RequestSpec {
method: Method::Post,
path: "/v1/apps/find".to_string(),
query: Vec::new(),
body: Some(bytes),
extra_headers: Vec::new(),
timeout: None,
policy: DEFAULT_RETRY_POLICY,
idempotency_key: IdempotencyKey::Auto,
})
.await?;
if status == 404 {
return Err(SailError::NotFound {
message: format!("App {name:?} not found"),
});
}
raise_app_error(status, &data, "Failed to find app")?;
Ok(App::from_json(&data))
}
pub async fn list_apps(api_http: &HttpCore) -> Result<Vec<App>, SailError> {
let (status, data) = api_http
.request(&RequestSpec {
method: Method::Get,
path: "/v1/apps".to_string(),
query: Vec::new(),
body: None,
extra_headers: Vec::new(),
timeout: None,
policy: DEFAULT_RETRY_POLICY,
idempotency_key: IdempotencyKey::Auto,
})
.await?;
raise_app_error(status, &data, "Failed to list apps")?;
let Some(rows) = data.get("data").and_then(Value::as_array) else {
return Ok(Vec::new());
};
Ok(rows.iter().map(App::from_json).collect())
}
fn raise_app_error(status: u16, data: &Value, context: &str) -> Result<(), SailError> {
if status < 300 {
return Ok(());
}
let detail = crate::http::api_error_message(data, "unknown error");
let message = format!("{context}: {detail}");
if status == 401 || status == 403 {
return Err(SailError::PermissionDenied { message });
}
Err(SailError::Api {
status,
message,
body: data.clone(),
})
}