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, CredentialGenerationError, CredentialLifetimeError,
52 ScopeValueError, SigningBuildError, SigningContextValueError, SigningInputError,
53 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::<CredentialGenerationError>();
105 assert_error::<CredentialLifetimeError>();
106 assert_error::<ScopeValueError>();
107 assert_error::<SigningValueError>();
108 assert_error::<SigningContextValueError>();
109 assert_error::<SigningInputError>();
110 assert_error::<SigningBuildError<core::convert::Infallible>>();
111 assert_error::<SigningOutputError<core::convert::Infallible>>();
112 assert_error::<RateLimitError>();
113 assert_error::<QuotaError>();
114 assert_error::<QuotaExtensionError>();
115 assert_error::<RetryAfterError>();
116 assert_error::<DelayDecisionError>();
117 assert_error::<FingerprintBuildError<core::convert::Infallible>>();
118 assert_error::<IdempotencyIntentError>();
119 assert_error::<MaxAttemptsError>();
120 assert_error::<RetryPolicyError>();
121 assert_error::<RetryPermitError>();
122 assert_error::<RetryExecutionError<()>>();
123 assert_error::<ContentTypeError>();
124 assert_error::<HeaderError>();
125 assert_error::<EndpointIdentityError>();
126 assert_error::<EndpointPairPolicyError>();
127 assert_error::<RequestTargetError>();
128 assert_error::<MethodError>();
129 assert_error::<ActionPollError>();
130 assert_error::<ActionObserveError<&'static str>>();
131 assert_error::<OperationMetadataError>();
132 assert_error::<ResponsePolicyError>();
133 assert_error::<ResponsePolicyValidationError>();
134 assert_error::<PreparedExecutionError<()>>();
135 assert_error::<AttemptBudgetError>();
136 assert_error::<CurrencyCodeError>();
137 assert_error::<ExecutionPermitError>();
138 assert_error::<PermitContextError>();
139 assert_error::<PermitExecutionError<()>>();
140 assert_error::<PermitIdempotencyKeyError>();
141 assert_error::<PermitValidityError>();
142 assert_error::<PlanCostError>();
143 assert_error::<PlanFingerprintBuildError<core::convert::Infallible>>();
144 assert_error::<ResponseWriterError>();
145 assert_error::<AsyncExecutionError<()>>();
146 assert_error::<RawResponsePolicyError>();
147 assert_error::<InformationalResponseError>();
148 assert_error::<StreamLimitsError>();
149 assert_error::<StreamPolicyError>();
150 assert_error::<StreamProgressError>();
151 assert_error::<StreamSourceIdError>();
152 assert_error::<StreamReplayError>();
153 assert_error::<StreamExecutionError<(), ()>>();
154 assert_error::<TransportFailure<()>>();
155 assert_error::<CheckedDecodeError<()>>();
156 assert_error::<ClientExecutionError<(), (), ()>>();
157 assert_error::<WorkspaceAcquireError>();
158 assert_error::<WorkspacePoolError>();
159 assert_error::<SchemaVersionError>();
160
161 assert_display(PaginationError::PageZero, "page number must be nonzero");
162 assert_display(RateLimitError::LimitZero, "rate limit must be nonzero");
163 assert_display(ContentTypeError::Empty, "content type is empty");
164 assert_display(HeaderError::DuplicateName, "HTTP header name is duplicated");
165 assert_display(
166 EndpointIdentityError::UnboundTransport,
167 "transport endpoint identity is unbound",
168 );
169 assert_display(
170 RequestTargetError::Path(RequestPathError::Empty),
171 "invalid request path: request path is empty",
172 );
173 assert_display(
174 MethodError::DeniedMethod,
175 "HTTP method is denied by the transport contract",
176 );
177 assert_display(
178 OperationMetadataError::NonIdempotentRetry,
179 "non-idempotent operation cannot be retry eligible",
180 );
181 assert_display(
182 ResponsePolicyError::UnexpectedContentType,
183 "response content type is not accepted",
184 );
185 assert_display(
186 ResponsePolicyError::InvalidContentType,
187 "response content type is invalid",
188 );
189 assert_display(
190 ResponsePolicyValidationError::MissingSuccessStatus,
191 "response policy has no success status",
192 );
193 assert_display(
194 PreparedExecutionError::<()>::Transport(()),
195 "prepared request transport failed",
196 );
197 assert_display(
198 PreparedExecutionError::<()>::AuthorizationRequired,
199 "state-changing request requires execution authority",
200 );
201 assert_display(
202 ResponseWriterError::AlreadyCommitted,
203 "response writer is already committed",
204 );
205 assert_display(
206 RawResponsePolicyError::UnsafeAdmittedHeader,
207 "an unsafe response header was admitted",
208 );
209 assert_display(
210 InformationalResponseError::SwitchingProtocols,
211 "switching protocols is forbidden",
212 );
213 assert_display(
214 TransportFailure::unknown("sentinel-secret"),
215 "transport failed with uncertain delivery",
216 );
217 assert_display(
218 ActionObserveError::Backoff("sentinel-secret"),
219 "action poll backoff policy failed",
220 );
221 }
222
223 fn assert_display(error: impl fmt::Display, expected: &str) {
224 let mut output = DisplayBuffer::new();
225 assert!(write!(&mut output, "{error}").is_ok());
226 assert_eq!(output.as_str(), expected);
227 }
228
229 struct DisplayBuffer {
230 bytes: [u8; 128],
231 len: usize,
232 }
233
234 impl DisplayBuffer {
235 const fn new() -> Self {
236 Self {
237 bytes: [0; 128],
238 len: 0,
239 }
240 }
241
242 fn as_str(&self) -> &str {
243 core::str::from_utf8(self.bytes.get(..self.len).unwrap_or_default()).unwrap_or_default()
244 }
245 }
246
247 impl Write for DisplayBuffer {
248 fn write_str(&mut self, value: &str) -> fmt::Result {
249 let end = self.len.checked_add(value.len()).ok_or(fmt::Error)?;
250 let target = self.bytes.get_mut(self.len..end).ok_or(fmt::Error)?;
251 target.copy_from_slice(value.as_bytes());
252 self.len = end;
253 Ok(())
254 }
255 }
256}