cloud-sdk 0.55.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
//! Explicitly shareable permits backed by caller-owned atomic state.

use core::sync::atomic::{AtomicU32, Ordering};

use super::state::{AttemptPhase, PermitAttempt};
use super::{
    ExecutionPermitError, PermitDisposition, PermitIdempotencyKey, PermitScope, PermitState,
    PermitTimestamp, PlanSubject, ReconciliationToken, RecoveryToken, ReplayPolicy,
};

const STATE_MASK: u32 = 0b111;
const GENERATION_SHIFT: u32 = 3;
const GENERATION_MASK: u32 = 0x1fff;
const REMAINING_SHIFT: u32 = 16;

const READY: u32 = 0;
const IN_FLIGHT: u32 = 1;
const RECOVERABLE: u32 = 2;
const PENDING: u32 = 3;
const SPENT: u32 = 4;

/// Caller-owned atomic authority shared by all explicit permit-handle clones.
///
/// The state is initialized only through a shared permit constructor taking
/// `&mut SharedPermitState`. That exclusive borrow prevents safe code from
/// binding two independent plans to the same atomic state concurrently.
pub struct SharedPermitState {
    packed: AtomicU32,
    last_offset: AtomicU32,
}

impl SharedPermitState {
    /// Creates unbound spent state ready for one exclusive plan binding.
    #[must_use]
    pub fn new() -> Self {
        Self {
            packed: AtomicU32::new(pack(SPENT, 0, 0)),
            last_offset: AtomicU32::new(0),
        }
    }

    /// Returns the current atomic lifecycle state.
    #[must_use]
    pub fn state(&self) -> PermitState {
        unpack_state(self.packed.load(Ordering::Acquire))
    }

    fn initialize(
        &mut self,
        subject: PlanSubject<'_, '_>,
        now: PermitTimestamp,
    ) -> Result<(), ExecutionPermitError> {
        let offset = subject.validity().offset(now)?;
        *self.packed.get_mut() = pack(READY, 0, subject.attempt_budget().get());
        *self.last_offset.get_mut() = offset;
        Ok(())
    }

    fn begin(
        &self,
        subject: PlanSubject<'_, '_>,
        now: PermitTimestamp,
    ) -> Result<u16, ExecutionPermitError> {
        self.observe(subject, now)?;
        loop {
            let current = self.packed.load(Ordering::Acquire);
            let (state, generation, remaining) = unpack(current);
            match state {
                READY if remaining != 0 => {}
                READY | SPENT => return Err(ExecutionPermitError::Spent),
                IN_FLIGHT => return Err(ExecutionPermitError::AttemptInFlight),
                RECOVERABLE => return Err(ExecutionPermitError::RecoveryRequired),
                PENDING => return Err(ExecutionPermitError::ReconciliationRequired),
                _ => return Err(ExecutionPermitError::Spent),
            }
            let next_remaining = remaining
                .checked_sub(1)
                .ok_or(ExecutionPermitError::Spent)?;
            let next = pack(IN_FLIGHT, generation, next_remaining);
            if self
                .packed
                .compare_exchange(current, next, Ordering::AcqRel, Ordering::Acquire)
                .is_ok()
            {
                return Ok(generation);
            }
        }
    }

    pub(super) fn complete(
        &self,
        expected_generation: u16,
        phase: AttemptPhase,
    ) -> PermitDisposition {
        loop {
            let current = self.packed.load(Ordering::Acquire);
            let (state, generation, remaining) = unpack(current);
            if state != IN_FLIGHT || generation != expected_generation {
                return PermitDisposition::Spent;
            }
            let (next_state, disposition) = match phase {
                AttemptPhase::Applied | AttemptPhase::Rejected => (SPENT, PermitDisposition::Spent),
                AttemptPhase::NotSent if remaining == 0 => (SPENT, PermitDisposition::Spent),
                AttemptPhase::NotSent => (
                    RECOVERABLE,
                    PermitDisposition::Recoverable(RecoveryToken(generation)),
                ),
                AttemptPhase::Uncertain => (
                    PENDING,
                    PermitDisposition::PendingReconciliation(ReconciliationToken(generation)),
                ),
            };
            let next = pack(next_state, generation, remaining);
            if self
                .packed
                .compare_exchange(current, next, Ordering::AcqRel, Ordering::Acquire)
                .is_ok()
            {
                return disposition;
            }
        }
    }

