saddle-runtime 0.3.0-alpha.2

Saddle managed asynchronous runtime and lifecycle
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
//! Alpha.1 bridge from a fixed, parsed Ingress owner into the 0.2 request domain.
//!
//! This is intentionally an execution seam, not a listener or protocol API.

use std::{
    future::Future,
    pin::Pin,
    sync::{
        Arc,
        atomic::{AtomicBool, AtomicUsize, Ordering},
    },
    task::{Context, Poll},
    time::{Duration, SystemTime, UNIX_EPOCH},
};

use tokio::{sync::oneshot, time::Instant};

use crate::{RequestLifecycle, request::RequestClaim};

/// Verified absolute deadline consumed by one managed request submission.
///
/// It is non-cloneable and exposes no raw duration or Tokio instant.
#[doc(hidden)]
pub struct AbsoluteDeadlineOwner {
    instant: Instant,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[doc(hidden)]
pub enum AbsoluteDeadlineError {
    ClockBeforeUnixEpoch,
    Expired,
    OutOfRange,
}

/// Converts the protocol absolute deadline once, before Admission publication.
#[doc(hidden)]
pub fn verify_absolute_deadline(
    deadline_unix_ms: u64,
) -> Result<AbsoluteDeadlineOwner, AbsoluteDeadlineError> {
    let now_wall = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_err(|_| AbsoluteDeadlineError::ClockBeforeUnixEpoch)?;
    let now_ms =
        u64::try_from(now_wall.as_millis()).map_err(|_| AbsoluteDeadlineError::OutOfRange)?;
    let remaining_ms = deadline_unix_ms
        .checked_sub(now_ms)
        .filter(|remaining| *remaining > 0)
        .ok_or(AbsoluteDeadlineError::Expired)?;
    let instant = Instant::now()
        .checked_add(Duration::from_millis(remaining_ms))
        .ok_or(AbsoluteDeadlineError::OutOfRange)?;
    Ok(AbsoluteDeadlineOwner { instant })
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[doc(hidden)]
pub enum ManagedIngressRejectReason {
    RuntimeUnavailable,
    AtCapacity,
    Lifecycle,
}

/// Recoverable pre-publication rejection. The exact input and deadline owner
/// are returned; no task or request guard exists.
#[doc(hidden)]
pub struct ManagedIngressRejection<I> {
    input: I,
    deadline: AbsoluteDeadlineOwner,
    reason: ManagedIngressRejectReason,
}

impl<I> std::fmt::Debug for ManagedIngressRejection<I> {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("ManagedIngressRejection")
            .field("reason", &self.reason)
            .finish_non_exhaustive()
    }
}

impl<I> ManagedIngressRejection<I> {
    pub fn into_parts(self) -> (I, AbsoluteDeadlineOwner, ManagedIngressRejectReason) {
        (self.input, self.deadline, self.reason)
    }
}

/// The one terminal emitted by the Runtime-owned request task.
#[derive(Debug, Eq, PartialEq)]
#[doc(hidden)]
pub enum ManagedIngressTerminal<O, E> {
    Completed(Result<O, E>),
    DeadlineExceeded,
    Panicked,
}

/// Consumable post-finalizer resource fact. `Zero` is signed only after the
/// request lifecycle guard has been returned and this bridge has no other
/// occupied request generation at the finalizer linearization point.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[doc(hidden)]
pub enum ManagedIngressResourceState {
    Zero,
    NonZero,
}

/// Non-cloneable evidence emitted by the unique request finalizer.
#[doc(hidden)]
pub struct ManagedIngressFinalized<O, E> {
    terminal: ManagedIngressTerminal<O, E>,
    resources: ManagedIngressResourceState,
}

impl<O, E> ManagedIngressFinalized<O, E> {
    pub fn into_parts(self) -> (ManagedIngressTerminal<O, E>, ManagedIngressResourceState) {
        (self.terminal, self.resources)
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[doc(hidden)]
pub struct ManagedIngressFinalizerLost;

/// Failure from the supported one-shot composition seam. A submission
/// rejection is preserved exactly; a missing finalizer remains fail-closed.
#[doc(hidden)]
pub enum ManagedIngressCompositionFailure<R> {
    InvalidCapacity,
    Rejected(R),
    FinalizerLost(ManagedIngressFinalizerLost),
}

#[cfg(test)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct ManagedIngressResourceSnapshot {
    active: usize,
    occupied_slots: usize,
    terminals: usize,
}

struct Shared {
    requests: RequestLifecycle,
    slots: Box<[AtomicBool]>,
    active: AtomicUsize,
    terminals: AtomicUsize,
}

/// Fixed-capacity ingress bridge. It owns no listener and exposes no executor.
#[derive(Clone)]
#[doc(hidden)]
pub struct ManagedIngressBridge {
    shared: Arc<Shared>,
}

impl ManagedIngressBridge {
    pub(crate) fn new(requests: RequestLifecycle, capacity: usize) -> Option<Self> {
        if capacity == 0 {
            return None;
        }
        Some(Self {
            shared: Arc::new(Shared {
                requests,
                slots: (0..capacity).map(|_| AtomicBool::new(false)).collect(),
                active: AtomicUsize::new(0),
                terminals: AtomicUsize::new(0),
            }),
        })
    }

