rift-http-proxy 0.3.0

Rift: high-performance HTTP chaos engineering proxy with Lua/Rhai/JavaScript scripting for fault injection.
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
//! Type definitions for Mountebank-compatible imposter management.
//!
//! This module contains all the structs, enums, and type aliases used by the imposter system.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

// ============================================================================
// Recorded Request Types
// ============================================================================

/// Recorded request for imposter
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RecordedRequest {
    pub request_from: String,
    pub method: String,
    pub path: String,
    pub query: HashMap<String, String>,
    pub headers: HashMap<String, String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,
    pub timestamp: String,
}

// ============================================================================
// Debug Mode Structures (Rift Extension)
// ============================================================================

/// Debug response for X-Rift-Debug header (Rift extension)
/// Returns match information instead of executing the response
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DebugResponse {
    pub debug: bool,
    pub request: DebugRequest,
    pub imposter: DebugImposter,
    pub match_result: DebugMatchResult,
}

/// Debug request information
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DebugRequest {
    pub method: String,
    pub path: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub query: Option<String>,
    pub headers: HashMap<String, String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,
}

/// Debug imposter information
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DebugImposter {
    pub port: u16,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    pub protocol: String,
    pub stub_count: usize,
}

/// Debug match result
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DebugMatchResult {
    pub matched: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stub_index: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stub_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub predicates: Option<Vec<Predicate>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response_preview: Option<DebugResponsePreview>,
    /// All stubs for inspection when no match found
    #[serde(skip_serializing_if = "Option::is_none")]
    pub all_stubs: Option<Vec<DebugStubInfo>>,
    /// Reason for no match
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

/// Debug response preview (subset of actual response)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DebugResponsePreview {
    pub response_type: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status_code: Option<u16>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub headers: Option<HashMap<String, String>>,
    /// Truncated body preview (first 500 chars)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body_preview: Option<String>,
}

/// Debug stub info for listing all stubs
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DebugStubInfo {
    pub index: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    pub predicates: Vec<Predicate>,
    pub response_count: usize,
}

// ============================================================================
// Stub Types
// ============================================================================

/// Stub definition (Mountebank-compatible with Rift extensions)
/// Field ordering matches Mountebank output: scenarioName, predicates, responses, _links
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", from = "StubRaw")]
pub struct Stub {
    /// Optional scenario name for documentation/organization (Mountebank compatible)
    /// Placed first to match Mountebank output ordering
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scenario_name: Option<String>,
    /// Optional unique identifier for the stub (Rift extension)
    /// Useful for targeting specific stubs for updates/deletion without relying on index
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    #[serde(default)]
    pub predicates: Vec<Predicate>,
    #[serde(default)]
    pub responses: Vec<StubResponse>,
    /// Upstream URL recorded from during proxy recording (Mountebank compatible)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recorded_from: Option<String>,
}

/// Raw deserialization type for Stub — handles alternative field names and format conversions:
/// - `rules` as an alias for `predicates`
/// - `delayRange` array (stub-level latency) converted to per-response `wait` behavior
/// - `recordedFrom` URL from Mountebank proxy recording
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct StubRaw {
    #[serde(default)]
    scenario_name: Option<String>,
    #[serde(default)]
    id: Option<String>,
    #[serde(default)]
    predicates: Vec<Predicate>,
    /// Alternative field name "rules" used instead of "predicates" in some recorded formats
    #[serde(default)]
    rules: Vec<Predicate>,
    #[serde(default)]
    responses: Vec<StubResponse>,
    #[serde(default)]
    recorded_from: Option<String>,
    /// Stub-level latency range: `[{ "min": "50", "max": "100" }]`
    #[serde(default)]
    delay_range: Vec<DelayRange>,
}

/// A `delayRange` entry for stub-level latency configuration.
/// Both `min` and `max` may be numbers or numeric strings.
#[derive(Debug, Clone, Deserialize)]
struct DelayRange {
    #[serde(deserialize_with = "de_u64_or_string")]
    min: u64,
    #[serde(deserialize_with = "de_u64_or_string")]
    max: u64,
}

