Skip to main content

pact_plugin_driver/
catalogue_manager.rs

1//! Manages the catalogue of features provided by plugins
2
3use std::collections::HashMap;
4use std::fmt::{self, Display, Formatter};
5use std::sync::Mutex;
6
7use itertools::Itertools;
8use lazy_static::lazy_static;
9use maplit::hashset;
10use pact_models::content_types::ContentType;
11use regex::Regex;
12use serde::{Deserialize, Serialize};
13use tracing::{debug, error, instrument, trace, warn};
14
15use crate::content::{ContentGenerator, ContentMatcher};
16use crate::plugin_models::PactPluginManifest;
17use crate::proto::catalogue_entry::EntryType;
18use crate::proto::CatalogueEntry as ProtoCatalogueEntry;
19use crate::proto_v2::catalogue_entry::EntryType as EntryTypeV2;
20
21lazy_static! {
22  static ref CATALOGUE_REGISTER: Mutex<HashMap<String, CatalogueEntry>> = Mutex::new(HashMap::new());
23}
24
25/// Type of catalogue entry
26#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
27#[allow(non_camel_case_types)]
28pub enum CatalogueEntryType {
29  /// Content matcher (based on content type)
30  CONTENT_MATCHER,
31  /// Content generator (based on content type)
32  CONTENT_GENERATOR,
33  /// Network transport
34  TRANSPORT,
35  /// Matching rule for a content field/value
36  MATCHER,
37  /// Type of interaction
38  INTERACTION,
39  /// Generator for a content field/value. Only representable on the V2 plugin interface - the V1
40  /// `EntryType` enum has no equivalent. See proposal 006 (Field-level matchers and generators).
41  GENERATOR
42}
43
44impl CatalogueEntryType {
45  /// Return the protobuf type for this entry type.
46  ///
47  /// This maps to the *V1* enum, which cannot represent every entry type: `GENERATOR` has no V1
48  /// equivalent and is reported as `Matcher`. Use [`CatalogueEntryType::to_proto_value`] instead,
49  /// which returns the wire value and is lossless for both interface versions.
50  #[deprecated(
51    since = "1.2.0",
52    note = "Use to_proto_value, which can represent entry types that only exist on the V2 interface"
53  )]
54  pub fn to_proto_type(&self) -> EntryType {
55    match self {
56      CatalogueEntryType::CONTENT_MATCHER => EntryType::ContentMatcher,
57      CatalogueEntryType::CONTENT_GENERATOR => EntryType::ContentGenerator,
58      CatalogueEntryType::TRANSPORT => EntryType::Transport,
59      CatalogueEntryType::MATCHER => EntryType::Matcher,
60      CatalogueEntryType::INTERACTION => EntryType::Interaction,
61      CatalogueEntryType::GENERATOR => EntryType::Matcher
62    }
63  }
64
65  /// The V2 protobuf enum for this entry type. V2 is the canonical source of the wire values: it
66  /// mirrors V1 for the entry types both versions share, and adds the ones V1 never had.
67  fn to_proto_enum(self) -> EntryTypeV2 {
68    match self {
69      CatalogueEntryType::CONTENT_MATCHER => EntryTypeV2::ContentMatcher,
70      CatalogueEntryType::CONTENT_GENERATOR => EntryTypeV2::ContentGenerator,
71      CatalogueEntryType::TRANSPORT => EntryTypeV2::Transport,
72      CatalogueEntryType::MATCHER => EntryTypeV2::Matcher,
73      CatalogueEntryType::INTERACTION => EntryTypeV2::Interaction,
74      CatalogueEntryType::GENERATOR => EntryTypeV2::Generator
75    }
76  }
77
78  fn from_proto_enum(entry_type: EntryTypeV2) -> CatalogueEntryType {
79    match entry_type {
80      EntryTypeV2::ContentMatcher => CatalogueEntryType::CONTENT_MATCHER,
81      EntryTypeV2::ContentGenerator => CatalogueEntryType::CONTENT_GENERATOR,
82      EntryTypeV2::Transport => CatalogueEntryType::TRANSPORT,
83      EntryTypeV2::Matcher => CatalogueEntryType::MATCHER,
84      EntryTypeV2::Interaction => CatalogueEntryType::INTERACTION,
85      EntryTypeV2::Generator => CatalogueEntryType::GENERATOR
86    }
87  }
88
89  /// The protobuf enum value for this entry type, for setting the `type` field of a
90  /// `CatalogueEntry` message. Lossless for every entry type, including those a V1 plugin will
91  /// not recognise - a V1 plugin decodes an unknown value as an unrecognised enum and ignores the
92  /// entry, which is the correct outcome, whereas mapping it onto some other V1 type would have
93  /// the plugin act on an entry that is not what it thinks it is.
94  pub fn to_proto_value(self) -> i32 {
95    self.to_proto_enum() as i32
96  }
97
98  /// The entry type for a protobuf enum value, or `None` if the value is not one this driver
99  /// understands (an entry type added by a later interface version). Deliberately not defaulting
100  /// to `CONTENT_MATCHER` the way prost's generated accessor does: silently mis-typing an entry
101  /// is worse than ignoring one.
102  pub fn from_proto_value(value: i32) -> Option<CatalogueEntryType> {
103    EntryTypeV2::try_from(value).ok().map(CatalogueEntryType::from_proto_enum)
104  }
105
106  /// The protobuf enum value name for this entry type, e.g. `"CONTENT_MATCHER"`. This is the form
107  /// a Lua plugin uses in the catalogue entries returned from its `init` function.
108  pub fn as_proto_name(&self) -> &'static str {
109    self.to_proto_enum().as_str_name()
110  }
111
112  /// The entry type for a protobuf enum value name, e.g. `"CONTENT_MATCHER"`, or `None` if the
113  /// name is not one this driver understands.
114  pub fn from_proto_name(name: &str) -> Option<CatalogueEntryType> {
115    EntryTypeV2::from_str_name(name).map(CatalogueEntryType::from_proto_enum)
116  }
117}
118
119impl Display for CatalogueEntryType {
120  fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
121    match self {
122      CatalogueEntryType::CONTENT_MATCHER => write!(f, "content-matcher"),
123      CatalogueEntryType::CONTENT_GENERATOR => write!(f, "content-generator"),
124      CatalogueEntryType::TRANSPORT => write!(f, "transport"),
125      CatalogueEntryType::MATCHER => write!(f, "matcher"),
126      CatalogueEntryType::INTERACTION => write!(f, "interaction"),
127      CatalogueEntryType::GENERATOR => write!(f, "generator"),
128    }
129  }
130}
131
132impl From<&str> for CatalogueEntryType {
133  fn from(s: &str) -> Self {
134    match s {
135      "content-matcher" => CatalogueEntryType::CONTENT_MATCHER,
136      "content-generator" => CatalogueEntryType::CONTENT_GENERATOR,
137      "interaction" => CatalogueEntryType::INTERACTION,
138      "matcher" => CatalogueEntryType::MATCHER,
139      "transport" => CatalogueEntryType::TRANSPORT,
140      "generator" => CatalogueEntryType::GENERATOR,
141      _ => {
142        let message = format!("'{}' is not a valid CatalogueEntryType value", s);
143        error!("{}", message);
144        panic!("{}", message)
145      }
146    }
147  }
148}
149
150impl From<String> for CatalogueEntryType {
151  fn from(s: String) -> Self {
152    Self::from(s.as_str())
153  }
154}
155
156impl From<EntryType> for CatalogueEntryType {
157  fn from(t: EntryType) -> Self {
158    match t {
159      EntryType::ContentMatcher => CatalogueEntryType::CONTENT_MATCHER,
160      EntryType::ContentGenerator => CatalogueEntryType::CONTENT_GENERATOR,
161      EntryType::Transport => CatalogueEntryType::TRANSPORT,
162      EntryType::Matcher => CatalogueEntryType::MATCHER,
163      EntryType::Interaction => CatalogueEntryType::INTERACTION
164    }
165  }
166}
167
168/// Provider of the catalogue entry
169#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
170#[allow(non_camel_case_types)]
171pub enum CatalogueEntryProviderType {
172  /// Core Pact framework
173  CORE,
174  /// Plugin
175  PLUGIN
176}
177
178/// Catalogue entry
179#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
180#[serde(rename_all = "camelCase")]
181pub struct CatalogueEntry {
182  /// Type of entry
183  pub entry_type: CatalogueEntryType,
184  /// Provider of the entry
185  pub provider_type: CatalogueEntryProviderType,
186  /// Plugin manifest
187  pub plugin: Option<PactPluginManifest>,
188  /// Entry key
189  pub key: String,
190  /// assocaited Entry values
191  pub values: HashMap<String, String>
192}
193
194/// Register the entries in the global catalogue
195pub fn register_plugin_entries(plugin: &PactPluginManifest, catalogue_list: &Vec<ProtoCatalogueEntry>) {
196  trace!("register_plugin_entries({:?}, {:?})", plugin, catalogue_list);
197
198  let mut guard = CATALOGUE_REGISTER.lock().unwrap();
199
200  for entry in catalogue_list {
201    // Deliberately reading the raw field rather than prost's `entry.r#type()` accessor: the
202    // accessor is generated against the V1 enum and maps anything it doesn't recognise to the
203    // default (`CONTENT_MATCHER`), which would silently register a V2-only entry type - a
204    // `GENERATOR`, say - as a content matcher.
205    let entry_type = match CatalogueEntryType::from_proto_value(entry.r#type) {
206      Some(entry_type) => entry_type,
207      None => {
208        warn!(
209          "Ignoring catalogue entry '{}' from plugin '{}': {} is not a catalogue entry type this driver understands",
210          entry.key, plugin.name, entry.r#type
211        );
212        continue;
213      }
214    };
215    let key = format!("plugin/{}/{}/{}", plugin.name, entry_type, entry.key);
216    guard.insert(key.clone(), CatalogueEntry {
217      entry_type,
218      provider_type: CatalogueEntryProviderType::PLUGIN,
219      plugin: Some(plugin.clone()),
220      key: entry.key.clone(),
221      values: entry.values.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
222    });
223  }
224
225  debug!("Updated catalogue entries:\n{}", guard.keys().sorted().join("\n"))
226}
227
228/// Register the core Pact framework entries in the global catalogue
229pub fn register_core_entries(entries: &Vec<CatalogueEntry>) {
230  trace!("register_core_entries({:?})", entries);
231
232  let mut inner = CATALOGUE_REGISTER.lock().unwrap();
233
234  let mut updated_keys = hashset!();
235  for entry in entries {
236    let key = format!("core/{}/{}", entry.entry_type, entry.key);
237    if !inner.contains_key(&key) {
238      inner.insert(key.clone(), entry.clone());
239      updated_keys.insert(key.clone());
240    }
241  }
242
243  if !updated_keys.is_empty() {
244    debug!("Updated catalogue entries:\n{}", updated_keys.iter().sorted().join("\n"));
245  }
246}
247
248/// Lookup an entry in the catalogue by the key, matched the same way [`resolve_capability`] does:
249/// by name - the whole catalogue key, or a trailing run of its `/`-separated components.
250///
251/// Unlike [`resolve_capability`], this takes the first match when more than one entry matches, and
252/// `HashMap` iteration order is randomised per process. Prefer [`resolve_capability`] wherever the
253/// expected entry type is known and a deterministic answer matters.
254pub fn lookup_entry(key: &str) -> Option<CatalogueEntry> {
255  let inner = CATALOGUE_REGISTER.lock().unwrap();
256  inner.iter()
257    .find(|(k, _)| names_catalogue_key(k, key))
258    .map(|(_, v)| v.clone())
259}
260
261/// Where a resolved catalogue entry's capability should be dispatched. Shared by every transport
262/// that lets a plugin call back into a capability by catalogue entry key - the gRPC `PluginHost`
263/// service, and the Lua/WASM host functions - so there is exactly one place that decides "who
264/// provides this entry". See proposal 007 ("One resolver, [multiple] call directions").
265#[derive(Debug, Clone)]
266pub enum ResolvedCapability {
267  /// A host-registered core handler, keyed by the unprefixed catalogue entry key.
268  Core(String),
269  /// A running plugin, identified by its manifest.
270  Plugin(Box<PactPluginManifest>)
271}
272
273/// Does `entry_key` name this catalogue key? Either the whole key (`core/content-matcher/xml`),
274/// or a trailing run of its `/`-separated components (`content-matcher/xml`, or just `xml`).
275///
276/// Components are compared whole, never as substrings: `"type"` names `core/matcher/type` but not
277/// `core/matcher/content-type`, which is the `content-type` rule and has nothing to do with it.
278fn names_catalogue_key(catalogue_key: &str, entry_key: &str) -> bool {
279  let key_parts = catalogue_key.split('/').collect::<Vec<_>>();
280  let query_parts = entry_key.split('/').collect::<Vec<_>>();
281  query_parts.len() <= key_parts.len()
282    && key_parts[key_parts.len() - query_parts.len()..] == query_parts[..]
283}
284
285/// Resolve a callback's catalogue entry key to a dispatch target, the same way
286/// [`crate::content::ContentMatcher::is_core`]/[`crate::content::ContentGenerator::is_core`] do
287/// for the driver's own outbound calls.
288///
289/// `entry_key` is matched against the catalogue by name - the whole catalogue key
290/// (`core/content-matcher/xml`) or a trailing run of its components (`content-matcher/xml`,
291/// `xml`), compared component by component. Core matching rules and generators are registered
292/// under the name the rule carries in a request (`type`, `regex`, `content-type`), so a bare rule
293/// name resolves to the core entry without any further convention.
294///
295/// A short name that matches both a core entry and a plugin's own - a plugin registering
296/// `matcher/date` alongside the core `date` rule - is an ambiguity error, not a silent pick;
297/// either caller disambiguates with more of the key (`core/matcher/date`,
298/// `plugin/my-plugin/matcher/date`).
299///
300/// Unlike [`lookup_entry`], this does not just take the first `HashMap` hit when more than one
301/// entry matches. A short, unqualified `entry_key` can still match more than one entry of the
302/// *same* `expected_type` (a plugin registering its own `content-matcher/xml` alongside a
303/// host-registered core `content-matcher/xml`), and `HashMap` iteration order is randomised per
304/// process - silently picking one would make the dispatch target non-deterministic across
305/// restarts. `expected_type` still guards against the *wrong* capability shape (a
306/// content-generator registered under the same name as an unrelated content-matcher), mirroring
307/// the explicit `entry_type` check [`find_content_matcher`]/[`find_content_generator`] already do.
308pub fn resolve_capability(entry_key: &str, expected_type: CatalogueEntryType) -> anyhow::Result<ResolvedCapability> {
309  let entry = resolve_capability_entry(entry_key, expected_type)?;
310  match entry.provider_type {
311    CatalogueEntryProviderType::CORE => Ok(ResolvedCapability::Core(entry.key.clone())),
312    CatalogueEntryProviderType::PLUGIN => entry.plugin.clone()
313      .map(|manifest| ResolvedCapability::Plugin(Box::new(manifest)))
314      .ok_or_else(|| anyhow::anyhow!("Catalogue entry '{}' has no plugin manifest", entry_key))
315  }
316}
317
318/// Resolve a catalogue entry key to the entry itself, matching it the same way
319/// [`resolve_capability`] documents. Callers that need the entry rather than a dispatch target -
320/// [`crate::field::find_field_matcher`] and [`crate::field::find_field_generator`], which wrap it
321/// in a matcher/generator - use this directly.
322pub fn resolve_capability_entry(entry_key: &str, expected_type: CatalogueEntryType) -> anyhow::Result<CatalogueEntry> {
323  let candidates: Vec<(String, CatalogueEntry)> = {
324    let inner = CATALOGUE_REGISTER.lock().unwrap();
325    inner.iter()
326      .filter(|(k, _)| names_catalogue_key(k, entry_key))
327      .map(|(k, v)| (k.clone(), v.clone()))
328      .collect()
329  };
330
331  let mut of_expected_type = candidates.iter().filter(|(_, entry)| entry.entry_type == expected_type);
332  let entry = match (of_expected_type.next(), of_expected_type.next()) {
333    (None, _) => return match candidates.first() {
334      Some((_, entry)) => Err(anyhow::anyhow!(
335        "Catalogue entry '{}' is a {:?}, not a {:?}", entry_key, entry.entry_type, expected_type
336      )),
337      None => Err(anyhow::anyhow!("No catalogue entry found for key '{}'", entry_key))
338    },
339    (Some(only), None) => &only.1,
340    (Some(first), Some(second)) => {
341      let mut keys: Vec<&str> = std::iter::once(first).chain(std::iter::once(second))
342        .chain(of_expected_type)
343        .map(|(k, _)| k.as_str())
344        .collect();
345      keys.sort_unstable();
346      return Err(anyhow::anyhow!(
347        "Ambiguous catalogue entry key '{}': matches multiple entries ({}) - register it under a more specific key",
348        entry_key, keys.join(", ")
349      ));
350    }
351  };
352
353  Ok(entry.clone())
354}
355
356/// Remove all entries for a plugin given the plugin name
357pub fn remove_plugin_entries(name: &str) {
358  trace!("remove_plugin_entries({})", name);
359
360  let prefix = format!("plugin/{}/", name);
361  let keys: Vec<String> = {
362    let guard = CATALOGUE_REGISTER.lock().unwrap();
363    guard.keys()
364      .filter(|key| key.starts_with(&prefix))
365      .cloned()
366      .collect()
367  };
368
369  let mut guard = CATALOGUE_REGISTER.lock().unwrap();
370  for key in keys {
371    guard.remove(&key);
372  }
373
374  debug!("Removed all catalogue entries for plugin {}", name);
375}
376
377/// Find a content matcher in the global catalogue for the provided content type
378#[instrument(level = "trace", skip(content_type))]
379pub fn find_content_matcher<CT: Into<String>>(content_type: CT) -> Option<ContentMatcher> {
380  let content_type_str = content_type.into();
381  debug!("Looking for a content matcher for {}", content_type_str);
382  let content_type = match ContentType::parse(content_type_str.as_str()) {
383    Ok(ct) => ct,
384    Err(err) => {
385      error!("'{}' is not a valid content type", err);
386      return None;
387    }
388  };
389  let guard = CATALOGUE_REGISTER.lock().unwrap();
390  trace!("Catalogue has {} entries", guard.len());
391  guard.values().find(|entry| {
392    trace!("Catalogue entry {:?}", entry);
393    if entry.entry_type == CatalogueEntryType::CONTENT_MATCHER {
394      trace!("Catalogue entry is a content matcher for {:?}", entry.values.get("content-types"));
395      if let Some(content_types) = entry.values.get("content-types") {
396        content_types.split(";").any(|ct| matches_pattern(ct.trim(), &content_type))
397      } else {
398        false
399      }
400    } else {
401      false
402    }
403  }).map(|entry| ContentMatcher { catalogue_entry: entry.clone() })
404}
405
406/// Checks if a registered content-type pattern matches a content type. The pattern is
407/// matched as a regex against the base type (i.e. with any parameters like `charset`
408/// stripped), anchored at both ends (the whole base type must match, not just a substring) -
409/// this must stay consistent with the equivalent check in the JVM driver's
410/// `CatalogueManager.matches`, so that a plugin's catalogue registration behaves the same way
411/// regardless of which driver loaded it. Regex metacharacters in a content type (most
412/// commonly `+`, as in a `+json`/`+xml` structured syntax suffix) need to be escaped by the
413/// plugin author for a literal match.
414fn matches_pattern(pattern: &str, content_type: &ContentType) -> bool {
415  // Deliberately not `content_type.base_type()`: that replaces the subtype with the
416  // structured syntax suffix (e.g. "application/jwt+json" -> "application/json"), which is
417  // useful for deciding how to *parse* a body but wrong here - it would make two unrelated
418  // "+json" content types register as the same catalogue entry. Just strip attributes
419  // (e.g. `charset`), keeping the type/subtype+suffix as the plugin actually registered it.
420  let base_type = match &content_type.suffix {
421    Some(suffix) => format!("{}/{}+{}", content_type.main_type, content_type.sub_type, suffix),
422    None => format!("{}/{}", content_type.main_type, content_type.sub_type)
423  };
424  match Regex::new(&format!("^(?:{})$", pattern)) {
425    Ok(regex) => regex.is_match(base_type.as_str()),
426    Err(err) => {
427      error!("Failed to parse '{}' as a regex - {}", pattern, err);
428      false
429    }
430  }
431}
432
433/// Find a content generator in the global catalogue for the provided content type
434pub fn find_content_generator(content_type: &ContentType) -> Option<ContentGenerator> {
435  debug!("Looking for a content generator for {}", content_type);
436  let guard = CATALOGUE_REGISTER.lock().unwrap();
437  guard.values().find(|entry| {
438    if entry.entry_type == CatalogueEntryType::CONTENT_GENERATOR {
439      if let Some(content_types) = entry.values.get("content-types") {
440        content_types.split(";").any(|ct| matches_pattern(ct.trim(), content_type))
441      } else {
442        false
443      }
444    } else {
445      false
446    }
447  }).map(|entry| ContentGenerator { catalogue_entry: entry.clone() })
448}
449
450/// Returns a copy of all catalogue entries
451pub fn all_entries() -> Vec<CatalogueEntry> {
452  let guard = CATALOGUE_REGISTER.lock().unwrap();
453  guard.values().cloned().collect()
454}
455
456/// Returns catalogue entries provided by the core host framework (excludes plugin entries)
457pub fn core_entries() -> Vec<CatalogueEntry> {
458  let guard = CATALOGUE_REGISTER.lock().unwrap();
459  guard.values()
460    .filter(|entry| entry.provider_type == CatalogueEntryProviderType::CORE)
461    .cloned()
462    .collect()
463}
464
465#[cfg(test)]
466mod tests {
467  use expectest::prelude::*;
468  use maplit::hashmap;
469
470  use crate::proto::catalogue_entry;
471
472  use super::*;
473
474  #[test]
475  fn sets_plugin_catalogue_entries_correctly() {
476    // Given
477    let manifest = PactPluginManifest {
478      name: "sets_plugin_catalogue_entries_correctly".to_string(),
479      .. PactPluginManifest::default()
480    };
481    let entries = vec![
482      ProtoCatalogueEntry {
483        r#type: catalogue_entry::EntryType::ContentMatcher as i32,
484        key: "protobuf".to_string(),
485        values: hashmap!{ "content-types".to_string() => "application/protobuf;application/grpc".to_string() }
486      },
487      ProtoCatalogueEntry {
488        r#type: catalogue_entry::EntryType::ContentGenerator as i32,
489        key: "protobuf".to_string(),
490        values: hashmap!{ "content-types".to_string() => "application/protobuf;application/grpc".to_string() }
491      },
492      ProtoCatalogueEntry {
493        r#type: catalogue_entry::EntryType::Transport as i32,
494        key: "grpc".to_string(),
495        values: hashmap!{}
496      }
497    ];
498
499    // When
500    register_plugin_entries(&manifest, &entries);
501
502    // Then
503    let matcher_entry = lookup_entry("content-matcher/protobuf");
504    let generator_entry = lookup_entry("content-generator/protobuf");
505    let transport_entry = lookup_entry("transport/grpc");
506
507    remove_plugin_entries("sets_plugin_catalogue_entries_correctly");
508
509    expect!(matcher_entry).to(be_some().value(CatalogueEntry {
510      entry_type: CatalogueEntryType::CONTENT_MATCHER,
511      provider_type: CatalogueEntryProviderType::PLUGIN,
512      plugin: Some(manifest.clone()),
513      key: "protobuf".to_string(),
514      values: hashmap!{ "content-types".to_string() => "application/protobuf;application/grpc".to_string() }
515    }));
516    expect!(generator_entry).to(be_some().value(CatalogueEntry {
517      entry_type: CatalogueEntryType::CONTENT_GENERATOR,
518      provider_type: CatalogueEntryProviderType::PLUGIN,
519      plugin: Some(manifest.clone()),
520      key: "protobuf".to_string(),
521      values: hashmap!{ "content-types".to_string() => "application/protobuf;application/grpc".to_string() }
522    }));
523    expect!(transport_entry).to(be_some().value(CatalogueEntry {
524      entry_type: CatalogueEntryType::TRANSPORT,
525      provider_type: CatalogueEntryProviderType::PLUGIN,
526      plugin: Some(manifest.clone()),
527      key: "grpc".to_string(),
528      values: hashmap!{}
529    }));
530  }
531
532  #[test]
533  fn entry_type_proto_values_and_names_round_trip() {
534    for entry_type in [
535      CatalogueEntryType::CONTENT_MATCHER,
536      CatalogueEntryType::CONTENT_GENERATOR,
537      CatalogueEntryType::TRANSPORT,
538      CatalogueEntryType::MATCHER,
539      CatalogueEntryType::INTERACTION,
540      CatalogueEntryType::GENERATOR
541    ] {
542      expect!(CatalogueEntryType::from_proto_value(entry_type.to_proto_value()))
543        .to(be_some().value(entry_type));
544      expect!(CatalogueEntryType::from_proto_name(entry_type.as_proto_name()))
545        .to(be_some().value(entry_type));
546      // The Display form round-trips too - it is what catalogue keys are built from
547      expect!(CatalogueEntryType::from(entry_type.to_string().as_str())).to(be_equal_to(entry_type));
548    }
549
550    expect!(CatalogueEntryType::from_proto_value(99)).to(be_none());
551    expect!(CatalogueEntryType::from_proto_name("NOT_AN_ENTRY_TYPE")).to(be_none());
552  }
553
554  #[test]
555  fn entry_types_shared_with_v1_keep_their_v1_wire_values() {
556    // The wire values come from the V2 enum, but the driver publishes one catalogue to every
557    // running plugin, V1 ones included - so the values V1 knows about must not shift.
558    expect!(CatalogueEntryType::CONTENT_MATCHER.to_proto_value())
559      .to(be_equal_to(EntryType::ContentMatcher as i32));
560    expect!(CatalogueEntryType::CONTENT_GENERATOR.to_proto_value())
561      .to(be_equal_to(EntryType::ContentGenerator as i32));
562    expect!(CatalogueEntryType::TRANSPORT.to_proto_value())
563      .to(be_equal_to(EntryType::Transport as i32));
564    expect!(CatalogueEntryType::MATCHER.to_proto_value())
565      .to(be_equal_to(EntryType::Matcher as i32));
566    expect!(CatalogueEntryType::INTERACTION.to_proto_value())
567      .to(be_equal_to(EntryType::Interaction as i32));
568  }
569
570  #[test]
571  fn registers_a_generator_entry_under_its_own_entry_type() {
572    let name = "registers_a_generator_entry_under_its_own_entry_type";
573    let manifest = PactPluginManifest { name: name.to_string(), .. PactPluginManifest::default() };
574    // GENERATOR only exists on the V2 enum. This is exactly the case where prost's generated
575    // `entry.r#type()` accessor - built against V1 - would report CONTENT_MATCHER instead.
576    let entries = vec![
577      ProtoCatalogueEntry {
578        r#type: CatalogueEntryType::GENERATOR.to_proto_value(),
579        key: name.to_string(),
580        values: hashmap!{}
581      }
582    ];
583
584    register_plugin_entries(&manifest, &entries);
585
586    let entry = lookup_entry(&format!("generator/{}", name));
587    let as_a_content_matcher = lookup_entry(&format!("content-matcher/{}", name));
588    remove_plugin_entries(name);
589
590    expect!(entry.map(|entry| entry.entry_type)).to(be_some().value(CatalogueEntryType::GENERATOR));
591    expect!(as_a_content_matcher).to(be_none());
592  }
593
594  #[test]
595  fn ignores_a_catalogue_entry_whose_type_this_driver_does_not_understand() {
596    let name = "ignores_a_catalogue_entry_whose_type_this_driver_does_not_understand";
597    let manifest = PactPluginManifest { name: name.to_string(), .. PactPluginManifest::default() };
598    let entries = vec![
599      ProtoCatalogueEntry { r#type: 99, key: name.to_string(), values: hashmap!{} }
600    ];
601
602    register_plugin_entries(&manifest, &entries);
603
604    let registered = all_entries().into_iter().find(|entry| entry.key == name);
605    remove_plugin_entries(name);
606
607    expect!(registered).to(be_none());
608  }
609
610  #[test]
611  fn find_content_matcher_requires_the_whole_base_type_to_match() {
612    let manifest = PactPluginManifest {
613      name: "find_content_matcher_requires_the_whole_base_type_to_match".to_string(),
614      .. PactPluginManifest::default()
615    };
616    let entries = vec![
617      ProtoCatalogueEntry {
618        r#type: catalogue_entry::EntryType::ContentMatcher as i32,
619        key: "jwt".to_string(),
620        // "+" must be escaped, otherwise it's a regex quantifier, not a literal character
621        values: hashmap!{ "content-types".to_string() => "application/jwt;application/jwt\\+json".to_string() }
622      }
623    ];
624    register_plugin_entries(&manifest, &entries);
625
626    let exact_match = find_content_matcher("application/jwt+json");
627    let with_params = find_content_matcher("application/jwt+json;charset=utf-8");
628    let longer_type = find_content_matcher("application/jwt+jsonextra");
629    let unrelated_type = find_content_matcher("application/json");
630
631    remove_plugin_entries("find_content_matcher_requires_the_whole_base_type_to_match");
632
633    expect!(exact_match).to(be_some());
634    expect!(with_params).to(be_some());
635    expect!(longer_type).to(be_none());
636    expect!(unrelated_type).to(be_none());
637  }
638
639  #[test]
640  fn resolve_capability_resolves_an_unambiguous_core_entry() {
641    let key = "resolve_capability_resolves_an_unambiguous_core_entry";
642    register_core_entries(&vec![CatalogueEntry {
643      entry_type: CatalogueEntryType::CONTENT_MATCHER,
644      provider_type: CatalogueEntryProviderType::CORE,
645      plugin: None,
646      key: key.to_string(),
647      values: hashmap!{}
648    }]);
649
650    let resolved = resolve_capability(key, CatalogueEntryType::CONTENT_MATCHER).unwrap();
651
652    let core_key = match resolved {
653      ResolvedCapability::Core(core_key) => core_key,
654      ResolvedCapability::Plugin(_) => panic!("expected a Core resolution, got Plugin")
655    };
656    expect!(core_key).to(be_equal_to(key.to_string()));
657  }
658
659  /// The core matcher entries as the Pact frameworks actually register them - keyed by the name
660  /// the rule carries in a request (`MatchingRule::name()`), with the specification version it was
661  /// introduced in as a value. Kept in sync with `MATCHER_CATALOGUE_ENTRIES` in pact_matching and
662  /// `MatcherExecutor.kt` in Pact-JVM.
663  fn register_core_matcher_entries() {
664    let entries = [("equality", "V1"), ("regex", "V2"), ("type", "V2"), ("min-type", "V2"),
665      ("max-type", "V2"), ("min-max-type", "V2"), ("include", "V3"), ("number", "V3"),
666      ("integer", "V3"), ("decimal", "V3"), ("null", "V3"), ("date", "V3"), ("time", "V3"),
667      ("datetime", "V3"), ("content-type", "V3"), ("values", "V3"), ("array-contains", "V4"),
668      ("boolean", "V4"), ("status-code", "V4"), ("not-empty", "V4"), ("semver", "V4"),
669      ("each-key", "V4"), ("each-value", "V4")]
670      .iter()
671      .map(|(key, version)| CatalogueEntry {
672        entry_type: CatalogueEntryType::MATCHER,
673        provider_type: CatalogueEntryProviderType::CORE,
674        plugin: None,
675        key: key.to_string(),
676        values: hashmap!{ "spec-version".to_string() => version.to_string() }
677      })
678      .collect();
679    register_core_entries(&entries);
680  }
681
682  fn resolved_core_key(entry_key: &str) -> String {
683    match resolve_capability(entry_key, CatalogueEntryType::MATCHER) {
684      Ok(ResolvedCapability::Core(key)) => key,
685      other => panic!("expected '{}' to resolve to a core entry, got {:?}", entry_key, other)
686    }
687  }
688
689  #[test]
690  fn resolve_capability_resolves_a_core_rule_by_the_name_it_is_registered_under() {
691    register_core_matcher_entries();
692
693    // The name a Pact file (and a plugin calling back) uses - the same string the driver puts in
694    // MatchFieldRequest.rule.type, so a plugin can forward a rule it was handed straight back
695    expect!(resolved_core_key("type")).to(be_equal_to("type".to_string()));
696    expect!(resolved_core_key("regex")).to(be_equal_to("regex".to_string()));
697    expect!(resolved_core_key("date")).to(be_equal_to("date".to_string()));
698    expect!(resolved_core_key("equality")).to(be_equal_to("equality".to_string()));
699    expect!(resolved_core_key("semver")).to(be_equal_to("semver".to_string()));
700    expect!(resolved_core_key("not-empty")).to(be_equal_to("not-empty".to_string()));
701
702    // Rules whose name ends in another rule's name are distinct entries, not ambiguous with it
703    expect!(resolved_core_key("content-type")).to(be_equal_to("content-type".to_string()));
704    expect!(resolved_core_key("min-type")).to(be_equal_to("min-type".to_string()));
705    expect!(resolved_core_key("min-max-type")).to(be_equal_to("min-max-type".to_string()));
706
707    // More of the catalogue key resolves the same entry
708    expect!(resolved_core_key("core/matcher/date")).to(be_equal_to("date".to_string()));
709    expect!(resolved_core_key("matcher/date")).to(be_equal_to("date".to_string()));
710  }
711
712  #[test]
713  fn resolve_capability_does_not_match_a_key_component_as_a_substring() {
714    // "type" names the `type` rule and nothing else - if a component matched by suffix it would
715    // also name `content-type`, `min-type` and `max-type`, and be ambiguous across all of them
716    expect!(names_catalogue_key("core/matcher/type", "type")).to(be_true());
717    expect!(names_catalogue_key("core/matcher/content-type", "type")).to(be_false());
718    expect!(names_catalogue_key("core/matcher/type", "matcher/type")).to(be_true());
719    expect!(names_catalogue_key("core/matcher/type", "core/matcher/type")).to(be_true());
720    expect!(names_catalogue_key("core/matcher/type", "r/type")).to(be_false());
721    expect!(names_catalogue_key("core/content-matcher/xml", "xml")).to(be_true());
722    expect!(names_catalogue_key("core/content-matcher/xml", "ml")).to(be_false());
723  }
724
725  #[test]
726  fn lookup_entry_matches_by_name_not_by_substring() {
727    let name = "lookup_entry_matches_by_name_not_by_substring";
728    let manifest = PactPluginManifest { name: name.to_string(), .. PactPluginManifest::default() };
729    register_plugin_entries(&manifest, &vec![
730      ProtoCatalogueEntry {
731        r#type: CatalogueEntryType::CONTENT_MATCHER.to_proto_value(),
732        key: name.to_string(),
733        values: hashmap!{}
734      },
735      ProtoCatalogueEntry {
736        r#type: CatalogueEntryType::MATCHER.to_proto_value(),
737        key: format!("other-{}", name),
738        values: hashmap!{}
739      }
740    ]);
741
742    let by_name = lookup_entry(name).map(|entry| entry.entry_type);
743    let by_components = lookup_entry(&format!("content-matcher/{}", name)).map(|entry| entry.entry_type);
744    let fully_qualified = lookup_entry(&format!("plugin/{}/content-matcher/{}", name, name))
745      .map(|entry| entry.entry_type);
746    // A trailing substring of a component names nothing
747    let by_substring = lookup_entry(&name[3..]);
748
749    remove_plugin_entries(name);
750
751    expect!(by_name).to(be_some().value(CatalogueEntryType::CONTENT_MATCHER));
752    expect!(by_components).to(be_some().value(CatalogueEntryType::CONTENT_MATCHER));
753    expect!(fully_qualified).to(be_some().value(CatalogueEntryType::CONTENT_MATCHER));
754    expect!(by_substring).to(be_none());
755  }
756
757  #[test]
758  fn lookup_entry_finds_a_core_rule_by_name() {
759    register_core_matcher_entries();
760
761    expect!(lookup_entry("type").map(|entry| entry.key)).to(be_some().value("type".to_string()));
762    expect!(lookup_entry("date").map(|entry| entry.key)).to(be_some().value("date".to_string()));
763    expect!(lookup_entry("matcher/date").map(|entry| entry.key)).to(be_some().value("date".to_string()));
764    expect!(lookup_entry("core/matcher/date").map(|entry| entry.key)).to(be_some().value("date".to_string()));
765  }
766
767  #[test]
768  fn resolve_capability_reports_a_plugin_rule_sharing_a_core_rule_name_as_ambiguous() {
769    // Core rules are now keyed by the rule name itself, so a plugin registering the same name is a
770    // genuine collision. Neither wins silently - both are reachable by a fully qualified key.
771    let name = "resolve_capability_reports_a_plugin_rule_sharing_a_core_rule_name_as_ambiguous";
772    register_core_entries(&vec![CatalogueEntry {
773      entry_type: CatalogueEntryType::MATCHER,
774      provider_type: CatalogueEntryProviderType::CORE,
775      plugin: None,
776      key: name.to_string(),
777      values: hashmap!{}
778    }]);
779    // Before the plugin registers anything, the bare name finds the core rule
780    let core_first = resolved_core_key(name);
781
782    let manifest = PactPluginManifest { name: name.to_string(), .. PactPluginManifest::default() };
783    register_plugin_entries(&manifest, &vec![ProtoCatalogueEntry {
784      r#type: CatalogueEntryType::MATCHER.to_proto_value(),
785      key: name.to_string(),
786      values: hashmap!{}
787    }]);
788
789    let ambiguous = resolve_capability(name, CatalogueEntryType::MATCHER);
790    let still_core = resolved_core_key(&format!("core/matcher/{}", name));
791    let plugin_rule = resolve_capability(
792      &format!("plugin/{}/matcher/{}", name, name), CatalogueEntryType::MATCHER
793    );
794    remove_plugin_entries(name);
795
796    expect!(core_first).to(be_equal_to(name.to_string()));
797    let error = ambiguous.expect_err("expected the shared name to be ambiguous").to_string();
798    expect!(error.contains("Ambiguous catalogue entry key")).to(be_true());
799    expect!(error.contains(&format!("core/matcher/{}", name))).to(be_true());
800    expect!(error.contains(&format!("plugin/{}/matcher/{}", name, name))).to(be_true());
801    expect!(still_core).to(be_equal_to(name.to_string()));
802    match plugin_rule.expect("expected the plugin's own entry to resolve when fully qualified") {
803      ResolvedCapability::Plugin(resolved_manifest) => expect!(resolved_manifest.name).to(be_equal_to(name.to_string())),
804      ResolvedCapability::Core(key) => panic!("expected the plugin entry, got core '{}'", key)
805    };
806  }
807
808  #[test]
809  fn resolve_capability_returns_a_clear_error_for_an_unregistered_key() {
810    let result = resolve_capability(
811      "resolve_capability_returns_a_clear_error_for_an_unregistered_key",
812      CatalogueEntryType::CONTENT_MATCHER
813    );
814
815    let err = result.expect_err("expected an error for an unregistered key");
816    expect!(err.to_string().contains("No catalogue entry found")).to(be_true());
817  }
818
819  #[test]
820  fn resolve_capability_returns_a_clear_error_for_the_wrong_capability_shape() {
821    let key = "resolve_capability_returns_a_clear_error_for_the_wrong_capability_shape";
822    register_core_entries(&vec![CatalogueEntry {
823      entry_type: CatalogueEntryType::CONTENT_GENERATOR,
824      provider_type: CatalogueEntryProviderType::CORE,
825      plugin: None,
826      key: key.to_string(),
827      values: hashmap!{}
828    }]);
829
830    let result = resolve_capability(key, CatalogueEntryType::CONTENT_MATCHER);
831
832    let err = result.expect_err("expected an error when the entry is a generator, not a matcher");
833    expect!(err.to_string().contains("is a CONTENT_GENERATOR, not a CONTENT_MATCHER")).to(be_true());
834  }
835
836  #[test]
837  fn resolve_capability_rejects_an_ambiguous_key_shared_by_a_core_and_a_plugin_entry() {
838    let key = "resolve_capability_rejects_an_ambiguous_key_shared_by_a_core_and_a_plugin_entry";
839    let manifest = PactPluginManifest {
840      name: "resolve_capability_rejects_an_ambiguous_key_shared_by_a_core_and_a_plugin_entry".to_string(),
841      .. PactPluginManifest::default()
842    };
843    register_core_entries(&vec![CatalogueEntry {
844      entry_type: CatalogueEntryType::CONTENT_MATCHER,
845      provider_type: CatalogueEntryProviderType::CORE,
846      plugin: None,
847      key: key.to_string(),
848      values: hashmap!{}
849    }]);
850    register_plugin_entries(&manifest, &vec![ProtoCatalogueEntry {
851      r#type: catalogue_entry::EntryType::ContentMatcher as i32,
852      key: key.to_string(),
853      values: hashmap!{}
854    }]);
855
856    let result = resolve_capability(key, CatalogueEntryType::CONTENT_MATCHER);
857
858    remove_plugin_entries(&manifest.name);
859
860    let err = result.expect_err("expected an error for a key matching more than one entry");
861    expect!(err.to_string().contains("Ambiguous catalogue entry key")).to(be_true());
862  }
863}