cloud-sdk 0.60.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
433
434
435
use core::fmt;

use cloud_sdk_sanitization::sanitize_bytes;

use crate::authentication::BlockingAuthenticatedTransport;
use crate::operation::{CheckedResponseGuard, PreparedExecutionError, PreparedRequest};
use crate::transport::{
    BoundTransport, EndpointIdentity, MAX_REQUEST_HEADERS, RequestHeader, RequestHeaders,
};

use super::{DecodedHeaderCursor, HeaderCursorPolicy};
use crate::pagination::{
    CursorDigest, CursorHistory, PaginationCursor, PaginationError, PaginationLimits,
};

mod asynchronous;
mod local_async;

/// Cursor validation or prepared-request execution failure.
pub enum HeaderCursorExecutionError<E> {
    /// Cursor policy, provenance, storage, or header validation failed.
    Pagination(PaginationError),
    /// The exact retained prepared request failed to execute.
    Prepared(PreparedExecutionError<E>),
}

impl<E> fmt::Debug for HeaderCursorExecutionError<E> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Pagination(error) => formatter.debug_tuple("Pagination").field(error).finish(),
            Self::Prepared(_) => formatter.write_str("Prepared([redacted])"),
        }
    }
}

impl<E> fmt::Display for HeaderCursorExecutionError<E> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::Pagination(_) => "header cursor validation failed",
            Self::Prepared(_) => "header cursor prepared request failed",
        })
    }
}

impl<E> core::error::Error for HeaderCursorExecutionError<E> {}

/// Exact prepared-request context retained for one header-cursor traversal.
#[derive(Clone, Copy)]
pub struct HeaderCursorSession<'request, 'policy> {
    pub(super) policy: HeaderCursorPolicy<'policy>,
    pub(super) prepared: PreparedRequest<'request>,
}

impl<'policy> HeaderCursorPolicy<'policy> {
    /// Binds pagination to one complete prepared request before any dispatch.
    pub fn bind<'request>(
        self,
        prepared: PreparedRequest<'request>,
    ) -> Result<HeaderCursorSession<'request, 'policy>, PaginationError> {
        if prepared.operation_id() != Some(self.operation_id()) {
            return Err(PaginationError::OperationMismatch);
        }
        if !prepared
            .raw_response_policy()
            .admits_header(self.next_response().as_str())
        {
            return Err(PaginationError::ResponseHeaderNotAdmitted);
        }
        Ok(HeaderCursorSession {
            policy: self,
            prepared,
        })
    }
}

impl HeaderCursorSession<'_, '_> {
    /// Returns the operation retained by this exact request context.
    #[must_use]
    pub const fn operation_id(&self) -> crate::operation::OperationId {
        self.policy.operation_id()
    }

    /// Executes the initial blocking request and decodes only its own response.
    #[allow(clippy::too_many_arguments)]
    pub fn execute_blocking<'response, 'cursor, 'endpoint, T>(
        &self,
        transport: &'endpoint T,
        response_storage: &'response mut [u8],
        response_header_storage: &'response mut [u8],
        decimal_scratch: &mut [u8],
        transfer_scratch: &mut [u8],
        cursor_destination: &'cursor mut [u8],
        limits: PaginationLimits,
    ) -> Result<
        HeaderCursorPage<'response, 'cursor, 'endpoint, '_, '_, '_>,
        HeaderCursorExecutionError<T::Error>,
    >
    where
        T: BlockingAuthenticatedTransport + BoundTransport,
    {
        clear_execution_buffers(
            response_storage,
            response_header_storage,
            decimal_scratch,
            transfer_scratch,
            cursor_destination,
        );
        let endpoint = transport.endpoint_identity().map_err(|error| {
            HeaderCursorExecutionError::Prepared(PreparedExecutionError::EndpointIdentity(error))
        })?;
        execute_blocking(
            self,
            None,
            endpoint,
            transport,
            response_storage,
            response_header_storage,
            decimal_scratch,
            transfer_scratch,
            cursor_destination,
            limits,
        )
    }
}

impl fmt::Debug for HeaderCursorSession<'_, '_> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("HeaderCursorSession")
            .field("policy", &self.policy)
            .field("prepared", &"[bound]")
            .finish()
    }
}

/// Checked response and provenance-bound next-page state.
pub struct HeaderCursorPage<'response, 'cursor, 'endpoint, 'session, 'request, 'policy> {
    response: CheckedResponseGuard<'response>,
    next: HeaderCursorNext<'cursor, 'endpoint, 'session, 'request, 'policy>,
}

impl<'response, 'cursor, 'endpoint, 'session, 'request, 'policy>
    HeaderCursorPage<'response, 'cursor, 'endpoint, 'session, 'request, 'policy>
{
    /// Separates the checked response from its next-page state.
    #[must_use]
    pub fn into_parts(
        self,
    ) -> (
        CheckedResponseGuard<'response>,
        HeaderCursorNext<'cursor, 'endpoint, 'session, 'request, 'policy>,
    ) {
        (self.response, self.next)
    }
}

