httpcan 0.6.0

A simple HTTP Request & Response Service, with httpbin compatibility
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
use actix_web::{web, HttpRequest, HttpResponse, Result};
use chrono::Utc;
use serde::{Deserialize, Serialize};
use std::time::Duration;
use tokio::time::sleep;
use uuid::Uuid;

#[derive(Deserialize)]
pub struct SseParams {
    /// Number of events to send (default: 5)
    count: Option<u32>,
    /// Delay between events in milliseconds (default: 1000)
    delay: Option<u64>,
    /// Message format: "simple", "openai", "custom" (default: "simple")
    format: Option<String>,
    /// Custom message content for "custom" format
    message: Option<String>,
    /// Event type for SSE events (default: "message")
    event_type: Option<String>,
}

#[derive(Serialize)]
pub struct OpenAIChoice {
    pub delta: OpenAIDelta,
    pub index: u32,
    pub finish_reason: Option<String>,
}

#[derive(Serialize)]
pub struct OpenAIDelta {
    pub content: Option<String>,
    pub role: Option<String>,
}

#[derive(Serialize)]
pub struct OpenAIMessage {
    pub id: String,
    pub object: String,
    pub created: i64,
    pub model: String,
    pub choices: Vec<OpenAIChoice>,
}

#[derive(Serialize)]
pub struct OllamaResponse {
    pub model: String,
    pub created_at: String,
    pub response: String,
    pub done: bool,
    pub context: Option<Vec<u32>>,
    pub total_duration: Option<u64>,
    pub load_duration: Option<u64>,
    pub prompt_eval_count: Option<u32>,
    pub prompt_eval_duration: Option<u64>,
    pub eval_count: Option<u32>,
    pub eval_duration: Option<u64>,
}

#[derive(Deserialize)]
pub struct NdjsonParams {
    /// Number of events to send (default: 5)
    count: Option<u32>,
    /// Delay between events in milliseconds (default: 1000)
    delay: Option<u64>,
    /// Message format: "simple", "openai", "ollama", "custom" (default: "simple")
    format: Option<String>,
    /// Custom message content for "custom" format
    message: Option<String>,
    /// Model name for ollama format (default: "llama2")
    model: Option<String>,
}

/// SSE endpoint that streams events with configurable count and format
///
/// Query parameters:
/// - count: number of events to send (default: 5, max: 100)
/// - delay: delay between events in milliseconds (default: 1000, max: 10000)
/// - format: message format - "simple", "openai", "custom" (default: "simple")
/// - message: custom message content (used with format=custom)
/// - event_type: SSE event type (default: "message")
pub async fn sse_handler(_req: HttpRequest, query: web::Query<SseParams>) -> Result<HttpResponse> {
    let count = query.count.unwrap_or(5).min(100); // Max 100 events
    let delay = query.delay.unwrap_or(1000).min(10000); // Max 10 seconds delay
    let format = query.format.as_deref().unwrap_or("simple").to_string();
    let event_type = query.event_type.as_deref().unwrap_or("message").to_string();
    let custom_message = query
        .message
        .as_deref()
        .unwrap_or("Hello from HTTPCan SSE!")
        .to_string();

    let stream = async_stream::stream! {
        for i in 0..count {
            let event_data = match format.as_str() {
                "openai" => generate_openai_event(i, count),
                "custom" => custom_message.clone(),
                _ => {
                    // Simple format - consistent with NDJSON
                    let simple_obj = serde_json::json!({
                        "event": i + 1,
                        "message": format!("Hello from HTTPCan SSE! Event {}/{}", i + 1, count),
                        "timestamp": Utc::now().to_rfc3339()
                    });
                    serde_json::to_string(&simple_obj).unwrap()
                }
            };

            // Format as SSE event
            let sse_event = if event_type == "message" && format != "openai" {
                format!("data: {}\n\n", event_data)
            } else {
                format!("event: {}\ndata: {}\n\n", event_type, event_data)
            };

            yield Ok::<actix_web::web::Bytes, actix_web::Error>(actix_web::web::Bytes::from(sse_event));

            // Don't delay after the last event
            if i < count - 1 {
                sleep(Duration::from_millis(delay)).await;
            }
        }

        // Send final event to indicate completion
        let final_event = match format.as_str() {
            "openai" => {
                let final_chunk = OpenAIMessage {
                    id: format!("chatcmpl-{}", Uuid::new_v4().simple()),
                    object: "chat.completion.chunk".to_string(),
                    created: Utc::now().timestamp(),
                    model: "httpcan-sse".to_string(),
                    choices: vec![OpenAIChoice {
                        delta: OpenAIDelta {
                            content: None,
                            role: None,
                        },
                        index: 0,
                        finish_reason: Some("stop".to_string()),
                    }],
                };
                format!("data: {}\n\n", serde_json::to_string(&final_chunk).unwrap())
            },
            _ => "event: end\ndata: Stream completed\n\n".to_string()
        };

        yield Ok::<actix_web::web::Bytes, actix_web::Error>(actix_web::web::Bytes::from(final_event));

        // Send the SSE termination
        yield Ok::<actix_web::web::Bytes, actix_web::Error>(actix_web::web::Bytes::from("data: [DONE]\n\n"));
    };

    Ok(HttpResponse::Ok()
        .content_type("text/event-stream")
        .insert_header(("Cache-Control", "no-cache"))
        .insert_header(("Connection", "keep-alive"))
        .insert_header(("Access-Control-Allow-Origin", "*"))
        .insert_header(("Access-Control-Allow-Headers", "Cache-Control"))
        .streaming(stream))
}

