anyllm_proxy 0.9.6

HTTP proxy translating Anthropic Messages API to OpenAI Chat Completions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
// Route handlers for the routes + route_providers CRUD API.
pub use crate::admin::db::{ReorderOutcome, RoutePatch, RouteProviderRow, RouteRow};

use crate::admin::state::SharedState;
use axum::{
    extract::{ConnectInfo, Path, State},
    http::StatusCode,
    response::IntoResponse,
    Json,
};
use serde::Deserialize;
use std::net::SocketAddr;

// ── Response types ────────────────────────────────────────────────────────────

#[derive(serde::Serialize)]
struct RouteResponse {
    id: String,
    name: String,
    description: Option<String>,
    strategy: String,
    rpm: Option<u32>,
    tpm: Option<u64>,
    budget_usd: Option<f64>,
    provider_count: usize,
    created_at: String,
    updated_at: String,
}

#[derive(serde::Serialize)]
struct RouteProviderResponse {
    id: String,
    route_id: String,
    backend_id: String,
    backend_name: String,
    provider_id: String,
    models: Vec<String>,
    priority: i32,
    enabled: bool,
}

// ── Request types ─────────────────────────────────────────────────────────────

#[derive(Deserialize)]
pub struct CreateRouteRequest {
    pub name: String,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default = "default_strategy")]
    pub strategy: String,
    pub rpm: Option<u32>,
    pub tpm: Option<u64>,
    pub budget_usd: Option<f64>,
}

fn default_strategy() -> String {
    "failover".into()
}

#[derive(Deserialize)]
pub struct AddRouteProviderRequest {
    pub backend_id: String,
    #[serde(default = "default_models")]
    pub models: Vec<String>,
    #[serde(default)]
    pub priority: i32,
    #[serde(default = "default_true")]
    pub enabled: bool,
}

fn default_models() -> Vec<String> {
    vec!["*".into()]
}

fn default_true() -> bool {
    true
}

#[derive(Deserialize)]
pub struct UpdateRouteProviderRequest {
    pub models: Option<Vec<String>>,
    pub priority: Option<i32>,
    pub enabled: Option<bool>,
}

#[derive(Deserialize)]
pub struct ReorderRouteProvidersRequest {
    pub provider_ids: Vec<String>,
}

// ── Helpers ───────────────────────────────────────────────────────────────────

fn route_to_response(route: &RouteRow, provider_count: usize) -> RouteResponse {
    RouteResponse {
        id: route.id.clone(),
        name: route.name.clone(),
        description: route.description.clone(),
        strategy: route.strategy.clone(),
        rpm: route.rpm,
        tpm: route.tpm,
        budget_usd: route.budget_usd,
        provider_count,
        created_at: route.created_at.clone(),
        updated_at: route.updated_at.clone(),
    }
}

fn db_error_status(e: &rusqlite::Error) -> StatusCode {
    if let rusqlite::Error::SqliteFailure(ref err, _) = e {
        if err.code == rusqlite::ErrorCode::ConstraintViolation {
            return StatusCode::CONFLICT;
        }
    }
    StatusCode::INTERNAL_SERVER_ERROR
}

fn ok_json<T: serde::Serialize>(val: T) -> axum::response::Response {
    (StatusCode::OK, Json(serde_json::to_value(val).unwrap())).into_response()
}

fn err_json(status: StatusCode, msg: impl Into<String>) -> axum::response::Response {
    (status, Json(serde_json::json!({ "error": msg.into() }))).into_response()
}

fn build_provider_responses(
    providers: &[RouteProviderRow],
    backends: &[crate::admin::db::ManagedBackendRow],
) -> Vec<RouteProviderResponse> {
    let backend_map: std::collections::HashMap<&str, &crate::admin::db::ManagedBackendRow> =
        backends.iter().map(|b| (b.id.as_str(), b)).collect();
    providers
        .iter()
        .map(|p| {
            let backend = backend_map.get(p.backend_id.as_str());
            RouteProviderResponse {
                id: p.id.clone(),
                route_id: p.route_id.clone(),
                backend_id: p.backend_id.clone(),
                backend_name: backend.map(|b| b.name.clone()).unwrap_or_default(),
                provider_id: backend.map(|b| b.provider_id.clone()).unwrap_or_default(),
                models: p.models.clone(),
                priority: p.priority,
                enabled: p.enabled,
            }
        })
        .collect()
}

