Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(bots): Sender, Bots, Channel Bots (#3647)

teoee473313a521
diff --git a/js/app/packages/block-call/component/CallTranscript.tsx b/js/app/packages/block-call/component/CallTranscript.tsx
index 7ef6d1c440..b18df28c02 100644
--- a/js/app/packages/block-call/component/CallTranscript.tsx
+++ b/js/app/packages/block-call/component/CallTranscript.tsx
@@ -3,6 +3,7 @@ import { Thread } from '@channel/Thread/Thread';
import { CustomScrollbar } from '@core/component/CustomScrollbar';
import { formatVideoTimestamp } from '@core/util/duration';
import Subtitles from '@phosphor/subtitles.svg';
+import { senderFromStorageId } from '@queries/channel/message-sender';
import type { ApiChannelMessage } from '@service-comms/client';
import type { CallRecordTranscriptSegment } from '@service-storage/generated/schemas/callRecordTranscriptSegment';
import {
@@ -83,6 +84,7 @@ function segmentToApiChannelMessage(
id: s.segmentId ?? `transcript-${s.sequenceNum}`,
channel_id: channelId,
content: s.content,
+ sender: senderFromStorageId(s.speakerId),
sender_id: s.speakerId,
created_at: s.startedAt,
updated_at: s.startedAt,
diff --git a/js/app/packages/block-md/comments/discussionAdapter.ts b/js/app/packages/block-md/comments/discussionAdapter.ts
index c59233cbc1..9dafd6e985 100644
--- a/js/app/packages/block-md/comments/discussionAdapter.ts
+++ b/js/app/packages/block-md/comments/discussionAdapter.ts
@@ -1,4 +1,5 @@
import type { MessageData } from '@channel/Message/types';
+import { senderFromStorageId } from '@queries/channel/message-sender';
import type { ApiChannelMessage } from '@service-storage/generated/schemas/apiChannelMessage';
import type { Comment } from '@service-storage/generated/schemas/comment';
@@ -25,6 +26,7 @@ export function commentToApiChannelMessage(
return {
id: String(comment.commentId),
content: comment.text,
+ sender: senderFromStorageId(comment.sender ?? comment.owner),
sender_id: comment.sender ?? comment.owner,
created_at: comment.createdAt ?? '',
updated_at: comment.updatedAt ?? comment.createdAt ?? '',
diff --git a/js/app/packages/channel/Channel/tests/message-grouping-meta.test.ts b/js/app/packages/channel/Channel/tests/message-grouping-meta.test.ts
index 2ef11aa250..c82d67aeb9 100644
--- a/js/app/packages/channel/Channel/tests/message-grouping-meta.test.ts
+++ b/js/app/packages/channel/Channel/tests/message-grouping-meta.test.ts
@@ -1,3 +1,4 @@
+import { senderFromStorageId } from '@queries/channel/message-sender';
import type { ApiChannelMessage } from '@service-comms/client';
import { describe, expect, it } from 'vitest';
import {
@@ -16,6 +17,7 @@ function createMessage(
content: '',
created_at: createdAt,
updated_at: createdAt,
+ sender: senderFromStorageId(senderId),
sender_id: senderId,
attachments: [],
reactions: [],
diff --git a/js/app/packages/channel/Channel/tests/message-list-meta.test.ts b/js/app/packages/channel/Channel/tests/message-list-meta.test.ts
index e0c51b626a..15337f5334 100644
--- a/js/app/packages/channel/Channel/tests/message-list-meta.test.ts
+++ b/js/app/packages/channel/Channel/tests/message-list-meta.test.ts
@@ -1,3 +1,4 @@
+import { senderFromStorageId } from '@queries/channel/message-sender';
import type { ApiChannelMessage } from '@service-comms/client';
import { describe, expect, it } from 'vitest';
import { buildChannelMessageListMeta } from '../message-list-meta';
@@ -13,6 +14,7 @@ function createMessage(
content: '',
created_at: createdAt,
updated_at: createdAt,
+ sender: senderFromStorageId(senderId),
sender_id: senderId,
attachments: [],
reactions: [],
diff --git a/js/app/packages/channel/Thread/tests/reply-list-meta.test.ts b/js/app/packages/channel/Thread/tests/reply-list-meta.test.ts
index ef48351d89..40a29445ad 100644
--- a/js/app/packages/channel/Thread/tests/reply-list-meta.test.ts
+++ b/js/app/packages/channel/Thread/tests/reply-list-meta.test.ts
@@ -1,3 +1,4 @@
+import { senderFromStorageId } from '@queries/channel/message-sender';
import type { ApiThreadReply } from '@service-comms/client';
import { describe, expect, it } from 'vitest';
import { buildThreadReplyListMeta } from '../reply-list-meta';
@@ -12,6 +13,7 @@ function createReply(
content: '',
created_at: createdAt,
updated_at: createdAt,
+ sender: senderFromStorageId(senderId),
sender_id: senderId,
attachments: [],
reactions: [],
diff --git a/js/app/packages/queries/channel/channel-messages.ts b/js/app/packages/queries/channel/channel-messages.ts
index 0c3e30daec..d9a0a4d25b 100644
--- a/js/app/packages/queries/channel/channel-messages.ts
+++ b/js/app/packages/queries/channel/channel-messages.ts
@@ -16,6 +16,10 @@ import { type Accessor, createEffect, on } from 'solid-js';
import { createStore, reconcile } from 'solid-js/store';
import { queryClient } from '../client';
import { channelKeys } from './keys';
+import {
+ normalizeChannelMessageSender,
+ normalizeChannelMessagesPageSenders,
+} from './message-sender';
import {
captureThreadPreviewReplySnapshot,
insertReplyIntoThreadPreview,
@@ -68,7 +72,7 @@ export function channelMessagesQueryOptions(
}: {
pageParam: ChannelMessagesPageParam | null;
}) => {
- return await throwOnErr(
+ const page = await throwOnErr(
async () =>
await storageServiceClient.getChannelMessages({
channel_id: channelId,
@@ -78,6 +82,7 @@ export function channelMessagesQueryOptions(
load_around_message_id: !pageParam ? loadAroundMessageId : null,
})
);
+ return normalizeChannelMessagesPageSenders(page);
},
initialPageParam: null as ChannelMessagesPageParam | null,
getNextPageParam: (lastPage: ChannelMessagesPage) =>
@@ -130,7 +135,7 @@ export function useChannelMessagesByIdsQuery(
filters: { message_ids: resolvedMessageIds },
})
);
- return page.items;
+ return page.items.map(normalizeChannelMessageSender);
},
enabled: resolvedMessageIds.length > 0,
staleTime: Infinity,
diff --git a/js/app/packages/queries/channel/message-sender.ts b/js/app/packages/queries/channel/message-sender.ts
new file mode 100644
index 0000000000..5659729d4d
--- /dev/null
+++ b/js/app/packages/queries/channel/message-sender.ts
@@ -0,0 +1,70 @@
+import type {
+ ApiChannelMessage,
+ ApiThreadReply,
+ ChannelMessagesPage,
+} from '@service-storage/client';
+import type { ApiMessageSender } from '@service-storage/generated/schemas/apiMessageSender';
+
+type WithMaybeSender<
+ T extends { sender_id: string; sender: ApiMessageSender },
+> = Omit<T, 'sender'> & { sender?: ApiMessageSender };
+
+export type ThreadReplyWithMaybeSender = WithMaybeSender<ApiThreadReply>;
+
+export type ChannelMessageWithMaybeSender = Omit<
+ WithMaybeSender<ApiChannelMessage>,
+ 'thread'
+> & {
+ thread: Omit<ApiChannelMessage['thread'], 'preview'> & {
+ preview: ThreadReplyWithMaybeSender[];
+ };
+};
+
+// Temporary compatibility for API nodes that only return sender_id.
+// Remove once all deployed channel message responses include sender.
+export function senderFromStorageId(senderId: string): ApiMessageSender {
+ if (senderId.startsWith('bot|')) {
+ return { type: 'bot', id: senderId.slice('bot|'.length) };
+ }
+
+ return { type: 'user', id: senderId };
+}
+
+export function normalizeMessageSender<
+ T extends { sender_id: string; sender?: ApiMessageSender },
+>(message: T): T & { sender: ApiMessageSender } {
+ return message.sender
+ ? (message as T & { sender: ApiMessageSender })
+ : { ...message, sender: senderFromStorageId(message.sender_id) };
+}
+
+export function normalizeThreadReplySender(
+ reply: ThreadReplyWithMaybeSender
+): ApiThreadReply {
+ return normalizeMessageSender(reply);
+}
+
+export function normalizeChannelMessageSender(
+ message: ChannelMessageWithMaybeSender
+): ApiChannelMessage {
+ const normalized = normalizeMessageSender(message);
+
+ return {
+ ...normalized,
+ thread: {
+ ...normalized.thread,
+ preview: normalized.thread.preview.map(normalizeThreadReplySender),
+ },
+ };
+}
+
+export function normalizeChannelMessagesPageSenders(
+ page: Omit<ChannelMessagesPage, 'items'> & {
+ items: ChannelMessageWithMaybeSender[];
+ }
+): ChannelMessagesPage {
+ return {
+ ...page,
+ items: page.items.map(normalizeChannelMessageSender),
+ };
+}
diff --git a/js/app/packages/queries/channel/message.ts b/js/app/packages/queries/channel/message.ts
index 32ba8691c8..ed4f8e9e5a 100644
--- a/js/app/packages/queries/channel/message.ts
+++ b/js/app/packages/queries/channel/message.ts
@@ -26,6 +26,7 @@ import { queryClient } from '../client';
import { createMutationNonce, registerNonce } from '../nonce';
import { getChannelMessagesQueryKeyPrefix } from './channel-messages';
import { ChannelNonceKeys } from './keys';
+import { senderFromStorageId } from './message-sender';
import {
captureDeleteSnapshotForTarget,
type DeleteTargetSnapshot,
@@ -121,6 +122,7 @@ function makeOptimisticTopLevelMessage(
return {
id: vars.optimisticId,
channel_id: vars.channelId,
+ sender: senderFromStorageId(vars.senderId),
sender_id: vars.senderId,
content: vars.content,
created_at: now,
@@ -144,6 +146,7 @@ function makeOptimisticThreadReply(
): ApiThreadReply {
return {
id: vars.optimisticId,
+ sender: senderFromStorageId(vars.senderId),
sender_id: vars.senderId,
content: vars.content,
created_at: now,
diff --git a/js/app/packages/queries/channel/sync.ts b/js/app/packages/queries/channel/sync.ts
index cb212964f4..45f02883d4 100644
--- a/js/app/packages/queries/channel/sync.ts
+++ b/js/app/packages/queries/channel/sync.ts
@@ -4,8 +4,10 @@ import type {
CountedReaction,
} from '@service-comms/generated/models';
import type { ApiThreadReply } from '@service-storage/client';
+import type { ApiMessageSender } from '@service-storage/generated/schemas/apiMessageSender';
import { consumeNonce } from '../nonce';
import { ChannelNonceKeys } from './keys';
+import { senderFromStorageId } from './message-sender';
import {
getTargetMessageState,
insertMessageIntoTargetCaches,
@@ -22,7 +24,11 @@ import {
/**
* Websocket payload types
*/
-type CommsMessagePayload = ApiMessage & { channel_id: string; nonce: string };
+type CommsMessagePayload = ApiMessage & {
+ channel_id: string;
+ nonce: string;
+ sender?: ApiMessageSender;
+};
type CommsReactionPayload = {
channel_id: string;
@@ -94,6 +100,7 @@ export function handleCommsMessage(payload: CommsMessagePayload): void {
} else if (target.kind === 'thread_reply') {
const reply: ApiThreadReply = {
id: payload.id,
+ sender: payload.sender ?? senderFromStorageId(payload.sender_id),
sender_id: payload.sender_id,
content: payload.content,
created_at: payload.created_at,
@@ -107,6 +114,7 @@ export function handleCommsMessage(payload: CommsMessagePayload): void {
insertMessageIntoTargetCaches(payload.channel_id, target, {
id: payload.id,
channel_id: payload.channel_id,
+ sender: payload.sender ?? senderFromStorageId(payload.sender_id),
sender_id: payload.sender_id,
content: payload.content,
created_at: payload.created_at,
diff --git a/js/app/packages/queries/channel/tests/channel-optimistic.test.ts b/js/app/packages/queries/channel/tests/channel-optimistic.test.ts
index 536e141257..a1176ddef1 100644
--- a/js/app/packages/queries/channel/tests/channel-optimistic.test.ts
+++ b/js/app/packages/queries/channel/tests/channel-optimistic.test.ts
@@ -42,6 +42,10 @@ import {
rollbackInsertChannelMessage,
rollbackUpdateChannelMessage,
} from '../message';
+import {
+ normalizeChannelMessageSender,
+ normalizeThreadReplySender,
+} from '../message-sender';
import {
optimisticAddReaction,
optimisticRemoveReaction,
@@ -55,7 +59,7 @@ function createPaginatedMessage(
createdAt: string,
overrides: Partial<ApiChannelMessage> = {}
): ApiChannelMessage {
- return {
+ return normalizeChannelMessageSender({
id,
channel_id: 'channel-1',
sender_id: 'user-1',
@@ -72,7 +76,7 @@ function createPaginatedMessage(
latest_reply_at: null,
},
...overrides,
- };
+ });
}
function createThreadReply(
@@ -80,7 +84,7 @@ function createThreadReply(
createdAt: string,
overrides: Partial<ApiThreadReply> = {}
): ApiThreadReply {
- return {
+ return normalizeThreadReplySender({
id,
sender_id: 'user-1',
content: `Reply ${id}`,
@@ -90,7 +94,7 @@ function createThreadReply(
attachments: [],
reactions: [],
...overrides,
- };
+ });
}
function createChannelMessagesData(
diff --git a/js/app/packages/queries/channel/tests/message-sender.test.ts b/js/app/packages/queries/channel/tests/message-sender.test.ts
new file mode 100644
index 0000000000..6b8621631e
--- /dev/null
+++ b/js/app/packages/queries/channel/tests/message-sender.test.ts
@@ -0,0 +1,63 @@
+import { describe, expect, it } from 'vitest';
+import {
+ type ChannelMessageWithMaybeSender,
+ normalizeChannelMessageSender,
+ senderFromStorageId,
+} from '../message-sender';
+
+function legacyMessage(
+ senderId: string,
+ replySenderId = 'macro|[email protected]'
+): ChannelMessageWithMaybeSender {
+ return {
+ id: 'message-1',
+ channel_id: 'channel-1',
+ sender_id: senderId,
+ content: 'hello',
+ created_at: '2026-05-28T10:00:00.000Z',
+ updated_at: '2026-05-28T10:00:00.000Z',
+ attachments: [],
+ reactions: [],
+ thread: {
+ preview: [
+ {
+ id: 'reply-1',
+ sender_id: replySenderId,
+ content: 'reply',
+ created_at: '2026-05-28T10:01:00.000Z',
+ updated_at: '2026-05-28T10:01:00.000Z',
+ attachments: [],
+ reactions: [],
+ },
+ ],
+ reply_count: 1,
+ latest_reply_at: '2026-05-28T10:01:00.000Z',
+ },
+ };
+}
+
+describe('message sender normalization', () => {
+ it('derives user senders for old channel message payloads', () => {
+ const message = normalizeChannelMessageSender(
+ legacyMessage('macro|[email protected]')
+ );
+
+ expect(message.sender).toEqual({
+ type: 'user',
+ id: 'macro|[email protected]',
+ });
+ expect(message.thread.preview[0].sender).toEqual({
+ type: 'user',
+ id: 'macro|[email protected]',
+ });
+ });
+
+ it('derives bot sender ids from storage ids', () => {
+ expect(
+ senderFromStorageId('bot|00000000-0000-0000-0000-000000000001')
+ ).toEqual({
+ type: 'bot',
+ id: '00000000-0000-0000-0000-000000000001',
+ });
+ });
+});
diff --git a/js/app/packages/queries/channel/tests/sync.test.ts b/js/app/packages/queries/channel/tests/sync.test.ts
index 5b299174a8..9e6801cf66 100644
--- a/js/app/packages/queries/channel/tests/sync.test.ts
+++ b/js/app/packages/queries/channel/tests/sync.test.ts
@@ -24,6 +24,10 @@ vi.mock('@service-storage/client', () => ({
import type { ChannelMessagesData } from '../channel-messages';
import { getChannelMessagesQueryKey } from '../channel-messages';
+import {
+ normalizeChannelMessageSender,
+ normalizeThreadReplySender,
+} from '../message-sender';
import {
handleCommsAttachment,
handleCommsMessage,
@@ -36,7 +40,7 @@ function createPaginatedMessage(
createdAt: string,
overrides: Partial<ApiChannelMessage> = {}
): ApiChannelMessage {
- return {
+ return normalizeChannelMessageSender({
id,
channel_id: 'channel-1',
sender_id: 'user-1',
@@ -53,7 +57,7 @@ function createPaginatedMessage(
latest_reply_at: null,
},
...overrides,
- };
+ });
}
function createThreadReply(
@@ -61,7 +65,7 @@ function createThreadReply(
createdAt: string,
overrides: Partial<ApiThreadReply> = {}
): ApiThreadReply {
- return {
+ return normalizeThreadReplySender({
id,
sender_id: 'user-1',
content: `Reply ${id}`,
@@ -71,7 +75,7 @@ function createThreadReply(
attachments: [],
reactions: [],
...overrides,
- };
+ });
}
function createAttachment(id: string, messageId: string): ApiAttachment {
diff --git a/js/app/packages/queries/preview/fetchers.ts b/js/app/packages/queries/preview/fetchers.ts
index 257601020c..d007671471 100644
--- a/js/app/packages/queries/preview/fetchers.ts
+++ b/js/app/packages/queries/preview/fetchers.ts
@@ -5,6 +5,7 @@ import { emailClient } from '@service-email/client';
import { storageServiceClient } from '@service-storage/client';
import type { FileType } from '@service-storage/generated/schemas/fileType';
import { formatDocumentName } from '@service-storage/util/filename';
+import { normalizeMessageSender } from '../channel/message-sender';
import type { ItemEntity, MessageContext, PreviewItem } from './types';
async function fetchChannelPreviews(
@@ -69,7 +70,7 @@ export async function fetchMessageContext(
return null;
}
- return message;
+ return normalizeMessageSender(message);
}
async function fetchDocumentPreviews(ids: string[]): Promise<PreviewItem[]> {
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelContextMessage.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelContextMessage.ts
index 2fb18ac1ed..61aff2ebc9 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelContextMessage.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelContextMessage.ts
@@ -7,6 +7,7 @@
import type { ApiChannelContextMessageDeletedAt } from './apiChannelContextMessageDeletedAt';
import type { ApiChannelContextMessageEditedAt } from './apiChannelContextMessageEditedAt';
import type { ApiChannelContextMessageThreadId } from './apiChannelContextMessageThreadId';
+import type { ApiMessageSender } from './apiMessageSender';
/**
* A channel message returned by the message-context endpoint.
@@ -24,6 +25,8 @@ export interface ApiChannelContextMessage {
edited_at?: ApiChannelContextMessageEditedAt;
/** Message id. */
id: string;
+ /** Structured sender identity. */
+ sender: ApiMessageSender;
/** Sender user id. */
sender_id: string;
/** Parent thread id for replies. */
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.ts
index 256377a1c5..b1b363a82d 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelMessage.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiChannelMessage.ts
@@ -9,6 +9,7 @@ import type { ApiChannelMessageDeletedAt } from './apiChannelMessageDeletedAt';
import type { ApiChannelMessageEditedAt } from './apiChannelMessageEditedAt';
import type { ApiCountedReaction } from './apiCountedReaction';
import type { ApiMessageAttachment } from './apiMessageAttachment';
+import type { ApiMessageSender } from './apiMessageSender';
import type { ApiThreadInfo } from './apiThreadInfo';
/**
@@ -31,6 +32,8 @@ export interface ApiChannelMessage {
id: string;
/** Reactions on this message. */
reactions: ApiCountedReaction[];
+ /** Structured sender identity. */
+ sender: ApiMessageSender;
/** Sender user id. */
sender_id: string;
/** Thread metadata and preview. */
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiMessageSender.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiMessageSender.ts
new file mode 100644
index 0000000000..b5e85e8c33
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiMessageSender.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ApiMessageSenderType } from './apiMessageSenderType';
+
+/**
+ * Public sender identity for channel messages.
+ */
+export interface ApiMessageSender {
+ /** Sender id without the storage namespace prefix. */
+ id: string;
+ /** Sender type. */
+ type: ApiMessageSenderType;
+}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiMessageSenderType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiMessageSenderType.ts
new file mode 100644
index 0000000000..aa8f0c2bb0
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiMessageSenderType.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Public sender type.
+ */
+export type ApiMessageSenderType =
+ (typeof ApiMessageSenderType)[keyof typeof ApiMessageSenderType];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const ApiMessageSenderType = {
+ user: 'user',
+ bot: 'bot',
+} as const;
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.ts
index 043b2fc5fa..f7f7c00fc9 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/apiThreadReply.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiThreadReply.ts
@@ -7,6 +7,7 @@
import type { ApiCountedReaction } from './apiCountedReaction';
import type { ApiMessageAttachment } from './apiMessageAttachment';
+import type { ApiMessageSender } from './apiMessageSender';
import type { ApiThreadReplyEditedAt } from './apiThreadReplyEditedAt';
/**
@@ -25,6 +26,8 @@ export interface ApiThreadReply {
id: string;
/** Reactions on this reply. */
reactions: ApiCountedReaction[];
+ /** Structured sender identity. */
+ sender: ApiMessageSender;
/** Sender user id. */
sender_id: string;
/** When the reply was last updated. */
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
index 4bdd5a3a6a..15d681d6fb 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
@@ -78,6 +78,8 @@ export * from './apiEntityFilterAst';
export * from './apiMessageAttachment';
export * from './apiMessageAttachmentHeight';
export * from './apiMessageAttachmentWidth';
+export * from './apiMessageSender';
+export * from './apiMessageSenderType';
export * from './apiParticipantRole';
export * from './apiResolvedChannelMessage';
export * from './apiThreadInfo';
diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.ts
index 28512b25b0..99ea269777 100644
--- a/js/app/packages/service-clients/service-storage/generated/zod.ts
+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts
@@ -1841,6 +1841,14 @@ export const getChannelMessagesResponse = zod
.describe('A reaction with emoji and user list.')
)
.describe('Reactions on this message.'),
+ sender: zod
+ .object({
+ id: zod
+ .string()
+ .describe('Sender id without the storage namespace prefix.'),
+ type: zod.enum(['user', 'bot']).describe('Public sender type.'),
+ })
+ .describe('Public sender identity for channel messages.'),
sender_id: zod.string().describe('Sender user id.'),
thread: zod
.object({
@@ -1901,6 +1909,20 @@ export const getChannelMessagesResponse = zod
.describe('A reaction with emoji and user list.')
)
.describe('Reactions on this reply.'),
+ sender: zod
+ .object({
+ id: zod
+ .string()
+ .describe(
+ 'Sender id without the storage namespace prefix.'
+ ),
+ type: zod
+ .enum(['user', 'bot'])
+ .describe('Public sender type.'),
+ })
+ .describe(
+ 'Public sender identity for channel messages.'
+ ),
sender_id: zod.string().describe('Sender user id.'),
updated_at: zod.iso
.datetime({})
@@ -2063,6 +2085,14 @@ export const postChannelMessagesResponse = zod
.describe('A reaction with emoji and user list.')
)
.describe('Reactions on this message.'),
+ sender: zod
+ .object({
+ id: zod
+ .string()
+ .describe('Sender id without the storage namespace prefix.'),
+ type: zod.enum(['user', 'bot']).describe('Public sender type.'),
+ })
+ .describe('Public sender identity for channel messages.'),
sender_id: zod.string().describe('Sender user id.'),
thread: zod
.object({
@@ -2123,6 +2153,20 @@ export const postChannelMessagesResponse = zod
.describe('A reaction with emoji and user list.')
)
.describe('Reactions on this reply.'),
+ sender: zod
+ .object({
+ id: zod
+ .string()
+ .describe(
+ 'Sender id without the storage namespace prefix.'
+ ),
+ type: zod
+ .enum(['user', 'bot'])
+ .describe('Public sender type.'),
+ })
+ .describe(
+ 'Public sender identity for channel messages.'
+ ),
sender_id: zod.string().describe('Sender user id.'),
updated_at: zod.iso
.datetime({})
@@ -2191,6 +2235,14 @@ export const getMessageWithContextResponse = zod
.nullish()
.describe('When the message was edited.'),
id: zod.uuid().describe('Message id.'),
+ sender: zod
+ .object({
+ id: zod
+ .string()
+ .describe('Sender id without the storage namespace prefix.'),
+ type: zod.enum(['user', 'bot']).describe('Public sender type.'),
+ })
+ .describe('Public sender identity for channel messages.'),
sender_id: zod.string().describe('Sender user id.'),
thread_id: zod
.uuid()
@@ -2255,6 +2307,14 @@ export const getThreadRepliesResponseItem = zod
.describe('A reaction with emoji and user list.')
)
.describe('Reactions on this reply.'),
+ sender: zod
+ .object({
+ id: zod
+ .string()
+ .describe('Sender id without the storage namespace prefix.'),
+ type: zod.enum(['user', 'bot']).describe('Public sender type.'),
+ })
+ .describe('Public sender identity for channel messages.'),
sender_id: zod.string().describe('Sender user id.'),
updated_at: zod.iso
.datetime({})
diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.json
index 429ca031a5..991a66ae7c 100644
--- a/js/app/packages/service-clients/service-storage/openapi.json
+++ b/js/app/packages/service-clients/service-storage/openapi.json
@@ -8665,6 +8665,7 @@
"id",
"channel_id",
"sender_id",
+ "sender",
"content",
"created_at",
"updated_at"
@@ -8699,6 +8700,10 @@
"format": "uuid",
"description": "Message id."
},
+ "sender": {
+ "$ref": "#/components/schemas/ApiMessageSender",
+ "description": "Structured sender identity."
+ },
"sender_id": {
"type": "string",
"description": "Sender user id."
@@ -8722,6 +8727,7 @@
"id",
"channel_id",
"sender_id",
+ "sender",
"content",
"created_at",
"updated_at",
@@ -8773,6 +8779,10 @@
},
"description": "Reactions on this message."
},
+ "sender": {
+ "$ref": "#/components/schemas/ApiMessageSender",
+ "description": "Structured sender identity."
+ },
"sender_id": {
"type": "string",
"description": "Sender user id."
@@ -8939,6 +8949,26 @@
}
}
},
+ "ApiMessageSender": {
+ "type": "object",
+ "description": "Public sender identity for channel messages.",
+ "required": ["type", "id"],
+ "properties": {
+ "id": {
+ "type": "string",
+ "description": "Sender id without the storage namespace prefix."
+ },
+ "type": {
+ "$ref": "#/components/schemas/ApiMessageSenderType",
+ "description": "Sender type."
+ }
+ }
+ },
+ "ApiMessageSenderType": {
+ "type": "string",
+ "description": "Public sender type.",
+ "enum": ["user", "bot"]
+ },
"ApiParticipantRole": {
"type": "string",
"description": "Participant role in a channel.",
@@ -9011,6 +9041,7 @@
"required": [
"id",
"sender_id",
+ "sender",
"content",
"created_at",
"updated_at",
@@ -9051,6 +9082,10 @@
},
"description": "Reactions on this reply."
},
+ "sender": {
+ "$ref": "#/components/schemas/ApiMessageSender",
+ "description": "Structured sender identity."
+ },
"sender_id": {
"type": "string",
"description": "Sender user id."
diff --git a/rust/cloud-storage/.sqlx/query-000dcd3c4befc3975adf3bee932023bec273d62d6c2f233c3236ffebbfaf5810.json b/rust/cloud-storage/.sqlx/query-000dcd3c4befc3975adf3bee932023bec273d62d6c2f233c3236ffebbfaf5810.json
new file mode 100644
index 0000000000..02036afbf1
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-000dcd3c4befc3975adf3bee932023bec273d62d6c2f233c3236ffebbfaf5810.json
@@ -0,0 +1,66 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n a.channel_id AS \"channel_id: uuid::Uuid\",\n c.name AS \"channel_name?\", -- Option<String>\n a.message_id AS \"message_id: uuid::Uuid\",\n m.thread_id AS \"thread_id?: uuid::Uuid\",\n m.sender_id AS \"sender_id!\", -- String\n m.content AS \"message_content!\", -- String\n m.created_at AS \"message_created_at!: chrono::DateTime<chrono::Utc>\",\n a.created_at AS \"attachment_created_at!: chrono::DateTime<chrono::Utc>\"\n FROM comms_attachments a\n JOIN comms_messages m ON a.message_id = m.id\n JOIN comms_channels c ON a.channel_id = c.id\n JOIN comms_channel_participants cp ON cp.channel_id = c.id\n WHERE a.entity_type = $1\n AND a.entity_id = $2\n AND cp.user_id = $3\n AND cp.left_at IS NULL\n AND m.deleted_at IS NULL\n ORDER BY a.created_at DESC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "channel_id: uuid::Uuid",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "channel_name?",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 2,
+ "name": "message_id: uuid::Uuid",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 3,
+ "name": "thread_id?: uuid::Uuid",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 4,
+ "name": "sender_id!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "message_content!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "message_created_at!: chrono::DateTime<chrono::Utc>",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "attachment_created_at!: chrono::DateTime<chrono::Utc>",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ false,
+ true,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "000dcd3c4befc3975adf3bee932023bec273d62d6c2f233c3236ffebbfaf5810"
+}
diff --git a/rust/cloud-storage/.sqlx/query-2849c75501e874a2056d63e028c97cece3f7605b12f4c6f904c7ba8c718844f7.json b/rust/cloud-storage/.sqlx/query-046aa54b375545002a615891a34147d0d4f2c1e409bf1aa2263b84c88e2deda9.json
similarity index 75%
rename from rust/cloud-storage/.sqlx/query-2849c75501e874a2056d63e028c97cece3f7605b12f4c6f904c7ba8c718844f7.json
rename to rust/cloud-storage/.sqlx/query-046aa54b375545002a615891a34147d0d4f2c1e409bf1aa2263b84c88e2deda9.json
index 1207987257..33eecf6bc8 100644
--- a/rust/cloud-storage/.sqlx/query-2849c75501e874a2056d63e028c97cece3f7605b12f4c6f904c7ba8c718844f7.json
+++ b/rust/cloud-storage/.sqlx/query-046aa54b375545002a615891a34147d0d4f2c1e409bf1aa2263b84c88e2deda9.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO comms_messages (id, channel_id, sender_id, content, thread_id)\n VALUES ($1, $2, $3, $4, $5)\n RETURNING\n id,\n channel_id,\n sender_id AS \"sender_id: MacroUserIdStr\",\n content,\n created_at,\n updated_at,\n thread_id,\n edited_at::timestamptz AS \"edited_at?\",\n deleted_at::timestamptz AS \"deleted_at?\"\n ",
+ "query": "\n INSERT INTO comms_messages (id, channel_id, sender_id, content, thread_id)\n VALUES ($1, $2, $3, $4, $5)\n RETURNING\n id,\n channel_id,\n sender_id,\n content,\n created_at,\n updated_at,\n thread_id,\n edited_at::timestamptz AS \"edited_at?\",\n deleted_at::timestamptz AS \"deleted_at?\"\n ",
"describe": {
"columns": [
{
@@ -15,7 +15,7 @@
},
{
"ordinal": 2,
- "name": "sender_id: MacroUserIdStr",
+ "name": "sender_id",
"type_info": "Text"
},
{
@@ -70,5 +70,5 @@
null
]
},
- "hash": "2849c75501e874a2056d63e028c97cece3f7605b12f4c6f904c7ba8c718844f7"
+ "hash": "046aa54b375545002a615891a34147d0d4f2c1e409bf1aa2263b84c88e2deda9"
}
diff --git a/rust/cloud-storage/.sqlx/query-06072374ba47adb6156d2a4d0160ab3ab9a686e9617ce4aea0e768cdc3c78f86.json b/rust/cloud-storage/.sqlx/query-06072374ba47adb6156d2a4d0160ab3ab9a686e9617ce4aea0e768cdc3c78f86.json
new file mode 100644
index 0000000000..5d8ba7d6e7
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-06072374ba47adb6156d2a4d0160ab3ab9a686e9617ce4aea0e768cdc3c78f86.json
@@ -0,0 +1,58 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n a.id as \"id!: Uuid\",\n a.user_id as \"user_id!: String\",\n a.channel_id as \"channel_id!: Uuid\",\n a.viewed_at as \"viewed_at?: DateTime<Utc>\",\n a.interacted_at as \"interacted_at?: DateTime<Utc>\",\n a.created_at as \"created_at!: DateTime<Utc>\",\n a.updated_at as \"updated_at!: DateTime<Utc>\"\n FROM comms_activity a\n WHERE a.user_id = $1\n ORDER BY\n GREATEST(\n COALESCE(a.viewed_at, '1970-01-01'::timestamp),\n COALESCE(a.interacted_at, '1970-01-01'::timestamp)\n ) DESC,\n a.created_at DESC\n LIMIT 100\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id!: Uuid",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "user_id!: String",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "channel_id!: Uuid",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 3,
+ "name": "viewed_at?: DateTime<Utc>",
+ "type_info": "Timestamp"
+ },
+ {
+ "ordinal": 4,
+ "name": "interacted_at?: DateTime<Utc>",
+ "type_info": "Timestamp"
+ },
+ {
+ "ordinal": 5,
+ "name": "created_at!: DateTime<Utc>",
+ "type_info": "Timestamp"
+ },
+ {
+ "ordinal": 6,
+ "name": "updated_at!: DateTime<Utc>",
+ "type_info": "Timestamp"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ true,
+ true,
+ false,
+ false
+ ]
+ },
+ "hash": "06072374ba47adb6156d2a4d0160ab3ab9a686e9617ce4aea0e768cdc3c78f86"
+}
diff --git a/rust/cloud-storage/.sqlx/query-107c7ff9f46c80e689a642b15b85ea8978acaeba5aa4a264639b2a5c8c741a62.json b/rust/cloud-storage/.sqlx/query-107c7ff9f46c80e689a642b15b85ea8978acaeba5aa4a264639b2a5c8c741a62.json
deleted file mode 100644
index 514fa3d797..0000000000
--- a/rust/cloud-storage/.sqlx/query-107c7ff9f46c80e689a642b15b85ea8978acaeba5aa4a264639b2a5c8c741a62.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT DISTINCT id AS \"user_id!: MacroUserIdStr\" FROM (\n SELECT m.sender_id AS id\n FROM comms_channel_participants cp\n JOIN comms_channels c ON c.id = cp.channel_id\n JOIN comms_messages m ON m.channel_id = c.id\n WHERE (m.id = $1 OR m.thread_id = $1) AND cp.left_at IS NULL\n UNION\n SELECT em.entity_id AS id\n FROM comms_entity_mentions em\n JOIN comms_messages m ON m.id::text = em.source_entity_id\n JOIN comms_channel_participants cp\n ON cp.channel_id = m.channel_id AND cp.user_id = em.entity_id\n WHERE (m.id = $1 OR m.thread_id = $1)\n AND em.source_entity_type = 'message'\n AND em.entity_type = 'user'\n AND cp.left_at IS NULL\n ) AS combined\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "user_id!: MacroUserIdStr",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "107c7ff9f46c80e689a642b15b85ea8978acaeba5aa4a264639b2a5c8c741a62"
-}
diff --git a/rust/cloud-storage/.sqlx/query-1a8ff2838fcde3373b6cb6e0886cf5c20932ec3e9fe9eb8f5812f75f641b40b2.json b/rust/cloud-storage/.sqlx/query-1a8ff2838fcde3373b6cb6e0886cf5c20932ec3e9fe9eb8f5812f75f641b40b2.json
deleted file mode 100644
index 1ff2e97f41..0000000000
--- a/rust/cloud-storage/.sqlx/query-1a8ff2838fcde3373b6cb6e0886cf5c20932ec3e9fe9eb8f5812f75f641b40b2.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT sender_id AS \"sender_id: MacroUserIdStr\"\n FROM comms_messages\n WHERE id = $1\n ORDER BY created_at ASC\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "sender_id: MacroUserIdStr",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "1a8ff2838fcde3373b6cb6e0886cf5c20932ec3e9fe9eb8f5812f75f641b40b2"
-}
diff --git a/rust/cloud-storage/.sqlx/query-1ad1d46ce50de26cb5f1441e73845df205acdf018d65ada384f0b059425e9ab0.json b/rust/cloud-storage/.sqlx/query-1ad1d46ce50de26cb5f1441e73845df205acdf018d65ada384f0b059425e9ab0.json
new file mode 100644
index 0000000000..fdda5f8185
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-1ad1d46ce50de26cb5f1441e73845df205acdf018d65ada384f0b059425e9ab0.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE bot_tokens\n SET last_used_at = now()\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "1ad1d46ce50de26cb5f1441e73845df205acdf018d65ada384f0b059425e9ab0"
+}
diff --git a/rust/cloud-storage/.sqlx/query-1c03d1e837124187c0f4b940ee6863ec370be7dc1b87c38d1c53d898bfa6a235.json b/rust/cloud-storage/.sqlx/query-1c03d1e837124187c0f4b940ee6863ec370be7dc1b87c38d1c53d898bfa6a235.json
new file mode 100644
index 0000000000..7bafd18b74
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-1c03d1e837124187c0f4b940ee6863ec370be7dc1b87c38d1c53d898bfa6a235.json
@@ -0,0 +1,35 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n cp.role::text as \"role?\",\n c.channel_type::text as \"channel_type!\",\n c.org_id as \"org_id?\"\n FROM comms_channels c\n LEFT JOIN comms_channel_participants cp\n ON cp.channel_id = c.id AND cp.user_id = $2 AND cp.left_at IS NULL\n WHERE c.id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "role?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "channel_type!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "org_id?",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null,
+ null,
+ true
+ ]
+ },
+ "hash": "1c03d1e837124187c0f4b940ee6863ec370be7dc1b87c38d1c53d898bfa6a235"
+}
diff --git a/rust/cloud-storage/.sqlx/query-7e64280ac5918582d61bf6573e0f9b83180c03d2f0d5a9c8574217f9dbd02cbe.json b/rust/cloud-storage/.sqlx/query-1df49f5d478dcee269a9bded7fdcc34060d1c9dd6f964f3d6444b55830af299a.json
similarity index 77%
rename from rust/cloud-storage/.sqlx/query-7e64280ac5918582d61bf6573e0f9b83180c03d2f0d5a9c8574217f9dbd02cbe.json
rename to rust/cloud-storage/.sqlx/query-1df49f5d478dcee269a9bded7fdcc34060d1c9dd6f964f3d6444b55830af299a.json
index 3b0a31710e..9826ea2bab 100644
--- a/rust/cloud-storage/.sqlx/query-7e64280ac5918582d61bf6573e0f9b83180c03d2f0d5a9c8574217f9dbd02cbe.json
+++ b/rust/cloud-storage/.sqlx/query-1df49f5d478dcee269a9bded7fdcc34060d1c9dd6f964f3d6444b55830af299a.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n UPDATE comms_messages\n SET content = $1, updated_at = NOW(), edited_at = NOW()\n WHERE id = $2 AND channel_id = $3\n RETURNING\n id,\n channel_id,\n sender_id AS \"sender_id: MacroUserIdStr\",\n content,\n created_at,\n updated_at,\n thread_id,\n edited_at::timestamptz AS \"edited_at?\",\n deleted_at::timestamptz AS \"deleted_at?\"\n ",
+ "query": "\n UPDATE comms_messages\n SET content = $1, updated_at = NOW(), edited_at = NOW()\n WHERE id = $2 AND channel_id = $3\n RETURNING\n id,\n channel_id,\n sender_id,\n content,\n created_at,\n updated_at,\n thread_id,\n edited_at::timestamptz AS \"edited_at?\",\n deleted_at::timestamptz AS \"deleted_at?\"\n ",
"describe": {
"columns": [
{
@@ -15,7 +15,7 @@
},
{
"ordinal": 2,
- "name": "sender_id: MacroUserIdStr",
+ "name": "sender_id",
"type_info": "Text"
},
{
@@ -68,5 +68,5 @@
null
]
},
- "hash": "7e64280ac5918582d61bf6573e0f9b83180c03d2f0d5a9c8574217f9dbd02cbe"
+ "hash": "1df49f5d478dcee269a9bded7fdcc34060d1c9dd6f964f3d6444b55830af299a"
}
diff --git a/rust/cloud-storage/.sqlx/query-1f007b302205e5fb56f1d90b145aa96922a8f97e7a10d91ec7970c0cbf824281.json b/rust/cloud-storage/.sqlx/query-1f007b302205e5fb56f1d90b145aa96922a8f97e7a10d91ec7970c0cbf824281.json
new file mode 100644
index 0000000000..22393c625f
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-1f007b302205e5fb56f1d90b145aa96922a8f97e7a10d91ec7970c0cbf824281.json
@@ -0,0 +1,88 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n id,\n kind,\n owner_user_id,\n team_id,\n name,\n handle,\n description,\n avatar_url,\n created_by,\n created_at,\n updated_at,\n deleted_at\n FROM bots\n WHERE id = $1\n AND deleted_at IS NULL\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "kind",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "owner_user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "team_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 4,
+ "name": "name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "handle",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "description",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 7,
+ "name": "avatar_url",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "created_by",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 9,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 10,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 11,
+ "name": "deleted_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true,
+ true,
+ false,
+ false,
+ true,
+ true,
+ true,
+ false,
+ false,
+ true
+ ]
+ },
+ "hash": "1f007b302205e5fb56f1d90b145aa96922a8f97e7a10d91ec7970c0cbf824281"
+}
diff --git a/rust/cloud-storage/.sqlx/query-293ae45a8798edad6555057aa63f96b7c27c4d7457aeeb615789f1ebd5468337.json b/rust/cloud-storage/.sqlx/query-293ae45a8798edad6555057aa63f96b7c27c4d7457aeeb615789f1ebd5468337.json
new file mode 100644
index 0000000000..50f4178fc0
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-293ae45a8798edad6555057aa63f96b7c27c4d7457aeeb615789f1ebd5468337.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE bots\n SET deleted_at = now(), updated_at = now()\n WHERE id = $1\n AND deleted_at IS NULL\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "293ae45a8798edad6555057aa63f96b7c27c4d7457aeeb615789f1ebd5468337"
+}
diff --git a/rust/cloud-storage/.sqlx/query-9c40820250bebc60feaa2af6d84138690f54dc428ebef57f72b13d4542a984be.json b/rust/cloud-storage/.sqlx/query-2b2674801d90fb7b89f286300e8a03ec10c34ab1f8a6ecc6a9ecac5b964669a2.json
similarity index 79%
rename from rust/cloud-storage/.sqlx/query-9c40820250bebc60feaa2af6d84138690f54dc428ebef57f72b13d4542a984be.json
rename to rust/cloud-storage/.sqlx/query-2b2674801d90fb7b89f286300e8a03ec10c34ab1f8a6ecc6a9ecac5b964669a2.json
index 8b0f84192f..be3b1e901c 100644
--- a/rust/cloud-storage/.sqlx/query-9c40820250bebc60feaa2af6d84138690f54dc428ebef57f72b13d4542a984be.json
+++ b/rust/cloud-storage/.sqlx/query-2b2674801d90fb7b89f286300e8a03ec10c34ab1f8a6ecc6a9ecac5b964669a2.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n UPDATE comms_messages\n SET\n updated_at = NOW(),\n edited_at = NOW(),\n deleted_at = CASE\n WHEN $2 = false AND (content IS NULL OR content ~ '^[\\s]*$') THEN NOW()\n ELSE deleted_at\n END\n WHERE id = $1\n RETURNING\n id,\n channel_id,\n sender_id AS \"sender_id: MacroUserIdStr\",\n content,\n created_at,\n updated_at,\n thread_id,\n edited_at::timestamptz AS \"edited_at?\",\n deleted_at::timestamptz AS \"deleted_at?\"\n ",
+ "query": "\n UPDATE comms_messages\n SET\n updated_at = NOW(),\n edited_at = NOW(),\n deleted_at = CASE\n WHEN $2 = false AND (content IS NULL OR content ~ '^[\\s]*$') THEN NOW()\n ELSE deleted_at\n END\n WHERE id = $1\n RETURNING\n id,\n channel_id,\n sender_id,\n content,\n created_at,\n updated_at,\n thread_id,\n edited_at::timestamptz AS \"edited_at?\",\n deleted_at::timestamptz AS \"deleted_at?\"\n ",
"describe": {
"columns": [
{
@@ -15,7 +15,7 @@
},
{
"ordinal": 2,
- "name": "sender_id: MacroUserIdStr",
+ "name": "sender_id",
"type_info": "Text"
},
{
@@ -67,5 +67,5 @@
null
]
},
- "hash": "9c40820250bebc60feaa2af6d84138690f54dc428ebef57f72b13d4542a984be"
+ "hash": "2b2674801d90fb7b89f286300e8a03ec10c34ab1f8a6ecc6a9ecac5b964669a2"
}
diff --git a/rust/cloud-storage/.sqlx/query-2e94210011a9636d994437cbe074d904d563e57443cc3f65432e1db986f016dc.json b/rust/cloud-storage/.sqlx/query-2e94210011a9636d994437cbe074d904d563e57443cc3f65432e1db986f016dc.json
new file mode 100644
index 0000000000..c8f7b6d614
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-2e94210011a9636d994437cbe074d904d563e57443cc3f65432e1db986f016dc.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT sender_id\n FROM comms_messages\n WHERE id = $1\n ORDER BY created_at ASC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "sender_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "2e94210011a9636d994437cbe074d904d563e57443cc3f65432e1db986f016dc"
+}
diff --git a/rust/cloud-storage/.sqlx/query-2ff80f0d8f9b480e0e9068fbb795afdfe2a80bdd764e843e9f07d767b1eea7df.json b/rust/cloud-storage/.sqlx/query-2ff80f0d8f9b480e0e9068fbb795afdfe2a80bdd764e843e9f07d767b1eea7df.json
new file mode 100644
index 0000000000..96300aeeef
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-2ff80f0d8f9b480e0e9068fbb795afdfe2a80bdd764e843e9f07d767b1eea7df.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT DISTINCT id AS \"user_id!\" FROM (\n SELECT m.sender_id AS id\n FROM comms_channel_participants cp\n JOIN comms_channels c ON c.id = cp.channel_id\n JOIN comms_messages m ON m.channel_id = c.id\n WHERE (m.id = $1 OR m.thread_id = $1) AND cp.left_at IS NULL\n UNION\n SELECT em.entity_id AS id\n FROM comms_entity_mentions em\n JOIN comms_messages m ON m.id::text = em.source_entity_id\n JOIN comms_channel_participants cp\n ON cp.channel_id = m.channel_id AND cp.user_id = em.entity_id\n WHERE (m.id = $1 OR m.thread_id = $1)\n AND em.source_entity_type = 'message'\n AND em.entity_type = 'user'\n AND cp.left_at IS NULL\n ) AS combined\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "2ff80f0d8f9b480e0e9068fbb795afdfe2a80bdd764e843e9f07d767b1eea7df"
+}
diff --git a/rust/cloud-storage/.sqlx/query-33d640ec17b5f3daff76c169a999c7347151ce6a8bed1faa103c27a490a110d6.json b/rust/cloud-storage/.sqlx/query-33d640ec17b5f3daff76c169a999c7347151ce6a8bed1faa103c27a490a110d6.json
new file mode 100644
index 0000000000..08cef514e3
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-33d640ec17b5f3daff76c169a999c7347151ce6a8bed1faa103c27a490a110d6.json
@@ -0,0 +1,64 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, bot_id, token_prefix, label, last_used_at, expires_at, revoked_at, created_at\n FROM bot_tokens\n WHERE bot_id = $1\n AND revoked_at IS NULL\n ORDER BY created_at DESC, id DESC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "bot_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "token_prefix",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "label",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "last_used_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "expires_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "revoked_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ true,
+ true,
+ true,
+ true,
+ false
+ ]
+ },
+ "hash": "33d640ec17b5f3daff76c169a999c7347151ce6a8bed1faa103c27a490a110d6"
+}
diff --git a/rust/cloud-storage/.sqlx/query-429ca8e2c629499903d69292063060cafd143f63c7548ffdb8ae19461d0f0c76.json b/rust/cloud-storage/.sqlx/query-429ca8e2c629499903d69292063060cafd143f63c7548ffdb8ae19461d0f0c76.json
new file mode 100644
index 0000000000..3f7b7596cb
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-429ca8e2c629499903d69292063060cafd143f63c7548ffdb8ae19461d0f0c76.json
@@ -0,0 +1,95 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO bots (\n id, kind, owner_user_id, team_id, name, handle, description, avatar_url, created_by\n )\n VALUES ($1, 'owned', $2, $3, $4, $5, $6, $7, $8)\n RETURNING\n id,\n kind,\n owner_user_id,\n team_id,\n name,\n handle,\n description,\n avatar_url,\n created_by,\n created_at,\n updated_at,\n deleted_at\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "kind",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "owner_user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "team_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 4,
+ "name": "name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "handle",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "description",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 7,
+ "name": "avatar_url",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "created_by",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 9,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 10,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 11,
+ "name": "deleted_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Uuid",
+ "Text",
+ "Text",
+ "Text",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true,
+ true,
+ false,
+ false,
+ true,
+ true,
+ true,
+ false,
+ false,
+ true
+ ]
+ },
+ "hash": "429ca8e2c629499903d69292063060cafd143f63c7548ffdb8ae19461d0f0c76"
+}
diff --git a/rust/cloud-storage/.sqlx/query-5b8af25b1f47229f74c98541bbd200ba0582eaece5a30939ed5527bc05970795.json b/rust/cloud-storage/.sqlx/query-5b8af25b1f47229f74c98541bbd200ba0582eaece5a30939ed5527bc05970795.json
new file mode 100644
index 0000000000..8ae9384b70
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-5b8af25b1f47229f74c98541bbd200ba0582eaece5a30939ed5527bc05970795.json
@@ -0,0 +1,76 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n bt.id AS token_id,\n bt.bot_id,\n bt.token_hash,\n bt.token_prefix,\n bt.label,\n bt.last_used_at,\n bt.expires_at,\n bt.revoked_at,\n bt.created_at,\n b.kind\n FROM bot_tokens bt\n JOIN bots b ON b.id = bt.bot_id\n WHERE bt.token_prefix = $1\n AND b.deleted_at IS NULL\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "token_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "bot_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "token_hash",
+ "type_info": "Bytea"
+ },
+ {
+ "ordinal": 3,
+ "name": "token_prefix",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "label",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "last_used_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "expires_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "revoked_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 8,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "kind",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ true,
+ true,
+ true,
+ true,
+ false,
+ false
+ ]
+ },
+ "hash": "5b8af25b1f47229f74c98541bbd200ba0582eaece5a30939ed5527bc05970795"
+}
diff --git a/rust/cloud-storage/.sqlx/query-67255839adc83c0e1dfba11289811d0e6c269464a8506f0ec29db94b7841a038.json b/rust/cloud-storage/.sqlx/query-67255839adc83c0e1dfba11289811d0e6c269464a8506f0ec29db94b7841a038.json
new file mode 100644
index 0000000000..38af92f8da
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-67255839adc83c0e1dfba11289811d0e6c269464a8506f0ec29db94b7841a038.json
@@ -0,0 +1,88 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n b.id,\n b.kind,\n b.owner_user_id,\n b.team_id,\n b.name,\n b.handle,\n b.description,\n b.avatar_url,\n b.created_by,\n b.created_at,\n b.updated_at,\n b.deleted_at\n FROM bots b\n JOIN comms_channel_participants cp\n ON cp.user_id = ('bot|' || b.id::text)\n WHERE cp.channel_id = $1\n AND cp.left_at IS NULL\n AND b.deleted_at IS NULL\n ORDER BY b.created_at ASC, b.id ASC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "kind",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "owner_user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "team_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 4,
+ "name": "name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "handle",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "description",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 7,
+ "name": "avatar_url",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "created_by",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 9,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 10,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 11,
+ "name": "deleted_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true,
+ true,
+ false,
+ false,
+ true,
+ true,
+ true,
+ false,
+ false,
+ true
+ ]
+ },
+ "hash": "67255839adc83c0e1dfba11289811d0e6c269464a8506f0ec29db94b7841a038"
+}
diff --git a/rust/cloud-storage/.sqlx/query-720246c9399231f60479aa8c51bee2054d9f2cf9789f913e0f9cd65b9a93de79.json b/rust/cloud-storage/.sqlx/query-720246c9399231f60479aa8c51bee2054d9f2cf9789f913e0f9cd65b9a93de79.json
new file mode 100644
index 0000000000..49663920d1
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-720246c9399231f60479aa8c51bee2054d9f2cf9789f913e0f9cd65b9a93de79.json
@@ -0,0 +1,60 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO comms_activity (\n id,\n user_id,\n channel_id,\n interacted_at\n )\n VALUES (\n $1, $2, $3, NOW()\n )\n ON CONFLICT (user_id, channel_id) DO UPDATE\n SET\n interacted_at = NOW(),\n updated_at = NOW()\n RETURNING\n id as \"id!: Uuid\",\n user_id as \"user_id!: String\",\n channel_id as \"channel_id!: Uuid\",\n created_at as \"created_at!: DateTime<Utc>\",\n updated_at as \"updated_at!: DateTime<Utc>\",\n viewed_at as \"viewed_at?: DateTime<Utc>\",\n interacted_at as \"interacted_at?: DateTime<Utc>\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id!: Uuid",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "user_id!: String",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "channel_id!: Uuid",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 3,
+ "name": "created_at!: DateTime<Utc>",
+ "type_info": "Timestamp"
+ },
+ {
+ "ordinal": 4,
+ "name": "updated_at!: DateTime<Utc>",
+ "type_info": "Timestamp"
+ },
+ {
+ "ordinal": 5,
+ "name": "viewed_at?: DateTime<Utc>",
+ "type_info": "Timestamp"
+ },
+ {
+ "ordinal": 6,
+ "name": "interacted_at?: DateTime<Utc>",
+ "type_info": "Timestamp"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ true
+ ]
+ },
+ "hash": "720246c9399231f60479aa8c51bee2054d9f2cf9789f913e0f9cd65b9a93de79"
+}
diff --git a/rust/cloud-storage/.sqlx/query-45ad79d68456546519948ee22ab123c807c6ebc97bf5d6b523ef00b40beeb70e.json b/rust/cloud-storage/.sqlx/query-7a04573d80958eb5b841e520136db80173119aacbab82f50a4a1ae468aaada65.json
similarity index 77%
rename from rust/cloud-storage/.sqlx/query-45ad79d68456546519948ee22ab123c807c6ebc97bf5d6b523ef00b40beeb70e.json
rename to rust/cloud-storage/.sqlx/query-7a04573d80958eb5b841e520136db80173119aacbab82f50a4a1ae468aaada65.json
index 22a8b4e775..d692f301d5 100644
--- a/rust/cloud-storage/.sqlx/query-45ad79d68456546519948ee22ab123c807c6ebc97bf5d6b523ef00b40beeb70e.json
+++ b/rust/cloud-storage/.sqlx/query-7a04573d80958eb5b841e520136db80173119aacbab82f50a4a1ae468aaada65.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n UPDATE comms_messages\n SET content = '', updated_at = NOW(), deleted_at = NOW()\n WHERE id = $1 AND channel_id = $2\n RETURNING\n id,\n channel_id,\n sender_id AS \"sender_id: MacroUserIdStr\",\n content,\n created_at,\n updated_at,\n thread_id,\n edited_at::timestamptz AS \"edited_at?\",\n deleted_at::timestamptz AS \"deleted_at?\"\n ",
+ "query": "\n UPDATE comms_messages\n SET content = '', updated_at = NOW(), deleted_at = NOW()\n WHERE id = $1 AND channel_id = $2\n RETURNING\n id,\n channel_id,\n sender_id,\n content,\n created_at,\n updated_at,\n thread_id,\n edited_at::timestamptz AS \"edited_at?\",\n deleted_at::timestamptz AS \"deleted_at?\"\n ",
"describe": {
"columns": [
{
@@ -15,7 +15,7 @@
},
{
"ordinal": 2,
- "name": "sender_id: MacroUserIdStr",
+ "name": "sender_id",
"type_info": "Text"
},
{
@@ -67,5 +67,5 @@
null
]
},
- "hash": "45ad79d68456546519948ee22ab123c807c6ebc97bf5d6b523ef00b40beeb70e"
+ "hash": "7a04573d80958eb5b841e520136db80173119aacbab82f50a4a1ae468aaada65"
}
diff --git a/rust/cloud-storage/.sqlx/query-83c56e766513141232e2552b51f710814de9a258724b40796328784a5239ea5f.json b/rust/cloud-storage/.sqlx/query-83c56e766513141232e2552b51f710814de9a258724b40796328784a5239ea5f.json
new file mode 100644
index 0000000000..c2298b3f0e
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-83c56e766513141232e2552b51f710814de9a258724b40796328784a5239ea5f.json
@@ -0,0 +1,60 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO comms_activity (\n id,\n user_id,\n channel_id,\n viewed_at\n )\n VALUES (\n $1, $2, $3, NOW()\n )\n ON CONFLICT (user_id, channel_id) DO UPDATE\n SET\n viewed_at = NOW(),\n updated_at = NOW()\n RETURNING\n id as \"id!: Uuid\",\n user_id as \"user_id!: String\",\n channel_id as \"channel_id!: Uuid\",\n created_at as \"created_at!: DateTime<Utc>\",\n updated_at as \"updated_at!: DateTime<Utc>\",\n viewed_at as \"viewed_at?: DateTime<Utc>\",\n interacted_at as \"interacted_at?: DateTime<Utc>\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id!: Uuid",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "user_id!: String",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "channel_id!: Uuid",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 3,
+ "name": "created_at!: DateTime<Utc>",
+ "type_info": "Timestamp"
+ },
+ {
+ "ordinal": 4,
+ "name": "updated_at!: DateTime<Utc>",
+ "type_info": "Timestamp"
+ },
+ {
+ "ordinal": 5,
+ "name": "viewed_at?: DateTime<Utc>",
+ "type_info": "Timestamp"
+ },
+ {
+ "ordinal": 6,
+ "name": "interacted_at?: DateTime<Utc>",
+ "type_info": "Timestamp"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ true
+ ]
+ },
+ "hash": "83c56e766513141232e2552b51f710814de9a258724b40796328784a5239ea5f"
+}
diff --git a/rust/cloud-storage/.sqlx/query-92b33fffecd9a49fed7c74fe6994932e4d2123e0721a86c2b2fb691a32b92054.json b/rust/cloud-storage/.sqlx/query-92b33fffecd9a49fed7c74fe6994932e4d2123e0721a86c2b2fb691a32b92054.json
new file mode 100644
index 0000000000..467edfdf44
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-92b33fffecd9a49fed7c74fe6994932e4d2123e0721a86c2b2fb691a32b92054.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO comms_channel_participants (channel_id, user_id, role, left_at)\n VALUES ($1, $2, 'member'::comms_participant_role, NULL)\n ON CONFLICT (channel_id, user_id)\n DO UPDATE SET role = 'member'::comms_participant_role,\n left_at = NULL,\n joined_at = now()\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "92b33fffecd9a49fed7c74fe6994932e4d2123e0721a86c2b2fb691a32b92054"
+}
diff --git a/rust/cloud-storage/.sqlx/query-9c2fa9459318bdf3adfd77ae07e0aa74c7b53c39640602546483c6509c94fa8d.json b/rust/cloud-storage/.sqlx/query-9c2fa9459318bdf3adfd77ae07e0aa74c7b53c39640602546483c6509c94fa8d.json
deleted file mode 100644
index 3c1fac2605..0000000000
--- a/rust/cloud-storage/.sqlx/query-9c2fa9459318bdf3adfd77ae07e0aa74c7b53c39640602546483c6509c94fa8d.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT sender_id AS \"sender_id: MacroUserIdStr\"\n FROM comms_messages\n WHERE id = $1 AND channel_id = $2\n ORDER BY created_at ASC\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "sender_id: MacroUserIdStr",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Uuid"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "9c2fa9459318bdf3adfd77ae07e0aa74c7b53c39640602546483c6509c94fa8d"
-}
diff --git a/rust/cloud-storage/.sqlx/query-b2a631a3c9b08b85813839c25a2c7a530010c3a00b2f2d67403bc036af6c8fb5.json b/rust/cloud-storage/.sqlx/query-b2a631a3c9b08b85813839c25a2c7a530010c3a00b2f2d67403bc036af6c8fb5.json
new file mode 100644
index 0000000000..d3fc4432fe
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-b2a631a3c9b08b85813839c25a2c7a530010c3a00b2f2d67403bc036af6c8fb5.json
@@ -0,0 +1,53 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n em.source_entity_type,\n em.source_entity_id,\n em.entity_type,\n em.entity_id,\n em.user_id,\n em.created_at\n FROM comms_entity_mentions em\n WHERE em.entity_type = $1\n AND em.entity_id = $2\n AND em.source_entity_type != 'message'\n ORDER BY em.created_at DESC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "source_entity_type",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 1,
+ "name": "source_entity_id",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 2,
+ "name": "entity_type",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 3,
+ "name": "entity_id",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 4,
+ "name": "user_id",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 5,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ true,
+ false
+ ]
+ },
+ "hash": "b2a631a3c9b08b85813839c25a2c7a530010c3a00b2f2d67403bc036af6c8fb5"
+}
diff --git a/rust/cloud-storage/.sqlx/query-c59c1f638ad1ff78414fdb6733442120d6333b8c605f6da5b748951d9561c1f9.json b/rust/cloud-storage/.sqlx/query-c59c1f638ad1ff78414fdb6733442120d6333b8c605f6da5b748951d9561c1f9.json
new file mode 100644
index 0000000000..8097b5691b
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-c59c1f638ad1ff78414fdb6733442120d6333b8c605f6da5b748951d9561c1f9.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE comms_channel_participants\n SET left_at = now()\n WHERE channel_id = $1\n AND user_id = $2\n AND left_at IS NULL\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "c59c1f638ad1ff78414fdb6733442120d6333b8c605f6da5b748951d9561c1f9"
+}
diff --git a/rust/cloud-storage/.sqlx/query-cb43982dff09d09997be524b6e1034ed73a87e8599f27986495b62ce42e86384.json b/rust/cloud-storage/.sqlx/query-cb43982dff09d09997be524b6e1034ed73a87e8599f27986495b62ce42e86384.json
new file mode 100644
index 0000000000..daf77cdfde
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-cb43982dff09d09997be524b6e1034ed73a87e8599f27986495b62ce42e86384.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT sender_id\n FROM comms_messages\n WHERE id = $1 AND channel_id = $2\n ORDER BY created_at ASC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "sender_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "cb43982dff09d09997be524b6e1034ed73a87e8599f27986495b62ce42e86384"
+}
diff --git a/rust/cloud-storage/.sqlx/query-dbf934ed3c82b433deea3da7035a976b443a4280c01b09fdc5f673ad66f06c28.json b/rust/cloud-storage/.sqlx/query-dbf934ed3c82b433deea3da7035a976b443a4280c01b09fdc5f673ad66f06c28.json
new file mode 100644
index 0000000000..568c59efeb
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-dbf934ed3c82b433deea3da7035a976b443a4280c01b09fdc5f673ad66f06c28.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE comms_channel_participants\n SET left_at = now()\n WHERE user_id = $1\n AND left_at IS NULL\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "dbf934ed3c82b433deea3da7035a976b443a4280c01b09fdc5f673ad66f06c28"
+}
diff --git a/rust/cloud-storage/.sqlx/query-dcf19b1a30385a18a23d0fa7d4d724d755c0a3353480bcbe573a3f867cf24091.json b/rust/cloud-storage/.sqlx/query-dcf19b1a30385a18a23d0fa7d4d724d755c0a3353480bcbe573a3f867cf24091.json
new file mode 100644
index 0000000000..15e39a719d
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-dcf19b1a30385a18a23d0fa7d4d724d755c0a3353480bcbe573a3f867cf24091.json
@@ -0,0 +1,69 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO bot_tokens (\n id, bot_id, token_hash, token_prefix, label, expires_at\n )\n VALUES ($1, $2, $3, $4, $5, $6)\n RETURNING id, bot_id, token_prefix, label, last_used_at, expires_at, revoked_at, created_at\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "bot_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "token_prefix",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "label",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "last_used_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "expires_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "revoked_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Bytea",
+ "Text",
+ "Text",
+ "Timestamptz"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ true,
+ true,
+ true,
+ true,
+ false
+ ]
+ },
+ "hash": "dcf19b1a30385a18a23d0fa7d4d724d755c0a3353480bcbe573a3f867cf24091"
+}
diff --git a/rust/cloud-storage/.sqlx/query-e1aae69a066a831096b61a7318b753897d59e28cedd21e439c20ff09268a831a.json b/rust/cloud-storage/.sqlx/query-e1aae69a066a831096b61a7318b753897d59e28cedd21e439c20ff09268a831a.json
new file mode 100644
index 0000000000..0aa41ab440
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-e1aae69a066a831096b61a7318b753897d59e28cedd21e439c20ff09268a831a.json
@@ -0,0 +1,92 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE bots\n SET name = COALESCE($2, name),\n handle = COALESCE($3, handle),\n description = COALESCE($4, description),\n avatar_url = COALESCE($5, avatar_url),\n updated_at = now()\n WHERE id = $1\n AND deleted_at IS NULL\n RETURNING\n id,\n kind,\n owner_user_id,\n team_id,\n name,\n handle,\n description,\n avatar_url,\n created_by,\n created_at,\n updated_at,\n deleted_at\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "kind",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "owner_user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "team_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 4,
+ "name": "name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "handle",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "description",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 7,
+ "name": "avatar_url",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "created_by",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 9,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 10,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 11,
+ "name": "deleted_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true,
+ true,
+ false,
+ false,
+ true,
+ true,
+ true,
+ false,
+ false,
+ true
+ ]
+ },
+ "hash": "e1aae69a066a831096b61a7318b753897d59e28cedd21e439c20ff09268a831a"
+}
diff --git a/rust/cloud-storage/.sqlx/query-eda8f3dae4d58225307ad036c6a19e0d6bef4a3d9ea2791d75799c93b4f2350f.json b/rust/cloud-storage/.sqlx/query-eda8f3dae4d58225307ad036c6a19e0d6bef4a3d9ea2791d75799c93b4f2350f.json
new file mode 100644
index 0000000000..bb45b730c4
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-eda8f3dae4d58225307ad036c6a19e0d6bef4a3d9ea2791d75799c93b4f2350f.json
@@ -0,0 +1,66 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n m.channel_id AS \"channel_id: uuid::Uuid\",\n c.name AS \"channel_name?\", -- Option<String>\n m.id AS \"message_id: uuid::Uuid\",\n m.thread_id AS \"thread_id?: uuid::Uuid\",\n m.sender_id AS \"sender_id!\", -- String\n m.content AS \"message_content!\", -- String\n m.created_at AS \"message_created_at!: chrono::DateTime<chrono::Utc>\",\n em.created_at AS \"attachment_created_at!: chrono::DateTime<chrono::Utc>\"\n FROM comms_entity_mentions em\n JOIN comms_messages m ON (em.source_entity_id = m.id::text AND em.source_entity_type = 'message')\n JOIN comms_channels c ON m.channel_id = c.id\n JOIN comms_channel_participants cp ON cp.channel_id = c.id\n WHERE em.entity_type = $1\n AND em.entity_id = $2\n AND cp.user_id = $3\n AND cp.left_at IS NULL\n AND m.deleted_at IS NULL\n ORDER BY em.created_at DESC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "channel_id: uuid::Uuid",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "channel_name?",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 2,
+ "name": "message_id: uuid::Uuid",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 3,
+ "name": "thread_id?: uuid::Uuid",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 4,
+ "name": "sender_id!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "message_content!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "message_created_at!: chrono::DateTime<chrono::Utc>",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "attachment_created_at!: chrono::DateTime<chrono::Utc>",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ false,
+ true,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "eda8f3dae4d58225307ad036c6a19e0d6bef4a3d9ea2791d75799c93b4f2350f"
+}
diff --git a/rust/cloud-storage/.sqlx/query-eed44d491b8b8bce4f111b92565b371093099209a80349d311f45a0aa4b9cca9.json b/rust/cloud-storage/.sqlx/query-eed44d491b8b8bce4f111b92565b371093099209a80349d311f45a0aa4b9cca9.json
new file mode 100644
index 0000000000..37b4e188f4
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-eed44d491b8b8bce4f111b92565b371093099209a80349d311f45a0aa4b9cca9.json
@@ -0,0 +1,88 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n id,\n kind,\n owner_user_id,\n team_id,\n name,\n handle,\n description,\n avatar_url,\n created_by,\n created_at,\n updated_at,\n deleted_at\n FROM bots\n WHERE kind = 'owned'\n AND deleted_at IS NULL\n AND (\n owner_user_id = $1\n OR team_id IN (\n SELECT team_id FROM team_user WHERE user_id = $1\n )\n )\n ORDER BY created_at ASC, id ASC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "kind",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "owner_user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "team_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 4,
+ "name": "name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "handle",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "description",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 7,
+ "name": "avatar_url",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "created_by",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 9,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 10,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 11,
+ "name": "deleted_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true,
+ true,
+ false,
+ false,
+ true,
+ true,
+ true,
+ false,
+ false,
+ true
+ ]
+ },
+ "hash": "eed44d491b8b8bce4f111b92565b371093099209a80349d311f45a0aa4b9cca9"
+}
diff --git a/rust/cloud-storage/.sqlx/query-f8ea2beac8e9feddd9f8ebd4e3d67032505a085b4c9c5e787f3194414758601b.json b/rust/cloud-storage/.sqlx/query-f8ea2beac8e9feddd9f8ebd4e3d67032505a085b4c9c5e787f3194414758601b.json
new file mode 100644
index 0000000000..0bd8267545
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-f8ea2beac8e9feddd9f8ebd4e3d67032505a085b4c9c5e787f3194414758601b.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE bot_tokens\n SET revoked_at = now()\n WHERE id = $1\n AND bot_id = $2\n AND revoked_at IS NULL\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "f8ea2beac8e9feddd9f8ebd4e3d67032505a085b4c9c5e787f3194414758601b"
+}
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index cc74bb3cad..98698c682b 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -1703,6 +1703,45 @@ dependencies = [
"cfg_aliases",
]
+[[package]]
+name = "bot_id"
+version = "0.1.0"
+dependencies = [
+ "serde",
+ "sqlx",
+ "thiserror 2.0.18",
+ "utoipa",
+ "uuid",
+]
+
+[[package]]
+name = "bots"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "axum",
+ "bot_id",
+ "chrono",
+ "entity_access",
+ "hex",
+ "macro_db_migrator",
+ "macro_user_id",
+ "macro_uuid",
+ "model-error-response",
+ "model_user",
+ "rand 0.9.4",
+ "serde",
+ "serde_json",
+ "sha2 0.10.9",
+ "sqlx",
+ "thiserror 2.0.18",
+ "tokio",
+ "tower 0.5.3",
+ "tracing",
+ "utoipa",
+ "uuid",
+]
+
[[package]]
name = "bs58"
version = "0.5.1"
@@ -1959,6 +1998,7 @@ dependencies = [
"anyhow",
"async-trait",
"axum",
+ "bot_id",
"chrono",
"connection_gateway_client",
"contacts",
@@ -3414,6 +3454,7 @@ dependencies = [
"axum",
"axum-extra",
"base64 0.22.1",
+ "bots",
"bytes",
"bzip2",
"cal",
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index b8ccedba5f..0942e9372e 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -5,6 +5,8 @@ members = [
"agent",
"authentication_service",
"backfill_entity_access",
+ "bot_id",
+ "bots",
"comms_service",
"connection_gateway",
"contacts_service",
diff --git a/rust/cloud-storage/bot_id/Cargo.toml b/rust/cloud-storage/bot_id/Cargo.toml
new file mode 100644
index 0000000000..b4766c0b1e
--- /dev/null
+++ b/rust/cloud-storage/bot_id/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+edition = "2024"
+name = "bot_id"
+publish = false
+version = "0.1.0"
+
+[features]
+schema = ["dep:utoipa"]
+sqlx = ["dep:sqlx"]
+
+[dependencies]
+serde = { workspace = true }
+sqlx = { workspace = true, optional = true }
+thiserror = { workspace = true }
+utoipa = { workspace = true, optional = true }
+uuid = { workspace = true }
diff --git a/rust/cloud-storage/bot_id/src/lib.rs b/rust/cloud-storage/bot_id/src/lib.rs
new file mode 100644
index 0000000000..4c1ae4af21
--- /dev/null
+++ b/rust/cloud-storage/bot_id/src/lib.rs
@@ -0,0 +1,161 @@
+#![deny(missing_docs)]
+
+//! Bot identity primitives.
+
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+const BOT_STORAGE_PREFIX: &str = "bot|";
+
+/// A bot id.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(transparent)]
+pub struct BotId(Uuid);
+
+impl BotId {
+ /// Build a bot id from its UUID.
+ pub const fn from_uuid(id: Uuid) -> Self {
+ Self(id)
+ }
+
+ /// Return the underlying UUID.
+ pub const fn as_uuid(self) -> Uuid {
+ self.0
+ }
+
+ /// Parse a bot id from its UUID string representation.
+ pub fn parse_uuid_str(value: &str) -> Result<Self, BotIdParseError> {
+ Uuid::parse_str(value)
+ .map(Self)
+ .map_err(|_| BotIdParseError::invalid(value))
+ }
+
+ /// Parse the existing storage principal representation, `bot|<uuid>`.
+ pub fn parse_storage_str(value: &str) -> Result<Self, BotIdParseError> {
+ let Some(id) = value.strip_prefix(BOT_STORAGE_PREFIX) else {
+ return Err(BotIdParseError::invalid(value));
+ };
+ Self::parse_uuid_str(id).map_err(|_| BotIdParseError::invalid(value))
+ }
+
+ /// Canonical storage representation for existing TEXT sender/participant columns.
+ pub fn to_storage_string(self) -> String {
+ format!("{BOT_STORAGE_PREFIX}{}", self.0)
+ }
+}
+
+impl From<Uuid> for BotId {
+ fn from(value: Uuid) -> Self {
+ Self::from_uuid(value)
+ }
+}
+
+impl From<BotId> for Uuid {
+ fn from(value: BotId) -> Self {
+ value.as_uuid()
+ }
+}
+
+impl std::fmt::Display for BotId {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}", self.0)
+ }
+}
+
+impl std::str::FromStr for BotId {
+ type Err = BotIdParseError;
+
+ fn from_str(value: &str) -> Result<Self, Self::Err> {
+ Self::parse_uuid_str(value)
+ }
+}
+
+/// Error returned when a bot id cannot be parsed.
+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+#[error("invalid bot id: {value}")]
+pub struct BotIdParseError {
+ value: String,
+}
+
+impl BotIdParseError {
+ fn invalid(value: &str) -> Self {
+ Self {
+ value: value.to_string(),
+ }
+ }
+}
+
+#[cfg(feature = "schema")]
+impl utoipa::ToSchema for BotId {
+ fn name() -> std::borrow::Cow<'static, str> {
+ std::borrow::Cow::Borrowed("BotId")
+ }
+}
+
+#[cfg(feature = "schema")]
+impl utoipa::PartialSchema for BotId {
+ fn schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
+ String::schema()
+ }
+}
+
+#[cfg(feature = "sqlx")]
+impl sqlx::Type<sqlx::Postgres> for BotId {
+ fn type_info() -> sqlx::postgres::PgTypeInfo {
+ <Uuid as sqlx::Type<sqlx::Postgres>>::type_info()
+ }
+
+ fn compatible(ty: &sqlx::postgres::PgTypeInfo) -> bool {
+ <Uuid as sqlx::Type<sqlx::Postgres>>::compatible(ty)
+ }
+}
+
+#[cfg(feature = "sqlx")]
+impl sqlx::postgres::PgHasArrayType for BotId {
+ fn array_type_info() -> sqlx::postgres::PgTypeInfo {
+ <Uuid as sqlx::postgres::PgHasArrayType>::array_type_info()
+ }
+}
+
+#[cfg(feature = "sqlx")]
+impl<'q> sqlx::Encode<'q, sqlx::Postgres> for BotId {
+ fn encode_by_ref(
+ &self,
+ buf: &mut sqlx::postgres::PgArgumentBuffer,
+ ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> {
+ <Uuid as sqlx::Encode<sqlx::Postgres>>::encode_by_ref(&self.0, buf)
+ }
+
+ fn size_hint(&self) -> usize {
+ <Uuid as sqlx::Encode<sqlx::Postgres>>::size_hint(&self.0)
+ }
+}
+
+#[cfg(feature = "sqlx")]
+impl<'r> sqlx::Decode<'r, sqlx::Postgres> for BotId {
+ fn decode(value: sqlx::postgres::PgValueRef<'r>) -> Result<Self, sqlx::error::BoxDynError> {
+ let value = <Uuid as sqlx::Decode<sqlx::Postgres>>::decode(value)?;
+ Ok(Self(value))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn storage_string_round_trips() {
+ let uuid = Uuid::new_v4();
+ let bot_id = BotId::from_uuid(uuid);
+
+ assert_eq!(
+ BotId::parse_storage_str(&bot_id.to_storage_string()).unwrap(),
+ bot_id
+ );
+ }
+
+ #[test]
+ fn rejects_non_bot_storage_string() {
+ assert!(BotId::parse_storage_str("macro|[email protected]").is_err());
+ }
+}
diff --git a/rust/cloud-storage/bots/Cargo.toml b/rust/cloud-storage/bots/Cargo.toml
new file mode 100644
index 0000000000..5f6620eb62
--- /dev/null
+++ b/rust/cloud-storage/bots/Cargo.toml
@@ -0,0 +1,51 @@
+[package]
+edition = "2024"
+name = "bots"
+publish = false
+version = "0.1.0"
+
+[features]
+default = ["inbound", "outbound", "ports"]
+inbound = [
+ "dep:axum",
+ "dep:entity_access",
+ "entity_access/inbound",
+ "entity_access/ports",
+ "dep:model-error-response",
+ "dep:model_user",
+ "dep:utoipa",
+ "ports",
+]
+outbound = ["dep:sqlx", "dep:macro_uuid", "ports"]
+ports = ["dep:tokio"]
+
+[dependencies]
+anyhow = { workspace = true }
+axum = { workspace = true, optional = true }
+bot_id = { path = "../bot_id", features = ["schema"] }
+chrono = { workspace = true }
+entity_access = { path = "../entity_access", optional = true, default-features = false }
+hex = { workspace = true }
+macro_user_id = { path = "../macro_user_id" }
+macro_uuid = { path = "../macro_uuid", optional = true }
+model-error-response = { path = "../model-error-response", optional = true }
+model_user = { path = "../model_user", optional = true, features = ["axum"] }
+rand = { workspace = true }
+serde = { workspace = true }
+sha2 = { workspace = true }
+sqlx = { workspace = true, optional = true }
+thiserror = { workspace = true }
+tokio = { workspace = true, optional = true }
+tracing = { workspace = true }
+utoipa = { workspace = true, optional = true }
+uuid = { workspace = true }
+
+[dev-dependencies]
+entity_access = { path = "../entity_access", default-features = false, features = [
+ "outbound",
+ "ports",
+] }
+macro_db_migrator = { path = "../macro_db_migrator" }
+serde_json = { workspace = true }
+tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
+tower = { workspace = true }
diff --git a/rust/cloud-storage/bots/src/domain/mod.rs b/rust/cloud-storage/bots/src/domain/mod.rs
new file mode 100644
index 0000000000..dc3ae0c350
--- /dev/null
+++ b/rust/cloud-storage/bots/src/domain/mod.rs
@@ -0,0 +1,12 @@
+//! Domain layer for bots.
+
+/// Bot domain models.
+pub mod models;
+#[cfg(feature = "ports")]
+/// Bot ports.
+pub mod ports;
+#[cfg(feature = "ports")]
+/// Bot service.
+pub mod service;
+/// Token utilities.
+pub mod tokens;
diff --git a/rust/cloud-storage/bots/src/domain/models.rs b/rust/cloud-storage/bots/src/domain/models.rs
new file mode 100644
index 0000000000..948fea463b
--- /dev/null
+++ b/rust/cloud-storage/bots/src/domain/models.rs
@@ -0,0 +1,186 @@
+//! Bot domain models.
+
+use chrono::{DateTime, Utc};
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+/// Shared bot id used by bot principals.
+pub use bot_id::BotId;
+
+/// Bot kind.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+#[serde(rename_all = "snake_case")]
+pub enum BotKind {
+ /// User- or team-owned bot.
+ Owned,
+ /// First-party system bot.
+ System,
+}
+
+impl BotKind {
+ /// Storage representation.
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Self::Owned => "owned",
+ Self::System => "system",
+ }
+ }
+}
+
+impl std::str::FromStr for BotKind {
+ type Err = String;
+
+ fn from_str(value: &str) -> Result<Self, Self::Err> {
+ match value {
+ "owned" => Ok(Self::Owned),
+ "system" => Ok(Self::System),
+ other => Err(format!("unknown bot kind: {other}")),
+ }
+ }
+}
+
+/// Bot owner.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+#[serde(rename_all = "snake_case", tag = "type")]
+pub enum BotOwner {
+ /// User-owned bot.
+ User {
+ /// Owner user id.
+ user_id: String,
+ },
+ /// Team-owned bot.
+ Team {
+ /// Owner team id.
+ team_id: Uuid,
+ },
+}
+
+/// Bot row.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+pub struct Bot {
+ /// Bot id.
+ pub id: BotId,
+ /// Bot kind.
+ pub kind: BotKind,
+ /// Owner for owned bots.
+ pub owner: Option<BotOwner>,
+ /// Display name.
+ pub name: String,
+ /// Stable handle.
+ pub handle: String,
+ /// Optional description.
+ pub description: Option<String>,
+ /// Optional avatar URL.
+ pub avatar_url: Option<String>,
+ /// User that created this bot.
+ pub created_by: Option<String>,
+ /// Creation timestamp.
+ pub created_at: DateTime<Utc>,
+ /// Update timestamp.
+ pub updated_at: DateTime<Utc>,
+ /// Soft-delete timestamp.
+ pub deleted_at: Option<DateTime<Utc>>,
+}
+
+/// Bot token metadata.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+pub struct BotToken {
+ /// Token id.
+ pub id: Uuid,
+ /// Owning bot id.
+ pub bot_id: BotId,
+ /// Token lookup prefix.
+ pub token_prefix: String,
+ /// Optional token label.
+ pub label: Option<String>,
+ /// Last successful use.
+ pub last_used_at: Option<DateTime<Utc>>,
+ /// Expiration timestamp.
+ pub expires_at: Option<DateTime<Utc>>,
+ /// Revocation timestamp.
+ pub revoked_at: Option<DateTime<Utc>>,
+ /// Creation timestamp.
+ pub created_at: DateTime<Utc>,
+}
+
+/// Authenticated bot principal.
+#[derive(Debug, Clone)]
+pub struct AuthenticatedBot {
+ /// Bot id.
+ pub bot_id: BotId,
+ /// Bot kind.
+ pub kind: BotKind,
+}
+
+/// Candidate token row used during bearer-token authentication.
+#[derive(Debug, Clone)]
+pub struct BotTokenCandidate {
+ /// Token metadata.
+ pub token: BotToken,
+ /// Stored token hash.
+ pub token_hash: Vec<u8>,
+ /// Authenticated bot principal associated with the token.
+ pub bot: AuthenticatedBot,
+}
+
+/// Request to create a bot.
+#[derive(Debug, Clone, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+pub struct CreateBotRequest {
+ /// Team owner. Omit for a user-owned bot.
+ pub team_id: Option<Uuid>,
+ /// Display name.
+ pub name: String,
+ /// Stable handle.
+ pub handle: String,
+ /// Optional description.
+ pub description: Option<String>,
+ /// Optional avatar URL.
+ pub avatar_url: Option<String>,
+}
+
+/// Request to patch a bot.
+#[derive(Debug, Clone, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+pub struct PatchBotRequest {
+ /// Display name.
+ pub name: Option<String>,
+ /// Stable handle.
+ pub handle: Option<String>,
+ /// Optional description.
+ pub description: Option<String>,
+ /// Optional avatar URL.
+ pub avatar_url: Option<String>,
+}
+
+/// Request to create a bot token.
+#[derive(Debug, Clone, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+pub struct CreateBotTokenRequest {
+ /// Token label.
+ pub label: Option<String>,
+ /// Optional expiration timestamp.
+ pub expires_at: Option<DateTime<Utc>>,
+}
+
+/// Request to add a bot to a channel.
+#[derive(Debug, Clone, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+pub struct AddChannelBotRequest {
+ /// Bot id.
+ pub bot_id: BotId,
+}
+
+/// Response containing a newly minted token. The raw token is shown once.
+#[derive(Debug, Clone, Serialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+pub struct CreateBotTokenResponse {
+ /// Token metadata.
+ pub token: BotToken,
+ /// Raw bearer token.
+ pub bearer_token: String,
+}
diff --git a/rust/cloud-storage/bots/src/domain/ports.rs b/rust/cloud-storage/bots/src/domain/ports.rs
new file mode 100644
index 0000000000..461ea738d1
--- /dev/null
+++ b/rust/cloud-storage/bots/src/domain/ports.rs
@@ -0,0 +1,208 @@
+//! Bot ports.
+
+use super::models::{
+ AuthenticatedBot, Bot, BotId, BotOwner, BotToken, BotTokenCandidate, CreateBotRequest,
+ CreateBotTokenRequest, CreateBotTokenResponse, PatchBotRequest,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+use std::future::Future;
+use uuid::Uuid;
+
+/// Bot repository.
+pub trait BotRepo: Clone + Send + Sync + 'static {
+ /// Repository error.
+ type Err: Into<anyhow::Error> + Send;
+
+ /// Create an owned bot.
+ fn create_owned_bot(
+ &self,
+ owner: BotOwner,
+ created_by: MacroUserIdStr<'static>,
+ req: CreateBotRequest,
+ ) -> impl Future<Output = Result<Bot, Self::Err>> + Send;
+
+ /// List active bots manageable by a caller.
+ fn list_manageable_bots(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<Vec<Bot>, Self::Err>> + Send;
+
+ /// Get an active bot by id.
+ fn get_bot(&self, bot_id: BotId)
+ -> impl Future<Output = Result<Option<Bot>, Self::Err>> + Send;
+
+ /// Check team membership.
+ fn user_has_team(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ team_id: Uuid,
+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;
+
+ /// Patch an active bot.
+ fn patch_bot(
+ &self,
+ bot_id: BotId,
+ req: PatchBotRequest,
+ ) -> impl Future<Output = Result<Option<Bot>, Self::Err>> + Send;
+
+ /// Soft-delete an active bot.
+ fn delete_bot(&self, bot_id: BotId) -> impl Future<Output = Result<bool, Self::Err>> + Send;
+
+ /// Add bot reach to a channel.
+ fn add_bot_to_channel(
+ &self,
+ channel_id: Uuid,
+ bot_id: BotId,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Remove bot reach from a channel.
+ fn remove_bot_from_channel(
+ &self,
+ channel_id: Uuid,
+ bot_id: BotId,
+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;
+
+ /// List active bots in a channel.
+ fn list_channel_bots(
+ &self,
+ channel_id: Uuid,
+ ) -> impl Future<Output = Result<Vec<Bot>, Self::Err>> + Send;
+
+ /// Create a token.
+ fn create_token(
+ &self,
+ bot_id: BotId,
+ token_hash: Vec<u8>,
+ token_prefix: String,
+ req: CreateBotTokenRequest,
+ ) -> impl Future<Output = Result<BotToken, Self::Err>> + Send;
+
+ /// List active token metadata.
+ fn list_tokens(
+ &self,
+ bot_id: BotId,
+ ) -> impl Future<Output = Result<Vec<BotToken>, Self::Err>> + Send;
+
+ /// Revoke a token.
+ fn revoke_token(
+ &self,
+ bot_id: BotId,
+ token_id: Uuid,
+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;
+
+ /// Lookup token candidates by prefix.
+ fn token_candidates(
+ &self,
+ token_prefix: &str,
+ ) -> impl Future<Output = Result<Vec<BotTokenCandidate>, Self::Err>> + Send;
+
+ /// Mark a token as used.
+ fn mark_token_used(&self, token_id: Uuid)
+ -> impl Future<Output = Result<(), Self::Err>> + Send;
+}
+
+/// Bot service.
+pub trait BotService: Clone + Send + Sync + 'static {
+ /// Create a bot owned by the caller or one of their teams.
+ fn create_bot(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ req: CreateBotRequest,
+ ) -> impl Future<Output = Result<Bot, BotError>> + Send;
+
+ /// List bots manageable by the caller.
+ fn list_bots(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<Vec<Bot>, BotError>> + Send;
+
+ /// Get a manageable bot.
+ fn get_bot(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ bot_id: BotId,
+ ) -> impl Future<Output = Result<Bot, BotError>> + Send;
+
+ /// Patch a manageable bot.
+ fn patch_bot(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ bot_id: BotId,
+ req: PatchBotRequest,
+ ) -> impl Future<Output = Result<Bot, BotError>> + Send;
+
+ /// Delete a manageable bot.
+ fn delete_bot(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ bot_id: BotId,
+ ) -> impl Future<Output = Result<(), BotError>> + Send;
+
+ /// Add an owned/team-available bot to a channel.
+ fn add_bot_to_channel(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ channel_id: Uuid,
+ bot_id: BotId,
+ ) -> impl Future<Output = Result<(), BotError>> + Send;
+
+ /// Remove a bot from a channel.
+ fn remove_bot_from_channel(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ channel_id: Uuid,
+ bot_id: BotId,
+ ) -> impl Future<Output = Result<(), BotError>> + Send;
+
+ /// List channel bots.
+ fn list_channel_bots(
+ &self,
+ channel_id: Uuid,
+ ) -> impl Future<Output = Result<Vec<Bot>, BotError>> + Send;
+
+ /// Create a token for a manageable bot.
+ fn create_token(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ bot_id: BotId,
+ req: CreateBotTokenRequest,
+ ) -> impl Future<Output = Result<CreateBotTokenResponse, BotError>> + Send;
+
+ /// List token metadata for a manageable bot.
+ fn list_tokens(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ bot_id: BotId,
+ ) -> impl Future<Output = Result<Vec<BotToken>, BotError>> + Send;
+
+ /// Revoke a token for a manageable bot.
+ fn revoke_token(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ bot_id: BotId,
+ token_id: Uuid,
+ ) -> impl Future<Output = Result<(), BotError>> + Send;
+
+ /// Authenticate a raw bearer token.
+ fn authenticate_token(
+ &self,
+ token: &str,
+ ) -> impl Future<Output = Result<AuthenticatedBot, BotError>> + Send;
+}
+
+/// Bot service error.
+#[derive(Debug, thiserror::Error)]
+pub enum BotError {
+ /// Bad request.
+ #[error("{0}")]
+ BadRequest(String),
+ /// Not found.
+ #[error("{0}")]
+ NotFound(String),
+ /// Unauthorized.
+ #[error("unauthorized")]
+ Unauthorized,
+ /// Repository error.
+ #[error(transparent)]
+ Repo(#[from] anyhow::Error),
+}
diff --git a/rust/cloud-storage/bots/src/domain/service.rs b/rust/cloud-storage/bots/src/domain/service.rs
new file mode 100644
index 0000000000..4e4bc3d10d
--- /dev/null
+++ b/rust/cloud-storage/bots/src/domain/service.rs
@@ -0,0 +1,278 @@
+//! Bot service implementation.
+
+use super::{
+ models::{
+ AuthenticatedBot, Bot, BotId, BotKind, BotOwner, BotToken, CreateBotRequest,
+ CreateBotTokenRequest, PatchBotRequest,
+ },
+ ports::{BotError, BotRepo, BotService},
+ tokens,
+};
+use chrono::Utc;
+use macro_user_id::user_id::MacroUserIdStr;
+use uuid::Uuid;
+
+/// Bot service implementation.
+#[derive(Debug, Clone)]
+pub struct BotServiceImpl<R> {
+ repo: R,
+}
+
+impl<R> BotServiceImpl<R> {
+ /// Create a bot service.
+ pub fn new(repo: R) -> Self {
+ Self { repo }
+ }
+}
+
+fn validate_handle(handle: &str) -> Result<(), BotError> {
+ if handle.is_empty()
+ || handle.len() > 64
+ || !handle
+ .chars()
+ .all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '-' || ch == '_')
+ {
+ return Err(BotError::BadRequest(
+ "handle must be lowercase ascii, digits, '-' or '_'".to_string(),
+ ));
+ }
+ Ok(())
+}
+
+impl<R> BotServiceImpl<R>
+where
+ R: BotRepo,
+{
+ async fn ensure_manageable(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ bot_id: BotId,
+ ) -> Result<Bot, BotError> {
+ let bot = self
+ .repo
+ .get_bot(bot_id)
+ .await
+ .map_err(|err| BotError::Repo(err.into()))?
+ .ok_or_else(|| BotError::NotFound("bot not found".to_string()))?;
+
+ if bot.kind == BotKind::System {
+ return Err(BotError::Unauthorized);
+ }
+
+ let Some(owner) = &bot.owner else {
+ return Err(BotError::Unauthorized);
+ };
+
+ match owner {
+ BotOwner::User { user_id } if user_id == caller.as_ref() => Ok(bot),
+ BotOwner::Team { team_id }
+ if self
+ .repo
+ .user_has_team(caller, *team_id)
+ .await
+ .map_err(|err| BotError::Repo(err.into()))? =>
+ {
+ Ok(bot)
+ }
+ _ => Err(BotError::Unauthorized),
+ }
+ }
+}
+
+impl<R> BotService for BotServiceImpl<R>
+where
+ R: BotRepo,
+{
+ async fn create_bot(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ req: CreateBotRequest,
+ ) -> Result<Bot, BotError> {
+ validate_handle(&req.handle)?;
+ let owner = if let Some(team_id) = req.team_id {
+ if !self
+ .repo
+ .user_has_team(caller.clone(), team_id)
+ .await
+ .map_err(|err| BotError::Repo(err.into()))?
+ {
+ return Err(BotError::Unauthorized);
+ }
+ BotOwner::Team { team_id }
+ } else {
+ BotOwner::User {
+ user_id: caller.as_ref().to_string(),
+ }
+ };
+
+ self.repo
+ .create_owned_bot(owner, caller, req)
+ .await
+ .map_err(|err| BotError::Repo(err.into()))
+ }
+
+ async fn list_bots(&self, caller: MacroUserIdStr<'static>) -> Result<Vec<Bot>, BotError> {
+ self.repo
+ .list_manageable_bots(caller)
+ .await
+ .map_err(|err| BotError::Repo(err.into()))
+ }
+
+ async fn get_bot(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ bot_id: BotId,
+ ) -> Result<Bot, BotError> {
+ self.ensure_manageable(caller, bot_id).await
+ }
+
+ async fn patch_bot(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ bot_id: BotId,
+ req: PatchBotRequest,
+ ) -> Result<Bot, BotError> {
+ self.ensure_manageable(caller, bot_id).await?;
+ if let Some(handle) = &req.handle {
+ validate_handle(handle)?;
+ }
+ self.repo
+ .patch_bot(bot_id, req)
+ .await
+ .map_err(|err| BotError::Repo(err.into()))?
+ .ok_or_else(|| BotError::NotFound("bot not found".to_string()))
+ }
+
+ async fn delete_bot(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ bot_id: BotId,
+ ) -> Result<(), BotError> {
+ self.ensure_manageable(caller, bot_id).await?;
+ if self
+ .repo
+ .delete_bot(bot_id)
+ .await
+ .map_err(|err| BotError::Repo(err.into()))?
+ {
+ Ok(())
+ } else {
+ Err(BotError::NotFound("bot not found".to_string()))
+ }
+ }
+
+ async fn add_bot_to_channel(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ channel_id: Uuid,
+ bot_id: BotId,
+ ) -> Result<(), BotError> {
+ self.ensure_manageable(caller, bot_id).await?;
+ self.repo
+ .add_bot_to_channel(channel_id, bot_id)
+ .await
+ .map_err(|err| BotError::Repo(err.into()))
+ }
+
+ async fn remove_bot_from_channel(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ channel_id: Uuid,
+ bot_id: BotId,
+ ) -> Result<(), BotError> {
+ self.ensure_manageable(caller, bot_id).await?;
+ if self
+ .repo
+ .remove_bot_from_channel(channel_id, bot_id)
+ .await
+ .map_err(|err| BotError::Repo(err.into()))?
+ {
+ Ok(())
+ } else {
+ Err(BotError::NotFound("channel bot not found".to_string()))
+ }
+ }
+
+ async fn list_channel_bots(&self, channel_id: Uuid) -> Result<Vec<Bot>, BotError> {
+ self.repo
+ .list_channel_bots(channel_id)
+ .await
+ .map_err(|err| BotError::Repo(err.into()))
+ }
+
+ async fn create_token(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ bot_id: BotId,
+ req: CreateBotTokenRequest,
+ ) -> Result<super::models::CreateBotTokenResponse, BotError> {
+ self.ensure_manageable(caller, bot_id).await?;
+ let generated = tokens::generate_token();
+ let token = self
+ .repo
+ .create_token(bot_id, generated.hash, generated.prefix, req)
+ .await
+ .map_err(|err| BotError::Repo(err.into()))?;
+ Ok(super::models::CreateBotTokenResponse {
+ token,
+ bearer_token: generated.token,
+ })
+ }
+
+ async fn list_tokens(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ bot_id: BotId,
+ ) -> Result<Vec<BotToken>, BotError> {
+ self.ensure_manageable(caller, bot_id).await?;
+ self.repo
+ .list_tokens(bot_id)
+ .await
+ .map_err(|err| BotError::Repo(err.into()))
+ }
+
+ async fn revoke_token(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ bot_id: BotId,
+ token_id: Uuid,
+ ) -> Result<(), BotError> {
+ self.ensure_manageable(caller, bot_id).await?;
+ if self
+ .repo
+ .revoke_token(bot_id, token_id)
+ .await
+ .map_err(|err| BotError::Repo(err.into()))?
+ {
+ Ok(())
+ } else {
+ Err(BotError::NotFound("token not found".to_string()))
+ }
+ }
+
+ async fn authenticate_token(&self, token: &str) -> Result<AuthenticatedBot, BotError> {
+ let prefix = tokens::token_prefix(token).ok_or(BotError::Unauthorized)?;
+ let hash = tokens::hash_token(token);
+ for candidate in self
+ .repo
+ .token_candidates(prefix)
+ .await
+ .map_err(|err| BotError::Repo(err.into()))?
+ {
+ if candidate.token.revoked_at.is_none()
+ && candidate
+ .token
+ .expires_at
+ .is_none_or(|expires_at| expires_at > Utc::now())
+ && tokens::verify_hash(&candidate.token_hash, &hash)
+ {
+ self.repo
+ .mark_token_used(candidate.token.id)
+ .await
+ .map_err(|err| BotError::Repo(err.into()))?;
+ return Ok(candidate.bot);
+ }
+ }
+ Err(BotError::Unauthorized)
+ }
+}
diff --git a/rust/cloud-storage/bots/src/domain/tokens.rs b/rust/cloud-storage/bots/src/domain/tokens.rs
new file mode 100644
index 0000000000..2034edc603
--- /dev/null
+++ b/rust/cloud-storage/bots/src/domain/tokens.rs
@@ -0,0 +1,78 @@
+//! Bot token generation and verification utilities.
+
+use rand::RngCore;
+use sha2::{Digest, Sha256};
+
+const TOKEN_SECRET_BYTES: usize = 32;
+const TOKEN_PREFIX_BYTES: usize = 6;
+
+/// Generated raw token plus lookup prefix and hash.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct GeneratedBotToken {
+ /// Raw bearer token.
+ pub token: String,
+ /// Lookup prefix.
+ pub prefix: String,
+ /// SHA-256 hash bytes.
+ pub hash: Vec<u8>,
+}
+
+/// Generate an `mbot_<prefix>_<secret>` token.
+pub fn generate_token() -> GeneratedBotToken {
+ let mut secret = [0_u8; TOKEN_SECRET_BYTES];
+ rand::rng().fill_bytes(&mut secret);
+ let secret_hex = hex::encode(secret);
+ let prefix = secret_hex[..TOKEN_PREFIX_BYTES * 2].to_string();
+ let token = format!("mbot_{prefix}_{secret_hex}");
+ let hash = hash_token(&token);
+ GeneratedBotToken {
+ token,
+ prefix,
+ hash,
+ }
+}
+
+/// Extract the lookup prefix from a raw bot token.
+pub fn token_prefix(token: &str) -> Option<&str> {
+ let mut parts = token.splitn(3, '_');
+ match (parts.next(), parts.next(), parts.next()) {
+ (Some("mbot"), Some(prefix), Some(secret)) if !prefix.is_empty() && !secret.is_empty() => {
+ Some(prefix)
+ }
+ _ => None,
+ }
+}
+
+/// SHA-256 hash a token.
+pub fn hash_token(token: &str) -> Vec<u8> {
+ Sha256::digest(token.as_bytes()).to_vec()
+}
+
+/// Constant-time equality for token hashes.
+pub fn verify_hash(expected: &[u8], actual: &[u8]) -> bool {
+ if expected.len() != actual.len() {
+ return false;
+ }
+ expected
+ .iter()
+ .zip(actual.iter())
+ .fold(0_u8, |acc, (a, b)| acc | (a ^ b))
+ == 0
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn generated_token_has_prefix_and_hash() {
+ let generated = generate_token();
+
+ assert!(generated.token.starts_with("mbot_"));
+ assert_eq!(
+ token_prefix(&generated.token),
+ Some(generated.prefix.as_str())
+ );
+ assert!(verify_hash(&generated.hash, &hash_token(&generated.token)));
+ }
+}
diff --git a/rust/cloud-storage/bots/src/inbound/axum_router.rs b/rust/cloud-storage/bots/src/inbound/axum_router.rs
new file mode 100644
index 0000000000..622a1a8144
--- /dev/null
+++ b/rust/cloud-storage/bots/src/inbound/axum_router.rs
@@ -0,0 +1,309 @@
+//! Axum router for bot management and channel reach.
+
+#[cfg(test)]
+mod tests;
+
+use crate::domain::{
+ models::{
+ AddChannelBotRequest, Bot, BotId, BotToken, CreateBotRequest, CreateBotTokenRequest,
+ CreateBotTokenResponse, PatchBotRequest,
+ },
+ ports::{BotError, BotService},
+};
+use axum::{
+ Json, Router,
+ extract::{FromRef, Path, State},
+ http::StatusCode,
+ response::IntoResponse,
+ routing::{delete, get, patch, post},
+};
+use entity_access::{
+ domain::{
+ models::{AdminParticipantRole, EntityAccessReceipt},
+ ports::EntityAccessService,
+ },
+ inbound::axum_extractors::ChannelAccessLevelExtractor,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+use model_error_response::ErrorResponse;
+use model_user::axum_extractor::MacroUserExtractor;
+use std::sync::Arc;
+use uuid::Uuid;
+
+/// State for the bots router.
+pub struct BotsRouterState<S, Svc> {
+ service: Arc<S>,
+ access_service: Arc<Svc>,
+}
+
+impl<S, Svc> Clone for BotsRouterState<S, Svc> {
+ fn clone(&self) -> Self {
+ Self {
+ service: self.service.clone(),
+ access_service: self.access_service.clone(),
+ }
+ }
+}
+
+impl<S: BotService, Svc: EntityAccessService> BotsRouterState<S, Svc> {
+ /// Create a router state.
+ pub fn new(service: S, access_service: Svc) -> Self {
+ Self {
+ service: Arc::new(service),
+ access_service: Arc::new(access_service),
+ }
+ }
+}
+
+impl<S, Svc> FromRef<BotsRouterState<S, Svc>> for Arc<Svc> {
+ fn from_ref(state: &BotsRouterState<S, Svc>) -> Self {
+ state.access_service.clone()
+ }
+}
+
+/// Bot path.
+#[derive(Debug, serde::Deserialize)]
+pub struct BotPath {
+ /// Bot id.
+ pub bot_id: BotId,
+}
+
+/// Bot token path.
+#[derive(Debug, serde::Deserialize)]
+pub struct BotTokenPath {
+ /// Bot id.
+ pub bot_id: BotId,
+ /// Token id.
+ pub token_id: Uuid,
+}
+
+/// Channel path.
+#[derive(Debug, serde::Deserialize)]
+pub struct ChannelPath {
+ /// Channel id.
+ pub channel_id: Uuid,
+}
+
+/// Channel bot path.
+#[derive(Debug, serde::Deserialize)]
+pub struct ChannelBotPath {
+ /// Channel id.
+ pub channel_id: Uuid,
+ /// Bot id.
+ pub bot_id: BotId,
+}
+
+/// Create a bots router.
+pub fn bots_router<S, Svc, T>(state: BotsRouterState<S, Svc>) -> Router<T>
+where
+ S: BotService,
+ Svc: EntityAccessService,
+ T: Send + Sync,
+{
+ Router::new()
+ .route("/bots", get(list_bots_handler::<S, Svc>))
+ .route("/bots", post(create_bot_handler::<S, Svc>))
+ .route("/bots/{bot_id}", get(get_bot_handler::<S, Svc>))
+ .route("/bots/{bot_id}", patch(patch_bot_handler::<S, Svc>))
+ .route("/bots/{bot_id}", delete(delete_bot_handler::<S, Svc>))
+ .route("/bots/{bot_id}/tokens", get(list_tokens_handler::<S, Svc>))
+ .route(
+ "/bots/{bot_id}/tokens",
+ post(create_token_handler::<S, Svc>),
+ )
+ .route(
+ "/bots/{bot_id}/tokens/{token_id}",
+ delete(revoke_token_handler::<S, Svc>),
+ )
+ .route(
+ "/channels/{channel_id}/bots",
+ get(list_channel_bots_handler::<S, Svc>),
+ )
+ .route(
+ "/channels/{channel_id}/bots",
+ post(add_channel_bot_handler::<S, Svc>),
+ )
+ .route(
+ "/channels/{channel_id}/bots/{bot_id}",
+ delete(remove_channel_bot_handler::<S, Svc>),
+ )
+ .with_state(state)
+}
+
+fn caller_from_user(user: MacroUserExtractor) -> MacroUserIdStr<'static> {
+ user.macro_user_id
+}
+
+fn caller_from_receipt(
+ receipt: &EntityAccessReceipt<AdminParticipantRole>,
+) -> Result<MacroUserIdStr<'static>, BotsHandlerErr> {
+ receipt
+ .get_authenticated_user()
+ .cloned()
+ .map_err(|_| BotsHandlerErr::BadRequest("authenticated user required"))
+}
+
+async fn create_bot_handler<S: BotService, Svc: EntityAccessService>(
+ State(state): State<BotsRouterState<S, Svc>>,
+ user: MacroUserExtractor,
+ Json(req): Json<CreateBotRequest>,
+) -> Result<(StatusCode, Json<Bot>), BotsHandlerErr> {
+ let bot = state
+ .service
+ .create_bot(caller_from_user(user), req)
+ .await?;
+ Ok((StatusCode::CREATED, Json(bot)))
+}
+
+async fn list_bots_handler<S: BotService, Svc: EntityAccessService>(
+ State(state): State<BotsRouterState<S, Svc>>,
+ user: MacroUserExtractor,
+) -> Result<Json<Vec<Bot>>, BotsHandlerErr> {
+ Ok(Json(state.service.list_bots(caller_from_user(user)).await?))
+}
+
+async fn get_bot_handler<S: BotService, Svc: EntityAccessService>(
+ State(state): State<BotsRouterState<S, Svc>>,
+ user: MacroUserExtractor,
+ Path(path): Path<BotPath>,
+) -> Result<Json<Bot>, BotsHandlerErr> {
+ Ok(Json(
+ state
+ .service
+ .get_bot(caller_from_user(user), path.bot_id)
+ .await?,
+ ))
+}
+
+async fn patch_bot_handler<S: BotService, Svc: EntityAccessService>(
+ State(state): State<BotsRouterState<S, Svc>>,
+ user: MacroUserExtractor,
+ Path(path): Path<BotPath>,
+ Json(req): Json<PatchBotRequest>,
+) -> Result<Json<Bot>, BotsHandlerErr> {
+ Ok(Json(
+ state
+ .service
+ .patch_bot(caller_from_user(user), path.bot_id, req)
+ .await?,
+ ))
+}
+
+async fn delete_bot_handler<S: BotService, Svc: EntityAccessService>(
+ State(state): State<BotsRouterState<S, Svc>>,
+ user: MacroUserExtractor,
+ Path(path): Path<BotPath>,
+) -> Result<StatusCode, BotsHandlerErr> {
+ state
+ .service
+ .delete_bot(caller_from_user(user), path.bot_id)
+ .await?;
+ Ok(StatusCode::NO_CONTENT)
+}
+
+async fn create_token_handler<S: BotService, Svc: EntityAccessService>(
+ State(state): State<BotsRouterState<S, Svc>>,
+ user: MacroUserExtractor,
+ Path(path): Path<BotPath>,
+ Json(req): Json<CreateBotTokenRequest>,
+) -> Result<(StatusCode, Json<CreateBotTokenResponse>), BotsHandlerErr> {
+ let token = state
+ .service
+ .create_token(caller_from_user(user), path.bot_id, req)
+ .await?;
+ Ok((StatusCode::CREATED, Json(token)))
+}
+
+async fn list_tokens_handler<S: BotService, Svc: EntityAccessService>(
+ State(state): State<BotsRouterState<S, Svc>>,
+ user: MacroUserExtractor,
+ Path(path): Path<BotPath>,
+) -> Result<Json<Vec<BotToken>>, BotsHandlerErr> {
+ Ok(Json(
+ state
+ .service
+ .list_tokens(caller_from_user(user), path.bot_id)
+ .await?,
+ ))
+}
+
+async fn revoke_token_handler<S: BotService, Svc: EntityAccessService>(
+ State(state): State<BotsRouterState<S, Svc>>,
+ user: MacroUserExtractor,
+ Path(path): Path<BotTokenPath>,
+) -> Result<StatusCode, BotsHandlerErr> {
+ state
+ .service
+ .revoke_token(caller_from_user(user), path.bot_id, path.token_id)
+ .await?;
+ Ok(StatusCode::NO_CONTENT)
+}
+
+async fn list_channel_bots_handler<S: BotService, Svc: EntityAccessService>(
+ State(state): State<BotsRouterState<S, Svc>>,
+ _access: ChannelAccessLevelExtractor<AdminParticipantRole, Svc>,
+ Path(path): Path<ChannelPath>,
+) -> Result<Json<Vec<Bot>>, BotsHandlerErr> {
+ Ok(Json(
+ state.service.list_channel_bots(path.channel_id).await?,
+ ))
+}
+
+async fn add_channel_bot_handler<S: BotService, Svc: EntityAccessService>(
+ State(state): State<BotsRouterState<S, Svc>>,
+ access: ChannelAccessLevelExtractor<AdminParticipantRole, Svc>,
+ Path(path): Path<ChannelPath>,
+ Json(req): Json<AddChannelBotRequest>,
+) -> Result<StatusCode, BotsHandlerErr> {
+ let caller = caller_from_receipt(&access.entity_access_receipt)?;
+ state
+ .service
+ .add_bot_to_channel(caller, path.channel_id, req.bot_id)
+ .await?;
+ Ok(StatusCode::NO_CONTENT)
+}
+
+async fn remove_channel_bot_handler<S: BotService, Svc: EntityAccessService>(
+ State(state): State<BotsRouterState<S, Svc>>,
+ access: ChannelAccessLevelExtractor<AdminParticipantRole, Svc>,
+ Path(path): Path<ChannelBotPath>,
+) -> Result<StatusCode, BotsHandlerErr> {
+ let caller = caller_from_receipt(&access.entity_access_receipt)?;
+ state
+ .service
+ .remove_bot_from_channel(caller, path.channel_id, path.bot_id)
+ .await?;
+ Ok(StatusCode::NO_CONTENT)
+}
+
+/// Bots handler error.
+#[derive(Debug, thiserror::Error)]
+pub enum BotsHandlerErr {
+ /// Bad request.
+ #[error("{0}")]
+ BadRequest(&'static str),
+ /// Domain error.
+ #[error(transparent)]
+ Bot(#[from] BotError),
+}
+
+impl IntoResponse for BotsHandlerErr {
+ fn into_response(self) -> axum::response::Response {
+ let status = match &self {
+ Self::BadRequest(_) | Self::Bot(BotError::BadRequest(_)) => StatusCode::BAD_REQUEST,
+ Self::Bot(BotError::NotFound(_)) => StatusCode::NOT_FOUND,
+ Self::Bot(BotError::Unauthorized) => StatusCode::UNAUTHORIZED,
+ Self::Bot(BotError::Repo(_)) => StatusCode::INTERNAL_SERVER_ERROR,
+ };
+ if status == StatusCode::INTERNAL_SERVER_ERROR {
+ tracing::error!(error=?self, "bots handler error");
+ }
+ (
+ status,
+ Json(ErrorResponse {
+ message: self.to_string().into(),
+ }),
+ )
+ .into_response()
+ }
+}
diff --git a/rust/cloud-storage/bots/src/inbound/axum_router/tests.rs b/rust/cloud-storage/bots/src/inbound/axum_router/tests.rs
new file mode 100644
index 0000000000..d4214c0dfb
--- /dev/null
+++ b/rust/cloud-storage/bots/src/inbound/axum_router/tests.rs
@@ -0,0 +1,502 @@
+use super::*;
+use crate::domain::models::AuthenticatedBot;
+use crate::{domain::service::BotServiceImpl, outbound::pg_bots_repo::PgBotsRepo};
+use axum::{
+ Extension,
+ body::Body,
+ http::{Request, StatusCode},
+};
+use entity_access::domain::{
+ models::{
+ AccessError, AccessLevel, CallChannelInfo, EntityPermission, EntityType,
+ ParticipantRole as EntityParticipantRole, RequiredPermission, UserTeamInfo,
+ },
+ ports::EntityAccessService,
+};
+use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+use model_user::UserContext;
+use sqlx::{PgPool, Row};
+use std::sync::{
+ Arc,
+ atomic::{AtomicUsize, Ordering},
+};
+use tower::ServiceExt;
+
+#[derive(Clone, Copy)]
+enum TestBotMode {
+ Ok,
+ Unauthorized,
+}
+
+#[derive(Clone)]
+struct TestBotService {
+ mode: TestBotMode,
+ add_calls: Arc<AtomicUsize>,
+ remove_calls: Arc<AtomicUsize>,
+}
+
+impl TestBotService {
+ fn new(mode: TestBotMode) -> Self {
+ Self {
+ mode,
+ add_calls: Arc::new(AtomicUsize::new(0)),
+ remove_calls: Arc::new(AtomicUsize::new(0)),
+ }
+ }
+
+ fn result(&self) -> Result<(), BotError> {
+ match self.mode {
+ TestBotMode::Ok => Ok(()),
+ TestBotMode::Unauthorized => Err(BotError::Unauthorized),
+ }
+ }
+}
+
+impl BotService for TestBotService {
+ async fn create_bot(
+ &self,
+ _caller: MacroUserIdStr<'static>,
+ _req: CreateBotRequest,
+ ) -> Result<Bot, BotError> {
+ unimplemented!()
+ }
+
+ async fn list_bots(&self, _caller: MacroUserIdStr<'static>) -> Result<Vec<Bot>, BotError> {
+ unimplemented!()
+ }
+
+ async fn get_bot(
+ &self,
+ _caller: MacroUserIdStr<'static>,
+ _bot_id: BotId,
+ ) -> Result<Bot, BotError> {
+ unimplemented!()
+ }
+
+ async fn patch_bot(
+ &self,
+ _caller: MacroUserIdStr<'static>,
+ _bot_id: BotId,
+ _req: PatchBotRequest,
+ ) -> Result<Bot, BotError> {
+ unimplemented!()
+ }
+
+ async fn delete_bot(
+ &self,
+ _caller: MacroUserIdStr<'static>,
+ _bot_id: BotId,
+ ) -> Result<(), BotError> {
+ unimplemented!()
+ }
+
+ async fn add_bot_to_channel(
+ &self,
+ _caller: MacroUserIdStr<'static>,
+ _channel_id: Uuid,
+ _bot_id: BotId,
+ ) -> Result<(), BotError> {
+ self.add_calls.fetch_add(1, Ordering::SeqCst);
+ self.result()
+ }
+
+ async fn remove_bot_from_channel(
+ &self,
+ _caller: MacroUserIdStr<'static>,
+ _channel_id: Uuid,
+ _bot_id: BotId,
+ ) -> Result<(), BotError> {
+ self.remove_calls.fetch_add(1, Ordering::SeqCst);
+ self.result()
+ }
+
+ async fn list_channel_bots(&self, _channel_id: Uuid) -> Result<Vec<Bot>, BotError> {
+ unimplemented!()
+ }
+
+ async fn create_token(
+ &self,
+ _caller: MacroUserIdStr<'static>,
+ _bot_id: BotId,
+ _req: CreateBotTokenRequest,
+ ) -> Result<CreateBotTokenResponse, BotError> {
+ unimplemented!()
+ }
+
+ async fn list_tokens(
+ &self,
+ _caller: MacroUserIdStr<'static>,
+ _bot_id: BotId,
+ ) -> Result<Vec<BotToken>, BotError> {
+ unimplemented!()
+ }
+
+ async fn revoke_token(
+ &self,
+ _caller: MacroUserIdStr<'static>,
+ _bot_id: BotId,
+ _token_id: Uuid,
+ ) -> Result<(), BotError> {
+ unimplemented!()
+ }
+
+ async fn authenticate_token(&self, _token: &str) -> Result<AuthenticatedBot, BotError> {
+ unimplemented!()
+ }
+}
+
+#[derive(Clone, Copy)]
+struct TestAccessService {
+ role: EntityParticipantRole,
+}
+
+impl TestAccessService {
+ const fn new(role: EntityParticipantRole) -> Self {
+ Self { role }
+ }
+}
+
+impl EntityAccessService for TestAccessService {
+ async fn generate_entity_access_receipt<T: RequiredPermission>(
+ &self,
+ _user_id: &MacroUserId<Lowercase<'_>>,
+ _user_org_id: Option<i64>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<EntityAccessReceipt<T>, AccessError> {
+ unimplemented!()
+ }
+
+ async fn get_access_level(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<Option<AccessLevel>, AccessError> {
+ unimplemented!()
+ }
+
+ async fn check_access(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ _required_level: AccessLevel,
+ ) -> Result<AccessLevel, AccessError> {
+ unimplemented!()
+ }
+
+ async fn check_public_access(
+ &self,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ _required_level: AccessLevel,
+ ) -> Result<AccessLevel, AccessError> {
+ unimplemented!()
+ }
+
+ async fn get_entity_permission(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ _user_org_id: Option<i64>,
+ ) -> Result<EntityPermission, AccessError> {
+ Ok(EntityPermission::ChannelRole { role: self.role })
+ }
+
+ async fn get_users_by_entity(
+ &self,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {
+ unimplemented!()
+ }
+
+ async fn get_call_channel(
+ &self,
+ _call_id: &Uuid,
+ ) -> Result<Option<CallChannelInfo>, AccessError> {
+ unimplemented!()
+ }
+
+ async fn get_call_channel_by_channel_id(
+ &self,
+ _channel_id: &Uuid,
+ ) -> Result<Option<CallChannelInfo>, AccessError> {
+ unimplemented!()
+ }
+
+ async fn get_user_team(
+ &self,
+ _user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> Result<Option<UserTeamInfo>, AccessError> {
+ unimplemented!()
+ }
+}
+
+fn user_extension() -> Extension<UserContext> {
+ Extension(UserContext {
+ user_id: "macro|[email protected]".to_string(),
+ fusion_user_id: "fusion-user".to_string(),
+ permissions: None,
+ organization_id: None,
+ })
+}
+
+fn router(service: TestBotService, role: EntityParticipantRole) -> Router {
+ bots_router(BotsRouterState::new(service, TestAccessService::new(role))).layer(user_extension())
+}
+
+fn user_context(user_id: &str) -> Extension<UserContext> {
+ Extension(UserContext {
+ user_id: user_id.to_string(),
+ fusion_user_id: "fusion-user".to_string(),
+ permissions: None,
+ organization_id: None,
+ })
+}
+
+fn real_router(pool: PgPool, user_id: &str) -> Router {
+ let bot_service = BotServiceImpl::new(PgBotsRepo::new(pool.clone()));
+ let access_service = EntityAccessServiceImpl::new(PgAccessRepository::new(pool));
+ bots_router(BotsRouterState::new(bot_service, access_service)).layer(user_context(user_id))
+}
+
+async fn insert_user(pool: &PgPool, user_id: &str) -> anyhow::Result<()> {
+ let macro_user_id = Uuid::new_v4();
+ let email = user_id.strip_prefix("macro|").unwrap_or(user_id);
+ let stripe_customer_id = format!("stripe_{macro_user_id}");
+
+ sqlx::query(
+ r#"
+ INSERT INTO macro_user (id, username, email, stripe_customer_id)
+ VALUES ($1, $2, $3, $4)
+ ON CONFLICT (id) DO NOTHING
+ "#,
+ )
+ .bind(macro_user_id)
+ .bind(email)
+ .bind(email)
+ .bind(stripe_customer_id)
+ .execute(pool)
+ .await?;
+
+ sqlx::query(
+ r#"
+ INSERT INTO "User" (id, email, macro_user_id)
+ VALUES ($1, $2, $3)
+ ON CONFLICT (id) DO NOTHING
+ "#,
+ )
+ .bind(user_id)
+ .bind(email)
+ .bind(macro_user_id)
+ .execute(pool)
+ .await?;
+
+ Ok(())
+}
+
+async fn insert_private_channel_with_admin(
+ pool: &PgPool,
+ channel_id: Uuid,
+ admin_user_id: &str,
+) -> anyhow::Result<()> {
+ sqlx::query(
+ r#"
+ INSERT INTO comms_channels (id, name, channel_type, owner_id)
+ VALUES ($1, $2, 'private'::comms_channel_type, $3)
+ "#,
+ )
+ .bind(channel_id)
+ .bind("alarms")
+ .bind(admin_user_id)
+ .execute(pool)
+ .await?;
+
+ sqlx::query(
+ r#"
+ INSERT INTO comms_channel_participants (channel_id, user_id, role)
+ VALUES ($1, $2, 'admin'::comms_participant_role)
+ "#,
+ )
+ .bind(channel_id)
+ .bind(admin_user_id)
+ .execute(pool)
+ .await?;
+
+ Ok(())
+}
+
+fn macro_user_id(value: &str) -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from(value.to_string()).expect("valid macro user id")
+}
+
+#[tokio::test]
+async fn channel_member_cannot_add_bot_to_channel() {
+ let service = TestBotService::new(TestBotMode::Ok);
+ let channel_id = Uuid::new_v4();
+ let bot_id = BotId::from_uuid(Uuid::new_v4());
+ let request = Request::builder()
+ .method("POST")
+ .uri(format!("/channels/{channel_id}/bots"))
+ .header("content-type", "application/json")
+ .body(Body::from(
+ serde_json::json!({ "bot_id": bot_id }).to_string(),
+ ))
+ .unwrap();
+
+ let response = router(service.clone(), EntityParticipantRole::Member)
+ .oneshot(request)
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(service.add_calls.load(Ordering::SeqCst), 0);
+}
+
+#[tokio::test]
+async fn channel_admin_still_needs_bot_usability_to_add_bot() {
+ let service = TestBotService::new(TestBotMode::Unauthorized);
+ let channel_id = Uuid::new_v4();
+ let bot_id = BotId::from_uuid(Uuid::new_v4());
+ let request = Request::builder()
+ .method("POST")
+ .uri(format!("/channels/{channel_id}/bots"))
+ .header("content-type", "application/json")
+ .body(Body::from(
+ serde_json::json!({ "bot_id": bot_id }).to_string(),
+ ))
+ .unwrap();
+
+ let response = router(service.clone(), EntityParticipantRole::Admin)
+ .oneshot(request)
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(service.add_calls.load(Ordering::SeqCst), 1);
+}
+
+#[tokio::test]
+async fn channel_member_cannot_remove_bot_from_channel() {
+ let service = TestBotService::new(TestBotMode::Ok);
+ let channel_id = Uuid::new_v4();
+ let bot_id = BotId::from_uuid(Uuid::new_v4());
+ let request = Request::builder()
+ .method("DELETE")
+ .uri(format!("/channels/{channel_id}/bots/{bot_id}"))
+ .body(Body::empty())
+ .unwrap();
+
+ let response = router(service.clone(), EntityParticipantRole::Member)
+ .oneshot(request)
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(service.remove_calls.load(Ordering::SeqCst), 0);
+}
+
+#[tokio::test]
+async fn channel_admin_still_needs_bot_usability_to_remove_bot() {
+ let service = TestBotService::new(TestBotMode::Unauthorized);
+ let channel_id = Uuid::new_v4();
+ let bot_id = BotId::from_uuid(Uuid::new_v4());
+ let request = Request::builder()
+ .method("DELETE")
+ .uri(format!("/channels/{channel_id}/bots/{bot_id}"))
+ .body(Body::empty())
+ .unwrap();
+
+ let response = router(service.clone(), EntityParticipantRole::Admin)
+ .oneshot(request)
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert_eq!(service.remove_calls.load(Ordering::SeqCst), 1);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn channel_admin_can_add_and_remove_owned_bot_via_http(pool: PgPool) -> anyhow::Result<()> {
+ const ADMIN_USER_ID: &str = "macro|[email protected]";
+ let channel_id = Uuid::new_v4();
+
+ insert_user(&pool, ADMIN_USER_ID).await?;
+ insert_private_channel_with_admin(&pool, channel_id, ADMIN_USER_ID).await?;
+
+ let bot_service = BotServiceImpl::new(PgBotsRepo::new(pool.clone()));
+ let bot = bot_service
+ .create_bot(
+ macro_user_id(ADMIN_USER_ID),
+ CreateBotRequest {
+ team_id: None,
+ name: "Datadog Alerts".to_string(),
+ handle: "datadog-alerts".to_string(),
+ description: Some("Posts alarm notifications".to_string()),
+ avatar_url: None,
+ },
+ )
+ .await?;
+
+ let bot_principal_id = bot.id.to_storage_string();
+ let router = real_router(pool.clone(), ADMIN_USER_ID);
+ let add_request = Request::builder()
+ .method("POST")
+ .uri(format!("/channels/{channel_id}/bots"))
+ .header("content-type", "application/json")
+ .body(Body::from(
+ serde_json::json!({ "bot_id": bot.id }).to_string(),
+ ))
+ .unwrap();
+
+ let add_response = router.clone().oneshot(add_request).await.unwrap();
+ assert_eq!(add_response.status(), StatusCode::NO_CONTENT);
+
+ let participant = sqlx::query(
+ r#"
+ SELECT role::text AS role, left_at
+ FROM comms_channel_participants
+ WHERE channel_id = $1 AND user_id = $2
+ "#,
+ )
+ .bind(channel_id)
+ .bind(&bot_principal_id)
+ .fetch_one(&pool)
+ .await?;
+
+ let role: String = participant.try_get("role")?;
+ let left_at: Option<chrono::DateTime<chrono::Utc>> = participant.try_get("left_at")?;
+ assert_eq!(role, "member");
+ assert!(left_at.is_none());
+
+ let remove_request = Request::builder()
+ .method("DELETE")
+ .uri(format!("/channels/{channel_id}/bots/{}", bot.id))
+ .body(Body::empty())
+ .unwrap();
+
+ let remove_response = router.oneshot(remove_request).await.unwrap();
+ assert_eq!(remove_response.status(), StatusCode::NO_CONTENT);
+
+ let participant = sqlx::query(
+ r#"
+ SELECT left_at
+ FROM comms_channel_participants
+ WHERE channel_id = $1 AND user_id = $2
+ "#,
+ )
+ .bind(channel_id)
+ .bind(bot_principal_id)
+ .fetch_one(&pool)
+ .await?;
+
+ let left_at: Option<chrono::DateTime<chrono::Utc>> = participant.try_get("left_at")?;
+ assert!(left_at.is_some());
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/bots/src/inbound/mod.rs b/rust/cloud-storage/bots/src/inbound/mod.rs
new file mode 100644
index 0000000000..3d33942ed2
--- /dev/null
+++ b/rust/cloud-storage/bots/src/inbound/mod.rs
@@ -0,0 +1,4 @@
+//! Inbound HTTP adapters for bots.
+
+/// Axum router for bot management.
+pub mod axum_router;
diff --git a/rust/cloud-storage/bots/src/lib.rs b/rust/cloud-storage/bots/src/lib.rs
new file mode 100644
index 0000000000..88c9905921
--- /dev/null
+++ b/rust/cloud-storage/bots/src/lib.rs
@@ -0,0 +1,11 @@
+#![deny(missing_docs)]
+//! Bot management hex crate.
+
+/// Domain models, ports, and service.
+pub mod domain;
+#[cfg(feature = "inbound")]
+/// HTTP adapters.
+pub mod inbound;
+#[cfg(feature = "outbound")]
+/// Postgres adapters.
+pub mod outbound;
diff --git a/rust/cloud-storage/bots/src/outbound/mod.rs b/rust/cloud-storage/bots/src/outbound/mod.rs
new file mode 100644
index 0000000000..b9dab41adf
--- /dev/null
+++ b/rust/cloud-storage/bots/src/outbound/mod.rs
@@ -0,0 +1,4 @@
+//! Outbound adapters for bots.
+
+/// Postgres bot repository.
+pub mod pg_bots_repo;
diff --git a/rust/cloud-storage/bots/src/outbound/pg_bots_repo.rs b/rust/cloud-storage/bots/src/outbound/pg_bots_repo.rs
new file mode 100644
index 0000000000..8e077067c3
--- /dev/null
+++ b/rust/cloud-storage/bots/src/outbound/pg_bots_repo.rs
@@ -0,0 +1,562 @@
+//! Postgres bot repository.
+
+#[cfg(test)]
+mod tests;
+
+use crate::domain::{
+ models::{
+ AuthenticatedBot, Bot, BotId, BotKind, BotOwner, BotToken, BotTokenCandidate,
+ CreateBotRequest, CreateBotTokenRequest, PatchBotRequest,
+ },
+ ports::BotRepo,
+};
+use anyhow::Context;
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use sqlx::PgPool;
+use uuid::Uuid;
+
+/// Postgres implementation of [`BotRepo`].
+#[derive(Debug, Clone)]
+pub struct PgBotsRepo {
+ pool: PgPool,
+}
+
+impl PgBotsRepo {
+ /// Create a Postgres bot repository.
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
+ }
+}
+
+fn principal_id(bot_id: BotId) -> String {
+ bot_id.to_storage_string()
+}
+
+#[derive(Debug)]
+struct BotRow {
+ id: Uuid,
+ kind: String,
+ owner_user_id: Option<String>,
+ team_id: Option<Uuid>,
+ name: String,
+ handle: String,
+ description: Option<String>,
+ avatar_url: Option<String>,
+ created_by: Option<String>,
+ created_at: DateTime<Utc>,
+ updated_at: DateTime<Utc>,
+ deleted_at: Option<DateTime<Utc>>,
+}
+
+impl TryFrom<BotRow> for Bot {
+ type Error = anyhow::Error;
+
+ fn try_from(row: BotRow) -> Result<Self, Self::Error> {
+ let kind = row
+ .kind
+ .parse()
+ .map_err(|err: String| anyhow::anyhow!(err))?;
+ let owner = match (row.owner_user_id, row.team_id) {
+ (Some(user_id), None) => Some(BotOwner::User { user_id }),
+ (None, Some(team_id)) => Some(BotOwner::Team { team_id }),
+ _ => None,
+ };
+
+ Ok(Self {
+ id: BotId::from_uuid(row.id),
+ kind,
+ owner,
+ name: row.name,
+ handle: row.handle,
+ description: row.description,
+ avatar_url: row.avatar_url,
+ created_by: row.created_by,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ deleted_at: row.deleted_at,
+ })
+ }
+}
+
+#[derive(Debug)]
+struct BotTokenRow {
+ id: Uuid,
+ bot_id: Uuid,
+ token_prefix: String,
+ label: Option<String>,
+ last_used_at: Option<DateTime<Utc>>,
+ expires_at: Option<DateTime<Utc>>,
+ revoked_at: Option<DateTime<Utc>>,
+ created_at: DateTime<Utc>,
+}
+
+impl From<BotTokenRow> for BotToken {
+ fn from(row: BotTokenRow) -> Self {
+ Self {
+ id: row.id,
+ bot_id: BotId::from_uuid(row.bot_id),
+ token_prefix: row.token_prefix,
+ label: row.label,
+ last_used_at: row.last_used_at,
+ expires_at: row.expires_at,
+ revoked_at: row.revoked_at,
+ created_at: row.created_at,
+ }
+ }
+}
+
+#[derive(Debug)]
+struct TokenCandidateRow {
+ token_id: Uuid,
+ bot_id: Uuid,
+ token_hash: Vec<u8>,
+ token_prefix: String,
+ label: Option<String>,
+ last_used_at: Option<DateTime<Utc>>,
+ expires_at: Option<DateTime<Utc>>,
+ revoked_at: Option<DateTime<Utc>>,
+ created_at: DateTime<Utc>,
+ kind: String,
+}
+
+impl TokenCandidateRow {
+ fn into_candidate(self) -> anyhow::Result<BotTokenCandidate> {
+ let bot_id = BotId::from_uuid(self.bot_id);
+ let kind = self
+ .kind
+ .parse::<BotKind>()
+ .map_err(|err| anyhow::anyhow!(err))?;
+ let token = BotToken {
+ id: self.token_id,
+ bot_id,
+ token_prefix: self.token_prefix,
+ label: self.label,
+ last_used_at: self.last_used_at,
+ expires_at: self.expires_at,
+ revoked_at: self.revoked_at,
+ created_at: self.created_at,
+ };
+
+ Ok(BotTokenCandidate {
+ token,
+ token_hash: self.token_hash,
+ bot: AuthenticatedBot { bot_id, kind },
+ })
+ }
+}
+
+fn map_bot_row(row: BotRow) -> anyhow::Result<Bot> {
+ row.try_into()
+}
+
+fn map_token_row(row: BotTokenRow) -> BotToken {
+ row.into()
+}
+
+impl BotRepo for PgBotsRepo {
+ type Err = anyhow::Error;
+
+ async fn create_owned_bot(
+ &self,
+ owner: BotOwner,
+ created_by: MacroUserIdStr<'static>,
+ req: CreateBotRequest,
+ ) -> Result<Bot, Self::Err> {
+ let bot_id = BotId::from_uuid(macro_uuid::generate_uuid_v7());
+ let (owner_user_id, team_id) = match owner {
+ BotOwner::User { user_id } => (Some(user_id), None),
+ BotOwner::Team { team_id } => (None, Some(team_id)),
+ };
+ let row = sqlx::query_as!(
+ BotRow,
+ r#"
+ INSERT INTO bots (
+ id, kind, owner_user_id, team_id, name, handle, description, avatar_url, created_by
+ )
+ VALUES ($1, 'owned', $2, $3, $4, $5, $6, $7, $8)
+ RETURNING
+ id,
+ kind,
+ owner_user_id,
+ team_id,
+ name,
+ handle,
+ description,
+ avatar_url,
+ created_by,
+ created_at,
+ updated_at,
+ deleted_at
+ "#,
+ bot_id.as_uuid(),
+ owner_user_id,
+ team_id,
+ req.name,
+ req.handle,
+ req.description,
+ req.avatar_url,
+ created_by.as_ref(),
+ )
+ .fetch_one(&self.pool)
+ .await
+ .context("failed to create bot")?;
+
+ map_bot_row(row)
+ }
+
+ async fn list_manageable_bots(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ ) -> Result<Vec<Bot>, Self::Err> {
+ let rows = sqlx::query_as!(
+ BotRow,
+ r#"
+ SELECT
+ id,
+ kind,
+ owner_user_id,
+ team_id,
+ name,
+ handle,
+ description,
+ avatar_url,
+ created_by,
+ created_at,
+ updated_at,
+ deleted_at
+ FROM bots
+ WHERE kind = 'owned'
+ AND deleted_at IS NULL
+ AND (
+ owner_user_id = $1
+ OR team_id IN (
+ SELECT team_id FROM team_user WHERE user_id = $1
+ )
+ )
+ ORDER BY created_at ASC, id ASC
+ "#,
+ caller.as_ref(),
+ )
+ .fetch_all(&self.pool)
+ .await
+ .context("failed to list manageable bots")?;
+ rows.into_iter().map(map_bot_row).collect()
+ }
+
+ async fn get_bot(&self, bot_id: BotId) -> Result<Option<Bot>, Self::Err> {
+ let row = sqlx::query_as!(
+ BotRow,
+ r#"
+ SELECT
+ id,
+ kind,
+ owner_user_id,
+ team_id,
+ name,
+ handle,
+ description,
+ avatar_url,
+ created_by,
+ created_at,
+ updated_at,
+ deleted_at
+ FROM bots
+ WHERE id = $1
+ AND deleted_at IS NULL
+ "#,
+ bot_id.as_uuid(),
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .context("failed to get bot")?;
+ row.map(map_bot_row).transpose()
+ }
+
+ async fn user_has_team(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ team_id: Uuid,
+ ) -> Result<bool, Self::Err> {
+ let has_team = sqlx::query_scalar!(
+ r#"
+ SELECT EXISTS (
+ SELECT 1
+ FROM team_user
+ WHERE user_id = $1 AND team_id = $2
+ ) AS "has_team!"
+ "#,
+ caller.as_ref(),
+ team_id,
+ )
+ .fetch_one(&self.pool)
+ .await
+ .context("failed to check team membership")?;
+ Ok(has_team)
+ }
+
+ async fn patch_bot(
+ &self,
+ bot_id: BotId,
+ req: PatchBotRequest,
+ ) -> Result<Option<Bot>, Self::Err> {
+ let row = sqlx::query_as!(
+ BotRow,
+ r#"
+ UPDATE bots
+ SET name = COALESCE($2, name),
+ handle = COALESCE($3, handle),
+ description = COALESCE($4, description),
+ avatar_url = COALESCE($5, avatar_url),
+ updated_at = now()
+ WHERE id = $1
+ AND deleted_at IS NULL
+ RETURNING
+ id,
+ kind,
+ owner_user_id,
+ team_id,
+ name,
+ handle,
+ description,
+ avatar_url,
+ created_by,
+ created_at,
+ updated_at,
+ deleted_at
+ "#,
+ bot_id.as_uuid(),
+ req.name,
+ req.handle,
+ req.description,
+ req.avatar_url,
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .context("failed to patch bot")?;
+ row.map(map_bot_row).transpose()
+ }
+
+ async fn delete_bot(&self, bot_id: BotId) -> Result<bool, Self::Err> {
+ let mut tx = self.pool.begin().await?;
+ let result = sqlx::query!(
+ r#"
+ UPDATE bots
+ SET deleted_at = now(), updated_at = now()
+ WHERE id = $1
+ AND deleted_at IS NULL
+ "#,
+ bot_id.as_uuid(),
+ )
+ .execute(&mut *tx)
+ .await
+ .context("failed to soft-delete bot")?;
+
+ if result.rows_affected() > 0 {
+ sqlx::query!(
+ r#"
+ UPDATE comms_channel_participants
+ SET left_at = now()
+ WHERE user_id = $1
+ AND left_at IS NULL
+ "#,
+ principal_id(bot_id),
+ )
+ .execute(&mut *tx)
+ .await
+ .context("failed to remove deleted bot from channels")?;
+ }
+
+ tx.commit().await?;
+ Ok(result.rows_affected() > 0)
+ }
+
+ async fn add_bot_to_channel(&self, channel_id: Uuid, bot_id: BotId) -> Result<(), Self::Err> {
+ sqlx::query!(
+ r#"
+ INSERT INTO comms_channel_participants (channel_id, user_id, role, left_at)
+ VALUES ($1, $2, 'member'::comms_participant_role, NULL)
+ ON CONFLICT (channel_id, user_id)
+ DO UPDATE SET role = 'member'::comms_participant_role,
+ left_at = NULL,
+ joined_at = now()
+ "#,
+ channel_id,
+ principal_id(bot_id),
+ )
+ .execute(&self.pool)
+ .await
+ .context("failed to add bot to channel")?;
+ Ok(())
+ }
+
+ async fn remove_bot_from_channel(
+ &self,
+ channel_id: Uuid,
+ bot_id: BotId,
+ ) -> Result<bool, Self::Err> {
+ let result = sqlx::query!(
+ r#"
+ UPDATE comms_channel_participants
+ SET left_at = now()
+ WHERE channel_id = $1
+ AND user_id = $2
+ AND left_at IS NULL
+ "#,
+ channel_id,
+ principal_id(bot_id),
+ )
+ .execute(&self.pool)
+ .await
+ .context("failed to remove bot from channel")?;
+ Ok(result.rows_affected() > 0)
+ }
+
+ async fn list_channel_bots(&self, channel_id: Uuid) -> Result<Vec<Bot>, Self::Err> {
+ let rows = sqlx::query_as!(
+ BotRow,
+ r#"
+ SELECT
+ b.id,
+ b.kind,
+ b.owner_user_id,
+ b.team_id,
+ b.name,
+ b.handle,
+ b.description,
+ b.avatar_url,
+ b.created_by,
+ b.created_at,
+ b.updated_at,
+ b.deleted_at
+ FROM bots b
+ JOIN comms_channel_participants cp
+ ON cp.user_id = ('bot|' || b.id::text)
+ WHERE cp.channel_id = $1
+ AND cp.left_at IS NULL
+ AND b.deleted_at IS NULL
+ ORDER BY b.created_at ASC, b.id ASC
+ "#,
+ channel_id,
+ )
+ .fetch_all(&self.pool)
+ .await
+ .context("failed to list channel bots")?;
+ rows.into_iter().map(map_bot_row).collect()
+ }
+
+ async fn create_token(
+ &self,
+ bot_id: BotId,
+ token_hash: Vec<u8>,
+ token_prefix: String,
+ req: CreateBotTokenRequest,
+ ) -> Result<BotToken, Self::Err> {
+ let token_id = macro_uuid::generate_uuid_v7();
+ let row = sqlx::query_as!(
+ BotTokenRow,
+ r#"
+ INSERT INTO bot_tokens (
+ id, bot_id, token_hash, token_prefix, label, expires_at
+ )
+ VALUES ($1, $2, $3, $4, $5, $6)
+ RETURNING id, bot_id, token_prefix, label, last_used_at, expires_at, revoked_at, created_at
+ "#,
+ token_id,
+ bot_id.as_uuid(),
+ token_hash,
+ token_prefix,
+ req.label,
+ req.expires_at,
+ )
+ .fetch_one(&self.pool)
+ .await
+ .context("failed to create bot token")?;
+ Ok(map_token_row(row))
+ }
+
+ async fn list_tokens(&self, bot_id: BotId) -> Result<Vec<BotToken>, Self::Err> {
+ let rows = sqlx::query_as!(
+ BotTokenRow,
+ r#"
+ SELECT id, bot_id, token_prefix, label, last_used_at, expires_at, revoked_at, created_at
+ FROM bot_tokens
+ WHERE bot_id = $1
+ AND revoked_at IS NULL
+ ORDER BY created_at DESC, id DESC
+ "#,
+ bot_id.as_uuid(),
+ )
+ .fetch_all(&self.pool)
+ .await
+ .context("failed to list bot tokens")?;
+ Ok(rows.into_iter().map(map_token_row).collect())
+ }
+
+ async fn revoke_token(&self, bot_id: BotId, token_id: Uuid) -> Result<bool, Self::Err> {
+ let result = sqlx::query!(
+ r#"
+ UPDATE bot_tokens
+ SET revoked_at = now()
+ WHERE id = $1
+ AND bot_id = $2
+ AND revoked_at IS NULL
+ "#,
+ token_id,
+ bot_id.as_uuid(),
+ )
+ .execute(&self.pool)
+ .await
+ .context("failed to revoke bot token")?;
+ Ok(result.rows_affected() > 0)
+ }
+
+ async fn token_candidates(
+ &self,
+ token_prefix: &str,
+ ) -> Result<Vec<BotTokenCandidate>, Self::Err> {
+ let rows = sqlx::query_as!(
+ TokenCandidateRow,
+ r#"
+ SELECT
+ bt.id AS token_id,
+ bt.bot_id,
+ bt.token_hash,
+ bt.token_prefix,
+ bt.label,
+ bt.last_used_at,
+ bt.expires_at,
+ bt.revoked_at,
+ bt.created_at,
+ b.kind
+ FROM bot_tokens bt
+ JOIN bots b ON b.id = bt.bot_id
+ WHERE bt.token_prefix = $1
+ AND b.deleted_at IS NULL
+ "#,
+ token_prefix,
+ )
+ .fetch_all(&self.pool)
+ .await
+ .context("failed to lookup bot token candidates")?;
+
+ rows.into_iter()
+ .map(TokenCandidateRow::into_candidate)
+ .collect()
+ }
+
+ async fn mark_token_used(&self, token_id: Uuid) -> Result<(), Self::Err> {
+ sqlx::query!(
+ r#"
+ UPDATE bot_tokens
+ SET last_used_at = now()
+ WHERE id = $1
+ "#,
+ token_id,
+ )
+ .execute(&self.pool)
+ .await
+ .context("failed to mark bot token used")?;
+ Ok(())
+ }
+}
diff --git a/rust/cloud-storage/bots/src/outbound/pg_bots_repo/tests.rs b/rust/cloud-storage/bots/src/outbound/pg_bots_repo/tests.rs
new file mode 100644
index 0000000000..fd0bb79a61
--- /dev/null
+++ b/rust/cloud-storage/bots/src/outbound/pg_bots_repo/tests.rs
@@ -0,0 +1,258 @@
+use super::*;
+use crate::domain::{
+ models::{CreateBotRequest, CreateBotTokenRequest},
+ ports::{BotError, BotService},
+ service::BotServiceImpl,
+};
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use sqlx::PgPool;
+
+const USER_OWNER: &str = "macro|[email protected]";
+const USER_OTHER: &str = "macro|[email protected]";
+const TEAM_MEMBER: &str = "macro|[email protected]";
+const TEAM_OTHER: &str = "macro|[email protected]";
+
+fn user_id(value: &str) -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from(value.to_string()).expect("valid macro user id")
+}
+
+fn create_req(handle: &str) -> CreateBotRequest {
+ CreateBotRequest {
+ team_id: None,
+ name: "Datadog Alerts".to_string(),
+ handle: handle.to_string(),
+ description: Some("Posts alarm notifications".to_string()),
+ avatar_url: None,
+ }
+}
+
+fn service(pool: &PgPool) -> BotServiceImpl<PgBotsRepo> {
+ BotServiceImpl::new(PgBotsRepo::new(pool.clone()))
+}
+
+async fn insert_user(pool: &PgPool, user_id: &str) -> anyhow::Result<()> {
+ let macro_user_id = Uuid::new_v4();
+ let email = user_id.strip_prefix("macro|").unwrap_or(user_id);
+ let stripe_customer_id = format!("stripe_{macro_user_id}");
+
+ sqlx::query(
+ r#"
+ INSERT INTO macro_user (id, username, email, stripe_customer_id)
+ VALUES ($1, $2, $3, $4)
+ ON CONFLICT (id) DO NOTHING
+ "#,
+ )
+ .bind(macro_user_id)
+ .bind(email)
+ .bind(email)
+ .bind(stripe_customer_id)
+ .execute(pool)
+ .await?;
+
+ sqlx::query(
+ r#"
+ INSERT INTO "User" (id, email, macro_user_id)
+ VALUES ($1, $2, $3)
+ ON CONFLICT (id) DO NOTHING
+ "#,
+ )
+ .bind(user_id)
+ .bind(email)
+ .bind(macro_user_id)
+ .execute(pool)
+ .await?;
+
+ Ok(())
+}
+
+async fn insert_team_member(pool: &PgPool, team_id: Uuid, member_id: &str) -> anyhow::Result<()> {
+ insert_user(pool, member_id).await?;
+ sqlx::query(
+ r#"
+ INSERT INTO team (id, name, owner_id)
+ VALUES ($1, $2, $3)
+ ON CONFLICT (id) DO NOTHING
+ "#,
+ )
+ .bind(team_id)
+ .bind("Platform")
+ .bind(member_id)
+ .execute(pool)
+ .await?;
+
+ sqlx::query(
+ r#"
+ INSERT INTO team_user (user_id, team_id, team_role)
+ VALUES ($1, $2, 'member'::team_role)
+ ON CONFLICT (user_id, team_id) DO NOTHING
+ "#,
+ )
+ .bind(member_id)
+ .bind(team_id)
+ .execute(pool)
+ .await?;
+
+ Ok(())
+}
+
+async fn insert_channel(pool: &PgPool, channel_id: Uuid) -> anyhow::Result<()> {
+ sqlx::query(
+ r#"
+ INSERT INTO comms_channels (id, name, channel_type, owner_id)
+ VALUES ($1, $2, 'private'::comms_channel_type, $3)
+ "#,
+ )
+ .bind(channel_id)
+ .bind("alarms")
+ .bind(USER_OWNER)
+ .execute(pool)
+ .await?;
+
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn create_user_owned_bot_records_user_owner(pool: PgPool) -> anyhow::Result<()> {
+ let service = service(&pool);
+
+ let bot = service
+ .create_bot(user_id(USER_OWNER), create_req("datadog"))
+ .await?;
+
+ assert_eq!(bot.kind, BotKind::Owned);
+ assert_eq!(
+ bot.owner,
+ Some(BotOwner::User {
+ user_id: USER_OWNER.to_string(),
+ })
+ );
+ assert_eq!(bot.created_by.as_deref(), Some(USER_OWNER));
+ assert_eq!(bot.handle, "datadog");
+
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn create_team_owned_bot_requires_team_membership(pool: PgPool) -> anyhow::Result<()> {
+ let service = service(&pool);
+ let team_id = Uuid::new_v4();
+ insert_team_member(&pool, team_id, TEAM_MEMBER).await?;
+
+ let mut req = create_req("team-datadog");
+ req.team_id = Some(team_id);
+
+ let bot = service
+ .create_bot(user_id(TEAM_MEMBER), req.clone())
+ .await?;
+
+ assert_eq!(bot.owner, Some(BotOwner::Team { team_id }));
+
+ let err = service
+ .create_bot(user_id(TEAM_OTHER), req)
+ .await
+ .expect_err("non-team member must not create team-owned bot");
+
+ assert!(matches!(err, BotError::Unauthorized));
+
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn add_remove_channel_bot_requires_bot_usability_and_soft_removes(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ let service = service(&pool);
+ let channel_id = Uuid::new_v4();
+ insert_channel(&pool, channel_id).await?;
+
+ let bot = service
+ .create_bot(user_id(USER_OWNER), create_req("ops-alerts"))
+ .await?;
+
+ let err = service
+ .add_bot_to_channel(user_id(USER_OTHER), channel_id, bot.id)
+ .await
+ .expect_err("non-owner must not add someone else's bot");
+ assert!(matches!(err, BotError::Unauthorized));
+
+ service
+ .add_bot_to_channel(user_id(USER_OWNER), channel_id, bot.id)
+ .await?;
+
+ let active_count: i64 = sqlx::query_scalar(
+ r#"
+ SELECT COUNT(*) AS "count!"
+ FROM comms_channel_participants
+ WHERE channel_id = $1
+ AND user_id = $2
+ AND left_at IS NULL
+ "#,
+ )
+ .bind(channel_id)
+ .bind(principal_id(bot.id))
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(active_count, 1);
+
+ let err = service
+ .remove_bot_from_channel(user_id(USER_OTHER), channel_id, bot.id)
+ .await
+ .expect_err("non-owner must not remove someone else's bot");
+ assert!(matches!(err, BotError::Unauthorized));
+
+ service
+ .remove_bot_from_channel(user_id(USER_OWNER), channel_id, bot.id)
+ .await?;
+
+ let left_at: Option<chrono::DateTime<chrono::Utc>> = sqlx::query_scalar(
+ r#"
+ SELECT left_at
+ FROM comms_channel_participants
+ WHERE channel_id = $1 AND user_id = $2
+ "#,
+ )
+ .bind(channel_id)
+ .bind(principal_id(bot.id))
+ .fetch_one(&pool)
+ .await?;
+
+ assert!(left_at.is_some());
+ assert!(service.list_channel_bots(channel_id).await?.is_empty());
+
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn revoke_token_prevents_future_authentication(pool: PgPool) -> anyhow::Result<()> {
+ let service = service(&pool);
+ let bot = service
+ .create_bot(user_id(USER_OWNER), create_req("pagerduty"))
+ .await?;
+
+ let created = service
+ .create_token(
+ user_id(USER_OWNER),
+ bot.id,
+ CreateBotTokenRequest {
+ label: Some("Datadog".to_string()),
+ expires_at: None,
+ },
+ )
+ .await?;
+
+ let authenticated = service.authenticate_token(&created.bearer_token).await?;
+ assert_eq!(authenticated.bot_id, bot.id);
+ assert_eq!(authenticated.kind, BotKind::Owned);
+
+ service
+ .revoke_token(user_id(USER_OWNER), bot.id, created.token.id)
+ .await?;
+
+ let err = service
+ .authenticate_token(&created.bearer_token)
+ .await
+ .expect_err("revoked token must not authenticate");
+ assert!(matches!(err, BotError::Unauthorized));
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/channels/Cargo.toml b/rust/cloud-storage/channels/Cargo.toml
index 99b29c1a2b..8747d7c20b 100644
--- a/rust/cloud-storage/channels/Cargo.toml
+++ b/rust/cloud-storage/channels/Cargo.toml
@@ -46,6 +46,7 @@ ports = ["dep:tokio"]
[dependencies]
anyhow = { workspace = true }
axum = { workspace = true, optional = true }
+bot_id = { path = "../bot_id" }
chrono = { workspace = true }
connection_gateway_client = { path = "../connection_gateway_client", optional = true }
contacts = { path = "../contacts", default-features = false, features = ["outbound"], optional = true }
diff --git a/rust/cloud-storage/channels/src/domain/events.rs b/rust/cloud-storage/channels/src/domain/events.rs
index d8a09b0f6c..7a5e93f4a7 100644
--- a/rust/cloud-storage/channels/src/domain/events.rs
+++ b/rust/cloud-storage/channels/src/domain/events.rs
@@ -2,7 +2,7 @@
use crate::domain::models::{
ChannelMetadata, ChannelParticipant, ChannelType, CountedReaction, MutatedAttachment,
- MutatedMessage, SimpleMention, TypingAction,
+ MutatedMessage, Sender, SimpleMention, TypingAction,
};
use macro_user_id::user_id::MacroUserIdStr;
use uuid::Uuid;
@@ -14,6 +14,8 @@ pub enum ChannelEvent {
ChannelCreated {
/// Created channel id.
channel_id: Uuid,
+ /// Actor that created the channel.
+ actor: Sender,
/// Type of channel that was created.
channel_type: ChannelType,
/// Active participants after creation.
@@ -23,6 +25,8 @@ pub enum ChannelEvent {
ChannelDeleted {
/// Deleted channel id.
channel_id: Uuid,
+ /// Actor that deleted the channel.
+ actor: Sender,
},
/// A message was posted.
MessagePosted {
@@ -47,6 +51,8 @@ pub enum ChannelEvent {
AttachmentsChanged {
/// Channel containing the message.
channel_id: Uuid,
+ /// Actor that changed the attachments.
+ actor: Sender,
/// Message whose attachments changed.
message_id: Uuid,
/// Current attachment set for the message.
@@ -60,6 +66,8 @@ pub enum ChannelEvent {
MessageChanged {
/// Channel containing the message.
channel_id: Uuid,
+ /// Actor that changed the message.
+ actor: Sender,
/// Persisted message payload after mutation.
message: MutatedMessage,
/// Realtime recipients at mutation time.
@@ -71,6 +79,8 @@ pub enum ChannelEvent {
MessageDeleted {
/// Channel containing the message.
channel_id: Uuid,
+ /// Actor that deleted the message.
+ actor: Sender,
/// Persisted message payload after deletion.
message: MutatedMessage,
/// Realtime recipients at mutation time.
@@ -82,6 +92,8 @@ pub enum ChannelEvent {
ReactionChanged {
/// Channel containing the message.
channel_id: Uuid,
+ /// Actor that changed the reaction.
+ actor: Sender,
/// Message whose reactions changed.
message_id: Uuid,
/// Current grouped reaction state for the message.
@@ -95,8 +107,8 @@ pub enum ChannelEvent {
TypingChanged {
/// Channel containing the typing update.
channel_id: Uuid,
- /// User whose typing state changed.
- user_id: String,
+ /// Actor whose typing state changed.
+ actor: Sender,
/// Typing action.
action: TypingAction,
/// Optional thread id for thread-scoped typing.
@@ -114,8 +126,8 @@ pub enum ChannelEvent {
channel_type: ChannelType,
/// Active participants after the addition.
active_participant_user_ids: Vec<MacroUserIdStr<'static>>,
- /// User who initiated the add.
- invited_by_user_id: MacroUserIdStr<'static>,
+ /// Actor who initiated the add.
+ invited_by: Sender,
/// Newly added recipients.
recipient_user_ids: Vec<MacroUserIdStr<'static>>,
/// Resolved channel metadata for notification copy.
@@ -129,8 +141,8 @@ pub enum ChannelEvent {
channel_id: Uuid,
/// Type of channel that was joined.
channel_type: ChannelType,
- /// User that joined the channel.
- user_id: MacroUserIdStr<'static>,
+ /// Actor that joined the channel.
+ user_id: Sender,
/// Active participants after the join.
active_participant_user_ids: Vec<MacroUserIdStr<'static>>,
},
diff --git a/rust/cloud-storage/channels/src/domain/models.rs b/rust/cloud-storage/channels/src/domain/models.rs
index 0dce470c18..e8263e6883 100644
--- a/rust/cloud-storage/channels/src/domain/models.rs
+++ b/rust/cloud-storage/channels/src/domain/models.rs
@@ -1,9 +1,98 @@
use chrono::{DateTime, Utc};
use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{CreatedAt, CursorVal, Identify, SortOn};
-use serde::{Deserialize, Serialize};
+use serde::{Deserialize, Serialize, Serializer};
use uuid::Uuid;
+pub use bot_id::BotId;
+
+/// Error returned when a sender storage string is not a user or bot id.
+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+#[error("invalid sender id: {value}")]
+pub struct SenderParseError {
+ value: String,
+}
+
+impl SenderParseError {
+ fn invalid(value: &str) -> Self {
+ Self {
+ value: value.to_string(),
+ }
+ }
+}
+
+/// Actor identity for channel mutations.
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub enum Sender {
+ /// A first-party Macro user.
+ User(MacroUserIdStr<'static>),
+ /// A channel-scoped or system bot.
+ Bot(BotId),
+}
+
+impl Sender {
+ /// Parse a sender id from the existing TEXT storage representation.
+ pub fn parse_storage_str(value: &str) -> Result<Self, SenderParseError> {
+ if let Ok(bot_id) = BotId::parse_storage_str(value) {
+ return Ok(Self::Bot(bot_id));
+ }
+
+ MacroUserIdStr::try_from(value.to_string())
+ .map(Self::User)
+ .map_err(|_| SenderParseError::invalid(value))
+ }
+
+ /// Canonical storage representation for existing TEXT sender/participant columns.
+ pub fn to_storage_string(&self) -> String {
+ match self {
+ Self::User(user_id) => user_id.as_ref().to_string(),
+ Self::Bot(bot_id) => bot_id.to_storage_string(),
+ }
+ }
+
+ /// Return the authenticated user id when the sender is a user.
+ pub fn as_user(&self) -> Option<&MacroUserIdStr<'static>> {
+ match self {
+ Self::User(user_id) => Some(user_id),
+ Self::Bot(_) => None,
+ }
+ }
+
+ /// Whether this sender is a bot.
+ pub const fn is_bot(&self) -> bool {
+ matches!(self, Self::Bot(_))
+ }
+}
+
+impl From<MacroUserIdStr<'static>> for Sender {
+ fn from(user_id: MacroUserIdStr<'static>) -> Self {
+ Self::User(user_id)
+ }
+}
+
+impl std::str::FromStr for Sender {
+ type Err = SenderParseError;
+
+ fn from_str(value: &str) -> Result<Self, Self::Err> {
+ Self::parse_storage_str(value)
+ }
+}
+
+impl std::fmt::Display for Sender {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(&self.to_storage_string())
+ }
+}
+
+impl Serialize for Sender {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ serializer.serialize_str(&self.to_storage_string())
+ }
+}
+
/// Request to fetch a page of channel messages.
#[derive(Debug)]
pub struct GetChannelMessagesRequest {
@@ -767,8 +856,8 @@ pub struct MutatedMessage {
pub channel_id: Uuid,
/// Thread parent id.
pub thread_id: Option<Uuid>,
- /// Sender user id.
- pub sender_id: MacroUserIdStr<'static>,
+ /// Sender actor id.
+ pub sender_id: Sender,
/// Message body.
pub content: String,
/// Created timestamp.
@@ -951,3 +1040,26 @@ pub struct DeleteEntityMentionResponse {
/// Whether the mention was deleted.
pub deleted: bool,
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn sender_round_trips_user_storage_string() {
+ let sender = Sender::parse_storage_str("macro|[email protected]").unwrap();
+
+ assert_eq!(sender.to_storage_string(), "macro|[email protected]");
+ assert!(matches!(sender, Sender::User(_)));
+ }
+
+ #[test]
+ fn sender_round_trips_bot_storage_string() {
+ let id = Uuid::new_v4();
+ let storage = format!("bot|{id}");
+ let sender = Sender::parse_storage_str(&storage).unwrap();
+
+ assert_eq!(sender.to_storage_string(), storage);
+ assert_eq!(serde_json::to_value(&sender).unwrap(), storage);
+ }
+}
diff --git a/rust/cloud-storage/channels/src/domain/ports.rs b/rust/cloud-storage/channels/src/domain/ports.rs
index 5ab1dd1ade..6ed9ec558a 100644
--- a/rust/cloud-storage/channels/src/domain/ports.rs
+++ b/rust/cloud-storage/channels/src/domain/ports.rs
@@ -8,8 +8,8 @@ use crate::domain::models::{
MessageAttachment, MessagePageDirection, MutatedAttachment, MutatedMessage,
NewChannelAttachment, PatchChannelRequest, PatchMessageRequest, PostMessageRequest,
PostMessageResponse, PostReactionRequest, PostTypingRequest, ReferencedShareItem,
- RemoveParticipantsRequest, ResolvedChannelMessage, SimpleMention, ThreadData, ThreadReply,
- ThreadReplyRow, TopLevelMessageRow,
+ RemoveParticipantsRequest, ResolvedChannelMessage, Sender, SimpleMention, ThreadData,
+ ThreadReply, ThreadReplyRow, TopLevelMessageRow,
};
use crate::domain::side_effects::{
ChannelDocumentMention, ChannelNotificationEffect, ChannelRealtimeEffect,
@@ -474,7 +474,7 @@ pub trait ChannelService: Send + Sync + 'static {
/// Create a channel.
fn create_channel(
&self,
- _actor: MacroUserIdStr<'static>,
+ _actor: Sender,
_actor_org_id: Option<i64>,
_req: CreateChannelRequest,
) -> impl Future<Output = Result<CreateChannelResponse, ChannelMutationErr>> + Send {
@@ -488,7 +488,7 @@ pub trait ChannelService: Send + Sync + 'static {
/// Get or create a direct message channel.
fn get_or_create_dm(
&self,
- _actor: MacroUserIdStr<'static>,
+ _actor: Sender,
_req: GetOrCreateDmRequest,
) -> impl Future<Output = Result<GetOrCreateChannelResponse, ChannelMutationErr>> + Send {
async move {
@@ -501,7 +501,7 @@ pub trait ChannelService: Send + Sync + 'static {
/// Get or create a private channel.
fn get_or_create_private(
&self,
- _actor: MacroUserIdStr<'static>,
+ _actor: Sender,
_req: GetOrCreatePrivateRequest,
) -> impl Future<Output = Result<GetOrCreateChannelResponse, ChannelMutationErr>> + Send {
async move {
@@ -514,7 +514,7 @@ pub trait ChannelService: Send + Sync + 'static {
/// Patch a channel.
fn patch_channel(
&self,
- _actor: MacroUserIdStr<'static>,
+ _actor: Sender,
_channel_id: Uuid,
_req: PatchChannelRequest,
) -> impl Future<Output = Result<(), ChannelMutationErr>> + Send {
@@ -528,7 +528,7 @@ pub trait ChannelService: Send + Sync + 'static {
/// Delete a channel.
fn delete_channel(
&self,
- _actor: MacroUserIdStr<'static>,
+ _actor: Sender,
_channel_id: Uuid,
) -> impl Future<Output = Result<(), ChannelMutationErr>> + Send {
async move {
@@ -541,7 +541,7 @@ pub trait ChannelService: Send + Sync + 'static {
/// Send a message.
fn post_message(
&self,
- _actor: MacroUserIdStr<'static>,
+ _actor: Sender,
_channel_id: Uuid,
_req: PostMessageRequest,
) -> impl Future<Output = Result<PostMessageResponse, ChannelMutationErr>> + Send {
@@ -555,7 +555,7 @@ pub trait ChannelService: Send + Sync + 'static {
/// Patch a message.
fn patch_message(
&self,
- _actor: MacroUserIdStr<'static>,
+ _actor: Sender,
_actor_role: super::models::ParticipantRole,
_channel_id: Uuid,
_message_id: Uuid,
@@ -571,7 +571,7 @@ pub trait ChannelService: Send + Sync + 'static {
/// Delete a message.
fn delete_message(
&self,
- _actor: MacroUserIdStr<'static>,
+ _actor: Sender,
_actor_role: super::models::ParticipantRole,
_channel_id: Uuid,
_message_id: Uuid,
@@ -587,7 +587,7 @@ pub trait ChannelService: Send + Sync + 'static {
/// Mutate a reaction.
fn post_reaction(
&self,
- _actor: MacroUserIdStr<'static>,
+ _actor: Sender,
_channel_id: Uuid,
_req: PostReactionRequest,
) -> impl Future<Output = Result<(), ChannelMutationErr>> + Send {
@@ -601,7 +601,7 @@ pub trait ChannelService: Send + Sync + 'static {
/// Emit a typing update.
fn post_typing(
&self,
- _actor: MacroUserIdStr<'static>,
+ _actor: Sender,
_channel_id: Uuid,
_req: PostTypingRequest,
) -> impl Future<Output = Result<(), ChannelMutationErr>> + Send {
@@ -615,7 +615,7 @@ pub trait ChannelService: Send + Sync + 'static {
/// Add participants to a channel.
fn add_participants(
&self,
- _actor: MacroUserIdStr<'static>,
+ _actor: Sender,
_channel_id: Uuid,
_req: AddParticipantsRequest,
) -> impl Future<Output = Result<(), ChannelMutationErr>> + Send {
@@ -629,6 +629,7 @@ pub trait ChannelService: Send + Sync + 'static {
/// Remove participants from a channel.
fn remove_participants(
&self,
+ _actor: Sender,
_channel_id: Uuid,
_req: RemoveParticipantsRequest,
) -> impl Future<Output = Result<(), ChannelMutationErr>> + Send {
@@ -642,7 +643,7 @@ pub trait ChannelService: Send + Sync + 'static {
/// Join a channel.
fn join_channel(
&self,
- _actor: MacroUserIdStr<'static>,
+ _actor: Sender,
_channel_id: Uuid,
) -> impl Future<Output = Result<(), ChannelMutationErr>> + Send {
async move {
@@ -655,7 +656,7 @@ pub trait ChannelService: Send + Sync + 'static {
/// Leave a channel.
fn leave_channel(
&self,
- _actor: MacroUserIdStr<'static>,
+ _actor: Sender,
_channel_id: Uuid,
) -> impl Future<Output = Result<(), ChannelMutationErr>> + Send {
async move {
@@ -704,7 +705,7 @@ pub trait ChannelService: Send + Sync + 'static {
/// Upsert the user's activity (view/interaction) for a channel.
fn post_activity(
&self,
- _user_id: String,
+ _actor: Sender,
_channel_id: Uuid,
_activity_type: ActivityType,
) -> impl Future<Output = Result<Activity, ChannelMutationErr>> + Send {
diff --git a/rust/cloud-storage/channels/src/domain/service.rs b/rust/cloud-storage/channels/src/domain/service.rs
index 23caa2f772..ce860739c1 100644
--- a/rust/cloud-storage/channels/src/domain/service.rs
+++ b/rust/cloud-storage/channels/src/domain/service.rs
@@ -3,13 +3,13 @@ use crate::domain::{
models::{
Activity, ActivityType, AddParticipantsRequest, AttachmentEntityReference,
ChannelAttachmentType, ChannelContextMessage, ChannelMessage, ChannelMessageFilters,
- ChannelParticipant, ChannelPreview, ChannelPreviewData, ChannelType,
+ ChannelMetadata, ChannelParticipant, ChannelPreview, ChannelPreviewData, ChannelType,
CreateEntityMentionOptions, DeleteMessageQuery, EntityMention, GetOrCreateAction,
GetOrCreateChannelResponse, GetOrCreateDmRequest, GetOrCreatePrivateRequest,
MessagePageDirection, NewChannelAttachment, ParticipantRole, PatchChannelRequest,
PatchMessageRequest, PostMessageRequest, PostMessageResponse, PostReactionRequest,
PostTypingRequest, ReactionAction, ReferencedShareItem, RemoveParticipantsRequest,
- ResolvedChannelMessage, SimpleMention, ThreadInfo, ThreadReply, TopLevelMessageRow,
+ ResolvedChannelMessage, Sender, SimpleMention, ThreadInfo, ThreadReply, TopLevelMessageRow,
WithChannelId,
},
ports::{
@@ -184,6 +184,13 @@ fn parse_macro_user_id(
.map_err(|_| ChannelMutationErr::BadRequest("invalid user id".to_string()))
}
+fn require_user_actor(actor: &Sender) -> Result<MacroUserIdStr<'static>, ChannelMutationErr> {
+ actor
+ .as_user()
+ .cloned()
+ .ok_or_else(|| ChannelMutationErr::BadRequest("authenticated user required".to_string()))
+}
+
fn participant_ids(participants: &[ChannelParticipant]) -> Vec<MacroUserIdStr<'static>> {
participants
.iter()
@@ -239,10 +246,11 @@ where
#[tracing::instrument(err, skip(self, req))]
async fn create_channel(
&self,
- actor: MacroUserIdStr<'static>,
+ actor: Sender,
actor_org_id: Option<i64>,
req: crate::domain::models::CreateChannelRequest,
) -> Result<crate::domain::models::CreateChannelResponse, ChannelMutationErr> {
+ let actor = require_user_actor(&actor)?;
if req.channel_type == ChannelType::Team {
let team_id = req.team_id.ok_or_else(|| {
ChannelMutationErr::BadRequest("team id missing for team channel type".to_string())
@@ -286,6 +294,7 @@ where
self.events.dispatch(ChannelEvent::ChannelCreated {
channel_id,
+ actor: Sender::User(actor.clone()),
channel_type: req.channel_type,
participant_user_ids: created_channel_participant_ids(actor.as_ref(), &participants)?,
});
@@ -298,9 +307,10 @@ where
#[tracing::instrument(err, skip(self, req))]
async fn get_or_create_dm(
&self,
- actor: MacroUserIdStr<'static>,
+ actor: Sender,
req: GetOrCreateDmRequest,
) -> Result<GetOrCreateChannelResponse, ChannelMutationErr> {
+ let actor = require_user_actor(&actor)?;
let recipient_id = req.recipient_id.to_lowercase();
let user_id = actor.as_ref().to_lowercase();
@@ -343,9 +353,10 @@ where
#[tracing::instrument(err, skip(self, req))]
async fn get_or_create_private(
&self,
- actor: MacroUserIdStr<'static>,
+ actor: Sender,
mut req: GetOrCreatePrivateRequest,
) -> Result<GetOrCreateChannelResponse, ChannelMutationErr> {
+ let actor = require_user_actor(&actor)?;
req.recipients = lower_macro_users(&req.recipients);
if req.recipients.is_empty() {
return Err(ChannelMutationErr::BadRequest(
@@ -379,10 +390,11 @@ where
#[tracing::instrument(err, skip(self, req))]
async fn patch_channel(
&self,
- actor: MacroUserIdStr<'static>,
+ actor: Sender,
channel_id: Uuid,
req: PatchChannelRequest,
) -> Result<(), ChannelMutationErr> {
+ let actor = require_user_actor(&actor)?;
let info = self
.repo
.get_channel_info(channel_id)
@@ -402,30 +414,34 @@ where
#[tracing::instrument(err, skip(self))]
async fn delete_channel(
&self,
- actor: MacroUserIdStr<'static>,
+ actor: Sender,
channel_id: Uuid,
) -> Result<(), ChannelMutationErr> {
+ let actor = require_user_actor(&actor)?;
self.repo
.delete_channel(channel_id, actor.as_ref().to_string())
.await
.map_err(|e| ChannelMutationErr::Repo(e.into()))?;
- self.events
- .dispatch(ChannelEvent::ChannelDeleted { channel_id });
+ self.events.dispatch(ChannelEvent::ChannelDeleted {
+ channel_id,
+ actor: Sender::User(actor),
+ });
Ok(())
}
#[tracing::instrument(err, skip(self, req))]
async fn post_message(
&self,
- actor: MacroUserIdStr<'static>,
+ actor: Sender,
channel_id: Uuid,
req: PostMessageRequest,
) -> Result<PostMessageResponse, ChannelMutationErr> {
+ let actor_storage_id = actor.to_storage_string();
let message = self
.repo
.create_message(
channel_id,
- actor.as_ref().to_string(),
+ actor_storage_id.clone(),
req.content.clone(),
req.thread_id,
)
@@ -446,10 +462,11 @@ where
let items = extract_share_items(&req.attachments, &req.mentions);
if !items.is_empty()
+ && let Some(user_actor) = actor.as_user()
&& let Err(err) = self
.reference_share_permissions
.update_channel_share_permissions_for_referenced_items(
- actor.clone(),
+ user_actor.clone(),
channel_id,
items,
)
@@ -459,21 +476,33 @@ where
tracing::error!(error=?err, "unable to update channel share permissions");
}
- let channel_metadata = self
- .repo
- .get_channel_metadata(channel_id, actor.clone())
- .await
- .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+ let channel_metadata = if let Some(user_actor) = actor.as_user() {
+ self.repo
+ .get_channel_metadata(channel_id, user_actor.clone())
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?
+ } else {
+ let info = self
+ .repo
+ .get_channel_info(channel_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+ ChannelMetadata {
+ channel_type: info.channel_type,
+ channel_name: info.name.unwrap_or_default(),
+ }
+ };
let participants = self
.repo
.get_participants(channel_id)
.await
.map_err(|e| ChannelMutationErr::Repo(e.into()))?;
- if let Err(err) = self
- .repo
- .upsert_activity(actor.as_ref().to_string(), channel_id)
- .await
+ if actor.as_user().is_some()
+ && let Err(err) = self
+ .repo
+ .upsert_activity(actor_storage_id, channel_id)
+ .await
{
let err: anyhow::Error = err.into();
tracing::error!(error=?err, "unable to upsert activity for message");
@@ -506,19 +535,20 @@ where
#[tracing::instrument(err, skip(self, req))]
async fn patch_message(
&self,
- actor: MacroUserIdStr<'static>,
+ actor: Sender,
actor_role: ParticipantRole,
channel_id: Uuid,
message_id: Uuid,
mut req: PatchMessageRequest,
) -> Result<(), ChannelMutationErr> {
+ let actor_storage_id = actor.to_storage_string();
let owner = self
.repo
.get_message_owner(channel_id, message_id)
.await
.map_err(|e| ChannelMutationErr::Repo(e.into()))?
.ok_or_else(|| ChannelMutationErr::NotFound("message not found".to_string()))?;
- if owner != actor.as_ref() && !is_admin_or_owner(actor_role) {
+ if owner.as_str() != actor_storage_id.as_str() && !is_admin_or_owner(actor_role) {
return Err(ChannelMutationErr::Unauthorized(
"user is not authorized to edit this message".to_string(),
));
@@ -556,10 +586,11 @@ where
let items = extract_share_items(&[], &mentions);
if !items.is_empty()
+ && let Some(user_actor) = actor.as_user()
&& let Err(err) = self
.reference_share_permissions
.update_channel_share_permissions_for_referenced_items(
- actor.clone(),
+ user_actor.clone(),
channel_id,
items,
)
@@ -587,15 +618,17 @@ where
self.events.dispatch(ChannelEvent::MessageChanged {
channel_id,
+ actor: actor.clone(),
message: message.clone(),
recipients: participants,
nonce: req.nonce.clone(),
});
- if let Err(err) = self
- .repo
- .upsert_activity(actor.as_ref().to_string(), channel_id)
- .await
+ if actor.as_user().is_some()
+ && let Err(err) = self
+ .repo
+ .upsert_activity(actor_storage_id.clone(), channel_id)
+ .await
{
let err: anyhow::Error = err.into();
tracing::error!(error=?err, "unable to upsert activity for message");
@@ -604,9 +637,10 @@ where
if attachments_changed
&& req.content.is_none()
+ && actor.as_user().is_some()
&& let Err(err) = self
.repo
- .upsert_activity(actor.as_ref().to_string(), channel_id)
+ .upsert_activity(actor_storage_id, channel_id)
.await
{
let err: anyhow::Error = err.into();
@@ -619,19 +653,20 @@ where
#[tracing::instrument(err, skip(self, query))]
async fn delete_message(
&self,
- actor: MacroUserIdStr<'static>,
+ actor: Sender,
actor_role: ParticipantRole,
channel_id: Uuid,
message_id: Uuid,
query: DeleteMessageQuery,
) -> Result<(), ChannelMutationErr> {
+ let actor_storage_id = actor.to_storage_string();
let owner = self
.repo
.get_message_owner(channel_id, message_id)
.await
.map_err(|e| ChannelMutationErr::Repo(e.into()))?
.ok_or_else(|| ChannelMutationErr::NotFound("message not found".to_string()))?;
- if owner != actor.as_ref() && !is_admin_or_owner(actor_role) {
+ if owner.as_str() != actor_storage_id.as_str() && !is_admin_or_owner(actor_role) {
return Err(ChannelMutationErr::Unauthorized(
"user is not authorized to delete this message".to_string(),
));
@@ -650,6 +685,7 @@ where
self.events.dispatch(ChannelEvent::MessageDeleted {
channel_id,
+ actor,
message,
recipients: participant_ids(&participants),
nonce: query.nonce,
@@ -660,10 +696,11 @@ where
#[tracing::instrument(err, skip(self, req))]
async fn post_reaction(
&self,
- actor: MacroUserIdStr<'static>,
+ actor: Sender,
channel_id: Uuid,
req: PostReactionRequest,
) -> Result<(), ChannelMutationErr> {
+ let actor_storage_id = actor.to_storage_string();
let message_id = Uuid::parse_str(&req.message_id)
.map_err(|err| ChannelMutationErr::BadRequest(err.to_string()))?;
self.repo
@@ -674,22 +711,12 @@ where
match req.action {
ReactionAction::Add => {
self.repo
- .add_reaction(
- channel_id,
- message_id,
- req.emoji,
- actor.as_ref().to_string(),
- )
+ .add_reaction(channel_id, message_id, req.emoji, actor_storage_id.clone())
.await
}
ReactionAction::Remove => {
self.repo
- .remove_reaction(
- channel_id,
- message_id,
- req.emoji,
- actor.as_ref().to_string(),
- )
+ .remove_reaction(channel_id, message_id, req.emoji, actor_storage_id.clone())
.await
}
}
@@ -708,16 +735,18 @@ where
self.events.dispatch(ChannelEvent::ReactionChanged {
channel_id,
+ actor: actor.clone(),
message_id,
reactions,
recipients: participant_ids(&participants),
nonce: req.nonce,
});
- if let Err(err) = self
- .repo
- .upsert_activity(actor.as_ref().to_string(), channel_id)
- .await
+ if actor.as_user().is_some()
+ && let Err(err) = self
+ .repo
+ .upsert_activity(actor_storage_id, channel_id)
+ .await
{
let err: anyhow::Error = err.into();
tracing::error!(error=?err, "unable to upsert activity for reaction");
@@ -728,7 +757,7 @@ where
#[tracing::instrument(err, skip(self, req))]
async fn post_typing(
&self,
- actor: MacroUserIdStr<'static>,
+ actor: Sender,
channel_id: Uuid,
req: PostTypingRequest,
) -> Result<(), ChannelMutationErr> {
@@ -745,7 +774,7 @@ where
.map_err(|e| ChannelMutationErr::Repo(e.into()))?;
self.events.dispatch(ChannelEvent::TypingChanged {
channel_id,
- user_id: actor.as_ref().to_string(),
+ actor,
action: req.action,
thread_id,
recipients: participant_ids(&participants),
@@ -757,10 +786,11 @@ where
#[tracing::instrument(err, skip(self, req))]
async fn add_participants(
&self,
- actor: MacroUserIdStr<'static>,
+ actor: Sender,
channel_id: Uuid,
req: AddParticipantsRequest,
) -> Result<(), ChannelMutationErr> {
+ let actor_user = require_user_actor(&actor)?;
let info = self
.repo
.get_channel_info(channel_id)
@@ -792,19 +822,15 @@ where
.collect();
let channel_metadata = self
.repo
- .get_channel_metadata(channel_id, actor.clone())
+ .get_channel_metadata(channel_id, actor_user.clone())
.await
.map_err(|e| ChannelMutationErr::Repo(e.into()))?;
- let active_participant_user_ids = parse_user_ids(
- active_participants
- .into_iter()
- .map(|participant| participant.user_id),
- )?;
+ let active_participant_user_ids = participant_ids(&active_participants);
self.events.dispatch(ChannelEvent::ParticipantsAdded {
channel_id,
channel_type: info.channel_type,
active_participant_user_ids,
- invited_by_user_id: actor.clone(),
+ invited_by: Sender::User(actor_user),
recipient_user_ids: recipients,
metadata: channel_metadata,
message_content: None,
@@ -816,6 +842,7 @@ where
#[tracing::instrument(err, skip(self, req))]
async fn remove_participants(
&self,
+ _actor: Sender,
channel_id: Uuid,
req: RemoveParticipantsRequest,
) -> Result<(), ChannelMutationErr> {
@@ -841,9 +868,10 @@ where
#[tracing::instrument(err, skip(self))]
async fn join_channel(
&self,
- actor: MacroUserIdStr<'static>,
+ actor: Sender,
channel_id: Uuid,
) -> Result<(), ChannelMutationErr> {
+ let actor_user = require_user_actor(&actor)?;
let info = self
.repo
.get_channel_info(channel_id)
@@ -862,22 +890,23 @@ where
self.repo
.add_participant(
channel_id,
- actor.as_ref().to_string(),
+ actor_user.as_ref().to_string(),
ParticipantRole::Member,
)
.await
.map_err(|e| ChannelMutationErr::Repo(e.into()))?;
- let active_participant_user_ids = parse_user_ids(
- before
- .into_iter()
- .map(|participant| participant.user_id)
- .chain(std::iter::once(actor.as_ref().to_string())),
- )?;
+ let mut active_participant_user_ids = participant_ids(&before);
+ if !active_participant_user_ids
+ .iter()
+ .any(|participant| participant == &actor_user)
+ {
+ active_participant_user_ids.push(actor_user.clone());
+ }
self.events.dispatch(ChannelEvent::ParticipantJoined {
channel_id,
channel_type: info.channel_type,
- user_id: actor,
+ user_id: Sender::User(actor_user),
active_participant_user_ids,
});
Ok(())
@@ -886,9 +915,10 @@ where
#[tracing::instrument(err, skip(self))]
async fn leave_channel(
&self,
- actor: MacroUserIdStr<'static>,
+ actor: Sender,
channel_id: Uuid,
) -> Result<(), ChannelMutationErr> {
+ let actor_user = require_user_actor(&actor)?;
let info = self
.repo
.get_channel_info(channel_id)
@@ -913,7 +943,7 @@ where
_ => {}
}
self.repo
- .remove_participant(channel_id, actor.as_ref().to_string())
+ .remove_participant(channel_id, actor_user.as_ref().to_string())
.await
.map_err(|e| ChannelMutationErr::Repo(e.into()))
}
@@ -954,11 +984,14 @@ where
let channel_type = create_req.channel_type;
let participant_user_ids =
created_channel_participant_ids(&owner_id, &create_req.participants)?;
+ let owner_sender = Sender::parse_storage_str(&owner_id)
+ .map_err(|err| ChannelMutationErr::BadRequest(format!("invalid owner id: {err}")))?;
let channel_id = self
.create_channel_record(owner_id, org_id, create_req)
.await?;
self.events.dispatch(ChannelEvent::ChannelCreated {
channel_id,
+ actor: owner_sender,
channel_type,
participant_user_ids,
});
@@ -970,7 +1003,7 @@ where
async fn patch_message_attachments(
&self,
- actor: MacroUserIdStr<'static>,
+ actor: Sender,
channel_id: Uuid,
message_id: Uuid,
attachment_ids_to_delete: Vec<String>,
@@ -1026,9 +1059,14 @@ where
let items = extract_share_items(&attachments_to_add, &[]);
if !items.is_empty()
+ && let Some(user_actor) = actor.as_user()
&& let Err(err) = self
.reference_share_permissions
- .update_channel_share_permissions_for_referenced_items(actor, channel_id, items)
+ .update_channel_share_permissions_for_referenced_items(
+ user_actor.clone(),
+ channel_id,
+ items,
+ )
.await
{
let err: anyhow::Error = err.into();
@@ -1052,6 +1090,7 @@ where
.map_err(|e| ChannelMutationErr::Repo(e.into()))?;
self.events.dispatch(ChannelEvent::AttachmentsChanged {
channel_id,
+ actor,
message_id,
attachments: all_attachments,
recipients: participant_ids(&participants),
@@ -1270,13 +1309,13 @@ where
#[tracing::instrument(err, skip(self))]
async fn post_activity(
&self,
- user_id: String,
+ actor: Sender,
channel_id: Uuid,
activity_type: ActivityType,
) -> Result<Activity, ChannelMutationErr> {
let activity = self
.repo
- .set_activity(user_id, channel_id, activity_type)
+ .set_activity(actor.to_storage_string(), channel_id, activity_type)
.await
.map_err(anyhow::Error::from)?;
@@ -1429,7 +1468,7 @@ where
async fn create_channel(
&self,
- actor: MacroUserIdStr<'static>,
+ actor: Sender,
actor_org_id: Option<i64>,
req: crate::domain::models::CreateChannelRequest,
) -> Result<crate::domain::models::CreateChannelResponse, ChannelMutationErr> {
@@ -1438,7 +1477,7 @@ where
async fn get_or_create_dm(
&self,
- actor: MacroUserIdStr<'static>,
+ actor: Sender,
req: GetOrCreateDmRequest,
) -> Result<GetOrCreateChannelResponse, ChannelMutationErr> {
ChannelServiceImpl::get_or_create_dm(self, actor, req).await
@@ -1446,7 +1485,7 @@ where
async fn get_or_create_private(
&self,
- actor: MacroUserIdStr<'static>,
+ actor: Sender,
req: GetOrCreatePrivateRequest,
) -> Result<GetOrCreateChannelResponse, ChannelMutationErr> {
ChannelServiceImpl::get_or_create_private(self, actor, req).await
@@ -1454,7 +1493,7 @@ where
async fn patch_channel(
&self,
- actor: MacroUserIdStr<'static>,
+ actor: Sender,
channel_id: Uuid,
req: PatchChannelRequest,
) -> Result<(), ChannelMutationErr> {
@@ -1463,7 +1502,7 @@ where
async fn delete_channel(
&self,
- actor: MacroUserIdStr<'static>,
+ actor: Sender,
channel_id: Uuid,
) -> Result<(), ChannelMutationErr> {
ChannelServiceImpl::delete_channel(self, actor, channel_id).await
@@ -1471,7 +1510,7 @@ where
async fn post_message(
&self,
- actor: MacroUserIdStr<'static>,
+ actor: Sender,
channel_id: Uuid,
req: PostMessageRequest,
) -> Result<PostMessageResponse, ChannelMutationErr> {
@@ -1480,7 +1519,7 @@ where
async fn patch_message(
&self,
- actor: MacroUserIdStr<'static>,
+ actor: Sender,
actor_role: ParticipantRole,
channel_id: Uuid,
message_id: Uuid,
@@ -1492,7 +1531,7 @@ where
async fn delete_message(
&self,
- actor: MacroUserIdStr<'static>,
+ actor: Sender,
actor_role: ParticipantRole,
channel_id: Uuid,
message_id: Uuid,
@@ -1504,7 +1543,7 @@ where
async fn post_reaction(
&self,
- actor: MacroUserIdStr<'static>,
+ actor: Sender,
channel_id: Uuid,
req: PostReactionRequest,
) -> Result<(), ChannelMutationErr> {
@@ -1513,7 +1552,7 @@ where
async fn post_typing(
&self,
- actor: MacroUserIdStr<'static>,
+ actor: Sender,
channel_id: Uuid,
req: PostTypingRequest,
) -> Result<(), ChannelMutationErr> {
@@ -1522,7 +1561,7 @@ where
async fn add_participants(
&self,
- actor: MacroUserIdStr<'static>,
+ actor: Sender,
channel_id: Uuid,
req: AddParticipantsRequest,
) -> Result<(), ChannelMutationErr> {
@@ -1531,15 +1570,16 @@ where
async fn remove_participants(
&self,
+ actor: Sender,
channel_id: Uuid,
req: RemoveParticipantsRequest,
) -> Result<(), ChannelMutationErr> {
- ChannelServiceImpl::remove_participants(self, channel_id, req).await
+ ChannelServiceImpl::remove_participants(self, actor, channel_id, req).await
}
async fn join_channel(
&self,
- actor: MacroUserIdStr<'static>,
+ actor: Sender,
channel_id: Uuid,
) -> Result<(), ChannelMutationErr> {
ChannelServiceImpl::join_channel(self, actor, channel_id).await
@@ -1547,7 +1587,7 @@ where
async fn leave_channel(
&self,
- actor: MacroUserIdStr<'static>,
+ actor: Sender,
channel_id: Uuid,
) -> Result<(), ChannelMutationErr> {
ChannelServiceImpl::leave_channel(self, actor, channel_id).await
diff --git a/rust/cloud-storage/channels/src/domain/service/test.rs b/rust/cloud-storage/channels/src/domain/service/test.rs
index 06eaa5e5b5..751bb5badd 100644
--- a/rust/cloud-storage/channels/src/domain/service/test.rs
+++ b/rust/cloud-storage/channels/src/domain/service/test.rs
@@ -2,13 +2,14 @@ use super::*;
use crate::domain::{
events::ChannelEvent,
models::{
- Activity, ActivityType, ChannelAttachment, ChannelAttachmentType, ChannelContextMessage,
- ChannelInfo, ChannelMessageFilters, ChannelMetadata, ChannelParticipant, ChannelType,
- CountedReaction, CreateEntityMentionOptions, EntityMention, MessageAttachment,
- MessagePageDirection, MutatedAttachment, MutatedMessage, NewChannelAttachment,
- ParticipantRole, PatchChannelRequest, PatchMessageRequest, PostMessageRequest,
- PostReactionRequest, ReactionAction, ReferencedShareItem, ReferencedShareItemType,
- ResolvedChannelMessage, SimpleMention, ThreadData, ThreadReplyRow, TopLevelMessageRow,
+ Activity, ActivityType, BotId, ChannelAttachment, ChannelAttachmentType,
+ ChannelContextMessage, ChannelInfo, ChannelMessageFilters, ChannelMetadata,
+ ChannelParticipant, ChannelType, CountedReaction, CreateEntityMentionOptions,
+ EntityMention, MessageAttachment, MessagePageDirection, MutatedAttachment, MutatedMessage,
+ NewChannelAttachment, ParticipantRole, PatchChannelRequest, PatchMessageRequest,
+ PostMessageRequest, PostReactionRequest, ReactionAction, ReferencedShareItem,
+ ReferencedShareItemType, ResolvedChannelMessage, Sender, SimpleMention, ThreadData,
+ ThreadReplyRow, TopLevelMessageRow,
},
ports::{
ChannelEventDispatcher, ChannelReferenceSharePermissions, ChannelRepo, MockChannelRepo,
@@ -203,7 +204,7 @@ impl FakeMutationRepo {
id: Uuid::new_v4(),
channel_id,
thread_id: None,
- sender_id: MacroUserIdStr::try_from(sender.to_string()).unwrap(),
+ sender_id: Sender::parse_storage_str(sender).unwrap(),
content: "hello".to_string(),
created_at: now,
updated_at: now,
@@ -453,7 +454,7 @@ impl ChannelRepo for FakeMutationRepo {
) -> Result<MutatedMessage, Self::Err> {
let mut state = self.state.lock().unwrap();
state.message.channel_id = channel_id;
- state.message.sender_id = MacroUserIdStr::try_from(sender_id).unwrap();
+ state.message.sender_id = Sender::parse_storage_str(&sender_id).unwrap();
state.message.content = content;
state.message.thread_id = thread_id;
Ok(state.message.clone())
@@ -693,6 +694,10 @@ fn macro_id(user_id: &str) -> MacroUserIdStr<'static> {
MacroUserIdStr::try_from(user_id.to_string()).unwrap()
}
+fn sender(user_id: &str) -> Sender {
+ Sender::User(macro_id(user_id))
+}
+
#[tokio::test]
async fn post_message_emits_message_posted_event_and_updates_share_permissions() {
let channel_id = Uuid::new_v4();
@@ -703,7 +708,7 @@ async fn post_message_emits_message_posted_event_and_updates_share_permissions()
let res = svc
.post_message(
- macro_id("macro|[email protected]"),
+ sender("macro|[email protected]"),
channel_id,
PostMessageRequest {
content: "hello world".to_string(),
@@ -761,6 +766,52 @@ async fn post_message_emits_message_posted_event_and_updates_share_permissions()
)));
}
+#[tokio::test]
+async fn bot_post_message_persists_bot_sender_and_skips_user_only_effects() {
+ let channel_id = Uuid::new_v4();
+ let bot_id = BotId::from_uuid(Uuid::new_v4());
+ let actor = Sender::Bot(bot_id);
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ let events = FakeEvents::default();
+ let share = FakeReferenceSharing::default();
+ let svc = mutation_service(repo.clone(), events.clone(), share.clone());
+
+ svc.post_message(
+ actor.clone(),
+ channel_id,
+ PostMessageRequest {
+ content: "bot update".to_string(),
+ mentions: vec![SimpleMention {
+ entity_type: "document".to_string(),
+ entity_id: "doc-1".to_string(),
+ }],
+ thread_id: None,
+ attachments: vec![NewChannelAttachment {
+ entity_type: "chat".to_string(),
+ entity_id: "chat-1".to_string(),
+ width: None,
+ height: None,
+ }],
+ nonce: None,
+ },
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(repo.state.lock().unwrap().message.sender_id.clone(), actor);
+ assert_eq!(repo.state.lock().unwrap().activity_upserts, 0);
+ assert!(share.items.lock().unwrap().is_empty());
+
+ let emitted = events.events.lock().unwrap();
+ let ChannelEvent::MessagePosted { message, .. } = &emitted[0] else {
+ panic!("expected MessagePosted event, got {:?}", emitted[0]);
+ };
+ assert_eq!(
+ message.sender_id.to_storage_string(),
+ bot_id.to_storage_string()
+ );
+}
+
#[tokio::test]
async fn patch_message_content_emits_message_changed_event_to_thread_participants() {
let channel_id = Uuid::new_v4();
@@ -776,7 +827,7 @@ async fn patch_message_content_emits_message_changed_event_to_thread_participant
);
svc.patch_message(
- macro_id("macro|[email protected]"),
+ sender("macro|[email protected]"),
ParticipantRole::Member,
channel_id,
message_id,
@@ -798,6 +849,7 @@ async fn patch_message_content_emits_message_changed_event_to_thread_participant
message,
recipients,
nonce,
+ ..
} = &emitted[0]
else {
panic!("expected MessageChanged event, got {:?}", emitted[0]);
@@ -819,7 +871,7 @@ async fn reaction_mutation_emits_grouped_reaction_event() {
let svc = mutation_service(repo, events.clone(), FakeReferenceSharing::default());
svc.post_reaction(
- macro_id("macro|[email protected]"),
+ sender("macro|[email protected]"),
channel_id,
PostReactionRequest {
emoji: "👍".to_string(),
diff --git a/rust/cloud-storage/channels/src/domain/side_effects.rs b/rust/cloud-storage/channels/src/domain/side_effects.rs
index e20baddb95..e17cbd65db 100644
--- a/rust/cloud-storage/channels/src/domain/side_effects.rs
+++ b/rust/cloud-storage/channels/src/domain/side_effects.rs
@@ -4,7 +4,7 @@ use crate::domain::{
events::ChannelEvent,
models::{
ChannelMetadata, ChannelParticipant, ChannelType, CountedReaction, MutatedAttachment,
- MutatedMessage, SimpleMention, TypingAction,
+ MutatedMessage, Sender, SimpleMention, TypingAction,
},
ports::{
ChannelContactsDispatcher, ChannelEventDispatcher, ChannelEventHandler,
@@ -276,7 +276,7 @@ where
match event {
ChannelEvent::ChannelCreated { .. } => {}
- ChannelEvent::ChannelDeleted { channel_id } => {
+ ChannelEvent::ChannelDeleted { channel_id, .. } => {
self.search.remove_message(channel_id, None).await;
}
ChannelEvent::MessagePosted {
@@ -307,6 +307,7 @@ where
attachments,
recipients,
nonce,
+ ..
} => {
self.publish_realtime(ChannelRealtimeEffect::Attachments {
recipients,
@@ -323,6 +324,7 @@ where
message,
recipients,
nonce,
+ ..
} => {
let message_id = message.id;
self.publish_realtime(ChannelRealtimeEffect::Message {
@@ -338,6 +340,7 @@ where
message,
recipients,
nonce,
+ ..
} => {
let message_id = message.id;
self.publish_realtime(ChannelRealtimeEffect::Message {
@@ -356,6 +359,7 @@ where
reactions,
recipients,
nonce,
+ ..
} => {
self.publish_realtime(ChannelRealtimeEffect::Reaction {
recipients,
@@ -368,7 +372,7 @@ where
}
ChannelEvent::TypingChanged {
channel_id,
- user_id,
+ actor,
action,
thread_id,
recipients,
@@ -377,7 +381,7 @@ where
self.publish_realtime(ChannelRealtimeEffect::Typing {
recipients,
channel_id,
- user_id,
+ user_id: actor.to_storage_string(),
action,
thread_id,
nonce,
@@ -386,20 +390,22 @@ where
}
ChannelEvent::ParticipantsAdded {
channel_id,
- invited_by_user_id,
+ invited_by,
recipient_user_ids,
metadata,
message_content,
..
} => {
- self.send_participants_added_notification(
- channel_id,
- invited_by_user_id,
- recipient_user_ids,
- metadata,
- message_content,
- )
- .await;
+ if let Some(invited_by_user_id) = invited_by.as_user().cloned() {
+ self.send_participants_added_notification(
+ channel_id,
+ invited_by_user_id,
+ recipient_user_ids,
+ metadata,
+ message_content,
+ )
+ .await;
+ }
}
ChannelEvent::ParticipantJoined { .. } => {}
}
@@ -452,6 +458,9 @@ where
}
self.search.index_message(channel_id, message.id).await;
+ if message.sender_id.is_bot() {
+ return;
+ }
self.send_message_posted_notifications(
channel_id,
metadata,
@@ -486,8 +495,18 @@ where
mentions: Vec<SimpleMention>,
has_attachments: bool,
) {
+ let Some(sender_id) = message.sender_id.as_user().cloned() else {
+ return;
+ };
let context = match self
- .build_posted_message_context(channel_id, metadata, &participants, &message, mentions)
+ .build_posted_message_context(
+ channel_id,
+ metadata,
+ &participants,
+ &message,
+ sender_id,
+ mentions,
+ )
.await
{
Ok(context) => context,
@@ -526,6 +545,7 @@ where
metadata: ChannelMetadata,
participants: &[ChannelParticipant],
message: &MutatedMessage,
+ sender_id: MacroUserIdStr<'static>,
mentions: Vec<SimpleMention>,
) -> anyhow::Result<PostedMessageNotificationContext> {
let message_count = self
@@ -565,17 +585,17 @@ where
.await;
let sender_profile_picture_url = self
.context
- .get_sender_profile_picture_url(message.sender_id.clone())
+ .get_sender_profile_picture_url(sender_id.clone())
.await;
- let excluded_user_ids = std::iter::once(message.sender_id.as_ref().to_string())
+ let excluded_user_ids = std::iter::once(sender_id.as_ref().to_string())
.chain(user_mentions.iter().cloned())
.collect::<Vec<_>>();
let recipients_without_sender = recipients_excluding(
participants
.iter()
.map(|participant| participant.user_id.as_str()),
- std::iter::once(message.sender_id.as_ref()),
+ std::iter::once(sender_id.as_ref()),
)
.collect();
let recipients_without_sender_and_mentions = recipients_excluding(
@@ -588,6 +608,7 @@ where
Ok(PostedMessageNotificationContext {
metadata,
+ sender_id,
sender_profile_picture_url,
user_mentions,
document_mentions,
@@ -656,11 +677,11 @@ where
thread_id: message.thread_id,
metadata: context.metadata.clone(),
sender_profile_picture_url: context.sender_profile_picture_url.clone(),
- sender_id: message.sender_id.clone(),
+ sender_id: context.sender_id.clone(),
},
recipient_ids: recipients_excluding(
context.user_mentions.iter().map(String::as_str),
- std::iter::once(message.sender_id.as_ref()),
+ std::iter::once(context.sender_id.as_ref()),
)
.collect(),
})
@@ -688,7 +709,7 @@ where
thread_id: message.thread_id,
metadata: context.metadata.clone(),
sender_profile_picture_url: context.sender_profile_picture_url.clone(),
- sender_id: message.sender_id.clone(),
+ sender_id: context.sender_id.clone(),
},
document: document.clone(),
recipient_ids: context.recipients_without_sender.clone(),
@@ -714,7 +735,7 @@ where
channel_id,
thread_id,
message_id: message.id,
- sender_id: message.sender_id.clone(),
+ sender_id: context.sender_id.clone(),
message_content: message.content.clone(),
has_attachments,
thread_parent_sender_id: context.thread_context.parent_sender_id.clone(),
@@ -741,7 +762,7 @@ where
) {
self.send_invite_notification(InviteNotificationRequest {
channel_id,
- invited_by_user_id: message.sender_id.clone(),
+ invited_by_user_id: context.sender_id.clone(),
recipient_user_ids: context
.recipients_without_sender_and_mentions
.into_iter()
@@ -764,7 +785,7 @@ where
self.send_notification(ChannelNotificationEffect::ChannelMessage {
channel_id,
message_id: message.id,
- sender_id: message.sender_id.clone(),
+ sender_id: context.sender_id.clone(),
message_content: message.content.clone(),
has_attachments,
metadata: context.metadata.clone(),
@@ -841,6 +862,7 @@ where
struct PostedMessageNotificationContext {
metadata: ChannelMetadata,
+ sender_id: MacroUserIdStr<'static>,
sender_profile_picture_url: Option<String>,
user_mentions: Vec<String>,
document_mentions: Vec<ChannelDocumentMention>,
@@ -876,16 +898,19 @@ fn contact_sync_users_for_event(event: &ChannelEvent) -> Option<HashSet<MacroUse
match event {
ChannelEvent::ChannelCreated {
channel_type: ChannelType::Private | ChannelType::DirectMessage,
+ actor: Sender::User(_),
participant_user_ids,
..
} => Some(participant_user_ids.iter().cloned().collect()),
ChannelEvent::ParticipantsAdded {
channel_type: ChannelType::Private | ChannelType::Team,
+ invited_by: Sender::User(_),
active_participant_user_ids,
..
} => Some(active_participant_user_ids.iter().cloned().collect()),
ChannelEvent::ParticipantJoined {
channel_type: ChannelType::Public | ChannelType::Private | ChannelType::Team,
+ user_id: Sender::User(_),
active_participant_user_ids,
..
} if active_participant_user_ids.len() > 1 => {
@@ -899,7 +924,7 @@ fn contact_sync_users_for_event(event: &ChannelEvent) -> Option<HashSet<MacroUse
mod tests {
use super::*;
use crate::domain::{
- models::ParticipantRole,
+ models::{BotId, ParticipantRole, Sender},
ports::{
ChannelEventHandler, ChannelNotificationSender, ChannelRealtimePublisher,
ChannelSearchIndexer, ChannelSideEffectContext,
@@ -1074,7 +1099,7 @@ mod tests {
id: message_id,
channel_id,
thread_id: None,
- sender_id: sender.clone(),
+ sender_id: Sender::User(sender.clone()),
content: "hello".to_string(),
created_at: now,
updated_at: now,
@@ -1125,6 +1150,66 @@ mod tests {
assert!(recipient_ids.contains(&recipient));
}
+ #[tokio::test]
+ async fn bot_message_posted_keeps_realtime_and_search_but_skips_notifications() {
+ let channel_id = Uuid::new_v4();
+ let message_id = Uuid::new_v4();
+ let recipient = user("[email protected]");
+ let realtime = FakeRealtime::default();
+ let notifications = FakeNotifications::default();
+ let search = FakeSearch::default();
+ let service = ChannelSideEffectService::new(
+ FakeContext {
+ message_count: 2,
+ document_mentions: Vec::new(),
+ },
+ realtime.clone(),
+ notifications.clone(),
+ search.clone(),
+ FakeContacts::default(),
+ );
+ let now = Utc::now();
+
+ service
+ .handle(ChannelEvent::MessagePosted {
+ channel_id,
+ metadata: ChannelMetadata {
+ channel_type: ChannelType::Private,
+ channel_name: "Project".to_string(),
+ },
+ participants: vec![ChannelParticipant {
+ channel_id,
+ user_id: recipient.as_ref().to_string(),
+ role: ParticipantRole::Member,
+ joined_at: now,
+ left_at: None,
+ }],
+ message: MutatedMessage {
+ id: message_id,
+ channel_id,
+ thread_id: None,
+ sender_id: Sender::Bot(BotId::from_uuid(Uuid::new_v4())),
+ content: "hello".to_string(),
+ created_at: now,
+ updated_at: now,
+ edited_at: None,
+ deleted_at: None,
+ },
+ mentions: Vec::new(),
+ has_attachments: false,
+ attachments: Vec::new(),
+ nonce: None,
+ })
+ .await;
+
+ assert_eq!(realtime.effects.lock().unwrap().len(), 1);
+ assert_eq!(
+ *search.indexed.lock().unwrap(),
+ vec![(channel_id, message_id)]
+ );
+ assert!(notifications.effects.lock().unwrap().is_empty());
+ }
+
#[tokio::test]
async fn document_mentions_notify_participants_except_sender() {
let channel_id = Uuid::new_v4();
@@ -1184,7 +1269,7 @@ mod tests {
id: message_id,
channel_id,
thread_id: None,
- sender_id: sender.clone(),
+ sender_id: Sender::User(sender.clone()),
content: "hello".to_string(),
created_at: now,
updated_at: now,
@@ -1226,6 +1311,7 @@ mod tests {
fn contact_sync_is_derived_from_private_channel_created() {
let event = ChannelEvent::ChannelCreated {
channel_id: Uuid::nil(),
+ actor: Sender::User(user("[email protected]")),
channel_type: ChannelType::Private,
participant_user_ids: users(&["[email protected]", "[email protected]"]),
};
@@ -1241,6 +1327,7 @@ mod tests {
fn contact_sync_ignores_public_channel_created() {
let event = ChannelEvent::ChannelCreated {
channel_id: Uuid::nil(),
+ actor: Sender::User(user("[email protected]")),
channel_type: ChannelType::Public,
participant_user_ids: users(&["[email protected]", "[email protected]"]),
};
@@ -1248,13 +1335,31 @@ mod tests {
assert!(contact_sync_users_for_event(&event).is_none());
}
+ #[test]
+ fn contact_sync_ignores_bot_actor() {
+ let event = ChannelEvent::ParticipantsAdded {
+ channel_id: Uuid::nil(),
+ channel_type: ChannelType::Team,
+ active_participant_user_ids: users(&["[email protected]", "[email protected]"]),
+ invited_by: Sender::Bot(BotId::from_uuid(Uuid::new_v4())),
+ recipient_user_ids: users(&["[email protected]"]),
+ metadata: ChannelMetadata {
+ channel_type: ChannelType::Team,
+ channel_name: "team".to_string(),
+ },
+ message_content: None,
+ };
+
+ assert!(contact_sync_users_for_event(&event).is_none());
+ }
+
#[test]
fn contact_sync_is_derived_from_team_participants_added() {
let event = ChannelEvent::ParticipantsAdded {
channel_id: Uuid::nil(),
channel_type: ChannelType::Team,
active_participant_user_ids: users(&["[email protected]", "[email protected]"]),
- invited_by_user_id: user("[email protected]"),
+ invited_by: Sender::User(user("[email protected]")),
recipient_user_ids: users(&["[email protected]"]),
metadata: ChannelMetadata {
channel_type: ChannelType::Team,
@@ -1271,7 +1376,7 @@ mod tests {
let event = ChannelEvent::ParticipantJoined {
channel_id: Uuid::nil(),
channel_type: ChannelType::Public,
- user_id: user("[email protected]"),
+ user_id: Sender::User(user("[email protected]")),
active_participant_user_ids: users(&["[email protected]"]),
};
diff --git a/rust/cloud-storage/channels/src/inbound/axum_router.rs b/rust/cloud-storage/channels/src/inbound/axum_router.rs
index 9d5202037e..d5bc45046b 100644
--- a/rust/cloud-storage/channels/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/channels/src/inbound/axum_router.rs
@@ -6,7 +6,7 @@ use crate::domain::models::{
AttachmentGenericReference, ChannelAttachment, ChannelAttachmentType, ChannelContextMessage,
ChannelMessage, ChannelMessageKind, ChannelParticipant, CountedReaction,
CreateEntityMentionOptions, MessageAttachment, MessagePageDirection, ParticipantRole,
- ResolvedChannelMessage, ThreadInfo, ThreadReply,
+ ResolvedChannelMessage, Sender, ThreadInfo, ThreadReply,
};
pub use crate::domain::models::{
AddParticipantsRequest, ChannelPreview, ChannelPreviewData, CreateChannelRequest,
@@ -33,8 +33,9 @@ use chrono::{DateTime, Utc};
use entity_access::{
domain::{
models::{
- AccessError, AccessLevel, AdminParticipantRole, EntityAccessReceipt, EntityPermission,
- EntityType, MemberParticipantRole, OwnerParticipantRole, RequiredPermission,
+ AccessError, AccessLevel, AdminParticipantRole, EntityAccessAuth, EntityAccessReceipt,
+ EntityPermission, EntityType, MemberParticipantRole, OwnerParticipantRole,
+ RequiredPermission,
},
ports::EntityAccessService,
},
@@ -105,10 +106,22 @@ fn notification_user_id_from_receipt<T: RequiredPermission>(
fn actor_from_receipt<T: RequiredPermission>(
receipt: &EntityAccessReceipt<T>,
-) -> Result<MacroUserIdStr<'static>, ChannelsHandlerErr> {
+) -> Result<Sender, ChannelsHandlerErr> {
+ match receipt.auth() {
+ EntityAccessAuth::Authenticated(user_id) => Ok(Sender::User(user_id.clone())),
+ EntityAccessAuth::Unauthenticated | EntityAccessAuth::Internal => Err(
+ ChannelsHandlerErr::BadRequest("authenticated actor required"),
+ ),
+ }
+}
+
+fn user_actor_from_receipt<T: RequiredPermission>(
+ receipt: &EntityAccessReceipt<T>,
+) -> Result<Sender, ChannelsHandlerErr> {
receipt
.get_authenticated_user()
.cloned()
+ .map(Sender::User)
.map_err(|_| ChannelsHandlerErr::BadRequest("authenticated user required"))
}
@@ -343,7 +356,7 @@ pub async fn create_channel_handler<S: ChannelService, Svc: EntityAccessService>
let res = state
.service
.create_channel(
- user.macro_user_id,
+ Sender::User(user.macro_user_id),
user.user_context.organization_id.map(i64::from),
req,
)
@@ -374,7 +387,7 @@ pub async fn get_or_create_dm_handler<S: ChannelService, Svc: EntityAccessServic
) -> Result<(StatusCode, Json<GetOrCreateChannelResponse>), ChannelsHandlerErr> {
let res = state
.service
- .get_or_create_dm(user.macro_user_id, req)
+ .get_or_create_dm(Sender::User(user.macro_user_id), req)
.await?;
Ok((StatusCode::OK, Json(res)))
}
@@ -402,7 +415,7 @@ pub async fn get_or_create_private_handler<S: ChannelService, Svc: EntityAccessS
) -> Result<(StatusCode, Json<GetOrCreateChannelResponse>), ChannelsHandlerErr> {
let res = state
.service
- .get_or_create_private(user.macro_user_id, req)
+ .get_or_create_private(Sender::User(user.macro_user_id), req)
.await?;
Ok((StatusCode::OK, Json(res)))
}
@@ -433,7 +446,7 @@ pub async fn patch_channel_handler<S: ChannelService, Svc: EntityAccessService>(
Json(req): Json<PatchChannelRequest>,
) -> Result<(StatusCode, String), ChannelsHandlerErr> {
let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
- let actor = actor_from_receipt(&access.entity_access_receipt)?;
+ let actor = user_actor_from_receipt(&access.entity_access_receipt)?;
state.service.patch_channel(actor, channel_id, req).await?;
Ok((StatusCode::OK, "patched channel".to_string()))
}
@@ -462,7 +475,7 @@ pub async fn delete_channel_handler<S: ChannelService, Svc: EntityAccessService>
access: ChannelAccessLevelExtractor<OwnerParticipantRole, Svc>,
) -> Result<(StatusCode, String), ChannelsHandlerErr> {
let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
- let actor = actor_from_receipt(&access.entity_access_receipt)?;
+ let actor = user_actor_from_receipt(&access.entity_access_receipt)?;
state.service.delete_channel(actor, channel_id).await?;
Ok((StatusCode::OK, "channel successfully deleted".to_string()))
}
@@ -658,7 +671,7 @@ pub async fn add_participants_handler<S: ChannelService, Svc: EntityAccessServic
Json(req): Json<AddParticipantsRequest>,
) -> Result<StatusCode, ChannelsHandlerErr> {
let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
- let actor = actor_from_receipt(&access.entity_access_receipt)?;
+ let actor = user_actor_from_receipt(&access.entity_access_receipt)?;
state
.service
.add_participants(actor, channel_id, req)
@@ -692,7 +705,11 @@ pub async fn remove_participants_handler<S: ChannelService, Svc: EntityAccessSer
Json(req): Json<RemoveParticipantsRequest>,
) -> Result<StatusCode, ChannelsHandlerErr> {
let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
- state.service.remove_participants(channel_id, req).await?;
+ let actor = user_actor_from_receipt(&access.entity_access_receipt)?;
+ state
+ .service
+ .remove_participants(actor, channel_id, req)
+ .await?;
Ok(StatusCode::OK)
}
@@ -722,7 +739,7 @@ pub async fn join_channel_handler<S: ChannelService, Svc: EntityAccessService>(
let channel_id = path.channel_id;
state
.service
- .join_channel(user.macro_user_id, channel_id)
+ .join_channel(Sender::User(user.macro_user_id), channel_id)
.await?;
Ok(StatusCode::OK)
}
@@ -751,7 +768,7 @@ pub async fn leave_channel_handler<S: ChannelService, Svc: EntityAccessService>(
access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
) -> Result<StatusCode, ChannelsHandlerErr> {
let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
- let actor = actor_from_receipt(&access.entity_access_receipt)?;
+ let actor = user_actor_from_receipt(&access.entity_access_receipt)?;
state.service.leave_channel(actor, channel_id).await?;
Ok(StatusCode::OK)
}
@@ -1428,7 +1445,7 @@ pub async fn post_activity_handler<S: ChannelService, Svc: EntityAccessService>(
let activity = state
.service
.post_activity(
- user.macro_user_id.to_string(),
+ Sender::User(user.macro_user_id),
channel_id,
req.activity_type,
)
@@ -1489,6 +1506,45 @@ pub struct ApiChannelMessagesPage {
previous_cursor: Option<String>,
}
+/// Public sender identity for channel messages.
+#[derive(Debug, Serialize, utoipa::ToSchema)]
+pub struct ApiMessageSender {
+ /// Sender type.
+ #[serde(rename = "type")]
+ sender_type: ApiMessageSenderType,
+ /// Sender id without the storage namespace prefix.
+ id: String,
+}
+
+/// Public sender type.
+#[derive(Debug, Serialize, utoipa::ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum ApiMessageSenderType {
+ /// Macro user sender.
+ User,
+ /// Bot sender.
+ Bot,
+}
+
+impl ApiMessageSender {
+ fn from_storage_string(sender_id: &str) -> Self {
+ match Sender::parse_storage_str(sender_id) {
+ Ok(Sender::Bot(bot_id)) => Self {
+ sender_type: ApiMessageSenderType::Bot,
+ id: bot_id.as_uuid().to_string(),
+ },
+ Ok(Sender::User(user_id)) => Self {
+ sender_type: ApiMessageSenderType::User,
+ id: user_id.to_string(),
+ },
+ Err(_) => Self {
+ sender_type: ApiMessageSenderType::User,
+ id: sender_id.to_string(),
+ },
+ }
+ }
+}
+
/// A top-level channel message with thread info.
#[derive(Debug, Serialize, utoipa::ToSchema)]
pub struct ApiChannelMessage {
@@ -1498,6 +1554,8 @@ pub struct ApiChannelMessage {
channel_id: Uuid,
/// Sender user id.
sender_id: String,
+ /// Structured sender identity.
+ sender: ApiMessageSender,
/// Message content.
content: String,
/// When the message was created.
@@ -1521,6 +1579,7 @@ impl From<ChannelMessage> for ApiChannelMessage {
Self {
id: m.id,
channel_id: m.channel_id,
+ sender: ApiMessageSender::from_storage_string(&m.sender_id),
sender_id: m.sender_id,
content: m.content,
created_at: m.created_at,
@@ -1560,6 +1619,8 @@ pub struct ApiChannelContextMessage {
thread_id: Option<Uuid>,
/// Sender user id.
sender_id: String,
+ /// Structured sender identity.
+ sender: ApiMessageSender,
/// Message content.
content: String,
/// When the message was created.
@@ -1578,6 +1639,7 @@ impl From<ChannelContextMessage> for ApiChannelContextMessage {
id: message.id,
channel_id: message.channel_id,
thread_id: message.thread_id,
+ sender: ApiMessageSender::from_storage_string(&message.sender_id),
sender_id: message.sender_id,
content: message.content,
created_at: message.created_at,
@@ -1712,6 +1774,8 @@ pub struct ApiThreadReply {
id: Uuid,
/// Sender user id.
sender_id: String,
+ /// Structured sender identity.
+ sender: ApiMessageSender,
/// Reply content.
content: String,
/// When the reply was created.
@@ -1730,6 +1794,7 @@ impl From<ThreadReply> for ApiThreadReply {
fn from(r: ThreadReply) -> Self {
Self {
id: r.id,
+ sender: ApiMessageSender::from_storage_string(&r.sender_id),
sender_id: r.sender_id,
content: r.content,
created_at: r.created_at,
diff --git a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs b/rust/cloud-storage/channels/src/inbound/axum_router/test.rs
index 0b0bed70bb..3780f3d772 100644
--- a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs
+++ b/rust/cloud-storage/channels/src/inbound/axum_router/test.rs
@@ -4,7 +4,7 @@ use crate::domain::models::{
ChannelMessageFilters, ChannelParticipant, DeleteMessageQuery, GetOrCreateChannelResponse,
GetOrCreateDmRequest, GetOrCreatePrivateRequest, MessagePageDirection, ParticipantRole,
PatchChannelRequest, PatchMessageRequest, PostMessageRequest, PostMessageResponse,
- PostReactionRequest, PostTypingRequest, RemoveParticipantsRequest,
+ PostReactionRequest, PostTypingRequest, RemoveParticipantsRequest, Sender,
};
use crate::domain::ports::{
ChannelAttachmentsPage, ChannelMessagesErr, ChannelMessagesQueryResult, ChannelMutationErr,
@@ -450,7 +450,7 @@ impl ChannelService for ParticipantsService {
#[derive(Clone, Default)]
struct RecordingMutationService {
- posts: Arc<Mutex<Vec<(MacroUserIdStr<'static>, Uuid, PostMessageRequest)>>>,
+ posts: Arc<Mutex<Vec<(Sender, Uuid, PostMessageRequest)>>>,
}
impl ChannelService for RecordingMutationService {
@@ -520,7 +520,7 @@ impl ChannelService for RecordingMutationService {
async fn create_channel(
&self,
- _actor: MacroUserIdStr<'static>,
+ _actor: Sender,
_actor_org_id: Option<i64>,
_req: CreateChannelRequest,
) -> Result<CreateChannelResponse, ChannelMutationErr> {
@@ -531,7 +531,7 @@ impl ChannelService for RecordingMutationService {
async fn get_or_create_dm(
&self,
- _actor: MacroUserIdStr<'static>,
+ _actor: Sender,
_req: GetOrCreateDmRequest,
) -> Result<GetOrCreateChannelResponse, ChannelMutationErr> {
Err(ChannelMutationErr::NotFound("unused".to_string()))
@@ -539,7 +539,7 @@ impl ChannelService for RecordingMutationService {
async fn get_or_create_private(
&self,
- _actor: MacroUserIdStr<'static>,
+ _actor: Sender,
_req: GetOrCreatePrivateRequest,
) -> Result<GetOrCreateChannelResponse, ChannelMutationErr> {
Err(ChannelMutationErr::NotFound("unused".to_string()))
@@ -547,7 +547,7 @@ impl ChannelService for RecordingMutationService {
async fn patch_channel(
&self,
- _actor: MacroUserIdStr<'static>,
+ _actor: Sender,
_channel_id: Uuid,
_req: PatchChannelRequest,
) -> Result<(), ChannelMutationErr> {
@@ -556,7 +556,7 @@ impl ChannelService for RecordingMutationService {
async fn delete_channel(
&self,
- _actor: MacroUserIdStr<'static>,
+ _actor: Sender,
_channel_id: Uuid,
) -> Result<(), ChannelMutationErr> {
Ok(())
@@ -564,7 +564,7 @@ impl ChannelService for RecordingMutationService {
async fn post_message(
&self,
- actor: MacroUserIdStr<'static>,
+ actor: Sender,
channel_id: Uuid,
req: PostMessageRequest,
) -> Result<PostMessageResponse, ChannelMutationErr> {
@@ -577,7 +577,7 @@ impl ChannelService for RecordingMutationService {
async fn patch_message(
&self,
- _actor: MacroUserIdStr<'static>,
+ _actor: Sender,
_actor_role: ParticipantRole,
_channel_id: Uuid,
_message_id: Uuid,
@@ -588,7 +588,7 @@ impl ChannelService for RecordingMutationService {
async fn delete_message(
&self,
- _actor: MacroUserIdStr<'static>,
+ _actor: Sender,
_actor_role: ParticipantRole,
_channel_id: Uuid,
_message_id: Uuid,
@@ -599,7 +599,7 @@ impl ChannelService for RecordingMutationService {
async fn post_reaction(
&self,
- _actor: MacroUserIdStr<'static>,
+ _actor: Sender,
_channel_id: Uuid,
_req: PostReactionRequest,
) -> Result<(), ChannelMutationErr> {
@@ -608,7 +608,7 @@ impl ChannelService for RecordingMutationService {
async fn post_typing(
&self,
- _actor: MacroUserIdStr<'static>,
+ _actor: Sender,
_channel_id: Uuid,
_req: PostTypingRequest,
) -> Result<(), ChannelMutationErr> {
@@ -617,7 +617,7 @@ impl ChannelService for RecordingMutationService {
async fn add_participants(
&self,
- _actor: MacroUserIdStr<'static>,
+ _actor: Sender,
_channel_id: Uuid,
_req: AddParticipantsRequest,
) -> Result<(), ChannelMutationErr> {
@@ -626,6 +626,7 @@ impl ChannelService for RecordingMutationService {
async fn remove_participants(
&self,
+ _actor: Sender,
_channel_id: Uuid,
_req: RemoveParticipantsRequest,
) -> Result<(), ChannelMutationErr> {
@@ -634,7 +635,7 @@ impl ChannelService for RecordingMutationService {
async fn join_channel(
&self,
- _actor: MacroUserIdStr<'static>,
+ _actor: Sender,
_channel_id: Uuid,
) -> Result<(), ChannelMutationErr> {
Ok(())
@@ -642,7 +643,7 @@ impl ChannelService for RecordingMutationService {
async fn leave_channel(
&self,
- _actor: MacroUserIdStr<'static>,
+ _actor: Sender,
_channel_id: Uuid,
) -> Result<(), ChannelMutationErr> {
Ok(())
@@ -733,7 +734,7 @@ async fn post_message_route_uses_entity_access_and_mutation_service() {
let posts = posts.lock().unwrap();
assert_eq!(posts.len(), 1);
- assert_eq!(posts[0].0.as_ref(), "macro|[email protected]");
+ assert_eq!(posts[0].0.to_storage_string(), "macro|[email protected]");
assert_eq!(posts[0].1, channel_id);
assert_eq!(posts[0].2.content, "hello");
}
@@ -1613,7 +1614,7 @@ async fn missing_channel_returns_404() {
#[derive(Default)]
struct ActivityService {
- posts: Arc<Mutex<Vec<(String, Uuid, ActivityType)>>>,
+ posts: Arc<Mutex<Vec<(Sender, Uuid, ActivityType)>>>,
}
impl ChannelService for ActivityService {
@@ -1704,17 +1705,17 @@ impl ChannelService for ActivityService {
async fn post_activity(
&self,
- user_id: String,
+ actor: Sender,
channel_id: Uuid,
activity_type: ActivityType,
) -> Result<Activity, ChannelMutationErr> {
self.posts
.lock()
.unwrap()
- .push((user_id.clone(), channel_id, activity_type));
+ .push((actor.clone(), channel_id, activity_type));
Ok(Activity {
id: Uuid::nil(),
- user_id,
+ user_id: actor.to_storage_string(),
channel_id,
created_at: chrono::Utc::now(),
updated_at: chrono::Utc::now(),
@@ -1775,7 +1776,7 @@ async fn post_activity_records_and_returns_activity() {
let posts = posts.lock().unwrap();
assert_eq!(posts.len(), 1);
- assert_eq!(posts[0].0, "macro|[email protected]");
+ assert_eq!(posts[0].0.to_storage_string(), "macro|[email protected]");
assert_eq!(posts[0].1, channel_id);
assert!(matches!(posts[0].2, ActivityType::View));
}
diff --git a/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs b/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs
index 2cf05fbb7f..c625947de7 100644
--- a/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs
+++ b/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs
@@ -9,8 +9,8 @@ use crate::domain::{
ChannelMetadata, ChannelParticipant, ChannelPreviewRow, ChannelType, CountedReaction,
CreateChannelRequest, CreateEntityMentionOptions, EntityMention, MessageAttachment,
MessagePageDirection, MutatedAttachment, MutatedMessage, NewChannelAttachment,
- ParticipantRole, PatchChannelRequest, ResolvedChannelMessage, SimpleMention, ThreadData,
- ThreadReplyRow, TopLevelMessageRow,
+ ParticipantRole, PatchChannelRequest, ResolvedChannelMessage, Sender, SimpleMention,
+ ThreadData, ThreadReplyRow, TopLevelMessageRow,
},
ports::{ChannelRepo, TopLevelMessagesQueryResult},
};
@@ -171,7 +171,7 @@ struct MutatedMessageRow {
id: Uuid,
channel_id: Uuid,
thread_id: Option<Uuid>,
- sender_id: MacroUserIdStr<'static>,
+ sender_id: String,
content: String,
created_at: chrono::DateTime<chrono::Utc>,
updated_at: chrono::DateTime<chrono::Utc>,
@@ -228,12 +228,12 @@ struct UserIdRow {
#[derive(Debug, sqlx::FromRow)]
struct MacroUserIdRow {
- user_id: MacroUserIdStr<'static>,
+ user_id: String,
}
#[derive(Debug, sqlx::FromRow)]
struct SenderIdRow {
- sender_id: MacroUserIdStr<'static>,
+ sender_id: String,
}
#[derive(Debug, sqlx::FromRow)]
@@ -246,20 +246,20 @@ struct ExistsRow {
exists: bool,
}
-impl From<MutatedMessageRow> for MutatedMessage {
- fn from(row: MutatedMessageRow) -> Self {
- Self {
- id: row.id,
- channel_id: row.channel_id,
- thread_id: row.thread_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,
- }
- }
+fn mutated_message_from_row(row: MutatedMessageRow) -> anyhow::Result<MutatedMessage> {
+ let sender_id = Sender::parse_storage_str(&row.sender_id)
+ .with_context(|| format!("invalid message sender_id {}", row.sender_id))?;
+ Ok(MutatedMessage {
+ id: row.id,
+ channel_id: row.channel_id,
+ thread_id: row.thread_id,
+ 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,
+ })
}
impl From<MutatedAttachmentRow> for MutatedAttachment {
@@ -415,7 +415,7 @@ async fn get_message_owner(
let row = sqlx::query_as!(
SenderIdRow,
r#"
- SELECT sender_id AS "sender_id: MacroUserIdStr"
+ SELECT sender_id
FROM comms_messages
WHERE id = $1 AND channel_id = $2
ORDER BY created_at ASC
@@ -436,7 +436,7 @@ async fn get_channel_participants_for_thread_id(
let rows = sqlx::query_as!(
MacroUserIdRow,
r#"
- SELECT DISTINCT id AS "user_id!: MacroUserIdStr" FROM (
+ SELECT DISTINCT id AS "user_id!" FROM (
SELECT m.sender_id AS id
FROM comms_channel_participants cp
JOIN comms_channels c ON c.id = cp.channel_id
@@ -458,7 +458,10 @@ async fn get_channel_participants_for_thread_id(
)
.fetch_all(pool)
.await?;
- Ok(rows.into_iter().map(|row| row.user_id).collect())
+ Ok(rows
+ .into_iter()
+ .filter_map(|row| MacroUserIdStr::try_from(row.user_id).ok())
+ .collect())
}
fn static_channel_name(
@@ -1134,12 +1137,15 @@ impl ChannelRepo for PgChannelsRepo {
Ok(rows
.into_iter()
- .map(|row| ChannelParticipant {
- channel_id: row.channel_id,
- user_id: row.user_id,
- role: row.role,
- joined_at: row.joined_at,
- left_at: row.left_at,
+ .filter_map(|row| {
+ let user_id = MacroUserIdStr::try_from(row.user_id).ok()?;
+ Some(ChannelParticipant {
+ channel_id: row.channel_id,
+ user_id: user_id.as_ref().to_string(),
+ role: row.role,
+ joined_at: row.joined_at,
+ left_at: row.left_at,
+ })
})
.collect())
}
@@ -1257,7 +1263,7 @@ impl ChannelRepo for PgChannelsRepo {
let attachment_references = sqlx::query_as!(
AttachmentChannelReference,
r#"
- SELECT
+ SELECT
a.channel_id AS "channel_id: uuid::Uuid",
c.name AS "channel_name?", -- Option<String>
a.message_id AS "message_id: uuid::Uuid",
@@ -1288,7 +1294,7 @@ impl ChannelRepo for PgChannelsRepo {
let mention_references = sqlx::query_as!(
AttachmentChannelReference,
r#"
- SELECT
+ SELECT
m.channel_id AS "channel_id: uuid::Uuid",
c.name AS "channel_name?", -- Option<String>
m.id AS "message_id: uuid::Uuid",
@@ -1318,7 +1324,7 @@ impl ChannelRepo for PgChannelsRepo {
let generic_references = sqlx::query!(
r#"
- SELECT
+ SELECT
em.source_entity_type,
em.source_entity_id,
em.entity_type,
@@ -1921,7 +1927,7 @@ impl ChannelRepo for PgChannelsRepo {
RETURNING
id,
channel_id,
- sender_id AS "sender_id: MacroUserIdStr",
+ sender_id,
content,
created_at,
updated_at,
@@ -1938,7 +1944,7 @@ impl ChannelRepo for PgChannelsRepo {
.fetch_one(&self.pool)
.await
.context("unable to create message")?;
- Ok(row.into())
+ mutated_message_from_row(row)
}
async fn touch_channel_updated_at(&self, channel_id: Uuid) -> Result<(), Self::Err> {
@@ -2156,7 +2162,7 @@ impl ChannelRepo for PgChannelsRepo {
RETURNING
id,
channel_id,
- sender_id AS "sender_id: MacroUserIdStr",
+ sender_id,
content,
created_at,
updated_at,
@@ -2170,7 +2176,7 @@ impl ChannelRepo for PgChannelsRepo {
.fetch_one(&self.pool)
.await
.context("unable to update message")?;
- Ok(row.into())
+ mutated_message_from_row(row)
}
async fn patch_message(
@@ -2188,7 +2194,7 @@ impl ChannelRepo for PgChannelsRepo {
RETURNING
id,
channel_id,
- sender_id AS "sender_id: MacroUserIdStr",
+ sender_id,
content,
created_at,
updated_at,
@@ -2203,7 +2209,7 @@ impl ChannelRepo for PgChannelsRepo {
.fetch_one(&self.pool)
.await
.context("unable to update message")?;
- Ok(row.into())
+ mutated_message_from_row(row)
}
async fn delete_message(
&self,
@@ -2219,7 +2225,7 @@ impl ChannelRepo for PgChannelsRepo {
RETURNING
id,
channel_id,
- sender_id AS "sender_id: MacroUserIdStr",
+ sender_id,
content,
created_at,
updated_at,
@@ -2233,7 +2239,7 @@ impl ChannelRepo for PgChannelsRepo {
.fetch_one(&self.pool)
.await
.context("unable to delete message")?;
- Ok(row.into())
+ mutated_message_from_row(row)
}
async fn get_message_owner(
@@ -2268,12 +2274,18 @@ impl ChannelRepo for PgChannelsRepo {
Ok(rows
.into_iter()
- .map(|row| ChannelParticipant {
- channel_id: row.channel_id,
- user_id: row.user_id,
- role: row.role,
- joined_at: row.joined_at,
- left_at: row.left_at,
+ .filter_map(|row| {
+ if row.left_at.is_some() {
+ return None;
+ }
+ let user_id = MacroUserIdStr::try_from(row.user_id).ok()?;
+ Some(ChannelParticipant {
+ channel_id: row.channel_id,
+ user_id: user_id.as_ref().to_string(),
+ role: row.role,
+ joined_at: row.joined_at,
+ left_at: row.left_at,
+ })
})
.collect())
}
@@ -2305,7 +2317,7 @@ impl ChannelRepo for PgChannelsRepo {
async fn get_activities(&self, user_id: String) -> Result<Vec<Activity>, Self::Err> {
let activities = sqlx::query!(
r#"
- SELECT
+ SELECT
a.id as "id!: Uuid",
a.user_id as "user_id!: String",
a.channel_id as "channel_id!: Uuid",
@@ -2315,7 +2327,7 @@ impl ChannelRepo for PgChannelsRepo {
a.updated_at as "updated_at!: DateTime<Utc>"
FROM comms_activity a
WHERE a.user_id = $1
- ORDER BY
+ ORDER BY
GREATEST(
COALESCE(a.viewed_at, '1970-01-01'::timestamp),
COALESCE(a.interacted_at, '1970-01-01'::timestamp)
@@ -2359,11 +2371,11 @@ impl ChannelRepo for PgChannelsRepo {
VALUES (
$1, $2, $3, NOW()
)
- ON CONFLICT (user_id, channel_id) DO UPDATE
- SET
+ ON CONFLICT (user_id, channel_id) DO UPDATE
+ SET
viewed_at = NOW(),
updated_at = NOW()
- RETURNING
+ RETURNING
id as "id!: Uuid",
user_id as "user_id!: String",
channel_id as "channel_id!: Uuid",
@@ -2392,11 +2404,11 @@ impl ChannelRepo for PgChannelsRepo {
VALUES (
$1, $2, $3, NOW()
)
- ON CONFLICT (user_id, channel_id) DO UPDATE
- SET
+ ON CONFLICT (user_id, channel_id) DO UPDATE
+ SET
interacted_at = NOW(),
updated_at = NOW()
- RETURNING
+ RETURNING
id as "id!: Uuid",
user_id as "user_id!: String",
channel_id as "channel_id!: Uuid",
diff --git a/rust/cloud-storage/channels/src/outbound/pg_side_effect_context.rs b/rust/cloud-storage/channels/src/outbound/pg_side_effect_context.rs
index 5f175f0936..d7f2428893 100644
--- a/rust/cloud-storage/channels/src/outbound/pg_side_effect_context.rs
+++ b/rust/cloud-storage/channels/src/outbound/pg_side_effect_context.rs
@@ -11,11 +11,11 @@ use std::collections::HashSet;
use uuid::Uuid;
struct SenderIdRow {
- sender_id: MacroUserIdStr<'static>,
+ sender_id: String,
}
struct UserIdRow {
- user_id: MacroUserIdStr<'static>,
+ user_id: String,
}
struct DocumentMentionRow {
@@ -161,7 +161,7 @@ async fn get_message_owner(pool: &PgPool, message_id: Uuid) -> anyhow::Result<St
let row = sqlx::query_as!(
SenderIdRow,
r#"
- SELECT sender_id AS "sender_id: MacroUserIdStr"
+ SELECT sender_id
FROM comms_messages
WHERE id = $1
ORDER BY created_at ASC
@@ -171,7 +171,7 @@ async fn get_message_owner(pool: &PgPool, message_id: Uuid) -> anyhow::Result<St
.fetch_one(pool)
.await
.context("unable to get message owner")?;
- Ok(row.sender_id.to_string())
+ Ok(row.sender_id)
}
async fn get_channel_message_count(pool: &PgPool, channel_id: Uuid) -> anyhow::Result<i64> {
@@ -195,7 +195,7 @@ async fn get_channel_participants_for_thread_id(
let rows = sqlx::query_as!(
UserIdRow,
r#"
- SELECT DISTINCT id AS "user_id!: MacroUserIdStr" FROM (
+ SELECT DISTINCT id AS "user_id!" FROM (
SELECT m.sender_id AS id
FROM comms_channel_participants cp
JOIN comms_channels c ON c.id = cp.channel_id
@@ -217,5 +217,8 @@ async fn get_channel_participants_for_thread_id(
)
.fetch_all(pool)
.await?;
- Ok(rows.into_iter().map(|row| row.user_id).collect())
+ Ok(rows
+ .into_iter()
+ .filter_map(|row| MacroUserIdStr::try_from(row.user_id).ok())
+ .collect())
}
diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.toml
index 4ac1934e54..808876168e 100644
--- a/rust/cloud-storage/document_storage_service/Cargo.toml
+++ b/rust/cloud-storage/document_storage_service/Cargo.toml
@@ -30,6 +30,7 @@ aws-sdk-sqs = { workspace = true }
axum = { workspace = true, features = ["macros", "multipart", "tower-log"] }
axum-extra = { workspace = true }
base64 = { workspace = true }
+bots = { path = "../bots" }
bytes = { workspace = true }
bzip2 = { workspace = true, default-features = false, features = [
"libbz2-rs-sys",
diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rs
index 083e704092..9f8e8daca6 100644
--- a/rust/cloud-storage/document_storage_service/src/api/context.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs
@@ -3,6 +3,10 @@ use contacts::outbound::ingress::SqsContactsQueue;
use crate::{config::Config, service::s3::S3};
use axum::extract::FromRef;
+use bots::{
+ domain::service::BotServiceImpl, inbound::axum_router::BotsRouterState,
+ outbound::pg_bots_repo::PgBotsRepo,
+};
use cal::{
domain::service::CalWebhookServiceImpl, inbound::cal_webhook_router::CalWebhookRouterState,
outbound::analytics_client::AnalyticsClientSink,
@@ -229,6 +233,12 @@ pub(crate) type DssChannelService = ChannelServiceImpl<
/// Type alias for the channels router state.
pub(crate) type DssChannelsState = ChannelsRouterState<DssChannelService, EntityAccessService>;
+/// Type alias for the bots service wired into DSS.
+pub(crate) type DssBotService = BotServiceImpl<PgBotsRepo>;
+
+/// Type alias for the bots router state.
+pub(crate) type DssBotsState = BotsRouterState<DssBotService, EntityAccessService>;
+
/// Type alias for the call connection service.
pub(crate) type CallConnectionService =
ConnectionServiceImpl<EntityAccessService, ConnectionGatewayImpl>;
@@ -315,6 +325,7 @@ pub(crate) struct ApiContext {
pub entity_access_service: Arc<EntityAccessService>,
pub documents_state: DocumentsState,
pub channels_state: DssChannelsState,
+ pub bots_state: DssBotsState,
pub call_state: DssCallState,
pub call_webhook_state: DssCallWebhookState,
pub call_internal_state: DssCallInternalState,
diff --git a/rust/cloud-storage/document_storage_service/src/api/mod.rs b/rust/cloud-storage/document_storage_service/src/api/mod.rs
index eb58d73502..7e72470081 100644
--- a/rust/cloud-storage/document_storage_service/src/api/mod.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/mod.rs
@@ -211,6 +211,9 @@ fn api_router(state: ApiContext) -> Router {
"/channels",
channels::inbound::axum_router::channels_router(state.channels_state.clone()),
)
+ .merge(bots::inbound::axum_router::bots_router(
+ state.bots_state.clone(),
+ ))
.nest(
"/foreign_entity",
foreign_entity::inbound::axum_router::foreign_entity_router(
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index 88450cc1eb..40d58a994d 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -569,6 +569,9 @@ async fn main() -> anyhow::Result<()> {
let sqs_client = Arc::new(sqs_client);
let conn_gateway_client = Arc::new(conn_gateway_client);
let channels_repo = PgChannelsRepo::new(db.clone());
+ let bots_service = bots::domain::service::BotServiceImpl::new(
+ bots::outbound::pg_bots_repo::PgBotsRepo::new(db.clone()),
+ );
let channels_service = ChannelServiceImpl::with_dependencies(
channels_repo,
@@ -634,6 +637,10 @@ async fn main() -> anyhow::Result<()> {
channels_service,
(*entity_access_service).clone(),
),
+ bots_state: bots::inbound::axum_router::BotsRouterState::new(
+ bots_service.clone(),
+ (*entity_access_service).clone(),
+ ),
call_state,
call_webhook_state,
call_internal_state,
diff --git a/rust/cloud-storage/entity_access/src/domain/service.rs b/rust/cloud-storage/entity_access/src/domain/service.rs
index 2490f2a97f..0d5bf8df50 100644
--- a/rust/cloud-storage/entity_access/src/domain/service.rs
+++ b/rust/cloud-storage/entity_access/src/domain/service.rs
@@ -240,15 +240,11 @@ where
let channel_uuid = Uuid::from_str(entity_id)
.map_err(|_| AccessError::BadRequest("Invalid channel ID format"))?;
- match self
+ let result = self
.repo
.get_channel_role(&channel_uuid, user_id, user_org_id)
- .await?
- {
- ChannelRoleResult::Role(role) => Ok(EntityPermission::ChannelRole { role }),
- ChannelRoleResult::NoAccess => Err(AccessError::Unauthorized),
- ChannelRoleResult::NotFound => Err(AccessError::NotFound("Channel not found")),
- }
+ .await?;
+ channel_role_result_to_permission(result)
}
_ => Err(AccessError::BadRequest("Unsupported entity type")),
}
@@ -313,5 +309,15 @@ where
}
}
+fn channel_role_result_to_permission(
+ result: ChannelRoleResult,
+) -> Result<EntityPermission, AccessError> {
+ match result {
+ ChannelRoleResult::Role(role) => Ok(EntityPermission::ChannelRole { role }),
+ ChannelRoleResult::NoAccess => Err(AccessError::Unauthorized),
+ ChannelRoleResult::NotFound => Err(AccessError::NotFound("Channel not found")),
+ }
+}
+
#[cfg(test)]
mod test;
diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/channel_role.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/channel_role.rs
index d4d58563e8..ac7ca7753d 100644
--- a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/channel_role.rs
+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/channel_role.rs
@@ -5,7 +5,6 @@ use sqlx::PgPool;
use uuid::Uuid;
/// Row returned from the channel role query.
-#[derive(sqlx::FromRow)]
struct ChannelRoleRow {
role: Option<String>,
channel_type: String,
@@ -40,20 +39,21 @@ pub async fn get_channel_role(
user_id: &str,
user_org_id: Option<i64>,
) -> Result<ChannelRoleResult, sqlx::Error> {
- let row = sqlx::query_as::<_, ChannelRoleRow>(
+ let row = sqlx::query_as!(
+ ChannelRoleRow,
r#"
SELECT
- cp.role::text as role,
- c.channel_type::text as channel_type,
- c.org_id
+ cp.role::text as "role?",
+ c.channel_type::text as "channel_type!",
+ c.org_id as "org_id?"
FROM comms_channels c
LEFT JOIN comms_channel_participants cp
ON cp.channel_id = c.id AND cp.user_id = $2 AND cp.left_at IS NULL
WHERE c.id = $1
"#,
+ channel_id,
+ user_id,
)
- .bind(channel_id)
- .bind(user_id)
.fetch_optional(pool)
.await?;
diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfile
index 9f7fe67a03..daa2e97d65 100644
--- a/rust/cloud-storage/justfile
+++ b/rust/cloud-storage/justfile
@@ -101,6 +101,7 @@ setup_test_envs:
echo "DATABASE_URL={{ DATABASE_URL }}" >> ./mcp_client/.env
echo "DATABASE_URL={{ DATABASE_URL }}" >> ./document_storage_service/.env
echo "DATABASE_URL={{ DATABASE_URL }}" >> ./crm/.env
+ echo "DATABASE_URL={{ DATABASE_URL }}" >> ./bots/.env
setup_macrodb:
just macro_db_client/create_db
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260527160000_channel_bots.sql b/rust/cloud-storage/macro_db_client/migrations/20260527160000_channel_bots.sql
new file mode 100644
index 0000000000..12990c9383
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260527160000_channel_bots.sql
@@ -0,0 +1,51 @@
+CREATE TABLE public.bots (
+ id uuid PRIMARY KEY,
+ kind text NOT NULL CHECK (kind IN ('owned', 'system')),
+ owner_user_id text,
+ team_id uuid REFERENCES public.team(id) ON DELETE CASCADE,
+ name text NOT NULL,
+ handle text NOT NULL,
+ description text,
+ avatar_url text,
+ created_by text,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ deleted_at timestamptz,
+ CONSTRAINT bots_kind_owner_check CHECK (
+ (
+ kind = 'owned'
+ AND ((owner_user_id IS NOT NULL)::int + (team_id IS NOT NULL)::int = 1)
+ )
+ OR (
+ kind = 'system'
+ AND owner_user_id IS NULL
+ AND team_id IS NULL
+ )
+ )
+);
+
+CREATE INDEX bots_owner_user_id_idx
+ ON public.bots (owner_user_id)
+ WHERE deleted_at IS NULL;
+
+CREATE INDEX bots_team_id_idx
+ ON public.bots (team_id)
+ WHERE deleted_at IS NULL;
+
+CREATE TABLE public.bot_tokens (
+ id uuid PRIMARY KEY,
+ bot_id uuid NOT NULL REFERENCES public.bots(id) ON DELETE CASCADE,
+ token_hash bytea NOT NULL,
+ token_prefix text NOT NULL,
+ label text,
+ last_used_at timestamptz,
+ expires_at timestamptz,
+ revoked_at timestamptz,
+ created_at timestamptz NOT NULL DEFAULT now()
+);
+
+CREATE INDEX bot_tokens_bot_id_idx
+ ON public.bot_tokens (bot_id);
+
+CREATE INDEX bot_tokens_token_prefix_idx
+ ON public.bot_tokens (token_prefix);