feat(outbox): local retry queue for chat sends
All checks were successful
ci / test (pull_request) Successful in 3m22s
All checks were successful
ci / test (pull_request) Successful in 3m22s
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
e6e2a158a8
commit
068b655c19
9 changed files with 1042 additions and 53 deletions
|
|
@ -5,6 +5,7 @@ pub mod frame;
|
|||
pub mod hs;
|
||||
pub mod loc;
|
||||
pub mod node;
|
||||
pub mod outbox;
|
||||
pub mod pay;
|
||||
pub mod profile;
|
||||
pub mod qr;
|
||||
|
|
|
|||
130
src/node.rs
130
src/node.rs
|
|
@ -14,6 +14,7 @@ use crate::file;
|
|||
use crate::frame;
|
||||
use crate::hs::{self, Client, HS_PORT};
|
||||
use crate::loc;
|
||||
use crate::outbox::{ArtiDeliverer, Outbox, OutboxStatus};
|
||||
use crate::pay;
|
||||
use crate::profile;
|
||||
use crate::qr;
|
||||
|
|
@ -39,9 +40,18 @@ impl Drop for HsHandle {
|
|||
}
|
||||
}
|
||||
|
||||
/// Abort the outbox worker when the node goes away.
|
||||
struct WorkerHandle(tokio::task::JoinHandle<()>);
|
||||
|
||||
impl Drop for WorkerHandle {
|
||||
fn drop(&mut self) {
|
||||
self.0.abort();
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Node {
|
||||
home: PathBuf,
|
||||
store: Mutex<Store>,
|
||||
store: Arc<Mutex<Store>>,
|
||||
client: Client,
|
||||
hs: Mutex<Option<HsHandle>>,
|
||||
onion: Mutex<String>,
|
||||
|
|
@ -49,6 +59,8 @@ pub struct Node {
|
|||
wallet: Wallet,
|
||||
incoming_limit: Mutex<TokenBucket>,
|
||||
inbox: Mutex<file::Inbox>,
|
||||
outbox: Arc<Outbox>,
|
||||
_outbox_worker: WorkerHandle,
|
||||
}
|
||||
|
||||
impl Node {
|
||||
|
|
@ -79,9 +91,17 @@ impl Node {
|
|||
let (svc, rend) = launched;
|
||||
let onion = hs::onion_string(&svc)?;
|
||||
let inbox = file::Inbox::new(home.join("inbox"));
|
||||
let store = Arc::new(Mutex::new(store));
|
||||
let outbox = Arc::new(Outbox::new(
|
||||
Arc::clone(&store),
|
||||
Arc::new(ArtiDeliverer::new(client.clone(), keys.clone())),
|
||||
));
|
||||
if let Err(e) = outbox.reset_stale() {
|
||||
eprintln!("outbox: {e}");
|
||||
}
|
||||
let node = Arc::new(Self {
|
||||
home,
|
||||
store: Mutex::new(store),
|
||||
store,
|
||||
client,
|
||||
hs: Mutex::new(None),
|
||||
onion: Mutex::new(onion.clone()),
|
||||
|
|
@ -89,7 +109,12 @@ impl Node {
|
|||
wallet: Wallet::from_env(),
|
||||
incoming_limit: Mutex::new(TokenBucket::default()),
|
||||
inbox: Mutex::new(inbox),
|
||||
outbox: Arc::clone(&outbox),
|
||||
_outbox_worker: WorkerHandle(outbox.spawn_worker()),
|
||||
});
|
||||
// Unlock trigger: flush anything queued by a previous run now, in the
|
||||
// background, rather than waiting out its backoff.
|
||||
spawn_flush_all(Arc::clone(&node.outbox));
|
||||
// Accept rens before waiting so a reachability probe can succeed
|
||||
// while combined status is still Bootstrapping.
|
||||
let rend = spawn_rend(Arc::clone(&node), rend);
|
||||
|
|
@ -416,6 +441,8 @@ impl Node {
|
|||
self.try_send(&onion, friend_pk, &prekey, plaintext).await
|
||||
}
|
||||
|
||||
/// Dial a peer's onion. Success is evidence the peer is up, which is one of
|
||||
/// the outbox retry triggers.
|
||||
pub async fn connect_onion(&self, onion: &str) -> Result<(), String> {
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(20),
|
||||
|
|
@ -424,6 +451,14 @@ impl Node {
|
|||
.await
|
||||
.map_err(|_| format!("connect {onion}:{HS_PORT} timed out"))?
|
||||
.map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?;
|
||||
if let Ok(Some(friend)) = self
|
||||
.store
|
||||
.lock()
|
||||
.map_err(|e| e.to_string())
|
||||
.and_then(|s| s.friend_by_onion(onion).map_err(|e| e.to_string()))
|
||||
{
|
||||
spawn_flush_friend(Arc::clone(&self.outbox), friend.pubkey);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -506,36 +541,30 @@ impl Node {
|
|||
Ok(name)
|
||||
}
|
||||
|
||||
pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<(), String> {
|
||||
let (onion, prekey) = {
|
||||
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||||
let f = store
|
||||
.get_friend(friend_pk)
|
||||
.map_err(|e| e.to_string())?
|
||||
.ok_or_else(|| "unknown friend".to_string())?;
|
||||
if f.prekey.len() != 32 {
|
||||
return Err("friend missing prekey".into());
|
||||
}
|
||||
(f.onion, f.prekey)
|
||||
};
|
||||
let deadline = Instant::now() + Duration::from_secs(180);
|
||||
let mut last = None::<String>;
|
||||
while Instant::now() < deadline {
|
||||
match self.try_send(&onion, friend_pk, &prekey, plaintext).await {
|
||||
Ok(()) => {
|
||||
self.store
|
||||
.lock()
|
||||
.map_err(|e| e.to_string())?
|
||||
.append_message(friend_pk, "out", plaintext)
|
||||
.map_err(|e| e.to_string())?;
|
||||
return Ok(());
|
||||
}
|
||||
Err(e) if e.contains("fingerprint mismatch") => return Err(e),
|
||||
Err(e) => last = Some(e),
|
||||
}
|
||||
tokio::time::sleep(Duration::from_secs(3)).await;
|
||||
}
|
||||
Err(last.unwrap_or_else(|| "send timed out".into()))
|
||||
/// Send one chat message. Returns `Sent` when it went out now and `Queued`
|
||||
/// when the peer's onion is unreachable — the outbox worker then retries with
|
||||
/// backoff. A real protocol error (signature mismatch, unknown/short/oversize
|
||||
/// frame) still fails immediately and is never retried.
|
||||
pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<OutboxStatus, String> {
|
||||
self.outbox.send(friend_pk, plaintext).await
|
||||
}
|
||||
|
||||
/// Pending and failed outbox rows for a friend, for UI surfacing.
|
||||
/// Delivered rows are dropped, so a message absent here was sent.
|
||||
pub fn outbox_pending(&self, friend_pk: &[u8]) -> Result<Vec<crate::store::OutboxEntry>, String> {
|
||||
self.outbox.pending(friend_pk)
|
||||
}
|
||||
|
||||
pub fn outbox_status_of_message(
|
||||
&self,
|
||||
message_id: i64,
|
||||
) -> Result<Option<OutboxStatus>, String> {
|
||||
self.outbox.status_of_message(message_id)
|
||||
}
|
||||
|
||||
/// Foreground/unlock trigger: try every outstanding queued send now.
|
||||
pub fn flush_outbox(&self) {
|
||||
spawn_flush_all(Arc::clone(&self.outbox));
|
||||
}
|
||||
|
||||
async fn push_loc(
|
||||
|
|
@ -568,20 +597,10 @@ impl Node {
|
|||
remote_prekey: &[u8],
|
||||
plaintext: &[u8],
|
||||
) -> Result<(), String> {
|
||||
let mut stream = self
|
||||
.client
|
||||
.connect((onion, HS_PORT))
|
||||
self.outbox
|
||||
.deliverer()
|
||||
.deliver(onion, pinned_id, remote_prekey, plaintext)
|
||||
.await
|
||||
.map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?;
|
||||
let keys = self.keys()?;
|
||||
let mut sess = session::handshake_initiator(&mut stream, &keys, pinned_id, remote_prekey)
|
||||
.await
|
||||
.map_err(session_err)?;
|
||||
let ct = sess.encrypt(plaintext).map_err(session_err)?;
|
||||
frame::write_frame(&mut stream, &ct)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn handle_incoming<S>(&self, stream: &mut S) -> Result<(), String>
|
||||
|
|
@ -598,6 +617,9 @@ impl Node {
|
|||
})
|
||||
.await
|
||||
.map_err(session_err)?;
|
||||
// Trigger (c): the peer just proved they are online. Try their queued
|
||||
// sends now instead of waiting out the backoff, off this stream's path.
|
||||
spawn_flush_friend(Arc::clone(&self.outbox), sess.peer_identity.clone());
|
||||
let ct = frame::read_frame(stream).await.map_err(|e| e.to_string())?;
|
||||
let pt = sess.decrypt(&ct).map_err(session_err)?;
|
||||
match dispatch::classify(&pt) {
|
||||
|
|
@ -814,6 +836,24 @@ fn spawn_rend(
|
|||
})
|
||||
}
|
||||
|
||||
/// Foreground/unlock flush: every outstanding queued send gets one attempt now.
|
||||
fn spawn_flush_all(outbox: Arc<Outbox>) {
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = outbox.flush_all(unix_now()).await {
|
||||
eprintln!("outbox: {e}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// We just saw this peer (handshake or successful dial): try their queue now.
|
||||
fn spawn_flush_friend(outbox: Arc<Outbox>, friend_pk: Vec<u8>) {
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = outbox.flush_friend(&friend_pk, unix_now()).await {
|
||||
eprintln!("outbox: {e}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn next_hs_nickname(cur: &str) -> String {
|
||||
let n = cur
|
||||
.strip_prefix("ow")
|
||||
|
|
|
|||
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)
|
||||
}
|
||||
|
|
@ -35,6 +35,16 @@ impl Error {
|
|||
pub fn is_fingerprint_mismatch(&self) -> bool {
|
||||
self.mismatch
|
||||
}
|
||||
|
||||
/// String for the UI: a pinned-identity mismatch gets the documented banner,
|
||||
/// everything else is the underlying snow/framing message.
|
||||
pub fn into_message(self) -> String {
|
||||
if self.mismatch {
|
||||
crate::tui::fingerprint_mismatch_banner().to_string()
|
||||
} else {
|
||||
self.msg
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Error {
|
||||
|
|
|
|||
297
src/store.rs
297
src/store.rs
|
|
@ -40,6 +40,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],
|
||||
|
|
@ -88,6 +97,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,
|
||||
|
|
@ -189,6 +256,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);
|
||||
",
|
||||
)?;
|
||||
|
|
@ -475,6 +554,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
|
||||
|
|
@ -699,6 +792,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()));
|
||||
}
|
||||
|
|
@ -723,7 +827,7 @@ impl Store {
|
|||
params![blob, row_id],
|
||||
)?;
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
Ok(row_id)
|
||||
}
|
||||
|
||||
pub fn list_messages(&self, friend_pk: &[u8]) -> Result<Vec<Message>> {
|
||||
|
|
@ -752,9 +856,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))",
|
||||
[],
|
||||
|
|
@ -859,6 +1148,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);
|
||||
|
|
|
|||
|
|
@ -1449,8 +1449,10 @@ impl App {
|
|||
let (tx, rx) = mpsc::channel();
|
||||
self.status_note = Some("sending".into());
|
||||
std::mem::drop(self.rt.spawn(async move {
|
||||
// send() now reports `Sent`/`Queued`; surfacing `queued` in the
|
||||
// footer is a follow-up card, so this arm keeps today's wording.
|
||||
let note = match node.send(&pk, &body).await {
|
||||
Ok(()) => "sent".to_string(),
|
||||
Ok(_) => "sent".to_string(),
|
||||
Err(e) => format!("send failed: {e}"),
|
||||
};
|
||||
let _ = tx.send(note);
|
||||
|
|
|
|||
Loading…
Reference in a new issue