bitrouter-api 0.24.1

BitRouter API - reusable warp server components for AI model routing
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
//! Warp filters for the admin route management API.
//!
//! Provides HTTP endpoints for managing routes at runtime without requiring
//! config file rewrites and daemon restarts:
//!
//! - `GET /admin/routes` — list all routes (config-defined + dynamic)
//! - `POST /admin/routes` — create or update a dynamic route
//! - `DELETE /admin/routes/:name` — remove a dynamically-added route

use std::sync::Arc;

use bitrouter_core::routers::admin::{AdminRoutingTable, DynamicRoute, RouteKind};
use serde::Serialize;
use warp::Filter;

/// Mount all admin route management endpoints under `/admin/routes`.
///
/// The caller is responsible for auth gating — this function does not apply
/// any authentication. Compose with an auth filter before mounting:
///
/// ```ignore
/// let admin = auth_gate(management_auth(ctx.clone()))
///     .and(admin::admin_routes_filter(table.clone()));
/// ```
pub fn admin_routes_filter<T>(
    table: Arc<T>,
) -> impl Filter<Extract = (impl warp::Reply,), Error = warp::Rejection> + Clone
where
    T: AdminRoutingTable + Send + Sync + 'static,
{
    list_routes(table.clone())
        .or(create_route(table.clone()))
        .or(delete_route(table))
}

// ── GET /admin/routes ────────────────────────────────────────────────

fn list_routes<T>(
    table: Arc<T>,
) -> impl Filter<Extract = (impl warp::Reply,), Error = warp::Rejection> + Clone
where
    T: AdminRoutingTable + Send + Sync + 'static,
{
    warp::path!("admin" / "routes")
        .and(warp::get())
        .and(warp::any().map(move || table.clone()))
        .map(handle_list_routes)
}

#[derive(Serialize)]
struct AdminRouteListEntry {
    name: String,
    kind: &'static str,
    #[serde(skip_serializing_if = "Option::is_none")]
    strategy: Option<String>,
    endpoints: Vec<AdminRouteEndpoint>,
    source: &'static str,
}

#[derive(Serialize)]
struct AdminRouteEndpoint {
    provider: String,
    service_id: String,
}

fn handle_list_routes<T: AdminRoutingTable>(table: Arc<T>) -> impl warp::Reply {
    let mut entries: Vec<AdminRouteListEntry> = Vec::new();

    // Config-defined routes (from the inner table).
    for entry in table.list_routes() {
        entries.push(AdminRouteListEntry {
            name: entry.name,
            kind: "model",
            strategy: None,
            endpoints: vec![AdminRouteEndpoint {
                provider: entry.provider,
                service_id: String::new(),
            }],
            source: "config",
        });
    }

    // Dynamic routes.
    for route in table.list_dynamic_routes() {
        // Remove any config entry that is shadowed by a dynamic route.
        entries.retain(|e| e.name != route.name);

        let kind = match route.kind {
            RouteKind::Model => "model",
            RouteKind::Tool => "tool",
            RouteKind::Agent => "agent",
        };
        let strategy = match route.strategy {
            bitrouter_core::routers::admin::RouteStrategy::Priority => "priority",
            bitrouter_core::routers::admin::RouteStrategy::LoadBalance => "load_balance",
        };
        entries.push(AdminRouteListEntry {
            name: route.name,
            kind,
            strategy: Some(strategy.to_owned()),
            endpoints: route
                .endpoints
                .into_iter()
                .map(|ep| AdminRouteEndpoint {
                    provider: ep.provider,
                    service_id: ep.service_id,
                })
                .collect(),
            source: "dynamic",
        });
    }

    entries.sort_by(|a, b| a.name.cmp(&b.name));
    warp::reply::json(&serde_json::json!({ "routes": entries }))
}

// ── POST /admin/routes ───────────────────────────────────────────────

fn create_route<T>(
    table: Arc<T>,
) -> impl Filter<Extract = (impl warp::Reply,), Error = warp::Rejection> + Clone
where
    T: AdminRoutingTable + Send + Sync + 'static,
{
    warp::path!("admin" / "routes")
        .and(warp::post())
        .and(warp::body::json::<DynamicRoute>())
        .and(warp::any().map(move || table.clone()))
        .map(handle_create_route)
}

