gearbox 3.0.0

Excessive tooling for Rust, boosting productivity and operations
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
use crate::net::http::request::{Body, Builder, Url};
use serde_derive::{Deserialize, Serialize};

use crate::collections::HashMap;
use crate::error::{DynTracerError, TracerError};
use crate::net::http::request;
use crate::net::http::request::body::BodyTrait;
use crate::rails::ext::fut::ext::result::Map;
use crate::rails::ext::future::FutureResult;
#[cfg(target_arch = "wasm32")]
use crate::serde::wasm_bindgen as serde_wasm_bindgen;
use crate::template::engine::TemplateContext;
use crate::template::{PipelineValue, TemplateEngine};
use crate::{tracer_dyn_err, tracer_err};
use alloc::{string::String, sync::Arc, vec::Vec};
use core::future::Future;
use serde::{de, ser, Deserializer, Serializer};
use spin::Mutex;
use std::ops::{Deref, DerefMut};
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*;

/// The `RequestChain` structure allows for creating a sequence of HTTP requests where the response
/// from one request can be used to populate and forward data to the next request. This is useful
/// for scenarios such as calling a REST API where an initial request is needed to obtain a nonce
/// before making the main API call.
///
/// Requests are stored in `template_requests` with each `RequestNode` identified by a unique name.
/// Multiple call chains can be defined in `call_structures`, where each chain is represented by
/// a vector of request names. This allows for reusing requests across different chains.
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct RequestChain {
    template_requests: HashMap<String, RequestNode>,
    call_structures: HashMap<String, CallStructure>,
}

impl RequestChain {
    /// Creates a new, empty `RequestChain`.
    ///
    /// # Examples
    ///
    /// ```
    /// use gearbox::net::http::request_chaining::*;
    ///
    /// let chain = RequestChain::new();
    /// ```
    pub fn new() -> RequestChain {
        RequestChain {
            template_requests: HashMap::new(),
            call_structures: HashMap::new(),
        }
    }

    /// Adds a `RequestNode` to the template requests.
    ///
    /// # Arguments
    ///
    /// * `request` - The `RequestNode` to add to the template requests.
    ///
    /// # Examples
    ///
    /// ```
    /// use gearbox::net::http::request_chaining::*;
    ///
    /// let mut chain = RequestChain::new();
    /// let node = RequestNode::default();
    /// chain.add_template_request(node);
    /// ```
    pub fn add_template_request(&mut self, request: RequestNode) {
        self.template_requests.insert(request.name.clone(), request);
    }
    /// Adds a template request to the chain using an asynchronous callback function.
    ///
    /// This method allows for the addition of a `RequestNode` to the `RequestChain` through a
    /// provided callback function that operates asynchronously. The callback function receives
    /// a `RequestNodeBuilder` which can be used to construct and return a `RequestNodeBuilder`
    /// to be added to the chain.
    ///
    /// # Arguments
    ///
    /// * `o` - A callback function that takes a `RequestNodeBuilder` and returns a future that
    ///         resolves to a `Result<RequestNodeBuilder, TracerError>`.
    ///
    /// # Returns
    ///
    /// A `Result` containing a mutable reference to the `RequestChain` if successful, or a
    /// `TracerError` if an error occurs.
    ///
    /// # Examples
    ///
    /// ```
    /// use gearbox::net::http::request_chaining::*;
    /// use gearbox::error::DynTracerError;
    /// use core::future::Future;
    ///
    /// async fn example_callback(mut builder: RequestNodeBuilder) -> Result<RequestNodeBuilder, DynTracerError> {
    ///     builder = builder.name("example_node");
    ///     Ok(builder)
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let mut chain = RequestChain::new();
    ///     chain.add_template_with_callback(example_callback).await.unwrap();
    /// }
    /// ```
    pub async fn add_template_with_callback<
        U: Future<Output = Result<RequestNodeBuilder, DynTracerError>>,
        O: FnOnce(RequestNodeBuilder) -> U,
    >(
        &mut self,
        o: O,
    ) -> Result<&mut Self, DynTracerError> {
        let builder = RequestNodeBuilder::default();
        o(builder).await.map(|t| {
            self.add_template_request(t.build());
            self
        })
    }

