use bytes::Bytes;
use http::{HeaderMap, HeaderValue, Method, StatusCode, header};
use serde_json::Value;
use crate::api::{Api, TmfRequest, TmfResponse};
use crate::core::EventKind;
use super::notify::{
HUB_COLLECTION, Listener, change_event, event_type_for, matching_listeners, state_change_kind,
};
use super::semantics::{apply_json_patch, apply_merge_patch, project_fields};
use super::store::{Replaced, ResourceStore, Selection, StoreError};
#[derive(Clone)]
pub struct TmfHandler<S> {
base_url: String,
surface: Surface,
store: S,
ids: std::sync::Arc<dyn IdGenerator>,
notifier: Option<std::sync::Arc<dyn Notifier>>,
max_page_size: Option<usize>,
}
impl<S: std::fmt::Debug> std::fmt::Debug for TmfHandler<S> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TmfHandler")
.field("base_url", &self.base_url)
.field("store", &self.store)
.finish_non_exhaustive()
}
}
#[derive(Debug, Clone, Copy)]
enum Surface {
Declared(&'static Api),
#[cfg_attr(
not(feature = "mock"),
allow(dead_code, reason = "only the mock serves every collection")
)]
Any,
}
impl<S> TmfHandler<S> {
pub fn new(api: &'static Api, base_url: impl Into<String>, store: S) -> Self {
Self::with_surface(Surface::Declared(api), &base_url.into(), store)
}
pub fn for_host(api: &'static Api, host: &str, store: S) -> Self {
Self::new(api, api.url_on(host), store)
}
#[cfg(feature = "mock")]
pub(crate) fn serving_anything(base_url: impl Into<String>, store: S) -> Self {
Self::with_surface(Surface::Any, &base_url.into(), store)
}
fn with_surface(surface: Surface, base_url: &str, store: S) -> Self {
Self {
base_url: base_url.trim_end_matches('/').to_owned(),
surface,
store,
ids: std::sync::Arc::new(RandomId::default()),
notifier: None,
max_page_size: None,
}
}
#[must_use]
pub fn with_max_page_size(mut self, max: usize) -> Self {
self.max_page_size = Some(max);
self
}
#[must_use]
pub fn with_id_generator(mut self, generator: impl IdGenerator + 'static) -> Self {
self.ids = std::sync::Arc::new(generator);
self
}
#[must_use]
pub fn with_notifier(mut self, notifier: impl Notifier + 'static) -> Self {
self.notifier = Some(std::sync::Arc::new(notifier));
self
}
#[must_use]
pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
base_url
.into()
.trim_end_matches('/')
.clone_into(&mut self.base_url);
self
}
#[must_use]
pub fn base_url(&self) -> &str {
&self.base_url
}
#[must_use]
pub fn api(&self) -> Option<&'static Api> {
match self.surface {
Surface::Declared(api) => Some(api),
Surface::Any => None,
}
}
#[must_use]
pub fn refusal(&self, method: &Method, url: &str) -> Option<TmfResponse> {
let Some((collection, id)) = route(&self.base_url, url) else {
return Some(no_resource_at(url));
};
let on_item = id.is_some();
let allowed = match self.surface {
Surface::Declared(api) => {
let Some(declared) = api.collection(&collection) else {
return Some(error_response(
StatusCode::NOT_FOUND,
"40401",
&format!("{} declares no {collection} collection", api.name),
));
};
declared.allowed_methods(on_item)
}
Surface::Any if on_item => vec![Method::GET, Method::PATCH, Method::DELETE],
Surface::Any => vec![Method::GET, Method::POST],
};
if allowed.is_empty() {
return Some(no_resource_at(url));
}
(!allowed.contains(method)).then(|| method_not_allowed(method, &allowed))
}
#[must_use]
pub fn store(&self) -> &S {
&self.store
}
pub fn store_mut(&mut self) -> &mut S {
&mut self.store
}
}
impl<S: ResourceStore> TmfHandler<S> {
pub async fn notify(&self, collection: &str, kind: EventKind, resource: &Value) {
let Some(notifier) = &self.notifier else {
return;
};
let Ok(hubs) = self.store.list(HUB_COLLECTION, &Selection::default()).await else {
return;
};
if hubs.items.is_empty() {
return;
}
let event = change_event(collection, kind, resource, &self.ids.next_id());
let event_type = event_type_for(collection, kind);
for listener in matching_listeners(&hubs.items, &event) {
notifier.notify(&listener, &event_type, &event).await;
}
}
fn is_notifiable(collection: &str) -> bool {
collection != HUB_COLLECTION
}
}
impl<S: ResourceStore> TmfHandler<S> {
pub async fn handle(&self, request: &TmfRequest) -> TmfResponse {
if let Some(refused) = self.refusal(&request.method, &request.url) {
return refused;
}
let Some((collection, id)) = route(&self.base_url, &request.url) else {
return no_resource_at(&request.url);
};
if !self.store.has_collection(&collection).await {
return error_response(
StatusCode::NOT_FOUND,
"40401",
&format!("This API does not serve a {collection} collection"),
);
}
match (request.method.clone(), id) {
(Method::GET, None) => self.list(&collection, request).await,
(Method::GET, Some(id)) => self.get(&collection, &id, request).await,
(Method::POST, None) => self.create(&collection, request).await,
(Method::PATCH, Some(id)) => self.patch(&collection, &id, request).await,
(Method::DELETE, Some(id)) => self.delete(&collection, &id, request).await,
(method, _) => method_not_allowed(&method, &[]),
}
}
async fn list(&self, collection: &str, request: &TmfRequest) -> TmfResponse {
if request.query.contains_key("filter") {
return error_response(
StatusCode::BAD_REQUEST,
"40001",
"JSONPath `filter` is not supported by this server; filter by \
attribute name instead",
);
}
let selection = match Selection::from_query(&request.query) {
Ok(selection) => match self.max_page_size {
Some(max) => selection.capped_at(max),
None => selection,
},
Err(reason) => return error_response(StatusCode::BAD_REQUEST, "40001", &reason),
};
let matched = match self.store.list(collection, &selection).await {
Ok(matched) => matched,
Err(error) => return store_error_response(&error),
};
let fields = request.query.get("fields").map(String::as_str);
let items: Vec<Value> = matched
.items
.iter()
.map(|item| project_fields(item, fields))
.collect();
let mut headers = HeaderMap::new();
insert_count(&mut headers, "x-total-count", matched.total);
insert_count(&mut headers, "x-result-count", items.len());
let status = if selection.offset + items.len() < matched.total {
StatusCode::PARTIAL_CONTENT
} else {
StatusCode::OK
};
json_response(status, headers, &Value::Array(items))
}
async fn get(&self, collection: &str, id: &str, request: &TmfRequest) -> TmfResponse {
match self.store.get(collection, id).await {
Ok(Some(found)) => {
let tag = entity_tag(&found);
let mut headers = HeaderMap::new();
if let Ok(value) = HeaderValue::from_str(&tag) {
headers.insert(header::ETAG, value);
}
if if_none_match(request).is_some_and(|expected| expected.matches(&tag)) {
return TmfResponse::new(StatusCode::NOT_MODIFIED, headers, Bytes::new());
}
json_response(
StatusCode::OK,
headers,
&project_fields(&found, request.query.get("fields").map(String::as_str)),
)
}
Ok(None) => not_found(collection, id),
Err(error) => store_error_response(&error),
}
}
async fn create(&self, collection: &str, request: &TmfRequest) -> TmfResponse {
let mut resource = match json_body(request) {
Ok(body) => body,
Err(reason) => return error_response(StatusCode::BAD_REQUEST, "40001", &reason),
};
let Some(object) = resource.as_object_mut() else {
return error_response(
StatusCode::BAD_REQUEST,
"40001",
"A resource must be a JSON object",
);
};
let id = match object.get("id").and_then(Value::as_str) {
Some(id) => id.to_owned(),
None => self.ids.next_id(),
};
object.insert("id".to_owned(), Value::String(id.clone()));
let href = format!("{}/{collection}/{id}", self.base_url);
object
.entry("href")
.or_insert_with(|| Value::String(href.clone()));
match self.store.create(collection, resource).await {
Ok(created) => {
if Self::is_notifiable(collection) {
self.notify(collection, EventKind::Create, &created).await;
}
let mut headers = HeaderMap::new();
let location = created
.get("href")
.and_then(Value::as_str)
.unwrap_or(href.as_str());
if let Ok(value) = HeaderValue::from_str(location) {
headers.insert(header::LOCATION, value);
}
insert_etag(&mut headers, &created);
json_response(StatusCode::CREATED, headers, &created)
}
Err(error) => store_error_response(&error),
}
}
async fn patch(&self, collection: &str, id: &str, request: &TmfRequest) -> TmfResponse {
let patch = match json_body(request) {
Ok(body) => body,
Err(reason) => return error_response(StatusCode::BAD_REQUEST, "40001", &reason),
};
let mut target = match self.store.get(collection, id).await {
Ok(Some(found)) => found,
Ok(None) => return not_found(collection, id),
Err(error) => return store_error_response(&error),
};
let read_tag = entity_tag(&target);
let before = target.clone();
let conditional = if_match(request);
if let Some(expected) = &conditional
&& !expected.matches(&read_tag)
{
return precondition_failed();
}
let content_type = request
.headers
.get(header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.unwrap_or("application/json");
if content_type.starts_with("application/json-patch") {
if let Err(reason) = apply_json_patch(&mut target, &patch) {
return error_response(StatusCode::UNPROCESSABLE_ENTITY, "42201", &reason);
}
} else {
apply_merge_patch(&mut target, &patch);
}
if let Some(object) = target.as_object_mut() {
object.insert("id".to_owned(), Value::String(id.to_owned()));
}
let written = if conditional.is_some() {
self.store
.replace_if_unchanged(collection, id, target, &read_tag)
.await
} else {
self.store
.replace(collection, id, target)
.await
.map(|found| found.map_or(Replaced::Missing, Replaced::Updated))
};
match written {
Ok(Replaced::Updated(updated)) => {
if Self::is_notifiable(collection) {
let kind = change_kind(collection, &before, &updated);
self.notify(collection, kind, &updated).await;
}
let mut headers = HeaderMap::new();
insert_etag(&mut headers, &updated);
json_response(StatusCode::OK, headers, &updated)
}
Ok(Replaced::Missing) => not_found(collection, id),
Ok(Replaced::Stale) => precondition_failed(),
Err(error) => store_error_response(&error),
}
}
async fn delete(&self, collection: &str, id: &str, request: &TmfRequest) -> TmfResponse {
let Some(expected) = if_match(request) else {
return match self.store.delete(collection, id).await {
Ok(true) => {
if Self::is_notifiable(collection) {
let gone = serde_json::json!({"id": id});
self.notify(collection, EventKind::Delete, &gone).await;
}
TmfResponse::new(StatusCode::NO_CONTENT, HeaderMap::new(), Bytes::new())
}
Ok(false) => not_found(collection, id),
Err(error) => store_error_response(&error),
};
};
let current = match self.store.get(collection, id).await {
Ok(Some(current)) => current,
Ok(None) => return not_found(collection, id),
Err(error) => return store_error_response(&error),
};
let tag = entity_tag(¤t);
if !expected.matches(&tag) {
return precondition_failed();
}
match self.store.delete_if_unchanged(collection, id, &tag).await {
Ok(Replaced::Updated(removed)) => {
if Self::is_notifiable(collection) {
self.notify(collection, EventKind::Delete, &removed).await;
}
TmfResponse::new(StatusCode::NO_CONTENT, HeaderMap::new(), Bytes::new())
}
Ok(Replaced::Missing) => not_found(collection, id),
Ok(Replaced::Stale) => precondition_failed(),
Err(error) => store_error_response(&error),
}
}
}
pub(crate) fn route(base_url: &str, url: &str) -> Option<(String, Option<String>)> {
let path = url.split('?').next().unwrap_or_default();
let rest = path
.strip_prefix(base_url)
.or_else(|| after_version_segment(path))
.unwrap_or_else(|| trailing_segments(path));
let mut segments = rest.split('/').filter(|segment| !segment.is_empty());
let collection = segments.next()?.to_owned();
let id = segments.next().map(ToOwned::to_owned);
if segments.next().is_some() {
return None;
}
Some((collection, id))
}
fn after_version_segment(path: &str) -> Option<&str> {
let without_scheme = path.split_once("://").map_or(path, |(_, rest)| rest);
let mut offset = path.len() - without_scheme.len();
for segment in without_scheme.split('/') {
let is_version = segment.starts_with('v')
&& segment.len() > 1
&& segment[1..].chars().all(|c| c.is_ascii_digit() || c == '.');
if is_version {
return Some(&path[offset + segment.len()..]);
}
offset += segment.len() + 1;
}
None
}
fn trailing_segments(path: &str) -> &str {
let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
let take = segments.len().min(2);
let tail = &segments[segments.len() - take..];
tail.first().map_or("", |first| {
let start = path.rfind(first).unwrap_or(0);
&path[start..]
})
}
#[async_trait::async_trait]
pub trait Notifier: Send + Sync {
async fn notify(&self, listener: &Listener, event_type: &str, event: &Value);
}
#[async_trait::async_trait]
impl Notifier for () {
async fn notify(&self, _: &Listener, _: &str, _: &Value) {}
}
pub trait IdGenerator: Send + Sync {
fn next_id(&self) -> String;
}
pub struct RandomId {
key: std::hash::RandomState,
counter: std::sync::atomic::AtomicU64,
}
impl Default for RandomId {
fn default() -> Self {
Self {
key: std::hash::RandomState::new(),
counter: std::sync::atomic::AtomicU64::new(0),
}
}
}
impl std::fmt::Debug for RandomId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RandomId").finish_non_exhaustive()
}
}
impl IdGenerator for RandomId {
fn next_id(&self) -> String {
use std::hash::BuildHasher;
use std::sync::atomic::Ordering;
let n = self.counter.fetch_add(1, Ordering::Relaxed);
let high = self.key.hash_one((0u8, n));
let low = self.key.hash_one((1u8, n));
format!("{high:016x}{low:016x}")
}
}
fn json_body(request: &TmfRequest) -> Result<Value, String> {
let Some(body) = request.body.as_ref() else {
return Err("Missing request body".to_owned());
};
serde_json::from_slice(body).map_err(|error| format!("Body is not valid JSON: {error}"))
}
fn change_kind(collection: &str, before: &Value, after: &Value) -> EventKind {
const STATE_MEMBERS: [&str; 3] = ["lifecycleStatus", "state", "status"];
if before.get("operatingStatus") != after.get("operatingStatus") {
return EventKind::OperatingStatusChange;
}
let moved = STATE_MEMBERS
.iter()
.any(|member| before.get(member) != after.get(member));
if moved {
state_change_kind(collection)
} else {
EventKind::AttributeValueChange
}
}
fn precondition_failed() -> TmfResponse {
error_response(
StatusCode::PRECONDITION_FAILED,
"41201",
"The resource has changed since the tag in If-Match was issued",
)
}
fn not_found(collection: &str, id: &str) -> TmfResponse {
error_response(
StatusCode::NOT_FOUND,
"40401",
&format!("No {collection} with id {id}"),
)
}
fn store_error_response(error: &StoreError) -> TmfResponse {
let (status, code) = match error {
StoreError::Accepted { monitor } => {
let mut headers = HeaderMap::new();
if let Some(value) = monitor
.as_deref()
.and_then(|url| HeaderValue::from_str(url).ok())
{
headers.insert(header::LOCATION, value);
}
return TmfResponse::new(StatusCode::ACCEPTED, headers, Bytes::new());
}
StoreError::Invalid(_) => (StatusCode::BAD_REQUEST, "40001"),
StoreError::Forbidden(_) => (StatusCode::FORBIDDEN, "40301"),
StoreError::Conflict(_) => (StatusCode::CONFLICT, "40901"),
StoreError::Unprocessable(_) => (StatusCode::UNPROCESSABLE_ENTITY, "42201"),
StoreError::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "50001"),
};
error_response(status, code, &error.to_string())
}
#[must_use]
pub fn entity_tag(resource: &Value) -> String {
use std::hash::{Hash, Hasher};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
serde_json::to_string(resource)
.unwrap_or_default()
.hash(&mut hasher);
format!("\"{:016x}\"", hasher.finish())
}
fn insert_etag(headers: &mut HeaderMap, resource: &Value) {
if let Ok(value) = HeaderValue::from_str(&entity_tag(resource)) {
headers.insert(header::ETAG, value);
}
}
#[derive(Debug, PartialEq, Eq)]
enum IfMatch {
Any,
Tags(Vec<String>),
}
impl IfMatch {
fn matches(&self, current: &str) -> bool {
match self {
Self::Any => true,
Self::Tags(tags) => tags.iter().any(|tag| tag == current),
}
}
}
fn if_match(request: &TmfRequest) -> Option<IfMatch> {
parse_precondition(request, header::IF_MATCH)
}
fn if_none_match(request: &TmfRequest) -> Option<IfMatch> {
parse_precondition(request, header::IF_NONE_MATCH)
}
fn parse_precondition(request: &TmfRequest, name: header::HeaderName) -> Option<IfMatch> {
let raw = request.headers.get(name)?.to_str().ok()?.trim();
if raw == "*" {
return Some(IfMatch::Any);
}
let tags: Vec<String> = raw
.split(',')
.map(str::trim)
.filter(|tag| !tag.is_empty())
.map(ToOwned::to_owned)
.collect();
(!tags.is_empty()).then_some(IfMatch::Tags(tags))
}
fn insert_count(headers: &mut HeaderMap, name: &'static str, value: usize) {
if let Ok(value) = HeaderValue::from_str(&value.to_string()) {
headers.insert(name, value);
}
}
fn json_response(status: StatusCode, mut headers: HeaderMap, body: &Value) -> TmfResponse {
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/json"),
);
let bytes = serde_json::to_vec(body).unwrap_or_else(|_| b"null".to_vec());
TmfResponse::new(status, headers, Bytes::from(bytes))
}
fn no_resource_at(url: &str) -> TmfResponse {
error_response(
StatusCode::NOT_FOUND,
"40401",
&format!("No TM Forum resource at {url}"),
)
}
fn method_not_allowed(method: &Method, allowed: &[Method]) -> TmfResponse {
let list = allowed
.iter()
.map(Method::as_str)
.collect::<Vec<_>>()
.join(", ");
let mut response = error_response(
StatusCode::METHOD_NOT_ALLOWED,
"40501",
&format!("{method} is not allowed on this path; allowed: {list}"),
);
if let Ok(value) = HeaderValue::from_str(&list) {
response.headers.insert(header::ALLOW, value);
}
response
}
pub(crate) fn error_response(status: StatusCode, code: &str, reason: &str) -> TmfResponse {
let body = serde_json::json!({
"code": code,
"reason": reason,
"status": status.as_u16().to_string(),
"@type": "Error",
});
json_response(status, HeaderMap::new(), &body)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::api::{Collection, Operation};
const TEST_API: Api = Api::new(
"TMF678",
"tmf-api/customerBillManagement/v5",
"5.0.0",
&[
Collection::read_only("appliedCustomerBillingRate"),
Collection::new(
"customerBill",
&[Operation::List, Operation::Retrieve, Operation::Update],
),
Collection::task("customerBillOnDemand"),
Collection::new("hub", &[Operation::Create, Operation::Delete]),
],
);
const BASE: &str = "http://host/tmf-api/customerBillManagement/v5";
fn bills() -> TmfHandler<crate::server::MemoryStore> {
let store = crate::server::MemoryStore::new();
store.seed(
"customerBill",
serde_json::json!({"id": "B1", "state": "new", "@type": "CustomerBill"}),
);
TmfHandler::new(&TEST_API, BASE, store)
}
fn send(method: Method, path: &str, body: Option<&str>) -> TmfRequest {
let mut request = TmfRequest::new(method, format!("{BASE}/{path}"));
if let Some(body) = body {
request.headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/merge-patch+json"),
);
request.body = Some(Bytes::from(body.to_owned()));
}
request
}
fn allow(response: &TmfResponse) -> &str {
response
.headers
.get(header::ALLOW)
.and_then(|v| v.to_str().ok())
.unwrap_or("<none>")
}
#[tokio::test]
async fn a_billing_server_refuses_what_tmf678_does_not_declare() {
let handler = bills();
let post = handler
.handle(&send(Method::POST, "customerBill", Some("{}")))
.await;
assert_eq!(
(post.status, allow(&post)),
(StatusCode::METHOD_NOT_ALLOWED, "GET")
);
let delete = handler
.handle(&send(Method::DELETE, "customerBill/B1", None))
.await;
assert_eq!(
(delete.status, allow(&delete)),
(StatusCode::METHOD_NOT_ALLOWED, "GET, PATCH")
);
let rate = handler
.handle(&send(
Method::POST,
"appliedCustomerBillingRate",
Some("{}"),
))
.await;
assert_eq!(
(rate.status, allow(&rate)),
(StatusCode::METHOD_NOT_ALLOWED, "GET")
);
assert_eq!(handler.store().collection("customerBill").len(), 1);
assert_eq!(
handler
.store()
.collection("appliedCustomerBillingRate")
.len(),
0
);
let patch = handler
.handle(&send(
Method::PATCH,
"customerBill/B1",
Some(r#"{"state":"sent"}"#),
))
.await;
assert_eq!(patch.status, StatusCode::OK);
}
#[tokio::test]
async fn every_405_names_what_is_allowed_and_undeclared_collections_are_404() {
let handler = bills();
let put = handler
.handle(&send(Method::PUT, "customerBill/B1", Some("{}")))
.await;
assert_eq!(
(put.status, allow(&put)),
(StatusCode::METHOD_NOT_ALLOWED, "GET, PATCH")
);
let hub = handler.handle(&send(Method::GET, "hub/h1", None)).await;
assert_eq!(
(hub.status, allow(&hub)),
(StatusCode::METHOD_NOT_ALLOWED, "DELETE")
);
let listener = handler
.handle(&send(Method::POST, "listener", Some("{}")))
.await;
assert_eq!(listener.status, StatusCode::NOT_FOUND);
assert_eq!(handler.store().collection("listener").len(), 0);
}
#[test]
fn for_host_roots_the_api_at_its_conventional_path() {
let handler = TmfHandler::for_host(
&TEST_API,
"https://mycsp.com/",
crate::server::MemoryStore::new(),
);
assert_eq!(
handler.base_url(),
BASE.replace("http://host", "https://mycsp.com")
);
assert_eq!(handler.api().map(|api| api.name), Some("TMF678"));
}
#[test]
fn a_collection_and_an_item_route_apart() {
let base = "http://host/tmf-api/productCatalogManagement/v5";
assert_eq!(
route(base, &format!("{base}/productOffering")),
Some(("productOffering".to_owned(), None))
);
assert_eq!(
route(base, &format!("{base}/productOffering/7655")),
Some(("productOffering".to_owned(), Some("7655".to_owned())))
);
}
#[test]
fn a_url_under_another_root_routes_by_its_version_segment() {
assert_eq!(
route(
"http://host/tmf-api/productCatalogManagement/v5",
"https://elsewhere.example/tmf-api/partyManagement/v5/individual/7"
),
Some(("individual".to_owned(), Some("7".to_owned())))
);
}
#[test]
fn a_path_deeper_than_a_resource_does_not_route() {
let base = "http://host/tmf-api/v5";
assert_eq!(route(base, &format!("{base}/a/b/c")), None);
}
#[test]
fn ids_are_not_sequential() {
let generator = RandomId::default();
let ids: std::collections::BTreeSet<String> =
(0..64).map(|_| generator.next_id()).collect();
assert_eq!(ids.len(), 64, "ids collided");
assert!(!ids.contains("1"), "ids look like a counter");
assert!(
ids.iter().all(|id| id.len() == 32),
"128 bits, rendered as hex"
);
let other = RandomId::default();
assert!(
!ids.contains(&other.next_id()),
"a second generator reproduced the first's sequence"
);
}
#[test]
fn an_id_generator_can_be_replaced() {
struct Fixed;
impl IdGenerator for Fixed {
fn next_id(&self) -> String {
"fixed".to_owned()
}
}
let handler = TmfHandler::new(
&TEST_API,
"http://host/tmf-api/x/v5",
crate::server::MemoryStore::new(),
)
.with_id_generator(Fixed);
assert_eq!(handler.ids.next_id(), "fixed");
}
#[test]
fn if_match_is_parsed_and_compared_strongly() {
fn request(value: &'static str) -> TmfRequest {
let mut request = TmfRequest::new(Method::PATCH, "http://host/x/v5/a/1");
request
.headers
.insert(header::IF_MATCH, HeaderValue::from_static(value));
request
}
assert_eq!(if_match(&TmfRequest::new(Method::PATCH, "u")), None);
assert_eq!(if_match(&request("*")), Some(IfMatch::Any));
assert!(IfMatch::Any.matches("\"abc\""));
let parsed = if_match(&request("\"abc\", \"def\"")).expect("two tags");
assert!(parsed.matches("\"def\""));
assert!(!parsed.matches("\"ghi\""));
let weak = if_match(&request("W/\"abc\"")).expect("a weak tag");
assert!(!weak.matches("\"abc\""));
}
#[test]
fn an_entity_tag_tracks_the_content() {
let a = serde_json::json!({"id": "1", "name": "old"});
let b = serde_json::json!({"id": "1", "name": "new"});
assert_eq!(entity_tag(&a), entity_tag(&a.clone()), "stable");
assert_ne!(entity_tag(&a), entity_tag(&b), "an edit changes the tag");
assert!(
entity_tag(&a).starts_with('"') && entity_tag(&a).ends_with('"'),
"RFC 9110 entity-tags are quoted"
);
}
}