1use 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
28pub 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
50pub const BUILD_IDLE_MS: i64 = 10 * 60 * 1000;
52
53#[derive(Debug, Clone)]
55pub struct FillOf {
56 pub component: String,
57 pub version: String,
59 pub props: Option<Map<String, Value>>,
61 pub say: Option<String>,
62}
63
64#[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
75pub 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 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 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 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 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 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 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 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 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 #[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}