c0re: keep power intent in memory, drop agent_power/kv tables and the stop snapshot
This commit is contained in:
parent
fca7f669f5
commit
b77fa9edc3
1 changed files with 222 additions and 553 deletions
|
|
@ -11,7 +11,7 @@ use chrono::Utc;
|
|||
use hive_sh4re::inbox::{InboxRow, Message};
|
||||
|
||||
use crate::db::Migration;
|
||||
use rusqlite::{Connection, OptionalExtension, params};
|
||||
use rusqlite::{Connection, params};
|
||||
use serde::Serialize;
|
||||
use tokio::sync::broadcast;
|
||||
|
||||
|
|
@ -29,10 +29,11 @@ CREATE TABLE IF NOT EXISTS messages (
|
|||
CREATE INDEX IF NOT EXISTS idx_messages_undelivered
|
||||
ON messages (recipient, priority DESC, id) WHERE delivered_at IS NULL;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS kv (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
);
|
||||
-- Tables an earlier build kept here: the running-agents snapshot (`kv`) and
|
||||
-- the durable power intent (`agent_power`). The swarm owns power intent now,
|
||||
-- so a file from that build sheds them on its next open.
|
||||
DROP TABLE IF EXISTS kv;
|
||||
DROP TABLE IF EXISTS agent_power;
|
||||
";
|
||||
|
||||
/// Capacity of the live event channel. Slow subscribers (e.g. an idle browser)
|
||||
|
|
@ -163,52 +164,6 @@ impl Broker {
|
|||
self.events.subscribe()
|
||||
}
|
||||
|
||||
/// Set a small persistent key/value pair (upsert). The `kv` table is a
|
||||
/// general single-value store for state that must survive a hive-c0re
|
||||
/// restart but isn't worth a dedicated table — currently just the
|
||||
/// `hivectl start` running-agents snapshot (see
|
||||
/// `Coordinator::set_last_stopped_running`).
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the sqlite upsert fails.
|
||||
pub fn kv_set(&self, key: &str, value: &str) -> Result<()> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO kv (key, value) VALUES (?1, ?2)
|
||||
ON CONFLICT(key) DO UPDATE SET value = excluded.value",
|
||||
params![key, value],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Read a persistent key/value pair. `None` when the key is absent.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the sqlite query fails.
|
||||
pub fn kv_get(&self, key: &str) -> Result<Option<String>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let value: Option<String> = conn
|
||||
.query_row("SELECT value FROM kv WHERE key = ?1", params![key], |row| {
|
||||
row.get(0)
|
||||
})
|
||||
.optional()?;
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
/// Delete a persistent key/value pair. Idempotent — deleting an absent
|
||||
/// key is a no-op.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the sqlite delete fails.
|
||||
pub fn kv_delete(&self, key: &str) -> Result<()> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
conn.execute("DELETE FROM kv WHERE key = ?1", params![key])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn send(&self, message: &Message) -> Result<()> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let now = Utc::now().timestamp();
|
||||
|
|
@ -664,6 +619,42 @@ mod tests {
|
|||
TmpBroker { path, broker }
|
||||
}
|
||||
|
||||
/// A file from the build that kept the running-agents snapshot (`kv`) and
|
||||
/// the durable power intent (`agent_power`) in it sheds both tables on its
|
||||
/// next open and keeps its messages.
|
||||
#[test]
|
||||
fn opening_an_older_file_drops_the_kv_and_power_tables() {
|
||||
let first = open_broker();
|
||||
first.broker.send(&msg("alice", "bob", "kept")).unwrap();
|
||||
let path = first.path.clone();
|
||||
{
|
||||
let conn = Connection::open(&path).unwrap();
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE kv (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
||||
CREATE TABLE agent_power (
|
||||
agent TEXT PRIMARY KEY, wanted TEXT NOT NULL, updated_at INTEGER NOT NULL);
|
||||
INSERT INTO kv VALUES ('last_stopped_running', '[]');
|
||||
INSERT INTO agent_power VALUES ('alice', 'up', 0);",
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let reopened = Broker::open(&path).unwrap();
|
||||
let conn = Connection::open(&path).unwrap();
|
||||
let left: Vec<String> = conn
|
||||
.prepare("SELECT name FROM sqlite_master WHERE name IN ('kv', 'agent_power')")
|
||||
.unwrap()
|
||||
.query_map([], |r| r.get(0))
|
||||
.unwrap()
|
||||
.collect::<Result<_, _>>()
|
||||
.unwrap();
|
||||
assert!(left.is_empty(), "left behind: {left:?}");
|
||||
assert_eq!(
|
||||
pop_one(&reopened, "bob").map(|d| d.message.body),
|
||||
Some("kept".to_owned())
|
||||
);
|
||||
}
|
||||
|
||||
fn msg(from: &str, to: &str, body: &str) -> Message {
|
||||
Message {
|
||||
from: hive_types::Ident::parse(from).expect("test sender must be a valid ident"),
|
||||
|
|
@ -681,24 +672,6 @@ mod tests {
|
|||
batch.pop()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kv_set_get_delete_roundtrip() {
|
||||
let tb = open_broker();
|
||||
let b = &tb.broker;
|
||||
// Absent key -> None.
|
||||
assert_eq!(b.kv_get("k").unwrap(), None);
|
||||
// Set then get.
|
||||
b.kv_set("k", "v1").unwrap();
|
||||
assert_eq!(b.kv_get("k").unwrap(), Some("v1".to_owned()));
|
||||
// Upsert overwrites.
|
||||
b.kv_set("k", "v2").unwrap();
|
||||
assert_eq!(b.kv_get("k").unwrap(), Some("v2".to_owned()));
|
||||
// Delete clears; deleting again is a no-op.
|
||||
b.kv_delete("k").unwrap();
|
||||
assert_eq!(b.kv_get("k").unwrap(), None);
|
||||
b.kv_delete("k").unwrap();
|
||||
}
|
||||
|
||||
/// Happy path: send → recv → `ack_turn` drains the in-memory list
|
||||
/// and marks the row `acked_at IS NOT NULL`. A second recv finds
|
||||
/// nothing pending (the row stays in the table for vacuum).
|
||||
|
|
|
|||
Loading…
Reference in a new issue