    /// Adds a call structure to the request chain.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the call structure.
    /// * `calls` - A vector of strings representing the call sequence.
    ///
    /// # Examples
    ///
    /// ```
    /// use gearbox::net::http::request_chaining::*;
    ///
    /// let mut chain = RequestChain::new();
    /// chain.add_call_structure("example_chain", vec!["request1".to_string(), "request2".to_string()]);
    /// ```
    pub fn add_call_structure(&mut self, name: &str, calls: Vec<String>) {
        self.call_structures.insert(
            name.to_string(),
            CallStructure::new(Some(name.to_string()), None, calls),
        );
    }
}

/// This implementation for the Request Chain is mainly meant for use in conjunction with WASM.
/// WASM has several limitations and often requires a different structure, such as using callbacks
/// instead of closures. These function implementations provide a more "JavaScript-like" experience
/// when using the RequestChain structure.
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
#[cfg(target_arch = "wasm32")]
impl RequestChain {
    /// Adds a call to the request chain using a JavaScript callback.
    ///
    /// # Arguments
    ///
    /// * `callback` - The JavaScript function to call.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let chain = RequestChain::new().add_call(&js_function);
    /// ```
    pub fn add_call(mut self, callback: &js_sys::Function) -> Self {
        let request_node_builder = RequestNodeBuilder::default();

        let this = JsValue::null();
        let result = callback.call1(&this, &request_node_builder.into()).unwrap();
        let returned_builder: RequestNodeBuilder = serde_wasm_bindgen::from_value(result).unwrap();

        self.add_template_request(returned_builder.build());

        self
    }
}

#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
impl RequestChain {
    pub async fn run(
        &self,
        chain_name: &str,
        variables: Vec<WasmVariable>,
    ) -> Result<ChainResponses, DynTracerError> {
        let mut processor = RequestProcessor::new(self.clone());
        processor
            .process(
                chain_name,
                variables
                    .into_iter()
                    .map(|t| t.into())
                    .collect::<HashMap<String, String>>(),
            )
            .await
    }
}

#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct WasmVariable {
    name: String,
    value: String,
}

impl From<WasmVariable> for (String, String) {
    fn from(v: WasmVariable) -> (String, String) {
        (v.name, v.value)
    }
}

/// A builder for creating `RequestNode` objects. It allows adjusting for variable captures and
/// templating for forwarding the data.
///
/// # Examples
///
/// ```
/// use gearbox::net::http::request_chaining::*;
///
/// let builder = RequestNodeBuilder::default()
///     .name("example_node")
///     .build();
/// ```
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct RequestNodeBuilder {
    requests: Vec<Builder>,
    captures: VariableCaptures,
    name: String,
}

/// These are extensive implementations that is not allowed under WASM. But functions that improve
/// usability under Rust.
impl RequestNodeBuilder {}

/// These are common implementations for the RequestNodeBuilder structure, that are also supported under
/// WASM. These functions are used to set the name of the RequestNodeBuilder and to build the RequestNode.
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
impl RequestNodeBuilder {
    /// Adds a request to the `RequestNodeBuilder`.
    ///
    /// # Arguments
    ///
    /// * `request` - The request to add.
    ///
    /// # Examples
    ///
    /// ```
    /// use gearbox::net::http::request::Builder;
    /// use gearbox::net::http::request_chaining::*;
    ///
    /// let builder = RequestNodeBuilder::default().add_request(Builder::default());
    /// ```
    pub fn add_request(mut self, request: Builder) -> RequestNodeBuilder {
        self.requests.push(request);
        self
    }