    /// Moves an owned, already parsed fixed-Ingress input into the managed
    /// request domain. Dropping the returned completion does not cancel work.
    #[allow(clippy::type_complexity)]
    pub fn try_submit<I, F, Fut, O, E>(
        &self,
        input: I,
        deadline: AbsoluteDeadlineOwner,
        execute: F,
    ) -> Result<ManagedIngressCompletion<O, E>, ManagedIngressRejection<I>>
    where
        I: Send + 'static,
        F: FnOnce(I) -> Fut + Send + 'static,
        Fut: Future<Output = Result<O, E>> + Send + 'static,
        O: Send + 'static,
        E: Send + 'static,
    {
        if tokio::runtime::Handle::try_current().is_err() {
            return Err(ManagedIngressRejection {
                input,
                deadline,
                reason: ManagedIngressRejectReason::RuntimeUnavailable,
            });
        }
        let Some(slot) = self.shared.slots.iter().position(|slot| {
            slot.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
                .is_ok()
        }) else {
            return Err(ManagedIngressRejection {
                input,
                deadline,
                reason: ManagedIngressRejectReason::AtCapacity,
            });
        };
        self.shared.active.fetch_add(1, Ordering::AcqRel);
        let claim = match self.shared.requests.try_claim() {
            Ok(claim) => claim,
            Err(_) => {
                self.shared.active.fetch_sub(1, Ordering::AcqRel);
                self.shared.slots[slot].store(false, Ordering::Release);
                return Err(ManagedIngressRejection {
                    input,
                    deadline,
                    reason: ManagedIngressRejectReason::Lifecycle,
                });
            }
        };
        let (sender, receiver) = oneshot::channel();
        let finalizer = RequestFinalizer {
            shared: Arc::clone(&self.shared),
            slot,
            lifecycle: Some(RequestClaim::publish(claim)),
            sender: Some(sender),
            finished: false,
        };
        tokio::spawn(async move {
            let terminal = match tokio::time::timeout_at(deadline.instant, execute(input)).await {
                Ok(result) => ManagedIngressTerminal::Completed(result),
                Err(_) => ManagedIngressTerminal::DeadlineExceeded,
            };
            finalizer.finish(terminal);
        });
        Ok(ManagedIngressCompletion { receiver })
    }

    #[cfg(test)]
    fn resource_snapshot(&self) -> ManagedIngressResourceSnapshot {
        ManagedIngressResourceSnapshot {
            active: self.shared.active.load(Ordering::Acquire),
            occupied_slots: self
                .shared
                .slots
                .iter()
                .filter(|slot| slot.load(Ordering::Acquire))
                .count(),
            terminals: self.shared.terminals.load(Ordering::Acquire),
        }
    }
}

/// Supported non-business composition seam for framework integration and
/// cross-component verification.
///
/// Runtime exclusively performs the Ready transition, invokes exactly one
/// submission closure, then drains the same 0.2 lifecycle before returning
/// the post-finalizer receipt. It is not a listener or production entry API.
#[doc(hidden)]
pub async fn compose_managed_ingress_once<F, O, E, R>(
    capacity: usize,
    submit: F,
) -> Result<ManagedIngressFinalized<O, E>, ManagedIngressCompositionFailure<R>>
where
    F: FnOnce(&ManagedIngressBridge) -> Result<ManagedIngressCompletion<O, E>, R>,
{
    let requests = RequestLifecycle::new();
    let Some(bridge) = ManagedIngressBridge::new(requests.clone(), capacity) else {
        return Err(ManagedIngressCompositionFailure::InvalidCapacity);
    };
    requests.mark_ready();
    let completion = match submit(&bridge) {
        Ok(completion) => completion,
        Err(rejection) => {
            requests.begin_draining();
            requests.wait_until_drained().await;
            requests.mark_stopped();
            return Err(ManagedIngressCompositionFailure::Rejected(rejection));
        }
    };
    let finalized = completion.await;
    requests.begin_draining();
    requests.wait_until_drained().await;
    requests.mark_stopped();
    finalized.map_err(ManagedIngressCompositionFailure::FinalizerLost)
}

struct RequestFinalizer<O, E> {
    shared: Arc<Shared>,
    slot: usize,
    lifecycle: Option<crate::RequestGuard>,
    sender: Option<oneshot::Sender<ManagedIngressFinalized<O, E>>>,
    finished: bool,
}

impl<O, E> RequestFinalizer<O, E> {
    fn finish(mut self, terminal: ManagedIngressTerminal<O, E>) {
        self.record(terminal);
    }