fn de_u64_or_string<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u64, D::Error> {
    use serde::de::Error;
    let v = serde_json::Value::deserialize(d)?;
    match v {
        serde_json::Value::Number(n) => n
            .as_u64()
            .ok_or_else(|| D::Error::custom("expected non-negative integer")),
        serde_json::Value::String(s) => s
            .parse::<u64>()
            .map_err(|_| D::Error::custom(format!("cannot parse '{s}' as integer"))),
        _ => Err(D::Error::custom("expected number or numeric string")),
    }
}

impl From<StubRaw> for Stub {
    fn from(raw: StubRaw) -> Self {
        // "rules" is an alias for "predicates"; prefer "predicates" when both present
        let predicates = if !raw.predicates.is_empty() {
            raw.predicates
        } else {
            raw.rules
        };

        // Convert stub-level delayRange to a wait behavior injected into each response
        let responses = if raw.delay_range.is_empty() {
            raw.responses
        } else {
            let wait_val = build_wait_from_delay_range(&raw.delay_range);
            raw.responses
                .into_iter()
                .map(|r| inject_wait_behavior(r, wait_val.clone()))
                .collect()
        };

        Stub {
            scenario_name: raw.scenario_name,
            id: raw.id,
            predicates,
            responses,
            recorded_from: raw.recorded_from,
        }
    }
}

/// Build a wait value from a delayRange array (uses first entry).
/// Emits a fixed value when min == max, otherwise a range object.
fn build_wait_from_delay_range(ranges: &[DelayRange]) -> serde_json::Value {
    let first = &ranges[0];
    if first.min == first.max {
        serde_json::Value::Number(first.min.into())
    } else {
        serde_json::json!({ "min": first.min, "max": first.max })
    }
}

