feat(outbox): local retry queue for chat sends
All checks were successful
ci / test (pull_request) Successful in 4m8s

Queue a chat send locally when the peer's v3 onion is unreachable and retry
it with exponential backoff (30s doubling, capped at 30 min, 8 attempts then
terminal Failed). Still peer-to-peer: no server, no store-and-forward relay,
no new frame prefix — every attempt is a fresh Noise IK handshake.

- src/outbox.rs: Outbox + Deliverer + ArtiDeliverer, pure backoff_secs(),
  is_permanent_send_error(), background worker (15s scan).
- store: `outbox` table (no body column — the body is read from the joined
  messages row, under that row's existing AEAD + AAD), append_message_id(),
  queue/due/pending/mark_* helpers, reset_sending_outbox(), wipe.
- Node::send() returns Result<OutboxStatus, String> (Sent/Queued) instead of
  Err on transport failure; protocol errors still fail immediately and are
  never queued.
- Retry triggers: timer, unlock/foreground (spawn_flush_all), and "that peer
  was just seen" (handshake or connect_onion -> spawn_flush_friend).
- File transfer and payment/rcp frames stay fail-closed.
- docs/PROTOCOL.md + docs/THREAT_MODEL.md: replace the no-queue statements;
  add the seizure/cadence delta to the threat model.

src/tui.rs gets one forced arm change (Ok(()) -> Ok(_)); UI surfacing is
child card t_d9a5b065.
This commit is contained in:
Sirius DevOps 2026-09-12 13:35:10 -04:00 • committed by agent
commit d6d157765a
No known key found for this signature in database
9 changed files with 1042 additions and 53 deletions

View file

@ -41,6 +41,15 @@ impl From<String> for Error {
}
}
/// The store error is a message and nothing else, and the rest of the crate
/// (transport, UI) already speaks `String`. Lossless, so `?` is enough at the
/// outbox boundary — no per-call `map_err`.
impl From<Error> for String {
fn from(e: Error) -> Self {
e.0
}
}
pub struct Store {
conn: Connection,
msg_key: [u8; 32],
@ -89,6 +98,64 @@ pub struct Payment {
pub created_at: i64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OutboxStatus {
Queued,
Sending,
Sent,
/// Terminal: transport or protocol failure that will not be retried.
Failed(String),
}
impl OutboxStatus {
pub fn is_terminal(&self) -> bool {
matches!(self, OutboxStatus::Sent | OutboxStatus::Failed(_))
}
/// Column encoding for the `outbox.status` CHECK constraint.
pub fn as_db_str(&self) -> &'static str {
match self {
OutboxStatus::Queued => "queued",
OutboxStatus::Sending => "sending",
OutboxStatus::Sent => "sent",
OutboxStatus::Failed(_) => "failed",
}
}
pub fn from_db(status: &str, last_error: Option<&str>) -> Self {
match status {
"sending" => OutboxStatus::Sending,
"sent" => OutboxStatus::Sent,
"failed" => OutboxStatus::Failed(last_error.unwrap_or("failed").to_string()),
_ => OutboxStatus::Queued,
}
}
}
impl std::fmt::Display for OutboxStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
OutboxStatus::Failed(why) => write!(f, "failed: {why}"),
other => f.write_str(other.as_db_str()),
}
}
}
/// One queued chat send. The body is not copied: it lives in the `messages`
/// row the outbox row points at, under that row's own AEAD.
#[derive(Debug, Clone)]
pub struct OutboxEntry {
pub id: i64,
pub friend_pk: Vec<u8>,
pub message_id: i64,
pub body: Vec<u8>,
pub attempts: u32,
pub next_attempt_at: i64,
pub created_at: i64,
pub status: OutboxStatus,
pub last_error: Option<String>,
}
pub struct PaymentWrite<'a> {
pub dir: &'a str,
pub kind: &'a str,
@ -190,6 +257,18 @@ impl Store {
verified INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS outbox (
id INTEGER PRIMARY KEY,
friend_id INTEGER NOT NULL REFERENCES friends(id),
message_id INTEGER NOT NULL,
attempts INTEGER NOT NULL DEFAULT 0,
next_attempt_at INTEGER NOT NULL,
status TEXT NOT NULL CHECK(status IN ('queued','sending','sent','failed')),
last_error TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS outbox_due ON outbox (status, next_attempt_at);
INSERT OR IGNORE INTO self_profile (id) VALUES (1);
",
)?;
@ -476,6 +555,20 @@ impl Store {
.map_err(Into::into)
}
/// Locator → friend. Onions are not unique in the schema (a stale row can
/// hold a rotated address), so the first match wins; the outbox uses this
/// only to pick which queue to flush early.
pub fn friend_by_onion(&self, onion: &str) -> Result<Option<Friend>> {
self.conn
.query_row(
"SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey FROM friends WHERE onion = ?1 ORDER BY id LIMIT 1",
params![onion],
friend_from_row,
)
.optional()
.map_err(Into::into)
}
pub fn list_friends(&self) -> Result<Vec<Friend>> {
let mut stmt = self.conn.prepare(
"SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey FROM friends
@ -700,6 +793,17 @@ impl Store {
}
pub fn append_message(&self, friend_pk: &[u8], dir: &str, plaintext: &[u8]) -> Result<()> {
self.append_message_id(friend_pk, dir, plaintext).map(|_| ())
}
/// Same as `append_message`, returning the row id so an outbox row can
/// point at the body instead of storing a second copy.
pub fn append_message_id(
&self,
friend_pk: &[u8],
dir: &str,
plaintext: &[u8],
) -> Result<i64> {
if dir != "in" && dir != "out" {
return Err(Error("dir must be in or out".into()));
}
@ -724,7 +828,7 @@ impl Store {
params![blob, row_id],
)?;
tx.commit()?;
Ok(())
Ok(row_id)
}
pub fn list_messages(&self, friend_pk: &[u8]) -> Result<Vec<Message>> {
@ -753,9 +857,194 @@ impl Store {
Ok(out)
}
/// Queue one already-stored chat message for retry. `next_attempt_at` is an
/// absolute unix second; `now` is used for created_at/updated_at so the
/// caller and the row agree on the clock.
pub fn enqueue_outbox(
&self,
friend_pk: &[u8],
message_id: i64,
attempts: u32,
next_attempt_at: i64,
last_error: &str,
now: i64,
) -> Result<i64> {
let friend_id: i64 = self
.conn
.query_row(
"SELECT id FROM friends WHERE pubkey = ?1",
params![friend_pk],
|row| row.get(0),
)
.map_err(|_| Error("friend not found".into()))?;
self.conn.execute(
"INSERT INTO outbox (friend_id, message_id, attempts, next_attempt_at, status, last_error, created_at, updated_at)
VALUES (?1, ?2, ?3, ?4, 'queued', ?5, ?6, ?6)",
params![friend_id, message_id, attempts, next_attempt_at, last_error, now],
)?;
Ok(self.conn.last_insert_rowid())
}
/// Rows whose backoff has elapsed: the timer trigger for the worker.
pub fn due_outbox(&self, now: i64, limit: i64) -> Result<Vec<OutboxEntry>> {
self.outbox_query(
&format!(
"{OUTBOX_SELECT} WHERE o.status = 'queued' AND o.next_attempt_at <= ?1
ORDER BY o.next_attempt_at, o.id LIMIT ?2"
),
params![now, limit],
)
}
/// Unscheduleable rows for one friend (queued or mid-attempt): the
/// "we just heard from this peer" trigger, which ignores the backoff.
pub fn outbox_for_friend(&self, friend_pk: &[u8]) -> Result<Vec<OutboxEntry>> {
self.outbox_query(
&format!(
"{OUTBOX_SELECT} WHERE f.pubkey = ?1 AND o.status IN ('queued','sending')
ORDER BY o.id"
),
params![friend_pk],
)
}
/// Every row the worker may still try: the unlock/foreground trigger.
pub fn all_pending_outbox(&self, limit: i64) -> Result<Vec<OutboxEntry>> {
self.outbox_query(
&format!(
"{OUTBOX_SELECT} WHERE o.status IN ('queued','sending')
ORDER BY o.next_attempt_at, o.id LIMIT ?1"
),
params![limit],
)
}
/// Pending and failed rows for one friend — what a UI shows as not-yet-sent.
/// Delivered rows are deleted, so absence means "sent".
pub fn pending_outbox(&self, friend_pk: &[u8]) -> Result<Vec<OutboxEntry>> {
self.outbox_query(
&format!(
"{OUTBOX_SELECT} WHERE f.pubkey = ?1 AND o.status IN ('queued','sending','failed')
ORDER BY o.id"
),
params![friend_pk],
)
}
pub fn outbox_status_of_message(&self, message_id: i64) -> Result<Option<OutboxStatus>> {
let row: Option<(String, Option<String>)> = self
.conn
.query_row(
"SELECT status, last_error FROM outbox WHERE message_id = ?1 ORDER BY id DESC LIMIT 1",
params![message_id],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.optional()?;
Ok(row.map(|(s, e)| OutboxStatus::from_db(&s, e.as_deref())))
}
pub fn mark_outbox_sending(&self, id: i64, now: i64) -> Result<()> {
self.conn.execute(
"UPDATE outbox SET status = 'sending', updated_at = ?1 WHERE id = ?2",
params![now, id],
)?;
Ok(())
}
/// Delivered. The row is dropped — the chat history is the record, and a
/// per-message status table would grow without bound.
pub fn mark_outbox_sent(&self, id: i64) -> Result<()> {
self.conn
.execute("DELETE FROM outbox WHERE id = ?1", params![id])?;
Ok(())
}
pub fn mark_outbox_failed(&self, id: i64, now: i64, why: &str) -> Result<()> {
self.conn.execute(
"UPDATE outbox SET status = 'failed', last_error = ?1, updated_at = ?2 WHERE id = ?3",
params![why, now, id],
)?;
Ok(())
}
pub fn mark_outbox_retry(
&self,
id: i64,
attempts: u32,
next_attempt_at: i64,
now: i64,
why: &str,
) -> Result<()> {
self.conn.execute(
"UPDATE outbox SET status = 'queued', attempts = ?1, next_attempt_at = ?2, last_error = ?3, updated_at = ?4 WHERE id = ?5",
params![attempts, next_attempt_at, why, now, id],
)?;
Ok(())
}
/// A row left in 'sending' means we died mid-attempt. Requeue on unlock.
pub fn reset_sending_outbox(&self) -> Result<usize> {
let n = self.conn.execute(
"UPDATE outbox SET status = 'queued' WHERE status = 'sending'",
[],
)?;
Ok(n)
}
fn outbox_query(&self, sql: &str, args: &[&dyn rusqlite::ToSql]) -> Result<Vec<OutboxEntry>> {
let mut stmt = self.conn.prepare(sql)?;
let rows = stmt.query_map(args, |row| {
Ok((
row.get::<_, i64>(0)?,
row.get::<_, Vec<u8>>(1)?,
row.get::<_, i64>(2)?,
row.get::<_, i64>(3)?,
row.get::<_, i64>(4)?,
row.get::<_, String>(5)?,
row.get::<_, Option<String>>(6)?,
row.get::<_, i64>(7)?,
row.get::<_, i64>(8)?,
row.get::<_, String>(9)?,
row.get::<_, Vec<u8>>(10)?,
))
})?;
let mut out = Vec::new();
for row in rows {
let (
id,
friend_pk,
message_id,
attempts,
next_attempt_at,
status,
last_error,
created_at,
m_friend_id,
dir,
blob,
) = row?;
let aad = message_aad(m_friend_id, &dir, message_id);
let body = crate::backup::aead_decrypt(&self.msg_key, &blob, &aad)
.map_err(|_| Error("outbox body decrypt failed".into()))?;
out.push(OutboxEntry {
id,
friend_pk,
message_id,
body,
attempts: attempts as u32,
next_attempt_at,
created_at,
status: OutboxStatus::from_db(&status, last_error.as_deref()),
last_error,
});
}
Ok(out)
}
/// Drop chat + payments history. Identity + friends stay.
/// Not a forensic erase: SSD wear-leveling can keep copies.
pub fn wipe_messages(&self) -> Result<()> {
self.conn.execute("DELETE FROM outbox", [])?;
self.conn.execute(
"UPDATE messages SET plaintext = zeroblob(length(plaintext))",
[],
@ -1041,6 +1330,12 @@ fn mkdir_700(path: &Path) -> Result<()> {
Ok(())
}
/// Base projection for outbox rows: the body comes from the `messages` row the
/// outbox row points at, so it stays under that row's AEAD + AAD.
const OUTBOX_SELECT: &str = "SELECT o.id, f.pubkey, o.message_id, o.attempts, o.next_attempt_at, \
o.status, o.last_error, o.created_at, m.friend_id, m.dir, m.plaintext \
FROM outbox o JOIN friends f ON f.id = o.friend_id JOIN messages m ON m.id = o.message_id";
/// AAD: `owmsg1` || friend_id_le64 || dir || 0x00 || row_id_le64
fn message_aad(friend_id: i64, dir: &str, row_id: i64) -> Vec<u8> {
let mut aad = Vec::with_capacity(6 + 8 + dir.len() + 1 + 8);