feat(outbox): local retry queue for chat sends
All checks were successful
ci / test (pull_request) Successful in 3m21s
All checks were successful
ci / test (pull_request) Successful in 3m21s
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:
parent
2b2ad573c0
commit
ad59a171b3
9 changed files with 1042 additions and 53 deletions
308
src/outbox.rs
Normal file
308
src/outbox.rs
Normal file
|
|
@ -0,0 +1,308 @@
|
|||
//! Local-only outbox.
|
||||
//!
|
||||
//! When a peer's v3 onion cannot be dialed, a chat send is persisted locally and
|
||||
//! retried by a background worker with exponential backoff. There is no server
|
||||
//! and no store-and-forward relay: every attempt is a fresh Noise IK handshake
|
||||
//! straight to the friend's onion, so a queued message is never handed to a
|
||||
//! third party. File transfer and payment frames stay fail-closed — only chat
|
||||
//! goes through here.
|
||||
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::{Arc, Mutex, MutexGuard};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use tokio::sync::Notify;
|
||||
|
||||
use crate::frame;
|
||||
use crate::hs::{Client, HS_PORT};
|
||||
use crate::session::{self, Keys};
|
||||
use crate::store::Store;
|
||||
|
||||
pub use crate::store::{OutboxEntry, OutboxStatus};
|
||||
|
||||
/// First retry waits this long.
|
||||
pub const BACKOFF_START_SECS: i64 = 30;
|
||||
/// Backoff never sleeps longer than this.
|
||||
pub const BACKOFF_CAP_SECS: i64 = 1_800;
|
||||
/// Attempts after which a queued message is terminally `Failed`.
|
||||
pub const DEFAULT_MAX_ATTEMPTS: u32 = 8;
|
||||
/// Worker scan period. The shortest backoff is 30s, so a slower scan still
|
||||
/// lands each retry close to its schedule without busy-waiting.
|
||||
pub const WORKER_TICK: Duration = Duration::from_secs(15);
|
||||
/// Cap on rows attempted in one pass, so a big backlog cannot monopolize the
|
||||
/// worker.
|
||||
const MAX_PER_PASS: i64 = 32;
|
||||
|
||||
pub type BoxFut<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
|
||||
|
||||
/// Pure backoff schedule, asserted numerically by a unit test: 30s, 60s, 120s…
|
||||
/// capped at 30 min. `attempt` is the number of retries already made.
|
||||
pub fn backoff_secs(attempt: u32) -> i64 {
|
||||
// 30 << 16 is the largest shift we ever need to reach the cap, so this
|
||||
// cannot overflow even for a silly attempt count.
|
||||
(BACKOFF_START_SECS << attempt.min(16)).min(BACKOFF_CAP_SECS)
|
||||
}
|
||||
|
||||
/// Protocol failures: another attempt cannot fix a bad signature, a bad frame
|
||||
/// header, or an oversize payload, so they must fail loudly and never queue.
|
||||
const PERMANENT_ERRORS: &[&str] = &[
|
||||
"fingerprint mismatch",
|
||||
"bad identity proof",
|
||||
"unexpected handshake payload",
|
||||
"frame too large",
|
||||
"bad version",
|
||||
"length mismatch",
|
||||
"short frame",
|
||||
];
|
||||
|
||||
pub fn is_permanent_send_error(err: &str) -> bool {
|
||||
PERMANENT_ERRORS.iter().any(|p| err.contains(p))
|
||||
}
|
||||
|
||||
/// One delivery attempt. Implemented by Arti for real sends and by tests for a
|
||||
/// fake or flaky peer.
|
||||
pub trait Deliverer: Send + Sync {
|
||||
fn deliver<'a>(
|
||||
&'a self,
|
||||
onion: &'a str,
|
||||
pinned_id: &'a [u8],
|
||||
prekey: &'a [u8],
|
||||
plaintext: &'a [u8],
|
||||
) -> BoxFut<'a, Result<(), String>>;
|
||||
}
|
||||
|
||||
/// Real transport: dial the v3 onion, Noise IK handshake pinned to the friend's
|
||||
/// identity key, send exactly one application frame, drop the circuit.
|
||||
pub struct ArtiDeliverer {
|
||||
client: Client,
|
||||
keys: Keys,
|
||||
}
|
||||
|
||||
impl ArtiDeliverer {
|
||||
pub fn new(client: Client, keys: Keys) -> Self {
|
||||
Self { client, keys }
|
||||
}
|
||||
}
|
||||
|
||||
impl Deliverer for ArtiDeliverer {
|
||||
fn deliver<'a>(
|
||||
&'a self,
|
||||
onion: &'a str,
|
||||
pinned_id: &'a [u8],
|
||||
prekey: &'a [u8],
|
||||
plaintext: &'a [u8],
|
||||
) -> BoxFut<'a, Result<(), String>> {
|
||||
Box::pin(async move {
|
||||
let mut stream = self
|
||||
.client
|
||||
.connect((onion, HS_PORT))
|
||||
.await
|
||||
.map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?;
|
||||
let mut sess =
|
||||
session::handshake_initiator(&mut stream, &self.keys, pinned_id, prekey)
|
||||
.await
|
||||
.map_err(|e| e.into_message())?;
|
||||
let ct = sess.encrypt(plaintext).map_err(|e| e.into_message())?;
|
||||
frame::write_frame(&mut stream, &ct)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Outbox {
|
||||
store: Arc<Mutex<Store>>,
|
||||
deliverer: Arc<dyn Deliverer>,
|
||||
max_attempts: u32,
|
||||
wake: Notify,
|
||||
}
|
||||
|
||||
impl Outbox {
|
||||
pub fn new(store: Arc<Mutex<Store>>, deliverer: Arc<dyn Deliverer>) -> Self {
|
||||
Self {
|
||||
store,
|
||||
deliverer,
|
||||
max_attempts: DEFAULT_MAX_ATTEMPTS,
|
||||
wake: Notify::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_max_attempts(mut self, max: u32) -> Self {
|
||||
self.max_attempts = max.max(1);
|
||||
self
|
||||
}
|
||||
|
||||
/// The transport, for callers (locator/profile pushes) that stay fail-closed
|
||||
/// and must not queue.
|
||||
pub fn deliverer(&self) -> &dyn Deliverer {
|
||||
self.deliverer.as_ref()
|
||||
}
|
||||
|
||||
/// Try once. `Ok(Sent)` — delivered now. `Ok(Queued)` — the peer's onion is
|
||||
/// unreachable, the message is persisted and will be retried. `Err` — a
|
||||
/// protocol error or a bad local state, never retried.
|
||||
pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<OutboxStatus, String> {
|
||||
let (onion, prekey) = self.target(friend_pk)?;
|
||||
match self.deliverer.deliver(&onion, friend_pk, &prekey, plaintext).await {
|
||||
Ok(()) => {
|
||||
self.store()?.append_message(friend_pk, "out", plaintext)?;
|
||||
Ok(OutboxStatus::Sent)
|
||||
}
|
||||
Err(e) if is_permanent_send_error(&e) => Err(e),
|
||||
Err(e) => {
|
||||
let now = unix_now();
|
||||
let store = self.store()?;
|
||||
let message_id = store.append_message_id(friend_pk, "out", plaintext)?;
|
||||
store.enqueue_outbox(
|
||||
friend_pk,
|
||||
message_id,
|
||||
1,
|
||||
now + backoff_secs(0),
|
||||
&e,
|
||||
now,
|
||||
)?;
|
||||
Ok(OutboxStatus::Queued)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Timer trigger: every row whose backoff has elapsed gets one attempt.
|
||||
pub async fn tick(&self, now: i64) -> Result<Vec<(i64, OutboxStatus)>, String> {
|
||||
let due = self.store()?.due_outbox(now, MAX_PER_PASS)?;
|
||||
self.attempt(due, now).await
|
||||
}
|
||||
|
||||
/// Unlock / foreground trigger: every outstanding row gets one attempt now,
|
||||
/// regardless of where it sits in the backoff.
|
||||
pub async fn flush_all(&self, now: i64) -> Result<Vec<(i64, OutboxStatus)>, String> {
|
||||
let rows = self.store()?.all_pending_outbox(MAX_PER_PASS)?;
|
||||
self.attempt(rows, now).await
|
||||
}
|
||||
|
||||
/// Trigger (c): we just heard from this peer, so try their rows immediately.
|
||||
pub async fn flush_friend(
|
||||
&self,
|
||||
friend_pk: &[u8],
|
||||
now: i64,
|
||||
) -> Result<Vec<(i64, OutboxStatus)>, String> {
|
||||
let rows = self.store()?.outbox_for_friend(friend_pk)?;
|
||||
self.attempt(rows, now).await
|
||||
}
|
||||
|
||||
/// Pending and failed rows for one friend. Delivered rows are deleted, so a
|
||||
/// message that is not here was either sent first try or flushed since.
|
||||
pub fn pending(&self, friend_pk: &[u8]) -> Result<Vec<OutboxEntry>, String> {
|
||||
self.store()?.pending_outbox(friend_pk).map_err(store_err)
|
||||
}
|
||||
|
||||
pub fn status_of_message(&self, message_id: i64) -> Result<Option<OutboxStatus>, String> {
|
||||
self.store()?
|
||||
.outbox_status_of_message(message_id)
|
||||
.map_err(store_err)
|
||||
}
|
||||
|
||||
/// A process that died mid-attempt leaves `sending` rows behind; requeue
|
||||
/// them on unlock so they are retried instead of stranded.
|
||||
pub fn reset_stale(&self) -> Result<usize, String> {
|
||||
self.store()?.reset_sending_outbox().map_err(store_err)
|
||||
}
|
||||
|
||||
/// Wake the worker (e.g. after `flush_all` was queued from a UI thread).
|
||||
pub fn kick(&self) {
|
||||
self.wake.notify_one();
|
||||
}
|
||||
|
||||
/// Background retry worker. Aborted by dropping the returned handle.
|
||||
pub fn spawn_worker(self: &Arc<Self>) -> tokio::task::JoinHandle<()> {
|
||||
let me = Arc::clone(self);
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
if let Err(e) = me.tick(unix_now()).await {
|
||||
eprintln!("outbox: {e}");
|
||||
}
|
||||
tokio::select! {
|
||||
_ = tokio::time::sleep(WORKER_TICK) => {}
|
||||
_ = me.wake.notified() => {}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async fn attempt(
|
||||
&self,
|
||||
rows: Vec<OutboxEntry>,
|
||||
now: i64,
|
||||
) -> Result<Vec<(i64, OutboxStatus)>, String> {
|
||||
let mut out = Vec::with_capacity(rows.len());
|
||||
for entry in rows {
|
||||
self.store()?.mark_outbox_sending(entry.id, now)?;
|
||||
let (onion, prekey) = match self.target(&entry.friend_pk) {
|
||||
Ok(t) => t,
|
||||
Err(e) => {
|
||||
self.store()?.mark_outbox_failed(entry.id, now, &e)?;
|
||||
out.push((entry.id, OutboxStatus::Failed(e)));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let result = self
|
||||
.deliverer
|
||||
.deliver(&onion, &entry.friend_pk, &prekey, &entry.body)
|
||||
.await;
|
||||
let status = match result {
|
||||
Ok(()) => {
|
||||
self.store()?.mark_outbox_sent(entry.id)?;
|
||||
OutboxStatus::Sent
|
||||
}
|
||||
Err(e) if is_permanent_send_error(&e) => {
|
||||
self.store()?.mark_outbox_failed(entry.id, now, &e)?;
|
||||
OutboxStatus::Failed(e)
|
||||
}
|
||||
Err(e) => {
|
||||
let attempts = entry.attempts.saturating_add(1);
|
||||
if attempts >= self.max_attempts {
|
||||
self.store()?.mark_outbox_failed(entry.id, now, &e)?;
|
||||
OutboxStatus::Failed(e)
|
||||
} else {
|
||||
let next = now + backoff_secs(attempts - 1);
|
||||
self.store()?
|
||||
.mark_outbox_retry(entry.id, attempts, next, now, &e)?;
|
||||
OutboxStatus::Queued
|
||||
}
|
||||
}
|
||||
};
|
||||
out.push((entry.id, status));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Friend's current locator + Noise static. Missing prekey means the invite
|
||||
/// was never completed — retrying cannot fix that, so it is fatal.
|
||||
fn target(&self, friend_pk: &[u8]) -> Result<(String, Vec<u8>), String> {
|
||||
let store = self.store()?;
|
||||
let f = store
|
||||
.get_friend(friend_pk)
|
||||
.map_err(store_err)?
|
||||
.ok_or_else(|| "unknown friend".to_string())?;
|
||||
if f.prekey.len() != 32 {
|
||||
return Err("friend missing prekey".into());
|
||||
}
|
||||
Ok((f.onion, f.prekey))
|
||||
}
|
||||
|
||||
fn store(&self) -> Result<MutexGuard<'_, Store>, String> {
|
||||
self.store.lock().map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn store_err(e: crate::store::Error) -> String {
|
||||
e.to_string()
|
||||
}
|
||||
|
||||
fn unix_now() -> i64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs() as i64)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
Loading…
Reference in a new issue