/// Inject a `wait` value into a stub response's `_behaviors`, but only when
/// the response does not already have an explicit wait configured.
fn inject_wait_behavior(response: StubResponse, wait_val: serde_json::Value) -> StubResponse {
    match response {
        StubResponse::Is {
            is,
            behaviors,
            rift,
        } => {
            let behaviors = Some(match behaviors {
                Some(serde_json::Value::Object(mut obj)) => {
                    obj.entry("wait").or_insert(wait_val);
                    serde_json::Value::Object(obj)
                }
                Some(other) => other,
                None => serde_json::json!({ "wait": wait_val }),
            });
            StubResponse::Is {
                is,
                behaviors,
                rift,
            }
        }
        other => other,
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Predicate {
    #[serde(flatten)]
    pub parameters: PredicateParameters,
    #[serde(flatten)]
    pub operation: PredicateOperation,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum PredicateOperation {
    Equals(HashMap<String, serde_json::Value>),
    DeepEquals(HashMap<String, serde_json::Value>),
    Contains(HashMap<String, serde_json::Value>),
    StartsWith(HashMap<String, serde_json::Value>),
    EndsWith(HashMap<String, serde_json::Value>),
    Matches(HashMap<String, serde_json::Value>),
    Exists(HashMap<String, serde_json::Value>),
    Not(Box<Predicate>),
    Or(Vec<Predicate>),
    And(Vec<Predicate>),
    Inject(String),
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PredicateParameters {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub case_sensitive: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub key_case_sensitive: Option<bool>,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub except: String,
    #[serde(flatten)]
    pub selector: Option<PredicateSelector>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PredicateSelector {
    XPath {
        selector: String,
        #[serde(rename = "ns", default, skip_serializing_if = "Option::is_none")]
        namespaces: Option<HashMap<String, String>>,
    },
    JsonPath {
        selector: String,
    },
}

/// Response within a stub - wrapper type that handles various formats
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(from = "StubResponseRaw", into = "StubResponseOut")]
pub enum StubResponse {
    Is {
        is: IsResponse,
        #[serde(rename = "_behaviors", skip_serializing_if = "Option::is_none")]
        behaviors: Option<serde_json::Value>,
        #[serde(rename = "_rift", skip_serializing_if = "Option::is_none")]
        rift: Option<RiftResponseExtension>,
    },
    Proxy {
        proxy: ProxyResponse,
    },
    Inject {
        inject: String,
    },
    Fault {
        fault: String,
    },
    /// Rift script-only response (no `is` block, response generated by script)
    RiftScript {
        rift: RiftResponseExtension,
    },
}

/// Raw deserialization type that handles multiple JSON formats for stub responses
/// Supports:
/// - Standard Mountebank format with `is`, `proxy`, `inject`, or `fault` fields
/// - Formats with `behaviors` (without underscore) or `_behaviors`
/// - Formats with `proxy: null` alongside `is` (ignored)
/// - `statusCode` as either string or number
/// - Rift extensions via `_rift` field
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct StubResponseRaw {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is: Option<IsResponseRaw>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub proxy: Option<ProxyResponse>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inject: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fault: Option<String>,
    /// Mountebank-style behaviors (with underscore prefix) - for deserialization
    #[serde(rename = "_behaviors", skip_serializing_if = "Option::is_none")]
    pub underscore_behaviors: Option<serde_json::Value>,
    /// Alternative behaviors field (without underscore, used by some tools) - for deserialization
    #[serde(skip_serializing_if = "Option::is_none")]
    pub behaviors: Option<serde_json::Value>,
    /// Rift extensions for advanced features
    #[serde(rename = "_rift", skip_serializing_if = "Option::is_none")]
    pub rift: Option<RiftResponseExtension>,
}

/// Serialization type for stub responses - outputs Mountebank-compatible format
/// Uses `behaviors` as array (Mountebank standard format)
/// Field ordering matches Mountebank: behaviors, is, proxy
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct StubResponseOut {
    /// Mountebank-style behaviors as array (standard Mountebank output format)
    /// Placed first to match Mountebank output ordering
    #[serde(skip_serializing_if = "Option::is_none")]
    pub behaviors: Option<Vec<serde_json::Value>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is: Option<IsResponseOut>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub proxy: Option<ProxyResponse>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inject: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fault: Option<String>,
    /// Rift extensions for advanced features
    #[serde(rename = "_rift", skip_serializing_if = "Option::is_none")]
    pub rift: Option<RiftResponseExtension>,
}

/// Raw IsResponse that handles statusCode as string or number (for deserialization)
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct IsResponseRaw {
    #[serde(
        default = "default_status_code",
        deserialize_with = "deserialize_status_code"
    )]
    pub status_code: u16,
    #[serde(default)]
    pub headers: HashMap<String, String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<serde_json::Value>,
    /// Response mode: "text" (default) or "binary" (body is base64-encoded)
    #[serde(rename = "_mode", default)]
    pub mode: ResponseMode,
}

/// IsResponse for serialization - outputs statusCode as string (Mountebank format)
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct IsResponseOut {
    /// Status code serialized as string for Mountebank compatibility
    #[serde(serialize_with = "serialize_status_code_as_string")]
    pub status_code: u16,
    #[serde(default)]
    pub headers: HashMap<String, String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<serde_json::Value>,
    /// Response mode: "text" (default) or "binary" (body is base64-encoded)
    /// Skipped when text (default) as Mountebank doesn't output it for text mode
    #[serde(rename = "_mode", default, skip_serializing_if = "is_text_mode")]
    pub mode: ResponseMode,
}

/// Serialize statusCode as a string for Mountebank compatibility
fn serialize_status_code_as_string<S>(status_code: &u16, serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    serializer.serialize_str(&status_code.to_string())
}

pub(crate) fn default_status_code() -> u16 {
    200
}

/// Deserialize statusCode from either a number or a string
pub(crate) fn deserialize_status_code<'de, D>(deserializer: D) -> Result<u16, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::de::Error;
    let value = serde_json::Value::deserialize(deserializer)?;
    match value {
        serde_json::Value::Number(n) => n
            .as_u64()
            .and_then(|n| u16::try_from(n).ok())
            .ok_or_else(|| D::Error::custom("invalid status code number")),
        serde_json::Value::String(s) => s
            .parse::<u16>()
            .map_err(|_| D::Error::custom(format!("invalid status code string: {s}"))),
        _ => Err(D::Error::custom("statusCode must be a number or string")),
    }
}

impl From<StubResponseRaw> for StubResponse {
    fn from(raw: StubResponseRaw) -> Self {
        // Priority: is > proxy > inject > fault > rift-script-only
        if let Some(is_raw) = raw.is {
            // Merge behaviors: prefer _behaviors, fall back to behaviors
            let behaviors = raw.underscore_behaviors.or_else(|| {
                // Convert array format to object format if needed
                raw.behaviors.and_then(normalize_behaviors)
            });
            StubResponse::Is {
                is: IsResponse {
                    status_code: is_raw.status_code,
                    headers: is_raw.headers,
                    body: is_raw.body,
                    mode: is_raw.mode,
                },
                behaviors,
                rift: raw.rift,
            }
        } else if let Some(proxy) = raw.proxy {
            StubResponse::Proxy { proxy }
        } else if let Some(inject) = raw.inject {
            StubResponse::Inject { inject }
        } else if let Some(fault) = raw.fault {
            StubResponse::Fault { fault }
        } else if let Some(rift) = raw.rift {
            // Rift-only response (script generates the response)
            StubResponse::RiftScript { rift }
        } else {
            // Default to empty Is response
            StubResponse::Is {
                is: IsResponse {
                    status_code: 200,
                    headers: HashMap::new(),
                    body: None,
                    mode: ResponseMode::Text,
                },
                behaviors: None,
                rift: None,
            }
        }
    }
}

impl From<StubResponse> for StubResponseOut {
    fn from(response: StubResponse) -> Self {
        match response {
            StubResponse::Is {
                is,
                behaviors,
                rift,
            } => StubResponseOut {
                is: Some(IsResponseOut {
                    status_code: is.status_code,
                    headers: is.headers,
                    body: is.body,
                    mode: is.mode,
                }),
                proxy: None,
                inject: None,
                fault: None,
                // Convert behaviors object to array format for Mountebank compatibility
                behaviors: behaviors.and_then(behaviors_to_array),
                rift,
            },
            StubResponse::Proxy { proxy } => StubResponseOut {
                is: None,
                proxy: Some(proxy),
                inject: None,
                fault: None,
                behaviors: None,
                rift: None,
            },
            StubResponse::Inject { inject } => StubResponseOut {
                is: None,
                proxy: None,
                inject: Some(inject),
                fault: None,
                behaviors: None,
                rift: None,
            },
            StubResponse::Fault { fault } => StubResponseOut {
                is: None,
                proxy: None,
                inject: None,
                fault: Some(fault),
                behaviors: None,
                rift: None,
            },
            StubResponse::RiftScript { rift } => StubResponseOut {
                is: None,
                proxy: None,
                inject: None,
                fault: None,
                behaviors: None,
                rift: Some(rift),
            },
        }
    }
}

/// Convert behaviors from object format to array format for Mountebank compatibility
/// Mountebank outputs: `"behaviors": [{"wait": ...}, {"decorate": ...}]`
/// Rift internally stores as object: `{"wait": ..., "decorate": ...}`
fn behaviors_to_array(value: serde_json::Value) -> Option<Vec<serde_json::Value>> {
    match value {
        serde_json::Value::Object(obj) => {
            if obj.is_empty() {
                None
            } else {
                // Convert each key-value pair to a separate object in the array
                let arr: Vec<serde_json::Value> = obj
                    .into_iter()
                    .map(|(k, v)| {
                        let mut m = serde_json::Map::new();
                        m.insert(k, v);
                        serde_json::Value::Object(m)
                    })
                    .collect();
                Some(arr)
            }
        }
        serde_json::Value::Array(arr) => {
            if arr.is_empty() {
                None
            } else {
                Some(arr)
            }
        }
        _ => None,
    }
}

/// Normalize behaviors from array format to object format
/// Some tools use `behaviors: [{"wait": ...}, {"decorate": ...}]` instead of
/// `_behaviors: {"wait": ..., "decorate": ...}`
pub(crate) fn normalize_behaviors(value: serde_json::Value) -> Option<serde_json::Value> {
    match value {
        serde_json::Value::Array(arr) => {
            // Convert array of behavior objects to a single merged object
            let mut merged = serde_json::Map::new();
            for item in arr {
                if let serde_json::Value::Object(obj) = item {
                    for (k, v) in obj {
                        merged.insert(k, v);
                    }
                }
            }
            if merged.is_empty() {
                None
            } else {
                Some(serde_json::Value::Object(merged))
            }
        }
        serde_json::Value::Object(_) => Some(value),
        _ => None,
    }
}

/// Response mode for body handling (Mountebank compatible)
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum ResponseMode {
    /// Body is UTF-8 text (default)
    #[default]
    Text,
    /// Body is base64-encoded binary data
    Binary,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct IsResponse {
    #[serde(default = "default_status_code")]
    pub status_code: u16,
    #[serde(default)]
    pub headers: HashMap<String, String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<serde_json::Value>,
    /// Response mode: "text" (default) or "binary" (body is base64-encoded)
    #[serde(rename = "_mode", default, skip_serializing_if = "is_text_mode")]
    pub mode: ResponseMode,
}

fn is_text_mode(mode: &ResponseMode) -> bool {
    *mode == ResponseMode::Text
}

/// Path rewrite configuration for proxy responses (Mountebank compatible)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PathRewrite {
    /// Pattern to match in the path (string to replace)
    pub from: String,
    /// Replacement string
    pub to: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProxyResponse {
    pub to: String,
    #[serde(default)]
    pub mode: String,
    #[serde(default)]
    pub predicate_generators: Vec<serde_json::Value>,
    #[serde(default)]
    pub add_wait_behavior: bool,
    #[serde(default)]
    pub inject_headers: HashMap<String, String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub add_decorate_behavior: Option<String>,
    /// Path rewrite configuration for transforming the request path before proxying
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path_rewrite: Option<PathRewrite>,
}

// ============================================================================
// Imposter Config
// ============================================================================

fn default_protocol() -> String {
    "http".to_string()
}

/// Configuration for creating an imposter
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ImposterConfig {
    /// Port for the imposter. If not specified, an available port will be auto-assigned.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub port: Option<u16>,
    /// Host/IP address to bind the imposter to. Defaults to "0.0.0.0" (all interfaces).
    /// Use "127.0.0.1" or "localhost" for local-only access.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub host: Option<String>,
    #[serde(default = "default_protocol")]
    pub protocol: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(default)]
    pub record_requests: bool,
    /// Record which stub matched each request (Mountebank compatible)
    #[serde(default)]
    pub record_matches: bool,
    #[serde(default)]
    pub stubs: Vec<Stub>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default_response: Option<IsResponse>,
    /// Allow CORS headers (Mountebank compatible)
    #[serde(
        default,
        skip_serializing_if = "std::ops::Not::not",
        alias = "allowCORS"
    )]
    pub allow_cors: bool,
    /// Service name for documentation (optional metadata)
    #[serde(skip_serializing_if = "Option::is_none", alias = "service_name")]
    pub service_name: Option<String>,
    /// Service info for documentation (optional metadata, stored as-is)
    #[serde(skip_serializing_if = "Option::is_none", alias = "service_info")]
    pub service_info: Option<serde_json::Value>,
    /// Rift extensions for advanced features (flow state, scripting, faults)
    #[serde(rename = "_rift", default, skip_serializing_if = "Option::is_none")]
    pub rift: Option<RiftConfig>,
}