    fn recover_not_sent(
        &self,
        subject: PlanSubject<'_, '_>,
        token: RecoveryToken,
        now: PermitTimestamp,
    ) -> Result<(), ExecutionPermitError> {
        self.observe(subject, now)?;
        if subject.replay_policy() == ReplayPolicy::SingleAttempt {
            return Err(ExecutionPermitError::ReplayForbidden);
        }
        self.rearm(RECOVERABLE, token.0)
    }

    fn reconcile_not_applied(
        &self,
        bound: PlanSubject<'_, '_>,
        candidate: PlanSubject<'_, '_>,
        token: ReconciliationToken,
        idempotency: PermitIdempotencyKey<'_>,
        now: PermitTimestamp,
    ) -> Result<(), ExecutionPermitError> {
        self.observe(bound, now)?;
        if bound.replay_policy() != ReplayPolicy::ReconcileThenRetry {
            return Err(ExecutionPermitError::ReplayForbidden);
        }
        if !bound.fingerprint().matches(candidate.fingerprint()) {
            return Err(ExecutionPermitError::FingerprintMismatch);
        }
        if !bound
            .idempotency()
            .is_some_and(|expected| expected.matches(idempotency))
        {
            return Err(ExecutionPermitError::IdempotencyMismatch);
        }
        self.rearm(PENDING, token.0)
    }

    fn rearm(
        &self,
        required_state: u32,
        expected_generation: u16,
    ) -> Result<(), ExecutionPermitError> {
        loop {
            let current = self.packed.load(Ordering::Acquire);
            let (state, generation, remaining) = unpack(current);
            if state != required_state || generation != expected_generation {
                return Err(ExecutionPermitError::StaleGeneration);
            }
            if remaining == 0 {
                let _ = self.packed.compare_exchange(
                    current,
                    pack(SPENT, generation, 0),
                    Ordering::AcqRel,
                    Ordering::Acquire,
                );
                return Err(ExecutionPermitError::Spent);
            }
            let Some(next_generation) = generation
                .checked_add(1)
                .filter(|value| u32::from(*value) <= GENERATION_MASK)
            else {
                if self
                    .packed
                    .compare_exchange(
                        current,
                        pack(SPENT, generation, 0),
                        Ordering::AcqRel,
                        Ordering::Acquire,
                    )
                    .is_ok()
                {
                    return Err(ExecutionPermitError::GenerationExhausted);
                }
                continue;
            };
            let next = pack(READY, next_generation, remaining);
            if self
                .packed
                .compare_exchange(current, next, Ordering::AcqRel, Ordering::Acquire)
                .is_ok()
            {
                return Ok(());
            }
        }
    }

    // `try_update` is unavailable on Rust 1.90; retain its predecessor through MSRV.
    #[allow(deprecated)]
    pub(super) fn observe(
        &self,
        subject: PlanSubject<'_, '_>,
        now: PermitTimestamp,
    ) -> Result<(), ExecutionPermitError> {
        let offset = match subject.validity().offset(now) {
            Ok(offset) => offset,
            Err(error) => {
                self.spend();
                return Err(error);
            }
        };
        let result = self
            .last_offset
            .fetch_update(Ordering::AcqRel, Ordering::Acquire, |previous| {
                (offset >= previous).then_some(offset)
            })
            .map(|_| ())
            .map_err(|_| ExecutionPermitError::ClockRollback);
        if result.is_err() {
            self.spend();
        }
        result
    }

    pub(super) fn observe_attempt(
        &self,
        subject: PlanSubject<'_, '_>,
        expected_generation: u16,
        now: PermitTimestamp,
    ) -> Result<(), ExecutionPermitError> {
        self.observe(subject, now)?;
        let (state, generation, _) = unpack(self.packed.load(Ordering::Acquire));
        if state != IN_FLIGHT || generation != expected_generation {
            return Err(ExecutionPermitError::Spent);
        }
        Ok(())
    }

    fn spend(&self) {
        loop {
            let current = self.packed.load(Ordering::Acquire);
            let (_, generation, _) = unpack(current);
            if current == pack(SPENT, generation, 0) {
                return;
            }
            if self
                .packed
                .compare_exchange(
                    current,
                    pack(SPENT, generation, 0),
                    Ordering::AcqRel,
                    Ordering::Acquire,
                )
                .is_ok()
            {
                return;
            }
        }
    }
}

impl Default for SharedPermitState {
    fn default() -> Self {
        Self::new()
    }
}

impl core::fmt::Debug for SharedPermitState {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter
            .debug_struct("SharedPermitState")
            .field("state", &self.state())
            .field("authority", &"[redacted]")
            .finish()
    }
}

