saddle-boundary 0.3.24

Saddle 0.3 ProfuseContract unary boundary transport
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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
//! Guarded request consumers. These owners must remain outside cancelled futures.
//! No network, timeout, root issuer or physical completion authority is created.
use crate::request_diagnostics::BoundaryFailure;
use crate::source_diagnostics::{SourceCapture, SourceReceipt, code};
use crate::{
    BoundaryError, InvokeRequest, InvokeResponse, ProfuseContractAuthorityTemplate, TonicBoundary,
};
use saddle_core::{
    BoundedDiagnostic, BoundedDiagnosticCause, CaptureSite, DiagnosticCategory,
    DiagnosticOutcomeAxes, DiagnosticStage, OperationOutcome,
};
use saddle_observability::root_diagnostic::{RootOutcomeFacts, RootRequestEvent};
use saddle_observability::{DiagnosticSubmission, EmergencyDiagnosticHandle, EventContext};
use saddle_runtime::request_task::reserved::{ReservedRequestFailure, ReservedRequestView};
use std::sync::Mutex;

/// Mapping only moves the classification. The original guarded receipt survives.
/// ```compile_fail
/// use saddle_boundary::reserved_diagnostics::ReservedFailure;
/// fn naked() -> ReservedFailure<()> { ().into() }
/// ```
/// ```compile_fail
/// use saddle_boundary::reserved_diagnostics::ReservedFailure;
/// fn duplicate(f: ReservedFailure<()>) { let _ = f.clone(); }
/// ```
#[must_use]
pub struct ReservedFailure<E> {
    error: E,
    receipt: ReservedRequestFailure,
}
impl<E> ReservedFailure<E> {
    pub fn error(&self) -> &E {
        &self.error
    }
    pub fn occurrence(&self) -> saddle_core::DiagnosticOccurrence {
        self.receipt.occurrence()
    }
    pub fn map_error<F>(self, map: impl FnOnce(E) -> F) -> ReservedFailure<F> {
        ReservedFailure {
            error: map(self.error),
            receipt: self.receipt,
        }
    }
    pub fn into_parts(self) -> (E, ReservedRequestFailure) {
        (self.error, self.receipt)
    }
}

struct State {
    view: ReservedRequestView,
    failure: Option<ReservedRequestFailure>,
    started: bool,
    completed: bool,
}
/// Inline owner. Any boxing/collection and its enclosing Future must be charged
/// by its real caller; view/child allocations use the existing guarded permit.
pub struct ReservedAttempt<'a> {
    state: Mutex<State>,
    output: Option<&'a EmergencyDiagnosticHandle>,
}
#[must_use]
pub enum ReservedAttemptCompletion {
    Returned,
    Interrupted(ReservedFailure<BoundaryFailure>),
}
fn facts(operation: OperationOutcome) -> RootOutcomeFacts {
    RootOutcomeFacts {
        axes: DiagnosticOutcomeAxes {
            operation,
            ..Default::default()
        },
        ..Default::default()
    }
}

