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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
//! Key-Value store service.
//!
//! Provides an embedded key-value store using redb (pure Rust, no dependencies).
//!
//! ## URL Schemes
//!
//! ```text
//! redb:///data/kv.redb           # Embedded database at path
//! redb://./kv.redb               # Relative path
//! memory://                      # In-memory (testing only)
//! ```

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

#[cfg(feature = "kv")]
use redb::ReadableDatabase;

use axum::{
    Json, Router,
    body::Bytes,
    extract::{Path, Query, State},
    http::StatusCode,
    response::IntoResponse,
    routing::{delete, get, post},
};
use redb::{Database, ReadableTable, TableDefinition};
use serde::Deserialize;
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

// ============================================================================
// Backend Trait
// ============================================================================

/// Boxed future type for trait methods.
type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;

/// Backend trait for KV operations.
pub trait KvBackend: Send + Sync + 'static {
    /// Backend name for health checks.
    fn name(&self) -> &'static str;

    /// Get a value by key.
    fn get(&self, key: &str) -> BoxFuture<'_, Result<Option<String>>>;

    /// Set a value with optional TTL.
    fn set(&self, key: &str, value: &str, ttl: Option<i64>) -> BoxFuture<'_, Result<()>>;

    /// Delete a key.
    fn del(&self, key: &str) -> BoxFuture<'_, Result<i64>>;

    /// List keys matching a pattern.
    fn keys(&self, pattern: &str) -> BoxFuture<'_, Result<Vec<String>>>;

    /// Increment a key atomically.
    fn incr(&self, key: &str) -> BoxFuture<'_, Result<i64>>;

    /// Get multiple keys at once.
    fn mget(&self, keys: &[String]) -> BoxFuture<'_, Result<Vec<Option<String>>>>;

    /// Set multiple keys at once.
    fn mset(&self, pairs: &[(String, String)]) -> BoxFuture<'_, Result<()>>;

    /// Check if a key exists.
    fn exists(&self, key: &str) -> BoxFuture<'_, Result<bool>>;

    /// Get TTL of a key (-1 if no TTL, -2 if key doesn't exist).
    fn ttl(&self, key: &str) -> BoxFuture<'_, Result<i64>>;

    /// Set expiration on a key.
    fn expire(&self, key: &str, seconds: i64) -> BoxFuture<'_, Result<bool>>;

    /// Health check.
    fn health(&self) -> BoxFuture<'_, HealthResult>;
}

// ============================================================================
// KV Service
// ============================================================================

/// KV service wrapping a backend.
pub struct KvService {
    backend: Arc<dyn KvBackend>,
}

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

impl KvService {
    /// Create a new KV service with a specific backend.
    pub fn new<B: KvBackend>(backend: B) -> Self {
        Self {
            backend: Arc::new(backend),
        }
    }

    /// Create KV service from a URL.
    ///
    /// Supported schemes:
    /// - `redb://path` - Embedded redb database
    /// - `memory://` - In-memory (testing)
    ///
    /// # Errors
    ///
    /// Returns an error if the URL scheme is unknown or the database cannot be opened.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use mikcar::KvService;
    ///
    /// // In-memory store for testing
    /// let kv = KvService::from_url("memory://")?;
    ///
    /// // Embedded redb database
    /// let kv = KvService::from_url("redb://./data/kv.redb")?;
    /// ```
    pub fn from_url(url: &str) -> Result<Self> {
        if url.starts_with("memory://") {
            Ok(Self::new(MemoryBackend::new()))
        } else if url.starts_with("redb://") {
            let path = url.strip_prefix("redb://").unwrap();
            Ok(Self::new(RedbBackend::new(path)?))
        } else {
            Err(Error::Config(format!(
                "Unknown KV URL scheme: {url}. Use redb:// or memory://"
            )))
        }
    }

    /// Create KV service from environment configuration.
    ///
    /// Reads `KV_URL` environment variable.
    ///
    /// # Errors
    ///
    /// Returns an error if `KV_URL` is not set or contains an invalid URL.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use mikcar::KvService;
    ///
    /// // Set KV_URL=redb://./data/kv.redb
    /// let kv = KvService::from_env()?;
    /// ```
    pub fn from_env() -> Result<Self> {
        let url = std::env::var("KV_URL")
            .map_err(|_| Error::Config("KV_URL environment variable not set".to_string()))?;

        Self::from_url(&url)
    }

