Skip to main content

postvak_core/daemon/
wire.rs

1//! The messages clients and the daemon exchange, one JSON object per line; these types are the protocol.
2use serde::{Deserialize, Serialize};
3
4use crate::sync::{Activity, Command, Event};
5
6pub const PROTOCOL: u32 = 1;
7pub const VERSION: &str = env!("CARGO_PKG_VERSION");
8
9#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
10#[serde(rename_all = "snake_case")]
11pub enum ClientMessage {
12    Hello {
13        protocol: u32,
14        version: String,
15    },
16    Subscribe {
17        id: u64,
18    },
19    Status {
20        id: u64,
21    },
22    Shutdown {
23        id: u64,
24    },
25    Command {
26        id: u64,
27        account: String,
28        command: Command,
29    },
30}
31
32#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
33#[serde(rename_all = "snake_case")]
34pub enum DaemonMessage {
35    Hello {
36        protocol: u32,
37        version: String,
38        pid: u32,
39    },
40    Reply {
41        id: u64,
42        outcome: Outcome,
43    },
44    Event(Event),
45}
46
47#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
48#[serde(rename_all = "snake_case")]
49pub enum Outcome {
50    Ok(Payload),
51    Error(String),
52}
53
54#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
55#[serde(rename_all = "snake_case")]
56pub enum Payload {
57    Done,
58    Event(Event),
59    Status(Status),
60}
61
62#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
63pub struct Status {
64    pub pid: u32,
65    pub version: String,
66    pub uptime_secs: u64,
67    pub clients: usize,
68    pub accounts: Vec<AccountStatus>,
69}
70
71#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
72pub struct AccountStatus {
73    pub name: String,
74    pub activity: Option<Activity>,
75}
76
77/// One message per line.
78pub fn write_line(out: &mut impl std::io::Write, message: &impl Serialize) -> std::io::Result<()> {
79    out.write_all(line(message)?.as_bytes())
80}
81
82/// The message as one JSON line, newline included; serde_json escapes any newline inside it.
83pub(crate) fn line(message: &impl Serialize) -> std::io::Result<String> {
84    let mut text = serde_json::to_string(message)?;
85    text.push('\n');
86    Ok(text)
87}