macro_rules! shared_permit {
    ($name:ident, $scope:expr, $description:literal) => {
        #[doc = $description]
        ///
        /// Every clone references the same caller-owned atomic state. Cloning
        /// never creates new budget or an independent recovery generation.
        pub struct $name<'state, 'request, 'fingerprint> {
            state: &'state SharedPermitState,
            subject: PlanSubject<'request, 'fingerprint>,
        }

        impl<'state, 'request, 'fingerprint> $name<'state, 'request, 'fingerprint> {
            /// Exclusively binds fresh shared state to one confirmed plan.
            pub fn new(
                state: &'state mut SharedPermitState,
                subject: PlanSubject<'request, 'fingerprint>,
                now: PermitTimestamp,
            ) -> Result<Self, ExecutionPermitError> {
                if subject.scope() != $scope {
                    return Err(ExecutionPermitError::ScopeMismatch);
                }
                state.initialize(subject, now)?;
                Ok(Self { state, subject })
            }

            /// Returns the shared lifecycle state.
            #[must_use]
            pub fn state(&self) -> PermitState {
                self.state.state()
            }

            /// Atomically starts one attempt for the bound plan.
            pub fn begin(
                &self,
                now: PermitTimestamp,
            ) -> Result<PermitAttempt<'_, 'request, 'fingerprint>, ExecutionPermitError> {
                let generation = self.state.begin(self.subject, now)?;
                Ok(PermitAttempt::shared(self.state, self.subject, generation))
            }

            /// Starts only if the candidate fingerprint matches the bound plan.
            pub fn begin_for(
                &self,
                candidate: PlanSubject<'_, '_>,
                now: PermitTimestamp,
            ) -> Result<PermitAttempt<'_, 'request, 'fingerprint>, ExecutionPermitError> {
                if !self.subject.fingerprint().matches(candidate.fingerprint()) {
                    return Err(ExecutionPermitError::FingerprintMismatch);
                }
                self.begin(now)
            }

            /// Atomically recovers a generation-matched `NotSent` attempt.
            pub fn recover_not_sent(
                &self,
                token: RecoveryToken,
                now: PermitTimestamp,
            ) -> Result<(), ExecutionPermitError> {
                self.state.recover_not_sent(self.subject, token, now)
            }

            /// Rearms after caller-performed operation-specific reconciliation.
            pub fn reconcile_not_applied(
                &self,
                token: ReconciliationToken,
                candidate: PlanSubject<'_, '_>,
                idempotency: PermitIdempotencyKey<'_>,
                now: PermitTimestamp,
            ) -> Result<(), ExecutionPermitError> {
                self.state
                    .reconcile_not_applied(self.subject, candidate, token, idempotency, now)
            }
        }

        impl Clone for $name<'_, '_, '_> {
            fn clone(&self) -> Self {
                Self {
                    state: self.state,
                    subject: self.subject,
                }
            }
        }

        impl core::fmt::Debug for $name<'_, '_, '_> {
            fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                formatter
                    .debug_struct(stringify!($name))
                    .field("state", &self.state())
                    .field("plan", &"[redacted]")
                    .finish()
            }
        }
    };
}

shared_permit!(
    SharedMutationPermit,
    PermitScope::Mutation,
    "Shared atomic mutation authority."
);
shared_permit!(
    SharedDestructivePermit,
    PermitScope::Destructive,
    "Shared atomic destructive authority."
);
shared_permit!(
    SharedCostPermit,
    PermitScope::Cost,
    "Shared atomic price-bounded authority."
);

fn pack(state: u32, generation: u16, remaining: u16) -> u32 {
    state | (u32::from(generation) << GENERATION_SHIFT) | (u32::from(remaining) << REMAINING_SHIFT)
}

fn unpack(value: u32) -> (u32, u16, u16) {
    let generation = u16::try_from((value >> GENERATION_SHIFT) & GENERATION_MASK).unwrap_or(0);
    let remaining = u16::try_from(value >> REMAINING_SHIFT).unwrap_or(0);
    (value & STATE_MASK, generation, remaining)
}

fn unpack_state(value: u32) -> PermitState {
    match value & STATE_MASK {
        READY => PermitState::Ready,
        IN_FLIGHT => PermitState::InFlight,
        RECOVERABLE => PermitState::Recoverable,
        PENDING => PermitState::PendingReconciliation,
        _ => PermitState::Spent,
    }
}