pipecircuit 0.0.19

Correct. Robust. Fast. Portable. Pick four.
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
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
#[cfg(feature = "storage")]
mod ledger;

use core::{
    cmp::Ordering,
    fmt,
    hash::{Hash, Hasher},
    marker::PhantomData,
    num::NonZeroU64,
};

use crate::{
    Pipe, StateMachine, StepInputOf, TimerArmDecision, TimerArmOutcome, TimerCancellationDecision,
    TimerCancellationOutcome, TimerIn, TimerToken, WakeAfter,
};

#[cfg(feature = "storage")]
pub use ledger::{
    ContinuationAdmissionOutcome, ContinuationExpiration, ContinuationExpirationOutcome,
    ContinuationLedger, ContinuationLedgerCreationError, ContinuationLedgerCreationFailure,
    ContinuationRefusalOutcome, ContinuationResolutionOutcome, ContinuationRetractionOutcome,
};

pub type TimeoutAfter = WakeAfter;

pub struct Continued<Worker>(PhantomData<fn() -> Worker>);

impl<Worker> Pipe for Continued<Worker>
where
    Worker: Pipe,
{
    type In<'message> = Owed<Worker::In<'message>>;
    type Out<'message> = ContinuationResult<'message, Worker>;
}

#[must_use = "owed work must be sent through a continued pipe"]
pub struct Owed<Work> {
    work: Work,
    timeout_after: TimeoutAfter,
}

impl<Work> Owed<Work> {
    pub const fn new(work: Work, timeout_after: TimeoutAfter) -> Self {
        Self {
            work,
            timeout_after,
        }
    }

    pub const fn work(&self) -> &Work {
        &self.work
    }

    pub const fn timeout_after(&self) -> TimeoutAfter {
        self.timeout_after
    }

    fn into_parts(self) -> (Work, TimeoutAfter) {
        (self.work, self.timeout_after)
    }
}

impl Owed<()> {
    pub const fn wait(timeout_after: TimeoutAfter) -> Self {
        Self::new((), timeout_after)
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ContinuationUnavailable {
    AtCapacity { maximum_pending: u32 },
    IdentifiersExhausted,
    TimerRefused { reason: crate::TimerArmRefusal },
}

#[must_use = "continuation failures must be handled"]
pub enum ContinuationFailure<Work> {
    Expired,
    Unavailable {
        reason: ContinuationUnavailable,
        rejected: Owed<Work>,
    },
}

pub type ContinuationResult<'message, Worker> =
    Result<<Worker as Pipe>::Out<'message>, ContinuationFailure<<Worker as Pipe>::In<'message>>>;

pub struct ContinuationId<Worker> {
    value: NonZeroU64,
    worker: PhantomData<fn() -> Worker>,
}

impl<Worker> ContinuationId<Worker> {
    #[cfg(feature = "storage")]
    const fn new(value: NonZeroU64) -> Self {
        Self {
            value,
            worker: PhantomData,
        }
    }

    pub const fn value(self) -> NonZeroU64 {
        self.value
    }

    const fn timer_token(self) -> TimerToken {
        TimerToken::from_nonzero(self.value)
    }
}

impl<Worker> Clone for ContinuationId<Worker> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<Worker> Copy for ContinuationId<Worker> {}

impl<Worker> fmt::Debug for ContinuationId<Worker> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.value.fmt(formatter)
    }
}

impl<Worker> PartialEq for ContinuationId<Worker> {
    fn eq(&self, other: &Self) -> bool {
        self.value == other.value
    }
}

impl<Worker> Eq for ContinuationId<Worker> {}

impl<Worker> PartialOrd for ContinuationId<Worker> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl<Worker> Ord for ContinuationId<Worker> {
    fn cmp(&self, other: &Self) -> Ordering {
        self.value.cmp(&other.value)
    }
}

impl<Worker> Hash for ContinuationId<Worker> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.value.hash(state);
    }
}

