mockforge-core 0.3.115

Shared logic for MockForge - routing, validation, latency, proxy
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
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
//! Protocol-agnostic abstractions for unified mocking across HTTP, GraphQL, gRPC, and WebSocket
//!
//! This module provides traits and types that abstract common patterns across different
//! protocols, enabling code reuse for spec-driven mocking, middleware, and request matching.

pub mod auth;
pub mod base_registry;
pub mod matcher;
pub mod middleware;
pub mod protocol_registry;
pub mod streaming;

use crate::Result;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;

// Re-export middleware types
pub use auth::{AuthMiddleware, AuthResult, Claims};
pub use base_registry::{BaseSpecRegistry, ProtocolFixture};
pub use matcher::{FuzzyRequestMatcher, RequestFingerprint, SimpleRequestMatcher};
pub use middleware::{LatencyMiddleware, LoggingMiddleware, MetricsMiddleware};
pub use protocol_registry::{ProtocolHandler, ProtocolRegistry};
pub use streaming::{
    MessageBuilder, MessageStream, ProtocolMessage, StreamingMetadata, StreamingProtocol,
    StreamingProtocolRegistry,
};

/// Protocol type enumeration for multi-protocol support
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum Protocol {
    /// HTTP/REST protocol for RESTful APIs
    Http,
    /// GraphQL protocol for GraphQL APIs
    GraphQL,
    /// gRPC protocol for gRPC services
    Grpc,
    /// WebSocket protocol for real-time bidirectional communication
    WebSocket,
    /// SMTP/Email protocol for email communication
    Smtp,
    /// MQTT protocol for IoT messaging and pub/sub
    Mqtt,
    /// FTP protocol for file transfer operations
    Ftp,
    /// Kafka protocol for distributed event streaming
    Kafka,
    /// RabbitMQ/AMQP protocol for message queuing
    RabbitMq,
    /// AMQP protocol for advanced message queuing scenarios
    Amqp,
    /// TCP protocol for raw TCP connections
    Tcp,
}

impl fmt::Display for Protocol {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Protocol::Http => write!(f, "HTTP"),
            Protocol::GraphQL => write!(f, "GraphQL"),
            Protocol::Grpc => write!(f, "gRPC"),
            Protocol::WebSocket => write!(f, "WebSocket"),
            Protocol::Smtp => write!(f, "SMTP"),
            Protocol::Mqtt => write!(f, "MQTT"),
            Protocol::Ftp => write!(f, "FTP"),
            Protocol::Kafka => write!(f, "Kafka"),
            Protocol::RabbitMq => write!(f, "RabbitMQ"),
            Protocol::Amqp => write!(f, "AMQP"),
            Protocol::Tcp => write!(f, "TCP"),
        }
    }
}

/// Message pattern enumeration for different communication patterns
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum MessagePattern {
    /// Request-Response pattern (HTTP, gRPC unary)
    RequestResponse,
    /// One-way/fire-and-forget pattern (MQTT publish, email)
    OneWay,
    /// Publish-Subscribe pattern (Kafka, RabbitMQ, MQTT)
    PubSub,
    /// Streaming pattern (gRPC streaming, WebSocket)
    Streaming,
}

impl fmt::Display for MessagePattern {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MessagePattern::RequestResponse => write!(f, "Request-Response"),
            MessagePattern::OneWay => write!(f, "One-Way"),
            MessagePattern::PubSub => write!(f, "Pub-Sub"),
            MessagePattern::Streaming => write!(f, "Streaming"),
        }
    }
}

/// A protocol-agnostic request representation
#[derive(Debug, Clone)]
pub struct ProtocolRequest {
    /// The protocol this request uses
    pub protocol: Protocol,
    /// Message pattern for this request
    pub pattern: MessagePattern,
    /// Method or operation (e.g., "GET", "Query.users", "greeter.SayHello")
    pub operation: String,
    /// Path, query name, or service/method name
    pub path: String,
    /// Topic for pub/sub protocols (MQTT, Kafka)
    pub topic: Option<String>,
    /// Routing key for message queuing protocols (AMQP, RabbitMQ)
    pub routing_key: Option<String>,
    /// Partition for partitioned protocols (Kafka)
    pub partition: Option<i32>,
    /// Quality of Service level (MQTT: 0, 1, 2)
    pub qos: Option<u8>,
    /// Request metadata (headers, metadata, etc.)
    pub metadata: HashMap<String, String>,
    /// Request body/payload as bytes
    pub body: Option<Vec<u8>>,
    /// Client IP address if available
    pub client_ip: Option<String>,
}

impl Default for ProtocolRequest {
    fn default() -> Self {
        Self {
            protocol: Protocol::Http,
            pattern: MessagePattern::RequestResponse,
            operation: String::new(),
            path: String::new(),
            topic: None,
            routing_key: None,
            partition: None,
            qos: None,
            metadata: HashMap::new(),
            body: None,
            client_ip: None,
        }
    }
}