    fn record(&mut self, terminal: ManagedIngressTerminal<O, E>) {
        // This is the finalizer linearization sequence. The receipt cannot be
        // observed until the lifecycle and fixed-slot resources are returned.
        drop(self.lifecycle.take());
        let previous_active = self.shared.active.fetch_sub(1, Ordering::AcqRel);
        debug_assert!(previous_active > 0);
        self.shared.slots[self.slot].store(false, Ordering::Release);
        self.shared.terminals.fetch_add(1, Ordering::AcqRel);
        self.finished = true;
        let resources = if previous_active == 1 {
            ManagedIngressResourceState::Zero
        } else {
            ManagedIngressResourceState::NonZero
        };
        let _ = self
            .sender
            .take()
            .expect("terminal sender exists")
            .send(ManagedIngressFinalized {
                terminal,
                resources,
            });
    }
}

impl<O, E> Drop for RequestFinalizer<O, E> {
    fn drop(&mut self) {
        if !self.finished {
            self.record(ManagedIngressTerminal::Panicked);
        }
    }
}

/// Awaitable terminal receiver. Dropping it detaches only the response waiter;
/// the Runtime-owned task, finalizer and lifecycle guard continue to terminal.
#[doc(hidden)]
pub struct ManagedIngressCompletion<O, E> {
    receiver: oneshot::Receiver<ManagedIngressFinalized<O, E>>,
}

impl<O, E> Future for ManagedIngressCompletion<O, E> {
    type Output = Result<ManagedIngressFinalized<O, E>, ManagedIngressFinalizerLost>;

    fn poll(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
        match Pin::new(&mut self.receiver).poll(context) {
            Poll::Ready(Ok(finalized)) => Poll::Ready(Ok(finalized)),
            Poll::Ready(Err(_)) => Poll::Ready(Err(ManagedIngressFinalizerLost)),
            Poll::Pending => Poll::Pending,
        }
    }
}

#[cfg(test)]
mod tests {
    use std::{
        sync::{
            Arc,
            atomic::{AtomicUsize, Ordering},
        },
        time::{Duration, SystemTime, UNIX_EPOCH},
    };

    use super::*;

    fn deadline(after: Duration) -> AbsoluteDeadlineOwner {
        let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
        verify_absolute_deadline(u64::try_from((now + after).as_millis()).unwrap()).unwrap()
    }

    async fn ready_bridge(capacity: usize) -> ManagedIngressBridge {
        let requests = RequestLifecycle::new();
        requests.mark_ready();
        ManagedIngressBridge::new(requests, capacity).unwrap()
    }

    #[tokio::test]
    async fn success_deadline_panic_and_detached_waiter_all_return_resources() {
        let bridge = ready_bridge(1).await;
        let (completed, completed_resources) = bridge
            .try_submit(7, deadline(Duration::from_secs(1)), |value| async move {
                Ok::<_, ()>(value + 1)
            })
            .unwrap()
            .await
            .unwrap()
            .into_parts();
        assert_eq!(completed, ManagedIngressTerminal::Completed(Ok(8)));
        assert_eq!(completed_resources, ManagedIngressResourceState::Zero);

        let (expired, expired_resources) = bridge
            .try_submit((), deadline(Duration::from_millis(5)), |_| async {
                tokio::time::sleep(Duration::from_secs(1)).await;
                Ok::<_, ()>(())
            })
            .unwrap()
            .await
            .unwrap()
            .into_parts();
        assert_eq!(expired, ManagedIngressTerminal::DeadlineExceeded);
        assert_eq!(expired_resources, ManagedIngressResourceState::Zero);

        let (panicked, panicked_resources) = bridge
            .try_submit((), deadline(Duration::from_secs(1)), |_| async {
                panic!("managed panic");
                #[allow(unreachable_code)]
                Ok::<(), ()>(())
            })
            .unwrap()
            .await
            .unwrap()
            .into_parts();
        assert_eq!(panicked, ManagedIngressTerminal::Panicked);
        assert_eq!(panicked_resources, ManagedIngressResourceState::Zero);

        let drops = Arc::new(AtomicUsize::new(0));
        struct Input(Arc<AtomicUsize>);
        impl Drop for Input {
            fn drop(&mut self) {
                self.0.fetch_add(1, Ordering::SeqCst);
            }
        }
        let completion = bridge
            .try_submit(
                Input(Arc::clone(&drops)),
                deadline(Duration::from_secs(1)),
                |input| async move {
                    tokio::time::sleep(Duration::from_millis(10)).await;
                    drop(input);
                    Ok::<_, ()>(())
                },
            )
            .unwrap();
        drop(completion);
        tokio::time::sleep(Duration::from_millis(30)).await;
        assert_eq!(drops.load(Ordering::SeqCst), 1);
        let snapshot = bridge.resource_snapshot();
        assert_eq!(snapshot.active, 0);
        assert_eq!(snapshot.occupied_slots, 0);
        assert_eq!(snapshot.terminals, 4);
    }