    /// Adds a variable capture to the `RequestNodeBuilder`.
    ///
    /// # Arguments
    ///
    /// * `capture` - The variable capture to add.
    ///
    /// # Examples
    ///
    /// ```
    /// use gearbox::net::http::request_chaining::*;
    ///
    /// let builder = RequestNodeBuilder::default().add_capture(VariableCapture::default());
    /// ```
    pub fn add_capture(mut self, capture: VariableCapture) -> RequestNodeBuilder {
        self.captures.body.push(capture);
        self
    }

    /// Sets the name of the `RequestNodeBuilder`.
    ///
    /// # Arguments
    ///
    /// * `name` - The name to set.
    ///
    /// # Examples
    ///
    /// ```
    /// use gearbox::net::http::request_chaining::*;
    ///
    /// let builder = RequestNodeBuilder::default().name("example_node");
    /// ```
    pub fn name(mut self, name: &str) -> RequestNodeBuilder {
        self.name = name.to_string();
        self
    }

    /// Builds and returns a `RequestNode`.
    ///
    /// # Examples
    ///
    /// ```
    /// use gearbox::net::http::request_chaining::*;
    ///
    /// let node = RequestNodeBuilder::default().build();
    /// ```
    pub fn build(self) -> RequestNode {
        RequestNode {
            name: self.name,
            matcher: self.captures,
            children: self.requests,
            depends_on: Vec::new(),
        }
    }
}

/// These implementations of RequestNodeBuilder are mainly meant for WASM, as they allow for a more
/// "JavaScript-like" experience when using the RequestNodeBuilder structure.
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
#[cfg(target_arch = "wasm32")]
impl RequestNodeBuilder {
    /// Adds a request using a JavaScript callback.
    ///
    /// # Arguments
    ///
    /// * `callback` - The JavaScript function to call.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let builder = RequestNodeBuilder::default().make_request(&js_function);
    /// ```
    pub fn make_request(mut self, callback: &js_sys::Function) -> Self {
        let request_builder = Builder::default();

        let result = callback
            .call1(&JsValue::NULL, &request_builder.into())
            .unwrap();
        let returned_builder: Builder = serde_wasm_bindgen::from_value(result).unwrap();

        self.requests.push(returned_builder);

        self
    }
}

#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct CallStructure {
    name: Option<String>,
    description: Option<String>,
    calls: Vec<String>,
}

impl CallStructure {
    pub fn new(
        name: Option<String>,
        description: Option<String>,
        calls: Vec<String>,
    ) -> CallStructure {
        CallStructure {
            name,
            description,
            calls,
        }
    }

    pub fn name(&self) -> Option<String> {
        self.name.clone()
    }

    pub fn description(&self) -> Option<String> {
        self.description.clone()
    }

    pub fn calls(&self) -> Vec<String> {
        self.calls.clone()
    }

    pub fn set_name(&mut self, name: Option<String>) {
        self.name = name;
    }

    pub fn set_description(&mut self, description: Option<String>) {
        self.description = description;
    }

    pub fn set_calls(&mut self, calls: Vec<String>) {
        self.calls = calls;
    }
}

impl From<Vec<String>> for CallStructure {
    fn from(v: Vec<String>) -> CallStructure {
        CallStructure {
            name: None,
            description: None,
            calls: v,
        }
    }
}

impl From<CallStructure> for Vec<String> {
    fn from(v: CallStructure) -> Vec<String> {
        v.calls
    }
}

impl Deref for CallStructure {
    type Target = Vec<String>;

    fn deref(&self) -> &Self::Target {
        &self.calls
    }
}

impl DerefMut for CallStructure {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.calls
    }
}

/// A node in the request chain.
///
/// # Examples
///
/// ```
/// use gearbox::net::http::request_chaining::*;
///
/// let node = RequestNode::default();
/// ```
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct RequestNode {
    name: String,
    matcher: VariableCaptures,
    children: Vec<Builder>,
    depends_on: Vec<String>,
}