// ============================================================================
// Rift Extension Types (_rift namespace)
// ============================================================================

/// Top-level Rift configuration block for imposters
/// Extends Mountebank format with advanced features while maintaining backward compatibility
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct RiftConfig {
    /// Flow state configuration (enables stateful scripting)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub flow_state: Option<RiftFlowStateConfig>,
    /// Metrics configuration
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metrics: Option<RiftMetricsConfig>,
    /// Proxy/upstream configuration
    #[serde(skip_serializing_if = "Option::is_none")]
    pub proxy: Option<RiftProxyConfig>,
    /// Global script engine configuration
    #[serde(skip_serializing_if = "Option::is_none")]
    pub script_engine: Option<RiftScriptEngineConfig>,
}

/// Flow state configuration for Rift extensions
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RiftFlowStateConfig {
    /// Backend type: "inmemory" or "redis"
    #[serde(default = "default_flow_backend")]
    pub backend: String,
    /// Default TTL for state entries in seconds
    #[serde(default = "default_flow_ttl")]
    pub ttl_seconds: i64,
    /// Redis configuration (required when backend is "redis")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub redis: Option<RiftRedisConfig>,
    /// Mountebank state mapping configuration
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mountebank_state_mapping: Option<MountebankStateMapping>,
}

fn default_flow_backend() -> String {
    "inmemory".to_string()
}

