Rename tenant fields to tenant_pubkey and plan to plan_id

This commit is contained in:
Jon Staab
2026-05-28 15:18:41 -07:00
parent 9f599d66be
commit eb0123abef
18 changed files with 148 additions and 148 deletions
+21 -23
View File
@@ -79,7 +79,7 @@ impl Billing {
command::set_tenant_billing_anchor(&tenant).await?;
}
let invoice_item = self.reconcile_activity(&tenant, &activity).await?;
self.reconcile_activity(&tenant, &activity).await?;
}
// If the tenant has no billing anchor, they have nothing to bill
@@ -104,7 +104,7 @@ impl Billing {
/// persist it with the activity's billed marker. Activities that produce no
/// item (e.g. free-plan changes) are still marked billed so they aren't
/// re-scanned.
async fn reconcile_activity(&self, tenant: &Tenant, activity: &Activity) -> Result<Option<InvoiceItem>> {
async fn reconcile_activity(&self, tenant: &Tenant, activity: &Activity) -> Result<()> {
let invoice_item = match activity.activity_type.as_str() {
"create_relay" => {
self.make_prorated_item(tenant, activity, 1, "New relay created")
@@ -123,11 +123,9 @@ impl Billing {
};
match invoice_item {
Some(ref item) => command::insert_invoice_item_for_activity(&item, &activity.id).await?,
None => command::mark_activity_billed(&activity.id).await?,
Some(ref item) => command::insert_invoice_item_for_activity(&item, &activity.id).await,
None => command::mark_activity_billed(&activity.id).await,
}
Ok(invoice_item)
}
/// A prorated charge (or credit, with `sign` = -1) for the relay's current
@@ -141,10 +139,10 @@ impl Billing {
description: &str,
) -> Result<Option<InvoiceItem>> {
let Some(relay) = query::get_relay(&activity.resource_id).await? else {
return anyhow!("activity resource was not a valid relay");
return Err(anyhow!("activity resource was not a valid relay"));
};
let Some(plan) = query::get_plan(&relay.plan) else {
return anyhow!("activity plan was not a valid plan");
let Some(plan) = query::get_plan(&relay.plan_id) else {
return Err(anyhow!("activity plan was not a valid plan"));
};
if plan.amount <= 0 {
return Ok(None);
@@ -158,9 +156,9 @@ impl Billing {
id: uuid::Uuid::new_v4().to_string(),
invoice_id: None,
activity_id: Some(activity.id.clone()),
tenant_pubkey: activity.tenant.clone(),
tenant_pubkey: activity.tenant_pubkey.clone(),
relay_id: activity.resource_id.clone(),
plan: plan.id,
plan_id: plan.id,
amount,
description: description.to_string(),
created_at: activity.created_at,
@@ -178,21 +176,21 @@ impl Billing {
activity: &Activity,
) -> Result<Option<InvoiceItem>> {
let Some(new_plan_id) = activity.plan_id.as_deref() else {
return anyhow!("activity plan was not a valid plan");
return Err(anyhow!("activity plan was not a valid plan"));
};
let Some(old_plan_id) =
query::get_relay_plan_before(&activity.resource_id, activity.created_at).await?
else {
return anyhow!("no previous plan found for relay update activity");
return Err(anyhow!("no previous plan found for relay update activity"));
};
if old_plan_id == new_plan_id {
return Ok(None);
}
let Some(new_plan) = query::get_plan(new_plan_id) else {
return anyhow!("new plan is an invalid plan");
return Err(anyhow!("new plan is an invalid plan"));
};
let Some(old_plan) = query::get_plan(old_plan_id) else {
return anyhow!("old plan is an invalid plan");
let Some(old_plan) = query::get_plan(&old_plan_id) else {
return Err(anyhow!("old plan is an invalid plan"));
};
let period = BillingPeriod::at(tenant, activity.created_at)
@@ -208,9 +206,9 @@ impl Billing {
id: uuid::Uuid::new_v4().to_string(),
invoice_id: None,
activity_id: Some(activity.id.clone()),
tenant_pubkey: activity.tenant.clone(),
tenant_pubkey: activity.tenant_pubkey.clone(),
relay_id: activity.resource_id.clone(),
plan: new_plan.id,
plan_id: new_plan.id,
amount,
description,
created_at: activity.created_at,
@@ -232,7 +230,7 @@ impl Billing {
if !state.active {
continue;
}
let Some(plan) = state.plan.and_then(|id| query::get_plan(&id)) else {
let Some(plan) = state.plan_id.and_then(|id| query::get_plan(&id)) else {
continue;
};
if plan.amount <= 0 {
@@ -244,7 +242,7 @@ impl Billing {
activity_id: None,
tenant_pubkey: tenant.pubkey.clone(),
relay_id,
plan: plan.id,
plan_id: plan.id,
amount: plan.amount,
description: "Subscription renewal".to_string(),
created_at: period.start,
@@ -483,7 +481,7 @@ impl BillingPeriod {
#[derive(Default)]
struct RelayState {
active: bool,
plan: Option<String>,
plan_id: Option<String>,
}
/// Fold relay activities (which must be oldest-first) into each relay's
@@ -498,11 +496,11 @@ fn relay_states(activities: &[Activity]) -> HashMap<String, RelayState> {
match activity.activity_type.as_str() {
"create_relay" => {
state.active = true;
state.plan = activity.plan_id.clone();
state.plan_id = activity.plan_id.clone();
}
"update_relay" => {
if activity.plan_id.is_some() {
state.plan = activity.plan_id.clone();
state.plan_id = activity.plan_id.clone();
}
}
"activate_relay" => state.active = true,
+15 -15
View File
@@ -66,7 +66,7 @@ pub async fn create_relay(relay: &Relay) -> Result<()> {
let activity = with_tx(async |tx| {
sqlx::query(
"INSERT INTO relay (
id, tenant, subdomain, plan, status, synced, sync_error,
id, tenant_pubkey, subdomain, plan_id, status, synced, sync_error,
info_name, info_icon, info_description,
policy_public_join, policy_strip_signatures,
groups_enabled, management_enabled, blossom_enabled,
@@ -74,9 +74,9 @@ pub async fn create_relay(relay: &Relay) -> Result<()> {
) VALUES (?, ?, ?, ?, 'active', 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
)
.bind(&relay.id)
.bind(&relay.tenant)
.bind(&relay.tenant_pubkey)
.bind(&relay.subdomain)
.bind(&relay.plan)
.bind(&relay.plan_id)
.bind(&relay.sync_error)
.bind(&relay.info_name)
.bind(&relay.info_icon)
@@ -90,7 +90,7 @@ pub async fn create_relay(relay: &Relay) -> Result<()> {
.bind(relay.push_enabled)
.execute(&mut **tx)
.await?;
insert_activity_tx(tx, "create_relay", "relay", &relay.id, Some(&relay.plan)).await
insert_activity_tx(tx, "create_relay", "relay", &relay.id, Some(&relay.plan_id)).await
})
.await?;
publish(activity);
@@ -101,16 +101,16 @@ pub async fn update_relay(relay: &Relay) -> Result<()> {
let activity = with_tx(async |tx| {
sqlx::query(
"UPDATE relay
SET tenant = ?, subdomain = ?, plan = ?, status = ?, sync_error = ?, synced = 0,
SET tenant_pubkey = ?, subdomain = ?, plan_id = ?, status = ?, sync_error = ?, synced = 0,
info_name = ?, info_icon = ?, info_description = ?,
policy_public_join = ?, policy_strip_signatures = ?,
groups_enabled = ?, management_enabled = ?, blossom_enabled = ?,
livekit_enabled = ?, push_enabled = ?
WHERE id = ?",
)
.bind(&relay.tenant)
.bind(&relay.tenant_pubkey)
.bind(&relay.subdomain)
.bind(&relay.plan)
.bind(&relay.plan_id)
.bind(&relay.status)
.bind(&relay.sync_error)
.bind(&relay.info_name)
@@ -126,7 +126,7 @@ pub async fn update_relay(relay: &Relay) -> Result<()> {
.bind(&relay.id)
.execute(&mut **tx)
.await?;
insert_activity_tx(tx, "update_relay", "relay", &relay.id, Some(&relay.plan)).await
insert_activity_tx(tx, "update_relay", "relay", &relay.id, Some(&relay.plan_id)).await
})
.await?;
publish(activity);
@@ -376,10 +376,10 @@ async fn insert_activity_tx(
resource_id: &str,
plan_id: Option<&str>,
) -> Result<Activity> {
let tenant = match resource_type {
let tenant_pubkey = match resource_type {
"tenant" => resource_id.to_string(),
"relay" => {
sqlx::query_scalar::<_, String>("SELECT tenant FROM relay WHERE id = ?")
sqlx::query_scalar::<_, String>("SELECT tenant_pubkey FROM relay WHERE id = ?")
.bind(resource_id)
.fetch_one(&mut **tx)
.await?
@@ -391,11 +391,11 @@ async fn insert_activity_tx(
let created_at = chrono::Utc::now().timestamp();
sqlx::query(
"INSERT INTO activity (id, tenant, created_at, activity_type, resource_type, resource_id, plan_id)
"INSERT INTO activity (id, tenant_pubkey, created_at, activity_type, resource_type, resource_id, plan_id)
VALUES (?, ?, ?, ?, ?, ?, ?)",
)
.bind(&id)
.bind(&tenant)
.bind(&tenant_pubkey)
.bind(created_at)
.bind(activity_type)
.bind(resource_type)
@@ -406,7 +406,7 @@ async fn insert_activity_tx(
Ok(Activity {
id,
tenant,
tenant_pubkey,
created_at,
activity_type: activity_type.to_string(),
resource_type: resource_type.to_string(),
@@ -441,7 +441,7 @@ async fn insert_invoice_tx(
async fn insert_invoice_item_tx(tx: &mut Transaction<'_, Sqlite>, item: &InvoiceItem) -> Result<()> {
sqlx::query(
"INSERT INTO invoice_item
(id, invoice_id, activity_id, tenant_pubkey, relay_id, plan, amount, description, created_at)
(id, invoice_id, activity_id, tenant_pubkey, relay_id, plan_id, amount, description, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
)
.bind(&item.id)
@@ -449,7 +449,7 @@ async fn insert_invoice_item_tx(tx: &mut Transaction<'_, Sqlite>, item: &Invoice
.bind(&item.activity_id)
.bind(&item.tenant_pubkey)
.bind(&item.relay_id)
.bind(&item.plan)
.bind(&item.plan_id)
.bind(item.amount)
.bind(&item.description)
.bind(item.created_at)
+1 -1
View File
@@ -180,7 +180,7 @@ async fn try_sync_relay(relay: &Relay) -> Result<()> {
"name": relay.info_name,
"icon": relay.info_icon,
"description": relay.info_description,
"pubkey": relay.tenant,
"pubkey": relay.tenant_pubkey,
},
"policy": {
"public_join": relay.policy_public_join == 1,
+19 -19
View File
@@ -4,20 +4,6 @@ pub const RELAY_STATUS_ACTIVE: &str = "active";
pub const RELAY_STATUS_INACTIVE: &str = "inactive";
pub const RELAY_STATUS_DELINQUENT: &str = "delinquent";
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
pub struct Activity {
pub id: String,
pub tenant: String,
pub created_at: i64,
pub activity_type: String,
pub resource_type: String,
pub resource_id: String,
pub billed_at: Option<i64>,
/// The relay's plan at the time of a `create_relay`/`update_relay` activity;
/// `None` for all other activity types.
pub plan_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Plan {
pub id: String,
@@ -41,12 +27,26 @@ pub struct Tenant {
pub renewed_at: Option<i64>,
}
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
pub struct Activity {
pub id: String,
pub tenant_pubkey: String,
pub created_at: i64,
pub activity_type: String,
pub resource_type: String,
pub resource_id: String,
pub billed_at: Option<i64>,
/// The relay's plan at the time of a `create_relay`/`update_relay` activity;
/// `None` for all other activity types.
pub plan_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
pub struct Relay {
pub id: String,
pub tenant: String,
pub tenant_pubkey: String,
pub subdomain: String,
pub plan: String,
pub plan_id: String,
pub status: String,
pub sync_error: String,
pub info_name: String,
@@ -66,9 +66,9 @@ impl Default for Relay {
fn default() -> Self {
Self {
id: String::new(),
tenant: String::new(),
tenant_pubkey: String::new(),
subdomain: String::new(),
plan: String::new(),
plan_id: String::new(),
status: RELAY_STATUS_ACTIVE.to_string(),
sync_error: String::new(),
info_name: String::new(),
@@ -106,7 +106,7 @@ pub struct InvoiceItem {
pub activity_id: Option<String>,
pub tenant_pubkey: String,
pub relay_id: String,
pub plan: String,
pub plan_id: String,
pub amount: i64,
pub description: String,
pub created_at: i64,
+5 -5
View File
@@ -81,9 +81,9 @@ pub async fn list_relays_pending_sync() -> Result<Vec<Relay>> {
)
}
pub async fn list_relays_for_tenant(tenant_id: &str) -> Result<Vec<Relay>> {
Ok(sqlx::query_as::<_, Relay>(&select_relay("WHERE tenant = ?"))
.bind(tenant_id)
pub async fn list_relays_for_tenant(tenant_pubkey: &str) -> Result<Vec<Relay>> {
Ok(sqlx::query_as::<_, Relay>(&select_relay("WHERE tenant_pubkey = ?"))
.bind(tenant_pubkey)
.fetch_all(pool())
.await?)
}
@@ -176,7 +176,7 @@ pub async fn get_bolt11_for_invoice(invoice_id: &str) -> Result<Option<Bolt11>>
/// Ordered oldest-first so line items and proration apply in event order.
pub async fn list_billable_activity_for_tenant(tenant_pubkey: &str) -> Result<Vec<Activity>> {
Ok(sqlx::query_as::<_, Activity>(&select_activity(
"WHERE tenant = ?
"WHERE tenant_pubkey = ?
AND billed_at IS NULL
AND activity_type IN (
'create_relay', 'update_relay', 'activate_relay', 'deactivate_relay'
@@ -197,7 +197,7 @@ pub async fn list_relay_activity_before(
before: i64,
) -> Result<Vec<Activity>> {
Ok(sqlx::query_as::<_, Activity>(&select_activity(
"WHERE tenant = ?
"WHERE tenant_pubkey = ?
AND resource_type = 'relay'
AND activity_type IN (
'create_relay', 'update_relay', 'activate_relay', 'deactivate_relay'
+17 -17
View File
@@ -34,7 +34,7 @@ pub async fn get_relay(
Path(id): Path<String>,
) -> ApiResult {
let relay = api.get_relay_or_404(&id).await?;
api.require_admin_or_tenant(&auth, &relay.tenant)?;
api.require_admin_or_tenant(&auth, &relay.tenant_pubkey)?;
ok(relay)
}
@@ -44,7 +44,7 @@ pub async fn list_relay_activity(
Path(id): Path<String>,
) -> ApiResult {
let relay = api.get_relay_or_404(&id).await?;
api.require_admin_or_tenant(&auth, &relay.tenant)?;
api.require_admin_or_tenant(&auth, &relay.tenant_pubkey)?;
let activity = query::list_activity_for_resource(&id)
.await
@@ -58,7 +58,7 @@ pub async fn list_relay_members(
Path(id): Path<String>,
) -> ApiResult {
let relay = api.get_relay_or_404(&id).await?;
api.require_admin_or_tenant(&auth, &relay.tenant)?;
api.require_admin_or_tenant(&auth, &relay.tenant_pubkey)?;
let members = fetch_relay_members(&relay).await.map_err(internal)?;
ok(serde_json::json!({ "members": members }))
@@ -66,9 +66,9 @@ pub async fn list_relay_members(
#[derive(Deserialize)]
pub struct CreateRelayRequest {
pub tenant: String,
pub tenant_pubkey: String,
pub subdomain: String,
pub plan: String,
pub plan_id: String,
pub info_name: String,
pub info_icon: String,
pub info_description: String,
@@ -86,7 +86,7 @@ pub async fn create_relay(
AuthedPubkey(auth): AuthedPubkey,
Json(payload): Json<CreateRelayRequest>,
) -> ApiResult {
api.require_admin_or_tenant(&auth, &payload.tenant)?;
api.require_admin_or_tenant(&auth, &payload.tenant_pubkey)?;
let relay_id = format!(
"{}_{}",
@@ -96,9 +96,9 @@ pub async fn create_relay(
let relay = Relay {
id: relay_id.clone(),
tenant: payload.tenant,
tenant_pubkey: payload.tenant_pubkey,
subdomain: payload.subdomain,
plan: payload.plan,
plan_id: payload.plan_id,
info_name: payload.info_name,
info_icon: payload.info_icon,
info_description: payload.info_description,
@@ -124,7 +124,7 @@ pub async fn create_relay(
#[derive(Deserialize)]
pub struct UpdateRelayRequest {
pub subdomain: Option<String>,
pub plan: Option<String>,
pub plan_id: Option<String>,
pub info_name: Option<String>,
pub info_icon: Option<String>,
pub info_description: Option<String>,
@@ -145,16 +145,16 @@ pub async fn update_relay(
) -> ApiResult {
let mut relay = api.get_relay_or_404(&id).await?;
api.require_admin_or_tenant(&auth, &relay.tenant)?;
api.require_admin_or_tenant(&auth, &relay.tenant_pubkey)?;
let current_plan = relay.plan.clone();
let requested_plan = payload.plan.clone();
let current_plan = relay.plan_id.clone();
let requested_plan = payload.plan_id.clone();
if let Some(v) = payload.subdomain {
relay.subdomain = v;
}
if let Some(v) = requested_plan.clone() {
relay.plan = v;
relay.plan_id = v;
}
if let Some(v) = payload.info_name {
relay.info_name = v;
@@ -195,7 +195,7 @@ pub async fn update_relay(
if plan_changed {
let selected_plan =
query::get_plan(&relay.plan).expect("validated plan must exist");
query::get_plan(&relay.plan_id).expect("validated plan must exist");
if let Some(limit) = selected_plan.members {
let current_members = fetch_relay_members(&relay)
.await
@@ -225,7 +225,7 @@ pub async fn deactivate_relay(
Path(id): Path<String>,
) -> ApiResult {
let relay = api.get_relay_or_404(&id).await?;
api.require_admin_or_tenant(&auth, &relay.tenant)?;
api.require_admin_or_tenant(&auth, &relay.tenant_pubkey)?;
if relay.status == RELAY_STATUS_DELINQUENT {
return Err(bad_request("relay-is-delinquent", "relay is delinquent"));
@@ -248,7 +248,7 @@ pub async fn reactivate_relay(
Path(id): Path<String>,
) -> ApiResult {
let relay = api.get_relay_or_404(&id).await?;
api.require_admin_or_tenant(&auth, &relay.tenant)?;
api.require_admin_or_tenant(&auth, &relay.tenant_pubkey)?;
if relay.status == RELAY_STATUS_DELINQUENT {
return Err(bad_request("relay-is-delinquent", "relay is delinquent"));
@@ -287,7 +287,7 @@ fn prepare_relay(mut relay: Relay) -> Result<Relay, ApiError> {
return Err(unprocessable("invalid-subdomain", "subdomain is invalid"));
}
let plan = query::get_plan(&relay.plan)
let plan = query::get_plan(&relay.plan_id)
.ok_or_else(|| unprocessable("invalid-plan", "plan not found"))?;
if (!plan.blossom && relay.blossom_enabled == 1) || (!plan.livekit && relay.livekit_enabled == 1) {