/// A protocol-agnostic response representation
#[derive(Debug, Clone)]
pub struct ProtocolResponse {
    /// Status code or success indicator (HTTP: 200, gRPC: OK, GraphQL: no errors)
    pub status: ResponseStatus,
    /// Response metadata (headers, metadata, etc.)
    pub metadata: HashMap<String, String>,
    /// Response body/payload
    pub body: Vec<u8>,
    /// Content type or serialization format
    pub content_type: String,
}

/// Response status abstraction across protocols
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResponseStatus {
    /// HTTP status code
    HttpStatus(u16),
    /// gRPC status code
    GrpcStatus(i32),
    /// GraphQL success (true) or error (false)
    GraphQLStatus(bool),
    /// WebSocket status
    WebSocketStatus(bool),
    /// SMTP status code (2xx = success, 4xx/5xx = error)
    SmtpStatus(u16),
    /// MQTT status (true = success, false = error)
    MqttStatus(bool),
    /// Kafka status code (0 = success, non-zero = error)
    KafkaStatus(i16),
    /// AMQP/RabbitMQ status code
    AmqpStatus(u16),
    /// FTP status code
    FtpStatus(u16),
    /// TCP status (true = success, false = error/close)
    TcpStatus(bool),
}

impl ResponseStatus {
    /// Check if the response is successful
    pub fn is_success(&self) -> bool {
        match self {
            ResponseStatus::HttpStatus(code) => (200..300).contains(code),
            ResponseStatus::GrpcStatus(code) => *code == 0, // gRPC OK = 0
            ResponseStatus::GraphQLStatus(success) => *success,
            ResponseStatus::WebSocketStatus(success) => *success,
            ResponseStatus::SmtpStatus(code) => (200..300).contains(code), // 2xx codes are success
            ResponseStatus::MqttStatus(success) => *success,
            ResponseStatus::KafkaStatus(code) => *code == 0, // Kafka OK = 0
            ResponseStatus::AmqpStatus(code) => (200..300).contains(code), // AMQP success codes
            ResponseStatus::FtpStatus(code) => (200..300).contains(code), // FTP success codes
            ResponseStatus::TcpStatus(success) => *success,  // TCP success flag
        }
    }

    /// Get numeric representation if applicable
    pub fn as_code(&self) -> Option<i32> {
        match self {
            ResponseStatus::HttpStatus(code) => Some(*code as i32),
            ResponseStatus::GrpcStatus(code) => Some(*code),
            ResponseStatus::SmtpStatus(code) => Some(*code as i32),
            ResponseStatus::KafkaStatus(code) => Some(*code as i32),
            ResponseStatus::AmqpStatus(code) => Some(*code as i32),
            ResponseStatus::FtpStatus(code) => Some(*code as i32),
            ResponseStatus::TcpStatus(_) => None, // TCP uses boolean status
            ResponseStatus::GraphQLStatus(_)
            | ResponseStatus::WebSocketStatus(_)
            | ResponseStatus::MqttStatus(_) => None,
        }
    }
}

/// Trait for spec-driven mocking registries (OpenAPI, GraphQL schema, Proto files)
pub trait SpecRegistry: Send + Sync {
    /// Get the protocol this registry handles
    fn protocol(&self) -> Protocol;

    /// Get all available operations/routes in this spec
    fn operations(&self) -> Vec<SpecOperation>;

    /// Find an operation by path/name
    fn find_operation(&self, operation: &str, path: &str) -> Option<SpecOperation>;

    /// Validate a request against the spec
    fn validate_request(&self, request: &ProtocolRequest) -> Result<ValidationResult>;

    /// Generate a mock response for a request
    fn generate_mock_response(&self, request: &ProtocolRequest) -> Result<ProtocolResponse>;
}

/// Represents a single operation in a spec (endpoint, query, RPC method)
#[derive(Debug, Clone)]
pub struct SpecOperation {
    /// Operation name or identifier
    pub name: String,
    /// Path or fully qualified name
    pub path: String,
    /// Operation type (GET, POST, Query, Mutation, RPC)
    pub operation_type: String,
    /// Input schema/type information
    pub input_schema: Option<String>,
    /// Output schema/type information
    pub output_schema: Option<String>,
    /// Metadata from spec
    pub metadata: HashMap<String, String>,
}

/// Result of request validation
#[derive(Debug, Clone)]
pub struct ValidationResult {
    /// Whether validation passed
    pub valid: bool,
    /// Validation errors if any
    pub errors: Vec<ValidationError>,
    /// Validation warnings
    pub warnings: Vec<String>,
}

/// A validation error
#[derive(Debug, Clone)]
pub struct ValidationError {
    /// Error message
    pub message: String,
    /// Path to the error (e.g., "body.user.email")
    pub path: Option<String>,
    /// Error code
    pub code: Option<String>,
}

impl ValidationResult {
    /// Create a successful validation result
    pub fn success() -> Self {
        Self {
            valid: true,
            errors: Vec::new(),
            warnings: Vec::new(),
        }
    }

    /// Create a failed validation result with errors
    pub fn failure(errors: Vec<ValidationError>) -> Self {
        Self {
            valid: false,
            errors,
            warnings: Vec::new(),
        }
    }

