menger_notes/events.rs
1//! What the `notes` service streams ([`NotesEvent`]) and what it says a
2//! note is ([`Note`], [`HistoryRow`], [`Present`]). Every method returns `impl
3//! Stream<Item = NotesEvent>`; a refusal is in band.
4
5use serde::{Deserialize, Serialize};
6
7/// A note: its id, its organization, its title and markdown body, its
8/// revision now (every write keeps one), who made it and who wrote it last.
9#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
10pub struct Note {
11 /// Its id, 8 characters of Crockford's base32 (`7k3mq2xa`); the app opens it at `#/note/<id>`.
12 pub id: String,
13 /// The organization it is in (`acme`): who may read and write it is the roles held there.
14 pub org: String,
15 pub title: String,
16 /// The markdown, byte for byte — absent from a list's rows and a watch of every note.
17 #[serde(default, skip_serializing_if = "Option::is_none")]
18 pub body: Option<String>,
19 /// The body's size, in bytes.
20 pub bytes: u64,
21 /// The revision it is at: the `seq` of its last change (1 when made, one more with every change).
22 pub revision: u32,
23 /// When it was made (unix seconds), and by whom.
24 pub created_at: i64,
25 pub created_by: String,
26 /// When it was last written (unix seconds), and by whom.
27 pub at: i64,
28 pub by: String,
29}
30
31impl Note {
32 /// The same note without its body — a list's row.
33 pub fn summary(&self) -> Note {
34 Note { body: None, ..self.clone() }
35 }
36}
37
38/// One change of a note, as `history` lists it.
39#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
40pub struct HistoryRow {
41 pub id: String,
42 /// Its place in the note's changes, from 1; `replay { seq }` stands the note there.
43 pub seq: u32,
44 /// What it was: `create`, `update` (a live edit), `save` (a whole body, merged), `rename`, `delete`, or `snapshot` (a squash of every change up to it).
45 pub kind: String,
46 /// When, in unix milliseconds.
47 pub at: i64,
48 /// Who: their name, and their principal.
49 pub by: String,
50 pub principal: String,
51 /// The update's size, in bytes.
52 pub bytes: u64,
53 /// The title it set (`create`, `rename`, `snapshot`).
54 #[serde(default, skip_serializing_if = "Option::is_none")]
55 pub title: Option<String>,
56 /// A snapshot's: who wrote what in the changes it holds.
57 #[serde(default, skip_serializing_if = "Option::is_none")]
58 pub authors: Option<Vec<Author>>,
59}
60
61/// Who wrote what in a squashed run of changes.
62#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
63pub struct Author {
64 pub by: String,
65 pub principal: String,
66 /// How many changes, and their bytes.
67 pub changes: u32,
68 pub bytes: u64,
69 /// The first and the last, in unix milliseconds.
70 pub first: i64,
71 pub last: i64,
72}
73
74/// V2-31: a snapshot's `bytes` shared among its `authors` by what each
75/// wrote (their `bytes`): each the floor of their part, what is left one
76/// byte apiece to the largest writers first (then by principal) — so the
77/// shares sum to the snapshot's bytes, the same every time it is asked. No
78/// writing at all: the first author holds it. What `notes.bytes` charges
79/// each author of a squash, and what `notes.usage` counts.
80pub fn shares(bytes: u64, authors: &[Author]) -> Vec<(String, u64)> {
81 let total: u128 = authors.iter().map(|a| a.bytes as u128).sum();
82 if authors.is_empty() {
83 return Vec::new();
84 }
85 if total == 0 {
86 let mut out: Vec<(String, u64)> = authors.iter().map(|a| (a.principal.clone(), 0)).collect();
87 out[0].1 = bytes;
88 return out;
89 }
90 let mut out: Vec<(String, u64)> = authors.iter().map(|a| (a.principal.clone(), ((bytes as u128 * a.bytes as u128) / total) as u64)).collect();
91 let mut left = bytes - out.iter().map(|(_, n)| n).sum::<u64>();
92 let mut order: Vec<usize> = (0..authors.len()).collect();
93 order.sort_by(|&a, &b| authors[b].bytes.cmp(&authors[a].bytes).then_with(|| authors[a].principal.cmp(&authors[b].principal)));
94 for i in order.into_iter().cycle() {
95 if left == 0 {
96 break;
97 }
98 out[i].1 += 1;
99 left -= 1;
100 }
101 out
102}
103
104/// Someone on a note: a connection open on it, or a writer while it writes.
105#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
106pub struct Present {
107 /// The note.
108 pub id: String,
109 /// The connection's own id (the page's, as its watch said it).
110 pub session: String,
111 pub principal: String,
112 /// The name they signed in as.
113 pub name: String,
114 /// An agent's key, not a person.
115 pub agent: bool,
116 /// Their colour, for their caret and their name (#rrggbb).
117 pub colour: String,
118 /// Their Yjs client id, when their page said it.
119 #[serde(default, skip_serializing_if = "Option::is_none")]
120 pub client: Option<u64>,
121 /// Their caret and selection: a Yjs awareness update (base64), when their page said one.
122 #[serde(default, skip_serializing_if = "Option::is_none")]
123 pub awareness: Option<String>,
124 /// Their last word, in unix milliseconds.
125 pub at: i64,
126}
127
128/// V2-30: a question on a range of a note, and its thread.
129#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
130pub struct Thread {
131 /// Its id, 8 characters as a note's.
132 pub thread: String,
133 /// The note it is on.
134 pub id: String,
135 /// The range as the note's CRDT holds it: two Yjs relative positions (base64), which follow the text.
136 pub anchor: Anchor,
137 /// The range now, in characters of the text — absent when it is detached.
138 #[serde(default, skip_serializing_if = "Option::is_none")]
139 pub from: Option<u32>,
140 #[serde(default, skip_serializing_if = "Option::is_none")]
141 pub to: Option<u32>,
142 /// The text it was on was deleted whole: the thread is kept, listed at the end.
143 pub detached: bool,
144 /// The text the range held when it was asked.
145 pub quote: String,
146 /// The question, markdown.
147 pub question: String,
148 /// Whom it is asked of — an agent's name, `agent` for any (absent: anyone reading).
149 #[serde(default, skip_serializing_if = "Option::is_none")]
150 pub to_whom: Option<String>,
151 pub by: String,
152 pub principal: String,
153 /// When, unix milliseconds.
154 pub at: i64,
155 /// When it was resolved and by whom — absent while it is open.
156 #[serde(default, skip_serializing_if = "Option::is_none")]
157 pub resolved: Option<Resolution>,
158 /// The answers, in order.
159 pub replies: Vec<Reply>,
160}
161
162/// A thread's range as two Yjs relative positions, base64 (`Y.decodeRelativePosition`).
163#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
164pub struct Anchor {
165 pub from: String,
166 pub to: String,
167}
168
169/// An answer in a thread.
170#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
171pub struct Reply {
172 /// Its place in the thread, from 1.
173 pub n: u32,
174 /// Markdown: words, links, images (as a body shows them).
175 pub body: String,
176 pub by: String,
177 pub principal: String,
178 /// When, unix milliseconds.
179 pub at: i64,
180}
181
182/// When a thread was resolved, and by whom.
183#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
184pub struct Resolution {
185 pub at: i64,
186 pub by: String,
187}
188
189/// NOTES-4: a note's slot whole — what fills it now, its props, every fill
190/// it had and the build under way — as every answer and every watch event
191/// about it carries it (a page's `live()` replaces its row whole).
192#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
193pub struct Slot {
194 /// The note.
195 pub id: String,
196 /// What fills it now — absent: nothing (never filled, or emptied).
197 #[serde(default, skip_serializing_if = "Option::is_none")]
198 pub fill: Option<Fill>,
199 /// What the component in it is given beside the note's id: a JSON object (`{}` when none).
200 pub props: serde_json::Map<String, serde_json::Value>,
201 /// Every fill it had, the newest first (`fill`, when there is one, is among them).
202 pub fills: Vec<Fill>,
203 /// A build under way, said by the agent with `notes.building` — absent when none.
204 #[serde(default, skip_serializing_if = "Option::is_none")]
205 pub building: Option<Building>,
206}
207
208/// NOTES-4: one fill of a slot: a component of a kept version, who and when.
209#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
210pub struct Fill {
211 /// Which fill of the slot it is, from 1.
212 pub n: u32,
213 /// The component, as its version's manifest names it.
214 pub component: String,
215 /// The version it is of: its hash, 64 hex digits — what the page pins its mark to.
216 pub version: String,
217 /// One line saying what this fill does.
218 #[serde(default, skip_serializing_if = "Option::is_none")]
219 pub say: Option<String>,
220 pub by: String,
221 pub principal: String,
222 /// When, unix milliseconds.
223 pub at: i64,
224}
225
226/// NOTES-4: a build under way in a slot — kept in memory only: a fill or an
227/// empty ends it, so do ten minutes without a word, and a restart.
228#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
229pub struct Building {
230 /// The component being built.
231 pub component: String,
232 /// The last step reached: `heard`, `written` or `compiled` (absent: none yet).
233 #[serde(default, skip_serializing_if = "Option::is_none")]
234 pub step: Option<crate::vocab::BuildStep>,
235 /// The agent's line — with `failed`, the refusal (the compiler's line).
236 #[serde(default, skip_serializing_if = "Option::is_none")]
237 pub say: Option<String>,
238 /// The build failed: the step after `step` is where.
239 pub failed: bool,
240 pub by: String,
241 pub principal: String,
242 /// When it began, and its last word — unix milliseconds.
243 pub started: i64,
244 pub at: i64,
245}
246
247/// NOTES-5: a mark — an agent's underline on a range of a note, which
248/// follows its words as a question's range does: a link, a line of state,
249/// or both. It sits on the text, never in it: no mark writes the note.
250#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
251pub struct Mark {
252 /// Its id, 8 characters as a note's.
253 pub mark: String,
254 /// The note it is on.
255 pub id: String,
256 /// The range as the note's CRDT holds it: two Yjs relative positions (base64), which follow the text.
257 pub anchor: Anchor,
258 /// The range now, in characters of the text — absent when it is detached.
259 #[serde(default, skip_serializing_if = "Option::is_none")]
260 pub from: Option<u32>,
261 #[serde(default, skip_serializing_if = "Option::is_none")]
262 pub to: Option<u32>,
263 /// Every character it was on was deleted: the mark is kept, listed last, drawn nowhere.
264 pub detached: bool,
265 /// The words the range holds now (empty when it is detached).
266 pub words: String,
267 /// The words it held when it was made.
268 pub quote: String,
269 /// What a click on its underline opens: a ticket (`KILN-12`), an address of the app (`#/…`) or an `https` address.
270 #[serde(default, skip_serializing_if = "Option::is_none")]
271 pub link: Option<String>,
272 /// Its line of state, drawn under the passage that holds it.
273 #[serde(default, skip_serializing_if = "Option::is_none")]
274 pub label: Option<String>,
275 /// Who left it: their name, and their principal.
276 pub by: String,
277 pub principal: String,
278 /// When, unix milliseconds.
279 pub at: i64,
280 /// When it was last changed (unix milliseconds) and by whom — absent until it is.
281 #[serde(default, skip_serializing_if = "Option::is_none")]
282 pub changed_at: Option<i64>,
283 #[serde(default, skip_serializing_if = "Option::is_none")]
284 pub changed_by: Option<String>,
285 /// The component placed under the passage that holds the range (the page draws it there, never in the text) — absent when it places none.
286 #[serde(default, skip_serializing_if = "Option::is_none")]
287 pub component: Option<String>,
288 /// The kept version that holds it, its whole hash.
289 #[serde(default, skip_serializing_if = "Option::is_none")]
290 pub version: Option<String>,
291 /// Its props, a JSON object (`mark_props` patches them) — with a component alone.
292 #[serde(default, skip_serializing_if = "Option::is_none")]
293 pub props: Option<serde_json::Map<String, serde_json::Value>>,
294}
295
296/// Why an open `watch` ended.
297#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
298#[serde(rename_all = "snake_case")]
299pub enum WatchEnd {
300 /// Its session was signed out.
301 SignedOut,
302 /// Its sign-in's expiry passed.
303 Expired,
304 /// Its grants changed: it holds the watch's grant nowhere any more.
305 Revoked,
306 /// Verified again, it was refused for another reason (named in `message`).
307 Refused,
308}
309
310/// What the `notes` service streams.
311#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
312#[serde(tag = "type", rename_all = "snake_case")]
313pub enum NotesEvent {
314 /// `create`'s answer, and a watch's word for a note made.
315 Created { note: Note },
316 /// `get`'s and `replay`'s answer: the note whole (as it stood then, for a replay).
317 Note { note: Note },
318 /// A page of `list`'s rows at once: each item a `note { note }` without its body.
319 Rows { items: Vec<NotesEvent> },
320 /// Where a `list` walk stands, the last data event of the call: `next` is the
321 /// cursor to pass as the next call's `after` (`null` when nothing more
322 /// matches); `remaining` counts the matches past this page.
323 Page { next: Option<String>, remaining: u64 },
324 /// `save`'s and `restore`'s answer: the body merged in as the CRDT's own
325 /// edits — the revision it made (none new when it changed nothing), when and
326 /// by whom; `stale` when `base` was not the revision it found.
327 Saved {
328 id: String,
329 revision: u32,
330 at: i64,
331 by: String,
332 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
333 stale: bool,
334 },
335 /// `update`'s answer: the update kept as change `revision`.
336 Applied { id: String, revision: u32 },
337 /// `state`'s answer: what the caller's state vector lacks (`update`, a Yjs v1
338 /// update, base64), the note's own state vector (`vector`, base64), and
339 /// its revision.
340 State { id: String, update: String, vector: String, revision: u32 },
341 /// A watch's word for every change of the body: the Yjs v1 update (base64) to
342 /// apply, its `seq`, who and when, the presence `session` it came from when it
343 /// said; `note` the note as it is now (without its body on a watch of every
344 /// note).
345 Updated {
346 id: String,
347 seq: u32,
348 update: String,
349 at: i64,
350 by: String,
351 #[serde(default, skip_serializing_if = "Option::is_none")]
352 session: Option<String>,
353 #[serde(default, skip_serializing_if = "Option::is_none")]
354 note: Option<Note>,
355 },
356 /// `rename`'s answer, and a watch's: the new title and the revision it made.
357 Renamed {
358 id: String,
359 title: String,
360 revision: u32,
361 at: i64,
362 by: String,
363 #[serde(default, skip_serializing_if = "Option::is_none")]
364 note: Option<Note>,
365 },
366 /// `delete`'s answer, and a watch's: the note is gone (its changes are kept in the file).
367 Deleted { id: String, at: i64, by: String },
368 /// `squash`'s answer, and a watch's: the changes up to `until` are one
369 /// snapshot now (`removed` rows fewer), who wrote what kept as its authors.
370 Squashed { id: String, until: u32, removed: u32, at: i64, by: String },
371 /// `history`'s rows, newest first.
372 Change { change: HistoryRow },
373 /// `present`'s rows, and a watch's word: someone is on the note, or moved their caret.
374 Present { present: Present },
375 /// A watch's word: someone left the note (`client` their Yjs client id, when said).
376 Left {
377 id: String,
378 session: String,
379 #[serde(default, skip_serializing_if = "Option::is_none")]
380 client: Option<u64>,
381 },
382 /// V2-30: `threads`' and `waiting`'s rows, a thread whole.
383 Thread { thread: Thread },
384 /// V2-30: `ask`'s answer, and a watch's: a question asked on a range.
385 Asked { thread: Thread },
386 /// V2-30: `reply`'s answer, and a watch's: the thread with its new answer.
387 Replied { thread: Thread },
388 /// V2-30: `resolve`'s answer, and a watch's: the thread folded (or opened again: `resolved` absent).
389 Resolved { thread: Thread },
390 /// NOTES-5: `marks`' rows, a mark whole.
391 Mark { mark: Mark },
392 /// NOTES-5: `mark`'s answer: the mark made, or changed.
393 Marked { mark: Mark },
394 /// NOTES-5: `unmark`'s answer: the mark `mark` is gone from the note `id`.
395 Unmarked { id: String, mark: String },
396 /// NOTES-5: a watch's word: a mark made or changed on the note `id`, whole.
397 MarkChanged { id: String, mark: Mark },
398 /// NOTES-5: a watch's word: the mark `mark` taken off the note `id`.
399 MarkRemoved { id: String, mark: String },
400 /// NOTES-5: a watch's word with `text: true` — the note's markdown after
401 /// a change (at most once a second, the last change always said), and
402 /// once as the watch opens: its revision then, who wrote it last and when
403 /// (unix seconds).
404 Text { id: String, revision: u32, body: String, by: String, at: i64 },
405 /// `may`'s answer: whether the caller holds `role` on the note `id`.
406 May { id: String, role: menger_tickets_api::members::Role, held: bool },
407 /// A watch is open: what it hears follows (`id` when it watches one note).
408 Watching {
409 #[serde(default, skip_serializing_if = "Option::is_none")]
410 id: Option<String>,
411 },
412 /// A watch fell behind by `missed` writes: read again (`state`, `list`).
413 Lagged { missed: u64 },
414 /// A watch ended: `reason` is `signed_out`, `expired`, `revoked` or `refused`.
415 WatchClosed { reason: WatchEnd, message: String },
416 /// No such note, or none the caller may read (one answer); with
417 /// `revision`, no such change kept (none, or squashed). `org` for an
418 /// organization the caller is not in.
419 NotFound {
420 #[serde(default, skip_serializing_if = "Option::is_none")]
421 id: Option<String>,
422 #[serde(default, skip_serializing_if = "Option::is_none")]
423 revision: Option<u32>,
424 #[serde(default, skip_serializing_if = "Option::is_none")]
425 org: Option<String>,
426 /// V2-30: no such thread on the note.
427 #[serde(default, skip_serializing_if = "Option::is_none")]
428 thread: Option<String>,
429 /// NOTES-5: no such mark on the note.
430 #[serde(default, skip_serializing_if = "Option::is_none")]
431 mark: Option<String>,
432 },
433 /// The caller reads the note but may not do this to it (`forbidden`,
434 /// `message` naming the grant and role it takes), or the meter refused the
435 /// write (`quota`). Nothing was written.
436 Refused { reason: String, message: String },
437 /// NOTES-4: `slot`'s answer: the note's slot whole.
438 Slot { slot: Slot },
439 /// NOTES-4: `fill`'s answer: the slot with its new fill.
440 Filled { slot: Slot },
441 /// NOTES-4: `empty`'s answer: the slot with nothing in it.
442 Emptied { slot: Slot },
443 /// NOTES-4: `building`'s answer: the slot with its build under way.
444 Building { slot: Slot },
445 /// NOTES-4: `props`' answer: the slot with its props merged.
446 Props { slot: Slot },
447 /// NOTES-4: a watch's word: the slot was filled or emptied — `slot` whole.
448 SlotChanged { id: String, slot: Slot },
449 /// NOTES-4: a watch's word: a build began, moved a step, failed or ended (`building` absent) — `slot` whole.
450 BuildingChanged {
451 id: String,
452 #[serde(default, skip_serializing_if = "Option::is_none")]
453 building: Option<Building>,
454 slot: Slot,
455 },
456 /// NOTES-4: a watch's word: the slot's props, merged by `by` — `slot` whole.
457 PropsChanged { id: String, props: serde_json::Map<String, serde_json::Value>, by: String, slot: Slot },
458 /// V2-31: `usage { everyone }` — what one principal's changes keep:
459 /// the notes they made and the bytes they wrote.
460 Usage { principal: String, count: u64, bytes: u64 },
461 /// V2-70: `usage { everyone, daily }` — what one principal's changes
462 /// kept on one UTC day (`day`: days since 1970-01-01).
463 UsageDay { principal: String, day: i64, count: u64, bytes: u64 },
464 /// Any other in-band refusal, naming the problem; nothing was written.
465 Error { message: String },
466}
467
468impl plexus_rpc::client::FromClientError for NotesEvent {
469 fn from_client_error(error: plexus_rpc::client::ClientError) -> Self {
470 NotesEvent::Error { message: error.to_string() }
471 }
472}
473
474impl NotesEvent {
475 /// `not_found` for the note `id`.
476 pub fn no_doc(id: &str) -> Self {
477 NotesEvent::NotFound { id: Some(id.to_string()), revision: None, org: None, thread: None, mark: None }
478 }
479}