fn audit(
    shared: &SharedState,
    source_ip: Option<String>,
    action: &str,
    target_type: &str,
    target_id: String,
    detail: Option<String>,
) {
    super::emit_audit(
        shared,
        crate::admin::db::AuditEntry {
            id: None,
            timestamp: None,
            action: action.into(),
            target_type: target_type.into(),
            target_id: Some(target_id),
            detail,
            source_ip,
        },
    );
}

// ── Route CRUD ────────────────────────────────────────────────────────────────

pub(super) async fn list_routes(State(shared): State<SharedState>) -> axum::response::Response {
    let result = crate::admin::state::with_db(&shared.db, |conn| {
        let routes = crate::admin::db::list_routes(conn)?;
        let mut resp = Vec::with_capacity(routes.len());
        for r in &routes {
            let count = crate::admin::db::count_route_providers(conn, &r.id).unwrap_or(0);
            resp.push(route_to_response(r, count));
        }
        Ok::<_, rusqlite::Error>(resp)
    })
    .await;

    match result {
        Some(Ok(resp)) => ok_json(serde_json::json!({ "routes": resp })),
        _ => err_json(StatusCode::INTERNAL_SERVER_ERROR, "Failed to list routes"),
    }
}

pub(super) async fn create_route(
    ConnectInfo(addr): ConnectInfo<SocketAddr>,
    State(shared): State<SharedState>,
    Json(body): Json<CreateRouteRequest>,
) -> axum::response::Response {
    if body.name.trim().is_empty() {
        return err_json(StatusCode::BAD_REQUEST, "name is required");
    }

    let now = crate::admin::db::now_iso8601();
    let row = RouteRow {
        id: uuid::Uuid::new_v4().to_string(),
        name: body.name.trim().to_string(),
        description: body.description,
        strategy: body.strategy,
        rpm: body.rpm,
        tpm: body.tpm,
        budget_usd: body.budget_usd,
        created_at: now.clone(),
        updated_at: now,
    };

    let row_clone = row.clone();
    let result = crate::admin::state::with_db(&shared.db, move |conn| {
        crate::admin::db::insert_route(conn, &row_clone)
    })
    .await;

    match result {
        Some(Ok(())) => {
            audit(
                &shared,
                Some(addr.ip().to_string()),
                "route_created",
                "route",
                row.name.clone(),
                None,
            );
            (
                StatusCode::CREATED,
                Json(serde_json::to_value(route_to_response(&row, 0)).unwrap()),
            )
                .into_response()
        }
        Some(Err(e)) => err_json(db_error_status(&e), e.to_string()),
        None => err_json(StatusCode::INTERNAL_SERVER_ERROR, "Failed to create route"),
    }
}