fn default_flow_ttl() -> i64 {
    300
}

impl Default for RiftFlowStateConfig {
    fn default() -> Self {
        Self {
            backend: default_flow_backend(),
            ttl_seconds: default_flow_ttl(),
            redis: None,
            mountebank_state_mapping: None,
        }
    }
}

/// Redis configuration for flow state
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RiftRedisConfig {
    /// Redis connection URL
    pub url: String,
    /// Connection pool size
    #[serde(default = "default_redis_pool")]
    pub pool_size: usize,
    /// Key prefix for all flow state keys
    #[serde(default = "default_redis_prefix")]
    pub key_prefix: String,
}

fn default_redis_pool() -> usize {
    10
}

fn default_redis_prefix() -> String {
    "rift:".to_string()
}

/// Configuration for bridging Mountebank state to flow store
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MountebankStateMapping {
    /// Enable state mapping
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Source for flow_id: "imposter_port" or "header:X-Header-Name"
    #[serde(default = "default_flow_id_source")]
    pub flow_id_source: String,
}

fn default_true() -> bool {
    true
}

fn default_flow_id_source() -> String {
    "imposter_port".to_string()
}

/// Metrics configuration for Rift extensions
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RiftMetricsConfig {
    /// Enable metrics collection
    #[serde(default)]
    pub enabled: bool,
    /// Metrics server port
    #[serde(default = "default_metrics_port")]
    pub port: u16,
}