#[must_use = "admitted continuations must be armed before their work is released"]
pub struct ContinuationAdmission<'message, Worker>
where
    Worker: Pipe,
{
    id: ContinuationId<Worker>,
    owed: Owed<Worker::In<'message>>,
}

impl<'message, Worker> ContinuationAdmission<'message, Worker>
where
    Worker: Pipe,
{
    pub const fn id(&self) -> ContinuationId<Worker> {
        self.id
    }

    pub const fn timeout_after(&self) -> TimeoutAfter {
        self.owed.timeout_after()
    }

    pub const fn timer_token(&self) -> TimerToken {
        self.id.timer_token()
    }

    pub const fn timer_input(&self) -> TimerIn<TimerToken> {
        TimerIn::Arm {
            token: self.timer_token(),
            after: self.timeout_after(),
        }
    }

    pub fn settle_timer_arm(
        self,
        outcome: TimerArmOutcome<TimerToken>,
    ) -> Result<ContinuationArmOutcome<'message, Worker>, ContinuationArmMismatch<'message, Worker>>
    {
        let decision = outcome.into_decision();
        let returned_token = match decision {
            TimerArmDecision::Armed { token } | TimerArmDecision::Refused { token, .. } => token,
        };
        if returned_token != self.timer_token() {
            return Err(ContinuationArmMismatch {
                admission: self,
                decision,
            });
        }
        match decision {
            TimerArmDecision::Armed { .. } => Ok(ContinuationArmOutcome::Armed {
                work: ContinuationWork {
                    id: self.id,
                    owed: self.owed,
                },
            }),
            TimerArmDecision::Refused { reason, .. } => Ok(ContinuationArmOutcome::Refused {
                refusal: ContinuationArmRefusal {
                    id: self.id,
                    reason,
                    owed: self.owed,
                },
            }),
        }
    }
}

#[must_use = "armed work or exact timer refusal must be handled by the fitting"]
pub enum ContinuationArmOutcome<'message, Worker>
where
    Worker: Pipe,
{
    Armed {
        work: ContinuationWork<'message, Worker>,
    },
    Refused {
        refusal: ContinuationArmRefusal<'message, Worker>,
    },
}

pub struct ContinuationArmMismatch<'message, Worker>
where
    Worker: Pipe,
{
    admission: ContinuationAdmission<'message, Worker>,
    decision: TimerArmDecision<TimerToken>,
}

impl<'message, Worker> ContinuationArmMismatch<'message, Worker>
where
    Worker: Pipe,
{
    pub fn into_parts(
        self,
    ) -> (
        ContinuationAdmission<'message, Worker>,
        TimerArmDecision<TimerToken>,
    ) {
        (self.admission, self.decision)
    }
}

#[must_use = "timer refusal must be returned to the continuation ledger"]
pub struct ContinuationArmRefusal<'message, Worker>
where
    Worker: Pipe,
{
    id: ContinuationId<Worker>,
    reason: crate::TimerArmRefusal,
    owed: Owed<Worker::In<'message>>,
}

impl<'message, Worker> ContinuationArmRefusal<'message, Worker>
where
    Worker: Pipe,
{
    pub const fn id(&self) -> ContinuationId<Worker> {
        self.id
    }

    pub const fn reason(&self) -> crate::TimerArmRefusal {
        self.reason
    }

    pub fn into_owed(self) -> Owed<Worker::In<'message>> {
        self.owed
    }
}

#[must_use = "continuation work must be carried by the selected fitting"]
pub struct ContinuationWork<'message, Worker>
where
    Worker: Pipe,
{
    id: ContinuationId<Worker>,
    owed: Owed<Worker::In<'message>>,
}