    /// Add a warning to the result
    pub fn with_warning(mut self, warning: String) -> Self {
        self.warnings.push(warning);
        self
    }
}

/// Result of middleware request processing
///
/// Allows middleware to either continue the chain or short-circuit with a response
/// (e.g., auth middleware rejecting an unauthenticated request with a 401).
#[derive(Debug)]
pub enum MiddlewareAction {
    /// Continue processing the next middleware in the chain
    Continue,
    /// Stop the chain and return this response immediately
    ShortCircuit(ProtocolResponse),
}

/// Trait for protocol-agnostic middleware
#[async_trait::async_trait]
pub trait ProtocolMiddleware: Send + Sync {
    /// Get the name of this middleware
    fn name(&self) -> &str;

    /// Process a request before it reaches the handler
    ///
    /// Returns `MiddlewareAction::Continue` to pass the request to the next middleware,
    /// or `MiddlewareAction::ShortCircuit(response)` to stop the chain and return early.
    async fn process_request(&self, request: &mut ProtocolRequest) -> Result<MiddlewareAction>;

    /// Process a response before it's returned to the client
    async fn process_response(
        &self,
        request: &ProtocolRequest,
        response: &mut ProtocolResponse,
    ) -> Result<()>;

    /// Check if this middleware should run for a given protocol
    fn supports_protocol(&self, protocol: Protocol) -> bool;
}

/// Trait for request matching across protocols
pub trait RequestMatcher: Send + Sync {
    /// Match a request and return a score (higher = better match)
    fn match_score(&self, request: &ProtocolRequest) -> f64;

    /// Get the protocol this matcher handles
    fn protocol(&self) -> Protocol;
}

/// Unified fixture format supporting all protocols
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UnifiedFixture {
    /// Unique identifier for this fixture
    pub id: String,

    /// Human-readable name
    pub name: String,

    /// Description of what this fixture does
    #[serde(default)]
    pub description: String,

    /// Protocol this fixture applies to
    pub protocol: Protocol,

    /// Request matching criteria
    pub request: FixtureRequest,

    /// Response configuration
    pub response: FixtureResponse,

    /// Additional metadata
    #[serde(default)]
    pub metadata: HashMap<String, serde_json::Value>,

    /// Whether this fixture is enabled
    #[serde(default = "default_true")]
    pub enabled: bool,

    /// Priority for matching (higher = matched first)
    #[serde(default)]
    pub priority: i32,

    /// Tags for organization
    #[serde(default)]
    pub tags: Vec<String>,
}

/// Request matching criteria for fixtures
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FixtureRequest {
    /// Message pattern to match
    #[serde(default)]
    pub pattern: Option<MessagePattern>,

    /// Operation/method to match (exact or regex)
    pub operation: Option<String>,

    /// Path/route to match (exact or regex)
    pub path: Option<String>,

    /// Topic to match (for pub/sub protocols)
    pub topic: Option<String>,

    /// Routing key to match (for message queuing)
    pub routing_key: Option<String>,

    /// Partition to match
    pub partition: Option<i32>,

    /// QoS level to match
    pub qos: Option<u8>,

    /// Headers/metadata to match (key-value pairs)
    #[serde(default)]
    pub headers: HashMap<String, String>,

    /// Request body pattern (regex for text, or exact match)
    pub body_pattern: Option<String>,

    /// Custom matching logic (script or expression)
    pub custom_matcher: Option<String>,
}

/// Response configuration for fixtures
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FixtureResponse {
    /// Response status
    pub status: FixtureStatus,

    /// Response headers
    #[serde(default)]
    pub headers: HashMap<String, String>,

    /// Response body (can be string, JSON, or base64-encoded binary)
    pub body: Option<serde_json::Value>,

    /// Content type
    pub content_type: Option<String>,

    /// Response delay in milliseconds
    #[serde(default)]
    pub delay_ms: u64,

    /// Template variables for dynamic responses
    #[serde(default)]
    pub template_vars: HashMap<String, serde_json::Value>,
}

/// Status representation for fixtures
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum FixtureStatus {
    /// HTTP status code
    Http(u16),
    /// gRPC status code
    Grpc(i32),
    /// Generic success/failure
    Generic(bool),
    /// Custom status with code and message
    Custom {
        /// Custom status code
        code: i32,
        /// Custom status message
        message: String,
    },
}

fn default_true() -> bool {
    true
}

