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