git clone https://garage44.eu/jeroen/midas.git.. /src/talks.rs
//! Voice conversations kept (Discuss, `web/src/lib/discuss.ts`): what was
//! said, the brief it wrote and what it was about, saved by the page while the
//! call goes on, so a reload, a phone that closed the page in the background,
//! or a closed panel loses nothing. Until 2026-11-17 a conversation lived only
//! in the page: a design talked through for a new session was gone with it.
//!
//! One file each, `hosted/talks/<id>.json`; the newest `KEPT` are kept.
use anyhow::{bail, Context, Result};
use serde_json::{json, Value};
use std::path::PathBuf;
use std::sync::Mutex;
/// How many conversations are kept, newest first.
const KEPT: usize = 200;
/// What one may hold: a long talk with its brief fits many times over.
const BODY_MAX: usize = 512 * 1024;
/// Lines kept of one conversation.
const LINES_MAX: usize = 1000;
/// What the list says of each: its first words.
const PREVIEW: usize = 160;
static LOCK: Mutex<()> = Mutex::new(());
fn dir() -> PathBuf {
crate::registry::root().join("hosted").join("talks")
}
fn file(id: &str) -> Result<PathBuf> {
if !valid(id) {
bail!("no conversation {id}");
}
Ok(dir().join(format!("{id}.json")))
}
/// A conversation's id: `c` and a number, nothing that names another path.
fn valid(id: &str) -> bool {
id.len() > 1 && id.len() < 24 && id.starts_with('c') && id[1..].bytes().all(|b| b.is_ascii_digit())
}
fn next_id() -> Result<String> {
let seq = dir().join("seq");
let n = std::fs::read_to_string(&seq).ok().and_then(|s| s.trim().parse::<u64>().ok()).unwrap_or(0) + 1;
crate::store::write_atomic(&seq, n.to_string().as_bytes(), crate::store::PUBLIC)?;
Ok(format!("c{n}"))
}
/// One conversation, whole.
pub fn get(id: &str) -> Result<Value> {
crate::store::read::<Value>(&file(id)?).with_context(|| format!("no conversation {id}"))
}
/// Save a conversation as the page has it now: a new one gets an id. Who started it stays its owner.
pub fn save(body: &Value, by: &str) -> Result<Value> {
if body.to_string().len() > BODY_MAX {
bail!("a conversation that long is not kept");
}
let about = &body["about"];
if !matches!(about["kind"].as_str(), Some("new" | "session" | "board" | "free" | "tree")) {
bail!("what is it about?");
}
let lines: Vec<Value> = body["lines"].as_array().into_iter().flatten()
.filter(|l| matches!(l["who"].as_str(), Some("you" | "midas" | "note")))
.map(|l| json!({"who": l["who"], "text": crate::util::short(l["text"].as_str().unwrap_or(""), 8000)}))
.collect();
let lines = lines[lines.len().saturating_sub(LINES_MAX)..].to_vec();
let text = |k: &str, max: usize| crate::util::short(body[k].as_str().unwrap_or(""), max);
let _l = LOCK.lock().unwrap_or_else(|p| p.into_inner());
std::fs::create_dir_all(dir())?;
let asked = body["id"].as_str().filter(|i| !i.is_empty());
let (id, was) = match asked {
Some(id) => (id.to_string(), get(id).ok()),
None => (next_id()?, None),
};
if asked.is_some() && was.is_none() {
bail!("no conversation {id}");
}
let now = crate::registry::now();
let v = json!({
"id": id,
"by": was.as_ref().map(|w| w["by"].clone()).unwrap_or(json!(by)),
"at": was.as_ref().map(|w| w["at"].clone()).unwrap_or(json!(now)),
"updated": now,
"about": about,
"persona": text("persona", 20),
"brief": text("brief", 60_000),
"sent_to": text("sent_to", 20),
"lines": lines,
});
crate::store::write_atomic(&file(&id)?, serde_json::to_string(&v)?.as_bytes(), crate::store::PUBLIC)?;
prune();
Ok(json!({"id": id}))
}
/// The conversations kept, newest first, each with enough to know it again.
pub fn list() -> Value {
let mut all: Vec<Value> = std::fs::read_dir(dir()).into_iter().flatten().flatten()
.filter_map(|e| {
let name = e.file_name().to_string_lossy().to_string();
let id = name.strip_suffix(".json")?;
valid(id).then(|| get(id).ok()).flatten()
})
.map(|v| {
let said: Vec<&Value> = v["lines"].as_array().into_iter().flatten().filter(|l| l["who"] != "note").collect();
let first = said.iter().find(|l| l["who"] == "you").or(said.first()).and_then(|l| l["text"].as_str()).unwrap_or("");
let title = v["brief"].as_str().and_then(|b| b.lines().find(|l| l.starts_with("# "))).map(|l| l[2..].trim().to_string());
json!({"id": v["id"], "by": v["by"], "at": v["at"], "updated": v["updated"], "about": v["about"], "persona": v["persona"],
"sent_to": v["sent_to"], "title": title, "said": said.len(), "preview": crate::util::short(first, PREVIEW)})
})
.collect();
all.sort_by_key(|v| std::cmp::Reverse(v["updated"].as_i64().unwrap_or(0)));
json!({"talks": all})
}
/// Forget one, on the person's word.
pub fn forget(id: &str) -> Result<()> {
let _l = LOCK.lock().unwrap_or_else(|p| p.into_inner());
std::fs::remove_file(file(id)?).with_context(|| format!("no conversation {id}"))
}
/// The oldest go once there are more than `KEPT`.
fn prune() {
let mut files: Vec<(std::time::SystemTime, PathBuf)> = std::fs::read_dir(dir()).into_iter().flatten().flatten()
.filter(|e| e.file_name().to_string_lossy().ends_with(".json"))
.filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path())))
.collect();
if files.len() <= KEPT {
return;
}
files.sort();
for (_, p) in &files[..files.len() - KEPT] {
let _ = std::fs::remove_file(p);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_conversation_is_kept_and_carried_on() {
let _g = crate::tests::SERIAL.lock().unwrap_or_else(|p| p.into_inner());
crate::tests::scratch("talks");
let made = save(&json!({"about": {"kind": "new"}, "persona": "coach", "brief": "# Invite by link\n\nDecided: …",
"lines": [{"who": "you", "text": "I want invites"}, {"who": "midas", "text": "By link?"}]}), "sam").unwrap();
let id = made["id"].as_str().unwrap().to_string();
assert_eq!(id, "c1");
// Saved again as it goes: the same one, its owner and start kept.
save(&json!({"id": id, "about": {"kind": "new"}, "persona": "coach", "brief": "# Invite by link",
"lines": [{"who": "you", "text": "I want invites"}, {"who": "midas", "text": "By link?"}, {"who": "you", "text": "Yes"}]}), "other").unwrap();
let v = get(&id).unwrap();
assert_eq!(v["by"], "sam");
assert_eq!(v["lines"].as_array().unwrap().len(), 3);
let l = list();
assert_eq!(l["talks"][0]["title"], "Invite by link");
assert_eq!(l["talks"][0]["preview"], "I want invites");
assert_eq!(l["talks"][0]["said"], 3);
// A tree conversation is one too; an unknown subject, a made-up id or a path are not.
assert!(save(&json!({"about": {"kind": "tree", "goal": "g1"}, "lines": []}), "j").is_ok());
assert!(save(&json!({"about": {"kind": "elsewhere"}}), "j").is_err());
assert!(save(&json!({"id": "c99", "about": {"kind": "free"}}), "j").is_err());
assert!(get("../tree").is_err());
forget(&id).unwrap();
assert!(get(&id).is_err());
}
}