impl UnifiedFixture {
    /// Check if this fixture matches the given protocol request
    pub fn matches(&self, request: &ProtocolRequest) -> bool {
        // Check protocol
        if request.protocol != self.protocol {
            return false;
        }

        // Check pattern
        if let Some(pattern) = &self.request.pattern {
            if request.pattern != *pattern {
                return false;
            }
        }

        // Check operation
        if let Some(operation) = &self.request.operation {
            if !self.matches_pattern(&request.operation, operation) {
                return false;
            }
        }

        // Check path
        if let Some(path) = &self.request.path {
            if !self.matches_pattern(&request.path, path) {
                return false;
            }
        }

        // Check topic
        if let Some(topic) = &self.request.topic {
            if !self.matches_pattern(request.topic.as_ref().unwrap_or(&String::new()), topic) {
                return false;
            }
        }

        // Check routing key
        if let Some(routing_key) = &self.request.routing_key {
            if !self.matches_pattern(
                request.routing_key.as_ref().unwrap_or(&String::new()),
                routing_key,
            ) {
                return false;
            }
        }

        // Check partition
        if let Some(partition) = self.request.partition {
            if request.partition != Some(partition) {
                return false;
            }
        }

        // Check QoS
        if let Some(qos) = self.request.qos {
            if request.qos != Some(qos) {
                return false;
            }
        }

        // Check headers
        for (key, expected_value) in &self.request.headers {
            if let Some(actual_value) = request.metadata.get(key) {
                if !self.matches_pattern(actual_value, expected_value) {
                    return false;
                }
            } else {
                return false;
            }
        }

        // Check body pattern
        if let Some(pattern) = &self.request.body_pattern {
            if let Some(body) = &request.body {
                let body_str = String::from_utf8_lossy(body);
                if !self.matches_pattern(&body_str, pattern) {
                    return false;
                }
            } else {
                return false;
            }
        }

        // Check custom matcher logic
        if let Some(custom_matcher) = &self.request.custom_matcher {
            if !self.evaluate_custom_matcher(custom_matcher, request) {
                return false;
            }
        }

        true
    }

    /// Helper method to match patterns (supports regex and exact match)
    fn matches_pattern(&self, value: &str, pattern: &str) -> bool {
        use regex::Regex;

        // Try regex first
        if let Ok(re) = Regex::new(pattern) {
            re.is_match(value)
        } else {
            // Fall back to exact match
            value == pattern
        }
    }

    /// Evaluate custom matcher expression
    fn evaluate_custom_matcher(&self, expression: &str, request: &ProtocolRequest) -> bool {
        // Simple expression evaluator for custom matching logic
        // Supports basic conditions like:
        // - operation == "GET"
        // - path =~ "/api/.*"
        // - headers.content-type == "application/json"
        // - body contains "test"

        let expr = expression.trim();

        // Handle different types of expressions
        if expr.contains("==") {
            self.evaluate_equality(expr, request)
        } else if expr.contains("=~") {
            self.evaluate_regex_match(expr, request)
        } else if expr.contains("contains") {
            self.evaluate_contains(expr, request)
        } else {
            // Unknown expression format, log warning and return false
            tracing::warn!("Unknown custom matcher expression format: {}", expr);
            false
        }
    }

    /// Evaluate equality expressions (field == "value")
    fn evaluate_equality(&self, expr: &str, request: &ProtocolRequest) -> bool {
        let parts: Vec<&str> = expr.split("==").map(|s| s.trim()).collect();
        if parts.len() != 2 {
            return false;
        }

        let field = parts[0];
        let expected_value = parts[1].trim_matches('"');

        match field {
            "operation" => request.operation == expected_value,
            "path" => request.path == expected_value,
            "topic" => request.topic.as_ref().unwrap_or(&String::new()) == expected_value,
            "routing_key" => {
                request.routing_key.as_ref().unwrap_or(&String::new()) == expected_value
            }
            _ if field.starts_with("headers.") => {
                let header_name = &field[8..]; // Remove "headers." prefix
                request.metadata.get(header_name).is_some_and(|v| v == expected_value)
            }
            _ => {
                tracing::warn!("Unknown field in equality expression: {}", field);
                false
            }
        }
    }

    /// Evaluate regex match expressions (field =~ "pattern")
    fn evaluate_regex_match(&self, expr: &str, request: &ProtocolRequest) -> bool {
        let parts: Vec<&str> = expr.split("=~").map(|s| s.trim()).collect();
        if parts.len() != 2 {
            return false;
        }

        let field = parts[0];
        let pattern = parts[1].trim_matches('"');

        let value: String = match field {
            "operation" => request.operation.clone(),
            "path" => request.path.clone(),
            "topic" => request.topic.clone().unwrap_or_default(),
            "routing_key" => request.routing_key.clone().unwrap_or_default(),
            _ if field.starts_with("headers.") => {
                let header_name = &field[8..]; // Remove "headers." prefix
                request.metadata.get(header_name).cloned().unwrap_or_default()
            }
            _ => {
                tracing::warn!("Unknown field in regex expression: {}", field);
                return false;
            }
        };

        use regex::Regex;
        match Regex::new(pattern) {
            Ok(re) => re.is_match(&value),
            Err(e) => {
                tracing::warn!("Invalid regex pattern '{}': {}", pattern, e);
                false
            }
        }
    }

    /// Evaluate contains expressions (field contains "substring")
    fn evaluate_contains(&self, expr: &str, request: &ProtocolRequest) -> bool {
        let parts: Vec<&str> = expr.split("contains").map(|s| s.trim()).collect();
        if parts.len() != 2 {
            return false;
        }

        let field = parts[0];
        let substring = parts[1].trim_matches('"');

        let value: String = match field {
            "body" => {
                if let Some(body) = &request.body {
                    String::from_utf8_lossy(body).to_string()
                } else {
                    return false;
                }
            }
            _ if field.starts_with("headers.") => {
                let header_name = &field[8..]; // Remove "headers." prefix
                request.metadata.get(header_name).cloned().unwrap_or_default()
            }
            _ => {
                tracing::warn!("Unsupported field for contains expression: {}", field);
                return false;
            }
        };

        value.contains(substring)
    }

