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
use std::collections::HashMap;
use std::fmt::{self, Display, Formatter};
use std::sync::Mutex;
use itertools::Itertools;
use lazy_static::lazy_static;
use log::{debug, error, trace};
use maplit::hashset;
use regex::Regex;
use serde::{Deserialize, Serialize};
use pact_models::content_types::ContentType;
use crate::content::{ContentMatcher, ContentGenerator};
use crate::plugin_models::PactPluginManifest;
use crate::proto::{CatalogueEntry as ProtoCatalogueEntry};
use crate::proto::catalogue_entry::EntryType;
lazy_static! {
static ref CATALOGUE_REGISTER: Mutex<HashMap<String, CatalogueEntry>> = Mutex::new(HashMap::new());
}
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[allow(non_camel_case_types)]
pub enum CatalogueEntryType {
CONTENT_MATCHER,
CONTENT_GENERATOR,
MOCK_SERVER,
MATCHER,
INTERACTION
}
impl Display for CatalogueEntryType {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
CatalogueEntryType::CONTENT_MATCHER => write!(f, "content-matcher"),
CatalogueEntryType::CONTENT_GENERATOR => write!(f, "content-generator"),
CatalogueEntryType::MOCK_SERVER => write!(f, "mock-server"),
CatalogueEntryType::MATCHER => write!(f, "matcher"),
CatalogueEntryType::INTERACTION => write!(f, "interaction"),
}
}
}
impl From<&str> for CatalogueEntryType {
fn from(s: &str) -> Self {
match s {
"content-matcher" => CatalogueEntryType::CONTENT_MATCHER,
"content-generator" => CatalogueEntryType::CONTENT_GENERATOR,
"interaction" => CatalogueEntryType::INTERACTION,
"matcher" => CatalogueEntryType::MATCHER,
"mock-server" => CatalogueEntryType::MOCK_SERVER,
_ => {
let message = format!("'{}' is not a valid CatalogueEntryType value", s);
error!("{}", message);
panic!("{}", message)
}
}
}
}
impl From<String> for CatalogueEntryType {
fn from(s: String) -> Self {
Self::from(s.as_str())
}
}
impl From<EntryType> for CatalogueEntryType {
fn from(t: EntryType) -> Self {
match t {
EntryType::ContentMatcher => CatalogueEntryType::CONTENT_MATCHER,
EntryType::ContentGenerator => CatalogueEntryType::CONTENT_GENERATOR,
EntryType::MockServer => CatalogueEntryType::MOCK_SERVER,
EntryType::Matcher => CatalogueEntryType::MATCHER,
EntryType::Interaction => CatalogueEntryType::INTERACTION
}
}
}
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[allow(non_camel_case_types)]
pub enum CatalogueEntryProviderType {
CORE,
PLUGIN
}
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct CatalogueEntry {
pub entry_type: CatalogueEntryType,
pub provider_type: CatalogueEntryProviderType,
pub plugin: Option<PactPluginManifest>,
pub key: String,
pub values: HashMap<String, String>
}
pub fn register_plugin_entries(plugin: &PactPluginManifest, catalogue_list: &Vec<ProtoCatalogueEntry>) {
trace!("register_plugin_entries({:?}, {:?})", plugin, catalogue_list);
let mut guard = CATALOGUE_REGISTER.lock().unwrap();
for entry in catalogue_list {
let entry_type = CatalogueEntryType::from(entry.r#type());
let key = format!("plugin/{}/{}/{}", plugin.name, entry_type, entry.key);
guard.insert(key.clone(), CatalogueEntry {
entry_type,
provider_type: CatalogueEntryProviderType::PLUGIN,
plugin: Some(plugin.clone()),
key: key.clone(),
values: entry.values.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
});
}
debug!("Updated catalogue entries:\n{}", guard.keys().sorted().join("\n"))
}
pub fn register_core_entries(entries: &Vec<CatalogueEntry>) {
trace!("register_core_entries({:?})", entries);
let mut inner = CATALOGUE_REGISTER.lock().unwrap();
let mut updated_keys = hashset!();
for entry in entries {
let key = format!("core/{}/{}", entry.entry_type, entry.key);
if !inner.contains_key(&key) {
inner.insert(key.clone(), entry.clone());
updated_keys.insert(key.clone());
}
}
if !updated_keys.is_empty() {
debug!("Updated catalogue entries:\n{}", updated_keys.iter().sorted().join("\n"));
}
}
pub fn remove_plugin_entries(name: &String) {
trace!("remove_plugin_entries({})", name);
let prefix = format!("plugin/{}/", name);
let keys: Vec<String> = {
let guard = CATALOGUE_REGISTER.lock().unwrap();
guard.keys()
.filter(|key| key.starts_with(&prefix))
.cloned()
.collect()
};
let mut guard = CATALOGUE_REGISTER.lock().unwrap();
for key in keys {
guard.remove(&key);
}
debug!("Removed all catalogue entries for plugin {}", name);
}
pub fn find_content_matcher(content_type: &ContentType) -> Option<ContentMatcher> {
debug!("Looking for a content matcher for {}", content_type);
let guard = CATALOGUE_REGISTER.lock().unwrap();
trace!("Catalogue has {} entries", guard.len());
guard.values().find(|entry| {
trace!("Catalogue entry {:?}", entry);
if entry.entry_type == CatalogueEntryType::CONTENT_MATCHER {
trace!("Catalogue entry is a content matcher for {:?}", entry.values.get("content-types"));
if let Some(content_types) = entry.values.get("content-types") {
content_types.split(";").any(|ct| matches_pattern(ct.trim(), content_type))
} else {
false
}
} else {
false
}
}).map(|entry| ContentMatcher { catalogue_entry: entry.clone() })
}
fn matches_pattern(pattern: &str, content_type: &ContentType) -> bool {
let base_type = content_type.base_type().to_string();
match Regex::new(pattern) {
Ok(regex) => regex.is_match(content_type.to_string().as_str()) || regex.is_match(base_type.as_str()),
Err(err) => {
error!("Failed to parse '{}' as a regex - {}", pattern, err);
false
}
}
}
pub fn find_content_generator(content_type: &ContentType) -> Option<ContentGenerator> {
debug!("Looking for a content generator for {}", content_type);
let guard = CATALOGUE_REGISTER.lock().unwrap();
guard.values().find(|entry| {
if entry.entry_type == CatalogueEntryType::CONTENT_GENERATOR {
if let Some(content_types) = entry.values.get("content-types") {
content_types.split(";").any(|ct| matches_pattern(ct.trim(), content_type))
} else {
false
}
} else {
false
}
}).map(|entry| ContentGenerator { catalogue_entry: entry.clone() })
}