use std::fmt;
use crate::hash::ContentHash;
const DOMAIN: &str = "ligase.request";
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Method {
Get,
Post,
}
impl Method {
#[must_use]
pub const fn name(self) -> &'static str {
match self {
Self::Get => "GET",
Self::Post => "POST",
}
}
#[must_use]
pub fn parse(name: &str) -> Option<Self> {
match name {
"GET" => Some(Self::Get),
"POST" => Some(Self::Post),
_ => None,
}
}
}
impl fmt::Display for Method {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct Auth {
token: String,
}
impl Auth {
#[must_use]
pub fn bearer(token: &str) -> Self {
Self {
token: token.to_owned(),
}
}
#[must_use]
pub fn header(&self) -> (&'static str, String) {
("Authorization", format!("Bearer {}", self.token))
}
}
impl fmt::Debug for Auth {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Auth(<redacted>)")
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Request {
pub method: Method,
pub url: String,
pub body: Vec<u8>,
pub auth: Option<Auth>,
}
impl Request {
#[must_use]
pub fn get(url: &str) -> Self {
Self {
method: Method::Get,
url: url.to_owned(),
body: Vec::new(),
auth: None,
}
}
#[must_use]
pub fn post(url: &str, body: &[u8]) -> Self {
Self {
method: Method::Post,
url: url.to_owned(),
body: body.to_vec(),
auth: None,
}
}
#[must_use]
pub fn with_auth(mut self, auth: Option<Auth>) -> Self {
self.auth = auth;
self
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CanonicalRequest {
method: Method,
url: String,
body: Vec<u8>,
}
impl CanonicalRequest {
#[must_use]
pub fn of(request: &Request) -> Self {
Self {
method: request.method,
url: canonical_url(&request.url),
body: request.body.clone(),
}
}
#[must_use]
pub const fn method(&self) -> Method {
self.method
}
#[must_use]
pub fn url(&self) -> &str {
&self.url
}
#[must_use]
pub fn body(&self) -> &[u8] {
&self.body
}
#[must_use]
pub fn hash(&self) -> ContentHash {
let mut preimage = Vec::with_capacity(self.url.len() + self.body.len() + 32);
for field in [
DOMAIN.as_bytes(),
self.method.name().as_bytes(),
self.url.as_bytes(),
self.body.as_slice(),
] {
preimage.extend_from_slice(&(field.len() as u64).to_le_bytes());
preimage.extend_from_slice(field);
}
ContentHash::of_bytes(&preimage)
}
}
impl fmt::Display for CanonicalRequest {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} {}", self.method, self.url)
}
}
fn canonical_url(url: &str) -> String {
let without_fragment = url.split('#').next().unwrap_or(url);
let Some((base, query)) = without_fragment.split_once('?') else {
return without_fragment.to_owned();
};
if query.is_empty() {
return base.to_owned();
}
let mut parameters: Vec<&str> = query.split('&').filter(|part| !part.is_empty()).collect();
parameters.sort_unstable();
if parameters.is_empty() {
return base.to_owned();
}
format!("{base}?{}", parameters.join("&"))
}