    /// Create a health check.
    #[must_use]
    pub fn health_checker(&self) -> HealthCheck {
        let backend = self.backend.clone();
        HealthCheck::with_async("kv", move || {
            let backend = backend.clone();
            async move { backend.health().await }
        })
    }
}

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

    fn router(&self) -> Router {
        Router::new()
            .route("/get/{key}", get(get_key))
            .route("/get/batch", post(mget_keys))
            .route("/set/{key}", post(set_key))
            .route("/set/batch", post(mset_keys))
            .route("/del/{key}", delete(del_key))
            .route("/keys/{pattern}", get(list_keys))
            .route("/increment/{key}", post(incr_key))
            .route("/exists/{key}", get(exists_key))
            .route("/ttl/{key}", get(get_ttl))
            .route("/expire/{key}", post(set_expire))
            .with_state(self.backend.clone())
    }

    fn health_check(&self) -> bool {
        // Use block_in_place to run the async health check synchronously.
        // This avoids blocking the async runtime thread pool.
        let backend = self.backend.clone();
        match tokio::runtime::Handle::try_current() {
            Ok(handle) => {
                // We're in a tokio context, use block_in_place
                tokio::task::block_in_place(|| {
                    handle.block_on(async { backend.health().await.healthy })
                })
            }
            Err(_) => {
                // Not in a tokio context, assume healthy (sync fallback)
                true
            }
        }
    }
}

// ============================================================================
// Handlers
// ============================================================================

/// Query parameters for set operation.
#[derive(Deserialize)]
struct SetQuery {
    #[serde(default)]
    ttl: Option<i64>,
}

async fn get_key(
    State(backend): State<Arc<dyn KvBackend>>,
    Path(key): Path<String>,
) -> Result<impl IntoResponse> {
    match backend.get(&key).await? {
        Some(v) => Ok((StatusCode::OK, v)),
        None => Err(Error::NotFound(key)),
    }
}

async fn set_key(
    State(backend): State<Arc<dyn KvBackend>>,
    Path(key): Path<String>,
    Query(query): Query<SetQuery>,
    body: Bytes,
) -> Result<impl IntoResponse> {
    let value = String::from_utf8_lossy(&body).to_string();
    backend.set(&key, &value, query.ttl).await?;

    Ok((
        StatusCode::OK,
        Json(serde_json::json!({
            "status": "ok",
            "key": key
        })),
    ))
}

async fn del_key(
    State(backend): State<Arc<dyn KvBackend>>,
    Path(key): Path<String>,
) -> Result<impl IntoResponse> {
    let deleted = backend.del(&key).await?;

    Ok(Json(serde_json::json!({
        "status": "ok",
        "deleted": deleted
    })))
}

async fn list_keys(
    State(backend): State<Arc<dyn KvBackend>>,
    Path(pattern): Path<String>,
) -> Result<impl IntoResponse> {
    let keys = backend.keys(&pattern).await?;

    Ok(Json(serde_json::json!({
        "keys": keys
    })))
}

async fn incr_key(
    State(backend): State<Arc<dyn KvBackend>>,
    Path(key): Path<String>,
) -> Result<impl IntoResponse> {
    let value = backend.incr(&key).await?;

    Ok(Json(serde_json::json!({
        "value": value
    })))
}

#[derive(Deserialize)]
struct MgetRequest {
    keys: Vec<String>,
}

async fn mget_keys(
    State(backend): State<Arc<dyn KvBackend>>,
    Json(body): Json<MgetRequest>,
) -> Result<impl IntoResponse> {
    let values = backend.mget(&body.keys).await?;
    let result: HashMap<String, Option<String>> = body.keys.into_iter().zip(values).collect();

    Ok(Json(result))
}

async fn mset_keys(
    State(backend): State<Arc<dyn KvBackend>>,
    Json(body): Json<HashMap<String, String>>,
) -> Result<impl IntoResponse> {
    let pairs: Vec<(String, String)> = body.into_iter().collect();
    backend.mset(&pairs).await?;

    Ok(Json(serde_json::json!({
        "status": "ok",
        "count": pairs.len()
    })))
}

async fn exists_key(
    State(backend): State<Arc<dyn KvBackend>>,
    Path(key): Path<String>,
) -> Result<impl IntoResponse> {
    let exists = backend.exists(&key).await?;

    Ok(Json(serde_json::json!({
        "exists": exists
    })))
}

async fn get_ttl(
    State(backend): State<Arc<dyn KvBackend>>,
    Path(key): Path<String>,
) -> Result<impl IntoResponse> {
    let ttl = backend.ttl(&key).await?;

    Ok(Json(serde_json::json!({
        "ttl": ttl
    })))
}

#[derive(Deserialize)]
struct ExpireRequest {
    seconds: i64,
}

async fn set_expire(
    State(backend): State<Arc<dyn KvBackend>>,
    Path(key): Path<String>,
    Json(body): Json<ExpireRequest>,
) -> Result<impl IntoResponse> {
    let result = backend.expire(&key, body.seconds).await?;

    Ok(Json(serde_json::json!({
        "status": if result { "ok" } else { "key_not_found" }
    })))
}

// ============================================================================
// Memory Backend (for testing)
// ============================================================================

use std::sync::RwLock;
use std::time::{Duration, Instant};

struct MemoryEntry {
    value: String,
    expires_at: Option<Instant>,
}

/// In-memory KV backend for testing.
pub struct MemoryBackend {
    data: RwLock<HashMap<String, MemoryEntry>>,
}

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