pub(super) async fn update_route(
    ConnectInfo(addr): ConnectInfo<SocketAddr>,
    State(shared): State<SharedState>,
    Path(id): Path<String>,
    Json(body): Json<RoutePatch>,
) -> axum::response::Response {
    let id_clone = id.clone();
    let result = crate::admin::state::with_db(&shared.db, move |conn| {
        let updated = crate::admin::db::update_route(conn, &id_clone, &body)?;
        if !updated {
            return Ok::<_, rusqlite::Error>((false, None, 0));
        }
        let route = crate::admin::db::get_route(conn, &id_clone).ok().flatten();
        let count = crate::admin::db::count_route_providers(conn, &id_clone).unwrap_or(0);
        Ok((true, route, count))
    })
    .await;

    match result {
        Some(Ok((true, Some(r), count))) => {
            audit(
                &shared,
                Some(addr.ip().to_string()),
                "route_updated",
                "route",
                id,
                None,
            );
            ok_json(route_to_response(&r, count))
        }
        Some(Ok((true, None, _))) => err_json(
            StatusCode::INTERNAL_SERVER_ERROR,
            "route not found after update",
        ),
        Some(Ok((false, _, _))) => err_json(StatusCode::NOT_FOUND, "route not found"),
        Some(Err(e)) => err_json(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
        None => err_json(StatusCode::INTERNAL_SERVER_ERROR, "Failed to update route"),
    }
}

pub(super) async fn delete_route(
    ConnectInfo(addr): ConnectInfo<SocketAddr>,
    State(shared): State<SharedState>,
    Path(id): Path<String>,
) -> axum::response::Response {
    let id_clone = id.clone();
    let result = crate::admin::state::with_db(&shared.db, move |conn| {
        crate::admin::db::delete_route(conn, &id_clone)
    })
    .await;

    match result {
        Some(Ok(true)) => {
            audit(
                &shared,
                Some(addr.ip().to_string()),
                "route_deleted",
                "route",
                id,
                None,
            );
            ok_json(serde_json::json!({ "ok": true }))
        }
        Some(Ok(false)) => err_json(StatusCode::NOT_FOUND, "route not found"),
        Some(Err(e)) => err_json(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
        None => err_json(StatusCode::INTERNAL_SERVER_ERROR, "Failed to delete route"),
    }
}

// ── Route Providers CRUD ──────────────────────────────────────────────────────

pub(super) async fn list_route_providers_handler(
    State(shared): State<SharedState>,
    Path(route_id): Path<String>,
) -> axum::response::Response {
    let result = crate::admin::state::with_db(&shared.db, move |conn| {
        if crate::admin::db::get_route(conn, &route_id)
            .ok()
            .flatten()
            .is_none()
        {
            return Ok::<_, rusqlite::Error>(None);
        }
        let providers = crate::admin::db::list_route_providers(conn, &route_id)?;
        let backends = crate::admin::db::list_managed_backends(conn).unwrap_or_default();
        Ok(Some(build_provider_responses(&providers, &backends)))
    })
    .await;

    match result {
        Some(Ok(Some(resp))) => ok_json(serde_json::json!({ "providers": resp })),
        Some(Ok(None)) => err_json(StatusCode::NOT_FOUND, "route not found"),
        _ => err_json(
            StatusCode::INTERNAL_SERVER_ERROR,
            "Failed to list route providers",
        ),
    }
}

pub(super) async fn add_route_provider_handler(
    ConnectInfo(addr): ConnectInfo<SocketAddr>,
    State(shared): State<SharedState>,
    Path(route_id): Path<String>,
    Json(body): Json<AddRouteProviderRequest>,
) -> axum::response::Response {
    let route_id_clone = route_id.clone();
    let backend_id = body.backend_id.clone();
    let models = body.models.clone();
    let priority = body.priority;
    let enabled = body.enabled;

    let backend_id_for_db = backend_id.clone();
    let backend_id_check = backend_id.clone();
    let result = crate::admin::state::with_db(&shared.db, move |conn| {
        if crate::admin::db::get_route(conn, &route_id_clone)
            .ok()
            .flatten()
            .is_none()
        {
            return Ok::<_, rusqlite::Error>(Err::<(), String>("route not found".into()));
        }
        if !crate::admin::db::managed_backend_exists(conn, &backend_id_check)? {
            return Ok(Err::<(), String>("backend not found".into()));
        }
        crate::admin::db::add_route_provider(
            conn,
            &route_id_clone,
            &backend_id_for_db,
            &models,
            priority,
            enabled,
        )?;
        Ok(Ok::<(), String>(()))
    })
    .await;

    match result {
        Some(Ok(Ok(()))) => {
            audit(
                &shared,
                Some(addr.ip().to_string()),
                "route_provider_added",
                "route_provider",
                route_id,
                Some(format!("backend_id={}", backend_id)),
            );
            (StatusCode::CREATED, Json(serde_json::json!({ "ok": true }))).into_response()
        }
        Some(Ok(Err(msg))) => err_json(
            if msg == "route not found" {
                StatusCode::NOT_FOUND
            } else {
                StatusCode::BAD_REQUEST
            },
            msg,
        ),
        Some(Err(e)) => err_json(db_error_status(&e), e.to_string()),
        None => err_json(
            StatusCode::INTERNAL_SERVER_ERROR,
            "Failed to add route provider",
        ),
    }
}

pub(super) async fn update_route_provider_handler(
    ConnectInfo(addr): ConnectInfo<SocketAddr>,
    State(shared): State<SharedState>,
    Path((route_id, provider_id)): Path<(String, String)>,
    Json(body): Json<UpdateRouteProviderRequest>,
) -> axum::response::Response {
    let provider_id_clone = provider_id.clone();
    let result = crate::admin::state::with_db(&shared.db, move |conn| {
        crate::admin::db::update_route_provider(
            conn,
            &provider_id_clone,
            body.models.as_deref(),
            body.priority,
            body.enabled,
        )
    })
    .await;

    match result {
        Some(Ok(true)) => {
            audit(
                &shared,
                Some(addr.ip().to_string()),
                "route_provider_updated",
                "route_provider",
                provider_id,
                Some(format!("route_id={}", route_id)),
            );
            ok_json(serde_json::json!({ "ok": true }))
        }
        Some(Ok(false)) => err_json(StatusCode::NOT_FOUND, "route provider not found"),
        Some(Err(e)) => err_json(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
        None => err_json(
            StatusCode::INTERNAL_SERVER_ERROR,
            "Failed to update route provider",
        ),
    }
}

pub(super) async fn reorder_route_providers_handler(
    ConnectInfo(addr): ConnectInfo<SocketAddr>,
    State(shared): State<SharedState>,
    Path(route_id): Path<String>,
    Json(body): Json<ReorderRouteProvidersRequest>,
) -> axum::response::Response {
    let route_id_clone = route_id.clone();
    let ordered = body.provider_ids.clone();
    let result = crate::admin::state::with_db(&shared.db, move |conn| {
        if crate::admin::db::get_route(conn, &route_id_clone)
            .ok()
            .flatten()
            .is_none()
        {
            return Ok::<_, rusqlite::Error>(None);
        }
        let outcome = crate::admin::db::reorder_route_providers(conn, &route_id_clone, &ordered)?;
        match outcome {
            ReorderOutcome::Mismatch => Ok(Some(Err::<_, ()>(()))),
            ReorderOutcome::Ok(rows) => {
                let backends = crate::admin::db::list_managed_backends(conn).unwrap_or_default();
                Ok(Some(Ok(build_provider_responses(&rows, &backends))))
            }
        }
    })
    .await;

    match result {
        Some(Ok(Some(Ok(providers)))) => {
            audit(
                &shared,
                Some(addr.ip().to_string()),
                "route_providers_reordered",
                "route",
                route_id,
                Some(format!("count={}", providers.len())),
            );
            ok_json(serde_json::json!({ "providers": providers }))
        }
        Some(Ok(Some(Err(())))) => err_json(
            StatusCode::BAD_REQUEST,
            "provider_ids must match the route's current provider set exactly",
        ),
        Some(Ok(None)) => err_json(StatusCode::NOT_FOUND, "route not found"),
        Some(Err(e)) => err_json(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
        None => err_json(
            StatusCode::INTERNAL_SERVER_ERROR,
            "Failed to reorder route providers",
        ),
    }
}

pub(super) async fn remove_route_provider_handler(
    ConnectInfo(addr): ConnectInfo<SocketAddr>,
    State(shared): State<SharedState>,
    Path((_route_id, provider_id)): Path<(String, String)>,
) -> axum::response::Response {
    let provider_id_clone = provider_id.clone();
    let result = crate::admin::state::with_db(&shared.db, move |conn| {
        crate::admin::db::remove_route_provider(conn, &provider_id_clone)
    })
    .await;

    match result {
        Some(Ok(true)) => {
            audit(
                &shared,
                Some(addr.ip().to_string()),
                "route_provider_removed",
                "route_provider",
                provider_id,
                None,
            );
            ok_json(serde_json::json!({ "ok": true }))
        }
        Some(Ok(false)) => err_json(StatusCode::NOT_FOUND, "route provider not found"),
        Some(Err(e)) => err_json(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
        None => err_json(
            StatusCode::INTERNAL_SERVER_ERROR,
            "Failed to remove route provider",
        ),
    }
}