mikcar 0.1.1

Sidecar infrastructure services for mik (storage, kv, sql, queue)
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
//! Queue backend integration tests.
//!
//! These tests require Docker services to be running:
//! ```bash
//! docker-compose up -d redis rabbitmq localstack
//! ```
//!
//! Run these tests with:
//! ```bash
//! cargo test --test queue_integration -- --ignored
//! ```
//!
//! Note: omniqueue-based tests (Redis, RabbitMQ, SQS) only run on Linux/macOS.
//! In-memory tests run on all platforms.

use std::time::Duration;

/// Helper to check if a service is available
#[allow(dead_code)]
async fn is_service_available(url: &str) -> bool {
    let client = reqwest::Client::new();
    match tokio::time::timeout(Duration::from_secs(2), client.get(url).send()).await {
        Ok(Ok(resp)) => resp.status().is_success(),
        _ => false,
    }
}

/// Helper to check if Redis is available
#[allow(dead_code)]
async fn is_redis_available() -> bool {
    use std::process::Command;
    let output = Command::new("redis-cli")
        .args(["-h", "localhost", "-p", "6379", "ping"])
        .output();
    matches!(output, Ok(o) if o.status.success())
}

/// Helper to check if RabbitMQ is available
#[allow(dead_code)]
async fn is_rabbitmq_available() -> bool {
    is_service_available("http://localhost:15672/api/health/checks/alarms").await
}

/// Helper to check if LocalStack SQS is available
#[allow(dead_code)]
async fn is_localstack_available() -> bool {
    is_service_available("http://localhost:4566/_localstack/health").await
}

// ============================================================================
// omniqueue-based tests (Linux/macOS only)
// ============================================================================

#[cfg(all(not(target_os = "windows"), feature = "queue"))]
mod redis_queue {
    use super::*;
    use mikcar::queue::QueueService;

    const REDIS_URL: &str = "redis://localhost:6379";

    #[tokio::test]
    #[ignore = "requires Docker: docker-compose up -d redis"]
    async fn test_redis_queue_push_pop() {
        if !is_redis_available().await {
            eprintln!("Skipping: Redis not available at localhost:6379");
            return;
        }

        let service = QueueService::from_url(REDIS_URL)
            .await
            .expect("Failed to create Redis queue service");

        // Create a simple test by verifying the service was created
        // The actual push/pop would require running the HTTP server
        assert!(matches!(service, QueueService { .. }));
        println!("✓ Redis queue service created successfully");
    }

    #[tokio::test]
    #[ignore = "requires Docker: docker-compose up -d redis"]
    async fn test_redis_queue_service_http() {
        use axum::body::Body;
        use axum::http::{Request, StatusCode};
        use mikcar::Sidecar;
        use tower::ServiceExt;

        if !is_redis_available().await {
            eprintln!("Skipping: Redis not available at localhost:6379");
            return;
        }

        let service = QueueService::from_url(REDIS_URL)
            .await
            .expect("Failed to create Redis queue service");

        let router = service.router();

        // Test push
        let push_request = Request::builder()
            .method("POST")
            .uri("/push/test-queue")
            .header("content-type", "application/json")
            .body(Body::from(r#"{"message": "hello from redis test"}"#))
            .unwrap();

        let response = router.clone().oneshot(push_request).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        println!("✓ Redis push succeeded");

        // Test pop with short timeout
        let pop_request = Request::builder()
            .method("GET")
            .uri("/pop/test-queue?timeout=5")
            .body(Body::empty())
            .unwrap();

        let response = router.oneshot(pop_request).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);

        let body = axum::body::to_bytes(response.into_body(), 1024 * 1024)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();

        assert!(json.get("message").is_some());
        println!("✓ Redis pop succeeded: {:?}", json);
    }
}

#[cfg(all(not(target_os = "windows"), feature = "queue"))]
mod rabbitmq_queue {
    use super::*;
    use mikcar::queue::QueueService;

    const RABBITMQ_URL: &str = "amqp://guest:guest@localhost:5672";

