sew-proto 0.11.6

Sew wire contracts: ids, addresses, errors, HTTP and gateway bodies, permissions, policies, audit.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! Read cursors, unread and mention counts, the threads inbox and boot sync.
//!
//! Nothing here is a stored counter: every count is computed by the server from cursors,
//! pointers and mention rows at read time. Every read-state object carries `seq`, the member's
//! change-log head it is current as of; a client keeps the copy with the higher `seq`.

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::api::messages::{Message, ThreadSummary};
use crate::error::{Validate, ValidationError};
use crate::gateway::server::ThreadsInbox;
use crate::id::{Id, IdList};
use crate::limits::{
    BULK_ACK_CHANNELS_MAX, BULK_ACK_THREADS_MAX, PAGE_LIMIT_DEFAULT, PAGE_LIMIT_MAX,
};

/// The cap of [`ReadState::unread_count`]: the value `99` means 99 or more.
pub const UNREAD_COUNT_CAP: u32 = 99;

/// Feature flag: `ReadState.unread_count`.
pub const FEATURE_READ_STATE_UNREAD_COUNT: &str = "read_state_unread_count";

fn is_false(b: &bool) -> bool {
    !*b
}

/// A member's read state in one channel.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct ReadState {
    /// The channel.
    pub channel_id: Id,
    /// The read cursor: a comparator, possibly a synthetic id (mark unread writes
    /// `message_id − 1`). Absent = nothing read.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_read_id: Option<Id>,
    /// The channel's newest timeline message (omitted in READY, where the channel entry has
    /// it).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_message_id: Option<Id>,
    /// Unread mentions (a muted channel counts direct mentions only).
    pub mention_count: u32,
    /// Whether a message by someone else is past the cursor.
    pub unread: bool,
    /// Since 0.10.0: how many timeline messages are past the cursor (the messages behind
    /// `unread`: top-level ones and replies also sent to the channel, live, that the member can
    /// read), capped at [`UNREAD_COUNT_CAP`]: `99` means 99 or more. `0` when `unread` is false.
    /// Older servers leave it out (read as `0`; use `unread`).
    #[serde(default)]
    pub unread_count: u32,
    /// The member muted the channel; present only when true.
    #[serde(default, skip_serializing_if = "is_false")]
    pub muted: bool,
    /// The member change-log head this state is current as of.
    #[serde(default)]
    pub seq: u64,
}

impl ReadState {
    /// A `ReadState` with its required fields: every count 0, every flag `false` and every
    /// optional field unset.
    pub fn new(channel_id: Id) -> Self {
        ReadState {
            channel_id,
            last_read_id: None,
            last_message_id: None,
            mention_count: 0,
            unread: false,
            unread_count: 0,
            muted: false,
            seq: 0,
        }
    }
}

/// A member's read state in one thread.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct ThreadReadState {
    /// The thread root.
    pub root_id: Id,
    /// The root's channel (always set by current servers).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub channel_id: Option<Id>,
    /// The thread cursor; the root id when no reply was read (always set by current servers).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_read_id: Option<Id>,
    /// The newest live reply.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_reply_id: Option<Id>,
    /// Whether a reply is past the cursor.
    #[serde(default)]
    pub unread: bool,
    /// Live replies past the cursor (exact, no cap).
    #[serde(default)]
    pub unread_replies: u32,
    /// Unread mentions in the thread.
    #[serde(default)]
    pub mention_count: u32,
    /// Whether the member follows the thread.
    #[serde(default)]
    pub following: bool,
    /// The member change-log head this state is current as of.
    #[serde(default)]
    pub seq: u64,
}

impl ThreadReadState {
    /// A `ThreadReadState` with its required fields: every count 0, every flag `false` and
    /// every optional field unset.
    pub fn new(root_id: Id) -> Self {
        ThreadReadState {
            root_id,
            channel_id: None,
            last_read_id: None,
            last_reply_id: None,
            unread: false,
            unread_replies: 0,
            mention_count: 0,
            following: false,
            seq: 0,
        }
    }
}

