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::{
47        ContentTypeError, EndpointIdentityError, HeaderError, RequestPathError, RequestTargetError,
48    };
49    use core::fmt::{self, Write};
50
51    #[test]
52    fn exposes_provider_neutral_domains() {
53        assert_eq!(
54            ProviderId::new("example").map(ProviderId::as_str),
55            Ok("example")
56        );
57        assert_eq!(
58            ServiceId::new("compute").map(ServiceId::as_str),
59            Ok("compute")
60        );
61        assert_eq!(Method::Get, Method::Get);
62        assert_eq!(Method::Post.as_str(), "POST");
63    }
64
65    #[test]
66    fn public_errors_implement_payload_free_core_error() {
67        fn assert_error<E: core::error::Error>() {}
68
69        assert_error::<PaginationError>();
70        assert_error::<RateLimitError>();
71        assert_error::<ContentTypeError>();
72        assert_error::<HeaderError>();
73        assert_error::<EndpointIdentityError>();
74        assert_error::<RequestTargetError>();
75        assert_error::<MethodError>();
76        assert_error::<ActionPollError<&'static str>>();
77        assert_error::<OperationMetadataError>();
78        assert_error::<ResponsePolicyError>();
79        assert_error::<ResponsePolicyValidationError>();
80        assert_error::<PreparedExecutionError<()>>();
81
82        assert_display(PaginationError::PageZero, "page number must be nonzero");
83        assert_display(RateLimitError::LimitZero, "rate limit must be nonzero");
84        assert_display(ContentTypeError::Empty, "content type is empty");
85        assert_display(HeaderError::DuplicateName, "HTTP header name is duplicated");
86        assert_display(
87            EndpointIdentityError::UnboundTransport,
88            "transport endpoint identity is unbound",
89        );
90        assert_display(
91            RequestTargetError::Path(RequestPathError::Empty),
92            "invalid request path: request path is empty",
93        );
94        assert_display(
95            MethodError::DeniedMethod,
96            "HTTP method is denied by the transport contract",
97        );
98        assert_display(
99            OperationMetadataError::NonIdempotentRetry,
100            "non-idempotent operation cannot be retry eligible",
101        );
102        assert_display(
103            ResponsePolicyError::UnexpectedContentType,
104            "response content type is not accepted",
105        );
106        assert_display(
107            ResponsePolicyValidationError::MissingSuccessStatus,
108            "response policy has no success status",
109        );
110        assert_display(
111            PreparedExecutionError::<()>::Transport(()),
112            "prepared request transport failed",
113        );
114        assert_display(
115            ActionPollError::Policy("sentinel-secret"),
116            "action poll policy failed",
117        );
118    }
119
120    fn assert_display(error: impl fmt::Display, expected: &str) {
121        let mut output = DisplayBuffer::new();
122        assert!(write!(&mut output, "{error}").is_ok());
123        assert_eq!(output.as_str(), expected);
124    }
125
126    struct DisplayBuffer {
127        bytes: [u8; 128],
128        len: usize,
129    }
130
131    impl DisplayBuffer {
132        const fn new() -> Self {
133            Self {
134                bytes: [0; 128],
135                len: 0,
136            }
137        }
138
139        fn as_str(&self) -> &str {
140            core::str::from_utf8(self.bytes.get(..self.len).unwrap_or_default()).unwrap_or_default()
141        }
142    }
143
144    impl Write for DisplayBuffer {
145        fn write_str(&mut self, value: &str) -> fmt::Result {
146            let end = self.len.checked_add(value.len()).ok_or(fmt::Error)?;
147            let target = self.bytes.get_mut(self.len..end).ok_or(fmt::Error)?;
148            target.copy_from_slice(value.as_bytes());
149            self.len = end;
150            Ok(())
151        }
152    }
153}