fn default_metrics_port() -> u16 {
    9090
}

/// Proxy configuration for Rift extensions
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RiftProxyConfig {
    /// Upstream target configuration
    #[serde(skip_serializing_if = "Option::is_none")]
    pub upstream: Option<RiftUpstreamConfig>,
    /// Connection pool settings
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connection_pool: Option<RiftConnectionPoolConfig>,
}

/// Upstream configuration for Rift proxy
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RiftUpstreamConfig {
    pub host: String,
    pub port: u16,
    #[serde(default = "default_upstream_protocol")]
    pub protocol: String,
}

fn default_upstream_protocol() -> String {
    "http".to_string()
}

/// Connection pool configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RiftConnectionPoolConfig {
    #[serde(default = "default_max_idle")]
    pub max_idle_per_host: usize,
    #[serde(default = "default_idle_timeout")]
    pub idle_timeout_secs: u64,
}

fn default_max_idle() -> usize {
    100
}

fn default_idle_timeout() -> u64 {
    90
}

/// Global script engine configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RiftScriptEngineConfig {
    /// Default script engine: "rhai", "lua", or "javascript"
    #[serde(default = "default_script_engine")]
    pub default_engine: String,
    /// Script execution timeout in milliseconds
    #[serde(default = "default_script_timeout")]
    pub timeout_ms: u64,
}

fn default_script_engine() -> String {
    "rhai".to_string()
}

fn default_script_timeout() -> u64 {
    5000
}

/// Rift response extensions (added to stub responses)
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct RiftResponseExtension {
    /// Fault injection configuration
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fault: Option<RiftFaultConfig>,
    /// Script-based response generation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub script: Option<RiftScriptConfig>,
}

/// Fault injection configuration for responses
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct RiftFaultConfig {
    /// Latency injection
    #[serde(skip_serializing_if = "Option::is_none")]
    pub latency: Option<RiftLatencyFault>,
    /// Error injection
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<RiftErrorFault>,
    /// TCP-level fault
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tcp: Option<String>,
}

/// Latency fault configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RiftLatencyFault {
    /// Probability of fault injection (0.0 to 1.0)
    #[serde(default = "default_probability")]
    pub probability: f64,
    /// Minimum latency in milliseconds
    #[serde(default)]
    pub min_ms: u64,
    /// Maximum latency in milliseconds
    #[serde(default)]
    pub max_ms: u64,
    /// Fixed latency (alternative to min/max)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ms: Option<u64>,
}

fn default_probability() -> f64 {
    1.0
}

/// Error fault configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RiftErrorFault {
    /// Probability of error injection (0.0 to 1.0)
    #[serde(default = "default_probability")]
    pub probability: f64,
    /// HTTP status code for error response
    #[serde(default = "default_error_status")]
    pub status: u16,
    /// Response body for error
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,
    /// Custom headers for error response
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub headers: HashMap<String, String>,
}

