Skip to main content

cloud_sdk/
lib.rs

1#![no_std]
2#![doc = include_str!("../README.md")]
3
4#[cfg(feature = "std")]
5extern crate std;
6
7macro_rules! impl_static_error {
8    ($error:ty, $($pattern:pat => $message:literal),+ $(,)?) => {
9        impl core::fmt::Display for $error {
10            fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
11                formatter.write_str(match self {
12                    $($pattern => $message,)+
13                })
14            }
15        }
16
17        impl core::error::Error for $error {}
18    };
19}
20
21pub mod action_polling;
22pub mod buffer;
23mod identity;
24mod method;
25pub mod operation;
26pub mod pagination;
27pub mod rate_limit;
28pub mod transport;
29
30pub use identity::{
31    IdentityError, MAX_PROVIDER_ID_BYTES, MAX_SERVICE_ID_BYTES, ProviderId, ProviderMarker,
32    ServiceId, ServiceMarker,
33};
34pub use method::{MAX_METHOD_BYTES, Method, MethodError};
35
36#[cfg(test)]
37mod tests {
38    use super::{Method, MethodError, ProviderId, ServiceId};
39    use crate::action_polling::ActionPollError;
40    use crate::operation::{
41        OperationMetadataError, PreparedExecutionError, ResponsePolicyError,
42        ResponsePolicyValidationError,
43    };
44    use crate::pagination::PaginationError;
45    use crate::rate_limit::RateLimitError;
46    use crate::transport::{ContentTypeError, EndpointIdentityError, RequestTargetError};
47    use core::fmt::{self, Write};
48
49    #[test]
50    fn exposes_provider_neutral_domains() {
51        assert_eq!(
52            ProviderId::new("example").map(ProviderId::as_str),
53            Ok("example")
54        );
55        assert_eq!(
56            ServiceId::new("compute").map(ServiceId::as_str),
57            Ok("compute")
58        );
59        assert_eq!(Method::Get, Method::Get);
60        assert_eq!(Method::Post.as_str(), "POST");
61    }
62
63    #[test]
64    fn public_errors_implement_payload_free_core_error() {
65        fn assert_error<E: core::error::Error>() {}
66
67        assert_error::<PaginationError>();
68        assert_error::<RateLimitError>();
69        assert_error::<ContentTypeError>();
70        assert_error::<EndpointIdentityError>();
71        assert_error::<RequestTargetError>();
72        assert_error::<MethodError>();
73        assert_error::<ActionPollError<&'static str>>();
74        assert_error::<OperationMetadataError>();
75        assert_error::<ResponsePolicyError>();
76        assert_error::<ResponsePolicyValidationError>();
77        assert_error::<PreparedExecutionError<()>>();
78
79        assert_display(PaginationError::PageZero, "page number must be nonzero");
80        assert_display(RateLimitError::LimitZero, "rate limit must be nonzero");
81        assert_display(ContentTypeError::Empty, "content type is empty");
82        assert_display(
83            EndpointIdentityError::UnboundTransport,
84            "transport endpoint identity is unbound",
85        );
86        assert_display(RequestTargetError::Empty, "request target is empty");
87        assert_display(
88            MethodError::DeniedMethod,
89            "HTTP method is denied by the transport contract",
90        );
91        assert_display(
92            OperationMetadataError::NonIdempotentRetry,
93            "non-idempotent operation cannot be retry eligible",
94        );
95        assert_display(
96            ResponsePolicyError::UnexpectedContentType,
97            "response content type is not accepted",
98        );
99        assert_display(
100            ResponsePolicyValidationError::MissingSuccessStatus,
101            "response policy has no success status",
102        );
103        assert_display(
104            PreparedExecutionError::<()>::Transport(()),
105            "prepared request transport failed",
106        );
107        assert_display(
108            ActionPollError::Policy("sentinel-secret"),
109            "action poll policy failed",
110        );
111    }
112
113    fn assert_display(error: impl fmt::Display, expected: &str) {
114        let mut output = DisplayBuffer::new();
115        assert!(write!(&mut output, "{error}").is_ok());
116        assert_eq!(output.as_str(), expected);
117    }
118
119    struct DisplayBuffer {
120        bytes: [u8; 128],
121        len: usize,
122    }
123
124    impl DisplayBuffer {
125        const fn new() -> Self {
126            Self {
127                bytes: [0; 128],
128                len: 0,
129            }
130        }
131
132        fn as_str(&self) -> &str {
133            core::str::from_utf8(self.bytes.get(..self.len).unwrap_or_default()).unwrap_or_default()
134        }
135    }
136
137    impl Write for DisplayBuffer {
138        fn write_str(&mut self, value: &str) -> fmt::Result {
139            let end = self.len.checked_add(value.len()).ok_or(fmt::Error)?;
140            let target = self.bytes.get_mut(self.len..end).ok_or(fmt::Error)?;
141            target.copy_from_slice(value.as_bytes());
142            self.len = end;
143            Ok(())
144        }
145    }
146}