impl MemoryBackend {
    /// Create a new in-memory backend.
    #[must_use]
    pub fn new() -> Self {
        Self {
            data: RwLock::new(HashMap::new()),
        }
    }

    fn is_expired(entry: &MemoryEntry) -> bool {
        entry
            .expires_at
            .is_some_and(|expires| Instant::now() >= expires)
    }
}

impl Default for MemoryBackend {
    fn default() -> Self {
        Self::new()
    }
}

impl KvBackend for MemoryBackend {
    fn name(&self) -> &'static str {
        "memory"
    }

    fn get(&self, key: &str) -> BoxFuture<'_, Result<Option<String>>> {
        let key = key.to_string();
        Box::pin(async move {
            let data = self.data.read().unwrap();
            match data.get(&key) {
                Some(entry) if !Self::is_expired(entry) => Ok(Some(entry.value.clone())),
                _ => Ok(None),
            }
        })
    }

    fn set(&self, key: &str, value: &str, ttl: Option<i64>) -> BoxFuture<'_, Result<()>> {
        let key = key.to_string();
        let value = value.to_string();
        Box::pin(async move {
            #[allow(clippy::cast_sign_loss)]
            let expires_at = ttl
                .filter(|&t| t > 0)
                .map(|t| Instant::now() + Duration::from_secs(t as u64));

            let mut data = self.data.write().unwrap();
            data.insert(key, MemoryEntry { value, expires_at });
            Ok(())
        })
    }

    fn del(&self, key: &str) -> BoxFuture<'_, Result<i64>> {
        let key = key.to_string();
        Box::pin(async move {
            let mut data = self.data.write().unwrap();
            Ok(i64::from(data.remove(&key).is_some()))
        })
    }

    fn keys(&self, pattern: &str) -> BoxFuture<'_, Result<Vec<String>>> {
        let pattern = pattern.replace('*', ".*").replace('?', ".");
        Box::pin(async move {
            let data = self.data.read().unwrap();
            Ok(data
                .iter()
                .filter(|(k, v)| {
                    !Self::is_expired(v)
                        && (pattern == ".*" || k.contains(&pattern.replace(".*", "")))
                })
                .map(|(k, _)| k.clone())
                .collect())
        })
    }

    fn incr(&self, key: &str) -> BoxFuture<'_, Result<i64>> {
        let key = key.to_string();
        Box::pin(async move {
            let mut data = self.data.write().unwrap();
            let current = data
                .get(&key)
                .filter(|e| !Self::is_expired(e))
                .and_then(|e| e.value.parse::<i64>().ok())
                .unwrap_or(0);

            let new_value = current + 1;
            data.insert(
                key,
                MemoryEntry {
                    value: new_value.to_string(),
                    expires_at: None,
                },
            );
            Ok(new_value)
        })
    }

    fn mget(&self, keys: &[String]) -> BoxFuture<'_, Result<Vec<Option<String>>>> {
        let keys = keys.to_vec();
        Box::pin(async move {
            let data = self.data.read().unwrap();
            Ok(keys
                .iter()
                .map(|k| {
                    data.get(k)
                        .filter(|e| !Self::is_expired(e))
                        .map(|e| e.value.clone())
                })
                .collect())
        })
    }

    fn mset(&self, pairs: &[(String, String)]) -> BoxFuture<'_, Result<()>> {
        let pairs = pairs.to_vec();
        Box::pin(async move {
            let mut data = self.data.write().unwrap();
            for (k, v) in pairs {
                data.insert(
                    k,
                    MemoryEntry {
                        value: v,
                        expires_at: None,
                    },
                );
            }
            Ok(())
        })
    }

    fn exists(&self, key: &str) -> BoxFuture<'_, Result<bool>> {
        let key = key.to_string();
        Box::pin(async move {
            let data = self.data.read().unwrap();
            Ok(data.get(&key).is_some_and(|e| !Self::is_expired(e)))
        })
    }

    fn ttl(&self, key: &str) -> BoxFuture<'_, Result<i64>> {
        let key = key.to_string();
        Box::pin(async move {
            let data = self.data.read().unwrap();
            match data.get(&key) {
                Some(entry) if !Self::is_expired(entry) => match entry.expires_at {
                    Some(expires) => {
                        let remaining = expires.saturating_duration_since(Instant::now());
                        #[allow(clippy::cast_possible_wrap)]
                        Ok(remaining.as_secs() as i64)
                    }
                    None => Ok(-1), // No TTL
                },
                _ => Ok(-2), // Key doesn't exist
            }
        })
    }

    fn expire(&self, key: &str, seconds: i64) -> BoxFuture<'_, Result<bool>> {
        let key = key.to_string();
        Box::pin(async move {
            let mut data = self.data.write().unwrap();
            if let Some(entry) = data.get_mut(&key)
                && !Self::is_expired(entry)
            {
                #[allow(clippy::cast_sign_loss)]
                let expires_at = Instant::now() + Duration::from_secs(seconds as u64);
                entry.expires_at = Some(expires_at);
                return Ok(true);
            }
            Ok(false)
        })
    }

    fn health(&self) -> BoxFuture<'_, HealthResult> {
        Box::pin(async move { HealthResult::healthy() })
    }
}

