-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhttp_server_design.rs
More file actions
2017 lines (1714 loc) · 58.6 KB
/
http_server_design.rs
File metadata and controls
2017 lines (1714 loc) · 58.6 KB
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ============================================================================
// LLM-Simulator: Enterprise-Grade HTTP Server and API Layer
// ============================================================================
// Module: server
// Purpose: High-performance HTTP API server with OpenAI/Anthropic compatibility
// Framework: Axum with Tower middleware stack
// Performance: 10,000+ req/s, <5ms overhead, streaming SSE support
//
// Architecture:
// - server::app - Application state and server lifecycle
// - server::routes - Route definitions and router configuration
// - server::handlers - Request handlers for all endpoints
// - server::middleware - Authentication, rate limiting, logging
// - server::streaming - SSE streaming response handling
// - server::validation - Request validation and schema checking
// - server::error - Error types and HTTP error responses
// - server::metrics - Prometheus metrics collection
// ============================================================================
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::{Duration, Instant};
use std::pin::Pin;
use axum::{
Router,
extract::{State, Path, Query, Json},
response::{IntoResponse, Response, Sse, sse::Event},
http::{StatusCode, HeaderMap, header},
middleware::{self, Next},
};
use axum::body::Body;
use futures::{Stream, StreamExt};
use tokio::sync::{RwLock, Semaphore};
use tokio::time::sleep;
use tower::{ServiceBuilder, Layer};
use tower_http::{
trace::TraceLayer,
cors::CorsLayer,
compression::CompressionLayer,
timeout::TimeoutLayer,
};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use thiserror::Error;
use uuid::Uuid;
// Internal module imports (these would reference actual modules)
// use crate::simulation::{SimulationEngine, SimulationRequest};
// use crate::latency::{LatencyModel, StreamingSimulator};
// use crate::errors::{ErrorInjector, ErrorInjectionConfig};
// use crate::config::{SimulatorConfig, ConfigManager};
// ============================================================================
// APPLICATION STATE
// ============================================================================
/// Shared application state accessible across all handlers
#[derive(Clone)]
pub struct AppState {
/// Simulation engine for request processing
simulation_engine: Arc<SimulationEngine>,
/// Latency model for realistic timing
latency_model: Arc<RwLock<LatencyModel>>,
/// Error injection system
error_injector: Arc<ErrorInjector>,
/// Configuration manager with hot-reload support
config_manager: Arc<ConfigManager>,
/// Rate limiter
rate_limiter: Arc<RateLimiter>,
/// Metrics collector
metrics: Arc<MetricsCollector>,
/// Active scenario manager
scenario_manager: Arc<ScenarioManager>,
/// Request tracking
request_tracker: Arc<RequestTracker>,
/// Semaphore for concurrency control
concurrency_limiter: Arc<Semaphore>,
/// Server start time for uptime metrics
server_start: Instant,
}
impl AppState {
pub fn new(config: SimulatorConfig) -> Result<Self, ServerError> {
// Initialize simulation engine
let simulation_engine = Arc::new(
SimulationEngine::new(config.engine_config)
.map_err(|e| ServerError::InitializationFailed(e.to_string()))?
);
// Initialize latency model with built-in profiles
let latency_model = Arc::new(RwLock::new(
LatencyModel::new(config.latency_seed)
.with_builtin_profiles()
));
// Initialize error injector
let error_injector = Arc::new(
ErrorInjector::new(config.error_injection_config)
);
// Initialize configuration manager
let config_manager = Arc::new(
ConfigManager::new(config.config_path)
.with_hot_reload(config.hot_reload_enabled)
);
// Initialize rate limiter
let rate_limiter = Arc::new(
RateLimiter::new(config.rate_limit_config)
);
// Initialize metrics
let metrics = Arc::new(MetricsCollector::new());
// Initialize scenario manager
let scenario_manager = Arc::new(ScenarioManager::new());
// Initialize request tracker
let request_tracker = Arc::new(RequestTracker::new());
// Create concurrency limiter
let concurrency_limiter = Arc::new(
Semaphore::new(config.max_concurrent_requests)
);
Ok(Self {
simulation_engine,
latency_model,
error_injector,
config_manager,
rate_limiter,
metrics,
scenario_manager,
request_tracker,
concurrency_limiter,
server_start: Instant::now(),
})
}
}
// ============================================================================
// SERVER LIFECYCLE
// ============================================================================
/// Main HTTP server struct
pub struct SimulatorServer {
config: ServerConfig,
state: AppState,
shutdown_signal: Option<tokio::sync::broadcast::Sender<()>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerConfig {
pub host: String,
pub port: u16,
pub workers: usize,
pub max_concurrent_requests: usize,
pub request_timeout: Duration,
pub keepalive_timeout: Duration,
pub enable_compression: bool,
pub enable_cors: bool,
pub tls_config: Option<TlsConfig>,
pub admin_api_key: Option<String>,
}
impl Default for ServerConfig {
fn default() -> Self {
Self {
host: "0.0.0.0".to_string(),
port: 8080,
workers: num_cpus::get(),
max_concurrent_requests: 10000,
request_timeout: Duration::from_secs(300),
keepalive_timeout: Duration::from_secs(75),
enable_compression: true,
enable_cors: true,
tls_config: None,
admin_api_key: None,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TlsConfig {
pub cert_path: String,
pub key_path: String,
}
impl SimulatorServer {
/// Create a new server instance
pub async fn new(
server_config: ServerConfig,
simulator_config: SimulatorConfig,
) -> Result<Self, ServerError> {
let state = AppState::new(simulator_config)?;
Ok(Self {
config: server_config,
state,
shutdown_signal: None,
})
}
/// Start the server
pub async fn start(&mut self) -> Result<(), ServerError> {
let addr = format!("{}:{}", self.config.host, self.config.port)
.parse::<SocketAddr>()
.map_err(|e| ServerError::InvalidAddress(e.to_string()))?;
tracing::info!("Starting LLM Simulator Server on {}", addr);
// Create router with all routes
let app = create_router(self.state.clone(), &self.config);
// Create shutdown signal
let (shutdown_tx, _) = tokio::sync::broadcast::channel(1);
self.shutdown_signal = Some(shutdown_tx.clone());
// Start server
let listener = tokio::net::TcpListener::bind(addr)
.await
.map_err(|e| ServerError::BindFailed(e.to_string()))?;
tracing::info!("Server listening on {}", addr);
axum::serve(listener, app)
.with_graceful_shutdown(shutdown_handler(shutdown_tx.subscribe()))
.await
.map_err(|e| ServerError::ServerFailed(e.to_string()))?;
Ok(())
}
/// Initiate graceful shutdown
pub async fn shutdown(&self) -> Result<(), ServerError> {
if let Some(tx) = &self.shutdown_signal {
tx.send(()).ok();
tracing::info!("Shutdown signal sent");
}
Ok(())
}
}
async fn shutdown_handler(mut rx: tokio::sync::broadcast::Receiver<()>) {
rx.recv().await.ok();
tracing::info!("Initiating graceful shutdown...");
}
// ============================================================================
// ROUTER CONFIGURATION
// ============================================================================
pub fn create_router(state: AppState, config: &ServerConfig) -> Router {
// Create the main router
let mut app = Router::new()
// ====================================================================
// OpenAI-Compatible Routes
// ====================================================================
.route("/v1/chat/completions",
axum::routing::post(handle_chat_completion))
.route("/v1/completions",
axum::routing::post(handle_completion))
.route("/v1/embeddings",
axum::routing::post(handle_embeddings))
.route("/v1/models",
axum::routing::get(handle_list_models))
.route("/v1/models/:model",
axum::routing::get(handle_get_model))
// ====================================================================
// Anthropic-Compatible Routes
// ====================================================================
.route("/v1/messages",
axum::routing::post(handle_messages))
.route("/v1/complete",
axum::routing::post(handle_anthropic_complete))
// ====================================================================
// Health & Readiness Probes
// ====================================================================
.route("/health",
axum::routing::get(handle_health))
.route("/ready",
axum::routing::get(handle_ready))
.route("/live",
axum::routing::get(handle_liveness))
// ====================================================================
// Metrics & Observability
// ====================================================================
.route("/metrics",
axum::routing::get(handle_metrics))
// ====================================================================
// Admin API (Protected)
// ====================================================================
.route("/admin/config",
axum::routing::post(handle_config_reload))
.route("/admin/config",
axum::routing::get(handle_get_config))
.route("/admin/stats",
axum::routing::get(handle_stats))
.route("/admin/scenarios",
axum::routing::get(handle_list_scenarios))
.route("/admin/scenarios/:name/activate",
axum::routing::post(handle_activate_scenario))
.route("/admin/scenarios/:name/deactivate",
axum::routing::post(handle_deactivate_scenario))
.route("/admin/rate-limits/reset",
axum::routing::post(handle_reset_rate_limits))
// Attach shared state
.with_state(state.clone());
// Build middleware stack (applied in reverse order)
let middleware_stack = ServiceBuilder::new()
// Request tracing
.layer(TraceLayer::new_for_http())
// Global timeout
.layer(TimeoutLayer::new(config.request_timeout))
// Compression (gzip, br, deflate)
.layer(if config.enable_compression {
CompressionLayer::new()
} else {
CompressionLayer::new().no_br().no_gzip().no_deflate()
})
// CORS
.layer(if config.enable_cors {
CorsLayer::permissive()
} else {
CorsLayer::new()
});
app = app.layer(middleware_stack);
// Add custom middleware
app = app
.layer(middleware::from_fn_with_state(
state.clone(),
auth_middleware
))
.layer(middleware::from_fn_with_state(
state.clone(),
rate_limit_middleware
))
.layer(middleware::from_fn_with_state(
state.clone(),
request_logging_middleware
))
.layer(middleware::from_fn_with_state(
state.clone(),
metrics_middleware
));
app
}
// ============================================================================
// OPENAI-COMPATIBLE HANDLERS
// ============================================================================
/// OpenAI Chat Completion Request Schema
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatCompletionRequest {
pub model: String,
pub messages: Vec<ChatMessage>,
#[serde(default)]
pub stream: bool,
#[serde(default)]
pub temperature: Option<f32>,
#[serde(default)]
pub top_p: Option<f32>,
#[serde(default)]
pub max_tokens: Option<u32>,
#[serde(default)]
pub n: Option<u32>,
#[serde(default)]
pub stop: Option<Vec<String>>,
#[serde(default)]
pub presence_penalty: Option<f32>,
#[serde(default)]
pub frequency_penalty: Option<f32>,
#[serde(default)]
pub user: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatMessage {
pub role: String, // "system", "user", "assistant"
pub content: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
/// Handle POST /v1/chat/completions
async fn handle_chat_completion(
State(state): State<AppState>,
headers: HeaderMap,
Json(request): Json<ChatCompletionRequest>,
) -> Result<Response, ApiError> {
// Start timing
let start = Instant::now();
let request_id = generate_request_id();
tracing::debug!(
request_id = %request_id,
model = %request.model,
stream = request.stream,
"Processing chat completion request"
);
// Validate request
validate_chat_completion_request(&request)?;
// Check if error should be injected
if let Some(injected_error) = state.error_injector
.should_inject(&request.model, "chat_completion")
.await
{
return Ok(create_error_response(injected_error, "openai"));
}
// Acquire concurrency permit
let _permit = state.concurrency_limiter
.acquire()
.await
.map_err(|_| ApiError::ServiceUnavailable)?;
// Update metrics
state.metrics.increment_request("chat_completion", &request.model);
if request.stream {
// Handle streaming response
handle_streaming_chat_completion(state, request, request_id).await
} else {
// Handle non-streaming response
handle_non_streaming_chat_completion(state, request, request_id, start).await
}
}
/// Handle non-streaming chat completion
async fn handle_non_streaming_chat_completion(
state: AppState,
request: ChatCompletionRequest,
request_id: String,
start: Instant,
) -> Result<Response, ApiError> {
// Determine number of tokens to generate
let num_tokens = request.max_tokens.unwrap_or(100) as usize;
// Get latency profile for the model
let profile_key = map_model_to_profile(&request.model);
// Simulate latency
let latency_model = state.latency_model.read().await;
let timing = latency_model
.simulate_request(&profile_key, num_tokens)
.map_err(|e| ApiError::InternalError(e.to_string()))?;
drop(latency_model); // Release lock
// Wait for simulated TTFT + full generation
sleep(timing.total_duration).await;
// Generate response content
let response_content = state.simulation_engine
.generate_text(&request.model, &request.messages, num_tokens)
.await
.map_err(|e| ApiError::InternalError(e.to_string()))?;
// Build OpenAI-compatible response
let response = ChatCompletionResponse {
id: format!("chatcmpl-{}", request_id),
object: "chat.completion".to_string(),
created: chrono::Utc::now().timestamp(),
model: request.model.clone(),
choices: vec![
ChatCompletionChoice {
index: 0,
message: ChatMessage {
role: "assistant".to_string(),
content: response_content,
name: None,
},
finish_reason: "stop".to_string(),
}
],
usage: UsageInfo {
prompt_tokens: count_tokens(&request.messages),
completion_tokens: num_tokens as u32,
total_tokens: count_tokens(&request.messages) + num_tokens as u32,
},
};
// Record metrics
let duration = start.elapsed();
state.metrics.record_latency("chat_completion", duration);
state.metrics.record_tokens(num_tokens as u64);
tracing::info!(
request_id = %request_id,
duration_ms = duration.as_millis(),
tokens = num_tokens,
"Chat completion completed"
);
Ok(Json(response).into_response())
}
/// Handle streaming chat completion with SSE
async fn handle_streaming_chat_completion(
state: AppState,
request: ChatCompletionRequest,
request_id: String,
) -> Result<Response, ApiError> {
let num_tokens = request.max_tokens.unwrap_or(100) as usize;
let profile_key = map_model_to_profile(&request.model);
// Generate streaming timing
let latency_model = state.latency_model.read().await;
let mut simulator = latency_model
.create_simulator(&profile_key)
.map_err(|e| ApiError::InternalError(e.to_string()))?;
let timing = simulator.generate_stream_timing(num_tokens);
drop(latency_model);
// Generate token stream
let tokens = state.simulation_engine
.generate_tokens(&request.model, &request.messages, num_tokens)
.await
.map_err(|e| ApiError::InternalError(e.to_string()))?;
// Create SSE stream
let stream = create_chat_completion_stream(
request_id.clone(),
request.model.clone(),
tokens,
timing,
);
tracing::debug!(
request_id = %request_id,
tokens = num_tokens,
"Starting streaming chat completion"
);
Ok(Sse::new(stream).into_response())
}
/// Create SSE stream for chat completion
fn create_chat_completion_stream(
request_id: String,
model: String,
tokens: Vec<String>,
timing: crate::latency::StreamTiming,
) -> impl Stream<Item = Result<Event, std::convert::Infallible>> {
use tokio_stream::wrappers::IntervalStream;
async_stream::stream! {
let start = Instant::now();
for (idx, token) in tokens.iter().enumerate() {
// Wait until it's time to send this token
if let Some(arrival_time) = timing.get_token_arrival(idx) {
let elapsed = start.elapsed();
if arrival_time > elapsed {
sleep(arrival_time - elapsed).await;
}
}
// Create SSE chunk
let chunk = ChatCompletionChunk {
id: format!("chatcmpl-{}", request_id),
object: "chat.completion.chunk".to_string(),
created: chrono::Utc::now().timestamp(),
model: model.clone(),
choices: vec![
ChatCompletionChunkChoice {
index: 0,
delta: ChatMessageDelta {
role: if idx == 0 { Some("assistant".to_string()) } else { None },
content: Some(token.clone()),
},
finish_reason: None,
}
],
};
let event = Event::default()
.json_data(chunk)
.unwrap();
yield Ok(event);
}
// Send final chunk with finish_reason
let final_chunk = ChatCompletionChunk {
id: format!("chatcmpl-{}", request_id),
object: "chat.completion.chunk".to_string(),
created: chrono::Utc::now().timestamp(),
model: model.clone(),
choices: vec![
ChatCompletionChunkChoice {
index: 0,
delta: ChatMessageDelta {
role: None,
content: None,
},
finish_reason: Some("stop".to_string()),
}
],
};
let event = Event::default()
.json_data(final_chunk)
.unwrap();
yield Ok(event);
// Send [DONE] marker
yield Ok(Event::default().data("[DONE]"));
}
}
/// OpenAI Chat Completion Response
#[derive(Debug, Serialize)]
struct ChatCompletionResponse {
id: String,
object: String,
created: i64,
model: String,
choices: Vec<ChatCompletionChoice>,
usage: UsageInfo,
}
#[derive(Debug, Serialize)]
struct ChatCompletionChoice {
index: u32,
message: ChatMessage,
finish_reason: String,
}
#[derive(Debug, Serialize)]
struct UsageInfo {
prompt_tokens: u32,
completion_tokens: u32,
total_tokens: u32,
}
/// SSE Streaming chunks
#[derive(Debug, Serialize)]
struct ChatCompletionChunk {
id: String,
object: String,
created: i64,
model: String,
choices: Vec<ChatCompletionChunkChoice>,
}
#[derive(Debug, Serialize)]
struct ChatCompletionChunkChoice {
index: u32,
delta: ChatMessageDelta,
finish_reason: Option<String>,
}
#[derive(Debug, Serialize)]
struct ChatMessageDelta {
#[serde(skip_serializing_if = "Option::is_none")]
role: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
content: Option<String>,
}
/// Handle POST /v1/completions (legacy)
async fn handle_completion(
State(state): State<AppState>,
Json(request): Json<CompletionRequest>,
) -> Result<Response, ApiError> {
// Similar to chat completion but with legacy format
let request_id = generate_request_id();
tracing::debug!(
request_id = %request_id,
model = %request.model,
"Processing completion request"
);
// Check error injection
if let Some(injected_error) = state.error_injector
.should_inject(&request.model, "completion")
.await
{
return Ok(create_error_response(injected_error, "openai"));
}
let num_tokens = request.max_tokens.unwrap_or(100) as usize;
let profile_key = map_model_to_profile(&request.model);
// Simulate latency
let latency_model = state.latency_model.read().await;
let timing = latency_model
.simulate_request(&profile_key, num_tokens)
.map_err(|e| ApiError::InternalError(e.to_string()))?;
drop(latency_model);
sleep(timing.total_duration).await;
// Generate completion
let completion_text = state.simulation_engine
.generate_completion(&request.model, &request.prompt, num_tokens)
.await
.map_err(|e| ApiError::InternalError(e.to_string()))?;
let response = CompletionResponse {
id: format!("cmpl-{}", request_id),
object: "text_completion".to_string(),
created: chrono::Utc::now().timestamp(),
model: request.model.clone(),
choices: vec![
CompletionChoice {
text: completion_text,
index: 0,
finish_reason: "length".to_string(),
}
],
usage: UsageInfo {
prompt_tokens: count_prompt_tokens(&request.prompt),
completion_tokens: num_tokens as u32,
total_tokens: count_prompt_tokens(&request.prompt) + num_tokens as u32,
},
};
Ok(Json(response).into_response())
}
#[derive(Debug, Deserialize)]
struct CompletionRequest {
model: String,
prompt: String,
max_tokens: Option<u32>,
temperature: Option<f32>,
stream: Option<bool>,
}
#[derive(Debug, Serialize)]
struct CompletionResponse {
id: String,
object: String,
created: i64,
model: String,
choices: Vec<CompletionChoice>,
usage: UsageInfo,
}
#[derive(Debug, Serialize)]
struct CompletionChoice {
text: String,
index: u32,
finish_reason: String,
}
/// Handle POST /v1/embeddings
async fn handle_embeddings(
State(state): State<AppState>,
Json(request): Json<EmbeddingsRequest>,
) -> Result<Response, ApiError> {
let request_id = generate_request_id();
// Check error injection
if let Some(injected_error) = state.error_injector
.should_inject(&request.model, "embeddings")
.await
{
return Ok(create_error_response(injected_error, "openai"));
}
// Simulate embedding generation latency (fast, ~50-100ms)
let embedding_latency = Duration::from_millis(50 + (rand::random::<u64>() % 50));
sleep(embedding_latency).await;
// Determine input count
let input_count = match &request.input {
EmbeddingInput::Single(_) => 1,
EmbeddingInput::Multiple(arr) => arr.len(),
};
// Generate embeddings (deterministic dummy vectors)
let embeddings: Vec<EmbeddingObject> = (0..input_count)
.map(|idx| {
EmbeddingObject {
object: "embedding".to_string(),
index: idx,
embedding: generate_dummy_embedding(1536), // OpenAI default dimension
}
})
.collect();
let response = EmbeddingsResponse {
object: "list".to_string(),
data: embeddings,
model: request.model.clone(),
usage: EmbeddingUsage {
prompt_tokens: input_count as u32 * 10, // Rough estimate
total_tokens: input_count as u32 * 10,
},
};
state.metrics.record_latency("embeddings", embedding_latency);
Ok(Json(response).into_response())
}
#[derive(Debug, Deserialize)]
struct EmbeddingsRequest {
model: String,
input: EmbeddingInput,
}
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum EmbeddingInput {
Single(String),
Multiple(Vec<String>),
}
#[derive(Debug, Serialize)]
struct EmbeddingsResponse {
object: String,
data: Vec<EmbeddingObject>,
model: String,
usage: EmbeddingUsage,
}
#[derive(Debug, Serialize)]
struct EmbeddingObject {
object: String,
index: usize,
embedding: Vec<f32>,
}
#[derive(Debug, Serialize)]
struct EmbeddingUsage {
prompt_tokens: u32,
total_tokens: u32,
}
/// Handle GET /v1/models
async fn handle_list_models(
State(state): State<AppState>,
) -> Result<Response, ApiError> {
let models = vec![
create_model_info("gpt-4-turbo", "openai"),
create_model_info("gpt-4", "openai"),
create_model_info("gpt-3.5-turbo", "openai"),
create_model_info("gpt-3.5-turbo-16k", "openai"),
];
let response = ModelsListResponse {
object: "list".to_string(),
data: models,
};
Ok(Json(response).into_response())
}
/// Handle GET /v1/models/:model
async fn handle_get_model(
State(state): State<AppState>,
Path(model_id): Path<String>,
) -> Result<Response, ApiError> {
// Return model info if exists
let model_info = create_model_info(&model_id, "openai");
Ok(Json(model_info).into_response())
}
#[derive(Debug, Serialize)]
struct ModelsListResponse {
object: String,
data: Vec<ModelInfo>,
}
#[derive(Debug, Serialize)]
struct ModelInfo {
id: String,
object: String,
created: i64,
owned_by: String,
}
fn create_model_info(id: &str, owner: &str) -> ModelInfo {
ModelInfo {
id: id.to_string(),
object: "model".to_string(),
created: 1686935002, // Static timestamp
owned_by: owner.to_string(),
}
}
// ============================================================================
// ANTHROPIC-COMPATIBLE HANDLERS
// ============================================================================
/// Handle POST /v1/messages (Anthropic Messages API)
async fn handle_messages(
State(state): State<AppState>,
headers: HeaderMap,
Json(request): Json<MessagesRequest>,
) -> Result<Response, ApiError> {
let request_id = generate_request_id();
let start = Instant::now();
tracing::debug!(
request_id = %request_id,
model = %request.model,
stream = request.stream.unwrap_or(false),
"Processing Anthropic messages request"
);
// Check error injection
if let Some(injected_error) = state.error_injector
.should_inject(&request.model, "messages")
.await
{
return Ok(create_error_response(injected_error, "anthropic"));
}
let num_tokens = request.max_tokens as usize;
let profile_key = map_model_to_profile(&request.model);
if request.stream.unwrap_or(false) {
// Handle streaming
handle_streaming_messages(state, request, request_id).await
} else {
// Handle non-streaming
handle_non_streaming_messages(state, request, request_id, start).await
}
}
async fn handle_non_streaming_messages(
state: AppState,
request: MessagesRequest,
request_id: String,
start: Instant,
) -> Result<Response, ApiError> {
let num_tokens = request.max_tokens as usize;
let profile_key = map_model_to_profile(&request.model);
// Simulate latency
let latency_model = state.latency_model.read().await;
let timing = latency_model
.simulate_request(&profile_key, num_tokens)
.map_err(|e| ApiError::InternalError(e.to_string()))?;
drop(latency_model);
sleep(timing.total_duration).await;
// Generate response
let content_text = state.simulation_engine
.generate_anthropic_response(&request.model, &request.messages, num_tokens)
.await
.map_err(|e| ApiError::InternalError(e.to_string()))?;
let response = MessagesResponse {
id: format!("msg_{}", request_id),
type_field: "message".to_string(),
role: "assistant".to_string(),
content: vec![
ContentBlock {
type_field: "text".to_string(),
text: content_text,
}
],
model: request.model.clone(),
stop_reason: Some("end_turn".to_string()),
stop_sequence: None,
usage: AnthropicUsage {