/// Body of `POST /api/v1/channels/{id}/ack` and `POST /api/v1/threads/{root_id}/ack`: move
/// the cursor forward (never backward).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct AckRequest {
    /// The newest message read; absent = the newest message now.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message_id: Option<Id>,
}

impl Validate for AckRequest {
    fn validate(&self) -> Result<(), ValidationError> {
        Ok(())
    }
}

/// Body of `POST /api/v1/channels/{id}/mark_unread` and `/threads/{root_id}/mark_unread`:
/// the cursor moves back to just before `message_id`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct MarkUnreadRequest {
    /// The first message to show as unread.
    pub message_id: Id,
}

impl Validate for MarkUnreadRequest {
    fn validate(&self) -> Result<(), ValidationError> {
        Ok(())
    }
}

/// One channel of a bulk ack.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct AckItem {
    /// The channel.
    pub channel_id: Id,
    /// The newest message read; absent = the newest now.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message_id: Option<Id>,
}

/// One thread of a bulk ack.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ThreadAckItem {
    /// The thread root.
    pub root_id: Id,
    /// The newest reply read; absent = the newest now.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message_id: Option<Id>,
}

/// Body of `POST /api/v1/me/read_states/ack` ("mark all read").
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct BulkAckRequest {
    /// Channels, 0–500, unique.
    #[serde(default)]
    pub channels: Vec<AckItem>,
    /// Threads, 0–500, unique.
    #[serde(default)]
    pub threads: Vec<ThreadAckItem>,
    /// Also ack every thread of each listed channel the member follows or has an unread
    /// mention in.
    #[serde(default)]
    pub include_threads: bool,
}

impl Validate for BulkAckRequest {
    fn validate(&self) -> Result<(), ValidationError> {
        if self.channels.is_empty() && self.threads.is_empty() {
            return Err(ValidationError::invalid(
                "channels",
                "a bulk ack needs at least one channel or thread",
            ));
        }
        if self.channels.len() > BULK_ACK_CHANNELS_MAX {
            return Err(ValidationError::invalid(
                "channels",
                format!("at most {BULK_ACK_CHANNELS_MAX} channels"),
            ));
        }
        if self.threads.len() > BULK_ACK_THREADS_MAX {
            return Err(ValidationError::invalid(
                "threads",
                format!("at most {BULK_ACK_THREADS_MAX} threads"),
            ));
        }
        let mut seen = std::collections::HashSet::new();
        if !self.channels.iter().all(|c| seen.insert(c.channel_id)) {
            return Err(ValidationError::invalid(
                "channels",
                "channel ids must be unique",
            ));
        }
        let mut seen = std::collections::HashSet::new();
        if !self.threads.iter().all(|t| seen.insert(t.root_id)) {
            return Err(ValidationError::invalid(
                "threads",
                "thread root ids must be unique",
            ));
        }
        Ok(())
    }
}

/// Response of `POST /api/v1/me/read_states/ack`, and the `read_states_bulk_updated` event.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct BulkAckResponse {
    /// Every processed visible channel.
    pub read_states: Vec<ReadState>,
    /// Every processed thread.
    pub threads: Vec<ThreadReadState>,
    /// The threads inbox after the ack.
    pub threads_inbox: ThreadsInbox,
    /// More implied threads than `bulk_max_threads`: repeat the call.
    pub threads_truncated: bool,
}

/// Response of the thread ack and mark-unread routes, and the `thread_read_updated` event.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ThreadReadUpdated {
    /// The thread's read state.
    pub thread: ThreadReadState,
    /// Exact inbox totals; absent means "per-thread change only".
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub inbox: Option<ThreadsInbox>,
}

/// Query of `GET /api/v1/me/read_states`.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ReadStatesQuery {
    /// 1–100 channel ids; absent = every channel of the caller's sync set.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub channel_ids: Option<IdList>,
}

impl Validate for ReadStatesQuery {
    fn validate(&self) -> Result<(), ValidationError> {
        Ok(())
    }
}

