pub mod digest;
pub mod inventory;
pub mod load;
pub mod manifest;
pub mod operations;
pub mod pact;
pub mod policy;
pub mod verify;
use std::collections::{BTreeMap, BTreeSet};
use crate::config::DemandFormat;
use crate::contract::{Contract, EndpointKey, Span, TypeRef, Unmodelled};
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Route {
pub method: String,
pub path: String,
}
impl Route {
#[must_use]
pub fn new(method: &str, path: &str) -> Self {
Self {
method: method.trim().to_ascii_uppercase(),
path: normalise_path(path),
}
}
}
impl std::fmt::Display for Route {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(formatter, "{} {}", self.method, self.path)
}
}
fn normalise_path(path: &str) -> String {
let path = path.trim();
let path = path.split(['?', '#']).next().unwrap_or(path);
let trimmed = path.trim_end_matches('/');
if trimmed.is_empty() {
return "/".to_owned();
}
if trimmed.starts_with('/') {
trimmed.to_owned()
} else {
format!("/{trimmed}")
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Demand {
pub consumer: String,
pub provider: String,
pub source: String,
pub usages: BTreeSet<Usage>,
pub unmodelled: Vec<Unmodelled>,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Usage {
pub route: Route,
pub kind: UsageKind,
pub span: Span,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum UsageKind {
Endpoint,
Request { media_type: String, ty: TypeRef },
Response {
status: String,
media_type: String,
ty: TypeRef,
},
Parameter {
name: String,
location: String,
value: Option<String>,
},
}
pub fn ingest(format: DemandFormat, source: &str, bytes: &[u8]) -> Result<Demand, String> {
match format {
DemandFormat::Pact => pact::ingest(source, bytes),
DemandFormat::GraphqlOperations => operations::ingest(source, bytes),
DemandFormat::Manifest => manifest::ingest(source, bytes),
}
}
#[must_use]
pub fn identify(path: &std::path::Path) -> Option<DemandFormat> {
let bytes = std::fs::read(path).ok()?;
if bytes.len() > 8 * 1024 * 1024 {
return None;
}
let source = crate::check::display_path(path);
let name = source.to_ascii_lowercase();
let candidates: &[DemandFormat] = if name.ends_with(".toml") {
&[DemandFormat::Manifest]
} else if name.ends_with(".json") {
&[DemandFormat::Pact]
} else if name.ends_with(".graphql") || name.ends_with(".gql") {
&[DemandFormat::GraphqlOperations]
} else {
&[]
};
candidates
.iter()
.find(|format| ingest(**format, &source, &bytes).is_ok())
.copied()
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bound {
pub expectation: Contract,
pub issues: Vec<BindIssue>,
pub usage_index: BTreeMap<EndpointKey, Usages>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Usages {
pub span: Span,
pub subjects: BTreeSet<String>,
pub statuses: BTreeSet<String>,
pub reads: BTreeSet<String>,
pub sends: BTreeSet<String>,
}
impl Usages {
#[must_use]
pub fn empty(span: Span) -> Self {
Self::new(span)
}
fn new(span: Span) -> Self {
Self {
span,
subjects: BTreeSet::new(),
statuses: BTreeSet::new(),
reads: BTreeSet::new(),
sends: BTreeSet::new(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BindIssue {
pub rule: &'static str,
pub message: String,
pub endpoint: Option<EndpointKey>,
pub subject: Option<String>,
pub span: Span,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PathBinding {
Bound {
template: String,
parameters: BTreeMap<String, String>,
},
Ambiguous(Vec<String>),
Unmatched,
}
#[must_use]
pub fn bind_path<'a>(concrete: &str, templates: impl IntoIterator<Item = &'a str>) -> PathBinding {
let concrete = normalise_path(concrete);
let wanted: Vec<&str> = segments(&concrete);
let mut matches: Vec<(usize, String, BTreeMap<String, String>)> = Vec::new();
for template in templates {
let parts = segments(template);
if parts.len() != wanted.len() {
continue;
}
let mut parameters = BTreeMap::new();
let mut ok = true;
let mut templated = 0usize;
for (part, actual) in parts.iter().zip(&wanted) {
match part
.strip_prefix('{')
.and_then(|rest| rest.strip_suffix('}'))
{
Some(name) => {
templated += 1;
if actual.is_empty() {
ok = false;
break;
}
parameters.insert(name.to_owned(), (*actual).to_owned());
}
None => {
if part != actual {
ok = false;
break;
}
}
}
}
if ok {
matches.push((templated, template.to_owned(), parameters));
}
}
if matches.is_empty() {
return PathBinding::Unmatched;
}
matches.sort();
let fewest = matches[0].0;
let contenders: Vec<_> = matches
.iter()
.filter(|(templated, _, _)| *templated == fewest)
.collect();
if contenders.len() > 1 {
return PathBinding::Ambiguous(
contenders
.iter()
.map(|(_, template, _)| template.clone())
.collect(),
);
}
let (_, template, parameters) = matches.into_iter().next().expect("non-empty");
PathBinding::Bound {
template,
parameters,
}
}
fn segments(path: &str) -> Vec<&str> {
path.split('/').filter(|part| !part.is_empty()).collect()
}
pub const ANY_SCALAR: &str = "*";
#[must_use]
pub fn any_scalar() -> TypeRef {
TypeRef::Scalar {
ty: ANY_SCALAR.to_owned(),
format: None,
nullable: false,
constraints: crate::contract::Constraints::default(),
}
}
#[must_use]
pub fn normalise_media(media_type: &str) -> String {
media_type
.split(';')
.next()
.unwrap_or(media_type)
.trim()
.to_ascii_lowercase()
}
pub use verify::bind;