Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(channels): load_around_message_id returning previous_cursor when it shouldn't (#2853)

teo085937da1a34
diff --git a/js/app/packages/queries/channel/channel-messages.ts b/js/app/packages/queries/channel/channel-messages.ts
index e1c7a0775c..3c4678c03c 100644
--- a/js/app/packages/queries/channel/channel-messages.ts
+++ b/js/app/packages/queries/channel/channel-messages.ts
@@ -219,6 +219,11 @@ export function insertTopLevelMessageIntoChannelMessages(
const [newestPage, ...olderPages] = data.pages;
+ console.debug(
+ '[channel-messages.insertTopLevelMessageIntoChannelMessages]',
+ ` previous_cursor: ${newestPage.previous_cursor}`
+ );
+
// Only insert into cache entries that represent the bottom of the
// conversation. If the newest page has a previous_cursor, we're viewing
// a mid-conversation slice (e.g. load-around) and prepending here would
diff --git a/rust/cloud-storage/channels/src/domain/ports.rs b/rust/cloud-storage/channels/src/domain/ports.rs
index abb049acff..0831110bbf 100644
--- a/rust/cloud-storage/channels/src/domain/ports.rs
+++ b/rust/cloud-storage/channels/src/domain/ports.rs
@@ -109,12 +109,15 @@ pub trait ChannelMessagesService: Send + Sync + 'static {
) -> impl Future<Output = Result<Vec<ChannelParticipant>, ChannelMessagesErr>> + Send;
/// Fetch a centered window of messages around a specific message id.
+ ///
+ /// The result's `has_more_newer` reports whether newer messages exist outside the
+ /// returned window.
fn get_channel_messages_around(
&self,
channel_id: Uuid,
message_id: Uuid,
limit: u16,
- ) -> impl Future<Output = Result<ChannelMessagesPage, ChannelMessagesErr>> + Send;
+ ) -> impl Future<Output = Result<ChannelMessagesQueryResult, ChannelMessagesErr>> + Send;
/// Fetch all replies for the thread identified by `message_id`.
///
@@ -131,6 +134,7 @@ pub type ChannelMessagesPage =
models_pagination::PaginatedCursor<super::models::ChannelMessage, Uuid, CreatedAt, ()>;
/// Result for a cursor-paginated channel messages query.
+#[derive(Debug)]
pub struct ChannelMessagesQueryResult {
/// The page of messages.
pub page: ChannelMessagesPage,
diff --git a/rust/cloud-storage/channels/src/domain/service.rs b/rust/cloud-storage/channels/src/domain/service.rs
index c8f1d77613..2608a42a15 100644
--- a/rust/cloud-storage/channels/src/domain/service.rs
+++ b/rust/cloud-storage/channels/src/domain/service.rs
@@ -4,8 +4,8 @@ use crate::domain::{
ThreadInfo, ThreadReply, TopLevelMessageRow,
},
ports::{
- ChannelAttachmentsPage, ChannelMessagesErr, ChannelMessagesPage,
- ChannelMessagesQueryResult, ChannelMessagesRepo, ChannelMessagesService,
+ ChannelAttachmentsPage, ChannelMessagesErr, ChannelMessagesQueryResult,
+ ChannelMessagesRepo, ChannelMessagesService,
},
};
use models_pagination::{CreatedAt, PaginateOn, Query};
@@ -114,17 +114,36 @@ where
/// - `limit`: total number of messages to return (including the anchor).
///
/// Returns messages in DESC order (newest first).
+struct CenteredWindow {
+ rows: Vec<TopLevelMessageRow>,
+ has_more_newer: bool,
+}
+
+impl std::ops::Deref for CenteredWindow {
+ type Target = [TopLevelMessageRow];
+
+ fn deref(&self) -> &Self::Target {
+ &self.rows
+ }
+}
+
fn center_window(
before: Vec<TopLevelMessageRow>,
anchor: TopLevelMessageRow,
after: Vec<TopLevelMessageRow>,
limit: usize,
-) -> Vec<TopLevelMessageRow> {
+) -> CenteredWindow {
if limit == 0 {
- return vec![];
+ return CenteredWindow {
+ rows: vec![],
+ has_more_newer: !after.is_empty(),
+ };
}
if limit == 1 {
- return vec![anchor];
+ return CenteredWindow {
+ rows: vec![anchor],
+ has_more_newer: !after.is_empty(),
+ };
}
let slots = limit - 1;
@@ -133,6 +152,7 @@ fn center_window(
let before_take = half.min(before.len());
let after_take = (slots - before_take).min(after.len());
let before_take = (slots - after_take).min(before.len());
+ let has_more_newer = after.len() > after_take;
let mut before = before;
before.truncate(before_take);
@@ -146,7 +166,10 @@ fn center_window(
result.push(anchor);
result.append(&mut before);
- result
+ CenteredWindow {
+ rows: result,
+ has_more_newer,
+ }
}
impl<R> ChannelMessagesService for ChannelMessagesServiceImpl<R>
@@ -229,7 +252,7 @@ where
channel_id: Uuid,
message_id: Uuid,
limit: u16,
- ) -> Result<ChannelMessagesPage, ChannelMessagesErr> {
+ ) -> Result<ChannelMessagesQueryResult, ChannelMessagesErr> {
let limit = limit.clamp(1, 100);
let anchor = self
@@ -245,8 +268,9 @@ where
.await
.map_err(anyhow::Error::from)?;
- let rows = center_window(before, anchor, after, limit.into());
- let messages = self.hydrate_messages(rows).await?;
+ let window = center_window(before, anchor, after, limit.into());
+ let has_more_newer = window.has_more_newer;
+ let messages = self.hydrate_messages(window.rows).await?;
let page = messages
.into_iter()
@@ -254,7 +278,10 @@ where
.filter_on(())
.into_page();
- Ok(page)
+ Ok(ChannelMessagesQueryResult {
+ page,
+ has_more_newer,
+ })
}
#[tracing::instrument(err, skip(self))]
diff --git a/rust/cloud-storage/channels/src/domain/service/test.rs b/rust/cloud-storage/channels/src/domain/service/test.rs
index daa3803d87..b57bff6336 100644
--- a/rust/cloud-storage/channels/src/domain/service/test.rs
+++ b/rust/cloud-storage/channels/src/domain/service/test.rs
@@ -232,6 +232,7 @@ fn center_window_balanced() {
let result = center_window(before.clone(), anchor.clone(), after.clone(), 7);
assert_eq!(result.len(), 7);
+ assert!(result.has_more_newer);
// First 3 are from after (reversed = newest-first), then anchor, then 3 from before
assert_eq!(result[0].id, after[2].id);
assert_eq!(result[1].id, after[1].id);
@@ -251,6 +252,7 @@ fn center_window_near_oldest_edge() {
let result = center_window(before.clone(), anchor.clone(), after.clone(), 7);
assert_eq!(result.len(), 7);
+ assert!(result.has_more_newer);
assert_eq!(result[5].id, anchor.id);
assert_eq!(result[6].id, before[0].id);
// First 5 are after (reversed)
@@ -268,6 +270,7 @@ fn center_window_near_newest_edge() {
let result = center_window(before.clone(), anchor.clone(), after.clone(), 7);
assert_eq!(result.len(), 7);
+ assert!(!result.has_more_newer);
assert_eq!(result[0].id, after[0].id);
assert_eq!(result[1].id, anchor.id);
for i in 0..5 {
@@ -284,6 +287,7 @@ fn center_window_small_channel() {
let result = center_window(before.clone(), anchor.clone(), after.clone(), 10);
assert_eq!(result.len(), 4);
+ assert!(!result.has_more_newer);
assert_eq!(result[0].id, after[0].id);
assert_eq!(result[1].id, anchor.id);
assert_eq!(result[2].id, before[0].id);
@@ -298,6 +302,7 @@ fn center_window_limit_one() {
let result = center_window(before, anchor.clone(), after, 1);
assert_eq!(result.len(), 1);
+ assert!(result.has_more_newer);
assert_eq!(result[0].id, anchor.id);
}
@@ -350,11 +355,13 @@ async fn around_resolves_and_hydrates() {
.returning(|_| Box::pin(async { Ok(HashMap::new()) }));
let svc = ChannelMessagesServiceImpl::new(repo);
- let page = svc
+ let result = svc
.get_channel_messages_around(Uuid::nil(), anchor.id, 50)
.await
.unwrap();
+ let page = result.page;
+ assert!(!result.has_more_newer);
assert_eq!(page.items.len(), 3);
// DESC order: after, anchor, before
assert_eq!(page.items[0].id, after_row.id);
diff --git a/rust/cloud-storage/channels/src/inbound/axum_router.rs b/rust/cloud-storage/channels/src/inbound/axum_router.rs
index 8e09015c45..4e5f47bcfc 100644
--- a/rust/cloud-storage/channels/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/channels/src/inbound/axum_router.rs
@@ -273,11 +273,14 @@ async fn channel_messages_response<S: ChannelMessagesService, Svc>(
let (page, has_more_newer) = match params.load_around_message_id {
Some(message_id) => {
- let page = state
+ let ChannelMessagesQueryResult {
+ page,
+ has_more_newer,
+ } = state
.service
.get_channel_messages_around(channel_id, message_id, limit)
.await?;
- (page, false)
+ (page, has_more_newer)
}
None => {
let ChannelMessagesQueryResult {
@@ -291,21 +294,18 @@ async fn channel_messages_response<S: ChannelMessagesService, Svc>(
}
};
- let can_emit_previous = has_cursor || params.load_around_message_id.is_some();
- let previous_cursor = if !can_emit_previous {
- None
+ let has_newer_page = match params.load_around_message_id {
+ Some(_) => has_more_newer,
+ None => match direction {
+ MessagePageDirection::Older => has_cursor,
+ MessagePageDirection::Newer => has_more_newer,
+ },
+ };
+ let previous_cursor = if has_newer_page {
+ cursor_from_first_message(&page, limit)
+ .map(|first_cursor| Base64Str::encode_json(first_cursor).type_erase())
} else {
- match cursor_from_first_message(&page, limit) {
- Some(first_cursor) => {
- let has_previous = match direction {
- MessagePageDirection::Older => true,
- MessagePageDirection::Newer => has_more_newer,
- };
-
- has_previous.then(|| Base64Str::encode_json(first_cursor).type_erase())
- }
- None => None,
- }
+ None
};
let page = page.type_erase().map(ApiChannelMessage::from);
diff --git a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs b/rust/cloud-storage/channels/src/inbound/axum_router/test.rs
index 63296ed20b..c12bca809b 100644
--- a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs
+++ b/rust/cloud-storage/channels/src/inbound/axum_router/test.rs
@@ -4,8 +4,7 @@ use crate::domain::models::{
MessagePageDirection, ParticipantRole,
};
use crate::domain::ports::{
- ChannelAttachmentsPage, ChannelMessagesErr, ChannelMessagesPage, ChannelMessagesQueryResult,
- ChannelMessagesService,
+ ChannelAttachmentsPage, ChannelMessagesErr, ChannelMessagesQueryResult, ChannelMessagesService,
};
use axum::{
Extension, Router,
@@ -209,12 +208,15 @@ impl ChannelMessagesService for MockService {
_channel_id: Uuid,
_message_id: Uuid,
_limit: u16,
- ) -> Result<ChannelMessagesPage, ChannelMessagesErr> {
- Ok(Vec::<ChannelMessage>::new()
- .into_iter()
- .paginate_on(50, CreatedAt)
- .filter_on(())
- .into_page())
+ ) -> Result<ChannelMessagesQueryResult, ChannelMessagesErr> {
+ Ok(ChannelMessagesQueryResult {
+ page: Vec::<ChannelMessage>::new()
+ .into_iter()
+ .paginate_on(50, CreatedAt)
+ .filter_on(())
+ .into_page(),
+ has_more_newer: false,
+ })
}
async fn get_thread_replies(
@@ -261,7 +263,7 @@ impl ChannelMessagesService for ErrorService {
_channel_id: Uuid,
_message_id: Uuid,
_limit: u16,
- ) -> Result<ChannelMessagesPage, ChannelMessagesErr> {
+ ) -> Result<ChannelMessagesQueryResult, ChannelMessagesErr> {
Err(ChannelMessagesErr::Repo(anyhow::anyhow!("database error")))
}
@@ -335,12 +337,15 @@ impl ChannelMessagesService for ParticipantsService {
_channel_id: Uuid,
_message_id: Uuid,
_limit: u16,
- ) -> Result<ChannelMessagesPage, ChannelMessagesErr> {
- Ok(Vec::<ChannelMessage>::new()
- .into_iter()
- .paginate_on(50, CreatedAt)
- .filter_on(())
- .into_page())
+ ) -> Result<ChannelMessagesQueryResult, ChannelMessagesErr> {
+ Ok(ChannelMessagesQueryResult {
+ page: Vec::<ChannelMessage>::new()
+ .into_iter()
+ .paginate_on(50, CreatedAt)
+ .filter_on(())
+ .into_page(),
+ has_more_newer: false,
+ })
}
async fn get_thread_replies(
@@ -619,7 +624,7 @@ impl ChannelMessagesService for NotFoundService {
_channel_id: Uuid,
message_id: Uuid,
_limit: u16,
- ) -> Result<ChannelMessagesPage, ChannelMessagesErr> {
+ ) -> Result<ChannelMessagesQueryResult, ChannelMessagesErr> {
Err(ChannelMessagesErr::MessageNotFound(message_id))
}
@@ -632,7 +637,9 @@ impl ChannelMessagesService for NotFoundService {
}
}
-struct AroundHasItemsService;
+struct AroundHasItemsService {
+ has_more_newer: bool,
+}
impl ChannelMessagesService for AroundHasItemsService {
async fn get_channel_messages(
@@ -678,7 +685,7 @@ impl ChannelMessagesService for AroundHasItemsService {
channel_id: Uuid,
_message_id: Uuid,
limit: u16,
- ) -> Result<ChannelMessagesPage, ChannelMessagesErr> {
+ ) -> Result<ChannelMessagesQueryResult, ChannelMessagesErr> {
let now = chrono::Utc::now();
let message = ChannelMessage {
id: Uuid::new_v4(),
@@ -698,11 +705,14 @@ impl ChannelMessagesService for AroundHasItemsService {
attachments: vec![],
};
- Ok(vec![message]
- .into_iter()
- .paginate_on(usize::from(limit), CreatedAt)
- .filter_on(())
- .into_page())
+ Ok(ChannelMessagesQueryResult {
+ page: vec![message]
+ .into_iter()
+ .paginate_on(usize::from(limit), CreatedAt)
+ .filter_on(())
+ .into_page(),
+ has_more_newer: self.has_more_newer,
+ })
}
async fn get_thread_replies(
@@ -736,9 +746,38 @@ async fn messages_around_returns_empty_page() {
}
#[tokio::test]
-async fn messages_around_returns_previous_cursor_when_items_present() {
+async fn messages_around_omits_previous_cursor_when_no_newer_page() {
let router = channels_router(ChannelsRouterState::new(
- AroundHasItemsService,
+ AroundHasItemsService {
+ has_more_newer: false,
+ },
+ TestAccessService::allow(),
+ ))
+ .layer(user_extension());
+ let channel_id = Uuid::new_v4();
+ let message_id = Uuid::new_v4();
+ let request = Request::builder()
+ .uri(format!(
+ "/{channel_id}/messages?load_around_message_id={message_id}"
+ ))
+ .body(axum::body::Body::empty())
+ .unwrap();
+
+ let res = router.oneshot(request).await.unwrap();
+ assert_eq!(res.status(), StatusCode::OK);
+
+ let bytes = res.into_body().collect().await.unwrap().to_bytes();
+ let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
+ assert_eq!(json["items"].as_array().unwrap().len(), 1);
+ assert!(json["previous_cursor"].is_null());
+}
+
+#[tokio::test]
+async fn messages_around_returns_previous_cursor_when_newer_page_exists() {
+ let router = channels_router(ChannelsRouterState::new(
+ AroundHasItemsService {
+ has_more_newer: true,
+ },
TestAccessService::allow(),
))
.layer(user_extension());
@@ -843,12 +882,15 @@ impl ChannelMessagesService for std::sync::Arc<CapturingService> {
_channel_id: Uuid,
_message_id: Uuid,
_limit: u16,
- ) -> Result<ChannelMessagesPage, ChannelMessagesErr> {
- Ok(Vec::<ChannelMessage>::new()
- .into_iter()
- .paginate_on(50, CreatedAt)
- .filter_on(())
- .into_page())
+ ) -> Result<ChannelMessagesQueryResult, ChannelMessagesErr> {
+ Ok(ChannelMessagesQueryResult {
+ page: Vec::<ChannelMessage>::new()
+ .into_iter()
+ .paginate_on(50, CreatedAt)
+ .filter_on(())
+ .into_page(),
+ has_more_newer: false,
+ })
}
async fn get_thread_replies(