impl<'message, Worker> ContinuationWork<'message, Worker>
where
    Worker: Pipe,
{
    pub const fn id(&self) -> ContinuationId<Worker> {
        self.id
    }

    pub const fn input(&self) -> &Worker::In<'message> {
        self.owed.work()
    }

    pub const fn timeout_after(&self) -> TimeoutAfter {
        self.owed.timeout_after()
    }

    pub const fn timer_token(&self) -> TimerToken {
        self.id.timer_token()
    }

    pub const fn timer_input(&self) -> TimerIn<TimerToken> {
        TimerIn::Cancel {
            token: self.timer_token(),
        }
    }

    pub fn settle_timer_cancellation(
        self,
        outcome: TimerCancellationOutcome<TimerToken>,
    ) -> Result<
        ContinuationWorkCancellationOutcome<'message, Worker>,
        ContinuationWorkCancellationMismatch<'message, Worker>,
    > {
        let decision = outcome.into_decision();
        let returned_token = match decision {
            TimerCancellationDecision::Cancelled { token }
            | TimerCancellationDecision::Refused { token, .. } => token,
        };
        if returned_token != self.timer_token() {
            return Err(ContinuationWorkCancellationMismatch {
                work: self,
                decision,
            });
        }
        match decision {
            TimerCancellationDecision::Cancelled { .. } => {
                Ok(ContinuationWorkCancellationOutcome::Cancelled {
                    work: CancelledContinuationWork(self),
                })
            }
            TimerCancellationDecision::Refused { .. } => {
                Ok(ContinuationWorkCancellationOutcome::Stale { work: self })
            }
        }
    }

    /// Consume the input now and retain its move-only reply obligation across
    /// steps. Beginning work relinquishes the ability to retract it as unstarted.
    pub fn begin(self) -> (Worker::In<'message>, ContinuationReply<'message, Worker>) {
        let (input, _started_timeout) = self.owed.into_parts();
        (
            input,
            ContinuationReply {
                id: self.id,
                output: PhantomData,
            },
        )
    }

    pub fn fulfill(
        self,
        output: Worker::Out<'message>,
    ) -> ContinuationCompletion<'message, Worker> {
        let (_input, reply) = self.begin();
        reply.fulfill(output)
    }

    pub fn fulfill_with(
        self,
        fulfill: impl FnOnce(Worker::In<'message>) -> Worker::Out<'message>,
    ) -> ContinuationCompletion<'message, Worker> {
        let (input, reply) = self.begin();
        reply.fulfill(fulfill(input))
    }
}

/// The one reply still owed after a worker consumes its input. Expiry at the
/// requester does not cancel the worker's effects; its eventual completion is
/// classified by the original ledger and deadline.
#[must_use = "started work retains its reply obligation until completion"]
pub struct ContinuationReply<'message, Worker: Pipe> {
    id: ContinuationId<Worker>,
    output: PhantomData<fn() -> Worker::Out<'message>>,
}

impl<'message, Worker: Pipe> ContinuationReply<'message, Worker> {
    pub fn fulfill(
        self,
        output: Worker::Out<'message>,
    ) -> ContinuationCompletion<'message, Worker> {
        ContinuationCompletion {
            id: self.id,
            output,
        }
    }
}

#[must_use = "cancelled or stale unstarted work must be handled by the fitting"]
pub enum ContinuationWorkCancellationOutcome<'message, Worker>
where
    Worker: Pipe,
{
    Cancelled {
        work: CancelledContinuationWork<'message, Worker>,
    },
    Stale {
        work: ContinuationWork<'message, Worker>,
    },
}

pub struct ContinuationWorkCancellationMismatch<'message, Worker>
where
    Worker: Pipe,
{
    work: ContinuationWork<'message, Worker>,
    decision: TimerCancellationDecision<TimerToken>,
}

impl<'message, Worker> ContinuationWorkCancellationMismatch<'message, Worker>
where
    Worker: Pipe,
{
    pub fn into_parts(
        self,
    ) -> (
        ContinuationWork<'message, Worker>,
        TimerCancellationDecision<TimerToken>,
    ) {
        (self.work, self.decision)
    }
}

#[must_use = "cancelled unstarted work must be retracted through its ledger"]
pub struct CancelledContinuationWork<'message, Worker>(ContinuationWork<'message, Worker>)
where
    Worker: Pipe;

