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
7#[cfg(feature = "alloc")]
8extern crate alloc;
9
10macro_rules! impl_static_error {
11    ($error:ty, $($pattern:pat => $message:literal),+ $(,)?) => {
12        impl core::fmt::Display for $error {
13            fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
14                formatter.write_str(match self {
15                    $($pattern => $message,)+
16                })
17            }
18        }
19
20        impl core::error::Error for $error {}
21    };
22}
23
24pub mod action_polling;
25pub mod async_resource;
26pub mod authentication;
27pub mod buffer;
28pub mod client;
29pub mod diagnostics;
30mod identity;
31mod method;
32pub mod operation;
33pub mod pagination;
34pub mod rate_limit;
35pub mod retry;
36pub mod schema;
37pub mod transport;
38
39pub use identity::{
40    IdentityError, MAX_PROVIDER_ID_BYTES, MAX_SERVICE_ID_BYTES, ProviderId, ProviderMarker,
41    ServiceId, ServiceMarker,
42};
43pub use method::{MAX_METHOD_BYTES, Method, MethodError};
44
45#[cfg(test)]
46mod tests {
47    use super::{Method, MethodError, ProviderId, ServiceId};
48    use crate::action_polling::{ActionObserveError, ActionPollError};
49    use crate::async_resource::AsyncResourceValidationError;
50    use crate::authentication::{
51        AuthenticationScopeError, CredentialAttemptError, CredentialGenerationError,
52        CredentialLifetimeError, ScopeValueError, SigningBuildError, SigningContextValueError,
53        SigningInputError, SigningOutputError, SigningValueError,
54    };
55    use crate::client::{
56        CheckedDecodeError, ClientExecutionError, WorkspaceAcquireError, WorkspacePoolError,
57    };
58    use crate::operation::{
59        AttemptBudgetError, CurrencyCodeError, ExecutionPermitError, OperationMetadataError,
60        PermitContextError, PermitExecutionError, PermitIdempotencyKeyError, PermitValidityError,
61        PlanCostError, PlanFingerprintBuildError, PreparedExecutionError, ResponsePolicyError,
62        ResponsePolicyValidationError,
63    };
64    use crate::pagination::{HeaderCursorExecutionError, PaginationError};
65    use crate::rate_limit::{
66        DelayDecisionError, QuotaError, QuotaExtensionError, RateLimitError, RetryAfterError,
67    };
68    use crate::retry::{
69        FingerprintBuildError, IdempotencyIntentError, MaxAttemptsError, RetryExecutionError,
70        RetryPermitError, RetryPolicyError,
71    };
72    use crate::schema::SchemaVersionError;
73    use crate::transport::{
74        AsyncExecutionError, ContentTypeError, EndpointIdentityError, EndpointPairPolicyError,
75        HeaderError, InformationalResponseError, RawResponsePolicyError, RequestPathError,
76        RequestTargetError, ResponseWriterError, StreamExecutionError, StreamLimitsError,
77        StreamPolicyError, StreamProgressError, StreamReplayError, StreamSourceIdError,
78        TransportFailure,
79    };
80    use core::fmt::{self, Write};
81
82    #[test]
83    fn exposes_provider_neutral_domains() {
84        assert_eq!(
85            ProviderId::new("example").map(ProviderId::as_str),
86            Ok("example")
87        );
88        assert_eq!(
89            ServiceId::new("compute").map(ServiceId::as_str),
90            Ok("compute")
91        );
92        assert_eq!(Method::Get, Method::Get);
93        assert_eq!(Method::Post.as_str(), "POST");
94    }
95
96    #[test]
97    fn public_errors_implement_payload_free_core_error() {
98        fn assert_error<E: core::error::Error>() {}
99
100        assert_error::<PaginationError>();
101        assert_error::<AsyncResourceValidationError>();
102        assert_error::<HeaderCursorExecutionError<core::convert::Infallible>>();
103        assert_error::<AuthenticationScopeError>();
104        assert_error::<CredentialAttemptError>();
105        assert_error::<CredentialGenerationError>();
106        assert_error::<CredentialLifetimeError>();
107        assert_error::<ScopeValueError>();
108        assert_error::<SigningValueError>();
109        assert_error::<SigningContextValueError>();
110        assert_error::<SigningInputError>();
111        assert_error::<SigningBuildError<core::convert::Infallible>>();
112        assert_error::<SigningOutputError<core::convert::Infallible>>();
113        assert_error::<RateLimitError>();
114        assert_error::<QuotaError>();
115        assert_error::<QuotaExtensionError>();
116        assert_error::<RetryAfterError>();
117        assert_error::<DelayDecisionError>();
118        assert_error::<FingerprintBuildError<core::convert::Infallible>>();
119        assert_error::<IdempotencyIntentError>();
120        assert_error::<MaxAttemptsError>();
121        assert_error::<RetryPolicyError>();
122        assert_error::<RetryPermitError>();
123        assert_error::<RetryExecutionError<()>>();
124        assert_error::<ContentTypeError>();
125        assert_error::<HeaderError>();
126        assert_error::<EndpointIdentityError>();
127        assert_error::<EndpointPairPolicyError>();
128        assert_error::<RequestTargetError>();
129        assert_error::<MethodError>();
130        assert_error::<ActionPollError>();
131        assert_error::<ActionObserveError<&'static str>>();
132        assert_error::<OperationMetadataError>();
133        assert_error::<ResponsePolicyError>();
134        assert_error::<ResponsePolicyValidationError>();
135        assert_error::<PreparedExecutionError<()>>();
136        assert_error::<AttemptBudgetError>();
137        assert_error::<CurrencyCodeError>();
138        assert_error::<ExecutionPermitError>();
139        assert_error::<PermitContextError>();
140        assert_error::<PermitExecutionError<()>>();
141        assert_error::<PermitIdempotencyKeyError>();
142        assert_error::<PermitValidityError>();
143        assert_error::<PlanCostError>();
144        assert_error::<PlanFingerprintBuildError<core::convert::Infallible>>();
145        assert_error::<ResponseWriterError>();
146        assert_error::<AsyncExecutionError<()>>();
147        assert_error::<RawResponsePolicyError>();
148        assert_error::<InformationalResponseError>();
149        assert_error::<StreamLimitsError>();
150        assert_error::<StreamPolicyError>();
151        assert_error::<StreamProgressError>();
152        assert_error::<StreamSourceIdError>();
153        assert_error::<StreamReplayError>();
154        assert_error::<StreamExecutionError<(), ()>>();
155        assert_error::<TransportFailure<()>>();
156        assert_error::<CheckedDecodeError<()>>();
157        assert_error::<ClientExecutionError<(), (), ()>>();
158        assert_error::<WorkspaceAcquireError>();
159        assert_error::<WorkspacePoolError>();
160        assert_error::<SchemaVersionError>();
161
162        assert_display(PaginationError::PageZero, "page number must be nonzero");
163        assert_display(RateLimitError::LimitZero, "rate limit must be nonzero");
164        assert_display(ContentTypeError::Empty, "content type is empty");
165        assert_display(HeaderError::DuplicateName, "HTTP header name is duplicated");
166        assert_display(
167            EndpointIdentityError::UnboundTransport,
168            "transport endpoint identity is unbound",
169        );
170        assert_display(
171            RequestTargetError::Path(RequestPathError::Empty),
172            "invalid request path: request path is empty",
173        );
174        assert_display(
175            MethodError::DeniedMethod,
176            "HTTP method is denied by the transport contract",
177        );
178        assert_display(
179            OperationMetadataError::NonIdempotentRetry,
180            "non-idempotent operation cannot be retry eligible",
181        );
182        assert_display(
183            ResponsePolicyError::UnexpectedContentType,
184            "response content type is not accepted",
185        );
186        assert_display(
187            ResponsePolicyError::InvalidContentType,
188            "response content type is invalid",
189        );
190        assert_display(
191            ResponsePolicyValidationError::MissingSuccessStatus,
192            "response policy has no success status",
193        );
194        assert_display(
195            PreparedExecutionError::<()>::Transport(()),
196            "prepared request transport failed",
197        );
198        assert_display(
199            PreparedExecutionError::<()>::AuthorizationRequired,
200            "state-changing request requires execution authority",
201        );
202        assert_display(
203            ResponseWriterError::AlreadyCommitted,
204            "response writer is already committed",
205        );
206        assert_display(
207            RawResponsePolicyError::UnsafeAdmittedHeader,
208            "an unsafe response header was admitted",
209        );
210        assert_display(
211            InformationalResponseError::SwitchingProtocols,
212            "switching protocols is forbidden",
213        );
214        assert_display(
215            TransportFailure::unknown("sentinel-secret"),
216            "transport failed with uncertain delivery",
217        );
218        assert_display(
219            ActionObserveError::Backoff("sentinel-secret"),
220            "action poll backoff policy failed",
221        );
222    }
223
224    fn assert_display(error: impl fmt::Display, expected: &str) {
225        let mut output = DisplayBuffer::new();
226        assert!(write!(&mut output, "{error}").is_ok());
227        assert_eq!(output.as_str(), expected);
228    }
229
230    struct DisplayBuffer {
231        bytes: [u8; 128],
232        len: usize,
233    }
234
235    impl DisplayBuffer {
236        const fn new() -> Self {
237            Self {
238                bytes: [0; 128],
239                len: 0,
240            }
241        }
242
243        fn as_str(&self) -> &str {
244            core::str::from_utf8(self.bytes.get(..self.len).unwrap_or_default()).unwrap_or_default()
245        }
246    }
247
248    impl Write for DisplayBuffer {
249        fn write_str(&mut self, value: &str) -> fmt::Result {
250            let end = self.len.checked_add(value.len()).ok_or(fmt::Error)?;
251            let target = self.bytes.get_mut(self.len..end).ok_or(fmt::Error)?;
252            target.copy_from_slice(value.as_bytes());
253            self.len = end;
254            Ok(())
255        }
256    }
257}