impl fmt::Debug for HeaderCursorPage<'_, '_, '_, '_, '_, '_> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("HeaderCursorPage")
            .field("response", &self.response)
            .field("next", &self.next)
            .finish()
    }
}

/// Provenance-bound continuation state from one executed prepared request.
pub enum HeaderCursorNext<'cursor, 'endpoint, 'session, 'request, 'policy> {
    /// The next-cursor header was absent, so traversal is complete.
    Complete,
    /// The exact request context and bounded cursor are retained together.
    Continue(HeaderCursorContinuation<'cursor, 'endpoint, 'session, 'request, 'policy>),
}

impl HeaderCursorNext<'_, '_, '_, '_, '_> {
    /// Reports whether the provider declared a terminal page.
    #[must_use]
    pub const fn is_complete(&self) -> bool {
        matches!(self, Self::Complete)
    }
}

impl fmt::Debug for HeaderCursorNext<'_, '_, '_, '_, '_> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Complete => formatter.write_str("HeaderCursorNext::Complete"),
            Self::Continue(_) => formatter.write_str("HeaderCursorNext::Continue([redacted])"),
        }
    }
}

/// Cleanup-owning cursor inseparable from its original prepared request.
///
/// Continuations expose execution only; another request cannot be attached.
///
/// ```compile_fail
/// use cloud_sdk::operation::PreparedRequest;
/// use cloud_sdk::pagination::HeaderCursorContinuation;
///
/// fn rebind(
///     continuation: HeaderCursorContinuation<'_, '_, '_, '_, '_>,
///     replacement: PreparedRequest<'_>,
/// ) {
///     continuation.bind(replacement);
/// }
/// ```
pub struct HeaderCursorContinuation<'cursor, 'endpoint, 'session, 'request, 'policy> {
    pub(super) session: &'session HeaderCursorSession<'request, 'policy>,
    pub(super) cursor: PaginationCursor<'cursor>,
    pub(super) endpoint: EndpointIdentity<'endpoint>,
}

impl<'cursor, 'endpoint, 'session, 'request, 'policy>
    HeaderCursorContinuation<'cursor, 'endpoint, 'session, 'request, 'policy>
{
    /// Returns the provider operation that produced this continuation.
    #[must_use]
    pub const fn operation_id(&self) -> crate::operation::OperationId {
        self.session.operation_id()
    }

    /// Checks and transactionally records the exact cursor in caller history.
    pub fn observe_history(
        &self,
        history: &mut CursorHistory<'_>,
        digest: CursorDigest,
    ) -> Result<(), PaginationError> {
        history.observe(&self.cursor, digest)
    }

    /// Executes the next blocking request using the retained request context.
    #[allow(clippy::too_many_arguments)]
    pub fn execute_blocking<'response, 'next, T>(
        &self,
        transport: &T,
        response_storage: &'response mut [u8],
        response_header_storage: &'response mut [u8],
        decimal_scratch: &mut [u8],
        transfer_scratch: &mut [u8],
        cursor_destination: &'next mut [u8],
        limits: PaginationLimits,
    ) -> Result<
        HeaderCursorPage<'response, 'next, 'endpoint, 'session, 'request, 'policy>,
        HeaderCursorExecutionError<T::Error>,
    >
    where
        T: BlockingAuthenticatedTransport + BoundTransport,
    {
        clear_execution_buffers(
            response_storage,
            response_header_storage,
            decimal_scratch,
            transfer_scratch,
            cursor_destination,
        );
        let endpoint = transport.endpoint_identity().map_err(|error| {
            HeaderCursorExecutionError::Prepared(PreparedExecutionError::EndpointIdentity(error))
        })?;
        if endpoint != self.endpoint {
            return Err(HeaderCursorExecutionError::Pagination(
                PaginationError::EndpointMismatch,
            ));
        }
        execute_blocking(
            self.session,
            Some(&self.cursor),
            self.endpoint,
            transport,
            response_storage,
            response_header_storage,
            decimal_scratch,
            transfer_scratch,
            cursor_destination,
            limits,
        )
    }
}

impl fmt::Debug for HeaderCursorContinuation<'_, '_, '_, '_, '_> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("HeaderCursorContinuation")
            .field("operation", &self.operation_id())
            .field("request", &"[bound]")
            .field("cursor", &"[redacted]")
            .finish()
    }
}

pub(super) fn clear_execution_buffers(
    response_storage: &mut [u8],
    response_header_storage: &mut [u8],
    decimal_scratch: &mut [u8],
    transfer_scratch: &mut [u8],
    cursor_destination: &mut [u8],
) {
    sanitize_bytes(response_storage);
    sanitize_bytes(response_header_storage);
    sanitize_bytes(decimal_scratch);
    sanitize_bytes(transfer_scratch);
    sanitize_bytes(cursor_destination);
}