    #[tokio::test]
    async fn fixed_capacity_rejection_recovers_input_and_deadline_without_a_task() {
        let bridge = ready_bridge(1).await;
        let release = Arc::new(tokio::sync::Notify::new());
        let entered = Arc::new(tokio::sync::Notify::new());
        let first = bridge
            .try_submit((), deadline(Duration::from_secs(1)), {
                let release = Arc::clone(&release);
                let entered = Arc::clone(&entered);
                move |_| async move {
                    entered.notify_one();
                    release.notified().await;
                    Ok::<(), ()>(())
                }
            })
            .unwrap();
        entered.notified().await;

        let rejection = match bridge.try_submit(17, deadline(Duration::from_secs(1)), |_| async {
            Ok::<_, ()>(())
        }) {
            Ok(_) => panic!("second fixed slot must be rejected"),
            Err(rejection) => rejection,
        };
        let (input, recovered_deadline, reason) = rejection.into_parts();
        assert_eq!(input, 17);
        assert_eq!(reason, ManagedIngressRejectReason::AtCapacity);
        assert_eq!(bridge.resource_snapshot().active, 1);

        release.notify_one();
        let (first_terminal, first_resources) = first.await.unwrap().into_parts();
        assert_eq!(first_terminal, ManagedIngressTerminal::Completed(Ok(())));
        assert_eq!(first_resources, ManagedIngressResourceState::Zero);
        let (retry, retry_resources) = bridge
            .try_submit(input, recovered_deadline, |_| async { Ok::<_, ()>(()) })
            .unwrap()
            .await
            .unwrap()
            .into_parts();
        assert_eq!(retry, ManagedIngressTerminal::Completed(Ok(())));
        assert_eq!(retry_resources, ManagedIngressResourceState::Zero);
        let snapshot = bridge.resource_snapshot();
        assert_eq!(snapshot.active, 0);
        assert_eq!(snapshot.occupied_slots, 0);
        assert_eq!(snapshot.terminals, 2);
    }

    #[tokio::test]
    async fn finalized_receipt_distinguishes_nonzero_then_zero() {
        let bridge = ready_bridge(2).await;
        let release_first = Arc::new(tokio::sync::Notify::new());
        let release_second = Arc::new(tokio::sync::Notify::new());
        let first = bridge
            .try_submit((), deadline(Duration::from_secs(1)), {
                let release = Arc::clone(&release_first);
                move |_| async move {
                    release.notified().await;
                    Ok::<(), ()>(())
                }
            })
            .unwrap();
        let second = bridge
            .try_submit((), deadline(Duration::from_secs(1)), {
                let release = Arc::clone(&release_second);
                move |_| async move {
                    release.notified().await;
                    Ok::<(), ()>(())
                }
            })
            .unwrap();

        release_first.notify_one();
        let (_, first_resources) = first.await.unwrap().into_parts();
        assert_eq!(first_resources, ManagedIngressResourceState::NonZero);
        release_second.notify_one();
        let (_, second_resources) = second.await.unwrap().into_parts();
        assert_eq!(second_resources, ManagedIngressResourceState::Zero);
        assert_eq!(bridge.resource_snapshot().active, 0);
        assert_eq!(bridge.resource_snapshot().occupied_slots, 0);
    }

    #[test]
    fn application_issues_only_one_fixed_bridge() {
        let application = crate::Application::new();
        assert!(application.managed_ingress_bridge(0).is_none());
        assert!(application.managed_ingress_bridge(1).is_some());
        assert!(application.managed_ingress_bridge(1).is_none());
    }
}