cloud-sdk 0.37.0

no_std-first provider-neutral cloud SDK foundations.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//! Checked provider-neutral response policy.

use core::fmt;

use crate::rate_limit::RateLimit;
use crate::transport::{
    MediaType, ResponseBuffer, ResponseContentType, ResponseWriterError, StatusCode,
    TransportResponse,
};

/// Expected response-body shape.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum ResponseBodyPolicy {
    /// A non-empty response body is required.
    Required,
    /// An empty or non-empty response body is accepted.
    Optional,
    /// Any response body is rejected.
    Forbidden,
}

/// Response content-type requirement and accepted media types.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ContentTypePolicy {
    /// A content type is required and must match one accepted media type.
    Required(&'static [MediaType<'static>]),
    /// A content type may be absent, but when present it must match.
    Optional(&'static [MediaType<'static>]),
    /// Any response content type is rejected.
    Forbidden,
}

/// Invalid response-policy construction.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ResponsePolicyValidationError {
    /// At least one success status is required.
    MissingSuccessStatus,
    /// Expected success statuses must be in the HTTP `2xx` range.
    NonSuccessStatus,
    /// Expected success statuses must not contain duplicates.
    DuplicateSuccessStatus,
    /// Required or optional content-type policy needs accepted media types.
    MissingAcceptedMediaType,
    /// Accepted media types must not contain duplicates.
    DuplicateAcceptedMediaType,
    /// Required response bodies need a nonzero maximum length.
    RequiredBodyHasZeroLimit,
    /// Forbidden response bodies require a zero maximum length.
    ForbiddenBodyHasNonzeroLimit,
    /// A forbidden body cannot require or optionally accept a content type.
    ForbiddenBodyAllowsContentType,
    /// A required body cannot forbid its content type.
    RequiredBodyForbidsContentType,
}

impl_static_error!(ResponsePolicyValidationError,
    Self::MissingSuccessStatus => "response policy has no success status",
    Self::NonSuccessStatus => "response policy contains a non-success status",
    Self::DuplicateSuccessStatus => "response policy contains duplicate statuses",
    Self::MissingAcceptedMediaType => "response policy has no accepted media type",
    Self::DuplicateAcceptedMediaType => "response policy contains duplicate media types",
    Self::RequiredBodyHasZeroLimit => "required response body has a zero limit",
    Self::ForbiddenBodyHasNonzeroLimit => "forbidden response body has a nonzero limit",
    Self::ForbiddenBodyAllowsContentType => "forbidden response body allows a content type",
    Self::RequiredBodyForbidsContentType => "required response body forbids its content type",
);

/// Response rejected before provider decoding.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ResponsePolicyError {
    /// The response status is not an expected success status.
    UnexpectedStatus,
    /// The initialized body exceeds the operation's admitted limit.
    BodyTooLarge,
    /// A required response body is empty.
    MissingBody,
    /// A response body was supplied when forbidden.
    ForbiddenBody,
    /// A required response content type is absent.
    MissingContentType,
    /// The supplied content type is not accepted.
    UnexpectedContentType,
    /// A content type was supplied when forbidden.
    ForbiddenContentType,
    /// The response writer was not successfully committed.
    UncommittedResponse,
}

impl_static_error!(ResponsePolicyError,
    Self::UnexpectedStatus => "response status is not expected",
    Self::BodyTooLarge => "response body exceeds the operation limit",
    Self::MissingBody => "required response body is missing",
    Self::ForbiddenBody => "response body is forbidden",
    Self::MissingContentType => "required response content type is missing",
    Self::UnexpectedContentType => "response content type is not accepted",
    Self::ForbiddenContentType => "response content type is forbidden",
    Self::UncommittedResponse => "response writer is not committed",
);

/// Complete checked-response policy.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ResponsePolicy {
    success_statuses: &'static [StatusCode],
    content_type: ContentTypePolicy,
    body: ResponseBodyPolicy,
    max_body_bytes: usize,
}

impl ResponsePolicy {
    /// Creates a complete policy without implicit status, media, or body defaults.
    pub fn new(
        success_statuses: &'static [StatusCode],
        content_type: ContentTypePolicy,
        body: ResponseBodyPolicy,
        max_body_bytes: usize,
    ) -> Result<Self, ResponsePolicyValidationError> {
        validate_statuses(success_statuses)?;
        validate_media_types(content_type)?;
        match (body, content_type, max_body_bytes) {
            (ResponseBodyPolicy::Required, _, 0) => {
                return Err(ResponsePolicyValidationError::RequiredBodyHasZeroLimit);
            }
            (ResponseBodyPolicy::Forbidden, _, limit) if limit != 0 => {
                return Err(ResponsePolicyValidationError::ForbiddenBodyHasNonzeroLimit);
            }
            (
                ResponseBodyPolicy::Forbidden,
                ContentTypePolicy::Required(_) | ContentTypePolicy::Optional(_),
                _,
            ) => {
                return Err(ResponsePolicyValidationError::ForbiddenBodyAllowsContentType);
            }
            (ResponseBodyPolicy::Required, ContentTypePolicy::Forbidden, _) => {
                return Err(ResponsePolicyValidationError::RequiredBodyForbidsContentType);
            }
            _ => {}
        }
        Ok(Self {
            success_statuses,
            content_type,
            body,
            max_body_bytes,
        })
    }

