Skip to main content

taskfleet_core/reducer/
ask.rs

1//! Folds for a worker's blocking question to its parent (ADR 0004).
2//!
3//! Four told events, all node-scoped:
4//!
5//! - `node.asked` opens [`Node::open_ask`] with the question, the optional
6//!   options, the worker's default, its idempotency key, and a deadline fixed
7//!   once from the event timestamp plus `timeout_secs`;
8//! - `node.ask_escalated` marks the open question as passed on to a person and
9//!   can move the deadline later, never earlier;
10//! - `node.answered` and `node.ask_timed_out` close it into
11//!   [`Node::last_ask`].
12//!
13//! Every closing or escalating event names its question by `ask_id` (the seq of
14//! its `node.asked`), and only the open question with that id is affected, so
15//! the first closing event wins and a stale answer can never close a newer
16//! question. Whether an answer arrived before the deadline is decided by the
17//! command that appends it, under the run's exclusive lock; the fold itself is
18//! a pure function of the log. Payloads are validated before any
19//! state-dependent no-op so a malformed event never enters the durable log.
20//!
21//! A question also ends when its node does: a terminal status or report, a
22//! retry, the told worker exit, a round report, or a resumed round each close
23//! it as `cancelled` via [`cancel_open_ask`].
24
25use std::path::Path;
26
27use jiff::{SignedDuration, Timestamp};
28use serde_json::Value;
29
30use super::{require_envelope_node_id, ProjectionOp};
31use crate::error::{Error, Result};
32use crate::paths::RunPaths;
33use crate::projections::read_node_opt;
34use crate::schema::{AskOutcome, ClosedAsk, Event, Node, OpenAsk};
35
36/// Largest accepted question, in bytes.
37pub const MAX_ASK_QUESTION_BYTES: usize = 8 * 1024;
38/// Largest accepted default, in bytes.
39pub const MAX_ASK_DEFAULT_BYTES: usize = 4 * 1024;
40/// Largest accepted free-text answer, in bytes.
41pub const MAX_ASK_ANSWER_BYTES: usize = 16 * 1024;
42/// Largest accepted escalation note, in bytes.
43pub const MAX_ASK_NOTE_BYTES: usize = 2 * 1024;
44/// Most options one question may carry.
45pub const MAX_ASK_OPTIONS: usize = 16;
46/// Longest option, in characters.
47pub const MAX_ASK_OPTION_CHARS: usize = 256;
48/// Longest idempotency key, in characters.
49pub const MAX_ASK_KEY_CHARS: usize = 128;
50/// Longest deadline a question may set or an escalation may extend by.
51pub const MAX_ASK_TIMEOUT_SECS: u64 = 7 * 24 * 3600;
52
53fn corrupt(events_path: &Path, ev: &Event, what: &str) -> Error {
54    Error::CorruptEventLog {
55        path: events_path.to_path_buf(),
56        reason: format!("event seq={} kind={} {what}", ev.seq, ev.kind),
57    }
58}
59
60/// True for nonblank text without NUL of at most `max` bytes.
61#[must_use]
62pub fn valid_ask_text(s: &str, max: usize) -> bool {
63    !s.trim().is_empty() && s.len() <= max && !s.contains('\0')
64}
65
66/// True for a 1..=128 character key of visible ASCII.
67#[must_use]
68pub fn valid_ask_key(s: &str) -> bool {
69    !s.is_empty() && s.len() <= MAX_ASK_KEY_CHARS && s.bytes().all(|b| b.is_ascii_graphic())
70}
71
72/// True for a nonblank option without control characters, at most
73/// [`MAX_ASK_OPTION_CHARS`] long.
74#[must_use]
75pub fn valid_ask_option(s: &str) -> bool {
76    !s.trim().is_empty()
77        && s.chars().count() <= MAX_ASK_OPTION_CHARS
78        && !s.chars().any(char::is_control)
79}
80
81fn str_field<'a>(ev: &'a Event, key: &str) -> Option<&'a str> {
82    ev.data.get(key).and_then(Value::as_str)
83}
84
85fn ask_id(events_path: &Path, ev: &Event) -> Result<u64> {
86    ev.data
87        .get("ask_id")
88        .and_then(Value::as_u64)
89        .ok_or_else(|| corrupt(events_path, ev, "requires unsigned `ask_id`"))
90}
91
92fn secs(events_path: &Path, ev: &Event, key: &str) -> Result<Option<u64>> {
93    match ev.data.get(key) {
94        None | Some(Value::Null) => Ok(None),
95        Some(v) => v
96            .as_u64()
97            .filter(|s| (1..=MAX_ASK_TIMEOUT_SECS).contains(s))
98            .map(Some)
99            .ok_or_else(|| {
100                corrupt(
101                    events_path,
102                    ev,
103                    &format!("requires `{key}` in 1..={MAX_ASK_TIMEOUT_SECS}"),
104                )
105            }),
106    }
107}
108
109/// `at + secs`, saturating at the end of the representable range. Validated
110/// inputs are bounded by `MAX_ASK_TIMEOUT_SECS`; saturation only keeps a
111/// corrupt event value from panicking the reducer.
112fn deadline(at: Timestamp, secs: u64) -> Timestamp {
113    let secs = i64::try_from(secs).unwrap_or(i64::MAX);
114    at.checked_add(SignedDuration::from_secs(secs))
115        .unwrap_or(Timestamp::MAX)
116}
117
118/// Close the open question, if any, as `cancelled` because its node ended.
119/// Called next to every place the reducer ends a node or its worker attempt.
120pub(super) fn cancel_open_ask(n: &mut Node, ev: &Event) {
121    if let Some(open) = n.open_ask.take() {
122        n.last_ask = Some(Box::new(ClosedAsk {
123            ask: *open,
124            outcome: AskOutcome::Cancelled,
125            closed_at: ev.ts,
126            closed_seq: ev.seq,
127            answer: None,
128            choice: None,
129            decided_by: None,
130            cancel_reason: Some(ev.kind.clone()),
131        }));
132    }
133}
134
135pub(super) fn reduce_node_asked(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
136    let events_path = paths.events();
137    let node_id = require_envelope_node_id(&events_path, ev)?;
138    let attempt = ev
139        .data
140        .get("attempt")
141        .and_then(Value::as_u64)
142        .and_then(|a| u32::try_from(a).ok())
143        .ok_or_else(|| corrupt(&events_path, ev, "requires unsigned `attempt`"))?;
144    let question = str_field(ev, "question")
145        .filter(|q| valid_ask_text(q, MAX_ASK_QUESTION_BYTES))
146        .ok_or_else(|| {
147            corrupt(
148                &events_path,
149                ev,
150                &format!("requires nonblank `question` of at most {MAX_ASK_QUESTION_BYTES} bytes"),
151            )
152        })?;
153    let default = str_field(ev, "default")
154        .filter(|d| valid_ask_text(d, MAX_ASK_DEFAULT_BYTES))
155        .ok_or_else(|| {
156            corrupt(
157                &events_path,
158                ev,
159                &format!("requires nonblank `default` of at most {MAX_ASK_DEFAULT_BYTES} bytes"),
160            )
161        })?;
162    let key = str_field(ev, "idempotency_key")
163        .filter(|k| valid_ask_key(k))
164        .ok_or_else(|| {
165            corrupt(
166                &events_path,
167                ev,
168                "requires an `idempotency_key` of 1..=128 visible ASCII characters",
169            )
170        })?;
171    let timeout = secs(&events_path, ev, "timeout_secs")?
172        .ok_or_else(|| corrupt(&events_path, ev, "requires `timeout_secs`"))?;
173    let options: Vec<String> = match ev.data.get("options") {
174        None | Some(Value::Null) => Vec::new(),
175        Some(Value::Array(values)) => {
176            let opts: Option<Vec<String>> = values
177                .iter()
178                .map(|v| {
179                    v.as_str()
180                        .filter(|s| valid_ask_option(s))
181                        .map(str::to_string)
182                })
183                .collect();
184            let opts = opts
185                .filter(|o| o.len() <= MAX_ASK_OPTIONS)
186                .filter(|o| {
187                    let mut seen = std::collections::HashSet::new();
188                    o.iter().all(|s| seen.insert(s.as_str()))
189                })
190                .ok_or_else(|| {
191                    corrupt(
192                        &events_path,
193                        ev,
194                        &format!(
195                            "requires at most {MAX_ASK_OPTIONS} distinct nonblank `options` of at most {MAX_ASK_OPTION_CHARS} characters"
196                        ),
197                    )
198                })?;
199            opts
200        }
201        Some(_) => return Err(corrupt(&events_path, ev, "`options` must be an array")),
202    };
203
204    let Some(mut n) = read_node_opt(paths, &node_id)? else {
205        return Ok(vec![]);
206    };
207    // One open question per node, from the live current attempt only. The
208    // command refuses these cases before appending; the fold stays first-wins.
209    if n.status.is_terminal()
210        || n.worker_exit.is_some()
211        || n.retry_attempts != attempt
212        || n.open_ask.is_some()
213    {
214        return Ok(vec![]);
215    }
216    n.open_ask = Some(Box::new(OpenAsk {
217        ask_id: ev.seq,
218        attempt,
219        question: question.to_string(),
220        options,
221        default: default.to_string(),
222        idempotency_key: key.to_string(),
223        asked_at: ev.ts,
224        expires_at: deadline(ev.ts, timeout),
225        escalated_at: None,
226        escalation_note: None,
227    }));
228    n.updated_at = ev.ts;
229    Ok(vec![ProjectionOp::Node(n)])
230}
231
232pub(super) fn reduce_node_ask_escalated(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
233    let events_path = paths.events();
234    let node_id = require_envelope_node_id(&events_path, ev)?;
235    let id = ask_id(&events_path, ev)?;
236    let extend = secs(&events_path, ev, "extend_secs")?;
237    let note = match ev.data.get("note") {
238        None | Some(Value::Null) => None,
239        Some(v) => Some(
240            v.as_str()
241                .filter(|s| valid_ask_text(s, MAX_ASK_NOTE_BYTES))
242                .ok_or_else(|| {
243                    corrupt(
244                        &events_path,
245                        ev,
246                        &format!(
247                            "`note` must be nonblank text of at most {MAX_ASK_NOTE_BYTES} bytes"
248                        ),
249                    )
250                })?
251                .to_string(),
252        ),
253    };
254    let Some(mut n) = read_node_opt(paths, &node_id)? else {
255        return Ok(vec![]);
256    };
257    let Some(open) = n.open_ask.as_mut().filter(|o| o.ask_id == id) else {
258        return Ok(vec![]);
259    };
260    open.escalated_at.get_or_insert(ev.ts);
261    if note.is_some() {
262        open.escalation_note = note;
263    }
264    if let Some(extend) = extend {
265        open.expires_at = open.expires_at.max(deadline(ev.ts, extend));
266    }
267    n.updated_at = ev.ts;
268    Ok(vec![ProjectionOp::Node(n)])
269}
270
271pub(super) fn reduce_node_answered(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
272    let events_path = paths.events();
273    let node_id = require_envelope_node_id(&events_path, ev)?;
274    let id = ask_id(&events_path, ev)?;
275    // Absent and wrong-typed are different: a present non-string field is
276    // malformed, never "not given".
277    let typed = |k: &str| match ev.data.get(k) {
278        None | Some(Value::Null) => Ok(None),
279        Some(Value::String(v)) => Ok(Some(v.as_str())),
280        Some(_) => Err(corrupt(
281            &events_path,
282            ev,
283            &format!("`{k}` must be a string"),
284        )),
285    };
286    let answer = typed("answer")?;
287    let choice = typed("choice")?;
288    let shape_ok = match (answer, choice) {
289        (Some(a), None) => valid_ask_text(a, MAX_ASK_ANSWER_BYTES),
290        (None, Some(c)) => valid_ask_option(c),
291        _ => false,
292    };
293    if !shape_ok {
294        return Err(corrupt(
295            &events_path,
296            ev,
297            &format!(
298                "requires exactly one of nonblank `answer` (at most {MAX_ASK_ANSWER_BYTES} bytes) or `choice`"
299            ),
300        ));
301    }
302    let decided_by = str_field(ev, "decided_by")
303        .filter(|d| matches!(*d, "agent" | "person"))
304        .ok_or_else(|| corrupt(&events_path, ev, "requires `decided_by` agent|person"))?;
305    let Some(mut n) = read_node_opt(paths, &node_id)? else {
306        return Ok(vec![]);
307    };
308    let Some(open) = n.open_ask.take_if(|o| o.ask_id == id) else {
309        return Ok(vec![]);
310    };
311    if let Some(c) = choice {
312        if !open.options.iter().any(|o| o == c) {
313            return Err(corrupt(
314                &events_path,
315                ev,
316                &format!("`choice` {c:?} is not an option of ask {id}"),
317            ));
318        }
319    }
320    n.last_ask = Some(Box::new(ClosedAsk {
321        ask: *open,
322        outcome: AskOutcome::Answered,
323        closed_at: ev.ts,
324        closed_seq: ev.seq,
325        answer: answer.map(str::to_string),
326        choice: choice.map(str::to_string),
327        decided_by: Some(decided_by.to_string()),
328        cancel_reason: None,
329    }));
330    n.updated_at = ev.ts;
331    Ok(vec![ProjectionOp::Node(n)])
332}
333
334pub(super) fn reduce_node_ask_timed_out(paths: &RunPaths, ev: &Event) -> Result<Vec<ProjectionOp>> {
335    let events_path = paths.events();
336    let node_id = require_envelope_node_id(&events_path, ev)?;
337    let id = ask_id(&events_path, ev)?;
338    let Some(mut n) = read_node_opt(paths, &node_id)? else {
339        return Ok(vec![]);
340    };
341    let Some(open) = n.open_ask.take_if(|o| o.ask_id == id) else {
342        return Ok(vec![]);
343    };
344    n.last_ask = Some(Box::new(ClosedAsk {
345        ask: *open,
346        outcome: AskOutcome::TimedOut,
347        closed_at: ev.ts,
348        closed_seq: ev.seq,
349        answer: None,
350        choice: None,
351        decided_by: None,
352        cancel_reason: None,
353    }));
354    n.updated_at = ev.ts;
355    Ok(vec![ProjectionOp::Node(n)])
356}