use std::borrow::Cow;
use std::future::Future;
use std::pin::Pin;
use serde::Deserialize;
use serde_json::{Map, Value};
#[cfg(feature = "demo")]
pub use crate::demo::ProjectSummary;
#[cfg(feature = "demo")]
pub use crate::demo::get_project::{MAX_ID_BYTES, get_project};
#[cfg(feature = "demo")]
pub use crate::demo::list_projects::{MAX_SEARCH_CHARS, ProjectList, list_projects};
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct TenantId(Cow<'static, str>);
impl TenantId {
pub const fn from_static(id: &'static str) -> Self {
Self(Cow::Borrowed(id))
}
pub fn new(id: impl Into<String>) -> Self {
Self(Cow::Owned(id.into()))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Permission(&'static str);
impl Permission {
pub const fn new(name: &'static str) -> Self {
Self(name)
}
pub fn name(self) -> &'static str {
self.0
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Principal {
name: Cow<'static, str>,
tenant: TenantId,
permissions: Cow<'static, [Permission]>,
}
impl Principal {
pub const fn new(
name: &'static str,
tenant: TenantId,
permissions: &'static [Permission],
) -> Self {
Self {
name: Cow::Borrowed(name),
tenant,
permissions: Cow::Borrowed(permissions),
}
}
pub fn owned(
name: impl Into<String>,
tenant: TenantId,
permissions: impl Into<Vec<Permission>>,
) -> Self {
Self {
name: Cow::Owned(name.into()),
tenant,
permissions: Cow::Owned(permissions.into()),
}
}
pub fn name(&self) -> &str {
&self.name
}
pub fn tenant(&self) -> &TenantId {
&self.tenant
}
pub fn has(&self, permission: Permission) -> bool {
self.permissions.contains(&permission)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum OpError {
Forbidden,
InvalidRequest,
NotFound,
Internal,
Invalid {
code: &'static str,
phrase: &'static str,
},
}
impl OpError {
pub fn code(self) -> &'static str {
match self {
Self::Forbidden => "forbidden",
Self::InvalidRequest => "invalid_request",
Self::NotFound => "not_found",
Self::Internal => "internal",
Self::Invalid { code, .. } => code,
}
}
}
impl std::fmt::Display for OpError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.code())
}
}
impl std::error::Error for OpError {}
pub type Args = Map<String, Value>;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Param {
pub name: &'static str,
pub description: &'static str,
pub required: bool,
}
impl Param {
pub const fn required(name: &'static str, description: &'static str) -> Self {
Self {
name,
description,
required: true,
}
}
pub const fn optional(name: &'static str, description: &'static str) -> Self {
Self {
name,
description,
required: false,
}
}
}
pub type OpFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, OpError>> + Send + 'a>>;
pub enum Run<S, T> {
Sync(fn(&S, &Principal, &Args) -> Result<T, OpError>),
Async(for<'a> fn(&'a S, &'a Principal, &'a Args) -> OpFuture<'a, T>),
}
impl<S, T> Clone for Run<S, T> {
fn clone(&self) -> Self {
*self
}
}
impl<S, T> Copy for Run<S, T> {}
pub struct Operation<S, T> {
pub name: &'static str,
pub description: &'static str,
pub permission: Permission,
pub params: &'static [Param],
pub run: Run<S, T>,
}
impl<S, T> Operation<S, T> {
pub async fn call(&self, state: &S, principal: &Principal, args: &Args) -> Result<T, OpError> {
self.admit(principal, args)?;
match self.run {
Run::Sync(run) => run(state, principal, args),
Run::Async(run) => run(state, principal, args).await,
}
}
pub fn admit(&self, principal: &Principal, args: &Args) -> Result<(), OpError> {
if !principal.has(self.permission) {
return Err(OpError::Forbidden);
}
let declared = |key: &str| self.params.iter().any(|param| param.name == key);
let known = args
.iter()
.all(|(key, value)| value.is_string() && declared(key));
let complete = self
.params
.iter()
.all(|param| !param.required || args.contains_key(param.name));
if known && complete {
Ok(())
} else {
Err(OpError::InvalidRequest)
}
}
pub fn check(&self) -> Result<(), InvalidDeclaration> {
let invalid = |reason| {
Err(InvalidDeclaration {
operation: self.name,
reason,
})
};
if !is_snake_case(self.name) {
return invalid("the name is not snake_case of at most 64 bytes");
}
if !is_snake_case(self.permission.name()) {
return invalid("the permission is not snake_case of at most 64 bytes");
}
if self.description.trim().is_empty() {
return invalid("the description is empty");
}
for (i, param) in self.params.iter().enumerate() {
if !is_snake_case(param.name) {
return invalid("a parameter name is not snake_case of at most 64 bytes");
}
if param.description.trim().is_empty() {
return invalid("a parameter has no description");
}
if self.params[..i]
.iter()
.any(|other| other.name == param.name)
{
return invalid("a parameter is declared twice");
}
}
Ok(())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct InvalidDeclaration {
pub operation: &'static str,
pub reason: &'static str,
}
impl std::fmt::Display for InvalidDeclaration {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "operation {:?}: {}", self.operation, self.reason)
}
}
impl std::error::Error for InvalidDeclaration {}
fn is_snake_case(name: &str) -> bool {
name.len() <= 64
&& name.starts_with(|c: char| c.is_ascii_lowercase())
&& name
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
}
pub fn decode<'a, A: Deserialize<'a>>(args: &'a Args) -> Result<A, OpError> {
A::deserialize(args).map_err(|_| OpError::InvalidRequest)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn error_codes_are_stable() {
assert_eq!(OpError::Forbidden.code(), "forbidden");
assert_eq!(OpError::InvalidRequest.code(), "invalid_request");
assert_eq!(OpError::NotFound.code(), "not_found");
assert_eq!(OpError::Internal.code(), "internal");
assert_eq!(OpError::Internal.to_string(), "internal");
}
#[test]
fn principals_are_static_or_owned_and_compare_by_value() {
const READ: Permission = Permission::new("read");
const STATIC: Principal = Principal::new("ann", TenantId::from_static("t1"), &[READ]);
let owned = Principal::owned(String::from("ann"), TenantId::new("t1"), vec![READ]);
assert_eq!(STATIC, owned);
assert_eq!(owned.name(), "ann");
assert_eq!(owned.tenant().as_str(), "t1");
assert!(owned.has(READ));
assert!(!owned.has(Permission::new("write")));
assert_ne!(TenantId::new("t1"), TenantId::from_static("t2"));
}
#[test]
fn param_helpers_set_required() {
assert!(Param::required("id", "The id.").required);
assert!(!Param::optional("q", "A search.").required);
}
}