/// Captures variables from different parts of a response.
///
/// # Examples
///
/// ```
/// use gearbox::net::http::request_chaining::*;
///
/// let captures = VariableCaptures::default();
/// ```
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
#[derive(Clone, Debug, Default)]
pub struct VariableCaptures {
    body: Vec<VariableCapture>,
    headers: Vec<VariableCapture>,
    query: Vec<VariableCapture>,
}

impl VariableCaptures {}

impl ser::Serialize for VariableCaptures {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut captures = Vec::new();
        for capture in &self.body {
            captures.push(CaptureWrapper {
                id: capture.id.clone(),
                capture_type: "body".to_string(),
                matcher: capture.matcher.clone(),
                default: capture.default.clone(),
            });
        }
        for capture in &self.headers {
            captures.push(CaptureWrapper {
                id: capture.id.clone(),
                capture_type: "headers".to_string(),
                matcher: capture.matcher.clone(),
                default: capture.default.clone(),
            });
        }
        for capture in &self.query {
            captures.push(CaptureWrapper {
                id: capture.id.clone(),
                capture_type: "query".to_string(),
                matcher: capture.matcher.clone(),
                default: capture.default.clone(),
            });
        }
        captures.serialize(serializer)
    }
}

impl<'de> de::Deserialize<'de> for VariableCaptures {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let captures: Vec<CaptureWrapper> = de::Deserialize::deserialize(deserializer)?;
        let mut body = Vec::new();
        let mut headers = Vec::new();
        let mut query = Vec::new();

        for capture in captures {
            match capture.capture_type.to_lowercase().as_str() {
                "body" => body.push(VariableCapture {
                    id: capture.id.clone(),
                    matcher: capture.matcher.clone(),
                    default: capture.default.clone(),
                }),
                "headers" => headers.push(VariableCapture {
                    id: capture.id.parse().unwrap(),
                    matcher: capture.matcher.clone(),
                    default: capture.default.clone(),
                }),
                "query" => query.push(VariableCapture {
                    id: capture.id.parse().unwrap(),
                    matcher: capture.matcher.clone(),
                    default: capture.default.clone(),
                }),
                _ => {
                    return Err(serde::de::Error::unknown_variant(
                        &*capture.capture_type,
                        &["body", "headers", "query"],
                    ))
                }
            }
        }

        Ok(VariableCaptures {
            body,
            headers,
            query,
        })
    }
}

#[derive(Clone, Serialize, Deserialize)]
struct CaptureWrapper {
    id: String,
    #[serde(rename = "type")]
    capture_type: String,
    matcher: Matcher,
    default: Option<String>,
}

/// Captures a single variable from a response.
///
/// # Examples
///
/// ```
/// use gearbox::net::http::request_chaining::*;
///
/// let capture = VariableCapture::default();
/// ```
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct VariableCapture {
    id: String,
    matcher: Matcher,
    default: Option<String>,
}

/// Matches parts of a response for variable capturing.
///
/// # Examples
///
/// ```
/// use gearbox::net::http::request_chaining::*;
///
/// let matcher = Matcher::default();
/// ```
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct Matcher {
    #[serde(skip_serializing_if = "Option::is_none")]
    between: Option<(String, String)>,
    #[serde(skip_serializing_if = "Option::is_none")]
    regexp: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    xpath: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    all: Option<bool>,
}

#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
impl Matcher {
    /// Creates a matcher for capturing text between two strings.
    ///
    /// # Arguments
    ///
    /// * `from` - The start string.
    /// * `to` - The end string.
    ///
    /// # Examples
    ///
    /// ```
    /// use gearbox::net::http::request_chaining::*;
    ///
    /// let matcher = Matcher::between("start".to_string(), "end".to_string());
    /// ```
    pub fn between(from: String, to: String) -> Matcher {
        Matcher {
            between: Some((from, to)),
            regexp: None,
            xpath: None,
            all: None,
        }
    }

