forked from vhaudiquet/rhema-together
A room is one conversation, one ssh sandbox, and one agent. Accounts create rooms; friends join through a single-use invite link and a display name; the agent speaks only through the message tool. The server is Axum and SQLite. It serves the built Nuxt client, streams room events over SSE, and runs one serialized turn loop per room with turn-level steering copied from rhema-code. The client has the chat, preview iframe, read-only file pane, xterm terminal, and presence. Preview URLs are signed wildcard hosts, and the proxy tunnels HTTP over ssh direct-tcpip. HostAgent::step remains deferred in the framework.
134 lines
3.9 KiB
Rust
134 lines
3.9 KiB
Rust
//! Process state: the database, the secret box, the per-room event buses,
|
|
//! and the turn runners.
|
|
|
|
use std::collections::HashMap;
|
|
use std::sync::atomic::{AtomicU64, Ordering};
|
|
use std::sync::{Arc, Mutex};
|
|
|
|
use tokio::sync::broadcast;
|
|
|
|
use crate::config::Config;
|
|
use crate::crypto::Secrets;
|
|
use crate::db::Db;
|
|
use crate::error::AppResult;
|
|
use crate::models::Envelope;
|
|
use crate::preview::PreviewTunnels;
|
|
use crate::room::RoomRunner;
|
|
|
|
/// One room's live feed and sequence allocator.
|
|
pub struct Bus {
|
|
pub tx: broadcast::Sender<Envelope>,
|
|
pub seq: AtomicU64,
|
|
}
|
|
|
|
/// Every room's bus, created on demand.
|
|
#[derive(Default)]
|
|
pub struct Hub {
|
|
buses: Mutex<HashMap<String, Arc<Bus>>>,
|
|
}
|
|
|
|
impl Hub {
|
|
/// The bus for `room`, its sequence seeded from the database the
|
|
/// first time the room is seen in this process.
|
|
pub fn bus(&self, db: &Db, room: &str) -> Arc<Bus> {
|
|
let mut buses = self.buses.lock().unwrap_or_else(|err| err.into_inner());
|
|
if let Some(bus) = buses.get(room) {
|
|
return bus.clone();
|
|
}
|
|
let next: u64 = db
|
|
.scalar(
|
|
"SELECT COALESCE(MAX(seq), 0) FROM events WHERE room_id = ?1",
|
|
rusqlite::params![room],
|
|
)
|
|
.unwrap_or(0);
|
|
let (tx, _) = broadcast::channel(1024);
|
|
let bus = Arc::new(Bus {
|
|
tx,
|
|
seq: AtomicU64::new(next),
|
|
});
|
|
buses.insert(room.to_owned(), bus.clone());
|
|
bus
|
|
}
|
|
|
|
/// Allocates the next sequence number.
|
|
pub fn next_seq(&self, db: &Db, room: &str) -> u64 {
|
|
self.bus(db, room).seq.fetch_add(1, Ordering::SeqCst) + 1
|
|
}
|
|
|
|
/// Writes a durable event and broadcasts it.
|
|
pub fn durable(
|
|
&self,
|
|
db: &Db,
|
|
room: &str,
|
|
kind: &str,
|
|
data: serde_json::Value,
|
|
) -> AppResult<Envelope> {
|
|
let seq = self.next_seq(db, room);
|
|
self.insert(db, room, seq, kind, &data)?;
|
|
let envelope = Envelope {
|
|
seq,
|
|
kind: kind.to_owned(),
|
|
data,
|
|
};
|
|
self.broadcast(room, envelope.clone());
|
|
Ok(envelope)
|
|
}
|
|
|
|
/// Writes one durable event at an already allocated sequence.
|
|
pub fn insert(
|
|
&self,
|
|
db: &Db,
|
|
room: &str,
|
|
seq: u64,
|
|
kind: &str,
|
|
data: &serde_json::Value,
|
|
) -> AppResult<()> {
|
|
db.conn().execute(
|
|
"INSERT INTO events (room_id, seq, kind, data, created_at) VALUES (?1, ?2, ?3, ?4, ?5)",
|
|
rusqlite::params![room, seq, kind, data.to_string(), crate::util::now_ms()],
|
|
)?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Sends an envelope to every subscriber of `room`.
|
|
pub fn broadcast(&self, room: &str, envelope: Envelope) {
|
|
let buses = self.buses.lock().unwrap_or_else(|err| err.into_inner());
|
|
if let Some(bus) = buses.get(room) {
|
|
let _ = bus.tx.send(envelope);
|
|
}
|
|
}
|
|
|
|
/// Broadcasts a live-only event (a delta). Its sequence is allocated
|
|
/// but never written; on reconnect the client refetches durable
|
|
/// events and the gap is harmless.
|
|
pub fn live(&self, db: &Db, room: &str, kind: &str, data: serde_json::Value) -> u64 {
|
|
let bus = self.bus(db, room);
|
|
let seq = bus.seq.fetch_add(1, Ordering::SeqCst) + 1;
|
|
let _ = bus.tx.send(Envelope {
|
|
seq,
|
|
kind: kind.to_owned(),
|
|
data,
|
|
});
|
|
seq
|
|
}
|
|
|
|
/// Subscribes to a room's feed.
|
|
pub fn subscribe(&self, db: &Db, room: &str) -> broadcast::Receiver<Envelope> {
|
|
self.bus(db, room).tx.subscribe()
|
|
}
|
|
}
|
|
|
|
/// The single application state every handler receives.
|
|
pub struct AppState {
|
|
pub config: Config,
|
|
pub db: Db,
|
|
pub secrets: Secrets,
|
|
pub hub: Hub,
|
|
pub rooms: RoomRunner,
|
|
pub previews: PreviewTunnels,
|
|
pub presence: crate::presence::Presence,
|
|
}
|
|
|
|
/// The state behind an `Arc`.
|
|
pub type Shared = Arc<AppState>;
|