use std::{collections::HashMap, fmt, time::Duration};
use percent_encoding::{NON_ALPHANUMERIC, utf8_percent_encode};
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tokio_util::sync::CancellationToken;
use crate::{
DEFAULT_TIMEOUT, DEFAULT_USER_ENDPOINT, ErpcError, Result, config::endpoint,
rest::RestTransport, usage::UsageClient,
};
#[derive(Clone)]
pub struct ErpcCloudClientConfig {
access_token: String,
pub endpoint: String,
pub headers: Vec<(String, String)>,
pub timeout: Duration,
}
impl ErpcCloudClientConfig {
#[must_use]
pub fn new(access_token: impl Into<String>) -> Self {
Self {
access_token: access_token.into(),
endpoint: DEFAULT_USER_ENDPOINT.to_owned(),
headers: Vec::new(),
timeout: DEFAULT_TIMEOUT,
}
}
#[must_use]
pub fn with_endpoint(mut self, endpoint: impl Into<String>) -> Self {
self.endpoint = endpoint.into();
self
}
#[must_use]
pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.headers.push((name.into(), value.into()));
self
}
#[must_use]
pub const fn with_timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
}
impl fmt::Debug for ErpcCloudClientConfig {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ErpcCloudClientConfig")
.field("access_token", &"[REDACTED]")
.field("endpoint", &self.endpoint)
.field(
"header_names",
&self
.headers
.iter()
.map(|(name, _)| name)
.collect::<Vec<_>>(),
)
.field("timeout", &self.timeout)
.finish()
}
}
#[derive(Clone)]
pub struct ErpcCloudClient {
pub catalog: CloudCatalogClient,
pub credit: CloudCreditClient,
pub resources: CloudResourcesClient,
pub usage: UsageClient,
}
impl ErpcCloudClient {
pub fn new(config: ErpcCloudClientConfig) -> Result<Self> {
let access_token = config.access_token.trim().to_owned();
if access_token.is_empty() {
return Err(ErpcError::Config(
"access_token must not be empty".to_owned(),
));
}
if config.timeout.is_zero() {
return Err(ErpcError::Config("timeout must be positive".to_owned()));
}
let mut headers = HeaderMap::new();
for (name, value) in config.headers {
let name: HeaderName = name
.parse()
.map_err(|_| ErpcError::Config("header name is invalid".to_owned()))?;
let value: HeaderValue = value
.parse()
.map_err(|_| ErpcError::Config("header value is invalid".to_owned()))?;
headers.insert(name, value);
}
let client = reqwest::Client::builder()
.build()
.map_err(|_| ErpcError::Config("unable to create HTTP client".to_owned()))?;
let transport = RestTransport::new(
access_token,
endpoint(&config.endpoint, true)?,
headers,
config.timeout,
client,
);
Ok(Self {
catalog: CloudCatalogClient::new(transport.clone()),
credit: CloudCreditClient::new(transport.clone()),
resources: CloudResourcesClient::new(transport.clone()),
usage: UsageClient::new(transport),
})
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum CloudResourceKind {
BareMetal,
SolanaGrpc,
SolanaShredstream,
Vps,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum CloudResourceMode {
Dedicated,
Direct,
Shared,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CloudOfferingBilling {
pub amount_cents: u64,
pub unit: String,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum CloudOfferingComputeTenancy {
BareMetal,
VirtualMachine,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct CloudOfferingCompute {
pub tenancy: CloudOfferingComputeTenancy,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum CloudOfferingSolanaTransport {
Grpc,
Shredstream,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct CloudOfferingSolana {
pub transport: CloudOfferingSolanaTransport,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CloudOffering {
pub billing: Option<CloudOfferingBilling>,
pub capabilities: Vec<String>,
pub compute: Option<CloudOfferingCompute>,
pub description: String,
pub id: String,
pub kind: CloudResourceKind,
pub mode: Option<CloudResourceMode>,
pub name: String,
pub regions: Vec<String>,
pub solana: Option<CloudOfferingSolana>,
}
#[derive(Clone)]
pub struct CloudCatalogClient {
transport: RestTransport,
}
impl CloudCatalogClient {
const fn new(transport: RestTransport) -> Self {
Self { transport }
}
pub async fn list(&self) -> Result<Vec<CloudOffering>> {
self.list_with(None).await
}
pub async fn list_with(
&self,
cancellation: Option<&CancellationToken>,
) -> Result<Vec<CloudOffering>> {
let envelope: Envelope<CatalogMessage> = self
.transport
.get("/v4/cloud/catalog", Vec::new(), cancellation)
.await?;
if !envelope.success
|| envelope.message.offerings.iter().any(|offering| {
offering
.billing
.as_ref()
.is_some_and(|billing| billing.unit != "cents-per-hour")
})
{
return Err(invalid_cloud("catalog"));
}
Ok(envelope.message.offerings)
}
}
#[derive(Deserialize)]
struct CatalogMessage {
offerings: Vec<CloudOffering>,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum CloudCreditAlertLevel {
Critical,
Normal,
Suspended,
Warning,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CloudCredit {
pub alert_level: CloudCreditAlertLevel,
pub balance_cents: i64,
pub burn_rate_cents_per_hour: u64,
pub quote_expires_at: String,
pub quote_timestamp: String,
pub time_to_zero_hours: Option<f64>,
}
#[derive(Clone)]
pub struct CloudCreditClient {
transport: RestTransport,
}
impl CloudCreditClient {
const fn new(transport: RestTransport) -> Self {
Self { transport }
}
pub async fn get(&self) -> Result<CloudCredit> {
self.get_with(None).await
}
pub async fn get_with(&self, cancellation: Option<&CancellationToken>) -> Result<CloudCredit> {
let envelope: Envelope<CloudCredit> = self
.transport
.get("/v4/cloud/credit", Vec::new(), cancellation)
.await?;
let credit = envelope.message;
if !envelope.success
|| credit
.time_to_zero_hours
.is_some_and(|value| !value.is_finite() || value < 0.0)
|| !likely_datetime(&credit.quote_timestamp)
|| !likely_datetime(&credit.quote_expires_at)
{
return Err(invalid_cloud("credit snapshot"));
}
Ok(credit)
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CloudResource {
pub created_at: Option<String>,
pub id: String,
pub kind: CloudResourceKind,
pub mode: Option<CloudResourceMode>,
pub name: Option<String>,
pub region: Option<String>,
pub status: String,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CloudResourceStatusBilling {
pub grace_ends_at: Option<String>,
pub hourly_credits: Option<f64>,
pub next_charge_at: Option<String>,
pub status: CloudResourceBillingStatus,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum CloudResourceBillingStatus {
Active,
GracePeriod,
Inactive,
Suspended,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CloudResourceStatus {
pub billing: Option<CloudResourceStatusBilling>,
pub id: String,
pub status: String,
}
#[derive(Clone)]
pub struct CloudResourcesClient {
transport: RestTransport,
}
impl CloudResourcesClient {
const fn new(transport: RestTransport) -> Self {
Self { transport }
}
pub async fn list(&self) -> Result<Vec<CloudResource>> {
self.list_with(None).await
}
pub async fn list_with(
&self,
cancellation: Option<&CancellationToken>,
) -> Result<Vec<CloudResource>> {
let envelope: Envelope<ResourceListMessage> = self
.transport
.get("/v4/cloud/resources", Vec::new(), cancellation)
.await?;
if !envelope.success {
return Err(invalid_cloud("resource list"));
}
Ok(envelope.message.resources)
}
pub async fn get(&self, resource_id: &str) -> Result<CloudResource> {
self.get_with(resource_id, None).await
}
pub async fn get_with(
&self,
resource_id: &str,
cancellation: Option<&CancellationToken>,
) -> Result<CloudResource> {
let id = resource_id.trim();
if id.is_empty() {
return Err(ErpcError::Config(
"resource_id must not be empty".to_owned(),
));
}
let path = format!(
"/v4/cloud/resources/{}",
utf8_percent_encode(id, NON_ALPHANUMERIC)
);
let envelope: Envelope<ResourceMessage> =
self.transport.get(&path, Vec::new(), cancellation).await?;
if !envelope.success {
return Err(invalid_cloud("resource"));
}
Ok(envelope.message.resource)
}
pub async fn get_status(&self, resource_id: &str) -> Result<CloudResourceStatus> {
self.get_status_with(resource_id, None).await
}
pub async fn get_status_with(
&self,
resource_id: &str,
cancellation: Option<&CancellationToken>,
) -> Result<CloudResourceStatus> {
let id = resource_id.trim();
if id.is_empty() {
return Err(ErpcError::Config(
"resource_id must not be empty".to_owned(),
));
}
let path = format!(
"/v4/cloud/resources/{}/status",
utf8_percent_encode(id, NON_ALPHANUMERIC)
);
let envelope: Envelope<CloudResourceStatus> =
self.transport.get(&path, Vec::new(), cancellation).await?;
if !envelope.success || !valid_billing(envelope.message.billing.as_ref()) {
return Err(invalid_cloud("resource status"));
}
Ok(envelope.message)
}
}
#[derive(Deserialize)]
struct ResourceListMessage {
resources: Vec<CloudResource>,
}
#[derive(Deserialize)]
struct ResourceMessage {
resource: CloudResource,
}
#[derive(Deserialize)]
struct Envelope<T> {
success: bool,
message: T,
#[serde(flatten)]
_other: HashMap<String, Value>,
}
fn invalid_cloud(resource: &str) -> ErpcError {
ErpcError::InvalidResponse(format!("ERPC returned an invalid Cloud {resource}"))
}
fn likely_datetime(value: &str) -> bool {
value.len() >= 20 && value.contains('T') && (value.ends_with('Z') || value.contains('+'))
}
fn valid_billing(billing: Option<&CloudResourceStatusBilling>) -> bool {
billing.is_none_or(|billing| {
billing
.hourly_credits
.is_none_or(|value| value.is_finite() && value >= 0.0)
&& billing
.next_charge_at
.as_deref()
.is_none_or(likely_datetime)
&& billing.grace_ends_at.as_deref().is_none_or(likely_datetime)
})
}