-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathpact_broker.rs
2395 lines (2212 loc) · 90.4 KB
/
pact_broker.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
//! Structs and functions for interacting with a Pact Broker
use std::collections::HashMap;
use std::ops::Not;
use std::panic::RefUnwindSafe;
use std::str::from_utf8;
use anyhow::anyhow;
use futures::stream::*;
use itertools::Itertools;
use maplit::hashmap;
use pact_models::http_utils;
use pact_models::http_utils::HttpAuth;
use pact_models::json_utils::json_to_string;
use pact_models::pact::{load_pact_from_json, Pact};
use regex::{Captures, Regex};
use reqwest::{Method, Url};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use serde_with::skip_serializing_none;
use tracing::{debug, error, info, trace, warn};
use pact_matching::Mismatch;
use crate::{MismatchResult, VERIFIER_VERSION};
use crate::metrics::VerificationMetrics;
use crate::utils::with_retries;
fn is_true(object: &serde_json::Map<String, Value>, field: &str) -> bool {
match object.get(field) {
Some(json) => match *json {
serde_json::Value::Bool(b) => b,
_ => false
},
None => false
}
}
fn as_string(json: &Value) -> String {
match *json {
serde_json::Value::String(ref s) => s.clone(),
_ => format!("{}", json)
}
}
fn content_type(response: &reqwest::Response) -> String {
match response.headers().get("content-type") {
Some(value) => value.to_str().unwrap_or("text/plain").into(),
None => "text/plain".to_string()
}
}
fn json_content_type(response: &reqwest::Response) -> bool {
match content_type(response).parse::<mime::Mime>() {
Ok(mime) => {
match (mime.type_().as_str(), mime.subtype().as_str(), mime.suffix()) {
("application", "json", None) => true,
("application", "hal", Some(mime::JSON)) => true,
_ => false
}
}
Err(_) => false
}
}
fn find_entry(map: &serde_json::Map<String, Value>, key: &str) -> Option<(String, Value)> {
match map.keys().find(|k| k.to_lowercase() == key.to_lowercase() ) {
Some(k) => map.get(k).map(|v| (key.to_string(), v.clone()) ),
None => None
}
}
/// Errors that can occur with a Pact Broker
#[derive(Debug, Clone, thiserror::Error)]
pub enum PactBrokerError {
/// Error with a HAL link
#[error("Error with a HAL link - {0}")]
LinkError(String),
/// Error with the content of a HAL resource
#[error("Error with the content of a HAL resource - {0}")]
ContentError(String),
#[error("IO Error - {0}")]
/// IO Error
IoError(String),
/// Link/Resource was not found
#[error("Link/Resource was not found - {0}")]
NotFound(String),
/// Invalid URL
#[error("Invalid URL - {0}")]
UrlError(String),
/// Validation error
#[error("failed validation - {0:?}")]
ValidationError(Vec<String>)
}
impl PartialEq<String> for PactBrokerError {
fn eq(&self, other: &String) -> bool {
let mut buffer = String::new();
match self {
PactBrokerError::LinkError(s) => buffer.push_str(s),
PactBrokerError::ContentError(s) => buffer.push_str(s),
PactBrokerError::IoError(s) => buffer.push_str(s),
PactBrokerError::NotFound(s) => buffer.push_str(s),
PactBrokerError::UrlError(s) => buffer.push_str(s),
PactBrokerError::ValidationError(errors) => buffer.push_str(errors.iter().join(", ").as_str())
};
buffer == *other
}
}
impl <'a> PartialEq<&'a str> for PactBrokerError {
fn eq(&self, other: &&str) -> bool {
let message = match self {
PactBrokerError::LinkError(s) => s.clone(),
PactBrokerError::ContentError(s) => s.clone(),
PactBrokerError::IoError(s) => s.clone(),
PactBrokerError::NotFound(s) => s.clone(),
PactBrokerError::UrlError(s) => s.clone(),
PactBrokerError::ValidationError(errors) => errors.iter().join(", ")
};
message.as_str() == *other
}
}
impl From<url::ParseError> for PactBrokerError {
fn from(err: url::ParseError) -> Self {
PactBrokerError::UrlError(format!("{}", err))
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
/// Structure to represent a HAL link
pub struct Link {
/// Link name
pub name: String,
/// Link HREF
pub href: Option<String>,
/// If the link is templated (has expressions in the HREF that need to be expanded)
pub templated: bool,
/// Link title
pub title: Option<String>
}
impl Link {
/// Create a link from serde JSON data
pub fn from_json(link: &str, link_data: &serde_json::Map<String, serde_json::Value>) -> Link {
Link {
name: link.to_string(),
href: find_entry(link_data, &"href".to_string())
.map(|(_, href)| as_string(&href)),
templated: is_true(link_data, "templated"),
title: link_data.get("title").map(|title| as_string(title))
}
}
/// Converts the Link into a JSON representation
pub fn as_json(&self) -> serde_json::Value {
match (self.href.clone(), self.title.clone()) {
(Some(href), Some(title)) => json!({
"href": href,
"title": title,
"templated": self.templated
}),
(Some(href), None) => json!({
"href": href,
"templated": self.templated
}),
(None, Some(title)) => json!({
"title": title,
"templated": self.templated
}),
(None, None) => json!({
"templated": self.templated
})
}
}
}
impl Default for Link {
fn default() -> Self {
Link {
name: "link".to_string(),
href: None,
templated: false,
title: None
}
}
}
/// HAL aware HTTP client
#[derive(Clone)]
pub struct HALClient {
client: reqwest::Client,
url: String,
path_info: Option<Value>,
auth: Option<HttpAuth>,
retries: u8
}
impl HALClient {
/// Initialise a client with the URL and authentication
pub fn with_url(url: &str, auth: Option<HttpAuth>) -> HALClient {
HALClient { url: url.to_string(), auth, ..HALClient::default() }
}
fn update_path_info(self, path_info: serde_json::Value) -> HALClient {
HALClient {
client: self.client.clone(),
url: self.url.clone(),
path_info: Some(path_info),
auth: self.auth,
retries: self.retries
}
}
/// Navigate to the resource from the link name
pub async fn navigate(
self,
link: &'static str,
template_values: &HashMap<String, String>
) -> Result<HALClient, PactBrokerError> {
trace!("navigate(link='{}', template_values={:?})", link, template_values);
let client = if self.path_info.is_none() {
let path_info = self.clone().fetch("/".into()).await?;
self.update_path_info(path_info)
} else {
self
};
let path_info = client.clone().fetch_link(link, template_values).await?;
let client = client.update_path_info(path_info);
Ok(client)
}
fn find_link(&self, link: &'static str) -> Result<Link, PactBrokerError> {
match self.path_info {
None => Err(PactBrokerError::LinkError(format!("No previous resource has been fetched from the pact broker. URL: '{}', LINK: '{}'",
self.url, link))),
Some(ref json) => match json.get("_links") {
Some(json) => match json.get(link) {
Some(link_data) => link_data.as_object()
.map(|link_data| Link::from_json(&link.to_string(), &link_data))
.ok_or_else(|| PactBrokerError::LinkError(format!("Link is malformed, expected an object but got {}. URL: '{}', LINK: '{}'",
link_data, self.url, link))),
None => Err(PactBrokerError::LinkError(format!("Link '{}' was not found in the response, only the following links where found: {:?}. URL: '{}', LINK: '{}'",
link, json.as_object().unwrap_or(&json!({}).as_object().unwrap()).keys().join(", "), self.url, link)))
},
None => Err(PactBrokerError::LinkError(format!("Expected a HAL+JSON response from the pact broker, but got a response with no '_links'. URL: '{}', LINK: '{}'",
self.url, link)))
}
}
}
async fn fetch_link(
self,
link: &'static str,
template_values: &HashMap<String, String>
) -> Result<Value, PactBrokerError> {
trace!("fetch_link(link='{}', template_values={:?})", link, template_values);
let link_data = self.find_link(link)?;
self.fetch_url(&link_data, template_values).await
}
/// Fetch the resource at the Link from the Pact broker
pub async fn fetch_url(
self,
link: &Link,
template_values: &HashMap<String, String>
) -> Result<Value, PactBrokerError> {
trace!("fetch_url(link={:?}, template_values={:?})", link, template_values);
let link_url = if link.templated {
debug!("Link URL is templated");
self.clone().parse_link_url(&link, &template_values)
} else {
link.href.clone()
.ok_or_else(|| PactBrokerError::LinkError(
format!("Link is malformed, there is no href. URL: '{}', LINK: '{}'", self.url, link.name)
))
}?;
let base_url = self.url.parse::<Url>()?;
let joined_url = base_url.join(&link_url)?;
self.fetch(joined_url.path().into()).await
}
async fn fetch(self, path: &str) -> Result<Value, PactBrokerError> {
info!("Fetching path '{}' from pact broker", path);
let broker_url = self.url.parse::<Url>()?;
let context_path = broker_url.path();
let url = if context_path.is_empty().not() && context_path != "/" && path.starts_with(context_path) {
let mut base_url = broker_url.clone();
base_url.set_path("/");
base_url.join(path)?
} else {
broker_url.join(path)?
};
let request_builder = match self.auth {
Some(ref auth) => match auth {
HttpAuth::User(username, password) => self.client.get(url).basic_auth(username, password.clone()),
HttpAuth::Token(token) => self.client.get(url).bearer_auth(token),
_ => self.client.get(url)
},
None => self.client.get(url)
}.header("accept", "application/hal+json, application/json");
let response = with_retries(self.retries, request_builder).await
.map_err(|err| {
PactBrokerError::IoError(format!("Failed to access pact broker path '{}' - {}. URL: '{}'",
&path,
err,
&self.url,
))
})?;
self.parse_broker_response(path.to_string(), response)
.await
}
async fn parse_broker_response(
&self,
path: String,
response: reqwest::Response,
) -> Result<Value, PactBrokerError> {
let is_json_content_type = json_content_type(&response);
let content_type = content_type(&response);
let status_code = response.status();
if status_code.is_success() {
if is_json_content_type {
response.json::<Value>()
.await
.map_err(|err| PactBrokerError::ContentError(
format!("Did not get a valid HAL response body from pact broker path '{}' - {}. URL: '{}'",
path, err, self.url)
))
} else {
debug!("Request from broker was a success, but the response body was not JSON");
Err(PactBrokerError::ContentError(
format!("Did not get a valid HAL response body from pact broker path '{}', content type is '{}'. URL: '{}'",
path, content_type, self.url)
))
}
} else if status_code.as_u16() == 404 {
Err(PactBrokerError::NotFound(
format!("Request to pact broker path '{}' failed: {}. URL: '{}'", path,
status_code, self.url
)
))
} else if status_code.as_u16() == 400 {
let body = response.bytes()
.await
.map_err(|_| PactBrokerError::IoError(
format!("Failed to download response body for path '{}'. URL: '{}'", &path, self.url)
))?;
if is_json_content_type {
let errors = serde_json::from_slice(&body)
.map_err(|err| PactBrokerError::ContentError(
format!("Did not get a valid HAL response body from pact broker path '{}' - {}. URL: '{}'",
path, err, self.url)
))?;
Err(handle_validation_errors(errors))
} else {
let body = from_utf8(&body)
.map(|b| b.to_string())
.unwrap_or_else(|err| format!("could not read body: {}", err));
error!("Request to pact broker path '{}' failed: {}", path, body);
Err(PactBrokerError::IoError(
format!("Request to pact broker path '{}' failed: {}. URL: '{}'", path,
status_code, self.url
)
))
}
} else {
Err(PactBrokerError::IoError(
format!("Request to pact broker path '{}' failed: {}. URL: '{}'", path,
status_code, self.url)
))
}
}
fn parse_link_url(&self, link: &Link, values: &HashMap<String, String>) -> Result<String, PactBrokerError> {
match link.href {
Some(ref href) => {
debug!("templated URL = {}", href);
let re = Regex::new(r"\{(\w+)}").unwrap();
let final_url = re.replace_all(href, |caps: &Captures| {
let lookup = caps.get(1).unwrap().as_str();
trace!("Looking up value for key '{}'", lookup);
match values.get(lookup) {
Some(val) => urlencoding::encode(val.as_str()).to_string(),
None => {
warn!("No value was found for key '{}', mapped values are {:?}", lookup, values);
format!("{{{}}}", lookup)
}
}
});
debug!("final URL = {}", final_url);
Ok(final_url.to_string())
},
None => Err(PactBrokerError::LinkError(
format!("Expected a HAL+JSON response from the pact broker, but got a link with no HREF. URL: '{}', LINK: '{}'",
self.url, link.name)))
}
}
/// Iterate over all the links by name
pub fn iter_links(&self, link: &str) -> Result<Vec<Link>, PactBrokerError> {
match self.path_info {
None => Err(PactBrokerError::LinkError(format!("No previous resource has been fetched from the pact broker. URL: '{}', LINK: '{}'",
self.url, link))),
Some(ref json) => match json.get("_links") {
Some(json) => match json.get(&link) {
Some(link_data) => link_data.as_array()
.map(|link_data| link_data.iter().map(|link_json| match link_json {
Value::Object(data) => Link::from_json(&link, data),
Value::String(s) => Link { name: link.to_string(), href: Some(s.clone()), templated: false, title: None },
_ => Link { name: link.to_string(), href: Some(link_json.to_string()), templated: false, title: None }
}).collect())
.ok_or_else(|| PactBrokerError::LinkError(format!("Link is malformed, expected an object but got {}. URL: '{}', LINK: '{}'",
link_data, self.url, link))),
None => Err(PactBrokerError::LinkError(format!("Link '{}' was not found in the response, only the following links where found: {:?}. URL: '{}', LINK: '{}'",
link, json.as_object().unwrap_or(&json!({}).as_object().unwrap()).keys().join(", "), self.url, link)))
},
None => Err(PactBrokerError::LinkError(format!("Expected a HAL+JSON response from the pact broker, but got a response with no '_links'. URL: '{}', LINK: '{}'",
self.url, link)))
}
}
}
async fn post_json(&self, url: &str, body: &str) -> Result<serde_json::Value, PactBrokerError> {
trace!("post_json(url='{}', body='{}')", url, body);
self.send_document(url, body, Method::POST).await
}
async fn put_json(&self, url: &str, body: &str) -> Result<serde_json::Value, PactBrokerError> {
trace!("put_json(url='{}', body='{}')", url, body);
self.send_document(url, body, Method::PUT).await
}
async fn send_document(&self, url: &str, body: &str, method: Method) -> Result<Value, PactBrokerError> {
debug!("Sending JSON to {} using {}: {}", url, method, body);
let base_url = &self.url.parse::<Url>()?;
let url = if url.starts_with("/") {
base_url.join(url)?
} else {
let url = url.parse::<Url>()?;
base_url.join(&url.path())?
};
let request_builder = match self.auth {
Some(ref auth) => match auth {
HttpAuth::User(username, password) => self.client
.request(method, url.clone())
.basic_auth(username, password.clone()),
HttpAuth::Token(token) => self.client
.request(method, url.clone())
.bearer_auth(token),
_ => self.client.request(method, url.clone())
},
None => self.client.request(method, url.clone())
}
.header("Content-Type", "application/json")
.header("Accept", "application/hal+json")
.header("Accept", "application/json")
.body(body.to_string());
let response = with_retries(self.retries, request_builder).await;
match response {
Ok(res) => self.parse_broker_response(url.path().to_string(), res).await,
Err(err) => Err(PactBrokerError::IoError(
format!("Failed to send JSON to the pact broker URL '{}' - IoError {}", url, err)
))
}
}
fn with_doc_context(self, doc_attributes: &[Link]) -> Result<HALClient, PactBrokerError> {
let links: serde_json::Map<String, serde_json::Value> = doc_attributes.iter()
.map(|link| (link.name.clone(), link.as_json())).collect();
let links_json = json!({
"_links": json!(links)
});
Ok(self.update_path_info(links_json))
}
}
fn handle_validation_errors(body: Value) -> PactBrokerError {
match &body {
Value::Object(attrs) => if let Some(errors) = attrs.get("errors") {
match errors {
Value::Array(values) => PactBrokerError::ValidationError(values.iter().map(|v| json_to_string(v)).collect()),
Value::Object(errors) => PactBrokerError::ValidationError(
errors.iter().map(|(field, errors)| {
match errors {
Value::String(error) => format!("{}: {}", field, error),
Value::Array(errors) => format!("{}: {}", field, errors.iter().map(|err| json_to_string(err)).join(", ")),
_ => format!("{}: {}", field, errors),
}
})
.collect()
),
Value::String(s) => PactBrokerError::ValidationError(vec![s.clone()]),
_ => PactBrokerError::ValidationError(vec![errors.to_string()])
}
} else {
PactBrokerError::ValidationError(vec![body.to_string()])
},
Value::String(s) => PactBrokerError::ValidationError(vec![s.clone()]),
_ => PactBrokerError::ValidationError(vec![body.to_string()])
}
}
impl Default for HALClient {
fn default() -> Self {
HALClient {
client: reqwest::ClientBuilder::new()
.user_agent(format!("{}/{}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION")))
.build()
.unwrap(),
url: "".to_string(),
path_info: None,
auth: None,
retries: 3
}
}
}
fn links_from_json(json: &Value) -> Vec<Link> {
match json.get("_links") {
Some(json) => match json {
Value::Object(v) => {
v.iter().map(|(link, json)| match json {
Value::Object(attr) => Link::from_json(link, attr),
_ => Link { name: link.clone(), .. Link::default() }
}).collect()
},
_ => vec![]
},
None => vec![]
}
}
/// Fetches the pacts from the broker that match the provider name
pub async fn fetch_pacts_from_broker(
broker_url: &str,
provider_name: &str,
auth: Option<HttpAuth>
) -> anyhow::Result<Vec<anyhow::Result<(Box<dyn Pact + Send + Sync + RefUnwindSafe>, Option<PactVerificationContext>, Vec<Link>)>>> {
trace!("fetch_pacts_from_broker(broker_url='{}', provider_name='{}', auth={})", broker_url,
provider_name, auth.clone().unwrap_or_default());
let mut hal_client = HALClient::with_url(broker_url, auth);
let template_values = hashmap!{ "provider".to_string() => provider_name.to_string() };
hal_client = hal_client.navigate("pb:latest-provider-pacts", &template_values)
.await
.map_err(move |err| {
match err {
PactBrokerError::NotFound(_) =>
PactBrokerError::NotFound(
format!("No pacts for provider '{}' where found in the pact broker. URL: '{}'",
provider_name, broker_url)),
_ => err
}
})?;
let pact_links = hal_client.clone().iter_links("pacts")?;
let results: Vec<_> = futures::stream::iter(pact_links)
.map(|ref pact_link| {
match pact_link.href {
Some(_) => Ok((hal_client.clone(), pact_link.clone())),
None => Err(
PactBrokerError::LinkError(
format!(
"Expected a HAL+JSON response from the pact broker, but got a link with no HREF. URL: '{}', LINK: '{:?}'",
&hal_client.url,
pact_link
)
)
)
}
})
.and_then(|(hal_client, pact_link)| async {
let pact_json = hal_client.fetch_url(
&pact_link.clone(),
&template_values.clone()
).await?;
Ok((pact_link, pact_json))
})
.map(|result| {
match result {
Ok((pact_link, pact_json)) => {
let href = pact_link.href.unwrap_or_default();
let links = links_from_json(&pact_json);
load_pact_from_json(href.as_str(), &pact_json)
.map(|pact| (pact, None, links))
},
Err(err) => Err(err.into())
}
})
.into_stream()
.collect()
.await;
Ok(results)
}
/// Fetch Pacts from the broker using the "provider-pacts-for-verification" endpoint
pub async fn fetch_pacts_dynamically_from_broker(
broker_url: &str,
provider_name: String,
pending: bool,
include_wip_pacts_since: Option<String>,
provider_tags: Vec<String>,
provider_branch: Option<String>,
consumer_version_selectors: Vec<ConsumerVersionSelector>,
auth: Option<HttpAuth>
) -> anyhow::Result<Vec<Result<(Box<dyn Pact + Send + Sync + RefUnwindSafe>, Option<PactVerificationContext>, Vec<Link>), PactBrokerError>>> {
trace!("fetch_pacts_dynamically_from_broker(broker_url='{}', provider_name='{}', pending={}, \
include_wip_pacts_since={:?}, provider_tags: {:?}, consumer_version_selectors: {:?}, auth={})",
broker_url, provider_name, pending, include_wip_pacts_since, provider_tags,
consumer_version_selectors, auth.clone().unwrap_or_default());
let mut hal_client = HALClient::with_url(broker_url, auth);
let template_values = hashmap!{ "provider".to_string() => provider_name.clone() };
hal_client = hal_client.navigate("pb:provider-pacts-for-verification", &template_values)
.await
.map_err(move |err| {
match err {
PactBrokerError::NotFound(_) =>
PactBrokerError::NotFound(
format!("No pacts for provider '{}' were found in the pact broker. URL: '{}'",
provider_name.clone(), broker_url)),
_ => err
}
})?;
// Construct the Pacts for verification payload
let pacts_for_verification = PactsForVerificationRequest {
provider_version_tags: provider_tags,
provider_version_branch: provider_branch,
include_wip_pacts_since,
consumer_version_selectors,
include_pending_status: pending,
};
let request_body = serde_json::to_string(&pacts_for_verification).unwrap();
// Post the verification request
let response = match hal_client.find_link("self") {
Ok(link) => {
let link = hal_client.clone().parse_link_url(&link, &hashmap!{})?;
match hal_client.clone().post_json(link.as_str(), request_body.as_str()).await {
Ok(res) => Some(res),
Err(err) => {
info!("error response for pacts for verification: {} ", err);
return Err(anyhow!(err))
}
}
},
Err(e) => return Err(anyhow!(e))
};
// Find all of the Pact links
let pact_links = match response {
Some(v) => {
let pfv: PactsForVerificationResponse = serde_json::from_value(v)
.map_err(|err| {
trace!("Failed to deserialise PactsForVerificationResponse: {}", err);
err
})
.unwrap_or(PactsForVerificationResponse { embedded: PactsForVerificationBody { pacts: vec!() } });
trace!(?pfv, "got pacts for verification response");
if pfv.embedded.pacts.len() == 0 {
return Err(anyhow!(PactBrokerError::NotFound(format!("No pacts were found for this provider"))))
};
let links: Result<Vec<(Link, PactVerificationContext)>, PactBrokerError> = pfv.embedded.pacts.iter().map(| p| {
match p.links.get("self") {
Some(l) => Ok((l.clone(), p.into())),
None => Err(
PactBrokerError::LinkError(
format!(
"Expected a HAL+JSON response from the pact broker, but got a link with no HREF. URL: '{}', PATH: '{:?}'",
&hal_client.url,
&p.links,
)
)
)
}
}).collect();
links
},
None => Err(PactBrokerError::NotFound(format!("No pacts were found for this provider")))
}?;
let results: Vec<_> = futures::stream::iter(pact_links)
.map(|(ref pact_link, ref context)| {
match pact_link.href {
Some(_) => Ok((hal_client.clone(), pact_link.clone(), context.clone())),
None => Err(
PactBrokerError::LinkError(
format!(
"Expected a HAL+JSON response from the pact broker, but got a link with no HREF. URL: '{}', LINK: '{:?}'",
&hal_client.url,
pact_link
)
)
)
}
})
.and_then(|(hal_client, pact_link, context)| async {
let pact_json = hal_client.fetch_url(
&pact_link.clone(),
&template_values.clone()
).await?;
Ok((pact_link, pact_json, context))
})
.map(|result| {
match result {
Ok((pact_link, pact_json, context)) => {
let href = pact_link.href.unwrap_or_default();
let links = links_from_json(&pact_json);
load_pact_from_json(href.as_str(), &pact_json)
.map(|pact| (pact, Some(context), links))
.map_err(|err| PactBrokerError::ContentError(format!("{}", err)))
},
Err(err) => Err(err)
}
})
.into_stream()
.collect()
.await;
Ok(results)
}
/// Fetch the Pact from the given URL, using any required authentication. This will use a GET
/// request to the given URL and parse the result into a Pact model. It will also look for any HAL
/// links in the response, returning those if found.
pub async fn fetch_pact_from_url(url: &str, auth: &Option<HttpAuth>) -> anyhow::Result<(Box<dyn Pact + Send + Sync + RefUnwindSafe>, Vec<Link>)> {
let url = url.to_string();
let auth = auth.clone();
let (url, pact_json) = tokio::task::spawn_blocking(move || {
http_utils::fetch_json_from_url(&url, &auth)
}).await??;
let pact = load_pact_from_json(&url, &pact_json)?;
let links = links_from_json(&pact_json);
Ok((pact, links))
}
/// Struct that wraps the result of a verification test
pub enum TestResult {
/// Test was OK
Ok(Vec<Option<String>>),
/// Test failed verification
Failed(Vec<(Option<String>, Option<MismatchResult>)>)
}
impl TestResult {
/// Convert this test result to a boolean value
pub fn to_bool(&self) -> bool {
match self {
TestResult::Ok(_) => true,
_ => false
}
}
}
/// Publishes the result to the "pb:publish-verification-results" link in the links associated with the pact
pub async fn publish_verification_results(
links: Vec<Link>,
broker_url: &str,
auth: Option<HttpAuth>,
result: TestResult,
version: String,
build_url: Option<String>,
provider_tags: Vec<String>,
branch: Option<String>,
metrics_data: Option<&VerificationMetrics>
) -> Result<serde_json::Value, PactBrokerError> {
let hal_client = HALClient::with_url(broker_url, auth.clone());
if branch.is_some() {
publish_provider_branch(&hal_client, &links, &branch.unwrap(), &version).await?;
}
if !provider_tags.is_empty() {
publish_provider_tags(&hal_client, &links, provider_tags, &version).await?;
}
let publish_link = links
.iter()
.cloned()
.find(|item| item.name.to_ascii_lowercase() == "pb:publish-verification-results")
.ok_or_else(|| PactBrokerError::LinkError(
"Response from the pact broker has no 'pb:publish-verification-results' link".into()
))?;
let json = build_payload(result, version, build_url, metrics_data);
hal_client.post_json(publish_link.href.unwrap_or_default().as_str(), json.to_string().as_str()).await
}
fn build_payload(
result: TestResult,
version: String,
build_url: Option<String>,
metrics_data: Option<&VerificationMetrics>
) -> serde_json::Value {
let mut json = json!({
"success": result.to_bool(),
"providerApplicationVersion": version,
"verifiedBy": {
"implementation": "Pact-Rust",
"version": VERIFIER_VERSION
}
});
let json_obj = json.as_object_mut().unwrap();
if let Some(build_url) = build_url {
json_obj.insert("buildUrl".into(), build_url.into());
}
if let Some(metrics_data) = metrics_data {
json_obj.get_mut("verifiedBy").unwrap()["clientLanguage"] = json!({
"testFramework": metrics_data.test_framework,
"name": metrics_data.app_name,
"version": metrics_data.app_version
});
}
match result {
TestResult::Failed(mismatches) => {
let values = mismatches.iter()
.group_by(|(id, _)| id.clone().unwrap_or_default())
.into_iter()
.map(|(key, mismatches)| {
let acc: (Vec<serde_json::Value>, Vec<serde_json::Value>) = (vec![], vec![]);
let values = mismatches.fold(acc, |mut acc, (_, result)| {
if let Some(mismatch) = result {
match mismatch {
MismatchResult::Mismatches { mismatches, .. } => {
for mismatch in mismatches {
match mismatch {
Mismatch::MethodMismatch { expected, actual } => acc.0.push(json!({
"attribute": "method",
"description": format!("Expected method of {} but received {}", expected, actual)
})),
Mismatch::PathMismatch { mismatch, .. } => acc.0.push(json!({
"attribute": "path",
"description": mismatch
})),
Mismatch::StatusMismatch { mismatch, .. } => acc.0.push(json!({
"attribute": "status",
"description": mismatch
})),
Mismatch::QueryMismatch { parameter, mismatch, .. } => acc.0.push(json!({
"attribute": "query",
"identifier": parameter,
"description": mismatch
})),
Mismatch::HeaderMismatch { key, mismatch, .. } => acc.0.push(json!({
"attribute": "header",
"identifier": key,
"description": mismatch
})),
Mismatch::BodyTypeMismatch { expected, actual, .. } => acc.0.push(json!({
"attribute": "body",
"identifier": "$",
"description": format!("Expected body type of '{}' but received '{}'", expected, actual)
})),
Mismatch::BodyMismatch { path, mismatch, .. } => acc.0.push(json!({
"attribute": "body",
"identifier": path,
"description": mismatch
})),
Mismatch::MetadataMismatch { key, mismatch, .. } => acc.0.push(json!({
"attribute": "metadata",
"identifier": key,
"description": mismatch
}))
}
}
},
MismatchResult::Error(err, _) => acc.1.push(json!({ "message": err }))
};
};
acc
});
let mut json = json!({
"interactionId": key,
"success": values.0.is_empty() && values.1.is_empty()
});
if !values.0.is_empty() {
json.as_object_mut().unwrap().insert("mismatches".into(), json!(values.0));
}
if !values.1.is_empty() {
json.as_object_mut().unwrap().insert("exceptions".into(), json!(values.1));
}
json
}).collect::<Vec<serde_json::Value>>();
json_obj.insert("testResults".into(), serde_json::Value::Array(values));
}
TestResult::Ok(ids) => {
let values = ids.iter().filter(|id| id.is_some())
.map(|id| json!({
"interactionId": id.clone().unwrap_or_default(),
"success": true
})).collect();
json_obj.insert("testResults".into(), serde_json::Value::Array(values));
}
}
json
}
async fn publish_provider_tags(
hal_client: &HALClient,
links: &[Link],
provider_tags: Vec<String>,
version: &str) -> Result<(), PactBrokerError> {
let hal_client = hal_client.clone().with_doc_context(links)?
.navigate("pb:provider", &hashmap!{}).await?;
match hal_client.find_link("pb:version-tag") {
Ok(link) => {
for tag in &provider_tags {
let template_values = hashmap! {
"version".to_string() => version.to_string(),
"tag".to_string() => tag.clone()
};
match hal_client.clone().put_json(hal_client.clone().parse_link_url(&link, &template_values)?.as_str(), "{}").await {
Ok(_) => debug!("Pushed tag {} for provider version {}", tag, version),
Err(err) => {
error!("Failed to push tag {} for provider version {}", tag, version);
return Err(err);
}
}
};
Ok(())
},
Err(_) => Err(PactBrokerError::LinkError("Can't publish provider tags as there is no 'pb:version-tag' link".to_string()))
}
}
async fn publish_provider_branch(
hal_client: &HALClient,
links: &[Link],
branch: &str,
version: &str
) -> Result<(), PactBrokerError> {
let hal_client = hal_client.clone().with_doc_context(links)?
.navigate("pb:provider", &hashmap!{}).await?;
match hal_client.find_link("pb:branch-version") {
Ok(link) => {
let template_values = hashmap! {
"branch".to_string() => branch.to_string(),
"version".to_string() => version.to_string(),
};
match hal_client.clone().put_json(hal_client.clone().parse_link_url(&link, &template_values)?.as_str(), "{}").await {
Ok(_) => debug!("Pushed branch {} for provider version {}", branch, version),
Err(err) => {
error!("Failed to push branch {} for provider version {}", branch, version);
return Err(err);
}
}
Ok(())
},
Err(_) => Err(PactBrokerError::LinkError("Can't publish provider branch as there is no 'pb:branch-version' link. Please ugrade to Pact Broker version 2.86.0 or later for branch support".to_string()))
}
}
#[skip_serializing_none]
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
/// Structure to represent a HAL link
pub struct ConsumerVersionSelector {
/// Application name to filter the results on
pub consumer: Option<String>,
/// Tag
pub tag: Option<String>,