#[allow(clippy::too_many_arguments)]
fn execute_blocking<'response, 'cursor, 'endpoint, 'session, 'request, 'policy, T>(
    session: &'session HeaderCursorSession<'request, 'policy>,
    cursor: Option<&PaginationCursor<'_>>,
    endpoint: EndpointIdentity<'endpoint>,
    transport: &T,
    response_storage: &'response mut [u8],
    response_header_storage: &'response mut [u8],
    decimal_scratch: &mut [u8],
    transfer_scratch: &mut [u8],
    cursor_destination: &'cursor mut [u8],
    limits: PaginationLimits,
) -> Result<
    HeaderCursorPage<'response, 'cursor, 'endpoint, 'session, 'request, 'policy>,
    HeaderCursorExecutionError<T::Error>,
>
where
    T: BlockingAuthenticatedTransport + BoundTransport,
{
    let response = session
        .policy
        .with_request_headers(cursor, decimal_scratch, |pagination| {
            with_merged_request(&session.prepared, pagination, |prepared| {
                prepared.execute_blocking(transport, response_storage, response_header_storage)
            })
        })
        .map_err(HeaderCursorExecutionError::Pagination)?
        .map_err(HeaderCursorExecutionError::Pagination)?
        .map_err(HeaderCursorExecutionError::Prepared)?;
    finish_page(
        session,
        endpoint,
        response,
        transfer_scratch,
        cursor_destination,
        limits,
    )
}

pub(super) fn finish_page<'response, 'cursor, 'endpoint, 'session, 'request, 'policy, E>(
    session: &'session HeaderCursorSession<'request, 'policy>,
    endpoint: EndpointIdentity<'endpoint>,
    response: CheckedResponseGuard<'response>,
    transfer_scratch: &mut [u8],
    cursor_destination: &'cursor mut [u8],
    limits: PaginationLimits,
) -> Result<
    HeaderCursorPage<'response, 'cursor, 'endpoint, 'session, 'request, 'policy>,
    HeaderCursorExecutionError<E>,
> {
    let next = session
        .policy
        .decode_next(
            response.response_headers(),
            transfer_scratch,
            cursor_destination,
            limits,
        )
        .map_err(HeaderCursorExecutionError::Pagination)?;
    let next = match next {
        DecodedHeaderCursor::Complete => HeaderCursorNext::Complete,
        DecodedHeaderCursor::Continue(cursor) => {
            HeaderCursorNext::Continue(HeaderCursorContinuation {
                session,
                cursor,
                endpoint,
            })
        }
    };
    Ok(HeaderCursorPage { response, next })
}

pub(super) fn with_merged_request<'request, R>(
    prepared: &PreparedRequest<'request>,
    pagination: RequestHeaders<'_>,
    inspect: impl FnOnce(PreparedRequest<'_>) -> R,
) -> Result<R, PaginationError> {
    let base = prepared.transport_request().headers().as_slice();
    let extra = pagination.as_slice();
    let count = base
        .len()
        .checked_add(extra.len())
        .ok_or(PaginationError::RequestHeaderConflict)?;
    if count > MAX_REQUEST_HEADERS {
        return Err(PaginationError::RequestHeaderConflict);
    }
    let first = extra
        .first()
        .copied()
        .ok_or(PaginationError::InvalidHeaderState)?;
    let mut entries: [RequestHeader<'_>; MAX_REQUEST_HEADERS] = [first; MAX_REQUEST_HEADERS];
    entries
        .get_mut(..base.len())
        .ok_or(PaginationError::RequestHeaderConflict)?
        .copy_from_slice(base);
    entries
        .get_mut(base.len()..count)
        .ok_or(PaginationError::RequestHeaderConflict)?
        .copy_from_slice(extra);
    let selected = entries
        .get(..count)
        .ok_or(PaginationError::RequestHeaderConflict)?;
    let headers =
        RequestHeaders::new(selected).map_err(|_| PaginationError::RequestHeaderConflict)?;
    Ok(inspect((*prepared).with_request_headers(headers)))
}

#[cfg(test)]
mod tests {
    use super::clear_execution_buffers;

    #[test]
    fn predispatch_cleanup_clears_every_caller_buffer() {
        let mut response = [0xa5; 3];
        let mut headers = [0xa5; 5];
        let mut decimal = [0xa5; 7];
        let mut transfer = [0xa5; 11];
        let mut cursor = [0xa5; 13];
        clear_execution_buffers(
            &mut response,
            &mut headers,
            &mut decimal,
            &mut transfer,
            &mut cursor,
        );
        assert_eq!(response, [0; 3]);
        assert_eq!(headers, [0; 5]);
        assert_eq!(decimal, [0; 7]);
        assert_eq!(transfer, [0; 11]);
        assert_eq!(cursor, [0; 13]);
    }
}