/// Same actual IO classifier as legacy ingress, but captures the complete
/// original synchronously under the caller's existing guarded view.
#[track_caller]
pub fn capture_io(
    view: &ReservedRequestView,
    output: Option<&EmergencyDiagnosticHandle>,
    operation: crate::source_diagnostics::IoOperation,
    error: &std::io::Error,
) -> ReservedFailure<std::io::ErrorKind> {
    struct Capture<'a> {
        view: &'a ReservedRequestView,
        output: Option<&'a EmergencyDiagnosticHandle>,
        event: RootRequestEvent,
        receipt: Mutex<Option<ReservedRequestFailure>>,
    }
    impl SourceCapture for Capture<'_> {
        fn submit_cause(
            &self,
            _: DiagnosticCategory,
            _: BoundedDiagnosticCause,
        ) -> Option<SourceReceipt> {
            unreachable!("IO always supplies its actual error")
        }
        fn submit_error(
            &self,
            error: &(dyn std::error::Error + 'static),
            category: DiagnosticCategory,
            cause: BoundedDiagnosticCause,
        ) -> Option<SourceReceipt> {
            let diagnostic =
                BoundedDiagnostic::capture(category, CaptureSite::FirstObserved, cause);
            *self.receipt.lock().unwrap_or_else(|p| p.into_inner()) =
                Some(self.view.source_error_with_facts(
                    error,
                    diagnostic,
                    code("transport.io"),
                    self.output,
                    self.event,
                    facts(OperationOutcome::Failed),
                ));
            None
        }
        fn boundary(
            &self,
            _: Option<SourceReceipt>,
            _: &DiagnosticOutcomeAxes,
        ) -> DiagnosticSubmission {
            unreachable!("source only")
        }
    }
    use crate::source_diagnostics::IoOperation;
    let event = match operation {
        IoOperation::Accept | IoOperation::ReadHead | IoOperation::ReadBody => {
            RootRequestEvent::Ingress
        }
        _ => RootRequestEvent::Response,
    };
    let capture = Capture {
        view,
        output,
        event,
        receipt: Mutex::new(None),
    };
    let _ = (&capture as &dyn SourceCapture).io_failure(operation, error);
    ReservedFailure {
        error: error.kind(),
        receipt: capture
            .receipt
            .into_inner()
            .unwrap_or_else(|p| p.into_inner())
            .expect("actual IO captured before mapping"),
    }
}
impl<'a> ReservedAttempt<'a> {
    /// Construction/fake failures use the same owner and mandatory credential.
    /// Call before mapping the original error. No retry or cloned source occurs.
    pub fn capture_boundary_failure(
        &mut self,
        error: BoundaryError,
    ) -> ReservedFailure<BoundaryFailure> {
        self.capture(
            Some(&error),
            DiagnosticCategory::ExpectedRejection,
            BoundedDiagnosticCause::new(
                DiagnosticStage::RequestOutbound,
                code("transport.adapter_failure"),
            ),
        );
        let mut state = self.state.lock().unwrap_or_else(|p| p.into_inner());
        state.completed = true;
        ReservedFailure {
            error: BoundaryFailure {
                code: error.code,
                certainty: error.certainty,
            },
            receipt: state.failure.take().expect("source before mapping"),
        }
    }
    pub fn complete_adapter(&mut self) {
        self.state
            .lock()
            .unwrap_or_else(|p| p.into_inner())
            .completed = true;
    }
    /// The original supervisor selected its deadline after dropping the invoke
    /// borrow. Retain any earlier source; do not create a second occurrence.
    pub fn timed_out(&self) {
        self.local_failure(crate::source_diagnostics::LocalFailure::Deadline);
    }
    pub fn new(view: ReservedRequestView, output: Option<&'a EmergencyDiagnosticHandle>) -> Self {
        Self {
            state: Mutex::new(State {
                view,
                failure: None,
                started: false,
                completed: false,
            }),
            output,
        }
    }
    /// Sharing this handle preserves its original storage permission.
    pub fn view(&self) -> ReservedRequestView {
        self.state
            .lock()
            .unwrap_or_else(|p| p.into_inner())
            .view
            .clone()
    }
    #[track_caller]
    fn capture(
        &self,
        original: Option<&(dyn std::error::Error + 'static)>,
        category: DiagnosticCategory,
        cause: BoundedDiagnosticCause,
    ) {
        self.capture_with_outcome(
            original,
            category,
            cause,
            "transport source has no Error object",
            OperationOutcome::Failed,
        );
    }
    #[track_caller]
    fn capture_with_outcome(
        &self,
        original: Option<&(dyn std::error::Error + 'static)>,
        category: DiagnosticCategory,
        cause: BoundedDiagnosticCause,
        description: &'static str,
        operation: OperationOutcome,
    ) {
        let mut state = self.state.lock().unwrap_or_else(|p| p.into_inner());
        if state.failure.is_some() {
            return;
        }
        let diagnostic = BoundedDiagnostic::capture(category, CaptureSite::FirstObserved, cause);
        state.failure = Some(match original {
            Some(error) => state.view.source_error_with_facts(
                error,
                diagnostic,
                code("transport.source"),
                self.output,
                RootRequestEvent::Outbound,
                facts(operation),
            ),
            None => state.view.source_description(
                &description,
                diagnostic,
                code("transport.source"),
                self.output,
                RootRequestEvent::Outbound,
                facts(operation),
            ),
        });
    }
    pub fn finish(self) -> ReservedAttemptCompletion {
        if !self
            .state
            .lock()
            .unwrap_or_else(|p| p.into_inner())
            .completed
        {
            self.local_failure(crate::source_diagnostics::LocalFailure::Cancelled);
        }
        let state = self.state.into_inner().unwrap_or_else(|p| p.into_inner());
        if state.completed {
            return ReservedAttemptCompletion::Returned;
        }
        ReservedAttemptCompletion::Interrupted(ReservedFailure {
            error: BoundaryFailure {
                code: crate::TechnicalCode::TransportFailure,
                certainty: if state.started {
                    crate::ExecutionCertainty::MayHaveExecuted
                } else {
                    crate::ExecutionCertainty::NotExecuted
                },
            },
            receipt: state.failure.expect("cancellation captured"),
        })
    }
}
impl SourceCapture for ReservedAttempt<'_> {
    fn protocol_failure(&self, description: &'static str) -> Option<SourceReceipt> {
        self.capture_with_outcome(
            None,
            DiagnosticCategory::UnexpectedError,
            BoundedDiagnosticCause::new(
                DiagnosticStage::RequestOutbound,
                code("transport.response_invalid"),
            ),
            description,
            OperationOutcome::Failed,
        );
        None
    }
    fn guarded(&self) -> bool {
        true
    }
    fn local_error(
        &self,
        error: &BoundaryError,
        failure: crate::source_diagnostics::LocalFailure,
    ) -> Option<SourceReceipt> {
        use crate::source_diagnostics::LocalFailure;
        let (reason, operation) = match failure {
            LocalFailure::Deadline => ("transport.deadline_elapsed", OperationOutcome::TimedOut),
            LocalFailure::Cancelled => ("transport.cancelled", OperationOutcome::Cancelled),
            LocalFailure::InvalidAuthority => {
                ("transport.authority_invalid", OperationOutcome::Rejected)
            }
            LocalFailure::InvalidRequest => {
                ("transport.request_invalid", OperationOutcome::Rejected)
            }
        };
        self.capture_with_outcome(
            Some(error),
            DiagnosticCategory::ExpectedRejection,
            BoundedDiagnosticCause::new(DiagnosticStage::RequestOutbound, code(reason)),
            reason,
            operation,
        );
        None
    }
    fn local_failure(
        &self,
        failure: crate::source_diagnostics::LocalFailure,
    ) -> Option<SourceReceipt> {
        use crate::source_diagnostics::LocalFailure;
        let (reason, operation) = match failure {
            LocalFailure::Cancelled => ("transport.cancelled", OperationOutcome::Cancelled),
            LocalFailure::Deadline => ("transport.deadline_elapsed", OperationOutcome::TimedOut),
            LocalFailure::InvalidRequest => {
                ("transport.request_invalid", OperationOutcome::Rejected)
            }
            LocalFailure::InvalidAuthority => {
                ("transport.authority_invalid", OperationOutcome::Rejected)
            }
        };
        self.capture_with_outcome(
            None,
            DiagnosticCategory::ExpectedRejection,
            BoundedDiagnosticCause::new(DiagnosticStage::RequestOutbound, code(reason)),
            reason,
            operation,
        );
        None
    }
    fn required(&self) -> bool {
        true
    }
    fn submit_cause(
        &self,
        category: DiagnosticCategory,
        cause: BoundedDiagnosticCause,
    ) -> Option<SourceReceipt> {
        self.capture(None, category, cause);
        None // Guarded mandatory receipt stays in the owner, not the legacy error.
    }
    fn submit_error(
        &self,
        error: &(dyn std::error::Error + 'static),
        category: DiagnosticCategory,
        cause: BoundedDiagnosticCause,
    ) -> Option<SourceReceipt> {
        self.capture(Some(error), category, cause);
        None
    }
    fn boundary(
        &self,
        _: Option<SourceReceipt>,
        _: &DiagnosticOutcomeAxes,
    ) -> DiagnosticSubmission {
        // Finalization is exclusively the caller's guarded receipt consumption.
        DiagnosticSubmission::OutputUnavailable
    }
    fn bind_child(
        &self,
        call: &saddle_core::CallContext,
        _: &EventContext,
        request: &str,
        route: &str,
    ) -> Result<(), BoundaryError> {
        let child = self
            .state
            .lock()
            .unwrap_or_else(|p| p.into_inner())
            .view
            .child(call, request, route, 1)
            .and_then(|view| {
                view.with_phase(saddle_core::request_context::RequestViewPhase::Outbound)
            });
        match child {
            Ok(view) => {
                self.state.lock().unwrap_or_else(|p| p.into_inner()).view = view;
                Ok(())
            }
            Err(error) => {
                // This typed rejection exposes Debug, not Error/Display. Preserve
                // that original representation and explicitly do not invent a chain.
                #[derive(Debug)]
                struct Description<'a>(
                    &'a saddle_runtime::request_task::reserved::ReservedContextError,
                );
                impl std::fmt::Display for Description<'_> {
                    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                        write!(f, "{:?}", self.0)
                    }
                }
                let mut state = self.state.lock().unwrap_or_else(|p| p.into_inner());
                let diagnostic = BoundedDiagnostic::capture(
                    DiagnosticCategory::ExpectedRejection,
                    CaptureSite::FirstObserved,
                    BoundedDiagnosticCause::new(
                        DiagnosticStage::RequestOutbound,
                        code("transport.child_context_rejected"),
                    ),
                );
                state.failure = Some(state.view.source_description(
                    &Description(&error),
                    diagnostic,
                    code("transport.child_context_rejected"),
                    self.output,
                    RootRequestEvent::Outbound,
                    facts(OperationOutcome::Rejected),
                ));
                Err(BoundaryError::invalid_request(
                    "outbound diagnostic context rejected",
                ))
            }
        }
    }
}
impl TonicBoundary {
    pub async fn invoke_routed_reserved(
        template: &ProfuseContractAuthorityTemplate,
        request: InvokeRequest,
        attempt: &mut ReservedAttempt<'_>,
    ) -> Result<InvokeResponse, ReservedFailure<BoundaryFailure>> {
        {
            let mut state = attempt.state.lock().unwrap_or_else(|p| p.into_inner());
            if state.started {
                let receipt = state.view.source_description(
                    &"attempt owner reused",
                    BoundedDiagnostic::capture(
                        DiagnosticCategory::ExpectedRejection,
                        CaptureSite::FirstObserved,
                        BoundedDiagnosticCause::new(
                            DiagnosticStage::RequestOutbound,
                            code("transport.attempt_reused"),
                        ),
                    ),
                    code("transport.attempt_reused"),
                    attempt.output,
                    RootRequestEvent::Outbound,
                    facts(OperationOutcome::Rejected),
                );
                return Err(ReservedFailure {
                    error: BoundaryFailure {
                        code: crate::TechnicalCode::FunctionRequestInvalid,
                        certainty: crate::ExecutionCertainty::NotExecuted,
                    },
                    receipt,
                });
            }
            state.started = true;
        }
        let result =
            Self::invoke_routed_inner(template, request, attempt.output, Some(attempt)).await;
        let mut state = attempt.state.lock().unwrap_or_else(|p| p.into_inner());
        state.completed = true;
        result.map_err(|error| ReservedFailure {
            error: BoundaryFailure {
                code: error.code,
                certainty: error.certainty,
            },
            receipt: state
                .failure
                .take()
                .expect("every technical exit captures before mapping"),
        })
    }
}

