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
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
//! Message queue service.
//!
//! ## Design Philosophy
//!
//! mikcar acts as an **HTTP proxy** to queue infrastructure, not a reimplementation.
//!
//! ```text
//! WASM Handler → HTTP → mikcar (proxy) → Redis/RabbitMQ
//! ```
//!
//! ## Platform Support
//!
//! - **Linux/macOS**: Redis Streams and `RabbitMQ` via omniqueue
//! - **Windows**: In-memory only (omniqueue requires cmake)
//!
//! ## Supported Backends (Linux/macOS)
//!
//! - `memory://` - In-memory (tokio mpsc) - development only
//! - `redis://host:port/queue_key` - Redis Streams - production ready
//! - `amqp://user:pass@host:port/queue` - `RabbitMQ` - production ready
//!
//! ## Windows Limitation
//!
//! Windows builds only support `memory://` backend. For production on Windows,
//! deploy mikcar in a Linux container.
//!
//! ## API Design
//!
//! ### Work Queues (At-least-once delivery)
//! - POST /push/{queue} - Push message to queue
//! - GET /pop/{queue}?timeout=30 - Pop message from queue (long-poll)
//! - GET /len/{queue} - Get queue length (backend-dependent)
//!
//! ### Pub/Sub (Topic-based) - In-memory only
//! - POST /publish/{topic} - Publish message to topic
//! - `GET /subscribe/{topic}?timeout=30&max_messages=10` - Long-poll for messages
//! - POST /ack/{topic}/{id} - Acknowledge message
//!
//! Note: For production pub/sub, use native client libraries or dedicated services.
//! omniqueue is optimized for work queue semantics (each message to one consumer).

use crate::{Error, Result, Sidecar};

use axum::{
    Json, Router,
    body::Bytes,
    extract::{Path, Query, State},
    http::StatusCode,
    response::IntoResponse,
    routing::{get, post},
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Mutex;

// ============================================================================
// In-memory backend types (always available)
// ============================================================================

type InMemoryProducer = tokio::sync::mpsc::UnboundedSender<serde_json::Value>;
type InMemoryConsumer = Arc<Mutex<tokio::sync::mpsc::UnboundedReceiver<serde_json::Value>>>;

/// In-memory queue for a single topic/queue.
#[derive(Clone)]
struct InMemoryQueue {
    producer: InMemoryProducer,
    consumer: InMemoryConsumer,
}

// ============================================================================
// Backend abstraction
// ============================================================================

/// Queue backend type.
#[derive(Clone)]
enum QueueBackend {
    /// In-memory backend (development only)
    InMemory {
        topics: Arc<Mutex<HashMap<String, InMemoryQueue>>>,
        queues: Arc<Mutex<HashMap<String, InMemoryQueue>>>,
    },
    /// omniqueue-based backend (Linux/macOS only)
    #[cfg(not(target_os = "windows"))]
    Omniqueue(OmniqueueBackend),
}

/// omniqueue backend wrapper.
#[cfg(not(target_os = "windows"))]
#[derive(Clone)]
struct OmniqueueBackend {
    backend_type: OmniqueueType,
    // Dynamic producers/consumers per queue name
    producers: Arc<Mutex<HashMap<String, Arc<omniqueue::DynProducer>>>>,
    consumers: Arc<Mutex<HashMap<String, Arc<Mutex<omniqueue::DynConsumer>>>>>,
}

#[cfg(not(target_os = "windows"))]
#[derive(Clone, Debug)]
enum OmniqueueType {
    Redis { dsn: String },
    RabbitMq { uri: String },
}

// ============================================================================
// Queue Service
// ============================================================================

/// Queue service configuration.
#[derive(Clone)]
pub struct QueueService {
    backend: QueueBackend,
}

impl std::fmt::Debug for QueueService {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("QueueService")
            .field("backend", &"<queue backend>")
            .finish()
    }
}

