use serde::{Deserialize, Serialize};
use super::{ActionAddress, RemoteActionTarget};
pub const PROVIDER: &str = "tilo.server";
pub const RESOURCE: &str = "server.account";
pub const ACCOUNT: &str = "account";
#[must_use]
pub fn target(action: &str) -> RemoteActionTarget {
RemoteActionTarget {
provider: PROVIDER.to_owned(),
address: ActionAddress::new(RESOURCE, action),
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ServerKind {
#[default]
Device,
SelfHosted,
Provider,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Limits {
pub max_running: u32,
pub max_vms: u32,
pub sizes: Vec<String>,
pub included_vm_seconds: Option<u64>,
pub storage_bytes: Option<u64>,
pub max_workspaces: Option<u32>,
pub free_browser_actions: Option<u32>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct PlanOffer {
pub id: String,
pub name: String,
pub price: Option<String>,
pub limits: Limits,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Entitlement {
LinuxVms,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct WorkspaceUsage {
pub workspace: String,
pub vm_seconds: u64,
pub snapshot_seconds: u64,
pub running: bool,
pub stored_bytes: u64,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Usage {
pub period_start_ms: u64,
pub period_end_ms: u64,
pub browser_actions: u64,
pub workspaces: Vec<WorkspaceUsage>,
}
impl Usage {
#[must_use]
pub fn vm_seconds(&self) -> u64 {
self.workspaces
.iter()
.fold(0_u64, |sum, usage| sum.saturating_add(usage.vm_seconds))
}
#[must_use]
pub fn stored_bytes(&self) -> u64 {
self.workspaces
.iter()
.fold(0_u64, |sum, usage| sum.saturating_add(usage.stored_bytes))
}
#[must_use]
pub fn of(&self, workspace: &str) -> Option<&WorkspaceUsage> {
self.workspaces
.iter()
.find(|usage| usage.workspace == workspace)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum InvoiceStatus {
Paid,
#[default]
Open,
PastDue,
Void,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Invoice {
pub id: String,
pub issued_ms: u64,
pub amount: String,
pub status: InvoiceStatus,
pub url: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct PaymentMethod {
pub brand: Option<String>,
pub last4: Option<String>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Subscription {
pub account: String,
pub plan: Option<String>,
pub payment_method: Option<PaymentMethod>,
pub entitlements: Vec<Entitlement>,
pub limits: Option<Limits>,
pub usage: Usage,
pub credit: Option<String>,
pub invoices: Vec<Invoice>,
}
impl Subscription {
#[must_use]
pub fn entitled(&self, entitlement: Entitlement) -> bool {
self.entitlements.contains(&entitlement)
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct ServerAccount {
pub server: String,
pub kind: ServerKind,
pub plans: Vec<PlanOffer>,
pub subscription: Option<Subscription>,
pub manage_billing: Option<String>,
}
impl ServerAccount {
#[must_use]
pub fn sells_nothing(server: impl Into<String>, kind: ServerKind) -> Self {
Self {
server: server.into(),
kind,
..Self::default()
}
}
#[must_use]
pub fn sells(&self) -> bool {
!self.plans.is_empty()
}
#[must_use]
pub fn plan(&self) -> Option<&PlanOffer> {
let id = self.subscription.as_ref()?.plan.as_deref()?;
self.plans.iter().find(|plan| plan.id == id)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NextStepKind {
AddPaymentMethod,
RaiseLimit,
ChooseSize,
WaitForIdle,
UseExisting,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct NextStep {
pub kind: NextStepKind,
#[serde(default)]
pub url: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Reason {
NoPaymentMethod,
SizeNotInPlan { size: String, allowed: Vec<String> },
TooManyRunning {
limit: u32,
running: Vec<String>,
},
TooManyVms { limit: u32, existing: u32 },
StorageFull { limit_bytes: u64, used_bytes: u64 },
TooManyWorkspaces {
limit: u32,
existing: Vec<String>,
},
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Refusal {
pub reason: Reason,
pub message: String,
#[serde(default)]
pub next: Vec<NextStep>,
}
impl Refusal {
#[must_use]
pub fn step(&self, kind: NextStepKind) -> Option<&NextStep> {
self.next.iter().find(|step| step.kind == kind)
}
#[must_use]
pub const fn awaits_the_account(&self) -> bool {
matches!(self.reason, Reason::NoPaymentMethod)
}
#[must_use]
pub fn to_reason(&self) -> String {
serde_json::to_string(self).unwrap_or_else(|_| self.message.clone())
}
#[must_use]
pub fn from_reason(reason: &str) -> Option<Self> {
serde_json::from_str(reason).ok()
}
}
impl std::fmt::Display for Refusal {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.message)
}
}
#[cfg(test)]
mod tests {
use super::*;
tilo_test_env::scenario! {
fn a_server_account_answers_plans_and_typed_refusals;
phase a_host_that_sells_nothing_answers_no_plans_and_no_subscription;
{
let account = ServerAccount::sells_nothing("Ada's server", ServerKind::SelfHosted);
assert!(!account.sells());
assert!(account.plan().is_none());
let json = serde_json::to_value(&account).unwrap();
assert_eq!(
json,
serde_json::json!({
"server": "Ada's server",
"kind": "self-hosted",
"plans": [],
"subscription": null,
"manage_billing": null
})
);
assert_eq!(serde_json::from_value::<ServerAccount>(json).unwrap(), account);
}
phase a_refusal_names_its_reason_and_next_steps_on_the_wire;
{
let refusal = Refusal {
reason: Reason::NoPaymentMethod,
message: "This needs a Linux machine.".into(),
next: vec![NextStep {
kind: NextStepKind::AddPaymentMethod,
url: Some("https://billing.example/card".into()),
}],
};
let json = serde_json::to_value(&refusal).unwrap();
assert_eq!(
json,
serde_json::json!({
"reason": "no_payment_method",
"message": "This needs a Linux machine.",
"next": [{"kind": "add_payment_method", "url": "https://billing.example/card"}]
})
);
assert!(refusal.awaits_the_account());
let bytes = postcard::to_allocvec(&refusal).unwrap();
assert_eq!(postcard::from_bytes::<Refusal>(&bytes).unwrap(), refusal);
assert_eq!(
refusal
.step(NextStepKind::AddPaymentMethod)
.and_then(|step| step.url.as_deref()),
Some("https://billing.example/card")
);
let limit = Refusal {
reason: Reason::TooManyRunning {
limit: 1,
running: vec!["ws1".into()],
},
message: String::new(),
next: Vec::new(),
};
assert!(!limit.awaits_the_account());
assert_eq!(
serde_json::to_value(&limit.reason).unwrap(),
serde_json::json!({"too_many_running": {"limit": 1, "running": ["ws1"]}})
);
}
phase storage_refusals_cross_an_actions_reason_typed;
{
let full = Refusal {
reason: Reason::StorageFull {
limit_bytes: 10,
used_bytes: 12,
},
message: "Your workspace is full.".into(),
next: vec![NextStep {
kind: NextStepKind::RaiseLimit,
url: None,
}],
};
assert_eq!(
serde_json::to_value(&full.reason).unwrap(),
serde_json::json!({"storage_full": {"limit_bytes": 10, "used_bytes": 12}})
);
assert_eq!(Refusal::from_reason(&full.to_reason()), Some(full.clone()));
assert!(!full.awaits_the_account());
assert_eq!(Refusal::from_reason("the host refused"), None);
let second = Reason::TooManyWorkspaces {
limit: 1,
existing: vec!["w".into()],
};
let bytes = postcard::to_allocvec(&second).unwrap();
assert_eq!(postcard::from_bytes::<Reason>(&bytes).unwrap(), second);
let usage = Usage {
workspaces: vec![
WorkspaceUsage {
workspace: "a".into(),
stored_bytes: 7,
..WorkspaceUsage::default()
},
WorkspaceUsage {
workspace: "b".into(),
stored_bytes: 5,
..WorkspaceUsage::default()
},
],
..Usage::default()
};
assert_eq!(usage.stored_bytes(), 12);
}
phase the_plan_an_account_is_on_is_one_of_the_offers;
{
let host = ServerAccount {
server: "Tilo Cloud".into(),
kind: ServerKind::Provider,
plans: vec![PlanOffer {
id: "pro".into(),
name: "Pro".into(),
..PlanOffer::default()
}],
subscription: Some(Subscription {
plan: Some("pro".into()),
usage: Usage {
workspaces: vec![
WorkspaceUsage {
workspace: "a".into(),
vm_seconds: 60,
..WorkspaceUsage::default()
},
WorkspaceUsage {
workspace: "b".into(),
vm_seconds: 30,
..WorkspaceUsage::default()
},
],
..Usage::default()
},
..Subscription::default()
}),
manage_billing: Some("https://billing.example".into()),
};
assert!(host.sells());
let bytes = postcard::to_allocvec(&host).unwrap();
assert_eq!(postcard::from_bytes::<ServerAccount>(&bytes).unwrap(), host);
assert_eq!(host.plan().map(|plan| plan.name.as_str()), Some("Pro"));
let usage = &host.subscription.as_ref().unwrap().usage;
assert_eq!(usage.vm_seconds(), 90);
assert_eq!(usage.of("b").map(|usage| usage.vm_seconds), Some(30));
}
}
}