Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(channels): load around specific message (#1589)
teob91c6f1e37a6
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.tsindex bf78d63b8c..777bb8f13c 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@@ -15,4 +15,8 @@ export type GetChannelMessagesParams = {* Base64 encoded cursor value*/cursor?: string;+ /**+ * Return a centered window around this message ID+ */+ load_around_message_id?: string;};diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex c0ddf20d5d..907dddbe1b 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -875,6 +875,11 @@ export const getChannelMessagesQueryParams = zod.object({.optional().describe('Page size (1-100, default 50)'),cursor: zod.string().optional().describe('Base64 encoded cursor value'),+ load_around_message_id: zod+ .string()+ .uuid()+ .optional()+ .describe('Return a centered window around this message ID'),});export const getChannelMessagesResponse = zoddiff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex 7c32ac5df0..cff9924092 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -694,6 +694,16 @@"schema": {"type": "string"}+ },+ {+ "name": "load_around_message_id",+ "in": "query",+ "description": "Return a centered window around this message ID",+ "required": false,+ "schema": {+ "type": "string",+ "format": "uuid"+ }}],"responses": {@@ -707,6 +717,16 @@}}},+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },"500": {"description": "","content": {diff --git a/rust/cloud-storage/channels/.sqlx/query-ab3aa320a07e9885f1de7995533b75dfc995ac18e421ca940dd0828aa32b47a6.json b/rust/cloud-storage/channels/.sqlx/query-ab3aa320a07e9885f1de7995533b75dfc995ac18e421ca940dd0828aa32b47a6.jsonnew file mode 100644index 0000000000..026107a6ab--- /dev/null+++ b/rust/cloud-storage/channels/.sqlx/query-ab3aa320a07e9885f1de7995533b75dfc995ac18e421ca940dd0828aa32b47a6.json@@ -0,0 +1,65 @@+{+ "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.id = COALESCE(\n (SELECT thread_id FROM comms_messages WHERE id = $1 AND channel_id = $2),\n $1\n )\n AND m.channel_id = $2\n AND m.thread_id IS NULL\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",+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ false,+ null,+ null+ ]+ },+ "hash": "ab3aa320a07e9885f1de7995533b75dfc995ac18e421ca940dd0828aa32b47a6"+}diff --git a/rust/cloud-storage/channels/.sqlx/query-d7a3be325f304ca9642f1ae4f18a3b22e871c61feff6dbc1fe793cedd2cf403c.json b/rust/cloud-storage/channels/.sqlx/query-d7a3be325f304ca9642f1ae4f18a3b22e871c61feff6dbc1fe793cedd2cf403c.jsonnew file mode 100644index 0000000000..59be5b6504--- /dev/null+++ b/rust/cloud-storage/channels/.sqlx/query-d7a3be325f304ca9642f1ae4f18a3b22e871c61feff6dbc1fe793cedd2cf403c.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 (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": "d7a3be325f304ca9642f1ae4f18a3b22e871c61feff6dbc1fe793cedd2cf403c"+}diff --git a/rust/cloud-storage/channels/.sqlx/query-f9dd839c0eeb6b25a432136def701390348a6d4e33feefb4c3d33974e15fcf83.json b/rust/cloud-storage/channels/.sqlx/query-f9dd839c0eeb6b25a432136def701390348a6d4e33feefb4c3d33974e15fcf83.jsonnew file mode 100644index 0000000000..ac492d99f7--- /dev/null+++ b/rust/cloud-storage/channels/.sqlx/query-f9dd839c0eeb6b25a432136def701390348a6d4e33feefb4c3d33974e15fcf83.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 (m.created_at, m.id) < ($2, $3)\n ORDER BY m.created_at DESC, m.id DESC\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": "f9dd839c0eeb6b25a432136def701390348a6d4e33feefb4c3d33974e15fcf83"+}diff --git a/rust/cloud-storage/channels/src/domain/ports.rs b/rust/cloud-storage/channels/src/domain/ports.rsindex 28d8a0e86e..67657658c7 100644--- a/rust/cloud-storage/channels/src/domain/ports.rs+++ b/rust/cloud-storage/channels/src/domain/ports.rs@@ -2,6 +2,7 @@ use crate::domain::models::{ChannelAttachment, ChannelParticipant, CountedReaction, MessageAttachment, ThreadData,TopLevelMessageRow,};+use chrono::{DateTime, Utc};use models_pagination::{CreatedAt, Query};use std::collections::HashMap;use uuid::Uuid;@@ -52,6 +53,24 @@ pub trait ChannelMessagesRepo: Send + Sync + 'static {&self,channel_id: Uuid,) -> impl Future<Output = Result<Vec<ChannelParticipant>, Self::Err>> + Send;++ /// Resolve a message id to its top-level parent row. If the message is a thread reply,+ /// returns the parent; if already top-level, returns itself. Returns `None` if not found.+ fn resolve_top_level_parent(+ &self,+ channel_id: Uuid,+ message_id: Uuid,+ ) -> impl Future<Output = Result<Option<TopLevelMessageRow>, Self::Err>> + Send;++ /// Fetch top-level messages around an anchor, split into before (DESC) and after (ASC).+ /// Each side is limited to `limit` rows for overfetch; trimming happens in the service.+ fn get_top_level_messages_around(+ &self,+ channel_id: Uuid,+ anchor_created_at: DateTime<Utc>,+ anchor_id: Uuid,+ limit: u16,+ ) -> impl Future<Output = Result<(Vec<TopLevelMessageRow>, Vec<TopLevelMessageRow>), Self::Err>> + Send;}/// Service for fetching paginated channel messages.@@ -77,6 +96,24 @@ pub trait ChannelMessagesService: Send + Sync + 'static {&self,channel_id: Uuid,) -> impl Future<Output = Result<Vec<ChannelParticipant>, ChannelMessagesErr>> + Send;++ /// Fetch a centered window of messages around a specific message id.+ fn get_channel_messages_around(+ &self,+ channel_id: Uuid,+ message_id: Uuid,+ limit: u16,+ ) -> impl Future<Output = Result<ChannelMessagesPage, ChannelMessagesErr>> + Send;+}++/// Access check for channel membership. Separated from the business logic service.+pub trait ChannelAccessCheck: Send + Sync + 'static {+ /// Check whether a user is an active participant in a channel.+ fn is_channel_member(+ &self,+ channel_id: Uuid,+ user_id: &str,+ ) -> impl Future<Output = Result<bool, anyhow::Error>> + Send;}/// A paginated page of channel messages.@@ -93,4 +130,7 @@ pub enum ChannelMessagesErr {/// A database error occurred.#[error(transparent)]Repo(#[from] anyhow::Error),+ /// The requested message was not found.+ #[error("message {0} not found")]+ MessageNotFound(Uuid),}diff --git a/rust/cloud-storage/channels/src/domain/service.rs b/rust/cloud-storage/channels/src/domain/service.rsindex 6b3ff7f3e4..6d52ac6c52 100644--- a/rust/cloud-storage/channels/src/domain/service.rs+++ b/rust/cloud-storage/channels/src/domain/service.rs@@ -1,5 +1,5 @@use crate::domain::{- models::{ChannelMessage, ChannelParticipant, ThreadInfo, ThreadReply},+ models::{ChannelMessage, ChannelParticipant, ThreadInfo, ThreadReply, TopLevelMessageRow},ports::{ChannelAttachmentsPage, ChannelMessagesErr, ChannelMessagesPage, ChannelMessagesRepo,ChannelMessagesService,@@ -28,28 +28,12 @@ wherepub fn new(repo: R) -> Self {Self { repo }}-}-impl<R> ChannelMessagesService for ChannelMessagesServiceImpl<R>-where- R: ChannelMessagesRepo,- anyhow::Error: From<R::Err>,-{- #[tracing::instrument(err, skip(self))]- async fn get_channel_messages(+ /// Hydrate top-level message rows with thread data, reactions, and attachments.+ async fn hydrate_messages(&self,- channel_id: Uuid,- query: Query<Uuid, CreatedAt, ()>,- limit: u16,- ) -> Result<ChannelMessagesPage, ChannelMessagesErr> {- let limit = limit.clamp(1, 100);-- let rows = self- .repo- .get_top_level_messages(channel_id, &query, limit)- .await- .map_err(anyhow::Error::from)?;-+ rows: Vec<TopLevelMessageRow>,+ ) -> Result<Vec<ChannelMessage>, ChannelMessagesErr> {let parent_ids: Vec<Uuid> = rows.iter().map(|r| r.id).collect();let thread_data = self@@ -115,7 +99,75 @@ where}).collect();- // 6. Paginate.+ Ok(messages)+ }+}++/// Build a centered window of messages around an anchor.+///+/// - `before`: older messages in DESC order (closest to anchor first).+/// - `anchor`: the anchor message itself.+/// - `after`: newer messages in ASC order (closest to anchor first).+/// - `limit`: total number of messages to return (including the anchor).+///+/// Returns messages in DESC order (newest first).+fn center_window(+ before: Vec<TopLevelMessageRow>,+ anchor: TopLevelMessageRow,+ after: Vec<TopLevelMessageRow>,+ limit: usize,+) -> Vec<TopLevelMessageRow> {+ if limit == 0 {+ return vec![];+ }+ if limit == 1 {+ return vec![anchor];+ }++ let slots = limit - 1;+ let half = slots / 2;++ 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 mut before = before;+ before.truncate(before_take);++ let mut after = after;+ after.truncate(after_take);+ after.reverse();++ let mut result = after;+ result.reserve(1 + before.len());+ result.push(anchor);+ result.append(&mut before);++ result+}++impl<R> ChannelMessagesService for ChannelMessagesServiceImpl<R>+where+ R: ChannelMessagesRepo,+ anyhow::Error: From<R::Err>,+{+ #[tracing::instrument(err, skip(self))]+ async fn get_channel_messages(+ &self,+ channel_id: Uuid,+ query: Query<Uuid, CreatedAt, ()>,+ limit: u16,+ ) -> Result<ChannelMessagesPage, ChannelMessagesErr> {+ let limit = limit.clamp(1, 100);++ let rows = self+ .repo+ .get_top_level_messages(channel_id, &query, limit)+ .await+ .map_err(anyhow::Error::from)?;++ let messages = self.hydrate_messages(rows).await?;+let page = messages.into_iter().paginate_on(limit.into(), CreatedAt)@@ -162,4 +214,38 @@ whereOk(participants)}++ #[tracing::instrument(err, skip(self))]+ async fn get_channel_messages_around(+ &self,+ channel_id: Uuid,+ message_id: Uuid,+ limit: u16,+ ) -> Result<ChannelMessagesPage, ChannelMessagesErr> {+ let limit = limit.clamp(1, 100);++ let anchor = self+ .repo+ .resolve_top_level_parent(channel_id, message_id)+ .await+ .map_err(anyhow::Error::from)?+ .ok_or(ChannelMessagesErr::MessageNotFound(message_id))?;++ let (before, after) = self+ .repo+ .get_top_level_messages_around(channel_id, anchor.created_at, anchor.id, limit)+ .await+ .map_err(anyhow::Error::from)?;++ let rows = center_window(before, anchor, after, limit.into());+ let messages = self.hydrate_messages(rows).await?;++ let page = messages+ .into_iter()+ .paginate_on(limit.into(), CreatedAt)+ .filter_on(())+ .into_page();++ Ok(page)+ }}diff --git a/rust/cloud-storage/channels/src/domain/service/test.rs b/rust/cloud-storage/channels/src/domain/service/test.rsindex e30f6c5054..c87d1434b4 100644--- a/rust/cloud-storage/channels/src/domain/service/test.rs+++ b/rust/cloud-storage/channels/src/domain/service/test.rs@@ -34,6 +34,10 @@ fn empty_repo() -> MockChannelMessagesRepo {.returning(|_, _, _| Box::pin(async { Ok(vec![]) }));repo.expect_get_channel_participants().returning(|_| Box::pin(async { Ok(vec![]) }));+ repo.expect_resolve_top_level_parent()+ .returning(|_, _| Box::pin(async { Ok(None) }));+ repo.expect_get_top_level_messages_around()+ .returning(|_, _, _, _| Box::pin(async { Ok((vec![], vec![])) }));repo}@@ -169,3 +173,144 @@ async fn returns_empty_participants_list() {assert!(participants.is_empty());}++// --- center_window tests ---++#[test]+fn center_window_balanced() {+ // 5 before, anchor, 5 after, limit=7 → half=3 before, 3 after+ let before: Vec<_> = (1..=5).map(|i| make_row(Uuid::new_v4(), i)).collect();+ let anchor = make_row(Uuid::new_v4(), 0);+ let after: Vec<_> = (1..=5).map(|i| make_row(Uuid::new_v4(), -i)).collect();++ let result = center_window(before.clone(), anchor.clone(), after.clone(), 7);+ assert_eq!(result.len(), 7);+ // 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);+ assert_eq!(result[2].id, after[0].id);+ assert_eq!(result[3].id, anchor.id);+ assert_eq!(result[4].id, before[0].id);+ assert_eq!(result[5].id, before[1].id);+ assert_eq!(result[6].id, before[2].id);+}++#[test]+fn center_window_near_oldest_edge() {+ // Only 1 before, anchor, 10 after, limit=7 → 1 before, 5 after+ let before = vec![make_row(Uuid::new_v4(), 1)];+ let anchor = make_row(Uuid::new_v4(), 0);+ let after: Vec<_> = (1..=10).map(|i| make_row(Uuid::new_v4(), -i)).collect();++ let result = center_window(before.clone(), anchor.clone(), after.clone(), 7);+ assert_eq!(result.len(), 7);+ assert_eq!(result[5].id, anchor.id);+ assert_eq!(result[6].id, before[0].id);+ // First 5 are after (reversed)+ for i in 0..5 {+ assert_eq!(result[i].id, after[4 - i].id);+ }+}++#[test]+fn center_window_near_newest_edge() {+ // 10 before, anchor, only 1 after, limit=7 → 5 before, 1 after+ let before: Vec<_> = (1..=10).map(|i| make_row(Uuid::new_v4(), i)).collect();+ let anchor = make_row(Uuid::new_v4(), 0);+ let after = vec![make_row(Uuid::new_v4(), -1)];++ let result = center_window(before.clone(), anchor.clone(), after.clone(), 7);+ assert_eq!(result.len(), 7);+ assert_eq!(result[0].id, after[0].id);+ assert_eq!(result[1].id, anchor.id);+ for i in 0..5 {+ assert_eq!(result[2 + i].id, before[i].id);+ }+}++#[test]+fn center_window_small_channel() {+ // 2 before, anchor, 1 after, limit=10 → returns all 4+ let before: Vec<_> = (1..=2).map(|i| make_row(Uuid::new_v4(), i)).collect();+ let anchor = make_row(Uuid::new_v4(), 0);+ let after = vec![make_row(Uuid::new_v4(), -1)];++ let result = center_window(before.clone(), anchor.clone(), after.clone(), 10);+ assert_eq!(result.len(), 4);+ assert_eq!(result[0].id, after[0].id);+ assert_eq!(result[1].id, anchor.id);+ assert_eq!(result[2].id, before[0].id);+ assert_eq!(result[3].id, before[1].id);+}++#[test]+fn center_window_limit_one() {+ let before: Vec<_> = (1..=5).map(|i| make_row(Uuid::new_v4(), i)).collect();+ let anchor = make_row(Uuid::new_v4(), 0);+ let after: Vec<_> = (1..=5).map(|i| make_row(Uuid::new_v4(), -i)).collect();++ let result = center_window(before, anchor.clone(), after, 1);+ assert_eq!(result.len(), 1);+ assert_eq!(result[0].id, anchor.id);+}++// --- get_channel_messages_around tests ---++#[tokio::test]+async fn around_message_not_found() {+ let svc = ChannelMessagesServiceImpl::new(empty_repo());+ let message_id = Uuid::new_v4();++ let err = svc+ .get_channel_messages_around(Uuid::nil(), message_id, 50)+ .await+ .unwrap_err();++ assert!(+ matches!(err, ChannelMessagesErr::MessageNotFound(id) if id == message_id),+ "expected MessageNotFound, got {err:?}"+ );+}++#[tokio::test]+async fn around_resolves_and_hydrates() {+ let anchor = make_row(Uuid::new_v4(), 0);+ let before_row = make_row(Uuid::new_v4(), 1);+ let after_row = make_row(Uuid::new_v4(), -1);++ let anchor_clone = anchor.clone();+ let before_clone = before_row.clone();+ let after_clone = after_row.clone();++ let mut repo = MockChannelMessagesRepo::new();++ repo.expect_resolve_top_level_parent()+ .returning(move |_, _| {+ let a = anchor_clone.clone();+ Box::pin(async move { Ok(Some(a)) })+ });+ repo.expect_get_top_level_messages_around()+ .returning(move |_, _, _, _| {+ let b = vec![before_clone.clone()];+ let a = vec![after_clone.clone()];+ Box::pin(async move { Ok((b, a)) })+ });+ repo.expect_get_thread_data()+ .returning(|_, _| Box::pin(async { Ok(HashMap::new()) }));+ repo.expect_get_reactions_batch()+ .returning(|_| Box::pin(async { Ok(HashMap::new()) }));+ repo.expect_get_attachments_batch()+ .returning(|_| Box::pin(async { Ok(HashMap::new()) }));++ let svc = ChannelMessagesServiceImpl::new(repo);+ let page = svc+ .get_channel_messages_around(Uuid::nil(), anchor.id, 50)+ .await+ .unwrap();++ assert_eq!(page.items.len(), 3);+ // DESC order: after, anchor, before+ assert_eq!(page.items[0].id, after_row.id);+ assert_eq!(page.items[1].id, anchor.id);+ assert_eq!(page.items[2].id, before_row.id);+}diff --git a/rust/cloud-storage/channels/src/inbound/axum_router.rs b/rust/cloud-storage/channels/src/inbound/axum_router.rsindex bf8ee71965..32b51e714d 100644--- a/rust/cloud-storage/channels/src/inbound/axum_router.rs+++ b/rust/cloud-storage/channels/src/inbound/axum_router.rs@@ -5,11 +5,11 @@ use crate::domain::models::{ChannelAttachment, ChannelMessage, ChannelParticipant, CountedReaction, MessageAttachment,ParticipantRole, ThreadInfo, ThreadReply,};-use crate::domain::ports::{ChannelMessagesErr, ChannelMessagesService};+use crate::domain::ports::{ChannelAccessCheck, ChannelMessagesErr, ChannelMessagesService};use axum::{Json, Router,- extract::{Path, Query, State},- http::StatusCode,+ extract::{FromRequestParts, Path, Query, State},+ http::{StatusCode, request::Parts},response::IntoResponse,routing::get,};@@ -22,53 +22,130 @@ use std::sync::Arc;use uuid::Uuid;/// State for the channels router.-pub struct ChannelsRouterState<S> {+pub struct ChannelsRouterState<S, A> {service: Arc<S>,+ access: Arc<A>,}-impl<S> Clone for ChannelsRouterState<S> {+impl<S, A> Clone for ChannelsRouterState<S, A> {fn clone(&self) -> Self {Self {service: self.service.clone(),+ access: self.access.clone(),}}}-impl<S: ChannelMessagesService> ChannelsRouterState<S> {- /// Create a new router state wrapping the service.- pub fn new(service: S) -> Self {+impl<S: ChannelMessagesService, A: ChannelAccessCheck> ChannelsRouterState<S, A> {+ /// Create a new router state wrapping the service and access checker.+ pub fn new(service: S, access: A) -> Self {Self {service: Arc::new(service),+ access: Arc::new(access),}}}+/// Verified channel member. Rejects the request if the authenticated user is not an active+/// participant in the channel identified by the `:channel_id` path parameter.+pub struct ChannelMember {+ /// The channel id from the path.+ pub channel_id: Uuid,+}++/// Rejection returned by the [`ChannelMember`] extractor.+#[derive(Debug)]+pub enum ChannelMemberRejection {+ /// The user is not authenticated.+ Unauthenticated,+ /// The `:channel_id` path parameter is missing or invalid.+ InvalidPath,+ /// The user is not a member of the channel.+ Forbidden,+ /// A database or internal error occurred.+ Internal,+}++impl IntoResponse for ChannelMemberRejection {+ fn into_response(self) -> axum::response::Response {+ let (status, message) = match self {+ Self::Unauthenticated => (StatusCode::UNAUTHORIZED, "Unauthorized"),+ Self::InvalidPath => (StatusCode::BAD_REQUEST, "Invalid channel_id"),+ Self::Forbidden => (StatusCode::FORBIDDEN, "Not a channel member"),+ Self::Internal => (+ StatusCode::INTERNAL_SERVER_ERROR,+ "An internal server error occurred",+ ),+ };+ (status, Json(ErrorResponse { message })).into_response()+ }+}++#[axum::async_trait]+impl<S, A> FromRequestParts<ChannelsRouterState<S, A>> for ChannelMember+where+ S: ChannelMessagesService,+ A: ChannelAccessCheck,+{+ type Rejection = ChannelMemberRejection;++ async fn from_request_parts(+ parts: &mut Parts,+ state: &ChannelsRouterState<S, A>,+ ) -> Result<Self, Self::Rejection> {+ let user = MacroUserExtractor::from_request_parts(parts, state)+ .await+ .map_err(|_| ChannelMemberRejection::Unauthenticated)?;++ let Path(channel_id) = Path::<Uuid>::from_request_parts(parts, state)+ .await+ .map_err(|_| ChannelMemberRejection::InvalidPath)?;++ let is_member = state+ .access+ .is_channel_member(channel_id, &user.user_context.user_id)+ .await+ .map_err(|_| ChannelMemberRejection::Internal)?;++ if !is_member {+ return Err(ChannelMemberRejection::Forbidden);+ }++ Ok(ChannelMember { channel_id })+ }+}+/// Query parameters for the messages endpoint.#[derive(Debug, Default, Deserialize)]pub struct Params {/// Page size. Clamped to [1, 100], defaults to 50.#[serde(default)]limit: Option<u16>,+ /// When set, return a centered window of messages around this message id+ /// instead of cursor-paginated results.+ #[serde(default)]+ load_around_message_id: Option<Uuid>,}/// Create the channels router.-pub fn channels_router<S, T>(state: ChannelsRouterState<S>) -> Router<T>+pub fn channels_router<S, A, T>(state: ChannelsRouterState<S, A>) -> Router<T>whereS: ChannelMessagesService,+ A: ChannelAccessCheck,T: Send + Sync,{Router::new().route("/:channel_id/messages",- get(get_channel_messages_handler::<S>),+ get(get_channel_messages_handler::<S, A>),).route("/:channel_id/attachments",- get(get_channel_attachments_handler::<S>),+ get(get_channel_attachments_handler::<S, A>),).route("/:channel_id/participants",- get(get_channel_participants_handler::<S>),+ get(get_channel_participants_handler::<S, A>),).with_state(state)}@@ -82,27 +159,38 @@ where("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"),+ ("load_around_message_id" = Option<Uuid>, Query, description = "Return a centered window around this message ID"),),responses((status = 200, body = ApiChannelMessagesPage),+ (status = 404, body = ErrorResponse),(status = 500, body = ErrorResponse),))]#[tracing::instrument(err, skip_all)]-pub async fn get_channel_messages_handler<S: ChannelMessagesService>(- State(state): State<ChannelsRouterState<S>>,- MacroUserExtractor { .. }: MacroUserExtractor,- Path(channel_id): Path<Uuid>,+pub async fn get_channel_messages_handler<S: ChannelMessagesService, A: ChannelAccessCheck>(+ 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);- let query = cursor.into_query(CreatedAt, ());- let page = state- .service- .get_channel_messages(channel_id, query, limit)- .await?;+ let page = match params.load_around_message_id {+ Some(message_id) => {+ state+ .service+ .get_channel_messages_around(member.channel_id, message_id, limit)+ .await?+ }+ None => {+ let query = cursor.into_query(CreatedAt, ());+ state+ .service+ .get_channel_messages(member.channel_id, query, limit)+ .await?+ }+ };Ok(Json(page.type_erase().map(ApiChannelMessage::from)))}@@ -123,10 +211,9 @@ pub async fn get_channel_messages_handler<S: ChannelMessagesService>())]#[tracing::instrument(err, skip_all)]-pub async fn get_channel_attachments_handler<S: ChannelMessagesService>(- State(state): State<ChannelsRouterState<S>>,- MacroUserExtractor { .. }: MacroUserExtractor,- Path(channel_id): Path<Uuid>,+pub async fn get_channel_attachments_handler<S: ChannelMessagesService, A: ChannelAccessCheck>(+ State(state): State<ChannelsRouterState<S, A>>,+ member: ChannelMember,Query(params): Query<Params>,cursor: CursorExtractor<Uuid, CreatedAt, ()>,) -> Result<Json<PaginatedOpaqueCursor<ApiChannelAttachment>>, ChannelsHandlerErr> {@@ -135,7 +222,7 @@ pub async fn get_channel_attachments_handler<S: ChannelMessagesService>(let page = state.service- .get_channel_attachments(channel_id, query, limit)+ .get_channel_attachments(member.channel_id, query, limit).await?;Ok(Json(page.type_erase().map(ApiChannelAttachment::from)))@@ -155,12 +242,14 @@ pub async fn get_channel_attachments_handler<S: ChannelMessagesService>())]#[tracing::instrument(err, skip_all)]-pub async fn get_channel_participants_handler<S: ChannelMessagesService>(- State(state): State<ChannelsRouterState<S>>,- MacroUserExtractor { .. }: MacroUserExtractor,- Path(channel_id): Path<Uuid>,+pub async fn get_channel_participants_handler<S: ChannelMessagesService, A: ChannelAccessCheck>(+ State(state): State<ChannelsRouterState<S, A>>,+ member: ChannelMember,) -> Result<Json<Vec<ApiChannelParticipant>>, ChannelsHandlerErr> {- let participants = state.service.get_channel_participants(channel_id).await?;+ let participants = state+ .service+ .get_channel_participants(member.channel_id)+ .await?;Ok(Json(participants@@ -440,13 +529,28 @@ pub enum ChannelsHandlerErr {impl IntoResponse for ChannelsHandlerErr {fn into_response(self) -> axum::response::Response {- tracing::error!(error=?self, "channels handler error");- (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: "An internal server error occurred",- }),- )- .into_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()+ }+ }}}diff --git a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs b/rust/cloud-storage/channels/src/inbound/axum_router/test.rsindex c7b7ed59f7..bae6a1acf3 100644--- a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs+++ b/rust/cloud-storage/channels/src/inbound/axum_router/test.rs@@ -3,7 +3,8 @@ use crate::domain::models::{ChannelAttachment, ChannelMessage, ChannelParticipant, ParticipantRole,};use crate::domain::ports::{- ChannelAttachmentsPage, ChannelMessagesErr, ChannelMessagesPage, ChannelMessagesService,+ ChannelAccessCheck, ChannelAttachmentsPage, ChannelMessagesErr, ChannelMessagesPage,+ ChannelMessagesService,};use axum::{Extension, Router,@@ -14,6 +15,34 @@ use model_user::UserContext;use models_pagination::{CreatedAt, PaginateOn, Query};use tower::util::ServiceExt;+// --- Access check implementations for tests ---++struct AlwaysAllow;++impl ChannelAccessCheck for AlwaysAllow {+ async fn is_channel_member(+ &self,+ _channel_id: Uuid,+ _user_id: &str,+ ) -> Result<bool, anyhow::Error> {+ Ok(true)+ }+}++struct AlwaysDeny;++impl ChannelAccessCheck for AlwaysDeny {+ async fn is_channel_member(+ &self,+ _channel_id: Uuid,+ _user_id: &str,+ ) -> Result<bool, anyhow::Error> {+ Ok(false)+ }+}++// --- Mock services (business logic only, no auth concerns) ---+struct MockService;impl ChannelMessagesService for MockService {@@ -49,6 +78,19 @@ impl ChannelMessagesService for MockService {) -> Result<Vec<ChannelParticipant>, ChannelMessagesErr> {Ok(vec![])}++ async fn get_channel_messages_around(+ &self,+ _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())+ }}struct ErrorService;@@ -78,6 +120,15 @@ impl ChannelMessagesService for ErrorService {) -> Result<Vec<ChannelParticipant>, ChannelMessagesErr> {Err(ChannelMessagesErr::Repo(anyhow::anyhow!("database error")))}++ async fn get_channel_messages_around(+ &self,+ _channel_id: Uuid,+ _message_id: Uuid,+ _limit: u16,+ ) -> Result<ChannelMessagesPage, ChannelMessagesErr> {+ Err(ChannelMessagesErr::Repo(anyhow::anyhow!("database error")))+ }}struct ParticipantsService;@@ -130,6 +181,19 @@ impl ChannelMessagesService for ParticipantsService {},])}++ async fn get_channel_messages_around(+ &self,+ _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())+ }}fn user_extension() -> Extension<UserContext> {@@ -142,11 +206,15 @@ fn user_extension() -> Extension<UserContext> {}fn mock_router() -> Router {- channels_router(ChannelsRouterState::new(MockService)).layer(user_extension())+ channels_router(ChannelsRouterState::new(MockService, AlwaysAllow)).layer(user_extension())}fn error_router() -> Router {- channels_router(ChannelsRouterState::new(ErrorService)).layer(user_extension())+ channels_router(ChannelsRouterState::new(ErrorService, AlwaysAllow)).layer(user_extension())+}++fn denied_router() -> Router {+ channels_router(ChannelsRouterState::new(MockService, AlwaysDeny)).layer(user_extension())}#[tokio::test]@@ -234,8 +302,8 @@ async fn participants_returns_empty_list() {#[tokio::test]async fn participants_returns_data_with_correct_shape() {- let router =- channels_router(ChannelsRouterState::new(ParticipantsService)).layer(user_extension());+ let router = channels_router(ChannelsRouterState::new(ParticipantsService, AlwaysAllow))+ .layer(user_extension());let channel_id = Uuid::new_v4();let request = Request::builder().uri(format!("/{channel_id}/participants"))@@ -270,3 +338,135 @@ async fn participants_returns_500_on_service_error() {let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();assert_eq!(json["message"], "An internal server error occurred");}++struct NotFoundService;++impl ChannelMessagesService for NotFoundService {+ async fn get_channel_messages(+ &self,+ _channel_id: Uuid,+ _query: Query<Uuid, CreatedAt, ()>,+ _limit: u16,+ ) -> Result<ChannelMessagesPage, ChannelMessagesErr> {+ Ok(Vec::<ChannelMessage>::new()+ .into_iter()+ .paginate_on(50, CreatedAt)+ .filter_on(())+ .into_page())+ }++ async fn get_channel_attachments(+ &self,+ _channel_id: Uuid,+ _query: Query<Uuid, CreatedAt, ()>,+ _limit: u16,+ ) -> Result<ChannelAttachmentsPage, ChannelMessagesErr> {+ Ok(Vec::<ChannelAttachment>::new()+ .into_iter()+ .paginate_on(50, CreatedAt)+ .filter_on(())+ .into_page())+ }++ async fn get_channel_participants(+ &self,+ _channel_id: Uuid,+ ) -> Result<Vec<ChannelParticipant>, ChannelMessagesErr> {+ Ok(vec![])+ }++ async fn get_channel_messages_around(+ &self,+ _channel_id: Uuid,+ message_id: Uuid,+ _limit: u16,+ ) -> Result<ChannelMessagesPage, ChannelMessagesErr> {+ Err(ChannelMessagesErr::MessageNotFound(message_id))+ }+}++#[tokio::test]+async fn messages_around_returns_empty_page() {+ let router = mock_router();+ 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"], serde_json::json!([]));+}++#[tokio::test]+async fn messages_around_returns_404_when_not_found() {+ let router = channels_router(ChannelsRouterState::new(NotFoundService, AlwaysAllow))+ .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::NOT_FOUND);++ 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"], "Message not found");+}++// --- Access control tests ---++#[tokio::test]+async fn non_member_cannot_access_messages() {+ let router = denied_router();+ let channel_id = Uuid::new_v4();+ let request = Request::builder()+ .uri(format!("/{channel_id}/messages"))+ .body(axum::body::Body::empty())+ .unwrap();++ let res = router.oneshot(request).await.unwrap();+ assert_eq!(res.status(), StatusCode::FORBIDDEN);++ 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"], "Not a channel member");+}++#[tokio::test]+async fn non_member_cannot_access_attachments() {+ let router = denied_router();+ let channel_id = Uuid::new_v4();+ let request = Request::builder()+ .uri(format!("/{channel_id}/attachments"))+ .body(axum::body::Body::empty())+ .unwrap();++ let res = router.oneshot(request).await.unwrap();+ assert_eq!(res.status(), StatusCode::FORBIDDEN);+}++#[tokio::test]+async fn non_member_cannot_access_participants() {+ let router = denied_router();+ let channel_id = Uuid::new_v4();+ let request = Request::builder()+ .uri(format!("/{channel_id}/participants"))+ .body(axum::body::Body::empty())+ .unwrap();++ let res = router.oneshot(request).await.unwrap();+ assert_eq!(res.status(), StatusCode::FORBIDDEN);+}diff --git a/rust/cloud-storage/channels/src/outbound/mod.rs b/rust/cloud-storage/channels/src/outbound/mod.rsindex 7e85e2b8a8..0aaaa8fe2d 100644--- a/rust/cloud-storage/channels/src/outbound/mod.rs+++ b/rust/cloud-storage/channels/src/outbound/mod.rs@@ -1,2 +1,4 @@+/// Postgres-backed channel membership check.+pub mod pg_access_check;/// Postgres repository for channel messages.pub mod pg_channels_repo;diff --git a/rust/cloud-storage/channels/src/outbound/pg_access_check/mod.rs b/rust/cloud-storage/channels/src/outbound/pg_access_check/mod.rsnew file mode 100644index 0000000000..325d22654e--- /dev/null+++ b/rust/cloud-storage/channels/src/outbound/pg_access_check/mod.rs@@ -0,0 +1,39 @@+#[cfg(test)]+mod test;++use crate::domain::ports::ChannelAccessCheck;+use sqlx::PgPool;+use uuid::Uuid;++/// Postgres-backed channel membership check.+pub struct PgChannelAccessCheck {+ pool: PgPool,+}++impl PgChannelAccessCheck {+ /// Create a new access check with the given connection pool.+ pub fn new(pool: PgPool) -> Self {+ Self { pool }+ }+}++impl ChannelAccessCheck for PgChannelAccessCheck {+ #[tracing::instrument(err, skip(self))]+ async fn is_channel_member(+ &self,+ channel_id: Uuid,+ user_id: &str,+ ) -> Result<bool, anyhow::Error> {+ let row = sqlx::query(+ "SELECT 1 FROM comms_channel_participants \+ WHERE channel_id = $1 AND user_id = $2 AND left_at IS NULL \+ LIMIT 1",+ )+ .bind(channel_id)+ .bind(user_id)+ .fetch_optional(&self.pool)+ .await?;++ Ok(row.is_some())+ }+}diff --git a/rust/cloud-storage/channels/src/outbound/pg_access_check/test.rs b/rust/cloud-storage/channels/src/outbound/pg_access_check/test.rsnew file mode 100644index 0000000000..006d0c45d4--- /dev/null+++ b/rust/cloud-storage/channels/src/outbound/pg_access_check/test.rs@@ -0,0 +1,92 @@+use super::*;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::{Pool, Postgres};++const CH1: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000c01);+const CH2: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000c02);++fn access(pool: Pool<Postgres>) -> PgChannelAccessCheck {+ PgChannelAccessCheck::new(pool)+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn active_member_is_allowed(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let check = access(pool);+ assert!(+ check+ .is_channel_member(CH1, "macro|[email protected]")+ .await?+ );+ assert!(+ check+ .is_channel_member(CH1, "macro|[email protected]")+ .await?+ );+ assert!(+ check+ .is_channel_member(CH1, "macro|[email protected]")+ .await?+ );+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn left_user_is_denied(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let check = access(pool);+ assert!(+ !check+ .is_channel_member(CH1, "macro|[email protected]")+ .await?+ );+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn non_participant_is_denied(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let check = access(pool);+ assert!(+ !check+ .is_channel_member(CH1, "macro|[email protected]")+ .await?+ );+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn member_of_different_channel_is_denied(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let check = access(pool);+ // user-a is in CH1 but not in CH2+ assert!(+ !check+ .is_channel_member(CH2, "macro|[email protected]")+ .await?+ );+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn nonexistent_channel_is_denied(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let check = access(pool);+ let fake_channel = Uuid::from_u128(0xdeadbeef);+ assert!(+ !check+ .is_channel_member(fake_channel, "macro|[email protected]")+ .await?+ );+ Ok(())+}diff --git a/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs b/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rsindex dc877a39d8..7e5d0a41cb 100644--- a/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs+++ b/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs@@ -8,6 +8,7 @@ use crate::domain::{},ports::ChannelMessagesRepo,};+use chrono::{DateTime, Utc};use models_pagination::{CreatedAt, Query};use sqlx::PgPool;use std::collections::HashMap;@@ -377,4 +378,138 @@ impl ChannelMessagesRepo for PgChannelMessagesRepo {}).collect())}++ #[tracing::instrument(err, skip(self))]+ async fn resolve_top_level_parent(+ &self,+ channel_id: Uuid,+ message_id: Uuid,+ ) -> Result<Option<TopLevelMessageRow>, Self::Err> {+ let row = 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.id = COALESCE(+ (SELECT thread_id FROM comms_messages WHERE id = $1 AND channel_id = $2),+ $1+ )+ AND m.channel_id = $2+ AND m.thread_id IS NULL+ "#,+ message_id,+ channel_id,+ )+ .fetch_optional(&self.pool)+ .await?;++ Ok(row.map(|r| TopLevelMessageRow {+ id: r.id,+ channel_id: r.channel_id,+ sender_id: r.sender_id,+ content: r.content,+ created_at: r.created_at,+ updated_at: r.updated_at,+ edited_at: r.edited_at,+ deleted_at: r.deleted_at,+ }))+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_top_level_messages_around(+ &self,+ channel_id: Uuid,+ anchor_created_at: DateTime<Utc>,+ anchor_id: Uuid,+ limit: u16,+ ) -> Result<(Vec<TopLevelMessageRow>, Vec<TopLevelMessageRow>), Self::Err> {+ let limit_i64 = i64::from(limit);++ let before_fut = 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 (m.created_at, m.id) < ($2, $3)+ ORDER BY m.created_at DESC, m.id DESC+ LIMIT $4+ "#,+ channel_id,+ anchor_created_at,+ anchor_id,+ limit_i64,+ )+ .fetch_all(&self.pool);++ let after_fut = 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 (m.created_at, m.id) > ($2, $3)+ ORDER BY m.created_at ASC, m.id ASC+ LIMIT $4+ "#,+ channel_id,+ anchor_created_at,+ anchor_id,+ limit_i64,+ )+ .fetch_all(&self.pool);++ let (before_rows, after_rows): (Vec<TopLevelRow>, Vec<TopLevelRow>) =+ tokio::try_join!(before_fut, after_fut)?;++ let to_row = |r: TopLevelRow| TopLevelMessageRow {+ id: r.id,+ channel_id: r.channel_id,+ sender_id: r.sender_id,+ content: r.content,+ created_at: r.created_at,+ updated_at: r.updated_at,+ edited_at: r.edited_at,+ deleted_at: r.deleted_at,+ };++ let before: Vec<TopLevelMessageRow> = before_rows.into_iter().map(to_row).collect();+ let after: Vec<TopLevelMessageRow> = after_rows.into_iter().map(to_row).collect();++ Ok((before, after))+ }}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.rsindex b483aa6abb..715867d18a 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@@ -7,9 +7,12 @@ use sqlx::{Pool, Postgres};use uuid::Uuid;const CH1: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000c01);+const CH2: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000c02);const MSG1: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000001);const MSG2: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000002);const MSG3: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000003);+const REPLY1: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_00000000b001);+const REPLY5: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_00000000b005);fn repo(pool: Pool<Postgres>) -> PgChannelMessagesRepo {PgChannelMessagesRepo::new(pool)@@ -105,9 +108,8 @@ 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 ch2 = Uuid::from_u128(0x00000000_0000_0000_0000_000000000c02);let rows = repo- .get_top_level_messages(ch2, &Query::Sort(CreatedAt, ()), 50)+ .get_top_level_messages(CH2, &Query::Sort(CreatedAt, ()), 50).await?;assert_eq!(rows.len(), 1);@@ -314,3 +316,152 @@ async fn participants_roles_parsed_correctly(pool: Pool<Postgres>) -> anyhow::Reassert_eq!(member.role, ParticipantRole::Member);Ok(())}++// -- resolve_top_level_parent -------------------------------------------------++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn resolve_top_level_parent_returns_self_for_top_level(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = repo(pool);+ let row = repo.resolve_top_level_parent(CH1, MSG1).await?;++ let row = row.expect("top-level message should resolve to itself");+ assert_eq!(row.id, MSG1);+ assert_eq!(row.content, "first message");+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn resolve_top_level_parent_follows_thread_id(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);+ // REPLY1 (b001) is a reply to MSG1+ let row = repo.resolve_top_level_parent(CH1, REPLY1).await?;++ let row = row.expect("thread reply should resolve to parent");+ assert_eq!(row.id, MSG1);+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn resolve_top_level_parent_follows_reply_to_deleted_parent(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = repo(pool);+ // REPLY5 (b005) is a reply to MSG2 (which is soft-deleted but has active reply)+ let row = repo.resolve_top_level_parent(CH1, REPLY5).await?;++ let row = row.expect("reply to deleted parent should still resolve");+ assert_eq!(row.id, MSG2);+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn resolve_top_level_parent_returns_none_for_nonexistent(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = repo(pool);+ let missing = Uuid::from_u128(0xdeadbeef);+ let row = repo.resolve_top_level_parent(CH1, missing).await?;++ assert!(row.is_none(), "nonexistent message should return None");+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn resolve_top_level_parent_returns_none_for_wrong_channel(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = repo(pool);+ // MSG1 is in CH1, query it against CH2+ let row = repo.resolve_top_level_parent(CH2, MSG1).await?;++ assert!(+ row.is_none(),+ "message in different channel should return None"+ );+ Ok(())+}++// -- get_top_level_messages_around --------------------------------------------++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn around_middle_message_returns_both_sides(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);+ // Anchor on MSG2 (11:00). Before should have MSG1, after should have MSG3.+ let anchor = repo+ .resolve_top_level_parent(CH1, MSG2)+ .await?+ .expect("msg2 exists");++ let (before, after) = repo+ .get_top_level_messages_around(CH1, anchor.created_at, anchor.id, 50)+ .await?;++ let before_ids: Vec<Uuid> = before.iter().map(|r| r.id).collect();+ let after_ids: Vec<Uuid> = after.iter().map(|r| r.id).collect();++ assert_eq!(before_ids, vec![MSG1], "MSG1 is older than anchor");+ assert_eq!(after_ids, vec![MSG3], "MSG3 is newer than anchor");+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn around_oldest_message_has_no_before(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);+ let anchor = repo+ .resolve_top_level_parent(CH1, MSG1)+ .await?+ .expect("msg1 exists");++ let (before, after) = repo+ .get_top_level_messages_around(CH1, anchor.created_at, anchor.id, 50)+ .await?;++ assert!(before.is_empty(), "nothing older than MSG1");+ let after_ids: Vec<Uuid> = after.iter().map(|r| r.id).collect();+ assert_eq!(after_ids, vec![MSG2, MSG3]);+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn around_newest_message_has_no_after(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);+ let anchor = repo+ .resolve_top_level_parent(CH1, MSG3)+ .await?+ .expect("msg3 exists");++ let (before, after) = repo+ .get_top_level_messages_around(CH1, anchor.created_at, anchor.id, 50)+ .await?;++ let before_ids: Vec<Uuid> = before.iter().map(|r| r.id).collect();+ assert_eq!(before_ids, vec![MSG2, MSG1]);+ assert!(after.is_empty(), "nothing newer than MSG3");+ Ok(())+}diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rsindex 9a09fef0f8..504337fa6c 100644--- a/rust/cloud-storage/document_storage_service/src/api/context.rs+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs@@ -1,8 +1,9 @@use crate::{config::Config, service::s3::S3};use axum::extract::FromRef;use channels::{- domain::service::ChannelMessagesServiceImpl, inbound::axum_router::ChannelsRouterState,- outbound::pg_channels_repo::PgChannelMessagesRepo,+ domain::service::ChannelMessagesServiceImpl,+ inbound::axum_router::ChannelsRouterState,+ outbound::{pg_access_check::PgChannelAccessCheck, pg_channels_repo::PgChannelMessagesRepo},};use comms::{domain::service::ChannelServiceImpl,@@ -79,7 +80,7 @@ pub(crate) type CommsState = CommsRouterState<CommsChannelService>;/// Type alias for the channels router state.pub(crate) type DssChannelsState =- ChannelsRouterState<ChannelMessagesServiceImpl<PgChannelMessagesRepo>>;+ ChannelsRouterState<ChannelMessagesServiceImpl<PgChannelMessagesRepo>, PgChannelAccessCheck>;#[derive(Clone, FromRef)]pub(crate) struct ApiContext {diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rsindex a5333b404b..106b0c6415 100644--- a/rust/cloud-storage/document_storage_service/src/main.rs+++ b/rust/cloud-storage/document_storage_service/src/main.rs@@ -7,8 +7,9 @@ use crate::{};use anyhow::Context;use channels::{- domain::service::ChannelMessagesServiceImpl, inbound::axum_router::ChannelsRouterState,- outbound::pg_channels_repo::PgChannelMessagesRepo,+ domain::service::ChannelMessagesServiceImpl,+ inbound::axum_router::ChannelsRouterState,+ outbound::{pg_access_check::PgChannelAccessCheck, pg_channels_repo::PgChannelMessagesRepo},};use comms::{domain::service::ChannelServiceImpl,@@ -321,9 +322,10 @@ async fn main() -> anyhow::Result<()> {access_service: entity_access_service,pool: db.clone(),},- channels_state: ChannelsRouterState::new(ChannelMessagesServiceImpl::new(- PgChannelMessagesRepo::new(db.clone()),- )),+ channels_state: ChannelsRouterState::new(+ ChannelMessagesServiceImpl::new(PgChannelMessagesRepo::new(db.clone())),+ PgChannelAccessCheck::new(db.clone()),+ ),};api::setup_and_serve(api_context).await?;