    /// Creates a matcher for capturing text using a regular expression.
    ///
    /// # Arguments
    ///
    /// * `regexp` - The regular expression.
    ///
    /// # Examples
    ///
    /// ```
    /// use gearbox::net::http::request_chaining::*;
    ///
    /// let matcher = Matcher::regexp("regex".to_string());
    /// ```
    pub fn regexp(regexp: String) -> Matcher {
        Matcher {
            between: None,
            regexp: Some(regexp),
            xpath: None,
            all: None,
        }
    }

    /// Creates a matcher for capturing all text.
    ///
    /// # Arguments
    ///
    /// * `all` - Whether to capture all text.
    ///
    /// # Examples
    ///
    /// ```
    /// use gearbox::net::http::request_chaining::*;
    ///
    /// let matcher = Matcher::all(true);
    /// ```
    pub fn all(all: bool) -> Matcher {
        Matcher {
            between: None,
            regexp: None,
            all: Some(all),
            xpath: None,
        }
    }
}

/// Processes a request chain, capturing variables and responses.
///
/// # Examples
///
/// ```
/// use gearbox::net::http::request_chaining::*;
/// use gearbox::collections::HashMap;
///
/// let mut variables = HashMap::new();
/// variables.insert("example".to_string(), "value".to_string());
///
/// let chain = RequestChain::new();
/// let mut processor = RequestProcessor::new(chain);
/// processor.process("example_chain", variables);
/// ```
pub struct RequestProcessor {
    request_chain: RequestChain,
    variables: HashMap<String, String>,
    response: ChainResponses,
}

impl RequestProcessor {
    /// Creates a new `RequestProcessor`.
    ///
    /// # Arguments
    ///
    /// * `request_chain` - The `RequestChain` to process.
    ///
    /// # Examples
    ///
    /// ```
    /// use gearbox::net::http::request_chaining::*;
    ///
    /// let chain = RequestChain::new();
    /// let processor = RequestProcessor::new(chain);
    /// ```
    pub fn new(request_chain: RequestChain) -> RequestProcessor {
        RequestProcessor {
            request_chain,
            variables: HashMap::new(),
            response: ChainResponses::default(),
        }
    }

    /// Processes a call structure in the request chain.
    ///
    /// # Arguments
    ///
    /// * `chain_name` - The name of the call structure to process.
    ///
    /// # Examples
    ///
    /// ```
    /// use gearbox::net::http::request_chaining::*;
    /// use gearbox::collections::HashMap;
    ///
    /// let mut variables = HashMap::new();
    /// variables.insert("example".to_string(), "value".to_string());
    ///
    /// let chain = RequestChain::new();
    /// let mut processor = RequestProcessor::new(chain);
    /// processor.process("example_chain", variables);
    /// ```
    pub async fn process(
        &mut self,
        chain_name: &str,
        variables: HashMap<String, String>,
    ) -> Result<ChainResponses, DynTracerError> {
        if let Some(calls) = self
            .request_chain
            .call_structures
            .get(chain_name)
            .map(Clone::clone)
        {
            for call in calls.calls() {
                if let Some(request_node) = self.request_chain.template_requests.get(&call) {
                    self.execute_request(request_node.clone()).await?;
                }
            }
            if self.response.responses.is_empty() {
                Err(tracer_dyn_err!("No responses were generated."))
            } else {
                self.variables = variables;
                Ok(self.response.clone())
            }
        } else {
            Err(tracer_dyn_err!("Call structure not found."))
        }
    }