fn handle_create_route<T: AdminRoutingTable>(
    route: DynamicRoute,
    table: Arc<T>,
) -> impl warp::Reply {
    let name = route.name.clone();
    match table.add_route(route) {
        Ok(()) => warp::reply::with_status(
            warp::reply::json(&serde_json::json!({
                "status": "ok",
                "name": name,
            })),
            warp::http::StatusCode::OK,
        ),
        Err(e) => warp::reply::with_status(
            warp::reply::json(&serde_json::json!({
                "error": { "message": e.to_string() }
            })),
            warp::http::StatusCode::BAD_REQUEST,
        ),
    }
}

// ── DELETE /admin/routes/:name ───────────────────────────────────────

fn delete_route<T>(
    table: Arc<T>,
) -> impl Filter<Extract = (impl warp::Reply,), Error = warp::Rejection> + Clone
where
    T: AdminRoutingTable + Send + Sync + 'static,
{
    warp::path!("admin" / "routes" / String)
        .and(warp::delete())
        .and(warp::any().map(move || table.clone()))
        .map(handle_delete_route)
}

fn handle_delete_route<T: AdminRoutingTable>(name: String, table: Arc<T>) -> impl warp::Reply {
    match table.remove_route(&name) {
        Ok(true) => warp::reply::with_status(
            warp::reply::json(&serde_json::json!({
                "status": "ok",
                "name": name,
                "removed": true,
            })),
            warp::http::StatusCode::OK,
        ),
        Ok(false) => warp::reply::with_status(
            warp::reply::json(&serde_json::json!({
                "error": { "message": format!("no dynamic route found for model: {name}") }
            })),
            warp::http::StatusCode::NOT_FOUND,
        ),
        Err(e) => warp::reply::with_status(
            warp::reply::json(&serde_json::json!({
                "error": { "message": e.to_string() }
            })),
            warp::http::StatusCode::INTERNAL_SERVER_ERROR,
        ),
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use bitrouter_core::errors::{BitrouterError, Result};
    use bitrouter_core::routers::admin::{
        AdminRoutingTable, DynamicRoute, RouteEndpoint, RouteKind, RouteStrategy,
    };
    use bitrouter_core::routers::content::RouteContext;
    use bitrouter_core::routers::dynamic::DynamicRoutingTable;
    use bitrouter_core::routers::routing_table::{
        ApiProtocol, RouteEntry, RoutingTable, RoutingTarget,
    };

    use super::admin_routes_filter;

    struct MockTable;

    impl RoutingTable for MockTable {
        async fn route(&self, incoming: &str, _context: &RouteContext) -> Result<RoutingTarget> {
            if incoming == "default" {
                Ok(RoutingTarget {
                    provider_name: "openai".to_owned(),
                    service_id: "gpt-4o".to_owned(),
                    api_protocol: ApiProtocol::Openai,
                })
            } else {
                Err(BitrouterError::invalid_request(
                    None,
                    format!("no route: {incoming}"),
                    None,
                ))
            }
        }

        fn list_routes(&self) -> Vec<RouteEntry> {
            vec![RouteEntry {
                name: "default".to_owned(),
                provider: "openai".to_owned(),
                protocol: ApiProtocol::Openai,
            }]
        }
    }

    fn test_table() -> Arc<DynamicRoutingTable<MockTable>> {
        Arc::new(DynamicRoutingTable::new(MockTable))
    }

    #[tokio::test]
    async fn list_routes_returns_config_routes() {
        let table = test_table();
        let filter = admin_routes_filter(table);

        let res = warp::test::request()
            .method("GET")
            .path("/admin/routes")
            .reply(&filter)
            .await;

        assert_eq!(res.status(), 200);
        let body: serde_json::Value = serde_json::from_slice(res.body()).unwrap();
        let routes = body["routes"].as_array().unwrap();
        assert_eq!(routes.len(), 1);
        assert_eq!(routes[0]["name"], "default");
        assert_eq!(routes[0]["kind"], "model");
        assert_eq!(routes[0]["source"], "config");
    }

    #[tokio::test]
    async fn create_route_success() {
        let table = test_table();
        let filter = admin_routes_filter(table.clone());

        let body = serde_json::json!({
            "name": "research",
            "strategy": "load_balance",
            "endpoints": [
                { "provider": "openai", "service_id": "gpt-4o" },
                { "provider": "anthropic", "service_id": "claude-sonnet-4-20250514" }
            ]
        });

        let res = warp::test::request()
            .method("POST")
            .path("/admin/routes")
            .json(&body)
            .reply(&filter)
            .await;

        assert_eq!(res.status(), 200);
        let resp: serde_json::Value = serde_json::from_slice(res.body()).unwrap();
        assert_eq!(resp["status"], "ok");
        assert_eq!(resp["name"], "research");

        // Verify the route was added.
        assert_eq!(table.list_dynamic_routes().len(), 1);
    }

    #[tokio::test]
    async fn create_route_empty_endpoints_fails() {
        let table = test_table();
        let filter = admin_routes_filter(table);

        let body = serde_json::json!({
            "name": "empty",
            "endpoints": []
        });

        let res = warp::test::request()
            .method("POST")
            .path("/admin/routes")
            .json(&body)
            .reply(&filter)
            .await;

        assert_eq!(res.status(), 400);
    }

    #[tokio::test]
    async fn delete_route_success() {
        let table = test_table();

        // First add a dynamic route.
        table
            .add_route(DynamicRoute {
                name: "temp".to_owned(),
                kind: RouteKind::Model,
                strategy: RouteStrategy::Priority,
                endpoints: vec![RouteEndpoint {
                    provider: "openai".to_owned(),
                    service_id: "gpt-4o".to_owned(),
                    api_protocol: None,
                }],
            })
            .ok();

        let filter = admin_routes_filter(table.clone());

        let res = warp::test::request()
            .method("DELETE")
            .path("/admin/routes/temp")
            .reply(&filter)
            .await;

        assert_eq!(res.status(), 200);
        let resp: serde_json::Value = serde_json::from_slice(res.body()).unwrap();
        assert_eq!(resp["removed"], true);
        assert!(table.list_dynamic_routes().is_empty());
    }

    #[tokio::test]
    async fn delete_nonexistent_route_returns_404() {
        let table = test_table();
        let filter = admin_routes_filter(table);

        let res = warp::test::request()
            .method("DELETE")
            .path("/admin/routes/nope")
            .reply(&filter)
            .await;

        assert_eq!(res.status(), 404);
    }

    #[tokio::test]
    async fn dynamic_route_shadows_config_in_listing() {
        let table = test_table();

        // Add a dynamic route that shadows "default".
        table
            .add_route(DynamicRoute {
                name: "default".to_owned(),
                kind: RouteKind::Model,
                strategy: RouteStrategy::Priority,
                endpoints: vec![RouteEndpoint {
                    provider: "anthropic".to_owned(),
                    service_id: "claude-sonnet-4-20250514".to_owned(),
                    api_protocol: None,
                }],
            })
            .ok();

        let filter = admin_routes_filter(table);

        let res = warp::test::request()
            .method("GET")
            .path("/admin/routes")
            .reply(&filter)
            .await;

        assert_eq!(res.status(), 200);
        let body: serde_json::Value = serde_json::from_slice(res.body()).unwrap();
        let routes = body["routes"].as_array().unwrap();

        // Should have only 1 entry for "default" (the dynamic one).
        let default_routes: Vec<_> = routes.iter().filter(|r| r["name"] == "default").collect();
        assert_eq!(default_routes.len(), 1);
        assert_eq!(default_routes[0]["source"], "dynamic");
    }

    #[tokio::test]
    async fn create_tool_route_success() {
        let table = test_table();
        let filter = admin_routes_filter(table.clone());

        let body = serde_json::json!({
            "name": "web_search",
            "kind": "tool",
            "strategy": "priority",
            "endpoints": [
                { "provider": "exa", "service_id": "search" }
            ]
        });

        let res = warp::test::request()
            .method("POST")
            .path("/admin/routes")
            .json(&body)
            .reply(&filter)
            .await;

        assert_eq!(res.status(), 200);

        // Verify kind is preserved in listing.
        let list_res = warp::test::request()
            .method("GET")
            .path("/admin/routes")
            .reply(&filter)
            .await;

        let list_body: serde_json::Value = serde_json::from_slice(list_res.body()).unwrap();
        let routes = list_body["routes"].as_array().unwrap();
        let tool_route: Vec<_> = routes
            .iter()
            .filter(|r| r["name"] == "web_search")
            .collect();
        assert_eq!(tool_route.len(), 1);
        assert_eq!(tool_route[0]["kind"], "tool");
        assert_eq!(tool_route[0]["source"], "dynamic");
    }
}