impl QueueService {
    /// Create a new in-memory queue service (for testing/development).
    #[must_use]
    pub fn in_memory() -> Self {
        Self {
            backend: QueueBackend::InMemory {
                topics: Arc::new(Mutex::new(HashMap::new())),
                queues: Arc::new(Mutex::new(HashMap::new())),
            },
        }
    }

    /// Create queue service from environment configuration.
    ///
    /// Reads `QUEUE_URL` environment variable.
    /// Supported URL schemes:
    /// - `memory://` - In-memory (tokio mpsc)
    /// - `redis://host:port/queue_key` - Redis Streams
    /// - `amqp://user:pass@host:port/queue` - `RabbitMQ`
    /// - `sqs://region/queue_name` - AWS SQS
    /// - `gcp://project/topic/subscription` - GCP Pub/Sub
    ///
    /// # Errors
    ///
    /// Returns an error if the URL scheme is unsupported or connection fails.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use mikcar::QueueService;
    ///
    /// // Set QUEUE_URL=redis://localhost:6379
    /// let queue = QueueService::from_env().await?;
    /// ```
    pub async fn from_env() -> Result<Self> {
        let url = std::env::var("QUEUE_URL").unwrap_or_else(|_| "memory://".to_string());

        Self::from_url(&url).await
    }

    /// Create queue service from a URL.
    ///
    /// # Errors
    ///
    /// Returns an error if the URL scheme is unsupported or connection fails.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use mikcar::QueueService;
    ///
    /// // In-memory queue (for testing)
    /// let queue = QueueService::from_url("memory://").await?;
    ///
    /// // Redis Streams (Linux/macOS only)
    /// let queue = QueueService::from_url("redis://localhost:6379").await?;
    ///
    /// // RabbitMQ (Linux/macOS only)
    /// let queue = QueueService::from_url("amqp://guest:guest@localhost:5672").await?;
    /// ```
    #[allow(clippy::unused_async)] // Async used on non-Windows platforms
    pub async fn from_url(url: &str) -> Result<Self> {
        if url.starts_with("memory://") {
            return Ok(Self::in_memory());
        }

        #[cfg(target_os = "windows")]
        {
            Err(Error::Config(format!(
                "Backend '{}' not available on Windows. Use memory:// or deploy in Linux container.",
                url.split("://").next().unwrap_or("unknown")
            )))
        }

        #[cfg(not(target_os = "windows"))]
        {
            Self::from_omniqueue_url(url)
        }
    }

    /// Create omniqueue-based backend from URL (Linux/macOS only).
    #[cfg(not(target_os = "windows"))]
    fn from_omniqueue_url(url: &str) -> Result<Self> {
        let backend_type = if url.starts_with("redis://") {
            tracing::info!(url = %url, "Configuring Redis queue backend");
            OmniqueueType::Redis {
                dsn: url.to_string(),
            }
        } else if url.starts_with("amqp://") {
            tracing::info!(url = %url, "Configuring RabbitMQ queue backend");
            OmniqueueType::RabbitMq {
                uri: url.to_string(),
            }
        } else {
            return Err(Error::Config(format!(
                "Unknown queue backend: {url}. Supported: memory://, redis://, amqp://"
            )));
        };

        Ok(Self {
            backend: QueueBackend::Omniqueue(OmniqueueBackend {
                backend_type,
                producers: Arc::new(Mutex::new(HashMap::new())),
                consumers: Arc::new(Mutex::new(HashMap::new())),
            }),
        })
    }

    /// Get or create an in-memory topic queue.
    async fn get_or_create_inmemory_topic(
        &self,
        topics: &Arc<Mutex<HashMap<String, InMemoryQueue>>>,
        topic: &str,
    ) -> Result<InMemoryQueue> {
        let mut topics = topics.lock().await;

        if let Some(queue) = topics.get(topic) {
            return Ok(queue.clone());
        }

        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
        let queue = InMemoryQueue {
            producer: tx,
            consumer: Arc::new(Mutex::new(rx)),
        };

        topics.insert(topic.to_string(), queue.clone());
        Ok(queue)
    }