    /// Convert fixture response to ProtocolResponse
    pub fn to_protocol_response(&self) -> Result<ProtocolResponse> {
        let status = match &self.response.status {
            FixtureStatus::Http(code) => ResponseStatus::HttpStatus(*code),
            FixtureStatus::Grpc(code) => ResponseStatus::GrpcStatus(*code),
            FixtureStatus::Generic(success) => ResponseStatus::GraphQLStatus(*success), // Using GraphQL as generic
            FixtureStatus::Custom { code, .. } => ResponseStatus::GrpcStatus(*code), // Using gRPC as custom
        };

        let body = match &self.response.body {
            Some(serde_json::Value::String(s)) => s.clone().into_bytes(),
            Some(value) => serde_json::to_string(value)?.into_bytes(),
            None => Vec::new(),
        };

        let content_type = self
            .response
            .content_type
            .clone()
            .unwrap_or_else(|| "application/json".to_string());

        Ok(ProtocolResponse {
            status,
            metadata: self.response.headers.clone(),
            body,
            content_type,
        })
    }
}

/// Middleware chain for composing and executing multiple middleware in sequence
pub struct MiddlewareChain {
    /// Ordered list of middleware to execute
    middleware: Vec<Arc<dyn ProtocolMiddleware>>,
}

impl MiddlewareChain {
    /// Create a new middleware chain
    pub fn new() -> Self {
        Self {
            middleware: Vec::new(),
        }
    }

    /// Add middleware to the chain
    pub fn with_middleware(mut self, middleware: Arc<dyn ProtocolMiddleware>) -> Self {
        self.middleware.push(middleware);
        self
    }

    /// Process a request through all middleware
    ///
    /// Returns `Ok(None)` if all middleware passed (continue to handler),
    /// or `Ok(Some(response))` if a middleware short-circuited the chain.
    pub async fn process_request(
        &self,
        request: &mut ProtocolRequest,
    ) -> Result<Option<ProtocolResponse>> {
        for middleware in &self.middleware {
            if middleware.supports_protocol(request.protocol) {
                match middleware.process_request(request).await? {
                    MiddlewareAction::Continue => {}
                    MiddlewareAction::ShortCircuit(response) => {
                        tracing::debug!(
                            middleware = middleware.name(),
                            "Middleware short-circuited request processing"
                        );
                        return Ok(Some(response));
                    }
                }
            }
        }
        Ok(None)
    }

