use std::any::Any;
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::Value;
use crate::error::ModelledError;
use crate::validate::{Rejection, Validate};
pub trait Operation: Send + Sync + 'static {
const INFO: &'static OperationInfo;
const AUTH_BEARER: bool = false;
const AUTH_SCHEMES: Option<&'static [AuthScheme]> = None;
const API_VERSION: Option<&'static str> = None;
const API_VERSION_HEADER: &'static str = "crucible-version";
const PAGINATION: Option<Pagination> = None;
const IDEMPOTENCY_TOKEN: Option<PaginationMember> = None;
const OUTPUT_FROM_JSON: Option<OutputFromJson<Self::Output>> = None;
const REQUIREMENTS: crate::permissions::Requirements =
crate::permissions::Requirements::Undeclared;
const CHECKS: Option<crate::permissions::Checks<Self::Input>> = None;
const ASSIGNS: Option<crate::permissions::Assignment> = None;
const ANONYMOUS: bool = false;
#[deprecated(since = "0.10.0", note = "use `ANONYMOUS`")]
const PUBLIC: bool = Self::ANONYMOUS;
const HAS_INPUT: bool = true;
const HAS_OUTPUT: bool = true;
type Input: DeserializeOwned + Serialize + Validate + Send + Sync + 'static;
type Output: Serialize + Send + Sync + 'static;
}
#[derive(Debug)]
#[non_exhaustive]
pub struct ServiceInfo {
pub mcp_tools: Option<&'static [crate::mcp::ToolDescriptor]>,
pub id: &'static str,
pub version: &'static str,
pub operations: &'static [&'static OperationInfo],
pub errors: &'static [&'static ErrorInfo],
pub classify: Classify,
pub reject: Option<RejectFn>,
pub internal: Option<InternalFn>,
pub unknown: Option<InternalFn>,
pub permissions: &'static [&'static crate::permissions::PermissionInfo],
pub not_found: Option<&'static str>,
pub version_header: &'static str,
pub unversioned_required: bool,
}
pub type Classify =
for<'a> fn(&'a (dyn std::error::Error + 'static)) -> Option<&'a dyn ModelledError>;
pub type RejectFn = fn(&Rejection) -> Box<dyn ModelledError>;
pub type InternalFn = fn() -> Box<dyn ModelledError>;
impl ServiceInfo {
pub const fn with_version_header(mut self, name: &'static str) -> Self {
self.version_header = name;
self
}
pub const fn with_unversioned_required(mut self) -> Self {
self.unversioned_required = true;
self
}
pub fn operation(&self, name: &str) -> Option<&'static OperationInfo> {
self.operations.iter().copied().find(|op| op.name == name)
}
pub const fn with_permissions(
mut self,
permissions: &'static [&'static crate::permissions::PermissionInfo],
) -> Self {
self.permissions = permissions;
self
}
pub const fn with_not_found(mut self, shape_id: &'static str) -> Self {
self.not_found = Some(shape_id);
self
}
pub fn permission(
&self,
resource: &str,
value: &str,
) -> Option<&'static crate::permissions::PermissionInfo> {
self.permissions
.iter()
.copied()
.find(|permission| permission.resource.name == resource && permission.accepts(value))
}
pub fn resource(&self, name: &str) -> Option<&'static crate::permissions::ResourceInfo> {
self.permissions
.iter()
.map(|permission| permission.resource)
.find(|resource| resource.name == name)
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct OperationInfo {
pub server_stream: bool,
pub internal: bool,
pub id: &'static str,
pub name: &'static str,
pub resource: Option<&'static str>,
pub method: &'static str,
pub path: &'static [Segment],
pub literal_query: &'static [(&'static str, Option<&'static str>)],
pub status: u16,
pub input: &'static [MemberInfo],
pub output: &'static [MemberInfo],
pub errors: &'static [&'static str],
pub readonly: bool,
pub idempotent: bool,
pub idempotency_token: Option<&'static str>,
pub traits: &'static [(&'static str, &'static str)],
pub sender: Option<&'static str>,
}
impl OperationInfo {
pub const fn with_server_stream(mut self) -> Self {
self.server_stream = true;
self
}
pub const fn with_sender(mut self, sender: &'static str) -> Self {
self.sender = Some(sender);
self
}
pub fn trait_value(&self, id: &str) -> Option<Value> {
trait_value(self.traits, id)
}
pub fn trait_as<T: DeserializeOwned>(&self, id: &str) -> serde_json::Result<Option<T>> {
self.traits
.iter()
.find(|(trait_id, _)| *trait_id == id)
.map(|(_, json)| serde_json::from_str(json))
.transpose()
}
pub fn has_trait(&self, id: &str) -> bool {
self.traits.iter().any(|(trait_id, _)| *trait_id == id)
}
pub fn declares(&self, error: &str) -> bool {
self.errors.contains(&error)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Segment {
GreedyLabel(&'static str),
Literal(&'static str),
Label(&'static str),
}
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct MemberInfo {
pub name: &'static str,
pub location: Location,
pub scalar: Scalar,
pub redaction: &'static Redaction,
pub traits: &'static [(&'static str, &'static str)],
}
pub enum Redaction {
Public,
Sensitive,
Structure(&'static [(&'static str, &'static Redaction)]),
List(&'static Redaction),
Map(&'static Redaction),
}
impl std::fmt::Debug for Redaction {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Public => "Public",
Self::Sensitive => "Sensitive",
Self::Structure(_) => "Structure(..)",
Self::List(_) => "List(..)",
Self::Map(_) => "Map(..)",
})
}
}
impl Redaction {
pub fn redact(&self, value: &mut Value) -> bool {
match self {
Self::Sensitive => return false,
Self::Public => {}
Self::Structure(members) => {
if let Value::Object(object) = value {
object.retain(|name, value| {
members
.iter()
.find(|(member, _)| name == member)
.is_some_and(|(_, policy)| policy.redact(value))
});
}
}
Self::List(policy) => {
if let Value::Array(items) = value {
for item in items {
if !policy.redact(item) {
*item = Value::Null;
}
}
}
}
Self::Map(policy) => {
if let Value::Object(object) = value {
object.retain(|_, value| policy.redact(value));
}
}
}
true
}
}
impl MemberInfo {
pub fn trait_value(&self, id: &str) -> Option<Value> {
trait_value(self.traits, id)
}
pub fn has_trait(&self, id: &str) -> bool {
self.traits.iter().any(|(trait_id, _)| *trait_id == id)
}
}
fn trait_value(traits: &[(&str, &str)], id: &str) -> Option<Value> {
traits
.iter()
.find(|(trait_id, _)| *trait_id == id)
.and_then(|(_, json)| serde_json::from_str(json).ok())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Location {
Label,
Query(&'static str),
Header(&'static str),
Body,
Payload(&'static str),
TextPayload(&'static str),
DocumentPayload(&'static str),
}
impl Location {
pub fn payload(members: &[MemberInfo]) -> Option<(&MemberInfo, &'static str)> {
members.iter().find_map(|member| match member.location {
Self::Payload(media_type)
| Self::TextPayload(media_type)
| Self::DocumentPayload(media_type) => Some((member, media_type)),
_ => None,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Scalar {
BigInteger,
BigDecimal,
String,
Integer,
Float,
Boolean,
DateTime,
EpochSeconds,
HttpDate,
Timestamp {
text: TimestampFormat,
json: TimestampFormat,
},
Base64,
List(&'static Scalar),
Json,
}
impl Scalar {
pub fn http_date(self) -> bool {
matches!(
self,
Self::HttpDate
| Self::Timestamp {
text: TimestampFormat::HttpDate,
..
}
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TimestampFormat {
DateTime,
EpochSeconds,
HttpDate,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Pagination {
pub input_token: PaginationMember,
pub page_size: Option<PaginationMember>,
pub input_token_map: bool,
pub input_token_max_length: Option<u64>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PaginationMember {
pub name: &'static str,
}
#[derive(Debug)]
#[non_exhaustive]
pub struct ErrorInfo {
pub name: &'static str,
pub status: u16,
pub fault: Fault,
pub retryable: bool,
pub throttling: bool,
pub members: &'static [MemberInfo],
#[doc(hidden)]
pub retryable_reasons: Option<RetryableReasons>,
}
#[doc(hidden)]
#[derive(Debug)]
pub struct RetryableReasons {
pub member: Option<&'static str>,
pub values: &'static [&'static str],
pub throttling: bool,
}
impl ErrorInfo {
#[doc(hidden)]
pub const fn with_retryable_reasons(
mut self,
member: Option<&'static str>,
values: &'static [&'static str],
throttling: bool,
) -> Self {
self.retryable_reasons = Some(RetryableReasons {
member,
values,
throttling,
});
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Fault {
Client,
Server,
}
#[derive(
Debug, Clone, Copy, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize,
)]
#[serde(deny_unknown_fields)]
pub struct Unit {}
impl Validate for Unit {
fn validate(&self, _: &mut crate::validate::Validator) {}
}
pub trait Input: Any + Send + Sync {
fn to_json(&self) -> Value;
fn as_any(&self) -> &dyn Any;
fn into_any(self: Box<Self>) -> Box<dyn Any + Send>;
}
impl<T: Serialize + Any + Send + Sync> Input for T {
fn to_json(&self) -> Value {
serde_json::to_value(self).unwrap_or(Value::Null)
}
fn as_any(&self) -> &dyn Any {
self
}
fn into_any(self: Box<Self>) -> Box<dyn Any + Send> {
self
}
}
pub type OutputFromJson<O> = fn(Value) -> serde_json::Result<O>;
pub trait Output: Any + Send + Sync {
fn to_json(&self) -> Value;
fn write_json_to(&self, out: &mut dyn std::io::Write) -> serde_json::Result<()> {
serde_json::to_writer(out, &self.to_json())
}
fn write_json(&self, out: &mut Vec<u8>) -> serde_json::Result<()> {
serde_json::to_writer(out, &self.to_json())
}
fn write_json_split(
&self,
members: &[MemberInfo],
out: &mut Vec<u8>,
) -> serde_json::Result<Vec<(&'static str, String)>> {
crate::split::write(&self.to_json(), members, out)
}
fn as_any(&self) -> &dyn Any;
}
impl<T: Serialize + Any + Send + Sync> Output for T {
fn write_json_to(&self, out: &mut dyn std::io::Write) -> serde_json::Result<()> {
serde_json::to_writer(out, self)
}
fn to_json(&self) -> Value {
serde_json::to_value(self).unwrap_or(Value::Null)
}
fn write_json(&self, out: &mut Vec<u8>) -> serde_json::Result<()> {
serde_json::to_writer(out, self)
}
fn write_json_split(
&self,
members: &[MemberInfo],
out: &mut Vec<u8>,
) -> serde_json::Result<Vec<(&'static str, String)>> {
crate::split::write(self, members, out)
}
fn as_any(&self) -> &dyn Any {
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AuthScheme {
Bearer,
}