    /// Get or create an in-memory work queue.
    async fn get_or_create_inmemory_queue(
        &self,
        queues: &Arc<Mutex<HashMap<String, InMemoryQueue>>>,
        name: &str,
    ) -> Result<InMemoryQueue> {
        let mut queues = queues.lock().await;

        if let Some(queue) = queues.get(name) {
            return Ok(queue.clone());
        }

        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
        let queue = InMemoryQueue {
            producer: tx,
            consumer: Arc::new(Mutex::new(rx)),
        };

        queues.insert(name.to_string(), queue.clone());
        Ok(queue)
    }

    /// Ensure Redis consumer group exists (creates stream + group if needed).
    #[cfg(not(target_os = "windows"))]
    async fn ensure_redis_consumer_group(
        dsn: &str,
        queue_name: &str,
        group_name: &str,
    ) -> Result<()> {
        #![allow(unused_imports)]
        use redis::AsyncCommands;

        let client = redis::Client::open(dsn)
            .map_err(|e| Error::Internal(format!("Redis connection error: {e}")))?;
        let mut conn = client
            .get_multiplexed_async_connection()
            .await
            .map_err(|e| Error::Internal(format!("Redis connection error: {e}")))?;

        // XGROUP CREATE <stream> <group> $ MKSTREAM
        // Creates both stream and consumer group if they don't exist
        let result: redis::RedisResult<String> = redis::cmd("XGROUP")
            .arg("CREATE")
            .arg(queue_name)
            .arg(group_name)
            .arg("$")
            .arg("MKSTREAM")
            .query_async(&mut conn)
            .await;

        match result {
            Ok(_) => {
                tracing::info!(queue = %queue_name, group = %group_name, "Created Redis consumer group");
            }
            Err(e) if e.to_string().contains("BUSYGROUP") => {
                // Group already exists, that's fine
            }
            Err(e) => {
                return Err(Error::Internal(format!(
                    "Failed to create consumer group: {e}"
                )));
            }
        }

        Ok(())
    }

    /// Ensure RabbitMQ queue exists (declares queue if needed).
    #[cfg(not(target_os = "windows"))]
    async fn ensure_rabbitmq_queue(uri: &str, queue_name: &str) -> Result<()> {
        use lapin::{
            Connection, ConnectionProperties, options::QueueDeclareOptions, types::FieldTable,
        };

        let conn = Connection::connect(uri, ConnectionProperties::default())
            .await
            .map_err(|e| Error::Internal(format!("RabbitMQ connection error: {e}")))?;

        let channel = conn
            .create_channel()
            .await
            .map_err(|e| Error::Internal(format!("RabbitMQ channel error: {e}")))?;

        // Declare queue (creates if doesn't exist, idempotent if exists)
        channel
            .queue_declare(
                queue_name,
                QueueDeclareOptions {
                    durable: true,
                    ..Default::default()
                },
                FieldTable::default(),
            )
            .await
            .map_err(|e| Error::Internal(format!("Failed to declare RabbitMQ queue: {e}")))?;

        tracing::info!(queue = %queue_name, "Ensured RabbitMQ queue exists");
        Ok(())
    }

