#[derive(Debug, Clone)]
pub struct ClientConfig {
pub account_id: String,
pub host: String,
pub api_version: String,
pub timeout: std::time::Duration,
pub auth: crate::transport::AuthTransport,
pub max_retries: u32,
}
const DEFAULT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
const DEFAULT_MAX_RETRIES: u32 = 3;
impl ClientConfig {
pub fn builder(account_id: impl Into<String>, host: impl Into<String>) -> ClientConfigBuilder {
ClientConfigBuilder {
account_id: account_id.into(),
host: host.into(),
api_version: crate::transport::DEFAULT_API_VERSION.to_string(),
timeout: DEFAULT_TIMEOUT,
auth: None,
max_retries: DEFAULT_MAX_RETRIES,
}
}
pub fn base_url(&self) -> String {
let trimmed = self.host.trim_end_matches('/');
if let Some(host) = trimmed.strip_prefix("http://") {
format!("http://{host}/v1/accounts/{}", self.account_id)
} else {
let host = trimmed.strip_prefix("https://").unwrap_or(trimmed);
format!("https://{host}/v1/accounts/{}", self.account_id)
}
}
}
#[derive(Debug, Clone)]
pub struct ClientConfigBuilder {
account_id: String,
host: String,
api_version: String,
timeout: std::time::Duration,
auth: Option<crate::transport::AuthTransport>,
max_retries: u32,
}
impl ClientConfigBuilder {
pub fn api_version(mut self, version: impl Into<String>) -> Self {
self.api_version = version.into();
self
}
pub fn timeout(mut self, timeout: std::time::Duration) -> Self {
self.timeout = timeout;
self
}
pub fn auth(mut self, auth: crate::transport::AuthTransport) -> Self {
self.auth = Some(auth);
self
}
pub fn build(self) -> ClientConfig {
ClientConfig {
account_id: self.account_id,
host: self.host,
api_version: self.api_version,
timeout: self.timeout,
auth: self
.auth
.expect("ClientConfigBuilder::auth must be called before build()"),
max_retries: self.max_retries,
}
}
pub fn max_retries(mut self, retries: u32) -> Self {
self.max_retries = retries;
self
}
}
#[derive(Debug, Clone)]
pub struct Client {
pub(crate) http: reqwest::Client,
pub(crate) config: ClientConfig,
}
impl Client {
pub fn new(config: ClientConfig) -> Result<Self, crate::TamgaError> {
let http = reqwest::Client::builder()
.timeout(config.timeout)
.user_agent(concat!("tamga-rust/", env!("CARGO_PKG_VERSION")))
.build()
.map_err(crate::TamgaError::Http)?;
Ok(Client { http, config })
}
fn request(
&self,
method: reqwest::Method,
path: &str,
otp: Option<&str>,
) -> reqwest::RequestBuilder {
let url = format!("{}{path}", self.config.base_url());
let mut builder = self.http.request(method, url);
if let Some((name, value)) = self.config.auth.header() {
builder = builder.header(name, value);
}
if let Some((name, value)) = self.config.auth.query_param() {
builder = builder.query(&[(name, value)]);
}
builder = builder.header(
"Tamga-Version",
crate::transport::sanitize_version(&self.config.api_version),
);
if let Some(otp) = otp {
builder = builder.header("Tamga-OTP", otp);
}
builder
}
fn is_retryable(method: &reqwest::Method, path: &str) -> bool {
if method == reqwest::Method::GET {
return true;
}
method == reqwest::Method::POST
&& [
"/actions/validate",
"/actions/validate-key",
"/actions/check-in",
"/actions/check-out",
"/actions/ping",
]
.iter()
.any(|suffix| path.ends_with(suffix))
}
fn retry_delay(attempt: u32, retry_after: Option<u64>) -> std::time::Duration {
if let Some(secs) = retry_after {
return std::time::Duration::from_secs(secs.min(60));
}
let base = 1u64 << attempt.min(5); let jitter = crate::transport::jitter_millis(attempt);
std::time::Duration::from_millis(base * 1000 + jitter)
}
fn parse_retry_after(response: &reqwest::Response) -> Option<u64> {
response
.headers()
.get(reqwest::header::RETRY_AFTER)?
.to_str()
.ok()?
.trim()
.parse::<u64>()
.ok()
}
#[doc(hidden)]
pub fn retry_delay_for_test(attempt: u32, retry_after: Option<u64>) -> std::time::Duration {
Self::retry_delay(attempt, retry_after)
}
async fn send_with_retry(
&self,
builder: reqwest::RequestBuilder,
method: &reqwest::Method,
path: &str,
) -> Result<reqwest::Response, crate::TamgaError> {
let retryable = Self::is_retryable(method, path);
let mut attempt = 0u32;
loop {
let this_try = match builder.try_clone() {
Some(b) => b,
None => return builder.send().await.map_err(crate::TamgaError::Http),
};
let response = this_try.send().await?;
if response.status() != reqwest::StatusCode::TOO_MANY_REQUESTS
|| !retryable
|| attempt >= self.config.max_retries
{
return Ok(response);
}
let delay = Self::retry_delay(attempt, Self::parse_retry_after(&response));
tokio::time::sleep(delay).await;
attempt += 1;
}
}
async fn send_json_api<T: serde::de::DeserializeOwned>(
&self,
method: reqwest::Method,
path: &str,
body: Option<serde_json::Value>,
otp: Option<&str>,
) -> Result<T, crate::TamgaError> {
#[derive(serde::Deserialize)]
struct Envelope<T> {
data: T,
}
let mut builder = self
.request(method.clone(), path, otp)
.header(reqwest::header::CONTENT_TYPE, "application/vnd.api+json");
if let Some(body) = body {
builder = builder.json(&body);
}
let response = self.send_with_retry(builder, &method, path).await?;
if !response.status().is_success() {
return Err(Self::api_error(response).await);
}
let envelope: Envelope<T> = response.json().await?;
Ok(envelope.data)
}
async fn send_json_api_with_meta<T, M>(
&self,
method: reqwest::Method,
path: &str,
body: Option<serde_json::Value>,
otp: Option<&str>,
) -> Result<(T, M), crate::TamgaError>
where
T: serde::de::DeserializeOwned,
M: serde::de::DeserializeOwned,
{
#[derive(serde::Deserialize)]
struct EnvelopeWithMeta<T, M> {
data: T,
meta: M,
}
let mut builder = self
.request(method.clone(), path, otp)
.header(reqwest::header::CONTENT_TYPE, "application/vnd.api+json");
if let Some(body) = body {
builder = builder.json(&body);
}
let response = self.send_with_retry(builder, &method, path).await?;
if !response.status().is_success() {
return Err(Self::api_error(response).await);
}
let envelope: EnvelopeWithMeta<T, M> = response.json().await?;
Ok((envelope.data, envelope.meta))
}
async fn send_flat<T: serde::de::DeserializeOwned>(
&self,
method: reqwest::Method,
path: &str,
otp: Option<&str>,
) -> Result<T, crate::TamgaError> {
let builder = self.request(method.clone(), path, otp);
let response = self.send_with_retry(builder, &method, path).await?;
if !response.status().is_success() {
return Err(Self::api_error(response).await);
}
Ok(response.json().await?)
}
async fn api_error(response: reqwest::Response) -> crate::TamgaError {
let status = response.status();
if status == reqwest::StatusCode::TOO_MANY_REQUESTS {
let retry_after = Self::parse_retry_after(&response);
return crate::TamgaError::RateLimited { retry_after };
}
let json_api_error = match response.json::<crate::error::JsonApiErrorDocument>().await {
Ok(doc) => {
doc.errors
.into_iter()
.next()
.unwrap_or_else(|| crate::error::JsonApiError {
id: String::new(),
status: status.as_u16().to_string(),
code: "UNKNOWN".to_string(),
title: "Unknown Error".to_string(),
detail: "server returned an empty errors array".to_string(),
source: None,
})
}
Err(_) => crate::error::JsonApiError {
id: String::new(),
status: status.as_u16().to_string(),
code: "UNKNOWN".to_string(),
title: "Unknown Error".to_string(),
detail: format!("server returned {status} with a non-JSON:API body"),
source: None,
},
};
crate::TamgaError::from_json_api_error(json_api_error)
}
pub async fn validate_by_key(
&self,
key: &str,
otp: Option<&str>,
) -> Result<crate::models::validation::ValidationResult, crate::TamgaError> {
let body = serde_json::json!({ "key": key });
let (license, meta) = self
.send_json_api_with_meta(
reqwest::Method::POST,
"/licenses/actions/validate-key",
Some(body),
otp,
)
.await?;
Ok(crate::models::validation::ValidationResult { license, meta })
}
pub async fn validate_by_id(
&self,
license_id: uuid::Uuid,
scope: Option<crate::models::validation::ScopeObject>,
skip_touch: bool,
otp: Option<&str>,
) -> Result<crate::models::validation::ValidationResult, crate::TamgaError> {
let mut meta = serde_json::json!({ "skip_touch": skip_touch });
if let Some(scope) = scope {
meta["scope"] = serde_json::to_value(scope)?;
}
let body = serde_json::json!({ "meta": meta });
let (license, validation_meta) = self
.send_json_api_with_meta(
reqwest::Method::POST,
&format!("/licenses/{license_id}/actions/validate"),
Some(body),
otp,
)
.await?;
Ok(crate::models::validation::ValidationResult {
license,
meta: validation_meta,
})
}
pub async fn quick_validate(
&self,
license_id: uuid::Uuid,
otp: Option<&str>,
) -> Result<crate::models::validation::ValidationMeta, crate::TamgaError> {
self.send_flat(
reqwest::Method::GET,
&format!("/licenses/{license_id}/actions/validate"),
otp,
)
.await
}
pub async fn check_in(
&self,
license_id: uuid::Uuid,
) -> Result<crate::models::license::LicenseResource, crate::TamgaError> {
self.send_json_api(
reqwest::Method::POST,
&format!("/licenses/{license_id}/actions/check-in"),
None,
None,
)
.await
}
pub async fn check_out_license(
&self,
license_id: uuid::Uuid,
encrypt: bool,
ttl: Option<u64>,
) -> Result<String, crate::TamgaError> {
let mut builder = self.request(
reqwest::Method::GET,
&format!("/licenses/{license_id}/actions/check-out"),
None,
);
builder = builder.query(&[("encrypt", encrypt.to_string())]);
if let Some(ttl) = ttl {
builder = builder.query(&[("ttl", ttl.to_string())]);
}
let response = builder.send().await?;
if !response.status().is_success() {
return Err(Self::api_error(response).await);
}
Ok(response.text().await?)
}
pub async fn check_out_license_json(
&self,
license_id: uuid::Uuid,
encrypt: bool,
ttl: Option<u64>,
) -> Result<crate::checkout::license_file::LicenseFileResource, crate::TamgaError> {
let body = serde_json::json!({ "meta": { "encrypt": encrypt, "ttl": ttl } });
self.send_json_api(
reqwest::Method::POST,
&format!("/licenses/{license_id}/actions/check-out"),
Some(body),
None,
)
.await
}
pub async fn check_out_machine(
&self,
machine_id: uuid::Uuid,
encrypt: bool,
ttl: Option<u64>,
) -> Result<String, crate::TamgaError> {
if let Some(ttl) = ttl {
crate::checkout::machine_file::check_ttl(ttl)?;
}
let mut builder = self.request(
reqwest::Method::GET,
&format!("/machines/{machine_id}/actions/check-out"),
None,
);
builder = builder.query(&[("encrypt", encrypt.to_string())]);
if let Some(ttl) = ttl {
builder = builder.query(&[("ttl", ttl.to_string())]);
}
let response = builder.send().await?;
if !response.status().is_success() {
return Err(Self::api_error(response).await);
}
Ok(response.text().await?)
}
pub async fn check_out_machine_json(
&self,
machine_id: uuid::Uuid,
encrypt: bool,
ttl: Option<u64>,
) -> Result<crate::checkout::machine_file::MachineFileResource, crate::TamgaError> {
if let Some(ttl) = ttl {
crate::checkout::machine_file::check_ttl(ttl)?;
}
let body = serde_json::json!({ "meta": { "encrypt": encrypt, "ttl": ttl } });
self.send_json_api(
reqwest::Method::POST,
&format!("/machines/{machine_id}/actions/check-out"),
Some(body),
None,
)
.await
}
pub async fn create_machine(
&self,
license_id: uuid::Uuid,
fingerprint: &str,
opts: CreateMachineOptions,
) -> Result<crate::models::machine::MachineResource, crate::TamgaError> {
let body = serde_json::json!({
"data": {
"type": "machines",
"attributes": {
"fingerprint": fingerprint,
"name": opts.name,
"ip": opts.ip,
"hostname": opts.hostname,
"platform": opts.platform,
"cores": opts.cores,
"memory": opts.memory,
"disk": opts.disk,
"metadata": opts.metadata.unwrap_or_else(|| serde_json::json!({})),
},
"relationships": {
"license": { "data": { "type": "licenses", "id": license_id } }
}
}
});
self.send_json_api(reqwest::Method::POST, "/machines", Some(body), None)
.await
}
pub async fn activate_machine(
&self,
license_id: uuid::Uuid,
fingerprint: &str,
opts: CreateMachineOptions,
scope: Option<crate::models::validation::ScopeObject>,
auto_delete_on_overage: bool,
) -> Result<crate::models::validation::ValidationResult, crate::TamgaError> {
let machine = self.create_machine(license_id, fingerprint, opts).await?;
let result = self.validate_by_id(license_id, scope, false, None).await;
if auto_delete_on_overage {
let is_overage = matches!(
&result,
Ok(r) if is_overage_code(&r.meta.code)
);
if is_overage {
let _ = self.delete_machine(machine.id).await;
}
}
result
}
pub async fn ping_heartbeat(
&self,
machine_id: uuid::Uuid,
) -> Result<crate::models::machine::MachineResource, crate::TamgaError> {
self.send_json_api(
reqwest::Method::POST,
&format!("/machines/{machine_id}/actions/ping-heartbeat"),
None,
None,
)
.await
}
pub async fn reset_heartbeat(
&self,
machine_id: uuid::Uuid,
) -> Result<crate::models::machine::MachineResource, crate::TamgaError> {
self.send_json_api(
reqwest::Method::POST,
&format!("/machines/{machine_id}/actions/reset-heartbeat"),
None,
None,
)
.await
}
pub async fn delete_machine(&self, machine_id: uuid::Uuid) -> Result<(), crate::TamgaError> {
let response = self
.request(
reqwest::Method::DELETE,
&format!("/machines/{machine_id}"),
None,
)
.send()
.await?;
if !response.status().is_success() {
return Err(Self::api_error(response).await);
}
Ok(())
}
pub async fn generate_offline_proof(
&self,
machine_id: uuid::Uuid,
dataset: Option<serde_json::Value>,
) -> Result<(crate::models::machine::MachineResource, String), crate::TamgaError> {
#[derive(serde::Deserialize)]
struct ProofMeta {
proof: String,
}
let body = serde_json::json!({
"meta": { "dataset": dataset.unwrap_or_else(|| serde_json::json!({})) }
});
let (machine, meta): (crate::models::machine::MachineResource, ProofMeta) = self
.send_json_api_with_meta(
reqwest::Method::POST,
&format!("/machines/{machine_id}/actions/generate-offline-proof"),
Some(body),
None,
)
.await?;
Ok((machine, meta.proof))
}
pub async fn create_component(
&self,
machine_id: uuid::Uuid,
fingerprint: &str,
name: &str,
metadata: Option<serde_json::Value>,
) -> Result<crate::models::machine::ComponentResource, crate::TamgaError> {
let body = serde_json::json!({
"machine_id": machine_id,
"fingerprint": fingerprint,
"name": name,
"metadata": metadata.unwrap_or_else(|| serde_json::json!({})),
});
self.send_json_api(reqwest::Method::POST, "/components", Some(body), None)
.await
}
pub async fn list_components(
&self,
machine_id: uuid::Uuid,
limit: Option<u32>,
after: Option<uuid::Uuid>,
) -> Result<Vec<crate::models::machine::ComponentResource>, crate::TamgaError> {
#[derive(serde::Deserialize)]
struct Envelope {
data: Vec<crate::models::machine::ComponentResource>,
}
let mut builder = self.request(
reqwest::Method::GET,
&format!("/machines/{machine_id}/components"),
None,
);
if let Some(limit) = limit {
builder = builder.query(&[("limit", limit.to_string())]);
}
if let Some(after) = after {
builder = builder.query(&[("page[after]", after.to_string())]);
}
let response = builder.send().await?;
if !response.status().is_success() {
return Err(Self::api_error(response).await);
}
let envelope: Envelope = response.json().await?;
Ok(envelope.data)
}
pub async fn create_process(
&self,
machine_id: uuid::Uuid,
pid: impl Into<crate::models::machine::Pid>,
metadata: Option<serde_json::Value>,
) -> Result<crate::models::machine::ProcessResource, crate::TamgaError> {
let body = serde_json::json!({
"machine_id": machine_id,
"pid": pid.into(),
"metadata": metadata.unwrap_or_else(|| serde_json::json!({})),
});
self.send_json_api(reqwest::Method::POST, "/processes", Some(body), None)
.await
}
pub async fn ping_process(
&self,
process_id: uuid::Uuid,
) -> Result<crate::models::machine::ProcessResource, crate::TamgaError> {
self.send_json_api(
reqwest::Method::POST,
&format!("/processes/{process_id}/actions/ping"),
None,
None,
)
.await
}
pub async fn list_entitlements(
&self,
license_id: uuid::Uuid,
limit: Option<u32>,
after: Option<uuid::Uuid>,
) -> Result<Vec<crate::models::entitlement::EntitlementResource>, crate::TamgaError> {
#[derive(serde::Deserialize)]
struct Envelope {
data: Vec<crate::models::entitlement::EntitlementResource>,
}
let mut builder = self.request(
reqwest::Method::GET,
&format!("/licenses/{license_id}/entitlements"),
None,
);
if let Some(limit) = limit {
builder = builder.query(&[("limit", limit.to_string())]);
}
if let Some(after) = after {
builder = builder.query(&[("page[after]", after.to_string())]);
}
let response = builder.send().await?;
if !response.status().is_success() {
return Err(Self::api_error(response).await);
}
let envelope: Envelope = response.json().await?;
Ok(envelope.data)
}
pub async fn get_entitlement(
&self,
license_id: uuid::Uuid,
entitlement_id: uuid::Uuid,
) -> Result<crate::models::entitlement::EntitlementResource, crate::TamgaError> {
self.send_json_api(
reqwest::Method::GET,
&format!("/licenses/{license_id}/entitlements/{entitlement_id}"),
None,
None,
)
.await
}
pub async fn has_entitlement(
&self,
license_id: uuid::Uuid,
code: &str,
limit: Option<u32>,
) -> Result<bool, crate::TamgaError> {
let entitlements = self
.list_entitlements(license_id, Some(limit.unwrap_or(100)), None)
.await?;
Ok(entitlements.iter().any(|e| e.attributes.code == code))
}
}
#[derive(Debug, Clone, Default)]
pub struct CreateMachineOptions {
pub name: Option<String>,
pub ip: Option<String>,
pub hostname: Option<String>,
pub platform: Option<String>,
pub cores: Option<i32>,
pub memory: Option<i64>,
pub disk: Option<i64>,
pub metadata: Option<serde_json::Value>,
}
fn is_overage_code(code: &crate::models::validation::ValidationCode) -> bool {
use crate::models::validation::ValidationCode;
matches!(
code,
ValidationCode::TooManyMachines
| ValidationCode::TooManyCores
| ValidationCode::TooMuchMemory
| ValidationCode::TooMuchDisk
| ValidationCode::TooManyProcesses
)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::transport::AuthTransport;
#[test]
fn builder_sets_required_fields() {
let config = ClientConfig::builder("acc-123", "api.tamga.sh")
.auth(AuthTransport::License("lic-abc".to_string()))
.build();
assert_eq!(config.account_id, "acc-123");
assert_eq!(config.host, "api.tamga.sh");
}
#[test]
fn builder_defaults_api_version_to_1_8() {
let config = ClientConfig::builder("acc-123", "api.tamga.sh")
.auth(AuthTransport::License("lic-abc".to_string()))
.build();
assert_eq!(config.api_version, "1.8");
}
#[test]
fn builder_defaults_timeout_to_30_seconds() {
let config = ClientConfig::builder("acc-123", "api.tamga.sh")
.auth(AuthTransport::License("lic-abc".to_string()))
.build();
assert_eq!(config.timeout, std::time::Duration::from_secs(30));
}
#[test]
fn builder_allows_overriding_api_version_and_timeout() {
let config = ClientConfig::builder("acc-123", "api.tamga.sh")
.auth(AuthTransport::License("lic-abc".to_string()))
.api_version("2.0")
.timeout(std::time::Duration::from_secs(5))
.build();
assert_eq!(config.api_version, "2.0");
assert_eq!(config.timeout, std::time::Duration::from_secs(5));
}
#[test]
fn base_url_has_no_trailing_slash() {
let config = ClientConfig::builder("acc-123", "api.tamga.sh")
.auth(AuthTransport::License("lic-abc".to_string()))
.build();
assert_eq!(
config.base_url(),
"https://api.tamga.sh/v1/accounts/acc-123"
);
}
#[test]
fn base_url_strips_trailing_slash_from_host() {
let config = ClientConfig::builder("acc-123", "api.tamga.sh/")
.auth(AuthTransport::License("lic-abc".to_string()))
.build();
assert_eq!(
config.base_url(),
"https://api.tamga.sh/v1/accounts/acc-123"
);
}
#[test]
fn base_url_strips_scheme_if_caller_included_one() {
let config = ClientConfig::builder("acc-123", "https://api.tamga.sh")
.auth(AuthTransport::License("lic-abc".to_string()))
.build();
assert_eq!(
config.base_url(),
"https://api.tamga.sh/v1/accounts/acc-123"
);
}
#[test]
fn base_url_preserves_explicit_http_scheme_for_local_testing() {
let config = ClientConfig::builder("acc-123", "http://127.0.0.1:8080")
.auth(AuthTransport::License("lic-abc".to_string()))
.build();
assert_eq!(
config.base_url(),
"http://127.0.0.1:8080/v1/accounts/acc-123"
);
}
#[test]
fn client_new_succeeds_with_valid_config() {
let config = ClientConfig::builder("acc-123", "api.tamga.sh")
.auth(AuthTransport::License("lic-abc".to_string()))
.build();
let client = Client::new(config);
assert!(client.is_ok());
}
}