    #[tokio::test]
    #[ignore = "requires Docker: docker-compose up -d rabbitmq"]
    async fn test_rabbitmq_queue_push_pop() {
        if !is_rabbitmq_available().await {
            eprintln!("Skipping: RabbitMQ not available at localhost:5672");
            return;
        }

        let service = QueueService::from_url(RABBITMQ_URL)
            .await
            .expect("Failed to create RabbitMQ queue service");

        assert!(matches!(service, QueueService { .. }));
        println!("✓ RabbitMQ queue service created successfully");
    }

    #[tokio::test]
    #[ignore = "requires Docker: docker-compose up -d rabbitmq"]
    async fn test_rabbitmq_queue_service_http() {
        use axum::body::Body;
        use axum::http::{Request, StatusCode};
        use mikcar::Sidecar;
        use tower::ServiceExt;

        if !is_rabbitmq_available().await {
            eprintln!("Skipping: RabbitMQ not available at localhost:5672");
            return;
        }

        let service = QueueService::from_url(RABBITMQ_URL)
            .await
            .expect("Failed to create RabbitMQ queue service");

        let router = service.router();

        // Test push
        let push_request = Request::builder()
            .method("POST")
            .uri("/push/rabbitmq-test-queue")
            .header("content-type", "application/json")
            .body(Body::from(r#"{"message": "hello from rabbitmq test"}"#))
            .unwrap();

        let response = router.clone().oneshot(push_request).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        println!("✓ RabbitMQ push succeeded");

        // Test pop with short timeout
        let pop_request = Request::builder()
            .method("GET")
            .uri("/pop/rabbitmq-test-queue?timeout=5")
            .body(Body::empty())
            .unwrap();

        let response = router.oneshot(pop_request).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);

        let body = axum::body::to_bytes(response.into_body(), 1024 * 1024)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();

        assert!(json.get("message").is_some());
        println!("✓ RabbitMQ pop succeeded: {:?}", json);
    }
}

#[cfg(all(not(target_os = "windows"), feature = "queue"))]
mod sqs_queue {
    use super::*;
    use mikcar::queue::QueueService;

    // LocalStack SQS endpoint
    const SQS_URL: &str = "sqs://http://localhost:4566/000000000000/test-queue?override=true";

    /// Set fake AWS credentials for LocalStack
    fn setup_localstack_credentials() {
        // SAFETY: These are test-only fake credentials for LocalStack.
        // Single-threaded test execution ensures no race conditions.
        unsafe {
            std::env::set_var("AWS_ACCESS_KEY_ID", "test");
            std::env::set_var("AWS_SECRET_ACCESS_KEY", "test");
            std::env::set_var("AWS_REGION", "us-east-1");
        }
    }

    async fn create_sqs_queue() -> bool {
        // Create the SQS queue in LocalStack using proper SQS API
        let client = reqwest::Client::new();

        // LocalStack SQS uses query string parameters
        let response = client
            .get("http://localhost:4566")
            .query(&[
                ("Action", "CreateQueue"),
                ("QueueName", "test-queue"),
                ("Version", "2012-11-05"),
            ])
            .send()
            .await;

        match response {
            Ok(r) => {
                let success = r.status().is_success();
                if !success {
                    if let Ok(body) = r.text().await {
                        eprintln!("SQS queue creation response: {}", body);
                    }
                }
                success
            }
            Err(e) => {
                eprintln!("SQS queue creation failed: {}", e);
                false
            }
        }
    }

    #[tokio::test]
    #[ignore = "requires Docker: docker-compose up -d localstack"]
    async fn test_sqs_queue_push_pop() {
        setup_localstack_credentials();

        if !is_localstack_available().await {
            eprintln!("Skipping: LocalStack not available at localhost:4566");
            return;
        }

        // Create queue first
        create_sqs_queue().await;

        let service = QueueService::from_url(SQS_URL)
            .await
            .expect("Failed to create SQS queue service");

        assert!(matches!(service, QueueService { .. }));
        println!("✓ SQS queue service created successfully");
    }

