Skip to main content

muse_code_sdk/
pending.rs

1//! Locally pending command bookkeeping.
2//!
3//! Indexed lookup is expected O(1), ordered insert/retirement is O(log n),
4//! and transport death visits each currently pending command once.
5
6use std::collections::hash_map::Entry;
7use std::collections::{BTreeMap, HashMap};
8
9use crate::errors::MspError;
10use crate::msp::{CommandAcceptedResult, CommandAckStatus, ErrorKind};
11
12/// Whether a call to [`PendingCommandSet::submit`] should reach the transport.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14#[non_exhaustive]
15pub enum Submission {
16    /// A new command id and effect.
17    New,
18    /// The first same-id retry after the transport died.
19    Retry,
20    /// The command is already pending and no retry is due.
21    Duplicate,
22    /// The command id is already bound to different input.
23    Conflict,
24}
25
26/// A fact that retired a pending entry.
27#[derive(Debug, Clone, PartialEq, Eq)]
28#[non_exhaustive]
29pub enum PendingSettlement<I> {
30    /// The server acknowledged the command.
31    Acknowledged {
32        /// The command's id.
33        command_id: String,
34        /// The input the command was submitted with.
35        input: I,
36        /// The acknowledgement status the server returned.
37        status: CommandAckStatus,
38    },
39    /// The server durably rejected the command (`commandRejected`).
40    Refused {
41        /// The command's id.
42        command_id: String,
43        /// The input the command was submitted with.
44        input: I,
45        /// The server's reason, when it gave one.
46        reason: Option<String>,
47    },
48    /// Local cancellation or drop won before a server terminal was observed.
49    Discarded {
50        /// The command's id.
51        command_id: String,
52        /// The input the command was submitted with.
53        input: I,
54    },
55}
56
57/// An immutable view of one pending command.
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct PendingCommand<I> {
60    command_id: String,
61    input: I,
62    submission_index: u64,
63    retry_ready: bool,
64}
65
66impl<I> PendingCommand<I> {
67    /// The command's id.
68    #[must_use]
69    pub fn command_id(&self) -> &str {
70        &self.command_id
71    }
72
73    /// The input the command was first submitted with.
74    #[must_use]
75    pub const fn input(&self) -> &I {
76        &self.input
77    }
78
79    /// The command's submission number in this set: counted up from 0 and
80    /// never reused, so it orders commands by first submission.
81    #[must_use]
82    pub const fn submission_index(&self) -> u64 {
83        self.submission_index
84    }
85
86    /// Whether the transport died since the last send, so the next identical
87    /// [`PendingCommandSet::submit`] is a [`Submission::Retry`].
88    #[must_use]
89    pub const fn retry_ready(&self) -> bool {
90        self.retry_ready
91    }
92}
93
94/// Client-local commands that have no server-authored settlement yet.
95#[derive(Debug)]
96pub struct PendingCommandSet<I> {
97    entries: HashMap<String, PendingCommand<I>>,
98    order: BTreeMap<u64, String>,
99    next_submission_index: u64,
100}
101
102impl<I> Default for PendingCommandSet<I> {
103    fn default() -> Self {
104        Self {
105            entries: HashMap::new(),
106            order: BTreeMap::new(),
107            next_submission_index: 0,
108        }
109    }
110}
111
112impl<I> PendingCommandSet<I> {
113    /// An empty set.
114    #[must_use]
115    pub fn new() -> Self {
116        Self::default()
117    }
118
119    /// The pending command with this id, if any.
120    #[must_use]
121    pub fn get(&self, command_id: &str) -> Option<&PendingCommand<I>> {
122        self.entries.get(command_id)
123    }
124
125    /// How many commands are pending.
126    #[must_use]
127    pub fn len(&self) -> usize {
128        self.entries.len()
129    }
130
131    /// Whether no command is pending.
132    #[must_use]
133    pub fn is_empty(&self) -> bool {
134        self.entries.is_empty()
135    }
136
137    /// Pending entries in first-submission order.
138    pub fn iter(&self) -> impl Iterator<Item = &PendingCommand<I>> {
139        self.order
140            .values()
141            .filter_map(|command_id| self.entries.get(command_id))
142    }
143
144    /// An ACK is a server-authored settlement and retires the matching entry.
145    pub fn acknowledge(&mut self, ack: &CommandAcceptedResult) -> Option<PendingSettlement<I>> {
146        let entry = self.take(&ack.command_id)?;
147        Some(PendingSettlement::Acknowledged {
148            command_id: entry.command_id,
149            input: entry.input,
150            status: ack.status,
151        })
152    }
153
154    /// A durable `commandRejected` retires the exact command named in data.
155    /// Takes the `MspError` callers hold: the copy's `ErrorObject` is
156    /// `#[non_exhaustive]` and never reaches them.
157    pub fn refuse(&mut self, error: &MspError) -> Option<PendingSettlement<I>> {
158        let data = error.data();
159        if data.kind != ErrorKind::CommandRejected {
160            return None;
161        }
162        let command_id = data.command_id.as_deref()?;
163        let entry = self.take(command_id)?;
164        Some(PendingSettlement::Refused {
165            command_id: entry.command_id,
166            input: entry.input,
167            reason: data.reason.clone(),
168        })
169    }
170
171    /// Local cancellation or drop settles and retires the matching command.
172    pub fn discard(&mut self, command_id: &str) -> Option<PendingSettlement<I>> {
173        let entry = self.take(command_id)?;
174        Some(PendingSettlement::Discarded {
175            command_id: entry.command_id,
176            input: entry.input,
177        })
178    }
179
180    /// A server turn terminal retires pending intent without inventing a
181    /// second pending-layer outcome.
182    pub fn retire_server_terminal(&mut self, command_id: &str) -> bool {
183        self.take(command_id).is_some()
184    }
185
186    /// Transport death is not a durable outcome: retain every entry and make
187    /// exactly one same-id retry eligible on the next connection.
188    pub fn transport_died(&mut self) {
189        for entry in self.entries.values_mut() {
190            entry.retry_ready = true;
191        }
192    }
193
194    fn take(&mut self, command_id: &str) -> Option<PendingCommand<I>> {
195        let entry = self.entries.remove(command_id)?;
196        self.order.remove(&entry.submission_index);
197        Some(entry)
198    }
199}
200
201impl<I: PartialEq> PendingCommandSet<I> {
202    /// Register a transport submission.
203    ///
204    /// An existing id never inserts a second entry. After transport death the
205    /// first identical call returns [`Submission::Retry`]; another call is a
206    /// duplicate until a later death makes one new retry eligible.
207    pub fn submit(&mut self, command_id: impl Into<String>, input: I) -> Submission {
208        let command_id = command_id.into();
209        match self.entries.entry(command_id.clone()) {
210            Entry::Vacant(slot) => {
211                let submission_index = self.next_submission_index;
212                slot.insert(PendingCommand {
213                    command_id: command_id.clone(),
214                    input,
215                    submission_index,
216                    retry_ready: false,
217                });
218                self.next_submission_index += 1;
219                self.order.insert(submission_index, command_id);
220                Submission::New
221            }
222            Entry::Occupied(slot) if slot.get().input != input => Submission::Conflict,
223            Entry::Occupied(mut slot) if slot.get().retry_ready => {
224                slot.get_mut().retry_ready = false;
225                Submission::Retry
226            }
227            Entry::Occupied(_) => Submission::Duplicate,
228        }
229    }
230}