[client] Polls: a poll is a message, a vote replaces the voter's earlier one, only the asker closes and the close carries the final votes; the client keeps each conversation's polls

This commit is contained in:
2026-11-22 10:37:59 +01:00
parent 056a68de17
commit 65f56e306c
6 changed files with 1024 additions and 10 deletions
+632 -8
View File
@@ -45,8 +45,24 @@ pub const MAX_NAME_CHARS: usize = 64;
pub const MAX_TEXT_BYTES: usize = 64 * 1024;
/// The longest reaction, in bytes of UTF-8: the longest emoji ZWJ sequences are 28.
pub const MAX_EMOJI_BYTES: usize = 32;
/// The fewest and the most options a poll has.
pub const MIN_POLL_OPTIONS: usize = 2;
pub const MAX_POLL_OPTIONS: usize = 10;
/// The longest poll option, in characters.
pub const MAX_OPTION_CHARS: usize = 100;
/// The longest poll question, in characters.
pub const MAX_QUESTION_CHARS: usize = 300;
/// The payload kinds this client knows; any other kind that carries a `seq` is `Unsupported`.
const KNOWN_KINDS: [&str; 5] = ["hello", "text", "receipt", "inbox", "reaction"];
const KNOWN_KINDS: [&str; 8] = [
"hello",
"text",
"receipt",
"inbox",
"reaction",
"poll",
"vote",
"pollClose",
];
const WELCOME_ID_LABEL: &[u8] = b"tabellarius v0 welcome mailbox";
const WELCOME_POST_LABEL: &[u8] = b"tabellarius v0 welcome mailbox post";
@@ -66,6 +82,12 @@ pub enum ClientError {
/// A reply or reaction to a message that does not exist in this conversation, or an emoji
/// that is empty or has a control character.
BadReference,
/// A poll that is not well formed (an option blank or repeated, too few or too many), a vote
/// that is not (a choice out of range, repeated, or several in a single-choice poll), or a
/// close of a poll that is not ours or not in this conversation.
BadPoll,
/// A vote or a close for a poll that is already closed.
PollClosed,
/// A snapshot that does not parse, has another version, or does not match OpenMLS's storage.
State,
}
@@ -125,6 +147,28 @@ pub enum Event {
to: MessageRef,
emoji: Option<String>,
},
/// A poll (a message: `seq` names it with the contact's author, like a text's).
Poll {
contact: ContactId,
seq: u64,
question: String,
options: Vec<String>,
multiple: bool,
},
/// The contact's vote in a poll of this conversation, replacing their earlier one; no choices
/// takes it back. Indexes into the poll's options, ascending.
Vote {
contact: ContactId,
poll: MessageRef,
choices: Vec<u8>,
},
/// The contact closed their poll. `ballots` are the final votes, ours included: show these,
/// not what was counted before.
PollClosed {
contact: ContactId,
poll: MessageRef,
ballots: Vec<Ballot>,
},
/// A message of a kind this client does not know (a newer app's). Show that something arrived
/// that needs an update; its `seq` counts like a text's.
Unsupported { contact: ContactId, seq: u64 },
@@ -211,6 +255,45 @@ pub struct MessageRef {
pub seq: u64,
}
/// One member's choices in a poll, as a close reports them.
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Ballot {
pub author: Author,
pub choices: Vec<u8>,
}
/// A poll in a conversation, as this client accepted it (`.agents/features/polls.md` §2.3).
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub(crate) struct PollState {
pub(crate) poll: MessageRef,
pub(crate) options: u8,
pub(crate) multiple: bool,
pub(crate) closed: bool,
/// Each member's current, non-empty choices.
pub(crate) ballots: Vec<Ballot>,
}
impl PollState {
/// Indexes into the options, ascending, each once; at most one unless `multiple`.
fn choices_ok(&self, choices: &[u8]) -> bool {
choices.iter().all(|&i| i < self.options)
&& choices.windows(2).all(|w| w[0] < w[1])
&& (self.multiple || choices.len() <= 1)
}
fn set_ballot(&mut self, author: Author, choices: &[u8]) {
self.ballots.retain(|b| b.author != author);
if !choices.is_empty() {
self.ballots.push(Ballot {
author,
choices: choices.to_vec(),
});
}
}
}
/// The JSON inside an MLS application message. The relay never sees it.
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
@@ -237,6 +320,22 @@ enum Payload {
#[serde(default, skip_serializing_if = "Option::is_none")]
emoji: Option<String>,
},
/// A question with options; a message, sharing the sender's `seq` with texts.
#[serde(rename_all = "camelCase")]
Poll {
seq: u64,
question: String,
options: Vec<String>,
multiple: bool,
},
/// The sender's choices in `poll`, replacing their earlier ones; `[]` takes the vote back.
Vote { poll: MessageRef, choices: Vec<u8> },
/// The poll's author closed it; `ballots` are the final votes.
#[serde(rename_all = "camelCase")]
PollClose {
poll: MessageRef,
ballots: Vec<Ballot>,
},
/// The receiver has saved our texts up to `upto`.
Receipt { upto: u64 },
/// A new post token for the mailbox the receiver already knows (unblock).
@@ -273,6 +372,8 @@ struct Contact {
sent_seq: u64,
/// The highest `seq` of their texts we have received.
received_seq: u64,
/// The polls in this conversation, ours and theirs.
polls: Vec<PollState>,
}
pub struct Client<T: Transport> {
@@ -477,6 +578,7 @@ impl<T: Transport> Client<T> {
blocked: false,
sent_seq: 0,
received_seq: 0,
polls: Vec::new(),
});
id
}
@@ -573,6 +675,121 @@ impl<T: Transport> Client<T> {
Ok(Outgoing::post(out_to, post, blob))
}
/// A poll for a contact: a message, named by [`Client::sent_seq`] right after. `multiple`
/// lets a vote hold several choices. No network: save the snapshot, then deliver.
pub fn compose_poll(
&mut self,
contact: ContactId,
question: &str,
options: &[String],
multiple: bool,
) -> Result<Outgoing, ClientError> {
if question.chars().count() > MAX_QUESTION_CHARS
|| options.iter().any(|o| o.chars().count() > MAX_OPTION_CHARS)
{
return Err(ClientError::TooLong);
}
if !poll_ok(question, options) {
return Err(ClientError::BadPoll);
}
let index = self.index_of(contact)?;
let author = self.author();
let c = &mut self.contacts[index];
let (to, post) = c.outbox.ok_or(ClientError::UnknownContact)?;
let seq = c.sent_seq + 1;
let blob = Self::seal(
&self.provider,
&self.signer,
&mut c.group,
&Payload::Poll {
seq,
question: question.to_string(),
options: options.to_vec(),
multiple,
},
)?;
c.sent_seq = seq;
c.polls.push(PollState {
poll: MessageRef { author, seq },
// At most MAX_POLL_OPTIONS (10), checked above.
options: options.len() as u8,
multiple,
closed: false,
ballots: Vec::new(),
});
Ok(Outgoing::post(to, post, blob))
}
/// Our vote in a poll of this conversation, ours or theirs, replacing our earlier one; `[]`
/// takes it back. No network: save the snapshot, then deliver.
pub fn vote(
&mut self,
contact: ContactId,
poll: MessageRef,
choices: &[u8],
) -> Result<Outgoing, ClientError> {
let index = self.index_of(contact)?;
let author = self.author();
let c = &mut self.contacts[index];
let p = c
.polls
.iter()
.position(|p| p.poll == poll)
.ok_or(ClientError::BadPoll)?;
if c.polls[p].closed {
return Err(ClientError::PollClosed);
}
if !c.polls[p].choices_ok(choices) {
return Err(ClientError::BadPoll);
}
let (to, post) = c.outbox.ok_or(ClientError::UnknownContact)?;
let blob = Self::seal(
&self.provider,
&self.signer,
&mut c.group,
&Payload::Vote {
poll,
choices: choices.to_vec(),
},
)?;
c.polls[p].set_ballot(author, choices);
Ok(Outgoing::post(to, post, blob))
}
/// Closes our own poll. The close carries the votes this client has accepted, which become the
/// result on both sides. No network: save the snapshot, then deliver.
pub fn close_poll(
&mut self,
contact: ContactId,
poll: MessageRef,
) -> Result<Outgoing, ClientError> {
let index = self.index_of(contact)?;
if poll.author != self.author() {
return Err(ClientError::BadPoll);
}
let c = &mut self.contacts[index];
let p = c
.polls
.iter()
.position(|p| p.poll == poll)
.ok_or(ClientError::BadPoll)?;
if c.polls[p].closed {
return Err(ClientError::PollClosed);
}
let (to, post) = c.outbox.ok_or(ClientError::UnknownContact)?;
let blob = Self::seal(
&self.provider,
&self.signer,
&mut c.group,
&Payload::PollClose {
poll,
ballots: c.polls[p].ballots.clone(),
},
)?;
c.polls[p].closed = true;
Ok(Outgoing::post(to, post, blob))
}
/// Our author name: the 16 bytes in our credential. With a `seq` it names our messages.
pub fn author(&self) -> Author {
author_of(&self.identity).unwrap_or_else(|| Author::from_bytes([0; 16]))
@@ -1018,6 +1235,14 @@ impl<T: Transport> Client<T> {
emoji,
}))
}
Payload::Poll {
seq,
question,
options,
multiple,
} => self.receive_poll(index, seq, question, options, multiple),
Payload::Vote { poll, choices } => self.receive_vote(index, poll, choices),
Payload::PollClose { poll, ballots } => self.receive_close(index, poll, ballots),
Payload::Receipt { upto } => {
let c = &self.contacts[index];
if !self.receipts || c.name.is_none() || c.blocked {
@@ -1055,6 +1280,124 @@ impl<T: Transport> Client<T> {
c.received_seq = c.received_seq.max(seq);
Ok(Some(Event::Unsupported { contact: c.id, seq }))
}
/// The contact's poll: kept if well formed and not one we already have under that name.
fn receive_poll(
&mut self,
index: usize,
seq: u64,
question: String,
options: Vec<String>,
multiple: bool,
) -> Result<Option<Event>, ClientError> {
if self.contacts[index].name.is_none() {
return Err(ClientError::Mls);
}
let Some(author) = self.peer_author(index) else {
return Ok(None);
};
let name = MessageRef { author, seq };
let c = &mut self.contacts[index];
let fits = question.chars().count() <= MAX_QUESTION_CHARS
&& options
.iter()
.all(|o| o.chars().count() <= MAX_OPTION_CHARS);
if c.blocked
|| seq == 0
|| !fits
|| !poll_ok(&question, &options)
|| c.polls.iter().any(|p| p.poll == name)
{
return Ok(None);
}
c.received_seq = c.received_seq.max(seq);
c.polls.push(PollState {
poll: name,
// At most MAX_POLL_OPTIONS (10): poll_ok.
options: options.len() as u8,
multiple,
closed: false,
ballots: Vec::new(),
});
Ok(Some(Event::Poll {
contact: c.id,
seq,
question,
options,
multiple,
}))
}
/// The contact's vote, in a poll of this conversation that is still open.
fn receive_vote(
&mut self,
index: usize,
poll: MessageRef,
choices: Vec<u8>,
) -> Result<Option<Event>, ClientError> {
if self.contacts[index].name.is_none() {
return Err(ClientError::Mls);
}
let Some(author) = self.peer_author(index) else {
return Ok(None);
};
let c = &mut self.contacts[index];
if c.blocked {
return Ok(None);
}
let Some(p) = c.polls.iter_mut().find(|p| p.poll == poll) else {
return Ok(None);
};
if p.closed || !p.choices_ok(&choices) {
return Ok(None);
}
p.set_ballot(author, &choices);
Ok(Some(Event::Vote {
contact: c.id,
poll,
choices,
}))
}
/// The contact closed their own poll: its votes become the close's ballots, if each is a
/// member's, once, and a valid vote.
fn receive_close(
&mut self,
index: usize,
poll: MessageRef,
ballots: Vec<Ballot>,
) -> Result<Option<Event>, ClientError> {
if self.contacts[index].name.is_none() {
return Err(ClientError::Mls);
}
let Some(peer) = self.peer_author(index) else {
return Ok(None);
};
let me = self.author();
let c = &mut self.contacts[index];
if c.blocked || poll.author != peer {
return Ok(None);
}
let Some(p) = c.polls.iter_mut().find(|p| p.poll == poll) else {
return Ok(None);
};
let valid = ballots.iter().enumerate().all(|(i, b)| {
(b.author == me || b.author == peer)
&& !ballots[..i].iter().any(|o| o.author == b.author)
&& !b.choices.is_empty()
&& p.choices_ok(&b.choices)
});
if p.closed || !valid {
return Ok(None);
}
p.closed = true;
p.ballots = ballots.clone();
Ok(Some(Event::PollClosed {
contact: c.id,
poll,
ballots,
}))
}
}
enum Parsed {
@@ -1081,6 +1424,19 @@ fn parse_payload(bytes: &[u8]) -> Result<Parsed, ClientError> {
}
}
/// A poll's question and options as the wire allows them (the lengths are checked apart): 2–10
/// options, none blank, none repeated, no control characters anywhere.
fn poll_ok(question: &str, options: &[String]) -> bool {
let fine = |s: &str| !s.trim().is_empty() && !s.chars().any(char::is_control);
(MIN_POLL_OPTIONS..=MAX_POLL_OPTIONS).contains(&options.len())
&& fine(question)
&& options.iter().all(|o| fine(o))
&& options
.iter()
.enumerate()
.all(|(i, o)| !options[..i].contains(o))
}
/// An emoji as the wire allows it: not empty, no control characters (the length is checked apart,
/// as [`ClientError::TooLong`]).
fn emoji_ok(emoji: &str) -> bool {
@@ -1226,14 +1582,18 @@ mod tests {
#[test]
fn an_unknown_kind_needs_a_seq_and_a_known_kind_must_parse_exactly() {
assert!(matches!(
parse_payload(br#"{"kind":"poll","seq":4,"question":"?"}"#),
parse_payload(br#"{"kind":"file","seq":4,"name":"?"}"#),
Ok(Parsed::Unknown { seq: 4 })
));
for bad in [
&br#"{"kind":"poll","question":"?"}"#[..],
br#"{"kind":"poll","seq":0}"#,
br#"{"kind":"poll","seq":-1}"#,
br#"{"kind":"poll","seq":"4"}"#,
&br#"{"kind":"file","name":"?"}"#[..],
br#"{"kind":"file","seq":0}"#,
br#"{"kind":"file","seq":-1}"#,
br#"{"kind":"file","seq":"4"}"#,
br#"{"kind":"poll","seq":4,"question":"?"}"#,
br#"{"kind":"vote","poll":{"author":"AAAAAAAAAAAAAAAAAAAAAA","seq":1},"choices":[256]}"#,
br#"{"kind":"vote","poll":{"author":"AAAAAAAAAAAAAAAAAAAAAA","seq":1},"choices":[-1]}"#,
br#"{"kind":"pollClose","poll":{"author":"AAAAAAAAAAAAAAAAAAAAAA","seq":1},"ballots":[{"author":"AAAAAAAAAAAAAAAAAAAAAA","choices":[0],"x":1}]}"#,
br#"{"seq":4}"#,
br#"{"kind":"text","body":"x","seq":1,"mentions":[]}"#,
br#"{"kind":"reaction","to":{"author":"AAAAAAAAAAAAAAAAAAAAAA","seq":1},"emoji":"x","extra":1}"#,
@@ -1345,9 +1705,9 @@ mod tests {
fn a_newer_apps_message_is_unsupported_and_counts_for_receipts() {
let (mut eva, mut jan) = paired();
eva.set_receipts(true);
let out = seal_raw(&mut jan, r#"{"kind":"poll","seq":1,"question":"Pivo?"}"#);
let out = seal_raw(&mut jan, r#"{"kind":"file","seq":1,"name":"Pivo.jpg"}"#);
jan.deliver(&out).expect("deliver");
let out = seal_raw(&mut jan, r#"{"kind":"poll","question":"no seq"}"#);
let out = seal_raw(&mut jan, r#"{"kind":"file","name":"no seq"}"#);
jan.deliver(&out).expect("deliver");
let got = eva.receive().expect("receive");
assert_eq!(
@@ -1364,6 +1724,253 @@ mod tests {
assert_eq!(eva.receive_unknown(0, 2), Ok(None));
}
// Polls (`.agents/features/polls.md` §2.4).
fn strings(xs: &[&str]) -> Vec<String> {
xs.iter().map(|x| x.to_string()).collect()
}
fn their_poll(seq: u64, options: &[&str], multiple: bool) -> Payload {
Payload::Poll {
seq,
question: "Kam?".into(),
options: strings(options),
multiple,
}
}
#[test]
fn a_malformed_poll_is_refused_when_sending_and_dropped_when_received() {
let (mut eva, _jan) = paired();
let id = eva.contacts[0].id;
let long = "x".repeat(MAX_OPTION_CHARS + 1);
let eleven: Vec<String> = (0..11).map(|i| i.to_string()).collect();
let bad: [(&str, Vec<String>); 7] = [
("Kam?", strings(&["jen jedna"])),
("Kam?", eleven),
("Kam?", strings(&["a", "a"])),
("Kam?", strings(&["a", " "])),
(" ", strings(&["a", "b"])),
("Kam?\u{7}", strings(&["a", "b"])),
("Kam?", strings(&["a", "b\n"])),
];
for (question, options) in &bad {
assert_eq!(
eva.compose_poll(id, question, options, false).err(),
Some(ClientError::BadPoll),
"{question:?} {options:?}"
);
let got = eva.receive_payload(
0,
Payload::Poll {
seq: 1,
question: question.to_string(),
options: options.clone(),
multiple: false,
},
);
assert_eq!(got, Ok(None), "{question:?} {options:?}");
}
assert_eq!(
eva.compose_poll(id, "Kam?", &[long.clone(), "b".into()], false)
.err(),
Some(ClientError::TooLong)
);
let long_question = "?".repeat(MAX_QUESTION_CHARS + 1);
assert_eq!(
eva.compose_poll(id, &long_question, &strings(&["a", "b"]), false)
.err(),
Some(ClientError::TooLong)
);
assert_eq!(
eva.receive_payload(
0,
Payload::Poll {
seq: 1,
question: "Kam?".into(),
options: vec![long, "b".into()],
multiple: false,
}
),
Ok(None)
);
assert_eq!(
eva.contacts[0].received_seq, 0,
"a dropped poll does not count"
);
assert!(eva.contacts[0].polls.is_empty());
// Ten options of exactly 100 characters, and 300 of question: fits.
let ten: Vec<String> = (0..10).map(|i| format!("{i}{}", "y".repeat(99))).collect();
let q = "?".repeat(MAX_QUESTION_CHARS);
assert!(eva.compose_poll(id, &q, &ten, true).is_ok());
assert!(matches!(
eva.receive_payload(0, their_poll(1, &["a", "b"], false)),
Ok(Some(Event::Poll { seq: 1, .. }))
));
assert_eq!(
eva.receive_payload(0, their_poll(1, &["c", "d"], false)),
Ok(None),
"a second poll under the same name"
);
}
#[test]
fn a_vote_that_does_not_fit_its_poll_is_refused_and_dropped() {
let (mut eva, _jan) = paired();
let id = eva.contacts[0].id;
let jan = eva.peer_author(0).expect("author");
eva.receive_payload(0, their_poll(1, &["a", "b", "c"], false))
.expect("poll");
eva.receive_payload(0, their_poll(2, &["a", "b", "c"], true))
.expect("poll");
let single = MessageRef {
author: jan,
seq: 1,
};
let multi = MessageRef {
author: jan,
seq: 2,
};
let unknown = MessageRef {
author: jan,
seq: 3,
};
let vote = |poll, choices: &[u8]| Payload::Vote {
poll,
choices: choices.to_vec(),
};
for (poll, choices) in [
(single, &[0u8, 1][..]),
(single, &[3][..]),
(multi, &[1, 0][..]),
(multi, &[1, 1][..]),
(multi, &[3][..]),
(unknown, &[0][..]),
] {
assert_eq!(
eva.vote(id, poll, choices).err(),
Some(ClientError::BadPoll),
"{poll:?} {choices:?}"
);
assert_eq!(eva.receive_payload(0, vote(poll, choices)), Ok(None));
}
assert!(eva.vote(id, multi, &[0, 2]).is_ok());
assert!(eva.vote(id, single, &[]).is_ok(), "taking back nothing");
assert!(matches!(
eva.receive_payload(0, vote(multi, &[0, 1, 2])),
Ok(Some(Event::Vote { .. }))
));
let p = &eva.contacts[0].polls[1];
assert_eq!(p.ballots.len(), 2);
// Taking it back removes the ballot.
eva.receive_payload(0, vote(multi, &[])).expect("vote");
assert_eq!(eva.contacts[0].polls[1].ballots.len(), 1);
}
#[test]
fn only_the_asker_closes_with_valid_ballots_and_then_nothing_changes_it() {
let (mut eva, _jan) = paired();
let id = eva.contacts[0].id;
let jan = eva.peer_author(0).expect("author");
let me = eva.author();
eva.receive_payload(0, their_poll(1, &["a", "b"], false))
.expect("poll");
let theirs = MessageRef {
author: jan,
seq: 1,
};
let out = eva.compose_poll(id, "Kdy?", &strings(&["pá", "so"]), false);
assert!(out.is_ok());
let ours = MessageRef { author: me, seq: 1 };
assert_eq!(
eva.close_poll(id, theirs).err(),
Some(ClientError::BadPoll),
"not ours to close"
);
let close = |poll, ballots: Vec<Ballot>| Payload::PollClose { poll, ballots };
let ballot = |author, choices: &[u8]| Ballot {
author,
choices: choices.to_vec(),
};
let stranger = Author::from_bytes([7; 16]);
for payload in [
// Jan cannot close Eva's poll.
close(ours, vec![]),
close(theirs, vec![ballot(stranger, &[0])]),
close(theirs, vec![ballot(jan, &[0]), ballot(jan, &[1])]),
close(theirs, vec![ballot(jan, &[])]),
close(theirs, vec![ballot(me, &[0, 1])]),
close(theirs, vec![ballot(me, &[2])]),
close(
MessageRef {
author: jan,
seq: 2,
},
vec![],
),
] {
assert_eq!(eva.receive_payload(0, payload), Ok(None));
}
assert!(!eva.contacts[0].polls[0].closed);
let final_ = vec![ballot(jan, &[1]), ballot(me, &[0])];
assert_eq!(
eva.receive_payload(0, close(theirs, final_.clone())),
Ok(Some(Event::PollClosed {
contact: id,
poll: theirs,
ballots: final_.clone()
}))
);
assert_eq!(eva.contacts[0].polls[0].ballots, final_);
// Closed: no vote, no second close, from either side.
assert_eq!(
eva.vote(id, theirs, &[1]).err(),
Some(ClientError::PollClosed)
);
let vote = Payload::Vote {
poll: theirs,
choices: vec![0],
};
assert_eq!(eva.receive_payload(0, vote), Ok(None));
assert_eq!(eva.receive_payload(0, close(theirs, vec![])), Ok(None));
assert_eq!(eva.contacts[0].polls[0].ballots, final_);
// Our own: closed once.
assert!(eva.close_poll(id, ours).is_ok());
assert_eq!(
eva.close_poll(id, ours).err(),
Some(ClientError::PollClosed)
);
}
#[test]
fn a_blocked_contacts_poll_vote_and_close_are_dropped() {
let (mut eva, _jan) = paired();
let jan = eva.peer_author(0).expect("author");
eva.receive_payload(0, their_poll(1, &["a", "b"], false))
.expect("poll");
let poll = MessageRef {
author: jan,
seq: 1,
};
eva.contacts[0].blocked = true;
assert_eq!(
eva.receive_payload(0, their_poll(2, &["a", "b"], false)),
Ok(None)
);
let vote = Payload::Vote {
poll,
choices: vec![0],
};
assert_eq!(eva.receive_payload(0, vote), Ok(None));
let close = Payload::PollClose {
poll,
ballots: vec![],
};
assert_eq!(eva.receive_payload(0, close), Ok(None));
assert_eq!(eva.contacts[0].polls.len(), 1);
assert!(!eva.contacts[0].polls[0].closed);
assert!(eva.contacts[0].polls[0].ballots.is_empty());
}
/// Every kind this client sends is in `KNOWN_KINDS`: a variant left out would arrive as
/// *Unsupported* at a client of the same version.
#[test]
@@ -1388,6 +1995,23 @@ mod tests {
post_token: Token::from_bytes([0; 32]),
},
Payload::Reaction { to, emoji: None },
Payload::Poll {
seq: 2,
question: "?".into(),
options: vec!["a".into(), "b".into()],
multiple: false,
},
Payload::Vote {
poll: to,
choices: vec![0],
},
Payload::PollClose {
poll: to,
ballots: vec![Ballot {
author: to.author,
choices: vec![1],
}],
},
];
assert_eq!(all.len(), KNOWN_KINDS.len());
for payload in all {
+7 -2
View File
@@ -3,8 +3,8 @@
//! keys, fetch tokens and post tokens. `Debug` is not implemented for any of it.
use crate::{
credential_with_key, Client, ClientError, Contact, ContactId, Mailbox, Transport, WelcomeBox,
CIPHERSUITE, MAX_NAME_CHARS,
credential_with_key, Client, ClientError, Contact, ContactId, Mailbox, PollState, Transport,
WelcomeBox, CIPHERSUITE, MAX_NAME_CHARS,
};
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine as _;
@@ -54,6 +54,9 @@ struct ContactState {
sent_seq: u64,
#[serde(default)]
received_seq: u64,
// F28 (`.agents/features/polls.md` §2.3); absent in older snapshots.
#[serde(default)]
polls: Vec<PollState>,
}
fn yes() -> bool {
@@ -107,6 +110,7 @@ impl<T: Transport> Client<T> {
blocked: c.blocked,
sent_seq: c.sent_seq,
received_seq: c.received_seq,
polls: c.polls.clone(),
})
.collect(),
welcome_boxes: self.welcome_boxes.clone(),
@@ -163,6 +167,7 @@ impl<T: Transport> Client<T> {
blocked: c.blocked,
sent_seq: c.sent_seq,
received_seq: c.received_seq,
polls: c.polls,
});
}
Ok(Client {
+241
View File
@@ -0,0 +1,241 @@
//! Polls (`.agents/features/polls.md`). No I/O: runs on the Android emulator too.
use tabellarius_client::*;
type C = Client<MemoryTransport>;
fn pair(relay: &MemoryTransport, receipts: bool) -> (C, ContactId, C, ContactId) {
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
eva.set_receipts(receipts);
jan.set_receipts(receipts);
let invite = eva.create_invite().expect("invite");
let jan_side = jan.accept_invite(&invite).expect("accept");
let Some(Event::Joined {
contact: eva_side, ..
}) = eva.poll().expect("poll").first().cloned()
else {
panic!("no join")
};
jan.poll().expect("poll");
(eva, eva_side, jan, jan_side)
}
fn strings(xs: &[&str]) -> Vec<String> {
xs.iter().map(|x| x.to_string()).collect()
}
fn send(c: &mut C, out: Result<Outgoing, ClientError>) {
let out = out.expect("compose");
c.deliver(&out).expect("deliver");
}
#[test]
fn a_poll_arrives_votes_change_and_the_close_gives_both_sides_the_same_result() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay, false);
eva.send(eva_side, "Ahoj").expect("send");
let options = strings(&["Italská", "Thajská", "Doma"]);
let out = eva.compose_poll(eva_side, "Kam na večeři?", &options, true);
send(&mut eva, out);
assert_eq!(eva.sent_seq(eva_side), Some(2), "a poll is a message");
let poll = MessageRef {
author: eva.author(),
seq: 2,
};
let got = jan.poll().expect("poll");
assert_eq!(
got[1],
Event::Poll {
contact: jan_side,
seq: 2,
question: "Kam na večeři?".into(),
options: options.clone(),
multiple: true,
}
);
// Jan votes, changes his mind, takes it back, votes again; Eva votes in her own poll.
for choices in [&[0u8][..], &[0, 1], &[], &[1, 2]] {
let out = jan.vote(jan_side, poll, choices);
send(&mut jan, out);
}
let out = eva.vote(eva_side, poll, &[1]);
send(&mut eva, out);
let votes: Vec<Vec<u8>> = eva
.poll()
.expect("poll")
.into_iter()
.map(|e| match e {
Event::Vote {
contact,
poll: p,
choices,
} if contact == eva_side && p == poll => choices,
other => panic!("{other:?}"),
})
.collect();
assert_eq!(votes, vec![vec![0], vec![0, 1], vec![], vec![1, 2]]);
assert_eq!(
jan.poll().expect("poll"),
vec![Event::Vote {
contact: jan_side,
poll,
choices: vec![1]
}]
);
// A poll can be answered and reacted to like a text.
let out = jan.compose_text(jan_side, "Thajská!", Some(poll));
send(&mut jan, out);
let out = jan.react(jan_side, poll, Some("👍"));
send(&mut jan, out);
assert_eq!(eva.poll().expect("poll").len(), 2);
// Jan cannot close Eva's poll; Eva closes it.
assert_eq!(
jan.close_poll(jan_side, poll).err(),
Some(ClientError::BadPoll)
);
let out = eva.close_poll(eva_side, poll);
send(&mut eva, out);
let final_ = vec![
Ballot {
author: jan.author(),
choices: vec![1, 2],
},
Ballot {
author: eva.author(),
choices: vec![1],
},
];
let got = jan.poll().expect("poll");
let [Event::PollClosed {
contact,
poll: p,
ballots,
}] = got.as_slice()
else {
panic!("{got:?}")
};
assert_eq!((*contact, *p), (jan_side, poll));
let mut sorted = ballots.clone();
sorted.sort_by_key(|b| b.author.as_bytes().to_vec());
let mut expected = final_.clone();
expected.sort_by_key(|b| b.author.as_bytes().to_vec());
assert_eq!(sorted, expected);
assert_eq!(
jan.vote(jan_side, poll, &[0]).err(),
Some(ClientError::PollClosed)
);
assert_eq!(
eva.vote(eva_side, poll, &[0]).err(),
Some(ClientError::PollClosed)
);
}
#[test]
fn a_vote_that_crosses_the_close_is_counted_nowhere() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay, false);
let out = eva.compose_poll(eva_side, "Pátek?", &strings(&["ano", "ne"]), false);
send(&mut eva, out);
jan.poll().expect("poll");
let poll = MessageRef {
author: eva.author(),
seq: 1,
};
let out = jan.vote(jan_side, poll, &[0]);
send(&mut jan, out);
eva.poll().expect("poll");
// Both at once: Jan changes his vote while Eva closes.
let out = jan.vote(jan_side, poll, &[1]);
send(&mut jan, out);
let out = eva.close_poll(eva_side, poll);
send(&mut eva, out);
assert_eq!(
eva.poll().expect("poll"),
vec![],
"the late vote is dropped"
);
let got = jan.poll().expect("poll");
assert_eq!(
got,
vec![Event::PollClosed {
contact: jan_side,
poll,
ballots: vec![Ballot {
author: jan.author(),
choices: vec![0]
}],
}],
"Jan's result is Eva's: his first vote, not the one that crossed"
);
}
#[test]
fn a_receipt_covers_a_poll() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, _) = pair(&relay, true);
let out = eva.compose_poll(eva_side, "Pivo?", &strings(&["ano", "jasně"]), false);
send(&mut eva, out);
let got = jan.poll().expect("poll");
assert!(
matches!(got.as_slice(), [Event::Poll { seq: 1, .. }]),
"{got:?}"
);
assert!(eva.poll().expect("poll").contains(&Event::Delivered {
contact: eva_side,
upto: 1
}));
}
#[test]
fn a_poll_survives_a_restart_open_or_closed_with_its_votes() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay, false);
let out = eva.compose_poll(eva_side, "Kdy?", &strings(&["pá", "so", "ne"]), true);
send(&mut eva, out);
let out = eva.compose_poll(eva_side, "Kde?", &strings(&["u nás", "u vás"]), false);
send(&mut eva, out);
jan.poll().expect("poll");
let when = MessageRef {
author: eva.author(),
seq: 1,
};
let where_ = MessageRef {
author: eva.author(),
seq: 2,
};
let out = jan.vote(jan_side, when, &[0, 2]);
send(&mut jan, out);
eva.poll().expect("poll");
let out = eva.close_poll(eva_side, where_);
send(&mut eva, out);
jan.poll().expect("poll");
let mut eva = C::restore(&eva.snapshot().expect("snapshot"), relay.clone()).expect("eva");
let mut jan = C::restore(&jan.snapshot().expect("snapshot"), relay.clone()).expect("jan");
// Closed stays closed, on both sides.
assert_eq!(
jan.vote(jan_side, where_, &[0]).err(),
Some(ClientError::PollClosed)
);
assert_eq!(
eva.close_poll(eva_side, where_).err(),
Some(ClientError::PollClosed)
);
// The open one keeps Jan's vote: Eva's close after the restart carries it.
let out = eva.close_poll(eva_side, when);
send(&mut eva, out);
assert_eq!(
jan.poll().expect("poll"),
vec![Event::PollClosed {
contact: jan_side,
poll: when,
ballots: vec![Ballot {
author: jan.author(),
choices: vec![0, 2]
}],
}]
);
}
+17
View File
@@ -214,6 +214,13 @@ fn pair_and_talk_through_a_real_relay_which_never_sees_a_name_or_a_word() {
};
let out = jan.react(jan_side, mine, Some(emoji)).expect("react");
jan.deliver(&out).expect("deliver");
// And a poll (F28): its question and options neither.
let question = "POLL-QUESTION-CANARY";
let options = vec!["OPTION-CANARY-A".to_string(), "OPTION-CANARY-B".to_string()];
let out = jan
.compose_poll(jan_side, question, &options, false)
.expect("poll");
jan.deliver(&out).expect("deliver");
// Snapshot the database while both messages wait, before anyone fetches.
let waiting = std::fs::read(&db).expect("db");
@@ -240,6 +247,13 @@ fn pair_and_talk_through_a_real_relay_which_never_sees_a_name_or_a_word() {
to: mine,
emoji: Some(emoji.into()),
},
Event::Poll {
contact: eva_side,
seq: 2,
question: question.into(),
options: options.clone(),
multiple: false,
},
]
);
let after = std::fs::read(&db).expect("db");
@@ -248,6 +262,9 @@ fn pair_and_talk_through_a_real_relay_which_never_sees_a_name_or_a_word() {
for (what, needle) in [
("canary", canary.as_bytes()),
("reaction", emoji.as_bytes()),
("poll question", question.as_bytes()),
("poll option", options[0].as_bytes()),
("poll option", options[1].as_bytes()),
("inviter's name", "Eva Nováková".as_bytes()),
("invitee's name", "Jan Dvořák".as_bytes()),
("invite secret", invite.secret.as_bytes().as_slice()),