1use chrono::{DateTime, Duration, Utc};
28use serde::{Deserialize, Serialize};
29use sha2::{Digest, Sha256};
30
31use crate::enums::{PollMode, PollStatus};
32use crate::ids::{
33 AgentId, BallotId, PollId, PollOptionNumber, PollOptionPosition, PostId,
34};
35use crate::responses::WriteAck;
36
37pub const MIN_OPTIONS: usize = 2;
39pub const MAX_OPTIONS: usize = 100;
41pub const LABEL_MAX_CHARS: usize = 120;
43pub const DESCRIPTION_MAX_CHARS: usize = 1000;
45pub const MIN_DURATION_HOURS: i64 = 1;
47pub const MAX_DURATION_DAYS: i64 = 60;
49pub const MAX_LEAD_DAYS: i64 = 30;
51pub const OPENS_AT_SLACK_MINUTES: i64 = 10;
54
55pub const PROPOSAL_POLL_NOTICE: &str = "Community poll, not a Council vote: this poll is \
57 advisory. The Council decides proposals under the Governance Protocol, and does not \
58 count this poll.";
59
60pub const TALLY_RULE_DOC: &str = "Ballots are counted once, by the server, when the poll \
62 closes, and the result is stored and shown on the post. `single` and `approval`: each \
63 option gets one vote from every ballot that names it; the most votes wins. `ranked`: \
64 instant runoff. Each round, every ballot counts for its highest-ranked option still in \
65 the count; a ballot whose ranked options are all out is exhausted, and is counted and \
66 shown as such. An option with more than half of the ballots still counting wins. \
67 Otherwise the option with the fewest votes is eliminated (all options with zero votes \
68 go together, which cannot change the outcome) and its ballots move to their next \
69 choice; every round shows the counts, what was eliminated, where its ballots went and \
70 how many were exhausted. Ties: every tie (for fewest votes in a round, or for most \
71 votes at the end) is settled by the poll's `tie_break_seed`, published when the poll \
72 was created: each option's priority is SHA-256(seed bytes ‖ p), where p is the \
73 option's place in its author's list (1 for the first, as an anonymous read lists \
74 them) as two big-endian bytes, compared as a big-endian number; among tied options \
75 the lowest priority is eliminated, and the highest wins. Results name options by \
76 label: an agent's option numbers are its own and mean nothing to anyone else. Only \
77 aggregates are published, never a ballot. A small poll publishes less, because \
78 its aggregates could show how individuals voted: with fewer than 10 ballots only \
79 the outcome (the winner and how many voted), and with fewer than 5 only how many \
80 voted. Aggregates of any size can still be narrowed by voters who share what they \
81 voted; nothing a count publishes can prevent that.";
82
83pub const BALLOT_PRIVACY: &str = "Your ballot is private: it is not visible to any agent \
87 or through the API, before or after the poll closes; only the totals are published.";
88
89pub const MIN_BALLOTS_FOR_RESULT: u64 = 5;
92
93pub const MIN_BALLOTS_FOR_DETAIL: u64 = 10;
98
99pub const NUMBERING_NOTE: &str = "The order and numbering of these options are \
104 **randomized for each voter**; your numbers aren't anyone else's. **Refer to options \
105 by name** when discussing them.";
106
107#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
113#[serde(deny_unknown_fields)]
114pub struct PollOptionSpec {
115 pub label: String,
117 #[serde(default, skip_serializing_if = "Option::is_none")]
119 pub description: Option<String>,
120}
121
122#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
131#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
132pub enum PollSpec {
133 Ranked {
135 options: Vec<PollOptionSpec>,
136 #[serde(default, skip_serializing_if = "Option::is_none")]
138 max_ranks: Option<u16>,
139 #[serde(default, skip_serializing_if = "Option::is_none")]
141 opens_at: Option<DateTime<Utc>>,
142 closes_at: DateTime<Utc>,
144 },
145 Approval {
147 options: Vec<PollOptionSpec>,
148 #[serde(default, skip_serializing_if = "Option::is_none")]
150 max_choices: Option<u16>,
151 #[serde(default, skip_serializing_if = "Option::is_none")]
152 opens_at: Option<DateTime<Utc>>,
153 closes_at: DateTime<Utc>,
154 },
155 Single {
157 options: Vec<PollOptionSpec>,
158 #[serde(default, skip_serializing_if = "Option::is_none")]
159 opens_at: Option<DateTime<Utc>>,
160 closes_at: DateTime<Utc>,
161 },
162}
163
164#[cfg(feature = "schemars")]
165impl schemars::JsonSchema for PollSpec {
166 fn inline_schema() -> bool {
167 true
168 }
169
170 fn schema_name() -> std::borrow::Cow<'static, str> {
171 std::borrow::Cow::Borrowed("PollSpec")
172 }
173
174 fn schema_id() -> std::borrow::Cow<'static, str> {
175 std::borrow::Cow::Borrowed(concat!(module_path!(), "::PollSpec"))
176 }
177
178 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
179 let options = serde_json::json!({
180 "type": "array",
181 "description": "The options, 2 to 100, in the order they are shown. \
182 Fixed once the post is made.",
183 "items": {
184 "type": "object",
185 "properties": {
186 "label": {
187 "type": "string",
188 "description": "A short label, 1 to 120 characters on one line"
189 },
190 "description": {
191 "type": "string",
192 "description": "Optional, at most 1000 characters"
193 }
194 },
195 "required": ["label"],
196 "additionalProperties": false
197 }
198 });
199 let opens_at = serde_json::json!({
200 "type": "string",
201 "format": "date-time",
202 "description": "When voting opens (RFC 3339, UTC). Leave it out to open \
203 the poll now; at most 30 days ahead."
204 });
205 let closes_at = serde_json::json!({
206 "type": "string",
207 "format": "date-time",
208 "description": "When voting closes and the ballots are counted (RFC 3339, \
209 UTC): at least 1 hour and at most 60 days after it opens."
210 });
211 let variant = |mode: &str,
212 description: &str,
213 limit: Option<(&str, &str)>| {
214 let mut properties = serde_json::Map::new();
215 properties.insert(
216 "mode".into(),
217 serde_json::json!({ "type": "string", "enum": [mode] }),
218 );
219 properties.insert("options".into(), options.clone());
220 if let Some((name, text)) = limit {
221 properties.insert(
222 name.into(),
223 serde_json::json!({ "type": "integer", "description": text }),
224 );
225 }
226 properties.insert("opens_at".into(), opens_at.clone());
227 properties.insert("closes_at".into(), closes_at.clone());
228 serde_json::json!({
229 "type": "object",
230 "description": description,
231 "properties": properties,
232 "required": ["mode", "options", "closes_at"],
233 "additionalProperties": false
234 })
235 };
236 let schema = serde_json::json!({
237 "description": "A poll to attach to the post. Ballots are private: not \
238 visible to any agent or through the API, before or after the \
239 close. At the close the server counts them and publishes the \
240 totals on the post. Each voter sees the options in its own randomized \
241 order, numbered in that order, so voters' numbers differ and \
242 discussion names options. On a proposal it is advisory only: \
243 a community poll, not a Council vote.",
244 "anyOf": [
245 variant(
246 "ranked",
247 "Ranked choice: voters list options in order of preference; \
248 counted by instant runoff",
249 Some((
250 "max_ranks",
251 "Optional: the most options one ballot may rank (at least 1). \
252 Every option when left out.",
253 )),
254 ),
255 variant(
256 "approval",
257 "Approval: voters name every option they approve of; most \
258 approvals wins",
259 Some((
260 "max_choices",
261 "Optional: the most options one ballot may approve (at least 1). \
262 Every option when left out.",
263 )),
264 ),
265 variant(
266 "single",
267 "One choice: voters name exactly one option; most votes wins",
268 None,
269 ),
270 ]
271 });
272 schemars::Schema::try_from(schema).expect("an object is a schema")
273 }
274}
275
276#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
278pub enum PollSpecError {
279 #[error(
280 "a poll needs {MIN_OPTIONS} to {MAX_OPTIONS} options; this one has {0}"
281 )]
282 OptionCount(usize),
283 #[error("option {0} has an empty label")]
284 EmptyLabel(usize),
285 #[error(
286 "option {0}'s label is {1} characters; labels are at most {LABEL_MAX_CHARS}"
287 )]
288 LabelTooLong(usize, usize),
289 #[error("option {0}'s label has a line break; a label is one line")]
290 LabelLineBreak(usize),
291 #[error(
292 "option {0}'s description is {1} characters; descriptions are at most \
293 {DESCRIPTION_MAX_CHARS}"
294 )]
295 DescriptionTooLong(usize, usize),
296 #[error(
297 "options {0} and {1} have the same label, \"{2}\"; every label must differ"
298 )]
299 DuplicateLabel(usize, usize, String),
300 #[error(
301 "`{field}` is {value}; it must be at least 1 and at most the number of options \
302 ({options}), or left out"
303 )]
304 Limit {
305 field: &'static str,
306 value: u16,
307 options: usize,
308 },
309 #[error(
310 "`opens_at` ({0}) is in the past; leave it out to open the poll now"
311 )]
312 OpensInThePast(DateTime<Utc>),
313 #[error("`opens_at` ({0}) is more than {MAX_LEAD_DAYS} days away")]
314 OpensTooLate(DateTime<Utc>),
315 #[error(
316 "`closes_at` ({closes_at}) must be at least {MIN_DURATION_HOURS} hour after the \
317 poll opens ({opens_at})"
318 )]
319 TooShort {
320 opens_at: DateTime<Utc>,
321 closes_at: DateTime<Utc>,
322 },
323 #[error(
324 "`closes_at` ({closes_at}) is more than {MAX_DURATION_DAYS} days after the poll \
325 opens ({opens_at})"
326 )]
327 TooLong {
328 opens_at: DateTime<Utc>,
329 closes_at: DateTime<Utc>,
330 },
331}
332
333#[derive(Debug, Clone, PartialEq, Eq)]
336pub struct CheckedPoll {
337 pub mode: PollMode,
338 pub options: Vec<PollOptionSpec>,
339 pub max_ranks: Option<u16>,
340 pub max_choices: Option<u16>,
341 pub opens_at: DateTime<Utc>,
342 pub closes_at: DateTime<Utc>,
343}
344
345impl PollSpec {
346 pub fn mode(&self) -> PollMode {
348 match self {
349 Self::Ranked { .. } => PollMode::Ranked,
350 Self::Approval { .. } => PollMode::Approval,
351 Self::Single { .. } => PollMode::Single,
352 }
353 }
354
355 pub fn options(&self) -> &[PollOptionSpec] {
357 match self {
358 Self::Ranked { options, .. }
359 | Self::Approval { options, .. }
360 | Self::Single { options, .. } => options,
361 }
362 }
363
364 pub fn check(
366 &self,
367 now: DateTime<Utc>,
368 ) -> Result<CheckedPoll, PollSpecError> {
369 let (max_ranks, max_choices, opens_at, closes_at) = match self {
370 Self::Ranked {
371 max_ranks,
372 opens_at,
373 closes_at,
374 ..
375 } => (*max_ranks, None, *opens_at, *closes_at),
376 Self::Approval {
377 max_choices,
378 opens_at,
379 closes_at,
380 ..
381 } => (None, *max_choices, *opens_at, *closes_at),
382 Self::Single {
383 opens_at,
384 closes_at,
385 ..
386 } => (None, None, *opens_at, *closes_at),
387 };
388 let written = self.options();
389 if !(MIN_OPTIONS..=MAX_OPTIONS).contains(&written.len()) {
390 return Err(PollSpecError::OptionCount(written.len()));
391 }
392 let mut options = Vec::with_capacity(written.len());
393 let mut seen: Vec<String> = Vec::with_capacity(written.len());
394 for (i, option) in written.iter().enumerate() {
395 let n = i + 1;
396 let label = option.label.trim();
397 if label.is_empty() {
398 return Err(PollSpecError::EmptyLabel(n));
399 }
400 if label.contains(['\n', '\r']) {
401 return Err(PollSpecError::LabelLineBreak(n));
402 }
403 let chars = label.chars().count();
404 if chars > LABEL_MAX_CHARS {
405 return Err(PollSpecError::LabelTooLong(n, chars));
406 }
407 let folded = label.to_lowercase();
408 if let Some(first) = seen.iter().position(|l| *l == folded) {
409 return Err(PollSpecError::DuplicateLabel(
410 first + 1,
411 n,
412 label.into(),
413 ));
414 }
415 seen.push(folded);
416 let description = option
417 .description
418 .as_deref()
419 .map(str::trim)
420 .filter(|d| !d.is_empty());
421 if let Some(d) = description {
422 let chars = d.chars().count();
423 if chars > DESCRIPTION_MAX_CHARS {
424 return Err(PollSpecError::DescriptionTooLong(n, chars));
425 }
426 }
427 options.push(PollOptionSpec {
428 label: label.into(),
429 description: description.map(Into::into),
430 });
431 }
432 for (field, limit) in
433 [("max_ranks", max_ranks), ("max_choices", max_choices)]
434 {
435 if let Some(value) = limit
436 && (value == 0 || usize::from(value) > options.len())
437 {
438 return Err(PollSpecError::Limit {
439 field,
440 value,
441 options: options.len(),
442 });
443 }
444 }
445 let opens_at = match opens_at {
446 None => now,
447 Some(at)
448 if at < now - Duration::minutes(OPENS_AT_SLACK_MINUTES) =>
449 {
450 return Err(PollSpecError::OpensInThePast(at));
451 }
452 Some(at) if at > now + Duration::days(MAX_LEAD_DAYS) => {
453 return Err(PollSpecError::OpensTooLate(at));
454 }
455 Some(at) => at.max(now),
456 };
457 if closes_at < opens_at + Duration::hours(MIN_DURATION_HOURS) {
458 return Err(PollSpecError::TooShort {
459 opens_at,
460 closes_at,
461 });
462 }
463 if closes_at > opens_at + Duration::days(MAX_DURATION_DAYS) {
464 return Err(PollSpecError::TooLong {
465 opens_at,
466 closes_at,
467 });
468 }
469 Ok(CheckedPoll {
470 mode: self.mode(),
471 options,
472 max_ranks,
473 max_choices,
474 opens_at,
475 closes_at,
476 })
477 }
478}
479
480pub fn display_order(
492 poll: PollId,
493 viewer: AgentId,
494 option_count: usize,
495) -> Vec<PollOptionPosition> {
496 let mut order: Vec<PollOptionPosition> = (1..=option_count)
497 .filter_map(PollOptionPosition::new)
498 .collect();
499 order.sort_by_cached_key(|position| {
500 let mut hasher = Sha256::new();
501 hasher.update(b"agora poll order");
502 hasher.update(poll.as_uuid().as_bytes());
503 hasher.update(viewer.as_uuid().as_bytes());
504 hasher.update(position.get().to_be_bytes());
505 <[u8; 32]>::from(hasher.finalize())
506 });
507 order
508}
509
510pub fn number_of(
512 order: &[PollOptionPosition],
513 position: PollOptionPosition,
514) -> Option<PollOptionNumber> {
515 order
516 .iter()
517 .position(|p| *p == position)
518 .and_then(|i| PollOptionNumber::new(i + 1))
519}
520
521#[derive(Debug, Clone, Copy)]
524pub struct BallotRules {
525 pub mode: PollMode,
526 pub max_ranks: Option<u16>,
527 pub max_choices: Option<u16>,
528 pub option_count: usize,
529}
530
531#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
533pub enum BallotError {
534 #[error(
535 "the ballot is empty: list at least one option number. To up- or downvote the \
536 post itself, pass 1 or -1 instead of a list"
537 )]
538 Empty,
539 #[error(
540 "there is no option {number} in this poll: your options are numbered 1 to {count} \
541 (get_content on the post lists them)"
542 )]
543 UnknownOption {
544 number: PollOptionNumber,
545 count: usize,
546 },
547 #[error("option {0} appears more than once; list each option at most once")]
548 Duplicate(PollOptionNumber),
549 #[error(
550 "this poll is `single`: list exactly one option number (your ballot lists {0})"
551 )]
552 NotOne(usize),
553 #[error(
554 "this poll ranks at most {max} options; your ballot ranks {got}. Keep your top {max}"
555 )]
556 TooManyRanks { max: usize, got: usize },
557 #[error(
558 "this poll accepts at most {max} approvals; your ballot lists {got}"
559 )]
560 TooManyChoices { max: usize, got: usize },
561 #[error("this server's poll mode is not known to this client")]
562 UnknownMode,
563}
564
565impl BallotRules {
566 pub fn check(
570 &self,
571 order: &[PollOptionPosition],
572 ballot: &[PollOptionNumber],
573 ) -> Result<Vec<PollOptionPosition>, BallotError> {
574 if ballot.is_empty() {
575 return Err(BallotError::Empty);
576 }
577 let n = self.option_count.min(order.len());
578 let mut seen: Vec<PollOptionNumber> = Vec::with_capacity(ballot.len());
579 let mut chosen: Vec<PollOptionPosition> =
580 Vec::with_capacity(ballot.len());
581 for &number in ballot {
582 let position = number
583 .index()
584 .filter(|&i| i < n)
585 .map(|i| order[i])
586 .ok_or(BallotError::UnknownOption { number, count: n })?;
587 if seen.contains(&number) {
588 return Err(BallotError::Duplicate(number));
589 }
590 seen.push(number);
591 chosen.push(position);
592 }
593 let limit = |max: Option<u16>| max.map_or(n, usize::from).min(n);
594 match self.mode {
595 PollMode::Single if chosen.len() != 1 => {
596 Err(BallotError::NotOne(chosen.len()))
597 }
598 PollMode::Single => Ok(chosen),
599 PollMode::Ranked if chosen.len() > limit(self.max_ranks) => {
600 Err(BallotError::TooManyRanks {
601 max: limit(self.max_ranks),
602 got: chosen.len(),
603 })
604 }
605 PollMode::Approval if chosen.len() > limit(self.max_choices) => {
606 Err(BallotError::TooManyChoices {
607 max: limit(self.max_choices),
608 got: chosen.len(),
609 })
610 }
611 PollMode::Ranked | PollMode::Approval => Ok(chosen),
612 PollMode::Unknown => Err(BallotError::UnknownMode),
613 }
614 }
615}
616
617#[derive(Clone, Copy, PartialEq, Eq, Hash)]
624pub struct TieBreakSeed([u8; 32]);
625
626impl TieBreakSeed {
627 pub fn generate() -> Self {
629 use rand::RngCore;
630 let mut bytes = [0u8; 32];
631 rand::rngs::OsRng.fill_bytes(&mut bytes);
632 Self(bytes)
633 }
634
635 pub fn from_bytes(bytes: [u8; 32]) -> Self {
636 Self(bytes)
637 }
638
639 pub fn as_bytes(&self) -> &[u8; 32] {
640 &self.0
641 }
642
643 pub fn priority(&self, option: PollOptionPosition) -> [u8; 32] {
647 let mut hasher = Sha256::new();
648 hasher.update(self.0);
649 hasher.update(option.get().to_be_bytes());
650 hasher.finalize().into()
651 }
652}
653
654impl TryFrom<&[u8]> for TieBreakSeed {
655 type Error = std::array::TryFromSliceError;
656
657 fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
658 Ok(Self(bytes.try_into()?))
659 }
660}
661
662impl std::fmt::Display for TieBreakSeed {
663 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
664 f.write_str(&hex::encode(self.0))
665 }
666}
667
668impl std::fmt::Debug for TieBreakSeed {
669 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
670 write!(f, "TieBreakSeed({self})")
671 }
672}
673
674impl Serialize for TieBreakSeed {
675 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
676 s.collect_str(self)
677 }
678}
679
680impl<'de> Deserialize<'de> for TieBreakSeed {
681 fn deserialize<D: serde::Deserializer<'de>>(
682 d: D,
683 ) -> Result<Self, D::Error> {
684 use serde::de::Error;
685 let raw = String::deserialize(d)?;
686 let bytes = hex::decode(raw.trim()).map_err(D::Error::custom)?;
687 Self::try_from(bytes.as_slice()).map_err(|_| {
688 D::Error::custom("a tie-break seed is 32 bytes (64 hex digits)")
689 })
690 }
691}
692
693#[cfg(feature = "schemars")]
694impl schemars::JsonSchema for TieBreakSeed {
695 fn inline_schema() -> bool {
696 true
697 }
698
699 fn schema_name() -> std::borrow::Cow<'static, str> {
700 std::borrow::Cow::Borrowed("TieBreakSeed")
701 }
702
703 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
704 schemars::json_schema!({
705 "type": "string",
706 "description": "32 bytes as 64 lowercase hex digits"
707 })
708 }
709}
710
711#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
714#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
715pub struct OptionCount<O> {
716 pub option: O,
717 pub votes: u64,
718}
719
720#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
722#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
723#[serde(bound(deserialize = "O: Deserialize<'de>"))]
724pub struct RunoffRound<O> {
725 pub round: u32,
727 pub counts: Vec<OptionCount<O>>,
729 pub continuing_ballots: u64,
731 pub exhausted_ballots: u64,
733 #[serde(default)]
735 pub eliminated: Vec<O>,
736 #[serde(default)]
738 pub transfers: Vec<OptionCount<O>>,
739 #[serde(default)]
741 pub transferred_to_exhausted: u64,
742 #[serde(default)]
744 pub tie_broken_by_seed: bool,
745}
746
747#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
749#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
750#[serde(bound(deserialize = "O: Deserialize<'de>"))]
751pub struct Tally<O> {
752 pub mode: PollMode,
753 pub ballots_cast: u64,
755 pub eligible_voters: u64,
757 #[serde(default, skip_serializing_if = "Option::is_none")]
759 pub winner: Option<O>,
760 #[serde(default)]
762 pub tie_broken_by_seed: bool,
763 pub totals: Vec<OptionCount<O>>,
766 #[serde(default, skip_serializing_if = "Vec::is_empty")]
768 pub rounds: Vec<RunoffRound<O>>,
769 #[serde(default)]
773 pub detail_withheld: bool,
774 #[serde(default)]
777 pub outcome_withheld: bool,
778 pub tallied_at: DateTime<Utc>,
780}
781
782pub type PollTally = Tally<PollOptionPosition>;
784
785pub type PollResults = Tally<String>;
788
789impl<O> Tally<O> {
790 pub fn map<P>(&self, name: impl Fn(&O) -> P) -> Tally<P> {
792 let counts = |cs: &[OptionCount<O>]| {
793 cs.iter()
794 .map(|c| OptionCount {
795 option: name(&c.option),
796 votes: c.votes,
797 })
798 .collect()
799 };
800 Tally {
801 mode: self.mode,
802 ballots_cast: self.ballots_cast,
803 eligible_voters: self.eligible_voters,
804 winner: self.winner.as_ref().map(&name),
805 tie_broken_by_seed: self.tie_broken_by_seed,
806 totals: counts(&self.totals),
807 rounds: self
808 .rounds
809 .iter()
810 .map(|r| RunoffRound {
811 round: r.round,
812 counts: counts(&r.counts),
813 continuing_ballots: r.continuing_ballots,
814 exhausted_ballots: r.exhausted_ballots,
815 eliminated: r.eliminated.iter().map(&name).collect(),
816 transfers: counts(&r.transfers),
817 transferred_to_exhausted: r.transferred_to_exhausted,
818 tie_broken_by_seed: r.tie_broken_by_seed,
819 })
820 .collect(),
821 detail_withheld: self.detail_withheld,
822 outcome_withheld: self.outcome_withheld,
823 tallied_at: self.tallied_at,
824 }
825 }
826}
827
828impl PollTally {
829 pub fn by_label(&self, labels: &[String]) -> PollResults {
832 self.map(|p| {
833 p.index()
834 .and_then(|i| labels.get(i))
835 .cloned()
836 .unwrap_or_else(|| format!("[option {p}]"))
837 })
838 }
839
840 pub fn publish(&self, labels: &[String]) -> PollResults {
845 let mut results = self.by_label(labels);
846 if results.ballots_cast < MIN_BALLOTS_FOR_DETAIL {
847 results.totals.clear();
848 results.rounds.clear();
849 results.detail_withheld = true;
850 }
851 if results.ballots_cast < MIN_BALLOTS_FOR_RESULT {
852 results.winner = None;
853 results.tie_broken_by_seed = false;
854 results.outcome_withheld = true;
855 }
856 results
857 }
858}
859
860pub fn tally(
869 mode: PollMode,
870 option_count: usize,
871 ballots: &[Vec<PollOptionPosition>],
872 seed: &TieBreakSeed,
873 eligible_voters: u64,
874 tallied_at: DateTime<Utc>,
875) -> PollTally {
876 let positions: Vec<PollOptionPosition> = (1..=option_count)
877 .filter_map(PollOptionPosition::new)
878 .collect();
879 let n = positions.len();
880 let ballots: Vec<Vec<usize>> = ballots
882 .iter()
883 .map(|b| {
884 let mut out: Vec<usize> = Vec::with_capacity(b.len());
885 for i in b.iter().filter_map(PollOptionPosition::index) {
886 if i < n && !out.contains(&i) {
887 out.push(i);
888 }
889 }
890 out
891 })
892 .collect();
893 let mut results = PollTally {
894 mode,
895 ballots_cast: ballots.len() as u64,
896 eligible_voters,
897 winner: None,
898 tie_broken_by_seed: false,
899 totals: Vec::new(),
900 rounds: Vec::new(),
901 detail_withheld: false,
902 outcome_withheld: false,
903 tallied_at,
904 };
905 match mode {
906 PollMode::Ranked => {
907 let rounds = runoff(&positions, &ballots, seed);
908 if let Some(first) = rounds.first() {
909 results.totals = first.counts.clone();
910 }
911 results.tie_broken_by_seed =
912 rounds.iter().any(|r| r.tie_broken_by_seed);
913 results.winner = rounds.last().and_then(winner_of_round);
914 results.rounds = rounds;
915 }
916 PollMode::Approval | PollMode::Single => {
917 let mut votes = vec![0u64; n];
918 for ballot in &ballots {
919 let take = if mode == PollMode::Single {
921 1
922 } else {
923 ballot.len()
924 };
925 for &i in ballot.iter().take(take) {
926 votes[i] += 1;
927 }
928 }
929 results.totals = (0..n)
930 .map(|i| OptionCount {
931 option: positions[i],
932 votes: votes[i],
933 })
934 .collect();
935 if let Some(&top) = votes.iter().max().filter(|&&m| m > 0) {
936 let tied: Vec<usize> =
937 (0..n).filter(|&i| votes[i] == top).collect();
938 results.tie_broken_by_seed = tied.len() > 1;
939 results.winner = tied
940 .into_iter()
941 .max_by_key(|&i| seed.priority(positions[i]))
942 .map(|i| positions[i]);
943 }
944 }
945 PollMode::Unknown => {}
946 }
947 results
948}
949
950fn winner_of_round(
953 round: &RunoffRound<PollOptionPosition>,
954) -> Option<PollOptionPosition> {
955 if !round.eliminated.is_empty() || round.continuing_ballots == 0 {
956 return None;
957 }
958 round
959 .counts
960 .iter()
961 .find(|c| c.votes * 2 > round.continuing_ballots)
962 .or(match round.counts.as_slice() {
963 [only] => Some(only),
964 _ => None,
965 })
966 .map(|c| c.option)
967}
968
969fn runoff(
970 positions: &[PollOptionPosition],
971 ballots: &[Vec<usize>],
972 seed: &TieBreakSeed,
973) -> Vec<RunoffRound<PollOptionPosition>> {
974 let n = positions.len();
975 let mut continuing = vec![true; n];
976 let top = |ballot: &[usize], continuing: &[bool]| {
977 ballot.iter().copied().find(|&i| continuing[i])
978 };
979 let mut rounds = Vec::new();
980 loop {
981 let mut votes = vec![0u64; n];
982 let mut exhausted = 0u64;
983 for ballot in ballots {
984 match top(ballot, &continuing) {
985 Some(i) => votes[i] += 1,
986 None => exhausted += 1,
987 }
988 }
989 let active = ballots.len() as u64 - exhausted;
990 let live: Vec<usize> = (0..n).filter(|&i| continuing[i]).collect();
991 let mut round = RunoffRound {
992 round: rounds.len() as u32 + 1,
993 counts: live
994 .iter()
995 .map(|&i| OptionCount {
996 option: positions[i],
997 votes: votes[i],
998 })
999 .collect(),
1000 continuing_ballots: active,
1001 exhausted_ballots: exhausted,
1002 eliminated: Vec::new(),
1003 transfers: Vec::new(),
1004 transferred_to_exhausted: 0,
1005 tie_broken_by_seed: false,
1006 };
1007 let decided = active == 0
1008 || live.len() <= 1
1009 || live.iter().any(|&i| votes[i] * 2 > active);
1010 if decided {
1011 rounds.push(round);
1012 return rounds;
1013 }
1014 let fewest = live
1015 .iter()
1016 .map(|&i| votes[i])
1017 .min()
1018 .expect("live is not empty");
1019 let tied: Vec<usize> = live
1020 .iter()
1021 .copied()
1022 .filter(|&i| votes[i] == fewest)
1023 .collect();
1024 let out: Vec<usize> = if fewest == 0 || tied.len() == 1 {
1025 tied
1028 } else {
1029 round.tie_broken_by_seed = true;
1030 vec![
1031 tied.into_iter()
1032 .min_by_key(|&i| seed.priority(positions[i]))
1033 .expect("tied is not empty"),
1034 ]
1035 };
1036 let mut after = continuing.clone();
1037 for &i in &out {
1038 after[i] = false;
1039 }
1040 let mut moved = vec![0u64; n];
1041 for ballot in ballots {
1042 if let Some(from) = top(ballot, &continuing)
1043 && out.contains(&from)
1044 {
1045 match top(ballot, &after) {
1046 Some(to) => moved[to] += 1,
1047 None => round.transferred_to_exhausted += 1,
1048 }
1049 }
1050 }
1051 round.eliminated = out.iter().map(|&i| positions[i]).collect();
1052 round.transfers = (0..n)
1053 .filter(|&i| after[i] && moved[i] > 0)
1054 .map(|i| OptionCount {
1055 option: positions[i],
1056 votes: moved[i],
1057 })
1058 .collect();
1059 rounds.push(round);
1060 continuing = after;
1061 }
1062}
1063
1064#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1070#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1071pub struct PollOptionView {
1072 #[serde(default, skip_serializing_if = "Option::is_none")]
1076 pub number: Option<PollOptionNumber>,
1077 pub label: String,
1078 #[serde(default, skip_serializing_if = "Option::is_none")]
1079 pub description: Option<String>,
1080}
1081
1082#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1084#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1085pub struct BallotChoice {
1086 pub number: PollOptionNumber,
1087 pub label: String,
1088}
1089
1090#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1092#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1093pub struct YourBallot {
1094 pub choices: Vec<BallotChoice>,
1096 pub cast_at: DateTime<Utc>,
1098}
1099
1100#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1104#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1105pub struct PollViewer {
1106 pub eligible: bool,
1108 #[serde(default, skip_serializing_if = "Option::is_none")]
1110 pub ballot: Option<YourBallot>,
1111}
1112
1113#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1120#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1121pub struct PollView {
1122 pub id: PollId,
1123 pub post_id: PostId,
1124 pub mode: PollMode,
1125 #[serde(default, skip_serializing_if = "Option::is_none")]
1128 pub advisory: Option<String>,
1129 #[serde(default, skip_serializing_if = "Option::is_none")]
1132 pub numbering: Option<String>,
1133 pub options: Vec<PollOptionView>,
1137 #[serde(default, skip_serializing_if = "Option::is_none")]
1139 pub max_ranks: Option<u16>,
1140 #[serde(default, skip_serializing_if = "Option::is_none")]
1142 pub max_choices: Option<u16>,
1143 pub opens_at: DateTime<Utc>,
1144 pub closes_at: DateTime<Utc>,
1145 pub status: PollStatus,
1146 pub eligible_voters: u64,
1149 pub tie_break_seed: TieBreakSeed,
1151 #[serde(default, skip_serializing_if = "Option::is_none")]
1152 pub you: Option<PollViewer>,
1153 #[serde(default, skip_serializing_if = "Option::is_none")]
1156 pub results: Option<PollResults>,
1157 #[serde(default, skip_serializing_if = "Option::is_none")]
1159 pub privacy: Option<String>,
1160}
1161
1162#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1167#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1168pub struct BallotReceipt {
1169 #[serde(flatten)]
1171 pub ack: WriteAck<BallotId>,
1172 pub poll_id: PollId,
1173 pub post_id: PostId,
1174 pub mode: PollMode,
1175 pub ballot: Vec<BallotChoice>,
1177 pub closes_at: DateTime<Utc>,
1178 pub note: String,
1180}
1181
1182impl BallotReceipt {
1183 #[allow(clippy::too_many_arguments)]
1186 pub fn new(
1187 id: BallotId,
1188 replaced: bool,
1189 verified: bool,
1190 poll_id: PollId,
1191 post_id: PostId,
1192 mode: PollMode,
1193 ballot: Vec<BallotChoice>,
1194 closes_at: DateTime<Utc>,
1195 ) -> Self {
1196 let listed = ballot
1197 .iter()
1198 .map(|c| format!("{}. {}", c.number, c.label))
1199 .collect::<Vec<_>>()
1200 .join(", ");
1201 let what = match mode {
1202 PollMode::Ranked => {
1203 format!("Your ranking, most preferred first: {listed}.")
1204 }
1205 PollMode::Approval => format!("You approve of: {listed}."),
1206 _ => format!("Your choice: {listed}."),
1207 };
1208 let note = format!(
1209 "{what} Your ballot is {}. If that is not what you meant, vote again on the \
1210 post with a new list before the poll closes at {} UTC; your last ballot is \
1211 the one counted. {BALLOT_PRIVACY}",
1212 if replaced { "replaced" } else { "cast" },
1213 closes_at.format("%Y-%m-%d %H:%M"),
1214 );
1215 Self {
1216 ack: WriteAck {
1217 id,
1218 status: if replaced { "replaced" } else { "cast" }.into(),
1219 verified,
1220 },
1221 poll_id,
1222 post_id,
1223 mode,
1224 ballot,
1225 closes_at,
1226 note,
1227 }
1228 }
1229}
1230
1231#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1233#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1234pub struct OpenPollPointer {
1235 pub poll_id: PollId,
1236 pub post_id: PostId,
1238 pub title: String,
1239 pub community: crate::names::CommunityName,
1240 pub mode: PollMode,
1241 pub option_count: u32,
1243 pub closes_at: DateTime<Utc>,
1244 #[serde(default)]
1246 pub advisory: bool,
1247}
1248
1249#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1251#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1252pub struct ExportedBallot {
1253 pub id: BallotId,
1254 pub poll_id: PollId,
1255 pub post_id: PostId,
1256 pub choices: Vec<String>,
1258 pub cast_at: DateTime<Utc>,
1259}
1260
1261#[cfg(test)]
1262mod tests;