    /// Executes a request node and captures variables.
    ///
    /// # Arguments
    ///
    /// * `request_node` - The `RequestNode` to execute.
    async fn execute_request(&mut self, request_node: RequestNode) -> Result<(), DynTracerError> {
        let mut context = TemplateContext::new();

        self.variables.iter().for_each(|(k, v)| {
            context.insert(k.as_str(), Box::new(v.clone()));
        });

        let context = &context.clone();
        for mut request in request_node.children {
            // Updating headers, if the headers are using templating we are going to render them into
            // the variables and then update the headers with the rendered values
            request.headers_mut().iter_mut().for_each(|(k, v)| {
                v.iter_mut().for_each(|t| {
                    String::from_utf8(t.0.clone()).map(|s| {
                        TemplateEngine::new().render(&s, &context).map(|r| {
                            t.0 = r.into_bytes();
                        });
                    });
                });
            });

            request
                .update_body(|mut t| async move {
                    let output = t.into_string().await;
                    output
                        .and_then(|r| TemplateEngine::new().render(&r, &context))
                        .map(|t| Box::new(Body::from(t)))
                })
                .await?;

            request.url_mut().as_mut().map(|t| {
                TemplateEngine::new()
                    .render(&t.to_string(), &context)
                    .map(|r| {
                        *t = Url::from(&r);
                    });
            });

            let response = request
                .send()
                .map_err(|e| async { tracer_dyn_err!(e) })
                .and_then(|t| async { ChainResponse::try_from_response(t).await })
                .await?;

            self.capture_variables(&response, &request_node.matcher);
            self.response.responses.push(response.clone());
            self.response.last = response;
        }

        Ok(())
    }

    /// Captures variables from a response based on the provided captures.
    ///
    /// # Arguments
    ///
    /// * `response` - The `Response` object to capture variables from.
    /// * `captures` - The `VariableCaptures` defining what to capture.
    fn capture_variables(&mut self, response: &ChainResponse, captures: &VariableCaptures) {
        for capture in &captures.body {
            if let Some(value) = self.match_response(&response.body, &capture.matcher) {
                self.variables.insert(capture.id.clone(), value);
            }
        }
        // Similarly handle captures from headers and query
    }

    /// Matches a response based on the provided matcher.
    ///
    /// # Arguments
    ///
    /// * `response` - The response string to match.
    /// * `matcher` - The `Matcher` defining how to match the response.
    ///
    /// # Returns
    ///
    /// An optional string representing the matched value.
    fn match_response(&self, response: &str, matcher: &Matcher) -> Option<String> {
        if let Some((from, to)) = &matcher.between {
            if let Some(start) = response.find(from) {
                if let Some(end) = response[start..].find(to) {
                    return Some(response[start + from.len()..start + end].to_string());
                }
            }
        }
        if let Some(regexp) = &matcher.regexp {
            // Apply regexp matching logic
        }
        if matcher.all.unwrap_or(false) {
            return Some(response.to_string());
        }
        None
    }
}

/// Holds the responses from processed requests.
///
/// # Examples
///
/// ```
/// use gearbox::net::http::request_chaining::*;
///
/// let responses = ChainResponses::default();
/// ```
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct ChainResponses {
    responses: Vec<ChainResponse>,
    last: ChainResponse,
}

/// Represents a single response from a processed request.
///
/// # Examples
///
/// ```
/// use gearbox::net::http::request_chaining::*;
///
/// let response = ChainResponse::default();
/// ```
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct ChainResponse {
    body: String,
    headers: HashMap<String, String>,
    status: u16,
    status_msg: String,
    variables_state: HashMap<String, String>,
}