    /// Process a response through all middleware (in reverse order)
    pub async fn process_response(
        &self,
        request: &ProtocolRequest,
        response: &mut ProtocolResponse,
    ) -> Result<()> {
        for middleware in self.middleware.iter().rev() {
            if middleware.supports_protocol(request.protocol) {
                middleware.process_response(request, response).await?;
            }
        }
        Ok(())
    }
}

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

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

    #[test]
    fn test_protocol_display() {
        assert_eq!(Protocol::Http.to_string(), "HTTP");
        assert_eq!(Protocol::GraphQL.to_string(), "GraphQL");
        assert_eq!(Protocol::Grpc.to_string(), "gRPC");
        assert_eq!(Protocol::WebSocket.to_string(), "WebSocket");
        assert_eq!(Protocol::Smtp.to_string(), "SMTP");
        assert_eq!(Protocol::Mqtt.to_string(), "MQTT");
        assert_eq!(Protocol::Ftp.to_string(), "FTP");
        assert_eq!(Protocol::Kafka.to_string(), "Kafka");
        assert_eq!(Protocol::RabbitMq.to_string(), "RabbitMQ");
        assert_eq!(Protocol::Amqp.to_string(), "AMQP");
        assert_eq!(Protocol::Tcp.to_string(), "TCP");
    }

    #[test]
    fn test_response_status_is_success() {
        assert!(ResponseStatus::HttpStatus(200).is_success());
        assert!(ResponseStatus::HttpStatus(204).is_success());
        assert!(!ResponseStatus::HttpStatus(404).is_success());
        assert!(!ResponseStatus::HttpStatus(500).is_success());

        assert!(ResponseStatus::GrpcStatus(0).is_success());
        assert!(!ResponseStatus::GrpcStatus(2).is_success());

        assert!(ResponseStatus::GraphQLStatus(true).is_success());
        assert!(!ResponseStatus::GraphQLStatus(false).is_success());
    }

    #[test]
    fn test_response_status_as_code() {
        assert_eq!(ResponseStatus::HttpStatus(200).as_code(), Some(200));
        assert_eq!(ResponseStatus::GrpcStatus(0).as_code(), Some(0));
        assert_eq!(ResponseStatus::GraphQLStatus(true).as_code(), None);
    }

    #[test]
    fn test_validation_result_success() {
        let result = ValidationResult::success();
        assert!(result.valid);
        assert_eq!(result.errors.len(), 0);
        assert_eq!(result.warnings.len(), 0);
    }

    #[test]
    fn test_validation_result_failure() {
        let errors = vec![ValidationError {
            message: "Invalid field".to_string(),
            path: Some("body.field".to_string()),
            code: Some("INVALID_FIELD".to_string()),
        }];
        let result = ValidationResult::failure(errors);
        assert!(!result.valid);
        assert_eq!(result.errors.len(), 1);
    }

    #[test]
    fn test_validation_result_with_warning() {
        let result = ValidationResult::success().with_warning("Deprecated field used".to_string());
        assert!(result.valid);
        assert_eq!(result.warnings.len(), 1);
    }

    #[test]
    fn test_middleware_chain_creation() {
        let chain = MiddlewareChain::new();
        assert_eq!(chain.middleware.len(), 0);
    }

    #[test]
    fn test_protocol_request_creation() {
        let request = ProtocolRequest {
            protocol: Protocol::Http,
            operation: "GET".to_string(),
            path: "/users".to_string(),
            client_ip: Some("127.0.0.1".to_string()),
            ..Default::default()
        };
        assert_eq!(request.protocol, Protocol::Http);
        assert_eq!(request.pattern, MessagePattern::RequestResponse);
        assert_eq!(request.operation, "GET");
        assert_eq!(request.path, "/users");
    }

    #[test]
    fn test_protocol_response_creation() {
        let response = ProtocolResponse {
            status: ResponseStatus::HttpStatus(200),
            metadata: HashMap::new(),
            body: b"{}".to_vec(),
            content_type: "application/json".to_string(),
        };
        assert!(response.status.is_success());
        assert_eq!(response.content_type, "application/json");
    }

    #[test]
    fn test_unified_fixture_matching() {
        let fixture = UnifiedFixture {
            id: "test-fixture".to_string(),
            name: "Test Fixture".to_string(),
            description: "A test fixture".to_string(),
            protocol: Protocol::Http,
            request: FixtureRequest {
                pattern: Some(MessagePattern::RequestResponse),
                operation: Some("GET".to_string()),
                path: Some("/api/users".to_string()),
                topic: None,
                routing_key: None,
                partition: None,
                qos: None,
                headers: HashMap::new(),
                body_pattern: None,
                custom_matcher: None,
            },
            response: FixtureResponse {
                status: FixtureStatus::Http(200),
                headers: HashMap::new(),
                body: Some(serde_json::json!({"users": ["john", "jane"]})),
                content_type: Some("application/json".to_string()),
                delay_ms: 0,
                template_vars: HashMap::new(),
            },
            metadata: HashMap::new(),
            enabled: true,
            priority: 0,
            tags: vec![],
        };

        let matching_request = ProtocolRequest {
            protocol: Protocol::Http,
            pattern: MessagePattern::RequestResponse,
            operation: "GET".to_string(),
            path: "/api/users".to_string(),
            topic: None,
            routing_key: None,
            partition: None,
            qos: None,
            metadata: HashMap::new(),
            body: None,
            client_ip: None,
        };

        let non_matching_request = ProtocolRequest {
            protocol: Protocol::Http,
            pattern: MessagePattern::RequestResponse,
            operation: "POST".to_string(),
            path: "/api/users".to_string(),
            topic: None,
            routing_key: None,
            partition: None,
            qos: None,
            metadata: HashMap::new(),
            body: None,
            client_ip: None,
        };

        assert!(fixture.matches(&matching_request));
        assert!(!fixture.matches(&non_matching_request));
    }

    #[test]
    fn test_fixture_to_protocol_response() {
        let fixture = UnifiedFixture {
            id: "test".to_string(),
            name: "Test".to_string(),
            description: "".to_string(),
            protocol: Protocol::Http,
            request: FixtureRequest {
                pattern: None,
                operation: None,
                path: None,
                topic: None,
                routing_key: None,
                partition: None,
                qos: None,
                headers: HashMap::new(),
                body_pattern: None,
                custom_matcher: None,
            },
            response: FixtureResponse {
                status: FixtureStatus::Http(200),
                headers: {
                    let mut h = HashMap::new();
                    h.insert("content-type".to_string(), "application/json".to_string());
                    h
                },
                body: Some(serde_json::json!({"message": "ok"})),
                content_type: Some("application/json".to_string()),
                delay_ms: 0,
                template_vars: HashMap::new(),
            },
            metadata: HashMap::new(),
            enabled: true,
            priority: 0,
            tags: vec![],
        };

        let response = fixture.to_protocol_response().unwrap();
        assert!(response.status.is_success());
        assert_eq!(response.content_type, "application/json");
        assert_eq!(response.metadata.get("content-type"), Some(&"application/json".to_string()));
    }

    #[test]
    fn test_fixture_status_serialization() {
        // Test HTTP status
        let status = FixtureStatus::Http(404);
        let serialized = serde_json::to_string(&status).unwrap();
        assert_eq!(serialized, "404");

        // Test gRPC status
        let status = FixtureStatus::Grpc(5);
        let serialized = serde_json::to_string(&status).unwrap();
        assert_eq!(serialized, "5");

        // Test generic status
        let status = FixtureStatus::Generic(true);
        let serialized = serde_json::to_string(&status).unwrap();
        assert_eq!(serialized, "true");

        // Test custom status
        let status = FixtureStatus::Custom {
            code: 500,
            message: "Internal Error".to_string(),
        };
        let serialized = serde_json::to_string(&status).unwrap();
        let expected: serde_json::Value =
            serde_json::json!({"code": 500, "message": "Internal Error"});
        assert_eq!(serde_json::from_str::<serde_json::Value>(&serialized).unwrap(), expected);
    }

    #[test]
    fn test_fixture_pattern_matching() {
        let fixture = UnifiedFixture {
            id: "test".to_string(),
            name: "Test".to_string(),
            description: "".to_string(),
            protocol: Protocol::Http,
            request: FixtureRequest {
                pattern: Some(MessagePattern::RequestResponse),
                operation: Some("GET".to_string()),
                path: Some("/api/.*".to_string()),
                topic: None,
                routing_key: None,
                partition: None,
                qos: None,
                headers: HashMap::new(),
                body_pattern: None,
                custom_matcher: None,
            },
            response: FixtureResponse {
                status: FixtureStatus::Http(200),
                headers: HashMap::new(),
                body: None,
                content_type: None,
                delay_ms: 0,
                template_vars: HashMap::new(),
            },
            metadata: HashMap::new(),
            enabled: true,
            priority: 0,
            tags: vec![],
        };

        // Test matching request
        let request = ProtocolRequest {
            protocol: Protocol::Http,
            pattern: MessagePattern::RequestResponse,
            operation: "GET".to_string(),
            path: "/api/users".to_string(),
            topic: None,
            routing_key: None,
            partition: None,
            qos: None,
            metadata: HashMap::new(),
            body: None,
            client_ip: None,
        };
        assert!(fixture.matches(&request));

        // Test non-matching protocol
        let grpc_request = ProtocolRequest {
            protocol: Protocol::Grpc,
            pattern: MessagePattern::RequestResponse,
            operation: "GET".to_string(),
            path: "/api/users".to_string(),
            topic: None,
            routing_key: None,
            partition: None,
            qos: None,
            metadata: HashMap::new(),
            body: None,
            client_ip: None,
        };
        assert!(!fixture.matches(&grpc_request));

        // Test non-matching operation
        let post_request = ProtocolRequest {
            protocol: Protocol::Http,
            pattern: MessagePattern::RequestResponse,
            operation: "POST".to_string(),
            path: "/api/users".to_string(),
            topic: None,
            routing_key: None,
            partition: None,
            qos: None,
            metadata: HashMap::new(),
            body: None,
            client_ip: None,
        };
        assert!(!fixture.matches(&post_request));
    }

    #[test]
    fn test_custom_matcher_equality() {
        let fixture = UnifiedFixture {
            id: "test".to_string(),
            name: "Test".to_string(),
            description: "".to_string(),
            protocol: Protocol::Http,
            request: FixtureRequest {
                pattern: Some(MessagePattern::RequestResponse),
                operation: Some("GET".to_string()),
                path: Some("/api/users".to_string()),
                topic: None,
                routing_key: None,
                partition: None,
                qos: None,
                headers: HashMap::new(),
                body_pattern: None,
                custom_matcher: Some("operation == \"GET\"".to_string()),
            },
            response: FixtureResponse {
                status: FixtureStatus::Http(200),
                headers: HashMap::new(),
                body: None,
                content_type: None,
                delay_ms: 0,
                template_vars: HashMap::new(),
            },
            metadata: HashMap::new(),
            enabled: true,
            priority: 0,
            tags: vec![],
        };

        // Test matching request
        let request = ProtocolRequest {
            protocol: Protocol::Http,
            pattern: MessagePattern::RequestResponse,
            operation: "GET".to_string(),
            path: "/api/users".to_string(),
            topic: None,
            routing_key: None,
            partition: None,
            qos: None,
            metadata: HashMap::new(),
            body: None,
            client_ip: None,
        };
        assert!(fixture.matches(&request));

        // Test non-matching request
        let post_request = ProtocolRequest {
            protocol: Protocol::Http,
            pattern: MessagePattern::RequestResponse,
            operation: "POST".to_string(),
            path: "/api/users".to_string(),
            topic: None,
            routing_key: None,
            partition: None,
            qos: None,
            metadata: HashMap::new(),
            body: None,
            client_ip: None,
        };
        assert!(!fixture.matches(&post_request));
    }

    #[test]
    fn test_custom_matcher_regex() {
        let fixture = UnifiedFixture {
            id: "test".to_string(),
            name: "Test".to_string(),
            description: "".to_string(),
            protocol: Protocol::Http,
            request: FixtureRequest {
                pattern: Some(MessagePattern::RequestResponse),
                operation: Some("GET".to_string()),
                path: Some("/api/.*".to_string()),
                topic: None,
                routing_key: None,
                partition: None,
                qos: None,
                headers: HashMap::new(),
                body_pattern: None,
                custom_matcher: Some("path =~ \"/api/.*\"".to_string()),
            },
            response: FixtureResponse {
                status: FixtureStatus::Http(200),
                headers: HashMap::new(),
                body: None,
                content_type: None,
                delay_ms: 0,
                template_vars: HashMap::new(),
            },
            metadata: HashMap::new(),
            enabled: true,
            priority: 0,
            tags: vec![],
        };

        // Test matching request
        let request = ProtocolRequest {
            protocol: Protocol::Http,
            pattern: MessagePattern::RequestResponse,
            operation: "GET".to_string(),
            path: "/api/users".to_string(),
            topic: None,
            routing_key: None,
            partition: None,
            qos: None,
            metadata: HashMap::new(),
            body: None,
            client_ip: None,
        };
        assert!(fixture.matches(&request));

        // Test non-matching request
        let other_request = ProtocolRequest {
            protocol: Protocol::Http,
            pattern: MessagePattern::RequestResponse,
            operation: "GET".to_string(),
            path: "/other/path".to_string(),
            topic: None,
            routing_key: None,
            partition: None,
            qos: None,
            metadata: HashMap::new(),
            body: None,
            client_ip: None,
        };
        assert!(!fixture.matches(&other_request));
    }

    #[test]
    fn test_custom_matcher_contains() {
        let fixture = UnifiedFixture {
            id: "test".to_string(),
            name: "Test".to_string(),
            description: "".to_string(),
            protocol: Protocol::Http,
            request: FixtureRequest {
                pattern: Some(MessagePattern::RequestResponse),
                operation: Some("POST".to_string()),
                path: Some("/api/users".to_string()),
                topic: None,
                routing_key: None,
                partition: None,
                qos: None,
                headers: HashMap::new(),
                body_pattern: None,
                custom_matcher: Some("body contains \"test\"".to_string()),
            },
            response: FixtureResponse {
                status: FixtureStatus::Http(200),
                headers: HashMap::new(),
                body: None,
                content_type: None,
                delay_ms: 0,
                template_vars: HashMap::new(),
            },
            metadata: HashMap::new(),
            enabled: true,
            priority: 0,
            tags: vec![],
        };

        // Test matching request
        let request = ProtocolRequest {
            protocol: Protocol::Http,
            pattern: MessagePattern::RequestResponse,
            operation: "POST".to_string(),
            path: "/api/users".to_string(),
            topic: None,
            routing_key: None,
            partition: None,
            qos: None,
            metadata: HashMap::new(),
            body: Some(b"{\"name\": \"test user\"}".to_vec()),
            client_ip: None,
        };
        assert!(fixture.matches(&request));

        // Test non-matching request
        let no_match_request = ProtocolRequest {
            protocol: Protocol::Http,
            pattern: MessagePattern::RequestResponse,
            operation: "POST".to_string(),
            path: "/api/users".to_string(),
            topic: None,
            routing_key: None,
            partition: None,
            qos: None,
            metadata: HashMap::new(),
            body: Some(b"{\"name\": \"other user\"}".to_vec()),
            client_ip: None,
        };
        assert!(!fixture.matches(&no_match_request));
    }

    #[test]
    fn test_custom_matcher_header() {
        let fixture = UnifiedFixture {
            id: "test".to_string(),
            name: "Test".to_string(),
            description: "".to_string(),
            protocol: Protocol::Http,
            request: FixtureRequest {
                pattern: Some(MessagePattern::RequestResponse),
                operation: Some("GET".to_string()),
                path: Some("/api/data".to_string()),
                topic: None,
                routing_key: None,
                partition: None,
                qos: None,
                headers: HashMap::new(),
                body_pattern: None,
                custom_matcher: Some("headers.content-type == \"application/json\"".to_string()),
            },
            response: FixtureResponse {
                status: FixtureStatus::Http(200),
                headers: HashMap::new(),
                body: None,
                content_type: None,
                delay_ms: 0,
                template_vars: HashMap::new(),
            },
            metadata: HashMap::new(),
            enabled: true,
            priority: 0,
            tags: vec![],
        };

        // Test matching request
        let mut headers = HashMap::new();
        headers.insert("content-type".to_string(), "application/json".to_string());
        let request = ProtocolRequest {
            protocol: Protocol::Http,
            pattern: MessagePattern::RequestResponse,
            operation: "GET".to_string(),
            path: "/api/data".to_string(),
            topic: None,
            routing_key: None,
            partition: None,
            qos: None,
            metadata: headers,
            body: None,
            client_ip: None,
        };
        assert!(fixture.matches(&request));

        // Test non-matching request
        let mut wrong_headers = HashMap::new();
        wrong_headers.insert("content-type".to_string(), "text/plain".to_string());
        let wrong_request = ProtocolRequest {
            protocol: Protocol::Http,
            pattern: MessagePattern::RequestResponse,
            operation: "GET".to_string(),
            path: "/api/data".to_string(),
            topic: None,
            routing_key: None,
            partition: None,
            qos: None,
            metadata: wrong_headers,
            body: None,
            client_ip: None,
        };
        assert!(!fixture.matches(&wrong_request));
    }
}