Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ebd3a306e8 |
||
|
|
7c6de696a1 |
||
|
|
068b655c19 |
11 changed files with 1773 additions and 126 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.
|
||||
|
|
|
|||
|
|
@ -24,7 +24,16 @@ Identity secret key, friend public keys, and locators remain plaintext in the sa
|
|||
|
||||
## 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 db 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. `/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
|
||||
|
||||
|
|
@ -65,5 +74,7 @@ the peer already knows the plaintext they sent.
|
|||
|
||||
## Out of v1
|
||||
|
||||
Prosody, XMPP, s2s, MAM, carbons, outbox, multi-device, DHT / name server,
|
||||
sqlcipher, A/V.
|
||||
Prosody, XMPP, s2s, MAM, carbons, a **server-side** outbox / store-and-forward
|
||||
relay, multi-device, DHT / name server, sqlcipher, A/V. The local retry queue of
|
||||
the previous section is not an outbox in the XMPP sense: it never leaves the
|
||||
device.
|
||||
|
|
|
|||
52
docs/TUI.md
52
docs/TUI.md
|
|
@ -351,6 +351,16 @@ Else RGB as today.
|
|||
| box | ratatui `Borders::ALL` (light) | `+` `-` `\|` via `border::Set` |
|
||||
| alert prefix | `! ` | `! ` |
|
||||
| stale | word `stale` | `stale` |
|
||||
| delivery: delivered | `✓` | `ok` |
|
||||
| delivery: queued | `◷` | (word) `queued` |
|
||||
| delivery: sending | `»` | (word) `sending` |
|
||||
| delivery: failed | `✗` | (word) `failed` |
|
||||
|
||||
`queued` / `sending` / `failed` always carry their state word, so the ASCII
|
||||
fallback drops the glyph instead of inventing one. Only `✓` is wordless, so it
|
||||
falls back to `ok`. `delivery_glyph()` /
|
||||
`tests/tui_spec.rs::delivery_markers_have_exercised_ascii_fallbacks` exercise the
|
||||
fallback path.
|
||||
|
||||
No emoji. `onion_glyph()` stays for callers that already use it; do not put it
|
||||
on the main header.
|
||||
|
|
@ -401,6 +411,9 @@ Do not soften fail-closed into a loader.
|
|||
| sending | `sending` (keep, no spinner) |
|
||||
| sent | `sent` |
|
||||
| peer down / send err | `send failed: {e}` (visible) |
|
||||
| queued (outbox) | `{n} queued` — replaces the flat `sent`/`send failed` while rows are outstanding |
|
||||
| queued + terminal failure | `{n} queued, send failed: {short}` |
|
||||
| terminal failure | `send failed: {short}` (`{f} failed` when more than one) |
|
||||
| already sending | `already sending` (keep) |
|
||||
| stale friend | `stale` suffix (keep) |
|
||||
| empty composer | `message` as dim placeholder (not the slash list). Slash list stays in `?` |
|
||||
|
|
@ -570,3 +583,42 @@ cargo test --locked --test tui_spec -- --nocapture dump_spec_frames
|
|||
Copy wired in `src/tui.rs` (not in the reconstructed standin): empty thread is
|
||||
`no messages` / `type below, Enter sends`; paste error is `{err}` then
|
||||
`Enter resubmits Esc back`; alerts truncate to the frame width.
|
||||
|
||||
## Delivery state (outbox) — implemented
|
||||
|
||||
Per-message state, read from the local outbox. The states are the store's own
|
||||
(`Queued` / `Sending` / `Sent` / `Failed`) — no parallel model, no new wire
|
||||
prefix, no server.
|
||||
|
||||
| Row | Marker |
|
||||
|---|---|
|
||||
| delivered | `you: ping ✓` |
|
||||
| queued (2nd attempt, 45s out) | `you: pong ◷ queued (try 2/8, retry 45s)` |
|
||||
| sending | `you: pong » sending` |
|
||||
| failed | `you: pong ✗ failed: connection timed out` |
|
||||
| inbound | `them: pong` (no marker) |
|
||||
|
||||
- `try {n}/{8}` is the outbox attempt count; `retry {s}s` / `retry {m}m` /
|
||||
`retry now` comes from the stored absolute `next_attempt_at`.
|
||||
- Failed reasons are sanitized, cut to the tail of the `a: b: c` chain and
|
||||
capped at 24 cells (`short_send_reason`).
|
||||
- Footer while rows are outstanding: `{n} queued`; any terminal failure keeps a
|
||||
fail-closed `send failed: {short}` statement (with `! ` when colour is off).
|
||||
- The tag trails the body and wraps with it, so it is never clipped away.
|
||||
|
||||
Correlation: a delivered row is deleted from the outbox, so an outbound message
|
||||
with no row is `Sent`; pending rows are matched to messages by body, newest send
|
||||
first (`chat_with_delivery`). The outbox holds no message id the UI can join on,
|
||||
so two identical bodies where only the newer one is still queued attach the
|
||||
marker to the newer send. An id-bearing accessor would remove that last
|
||||
ambiguity; see the follow-up card noted in the PR.
|
||||
|
||||
### Size floor / target
|
||||
|
||||
- **Floor: 80x24.** Everything above must render there.
|
||||
- **Target: 120x40.**
|
||||
- `tests/tui_spec.rs::chat_and_footer_rows_fit_80x24_and_wrap_instead_of_clipping`
|
||||
draws the real `draw_chat` + `status_footer` at 80x24 and asserts every chat
|
||||
and footer row is `<=` the terminal width, that the markers render, and that
|
||||
an over-long message wraps instead of being clipped.
|
||||
- Dump frames: `cargo test --locked --test tui_spec -- --nocapture dump_spec_frames`.
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
376
src/tui.rs
376
src/tui.rs
|
|
@ -1,6 +1,7 @@
|
|||
use std::collections::HashMap;
|
||||
use std::io::{self, IsTerminal};
|
||||
use std::sync::{Arc, mpsc};
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
|
||||
use ratatui::layout::{Constraint, Layout, Rect};
|
||||
|
|
@ -10,9 +11,10 @@ use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragra
|
|||
use ratatui::{DefaultTerminal, Frame};
|
||||
|
||||
use crate::node::Node;
|
||||
use crate::outbox::DEFAULT_MAX_ATTEMPTS;
|
||||
use crate::qr::{self, QrPayload};
|
||||
use crate::sanitize;
|
||||
use crate::store::{Friend, FriendProfile};
|
||||
use crate::store::{Friend, FriendProfile, Message, OutboxEntry, OutboxStatus};
|
||||
|
||||
const C_ACCENT: Color = Color::Rgb(232, 165, 75);
|
||||
const C_TEXT: Color = Color::Rgb(196, 214, 176);
|
||||
|
|
@ -116,6 +118,202 @@ pub fn empty_friend_chat_text() -> &'static str {
|
|||
"no messages\ntype below, Enter sends"
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Delivery state (outbox)
|
||||
//
|
||||
// The outbox is the only source of per-message state: `Queued` / `Sending` /
|
||||
// `Failed` rows are what `Node::outbox_pending` still holds, and a row is
|
||||
// deleted the moment the send crosses the circuit — so an outbound message with
|
||||
// no row is `Sent`. No parallel state model, no new wire prefix.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Longest short-form failure reason shown in a chat row.
|
||||
pub const FAIL_REASON_BUDGET: usize = 24;
|
||||
|
||||
/// Marker glyph for one delivery state. ASCII chrome falls back to `ok` for the
|
||||
/// wordless delivered state; `queued` / `sending` / `failed` already carry their
|
||||
/// word, so their glyph is dropped rather than invented.
|
||||
pub fn delivery_glyph(status: &OutboxStatus) -> &'static str {
|
||||
let ascii = ascii_chrome();
|
||||
match status {
|
||||
OutboxStatus::Sent => {
|
||||
if ascii {
|
||||
"ok"
|
||||
} else {
|
||||
"✓"
|
||||
}
|
||||
}
|
||||
OutboxStatus::Queued => {
|
||||
if ascii {
|
||||
""
|
||||
} else {
|
||||
"◷"
|
||||
}
|
||||
}
|
||||
OutboxStatus::Sending => {
|
||||
if ascii {
|
||||
""
|
||||
} else {
|
||||
"»"
|
||||
}
|
||||
}
|
||||
OutboxStatus::Failed(_) => {
|
||||
if ascii {
|
||||
""
|
||||
} else {
|
||||
"✗"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Next-attempt age for a queued row, from the absolute `next_attempt_at` the
|
||||
/// outbox stores.
|
||||
pub fn retry_in_text(next_in_secs: i64) -> String {
|
||||
if next_in_secs <= 0 {
|
||||
"retry now".to_string()
|
||||
} else if next_in_secs < 60 {
|
||||
format!("retry {next_in_secs}s")
|
||||
} else {
|
||||
format!("retry {}m", (next_in_secs + 59) / 60)
|
||||
}
|
||||
}
|
||||
|
||||
/// Transport failure text, short form: sanitized, tail of the `a: b: c` chain,
|
||||
/// capped at `budget` cells so one peer's error cannot blow out the row.
|
||||
pub fn short_send_reason(why: &str, budget: usize) -> String {
|
||||
let clean = sanitize::display_text(why.as_bytes());
|
||||
let tail = clean.rsplit(": ").next().unwrap_or("").trim();
|
||||
let text = if tail.is_empty() { clean.trim() } else { tail };
|
||||
truncate_chars(text, budget)
|
||||
}
|
||||
|
||||
/// One row's delivery marker, straight from the outbox state.
|
||||
pub fn delivery_tag(status: &OutboxStatus, attempts: u32, next_in_secs: i64) -> String {
|
||||
let glyph = delivery_glyph(status);
|
||||
let body = match status {
|
||||
OutboxStatus::Sent => String::new(),
|
||||
OutboxStatus::Queued => format!(
|
||||
"queued (try {attempts}/{DEFAULT_MAX_ATTEMPTS}, {})",
|
||||
retry_in_text(next_in_secs)
|
||||
),
|
||||
OutboxStatus::Sending => "sending".to_string(),
|
||||
OutboxStatus::Failed(why) => {
|
||||
format!("failed: {}", short_send_reason(why, FAIL_REASON_BUDGET))
|
||||
}
|
||||
};
|
||||
match (glyph.is_empty(), body.is_empty()) {
|
||||
(_, true) => glyph.to_string(),
|
||||
(true, false) => body,
|
||||
(false, false) => format!("{glyph} {body}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Footer summary derived from the outbox rows of the selected friend.
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||
pub struct OutboxSummary {
|
||||
/// `Queued` + `Sending`: rows the worker may still deliver.
|
||||
pub queued: usize,
|
||||
/// Terminal failures — these never retry.
|
||||
pub failed: usize,
|
||||
/// First terminal failure, for the fail-closed footer copy.
|
||||
pub first_error: Option<String>,
|
||||
}
|
||||
|
||||
impl OutboxSummary {
|
||||
/// Footer note, or `None` when nothing is outstanding. Any terminal failure
|
||||
/// keeps a `send failed` statement so the fail-closed copy stays visible.
|
||||
pub fn note(&self) -> Option<String> {
|
||||
let reason = || {
|
||||
short_send_reason(
|
||||
self.first_error.as_deref().unwrap_or("unknown"),
|
||||
FAIL_REASON_BUDGET,
|
||||
)
|
||||
};
|
||||
match (self.queued, self.failed) {
|
||||
(0, 0) => None,
|
||||
(queued, 0) => Some(format!("{queued} queued")),
|
||||
(0, 1) => Some(format!("send failed: {}", reason())),
|
||||
(0, failed) => Some(format!("send failed: {} ({failed} failed)", reason())),
|
||||
(queued, _) => Some(format!("{queued} queued, send failed: {}", reason())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Chat transcript with per-message delivery state, plus the footer summary.
|
||||
///
|
||||
/// Pending rows are matched to messages by body, newest send first: an
|
||||
/// outstanding retry is the most recent send of that text, and the outbox holds
|
||||
/// no message id the UI could join on.
|
||||
pub fn chat_with_delivery(
|
||||
msgs: &[Message],
|
||||
pending: &[OutboxEntry],
|
||||
now: i64,
|
||||
) -> (Vec<String>, OutboxSummary) {
|
||||
let mut summary = OutboxSummary::default();
|
||||
for entry in pending {
|
||||
match &entry.status {
|
||||
OutboxStatus::Failed(why) => {
|
||||
summary.failed += 1;
|
||||
summary.first_error.get_or_insert_with(|| why.clone());
|
||||
}
|
||||
_ => summary.queued += 1,
|
||||
}
|
||||
}
|
||||
if msgs.is_empty() {
|
||||
return (
|
||||
empty_friend_chat_text()
|
||||
.lines()
|
||||
.map(str::to_string)
|
||||
.collect(),
|
||||
summary,
|
||||
);
|
||||
}
|
||||
|
||||
let mut by_body: HashMap<&[u8], Vec<&OutboxEntry>> = HashMap::new();
|
||||
for entry in pending {
|
||||
by_body
|
||||
.entry(entry.body.as_slice())
|
||||
.or_default()
|
||||
.push(entry);
|
||||
}
|
||||
let mut tags: Vec<Option<String>> = vec![None; msgs.len()];
|
||||
for (i, msg) in msgs.iter().enumerate().rev() {
|
||||
if msg.dir != "out" {
|
||||
continue;
|
||||
}
|
||||
if let Some(rows) = by_body.get_mut(msg.plaintext.as_slice())
|
||||
&& let Some(entry) = rows.pop()
|
||||
{
|
||||
tags[i] = Some(delivery_tag(
|
||||
&entry.status,
|
||||
entry.attempts,
|
||||
entry.next_attempt_at - now,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let lines = msgs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, msg)| {
|
||||
let side = if msg.dir == "out" { "you" } else { "them" };
|
||||
let body = sanitize::display_text(&msg.plaintext);
|
||||
let tag = match tags[i].clone() {
|
||||
Some(tag) => tag,
|
||||
None if msg.dir == "out" => delivery_tag(&OutboxStatus::Sent, 0, 0),
|
||||
None => String::new(),
|
||||
};
|
||||
if tag.is_empty() {
|
||||
format!("{side}: {body}")
|
||||
} else {
|
||||
format!("{side}: {body} {tag}")
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
(lines, summary)
|
||||
}
|
||||
|
||||
/// Paste overlay copy. Error keeps the resubmit hint.
|
||||
pub fn paste_screen_text(buf: &str, err: Option<&str>) -> String {
|
||||
let hint = match err {
|
||||
|
|
@ -1449,9 +1647,13 @@ impl App {
|
|||
let (tx, rx) = mpsc::channel();
|
||||
self.status_note = Some("sending".into());
|
||||
std::mem::drop(self.rt.spawn(async move {
|
||||
// `send()` reports `Sent` when the circuit took it and `Queued` when
|
||||
// the peer's onion is unreachable. The footer then reads the real
|
||||
// row count from the outbox, so this note is only the first word.
|
||||
let note = match node.send(&pk, &body).await {
|
||||
Ok(()) => "sent".to_string(),
|
||||
Err(e) => format!("send failed: {e}"),
|
||||
Ok(OutboxStatus::Sent) => "sent".to_string(),
|
||||
Ok(_) => "queued".to_string(),
|
||||
Err(e) => format!("send failed: {}", short_send_reason(&e, FAIL_REASON_BUDGET)),
|
||||
};
|
||||
let _ = tx.send(note);
|
||||
}));
|
||||
|
|
@ -1561,38 +1763,22 @@ impl App {
|
|||
}
|
||||
f.render_stateful_widget(roster, panes[0], &mut roster_state);
|
||||
|
||||
let chat_lines = self.chat_lines();
|
||||
let inner_h = panes[1].height.saturating_sub(2);
|
||||
let nlines = chat_lines.len();
|
||||
let max_scroll = nlines.saturating_sub(inner_h as usize) as u16;
|
||||
let scroll = self.chat_scroll.min(max_scroll);
|
||||
let overflow = nlines > inner_h as usize && inner_h > 0;
|
||||
let chat_title = {
|
||||
let name = self.friends.get(self.selected).map(|friend| {
|
||||
friend
|
||||
.petname
|
||||
.as_deref()
|
||||
.unwrap_or(&friend.fingerprint)
|
||||
.to_string()
|
||||
});
|
||||
let mut t = match name {
|
||||
Some(n) => format!("chat {n}"),
|
||||
None => "chat".to_string(),
|
||||
};
|
||||
if overflow {
|
||||
let end = (scroll as usize + inner_h as usize).min(nlines);
|
||||
t.push_str(&format!(" {}-{end}/{nlines}", scroll as usize + 1));
|
||||
}
|
||||
let mark = if self.focus == Pane::Chat { "> " } else { " " };
|
||||
format!("{mark}{t}")
|
||||
};
|
||||
let chat_text = chat_lines.join("\n");
|
||||
let chat = Paragraph::new(chat_text)
|
||||
.style(style_text())
|
||||
.wrap(Wrap { trim: false })
|
||||
.scroll((scroll, 0))
|
||||
.block(self.pane_block(&chat_title, Pane::Chat));
|
||||
f.render_widget(chat, panes[1]);
|
||||
let (chat_lines, summary) = self.chat_view();
|
||||
let chat_name = self.friends.get(self.selected).map(|friend| {
|
||||
friend
|
||||
.petname
|
||||
.as_deref()
|
||||
.unwrap_or(&friend.fingerprint)
|
||||
.to_string()
|
||||
});
|
||||
draw_chat(
|
||||
f,
|
||||
panes[1],
|
||||
&chat_lines,
|
||||
chat_name.as_deref(),
|
||||
self.focus == Pane::Chat,
|
||||
self.chat_scroll,
|
||||
);
|
||||
|
||||
let mark = if self.focus == Pane::Composer {
|
||||
"> "
|
||||
|
|
@ -1616,62 +1802,108 @@ impl App {
|
|||
cols[3],
|
||||
);
|
||||
|
||||
let footer = self.footer_line(area.width);
|
||||
let footer = self.footer_line(area.width, &summary);
|
||||
f.render_widget(Paragraph::new(footer).style(style_dim()), cols[4]);
|
||||
}
|
||||
|
||||
fn footer_line(&self, width: u16) -> String {
|
||||
fn footer_line(&self, width: u16, summary: &OutboxSummary) -> String {
|
||||
// The outbox is the source of truth while anything is outstanding; the
|
||||
// transient note still covers "sending", "sent file x", "invoice sent".
|
||||
let note = summary.note().or_else(|| self.status_note.clone());
|
||||
status_footer(
|
||||
width,
|
||||
&self.me_fp,
|
||||
&self.me_onion,
|
||||
self.status_note.as_deref(),
|
||||
note.as_deref(),
|
||||
footer_hints(&self.screen),
|
||||
)
|
||||
}
|
||||
|
||||
fn chat_lines(&self) -> Vec<String> {
|
||||
fn chat_view(&self) -> (Vec<String>, OutboxSummary) {
|
||||
let Some(friend) = self.friends.get(self.selected) else {
|
||||
return vec![
|
||||
"no friends yet".into(),
|
||||
"F3 paste an invite to add one".into(),
|
||||
];
|
||||
return (
|
||||
vec![
|
||||
"no friends yet".into(),
|
||||
"F3 paste an invite to add one".into(),
|
||||
],
|
||||
OutboxSummary::default(),
|
||||
);
|
||||
};
|
||||
match self.node.list_messages(&friend.pubkey) {
|
||||
Ok(msgs) if msgs.is_empty() => empty_friend_chat_text()
|
||||
.lines()
|
||||
.map(str::to_string)
|
||||
.collect(),
|
||||
Ok(msgs) => msgs
|
||||
.iter()
|
||||
.map(|m| {
|
||||
let side = if m.dir == "out" { "you" } else { "them" };
|
||||
format!("{side}: {}", sanitize::display_text(&m.plaintext))
|
||||
})
|
||||
.collect(),
|
||||
Err(e) => vec![e],
|
||||
Ok(msgs) => {
|
||||
let pending = self.node.outbox_pending(&friend.pubkey).unwrap_or_default();
|
||||
chat_with_delivery(&msgs, &pending, unix_now_secs())
|
||||
}
|
||||
Err(e) => (vec![e], OutboxSummary::default()),
|
||||
}
|
||||
}
|
||||
|
||||
fn pane_block<'a>(&self, title: &'a str, pane: Pane) -> Block<'a> {
|
||||
let focused = self.focus == pane;
|
||||
let border = if focused {
|
||||
style_accent()
|
||||
} else {
|
||||
style_border()
|
||||
};
|
||||
let title_style = if focused {
|
||||
style_accent().add_modifier(Modifier::BOLD)
|
||||
} else {
|
||||
style_dim()
|
||||
};
|
||||
apply_chrome_borders(Block::default())
|
||||
.border_style(border)
|
||||
.title(title)
|
||||
.title_style(title_style)
|
||||
pane_block_for(title, self.focus == pane)
|
||||
}
|
||||
}
|
||||
|
||||
/// Pane chrome without an `App`: focus is accent border + bold title, never
|
||||
/// color alone (the `> ` marks come from the callers).
|
||||
fn pane_block_for(title: &str, focused: bool) -> Block<'_> {
|
||||
let border = if focused {
|
||||
style_accent()
|
||||
} else {
|
||||
style_border()
|
||||
};
|
||||
let title_style = if focused {
|
||||
style_accent().add_modifier(Modifier::BOLD)
|
||||
} else {
|
||||
style_dim()
|
||||
};
|
||||
apply_chrome_borders(Block::default())
|
||||
.border_style(border)
|
||||
.title(title)
|
||||
.title_style(title_style)
|
||||
}
|
||||
|
||||
fn unix_now_secs() -> i64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs() as i64)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Real chat-pane renderer: `App::draw_main` calls this, so width, wrap and
|
||||
/// delivery-marker behaviour are testable without constructing a `Node`.
|
||||
pub fn draw_chat(
|
||||
f: &mut Frame,
|
||||
area: Rect,
|
||||
lines: &[String],
|
||||
name: Option<&str>,
|
||||
focused: bool,
|
||||
scroll: u16,
|
||||
) {
|
||||
let inner_h = area.height.saturating_sub(2);
|
||||
let nlines = lines.len();
|
||||
let max_scroll = nlines.saturating_sub(inner_h as usize) as u16;
|
||||
let scroll = scroll.min(max_scroll);
|
||||
let overflow = nlines > inner_h as usize && inner_h > 0;
|
||||
let mut title = match name {
|
||||
Some(n) => format!("chat {n}"),
|
||||
None => "chat".to_string(),
|
||||
};
|
||||
if overflow {
|
||||
let end = (scroll as usize + inner_h as usize).min(nlines);
|
||||
title.push_str(&format!(" {}-{end}/{nlines}", scroll as usize + 1));
|
||||
}
|
||||
let mark = if focused { "> " } else { " " };
|
||||
let title = format!("{mark}{title}");
|
||||
f.render_widget(
|
||||
Paragraph::new(lines.join("\n"))
|
||||
.style(style_text())
|
||||
.wrap(Wrap { trim: false })
|
||||
.scroll((scroll, 0))
|
||||
.block(pane_block_for(&title, focused)),
|
||||
area,
|
||||
);
|
||||
}
|
||||
|
||||
/// Status bar: never drop a non-empty `status_note`. Always keep `TOR`, `me:`, `? help`.
|
||||
pub fn status_footer(
|
||||
width: u16,
|
||||
|
|
@ -1687,7 +1919,7 @@ pub fn status_footer(
|
|||
let mut note = status_note.unwrap_or("").trim().to_string();
|
||||
if !note.is_empty()
|
||||
&& color_mode() == ColorMode::None
|
||||
&& (note.starts_with("send failed") || note == "fingerprint mismatch")
|
||||
&& (note.contains("send failed") || note == "fingerprint mismatch")
|
||||
&& !note.starts_with("! ")
|
||||
{
|
||||
note = format!("! {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());
|
||||
}
|
||||
|
|
@ -1,10 +1,13 @@
|
|||
//! Spec implementation tests for docs/TUI.md (this card).
|
||||
//! Does not own `tests/tui_frames.rs` (PR #23).
|
||||
|
||||
use onionwire::Message;
|
||||
use onionwire::outbox::{OutboxEntry, OutboxStatus};
|
||||
use onionwire::qr;
|
||||
use onionwire::tui::{
|
||||
alert_line, ascii_chrome, draw_share, draw_text_overlay, empty_friend_chat_text,
|
||||
help_overlay_text, main_footer_hints, main_header_line, paste_screen_text, roster_col_width,
|
||||
OutboxSummary, alert_line, ascii_chrome, chat_with_delivery, delivery_tag, draw_chat,
|
||||
draw_share, draw_text_overlay, empty_friend_chat_text, help_overlay_text, main_footer_hints,
|
||||
main_header_line, paste_screen_text, retry_in_text, roster_col_width, short_send_reason,
|
||||
status_footer, wrap_invite,
|
||||
};
|
||||
use ratatui::Frame;
|
||||
|
|
@ -376,3 +379,376 @@ fn ascii_switch_80x24_frame_is_pure_ascii() {
|
|||
println!("===== AFTER ascii share 80x24 =====\n{screen}");
|
||||
unsafe { std::env::remove_var("ONIONWIRE_ASCII") };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Outbox delivery state (card t_d9a5b065)
|
||||
//
|
||||
// States come from the outbox API (`Outbox::pending` → `Queued` / `Sending` /
|
||||
// `Failed`; delivered rows are deleted, so absence means `Sent`). No new wire
|
||||
// prefix, no parallel state model.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn out_msg(body: &str) -> Message {
|
||||
Message {
|
||||
dir: "out".into(),
|
||||
plaintext: body.as_bytes().to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
fn in_msg(body: &str) -> Message {
|
||||
Message {
|
||||
dir: "in".into(),
|
||||
plaintext: body.as_bytes().to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
fn pending_row(
|
||||
body: &str,
|
||||
status: OutboxStatus,
|
||||
attempts: u32,
|
||||
next_in: i64,
|
||||
now: i64,
|
||||
) -> OutboxEntry {
|
||||
OutboxEntry {
|
||||
id: 1,
|
||||
friend_pk: vec![9u8; 32],
|
||||
message_id: 1,
|
||||
body: body.as_bytes().to_vec(),
|
||||
attempts,
|
||||
next_attempt_at: now + next_in,
|
||||
created_at: now,
|
||||
status,
|
||||
last_error: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn queued_row(body: &str, attempts: u32, next_in: i64, now: i64) -> OutboxEntry {
|
||||
pending_row(body, OutboxStatus::Queued, attempts, next_in, now)
|
||||
}
|
||||
|
||||
fn sending_row(body: &str, now: i64) -> OutboxEntry {
|
||||
pending_row(body, OutboxStatus::Sending, 1, 0, now)
|
||||
}
|
||||
|
||||
fn failed_row(body: &str, why: &str, now: i64) -> OutboxEntry {
|
||||
pending_row(body, OutboxStatus::Failed(why.into()), 8, 0, now)
|
||||
}
|
||||
|
||||
/// Marker is everything after the two-space separator the render helper uses.
|
||||
fn marker_of(line: &str) -> &str {
|
||||
line.rsplit(" ").next().unwrap_or("")
|
||||
}
|
||||
|
||||
/// Force the non-ASCII (unicode glyph) path. Caller holds `ASCII_ENV`.
|
||||
fn force_unicode_mode() {
|
||||
unsafe {
|
||||
std::env::remove_var("ONIONWIRE_ASCII");
|
||||
std::env::remove_var("NO_COLOR");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queued_and_delivered_messages_render_different_markers() {
|
||||
let guard = ASCII_ENV.lock().expect("ascii env lock");
|
||||
force_unicode_mode();
|
||||
let _guard = guard;
|
||||
let now = 1_700_000_000;
|
||||
let msgs = vec![out_msg("ping"), out_msg("pong")];
|
||||
let pending = vec![queued_row("pong", 2, 45, now)];
|
||||
|
||||
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
|
||||
|
||||
assert!(
|
||||
lines[0].contains('✓'),
|
||||
"delivered row lost its mark: {:?}",
|
||||
lines[0]
|
||||
);
|
||||
assert!(!lines[0].contains("queued"), "{:?}", lines[0]);
|
||||
assert!(
|
||||
lines[1].contains('◷'),
|
||||
"queued row lost its glyph: {:?}",
|
||||
lines[1]
|
||||
);
|
||||
assert!(lines[1].contains("queued"), "{:?}", lines[1]);
|
||||
assert!(
|
||||
lines[1].contains("try 2/8"),
|
||||
"attempt count missing: {:?}",
|
||||
lines[1]
|
||||
);
|
||||
assert!(
|
||||
lines[1].contains("retry 45s"),
|
||||
"retry age missing: {:?}",
|
||||
lines[1]
|
||||
);
|
||||
assert_ne!(
|
||||
marker_of(&lines[0]),
|
||||
marker_of(&lines[1]),
|
||||
"queued and delivered must not share a marker"
|
||||
);
|
||||
assert_eq!(summary.queued, 1);
|
||||
assert_eq!(summary.failed, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delivery_markers_have_exercised_ascii_fallbacks() {
|
||||
let _guard = ASCII_ENV.lock().expect("ascii env lock");
|
||||
unsafe {
|
||||
std::env::set_var("ONIONWIRE_ASCII", "1");
|
||||
std::env::remove_var("NO_COLOR");
|
||||
}
|
||||
let now = 500;
|
||||
let msgs = vec![
|
||||
out_msg("alpha"),
|
||||
out_msg("beta"),
|
||||
out_msg("gamma"),
|
||||
out_msg("delta"),
|
||||
in_msg("epsilon"),
|
||||
];
|
||||
let pending = vec![
|
||||
failed_row("alpha", "connect peer.onion:80: connection timed out", now),
|
||||
queued_row("beta", 1, 30, now),
|
||||
sending_row("gamma", now),
|
||||
];
|
||||
|
||||
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
|
||||
for line in &lines {
|
||||
assert!(
|
||||
line.is_ascii(),
|
||||
"ASCII fallback missing, non-ASCII in {line:?}"
|
||||
);
|
||||
}
|
||||
assert_eq!(marker_of(&lines[0]), "failed: connection timed out");
|
||||
assert_eq!(marker_of(&lines[1]), "queued (try 1/8, retry 30s)");
|
||||
assert_eq!(marker_of(&lines[2]), "sending");
|
||||
assert_eq!(marker_of(&lines[3]), "ok", "delivered fallback is `ok`");
|
||||
assert_eq!(lines[4], "them: epsilon", "inbound rows carry no state");
|
||||
assert_eq!(summary.queued, 2, "queued + sending are both outstanding");
|
||||
assert_eq!(summary.failed, 1);
|
||||
|
||||
unsafe { std::env::remove_var("ONIONWIRE_ASCII") };
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_age_and_failure_reason_are_short_forms() {
|
||||
assert_eq!(retry_in_text(45), "retry 45s");
|
||||
assert_eq!(retry_in_text(59), "retry 59s");
|
||||
assert_eq!(retry_in_text(60), "retry 1m");
|
||||
assert_eq!(retry_in_text(720), "retry 12m");
|
||||
assert_eq!(retry_in_text(0), "retry now");
|
||||
assert_eq!(retry_in_text(-30), "retry now");
|
||||
|
||||
assert_eq!(
|
||||
short_send_reason("connect abcdef.onion:80: connection timed out", 24),
|
||||
"connection timed out"
|
||||
);
|
||||
let long = short_send_reason("a-really-long-failure-description-here", 12);
|
||||
assert!(long.chars().count() <= 12, "{long:?}");
|
||||
assert!(
|
||||
long.contains('…') || long.contains("..."),
|
||||
"truncation marker missing: {long:?}"
|
||||
);
|
||||
assert_eq!(short_send_reason("nope", 24), "nope");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delivery_tag_reads_the_outbox_status_enum() {
|
||||
let guard = ASCII_ENV.lock().expect("ascii env lock");
|
||||
force_unicode_mode();
|
||||
let _guard = guard;
|
||||
assert_eq!(delivery_tag(&OutboxStatus::Sent, 0, 0), "✓");
|
||||
assert_eq!(
|
||||
delivery_tag(&OutboxStatus::Queued, 3, 120),
|
||||
"◷ queued (try 3/8, retry 2m)"
|
||||
);
|
||||
assert_eq!(delivery_tag(&OutboxStatus::Sending, 1, 0), "» sending");
|
||||
assert_eq!(
|
||||
delivery_tag(&OutboxStatus::Failed("connect x:80: nope".into()), 8, 0),
|
||||
"✗ failed: nope"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn footer_summary_counts_queued_and_keeps_fail_closed() {
|
||||
let none = OutboxSummary::default();
|
||||
assert_eq!(none.note(), None);
|
||||
|
||||
let queued = OutboxSummary {
|
||||
queued: 2,
|
||||
failed: 0,
|
||||
first_error: None,
|
||||
};
|
||||
assert_eq!(queued.note().as_deref(), Some("2 queued"));
|
||||
|
||||
let failed = OutboxSummary {
|
||||
queued: 0,
|
||||
failed: 1,
|
||||
first_error: Some("connect peer.onion:80: connection timed out".into()),
|
||||
};
|
||||
let note = failed.note().expect("failed rows must produce a note");
|
||||
assert!(note.starts_with("send failed:"), "{note:?}");
|
||||
assert!(note.contains("connection timed out"), "{note:?}");
|
||||
|
||||
let mixed = OutboxSummary {
|
||||
queued: 3,
|
||||
failed: 1,
|
||||
first_error: Some("connect peer.onion:80: connection timed out".into()),
|
||||
};
|
||||
let mixed_note = mixed.note().expect("mixed rows must produce a note");
|
||||
assert!(mixed_note.contains("3 queued"), "{mixed_note:?}");
|
||||
assert!(mixed_note.contains("send failed"), "{mixed_note:?}");
|
||||
|
||||
// Fail-closed copy stays visible in the real footer at the 80-col floor.
|
||||
let line = status_footer(80, FP, ONION, Some(¬e), main_footer_hints());
|
||||
assert!(
|
||||
line.chars().count() <= 80,
|
||||
"{} {line:?}",
|
||||
line.chars().count()
|
||||
);
|
||||
assert!(line.contains("send failed"), "footer dropped it: {line:?}");
|
||||
assert!(line.contains("TOR") && line.contains("? help"), "{line:?}");
|
||||
|
||||
let queued_line = status_footer(80, FP, ONION, queued.note().as_deref(), main_footer_hints());
|
||||
assert!(queued_line.contains("2 queued"), "{queued_line:?}");
|
||||
assert!(queued_line.chars().count() <= 80);
|
||||
|
||||
// `! ` ornament (colour off) still lands on the derived failing note.
|
||||
let _guard = ASCII_ENV.lock().expect("ascii env lock");
|
||||
unsafe { std::env::set_var("NO_COLOR", "1") };
|
||||
let no_color = status_footer(80, FP, ONION, Some(¬e), main_footer_hints());
|
||||
assert!(no_color.contains("! send failed"), "{no_color:?}");
|
||||
unsafe { std::env::remove_var("NO_COLOR") };
|
||||
}
|
||||
|
||||
/// The card's width criterion: draw the real helpers at the documented floor
|
||||
/// (80x24) and prove nothing in the chat/footer region exceeds the width, and
|
||||
/// that an over-long row wraps in the pane instead of being clipped.
|
||||
#[test]
|
||||
fn chat_and_footer_rows_fit_80x24_and_wrap_instead_of_clipping() {
|
||||
let guard = ASCII_ENV.lock().expect("ascii env lock");
|
||||
force_unicode_mode();
|
||||
let _guard = guard;
|
||||
let now = 1_700_000_000;
|
||||
let long = "this is a very long chat line that should wrap inside the chat pane instead of running off the right edge of an 80-column terminal and colliding with the roster border";
|
||||
let msgs = vec![out_msg("ok"), in_msg("pong"), out_msg(long)];
|
||||
let pending = vec![queued_row(long, 3, 45, now)];
|
||||
|
||||
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
|
||||
for line in lines.iter().take(2) {
|
||||
assert!(
|
||||
line.chars().count() <= 80,
|
||||
"short row wider than 80: {} {line:?}",
|
||||
line.chars().count()
|
||||
);
|
||||
}
|
||||
let footer = status_footer(
|
||||
80,
|
||||
FP,
|
||||
ONION,
|
||||
summary.note().as_deref(),
|
||||
main_footer_hints(),
|
||||
);
|
||||
assert!(footer.chars().count() <= 80, "{footer:?}");
|
||||
|
||||
let backend = TestBackend::new(80, 24);
|
||||
let mut terminal = Terminal::new(backend).expect("terminal");
|
||||
terminal
|
||||
.draw(|f| {
|
||||
let area = f.area();
|
||||
let cols = Layout::vertical([Constraint::Min(3), Constraint::Length(1)]).split(area);
|
||||
draw_chat(f, cols[0], &lines, Some("alice"), true, 0);
|
||||
f.render_widget(Paragraph::new(footer.clone()), cols[1]);
|
||||
})
|
||||
.expect("draw");
|
||||
|
||||
let buf = terminal.backend().buffer();
|
||||
let mut screen = String::new();
|
||||
for y in 0..24u16 {
|
||||
for x in 0..80u16 {
|
||||
screen.push_str(buf[(x, y)].symbol());
|
||||
}
|
||||
screen.push('\n');
|
||||
}
|
||||
for (y, row) in screen.lines().enumerate() {
|
||||
assert!(
|
||||
row.chars().count() <= 80,
|
||||
"80x24 chat/footer row {y} wider than the terminal: {} {row:?}",
|
||||
row.chars().count()
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
screen.contains('◷'),
|
||||
"queued glyph missing from frame:\n{screen}"
|
||||
);
|
||||
assert!(screen.contains("queued"), "queued word missing:\n{screen}");
|
||||
assert!(screen.contains('✓'), "delivered glyph missing:\n{screen}");
|
||||
assert!(
|
||||
screen.contains("with the roster border"),
|
||||
"long row was clipped, not wrapped:\n{screen}"
|
||||
);
|
||||
assert!(
|
||||
screen.contains("1 queued"),
|
||||
"footer summary missing:\n{screen}"
|
||||
);
|
||||
println!("===== AFTER outbox 80x24 (real draw_chat + status_footer) =====\n{screen}");
|
||||
}
|
||||
|
||||
/// The renderer consumes the real outbox API, not a hand-written fixture: a
|
||||
/// genuine unreachable-onion send leaves a `Queued` row, and that row is what
|
||||
/// the chat line and the footer note are built from.
|
||||
#[tokio::test]
|
||||
async fn renders_a_queued_row_from_a_real_outbox_send() {
|
||||
use onionwire::Store;
|
||||
use onionwire::outbox::{BoxFut, Deliverer, Outbox};
|
||||
use std::sync::Arc;
|
||||
|
||||
struct Dead;
|
||||
impl Deliverer for Dead {
|
||||
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 { Err("connect dead.onion:80: timed out".to_string()) })
|
||||
}
|
||||
}
|
||||
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let store = Store::open_at_with_passphrase(dir.path(), "tui-spec-pass").expect("open store");
|
||||
let pk = [1u8; 32];
|
||||
store
|
||||
.upsert_friend(&pk, "dead.onion", None)
|
||||
.expect("friend");
|
||||
store.set_friend_prekey(&pk, &[7u8; 32]).expect("prekey");
|
||||
let store = Arc::new(std::sync::Mutex::new(store));
|
||||
let outbox = Outbox::new(Arc::clone(&store), Arc::new(Dead));
|
||||
|
||||
assert_eq!(
|
||||
outbox.send(&pk, b"queued for a dead peer").await,
|
||||
Ok(OutboxStatus::Queued)
|
||||
);
|
||||
let pending = outbox.pending(&pk).expect("pending rows");
|
||||
assert_eq!(pending.len(), 1, "one queued row");
|
||||
let msgs = store
|
||||
.lock()
|
||||
.expect("store lock")
|
||||
.list_messages(&pk)
|
||||
.expect("messages");
|
||||
|
||||
let now = pending[0].next_attempt_at - 45;
|
||||
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
|
||||
assert_eq!(lines.len(), 1);
|
||||
assert!(
|
||||
lines[0].contains("queued (try 1/8, retry 45s)"),
|
||||
"real outbox row did not render: {:?}",
|
||||
lines[0]
|
||||
);
|
||||
assert_eq!(summary.note().as_deref(), Some("1 queued"));
|
||||
|
||||
// And once a send crosses the circuit the row is gone, so the same message
|
||||
// renders as delivered.
|
||||
let (delivered, summary) = chat_with_delivery(&msgs, &[], now);
|
||||
assert!(delivered[0].contains('✓'), "{:?}", delivered[0]);
|
||||
assert_eq!(summary.note(), None);
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue