zaun_community_protocol/client/event.rs
1//! What [`super::Session::receive`] and [`super::Session::poll_timeouts`] report.
2
3use std::fmt;
4
5use serde::de::DeserializeOwned;
6use serde_json::value::RawValue;
7
8use super::{ClientError, VerifiedWelcome, WelcomeError, decode_response};
9use crate::command::Body;
10use crate::command::object::Stream;
11use crate::envelope::{ErrorBody, EventEnvelope};
12use crate::event::Event;
13use crate::framing::DiscardReason;
14use crate::ids::{ChannelId, RequestId};
15
16/// One outcome for the application.
17#[derive(Debug, Clone)]
18pub enum ClientEvent {
19 /// The welcome verified: commands may be sent (§6.2).
20 Welcome(Box<VerifiedWelcome>),
21 /// The welcome failed verification; the session is dead and SHOULD alert the user.
22 WelcomeRejected(WelcomeError),
23 /// A final response to a command.
24 Response(Response),
25 /// A transient error (`BUSY`, `RATE_LIMITED`, `SLOWMODE_ACTIVE`, `INTERNAL`): the same
26 /// request is resent at `retry_at_ms` (§7.3). For the session's own `sync.ack` refused
27 /// with `RATE_LIMITED` (`kind` `"sync.ack"`, a `request_id` the application never saw) a
28 /// new ack with the cursors current at `retry_at_ms` is sent instead (§10.5); nothing
29 /// needs doing.
30 Retrying {
31 /// The request.
32 request_id: RequestId,
33 /// Its command name.
34 kind: &'static str,
35 /// The transient error.
36 error: ErrorBody,
37 /// When it is resent.
38 retry_at_ms: u64,
39 },
40 /// No response within the give-up time (24 h, §7.3); the request is abandoned.
41 GaveUp {
42 /// The request.
43 request_id: RequestId,
44 /// Its command name.
45 kind: &'static str,
46 },
47 /// A catalogue event applied in stream order (§9.4, §10).
48 Event(Box<ReceivedEvent>),
49 /// A sequence gap; the session has sent `sync.resume` to repair it (§10).
50 Gap(Gap),
51 /// A stream is older than the host's retention: take a snapshot (member stream) or page
52 /// `message.history` (channel), then reset its cursor (§10.2).
53 ResyncRequired {
54 /// The stream.
55 stream: Stream,
56 /// The channel, for a channel stream.
57 channel_id: Option<ChannelId>,
58 },
59 /// Something was received and ignored safely.
60 ProtocolError(ProtocolError),
61}
62
63/// A final response. `Debug` hides the body, which may embed a secret (an invitation link).
64#[derive(Clone)]
65pub struct Response {
66 /// The request it answers.
67 pub request_id: RequestId,
68 /// The command name.
69 pub kind: &'static str,
70 /// The `ok` body exactly as received, or the error.
71 pub result: Result<Box<RawValue>, ErrorBody>,
72}
73
74impl Response {
75 /// Decodes a successful body as `B`'s response type.
76 ///
77 /// # Errors
78 /// `Err(Some(error))` for an error response, `Err(None)` for a body that is not a `B`
79 /// response.
80 pub fn decode<B: Body>(&self) -> Result<B::Response, Option<ErrorBody>>
81 where
82 B::Response: DeserializeOwned,
83 {
84 match &self.result {
85 Ok(raw) => decode_response::<B>(raw).map_err(|_| None),
86 Err(e) => Err(Some(e.clone())),
87 }
88 }
89}
90
91impl fmt::Debug for Response {
92 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93 let result: Result<usize, &ErrorBody> = match &self.result {
94 Ok(raw) => Ok(raw.get().len()),
95 Err(e) => Err(e),
96 };
97 f.debug_struct("Response")
98 .field("request_id", &self.request_id)
99 .field("kind", &self.kind)
100 .field("result(body_len)", &result)
101 .finish()
102 }
103}
104
105/// A received event: the envelope (sequence, timestamp, actor) and its decoded body.
106#[derive(Debug, Clone)]
107pub struct ReceivedEvent {
108 /// The validated envelope.
109 pub envelope: EventEnvelope,
110 /// The decoded body.
111 pub event: Event,
112}
113
114/// A detected gap in a sequenced stream.
115#[derive(Debug, Clone, Copy, PartialEq, Eq)]
116pub struct Gap {
117 /// The stream.
118 pub stream: Stream,
119 /// The channel, for a channel stream.
120 pub channel_id: Option<ChannelId>,
121 /// The next sequence the client needs.
122 pub expected: u64,
123 /// The sequence that arrived.
124 pub received: u64,
125}
126
127/// Input ignored safely (§5.2, §5.3, §1.1, §9.4).
128#[derive(Debug, Clone, PartialEq, Eq)]
129pub enum ProtocolError {
130 /// Text without the `zaun:` prefix.
131 NotProtocol,
132 /// An unknown frame prefix (`zaun:2:` …).
133 UnknownPrefix,
134 /// A malformed fragment header.
135 MalformedFragment,
136 /// A fragment reassembly was discarded.
137 FragmentDiscarded(DiscardReason),
138 /// An envelope above `max_frame`.
139 TooLarge,
140 /// Not a valid response, event or batch envelope.
141 MalformedEnvelope,
142 /// A batch inside a batch, or a batch element for another community.
143 BadBatch,
144 /// An event whose `v` is not the negotiated version (dropped, §1.1).
145 WrongVersion(u16),
146 /// An event for another community than the session's.
147 WrongCommunity,
148 /// A known event type with a malformed body; its cursor still advances.
149 MalformedEvent(String),
150 /// An error response with `request_id: null` (§5.3).
151 UncorrelatedError(ErrorBody),
152 /// An event before a verified welcome or after a failed one (dropped).
153 NotReady,
154 /// A binding response names another community than the one requested; not bound.
155 BindingMismatch,
156 /// An automatic `sync.resume` or `sync.ack` could not be prepared.
157 AutoSend(ClientError),
158}