    /// Get or create an omniqueue producer for a queue name.
    #[cfg(not(target_os = "windows"))]
    async fn get_or_create_producer(
        &self,
        backend: &OmniqueueBackend,
        queue_name: &str,
    ) -> Result<Arc<omniqueue::DynProducer>> {
        use lapin::options::{BasicConsumeOptions, BasicPublishOptions};
        use lapin::types::FieldTable;
        use lapin::{BasicProperties, ConnectionProperties};
        use omniqueue::backends::rabbitmq::RabbitMqConfig;
        use omniqueue::backends::redis::RedisConfig;
        use omniqueue::backends::{RabbitMqBackend, RedisBackend};

        let mut producers = backend.producers.lock().await;

        if let Some(producer) = producers.get(queue_name) {
            return Ok(Arc::clone(producer));
        }

        let producer: omniqueue::DynProducer = match &backend.backend_type {
            OmniqueueType::Redis { dsn } => {
                // Auto-create consumer group before first use
                Self::ensure_redis_consumer_group(dsn, queue_name, "mikcar").await?;
                let config = RedisConfig {
                    dsn: dsn.clone(),
                    max_connections: 8,
                    reinsert_on_nack: true,
                    queue_key: queue_name.to_string(),
                    delayed_queue_key: format!("{queue_name}:delayed"),
                    delayed_lock_key: format!("{queue_name}:delayed_lock"),
                    consumer_group: "mikcar".to_string(),
                    consumer_name: format!("mikcar-{}", uuid::Uuid::new_v4()),
                    payload_key: "payload".to_string(),
                    ack_deadline_ms: 30_000,
                    dlq_config: None,
                    sentinel_config: None,
                };
                RedisBackend::builder(config)
                    .make_dynamic()
                    .build_producer()
                    .await
                    .map_err(|e| Error::Internal(format!("Failed to create Redis producer: {e}")))?
            }
            OmniqueueType::RabbitMq { uri } => {
                // Auto-create queue before first use
                Self::ensure_rabbitmq_queue(uri, queue_name).await?;
                let config = RabbitMqConfig {
                    uri: uri.clone(),
                    connection_properties: ConnectionProperties::default(),
                    publish_exchange: String::new(),
                    publish_routing_key: queue_name.to_string(),
                    publish_options: BasicPublishOptions::default(),
                    publish_properties: BasicProperties::default(),
                    consume_queue: queue_name.to_string(),
                    consumer_tag: format!("mikcar-{}", uuid::Uuid::new_v4()),
                    consume_options: BasicConsumeOptions::default(),
                    consume_arguments: FieldTable::default(),
                    consume_prefetch_count: Some(10),
                    requeue_on_nack: true,
                };
                RabbitMqBackend::builder(config)
                    .make_dynamic()
                    .build_producer()
                    .await
                    .map_err(|e| {
                        Error::Internal(format!("Failed to create RabbitMQ producer: {e}"))
                    })?
            }
        };

        let producer = Arc::new(producer);
        producers.insert(queue_name.to_string(), Arc::clone(&producer));
        Ok(producer)
    }

    /// Get or create an omniqueue consumer for a queue name.
    #[cfg(not(target_os = "windows"))]
    async fn get_or_create_consumer(
        &self,
        backend: &OmniqueueBackend,
        queue_name: &str,
    ) -> Result<Arc<Mutex<omniqueue::DynConsumer>>> {
        use lapin::options::{BasicConsumeOptions, BasicPublishOptions};
        use lapin::types::FieldTable;
        use lapin::{BasicProperties, ConnectionProperties};
        use omniqueue::backends::rabbitmq::RabbitMqConfig;
        use omniqueue::backends::redis::RedisConfig;
        use omniqueue::backends::{RabbitMqBackend, RedisBackend};

        let mut consumers = backend.consumers.lock().await;

        if let Some(consumer) = consumers.get(queue_name) {
            return Ok(Arc::clone(consumer));
        }

        let consumer: omniqueue::DynConsumer = match &backend.backend_type {
            OmniqueueType::Redis { dsn } => {
                let config = RedisConfig {
                    dsn: dsn.clone(),
                    max_connections: 8,
                    reinsert_on_nack: true,
                    queue_key: queue_name.to_string(),
                    delayed_queue_key: format!("{queue_name}:delayed"),
                    delayed_lock_key: format!("{queue_name}:delayed_lock"),
                    consumer_group: "mikcar".to_string(),
                    consumer_name: format!("mikcar-{}", uuid::Uuid::new_v4()),
                    payload_key: "payload".to_string(),
                    ack_deadline_ms: 30_000,
                    dlq_config: None,
                    sentinel_config: None,
                };
                RedisBackend::builder(config)
                    .make_dynamic()
                    .build_consumer()
                    .await
                    .map_err(|e| Error::Internal(format!("Failed to create Redis consumer: {e}")))?
            }
            OmniqueueType::RabbitMq { uri } => {
                let config = RabbitMqConfig {
                    uri: uri.clone(),
                    connection_properties: ConnectionProperties::default(),
                    publish_exchange: String::new(),
                    publish_routing_key: queue_name.to_string(),
                    publish_options: BasicPublishOptions::default(),
                    publish_properties: BasicProperties::default(),
                    consume_queue: queue_name.to_string(),
                    consumer_tag: format!("mikcar-{}", uuid::Uuid::new_v4()),
                    consume_options: BasicConsumeOptions::default(),
                    consume_arguments: FieldTable::default(),
                    consume_prefetch_count: Some(10),
                    requeue_on_nack: true,
                };
                RabbitMqBackend::builder(config)
                    .make_dynamic()
                    .build_consumer()
                    .await
                    .map_err(|e| {
                        Error::Internal(format!("Failed to create RabbitMQ consumer: {e}"))
                    })?
            }
        };

        let consumer = Arc::new(Mutex::new(consumer));
        consumers.insert(queue_name.to_string(), Arc::clone(&consumer));
        Ok(consumer)
    }
}

