1use std::collections::HashMap;
2use std::net::SocketAddr;
3use std::sync::Arc;
4
5use anyhow::{Context, Result};
6use axum::{
7 extract::{Path, State},
8 http::StatusCode,
9 response::{IntoResponse, Response},
10 routing::{get, post},
11 Json, Router,
12};
13use chrono::{DateTime, Utc};
14use parking_lot::RwLock;
15use serde::{Deserialize, Serialize};
16use tokio::net::TcpListener;
17use tower_http::trace::TraceLayer;
18use tracing::{info, instrument};
19use uuid::Uuid;
20
21const VALID_ROLES: &[&str] = &["admin", "viewer", "billing"];
22
23#[derive(Debug, Clone)]
24pub struct ControlPlaneConfig {
25 pub addr: SocketAddr,
26}
27
28#[derive(Clone, Debug, Serialize, Deserialize)]
29pub struct Tenant {
30 pub id: Uuid,
31 pub name: String,
32 #[serde(skip_serializing_if = "Option::is_none")]
33 pub contact: Option<String>,
34 pub status: &'static str,
35}
36
37#[derive(Clone, Debug, Serialize, Deserialize)]
38pub struct Project {
39 pub id: Uuid,
40 pub tenant_id: Uuid,
41 pub name: String,
42}
43
44#[derive(Clone, Debug, Serialize, Deserialize)]
45pub struct ApiKey {
46 pub id: Uuid,
47 pub project_id: Uuid,
48 pub key: String,
49}
50
51#[derive(Clone, Debug, Serialize, Deserialize)]
52pub struct TenantQuota {
53 pub tenant_id: Uuid,
54 #[serde(default)]
55 pub daily_token_limit: Option<i64>,
56 #[serde(default)]
57 pub daily_cost_limit: Option<f64>,
58}
59
60#[derive(Clone, Debug, Serialize, Deserialize)]
61pub struct BillingRecord {
62 pub tenant_id: Uuid,
63 pub recorded_at: DateTime<Utc>,
64 pub tokens: i64,
65 pub cost: f64,
66}
67
68#[derive(Default)]
69struct ControlPlaneState {
70 tenants: RwLock<HashMap<Uuid, Tenant>>,
71 projects: RwLock<HashMap<Uuid, Project>>,
72 keys: RwLock<HashMap<Uuid, ApiKey>>,
73 quotas: RwLock<HashMap<Uuid, TenantQuota>>,
74 tenant_roles: RwLock<HashMap<Uuid, HashMap<String, String>>>,
75 billing: RwLock<Vec<BillingRecord>>,
76}
77
78#[derive(Debug, Deserialize)]
79struct TenantSpec {
80 name: String,
81 #[serde(default)]
82 contact: Option<String>,
83}
84
85#[derive(Debug, Deserialize)]
86struct ProjectSpec {
87 name: String,
88}
89
90#[derive(Debug, Deserialize)]
91struct QuotaSpec {
92 #[serde(default)]
93 daily_token_limit: Option<i64>,
94 #[serde(default)]
95 daily_cost_limit: Option<f64>,
96}
97
98#[derive(Debug, Deserialize)]
99struct RoleSpec {
100 email: String,
101 role: String,
102}
103
104#[derive(Debug, Deserialize)]
105struct UsageSpec {
106 #[serde(default)]
107 tokens: Option<i64>,
108 #[serde(default)]
109 cost: Option<f64>,
110 #[serde(default)]
111 recorded_at: Option<DateTime<Utc>>,
112}
113
114#[derive(Debug, Serialize)]
115struct CreateTenantResponse {
116 tenant: Tenant,
117}
118
119#[derive(Debug, Serialize)]
120struct CreateProjectResponse {
121 project: Project,
122}
123
124#[derive(Debug, Serialize)]
125struct CreateKeyResponse {
126 key: ApiKey,
127}
128
129#[derive(Debug, Serialize)]
130struct ErrorResponse {
131 error: String,
132}
133
134#[derive(Debug, Serialize)]
135struct QuotaResponse {
136 quota: TenantQuota,
137}
138
139#[derive(Debug, Serialize, Deserialize)]
140struct RolesResponse {
141 roles: Vec<RoleBinding>,
142}
143
144#[derive(Debug, Serialize, Deserialize, Clone)]
145struct RoleBinding {
146 email: String,
147 role: String,
148}
149
150#[derive(Debug, Serialize, Deserialize)]
151struct UsageResponse {
152 records: Vec<BillingRecord>,
153}
154
155pub async fn serve(config: ControlPlaneConfig) -> Result<()> {
156 let listener = TcpListener::bind(config.addr)
157 .await
158 .with_context(|| format!("failed to bind control plane on {}", config.addr))?;
159 info!(addr = %config.addr, "starting managed control plane");
160
161 let state = Arc::new(ControlPlaneState::default());
162 let app = Router::new()
163 .route("/healthz", get(healthz))
164 .route("/v1/tenants", post(create_tenant).get(list_tenants))
165 .route("/v1/tenants/:tenant_id/projects", post(create_project))
166 .route(
167 "/v1/tenants/:tenant_id/quotas",
168 post(upsert_quota).get(get_quota),
169 )
170 .route(
171 "/v1/tenants/:tenant_id/roles",
172 post(assign_role).get(list_roles),
173 )
174 .route(
175 "/v1/tenants/:tenant_id/usage",
176 post(record_usage).get(list_usage),
177 )
178 .route(
179 "/v1/projects/:project_id/keys",
180 post(issue_key).get(list_keys),
181 )
182 .with_state(state)
183 .layer(TraceLayer::new_for_http());
184
185 axum::serve(listener, app)
186 .await
187 .context("control plane server exited unexpectedly")
188}
189
190async fn healthz() -> &'static str {
191 "ok"
192}
193
194#[instrument(skip(state, payload))]
195async fn create_tenant(
196 State(state): State<Arc<ControlPlaneState>>,
197 Json(payload): Json<TenantSpec>,
198) -> Response {
199 if payload.name.trim().is_empty() {
200 return (
201 StatusCode::BAD_REQUEST,
202 Json(ErrorResponse {
203 error: "name is required".into(),
204 }),
205 )
206 .into_response();
207 }
208
209 let tenant = Tenant {
210 id: Uuid::new_v4(),
211 name: payload.name.clone(),
212 contact: payload.contact.clone(),
213 status: "provisioning",
214 };
215
216 state.tenants.write().insert(tenant.id, tenant.clone());
217 info!(tenant_id = %tenant.id, "provisioned tenant");
218 (StatusCode::CREATED, Json(CreateTenantResponse { tenant })).into_response()
219}
220
221async fn list_tenants(State(state): State<Arc<ControlPlaneState>>) -> Json<Vec<Tenant>> {
222 let tenants = state.tenants.read();
223 Json(tenants.values().cloned().collect())
224}
225
226#[instrument(skip(state, payload))]
227async fn create_project(
228 State(state): State<Arc<ControlPlaneState>>,
229 Path(tenant_id): Path<Uuid>,
230 Json(payload): Json<ProjectSpec>,
231) -> Response {
232 if payload.name.trim().is_empty() {
233 return (
234 StatusCode::BAD_REQUEST,
235 Json(ErrorResponse {
236 error: "name is required".into(),
237 }),
238 )
239 .into_response();
240 }
241
242 let tenants = state.tenants.read();
243 if !tenants.contains_key(&tenant_id) {
244 return (
245 StatusCode::NOT_FOUND,
246 Json(ErrorResponse {
247 error: "tenant not found".into(),
248 }),
249 )
250 .into_response();
251 }
252 drop(tenants);
253
254 let project = Project {
255 id: Uuid::new_v4(),
256 tenant_id,
257 name: payload.name.clone(),
258 };
259 state.projects.write().insert(project.id, project.clone());
260 info!(tenant_id = %tenant_id, project_id = %project.id, "created project");
261 (StatusCode::CREATED, Json(CreateProjectResponse { project })).into_response()
262}
263
264#[instrument(skip(state))]
265async fn issue_key(
266 State(state): State<Arc<ControlPlaneState>>,
267 Path(project_id): Path<Uuid>,
268) -> Response {
269 let projects = state.projects.read();
270 if !projects.contains_key(&project_id) {
271 return (
272 StatusCode::NOT_FOUND,
273 Json(ErrorResponse {
274 error: "project not found".into(),
275 }),
276 )
277 .into_response();
278 }
279 drop(projects);
280
281 let api_key = ApiKey {
282 id: Uuid::new_v4(),
283 project_id,
284 key: format!("ffk_{}", Uuid::new_v4().simple()),
285 };
286 state.keys.write().insert(api_key.id, api_key.clone());
287 info!(project_id = %project_id, key_id = %api_key.id, "issued project key");
288 (
289 StatusCode::CREATED,
290 Json(CreateKeyResponse { key: api_key }),
291 )
292 .into_response()
293}
294
295async fn list_keys(
296 State(state): State<Arc<ControlPlaneState>>,
297 Path(project_id): Path<Uuid>,
298) -> Response {
299 let projects = state.projects.read();
300 if !projects.contains_key(&project_id) {
301 return (
302 StatusCode::NOT_FOUND,
303 Json(ErrorResponse {
304 error: "project not found".into(),
305 }),
306 )
307 .into_response();
308 }
309 drop(projects);
310
311 let keys = state
312 .keys
313 .read()
314 .values()
315 .filter(|key| key.project_id == project_id)
316 .cloned()
317 .collect::<Vec<_>>();
318
319 Json(keys).into_response()
320}
321
322#[instrument(skip(state, payload))]
323async fn assign_role(
324 State(state): State<Arc<ControlPlaneState>>,
325 Path(tenant_id): Path<Uuid>,
326 Json(payload): Json<RoleSpec>,
327) -> Response {
328 let tenants = state.tenants.read();
329 if !tenants.contains_key(&tenant_id) {
330 return (
331 StatusCode::NOT_FOUND,
332 Json(ErrorResponse {
333 error: "tenant not found".into(),
334 }),
335 )
336 .into_response();
337 }
338 drop(tenants);
339
340 let role = payload.role.to_ascii_lowercase();
341 if !VALID_ROLES.contains(&role.as_str()) {
342 return (
343 StatusCode::BAD_REQUEST,
344 Json(ErrorResponse {
345 error: format!("unknown role '{}'", payload.role),
346 }),
347 )
348 .into_response();
349 }
350 if payload.email.trim().is_empty() {
351 return (
352 StatusCode::BAD_REQUEST,
353 Json(ErrorResponse {
354 error: "email is required".into(),
355 }),
356 )
357 .into_response();
358 }
359
360 let mut roles = state.tenant_roles.write();
361 roles
362 .entry(tenant_id)
363 .or_default()
364 .insert(payload.email.clone(), role.clone());
365 info!(tenant_id = %tenant_id, email = %payload.email, role = %role, "assigned tenant role");
366 (
367 StatusCode::OK,
368 Json(RolesResponse {
369 roles: roles[&tenant_id]
370 .iter()
371 .map(|(email, role)| RoleBinding {
372 email: email.clone(),
373 role: role.clone(),
374 })
375 .collect(),
376 }),
377 )
378 .into_response()
379}
380
381async fn list_roles(
382 State(state): State<Arc<ControlPlaneState>>,
383 Path(tenant_id): Path<Uuid>,
384) -> Response {
385 let tenants = state.tenants.read();
386 if !tenants.contains_key(&tenant_id) {
387 return (
388 StatusCode::NOT_FOUND,
389 Json(ErrorResponse {
390 error: "tenant not found".into(),
391 }),
392 )
393 .into_response();
394 }
395 drop(tenants);
396
397 let roles = state.tenant_roles.read();
398 let bindings = roles
399 .get(&tenant_id)
400 .map(|entries| {
401 entries
402 .iter()
403 .map(|(email, role)| RoleBinding {
404 email: email.clone(),
405 role: role.clone(),
406 })
407 .collect::<Vec<_>>()
408 })
409 .unwrap_or_default();
410 Json(RolesResponse { roles: bindings }).into_response()
411}
412
413#[instrument(skip(state, payload))]
414async fn record_usage(
415 State(state): State<Arc<ControlPlaneState>>,
416 Path(tenant_id): Path<Uuid>,
417 Json(payload): Json<UsageSpec>,
418) -> Response {
419 let tenants = state.tenants.read();
420 if !tenants.contains_key(&tenant_id) {
421 return (
422 StatusCode::NOT_FOUND,
423 Json(ErrorResponse {
424 error: "tenant not found".into(),
425 }),
426 )
427 .into_response();
428 }
429 drop(tenants);
430
431 let tokens = payload.tokens.unwrap_or_default().max(0);
432 let cost = payload.cost.unwrap_or_default().max(0.0);
433 let record = BillingRecord {
434 tenant_id,
435 recorded_at: payload.recorded_at.unwrap_or_else(Utc::now),
436 tokens,
437 cost,
438 };
439 state.billing.write().push(record.clone());
440 info!(tenant_id = %tenant_id, tokens = tokens, cost = cost, "recorded usage sample");
441 (StatusCode::CREATED, Json(record)).into_response()
442}
443
444async fn list_usage(
445 State(state): State<Arc<ControlPlaneState>>,
446 Path(tenant_id): Path<Uuid>,
447) -> Response {
448 let tenants = state.tenants.read();
449 if !tenants.contains_key(&tenant_id) {
450 return (
451 StatusCode::NOT_FOUND,
452 Json(ErrorResponse {
453 error: "tenant not found".into(),
454 }),
455 )
456 .into_response();
457 }
458 drop(tenants);
459
460 let records = state
461 .billing
462 .read()
463 .iter()
464 .filter(|record| record.tenant_id == tenant_id)
465 .cloned()
466 .collect::<Vec<_>>();
467 Json(UsageResponse { records }).into_response()
468}
469
470#[instrument(skip(state, payload))]
471async fn upsert_quota(
472 State(state): State<Arc<ControlPlaneState>>,
473 Path(tenant_id): Path<Uuid>,
474 Json(payload): Json<QuotaSpec>,
475) -> Response {
476 let tenants = state.tenants.read();
477 if !tenants.contains_key(&tenant_id) {
478 return (
479 StatusCode::NOT_FOUND,
480 Json(ErrorResponse {
481 error: "tenant not found".into(),
482 }),
483 )
484 .into_response();
485 }
486 drop(tenants);
487
488 if payload.daily_token_limit.is_none() && payload.daily_cost_limit.is_none() {
489 state.quotas.write().remove(&tenant_id);
490 info!(tenant_id = %tenant_id, "cleared tenant quota limits");
491 return StatusCode::NO_CONTENT.into_response();
492 }
493
494 let quota = TenantQuota {
495 tenant_id,
496 daily_token_limit: payload.daily_token_limit,
497 daily_cost_limit: payload.daily_cost_limit,
498 };
499 state.quotas.write().insert(tenant_id, quota.clone());
500 info!(tenant_id = %tenant_id, "updated tenant quota limits");
501 (StatusCode::OK, Json(QuotaResponse { quota })).into_response()
502}
503
504async fn get_quota(
505 State(state): State<Arc<ControlPlaneState>>,
506 Path(tenant_id): Path<Uuid>,
507) -> Response {
508 let tenants = state.tenants.read();
509 if !tenants.contains_key(&tenant_id) {
510 return (
511 StatusCode::NOT_FOUND,
512 Json(ErrorResponse {
513 error: "tenant not found".into(),
514 }),
515 )
516 .into_response();
517 }
518 drop(tenants);
519
520 let quotas = state.quotas.read();
521 match quotas.get(&tenant_id) {
522 Some(quota) => (
523 StatusCode::OK,
524 Json(QuotaResponse {
525 quota: quota.clone(),
526 }),
527 )
528 .into_response(),
529 None => (
530 StatusCode::NOT_FOUND,
531 Json(ErrorResponse {
532 error: "quota not configured".into(),
533 }),
534 )
535 .into_response(),
536 }
537}
538
539#[cfg(test)]
540mod tests {
541 use super::*;
542 use axum::body::to_bytes;
543 use axum::extract::State;
544
545 fn seeded_state() -> (Arc<ControlPlaneState>, Uuid) {
546 let state = ControlPlaneState::default();
547 let tenant = Tenant {
548 id: Uuid::new_v4(),
549 name: "Acme".into(),
550 contact: Some("ops@acme.test".into()),
551 status: "active",
552 };
553 let id = tenant.id;
554 state.tenants.write().insert(id, tenant);
555 (Arc::new(state), id)
556 }
557
558 #[tokio::test]
559 async fn assign_role_and_list_roles() {
560 let (state, tenant_id) = seeded_state();
561
562 let response = assign_role(
563 State(state.clone()),
564 Path(tenant_id),
565 Json(RoleSpec {
566 email: "owner@acme.test".into(),
567 role: "admin".into(),
568 }),
569 )
570 .await;
571
572 assert_eq!(response.status(), StatusCode::OK);
573
574 let response = list_roles(State(state.clone()), Path(tenant_id)).await;
575 let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
576 let listed: RolesResponse = serde_json::from_slice(&body).unwrap();
577 assert_eq!(listed.roles.len(), 1);
578 assert_eq!(listed.roles[0].role, "admin");
579 }
580
581 #[tokio::test]
582 async fn assign_role_rejects_unknown_role() {
583 let (state, tenant_id) = seeded_state();
584
585 let response = assign_role(
586 State(state),
587 Path(tenant_id),
588 Json(RoleSpec {
589 email: "owner@acme.test".into(),
590 role: "unknown".into(),
591 }),
592 )
593 .await;
594
595 assert_eq!(response.status(), StatusCode::BAD_REQUEST);
596 }
597
598 #[tokio::test]
599 async fn record_and_list_usage() {
600 let (state, tenant_id) = seeded_state();
601
602 let response = record_usage(
603 State(state.clone()),
604 Path(tenant_id),
605 Json(UsageSpec {
606 tokens: Some(120),
607 cost: Some(0.45),
608 recorded_at: None,
609 }),
610 )
611 .await;
612
613 assert_eq!(response.status(), StatusCode::CREATED);
614
615 let response = list_usage(State(state), Path(tenant_id)).await;
616 let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
617 let listed: UsageResponse = serde_json::from_slice(&body).unwrap();
618 assert_eq!(listed.records.len(), 1);
619 assert_eq!(listed.records[0].tokens, 120);
620 }
621}