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): hex channels crate with pagination (#1484)
teoe00020cbb3dd
diff --git a/js/app/packages/queries/channel/channel-attachments.ts b/js/app/packages/queries/channel/channel-attachments.tsnew file mode 100644index 0000000000..6b2b080315--- /dev/null+++ b/js/app/packages/queries/channel/channel-attachments.ts@@ -0,0 +1,68 @@+import { throwOnErr } from '@core/util/maybeResult';+import {+ commsServiceClient,+ type ApiChannelAttachment,+ type ChannelAttachmentsPage,+} from '@service-comms/client';+import { type InfiniteData, useInfiniteQuery } from '@tanstack/solid-query';+import { type Accessor, createMemo } from 'solid-js';+import { queryClient } from '../client';+import { channelKeys } from './keys';++export type ChannelAttachmentsData = InfiniteData<+ ChannelAttachmentsPage,+ string | null+>;++export function channelAttachmentsQueryOptions(channelId: string) {+ return {+ queryKey: channelKeys.attachments(channelId).queryKey,+ queryFn: async ({ pageParam }: { pageParam: string | null }) => {+ return await throwOnErr(+ async () =>+ await commsServiceClient.getChannelAttachments({+ channel_id: channelId,+ limit: 100,+ cursor: pageParam,+ })+ );+ },+ initialPageParam: null as string | null,+ getNextPageParam: (lastPage: ChannelAttachmentsPage) =>+ lastPage.next_cursor ?? null,+ staleTime: Infinity,+ };+}++export function useChannelAttachmentsQuery(channelId: Accessor<string>) {+ return useInfiniteQuery(() => channelAttachmentsQueryOptions(channelId()));+}++export function useChannelAttachmentsWithIndex(channelId: Accessor<string>) {+ const query = useChannelAttachmentsQuery(channelId);+ const byId = createMemo(() => {+ const flat = flattenAttachments(+ query.data as ChannelAttachmentsData | undefined+ );+ return new Map(flat.map((a) => [a.id, a]));+ });+ return { query, byId };+}++/**+ * Flatten all pages into a single newest-first array.+ * Pages arrive newest-first, items within each page are newest-first.+ */+export function flattenAttachments(+ data: ChannelAttachmentsData | undefined+): ApiChannelAttachment[] {+ if (!data?.pages?.length) return [];+ return data.pages.flatMap((page) => page.items);+}++export function softInvalidateChannelAttachments(channelId: string) {+ queryClient.invalidateQueries({+ queryKey: channelKeys.attachments(channelId).queryKey,+ refetchType: 'inactive',+ });+}diff --git a/js/app/packages/queries/channel/channel-messages.ts b/js/app/packages/queries/channel/channel-messages.tsnew file mode 100644index 0000000000..cc7a046e02--- /dev/null+++ b/js/app/packages/queries/channel/channel-messages.ts@@ -0,0 +1,76 @@+import { throwOnErr } from '@core/util/maybeResult';+import {+ commsServiceClient,+ type ApiChannelMessage,+ type ChannelMessagesPage,+} from '@service-comms/client';+import { type InfiniteData, useInfiniteQuery } from '@tanstack/solid-query';+import { type Accessor, createMemo } from 'solid-js';+import { queryClient } from '../client';+import { channelKeys } from './keys';++export type ChannelMessagesData = InfiniteData<+ ChannelMessagesPage,+ string | null+>;++export function channelMessagesQueryOptions(channelId: string) {+ return {+ queryKey: channelKeys.messages(channelId).queryKey,+ queryFn: async ({ pageParam }: { pageParam: string | null }) => {+ return await throwOnErr(+ async () =>+ await commsServiceClient.getChannelMessages({+ channel_id: channelId,+ limit: 100,+ cursor: pageParam,+ })+ );+ },+ initialPageParam: null as string | null,+ getNextPageParam: (lastPage: ChannelMessagesPage) =>+ lastPage.next_cursor ?? null,+ staleTime: Infinity,+ };+}++export function useChannelMessagesQuery(channelId: Accessor<string>) {+ return useInfiniteQuery(() => channelMessagesQueryOptions(channelId()));+}+export function useChannelMessagesWithIndex(channelId: Accessor<string>) {+ const query = useChannelMessagesQuery(channelId);+ const byId = createMemo(() => {+ const flat = flattenMessages(query.data as ChannelMessagesData | undefined);+ return new Map(flat.map((m) => [m.id, m]));+ });+ return { query, byId };+}++/**+ * Marks the channel messages query as stale without triggering an immediate refetch.+ */+export function softInvalidateChannelMessages(channelId: string) {+ queryClient.invalidateQueries({+ queryKey: channelKeys.messages(channelId).queryKey,+ refetchType: 'inactive',+ });+}++/**+ * Flatten all pages into a single oldest-first array for display.+ * Pages arrive newest-first, items within each page are newest-first,+ * so we reverse both layers.+ */+export function flattenMessages(+ data: ChannelMessagesData | undefined+): ApiChannelMessage[] {+ if (!data?.pages?.length) return [];+ const all: ApiChannelMessage[] = [];+ for (let i = data.pages.length - 1; i >= 0; i--) {+ const items = data.pages[i].items;+ for (let j = items.length - 1; j >= 0; j--) {+ all.push(items[j]);+ }+ }+ return all;+}diff --git a/js/app/packages/queries/channel/channel-participants.ts b/js/app/packages/queries/channel/channel-participants.tsnew file mode 100644index 0000000000..3950cb2aa2--- /dev/null+++ b/js/app/packages/queries/channel/channel-participants.ts@@ -0,0 +1,35 @@+import { throwOnErr } from '@core/util/maybeResult';+import {+ commsServiceClient,+ type ApiChannelParticipant,+} from '@service-comms/client';+import { useQuery } from '@tanstack/solid-query';+import type { Accessor } from 'solid-js';+import { queryClient } from '../client';+import { channelKeys } from './keys';++export function channelParticipantsQueryOptions(channelId: string) {+ return {+ queryKey: channelKeys.participants(channelId).queryKey,+ queryFn: async (): Promise<ApiChannelParticipant[]> => {+ return await throwOnErr(+ async () =>+ await commsServiceClient.getChannelParticipants({+ channel_id: channelId,+ })+ );+ },+ staleTime: Infinity,+ };+}++export function useChannelParticipantsQuery(channelId: Accessor<string>) {+ return useQuery(() => channelParticipantsQueryOptions(channelId()));+}++export function softInvalidateChannelParticipants(channelId: string) {+ queryClient.invalidateQueries({+ queryKey: channelKeys.participants(channelId).queryKey,+ refetchType: 'inactive',+ });+}diff --git a/js/app/packages/queries/channel/keys.ts b/js/app/packages/queries/channel/keys.tsindex dee6d8b768..d3eff4869e 100644--- a/js/app/packages/queries/channel/keys.ts+++ b/js/app/packages/queries/channel/keys.ts@@ -7,6 +7,15 @@ export const channelKeys = createQueryKeys('channel', {mentions: (channelID: string) => ({queryKey: [channelID],}),+ messages: (channelID: string) => ({+ queryKey: [channelID],+ }),+ attachments: (channelID: string) => ({+ queryKey: [channelID],+ }),+ participants: (channelID: string) => ({+ queryKey: [channelID],+ }),activity: null,listChannels: null,});diff --git a/js/app/packages/service-clients/service-comms/client.ts b/js/app/packages/service-clients/service-comms/client.tsindex d8867aceb1..eb3838acec 100644--- a/js/app/packages/service-clients/service-comms/client.ts+++ b/js/app/packages/service-clients/service-comms/client.ts@@ -40,6 +40,16 @@ import type { PostTypingRequest } from './generated/models/postTypingRequest';import type { RemoveParticipantsRequest } from './generated/models/removeParticipantsRequest';import { ChannelType } from './generated/models/channelType';+import type { ApiChannelMessagesPage } from '@service-storage/generated/schemas/apiChannelMessagesPage';+import type { ApiChannelAttachmentsPage } from '@service-storage/generated/schemas/apiChannelAttachmentsPage';+import type { ApiChannelParticipant } from '@service-storage/generated/schemas/apiChannelParticipant';++export type { ApiChannelMessage } from '@service-storage/generated/schemas/apiChannelMessage';+export type { ApiChannelMessagesPage as ChannelMessagesPage } from '@service-storage/generated/schemas/apiChannelMessagesPage';+export type { ApiChannelAttachment } from '@service-storage/generated/schemas/apiChannelAttachment';+export type { ApiChannelAttachmentsPage as ChannelAttachmentsPage } from '@service-storage/generated/schemas/apiChannelAttachmentsPage';+export type { ApiChannelParticipant } from '@service-storage/generated/schemas/apiChannelParticipant';+const commsHost: string = SERVER_HOSTS['document-storage-service'];export function commsFetch(@@ -360,4 +370,44 @@ export const commsServiceClient = {(result) => result);},+ async getChannelMessages(+ args: WithChannelId & { limit: number; cursor: string | null }+ ) {+ const { channel_id, limit, cursor } = args;+ const params = new URLSearchParams();+ params.append('limit', limit.toString());+ if (cursor) params.append('cursor', cursor);+ return mapOk(+ await commsFetch<ApiChannelMessagesPage>(+ `/channels/${channel_id}/messages?${params.toString()}`,+ { method: 'GET' }+ ),+ (result) => result+ );+ },+ async getChannelAttachments(+ args: WithChannelId & { limit: number; cursor: string | null }+ ) {+ const { channel_id, limit, cursor } = args;+ const params = new URLSearchParams();+ params.append('limit', limit.toString());+ if (cursor) params.append('cursor', cursor);+ return mapOk(+ await commsFetch<ApiChannelAttachmentsPage>(+ `/channels/${channel_id}/attachments?${params.toString()}`,+ { method: 'GET' }+ ),+ (result) => result+ );+ },+ async getChannelParticipants(args: WithChannelId) {+ const { channel_id } = args;+ return mapOk(+ await commsFetch<ApiChannelParticipant[]>(+ `/channels/${channel_id}/participants`,+ { method: 'GET' }+ ),+ (result) => result+ );+ },};diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelAttachment.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelAttachment.tsnew file mode 100644index 0000000000..07e09b5951--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelAttachment.ts@@ -0,0 +1,30 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiChannelAttachmentHeight } from './apiChannelAttachmentHeight';+import type { ApiChannelAttachmentWidth } from './apiChannelAttachmentWidth';++/**+ * A channel-level attachment.+ */+export interface ApiChannelAttachment {+ /** Channel id. */+ channel_id: string;+ /** When the attachment was created. */+ created_at: string;+ /** Entity id. */+ entity_id: string;+ /** Type of entity. */+ entity_type: string;+ /** Height (for images). */+ height?: ApiChannelAttachmentHeight;+ /** Attachment id. */+ id: string;+ /** Message id this attachment belongs to. */+ message_id: string;+ /** Width (for images). */+ width?: ApiChannelAttachmentWidth;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelAttachmentHeight.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelAttachmentHeight.tsnew file mode 100644index 0000000000..db47bc6f69--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelAttachmentHeight.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Height (for images).+ */+export type ApiChannelAttachmentHeight = number | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelAttachmentWidth.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelAttachmentWidth.tsnew file mode 100644index 0000000000..eaeb69665f--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelAttachmentWidth.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Width (for images).+ */+export type ApiChannelAttachmentWidth = number | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelAttachmentsPage.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelAttachmentsPage.tsnew file mode 100644index 0000000000..1f09d30034--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelAttachmentsPage.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiChannelAttachment } from './apiChannelAttachment';+import type { ApiChannelAttachmentsPageNextCursor } from './apiChannelAttachmentsPageNextCursor';++/**+ * Paginated response of channel attachments.+ */+export interface ApiChannelAttachmentsPage {+ /** Attachments on this page. */+ items: ApiChannelAttachment[];+ /** Cursor for the next page, null if no more pages. */+ next_cursor?: ApiChannelAttachmentsPageNextCursor;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelAttachmentsPageNextCursor.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelAttachmentsPageNextCursor.tsnew file mode 100644index 0000000000..a30c871d26--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelAttachmentsPageNextCursor.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 next page, null if no more pages.+ */+export type ApiChannelAttachmentsPageNextCursor = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelMessage.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelMessage.tsnew file mode 100644index 0000000000..c0330838c9--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelMessage.ts@@ -0,0 +1,40 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++import type { ApiChannelMessageDeletedAt } from './apiChannelMessageDeletedAt';+import type { ApiChannelMessageEditedAt } from './apiChannelMessageEditedAt';+import type { ApiCountedReaction } from './apiCountedReaction';+import type { ApiMessageAttachment } from './apiMessageAttachment';+import type { ApiThreadInfo } from './apiThreadInfo';++/**+ * A top-level channel message with thread info.+ */+export interface ApiChannelMessage {+ /** Attachments on this message. */+ attachments: ApiMessageAttachment[];+ /** Channel id. */+ channel_id: string;+ /** Message content. */+ content: string;+ /** When the message was created. */+ created_at: string;+ /** When the message was soft-deleted. */+ deleted_at?: ApiChannelMessageDeletedAt;+ /** When the message was edited. */+ edited_at?: ApiChannelMessageEditedAt;+ /** Message id. */+ id: string;+ /** Reactions on this message. */+ reactions: ApiCountedReaction[];+ /** Sender user id. */+ sender_id: string;+ /** Thread metadata and preview. */+ thread: ApiThreadInfo;+ /** When the message was last updated. */+ updated_at: string;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelMessageDeletedAt.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelMessageDeletedAt.tsnew file mode 100644index 0000000000..68c63c6abb--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelMessageDeletedAt.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * When the message was soft-deleted.+ */+export type ApiChannelMessageDeletedAt = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelMessageEditedAt.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelMessageEditedAt.tsnew file mode 100644index 0000000000..cdfe1132c0--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelMessageEditedAt.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * When the message was edited.+ */+export type ApiChannelMessageEditedAt = string | null;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.tsnew file mode 100644index 0000000000..f5dfd702fc--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelMessagesPage.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiChannelMessage } from './apiChannelMessage';+import type { ApiChannelMessagesPageNextCursor } from './apiChannelMessagesPageNextCursor';++/**+ * Paginated response of channel messages.+ */+export interface ApiChannelMessagesPage {+ /** Messages on this page. */+ items: ApiChannelMessage[];+ /** Cursor for the next page, null if no more pages. */+ next_cursor?: ApiChannelMessagesPageNextCursor;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelMessagesPageNextCursor.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelMessagesPageNextCursor.tsnew file mode 100644index 0000000000..ff7e5dc070--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelMessagesPageNextCursor.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 next page, null if no more pages.+ */+export type ApiChannelMessagesPageNextCursor = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelParticipant.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelParticipant.tsnew file mode 100644index 0000000000..f5e168e465--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelParticipant.ts@@ -0,0 +1,21 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiParticipantRole } from './apiParticipantRole';++/**+ * A channel participant.+ */+export interface ApiChannelParticipant {+ /** Channel id. */+ channel_id: string;+ /** When the user joined. */+ joined_at: string;+ /** Role in the channel. */+ role: ApiParticipantRole;+ /** User id. */+ user_id: string;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiCountedReaction.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiCountedReaction.tsnew file mode 100644index 0000000000..06723ee62a--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiCountedReaction.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * A reaction with emoji and user list.+ */+export interface ApiCountedReaction {+ /** The emoji string. */+ emoji: string;+ /** User ids who added this reaction. */+ users: string[];+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiMessageAttachment.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiMessageAttachment.tsnew file mode 100644index 0000000000..3525415dd8--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiMessageAttachment.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * An attachment on a message.+ */+export interface ApiMessageAttachment {+ /** When the attachment was created. */+ created_at: string;+ /** Entity id. */+ entity_id: string;+ /** Type of entity. */+ entity_type: string;+ /** Attachment id. */+ id: string;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiParticipantRole.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiParticipantRole.tsnew file mode 100644index 0000000000..41b8269068--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiParticipantRole.ts@@ -0,0 +1,19 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Participant role in a channel.+ */+export type ApiParticipantRole =+ (typeof ApiParticipantRole)[keyof typeof ApiParticipantRole];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const ApiParticipantRole = {+ owner: 'owner',+ admin: 'admin',+ member: 'member',+} as const;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiThreadInfo.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiThreadInfo.tsnew file mode 100644index 0000000000..1adaf290d6--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiThreadInfo.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiThreadInfoLatestReplyAt } from './apiThreadInfoLatestReplyAt';+import type { ApiThreadReply } from './apiThreadReply';++/**+ * Thread metadata and preview replies.+ */+export interface ApiThreadInfo {+ /** Timestamp of the latest reply. */+ latest_reply_at?: ApiThreadInfoLatestReplyAt;+ /** Last N replies for thread preview. */+ preview: ApiThreadReply[];+ /** Total reply count. */+ reply_count: number;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiThreadInfoLatestReplyAt.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiThreadInfoLatestReplyAt.tsnew file mode 100644index 0000000000..4086f24deb--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiThreadInfoLatestReplyAt.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Timestamp of the latest reply.+ */+export type ApiThreadInfoLatestReplyAt = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiThreadReply.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiThreadReply.tsnew file mode 100644index 0000000000..b8f8985217--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiThreadReply.ts@@ -0,0 +1,32 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++import type { ApiCountedReaction } from './apiCountedReaction';+import type { ApiMessageAttachment } from './apiMessageAttachment';+import type { ApiThreadReplyEditedAt } from './apiThreadReplyEditedAt';++/**+ * A thread reply shown in preview.+ */+export interface ApiThreadReply {+ /** Attachments on this reply. */+ attachments: ApiMessageAttachment[];+ /** Reply content. */+ content: string;+ /** When the reply was created. */+ created_at: string;+ /** When the reply was edited. */+ edited_at?: ApiThreadReplyEditedAt;+ /** Reply id. */+ id: string;+ /** Reactions on this reply. */+ reactions: ApiCountedReaction[];+ /** Sender user id. */+ sender_id: string;+ /** When the reply was last updated. */+ updated_at: string;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiThreadReplyEditedAt.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiThreadReplyEditedAt.tsnew file mode 100644index 0000000000..4109dd11c1--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiThreadReplyEditedAt.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * When the reply was edited.+ */+export type ApiThreadReplyEditedAt = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/getChannelAttachmentsParams.ts b/js/app/packages/service-clients/service-storage/generated/schemas/getChannelAttachmentsParams.tsnew file mode 100644index 0000000000..7e8a0b903e--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/getChannelAttachmentsParams.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type GetChannelAttachmentsParams = {+ /**+ * Page size (1-100, default 50)+ * @minimum 0+ */+ limit?: number;+ /**+ * Base64 encoded cursor value+ */+ cursor?: string;+};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.tsnew file mode 100644index 0000000000..bf78d63b8c--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/getChannelMessagesParams.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type GetChannelMessagesParams = {+ /**+ * Page size (1-100, default 50)+ * @minimum 0+ */+ limit?: number;+ /**+ * Base64 encoded cursor value+ */+ cursor?: string;+};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.tsindex 29a4a80b21..6820e529c7 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@@ -39,6 +39,24 @@ export * from './annotationIncrementalUpdateOneOfSeven';export * from './annotationIncrementalUpdateOneOfSevenPayload';export * from './annotationIncrementalUpdateOneOfSevenUpdateType';export * from './annotationIncrementalUpdateOneOfUpdateType';+export * from './apiChannelAttachment';+export * from './apiChannelAttachmentHeight';+export * from './apiChannelAttachmentsPage';+export * from './apiChannelAttachmentsPageNextCursor';+export * from './apiChannelAttachmentWidth';+export * from './apiChannelMessage';+export * from './apiChannelMessageDeletedAt';+export * from './apiChannelMessageEditedAt';+export * from './apiChannelMessagesPage';+export * from './apiChannelMessagesPageNextCursor';+export * from './apiChannelParticipant';+export * from './apiCountedReaction';+export * from './apiMessageAttachment';+export * from './apiParticipantRole';+export * from './apiThreadInfo';+export * from './apiThreadInfoLatestReplyAt';+export * from './apiThreadReply';+export * from './apiThreadReplyEditedAt';export * from './basicDocument';export * from './basicDocumentBranchedFromId';export * from './basicDocumentBranchedFromVersionId';@@ -283,6 +301,8 @@ export * from './getBatchPreviewRequest';export * from './getBatchPreviewResponse';export * from './getBatchProjectPreviewRequest';export * from './getBatchProjectPreviewResponse';+export * from './getChannelAttachmentsParams';+export * from './getChannelMessagesParams';export * from './getDocumentKeyResponse';export * from './getDocumentKeyResponseData';export * from './getDocumentListResult';diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex dd24fe7787..42feb2175e 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -810,6 +810,230 @@ export const getDocumentCommentsResponse = zod.object({),});+/**+ * @summary Handler for `GET /channels/:channel_id/attachments`.+ */+export const getChannelAttachmentsParams = zod.object({+ channel_id: zod.string().uuid().describe('Channel ID'),+});++export const getChannelAttachmentsQueryLimitMin = 0;++export const getChannelAttachmentsQueryParams = zod.object({+ limit: zod+ .number()+ .min(getChannelAttachmentsQueryLimitMin)+ .optional()+ .describe('Page size (1-100, default 50)'),+ cursor: zod.string().optional().describe('Base64 encoded cursor value'),+});++export const getChannelAttachmentsResponse = zod+ .object({+ items: zod+ .array(+ zod+ .object({+ channel_id: zod.string().uuid().describe('Channel id.'),+ created_at: zod+ .string()+ .datetime({})+ .describe('When the attachment was created.'),+ entity_id: zod.string().describe('Entity id.'),+ entity_type: zod.string().describe('Type of entity.'),+ height: zod.number().nullish().describe('Height (for images).'),+ id: zod.string().uuid().describe('Attachment id.'),+ message_id: zod+ .string()+ .uuid()+ .describe('Message id this attachment belongs to.'),+ width: zod.number().nullish().describe('Width (for images).'),+ })+ .describe('A channel-level attachment.')+ )+ .describe('Attachments on this page.'),+ next_cursor: zod+ .string()+ .nullish()+ .describe('Cursor for the next page, null if no more pages.'),+ })+ .describe('Paginated response of channel attachments.');++/**+ * @summary Handler for `GET /channels/:channel_id/messages`.+ */+export const getChannelMessagesParams = zod.object({+ channel_id: zod.string().uuid().describe('Channel ID'),+});++export const getChannelMessagesQueryLimitMin = 0;++export const getChannelMessagesQueryParams = zod.object({+ limit: zod+ .number()+ .min(getChannelMessagesQueryLimitMin)+ .optional()+ .describe('Page size (1-100, default 50)'),+ cursor: zod.string().optional().describe('Base64 encoded cursor value'),+});++export const getChannelMessagesResponse = zod+ .object({+ items: zod+ .array(+ zod+ .object({+ attachments: zod+ .array(+ zod+ .object({+ created_at: zod+ .string()+ .datetime({})+ .describe('When the attachment was created.'),+ entity_id: zod.string().describe('Entity id.'),+ entity_type: zod.string().describe('Type of entity.'),+ id: zod.string().uuid().describe('Attachment id.'),+ })+ .describe('An attachment on a message.')+ )+ .describe('Attachments on this message.'),+ channel_id: zod.string().uuid().describe('Channel id.'),+ content: zod.string().describe('Message content.'),+ created_at: zod+ .string()+ .datetime({})+ .describe('When the message was created.'),+ deleted_at: zod+ .string()+ .datetime({})+ .nullish()+ .describe('When the message was soft-deleted.'),+ edited_at: zod+ .string()+ .datetime({})+ .nullish()+ .describe('When the message was edited.'),+ id: zod.string().uuid().describe('Message id.'),+ reactions: zod+ .array(+ zod+ .object({+ emoji: zod.string().describe('The emoji string.'),+ users: zod+ .array(zod.string())+ .describe('User ids who added this reaction.'),+ })+ .describe('A reaction with emoji and user list.')+ )+ .describe('Reactions on this message.'),+ sender_id: zod.string().describe('Sender user id.'),+ thread: zod+ .object({+ latest_reply_at: zod+ .string()+ .datetime({})+ .nullish()+ .describe('Timestamp of the latest reply.'),+ preview: zod+ .array(+ zod+ .object({+ attachments: zod+ .array(+ zod+ .object({+ created_at: zod+ .string()+ .datetime({})+ .describe('When the attachment was created.'),+ entity_id: zod.string().describe('Entity id.'),+ entity_type: zod+ .string()+ .describe('Type of entity.'),+ id: zod+ .string()+ .uuid()+ .describe('Attachment id.'),+ })+ .describe('An attachment on a message.')+ )+ .describe('Attachments on this reply.'),+ content: zod.string().describe('Reply content.'),+ created_at: zod+ .string()+ .datetime({})+ .describe('When the reply was created.'),+ edited_at: zod+ .string()+ .datetime({})+ .nullish()+ .describe('When the reply was edited.'),+ id: zod.string().uuid().describe('Reply id.'),+ reactions: zod+ .array(+ zod+ .object({+ emoji: zod+ .string()+ .describe('The emoji string.'),+ users: zod+ .array(zod.string())+ .describe(+ 'User ids who added this reaction.'+ ),+ })+ .describe('A reaction with emoji and user list.')+ )+ .describe('Reactions on this reply.'),+ sender_id: zod.string().describe('Sender user id.'),+ updated_at: zod+ .string()+ .datetime({})+ .describe('When the reply was last updated.'),+ })+ .describe('A thread reply shown in preview.')+ )+ .describe('Last N replies for thread preview.'),+ reply_count: zod.number().describe('Total reply count.'),+ })+ .describe('Thread metadata and preview replies.'),+ updated_at: zod+ .string()+ .datetime({})+ .describe('When the message was last updated.'),+ })+ .describe('A top-level channel message with thread info.')+ )+ .describe('Messages on this page.'),+ next_cursor: zod+ .string()+ .nullish()+ .describe('Cursor for the next page, null if no more pages.'),+ })+ .describe('Paginated response of channel messages.');++/**+ * @summary Handler for `GET /channels/:channel_id/participants`.+ */+export const getChannelParticipantsParams = zod.object({+ channel_id: zod.string().uuid().describe('Channel ID'),+});++export const getChannelParticipantsResponseItem = zod+ .object({+ channel_id: zod.string().uuid().describe('Channel id.'),+ joined_at: zod.string().datetime({}).describe('When the user joined.'),+ role: zod+ .enum(['owner', 'admin', 'member'])+ .describe('Participant role in a channel.'),+ user_id: zod.string().describe('User id.'),+ })+ .describe('A channel participant.');+export const getChannelParticipantsResponse = zod.array(+ getChannelParticipantsResponseItem+);+/*** @summary Gets the users documents to populate their recent document list*/diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex 974cc732d2..939780d3a7 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -598,6 +598,172 @@}}},+ "/channels/{channel_id}/attachments": {+ "get": {+ "tags": ["channels::inbound::axum_router"],+ "summary": "Handler for `GET /channels/:channel_id/attachments`.",+ "operationId": "get_channel_attachments",+ "parameters": [+ {+ "name": "channel_id",+ "in": "path",+ "description": "Channel ID",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ },+ {+ "name": "limit",+ "in": "query",+ "description": "Page size (1-100, default 50)",+ "required": false,+ "schema": {+ "type": "integer",+ "format": "int32",+ "minimum": 0+ }+ },+ {+ "name": "cursor",+ "in": "query",+ "description": "Base64 encoded cursor value",+ "required": false,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiChannelAttachmentsPage"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/channels/{channel_id}/messages": {+ "get": {+ "tags": ["channels::inbound::axum_router"],+ "summary": "Handler for `GET /channels/:channel_id/messages`.",+ "operationId": "get_channel_messages",+ "parameters": [+ {+ "name": "channel_id",+ "in": "path",+ "description": "Channel ID",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ },+ {+ "name": "limit",+ "in": "query",+ "description": "Page size (1-100, default 50)",+ "required": false,+ "schema": {+ "type": "integer",+ "format": "int32",+ "minimum": 0+ }+ },+ {+ "name": "cursor",+ "in": "query",+ "description": "Base64 encoded cursor value",+ "required": false,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiChannelMessagesPage"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/channels/{channel_id}/participants": {+ "get": {+ "tags": ["channels::inbound::axum_router"],+ "summary": "Handler for `GET /channels/:channel_id/participants`.",+ "operationId": "get_channel_participants",+ "parameters": [+ {+ "name": "channel_id",+ "in": "path",+ "description": "Channel ID",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ApiChannelParticipant"+ }+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/documents": {"get": {"tags": ["document"],@@ -4519,6 +4685,321 @@}]},+ "ApiChannelAttachment": {+ "type": "object",+ "description": "A channel-level attachment.",+ "required": [+ "id",+ "channel_id",+ "message_id",+ "entity_type",+ "entity_id",+ "created_at"+ ],+ "properties": {+ "channel_id": {+ "type": "string",+ "format": "uuid",+ "description": "Channel id."+ },+ "created_at": {+ "type": "string",+ "format": "date-time",+ "description": "When the attachment was created."+ },+ "entity_id": {+ "type": "string",+ "description": "Entity id."+ },+ "entity_type": {+ "type": "string",+ "description": "Type of entity."+ },+ "height": {+ "type": ["integer", "null"],+ "format": "int32",+ "description": "Height (for images)."+ },+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "Attachment id."+ },+ "message_id": {+ "type": "string",+ "format": "uuid",+ "description": "Message id this attachment belongs to."+ },+ "width": {+ "type": ["integer", "null"],+ "format": "int32",+ "description": "Width (for images)."+ }+ }+ },+ "ApiChannelAttachmentsPage": {+ "type": "object",+ "description": "Paginated response of channel attachments.",+ "required": ["items"],+ "properties": {+ "items": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ApiChannelAttachment"+ },+ "description": "Attachments on this page."+ },+ "next_cursor": {+ "type": ["string", "null"],+ "description": "Cursor for the next page, null if no more pages."+ }+ }+ },+ "ApiChannelMessage": {+ "type": "object",+ "description": "A top-level channel message with thread info.",+ "required": [+ "id",+ "channel_id",+ "sender_id",+ "content",+ "created_at",+ "updated_at",+ "thread",+ "reactions",+ "attachments"+ ],+ "properties": {+ "attachments": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ApiMessageAttachment"+ },+ "description": "Attachments on this message."+ },+ "channel_id": {+ "type": "string",+ "format": "uuid",+ "description": "Channel id."+ },+ "content": {+ "type": "string",+ "description": "Message content."+ },+ "created_at": {+ "type": "string",+ "format": "date-time",+ "description": "When the message was created."+ },+ "deleted_at": {+ "type": ["string", "null"],+ "format": "date-time",+ "description": "When the message was soft-deleted."+ },+ "edited_at": {+ "type": ["string", "null"],+ "format": "date-time",+ "description": "When the message was edited."+ },+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "Message id."+ },+ "reactions": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ApiCountedReaction"+ },+ "description": "Reactions on this message."+ },+ "sender_id": {+ "type": "string",+ "description": "Sender user id."+ },+ "thread": {+ "$ref": "#/components/schemas/ApiThreadInfo",+ "description": "Thread metadata and preview."+ },+ "updated_at": {+ "type": "string",+ "format": "date-time",+ "description": "When the message was last updated."+ }+ }+ },+ "ApiChannelMessagesPage": {+ "type": "object",+ "description": "Paginated response of channel messages.",+ "required": ["items"],+ "properties": {+ "items": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ApiChannelMessage"+ },+ "description": "Messages on this page."+ },+ "next_cursor": {+ "type": ["string", "null"],+ "description": "Cursor for the next page, null if no more pages."+ }+ }+ },+ "ApiChannelParticipant": {+ "type": "object",+ "description": "A channel participant.",+ "required": ["channel_id", "user_id", "role", "joined_at"],+ "properties": {+ "channel_id": {+ "type": "string",+ "format": "uuid",+ "description": "Channel id."+ },+ "joined_at": {+ "type": "string",+ "format": "date-time",+ "description": "When the user joined."+ },+ "role": {+ "$ref": "#/components/schemas/ApiParticipantRole",+ "description": "Role in the channel."+ },+ "user_id": {+ "type": "string",+ "description": "User id."+ }+ }+ },+ "ApiCountedReaction": {+ "type": "object",+ "description": "A reaction with emoji and user list.",+ "required": ["emoji", "users"],+ "properties": {+ "emoji": {+ "type": "string",+ "description": "The emoji string."+ },+ "users": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "User ids who added this reaction."+ }+ }+ },+ "ApiMessageAttachment": {+ "type": "object",+ "description": "An attachment on a message.",+ "required": ["id", "entity_type", "entity_id", "created_at"],+ "properties": {+ "created_at": {+ "type": "string",+ "format": "date-time",+ "description": "When the attachment was created."+ },+ "entity_id": {+ "type": "string",+ "description": "Entity id."+ },+ "entity_type": {+ "type": "string",+ "description": "Type of entity."+ },+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "Attachment id."+ }+ }+ },+ "ApiParticipantRole": {+ "type": "string",+ "description": "Participant role in a channel.",+ "enum": ["owner", "admin", "member"]+ },+ "ApiThreadInfo": {+ "type": "object",+ "description": "Thread metadata and preview replies.",+ "required": ["reply_count", "preview"],+ "properties": {+ "latest_reply_at": {+ "type": ["string", "null"],+ "format": "date-time",+ "description": "Timestamp of the latest reply."+ },+ "preview": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ApiThreadReply"+ },+ "description": "Last N replies for thread preview."+ },+ "reply_count": {+ "type": "integer",+ "format": "int64",+ "description": "Total reply count."+ }+ }+ },+ "ApiThreadReply": {+ "type": "object",+ "description": "A thread reply shown in preview.",+ "required": [+ "id",+ "sender_id",+ "content",+ "created_at",+ "updated_at",+ "reactions",+ "attachments"+ ],+ "properties": {+ "attachments": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ApiMessageAttachment"+ },+ "description": "Attachments on this reply."+ },+ "content": {+ "type": "string",+ "description": "Reply content."+ },+ "created_at": {+ "type": "string",+ "format": "date-time",+ "description": "When the reply was created."+ },+ "edited_at": {+ "type": ["string", "null"],+ "format": "date-time",+ "description": "When the reply was edited."+ },+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "Reply id."+ },+ "reactions": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ApiCountedReaction"+ },+ "description": "Reactions on this reply."+ },+ "sender_id": {+ "type": "string",+ "description": "Sender user id."+ },+ "updated_at": {+ "type": "string",+ "format": "date-time",+ "description": "When the reply was last updated."+ }+ }+ },"BasicDocument": {"type": "object","required": ["id", "documentVersionId", "owner", "name"],diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex bdd334c219..a786348f9b 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -1685,6 +1685,30 @@ version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"+[[package]]+name = "channels"+version = "0.1.0"+dependencies = [+ "anyhow",+ "axum",+ "chrono",+ "http-body-util",+ "macro_db_migrator",+ "mockall",+ "model-error-response",+ "model_user",+ "models_pagination",+ "serde",+ "serde_json",+ "sqlx",+ "thiserror 2.0.17",+ "tokio",+ "tower 0.5.2",+ "tracing",+ "utoipa",+ "uuid",+]+[[package]]name = "charset"version = "0.1.5"@@ -2731,6 +2755,7 @@ dependencies = ["base64 0.22.1","bytes","bzip2",+ "channels","chrono","clap","cloudfront_sign",diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex f18cd6d591..4ec08699ba 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -8,6 +8,7 @@ members = ["ai_toolset","anthropic","authentication_service",+ "channels","authentication_service_client","comms_db_client","comms_service",diff --git a/rust/cloud-storage/channels/.sqlx/query-4760be157b671303b9a00690179b7fa85258f1fb5b0f73de16eaef3a683fcdf9.json b/rust/cloud-storage/channels/.sqlx/query-4760be157b671303b9a00690179b7fa85258f1fb5b0f73de16eaef3a683fcdf9.jsonnew file mode 100644index 0000000000..04b9bd7034--- /dev/null+++ b/rust/cloud-storage/channels/.sqlx/query-4760be157b671303b9a00690179b7fa85258f1fb5b0f73de16eaef3a683fcdf9.json@@ -0,0 +1,46 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, message_id, entity_type, entity_id, created_at\n FROM comms_attachments\n WHERE message_id = ANY($1)\n ORDER BY created_at ASC\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "message_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "entity_type",+ "type_info": "Varchar"+ },+ {+ "ordinal": 3,+ "name": "entity_id",+ "type_info": "Varchar"+ },+ {+ "ordinal": 4,+ "name": "created_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "UuidArray"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false+ ]+ },+ "hash": "4760be157b671303b9a00690179b7fa85258f1fb5b0f73de16eaef3a683fcdf9"+}diff --git a/rust/cloud-storage/channels/.sqlx/query-4aff42ef43f7b7ef454cc331d2e96f3fc28bd7c823b9eb181eb0c9fba7635c37.json b/rust/cloud-storage/channels/.sqlx/query-4aff42ef43f7b7ef454cc331d2e96f3fc28bd7c823b9eb181eb0c9fba7635c37.jsonnew file mode 100644index 0000000000..223860f0ff--- /dev/null+++ b/rust/cloud-storage/channels/.sqlx/query-4aff42ef43f7b7ef454cc331d2e96f3fc28bd7c823b9eb181eb0c9fba7635c37.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT message_id, emoji, user_id\n FROM comms_reactions\n WHERE message_id = ANY($1)\n ORDER BY created_at ASC\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "message_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "emoji",+ "type_info": "Varchar"+ },+ {+ "ordinal": 2,+ "name": "user_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "UuidArray"+ ]+ },+ "nullable": [+ false,+ false,+ false+ ]+ },+ "hash": "4aff42ef43f7b7ef454cc331d2e96f3fc28bd7c823b9eb181eb0c9fba7635c37"+}diff --git a/rust/cloud-storage/channels/.sqlx/query-54732f9baff7727d260859089cdd11700b9918470e0967a347a7687944fcb1e4.json b/rust/cloud-storage/channels/.sqlx/query-54732f9baff7727d260859089cdd11700b9918470e0967a347a7687944fcb1e4.jsonnew file mode 100644index 0000000000..957b640651--- /dev/null+++ b/rust/cloud-storage/channels/.sqlx/query-54732f9baff7727d260859089cdd11700b9918470e0967a347a7687944fcb1e4.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 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": [+ {+ "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": "54732f9baff7727d260859089cdd11700b9918470e0967a347a7687944fcb1e4"+}diff --git a/rust/cloud-storage/channels/.sqlx/query-935a3a59b6f7df8eac7cb9ba86bdde343a009e04e6735d3c0f8fb26dfbab4213.json b/rust/cloud-storage/channels/.sqlx/query-935a3a59b6f7df8eac7cb9ba86bdde343a009e04e6735d3c0f8fb26dfbab4213.jsonnew file mode 100644index 0000000000..0cbd192868--- /dev/null+++ b/rust/cloud-storage/channels/.sqlx/query-935a3a59b6f7df8eac7cb9ba86bdde343a009e04e6735d3c0f8fb26dfbab4213.json@@ -0,0 +1,67 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, channel_id, message_id, entity_type, entity_id,\n width AS \"width?\", height AS \"height?\", created_at\n FROM comms_attachments\n WHERE channel_id = $1\n AND ($2::timestamptz IS NULL OR (created_at, id) < ($2, $3))\n ORDER BY created_at DESC, 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": "message_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 3,+ "name": "entity_type",+ "type_info": "Varchar"+ },+ {+ "ordinal": 4,+ "name": "entity_id",+ "type_info": "Varchar"+ },+ {+ "ordinal": 5,+ "name": "width?",+ "type_info": "Int4"+ },+ {+ "ordinal": 6,+ "name": "height?",+ "type_info": "Int4"+ },+ {+ "ordinal": 7,+ "name": "created_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Timestamptz",+ "Uuid",+ "Int8"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ true,+ true,+ false+ ]+ },+ "hash": "935a3a59b6f7df8eac7cb9ba86bdde343a009e04e6735d3c0f8fb26dfbab4213"+}diff --git a/rust/cloud-storage/channels/.sqlx/query-b9a4ad717639aa71706e8476ac7eb030794f34cd8e05cc7dff262602d12ddcba.json b/rust/cloud-storage/channels/.sqlx/query-b9a4ad717639aa71706e8476ac7eb030794f34cd8e05cc7dff262602d12ddcba.jsonnew file mode 100644index 0000000000..8bb9e6f828--- /dev/null+++ b/rust/cloud-storage/channels/.sqlx/query-b9a4ad717639aa71706e8476ac7eb030794f34cd8e05cc7dff262602d12ddcba.json@@ -0,0 +1,46 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT channel_id, user_id, role::text AS \"role!\", joined_at,\n left_at AS \"left_at?\"\n FROM comms_channel_participants\n WHERE channel_id = $1 AND left_at IS NULL\n ORDER BY joined_at ASC\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "channel_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "role!",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "joined_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 4,+ "name": "left_at?",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ null,+ false,+ true+ ]+ },+ "hash": "b9a4ad717639aa71706e8476ac7eb030794f34cd8e05cc7dff262602d12ddcba"+}diff --git a/rust/cloud-storage/channels/.sqlx/query-e07a1b0b46445b02321a5a64420ed6d987af073a0868db4aaf9dd3cd5b78eddd.json b/rust/cloud-storage/channels/.sqlx/query-e07a1b0b46445b02321a5a64420ed6d987af073a0868db4aaf9dd3cd5b78eddd.jsonnew file mode 100644index 0000000000..c95d0e5136--- /dev/null+++ b/rust/cloud-storage/channels/.sqlx/query-e07a1b0b46445b02321a5a64420ed6d987af073a0868db4aaf9dd3cd5b78eddd.json@@ -0,0 +1,71 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n id AS \"id!\", thread_id AS \"thread_id!\", sender_id AS \"sender_id!\",\n content AS \"content!\", created_at AS \"created_at!\", updated_at AS \"updated_at!\",\n edited_at::timestamptz AS \"edited_at?\",\n reply_count AS \"reply_count!\", latest_reply_at AS \"latest_reply_at?\"\n FROM (\n SELECT\n r.id,\n r.thread_id,\n r.sender_id,\n r.content,\n r.created_at,\n r.updated_at,\n r.edited_at,\n COUNT(*) OVER (PARTITION BY r.thread_id) AS reply_count,\n MAX(r.created_at) OVER (PARTITION BY r.thread_id)::timestamptz AS latest_reply_at,\n ROW_NUMBER() OVER (PARTITION BY r.thread_id ORDER BY r.created_at DESC) AS rn\n FROM comms_messages r\n WHERE r.thread_id = ANY($1) AND r.deleted_at IS NULL\n ) sub\n WHERE rn <= $2\n ORDER BY thread_id, created_at ASC\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "thread_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": "reply_count!",+ "type_info": "Int8"+ },+ {+ "ordinal": 8,+ "name": "latest_reply_at?",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "UuidArray",+ "Int8"+ ]+ },+ "nullable": [+ false,+ true,+ false,+ false,+ false,+ false,+ null,+ null,+ null+ ]+ },+ "hash": "e07a1b0b46445b02321a5a64420ed6d987af073a0868db4aaf9dd3cd5b78eddd"+}diff --git a/rust/cloud-storage/channels/Cargo.toml b/rust/cloud-storage/channels/Cargo.tomlnew file mode 100644index 0000000000..764ee4d13f--- /dev/null+++ b/rust/cloud-storage/channels/Cargo.toml@@ -0,0 +1,40 @@+[package]+edition = "2024"+name = "channels"+publish = false+version = "0.1.0"++[features]+inbound = [+ "dep:axum",+ "dep:model-error-response",+ "dep:model_user",+ "dep:utoipa",+ "models_pagination/axum",+ "ports",+]+outbound = ["ports"]+ports = ["dep:tokio"]++[dependencies]+anyhow = { workspace = true }+axum = { workspace = true, optional = true }+chrono = { workspace = true }+model-error-response = { path = "../model-error-response", optional = true }+model_user = { path = "../model_user", optional = true, features = ["axum"] }+models_pagination = { path = "../models_pagination" }+serde = { workspace = true }+sqlx = { workspace = true }+thiserror = { workspace = true }+tokio = { workspace = true, features = ["macros"], optional = true }+tracing = { workspace = true }+utoipa = { workspace = true, optional = true }+uuid = { workspace = true }++[dev-dependencies]+http-body-util = { workspace = true }+macro_db_migrator = { path = "../macro_db_migrator" }+mockall = { workspace = true }+serde_json = { workspace = true }+tokio = { workspace = true }+tower = { workspace = true }diff --git a/rust/cloud-storage/channels/fixtures/channels_repo.sql b/rust/cloud-storage/channels/fixtures/channels_repo.sqlnew file mode 100644index 0000000000..5b9a7ddf78--- /dev/null+++ b/rust/cloud-storage/channels/fixtures/channels_repo.sql@@ -0,0 +1,93 @@+-- Fixture for channels outbound repo integration tests.+--+-- Channel: ch1 (public, in org 1)+-- Top-level messages: msg1 (oldest), msg2, msg3 (newest)+-- msg1 has a thread with 4 replies (r1..r4), reactions, and an attachment+-- msg2 is soft-deleted but has an active reply → should still appear+-- msg3 is a normal message with no thread+--+-- Also:+-- deleted_msg: soft-deleted with no active replies → should NOT appear+-- Channel: ch2 (separate channel for isolation tests)+-- Participants: owner, admin, member (active), left_user (left)++-- channels+INSERT INTO comms_channels (id, name, channel_type, org_id, owner_id, created_at, updated_at) VALUES+ ('00000000-0000-0000-0000-000000000c01', 'test-channel', 'public', NULL, 'macro|[email protected]',+ '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00'),+ ('00000000-0000-0000-0000-000000000c02', 'other-channel', 'public', NULL, 'macro|[email protected]',+ '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00');++-- top-level messages in ch1 (thread_id IS NULL)+INSERT INTO comms_messages (id, channel_id, thread_id, sender_id, content, created_at, updated_at, edited_at, deleted_at) VALUES+ -- msg1: oldest, has thread+ ('00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000c01', NULL,+ 'macro|[email protected]', 'first message', '2024-01-01 10:00:00+00', '2024-01-01 10:00:00+00', NULL, NULL),+ -- msg2: soft-deleted but has active reply → should appear+ ('00000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000c01', NULL,+ 'macro|[email protected]', 'deleted with reply', '2024-01-01 11:00:00+00', '2024-01-01 11:00:00+00', NULL, '2024-01-02 00:00:00'),+ -- msg3: newest, edited+ ('00000000-0000-0000-0000-000000000003', '00000000-0000-0000-0000-000000000c01', NULL,+ 'macro|[email protected]', 'third message edited', '2024-01-01 12:00:00+00', '2024-01-01 13:00:00+00', '2024-01-01 13:00:00', NULL),+ -- deleted_msg: soft-deleted with NO active replies → should NOT appear+ ('00000000-0000-0000-0000-000000000004', '00000000-0000-0000-0000-000000000c01', NULL,+ 'macro|[email protected]', 'fully deleted', '2024-01-01 09:00:00+00', '2024-01-01 09:00:00+00', NULL, '2024-01-02 00:00:00'),+ -- message in ch2 for isolation+ ('00000000-0000-0000-0000-000000000005', '00000000-0000-0000-0000-000000000c02', NULL,+ 'macro|[email protected]', 'other channel msg', '2024-01-01 10:00:00+00', '2024-01-01 10:00:00+00', NULL, NULL);++-- thread replies under msg1 (4 replies)+INSERT INTO comms_messages (id, channel_id, thread_id, sender_id, content, created_at, updated_at, edited_at, deleted_at) VALUES+ ('00000000-0000-0000-0000-00000000b001', '00000000-0000-0000-0000-000000000c01',+ '00000000-0000-0000-0000-000000000001', 'macro|[email protected]', 'reply 1',+ '2024-01-01 10:01:00+00', '2024-01-01 10:01:00+00', NULL, NULL),+ ('00000000-0000-0000-0000-00000000b002', '00000000-0000-0000-0000-000000000c01',+ '00000000-0000-0000-0000-000000000001', 'macro|[email protected]', 'reply 2',+ '2024-01-01 10:02:00+00', '2024-01-01 10:02:00+00', NULL, NULL),+ ('00000000-0000-0000-0000-00000000b003', '00000000-0000-0000-0000-000000000c01',+ '00000000-0000-0000-0000-000000000001', 'macro|[email protected]', 'reply 3',+ '2024-01-01 10:03:00+00', '2024-01-01 10:03:00+00', NULL, NULL),+ ('00000000-0000-0000-0000-00000000b004', '00000000-0000-0000-0000-000000000c01',+ '00000000-0000-0000-0000-000000000001', 'macro|[email protected]', 'reply 4',+ '2024-01-01 10:04:00+00', '2024-01-01 10:04:00+00', NULL, NULL);++-- active reply under msg2 (the deleted parent)+INSERT INTO comms_messages (id, channel_id, thread_id, sender_id, content, created_at, updated_at, edited_at, deleted_at) VALUES+ ('00000000-0000-0000-0000-00000000b005', '00000000-0000-0000-0000-000000000c01',+ '00000000-0000-0000-0000-000000000002', 'macro|[email protected]', 'reply to deleted',+ '2024-01-01 11:01:00+00', '2024-01-01 11:01:00+00', NULL, NULL);++-- deleted reply under deleted_msg (no active replies)+INSERT INTO comms_messages (id, channel_id, thread_id, sender_id, content, created_at, updated_at, edited_at, deleted_at) VALUES+ ('00000000-0000-0000-0000-00000000b006', '00000000-0000-0000-0000-000000000c01',+ '00000000-0000-0000-0000-000000000004', 'macro|[email protected]', 'also deleted reply',+ '2024-01-01 09:01:00+00', '2024-01-01 09:01:00+00', NULL, '2024-01-02 00:00:00');++-- reactions on msg1+INSERT INTO comms_reactions (message_id, emoji, user_id, created_at) VALUES+ ('00000000-0000-0000-0000-000000000001', '👍', 'macro|[email protected]', '2024-01-01 10:10:00+00'),+ ('00000000-0000-0000-0000-000000000001', '👍', 'macro|[email protected]', '2024-01-01 10:11:00+00'),+ ('00000000-0000-0000-0000-000000000001', '🎉', 'macro|[email protected]', '2024-01-01 10:12:00+00');++-- reactions on msg3+INSERT INTO comms_reactions (message_id, emoji, user_id, created_at) VALUES+ ('00000000-0000-0000-0000-000000000003', '👍', 'macro|[email protected]', '2024-01-01 12:10:00+00');++-- attachments on msg1+INSERT INTO comms_attachments (id, message_id, channel_id, entity_type, entity_id, width, height, created_at) VALUES+ ('00000000-0000-0000-0000-00000000a001', '00000000-0000-0000-0000-000000000001',+ '00000000-0000-0000-0000-000000000c01', 'document', 'doc-1', NULL, NULL, '2024-01-01 10:00:00+00'),+ ('00000000-0000-0000-0000-00000000a002', '00000000-0000-0000-0000-000000000001',+ '00000000-0000-0000-0000-000000000c01', 'image', 'img-1', 800, 600, '2024-01-01 10:00:01+00');++-- attachment on msg3+INSERT INTO comms_attachments (id, message_id, channel_id, entity_type, entity_id, width, height, created_at) VALUES+ ('00000000-0000-0000-0000-00000000a003', '00000000-0000-0000-0000-000000000003',+ '00000000-0000-0000-0000-000000000c01', 'document', 'doc-2', NULL, NULL, '2024-01-01 12:00:00+00');++-- participants in ch1+INSERT INTO comms_channel_participants (channel_id, user_id, role, joined_at, left_at) VALUES+ ('00000000-0000-0000-0000-000000000c01', 'macro|[email protected]', 'owner', '2024-01-01 00:00:00+00', NULL),+ ('00000000-0000-0000-0000-000000000c01', 'macro|[email protected]', 'admin', '2024-01-01 00:01:00+00', NULL),+ ('00000000-0000-0000-0000-000000000c01', 'macro|[email protected]', 'member', '2024-01-01 00:02:00+00', NULL),+ ('00000000-0000-0000-0000-000000000c01', 'macro|[email protected]', 'member', '2024-01-01 00:03:00+00', '2024-01-05 00:00:00+00');diff --git a/rust/cloud-storage/channels/justfile b/rust/cloud-storage/channels/justfilenew file mode 100644index 0000000000..44d95590f5--- /dev/null+++ b/rust/cloud-storage/channels/justfile@@ -0,0 +1,2 @@+prepare:+ cargo sqlx prepare -- --all-featuresdiff --git a/rust/cloud-storage/channels/src/domain/mod.rs b/rust/cloud-storage/channels/src/domain/mod.rsnew file mode 100644index 0000000000..2a2e74f008--- /dev/null+++ b/rust/cloud-storage/channels/src/domain/mod.rs@@ -0,0 +1,8 @@+/// Domain models for channel messages.+pub mod models;+#[cfg(feature = "ports")]+/// Port traits for channel messages.+pub mod ports;+#[cfg(feature = "ports")]+/// Service orchestration for channel messages.+pub mod service;diff --git a/rust/cloud-storage/channels/src/domain/models.rs b/rust/cloud-storage/channels/src/domain/models.rsnew file mode 100644index 0000000000..83f4626b65--- /dev/null+++ b/rust/cloud-storage/channels/src/domain/models.rs@@ -0,0 +1,238 @@+use chrono::{DateTime, Utc};+use models_pagination::{CreatedAt, CursorVal, Identify, SortOn};+use uuid::Uuid;++/// Request to fetch a page of channel messages.+#[derive(Debug)]+pub struct GetChannelMessagesRequest {+ /// The channel to fetch messages from.+ pub channel_id: Uuid,+ /// Page size, clamped to [1, 100].+ pub limit: u16,+}++/// A top-level message with thread info, reactions, and attachments.+#[derive(Debug)]+pub struct ChannelMessage {+ /// Message id.+ pub id: Uuid,+ /// Channel this message belongs to.+ pub channel_id: Uuid,+ /// User who sent the message.+ pub sender_id: String,+ /// Message body.+ pub content: String,+ /// When the message was created.+ pub created_at: DateTime<Utc>,+ /// When the message was last updated.+ pub updated_at: DateTime<Utc>,+ /// When the message was edited (if ever).+ pub edited_at: Option<DateTime<Utc>>,+ /// When the message was soft-deleted (if ever).+ pub deleted_at: Option<DateTime<Utc>>,+ /// Thread metadata and preview replies.+ pub thread: ThreadInfo,+ /// Aggregated reactions on this message.+ pub reactions: Vec<CountedReaction>,+ /// Attachments on this message.+ pub attachments: Vec<MessageAttachment>,+}++impl Identify for ChannelMessage {+ type Id = Uuid;++ fn id(&self) -> Self::Id {+ self.id+ }+}++impl SortOn<CreatedAt> for ChannelMessage {+ fn sort_on(sort_type: CreatedAt) -> impl FnMut(&Self) -> CursorVal<CreatedAt> {+ move |msg| CursorVal {+ sort_type,+ last_val: msg.created_at,+ }+ }+}++/// Thread metadata + preview replies for a top-level message.+#[derive(Debug)]+pub struct ThreadInfo {+ /// Total number of replies in the thread.+ pub reply_count: i64,+ /// Timestamp of the most recent reply.+ pub latest_reply_at: Option<DateTime<Utc>>,+ /// Last N replies for the collapsed thread preview.+ pub preview: Vec<ThreadReply>,+}++/// A reply shown in a thread preview.+#[derive(Debug)]+pub struct ThreadReply {+ /// Reply id.+ pub id: Uuid,+ /// User who sent the reply.+ pub sender_id: String,+ /// Reply body.+ pub content: String,+ /// When the reply was created.+ pub created_at: DateTime<Utc>,+ /// When the reply was last updated.+ pub updated_at: DateTime<Utc>,+ /// When the reply was edited (if ever).+ pub edited_at: Option<DateTime<Utc>>,+ /// Aggregated reactions on this reply.+ pub reactions: Vec<CountedReaction>,+ /// Attachments on this reply.+ pub attachments: Vec<MessageAttachment>,+}++/// A reaction emoji with the list of users who reacted.+#[derive(Debug, Clone)]+pub struct CountedReaction {+ /// The emoji string.+ pub emoji: String,+ /// User ids who added this reaction.+ pub users: Vec<String>,+}++/// An attachment on a message.+#[derive(Debug, Clone)]+pub struct MessageAttachment {+ /// Attachment id.+ pub id: Uuid,+ /// Type of attached entity (e.g. "document").+ pub entity_type: String,+ /// Id of the attached entity.+ pub entity_id: String,+ /// When the attachment was created.+ pub created_at: DateTime<Utc>,+}++/// An attachment in a channel (for the channel-level attachments listing).+#[derive(Debug, Clone)]+pub struct ChannelAttachment {+ /// Attachment id.+ pub id: Uuid,+ /// Channel this attachment belongs to.+ pub channel_id: Uuid,+ /// Message this attachment is on.+ pub message_id: Uuid,+ /// Type of attached entity (e.g. "document").+ pub entity_type: String,+ /// Id of the attached entity.+ pub entity_id: String,+ /// Optional width (for images).+ pub width: Option<i32>,+ /// Optional height (for images).+ pub height: Option<i32>,+ /// When the attachment was created.+ pub created_at: DateTime<Utc>,+}++impl Identify for ChannelAttachment {+ type Id = Uuid;++ fn id(&self) -> Self::Id {+ self.id+ }+}++impl SortOn<CreatedAt> for ChannelAttachment {+ fn sort_on(sort_type: CreatedAt) -> impl FnMut(&Self) -> CursorVal<CreatedAt> {+ move |a| CursorVal {+ sort_type,+ last_val: a.created_at,+ }+ }+}++/// Role of a channel participant.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum ParticipantRole {+ /// Channel owner.+ Owner,+ /// Channel admin.+ Admin,+ /// Regular member.+ Member,+}++impl std::str::FromStr for ParticipantRole {+ type Err = String;++ fn from_str(s: &str) -> Result<Self, Self::Err> {+ match s {+ "owner" => Ok(Self::Owner),+ "admin" => Ok(Self::Admin),+ "member" => Ok(Self::Member),+ other => Err(format!("unknown participant role: {other}")),+ }+ }+}++/// An active participant in a channel.+#[derive(Debug, Clone)]+pub struct ChannelParticipant {+ /// Channel id.+ pub channel_id: Uuid,+ /// User id.+ pub user_id: String,+ /// Role in the channel.+ pub role: ParticipantRole,+ /// When the user joined.+ pub joined_at: DateTime<Utc>,+ /// When the user left (None if still active).+ pub left_at: Option<DateTime<Utc>>,+}++/// Raw row returned from the top-level messages query.+#[derive(Debug, Clone)]+pub struct TopLevelMessageRow {+ /// Message id.+ pub id: Uuid,+ /// Channel id.+ pub channel_id: Uuid,+ /// Sender user id.+ pub sender_id: String,+ /// Message content.+ pub content: String,+ /// Created timestamp.+ pub created_at: DateTime<Utc>,+ /// Updated timestamp.+ pub updated_at: DateTime<Utc>,+ /// Edited timestamp.+ pub edited_at: Option<DateTime<Utc>>,+ /// Deleted timestamp.+ pub deleted_at: Option<DateTime<Utc>>,+}++/// Combined thread statistics and preview replies from a single query.+#[derive(Debug, Clone)]+pub struct ThreadData {+ /// Total number of replies in this thread.+ pub reply_count: i64,+ /// Timestamp of the latest reply.+ pub latest_reply_at: Option<DateTime<Utc>>,+ /// Last N replies for the thread preview (oldest-first).+ pub preview_replies: Vec<ThreadReplyRow>,+}++/// Raw row returned from the thread data query.+#[derive(Debug, Clone)]+pub struct ThreadReplyRow {+ /// Reply id.+ pub id: Uuid,+ /// Parent message id.+ pub thread_id: Uuid,+ /// Sender user id.+ pub sender_id: String,+ /// Reply content.+ pub content: String,+ /// Created timestamp.+ pub created_at: DateTime<Utc>,+ /// Updated timestamp.+ pub updated_at: DateTime<Utc>,+ /// Edited timestamp.+ pub edited_at: Option<DateTime<Utc>>,+}diff --git a/rust/cloud-storage/channels/src/domain/ports.rs b/rust/cloud-storage/channels/src/domain/ports.rsnew file mode 100644index 0000000000..28d8a0e86e--- /dev/null+++ b/rust/cloud-storage/channels/src/domain/ports.rs@@ -0,0 +1,96 @@+use crate::domain::models::{+ ChannelAttachment, ChannelParticipant, CountedReaction, MessageAttachment, ThreadData,+ TopLevelMessageRow,+};+use models_pagination::{CreatedAt, Query};+use std::collections::HashMap;+use uuid::Uuid;++/// Repository for fetching channel message data.+#[cfg_attr(test, mockall::automock(type Err = anyhow::Error;))]+pub trait ChannelMessagesRepo: Send + Sync + 'static {+ /// Error type for repo operations.+ type Err: Send;++ /// Fetch top-level messages (thread_id IS NULL). Cursor-paginated on created_at DESC.+ fn get_top_level_messages(+ &self,+ channel_id: Uuid,+ query: &Query<Uuid, CreatedAt, ()>,+ limit: u16,+ ) -> impl Future<Output = Result<Vec<TopLevelMessageRow>, Self::Err>> + Send;++ /// Batch-fetch thread data (stats + preview replies) for parent messages in a single query.+ fn get_thread_data(+ &self,+ parent_ids: &[Uuid],+ preview_count: u16,+ ) -> impl Future<Output = Result<HashMap<Uuid, ThreadData>, Self::Err>> + Send;++ /// Batch-fetch reactions for a set of message ids.+ fn get_reactions_batch(+ &self,+ message_ids: &[Uuid],+ ) -> impl Future<Output = Result<HashMap<Uuid, Vec<CountedReaction>>, Self::Err>> + Send;++ /// Batch-fetch attachments for a set of message ids.+ fn get_attachments_batch(+ &self,+ message_ids: &[Uuid],+ ) -> impl Future<Output = Result<HashMap<Uuid, Vec<MessageAttachment>>, Self::Err>> + Send;++ /// Fetch channel-level attachments, cursor-paginated on created_at DESC.+ fn get_channel_attachments(+ &self,+ channel_id: Uuid,+ query: &Query<Uuid, CreatedAt, ()>,+ limit: u16,+ ) -> impl Future<Output = Result<Vec<ChannelAttachment>, Self::Err>> + Send;++ /// Fetch active participants for a channel.+ fn get_channel_participants(+ &self,+ channel_id: Uuid,+ ) -> impl Future<Output = Result<Vec<ChannelParticipant>, Self::Err>> + Send;+}++/// Service for fetching paginated channel messages.+pub trait ChannelMessagesService: Send + Sync + 'static {+ /// Fetch a page of channel messages with thread previews, reactions, and attachments.+ fn get_channel_messages(+ &self,+ channel_id: Uuid,+ query: Query<Uuid, CreatedAt, ()>,+ limit: u16,+ ) -> impl Future<Output = Result<ChannelMessagesPage, ChannelMessagesErr>> + Send;++ /// Fetch a paginated page of channel-level attachments.+ fn get_channel_attachments(+ &self,+ channel_id: Uuid,+ query: Query<Uuid, CreatedAt, ()>,+ limit: u16,+ ) -> impl Future<Output = Result<ChannelAttachmentsPage, ChannelMessagesErr>> + Send;++ /// Fetch active participants for a channel.+ fn get_channel_participants(+ &self,+ channel_id: Uuid,+ ) -> impl Future<Output = Result<Vec<ChannelParticipant>, ChannelMessagesErr>> + Send;+}++/// A paginated page of channel messages.+pub type ChannelMessagesPage =+ models_pagination::PaginatedCursor<super::models::ChannelMessage, Uuid, CreatedAt, ()>;++/// A paginated page of channel attachments.+pub type ChannelAttachmentsPage =+ models_pagination::PaginatedCursor<ChannelAttachment, Uuid, CreatedAt, ()>;++/// Errors that can occur when fetching channel messages.+#[derive(Debug, thiserror::Error)]+pub enum ChannelMessagesErr {+ /// A database error occurred.+ #[error(transparent)]+ Repo(#[from] anyhow::Error),+}diff --git a/rust/cloud-storage/channels/src/domain/service.rs b/rust/cloud-storage/channels/src/domain/service.rsnew file mode 100644index 0000000000..6b3ff7f3e4--- /dev/null+++ b/rust/cloud-storage/channels/src/domain/service.rs@@ -0,0 +1,165 @@+use crate::domain::{+ models::{ChannelMessage, ChannelParticipant, ThreadInfo, ThreadReply},+ ports::{+ ChannelAttachmentsPage, ChannelMessagesErr, ChannelMessagesPage, ChannelMessagesRepo,+ ChannelMessagesService,+ },+};+use models_pagination::{CreatedAt, PaginateOn, Query};+use uuid::Uuid;++#[cfg(test)]+mod test;++/// Default number of preview replies per thread.+const THREAD_PREVIEW_COUNT: u16 = 3;++/// Service implementation backed by a [`ChannelMessagesRepo`].+pub struct ChannelMessagesServiceImpl<R> {+ repo: R,+}++impl<R> ChannelMessagesServiceImpl<R>+where+ R: ChannelMessagesRepo,+ anyhow::Error: From<R::Err>,+{+ /// Create a new service with the given repository.+ pub 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(+ &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 parent_ids: Vec<Uuid> = rows.iter().map(|r| r.id).collect();++ let thread_data = self+ .repo+ .get_thread_data(&parent_ids, THREAD_PREVIEW_COUNT)+ .await+ .map_err(anyhow::Error::from)?;++ let mut all_ids: Vec<Uuid> = parent_ids.clone();+ for td in thread_data.values() {+ for reply in &td.preview_replies {+ all_ids.push(reply.id);+ }+ }++ let (reactions, attachments) = tokio::join!(+ self.repo.get_reactions_batch(&all_ids),+ self.repo.get_attachments_batch(&all_ids),+ );++ let reactions = reactions.map_err(anyhow::Error::from)?;+ let attachments = attachments.map_err(anyhow::Error::from)?;++ let messages: Vec<ChannelMessage> = rows+ .into_iter()+ .map(|row| {+ let td = thread_data.get(&row.id);+ let preview_replies = td+ .map(|td| {+ td.preview_replies+ .iter()+ .map(|r| ThreadReply {+ id: r.id,+ sender_id: r.sender_id.clone(),+ content: r.content.clone(),+ created_at: r.created_at,+ updated_at: r.updated_at,+ edited_at: r.edited_at,+ reactions: reactions.get(&r.id).cloned().unwrap_or_default(),+ attachments: attachments.get(&r.id).cloned().unwrap_or_default(),+ })+ .collect()+ })+ .unwrap_or_default();++ ChannelMessage {+ id: row.id,+ channel_id: row.channel_id,+ sender_id: row.sender_id,+ content: row.content,+ created_at: row.created_at,+ updated_at: row.updated_at,+ edited_at: row.edited_at,+ deleted_at: row.deleted_at,+ thread: ThreadInfo {+ reply_count: td.map_or(0, |td| td.reply_count),+ latest_reply_at: td.and_then(|td| td.latest_reply_at),+ preview: preview_replies,+ },+ reactions: reactions.get(&row.id).cloned().unwrap_or_default(),+ attachments: attachments.get(&row.id).cloned().unwrap_or_default(),+ }+ })+ .collect();++ // 6. Paginate.+ let page = messages+ .into_iter()+ .paginate_on(limit.into(), CreatedAt)+ .filter_on(())+ .into_page();++ Ok(page)+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_channel_attachments(+ &self,+ channel_id: Uuid,+ query: Query<Uuid, CreatedAt, ()>,+ limit: u16,+ ) -> Result<ChannelAttachmentsPage, ChannelMessagesErr> {+ let limit = limit.clamp(1, 100);++ let attachments = self+ .repo+ .get_channel_attachments(channel_id, &query, limit)+ .await+ .map_err(anyhow::Error::from)?;++ let page = attachments+ .into_iter()+ .paginate_on(limit.into(), CreatedAt)+ .filter_on(())+ .into_page();++ Ok(page)+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_channel_participants(+ &self,+ channel_id: Uuid,+ ) -> Result<Vec<ChannelParticipant>, ChannelMessagesErr> {+ let participants = self+ .repo+ .get_channel_participants(channel_id)+ .await+ .map_err(anyhow::Error::from)?;++ Ok(participants)+ }+}diff --git a/rust/cloud-storage/channels/src/domain/service/test.rs b/rust/cloud-storage/channels/src/domain/service/test.rsnew file mode 100644index 0000000000..e30f6c5054--- /dev/null+++ b/rust/cloud-storage/channels/src/domain/service/test.rs@@ -0,0 +1,171 @@+use super::*;+use crate::domain::{+ models::{CountedReaction, MessageAttachment, ThreadData, ThreadReplyRow, TopLevelMessageRow},+ ports::MockChannelMessagesRepo,+};+use chrono::Utc;+use std::collections::HashMap;++fn make_row(id: Uuid, minutes_ago: i64) -> TopLevelMessageRow {+ let now = Utc::now();+ TopLevelMessageRow {+ id,+ channel_id: Uuid::nil(),+ sender_id: "user_1".into(),+ content: format!("msg {minutes_ago}"),+ created_at: now - chrono::Duration::minutes(minutes_ago),+ updated_at: now - chrono::Duration::minutes(minutes_ago),+ edited_at: None,+ deleted_at: None,+ }+}++fn empty_repo() -> MockChannelMessagesRepo {+ let mut repo = MockChannelMessagesRepo::new();+ repo.expect_get_top_level_messages()+ .returning(|_, _, _| Box::pin(async { Ok(vec![]) }));+ 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()) }));+ repo.expect_get_channel_attachments()+ .returning(|_, _, _| Box::pin(async { Ok(vec![]) }));+ repo.expect_get_channel_participants()+ .returning(|_| Box::pin(async { Ok(vec![]) }));+ repo+}++#[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)+ .await+ .unwrap();++ assert!(page.items.is_empty());+ assert!(page.next_cursor.is_none());+}++#[tokio::test]+async fn returns_messages_with_thread_info() {+ let parent_id = Uuid::new_v4();+ let reply_id = Uuid::new_v4();+ let row = make_row(parent_id, 10);+ let latest_reply = Utc::now();++ let reply_row = ThreadReplyRow {+ id: reply_id,+ thread_id: parent_id,+ sender_id: "user_2".into(),+ content: "reply".into(),+ created_at: Utc::now(),+ updated_at: Utc::now(),+ edited_at: None,+ };++ let mut repo = MockChannelMessagesRepo::new();++ let row_clone = row.clone();+ repo.expect_get_top_level_messages()+ .returning(move |_, _, _| {+ let r = row_clone.clone();+ Box::pin(async move { Ok(vec![r]) })+ });++ let reply_clone = reply_row.clone();+ repo.expect_get_thread_data().returning(move |_, _| {+ let mut map = HashMap::new();+ map.insert(+ parent_id,+ ThreadData {+ reply_count: 5,+ latest_reply_at: Some(latest_reply),+ preview_replies: vec![reply_clone.clone()],+ },+ );+ Box::pin(async move { Ok(map) })+ });++ let reaction = CountedReaction {+ emoji: "👍".into(),+ users: vec!["user_3".into()],+ };+ let reaction_clone = reaction.clone();+ repo.expect_get_reactions_batch().returning(move |_| {+ let mut map: HashMap<Uuid, Vec<CountedReaction>> = HashMap::new();+ map.insert(parent_id, vec![reaction_clone.clone()]);+ Box::pin(async move { Ok(map) })+ });++ let attachment = MessageAttachment {+ id: Uuid::new_v4(),+ entity_type: "document".into(),+ entity_id: "doc_1".into(),+ created_at: Utc::now(),+ };+ let attachment_clone = attachment.clone();+ repo.expect_get_attachments_batch().returning(move |_| {+ let mut map: HashMap<Uuid, Vec<MessageAttachment>> = HashMap::new();+ map.insert(parent_id, vec![attachment_clone.clone()]);+ Box::pin(async move { Ok(map) })+ });++ let svc = ChannelMessagesServiceImpl::new(repo);+ let page = svc+ .get_channel_messages(Uuid::nil(), Query::Sort(CreatedAt, ()), 50)+ .await+ .unwrap();++ assert_eq!(page.items.len(), 1);+ let msg = &page.items[0];+ assert_eq!(msg.thread.reply_count, 5);+ assert_eq!(msg.thread.preview.len(), 1);+ assert_eq!(msg.reactions.len(), 1);+ assert_eq!(msg.attachments.len(), 1);+ assert!(page.next_cursor.is_none());+}++#[tokio::test]+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![]) }));+ 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(Uuid::nil(), Query::Sort(CreatedAt, ()), 200)+ .await+ .unwrap();++ assert!(page.items.is_empty());+}++#[tokio::test]+async fn returns_empty_attachments_page() {+ let svc = ChannelMessagesServiceImpl::new(empty_repo());+ let page = svc+ .get_channel_attachments(Uuid::nil(), Query::Sort(CreatedAt, ()), 50)+ .await+ .unwrap();++ assert!(page.items.is_empty());+ assert!(page.next_cursor.is_none());+}++#[tokio::test]+async fn returns_empty_participants_list() {+ let svc = ChannelMessagesServiceImpl::new(empty_repo());+ let participants = svc.get_channel_participants(Uuid::nil()).await.unwrap();++ assert!(participants.is_empty());+}diff --git a/rust/cloud-storage/channels/src/inbound/axum_router.rs b/rust/cloud-storage/channels/src/inbound/axum_router.rsnew file mode 100644index 0000000000..bf8ee71965--- /dev/null+++ b/rust/cloud-storage/channels/src/inbound/axum_router.rs@@ -0,0 +1,452 @@+#[cfg(test)]+mod test;++use crate::domain::models::{+ ChannelAttachment, ChannelMessage, ChannelParticipant, CountedReaction, MessageAttachment,+ ParticipantRole, ThreadInfo, ThreadReply,+};+use crate::domain::ports::{ChannelMessagesErr, ChannelMessagesService};+use axum::{+ Json, Router,+ extract::{Path, Query, State},+ http::StatusCode,+ response::IntoResponse,+ routing::get,+};+use chrono::{DateTime, Utc};+use model_error_response::ErrorResponse;+use model_user::axum_extractor::MacroUserExtractor;+use models_pagination::{CreatedAt, CursorExtractor, PaginatedOpaqueCursor, TypeEraseCursor};+use serde::{Deserialize, Serialize};+use std::sync::Arc;+use uuid::Uuid;++/// State for the channels router.+pub struct ChannelsRouterState<S> {+ service: Arc<S>,+}++impl<S> Clone for ChannelsRouterState<S> {+ fn clone(&self) -> Self {+ Self {+ service: self.service.clone(),+ }+ }+}++impl<S: ChannelMessagesService> ChannelsRouterState<S> {+ /// Create a new router state wrapping the service.+ pub fn new(service: S) -> Self {+ Self {+ service: Arc::new(service),+ }+ }+}++/// 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>,+}++/// Create the channels router.+pub fn channels_router<S, T>(state: ChannelsRouterState<S>) -> Router<T>+where+ S: ChannelMessagesService,+ T: Send + Sync,+{+ Router::new()+ .route(+ "/:channel_id/messages",+ get(get_channel_messages_handler::<S>),+ )+ .route(+ "/:channel_id/attachments",+ get(get_channel_attachments_handler::<S>),+ )+ .route(+ "/:channel_id/participants",+ get(get_channel_participants_handler::<S>),+ )+ .with_state(state)+}++/// Handler for `GET /channels/:channel_id/messages`.+#[utoipa::path(+ get,+ operation_id = "get_channel_messages",+ path = "/channels/{channel_id}/messages",+ 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"),+ ),+ responses(+ (status = 200, body = ApiChannelMessagesPage),+ (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>,+ 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?;++ Ok(Json(page.type_erase().map(ApiChannelMessage::from)))+}++/// Handler for `GET /channels/:channel_id/attachments`.+#[utoipa::path(+ get,+ operation_id = "get_channel_attachments",+ path = "/channels/{channel_id}/attachments",+ 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"),+ ),+ responses(+ (status = 200, body = ApiChannelAttachmentsPage),+ (status = 500, body = ErrorResponse),+ )+)]+#[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>,+ Query(params): Query<Params>,+ cursor: CursorExtractor<Uuid, CreatedAt, ()>,+) -> Result<Json<PaginatedOpaqueCursor<ApiChannelAttachment>>, ChannelsHandlerErr> {+ let limit = params.limit.unwrap_or(50);+ let query = cursor.into_query(CreatedAt, ());++ let page = state+ .service+ .get_channel_attachments(channel_id, query, limit)+ .await?;++ Ok(Json(page.type_erase().map(ApiChannelAttachment::from)))+}++/// Handler for `GET /channels/:channel_id/participants`.+#[utoipa::path(+ get,+ operation_id = "get_channel_participants",+ path = "/channels/{channel_id}/participants",+ params(+ ("channel_id" = Uuid, Path, description = "Channel ID"),+ ),+ responses(+ (status = 200, body = Vec<ApiChannelParticipant>),+ (status = 500, body = ErrorResponse),+ )+)]+#[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>,+) -> Result<Json<Vec<ApiChannelParticipant>>, ChannelsHandlerErr> {+ let participants = state.service.get_channel_participants(channel_id).await?;++ Ok(Json(+ participants+ .into_iter()+ .map(ApiChannelParticipant::from)+ .collect(),+ ))+}++/// Paginated response of channel messages.+#[derive(Debug, Serialize, utoipa::ToSchema)]+pub struct ApiChannelMessagesPage {+ /// Messages on this page.+ items: Vec<ApiChannelMessage>,+ /// Cursor for the next page, null if no more pages.+ next_cursor: Option<String>,+}++/// A top-level channel message with thread info.+#[derive(Debug, Serialize, utoipa::ToSchema)]+pub struct ApiChannelMessage {+ /// Message id.+ id: Uuid,+ /// Channel id.+ channel_id: Uuid,+ /// Sender user id.+ sender_id: String,+ /// Message content.+ content: String,+ /// When the message was created.+ created_at: DateTime<Utc>,+ /// When the message was last updated.+ updated_at: DateTime<Utc>,+ /// When the message was edited.+ edited_at: Option<DateTime<Utc>>,+ /// When the message was soft-deleted.+ deleted_at: Option<DateTime<Utc>>,+ /// Thread metadata and preview.+ thread: ApiThreadInfo,+ /// Reactions on this message.+ reactions: Vec<ApiCountedReaction>,+ /// Attachments on this message.+ attachments: Vec<ApiMessageAttachment>,+}++impl From<ChannelMessage> for ApiChannelMessage {+ fn from(m: ChannelMessage) -> Self {+ Self {+ id: m.id,+ channel_id: m.channel_id,+ sender_id: m.sender_id,+ content: m.content,+ created_at: m.created_at,+ updated_at: m.updated_at,+ edited_at: m.edited_at,+ deleted_at: m.deleted_at,+ thread: ApiThreadInfo::from(m.thread),+ reactions: m+ .reactions+ .into_iter()+ .map(ApiCountedReaction::from)+ .collect(),+ attachments: m+ .attachments+ .into_iter()+ .map(ApiMessageAttachment::from)+ .collect(),+ }+ }+}++/// Thread metadata and preview replies.+#[derive(Debug, Serialize, utoipa::ToSchema)]+pub struct ApiThreadInfo {+ /// Total reply count.+ reply_count: i64,+ /// Timestamp of the latest reply.+ latest_reply_at: Option<DateTime<Utc>>,+ /// Last N replies for thread preview.+ preview: Vec<ApiThreadReply>,+}++impl From<ThreadInfo> for ApiThreadInfo {+ fn from(t: ThreadInfo) -> Self {+ Self {+ reply_count: t.reply_count,+ latest_reply_at: t.latest_reply_at,+ preview: t.preview.into_iter().map(ApiThreadReply::from).collect(),+ }+ }+}++/// A thread reply shown in preview.+#[derive(Debug, Serialize, utoipa::ToSchema)]+pub struct ApiThreadReply {+ /// Reply id.+ id: Uuid,+ /// Sender user id.+ sender_id: String,+ /// Reply content.+ content: String,+ /// When the reply was created.+ created_at: DateTime<Utc>,+ /// When the reply was last updated.+ updated_at: DateTime<Utc>,+ /// When the reply was edited.+ edited_at: Option<DateTime<Utc>>,+ /// Reactions on this reply.+ reactions: Vec<ApiCountedReaction>,+ /// Attachments on this reply.+ attachments: Vec<ApiMessageAttachment>,+}++impl From<ThreadReply> for ApiThreadReply {+ fn from(r: ThreadReply) -> Self {+ Self {+ id: r.id,+ sender_id: r.sender_id,+ content: r.content,+ created_at: r.created_at,+ updated_at: r.updated_at,+ edited_at: r.edited_at,+ reactions: r+ .reactions+ .into_iter()+ .map(ApiCountedReaction::from)+ .collect(),+ attachments: r+ .attachments+ .into_iter()+ .map(ApiMessageAttachment::from)+ .collect(),+ }+ }+}++/// A reaction with emoji and user list.+#[derive(Debug, Serialize, utoipa::ToSchema)]+pub struct ApiCountedReaction {+ /// The emoji string.+ emoji: String,+ /// User ids who added this reaction.+ users: Vec<String>,+}++impl From<CountedReaction> for ApiCountedReaction {+ fn from(r: CountedReaction) -> Self {+ Self {+ emoji: r.emoji,+ users: r.users,+ }+ }+}++/// An attachment on a message.+#[derive(Debug, Serialize, utoipa::ToSchema)]+pub struct ApiMessageAttachment {+ /// Attachment id.+ id: Uuid,+ /// Type of entity.+ entity_type: String,+ /// Entity id.+ entity_id: String,+ /// When the attachment was created.+ created_at: DateTime<Utc>,+}++impl From<MessageAttachment> for ApiMessageAttachment {+ fn from(a: MessageAttachment) -> Self {+ Self {+ id: a.id,+ entity_type: a.entity_type,+ entity_id: a.entity_id,+ created_at: a.created_at,+ }+ }+}++/// Paginated response of channel attachments.+#[derive(Debug, Serialize, utoipa::ToSchema)]+pub struct ApiChannelAttachmentsPage {+ /// Attachments on this page.+ items: Vec<ApiChannelAttachment>,+ /// Cursor for the next page, null if no more pages.+ next_cursor: Option<String>,+}++/// A channel-level attachment.+#[derive(Debug, Serialize, utoipa::ToSchema)]+pub struct ApiChannelAttachment {+ /// Attachment id.+ id: Uuid,+ /// Channel id.+ channel_id: Uuid,+ /// Message id this attachment belongs to.+ message_id: Uuid,+ /// Type of entity.+ entity_type: String,+ /// Entity id.+ entity_id: String,+ /// Width (for images).+ width: Option<i32>,+ /// Height (for images).+ height: Option<i32>,+ /// When the attachment was created.+ created_at: DateTime<Utc>,+}++impl From<ChannelAttachment> for ApiChannelAttachment {+ fn from(a: ChannelAttachment) -> Self {+ Self {+ id: a.id,+ channel_id: a.channel_id,+ message_id: a.message_id,+ entity_type: a.entity_type,+ entity_id: a.entity_id,+ width: a.width,+ height: a.height,+ created_at: a.created_at,+ }+ }+}++/// Participant role in a channel.+#[derive(Debug, Serialize, utoipa::ToSchema)]+#[serde(rename_all = "snake_case")]+pub enum ApiParticipantRole {+ /// Channel owner.+ Owner,+ /// Channel admin.+ Admin,+ /// Regular member.+ Member,+}++impl From<ParticipantRole> for ApiParticipantRole {+ fn from(r: ParticipantRole) -> Self {+ match r {+ ParticipantRole::Owner => Self::Owner,+ ParticipantRole::Admin => Self::Admin,+ ParticipantRole::Member => Self::Member,+ }+ }+}++/// A channel participant.+#[derive(Debug, Serialize, utoipa::ToSchema)]+pub struct ApiChannelParticipant {+ /// Channel id.+ channel_id: Uuid,+ /// User id.+ user_id: String,+ /// Role in the channel.+ role: ApiParticipantRole,+ /// When the user joined.+ joined_at: DateTime<Utc>,+}++impl From<ChannelParticipant> for ApiChannelParticipant {+ fn from(p: ChannelParticipant) -> Self {+ Self {+ channel_id: p.channel_id,+ user_id: p.user_id,+ role: ApiParticipantRole::from(p.role),+ joined_at: p.joined_at,+ }+ }+}++/// Errors from the channels handler.+#[derive(Debug, thiserror::Error)]+pub enum ChannelsHandlerErr {+ /// Internal server error.+ #[error("An internal server error occurred")]+ Internal(#[from] ChannelMessagesErr),+}++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()+ }+}diff --git a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs b/rust/cloud-storage/channels/src/inbound/axum_router/test.rsnew file mode 100644index 0000000000..c7b7ed59f7--- /dev/null+++ b/rust/cloud-storage/channels/src/inbound/axum_router/test.rs@@ -0,0 +1,272 @@+use super::*;+use crate::domain::models::{+ ChannelAttachment, ChannelMessage, ChannelParticipant, ParticipantRole,+};+use crate::domain::ports::{+ ChannelAttachmentsPage, ChannelMessagesErr, ChannelMessagesPage, ChannelMessagesService,+};+use axum::{+ Extension, Router,+ http::{Request, StatusCode},+};+use http_body_util::BodyExt;+use model_user::UserContext;+use models_pagination::{CreatedAt, PaginateOn, Query};+use tower::util::ServiceExt;++struct MockService;++impl ChannelMessagesService for MockService {+ 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![])+ }+}++struct ErrorService;++impl ChannelMessagesService for ErrorService {+ async fn get_channel_messages(+ &self,+ _channel_id: Uuid,+ _query: Query<Uuid, CreatedAt, ()>,+ _limit: u16,+ ) -> Result<ChannelMessagesPage, ChannelMessagesErr> {+ Err(ChannelMessagesErr::Repo(anyhow::anyhow!("database error")))+ }++ async fn get_channel_attachments(+ &self,+ _channel_id: Uuid,+ _query: Query<Uuid, CreatedAt, ()>,+ _limit: u16,+ ) -> Result<ChannelAttachmentsPage, ChannelMessagesErr> {+ Err(ChannelMessagesErr::Repo(anyhow::anyhow!("database error")))+ }++ async fn get_channel_participants(+ &self,+ _channel_id: Uuid,+ ) -> Result<Vec<ChannelParticipant>, ChannelMessagesErr> {+ Err(ChannelMessagesErr::Repo(anyhow::anyhow!("database error")))+ }+}++struct ParticipantsService;++impl ChannelMessagesService for ParticipantsService {+ 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![+ ChannelParticipant {+ channel_id,+ user_id: "macro|[email protected]".into(),+ role: ParticipantRole::Owner,+ joined_at: chrono::Utc::now(),+ left_at: None,+ },+ ChannelParticipant {+ channel_id,+ user_id: "macro|[email protected]".into(),+ role: ParticipantRole::Member,+ joined_at: chrono::Utc::now(),+ left_at: None,+ },+ ])+ }+}++fn user_extension() -> Extension<UserContext> {+ Extension(UserContext {+ user_id: "macro|[email protected]".to_string(),+ fusion_user_id: "1234".to_string(),+ permissions: None,+ organization_id: None,+ })+}++fn mock_router() -> Router {+ channels_router(ChannelsRouterState::new(MockService)).layer(user_extension())+}++fn error_router() -> Router {+ channels_router(ChannelsRouterState::new(ErrorService)).layer(user_extension())+}++#[tokio::test]+async fn messages_returns_empty_page() {+ let router = mock_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::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!([]));+ assert!(json["next_cursor"].is_null());+}++#[tokio::test]+async fn messages_returns_500_on_service_error() {+ let router = error_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::INTERNAL_SERVER_ERROR);++ 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"], "An internal server error occurred");+}++#[tokio::test]+async fn attachments_returns_empty_page() {+ let router = mock_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::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!([]));+ assert!(json["next_cursor"].is_null());+}++#[tokio::test]+async fn attachments_returns_500_on_service_error() {+ let router = error_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::INTERNAL_SERVER_ERROR);+}++#[tokio::test]+async fn participants_returns_empty_list() {+ let router = mock_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::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, serde_json::json!([]));+}++#[tokio::test]+async fn participants_returns_data_with_correct_shape() {+ let router =+ channels_router(ChannelsRouterState::new(ParticipantsService)).layer(user_extension());+ 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::OK);++ let bytes = res.into_body().collect().await.unwrap().to_bytes();+ let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();+ let arr = json.as_array().unwrap();+ assert_eq!(arr.len(), 2);+ assert_eq!(arr[0]["role"], "owner");+ assert_eq!(arr[1]["role"], "member");+ assert_eq!(arr[0]["user_id"], "macro|[email protected]");+}++#[tokio::test]+async fn participants_returns_500_on_service_error() {+ let router = error_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::INTERNAL_SERVER_ERROR);++ 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"], "An internal server error occurred");+}diff --git a/rust/cloud-storage/channels/src/inbound/mod.rs b/rust/cloud-storage/channels/src/inbound/mod.rsnew file mode 100644index 0000000000..1191bba681--- /dev/null+++ b/rust/cloud-storage/channels/src/inbound/mod.rs@@ -0,0 +1,2 @@+/// Axum handler and router for channel messages.+pub mod axum_router;diff --git a/rust/cloud-storage/channels/src/lib.rs b/rust/cloud-storage/channels/src/lib.rsnew file mode 100644index 0000000000..4c710727a9--- /dev/null+++ b/rust/cloud-storage/channels/src/lib.rs@@ -0,0 +1,11 @@+#![deny(missing_docs)]+//! Paginated channel messages with thread previews, reactions, and attachments.++/// Domain layer: models, ports, and service.+pub mod domain;+/// Inbound layer: axum handler and router.+#[cfg(feature = "inbound")]+pub mod inbound;+/// Outbound layer: postgres repository.+#[cfg(feature = "outbound")]+pub mod outbound;diff --git a/rust/cloud-storage/channels/src/outbound/mod.rs b/rust/cloud-storage/channels/src/outbound/mod.rsnew file mode 100644index 0000000000..7e85e2b8a8--- /dev/null+++ b/rust/cloud-storage/channels/src/outbound/mod.rs@@ -0,0 +1,2 @@+/// Postgres repository for channel messages.+pub mod pg_channels_repo;diff --git a/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs b/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rsnew file mode 100644index 0000000000..dc877a39d8--- /dev/null+++ b/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs@@ -0,0 +1,380 @@+#[cfg(test)]+mod tests;++use crate::domain::{+ models::{+ ChannelAttachment, ChannelParticipant, CountedReaction, MessageAttachment, ParticipantRole,+ ThreadData, ThreadReplyRow, TopLevelMessageRow,+ },+ ports::ChannelMessagesRepo,+};+use models_pagination::{CreatedAt, Query};+use sqlx::PgPool;+use std::collections::HashMap;+use uuid::Uuid;++/// Postgres-backed repository for channel messages.+pub struct PgChannelMessagesRepo {+ pool: PgPool,+}++impl PgChannelMessagesRepo {+ /// Create a new repo with the given connection pool.+ pub fn new(pool: PgPool) -> Self {+ Self { pool }+ }+}++/// Intermediate row for the top-level messages query.+#[derive(Debug)]+struct TopLevelRow {+ id: Uuid,+ channel_id: Uuid,+ sender_id: String,+ content: String,+ created_at: chrono::DateTime<chrono::Utc>,+ updated_at: chrono::DateTime<chrono::Utc>,+ edited_at: Option<chrono::DateTime<chrono::Utc>>,+ deleted_at: Option<chrono::DateTime<chrono::Utc>>,+}++/// Intermediate row for the merged thread data query (stats + preview replies).+#[derive(Debug)]+struct ThreadDataRow {+ id: Uuid,+ thread_id: Uuid,+ sender_id: String,+ content: String,+ created_at: chrono::DateTime<chrono::Utc>,+ updated_at: chrono::DateTime<chrono::Utc>,+ edited_at: Option<chrono::DateTime<chrono::Utc>>,+ reply_count: i64,+ latest_reply_at: Option<chrono::DateTime<chrono::Utc>>,+}++/// Intermediate row for reactions.+#[derive(Debug)]+struct ReactionRow {+ message_id: Uuid,+ emoji: String,+ user_id: String,+}++/// Intermediate row for attachments.+#[derive(Debug)]+struct AttachmentRow {+ id: Uuid,+ message_id: Uuid,+ entity_type: String,+ entity_id: String,+ created_at: chrono::DateTime<chrono::Utc>,+}++/// Intermediate row for channel-level attachments.+#[derive(Debug)]+struct ChannelAttachmentRow {+ id: Uuid,+ channel_id: Uuid,+ message_id: Uuid,+ entity_type: String,+ entity_id: String,+ width: Option<i32>,+ height: Option<i32>,+ created_at: chrono::DateTime<chrono::Utc>,+}++/// Intermediate row for channel participants.+#[derive(Debug)]+struct ParticipantRow {+ channel_id: Uuid,+ user_id: String,+ role: String,+ joined_at: chrono::DateTime<chrono::Utc>,+ left_at: Option<chrono::DateTime<chrono::Utc>>,+}++impl ChannelMessagesRepo for PgChannelMessagesRepo {+ type Err = anyhow::Error;++ #[tracing::instrument(err, skip(self))]+ async fn get_top_level_messages(+ &self,+ channel_id: Uuid,+ query: &Query<Uuid, CreatedAt, ()>,+ limit: u16,+ ) -> Result<Vec<TopLevelMessageRow>, Self::Err> {+ let (cursor_created_at, cursor_id) = match query.vals() {+ (Some(id), Some(val)) => (Some(*val), Some(*id)),+ _ => (None, None),+ };++ 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+ .into_iter()+ .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,+ })+ .collect())+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_thread_data(+ &self,+ parent_ids: &[Uuid],+ preview_count: u16,+ ) -> Result<HashMap<Uuid, ThreadData>, Self::Err> {+ if parent_ids.is_empty() {+ return Ok(HashMap::new());+ }++ let rows = sqlx::query_as!(+ ThreadDataRow,+ r#"+ SELECT+ id AS "id!", thread_id AS "thread_id!", sender_id AS "sender_id!",+ content AS "content!", created_at AS "created_at!", updated_at AS "updated_at!",+ edited_at::timestamptz AS "edited_at?",+ reply_count AS "reply_count!", latest_reply_at AS "latest_reply_at?"+ FROM (+ SELECT+ r.id,+ r.thread_id,+ r.sender_id,+ r.content,+ r.created_at,+ r.updated_at,+ r.edited_at,+ COUNT(*) OVER (PARTITION BY r.thread_id) AS reply_count,+ MAX(r.created_at) OVER (PARTITION BY r.thread_id)::timestamptz AS latest_reply_at,+ ROW_NUMBER() OVER (PARTITION BY r.thread_id ORDER BY r.created_at DESC) AS rn+ FROM comms_messages r+ WHERE r.thread_id = ANY($1) AND r.deleted_at IS NULL+ ) sub+ WHERE rn <= $2+ ORDER BY thread_id, created_at ASC+ "#,+ parent_ids,+ i64::from(preview_count) as i64,+ )+ .fetch_all(&self.pool)+ .await?;++ let mut map: HashMap<Uuid, ThreadData> = HashMap::new();+ for r in rows {+ let entry = map.entry(r.thread_id).or_insert_with(|| ThreadData {+ reply_count: r.reply_count,+ latest_reply_at: r.latest_reply_at,+ preview_replies: Vec::new(),+ });+ entry.preview_replies.push(ThreadReplyRow {+ id: r.id,+ thread_id: r.thread_id,+ sender_id: r.sender_id,+ content: r.content,+ created_at: r.created_at,+ updated_at: r.updated_at,+ edited_at: r.edited_at,+ });+ }++ Ok(map)+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_reactions_batch(+ &self,+ message_ids: &[Uuid],+ ) -> Result<HashMap<Uuid, Vec<CountedReaction>>, Self::Err> {+ if message_ids.is_empty() {+ return Ok(HashMap::new());+ }++ let rows = sqlx::query_as!(+ ReactionRow,+ r#"+ SELECT message_id, emoji, user_id+ FROM comms_reactions+ WHERE message_id = ANY($1)+ ORDER BY created_at ASC+ "#,+ message_ids,+ )+ .fetch_all(&self.pool)+ .await?;++ // Group by message_id, then fold by emoji within each message.+ let mut map: HashMap<Uuid, HashMap<String, Vec<String>>> = HashMap::new();+ for r in rows {+ map.entry(r.message_id)+ .or_default()+ .entry(r.emoji)+ .or_default()+ .push(r.user_id);+ }++ Ok(map+ .into_iter()+ .map(|(msg_id, emoji_map)| {+ let reactions = emoji_map+ .into_iter()+ .map(|(emoji, users)| CountedReaction { emoji, users })+ .collect();+ (msg_id, reactions)+ })+ .collect())+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_attachments_batch(+ &self,+ message_ids: &[Uuid],+ ) -> Result<HashMap<Uuid, Vec<MessageAttachment>>, Self::Err> {+ if message_ids.is_empty() {+ return Ok(HashMap::new());+ }++ let rows = sqlx::query_as!(+ AttachmentRow,+ r#"+ SELECT id, message_id, entity_type, entity_id, created_at+ FROM comms_attachments+ WHERE message_id = ANY($1)+ ORDER BY created_at ASC+ "#,+ message_ids,+ )+ .fetch_all(&self.pool)+ .await?;++ let mut map: HashMap<Uuid, Vec<MessageAttachment>> = HashMap::new();+ for r in rows {+ map.entry(r.message_id)+ .or_default()+ .push(MessageAttachment {+ id: r.id,+ entity_type: r.entity_type,+ entity_id: r.entity_id,+ created_at: r.created_at,+ });+ }++ Ok(map)+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_channel_attachments(+ &self,+ channel_id: Uuid,+ query: &Query<Uuid, CreatedAt, ()>,+ limit: u16,+ ) -> Result<Vec<ChannelAttachment>, Self::Err> {+ let (cursor_created_at, cursor_id) = match query.vals() {+ (Some(id), Some(val)) => (Some(*val), Some(*id)),+ _ => (None, None),+ };++ let rows = sqlx::query_as!(+ ChannelAttachmentRow,+ r#"+ SELECT id, channel_id, message_id, entity_type, entity_id,+ width AS "width?", height AS "height?", created_at+ FROM comms_attachments+ WHERE channel_id = $1+ AND ($2::timestamptz IS NULL OR (created_at, id) < ($2, $3))+ ORDER BY created_at DESC, id DESC+ LIMIT $4+ "#,+ channel_id,+ cursor_created_at,+ cursor_id,+ i64::from(limit) as i64,+ )+ .fetch_all(&self.pool)+ .await?;++ Ok(rows+ .into_iter()+ .map(|r| ChannelAttachment {+ id: r.id,+ channel_id: r.channel_id,+ message_id: r.message_id,+ entity_type: r.entity_type,+ entity_id: r.entity_id,+ width: r.width,+ height: r.height,+ created_at: r.created_at,+ })+ .collect())+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_channel_participants(+ &self,+ channel_id: Uuid,+ ) -> Result<Vec<ChannelParticipant>, Self::Err> {+ let rows = sqlx::query_as!(+ ParticipantRow,+ r#"+ SELECT channel_id, user_id, role::text AS "role!", joined_at,+ left_at AS "left_at?"+ FROM comms_channel_participants+ WHERE channel_id = $1 AND left_at IS NULL+ ORDER BY joined_at ASC+ "#,+ channel_id,+ )+ .fetch_all(&self.pool)+ .await?;++ Ok(rows+ .into_iter()+ .map(|r| ChannelParticipant {+ channel_id: r.channel_id,+ user_id: r.user_id,+ role: r+ .role+ .parse::<ParticipantRole>()+ .unwrap_or(ParticipantRole::Member),+ joined_at: r.joined_at,+ left_at: r.left_at,+ })+ .collect())+ }+}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.rsnew file mode 100644index 0000000000..b483aa6abb--- /dev/null+++ b/rust/cloud-storage/channels/src/outbound/pg_channels_repo/tests.rs@@ -0,0 +1,316 @@+use crate::domain::models::ParticipantRole;+use crate::domain::ports::ChannelMessagesRepo;+use crate::outbound::pg_channels_repo::PgChannelMessagesRepo;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use models_pagination::{CreatedAt, Cursor, CursorVal, Query};+use sqlx::{Pool, Postgres};+use uuid::Uuid;++const CH1: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000c01);+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);++fn repo(pool: Pool<Postgres>) -> PgChannelMessagesRepo {+ PgChannelMessagesRepo::new(pool)+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+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)+ .await?;++ let ids: Vec<Uuid> = rows.iter().map(|r| r.id).collect();+ // msg1, msg2 (deleted but has active reply), msg3 — but NOT msg4 (fully deleted)+ assert_eq!(ids.len(), 3);+ assert!(ids.contains(&MSG1));+ assert!(ids.contains(&MSG2));+ assert!(ids.contains(&MSG3));+ // msg4 (fully deleted, no active replies) must not appear+ let msg4 = Uuid::from_u128(0x00000000_0000_0000_0000_000000000004);+ assert!(!ids.contains(&msg4));+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+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)+ .await?;++ let ids: Vec<Uuid> = rows.iter().map(|r| r.id).collect();+ assert_eq!(ids, vec![MSG3, MSG2, MSG1]);+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn top_level_cursor_skips_earlier_messages(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);+ // First fetch all to get cursor values+ let all = repo+ .get_top_level_messages(CH1, &Query::Sort(CreatedAt, ()), 50)+ .await?;+ assert_eq!(all.len(), 3);++ // Use msg3 (newest) as cursor → should skip msg3, return msg2 + msg1+ let cursor = Query::Cursor(Cursor {+ id: MSG3,+ limit: 50,+ val: CursorVal {+ sort_type: CreatedAt,+ last_val: all[0].created_at,+ },+ filter: (),+ });+ let page2 = repo.get_top_level_messages(CH1, &cursor, 50).await?;+ 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_limit_is_respected(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);+ let rows = repo+ .get_top_level_messages(CH1, &Query::Sort(CreatedAt, ()), 2)+ .await?;++ assert_eq!(rows.len(), 2);+ // Should be the 2 newest+ assert_eq!(rows[0].id, MSG3);+ assert_eq!(rows[1].id, MSG2);+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+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)+ .await?;++ assert_eq!(rows.len(), 1);+ assert_eq!(rows[0].content, "other channel msg");+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn thread_data_preview_count_limits_replies(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);+ // msg1 has 4 replies; ask for preview of 2+ let map = repo.get_thread_data(&[MSG1], 2).await?;+ let thread = map.get(&MSG1).expect("thread data for msg1");++ assert_eq!(+ thread.reply_count, 4,+ "reply_count reflects total, not preview"+ );+ assert_eq!(+ thread.preview_replies.len(),+ 2,+ "only 2 preview replies returned"+ );+ // Preview should be the 2 most recent, in oldest-first order+ assert_eq!(thread.preview_replies[0].content, "reply 3");+ assert_eq!(thread.preview_replies[1].content, "reply 4");+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn thread_data_latest_reply_at_is_most_recent(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);+ let map = repo.get_thread_data(&[MSG1], 10).await?;+ let thread = map.get(&MSG1).unwrap();++ // reply 4 is at 10:04 — should be the latest+ let last = thread.preview_replies.last().unwrap();+ assert_eq!(thread.latest_reply_at, Some(last.created_at));+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn thread_data_multiple_parents(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);+ let map = repo.get_thread_data(&[MSG1, MSG2], 10).await?;++ assert!(map.contains_key(&MSG1));+ assert!(map.contains_key(&MSG2));+ assert_eq!(map[&MSG1].reply_count, 4);+ assert_eq!(map[&MSG2].reply_count, 1);+ assert_eq!(map[&MSG2].preview_replies[0].content, "reply to deleted");+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn reactions_grouped_by_emoji(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);+ let map = repo.get_reactions_batch(&[MSG1, MSG3]).await?;++ // msg1 has thumbsup (2 users) and tada (1 user)+ let msg1_reactions = map.get(&MSG1).unwrap();+ let thumbsup = msg1_reactions+ .iter()+ .find(|r| r.emoji == "\u{1f44d}")+ .unwrap();+ assert_eq!(thumbsup.users.len(), 2);+ let tada = msg1_reactions+ .iter()+ .find(|r| r.emoji == "\u{1f389}")+ .unwrap();+ assert_eq!(tada.users.len(), 1);++ // msg3 has thumbsup (1 user)+ let msg3_reactions = map.get(&MSG3).unwrap();+ assert_eq!(msg3_reactions.len(), 1);+ assert_eq!(msg3_reactions[0].users.len(), 1);++ // msg2 has no reactions+ assert!(map.get(&MSG2).is_none());+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn attachments_batch_grouped_by_message(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);+ let map = repo.get_attachments_batch(&[MSG1, MSG2, MSG3]).await?;++ assert_eq!(map[&MSG1].len(), 2);+ assert_eq!(map[&MSG3].len(), 1);+ assert!(map.get(&MSG2).is_none(), "msg2 has no attachments");+ Ok(())+}++// -- get_channel_attachments -----------------------------------------------++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn channel_attachments_cursor_pagination(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);+ // ch1 has 3 attachments total (a001, a002 on msg1, a003 on msg3)+ let page1 = repo+ .get_channel_attachments(CH1, &Query::Sort(CreatedAt, ()), 2)+ .await?;+ assert_eq!(page1.len(), 2, "limit respected");++ // Use last item as cursor for next page+ let last = &page1[1];+ let cursor = Query::Cursor(Cursor {+ id: last.id,+ limit: 2,+ val: CursorVal {+ sort_type: CreatedAt,+ last_val: last.created_at,+ },+ filter: (),+ });+ let page2 = repo.get_channel_attachments(CH1, &cursor, 2).await?;+ assert_eq!(page2.len(), 1, "remaining attachment");++ // No overlap between pages+ let p1_ids: Vec<Uuid> = page1.iter().map(|a| a.id).collect();+ let p2_ids: Vec<Uuid> = page2.iter().map(|a| a.id).collect();+ assert!(p1_ids.iter().all(|id| !p2_ids.contains(id)));+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn channel_attachments_include_dimensions(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);+ let all = repo+ .get_channel_attachments(CH1, &Query::Sort(CreatedAt, ()), 50)+ .await?;++ let img = all.iter().find(|a| a.entity_type == "image").unwrap();+ assert_eq!(img.width, Some(800));+ assert_eq!(img.height, Some(600));++ let doc = all.iter().find(|a| a.entity_id == "doc-1").unwrap();+ assert_eq!(doc.width, None);+ assert_eq!(doc.height, None);+ Ok(())+}++// -- get_channel_participants ----------------------------------------------++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn participants_excludes_left_users(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);+ let participants = repo.get_channel_participants(CH1).await?;++ let user_ids: Vec<&str> = participants.iter().map(|p| p.user_id.as_str()).collect();+ assert_eq!(participants.len(), 3);+ assert!(!user_ids.contains(&"macro|[email protected]"));+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn participants_roles_parsed_correctly(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);+ let participants = repo.get_channel_participants(CH1).await?;++ let owner = participants+ .iter()+ .find(|p| p.user_id == "macro|[email protected]")+ .unwrap();+ assert_eq!(owner.role, ParticipantRole::Owner);++ let admin = participants+ .iter()+ .find(|p| p.user_id == "macro|[email protected]")+ .unwrap();+ assert_eq!(admin.role, ParticipantRole::Admin);++ let member = participants+ .iter()+ .find(|p| p.user_id == "macro|[email protected]")+ .unwrap();+ assert_eq!(member.role, ParticipantRole::Member);+ Ok(())+}diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.tomlindex b7b513b0d8..37733bd4c2 100644--- a/rust/cloud-storage/document_storage_service/Cargo.toml+++ b/rust/cloud-storage/document_storage_service/Cargo.toml@@ -44,6 +44,7 @@ bzip2 = { workspace = true, default-features = false, features = [chrono = { workspace = true }clap = { workspace = true }cloudfront_sign = { workspace = true }+channels = { path = "../channels", features = ["inbound", "outbound"] }comms = { path = "../comms", features = ["outbound"] }connection_gateway = { path = "../connection_gateway" }document_sub_type = { path = "../document_sub_type" }diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rsindex 82e3f22495..ec838576dc 100644--- a/rust/cloud-storage/document_storage_service/src/api/context.rs+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs@@ -1,5 +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,+};use comms::{domain::service::ChannelServiceImpl,inbound::CommsRouterState,@@ -66,6 +70,10 @@ pub(crate) type CommsChannelService =/// Type alias for the CommsRouterStatepub(crate) type CommsState = CommsRouterState<CommsChannelService>;+/// Type alias for the channels router state.+pub(crate) type DssChannelsState =+ ChannelsRouterState<ChannelMessagesServiceImpl<PgChannelMessagesRepo>>;+#[derive(Clone, FromRef)]pub(crate) struct ApiContext {pub db: PgPool,@@ -90,6 +98,7 @@ pub(crate) struct ApiContext {pub permissions_token_secret:LocalOrRemoteSecret<comms_service::DocumentPermissionJwtSecretKey>,pub entity_access_service: Arc<EntityAccessService>,+ pub channels_state: DssChannelsState,}env_var! {diff --git a/rust/cloud-storage/document_storage_service/src/api/mod.rs b/rust/cloud-storage/document_storage_service/src/api/mod.rsindex 00e1483043..7ad52248dd 100644--- a/rust/cloud-storage/document_storage_service/src/api/mod.rs+++ b/rust/cloud-storage/document_storage_service/src/api/mod.rs@@ -167,6 +167,10 @@ fn api_router(state: ApiContext) -> Router {.with_state(CommsHandlerState::from_ref(&state)),).nest("/entity", entity::router())+ .nest(+ "/channels",+ channels::inbound::axum_router::channels_router(state.channels_state.clone()),+ ).layer(ServiceBuilder::new().layer(axum::middleware::from_fn(diff --git a/rust/cloud-storage/document_storage_service/src/api/swagger.rs b/rust/cloud-storage/document_storage_service/src/api/swagger.rsindex 1671ee78d1..c39b9fa33a 100644--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs@@ -65,6 +65,11 @@ use crate::{},},};+use channels::inbound::axum_router::{+ ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelMessage, ApiChannelMessagesPage,+ ApiChannelParticipant, ApiCountedReaction, ApiMessageAttachment, ApiParticipantRole,+ ApiThreadInfo, ApiThreadReply,+};use document_sub_type::DocumentSubType;use model::document::response::{CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData,@@ -178,6 +183,11 @@ use utoipa::OpenApi;soup::inbound::axum_router::get_soup_handler,soup::inbound::axum_router::post_soup_handler,+ // channels+ channels::inbound::axum_router::get_channel_messages_handler,+ channels::inbound::axum_router::get_channel_attachments_handler,+ channels::inbound::axum_router::get_channel_participants_handler,+// pinspins::add_pin::add_pin_handler,pins::remove_pin::remove_pin_handler,@@ -298,6 +308,18 @@ use utoipa::OpenApi;SoupLabelType,PostSoupRequest,+ // Channels+ ApiChannelMessagesPage,+ ApiChannelMessage,+ ApiThreadInfo,+ ApiThreadReply,+ ApiCountedReaction,+ ApiMessageAttachment,+ ApiChannelAttachmentsPage,+ ApiChannelAttachment,+ ApiChannelParticipant,+ ApiParticipantRole,+DocumentSubType,diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rsindex 77f6e43c5d..82c9441551 100644--- a/rust/cloud-storage/document_storage_service/src/main.rs+++ b/rust/cloud-storage/document_storage_service/src/main.rs@@ -6,6 +6,10 @@ use crate::{service::s3::S3,};use anyhow::Context;+use channels::{+ domain::service::ChannelMessagesServiceImpl, inbound::axum_router::ChannelsRouterState,+ outbound::pg_channels_repo::PgChannelMessagesRepo,+};use comms::{domain::service::ChannelServiceImpl,inbound::CommsRouterState,@@ -279,6 +283,9 @@ async fn main() -> anyhow::Result<()> {entity_access::outbound::PgAccessRepository::new(db.clone()),),),+ channels_state: ChannelsRouterState::new(ChannelMessagesServiceImpl::new(+ PgChannelMessagesRepo::new(db.clone()),+ )),};api::setup_and_serve(api_context).await?;diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfileindex 2649261d89..c0b989b039 100644--- a/rust/cloud-storage/justfile+++ b/rust/cloud-storage/justfile@@ -80,6 +80,7 @@ setup_test_envs:echo "DATABASE_URL={{ MACRODB }}" >> ./email_contact_search/.envecho "DATABASE_URL={{ MACRODB }}" >> ./email_scheduled_handler/.envecho "DATABASE_URL={{ MACRODB }}" >> ./saved_views/.env+ echo "DATABASE_URL={{ MACRODB }}" >> ./channels/.envecho "DATABASE_URL={{ MACRODB }}" >> ./comms_service/.envsetup_macrodb: