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.

Revert "Seanaye/feat/comms in soup (#757)" (#822)

Sean Aye05f90a991196
diff --git a/.gitattributes b/.gitattributes
deleted file mode 100644
index 8d0e6f7110..0000000000
--- a/.gitattributes
+++ /dev/null
@@ -1,2 +0,0 @@
-# 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 a31ee163e0..661a079b15 100644
--- a/flake.lock
+++ b/flake.lock
@@ -8,11 +8,11 @@
"rust-analyzer-src": "rust-analyzer-src"
},
"locked": {
- "lastModified": 1766472537,
- "narHash": "sha256-3L602HO6JUssIL3Vo32iceObsW75+6CwLMOXRD9S3IM=",
+ "lastModified": 1762584108,
+ "narHash": "sha256-wZUW7dlXMXaRdvNbaADqhF8gg9bAfFiMV+iyFQiDv+Y=",
"owner": "nix-community",
"repo": "fenix",
- "rev": "9591b811e48f906e0a9f7afe89676a1c333415dd",
+ "rev": "32f3ad3b6c690061173e1ac16708874975ec6056",
"type": "github"
},
"original": {
@@ -41,11 +41,11 @@
},
"nixpkgs": {
"locked": {
- "lastModified": 1766309749,
- "narHash": "sha256-3xY8CZ4rSnQ0NqGhMKAy5vgC+2IVK0NoVEzDoOh4DA4=",
+ "lastModified": 1762363567,
+ "narHash": "sha256-YRqMDEtSMbitIMj+JLpheSz0pwEr0Rmy5mC7myl17xs=",
"owner": "NixOS",
"repo": "nixpkgs",
- "rev": "a6531044f6d0bef691ea18d4d4ce44d0daa6e816",
+ "rev": "ae814fd3904b621d8ab97418f1d0f2eb0d3716f4",
"type": "github"
},
"original": {
@@ -65,11 +65,11 @@
"rust-analyzer-src": {
"flake": false,
"locked": {
- "lastModified": 1766411395,
- "narHash": "sha256-Cx5XbAfe0Iuoo+iQxF+H0peZ8XIZNotin5EcpzTsjXw=",
+ "lastModified": 1762438844,
+ "narHash": "sha256-ApIKJf6CcMsV2nYBXhGF95BmZMO/QXPhgfSnkA/rVUo=",
"owner": "rust-lang",
"repo": "rust-analyzer",
- "rev": "624761a86465fda44d329645774eee8080038e01",
+ "rev": "4bf516ee5a960c1e2eee9fedd9b1c9e976a19c86",
"type": "github"
},
"original": {
diff --git a/infra/stacks/cloud-storage-service/Pulumi.dev.yaml b/infra/stacks/cloud-storage-service/Pulumi.dev.yaml
index c4e8a4a2b5..2cfd8414e9 100644
--- a/infra/stacks/cloud-storage-service/Pulumi.dev.yaml
+++ b/infra/stacks/cloud-storage-service/Pulumi.dev.yaml
@@ -10,4 +10,3 @@ 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 9bed158ea8..e62422a0e7 100644
--- a/infra/stacks/cloud-storage-service/Pulumi.prod.yaml
+++ b/infra/stacks/cloud-storage-service/Pulumi.prod.yaml
@@ -10,4 +10,3 @@ 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 7db199caa8..49ec9de9b7 100644
--- a/infra/stacks/cloud-storage-service/index.ts
+++ b/infra/stacks/cloud-storage-service/index.ts
@@ -57,14 +57,6 @@ 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
@@ -231,7 +223,6 @@ const cloudStorageService = new CloudStorageService(
cloudfrontPrivateKeySecretArn,
internalApiKeyArn,
syncServiceAuthKeyArn,
- authenticationServiceSecretKeyArn,
MACRO_API_TOKENS.macroApiTokenPublicKeyArn,
],
notificationQueueArn,
@@ -357,14 +348,6 @@ 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 ea01204cee..3f7edbf56c 100644
--- a/js/app/flake.lock
+++ b/js/app/flake.lock
@@ -8,11 +8,11 @@
"rust-analyzer-src": "rust-analyzer-src"
},
"locked": {
- "lastModified": 1767682236,
- "narHash": "sha256-AWf4whMu4V1QA1wUFetWyddSfmhw6/VY5H90lXSDXjY=",
+ "lastModified": 1765435813,
+ "narHash": "sha256-C6tT7K1Lx6VsYw1BY5S3OavtapUvEnDQtmQB5DSgbCc=",
"owner": "nix-community",
"repo": "fenix",
- "rev": "ab32805338a72d8d69427426ce4259162e3d68bd",
+ "rev": "6399553b7a300c77e7f07342904eb696a5b6bf9d",
"type": "github"
},
"original": {
@@ -41,11 +41,11 @@
},
"nixpkgs": {
"locked": {
- "lastModified": 1767379071,
- "narHash": "sha256-EgE0pxsrW9jp9YFMkHL9JMXxcqi/OoumPJYwf+Okucw=",
+ "lastModified": 1765779637,
+ "narHash": "sha256-KJ2wa/BLSrTqDjbfyNx70ov/HdgNBCBBSQP3BIzKnv4=",
"owner": "NixOS",
"repo": "nixpkgs",
- "rev": "fb7944c166a3b630f177938e478f0378e64ce108",
+ "rev": "1306659b587dc277866c7b69eb97e5f07864d8c4",
"type": "github"
},
"original": {
@@ -65,11 +65,11 @@
"rust-analyzer-src": {
"flake": false,
"locked": {
- "lastModified": 1767609612,
- "narHash": "sha256-ghz849iTGb+if+co4yGQC2Nfc0H6B/K4JFeul9rm7n4=",
+ "lastModified": 1765400135,
+ "narHash": "sha256-D3+4hfNwUhG0fdCpDhOASLwEQ1jKuHi4mV72up4kLQM=",
"owner": "rust-lang",
"repo": "rust-analyzer",
- "rev": "58646b524408a5aecb12d91121ea5825bef3d0c8",
+ "rev": "fface27171988b3d605ef45cf986c25533116f7e",
"type": "github"
},
"original": {
diff --git a/js/app/packages/app/component/WhichKey.tsx b/js/app/packages/app/component/WhichKey.tsx
index 68070b54ec..9811b2e490 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 1c622582c6..1f0a8c6124 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 { ApiChannelWithLatest as ChannelWithLatest } from '@service-comms/generated/models';
+import type { 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 095ec7d7f2..9979a27bb2 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 4f6ccf1666..5c0e689247 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 3299ad1467..8b52bdd247 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 a686dfb8f7..ab2add9639 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,
- ApiChannelWithLatest as ChannelWithLatest,
+ 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] ?? [];
+ return result[1]?.items ?? [];
},
}));
}
@@ -44,7 +44,7 @@ export function createChannelsQuery() {
throw new Error('Failed to fetch channels', { cause: result[0] });
}
- return result[1] ?? [];
+ return result[1]?.channels ?? [];
},
}));
}
diff --git a/js/app/packages/core/component/NotificationRenderer.tsx b/js/app/packages/core/component/NotificationRenderer.tsx
index 14965e5492..3926c7ca63 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,7 +64,10 @@ 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 e4119daf30..3d8a1df77c 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 { ApiChannelWithLatest } from '@service-comms/generated/models';
+import type { GetChannelsResponse } from '@service-comms/generated/models/getChannelsResponse';
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: ApiChannelWithLatest[] = await response.json();
+ const { channels }: GetChannelsResponse = 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 ?? 0,
+ frecencyScore: channel.frecency_score,
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 b1164b18da..8b8968c9a8 100644
--- a/js/app/packages/macro-entity/src/queries/dss.ts
+++ b/js/app/packages/macro-entity/src/queries/dss.ts
@@ -27,7 +27,6 @@ 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,
@@ -199,13 +198,10 @@ const selectData: (
options: {
instructionsIdQuery: UseQueryResult<string | null | undefined, Error>;
}
-) => (
- | DocumentEntity
- | ChatEntity
- | ProjectEntity
- | EmailEntity
- | ChannelEntity
-)[] = (data, options) => {
+) => (DocumentEntity | ChatEntity | ProjectEntity | EmailEntity)[] = (
+ data,
+ options
+) => {
return data.pages.flatMap(({ items }) =>
items
.filter(
@@ -215,14 +211,7 @@ const selectData: (
item.data.id !== options.instructionsIdQuery.data
)
.map(
- (
- item
- ):
- | DocumentEntity
- | ChatEntity
- | ProjectEntity
- | EmailEntity
- | ChannelEntity => {
+ (item): DocumentEntity | ChatEntity | ProjectEntity | EmailEntity => {
if (item.tag === 'chat') {
return {
...item.data,
@@ -268,18 +257,6 @@ 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 4e38bb39bd..64234f3a92 100644
--- a/js/app/packages/service-clients/service-comms/client.ts
+++ b/js/app/packages/service-clients/service-comms/client.ts
@@ -10,11 +10,7 @@ import {
type ObjectLike,
} from '@core/util/maybeResult';
import type { SafeFetchInit } from '@core/util/safeFetch';
-import type {
- ApiActivity,
- ApiChannelWithLatest,
- GetMentionsResponse,
-} from './generated/models';
+import type { 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';
@@ -22,10 +18,12 @@ 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';
@@ -78,7 +76,7 @@ export const commsServiceClient = {
},
async getChannels() {
return mapOk(
- await commsFetch<ApiChannelWithLatest[]>(`/channels`, {
+ await commsFetch<GetChannelsResponse>(`/channels`, {
method: 'GET',
}),
(result) => result
@@ -164,7 +162,7 @@ export const commsServiceClient = {
},
async getActivity() {
return mapOk(
- await commsFetch<ApiActivity[]>(`/activity`, {
+ await commsFetch<GetActivityResponse>(`/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 5e1239f460..662f0cdc70 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: ApiActivity[]
+ data: GetActivityResponse
status: 200
}
@@ -209,7 +209,7 @@ export const getAttachmentReferences = async (entityType: string,
export type getChannelsResponse200 = {
- data: ApiChannelWithLatest[]
+ data: GetChannelsResponse
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
deleted file mode 100644
index 57620356e2..0000000000
--- a/js/app/packages/service-clients/service-comms/generated/models/apiActivity.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-/**
- * 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
deleted file mode 100644
index 0bf993bf19..0000000000
--- a/js/app/packages/service-clients/service-comms/generated/models/apiActivityInteractedAt.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-/**
- * 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/apiActivityViewedAt.ts b/js/app/packages/service-clients/service-comms/generated/models/apiActivityViewedAt.ts
deleted file mode 100644
index 51ee48b3cb..0000000000
--- a/js/app/packages/service-clients/service-comms/generated/models/apiActivityViewedAt.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
- */
-
-/**
- * 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/apiChannelWithLatestAllOf.ts b/js/app/packages/service-clients/service-comms/generated/models/apiChannelWithLatestAllOf.ts
deleted file mode 100644
index 9bfbae66a9..0000000000
--- a/js/app/packages/service-clients/service-comms/generated/models/apiChannelWithLatestAllOf.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-/**
- * 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/channel.ts b/js/app/packages/service-clients/service-comms/generated/models/channel.ts
index 01333eae54..b4853396f0 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,10 +17,7 @@ export interface Channel {
id: string;
/** string name of the channel */
name?: ChannelName;
- /**
- * id of the organization this channel belongs too
- * @minimum 0
- */
+ /** id of the organization this channel belongs too */
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 66e66ac67e..31d726a194 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,6 +7,5 @@
/**
* 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/apiChannelWithLatest.ts b/js/app/packages/service-clients/service-comms/generated/models/channelWithLatest.ts
similarity index 57%
rename from js/app/packages/service-clients/service-comms/generated/models/apiChannelWithLatest.ts
rename to js/app/packages/service-clients/service-comms/generated/models/channelWithLatest.ts
index adc7dccd1c..e306685d8a 100644
--- a/js/app/packages/service-clients/service-comms/generated/models/apiChannelWithLatest.ts
+++ b/js/app/packages/service-clients/service-comms/generated/models/channelWithLatest.ts
@@ -6,6 +6,6 @@
*/
import type { ChannelWithParticipants } from './channelWithParticipants';
import type { LatestMessage } from './latestMessage';
-import type { ApiChannelWithLatestAllOf } from './apiChannelWithLatestAllOf';
+import type { ChannelWithLatestAllOf } from './channelWithLatestAllOf';
-export type ApiChannelWithLatest = ChannelWithParticipants & LatestMessage & ApiChannelWithLatestAllOf;
+export type ChannelWithLatest = ChannelWithParticipants & LatestMessage & ChannelWithLatestAllOf;
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
new file mode 100644
index 0000000000..c203cc9cca
--- /dev/null
+++ b/js/app/packages/service-clients/service-comms/generated/models/channelWithLatestAllOf.ts
@@ -0,0 +1,14 @@
+/**
+ * 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/apiChannelWithLatestAllOfInteractedAt.ts b/js/app/packages/service-clients/service-comms/generated/models/channelWithLatestAllOfInteractedAt.ts
similarity index 63%
rename from js/app/packages/service-clients/service-comms/generated/models/apiChannelWithLatestAllOfInteractedAt.ts
rename to js/app/packages/service-clients/service-comms/generated/models/channelWithLatestAllOfInteractedAt.ts
index bf0391c7be..0651ba894b 100644
--- a/js/app/packages/service-clients/service-comms/generated/models/apiChannelWithLatestAllOfInteractedAt.ts
+++ b/js/app/packages/service-clients/service-comms/generated/models/channelWithLatestAllOfInteractedAt.ts
@@ -5,4 +5,4 @@
* OpenAPI spec version: 0.1.0
*/
-export type ApiChannelWithLatestAllOfInteractedAt = string | null;
+export type ChannelWithLatestAllOfInteractedAt = string | null;
diff --git a/js/app/packages/service-clients/service-comms/generated/models/apiChannelWithLatestAllOfViewedAt.ts b/js/app/packages/service-clients/service-comms/generated/models/channelWithLatestAllOfViewedAt.ts
similarity index 65%
rename from js/app/packages/service-clients/service-comms/generated/models/apiChannelWithLatestAllOfViewedAt.ts
rename to js/app/packages/service-clients/service-comms/generated/models/channelWithLatestAllOfViewedAt.ts
index 515da37ce3..615ba64487 100644
--- a/js/app/packages/service-clients/service-comms/generated/models/apiChannelWithLatestAllOfViewedAt.ts
+++ b/js/app/packages/service-clients/service-comms/generated/models/channelWithLatestAllOfViewedAt.ts
@@ -5,4 +5,4 @@
* OpenAPI spec version: 0.1.0
*/
-export type ApiChannelWithLatestAllOfViewedAt = string | null;
+export type ChannelWithLatestAllOfViewedAt = string | null;
diff --git a/js/app/packages/service-clients/service-comms/generated/models/apiChannelWithLatestAllOfFrecencyScore.ts b/js/app/packages/service-clients/service-comms/generated/models/getActivityResponse.ts
similarity index 52%
rename from js/app/packages/service-clients/service-comms/generated/models/apiChannelWithLatestAllOfFrecencyScore.ts
rename to js/app/packages/service-clients/service-comms/generated/models/getActivityResponse.ts
index cf3eedb234..818d7d4f91 100644
--- a/js/app/packages/service-clients/service-comms/generated/models/apiChannelWithLatestAllOfFrecencyScore.ts
+++ b/js/app/packages/service-clients/service-comms/generated/models/getActivityResponse.ts
@@ -4,5 +4,8 @@
* comms_service
* OpenAPI spec version: 0.1.0
*/
+import type { Activity } from './activity';
-export type ApiChannelWithLatestAllOfFrecencyScore = number | null;
+export interface GetActivityResponse {
+ items: Activity[];
+}
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
new file mode 100644
index 0000000000..69c441ca6d
--- /dev/null
+++ b/js/app/packages/service-clients/service-comms/generated/models/getChannelsResponse.ts
@@ -0,0 +1,11 @@
+/**
+ * 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 7dcf3be7a4..321f3d8c4f 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,14 +10,6 @@ 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';
@@ -44,6 +36,10 @@ 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';
@@ -69,6 +65,7 @@ export * from './entityReferenceOneOfFourAllOfReferenceType';
export * from './genericErrorResponse';
export * from './genericReference';
export * from './genericReferenceUserId';
+export * from './getActivityResponse';
export * from './getAttachmentReferencesResponse';
export * from './getBatchChannelPreviewRequest';
export * from './getBatchChannelPreviewResponse';
@@ -76,6 +73,7 @@ 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 fa4a8b1b08..698b597c5b 100644
--- a/js/app/packages/service-clients/service-comms/openapi.json
+++ b/js/app/packages/service-clients/service-comms/openapi.json
@@ -17,10 +17,7 @@
"description": "",
"content": {
"application/json": {
- "schema": {
- "type": "array",
- "items": { "$ref": "#/components/schemas/ApiActivity" }
- }
+ "schema": { "$ref": "#/components/schemas/GetActivityResponse" }
}
}
},
@@ -128,12 +125,7 @@
"description": "",
"content": {
"application/json": {
- "schema": {
- "type": "array",
- "items": {
- "$ref": "#/components/schemas/ApiChannelWithLatest"
- }
- }
+ "schema": { "$ref": "#/components/schemas/GetChannelsResponse" }
}
}
},
@@ -990,47 +982,6 @@
"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": [
@@ -1086,9 +1037,8 @@
},
"org_id": {
"type": ["integer", "null"],
- "format": "int32",
- "description": "id of the organization this channel belongs too",
- "minimum": 0
+ "format": "int64",
+ "description": "id of the organization this channel belongs too"
},
"owner_id": {
"type": "string",
@@ -1256,6 +1206,24 @@
"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" },
@@ -1468,6 +1436,16 @@
}
}
},
+ "GetActivityResponse": {
+ "type": "object",
+ "required": ["items"],
+ "properties": {
+ "items": {
+ "type": "array",
+ "items": { "$ref": "#/components/schemas/Activity" }
+ }
+ }
+ },
"GetAttachmentReferencesResponse": {
"type": "object",
"required": ["references"],
@@ -1549,6 +1527,16 @@
}
}
},
+ "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
deleted file mode 100644
index c973ba07a4..0000000000
--- a/js/app/packages/service-clients/service-storage/generated/schemas/channel.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-/**
- * 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
deleted file mode 100644
index d8fb5c8454..0000000000
--- a/js/app/packages/service-clients/service-storage/generated/schemas/channelMessage.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-/**
- * 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
deleted file mode 100644
index b5cf27a69c..0000000000
--- a/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageDeletedAt.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-/**
- * 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
deleted file mode 100644
index 17b8eaa334..0000000000
--- a/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageThreadId.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-/**
- * 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
deleted file mode 100644
index 2b7aa10b06..0000000000
--- a/js/app/packages/service-clients/service-storage/generated/schemas/channelName.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-/**
- * 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
deleted file mode 100644
index 6f0e6628a0..0000000000
--- a/js/app/packages/service-clients/service-storage/generated/schemas/channelOrgId.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/**
- * 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
deleted file mode 100644
index c1ee072769..0000000000
--- a/js/app/packages/service-clients/service-storage/generated/schemas/channelParticipant.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-/**
- * 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
deleted file mode 100644
index 024ace604c..0000000000
--- a/js/app/packages/service-clients/service-storage/generated/schemas/channelParticipantLeftAt.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-/**
- * 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
deleted file mode 100644
index a99327fb92..0000000000
--- a/js/app/packages/service-clients/service-storage/generated/schemas/channelType.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-/**
- * 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
deleted file mode 100644
index 941e556121..0000000000
--- a/js/app/packages/service-clients/service-storage/generated/schemas/channelWithParticipants.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-/**
- * 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 cd50931951..e61d634d6e 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,19 +50,9 @@ 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';
@@ -292,9 +282,6 @@ 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';
@@ -302,7 +289,6 @@ export * from './params';
export * from './paramsExpand';
export * from './paramsLimit';
export * from './paramsSortMethod';
-export * from './participantRole';
export * from './patchProjectRequestV2';
export * from './patchProjectRequestV2Name';
export * from './patchProjectRequestV2ProjectParentId';
@@ -413,10 +399,6 @@ 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';
@@ -448,13 +430,12 @@ 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
deleted file mode 100644
index 0d768f530f..0000000000
--- a/js/app/packages/service-clients/service-storage/generated/schemas/latestMessage.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-/**
- * 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
deleted file mode 100644
index 4023722f61..0000000000
--- a/js/app/packages/service-clients/service-storage/generated/schemas/latestMessageLatestMessage.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-/**
- * 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
deleted file mode 100644
index 089038e01d..0000000000
--- a/js/app/packages/service-clients/service-storage/generated/schemas/latestMessageLatestNonThreadMessage.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-/**
- * 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/soupChannel.ts b/js/app/packages/service-clients/service-storage/generated/schemas/soupChannel.ts
deleted file mode 100644
index d6dfe4d645..0000000000
--- a/js/app/packages/service-clients/service-storage/generated/schemas/soupChannel.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/**
- * 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
deleted file mode 100644
index 154952fb35..0000000000
--- a/js/app/packages/service-clients/service-storage/generated/schemas/soupChannelAllOf.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-/**
- * 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
deleted file mode 100644
index 01cd61667e..0000000000
--- a/js/app/packages/service-clients/service-storage/generated/schemas/soupChannelAllOfInteractedAt.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-/**
- * 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
deleted file mode 100644
index eb28cc17e6..0000000000
--- a/js/app/packages/service-clients/service-storage/generated/schemas/soupChannelAllOfViewedAt.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-/**
- * 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 b630920479..014b734ac3 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,6 +8,5 @@ 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 | SoupItemOneOfNine;
+export type SoupItem = SoupItemOneOf | SoupItemOneOfThree | SoupItemOneOfFive | SoupItemOneOfSeven;
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
deleted file mode 100644
index 52e089b4d3..0000000000
--- a/js/app/packages/service-clients/service-storage/generated/schemas/soupItemOneOfNine.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-/**
- * 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
deleted file mode 100644
index 878319dd98..0000000000
--- a/js/app/packages/service-clients/service-storage/generated/schemas/soupItemOneOfNineTag.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-/**
- * 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/schemas/participantRole.ts b/js/app/packages/service-clients/service-storage/generated/schemas/soupItemType.ts
similarity index 50%
rename from js/app/packages/service-clients/service-storage/generated/schemas/participantRole.ts
rename to js/app/packages/service-clients/service-storage/generated/schemas/soupItemType.ts
index 9029093a9b..c9032b01eb 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/participantRole.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/soupItemType.ts
@@ -5,12 +5,13 @@
* OpenAPI spec version: 0.1.0
*/
-export type ParticipantRole = typeof ParticipantRole[keyof typeof ParticipantRole];
+export type SoupItemType = typeof SoupItemType[keyof typeof SoupItemType];
// eslint-disable-next-line @typescript-eslint/no-redeclare
-export const ParticipantRole = {
- owner: 'owner',
- admin: 'admin',
- member: 'member',
+export const SoupItemType = {
+ document: 'document',
+ chat: 'chat',
+ project: 'project',
+ email_thread: 'email_thread',
} 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 addbea6340..9a088efa76 100644
--- a/js/app/packages/service-clients/service-storage/generated/zod.ts
+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts
@@ -1231,9 +1231,6 @@ 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({
@@ -1337,50 +1334,6 @@ 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()
}))),
@@ -1436,9 +1389,6 @@ 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({
@@ -1542,50 +1492,6 @@ 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 4073c246a2..774ed6a180 100644
--- a/js/app/packages/service-clients/service-storage/openapi.json
+++ b/js/app/packages/service-clients/service-storage/openapi.json
@@ -4209,29 +4209,6 @@
}
}
},
- "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.",
@@ -4263,42 +4240,6 @@
}
}
},
- "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",
@@ -4311,21 +4252,6 @@
"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": [
@@ -6278,23 +6204,6 @@
"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": [
{
@@ -6346,10 +6255,6 @@
}
}
},
- "ParticipantRole": {
- "type": "string",
- "enum": ["owner", "admin", "member"]
- },
"PatchProjectRequestV2": {
"type": "object",
"properties": {
@@ -7142,22 +7047,6 @@
"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": [
@@ -7432,17 +7321,13 @@
},
"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 822947b3fc..a8f9ffd9e0 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 dab070fd0d..fa3934429a 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -1776,30 +1776,6 @@ 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"
@@ -1807,13 +1783,11 @@ dependencies = [
"anyhow",
"cached",
"chrono",
- "doppleganger",
"futures",
"macro_db_migrator",
"macro_user_id",
"macro_uuid",
"model",
- "models_comms",
"serde",
"serde_json",
"sqlx",
@@ -1838,11 +1812,9 @@ dependencies = [
"axum-extra",
"axum-macros",
"chrono",
- "comms",
"comms_db_client",
"connection_gateway",
"document_storage_service_client",
- "doppleganger",
"frecency",
"futures",
"http-body-util",
@@ -2587,7 +2559,6 @@ dependencies = [
"dashmap",
"document_cognition_service_client",
"document_storage_service_client",
- "doppleganger",
"email_service_client",
"futures",
"http-body-util",
@@ -2669,7 +2640,6 @@ dependencies = [
"chrono",
"clap",
"cloudfront_sign",
- "comms",
"comms_service_client",
"connection_gateway",
"cool_asserts",
@@ -3771,7 +3741,7 @@ dependencies = [
"futures-sink",
"futures-util",
"http 0.2.12",
- "indexmap 2.12.1",
+ "indexmap 2.7.1",
"slab",
"tokio",
"tokio-util",
@@ -3790,7 +3760,7 @@ dependencies = [
"futures-core",
"futures-sink",
"http 1.3.1",
- "indexmap 2.12.1",
+ "indexmap 2.7.1",
"slab",
"tokio",
"tokio-util",
@@ -3834,12 +3804,6 @@ 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"
@@ -4406,14 +4370,13 @@ dependencies = [
[[package]]
name = "indexmap"
-version = "2.12.1"
+version = "2.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0ad4bb2b565bca0645f4d68c5c9af97fba094e9791da685bf83cb5f3ce74acf2"
+checksum = "8c9c992b02b5b4c94ea26e32fe5bccb7aa7d9f390ab5c1221ff895bc7ea8b652"
dependencies = [
"equivalent",
- "hashbrown 0.16.1",
+ "hashbrown 0.15.2",
"serde",
- "serde_core",
]
[[package]]
@@ -5441,7 +5404,6 @@ dependencies = [
"base64 0.22.1",
"chrono",
"document_sub_type",
- "doppleganger",
"macro_user_id",
"model-error-response",
"model_file_type",
@@ -5500,7 +5462,6 @@ version = "0.1.0"
dependencies = [
"anyhow",
"chrono",
- "doppleganger",
"macro_user_id",
"model-entity",
"models_comms",
@@ -5541,12 +5502,12 @@ version = "0.1.0"
dependencies = [
"anyhow",
"chrono",
- "doppleganger",
- "frecency",
- "macro_user_id",
"serde",
+ "serde_json",
+ "sqlx",
"strum",
"thiserror 2.0.17",
+ "utoipa",
"uuid",
]
@@ -5695,7 +5656,6 @@ version = "0.1.0"
dependencies = [
"anyhow",
"chrono",
- "comms",
"document_sub_type",
"doppleganger",
"email",
@@ -7251,28 +7211,6 @@ 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"
@@ -7593,7 +7531,6 @@ dependencies = [
"derive_builder",
"document_cognition_service_client",
"document_storage_service_client",
- "doppleganger",
"email_service_client",
"futures",
"image",
@@ -7693,7 +7630,7 @@ dependencies = [
"email_service_client",
"futures",
"http-body-util",
- "indexmap 2.12.1",
+ "indexmap 2.7.1",
"item_filters",
"macro_auth",
"macro_cors",
@@ -8021,7 +7958,7 @@ dependencies = [
"chrono",
"hex",
"indexmap 1.9.3",
- "indexmap 2.12.1",
+ "indexmap 2.7.1",
"serde",
"serde_derive",
"serde_json",
@@ -8298,7 +8235,6 @@ dependencies = [
"axum",
"axum-extra",
"chrono",
- "comms",
"cool_asserts",
"document_sub_type",
"doppleganger",
@@ -8320,7 +8256,6 @@ dependencies = [
"non_empty",
"ordered-float",
"recursion",
- "rootcause",
"serde",
"serde_json",
"sqlx",
@@ -8393,7 +8328,7 @@ dependencies = [
"futures-util",
"hashbrown 0.15.2",
"hashlink",
- "indexmap 2.12.1",
+ "indexmap 2.7.1",
"log",
"memchr",
"native-tls",
@@ -9288,12 +9223,6 @@ 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"
@@ -9607,7 +9536,7 @@ version = "5.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "435c6f69ef38c9017b4b4eea965dfb91e71e53d869e896db40d1cf2441dd75c0"
dependencies = [
- "indexmap 2.12.1",
+ "indexmap 2.7.1",
"serde",
"serde_json",
"utoipa-gen",
@@ -10411,7 +10340,7 @@ dependencies = [
"flate2",
"getrandom 0.3.1",
"hmac",
- "indexmap 2.12.1",
+ "indexmap 2.7.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
new file mode 100644
index 0000000000..40d7391973
--- /dev/null
+++ b/rust/cloud-storage/authentication_service_client/src/get_names.rs
@@ -0,0 +1,64 @@
+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 376e30fbed..c68fcca450 100644
--- a/rust/cloud-storage/authentication_service_client/src/lib.rs
+++ b/rust/cloud-storage/authentication_service_client/src/lib.rs
@@ -1,4 +1,5 @@
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/Cargo.toml b/rust/cloud-storage/comms/Cargo.toml
deleted file mode 100644
index 72678a25be..0000000000
--- a/rust/cloud-storage/comms/Cargo.toml
+++ /dev/null
@@ -1,30 +0,0 @@
-[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
deleted file mode 100644
index 901e625fda..0000000000
--- a/rust/cloud-storage/comms/src/domain.rs
+++ /dev/null
@@ -1,3 +0,0 @@
-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
deleted file mode 100644
index fabc786424..0000000000
--- a/rust/cloud-storage/comms/src/domain/models.rs
+++ /dev/null
@@ -1,37 +0,0 @@
-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
deleted file mode 100644
index ad79d1bdcb..0000000000
--- a/rust/cloud-storage/comms/src/domain/models/channel_name.rs
+++ /dev/null
@@ -1,81 +0,0 @@
-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
deleted file mode 100644
index 517b4ae266..0000000000
--- a/rust/cloud-storage/comms/src/domain/models/channel_name/tests.rs
+++ /dev/null
@@ -1,169 +0,0 @@
-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
deleted file mode 100644
index a46cfb7276..0000000000
--- a/rust/cloud-storage/comms/src/domain/ports.rs
+++ /dev/null
@@ -1,50 +0,0 @@
-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
deleted file mode 100644
index 9bb448dde7..0000000000
--- a/rust/cloud-storage/comms/src/domain/service.rs
+++ /dev/null
@@ -1,142 +0,0 @@
-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
deleted file mode 100644
index c9ee16742e..0000000000
--- a/rust/cloud-storage/comms/src/inbound.rs
+++ /dev/null
@@ -1,224 +0,0 @@
-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
deleted file mode 100644
index f76105df0f..0000000000
--- a/rust/cloud-storage/comms/src/lib.rs
+++ /dev/null
@@ -1,5 +0,0 @@
-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
deleted file mode 100644
index 921cda0f97..0000000000
--- a/rust/cloud-storage/comms/src/outbound.rs
+++ /dev/null
@@ -1,2 +0,0 @@
-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
deleted file mode 100644
index cf6231f423..0000000000
--- a/rust/cloud-storage/comms/src/outbound/http.rs
+++ /dev/null
@@ -1 +0,0 @@
-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
deleted file mode 100644
index 1a2edd3849..0000000000
--- a/rust/cloud-storage/comms/src/outbound/http/user_repo.rs
+++ /dev/null
@@ -1,73 +0,0 @@
-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
deleted file mode 100644
index 99bb43dbec..0000000000
--- a/rust/cloud-storage/comms/src/outbound/postgres.rs
+++ /dev/null
@@ -1 +0,0 @@
-pub mod comms_repo;
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
deleted file mode 100644
index bf838a4be9..0000000000
--- a/rust/cloud-storage/comms/src/outbound/postgres/comms_repo/tests.rs
+++ /dev/null
@@ -1,155 +0,0 @@
-#[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/.sqlx/query-23a3f847d9d017fb9e5faf9e8b7b0ed6fc3621a443b76867e7b193453cfae7eb.json b/rust/cloud-storage/comms_db_client/.sqlx/query-23a3f847d9d017fb9e5faf9e8b7b0ed6fc3621a443b76867e7b193453cfae7eb.json
similarity index 100%
rename from rust/cloud-storage/comms/.sqlx/query-23a3f847d9d017fb9e5faf9e8b7b0ed6fc3621a443b76867e7b193453cfae7eb.json
rename to rust/cloud-storage/comms_db_client/.sqlx/query-23a3f847d9d017fb9e5faf9e8b7b0ed6fc3621a443b76867e7b193453cfae7eb.json
diff --git a/rust/cloud-storage/comms/.sqlx/query-7ee9ba5adfac304c7ac930943538ecca7428b1054d451fb2f8973cf9c11caf45.json b/rust/cloud-storage/comms_db_client/.sqlx/query-7ee9ba5adfac304c7ac930943538ecca7428b1054d451fb2f8973cf9c11caf45.json
similarity index 100%
rename from rust/cloud-storage/comms/.sqlx/query-7ee9ba5adfac304c7ac930943538ecca7428b1054d451fb2f8973cf9c11caf45.json
rename to rust/cloud-storage/comms_db_client/.sqlx/query-7ee9ba5adfac304c7ac930943538ecca7428b1054d451fb2f8973cf9c11caf45.json
diff --git a/rust/cloud-storage/comms_db_client/.sqlx/query-a7f90096050e550d15ef11bbc56a3cd79e1a80bc3f46cd063d0ff94d9b76f252.json b/rust/cloud-storage/comms_db_client/.sqlx/query-8b6544a586ac95ece01dc4837e5d7be5b36735131fc567e0ae371b6b2b6dcb66.json
similarity index 79%
rename from rust/cloud-storage/comms_db_client/.sqlx/query-a7f90096050e550d15ef11bbc56a3cd79e1a80bc3f46cd063d0ff94d9b76f252.json
rename to rust/cloud-storage/comms_db_client/.sqlx/query-8b6544a586ac95ece01dc4837e5d7be5b36735131fc567e0ae371b6b2b6dcb66.json
index 8bc55d69f6..3e46c2eac4 100644
--- a/rust/cloud-storage/comms_db_client/.sqlx/query-a7f90096050e550d15ef11bbc56a3cd79e1a80bc3f46cd063d0ff94d9b76f252.json
+++ b/rust/cloud-storage/comms_db_client/.sqlx/query-8b6544a586ac95ece01dc4837e5d7be5b36735131fc567e0ae371b6b2b6dcb66.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: DbParticipantRole\"\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: ParticipantRole\"\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: DbParticipantRole",
+ "name": "role: ParticipantRole",
"type_info": {
"Custom": {
"name": "comms_participant_role",
@@ -53,5 +53,5 @@
false
]
},
- "hash": "a7f90096050e550d15ef11bbc56a3cd79e1a80bc3f46cd063d0ff94d9b76f252"
+ "hash": "8b6544a586ac95ece01dc4837e5d7be5b36735131fc567e0ae371b6b2b6dcb66"
}
diff --git a/rust/cloud-storage/comms/.sqlx/query-9afc6f436aedd226ed0d6bf85de64c5ff57853c93ff00f768b49bf79f198590b.json b/rust/cloud-storage/comms_db_client/.sqlx/query-9afc6f436aedd226ed0d6bf85de64c5ff57853c93ff00f768b49bf79f198590b.json
similarity index 100%
rename from rust/cloud-storage/comms/.sqlx/query-9afc6f436aedd226ed0d6bf85de64c5ff57853c93ff00f768b49bf79f198590b.json
rename to rust/cloud-storage/comms_db_client/.sqlx/query-9afc6f436aedd226ed0d6bf85de64c5ff57853c93ff00f768b49bf79f198590b.json
diff --git a/rust/cloud-storage/comms_db_client/Cargo.toml b/rust/cloud-storage/comms_db_client/Cargo.toml
index 7b277010a8..d06797fba8 100644
--- a/rust/cloud-storage/comms_db_client/Cargo.toml
+++ b/rust/cloud-storage/comms_db_client/Cargo.toml
@@ -8,12 +8,10 @@ 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 693602b334..875c2d9c31 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, '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]');
+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');
INSERT INTO comms_channel_participants (channel_id, role, user_id)
-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]');
+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');
-- 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 9bf2b2679b..c0f798396b 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, 'macro|[email protected]'),
- ('22222222-2222-2222-2222-222222222222', 'private-channel', 'private', NULL, 'macro|[email protected]');
+VALUES ('11111111-1111-1111-1111-111111111111', 'private-channel', 'private', NULL, 'owner1'),
+ ('22222222-2222-2222-2222-222222222222', 'private-channel', 'private', NULL, 'owner1');
INSERT INTO comms_channel_participants (channel_id, role, user_id)
-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]');
+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');
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', 'macro|[email protected]', 'Test message 1'),
+ '11111111-1111-1111-1111-111111111111', 'user1', 'Test message 1'),
('22222222-2222-2222-2222-222222222222', '11111111-1111-1111-1111-111111111111',
- '11111111-1111-1111-1111-111111111111', 'macro|[email protected]', 'Test message 1'),
+ '11111111-1111-1111-1111-111111111111', 'user2', 'Test message 1'),
('33333333-3333-3333-3333-333333333333', '11111111-1111-1111-1111-111111111111',
- '11111111-1111-1111-1111-111111111111', 'macro|[email protected]', 'Test message 1'),
+ '11111111-1111-1111-1111-111111111111', 'user3', 'Test message 1'),
('44444444-4444-4444-4444-444444444444', '11111111-1111-1111-1111-111111111111',
- '11111111-1111-1111-1111-111111111111', 'macro|[email protected]', 'Test message 1'),
+ '11111111-1111-1111-1111-111111111111', 'user4', 'Test message 1'),
('55555555-5555-5555-5555-555555555555', '11111111-1111-1111-1111-111111111111',
- '22222222-2222-2222-2222-222222222222', 'macro|[email protected]', 'Test message 1');
+ '22222222-2222-2222-2222-222222222222', 'user5', '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 9679001ff1..08ed6f815f 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,6 +6,36 @@ 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 a3d45304ea..08cb684df7 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 961f1c699d..be94c0e666 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,11 +1,12 @@
use anyhow::{Context, Result};
-use macro_user_id::cowlike::CowLike;
-use model::comms::{Channel, ChannelId, ChannelType, OrganizationId};
+#[allow(unused_imports)]
+use model::comms::{Channel, ChannelType};
use sqlx::{Pool, Postgres};
use uuid::Uuid;
pub async fn get_channel(db: &Pool<Postgres>, channel_id: &Uuid) -> Result<Channel> {
- let channel = sqlx::query!(
+ let channel = sqlx::query_as!(
+ Channel,
r#"
SELECT
id,
@@ -20,19 +21,6 @@ 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 5156acde36..969aa5a73c 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,8 +1,6 @@
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;
@@ -72,11 +70,95 @@ 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!(
+ let channels = sqlx::query_as!(
+ Channel,
r#"
SELECT
id as "id!",
@@ -93,19 +175,6 @@ 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 3b3fce63d7..2b5a16ef27 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,23 +53,18 @@ 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![
- "macro|[email protected]".to_string(),
- "macro|[email protected]".to_string(),
- ],
- )
- .await?;
+ let result =
+ maybe_get_private_channel(&pool, &vec!["user1".to_string(), "user2".to_string()])
+ .await?;
assert_eq!(result, None);
let result = maybe_get_private_channel(
&pool,
&vec![
- "macro|[email protected]".to_string(),
- "macro|[email protected]".to_string(),
- "macro|[email protected]".to_string(),
+ "user1".to_string(),
+ "user3".to_string(),
+ "user2".to_string(),
],
)
.await?;
@@ -82,10 +77,10 @@ mod tests {
let result = maybe_get_private_channel(
&pool,
&vec![
- "macro|[email protected]".to_string(),
- "macro|[email protected]".to_string(),
- "macro|[email protected]".to_string(),
- "macro|[email protected]".to_string(),
+ "user1".to_string(),
+ "user3".to_string(),
+ "user4".to_string(),
+ "user2".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 da73412e12..92088ef7d3 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/src/outbound/postgres/comms_repo.rs b/rust/cloud-storage/comms_db_client/src/messages/get_latest_message.rs
similarity index 52%
rename from rust/cloud-storage/comms/src/outbound/postgres/comms_repo.rs
rename to rust/cloud-storage/comms_db_client/src/messages/get_latest_message.rs
index 274a615c72..f9d478ddf7 100644
--- a/rust/cloud-storage/comms/src/outbound/postgres/comms_repo.rs
+++ b/rust/cloud-storage/comms_db_client/src/messages/get_latest_message.rs
@@ -1,117 +1,20 @@
-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 anyhow::Result;
+use model::comms::{ChannelMessage, LatestMessage};
+use sqlx::{Pool, Postgres};
use std::collections::HashMap;
use uuid::Uuid;
-#[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
-}
+pub type ChannelLatestMessages = HashMap<Uuid, LatestMessage>;
#[tracing::instrument(err)]
pub async fn get_latest_channel_messages_batch(
- pool: &PgPool,
- channel_ids: &[ChannelId],
-) -> Result<HashMap<ChannelId, LatestMessage>, Report> {
+ pool: &Pool<Postgres>,
+ channel_ids: &[Uuid],
+) -> Result<ChannelLatestMessages> {
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 (
@@ -186,12 +89,12 @@ pub async fn get_latest_channel_messages_batch(
LIMIT 1
) n ON TRUE
"#,
- &ids
+ channel_ids
)
.fetch_all(pool)
.await?;
- let mut result = HashMap::with_capacity(rows.len());
+ let mut result: ChannelLatestMessages = HashMap::with_capacity(rows.len());
let build_message = |message_id: Option<Uuid>,
thread_id: Option<Uuid>,
@@ -250,7 +153,7 @@ pub async fn get_latest_channel_messages_batch(
);
result.insert(
- ChannelId(row.channel_id),
+ row.channel_id,
LatestMessage {
latest_message,
latest_non_thread_message,
@@ -262,81 +165,168 @@ pub async fn get_latest_channel_messages_batch(
}
pub async fn get_latest_channel_message(
- pool: &PgPool,
- channel_id: ChannelId,
-) -> Result<LatestMessage, Report> {
+ pool: &Pool<Postgres>,
+ channel_id: Uuid,
+) -> Result<LatestMessage> {
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?)
-}
-pub struct PgCommsRepo {
- pub pool: PgPool,
-}
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use macro_db_migrator::MACRO_DB_MIGRATIONS;
-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?)
+ fn uuid(s: &str) -> Uuid {
+ Uuid::parse_str(s).unwrap()
}
- 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_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_activities(
- &self,
- user_id: MacroUserIdStr<'_>,
- ) -> Result<Vec<models_comms::channel::Activity>, rootcause::Report> {
- get_activities(&self.pool, user_id).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(())
}
}
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 c85405052a..eea1d97b15 100644
--- a/rust/cloud-storage/comms_db_client/src/messages/mod.rs
+++ b/rust/cloud-storage/comms_db_client/src/messages/mod.rs
@@ -4,7 +4,10 @@ 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 568c9cbf7e..09b9784900 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,51 +1,29 @@
use anyhow::{Context, Result};
-use doppleganger::Doppleganger;
-use doppleganger::Mirror;
-use macro_user_id::cowlike::CowLike;
-use macro_user_id::user_id::MacroUserIdStr;
-use model::comms::ChannelId;
+use model::comms::ChannelParticipant;
+use model::comms::ParticipantRole;
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<models_comms::channel::ChannelParticipant>, sqlx::Error> {
- let participants = sqlx::query!(
+) -> Result<Vec<ChannelParticipant>, sqlx::Error> {
+ let participants = sqlx::query_as!(
+ ChannelParticipant,
r#"
SELECT
user_id,
channel_id,
joined_at,
left_at,
- role as "role: DbParticipantRole"
+ role as "role: ParticipantRole"
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?;
@@ -78,8 +56,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<MacroUserIdStr<'static>>> {
- let participants: Vec<_> = sqlx::query!(
+) -> Result<Vec<String>> {
+ let participants: Vec<String> = sqlx::query!(
r#"
SELECT DISTINCT(m.sender_id) as id
FROM comms_channel_participants cp
@@ -89,11 +67,7 @@ pub async fn get_channel_participants_for_thread_id(
"#,
thread_id
)
- .try_map(|participant| {
- Ok(MacroUserIdStr::parse_from_str(&participant.id)
- .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
- .into_owned())
- })
+ .map(|participant| participant.id)
.fetch_all(db)
.await?;
@@ -118,18 +92,10 @@ mod tests {
assert_eq!(participants.len(), 4);
- 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())
- );
+ assert!(participants.contains(&"user1".to_string()));
+ assert!(participants.contains(&"user2".to_string()));
+ assert!(participants.contains(&"user3".to_string()));
+ assert!(participants.contains(&"user4".to_string()));
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 41ef1f3c03..60f75770e8 100644
--- a/rust/cloud-storage/comms_db_client/src/preview/mod.rs
+++ b/rust/cloud-storage/comms_db_client/src/preview/mod.rs
@@ -1,6 +1,5 @@
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;
@@ -73,11 +72,7 @@ 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?
- .into_iter()
- .map(model::comms::ChannelParticipant::mirror)
- .collect();
+ let participants = get_participants(db, &row.channel_id).await?;
previews.push(RawPreviewRecord {
channel_id: row.channel_id,
@@ -123,7 +118,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, "macro|[email protected]", None).await?;
+ let previews = batch_get_channel_preview(&pool, &ids, "user1", None).await?;
assert_eq!(previews.exists.len(), 1);
assert_eq!(
previews.exists[0].channel_id,
@@ -148,7 +143,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, "macro|[email protected]", None).await?;
+ let previews = batch_get_channel_preview(&pool, &ids, "user4", None).await?;
assert_eq!(previews.exists.len(), 1);
assert!(
previews.exists[0].has_access,
@@ -163,7 +158,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, "macro|[email protected]", None).await?;
+ let previews = batch_get_channel_preview(&pool, &ids, "user1", None).await?;
assert_eq!(previews.exists.len(), 1);
assert!(
!previews.exists[0].has_access,
@@ -178,7 +173,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, "macro|[email protected]", None).await?;
+ let previews = batch_get_channel_preview(&pool, &ids, "user1", None).await?;
assert_eq!(previews.exists.len(), 0);
assert_eq!(previews.remaining.len(), 1);
Ok(())
@@ -190,7 +185,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, "macro|[email protected]", None).await?;
+ let previews = batch_get_channel_preview(&pool, &ids, "user4", None).await?;
assert_eq!(previews.exists.len(), 1);
assert!(
!previews.exists[0].has_access,
diff --git a/rust/cloud-storage/comms_service/.sqlx/query-92afd811fa4a67de45ac9a1d6d4274f01c865b9c861f2034c89f0531b88aac85.json b/rust/cloud-storage/comms_service/.sqlx/query-af221abca7c795e8be43765273da50af55ed9b7f069ee43fa7149deb8425f6bf.json
similarity index 77%
rename from rust/cloud-storage/comms_service/.sqlx/query-92afd811fa4a67de45ac9a1d6d4274f01c865b9c861f2034c89f0531b88aac85.json
rename to rust/cloud-storage/comms_service/.sqlx/query-af221abca7c795e8be43765273da50af55ed9b7f069ee43fa7149deb8425f6bf.json
index d5becc2c4f..db4be8c299 100644
--- a/rust/cloud-storage/comms_service/.sqlx/query-92afd811fa4a67de45ac9a1d6d4274f01c865b9c861f2034c89f0531b88aac85.json
+++ b/rust/cloud-storage/comms_service/.sqlx/query-af221abca7c795e8be43765273da50af55ed9b7f069ee43fa7149deb8425f6bf.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "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 ",
+ "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 ",
"describe": {
"columns": [
{
@@ -15,7 +15,7 @@
},
{
"ordinal": 2,
- "name": "channel_type: model::comms::ChannelType",
+ "name": "channel_type: ChannelType",
"type_info": {
"Custom": {
"name": "comms_channel_type",
@@ -66,5 +66,5 @@
false
]
},
- "hash": "92afd811fa4a67de45ac9a1d6d4274f01c865b9c861f2034c89f0531b88aac85"
+ "hash": "af221abca7c795e8be43765273da50af55ed9b7f069ee43fa7149deb8425f6bf"
}
diff --git a/rust/cloud-storage/comms_service/Cargo.toml b/rust/cloud-storage/comms_service/Cargo.toml
index 214356a3ba..779517552b 100644
--- a/rust/cloud-storage/comms_service/Cargo.toml
+++ b/rust/cloud-storage/comms_service/Cargo.toml
@@ -33,11 +33,9 @@ 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 }
@@ -57,7 +55,6 @@ 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" }
@@ -76,6 +73,7 @@ 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
new file mode 100644
index 0000000000..99fa8f47a3
--- /dev/null
+++ b/rust/cloud-storage/comms_service/src/api/activity/get_activity.rs
@@ -0,0 +1,44 @@
+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 98719af1f4..0f0d4847c9 100644
--- a/rust/cloud-storage/comms_service/src/api/activity/mod.rs
+++ b/rust/cloud-storage/comms_service/src/api/activity/mod.rs
@@ -1 +1,15 @@
+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 5e0fa87c6d..2dad04e578 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, ChannelImpl};
+use crate::api::context::AppState;
use crate::api::extractors::{
ChannelAdmin, ChannelId, ChannelName, ChannelParticipants, ChannelTypeExtractor,
};
@@ -9,12 +9,11 @@ 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;
@@ -41,11 +40,10 @@ 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<ChannelImpl>>,
+ Cached(ChannelName(channel_name)): Cached<ChannelName>,
Cached(ChannelTypeExtractor(channel_type)): Cached<ChannelTypeExtractor>,
Cached(ChannelParticipants(channel_participants)): Cached<ChannelParticipants>,
Cached(ChannelId(channel_id)): Cached<ChannelId>,
@@ -67,7 +65,7 @@ pub async fn handler(
AddParticipantOptions {
channel_id: &channel_id,
user_id: participant.as_str(),
- participant_role: Some(model::comms::ParticipantRole::Member),
+ participant_role: Some(ParticipantRole::Member),
},
)
.await
@@ -100,7 +98,7 @@ pub async fn handler(
// There should always be participants, but better safe than sorry
if !participants.is_empty() {
let metadata = CommonChannelMetadata {
- channel_type: model_notifications::ChannelType::mirror(channel_type),
+ channel_type,
channel_name: channel_name.clone(),
};
comms_notification::dispatch_notifications_for_invite(
@@ -118,7 +116,7 @@ pub async fn handler(
})
.ok();
- if matches!(channel_type, ChannelType::Private) && !channel_participants.is_empty() {
+ if 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 2e6c766ded..599e202209 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, ChannelImpl},
+ context::AppState,
extractors::{ChannelId, ChannelMember, ChannelName, ChannelParticipants, ParticipantAccess},
};
use anyhow::Result;
@@ -17,7 +17,6 @@ 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};
@@ -72,7 +71,7 @@ pub async fn get_channel_handler(
ChannelId(channel_id): ChannelId,
ChannelParticipants(participants): ChannelParticipants,
ChannelMember(channel_member): ChannelMember,
- ChannelName(channel_name, ..): ChannelName<ChannelImpl>,
+ ChannelName(channel_name): ChannelName,
Cached(access): Cached<ParticipantAccess>,
Query(query): Query<GetChannelQuery>,
) -> Result<(StatusCode, Json<GetChannelResponse>), (StatusCode, String)> {
@@ -104,7 +103,7 @@ pub async fn get_channel_handler(
StatusCode::OK,
Json(GetChannelResponse {
channel,
- participants: <Vec<model::comms::ChannelParticipant>>::mirror(participants),
+ 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 fc947ada79..059be9c72a 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,6 +1,9 @@
-use crate::api::{
- context::AppState,
- extractors::{ChannelId, ChannelMember},
+use crate::{
+ api::{
+ context::AppState,
+ extractors::{ChannelId, ChannelMember},
+ },
+ utils::channel_name::resolve_channel_name,
};
use anyhow::Result;
use axum::{
@@ -9,37 +12,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;
-use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
-use models_comms::channel::OrganizationId;
+#[allow(unused_imports)]
+use model::comms::{Channel, ChannelType};
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: model::comms::ChannelType,
+ pub channel_type: ChannelType,
}
#[derive(Deserialize, Debug)]
pub struct UserIdQuery {
- pub user_id: MacroUserIdStr<'static>,
+ pub user_id: Option<String>,
}
#[tracing::instrument(skip(db))]
pub async fn get_channel_name_and_type(
db: &Pool<Postgres>,
- channel_id: &models_comms::channel::ChannelId,
- user_id: MacroUserIdStr<'_>,
-) -> Result<(String, model::comms::ChannelType)> {
- let channel = sqlx::query!(
+ channel_id: &Uuid,
+ user_id: &str,
+) -> Result<(String, ChannelType)> {
+ let channel_row = sqlx::query!(
r#"
SELECT
id,
name,
- channel_type AS "channel_type: model::comms::ChannelType",
+ channel_type AS "channel_type: ChannelType",
org_id,
created_at,
updated_at,
@@ -47,42 +50,30 @@ pub async fn get_channel_name_and_type(
FROM comms_channels
WHERE id = $1
"#,
- channel_id.0
+ channel_id
)
- .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 participants = get_participants(db, &channel_id.0).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 channel_name = resolve_channel_name(
- &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.channel_type,
channel.name.as_deref(),
&participants,
channel_id,
user_id,
- &Default::default(),
+ None,
);
Ok((channel_name, channel.channel_type))
@@ -90,26 +81,22 @@ 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,
- &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 (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 response = ChannelMetadataResponse {
channel_name,
@@ -123,20 +110,21 @@ pub async fn handler_external(
#[tracing::instrument(skip(ctx))]
pub async fn handler_internal(
State(ctx): State<AppState>,
- Path(channel_id): Path<models_comms::channel::ChannelId>,
+ Path(channel_id): Path<Uuid>,
Query(query): Query<UserIdQuery>,
) -> Result<Response, 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 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 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
new file mode 100644
index 0000000000..4b2b851e72
--- /dev/null
+++ b/rust/cloud-storage/comms_service/src/api/channels/get_channels.rs
@@ -0,0 +1,141 @@
+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 8a9e1e4b6e..fb0af9ea7e 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::ParticipantRole;
+use model::comms::{ChannelType, 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 models_comms::channel::ChannelType::DirectMessage = channel_type {
+ if let 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 11852ccdec..ffe50121a8 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,6 +8,7 @@ use axum_extra::extract::Cached;
use comms_db_client::participants::remove_participant::{
RemoveParticipantOptions, remove_participant,
};
+use model::comms::ChannelType;
#[utoipa::path(
post,
@@ -34,15 +35,14 @@ pub async fn leave_channel_handler(
Cached(ChannelMember(channel_member)): Cached<ChannelMember>,
) -> Result<StatusCode, (StatusCode, String)> {
match (channel_type, participants.len()) {
- (models_comms::channel::ChannelType::Organization, _) => {
+ (ChannelType::Organization, _) => {
tracing::warn!("user tried to leave organization channel");
return Err((
StatusCode::BAD_REQUEST,
"cannot leave organization channel".to_string(),
));
}
- (models_comms::channel::ChannelType::Private, 2)
- | (models_comms::channel::ChannelType::DirectMessage, _) => {
+ (ChannelType::Private, 2) | (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 62df8975cf..761e6c5126 100644
--- a/rust/cloud-storage/comms_service/src/api/channels/mod.rs
+++ b/rust/cloud-storage/comms_service/src/api/channels/mod.rs
@@ -11,6 +11,7 @@ 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;
@@ -30,6 +31,10 @@ 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 35cd46603e..71169081b8 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,6 +6,7 @@ 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;
@@ -30,11 +31,7 @@ pub async fn patch_channel_handler(
Cached(ChannelTypeExtractor(channel_type)): Cached<ChannelTypeExtractor>,
Json(req): Json<PatchChannelOptions>,
) -> Result<(StatusCode, String), (StatusCode, String)> {
- if matches!(
- channel_type,
- models_comms::channel::ChannelType::DirectMessage
- ) && req.channel_name.is_some()
- {
+ if channel_type == 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 c4795670fb..99b32cddf6 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,7 +16,6 @@ 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;
@@ -80,7 +79,7 @@ pub async fn patch_message_handler(
})?;
let participants = participants;
- let participants: Vec<_> = if let Some(thread_id) = message.thread_id.as_ref() {
+ let participants: Vec<String> = 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,
@@ -94,7 +93,7 @@ pub async fn patch_message_handler(
)
})?
} else {
- participants.iter().map(|p| p.user_id.copied()).collect()
+ participants.iter().map(|p| p.user_id.clone()).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 46a9077182..9457ae8525 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,4 +1,3 @@
-use crate::api::context::ChannelImpl;
use crate::api::{context::AppState, extractors::ChannelName};
use crate::notification as comms_notification;
use crate::{
@@ -22,8 +21,6 @@ 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;
@@ -65,7 +62,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<ChannelImpl>>,
+ Cached(ChannelName(channel_name)): Cached<ChannelName>,
Cached(ChannelId(channel_id)): Cached<ChannelId>,
Cached(ChannelTypeExtractor(channel_type)): Cached<ChannelTypeExtractor>,
extract::Json(req): extract::Json<PostMessageRequest>,
@@ -208,9 +205,10 @@ pub async fn post_message_handler(
// TODO: -- end
- let participants: Vec<_> = channel_participants
+ let participants: Vec<String> = channel_participants
+ .clone()
.iter()
- .map(|p| p.user_id.copied())
+ .map(|p| p.user_id.clone())
.collect();
let start_time = Instant::now();
@@ -282,10 +280,10 @@ pub async fn post_message_handler(
&ctx,
channel_id,
CommonChannelMetadata {
- channel_type: model_notifications::ChannelType::mirror(channel_type),
+ channel_type,
channel_name: channel_name.clone(),
},
- <Vec<model::comms::ChannelParticipant>>::mirror(channel_participants),
+ channel_participants.clone(),
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 40158af5c6..edb7d99d8e 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,6 +7,7 @@ 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};
@@ -41,7 +42,7 @@ pub async fn handler(
Cached(ChannelId(channel_id)): Cached<ChannelId>,
req: Json<RemoveParticipantsRequest>,
) -> Result<StatusCode, (StatusCode, String)> {
- if let models_comms::channel::ChannelType::DirectMessage = channel_type {
+ if let 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 f6adeacd90..c44df48529 100644
--- a/rust/cloud-storage/comms_service/src/api/context.rs
+++ b/rust/cloud-storage/comms_service/src/api/context.rs
@@ -1,9 +1,4 @@
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;
@@ -31,7 +26,4 @@ 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
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/rust/cloud-storage/comms_service/src/api/extractors.rs b/rust/cloud-storage/comms_service/src/api/extractors.rs
index ff83438aef..f088aa4742 100644
--- a/rust/cloud-storage/comms_service/src/api/extractors.rs
+++ b/rust/cloud-storage/comms_service/src/api/extractors.rs
@@ -1,51 +1,39 @@
+use authentication_service_client::AuthServiceClient;
use axum::{
- RequestPartsExt, async_trait,
+ Extension, 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::ParticipantRole,
- user::{UserContext, axum_extractor::MacroUserExtractor},
+ comms::{ChannelParticipant, ParticipantRole},
+ user::UserContext,
};
-use models_comms::channel::ChannelType;
+use models_comms::ChannelType;
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
-use std::{
- collections::{HashMap, HashSet},
- marker::PhantomData,
-};
+use std::{collections::HashMap, sync::Arc};
use utoipa::ToSchema;
use uuid::Uuid;
-#[derive(Serialize, Deserialize, Debug)]
-pub struct ChannelName<T>(pub String, pub PhantomData<T>);
+use crate::utils::{channel_name::resolve_channel_name, user_name::generate_name_lookup};
-impl<T> Clone for ChannelName<T> {
- fn clone(&self) -> Self {
- Self(self.0.clone(), PhantomData)
- }
-}
+#[derive(Serialize, Deserialize, Debug, Clone)]
+pub struct ChannelName(pub String);
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ChannelId(pub Uuid);
-#[derive(Deserialize, Clone, Debug)]
-pub struct ChannelParticipants(pub Vec<models_comms::channel::ChannelParticipant>);
+#[derive(Serialize, Deserialize, Clone, Debug)]
+pub struct ChannelParticipants(pub Vec<ChannelParticipant>);
-#[derive(Debug, Clone, Copy)]
+#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ChannelTypeExtractor(pub ChannelType);
#[derive(Serialize, Deserialize, Clone, Debug, ToSchema)]
@@ -73,6 +61,13 @@ 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,
@@ -159,59 +154,47 @@ where
}
#[async_trait]
-impl<S, U> FromRequestParts<S> for ChannelName<U>
+impl<S> FromRequestParts<S> for ChannelName
where
S: Send + Sync,
PgPool: FromRef<S>,
- CommsRouterState<U>: FromRef<S>,
- U: ChannelsService,
+ Arc<AuthServiceClient>: FromRef<S>,
{
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 MacroUserExtractor { macro_user_id, .. } =
- parts.extract().await.map_err(IntoResponse::into_response)?;
+ let UserContext { user_id, .. } = extract_user_context(parts).await?;
let ChannelInfoExtractor(ChannelInfo { name, .. }) =
extract_cached::<ChannelInfoExtractor, _>(parts, state).await?;
let user_ids = participants
.iter()
- .map(|p| p.user_id.copied())
- .collect::<HashSet<_>>();
+ .map(|p| p.user_id.clone())
+ .collect::<Vec<String>>();
- let service = <CommsRouterState<U>>::from_ref(state);
- let name_lookup = service
- .inner
+ let name_lookup = auth_service_client
.get_names(user_ids)
.await
.ok()
- .map(|names| {
- names
- .into_iter()
- .filter_map(|n| {
- let display = n.display_name()?;
- Some((n.id, display))
- })
- .collect::<HashMap<_, _>>()
- })
- .unwrap_or_default();
+ .map(generate_name_lookup);
let channel_name = resolve_channel_name(
&channel_type,
name.as_deref(),
&participants,
- &models_comms::channel::ChannelId(channel_id),
- macro_user_id,
- &name_lookup,
+ &channel_id,
+ &user_id,
+ name_lookup.as_ref(),
);
- return Ok(ChannelName(channel_name, PhantomData));
+ return Ok(ChannelName(channel_name));
}
}
@@ -240,42 +223,32 @@ where
.into_response()
})?;
- 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
- }
- }))
+ Ok(ChannelTypeExtractor(info.channel_type))
}
}
-#[derive(Clone, Debug)]
+#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct UserContextWithRole {
pub context: UserContext,
- pub user_id: MacroUserIdStr<'static>,
- pub role: Option<models_comms::channel::ParticipantRole>,
+ pub role: Option<ParticipantRole>,
}
pub async fn get_user_role(
user_context: &UserContext,
info: &ChannelInfo,
- participants: &[models_comms::channel::ChannelParticipant],
-) -> Option<models_comms::channel::ParticipantRole> {
+ participants: &[ChannelParticipant],
+) -> Option<ParticipantRole> {
let user_participant = participants
.iter()
- .find(|p| p.user_id.as_ref() == user_context.user_id);
+ .find(|p| p.user_id == user_context.user_id);
match info.channel_type {
- model::comms::ChannelType::Public => Some(
+ ChannelType::Public => Some(
user_participant
.map(|p| p.role)
- .unwrap_or(models_comms::channel::ParticipantRole::Member),
+ .unwrap_or(ParticipantRole::Member),
),
- model::comms::ChannelType::Organization => {
+ 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))
@@ -285,7 +258,7 @@ pub async fn get_user_role(
Some(
user_participant
.map(|p| p.role)
- .unwrap_or(models_comms::channel::ParticipantRole::Member),
+ .unwrap_or(ParticipantRole::Member),
)
} else {
user_participant.map(|p| p.role)
@@ -310,11 +283,7 @@ where
let Cached(ChannelParticipants(participants)) =
Cached::<ChannelParticipants>::from_request_parts(parts, state).await?;
- let MacroUserExtractor {
- macro_user_id,
- user_context,
- ..
- } = parts.extract().await.map_err(IntoResponse::into_response)?;
+ let user_context = extract_user_context(parts).await?;
let info = get_channel_info(&PgPool::from_ref(state), &channel_id)
.await
.map_err(|err| {
@@ -328,13 +297,12 @@ where
let role = get_user_role(&user_context, &info, &participants).await;
Ok(UserContextWithRole {
context: user_context,
- user_id: macro_user_id,
role,
})
}
}
-#[derive(Clone, Debug)]
+#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ChannelMember(pub UserContextWithRole);
#[async_trait]
@@ -355,7 +323,7 @@ where
}
}
-#[derive(Clone, Debug)]
+#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ChannelOwner(pub UserContextWithRole);
#[async_trait]
@@ -370,15 +338,13 @@ where
let user_context_with_role = UserContextWithRole::from_request_parts(parts, state).await?;
match user_context_with_role.role {
- Some(models_comms::channel::ParticipantRole::Owner) => {
- Ok(ChannelOwner(user_context_with_role))
- }
+ Some(ParticipantRole::Owner) => Ok(ChannelOwner(user_context_with_role)),
_ => Err(unauthorized("user is not authorized to view this channel")),
}
}
}
-#[derive(Clone, Debug)]
+#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ChannelAdmin(pub UserContextWithRole);
#[async_trait]
@@ -393,10 +359,9 @@ where
let user_context_with_role = UserContextWithRole::from_request_parts(parts, state).await?;
match user_context_with_role.role {
- Some(
- models_comms::channel::ParticipantRole::Owner
- | models_comms::channel::ParticipantRole::Admin,
- ) => Ok(ChannelAdmin(user_context_with_role)),
+ Some(ParticipantRole::Owner | ParticipantRole::Admin) => {
+ Ok(ChannelAdmin(user_context_with_role))
+ }
_ => Err(unauthorized("user is not authorized to view this channel")),
}
}
@@ -450,8 +415,7 @@ where
}
}
-#[derive(Clone, Debug)]
-#[expect(dead_code)]
+#[derive(Serialize, Deserialize, Clone, Debug)]
pub enum MessageSenderOrAdmin {
MessageSender(MessageSender),
ChannelAdmin(ChannelAdmin),
@@ -488,9 +452,7 @@ where
let user_context_with_role = extract_cached::<UserContextWithRole, _>(parts, state).await?;
match user_context_with_role.role {
- Some(role) => Ok(ParticipantAccess::Access {
- role: ParticipantRole::mirror(role),
- }),
+ Some(role) => Ok(ParticipantAccess::Access { 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 9fc08f3aa2..55c708ab38 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.0,
+ channel_id: &channel.id,
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 40ebf7a806..82ec53499f 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,7 +12,6 @@ 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};
@@ -31,13 +30,17 @@ 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");
}
}
@@ -51,18 +54,17 @@ pub async fn handler(
#[tracing::instrument(skip(ctx))]
async fn create_welcome_message(
ctx: &AppState,
- welcome_user_id: MacroUserIdStr<'_>,
- to_user_id: MacroUserIdStr<'_>,
+ welcome_user_id: &str,
+ to_user_id: &str,
) -> anyhow::Result<()> {
let content = WELCOME_MESSAGE.to_string();
let sleep_time = SLEEP_TIME_SECONDS;
- let participants: Vec<_> = vec![welcome_user_id.copied(), to_user_id.copied()];
+ let participants: Vec<String> = vec![welcome_user_id.to_string(), to_user_id.to_string()];
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.as_ref(), to_user_id.as_ref()).await?;
+ let maybe_dm = get_dm::maybe_get_dm(&ctx.db, welcome_user_id, to_user_id).await?;
let (channel_id, action) = match maybe_dm {
Some(private_id) => (private_id, GetOrCreateAction::Get),
@@ -74,7 +76,7 @@ async fn create_welcome_message(
owner_id: welcome_user_id.to_string(),
org_id: None,
channel_type: ChannelType::DirectMessage,
- participants: participants.iter().map(|x| x.to_string()).collect(),
+ participants: participants.clone(),
},
)
.await?;
@@ -115,7 +117,7 @@ async fn create_welcome_message(
upsert_activity(
&ctx.db,
- welcome_user_id.as_ref(),
+ welcome_user_id,
&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 6d4a9154bb..9f37d2c954 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,7 +3,6 @@ use axum::{
extract::{Path, State},
response::{IntoResponse, Json, Response},
};
-use doppleganger::Mirror;
use reqwest::StatusCode;
use uuid::Uuid;
@@ -31,11 +30,5 @@ pub async fn handler(
.into_response()
})?;
- Ok((
- StatusCode::OK,
- Json(<Vec<model::comms::ChannelParticipant>>::mirror(
- participants,
- )),
- )
- .into_response())
+ Ok((StatusCode::OK, Json(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 b4cf90d837..8799134122 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.0,
+ channel_id: &channel.id,
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 5194003a9c..61426f51d4 100644
--- a/rust/cloud-storage/comms_service/src/api/mod.rs
+++ b/rust/cloud-storage/comms_service/src/api/mod.rs
@@ -1,9 +1,5 @@
-use crate::api::{activity::post_activity, context::AppState};
-use axum::{
- Router,
- middleware::from_fn_with_state,
- routing::{IntoMakeService, post},
-};
+use crate::api::context::AppState;
+use axum::{Router, middleware::from_fn_with_state, routing::IntoMakeService};
use tower_http::trace::TraceLayer;
use utoipa::OpenApi;
use utoipa_swagger_ui::SwaggerUi;
@@ -26,8 +22,7 @@ pub fn service(app_state: AppState) -> Service {
let cors = macro_cors::cors_layer();
let app = Router::new()
- .merge(comms::inbound::comms_router(app_state.comms_state.clone()))
- .route("/activity", post(post_activity::post_activity_handler))
+ .nest("/activity", activity::router())
.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 9144211628..487f90e4a0 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::axum_extractor::MacroUserExtractor;
+use model::user::UserContext;
use reqwest::StatusCode;
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
@@ -36,17 +36,13 @@ pub struct GetBatchChannelPreviewResponse {
)]
pub async fn handler(
State(db): State<PgPool>,
- MacroUserExtractor {
- macro_user_id,
- user_context,
- ..
- }: MacroUserExtractor,
+ user_context: Extension<UserContext>,
Json(req): Json<GetBatchChannelPreviewRequest>,
) -> Result<(StatusCode, Json<GetBatchChannelPreviewResponse>), Response> {
let raw_previews = comms_db_client::preview::batch_get_channel_preview(
&db,
&req.channel_ids,
- macro_user_id.as_ref(),
+ &user_context.user_id,
user_context.organization_id.map(|org_id| org_id as i64),
)
.await
@@ -61,7 +57,7 @@ pub async fn handler(
// TODO: if previews include direct messages or private group chats, generate lookup table
// somehow
- let previews = resolve_previews(macro_user_id, raw_previews, &Default::default());
+ let previews = resolve_previews(&user_context, raw_previews, None);
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 e117002e64..2f05c514ec 100644
--- a/rust/cloud-storage/comms_service/src/api/swagger.rs
+++ b/rust/cloud-storage/comms_service/src/api/swagger.rs
@@ -1,10 +1,12 @@
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},
@@ -21,14 +23,13 @@ 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, ChannelWithParticipants,
+ Channel, ChannelParticipant, ChannelType, ChannelWithLatest, ChannelWithParticipants,
GetMessageWithContextResponse, GetOrCreateAction, LatestMessage, ParticipantRole,
};
@@ -37,9 +38,10 @@ use model::version::CommunicationServiceApiVersion;
use utoipa::OpenApi;
use super::channels::{
- 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,
+ 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,
};
use super::attachments::references;
@@ -50,7 +52,7 @@ use comms_db_client::attachments::get_attachment_references::{
use super::channels::get_mentions::GetMentionsResponse;
-use super::activity::post_activity;
+use super::activity::{get_activity, post_activity};
use super::mentions::{
create_mention::__path_create_mention_handler, delete_mention::__path_delete_mention_handler,
};
@@ -64,13 +66,13 @@ use super::preview::get_batch_preview;
paths(
create_channel::create_channel_handler,
get_channel::get_channel_handler,
- comms::inbound::get_channels_handler,
+ get_channels::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,
- comms::inbound::get_activity_handler,
+ get_activity::get_activity_handler,
post_activity::post_activity_handler,
join_channel::join_channel_handler,
leave_channel::leave_channel_handler,
@@ -93,7 +95,7 @@ use super::preview::get_batch_preview;
CreateChannelRequest,
CreateChannelResponse,
GetChannelResponse,
- ApiChannelWithLatest,
+ GetChannelsResponse,
PostMessageRequest,
PostMessageResponse,
PostTypingRequest,
@@ -105,6 +107,7 @@ use super::preview::get_batch_preview;
PatchMessageRequest,
DeleteMessageParams,
PostActivityRequest,
+ GetActivityResponse,
AddParticipantsRequest,
RemoveParticipantsRequest,
@@ -116,7 +119,6 @@ use super::preview::get_batch_preview;
Reaction,
CountedReaction,
Activity,
- ApiActivity,
ActivityType,
NewAttachment,
ParticipantAccess,
@@ -146,6 +148,7 @@ 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 0661b0bdc0..b30004375a 100644
--- a/rust/cloud-storage/comms_service/src/config.rs
+++ b/rust/cloud-storage/comms_service/src/config.rs
@@ -1,7 +1,6 @@
use anyhow::Context;
pub use macro_env::Environment;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
-use reqwest::Url;
/// The configuration parameters for the application.
///
@@ -32,7 +31,7 @@ pub struct Config {
pub contacts_queue: String,
/// Auth service client
- pub auth_service_url: Url,
+ pub auth_service_url: String,
/// Auth service secret key, used for internal access
pub auth_service_secret_key: String,
@@ -65,9 +64,7 @@ impl Config {
std::env::var("CONTACTS_QUEUE").context("CONTACTS_QUEUE must be provided")?;
let auth_service_url = std::env::var("AUTHENTICATION_SERVICE_URL")
- .map(|s| Url::parse(&s))
- .context("AUTHENTICATION_SERVICE_URL must be provided")?
- .context("AUTHENTICATION_SERVICE_URL must be a valid url")?;
+ .context("AUTHENTICATION_SERVICE_URL must be provided")?;
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 5822c30557..468ca26422 100644
--- a/rust/cloud-storage/comms_service/src/main.rs
+++ b/rust/cloud-storage/comms_service/src/main.rs
@@ -1,10 +1,5 @@
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;
@@ -110,8 +105,8 @@ async fn main() -> anyhow::Result<()> {
};
let auth_service_client = authentication_service_client::AuthServiceClient::new(
- auth_service_secret_key.clone(),
- config.auth_service_url.to_string(),
+ auth_service_secret_key,
+ config.auth_service_url.clone(),
);
let permissions_token_secret = secretsmanager_client
@@ -137,8 +132,6 @@ 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(
@@ -152,12 +145,7 @@ async fn main() -> anyhow::Result<()> {
auth_service_client: Arc::new(auth_service_client),
connection_gateway_client: Arc::new(connection_gateway_client),
permissions_token_secret,
- 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,
+ frecency_storage: FrecencyPgStorage::new(macro_db),
});
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 1443c4546b..9e59c1790b 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 [MacroUserIdStr<'static>],
+ thread_participants: &'a [String],
}
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_ref()),
+ self.participants.iter().map(|p| p.user_id.as_str()),
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_ref()),
+ self.participants.iter().map(|p| p.user_id.as_str()),
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_ref()),
+ self.thread_participants.iter().map(|p| p.as_str()),
sender_and_mentions,
),
NotificationEvent::ChannelMessageReply(ChannelReplyMetadata {
@@ -285,15 +285,16 @@ pub async fn dispatch_notifications_for_message(
#[cfg(test)]
mod tests {
use super::*;
- use model::comms::{ChannelId, ParticipantRole};
+ use model::comms::ParticipantRole;
use model_notifications::NotificationEventType;
+ use models_comms::ChannelType;
use std::collections::HashMap;
use uuid::Uuid;
- fn participant(user_id: MacroUserIdStr<'static>, channel_id: Uuid) -> ChannelParticipant {
+ fn participant(user_id: &str, channel_id: Uuid) -> ChannelParticipant {
ChannelParticipant {
- user_id,
- channel_id: ChannelId(channel_id),
+ user_id: user_id.to_string(),
+ channel_id,
role: ParticipantRole::Member,
left_at: None,
joined_at: chrono::Utc::now(),
@@ -331,7 +332,7 @@ mod tests {
fn private_metadata() -> CommonChannelMetadata {
CommonChannelMetadata {
- channel_type: model_notifications::ChannelType::Private,
+ channel_type: ChannelType::Private,
channel_name: "group".to_string(),
}
}
@@ -375,18 +376,9 @@ mod tests {
fn sender_excluded_from_all_recipients() {
let channel_id = Uuid::new_v4();
let participants = vec![
- 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("macro|[email protected]", channel_id),
+ participant("macro|[email protected]", channel_id),
+ participant("macro|[email protected]", channel_id),
];
let msg = message(
channel_id,
@@ -425,14 +417,8 @@ mod tests {
fn first_message_sends_invite_notification() {
let channel_id = Uuid::new_v4();
let participants = vec![
- participant(
- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
- channel_id,
- ),
- participant(
- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
- channel_id,
- ),
+ participant("sender", channel_id),
+ participant("alice", channel_id),
];
let msg = message(
channel_id,
@@ -468,14 +454,8 @@ mod tests {
fn subsequent_messages_send_message_send_notification() {
let channel_id = Uuid::new_v4();
let participants = vec![
- participant(
- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
- channel_id,
- ),
- participant(
- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
- channel_id,
- ),
+ participant("sender", channel_id),
+ participant("alice", channel_id),
];
let msg = message(
channel_id,
@@ -511,18 +491,9 @@ mod tests {
fn mentioned_users_get_mention_not_message_send() {
let channel_id = Uuid::new_v4();
let participants = vec![
- 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("sender", channel_id),
+ participant("alice", channel_id),
+ participant("bob", channel_id),
];
let msg = message(
channel_id,
@@ -532,7 +503,7 @@ mod tests {
None,
);
let metadata = private_metadata();
- let user_mentions = vec!["macro|[email protected]".to_string()];
+ let user_mentions = vec!["alice".to_string()];
let event = ChannelMessageEvent {
channel_id: &channel_id,
@@ -554,8 +525,7 @@ mod tests {
.expect("should have mention notification");
let mention_recipients = mention.recipient_ids.as_ref().unwrap();
-
- assert!(mention_recipients.contains(&"macro|[email protected]".to_string()));
+ assert!(mention_recipients.contains(&"alice".to_string()));
let send = notifications
.iter()
@@ -568,8 +538,8 @@ mod tests {
.expect("should have message send notification");
let send_recipients = send.recipient_ids.as_ref().unwrap();
- assert!(!send_recipients.contains(&"macro|[email protected]".to_string()));
- assert!(send_recipients.contains(&"macro|[email protected]".to_string()));
+ assert!(!send_recipients.contains(&"alice".to_string()));
+ assert!(send_recipients.contains(&"bob".to_string()));
}
#[test]
@@ -577,22 +547,10 @@ mod tests {
let channel_id = Uuid::new_v4();
let thread_id = Uuid::new_v4();
let participants = vec![
- 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,
- ),
+ participant("macro|[email protected]", channel_id),
+ participant("macro|[email protected]", channel_id),
+ participant("macro|[email protected]", channel_id),
+ participant("macro|[email protected]", channel_id),
];
let msg = message(
channel_id,
@@ -604,10 +562,10 @@ mod tests {
let metadata = private_metadata();
let user_mentions = vec!["macro|[email protected]".to_string()];
let thread_participants = vec![
- 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(),
+ "macro|[email protected]".to_string(),
+ "macro|[email protected]".to_string(),
+ "macro|[email protected]".to_string(),
+ "macro|[email protected]".to_string(),
];
let event = ChannelMessageEvent {
@@ -645,18 +603,9 @@ mod tests {
fn document_mentions_exclude_sender() {
let channel_id = Uuid::new_v4();
let participants = vec![
- 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("macro|[email protected]", channel_id),
+ participant("macro|[email protected]", channel_id),
+ participant("macro|[email protected]", channel_id),
];
let msg = message(
channel_id,
@@ -703,14 +652,8 @@ mod tests {
let channel_id = Uuid::new_v4();
let thread_id = Uuid::new_v4();
let participants = vec![
- participant(
- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
- channel_id,
- ),
- participant(
- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
- channel_id,
- ),
+ participant("sender", channel_id),
+ participant("alice", 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 786e1c6ba2..3660b358e4 100644
--- a/rust/cloud-storage/comms_service/src/service/sender/notify.rs
+++ b/rust/cloud-storage/comms_service/src/service/sender/notify.rs
@@ -1,7 +1,6 @@
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;
@@ -12,7 +11,7 @@ use crate::api::context::AppState;
pub async fn notify_message(
ctx: &AppState,
message: Message,
- participants: &[MacroUserIdStr<'_>],
+ participants: &[String],
) -> Result<()> {
if participants.is_empty() {
return Ok(());
@@ -23,7 +22,7 @@ pub async fn notify_message(
serde_json::to_value(message)?,
participants
.iter()
- .map(|p| EntityType::User.with_entity_str(p.as_ref()))
+ .map(|p| EntityType::User.with_entity_str(p.as_str()))
.collect(),
)
.await?;
@@ -48,7 +47,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.as_ref()))
+ .map(|p| EntityType::User.with_entity_str(&p.user_id))
.collect(),
)
.await?;
@@ -72,7 +71,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.as_ref()))
+ .map(|p| EntityType::User.with_entity_str(&p.user_id))
.collect(),
)
.await?;
@@ -96,7 +95,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.as_ref()))
+ .map(|p| EntityType::User.with_entity_str(&p.user_id))
.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
new file mode 100644
index 0000000000..7dae1182b8
--- /dev/null
+++ b/rust/cloud-storage/comms_service/src/utils/channel_name.rs
@@ -0,0 +1,244 @@
+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 c076fb97ed..fcc1c1c455 100644
--- a/rust/cloud-storage/comms_service/src/utils/mod.rs
+++ b/rust/cloud-storage/comms_service/src/utils/mod.rs
@@ -1 +1,3 @@
+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 7f892792e3..76e5df8175 100644
--- a/rust/cloud-storage/comms_service/src/utils/previews.rs
+++ b/rust/cloud-storage/comms_service/src/utils/previews.rs
@@ -1,15 +1,14 @@
-use comms::domain::models::channel_name::resolve_channel_name;
use comms_db_client::model::{ChannelPreview, ChannelPreviewData, WithChannelId};
use comms_db_client::preview::Previews;
-use macro_user_id::cowlike::CowLike;
-use macro_user_id::user_id::MacroUserIdStr;
-use models_comms::channel::ChannelId;
+use model::user::UserContext;
use std::collections::HashMap;
+use crate::utils::channel_name::resolve_channel_name;
+
pub fn resolve_previews(
- context: MacroUserIdStr<'_>,
+ context: &UserContext,
raw_previews: Previews,
- name_lookup: &HashMap<MacroUserIdStr<'static>, String>,
+ name_lookup: Option<&HashMap<String, String>>,
) -> Vec<ChannelPreview> {
let mut previews = vec![];
@@ -27,45 +26,12 @@ 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(
- &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_type,
preview.channel_name.as_deref(),
- &participants,
- &ChannelId(preview.channel_id),
- context.copied(),
+ &preview.participants,
+ &preview.channel_id,
+ &context.user_id,
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
new file mode 100644
index 0000000000..39b185ba95
--- /dev/null
+++ b/rust/cloud-storage/comms_service/src/utils/user_name.rs
@@ -0,0 +1,89 @@
+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 86b7e8fe49..a630f26964 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 b859bbac0f..0bca689304 100644
--- a/rust/cloud-storage/document_cognition_service/Cargo.toml
+++ b/rust/cloud-storage/document_cognition_service/Cargo.toml
@@ -36,7 +36,6 @@ 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 }
@@ -57,12 +56,10 @@ 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
@@ -98,6 +95,8 @@ 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 d6ffda31a6..29e336d998 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,7 +4,6 @@ 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,
};
@@ -63,7 +62,7 @@ pub async fn get_chat(
.await
.map(|channel_metadata| AttachmentMetadata::Channel {
channel_name: channel_metadata.name,
- channel_type: model::comms::ChannelType::mirror(channel_metadata.channel_type),
+ channel_type: 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 b2ef2bf2fe..aa8ce86ee4 100644
--- a/rust/cloud-storage/document_storage_service/Cargo.toml
+++ b/rust/cloud-storage/document_storage_service/Cargo.toml
@@ -40,7 +40,6 @@ 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 85e591a89d..8086942469 100644
--- a/rust/cloud-storage/document_storage_service/src/api/context.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs
@@ -1,9 +1,5 @@
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};
@@ -34,7 +30,6 @@ 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 65ebeee405..c5148a53da 100644
--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs
@@ -109,6 +109,7 @@ 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;
@@ -289,6 +290,7 @@ 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 4567beda0c..738bab3fea 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.as_ref() != user_id {
+ if participant.user_id != user_id {
generated_items.push(UserItemAccess {
id: macro_uuid::generate_uuid_v7(),
- user_id: participant.user_id.to_string(),
+ user_id: participant.user_id,
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 263801ce4d..ed91744595 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 {
+ if participant.user_id != user_id.as_ref() {
generated_items.push(UserItemAccess {
id: macro_uuid::generate_uuid_v7(),
- user_id: participant.user_id.to_string(),
+ user_id: participant.user_id,
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 2c958c9655..118f0a64eb 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.as_ref() != user_id {
+ if participant.user_id != user_id {
generated_items.push(UserItemAccess {
id: macro_uuid::generate_uuid_v7(),
- user_id: participant.user_id.to_string(),
+ user_id: participant.user_id,
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 5c6260372e..cccffa5dd4 100644
--- a/rust/cloud-storage/document_storage_service/src/config.rs
+++ b/rust/cloud-storage/document_storage_service/src/config.rs
@@ -48,8 +48,6 @@ 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 81ee2d90eb..e63f674cad 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -4,10 +4,6 @@ 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;
@@ -189,19 +185,6 @@ 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());
@@ -226,19 +209,6 @@ 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 0ef73efaa0..8707e8934f 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', 'macro|[email protected]', 'test-item', 'document', 'owner', NOW());
+VALUES ('00000000-0000-0000-0000-000000000001', 'test-user', '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', '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());
+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());
-- 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', '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());
+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
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 c16ab2fcde..0fd58c9a32 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,5 +1,4 @@
use anyhow::Context;
-use macro_user_id::user_id::MacroUserIdStr;
use sqlx::{Postgres, Transaction};
/// Deletes all user access records for a specific item
@@ -86,7 +85,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: &[MacroUserIdStr<'_>],
+ user_ids: &[String],
item_id: &str,
item_type: &str,
granted_from_channel_id: uuid::Uuid,
@@ -95,8 +94,6 @@ 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"
@@ -105,7 +102,7 @@ pub async fn delete_user_item_access_by_users_and_channel(
AND "item_type" = $3
AND "granted_from_channel_id" = $4
"#,
- macro_ids.as_slice(),
+ user_ids,
item_id,
item_type,
granted_from_channel_id,
@@ -185,7 +182,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 = "macro|[email protected]";
+ let user_id = "test-user";
let item_id = "test-item";
let item_type = "document";
@@ -311,10 +308,7 @@ 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![
- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
- ];
+ let user_ids = vec!["user1".to_string(), "user2".to_string()];
// First ensure test data exists
for user_id in &user_ids {
@@ -325,7 +319,7 @@ mod tests {
ON CONFLICT DO NOTHING
"#,
uuid::Uuid::now_v7(),
- user_id.as_ref(),
+ user_id,
item_id,
item_type,
channel_id,
@@ -342,8 +336,6 @@ 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#"
@@ -351,7 +343,7 @@ mod tests {
FROM "UserItemAccess"
WHERE "user_id" = ANY($1) AND "item_id" = $2 AND "item_type" = $3 AND "granted_from_channel_id" = $4
"#,
- &ids,
+ &user_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 6df76b950c..3d58bb0ad4 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: &[MacroUserIdStr<'_>],
+ user_ids: &[String],
item_id: &str,
item_type: &str,
access_level: AccessLevel,
@@ -67,8 +67,6 @@ 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()
@@ -108,7 +106,7 @@ where
access_level as _,
granted_from_channel_id,
&ids,
- macro_ids.as_slice(),
+ user_ids as &[String],
)
.execute(executor)
.await?;
@@ -256,7 +254,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;
@@ -310,9 +308,9 @@ mod tests {
let access_level = AccessLevel::View;
let granted_from_channel_id = Some(Uuid::now_v7());
let user_ids = vec![
- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ "user0".to_string(),
+ "user1".to_string(),
+ "user2".to_string(),
];
let mut transaction = pool.begin().await?;
@@ -328,8 +326,6 @@ mod tests {
)
.await?;
- let ids: Vec<_> = user_ids.iter().map(|x| x.to_string()).collect();
-
// Verify all records exist
let result = sqlx::query!(
r#"
@@ -338,7 +334,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
"#,
- &ids,
+ &user_ids,
item_id,
item_type,
access_level.to_string(),
@@ -367,13 +363,13 @@ mod tests {
FROM "UserItemAccess"
WHERE "user_id" = $1 AND "item_id" = $2
"#,
- user_id.as_ref(),
+ user_id,
item_id,
)
.fetch_one(&mut *transaction)
.await?;
- assert_eq!(result.user_id, user_id.as_ref());
+ assert_eq!(result.user_id, *user_id);
assert_eq!(result.item_id, item_id);
assert_eq!(result.item_type, item_type);
assert_eq!(result.access_level, Some(access_level.to_string()));
@@ -432,9 +428,9 @@ mod tests {
let access_level = AccessLevel::Owner;
let granted_from_channel_id = Some(Uuid::now_v7());
let user_ids = vec![
- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ "user3".to_string(),
+ "user4".to_string(),
+ "user5".to_string(),
];
// Insert using the pool directly
@@ -448,8 +444,6 @@ mod tests {
)
.await?;
- let ids: Vec<_> = user_ids.iter().map(|x| x.to_string()).collect();
-
// Verify all records exist
let result = sqlx::query!(
r#"
@@ -458,7 +452,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
"#,
- &ids,
+ &user_ids,
item_id,
item_type,
access_level.to_string(),
@@ -482,10 +476,7 @@ 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![
- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
- ];
+ let user_ids = vec!["user1".to_string(), "user2".to_string()];
let mut transaction = pool.begin().await?;
@@ -501,8 +492,6 @@ mod tests {
)
.await?;
- let ids: Vec<_> = user_ids.iter().map(|x| x.to_string()).collect();
-
// Verify initial insert
let initial_result = sqlx::query!(
r#"
@@ -512,7 +501,7 @@ mod tests {
AND "granted_from_channel_id" = $4
ORDER BY "user_id"
"#,
- &ids,
+ &user_ids,
item_id,
item_type,
granted_from_channel_id,
@@ -546,8 +535,6 @@ 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#"
@@ -560,7 +547,7 @@ mod tests {
AND "granted_from_channel_id" = $4
ORDER BY "user_id"
"#,
- &ids,
+ &user_ids,
item_id,
item_type,
granted_from_channel_id,
@@ -593,9 +580,9 @@ mod tests {
// Test with both updates and new inserts
let mixed_user_ids = vec![
- 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
+ "user1".to_string(), // existing
+ "user3".to_string(), // new
+ "user4".to_string(), // new
];
let final_access_level = AccessLevel::Owner;
@@ -611,8 +598,6 @@ 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#"
@@ -625,7 +610,7 @@ mod tests {
AND "granted_from_channel_id" = $4
ORDER BY "user_id"
"#,
- &ids,
+ &mixed_user_ids,
item_id,
item_type,
granted_from_channel_id,
@@ -659,12 +644,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
"#,
- &ids,
- &["macro|[email protected]".to_string()], // user2 from original insert, not in mixed_user_ids
+ &user_ids,
+ &["user3".to_string(), "user4".to_string()],
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 f2e377dcfc..fddf08be4e 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.as_ref() != user_id && p.left_at.is_none())
+ .filter(|p| p.user_id != 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 08525ab6b6..6113b239b9 100644
--- a/rust/cloud-storage/model/Cargo.toml
+++ b/rust/cloud-storage/model/Cargo.toml
@@ -12,7 +12,6 @@ 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 7324c8b0c8..e9fce3798c 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,12 +47,9 @@ pub struct UserActivityForChannel {
pub updated_at: chrono::NaiveDateTime,
}
-#[derive(
- Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type, ToSchema, Default, Doppleganger,
-)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type, ToSchema, Default)]
#[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,
@@ -60,15 +57,12 @@ pub enum ParticipantRole {
Member,
}
-#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, Doppleganger)]
-#[dg(backward = models_comms::channel::ChannelParticipant)]
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct ChannelParticipant {
/// id of the channel
- #[schema(value_type = Uuid)]
- pub channel_id: ChannelId,
+ pub channel_id: Uuid,
/// id of the user
- #[schema(value_type = String)]
- pub user_id: MacroUserIdStr<'static>,
+ pub user_id: String,
/// type of the participant
pub role: ParticipantRole,
/// timestamp of when the user joined the channel
@@ -77,67 +71,48 @@ pub struct ChannelParticipant {
pub left_at: Option<chrono::DateTime<chrono::Utc>>,
}
-#[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)]
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)]
pub struct Channel {
/// uuid of the channel
- #[schema(value_type = Uuid)]
- pub id: ChannelId,
+ pub id: Uuid,
/// 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>,
+ pub org_id: Option<i64>,
/// 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>,
+ pub owner_id: String,
}
-#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, Doppleganger)]
-#[dg(backward = models_comms::channel::ChannelWithParticipants)]
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct ChannelWithParticipants {
#[serde(flatten)]
pub channel: Channel,
pub participants: Vec<ChannelParticipant>,
}
-#[derive(Debug, Clone, Default, ToSchema, Serialize, Deserialize, Doppleganger)]
-#[dg(backward = models_comms::channel::LatestMessage)]
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, Default)]
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 {
@@ -166,13 +141,12 @@ 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: MacroUserIdStr<'static>,
+ pub welcome_user_id: String,
/// The id of the user to send the welcome message to
- pub to_user_id: MacroUserIdStr<'static>,
+ pub to_user_id: String,
}
-#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, Doppleganger)]
-#[dg(backward = models_comms::channel::ChannelMessage)]
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
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 9181483911..85ad54010b 100644
--- a/rust/cloud-storage/model_notifications/Cargo.toml
+++ b/rust/cloud-storage/model_notifications/Cargo.toml
@@ -7,7 +7,6 @@ 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 8442662e65..dee3543f7c 100644
--- a/rust/cloud-storage/model_notifications/src/metadata.rs
+++ b/rust/cloud-storage/model_notifications/src/metadata.rs
@@ -1,30 +1,10 @@
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 c43368b354..1f805e4cb5 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 5100419508..71c4b22b48 100644
--- a/rust/cloud-storage/models_comms/src/channel.rs
+++ b/rust/cloud-storage/models_comms/src/channel.rs
@@ -1,14 +1,12 @@
-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 uuid::Uuid;
+use utoipa::ToSchema;
-#[derive(Debug, Clone, Copy, Display, Deserialize)]
-#[strum(serialize_all = "snake_case")]
+#[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")]
+#[strum(serialize_all = "snake_case")]
pub enum ChannelType {
Public,
Organization,
@@ -16,102 +14,14 @@ pub enum ChannelType {
DirectMessage,
}
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChannelMetadata {
pub name: String,
pub channel_type: ChannelType,
}
-#[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>>,
+impl From<(String, ChannelType)> for ChannelMetadata {
+ fn from((name, channel_type): (String, ChannelType)) -> Self {
+ Self { name, channel_type }
+ }
}
diff --git a/rust/cloud-storage/models_comms/src/lib.rs b/rust/cloud-storage/models_comms/src/lib.rs
index f333359c6f..b4c0de73e9 100644
--- a/rust/cloud-storage/models_comms/src/lib.rs
+++ b/rust/cloud-storage/models_comms/src/lib.rs
@@ -1,2 +1,4 @@
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 7fe4a39b6c..8d7c236cb2 100644
--- a/rust/cloud-storage/models_comms/src/mentions.rs
+++ b/rust/cloud-storage/models_comms/src/mentions.rs
@@ -1,12 +1,13 @@
use serde::{Deserialize, Serialize};
+use utoipa::ToSchema;
use uuid::Uuid;
-#[derive(Debug, Serialize, Deserialize)]
+#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct DeleteMentionsRequest {
pub item_ids: Vec<String>,
}
-#[derive(Debug, Clone, Serialize, Deserialize)]
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
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 44b43b8d73..4b295999eb 100644
--- a/rust/cloud-storage/models_soup/Cargo.toml
+++ b/rust/cloud-storage/models_soup/Cargo.toml
@@ -11,8 +11,6 @@ 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" }
@@ -22,3 +20,4 @@ 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
deleted file mode 100644
index f0f9f260ad..0000000000
--- a/rust/cloud-storage/models_soup/src/comms.rs
+++ /dev/null
@@ -1,99 +0,0 @@
-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 a161f8ce22..23e5c941f5 100644
--- a/rust/cloud-storage/models_soup/src/item.rs
+++ b/rust/cloud-storage/models_soup/src/item.rs
@@ -1,14 +1,27 @@
+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 {
@@ -16,7 +29,6 @@ pub enum SoupItem {
Chat(SoupChat),
Project(SoupProject),
EmailThread(SoupEnrichedEmailThreadPreview),
- Channel(SoupChannel),
}
impl SoupItem {
@@ -35,9 +47,6 @@ 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())
- }
}
}
@@ -47,7 +56,6 @@ 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,
}
}
}
@@ -99,18 +107,6 @@ 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),
}
}
}
@@ -124,7 +120,6 @@ 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 bb92c464d3..9bc875b4aa 100644
--- a/rust/cloud-storage/models_soup/src/lib.rs
+++ b/rust/cloud-storage/models_soup/src/lib.rs
@@ -1,5 +1,4 @@
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 0b5951b1ec..2103831efd 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,6 +8,7 @@ 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;
@@ -209,9 +210,7 @@ impl BuildNotification for ChannelMessageSendMetadata {
aps: Aps {
alert: Some(sns_client::Alert::Dictionary(sns_client::AlertDictionary {
title: Some(match self.common.channel_type {
- model_notifications::ChannelType::DirectMessage => {
- self.common.channel_name.to_string()
- }
+ 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 4a2ad1f866..ec931448a7 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,11 +53,7 @@ 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_model_comms()
- .to_string(),
+ &channel_metadata.common.channel_type.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 fcc63abc9f..9de91333bb 100644
--- a/rust/cloud-storage/properties/src/domain/ports.rs
+++ b/rust/cloud-storage/properties/src/domain/ports.rs
@@ -3,7 +3,6 @@
//! 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;
@@ -116,9 +115,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<'a>(
+ fn grant_permissions_to_task(
&self,
- user_ids: &[MacroUserIdStr<'a>],
+ user_ids: &[String],
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 ed970d6ba4..032777cf21 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,10 +1,7 @@
//! 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;
@@ -108,11 +105,7 @@ where
return Ok(());
};
- 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()))?;
+ let assignee_ids: Vec<String> = references.iter().map(|r| r.entity_id.clone()).collect();
if assignee_ids.is_empty() {
return Ok(());
}
@@ -131,7 +124,7 @@ where
pub async fn handle_task_assignee_notifications(
&self,
task_id: Uuid,
- assignee_ids: &[MacroUserIdStr<'_>],
+ assignee_ids: &[String],
assigned_by_user_id: &str,
) -> Result<(), PropertiesErr> {
if assignee_ids.is_empty() {
@@ -157,19 +150,17 @@ where
.map_err(anyhow::Error::from)
.map_err(PropertiesErr::Repo)?;
- let current_assignee_ids: HashSet<String> = match current_value {
+ let current_assignee_ids: Vec<String> = match current_value {
Some(PropertyValue::EntityRef(refs)) => {
refs.iter().map(|r| r.entity_id.clone()).collect()
}
- _ => Default::default(),
+ _ => vec![],
};
- let recipient_ids: Vec<MacroUserIdStr<'_>> = assignee_ids
+ let recipient_ids: Vec<String> = assignee_ids
.iter()
- .filter(|id| {
- !current_assignee_ids.contains(id.as_ref()) && id.as_ref() != assigned_by_user_id
- })
- .map(|id| id.copied())
+ .filter(|id| !current_assignee_ids.contains(id) && id.as_str() != assigned_by_user_id)
+ .cloned()
.collect();
if recipient_ids.is_empty() {
@@ -207,7 +198,7 @@ where
notification_entity: notification_entity.clone(),
notification_event: notification_event.clone(),
sender_id: Some(assigned_by.clone()),
- recipient_ids: Some(vec![recipient_id.to_string()]),
+ recipient_ids: Some(vec![recipient_id.clone()]),
};
let recipient_id_for_log = recipient_id.clone();
@@ -241,7 +232,7 @@ where
pub async fn handle_task_assignee_permissions(
&self,
task_id: Uuid,
- assignee_ids: &[MacroUserIdStr<'_>],
+ assignee_ids: &[String],
) -> 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 6a1940cc30..0fd1b01c61 100644
--- a/rust/cloud-storage/properties/src/domain/test.rs
+++ b/rust/cloud-storage/properties/src/domain/test.rs
@@ -6,7 +6,6 @@ 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;
@@ -382,20 +381,15 @@ 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![
- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
- ];
+ let assignee_ids = vec!["user1".to_string(), "user2".to_string()];
perm_service
.expect_grant_permissions_to_task()
.withf(move |user_ids, task_id_param| {
user_ids.len() == 2
- && 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()
+ && user_ids.contains(&"user1".to_string())
+ && user_ids.contains(&"user2".to_string())
+ && task_id_param == &task_id.to_string()
})
.returning(|_, _| Box::pin(async { Ok(()) }));
@@ -429,7 +423,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![MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()];
+ let assignee_ids = vec!["user1".to_string()];
let service = PropertiesServiceImpl::new(
repo,
@@ -454,7 +448,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![MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()];
+ let assignee_ids = vec!["user1".to_string()];
perm_service
.expect_grant_permissions_to_task()
@@ -478,7 +472,7 @@ async fn test_handle_task_assignee_permissions_error_propagates() {
struct NotificationTestCase {
task_id: Uuid,
assigned_by: String,
- assignees: Vec<MacroUserIdStr<'static>>,
+ assignees: Vec<String>,
existing_assignees: Vec<String>,
task_name: Option<String>,
expected_notification_count: usize,
@@ -499,7 +493,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
})
@@ -527,7 +521,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) })
@@ -584,9 +578,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![
- 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
+ "macro|[email protected]".to_string(),
+ "macro|[email protected]".to_string(),
+ "macro|[email protected]".to_string(), // existing, should not get notification
],
existing_assignees: vec!["macro|[email protected]".to_string()],
task_name: Some("Test Task".to_string()),
@@ -603,8 +597,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![
- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ "macro|[email protected]".to_string(),
+ "macro|[email protected]".to_string(),
],
existing_assignees: vec![],
task_name: Some("Test Task".to_string()),
@@ -620,7 +614,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![MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()],
+ assignees: vec!["macro|[email protected]".to_string()],
existing_assignees: vec!["macro|[email protected]".to_string()],
task_name: None, // Should not call get_entity_name
expected_notification_count: 0, // no new assignees
@@ -635,7 +629,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![MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()],
+ assignees: vec!["user1".to_string()],
existing_assignees: vec![],
task_name: None, // Should not call get_entity_name when no service
expected_notification_count: 0,
@@ -665,7 +659,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![MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()],
+ assignees: vec!["macro|[email protected]".to_string()],
existing_assignees: vec![],
task_name: None, // task doesn't exist yet
expected_notification_count: 1,
@@ -688,9 +682,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 = [
- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ let assignees = vec![
+ "macro|[email protected]".to_string(),
+ "macro|[email protected]".to_string(),
];
let value = Some(
@@ -699,7 +693,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.to_string(),
+ entity_id: id.clone(),
specific_message_id: None,
})
.collect(),
@@ -719,7 +713,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 e5a523ff97..f622ac8b65 100644
--- a/rust/cloud-storage/properties/src/outbound/permission_service.rs
+++ b/rust/cloud-storage/properties/src/outbound/permission_service.rs
@@ -1,6 +1,5 @@
//! 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};
@@ -87,7 +86,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: &[MacroUserIdStr<'_>],
+ user_ids: &[String],
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 0c29e3e138..531fa8f9c3 100644
--- a/rust/cloud-storage/scribe/Cargo.toml
+++ b/rust/cloud-storage/scribe/Cargo.toml
@@ -27,7 +27,6 @@ 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 }
@@ -53,9 +52,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 6d46bd7224..0176dcc4c1 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::channel::ChannelMetadata;
+use models_comms::ChannelMetadata;
use std::fmt::Debug;
use std::sync::Arc;
use uuid::Uuid;
@@ -39,19 +39,10 @@ impl ChannelClient {
.await
.map_err(Error::from)?,
};
- 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
- }
- },
- })
+ Ok(ChannelMetadata::from((
+ response.channel_name,
+ response.channel_type,
+ )))
}
/// 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 0bedaf0908..8cb98ef163 100644
--- a/rust/cloud-storage/soup/Cargo.toml
+++ b/rust/cloud-storage/soup/Cargo.toml
@@ -26,8 +26,6 @@ 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"] }
@@ -49,6 +47,7 @@ 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"
@@ -60,7 +59,6 @@ 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 d629536553..c544a4b8ea 100644
--- a/rust/cloud-storage/soup/src/domain/models.rs
+++ b/rust/cloud-storage/soup/src/domain/models.rs
@@ -194,6 +194,4 @@ 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 77d16e23db..1a7a910f15 100644
--- a/rust/cloud-storage/soup/src/domain/service.rs
+++ b/rust/cloud-storage/soup/src/domain/service.rs
@@ -5,7 +5,6 @@ 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};
@@ -19,9 +18,7 @@ use model_entity::as_owned::ShallowClone;
use models_pagination::{
Cursor, CursorVal, Frecency, FrecencyValue, PaginateOn, Query, SimpleSortMethod,
};
-use models_soup::{
- comms::SoupChannel, email_thread::SoupEnrichedEmailThreadPreview, item::SoupItem,
-};
+use models_soup::{email_thread::SoupEnrichedEmailThreadPreview, item::SoupItem};
use std::cmp::Ordering;
use uuid::Uuid;
@@ -29,31 +26,27 @@ use uuid::Uuid;
mod tests;
/// struct which handles the actual implementation of soup with abstracted interfaces for mocking
-pub struct SoupImpl<T, U, V, C> {
+pub struct SoupImpl<T, U, V> {
/// 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, C> SoupImpl<T, U, V, C>
+impl<T, U, V> SoupImpl<T, U, V>
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, comms_service: C) -> Self {
+ pub fn new(soup_storage: T, frecency: U, email_service: V) -> Self {
SoupImpl {
soup_storage,
frecency,
email_service,
- comms_service,
}
}
@@ -269,35 +262,14 @@ 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, C> SoupService for SoupImpl<T, U, V, C>
+impl<T, U, V> SoupService for SoupImpl<T, U, V>
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);
@@ -314,21 +286,17 @@ where
SimpleSortRequest {
limit,
cursor: SimpleSortQuery::from_entity_cursor(cursor),
- user_id: req.user.copied(),
+ user_id: req.user,
},
);
let email_soup_fut = self.handle_email_request(email_request);
- 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)?;
+ let (main_soup, email_soup) = tokio::try_join!(main_soup_fut, email_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 dfe118952a..aec79915fc 100644
--- a/rust/cloud-storage/soup/src/domain/service/tests.rs
+++ b/rust/cloud-storage/soup/src/domain/service/tests.rs
@@ -13,7 +13,6 @@ use models_pagination::{
};
use models_soup::document::SoupDocument;
use ordered_float::OrderedFloat;
-use rootcause::Report;
use sqlx::types::chrono::{DateTime, Utc};
use uuid::Uuid;
@@ -44,31 +43,6 @@ 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(|_| {
@@ -153,7 +127,6 @@ async fn it_should_not_query_frecency() {
soup_mock,
FrecencyQueryServiceImpl::new(MockFrecencyStorage::new()),
NoopEmailService,
- NoopCommsService,
)
.get_user_soup(SoupRequest {
email_preview_view: PreviewView::StandardLabel(
@@ -231,7 +204,6 @@ async fn it_should_query_frecency() {
soup_mock,
FrecencyQueryServiceImpl::new(frecency_mock),
NoopEmailService,
- NoopCommsService,
)
.get_user_soup(SoupRequest {
email_preview_view: PreviewView::StandardLabel(
@@ -309,7 +281,6 @@ async fn it_should_sort_frecency_descending() {
soup_mock,
FrecencyQueryServiceImpl::new(frecency_mock),
NoopEmailService,
- NoopCommsService,
)
.get_user_soup(SoupRequest {
email_preview_view: PreviewView::StandardLabel(
@@ -397,7 +368,7 @@ async fn frecency_should_fallback() {
Box::pin(async move { res })
});
- let res = SoupImpl::new(soup, frecency, NoopEmailService, NoopCommsService)
+ let res = SoupImpl::new(soup, frecency, NoopEmailService)
.get_user_soup(SoupRequest {
email_preview_view: PreviewView::StandardLabel(
email::domain::models::PreviewViewStandardLabel::Inbox,
@@ -467,7 +438,7 @@ async fn frecency_should_paginate() {
Box::pin(async move { Ok(vec) })
});
- let res = SoupImpl::new(soup, frecency, NoopEmailService, NoopCommsService)
+ let res = SoupImpl::new(soup, frecency, NoopEmailService)
.get_user_soup(SoupRequest {
email_preview_view: PreviewView::StandardLabel(
email::domain::models::PreviewViewStandardLabel::Inbox,
@@ -539,7 +510,7 @@ async fn frecency_should_resume_cursor() {
Box::pin(async move { Ok(vec) })
});
- let res = SoupImpl::new(soup, frecency, NoopEmailService, NoopCommsService)
+ let res = SoupImpl::new(soup, frecency, NoopEmailService)
.get_user_soup(SoupRequest {
email_preview_view: PreviewView::StandardLabel(
email::domain::models::PreviewViewStandardLabel::Inbox,
@@ -627,7 +598,7 @@ async fn frecency_fallback_cursor_should_resume() {
Box::pin(async move { res })
});
- let res = SoupImpl::new(soup, frecency, NoopEmailService, NoopCommsService)
+ let res = SoupImpl::new(soup, frecency, NoopEmailService)
.get_user_soup(SoupRequest {
email_preview_view: PreviewView::StandardLabel(
email::domain::models::PreviewViewStandardLabel::Inbox,
@@ -692,7 +663,6 @@ async fn cursor_should_return_simple_sort() {
soup_mock,
FrecencyQueryServiceImpl::new(MockFrecencyStorage::new()),
NoopEmailService,
- NoopCommsService,
)
.get_user_soup(SoupRequest {
email_preview_view: PreviewView::StandardLabel(
@@ -751,7 +721,7 @@ async fn cursor_should_return_frecency() {
Box::pin(async move { Ok(vec) })
});
- let res = SoupImpl::new(soup, frecency, NoopEmailService, NoopCommsService)
+ let res = SoupImpl::new(soup, frecency, NoopEmailService)
.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 d2d3436ada..51b017c784 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,7 +35,15 @@ 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| item.id()).collect();
+ 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 expected_ids: HashSet<Uuid> = [
"22222222-0000-0000-0000-000000000000", // chat-standalone
@@ -216,7 +224,7 @@ async fn test_expanded_generic_sorting_methods(pool: Pool<Postgres>) -> anyhow::
);
let item_ids = get_item_ids(&items);
- let expected_ids: Vec<Uuid> = [
+ let expected_ids: Vec<Uuid> = vec![
"aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", // doc-A
"bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", // doc-B
"aaaaaaaa-cccc-cccc-cccc-cccccccccccc", // chat-A
@@ -246,7 +254,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> = [
+ let expected_ids: Vec<Uuid> = vec![
"aaaaaaaa-cccc-cccc-cccc-cccccccccccc", // chat-A
"aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", // doc-A
"bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", // doc-B
@@ -276,7 +284,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> = [
+ let expected_ids: Vec<Uuid> = vec![
"bbbbbbbb-cccc-cccc-cccc-cccccccccccc", // chat-B
"bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", // doc-B
"aaaaaaaa-cccc-cccc-cccc-cccccccccccc", // chat-A
@@ -329,10 +337,7 @@ 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(_)
- | SoupItem::EmailThread(_)
- | SoupItem::Channel(_) => None,
+ SoupItem::Chat(_) | SoupItem::Project(_) | _ => None,
})
.expect("The document should exist");
let expected_doc_id = Uuid::parse_str("11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa").unwrap(); // doc-in-A
@@ -346,7 +351,7 @@ async fn test_expanded_soup_by_ids(pool: Pool<Postgres>) {
.iter()
.find_map(|x| match x {
SoupItem::Chat(soup_chat) => Some(soup_chat),
- _ => None,
+ SoupItem::Document(_) | SoupItem::Project(_) | _ => None,
})
.expect("The chat should exist");
let expected_chat_id = Uuid::parse_str("22222222-bbbb-bbbb-bbbb-bbbbbbbbbbbb").unwrap(); // chat-in-B