// ============================================================================
// Redb Backend (embedded, pure Rust)
// ============================================================================

const KV_TABLE: TableDefinition<'_, &str, &str> = TableDefinition::new("kv");
const TTL_TABLE: TableDefinition<'_, &str, u64> = TableDefinition::new("ttl");

/// Embedded redb backend (pure Rust, no external dependencies).
/// Uses `spawn_blocking` for disk I/O to avoid blocking the async executor.
pub struct RedbBackend {
    db: Arc<Database>,
}

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

impl RedbBackend {
    /// Create a new redb backend at the given path.
    pub fn new<P: AsRef<std::path::Path>>(path: P) -> Result<Self> {
        // Create parent directories if they don't exist
        if let Some(parent) = path.as_ref().parent()
            && !parent.as_os_str().is_empty()
        {
            std::fs::create_dir_all(parent)
                .map_err(|e| Error::Config(format!("Failed to create database directory: {e}")))?;
        }

        let db = Database::create(path)
            .map_err(|e| Error::Config(format!("Failed to create redb database: {e}")))?;

        // Initialize tables
        let write_txn = db
            .begin_write()
            .map_err(|e| Error::Internal(format!("Failed to begin transaction: {e}")))?;
        {
            let _ = write_txn.open_table(KV_TABLE);
            let _ = write_txn.open_table(TTL_TABLE);
        }
        write_txn
            .commit()
            .map_err(|e| Error::Internal(format!("Failed to commit: {e}")))?;

        Ok(Self { db: Arc::new(db) })
    }
}

// Free functions for spawn_blocking (can't capture &self)
fn current_timestamp() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs()
}

fn is_key_expired(db: &Database, key: &str) -> bool {
    let Ok(read_txn) = db.begin_read() else {
        return false;
    };
    let Ok(ttl_table) = read_txn.open_table(TTL_TABLE) else {
        return false;
    };
    if let Ok(Some(expires)) = ttl_table.get(key) {
        return current_timestamp() >= expires.value();
    }
    false
}

fn get_sync(db: &Database, key: &str) -> Result<Option<String>> {
    if is_key_expired(db, key) {
        return Ok(None);
    }

    let read_txn = db
        .begin_read()
        .map_err(|e| Error::Internal(e.to_string()))?;
    let table = read_txn
        .open_table(KV_TABLE)
        .map_err(|e| Error::Internal(e.to_string()))?;

    match table.get(key) {
        Ok(Some(value)) => Ok(Some(value.value().to_string())),
        Ok(None) => Ok(None),
        Err(e) => Err(Error::Internal(e.to_string())),
    }
}

fn set_sync(db: &Database, key: &str, value: &str, ttl: Option<i64>) -> Result<()> {
    let write_txn = db
        .begin_write()
        .map_err(|e| Error::Internal(e.to_string()))?;
    {
        let mut table = write_txn
            .open_table(KV_TABLE)
            .map_err(|e| Error::Internal(e.to_string()))?;
        table
            .insert(key, value)
            .map_err(|e| Error::Internal(e.to_string()))?;

        if let Some(ttl) = ttl.filter(|&t| t > 0) {
            let mut ttl_table = write_txn
                .open_table(TTL_TABLE)
                .map_err(|e| Error::Internal(e.to_string()))?;
            #[allow(clippy::cast_sign_loss)]
            let expires_at = current_timestamp() + ttl as u64;
            ttl_table
                .insert(key, expires_at)
                .map_err(|e| Error::Internal(e.to_string()))?;
        }
    }
    write_txn
        .commit()
        .map_err(|e| Error::Internal(e.to_string()))?;
    Ok(())
}

fn del_sync(db: &Database, key: &str) -> Result<i64> {
    let write_txn = db
        .begin_write()
        .map_err(|e| Error::Internal(e.to_string()))?;
    let deleted = {
        let mut table = write_txn
            .open_table(KV_TABLE)
            .map_err(|e| Error::Internal(e.to_string()))?;
        let existed = table
            .remove(key)
            .map_err(|e| Error::Internal(e.to_string()))?
            .is_some();

        if let Ok(mut ttl_table) = write_txn.open_table(TTL_TABLE) {
            let _ = ttl_table.remove(key);
        }

        i64::from(existed)
    };
    write_txn
        .commit()
        .map_err(|e| Error::Internal(e.to_string()))?;
    Ok(deleted)
}

fn keys_sync(db: &Database, pattern: &str) -> Result<Vec<String>> {
    let read_txn = db
        .begin_read()
        .map_err(|e| Error::Internal(e.to_string()))?;
    let table = read_txn
        .open_table(KV_TABLE)
        .map_err(|e| Error::Internal(e.to_string()))?;

    let pattern_str = pattern.replace('*', "");
    let mut keys = Vec::new();

    for entry in table.iter().map_err(|e| Error::Internal(e.to_string()))? {
        let (key, _) = entry.map_err(|e| Error::Internal(e.to_string()))?;
        let key_str = key.value();
        if (pattern == "*" || key_str.contains(&pattern_str)) && !is_key_expired(db, key_str) {
            keys.push(key_str.to_string());
        }
    }

    Ok(keys)
}