impl ChainResponse {
    pub async fn try_from_response(response: request::Response) -> Result<Self, DynTracerError> {
        let body = response.body().into_str().await?;
        let headers = response
            .headers()
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_header_string()))
            .collect();
        let status = response.status().as_u16();
        let status_msg = response.status().as_str().to_string();
        let variables_state = HashMap::new();
        Ok(ChainResponse {
            body,
            headers,
            status,
            status_msg,
            variables_state,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::collections::HashMap;
    use crate::net::http::request::Method;
    use crate::net::http::test::test_server::start_test_server;
    use crate::rails::ext::future::*;
    use tokio::sync::oneshot;

    #[tokio::test]
    async fn test_complete_request_chain_functionality() {
        let (addr, shutdown_tx) = start_test_server().await;

        // Setup RequestChain
        let mut chain = RequestChain::new();
        chain
            .add_template_with_callback(|mut builder| async {
                builder = builder
                    .name("test_node_1")
                    .add_request(
                        Builder::default()
                            .body(r#"{"status":200, "payload":"hello", "headers":{}}"#)
                            .content_type("application/json")
                            .method(Method::Post)
                            .url(format!("http://{}/", addr)),
                    )
                    .add_capture(VariableCapture {
                        id: "text".to_string(),
                        matcher: Matcher::all(true),
                        default: None,
                    });
                Ok(builder)
            })
            .and_then(|t| async {
                t.add_template_with_callback(|mut builder| async {
                    builder = builder
                        .name("test_node_2")
                        .add_request(
                            Builder::default()
                                .body(
                                    r#"{"status":200, "payload":"{{ text }} world", "headers":{}}"#,
                                )
                                .content_type("application/json")
                                .method(Method::Post)
                                .url(format!("http://{}/", addr)),
                        )
                        .add_capture(VariableCapture {
                            id: "test_capture".to_string(),
                            matcher: Matcher::all(true),
                            default: None,
                        });
                    Ok(builder) as Result<_, DynTracerError>
                })
                .await
            })
            .await
            .ok();

        chain.call_structures.insert(
            "test_chain".to_string(),
            vec!["test_node_1".to_string(), "test_node_2".to_string()].into(),
        );

        let serialized_chain = serde_json::to_string(&chain).unwrap();

        println!("{}", serialized_chain);

        let deserialized_chain: RequestChain = serde_json::from_str(&serialized_chain).unwrap();

        let responses = deserialized_chain
            .run("test_chain", Vec::new())
            .await
            .unwrap();

        assert_eq!(responses.responses.len(), 2);
        assert_eq!(responses.responses[0].body, r#"hello"#);
        assert_eq!(responses.responses[1].body, r#"hello world"#);

        // Shutdown the server
        shutdown_tx.send(()).unwrap();
    }

    #[tokio::test]
    async fn test_request_chain_new() {
        let chain = RequestChain::new();
        assert!(chain.template_requests.is_empty());
        assert!(chain.call_structures.is_empty());
    }

    #[tokio::test]
    async fn test_add_template_request() {
        let mut chain = RequestChain::new();
        let node = RequestNode {
            name: "test_node".to_string(),
            ..Default::default()
        };
        chain.add_template_request(node.clone());
        assert_eq!(
            chain.template_requests.get("test_node").unwrap().name,
            "test_node"
        );
    }

    #[tokio::test]
    async fn test_add_call_structure() {
        let mut chain = RequestChain::new();
        chain.add_call_structure(
            "test_chain",
            vec!["request1".to_string(), "request2".to_string()],
        );
        assert_eq!(
            chain.call_structures.get("test_chain").unwrap().calls(),
            vec!["request1".to_string(), "request2".to_string()]
        );
    }

    #[tokio::test]
    async fn test_request_node_builder() {
        let mut builder = RequestNodeBuilder::default()
            .name("example_node")
            .add_request(Builder::default())
            .add_capture(VariableCapture::default());

        let node = builder.build();
        assert_eq!(node.name, "example_node");
        assert_eq!(node.children.len(), 1);
        assert_eq!(node.matcher.body.len(), 1);
    }

    #[tokio::test]
    async fn test_request_node_builder_with_request() {
        let mut builder = RequestNodeBuilder::default()
            .name("example_node")
            .add_request(Builder::default())
            .add_capture(VariableCapture::default())
            .add_request(Builder::default());

        let node = builder.build();
        assert_eq!(node.name, "example_node");
        assert_eq!(node.children.len(), 2);
        assert_eq!(node.matcher.body.len(), 1);
    }

    #[tokio::test]
    async fn test_request_processor_with_server() {
        let (addr, shutdown_tx) = start_test_server().await;

        // Setup RequestChain
        let mut chain = RequestChain::new();

        // Create a request node
        let node = RequestNodeBuilder::default()
            .name("test_node")
            .add_request(
                Builder::default()
                    .method("GET")
                    .url(format!("http://{}/", addr)),
            )
            .build();
        chain.add_template_request(node.clone());
        chain.add_call_structure("test_chain", vec!["test_node".to_string()]);

        // Process the request chain
        let mut processor = RequestProcessor::new(chain);
        let variables = HashMap::new();
        let result = processor.process("test_chain", variables).await;

        // Validate the result
        match result {
            Ok(responses) => {
                assert_eq!(responses.responses.len(), 1);
                let response = &responses.responses[0];
                assert_eq!(response.body, "GET response");
            }
            Err(e) => panic!("Process failed: {:?}", e),
        }

        // Shutdown the server
        shutdown_tx.send(()).unwrap();
    }

    #[tokio::test]
    async fn test_multi_request_processor_with_server() {
        let (addr, shutdown_tx) = start_test_server().await;

        // Setup RequestChain
        let mut chain = RequestChain::new();

        // Create first request node
        let node1 = RequestNodeBuilder::default()
            .name("test_node_1")
            .add_request(
                Builder::default()
                    .method(Method::Get)
                    .url(format!("http://{}/", addr))
                    .body(Body::empty()),
            )
            .build();
        chain.add_template_request(node1.clone());

        // Create second request node
        let node2 = RequestNodeBuilder::default()
            .name("test_node_2")
            .add_request(
                Builder::default()
                    .method(Method::Post)
                    .url(format!("http://{}/", addr))
                    .body(Body::empty()),
            )
            .build();
        chain.add_template_request(node2.clone());

        // Create third request node
        let node3 = RequestNodeBuilder::default()
            .name("test_node_3")
            .add_request(
                Builder::default()
                    .method(Method::Delete)
                    .url(format!("http://{}/", addr))
                    .body(Body::empty()),
            )
            .build();
        chain.add_template_request(node3.clone());

        // Add call structure
        chain.add_call_structure(
            "test_chain",
            vec![
                "test_node_1".to_string(),
                "test_node_2".to_string(),
                "test_node_3".to_string(),
            ],
        );

        // Process the request chain
        let mut processor = RequestProcessor::new(chain);
        let variables = HashMap::new();
        let result = processor.process("test_chain", variables).await;

        // Validate the result
        match result {
            Ok(responses) => {
                assert_eq!(responses.responses.len(), 3);

                let response1 = &responses.responses[0];
                assert_eq!(response1.body, "GET response");

                let response2 = &responses.responses[1];
                assert_eq!(response2.body, "POST response");

                let response3 = &responses.responses[2];
                assert_eq!(response3.body, "DELETE response");
            }
            Err(e) => panic!("Process failed: {:?}", e),
        }

        // Shutdown the server
        shutdown_tx.send(()).unwrap();
    }

    #[tokio::test]
    async fn test_matcher_between() {
        let matcher = Matcher::between("start".to_string(), "end".to_string());
        let response = "this is the start of the match end of the string";
        let value = RequestProcessor {
            request_chain: RequestChain::new(),
            variables: HashMap::new(),
            response: ChainResponses::default(),
        }
        .match_response(response, &matcher);
        assert_eq!(value, Some(" of the match ".to_string()));
    }

    #[tokio::test]
    async fn test_matcher_regexp() {
        let matcher = Matcher::regexp(r"\d+".to_string());
        let response = "there are 42 apples";
        let value = RequestProcessor {
            request_chain: RequestChain::new(),
            variables: HashMap::new(),
            response: ChainResponses::default(),
        }
        .match_response(response, &matcher);
        // Assuming the implementation of regex matching is added
        // assert_eq!(value, Some("42".to_string()));
    }

    #[tokio::test]
    async fn test_matcher_all() {
        let matcher = Matcher::all(true);
        let response = "capture the entire string";
        let value = RequestProcessor {
            request_chain: RequestChain::new(),
            variables: HashMap::new(),
            response: ChainResponses::default(),
        }
        .match_response(response, &matcher);
        assert_eq!(value, Some(response.to_string()));
    }
}