| 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | |
| 3 | //! Whether a failed peer dispatch may be re-sent. |
| 4 | //! |
| 5 | //! A cell runs on exactly one node, so every other node forwards to the |
| 6 | //! owner. When that forward fails, celld must decide between two bad |
| 7 | //! options: fail the caller, or re-send and risk running the request twice. |
| 8 | //! The deciding fact is how far the attempt got. A connection that was never |
| 9 | //! established carried no request bytes, so the owner's cell is untouched and |
| 10 | //! a fresh attempt cannot double-apply. Every other failure — a timeout after |
| 11 | //! the request was written, a truncated body, a decode error — leaves the |
| 12 | //! outcome ambiguous: the owner may have run it and lost the reply. Re-sending |
| 13 | //! those would break at-most-once execution. |
| 14 | //! |
| 15 | //! The case this exists for is a burst of cold activations, where TCP |
| 16 | //! handshakes stall past the client's connect timeout. Those forwards never |
| 17 | //! reached the owner, so surfacing them to the caller is a self-inflicted |
| 18 | //! error. |
| 19 | |
| 20 | /// How far a dispatch attempt got before it failed. |
| 21 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 22 | pub enum Attempt { |
| 23 | /// The peer answered that it no longer owns the cell. Nothing ran. |
| 24 | NotOwner, |
| 25 | /// The connection was never established. No bytes reached the owner. |
| 26 | NeverConnected, |
| 27 | /// The request was on the wire when the attempt failed. The owner may or |
| 28 | /// may not have run it. |
| 29 | Ambiguous, |
| 30 | } |
| 31 | |
| 32 | /// Per-request redispatch state. Each recoverable failure class gets one retry, |
| 33 | /// counted separately so a route that is both stale and unreachable still |
| 34 | /// terminates. A connection retry costs a full connect timeout, so a second |
| 35 | /// retry would add the same latency when the owner is genuinely down. |
| 36 | #[derive(Debug, Default)] |
| 37 | pub struct Dispatcher { |
| 38 | retried_not_owner: bool, |
| 39 | retried_never_connected: bool, |
| 40 | } |
| 41 | |
| 42 | impl Dispatcher { |
| 43 | /// Record a failed attempt. Return `true` when the caller can safely |
| 44 | /// invalidate the failed route and dispatch the request again. |
| 45 | pub fn redispatch(&mut self, attempt: Attempt) -> bool { |
| 46 | match attempt { |
| 47 | Attempt::Ambiguous => false, |
| 48 | Attempt::NotOwner if self.retried_not_owner => false, |
| 49 | Attempt::NotOwner => { |
| 50 | self.retried_not_owner = true; |
| 51 | true |
| 52 | } |
| 53 | Attempt::NeverConnected if self.retried_never_connected => false, |
| 54 | Attempt::NeverConnected => { |
| 55 | self.retried_never_connected = true; |
| 56 | true |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 | } |