use crate::net::wire; use std::time::{Duration, Instant}; const REQUEST_TIMEOUT: Duration = Duration::from_secs(20); struct Pending { request: wire::ForumRequest, started: Instant, } /// View state belongs to one authenticated node session; mutations stay drafts until ACK. #[derive(Default)] pub struct ForumState { pub supported: bool, pub channel_id: Option, pub joined: bool, pub topics: Vec, pub posts: Vec, pub topic_id: Option, pub creating: bool, pub title_draft: String, pub body_draft: String, pub reply_draft: String, pub error: String, pub topics_offset: Option, pub posts_offset: Option, pub waiting_join: Option, topic_draft_id: Option, first_message_id: Option, reply_message_id: Option, pending: Option, } impl ForumState { pub fn suspend(&mut self) { self.supported = false; self.joined = false; self.pending = None; self.waiting_join = None; } pub fn with_support(supported: bool) -> Self { Self { supported, ..Default::default() } } pub fn edit_title(&mut self, value: String) { if !self.busy() && self.title_draft != value { self.title_draft = value; self.topic_draft_id = None; self.first_message_id = None; } } pub fn edit_body(&mut self, value: String) { if !self.busy() && self.body_draft != value { self.body_draft = value; self.topic_draft_id = None; self.first_message_id = None; } } pub fn edit_reply(&mut self, value: String) { if !self.busy() && self.reply_draft != value { self.reply_draft = value; self.reply_message_id = None; } } pub fn loading(&self) -> bool { self.waiting_join.is_some() || self .pending .as_ref() .is_some_and(|p| !crate::net::forum::is_mutation(&p.request)) } pub fn busy(&self) -> bool { self.pending .as_ref() .is_some_and(|p| crate::net::forum::is_mutation(&p.request)) } pub fn pending(&self) -> bool { self.pending.is_some() || self.waiting_join.is_some() } pub fn select(&mut self, channel: &str) { if self.channel_id.as_deref() != Some(channel) { *self = Self { supported: self.supported, ..Default::default() }; } self.channel_id = Some(channel.to_owned()); self.joined = false; self.waiting_join = Some(Instant::now()); self.error.clear(); } pub fn create(&mut self) { if self.pending() || !self.supported { return; } self.creating = true; self.topic_id = None; self.posts.clear(); self.error.clear(); } pub fn request( &mut self, operation: wire::ForumOperation, offset: u32, ) -> Option { if !self.supported || !self.joined || self.pending() { return None; } let channel_id = self.channel_id.clone()?; let mut request = wire::ForumRequest { request_id: uuid::Uuid::new_v4().to_string(), channel_id, operation: operation as i32, offset, limit: if operation == wire::ForumOperation::List { 20 } else { 50 }, ..Default::default() }; match operation { wire::ForumOperation::List => (), wire::ForumOperation::Open => { request.topic_id = self.topic_id.clone()?; if offset == 0 { self.posts.clear(); self.posts_offset = None; } } wire::ForumOperation::Create => { let title = self.title_draft.trim(); let content = self.body_draft.trim(); if !valid_title(title) || !valid_body(content) { self.error = "Enter a title (1–160 characters) and a first message (1–16000 characters).".into(); return None; } request.topic_id = self .topic_draft_id .get_or_insert_with(|| uuid::Uuid::new_v4().to_string()) .clone(); request.message_id = self .first_message_id .get_or_insert_with(|| uuid::Uuid::new_v4().to_string()) .clone(); request.title = title.to_owned(); request.content = content.to_owned(); } wire::ForumOperation::Reply => { if !valid_body(self.reply_draft.trim()) { self.error = "Enter a reply (1–16000 characters).".into(); return None; } request.topic_id = self.topic_id.clone()?; request.message_id = self .reply_message_id .get_or_insert_with(|| uuid::Uuid::new_v4().to_string()) .clone(); request.content = self.reply_draft.trim().to_owned(); } _ => return None, } self.error.clear(); self.pending = Some(Pending { request: request.clone(), started: Instant::now(), }); Some(request) } pub fn open(&mut self, id: &str) -> Option { if self.pending() || !self.topics.iter().any(|topic| topic.topic_id == id) { return None; } self.topic_id = Some(id.to_owned()); self.creating = false; self.posts.clear(); self.reply_draft.clear(); self.reply_message_id = None; self.posts_offset = None; self.request(wire::ForumOperation::Open, 0) } pub fn timeout(&mut self) { if self .waiting_join .is_some_and(|at| at.elapsed() >= REQUEST_TIMEOUT) || self .pending .as_ref() .is_some_and(|p| p.started.elapsed() >= REQUEST_TIMEOUT) { self.waiting_join = None; self.pending = None; self.error = "The forum request timed out. Your draft has been kept; refresh or retry.".into(); } } pub fn result(&mut self, result: wire::ForumResult) { let Some(pending) = self.pending.as_ref() else { return; }; let request = &pending.request; if result.request_id != request.request_id || result.operation != request.operation || result.channel_id != request.channel_id || (!request.topic_id.is_empty() && result.topic_id != request.topic_id) { return; } let request = request.clone(); self.pending = None; if result.error_code != 0 || !result.error.is_empty() { self.error = result.error.chars().take(500).collect(); if self.error.is_empty() { self.error = "The server refused this forum request.".into(); } return; } if result.topics.len() > 50 || result.posts.len() > 100 || result .topics .iter() .any(|t| t.channel_id != request.channel_id) || result.posts.iter().any(|p| { p.topic_id != result.topic_id || p.message .as_ref() .is_none_or(|m| m.channel_id != request.channel_id) }) { self.error = "The server returned an invalid forum response.".into(); return; } let operation = wire::ForumOperation::try_from(request.operation).ok(); if matches!( operation, Some(wire::ForumOperation::Create | wire::ForumOperation::Reply) ) && !result.posts.iter().any(|p| { p.message .as_ref() .is_some_and(|m| m.message_id == request.message_id) }) { self.error = "The server did not acknowledge this forum message.".into(); return; } self.error.clear(); match operation { Some(wire::ForumOperation::List) => { if request.offset == 0 { self.topics.clear(); } let count = result.topics.len() as u32; for topic in result.topics { self.upsert_topic(topic); } self.topics_offset = next_offset(request.offset, count, result.has_more); } Some(wire::ForumOperation::Open) => { let count = result.posts.len() as u32; if result.has_more && let Some(last) = result.posts.iter().map(|p| p.ordinal).max() { self.posts.retain(|p| p.ordinal <= last); } for topic in result.topics { self.upsert_topic(topic); } for post in result.posts { self.upsert_post(post); } self.posts_offset = next_offset(request.offset, count, result.has_more); } Some(wire::ForumOperation::Create) => { self.creating = false; self.topic_id = Some(request.topic_id); self.title_draft.clear(); self.body_draft.clear(); self.topic_draft_id = None; self.first_message_id = None; self.posts.clear(); self.posts_offset = None; for topic in result.topics { self.upsert_topic(topic); } for post in result.posts { self.upsert_post(post); } } Some(wire::ForumOperation::Reply) => { self.reply_draft.clear(); self.reply_message_id = None; for topic in result.topics { self.upsert_topic(topic); } // When a thread is only partially loaded, do not insert a later reply ahead // of unseen posts: refresh/page through its chronological history instead. if self.posts_offset.is_none() { for post in result.posts { self.upsert_post(post); } } } _ => (), } } pub fn changed(&mut self, event: wire::ForumChanged) { if self.channel_id.as_deref() != Some(event.channel_id.as_str()) || !self.supported { return; } if let Some(topic) = event.topic && topic.channel_id == event.channel_id { self.upsert_topic(topic); } if self.posts_offset.is_none() && let Some(post) = event.post && self.topic_id.as_deref() == Some(post.topic_id.as_str()) && post .message .as_ref() .is_some_and(|m| m.channel_id == event.channel_id) { self.upsert_post(post); } } fn upsert_topic(&mut self, topic: wire::ForumTopic) { if let Some(current) = self .topics .iter_mut() .find(|t| t.topic_id == topic.topic_id) { if current.updated_at <= topic.updated_at { *current = topic; } } else { self.topics.push(topic); } self.topics.sort_by(|a, b| { b.updated_at .cmp(&a.updated_at) .then_with(|| a.topic_id.cmp(&b.topic_id)) }); } fn upsert_post(&mut self, post: wire::ForumPost) { let Some(message) = &post.message else { return; }; if !self.posts.iter().any(|p| { p.message .as_ref() .is_some_and(|m| m.message_id == message.message_id) }) { self.posts.push(post); } self.posts.sort_by_key(|post| post.ordinal); } } fn next_offset(offset: u32, count: u32, has_more: bool) -> Option { (has_more && count > 0 && offset.saturating_add(count) <= 100_000) .then_some(offset.saturating_add(count)) } fn bidi_or_control(c: char) -> bool { c.is_control() || matches!(c, '\u{061c}'|'\u{200e}'|'\u{200f}'|'\u{202a}'..='\u{202e}'|'\u{2066}'..='\u{2069}') } fn valid_title(value: &str) -> bool { !value.is_empty() && value.chars().count() <= 160 && !value.chars().any(bidi_or_control) } fn valid_body(value: &str) -> bool { !value.is_empty() && value.chars().count() <= 16000 && value.len() <= 64 * 1024 && !value .chars() .any(|c| bidi_or_control(c) && c != '\n' && c != '\t') } #[cfg(test)] mod tests { use super::*; fn ready() -> ForumState { ForumState { supported: true, joined: true, channel_id: Some("forum".into()), ..Default::default() } } fn topic(id: &str) -> wire::ForumTopic { wire::ForumTopic { topic_id: id.into(), channel_id: "forum".into(), title: "A real topic".into(), ..Default::default() } } fn post(id: &str, topic: &str, ordinal: u64) -> wire::ForumPost { wire::ForumPost { topic_id: topic.into(), ordinal, message: Some(wire::ChatMessage { message_id: id.into(), channel_id: "forum".into(), content: "A real reply".into(), timestamp: 1000, ..Default::default() }), ..Default::default() } } fn response(request: &wire::ForumRequest) -> wire::ForumResult { wire::ForumResult { request_id: request.request_id.clone(), operation: request.operation, channel_id: request.channel_id.clone(), topic_id: request.topic_id.clone(), ..Default::default() } } #[test] fn old_server_or_unacknowledged_join_cannot_prepare_forum_packets() { let mut state = ready(); state.supported = false; assert!(state.request(wire::ForumOperation::List, 0).is_none()); state.supported = true; state.joined = false; assert!(state.request(wire::ForumOperation::List, 0).is_none()); } #[test] fn failed_create_keeps_draft_and_stable_mutation_ids_until_matching_ack() { let mut state = ready(); state.create(); state.edit_title("Topic".into()); state.edit_body("Opening post".into()); let first = state.request(wire::ForumOperation::Create, 0).unwrap(); assert!(state.topic_id.is_none()); assert_eq!(state.title_draft, "Topic"); let mut denied = response(&first); denied.error_code = 5; denied.error = "Permission denied".into(); state.result(denied); assert_eq!(state.body_draft, "Opening post"); assert!(!state.busy()); let retry = state.request(wire::ForumOperation::Create, 0).unwrap(); assert_ne!(first.request_id, retry.request_id); assert_eq!(first.topic_id, retry.topic_id); assert_eq!(first.message_id, retry.message_id); let mut stale = response(&first); stale.topics = vec![topic(&first.topic_id)]; stale.posts = vec![post(&first.message_id, &first.topic_id, 1)]; state.result(stale); assert!(state.busy()); assert_eq!(state.title_draft, "Topic"); let mut accepted = response(&retry); accepted.topics = vec![topic(&retry.topic_id)]; accepted.posts = vec![post(&retry.message_id, &retry.topic_id, 1)]; state.result(accepted); assert_eq!(state.topic_id.as_deref(), Some(retry.topic_id.as_str())); assert_eq!(state.posts.len(), 1); assert!(state.title_draft.is_empty()); assert!(state.body_draft.is_empty()); assert!(!state.creating); } #[test] fn changing_failed_draft_allocates_new_object_ids_and_stale_node_results_are_ignored() { let mut state = ready(); state.edit_title("Topic".into()); state.edit_body("First".into()); let old = state.request(wire::ForumOperation::Create, 0).unwrap(); let mut failed = response(&old); failed.error = "Denied".into(); state.result(failed); state.edit_body("Changed".into()); let new = state.request(wire::ForumOperation::Create, 0).unwrap(); assert_ne!(old.topic_id, new.topic_id); assert_ne!(old.message_id, new.message_id); state.select("different-forum"); state.result(response(&new)); assert!(state.topics.is_empty()); assert!(state.posts.is_empty()); assert_eq!(state.channel_id.as_deref(), Some("different-forum")); } #[test] fn pagination_uses_actual_byte_bounded_page_size_and_posts_sort_by_ordinal() { let mut state = ready(); state.topics.push(topic("topic")); let request = state.open("topic").unwrap(); assert_eq!(request.limit, 50); let mut result = response(&request); result.topics = vec![topic("topic")]; result.posts = vec![post("two", "topic", 2), post("one", "topic", 1)]; result.has_more = true; state.result(result); assert_eq!(state.posts_offset, Some(2)); assert_eq!( state.posts.iter().map(|p| p.ordinal).collect::>(), vec![1, 2] ); let request = state .request(wire::ForumOperation::Open, state.posts_offset.unwrap()) .unwrap(); assert_eq!(request.offset, 2); let mut last = response(&request); last.posts = vec![post("three", "topic", 3)]; state.result(last); assert!(state.posts_offset.is_none()); assert_eq!(state.posts.len(), 3); } #[test] fn changed_ack_and_page_overlap_deduplicate_even_with_equal_millisecond_timestamps() { let mut state = ready(); state.topics.push(topic("topic")); state.topic_id = Some("topic".into()); state.posts.push(post("first", "topic", 1)); state.edit_reply("Own reply".into()); let request = state.request(wire::ForumOperation::Reply, 0).unwrap(); state.changed(wire::ForumChanged { channel_id: "forum".into(), topic: Some(topic("topic")), post: Some(post("third", "topic", 3)), }); let mut result = response(&request); result.topics = vec![topic("topic")]; result.posts = vec![post(&request.message_id, "topic", 2)]; state.result(result); state.changed(wire::ForumChanged { channel_id: "forum".into(), topic: Some(topic("topic")), post: Some(post(&request.message_id, "topic", 2)), }); assert_eq!( state.posts.iter().map(|p| p.ordinal).collect::>(), vec![1, 2, 3] ); assert!(state.reply_draft.is_empty()); } #[test] fn timeout_keeps_text_and_retry_ids_and_invalid_reply_ack_cannot_clear_input() { let mut state = ready(); state.topic_id = Some("topic".into()); state.edit_reply("Keep this".into()); let request = state.request(wire::ForumOperation::Reply, 0).unwrap(); state.pending.as_mut().unwrap().started = Instant::now() - REQUEST_TIMEOUT; state.timeout(); assert_eq!(state.reply_draft, "Keep this"); assert!(!state.error.is_empty()); let retry = state.request(wire::ForumOperation::Reply, 0).unwrap(); assert_eq!(request.message_id, retry.message_id); state.result(response(&retry)); assert_eq!(state.reply_draft, "Keep this"); assert!(!state.error.is_empty()); } }