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.

Seanaye/revert/revert comms soup (#830)

Sean Ayed88f72ad3939
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000000..8d0e6f7110
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,2 @@
+# Mark .sqlx files as generated so they're excluded from PR diff stats
+**/.sqlx/** linguist-generated=true
diff --git a/flake.lock b/flake.lock
index 661a079b15..a31ee163e0 100644
--- a/flake.lock
+++ b/flake.lock
@@ -8,11 +8,11 @@
"rust-analyzer-src": "rust-analyzer-src"
},
"locked": {
- "lastModified": 1762584108,
- "narHash": "sha256-wZUW7dlXMXaRdvNbaADqhF8gg9bAfFiMV+iyFQiDv+Y=",
+ "lastModified": 1766472537,
+ "narHash": "sha256-3L602HO6JUssIL3Vo32iceObsW75+6CwLMOXRD9S3IM=",
"owner": "nix-community",
"repo": "fenix",
- "rev": "32f3ad3b6c690061173e1ac16708874975ec6056",
+ "rev": "9591b811e48f906e0a9f7afe89676a1c333415dd",
"type": "github"
},
"original": {
@@ -41,11 +41,11 @@
},
"nixpkgs": {
"locked": {
- "lastModified": 1762363567,
- "narHash": "sha256-YRqMDEtSMbitIMj+JLpheSz0pwEr0Rmy5mC7myl17xs=",
+ "lastModified": 1766309749,
+ "narHash": "sha256-3xY8CZ4rSnQ0NqGhMKAy5vgC+2IVK0NoVEzDoOh4DA4=",
"owner": "NixOS",
"repo": "nixpkgs",
- "rev": "ae814fd3904b621d8ab97418f1d0f2eb0d3716f4",
+ "rev": "a6531044f6d0bef691ea18d4d4ce44d0daa6e816",
"type": "github"
},
"original": {
@@ -65,11 +65,11 @@
"rust-analyzer-src": {
"flake": false,
"locked": {
- "lastModified": 1762438844,
- "narHash": "sha256-ApIKJf6CcMsV2nYBXhGF95BmZMO/QXPhgfSnkA/rVUo=",
+ "lastModified": 1766411395,
+ "narHash": "sha256-Cx5XbAfe0Iuoo+iQxF+H0peZ8XIZNotin5EcpzTsjXw=",
"owner": "rust-lang",
"repo": "rust-analyzer",
- "rev": "4bf516ee5a960c1e2eee9fedd9b1c9e976a19c86",
+ "rev": "624761a86465fda44d329645774eee8080038e01",
"type": "github"
},
"original": {
diff --git a/infra/stacks/cloud-storage-service/Pulumi.dev.yaml b/infra/stacks/cloud-storage-service/Pulumi.dev.yaml
index 2cfd8414e9..c4e8a4a2b5 100644
--- a/infra/stacks/cloud-storage-service/Pulumi.dev.yaml
+++ b/infra/stacks/cloud-storage-service/Pulumi.dev.yaml
@@ -10,3 +10,4 @@ config:
cloud-storage-service:document_storage_permissions_key: document-storage-permissions-key-dev
cloud-storage-service:internal_api_key: document-storage-service-auth-key-dev
cloud-storage-service:sync_service_auth_key: sync-service-key-dev
+ cloud-storage-service:authentication_service_secret_key: authentication-service-internal-api-key-dev
diff --git a/infra/stacks/cloud-storage-service/Pulumi.prod.yaml b/infra/stacks/cloud-storage-service/Pulumi.prod.yaml
index e62422a0e7..9bed158ea8 100644
--- a/infra/stacks/cloud-storage-service/Pulumi.prod.yaml
+++ b/infra/stacks/cloud-storage-service/Pulumi.prod.yaml
@@ -10,3 +10,4 @@ config:
cloud-storage-service:document_storage_permissions_key: document-storage-permissions-key-prod
cloud-storage-service:internal_api_key: document-storage-service-auth-key-prod
cloud-storage-service:sync_service_auth_key: sync-service-key-prod
+ cloud-storage-service:authentication_service_secret_key: authentication-service-internal-api-key-prod
diff --git a/infra/stacks/cloud-storage-service/index.ts b/infra/stacks/cloud-storage-service/index.ts
index 49ec9de9b7..7db199caa8 100644
--- a/infra/stacks/cloud-storage-service/index.ts
+++ b/infra/stacks/cloud-storage-service/index.ts
@@ -57,6 +57,14 @@ const syncServiceAuthKeyArn: pulumi.Output<string> = aws.secretsmanager
.getSecretVersionOutput({ secretId: SYNC_SERVICE_AUTH_KEY })
.apply((secret) => secret.arn);
+const AUTHENTICATION_SERVICE_SECRET_KEY = config.require(
+ `authentication_service_secret_key`
+);
+const authenticationServiceSecretKeyArn: pulumi.Output<string> =
+ aws.secretsmanager
+ .getSecretVersionOutput({ secretId: AUTHENTICATION_SERVICE_SECRET_KEY })
+ .apply((secret) => secret.arn);
+
const fusionauthClientIdSecretKey = config.require(`fusionauth_client_id`);
const FUSIONAUTH_CLIENT_ID = aws.secretsmanager
@@ -223,6 +231,7 @@ const cloudStorageService = new CloudStorageService(
cloudfrontPrivateKeySecretArn,
internalApiKeyArn,
syncServiceAuthKeyArn,
+ authenticationServiceSecretKeyArn,
MACRO_API_TOKENS.macroApiTokenPublicKeyArn,
],
notificationQueueArn,
@@ -348,6 +357,14 @@ const cloudStorageService = new CloudStorageService(
name: 'SYNC_SERVICE_URL',
value: `https://sync-service-${stack === 'dev' ? 'dev3' : 'prod2'}.macroverse.workers.dev`,
},
+ {
+ name: 'AUTHENTICATION_SERVICE_SECRET_KEY',
+ value: pulumi.interpolate`${AUTHENTICATION_SERVICE_SECRET_KEY}`,
+ },
+ {
+ name: 'AUTHENTICATION_SERVICE_URL',
+ value: `https://auth-service${stack === 'prod' ? '' : `-${stack}`}.macro.com`,
+ },
{
name: 'MACRO_API_TOKEN_ISSUER',
value: pulumi.interpolate`${MACRO_API_TOKENS.macroApiTokenIssuer}`,
diff --git a/js/app/flake.lock b/js/app/flake.lock
index 3f7edbf56c..ea01204cee 100644
--- a/js/app/flake.lock
+++ b/js/app/flake.lock
@@ -8,11 +8,11 @@
"rust-analyzer-src": "rust-analyzer-src"
},
"locked": {
- "lastModified": 1765435813,
- "narHash": "sha256-C6tT7K1Lx6VsYw1BY5S3OavtapUvEnDQtmQB5DSgbCc=",
+ "lastModified": 1767682236,
+ "narHash": "sha256-AWf4whMu4V1QA1wUFetWyddSfmhw6/VY5H90lXSDXjY=",
"owner": "nix-community",
"repo": "fenix",
- "rev": "6399553b7a300c77e7f07342904eb696a5b6bf9d",
+ "rev": "ab32805338a72d8d69427426ce4259162e3d68bd",
"type": "github"
},
"original": {
@@ -41,11 +41,11 @@
},
"nixpkgs": {
"locked": {
- "lastModified": 1765779637,
- "narHash": "sha256-KJ2wa/BLSrTqDjbfyNx70ov/HdgNBCBBSQP3BIzKnv4=",
+ "lastModified": 1767379071,
+ "narHash": "sha256-EgE0pxsrW9jp9YFMkHL9JMXxcqi/OoumPJYwf+Okucw=",
"owner": "NixOS",
"repo": "nixpkgs",
- "rev": "1306659b587dc277866c7b69eb97e5f07864d8c4",
+ "rev": "fb7944c166a3b630f177938e478f0378e64ce108",
"type": "github"
},
"original": {
@@ -65,11 +65,11 @@
"rust-analyzer-src": {
"flake": false,
"locked": {
- "lastModified": 1765400135,
- "narHash": "sha256-D3+4hfNwUhG0fdCpDhOASLwEQ1jKuHi4mV72up4kLQM=",
+ "lastModified": 1767609612,
+ "narHash": "sha256-ghz849iTGb+if+co4yGQC2Nfc0H6B/K4JFeul9rm7n4=",
"owner": "rust-lang",
"repo": "rust-analyzer",
- "rev": "fface27171988b3d605ef45cf986c25533116f7e",
+ "rev": "58646b524408a5aecb12d91121ea5825bef3d0c8",
"type": "github"
},
"original": {
diff --git a/js/app/packages/app/component/WhichKey.tsx b/js/app/packages/app/component/WhichKey.tsx
index 9811b2e490..68070b54ec 100644
--- a/js/app/packages/app/component/WhichKey.tsx
+++ b/js/app/packages/app/component/WhichKey.tsx
@@ -48,7 +48,7 @@ function WhichKeyContent(props: WhichKeyContentProps) {
token={command.hotkeyToken}
shortcut={prettyPrintHotkeyString(
// Asserting this, because useActiveCommands only returns commands with hotkeys.
- command.hotkeys!.at(0)!
+ command.hotkeys.at(0)!
)}
/>
</div>
@@ -70,7 +70,7 @@ function WhichKeyContent(props: WhichKeyContentProps) {
token={command.hotkeyToken}
shortcut={prettyPrintHotkeyString(
// Asserting this, because useActiveCommands only returns commands with hotkeys.
- command.hotkeys!.at(0)!
+ command.hotkeys.at(0)!
)}
/>
</div>
diff --git a/js/app/packages/app/component/dock/QuickAccess.tsx b/js/app/packages/app/component/dock/QuickAccess.tsx
index 1f0a8c6124..1c622582c6 100644
--- a/js/app/packages/app/component/dock/QuickAccess.tsx
+++ b/js/app/packages/app/component/dock/QuickAccess.tsx
@@ -12,7 +12,7 @@ import {
notificationIsRead,
type UnifiedNotification,
} from '@notifications';
-import type { ChannelWithLatest } from '@service-comms/generated/models';
+import type { ApiChannelWithLatest as ChannelWithLatest } from '@service-comms/generated/models';
import { useUserId } from '@service-gql/client';
import { NotificationEventType } from '@service-notification/generated/schemas';
import { createMemo, createSignal, For, Show } from 'solid-js';
diff --git a/js/app/packages/app/component/split-layout/layoutManager.ts b/js/app/packages/app/component/split-layout/layoutManager.ts
index 9979a27bb2..095ec7d7f2 100644
--- a/js/app/packages/app/component/split-layout/layoutManager.ts
+++ b/js/app/packages/app/component/split-layout/layoutManager.ts
@@ -689,7 +689,7 @@ export function createSplitLayout(
s.content.id === initialContent.id
);
- return getSplit(existingSplit!.id)!;
+ return getSplit(existingSplit.id)!;
}
const split = buildSplit(initialContent, isDefault);
diff --git a/js/app/packages/block-md/component/History.tsx b/js/app/packages/block-md/component/History.tsx
index 5c0e689247..4f6ccf1666 100644
--- a/js/app/packages/block-md/component/History.tsx
+++ b/js/app/packages/block-md/component/History.tsx
@@ -199,7 +199,7 @@ export function History(props: HistoryProps) {
if (!found) return undefined;
- return [found, sortedHistory()!.indexOf(found)!];
+ return [found, sortedHistory().indexOf(found)!];
};
const handleFork = async () => {
diff --git a/js/app/packages/block-pdf/PdfViewer/InternalPDFViewer.ts b/js/app/packages/block-pdf/PdfViewer/InternalPDFViewer.ts
index 8b52bdd247..3299ad1467 100644
--- a/js/app/packages/block-pdf/PdfViewer/InternalPDFViewer.ts
+++ b/js/app/packages/block-pdf/PdfViewer/InternalPDFViewer.ts
@@ -536,7 +536,7 @@ export class InternalPDFViewer {
if (_target == null && this._popupTargetID == null) return;
const target = (_target ??
- document.getElementById(this._popupTargetID!) ??
+ document.getElementById(this._popupTargetID) ??
document.querySelector(
`.annotationLayer .linkAnnotation[data-annotation-id="${this._popupTargetID}"]`
))!;
diff --git a/js/app/packages/core/component/ChannelsProvider.tsx b/js/app/packages/core/component/ChannelsProvider.tsx
index ab2add9639..a686dfb8f7 100644
--- a/js/app/packages/core/component/ChannelsProvider.tsx
+++ b/js/app/packages/core/component/ChannelsProvider.tsx
@@ -3,7 +3,7 @@ import { queryKeys } from '@macro-entity';
import { commsServiceClient } from '@service-comms/client';
import type {
ActivityType,
- ChannelWithLatest,
+ ApiChannelWithLatest as ChannelWithLatest,
} from '@service-comms/generated/models';
import type { Activity as ChannelActivity } from '@service-comms/generated/models/activity';
import { type UseQueryResult, useQuery } from '@tanstack/solid-query';
@@ -29,7 +29,7 @@ export function createChannelActivityQuery() {
throw new Error('Failed to fetch activity', { cause: result[0] });
}
- return result[1]?.items ?? [];
+ return result[1] ?? [];
},
}));
}
@@ -44,7 +44,7 @@ export function createChannelsQuery() {
throw new Error('Failed to fetch channels', { cause: result[0] });
}
- return result[1]?.channels ?? [];
+ return result[1] ?? [];
},
}));
}
diff --git a/js/app/packages/core/component/NotificationRenderer.tsx b/js/app/packages/core/component/NotificationRenderer.tsx
index 3926c7ca63..14965e5492 100644
--- a/js/app/packages/core/component/NotificationRenderer.tsx
+++ b/js/app/packages/core/component/NotificationRenderer.tsx
@@ -44,7 +44,7 @@ export function NotificationRenderer(props: NotificationRendererProps) {
<Show when={d().target?.type === 'channel' && d().target?.id}>
<div class="self-center max-h-[1lh]">
<InlineItemPreview
- itemId={d().target!.id!}
+ itemId={d().target.id!}
itemType="channel"
/>
</div>
@@ -64,10 +64,7 @@ export function NotificationRenderer(props: NotificationRendererProps) {
<div class="text-sm text-ink inline-flex items-center gap-1">
<span class="font-medium">{displayName()}</span> {d().action}{' '}
<Show when={d().target?.type === 'channel' && d().target?.id}>
- <InlineItemPreview
- itemId={d().target!.id!}
- itemType="channel"
- />
+ <InlineItemPreview itemId={d().target.id!} itemType="channel" />
</Show>
<Show when={d().target?.name && d().target?.type !== 'channel'}>
<span class="font-medium">{d().target!.name}</span>
diff --git a/js/app/packages/macro-entity/src/queries/channel.ts b/js/app/packages/macro-entity/src/queries/channel.ts
index 3d8a1df77c..e4119daf30 100644
--- a/js/app/packages/macro-entity/src/queries/channel.ts
+++ b/js/app/packages/macro-entity/src/queries/channel.ts
@@ -1,4 +1,4 @@
-import type { GetChannelsResponse } from '@service-comms/generated/models/getChannelsResponse';
+import type { ApiChannelWithLatest } from '@service-comms/generated/models';
import { useQuery } from '@tanstack/solid-query';
import { SERVER_HOSTS } from 'core/constant/servers';
import { platformFetch } from 'core/util/platformFetch';
@@ -20,7 +20,7 @@ const fetchChannels = async ({ apiToken }: { apiToken?: string }) => {
if (!response.ok)
throw new Error('Failed to fetch channels', { cause: response });
- const { channels }: GetChannelsResponse = await response.json();
+ const channels: ApiChannelWithLatest[] = await response.json();
return channels;
};
@@ -39,7 +39,7 @@ export function createChannelsQuery(options?: {
name: channel.name ?? 'Unknown Channel',
channelType: channel.channel_type,
ownerId: channel.owner_id,
- frecencyScore: channel.frecency_score,
+ frecencyScore: channel.frecency_score ?? 0,
createdAt: Date.parse(channel.created_at),
updatedAt: Date.parse(channel.updated_at),
participantIds: channel.participants.map((p) => p.user_id),
diff --git a/js/app/packages/macro-entity/src/queries/dss.ts b/js/app/packages/macro-entity/src/queries/dss.ts
index 8b8968c9a8..b1164b18da 100644
--- a/js/app/packages/macro-entity/src/queries/dss.ts
+++ b/js/app/packages/macro-entity/src/queries/dss.ts
@@ -27,6 +27,7 @@ import { SERVER_HOSTS } from 'core/constant/servers';
import { platformFetch } from 'core/util/platformFetch';
import type { Accessor } from 'solid-js';
import type {
+ ChannelEntity,
ChatEntity,
DocumentEntity,
EmailEntity,
@@ -198,10 +199,13 @@ const selectData: (
options: {
instructionsIdQuery: UseQueryResult<string | null | undefined, Error>;
}
-) => (DocumentEntity | ChatEntity | ProjectEntity | EmailEntity)[] = (
- data,
- options
-) => {
+) => (
+ | DocumentEntity
+ | ChatEntity
+ | ProjectEntity
+ | EmailEntity
+ | ChannelEntity
+)[] = (data, options) => {
return data.pages.flatMap(({ items }) =>
items
.filter(
@@ -211,7 +215,14 @@ const selectData: (
item.data.id !== options.instructionsIdQuery.data
)
.map(
- (item): DocumentEntity | ChatEntity | ProjectEntity | EmailEntity => {
+ (
+ item
+ ):
+ | DocumentEntity
+ | ChatEntity
+ | ProjectEntity
+ | EmailEntity
+ | ChannelEntity => {
if (item.tag === 'chat') {
return {
...item.data,
@@ -257,6 +268,18 @@ const selectData: (
};
}
+ if (item.tag === 'channel') {
+ const out: ChannelEntity = {
+ ...item.data.channel,
+ channelType: item.data.channel.channel_type,
+ type: 'channel',
+ id: item.data.channel.id,
+ name: item.data.channel.name || 'New Channel',
+ ownerId: item.data.channel.owner_id,
+ };
+ return out;
+ }
+
return {
...item.data,
type: item.tag,
diff --git a/js/app/packages/service-clients/service-comms/client.ts b/js/app/packages/service-clients/service-comms/client.ts
index 64234f3a92..4e38bb39bd 100644
--- a/js/app/packages/service-clients/service-comms/client.ts
+++ b/js/app/packages/service-clients/service-comms/client.ts
@@ -10,7 +10,11 @@ import {
type ObjectLike,
} from '@core/util/maybeResult';
import type { SafeFetchInit } from '@core/util/safeFetch';
-import type { GetMentionsResponse } from './generated/models';
+import type {
+ ApiActivity,
+ ApiChannelWithLatest,
+ GetMentionsResponse,
+} from './generated/models';
import type { Activity } from './generated/models/activity';
import type { AddParticipantsRequest } from './generated/models/addParticipantsRequest';
import type { CreateChannelRequest } from './generated/models/createChannelRequest';
@@ -18,12 +22,10 @@ import type { CreateChannelResponse } from './generated/models/createChannelResp
import type { CreateEntityMentionRequest } from './generated/models/createEntityMentionRequest';
import type { CreateEntityMentionResponse } from './generated/models/createEntityMentionResponse';
import type { DeleteEntityMentionResponse } from './generated/models/deleteEntityMentionResponse';
-import type { GetActivityResponse } from './generated/models/getActivityResponse';
import type { GetAttachmentReferencesResponse } from './generated/models/getAttachmentReferencesResponse';
import type { GetBatchChannelPreviewRequest } from './generated/models/getBatchChannelPreviewRequest';
import type { GetBatchChannelPreviewResponse } from './generated/models/getBatchChannelPreviewResponse';
import type { GetChannelResponse } from './generated/models/getChannelResponse';
-import type { GetChannelsResponse } from './generated/models/getChannelsResponse';
import type { GetOrCreateDmRequest } from './generated/models/getOrCreateDmRequest';
import type { GetOrCreateDmResponse } from './generated/models/getOrCreateDmResponse';
import type { GetOrCreatePrivateRequest } from './generated/models/getOrCreatePrivateRequest';
@@ -76,7 +78,7 @@ export const commsServiceClient = {
},
async getChannels() {
return mapOk(
- await commsFetch<GetChannelsResponse>(`/channels`, {
+ await commsFetch<ApiChannelWithLatest[]>(`/channels`, {
method: 'GET',
}),
(result) => result
@@ -162,7 +164,7 @@ export const commsServiceClient = {
},
async getActivity() {
return mapOk(
- await commsFetch<GetActivityResponse>(`/activity`, {
+ await commsFetch<ApiActivity[]>(`/activity`, {
method: 'GET',
}),
(result) => result
diff --git a/js/app/packages/service-clients/service-comms/generated/client.ts b/js/app/packages/service-clients/service-comms/generated/client.ts
index 662f0cdc70..5e1239f460 100644
--- a/js/app/packages/service-clients/service-comms/generated/client.ts
+++ b/js/app/packages/service-clients/service-comms/generated/client.ts
@@ -7,19 +7,19 @@
import type {
Activity,
AddParticipantsRequest,
+ ApiActivity,
+ ApiChannelWithLatest,
CreateChannelRequest,
CreateChannelResponse,
CreateEntityMentionRequest,
CreateEntityMentionResponse,
DeleteEntityMentionResponse,
GenericErrorResponse,
- GetActivityResponse,
GetAttachmentReferencesResponse,
GetBatchChannelPreviewRequest,
GetBatchChannelPreviewResponse,
GetChannelParams,
GetChannelResponse,
- GetChannelsResponse,
GetMentionsResponse,
GetMessageWithContextParams,
GetMessageWithContextResponse,
@@ -38,7 +38,7 @@ import type {
} from './models';
export type getActivityResponse200 = {
- data: GetActivityResponse
+ data: ApiActivity[]
status: 200
}
@@ -209,7 +209,7 @@ export const getAttachmentReferences = async (entityType: string,
export type getChannelsResponse200 = {
- data: GetChannelsResponse
+ data: ApiChannelWithLatest[]
status: 200
}
diff --git a/js/app/packages/service-clients/service-comms/generated/models/apiActivity.ts b/js/app/packages/service-clients/service-comms/generated/models/apiActivity.ts
new file mode 100644
index 0000000000..57620356e2
--- /dev/null
+++ b/js/app/packages/service-clients/service-comms/generated/models/apiActivity.ts
@@ -0,0 +1,21 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * comms_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ApiActivityInteractedAt } from './apiActivityInteractedAt';
+import type { ApiActivityViewedAt } from './apiActivityViewedAt';
+
+export interface ApiActivity {
+ channel_id: string;
+ created_at: string;
+ id: string;
+ /** the last time the user intereacted with the channel
+eg. reacting, replying, sending a message */
+ interacted_at?: ApiActivityInteractedAt;
+ updated_at: string;
+ user_id: string;
+ /** the last time the user viewed the channel */
+ viewed_at?: ApiActivityViewedAt;
+}
diff --git a/js/app/packages/service-clients/service-comms/generated/models/apiActivityInteractedAt.ts b/js/app/packages/service-clients/service-comms/generated/models/apiActivityInteractedAt.ts
new file mode 100644
index 0000000000..0bf993bf19
--- /dev/null
+++ b/js/app/packages/service-clients/service-comms/generated/models/apiActivityInteractedAt.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * comms_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * the last time the user intereacted with the channel
+eg. reacting, replying, sending a message
+ */
+export type ApiActivityInteractedAt = string | null;
diff --git a/js/app/packages/service-clients/service-comms/generated/models/getActivityResponse.ts b/js/app/packages/service-clients/service-comms/generated/models/apiActivityViewedAt.ts
similarity index 52%
rename from js/app/packages/service-clients/service-comms/generated/models/getActivityResponse.ts
rename to js/app/packages/service-clients/service-comms/generated/models/apiActivityViewedAt.ts
index 818d7d4f91..51ee48b3cb 100644
--- a/js/app/packages/service-clients/service-comms/generated/models/getActivityResponse.ts
+++ b/js/app/packages/service-clients/service-comms/generated/models/apiActivityViewedAt.ts
@@ -4,8 +4,8 @@
* comms_service
* OpenAPI spec version: 0.1.0
*/
-import type { Activity } from './activity';
-export interface GetActivityResponse {
- items: Activity[];
-}
+/**
+ * the last time the user viewed the channel
+ */
+export type ApiActivityViewedAt = string | null;
diff --git a/js/app/packages/service-clients/service-comms/generated/models/channelWithLatest.ts b/js/app/packages/service-clients/service-comms/generated/models/apiChannelWithLatest.ts
similarity index 57%
rename from js/app/packages/service-clients/service-comms/generated/models/channelWithLatest.ts
rename to js/app/packages/service-clients/service-comms/generated/models/apiChannelWithLatest.ts
index e306685d8a..adc7dccd1c 100644
--- a/js/app/packages/service-clients/service-comms/generated/models/channelWithLatest.ts
+++ b/js/app/packages/service-clients/service-comms/generated/models/apiChannelWithLatest.ts
@@ -6,6 +6,6 @@
*/
import type { ChannelWithParticipants } from './channelWithParticipants';
import type { LatestMessage } from './latestMessage';
-import type { ChannelWithLatestAllOf } from './channelWithLatestAllOf';
+import type { ApiChannelWithLatestAllOf } from './apiChannelWithLatestAllOf';
-export type ChannelWithLatest = ChannelWithParticipants & LatestMessage & ChannelWithLatestAllOf;
+export type ApiChannelWithLatest = ChannelWithParticipants & LatestMessage & ApiChannelWithLatestAllOf;
diff --git a/js/app/packages/service-clients/service-comms/generated/models/apiChannelWithLatestAllOf.ts b/js/app/packages/service-clients/service-comms/generated/models/apiChannelWithLatestAllOf.ts
new file mode 100644
index 0000000000..9bfbae66a9
--- /dev/null
+++ b/js/app/packages/service-clients/service-comms/generated/models/apiChannelWithLatestAllOf.ts
@@ -0,0 +1,15 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * comms_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ApiChannelWithLatestAllOfFrecencyScore } from './apiChannelWithLatestAllOfFrecencyScore';
+import type { ApiChannelWithLatestAllOfInteractedAt } from './apiChannelWithLatestAllOfInteractedAt';
+import type { ApiChannelWithLatestAllOfViewedAt } from './apiChannelWithLatestAllOfViewedAt';
+
+export type ApiChannelWithLatestAllOf = {
+ frecency_score?: ApiChannelWithLatestAllOfFrecencyScore;
+ interacted_at?: ApiChannelWithLatestAllOfInteractedAt;
+ viewed_at?: ApiChannelWithLatestAllOfViewedAt;
+};
diff --git a/js/app/packages/service-clients/service-comms/generated/models/apiChannelWithLatestAllOfFrecencyScore.ts b/js/app/packages/service-clients/service-comms/generated/models/apiChannelWithLatestAllOfFrecencyScore.ts
new file mode 100644
index 0000000000..cf3eedb234
--- /dev/null
+++ b/js/app/packages/service-clients/service-comms/generated/models/apiChannelWithLatestAllOfFrecencyScore.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * comms_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiChannelWithLatestAllOfFrecencyScore = number | null;
diff --git a/js/app/packages/service-clients/service-comms/generated/models/channelWithLatestAllOfInteractedAt.ts b/js/app/packages/service-clients/service-comms/generated/models/apiChannelWithLatestAllOfInteractedAt.ts
similarity index 63%
rename from js/app/packages/service-clients/service-comms/generated/models/channelWithLatestAllOfInteractedAt.ts
rename to js/app/packages/service-clients/service-comms/generated/models/apiChannelWithLatestAllOfInteractedAt.ts
index 0651ba894b..bf0391c7be 100644
--- a/js/app/packages/service-clients/service-comms/generated/models/channelWithLatestAllOfInteractedAt.ts
+++ b/js/app/packages/service-clients/service-comms/generated/models/apiChannelWithLatestAllOfInteractedAt.ts
@@ -5,4 +5,4 @@
* OpenAPI spec version: 0.1.0
*/
-export type ChannelWithLatestAllOfInteractedAt = string | null;
+export type ApiChannelWithLatestAllOfInteractedAt = string | null;
diff --git a/js/app/packages/service-clients/service-comms/generated/models/channelWithLatestAllOfViewedAt.ts b/js/app/packages/service-clients/service-comms/generated/models/apiChannelWithLatestAllOfViewedAt.ts
similarity index 65%
rename from js/app/packages/service-clients/service-comms/generated/models/channelWithLatestAllOfViewedAt.ts
rename to js/app/packages/service-clients/service-comms/generated/models/apiChannelWithLatestAllOfViewedAt.ts
index 615ba64487..515da37ce3 100644
--- a/js/app/packages/service-clients/service-comms/generated/models/channelWithLatestAllOfViewedAt.ts
+++ b/js/app/packages/service-clients/service-comms/generated/models/apiChannelWithLatestAllOfViewedAt.ts
@@ -5,4 +5,4 @@
* OpenAPI spec version: 0.1.0
*/
-export type ChannelWithLatestAllOfViewedAt = string | null;
+export type ApiChannelWithLatestAllOfViewedAt = string | null;
diff --git a/js/app/packages/service-clients/service-comms/generated/models/channel.ts b/js/app/packages/service-clients/service-comms/generated/models/channel.ts
index b4853396f0..01333eae54 100644
--- a/js/app/packages/service-clients/service-comms/generated/models/channel.ts
+++ b/js/app/packages/service-clients/service-comms/generated/models/channel.ts
@@ -17,7 +17,10 @@ export interface Channel {
id: string;
/** string name of the channel */
name?: ChannelName;
- /** id of the organization this channel belongs too */
+ /**
+ * id of the organization this channel belongs too
+ * @minimum 0
+ */
org_id?: ChannelOrgId;
/** id of the user who created the channel */
owner_id: string;
diff --git a/js/app/packages/service-clients/service-comms/generated/models/channelOrgId.ts b/js/app/packages/service-clients/service-comms/generated/models/channelOrgId.ts
index 31d726a194..66e66ac67e 100644
--- a/js/app/packages/service-clients/service-comms/generated/models/channelOrgId.ts
+++ b/js/app/packages/service-clients/service-comms/generated/models/channelOrgId.ts
@@ -7,5 +7,6 @@
/**
* id of the organization this channel belongs too
+ * @minimum 0
*/
export type ChannelOrgId = number | null;
diff --git a/js/app/packages/service-clients/service-comms/generated/models/channelWithLatestAllOf.ts b/js/app/packages/service-clients/service-comms/generated/models/channelWithLatestAllOf.ts
deleted file mode 100644
index c203cc9cca..0000000000
--- a/js/app/packages/service-clients/service-comms/generated/models/channelWithLatestAllOf.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * comms_service
- * OpenAPI spec version: 0.1.0
- */
-import type { ChannelWithLatestAllOfInteractedAt } from './channelWithLatestAllOfInteractedAt';
-import type { ChannelWithLatestAllOfViewedAt } from './channelWithLatestAllOfViewedAt';
-
-export type ChannelWithLatestAllOf = {
- frecency_score: number;
- interacted_at?: ChannelWithLatestAllOfInteractedAt;
- viewed_at?: ChannelWithLatestAllOfViewedAt;
-};
diff --git a/js/app/packages/service-clients/service-comms/generated/models/getChannelsResponse.ts b/js/app/packages/service-clients/service-comms/generated/models/getChannelsResponse.ts
deleted file mode 100644
index 69c441ca6d..0000000000
--- a/js/app/packages/service-clients/service-comms/generated/models/getChannelsResponse.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * comms_service
- * OpenAPI spec version: 0.1.0
- */
-import type { ChannelWithLatest } from './channelWithLatest';
-
-export interface GetChannelsResponse {
- channels: ChannelWithLatest[];
-}
diff --git a/js/app/packages/service-clients/service-comms/generated/models/index.ts b/js/app/packages/service-clients/service-comms/generated/models/index.ts
index 321f3d8c4f..7dcf3be7a4 100644
--- a/js/app/packages/service-clients/service-comms/generated/models/index.ts
+++ b/js/app/packages/service-clients/service-comms/generated/models/index.ts
@@ -10,6 +10,14 @@ export * from './activityInteractedAt';
export * from './activityType';
export * from './activityViewedAt';
export * from './addParticipantsRequest';
+export * from './apiActivity';
+export * from './apiActivityInteractedAt';
+export * from './apiActivityViewedAt';
+export * from './apiChannelWithLatest';
+export * from './apiChannelWithLatestAllOf';
+export * from './apiChannelWithLatestAllOfFrecencyScore';
+export * from './apiChannelWithLatestAllOfInteractedAt';
+export * from './apiChannelWithLatestAllOfViewedAt';
export * from './attachment';
export * from './attachmentHeight';
export * from './attachmentWidth';
@@ -36,10 +44,6 @@ export * from './channelReference';
export * from './channelReferenceChannelName';
export * from './channelReferenceThreadId';
export * from './channelType';
-export * from './channelWithLatest';
-export * from './channelWithLatestAllOf';
-export * from './channelWithLatestAllOfInteractedAt';
-export * from './channelWithLatestAllOfViewedAt';
export * from './channelWithParticipants';
export * from './channelWithParticipantsAllOf';
export * from './communicationServiceApiVersion';
@@ -65,7 +69,6 @@ export * from './entityReferenceOneOfFourAllOfReferenceType';
export * from './genericErrorResponse';
export * from './genericReference';
export * from './genericReferenceUserId';
-export * from './getActivityResponse';
export * from './getAttachmentReferencesResponse';
export * from './getBatchChannelPreviewRequest';
export * from './getBatchChannelPreviewResponse';
@@ -73,7 +76,6 @@ export * from './getChannelParams';
export * from './getChannelResponse';
export * from './getChannelResponseActivity';
export * from './getChannelResponseReactions';
-export * from './getChannelsResponse';
export * from './getMentionsResponse';
export * from './getMessageWithContextParams';
export * from './getMessageWithContextResponse';
diff --git a/js/app/packages/service-clients/service-comms/openapi.json b/js/app/packages/service-clients/service-comms/openapi.json
index 698b597c5b..fa4a8b1b08 100644
--- a/js/app/packages/service-clients/service-comms/openapi.json
+++ b/js/app/packages/service-clients/service-comms/openapi.json
@@ -17,7 +17,10 @@
"description": "",
"content": {
"application/json": {
- "schema": { "$ref": "#/components/schemas/GetActivityResponse" }
+ "schema": {
+ "type": "array",
+ "items": { "$ref": "#/components/schemas/ApiActivity" }
+ }
}
}
},
@@ -125,7 +128,12 @@
"description": "",
"content": {
"application/json": {
- "schema": { "$ref": "#/components/schemas/GetChannelsResponse" }
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ApiChannelWithLatest"
+ }
+ }
}
}
},
@@ -982,6 +990,47 @@
"participants": { "type": "array", "items": { "type": "string" } }
}
},
+ "ApiActivity": {
+ "type": "object",
+ "required": ["id", "user_id", "channel_id", "created_at", "updated_at"],
+ "properties": {
+ "channel_id": { "type": "string", "format": "uuid" },
+ "created_at": { "type": "string", "format": "date-time" },
+ "id": { "type": "string", "format": "uuid" },
+ "interacted_at": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "the last time the user intereacted with the channel\neg. reacting, replying, sending a message"
+ },
+ "updated_at": { "type": "string", "format": "date-time" },
+ "user_id": { "type": "string" },
+ "viewed_at": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "the last time the user viewed the channel"
+ }
+ }
+ },
+ "ApiChannelWithLatest": {
+ "allOf": [
+ { "$ref": "#/components/schemas/ChannelWithParticipants" },
+ { "$ref": "#/components/schemas/LatestMessage" },
+ {
+ "type": "object",
+ "properties": {
+ "frecency_score": {
+ "type": ["number", "null"],
+ "format": "double"
+ },
+ "interacted_at": {
+ "type": ["string", "null"],
+ "format": "date-time"
+ },
+ "viewed_at": { "type": ["string", "null"], "format": "date-time" }
+ }
+ }
+ ]
+ },
"Attachment": {
"type": "object",
"required": [
@@ -1037,8 +1086,9 @@
},
"org_id": {
"type": ["integer", "null"],
- "format": "int64",
- "description": "id of the organization this channel belongs too"
+ "format": "int32",
+ "description": "id of the organization this channel belongs too",
+ "minimum": 0
},
"owner_id": {
"type": "string",
@@ -1206,24 +1256,6 @@
"type": "string",
"enum": ["public", "organization", "private", "direct_message"]
},
- "ChannelWithLatest": {
- "allOf": [
- { "$ref": "#/components/schemas/ChannelWithParticipants" },
- { "$ref": "#/components/schemas/LatestMessage" },
- {
- "type": "object",
- "required": ["frecency_score"],
- "properties": {
- "frecency_score": { "type": "number", "format": "double" },
- "interacted_at": {
- "type": ["string", "null"],
- "format": "date-time"
- },
- "viewed_at": { "type": ["string", "null"], "format": "date-time" }
- }
- }
- ]
- },
"ChannelWithParticipants": {
"allOf": [
{ "$ref": "#/components/schemas/Channel" },
@@ -1436,16 +1468,6 @@
}
}
},
- "GetActivityResponse": {
- "type": "object",
- "required": ["items"],
- "properties": {
- "items": {
- "type": "array",
- "items": { "$ref": "#/components/schemas/Activity" }
- }
- }
- },
"GetAttachmentReferencesResponse": {
"type": "object",
"required": ["references"],
@@ -1527,16 +1549,6 @@
}
}
},
- "GetChannelsResponse": {
- "type": "object",
- "required": ["channels"],
- "properties": {
- "channels": {
- "type": "array",
- "items": { "$ref": "#/components/schemas/ChannelWithLatest" }
- }
- }
- },
"GetMentionsResponse": {
"type": "object",
"required": ["mentions"],
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/channel.ts b/js/app/packages/service-clients/service-storage/generated/schemas/channel.ts
new file mode 100644
index 0000000000..c973ba07a4
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/channel.ts
@@ -0,0 +1,20 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ChannelType } from './channelType';
+import type { ChannelName } from './channelName';
+import type { ChannelOrgId } from './channelOrgId';
+
+export interface Channel {
+ channel_type: ChannelType;
+ created_at: string;
+ id: string;
+ name?: ChannelName;
+ /** @minimum 0 */
+ org_id?: ChannelOrgId;
+ owner_id: string;
+ updated_at: string;
+}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/channelMessage.ts b/js/app/packages/service-clients/service-storage/generated/schemas/channelMessage.ts
new file mode 100644
index 0000000000..d8fb5c8454
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/channelMessage.ts
@@ -0,0 +1,20 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ChannelMessageDeletedAt } from './channelMessageDeletedAt';
+import type { ChannelMessageThreadId } from './channelMessageThreadId';
+
+export interface ChannelMessage {
+ content: string;
+ created_at: string;
+ deleted_at?: ChannelMessageDeletedAt;
+ /** message mentions formatted as `{ENTITY_TYPE}:{ENTITY_ID}` */
+ mentions: string[];
+ message_id: string;
+ sender_id: string;
+ thread_id?: ChannelMessageThreadId;
+ updated_at: string;
+}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageDeletedAt.ts b/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageDeletedAt.ts
new file mode 100644
index 0000000000..b5cf27a69c
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageDeletedAt.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ChannelMessageDeletedAt = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageThreadId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageThreadId.ts
new file mode 100644
index 0000000000..17b8eaa334
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageThreadId.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ChannelMessageThreadId = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/channelName.ts b/js/app/packages/service-clients/service-storage/generated/schemas/channelName.ts
new file mode 100644
index 0000000000..2b7aa10b06
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/channelName.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ChannelName = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/channelOrgId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/channelOrgId.ts
new file mode 100644
index 0000000000..6f0e6628a0
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/channelOrgId.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * @minimum 0
+ */
+export type ChannelOrgId = number | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/channelParticipant.ts b/js/app/packages/service-clients/service-storage/generated/schemas/channelParticipant.ts
new file mode 100644
index 0000000000..c1ee072769
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/channelParticipant.ts
@@ -0,0 +1,16 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ChannelParticipantLeftAt } from './channelParticipantLeftAt';
+import type { ParticipantRole } from './participantRole';
+
+export interface ChannelParticipant {
+ channel_id: string;
+ joined_at: string;
+ left_at?: ChannelParticipantLeftAt;
+ role: ParticipantRole;
+ user_id: string;
+}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/channelParticipantLeftAt.ts b/js/app/packages/service-clients/service-storage/generated/schemas/channelParticipantLeftAt.ts
new file mode 100644
index 0000000000..024ace604c
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/channelParticipantLeftAt.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ChannelParticipantLeftAt = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/channelType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/channelType.ts
new file mode 100644
index 0000000000..a99327fb92
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/channelType.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ChannelType = typeof ChannelType[keyof typeof ChannelType];
+
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const ChannelType = {
+ public: 'public',
+ organization: 'organization',
+ private: 'private',
+ direct_message: 'direct_message',
+} as const;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/channelWithParticipants.ts b/js/app/packages/service-clients/service-storage/generated/schemas/channelWithParticipants.ts
new file mode 100644
index 0000000000..941e556121
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/channelWithParticipants.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { Channel } from './channel';
+import type { ChannelParticipant } from './channelParticipant';
+
+export interface ChannelWithParticipants {
+ channel: Channel;
+ participants: ChannelParticipant[];
+}
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 e61d634d6e..cd50931951 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
@@ -50,9 +50,19 @@ export * from './basicDocumentSha';
export * from './basicDocumentSubType';
export * from './basicDocumentType';
export * from './bomPart';
+export * from './channel';
export * from './channelFilters';
export * from './channelFiltersOrgId';
+export * from './channelMessage';
+export * from './channelMessageDeletedAt';
+export * from './channelMessageThreadId';
+export * from './channelName';
+export * from './channelOrgId';
+export * from './channelParticipant';
+export * from './channelParticipantLeftAt';
export * from './channelSharePermission';
+export * from './channelType';
+export * from './channelWithParticipants';
export * from './chat';
export * from './chatDeletedAt';
export * from './chatFilters';
@@ -282,6 +292,9 @@ export * from './hashMapOneOfFourAllOfType';
export * from './highlightType';
export * from './item';
export * from './itemWithUserAccessLevel';
+export * from './latestMessage';
+export * from './latestMessageLatestMessage';
+export * from './latestMessageLatestNonThreadMessage';
export * from './locationResponseData';
export * from './locationResponseDataOneOf';
export * from './locationResponseDataOneOfTwo';
@@ -289,6 +302,7 @@ export * from './params';
export * from './paramsExpand';
export * from './paramsLimit';
export * from './paramsSortMethod';
+export * from './participantRole';
export * from './patchProjectRequestV2';
export * from './patchProjectRequestV2Name';
export * from './patchProjectRequestV2ProjectParentId';
@@ -399,6 +413,10 @@ export * from './soupAttachmentFilename';
export * from './soupAttachmentMimeType';
export * from './soupAttachmentProviderAttachmentId';
export * from './soupAttachmentSizeBytes';
+export * from './soupChannel';
+export * from './soupChannelAllOf';
+export * from './soupChannelAllOfInteractedAt';
+export * from './soupChannelAllOfViewedAt';
export * from './soupChat';
export * from './soupChatProjectId';
export * from './soupChatViewedAt';
@@ -430,12 +448,13 @@ export * from './soupItem';
export * from './soupItemOneOf';
export * from './soupItemOneOfFive';
export * from './soupItemOneOfFiveTag';
+export * from './soupItemOneOfNine';
+export * from './soupItemOneOfNineTag';
export * from './soupItemOneOfSeven';
export * from './soupItemOneOfSevenTag';
export * from './soupItemOneOfTag';
export * from './soupItemOneOfThree';
export * from './soupItemOneOfThreeTag';
-export * from './soupItemType';
export * from './soupLabel';
export * from './soupLabelListVisibility';
export * from './soupLabelType';
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/latestMessage.ts b/js/app/packages/service-clients/service-storage/generated/schemas/latestMessage.ts
new file mode 100644
index 0000000000..0d768f530f
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/latestMessage.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { LatestMessageLatestMessage } from './latestMessageLatestMessage';
+import type { LatestMessageLatestNonThreadMessage } from './latestMessageLatestNonThreadMessage';
+
+export interface LatestMessage {
+ latest_message?: LatestMessageLatestMessage;
+ latest_non_thread_message?: LatestMessageLatestNonThreadMessage;
+}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/latestMessageLatestMessage.ts b/js/app/packages/service-clients/service-storage/generated/schemas/latestMessageLatestMessage.ts
new file mode 100644
index 0000000000..4023722f61
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/latestMessageLatestMessage.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ChannelMessage } from './channelMessage';
+
+export type LatestMessageLatestMessage = null | ChannelMessage;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/latestMessageLatestNonThreadMessage.ts b/js/app/packages/service-clients/service-storage/generated/schemas/latestMessageLatestNonThreadMessage.ts
new file mode 100644
index 0000000000..089038e01d
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/latestMessageLatestNonThreadMessage.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ChannelMessage } from './channelMessage';
+
+export type LatestMessageLatestNonThreadMessage = null | ChannelMessage;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/soupItemType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/participantRole.ts
similarity index 50%
rename from js/app/packages/service-clients/service-storage/generated/schemas/soupItemType.ts
rename to js/app/packages/service-clients/service-storage/generated/schemas/participantRole.ts
index c9032b01eb..9029093a9b 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/soupItemType.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/participantRole.ts
@@ -5,13 +5,12 @@
* OpenAPI spec version: 0.1.0
*/
-export type SoupItemType = typeof SoupItemType[keyof typeof SoupItemType];
+export type ParticipantRole = typeof ParticipantRole[keyof typeof ParticipantRole];
// eslint-disable-next-line @typescript-eslint/no-redeclare
-export const SoupItemType = {
- document: 'document',
- chat: 'chat',
- project: 'project',
- email_thread: 'email_thread',
+export const ParticipantRole = {
+ owner: 'owner',
+ admin: 'admin',
+ member: 'member',
} as const;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/soupChannel.ts b/js/app/packages/service-clients/service-storage/generated/schemas/soupChannel.ts
new file mode 100644
index 0000000000..d6dfe4d645
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/soupChannel.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ChannelWithParticipants } from './channelWithParticipants';
+import type { LatestMessage } from './latestMessage';
+import type { SoupChannelAllOf } from './soupChannelAllOf';
+
+export type SoupChannel = ChannelWithParticipants & LatestMessage & SoupChannelAllOf;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/soupChannelAllOf.ts b/js/app/packages/service-clients/service-storage/generated/schemas/soupChannelAllOf.ts
new file mode 100644
index 0000000000..154952fb35
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/soupChannelAllOf.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { SoupChannelAllOfInteractedAt } from './soupChannelAllOfInteractedAt';
+import type { SoupChannelAllOfViewedAt } from './soupChannelAllOfViewedAt';
+
+export type SoupChannelAllOf = {
+ interacted_at?: SoupChannelAllOfInteractedAt;
+ viewed_at?: SoupChannelAllOfViewedAt;
+};
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/soupChannelAllOfInteractedAt.ts b/js/app/packages/service-clients/service-storage/generated/schemas/soupChannelAllOfInteractedAt.ts
new file mode 100644
index 0000000000..01cd61667e
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/soupChannelAllOfInteractedAt.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type SoupChannelAllOfInteractedAt = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/soupChannelAllOfViewedAt.ts b/js/app/packages/service-clients/service-storage/generated/schemas/soupChannelAllOfViewedAt.ts
new file mode 100644
index 0000000000..eb28cc17e6
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/soupChannelAllOfViewedAt.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type SoupChannelAllOfViewedAt = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/soupItem.ts b/js/app/packages/service-clients/service-storage/generated/schemas/soupItem.ts
index 014b734ac3..b630920479 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/soupItem.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/soupItem.ts
@@ -8,5 +8,6 @@ import type { SoupItemOneOf } from './soupItemOneOf';
import type { SoupItemOneOfThree } from './soupItemOneOfThree';
import type { SoupItemOneOfFive } from './soupItemOneOfFive';
import type { SoupItemOneOfSeven } from './soupItemOneOfSeven';
+import type { SoupItemOneOfNine } from './soupItemOneOfNine';
-export type SoupItem = SoupItemOneOf | SoupItemOneOfThree | SoupItemOneOfFive | SoupItemOneOfSeven;
+export type SoupItem = SoupItemOneOf | SoupItemOneOfThree | SoupItemOneOfFive | SoupItemOneOfSeven | SoupItemOneOfNine;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/soupItemOneOfNine.ts b/js/app/packages/service-clients/service-storage/generated/schemas/soupItemOneOfNine.ts
new file mode 100644
index 0000000000..52e089b4d3
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/soupItemOneOfNine.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { SoupChannel } from './soupChannel';
+import type { SoupItemOneOfNineTag } from './soupItemOneOfNineTag';
+
+export type SoupItemOneOfNine = {
+ data: SoupChannel;
+ tag: SoupItemOneOfNineTag;
+};
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/soupItemOneOfNineTag.ts b/js/app/packages/service-clients/service-storage/generated/schemas/soupItemOneOfNineTag.ts
new file mode 100644
index 0000000000..878319dd98
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/soupItemOneOfNineTag.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type SoupItemOneOfNineTag = typeof SoupItemOneOfNineTag[keyof typeof SoupItemOneOfNineTag];
+
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const SoupItemOneOfNineTag = {
+ channel: 'channel',
+} as const;
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 9a088efa76..addbea6340 100644
--- a/js/app/packages/service-clients/service-storage/generated/zod.ts
+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts
@@ -1231,6 +1231,9 @@ export const getItemsSoupQueryParams = zod.object({
"cursor": zod.string().optional().describe('Base64 encoded cursor value.')
})
+export const getItemsSoupResponseItemsItemDataChannelOrgIdMin = 0;
+
+
export const getItemsSoupResponse = zod.object({
"items": zod.array(zod.union([zod.object({
"data": zod.object({
@@ -1334,6 +1337,50 @@ export const getItemsSoupResponse = zod.object({
}))
})),
"tag": zod.enum(['emailThread'])
+}),zod.object({
+ "data": zod.object({
+ "channel": zod.object({
+ "channel_type": zod.enum(['public', 'organization', 'private', 'direct_message']),
+ "created_at": zod.string().datetime({}),
+ "id": zod.string().uuid(),
+ "name": zod.string().nullish(),
+ "org_id": zod.number().min(getItemsSoupResponseItemsItemDataChannelOrgIdMin).nullish(),
+ "owner_id": zod.string(),
+ "updated_at": zod.string().datetime({})
+}),
+ "participants": zod.array(zod.object({
+ "channel_id": zod.string().uuid(),
+ "joined_at": zod.string().datetime({}),
+ "left_at": zod.string().datetime({}).nullish(),
+ "role": zod.enum(['owner', 'admin', 'member']),
+ "user_id": zod.string()
+}))
+}).and(zod.object({
+ "latest_message": zod.union([zod.null(),zod.object({
+ "content": zod.string(),
+ "created_at": zod.string().datetime({}),
+ "deleted_at": zod.string().datetime({}).nullish(),
+ "mentions": zod.array(zod.string()).describe('message mentions formatted as `{ENTITY_TYPE}:{ENTITY_ID}`'),
+ "message_id": zod.string().uuid(),
+ "sender_id": zod.string(),
+ "thread_id": zod.string().uuid().nullish(),
+ "updated_at": zod.string().datetime({})
+})]).optional(),
+ "latest_non_thread_message": zod.union([zod.null(),zod.object({
+ "content": zod.string(),
+ "created_at": zod.string().datetime({}),
+ "deleted_at": zod.string().datetime({}).nullish(),
+ "mentions": zod.array(zod.string()).describe('message mentions formatted as `{ENTITY_TYPE}:{ENTITY_ID}`'),
+ "message_id": zod.string().uuid(),
+ "sender_id": zod.string(),
+ "thread_id": zod.string().uuid().nullish(),
+ "updated_at": zod.string().datetime({})
+})]).optional()
+})).and(zod.object({
+ "interacted_at": zod.string().datetime({}).nullish(),
+ "viewed_at": zod.string().datetime({}).nullish()
+})),
+ "tag": zod.enum(['channel'])
})]).and(zod.object({
"frecency_score": zod.number()
}))),
@@ -1389,6 +1436,9 @@ export const postItemsSoupBody = zod.object({
"emailView": zod.string().optional().describe('the view of specific emails to display')
}))
+export const postItemsSoupResponseItemsItemDataChannelOrgIdMin = 0;
+
+
export const postItemsSoupResponse = zod.object({
"items": zod.array(zod.union([zod.object({
"data": zod.object({
@@ -1492,6 +1542,50 @@ export const postItemsSoupResponse = zod.object({
}))
})),
"tag": zod.enum(['emailThread'])
+}),zod.object({
+ "data": zod.object({
+ "channel": zod.object({
+ "channel_type": zod.enum(['public', 'organization', 'private', 'direct_message']),
+ "created_at": zod.string().datetime({}),
+ "id": zod.string().uuid(),
+ "name": zod.string().nullish(),
+ "org_id": zod.number().min(postItemsSoupResponseItemsItemDataChannelOrgIdMin).nullish(),
+ "owner_id": zod.string(),
+ "updated_at": zod.string().datetime({})
+}),
+ "participants": zod.array(zod.object({
+ "channel_id": zod.string().uuid(),
+ "joined_at": zod.string().datetime({}),
+ "left_at": zod.string().datetime({}).nullish(),
+ "role": zod.enum(['owner', 'admin', 'member']),
+ "user_id": zod.string()
+}))
+}).and(zod.object({
+ "latest_message": zod.union([zod.null(),zod.object({
+ "content": zod.string(),
+ "created_at": zod.string().datetime({}),
+ "deleted_at": zod.string().datetime({}).nullish(),
+ "mentions": zod.array(zod.string()).describe('message mentions formatted as `{ENTITY_TYPE}:{ENTITY_ID}`'),
+ "message_id": zod.string().uuid(),
+ "sender_id": zod.string(),
+ "thread_id": zod.string().uuid().nullish(),
+ "updated_at": zod.string().datetime({})
+})]).optional(),
+ "latest_non_thread_message": zod.union([zod.null(),zod.object({
+ "content": zod.string(),
+ "created_at": zod.string().datetime({}),
+ "deleted_at": zod.string().datetime({}).nullish(),
+ "mentions": zod.array(zod.string()).describe('message mentions formatted as `{ENTITY_TYPE}:{ENTITY_ID}`'),
+ "message_id": zod.string().uuid(),
+ "sender_id": zod.string(),
+ "thread_id": zod.string().uuid().nullish(),
+ "updated_at": zod.string().datetime({})
+})]).optional()
+})).and(zod.object({
+ "interacted_at": zod.string().datetime({}).nullish(),
+ "viewed_at": zod.string().datetime({}).nullish()
+})),
+ "tag": zod.enum(['channel'])
})]).and(zod.object({
"frecency_score": zod.number()
}))),
diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.json
index 774ed6a180..4073c246a2 100644
--- a/js/app/packages/service-clients/service-storage/openapi.json
+++ b/js/app/packages/service-clients/service-storage/openapi.json
@@ -4209,6 +4209,29 @@
}
}
},
+ "Channel": {
+ "type": "object",
+ "required": [
+ "id",
+ "channel_type",
+ "created_at",
+ "updated_at",
+ "owner_id"
+ ],
+ "properties": {
+ "channel_type": { "$ref": "#/components/schemas/ChannelType" },
+ "created_at": { "type": "string", "format": "date-time" },
+ "id": { "type": "string", "format": "uuid" },
+ "name": { "type": ["string", "null"] },
+ "org_id": {
+ "type": ["integer", "null"],
+ "format": "int32",
+ "minimum": 0
+ },
+ "owner_id": { "type": "string" },
+ "updated_at": { "type": "string", "format": "date-time" }
+ }
+ },
"ChannelFilters": {
"type": "object",
"description": "The channel message filters used to filter down what channel messages you search over.",
@@ -4240,6 +4263,42 @@
}
}
},
+ "ChannelMessage": {
+ "type": "object",
+ "required": [
+ "message_id",
+ "sender_id",
+ "content",
+ "created_at",
+ "updated_at",
+ "mentions"
+ ],
+ "properties": {
+ "content": { "type": "string" },
+ "created_at": { "type": "string", "format": "date-time" },
+ "deleted_at": { "type": ["string", "null"], "format": "date-time" },
+ "mentions": {
+ "type": "array",
+ "items": { "type": "string" },
+ "description": "message mentions formatted as `{ENTITY_TYPE}:{ENTITY_ID}`"
+ },
+ "message_id": { "type": "string", "format": "uuid" },
+ "sender_id": { "type": "string" },
+ "thread_id": { "type": ["string", "null"], "format": "uuid" },
+ "updated_at": { "type": "string", "format": "date-time" }
+ }
+ },
+ "ChannelParticipant": {
+ "type": "object",
+ "required": ["channel_id", "user_id", "role", "joined_at"],
+ "properties": {
+ "channel_id": { "type": "string", "format": "uuid" },
+ "joined_at": { "type": "string", "format": "date-time" },
+ "left_at": { "type": ["string", "null"], "format": "date-time" },
+ "role": { "$ref": "#/components/schemas/ParticipantRole" },
+ "user_id": { "type": "string" }
+ }
+ },
"ChannelSharePermission": {
"type": "object",
"description": "The channel share permission",
@@ -4252,6 +4311,21 @@
"channel_id": { "type": "string", "description": "The channel id" }
}
},
+ "ChannelType": {
+ "type": "string",
+ "enum": ["public", "organization", "private", "direct_message"]
+ },
+ "ChannelWithParticipants": {
+ "type": "object",
+ "required": ["channel", "participants"],
+ "properties": {
+ "channel": { "$ref": "#/components/schemas/Channel" },
+ "participants": {
+ "type": "array",
+ "items": { "$ref": "#/components/schemas/ChannelParticipant" }
+ }
+ }
+ },
"Chat": {
"type": "object",
"required": [
@@ -6204,6 +6278,23 @@
"userAccessLevel": { "$ref": "#/components/schemas/AccessLevel" }
}
},
+ "LatestMessage": {
+ "type": "object",
+ "properties": {
+ "latest_message": {
+ "oneOf": [
+ { "type": "null" },
+ { "$ref": "#/components/schemas/ChannelMessage" }
+ ]
+ },
+ "latest_non_thread_message": {
+ "oneOf": [
+ { "type": "null" },
+ { "$ref": "#/components/schemas/ChannelMessage" }
+ ]
+ }
+ }
+ },
"LocationResponseData": {
"oneOf": [
{
@@ -6255,6 +6346,10 @@
}
}
},
+ "ParticipantRole": {
+ "type": "string",
+ "enum": ["owner", "admin", "member"]
+ },
"PatchProjectRequestV2": {
"type": "object",
"properties": {
@@ -7047,6 +7142,22 @@
"sizeBytes": { "type": ["integer", "null"], "format": "int64" }
}
},
+ "SoupChannel": {
+ "allOf": [
+ { "$ref": "#/components/schemas/ChannelWithParticipants" },
+ { "$ref": "#/components/schemas/LatestMessage" },
+ {
+ "type": "object",
+ "properties": {
+ "interacted_at": {
+ "type": ["string", "null"],
+ "format": "date-time"
+ },
+ "viewed_at": { "type": ["string", "null"], "format": "date-time" }
+ }
+ }
+ ]
+ },
"SoupChat": {
"type": "object",
"required": [
@@ -7321,13 +7432,17 @@
},
"tag": { "type": "string", "enum": ["emailThread"] }
}
+ },
+ {
+ "type": "object",
+ "required": ["data", "tag"],
+ "properties": {
+ "data": { "$ref": "#/components/schemas/SoupChannel" },
+ "tag": { "type": "string", "enum": ["channel"] }
+ }
}
]
},
- "SoupItemType": {
- "type": "string",
- "enum": ["document", "chat", "project", "email_thread"]
- },
"SoupLabel": {
"type": "object",
"required": [
diff --git a/js/app/packages/websocket/tests/websocket-builder.test.ts b/js/app/packages/websocket/tests/websocket-builder.test.ts
index a8f9ffd9e0..822947b3fc 100644
--- a/js/app/packages/websocket/tests/websocket-builder.test.ts
+++ b/js/app/packages/websocket/tests/websocket-builder.test.ts
@@ -157,7 +157,7 @@ describe('Testsuite for WebSocketBuilder', () => {
const listener = vi.fn();
const builder = new WebsocketBuilder(url).onOpen(listener);
- expect(builder['_options']!['listeners']!.open).toStrictEqual<
+ expect(builder['_options']['listeners']!.open).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Open>[]
>([
{
@@ -184,7 +184,7 @@ describe('Testsuite for WebSocketBuilder', () => {
const builder = new WebsocketBuilder(url)
.onOpen(listener1)
.onOpen(listener2);
- expect(builder['_options']!['listeners']!.open).toStrictEqual<
+ expect(builder['_options']['listeners']!.open).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Open>[]
>([
{
@@ -195,7 +195,7 @@ describe('Testsuite for WebSocketBuilder', () => {
]);
const ws = builder.build();
- expect(ws['_options']!['listeners']!.open).toStrictEqual<
+ expect(ws['_options']['listeners']!.open).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Open>[]
>([
{
@@ -211,12 +211,12 @@ describe('Testsuite for WebSocketBuilder', () => {
const options = { once: true };
const builder = new WebsocketBuilder(url).onOpen(listener, options);
- expect(builder['_options']!['listeners']!.open).toStrictEqual<
+ expect(builder['_options']['listeners']!.open).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Open>[]
>([{ listener, options }]);
const ws = builder.build();
- expect(ws['_options']!['listeners']!.open).toStrictEqual<
+ expect(ws['_options']['listeners']!.open).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Open>[]
>([{ listener, options }]);
});
@@ -229,7 +229,7 @@ describe('Testsuite for WebSocketBuilder', () => {
const builder = new WebsocketBuilder(url)
.onOpen(listener1)
.onOpen(listener2, options);
- expect(builder['_options']!['listeners']!.open).toStrictEqual<
+ expect(builder['_options']['listeners']!.open).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Open>[]
>([
{
@@ -240,7 +240,7 @@ describe('Testsuite for WebSocketBuilder', () => {
]);
const ws = builder.build();
- expect(ws['_options']!['listeners']!.open).toStrictEqual<
+ expect(ws['_options']['listeners']!.open).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Open>[]
>([
{
@@ -255,7 +255,7 @@ describe('Testsuite for WebSocketBuilder', () => {
const listener = vi.fn();
const builder = new WebsocketBuilder(url).onClose(listener);
- expect(builder['_options']!['listeners']!.close).toStrictEqual<
+ expect(builder['_options']['listeners']!.close).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Close>[]
>([
{
@@ -265,7 +265,7 @@ describe('Testsuite for WebSocketBuilder', () => {
]);
const ws = builder.build();
- expect(ws['_options']!['listeners']!.close).toStrictEqual<
+ expect(ws['_options']['listeners']!.close).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Close>[]
>([
{
@@ -282,7 +282,7 @@ describe('Testsuite for WebSocketBuilder', () => {
const builder = new WebsocketBuilder(url)
.onClose(listener1)
.onClose(listener2);
- expect(builder['_options']!['listeners']!.close).toStrictEqual<
+ expect(builder['_options']['listeners']!.close).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Close>[]
>([
{
@@ -293,7 +293,7 @@ describe('Testsuite for WebSocketBuilder', () => {
]);
const ws = builder.build();
- expect(ws['_options']!['listeners']!.close).toStrictEqual<
+ expect(ws['_options']['listeners']!.close).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Close>[]
>([
{
@@ -309,7 +309,7 @@ describe('Testsuite for WebSocketBuilder', () => {
const options = { once: true };
const builder = new WebsocketBuilder(url).onClose(listener, options);
- expect(builder['_options']!['listeners']!.close).toStrictEqual<
+ expect(builder['_options']['listeners']!.close).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Close>[]
>([
{
@@ -319,7 +319,7 @@ describe('Testsuite for WebSocketBuilder', () => {
]);
const ws = builder.build();
- expect(ws['_options']!['listeners']!.close).toStrictEqual<
+ expect(ws['_options']['listeners']!.close).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Close>[]
>([{ listener, options }]);
});
@@ -332,7 +332,7 @@ describe('Testsuite for WebSocketBuilder', () => {
const builder = new WebsocketBuilder(url)
.onClose(listener1)
.onClose(listener2, options);
- expect(builder['_options']!['listeners']!.close).toStrictEqual<
+ expect(builder['_options']['listeners']!.close).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Close>[]
>([
{
@@ -343,7 +343,7 @@ describe('Testsuite for WebSocketBuilder', () => {
]);
const ws = builder.build();
- expect(ws['_options']!['listeners']!.close).toStrictEqual<
+ expect(ws['_options']['listeners']!.close).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Close>[]
>([
{
@@ -358,7 +358,7 @@ describe('Testsuite for WebSocketBuilder', () => {
const listener = vi.fn();
const builder = new WebsocketBuilder(url).onError(listener);
- expect(builder['_options']!['listeners']!.error).toStrictEqual<
+ expect(builder['_options']['listeners']!.error).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Error>[]
>([
{
@@ -368,7 +368,7 @@ describe('Testsuite for WebSocketBuilder', () => {
]);
const ws = builder.build();
- expect(ws['_options']!['listeners']!.error).toStrictEqual<
+ expect(ws['_options']['listeners']!.error).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Error>[]
>([
{
@@ -385,7 +385,7 @@ describe('Testsuite for WebSocketBuilder', () => {
const builder = new WebsocketBuilder(url)
.onError(listener1)
.onError(listener2);
- expect(builder['_options']!['listeners']!.error).toStrictEqual<
+ expect(builder['_options']['listeners']!.error).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Error>[]
>([
{
@@ -396,7 +396,7 @@ describe('Testsuite for WebSocketBuilder', () => {
]);
const ws = builder.build();
- expect(ws['_options']!['listeners']!.error).toStrictEqual<
+ expect(ws['_options']['listeners']!.error).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Error>[]
>([
{
@@ -412,7 +412,7 @@ describe('Testsuite for WebSocketBuilder', () => {
const options = { once: true };
const builder = new WebsocketBuilder(url).onError(listener, options);
- expect(builder['_options']!['listeners']!.error).toStrictEqual<
+ expect(builder['_options']['listeners']!.error).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Error>[]
>([
{
@@ -422,7 +422,7 @@ describe('Testsuite for WebSocketBuilder', () => {
]);
const ws = builder.build();
- expect(ws['_options']!['listeners']!.error).toStrictEqual<
+ expect(ws['_options']['listeners']!.error).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Error>[]
>([{ listener, options }]);
});
@@ -435,7 +435,7 @@ describe('Testsuite for WebSocketBuilder', () => {
const builder = new WebsocketBuilder(url)
.onError(listener1)
.onError(listener2, options);
- expect(builder['_options']!['listeners']!.error).toStrictEqual<
+ expect(builder['_options']['listeners']!.error).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Error>[]
>([
{
@@ -446,7 +446,7 @@ describe('Testsuite for WebSocketBuilder', () => {
]);
const ws = builder.build();
- expect(ws['_options']!['listeners']!.error).toStrictEqual<
+ expect(ws['_options']['listeners']!.error).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Error>[]
>([
{
@@ -461,7 +461,7 @@ describe('Testsuite for WebSocketBuilder', () => {
const listener = vi.fn();
const builder = new WebsocketBuilder(url).onMessage(listener);
- expect(builder['_options']!['listeners']!.message).toStrictEqual<
+ expect(builder['_options']['listeners']!.message).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Message>[]
>([
{
@@ -471,7 +471,7 @@ describe('Testsuite for WebSocketBuilder', () => {
]);
const ws = builder.build();
- expect(ws['_options']!['listeners']!.message).toStrictEqual<
+ expect(ws['_options']['listeners']!.message).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Message>[]
>([
{
@@ -488,7 +488,7 @@ describe('Testsuite for WebSocketBuilder', () => {
const builder = new WebsocketBuilder(url)
.onMessage(listener1)
.onMessage(listener2);
- expect(builder['_options']!['listeners']!.message).toStrictEqual<
+ expect(builder['_options']['listeners']!.message).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Message>[]
>([
{
@@ -499,7 +499,7 @@ describe('Testsuite for WebSocketBuilder', () => {
]);
const ws = builder.build();
- expect(ws['_options']!['listeners']!.message).toStrictEqual<
+ expect(ws['_options']['listeners']!.message).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Message>[]
>([
{
@@ -515,7 +515,7 @@ describe('Testsuite for WebSocketBuilder', () => {
const options = { once: true };
const builder = new WebsocketBuilder(url).onMessage(listener, options);
- expect(builder['_options']!['listeners']!.message).toStrictEqual<
+ expect(builder['_options']['listeners']!.message).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Message>[]
>([
{
@@ -525,7 +525,7 @@ describe('Testsuite for WebSocketBuilder', () => {
]);
const ws = builder.build();
- expect(ws['_options']!['listeners']!.message).toStrictEqual<
+ expect(ws['_options']['listeners']!.message).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Message>[]
>([
{
@@ -543,7 +543,7 @@ describe('Testsuite for WebSocketBuilder', () => {
const builder = new WebsocketBuilder(url)
.onMessage(listener1)
.onMessage(listener2, options);
- expect(builder['_options']!['listeners']!.message).toStrictEqual<
+ expect(builder['_options']['listeners']!.message).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Message>[]
>([
{
@@ -554,7 +554,7 @@ describe('Testsuite for WebSocketBuilder', () => {
]);
const ws = builder.build();
- expect(ws['_options']!['listeners']!.message).toStrictEqual<
+ expect(ws['_options']['listeners']!.message).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Message>[]
>([
{
@@ -569,7 +569,7 @@ describe('Testsuite for WebSocketBuilder', () => {
const listener = vi.fn();
const builder = new WebsocketBuilder(url).onRetry(listener);
- expect(builder['_options']!['listeners']!.retry).toStrictEqual<
+ expect(builder['_options']['listeners']!.retry).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.retry>[]
>([
{
@@ -579,7 +579,7 @@ describe('Testsuite for WebSocketBuilder', () => {
]);
const ws = builder.build();
- expect(ws['_options']!['listeners']!.retry).toStrictEqual<
+ expect(ws['_options']['listeners']!.retry).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.retry>[]
>([
{
@@ -596,7 +596,7 @@ describe('Testsuite for WebSocketBuilder', () => {
const builder = new WebsocketBuilder(url)
.onRetry(listener1)
.onRetry(listener2);
- expect(builder['_options']!['listeners']!.retry).toStrictEqual<
+ expect(builder['_options']['listeners']!.retry).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.retry>[]
>([
{
@@ -607,7 +607,7 @@ describe('Testsuite for WebSocketBuilder', () => {
]);
const ws = builder.build();
- expect(ws['_options']!['listeners']!.retry).toStrictEqual<
+ expect(ws['_options']['listeners']!.retry).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.retry>[]
>([
{
@@ -623,7 +623,7 @@ describe('Testsuite for WebSocketBuilder', () => {
const options = { once: true };
const builder = new WebsocketBuilder(url).onRetry(listener, options);
- expect(builder['_options']!['listeners']!.retry).toStrictEqual<
+ expect(builder['_options']['listeners']!.retry).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.retry>[]
>([
{
@@ -633,7 +633,7 @@ describe('Testsuite for WebSocketBuilder', () => {
]);
const ws = builder.build();
- expect(ws['_options']!['listeners']!.retry).toStrictEqual<
+ expect(ws['_options']['listeners']!.retry).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.retry>[]
>([{ listener, options }]);
});
@@ -646,7 +646,7 @@ describe('Testsuite for WebSocketBuilder', () => {
const builder = new WebsocketBuilder(url)
.onRetry(listener1)
.onRetry(listener2, options);
- expect(builder['_options']!['listeners']!.retry).toStrictEqual<
+ expect(builder['_options']['listeners']!.retry).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.retry>[]
>([
{
@@ -657,7 +657,7 @@ describe('Testsuite for WebSocketBuilder', () => {
]);
const ws = builder.build();
- expect(ws['_options']!['listeners']!.retry).toStrictEqual<
+ expect(ws['_options']['listeners']!.retry).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.retry>[]
>([
{
@@ -672,7 +672,7 @@ describe('Testsuite for WebSocketBuilder', () => {
const listener = vi.fn();
const builder = new WebsocketBuilder(url).onReconnect(listener);
- expect(builder['_options']!['listeners']!.reconnect).toStrictEqual<
+ expect(builder['_options']['listeners']!.reconnect).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Reconnect>[]
>([
{
@@ -682,7 +682,7 @@ describe('Testsuite for WebSocketBuilder', () => {
]);
const ws = builder.build();
- expect(ws['_options']!['listeners']!.reconnect).toStrictEqual<
+ expect(ws['_options']['listeners']!.reconnect).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Reconnect>[]
>([
{
@@ -699,7 +699,7 @@ describe('Testsuite for WebSocketBuilder', () => {
const builder = new WebsocketBuilder(url)
.onReconnect(listener1)
.onReconnect(listener2);
- expect(builder['_options']!['listeners']!.reconnect).toStrictEqual<
+ expect(builder['_options']['listeners']!.reconnect).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Reconnect>[]
>([
{
@@ -710,7 +710,7 @@ describe('Testsuite for WebSocketBuilder', () => {
]);
const ws = builder.build();
- expect(ws['_options']!['listeners']!.reconnect).toStrictEqual<
+ expect(ws['_options']['listeners']!.reconnect).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Reconnect>[]
>([
{
@@ -726,7 +726,7 @@ describe('Testsuite for WebSocketBuilder', () => {
const options = { once: true };
const builder = new WebsocketBuilder(url).onReconnect(listener, options);
- expect(builder['_options']!['listeners']!.reconnect).toStrictEqual<
+ expect(builder['_options']['listeners']!.reconnect).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Reconnect>[]
>([
{
@@ -736,7 +736,7 @@ describe('Testsuite for WebSocketBuilder', () => {
]);
const ws = builder.build();
- expect(ws['_options']!['listeners']!.reconnect).toStrictEqual<
+ expect(ws['_options']['listeners']!.reconnect).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Reconnect>[]
>([
{
@@ -754,7 +754,7 @@ describe('Testsuite for WebSocketBuilder', () => {
const builder = new WebsocketBuilder(url)
.onReconnect(listener1)
.onReconnect(listener2, options);
- expect(builder['_options']!['listeners']!.reconnect).toStrictEqual<
+ expect(builder['_options']['listeners']!.reconnect).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Reconnect>[]
>([
{
@@ -765,7 +765,7 @@ describe('Testsuite for WebSocketBuilder', () => {
]);
const ws = builder.build();
- expect(ws['_options']!['listeners']!.reconnect).toStrictEqual<
+ expect(ws['_options']['listeners']!.reconnect).toStrictEqual<
WebsocketEventListenerWithOptions<WebsocketEvent.Reconnect>[]
>([
{
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index fa3934429a..dab070fd0d 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -1776,6 +1776,30 @@ dependencies = [
"tokio-util",
]
+[[package]]
+name = "comms"
+version = "0.1.0"
+dependencies = [
+ "axum",
+ "chrono",
+ "doppleganger",
+ "frecency",
+ "macro_user_id",
+ "model-entity",
+ "model_user",
+ "models_comms",
+ "reqwest",
+ "rootcause",
+ "serde",
+ "serde_json",
+ "sqlx",
+ "thiserror 2.0.17",
+ "tokio",
+ "tracing",
+ "utoipa",
+ "uuid",
+]
+
[[package]]
name = "comms_db_client"
version = "0.1.0"
@@ -1783,11 +1807,13 @@ dependencies = [
"anyhow",
"cached",
"chrono",
+ "doppleganger",
"futures",
"macro_db_migrator",
"macro_user_id",
"macro_uuid",
"model",
+ "models_comms",
"serde",
"serde_json",
"sqlx",
@@ -1812,9 +1838,11 @@ dependencies = [
"axum-extra",
"axum-macros",
"chrono",
+ "comms",
"comms_db_client",
"connection_gateway",
"document_storage_service_client",
+ "doppleganger",
"frecency",
"futures",
"http-body-util",
@@ -2559,6 +2587,7 @@ dependencies = [
"dashmap",
"document_cognition_service_client",
"document_storage_service_client",
+ "doppleganger",
"email_service_client",
"futures",
"http-body-util",
@@ -2640,6 +2669,7 @@ dependencies = [
"chrono",
"clap",
"cloudfront_sign",
+ "comms",
"comms_service_client",
"connection_gateway",
"cool_asserts",
@@ -3741,7 +3771,7 @@ dependencies = [
"futures-sink",
"futures-util",
"http 0.2.12",
- "indexmap 2.7.1",
+ "indexmap 2.12.1",
"slab",
"tokio",
"tokio-util",
@@ -3760,7 +3790,7 @@ dependencies = [
"futures-core",
"futures-sink",
"http 1.3.1",
- "indexmap 2.7.1",
+ "indexmap 2.12.1",
"slab",
"tokio",
"tokio-util",
@@ -3804,6 +3834,12 @@ dependencies = [
"foldhash",
]
+[[package]]
+name = "hashbrown"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
+
[[package]]
name = "hashlink"
version = "0.10.0"
@@ -4370,13 +4406,14 @@ dependencies = [
[[package]]
name = "indexmap"
-version = "2.7.1"
+version = "2.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8c9c992b02b5b4c94ea26e32fe5bccb7aa7d9f390ab5c1221ff895bc7ea8b652"
+checksum = "0ad4bb2b565bca0645f4d68c5c9af97fba094e9791da685bf83cb5f3ce74acf2"
dependencies = [
"equivalent",
- "hashbrown 0.15.2",
+ "hashbrown 0.16.1",
"serde",
+ "serde_core",
]
[[package]]
@@ -5404,6 +5441,7 @@ dependencies = [
"base64 0.22.1",
"chrono",
"document_sub_type",
+ "doppleganger",
"macro_user_id",
"model-error-response",
"model_file_type",
@@ -5462,6 +5500,7 @@ version = "0.1.0"
dependencies = [
"anyhow",
"chrono",
+ "doppleganger",
"macro_user_id",
"model-entity",
"models_comms",
@@ -5502,12 +5541,12 @@ version = "0.1.0"
dependencies = [
"anyhow",
"chrono",
+ "doppleganger",
+ "frecency",
+ "macro_user_id",
"serde",
- "serde_json",
- "sqlx",
"strum",
"thiserror 2.0.17",
- "utoipa",
"uuid",
]
@@ -5656,6 +5695,7 @@ version = "0.1.0"
dependencies = [
"anyhow",
"chrono",
+ "comms",
"document_sub_type",
"doppleganger",
"email",
@@ -7211,6 +7251,28 @@ dependencies = [
"tracing",
]
+[[package]]
+name = "rootcause"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "19b2fa24b30d915f807d1a14eb9eb0947fad76d6e63f165f3969e61a2942a928"
+dependencies = [
+ "hashbrown 0.16.1",
+ "indexmap 2.12.1",
+ "rootcause-internals",
+ "rustc-hash 2.1.1",
+ "triomphe",
+]
+
+[[package]]
+name = "rootcause-internals"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "15e09e790e6a1ade68d035e081be5054b03b9329a7b568ea5707c4395053b778"
+dependencies = [
+ "triomphe",
+]
+
[[package]]
name = "rs-libreoffice-bindings"
version = "0.0.7"
@@ -7531,6 +7593,7 @@ dependencies = [
"derive_builder",
"document_cognition_service_client",
"document_storage_service_client",
+ "doppleganger",
"email_service_client",
"futures",
"image",
@@ -7630,7 +7693,7 @@ dependencies = [
"email_service_client",
"futures",
"http-body-util",
- "indexmap 2.7.1",
+ "indexmap 2.12.1",
"item_filters",
"macro_auth",
"macro_cors",
@@ -7958,7 +8021,7 @@ dependencies = [
"chrono",
"hex",
"indexmap 1.9.3",
- "indexmap 2.7.1",
+ "indexmap 2.12.1",
"serde",
"serde_derive",
"serde_json",
@@ -8235,6 +8298,7 @@ dependencies = [
"axum",
"axum-extra",
"chrono",
+ "comms",
"cool_asserts",
"document_sub_type",
"doppleganger",
@@ -8256,6 +8320,7 @@ dependencies = [
"non_empty",
"ordered-float",
"recursion",
+ "rootcause",
"serde",
"serde_json",
"sqlx",
@@ -8328,7 +8393,7 @@ dependencies = [
"futures-util",
"hashbrown 0.15.2",
"hashlink",
- "indexmap 2.7.1",
+ "indexmap 2.12.1",
"log",
"memchr",
"native-tls",
@@ -9223,6 +9288,12 @@ dependencies = [
"tracing-subscriber",
]
+[[package]]
+name = "triomphe"
+version = "0.1.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dd69c5aa8f924c7519d6372789a74eac5b94fb0f8fcf0d4a97eb0bfc3e785f39"
+
[[package]]
name = "try-lock"
version = "0.2.5"
@@ -9536,7 +9607,7 @@ version = "5.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "435c6f69ef38c9017b4b4eea965dfb91e71e53d869e896db40d1cf2441dd75c0"
dependencies = [
- "indexmap 2.7.1",
+ "indexmap 2.12.1",
"serde",
"serde_json",
"utoipa-gen",
@@ -10340,7 +10411,7 @@ dependencies = [
"flate2",
"getrandom 0.3.1",
"hmac",
- "indexmap 2.7.1",
+ "indexmap 2.12.1",
"lzma-rs",
"memchr",
"pbkdf2",
diff --git a/rust/cloud-storage/authentication_service_client/src/get_names.rs b/rust/cloud-storage/authentication_service_client/src/get_names.rs
deleted file mode 100644
index 40d7391973..0000000000
--- a/rust/cloud-storage/authentication_service_client/src/get_names.rs
+++ /dev/null
@@ -1,64 +0,0 @@
-use std::collections::HashSet;
-
-use crate::AuthServiceClient;
-use crate::error::{AuthServiceClientError, GenericErrorResponse};
-use anyhow::Result;
-use model::comms::ChannelWithParticipants;
-use model::user::UserNames;
-
-// HACK: duplicate code, should probably move this to model at some point
-#[derive(Default, Debug, serde::Serialize, serde::Deserialize)]
-pub struct PostGetNamesRequestBody {
- pub user_ids: Vec<String>,
-}
-
-impl AuthServiceClient {
- pub async fn get_names(&self, user_ids: Vec<String>) -> Result<UserNames> {
- let body = PostGetNamesRequestBody { user_ids };
-
- let res = self
- .client
- .post(format!("{}/internal/get_names", self.url))
- .json(&body)
- .send()
- .await
- .map_err(|e| AuthServiceClientError::RequestBuildError {
- details: e.to_string(),
- })?;
-
- match res.status() {
- reqwest::StatusCode::OK => {
- let result = res.json::<UserNames>().await.map_err(|e| {
- AuthServiceClientError::Generic(GenericErrorResponse {
- message: e.to_string(),
- })
- })?;
- Ok(result)
- }
- status_code => {
- let body: String = res.text().await?;
- tracing::error!(
- body=%body,
- status=%status_code,
- "unexpected response from authentication service"
- );
- Err(anyhow::anyhow!(body))
- }
- }
- }
-
- #[tracing::instrument(err, skip(self))]
- pub async fn get_names_from_channels(
- &self,
- channels: &Vec<ChannelWithParticipants>,
- ) -> Result<UserNames> {
- let mut user_ids: HashSet<String> = HashSet::new();
- for channel in channels {
- for p in &channel.participants {
- user_ids.insert(p.user_id.clone());
- }
- }
-
- self.get_names(user_ids.into_iter().collect()).await
- }
-}
diff --git a/rust/cloud-storage/authentication_service_client/src/lib.rs b/rust/cloud-storage/authentication_service_client/src/lib.rs
index c68fcca450..376e30fbed 100644
--- a/rust/cloud-storage/authentication_service_client/src/lib.rs
+++ b/rust/cloud-storage/authentication_service_client/src/lib.rs
@@ -1,5 +1,4 @@
pub mod error;
-pub mod get_names;
pub mod google_access_token;
pub mod unlink;
pub mod users;
diff --git a/rust/cloud-storage/comms_db_client/.sqlx/query-23a3f847d9d017fb9e5faf9e8b7b0ed6fc3621a443b76867e7b193453cfae7eb.json b/rust/cloud-storage/comms/.sqlx/query-23a3f847d9d017fb9e5faf9e8b7b0ed6fc3621a443b76867e7b193453cfae7eb.json
similarity index 100%
rename from rust/cloud-storage/comms_db_client/.sqlx/query-23a3f847d9d017fb9e5faf9e8b7b0ed6fc3621a443b76867e7b193453cfae7eb.json
rename to rust/cloud-storage/comms/.sqlx/query-23a3f847d9d017fb9e5faf9e8b7b0ed6fc3621a443b76867e7b193453cfae7eb.json
diff --git a/rust/cloud-storage/comms_db_client/.sqlx/query-7ee9ba5adfac304c7ac930943538ecca7428b1054d451fb2f8973cf9c11caf45.json b/rust/cloud-storage/comms/.sqlx/query-7ee9ba5adfac304c7ac930943538ecca7428b1054d451fb2f8973cf9c11caf45.json
similarity index 100%
rename from rust/cloud-storage/comms_db_client/.sqlx/query-7ee9ba5adfac304c7ac930943538ecca7428b1054d451fb2f8973cf9c11caf45.json
rename to rust/cloud-storage/comms/.sqlx/query-7ee9ba5adfac304c7ac930943538ecca7428b1054d451fb2f8973cf9c11caf45.json
diff --git a/rust/cloud-storage/comms_db_client/.sqlx/query-9afc6f436aedd226ed0d6bf85de64c5ff57853c93ff00f768b49bf79f198590b.json b/rust/cloud-storage/comms/.sqlx/query-9afc6f436aedd226ed0d6bf85de64c5ff57853c93ff00f768b49bf79f198590b.json
similarity index 100%
rename from rust/cloud-storage/comms_db_client/.sqlx/query-9afc6f436aedd226ed0d6bf85de64c5ff57853c93ff00f768b49bf79f198590b.json
rename to rust/cloud-storage/comms/.sqlx/query-9afc6f436aedd226ed0d6bf85de64c5ff57853c93ff00f768b49bf79f198590b.json
diff --git a/rust/cloud-storage/comms/Cargo.toml b/rust/cloud-storage/comms/Cargo.toml
new file mode 100644
index 0000000000..72678a25be
--- /dev/null
+++ b/rust/cloud-storage/comms/Cargo.toml
@@ -0,0 +1,30 @@
+[package]
+edition = "2024"
+name = "comms"
+publish = false
+version = "0.1.0"
+
+[features]
+inbound = ["dep:axum", "dep:model_user", "dep:reqwest", "dep:utoipa"]
+outbound = ["dep:reqwest"]
+
+
+[dependencies]
+axum = { workspace = true, optional = true }
+chrono = { workspace = true }
+doppleganger = { workspace = true, features = ["chrono", "uuid"] }
+frecency = { path = "../frecency", features = ["ports"] }
+macro_user_id = { path = "../macro_user_id" }
+model-entity = { path = "../model-entity" }
+model_user = { path = "../model_user", optional = true, features = ["axum"] }
+models_comms = { path = "../models_comms" }
+reqwest = { workspace = true, optional = true }
+rootcause = "0.11"
+serde = { workspace = true }
+serde_json = { workspace = true }
+sqlx = { workspace = true }
+thiserror = { workspace = true }
+tokio = { workspace = true }
+tracing = { workspace = true }
+utoipa = { workspace = true, optional = true }
+uuid = { workspace = true }
diff --git a/rust/cloud-storage/comms/src/domain.rs b/rust/cloud-storage/comms/src/domain.rs
new file mode 100644
index 0000000000..901e625fda
--- /dev/null
+++ b/rust/cloud-storage/comms/src/domain.rs
@@ -0,0 +1,3 @@
+pub mod models;
+pub mod ports;
+pub mod service;
diff --git a/rust/cloud-storage/comms/src/domain/models.rs b/rust/cloud-storage/comms/src/domain/models.rs
new file mode 100644
index 0000000000..fabc786424
--- /dev/null
+++ b/rust/cloud-storage/comms/src/domain/models.rs
@@ -0,0 +1,37 @@
+use macro_user_id::user_id::MacroUserIdStr;
+pub use models_comms::*;
+use serde::Deserialize;
+use uuid::Uuid;
+
+pub mod channel_name;
+
+pub struct ChannelPreviewsRequest<'a> {
+ pub channel_ids: &'a [Uuid],
+ pub user: MacroUserIdStr<'a>,
+ pub organization_id: Option<channel::OrganizationId>,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct UserName {
+ pub id: MacroUserIdStr<'static>,
+ pub first_name: Option<String>,
+ pub last_name: Option<String>,
+}
+
+impl UserName {
+ /// attempt to create the "pretty" name for this user
+ /// this can return None if the first name and last name dont exist
+ /// or if they are set to "N/A" which is apparrently something that can happen
+ pub fn display_name(&self) -> Option<String> {
+ const NA: &str = "N/A";
+ match (
+ self.first_name.as_deref().filter(|v| *v != NA),
+ self.last_name.as_deref().filter(|v| *v != NA),
+ ) {
+ (None, None) => None,
+ (None, Some(last)) => Some(last.to_string()),
+ (Some(first), None) => Some(first.to_string()),
+ (Some(first), Some(last)) => Some(format!("{first} {last}")),
+ }
+ }
+}
diff --git a/rust/cloud-storage/comms/src/domain/models/channel_name.rs b/rust/cloud-storage/comms/src/domain/models/channel_name.rs
new file mode 100644
index 0000000000..ad79d1bdcb
--- /dev/null
+++ b/rust/cloud-storage/comms/src/domain/models/channel_name.rs
@@ -0,0 +1,81 @@
+use macro_user_id::{cowlike::CowLike, email::ReadEmailParts, user_id::MacroUserIdStr};
+use models_comms::channel::{ChannelId, ChannelParticipant, ChannelType};
+use std::collections::HashMap;
+use uuid::Uuid;
+
+pub type ChannelName = String;
+pub type NameLookup = HashMap<MacroUserIdStr<'static>, String>;
+
+#[cfg(test)]
+mod tests;
+
+pub fn resolve_channel_name(
+ channel_type: &ChannelType,
+ channel_name: Option<&str>,
+ participants: &[ChannelParticipant],
+ channel_id: &ChannelId,
+ user_id: MacroUserIdStr<'_>,
+ name_lookup: &NameLookup,
+) -> ChannelName {
+ match channel_type {
+ ChannelType::Organization | ChannelType::Public => channel_name.map(|name| name.to_string()).unwrap_or_else(|| {
+ tracing::warn!(channel_id=?channel_id, "organization or public channel should have a name");
+ match channel_type {
+ ChannelType::Organization => "Organization".to_string(),
+ ChannelType::Public => "Public".to_string(),
+ _ => unreachable!(),
+ }
+ }),
+ ChannelType::Private => resolve_private_channel_name(channel_name, participants, name_lookup),
+ ChannelType::DirectMessage => resolve_direct_message_channel_name(channel_name, participants, &channel_id.0, user_id, name_lookup),
+ }
+}
+
+pub fn resolve_private_channel_name(
+ channel_name: Option<&str>,
+ participants: &[ChannelParticipant],
+ name_lookup: &NameLookup,
+) -> ChannelName {
+ if let Some(name) = &channel_name {
+ return name.to_string();
+ }
+
+ participants
+ .iter()
+ .map(|p| id_to_display_name(p.user_id.copied(), name_lookup))
+ .collect::<Vec<String>>()
+ .join(", ")
+}
+
+pub fn resolve_direct_message_channel_name(
+ channel_name: Option<&str>,
+ participants: &[ChannelParticipant],
+ channel_id: &Uuid,
+ user_id: MacroUserIdStr<'_>,
+ name_lookup: &NameLookup,
+) -> ChannelName {
+ // Direct Message Channels should not have a name
+ if channel_name.is_some() {
+ tracing::warn!(channel_id=?channel_id, "direct message channel should not have a name");
+ }
+
+ if !participants.iter().any(|p| p.user_id == user_id) {
+ return resolve_private_channel_name(channel_name, participants, name_lookup);
+ }
+
+ let other_participant = participants.iter().find(|p| p.user_id != user_id);
+
+ if let Some(other) = other_participant {
+ id_to_display_name(other.user_id.copied(), name_lookup)
+ } else {
+ tracing::error!(channel_id=?channel_id, "no other participant found, in a direct message channel");
+ "Unknown".to_string()
+ }
+}
+
+fn id_to_display_name(id: MacroUserIdStr<'_>, name_lookup: &NameLookup) -> String {
+ match name_lookup.get(&id) {
+ Some(name) => name.clone(),
+ None => id.email_part().local_part().to_string(),
+ }
+}
diff --git a/rust/cloud-storage/comms/src/domain/models/channel_name/tests.rs b/rust/cloud-storage/comms/src/domain/models/channel_name/tests.rs
new file mode 100644
index 0000000000..517b4ae266
--- /dev/null
+++ b/rust/cloud-storage/comms/src/domain/models/channel_name/tests.rs
@@ -0,0 +1,169 @@
+use super::*;
+use macro_user_id::user_id::MacroUserIdStr;
+use models_comms::channel::{Channel, ChannelId, ChannelType};
+use uuid::Uuid;
+
+fn make_participants(channel_id: &Uuid) -> Vec<ChannelParticipant> {
+ vec![
+ ChannelParticipant {
+ channel_id: ChannelId(channel_id.to_owned()),
+ user_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ role: models_comms::channel::ParticipantRole::Owner,
+ joined_at: chrono::Utc::now(),
+ left_at: None,
+ },
+ ChannelParticipant {
+ channel_id: ChannelId(channel_id.to_owned()),
+ user_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ role: models_comms::channel::ParticipantRole::Member,
+ joined_at: chrono::Utc::now(),
+ left_at: None,
+ },
+ ]
+}
+
+#[test]
+fn test_resolve_private_channel_name() {
+ let channel_with_name = Channel {
+ id: ChannelId(Uuid::default()),
+ name: Some("test".to_string()),
+ channel_type: ChannelType::Private,
+ org_id: None,
+ created_at: chrono::Utc::now(),
+ updated_at: chrono::Utc::now(),
+ owner_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ };
+
+ let channel_without_name = Channel {
+ id: ChannelId(Uuid::default()),
+ name: None,
+ channel_type: ChannelType::Private,
+ org_id: None,
+ created_at: chrono::Utc::now(),
+ updated_at: chrono::Utc::now(),
+ owner_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ };
+
+ let participants_with_name = make_participants(&channel_with_name.id.0);
+ let participants_without_name = make_participants(&channel_without_name.id.0);
+
+ assert_eq!(
+ resolve_private_channel_name(
+ channel_with_name.name.as_deref(),
+ &participants_with_name,
+ &Default::default()
+ ),
+ "test"
+ );
+ assert_eq!(
+ resolve_private_channel_name(
+ channel_without_name.name.as_deref(),
+ &participants_without_name,
+ &Default::default()
+ ),
+ "user1, user2"
+ );
+}
+
+#[test]
+fn test_resolve_direct_message_channel_name() {
+ let direct_message_channel = Channel {
+ id: ChannelId(Default::default()),
+ name: None,
+ channel_type: ChannelType::DirectMessage,
+ org_id: None,
+ created_at: chrono::Utc::now(),
+ updated_at: chrono::Utc::now(),
+ owner_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ };
+
+ let participants = make_participants(&direct_message_channel.id.0);
+
+ assert_eq!(
+ resolve_direct_message_channel_name(
+ direct_message_channel.name.as_deref(),
+ &participants,
+ &direct_message_channel.id.0,
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ &Default::default()
+ ),
+ "user2"
+ );
+}
+
+#[test]
+fn test_resolve_direct_message_channel_name_for_other() {
+ let direct_message_channel = Channel {
+ id: ChannelId(Default::default()),
+ name: None,
+ channel_type: ChannelType::DirectMessage,
+ org_id: None,
+ created_at: chrono::Utc::now(),
+ updated_at: chrono::Utc::now(),
+ owner_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ };
+
+ // Test the preview for a user who is not in the channel
+ let participants = make_participants(&direct_message_channel.id.0);
+
+ assert_eq!(
+ resolve_direct_message_channel_name(
+ direct_message_channel.name.as_deref(),
+ &participants,
+ &direct_message_channel.id.0,
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ &Default::default()
+ ),
+ "user1, user2"
+ );
+}
+
+#[test]
+fn test_resolve_organization_and_public_channel_name() {
+ let organization_channel = Channel {
+ id: ChannelId(Default::default()),
+ name: Some("organization_channel".to_string()),
+ channel_type: ChannelType::Organization,
+ org_id: None,
+ created_at: chrono::Utc::now(),
+ updated_at: chrono::Utc::now(),
+ owner_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ };
+
+ let public_channel = Channel {
+ id: ChannelId(Default::default()),
+ name: Some("public_channel".to_string()),
+ channel_type: ChannelType::Public,
+ org_id: None,
+ created_at: chrono::Utc::now(),
+ updated_at: chrono::Utc::now(),
+ owner_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ };
+
+ let org_participants = make_participants(&organization_channel.id.0);
+ let pub_participants = make_participants(&public_channel.id.0);
+
+ assert_eq!(
+ resolve_channel_name(
+ &organization_channel.channel_type,
+ organization_channel.name.as_deref(),
+ &org_participants,
+ &organization_channel.id,
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ &Default::default()
+ ),
+ "organization_channel"
+ );
+
+ assert_eq!(
+ resolve_channel_name(
+ &public_channel.channel_type,
+ public_channel.name.as_deref(),
+ &pub_participants,
+ &public_channel.id,
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ &Default::default()
+ ),
+ "public_channel"
+ );
+}
diff --git a/rust/cloud-storage/comms/src/domain/ports.rs b/rust/cloud-storage/comms/src/domain/ports.rs
new file mode 100644
index 0000000000..a46cfb7276
--- /dev/null
+++ b/rust/cloud-storage/comms/src/domain/ports.rs
@@ -0,0 +1,50 @@
+use std::collections::{HashMap, HashSet};
+
+use macro_user_id::user_id::MacroUserIdStr;
+use models_comms::channel::{
+ Activity, ChannelId, ChannelWithLatest, ChannelWithParticipants, LatestMessage,
+};
+use rootcause::Report;
+
+use crate::domain::models::UserName;
+
+pub trait CommsRepo: Send + Sync + 'static {
+ fn get_user_channels_with_participants(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<Vec<ChannelWithParticipants>, Report>> + Send;
+
+ fn get_latest_channel_messages_batch(
+ &self,
+ channels: &[ChannelId],
+ ) -> impl Future<Output = Result<HashMap<ChannelId, LatestMessage>, Report>> + Send;
+
+ fn get_activities(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<Vec<Activity>, Report>> + Send;
+}
+
+pub trait UserRepo: Send + Sync + 'static {
+ fn get_names_for_ids(
+ &self,
+ names: HashSet<MacroUserIdStr<'_>>,
+ ) -> impl Future<Output = Result<Vec<UserName>, Report>> + Send;
+}
+
+pub trait ChannelsService: Send + Sync + 'static {
+ fn get_channels(
+ &self,
+ user: MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<Vec<ChannelWithLatest>, Report>> + Send;
+
+ fn get_activities(
+ &self,
+ user: MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<Vec<Activity>, Report>> + Send;
+
+ fn get_names(
+ &self,
+ names: HashSet<MacroUserIdStr<'_>>,
+ ) -> impl Future<Output = Result<Vec<UserName>, Report>> + Send;
+}
diff --git a/rust/cloud-storage/comms/src/domain/service.rs b/rust/cloud-storage/comms/src/domain/service.rs
new file mode 100644
index 0000000000..9bb448dde7
--- /dev/null
+++ b/rust/cloud-storage/comms/src/domain/service.rs
@@ -0,0 +1,142 @@
+use std::{
+ collections::{HashMap, HashSet},
+ str::FromStr,
+};
+
+use frecency::domain::{models::AggregateFrecency, ports::AggregateFrecencyStorage};
+use macro_user_id::cowlike::CowLike;
+use model_entity::EntityType;
+use models_comms::channel::{Activity, ChannelId, ChannelWithLatest};
+use uuid::Uuid;
+
+use crate::domain::{
+ models::channel_name::resolve_channel_name,
+ ports::{ChannelsService, CommsRepo, UserRepo},
+};
+
+pub struct ChannelServiceImpl<Comms, Auth, Frec> {
+ comms: Comms,
+ auth: Auth,
+ frecency: Frec,
+}
+
+impl<Comms, Auth, Frec> ChannelServiceImpl<Comms, Auth, Frec>
+where
+ Comms: CommsRepo,
+ Auth: UserRepo,
+ Frec: AggregateFrecencyStorage,
+{
+ pub fn new(comms: Comms, auth: Auth, frecency: Frec) -> Self {
+ ChannelServiceImpl {
+ comms,
+ auth,
+ frecency,
+ }
+ }
+}
+
+impl<Comms, Auth, Frec> ChannelsService for ChannelServiceImpl<Comms, Auth, Frec>
+where
+ Comms: CommsRepo,
+ Auth: UserRepo,
+ Frec: AggregateFrecencyStorage,
+{
+ #[tracing::instrument(err, skip(self))]
+ async fn get_channels(
+ &self,
+ user: macro_user_id::user_id::MacroUserIdStr<'_>,
+ ) -> Result<Vec<models_comms::channel::ChannelWithLatest>, rootcause::Report> {
+ let channels = self
+ .comms
+ .get_user_channels_with_participants(user.copied())
+ .await?;
+
+ let channel_entities: Vec<_> = channels
+ .iter()
+ .map(|chan| EntityType::Channel.with_entity_string(chan.channel.id.0.to_string()))
+ .collect();
+
+ let channel_ids: Vec<_> = channels.iter().map(|chan| chan.channel.id).collect();
+
+ let participant_ids: HashSet<_> = channels
+ .iter()
+ .flat_map(|chan| chan.participants.iter().map(|p| p.user_id.copied()))
+ .collect();
+
+ let (names, latest_messages, activities, frecency) = tokio::join!(
+ self.auth.get_names_for_ids(participant_ids),
+ self.comms.get_latest_channel_messages_batch(&channel_ids),
+ self.comms.get_activities(user.copied()),
+ self.frecency
+ .get_aggregate_for_user_entities(user.clone(), channel_entities.as_slice())
+ );
+
+ let mut activity_lookup: HashMap<ChannelId, Activity> = activities
+ .unwrap_or_default()
+ .into_iter()
+ .map(|a| (a.channel_id, a))
+ .collect();
+
+ let mut frecency_map: HashMap<ChannelId, AggregateFrecency> = frecency
+ .unwrap_or_default()
+ .into_iter()
+ .filter_map(|f| Some((ChannelId(Uuid::from_str(&f.id.entity.entity_id).ok()?), f)))
+ .collect();
+
+ let name_lookup = names.map(|n| {
+ n.into_iter()
+ .filter_map(|n| {
+ let display = n.display_name()?;
+ Some((n.id, display))
+ })
+ .collect::<HashMap<_, _>>()
+ })?;
+
+ let mut latest_messages = latest_messages?;
+
+ // Map a channel to its correct name and latest message
+ let channels: Vec<ChannelWithLatest> = channels
+ .into_iter()
+ .map(|mut channel| {
+ let resolved_name = resolve_channel_name(
+ &channel.channel.channel_type,
+ channel.channel.name.as_deref(),
+ &channel.participants,
+ &channel.channel.id,
+ user.copied(),
+ &name_lookup,
+ );
+ channel.channel.name = Some(resolved_name);
+ let activity = activity_lookup.remove(&channel.channel.id);
+ let viewed_at = activity.as_ref().and_then(|a| a.viewed_at);
+ let interacted_at = activity.as_ref().and_then(|a| a.interacted_at);
+ let channel_with_latest = ChannelWithLatest {
+ channel: channel.clone(),
+ latest_message: latest_messages.remove(&channel.channel.id).unwrap_or_default(),
+ viewed_at,
+ interacted_at,
+ frecency_score: frecency_map.remove(&channel.channel.id)
+ };
+
+ tracing::trace!(channel_type=?channel.channel.channel_type,channel_name=?channel.channel.name, "resolved channel name");
+ channel_with_latest
+ })
+ .collect();
+
+ Ok(channels)
+ }
+
+ fn get_activities(
+ &self,
+ user: macro_user_id::user_id::MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<Vec<Activity>, rootcause::Report>> + Send {
+ self.comms.get_activities(user)
+ }
+
+ fn get_names(
+ &self,
+ names: HashSet<macro_user_id::user_id::MacroUserIdStr<'_>>,
+ ) -> impl Future<Output = Result<Vec<super::models::UserName>, rootcause::Report>> + Send {
+ self.auth.get_names_for_ids(names)
+ }
+}
diff --git a/rust/cloud-storage/comms/src/inbound.rs b/rust/cloud-storage/comms/src/inbound.rs
new file mode 100644
index 0000000000..c9ee16742e
--- /dev/null
+++ b/rust/cloud-storage/comms/src/inbound.rs
@@ -0,0 +1,224 @@
+use axum::{Json, Router, extract::State, http::StatusCode, response::IntoResponse, routing::get};
+use doppleganger::{Doppleganger, Mirror};
+use frecency::domain::models::AggregateFrecency;
+use macro_user_id::user_id::MacroUserIdStr;
+use model_user::axum_extractor::MacroUserExtractor;
+use models_comms::channel::{ChannelId, OrganizationId};
+use serde::Serialize;
+use std::sync::Arc;
+use thiserror::Error;
+use utoipa::ToSchema;
+use uuid::Uuid;
+
+use crate::domain::ports::ChannelsService;
+
+pub struct CommsRouterState<S> {
+ pub inner: Arc<S>,
+}
+
+impl<S> Clone for CommsRouterState<S> {
+ fn clone(&self) -> Self {
+ Self {
+ inner: Arc::clone(&self.inner),
+ }
+ }
+}
+
+impl<S: ChannelsService> CommsRouterState<S> {
+ pub fn new(s: S) -> Self {
+ CommsRouterState { inner: Arc::new(s) }
+ }
+}
+
+pub fn comms_router<S: ChannelsService, T: Send + Sync + 'static>(
+ s: CommsRouterState<S>,
+) -> Router<T> {
+ Router::new()
+ .route("/channels", get(get_channels_handler))
+ .route("/activity", get(get_activity_handler))
+ .with_state(s)
+}
+
+#[derive(Debug, Error)]
+pub enum CommsErr {
+ #[error("Internal server error")]
+ Internal,
+}
+
+impl IntoResponse for CommsErr {
+ fn into_response(self) -> axum::response::Response {
+ let status = match self {
+ CommsErr::Internal => StatusCode::INTERNAL_SERVER_ERROR,
+ };
+
+ (status, self.to_string()).into_response()
+ }
+}
+
+#[utoipa::path(
+ get,
+ path = "/channels",
+ tag = "channels",
+ operation_id = "get_channels",
+ responses(
+ (status = 200, body=Vec<ApiChannelWithLatest>),
+ (status = 401, body=String),
+ (status = 404, body=String),
+ (status = 500, body=String),
+ )
+)]
+async fn get_channels_handler<S: ChannelsService>(
+ State(service): State<CommsRouterState<S>>,
+ MacroUserExtractor { macro_user_id, .. }: MacroUserExtractor,
+) -> Result<Json<Vec<ApiChannelWithLatest>>, CommsErr> {
+ let res = service
+ .inner
+ .get_channels(macro_user_id)
+ .await
+ .map_err(|_| CommsErr::Internal)?;
+
+ Ok(Json(<Vec<ApiChannelWithLatest>>::mirror(res)))
+}
+
+#[tracing::instrument(skip(service))]
+#[utoipa::path(get,
+ tag = "activity",
+ operation_id = "get_activity",
+ path = "/activity", responses(
+ (status = 200, body=Vec<ApiActivity>),
+ (status = 401, body=String),
+ (status = 404, body=String),
+ (status = 500, body=String),
+))]
+pub async fn get_activity_handler<S: ChannelsService>(
+ State(service): State<CommsRouterState<S>>,
+ MacroUserExtractor { macro_user_id, .. }: MacroUserExtractor,
+) -> Result<Json<Vec<ApiActivity>>, CommsErr> {
+ let res = service
+ .inner
+ .get_activities(macro_user_id)
+ .await
+ .map_err(|_| CommsErr::Internal)?;
+
+ Ok(Json(<Vec<ApiActivity>>::mirror(res)))
+}
+
+#[derive(Debug, Clone, Copy, Serialize, ToSchema, Doppleganger)]
+#[serde(rename_all = "snake_case")]
+#[dg(backward = models_comms::channel::ParticipantRole)]
+pub enum ParticipantRole {
+ Owner,
+ Admin,
+ Member,
+}
+
+#[derive(Debug, Clone, Serialize, ToSchema, Doppleganger)]
+#[dg(backward = models_comms::channel::ChannelParticipant)]
+pub struct ChannelParticipant {
+ /// id of the channel
+ #[schema(value_type = Uuid)]
+ pub channel_id: ChannelId,
+ /// id of the user
+ #[schema(value_type = String)]
+ pub user_id: MacroUserIdStr<'static>,
+ /// type of the participant
+ pub role: ParticipantRole,
+ /// timestamp of when the user joined the channel
+ pub joined_at: chrono::DateTime<chrono::Utc>,
+ /// timestamp of when the user left the channel
+ pub left_at: Option<chrono::DateTime<chrono::Utc>>,
+}
+
+#[derive(Debug, Clone, Serialize, ToSchema, Doppleganger)]
+#[dg(backward = models_comms::channel::ChannelWithParticipants)]
+pub struct ChannelWithParticipants {
+ #[serde(flatten)]
+ pub channel: Channel,
+ pub participants: Vec<ChannelParticipant>,
+}
+
+#[derive(Debug, Clone, Serialize, ToSchema, Doppleganger)]
+#[dg(backward = models_comms::channel::ChannelWithLatest)]
+pub struct ApiChannelWithLatest {
+ #[serde(flatten)]
+ pub channel: ChannelWithParticipants,
+ #[serde(flatten)]
+ pub latest_message: LatestMessage,
+ pub viewed_at: Option<chrono::DateTime<chrono::Utc>>,
+ pub interacted_at: Option<chrono::DateTime<chrono::Utc>>,
+ #[dg(map = map_frecency)]
+ pub frecency_score: Option<f64>,
+}
+
+fn map_frecency(f: Option<AggregateFrecency>) -> Option<f64> {
+ f.map(|f| f.data.frecency_score)
+}
+
+#[derive(Debug, Clone, Serialize, ToSchema, Doppleganger)]
+#[dg(backward = models_comms::channel::Channel)]
+pub struct Channel {
+ /// uuid of the channel
+ #[schema(value_type = Uuid)]
+ pub id: ChannelId,
+ /// string name of the channel
+ pub name: Option<String>,
+ /// type of the channel
+ pub channel_type: ChannelType,
+ /// id of the organization this channel belongs too
+ #[schema(value_type = Option<u32>)]
+ pub org_id: Option<OrganizationId>,
+ /// timestamp of when the channel was created
+ pub created_at: chrono::DateTime<chrono::Utc>,
+ /// timestamp of when the channel was last updated
+ pub updated_at: chrono::DateTime<chrono::Utc>,
+ /// id of the user who created the channel
+ #[schema(value_type = String)]
+ pub owner_id: MacroUserIdStr<'static>,
+}
+
+#[derive(Debug, Clone, ToSchema, Serialize, Doppleganger)]
+#[dg(backward = models_comms::channel::LatestMessage)]
+pub struct LatestMessage {
+ pub latest_message: Option<ChannelMessage>,
+ pub latest_non_thread_message: Option<ChannelMessage>,
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Doppleganger, ToSchema)]
+#[dg(backward = models_comms::channel::ChannelType)]
+#[serde(rename_all = "snake_case")]
+pub enum ChannelType {
+ Public,
+ Organization,
+ Private,
+ DirectMessage,
+}
+
+#[derive(Debug, Clone, Serialize, ToSchema, Doppleganger)]
+#[dg(backward = models_comms::channel::ChannelMessage)]
+pub struct ChannelMessage {
+ pub message_id: Uuid,
+ pub thread_id: Option<Uuid>,
+ pub sender_id: String,
+ pub content: String,
+ pub created_at: chrono::DateTime<chrono::Utc>,
+ pub updated_at: chrono::DateTime<chrono::Utc>,
+ pub deleted_at: Option<chrono::DateTime<chrono::Utc>>,
+ /// message mentions formatted as `{ENTITY_TYPE}:{ENTITY_ID}`
+ pub mentions: Vec<String>,
+}
+
+#[derive(Debug, ToSchema, Doppleganger, Serialize)]
+#[dg(backward = models_comms::channel::Activity)]
+pub struct ApiActivity {
+ pub id: Uuid,
+ pub user_id: String,
+ #[schema(value_type = Uuid)]
+ pub channel_id: ChannelId,
+ pub created_at: chrono::DateTime<chrono::Utc>,
+ pub updated_at: chrono::DateTime<chrono::Utc>,
+ /// the last time the user viewed the channel
+ pub viewed_at: Option<chrono::DateTime<chrono::Utc>>,
+ /// the last time the user intereacted with the channel
+ /// eg. reacting, replying, sending a message
+ pub interacted_at: Option<chrono::DateTime<chrono::Utc>>,
+}
diff --git a/rust/cloud-storage/comms/src/lib.rs b/rust/cloud-storage/comms/src/lib.rs
new file mode 100644
index 0000000000..f76105df0f
--- /dev/null
+++ b/rust/cloud-storage/comms/src/lib.rs
@@ -0,0 +1,5 @@
+pub mod domain;
+#[cfg(feature = "inbound")]
+pub mod inbound;
+#[cfg(feature = "outbound")]
+pub mod outbound;
diff --git a/rust/cloud-storage/comms/src/outbound.rs b/rust/cloud-storage/comms/src/outbound.rs
new file mode 100644
index 0000000000..921cda0f97
--- /dev/null
+++ b/rust/cloud-storage/comms/src/outbound.rs
@@ -0,0 +1,2 @@
+pub mod http;
+pub mod postgres;
diff --git a/rust/cloud-storage/comms/src/outbound/http.rs b/rust/cloud-storage/comms/src/outbound/http.rs
new file mode 100644
index 0000000000..cf6231f423
--- /dev/null
+++ b/rust/cloud-storage/comms/src/outbound/http.rs
@@ -0,0 +1 @@
+pub mod user_repo;
diff --git a/rust/cloud-storage/comms/src/outbound/http/user_repo.rs b/rust/cloud-storage/comms/src/outbound/http/user_repo.rs
new file mode 100644
index 0000000000..1a2edd3849
--- /dev/null
+++ b/rust/cloud-storage/comms/src/outbound/http/user_repo.rs
@@ -0,0 +1,73 @@
+use crate::domain::{models::UserName, ports::UserRepo};
+use macro_user_id::user_id::MacroUserIdStr;
+use reqwest::Url;
+use rootcause::report;
+use serde::Deserialize;
+use std::{collections::HashSet, sync::Arc};
+
+#[derive(Clone)]
+pub struct UserRepoImpl {
+ url: Arc<Url>,
+ client: reqwest::Client,
+}
+
+pub static INTERNAL_AUTH_HEADER_KEY: &str = "x-internal-auth-key";
+
+impl UserRepoImpl {
+ pub fn new(internal_auth_key: String, url: Url) -> Self {
+ let mut headers = reqwest::header::HeaderMap::new();
+ headers.insert(INTERNAL_AUTH_HEADER_KEY, internal_auth_key.parse().unwrap());
+
+ let client = reqwest::Client::builder()
+ .default_headers(headers)
+ .build()
+ .unwrap();
+
+ Self {
+ url: Arc::new(url),
+ client,
+ }
+ }
+}
+
+#[derive(Debug, serde::Serialize)]
+pub struct PostGetNamesRequestBody<'a> {
+ pub user_ids: HashSet<MacroUserIdStr<'a>>,
+}
+
+#[derive(Deserialize, Debug)]
+pub struct UserNames {
+ pub names: Vec<UserName>,
+}
+
+impl UserRepo for UserRepoImpl {
+ async fn get_names_for_ids(
+ &self,
+ user_ids: std::collections::HashSet<macro_user_id::user_id::MacroUserIdStr<'_>>,
+ ) -> Result<Vec<UserName>, rootcause::Report> {
+ let body = PostGetNamesRequestBody { user_ids };
+
+ let res = self
+ .client
+ .post(format!("{}/internal/get_names", self.url))
+ .json(&body)
+ .send()
+ .await?;
+
+ match res.status() {
+ reqwest::StatusCode::OK => {
+ let result = res.json::<UserNames>().await?;
+ Ok(result.names)
+ }
+ status_code => {
+ let body: String = res.text().await?;
+ tracing::error!(
+ body=%body,
+ status=%status_code,
+ "unexpected response from authentication service"
+ );
+ Err(report!(body).into())
+ }
+ }
+ }
+}
diff --git a/rust/cloud-storage/comms/src/outbound/postgres.rs b/rust/cloud-storage/comms/src/outbound/postgres.rs
new file mode 100644
index 0000000000..99bb43dbec
--- /dev/null
+++ b/rust/cloud-storage/comms/src/outbound/postgres.rs
@@ -0,0 +1 @@
+pub mod comms_repo;
diff --git a/rust/cloud-storage/comms_db_client/src/messages/get_latest_message.rs b/rust/cloud-storage/comms/src/outbound/postgres/comms_repo.rs
similarity index 52%
rename from rust/cloud-storage/comms_db_client/src/messages/get_latest_message.rs
rename to rust/cloud-storage/comms/src/outbound/postgres/comms_repo.rs
index f9d478ddf7..274a615c72 100644
--- a/rust/cloud-storage/comms_db_client/src/messages/get_latest_message.rs
+++ b/rust/cloud-storage/comms/src/outbound/postgres/comms_repo.rs
@@ -1,20 +1,117 @@
-use anyhow::Result;
-use model::comms::{ChannelMessage, LatestMessage};
-use sqlx::{Pool, Postgres};
+use crate::domain::ports::CommsRepo;
+use chrono::DateTime;
+use chrono::Utc;
+use doppleganger::{Doppleganger, Mirror};
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
+use models_comms::channel::{
+ Activity, Channel, ChannelId, ChannelMessage, ChannelParticipant, ChannelWithParticipants,
+ LatestMessage, OrganizationId,
+};
+use rootcause::Report;
+use sqlx::PgPool;
use std::collections::HashMap;
use uuid::Uuid;
-pub type ChannelLatestMessages = HashMap<Uuid, LatestMessage>;
+#[derive(Debug, Clone, Copy, Doppleganger, sqlx::Type)]
+#[sqlx(type_name = "comms_channel_type", rename_all = "snake_case")]
+#[dg(forward = models_comms::channel::ChannelType)]
+pub enum ChannelType {
+ Public,
+ Organization,
+ Private,
+ DirectMessage,
+}
+
+#[tracing::instrument(skip(db))]
+pub async fn get_user_channels_with_participants(
+ db: &PgPool,
+ user_id: &str,
+) -> Result<Vec<ChannelWithParticipants>, sqlx::Error> {
+ sqlx::query!(
+ r#"
+ WITH user_channels AS (
+ SELECT DISTINCT c.*
+ FROM comms_channels c
+ INNER JOIN comms_channel_participants cp ON cp.channel_id = c.id
+ WHERE cp.user_id = $1 AND cp.left_at IS NULL
+ ),
+ channel_participants_json AS (
+ SELECT
+ uc.id as channel_id,
+ ARRAY_AGG(
+ json_build_object(
+ 'channel_id', cp.channel_id,
+ 'user_id', cp.user_id,
+ 'role', cp.role,
+ 'joined_at', cp.joined_at,
+ 'left_at', cp.left_at
+ )
+ ) as participants
+ FROM user_channels uc
+ JOIN comms_channel_participants cp ON cp.channel_id = uc.id
+ WHERE cp.left_at IS NULL
+ GROUP BY uc.id
+ )
+ SELECT
+ uc.id as "id!",
+ uc.name as "name",
+ uc.channel_type as "channel_type!: ChannelType",
+ uc.org_id,
+ uc.created_at as "created_at!",
+ uc.updated_at as "updated_at!",
+ uc.owner_id as "owner_id!",
+ cpj.participants as "participants_json?"
+ FROM user_channels uc
+ LEFT JOIN channel_participants_json cpj ON cpj.channel_id = uc.id
+ ORDER BY uc.created_at DESC
+ "#,
+ user_id
+ )
+ .try_map(|row| {
+ let channel = Channel {
+ id: ChannelId(row.id),
+ name: row.name,
+ channel_type: ChannelType::mirror(row.channel_type),
+ org_id: row.org_id.map(|id| OrganizationId(id as u32)),
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ owner_id: MacroUserIdStr::parse_from_str(&row.owner_id)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned(),
+ };
+
+ let participants = row
+ .participants_json
+ .map(|json_array| {
+ json_array
+ .iter()
+ .filter_map(|json_value| {
+ serde_json::from_value::<ChannelParticipant>(json_value.clone()).ok()
+ })
+ .collect::<Vec<ChannelParticipant>>()
+ })
+ .unwrap_or_default();
+
+ Ok(ChannelWithParticipants {
+ channel,
+ participants,
+ })
+ })
+ .fetch_all(db)
+ .await
+}
#[tracing::instrument(err)]
pub async fn get_latest_channel_messages_batch(
- pool: &Pool<Postgres>,
- channel_ids: &[Uuid],
-) -> Result<ChannelLatestMessages> {
+ pool: &PgPool,
+ channel_ids: &[ChannelId],
+) -> Result<HashMap<ChannelId, LatestMessage>, Report> {
if channel_ids.is_empty() {
return Ok(HashMap::new());
}
+ let ids: Vec<Uuid> = channel_ids.iter().map(|x| x.0).collect();
+
let rows = sqlx::query!(
r#"
WITH input_ids AS (
@@ -89,12 +186,12 @@ pub async fn get_latest_channel_messages_batch(
LIMIT 1
) n ON TRUE
"#,
- channel_ids
+ &ids
)
.fetch_all(pool)
.await?;
- let mut result: ChannelLatestMessages = HashMap::with_capacity(rows.len());
+ let mut result = HashMap::with_capacity(rows.len());
let build_message = |message_id: Option<Uuid>,
thread_id: Option<Uuid>,
@@ -153,7 +250,7 @@ pub async fn get_latest_channel_messages_batch(
);
result.insert(
- row.channel_id,
+ ChannelId(row.channel_id),
LatestMessage {
latest_message,
latest_non_thread_message,
@@ -165,168 +262,81 @@ pub async fn get_latest_channel_messages_batch(
}
pub async fn get_latest_channel_message(
- pool: &Pool<Postgres>,
- channel_id: Uuid,
-) -> Result<LatestMessage> {
+ pool: &PgPool,
+ channel_id: ChannelId,
+) -> Result<LatestMessage, Report> {
let res = get_latest_channel_messages_batch(pool, &[channel_id]).await?;
Ok(res.get(&channel_id).cloned().unwrap_or(LatestMessage {
latest_message: None,
latest_non_thread_message: None,
}))
}
+#[tracing::instrument(skip(db), err)]
+pub async fn get_activities(
+ db: &PgPool,
+ user_id: MacroUserIdStr<'_>,
+) -> Result<Vec<Activity>, Report> {
+ Ok(sqlx::query!(
+ r#"
+ SELECT
+ a.id as "id!: Uuid",
+ a.user_id as "user_id!: String",
+ a.channel_id as "channel_id!: Uuid",
+ a.viewed_at as "viewed_at?: DateTime<Utc>",
+ a.interacted_at as "interacted_at?: DateTime<Utc>",
+ a.created_at as "created_at!: DateTime<Utc>",
+ a.updated_at as "updated_at!: DateTime<Utc>"
+ FROM comms_activity a
+ WHERE a.user_id = $1
+ ORDER BY
+ GREATEST(
+ COALESCE(a.viewed_at, '1970-01-01'::timestamp),
+ COALESCE(a.interacted_at, '1970-01-01'::timestamp)
+ ) DESC,
+ a.created_at DESC
+ LIMIT 100
+ "#,
+ user_id.as_ref()
+ )
+ .map(|row| Activity {
+ id: row.id,
+ user_id: row.user_id,
+ channel_id: ChannelId(row.channel_id),
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ viewed_at: row.viewed_at,
+ interacted_at: row.interacted_at,
+ })
+ .fetch_all(db)
+ .await?)
+}
-#[cfg(test)]
-mod tests {
- use super::*;
- use macro_db_migrator::MACRO_DB_MIGRATIONS;
+pub struct PgCommsRepo {
+ pub pool: PgPool,
+}
- fn uuid(s: &str) -> Uuid {
- Uuid::parse_str(s).unwrap()
+impl CommsRepo for PgCommsRepo {
+ async fn get_user_channels_with_participants(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ ) -> Result<Vec<ChannelWithParticipants>, rootcause::Report> {
+ Ok(get_user_channels_with_participants(&self.pool, user_id.as_ref()).await?)
}
- #[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../fixtures", scripts("latest_messages"))
- )]
- async fn test_get_latest_channel_messages_batch(
- pool: sqlx::Pool<sqlx::Postgres>,
- ) -> Result<()> {
- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS; // Dummy reference for IDE
- let ids = vec![
- uuid("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"),
- uuid("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"),
- uuid("cccccccc-cccc-cccc-cccc-cccccccccccc"),
- uuid("dddddddd-dddd-dddd-dddd-dddddddddddd"),
- ];
-
- let res = get_latest_channel_messages_batch(&pool, &ids).await?;
-
- // aaaaaaaa
- let a = res.get(&ids[0]).expect("channel a should exist");
- assert_eq!(
- a.latest_non_thread_message
- .as_ref()
- .map(|m| m.message_id.to_string())
- .as_deref(),
- Some("aaaaaa2a-0000-0000-0000-000000000002")
- );
-
- // bbbbbbbb
- let b = res.get(&ids[1]).expect("channel b should exist");
- assert_eq!(
- b.latest_message
- .as_ref()
- .map(|m| m.message_id.to_string())
- .as_deref(),
- Some("bbbbbb2b-0000-0000-0000-000000000003")
- );
- assert!(b.latest_non_thread_message.is_none());
-
- // cccccccc
- let c = res.get(&ids[2]).expect("channel c should exist");
- assert_eq!(
- c.latest_message
- .as_ref()
- .map(|m| m.message_id.to_string())
- .as_deref(),
- Some("cccccc2c-0000-0000-0000-000000000002")
- );
- assert_eq!(
- c.latest_non_thread_message
- .as_ref()
- .map(|m| m.message_id.to_string())
- .as_deref(),
- Some("cccccc2c-0000-0000-0000-000000000002")
- );
-
- // dddddddd
- let d = res.get(&ids[3]).expect("channel d should exist");
- assert_eq!(
- d.latest_message
- .as_ref()
- .map(|m| m.message_id.to_string())
- .as_deref(),
- Some("dddddd1d-0000-0000-0000-000000000001")
- );
- assert_eq!(
- d.latest_non_thread_message
- .as_ref()
- .map(|m| m.message_id.to_string())
- .as_deref(),
- Some("dddddd1d-0000-0000-0000-000000000001")
- );
-
- Ok(())
+ async fn get_latest_channel_messages_batch(
+ &self,
+ channels: &[ChannelId],
+ ) -> Result<
+ std::collections::HashMap<ChannelId, models_comms::channel::LatestMessage>,
+ rootcause::Report,
+ > {
+ get_latest_channel_messages_batch(&self.pool, channels).await
}
- #[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../fixtures", scripts("latest_messages"))
- )]
- async fn test_get_latest_channel_message(pool: sqlx::Pool<sqlx::Postgres>) -> Result<()> {
- let a =
- get_latest_channel_message(&pool, uuid("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")).await?;
-
- assert_eq!(
- a.latest_message
- .as_ref()
- .map(|m| m.message_id.to_string())
- .as_deref(),
- Some("aaaaaa2a-0000-0000-0000-000000000004")
- );
- assert_eq!(
- a.latest_non_thread_message
- .as_ref()
- .map(|m| m.message_id.to_string())
- .as_deref(),
- Some("aaaaaa2a-0000-0000-0000-000000000002")
- );
-
- let b =
- get_latest_channel_message(&pool, uuid("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb")).await?;
- assert_eq!(
- b.latest_message
- .as_ref()
- .map(|m| m.message_id.to_string())
- .as_deref(),
- Some("bbbbbb2b-0000-0000-0000-000000000003")
- );
- assert!(b.latest_non_thread_message.is_none());
-
- let c =
- get_latest_channel_message(&pool, uuid("cccccccc-cccc-cccc-cccc-cccccccccccc")).await?;
- assert_eq!(
- c.latest_message
- .as_ref()
- .map(|m| m.message_id.to_string())
- .as_deref(),
- Some("cccccc2c-0000-0000-0000-000000000002")
- );
- assert_eq!(
- c.latest_non_thread_message
- .as_ref()
- .map(|m| m.message_id.to_string())
- .as_deref(),
- Some("cccccc2c-0000-0000-0000-000000000002")
- );
-
- let d =
- get_latest_channel_message(&pool, uuid("dddddddd-dddd-dddd-dddd-dddddddddddd")).await?;
- assert_eq!(
- d.latest_message
- .as_ref()
- .map(|m| m.message_id.to_string())
- .as_deref(),
- Some("dddddd1d-0000-0000-0000-000000000001")
- );
- assert_eq!(
- d.latest_non_thread_message
- .as_ref()
- .map(|m| m.message_id.to_string())
- .as_deref(),
- Some("dddddd1d-0000-0000-0000-000000000001")
- );
-
- Ok(())
+ async fn get_activities(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ ) -> Result<Vec<models_comms::channel::Activity>, rootcause::Report> {
+ get_activities(&self.pool, user_id).await
}
}
diff --git a/rust/cloud-storage/comms/src/outbound/postgres/comms_repo/tests.rs b/rust/cloud-storage/comms/src/outbound/postgres/comms_repo/tests.rs
new file mode 100644
index 0000000000..bf838a4be9
--- /dev/null
+++ b/rust/cloud-storage/comms/src/outbound/postgres/comms_repo/tests.rs
@@ -0,0 +1,155 @@
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use macro_db_migrator::MACRO_DB_MIGRATIONS;
+
+ fn uuid(s: &str) -> Uuid {
+ Uuid::parse_str(s).unwrap()
+ }
+
+ #[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("latest_messages"))
+ )]
+ async fn test_get_latest_channel_messages_batch(
+ pool: sqlx::Pool<sqlx::Postgres>,
+ ) -> Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS; // Dummy reference for IDE
+ let ids = vec![
+ uuid("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"),
+ uuid("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"),
+ uuid("cccccccc-cccc-cccc-cccc-cccccccccccc"),
+ uuid("dddddddd-dddd-dddd-dddd-dddddddddddd"),
+ ];
+
+ let res = get_latest_channel_messages_batch(&pool, &ids).await?;
+
+ // aaaaaaaa
+ let a = res.get(&ids[0]).expect("channel a should exist");
+ assert_eq!(
+ a.latest_non_thread_message
+ .as_ref()
+ .map(|m| m.message_id.to_string())
+ .as_deref(),
+ Some("aaaaaa2a-0000-0000-0000-000000000002")
+ );
+
+ // bbbbbbbb
+ let b = res.get(&ids[1]).expect("channel b should exist");
+ assert_eq!(
+ b.latest_message
+ .as_ref()
+ .map(|m| m.message_id.to_string())
+ .as_deref(),
+ Some("bbbbbb2b-0000-0000-0000-000000000003")
+ );
+ assert!(b.latest_non_thread_message.is_none());
+
+ // cccccccc
+ let c = res.get(&ids[2]).expect("channel c should exist");
+ assert_eq!(
+ c.latest_message
+ .as_ref()
+ .map(|m| m.message_id.to_string())
+ .as_deref(),
+ Some("cccccc2c-0000-0000-0000-000000000002")
+ );
+ assert_eq!(
+ c.latest_non_thread_message
+ .as_ref()
+ .map(|m| m.message_id.to_string())
+ .as_deref(),
+ Some("cccccc2c-0000-0000-0000-000000000002")
+ );
+
+ // dddddddd
+ let d = res.get(&ids[3]).expect("channel d should exist");
+ assert_eq!(
+ d.latest_message
+ .as_ref()
+ .map(|m| m.message_id.to_string())
+ .as_deref(),
+ Some("dddddd1d-0000-0000-0000-000000000001")
+ );
+ assert_eq!(
+ d.latest_non_thread_message
+ .as_ref()
+ .map(|m| m.message_id.to_string())
+ .as_deref(),
+ Some("dddddd1d-0000-0000-0000-000000000001")
+ );
+
+ Ok(())
+ }
+
+ #[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("latest_messages"))
+ )]
+ async fn test_get_latest_channel_message(pool: sqlx::Pool<sqlx::Postgres>) -> Result<()> {
+ let a =
+ get_latest_channel_message(&pool, uuid("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")).await?;
+
+ assert_eq!(
+ a.latest_message
+ .as_ref()
+ .map(|m| m.message_id.to_string())
+ .as_deref(),
+ Some("aaaaaa2a-0000-0000-0000-000000000004")
+ );
+ assert_eq!(
+ a.latest_non_thread_message
+ .as_ref()
+ .map(|m| m.message_id.to_string())
+ .as_deref(),
+ Some("aaaaaa2a-0000-0000-0000-000000000002")
+ );
+
+ let b =
+ get_latest_channel_message(&pool, uuid("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb")).await?;
+ assert_eq!(
+ b.latest_message
+ .as_ref()
+ .map(|m| m.message_id.to_string())
+ .as_deref(),
+ Some("bbbbbb2b-0000-0000-0000-000000000003")
+ );
+ assert!(b.latest_non_thread_message.is_none());
+
+ let c =
+ get_latest_channel_message(&pool, uuid("cccccccc-cccc-cccc-cccc-cccccccccccc")).await?;
+ assert_eq!(
+ c.latest_message
+ .as_ref()
+ .map(|m| m.message_id.to_string())
+ .as_deref(),
+ Some("cccccc2c-0000-0000-0000-000000000002")
+ );
+ assert_eq!(
+ c.latest_non_thread_message
+ .as_ref()
+ .map(|m| m.message_id.to_string())
+ .as_deref(),
+ Some("cccccc2c-0000-0000-0000-000000000002")
+ );
+
+ let d =
+ get_latest_channel_message(&pool, uuid("dddddddd-dddd-dddd-dddd-dddddddddddd")).await?;
+ assert_eq!(
+ d.latest_message
+ .as_ref()
+ .map(|m| m.message_id.to_string())
+ .as_deref(),
+ Some("dddddd1d-0000-0000-0000-000000000001")
+ );
+ assert_eq!(
+ d.latest_non_thread_message
+ .as_ref()
+ .map(|m| m.message_id.to_string())
+ .as_deref(),
+ Some("dddddd1d-0000-0000-0000-000000000001")
+ );
+
+ Ok(())
+ }
+}
diff --git a/rust/cloud-storage/comms_db_client/.sqlx/query-8b6544a586ac95ece01dc4837e5d7be5b36735131fc567e0ae371b6b2b6dcb66.json b/rust/cloud-storage/comms_db_client/.sqlx/query-a7f90096050e550d15ef11bbc56a3cd79e1a80bc3f46cd063d0ff94d9b76f252.json
similarity index 79%
rename from rust/cloud-storage/comms_db_client/.sqlx/query-8b6544a586ac95ece01dc4837e5d7be5b36735131fc567e0ae371b6b2b6dcb66.json
rename to rust/cloud-storage/comms_db_client/.sqlx/query-a7f90096050e550d15ef11bbc56a3cd79e1a80bc3f46cd063d0ff94d9b76f252.json
index 3e46c2eac4..8bc55d69f6 100644
--- a/rust/cloud-storage/comms_db_client/.sqlx/query-8b6544a586ac95ece01dc4837e5d7be5b36735131fc567e0ae371b6b2b6dcb66.json
+++ b/rust/cloud-storage/comms_db_client/.sqlx/query-a7f90096050e550d15ef11bbc56a3cd79e1a80bc3f46cd063d0ff94d9b76f252.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n user_id,\n channel_id,\n joined_at,\n left_at,\n role as \"role: ParticipantRole\"\n FROM comms_channel_participants\n WHERE channel_id = $1\n ORDER BY joined_at DESC\n ",
+ "query": "\n SELECT\n user_id,\n channel_id,\n joined_at,\n left_at,\n role as \"role: DbParticipantRole\"\n FROM comms_channel_participants\n WHERE channel_id = $1\n ORDER BY joined_at DESC\n ",
"describe": {
"columns": [
{
@@ -25,7 +25,7 @@
},
{
"ordinal": 4,
- "name": "role: ParticipantRole",
+ "name": "role: DbParticipantRole",
"type_info": {
"Custom": {
"name": "comms_participant_role",
@@ -53,5 +53,5 @@
false
]
},
- "hash": "8b6544a586ac95ece01dc4837e5d7be5b36735131fc567e0ae371b6b2b6dcb66"
+ "hash": "a7f90096050e550d15ef11bbc56a3cd79e1a80bc3f46cd063d0ff94d9b76f252"
}
diff --git a/rust/cloud-storage/comms_db_client/Cargo.toml b/rust/cloud-storage/comms_db_client/Cargo.toml
index d06797fba8..7b277010a8 100644
--- a/rust/cloud-storage/comms_db_client/Cargo.toml
+++ b/rust/cloud-storage/comms_db_client/Cargo.toml
@@ -8,10 +8,12 @@ version = "0.1.0"
anyhow = { workspace = true }
cached = { workspace = true }
chrono = { workspace = true }
+doppleganger = { workspace = true }
futures = { workspace = true }
macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
model = { path = "../model" }
+models_comms = { path = "../models_comms" }
serde = { workspace = true }
serde_json = { workspace = true }
sqlx = { workspace = true }
diff --git a/rust/cloud-storage/comms_db_client/fixtures/channels.sql b/rust/cloud-storage/comms_db_client/fixtures/channels.sql
index 875c2d9c31..693602b334 100644
--- a/rust/cloud-storage/comms_db_client/fixtures/channels.sql
+++ b/rust/cloud-storage/comms_db_client/fixtures/channels.sql
@@ -1,20 +1,20 @@
INSERT INTO comms_channels (id, name, channel_type, org_id, owner_id)
-VALUES ('11111111-1111-1111-1111-111111111111', 'private 1 ', 'private', NULL, 'user1'),
- ('22222222-2222-2222-2222-222222222222', NULL, 'direct_message', NULL, 'user3'),
- ('33333333-3333-3333-3333-333333333333', 'public channel', 'public', NULL, 'user5');
+VALUES ('11111111-1111-1111-1111-111111111111', 'private 1 ', 'private', NULL, 'macro|[email protected]'),
+ ('22222222-2222-2222-2222-222222222222', NULL, 'direct_message', NULL, 'macro|[email protected]'),
+ ('33333333-3333-3333-3333-333333333333', 'public channel', 'public', NULL, 'macro|[email protected]');
INSERT INTO comms_channel_participants (channel_id, role, user_id)
-VALUES ('11111111-1111-1111-1111-111111111111', 'owner', 'user1'),
- ('11111111-1111-1111-1111-111111111111', 'member', 'user2'),
- ('11111111-1111-1111-1111-111111111111', 'member', 'user3'),
- ('22222222-2222-2222-2222-222222222222', 'owner', 'user3'),
- ('22222222-2222-2222-2222-222222222222', 'member', 'user4'),
- ('33333333-3333-3333-3333-333333333333', 'owner', 'user5'),
- ('33333333-3333-3333-3333-333333333333', 'member', 'user1'),
- ('33333333-3333-3333-3333-333333333333', 'member', 'user2'),
- ('33333333-3333-3333-3333-333333333333', 'member', 'user3'),
- ('33333333-3333-3333-3333-333333333333', 'member', 'user4'),
- ('33333333-3333-3333-3333-333333333333', 'member', 'user7');
+VALUES ('11111111-1111-1111-1111-111111111111', 'owner', 'macro|[email protected]'),
+ ('11111111-1111-1111-1111-111111111111', 'member', 'macro|[email protected]'),
+ ('11111111-1111-1111-1111-111111111111', 'member', 'macro|[email protected]'),
+ ('22222222-2222-2222-2222-222222222222', 'owner', 'macro|[email protected]'),
+ ('22222222-2222-2222-2222-222222222222', 'member', 'macro|[email protected]'),
+ ('33333333-3333-3333-3333-333333333333', 'owner', 'macro|[email protected]'),
+ ('33333333-3333-3333-3333-333333333333', 'member', 'macro|[email protected]'),
+ ('33333333-3333-3333-3333-333333333333', 'member', 'macro|[email protected]'),
+ ('33333333-3333-3333-3333-333333333333', 'member', 'macro|[email protected]'),
+ ('33333333-3333-3333-3333-333333333333', 'member', 'macro|[email protected]'),
+ ('33333333-3333-3333-3333-333333333333', 'member', 'macro|[email protected]');
-- User7 will later have left_at set to simulate leaving the channel
-- This is handled in integration test or a migration if requested again.
diff --git a/rust/cloud-storage/comms_db_client/fixtures/threads.sql b/rust/cloud-storage/comms_db_client/fixtures/threads.sql
index c0f798396b..9bf2b2679b 100644
--- a/rust/cloud-storage/comms_db_client/fixtures/threads.sql
+++ b/rust/cloud-storage/comms_db_client/fixtures/threads.sql
@@ -1,25 +1,25 @@
INSERT INTO comms_channels (id, name, channel_type, org_id, owner_id)
-VALUES ('11111111-1111-1111-1111-111111111111', 'private-channel', 'private', NULL, 'owner1'),
- ('22222222-2222-2222-2222-222222222222', 'private-channel', 'private', NULL, 'owner1');
+VALUES ('11111111-1111-1111-1111-111111111111', 'private-channel', 'private', NULL, 'macro|[email protected]'),
+ ('22222222-2222-2222-2222-222222222222', 'private-channel', 'private', NULL, 'macro|[email protected]');
INSERT INTO comms_channel_participants (channel_id, role, user_id)
-VALUES ('11111111-1111-1111-1111-111111111111', 'owner', 'user1'),
- ('11111111-1111-1111-1111-111111111111', 'member', 'user2'),
- ('11111111-1111-1111-1111-111111111111', 'member', 'user3'),
- ('11111111-1111-1111-1111-111111111111', 'member', 'user4'),
- ('22222222-2222-2222-2222-222222222222', 'owner', 'user5'),
- ('22222222-2222-2222-2222-222222222222', 'member', 'user6');
+VALUES ('11111111-1111-1111-1111-111111111111', 'owner', 'macro|[email protected]'),
+ ('11111111-1111-1111-1111-111111111111', 'member', 'macro|[email protected]'),
+ ('11111111-1111-1111-1111-111111111111', 'member', 'macro|[email protected]'),
+ ('11111111-1111-1111-1111-111111111111', 'member', 'macro|[email protected]'),
+ ('22222222-2222-2222-2222-222222222222', 'owner', 'macro|[email protected]'),
+ ('22222222-2222-2222-2222-222222222222', 'member', 'macro|[email protected]');
INSERT INTO comms_messages (id, channel_id, thread_id, sender_id, content)
VALUES ('11111111-1111-1111-1111-111111111111', '11111111-1111-1111-1111-111111111111',
- '11111111-1111-1111-1111-111111111111', 'user1', 'Test message 1'),
+ '11111111-1111-1111-1111-111111111111', 'macro|[email protected]', 'Test message 1'),
('22222222-2222-2222-2222-222222222222', '11111111-1111-1111-1111-111111111111',
- '11111111-1111-1111-1111-111111111111', 'user2', 'Test message 1'),
+ '11111111-1111-1111-1111-111111111111', 'macro|[email protected]', 'Test message 1'),
('33333333-3333-3333-3333-333333333333', '11111111-1111-1111-1111-111111111111',
- '11111111-1111-1111-1111-111111111111', 'user3', 'Test message 1'),
+ '11111111-1111-1111-1111-111111111111', 'macro|[email protected]', 'Test message 1'),
('44444444-4444-4444-4444-444444444444', '11111111-1111-1111-1111-111111111111',
- '11111111-1111-1111-1111-111111111111', 'user4', 'Test message 1'),
+ '11111111-1111-1111-1111-111111111111', 'macro|[email protected]', 'Test message 1'),
('55555555-5555-5555-5555-555555555555', '11111111-1111-1111-1111-111111111111',
- '22222222-2222-2222-2222-222222222222', 'user5', 'Test message 1');
+ '22222222-2222-2222-2222-222222222222', 'macro|[email protected]', 'Test message 1');
diff --git a/rust/cloud-storage/comms_db_client/src/activity/get_activity.rs b/rust/cloud-storage/comms_db_client/src/activity/get_activity.rs
index 08ed6f815f..9679001ff1 100644
--- a/rust/cloud-storage/comms_db_client/src/activity/get_activity.rs
+++ b/rust/cloud-storage/comms_db_client/src/activity/get_activity.rs
@@ -6,36 +6,6 @@ use sqlx::{Pool, Postgres};
use std::collections::HashMap;
use uuid::Uuid;
-#[tracing::instrument(skip(db), err)]
-pub async fn get_activities(db: &Pool<Postgres>, user_id: &str) -> Result<Vec<Activity>> {
- sqlx::query_as!(
- Activity,
- r#"
- SELECT
- a.id as "id!: Uuid",
- a.user_id as "user_id!: String",
- a.channel_id as "channel_id!: Uuid",
- a.viewed_at as "viewed_at?: DateTime<Utc>",
- a.interacted_at as "interacted_at?: DateTime<Utc>",
- a.created_at as "created_at!: DateTime<Utc>",
- a.updated_at as "updated_at!: DateTime<Utc>"
- FROM comms_activity a
- WHERE a.user_id = $1
- ORDER BY
- GREATEST(
- COALESCE(a.viewed_at, '1970-01-01'::timestamp),
- COALESCE(a.interacted_at, '1970-01-01'::timestamp)
- ) DESC,
- a.created_at DESC
- LIMIT 100
- "#,
- user_id
- )
- .fetch_all(db)
- .await
- .context("failed to get activities")
-}
-
#[tracing::instrument(skip(db))]
pub async fn get_activity_for_channel(
db: &Pool<Postgres>,
diff --git a/rust/cloud-storage/comms_db_client/src/channels/delete_channel.rs b/rust/cloud-storage/comms_db_client/src/channels/delete_channel.rs
index 08cb684df7..a3d45304ea 100644
--- a/rust/cloud-storage/comms_db_client/src/channels/delete_channel.rs
+++ b/rust/cloud-storage/comms_db_client/src/channels/delete_channel.rs
@@ -51,7 +51,7 @@ mod tests {
"11111111-1111-1111-1111-111111111111"
.parse::<Uuid>()
.unwrap(),
- "user1",
)
.await;
diff --git a/rust/cloud-storage/comms_db_client/src/channels/get_channel.rs b/rust/cloud-storage/comms_db_client/src/channels/get_channel.rs
index be94c0e666..961f1c699d 100644
--- a/rust/cloud-storage/comms_db_client/src/channels/get_channel.rs
+++ b/rust/cloud-storage/comms_db_client/src/channels/get_channel.rs
@@ -1,12 +1,11 @@
use anyhow::{Context, Result};
-#[allow(unused_imports)]
-use model::comms::{Channel, ChannelType};
+use macro_user_id::cowlike::CowLike;
+use model::comms::{Channel, ChannelId, ChannelType, OrganizationId};
use sqlx::{Pool, Postgres};
use uuid::Uuid;
pub async fn get_channel(db: &Pool<Postgres>, channel_id: &Uuid) -> Result<Channel> {
- let channel = sqlx::query_as!(
- Channel,
+ let channel = sqlx::query!(
r#"
SELECT
id,
@@ -21,6 +20,19 @@ pub async fn get_channel(db: &Pool<Postgres>, channel_id: &Uuid) -> Result<Chann
"#,
channel_id
)
+ .try_map(|row| {
+ Ok(Channel {
+ id: ChannelId(row.id),
+ name: row.name,
+ channel_type: row.channel_type,
+ org_id: row.org_id.map(|id| OrganizationId(id as u32)),
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ owner_id: macro_user_id::user_id::MacroUserIdStr::parse_from_str(&row.owner_id)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned(),
+ })
+ })
.fetch_one(db)
.await
.context("failed to get channel")?;
diff --git a/rust/cloud-storage/comms_db_client/src/channels/get_channels.rs b/rust/cloud-storage/comms_db_client/src/channels/get_channels.rs
index 969aa5a73c..5156acde36 100644
--- a/rust/cloud-storage/comms_db_client/src/channels/get_channels.rs
+++ b/rust/cloud-storage/comms_db_client/src/channels/get_channels.rs
@@ -1,6 +1,8 @@
use cached::proc_macro::cached;
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
#[allow(unused_imports)]
use model::comms::{Channel, ChannelParticipant, ChannelType, ChannelWithParticipants};
+use model::comms::{ChannelId, OrganizationId};
use sqlx::{Pool, Postgres};
use uuid::Uuid;
@@ -70,95 +72,11 @@ pub async fn get_user_channel_ids(
Ok(channels)
}
-#[tracing::instrument(skip(db))]
-pub async fn get_user_channels_with_participants(
- db: &Pool<Postgres>,
- user_id: &str,
-) -> Result<Vec<ChannelWithParticipants>, sqlx::Error> {
- let rows = sqlx::query!(
- r#"
- WITH user_channels AS (
- SELECT DISTINCT c.*
- FROM comms_channels c
- INNER JOIN comms_channel_participants cp ON cp.channel_id = c.id
- WHERE cp.user_id = $1 AND cp.left_at IS NULL
- ),
- channel_participants_json AS (
- SELECT
- uc.id as channel_id,
- ARRAY_AGG(
- json_build_object(
- 'channel_id', cp.channel_id,
- 'user_id', cp.user_id,
- 'role', cp.role,
- 'joined_at', cp.joined_at,
- 'left_at', cp.left_at
- )
- ) as participants
- FROM user_channels uc
- JOIN comms_channel_participants cp ON cp.channel_id = uc.id
- WHERE cp.left_at IS NULL
- GROUP BY uc.id
- )
- SELECT
- uc.id as "id!",
- uc.name as "name",
- uc.channel_type as "channel_type!: ChannelType",
- uc.org_id,
- uc.created_at as "created_at!",
- uc.updated_at as "updated_at!",
- uc.owner_id as "owner_id!",
- cpj.participants as "participants_json?"
- FROM user_channels uc
- LEFT JOIN channel_participants_json cpj ON cpj.channel_id = uc.id
- ORDER BY uc.created_at DESC
- "#,
- user_id
- )
- .fetch_all(db)
- .await?;
-
- let channels_with_participants = rows
- .into_iter()
- .map(|row| {
- let channel = Channel {
- id: row.id,
- name: row.name,
- channel_type: row.channel_type,
- org_id: row.org_id,
- created_at: row.created_at,
- updated_at: row.updated_at,
- owner_id: row.owner_id,
- };
-
- let participants = row
- .participants_json
- .map(|json_array| {
- json_array
- .iter()
- .filter_map(|json_value| {
- serde_json::from_value::<ChannelParticipant>(json_value.clone()).ok()
- })
- .collect::<Vec<ChannelParticipant>>()
- })
- .unwrap_or_default();
-
- ChannelWithParticipants {
- channel,
- participants,
- }
- })
- .collect();
-
- Ok(channels_with_participants)
-}
-
pub async fn get_org_channels(
db: &Pool<Postgres>,
org_id: &i64,
) -> Result<Vec<Channel>, sqlx::Error> {
- let channels = sqlx::query_as!(
- Channel,
+ let channels = sqlx::query!(
r#"
SELECT
id as "id!",
@@ -175,6 +93,19 @@ pub async fn get_org_channels(
"#,
org_id
)
+ .try_map(|row| {
+ Ok(Channel {
+ id: ChannelId(row.id),
+ name: Some(row.name),
+ channel_type: row.channel_type,
+ org_id: row.org_id.map(|id| OrganizationId(id as u32)),
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ owner_id: MacroUserIdStr::parse_from_str(&row.owner_id)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned(),
+ })
+ })
.fetch_all(db)
.await?;
diff --git a/rust/cloud-storage/comms_db_client/src/channels/get_private.rs b/rust/cloud-storage/comms_db_client/src/channels/get_private.rs
index 2b5a16ef27..3b3fce63d7 100644
--- a/rust/cloud-storage/comms_db_client/src/channels/get_private.rs
+++ b/rust/cloud-storage/comms_db_client/src/channels/get_private.rs
@@ -53,18 +53,23 @@ mod tests {
)]
async fn test_get_existing_private_channel(pool: Pool<Postgres>) -> anyhow::Result<()> {
const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS; // Dummy reference for IDE
- let result =
- maybe_get_private_channel(&pool, &vec!["user1".to_string(), "user2".to_string()])
- .await?;
+ let result = maybe_get_private_channel(
+ &pool,
+ &vec![
+ "macro|[email protected]".to_string(),
+ "macro|[email protected]".to_string(),
+ ],
+ )
+ .await?;
assert_eq!(result, None);
let result = maybe_get_private_channel(
&pool,
&vec![
- "user1".to_string(),
- "user3".to_string(),
- "user2".to_string(),
+ "macro|[email protected]".to_string(),
+ "macro|[email protected]".to_string(),
+ "macro|[email protected]".to_string(),
],
)
.await?;
@@ -77,10 +82,10 @@ mod tests {
let result = maybe_get_private_channel(
&pool,
&vec![
- "user1".to_string(),
- "user3".to_string(),
- "user4".to_string(),
- "user2".to_string(),
+ "macro|[email protected]".to_string(),
+ "macro|[email protected]".to_string(),
+ "macro|[email protected]".to_string(),
+ "macro|[email protected]".to_string(),
],
)
.await?;
diff --git a/rust/cloud-storage/comms_db_client/src/channels/patch_channel.rs b/rust/cloud-storage/comms_db_client/src/channels/patch_channel.rs
index 92088ef7d3..da73412e12 100644
--- a/rust/cloud-storage/comms_db_client/src/channels/patch_channel.rs
+++ b/rust/cloud-storage/comms_db_client/src/channels/patch_channel.rs
@@ -77,7 +77,7 @@ mod tests {
&"11111111-1111-1111-1111-111111111111"
.parse::<Uuid>()
.unwrap(),
- "user1",
PatchChannelOptions {
channel_name: Some("new channel name".to_string()),
},
@@ -111,7 +111,7 @@ mod tests {
&"11111111-1111-1111-1111-111111111111"
.parse::<Uuid>()
.unwrap(),
- "user2",
PatchChannelOptions {
channel_name: Some("new channel name".to_string()),
},
diff --git a/rust/cloud-storage/comms_db_client/src/messages/mod.rs b/rust/cloud-storage/comms_db_client/src/messages/mod.rs
index eea1d97b15..c85405052a 100644
--- a/rust/cloud-storage/comms_db_client/src/messages/mod.rs
+++ b/rust/cloud-storage/comms_db_client/src/messages/mod.rs
@@ -4,10 +4,7 @@ pub mod create_message_mentions;
pub mod delete_message;
pub mod get_channel_message;
pub mod get_count;
-mod get_latest_message;
pub mod get_message_owner;
pub mod get_messages;
pub mod patch_message;
pub mod read_message_with_context;
-
-pub use get_latest_message::{get_latest_channel_message, get_latest_channel_messages_batch};
diff --git a/rust/cloud-storage/comms_db_client/src/participants/get_participants.rs b/rust/cloud-storage/comms_db_client/src/participants/get_participants.rs
index 09b9784900..568c9cbf7e 100644
--- a/rust/cloud-storage/comms_db_client/src/participants/get_participants.rs
+++ b/rust/cloud-storage/comms_db_client/src/participants/get_participants.rs
@@ -1,29 +1,51 @@
use anyhow::{Context, Result};
-use model::comms::ChannelParticipant;
-use model::comms::ParticipantRole;
+use doppleganger::Doppleganger;
+use doppleganger::Mirror;
+use macro_user_id::cowlike::CowLike;
+use macro_user_id::user_id::MacroUserIdStr;
+use model::comms::ChannelId;
use sqlx::{Pool, Postgres};
use uuid::Uuid;
+#[derive(sqlx::Type, Doppleganger, Debug)]
+#[dg(forward = models_comms::channel::ParticipantRole)]
+#[sqlx(rename_all = "lowercase")]
+pub enum DbParticipantRole {
+ Admin,
+ Member,
+ Owner,
+}
+
#[tracing::instrument(skip(db))]
pub async fn get_participants(
db: &Pool<Postgres>,
channel_id: &Uuid,
-) -> Result<Vec<ChannelParticipant>, sqlx::Error> {
- let participants = sqlx::query_as!(
- ChannelParticipant,
+) -> Result<Vec<models_comms::channel::ChannelParticipant>, sqlx::Error> {
+ let participants = sqlx::query!(
r#"
SELECT
user_id,
channel_id,
joined_at,
left_at,
- role as "role: ParticipantRole"
+ role as "role: DbParticipantRole"
FROM comms_channel_participants
WHERE channel_id = $1
ORDER BY joined_at DESC
"#,
channel_id
)
+ .try_map(|row| {
+ Ok(models_comms::channel::ChannelParticipant {
+ channel_id: ChannelId(row.channel_id),
+ user_id: macro_user_id::user_id::MacroUserIdStr::parse_from_str(&row.user_id)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned(),
+ role: DbParticipantRole::mirror(row.role),
+ joined_at: row.joined_at,
+ left_at: row.left_at,
+ })
+ })
.fetch_all(db)
.await?;
@@ -56,8 +78,8 @@ pub async fn get_channel_participants_for_notification(
pub async fn get_channel_participants_for_thread_id(
db: &Pool<Postgres>,
thread_id: &Uuid,
-) -> Result<Vec<String>> {
- let participants: Vec<String> = sqlx::query!(
+) -> Result<Vec<MacroUserIdStr<'static>>> {
+ let participants: Vec<_> = sqlx::query!(
r#"
SELECT DISTINCT(m.sender_id) as id
FROM comms_channel_participants cp
@@ -67,7 +89,11 @@ pub async fn get_channel_participants_for_thread_id(
"#,
thread_id
)
- .map(|participant| participant.id)
+ .try_map(|participant| {
+ Ok(MacroUserIdStr::parse_from_str(&participant.id)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned())
+ })
.fetch_all(db)
.await?;
@@ -92,10 +118,18 @@ mod tests {
assert_eq!(participants.len(), 4);
- assert!(participants.contains(&"user1".to_string()));
- assert!(participants.contains(&"user2".to_string()));
- assert!(participants.contains(&"user3".to_string()));
- assert!(participants.contains(&"user4".to_string()));
+ assert!(
+ participants.contains(&MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap())
+ );
+ assert!(
+ participants.contains(&MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap())
+ );
+ assert!(
+ participants.contains(&MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap())
+ );
+ assert!(
+ participants.contains(&MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap())
+ );
Ok(())
}
diff --git a/rust/cloud-storage/comms_db_client/src/preview/mod.rs b/rust/cloud-storage/comms_db_client/src/preview/mod.rs
index 60f75770e8..41ef1f3c03 100644
--- a/rust/cloud-storage/comms_db_client/src/preview/mod.rs
+++ b/rust/cloud-storage/comms_db_client/src/preview/mod.rs
@@ -1,5 +1,6 @@
use crate::participants::get_participants::get_participants;
use anyhow::{Context, Result};
+use doppleganger::Mirror;
use model::comms::{ChannelParticipant, ChannelType};
use sqlx::{Pool, Postgres};
use uuid::Uuid;
@@ -72,7 +73,11 @@ pub async fn batch_get_channel_preview(
let mut previews: Vec<RawPreviewRecord> = vec![];
for row in preview_data {
- let participants = get_participants(db, &row.channel_id).await?;
+ let participants = get_participants(db, &row.channel_id)
+ .await?
+ .into_iter()
+ .map(model::comms::ChannelParticipant::mirror)
+ .collect();
previews.push(RawPreviewRecord {
channel_id: row.channel_id,
@@ -118,7 +123,7 @@ mod tests {
async fn test_preview_for_private_channel(pool: Pool<Postgres>) -> anyhow::Result<()> {
const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS; // Dummy reference for IDE
let ids = vec!["11111111-1111-1111-1111-111111111111".to_string()];
- let previews = batch_get_channel_preview(&pool, &ids, "user1", None).await?;
+ let previews = batch_get_channel_preview(&pool, &ids, "macro|[email protected]", None).await?;
assert_eq!(previews.exists.len(), 1);
assert_eq!(
previews.exists[0].channel_id,
@@ -143,7 +148,7 @@ mod tests {
)]
async fn test_access_dm(pool: Pool<Postgres>) -> anyhow::Result<()> {
let ids = vec!["22222222-2222-2222-2222-222222222222".to_string()];
- let previews = batch_get_channel_preview(&pool, &ids, "user4", None).await?;
+ let previews = batch_get_channel_preview(&pool, &ids, "macro|[email protected]", None).await?;
assert_eq!(previews.exists.len(), 1);
assert!(
previews.exists[0].has_access,
@@ -158,7 +163,7 @@ mod tests {
)]
async fn test_no_access_dm(pool: Pool<Postgres>) -> anyhow::Result<()> {
let ids = vec!["22222222-2222-2222-2222-222222222222".to_string()];
- let previews = batch_get_channel_preview(&pool, &ids, "user1", None).await?;
+ let previews = batch_get_channel_preview(&pool, &ids, "macro|[email protected]", None).await?;
assert_eq!(previews.exists.len(), 1);
assert!(
!previews.exists[0].has_access,
@@ -173,7 +178,7 @@ mod tests {
)]
async fn test_does_not_exist(pool: Pool<Postgres>) -> anyhow::Result<()> {
let ids = vec!["44444444-4444-4444-4444-444444444444".to_string()];
- let previews = batch_get_channel_preview(&pool, &ids, "user1", None).await?;
+ let previews = batch_get_channel_preview(&pool, &ids, "macro|[email protected]", None).await?;
assert_eq!(previews.exists.len(), 0);
assert_eq!(previews.remaining.len(), 1);
Ok(())
@@ -185,7 +190,7 @@ mod tests {
)]
async fn test_no_access_private(pool: Pool<Postgres>) -> anyhow::Result<()> {
let ids = vec!["11111111-1111-1111-1111-111111111111".to_string()];
- let previews = batch_get_channel_preview(&pool, &ids, "user4", None).await?;
+ let previews = batch_get_channel_preview(&pool, &ids, "macro|[email protected]", None).await?;
assert_eq!(previews.exists.len(), 1);
assert!(
!previews.exists[0].has_access,
diff --git a/rust/cloud-storage/comms_service/.sqlx/query-af221abca7c795e8be43765273da50af55ed9b7f069ee43fa7149deb8425f6bf.json b/rust/cloud-storage/comms_service/.sqlx/query-92afd811fa4a67de45ac9a1d6d4274f01c865b9c861f2034c89f0531b88aac85.json
similarity index 77%
rename from rust/cloud-storage/comms_service/.sqlx/query-af221abca7c795e8be43765273da50af55ed9b7f069ee43fa7149deb8425f6bf.json
rename to rust/cloud-storage/comms_service/.sqlx/query-92afd811fa4a67de45ac9a1d6d4274f01c865b9c861f2034c89f0531b88aac85.json
index db4be8c299..d5becc2c4f 100644
--- a/rust/cloud-storage/comms_service/.sqlx/query-af221abca7c795e8be43765273da50af55ed9b7f069ee43fa7149deb8425f6bf.json
+++ b/rust/cloud-storage/comms_service/.sqlx/query-92afd811fa4a67de45ac9a1d6d4274f01c865b9c861f2034c89f0531b88aac85.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n id,\n name,\n channel_type AS \"channel_type: ChannelType\",\n org_id,\n created_at,\n updated_at,\n owner_id\n FROM comms_channels\n WHERE id = $1\n ",
+ "query": "\n SELECT\n id,\n name,\n channel_type AS \"channel_type: model::comms::ChannelType\",\n org_id,\n created_at,\n updated_at,\n owner_id\n FROM comms_channels\n WHERE id = $1\n ",
"describe": {
"columns": [
{
@@ -15,7 +15,7 @@
},
{
"ordinal": 2,
- "name": "channel_type: ChannelType",
+ "name": "channel_type: model::comms::ChannelType",
"type_info": {
"Custom": {
"name": "comms_channel_type",
@@ -66,5 +66,5 @@
false
]
},
- "hash": "af221abca7c795e8be43765273da50af55ed9b7f069ee43fa7149deb8425f6bf"
+ "hash": "92afd811fa4a67de45ac9a1d6d4274f01c865b9c861f2034c89f0531b88aac85"
}
diff --git a/rust/cloud-storage/comms_service/Cargo.toml b/rust/cloud-storage/comms_service/Cargo.toml
index 779517552b..214356a3ba 100644
--- a/rust/cloud-storage/comms_service/Cargo.toml
+++ b/rust/cloud-storage/comms_service/Cargo.toml
@@ -33,9 +33,11 @@ axum = { workspace = true, features = ["tower-log", "ws"] }
axum-extra = { workspace = true }
axum-macros = { workspace = true }
chrono = { workspace = true }
+comms = { path = "../comms", features = ["inbound", "outbound"] }
comms_db_client = { path = "../comms_db_client", optional = true }
connection_gateway = { path = "../connection_gateway" }
document_storage_service_client = { path = "../document_storage_service_client" }
+doppleganger = { workspace = true }
frecency = { path = "../frecency", features = ["postgres"] }
futures = { workspace = true }
http-body-util = { workspace = true }
@@ -55,6 +57,7 @@ model = { path = "../model" }
model-entity = { path = "../model-entity" }
model_notifications = { path = "../model_notifications" }
models_comms = { path = "../models_comms" }
+models_opensearch = { path = "../models_opensearch" }
models_permissions = { path = "../models_permissions" }
reqwest.workspace = true
secretsmanager_client = { path = "../secretsmanager_client" }
@@ -73,7 +76,6 @@ tracing = { workspace = true }
utoipa = { workspace = true, features = ["axum_extras", "chrono", "uuid"] }
utoipa-swagger-ui = { workspace = true, features = ["axum"] }
uuid = { workspace = true }
-models_opensearch = { path = "../models_opensearch" }
[package.metadata.cargo-machete]
ignored = ["connection_gateway"]
diff --git a/rust/cloud-storage/comms_service/src/api/activity/get_activity.rs b/rust/cloud-storage/comms_service/src/api/activity/get_activity.rs
deleted file mode 100644
index 99fa8f47a3..0000000000
--- a/rust/cloud-storage/comms_service/src/api/activity/get_activity.rs
+++ /dev/null
@@ -1,44 +0,0 @@
-use axum::extract::Json;
-use axum::http::StatusCode;
-use axum::{Extension, extract::State};
-use model::user::UserContext;
-
-use crate::api::context::AppState;
-use comms_db_client::{activity::get_activity::get_activities, model::Activity};
-use serde::{Deserialize, Serialize};
-use utoipa::ToSchema;
-
-#[derive(Debug, Serialize, Deserialize, ToSchema)]
-pub struct GetActivityResponse {
- pub items: Vec<Activity>,
-}
-
-#[tracing::instrument(skip(app_state, user_context), fields(user_id = user_context.user_id))]
-#[utoipa::path(get,
- tag = "activity",
- operation_id = "get_activity",
- path = "/activity", responses(
- (status = 200, body=GetActivityResponse),
- (status = 401, body=String),
- (status = 404, body=String),
- (status = 500, body=String),
-))]
-pub async fn get_activity_handler(
- app_state: State<AppState>,
- user_context: Extension<UserContext>,
-) -> Result<(StatusCode, Json<GetActivityResponse>), (StatusCode, String)> {
- let activities = get_activities(&app_state.db, &user_context.user_id)
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "unable to get activities");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- "unable to get activities".to_string(),
- )
- })?;
-
- Ok((
- StatusCode::OK,
- Json(GetActivityResponse { items: activities }),
- ))
-}
diff --git a/rust/cloud-storage/comms_service/src/api/activity/mod.rs b/rust/cloud-storage/comms_service/src/api/activity/mod.rs
index 0f0d4847c9..98719af1f4 100644
--- a/rust/cloud-storage/comms_service/src/api/activity/mod.rs
+++ b/rust/cloud-storage/comms_service/src/api/activity/mod.rs
@@ -1,15 +1 @@
-use axum::{
- Router,
- routing::{get, post},
-};
-
-use crate::api::context::AppState;
-
-pub mod get_activity;
pub mod post_activity;
-
-pub fn router() -> Router<AppState> {
- Router::new()
- .route("/", post(post_activity::post_activity_handler))
- .route("/", get(get_activity::get_activity_handler))
-}
diff --git a/rust/cloud-storage/comms_service/src/api/channels/add_participants.rs b/rust/cloud-storage/comms_service/src/api/channels/add_participants.rs
index 2dad04e578..5e0fa87c6d 100644
--- a/rust/cloud-storage/comms_service/src/api/channels/add_participants.rs
+++ b/rust/cloud-storage/comms_service/src/api/channels/add_participants.rs
@@ -1,5 +1,5 @@
use crate::api::channels::create_channel::to_lowercase;
-use crate::api::context::AppState;
+use crate::api::context::{AppState, ChannelImpl};
use crate::api::extractors::{
ChannelAdmin, ChannelId, ChannelName, ChannelParticipants, ChannelTypeExtractor,
};
@@ -9,11 +9,12 @@ use axum::extract::Json;
use axum::{extract::State, http::StatusCode};
use axum_extra::extract::Cached;
use comms_db_client::participants::add_participant::{AddParticipantOptions, add_participant};
+use doppleganger::Mirror;
use macro_user_id::cowlike::CowLike;
use macro_user_id::user_id::MacroUserIdStr;
-use model::comms::{ChannelType, ParticipantRole};
use model::document_storage_service_internal::UpdateUserChannelPermissionsRequest;
use model_notifications::CommonChannelMetadata;
+use models_comms::channel::ChannelType;
use models_permissions::share_permission::channel_share_permission::UpdateOperation;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
@@ -40,10 +41,11 @@ pub struct AddParticipantsRequest {
)
)]
#[tracing::instrument(skip(ctx, channel_participants))]
+#[axum::debug_handler]
pub async fn handler(
State(ctx): State<AppState>,
Cached(ChannelAdmin(channel_admin)): Cached<ChannelAdmin>,
- Cached(ChannelName(channel_name)): Cached<ChannelName>,
+ Cached(ChannelName(channel_name, ..)): Cached<ChannelName<ChannelImpl>>,
Cached(ChannelTypeExtractor(channel_type)): Cached<ChannelTypeExtractor>,
Cached(ChannelParticipants(channel_participants)): Cached<ChannelParticipants>,
Cached(ChannelId(channel_id)): Cached<ChannelId>,
@@ -65,7 +67,7 @@ pub async fn handler(
AddParticipantOptions {
channel_id: &channel_id,
user_id: participant.as_str(),
- participant_role: Some(ParticipantRole::Member),
+ participant_role: Some(model::comms::ParticipantRole::Member),
},
)
.await
@@ -98,7 +100,7 @@ pub async fn handler(
// There should always be participants, but better safe than sorry
if !participants.is_empty() {
let metadata = CommonChannelMetadata {
- channel_type,
+ channel_type: model_notifications::ChannelType::mirror(channel_type),
channel_name: channel_name.clone(),
};
comms_notification::dispatch_notifications_for_invite(
@@ -116,7 +118,7 @@ pub async fn handler(
})
.ok();
- if channel_type == ChannelType::Private && !channel_participants.is_empty() {
+ if matches!(channel_type, ChannelType::Private) && !channel_participants.is_empty() {
// Contacts: add participants to social graph
let channel_participants: Vec<String> = channel_participants
.iter()
diff --git a/rust/cloud-storage/comms_service/src/api/channels/get_channel.rs b/rust/cloud-storage/comms_service/src/api/channels/get_channel.rs
index 599e202209..2e6c766ded 100644
--- a/rust/cloud-storage/comms_service/src/api/channels/get_channel.rs
+++ b/rust/cloud-storage/comms_service/src/api/channels/get_channel.rs
@@ -1,5 +1,5 @@
use crate::api::{
- context::AppState,
+ context::{AppState, ChannelImpl},
extractors::{ChannelId, ChannelMember, ChannelName, ChannelParticipants, ParticipantAccess},
};
use anyhow::Result;
@@ -17,6 +17,7 @@ use comms_db_client::{
model::{Activity, Attachment, CountedReaction, Message},
reactions::{get_reactions::get_messages_reactions, group_reactions_by_message},
};
+use doppleganger::Mirror;
use futures::try_join;
use model::comms::{Channel, ChannelParticipant};
use serde::{Deserialize, Serialize};
@@ -71,7 +72,7 @@ pub async fn get_channel_handler(
ChannelId(channel_id): ChannelId,
ChannelParticipants(participants): ChannelParticipants,
ChannelMember(channel_member): ChannelMember,
- ChannelName(channel_name): ChannelName,
+ ChannelName(channel_name, ..): ChannelName<ChannelImpl>,
Cached(access): Cached<ParticipantAccess>,
Query(query): Query<GetChannelQuery>,
) -> Result<(StatusCode, Json<GetChannelResponse>), (StatusCode, String)> {
@@ -103,7 +104,7 @@ pub async fn get_channel_handler(
StatusCode::OK,
Json(GetChannelResponse {
channel,
- participants,
+ participants: <Vec<model::comms::ChannelParticipant>>::mirror(participants),
messages,
reactions,
activity,
diff --git a/rust/cloud-storage/comms_service/src/api/channels/get_channel_metadata.rs b/rust/cloud-storage/comms_service/src/api/channels/get_channel_metadata.rs
index 059be9c72a..fc947ada79 100644
--- a/rust/cloud-storage/comms_service/src/api/channels/get_channel_metadata.rs
+++ b/rust/cloud-storage/comms_service/src/api/channels/get_channel_metadata.rs
@@ -1,9 +1,6 @@
-use crate::{
- api::{
- context::AppState,
- extractors::{ChannelId, ChannelMember},
- },
- utils::channel_name::resolve_channel_name,
+use crate::api::{
+ context::AppState,
+ extractors::{ChannelId, ChannelMember},
};
use anyhow::Result;
use axum::{
@@ -12,37 +9,37 @@ use axum::{
response::{IntoResponse, Json, Response},
};
use axum_extra::extract::Cached;
+use comms::domain::models::channel_name::resolve_channel_name;
use comms_db_client::participants::get_participants::get_participants;
-#[allow(unused_imports)]
-use model::comms::{Channel, ChannelType};
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
+use models_comms::channel::OrganizationId;
use serde::{Deserialize, Serialize};
use sqlx::{Pool, Postgres};
use utoipa::ToSchema;
-use uuid::Uuid;
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct ChannelMetadataResponse {
pub channel_name: String,
- pub channel_type: ChannelType,
+ pub channel_type: model::comms::ChannelType,
}
#[derive(Deserialize, Debug)]
pub struct UserIdQuery {
- pub user_id: Option<String>,
+ pub user_id: MacroUserIdStr<'static>,
}
#[tracing::instrument(skip(db))]
pub async fn get_channel_name_and_type(
db: &Pool<Postgres>,
- channel_id: &Uuid,
- user_id: &str,
-) -> Result<(String, ChannelType)> {
- let channel_row = sqlx::query!(
+ channel_id: &models_comms::channel::ChannelId,
+ user_id: MacroUserIdStr<'_>,
+) -> Result<(String, model::comms::ChannelType)> {
+ let channel = sqlx::query!(
r#"
SELECT
id,
name,
- channel_type AS "channel_type: ChannelType",
+ channel_type AS "channel_type: model::comms::ChannelType",
org_id,
created_at,
updated_at,
@@ -50,30 +47,42 @@ pub async fn get_channel_name_and_type(
FROM comms_channels
WHERE id = $1
"#,
- channel_id
+ channel_id.0
)
+ .try_map(|channel_row| {
+ Ok(model::comms::Channel {
+ id: models_comms::channel::ChannelId(channel_row.id),
+ name: channel_row.name,
+ channel_type: channel_row.channel_type,
+ org_id: channel_row.org_id.map(|i| OrganizationId(i as u32)),
+ created_at: channel_row.created_at,
+ updated_at: channel_row.updated_at,
+ owner_id: MacroUserIdStr::parse_from_str(&channel_row.owner_id)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned(),
+ })
+ })
.fetch_one(db)
.await?;
- let channel = Channel {
- id: channel_row.id,
- name: channel_row.name,
- channel_type: channel_row.channel_type,
- org_id: channel_row.org_id,
- created_at: channel_row.created_at,
- updated_at: channel_row.updated_at,
- owner_id: channel_row.owner_id,
- };
-
- let participants = get_participants(db, channel_id).await?;
+ let participants = get_participants(db, &channel_id.0).await?;
let channel_name = resolve_channel_name(
- &channel.channel_type,
+ &match channel.channel_type {
+ model::comms::ChannelType::Public => models_comms::channel::ChannelType::Public,
+ model::comms::ChannelType::Organization => {
+ models_comms::channel::ChannelType::Organization
+ }
+ model::comms::ChannelType::Private => models_comms::channel::ChannelType::Private,
+ model::comms::ChannelType::DirectMessage => {
+ models_comms::channel::ChannelType::DirectMessage
+ }
+ },
channel.name.as_deref(),
&participants,
channel_id,
user_id,
- None,
+ &Default::default(),
);
Ok((channel_name, channel.channel_type))
@@ -81,22 +90,26 @@ pub async fn get_channel_name_and_type(
/// External handler with channel access middleware
#[tracing::instrument(skip(ctx))]
+#[axum::debug_handler]
pub async fn handler_external(
State(ctx): State<AppState>,
Cached(ChannelMember(channel_member)): Cached<ChannelMember>,
Cached(ChannelId(channel_id)): Cached<ChannelId>,
) -> Result<Response, Response> {
- let (channel_name, channel_type) =
- get_channel_name_and_type(&ctx.db, &channel_id, &channel_member.context.user_id)
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "unable to get channel metadata");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- "unable to get channel metadata",
- )
- .into_response()
- })?;
+ let (channel_name, channel_type) = get_channel_name_and_type(
+ &ctx.db,
+ &models_comms::channel::ChannelId(channel_id),
+ channel_member.user_id,
+ )
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, "unable to get channel metadata");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "unable to get channel metadata",
+ )
+ .into_response()
+ })?;
let response = ChannelMetadataResponse {
channel_name,
@@ -110,21 +123,20 @@ pub async fn handler_external(
#[tracing::instrument(skip(ctx))]
pub async fn handler_internal(
State(ctx): State<AppState>,
- Path(channel_id): Path<Uuid>,
+ Path(channel_id): Path<models_comms::channel::ChannelId>,
Query(query): Query<UserIdQuery>,
) -> Result<Response, Response> {
- let user_id = query.user_id.as_deref().unwrap_or("");
-
- let (channel_name, channel_type) = get_channel_name_and_type(&ctx.db, &channel_id, user_id)
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "unable to get channel metadata");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- "unable to get channel metadata",
- )
- .into_response()
- })?;
+ let (channel_name, channel_type) =
+ get_channel_name_and_type(&ctx.db, &channel_id, query.user_id)
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, "unable to get channel metadata");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "unable to get channel metadata",
+ )
+ .into_response()
+ })?;
let response = ChannelMetadataResponse {
channel_name,
diff --git a/rust/cloud-storage/comms_service/src/api/channels/get_channels.rs b/rust/cloud-storage/comms_service/src/api/channels/get_channels.rs
deleted file mode 100644
index 4b2b851e72..0000000000
--- a/rust/cloud-storage/comms_service/src/api/channels/get_channels.rs
+++ /dev/null
@@ -1,141 +0,0 @@
-use crate::{
- api::context::AppState,
- utils::{channel_name::resolve_channel_name, user_name::generate_name_lookup},
-};
-use anyhow::Result;
-use axum::{
- Json,
- extract::{Extension, State},
- http::StatusCode,
- response::IntoResponse,
-};
-use comms_db_client::{
- activity::get_activity::get_activities,
- channels::get_channels::get_user_channels_with_participants,
-};
-use comms_db_client::{messages::get_latest_channel_messages_batch, model::Activity};
-use frecency::domain::ports::AggregateFrecencyStorage;
-use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
-use model::{comms::ChannelWithLatest, user::UserContext};
-use model_entity::EntityType;
-use serde::{Deserialize, Serialize};
-use std::{collections::HashMap, str::FromStr};
-use thiserror::Error;
-use utoipa::ToSchema;
-use uuid::Uuid;
-
-#[derive(Debug, Serialize, Deserialize, ToSchema)]
-pub struct GetChannelsResponse {
- pub channels: Vec<ChannelWithLatest>,
-}
-
-#[derive(Debug, Error)]
-pub enum GetChannelsError {
- #[error(transparent)]
- Sqlx(#[from] sqlx::Error),
- #[error("Invalid user id")]
- Id(#[from] macro_user_id::error::ParseErr),
-}
-
-impl IntoResponse for GetChannelsError {
- fn into_response(self) -> axum::response::Response {
- let status = match &self {
- GetChannelsError::Sqlx(_) | GetChannelsError::Id(_) => {
- StatusCode::INTERNAL_SERVER_ERROR
- }
- };
- (status, self.to_string()).into_response()
- }
-}
-
-#[utoipa::path(
- get,
- path = "/channels",
- tag = "channels",
- operation_id = "get_channels",
- responses(
- (status = 200, body=GetChannelsResponse),
- (status = 401, body=String),
- (status = 404, body=String),
- (status = 500, body=String),
- )
- )]
-#[tracing::instrument(skip(app_state, user_context), fields(user_id=?user_context.user_id))]
-pub async fn get_channels_handler(
- State(app_state): State<AppState>,
- user_context: Extension<UserContext>,
-) -> Result<Json<GetChannelsResponse>, GetChannelsError> {
- let db = &app_state.db;
-
- let channels = get_user_channels_with_participants(db, &user_context.user_id).await?;
-
- let channel_ids: Vec<Uuid> = channels.iter().map(|c| c.channel.id).collect();
-
- let ids: Vec<_> = channel_ids
- .iter()
- .map(|id| EntityType::Channel.with_entity_string(id.to_string()))
- .collect();
-
- let (names_res, latest_messages, activities, frecency_score) = futures::join!(
- app_state
- .auth_service_client
- .get_names_from_channels(&channels),
- get_latest_channel_messages_batch(db, &channel_ids),
- get_activities(db, &user_context.user_id),
- app_state.frecency_storage.get_aggregate_for_user_entities(
- MacroUserIdStr::parse_from_str(&user_context.0.user_id)?.into_owned(),
- ids.as_slice()
- )
- );
-
- let mut activity_lookup: HashMap<Uuid, Activity> = activities
- .unwrap_or_default()
- .into_iter()
- .map(|a| (a.channel_id, a))
- .collect();
-
- let frecency_map: HashMap<Uuid, f64> = frecency_score
- .unwrap_or_default()
- .into_iter()
- .filter_map(|f| {
- Some((
- Uuid::from_str(&f.id.entity.entity_id).ok()?,
- f.data.frecency_score,
- ))
- })
- .collect();
-
- let name_lookup = names_res.ok().map(generate_name_lookup);
-
- let mut latest_messages = latest_messages.unwrap_or_default();
- // Map a channel to its correct name and latest message
- let channels: Vec<ChannelWithLatest> = channels
- .into_iter()
- .map(|mut channel| {
- let resolved_name = resolve_channel_name(
- &channel.channel.channel_type,
- channel.channel.name.as_deref(),
- &channel.participants,
- &channel.channel.id,
- &user_context.user_id,
- name_lookup.as_ref(),
- );
- channel.channel.name = Some(resolved_name);
- let activity = activity_lookup.remove(&channel.channel.id);
- let viewed_at = activity.as_ref().and_then(|a| a.viewed_at);
- let interacted_at = activity.as_ref().and_then(|a| a.interacted_at);
- let channel_with_latest = ChannelWithLatest {
- channel: channel.clone(),
- latest_message: latest_messages.remove(&channel.channel.id).unwrap_or_default(),
- viewed_at,
- interacted_at,
- frecency_score: frecency_map.get(&channel.channel.id).copied().unwrap_or_default()
- };
-
- tracing::trace!(channel_type=?channel.channel.channel_type,channel_name=?channel.channel.name, "resolved channel name");
- channel_with_latest
- })
- .collect();
-
- return Ok(Json(GetChannelsResponse { channels }));
-}
diff --git a/rust/cloud-storage/comms_service/src/api/channels/join_channel.rs b/rust/cloud-storage/comms_service/src/api/channels/join_channel.rs
index fb0af9ea7e..8a9e1e4b6e 100644
--- a/rust/cloud-storage/comms_service/src/api/channels/join_channel.rs
+++ b/rust/cloud-storage/comms_service/src/api/channels/join_channel.rs
@@ -6,7 +6,7 @@ use axum::{
};
use axum_extra::extract::Cached;
use comms_db_client::participants::add_participant::{AddParticipantOptions, add_participant};
-use model::comms::{ChannelType, ParticipantRole};
+use model::comms::ParticipantRole;
use model::user::UserContext;
use sqlx::PgPool;
@@ -36,7 +36,7 @@ pub async fn join_channel_handler(
Cached(ChannelId(channel_id)): Cached<ChannelId>,
user_ctx: Extension<UserContext>,
) -> Result<StatusCode, (StatusCode, String)> {
- if let ChannelType::DirectMessage = channel_type {
+ if let models_comms::channel::ChannelType::DirectMessage = channel_type {
tracing::error!("user tried to join a direct message channel");
return Err((
StatusCode::BAD_REQUEST,
diff --git a/rust/cloud-storage/comms_service/src/api/channels/leave_channel.rs b/rust/cloud-storage/comms_service/src/api/channels/leave_channel.rs
index ffe50121a8..11852ccdec 100644
--- a/rust/cloud-storage/comms_service/src/api/channels/leave_channel.rs
+++ b/rust/cloud-storage/comms_service/src/api/channels/leave_channel.rs
@@ -8,7 +8,6 @@ use axum_extra::extract::Cached;
use comms_db_client::participants::remove_participant::{
RemoveParticipantOptions, remove_participant,
};
-use model::comms::ChannelType;
#[utoipa::path(
post,
@@ -35,14 +34,15 @@ pub async fn leave_channel_handler(
Cached(ChannelMember(channel_member)): Cached<ChannelMember>,
) -> Result<StatusCode, (StatusCode, String)> {
match (channel_type, participants.len()) {
- (ChannelType::Organization, _) => {
+ (models_comms::channel::ChannelType::Organization, _) => {
tracing::warn!("user tried to leave organization channel");
return Err((
StatusCode::BAD_REQUEST,
"cannot leave organization channel".to_string(),
));
}
- (ChannelType::Private, 2) | (ChannelType::DirectMessage, _) => {
+ (models_comms::channel::ChannelType::Private, 2)
+ | (models_comms::channel::ChannelType::DirectMessage, _) => {
tracing::warn!("user tried to leave private channel with only 2 participants");
return Err((
StatusCode::BAD_REQUEST,
diff --git a/rust/cloud-storage/comms_service/src/api/channels/mod.rs b/rust/cloud-storage/comms_service/src/api/channels/mod.rs
index 761e6c5126..62df8975cf 100644
--- a/rust/cloud-storage/comms_service/src/api/channels/mod.rs
+++ b/rust/cloud-storage/comms_service/src/api/channels/mod.rs
@@ -11,7 +11,6 @@ pub mod delete_message;
pub mod get_channel;
pub mod get_channel_metadata;
pub mod get_channel_transcript;
-pub mod get_channels;
pub mod get_mentions;
pub mod get_message_with_context;
pub mod get_or_create_dm;
@@ -31,10 +30,6 @@ use tower_http::compression::CompressionLayer;
pub fn router() -> Router<AppState> {
Router::new()
.route("/", post(create_channel::create_channel_handler))
- .route(
- "/",
- get(get_channels::get_channels_handler).layer(CompressionLayer::new()),
- )
.route(
"/:channel_id",
get(get_channel::get_channel_handler).layer(compose_layers![CompressionLayer::new(),]),
diff --git a/rust/cloud-storage/comms_service/src/api/channels/patch_channel.rs b/rust/cloud-storage/comms_service/src/api/channels/patch_channel.rs
index 71169081b8..35cd46603e 100644
--- a/rust/cloud-storage/comms_service/src/api/channels/patch_channel.rs
+++ b/rust/cloud-storage/comms_service/src/api/channels/patch_channel.rs
@@ -6,7 +6,6 @@ use anyhow::Result;
use axum::{Json, extract::State, http::StatusCode};
use axum_extra::extract::Cached;
use comms_db_client::channels::patch_channel::{self, PatchChannelOptions};
-use model::comms::ChannelType;
use models_opensearch::SearchEntityType;
use tracing::Instrument;
@@ -31,7 +30,11 @@ pub async fn patch_channel_handler(
Cached(ChannelTypeExtractor(channel_type)): Cached<ChannelTypeExtractor>,
Json(req): Json<PatchChannelOptions>,
) -> Result<(StatusCode, String), (StatusCode, String)> {
- if channel_type == ChannelType::DirectMessage && req.channel_name.is_some() {
+ if matches!(
+ channel_type,
+ models_comms::channel::ChannelType::DirectMessage
+ ) && req.channel_name.is_some()
+ {
return Err((
StatusCode::BAD_REQUEST,
"cannot change channel_name for direct message channels".to_string(),
diff --git a/rust/cloud-storage/comms_service/src/api/channels/patch_message.rs b/rust/cloud-storage/comms_service/src/api/channels/patch_message.rs
index 99b32cddf6..c4795670fb 100644
--- a/rust/cloud-storage/comms_service/src/api/channels/patch_message.rs
+++ b/rust/cloud-storage/comms_service/src/api/channels/patch_message.rs
@@ -16,6 +16,7 @@ use comms_db_client::{
messages::patch_message::{patch_message, patch_message_attachments},
model::ActivityType,
};
+use macro_user_id::cowlike::CowLike;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use uuid::Uuid;
@@ -79,7 +80,7 @@ pub async fn patch_message_handler(
})?;
let participants = participants;
- let participants: Vec<String> = if let Some(thread_id) = message.thread_id.as_ref() {
+ let participants: Vec<_> = if let Some(thread_id) = message.thread_id.as_ref() {
comms_db_client::participants::get_participants::get_channel_participants_for_thread_id(
&app_state.db,
thread_id,
@@ -93,7 +94,7 @@ pub async fn patch_message_handler(
)
})?
} else {
- participants.iter().map(|p| p.user_id.clone()).collect()
+ participants.iter().map(|p| p.user_id.copied()).collect()
};
notify::notify_message(&app_state, message, &participants)
.await
diff --git a/rust/cloud-storage/comms_service/src/api/channels/post_message.rs b/rust/cloud-storage/comms_service/src/api/channels/post_message.rs
index 9457ae8525..46a9077182 100644
--- a/rust/cloud-storage/comms_service/src/api/channels/post_message.rs
+++ b/rust/cloud-storage/comms_service/src/api/channels/post_message.rs
@@ -1,3 +1,4 @@
+use crate::api::context::ChannelImpl;
use crate::api::{context::AppState, extractors::ChannelName};
use crate::notification as comms_notification;
use crate::{
@@ -21,6 +22,8 @@ use comms_db_client::{
messages::{add_attachments, create_message, create_message_mentions},
model::{ActivityType, NewAttachment, SimpleMention},
};
+use doppleganger::Mirror;
+use macro_user_id::cowlike::CowLike;
use model::comms::ChannelParticipant;
use model::document_storage_service_internal::UpdateChannelSharePermissionRequest;
use model_notifications::CommonChannelMetadata;
@@ -62,7 +65,7 @@ pub async fn post_message_handler(
State(ctx): State<AppState>,
ChannelMember(channel_member): ChannelMember,
Cached(ChannelParticipants(channel_participants)): Cached<ChannelParticipants>,
- Cached(ChannelName(channel_name)): Cached<ChannelName>,
+ Cached(ChannelName(channel_name, ..)): Cached<ChannelName<ChannelImpl>>,
Cached(ChannelId(channel_id)): Cached<ChannelId>,
Cached(ChannelTypeExtractor(channel_type)): Cached<ChannelTypeExtractor>,
extract::Json(req): extract::Json<PostMessageRequest>,
@@ -205,10 +208,9 @@ pub async fn post_message_handler(
// TODO: -- end
- let participants: Vec<String> = channel_participants
- .clone()
+ let participants: Vec<_> = channel_participants
.iter()
- .map(|p| p.user_id.clone())
+ .map(|p| p.user_id.copied())
.collect();
let start_time = Instant::now();
@@ -280,10 +282,10 @@ pub async fn post_message_handler(
&ctx,
channel_id,
CommonChannelMetadata {
- channel_type,
+ channel_type: model_notifications::ChannelType::mirror(channel_type),
channel_name: channel_name.clone(),
},
- channel_participants.clone(),
+ <Vec<model::comms::ChannelParticipant>>::mirror(channel_participants),
message.clone(),
req.mentions.clone(),
);
diff --git a/rust/cloud-storage/comms_service/src/api/channels/remove_participants.rs b/rust/cloud-storage/comms_service/src/api/channels/remove_participants.rs
index edb7d99d8e..40158af5c6 100644
--- a/rust/cloud-storage/comms_service/src/api/channels/remove_participants.rs
+++ b/rust/cloud-storage/comms_service/src/api/channels/remove_participants.rs
@@ -7,7 +7,6 @@ use axum_extra::extract::Cached;
use comms_db_client::participants::remove_participant::{
RemoveParticipantOptions, remove_participant,
};
-use model::comms::ChannelType;
use model::document_storage_service_internal::UpdateUserChannelPermissionsRequest;
use models_permissions::share_permission::channel_share_permission::UpdateOperation;
use serde::{Deserialize, Serialize};
@@ -42,7 +41,7 @@ pub async fn handler(
Cached(ChannelId(channel_id)): Cached<ChannelId>,
req: Json<RemoveParticipantsRequest>,
) -> Result<StatusCode, (StatusCode, String)> {
- if let ChannelType::DirectMessage = channel_type {
+ if let models_comms::channel::ChannelType::DirectMessage = channel_type {
tracing::error!("cannot add or remove participants from direct message channel");
return Err((
StatusCode::BAD_REQUEST,
diff --git a/rust/cloud-storage/comms_service/src/api/context.rs b/rust/cloud-storage/comms_service/src/api/context.rs
index c44df48529..f6adeacd90 100644
--- a/rust/cloud-storage/comms_service/src/api/context.rs
+++ b/rust/cloud-storage/comms_service/src/api/context.rs
@@ -1,4 +1,9 @@
use axum_macros::FromRef;
+use comms::{
+ domain::service::ChannelServiceImpl,
+ inbound::CommsRouterState,
+ outbound::{http::user_repo::UserRepoImpl, postgres::comms_repo::PgCommsRepo},
+};
use connection_gateway_client::client::ConnectionGatewayClient;
use frecency::outbound::postgres::FrecencyPgStorage;
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
@@ -26,4 +31,7 @@ pub struct AppState {
pub auth_service_client: Arc<authentication_service_client::AuthServiceClient>,
pub permissions_token_secret: LocalOrRemoteSecret<DocumentPermissionJwtSecretKey>,
pub frecency_storage: FrecencyPgStorage,
+ pub comms_state: CommsRouterState<ChannelImpl>,
}
+
+pub type ChannelImpl = ChannelServiceImpl<PgCommsRepo, UserRepoImpl, FrecencyPgStorage>;
diff --git a/rust/cloud-storage/comms_service/src/api/extractor.rs b/rust/cloud-storage/comms_service/src/api/extractor.rs
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/rust/cloud-storage/comms_service/src/api/extractors.rs b/rust/cloud-storage/comms_service/src/api/extractors.rs
index f088aa4742..ff83438aef 100644
--- a/rust/cloud-storage/comms_service/src/api/extractors.rs
+++ b/rust/cloud-storage/comms_service/src/api/extractors.rs
@@ -1,39 +1,51 @@
-use authentication_service_client::AuthServiceClient;
use axum::{
- Extension, async_trait,
+ RequestPartsExt, async_trait,
extract::{FromRef, FromRequestParts, Path},
http::{StatusCode, request::Parts},
response::{IntoResponse, Response},
};
use axum_extra::extract::Cached;
+use comms::{
+ domain::{models::channel_name::resolve_channel_name, ports::ChannelsService},
+ inbound::CommsRouterState,
+};
use comms_db_client::{
channels::get_channel_info::{ChannelInfo, get_channel_info},
messages::get_message_owner::get_message_owner,
participants::get_participants::get_participants,
};
+use doppleganger::Mirror;
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use model::{
- comms::{ChannelParticipant, ParticipantRole},
- user::UserContext,
+ comms::ParticipantRole,
+ user::{UserContext, axum_extractor::MacroUserExtractor},
};
-use models_comms::ChannelType;
+use models_comms::channel::ChannelType;
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
-use std::{collections::HashMap, sync::Arc};
+use std::{
+ collections::{HashMap, HashSet},
+ marker::PhantomData,
+};
use utoipa::ToSchema;
use uuid::Uuid;
-use crate::utils::{channel_name::resolve_channel_name, user_name::generate_name_lookup};
+#[derive(Serialize, Deserialize, Debug)]
+pub struct ChannelName<T>(pub String, pub PhantomData<T>);
-#[derive(Serialize, Deserialize, Debug, Clone)]
-pub struct ChannelName(pub String);
+impl<T> Clone for ChannelName<T> {
+ fn clone(&self) -> Self {
+ Self(self.0.clone(), PhantomData)
+ }
+}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ChannelId(pub Uuid);
-#[derive(Serialize, Deserialize, Clone, Debug)]
-pub struct ChannelParticipants(pub Vec<ChannelParticipant>);
+#[derive(Deserialize, Clone, Debug)]
+pub struct ChannelParticipants(pub Vec<models_comms::channel::ChannelParticipant>);
-#[derive(Serialize, Deserialize, Clone, Debug)]
+#[derive(Debug, Clone, Copy)]
pub struct ChannelTypeExtractor(pub ChannelType);
#[derive(Serialize, Deserialize, Clone, Debug, ToSchema)]
@@ -61,13 +73,6 @@ pub async fn extract_path_uuid_by_name(parts: &mut Parts, name: &str) -> Result<
})
}
-async fn extract_user_context(parts: &mut Parts) -> Result<UserContext, Response> {
- Extension::<UserContext>::from_request_parts(parts, &())
- .await
- .map(|Extension(ctx)| ctx)
- .map_err(|_| unauthorized("Missing user context"))
-}
-
async fn extract_cached<T, S>(parts: &mut Parts, state: &S) -> Result<T, Response>
where
T: 'static,
@@ -154,47 +159,59 @@ where
}
#[async_trait]
-impl<S> FromRequestParts<S> for ChannelName
+impl<S, U> FromRequestParts<S> for ChannelName<U>
where
S: Send + Sync,
PgPool: FromRef<S>,
- Arc<AuthServiceClient>: FromRef<S>,
+ CommsRouterState<U>: FromRef<S>,
+ U: ChannelsService,
{
type Rejection = Response;
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
- let auth_service_client = <Arc<AuthServiceClient>>::from_ref(state);
let ChannelId(channel_id) = extract_cached::<ChannelId, _>(parts, state).await?;
let ChannelTypeExtractor(channel_type) =
extract_cached::<ChannelTypeExtractor, _>(parts, state).await?;
let ChannelParticipants(participants) =
extract_cached::<ChannelParticipants, _>(parts, state).await?;
- let UserContext { user_id, .. } = extract_user_context(parts).await?;
+ let MacroUserExtractor { macro_user_id, .. } =
+ parts.extract().await.map_err(IntoResponse::into_response)?;
let ChannelInfoExtractor(ChannelInfo { name, .. }) =
extract_cached::<ChannelInfoExtractor, _>(parts, state).await?;
let user_ids = participants
.iter()
- .map(|p| p.user_id.clone())
- .collect::<Vec<String>>();
+ .map(|p| p.user_id.copied())
+ .collect::<HashSet<_>>();
- let name_lookup = auth_service_client
+ let service = <CommsRouterState<U>>::from_ref(state);
+ let name_lookup = service
+ .inner
.get_names(user_ids)
.await
.ok()
- .map(generate_name_lookup);
+ .map(|names| {
+ names
+ .into_iter()
+ .filter_map(|n| {
+ let display = n.display_name()?;
+ Some((n.id, display))
+ })
+ .collect::<HashMap<_, _>>()
+ })
+ .unwrap_or_default();
let channel_name = resolve_channel_name(
&channel_type,
name.as_deref(),
&participants,
- &channel_id,
- &user_id,
- name_lookup.as_ref(),
+ &models_comms::channel::ChannelId(channel_id),
+ macro_user_id,
+ &name_lookup,
);
- return Ok(ChannelName(channel_name));
+ return Ok(ChannelName(channel_name, PhantomData));
}
}
@@ -223,32 +240,42 @@ where
.into_response()
})?;
- Ok(ChannelTypeExtractor(info.channel_type))
+ Ok(ChannelTypeExtractor(match info.channel_type {
+ model::comms::ChannelType::Public => models_comms::channel::ChannelType::Public,
+ model::comms::ChannelType::Organization => {
+ models_comms::channel::ChannelType::Organization
+ }
+ model::comms::ChannelType::Private => models_comms::channel::ChannelType::Private,
+ model::comms::ChannelType::DirectMessage => {
+ models_comms::channel::ChannelType::DirectMessage
+ }
+ }))
}
}
-#[derive(Serialize, Deserialize, Clone, Debug)]
+#[derive(Clone, Debug)]
pub struct UserContextWithRole {
pub context: UserContext,
- pub role: Option<ParticipantRole>,
+ pub user_id: MacroUserIdStr<'static>,
+ pub role: Option<models_comms::channel::ParticipantRole>,
}
pub async fn get_user_role(
user_context: &UserContext,
info: &ChannelInfo,
- participants: &[ChannelParticipant],
-) -> Option<ParticipantRole> {
+ participants: &[models_comms::channel::ChannelParticipant],
+) -> Option<models_comms::channel::ParticipantRole> {
let user_participant = participants
.iter()
- .find(|p| p.user_id == user_context.user_id);
+ .find(|p| p.user_id.as_ref() == user_context.user_id);
match info.channel_type {
- ChannelType::Public => Some(
+ model::comms::ChannelType::Public => Some(
user_participant
.map(|p| p.role)
- .unwrap_or(ParticipantRole::Member),
+ .unwrap_or(models_comms::channel::ParticipantRole::Member),
),
- ChannelType::Organization => {
+ model::comms::ChannelType::Organization => {
let org_match = user_context
.organization_id
.and_then(|user_org| info.org_id.map(|ch_org| ch_org == user_org as i64))
@@ -258,7 +285,7 @@ pub async fn get_user_role(
Some(
user_participant
.map(|p| p.role)
- .unwrap_or(ParticipantRole::Member),
+ .unwrap_or(models_comms::channel::ParticipantRole::Member),
)
} else {
user_participant.map(|p| p.role)
@@ -283,7 +310,11 @@ where
let Cached(ChannelParticipants(participants)) =
Cached::<ChannelParticipants>::from_request_parts(parts, state).await?;
- let user_context = extract_user_context(parts).await?;
+ let MacroUserExtractor {
+ macro_user_id,
+ user_context,
+ ..
+ } = parts.extract().await.map_err(IntoResponse::into_response)?;
let info = get_channel_info(&PgPool::from_ref(state), &channel_id)
.await
.map_err(|err| {
@@ -297,12 +328,13 @@ where
let role = get_user_role(&user_context, &info, &participants).await;
Ok(UserContextWithRole {
context: user_context,
+ user_id: macro_user_id,
role,
})
}
}
-#[derive(Serialize, Deserialize, Clone, Debug)]
+#[derive(Clone, Debug)]
pub struct ChannelMember(pub UserContextWithRole);
#[async_trait]
@@ -323,7 +355,7 @@ where
}
}
-#[derive(Serialize, Deserialize, Clone, Debug)]
+#[derive(Clone, Debug)]
pub struct ChannelOwner(pub UserContextWithRole);
#[async_trait]
@@ -338,13 +370,15 @@ where
let user_context_with_role = UserContextWithRole::from_request_parts(parts, state).await?;
match user_context_with_role.role {
- Some(ParticipantRole::Owner) => Ok(ChannelOwner(user_context_with_role)),
+ Some(models_comms::channel::ParticipantRole::Owner) => {
+ Ok(ChannelOwner(user_context_with_role))
+ }
_ => Err(unauthorized("user is not authorized to view this channel")),
}
}
}
-#[derive(Serialize, Deserialize, Clone, Debug)]
+#[derive(Clone, Debug)]
pub struct ChannelAdmin(pub UserContextWithRole);
#[async_trait]
@@ -359,9 +393,10 @@ where
let user_context_with_role = UserContextWithRole::from_request_parts(parts, state).await?;
match user_context_with_role.role {
- Some(ParticipantRole::Owner | ParticipantRole::Admin) => {
- Ok(ChannelAdmin(user_context_with_role))
- }
+ Some(
+ models_comms::channel::ParticipantRole::Owner
+ | models_comms::channel::ParticipantRole::Admin,
+ ) => Ok(ChannelAdmin(user_context_with_role)),
_ => Err(unauthorized("user is not authorized to view this channel")),
}
}
@@ -415,7 +450,8 @@ where
}
}
-#[derive(Serialize, Deserialize, Clone, Debug)]
+#[derive(Clone, Debug)]
+#[expect(dead_code)]
pub enum MessageSenderOrAdmin {
MessageSender(MessageSender),
ChannelAdmin(ChannelAdmin),
@@ -452,7 +488,9 @@ where
let user_context_with_role = extract_cached::<UserContextWithRole, _>(parts, state).await?;
match user_context_with_role.role {
- Some(role) => Ok(ParticipantAccess::Access { role }),
+ Some(role) => Ok(ParticipantAccess::Access {
+ role: ParticipantRole::mirror(role),
+ }),
_ => Ok(ParticipantAccess::NoAccess),
}
}
diff --git a/rust/cloud-storage/comms_service/src/api/internal/add_user_to_org_channels.rs b/rust/cloud-storage/comms_service/src/api/internal/add_user_to_org_channels.rs
index 55c708ab38..9fc08f3aa2 100644
--- a/rust/cloud-storage/comms_service/src/api/internal/add_user_to_org_channels.rs
+++ b/rust/cloud-storage/comms_service/src/api/internal/add_user_to_org_channels.rs
@@ -27,7 +27,7 @@ pub async fn handler(
add_participant(
&ctx.db,
AddParticipantOptions {
- channel_id: &channel.id,
+ channel_id: &channel.id.0,
user_id: &req.user_id,
participant_role: Some(ParticipantRole::Member),
},
diff --git a/rust/cloud-storage/comms_service/src/api/internal/create_welcome_message.rs b/rust/cloud-storage/comms_service/src/api/internal/create_welcome_message.rs
index 82ec53499f..40ebf7a806 100644
--- a/rust/cloud-storage/comms_service/src/api/internal/create_welcome_message.rs
+++ b/rust/cloud-storage/comms_service/src/api/internal/create_welcome_message.rs
@@ -12,6 +12,7 @@ use comms_db_client::{
messages::create_message,
model::ActivityType,
};
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use tracing::Instrument;
use crate::{api::context::AppState, service::sender::notify};
@@ -30,17 +31,13 @@ pub async fn handler(
) -> Result<Response, Response> {
tracing::trace!("checking channels for user");
- if req.welcome_user_id.is_empty() || req.to_user_id.is_empty() {
- return Err((StatusCode::BAD_REQUEST, "empty user ids").into_response());
- }
-
tokio::spawn(
{
let ctx = app_state.clone();
let welcome_user_id = req.welcome_user_id.clone();
let to_user_id = req.to_user_id.clone();
async move {
- if let Err(e) = create_welcome_message(&ctx, &welcome_user_id, &to_user_id).await {
+ if let Err(e) = create_welcome_message(&ctx, welcome_user_id, to_user_id).await {
tracing::error!(error=?e, "unable to create welcome message");
}
}
@@ -54,17 +51,18 @@ pub async fn handler(
#[tracing::instrument(skip(ctx))]
async fn create_welcome_message(
ctx: &AppState,
- welcome_user_id: &str,
- to_user_id: &str,
+ welcome_user_id: MacroUserIdStr<'_>,
+ to_user_id: MacroUserIdStr<'_>,
) -> anyhow::Result<()> {
let content = WELCOME_MESSAGE.to_string();
let sleep_time = SLEEP_TIME_SECONDS;
- let participants: Vec<String> = vec![welcome_user_id.to_string(), to_user_id.to_string()];
+ let participants: Vec<_> = vec![welcome_user_id.copied(), to_user_id.copied()];
tracing::trace!("sleeping welcome message");
tokio::time::sleep(std::time::Duration::from_secs(sleep_time)).await;
- let maybe_dm = get_dm::maybe_get_dm(&ctx.db, welcome_user_id, to_user_id).await?;
+ let maybe_dm =
+ get_dm::maybe_get_dm(&ctx.db, welcome_user_id.as_ref(), to_user_id.as_ref()).await?;
let (channel_id, action) = match maybe_dm {
Some(private_id) => (private_id, GetOrCreateAction::Get),
@@ -76,7 +74,7 @@ async fn create_welcome_message(
owner_id: welcome_user_id.to_string(),
org_id: None,
channel_type: ChannelType::DirectMessage,
- participants: participants.clone(),
+ participants: participants.iter().map(|x| x.to_string()).collect(),
},
)
.await?;
@@ -117,7 +115,7 @@ async fn create_welcome_message(
upsert_activity(
&ctx.db,
- welcome_user_id,
+ welcome_user_id.as_ref(),
&channel_id,
&ActivityType::Interact,
)
diff --git a/rust/cloud-storage/comms_service/src/api/internal/get_channel_participants.rs b/rust/cloud-storage/comms_service/src/api/internal/get_channel_participants.rs
index 9f37d2c954..6d4a9154bb 100644
--- a/rust/cloud-storage/comms_service/src/api/internal/get_channel_participants.rs
+++ b/rust/cloud-storage/comms_service/src/api/internal/get_channel_participants.rs
@@ -3,6 +3,7 @@ use axum::{
extract::{Path, State},
response::{IntoResponse, Json, Response},
};
+use doppleganger::Mirror;
use reqwest::StatusCode;
use uuid::Uuid;
@@ -30,5 +31,11 @@ pub async fn handler(
.into_response()
})?;
- Ok((StatusCode::OK, Json(participants)).into_response())
+ Ok((
+ StatusCode::OK,
+ Json(<Vec<model::comms::ChannelParticipant>>::mirror(
+ participants,
+ )),
+ )
+ .into_response())
}
diff --git a/rust/cloud-storage/comms_service/src/api/internal/remove_user_from_org_channels.rs b/rust/cloud-storage/comms_service/src/api/internal/remove_user_from_org_channels.rs
index 8799134122..b4cf90d837 100644
--- a/rust/cloud-storage/comms_service/src/api/internal/remove_user_from_org_channels.rs
+++ b/rust/cloud-storage/comms_service/src/api/internal/remove_user_from_org_channels.rs
@@ -28,7 +28,7 @@ pub async fn handler(
remove_participant(
&ctx.db,
RemoveParticipantOptions {
- channel_id: &channel.id,
+ channel_id: &channel.id.0,
user_id: &req.user_id,
},
)
diff --git a/rust/cloud-storage/comms_service/src/api/mod.rs b/rust/cloud-storage/comms_service/src/api/mod.rs
index 61426f51d4..5194003a9c 100644
--- a/rust/cloud-storage/comms_service/src/api/mod.rs
+++ b/rust/cloud-storage/comms_service/src/api/mod.rs
@@ -1,5 +1,9 @@
-use crate::api::context::AppState;
-use axum::{Router, middleware::from_fn_with_state, routing::IntoMakeService};
+use crate::api::{activity::post_activity, context::AppState};
+use axum::{
+ Router,
+ middleware::from_fn_with_state,
+ routing::{IntoMakeService, post},
+};
use tower_http::trace::TraceLayer;
use utoipa::OpenApi;
use utoipa_swagger_ui::SwaggerUi;
@@ -22,7 +26,8 @@ pub fn service(app_state: AppState) -> Service {
let cors = macro_cors::cors_layer();
let app = Router::new()
- .nest("/activity", activity::router())
+ .merge(comms::inbound::comms_router(app_state.comms_state.clone()))
+ .route("/activity", post(post_activity::post_activity_handler))
.nest("/channels", channels::router())
.nest("/preview", preview::router())
.nest("/attachments", attachments::router())
diff --git a/rust/cloud-storage/comms_service/src/api/preview/get_batch_preview.rs b/rust/cloud-storage/comms_service/src/api/preview/get_batch_preview.rs
index 487f90e4a0..9144211628 100644
--- a/rust/cloud-storage/comms_service/src/api/preview/get_batch_preview.rs
+++ b/rust/cloud-storage/comms_service/src/api/preview/get_batch_preview.rs
@@ -1,11 +1,11 @@
use crate::utils::previews::resolve_previews;
use anyhow::Result;
+use axum::extract::Json;
use axum::extract::State;
use axum::response::{IntoResponse, Response};
-use axum::{Extension, extract::Json};
use comms_db_client::model::ChannelPreview;
use model::response::{GenericErrorResponse, GenericResponse};
-use model::user::UserContext;
+use model::user::axum_extractor::MacroUserExtractor;
use reqwest::StatusCode;
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
@@ -36,13 +36,17 @@ pub struct GetBatchChannelPreviewResponse {
)]
pub async fn handler(
State(db): State<PgPool>,
- user_context: Extension<UserContext>,
+ MacroUserExtractor {
+ macro_user_id,
+ user_context,
+ ..
+ }: MacroUserExtractor,
Json(req): Json<GetBatchChannelPreviewRequest>,
) -> Result<(StatusCode, Json<GetBatchChannelPreviewResponse>), Response> {
let raw_previews = comms_db_client::preview::batch_get_channel_preview(
&db,
&req.channel_ids,
- &user_context.user_id,
+ macro_user_id.as_ref(),
user_context.organization_id.map(|org_id| org_id as i64),
)
.await
@@ -57,7 +61,7 @@ pub async fn handler(
// TODO: if previews include direct messages or private group chats, generate lookup table
// somehow
- let previews = resolve_previews(&user_context, raw_previews, None);
+ let previews = resolve_previews(macro_user_id, raw_previews, &Default::default());
Ok((
StatusCode::OK,
diff --git a/rust/cloud-storage/comms_service/src/api/swagger.rs b/rust/cloud-storage/comms_service/src/api/swagger.rs
index 2f05c514ec..e117002e64 100644
--- a/rust/cloud-storage/comms_service/src/api/swagger.rs
+++ b/rust/cloud-storage/comms_service/src/api/swagger.rs
@@ -1,12 +1,10 @@
use crate::api::{
- activity::get_activity::GetActivityResponse,
activity::post_activity::PostActivityRequest,
channels::{
add_participants::AddParticipantsRequest,
create_channel::{CreateChannelRequest, CreateChannelResponse},
delete_message::DeleteMessageParams,
get_channel::GetChannelResponse,
- get_channels::GetChannelsResponse,
get_or_create_dm::{GetOrCreateDmRequest, GetOrCreateDmResponse},
get_or_create_private::{GetOrCreatePrivateRequest, GetOrCreatePrivateResponse},
patch_message::{PatchMessageParams, PatchMessageRequest},
@@ -23,13 +21,14 @@ use crate::api::{
};
use crate::api::extractors::ParticipantAccess;
+use comms::inbound::{ApiActivity, ApiChannelWithLatest};
use comms_db_client::channels::patch_channel::PatchChannelOptions;
use comms_db_client::model::{
Activity, ActivityType, CountedReaction, EntityMention, Message, NewAttachment, Reaction,
SimpleMention,
};
use model::comms::{
- Channel, ChannelParticipant, ChannelType, ChannelWithLatest, ChannelWithParticipants,
+ Channel, ChannelParticipant, ChannelType, ChannelWithParticipants,
GetMessageWithContextResponse, GetOrCreateAction, LatestMessage, ParticipantRole,
};
@@ -38,10 +37,9 @@ use model::version::CommunicationServiceApiVersion;
use utoipa::OpenApi;
use super::channels::{
- add_participants, create_channel, delete_channel, delete_message, get_channel, get_channels,
- get_mentions, get_message_with_context, get_or_create_dm, get_or_create_private, join_channel,
- leave_channel, patch_channel, patch_message, post_message, post_reaction, post_typing,
- remove_participants,
+ add_participants, create_channel, delete_channel, delete_message, get_channel, get_mentions,
+ get_message_with_context, get_or_create_dm, get_or_create_private, join_channel, leave_channel,
+ patch_channel, patch_message, post_message, post_reaction, post_typing, remove_participants,
};
use super::attachments::references;
@@ -52,7 +50,7 @@ use comms_db_client::attachments::get_attachment_references::{
use super::channels::get_mentions::GetMentionsResponse;
-use super::activity::{get_activity, post_activity};
+use super::activity::post_activity;
use super::mentions::{
create_mention::__path_create_mention_handler, delete_mention::__path_delete_mention_handler,
};
@@ -66,13 +64,13 @@ use super::preview::get_batch_preview;
paths(
create_channel::create_channel_handler,
get_channel::get_channel_handler,
- get_channels::get_channels_handler,
+ comms::inbound::get_channels_handler,
post_message::post_message_handler,
post_typing::post_typing_handler,
post_reaction::post_reaction_handler,
patch_message::patch_message_handler,
delete_message::delete_message_handler,
- get_activity::get_activity_handler,
+ comms::inbound::get_activity_handler,
post_activity::post_activity_handler,
join_channel::join_channel_handler,
leave_channel::leave_channel_handler,
@@ -95,7 +93,7 @@ use super::preview::get_batch_preview;
CreateChannelRequest,
CreateChannelResponse,
GetChannelResponse,
- GetChannelsResponse,
+ ApiChannelWithLatest,
PostMessageRequest,
PostMessageResponse,
PostTypingRequest,
@@ -107,7 +105,6 @@ use super::preview::get_batch_preview;
PatchMessageRequest,
DeleteMessageParams,
PostActivityRequest,
- GetActivityResponse,
AddParticipantsRequest,
RemoveParticipantsRequest,
@@ -119,6 +116,7 @@ use super::preview::get_batch_preview;
Reaction,
CountedReaction,
Activity,
+ ApiActivity,
ActivityType,
NewAttachment,
ParticipantAccess,
@@ -148,7 +146,6 @@ use super::preview::get_batch_preview;
DeleteEntityMentionResponse,
GetMentionsResponse,
- ChannelWithLatest,
ChannelWithParticipants,
LatestMessage,
GetMessageWithContextResponse,
diff --git a/rust/cloud-storage/comms_service/src/config.rs b/rust/cloud-storage/comms_service/src/config.rs
index b30004375a..0661b0bdc0 100644
--- a/rust/cloud-storage/comms_service/src/config.rs
+++ b/rust/cloud-storage/comms_service/src/config.rs
@@ -1,6 +1,7 @@
use anyhow::Context;
pub use macro_env::Environment;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
+use reqwest::Url;
/// The configuration parameters for the application.
///
@@ -31,7 +32,7 @@ pub struct Config {
pub contacts_queue: String,
/// Auth service client
- pub auth_service_url: String,
+ pub auth_service_url: Url,
/// Auth service secret key, used for internal access
pub auth_service_secret_key: String,
@@ -64,7 +65,9 @@ impl Config {
std::env::var("CONTACTS_QUEUE").context("CONTACTS_QUEUE must be provided")?;
let auth_service_url = std::env::var("AUTHENTICATION_SERVICE_URL")
- .context("AUTHENTICATION_SERVICE_URL must be provided")?;
+ .map(|s| Url::parse(&s))
+ .context("AUTHENTICATION_SERVICE_URL must be provided")?
+ .context("AUTHENTICATION_SERVICE_URL must be a valid url")?;
let auth_service_secret_key = std::env::var("AUTHENTICATION_SERVICE_SECRET_KEY")
.context("AUTHENTICATION_SERVICE_SECRET_KEY must be provided")?;
diff --git a/rust/cloud-storage/comms_service/src/main.rs b/rust/cloud-storage/comms_service/src/main.rs
index 468ca26422..5822c30557 100644
--- a/rust/cloud-storage/comms_service/src/main.rs
+++ b/rust/cloud-storage/comms_service/src/main.rs
@@ -1,5 +1,10 @@
use crate::api::context::{AppState, DocumentPermissionJwtSecretKey};
use anyhow::Context;
+use comms::{
+ domain::service::ChannelServiceImpl,
+ inbound::CommsRouterState,
+ outbound::{http::user_repo::UserRepoImpl, postgres::comms_repo::PgCommsRepo},
+};
use config::{Config, Environment};
use connection_gateway_client::ConnectionGatewayClient;
use frecency::outbound::postgres::FrecencyPgStorage;
@@ -105,8 +110,8 @@ async fn main() -> anyhow::Result<()> {
};
let auth_service_client = authentication_service_client::AuthServiceClient::new(
- auth_service_secret_key,
- config.auth_service_url.clone(),
+ auth_service_secret_key.clone(),
+ config.auth_service_url.to_string(),
);
let permissions_token_secret = secretsmanager_client
@@ -132,6 +137,8 @@ async fn main() -> anyhow::Result<()> {
&config.port
);
+ let frecency_storage = FrecencyPgStorage::new(macro_db.clone());
+
let service = api::service(AppState {
jwt_validation_args,
internal_auth_key: secretsmanager_client::LocalOrRemoteSecret::Local(
@@ -145,7 +152,12 @@ async fn main() -> anyhow::Result<()> {
auth_service_client: Arc::new(auth_service_client),
connection_gateway_client: Arc::new(connection_gateway_client),
permissions_token_secret,
- frecency_storage: FrecencyPgStorage::new(macro_db),
+ comms_state: CommsRouterState::new(ChannelServiceImpl::new(
+ PgCommsRepo { pool: macro_db },
+ UserRepoImpl::new(auth_service_secret_key, config.auth_service_url.clone()),
+ frecency_storage.clone(),
+ )),
+ frecency_storage,
});
axum::serve(listener, service)
diff --git a/rust/cloud-storage/comms_service/src/notification.rs b/rust/cloud-storage/comms_service/src/notification.rs
index 9e59c1790b..1443c4546b 100644
--- a/rust/cloud-storage/comms_service/src/notification.rs
+++ b/rust/cloud-storage/comms_service/src/notification.rs
@@ -23,7 +23,7 @@ pub struct ChannelMessageEvent<'a> {
user_mentions: &'a [String],
document_mentions: &'a [DocumentMetadata],
participants: &'a [ChannelParticipant],
- thread_participants: &'a [String],
+ thread_participants: &'a [MacroUserIdStr<'static>],
}
pub struct ChannelInviteEvent<'a> {
@@ -105,7 +105,7 @@ impl ChannelMessageEvent<'_> {
if !self.document_mentions.is_empty() {
let recipients_excluding_mentions = recipients_excluding(
- self.participants.iter().map(|p| p.user_id.as_str()),
+ self.participants.iter().map(|p| p.user_id.as_ref()),
once(self.message.sender_id.0.as_ref()),
);
@@ -133,7 +133,7 @@ impl ChannelMessageEvent<'_> {
// MessageSend and Invite notifications are sent to all participants except the sender and
// mentioned users. Mentioned users receive a seperate ChannelMention Notification.
let recipients_without_sender_and_mentions = recipients_excluding(
- self.participants.iter().map(|p| p.user_id.as_str()),
+ self.participants.iter().map(|p| p.user_id.as_ref()),
sender_and_mentions.clone(),
);
@@ -145,7 +145,7 @@ impl ChannelMessageEvent<'_> {
self.channel_id,
self.message.sender_id.clone(),
&recipients_excluding(
- self.thread_participants.iter().map(|p| p.as_str()),
+ self.thread_participants.iter().map(|p| p.as_ref()),
sender_and_mentions,
),
NotificationEvent::ChannelMessageReply(ChannelReplyMetadata {
@@ -285,16 +285,15 @@ pub async fn dispatch_notifications_for_message(
#[cfg(test)]
mod tests {
use super::*;
- use model::comms::ParticipantRole;
+ use model::comms::{ChannelId, ParticipantRole};
use model_notifications::NotificationEventType;
- use models_comms::ChannelType;
use std::collections::HashMap;
use uuid::Uuid;
- fn participant(user_id: &str, channel_id: Uuid) -> ChannelParticipant {
+ fn participant(user_id: MacroUserIdStr<'static>, channel_id: Uuid) -> ChannelParticipant {
ChannelParticipant {
- user_id: user_id.to_string(),
- channel_id,
+ user_id,
+ channel_id: ChannelId(channel_id),
role: ParticipantRole::Member,
left_at: None,
joined_at: chrono::Utc::now(),
@@ -332,7 +331,7 @@ mod tests {
fn private_metadata() -> CommonChannelMetadata {
CommonChannelMetadata {
- channel_type: ChannelType::Private,
+ channel_type: model_notifications::ChannelType::Private,
channel_name: "group".to_string(),
}
}
@@ -376,9 +375,18 @@ mod tests {
fn sender_excluded_from_all_recipients() {
let channel_id = Uuid::new_v4();
let participants = vec![
- participant("macro|[email protected]", channel_id),
- participant("macro|[email protected]", channel_id),
- participant("macro|[email protected]", channel_id),
+ participant(
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ channel_id,
+ ),
+ participant(
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ channel_id,
+ ),
+ participant(
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ channel_id,
+ ),
];
let msg = message(
channel_id,
@@ -417,8 +425,14 @@ mod tests {
fn first_message_sends_invite_notification() {
let channel_id = Uuid::new_v4();
let participants = vec![
- participant("sender", channel_id),
- participant("alice", channel_id),
+ participant(
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ channel_id,
+ ),
+ participant(
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ channel_id,
+ ),
];
let msg = message(
channel_id,
@@ -454,8 +468,14 @@ mod tests {
fn subsequent_messages_send_message_send_notification() {
let channel_id = Uuid::new_v4();
let participants = vec![
- participant("sender", channel_id),
- participant("alice", channel_id),
+ participant(
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ channel_id,
+ ),
+ participant(
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ channel_id,
+ ),
];
let msg = message(
channel_id,
@@ -491,9 +511,18 @@ mod tests {
fn mentioned_users_get_mention_not_message_send() {
let channel_id = Uuid::new_v4();
let participants = vec![
- participant("sender", channel_id),
- participant("alice", channel_id),
- participant("bob", channel_id),
+ participant(
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ channel_id,
+ ),
+ participant(
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ channel_id,
+ ),
+ participant(
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ channel_id,
+ ),
];
let msg = message(
channel_id,
@@ -503,7 +532,7 @@ mod tests {
None,
);
let metadata = private_metadata();
- let user_mentions = vec!["alice".to_string()];
+ let user_mentions = vec!["macro|[email protected]".to_string()];
let event = ChannelMessageEvent {
channel_id: &channel_id,
@@ -525,7 +554,8 @@ mod tests {
.expect("should have mention notification");
let mention_recipients = mention.recipient_ids.as_ref().unwrap();
- assert!(mention_recipients.contains(&"alice".to_string()));
+
+ assert!(mention_recipients.contains(&"macro|[email protected]".to_string()));
let send = notifications
.iter()
@@ -538,8 +568,8 @@ mod tests {
.expect("should have message send notification");
let send_recipients = send.recipient_ids.as_ref().unwrap();
- assert!(!send_recipients.contains(&"alice".to_string()));
- assert!(send_recipients.contains(&"bob".to_string()));
+ assert!(!send_recipients.contains(&"macro|[email protected]".to_string()));
+ assert!(send_recipients.contains(&"macro|[email protected]".to_string()));
}
#[test]
@@ -547,10 +577,22 @@ mod tests {
let channel_id = Uuid::new_v4();
let thread_id = Uuid::new_v4();
let participants = vec![
- participant("macro|[email protected]", channel_id),
- participant("macro|[email protected]", channel_id),
- participant("macro|[email protected]", channel_id),
- participant("macro|[email protected]", channel_id),
+ participant(
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ channel_id,
+ ),
+ participant(
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ channel_id,
+ ),
+ participant(
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ channel_id,
+ ),
+ participant(
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ channel_id,
+ ),
];
let msg = message(
channel_id,
@@ -562,10 +604,10 @@ mod tests {
let metadata = private_metadata();
let user_mentions = vec!["macro|[email protected]".to_string()];
let thread_participants = vec![
- "macro|[email protected]".to_string(),
- "macro|[email protected]".to_string(),
- "macro|[email protected]".to_string(),
- "macro|[email protected]".to_string(),
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
];
let event = ChannelMessageEvent {
@@ -603,9 +645,18 @@ mod tests {
fn document_mentions_exclude_sender() {
let channel_id = Uuid::new_v4();
let participants = vec![
- participant("macro|[email protected]", channel_id),
- participant("macro|[email protected]", channel_id),
- participant("macro|[email protected]", channel_id),
+ participant(
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ channel_id,
+ ),
+ participant(
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ channel_id,
+ ),
+ participant(
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ channel_id,
+ ),
];
let msg = message(
channel_id,
@@ -652,8 +703,14 @@ mod tests {
let channel_id = Uuid::new_v4();
let thread_id = Uuid::new_v4();
let participants = vec![
- participant("sender", channel_id),
- participant("alice", channel_id),
+ participant(
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ channel_id,
+ ),
+ participant(
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ channel_id,
+ ),
];
let msg = message(
channel_id,
diff --git a/rust/cloud-storage/comms_service/src/service/sender/notify.rs b/rust/cloud-storage/comms_service/src/service/sender/notify.rs
index 3660b358e4..786e1c6ba2 100644
--- a/rust/cloud-storage/comms_service/src/service/sender/notify.rs
+++ b/rust/cloud-storage/comms_service/src/service/sender/notify.rs
@@ -1,6 +1,7 @@
use anyhow::Result;
use comms_db_client::model::{Attachment, CountedReaction, Message, TypingAction};
use comms_db_client::participants::get_participants::get_participants;
+use macro_user_id::user_id::MacroUserIdStr;
use model_entity::EntityType;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
@@ -11,7 +12,7 @@ use crate::api::context::AppState;
pub async fn notify_message(
ctx: &AppState,
message: Message,
- participants: &[String],
+ participants: &[MacroUserIdStr<'_>],
) -> Result<()> {
if participants.is_empty() {
return Ok(());
@@ -22,7 +23,7 @@ pub async fn notify_message(
serde_json::to_value(message)?,
participants
.iter()
- .map(|p| EntityType::User.with_entity_str(p.as_str()))
+ .map(|p| EntityType::User.with_entity_str(p.as_ref()))
.collect(),
)
.await?;
@@ -47,7 +48,7 @@ pub async fn notify_typing(ctx: &AppState, update: TypingUpdate) -> Result<()> {
serde_json::to_value(update)?,
participants
.iter()
- .map(|p| EntityType::User.with_entity_str(&p.user_id))
+ .map(|p| EntityType::User.with_entity_str(p.user_id.as_ref()))
.collect(),
)
.await?;
@@ -71,7 +72,7 @@ pub async fn notify_reactions(ctx: &AppState, update: ReactionUpdate) -> Result<
serde_json::to_value(update)?,
participants
.iter()
- .map(|p| EntityType::User.with_entity_str(&p.user_id))
+ .map(|p| EntityType::User.with_entity_str(p.user_id.as_ref()))
.collect(),
)
.await?;
@@ -95,7 +96,7 @@ pub async fn notify_attachments(ctx: &AppState, update: AttachmentUpdate) -> Res
serde_json::to_value(update)?,
participants
.iter()
- .map(|p| EntityType::User.with_entity_str(&p.user_id))
+ .map(|p| EntityType::User.with_entity_str(p.user_id.as_ref()))
.collect(),
)
.await?;
diff --git a/rust/cloud-storage/comms_service/src/utils/channel_name.rs b/rust/cloud-storage/comms_service/src/utils/channel_name.rs
deleted file mode 100644
index 7dae1182b8..0000000000
--- a/rust/cloud-storage/comms_service/src/utils/channel_name.rs
+++ /dev/null
@@ -1,244 +0,0 @@
-use super::user_name::id_to_display_name;
-use model::comms::ChannelParticipant;
-use models_comms::ChannelType;
-use std::collections::HashMap;
-use uuid::Uuid;
-
-pub type ChannelName = String;
-pub type NameLookup = HashMap<String, String>;
-
-pub fn resolve_channel_name(
- channel_type: &ChannelType,
- channel_name: Option<&str>,
- participants: &[ChannelParticipant],
- channel_id: &Uuid,
- user_id: &str,
- name_lookup: Option<&NameLookup>,
-) -> ChannelName {
- match channel_type {
- ChannelType::Organization | ChannelType::Public => channel_name.map(|name| name.to_string()).unwrap_or_else(|| {
- tracing::warn!(channel_id=?channel_id, "organization or public channel should have a name");
- match channel_type {
- ChannelType::Organization => "Organization".to_string(),
- ChannelType::Public => "Public".to_string(),
- _ => unreachable!(),
- }
- }),
- ChannelType::Private => resolve_private_channel_name(channel_name, participants, name_lookup),
- ChannelType::DirectMessage => resolve_direct_message_channel_name(channel_name, participants, channel_id, user_id, name_lookup),
- }
-}
-
-pub fn resolve_private_channel_name(
- channel_name: Option<&str>,
- participants: &[ChannelParticipant],
- name_lookup: Option<&NameLookup>,
-) -> ChannelName {
- if let Some(name) = &channel_name {
- return name.to_string();
- }
-
- participants
- .iter()
- .map(|p| id_to_display_name(&p.user_id, name_lookup))
- .collect::<Vec<String>>()
- .join(", ")
-}
-
-pub fn resolve_direct_message_channel_name(
- channel_name: Option<&str>,
- participants: &[ChannelParticipant],
- channel_id: &Uuid,
- user_id: &str,
- name_lookup: Option<&NameLookup>,
-) -> ChannelName {
- // Direct Message Channels should not have a name
- if channel_name.is_some() {
- tracing::warn!(channel_id=?channel_id, "direct message channel should not have a name");
- }
-
- if !participants.iter().any(|p| p.user_id == user_id) {
- return resolve_private_channel_name(channel_name, participants, name_lookup);
- }
-
- let other_participant = participants.iter().find(|p| p.user_id != user_id);
-
- if let Some(other) = other_participant {
- id_to_display_name(&other.user_id, name_lookup)
- } else {
- tracing::error!(channel_id=?channel_id, "no other participant found, in a direct message channel");
- "Unknown".to_string()
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use model::comms::{Channel, ChannelType};
- use uuid::Uuid;
-
- fn make_participants(channel_id: &Uuid) -> Vec<ChannelParticipant> {
- vec![
- ChannelParticipant {
- channel_id: channel_id.to_owned(),
- user_id: "macro|[email protected]".to_string(),
- role: model::comms::ParticipantRole::Owner,
- joined_at: chrono::Utc::now(),
- left_at: None,
- },
- ChannelParticipant {
- channel_id: channel_id.to_owned(),
- user_id: "macro|[email protected]".to_string(),
- role: model::comms::ParticipantRole::Member,
- joined_at: chrono::Utc::now(),
- left_at: None,
- },
- ]
- }
-
- #[test]
- fn test_resolve_private_channel_name() {
- let channel_with_name = Channel {
- id: Default::default(),
- name: Some("test".to_string()),
- channel_type: ChannelType::Private,
- org_id: None,
- created_at: chrono::Utc::now(),
- updated_at: chrono::Utc::now(),
- owner_id: "test".to_string(),
- };
-
- let channel_without_name = Channel {
- id: Default::default(),
- name: None,
- channel_type: ChannelType::Private,
- org_id: None,
- created_at: chrono::Utc::now(),
- updated_at: chrono::Utc::now(),
- owner_id: "test".to_string(),
- };
-
- let participants_with_name = make_participants(&channel_with_name.id);
- let participants_without_name = make_participants(&channel_without_name.id);
-
- assert_eq!(
- resolve_private_channel_name(
- channel_with_name.name.as_deref(),
- &participants_with_name,
- None
- ),
- "test"
- );
- assert_eq!(
- resolve_private_channel_name(
- channel_without_name.name.as_deref(),
- &participants_without_name,
- None
- ),
- "user1, user2"
- );
- }
-
- #[test]
- fn test_resolve_direct_message_channel_name() {
- let direct_message_channel = Channel {
- id: Default::default(),
- name: None,
- channel_type: ChannelType::DirectMessage,
- org_id: None,
- created_at: chrono::Utc::now(),
- updated_at: chrono::Utc::now(),
- owner_id: "test".to_string(),
- };
-
- let participants = make_participants(&direct_message_channel.id);
-
- assert_eq!(
- resolve_direct_message_channel_name(
- direct_message_channel.name.as_deref(),
- &participants,
- &direct_message_channel.id,
- None
- ),
- "user2"
- );
- }
-
- #[test]
- fn test_resolve_direct_message_channel_name_for_other() {
- let direct_message_channel = Channel {
- id: Default::default(),
- name: None,
- channel_type: ChannelType::DirectMessage,
- org_id: None,
- created_at: chrono::Utc::now(),
- updated_at: chrono::Utc::now(),
- owner_id: "test".to_string(),
- };
-
- // Test the preview for a user who is not in the channel
- let participants = make_participants(&direct_message_channel.id);
-
- assert_eq!(
- resolve_direct_message_channel_name(
- direct_message_channel.name.as_deref(),
- &participants,
- &direct_message_channel.id,
- None
- ),
- "user1, user2"
- );
- }
-
- #[test]
- fn test_resolve_organization_and_public_channel_name() {
- let organization_channel = Channel {
- id: Default::default(),
- name: Some("organization_channel".to_string()),
- channel_type: ChannelType::Organization,
- org_id: None,
- created_at: chrono::Utc::now(),
- updated_at: chrono::Utc::now(),
- owner_id: "test".to_string(),
- };
-
- let public_channel = Channel {
- id: Default::default(),
- name: Some("public_channel".to_string()),
- channel_type: ChannelType::Public,
- org_id: None,
- created_at: chrono::Utc::now(),
- updated_at: chrono::Utc::now(),
- owner_id: "test".to_string(),
- };
-
- let org_participants = make_participants(&organization_channel.id);
- let pub_participants = make_participants(&public_channel.id);
-
- assert_eq!(
- resolve_channel_name(
- &organization_channel.channel_type,
- organization_channel.name.as_deref(),
- &org_participants,
- &organization_channel.id,
- None
- ),
- "organization_channel"
- );
-
- assert_eq!(
- resolve_channel_name(
- &public_channel.channel_type,
- public_channel.name.as_deref(),
- &pub_participants,
- &public_channel.id,
- None
- ),
- "public_channel"
- );
- }
-}
diff --git a/rust/cloud-storage/comms_service/src/utils/mod.rs b/rust/cloud-storage/comms_service/src/utils/mod.rs
index fcc1c1c455..c076fb97ed 100644
--- a/rust/cloud-storage/comms_service/src/utils/mod.rs
+++ b/rust/cloud-storage/comms_service/src/utils/mod.rs
@@ -1,3 +1 @@
-pub mod channel_name;
pub mod previews;
-pub mod user_name;
diff --git a/rust/cloud-storage/comms_service/src/utils/previews.rs b/rust/cloud-storage/comms_service/src/utils/previews.rs
index 76e5df8175..7f892792e3 100644
--- a/rust/cloud-storage/comms_service/src/utils/previews.rs
+++ b/rust/cloud-storage/comms_service/src/utils/previews.rs
@@ -1,14 +1,15 @@
+use comms::domain::models::channel_name::resolve_channel_name;
use comms_db_client::model::{ChannelPreview, ChannelPreviewData, WithChannelId};
use comms_db_client::preview::Previews;
-use model::user::UserContext;
+use macro_user_id::cowlike::CowLike;
+use macro_user_id::user_id::MacroUserIdStr;
+use models_comms::channel::ChannelId;
use std::collections::HashMap;
-use crate::utils::channel_name::resolve_channel_name;
-
pub fn resolve_previews(
- context: &UserContext,
+ context: MacroUserIdStr<'_>,
raw_previews: Previews,
- name_lookup: Option<&HashMap<String, String>>,
+ name_lookup: &HashMap<MacroUserIdStr<'static>, String>,
) -> Vec<ChannelPreview> {
let mut previews = vec![];
@@ -26,12 +27,45 @@ pub fn resolve_previews(
.exists
.iter()
.map(|preview| {
+ let participants: Vec<_> = preview
+ .participants
+ .iter()
+ .map(|p| models_comms::channel::ChannelParticipant {
+ channel_id: p.channel_id,
+ user_id: p.user_id.clone(),
+ role: match p.role {
+ model::comms::ParticipantRole::Owner => {
+ models_comms::channel::ParticipantRole::Owner
+ }
+ model::comms::ParticipantRole::Admin => {
+ models_comms::channel::ParticipantRole::Admin
+ }
+ model::comms::ParticipantRole::Member => {
+ models_comms::channel::ParticipantRole::Member
+ }
+ },
+ joined_at: p.joined_at,
+ left_at: p.left_at,
+ })
+ .collect();
+
let resolved_name = resolve_channel_name(
- &preview.channel_type,
+ &match preview.channel_type {
+ model::comms::ChannelType::Public => models_comms::channel::ChannelType::Public,
+ model::comms::ChannelType::Organization => {
+ models_comms::channel::ChannelType::Organization
+ }
+ model::comms::ChannelType::Private => {
+ models_comms::channel::ChannelType::Private
+ }
+ model::comms::ChannelType::DirectMessage => {
+ models_comms::channel::ChannelType::DirectMessage
+ }
+ },
preview.channel_name.as_deref(),
- &preview.participants,
- &preview.channel_id,
- &context.user_id,
+ &participants,
+ &ChannelId(preview.channel_id),
+ context.copied(),
name_lookup,
);
ChannelPreview::Access(ChannelPreviewData {
diff --git a/rust/cloud-storage/comms_service/src/utils/user_name.rs b/rust/cloud-storage/comms_service/src/utils/user_name.rs
deleted file mode 100644
index 39b185ba95..0000000000
--- a/rust/cloud-storage/comms_service/src/utils/user_name.rs
+++ /dev/null
@@ -1,89 +0,0 @@
-use std::collections::HashMap;
-
-use model::user::UserNames;
-
-pub fn id_to_email(id: &str) -> String {
- id.replace("macro|", "")
-}
-
-/// removes the @<domain>.com part of the email
-pub fn strip_email(email: &str) -> String {
- email.split('@').collect::<Vec<&str>>()[0].to_string()
-}
-
-pub fn id_to_name(id: &str) -> String {
- strip_email(&id_to_email(id))
-}
-
-pub fn id_to_display_name(id: &str, name_lookup: Option<&HashMap<String, String>>) -> String {
- match name_lookup {
- Some(lookup) => match lookup.get(id) {
- Some(name) => name.clone(),
- _ => id_to_name(id),
- },
- _ => id_to_name(id),
- }
-}
-
-pub fn generate_name_lookup(names: UserNames) -> HashMap<String, String> {
- let mut map = HashMap::new();
-
- for name in &names.names {
- let mut firstlast = Vec::new();
- let first = &name.first_name;
- let last = &name.last_name;
-
- if first.is_none() && last.is_none() {
- continue;
- }
-
- if first.is_some() {
- let firstname = first.as_ref().unwrap();
- // HACK: temporarily ignore N/A string as a workaround for new users being
- // initalized as N/A.
- if firstname != "N/A" && !firstname.is_empty() {
- firstlast.push(firstname.clone());
- }
- }
-
- if last.is_some() {
- let lastname = last.as_ref().unwrap();
- // HACK: temporarily ignore N/A string as a workaround for new users being
- // initalized as N/A.
- if lastname != "N/A" && !lastname.is_empty() {
- firstlast.push(lastname.clone());
- }
- }
-
- // HACK: names can still be empty at this point because of N/A, so only add when
- // there's a name to add
- if !firstlast.is_empty() {
- map.insert(name.id.clone(), firstlast.join(" "));
- }
- }
-
- map
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn test_id_to_email() {
- assert_eq!(id_to_email("macro|123"), "123");
- assert_eq!(id_to_email("macro|[email protected]"), "[email protected]");
- }
-
- #[test]
- fn test_strip_email() {
- assert_eq!(strip_email("[email protected]"), "123");
- assert_eq!(strip_email("123"), "123");
- }
-
- #[test]
- fn test_id_to_name() {
- assert_eq!(id_to_name("macro|123"), "123");
- assert_eq!(id_to_name("macro|[email protected]"), "123");
- }
-}
diff --git a/rust/cloud-storage/comms_service_client/src/channels.rs b/rust/cloud-storage/comms_service_client/src/channels.rs
index a630f26964..86b7e8fe49 100644
--- a/rust/cloud-storage/comms_service_client/src/channels.rs
+++ b/rust/cloud-storage/comms_service_client/src/channels.rs
@@ -1,7 +1,7 @@
use super::CommsServiceClient;
use crate::error::{ClientError, ResponseExt};
+use model::comms::ChannelType;
use model::comms::{GetChannelsHistoryRequest, GetChannelsHistoryResponse};
-use models_comms::ChannelType;
use serde::{Deserialize, Serialize};
use urlencoding;
use uuid::Uuid;
diff --git a/rust/cloud-storage/document_cognition_service/Cargo.toml b/rust/cloud-storage/document_cognition_service/Cargo.toml
index 0bca689304..b859bbac0f 100644
--- a/rust/cloud-storage/document_cognition_service/Cargo.toml
+++ b/rust/cloud-storage/document_cognition_service/Cargo.toml
@@ -36,6 +36,7 @@ cookie = { workspace = true }
dashmap = { workspace = true }
document_cognition_service_client = { path = "../document_cognition_service_client" }
document_storage_service_client = { path = "../document_storage_service_client" }
+doppleganger = { workspace = true }
email_service_client = { path = "../email_service_client" }
futures = { workspace = true }
http-body-util = { workspace = true }
@@ -56,10 +57,12 @@ macro_middleware = { path = "../macro_middleware", default-features = false, fea
macro_notify = { path = "../macro_notify" }
macro_project_utils = { path = "../macro_project_utils" }
macro_share_permissions = { path = "../macro_share_permissions" }
+macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
metering_service_client = { path = "../metering_service_client" }
model = { path = "../model" }
models_dcs = { path = "../models_dcs" }
+models_opensearch = { path = "../models_opensearch" }
models_permissions = { path = "../models_permissions" }
regex = { workspace = true }
reqwest.workspace = true
@@ -95,8 +98,6 @@ unfurl_service = { path = "../unfurl_service" }
utoipa = { workspace = true, features = ["axum_extras", "chrono"] }
utoipa-swagger-ui = { workspace = true, features = ["axum"] }
uuid = { workspace = true }
-macro_user_id = { path = "../macro_user_id" }
-models_opensearch = { path = "../models_opensearch" }
[dev-dependencies]
macro_auth = { path = "../macro_auth", features = ["testing"] }
diff --git a/rust/cloud-storage/document_cognition_service/src/service/get_chat.rs b/rust/cloud-storage/document_cognition_service/src/service/get_chat.rs
index 29e336d998..d6ffda31a6 100644
--- a/rust/cloud-storage/document_cognition_service/src/service/get_chat.rs
+++ b/rust/cloud-storage/document_cognition_service/src/service/get_chat.rs
@@ -4,6 +4,7 @@ use crate::core::model::FALLBACK_MODEL;
use crate::model::chats::ChatResponse;
use ai::model_selection::ModelSelection;
use anyhow::Context;
+use doppleganger::Mirror;
use macro_db_client::dcs::get_chat::{
get_chat_db, get_messages, get_web_citations, raw_attachments,
};
@@ -62,7 +63,7 @@ pub async fn get_chat(
.await
.map(|channel_metadata| AttachmentMetadata::Channel {
channel_name: channel_metadata.name,
- channel_type: channel_metadata.channel_type,
+ channel_type: model::comms::ChannelType::mirror(channel_metadata.channel_type),
})
.ok(),
AttachmentType::Email => {
diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.toml
index aa8ce86ee4..b2ef2bf2fe 100644
--- a/rust/cloud-storage/document_storage_service/Cargo.toml
+++ b/rust/cloud-storage/document_storage_service/Cargo.toml
@@ -40,6 +40,7 @@ bzip2 = { workspace = true, default-features = false, features = [
chrono = { workspace = true }
clap = { workspace = true }
cloudfront_sign = { workspace = true }
+comms = { path = "../comms", features = ["outbound"] }
comms_service_client = { path = "../comms_service_client" }
connection_gateway = { path = "../connection_gateway" }
document_sub_type = { path = "../document_sub_type" }
diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rs
index 8086942469..85e591a89d 100644
--- a/rust/cloud-storage/document_storage_service/src/api/context.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs
@@ -1,5 +1,9 @@
use crate::{config::Config, service::s3::S3};
use axum::extract::FromRef;
+use comms::{
+ domain::service::ChannelServiceImpl,
+ outbound::{http::user_repo::UserRepoImpl, postgres::comms_repo::PgCommsRepo},
+};
use connection_gateway_client::client::ConnectionGatewayClient;
use dynamodb_client::DynamodbClient;
use email::{domain::service::EmailServiceImpl, outbound::EmailPgRepo};
@@ -30,6 +34,7 @@ type DssSoupState = SoupRouterState<
PgSoupRepo,
FrecencyQueryServiceImpl<FrecencyPgStorage>,
EmailServiceImpl<EmailPgRepo, FrecencyQueryServiceImpl<FrecencyPgStorage>>,
+ ChannelServiceImpl<PgCommsRepo, UserRepoImpl, FrecencyPgStorage>,
>,
EmailServiceImpl<EmailPgRepo, FrecencyQueryServiceImpl<FrecencyPgStorage>>,
>;
diff --git a/rust/cloud-storage/document_storage_service/src/api/swagger.rs b/rust/cloud-storage/document_storage_service/src/api/swagger.rs
index c5148a53da..65ebeee405 100644
--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs
@@ -109,7 +109,6 @@ use models_soup::email_thread::{
SoupMacroAttachment, SoupMessageListVisibility,
};
use models_soup::item::SoupItem;
-use models_soup::item::SoupItemType;
use models_soup::project::SoupProject;
use soup::inbound::axum_router::{PostSoupRequest, SoupApiItem, SoupApiSort, SoupPage};
use utoipa::OpenApi;
@@ -290,7 +289,6 @@ use utoipa::OpenApi;
SoupDocument,
SoupChat,
SoupProject,
- SoupItemType,
SoupApiSort,
SoupPage,
SoupEnrichedEmailThreadPreview,
diff --git a/rust/cloud-storage/document_storage_service/src/bin/backfill_useritemaccess/chat.rs b/rust/cloud-storage/document_storage_service/src/bin/backfill_useritemaccess/chat.rs
index 738bab3fea..4567beda0c 100644
--- a/rust/cloud-storage/document_storage_service/src/bin/backfill_useritemaccess/chat.rs
+++ b/rust/cloud-storage/document_storage_service/src/bin/backfill_useritemaccess/chat.rs
@@ -46,10 +46,10 @@ async fn process_single_chat(
// Add an access record for each participant
for participant in participants {
- if participant.user_id != user_id {
+ if participant.user_id.as_ref() != user_id {
generated_items.push(UserItemAccess {
id: macro_uuid::generate_uuid_v7(),
- user_id: participant.user_id,
+ user_id: participant.user_id.to_string(),
item_id: chat_id.clone(),
item_type: "chat".to_string(),
access_level: csp.access_level,
diff --git a/rust/cloud-storage/document_storage_service/src/bin/backfill_useritemaccess/document.rs b/rust/cloud-storage/document_storage_service/src/bin/backfill_useritemaccess/document.rs
index ed91744595..263801ce4d 100644
--- a/rust/cloud-storage/document_storage_service/src/bin/backfill_useritemaccess/document.rs
+++ b/rust/cloud-storage/document_storage_service/src/bin/backfill_useritemaccess/document.rs
@@ -54,10 +54,10 @@ async fn process_single_document(
})?;
for participant in participants {
- if participant.user_id != user_id.as_ref() {
+ if participant.user_id != user_id {
generated_items.push(UserItemAccess {
id: macro_uuid::generate_uuid_v7(),
- user_id: participant.user_id,
+ user_id: participant.user_id.to_string(),
item_id: document_id.clone(),
item_type: "document".to_string(),
access_level: csp.access_level,
diff --git a/rust/cloud-storage/document_storage_service/src/bin/backfill_useritemaccess/project.rs b/rust/cloud-storage/document_storage_service/src/bin/backfill_useritemaccess/project.rs
index 118f0a64eb..2c958c9655 100644
--- a/rust/cloud-storage/document_storage_service/src/bin/backfill_useritemaccess/project.rs
+++ b/rust/cloud-storage/document_storage_service/src/bin/backfill_useritemaccess/project.rs
@@ -45,10 +45,10 @@ pub async fn process_single_project(
})?;
for participant in participants {
- if participant.user_id != user_id {
+ if participant.user_id.as_ref() != user_id {
generated_items.push(UserItemAccess {
id: macro_uuid::generate_uuid_v7(),
- user_id: participant.user_id,
+ user_id: participant.user_id.to_string(),
item_id: project_id.clone(),
item_type: "project".to_string(),
access_level: csp.access_level,
diff --git a/rust/cloud-storage/document_storage_service/src/config.rs b/rust/cloud-storage/document_storage_service/src/config.rs
index cccffa5dd4..5c6260372e 100644
--- a/rust/cloud-storage/document_storage_service/src/config.rs
+++ b/rust/cloud-storage/document_storage_service/src/config.rs
@@ -48,6 +48,8 @@ env_var! {
pub UploadStagingBucket,
pub SyncServiceUrl,
pub SyncServiceAuthKey,
+ pub AuthenticationServiceUrl,
+ pub AuthenticationServiceSecretKey,
}
}
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index e63f674cad..81ee2d90eb 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -4,6 +4,10 @@ use crate::{
service::s3::S3,
};
use anyhow::Context;
+use comms::{
+ domain::service::ChannelServiceImpl,
+ outbound::{http::user_repo::UserRepoImpl, postgres::comms_repo::PgCommsRepo},
+};
use comms_service_client::CommsServiceClient;
use config::{Config, Environment};
use connection_gateway_client::client::ConnectionGatewayClient;
@@ -185,6 +189,19 @@ async fn main() -> anyhow::Result<()> {
JwtValidationArgs::new_with_secret_manager(config.environment, &secretsmanager_client)
.await?;
+ let auth_service_secret_key = match config.environment {
+ Environment::Local => config
+ .vars
+ .authentication_service_secret_key
+ .as_ref()
+ .to_string(),
+ _ => secretsmanager_client
+ .get_secret_value(&config.vars.authentication_service_secret_key)
+ .await
+ .context("unable to get auth service secret")?
+ .to_string(),
+ };
+
let frecency_service = FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(db.clone()));
let email_service =
EmailServiceImpl::new(EmailPgRepo::new(db.clone()), frecency_service.clone());
@@ -209,6 +226,19 @@ async fn main() -> anyhow::Result<()> {
PgSoupRepo::new(db.clone()),
frecency_service,
email_service.clone(),
+ ChannelServiceImpl::new(
+ PgCommsRepo { pool: db.clone() },
+ UserRepoImpl::new(
+ auth_service_secret_key,
+ config
+ .vars
+ .authentication_service_url
+ .as_ref()
+ .parse()
+ .context("AUTHENTICATION_SERVICE_URL must be a valid url")?,
+ ),
+ FrecencyPgStorage::new(db.clone()),
+ ),
),
email_service,
),
diff --git a/rust/cloud-storage/macro_db_client/fixtures/user_item_access.sql b/rust/cloud-storage/macro_db_client/fixtures/user_item_access.sql
index 8707e8934f..0ef73efaa0 100644
--- a/rust/cloud-storage/macro_db_client/fixtures/user_item_access.sql
+++ b/rust/cloud-storage/macro_db_client/fixtures/user_item_access.sql
@@ -2,25 +2,25 @@ INSERT INTO public."Organization" ("id", "name")
(SELECT 1, 'organization-one');
INSERT INTO public."User" ("id", "email", "stripeCustomerId", "organizationId")
- (SELECT 'macro|[email protected]', '[email protected]', 'stripe_id', 1);
+ (SELECT 'macro|[email protected]', '[email protected]', 'stripe_id', 1);
INSERT INTO public."User" ("id", "email", "stripeCustomerId", "organizationId")
- (SELECT 'macro|[email protected]', '[email protected]', 'stripe_id2', 1);
+ (SELECT 'macro|[email protected]', '[email protected]', 'stripe_id2', 1);
INSERT INTO public."User" ("id", "email", "stripeCustomerId", "organizationId")
- (SELECT 'macro|[email protected]', '[email protected]', 'stripe_id3', 1);
+ (SELECT 'macro|[email protected]', '[email protected]', 'stripe_id3', 1);
INSERT INTO public."User" ("id", "email", "stripeCustomerId")
- (SELECT 'macro|[email protected]', '[email protected]', 'stripe_id4');
+ (SELECT 'macro|[email protected]', '[email protected]', 'stripe_id4');
INSERT INTO public."User" ("id", "email", "stripeCustomerId")
- (SELECT 'macro|[email protected]', '[email protected]', 'stripe_id5');
+ (SELECT 'macro|[email protected]', '[email protected]', 'stripe_id5');
INSERT INTO public."Document" ("id", "name", "fileType", "owner", "createdAt", "updatedAt")
(SELECT 'document-one',
'test_document_name',
'pdf',
'2019-10-16 00:00:00',
'2019-10-16 00:00:00');
@@ -34,7 +34,7 @@ INSERT INTO public."Document" ("id", "name", "fileType", "owner", "createdAt", "
(SELECT 'document-two',
'test_document_name',
'pdf',
'2019-10-16 00:00:00',
'2019-10-16 00:00:00');
@@ -43,30 +43,30 @@ INSERT INTO public."DocumentInstance" ("revisionName", "documentId", "createdAt"
-- Create test users needed for all UserItemAccess tests
INSERT INTO public."User" ("id", "email")
-VALUES ('test-user', '[email protected]'),
- ('user0', '[email protected]'),
- ('user1', '[email protected]'),
- ('user2', '[email protected]'),
- ('user3', '[email protected]'),
- ('user4', '[email protected]'),
- ('user5', '[email protected]')
ON CONFLICT (id) DO NOTHING;
-- Create single user item access record for test_delete_user_item_access
INSERT INTO public."UserItemAccess" ("id", "user_id", "item_id", "item_type", "access_level", "created_at")
-VALUES ('00000000-0000-0000-0000-000000000001', 'test-user', 'test-item', 'document', 'owner', NOW());
+VALUES ('00000000-0000-0000-0000-000000000001', 'macro|[email protected]', 'test-item', 'document', 'owner', NOW());
-- Create multiple user item access records for test_delete_user_item_access_by_item
INSERT INTO public."UserItemAccess" ("id", "user_id", "item_id", "item_type", "access_level", "created_at")
-VALUES ('00000000-0000-0000-0000-000000000002', 'user1', 'multi-access-item', 'document', 'view', NOW()),
- ('00000000-0000-0000-0000-000000000003', 'user2', 'multi-access-item', 'document', 'view', NOW()),
- ('00000000-0000-0000-0000-000000000004', 'user3', 'multi-access-item', 'document', 'view', NOW());
+VALUES ('00000000-0000-0000-0000-000000000002', 'macro|[email protected]', 'multi-access-item', 'document', 'view', NOW()),
+ ('00000000-0000-0000-0000-000000000003', 'macro|[email protected]', 'multi-access-item', 'document', 'view', NOW()),
+ ('00000000-0000-0000-0000-000000000004', 'macro|[email protected]', 'multi-access-item', 'document', 'view', NOW());
-- Create multiple user item access records for test_delete_user_item_access_bulk
INSERT INTO public."UserItemAccess" ("id", "user_id", "item_id", "item_type", "access_level", "created_at")
-VALUES ('00000000-0000-0000-0000-000000000005', 'user0', 'bulk-test-item-1', 'document', 'view', NOW()),
- ('00000000-0000-0000-0000-000000000006', 'user1', 'bulk-test-item-1', 'document', 'edit', NOW()),
- ('00000000-0000-0000-0000-000000000007', 'user2', 'bulk-test-item-2', 'document', 'view', NOW()),
- ('00000000-0000-0000-0000-000000000008', 'user3', 'bulk-test-item-2', 'document', 'edit', NOW()),
- ('00000000-0000-0000-0000-000000000009', 'user4', 'bulk-test-item-3', 'document', 'view', NOW()),
- ('00000000-0000-0000-0000-000000000010', 'user5', 'bulk-test-item-3', 'document', 'edit', NOW());
\ No newline at end of file
+VALUES ('00000000-0000-0000-0000-000000000005', 'macro|[email protected]', 'bulk-test-item-1', 'document', 'view', NOW()),
+ ('00000000-0000-0000-0000-000000000006', 'macro|[email protected]', 'bulk-test-item-1', 'document', 'edit', NOW()),
+ ('00000000-0000-0000-0000-000000000007', 'macro|[email protected]', 'bulk-test-item-2', 'document', 'view', NOW()),
+ ('00000000-0000-0000-0000-000000000008', 'macro|[email protected]', 'bulk-test-item-2', 'document', 'edit', NOW()),
+ ('00000000-0000-0000-0000-000000000009', 'macro|[email protected]', 'bulk-test-item-3', 'document', 'view', NOW()),
+ ('00000000-0000-0000-0000-000000000010', 'macro|[email protected]', 'bulk-test-item-3', 'document', 'edit', NOW());
diff --git a/rust/cloud-storage/macro_db_client/src/item_access/delete.rs b/rust/cloud-storage/macro_db_client/src/item_access/delete.rs
index 0fd58c9a32..c16ab2fcde 100644
--- a/rust/cloud-storage/macro_db_client/src/item_access/delete.rs
+++ b/rust/cloud-storage/macro_db_client/src/item_access/delete.rs
@@ -1,4 +1,5 @@
use anyhow::Context;
+use macro_user_id::user_id::MacroUserIdStr;
use sqlx::{Postgres, Transaction};
/// Deletes all user access records for a specific item
@@ -85,7 +86,7 @@ pub async fn delete_user_item_access(
#[tracing::instrument(skip_all)]
pub async fn delete_user_item_access_by_users_and_channel(
executor: impl sqlx::Executor<'_, Database = Postgres>,
- user_ids: &[String],
+ user_ids: &[MacroUserIdStr<'_>],
item_id: &str,
item_type: &str,
granted_from_channel_id: uuid::Uuid,
@@ -94,6 +95,8 @@ pub async fn delete_user_item_access_by_users_and_channel(
return Ok(0);
}
+ let macro_ids: Vec<String> = user_ids.iter().map(|s| s.to_string()).collect();
+
let result = sqlx::query!(
r#"
DELETE FROM "UserItemAccess"
@@ -102,7 +105,7 @@ pub async fn delete_user_item_access_by_users_and_channel(
AND "item_type" = $3
AND "granted_from_channel_id" = $4
"#,
- user_ids,
+ macro_ids.as_slice(),
item_id,
item_type,
granted_from_channel_id,
@@ -182,7 +185,7 @@ mod tests {
#[sqlx::test(fixtures(path = "../../fixtures", scripts("user_item_access.sql")))]
async fn test_delete_user_item_access(pool: Pool<Postgres>) -> anyhow::Result<()> {
- let user_id = "test-user";
+ let user_id = "macro|[email protected]";
let item_id = "test-item";
let item_type = "document";
@@ -308,7 +311,10 @@ mod tests {
let item_id = "channel-shared-item";
let item_type = "document";
let channel_id = uuid::Uuid::parse_str("00000000-0000-0000-0000-000000000001")?;
- let user_ids = vec!["user1".to_string(), "user2".to_string()];
+ let user_ids = vec![
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ ];
// First ensure test data exists
for user_id in &user_ids {
@@ -319,7 +325,7 @@ mod tests {
ON CONFLICT DO NOTHING
"#,
uuid::Uuid::now_v7(),
- user_id,
+ user_id.as_ref(),
item_id,
item_type,
channel_id,
@@ -336,6 +342,8 @@ mod tests {
assert_eq!(affected, 2, "Should have deleted exactly two records");
+ let ids: Vec<_> = user_ids.iter().map(|x| x.to_string()).collect();
+
// Verify they're gone
let result = sqlx::query!(
r#"
@@ -343,7 +351,7 @@ mod tests {
FROM "UserItemAccess"
WHERE "user_id" = ANY($1) AND "item_id" = $2 AND "item_type" = $3 AND "granted_from_channel_id" = $4
"#,
- &user_ids,
+ &ids,
item_id,
item_type,
channel_id
diff --git a/rust/cloud-storage/macro_db_client/src/item_access/insert.rs b/rust/cloud-storage/macro_db_client/src/item_access/insert.rs
index 3d58bb0ad4..6df76b950c 100644
--- a/rust/cloud-storage/macro_db_client/src/item_access/insert.rs
+++ b/rust/cloud-storage/macro_db_client/src/item_access/insert.rs
@@ -54,7 +54,7 @@ pub async fn insert_user_item_access(
#[tracing::instrument(skip(executor))]
pub async fn upsert_user_item_access_bulk<'e, E>(
executor: E,
- user_ids: &[String],
+ user_ids: &[MacroUserIdStr<'_>],
item_id: &str,
item_type: &str,
access_level: AccessLevel,
@@ -67,6 +67,8 @@ where
return Ok(());
}
+ let macro_ids: Vec<String> = user_ids.iter().map(|s| s.to_string()).collect();
+
// Generate UUIDs for each user
let ids: Vec<Uuid> = user_ids
.iter()
@@ -106,7 +108,7 @@ where
access_level as _,
granted_from_channel_id,
&ids,
- user_ids as &[String],
+ macro_ids.as_slice(),
)
.execute(executor)
.await?;
@@ -254,7 +256,7 @@ mod tests {
#[sqlx::test(fixtures(path = "../../fixtures", scripts("user_item_access.sql")))]
async fn test_insert_user_item_access(pool: Pool<Postgres>) -> anyhow::Result<()> {
- let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
let item_id = "new-test-item";
let item_type = "document";
let access_level = AccessLevel::Edit;
@@ -308,9 +310,9 @@ mod tests {
let access_level = AccessLevel::View;
let granted_from_channel_id = Some(Uuid::now_v7());
let user_ids = vec![
- "user0".to_string(),
- "user1".to_string(),
- "user2".to_string(),
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
];
let mut transaction = pool.begin().await?;
@@ -326,6 +328,8 @@ mod tests {
)
.await?;
+ let ids: Vec<_> = user_ids.iter().map(|x| x.to_string()).collect();
+
// Verify all records exist
let result = sqlx::query!(
r#"
@@ -334,7 +338,7 @@ mod tests {
WHERE "user_id" = ANY($1) AND "item_id" = $2 AND "item_type" = $3
AND "access_level"::text = $4 AND "granted_from_channel_id" = $5
"#,
- &user_ids,
+ &ids,
item_id,
item_type,
access_level.to_string(),
@@ -363,13 +367,13 @@ mod tests {
FROM "UserItemAccess"
WHERE "user_id" = $1 AND "item_id" = $2
"#,
- user_id,
+ user_id.as_ref(),
item_id,
)
.fetch_one(&mut *transaction)
.await?;
- assert_eq!(result.user_id, *user_id);
+ assert_eq!(result.user_id, user_id.as_ref());
assert_eq!(result.item_id, item_id);
assert_eq!(result.item_type, item_type);
assert_eq!(result.access_level, Some(access_level.to_string()));
@@ -428,9 +432,9 @@ mod tests {
let access_level = AccessLevel::Owner;
let granted_from_channel_id = Some(Uuid::now_v7());
let user_ids = vec![
- "user3".to_string(),
- "user4".to_string(),
- "user5".to_string(),
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
];
// Insert using the pool directly
@@ -444,6 +448,8 @@ mod tests {
)
.await?;
+ let ids: Vec<_> = user_ids.iter().map(|x| x.to_string()).collect();
+
// Verify all records exist
let result = sqlx::query!(
r#"
@@ -452,7 +458,7 @@ mod tests {
WHERE "user_id" = ANY($1) AND "item_id" = $2 AND "item_type" = $3
AND "access_level"::text = $4 AND "granted_from_channel_id" = $5
"#,
- &user_ids,
+ &ids,
item_id,
item_type,
access_level.to_string(),
@@ -476,7 +482,10 @@ mod tests {
let item_id = "upsert-test-item";
let item_type = "document";
let granted_from_channel_id = Some(Uuid::now_v7());
- let user_ids = vec!["user1".to_string(), "user2".to_string()];
+ let user_ids = vec![
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ ];
let mut transaction = pool.begin().await?;
@@ -492,6 +501,8 @@ mod tests {
)
.await?;
+ let ids: Vec<_> = user_ids.iter().map(|x| x.to_string()).collect();
+
// Verify initial insert
let initial_result = sqlx::query!(
r#"
@@ -501,7 +512,7 @@ mod tests {
AND "granted_from_channel_id" = $4
ORDER BY "user_id"
"#,
- &user_ids,
+ &ids,
item_id,
item_type,
granted_from_channel_id,
@@ -535,6 +546,8 @@ mod tests {
)
.await?;
+ let ids: Vec<_> = user_ids.iter().map(|x| x.to_string()).collect();
+
// Verify the upsert updated the access levels but kept the same records
let updated_result = sqlx::query!(
r#"
@@ -547,7 +560,7 @@ mod tests {
AND "granted_from_channel_id" = $4
ORDER BY "user_id"
"#,
- &user_ids,
+ &ids,
item_id,
item_type,
granted_from_channel_id,
@@ -580,9 +593,9 @@ mod tests {
// Test with both updates and new inserts
let mixed_user_ids = vec![
- "user1".to_string(), // existing
- "user3".to_string(), // new
- "user4".to_string(), // new
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(), // existing
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(), // new
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(), // new
];
let final_access_level = AccessLevel::Owner;
@@ -598,6 +611,8 @@ mod tests {
)
.await?;
+ let ids: Vec<_> = mixed_user_ids.iter().map(|x| x.to_string()).collect();
+
// Verify the result
let final_result = sqlx::query!(
r#"
@@ -610,7 +625,7 @@ mod tests {
AND "granted_from_channel_id" = $4
ORDER BY "user_id"
"#,
- &mixed_user_ids,
+ &ids,
item_id,
item_type,
granted_from_channel_id,
@@ -644,12 +659,12 @@ mod tests {
r#"
SELECT COUNT(*) as count
FROM "UserItemAccess"
- WHERE ("user_id" = ANY($1) OR "user_id" = ANY($2))
- AND "item_id" = $3 AND "item_type" = $4
+ WHERE ("user_id" = ANY($1) OR "user_id" = ANY($2))
+ AND "item_id" = $3 AND "item_type" = $4
AND "granted_from_channel_id" = $5
"#,
- &user_ids,
- &["user3".to_string(), "user4".to_string()],
+ &ids,
+ &["macro|[email protected]".to_string()], // user2 from original insert, not in mixed_user_ids
item_id,
item_type,
granted_from_channel_id,
diff --git a/rust/cloud-storage/macro_share_permissions/src/user_item_access.rs b/rust/cloud-storage/macro_share_permissions/src/user_item_access.rs
index fddf08be4e..f2e377dcfc 100644
--- a/rust/cloud-storage/macro_share_permissions/src/user_item_access.rs
+++ b/rust/cloud-storage/macro_share_permissions/src/user_item_access.rs
@@ -35,7 +35,7 @@ pub async fn update_user_item_access<'t>(
})?
.into_iter()
// don't make another entry for the owner of the item
- .filter(|p| p.user_id != user_id && p.left_at.is_none())
+ .filter(|p| p.user_id.as_ref() != user_id && p.left_at.is_none())
.map(|p| p.user_id)
.collect::<Vec<_>>();
diff --git a/rust/cloud-storage/model/Cargo.toml b/rust/cloud-storage/model/Cargo.toml
index 6113b239b9..08525ab6b6 100644
--- a/rust/cloud-storage/model/Cargo.toml
+++ b/rust/cloud-storage/model/Cargo.toml
@@ -12,6 +12,7 @@ axum = { workspace = true }
base64 = { workspace = true }
chrono = { workspace = true }
document_sub_type = { path = "../document_sub_type" }
+doppleganger = { workspace = true }
macro_user_id = { path = "../macro_user_id" }
model-error-response = { path = "../model-error-response" }
model_file_type = { path = "../model_file_type", features = ["utoipa"] }
diff --git a/rust/cloud-storage/model/src/comms/mod.rs b/rust/cloud-storage/model/src/comms/mod.rs
index e9fce3798c..7324c8b0c8 100644
--- a/rust/cloud-storage/model/src/comms/mod.rs
+++ b/rust/cloud-storage/model/src/comms/mod.rs
@@ -1,14 +1,14 @@
use chrono::{DateTime, Utc};
+use doppleganger::Doppleganger;
use macro_user_id::user_id::MacroUserIdStr;
+pub use models_comms::channel::{ChannelId, OrganizationId};
use serde::{Deserialize, Serialize};
use sqlx::Type;
use std::collections::HashMap;
+use strum::Display;
use utoipa::ToSchema;
use uuid::Uuid;
-// Re-export ChannelType for use by other modules in this crate
-pub use models_comms::ChannelType;
-
/// Ugly place to store the models that are used by service client.
/// it's ugly to promot someone else moving it as I am lazy -- Hutch.
@@ -47,9 +47,12 @@ pub struct UserActivityForChannel {
pub updated_at: chrono::NaiveDateTime,
}
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type, ToSchema, Default)]
+#[derive(
+ Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type, ToSchema, Default, Doppleganger,
+)]
#[sqlx(type_name = "comms_participant_role", rename_all = "lowercase")]
#[serde(rename_all = "snake_case")]
+#[dg(backward = models_comms::channel::ParticipantRole)]
pub enum ParticipantRole {
Owner,
Admin,
@@ -57,12 +60,15 @@ pub enum ParticipantRole {
Member,
}
-#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, Doppleganger)]
+#[dg(backward = models_comms::channel::ChannelParticipant)]
pub struct ChannelParticipant {
/// id of the channel
- pub channel_id: Uuid,
+ #[schema(value_type = Uuid)]
+ pub channel_id: ChannelId,
/// id of the user
- pub user_id: String,
+ #[schema(value_type = String)]
+ pub user_id: MacroUserIdStr<'static>,
/// type of the participant
pub role: ParticipantRole,
/// timestamp of when the user joined the channel
@@ -71,48 +77,67 @@ pub struct ChannelParticipant {
pub left_at: Option<chrono::DateTime<chrono::Utc>>,
}
-#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)]
+#[derive(
+ Debug,
+ Clone,
+ Copy,
+ PartialEq,
+ Eq,
+ Display,
+ ToSchema,
+ Doppleganger,
+ Serialize,
+ Deserialize,
+ sqlx::Type,
+)]
+#[strum(serialize_all = "snake_case")]
+#[serde(rename_all = "snake_case")]
+#[sqlx(type_name = "comms_channel_type", rename_all = "snake_case")]
+#[dg(backward = models_comms::channel::ChannelType)]
+pub enum ChannelType {
+ Public,
+ Organization,
+ Private,
+ DirectMessage,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq, Doppleganger)]
+#[dg(backward = models_comms::channel::Channel)]
pub struct Channel {
/// uuid of the channel
- pub id: Uuid,
+ #[schema(value_type = Uuid)]
+ pub id: ChannelId,
/// string name of the channel
pub name: Option<String>,
/// type of the channel
pub channel_type: ChannelType,
/// id of the organization this channel belongs too
- pub org_id: Option<i64>,
+ #[schema(value_type = Option<u32>)]
+ pub org_id: Option<OrganizationId>,
/// timestamp of when the channel was created
pub created_at: chrono::DateTime<chrono::Utc>,
/// timestamp of when the channel was last updated
pub updated_at: chrono::DateTime<chrono::Utc>,
/// id of the user who created the channel
- pub owner_id: String,
+ #[schema(value_type = String)]
+ pub owner_id: MacroUserIdStr<'static>,
}
-#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, Doppleganger)]
+#[dg(backward = models_comms::channel::ChannelWithParticipants)]
pub struct ChannelWithParticipants {
#[serde(flatten)]
pub channel: Channel,
pub participants: Vec<ChannelParticipant>,
}
-#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, Default)]
+#[derive(Debug, Clone, Default, ToSchema, Serialize, Deserialize, Doppleganger)]
+#[dg(backward = models_comms::channel::LatestMessage)]
pub struct LatestMessage {
pub latest_message: Option<ChannelMessage>,
pub latest_non_thread_message: Option<ChannelMessage>,
}
-#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
-pub struct ChannelWithLatest {
- #[serde(flatten)]
- pub channel: ChannelWithParticipants,
- #[serde(flatten)]
- pub latest_message: LatestMessage,
- pub viewed_at: Option<chrono::DateTime<chrono::Utc>>,
- pub interacted_at: Option<chrono::DateTime<chrono::Utc>>,
- pub frecency_score: f64,
-}
-
/// information about a channel used in search responses
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ChannelHistoryInfo {
@@ -141,12 +166,13 @@ pub struct GetChannelsHistoryResponse {
#[derive(Debug, Serialize, Deserialize)]
pub struct CreateWelcomeMessageRequest {
/// The id of the user to create the welcome message to
- pub welcome_user_id: String,
+ pub welcome_user_id: MacroUserIdStr<'static>,
/// The id of the user to send the welcome message to
- pub to_user_id: String,
+ pub to_user_id: MacroUserIdStr<'static>,
}
-#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, Doppleganger)]
+#[dg(backward = models_comms::channel::ChannelMessage)]
pub struct ChannelMessage {
pub message_id: Uuid,
pub thread_id: Option<Uuid>,
diff --git a/rust/cloud-storage/model_notifications/Cargo.toml b/rust/cloud-storage/model_notifications/Cargo.toml
index 85ad54010b..9181483911 100644
--- a/rust/cloud-storage/model_notifications/Cargo.toml
+++ b/rust/cloud-storage/model_notifications/Cargo.toml
@@ -7,6 +7,7 @@ version = "0.1.0"
[dependencies]
anyhow = { workspace = true }
chrono = { workspace = true }
+doppleganger = { workspace = true }
macro_user_id = { path = "../macro_user_id" }
model-entity = { path = "../model-entity" }
models_comms = { path = "../models_comms" }
diff --git a/rust/cloud-storage/model_notifications/src/metadata.rs b/rust/cloud-storage/model_notifications/src/metadata.rs
index dee3543f7c..8442662e65 100644
--- a/rust/cloud-storage/model_notifications/src/metadata.rs
+++ b/rust/cloud-storage/model_notifications/src/metadata.rs
@@ -1,10 +1,30 @@
use crate::NotificationEventType;
+use doppleganger::Doppleganger;
use macro_user_id::user_id::MacroUserIdStr;
use model_entity::EntityType;
-use models_comms::ChannelType;
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use utoipa::ToSchema;
+#[derive(Debug, Clone, Copy, ToSchema, Doppleganger, Serialize, Deserialize)]
+#[dg(backward = models_comms::channel::ChannelType)]
+pub enum ChannelType {
+ Public,
+ Organization,
+ Private,
+ DirectMessage,
+}
+
+impl ChannelType {
+ pub fn to_model_comms(self) -> models_comms::channel::ChannelType {
+ match self {
+ ChannelType::Public => models_comms::channel::ChannelType::Public,
+ ChannelType::Organization => models_comms::channel::ChannelType::Organization,
+ ChannelType::Private => models_comms::channel::ChannelType::Private,
+ ChannelType::DirectMessage => models_comms::channel::ChannelType::DirectMessage,
+ }
+ }
+}
+
/// Common metadata for notifications on channels
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
#[serde(rename_all = "camelCase")]
diff --git a/rust/cloud-storage/models_comms/Cargo.toml b/rust/cloud-storage/models_comms/Cargo.toml
index 1f805e4cb5..c43368b354 100644
--- a/rust/cloud-storage/models_comms/Cargo.toml
+++ b/rust/cloud-storage/models_comms/Cargo.toml
@@ -7,10 +7,10 @@ version = "0.1.0"
[dependencies]
anyhow = { workspace = true }
chrono = { workspace = true }
+doppleganger = { workspace = true }
+frecency = { path = "../frecency" }
+macro_user_id = { path = "../macro_user_id" }
serde = { workspace = true }
-serde_json = { workspace = true }
-sqlx = { workspace = true }
strum = { workspace = true }
thiserror = { workspace = true }
-utoipa = { workspace = true, features = ["axum_extras", "chrono"] }
uuid = { workspace = true }
diff --git a/rust/cloud-storage/models_comms/src/channel.rs b/rust/cloud-storage/models_comms/src/channel.rs
index 71c4b22b48..5100419508 100644
--- a/rust/cloud-storage/models_comms/src/channel.rs
+++ b/rust/cloud-storage/models_comms/src/channel.rs
@@ -1,12 +1,14 @@
+use chrono::{DateTime, Utc};
+use doppleganger::Primitive;
+use frecency::domain::models::AggregateFrecency;
+use macro_user_id::user_id::MacroUserIdStr;
use serde::{Deserialize, Serialize};
-use sqlx::Type;
use strum::Display;
-use utoipa::ToSchema;
+use uuid::Uuid;
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type, ToSchema, Display)]
-#[sqlx(type_name = "comms_channel_type", rename_all = "snake_case")]
-#[serde(rename_all = "snake_case")]
+#[derive(Debug, Clone, Copy, Display, Deserialize)]
#[strum(serialize_all = "snake_case")]
+#[serde(rename_all = "snake_case")]
pub enum ChannelType {
Public,
Organization,
@@ -14,14 +16,102 @@ pub enum ChannelType {
DirectMessage,
}
-#[derive(Debug, Clone, Serialize, Deserialize)]
+#[derive(Debug, Clone)]
pub struct ChannelMetadata {
pub name: String,
pub channel_type: ChannelType,
}
-impl From<(String, ChannelType)> for ChannelMetadata {
- fn from((name, channel_type): (String, ChannelType)) -> Self {
- Self { name, channel_type }
- }
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(transparent)]
+pub struct OrganizationId(pub u32);
+
+impl Primitive for OrganizationId {}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
+#[serde(transparent)]
+pub struct ChannelId(pub Uuid);
+
+impl Primitive for ChannelId {}
+
+#[derive(Debug, Clone, Copy, Default, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ParticipantRole {
+ Owner,
+ Admin,
+ #[default]
+ Member,
+}
+
+#[derive(Debug, Clone, Deserialize)]
+pub struct ChannelParticipant {
+ pub channel_id: ChannelId,
+ pub user_id: MacroUserIdStr<'static>,
+ pub role: ParticipantRole,
+ pub joined_at: DateTime<Utc>,
+ pub left_at: Option<DateTime<Utc>>,
+}
+
+#[derive(Debug, Clone)]
+pub struct Channel {
+ pub id: ChannelId,
+ pub name: Option<String>,
+ pub channel_type: ChannelType,
+ pub org_id: Option<OrganizationId>,
+ pub created_at: DateTime<Utc>,
+ pub updated_at: DateTime<Utc>,
+ pub owner_id: MacroUserIdStr<'static>,
+}
+
+#[derive(Debug, Clone)]
+pub struct ChannelWithParticipants {
+ pub channel: Channel,
+ pub participants: Vec<ChannelParticipant>,
+}
+
+#[derive(Debug, Clone, Default)]
+pub struct LatestMessage {
+ pub latest_message: Option<ChannelMessage>,
+ pub latest_non_thread_message: Option<ChannelMessage>,
+}
+
+#[derive(Debug, Clone)]
+pub struct ChannelWithLatest {
+ pub channel: ChannelWithParticipants,
+ pub latest_message: LatestMessage,
+ pub viewed_at: Option<chrono::DateTime<chrono::Utc>>,
+ pub interacted_at: Option<chrono::DateTime<chrono::Utc>>,
+ pub frecency_score: Option<AggregateFrecency>,
+}
+
+#[derive(Debug, Clone)]
+pub struct ChannelMessage {
+ pub message_id: Uuid,
+ pub thread_id: Option<Uuid>,
+ pub sender_id: String,
+ pub content: String,
+ pub created_at: chrono::DateTime<chrono::Utc>,
+ pub updated_at: chrono::DateTime<chrono::Utc>,
+ pub deleted_at: Option<chrono::DateTime<chrono::Utc>>,
+ /// message mentions formatted as `{ENTITY_TYPE}:{ENTITY_ID}`
+ pub mentions: Vec<String>,
+}
+
+pub struct EnrichedChannel {
+ pub channel: ChannelWithParticipants,
+ pub latest_message: LatestMessage,
+}
+
+/// Represents a user's activity in a channel
+pub struct Activity {
+ pub id: Uuid,
+ pub user_id: String,
+ pub channel_id: ChannelId,
+ pub created_at: chrono::DateTime<chrono::Utc>,
+ pub updated_at: chrono::DateTime<chrono::Utc>,
+ /// the last time the user viewed the channel
+ pub viewed_at: Option<chrono::DateTime<chrono::Utc>>,
+ /// the last time the user intereacted with the channel
+ /// eg. reacting, replying, sending a message
+ pub interacted_at: Option<chrono::DateTime<chrono::Utc>>,
}
diff --git a/rust/cloud-storage/models_comms/src/lib.rs b/rust/cloud-storage/models_comms/src/lib.rs
index b4c0de73e9..f333359c6f 100644
--- a/rust/cloud-storage/models_comms/src/lib.rs
+++ b/rust/cloud-storage/models_comms/src/lib.rs
@@ -1,4 +1,2 @@
pub mod channel;
pub mod mentions;
-
-pub use channel::{ChannelMetadata, ChannelType};
diff --git a/rust/cloud-storage/models_comms/src/mentions.rs b/rust/cloud-storage/models_comms/src/mentions.rs
index 8d7c236cb2..7fe4a39b6c 100644
--- a/rust/cloud-storage/models_comms/src/mentions.rs
+++ b/rust/cloud-storage/models_comms/src/mentions.rs
@@ -1,13 +1,12 @@
use serde::{Deserialize, Serialize};
-use utoipa::ToSchema;
use uuid::Uuid;
-#[derive(Debug, Serialize, Deserialize, ToSchema)]
+#[derive(Debug, Serialize, Deserialize)]
pub struct DeleteMentionsRequest {
pub item_ids: Vec<String>,
}
-#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EntityMention {
pub id: Uuid,
pub source_entity_type: String,
diff --git a/rust/cloud-storage/models_soup/Cargo.toml b/rust/cloud-storage/models_soup/Cargo.toml
index 4b295999eb..44b43b8d73 100644
--- a/rust/cloud-storage/models_soup/Cargo.toml
+++ b/rust/cloud-storage/models_soup/Cargo.toml
@@ -11,6 +11,8 @@ schema = ["dep:utoipa"]
[dependencies]
anyhow = { workspace = true }
chrono = { workspace = true }
+comms = { path = "../comms" }
+document_sub_type = { path = "../document_sub_type" }
doppleganger = { workspace = true, features = ["chrono", "uuid"] }
email = { path = "../email" }
macro_user_id = { path = "../macro_user_id" }
@@ -20,4 +22,3 @@ serde = { workspace = true }
strum = { workspace = true }
utoipa = { workspace = true, optional = true }
uuid = { workspace = true }
-document_sub_type = { path = "../document_sub_type" }
diff --git a/rust/cloud-storage/models_soup/src/comms.rs b/rust/cloud-storage/models_soup/src/comms.rs
new file mode 100644
index 0000000000..f0f9f260ad
--- /dev/null
+++ b/rust/cloud-storage/models_soup/src/comms.rs
@@ -0,0 +1,99 @@
+use chrono::{DateTime, Utc};
+use comms::domain::models::channel::{ChannelId, OrganizationId};
+use doppleganger::Doppleganger;
+use macro_user_id::user_id::MacroUserIdStr;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+#[derive(Debug, Doppleganger, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[dg(backward = comms::domain::models::channel::ChannelWithLatest)]
+pub struct SoupChannel {
+ #[serde(flatten)]
+ pub channel: ChannelWithParticipants,
+ #[serde(flatten)]
+ pub latest_message: LatestMessage,
+ pub viewed_at: Option<chrono::DateTime<chrono::Utc>>,
+ pub interacted_at: Option<chrono::DateTime<chrono::Utc>>,
+}
+
+#[derive(Debug, Doppleganger, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[dg(backward = comms::domain::models::channel::ChannelWithParticipants)]
+pub struct ChannelWithParticipants {
+ pub channel: Channel,
+ pub participants: Vec<ChannelParticipant>,
+}
+
+#[derive(Debug, Doppleganger, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[dg(backward = comms::domain::models::channel::LatestMessage)]
+pub struct LatestMessage {
+ pub latest_message: Option<ChannelMessage>,
+ pub latest_non_thread_message: Option<ChannelMessage>,
+}
+
+#[derive(Debug, Doppleganger, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[dg(backward = comms::domain::models::channel::ChannelMessage)]
+pub struct ChannelMessage {
+ pub message_id: Uuid,
+ pub thread_id: Option<Uuid>,
+ pub sender_id: String,
+ pub content: String,
+ pub created_at: chrono::DateTime<chrono::Utc>,
+ pub updated_at: chrono::DateTime<chrono::Utc>,
+ pub deleted_at: Option<chrono::DateTime<chrono::Utc>>,
+ /// message mentions formatted as `{ENTITY_TYPE}:{ENTITY_ID}`
+ pub mentions: Vec<String>,
+}
+
+#[derive(Debug, Doppleganger, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[dg(backward = comms::domain::models::channel::Channel)]
+pub struct Channel {
+ #[schema(value_type = Uuid)]
+ pub id: ChannelId,
+ pub name: Option<String>,
+ pub channel_type: ChannelType,
+ #[schema(value_type = Option<u32>)]
+ pub org_id: Option<OrganizationId>,
+ pub created_at: DateTime<Utc>,
+ pub updated_at: DateTime<Utc>,
+ #[schema(value_type = String)]
+ pub owner_id: MacroUserIdStr<'static>,
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, Doppleganger)]
+#[serde(rename_all = "snake_case")]
+#[dg(backward = comms::domain::models::channel::ChannelType)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+pub enum ChannelType {
+ Public,
+ Organization,
+ Private,
+ DirectMessage,
+}
+
+#[derive(Debug, Doppleganger, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[dg(backward = comms::domain::models::channel::ChannelParticipant)]
+pub struct ChannelParticipant {
+ #[schema(value_type = Uuid)]
+ pub channel_id: ChannelId,
+ #[schema(value_type = String)]
+ pub user_id: MacroUserIdStr<'static>,
+ pub role: ParticipantRole,
+ pub joined_at: DateTime<Utc>,
+ pub left_at: Option<DateTime<Utc>>,
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, Doppleganger)]
+#[serde(rename_all = "snake_case")]
+#[dg(backward = comms::domain::models::channel::ParticipantRole)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+pub enum ParticipantRole {
+ Owner,
+ Admin,
+ Member,
+}
diff --git a/rust/cloud-storage/models_soup/src/item.rs b/rust/cloud-storage/models_soup/src/item.rs
index 23e5c941f5..a161f8ce22 100644
--- a/rust/cloud-storage/models_soup/src/item.rs
+++ b/rust/cloud-storage/models_soup/src/item.rs
@@ -1,27 +1,14 @@
-use crate::chat::SoupChat;
use crate::document::SoupDocument;
use crate::email_thread::SoupEnrichedEmailThreadPreview;
use crate::project::SoupProject;
+use crate::{chat::SoupChat, comms::SoupChannel};
use chrono::{DateTime, Utc};
use model_entity::{Entity, EntityType};
use models_pagination::{Identify, SimpleSortMethod, SortOn};
use serde::{Deserialize, Serialize};
-use strum::EnumString;
use uuid::Uuid;
-#[derive(Debug, Clone, Eq, PartialEq, EnumString, Deserialize, Serialize)]
-#[strum(serialize_all = "snake_case")]
-#[serde(rename_all = "snake_case")]
-#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
-pub enum SoupItemType {
- Document,
- Chat,
- Project,
- EmailThread,
-}
-
#[derive(Serialize, Deserialize, Debug)]
-#[cfg_attr(feature = "mock", derive(PartialEq, Eq))]
#[serde(rename_all = "camelCase", tag = "tag", content = "data")]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
pub enum SoupItem {
@@ -29,6 +16,7 @@ pub enum SoupItem {
Chat(SoupChat),
Project(SoupProject),
EmailThread(SoupEnrichedEmailThreadPreview),
+ Channel(SoupChannel),
}
impl SoupItem {
@@ -47,6 +35,9 @@ impl SoupItem {
SoupItem::EmailThread(email_thread) => {
EntityType::EmailThread.with_entity_string(email_thread.thread.id.to_string())
}
+ SoupItem::Channel(channel) => {
+ EntityType::Channel.with_entity_string(channel.channel.channel.id.0.to_string())
+ }
}
}
@@ -56,6 +47,7 @@ impl SoupItem {
SoupItem::Chat(soup_chat) => soup_chat.updated_at,
SoupItem::Project(soup_project) => soup_project.updated_at,
SoupItem::EmailThread(soup_thread) => soup_thread.thread.updated_at,
+ SoupItem::Channel(soup_channel) => soup_channel.channel.channel.updated_at,
}
}
}
@@ -107,6 +99,18 @@ impl SoupItem {
(SoupItem::EmailThread(thread), SimpleSortMethod::ViewedUpdated) => {
thread.thread.viewed_at.unwrap_or(thread.thread.updated_at)
}
+ (SoupItem::Channel(soup_channel), SimpleSortMethod::ViewedAt) => {
+ soup_channel.viewed_at.unwrap_or_default()
+ }
+ (SoupItem::Channel(soup_channel), SimpleSortMethod::UpdatedAt) => {
+ soup_channel.channel.channel.updated_at
+ }
+ (SoupItem::Channel(soup_channel), SimpleSortMethod::CreatedAt) => {
+ soup_channel.channel.channel.created_at
+ }
+ (SoupItem::Channel(soup_channel), SimpleSortMethod::ViewedUpdated) => soup_channel
+ .viewed_at
+ .unwrap_or(soup_channel.channel.channel.updated_at),
}
}
}
@@ -120,6 +124,7 @@ impl Identify for SoupItem {
SoupItem::Chat(soup_chat) => soup_chat.id,
SoupItem::Project(soup_project) => soup_project.id,
SoupItem::EmailThread(thread) => thread.thread.id,
+ SoupItem::Channel(soup_channel) => soup_channel.channel.channel.id.0,
}
}
}
diff --git a/rust/cloud-storage/models_soup/src/lib.rs b/rust/cloud-storage/models_soup/src/lib.rs
index 9bc875b4aa..bb92c464d3 100644
--- a/rust/cloud-storage/models_soup/src/lib.rs
+++ b/rust/cloud-storage/models_soup/src/lib.rs
@@ -1,4 +1,5 @@
pub mod chat;
+pub mod comms;
pub mod document;
pub mod email_thread;
pub mod item;
diff --git a/rust/cloud-storage/notification_service/src/notification/send/push/generate.rs b/rust/cloud-storage/notification_service/src/notification/send/push/generate.rs
index 2103831efd..0b5951b1ec 100644
--- a/rust/cloud-storage/notification_service/src/notification/send/push/generate.rs
+++ b/rust/cloud-storage/notification_service/src/notification/send/push/generate.rs
@@ -8,7 +8,6 @@ use model_notifications::{
ChannelInviteMetadata, ChannelMentionMetadata, ChannelMessageSendMetadata,
ChannelReplyMetadata, DocumentMentionMetadata, TaskAssignedMetadata,
};
-use models_comms::ChannelType;
use sns_client::{APNSPushNotification, Aps};
use std::str::FromStr;
use thiserror::Error;
@@ -210,7 +209,9 @@ impl BuildNotification for ChannelMessageSendMetadata {
aps: Aps {
alert: Some(sns_client::Alert::Dictionary(sns_client::AlertDictionary {
title: Some(match self.common.channel_type {
- ChannelType::DirectMessage => self.common.channel_name.to_string(),
+ model_notifications::ChannelType::DirectMessage => {
+ self.common.channel_name.to_string()
+ }
_ => format!(
"{} <{}>",
self.sender.email_part().local_part(),
diff --git a/rust/cloud-storage/notification_service/src/templates/channel_invite/mod.rs b/rust/cloud-storage/notification_service/src/templates/channel_invite/mod.rs
index ec931448a7..4a2ad1f866 100644
--- a/rust/cloud-storage/notification_service/src/templates/channel_invite/mod.rs
+++ b/rust/cloud-storage/notification_service/src/templates/channel_invite/mod.rs
@@ -53,7 +53,11 @@ pub fn fill_channel_invite_template(
&channel_url,
&channel_metadata.invited_by.to_string(),
Some(&channel_metadata.common.channel_name),
- &channel_metadata.common.channel_type.to_string(),
+ &channel_metadata
+ .common
+ .channel_type
+ .to_model_comms()
+ .to_string(),
);
Ok((content, subject.to_string()))
diff --git a/rust/cloud-storage/properties/src/domain/ports.rs b/rust/cloud-storage/properties/src/domain/ports.rs
index 9de91333bb..fcc63abc9f 100644
--- a/rust/cloud-storage/properties/src/domain/ports.rs
+++ b/rust/cloud-storage/properties/src/domain/ports.rs
@@ -3,6 +3,7 @@
//! These traits define the interfaces that the domain layer uses.
//! Implementations live in the outbound module.
+use macro_user_id::user_id::MacroUserIdStr;
use models_properties::EntityType;
use models_properties::service::property_definition::PropertyDefinition;
use models_properties::service::property_value::PropertyValue;
@@ -115,9 +116,9 @@ pub trait PermissionService: Send + Sync + 'static {
/// Grant edit permissions to users for a task.
/// This is used when task assignees are updated to ensure they can edit the task.
- fn grant_permissions_to_task(
+ fn grant_permissions_to_task<'a>(
&self,
- user_ids: &[String],
+ user_ids: &[MacroUserIdStr<'a>],
task_id: &str,
) -> impl Future<Output = Result<(), Self::Err>> + Send;
}
diff --git a/rust/cloud-storage/properties/src/domain/service_impl/task_properties.rs b/rust/cloud-storage/properties/src/domain/service_impl/task_properties.rs
index 032777cf21..ed970d6ba4 100644
--- a/rust/cloud-storage/properties/src/domain/service_impl/task_properties.rs
+++ b/rust/cloud-storage/properties/src/domain/service_impl/task_properties.rs
@@ -1,7 +1,10 @@
//! Task-specific property handlers.
+use std::collections::HashSet;
+
use futures::future::join_all;
use macro_user_id::cowlike::CowLike;
+use macro_user_id::user_id::MacroUserIdStr;
use models_properties::EntityType;
use models_properties::api::requests::SetPropertyValue;
use models_properties::service::property_value::PropertyValue;
@@ -105,7 +108,11 @@ where
return Ok(());
};
- let assignee_ids: Vec<String> = references.iter().map(|r| r.entity_id.clone()).collect();
+ let assignee_ids = references
+ .iter()
+ .map(|r| MacroUserIdStr::parse_from_str(&r.entity_id))
+ .collect::<Result<Vec<_>, _>>()
+ .map_err(|e| PropertiesErr::Validation(e.to_string()))?;
if assignee_ids.is_empty() {
return Ok(());
}
@@ -124,7 +131,7 @@ where
pub async fn handle_task_assignee_notifications(
&self,
task_id: Uuid,
- assignee_ids: &[String],
+ assignee_ids: &[MacroUserIdStr<'_>],
assigned_by_user_id: &str,
) -> Result<(), PropertiesErr> {
if assignee_ids.is_empty() {
@@ -150,17 +157,19 @@ where
.map_err(anyhow::Error::from)
.map_err(PropertiesErr::Repo)?;
- let current_assignee_ids: Vec<String> = match current_value {
+ let current_assignee_ids: HashSet<String> = match current_value {
Some(PropertyValue::EntityRef(refs)) => {
refs.iter().map(|r| r.entity_id.clone()).collect()
}
- _ => vec![],
+ _ => Default::default(),
};
- let recipient_ids: Vec<String> = assignee_ids
+ let recipient_ids: Vec<MacroUserIdStr<'_>> = assignee_ids
.iter()
- .filter(|id| !current_assignee_ids.contains(id) && id.as_str() != assigned_by_user_id)
- .cloned()
+ .filter(|id| {
+ !current_assignee_ids.contains(id.as_ref()) && id.as_ref() != assigned_by_user_id
+ })
+ .map(|id| id.copied())
.collect();
if recipient_ids.is_empty() {
@@ -198,7 +207,7 @@ where
notification_entity: notification_entity.clone(),
notification_event: notification_event.clone(),
sender_id: Some(assigned_by.clone()),
- recipient_ids: Some(vec![recipient_id.clone()]),
+ recipient_ids: Some(vec![recipient_id.to_string()]),
};
let recipient_id_for_log = recipient_id.clone();
@@ -232,7 +241,7 @@ where
pub async fn handle_task_assignee_permissions(
&self,
task_id: Uuid,
- assignee_ids: &[String],
+ assignee_ids: &[MacroUserIdStr<'_>],
) -> Result<(), PropertiesErr> {
if assignee_ids.is_empty() {
return Ok(());
diff --git a/rust/cloud-storage/properties/src/domain/test.rs b/rust/cloud-storage/properties/src/domain/test.rs
index 0fd1b01c61..6a1940cc30 100644
--- a/rust/cloud-storage/properties/src/domain/test.rs
+++ b/rust/cloud-storage/properties/src/domain/test.rs
@@ -6,6 +6,7 @@ use crate::domain::{
service::PropertiesService,
};
use anyhow::anyhow;
+use macro_user_id::user_id::MacroUserIdStr;
use models_properties::{EntityType, service::property_value::PropertyValue};
use system_properties::{StatusOption, SystemPropertyKey};
use uuid::Uuid;
@@ -381,15 +382,20 @@ async fn test_handle_task_assignee_permissions_grants_permissions() {
let mut perm_service = MockPermissionService::new();
let task_id = Uuid::from_u128(0x12345678_1234_1234_1234_123456789abc);
- let assignee_ids = vec!["user1".to_string(), "user2".to_string()];
+ let assignee_ids = vec![
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ ];
perm_service
.expect_grant_permissions_to_task()
.withf(move |user_ids, task_id_param| {
user_ids.len() == 2
- && user_ids.contains(&"user1".to_string())
- && user_ids.contains(&"user2".to_string())
- && task_id_param == &task_id.to_string()
+ && user_ids
+ .contains(&MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap())
+ && user_ids
+ .contains(&MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap())
+ && task_id_param == task_id.to_string()
})
.returning(|_, _| Box::pin(async { Ok(()) }));
@@ -423,7 +429,7 @@ async fn test_handle_task_assignee_permissions_empty_assignees() {
async fn test_handle_task_assignee_permissions_no_service() {
let repo = MockPropertiesRepo::new();
let task_id = Uuid::from_u128(0x12345678_1234_1234_1234_123456789abc);
- let assignee_ids = vec!["user1".to_string()];
+ let assignee_ids = vec![MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()];
let service = PropertiesServiceImpl::new(
repo,
@@ -448,7 +454,7 @@ async fn test_handle_task_assignee_permissions_error_propagates() {
let mut perm_service = MockPermissionService::new();
let task_id = Uuid::from_u128(0x12345678_1234_1234_1234_123456789abc);
- let assignee_ids = vec!["user1".to_string()];
+ let assignee_ids = vec![MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()];
perm_service
.expect_grant_permissions_to_task()
@@ -472,7 +478,7 @@ async fn test_handle_task_assignee_permissions_error_propagates() {
struct NotificationTestCase {
task_id: Uuid,
assigned_by: String,
- assignees: Vec<String>,
+ assignees: Vec<MacroUserIdStr<'static>>,
existing_assignees: Vec<String>,
task_name: Option<String>,
expected_notification_count: usize,
@@ -493,7 +499,7 @@ async fn check_notifications(test_case: NotificationTestCase) {
// Mock: get current assignees
repo.expect_get_entity_property_value()
.withf(move |entity_id, entity_type, prop_id| {
- entity_id == &task_id.to_string()
+ entity_id == task_id.to_string()
&& *entity_type == EntityType::Task
&& *prop_id == SystemPropertyKey::ASSIGNEES_UUID
})
@@ -521,7 +527,7 @@ async fn check_notifications(test_case: NotificationTestCase) {
let task_id_clone = task_id;
let task_name_result = task_name.clone();
repo.expect_get_document_name()
- .withf(move |id| id == &task_id_clone.to_string())
+ .withf(move |id| id == task_id_clone.to_string())
.returning(move |_| {
let name = task_name_result.clone();
Box::pin(async move { Ok(name) })
@@ -578,9 +584,9 @@ async fn test_handle_task_assignee_notifications_sends_to_new_assignees_only() {
task_id: Uuid::from_u128(0x12345678_1234_1234_1234_123456789abc),
assigned_by: "macro|[email protected]".to_string(),
assignees: vec![
- "macro|[email protected]".to_string(),
- "macro|[email protected]".to_string(),
- "macro|[email protected]".to_string(), // existing, should not get notification
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(), // existing, should not get notification
],
existing_assignees: vec!["macro|[email protected]".to_string()],
task_name: Some("Test Task".to_string()),
@@ -597,8 +603,8 @@ async fn test_handle_task_assignee_notifications_filters_out_assigner() {
task_id: Uuid::from_u128(0x12345678_1234_1234_1234_123456789abc),
assigned_by: "macro|[email protected]".to_string(),
assignees: vec![
- "macro|[email protected]".to_string(),
- "macro|[email protected]".to_string(),
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
],
existing_assignees: vec![],
task_name: Some("Test Task".to_string()),
@@ -614,7 +620,7 @@ async fn test_handle_task_assignee_notifications_no_new_assignees() {
check_notifications(NotificationTestCase {
task_id: Uuid::from_u128(0x12345678_1234_1234_1234_123456789abc),
assigned_by: "macro|[email protected]".to_string(),
- assignees: vec!["macro|[email protected]".to_string()],
+ assignees: vec![MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()],
existing_assignees: vec!["macro|[email protected]".to_string()],
task_name: None, // Should not call get_entity_name
expected_notification_count: 0, // no new assignees
@@ -629,7 +635,7 @@ async fn test_handle_task_assignee_notifications_no_service() {
check_notifications(NotificationTestCase {
task_id: Uuid::from_u128(0x12345678_1234_1234_1234_123456789abc),
assigned_by: "assigner".to_string(),
- assignees: vec!["user1".to_string()],
+ assignees: vec![MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()],
existing_assignees: vec![],
task_name: None, // Should not call get_entity_name when no service
expected_notification_count: 0,
@@ -659,7 +665,7 @@ async fn test_handle_task_assignee_notifications_task_name_none() {
check_notifications(NotificationTestCase {
task_id: Uuid::from_u128(0x12345678_1234_1234_1234_123456789abc),
assigned_by: "macro|[email protected]".to_string(),
- assignees: vec!["macro|[email protected]".to_string()],
+ assignees: vec![MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()],
existing_assignees: vec![],
task_name: None, // task doesn't exist yet
expected_notification_count: 1,
@@ -682,9 +688,9 @@ async fn test_handle_task_assignees_property_calls_both_handlers() {
let task_id = Uuid::from_u128(0x12345678_1234_1234_1234_123456789abc);
let entity_id = task_id.to_string();
let assigned_by = "macro|[email protected]".to_string();
- let assignees = vec![
- "macro|[email protected]".to_string(),
- "macro|[email protected]".to_string(),
+ let assignees = [
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
];
let value = Some(
@@ -693,7 +699,7 @@ async fn test_handle_task_assignees_property_calls_both_handlers() {
.iter()
.map(|id| models_properties::shared::EntityReference {
entity_type: EntityType::User,
- entity_id: id.clone(),
+ entity_id: id.to_string(),
specific_message_id: None,
})
.collect(),
@@ -713,7 +719,7 @@ async fn test_handle_task_assignees_property_calls_both_handlers() {
perm_service
.expect_grant_permissions_to_task()
.times(1)
- .withf(move |user_ids, tid| user_ids.len() == 2 && tid == &entity_id_clone)
+ .withf(move |user_ids, tid| user_ids.len() == 2 && tid == entity_id_clone)
.returning(|_, _| Box::pin(async { Ok(()) }));
// Mock: notifications should be sent
diff --git a/rust/cloud-storage/properties/src/outbound/permission_service.rs b/rust/cloud-storage/properties/src/outbound/permission_service.rs
index f622ac8b65..e5a523ff97 100644
--- a/rust/cloud-storage/properties/src/outbound/permission_service.rs
+++ b/rust/cloud-storage/properties/src/outbound/permission_service.rs
@@ -1,5 +1,6 @@
//! Permission service implementation for properties.
+use macro_user_id::user_id::MacroUserIdStr;
use models_permissions::share_permission::access_level::AccessLevel;
use models_properties::EntityType;
use sqlx::{Pool, Postgres};
@@ -86,7 +87,7 @@ impl PermissionService for PermissionServiceImpl {
#[tracing::instrument(skip(self), fields(task_id = %task_id, user_count = user_ids.len()), err)]
async fn grant_permissions_to_task(
&self,
- user_ids: &[String],
+ user_ids: &[MacroUserIdStr<'_>],
task_id: &str,
) -> Result<(), Self::Err> {
if user_ids.is_empty() {
diff --git a/rust/cloud-storage/scribe/Cargo.toml b/rust/cloud-storage/scribe/Cargo.toml
index 531fa8f9c3..0c29e3e138 100644
--- a/rust/cloud-storage/scribe/Cargo.toml
+++ b/rust/cloud-storage/scribe/Cargo.toml
@@ -27,6 +27,7 @@ base64 = { workspace = true }
bytes = { workspace = true }
chrono = { workspace = true }
derive_builder = { workspace = true }
+doppleganger = { workspace = true }
futures = { workspace = true }
reqwest = { workspace = true }
serde = { workspace = true }
@@ -52,9 +53,9 @@ sync_service_client = { path = "../sync_service_client", optional = true }
comms_service_client = { path = "../comms_service_client", optional = true }
document_cognition_service_client = { path = "../document_cognition_service_client", optional = true }
email_service_client = { path = "../email_service_client", optional = true }
+image = "0.25.9"
models_comms = { path = "../models_comms", optional = true }
models_email = { path = "../models_email", optional = true }
models_sfs = { path = "../models_sfs", optional = true }
static_file_service_client = { path = "../static_file_service_client", optional = true }
-image = "0.25.9"
webp = "0.3.1"
diff --git a/rust/cloud-storage/scribe/src/channel/client.rs b/rust/cloud-storage/scribe/src/channel/client.rs
index 0176dcc4c1..6d46bd7224 100644
--- a/rust/cloud-storage/scribe/src/channel/client.rs
+++ b/rust/cloud-storage/scribe/src/channel/client.rs
@@ -1,7 +1,7 @@
use ai_format::{Indent, InsightContextLog};
use anyhow::Error;
use comms_service_client::CommsServiceClient;
-use models_comms::ChannelMetadata;
+use models_comms::channel::ChannelMetadata;
use std::fmt::Debug;
use std::sync::Arc;
use uuid::Uuid;
@@ -39,10 +39,19 @@ impl ChannelClient {
.await
.map_err(Error::from)?,
};
- Ok(ChannelMetadata::from((
- response.channel_name,
- response.channel_type,
- )))
+ Ok(ChannelMetadata {
+ name: response.channel_name,
+ channel_type: match response.channel_type {
+ model::comms::ChannelType::Public => models_comms::channel::ChannelType::Public,
+ model::comms::ChannelType::Organization => {
+ models_comms::channel::ChannelType::Organization
+ }
+ model::comms::ChannelType::Private => models_comms::channel::ChannelType::Private,
+ model::comms::ChannelType::DirectMessage => {
+ models_comms::channel::ChannelType::DirectMessage
+ }
+ },
+ })
}
/// Get channel transcript (message history) by channel ID
diff --git a/rust/cloud-storage/soup/Cargo.toml b/rust/cloud-storage/soup/Cargo.toml
index 8cb98ef163..0bedaf0908 100644
--- a/rust/cloud-storage/soup/Cargo.toml
+++ b/rust/cloud-storage/soup/Cargo.toml
@@ -26,6 +26,8 @@ anyhow = { workspace = true }
axum = { workspace = true, optional = true }
axum-extra = { workspace = true, optional = true }
chrono = { workspace = true }
+comms = { path = "../comms" }
+document_sub_type = { path = "../document_sub_type" }
doppleganger = { workspace = true, features = ["chrono", "uuid"] }
either = { workspace = true }
email = { path = "../email", features = ["ports"] }
@@ -47,7 +49,6 @@ tokio = { workspace = true, features = ["macros"], optional = true }
tracing = { workspace = true }
utoipa = { workspace = true, optional = true }
uuid = { workspace = true }
-document_sub_type = { path = "../document_sub_type" }
[dev-dependencies]
cool_asserts = "2"
@@ -59,6 +60,7 @@ item_filters = { path = "../item_filters", features = ["mock"] }
macro_db_migrator = { path = "../macro_db_migrator" }
mockall = { workspace = true }
ordered-float = { workspace = true }
+rootcause = "0.11"
serde_json = { workspace = true }
tokio = { workspace = true }
tower = { workspace = true }
diff --git a/rust/cloud-storage/soup/src/domain/models.rs b/rust/cloud-storage/soup/src/domain/models.rs
index c544a4b8ea..d629536553 100644
--- a/rust/cloud-storage/soup/src/domain/models.rs
+++ b/rust/cloud-storage/soup/src/domain/models.rs
@@ -194,4 +194,6 @@ pub enum SoupErr {
SoupDbErr(#[from] anyhow::Error),
#[error(transparent)]
EmailErr(#[from] email::domain::models::EmailErr),
+ #[error("A comms error has occured, see logs for more details")]
+ CommsErr,
}
diff --git a/rust/cloud-storage/soup/src/domain/service.rs b/rust/cloud-storage/soup/src/domain/service.rs
index 1a7a910f15..77d16e23db 100644
--- a/rust/cloud-storage/soup/src/domain/service.rs
+++ b/rust/cloud-storage/soup/src/domain/service.rs
@@ -5,6 +5,7 @@ use crate::domain::{
},
ports::{SoupOutput, SoupRepo, SoupService},
};
+use comms::domain::ports::ChannelsService;
use doppleganger::Mirror;
use either::Either;
use email::domain::{models::GetEmailsRequest, ports::EmailService};
@@ -18,7 +19,9 @@ use model_entity::as_owned::ShallowClone;
use models_pagination::{
Cursor, CursorVal, Frecency, FrecencyValue, PaginateOn, Query, SimpleSortMethod,
};
-use models_soup::{email_thread::SoupEnrichedEmailThreadPreview, item::SoupItem};
+use models_soup::{
+ comms::SoupChannel, email_thread::SoupEnrichedEmailThreadPreview, item::SoupItem,
+};
use std::cmp::Ordering;
use uuid::Uuid;
@@ -26,27 +29,31 @@ use uuid::Uuid;
mod tests;
/// struct which handles the actual implementation of soup with abstracted interfaces for mocking
-pub struct SoupImpl<T, U, V> {
+pub struct SoupImpl<T, U, V, C> {
/// the interface for interacting with the db
soup_storage: T,
/// the interface for interacting with frecency
frecency: U,
/// the interface for interacting with email
email_service: V,
+ /// the interface for interacting with comms
+ comms_service: C,
}
-impl<T, U, V> SoupImpl<T, U, V>
+impl<T, U, V, C> SoupImpl<T, U, V, C>
where
T: SoupRepo,
anyhow::Error: From<T::Err>,
U: FrecencyQueryService,
V: EmailService,
+ C: ChannelsService,
{
- pub fn new(soup_storage: T, frecency: U, email_service: V) -> Self {
+ pub fn new(soup_storage: T, frecency: U, email_service: V, comms_service: C) -> Self {
SoupImpl {
soup_storage,
frecency,
email_service,
+ comms_service,
}
}
@@ -262,14 +269,35 @@ where
});
Ok(Either::Right(emails))
}
+
+ async fn handle_comms_request(
+ &self,
+ req: MacroUserIdStr<'_>,
+ ) -> Result<impl Iterator<Item = FrecencySoupItem>, SoupErr> {
+ self.comms_service
+ .get_channels(req)
+ .await
+ .map_err(|_| SoupErr::CommsErr)
+ .map(|r| {
+ r.into_iter().map(|mut c| {
+ let frecency_score = c.frecency_score.take();
+ let soup_channel = SoupChannel::mirror(c);
+ FrecencySoupItem {
+ item: SoupItem::Channel(soup_channel),
+ frecency_score,
+ }
+ })
+ })
+ }
}
-impl<T, U, V> SoupService for SoupImpl<T, U, V>
+impl<T, U, V, C> SoupService for SoupImpl<T, U, V, C>
where
T: SoupRepo,
anyhow::Error: From<T::Err>,
U: FrecencyQueryService,
V: EmailService,
+ C: ChannelsService,
{
async fn get_user_soup(&self, req: SoupRequest) -> Result<SoupOutput, SoupErr> {
let limit = req.limit.clamp(20, 500);
@@ -286,17 +314,21 @@ where
SimpleSortRequest {
limit,
cursor: SimpleSortQuery::from_entity_cursor(cursor),
- user_id: req.user,
+ user_id: req.user.copied(),
},
);
let email_soup_fut = self.handle_email_request(email_request);
- let (main_soup, email_soup) = tokio::try_join!(main_soup_fut, email_soup_fut)?;
+ let comms_soup_fut = self.handle_comms_request(req.user.copied());
+
+ let (main_soup, email_soup, comms_soup) =
+ tokio::try_join!(main_soup_fut, email_soup_fut, comms_soup_fut)?;
Ok(Either::Left(
main_soup
.chain(email_soup)
+ .chain(comms_soup)
.paginate_on(limit.into(), sort_method)
.filter_on(paginate_filter)
.sort_desc()
diff --git a/rust/cloud-storage/soup/src/domain/service/tests.rs b/rust/cloud-storage/soup/src/domain/service/tests.rs
index aec79915fc..dfe118952a 100644
--- a/rust/cloud-storage/soup/src/domain/service/tests.rs
+++ b/rust/cloud-storage/soup/src/domain/service/tests.rs
@@ -13,6 +13,7 @@ use models_pagination::{
};
use models_soup::document::SoupDocument;
use ordered_float::OrderedFloat;
+use rootcause::Report;
use sqlx::types::chrono::{DateTime, Utc};
use uuid::Uuid;
@@ -43,6 +44,31 @@ impl EmailService for NoopEmailService {
}
}
+struct NoopCommsService;
+
+impl ChannelsService for NoopCommsService {
+ async fn get_channels(
+ &self,
+ _user: MacroUserIdStr<'_>,
+ ) -> Result<Vec<comms::domain::models::channel::ChannelWithLatest>, Report> {
+ Ok(Vec::new())
+ }
+
+ async fn get_activities(
+ &self,
+ _user: MacroUserIdStr<'_>,
+ ) -> Result<Vec<comms::domain::models::channel::Activity>, Report> {
+ Ok(Vec::new())
+ }
+
+ async fn get_names(
+ &self,
+ _names: std::collections::HashSet<MacroUserIdStr<'_>>,
+ ) -> Result<Vec<comms::domain::models::UserName>, Report> {
+ Ok(Vec::new())
+ }
+}
+
fn soup_document(id: &str) -> SoupDocument {
// Create a deterministic UUID from the string ID
let uuid = Uuid::parse_str(id).unwrap_or_else(|_| {
@@ -127,6 +153,7 @@ async fn it_should_not_query_frecency() {
soup_mock,
FrecencyQueryServiceImpl::new(MockFrecencyStorage::new()),
NoopEmailService,
+ NoopCommsService,
)
.get_user_soup(SoupRequest {
email_preview_view: PreviewView::StandardLabel(
@@ -204,6 +231,7 @@ async fn it_should_query_frecency() {
soup_mock,
FrecencyQueryServiceImpl::new(frecency_mock),
NoopEmailService,
+ NoopCommsService,
)
.get_user_soup(SoupRequest {
email_preview_view: PreviewView::StandardLabel(
@@ -281,6 +309,7 @@ async fn it_should_sort_frecency_descending() {
soup_mock,
FrecencyQueryServiceImpl::new(frecency_mock),
NoopEmailService,
+ NoopCommsService,
)
.get_user_soup(SoupRequest {
email_preview_view: PreviewView::StandardLabel(
@@ -368,7 +397,7 @@ async fn frecency_should_fallback() {
Box::pin(async move { res })
});
- let res = SoupImpl::new(soup, frecency, NoopEmailService)
+ let res = SoupImpl::new(soup, frecency, NoopEmailService, NoopCommsService)
.get_user_soup(SoupRequest {
email_preview_view: PreviewView::StandardLabel(
email::domain::models::PreviewViewStandardLabel::Inbox,
@@ -438,7 +467,7 @@ async fn frecency_should_paginate() {
Box::pin(async move { Ok(vec) })
});
- let res = SoupImpl::new(soup, frecency, NoopEmailService)
+ let res = SoupImpl::new(soup, frecency, NoopEmailService, NoopCommsService)
.get_user_soup(SoupRequest {
email_preview_view: PreviewView::StandardLabel(
email::domain::models::PreviewViewStandardLabel::Inbox,
@@ -510,7 +539,7 @@ async fn frecency_should_resume_cursor() {
Box::pin(async move { Ok(vec) })
});
- let res = SoupImpl::new(soup, frecency, NoopEmailService)
+ let res = SoupImpl::new(soup, frecency, NoopEmailService, NoopCommsService)
.get_user_soup(SoupRequest {
email_preview_view: PreviewView::StandardLabel(
email::domain::models::PreviewViewStandardLabel::Inbox,
@@ -598,7 +627,7 @@ async fn frecency_fallback_cursor_should_resume() {
Box::pin(async move { res })
});
- let res = SoupImpl::new(soup, frecency, NoopEmailService)
+ let res = SoupImpl::new(soup, frecency, NoopEmailService, NoopCommsService)
.get_user_soup(SoupRequest {
email_preview_view: PreviewView::StandardLabel(
email::domain::models::PreviewViewStandardLabel::Inbox,
@@ -663,6 +692,7 @@ async fn cursor_should_return_simple_sort() {
soup_mock,
FrecencyQueryServiceImpl::new(MockFrecencyStorage::new()),
NoopEmailService,
+ NoopCommsService,
)
.get_user_soup(SoupRequest {
email_preview_view: PreviewView::StandardLabel(
@@ -721,7 +751,7 @@ async fn cursor_should_return_frecency() {
Box::pin(async move { Ok(vec) })
});
- let res = SoupImpl::new(soup, frecency, NoopEmailService)
+ let res = SoupImpl::new(soup, frecency, NoopEmailService, NoopCommsService)
.get_user_soup(SoupRequest {
email_preview_view: PreviewView::StandardLabel(
email::domain::models::PreviewViewStandardLabel::Inbox,
diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs
index 51b017c784..d2d3436ada 100644
--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs
+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs
@@ -35,15 +35,7 @@ async fn test_viewed_at_orders_nulls_last(pool: Pool<Postgres>) -> anyhow::Resul
assert_eq!(items.len(), 13, "Should get 13 total items");
// Make sure we got only the items with a history entry.
- let returned_ids: HashSet<Uuid> = items
- .iter()
- .map(|item| match item {
- SoupItem::Chat(c) => c.id,
- SoupItem::Document(d) => d.id,
- SoupItem::Project(p) => p.id,
- SoupItem::EmailThread(t) => t.thread.id,
- })
- .collect();
+ let returned_ids: HashSet<Uuid> = items.iter().map(|item| item.id()).collect();
let expected_ids: HashSet<Uuid> = [
"22222222-0000-0000-0000-000000000000", // chat-standalone
@@ -224,7 +216,7 @@ async fn test_expanded_generic_sorting_methods(pool: Pool<Postgres>) -> anyhow::
);
let item_ids = get_item_ids(&items);
- let expected_ids: Vec<Uuid> = vec![
+ let expected_ids: Vec<Uuid> = [
"aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", // doc-A
"bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", // doc-B
"aaaaaaaa-cccc-cccc-cccc-cccccccccccc", // chat-A
@@ -254,7 +246,7 @@ async fn test_expanded_generic_sorting_methods(pool: Pool<Postgres>) -> anyhow::
assert_eq!(items.len(), 6, "UpdatedAt should return all 6 items");
let item_ids = get_item_ids(&items);
- let expected_ids: Vec<Uuid> = vec![
+ let expected_ids: Vec<Uuid> = [
"aaaaaaaa-cccc-cccc-cccc-cccccccccccc", // chat-A
"aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", // doc-A
"bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", // doc-B
@@ -284,7 +276,7 @@ async fn test_expanded_generic_sorting_methods(pool: Pool<Postgres>) -> anyhow::
assert_eq!(items.len(), 6, "CreatedAt should return all 6 items");
let item_ids = get_item_ids(&items);
- let expected_ids: Vec<Uuid> = vec![
+ let expected_ids: Vec<Uuid> = [
"bbbbbbbb-cccc-cccc-cccc-cccccccccccc", // chat-B
"bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", // doc-B
"aaaaaaaa-cccc-cccc-cccc-cccccccccccc", // chat-A
@@ -337,7 +329,10 @@ async fn test_expanded_soup_by_ids(pool: Pool<Postgres>) {
.iter()
.find_map(|x| match x {
SoupItem::Document(soup_document) => Some(soup_document),
- SoupItem::Chat(_) | SoupItem::Project(_) | _ => None,
+ SoupItem::Chat(_)
+ | SoupItem::Project(_)
+ | SoupItem::EmailThread(_)
+ | SoupItem::Channel(_) => None,
})
.expect("The document should exist");
let expected_doc_id = Uuid::parse_str("11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa").unwrap(); // doc-in-A
@@ -351,7 +346,7 @@ async fn test_expanded_soup_by_ids(pool: Pool<Postgres>) {
.iter()
.find_map(|x| match x {
SoupItem::Chat(soup_chat) => Some(soup_chat),
- SoupItem::Document(_) | SoupItem::Project(_) | _ => None,
+ _ => None,
})
.expect("The chat should exist");
let expected_chat_id = Uuid::parse_str("22222222-bbbb-bbbb-bbbb-bbbbbbbbbbbb").unwrap(); // chat-in-B