/// Query of `GET /api/v1/me/thread_reads`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ThreadReadsQuery {
    /// 1–100 thread root ids.
    pub root_ids: IdList,
}

impl Validate for ThreadReadsQuery {
    fn validate(&self) -> Result<(), ValidationError> {
        Ok(())
    }
}

unit_enum! {
    /// Which threads `GET /api/v1/me/threads` lists.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum ThreadsInboxFilter {
        /// Followed threads and threads with an unread mention.
        All = "all",
        /// Only those that are unread or have an unread mention.
        Unread = "unread",
    }
}

/// Query of `GET /api/v1/me/threads`: pages by `activity_id`, newest first (an exception
/// to the general paging rules).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ThreadsInboxQuery {
    /// Threads whose `activity_id` is below this.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub before: Option<Id>,
    /// Page size, 1–100 (default 50).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    /// `all` (default) or `unread`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub filter: Option<ThreadsInboxFilter>,
}

impl ThreadsInboxQuery {
    /// The page size, default 50.
    pub fn limit(&self) -> u32 {
        self.limit.unwrap_or(PAGE_LIMIT_DEFAULT)
    }
}

impl Validate for ThreadsInboxQuery {
    fn validate(&self) -> Result<(), ValidationError> {
        if let Some(l) = self.limit
            && !(1..=PAGE_LIMIT_MAX).contains(&l)
        {
            return Err(ValidationError::invalid(
                "limit",
                format!("limit must be 1–{PAGE_LIMIT_MAX}"),
            ));
        }
        if self.filter.is_some_and(ThreadsInboxFilter::is_unknown) {
            return Err(ValidationError::invalid(
                "filter",
                "filter is all or unread",
            ));
        }
        Ok(())
    }
}

/// One row of `GET /api/v1/me/threads`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ThreadInboxItem {
    /// The newest reply, or the root when there is none: the sort key and `before` cursor.
    pub activity_id: Id,
    /// The root, rendered for the caller (a tombstone for a deleted root).
    pub root: Message,
    /// The thread summary (`following` for the caller).
    pub thread: ThreadSummary,
    /// The caller's read state in the thread.
    pub read: ThreadReadState,
}

/// One channel of `GET /api/v1/me/sync`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct SyncChannel {
    /// The channel.
    pub id: Id,
    /// Its change-log head.
    pub head_seq: u64,
    /// Its change-log floor.
    pub floor_seq: u64,
    /// Its newest timeline message.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_message_id: Option<Id>,
}

/// Response of `GET /api/v1/me/threads`.
pub type ThreadInboxPage = crate::http::Page<ThreadInboxItem>;
/// Response of `GET /api/v1/me/read_states` (`has_more` is always false).
pub type ReadStatesPage = crate::http::Page<ReadState>;
/// Response of `GET /api/v1/me/thread_reads` (`has_more` is always false).
pub type ThreadReadsPage = crate::http::Page<ThreadReadState>;

/// Response of `GET /api/v1/me/sync`: READY's sync section over HTTP, read in one snapshot
/// (agents and clients without a socket).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct MeSync {
    /// The install.
    pub install_id: Id,
    /// The install's sync epoch (opaque; a change means "drop everything").
    pub sync_epoch: String,
    /// The caller.
    pub member_id: Id,
    /// The caller's member change-log head.
    pub member_seq: u64,
    /// Every channel of the caller's sync set, ascending id.
    pub channels: Vec<SyncChannel>,
    /// Read states of those channels.
    pub read_states: Vec<ReadState>,
    /// The threads inbox summary.
    pub threads_inbox: ThreadsInbox,
}

impl MeSync {
    /// A `MeSync` with its required fields: every count 0 and every list empty.
    pub fn new(
        install_id: Id,
        sync_epoch: impl Into<String>,
        member_id: Id,
        threads_inbox: ThreadsInbox,
    ) -> Self {
        MeSync {
            install_id,
            sync_epoch: sync_epoch.into(),
            member_id,
            member_seq: 0,
            channels: Vec::new(),
            read_states: Vec::new(),
            threads_inbox,
        }
    }
}