fn generate_openai_event(index: u32, total: u32) -> String {
    let content = if index < 16 {
        let messages = [
            "Hello",
            " from",
            " HTTPCan",
            " SSE",
            " endpoint!",
            " This",
            " is",
            " streaming",
            " like",
            " OpenAI",
            " ChatGPT",
            " API.",
            " Event",
            "",
            " of",
            "",
        ];

        if index == 13 {
            Some(format!(" {}", index + 1))
        } else if index == 15 {
            Some(format!(" {}.", total))
        } else {
            Some(messages[index as usize].to_string())
        }
    } else if index == 0 {
        Some("Hello from HTTPCan SSE endpoint!".to_string())
    } else {
        Some(format!(" Chunk {}", index + 1))
    };

    let chunk = OpenAIMessage {
        id: format!("chatcmpl-{}", Uuid::new_v4().simple()),
        object: "chat.completion.chunk".to_string(),
        created: Utc::now().timestamp(),
        model: "httpcan-sse".to_string(),
        choices: vec![OpenAIChoice {
            delta: OpenAIDelta {
                content,
                role: if index == 0 {
                    Some("assistant".to_string())
                } else {
                    None
                },
            },
            index: 0,
            finish_reason: None,
        }],
    };

    serde_json::to_string(&chunk).unwrap()
}

fn generate_ollama_event(index: u32, total: u32, model: &str) -> String {
    let responses = [
        "Hello",
        " from",
        " HTTPCan",
        " NDJSON",
        " endpoint!",
        " This",
        " is",
        " streaming",
        " like",
        " Ollama",
        " API.",
        " Response",
        "",
        " of",
        "",
    ];

    let response_text = if index < responses.len() as u32 {
        if index == 12 {
            format!(" {}", index + 1)
        } else if index == 14 {
            format!(" {}.", total)
        } else {
            responses[index as usize].to_string()
        }
    } else {
        format!(" Token {}", index + 1)
    };

    let is_done = index >= total - 1;

    let ollama_response = OllamaResponse {
        model: model.to_string(),
        created_at: Utc::now().to_rfc3339(),
        response: response_text,
        done: is_done,
        context: if is_done {
            Some(vec![1, 2, 3, 4, 5])
        } else {
            None
        },
        total_duration: if is_done { Some(1234567890) } else { None },
        load_duration: if is_done { Some(123456) } else { None },
        prompt_eval_count: if is_done { Some(10) } else { None },
        prompt_eval_duration: if is_done { Some(987654) } else { None },
        eval_count: if is_done { Some(index + 1) } else { None },
        eval_duration: if is_done { Some(5432109) } else { None },
    };

    serde_json::to_string(&ollama_response).unwrap()
}