    #[tokio::test]
    #[ignore = "requires Docker: docker-compose up -d localstack"]
    async fn test_sqs_queue_service_http() {
        use axum::body::Body;
        use axum::http::{Request, StatusCode};
        use mikcar::Sidecar;
        use tower::ServiceExt;

        setup_localstack_credentials();

        if !is_localstack_available().await {
            eprintln!("Skipping: LocalStack not available at localhost:4566");
            return;
        }

        // Create queue first
        create_sqs_queue().await;

        let service = QueueService::from_url(SQS_URL)
            .await
            .expect("Failed to create SQS queue service");

        let router = service.router();

        // Test push - use "test-queue" to match the configured SQS queue
        let push_request = Request::builder()
            .method("POST")
            .uri("/push/test-queue")
            .header("content-type", "application/json")
            .body(Body::from(r#"{"message": "hello from sqs test"}"#))
            .unwrap();

        let response = router.clone().oneshot(push_request).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        println!("✓ SQS push succeeded");

        // Test pop with short timeout
        let pop_request = Request::builder()
            .method("GET")
            .uri("/pop/test-queue?timeout=5")
            .body(Body::empty())
            .unwrap();

        let response = router.oneshot(pop_request).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);

        let body = axum::body::to_bytes(response.into_body(), 1024 * 1024)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();

        // SQS may return null message if queue is empty or message not yet visible
        println!("✓ SQS pop completed: {:?}", json);
    }
}

// ============================================================================
// In-memory tests (requires queue feature)
// ============================================================================

#[cfg(feature = "queue")]
mod memory_queue {
    use mikcar::Sidecar;
    use mikcar::queue::QueueService;

    #[tokio::test]
    async fn test_memory_queue_push_pop() {
        use axum::body::Body;
        use axum::http::{Request, StatusCode};
        use tower::ServiceExt;

        let service = QueueService::from_url("memory://")
            .await
            .expect("Failed to create in-memory queue service");

        let router = service.router();

        // Test push
        let push_request = Request::builder()
            .method("POST")
            .uri("/push/memory-test-queue")
            .header("content-type", "application/json")
            .body(Body::from(r#"{"message": "hello from memory test"}"#))
            .unwrap();

        let response = router.clone().oneshot(push_request).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);

        let body = axum::body::to_bytes(response.into_body(), 1024 * 1024)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["status"], "pushed");
        println!("✓ Memory push succeeded");

        // Test pop
        let pop_request = Request::builder()
            .method("GET")
            .uri("/pop/memory-test-queue?timeout=1")
            .body(Body::empty())
            .unwrap();

        let response = router.oneshot(pop_request).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);

        let body = axum::body::to_bytes(response.into_body(), 1024 * 1024)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();

        assert!(json.get("message").is_some());
        let message = &json["message"];
        assert_eq!(message["payload"]["message"], "hello from memory test");
        println!("✓ Memory pop succeeded: {:?}", json);
    }

    #[tokio::test]
    async fn test_memory_pubsub() {
        use axum::body::Body;
        use axum::http::{Request, StatusCode};
        use tower::ServiceExt;

        let service = QueueService::from_url("memory://")
            .await
            .expect("Failed to create in-memory queue service");

        let router = service.router();

        // Test publish
        let publish_request = Request::builder()
            .method("POST")
            .uri("/publish/test-topic")
            .header("content-type", "application/json")
            .body(Body::from(r#"{"event": "user_created", "user_id": 123}"#))
            .unwrap();

        let response = router.clone().oneshot(publish_request).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);

        let body = axum::body::to_bytes(response.into_body(), 1024 * 1024)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["status"], "published");
        println!("✓ Memory publish succeeded");

        // Test subscribe
        let subscribe_request = Request::builder()
            .method("GET")
            .uri("/subscribe/test-topic?timeout=1&max_messages=1")
            .body(Body::empty())
            .unwrap();

        let response = router.oneshot(subscribe_request).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);

        let body = axum::body::to_bytes(response.into_body(), 1024 * 1024)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();

        assert_eq!(json["count"], 1);
        let messages = json["messages"].as_array().unwrap();
        assert_eq!(messages[0]["payload"]["event"], "user_created");
        println!("✓ Memory subscribe succeeded: {:?}", json);
    }
}