fn incr_sync(db: &Database, key: &str) -> Result<i64> {
    let write_txn = db
        .begin_write()
        .map_err(|e| Error::Internal(e.to_string()))?;
    let new_value = {
        let mut table = write_txn
            .open_table(KV_TABLE)
            .map_err(|e| Error::Internal(e.to_string()))?;

        let current = table
            .get(key)
            .map_err(|e| Error::Internal(e.to_string()))?
            .and_then(|v| v.value().parse::<i64>().ok())
            .unwrap_or(0);

        let new_value = current + 1;
        let value_str = new_value.to_string();
        table
            .insert(key, value_str.as_str())
            .map_err(|e| Error::Internal(e.to_string()))?;
        new_value
    };
    write_txn
        .commit()
        .map_err(|e| Error::Internal(e.to_string()))?;
    Ok(new_value)
}

fn mget_sync(db: &Database, keys: &[String]) -> Result<Vec<Option<String>>> {
    let read_txn = db
        .begin_read()
        .map_err(|e| Error::Internal(e.to_string()))?;
    let table = read_txn
        .open_table(KV_TABLE)
        .map_err(|e| Error::Internal(e.to_string()))?;

    let mut results = Vec::with_capacity(keys.len());
    for key in keys {
        if is_key_expired(db, key) {
            results.push(None);
            continue;
        }
        match table.get(key.as_str()) {
            Ok(Some(v)) => results.push(Some(v.value().to_string())),
            _ => results.push(None),
        }
    }
    Ok(results)
}

fn mset_sync(db: &Database, pairs: &[(String, String)]) -> Result<()> {
    let write_txn = db
        .begin_write()
        .map_err(|e| Error::Internal(e.to_string()))?;
    {
        let mut table = write_txn
            .open_table(KV_TABLE)
            .map_err(|e| Error::Internal(e.to_string()))?;
        for (k, v) in pairs {
            table
                .insert(k.as_str(), v.as_str())
                .map_err(|e| Error::Internal(e.to_string()))?;
        }
    }
    write_txn
        .commit()
        .map_err(|e| Error::Internal(e.to_string()))?;
    Ok(())
}

fn exists_sync(db: &Database, key: &str) -> Result<bool> {
    if is_key_expired(db, key) {
        return Ok(false);
    }

    let read_txn = db
        .begin_read()
        .map_err(|e| Error::Internal(e.to_string()))?;
    let table = read_txn
        .open_table(KV_TABLE)
        .map_err(|e| Error::Internal(e.to_string()))?;

    Ok(table
        .get(key)
        .map_err(|e| Error::Internal(e.to_string()))?
        .is_some())
}

fn ttl_sync(db: &Database, key: &str) -> Result<i64> {
    let read_txn = db
        .begin_read()
        .map_err(|e| Error::Internal(e.to_string()))?;

    let table = read_txn
        .open_table(KV_TABLE)
        .map_err(|e| Error::Internal(e.to_string()))?;
    if table
        .get(key)
        .map_err(|e| Error::Internal(e.to_string()))?
        .is_none()
    {
        return Ok(-2);
    }

    let ttl_table = read_txn
        .open_table(TTL_TABLE)
        .map_err(|e| Error::Internal(e.to_string()))?;
    match ttl_table.get(key) {
        Ok(Some(expires)) => {
            let now = current_timestamp();
            let expires_at = expires.value();
            if now >= expires_at {
                Ok(-2)
            } else {
                #[allow(clippy::cast_possible_wrap)]
                Ok((expires_at - now) as i64)
            }
        }
        _ => Ok(-1),
    }
}

fn expire_sync(db: &Database, key: &str, seconds: i64) -> Result<bool> {
    let read_txn = db
        .begin_read()
        .map_err(|e| Error::Internal(e.to_string()))?;
    let table = read_txn
        .open_table(KV_TABLE)
        .map_err(|e| Error::Internal(e.to_string()))?;
    if table
        .get(key)
        .map_err(|e| Error::Internal(e.to_string()))?
        .is_none()
    {
        return Ok(false);
    }
    drop(read_txn);

    let write_txn = db
        .begin_write()
        .map_err(|e| Error::Internal(e.to_string()))?;
    {
        let mut ttl_table = write_txn
            .open_table(TTL_TABLE)
            .map_err(|e| Error::Internal(e.to_string()))?;
        #[allow(clippy::cast_sign_loss)]
        let expires_at = current_timestamp() + seconds as u64;
        ttl_table
            .insert(key, expires_at)
            .map_err(|e| Error::Internal(e.to_string()))?;
    }
    write_txn
        .commit()
        .map_err(|e| Error::Internal(e.to_string()))?;
    Ok(true)
}

