Skip to main content

zaun_community_protocol/command/sync/
validate.rs

1//! State-free checks of the synchronization commands.
2
3use super::{Ack, Events, Resume, Snapshot, SnapshotPart};
4use crate::command::object::Stream;
5use crate::command::{BodyError, Validate, check};
6use crate::limits::{ACK_CHANNELS, PAGE_LARGE, RESUME_CHANNELS, SNAPSHOT_PAGE};
7
8impl Validate for Snapshot {
9    /// The `community` part has one item, so it takes no `after`.
10    fn validate(&self) -> Result<(), BodyError> {
11        if let Some(limit) = self.limit {
12            check::page(limit, SNAPSHOT_PAGE)?;
13        }
14        if self.part == SnapshotPart::Community && self.after.is_some() {
15            return Err(BodyError::bad("after", "the community part has one item"));
16        }
17        Ok(())
18    }
19}
20
21impl Validate for Events {
22    fn validate(&self) -> Result<(), BodyError> {
23        check::page(self.limit, PAGE_LARGE)?;
24        check::json_safe("after", self.after)?;
25        match (self.stream, self.channel_id) {
26            (Stream::Channel, None) => Err(BodyError::bad(
27                "channel_id",
28                "required for the channel stream",
29            )),
30            (Stream::Member, Some(_)) => Err(BodyError::bad(
31                "channel_id",
32                "not allowed for the member stream",
33            )),
34            (Stream::Live, _) => Err(BodyError::bad(
35                "stream",
36                "the live stream is not recoverable",
37            )),
38            (Stream::Channel, Some(_)) | (Stream::Member, None) => Ok(()),
39        }
40    }
41}
42
43impl Validate for Resume {
44    fn validate(&self) -> Result<(), BodyError> {
45        check::json_safe("member_after", self.member_after)?;
46        check::count("channels", self.channels.len(), RESUME_CHANNELS)?;
47        check::unique("channels", self.channels.iter().map(|c| &c.channel_id))?;
48        self.channels
49            .iter()
50            .try_for_each(|c| check::json_safe("channels", c.after))
51    }
52}
53
54impl Validate for Ack {
55    fn validate(&self) -> Result<(), BodyError> {
56        check::json_safe("member", self.member)?;
57        check::count("channels", self.channels.len(), ACK_CHANNELS)?;
58        check::unique("channels", self.channels.iter().map(|c| &c.channel_id))?;
59        self.channels
60            .iter()
61            .try_for_each(|c| check::json_safe("channels", c.seq))
62    }
63}