/// State lives outside the write future. `begin_write` means a syscall/future
/// was actually started, not that the peer received anything.
pub struct ReservedDelivery<'a> {
    view: ReservedRequestView,
    output: Option<&'a EmergencyDiagnosticHandle>,
    written: u64,
    started: bool,
    complete: bool,
    failure: Option<ReservedFailure<crate::request_diagnostics::DeliveryReason>>,
}
#[must_use]
pub enum ReservedDeliveryOutcome {
    Complete(DiagnosticOutcomeAxes),
    Failed {
        axes: DiagnosticOutcomeAxes,
        failure: ReservedFailure<crate::request_diagnostics::DeliveryReason>,
    },
}
impl<'a> ReservedDelivery<'a> {
    pub fn new(view: ReservedRequestView, output: Option<&'a EmergencyDiagnosticHandle>) -> Self {
        Self {
            view,
            output,
            written: 0,
            started: false,
            complete: false,
            failure: None,
        }
    }
    pub fn begin_write(&mut self) -> bool {
        if self.complete || self.failure.is_some() {
            return false;
        }
        self.started = true;
        true
    }
    pub fn record_write(
        &mut self,
        result: std::io::Result<usize>,
    ) -> crate::request_diagnostics::WriteStep {
        use crate::request_diagnostics::WriteStep;
        if self.complete || self.failure.is_some() {
            return WriteStep::Stopped;
        }
        self.started = true;
        match result {
            Ok(n) if n > 0 => {
                self.written = self.written.saturating_add(n as u64);
                WriteStep::Progress
            }
            Ok(_) => {
                self.io_failure(&std::io::Error::from(std::io::ErrorKind::WriteZero));
                WriteStep::Stopped
            }
            Err(error) => {
                self.io_failure(&error);
                WriteStep::Stopped
            }
        }
    }
    pub fn local_write_complete(&mut self) {
        if self.failure.is_none() {
            self.complete = true;
        }
    }
    pub fn bytes_written(&self) -> u64 {
        self.written
    }
    #[track_caller]
    pub fn io_failure(&mut self, error: &std::io::Error) {
        if self.failure.is_some() {
            return;
        }
        let expected = matches!(
            error.kind(),
            std::io::ErrorKind::BrokenPipe
                | std::io::ErrorKind::ConnectionReset
                | std::io::ErrorKind::ConnectionAborted
                | std::io::ErrorKind::TimedOut
                | std::io::ErrorKind::UnexpectedEof
                | std::io::ErrorKind::Interrupted
                | std::io::ErrorKind::WouldBlock
                | std::io::ErrorKind::InvalidData
                | std::io::ErrorKind::InvalidInput
        );
        let diagnostic = BoundedDiagnostic::capture(
            if expected {
                DiagnosticCategory::ExpectedRejection
            } else {
                DiagnosticCategory::UnexpectedError
            },
            CaptureSite::FirstObserved,
            BoundedDiagnosticCause::new(
                DiagnosticStage::RequestResponse,
                code("transport.write_io"),
            )
            .with_system(
                crate::source_diagnostics::io_kind(error),
                error.raw_os_error(),
            ),
        );
        self.failure = Some(ReservedFailure {
            error: crate::request_diagnostics::DeliveryReason::Io(error.kind()),
            receipt: self.view.source_error_with_facts(
                error,
                diagnostic,
                code("transport.write_io"),
                self.output,
                RootRequestEvent::Response,
                facts(OperationOutcome::Failed),
            ),
        });
    }
    pub fn timed_out(&mut self) {
        self.stop(crate::request_diagnostics::DeliveryReason::Timeout);
    }
    pub fn cancelled(&mut self) {
        self.stop(crate::request_diagnostics::DeliveryReason::Cancelled);
    }
    #[track_caller]
    fn stop(&mut self, reason: crate::request_diagnostics::DeliveryReason) {
        if self.failure.is_some() {
            return;
        }
        let (text, operation) = match reason {
            crate::request_diagnostics::DeliveryReason::Timeout => {
                ("transport.delivery_timeout", OperationOutcome::TimedOut)
            }
            _ => ("transport.delivery_cancelled", OperationOutcome::Cancelled),
        };
        let diagnostic = BoundedDiagnostic::capture(
            DiagnosticCategory::ExpectedRejection,
            CaptureSite::FirstObserved,
            BoundedDiagnosticCause::new(DiagnosticStage::RequestResponse, code(text)),
        );
        self.failure = Some(ReservedFailure {
            error: reason,
            receipt: self.view.source_description(
                &text,
                diagnostic,
                code(text),
                self.output,
                RootRequestEvent::Response,
                facts(operation),
            ),
        });
    }
    /// Returns the original guarded credential without recording a second stage
    /// or finalization. S completes the stage then finalizes after actual cleanup.
    pub fn finish(mut self) -> ReservedDeliveryOutcome {
        if !self.complete && self.failure.is_none() {
            self.cancelled();
        }
        let delivery = if self.complete {
            saddle_core::ResponseDelivery::LocalWriteComplete
        } else if self.written > 0 {
            saddle_core::ResponseDelivery::Partial
        } else if self.started {
            saddle_core::ResponseDelivery::Unknown
        } else {
            saddle_core::ResponseDelivery::NotStarted
        };
        let mut axes = DiagnosticOutcomeAxes {
            delivery,
            bytes_written: Some(self.written),
            ..Default::default()
        };
        match self.failure {
            None => {
                axes.operation = OperationOutcome::Succeeded;
                ReservedDeliveryOutcome::Complete(axes)
            }
            Some(failure) => {
                axes.operation = match failure.error {
                    crate::request_diagnostics::DeliveryReason::Timeout => {
                        OperationOutcome::TimedOut
                    }
                    crate::request_diagnostics::DeliveryReason::Cancelled => {
                        OperationOutcome::Cancelled
                    }
                    _ => OperationOutcome::Failed,
                };
                ReservedDeliveryOutcome::Failed { axes, failure }
            }
        }
    }
}