Skip to main content

menger_notes/
slot.rs

1//! NOTES-4: **a note's slot** — the component drawn on the note's right
2//! (the owner, 2026-11-15: *"every note associated with a plexus-ui slot on
3//! it's right"*): a component of a version the ui service keeps, its props,
4//! and every fill before it; and what an agent says while it builds the
5//! next one (*"we instead want to show that the agent is building
6//! components as it builds"*).
7//!
8//! **Stored** in the notes file, by the store's own migration (`CREATE …
9//! IF NOT EXISTS`, so a `notes.db` from before opens with every slot empty):
10//! `note_slots` — a row a note: the fill drawn now (`fill`, a fill's `n`;
11//! null: empty), the props (a JSON object), who and when last; and
12//! `note_fills` — a row for every fill: its `n`, the component, the
13//! version's whole hash, its line, who and when. A delete of the note
14//! leaves both, so a note brought back has its slot as it was.
15//!
16//! **A build under way** is kept in memory alone ([`NotesStore::builds`]):
17//! a fill or an empty ends it, so does [`BUILD_IDLE_MS`] after its last
18//! word ([`NotesStore::sweep_builds`]), and a restart. Every change is said
19//! on the channel for `watch`, the slot whole: `SlotChanged`,
20//! `BuildingChanged`, `PropsChanged`.
21
22use crate::events::{Building, Fill, Slot};
23use crate::store::{live_doc, now_ms, Change, NotesStore, StoreError};
24use rusqlite::{params, Connection, OptionalExtension};
25use serde_json::{Map, Value};
26use std::sync::Arc;
27
28/// The tables.
29pub const TABLES: &str = "
30        CREATE TABLE IF NOT EXISTS note_slots (
31            id        TEXT PRIMARY KEY,
32            fill      INTEGER,
33            props     TEXT NOT NULL DEFAULT '{}',
34            at        INTEGER NOT NULL,
35            by        TEXT NOT NULL
36        );
37        CREATE TABLE IF NOT EXISTS note_fills (
38            id         TEXT NOT NULL,
39            n          INTEGER NOT NULL,
40            component  TEXT NOT NULL,
41            version    TEXT NOT NULL,
42            say        TEXT,
43            by         TEXT NOT NULL,
44            principal  TEXT NOT NULL,
45            at         INTEGER NOT NULL,
46            PRIMARY KEY (id, n)
47        );
48    ";
49
50/// A build is over ten minutes after its last word.
51pub const BUILD_IDLE_MS: i64 = 10 * 60 * 1000;
52
53/// What a fill sets.
54#[derive(Debug, Clone)]
55pub struct FillOf {
56    pub component: String,
57    /// The version's whole hash.
58    pub version: String,
59    /// The props it starts from; none: the props the slot holds stay.
60    pub props: Option<Map<String, Value>>,
61    pub say: Option<String>,
62}
63
64/// Who writes.
65#[derive(Debug, Clone)]
66pub struct Hand {
67    pub name: String,
68    pub principal: String,
69}
70
71fn fill_of(r: &rusqlite::Row<'_>) -> rusqlite::Result<Fill> {
72    Ok(Fill { n: r.get(0)?, component: r.get(1)?, version: r.get(2)?, say: r.get(3)?, by: r.get(4)?, principal: r.get(5)?, at: r.get(6)? })
73}
74
75/// `props` merged with `patch`: each key set, a `null` taken away.
76pub fn merged(mut props: Map<String, Value>, patch: Map<String, Value>) -> Map<String, Value> {
77    for (k, v) in patch {
78        match v {
79            Value::Null => {
80                props.remove(&k);
81            }
82            v => {
83                props.insert(k, v);
84            }
85        }
86    }
87    props
88}
89
90impl NotesStore {
91    /// The slot of `id` as `conn` holds it, with `building` beside it.
92    fn slot_in(&self, conn: &Connection, id: &str) -> Result<Slot, StoreError> {
93        let row: Option<(Option<u32>, String)> = conn.query_row("SELECT fill, props FROM note_slots WHERE id = ?1", [id], |r| Ok((r.get(0)?, r.get(1)?))).optional()?;
94        let (now, props) = row.unwrap_or((None, "{}".into()));
95        let mut stmt = conn.prepare("SELECT n, component, version, say, by, principal, at FROM note_fills WHERE id = ?1 ORDER BY n DESC")?;
96        let fills = stmt.query_map([id], fill_of)?.collect::<Result<Vec<_>, _>>()?;
97        Ok(Slot {
98            id: id.to_string(),
99            fill: now.and_then(|n| fills.iter().find(|f| f.n == n).cloned()),
100            props: serde_json::from_str(&props).unwrap_or_default(),
101            fills,
102            building: self.builds().get(id).cloned(),
103        })
104    }
105
106    /// The builds under way, by note.
107    fn builds(&self) -> std::sync::MutexGuard<'_, std::collections::HashMap<String, Building>> {
108        self.builds.lock().unwrap_or_else(|p| p.into_inner())
109    }
110
111    /// The slot of the live note `id`, with every fill and the build under way.
112    pub async fn slot(self: &Arc<Self>, id: &str) -> Result<Slot, StoreError> {
113        let id = id.to_string();
114        self.blocking(move |s| {
115            let conn = s.lock();
116            live_doc(&conn, &id)?;
117            s.slot_in(&conn, &id)
118        })
119        .await
120    }
121
122    /// Fills the slot of `id` with `fill` — a fill more, the build under way
123    /// ended — and says it.
124    pub async fn fill(self: &Arc<Self>, id: &str, fill: FillOf, hand: Hand) -> Result<Slot, StoreError> {
125        let id = id.to_string();
126        let (org, slot) = self
127            .blocking(move |s| {
128                let conn = s.lock();
129                let tx = conn.unchecked_transaction()?;
130                let org = live_doc(&tx, &id)?.org;
131                let n: u32 = tx.query_row("SELECT COALESCE(MAX(n), 0) + 1 FROM note_fills WHERE id = ?1", [&id], |r| r.get(0))?;
132                let at = now_ms();
133                tx.execute(
134                    "INSERT INTO note_fills (id, n, component, version, say, by, principal, at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
135                    params![id, n, fill.component, fill.version, fill.say, hand.name, hand.principal, at],
136                )?;
137                let props = fill.props.map(|p| Value::Object(p).to_string());
138                tx.execute(
139                    "INSERT INTO note_slots (id, fill, props, at, by) VALUES (?1, ?2, COALESCE(?3, '{}'), ?4, ?5)
140                     ON CONFLICT(id) DO UPDATE SET fill = excluded.fill, props = COALESCE(?3, props), at = excluded.at, by = excluded.by",
141                    params![id, n, props, at, hand.name],
142                )?;
143                tx.commit()?;
144                s.builds().remove(&id);
145                Ok((org, s.slot_in(&conn, &id)?))
146            })
147            .await?;
148        self.said(Change::SlotChanged { org, slot: slot.clone() });
149        Ok(slot)
150    }
151
152    /// Empties the slot of `id` — nothing drawn, its props cleared, its
153    /// fills kept, the build under way ended — and says it.
154    pub async fn empty(self: &Arc<Self>, id: &str, hand: Hand) -> Result<Slot, StoreError> {
155        let id = id.to_string();
156        let (org, slot) = self
157            .blocking(move |s| {
158                let conn = s.lock();
159                let org = live_doc(&conn, &id)?.org;
160                conn.execute(
161                    "INSERT INTO note_slots (id, fill, props, at, by) VALUES (?1, NULL, '{}', ?2, ?3)
162                     ON CONFLICT(id) DO UPDATE SET fill = NULL, props = '{}', at = excluded.at, by = excluded.by",
163                    params![id, now_ms(), hand.name],
164                )?;
165                s.builds().remove(&id);
166                Ok((org, s.slot_in(&conn, &id)?))
167            })
168            .await?;
169        self.said(Change::SlotChanged { org, slot: slot.clone() });
170        Ok(slot)
171    }
172
173    /// Merges `patch` into the props of `id`'s slot (a `null` takes its key
174    /// away), held to [`crate::vocab::PROPS_MAX`], and says it.
175    pub async fn props(self: &Arc<Self>, id: &str, patch: Map<String, Value>, hand: Hand) -> Result<Slot, StoreError> {
176        let id = id.to_string();
177        let by = hand.name.clone();
178        let (org, slot) = self
179            .blocking(move |s| {
180                let conn = s.lock();
181                let tx = conn.unchecked_transaction()?;
182                let org = live_doc(&tx, &id)?.org;
183                let was: Option<String> = tx.query_row("SELECT props FROM note_slots WHERE id = ?1", [&id], |r| r.get(0)).optional()?;
184                let props = merged(was.and_then(|p| serde_json::from_str(&p).ok()).unwrap_or_default(), patch);
185                let text = Value::Object(props).to_string();
186                if text.len() > crate::vocab::PROPS_MAX {
187                    return Err(StoreError::TooLarge(format!("the slot's props would be {} bytes written as JSON; they are held to {} (nothing was written)", text.len(), crate::vocab::PROPS_MAX)));
188                }
189                tx.execute(
190                    "INSERT INTO note_slots (id, fill, props, at, by) VALUES (?1, NULL, ?2, ?3, ?4)
191                     ON CONFLICT(id) DO UPDATE SET props = excluded.props, at = excluded.at, by = excluded.by",
192                    params![id, text, now_ms(), hand.name],
193                )?;
194                tx.commit()?;
195                Ok((org, s.slot_in(&conn, &id)?))
196            })
197            .await?;
198        self.said(Change::PropsChanged { org, slot: slot.clone(), by });
199        Ok(slot)
200    }
201
202    /// Marks `id`'s slot as being built — `building` its word now (kept from
203    /// the build before when it is of the same component and has not
204    /// failed) — and says it.
205    pub async fn building(self: &Arc<Self>, id: &str, mut building: Building) -> Result<Slot, StoreError> {
206        let id = id.to_string();
207        let (org, slot) = self
208            .blocking(move |s| {
209                let conn = s.lock();
210                let org = live_doc(&conn, &id)?.org;
211                {
212                    let mut builds = s.builds();
213                    if let Some(was) = builds.get(&id).filter(|b| b.component == building.component && !b.failed) {
214                        building.started = was.started;
215                    }
216                    builds.insert(id.clone(), building);
217                }
218                Ok((org, s.slot_in(&conn, &id)?))
219            })
220            .await?;
221        self.said(Change::BuildingChanged { org, slot: slot.clone() });
222        Ok(slot)
223    }
224
225    /// Ends every build silent for [`BUILD_IDLE_MS`], saying each.
226    pub fn sweep_builds(&self) {
227        let now = now_ms();
228        let gone: Vec<String> = {
229            let mut builds = self.builds();
230            let idle: Vec<String> = builds.iter().filter(|(_, b)| now - b.at > BUILD_IDLE_MS).map(|(id, _)| id.clone()).collect();
231            idle.into_iter().filter(|id| builds.remove(id).is_some()).collect()
232        };
233        for id in gone {
234            let conn = self.lock();
235            let (Ok(doc), Ok(slot)) = (live_doc(&conn, &id), self.slot_in(&conn, &id)) else { continue };
236            drop(conn);
237            self.said(Change::BuildingChanged { org: doc.org, slot });
238        }
239    }
240
241    /// Test seam: a build's last word moved back by `ms`.
242    #[cfg(test)]
243    pub(crate) fn age_build(&self, id: &str, ms: i64) {
244        if let Some(b) = self.builds().get_mut(id) {
245            b.at -= ms;
246        }
247    }
248}