feat(outbox): local chat retry queue — queue sends and retry with backoff #45
9 changed files with 1042 additions and 53 deletions
|
|
@ -19,7 +19,7 @@ SOCKS proxy.”
|
|||
| Discovery | DHT + bootstrap nodes | Out-of-band invite only |
|
||||
| After lookup | Direct IP or TCP relay (SOCKS if you forced it) | v3 onion ↔ v3 onion |
|
||||
| Address | Tox ID lives in the DHT | ed25519 pubkey is identity; onion is a locator |
|
||||
| Offline send | Expected (relays / retry) | Fail closed — no outbox |
|
||||
| Offline send | Expected (relays / retry) | Queued locally, retried peer-to-peer (no relay) |
|
||||
| Mixed clearnet | ToT can still talk to non-Tor Tox | No clearnet peers |
|
||||
|
||||
There is no directory, no name server, no introduction point of our own, and no
|
||||
|
|
@ -51,8 +51,18 @@ not on the wire.
|
|||
4. File transfer is N independent sessions (one handshake per chunk). There is
|
||||
no multiplexed long-lived stream in v1.
|
||||
|
||||
If the onion is down, send fails. No retry queue except the locator-push path,
|
||||
which retries for 180 seconds and then gives up.
|
||||
If the onion is down, a **chat** send is persisted to the local outbox and
|
||||
retried by a background worker with exponential backoff (30s, doubling, capped
|
||||
at 30 min; 8 attempts, then terminal `Failed`). There is no server and no
|
||||
store-and-forward relay: each attempt is a fresh handshake straight to
|
||||
`(friend.onion, 80)`, exactly as above. Retries fire on a timer, on
|
||||
unlock/foreground, and whenever that peer is heard from (successful handshake or
|
||||
`connect_onion()`). A protocol failure — signature mismatch, unknown frame,
|
||||
oversize — is not a transport failure and is never queued.
|
||||
|
||||
File transfer and payment frames stay fail-closed: they are one-shot and are
|
||||
**not** queued. The locator-push path still retries for 180 seconds and then
|
||||
gives up.
|
||||
|
||||
Incoming rendezvous accepts are token-bucket limited: 30 per 60s, burst 10.
|
||||
Excess is dropped before handshake. That is availability, not anonymity.
|
||||
|
|
|
|||
|
|
@ -54,7 +54,16 @@ dir (new identity); same disk caveat.
|
|||
|
||||
## Fail closed
|
||||
|
||||
Peer onion down → send fails. Fingerprint mismatch vs the pinned key → hard fail, no send. Arti HS experimental: if it cannot publish, OnionWire stops; it does not fall back to C-tor.
|
||||
Peer onion down → a **chat** send is queued locally and retried (see “Local outbox (chat retry queue)”); file transfer and payment frames still fail immediately. Fingerprint mismatch vs the pinned key → hard fail, no send, never queued. Arti HS experimental: if it cannot publish, OnionWire stops; it does not fall back to C-tor.
|
||||
|
||||
## Local outbox (chat retry queue) is local, and it re-dials on a schedule
|
||||
|
||||
A chat send to an unreachable onion is written to an `outbox` row next to its `messages` row and retried in the background. There is no server-side queue: a queued message is never handed to a third party, and it dies with the device. Two consequences are real and are accepted:
|
||||
|
||||
- **Device seizure.** A pending (never-delivered) message sits in the same SQLCipher store as the rest of the history, under the same per-row AEAD and the same passphrase-derived key — no weaker, but also no shorter-lived. Seizure *with* the passphrase reveals messages that were never actually sent, including ones the sender may have moved on from; seizure without it reveals nothing in this store. `/wipe` clears outbox rows with the rest of chat history; `/wipe-all` removes them with the data dir. Neither is a forensic erase.
|
||||
- **Retry cadence is a local traffic-analysis surface.** A queued send re-dials the peer's onion on a backoff schedule while the app runs. An observer of your Tor client (or the network in front of it) sees a repeating connection attempt to one onion on a predictable cadence — it does not learn the plaintext or the recipient identity, but it can infer that you have an undelivered message for someone, and roughly when you composed it. The backoff is per-row, capped at one attempt per 30 min per message, and stops after 8 attempts or on a terminal failure.
|
||||
|
||||
The queue is bounded in scope: chat only. File transfer and `rcp` frames are one-shot, so a failed payment claim does not sit in the store being retried forever.
|
||||
|
||||
## Profile is friend-visible, not a directory
|
||||
|
||||
|
|
@ -95,5 +104,7 @@ the peer already knows the plaintext they sent.
|
|||
|
||||
## Out of v1
|
||||
|
||||
Prosody, XMPP, s2s, MAM, carbons, outbox, multi-device, DHT / name server,
|
||||
A/V.
|
||||
Prosody, XMPP, s2s, MAM, carbons, a **server-side** outbox / store-and-forward
|
||||
relay, multi-device, DHT / name server, A/V. The local retry queue of the
|
||||
previous section is not an outbox in the XMPP sense: it never leaves the device.
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
312
tests/outbox.rs
Normal file
312
tests/outbox.rs
Normal file
|
|
@ -0,0 +1,312 @@
|
|||
//! Local outbox: queue a chat send when the peer's onion is unreachable, retry
|
||||
//! with exponential backoff, expose a terminal status. All offline — the
|
||||
//! transport is a fake deliverer, so these run without Tor.
|
||||
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use onionwire::outbox::{
|
||||
BACKOFF_CAP_SECS, BACKOFF_START_SECS, BoxFut, Deliverer, Outbox, OutboxStatus, backoff_secs,
|
||||
is_permanent_send_error,
|
||||
};
|
||||
use onionwire::Store;
|
||||
|
||||
const PASS: &str = "outbox-pass";
|
||||
|
||||
fn pk(tag: u8) -> [u8; 32] {
|
||||
let mut k = [0u8; 32];
|
||||
k[0] = tag;
|
||||
k
|
||||
}
|
||||
|
||||
/// Fails `fail_times` dials with `err`, then succeeds and records the plaintext.
|
||||
struct Flaky {
|
||||
fail_times: AtomicUsize,
|
||||
err: String,
|
||||
calls: AtomicUsize,
|
||||
delivered: Mutex<Vec<Vec<u8>>>,
|
||||
}
|
||||
|
||||
impl Flaky {
|
||||
fn new(fail_times: usize, err: &str) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
fail_times: AtomicUsize::new(fail_times),
|
||||
err: err.into(),
|
||||
calls: AtomicUsize::new(0),
|
||||
delivered: Mutex::new(Vec::new()),
|
||||
})
|
||||
}
|
||||
|
||||
fn calls(&self) -> usize {
|
||||
self.calls.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
fn delivered(&self) -> Vec<Vec<u8>> {
|
||||
self.delivered.lock().unwrap().clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl Deliverer for Flaky {
|
||||
fn deliver<'a>(
|
||||
&'a self,
|
||||
_onion: &'a str,
|
||||
_pinned_id: &'a [u8],
|
||||
_prekey: &'a [u8],
|
||||
plaintext: &'a [u8],
|
||||
) -> BoxFut<'a, Result<(), String>> {
|
||||
self.calls.fetch_add(1, Ordering::SeqCst);
|
||||
let left = self.fail_times.load(Ordering::SeqCst);
|
||||
if left > 0 {
|
||||
self.fail_times.fetch_sub(1, Ordering::SeqCst);
|
||||
let err = self.err.clone();
|
||||
return Box::pin(async move { Err(err) });
|
||||
}
|
||||
self.delivered.lock().unwrap().push(plaintext.to_vec());
|
||||
Box::pin(async move { Ok(()) })
|
||||
}
|
||||
}
|
||||
|
||||
fn store_and_friend(dir: &std::path::Path, onion: &str) -> Arc<Mutex<Store>> {
|
||||
let store = Store::open_at_with_passphrase(dir, PASS).expect("open store");
|
||||
store.upsert_friend(&pk(1), onion, None).unwrap();
|
||||
store.set_friend_prekey(&pk(1), &[7u8; 32]).unwrap();
|
||||
Arc::new(Mutex::new(store))
|
||||
}
|
||||
|
||||
fn outbox(store: Arc<Mutex<Store>>, deliverer: Arc<dyn Deliverer>, max_attempts: u32) -> Outbox {
|
||||
Outbox::new(store, deliverer).with_max_attempts(max_attempts)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backoff_schedule_doubles_from_30s_and_caps_at_30m() {
|
||||
assert_eq!(BACKOFF_START_SECS, 30);
|
||||
assert_eq!(BACKOFF_CAP_SECS, 1800);
|
||||
let got: Vec<i64> = (0..9).map(backoff_secs).collect();
|
||||
assert_eq!(
|
||||
got,
|
||||
vec![30, 60, 120, 240, 480, 960, 1800, 1800, 1800],
|
||||
"exponential backoff, capped"
|
||||
);
|
||||
assert_eq!(
|
||||
backoff_secs(u32::MAX),
|
||||
BACKOFF_CAP_SECS,
|
||||
"no overflow at silly attempt counts"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transport_errors_are_retryable_protocol_errors_are_not() {
|
||||
assert!(!is_permanent_send_error(
|
||||
"connect abc.onion:80: timed out"
|
||||
));
|
||||
assert!(!is_permanent_send_error("connect abc.onion:80: refused"));
|
||||
assert!(is_permanent_send_error("fingerprint mismatch"));
|
||||
assert!(is_permanent_send_error("frame too large"));
|
||||
assert!(is_permanent_send_error("bad version"));
|
||||
assert!(is_permanent_send_error("bad identity proof"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn send_to_dead_onion_is_queued_and_row_persists() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = store_and_friend(dir.path(), "dead.onion");
|
||||
let dead = Flaky::new(usize::MAX, "connect dead.onion:80: timed out");
|
||||
let ob = outbox(Arc::clone(&store), dead, 8);
|
||||
|
||||
let status = ob.send(&pk(1), b"hello dead peer").await.unwrap();
|
||||
assert_eq!(status, OutboxStatus::Queued, "dead onion must queue, not Err");
|
||||
assert!(!status.is_terminal());
|
||||
|
||||
let pending = ob.pending(&pk(1)).unwrap();
|
||||
assert_eq!(pending.len(), 1, "one outbox row");
|
||||
assert_eq!(pending[0].status, OutboxStatus::Queued);
|
||||
assert_eq!(pending[0].attempts, 1, "the immediate attempt counted");
|
||||
assert!(
|
||||
ob.status_of_message(pending[0].message_id).unwrap().is_some(),
|
||||
"status is addressable by chat row id"
|
||||
);
|
||||
|
||||
// The chat line is already in local history while it waits.
|
||||
let msgs = store.lock().unwrap().list_messages(&pk(1)).unwrap();
|
||||
assert_eq!(msgs.len(), 1);
|
||||
assert_eq!(msgs[0].dir, "out");
|
||||
assert_eq!(msgs[0].plaintext, b"hello dead peer");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn flaky_peer_is_flushed_by_the_worker_on_schedule() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = store_and_friend(dir.path(), "flaky.onion");
|
||||
// First dial fails (the immediate one), the rest succeed: "peer came up".
|
||||
let flaky = Flaky::new(1, "connect flaky.onion:80: timed out");
|
||||
let ob = outbox(Arc::clone(&store), flaky.clone(), 8);
|
||||
|
||||
let status = ob.send(&pk(1), b"late hello").await.unwrap();
|
||||
assert_eq!(status, OutboxStatus::Queued);
|
||||
let next = ob.pending(&pk(1)).unwrap()[0].next_attempt_at;
|
||||
assert_eq!(
|
||||
next - ob.pending(&pk(1)).unwrap()[0].created_at,
|
||||
BACKOFF_START_SECS,
|
||||
"first retry waits the start of the schedule"
|
||||
);
|
||||
|
||||
// Too early: the worker must not dial out of schedule.
|
||||
let t0 = next - BACKOFF_START_SECS;
|
||||
let fired = ob.tick(t0 + BACKOFF_START_SECS - 1).await.unwrap();
|
||||
assert!(fired.is_empty(), "not due yet");
|
||||
|
||||
let fired = ob.tick(t0 + BACKOFF_START_SECS).await.unwrap();
|
||||
assert_eq!(fired.len(), 1);
|
||||
assert_eq!(fired[0].1, OutboxStatus::Sent);
|
||||
assert_eq!(flaky.delivered(), vec![b"late hello".to_vec()]);
|
||||
assert!(
|
||||
ob.pending(&pk(1)).unwrap().is_empty(),
|
||||
"delivered rows leave the pending set"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn max_attempts_reaches_failed_and_stops_retrying() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = store_and_friend(dir.path(), "gone.onion");
|
||||
let dead = Flaky::new(usize::MAX, "connect gone.onion:80: timed out");
|
||||
let ob = outbox(Arc::clone(&store), dead.clone(), 3);
|
||||
|
||||
assert_eq!(
|
||||
ob.send(&pk(1), b"never lands").await.unwrap(),
|
||||
OutboxStatus::Queued
|
||||
);
|
||||
assert_eq!(dead.calls(), 1, "immediate attempt");
|
||||
|
||||
// Walk the schedule forward; each tick is one more attempt.
|
||||
let mut now = ob.pending(&pk(1)).unwrap()[0].next_attempt_at;
|
||||
let mut last = OutboxStatus::Queued;
|
||||
for _ in 0..6 {
|
||||
let fired = ob.tick(now).await.unwrap();
|
||||
if let Some((_, st)) = fired.first() {
|
||||
last = st.clone();
|
||||
}
|
||||
if last == OutboxStatus::Failed("connect gone.onion:80: timed out".into()) {
|
||||
break;
|
||||
}
|
||||
now += BACKOFF_CAP_SECS;
|
||||
}
|
||||
assert_eq!(
|
||||
last,
|
||||
OutboxStatus::Failed("connect gone.onion:80: timed out".into()),
|
||||
"gives up after max_attempts"
|
||||
);
|
||||
assert_eq!(dead.calls(), 3, "attempts stop at the cap");
|
||||
|
||||
let calls_at_cap = dead.calls();
|
||||
for _ in 0..3 {
|
||||
now += BACKOFF_CAP_SECS;
|
||||
assert!(ob.tick(now).await.unwrap().is_empty(), "no more retries");
|
||||
}
|
||||
assert_eq!(dead.calls(), calls_at_cap);
|
||||
|
||||
let pending = ob.pending(&pk(1)).unwrap();
|
||||
assert_eq!(pending.len(), 1);
|
||||
assert!(matches!(pending[0].status, OutboxStatus::Failed(_)));
|
||||
assert!(pending[0].status.is_terminal());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn queued_message_survives_reopen_and_flushes_after_unlock() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let pk1 = pk(1);
|
||||
let next_attempt_at = {
|
||||
let store = store_and_friend(dir.path(), "later.onion");
|
||||
let dead = Flaky::new(usize::MAX, "connect later.onion:80: timed out");
|
||||
let ob = outbox(Arc::clone(&store), dead, 8);
|
||||
assert_eq!(
|
||||
ob.send(&pk1, b"survives restart").await.unwrap(),
|
||||
OutboxStatus::Queued
|
||||
);
|
||||
ob.pending(&pk1).unwrap()[0].next_attempt_at
|
||||
};
|
||||
|
||||
// Process exit: everything above is dropped and the store is reopened.
|
||||
let store = Arc::new(Mutex::new(
|
||||
Store::open_at_with_passphrase(dir.path(), PASS).unwrap(),
|
||||
));
|
||||
let up = Flaky::new(0, "");
|
||||
let ob = outbox(Arc::clone(&store), up.clone(), 8);
|
||||
let fired = ob.flush_all(next_attempt_at).await.unwrap();
|
||||
assert_eq!(fired.len(), 1);
|
||||
assert_eq!(fired[0].1, OutboxStatus::Sent);
|
||||
assert_eq!(up.delivered(), vec![b"survives restart".to_vec()]);
|
||||
assert!(ob.pending(&pk1).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn protocol_error_fails_immediately_and_is_not_queued() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = store_and_friend(dir.path(), "liar.onion");
|
||||
let liar = Flaky::new(usize::MAX, "fingerprint mismatch");
|
||||
let ob = outbox(Arc::clone(&store), liar, 8);
|
||||
|
||||
let err = ob.send(&pk(1), b"hello liar").await.unwrap_err();
|
||||
assert!(err.contains("fingerprint mismatch"), "got {err}");
|
||||
assert!(
|
||||
ob.pending(&pk(1)).unwrap().is_empty(),
|
||||
"protocol errors are never queued"
|
||||
);
|
||||
assert!(
|
||||
store.lock().unwrap().list_messages(&pk(1)).unwrap().is_empty(),
|
||||
"a failed protocol send is not written to history"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn flush_friend_ignores_the_schedule_when_that_peer_was_seen() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = store_and_friend(dir.path(), "seen.onion");
|
||||
let flaky = Flaky::new(1, "connect seen.onion:80: timed out");
|
||||
let ob = outbox(Arc::clone(&store), flaky.clone(), 8);
|
||||
|
||||
assert_eq!(
|
||||
ob.send(&pk(1), b"you are back").await.unwrap(),
|
||||
OutboxStatus::Queued
|
||||
);
|
||||
let now = ob.pending(&pk(1)).unwrap()[0].created_at;
|
||||
let fired = ob.flush_friend(&pk(1), now).await.unwrap();
|
||||
assert_eq!(fired.len(), 1, "a live handshake flushes without waiting");
|
||||
assert_eq!(fired[0].1, OutboxStatus::Sent);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn wipe_clears_outbox_rows() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = store_and_friend(dir.path(), "dead.onion");
|
||||
let dead = Flaky::new(usize::MAX, "connect dead.onion:80: timed out");
|
||||
let ob = outbox(Arc::clone(&store), dead, 8);
|
||||
assert_eq!(
|
||||
ob.send(&pk(1), b"wipe me").await.unwrap(),
|
||||
OutboxStatus::Queued
|
||||
);
|
||||
assert_eq!(ob.pending(&pk(1)).unwrap().len(), 1);
|
||||
|
||||
store.lock().unwrap().wipe_messages().unwrap();
|
||||
|
||||
assert!(
|
||||
ob.pending(&pk(1)).unwrap().is_empty(),
|
||||
"wipe must drop queued sends, not only chat"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn missing_prekey_is_fatal_not_queued() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = Arc::new(Mutex::new(
|
||||
Store::open_at_with_passphrase(dir.path(), PASS).unwrap(),
|
||||
));
|
||||
{
|
||||
let s = store.lock().unwrap();
|
||||
s.upsert_friend(&pk(2), "noprekey.onion", None).unwrap();
|
||||
}
|
||||
let ob = outbox(Arc::clone(&store), Flaky::new(0, ""), 8);
|
||||
let err = ob.send(&pk(2), b"hi").await.unwrap_err();
|
||||
assert!(err.contains("prekey"), "got {err}");
|
||||
assert!(ob.pending(&pk(2)).unwrap().is_empty());
|
||||
}
|
||||
Loading…
Reference in a new issue