impl Sidecar for QueueService {
    fn name(&self) -> &'static str {
        "queue"
    }

    fn router(&self) -> Router {
        Router::new()
            .route("/publish/{topic}", post(publish_message))
            .route("/subscribe/{topic}", get(subscribe_messages))
            .route("/ack/{topic}/{id}", post(ack_message))
            .route("/push/{queue}", post(push_to_queue))
            .route("/pop/{queue}", get(pop_from_queue))
            .route("/len/{queue}", get(queue_length))
            .with_state(Arc::new(self.clone()))
    }

    fn health_check(&self) -> bool {
        match &self.backend {
            QueueBackend::InMemory { .. } => {
                // In-memory backend is always healthy
                true
            }
            #[cfg(not(target_os = "windows"))]
            QueueBackend::Omniqueue(omni) => {
                // For omniqueue backends, try to verify the connection
                match tokio::runtime::Handle::try_current() {
                    Ok(handle) => {
                        let backend_type = omni.backend_type.clone();
                        tokio::task::block_in_place(|| {
                            handle.block_on(async {
                                match backend_type {
                                    OmniqueueType::Redis { ref dsn } => {
                                        // Try a simple Redis PING
                                        match redis::Client::open(dsn.as_str()) {
                                            Ok(client) => {
                                                match client.get_multiplexed_async_connection().await {
                                                    Ok(mut conn) => {
                                                        match redis::cmd("PING")
                                                            .query_async::<String>(&mut conn)
                                                            .await
                                                        {
                                                            Ok(_) => true,
                                                            Err(e) => {
                                                                tracing::warn!(error = %e, "Queue Redis health check failed");
                                                                false
                                                            }
                                                        }
                                                    }
                                                    Err(e) => {
                                                        tracing::warn!(error = %e, "Queue Redis connection failed");
                                                        false
                                                    }
                                                }
                                            }
                                            Err(e) => {
                                                tracing::warn!(error = %e, "Queue Redis client creation failed");
                                                false
                                            }
                                        }
                                    }
                                    OmniqueueType::RabbitMq { ref uri } => {
                                        // For RabbitMQ, try to connect
                                        match lapin::Connection::connect(uri, lapin::ConnectionProperties::default()).await {
                                            Ok(_conn) => true,
                                            Err(e) => {
                                                tracing::warn!(error = %e, "Queue RabbitMQ health check failed");
                                                false
                                            }
                                        }
                                    }
                                }
                            })
                        })
                    }
                    Err(_) => {
                        // Not in a tokio context, assume healthy
                        true
                    }
                }
            }
        }
    }
}

// ============================================================================
// HTTP Handlers
// ============================================================================

/// Message response.
#[derive(Serialize)]
struct MessageResponse {
    id: String,
    payload: serde_json::Value,
    received_at: String,
}