    /// Returns expected success statuses.
    #[must_use]
    pub const fn success_statuses(self) -> &'static [StatusCode] {
        self.success_statuses
    }

    /// Returns response content-type policy.
    #[must_use]
    pub const fn content_type_policy(self) -> ContentTypePolicy {
        self.content_type
    }

    /// Returns response-body policy.
    #[must_use]
    pub const fn body_policy(self) -> ResponseBodyPolicy {
        self.body
    }

    /// Returns maximum admitted initialized response bytes.
    #[must_use]
    pub const fn max_body_bytes(self) -> usize {
        self.max_body_bytes
    }

    /// Checks status, initialized length, body shape, and content type.
    pub fn validate<'buffer, 'sanitizer, S>(
        self,
        writer: ResponseBuffer<'buffer, 'sanitizer, S>,
    ) -> Result<CheckedResponseGuard<'buffer, 'sanitizer, S>, ResponsePolicyError>
    where
        S: crate::transport::ResponseStorageSanitizer + ?Sized,
    {
        let snapshot = {
            let response = writer.response().map_err(map_writer_error)?;
            self.validate_view(response)?
        };
        Ok(CheckedResponseGuard { writer, snapshot })
    }

    fn validate_view(
        self,
        response: TransportResponse<'_>,
    ) -> Result<CheckedResponseSnapshot, ResponsePolicyError> {
        if !self.success_statuses.contains(&response.status()) {
            return Err(ResponsePolicyError::UnexpectedStatus);
        }
        match self.body {
            ResponseBodyPolicy::Forbidden if !response.body().is_empty() => {
                return Err(ResponsePolicyError::ForbiddenBody);
            }
            _ => {}
        }
        if response.body().len() > self.max_body_bytes {
            return Err(ResponsePolicyError::BodyTooLarge);
        }
        if matches!(self.body, ResponseBodyPolicy::Required) && response.body().is_empty() {
            return Err(ResponsePolicyError::MissingBody);
        }
        validate_content_type(self.content_type, response.content_type())?;
        Ok(CheckedResponseSnapshot {
            status: response.status(),
            body_len: response.body().len(),
            content_type: response.content_type(),
            rate_limit: response.rate_limit(),
        })
    }
}

/// Response that passed one operation's complete provider-neutral policy.
#[derive(Clone, Copy)]
pub struct CheckedResponse<'body> {
    status: StatusCode,
    body: &'body [u8],
    content_type: Option<ResponseContentType>,
    rate_limit: Option<RateLimit>,
}

impl CheckedResponse<'_> {
    /// Returns the checked status code.
    #[must_use]
    pub const fn status(&self) -> StatusCode {
        self.status
    }

    /// Returns the checked initialized response body.
    #[must_use]
    pub const fn body(&self) -> &[u8] {
        self.body
    }

    /// Returns the checked response content type when supplied.
    #[must_use]
    pub const fn content_type(&self) -> Option<ResponseContentType> {
        self.content_type
    }

    /// Returns validated rate-limit metadata when supplied.
    #[must_use]
    pub const fn rate_limit(&self) -> Option<RateLimit> {
        self.rate_limit
    }
}

#[derive(Clone, Copy)]
struct CheckedResponseSnapshot {
    status: StatusCode,
    body_len: usize,
    content_type: Option<ResponseContentType>,
    rate_limit: Option<RateLimit>,
}

/// Policy-checked response that owns cleanup of its caller storage.
///
/// Borrowed access is closure-scoped. [`Self::decode_owned`] clears the
/// complete response storage before returning the owned decoded result.
pub struct CheckedResponseGuard<
    'buffer,
    'sanitizer,
    S: crate::transport::ResponseStorageSanitizer + ?Sized,
> {
    writer: ResponseBuffer<'buffer, 'sanitizer, S>,
    snapshot: CheckedResponseSnapshot,
}