impl KvBackend for RedbBackend {
    fn name(&self) -> &'static str {
        "redb"
    }

    fn get(&self, key: &str) -> BoxFuture<'_, Result<Option<String>>> {
        let db = self.db.clone();
        let key = key.to_string();
        Box::pin(async move {
            tokio::task::spawn_blocking(move || get_sync(&db, &key))
                .await
                .map_err(|e| Error::Internal(format!("Task join error: {e}")))?
        })
    }

    fn set(&self, key: &str, value: &str, ttl: Option<i64>) -> BoxFuture<'_, Result<()>> {
        let db = self.db.clone();
        let key = key.to_string();
        let value = value.to_string();
        Box::pin(async move {
            tokio::task::spawn_blocking(move || set_sync(&db, &key, &value, ttl))
                .await
                .map_err(|e| Error::Internal(format!("Task join error: {e}")))?
        })
    }

    fn del(&self, key: &str) -> BoxFuture<'_, Result<i64>> {
        let db = self.db.clone();
        let key = key.to_string();
        Box::pin(async move {
            tokio::task::spawn_blocking(move || del_sync(&db, &key))
                .await
                .map_err(|e| Error::Internal(format!("Task join error: {e}")))?
        })
    }

    fn keys(&self, pattern: &str) -> BoxFuture<'_, Result<Vec<String>>> {
        let db = self.db.clone();
        let pattern = pattern.to_string();
        Box::pin(async move {
            tokio::task::spawn_blocking(move || keys_sync(&db, &pattern))
                .await
                .map_err(|e| Error::Internal(format!("Task join error: {e}")))?
        })
    }

    fn incr(&self, key: &str) -> BoxFuture<'_, Result<i64>> {
        let db = self.db.clone();
        let key = key.to_string();
        Box::pin(async move {
            tokio::task::spawn_blocking(move || incr_sync(&db, &key))
                .await
                .map_err(|e| Error::Internal(format!("Task join error: {e}")))?
        })
    }

    fn mget(&self, keys: &[String]) -> BoxFuture<'_, Result<Vec<Option<String>>>> {
        let db = self.db.clone();
        let keys = keys.to_vec();
        Box::pin(async move {
            tokio::task::spawn_blocking(move || mget_sync(&db, &keys))
                .await
                .map_err(|e| Error::Internal(format!("Task join error: {e}")))?
        })
    }

    fn mset(&self, pairs: &[(String, String)]) -> BoxFuture<'_, Result<()>> {
        let db = self.db.clone();
        let pairs = pairs.to_vec();
        Box::pin(async move {
            tokio::task::spawn_blocking(move || mset_sync(&db, &pairs))
                .await
                .map_err(|e| Error::Internal(format!("Task join error: {e}")))?
        })
    }

    fn exists(&self, key: &str) -> BoxFuture<'_, Result<bool>> {
        let db = self.db.clone();
        let key = key.to_string();
        Box::pin(async move {
            tokio::task::spawn_blocking(move || exists_sync(&db, &key))
                .await
                .map_err(|e| Error::Internal(format!("Task join error: {e}")))?
        })
    }

    fn ttl(&self, key: &str) -> BoxFuture<'_, Result<i64>> {
        let db = self.db.clone();
        let key = key.to_string();
        Box::pin(async move {
            tokio::task::spawn_blocking(move || ttl_sync(&db, &key))
                .await
                .map_err(|e| Error::Internal(format!("Task join error: {e}")))?
        })
    }

    fn expire(&self, key: &str, seconds: i64) -> BoxFuture<'_, Result<bool>> {
        let db = self.db.clone();
        let key = key.to_string();
        Box::pin(async move {
            tokio::task::spawn_blocking(move || expire_sync(&db, &key, seconds))
                .await
                .map_err(|e| Error::Internal(format!("Task join error: {e}")))?
        })
    }

    fn health(&self) -> BoxFuture<'_, HealthResult> {
        let db = self.db.clone();
        Box::pin(async move {
            match tokio::task::spawn_blocking(move || db.begin_read()).await {
                Ok(Ok(_)) => HealthResult::healthy(),
                Ok(Err(e)) => HealthResult::unhealthy(format!("Database error: {e}")),
                Err(e) => HealthResult::unhealthy(format!("Task join error: {e}")),
            }
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ========================================================================
    // MemoryBackend Tests
    // ========================================================================

    #[tokio::test]
    async fn test_memory_set_and_get() {
        let backend = MemoryBackend::new();
        backend.set("key1", "value1", None).await.unwrap();
        let value = backend.get("key1").await.unwrap();
        assert_eq!(value, Some("value1".to_string()));
    }

    #[tokio::test]
    async fn test_memory_get_nonexistent() {
        let backend = MemoryBackend::new();
        let value = backend.get("nonexistent").await.unwrap();
        assert!(value.is_none());
    }

    #[tokio::test]
    async fn test_memory_delete() {
        let backend = MemoryBackend::new();
        backend.set("key1", "value1", None).await.unwrap();
        let deleted = backend.del("key1").await.unwrap();
        assert_eq!(deleted, 1);
        let value = backend.get("key1").await.unwrap();
        assert!(value.is_none());
    }

    #[tokio::test]
    async fn test_memory_delete_nonexistent() {
        let backend = MemoryBackend::new();
        let deleted = backend.del("nonexistent").await.unwrap();
        assert_eq!(deleted, 0);
    }

    #[tokio::test]
    async fn test_memory_exists() {
        let backend = MemoryBackend::new();
        assert!(!backend.exists("key1").await.unwrap());
        backend.set("key1", "value1", None).await.unwrap();
        assert!(backend.exists("key1").await.unwrap());
        backend.del("key1").await.unwrap();
        assert!(!backend.exists("key1").await.unwrap());
    }

    #[tokio::test]
    async fn test_memory_keys() {
        let backend = MemoryBackend::new();
        backend.set("user:1", "alice", None).await.unwrap();
        backend.set("user:2", "bob", None).await.unwrap();
        backend.set("session:abc", "data", None).await.unwrap();
        let all_keys = backend.keys("*").await.unwrap();
        assert_eq!(all_keys.len(), 3);
        let user_keys = backend.keys("user").await.unwrap();
        assert_eq!(user_keys.len(), 2);
    }

    #[tokio::test]
    async fn test_memory_increment() {
        let backend = MemoryBackend::new();
        let val = backend.incr("counter").await.unwrap();
        assert_eq!(val, 1);
        let val = backend.incr("counter").await.unwrap();
        assert_eq!(val, 2);
        let val = backend.incr("counter").await.unwrap();
        assert_eq!(val, 3);
    }

    #[tokio::test]
    async fn test_memory_mget() {
        let backend = MemoryBackend::new();
        backend.set("key1", "value1", None).await.unwrap();
        backend.set("key2", "value2", None).await.unwrap();
        let values = backend
            .mget(&["key1".to_string(), "key2".to_string(), "key3".to_string()])
            .await
            .unwrap();
        assert_eq!(values.len(), 3);
        assert_eq!(values[0], Some("value1".to_string()));
        assert_eq!(values[1], Some("value2".to_string()));
        assert_eq!(values[2], None);
    }

    #[tokio::test]
    async fn test_memory_mset() {
        let backend = MemoryBackend::new();
        backend
            .mset(&[
                ("key1".to_string(), "value1".to_string()),
                ("key2".to_string(), "value2".to_string()),
            ])
            .await
            .unwrap();
        assert_eq!(
            backend.get("key1").await.unwrap(),
            Some("value1".to_string())
        );
        assert_eq!(
            backend.get("key2").await.unwrap(),
            Some("value2".to_string())
        );
    }

    #[tokio::test]
    async fn test_memory_ttl_query() {
        let backend = MemoryBackend::new();
        backend.set("permanent", "value", None).await.unwrap();
        assert_eq!(backend.ttl("permanent").await.unwrap(), -1);
        backend.set("temp", "value", Some(3600)).await.unwrap();
        let ttl = backend.ttl("temp").await.unwrap();
        assert!(ttl > 0 && ttl <= 3600);
        assert_eq!(backend.ttl("nonexistent").await.unwrap(), -2);
    }

    #[tokio::test]
    async fn test_memory_expire() {
        let backend = MemoryBackend::new();
        backend.set("key", "value", None).await.unwrap();
        let result = backend.expire("key", 3600).await.unwrap();
        assert!(result);
        let ttl = backend.ttl("key").await.unwrap();
        assert!(ttl > 0);
        let result = backend.expire("nonexistent", 3600).await.unwrap();
        assert!(!result);
    }

    #[tokio::test]
    async fn test_memory_health() {
        let backend = MemoryBackend::new();
        let health = backend.health().await;
        assert!(health.healthy);
    }

    #[tokio::test]
    async fn test_memory_overwrite() {
        let backend = MemoryBackend::new();
        backend.set("key", "value1", None).await.unwrap();
        backend.set("key", "value2", None).await.unwrap();
        assert_eq!(
            backend.get("key").await.unwrap(),
            Some("value2".to_string())
        );
    }

    // ========================================================================
    // RedbBackend Tests
    // ========================================================================

    #[tokio::test]
    async fn test_redb_set_and_get() {
        let tmp = tempfile::tempdir().unwrap();
        let db_path = tmp.path().join("test.redb");
        let backend = RedbBackend::new(&db_path).unwrap();
        backend.set("key1", "value1", None).await.unwrap();
        let value = backend.get("key1").await.unwrap();
        assert_eq!(value, Some("value1".to_string()));
    }

    #[tokio::test]
    async fn test_redb_get_nonexistent() {
        let tmp = tempfile::tempdir().unwrap();
        let db_path = tmp.path().join("test.redb");
        let backend = RedbBackend::new(&db_path).unwrap();
        let value = backend.get("nonexistent").await.unwrap();
        assert!(value.is_none());
    }

    #[tokio::test]
    async fn test_redb_delete() {
        let tmp = tempfile::tempdir().unwrap();
        let db_path = tmp.path().join("test.redb");
        let backend = RedbBackend::new(&db_path).unwrap();
        backend.set("key1", "value1", None).await.unwrap();
        let deleted = backend.del("key1").await.unwrap();
        assert_eq!(deleted, 1);
        let value = backend.get("key1").await.unwrap();
        assert!(value.is_none());
    }

    #[tokio::test]
    async fn test_redb_exists() {
        let tmp = tempfile::tempdir().unwrap();
        let db_path = tmp.path().join("test.redb");
        let backend = RedbBackend::new(&db_path).unwrap();
        assert!(!backend.exists("key1").await.unwrap());
        backend.set("key1", "value1", None).await.unwrap();
        assert!(backend.exists("key1").await.unwrap());
    }

    #[tokio::test]
    async fn test_redb_increment() {
        let tmp = tempfile::tempdir().unwrap();
        let db_path = tmp.path().join("test.redb");
        let backend = RedbBackend::new(&db_path).unwrap();
        let val = backend.incr("counter").await.unwrap();
        assert_eq!(val, 1);
        let val = backend.incr("counter").await.unwrap();
        assert_eq!(val, 2);
    }

    #[tokio::test]
    async fn test_redb_keys() {
        let tmp = tempfile::tempdir().unwrap();
        let db_path = tmp.path().join("test.redb");
        let backend = RedbBackend::new(&db_path).unwrap();
        backend.set("user:1", "alice", None).await.unwrap();
        backend.set("user:2", "bob", None).await.unwrap();
        backend.set("session:abc", "data", None).await.unwrap();
        let all_keys = backend.keys("*").await.unwrap();
        assert_eq!(all_keys.len(), 3);
    }

    #[tokio::test]
    async fn test_redb_mget_mset() {
        let tmp = tempfile::tempdir().unwrap();
        let db_path = tmp.path().join("test.redb");
        let backend = RedbBackend::new(&db_path).unwrap();
        backend
            .mset(&[
                ("key1".to_string(), "value1".to_string()),
                ("key2".to_string(), "value2".to_string()),
            ])
            .await
            .unwrap();
        let values = backend
            .mget(&["key1".to_string(), "key2".to_string(), "key3".to_string()])
            .await
            .unwrap();
        assert_eq!(values[0], Some("value1".to_string()));
        assert_eq!(values[1], Some("value2".to_string()));
        assert_eq!(values[2], None);
    }

    #[tokio::test]
    async fn test_redb_ttl() {
        let tmp = tempfile::tempdir().unwrap();
        let db_path = tmp.path().join("test.redb");
        let backend = RedbBackend::new(&db_path).unwrap();
        backend.set("permanent", "value", None).await.unwrap();
        assert_eq!(backend.ttl("permanent").await.unwrap(), -1);
        backend.set("temp", "value", Some(3600)).await.unwrap();
        let ttl = backend.ttl("temp").await.unwrap();
        assert!(ttl > 0 && ttl <= 3600);
        assert_eq!(backend.ttl("nonexistent").await.unwrap(), -2);
    }

    #[tokio::test]
    async fn test_redb_expire() {
        let tmp = tempfile::tempdir().unwrap();
        let db_path = tmp.path().join("test.redb");
        let backend = RedbBackend::new(&db_path).unwrap();
        backend.set("key", "value", None).await.unwrap();
        let result = backend.expire("key", 3600).await.unwrap();
        assert!(result);
        let ttl = backend.ttl("key").await.unwrap();
        assert!(ttl > 0);
    }

    #[tokio::test]
    async fn test_redb_health() {
        let tmp = tempfile::tempdir().unwrap();
        let db_path = tmp.path().join("test.redb");
        let backend = RedbBackend::new(&db_path).unwrap();
        let health = backend.health().await;
        assert!(health.healthy);
    }

    // ========================================================================
    // KvService Tests
    // ========================================================================

    #[test]
    fn test_kv_service_from_url_memory() {
        let service = KvService::from_url("memory://").unwrap();
        assert_eq!(service.backend.name(), "memory");
    }

    #[test]
    fn test_kv_service_from_url_redb() {
        let tmp = tempfile::tempdir().unwrap();
        let db_path = tmp.path().join("test.redb");
        let url = format!("redb://{}", db_path.display());
        let service = KvService::from_url(&url).unwrap();
        assert_eq!(service.backend.name(), "redb");
    }

    #[test]
    fn test_kv_service_from_url_invalid() {
        let result = KvService::from_url("invalid://something");
        assert!(result.is_err());
    }

    #[test]
    fn test_kv_service_name() {
        let service = KvService::from_url("memory://").unwrap();
        assert_eq!(service.name(), "kv");
    }

    #[test]
    fn test_kv_service_router() {
        let service = KvService::from_url("memory://").unwrap();
        let _router = service.router();
    }
}