feat(receipts): persist read horizons so receipts show at once after a restart
- migration 0022 read_horizons, store read/replace - engine reads stored horizons once per chat, refresh writes them back Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -4,9 +4,9 @@ use std::time::Duration;
4
4
5
5
use chatsvc::{EventKind, MemberHorizon, MessageEvent, StatusEvent, StatusKind};
6
6
use chrono::{DateTime, Utc};
7
use store::MessageRecord;
7
use store::{MessageRecord, ReadHorizonRecord};
8
8
9
use crate::engine::{Conversation, SyncEngine};
9
use crate::engine::{Conversation, META_USER_ID, SyncEngine};
10
10
use crate::error::Result;
11
11
use crate::events::CoreEvent;
12
12
use crate::remote::Remote;
@@ -46,6 +46,7 @@ struct ConversationReceipts {
46
46
pub(crate) struct ReceiptCache {
47
47
conversations: Mutex<HashMap<String, Option<ConversationReceipts>>>,
48
48
pending: Mutex<HashSet<String>>,
49
read_from_store: Mutex<HashSet<String>>,
49
50
pub(crate) debounce: Duration,
50
51
}
51
52
@@ -54,6 +55,7 @@ impl Default for ReceiptCache {
54
55
ReceiptCache {
55
56
conversations: Mutex::new(HashMap::new()),
56
57
pending: Mutex::new(HashSet::new()),
58
read_from_store: Mutex::new(HashSet::new()),
57
59
debounce: DEFAULT_RECEIPT_DEBOUNCE,
58
60
}
59
61
}
@@ -73,9 +75,17 @@ fn user_of(member_id: &str) -> &str {
73
75
member_id.rsplit(':').next().unwrap_or(member_id)
74
76
}
75
77
78
fn stored_horizon(horizon: MemberHorizon) -> ReadHorizonRecord {
79
ReadHorizonRecord {
80
member_id: horizon.member_id,
81
read_until: horizon.read_until,
82
read_at: horizon.read_at,
83
}
84
}
85
76
86
fn build(
77
87
my_user_id: &str,
78
horizons: &[MemberHorizon],
88
horizons: &[ReadHorizonRecord],
79
89
members: &[store::MemberRecord],
80
90
) -> Option<ConversationReceipts> {
81
91
let mut others: Vec<OtherMember> = horizons
@@ -169,8 +179,9 @@ impl<R: Remote> SyncEngine<R> {
169
179
})
170
180
}
171
181
172
/// Memory only, cheap enough to call per rendered message.
182
/// Memory first; the stored horizons of a chat are read once per session, so receipts show before the refresh.
173
183
pub fn receipt_state_for(&self, record: &MessageRecord) -> ReceiptState {
184
self.load_stored_receipts(&record.conversation_id);
174
185
let conversations = locked(&self.receipts.conversations);
175
186
match conversations.get(&record.conversation_id) {
176
187
Some(Some(receipts)) => state_of(receipts, record),
@@ -178,6 +189,31 @@ impl<R: Remote> SyncEngine<R> {
178
189
}
179
190
}
180
191
192
fn load_stored_receipts(&self, conversation_id: &str) {
193
if !locked(&self.receipts.read_from_store).insert(conversation_id.to_owned()) {
194
return;
195
}
196
if locked(&self.receipts.conversations).contains_key(conversation_id) {
197
return;
198
}
199
let Some(cached) = self.stored_receipts(conversation_id) else {
200
return;
201
};
202
locked(&self.receipts.conversations)
203
.entry(conversation_id.to_owned())
204
.or_insert(Some(cached));
205
}
206
207
fn stored_receipts(&self, conversation_id: &str) -> Option<ConversationReceipts> {
208
let horizons = self.store.read_horizons(conversation_id).ok()?;
209
if horizons.is_empty() {
210
return None;
211
}
212
let my_user_id = self.store.meta(META_USER_ID).ok()??;
213
let members = self.store.chat(conversation_id).ok()??.members;
214
build(&my_user_id, &horizons, &members)
215
}
216
181
217
/// Call when a chat opens. Channels are skipped.
182
218
pub async fn refresh_receipts(&self, conversation_id: &str) -> Result<()> {
183
219
if matches!(
@@ -187,7 +223,15 @@ impl<R: Remote> SyncEngine<R> {
187
223
return Ok(());
188
224
}
189
225
let my_user_id = self.my_user_id().await?;
190
let horizons = self.remote.consumption_horizons(conversation_id).await?;
226
let horizons: Vec<ReadHorizonRecord> = self
227
.remote
228
.consumption_horizons(conversation_id)
229
.await?
230
.into_iter()
231
.map(stored_horizon)
232
.collect();
233
self.store.set_read_horizons(conversation_id, &horizons)?;
234
locked(&self.receipts.read_from_store).insert(conversation_id.to_owned());
191
235
let members = self
192
236
.store
193
237
.chat(conversation_id)?
@@ -4,9 +4,9 @@ use std::time::Duration;4
4
5
use chatsvc::{EventKind, MemberHorizon, MessageEvent, StatusEvent, StatusKind};5
use chatsvc::{EventKind, MemberHorizon, MessageEvent, StatusEvent, StatusKind};6
use chrono::{DateTime, Utc};6
use chrono::{DateTime, Utc};7
use store::MessageRecord;7
use store::{MessageRecord, ReadHorizonRecord};8
8
9
use crate::engine::{Conversation, SyncEngine};9
use crate::engine::{Conversation, META_USER_ID, SyncEngine};10
use crate::error::Result;10
use crate::error::Result;11
use crate::events::CoreEvent;11
use crate::events::CoreEvent;12
use crate::remote::Remote;12
use crate::remote::Remote;@@ -46,6 +46,7 @@ struct ConversationReceipts {46
pub(crate) struct ReceiptCache {46
pub(crate) struct ReceiptCache {47
conversations: Mutex<HashMap<String, Option<ConversationReceipts>>>,47
conversations: Mutex<HashMap<String, Option<ConversationReceipts>>>,48
pending: Mutex<HashSet<String>>,48
pending: Mutex<HashSet<String>>,49
read_from_store: Mutex<HashSet<String>>,49
pub(crate) debounce: Duration,50
pub(crate) debounce: Duration,50
}51
}51
52
@@ -54,6 +55,7 @@ impl Default for ReceiptCache {54
ReceiptCache {55
ReceiptCache {55
conversations: Mutex::new(HashMap::new()),56
conversations: Mutex::new(HashMap::new()),56
pending: Mutex::new(HashSet::new()),57
pending: Mutex::new(HashSet::new()),58
read_from_store: Mutex::new(HashSet::new()),57
debounce: DEFAULT_RECEIPT_DEBOUNCE,59
debounce: DEFAULT_RECEIPT_DEBOUNCE,58
}60
}59
}61
}@@ -73,9 +75,17 @@ fn user_of(member_id: &str) -> &str {73
member_id.rsplit(':').next().unwrap_or(member_id)75
member_id.rsplit(':').next().unwrap_or(member_id)74
}76
}75
77
78
fn stored_horizon(horizon: MemberHorizon) -> ReadHorizonRecord {79
ReadHorizonRecord {80
member_id: horizon.member_id,81
read_until: horizon.read_until,82
read_at: horizon.read_at,83
}84
}85
76
fn build(86
fn build(77
my_user_id: &str,87
my_user_id: &str,78
horizons: &[MemberHorizon],88
horizons: &[ReadHorizonRecord],79
members: &[store::MemberRecord],89
members: &[store::MemberRecord],80
) -> Option<ConversationReceipts> {90
) -> Option<ConversationReceipts> {81
let mut others: Vec<OtherMember> = horizons91
let mut others: Vec<OtherMember> = horizons@@ -169,8 +179,9 @@ impl<R: Remote> SyncEngine<R> {169
})179
})170
}180
}171
181
172
/// Memory only, cheap enough to call per rendered message.182
/// Memory first; the stored horizons of a chat are read once per session, so receipts show before the refresh.173
pub fn receipt_state_for(&self, record: &MessageRecord) -> ReceiptState {183
pub fn receipt_state_for(&self, record: &MessageRecord) -> ReceiptState {184
self.load_stored_receipts(&record.conversation_id);174
let conversations = locked(&self.receipts.conversations);185
let conversations = locked(&self.receipts.conversations);175
match conversations.get(&record.conversation_id) {186
match conversations.get(&record.conversation_id) {176
Some(Some(receipts)) => state_of(receipts, record),187
Some(Some(receipts)) => state_of(receipts, record),@@ -178,6 +189,31 @@ impl<R: Remote> SyncEngine<R> {178
}189
}179
}190
}180
191
192
fn load_stored_receipts(&self, conversation_id: &str) {193
if !locked(&self.receipts.read_from_store).insert(conversation_id.to_owned()) {194
return;195
}196
if locked(&self.receipts.conversations).contains_key(conversation_id) {197
return;198
}199
let Some(cached) = self.stored_receipts(conversation_id) else {200
return;201
};202
locked(&self.receipts.conversations)203
.entry(conversation_id.to_owned())204
.or_insert(Some(cached));205
}206
207
fn stored_receipts(&self, conversation_id: &str) -> Option<ConversationReceipts> {208
let horizons = self.store.read_horizons(conversation_id).ok()?;209
if horizons.is_empty() {210
return None;211
}212
let my_user_id = self.store.meta(META_USER_ID).ok()??;213
let members = self.store.chat(conversation_id).ok()??.members;214
build(&my_user_id, &horizons, &members)215
}216
181
/// Call when a chat opens. Channels are skipped.217
/// Call when a chat opens. Channels are skipped.182
pub async fn refresh_receipts(&self, conversation_id: &str) -> Result<()> {218
pub async fn refresh_receipts(&self, conversation_id: &str) -> Result<()> {183
if matches!(219
if matches!(@@ -187,7 +223,15 @@ impl<R: Remote> SyncEngine<R> {187
return Ok(());223
return Ok(());188
}224
}189
let my_user_id = self.my_user_id().await?;225
let my_user_id = self.my_user_id().await?;190
let horizons = self.remote.consumption_horizons(conversation_id).await?;226
let horizons: Vec<ReadHorizonRecord> = self227
.remote228
.consumption_horizons(conversation_id)229
.await?230
.into_iter()231
.map(stored_horizon)232
.collect();233
self.store.set_read_horizons(conversation_id, &horizons)?;234
locked(&self.receipts.read_from_store).insert(conversation_id.to_owned());191
let members = self235
let members = self192
.store236
.store193
.chat(conversation_id)?237
.chat(conversation_id)?@@ -3856,6 +3856,27 @@ async fn one_on_one_read_up_to_horizon() {
3856
3856
);
3857
3857
}
3858
3858
3859
#[tokio::test]
3860
async fn stored_horizons_show_receipts_after_a_restart_before_any_refresh() {
3861
let fake = Arc::new(Fake::default());
3862
let engine = receipt_engine(&fake, vec![one_on_one()]).await;
3863
*fake.horizons.lock().unwrap() =
3864
vec![horizon_of("user-me", 3, 3), horizon_of("user-ada", 2, 9)];
3865
engine.refresh_receipts(CHAT).await.unwrap();
3866
let restarted =
3867
SyncEngine::with_config(Handle(fake.clone()), engine.store().clone(), small_pages());
3868
fake.horizons.lock().unwrap().clear();
3869
3870
assert!(matches!(
3871
restarted.receipt_state(CHAT, "m0001"),
3872
teams_core::ReceiptState::Read { .. }
3873
));
3874
assert_eq!(
3875
restarted.receipt_state(CHAT, "m0003"),
3876
teams_core::ReceiptState::Sent
3877
);
3878
}
3879
3859
3880
#[tokio::test]
3860
3881
async fn horizon_equal_to_creation_time_counts_as_read() {
3861
3882
let fake = Arc::new(Fake::default());
@@ -3856,6 +3856,27 @@ async fn one_on_one_read_up_to_horizon() {3856
);3856
);3857
}3857
}3858
3858
3859
#[tokio::test]3860
async fn stored_horizons_show_receipts_after_a_restart_before_any_refresh() {3861
let fake = Arc::new(Fake::default());3862
let engine = receipt_engine(&fake, vec![one_on_one()]).await;3863
*fake.horizons.lock().unwrap() =3864
vec![horizon_of("user-me", 3, 3), horizon_of("user-ada", 2, 9)];3865
engine.refresh_receipts(CHAT).await.unwrap();3866
let restarted =3867
SyncEngine::with_config(Handle(fake.clone()), engine.store().clone(), small_pages());3868
fake.horizons.lock().unwrap().clear();3869
3870
assert!(matches!(3871
restarted.receipt_state(CHAT, "m0001"),3872
teams_core::ReceiptState::Read { .. }3873
));3874
assert_eq!(3875
restarted.receipt_state(CHAT, "m0003"),3876
teams_core::ReceiptState::Sent3877
);3878
}3879
3859
#[tokio::test]3880
#[tokio::test]3860
async fn horizon_equal_to_creation_time_counts_as_read() {3881
async fn horizon_equal_to_creation_time_counts_as_read() {3861
let fake = Arc::new(Fake::default());3882
let fake = Arc::new(Fake::default());@@ -14,6 +14,7 @@ mod models;
14
14
mod outbox;
15
15
mod presence;
16
16
mod proposals;
17
mod read_horizons;
17
18
mod search;
18
19
mod sidebar;
19
20
mod store;
@@ -29,7 +30,7 @@ pub use models::{
29
30
AttachmentImage, AvatarRecord, ChannelLayoutRecord, ChannelNotificationLevel,
30
31
ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord,
31
32
ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord, MessageRecord,
32
OutboxRecord, OutboxState, OutboxTarget, RecentScope, SearchHit, Sidebar, SidebarTeam,
33
OutboxRecord, OutboxState, OutboxTarget, ReadHorizonRecord, RecentScope, SearchHit, Sidebar, SidebarTeam,
33
34
SyncState, TeamLayoutRecord, TeamRecord,
34
35
};
35
36
pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};
@@ -14,6 +14,7 @@ mod models;14
mod outbox;14
mod outbox;15
mod presence;15
mod presence;16
mod proposals;16
mod proposals;17
mod read_horizons;17
mod search;18
mod search;18
mod sidebar;19
mod sidebar;19
mod store;20
mod store;@@ -29,7 +30,7 @@ pub use models::{29
AttachmentImage, AvatarRecord, ChannelLayoutRecord, ChannelNotificationLevel,30
AttachmentImage, AvatarRecord, ChannelLayoutRecord, ChannelNotificationLevel,30
ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord,31
ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord,31
ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord, MessageRecord,32
ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord, MessageRecord,32
OutboxRecord, OutboxState, OutboxTarget, RecentScope, SearchHit, Sidebar, SidebarTeam,33
OutboxRecord, OutboxState, OutboxTarget, ReadHorizonRecord, RecentScope, SearchHit, Sidebar, SidebarTeam,33
SyncState, TeamLayoutRecord, TeamRecord,34
SyncState, TeamLayoutRecord, TeamRecord,34
};35
};35
pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};36
pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};@@ -93,6 +93,10 @@ const MIGRATIONS: &[Migration] = &[
93
93
script: include_str!("migrations/0021_recording_events.sql"),
94
94
after: None,
95
95
},
96
Migration {
97
script: include_str!("migrations/0022_read_horizons.sql"),
98
after: None,
99
},
96
100
];
97
101
98
102
pub fn latest_version() -> i64 {
@@ -93,6 +93,10 @@ const MIGRATIONS: &[Migration] = &[93
script: include_str!("migrations/0021_recording_events.sql"),93
script: include_str!("migrations/0021_recording_events.sql"),94
after: None,94
after: None,95
},95
},96
Migration {97
script: include_str!("migrations/0022_read_horizons.sql"),98
after: None,99
},96
];100
];97
101
98
pub fn latest_version() -> i64 {102
pub fn latest_version() -> i64 {@@ -0,0 +1,7 @@
1
CREATE TABLE IF NOT EXISTS read_horizons (
2
conversation_id TEXT NOT NULL,
3
member_id TEXT NOT NULL,
4
read_until INTEGER NOT NULL,
5
read_at INTEGER,
6
PRIMARY KEY (conversation_id, member_id)
7
);
@@ -0,0 +1,7 @@1
CREATE TABLE IF NOT EXISTS read_horizons (2
conversation_id TEXT NOT NULL,3
member_id TEXT NOT NULL,4
read_until INTEGER NOT NULL,5
read_at INTEGER,6
PRIMARY KEY (conversation_id, member_id)7
);@@ -98,6 +98,14 @@ pub struct RecentScope {
98
98
pub after: DateTime<Utc>,
99
99
}
100
100
101
/// The last read position of one conversation member, as chatsvc reports it.
102
#[derive(Debug, Clone, PartialEq, Eq)]
103
pub struct ReadHorizonRecord {
104
pub member_id: String,
105
pub read_until: DateTime<Utc>,
106
pub read_at: Option<DateTime<Utc>>,
107
}
108
101
109
#[derive(Debug, Clone, PartialEq)]
102
110
pub struct SyncState {
103
111
pub newest_seen: Option<DateTime<Utc>>,
@@ -98,6 +98,14 @@ pub struct RecentScope {98
pub after: DateTime<Utc>,98
pub after: DateTime<Utc>,99
}99
}100
100
101
/// The last read position of one conversation member, as chatsvc reports it.102
#[derive(Debug, Clone, PartialEq, Eq)]103
pub struct ReadHorizonRecord {104
pub member_id: String,105
pub read_until: DateTime<Utc>,106
pub read_at: Option<DateTime<Utc>>,107
}108
101
#[derive(Debug, Clone, PartialEq)]109
#[derive(Debug, Clone, PartialEq)]102
pub struct SyncState {110
pub struct SyncState {103
pub newest_seen: Option<DateTime<Utc>>,111
pub newest_seen: Option<DateTime<Utc>>,@@ -0,0 +1,56 @@
1
use rusqlite::params;
2
3
use crate::error::Result;
4
use crate::models::ReadHorizonRecord;
5
use crate::store::Store;
6
use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_millis};
7
8
impl Store {
9
pub fn read_horizons(&self, conversation_id: &str) -> Result<Vec<ReadHorizonRecord>> {
10
let connection = self.lock()?;
11
let mut statement = connection.prepare_cached(
12
"SELECT member_id, read_until, read_at FROM read_horizons
13
WHERE conversation_id = ?1 ORDER BY member_id",
14
)?;
15
let rows = statement.query_map([conversation_id], |row| {
16
Ok(ReadHorizonRecord {
17
member_id: row.get(0)?,
18
read_until: from_millis(row.get(1)?),
19
read_at: optional_from_millis(row.get(2)?),
20
})
21
})?;
22
Ok(rows.collect::<rusqlite::Result<_>>()?)
23
}
24
25
/// Replaces every stored horizon of the conversation.
26
pub fn set_read_horizons(
27
&self,
28
conversation_id: &str,
29
horizons: &[ReadHorizonRecord],
30
) -> Result<()> {
31
let mut connection = self.lock()?;
32
let transaction = connection.transaction()?;
33
transaction.execute(
34
"DELETE FROM read_horizons WHERE conversation_id = ?1",
35
[conversation_id],
36
)?;
37
{
38
let mut statement = transaction.prepare_cached(
39
"INSERT INTO read_horizons (conversation_id, member_id, read_until, read_at)
40
VALUES (?1, ?2, ?3, ?4)
41
ON CONFLICT (conversation_id, member_id) DO UPDATE SET
42
read_until = excluded.read_until, read_at = excluded.read_at",
43
)?;
44
for horizon in horizons {
45
statement.execute(params![
46
conversation_id,
47
horizon.member_id,
48
to_millis(horizon.read_until),
49
optional_to_millis(horizon.read_at),
50
])?;
51
}
52
}
53
transaction.commit()?;
54
Ok(())
55
}
56
}
@@ -0,0 +1,56 @@1
use rusqlite::params;2
3
use crate::error::Result;4
use crate::models::ReadHorizonRecord;5
use crate::store::Store;6
use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_millis};7
8
impl Store {9
pub fn read_horizons(&self, conversation_id: &str) -> Result<Vec<ReadHorizonRecord>> {10
let connection = self.lock()?;11
let mut statement = connection.prepare_cached(12
"SELECT member_id, read_until, read_at FROM read_horizons13
WHERE conversation_id = ?1 ORDER BY member_id",14
)?;15
let rows = statement.query_map([conversation_id], |row| {16
Ok(ReadHorizonRecord {17
member_id: row.get(0)?,18
read_until: from_millis(row.get(1)?),19
read_at: optional_from_millis(row.get(2)?),20
})21
})?;22
Ok(rows.collect::<rusqlite::Result<_>>()?)23
}24
25
/// Replaces every stored horizon of the conversation.26
pub fn set_read_horizons(27
&self,28
conversation_id: &str,29
horizons: &[ReadHorizonRecord],30
) -> Result<()> {31
let mut connection = self.lock()?;32
let transaction = connection.transaction()?;33
transaction.execute(34
"DELETE FROM read_horizons WHERE conversation_id = ?1",35
[conversation_id],36
)?;37
{38
let mut statement = transaction.prepare_cached(39
"INSERT INTO read_horizons (conversation_id, member_id, read_until, read_at)40
VALUES (?1, ?2, ?3, ?4)41
ON CONFLICT (conversation_id, member_id) DO UPDATE SET42
read_until = excluded.read_until, read_at = excluded.read_at",43
)?;44
for horizon in horizons {45
statement.execute(params![46
conversation_id,47
horizon.member_id,48
to_millis(horizon.read_until),49
optional_to_millis(horizon.read_at),50
])?;51
}52
}53
transaction.commit()?;54
Ok(())55
}56
}@@ -3,7 +3,8 @@ use rusqlite::Connection;
3
3
use store::{
4
4
AvatarRecord, ChannelLayoutRecord, ChannelNotificationLevel, ChannelNotifications,
5
5
ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord, MemberRecord,
6
MessageRecord, RecentScope, Store, SyncState, TeamLayoutRecord, TeamRecord,
6
MessageRecord, ReadHorizonRecord, RecentScope, Store, SyncState, TeamLayoutRecord,
7
TeamRecord,
7
8
};
8
9
9
10
#[test]
@@ -545,11 +546,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {
545
546
let path = directory.path().join("nested").join("cache.sqlite3");
546
547
{
547
548
let store = Store::open(&path).unwrap();
548
assert_eq!(store.schema_version().unwrap(), 21);
549
assert_eq!(store.schema_version().unwrap(), 22);
549
550
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
550
551
}
551
552
let reopened = Store::open(&path).unwrap();
552
assert_eq!(reopened.schema_version().unwrap(), 21);
553
assert_eq!(reopened.schema_version().unwrap(), 22);
553
554
assert_eq!(reopened.message_count("c").unwrap(), 1);
554
555
drop(reopened);
555
556
let mode: String = rusqlite_open(&path)
@@ -581,7 +582,7 @@ fn old_schema_is_upgraded_in_place() {
581
582
connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals; PRAGMA user_version = 0").unwrap();
582
583
drop(connection);
583
584
let store = Store::open(&path).unwrap();
584
assert_eq!(store.schema_version().unwrap(), 21);
585
assert_eq!(store.schema_version().unwrap(), 22);
585
586
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
586
587
}
587
588
@@ -647,7 +648,7 @@ fn migration_to_v2_keeps_existing_sync_state() {
647
648
let store = Store::open(&path).unwrap();
648
649
let state = store.sync_state("c").unwrap().unwrap();
649
650
assert_eq!(state.delta_link, None);
650
assert_eq!(store.schema_version().unwrap(), 21);
651
assert_eq!(store.schema_version().unwrap(), 22);
651
652
}
652
653
653
654
#[test]
@@ -1413,7 +1414,7 @@ fn migration_to_v20_adds_the_call_event_column() {
1413
1414
.unwrap();
1414
1415
}
1415
1416
let store = Store::open(&path).unwrap();
1416
assert_eq!(store.schema_version().unwrap(), 21);
1417
assert_eq!(store.schema_version().unwrap(), 22);
1417
1418
let old = store.messages("c", None, 10).unwrap();
1418
1419
assert_eq!(old[0].call_event_json, None);
1419
1420
assert!(store.sync_state("c").unwrap().is_none());
@@ -1457,8 +1458,51 @@ fn migration_to_v21_refetches_chats_and_channels_for_recordings() {
1457
1458
.unwrap();
1458
1459
}
1459
1460
let store = Store::open(&path).unwrap();
1460
assert_eq!(store.schema_version().unwrap(), 21);
1461
assert_eq!(store.schema_version().unwrap(), 22);
1461
1462
assert!(store.sync_state("c").unwrap().is_none());
1462
1463
assert!(store.sync_state("channel").unwrap().is_none());
1463
1464
assert!(store.sync_state("other").unwrap().is_some());
1464
1465
}
1466
1467
fn horizon(member_id: &str, read_minute: u32, at_minute: Option<u32>) -> ReadHorizonRecord {
1468
ReadHorizonRecord {
1469
member_id: member_id.to_owned(),
1470
read_until: at(read_minute),
1471
read_at: at_minute.map(at),
1472
}
1473
}
1474
1475
#[test]
1476
fn migration_to_v22_adds_read_horizons_that_survive_a_reopen() {
1477
let directory = tempfile::tempdir().unwrap();
1478
let path = directory.path().join("old.sqlite3");
1479
{
1480
let store = Store::open(&path).unwrap();
1481
store.upsert_chats(&[chat("c", "Chat", Some(at(1)))]).unwrap();
1482
drop(store);
1483
Connection::open(&path)
1484
.unwrap()
1485
.execute_batch("DROP TABLE read_horizons; PRAGMA user_version = 21")
1486
.unwrap();
1487
}
1488
let store = Store::open(&path).unwrap();
1489
assert_eq!(store.schema_version().unwrap(), 22);
1490
assert!(store.read_horizons("c").unwrap().is_empty());
1491
let horizons = [horizon("8:orgid:ada", 3, Some(4)), horizon("8:orgid:bob", 2, None)];
1492
store.set_read_horizons("c", &horizons).unwrap();
1493
drop(store);
1494
let reopened = Store::open(&path).unwrap();
1495
assert_eq!(reopened.read_horizons("c").unwrap(), horizons);
1496
}
1497
1498
#[test]
1499
fn setting_read_horizons_replaces_the_conversation_only() {
1500
let store = Store::open_in_memory().unwrap();
1501
let first = [horizon("8:orgid:ada", 3, None), horizon("8:orgid:bob", 2, None)];
1502
store.set_read_horizons("c", &first).unwrap();
1503
store.set_read_horizons("other", &[horizon("8:orgid:cy", 1, None)]).unwrap();
1504
let second = [horizon("8:orgid:ada", 5, Some(6))];
1505
store.set_read_horizons("c", &second).unwrap();
1506
assert_eq!(store.read_horizons("c").unwrap(), second);
1507
assert_eq!(store.read_horizons("other").unwrap().len(), 1);
1508
}
@@ -3,7 +3,8 @@ use rusqlite::Connection;3
use store::{3
use store::{4
AvatarRecord, ChannelLayoutRecord, ChannelNotificationLevel, ChannelNotifications,4
AvatarRecord, ChannelLayoutRecord, ChannelNotificationLevel, ChannelNotifications,5
ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord, MemberRecord,5
ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord, MemberRecord,6
MessageRecord, RecentScope, Store, SyncState, TeamLayoutRecord, TeamRecord,6
MessageRecord, ReadHorizonRecord, RecentScope, Store, SyncState, TeamLayoutRecord,7
TeamRecord,7
};8
};8
9
9
#[test]10
#[test]@@ -545,11 +546,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {545
let path = directory.path().join("nested").join("cache.sqlite3");546
let path = directory.path().join("nested").join("cache.sqlite3");546
{547
{547
let store = Store::open(&path).unwrap();548
let store = Store::open(&path).unwrap();548
assert_eq!(store.schema_version().unwrap(), 21);549
assert_eq!(store.schema_version().unwrap(), 22);549
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();550
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();550
}551
}551
let reopened = Store::open(&path).unwrap();552
let reopened = Store::open(&path).unwrap();552
assert_eq!(reopened.schema_version().unwrap(), 21);553
assert_eq!(reopened.schema_version().unwrap(), 22);553
assert_eq!(reopened.message_count("c").unwrap(), 1);554
assert_eq!(reopened.message_count("c").unwrap(), 1);554
drop(reopened);555
drop(reopened);555
let mode: String = rusqlite_open(&path)556
let mode: String = rusqlite_open(&path)@@ -581,7 +582,7 @@ fn old_schema_is_upgraded_in_place() {581
connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals; PRAGMA user_version = 0").unwrap();582
connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals; PRAGMA user_version = 0").unwrap();582
drop(connection);583
drop(connection);583
let store = Store::open(&path).unwrap();584
let store = Store::open(&path).unwrap();584
assert_eq!(store.schema_version().unwrap(), 21);585
assert_eq!(store.schema_version().unwrap(), 22);585
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();586
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();586
}587
}587
588
@@ -647,7 +648,7 @@ fn migration_to_v2_keeps_existing_sync_state() {647
let store = Store::open(&path).unwrap();648
let store = Store::open(&path).unwrap();648
let state = store.sync_state("c").unwrap().unwrap();649
let state = store.sync_state("c").unwrap().unwrap();649
assert_eq!(state.delta_link, None);650
assert_eq!(state.delta_link, None);650
assert_eq!(store.schema_version().unwrap(), 21);651
assert_eq!(store.schema_version().unwrap(), 22);651
}652
}652
653
653
#[test]654
#[test]@@ -1413,7 +1414,7 @@ fn migration_to_v20_adds_the_call_event_column() {1413
.unwrap();1414
.unwrap();1414
}1415
}1415
let store = Store::open(&path).unwrap();1416
let store = Store::open(&path).unwrap();1416
assert_eq!(store.schema_version().unwrap(), 21);1417
assert_eq!(store.schema_version().unwrap(), 22);1417
let old = store.messages("c", None, 10).unwrap();1418
let old = store.messages("c", None, 10).unwrap();1418
assert_eq!(old[0].call_event_json, None);1419
assert_eq!(old[0].call_event_json, None);1419
assert!(store.sync_state("c").unwrap().is_none());1420
assert!(store.sync_state("c").unwrap().is_none());@@ -1457,8 +1458,51 @@ fn migration_to_v21_refetches_chats_and_channels_for_recordings() {1457
.unwrap();1458
.unwrap();1458
}1459
}1459
let store = Store::open(&path).unwrap();1460
let store = Store::open(&path).unwrap();1460
assert_eq!(store.schema_version().unwrap(), 21);1461
assert_eq!(store.schema_version().unwrap(), 22);1461
assert!(store.sync_state("c").unwrap().is_none());1462
assert!(store.sync_state("c").unwrap().is_none());1462
assert!(store.sync_state("channel").unwrap().is_none());1463
assert!(store.sync_state("channel").unwrap().is_none());1463
assert!(store.sync_state("other").unwrap().is_some());1464
assert!(store.sync_state("other").unwrap().is_some());1464
}1465
}1466
1467
fn horizon(member_id: &str, read_minute: u32, at_minute: Option<u32>) -> ReadHorizonRecord {1468
ReadHorizonRecord {1469
member_id: member_id.to_owned(),1470
read_until: at(read_minute),1471
read_at: at_minute.map(at),1472
}1473
}1474
1475
#[test]1476
fn migration_to_v22_adds_read_horizons_that_survive_a_reopen() {1477
let directory = tempfile::tempdir().unwrap();1478
let path = directory.path().join("old.sqlite3");1479
{1480
let store = Store::open(&path).unwrap();1481
store.upsert_chats(&[chat("c", "Chat", Some(at(1)))]).unwrap();1482
drop(store);1483
Connection::open(&path)1484
.unwrap()1485
.execute_batch("DROP TABLE read_horizons; PRAGMA user_version = 21")1486
.unwrap();1487
}1488
let store = Store::open(&path).unwrap();1489
assert_eq!(store.schema_version().unwrap(), 22);1490
assert!(store.read_horizons("c").unwrap().is_empty());1491
let horizons = [horizon("8:orgid:ada", 3, Some(4)), horizon("8:orgid:bob", 2, None)];1492
store.set_read_horizons("c", &horizons).unwrap();1493
drop(store);1494
let reopened = Store::open(&path).unwrap();1495
assert_eq!(reopened.read_horizons("c").unwrap(), horizons);1496
}1497
1498
#[test]1499
fn setting_read_horizons_replaces_the_conversation_only() {1500
let store = Store::open_in_memory().unwrap();1501
let first = [horizon("8:orgid:ada", 3, None), horizon("8:orgid:bob", 2, None)];1502
store.set_read_horizons("c", &first).unwrap();1503
store.set_read_horizons("other", &[horizon("8:orgid:cy", 1, None)]).unwrap();1504
let second = [horizon("8:orgid:ada", 5, Some(6))];1505
store.set_read_horizons("c", &second).unwrap();1506
assert_eq!(store.read_horizons("c").unwrap(), second);1507
assert_eq!(store.read_horizons("other").unwrap().len(), 1);1508
}