impl<S> CheckedResponseGuard<'_, '_, S>
where
    S: crate::transport::ResponseStorageSanitizer + ?Sized,
{
    /// Returns the checked status code.
    #[must_use]
    pub const fn status(&self) -> StatusCode {
        self.snapshot.status
    }

    /// Returns the checked response content type when supplied.
    #[must_use]
    pub const fn content_type(&self) -> Option<ResponseContentType> {
        self.snapshot.content_type
    }

    /// Returns validated rate-limit metadata when supplied.
    #[must_use]
    pub const fn rate_limit(&self) -> Option<RateLimit> {
        self.snapshot.rate_limit
    }

    /// Runs a closure with a checked response borrow that cannot escape.
    ///
    /// ```compile_fail
    /// use cloud_sdk::operation::CheckedResponseGuard;
    /// use cloud_sdk::transport::ResponseStorageSanitizer;
    ///
    /// fn escape<'guard, S>(
    ///     guard: &'guard CheckedResponseGuard<'_, '_, S>,
    /// ) -> &'guard [u8]
    /// where
    ///     S: ResponseStorageSanitizer + ?Sized,
    /// {
    ///     guard.with_borrowed(|response| response.body())
    /// }
    /// ```
    pub fn with_borrowed<R>(
        &self,
        inspect: impl for<'response> FnOnce(CheckedResponse<'response>) -> R,
    ) -> R {
        inspect(self.checked_response())
    }

    /// Decodes an owned value, clears all response storage, and then returns.
    pub fn decode_owned<R, E>(
        self,
        decode: impl for<'response> FnOnce(CheckedResponse<'response>) -> Result<R, E>,
    ) -> Result<R, E> {
        let result = decode(self.checked_response());
        drop(self);
        result
    }

    fn checked_response(&self) -> CheckedResponse<'_> {
        CheckedResponse {
            status: self.snapshot.status,
            body: self.writer.initialized_body(self.snapshot.body_len),
            content_type: self.snapshot.content_type,
            rate_limit: self.snapshot.rate_limit,
        }
    }
}

impl<S> fmt::Debug for CheckedResponseGuard<'_, '_, S>
where
    S: crate::transport::ResponseStorageSanitizer + ?Sized,
{
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CheckedResponseGuard")
            .field("status", &self.status())
            .field("body_len", &self.snapshot.body_len)
            .field("body", &"[redacted]")
            .field("content_type", &self.content_type())
            .field("rate_limit", &self.rate_limit())
            .finish()
    }
}

impl fmt::Debug for CheckedResponse<'_> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CheckedResponse")
            .field("status", &self.status())
            .field("body_len", &self.body().len())
            .field("body", &"[redacted]")
            .field("content_type", &self.content_type())
            .field("rate_limit", &self.rate_limit())
            .finish()
    }
}

fn validate_statuses(statuses: &[StatusCode]) -> Result<(), ResponsePolicyValidationError> {
    if statuses.is_empty() {
        return Err(ResponsePolicyValidationError::MissingSuccessStatus);
    }
    for (index, status) in statuses.iter().enumerate() {
        if !status.is_success() {
            return Err(ResponsePolicyValidationError::NonSuccessStatus);
        }
        if statuses
            .get(..index)
            .is_some_and(|seen| seen.contains(status))
        {
            return Err(ResponsePolicyValidationError::DuplicateSuccessStatus);
        }
    }
    Ok(())
}

fn validate_media_types(policy: ContentTypePolicy) -> Result<(), ResponsePolicyValidationError> {
    let media_types = match policy {
        ContentTypePolicy::Required(values) | ContentTypePolicy::Optional(values) => values,
        ContentTypePolicy::Forbidden => return Ok(()),
    };
    if media_types.is_empty() {
        return Err(ResponsePolicyValidationError::MissingAcceptedMediaType);
    }
    for (index, media_type) in media_types.iter().enumerate() {
        if media_types.get(..index).is_some_and(|seen| {
            seen.iter()
                .any(|candidate| candidate.as_str().eq_ignore_ascii_case(media_type.as_str()))
        }) {
            return Err(ResponsePolicyValidationError::DuplicateAcceptedMediaType);
        }
    }
    Ok(())
}

fn validate_content_type(
    policy: ContentTypePolicy,
    actual: Option<ResponseContentType>,
) -> Result<(), ResponsePolicyError> {
    match (policy, actual) {
        (ContentTypePolicy::Required(_), None) => Err(ResponsePolicyError::MissingContentType),
        (ContentTypePolicy::Forbidden, Some(_)) => Err(ResponsePolicyError::ForbiddenContentType),
        (ContentTypePolicy::Forbidden | ContentTypePolicy::Optional(_), None) => Ok(()),
        (
            ContentTypePolicy::Required(accepted) | ContentTypePolicy::Optional(accepted),
            Some(actual),
        ) => {
            if accepted
                .iter()
                .any(|media_type| actual.matches(*media_type))
            {
                Ok(())
            } else {
                Err(ResponsePolicyError::UnexpectedContentType)
            }
        }
    }
}

const fn map_writer_error(error: ResponseWriterError) -> ResponsePolicyError {
    match error {
        ResponseWriterError::NotCommitted
        | ResponseWriterError::AlreadyCommitted
        | ResponseWriterError::InitializedLengthTooLarge => {
            ResponsePolicyError::UncommittedResponse
        }
    }
}