/// NDJSON endpoint that streams JSON objects separated by newlines
///
/// Query parameters:
/// - count: number of events to send (default: 5, max: 100)
/// - delay: delay between events in milliseconds (default: 1000, max: 10000)
/// - format: message format - "simple", "openai", "ollama", "custom" (default: "simple")
/// - message: custom message content (used with format=custom)
/// - model: model name for ollama format (default: "llama2")
pub async fn ndjson_handler(
    _req: HttpRequest,
    query: web::Query<NdjsonParams>,
) -> Result<HttpResponse> {
    let count = query.count.unwrap_or(5).min(100); // Max 100 events
    let delay = query.delay.unwrap_or(1000).min(10000); // Max 10 seconds delay
    let format = query.format.as_deref().unwrap_or("simple").to_string();
    let custom_message = query
        .message
        .as_deref()
        .unwrap_or("Hello from HTTPCan NDJSON!")
        .to_string();
    let model = query.model.as_deref().unwrap_or("llama2").to_string();

    let stream = async_stream::stream! {
        for i in 0..count {
            let event_data = match format.as_str() {
                "openai" => generate_openai_event(i, count),
                "ollama" => generate_ollama_event(i, count, &model),
                "custom" => {
                    let custom_obj = serde_json::json!({
                        "message": custom_message,
                        "index": i + 1,
                        "total": count,
                        "timestamp": Utc::now().to_rfc3339()
                    });
                    serde_json::to_string(&custom_obj).unwrap()
                },
                _ => {
                    // Simple format
                    let simple_obj = serde_json::json!({
                        "event": i + 1,
                        "message": format!("Hello from HTTPCan NDJSON! Event {}/{}", i + 1, count),
                        "timestamp": Utc::now().to_rfc3339()
                    });
                    serde_json::to_string(&simple_obj).unwrap()
                }
            };

            // Format as NDJSON (JSON object followed by newline)
            let ndjson_line = format!("{}\n", event_data);
            yield Ok::<actix_web::web::Bytes, actix_web::Error>(actix_web::web::Bytes::from(ndjson_line));

            // Don't delay after the last event
            if i < count - 1 {
                sleep(Duration::from_millis(delay)).await;
            }
        }
    };

    Ok(HttpResponse::Ok()
        .content_type("application/x-ndjson")
        .insert_header(("Cache-Control", "no-cache"))
        .insert_header(("Connection", "keep-alive"))
        .insert_header(("Access-Control-Allow-Origin", "*"))
        .insert_header(("Access-Control-Allow-Headers", "Cache-Control"))
        .streaming(stream))
}

/// NDJSON endpoint with path parameters for convenience
/// GET /ndjson/{count} - sends {count} events with default settings
/// GET /ndjson/{count}/{delay} - sends {count} events with {delay}ms between events
pub async fn ndjson_path_handler(
    req: HttpRequest,
    path: web::Path<(u32,)>,
    query: web::Query<NdjsonParams>,
) -> Result<HttpResponse> {
    let (count,) = path.into_inner();

    let params = NdjsonParams {
        count: Some(count.min(100)),
        delay: query.delay,
        format: query.format.clone(),
        message: query.message.clone(),
        model: query.model.clone(),
    };

    ndjson_handler(req, web::Query(params)).await
}

/// NDJSON endpoint with both count and delay as path parameters
pub async fn ndjson_path_with_delay_handler(
    req: HttpRequest,
    path: web::Path<(u32, u64)>,
    query: web::Query<NdjsonParams>,
) -> Result<HttpResponse> {
    let (count, delay) = path.into_inner();

    let params = NdjsonParams {
        count: Some(count.min(100)),
        delay: Some(delay.min(10000)),
        format: query.format.clone(),
        message: query.message.clone(),
        model: query.model.clone(),
    };

    ndjson_handler(req, web::Query(params)).await
}

/// SSE endpoint with path parameters for convenience
/// GET /sse/{count} - sends {count} events with default settings
/// GET /sse/{count}/{delay} - sends {count} events with {delay}ms between events
pub async fn sse_path_handler(
    req: HttpRequest,
    path: web::Path<(u32,)>,
    query: web::Query<SseParams>,
) -> Result<HttpResponse> {
    let (count,) = path.into_inner();

    let params = SseParams {
        count: Some(count.min(100)),
        delay: query.delay,
        format: query.format.clone(),
        message: query.message.clone(),
        event_type: query.event_type.clone(),
    };

    sse_handler(req, web::Query(params)).await
}

/// SSE endpoint with both count and delay as path parameters
pub async fn sse_path_with_delay_handler(
    req: HttpRequest,
    path: web::Path<(u32, u64)>,
    query: web::Query<SseParams>,
) -> Result<HttpResponse> {
    let (count, delay) = path.into_inner();

    let params = SseParams {
        count: Some(count.min(100)),
        delay: Some(delay.min(10000)),
        format: query.format.clone(),
        message: query.message.clone(),
        event_type: query.event_type.clone(),
    };

    sse_handler(req, web::Query(params)).await
}