-
Notifications
You must be signed in to change notification settings - Fork 46
/
handles.rs
4230 lines (3887 loc) · 168 KB
/
handles.rs
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
//! Handle interface wrapping Rust models for use via FFI calls.
//!
//! Example of setting up a Pact, starting a mock server and then sending requests to the mock
//! server:
//! ```
//! use std::ffi::{CStr, CString};
//! use expectest::prelude::*;
//! use reqwest::blocking::Client;
//! use pact_ffi::mock_server::handles::{
//! InteractionPart,
//! pactffi_new_interaction,
//! pactffi_new_pact,
//! pactffi_response_status,
//! pactffi_upon_receiving,
//! pactffi_with_body,
//! pactffi_with_header_v2,
//! pactffi_with_query_parameter_v2,
//! pactffi_with_request
//! };
//! use pact_ffi::mock_server::{
//! pactffi_cleanup_mock_server,
//! pactffi_create_mock_server_for_pact,
//! pactffi_mock_server_mismatches,
//! pactffi_write_pact_file
//! };
//!
//! let consumer_name = CString::new("http-consumer").unwrap();
//! let provider_name = CString::new("http-provider").unwrap();
//! let pact_handle = pactffi_new_pact(consumer_name.as_ptr(), provider_name.as_ptr());
//!
//! let description = CString::new("request_with_matchers").unwrap();
//! let interaction = pactffi_new_interaction(pact_handle.clone(), description.as_ptr());
//!
//! let special_header = CString::new("My-Special-Content-Type").unwrap();
//! let content_type = CString::new("Content-Type").unwrap();
//! let authorization = CString::new("Authorization").unwrap();
//! let path_matcher = CString::new("{\"value\":\"/request/1234\",\"pact:matcher:type\":\"regex\", \"regex\":\"\\/request\\/[0-9]+\"}").unwrap();
//! let value_header_with_matcher = CString::new("{\"value\":\"application/json\",\"pact:matcher:type\":\"dummy\"}").unwrap();
//! let auth_header_with_matcher = CString::new("{\"value\":\"Bearer 1234\",\"pact:matcher:type\":\"regex\", \"regex\":\"Bearer [0-9]+\"}").unwrap();
//! let query_param_matcher = CString::new("{\"value\":\"bar\",\"pact:matcher:type\":\"regex\", \"regex\":\"(bar|baz|bat)\"}").unwrap();
//! let request_body_with_matchers = CString::new("{\"id\": {\"value\":1,\"pact:matcher:type\":\"type\"}}").unwrap();
//! let response_body_with_matchers = CString::new("{\"created\": {\"value\":\"maybe\",\"pact:matcher:type\":\"regex\", \"regex\":\"(yes|no|maybe)\"}}").unwrap();
//! let address = CString::new("127.0.0.1:0").unwrap();
//! let file_path = CString::new("/tmp/pact").unwrap();
//! let description = CString::new("a request to test the FFI interface").unwrap();
//! let method = CString::new("POST").unwrap();
//! let query = CString::new("foo").unwrap();
//! let header = CString::new("application/json").unwrap();
//!
//! // Setup the request
//! pactffi_upon_receiving(interaction.clone(), description.as_ptr());
//! pactffi_with_request(interaction.clone(), method .as_ptr(), path_matcher.as_ptr());
//! pactffi_with_header_v2(interaction.clone(), InteractionPart::Request, content_type.as_ptr(), 0, value_header_with_matcher.as_ptr());
//! pactffi_with_header_v2(interaction.clone(), InteractionPart::Request, authorization.as_ptr(), 0, auth_header_with_matcher.as_ptr());
//! pactffi_with_query_parameter_v2(interaction.clone(), query.as_ptr(), 0, query_param_matcher.as_ptr());
//! pactffi_with_body(interaction.clone(), InteractionPart::Request, header.as_ptr(), request_body_with_matchers.as_ptr());
//!
//! // will respond with...
//! pactffi_with_header_v2(interaction.clone(), InteractionPart::Response, content_type.as_ptr(), 0, value_header_with_matcher.as_ptr());
//! pactffi_with_header_v2(interaction.clone(), InteractionPart::Response, special_header.as_ptr(), 0, value_header_with_matcher.as_ptr());
//! pactffi_with_body(interaction.clone(), InteractionPart::Response, header.as_ptr(), response_body_with_matchers.as_ptr());
//! pactffi_response_status(interaction.clone(), 200);
//!
//! // Start the mock server
//! let port = pactffi_create_mock_server_for_pact(pact_handle.clone(), address.as_ptr(), false);
//!
//! expect!(port).to(be_greater_than(0));
//!
//! // Mock server has started, we can't now modify the pact
//! expect!(pactffi_upon_receiving(interaction.clone(), description.as_ptr())).to(be_false());
//!
//! // Interact with the mock server
//! let client = Client::default();
//! let result = client.post(format!("http://127.0.0.1:{}/request/9999?foo=baz", port).as_str())
//! .header("Content-Type", "application/json")
//! .header("Authorization", "Bearer 9999")
//! .body(r#"{"id": 7}"#)
//! .send();
//!
//! match result {
//! Ok(res) => {
//! expect!(res.status()).to(be_eq(200));
//! expect!(res.headers().get("My-Special-Content-Type").unwrap()).to(be_eq("application/json"));
//! let json: serde_json::Value = res.json().unwrap_or_default();
//! expect!(json.get("created").unwrap().as_str().unwrap()).to(be_eq("maybe"));
//! }
//! Err(_) => {
//! panic!("expected 200 response but request failed");
//! }
//! };
//!
//! let mismatches = unsafe {
//! CStr::from_ptr(pactffi_mock_server_mismatches(port)).to_string_lossy().into_owned()
//! };
//!
//! // Write out the pact file, then clean up the mock server
//! pactffi_write_pact_file(port, file_path.as_ptr(), true);
//! pactffi_cleanup_mock_server(port);
//!
//! // Should be no mismatches
//! expect!(mismatches).to(be_equal_to("[]"));
//! ```
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::collections::hash_map::Entry;
use std::ffi::{CStr, CString};
use std::path::PathBuf;
use std::ptr::null_mut;
use std::str::from_utf8;
use std::sync::{Arc, Mutex};
use anyhow::anyhow;
use bytes::Bytes;
use either::Either;
use itertools::Itertools;
use lazy_static::*;
use libc::{c_char, c_int, c_uint, c_ushort, EXIT_FAILURE, EXIT_SUCCESS, size_t};
use maplit::*;
use pact_models::{Consumer, PactSpecification, Provider};
use pact_models::bodies::OptionalBody;
use pact_models::content_types::{ContentType, detect_content_type_from_string, JSON, TEXT, XML};
use pact_models::generators::{generators_from_json, Generator, Generators};
use pact_models::headers::parse_header;
use pact_models::http_parts::HttpPart;
use pact_models::interaction::Interaction;
use pact_models::json_utils::json_to_string;
use pact_models::matchingrules::{matchers_from_json, Category, MatchingRule, MatchingRuleCategory, MatchingRules, RuleLogic};
use pact_models::pact::{ReadWritePact, write_pact};
use pact_models::path_exp::DocPath;
use pact_models::prelude::Pact;
use pact_models::prelude::v4::V4Pact;
use pact_models::provider_states::ProviderState;
use pact_models::v4::async_message::AsynchronousMessage;
use pact_models::v4::interaction::V4Interaction;
use pact_models::v4::message_parts::MessageContents;
use pact_models::v4::sync_message::SynchronousMessage;
use pact_models::v4::synch_http::SynchronousHttp;
use serde_json::{json, Value};
use tracing::*;
use pact_matching::generators::generate_message;
use pact_models::generators::GeneratorTestMode;
use futures::executor::block_on;
use crate::{convert_cstr, ffi_fn, safe_str};
use crate::error::set_error_msg;
use crate::mock_server::{generator_category, StringResult, xml};
#[allow(deprecated)]
use crate::mock_server::bodies::{
empty_multipart_body,
file_as_multipart_body,
matchers_from_integration_json,
MultipartBody,
process_array,
process_json,
process_object,
request_multipart,
response_multipart,
get_content_type_hint,
part_body_replace_marker
};
use crate::models::iterators::{PactAsyncMessageIterator, PactMessageIterator, PactSyncHttpIterator, PactSyncMessageIterator};
use crate::ptr;
#[derive(Debug, Clone)]
/// Pact handle inner struct
/// cbindgen:ignore
pub struct PactHandleInner {
pub(crate) pact: V4Pact,
pub(crate) mock_server_started: bool,
pub(crate) specification_version: PactSpecification
}
lazy_static! {
static ref PACT_HANDLES: Arc<Mutex<HashMap<u16, RefCell<PactHandleInner>>>> = Arc::new(Mutex::new(hashmap![]));
}
#[repr(transparent)]
#[derive(Debug, Clone, Copy)]
/// Wraps a Pact model struct
pub struct PactHandle {
/// Pact reference
pact_ref: u16
}
#[repr(transparent)]
#[derive(Debug, Clone, Copy)]
/// Wraps a Pact model struct
pub struct InteractionHandle {
/// Interaction reference
interaction_ref: u32
}
#[repr(C)]
#[derive(Debug, Clone, Copy)]
/// Request or Response enum
pub enum InteractionPart {
/// Request part
Request = 0,
/// Response part
Response = 1
}
impl PactHandle {
/// Creates a new handle to a Pact model
pub fn new(consumer: &str, provider: &str) -> Self {
let mut pact = V4Pact {
consumer: Consumer { name: consumer.to_string() },
provider: Provider { name: provider.to_string() },
..V4Pact::default()
};
pact.add_md_version("ffi", option_env!("CARGO_PKG_VERSION").unwrap_or("unknown"));
let id = {
let mut handles = PACT_HANDLES.lock().unwrap();
let keys: HashSet<&u16> = handles.keys().collect();
let mut id: u16 = rand::random();
while keys.contains(&id) {
id = rand::random();
}
handles.insert(id, RefCell::new(PactHandleInner {
pact,
mock_server_started: false,
specification_version: PactSpecification::V3
}));
id
};
PactHandle {
pact_ref: id
}
}
/// Invokes the closure with the inner Pact model
///
/// # Errors
/// This function acquires a lock on the PACT_HANDLES mutex. If the closure panics, this mutex
/// will be poisoned. So panics must be avoided.
pub(crate) fn with_pact<R>(&self, f: &dyn Fn(u16, &mut PactHandleInner) -> R) -> Option<R> {
let mut handles = PACT_HANDLES.lock().unwrap();
trace!("with_pact - ref = {}, keys = {:?}", self.pact_ref, handles.keys());
handles.get_mut(&self.pact_ref).map(|inner| {
trace!("with_pact before - ref = {}, inner = {:?}", self.pact_ref, inner);
let result = f(self.pact_ref, &mut inner.borrow_mut());
trace!("with_pact after - ref = {}, inner = {:?}", self.pact_ref, inner);
result
})
}
}
impl InteractionHandle {
/// Creates a new handle to an Interaction
pub fn new(pact: PactHandle, interaction: u16) -> InteractionHandle {
let mut index = pact.pact_ref as u32;
index = index << 16;
index = index + interaction as u32;
InteractionHandle {
interaction_ref: index
}
}
/// Invokes the closure with the inner Pact model
///
/// # Errors
/// This function acquires a lock on the PACT_HANDLES mutex. If the closure panics, this mutex
/// will be poisoned. So panics must be avoided.
pub fn with_pact<R>(&self, f: &dyn Fn(u16, &mut PactHandleInner) -> R) -> Option<R> {
let mut handles = PACT_HANDLES.lock().unwrap();
let index = (self.interaction_ref >> 16) as u16;
handles.get_mut(&index).map(|inner| f(index, &mut inner.borrow_mut()))
}
/// Invokes the closure with the inner Interaction model
///
/// # Errors
/// This function acquires a lock on the PACT_HANDLES mutex. If the closure panics, this mutex
/// will be poisoned. So panics must be avoided.
pub fn with_interaction<R>(&self, f: &dyn Fn(u16, bool, &mut dyn V4Interaction) -> R) -> Option<R> {
let mut handles = PACT_HANDLES.lock().unwrap();
let index = (self.interaction_ref >> 16) as u16;
let interaction = (self.interaction_ref & 0x0000FFFF) as u16;
trace!("with_interaction - index = {}, interaction = {}", index, interaction);
trace!("with_interaction - keys = {:?}", handles.keys());
handles.get_mut(&index).map(|inner| {
let inner_mut = &mut *inner.borrow_mut();
trace!("with_interaction - inner = {:?}", inner_mut);
let interactions = &mut inner_mut.pact.interactions;
match interactions.get_mut((interaction - 1) as usize) {
Some(inner_i) => {
Some(f(interaction - 1, inner_mut.mock_server_started, inner_i.as_mut()))
},
None => {
debug!("Did not find interaction for index = {}, interaction = {}, pact has {} interactions",
index, interaction, interactions.len());
None
}
}
}).flatten()
}
}
#[repr(transparent)]
#[derive(Debug, Clone, Copy)]
/// Wraps a Pact model struct
pub struct MessagePactHandle {
/// Pact reference
pact_ref: u16
}
#[repr(transparent)]
#[derive(Debug, Clone, Copy)]
/// Wraps a Pact model struct
pub struct MessageHandle {
/// Interaction reference
interaction_ref: u32
}
impl MessagePactHandle {
/// Creates a new handle to a Pact model
pub fn new(consumer: &str, provider: &str) -> Self {
let mut pact = V4Pact {
consumer: Consumer { name: consumer.to_string() },
provider: Provider { name: provider.to_string() },
..V4Pact::default()
};
pact.add_md_version("ffi", option_env!("CARGO_PKG_VERSION").unwrap_or("unknown"));
let id = {
let mut handles = PACT_HANDLES.lock().unwrap();
let keys: HashSet<&u16> = handles.keys().collect();
let mut id: u16 = rand::random();
while keys.contains(&id) {
id = rand::random();
}
handles.insert(id, RefCell::new(PactHandleInner {
pact,
mock_server_started: false,
specification_version: PactSpecification::V3
}));
id
};
MessagePactHandle {
pact_ref: id
}
}
/// Invokes the closure with the inner model
pub fn with_pact<R>(&self, f: &dyn Fn(u16, &mut V4Pact, PactSpecification) -> R) -> Option<R> {
let mut handles = PACT_HANDLES.lock().unwrap();
handles.get_mut(&self.pact_ref).map(|inner| {
let mut ref_mut = inner.borrow_mut();
let specification = ref_mut.specification_version;
f(self.pact_ref, &mut ref_mut.pact, specification)
})
}
}
impl MessageHandle {
/// Creates a new handle to a message
pub fn new(pact: MessagePactHandle, message: u16) -> MessageHandle {
let mut index = pact.pact_ref as u32;
index = index << 16;
index = index + message as u32;
MessageHandle {
interaction_ref: index
}
}
/// Creates a new handle to a message
pub fn new_v4(pact: PactHandle, message: usize) -> MessageHandle {
let mut index = pact.pact_ref as u32;
index = index << 16;
index = index + message as u32;
MessageHandle {
interaction_ref: index
}
}
/// Invokes the closure with the inner model
pub fn with_pact<R>(&self, f: &dyn Fn(u16, &mut V4Pact, PactSpecification) -> R) -> Option<R> {
let mut handles = PACT_HANDLES.lock().unwrap();
let index = (self.interaction_ref >> 16) as u16;
handles.get_mut(&index).map(|inner| {
let mut ref_mut = inner.borrow_mut();
let specification = ref_mut.specification_version;
f(index, &mut ref_mut.pact, specification)
})
}
/// Invokes the closure with the inner Interaction model
pub fn with_message<R>(&self, f: &dyn Fn(u16, &mut dyn V4Interaction, PactSpecification) -> R) -> Option<R> {
let mut handles = PACT_HANDLES.lock().unwrap();
let index = (self.interaction_ref >> 16) as u16;
let interaction = self.interaction_ref as u16;
handles.get_mut(&index).map(|inner| {
let mut ref_mut = inner.borrow_mut();
let specification = ref_mut.specification_version;
ref_mut.pact.interactions.get_mut((interaction - 1) as usize)
.map(|inner_i| {
if inner_i.is_message() {
Some(f(interaction - 1, inner_i.as_mut(), specification))
} else {
error!("Interaction {:#x} is not a message interaction, it is {}", self.interaction_ref, inner_i.type_of());
None
}
}).flatten()
}).flatten()
}
}
/// Creates a new Pact model and returns a handle to it.
///
/// * `consumer_name` - The name of the consumer for the pact.
/// * `provider_name` - The name of the provider for the pact.
///
/// Returns a new `PactHandle`. The handle will need to be freed with the `pactffi_free_pact_handle`
/// method to release its resources.
#[no_mangle]
pub extern fn pactffi_new_pact(consumer_name: *const c_char, provider_name: *const c_char) -> PactHandle {
let consumer = convert_cstr("consumer_name", consumer_name).unwrap_or("Consumer");
let provider = convert_cstr("provider_name", provider_name).unwrap_or("Provider");
PactHandle::new(consumer, provider)
}
ffi_fn! {
/// Returns a mutable pointer to a Pact model which has been cloned from the Pact handle's inner
/// Pact model. The returned Pact model must be freed with the `pactffi_pact_model_delete`
/// function when no longer needed.
fn pactffi_pact_handle_to_pointer(pact: PactHandle) -> *mut crate::models::Pact {
pact.with_pact(&|_, inner| {
ptr::raw_to(crate::models::Pact::new(inner.pact.boxed()))
}).unwrap_or(std::ptr::null_mut())
} {
std::ptr::null_mut()
}
}
fn find_interaction_with_description(pact: &V4Pact, description: &str) -> Option<usize> {
pact.interactions.iter().find_position(|i| {
i.description() == description
}).map(|(index, _)| index)
}
/// Creates a new HTTP Interaction and returns a handle to it. Calling this function with the
/// same description as an existing interaction will result in that interaction being replaced
/// with the new one.
///
/// * `description` - The interaction description. It needs to be unique for each interaction.
///
/// Returns a new `InteractionHandle`.
#[no_mangle]
pub extern fn pactffi_new_interaction(pact: PactHandle, description: *const c_char) -> InteractionHandle {
if let Some(description) = convert_cstr("description", description) {
pact.with_pact(&|_, inner| {
let interaction = SynchronousHttp {
description: description.to_string(),
..SynchronousHttp::default()
};
if let Some(index) = find_interaction_with_description(&inner.pact, description) {
warn!("There is an existing interaction with description '{}', it will be replaced", description);
inner.pact.interactions[index] = interaction.boxed_v4();
InteractionHandle::new(pact, (index + 1) as u16)
} else {
inner.pact.interactions.push(interaction.boxed_v4());
InteractionHandle::new(pact, inner.pact.interactions.len() as u16)
}
}).unwrap_or_else(|| InteractionHandle::new(pact, 0))
} else {
InteractionHandle::new(pact, 0)
}
}
/// Creates a new message interaction and returns a handle to it. Calling this function with the
/// same description as an existing interaction will result in that interaction being replaced
/// with the new one.
///
/// * `description` - The interaction description. It needs to be unique for each interaction.
///
/// Returns a new `InteractionHandle`.
#[no_mangle]
pub extern fn pactffi_new_message_interaction(pact: PactHandle, description: *const c_char) -> InteractionHandle {
if let Some(description) = convert_cstr("description", description) {
pact.with_pact(&|_, inner| {
let interaction = AsynchronousMessage {
description: description.to_string(),
..AsynchronousMessage::default()
};
if let Some(index) = find_interaction_with_description(&inner.pact, description) {
warn!("There is an existing interaction with description '{}', it will be replaced", description);
inner.pact.interactions[index] = interaction.boxed_v4();
InteractionHandle::new(pact, (index + 1) as u16)
} else {
inner.pact.interactions.push(interaction.boxed_v4());
InteractionHandle::new(pact, inner.pact.interactions.len() as u16)
}
}).unwrap_or_else(|| InteractionHandle::new(pact, 0))
} else {
InteractionHandle::new(pact, 0)
}
}
/// Creates a new synchronous message interaction (request/response) and returns a handle to it.
/// Calling this function with the same description as an existing interaction will result in
/// that interaction being replaced with the new one.
///
/// * `description` - The interaction description. It needs to be unique for each interaction.
///
/// Returns a new `InteractionHandle`.
#[no_mangle]
pub extern fn pactffi_new_sync_message_interaction(pact: PactHandle, description: *const c_char) -> InteractionHandle {
if let Some(description) = convert_cstr("description", description) {
pact.with_pact(&|_, inner| {
let interaction = SynchronousMessage {
description: description.to_string(),
..SynchronousMessage::default()
};
if let Some(index) = find_interaction_with_description(&inner.pact, description) {
warn!("There is an existing interaction with description '{}', it will be replaced", description);
inner.pact.interactions[index] = interaction.boxed_v4();
InteractionHandle::new(pact, (index + 1) as u16)
} else {
inner.pact.interactions.push(interaction.boxed_v4());
InteractionHandle::new(pact, inner.pact.interactions.len() as u16)
}
}).unwrap_or_else(|| InteractionHandle::new(pact, 0))
} else {
InteractionHandle::new(pact, 0)
}
}
/// Sets the description for the Interaction. Returns false if the interaction or Pact can't be
/// modified (i.e. the mock server for it has already started)
///
/// * `description` - The interaction description. It needs to be unique for each interaction.
#[no_mangle]
pub extern fn pactffi_upon_receiving(interaction: InteractionHandle, description: *const c_char) -> bool {
if let Some(description) = convert_cstr("description", description) {
interaction.with_interaction(&|_, mock_server_started, inner| {
inner.set_description(description);
!mock_server_started
}).unwrap_or(false)
} else {
false
}
}
/// Adds a provider state to the Interaction. Returns false if the interaction or Pact can't be
/// modified (i.e. the mock server for it has already started)
///
/// * `description` - The provider state description. It needs to be unique.
#[no_mangle]
pub extern fn pactffi_given(interaction: InteractionHandle, description: *const c_char) -> bool {
if let Some(description) = convert_cstr("description", description) {
interaction.with_interaction(&|_, mock_server_started, inner| {
inner.provider_states_mut().push(ProviderState::default(&description.to_string()));
!mock_server_started
}).unwrap_or(false)
} else {
false
}
}
ffi_fn! {
/// Sets the test name annotation for the interaction. This allows capturing the name of
/// the test as metadata. This can only be used with V4 interactions.
///
/// # Safety
///
/// The test name parameter must be a valid pointer to a NULL terminated string.
///
/// # Error Handling
///
/// If the test name can not be set, this will return a positive value.
///
/// * `1` - Function panicked. Error message will be available by calling `pactffi_get_error_message`.
/// * `2` - Handle was not valid.
/// * `3` - Mock server was already started and the integration can not be modified.
/// * `4` - Not a V4 interaction.
fn pactffi_interaction_test_name(interaction: InteractionHandle, test_name: *const c_char) -> c_uint {
let test_name = safe_str!(test_name);
interaction.with_interaction(&|_, started, inner| {
if !started {
if let Some(i) = inner.as_v4_mut() {
i.comments_mut().insert("testname".to_string(), json!(test_name));
0
} else {
4
}
} else {
3
}
}).unwrap_or(2)
} {
1
}
}
/// Adds a parameter key and value to a provider state to the Interaction. If the provider state
/// does not exist, a new one will be created, otherwise the parameter will be merged into the
/// existing one. The parameter value will be parsed as JSON.
///
/// Returns false if the interaction or Pact can't be modified (i.e. the mock server for it has
/// already started).
///
/// # Parameters
/// * `description` - The provider state description. It needs to be unique.
/// * `name` - Parameter name.
/// * `value` - Parameter value as JSON.
#[no_mangle]
pub extern fn pactffi_given_with_param(interaction: InteractionHandle, description: *const c_char,
name: *const c_char, value: *const c_char) -> bool {
if let Some(description) = convert_cstr("description", description) {
if let Some(name) = convert_cstr("name", name) {
let value = convert_cstr("value", value).unwrap_or_default();
interaction.with_interaction(&|_, mock_server_started, inner| {
let value = match serde_json::from_str(value) {
Ok(json) => json,
Err(_) => json!(value)
};
match inner.provider_states().iter().find_position(|state| state.name == description) {
Some((index, _)) => {
inner.provider_states_mut().get_mut(index).unwrap().params.insert(name.to_string(), value);
},
None => inner.provider_states_mut().push(ProviderState {
name: description.to_string(),
params: hashmap!{ name.to_string() => value }
})
};
!mock_server_started
}).unwrap_or(false)
} else {
false
}
} else {
false
}
}
/// Adds a provider state to the Interaction with a set of parameter key and value pairs in JSON
/// form. If the params is not an JSON object, it will add it as a single parameter with a `value`
/// key.
///
/// # Parameters
/// * `description` - The provider state description.
/// * `params` - Parameter values as a JSON fragment.
///
/// # Errors
/// Returns EXIT_FAILURE (1) if the interaction or Pact can't be modified (i.e. the mock server
/// for it has already started).
/// Returns 2 and sets the error message (which can be retrieved with `pactffi_get_error_message`)
/// if the parameter values con't be parsed as JSON.
/// Returns 3 if any of the C strings are not valid.
///
#[no_mangle]
pub extern fn pactffi_given_with_params(
interaction: InteractionHandle,
description: *const c_char,
params: *const c_char
) -> c_int {
if let Some(description) = convert_cstr("description", description) {
if let Some(params) = convert_cstr("params", params) {
let params_value = match serde_json::from_str(params) {
Ok(json) => json,
Err(err) => {
error!("Parameters are not valid JSON: {}", err);
set_error_msg(err.to_string());
return 2;
}
};
let params_map = match params_value {
Value::Object(map) => map.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect(),
_ => hashmap! { "value".to_string() => params_value }
};
interaction.with_interaction(&|_, mock_server_started, inner| {
inner.provider_states_mut().push(ProviderState {
name: description.to_string(),
params: params_map.clone()
});
if mock_server_started { EXIT_FAILURE } else { EXIT_SUCCESS }
}).unwrap_or(EXIT_FAILURE)
} else {
3
}
} else {
3
}
}
/// Configures the request for the Interaction. Returns false if the interaction or Pact can't be
/// modified (i.e. the mock server for it has already started)
///
/// * `method` - The request method. Defaults to GET.
/// * `path` - The request path. Defaults to `/`.
///
/// To include matching rules for the path (only regex really makes sense to use), include the
/// matching rule JSON format with the value as a single JSON document. I.e.
///
/// ```c
/// const char* value = "{\"value\":\"/path/to/100\", \"pact:matcher:type\":\"regex\", \"regex\":\"\\/path\\/to\\/\\\\d+\"}";
/// pactffi_with_request(handle, "GET", value);
/// ```
/// See [IntegrationJson.md](https://github.com/pact-foundation/pact-reference/blob/master/rust/pact_ffi/IntegrationJson.md)
#[no_mangle]
pub extern fn pactffi_with_request(
interaction: InteractionHandle,
method: *const c_char,
path: *const c_char
) -> bool {
let method = convert_cstr("method", method).unwrap_or("GET");
let path = convert_cstr("path", path).unwrap_or("/");
interaction.with_interaction(&|_, mock_server_started, inner| {
if let Some(reqres) = inner.as_v4_http_mut() {
let path = from_integration_json_v2(&mut reqres.request.matching_rules,
&mut reqres.request.generators, &path.to_string(), DocPath::empty(), "path", 0);
reqres.request.method = method.to_string();
reqres.request.path = match path {
Either::Left(value) => value,
Either::Right(values) => {
warn!("Received multiple values for the path ({:?}), will only use the first one", values);
values.first().cloned().unwrap_or_default()
}
};
!mock_server_started
} else {
error!("Interaction is not an HTTP interaction, is {}", inner.type_of());
false
}
}).unwrap_or(false)
}
/// Configures a query parameter for the Interaction. Returns false if the interaction or Pact can't be
/// modified (i.e. the mock server for it has already started)
///
/// * `name` - the query parameter name.
/// * `value` - the query parameter value.
/// * `index` - the index of the value (starts at 0). You can use this to create a query parameter with multiple values
///
/// **DEPRECATED:** Use `pactffi_with_query_parameter_v2`, which deals with multiple values correctly
#[no_mangle]
#[deprecated]
pub extern fn pactffi_with_query_parameter(
interaction: InteractionHandle,
name: *const c_char,
index: size_t,
value: *const c_char
) -> bool {
if let Some(name) = convert_cstr("name", name) {
let value = convert_cstr("value", value).unwrap_or_default();
interaction.with_interaction(&|_, mock_server_started, inner| {
if let Some(reqres) = inner.as_v4_http_mut() {
reqres.request.query = reqres.request.query.clone().map(|mut q| {
let mut path = DocPath::root();
path.push_field(name).push_index(index);
#[allow(deprecated)]
let value = from_integration_json(&mut reqres.request.matching_rules, &mut reqres.request.generators, &value.to_string(), path, "query");
if q.contains_key(name) {
let values = q.get_mut(name).unwrap();
if index >= values.len() {
values.resize_with(index + 1, Default::default);
}
values[index] = Some(value);
} else {
let mut values: Vec<Option<String>> = Vec::new();
values.resize_with(index + 1, Default::default);
values[index] = Some(value);
q.insert(name.to_string(), values);
};
q
}).or_else(|| {
let mut path = DocPath::root();
path.push_field(name).push_index(index);
#[allow(deprecated)]
let value = from_integration_json(&mut reqres.request.matching_rules, &mut reqres.request.generators, &value.to_string(), path, "query");
let mut values: Vec<Option<String>> = Vec::new();
values.resize_with(index + 1, Default::default);
values[index] = Some(value);
Some(hashmap! { name.to_string() => values })
});
!mock_server_started
} else {
error!("Interaction is not an HTTP interaction, is {}", inner.type_of());
false
}
}).unwrap_or(false)
} else {
warn!("Ignoring query parameter with empty or null name");
false
}
}
/// Configures a query parameter for the Interaction. Returns false if the interaction or Pact can't be
/// modified (i.e. the mock server for it has already started)
///
/// * `name` - the query parameter name.
/// * `value` - the query parameter value. Either a simple string or a JSON document.
/// * `index` - the index of the value (starts at 0). You can use this to create a query parameter with multiple values
///
/// To setup a query parameter with multiple values, you can either call this function multiple times
/// with a different index value, i.e. to create `id=2&id=3`
///
/// ```c
/// pactffi_with_query_parameter_v2(handle, "id", 0, "2");
/// pactffi_with_query_parameter_v2(handle, "id", 1, "3");
/// ```
///
/// Or you can call it once with a JSON value that contains multiple values:
///
/// ```c
/// const char* value = "{\"value\": [\"2\",\"3\"]}";
/// pactffi_with_query_parameter_v2(handle, "id", 0, value);
/// ```
///
/// To include matching rules for the query parameter, include the matching rule JSON format with
/// the value as a single JSON document. I.e.
///
/// ```c
/// const char* value = "{\"value\":\"2\", \"pact:matcher:type\":\"regex\", \"regex\":\"\\\\d+\"}";
/// pactffi_with_query_parameter_v2(handle, "id", 0, value);
/// ```
/// See [IntegrationJson.md](https://github.com/pact-foundation/pact-reference/blob/master/rust/pact_ffi/IntegrationJson.md)
///
/// If you want the matching rules to apply to all values (and not just the one with the given
/// index), make sure to set the value to be an array.
///
/// ```c
/// const char* value = "{\"value\":[\"2\"], \"pact:matcher:type\":\"regex\", \"regex\":\"\\\\d+\"}";
/// pactffi_with_query_parameter_v2(handle, "id", 0, value);
/// ```
///
/// For query parameters with no value, two distinct formats are provided:
///
/// 1. Parameters with blank values, as specified by `?foo=&bar=`, require an empty string:
///
/// ```c
/// pactffi_with_query_parameter_v2(handle, "foo", 0, "");
/// pactffi_with_query_parameter_v2(handle, "bar", 0, "");
/// ```
///
/// 2. Parameters with no associated value, as specified by `?foo&bar`, require a NULL pointer:
///
/// ```c
/// pactffi_with_query_parameter_v2(handle, "foo", 0, NULL);
/// pactffi_with_query_parameter_v2(handle, "bar", 0, NULL);
/// ```
///
/// # Safety
/// The name parameter must be a valid pointer to a NULL terminated string. If the value
/// parameter is not NULL, it must point to a valid NULL terminated string.
/// ```
#[no_mangle]
pub extern fn pactffi_with_query_parameter_v2(
interaction: InteractionHandle,
name: *const c_char,
index: size_t,
value: *const c_char
) -> bool {
if let Some(name) = convert_cstr("name", name) {
let value = convert_cstr("value", value);
trace!(?interaction, name, index, value, "pactffi_with_query_parameter_v2 called");
interaction.with_interaction(&|_, mock_server_started, inner| {
if let Some(reqres) = inner.as_v4_http_mut() {
let mut path = DocPath::root();
path.push_field(name);
if index > 0 {
path.push_index(index);
}
if let Some(value) = value {
let value = from_integration_json_v2(
&mut reqres.request.matching_rules,
&mut reqres.request.generators,
value,
path,
"query",
index
);
match value {
Either::Left(value) => {
reqres.request.query = update_query_map(index, name, reqres, Some(value));
}
Either::Right(values) => if index == 0 {
reqres.request.query = reqres.request.query.clone().map(|mut q| {
let values = values.iter().map(|v| Some(v.clone())).collect_vec();
if q.contains_key(name) {
let vec = q.get_mut(name).unwrap();
vec.extend_from_slice(&values);
} else {
q.insert(name.to_string(), values);
};
q
}).or_else(|| Some(hashmap! {
name.to_string() => values.iter().map(|v| Some(v.clone())).collect_vec()
}))
} else {
reqres.request.query = update_query_map(index, name, reqres, values.first().cloned());
}
}
} else {
reqres.request.query = update_query_map(index, name, reqres, None);
}
!mock_server_started
} else {
error!("Interaction is not an HTTP interaction, is {}", inner.type_of());
false
}
}).unwrap_or(false)
} else {
warn!("Ignoring query parameter with empty or null name");
false
}
}
fn update_query_map(
index: size_t,
name: &str,
reqres: &mut SynchronousHttp,
value: Option<String>
) -> Option<HashMap<String, Vec<Option<String>>>> {
reqres.request.query.clone().map(|mut q| {
if let Some(entry) = q.get_mut(name) {
if index >= entry.len() {
entry.resize_with(index + 1, Default::default);
}
entry[index] = value.clone();
} else {
let mut values: Vec<Option<String>> = Vec::new();
values.resize_with(index + 1, Default::default);
values[index] = value.clone();
q.insert(name.to_string(), values);
};
q
}).or_else(|| {
let mut values: Vec<Option<String>> = Vec::new();
values.resize_with(index + 1, Default::default);
values[index] = value;
Some(hashmap! { name.to_string() => values })
})
}
/// Convert JSON matching rule structures into their internal representation (excl. bodies)
///
/// For non-body values (headers, query, path etc.) extract out the value from any matchers
/// and apply the matchers/generators to the model.
///
/// Will either return a single value, or a vector if the JSON represents multiple values.
#[deprecated]
fn from_integration_json(
rules: &mut MatchingRules,
generators: &mut Generators,
value: &str,
path: DocPath,
category: &str,
) -> String {
let category = rules.add_category(category);
match serde_json::from_str(value) {
Ok(json) => match json {
Value::Object(map) => {
let json: Value = process_object(&map, category, generators, path, false);
// These are simple JSON primitives (strings), so we must unescape them
json_to_string(&json)
},
_ => value.to_string()
},
Err(_) => value.to_string()
}
}
/// Convert JSON matching rule structures into their internal representation (excl. bodies)
///
/// For non-body values (headers, query, path etc.) extract out the value from any matchers
/// and apply the matchers/generators to the model.
///
/// Will either return a single value, or a vector if the JSON represents multiple values.
fn from_integration_json_v2(
rules: &mut MatchingRules,
generators: &mut Generators,
value: &str,
path: DocPath,
category: &str,
index: usize
) -> Either<String, Vec<String>> {
trace!(value, %path, category, index, "from_integration_json_v2 called");
let matching_rules = rules.add_category(category);
let path_or_status = [Category::PATH, Category::STATUS].contains(&matching_rules.name);
let query_or_header = [Category::QUERY, Category::HEADER].contains(&matching_rules.name);