/// Subscribe/pop query parameters.
#[derive(Deserialize)]
struct SubscribeQuery {
    #[serde(default = "default_timeout")]
    timeout: u32,
    #[serde(default = "default_max_messages")]
    max_messages: u32,
}

fn default_timeout() -> u32 {
    30
}

fn default_max_messages() -> u32 {
    10
}

/// Publish a message to a topic (in-memory pub/sub only).
async fn publish_message(
    State(service): State<Arc<QueueService>>,
    Path(topic): Path<String>,
    body: Bytes,
) -> Result<impl IntoResponse> {
    let payload: serde_json::Value = serde_json::from_slice(&body).unwrap_or_else(|_| {
        serde_json::json!({
            "data": String::from_utf8_lossy(&body).to_string()
        })
    });

    match &service.backend {
        QueueBackend::InMemory { topics, .. } => {
            let queue = service.get_or_create_inmemory_topic(topics, &topic).await?;
            queue
                .producer
                .send(payload)
                .map_err(|e| Error::Internal(format!("Failed to publish message: {e}")))?;
        }
        #[cfg(not(target_os = "windows"))]
        QueueBackend::Omniqueue(_) => {
            return Err(Error::Config(
                "Pub/sub not supported with omniqueue backends. Use /push/{queue} for work queues, or use native pub/sub clients.".to_string()
            ));
        }
    }

    let message_id = uuid::Uuid::new_v4().to_string();

    Ok((
        StatusCode::OK,
        Json(serde_json::json!({
            "status": "published",
            "topic": topic,
            "message_id": message_id
        })),
    ))
}

/// Subscribe to messages from a topic (in-memory pub/sub only).
async fn subscribe_messages(
    State(service): State<Arc<QueueService>>,
    Path(topic): Path<String>,
    Query(query): Query<SubscribeQuery>,
) -> Result<impl IntoResponse> {
    match &service.backend {
        QueueBackend::InMemory { topics, .. } => {
            let queue = service.get_or_create_inmemory_topic(topics, &topic).await?;
            let timeout = Duration::from_secs(u64::from(query.timeout));
            let max_messages = query.max_messages;

            let mut messages = Vec::new();
            let mut consumer = queue.consumer.lock().await;

            let deadline = tokio::time::Instant::now() + timeout;

            while messages.len() < max_messages as usize {
                let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
                if remaining.is_zero() {
                    break;
                }

                match tokio::time::timeout(remaining, consumer.recv()).await {
                    Ok(Some(payload)) => {
                        messages.push(MessageResponse {
                            id: uuid::Uuid::new_v4().to_string(),
                            payload,
                            received_at: chrono::Utc::now().to_rfc3339(),
                        });
                    }
                    Ok(None) | Err(_) => break,
                }
            }

            Ok(Json(serde_json::json!({
                "messages": messages,
                "topic": topic,
                "count": messages.len()
            })))
        }
        #[cfg(not(target_os = "windows"))]
        QueueBackend::Omniqueue(_) => {
            Err(Error::Config(
                "Pub/sub not supported with omniqueue backends. Use /pop/{queue} for work queues, or use native pub/sub clients.".to_string()
            ))
        }
    }
}

/// Acknowledge a message (in-memory: no-op, omniqueue: handled at pop).
async fn ack_message(
    State(_service): State<Arc<QueueService>>,
    Path((topic, id)): Path<(String, String)>,
) -> Result<impl IntoResponse> {
    Ok(Json(serde_json::json!({
        "status": "acknowledged",
        "topic": topic,
        "message_id": id
    })))
}