fn default_error_status() -> u16 {
    503
}

/// Script configuration for response generation
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RiftScriptConfig {
    /// Script engine: "rhai", "lua", or "javascript"
    #[serde(default = "default_script_engine")]
    pub engine: String,
    /// Inline script code
    pub code: String,
}

// ============================================================================
// Error Types
// ============================================================================

/// Error types for imposter management
#[derive(Debug, thiserror::Error)]
pub enum ImposterError {
    #[error("Port {0} is already in use")]
    PortInUse(u16),
    #[error("Imposter not found on port {0}")]
    NotFound(u16),
    #[error("Failed to bind port {0}: {1}")]
    BindError(u16, String),
    #[error("Invalid protocol: {0}")]
    InvalidProtocol(String),
    #[error("Stub index {0} out of bounds")]
    StubIndexOutOfBounds(usize),
    #[error("Failed to persist imposter: {0}")]
    PersistError(String),
}

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

    // Fix #107: Stub.responses now has #[serde(default)]
    #[test]
    fn test_stub_deserialize_without_responses_field() {
        let stub_json = json!({
            "predicates": [{ "equals": { "path": "/test" } }]
        });

        let result: Result<Stub, _> = serde_json::from_value(stub_json);

        assert!(
            result.is_ok(),
            "Stub without responses field should deserialize with empty responses vec"
        );
        assert!(result.unwrap().responses.is_empty());
    }

    #[test]
    fn test_stub_rules_alias_for_predicates() {
        let stub_json = json!({
            "rules": [{ "equals": { "path": "/test" } }],
            "responses": [{ "is": { "statusCode": 200 } }]
        });
        let stub: Stub = serde_json::from_value(stub_json).unwrap();
        assert_eq!(stub.predicates.len(), 1);
    }

    #[test]
    fn test_stub_predicates_takes_precedence_over_rules() {
        let stub_json = json!({
            "predicates": [{ "equals": { "path": "/a" } }],
            "rules": [{ "equals": { "path": "/b" } }, { "equals": { "path": "/c" } }],
            "responses": []
        });
        let stub: Stub = serde_json::from_value(stub_json).unwrap();
        assert_eq!(stub.predicates.len(), 1);
    }

    #[test]
    fn test_stub_delay_range_injected_as_wait() {
        let stub_json = json!({
            "predicates": [],
            "delayRange": [{ "min": "50", "max": "100" }],
            "responses": [{ "is": { "statusCode": 200 } }]
        });
        let stub: Stub = serde_json::from_value(stub_json).unwrap();
        assert_eq!(stub.responses.len(), 1);
        if let StubResponse::Is { behaviors, .. } = &stub.responses[0] {
            let wait = behaviors.as_ref().unwrap().get("wait").unwrap();
            // min != max → range object
            assert_eq!(wait.get("min").unwrap(), &json!(50u64));
            assert_eq!(wait.get("max").unwrap(), &json!(100u64));
        } else {
            panic!("expected Is response");
        }
    }

    #[test]
    fn test_stub_delay_range_fixed_when_min_equals_max() {
        let stub_json = json!({
            "predicates": [],
            "delayRange": [{ "min": 0, "max": 0 }],
            "responses": [{ "is": { "statusCode": 200 } }]
        });
        let stub: Stub = serde_json::from_value(stub_json).unwrap();
        if let StubResponse::Is { behaviors, .. } = &stub.responses[0] {
            let wait = behaviors.as_ref().unwrap().get("wait").unwrap();
            assert_eq!(wait, &json!(0u64));
        } else {
            panic!("expected Is response");
        }
    }

    #[test]
    fn test_stub_recorded_from_roundtrip() {
        let stub_json = json!({
            "predicates": [],
            "responses": [],
            "recordedFrom": "http://upstream:8080"
        });
        let stub: Stub = serde_json::from_value(stub_json).unwrap();
        assert_eq!(stub.recorded_from.as_deref(), Some("http://upstream:8080"));
        let serialized = serde_json::to_value(&stub).unwrap();
        assert_eq!(serialized["recordedFrom"], json!("http://upstream:8080"));
    }
}