impl<'message, Worker> CancelledContinuationWork<'message, Worker>
where
    Worker: Pipe,
{
    pub const fn id(&self) -> ContinuationId<Worker> {
        self.0.id()
    }

    pub const fn owed(&self) -> &Owed<Worker::In<'message>> {
        &self.0.owed
    }
}

impl<'message, Worker> StepInputOf<Worker> for ContinuationWork<'message, Worker>
where
    Worker: StateMachine + Pipe,
    Worker::In<'message>: StepInputOf<Worker, Outcome = Worker::Out<'message>>,
{
    type Outcome = ContinuationCompletion<'message, Worker>;

    fn step(self, worker: &mut Worker) -> Self::Outcome {
        self.fulfill_with(|input| worker.step(input))
    }
}

#[must_use = "continuation completions must be settled by the fitting"]
pub struct ContinuationCompletion<'message, Worker>
where
    Worker: Pipe,
{
    id: ContinuationId<Worker>,
    output: Worker::Out<'message>,
}

impl<'message, Worker> ContinuationCompletion<'message, Worker>
where
    Worker: Pipe,
{
    pub const fn id(&self) -> ContinuationId<Worker> {
        self.id
    }

    pub const fn output(&self) -> &Worker::Out<'message> {
        &self.output
    }

    pub const fn timer_token(&self) -> TimerToken {
        self.id.timer_token()
    }

    pub const fn timer_input(&self) -> TimerIn<TimerToken> {
        TimerIn::Cancel {
            token: self.timer_token(),
        }
    }

    pub fn settle_timer_cancellation(
        self,
        outcome: TimerCancellationOutcome<TimerToken>,
    ) -> Result<
        ContinuationCancellationOutcome<'message, Worker>,
        ContinuationCancellationMismatch<'message, Worker>,
    > {
        let decision = outcome.into_decision();
        let returned_token = match decision {
            TimerCancellationDecision::Cancelled { token }
            | TimerCancellationDecision::Refused { token, .. } => token,
        };
        if returned_token != self.timer_token() {
            return Err(ContinuationCancellationMismatch {
                completion: self,
                decision,
            });
        }
        match decision {
            TimerCancellationDecision::Cancelled { .. } => {
                Ok(ContinuationCancellationOutcome::Cancelled {
                    completion: CancelledContinuationCompletion(self),
                })
            }
            TimerCancellationDecision::Refused { .. } => {
                Ok(ContinuationCancellationOutcome::Stale { completion: self })
            }
        }
    }
}

#[must_use = "cancelled or stale completion must be handled by the fitting"]
pub enum ContinuationCancellationOutcome<'message, Worker>
where
    Worker: Pipe,
{
    Cancelled {
        completion: CancelledContinuationCompletion<'message, Worker>,
    },
    Stale {
        completion: ContinuationCompletion<'message, Worker>,
    },
}

pub struct ContinuationCancellationMismatch<'message, Worker>
where
    Worker: Pipe,
{
    completion: ContinuationCompletion<'message, Worker>,
    decision: TimerCancellationDecision<TimerToken>,
}

impl<'message, Worker> ContinuationCancellationMismatch<'message, Worker>
where
    Worker: Pipe,
{
    pub fn into_parts(
        self,
    ) -> (
        ContinuationCompletion<'message, Worker>,
        TimerCancellationDecision<TimerToken>,
    ) {
        (self.completion, self.decision)
    }
}

#[must_use = "cancelled completions must be resolved through the continuation ledger"]
pub struct CancelledContinuationCompletion<'message, Worker>(
    ContinuationCompletion<'message, Worker>,
)
where
    Worker: Pipe;

#[cfg(all(kani, feature = "storage"))]
mod proofs;
#[cfg(test)]
mod tests;

#[cfg(all(test, feature = "storage"))]
mod retraction_tests;

#[cfg(all(test, feature = "storage"))]
mod deferred_tests;