/// Push a message to a work queue.
async fn push_to_queue(
    State(service): State<Arc<QueueService>>,
    Path(queue_name): Path<String>,
    body: Bytes,
) -> Result<impl IntoResponse> {
    let payload: serde_json::Value = serde_json::from_slice(&body).unwrap_or_else(|_| {
        serde_json::json!({
            "data": String::from_utf8_lossy(&body).to_string()
        })
    });

    let message_id = uuid::Uuid::new_v4().to_string();

    match &service.backend {
        QueueBackend::InMemory { queues, .. } => {
            let queue = service
                .get_or_create_inmemory_queue(queues, &queue_name)
                .await?;
            queue
                .producer
                .send(payload.clone())
                .map_err(|e| Error::Internal(format!("Failed to push message: {e}")))?;
        }
        #[cfg(not(target_os = "windows"))]
        QueueBackend::Omniqueue(backend) => {
            let producer = service.get_or_create_producer(backend, &queue_name).await?;
            let payload_bytes = serde_json::to_vec(&payload)
                .map_err(|e| Error::Internal(format!("Failed to serialize payload: {e}")))?;
            producer
                .send_raw(&payload_bytes)
                .await
                .map_err(|e| Error::Internal(format!("Failed to push message: {e}")))?;
        }
    }

    Ok((
        StatusCode::OK,
        Json(serde_json::json!({
            "status": "pushed",
            "queue": queue_name,
            "message_id": message_id
        })),
    ))
}

/// Pop a message from a work queue.
async fn pop_from_queue(
    State(service): State<Arc<QueueService>>,
    Path(queue_name): Path<String>,
    Query(query): Query<SubscribeQuery>,
) -> Result<impl IntoResponse> {
    let timeout = Duration::from_secs(u64::from(query.timeout));

    match &service.backend {
        QueueBackend::InMemory { queues, .. } => {
            let queue = service
                .get_or_create_inmemory_queue(queues, &queue_name)
                .await?;
            let mut consumer = queue.consumer.lock().await;

            match tokio::time::timeout(timeout, consumer.recv()).await {
                Ok(Some(payload)) => {
                    let message = MessageResponse {
                        id: uuid::Uuid::new_v4().to_string(),
                        payload,
                        received_at: chrono::Utc::now().to_rfc3339(),
                    };

                    Ok(Json(serde_json::json!({
                        "message": message,
                        "queue": queue_name
                    })))
                }
                Ok(None) => Err(Error::Internal("Queue channel closed".to_string())),
                Err(_) => Ok(Json(serde_json::json!({
                    "message": null,
                    "queue": queue_name
                }))),
            }
        }
        #[cfg(not(target_os = "windows"))]
        QueueBackend::Omniqueue(backend) => {
            let consumer = service.get_or_create_consumer(backend, &queue_name).await?;
            let mut consumer = consumer.lock().await;

            match tokio::time::timeout(timeout, consumer.receive()).await {
                Ok(Ok(delivery)) => {
                    let payload: serde_json::Value = delivery
                        .payload_serde_json()
                        .unwrap_or(None)
                        .unwrap_or_else(|| {
                            // Fallback for None/missing payload
                            serde_json::json!({
                                "data": String::from_utf8_lossy(delivery.borrow_payload().unwrap_or(&[])).to_string()
                            })
                        });

                    // Auto-ack the message
                    if let Err(e) = delivery.ack().await {
                        tracing::warn!(error = %e.0, "Failed to ack message");
                    }

                    let message = MessageResponse {
                        id: uuid::Uuid::new_v4().to_string(),
                        payload,
                        received_at: chrono::Utc::now().to_rfc3339(),
                    };

                    Ok(Json(serde_json::json!({
                        "message": message,
                        "queue": queue_name
                    })))
                }
                Ok(Err(e)) => Err(Error::Internal(format!("Failed to receive message: {e}"))),
                Err(_) => Ok(Json(serde_json::json!({
                    "message": null,
                    "queue": queue_name
                }))),
            }
        }
    }
}

/// Get the length of a queue.
async fn queue_length(
    State(_service): State<Arc<QueueService>>,
    Path(queue): Path<String>,
) -> Result<impl IntoResponse> {
    // Queue length is not directly supported by omniqueue
    // Would need backend-specific queries
    Ok(Json(serde_json::json!({
        "queue": queue,
        "length": null,
        "note": "Queue length requires backend-specific queries"
    })))
}