This commit is contained in:
yves committed 2026-11-20 23:17:15 +01:00
1 parent 10af480218
commit 47b73e6935
11 files changed
+470 -28

No files matched your search

+95 -1
View File
@@ -36,7 +36,7 @@ use meow_proto::Message;
use meow_store::{Batch, RetiredMailbox, SpaceId, State as SpaceState, Store};
pub use meow_core::contact::ContactState as State;
pub use meow_store::{Content, HistoryEntry, HistoryPage, PendingAck};
pub use meow_store::{Content, HistoryEntry, HistoryPage, PendingAck, Settings, Status};
pub use outbox::{PendingSend, RetryPolicy};
/// Maximum file size sent in a single message (chunking: roadmap 5.7).
@@ -121,10 +121,22 @@ pub enum Event {
name: String,
data: Vec<u8>,
},
/// The contact's device received (or read) some of my messages.
Receipt {
contact: String,
kind: ReceiptKind,
message_ids: Vec<Vec<u8>>,
},
/// A queued message expired before any server accepted it.
SendFailed { contact: String, message_id: Vec<u8> },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReceiptKind {
Delivered,
Read,
}
/// Outcome of a send.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SendReport {
@@ -231,6 +243,16 @@ impl MeowClient {
&self.main().nickname
}
/// Identity preferences (receipts…).
pub fn settings(&self) -> Settings {
self.main().settings
}
pub async fn set_settings(&mut self, settings: Settings) -> Result<()> {
self.spaces[0].state.settings = settings;
self.save_space(0)
}
fn main(&self) -> &SpaceState {
&self.spaces[0].state
}
@@ -456,6 +478,39 @@ impl MeowClient {
Ok(lock(&self.store)?.history(sp.id, &sp.state.contacts[ci].id, page)?)
}
/// Mark every received message of a conversation as read, and tell the contact
/// (unless read receipts are off). Returns how many messages changed.
pub async fn mark_read(&mut self, name: &str) -> Result<usize> {
let (si, ci) = self.locate(name)?;
let cid = self.spaces[si].state.contacts[ci].id.clone();
let unread: Vec<Vec<u8>> = lock(&self.store)?
.full_history(self.spaces[si].id, &cid)?
.into_iter()
.filter(|h| !h.outbound && h.status < Status::Read)
.map(|h| h.id)
.collect();
if unread.is_empty() {
return Ok(0);
}
let read_receipts = self.settings().read_receipts;
let sp = &mut self.spaces[si];
sp.batch
.status
.extend(unread.iter().map(|m| (cid.clone(), m.clone(), Status::Read)));
if read_receipts {
let contact = &mut sp.state.contacts[ci];
let r = messaging::receipt(v2::receipt::Kind::Read, unread.clone(), now_ms());
let env = messaging::encrypt(contact, &r)?;
let d = messaging::deposit_for(contact, &env)?;
sp.state
.outbox
.push(outbox::item(&cid, vec![], &d, peer_servers(contact)));
}
self.save_space(si)?;
self.flush(false).await?;
Ok(unread.len())
}
/// Content of a received file.
pub fn file(&self, name: &str, message_id: &[u8]) -> Result<Option<Vec<u8>>> {
let (si, ci) = self.locate(name)?;
@@ -662,6 +717,7 @@ impl MeowClient {
sent_at_ms: msg.sent_at_ms,
received_at: now(),
content,
status: Status::Queued,
});
// Persisted (ratchet + queue) before anything is sent.
self.save_space(si)?;
@@ -888,6 +944,8 @@ impl MeowClient {
envs.sort_by_key(|(rank, at, _, _, _)| (*rank, *at));
let mut events = Vec::new();
// (space, contact id) → ids of the messages received, for delivery receipts.
let mut received: Vec<(usize, meow_core::contact::ContactId, Vec<Vec<u8>>)> = Vec::new();
for (_, received_at, si, mailbox, env) in envs {
let sp = &mut self.spaces[si];
let Some(ci) = sp.state.contacts.iter().position(|c| {
@@ -950,9 +1008,15 @@ impl MeowClient {
sent_at_ms: msg.sent_at_ms,
received_at,
content,
status: Status::Delivered,
};
let mut got = |id: &[u8]| match received.iter_mut().find(|(s, c, _)| *s == si && *c == cid) {
Some(r) => r.2.push(id.to_vec()),
None => received.push((si, cid.clone(), vec![id.to_vec()])),
};
match &msg.body {
Some(v2::user_message::Body::Text(t)) => {
got(&msg.id);
sp.batch.history.push(entry(Content::Text(t.text.clone())));
events.push(Event::Message {
contact: name,
@@ -962,6 +1026,7 @@ impl MeowClient {
});
}
Some(v2::user_message::Body::File(f)) => {
got(&msg.id);
sp.batch.history.push(entry(Content::File {
name: f.filename.clone(),
size: f.size,
@@ -974,6 +1039,20 @@ impl MeowClient {
data: f.data.clone(),
});
}
Some(v2::user_message::Body::Receipt(r)) => {
let (kind, status) = match v2::receipt::Kind::try_from(r.kind) {
Ok(v2::receipt::Kind::Read) => (ReceiptKind::Read, Status::Read),
_ => (ReceiptKind::Delivered, Status::Delivered),
};
sp.batch
.status
.extend(r.message_ids.iter().map(|m| (cid.clone(), m.clone(), status)));
events.push(Event::Receipt {
contact: name,
kind,
message_ids: r.message_ids.clone(),
});
}
_ => {}
}
}
@@ -981,6 +1060,21 @@ impl MeowClient {
}
sp.dirty = true;
}
// One delivery receipt per contact for this batch (never for receipts).
if self.settings().delivered_receipts {
for (si, cid, ids) in received {
let sp = &mut self.spaces[si];
let Some(contact) = sp.state.contacts.iter_mut().find(|c| c.id == cid) else {
continue;
};
let r = messaging::receipt(v2::receipt::Kind::Delivered, ids, now_ms());
let env = messaging::encrypt(contact, &r)?;
let d = messaging::deposit_for(contact, &env)?;
sp.state
.outbox
.push(outbox::item(&cid, vec![], &d, peer_servers(contact)));
}
}
for (si, before) in mailboxes_before.into_iter().enumerate() {
if self.spaces[si].dirty {
self.retire_mailboxes(si, before);
+7 -1
View File
@@ -217,8 +217,14 @@ impl MeowClient {
// Update the items.
let mut now_accepted: HashMap<Vec<u8>, usize> = HashMap::new();
for (si, id, key) in accepted {
if let Some(o) = self.spaces[si].state.outbox.iter_mut().find(|o| o.id == id) {
let sp = &mut self.spaces[si];
if let Some(o) = sp.state.outbox.iter_mut().find(|o| o.id == id) {
o.pending.retain(|s| s.sign_key != key);
if o.accepted == 0 && !o.message_id.is_empty() {
sp.batch
.status
.push((o.contact.clone(), o.message_id.clone(), meow_store::Status::Sent));
}
o.accepted += 1;
*now_accepted.entry(id).or_default() += 1;
}
+103 -3
View File
@@ -55,6 +55,22 @@ async fn client(dir: &std::path::Path, name: &str, servers: &[String]) -> MeowCl
c
}
fn no_receipts(events: Vec<Event>) -> Vec<Event> {
events
.into_iter()
.filter(|e| !matches!(e, Event::Receipt { .. }))
.collect()
}
async fn no_receipt_settings(c: &mut MeowClient) {
c.set_settings(meow_client::Settings {
delivered_receipts: false,
read_receipts: false,
})
.await
.unwrap();
}
fn texts(events: &[Event]) -> Vec<String> {
events
.iter()
@@ -139,16 +155,16 @@ async fn file_and_server_invitations_then_messaging() {
.await
.unwrap();
assert_eq!(who, "bob");
let ev = bob.sync(Duration::ZERO).await.unwrap();
let ev = no_receipts(bob.sync(Duration::ZERO).await.unwrap());
assert_eq!(
ev,
vec![Event::InvitationAccepted {
contact: "remote".into()
}]
);
let ev = remote.sync(Duration::ZERO).await.unwrap();
let ev = no_receipts(remote.sync(Duration::ZERO).await.unwrap());
assert_eq!(ev, vec![Event::ContactActivated { contact: "bob".into() }]);
let ev = bob.sync(Duration::ZERO).await.unwrap();
let ev = no_receipts(bob.sync(Duration::ZERO).await.unwrap());
assert_eq!(
ev,
vec![Event::ContactActivated {
@@ -311,6 +327,9 @@ async fn no_message_lost_when_the_client_dies() {
let servers = vec![url];
let mut bob = client(&dir, "bob", &servers).await;
let mut alice = client(&dir, "alice", &servers).await;
// This test counts what stays on the server: no receipts traffic.
no_receipt_settings(&mut bob).await;
no_receipt_settings(&mut alice).await;
let offer = bob.create_invitation("alice", &[], "", 3600).await.unwrap();
let answer = alice.answer_invitation(&offer, None, &[]).await.unwrap();
let confirm = bob.accept_answer(&answer).await.unwrap();
@@ -350,6 +369,7 @@ async fn no_message_lost_when_the_client_dies() {
// 3. Mailboxes that disappear still get their last messages acknowledged:
// the temporary answer mailbox of a server invitation...
let mut carol = client(&dir, "carol", &servers).await;
no_receipt_settings(&mut carol).await;
let link = bob.publish_invitation("carol", &[], "", "", 3600).await.unwrap();
carol.accept_published_invitation(&link, "", None, &[]).await.unwrap();
bob.sync(Duration::ZERO).await.unwrap(); // step 2 → 3, answer mailbox retired
@@ -515,3 +535,83 @@ async fn offline_messages_are_queued_and_retried() {
assert!(bob.pending_sends().is_empty());
let _ = std::fs::remove_dir_all(&dir);
}
// ───────────── receipts (roadmap lot 5.6) ─────────────
fn statuses(c: &MeowClient, name: &str, outbound: bool) -> Vec<meow_client::Status> {
c.history(name)
.unwrap()
.iter()
.filter(|h| h.outbound == outbound)
.map(|h| h.status)
.collect()
}
#[tokio::test(flavor = "multi_thread")]
async fn delivery_and_read_receipts() {
use meow_client::{ReceiptKind, Settings, Status};
let servers = vec![spawn_server().await, spawn_server().await];
let dir = tmpdir();
let mut alice = client(&dir, "alice", &servers).await;
let mut bob = client(&dir, "bob", &servers).await;
connect(&mut alice, &mut bob, "bob").await;
bob.sync(Duration::ZERO).await.unwrap();
let m1 = alice.send_text("bob", "one").await.unwrap().message_id;
let m2 = alice.send_text("bob", "two").await.unwrap().message_id;
assert_eq!(statuses(&alice, "bob", true), vec![Status::Sent, Status::Sent]);
// Bob receives (from 2 servers, processed once): one delivery receipt.
assert_eq!(texts(&bob.sync(Duration::ZERO).await.unwrap()), vec!["one", "two"]);
assert_eq!(
statuses(&bob, "alice", false),
vec![Status::Delivered, Status::Delivered]
);
let ev = alice.sync(Duration::ZERO).await.unwrap();
assert_eq!(
ev,
vec![Event::Receipt {
contact: "bob".into(),
kind: ReceiptKind::Delivered,
message_ids: vec![m1.clone(), m2.clone()]
}]
);
assert_eq!(
statuses(&alice, "bob", true),
vec![Status::Delivered, Status::Delivered]
);
// Bob reads.
assert_eq!(bob.mark_read("alice").await.unwrap(), 2);
assert_eq!(bob.mark_read("alice").await.unwrap(), 0);
assert_eq!(statuses(&bob, "alice", false), vec![Status::Read, Status::Read]);
let ev = alice.sync(Duration::ZERO).await.unwrap();
assert_eq!(
ev,
vec![Event::Receipt {
contact: "bob".into(),
kind: ReceiptKind::Read,
message_ids: vec![m1, m2]
}]
);
assert_eq!(statuses(&alice, "bob", true), vec![Status::Read, Status::Read]);
// Receipts are not acknowledged by receipts.
assert!(bob.sync(Duration::ZERO).await.unwrap().is_empty());
// Receipts can be turned off (persisted with the identity).
let off = Settings {
delivered_receipts: false,
read_receipts: false,
};
bob.set_settings(off).await.unwrap();
let path = dir.join("bob.mwid2");
drop(bob);
let mut bob = MeowClient::open(&path, "pw").await.unwrap();
assert_eq!(bob.settings(), off);
alice.send_text("bob", "three").await.unwrap();
assert_eq!(texts(&bob.sync(Duration::ZERO).await.unwrap()), vec!["three"]);
assert_eq!(bob.mark_read("alice").await.unwrap(), 1);
assert!(alice.sync(Duration::ZERO).await.unwrap().is_empty());
assert_eq!(statuses(&alice, "bob", true)[2], Status::Sent);
let _ = std::fs::remove_dir_all(&dir);
}