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.

feat(channels): bidirectional cursor for message pagination (#1603)

teo697f13b66289
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelMessagesPage.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelMessagesPage.ts
index f5dfd702fc..547feecdd9 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelMessagesPage.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelMessagesPage.ts
@@ -6,6 +6,7 @@
*/
import type { ApiChannelMessage } from './apiChannelMessage';
import type { ApiChannelMessagesPageNextCursor } from './apiChannelMessagesPageNextCursor';
+import type { ApiChannelMessagesPagePreviousCursor } from './apiChannelMessagesPagePreviousCursor';
/**
* Paginated response of channel messages.
@@ -15,4 +16,6 @@ export interface ApiChannelMessagesPage {
items: ApiChannelMessage[];
/** Cursor for the next page, null if no more pages. */
next_cursor?: ApiChannelMessagesPageNextCursor;
+ /** Cursor for the previous page, null if no newer page exists. */
+ previous_cursor?: ApiChannelMessagesPagePreviousCursor;
}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelMessagesPagePreviousCursor.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelMessagesPagePreviousCursor.ts
new file mode 100644
index 0000000000..c57cb23854
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelMessagesPagePreviousCursor.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Cursor for the previous page, null if no newer page exists.
+ */
+export type ApiChannelMessagesPagePreviousCursor = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/getChannelMessagesParams.ts b/js/app/packages/service-clients/service-storage/generated/schemas/getChannelMessagesParams.ts
index 777bb8f13c..9f381c5a90 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/getChannelMessagesParams.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/getChannelMessagesParams.ts
@@ -12,9 +12,13 @@ export type GetChannelMessagesParams = {
*/
limit?: number;
/**
- * Base64 encoded cursor value
+ * Base64 encoded cursor value for older messages
*/
cursor?: string;
+ /**
+ * Base64 encoded cursor value for newer messages
+ */
+ previous_cursor?: string;
/**
* Return a centered window around this message ID
*/
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
index 19d020d6f1..c841d0228b 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
@@ -49,6 +49,7 @@ export * from './apiChannelMessageDeletedAt';
export * from './apiChannelMessageEditedAt';
export * from './apiChannelMessagesPage';
export * from './apiChannelMessagesPageNextCursor';
+export * from './apiChannelMessagesPagePreviousCursor';
export * from './apiChannelParticipant';
export * from './apiCountedReaction';
export * from './apiMessageAttachment';
diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.ts
index 907dddbe1b..13a289b31d 100644
--- a/js/app/packages/service-clients/service-storage/generated/zod.ts
+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts
@@ -874,7 +874,14 @@ export const getChannelMessagesQueryParams = zod.object({
.min(getChannelMessagesQueryLimitMin)
.optional()
.describe('Page size (1-100, default 50)'),
- cursor: zod.string().optional().describe('Base64 encoded cursor value'),
+ cursor: zod
+ .string()
+ .optional()
+ .describe('Base64 encoded cursor value for older messages'),
+ previous_cursor: zod
+ .string()
+ .optional()
+ .describe('Base64 encoded cursor value for newer messages'),
load_around_message_id: zod
.string()
.uuid()
@@ -1015,6 +1022,10 @@ export const getChannelMessagesResponse = zod
.string()
.nullish()
.describe('Cursor for the next page, null if no more pages.'),
+ previous_cursor: zod
+ .string()
+ .nullish()
+ .describe('Cursor for the previous page, null if no newer page exists.'),
})
.describe('Paginated response of channel messages.');
diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.json
index cff9924092..1d787b79f8 100644
--- a/js/app/packages/service-clients/service-storage/openapi.json
+++ b/js/app/packages/service-clients/service-storage/openapi.json
@@ -689,7 +689,16 @@
{
"name": "cursor",
"in": "query",
- "description": "Base64 encoded cursor value",
+ "description": "Base64 encoded cursor value for older messages",
+ "required": false,
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "previous_cursor",
+ "in": "query",
+ "description": "Base64 encoded cursor value for newer messages",
"required": false,
"schema": {
"type": "string"
@@ -717,6 +726,16 @@
}
}
},
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"404": {
"description": "",
"content": {
@@ -4948,6 +4967,10 @@
"next_cursor": {
"type": ["string", "null"],
"description": "Cursor for the next page, null if no more pages."
+ },
+ "previous_cursor": {
+ "type": ["string", "null"],
+ "description": "Cursor for the previous page, null if no newer page exists."
}
}
},
diff --git a/rust/cloud-storage/channels/.sqlx/query-e370c8ac63367ff5f64f67376057512c24bd0ff50a8cd514f9c806620dc08d0d.json b/rust/cloud-storage/channels/.sqlx/query-e370c8ac63367ff5f64f67376057512c24bd0ff50a8cd514f9c806620dc08d0d.json
new file mode 100644
index 0000000000..60ced823ee
--- /dev/null
+++ b/rust/cloud-storage/channels/.sqlx/query-e370c8ac63367ff5f64f67376057512c24bd0ff50a8cd514f9c806620dc08d0d.json
@@ -0,0 +1,67 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n m.id,\n m.channel_id,\n m.sender_id,\n m.content,\n m.created_at,\n m.updated_at,\n m.edited_at::timestamptz AS \"edited_at?\",\n m.deleted_at::timestamptz AS \"deleted_at?\"\n FROM comms_messages m\n WHERE m.channel_id = $1\n AND m.thread_id IS NULL\n AND (m.deleted_at IS NULL OR EXISTS (\n SELECT 1 FROM comms_messages r\n WHERE r.thread_id = m.id AND r.deleted_at IS NULL\n ))\n AND ($2::timestamptz IS NOT NULL AND (m.created_at, m.id) > ($2, $3))\n ORDER BY m.created_at ASC, m.id ASC\n LIMIT $4\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "channel_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "sender_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "content",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "edited_at?",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "deleted_at?",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Timestamptz",
+ "Uuid",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ null,
+ null
+ ]
+ },
+ "hash": "e370c8ac63367ff5f64f67376057512c24bd0ff50a8cd514f9c806620dc08d0d"
+}
diff --git a/rust/cloud-storage/channels/.sqlx/query-54732f9baff7727d260859089cdd11700b9918470e0967a347a7687944fcb1e4.json b/rust/cloud-storage/channels/.sqlx/query-f5bbf9adae5783fab3e4ab384c5232bb49f8f0323f5a117f2cc8421e143ae797.json
similarity index 51%
rename from rust/cloud-storage/channels/.sqlx/query-54732f9baff7727d260859089cdd11700b9918470e0967a347a7687944fcb1e4.json
rename to rust/cloud-storage/channels/.sqlx/query-f5bbf9adae5783fab3e4ab384c5232bb49f8f0323f5a117f2cc8421e143ae797.json
index 957b640651..195ba1d6fc 100644
--- a/rust/cloud-storage/channels/.sqlx/query-54732f9baff7727d260859089cdd11700b9918470e0967a347a7687944fcb1e4.json
+++ b/rust/cloud-storage/channels/.sqlx/query-f5bbf9adae5783fab3e4ab384c5232bb49f8f0323f5a117f2cc8421e143ae797.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n m.id,\n m.channel_id,\n m.sender_id,\n m.content,\n m.created_at,\n m.updated_at,\n m.edited_at::timestamptz AS \"edited_at?\",\n m.deleted_at::timestamptz AS \"deleted_at?\"\n FROM comms_messages m\n WHERE m.channel_id = $1\n AND m.thread_id IS NULL\n AND (m.deleted_at IS NULL OR EXISTS (\n SELECT 1 FROM comms_messages r\n WHERE r.thread_id = m.id AND r.deleted_at IS NULL\n ))\n AND ($2::timestamptz IS NULL OR (m.created_at, m.id) < ($2, $3))\n ORDER BY m.created_at DESC, m.id DESC\n LIMIT $4\n ",
+ "query": "\n SELECT\n m.id,\n m.channel_id,\n m.sender_id,\n m.content,\n m.created_at,\n m.updated_at,\n m.edited_at::timestamptz AS \"edited_at?\",\n m.deleted_at::timestamptz AS \"deleted_at?\"\n FROM comms_messages m\n WHERE m.channel_id = $1\n AND m.thread_id IS NULL\n AND (m.deleted_at IS NULL OR EXISTS (\n SELECT 1 FROM comms_messages r\n WHERE r.thread_id = m.id AND r.deleted_at IS NULL\n ))\n AND ($2::timestamptz IS NULL OR (m.created_at, m.id) < ($2, $3))\n ORDER BY m.created_at DESC, m.id DESC\n LIMIT $4\n ",
"describe": {
"columns": [
{
@@ -63,5 +63,5 @@
null
]
},
- "hash": "54732f9baff7727d260859089cdd11700b9918470e0967a347a7687944fcb1e4"
+ "hash": "f5bbf9adae5783fab3e4ab384c5232bb49f8f0323f5a117f2cc8421e143ae797"
}
diff --git a/rust/cloud-storage/channels/src/domain/models.rs b/rust/cloud-storage/channels/src/domain/models.rs
index 83f4626b65..dc6a77ff89 100644
--- a/rust/cloud-storage/channels/src/domain/models.rs
+++ b/rust/cloud-storage/channels/src/domain/models.rs
@@ -11,6 +11,15 @@ pub struct GetChannelMessagesRequest {
pub limit: u16,
}
+/// Direction for cursor-based message pagination.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum MessagePageDirection {
+ /// Fetch older messages than the cursor.
+ Older,
+ /// Fetch newer messages than the cursor.
+ Newer,
+}
+
/// A top-level message with thread info, reactions, and attachments.
#[derive(Debug)]
pub struct ChannelMessage {
diff --git a/rust/cloud-storage/channels/src/domain/ports.rs b/rust/cloud-storage/channels/src/domain/ports.rs
index 67657658c7..7e13f1b52e 100644
--- a/rust/cloud-storage/channels/src/domain/ports.rs
+++ b/rust/cloud-storage/channels/src/domain/ports.rs
@@ -1,6 +1,6 @@
use crate::domain::models::{
- ChannelAttachment, ChannelParticipant, CountedReaction, MessageAttachment, ThreadData,
- TopLevelMessageRow,
+ ChannelAttachment, ChannelParticipant, CountedReaction, MessageAttachment,
+ MessagePageDirection, ThreadData, TopLevelMessageRow,
};
use chrono::{DateTime, Utc};
use models_pagination::{CreatedAt, Query};
@@ -18,8 +18,9 @@ pub trait ChannelMessagesRepo: Send + Sync + 'static {
&self,
channel_id: Uuid,
query: &Query<Uuid, CreatedAt, ()>,
+ direction: MessagePageDirection,
limit: u16,
- ) -> impl Future<Output = Result<Vec<TopLevelMessageRow>, Self::Err>> + Send;
+ ) -> impl Future<Output = Result<TopLevelMessagesQueryResult, Self::Err>> + Send;
/// Batch-fetch thread data (stats + preview replies) for parent messages in a single query.
fn get_thread_data(
@@ -80,8 +81,9 @@ pub trait ChannelMessagesService: Send + Sync + 'static {
&self,
channel_id: Uuid,
query: Query<Uuid, CreatedAt, ()>,
+ direction: MessagePageDirection,
limit: u16,
- ) -> impl Future<Output = Result<ChannelMessagesPage, ChannelMessagesErr>> + Send;
+ ) -> impl Future<Output = Result<ChannelMessagesQueryResult, ChannelMessagesErr>> + Send;
/// Fetch a paginated page of channel-level attachments.
fn get_channel_attachments(
@@ -120,6 +122,22 @@ pub trait ChannelAccessCheck: Send + Sync + 'static {
pub type ChannelMessagesPage =
models_pagination::PaginatedCursor<super::models::ChannelMessage, Uuid, CreatedAt, ()>;
+/// Result for a cursor-paginated channel messages query.
+pub struct ChannelMessagesQueryResult {
+ /// The page of messages.
+ pub page: ChannelMessagesPage,
+ /// Whether at least one newer message exists before the first item of this page.
+ pub has_more_newer: bool,
+}
+
+/// Result from fetching top-level message rows for pagination.
+pub struct TopLevelMessagesQueryResult {
+ /// Message rows for the requested direction.
+ pub rows: Vec<TopLevelMessageRow>,
+ /// Whether at least one newer message exists before the first returned row.
+ pub has_more_newer: bool,
+}
+
/// A paginated page of channel attachments.
pub type ChannelAttachmentsPage =
models_pagination::PaginatedCursor<ChannelAttachment, Uuid, CreatedAt, ()>;
diff --git a/rust/cloud-storage/channels/src/domain/service.rs b/rust/cloud-storage/channels/src/domain/service.rs
index 6d52ac6c52..9fb1e06a61 100644
--- a/rust/cloud-storage/channels/src/domain/service.rs
+++ b/rust/cloud-storage/channels/src/domain/service.rs
@@ -1,8 +1,11 @@
use crate::domain::{
- models::{ChannelMessage, ChannelParticipant, ThreadInfo, ThreadReply, TopLevelMessageRow},
+ models::{
+ ChannelMessage, ChannelParticipant, MessagePageDirection, ThreadInfo, ThreadReply,
+ TopLevelMessageRow,
+ },
ports::{
- ChannelAttachmentsPage, ChannelMessagesErr, ChannelMessagesPage, ChannelMessagesRepo,
- ChannelMessagesService,
+ ChannelAttachmentsPage, ChannelMessagesErr, ChannelMessagesPage,
+ ChannelMessagesQueryResult, ChannelMessagesRepo, ChannelMessagesService,
},
};
use models_pagination::{CreatedAt, PaginateOn, Query};
@@ -156,17 +159,18 @@ where
&self,
channel_id: Uuid,
query: Query<Uuid, CreatedAt, ()>,
+ direction: MessagePageDirection,
limit: u16,
- ) -> Result<ChannelMessagesPage, ChannelMessagesErr> {
+ ) -> Result<ChannelMessagesQueryResult, ChannelMessagesErr> {
let limit = limit.clamp(1, 100);
- let rows = self
+ let rows_result = self
.repo
- .get_top_level_messages(channel_id, &query, limit)
+ .get_top_level_messages(channel_id, &query, direction, limit)
.await
.map_err(anyhow::Error::from)?;
- let messages = self.hydrate_messages(rows).await?;
+ let messages = self.hydrate_messages(rows_result.rows).await?;
let page = messages
.into_iter()
@@ -174,7 +178,10 @@ where
.filter_on(())
.into_page();
- Ok(page)
+ Ok(ChannelMessagesQueryResult {
+ page,
+ has_more_newer: rows_result.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 c87d1434b4..62b950699b 100644
--- a/rust/cloud-storage/channels/src/domain/service/test.rs
+++ b/rust/cloud-storage/channels/src/domain/service/test.rs
@@ -1,7 +1,10 @@
use super::*;
use crate::domain::{
- models::{CountedReaction, MessageAttachment, ThreadData, ThreadReplyRow, TopLevelMessageRow},
- ports::MockChannelMessagesRepo,
+ models::{
+ CountedReaction, MessageAttachment, MessagePageDirection, ThreadData, ThreadReplyRow,
+ TopLevelMessageRow,
+ },
+ ports::{MockChannelMessagesRepo, TopLevelMessagesQueryResult},
};
use chrono::Utc;
use std::collections::HashMap;
@@ -23,7 +26,14 @@ fn make_row(id: Uuid, minutes_ago: i64) -> TopLevelMessageRow {
fn empty_repo() -> MockChannelMessagesRepo {
let mut repo = MockChannelMessagesRepo::new();
repo.expect_get_top_level_messages()
- .returning(|_, _, _| Box::pin(async { Ok(vec![]) }));
+ .returning(|_, _, _, _| {
+ Box::pin(async {
+ Ok(TopLevelMessagesQueryResult {
+ rows: vec![],
+ has_more_newer: false,
+ })
+ })
+ });
repo.expect_get_thread_data()
.returning(|_, _| Box::pin(async { Ok(HashMap::new()) }));
repo.expect_get_reactions_batch()
@@ -44,10 +54,16 @@ fn empty_repo() -> MockChannelMessagesRepo {
#[tokio::test]
async fn returns_empty_page_for_no_messages() {
let svc = ChannelMessagesServiceImpl::new(empty_repo());
- let page = svc
- .get_channel_messages(Uuid::nil(), Query::Sort(CreatedAt, ()), 50)
+ let result = svc
+ .get_channel_messages(
+ Uuid::nil(),
+ Query::Sort(CreatedAt, ()),
+ MessagePageDirection::Older,
+ 50,
+ )
.await
.unwrap();
+ let page = result.page;
assert!(page.items.is_empty());
assert!(page.next_cursor.is_none());
@@ -74,9 +90,14 @@ async fn returns_messages_with_thread_info() {
let row_clone = row.clone();
repo.expect_get_top_level_messages()
- .returning(move |_, _, _| {
+ .returning(move |_, _, _, _| {
let r = row_clone.clone();
- Box::pin(async move { Ok(vec![r]) })
+ Box::pin(async move {
+ Ok(TopLevelMessagesQueryResult {
+ rows: vec![r],
+ has_more_newer: false,
+ })
+ })
});
let reply_clone = reply_row.clone();
@@ -118,10 +139,16 @@ async fn returns_messages_with_thread_info() {
});
let svc = ChannelMessagesServiceImpl::new(repo);
- let page = svc
- .get_channel_messages(Uuid::nil(), Query::Sort(CreatedAt, ()), 50)
+ let result = svc
+ .get_channel_messages(
+ Uuid::nil(),
+ Query::Sort(CreatedAt, ()),
+ MessagePageDirection::Older,
+ 50,
+ )
.await
.unwrap();
+ let page = result.page;
assert_eq!(page.items.len(), 1);
let msg = &page.items[0];
@@ -136,8 +163,15 @@ async fn returns_messages_with_thread_info() {
async fn clamps_limit() {
let mut repo = MockChannelMessagesRepo::new();
repo.expect_get_top_level_messages()
- .withf(|_, _, limit| *limit == 100)
- .returning(|_, _, _| Box::pin(async { Ok(vec![]) }));
+ .withf(|_, _, _, limit| *limit == 100)
+ .returning(|_, _, _, _| {
+ Box::pin(async {
+ Ok(TopLevelMessagesQueryResult {
+ rows: vec![],
+ has_more_newer: false,
+ })
+ })
+ });
repo.expect_get_thread_data()
.returning(|_, _| Box::pin(async { Ok(HashMap::new()) }));
repo.expect_get_reactions_batch()
@@ -146,10 +180,16 @@ async fn clamps_limit() {
.returning(|_| Box::pin(async { Ok(HashMap::new()) }));
let svc = ChannelMessagesServiceImpl::new(repo);
- let page = svc
- .get_channel_messages(Uuid::nil(), Query::Sort(CreatedAt, ()), 200)
+ let result = svc
+ .get_channel_messages(
+ Uuid::nil(),
+ Query::Sort(CreatedAt, ()),
+ MessagePageDirection::Older,
+ 200,
+ )
.await
.unwrap();
+ let page = result.page;
assert!(page.items.is_empty());
}
diff --git a/rust/cloud-storage/channels/src/inbound/axum_router.rs b/rust/cloud-storage/channels/src/inbound/axum_router.rs
index 32b51e714d..d8b661a097 100644
--- a/rust/cloud-storage/channels/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/channels/src/inbound/axum_router.rs
@@ -3,9 +3,12 @@ mod test;
use crate::domain::models::{
ChannelAttachment, ChannelMessage, ChannelParticipant, CountedReaction, MessageAttachment,
- ParticipantRole, ThreadInfo, ThreadReply,
+ MessagePageDirection, ParticipantRole, ThreadInfo, ThreadReply,
+};
+use crate::domain::ports::{
+ ChannelAccessCheck, ChannelMessagesErr, ChannelMessagesPage, ChannelMessagesQueryResult,
+ ChannelMessagesService,
};
-use crate::domain::ports::{ChannelAccessCheck, ChannelMessagesErr, ChannelMessagesService};
use axum::{
Json, Router,
extract::{FromRequestParts, Path, Query, State},
@@ -16,7 +19,10 @@ use axum::{
use chrono::{DateTime, Utc};
use model_error_response::ErrorResponse;
use model_user::axum_extractor::MacroUserExtractor;
-use models_pagination::{CreatedAt, CursorExtractor, PaginatedOpaqueCursor, TypeEraseCursor};
+use models_pagination::{
+ Base64Str, BidirectionalCursor, BidirectionalCursorExtractor, CreatedAt, Cursor,
+ CursorExtractor, CursorVal, PaginatedOpaqueCursor, Query as PaginationQuery, TypeEraseCursor,
+};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use uuid::Uuid;
@@ -127,6 +133,47 @@ pub struct Params {
load_around_message_id: Option<Uuid>,
}
+fn parse_messages_query(
+ cursor: BidirectionalCursorExtractor<Uuid, CreatedAt, ()>,
+) -> (
+ PaginationQuery<Uuid, CreatedAt, ()>,
+ MessagePageDirection,
+ bool,
+) {
+ match cursor {
+ BidirectionalCursorExtractor::Some(BidirectionalCursor::Next(cursor)) => (
+ PaginationQuery::Cursor(cursor),
+ MessagePageDirection::Older,
+ true,
+ ),
+ BidirectionalCursorExtractor::Some(BidirectionalCursor::Previous(cursor)) => (
+ PaginationQuery::Cursor(cursor),
+ MessagePageDirection::Newer,
+ true,
+ ),
+ BidirectionalCursorExtractor::None => (
+ PaginationQuery::Sort(CreatedAt, ()),
+ MessagePageDirection::Older,
+ false,
+ ),
+ }
+}
+
+fn cursor_from_first_message(
+ page: &ChannelMessagesPage,
+ limit: u16,
+) -> Option<Cursor<Uuid, CursorVal<CreatedAt>, ()>> {
+ page.items.first().map(|first| Cursor {
+ id: first.id,
+ limit: usize::from(limit),
+ val: CursorVal {
+ sort_type: CreatedAt,
+ last_val: first.created_at,
+ },
+ filter: (),
+ })
+}
+
/// Create the channels router.
pub fn channels_router<S, A, T>(state: ChannelsRouterState<S, A>) -> Router<T>
where
@@ -158,11 +205,13 @@ where
params(
("channel_id" = Uuid, Path, description = "Channel ID"),
("limit" = Option<u16>, Query, description = "Page size (1-100, default 50)"),
- ("cursor" = Option<String>, Query, description = "Base64 encoded cursor value"),
+ ("cursor" = Option<String>, Query, description = "Base64 encoded cursor value for older messages"),
+ ("previous_cursor" = Option<String>, Query, description = "Base64 encoded cursor value for newer messages"),
("load_around_message_id" = Option<Uuid>, Query, description = "Return a centered window around this message ID"),
),
responses(
(status = 200, body = ApiChannelMessagesPage),
+ (status = 400, body = ErrorResponse),
(status = 404, body = ErrorResponse),
(status = 500, body = ErrorResponse),
)
@@ -172,27 +221,53 @@ pub async fn get_channel_messages_handler<S: ChannelMessagesService, A: ChannelA
State(state): State<ChannelsRouterState<S, A>>,
member: ChannelMember,
Query(params): Query<Params>,
- cursor: CursorExtractor<Uuid, CreatedAt, ()>,
-) -> Result<Json<PaginatedOpaqueCursor<ApiChannelMessage>>, ChannelsHandlerErr> {
- let limit = params.limit.unwrap_or(50);
+ cursor: BidirectionalCursorExtractor<Uuid, CreatedAt, ()>,
+) -> Result<Json<ApiChannelMessagesPage>, ChannelsHandlerErr> {
+ let limit = params.limit.unwrap_or(50).clamp(1, 100);
+ let (query, direction, has_cursor) = parse_messages_query(cursor);
- let page = match params.load_around_message_id {
+ let (page, has_more_newer) = match params.load_around_message_id {
Some(message_id) => {
- state
+ let page = state
.service
.get_channel_messages_around(member.channel_id, message_id, limit)
- .await?
+ .await?;
+ (page, false)
}
None => {
- let query = cursor.into_query(CreatedAt, ());
- state
+ let ChannelMessagesQueryResult {
+ page,
+ has_more_newer,
+ } = state
.service
- .get_channel_messages(member.channel_id, query, limit)
- .await?
+ .get_channel_messages(member.channel_id, query, direction, limit)
+ .await?;
+ (page, has_more_newer)
}
};
- Ok(Json(page.type_erase().map(ApiChannelMessage::from)))
+ let previous_cursor = if params.load_around_message_id.is_some() || !has_cursor {
+ None
+ } 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,
+ }
+ };
+
+ let page = page.type_erase().map(ApiChannelMessage::from);
+ Ok(Json(ApiChannelMessagesPage {
+ items: page.items,
+ next_cursor: page.next_cursor,
+ previous_cursor,
+ }))
}
/// Handler for `GET /channels/:channel_id/attachments`.
@@ -266,6 +341,8 @@ pub struct ApiChannelMessagesPage {
items: Vec<ApiChannelMessage>,
/// Cursor for the next page, null if no more pages.
next_cursor: Option<String>,
+ /// Cursor for the previous page, null if no newer page exists.
+ previous_cursor: Option<String>,
}
/// A top-level channel message with thread info.
@@ -522,6 +599,9 @@ impl From<ChannelParticipant> for ApiChannelParticipant {
/// Errors from the channels handler.
#[derive(Debug, thiserror::Error)]
pub enum ChannelsHandlerErr {
+ /// Bad request.
+ #[error("{0}")]
+ BadRequest(&'static str),
/// Internal server error.
#[error("An internal server error occurred")]
Internal(#[from] ChannelMessagesErr),
@@ -529,28 +609,32 @@ pub enum ChannelsHandlerErr {
impl IntoResponse for ChannelsHandlerErr {
fn into_response(self) -> axum::response::Response {
- let ChannelsHandlerErr::Internal(ref err) = self;
- match err {
- ChannelMessagesErr::MessageNotFound(id) => {
- tracing::warn!(message_id=?id, "message not found");
- (
- StatusCode::NOT_FOUND,
- Json(ErrorResponse {
- message: "Message not found",
- }),
- )
- .into_response()
- }
- ChannelMessagesErr::Repo(_) => {
- tracing::error!(error=?self, "channels handler error");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "An internal server error occurred",
- }),
- )
- .into_response()
+ match self {
+ ChannelsHandlerErr::BadRequest(message) => {
+ (StatusCode::BAD_REQUEST, Json(ErrorResponse { message })).into_response()
}
+ ChannelsHandlerErr::Internal(err) => match err {
+ ChannelMessagesErr::MessageNotFound(id) => {
+ tracing::warn!(message_id=?id, "message not found");
+ (
+ StatusCode::NOT_FOUND,
+ Json(ErrorResponse {
+ message: "Message not found",
+ }),
+ )
+ .into_response()
+ }
+ ChannelMessagesErr::Repo(repo_err) => {
+ tracing::error!(error=?repo_err, "channels handler error");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ErrorResponse {
+ message: "An internal server error occurred",
+ }),
+ )
+ .into_response()
+ }
+ },
}
}
}
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 bae6a1acf3..b3d38e8a45 100644
--- a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs
+++ b/rust/cloud-storage/channels/src/inbound/axum_router/test.rs
@@ -1,10 +1,10 @@
use super::*;
use crate::domain::models::{
- ChannelAttachment, ChannelMessage, ChannelParticipant, ParticipantRole,
+ ChannelAttachment, ChannelMessage, ChannelParticipant, MessagePageDirection, ParticipantRole,
};
use crate::domain::ports::{
ChannelAccessCheck, ChannelAttachmentsPage, ChannelMessagesErr, ChannelMessagesPage,
- ChannelMessagesService,
+ ChannelMessagesQueryResult, ChannelMessagesService,
};
use axum::{
Extension, Router,
@@ -12,7 +12,7 @@ use axum::{
};
use http_body_util::BodyExt;
use model_user::UserContext;
-use models_pagination::{CreatedAt, PaginateOn, Query};
+use models_pagination::{Base64Str, CreatedAt, Cursor, CursorVal, PaginateOn, Query};
use tower::util::ServiceExt;
// --- Access check implementations for tests ---
@@ -50,13 +50,17 @@ impl ChannelMessagesService for MockService {
&self,
_channel_id: Uuid,
_query: Query<Uuid, CreatedAt, ()>,
+ _direction: MessagePageDirection,
_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_channel_attachments(
@@ -100,8 +104,9 @@ impl ChannelMessagesService for ErrorService {
&self,
_channel_id: Uuid,
_query: Query<Uuid, CreatedAt, ()>,
+ _direction: MessagePageDirection,
_limit: u16,
- ) -> Result<ChannelMessagesPage, ChannelMessagesErr> {
+ ) -> Result<ChannelMessagesQueryResult, ChannelMessagesErr> {
Err(ChannelMessagesErr::Repo(anyhow::anyhow!("database error")))
}
@@ -138,13 +143,17 @@ impl ChannelMessagesService for ParticipantsService {
&self,
_channel_id: Uuid,
_query: Query<Uuid, CreatedAt, ()>,
+ _direction: MessagePageDirection,
_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_channel_attachments(
@@ -233,6 +242,61 @@ async fn messages_returns_empty_page() {
let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(json["items"], serde_json::json!([]));
assert!(json["next_cursor"].is_null());
+ assert!(json["previous_cursor"].is_null());
+}
+
+#[tokio::test]
+async fn messages_returns_400_when_both_cursor_params_are_set() {
+ let router = mock_router();
+ let channel_id = Uuid::new_v4();
+ let raw_cursor = Base64Str::encode_json(Cursor {
+ id: Uuid::new_v4(),
+ limit: 50,
+ val: CursorVal {
+ sort_type: CreatedAt,
+ last_val: chrono::Utc::now(),
+ },
+ filter: (),
+ })
+ .type_erase();
+ let cursor = raw_cursor
+ .replace('+', "%2B")
+ .replace('/', "%2F")
+ .replace('=', "%3D");
+
+ let request = Request::builder()
+ .uri(format!(
+ "/{channel_id}/messages?cursor={cursor}&previous_cursor={cursor}"
+ ))
+ .body(axum::body::Body::empty())
+ .unwrap();
+
+ let res = router.oneshot(request).await.unwrap();
+ assert_eq!(res.status(), StatusCode::BAD_REQUEST);
+
+ let bytes = res.into_body().collect().await.unwrap().to_bytes();
+ let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
+ assert_eq!(
+ json["message"],
+ "provide only one of cursor or previous_cursor"
+ );
+}
+
+#[tokio::test]
+async fn messages_returns_400_on_invalid_previous_cursor() {
+ let router = mock_router();
+ let channel_id = Uuid::new_v4();
+ let request = Request::builder()
+ .uri(format!("/{channel_id}/messages?previous_cursor=not-base64"))
+ .body(axum::body::Body::empty())
+ .unwrap();
+
+ let res = router.oneshot(request).await.unwrap();
+ assert_eq!(res.status(), StatusCode::BAD_REQUEST);
+
+ let bytes = res.into_body().collect().await.unwrap().to_bytes();
+ let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
+ assert_eq!(json["message"], "failed to decode cursor value");
}
#[tokio::test]
@@ -346,13 +410,17 @@ impl ChannelMessagesService for NotFoundService {
&self,
_channel_id: Uuid,
_query: Query<Uuid, CreatedAt, ()>,
+ _direction: MessagePageDirection,
_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_channel_attachments(
@@ -403,6 +471,7 @@ async fn messages_around_returns_empty_page() {
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"], serde_json::json!([]));
+ assert!(json["previous_cursor"].is_null());
}
#[tokio::test]
diff --git a/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs b/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs
index 7e5d0a41cb..35fcdd3f73 100644
--- a/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs
+++ b/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs
@@ -3,10 +3,10 @@ mod tests;
use crate::domain::{
models::{
- ChannelAttachment, ChannelParticipant, CountedReaction, MessageAttachment, ParticipantRole,
- ThreadData, ThreadReplyRow, TopLevelMessageRow,
+ ChannelAttachment, ChannelParticipant, CountedReaction, MessageAttachment,
+ MessagePageDirection, ParticipantRole, ThreadData, ThreadReplyRow, TopLevelMessageRow,
},
- ports::ChannelMessagesRepo,
+ ports::{ChannelMessagesRepo, TopLevelMessagesQueryResult},
};
use chrono::{DateTime, Utc};
use models_pagination::{CreatedAt, Query};
@@ -102,45 +102,98 @@ impl ChannelMessagesRepo for PgChannelMessagesRepo {
&self,
channel_id: Uuid,
query: &Query<Uuid, CreatedAt, ()>,
+ direction: MessagePageDirection,
limit: u16,
- ) -> Result<Vec<TopLevelMessageRow>, Self::Err> {
+ ) -> Result<TopLevelMessagesQueryResult, Self::Err> {
let (cursor_created_at, cursor_id) = match query.vals() {
(Some(id), Some(val)) => (Some(*val), Some(*id)),
_ => (None, None),
};
+ let limit_i64 = i64::from(limit);
+ let limit_usize = usize::from(limit);
+
+ let (rows, has_more_newer) = match direction {
+ MessagePageDirection::Older => {
+ let rows = sqlx::query_as!(
+ TopLevelRow,
+ r#"
+ SELECT
+ m.id,
+ m.channel_id,
+ m.sender_id,
+ m.content,
+ m.created_at,
+ m.updated_at,
+ m.edited_at::timestamptz AS "edited_at?",
+ m.deleted_at::timestamptz AS "deleted_at?"
+ FROM comms_messages m
+ WHERE m.channel_id = $1
+ AND m.thread_id IS NULL
+ AND (m.deleted_at IS NULL OR EXISTS (
+ SELECT 1 FROM comms_messages r
+ WHERE r.thread_id = m.id AND r.deleted_at IS NULL
+ ))
+ AND ($2::timestamptz IS NULL OR (m.created_at, m.id) < ($2, $3))
+ ORDER BY m.created_at DESC, m.id DESC
+ LIMIT $4
+ "#,
+ channel_id,
+ cursor_created_at,
+ cursor_id,
+ limit_i64,
+ )
+ .fetch_all(&self.pool)
+ .await?;
+
+ // For older pagination with a cursor, there is always at least one newer item
+ // (the cursor anchor itself) from the API's perspective.
+ (rows, cursor_created_at.is_some())
+ }
+ MessagePageDirection::Newer => {
+ // Query in ASC so we can overfetch one newer row and trim while preserving the
+ // "nearest newer page" semantics before reversing back to DESC.
+ let mut rows = sqlx::query_as!(
+ TopLevelRow,
+ r#"
+ SELECT
+ m.id,
+ m.channel_id,
+ m.sender_id,
+ m.content,
+ m.created_at,
+ m.updated_at,
+ m.edited_at::timestamptz AS "edited_at?",
+ m.deleted_at::timestamptz AS "deleted_at?"
+ FROM comms_messages m
+ WHERE m.channel_id = $1
+ AND m.thread_id IS NULL
+ AND (m.deleted_at IS NULL OR EXISTS (
+ SELECT 1 FROM comms_messages r
+ WHERE r.thread_id = m.id AND r.deleted_at IS NULL
+ ))
+ AND ($2::timestamptz IS NOT NULL AND (m.created_at, m.id) > ($2, $3))
+ ORDER BY m.created_at ASC, m.id ASC
+ LIMIT $4
+ "#,
+ channel_id,
+ cursor_created_at,
+ cursor_id,
+ limit_i64 + 1,
+ )
+ .fetch_all(&self.pool)
+ .await?;
+
+ let has_more_newer = rows.len() > limit_usize;
+ if has_more_newer {
+ rows.truncate(limit_usize);
+ }
+
+ rows.reverse();
+ (rows, has_more_newer)
+ }
+ };
- let rows = sqlx::query_as!(
- TopLevelRow,
- r#"
- SELECT
- m.id,
- m.channel_id,
- m.sender_id,
- m.content,
- m.created_at,
- m.updated_at,
- m.edited_at::timestamptz AS "edited_at?",
- m.deleted_at::timestamptz AS "deleted_at?"
- FROM comms_messages m
- WHERE m.channel_id = $1
- AND m.thread_id IS NULL
- AND (m.deleted_at IS NULL OR EXISTS (
- SELECT 1 FROM comms_messages r
- WHERE r.thread_id = m.id AND r.deleted_at IS NULL
- ))
- AND ($2::timestamptz IS NULL OR (m.created_at, m.id) < ($2, $3))
- ORDER BY m.created_at DESC, m.id DESC
- LIMIT $4
- "#,
- channel_id,
- cursor_created_at,
- cursor_id,
- i64::from(limit) as i64,
- )
- .fetch_all(&self.pool)
- .await?;
-
- Ok(rows
+ let rows = rows
.into_iter()
.map(|r| TopLevelMessageRow {
id: r.id,
@@ -152,7 +205,12 @@ impl ChannelMessagesRepo for PgChannelMessagesRepo {
edited_at: r.edited_at,
deleted_at: r.deleted_at,
})
- .collect())
+ .collect();
+
+ Ok(TopLevelMessagesQueryResult {
+ rows,
+ has_more_newer,
+ })
}
#[tracing::instrument(err, skip(self))]
diff --git a/rust/cloud-storage/channels/src/outbound/pg_channels_repo/tests.rs b/rust/cloud-storage/channels/src/outbound/pg_channels_repo/tests.rs
index 715867d18a..f61cb8567d 100644
--- a/rust/cloud-storage/channels/src/outbound/pg_channels_repo/tests.rs
+++ b/rust/cloud-storage/channels/src/outbound/pg_channels_repo/tests.rs
@@ -1,4 +1,4 @@
-use crate::domain::models::ParticipantRole;
+use crate::domain::models::{MessagePageDirection, ParticipantRole};
use crate::domain::ports::ChannelMessagesRepo;
use crate::outbound::pg_channels_repo::PgChannelMessagesRepo;
use macro_db_migrator::MACRO_DB_MIGRATIONS;
@@ -26,9 +26,15 @@ async fn top_level_excludes_thread_replies_and_fully_deleted(
pool: Pool<Postgres>,
) -> anyhow::Result<()> {
let repo = repo(pool);
- let rows = repo
- .get_top_level_messages(CH1, &Query::Sort(CreatedAt, ()), 50)
+ let result = repo
+ .get_top_level_messages(
+ CH1,
+ &Query::Sort(CreatedAt, ()),
+ MessagePageDirection::Older,
+ 50,
+ )
.await?;
+ let rows = result.rows;
let ids: Vec<Uuid> = rows.iter().map(|r| r.id).collect();
// msg1, msg2 (deleted but has active reply), msg3 — but NOT msg4 (fully deleted)
@@ -48,9 +54,15 @@ async fn top_level_excludes_thread_replies_and_fully_deleted(
)]
async fn top_level_ordered_newest_first(pool: Pool<Postgres>) -> anyhow::Result<()> {
let repo = repo(pool);
- let rows = repo
- .get_top_level_messages(CH1, &Query::Sort(CreatedAt, ()), 50)
+ let result = repo
+ .get_top_level_messages(
+ CH1,
+ &Query::Sort(CreatedAt, ()),
+ MessagePageDirection::Older,
+ 50,
+ )
.await?;
+ let rows = result.rows;
let ids: Vec<Uuid> = rows.iter().map(|r| r.id).collect();
assert_eq!(ids, vec![MSG3, MSG2, MSG1]);
@@ -65,8 +77,14 @@ async fn top_level_cursor_skips_earlier_messages(pool: Pool<Postgres>) -> anyhow
let repo = repo(pool);
// First fetch all to get cursor values
let all = repo
- .get_top_level_messages(CH1, &Query::Sort(CreatedAt, ()), 50)
- .await?;
+ .get_top_level_messages(
+ CH1,
+ &Query::Sort(CreatedAt, ()),
+ MessagePageDirection::Older,
+ 50,
+ )
+ .await?
+ .rows;
assert_eq!(all.len(), 3);
// Use msg3 (newest) as cursor → should skip msg3, return msg2 + msg1
@@ -79,21 +97,106 @@ async fn top_level_cursor_skips_earlier_messages(pool: Pool<Postgres>) -> anyhow
},
filter: (),
});
- let page2 = repo.get_top_level_messages(CH1, &cursor, 50).await?;
+ let page2 = repo
+ .get_top_level_messages(CH1, &cursor, MessagePageDirection::Older, 50)
+ .await?
+ .rows;
let ids: Vec<Uuid> = page2.iter().map(|r| r.id).collect();
assert_eq!(ids, vec![MSG2, MSG1]);
Ok(())
}
+#[sqlx::test(
+ fixtures(path = "../../../fixtures", scripts("channels_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn top_level_newer_direction_returns_nearest_newer_page(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = repo(pool);
+ let all = repo
+ .get_top_level_messages(
+ CH1,
+ &Query::Sort(CreatedAt, ()),
+ MessagePageDirection::Older,
+ 50,
+ )
+ .await?
+ .rows;
+
+ let oldest = all.last().expect("at least one message");
+ let cursor = Query::Cursor(Cursor {
+ id: oldest.id,
+ limit: 2,
+ val: CursorVal {
+ sort_type: CreatedAt,
+ last_val: oldest.created_at,
+ },
+ filter: (),
+ });
+ let page = repo
+ .get_top_level_messages(CH1, &cursor, MessagePageDirection::Newer, 2)
+ .await?;
+
+ let ids: Vec<Uuid> = page.rows.iter().map(|r| r.id).collect();
+ assert_eq!(ids, vec![MSG3, MSG2]);
+ assert!(!page.has_more_newer);
+ Ok(())
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../fixtures", scripts("channels_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn top_level_newer_direction_sets_has_more_newer_with_overfetch(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = repo(pool);
+ let all = repo
+ .get_top_level_messages(
+ CH1,
+ &Query::Sort(CreatedAt, ()),
+ MessagePageDirection::Older,
+ 50,
+ )
+ .await?
+ .rows;
+
+ let oldest = all.last().expect("at least one message");
+ let cursor = Query::Cursor(Cursor {
+ id: oldest.id,
+ limit: 1,
+ val: CursorVal {
+ sort_type: CreatedAt,
+ last_val: oldest.created_at,
+ },
+ filter: (),
+ });
+ let page = repo
+ .get_top_level_messages(CH1, &cursor, MessagePageDirection::Newer, 1)
+ .await?;
+
+ let ids: Vec<Uuid> = page.rows.iter().map(|r| r.id).collect();
+ assert_eq!(ids, vec![MSG2], "nearest newer message is returned");
+ assert!(page.has_more_newer, "there is still a newer page (MSG3)");
+ Ok(())
+}
+
#[sqlx::test(
fixtures(path = "../../../fixtures", scripts("channels_repo")),
migrator = "MACRO_DB_MIGRATIONS"
)]
async fn top_level_limit_is_respected(pool: Pool<Postgres>) -> anyhow::Result<()> {
let repo = repo(pool);
- let rows = repo
- .get_top_level_messages(CH1, &Query::Sort(CreatedAt, ()), 2)
+ let result = repo
+ .get_top_level_messages(
+ CH1,
+ &Query::Sort(CreatedAt, ()),
+ MessagePageDirection::Older,
+ 2,
+ )
.await?;
+ let rows = result.rows;
assert_eq!(rows.len(), 2);
// Should be the 2 newest
@@ -108,9 +211,15 @@ async fn top_level_limit_is_respected(pool: Pool<Postgres>) -> anyhow::Result<()
)]
async fn top_level_scoped_to_channel(pool: Pool<Postgres>) -> anyhow::Result<()> {
let repo = repo(pool);
- let rows = repo
- .get_top_level_messages(CH2, &Query::Sort(CreatedAt, ()), 50)
+ let result = repo
+ .get_top_level_messages(
+ CH2,
+ &Query::Sort(CreatedAt, ()),
+ MessagePageDirection::Older,
+ 50,
+ )
.await?;
+ let rows = result.rows;
assert_eq!(rows.len(), 1);
assert_eq!(rows[0].content, "other channel msg");
diff --git a/rust/cloud-storage/models_pagination/src/axum.rs b/rust/cloud-storage/models_pagination/src/axum.rs
index 25fa58f6b4..8d4c142915 100644
--- a/rust/cloud-storage/models_pagination/src/axum.rs
+++ b/rust/cloud-storage/models_pagination/src/axum.rs
@@ -10,7 +10,7 @@ use thiserror::Error;
/// An enum which denotes either the client did not provide a cursor value
/// or the cursor was provided and parsed.
-/// Provided but invalid cursors will be rejected as 401
+/// Provided but invalid cursors will be rejected as 400
// TODO: in axum 0.8 there is OptionalFromRequestParts which is preferable to this
#[derive(Debug)]
pub enum CursorExtractor<Id, S: Sortable, F> {
@@ -44,6 +44,12 @@ pub enum CursorExtractErr {
/// The query was too large to deserialize
#[error("Query is too large, must be < 32kb")]
SizeErr,
+ /// The cursor query parameters could not be parsed
+ #[error("invalid cursor query parameters")]
+ InvalidQueryParamsErr,
+ /// Both forward and backward cursors were provided.
+ #[error("provide only one of cursor or previous_cursor")]
+ MutuallyExclusiveErr,
}
impl IntoResponse for CursorExtractErr {
@@ -67,11 +73,45 @@ impl IntoResponse for CursorExtractErr {
message: "Query is too large, must be <32kb",
}),
),
+ CursorExtractErr::InvalidQueryParamsErr => (
+ StatusCode::BAD_REQUEST,
+ Json(ErrorResponse {
+ message: "invalid cursor query parameters",
+ }),
+ ),
+ CursorExtractErr::MutuallyExclusiveErr => (
+ StatusCode::BAD_REQUEST,
+ Json(ErrorResponse {
+ message: "provide only one of cursor or previous_cursor",
+ }),
+ ),
}
.into_response()
}
}
+fn decode_cursor<Id, Sort, F>(
+ encoded: Base64Str<CursorWithValAndFilter<Id, Sort, F>>,
+) -> Result<CursorWithValAndFilter<Id, Sort, F>, CursorExtractErr>
+where
+ Sort: Sortable + DeserializeOwned,
+ Sort::Value: DeserializeOwned,
+ Id: DeserializeOwned,
+ F: DeserializeOwned,
+{
+ let bytes = encoded.len();
+ if bytes > 32_000 {
+ return Err(CursorExtractErr::SizeErr);
+ }
+
+ encoded
+ .decode(|bytes| {
+ let mut deserializer = serde_json::Deserializer::from_slice(&bytes);
+ <CursorWithValAndFilter<Id, Sort, F>>::deserialize(&mut deserializer)
+ })
+ .map_err(CursorExtractErr::DecodeErr)
+}
+
#[async_trait]
impl<S, Id, Sort, F> FromRequestParts<S> for CursorExtractor<Id, Sort, F>
where
@@ -87,32 +127,100 @@ where
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
#[derive(Deserialize)]
struct Params {
- cursor: String,
+ cursor: Option<String>,
}
- let Ok(Query(Params { cursor })) = <Query<Params>>::from_request_parts(parts, state).await
- else {
+ let Query(Params { cursor }) = <Query<Params>>::from_request_parts(parts, state)
+ .await
+ .map_err(|_| CursorExtractErr::InvalidQueryParamsErr)?;
+
+ let Some(cursor) = cursor else {
return Ok(CursorExtractor::None);
};
let encoded: Base64Str<CursorWithValAndFilter<Id, Sort, F>> =
Base64Str::new_from_string(cursor);
- let bytes = encoded.len();
- if bytes > 32_000 {
- return Err(CursorExtractErr::SizeErr);
+ let decoded = decode_cursor(encoded)?;
+
+ Ok(CursorExtractor::Some(decoded))
+ }
+}
+
+/// A parsed bidirectional cursor used for pagination.
+#[derive(Debug)]
+pub enum BidirectionalCursor<Id, S: Sortable, F> {
+ /// The client provided a cursor to fetch the next page.
+ Next(Cursor<Id, CursorVal<S>, F>),
+ /// The client provided a cursor to fetch the previous page.
+ Previous(Cursor<Id, CursorVal<S>, F>),
+}
+
+/// An enum which denotes either the client did not provide cursor params
+/// or exactly one cursor direction was provided and parsed.
+/// Provided but invalid cursors will be rejected as 400.
+// TODO: in axum 0.8 there is OptionalFromRequestParts which is preferable to this
+#[derive(Debug)]
+pub enum BidirectionalCursorExtractor<Id, S: Sortable, F> {
+ /// The client provided a valid parsed cursor.
+ Some(BidirectionalCursor<Id, S, F>),
+ /// The client did not provide cursor params.
+ None,
+}
+
+impl<Id, S: Sortable, F> BidirectionalCursorExtractor<Id, S, F> {
+ /// convert self into an optional [BidirectionalCursor]
+ pub fn into_option(self) -> Option<BidirectionalCursor<Id, S, F>> {
+ match self {
+ BidirectionalCursorExtractor::Some(parsed_cursor) => Some(parsed_cursor),
+ BidirectionalCursorExtractor::None => None,
}
+ }
+}
+
+#[async_trait]
+impl<S, Id, Sort, F> FromRequestParts<S> for BidirectionalCursorExtractor<Id, Sort, F>
+where
+ S: Send + Sync,
+ Sort: Sortable + DeserializeOwned,
+ Sort::Value: DeserializeOwned,
+ Id: DeserializeOwned,
+ F: DeserializeOwned,
+{
+ type Rejection = CursorExtractErr;
- let decoded = encoded
- .decode(|bytes| {
- let mut deserializer = serde_json::Deserializer::from_slice(&bytes);
- deserializer.disable_recursion_limit();
- <CursorWithValAndFilter<Id, Sort, F>>::deserialize(&mut deserializer)
- })
- .inspect_err(|e| {
- dbg!(e);
- })
- .map_err(CursorExtractErr::DecodeErr)?;
+ #[tracing::instrument(err, skip(parts, state))]
+ async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
+ #[derive(Deserialize)]
+ struct Params {
+ cursor: Option<String>,
+ previous_cursor: Option<String>,
+ }
+ let Query(Params {
+ cursor,
+ previous_cursor,
+ }) = <Query<Params>>::from_request_parts(parts, state)
+ .await
+ .map_err(|_| CursorExtractErr::InvalidQueryParamsErr)?;
- Ok(CursorExtractor::Some(decoded))
+ match (cursor, previous_cursor) {
+ (Some(_), Some(_)) => Err(CursorExtractErr::MutuallyExclusiveErr),
+ (Some(cursor), None) => {
+ let encoded: Base64Str<CursorWithValAndFilter<Id, Sort, F>> =
+ Base64Str::new_from_string(cursor);
+ let decoded = decode_cursor(encoded)?;
+ Ok(BidirectionalCursorExtractor::Some(
+ BidirectionalCursor::Next(decoded),
+ ))
+ }
+ (None, Some(previous_cursor)) => {
+ let encoded: Base64Str<CursorWithValAndFilter<Id, Sort, F>> =
+ Base64Str::new_from_string(previous_cursor);
+ let decoded = decode_cursor(encoded)?;
+ Ok(BidirectionalCursorExtractor::Some(
+ BidirectionalCursor::Previous(decoded),
+ ))
+ }
+ (None, None) => Ok(BidirectionalCursorExtractor::None),
+ }
}
}