Skip to main content

arin_protocol/
daemon.rs

1//! Daemon to client messages.
2
3use crate::geom::{DisplayInfo, LogicalPoint};
4use crate::ids::{AnnotationId, SessionId};
5use serde::{Deserialize, Serialize};
6
7/// Anything the daemon can send.
8#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
9#[serde(tag = "type", rename_all = "snake_case")]
10pub enum DaemonMessage {
11    /// A client message was accepted.
12    Ack(Ack),
13    /// An annotation is no longer valid.
14    Invalidated(Invalidated),
15    /// A client message was rejected.
16    Error(ProtocolError),
17}
18
19/// A client message was accepted.
20///
21/// A session start acks with `session_id` and no annotation. Everything else acks with
22/// `annotation_id`. Resolver-backed requests additionally carry what was resolved and
23/// how confident the resolver was.
24#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
25pub struct Ack {
26    /// Present on the ack for a session start.
27    #[serde(default, skip_serializing_if = "Option::is_none")]
28    pub session_id: Option<SessionId>,
29    /// Present on the ack for an annotation.
30    #[serde(default, skip_serializing_if = "Option::is_none")]
31    pub annotation_id: Option<AnnotationId>,
32    /// Where a query landed. Only for query-form requests.
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    pub resolved_coords: Option<LogicalPoint>,
35    /// How sure the resolver was, in `0.0..=1.0`. Only for query-form requests.
36    ///
37    /// The daemon, not the client, decides what to draw from this. It is reported so
38    /// clients can phrase themselves honestly, not so they can pick a rendering.
39    #[serde(default, skip_serializing_if = "Option::is_none")]
40    pub confidence: Option<f64>,
41    /// Scale and size of the display involved, so clients can convert screenshot pixels.
42    #[serde(default, skip_serializing_if = "Option::is_none")]
43    pub display: Option<DisplayInfo>,
44}
45
46impl Ack {
47    /// Ack a session start.
48    pub fn session(session_id: SessionId) -> Self {
49        Self {
50            session_id: Some(session_id),
51            ..Self::default()
52        }
53    }
54
55    /// Ack an annotation.
56    pub fn annotation(annotation_id: AnnotationId) -> Self {
57        Self {
58            annotation_id: Some(annotation_id),
59            ..Self::default()
60        }
61    }
62
63    /// Attach display metadata.
64    #[must_use]
65    pub fn with_display(mut self, display: DisplayInfo) -> Self {
66        self.display = Some(display);
67        self
68    }
69
70    /// Attach what a resolver produced.
71    #[must_use]
72    pub fn with_resolution(mut self, coords: LogicalPoint, confidence: f64) -> Self {
73        self.resolved_coords = Some(coords);
74        self.confidence = Some(confidence);
75        self
76    }
77}
78
79/// An annotation is no longer valid and has been removed.
80#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
81pub struct Invalidated {
82    /// The annotation that went away. Absent when a whole display was invalidated.
83    #[serde(default, skip_serializing_if = "Option::is_none")]
84    pub annotation_id: Option<AnnotationId>,
85    /// Why.
86    pub reason: InvalidationReason,
87}
88
89impl Invalidated {
90    /// One annotation went away.
91    pub fn one(annotation_id: AnnotationId, reason: InvalidationReason) -> Self {
92        Self {
93            annotation_id: Some(annotation_id),
94            reason,
95        }
96    }
97}
98
99/// Why an annotation was invalidated.
100#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
101#[serde(rename_all = "snake_case")]
102pub enum InvalidationReason {
103    /// Content moved under the annotation.
104    ///
105    /// In 0.1 a scroll invalidates every annotation on that display. Later versions
106    /// translate annotations with the scroll and only invalidate when they cannot.
107    Scroll,
108    /// A display was added, removed, or reconfigured.
109    DisplayChange,
110    /// The owning session ended, or its socket disconnected.
111    SessionEnd,
112    /// The annotation's time to live expired.
113    Ttl,
114    /// The user cleared it, from the menu bar or the global hotkey.
115    ///
116    /// Distinct from `session_end` because the client did not ask for it and may want to
117    /// say so. The clear affordance belongs to the user, not to the agent driving.
118    Cleared,
119    /// A reason introduced by a newer daemon than this build knows about.
120    #[serde(untagged)]
121    Unknown(String),
122}
123
124/// A client message was rejected.
125#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
126pub struct ProtocolError {
127    /// Machine-readable cause.
128    pub code: ErrorCode,
129    /// Human-readable detail. Never load bearing, so do not parse it.
130    pub msg: String,
131}
132
133impl ProtocolError {
134    /// Build an error.
135    pub fn new(code: ErrorCode, msg: impl Into<String>) -> Self {
136        Self {
137            code,
138            msg: msg.into(),
139        }
140    }
141}
142
143/// Machine-readable rejection causes.
144#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
145#[serde(rename_all = "snake_case")]
146pub enum ErrorCode {
147    /// The message parsed as JSON but is not a valid message.
148    BadSchema,
149    /// The `type` field names a message this daemon does not implement.
150    UnknownType,
151    /// The line exceeded [`crate::MAX_PAYLOAD_BYTES`].
152    PayloadTooLarge,
153    /// A query-form request arrived with no resolver configured.
154    NoResolver,
155    /// A resolver exists, and the user has not permitted this daemon to ground for a
156    /// client.
157    ///
158    /// Distinct from [`Self::NoResolver`], which says grounding is not set up. This says it
159    /// is set up and was refused, which is a different thing for a client to do something
160    /// about: one is a configuration problem and the other is a person declining.
161    ///
162    /// Drawing is never refused this way. Any peer that reaches the socket can draw, since
163    /// a process running as the user could open its own window and draw anyway. Grounding
164    /// is the only capability Arin actually holds, because it is the one backed by the
165    /// Screen Recording grant.
166    NotPermitted,
167    /// A resolver ran and could not ground the query.
168    ResolveFailed,
169    /// The `display_id` does not name a connected display.
170    UnknownDisplay,
171    /// The annotation exists but belongs to a different session.
172    NotOwner,
173    /// The `v` field names an incompatible major version.
174    VersionUnsupported,
175    /// A code introduced by a newer daemon than this build knows about.
176    #[serde(untagged)]
177    Unknown(String),
178}
179
180impl ErrorCode {
181    /// The wire spelling of this code.
182    pub fn as_str(&self) -> &str {
183        match self {
184            Self::BadSchema => "bad_schema",
185            Self::UnknownType => "unknown_type",
186            Self::PayloadTooLarge => "payload_too_large",
187            Self::NoResolver => "no_resolver",
188            Self::NotPermitted => "not_permitted",
189            Self::ResolveFailed => "resolve_failed",
190            Self::UnknownDisplay => "unknown_display",
191            Self::NotOwner => "not_owner",
192            Self::VersionUnsupported => "version_unsupported",
193            Self::Unknown(s) => s,
194        }
195    }
196}
197
198impl std::fmt::Display for ErrorCode {
199    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
200        f.write_str(self.as_str())
201    }
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207
208    #[test]
209    fn unknown_codes_survive_a_round_trip() {
210        let json = r#""teleported_into_the_sun""#;
211        let code: ErrorCode = serde_json::from_str(json).unwrap();
212        assert_eq!(code, ErrorCode::Unknown("teleported_into_the_sun".into()));
213        assert_eq!(serde_json::to_string(&code).unwrap(), json);
214    }
215
216    #[test]
217    fn known_codes_take_priority_over_the_fallback() {
218        assert_eq!(
219            serde_json::from_str::<ErrorCode>(r#""not_owner""#).unwrap(),
220            ErrorCode::NotOwner
221        );
222        assert_eq!(
223            serde_json::from_str::<InvalidationReason>(r#""display_change""#).unwrap(),
224            InvalidationReason::DisplayChange
225        );
226    }
227}