| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
use axum::{ |
| 14 |
Json, |
| 15 |
extract::{Path, State}, |
| 16 |
response::IntoResponse, |
| 17 |
}; |
| 18 |
|
| 19 |
use sqlx::PgPool; |
| 20 |
|
| 21 |
use crate::{ |
| 22 |
auth::AuthUser, |
| 23 |
config::Config, |
| 24 |
db::{self, SyncAppId}, |
| 25 |
error::{AppError, Result}, |
| 26 |
synckit_billing::monthly_price_cents, |
| 27 |
}; |
| 28 |
|
| 29 |
use super::{ |
| 30 |
BillingActivateRequest, BillingPatchRequest, BillingSetupResponse, BillingStatusResponse, |
| 31 |
BillingUpdatedResponse, |
| 32 |
}; |
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
#[tracing::instrument(skip_all, name = "synckit::billing::setup")] |
| 39 |
pub(super) async fn setup( |
| 40 |
State(db): State<PgPool>, |
| 41 |
State(payments): State<crate::Billing>, |
| 42 |
State(config): State<Config>, |
| 43 |
AuthUser(user): AuthUser, |
| 44 |
Path(app_id): Path<SyncAppId>, |
| 45 |
) -> Result<impl IntoResponse> { |
| 46 |
user.check_not_sandbox()?; |
| 47 |
user.check_not_suspended()?; |
| 48 |
|
| 49 |
let app = db::synckit_billing::get_app_with_billing(&db, app_id) |
| 50 |
.await? |
| 51 |
.ok_or(AppError::NotFound)?; |
| 52 |
if app.creator_id != user.id { |
| 53 |
return Err(AppError::Forbidden); |
| 54 |
} |
| 55 |
if app.billing_status != crate::db::SyncBillingStatus::Draft { |
| 56 |
return Err(AppError::Conflict(format!( |
| 57 |
"App is already {}; billing setup is only valid in draft status", |
| 58 |
app.billing_status |
| 59 |
))); |
| 60 |
} |
| 61 |
|
| 62 |
let stripe = payments |
| 63 |
.stripe |
| 64 |
.as_ref() |
| 65 |
.ok_or_else(|| AppError::ServiceUnavailable("Stripe is not configured".to_string()))?; |
| 66 |
|
| 67 |
|
| 68 |
let customer_id = match app.stripe_customer_id.as_deref() { |
| 69 |
Some(id) => id.to_string(), |
| 70 |
None => { |
| 71 |
let developer = db::users::get_user_by_id(&db, user.id) |
| 72 |
.await? |
| 73 |
.ok_or(AppError::Unauthorized)?; |
| 74 |
let id = stripe |
| 75 |
.create_synckit_customer(user.id, app_id, developer.email.as_str(), &app.name) |
| 76 |
.await?; |
| 77 |
db::synckit_billing::set_stripe_customer(&db, app_id, &id).await?; |
| 78 |
id |
| 79 |
} |
| 80 |
}; |
| 81 |
|
| 82 |
let return_url = synckit_return_url(&config, &app); |
| 83 |
let portal_url = stripe |
| 84 |
.create_synckit_billing_portal(&customer_id, &return_url) |
| 85 |
.await?; |
| 86 |
|
| 87 |
Ok(Json(BillingSetupResponse { |
| 88 |
stripe_customer_id: customer_id, |
| 89 |
billing_portal_url: portal_url, |
| 90 |
})) |
| 91 |
} |
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
#[tracing::instrument(skip_all, name = "synckit::billing::activate")] |
| 98 |
pub(super) async fn activate( |
| 99 |
State(db): State<PgPool>, |
| 100 |
State(payments): State<crate::Billing>, |
| 101 |
AuthUser(user): AuthUser, |
| 102 |
Path(app_id): Path<SyncAppId>, |
| 103 |
Json(req): Json<BillingActivateRequest>, |
| 104 |
) -> Result<impl IntoResponse> { |
| 105 |
user.check_not_sandbox()?; |
| 106 |
user.check_not_suspended()?; |
| 107 |
let mode = validate_knobs( |
| 108 |
&req.enforcement_mode, |
| 109 |
req.storage_gb_cap, |
| 110 |
req.key_cap, |
| 111 |
req.gb_per_key, |
| 112 |
)?; |
| 113 |
|
| 114 |
let app = db::synckit_billing::get_app_with_billing(&db, app_id) |
| 115 |
.await? |
| 116 |
.ok_or(AppError::NotFound)?; |
| 117 |
if app.creator_id != user.id { |
| 118 |
return Err(AppError::Forbidden); |
| 119 |
} |
| 120 |
if app.billing_status != crate::db::SyncBillingStatus::Draft { |
| 121 |
return Err(AppError::Conflict(format!( |
| 122 |
"App is already {}; activate is only valid in draft status", |
| 123 |
app.billing_status |
| 124 |
))); |
| 125 |
} |
| 126 |
let customer_id = app.stripe_customer_id.as_deref().ok_or_else(|| { |
| 127 |
AppError::BadRequest( |
| 128 |
"Must POST /billing/setup before activating, no Stripe customer".to_string(), |
| 129 |
) |
| 130 |
})?; |
| 131 |
|
| 132 |
let price_cents = monthly_price_cents(mode, req.storage_gb_cap, req.key_cap, req.gb_per_key); |
| 133 |
|
| 134 |
let stripe = payments |
| 135 |
.stripe |
| 136 |
.as_ref() |
| 137 |
.ok_or_else(|| AppError::ServiceUnavailable("Stripe is not configured".to_string()))?; |
| 138 |
let sub = stripe |
| 139 |
.create_synckit_subscription(customer_id, app_id, &app.name, price_cents) |
| 140 |
.await?; |
| 141 |
|
| 142 |
let period_start = chrono::DateTime::<chrono::Utc>::from_timestamp(sub.current_period_start, 0) |
| 143 |
.ok_or_else(|| AppError::Internal(anyhow::anyhow!("Invalid period_start from Stripe")))?; |
| 144 |
let period_end = chrono::DateTime::<chrono::Utc>::from_timestamp(sub.current_period_end, 0) |
| 145 |
.ok_or_else(|| AppError::Internal(anyhow::anyhow!("Invalid period_end from Stripe")))?; |
| 146 |
|
| 147 |
db::synckit_billing::activate_billing( |
| 148 |
&db, |
| 149 |
app_id, |
| 150 |
mode, |
| 151 |
req.storage_gb_cap.map(|v| v as i32), |
| 152 |
req.key_cap.map(|v| v as i32), |
| 153 |
req.gb_per_key.map(|v| v as i32), |
| 154 |
&sub.subscription_id, |
| 155 |
period_start, |
| 156 |
period_end, |
| 157 |
) |
| 158 |
.await?; |
| 159 |
|
| 160 |
Ok(Json(BillingUpdatedResponse { |
| 161 |
monthly_price_cents: price_cents, |
| 162 |
billing_status: "active".to_string(), |
| 163 |
stripe_subscription_id: Some(sub.subscription_id), |
| 164 |
})) |
| 165 |
} |
| 166 |
|
| 167 |
|
| 168 |
|
| 169 |
|
| 170 |
#[tracing::instrument(skip_all, name = "synckit::billing::patch")] |
| 171 |
pub(super) async fn patch( |
| 172 |
State(db): State<PgPool>, |
| 173 |
State(payments): State<crate::Billing>, |
| 174 |
AuthUser(user): AuthUser, |
| 175 |
Path(app_id): Path<SyncAppId>, |
| 176 |
Json(req): Json<BillingPatchRequest>, |
| 177 |
) -> Result<impl IntoResponse> { |
| 178 |
user.check_not_sandbox()?; |
| 179 |
user.check_not_suspended()?; |
| 180 |
let mode = validate_knobs( |
| 181 |
&req.enforcement_mode, |
| 182 |
req.storage_gb_cap, |
| 183 |
req.key_cap, |
| 184 |
req.gb_per_key, |
| 185 |
)?; |
| 186 |
|
| 187 |
let app = db::synckit_billing::get_app_with_billing(&db, app_id) |
| 188 |
.await? |
| 189 |
.ok_or(AppError::NotFound)?; |
| 190 |
if app.creator_id != user.id { |
| 191 |
return Err(AppError::Forbidden); |
| 192 |
} |
| 193 |
if app.billing_status != crate::db::SyncBillingStatus::Active { |
| 194 |
return Err(AppError::Conflict(format!( |
| 195 |
"App is {}; PATCH is only valid when active", |
| 196 |
app.billing_status |
| 197 |
))); |
| 198 |
} |
| 199 |
let sub_id = app.stripe_subscription_id.as_deref().ok_or_else(|| { |
| 200 |
AppError::Internal(anyhow::anyhow!( |
| 201 |
"Active app has no stripe_subscription_id (data inconsistency)" |
| 202 |
)) |
| 203 |
})?; |
| 204 |
|
| 205 |
let new_price = monthly_price_cents(mode, req.storage_gb_cap, req.key_cap, req.gb_per_key); |
| 206 |
|
| 207 |
let stripe = payments |
| 208 |
.stripe |
| 209 |
.as_ref() |
| 210 |
.ok_or_else(|| AppError::ServiceUnavailable("Stripe is not configured".to_string()))?; |
| 211 |
stripe |
| 212 |
.update_synckit_subscription_price(sub_id, new_price, &app.name) |
| 213 |
.await?; |
| 214 |
|
| 215 |
db::synckit_billing::update_knobs( |
| 216 |
&db, |
| 217 |
app_id, |
| 218 |
mode, |
| 219 |
req.storage_gb_cap.map(|v| v as i32), |
| 220 |
req.key_cap.map(|v| v as i32), |
| 221 |
req.gb_per_key.map(|v| v as i32), |
| 222 |
) |
| 223 |
.await?; |
| 224 |
|
| 225 |
Ok(Json(BillingUpdatedResponse { |
| 226 |
monthly_price_cents: new_price, |
| 227 |
billing_status: "active".to_string(), |
| 228 |
stripe_subscription_id: Some(sub_id.to_string()), |
| 229 |
})) |
| 230 |
} |
| 231 |
|
| 232 |
|
| 233 |
|
| 234 |
|
| 235 |
#[tracing::instrument(skip_all, name = "synckit::billing::cancel")] |
| 236 |
pub(super) async fn cancel( |
| 237 |
State(db): State<PgPool>, |
| 238 |
State(payments): State<crate::Billing>, |
| 239 |
AuthUser(user): AuthUser, |
| 240 |
Path(app_id): Path<SyncAppId>, |
| 241 |
) -> Result<impl IntoResponse> { |
| 242 |
user.check_not_sandbox()?; |
| 243 |
|
| 244 |
let app = db::synckit_billing::get_app_with_billing(&db, app_id) |
| 245 |
.await? |
| 246 |
.ok_or(AppError::NotFound)?; |
| 247 |
if app.creator_id != user.id { |
| 248 |
return Err(AppError::Forbidden); |
| 249 |
} |
| 250 |
if app.billing_status == crate::db::SyncBillingStatus::Canceled { |
| 251 |
return Ok(axum::http::StatusCode::NO_CONTENT); |
| 252 |
} |
| 253 |
|
| 254 |
if let Some(sub_id) = app.stripe_subscription_id.as_deref() { |
| 255 |
let stripe = payments |
| 256 |
.stripe |
| 257 |
.as_ref() |
| 258 |
.ok_or_else(|| AppError::ServiceUnavailable("Stripe is not configured".to_string()))?; |
| 259 |
stripe.cancel_synckit_subscription(sub_id).await?; |
| 260 |
} |
| 261 |
|
| 262 |
db::synckit_billing::apply_billing_update(&db, app_id, Some("canceled"), None).await?; |
| 263 |
|
| 264 |
Ok(axum::http::StatusCode::NO_CONTENT) |
| 265 |
} |
| 266 |
|
| 267 |
|
| 268 |
|
| 269 |
|
| 270 |
#[tracing::instrument(skip_all, name = "synckit::billing::get")] |
| 271 |
pub(super) async fn get( |
| 272 |
State(db): State<PgPool>, |
| 273 |
AuthUser(user): AuthUser, |
| 274 |
Path(app_id): Path<SyncAppId>, |
| 275 |
) -> Result<impl IntoResponse> { |
| 276 |
let app = db::synckit_billing::get_app_with_billing(&db, app_id) |
| 277 |
.await? |
| 278 |
.ok_or(AppError::NotFound)?; |
| 279 |
if app.creator_id != user.id { |
| 280 |
return Err(AppError::Forbidden); |
| 281 |
} |
| 282 |
|
| 283 |
let knobs_set = match app.enforcement_mode { |
| 284 |
crate::db::SyncEnforcementMode::Bulk => app.storage_gb_cap.is_some(), |
| 285 |
crate::db::SyncEnforcementMode::PerKey => app.key_cap.is_some() && app.gb_per_key.is_some(), |
| 286 |
}; |
| 287 |
let monthly_price_cents = knobs_set.then(|| { |
| 288 |
monthly_price_cents( |
| 289 |
app.enforcement_mode, |
| 290 |
app.storage_gb_cap.map(|v| v as u32), |
| 291 |
app.key_cap.map(|v| v as u32), |
| 292 |
app.gb_per_key.map(|v| v as u32), |
| 293 |
) |
| 294 |
}); |
| 295 |
|
| 296 |
Ok(Json(BillingStatusResponse { |
| 297 |
app_id, |
| 298 |
billing_status: app.billing_status.to_string(), |
| 299 |
is_internal: app.is_internal, |
| 300 |
enforcement_mode: app.enforcement_mode.to_string(), |
| 301 |
storage_gb_cap: app.storage_gb_cap.map(|v| v as u32), |
| 302 |
key_cap: app.key_cap.map(|v| v as u32), |
| 303 |
gb_per_key: app.gb_per_key.map(|v| v as u32), |
| 304 |
bytes_stored: app.bytes_stored.unwrap_or(0), |
| 305 |
bytes_egress_period: app.bytes_egress_period.unwrap_or(0), |
| 306 |
keys_claimed: app.keys_claimed.unwrap_or(0) as u32, |
| 307 |
last_warning_pct: app.last_warning_pct.unwrap_or(0) as u8, |
| 308 |
current_period_start: app.current_period_start, |
| 309 |
current_period_end: app.current_period_end, |
| 310 |
monthly_price_cents, |
| 311 |
})) |
| 312 |
} |
| 313 |
|
| 314 |
|
| 315 |
|
| 316 |
|
| 317 |
|
| 318 |
|
| 319 |
#[tracing::instrument(skip_all, name = "synckit::billing::portal")] |
| 320 |
pub(super) async fn portal( |
| 321 |
State(db): State<PgPool>, |
| 322 |
State(payments): State<crate::Billing>, |
| 323 |
State(config): State<Config>, |
| 324 |
AuthUser(user): AuthUser, |
| 325 |
Path(app_id): Path<SyncAppId>, |
| 326 |
) -> Result<impl IntoResponse> { |
| 327 |
user.check_not_sandbox()?; |
| 328 |
|
| 329 |
let app = db::synckit_billing::get_app_with_billing(&db, app_id) |
| 330 |
.await? |
| 331 |
.ok_or(AppError::NotFound)?; |
| 332 |
if app.creator_id != user.id { |
| 333 |
return Err(AppError::Forbidden); |
| 334 |
} |
| 335 |
|
| 336 |
let customer_id = app.stripe_customer_id.as_deref().ok_or_else(|| { |
| 337 |
AppError::BadRequest( |
| 338 |
"No Stripe customer for this app yet, POST /billing/setup first".to_string(), |
| 339 |
) |
| 340 |
})?; |
| 341 |
|
| 342 |
let stripe = payments |
| 343 |
.stripe |
| 344 |
.as_ref() |
| 345 |
.ok_or_else(|| AppError::ServiceUnavailable("Stripe is not configured".to_string()))?; |
| 346 |
|
| 347 |
let return_url = synckit_return_url(&config, &app); |
| 348 |
let portal_url = stripe |
| 349 |
.create_synckit_billing_portal(customer_id, &return_url) |
| 350 |
.await?; |
| 351 |
|
| 352 |
Ok(Json( |
| 353 |
serde_json::json!({ "billing_portal_url": portal_url }), |
| 354 |
)) |
| 355 |
} |
| 356 |
|
| 357 |
|
| 358 |
|
| 359 |
|
| 360 |
|
| 361 |
|
| 362 |
|
| 363 |
|
| 364 |
|
| 365 |
|
| 366 |
|
| 367 |
fn synckit_return_url(config: &Config, app: &crate::db::DbSyncAppBilling) -> String { |
| 368 |
match app.project_slug.as_deref() { |
| 369 |
Some(slug) => format!("{}/dashboard/project/{}?tab=synckit", config.host_url, slug), |
| 370 |
None => format!("{}/dashboard?tab=settings", config.host_url), |
| 371 |
} |
| 372 |
} |
| 373 |
|
| 374 |
|
| 375 |
|
| 376 |
|
| 377 |
|
| 378 |
fn validate_knobs( |
| 379 |
enforcement_mode: &str, |
| 380 |
storage_gb_cap: Option<u32>, |
| 381 |
key_cap: Option<u32>, |
| 382 |
gb_per_key: Option<u32>, |
| 383 |
) -> Result<crate::db::SyncEnforcementMode> { |
| 384 |
use crate::db::SyncEnforcementMode; |
| 385 |
|
| 386 |
|
| 387 |
|
| 388 |
let max = crate::synckit_billing::MAX_STORAGE_GB; |
| 389 |
match enforcement_mode { |
| 390 |
"bulk" => { |
| 391 |
match storage_gb_cap { |
| 392 |
Some(v) if v > 0 && i64::from(v) <= max => {} |
| 393 |
_ => { |
| 394 |
return Err(AppError::BadRequest(format!( |
| 395 |
"storage_gb_cap must be between 1 and {max} GB for enforcement_mode = bulk" |
| 396 |
))); |
| 397 |
} |
| 398 |
} |
| 399 |
if key_cap.is_some() || gb_per_key.is_some() { |
| 400 |
return Err(AppError::BadRequest( |
| 401 |
"key_cap and gb_per_key must be omitted when enforcement_mode = bulk" |
| 402 |
.to_string(), |
| 403 |
)); |
| 404 |
} |
| 405 |
Ok(SyncEnforcementMode::Bulk) |
| 406 |
} |
| 407 |
"per_key" => { |
| 408 |
let k = match key_cap { |
| 409 |
Some(v) if v > 0 => v, |
| 410 |
_ => { |
| 411 |
return Err(AppError::BadRequest( |
| 412 |
"key_cap (> 0) is required when enforcement_mode = per_key".to_string(), |
| 413 |
)); |
| 414 |
} |
| 415 |
}; |
| 416 |
let g = match gb_per_key { |
| 417 |
Some(v) if v > 0 => v, |
| 418 |
_ => { |
| 419 |
return Err(AppError::BadRequest( |
| 420 |
"gb_per_key (> 0) is required when enforcement_mode = per_key".to_string(), |
| 421 |
)); |
| 422 |
} |
| 423 |
}; |
| 424 |
|
| 425 |
if u64::from(k) * u64::from(g) > max as u64 { |
| 426 |
return Err(AppError::BadRequest(format!( |
| 427 |
"key_cap × gb_per_key must not exceed {max} GB total" |
| 428 |
))); |
| 429 |
} |
| 430 |
if storage_gb_cap.is_some() { |
| 431 |
return Err(AppError::BadRequest( |
| 432 |
"storage_gb_cap must be omitted when enforcement_mode = per_key".to_string(), |
| 433 |
)); |
| 434 |
} |
| 435 |
Ok(SyncEnforcementMode::PerKey) |
| 436 |
} |
| 437 |
other => Err(AppError::BadRequest(format!( |
| 438 |
"enforcement_mode must be 'bulk' or 'per_key', got {other:?}" |
| 439 |
))), |
| 440 |
} |
| 441 |
} |
| 442 |
|
| 443 |
#[cfg(test)] |
| 444 |
mod tests { |
| 445 |
use super::validate_knobs; |
| 446 |
use crate::synckit_billing::MAX_STORAGE_GB; |
| 447 |
|
| 448 |
#[test] |
| 449 |
fn bulk_cap_is_bounded() { |
| 450 |
assert!(validate_knobs("bulk", Some(100), None, None).is_ok()); |
| 451 |
assert!(validate_knobs("bulk", Some(MAX_STORAGE_GB as u32), None, None).is_ok()); |
| 452 |
assert!(validate_knobs("bulk", Some(0), None, None).is_err()); |
| 453 |
|
| 454 |
assert!(validate_knobs("bulk", Some(MAX_STORAGE_GB as u32 + 1), None, None).is_err()); |
| 455 |
assert!(validate_knobs("bulk", Some(u32::MAX), None, None).is_err()); |
| 456 |
} |
| 457 |
|
| 458 |
#[test] |
| 459 |
fn per_key_product_is_bounded() { |
| 460 |
assert!(validate_knobs("per_key", None, Some(100), Some(1)).is_ok()); |
| 461 |
|
| 462 |
assert!(validate_knobs("per_key", None, Some(MAX_STORAGE_GB as u32), Some(1)).is_ok()); |
| 463 |
|
| 464 |
assert!(validate_knobs("per_key", None, Some(MAX_STORAGE_GB as u32), Some(2)).is_err()); |
| 465 |
assert!(validate_knobs("per_key", None, Some(u32::MAX), Some(u32::MAX)).is_err()); |
| 466 |
assert!(validate_knobs("per_key", None, Some(0), Some(1)).is_err()); |
| 467 |
} |
| 468 |
} |
| 469 |
|