Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(email+soup): hexify email preview cursor (#244)

Sean Aye599aab70e952
diff --git a/js/app/packages/core/email/preview.ts b/js/app/packages/core/email/preview.ts
index 6a27366675..6e7107935d 100644
--- a/js/app/packages/core/email/preview.ts
+++ b/js/app/packages/core/email/preview.ts
@@ -1,12 +1,11 @@
import { isErr } from '@core/util/maybeResult';
import { emailClient } from '@service-email/client';
-import type { GetPreviewsCursorResponse } from '@service-email/generated/schemas';
+import type { ApiPaginatedThreadCursor } from '@service-email/generated/schemas';
import { createSingletonRoot } from '@solid-primitives/rootless';
import type { Accessor } from 'solid-js';
import { createMemo, createResource } from 'solid-js';
-export type EmailPreview =
- GetPreviewsCursorResponse['previews']['items'][number];
+export type EmailPreview = ApiPaginatedThreadCursor['items'][number];
// TODO
async function getPreviews() {
@@ -28,6 +27,6 @@ export function usePreviewEmails(): Accessor<EmailPreview[]> {
return createMemo(() => {
const result = r.latest;
if (!result) return [];
- return result.previews.items;
+ return result.items;
});
}
diff --git a/js/app/packages/core/types/index.ts b/js/app/packages/core/types/index.ts
index 5143a3e8c8..4fb6574952 100644
--- a/js/app/packages/core/types/index.ts
+++ b/js/app/packages/core/types/index.ts
@@ -14,5 +14,5 @@ export type Entity = {
type: EntityType;
};
-export type { PaginatedThreadCursor as ThreadPreview } from '@service-email/generated/schemas/paginatedThreadCursor';
+export type { ApiPaginatedThreadCursor as ThreadPreview } from '@service-email/generated/schemas/apiPaginatedThreadCursor';
export { NotificationEventType as NotificationType } from '@service-notification/generated/schemas/notificationEventType';
diff --git a/js/app/packages/macro-entity/src/queries/email.ts b/js/app/packages/macro-entity/src/queries/email.ts
index 6871dc1def..61b3a91e2c 100644
--- a/js/app/packages/macro-entity/src/queries/email.ts
+++ b/js/app/packages/macro-entity/src/queries/email.ts
@@ -2,7 +2,7 @@ import type { PreviewViewStandardLabel } from '@service-email/generated/schemas'
import { useInfiniteQuery } from '@tanstack/solid-query';
import { SERVER_HOSTS } from 'core/constant/servers';
import { platformFetch } from 'core/util/platformFetch';
-import type { GetPreviewsCursorResponse } from 'service-email/generated/schemas/getPreviewsCursorResponse';
+import type { ApiPaginatedThreadCursor } from 'service-email/generated/schemas/apiPaginatedThreadCursor';
import type { PreviewsInboxCursorParams } from 'service-email/generated/schemas/previewsInboxCursorParams';
import { type Accessor, createMemo } from 'solid-js';
import type { EmailEntity } from '../types/entity';
@@ -37,7 +37,7 @@ const fetchPaginatedEmails = async ({
if (!response.ok)
throw new Error('Failed to fetch email', { cause: response });
- const { previews }: GetPreviewsCursorResponse = await response.json();
+ const previews: ApiPaginatedThreadCursor = await response.json();
return previews;
};
@@ -77,19 +77,16 @@ export function createEmailsInfiniteQuery(
select: (data) =>
data.pages.flatMap(({ items }) =>
items.map((email): EmailEntity => {
- const participantEmails = email.participants.map(
- (p) => p.email_address ?? ''
- );
- const participantNames = email.participants.map(
- (p) => p.name ?? ''
+ const participantEmails = email.contacts.map(
+ (p) => p.emailAddress ?? ''
);
+ const participantNames = email.contacts.map((p) => p.name ?? '');
return {
...email,
type: 'email',
name: email.name || 'No Subject',
- // @ts-expect-error - frecency_score is not typed in the response
- frecencyScore: email.frecency_score,
+ frecencyScore: email.frecencyScore ?? undefined,
viewedAt: email.viewedAt ?? undefined,
snippet: email.snippet ?? undefined,
isImportant: email.isImportant ?? false,
diff --git a/js/app/packages/service-email/client.ts b/js/app/packages/service-email/client.ts
index f6f65be475..122444fb97 100644
--- a/js/app/packages/service-email/client.ts
+++ b/js/app/packages/service-email/client.ts
@@ -11,10 +11,10 @@ import {
} from '@core/util/maybeResult';
import type { SafeFetchInit } from '@core/util/safeFetch';
import type {
+ ApiPaginatedThreadCursor,
CreateDraftRequest,
CreateDraftResponse,
GetAttachmentResponse,
- GetPreviewsCursorResponse,
GetThreadResponse,
ListContactsResponse,
ListLabelsResponse,
@@ -91,7 +91,7 @@ export const emailClient = {
const qp = p.length > 0 ? '?' + p : p;
return mapOk(
- await emailFetch<GetPreviewsCursorResponse>(
+ await emailFetch<ApiPaginatedThreadCursor>(
`/email/threads/previews/cursor/${view}${qp}`,
{
method: 'GET',
diff --git a/js/app/packages/service-email/generated/client.ts b/js/app/packages/service-email/generated/client.ts
index 7e89b3b38d..2dc21f9fe7 100644
--- a/js/app/packages/service-email/generated/client.ts
+++ b/js/app/packages/service-email/generated/client.ts
@@ -5,6 +5,7 @@
* OpenAPI spec version: 0.1.0
*/
import type {
+ ApiPaginatedThreadCursor,
ArchiveThreadRequest,
CancelBackfillParams,
CreateDraftRequest,
@@ -13,9 +14,9 @@ import type {
CreateLabelResponse,
EmptyResponse,
ErrorResponse,
+ GetActiveBackfillJobResponse,
GetAttachmentResponse,
GetBackfillJobResponse,
- GetPreviewsFrecencyResponse,
GetThreadMessagesHandlerParams,
GetThreadParams,
GetThreadResponse,
@@ -153,22 +154,81 @@ export const cancelBackfillGmail = async (cancelBackfillParams: CancelBackfillPa
+/**
+ * @summary Get any active backfill job for the user.
+ */
+export type getBackfillGmailActiveResponse200 = {
+ data: GetActiveBackfillJobResponse
+ status: 200
+}
+
+export type getBackfillGmailActiveResponse204 = {
+ data: EmptyResponse
+ status: 204
+}
+
+export type getBackfillGmailActiveResponse401 = {
+ data: ErrorResponse
+ status: 401
+}
+
+export type getBackfillGmailActiveResponse500 = {
+ data: ErrorResponse
+ status: 500
+}
+
+export type getBackfillGmailActiveResponseSuccess = (getBackfillGmailActiveResponse200 | getBackfillGmailActiveResponse204) & {
+ headers: Headers;
+};
+export type getBackfillGmailActiveResponseError = (getBackfillGmailActiveResponse401 | getBackfillGmailActiveResponse500) & {
+ headers: Headers;
+};
+
+export type getBackfillGmailActiveResponse = (getBackfillGmailActiveResponseSuccess | getBackfillGmailActiveResponseError)
+
+export const getGetBackfillGmailActiveUrl = () => {
+
+
+
+
+ return `/email/backfill/gmail/active`
+}
+
+export const getBackfillGmailActive = async ( options?: RequestInit): Promise<getBackfillGmailActiveResponse> => {
+
+ const res = await fetch(getGetBackfillGmailActiveUrl(),
+ {
+ ...options,
+ method: 'GET'
+
+
+ }
+)
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: getBackfillGmailActiveResponse['data'] = body ? JSON.parse(body) : {}
+ return { data, status: res.status, headers: res.headers } as getBackfillGmailActiveResponse
+}
+
+
+
/**
* @summary Get a backfill job.
*/
-export type getBackfillGmailResponse201 = {
+export type getBackfillGmailResponse200 = {
data: GetBackfillJobResponse
- status: 201
+ status: 200
}
-export type getBackfillGmailResponse404 = {
+export type getBackfillGmailResponse401 = {
data: ErrorResponse
- status: 404
+ status: 401
}
-export type getBackfillGmailResponse429 = {
+export type getBackfillGmailResponse404 = {
data: ErrorResponse
- status: 429
+ status: 404
}
export type getBackfillGmailResponse500 = {
@@ -176,10 +236,10 @@ export type getBackfillGmailResponse500 = {
status: 500
}
-export type getBackfillGmailResponseSuccess = (getBackfillGmailResponse201) & {
+export type getBackfillGmailResponseSuccess = (getBackfillGmailResponse200) & {
headers: Headers;
};
-export type getBackfillGmailResponseError = (getBackfillGmailResponse404 | getBackfillGmailResponse429 | getBackfillGmailResponse500) & {
+export type getBackfillGmailResponseError = (getBackfillGmailResponse401 | getBackfillGmailResponse404 | getBackfillGmailResponse500) & {
headers: Headers;
};
@@ -1071,7 +1131,7 @@ export const disableSync = async ( options?: RequestInit): Promise<disableSyncRe
* @summary Get paginated thread previews with cursor-based pagination.
*/
export type previewsInboxCursorResponse200 = {
- data: GetPreviewsFrecencyResponse
+ data: ApiPaginatedThreadCursor
status: 200
}
diff --git a/js/app/packages/service-email/generated/schemas/apiAttachment.ts b/js/app/packages/service-email/generated/schemas/apiAttachment.ts
new file mode 100644
index 0000000000..ec2c5606fa
--- /dev/null
+++ b/js/app/packages/service-email/generated/schemas/apiAttachment.ts
@@ -0,0 +1,22 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ApiAttachmentContentId } from './apiAttachmentContentId';
+import type { ApiAttachmentFilename } from './apiAttachmentFilename';
+import type { ApiAttachmentMimeType } from './apiAttachmentMimeType';
+import type { ApiAttachmentProviderAttachmentId } from './apiAttachmentProviderAttachmentId';
+import type { ApiAttachmentSizeBytes } from './apiAttachmentSizeBytes';
+
+export interface ApiAttachment {
+ contentId?: ApiAttachmentContentId;
+ createdAt: number;
+ filename?: ApiAttachmentFilename;
+ id: string;
+ messageId: string;
+ mimeType?: ApiAttachmentMimeType;
+ providerAttachmentId?: ApiAttachmentProviderAttachmentId;
+ sizeBytes?: ApiAttachmentSizeBytes;
+}
diff --git a/js/app/packages/service-email/generated/schemas/paginatedThreadCursorNextCursor.ts b/js/app/packages/service-email/generated/schemas/apiAttachmentContentId.ts
similarity index 65%
rename from js/app/packages/service-email/generated/schemas/paginatedThreadCursorNextCursor.ts
rename to js/app/packages/service-email/generated/schemas/apiAttachmentContentId.ts
index e931552e54..9f4e44c06e 100644
--- a/js/app/packages/service-email/generated/schemas/paginatedThreadCursorNextCursor.ts
+++ b/js/app/packages/service-email/generated/schemas/apiAttachmentContentId.ts
@@ -5,4 +5,4 @@
* OpenAPI spec version: 0.1.0
*/
-export type PaginatedThreadCursorNextCursor = string | null;
+export type ApiAttachmentContentId = string | null;
diff --git a/js/app/packages/service-email/generated/schemas/threadPreviewPaginationNextCursor.ts b/js/app/packages/service-email/generated/schemas/apiAttachmentFilename.ts
similarity index 65%
rename from js/app/packages/service-email/generated/schemas/threadPreviewPaginationNextCursor.ts
rename to js/app/packages/service-email/generated/schemas/apiAttachmentFilename.ts
index 4b7071c0d7..499409d5cb 100644
--- a/js/app/packages/service-email/generated/schemas/threadPreviewPaginationNextCursor.ts
+++ b/js/app/packages/service-email/generated/schemas/apiAttachmentFilename.ts
@@ -5,4 +5,4 @@
* OpenAPI spec version: 0.1.0
*/
-export type ThreadPreviewPaginationNextCursor = string | null;
+export type ApiAttachmentFilename = string | null;
diff --git a/js/app/packages/service-email/generated/schemas/apiAttachmentMacro.ts b/js/app/packages/service-email/generated/schemas/apiAttachmentMacro.ts
new file mode 100644
index 0000000000..429e1dafe8
--- /dev/null
+++ b/js/app/packages/service-email/generated/schemas/apiAttachmentMacro.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export interface ApiAttachmentMacro {
+ dbId: string;
+ itemId: string;
+ itemType: string;
+ messageId: string;
+}
diff --git a/js/app/packages/service-email/generated/schemas/threadPreviewFrecencyAllOf.ts b/js/app/packages/service-email/generated/schemas/apiAttachmentMimeType.ts
similarity index 61%
rename from js/app/packages/service-email/generated/schemas/threadPreviewFrecencyAllOf.ts
rename to js/app/packages/service-email/generated/schemas/apiAttachmentMimeType.ts
index 73da5d6a14..81f04edf08 100644
--- a/js/app/packages/service-email/generated/schemas/threadPreviewFrecencyAllOf.ts
+++ b/js/app/packages/service-email/generated/schemas/apiAttachmentMimeType.ts
@@ -5,6 +5,4 @@
* OpenAPI spec version: 0.1.0
*/
-export type ThreadPreviewFrecencyAllOf = {
- frecency_score: number;
-};
+export type ApiAttachmentMimeType = string | null;
diff --git a/js/app/packages/service-email/generated/schemas/apiAttachmentProviderAttachmentId.ts b/js/app/packages/service-email/generated/schemas/apiAttachmentProviderAttachmentId.ts
new file mode 100644
index 0000000000..3d76e09dba
--- /dev/null
+++ b/js/app/packages/service-email/generated/schemas/apiAttachmentProviderAttachmentId.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiAttachmentProviderAttachmentId = string | null;
diff --git a/js/app/packages/service-email/generated/schemas/apiAttachmentSizeBytes.ts b/js/app/packages/service-email/generated/schemas/apiAttachmentSizeBytes.ts
new file mode 100644
index 0000000000..0d1d8a5cda
--- /dev/null
+++ b/js/app/packages/service-email/generated/schemas/apiAttachmentSizeBytes.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiAttachmentSizeBytes = number | null;
diff --git a/js/app/packages/service-email/generated/schemas/apiContact.ts b/js/app/packages/service-email/generated/schemas/apiContact.ts
new file mode 100644
index 0000000000..820a0c8ada
--- /dev/null
+++ b/js/app/packages/service-email/generated/schemas/apiContact.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ApiContactEmailAddress } from './apiContactEmailAddress';
+import type { ApiContactName } from './apiContactName';
+import type { ApiContactSfsPhotoUrl } from './apiContactSfsPhotoUrl';
+
+export interface ApiContact {
+ emailAddress?: ApiContactEmailAddress;
+ id: string;
+ linkId: string;
+ name?: ApiContactName;
+ sfsPhotoUrl?: ApiContactSfsPhotoUrl;
+}
diff --git a/js/app/packages/service-email/generated/schemas/apiContactEmailAddress.ts b/js/app/packages/service-email/generated/schemas/apiContactEmailAddress.ts
new file mode 100644
index 0000000000..bbf4bf26a2
--- /dev/null
+++ b/js/app/packages/service-email/generated/schemas/apiContactEmailAddress.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiContactEmailAddress = string | null;
diff --git a/js/app/packages/service-email/generated/schemas/apiContactName.ts b/js/app/packages/service-email/generated/schemas/apiContactName.ts
new file mode 100644
index 0000000000..539b7ac4f2
--- /dev/null
+++ b/js/app/packages/service-email/generated/schemas/apiContactName.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiContactName = string | null;
diff --git a/js/app/packages/service-email/generated/schemas/apiContactSfsPhotoUrl.ts b/js/app/packages/service-email/generated/schemas/apiContactSfsPhotoUrl.ts
new file mode 100644
index 0000000000..9712e60c2c
--- /dev/null
+++ b/js/app/packages/service-email/generated/schemas/apiContactSfsPhotoUrl.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiContactSfsPhotoUrl = string | null;
diff --git a/js/app/packages/service-email/generated/schemas/apiPaginatedThreadCursor.ts b/js/app/packages/service-email/generated/schemas/apiPaginatedThreadCursor.ts
new file mode 100644
index 0000000000..e8513de473
--- /dev/null
+++ b/js/app/packages/service-email/generated/schemas/apiPaginatedThreadCursor.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ApiThreadPreviewCursor } from './apiThreadPreviewCursor';
+import type { ApiPaginatedThreadCursorNextCursor } from './apiPaginatedThreadCursorNextCursor';
+
+export interface ApiPaginatedThreadCursor {
+ items: ApiThreadPreviewCursor[];
+ next_cursor?: ApiPaginatedThreadCursorNextCursor;
+}
diff --git a/js/app/packages/service-email/generated/schemas/apiPaginatedThreadCursorNextCursor.ts b/js/app/packages/service-email/generated/schemas/apiPaginatedThreadCursorNextCursor.ts
new file mode 100644
index 0000000000..9c13be507e
--- /dev/null
+++ b/js/app/packages/service-email/generated/schemas/apiPaginatedThreadCursorNextCursor.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiPaginatedThreadCursorNextCursor = string | null;
diff --git a/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursor.ts b/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursor.ts
new file mode 100644
index 0000000000..024be66229
--- /dev/null
+++ b/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursor.ts
@@ -0,0 +1,10 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ApiThreadPreviewCursorInner } from './apiThreadPreviewCursorInner';
+import type { ApiThreadPreviewCursorAllOf } from './apiThreadPreviewCursorAllOf';
+
+export type ApiThreadPreviewCursor = ApiThreadPreviewCursorInner & ApiThreadPreviewCursorAllOf;
diff --git a/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursorAllOf.ts b/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursorAllOf.ts
new file mode 100644
index 0000000000..923f016f08
--- /dev/null
+++ b/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursorAllOf.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ApiAttachment } from './apiAttachment';
+import type { ApiContact } from './apiContact';
+import type { ApiThreadPreviewCursorAllOfFrecencyScore } from './apiThreadPreviewCursorAllOfFrecencyScore';
+import type { ApiAttachmentMacro } from './apiAttachmentMacro';
+
+export type ApiThreadPreviewCursorAllOf = {
+ attachments: ApiAttachment[];
+ contacts: ApiContact[];
+ frecencyScore?: ApiThreadPreviewCursorAllOfFrecencyScore;
+ macroAttachments: ApiAttachmentMacro[];
+};
diff --git a/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursorAllOfFrecencyScore.ts b/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursorAllOfFrecencyScore.ts
new file mode 100644
index 0000000000..c32d614d4f
--- /dev/null
+++ b/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursorAllOfFrecencyScore.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiThreadPreviewCursorAllOfFrecencyScore = number | null;
diff --git a/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursorInner.ts b/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursorInner.ts
new file mode 100644
index 0000000000..ce107475fb
--- /dev/null
+++ b/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursorInner.ts
@@ -0,0 +1,32 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ApiThreadPreviewCursorInnerName } from './apiThreadPreviewCursorInnerName';
+import type { ApiThreadPreviewCursorInnerProviderId } from './apiThreadPreviewCursorInnerProviderId';
+import type { ApiThreadPreviewCursorInnerSenderEmail } from './apiThreadPreviewCursorInnerSenderEmail';
+import type { ApiThreadPreviewCursorInnerSenderName } from './apiThreadPreviewCursorInnerSenderName';
+import type { ApiThreadPreviewCursorInnerSenderPhotoUrl } from './apiThreadPreviewCursorInnerSenderPhotoUrl';
+import type { ApiThreadPreviewCursorInnerSnippet } from './apiThreadPreviewCursorInnerSnippet';
+import type { ApiThreadPreviewCursorInnerViewedAt } from './apiThreadPreviewCursorInnerViewedAt';
+
+export interface ApiThreadPreviewCursorInner {
+ createdAt: number;
+ id: string;
+ inboxVisible: boolean;
+ isDraft: boolean;
+ isImportant: boolean;
+ isRead: boolean;
+ name?: ApiThreadPreviewCursorInnerName;
+ ownerId: string;
+ providerId?: ApiThreadPreviewCursorInnerProviderId;
+ senderEmail?: ApiThreadPreviewCursorInnerSenderEmail;
+ senderName?: ApiThreadPreviewCursorInnerSenderName;
+ senderPhotoUrl?: ApiThreadPreviewCursorInnerSenderPhotoUrl;
+ snippet?: ApiThreadPreviewCursorInnerSnippet;
+ sortTs: number;
+ updatedAt: number;
+ viewedAt: ApiThreadPreviewCursorInnerViewedAt;
+}
diff --git a/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursorInnerName.ts b/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursorInnerName.ts
new file mode 100644
index 0000000000..56b502590f
--- /dev/null
+++ b/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursorInnerName.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiThreadPreviewCursorInnerName = string | null;
diff --git a/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursorInnerProviderId.ts b/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursorInnerProviderId.ts
new file mode 100644
index 0000000000..82048e1597
--- /dev/null
+++ b/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursorInnerProviderId.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiThreadPreviewCursorInnerProviderId = string | null;
diff --git a/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursorInnerSenderEmail.ts b/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursorInnerSenderEmail.ts
new file mode 100644
index 0000000000..64e8906bd3
--- /dev/null
+++ b/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursorInnerSenderEmail.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiThreadPreviewCursorInnerSenderEmail = string | null;
diff --git a/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursorInnerSenderName.ts b/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursorInnerSenderName.ts
new file mode 100644
index 0000000000..566a573997
--- /dev/null
+++ b/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursorInnerSenderName.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiThreadPreviewCursorInnerSenderName = string | null;
diff --git a/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursorInnerSenderPhotoUrl.ts b/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursorInnerSenderPhotoUrl.ts
new file mode 100644
index 0000000000..f146c76872
--- /dev/null
+++ b/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursorInnerSenderPhotoUrl.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiThreadPreviewCursorInnerSenderPhotoUrl = string | null;
diff --git a/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursorInnerSnippet.ts b/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursorInnerSnippet.ts
new file mode 100644
index 0000000000..5123eb3db8
--- /dev/null
+++ b/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursorInnerSnippet.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiThreadPreviewCursorInnerSnippet = string | null;
diff --git a/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursorInnerViewedAt.ts b/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursorInnerViewedAt.ts
new file mode 100644
index 0000000000..1a0cd13a80
--- /dev/null
+++ b/js/app/packages/service-email/generated/schemas/apiThreadPreviewCursorInnerViewedAt.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiThreadPreviewCursorInnerViewedAt = number | null;
diff --git a/js/app/packages/service-email/generated/schemas/backfillJob.ts b/js/app/packages/service-email/generated/schemas/backfillJob.ts
index e4f76f7731..7b2fe66556 100644
--- a/js/app/packages/service-email/generated/schemas/backfillJob.ts
+++ b/js/app/packages/service-email/generated/schemas/backfillJob.ts
@@ -13,17 +13,9 @@ export interface BackfillJob {
fusionauth_user_id: string;
id: string;
link_id?: BackfillJobLinkId;
- messages_failed_count: number;
- messages_processed_count: number;
- messages_retrieved_count: number;
- messages_succeeded_count: number;
status: BackfillJobStatus;
- threads_failed_count: number;
- threads_processed_count: number;
threads_requested_limit?: BackfillJobThreadsRequestedLimit;
threads_retrieved_count: number;
- threads_skipped_count: number;
- threads_succeeded_count: number;
total_threads: number;
updated_at: string;
}
diff --git a/js/app/packages/service-email/generated/schemas/getActiveBackfillJobResponse.ts b/js/app/packages/service-email/generated/schemas/getActiveBackfillJobResponse.ts
new file mode 100644
index 0000000000..1203cdcd26
--- /dev/null
+++ b/js/app/packages/service-email/generated/schemas/getActiveBackfillJobResponse.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { BackfillJob } from './backfillJob';
+
+/**
+ * The response returned from the get backfill job endpoint
+ */
+export interface GetActiveBackfillJobResponse {
+ job: BackfillJob;
+}
diff --git a/js/app/packages/service-email/generated/schemas/getPreviewsCursorParams.ts b/js/app/packages/service-email/generated/schemas/getPreviewsCursorParams.ts
new file mode 100644
index 0000000000..9f16ce53a7
--- /dev/null
+++ b/js/app/packages/service-email/generated/schemas/getPreviewsCursorParams.ts
@@ -0,0 +1,20 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { GetPreviewsCursorParamsLimit } from './getPreviewsCursorParamsLimit';
+import type { GetPreviewsCursorParamsSortMethod } from './getPreviewsCursorParamsSortMethod';
+
+/**
+ * Parameters for getting thread previews with cursor-based pagination.
+ */
+export interface GetPreviewsCursorParams {
+ /**
+ * Limit for pagination. Default is 20. Max is 500.
+ * @minimum 0
+ */
+ limit?: GetPreviewsCursorParamsLimit;
+ sort_method?: GetPreviewsCursorParamsSortMethod;
+}
diff --git a/js/app/packages/service-email/generated/schemas/getPreviewsCursorParamsLimit.ts b/js/app/packages/service-email/generated/schemas/getPreviewsCursorParamsLimit.ts
new file mode 100644
index 0000000000..79b9eb838d
--- /dev/null
+++ b/js/app/packages/service-email/generated/schemas/getPreviewsCursorParamsLimit.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Limit for pagination. Default is 20. Max is 500.
+ * @minimum 0
+ */
+export type GetPreviewsCursorParamsLimit = number | null;
diff --git a/js/app/packages/service-email/generated/schemas/getPreviewsCursorParamsSortMethod.ts b/js/app/packages/service-email/generated/schemas/getPreviewsCursorParamsSortMethod.ts
new file mode 100644
index 0000000000..236684f95b
--- /dev/null
+++ b/js/app/packages/service-email/generated/schemas/getPreviewsCursorParamsSortMethod.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ApiSortMethod } from './apiSortMethod';
+
+export type GetPreviewsCursorParamsSortMethod = null | ApiSortMethod;
diff --git a/js/app/packages/service-email/generated/schemas/getPreviewsCursorResponse.ts b/js/app/packages/service-email/generated/schemas/getPreviewsCursorResponse.ts
deleted file mode 100644
index 1a5c556f6c..0000000000
--- a/js/app/packages/service-email/generated/schemas/getPreviewsCursorResponse.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * email_service
- * OpenAPI spec version: 0.1.0
- */
-import type { PaginatedThreadCursor } from './paginatedThreadCursor';
-
-export interface GetPreviewsCursorResponse {
- /** the thread, with messages inside */
- previews: PaginatedThreadCursor;
-}
diff --git a/js/app/packages/service-email/generated/schemas/getPreviewsFrecencyResponse.ts b/js/app/packages/service-email/generated/schemas/getPreviewsFrecencyResponse.ts
deleted file mode 100644
index 0ff4ded624..0000000000
--- a/js/app/packages/service-email/generated/schemas/getPreviewsFrecencyResponse.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * email_service
- * OpenAPI spec version: 0.1.0
- */
-import type { ThreadPreviewPagination } from './threadPreviewPagination';
-
-export interface GetPreviewsFrecencyResponse {
- /** the thread, with messages inside */
- previews: ThreadPreviewPagination;
-}
diff --git a/js/app/packages/service-email/generated/schemas/index.ts b/js/app/packages/service-email/generated/schemas/index.ts
index 53a456ea29..30d163497e 100644
--- a/js/app/packages/service-email/generated/schemas/index.ts
+++ b/js/app/packages/service-email/generated/schemas/index.ts
@@ -11,7 +11,31 @@ export * from './aPIThreadLatestInboundMessageTs';
export * from './aPIThreadLatestNonSpamMessageTs';
export * from './aPIThreadLatestOutboundMessageTs';
export * from './aPIThreadProviderId';
+export * from './apiAttachment';
+export * from './apiAttachmentContentId';
+export * from './apiAttachmentFilename';
+export * from './apiAttachmentMacro';
+export * from './apiAttachmentMimeType';
+export * from './apiAttachmentProviderAttachmentId';
+export * from './apiAttachmentSizeBytes';
+export * from './apiContact';
+export * from './apiContactEmailAddress';
+export * from './apiContactName';
+export * from './apiContactSfsPhotoUrl';
+export * from './apiPaginatedThreadCursor';
+export * from './apiPaginatedThreadCursorNextCursor';
export * from './apiSortMethod';
+export * from './apiThreadPreviewCursor';
+export * from './apiThreadPreviewCursorAllOf';
+export * from './apiThreadPreviewCursorAllOfFrecencyScore';
+export * from './apiThreadPreviewCursorInner';
+export * from './apiThreadPreviewCursorInnerName';
+export * from './apiThreadPreviewCursorInnerProviderId';
+export * from './apiThreadPreviewCursorInnerSenderEmail';
+export * from './apiThreadPreviewCursorInnerSenderName';
+export * from './apiThreadPreviewCursorInnerSenderPhotoUrl';
+export * from './apiThreadPreviewCursorInnerSnippet';
+export * from './apiThreadPreviewCursorInnerViewedAt';
export * from './archiveThreadRequest';
export * from './attachment';
export * from './attachmentContentId';
@@ -49,13 +73,16 @@ export * from './createLabelRequest';
export * from './createLabelResponse';
export * from './emptyResponse';
export * from './errorResponse';
+export * from './getActiveBackfillJobResponse';
export * from './getAttachmentResponse';
export * from './getBackfillJobResponse';
-export * from './getPreviewsCursorResponse';
-export * from './getPreviewsFrecencyResponse';
+export * from './getPreviewsCursorParams';
+export * from './getPreviewsCursorParamsLimit';
+export * from './getPreviewsCursorParamsSortMethod';
export * from './getThreadMessagesHandlerParams';
export * from './getThreadParams';
export * from './getThreadResponse';
+export * from './initResponse';
export * from './label';
export * from './labelId';
export * from './labelInfo';
@@ -109,8 +136,6 @@ export * from './messageToSendTo';
export * from './messageWithBodyReplyless';
export * from './messageWithBodyReplylessAllOf';
export * from './messageWithBodyReplylessAllOfBodyReplyless';
-export * from './paginatedThreadCursor';
-export * from './paginatedThreadCursorNextCursor';
export * from './parsedMessage';
export * from './parsedMessageBodyParsed';
export * from './parsedMessageFrom';
@@ -136,10 +161,6 @@ export * from './threadPreviewCursorSenderName';
export * from './threadPreviewCursorSenderPhotoUrl';
export * from './threadPreviewCursorSnippet';
export * from './threadPreviewCursorViewedAt';
-export * from './threadPreviewFrecency';
-export * from './threadPreviewFrecencyAllOf';
-export * from './threadPreviewPagination';
-export * from './threadPreviewPaginationNextCursor';
export * from './threadProviderId';
export * from './threadSummary';
export * from './updateLabelBatchRequest';
diff --git a/js/app/packages/service-email/generated/schemas/initResponse.ts b/js/app/packages/service-email/generated/schemas/initResponse.ts
new file mode 100644
index 0000000000..67cfc3a162
--- /dev/null
+++ b/js/app/packages/service-email/generated/schemas/initResponse.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export interface InitResponse {
+ backfill_job_id: string;
+ link_id: string;
+}
diff --git a/js/app/packages/service-email/generated/schemas/message.ts b/js/app/packages/service-email/generated/schemas/message.ts
index 7fb95e1c76..4d667a5f55 100644
--- a/js/app/packages/service-email/generated/schemas/message.ts
+++ b/js/app/packages/service-email/generated/schemas/message.ts
@@ -4,28 +4,28 @@
* email_service
* OpenAPI spec version: 0.1.0
*/
-import type { Attachment } from './attachment';
-import type { AttachmentMacro } from './attachmentMacro';
-import type { ContactInfo } from './contactInfo';
-import type { MessageBodyHtmlSanitized } from './messageBodyHtmlSanitized';
-import type { MessageBodyMacro } from './messageBodyMacro';
-import type { MessageBodyText } from './messageBodyText';
-import type { MessageDbId } from './messageDbId';
-import type { MessageFrom } from './messageFrom';
-import type { MessageGlobalId } from './messageGlobalId';
-import type { MessageHeadersJson } from './messageHeadersJson';
-import type { MessageInternalDateTs } from './messageInternalDateTs';
import type { Label } from './label';
-import type { MessageProviderHistoryId } from './messageProviderHistoryId';
-import type { MessageProviderId } from './messageProviderId';
-import type { MessageProviderThreadId } from './messageProviderThreadId';
-import type { MessageReplyingToId } from './messageReplyingToId';
-import type { MessageScheduledSendTime } from './messageScheduledSendTime';
-import type { MessageSentAt } from './messageSentAt';
-import type { MessageSizeEstimate } from './messageSizeEstimate';
-import type { MessageSnippet } from './messageSnippet';
-import type { MessageSubject } from './messageSubject';
import type { MessageThreadDbId } from './messageThreadDbId';
+import type { MessageSubject } from './messageSubject';
+import type { MessageSnippet } from './messageSnippet';
+import type { MessageSizeEstimate } from './messageSizeEstimate';
+import type { MessageSentAt } from './messageSentAt';
+import type { MessageScheduledSendTime } from './messageScheduledSendTime';
+import type { MessageReplyingToId } from './messageReplyingToId';
+import type { MessageProviderThreadId } from './messageProviderThreadId';
+import type { MessageProviderId } from './messageProviderId';
+import type { MessageProviderHistoryId } from './messageProviderHistoryId';
+import type { Attachment } from './attachment';
+import type { MessageInternalDateTs } from './messageInternalDateTs';
+import type { MessageHeadersJson } from './messageHeadersJson';
+import type { MessageGlobalId } from './messageGlobalId';
+import type { MessageFrom } from './messageFrom';
+import type { MessageDbId } from './messageDbId';
+import type { MessageBodyText } from './messageBodyText';
+import type { MessageBodyMacro } from './messageBodyMacro';
+import type { MessageBodyHtmlSanitized } from './messageBodyHtmlSanitized';
+import type { ContactInfo } from './contactInfo';
+import type { AttachmentMacro } from './attachmentMacro';
export interface Message {
attachments: Attachment[];
diff --git a/js/app/packages/service-email/generated/schemas/paginatedThreadCursor.ts b/js/app/packages/service-email/generated/schemas/paginatedThreadCursor.ts
deleted file mode 100644
index 49318a3c8a..0000000000
--- a/js/app/packages/service-email/generated/schemas/paginatedThreadCursor.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * email_service
- * OpenAPI spec version: 0.1.0
- */
-import type { ThreadPreviewCursor } from './threadPreviewCursor';
-import type { PaginatedThreadCursorNextCursor } from './paginatedThreadCursorNextCursor';
-
-export interface PaginatedThreadCursor {
- items: ThreadPreviewCursor[];
- next_cursor?: PaginatedThreadCursorNextCursor;
-}
diff --git a/js/app/packages/service-email/generated/schemas/threadPreviewFrecency.ts b/js/app/packages/service-email/generated/schemas/threadPreviewFrecency.ts
deleted file mode 100644
index a4d53ecf0d..0000000000
--- a/js/app/packages/service-email/generated/schemas/threadPreviewFrecency.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * email_service
- * OpenAPI spec version: 0.1.0
- */
-import type { ThreadPreviewCursor } from './threadPreviewCursor';
-import type { ThreadPreviewFrecencyAllOf } from './threadPreviewFrecencyAllOf';
-
-export type ThreadPreviewFrecency = ThreadPreviewCursor & ThreadPreviewFrecencyAllOf;
diff --git a/js/app/packages/service-email/generated/schemas/threadPreviewPagination.ts b/js/app/packages/service-email/generated/schemas/threadPreviewPagination.ts
deleted file mode 100644
index eec9379d25..0000000000
--- a/js/app/packages/service-email/generated/schemas/threadPreviewPagination.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * email_service
- * OpenAPI spec version: 0.1.0
- */
-import type { ThreadPreviewFrecency } from './threadPreviewFrecency';
-import type { ThreadPreviewPaginationNextCursor } from './threadPreviewPaginationNextCursor';
-
-export interface ThreadPreviewPagination {
- items: ThreadPreviewFrecency[];
- next_cursor?: ThreadPreviewPaginationNextCursor;
-}
diff --git a/js/app/packages/service-email/openapi.json b/js/app/packages/service-email/openapi.json
index 6826923778..c5b364571e 100644
--- a/js/app/packages/service-email/openapi.json
+++ b/js/app/packages/service-email/openapi.json
@@ -120,6 +120,49 @@
}
}
},
+ "/email/backfill/gmail/active": {
+ "get": {
+ "tags": ["Init"],
+ "summary": "Get any active backfill job for the user.",
+ "operationId": "get_backfill_gmail_active",
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GetActiveBackfillJobResponse"
+ }
+ }
+ }
+ },
+ "204": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/EmptyResponse" }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/ErrorResponse" }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/ErrorResponse" }
+ }
+ }
+ }
+ }
+ }
+ },
"/email/backfill/gmail/{id}": {
"get": {
"tags": ["Init"],
@@ -135,7 +178,7 @@
}
],
"responses": {
- "201": {
+ "200": {
"description": "",
"content": {
"application/json": {
@@ -145,7 +188,7 @@
}
}
},
- "404": {
+ "401": {
"description": "",
"content": {
"application/json": {
@@ -153,7 +196,7 @@
}
}
},
- "429": {
+ "404": {
"description": "",
"content": {
"application/json": {
@@ -908,7 +951,7 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/GetPreviewsFrecencyResponse"
+ "$ref": "#/components/schemas/ApiPaginatedThreadCursor"
}
}
}
@@ -1253,11 +1296,117 @@
"updated_at": { "type": "string", "format": "date-time" }
}
},
+ "ApiAttachment": {
+ "type": "object",
+ "required": ["id", "messageId", "createdAt"],
+ "properties": {
+ "contentId": { "type": ["string", "null"] },
+ "createdAt": { "type": "integer", "format": "int64" },
+ "filename": { "type": ["string", "null"] },
+ "id": { "type": "string", "format": "uuid" },
+ "messageId": { "type": "string", "format": "uuid" },
+ "mimeType": { "type": ["string", "null"] },
+ "providerAttachmentId": { "type": ["string", "null"] },
+ "sizeBytes": { "type": ["integer", "null"], "format": "int64" }
+ }
+ },
+ "ApiAttachmentMacro": {
+ "type": "object",
+ "required": ["dbId", "messageId", "itemId", "itemType"],
+ "properties": {
+ "dbId": { "type": "string", "format": "uuid" },
+ "itemId": { "type": "string", "format": "uuid" },
+ "itemType": { "type": "string" },
+ "messageId": { "type": "string", "format": "uuid" }
+ }
+ },
+ "ApiContact": {
+ "type": "object",
+ "required": ["id", "linkId"],
+ "properties": {
+ "emailAddress": { "type": ["string", "null"] },
+ "id": { "type": "string", "format": "uuid" },
+ "linkId": { "type": "string", "format": "uuid" },
+ "name": { "type": ["string", "null"] },
+ "sfsPhotoUrl": { "type": ["string", "null"] }
+ }
+ },
+ "ApiPaginatedThreadCursor": {
+ "type": "object",
+ "required": ["items"],
+ "properties": {
+ "items": {
+ "type": "array",
+ "items": { "$ref": "#/components/schemas/ApiThreadPreviewCursor" }
+ },
+ "next_cursor": { "type": ["string", "null"] }
+ }
+ },
"ApiSortMethod": {
"type": "string",
"description": "common types of sorts based on timestamps",
"enum": ["viewed_at", "updated_at", "created_at", "viewed_updated"]
},
+ "ApiThreadPreviewCursor": {
+ "allOf": [
+ { "$ref": "#/components/schemas/ApiThreadPreviewCursorInner" },
+ {
+ "type": "object",
+ "required": ["attachments", "macroAttachments", "contacts"],
+ "properties": {
+ "attachments": {
+ "type": "array",
+ "items": { "$ref": "#/components/schemas/ApiAttachment" }
+ },
+ "contacts": {
+ "type": "array",
+ "items": { "$ref": "#/components/schemas/ApiContact" }
+ },
+ "frecencyScore": {
+ "type": ["number", "null"],
+ "format": "double"
+ },
+ "macroAttachments": {
+ "type": "array",
+ "items": { "$ref": "#/components/schemas/ApiAttachmentMacro" }
+ }
+ }
+ }
+ ]
+ },
+ "ApiThreadPreviewCursorInner": {
+ "type": "object",
+ "required": [
+ "id",
+ "ownerId",
+ "inboxVisible",
+ "isRead",
+ "isDraft",
+ "isImportant",
+ "sortTs",
+ "createdAt",
+ "updatedAt",
+ "viewedAt"
+ ],
+ "properties": {
+ "createdAt": { "type": "integer", "format": "int64" },
+ "id": { "type": "string", "format": "uuid" },
+ "inboxVisible": { "type": "boolean" },
+ "isDraft": { "type": "boolean" },
+ "isImportant": { "type": "boolean" },
+ "isRead": { "type": "boolean" },
+ "name": { "type": ["string", "null"] },
+ "ownerId": { "type": "string" },
+ "providerId": { "type": ["string", "null"] },
+ "senderEmail": { "type": ["string", "null"] },
+ "senderName": { "type": ["string", "null"] },
+ "senderPhotoUrl": { "type": ["string", "null"] },
+ "snippet": { "type": ["string", "null"] },
+ "sortTs": { "type": "integer", "format": "int64" },
+ "updatedAt": { "type": "integer", "format": "int64" },
+ "viewedAt": { "type": ["integer", "null"], "format": "int64" }
+ }
+ },
"ArchiveThreadRequest": {
"type": "object",
"required": ["value"],
@@ -1295,14 +1444,6 @@
"total_threads",
"status",
"threads_retrieved_count",
- "threads_processed_count",
- "messages_retrieved_count",
- "messages_processed_count",
- "threads_succeeded_count",
- "threads_skipped_count",
- "threads_failed_count",
- "messages_succeeded_count",
- "messages_failed_count",
"created_at",
"updated_at"
],
@@ -1311,20 +1452,12 @@
"fusionauth_user_id": { "type": "string" },
"id": { "type": "string", "format": "uuid" },
"link_id": { "type": ["string", "null"], "format": "uuid" },
- "messages_failed_count": { "type": "integer", "format": "int32" },
- "messages_processed_count": { "type": "integer", "format": "int32" },
- "messages_retrieved_count": { "type": "integer", "format": "int32" },
- "messages_succeeded_count": { "type": "integer", "format": "int32" },
"status": { "$ref": "#/components/schemas/BackfillJobStatus" },
- "threads_failed_count": { "type": "integer", "format": "int32" },
- "threads_processed_count": { "type": "integer", "format": "int32" },
"threads_requested_limit": {
"type": ["integer", "null"],
"format": "int32"
},
"threads_retrieved_count": { "type": "integer", "format": "int32" },
- "threads_skipped_count": { "type": "integer", "format": "int32" },
- "threads_succeeded_count": { "type": "integer", "format": "int32" },
"total_threads": { "type": "integer", "format": "int32" },
"updated_at": { "type": "string", "format": "date-time" }
}
@@ -1427,6 +1560,12 @@
}
}
},
+ "GetActiveBackfillJobResponse": {
+ "type": "object",
+ "description": "The response returned from the get backfill job endpoint",
+ "required": ["job"],
+ "properties": { "job": { "$ref": "#/components/schemas/BackfillJob" } }
+ },
"GetAttachmentResponse": {
"type": "object",
"description": "The response returned from the get attachment endpoint",
@@ -1441,23 +1580,24 @@
"required": ["job"],
"properties": { "job": { "$ref": "#/components/schemas/BackfillJob" } }
},
- "GetPreviewsCursorResponse": {
- "type": "object",
- "required": ["previews"],
- "properties": {
- "previews": {
- "$ref": "#/components/schemas/PaginatedThreadCursor",
- "description": "the thread, with messages inside"
- }
- }
- },
- "GetPreviewsFrecencyResponse": {
+ "GetPreviewsCursorParams": {
"type": "object",
- "required": ["previews"],
+ "description": "Parameters for getting thread previews with cursor-based pagination.",
"properties": {
- "previews": {
- "$ref": "#/components/schemas/ThreadPreviewPagination",
- "description": "the thread, with messages inside"
+ "limit": {
+ "type": ["integer", "null"],
+ "format": "int32",
+ "description": "Limit for pagination. Default is 20. Max is 500.",
+ "minimum": 0
+ },
+ "sort_method": {
+ "oneOf": [
+ { "type": "null" },
+ {
+ "$ref": "#/components/schemas/ApiSortMethod",
+ "description": "Sort method. Options are viewed_at, created_at, updated_at, viewed_updated. Defaults to viewed_updated."
+ }
+ ]
}
}
},
@@ -1472,6 +1612,14 @@
}
}
},
+ "InitResponse": {
+ "type": "object",
+ "required": ["link_id", "backfill_job_id"],
+ "properties": {
+ "backfill_job_id": { "type": "string", "format": "uuid" },
+ "link_id": { "type": "string", "format": "uuid" }
+ }
+ },
"Label": {
"type": "object",
"required": ["link_id", "provider_label_id", "created_at"],
@@ -1719,17 +1867,6 @@
}
]
},
- "PaginatedThreadCursor": {
- "type": "object",
- "required": ["items"],
- "properties": {
- "items": {
- "type": "array",
- "items": { "$ref": "#/components/schemas/ThreadPreviewCursor" }
- },
- "next_cursor": { "type": ["string", "null"] }
- }
- },
"ParsedMessage": {
"type": "object",
"required": [
@@ -1916,29 +2053,6 @@
"viewedAt": { "type": ["integer", "null"], "format": "int64" }
}
},
- "ThreadPreviewFrecency": {
- "allOf": [
- { "$ref": "#/components/schemas/ThreadPreviewCursor" },
- {
- "type": "object",
- "required": ["frecency_score"],
- "properties": {
- "frecency_score": { "type": "number", "format": "double" }
- }
- }
- ]
- },
- "ThreadPreviewPagination": {
- "type": "object",
- "required": ["items"],
- "properties": {
- "items": {
- "type": "array",
- "items": { "$ref": "#/components/schemas/ThreadPreviewFrecency" }
- },
- "next_cursor": { "type": ["string", "null"] }
- }
- },
"ThreadSummary": {
"type": "object",
"required": ["provider_id"],
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index c214043045..86ecc79864 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -85,6 +85,7 @@ dependencies = [
"async-trait",
"chrono",
"cool_asserts",
+ "email",
"email_service_client",
"insight_service_client",
"lazy_static",
@@ -2785,6 +2786,32 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "email"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "axum",
+ "chrono",
+ "frecency",
+ "macro_user_id",
+ "model-entity",
+ "model-error-response",
+ "model_user",
+ "models_pagination",
+ "schemars",
+ "serde",
+ "serde_json",
+ "serde_with",
+ "sqlx",
+ "strum",
+ "thiserror 2.0.17",
+ "tokio",
+ "tracing",
+ "utoipa",
+ "uuid",
+]
+
[[package]]
name = "email_db_client"
version = "0.1.0"
@@ -2858,6 +2885,7 @@ dependencies = [
"connection_gateway",
"document_storage_service_client",
"ego-tree",
+ "email",
"email_db_client",
"frecency",
"futures",
@@ -2914,6 +2942,7 @@ name = "email_service_client"
version = "0.1.0"
dependencies = [
"anyhow",
+ "email",
"model",
"models_email",
"reqwest",
@@ -7150,6 +7179,7 @@ dependencies = [
"schemars_derive",
"serde",
"serde_json",
+ "uuid",
]
[[package]]
diff --git a/rust/cloud-storage/ai_tools/Cargo.toml b/rust/cloud-storage/ai_tools/Cargo.toml
index b434fbb97a..e542489746 100644
--- a/rust/cloud-storage/ai_tools/Cargo.toml
+++ b/rust/cloud-storage/ai_tools/Cargo.toml
@@ -9,6 +9,7 @@ ai = { path = "../ai" }
anyhow.workspace = true
async-trait.workspace = true
chrono.workspace = true
+email = { path = "../email", features = ["ai_schema", "axum"] }
email_service_client = { path = "../email_service_client" }
insight_service_client = { path = "../insight_service_client" }
lazy_static.workspace = true
diff --git a/rust/cloud-storage/ai_tools/src/list/email/tests.rs b/rust/cloud-storage/ai_tools/src/list/email/tests.rs
index fae869e993..a352530082 100644
--- a/rust/cloud-storage/ai_tools/src/list/email/tests.rs
+++ b/rust/cloud-storage/ai_tools/src/list/email/tests.rs
@@ -2,7 +2,8 @@ use super::tool::*;
use ai::generate_tool_input_schema;
use ai::tool::types::toolset::tool_object::validate_tool_schema;
use cool_asserts::assert_matches;
-use models_email::service::thread::{GetPreviewsCursorResponse, PreviewViewStandardLabel};
+use email::inbound::ApiPaginatedThreadCursor;
+use models_email::service::thread::PreviewViewStandardLabel;
// run `cargo test -p ai_tools list::email::tests::print_input_schema -- --nocapture --include-ignored`
#[test]
@@ -17,7 +18,7 @@ fn print_input_schema() {
#[ignore = "prints the output schema"]
fn print_output_schema() {
let generator = ai::tool::minimized_output_schema_generator();
- let schema = generator.into_root_schema_for::<GetPreviewsCursorResponse>();
+ let schema = generator.into_root_schema_for::<ApiPaginatedThreadCursor>();
println!("{}", serde_json::to_string_pretty(&schema).unwrap());
}
diff --git a/rust/cloud-storage/ai_tools/src/list/email/tool.rs b/rust/cloud-storage/ai_tools/src/list/email/tool.rs
index fe8fbcab0d..c78c8eec4c 100644
--- a/rust/cloud-storage/ai_tools/src/list/email/tool.rs
+++ b/rust/cloud-storage/ai_tools/src/list/email/tool.rs
@@ -1,9 +1,9 @@
use crate::{RequestContext, ToolServiceContext};
use ai::tool::{AsyncTool, ToolCallError, ToolResult};
use async_trait::async_trait;
+use email::inbound::ApiPaginatedThreadCursor;
use models_email::{
- email::service::thread::{GetPreviewsCursorResponse, PreviewView},
- service::thread::PreviewViewStandardLabel,
+ email::service::thread::PreviewView, service::thread::PreviewViewStandardLabel,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
@@ -94,7 +94,7 @@ impl ListEmails {
#[async_trait]
impl AsyncTool<ToolServiceContext, RequestContext> for ListEmails {
- type Output = GetPreviewsCursorResponse;
+ type Output = ApiPaginatedThreadCursor;
#[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]
async fn call(
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
index 17880e9dc6..fe54a9df38 100644
--- a/rust/cloud-storage/comms_service/src/api/channels/get_channels.rs
+++ b/rust/cloud-storage/comms_service/src/api/channels/get_channels.rs
@@ -71,6 +71,11 @@ pub async fn get_channels_handler(
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
@@ -79,9 +84,7 @@ pub async fn get_channels_handler(
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(),
- channel_ids
- .iter()
- .map(|id| EntityType::Channel.with_entity_string(id.to_string()))
+ ids.as_slice()
)
);
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-2a0ed7f36910e68da7fecb81e4ffae480bca219234b64579ca7e2e9e0f3f26bc.json b/rust/cloud-storage/email/.sqlx/query-2a0ed7f36910e68da7fecb81e4ffae480bca219234b64579ca7e2e9e0f3f26bc.json
similarity index 100%
rename from rust/cloud-storage/email_db_client/.sqlx/query-2a0ed7f36910e68da7fecb81e4ffae480bca219234b64579ca7e2e9e0f3f26bc.json
rename to rust/cloud-storage/email/.sqlx/query-2a0ed7f36910e68da7fecb81e4ffae480bca219234b64579ca7e2e9e0f3f26bc.json
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-336aefc215f5d215bab6111625d9fb3cc4c5645a6f5265d89ec80b18a37a1885.json b/rust/cloud-storage/email/.sqlx/query-336aefc215f5d215bab6111625d9fb3cc4c5645a6f5265d89ec80b18a37a1885.json
similarity index 100%
rename from rust/cloud-storage/email_db_client/.sqlx/query-336aefc215f5d215bab6111625d9fb3cc4c5645a6f5265d89ec80b18a37a1885.json
rename to rust/cloud-storage/email/.sqlx/query-336aefc215f5d215bab6111625d9fb3cc4c5645a6f5265d89ec80b18a37a1885.json
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-3cf772774d34ffc5d82677bc07146a002778c0fdccdd646c8ed985a62c3f1c25.json b/rust/cloud-storage/email/.sqlx/query-3cf772774d34ffc5d82677bc07146a002778c0fdccdd646c8ed985a62c3f1c25.json
similarity index 100%
rename from rust/cloud-storage/email_db_client/.sqlx/query-3cf772774d34ffc5d82677bc07146a002778c0fdccdd646c8ed985a62c3f1c25.json
rename to rust/cloud-storage/email/.sqlx/query-3cf772774d34ffc5d82677bc07146a002778c0fdccdd646c8ed985a62c3f1c25.json
diff --git a/rust/cloud-storage/email/.sqlx/query-438ae6729b0b27fe7928b261fbf8a81d12562122d1824650497938280c3a2282.json b/rust/cloud-storage/email/.sqlx/query-438ae6729b0b27fe7928b261fbf8a81d12562122d1824650497938280c3a2282.json
new file mode 100644
index 0000000000..2267b9d7a2
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-438ae6729b0b27fe7928b261fbf8a81d12562122d1824650497938280c3a2282.json
@@ -0,0 +1,52 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n a.id,\n a.message_id,\n a.item_id as \"item_id!\",\n a.item_type as \"item_type!\",\n a.created_at,\n m.thread_id\n FROM\n email_attachments_macro a\n JOIN\n email_messages m ON a.message_id = m.id\n WHERE\n m.thread_id = ANY($1)\n ORDER BY\n a.created_at ASC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "message_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "item_id!",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 3,
+ "name": "item_type!",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 4,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "thread_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "438ae6729b0b27fe7928b261fbf8a81d12562122d1824650497938280c3a2282"
+}
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-4563540d4ca5a6db491f7c6e910040ee07750688a15330b35afd6e1733af290c.json b/rust/cloud-storage/email/.sqlx/query-4563540d4ca5a6db491f7c6e910040ee07750688a15330b35afd6e1733af290c.json
similarity index 100%
rename from rust/cloud-storage/email_db_client/.sqlx/query-4563540d4ca5a6db491f7c6e910040ee07750688a15330b35afd6e1733af290c.json
rename to rust/cloud-storage/email/.sqlx/query-4563540d4ca5a6db491f7c6e910040ee07750688a15330b35afd6e1733af290c.json
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-8238fc2dc450f7f0eef41226fe741229dd9d662c20d97d0677813f68ad085839.json b/rust/cloud-storage/email/.sqlx/query-8238fc2dc450f7f0eef41226fe741229dd9d662c20d97d0677813f68ad085839.json
similarity index 100%
rename from rust/cloud-storage/email_db_client/.sqlx/query-8238fc2dc450f7f0eef41226fe741229dd9d662c20d97d0677813f68ad085839.json
rename to rust/cloud-storage/email/.sqlx/query-8238fc2dc450f7f0eef41226fe741229dd9d662c20d97d0677813f68ad085839.json
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-829c2db98012d40c52a2cf134dd95cc0b7bfccc54ac7553f61317b008335a7e3.json b/rust/cloud-storage/email/.sqlx/query-829c2db98012d40c52a2cf134dd95cc0b7bfccc54ac7553f61317b008335a7e3.json
similarity index 100%
rename from rust/cloud-storage/email_db_client/.sqlx/query-829c2db98012d40c52a2cf134dd95cc0b7bfccc54ac7553f61317b008335a7e3.json
rename to rust/cloud-storage/email/.sqlx/query-829c2db98012d40c52a2cf134dd95cc0b7bfccc54ac7553f61317b008335a7e3.json
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-9c61638f515824a01ba7b8c62512c69d4d22f915517cc1ac645057e1dfb622c5.json b/rust/cloud-storage/email/.sqlx/query-9c61638f515824a01ba7b8c62512c69d4d22f915517cc1ac645057e1dfb622c5.json
similarity index 100%
rename from rust/cloud-storage/email_db_client/.sqlx/query-9c61638f515824a01ba7b8c62512c69d4d22f915517cc1ac645057e1dfb622c5.json
rename to rust/cloud-storage/email/.sqlx/query-9c61638f515824a01ba7b8c62512c69d4d22f915517cc1ac645057e1dfb622c5.json
diff --git a/rust/cloud-storage/email/.sqlx/query-e8ff98a61e6520835e18bc399b31968576c7c0117ac821236990033b29726eae.json b/rust/cloud-storage/email/.sqlx/query-e8ff98a61e6520835e18bc399b31968576c7c0117ac821236990033b29726eae.json
new file mode 100644
index 0000000000..a6c2a88613
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-e8ff98a61e6520835e18bc399b31968576c7c0117ac821236990033b29726eae.json
@@ -0,0 +1,52 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n m.thread_id,\n c.id, c.link_id, c.email_address, c.name, c.sfs_photo_url\n FROM email_messages m\n JOIN email_contacts c ON m.from_contact_id = c.id\n WHERE m.thread_id = ANY($1) AND m.from_contact_id IS NOT NULL\n ORDER BY m.created_at ASC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "thread_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "link_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 3,
+ "name": "email_address",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 4,
+ "name": "name",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 5,
+ "name": "sfs_photo_url",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ true,
+ true
+ ]
+ },
+ "hash": "e8ff98a61e6520835e18bc399b31968576c7c0117ac821236990033b29726eae"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-f29e4bf80c1ceb89a1b6169f39b83fe8f49d30d99a4308f9b3cae25fff097d82.json b/rust/cloud-storage/email/.sqlx/query-f29e4bf80c1ceb89a1b6169f39b83fe8f49d30d99a4308f9b3cae25fff097d82.json
new file mode 100644
index 0000000000..bb06211076
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-f29e4bf80c1ceb89a1b6169f39b83fe8f49d30d99a4308f9b3cae25fff097d82.json
@@ -0,0 +1,70 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT \n a.id,\n a.message_id,\n a.provider_attachment_id,\n a.filename,\n a.mime_type,\n a.size_bytes,\n a.content_id,\n a.created_at,\n m.thread_id\n FROM \n email_attachments a\n JOIN\n email_messages m ON a.message_id = m.id\n WHERE \n m.thread_id = ANY($1)\n ORDER BY \n a.created_at ASC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "message_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "provider_attachment_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "filename",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 4,
+ "name": "mime_type",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 5,
+ "name": "size_bytes",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 6,
+ "name": "content_id",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 7,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 8,
+ "name": "thread_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true,
+ true,
+ true,
+ true,
+ true,
+ false,
+ false
+ ]
+ },
+ "hash": "f29e4bf80c1ceb89a1b6169f39b83fe8f49d30d99a4308f9b3cae25fff097d82"
+}
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-f84dc707a2d49887f6b17e68799e747d9b1f7b2e059c3759cef6d71294230d7d.json b/rust/cloud-storage/email/.sqlx/query-f84dc707a2d49887f6b17e68799e747d9b1f7b2e059c3759cef6d71294230d7d.json
similarity index 100%
rename from rust/cloud-storage/email_db_client/.sqlx/query-f84dc707a2d49887f6b17e68799e747d9b1f7b2e059c3759cef6d71294230d7d.json
rename to rust/cloud-storage/email/.sqlx/query-f84dc707a2d49887f6b17e68799e747d9b1f7b2e059c3759cef6d71294230d7d.json
diff --git a/rust/cloud-storage/email/Cargo.toml b/rust/cloud-storage/email/Cargo.toml
new file mode 100644
index 0000000000..ffc0bbb9dd
--- /dev/null
+++ b/rust/cloud-storage/email/Cargo.toml
@@ -0,0 +1,40 @@
+[package]
+edition = "2024"
+name = "email"
+publish = false
+version = "0.1.0"
+
+[features]
+ai_schema = ["dep:schemars"]
+axum = [
+ "dep:axum",
+ "dep:model-error-response",
+ "dep:model_user",
+ "dep:utoipa",
+ "model_user/axum",
+ "models_pagination/axum",
+]
+
+[dependencies]
+anyhow = { workspace = true }
+axum = { workspace = true, optional = true }
+chrono = { workspace = true, features = ["serde"] }
+frecency = { path = "../frecency" }
+macro_user_id = { path = "../macro_user_id" }
+model-entity = { path = "../model-entity" }
+model-error-response = { path = "../model-error-response", optional = true }
+model_user = { path = "../model_user", optional = true }
+models_pagination = { path = "../models_pagination" }
+schemars = { workspace = true, optional = true, features = ["uuid1"] }
+serde = { workspace = true }
+serde_with = { workspace = true }
+sqlx = { workspace = true }
+strum = { workspace = true }
+thiserror = { workspace = true }
+tokio = { workspace = true, features = ["macros"] }
+tracing = { workspace = true }
+utoipa = { workspace = true, optional = true }
+uuid = { workspace = true }
+
+[dev-dependencies]
+serde_json = { workspace = true }
diff --git a/rust/cloud-storage/email/src/domain.rs b/rust/cloud-storage/email/src/domain.rs
new file mode 100644
index 0000000000..901e625fda
--- /dev/null
+++ b/rust/cloud-storage/email/src/domain.rs
@@ -0,0 +1,3 @@
+pub mod models;
+pub mod ports;
+pub mod service;
diff --git a/rust/cloud-storage/email/src/domain/models.rs b/rust/cloud-storage/email/src/domain/models.rs
new file mode 100644
index 0000000000..c19639b905
--- /dev/null
+++ b/rust/cloud-storage/email/src/domain/models.rs
@@ -0,0 +1,194 @@
+use frecency::domain::ports::FrecencyQueryErr;
+use macro_user_id::user_id::MacroUserIdStr;
+use models_pagination::{Identify, Query, SimpleSortMethod, SortOn};
+use serde_with::{DeserializeFromStr, SerializeDisplay};
+use sqlx::types::chrono::{DateTime, Utc};
+use std::str::FromStr;
+use strum::{Display, EnumString};
+use thiserror::Error;
+use uuid::Uuid;
+
+#[cfg(test)]
+mod tests;
+
+#[derive(Debug)]
+pub struct PreviewCursorQuery {
+ pub view: PreviewView,
+ pub link_id: Uuid,
+ pub limit: u32,
+ pub query: Query<Uuid, SimpleSortMethod, ()>,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, EnumString, Display)]
+#[strum(serialize_all = "lowercase", ascii_case_insensitive)]
+pub enum PreviewViewStandardLabel {
+ Inbox,
+ Sent,
+ Drafts,
+ Starred,
+ All,
+ Important,
+ Other,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, SerializeDisplay, DeserializeFromStr)]
+pub enum PreviewView {
+ StandardLabel(PreviewViewStandardLabel),
+ UserLabel(String),
+}
+
+impl std::fmt::Display for PreviewView {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ PreviewView::StandardLabel(label) => write!(f, "{}", label),
+ PreviewView::UserLabel(label) => write!(f, "user:{}", label),
+ }
+ }
+}
+
+impl FromStr for PreviewView {
+ type Err = String;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ match PreviewViewStandardLabel::from_str(s) {
+ Ok(label) => Ok(PreviewView::StandardLabel(label)),
+ Err(_) => match s.to_lowercase().as_str() {
+ s if s.starts_with("user:") => Ok(PreviewView::UserLabel(s[5..].to_string())),
+ _ => Err(format!("Unknown preview view: {}", s)),
+ },
+ }
+ }
+}
+
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct ThreadPreviewCursor {
+ pub id: Uuid,
+ pub provider_id: Option<String>,
+ pub owner_id: MacroUserIdStr<'static>,
+ pub inbox_visible: bool,
+ pub is_read: bool,
+ pub is_draft: bool,
+ pub is_important: bool,
+ pub name: Option<String>,
+ pub snippet: Option<String>,
+ pub sender_email: Option<String>,
+ pub sender_name: Option<String>,
+ pub sender_photo_url: Option<String>,
+ pub sort_ts: DateTime<Utc>,
+ pub created_at: DateTime<Utc>,
+ pub updated_at: DateTime<Utc>,
+ pub viewed_at: Option<DateTime<Utc>>,
+}
+
+#[non_exhaustive]
+pub struct EnrichedThreadPreviewCursor {
+ pub thread: ThreadPreviewCursor,
+ pub attachments: Vec<Attachment>,
+ pub attachments_macro: Vec<AttachmentMacro>,
+ pub frecency_score: Option<f64>,
+ pub participants: Vec<Contact>,
+}
+
+impl Identify for EnrichedThreadPreviewCursor {
+ type Id = Uuid;
+
+ fn id(&self) -> Self::Id {
+ self.thread.id
+ }
+}
+
+impl SortOn<SimpleSortMethod> for EnrichedThreadPreviewCursor {
+ fn sort_on(
+ sort: SimpleSortMethod,
+ ) -> impl FnOnce(&Self) -> models_pagination::CursorVal<SimpleSortMethod> {
+ move |v| {
+ let val = match sort {
+ SimpleSortMethod::ViewedAt => v.thread.viewed_at.unwrap_or_default(),
+ SimpleSortMethod::UpdatedAt => v.thread.updated_at,
+ SimpleSortMethod::CreatedAt => v.thread.created_at,
+ SimpleSortMethod::ViewedUpdated => {
+ v.thread.viewed_at.unwrap_or(v.thread.updated_at)
+ }
+ };
+
+ models_pagination::CursorVal {
+ sort_type: sort,
+ last_val: val,
+ }
+ }
+ }
+}
+
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct Attachment {
+ pub id: Uuid,
+ pub(crate) thread_id: Uuid,
+ pub message_id: Uuid,
+ // a different value is returned by the gmail API for this each time you fetch a message -
+ // don't make the mistake of using it to uniquely identify an attachment
+ pub provider_attachment_id: Option<String>,
+ pub filename: Option<String>,
+ pub mime_type: Option<String>,
+ pub size_bytes: Option<i64>,
+ pub content_id: Option<String>,
+ pub created_at: DateTime<Utc>,
+}
+
+impl Identify for Attachment {
+ type Id = Uuid;
+
+ fn id(&self) -> Self::Id {
+ self.id
+ }
+}
+
+/// Attachments of a message created when sending a message/draft through Macro FE. references
+/// a macro item (document, canvas, etc). These don't actually get sent to the provider when
+/// sending a message, but we store them so we can display the pills for the Macro objects in the FE
+/// when displaying the message.
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct AttachmentMacro {
+ pub thread_id: Uuid,
+ pub db_id: Uuid,
+ pub message_id: Uuid,
+ pub item_id: Uuid,
+ pub item_type: String,
+}
+
+impl Identify for AttachmentMacro {
+ type Id = Uuid;
+
+ fn id(&self) -> Self::Id {
+ self.thread_id
+ }
+}
+
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct Contact {
+ pub id: Uuid,
+ pub(crate) thread_id: Uuid,
+ pub link_id: Uuid,
+ pub name: Option<String>,
+ pub email_address: Option<String>,
+ pub sfs_photo_url: Option<String>,
+}
+
+#[derive(Debug, Error)]
+pub enum EmailErr {
+ #[error(transparent)]
+ RepoErr(#[from] anyhow::Error),
+ #[error(transparent)]
+ Frecency(#[from] FrecencyQueryErr),
+}
+
+pub struct GetEmailsRequest {
+ pub view: PreviewView,
+ pub link_id: Uuid,
+ pub macro_id: MacroUserIdStr<'static>,
+ pub limit: Option<u32>,
+ pub query: Query<Uuid, SimpleSortMethod, ()>,
+}
diff --git a/rust/cloud-storage/email/src/domain/models/tests.rs b/rust/cloud-storage/email/src/domain/models/tests.rs
new file mode 100644
index 0000000000..3eb4b2c509
--- /dev/null
+++ b/rust/cloud-storage/email/src/domain/models/tests.rs
@@ -0,0 +1,68 @@
+use super::*;
+
+#[test]
+fn test_preview_view_display() {
+ assert_eq!(
+ PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox).to_string(),
+ "inbox"
+ );
+ assert_eq!(
+ PreviewView::StandardLabel(PreviewViewStandardLabel::Sent).to_string(),
+ "sent"
+ );
+ assert_eq!(
+ PreviewView::UserLabel("mytag".to_string()).to_string(),
+ "user:mytag"
+ );
+}
+
+#[test]
+fn test_preview_view_from_str() {
+ assert_eq!(
+ PreviewView::from_str("inbox").unwrap(),
+ PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox)
+ );
+ assert_eq!(
+ PreviewView::from_str("SENT").unwrap(),
+ PreviewView::StandardLabel(PreviewViewStandardLabel::Sent)
+ );
+ assert_eq!(
+ PreviewView::from_str("user:mytag").unwrap(),
+ PreviewView::UserLabel("mytag".to_string())
+ );
+ assert!(PreviewView::from_str("invalid").is_err());
+}
+
+#[test]
+fn test_preview_view_serialization() {
+ assert_eq!(
+ serde_json::to_string(&PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox))
+ .unwrap(),
+ "\"inbox\""
+ );
+ assert_eq!(
+ serde_json::to_string(&PreviewView::StandardLabel(PreviewViewStandardLabel::Sent)).unwrap(),
+ "\"sent\""
+ );
+ assert_eq!(
+ serde_json::to_string(&PreviewView::UserLabel("mytag".to_string())).unwrap(),
+ "\"user:mytag\""
+ );
+}
+
+#[test]
+fn test_preview_view_deserialization() {
+ assert_eq!(
+ serde_json::from_str::<PreviewView>("\"inbox\"").unwrap(),
+ PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox)
+ );
+ assert_eq!(
+ serde_json::from_str::<PreviewView>("\"SENT\"").unwrap(),
+ PreviewView::StandardLabel(PreviewViewStandardLabel::Sent)
+ );
+ assert_eq!(
+ serde_json::from_str::<PreviewView>("\"user:mytag\"").unwrap(),
+ PreviewView::UserLabel("mytag".to_string())
+ );
+ assert!(serde_json::from_str::<PreviewView>("\"invalid\"").is_err());
+}
diff --git a/rust/cloud-storage/email/src/domain/ports.rs b/rust/cloud-storage/email/src/domain/ports.rs
new file mode 100644
index 0000000000..f32c506fd4
--- /dev/null
+++ b/rust/cloud-storage/email/src/domain/ports.rs
@@ -0,0 +1,43 @@
+use crate::domain::models::{
+ Attachment, AttachmentMacro, Contact, EmailErr, EnrichedThreadPreviewCursor, GetEmailsRequest,
+ PreviewCursorQuery, ThreadPreviewCursor,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+use models_pagination::{PaginatedCursor, SimpleSortMethod};
+use uuid::Uuid;
+
+pub trait EmailRepo: Send + Sync + 'static {
+ type Err: Send;
+ fn previews_for_view_cursor(
+ &self,
+ query: PreviewCursorQuery,
+ user_id: MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<Vec<ThreadPreviewCursor>, Self::Err>> + Send;
+
+ fn attachments_by_thread_ids(
+ &self,
+ thread_ids: &[Uuid],
+ ) -> impl Future<Output = Result<Vec<Attachment>, Self::Err>> + Send;
+
+ fn macro_attachments_by_thread_ids(
+ &self,
+ thread_ids: &[Uuid],
+ ) -> impl Future<Output = Result<Vec<AttachmentMacro>, Self::Err>> + Send;
+
+ fn contacts_by_thread_ids(
+ &self,
+ thread_ids: &[Uuid],
+ ) -> impl Future<Output = Result<Vec<Contact>, Self::Err>> + Send;
+}
+
+pub trait EmailService: Send + Sync + 'static {
+ fn get_email_thread_previews(
+ &self,
+ req: GetEmailsRequest,
+ ) -> impl Future<
+ Output = Result<
+ PaginatedCursor<EnrichedThreadPreviewCursor, Uuid, SimpleSortMethod, ()>,
+ EmailErr,
+ >,
+ > + Send;
+}
diff --git a/rust/cloud-storage/email/src/domain/service.rs b/rust/cloud-storage/email/src/domain/service.rs
new file mode 100644
index 0000000000..ae0cbae1e4
--- /dev/null
+++ b/rust/cloud-storage/email/src/domain/service.rs
@@ -0,0 +1,129 @@
+use crate::domain::{
+ models::{EmailErr, EnrichedThreadPreviewCursor, GetEmailsRequest, PreviewCursorQuery},
+ ports::{EmailRepo, EmailService},
+};
+use frecency::domain::{models::FrecencyByIdsRequest, ports::FrecencyQueryService};
+use macro_user_id::cowlike::CowLike;
+use model_entity::EntityType;
+use models_pagination::{CollectBy, PaginateOn, PaginatedCursor, SimpleSortMethod};
+use std::{collections::HashMap, str::FromStr};
+use uuid::Uuid;
+
+pub struct EmailServiceImpl<T, U> {
+ email_repo: T,
+ frecency_service: U,
+}
+
+impl<T, U> EmailServiceImpl<T, U>
+where
+ T: EmailRepo,
+ U: FrecencyQueryService,
+{
+ pub fn new(email_repo: T, frecency_service: U) -> EmailServiceImpl<T, U> {
+ EmailServiceImpl {
+ email_repo,
+ frecency_service,
+ }
+ }
+}
+
+impl<T, U> EmailService for EmailServiceImpl<T, U>
+where
+ T: EmailRepo,
+ U: FrecencyQueryService,
+ anyhow::Error: From<T::Err>,
+{
+ async fn get_email_thread_previews(
+ &self,
+ req: GetEmailsRequest,
+ ) -> Result<PaginatedCursor<EnrichedThreadPreviewCursor, Uuid, SimpleSortMethod, ()>, EmailErr>
+ {
+ let GetEmailsRequest {
+ view,
+ link_id,
+ macro_id,
+ limit,
+ query,
+ } = req;
+ let sort_method = *query.sort_method();
+
+ const MIN_PAGE: u32 = 20;
+ const MAX_PAGE: u32 = 500;
+
+ let limit = limit.unwrap_or_default().clamp(MIN_PAGE, MAX_PAGE);
+
+ let query = PreviewCursorQuery {
+ view,
+ link_id,
+ limit,
+ query,
+ };
+
+ let previews = self
+ .email_repo
+ .previews_for_view_cursor(query, macro_id.copied().into_owned())
+ .await
+ .map_err(anyhow::Error::from)?;
+
+ let thread_ids: Vec<Uuid> = previews.iter().map(|p| p.id).collect();
+
+ let ids: Vec<_> = thread_ids
+ .iter()
+ .map(|id| EntityType::Email.with_entity_string(id.to_string()))
+ .collect();
+
+ let frecency_request = FrecencyByIdsRequest {
+ user_id: macro_id,
+ ids: ids.as_slice(),
+ };
+
+ let (
+ attachment_map_result,
+ macro_attachment_map_result,
+ participant_result,
+ frecency_scores,
+ ) = tokio::join!(
+ self.email_repo.attachments_by_thread_ids(&thread_ids),
+ self.email_repo.macro_attachments_by_thread_ids(&thread_ids),
+ self.email_repo.contacts_by_thread_ids(&thread_ids),
+ self.frecency_service
+ .get_frecencies_by_ids(frecency_request)
+ );
+
+ let mut attachment_map = attachment_map_result
+ .map_err(anyhow::Error::from)?
+ .into_iter()
+ .group_by(|v| v.thread_id);
+ let mut macro_attachment_map = macro_attachment_map_result
+ .map_err(anyhow::Error::from)?
+ .into_iter()
+ .group_by(|v| v.thread_id);
+ let mut participant_map = participant_result
+ .map_err(anyhow::Error::from)?
+ .into_iter()
+ .group_by(|v| v.thread_id);
+
+ let mut frecency_scores_map: HashMap<Uuid, f64> = frecency_scores?
+ .into_inner()
+ .into_iter()
+ .filter_map(|(id, data)| {
+ Some((
+ Uuid::from_str(&id.entity.entity_id).ok()?,
+ data.frecency_score,
+ ))
+ })
+ .collect();
+
+ Ok(previews
+ .into_iter()
+ .map(|thread| EnrichedThreadPreviewCursor {
+ attachments: attachment_map.remove(&thread.id).unwrap_or_default(),
+ attachments_macro: macro_attachment_map.remove(&thread.id).unwrap_or_default(),
+ participants: participant_map.remove(&thread.id).unwrap_or_default(),
+ frecency_score: frecency_scores_map.remove(&thread.id),
+ thread,
+ })
+ .paginate_on(limit as usize, sort_method)
+ .into_page())
+ }
+}
diff --git a/rust/cloud-storage/email/src/inbound.rs b/rust/cloud-storage/email/src/inbound.rs
new file mode 100644
index 0000000000..a66cfff8b3
--- /dev/null
+++ b/rust/cloud-storage/email/src/inbound.rs
@@ -0,0 +1,5 @@
+#[cfg(feature = "axum")]
+mod axum;
+
+#[cfg(feature = "axum")]
+pub use axum::*;
diff --git a/rust/cloud-storage/email/src/inbound/axum.rs b/rust/cloud-storage/email/src/inbound/axum.rs
new file mode 100644
index 0000000000..5037b9fe97
--- /dev/null
+++ b/rust/cloud-storage/email/src/inbound/axum.rs
@@ -0,0 +1,7 @@
+mod api_types;
+mod axum_impls;
+mod router;
+
+pub use api_types::*;
+pub use axum_impls::*;
+pub use router::*;
diff --git a/rust/cloud-storage/email/src/inbound/axum/api_types.rs b/rust/cloud-storage/email/src/inbound/axum/api_types.rs
new file mode 100644
index 0000000000..96ad7dfa5d
--- /dev/null
+++ b/rust/cloud-storage/email/src/inbound/axum/api_types.rs
@@ -0,0 +1,278 @@
+use chrono::{DateTime, Utc};
+use models_pagination::{PaginatedOpaqueCursor, SimpleSortMethod};
+use serde::{Deserialize, Serialize};
+use utoipa::ToSchema;
+use uuid::Uuid;
+
+use crate::domain::models::{
+ Attachment, AttachmentMacro, Contact, EnrichedThreadPreviewCursor, ThreadPreviewCursor,
+};
+
+/// common types of sorts based on timestamps
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum ApiSortMethod {
+ /// we are sorting by the viewed_at time
+ ViewedAt,
+ /// we are sorting by the updated_at time
+ UpdatedAt,
+ /// we are sorting by the created_at time
+ CreatedAt,
+ /// we are sorting by the viewed/updated time
+ ViewedUpdated,
+}
+
+impl ApiSortMethod {
+ pub fn into_simple_sort(self) -> SimpleSortMethod {
+ match self {
+ ApiSortMethod::ViewedAt => SimpleSortMethod::ViewedAt,
+ ApiSortMethod::UpdatedAt => SimpleSortMethod::UpdatedAt,
+ ApiSortMethod::CreatedAt => SimpleSortMethod::CreatedAt,
+ ApiSortMethod::ViewedUpdated => SimpleSortMethod::ViewedUpdated,
+ }
+ }
+}
+
+#[derive(Debug, ToSchema, Serialize, Deserialize)]
+#[cfg_attr(feature = "ai_schema", derive(schemars::JsonSchema))]
+#[serde(rename_all = "camelCase")]
+struct ApiThreadPreviewCursor {
+ #[serde(flatten)]
+ thread: ApiThreadPreviewCursorInner,
+ attachments: Vec<ApiAttachment>,
+ macro_attachments: Vec<ApiAttachmentMacro>,
+ contacts: Vec<ApiContact>,
+ frecency_score: Option<f64>,
+}
+
+impl ApiThreadPreviewCursor {
+ #[inline]
+ fn new(model: EnrichedThreadPreviewCursor) -> Self {
+ let EnrichedThreadPreviewCursor {
+ thread,
+ attachments,
+ attachments_macro,
+ frecency_score,
+ participants,
+ } = model;
+
+ ApiThreadPreviewCursor {
+ thread: ApiThreadPreviewCursorInner::new(thread),
+ attachments: attachments.into_iter().map(ApiAttachment::new).collect(),
+ macro_attachments: attachments_macro
+ .into_iter()
+ .map(ApiAttachmentMacro::new)
+ .collect(),
+ contacts: participants.into_iter().map(ApiContact::new).collect(),
+ frecency_score,
+ }
+ }
+}
+
+#[derive(Debug, ToSchema, Serialize, Deserialize)]
+#[cfg_attr(feature = "ai_schema", derive(schemars::JsonSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct ApiThreadPreviewCursorInner {
+ id: Uuid,
+ provider_id: Option<String>,
+ owner_id: String,
+ inbox_visible: bool,
+ is_read: bool,
+ is_draft: bool,
+ is_important: bool,
+ name: Option<String>,
+ snippet: Option<String>,
+ sender_email: Option<String>,
+ sender_name: Option<String>,
+ sender_photo_url: Option<String>,
+
+ #[serde(with = "chrono::serde::ts_milliseconds")]
+ #[schema(value_type = i64)]
+ #[cfg_attr(feature = "ai_schema", schemars(with = "i64"))]
+ sort_ts: DateTime<Utc>,
+ #[serde(with = "chrono::serde::ts_milliseconds")]
+ #[schema(value_type = i64)]
+ #[cfg_attr(feature = "ai_schema", schemars(with = "i64"))]
+ created_at: DateTime<Utc>,
+ #[serde(with = "chrono::serde::ts_milliseconds")]
+ #[schema(value_type = i64)]
+ #[cfg_attr(feature = "ai_schema", schemars(with = "i64"))]
+ updated_at: DateTime<Utc>,
+ #[serde(with = "chrono::serde::ts_milliseconds_option")]
+ #[schema(value_type = i64, nullable = true)]
+ #[cfg_attr(feature = "ai_schema", schemars(with = "Option<i64>"))]
+ viewed_at: Option<DateTime<Utc>>,
+}
+
+impl ApiThreadPreviewCursorInner {
+ #[inline]
+ fn new(thread: ThreadPreviewCursor) -> Self {
+ let ThreadPreviewCursor {
+ id,
+ provider_id,
+ owner_id,
+ inbox_visible,
+ is_read,
+ is_draft,
+ is_important,
+ name,
+ snippet,
+ sender_email,
+ sender_name,
+ sender_photo_url,
+ sort_ts,
+ created_at,
+ updated_at,
+ viewed_at,
+ } = thread;
+
+ Self {
+ id,
+ provider_id,
+ owner_id: owner_id.to_string(),
+ inbox_visible,
+ is_read,
+ is_draft,
+ is_important,
+ name,
+ snippet,
+ sender_email,
+ sender_name,
+ sender_photo_url,
+ sort_ts,
+ created_at,
+ updated_at,
+ viewed_at,
+ }
+ }
+}
+
+#[derive(Debug, ToSchema, Serialize, Deserialize)]
+#[cfg_attr(feature = "ai_schema", derive(schemars::JsonSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct ApiAttachment {
+ id: Uuid,
+ message_id: Uuid,
+ // a different value is returned by the gmail API for this each time you fetch a message -
+ // don't make the mistake of using it to uniquely identify an attachment
+ provider_attachment_id: Option<String>,
+ filename: Option<String>,
+ mime_type: Option<String>,
+ size_bytes: Option<i64>,
+ content_id: Option<String>,
+
+ #[serde(with = "chrono::serde::ts_milliseconds")]
+ #[schema(value_type = i64)]
+ #[cfg_attr(feature = "ai_schema", schemars(with = "i64"))]
+ created_at: DateTime<Utc>,
+}
+
+impl ApiAttachment {
+ #[inline]
+ fn new(model: Attachment) -> Self {
+ let Attachment {
+ id,
+ thread_id: _,
+ message_id,
+ provider_attachment_id,
+ filename,
+ mime_type,
+ size_bytes,
+ content_id,
+ created_at,
+ } = model;
+
+ ApiAttachment {
+ id,
+ message_id,
+ provider_attachment_id,
+ filename,
+ mime_type,
+ size_bytes,
+ content_id,
+ created_at,
+ }
+ }
+}
+
+#[derive(Debug, ToSchema, Serialize, Deserialize)]
+#[cfg_attr(feature = "ai_schema", derive(schemars::JsonSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct ApiAttachmentMacro {
+ db_id: Uuid,
+ message_id: Uuid,
+ item_id: Uuid,
+ item_type: String,
+}
+
+impl ApiAttachmentMacro {
+ #[inline]
+ fn new(model: AttachmentMacro) -> Self {
+ let AttachmentMacro {
+ thread_id: _,
+ db_id,
+ message_id,
+ item_id,
+ item_type,
+ } = model;
+ ApiAttachmentMacro {
+ db_id,
+ message_id,
+ item_id,
+ item_type,
+ }
+ }
+}
+
+#[derive(Debug, ToSchema, Serialize, Deserialize)]
+#[cfg_attr(feature = "ai_schema", derive(schemars::JsonSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct ApiContact {
+ id: Uuid,
+ link_id: Uuid,
+ name: Option<String>,
+ email_address: Option<String>,
+ sfs_photo_url: Option<String>,
+}
+
+impl ApiContact {
+ #[inline]
+ fn new(model: Contact) -> Self {
+ let Contact {
+ id,
+ thread_id: _,
+ link_id,
+ name,
+ email_address,
+ sfs_photo_url,
+ } = model;
+
+ ApiContact {
+ id,
+ link_id,
+ name,
+ email_address,
+ sfs_photo_url,
+ }
+ }
+}
+
+#[derive(Debug, ToSchema, Serialize, Deserialize)]
+#[cfg_attr(feature = "ai_schema", derive(schemars::JsonSchema))]
+pub struct ApiPaginatedThreadCursor {
+ items: Vec<ApiThreadPreviewCursor>,
+ next_cursor: Option<String>,
+}
+
+impl ApiPaginatedThreadCursor {
+ #[inline]
+ pub(crate) fn new(model: PaginatedOpaqueCursor<EnrichedThreadPreviewCursor>) -> Self {
+ let PaginatedOpaqueCursor {
+ items, next_cursor, ..
+ } = model;
+ ApiPaginatedThreadCursor {
+ items: items.into_iter().map(ApiThreadPreviewCursor::new).collect(),
+ next_cursor,
+ }
+ }
+}
diff --git a/rust/cloud-storage/email/src/inbound/axum/axum_impls.rs b/rust/cloud-storage/email/src/inbound/axum/axum_impls.rs
new file mode 100644
index 0000000000..1da9f8de16
--- /dev/null
+++ b/rust/cloud-storage/email/src/inbound/axum/axum_impls.rs
@@ -0,0 +1,70 @@
+use std::str::FromStr;
+
+use axum::{
+ RequestPartsExt, async_trait,
+ extract::{FromRequestParts, Path, rejection::PathRejection},
+ http::{StatusCode, request::Parts},
+ response::{IntoResponse, Response},
+};
+use thiserror::Error;
+use utoipa::{IntoParams, ToSchema};
+use uuid::Uuid;
+
+use crate::{
+ domain::models::{EmailErr, PreviewView},
+ inbound::ApiSortMethod,
+};
+
+#[derive(Debug, Error)]
+pub enum GetPreviewsCursorError {
+ #[error(transparent)]
+ PathErr(#[from] PathRejection),
+ #[error("Invalid view parameter: {0}")]
+ InvalidView(String),
+
+ #[error("Internal server error")]
+ DatabaseQueryError(#[from] EmailErr),
+}
+
+impl IntoResponse for GetPreviewsCursorError {
+ fn into_response(self) -> Response {
+ let msg = self.to_string();
+
+ let status_code = match self {
+ GetPreviewsCursorError::InvalidView(_) => StatusCode::BAD_REQUEST,
+ GetPreviewsCursorError::DatabaseQueryError(_) => StatusCode::INTERNAL_SERVER_ERROR,
+ GetPreviewsCursorError::PathErr(path_rejection) => {
+ return path_rejection.into_response();
+ }
+ };
+
+ (status_code, msg).into_response()
+ }
+}
+
+#[derive(Debug, Clone)]
+pub struct LinkUuid(pub Uuid);
+
+pub(crate) struct PreviewViewExtractor(pub PreviewView);
+
+#[async_trait]
+impl<S: Send + Sync> FromRequestParts<S> for PreviewViewExtractor {
+ type Rejection = GetPreviewsCursorError;
+
+ async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
+ let Path(view) = parts.extract::<Path<String>>().await?;
+ Ok(PreviewViewExtractor(
+ PreviewView::from_str(&view).map_err(GetPreviewsCursorError::InvalidView)?,
+ ))
+ }
+}
+
+/// Parameters for getting thread previews with cursor-based pagination.
+#[derive(serde::Serialize, serde::Deserialize, Debug, ToSchema, IntoParams)]
+#[into_params(parameter_in = Query)]
+pub struct GetPreviewsCursorParams {
+ /// Limit for pagination. Default is 20. Max is 500.
+ pub limit: Option<u32>,
+ /// Sort method. Options are viewed_at, created_at, updated_at, viewed_updated. Defaults to viewed_updated.
+ pub sort_method: Option<ApiSortMethod>,
+}
diff --git a/rust/cloud-storage/email/src/inbound/axum/router.rs b/rust/cloud-storage/email/src/inbound/axum/router.rs
new file mode 100644
index 0000000000..86d0595587
--- /dev/null
+++ b/rust/cloud-storage/email/src/inbound/axum/router.rs
@@ -0,0 +1,101 @@
+use axum::{
+ Extension, Json, Router,
+ extract::{self, State},
+ routing::get,
+};
+use model_error_response::ErrorResponse;
+use model_user::axum_extractor::MacroUserExtractor;
+use models_pagination::{CursorExtractor, SimpleSortMethod, TypeEraseCursor};
+use std::sync::Arc;
+use uuid::Uuid;
+
+use crate::{
+ domain::{models::GetEmailsRequest, ports::EmailService},
+ inbound::{
+ ApiPaginatedThreadCursor,
+ axum::axum_impls::{
+ GetPreviewsCursorError, GetPreviewsCursorParams, LinkUuid, PreviewViewExtractor,
+ },
+ },
+};
+
+pub struct EmailPreviewState<T> {
+ inner: Arc<T>,
+}
+
+impl<T> Clone for EmailPreviewState<T> {
+ fn clone(&self) -> Self {
+ Self {
+ inner: Arc::clone(&self.inner),
+ }
+ }
+}
+
+impl<T> EmailPreviewState<T>
+where
+ T: EmailService,
+{
+ pub fn new(state: T) -> Self {
+ Self {
+ inner: Arc::new(state),
+ }
+ }
+}
+
+pub fn router<S, T>(state: EmailPreviewState<T>) -> Router<S>
+where
+ S: Send + Sync,
+ T: EmailService,
+{
+ Router::new()
+ .route("/cursor/:view", get(cursor_handler))
+ .with_state(state)
+}
+
+/// Get paginated thread previews with cursor-based pagination.
+#[utoipa::path(
+ get,
+ tag = "Previews",
+ path = "/email/threads/previews/cursor/{view}",
+ operation_id = "previews_inbox_cursor",
+ params(
+ GetPreviewsCursorParams,
+ ("view" = String, Path, description = "View type. Supported values: inbox, sent, drafts, starred, all, important, other, user:<label>"),
+ ("cursor" = Option<String>, Query, description = "Cursor value. Base64 encoded timestamp and item id, separated by |."),
+ ),
+ responses(
+ (status = 200, body=ApiPaginatedThreadCursor),
+ (status = 400, body=ErrorResponse),
+ (status = 401, body=ErrorResponse),
+ (status = 500, body=ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip(link_id, macro_user, service), fields(user_id=macro_user.macro_user_id.as_ref(), fusionauth_user_id=macro_user.user_context.fusion_user_id))]
+async fn cursor_handler<T: EmailService>(
+ State(service): State<EmailPreviewState<T>>,
+ macro_user: MacroUserExtractor,
+ Extension(LinkUuid(link_id)): Extension<LinkUuid>,
+ PreviewViewExtractor(preview_view): PreviewViewExtractor,
+ extract::Query(params): extract::Query<GetPreviewsCursorParams>,
+ cursor: CursorExtractor<Uuid, SimpleSortMethod, ()>,
+) -> Result<Json<ApiPaginatedThreadCursor>, GetPreviewsCursorError> {
+ Ok(Json(ApiPaginatedThreadCursor::new(
+ service
+ .inner
+ .get_email_thread_previews(GetEmailsRequest {
+ view: preview_view,
+ link_id,
+ macro_id: macro_user.macro_user_id,
+ limit: params.limit,
+ query: cursor.into_query(
+ params
+ .sort_method
+ .map(|v| v.into_simple_sort())
+ .unwrap_or(SimpleSortMethod::ViewedUpdated),
+ (),
+ ),
+ })
+ .await?
+ .type_erase(),
+ )))
+}
diff --git a/rust/cloud-storage/email/src/lib.rs b/rust/cloud-storage/email/src/lib.rs
new file mode 100644
index 0000000000..a65f027d93
--- /dev/null
+++ b/rust/cloud-storage/email/src/lib.rs
@@ -0,0 +1,3 @@
+pub mod domain;
+pub mod inbound;
+pub mod outbound;
diff --git a/rust/cloud-storage/email/src/outbound.rs b/rust/cloud-storage/email/src/outbound.rs
new file mode 100644
index 0000000000..fffc16f08e
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound.rs
@@ -0,0 +1,3 @@
+mod email_pg_repo;
+
+pub use email_pg_repo::*;
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo.rs
new file mode 100644
index 0000000000..6eb0711a06
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo.rs
@@ -0,0 +1,215 @@
+use crate::domain::{
+ models::{
+ Attachment, AttachmentMacro, Contact, PreviewCursorQuery, PreviewView,
+ PreviewViewStandardLabel, ThreadPreviewCursor,
+ },
+ ports::EmailRepo,
+};
+use db_types::*;
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
+use sqlx::PgPool;
+use uuid::Uuid;
+
+mod db_types;
+mod queries;
+
+#[derive(Clone)]
+pub struct EmailPgRepo {
+ pool: PgPool,
+}
+
+impl EmailPgRepo {
+ pub fn new(pool: PgPool) -> Self {
+ EmailPgRepo { pool }
+ }
+}
+
+impl EmailRepo for EmailPgRepo {
+ type Err = sqlx::Error;
+
+ async fn previews_for_view_cursor(
+ &self,
+ query: PreviewCursorQuery,
+ user_id: MacroUserIdStr<'static>,
+ ) -> Result<Vec<ThreadPreviewCursor>, Self::Err> {
+ Ok(match query.view {
+ PreviewView::StandardLabel(ref label) => match label {
+ PreviewViewStandardLabel::Inbox => {
+ queries::new_inbox::new_inbox_preview_cursor(
+ &self.pool,
+ &query,
+ user_id.copied(),
+ )
+ .await?
+ }
+ PreviewViewStandardLabel::Sent => {
+ queries::sent::sent_preview_cursor(&self.pool, &query, user_id.copied()).await?
+ }
+ PreviewViewStandardLabel::Drafts => {
+ queries::draft::drafts_preview_cursor(&self.pool, &query, user_id.copied())
+ .await?
+ }
+ PreviewViewStandardLabel::Starred => {
+ queries::starred::starred_preview_cursor(&self.pool, &query, user_id.copied())
+ .await?
+ }
+ PreviewViewStandardLabel::All => {
+ queries::all_mail::all_mail_preview_cursor(&self.pool, &query, user_id.copied())
+ .await?
+ }
+ PreviewViewStandardLabel::Important => {
+ queries::important::important_preview_cursor(
+ &self.pool,
+ &query,
+ user_id.copied(),
+ )
+ .await?
+ }
+ PreviewViewStandardLabel::Other => {
+ queries::other_inbox::other_inbox_preview_cursor(
+ &self.pool,
+ &query,
+ user_id.copied(),
+ )
+ .await?
+ }
+ },
+ PreviewView::UserLabel(ref label_name) => {
+ queries::user_label::user_label_preview_cursor(
+ &self.pool,
+ &query,
+ label_name,
+ user_id.copied(),
+ )
+ .await?
+ }
+ }
+ .into_iter()
+ .map(|row| row.with_user_id(user_id.clone()))
+ .collect())
+ }
+
+ async fn attachments_by_thread_ids(
+ &self,
+ thread_ids: &[Uuid],
+ ) -> Result<Vec<Attachment>, Self::Err> {
+ // Query all attachments for messages in the provided threads
+ // Include thread_id in the result set
+ Ok(sqlx::query_as!(
+ AttachmentDbRow,
+ r#"
+ SELECT
+ a.id,
+ a.message_id,
+ a.provider_attachment_id,
+ a.filename,
+ a.mime_type,
+ a.size_bytes,
+ a.content_id,
+ a.created_at,
+ m.thread_id
+ FROM
+ email_attachments a
+ JOIN
+ email_messages m ON a.message_id = m.id
+ WHERE
+ m.thread_id = ANY($1)
+ ORDER BY
+ a.created_at ASC
+ "#,
+ thread_ids
+ )
+ .fetch_all(&self.pool)
+ .await?
+ .into_iter()
+ .map(AttachmentDbRow::into_model)
+ .collect())
+ }
+
+ async fn macro_attachments_by_thread_ids(
+ &self,
+ thread_ids: &[Uuid],
+ ) -> Result<Vec<AttachmentMacro>, Self::Err> {
+ // Query all attachments for email_messages in the provided threads
+ // Include thread_id in the result set
+ Ok(sqlx::query_as!(
+ AttachmentMacroDbRow,
+ r#"
+ SELECT
+ a.id,
+ a.message_id,
+ a.item_id as "item_id!",
+ a.item_type as "item_type!",
+ a.created_at,
+ m.thread_id
+ FROM
+ email_attachments_macro a
+ JOIN
+ email_messages m ON a.message_id = m.id
+ WHERE
+ m.thread_id = ANY($1)
+ ORDER BY
+ a.created_at ASC
+ "#,
+ thread_ids
+ )
+ .fetch_all(&self.pool)
+ .await?
+ .into_iter()
+ .map(AttachmentMacroDbRow::into_model)
+ .collect())
+ }
+
+ async fn contacts_by_thread_ids(&self, thread_ids: &[Uuid]) -> Result<Vec<Contact>, Self::Err> {
+ // Define a struct to hold the joined results
+ #[derive(Debug)]
+ struct ThreadContactResult {
+ thread_id: Uuid,
+ id: Uuid,
+ link_id: Uuid,
+ email_address: Option<String>,
+ name: Option<String>,
+ sfs_photo_url: Option<String>,
+ }
+
+ impl ThreadContactResult {
+ fn into_model(self) -> Contact {
+ let ThreadContactResult {
+ thread_id,
+ id,
+ link_id,
+ email_address,
+ name,
+ sfs_photo_url,
+ } = self;
+ Contact {
+ id,
+ link_id,
+ thread_id,
+ name,
+ email_address,
+ sfs_photo_url,
+ }
+ }
+ }
+
+ Ok(sqlx::query_as!(
+ ThreadContactResult,
+ r#"
+ SELECT
+ m.thread_id,
+ c.id, c.link_id, c.email_address, c.name, c.sfs_photo_url
+ FROM email_messages m
+ JOIN email_contacts c ON m.from_contact_id = c.id
+ WHERE m.thread_id = ANY($1) AND m.from_contact_id IS NOT NULL
+ ORDER BY m.created_at ASC
+ "#,
+ thread_ids
+ )
+ .fetch_all(&self.pool)
+ .await?
+ .into_iter()
+ .map(ThreadContactResult::into_model)
+ .collect())
+ }
+}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/db_types.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/db_types.rs
new file mode 100644
index 0000000000..8d31a2422a
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/db_types.rs
@@ -0,0 +1,140 @@
+use crate::domain::models::{Attachment, AttachmentMacro, ThreadPreviewCursor};
+use chrono::{DateTime, Utc};
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
+use uuid::Uuid;
+
+pub struct AttachmentMacroDbRow {
+ pub id: Uuid,
+ pub message_id: Uuid,
+ pub item_id: Uuid,
+ pub item_type: String,
+ #[expect(
+ dead_code,
+ reason = "We need this field to use query_as with the current query, but we never read it"
+ )]
+ pub created_at: DateTime<Utc>,
+ pub thread_id: Uuid,
+}
+
+impl AttachmentMacroDbRow {
+ pub fn into_model(self) -> AttachmentMacro {
+ let AttachmentMacroDbRow {
+ id,
+ message_id,
+ item_id,
+ item_type,
+ created_at: _,
+ thread_id,
+ } = self;
+ AttachmentMacro {
+ thread_id,
+ db_id: id,
+ message_id,
+ item_id,
+ item_type,
+ }
+ }
+}
+
+pub struct AttachmentDbRow {
+ pub id: Uuid,
+ pub message_id: Uuid,
+ // a different value is returned by the gmail API for this each time you fetch a message -
+ // don't make the mistake of using it to uniquely identify an attachment
+ pub provider_attachment_id: Option<String>,
+ pub filename: Option<String>,
+ pub mime_type: Option<String>,
+ pub size_bytes: Option<i64>,
+ pub content_id: Option<String>,
+ pub created_at: DateTime<Utc>,
+ pub thread_id: Uuid,
+}
+
+impl AttachmentDbRow {
+ pub fn into_model(self) -> Attachment {
+ let AttachmentDbRow {
+ id,
+ message_id,
+ provider_attachment_id,
+ filename,
+ mime_type,
+ size_bytes,
+ content_id,
+ created_at,
+ thread_id,
+ } = self;
+
+ Attachment {
+ id,
+ thread_id,
+ message_id,
+ provider_attachment_id,
+ filename,
+ mime_type,
+ size_bytes,
+ content_id,
+ created_at,
+ }
+ }
+}
+
+/// thread summary returned in preview cursor endpoint
+#[derive(Debug, Clone)]
+pub struct ThreadPreviewCursorDbRow {
+ pub id: Uuid,
+ pub provider_id: Option<String>,
+ pub inbox_visible: bool,
+ pub is_read: bool,
+ pub is_draft: bool,
+ pub is_important: bool,
+ pub sort_ts: DateTime<Utc>,
+ pub name: Option<String>,
+ pub snippet: Option<String>,
+ pub sender_email: Option<String>,
+ pub sender_name: Option<String>,
+ pub sender_photo_url: Option<String>,
+ pub viewed_at: Option<DateTime<Utc>>,
+ pub created_at: DateTime<Utc>,
+ pub updated_at: DateTime<Utc>,
+}
+
+impl ThreadPreviewCursorDbRow {
+ pub fn with_user_id(self, owner_id: MacroUserIdStr<'_>) -> ThreadPreviewCursor {
+ let ThreadPreviewCursorDbRow {
+ id,
+ provider_id,
+ inbox_visible,
+ is_read,
+ is_draft,
+ is_important,
+ sort_ts,
+ name,
+ snippet,
+ sender_email,
+ sender_name,
+ sender_photo_url,
+ viewed_at,
+ created_at,
+ updated_at,
+ } = self;
+
+ ThreadPreviewCursor {
+ id,
+ provider_id,
+ owner_id: owner_id.into_owned(),
+ inbox_visible,
+ is_read,
+ is_draft,
+ is_important,
+ name,
+ snippet,
+ sender_email,
+ sender_name,
+ sender_photo_url,
+ sort_ts,
+ created_at,
+ updated_at,
+ viewed_at,
+ }
+ }
+}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries.rs
new file mode 100644
index 0000000000..053d030005
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries.rs
@@ -0,0 +1,8 @@
+pub(super) mod all_mail;
+pub(super) mod draft;
+pub(super) mod important;
+pub(super) mod new_inbox;
+pub(super) mod other_inbox;
+pub(super) mod sent;
+pub(super) mod starred;
+pub(super) mod user_label;
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/all_mail.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/all_mail.rs
new file mode 100644
index 0000000000..18bda4fc33
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/all_mail.rs
@@ -0,0 +1,118 @@
+use super::super::db_types::*;
+use crate::domain::models::PreviewCursorQuery;
+use macro_user_id::user_id::MacroUserIdStr;
+use sqlx::PgPool;
+
+/// Fetches a paginated list of thread previews for the "All Mail" view using a
+/// denormalized timestamp.
+/// This view includes all threads that have at least one non-spam message, sorted by the
+/// `latest_non_spam_message_ts` column on the `threads` table. The preview shows
+/// details from the latest non-spam message
+#[tracing::instrument(skip(pool), err)]
+pub(crate) async fn all_mail_preview_cursor(
+ pool: &PgPool,
+ query: &PreviewCursorQuery,
+ user_id: MacroUserIdStr<'_>,
+) -> Result<Vec<ThreadPreviewCursorDbRow>, sqlx::Error> {
+ let query_limit = query.limit as i64;
+ let sort_method_str = query.query.sort_method().to_string();
+ let (cursor_id, cursor_timestamp) = query.query.vals();
+
+ sqlx::query_as!(
+ ThreadPreviewCursorDbRow,
+ r#"
+ SELECT
+ t.id,
+ t.provider_id,
+ t.inbox_visible,
+ t.is_read,
+ t.effective_ts AS "sort_ts!",
+ t.created_at AS "created_at!",
+ t.updated_at AS "updated_at!",
+ t.viewed_at AS "viewed_at?",
+ lmp.subject AS "name?",
+ lmp.snippet AS "snippet?",
+ lmp.is_draft,
+ (
+ SELECT EXISTS (
+ SELECT 1
+ FROM email_messages m_imp
+ JOIN email_message_labels ml ON m_imp.id = ml.message_id
+ JOIN email_labels l ON ml.label_id = l.id
+ WHERE m_imp.thread_id = t.id
+ AND l.name = 'IMPORTANT'
+ AND l.link_id = t.link_id
+ )
+ ) AS "is_important!",
+ c.email_address AS "sender_email?",
+ c.name AS "sender_name?",
+ c.sfs_photo_url as "sender_photo_url?"
+ FROM (
+ -- Step 1: Efficiently find, sort, and limit the top N+1 threads.
+ -- This subquery only touches `threads` and `user_history`, making it very fast.
+ SELECT
+ t.id,
+ t.provider_id,
+ t.link_id,
+ t.inbox_visible,
+ t.is_read,
+ t.latest_non_spam_message_ts AS created_at,
+ t.latest_non_spam_message_ts AS updated_at,
+ uh.updated_at AS viewed_at,
+ CASE $5 -- sort_method_str
+ WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
+ WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_non_spam_message_ts)
+ ELSE t.latest_non_spam_message_ts
+ END AS effective_ts
+ FROM email_threads t
+ LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id
+ WHERE
+ t.link_id = $1
+ AND t.latest_non_spam_message_ts IS NOT NULL
+
+ -- Cursor logic is moved inside for maximum efficiency
+ AND (($3::timestamptz IS NULL) OR (
+ -- This CASE must exactly match the one that defines `effective_ts`
+ CASE $5 -- sort_method_str
+ WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
+ WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_non_spam_message_ts)
+ ELSE t.latest_non_spam_message_ts
+ END, t.id
+ ) < ($3::timestamptz, $4::uuid))
+ ORDER BY effective_ts DESC, t.updated_at DESC
+ LIMIT $2
+ ) AS t
+ -- Step 2: For EACH of the limited threads from above, find its latest non-SPAM/TRASH message.
+ CROSS JOIN LATERAL (
+ SELECT
+ m.subject,
+ m.snippet,
+ m.is_draft,
+ m.from_contact_id
+ FROM email_messages m
+ WHERE m.thread_id = t.id
+ AND m.is_draft = FALSE
+ AND NOT EXISTS (
+ SELECT 1
+ FROM email_message_labels ml
+ JOIN email_labels l ON ml.label_id = l.id
+ WHERE ml.message_id = m.id
+ AND l.link_id = t.link_id
+ AND l.name IN ('SPAM', 'TRASH')
+ )
+ ORDER BY m.internal_date_ts DESC
+ LIMIT 1
+ ) AS lmp
+ -- Step 3: Join to get the sender's details for the final result set.
+ LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id
+ ORDER BY t.effective_ts DESC, t.updated_at DESC
+ "#,
+ query.link_id, // $1
+ query_limit, // $2
+ cursor_timestamp, // $3
+ cursor_id, // $4
+ sort_method_str, // $5
+ )
+ .fetch_all(pool)
+ .await
+}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/draft.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/draft.rs
new file mode 100644
index 0000000000..90782ff788
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/draft.rs
@@ -0,0 +1,113 @@
+use super::super::db_types::*;
+use crate::domain::models::PreviewCursorQuery;
+use macro_user_id::user_id::MacroUserIdStr;
+use sqlx::PgPool;
+
+/// Fetches a paginated list of thread previews for the "Drafts" view.
+/// This view includes all threads that contain at least one draft message, sorted by the
+/// timestamp of the most recent draft within each thread.
+#[tracing::instrument(skip(pool), err)]
+pub(crate) async fn drafts_preview_cursor(
+ pool: &PgPool,
+ query: &PreviewCursorQuery,
+ user_id: MacroUserIdStr<'_>,
+) -> Result<Vec<ThreadPreviewCursorDbRow>, sqlx::Error> {
+ let query_limit = query.limit as i64;
+ let sort_method_str = query.query.sort_method().to_string();
+ let (cursor_id, cursor_timestamp) = query.query.vals();
+
+ sqlx::query_as!(
+ ThreadPreviewCursorDbRow,
+ r#"
+ SELECT
+ t.id,
+ t.provider_id,
+ t.inbox_visible,
+ t.is_read,
+ t.effective_ts AS "sort_ts!",
+ t.created_at AS "created_at!",
+ t.updated_at AS "updated_at!",
+ t.viewed_at AS "viewed_at?",
+ lmp.subject AS "name?",
+ lmp.snippet AS "snippet?",
+ lmp.is_draft,
+ (
+ SELECT EXISTS (
+ SELECT 1
+ FROM email_messages m_imp
+ JOIN email_message_labels ml ON m_imp.id = ml.message_id
+ JOIN email_labels l ON ml.label_id = l.id
+ WHERE m_imp.thread_id = t.id
+ AND l.name = 'IMPORTANT'
+ AND l.link_id = t.link_id
+ )
+ ) AS "is_important!",
+ c.email_address AS "sender_email?",
+ c.name AS "sender_name?",
+ c.sfs_photo_url as "sender_photo_url?"
+ FROM (
+ -- Step 1: Find the latest draft timestamp for each thread, calculate the
+ -- effective sort key, then sort and limit the results. This is the core optimization.
+ SELECT
+ t.id,
+ t.provider_id,
+ t.link_id,
+ t.inbox_visible,
+ t.is_read,
+ ldpt.latest_draft_ts AS created_at,
+ ldpt.latest_draft_ts AS updated_at,
+ uh.updated_at AS viewed_at,
+ CASE $5 -- sort_method_str
+ WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
+ WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, ldpt.latest_draft_ts)
+ ELSE ldpt.latest_draft_ts
+ END AS effective_ts
+ FROM (
+ -- This sub-subquery efficiently finds the latest draft timestamp for every thread.
+ SELECT thread_id, MAX(updated_at) as latest_draft_ts
+ FROM email_messages
+ -- we only display macro drafts, not drafts created in gmail
+ WHERE link_id = $1 AND is_draft = TRUE AND internal_date_ts IS NULL
+ GROUP BY thread_id
+ ) ldpt
+ JOIN email_threads t ON ldpt.thread_id = t.id
+ LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id
+ WHERE
+ (($3::timestamptz IS NULL) OR (
+ CASE $5 -- sort_method_str
+ WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
+ WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, ldpt.latest_draft_ts)
+ ELSE ldpt.latest_draft_ts
+ END, t.id
+ ) < ($3::timestamptz, $4::uuid))
+ ORDER BY effective_ts DESC, t.updated_at DESC
+ LIMIT $2
+ ) AS t
+ -- Step 2: For EACH of the limited threads from above, find the full details of its latest draft.
+ CROSS JOIN LATERAL (
+ SELECT
+ m.subject,
+ m.snippet,
+ m.from_contact_id,
+ m.is_draft
+ FROM email_messages m
+ WHERE m.thread_id = t.id
+ AND m.is_draft = TRUE
+ -- we only display macro drafts, not drafts created in gmail
+ AND m.internal_date_ts IS NULL
+ ORDER BY m.updated_at DESC
+ LIMIT 1
+ ) AS lmp
+ -- Step 3: Join to get the sender's details.
+ LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id
+ ORDER BY t.effective_ts DESC, t.updated_at DESC
+ "#,
+ query.link_id, // $1
+ query_limit, // $2
+ cursor_timestamp, // $3
+ cursor_id, // $4
+ sort_method_str, // $5
+ )
+ .fetch_all(pool)
+ .await
+}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/important.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/important.rs
new file mode 100644
index 0000000000..af42f95f71
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/important.rs
@@ -0,0 +1,137 @@
+use super::super::db_types::*;
+use crate::domain::models::PreviewCursorQuery;
+use macro_user_id::user_id::MacroUserIdStr;
+use sqlx::PgPool;
+
+/// Fetches a paginated list of thread previews for the "Important" view.
+/// Includes threads that:
+/// 1. Have messages with both 'IMPORTANT' and 'INBOX' labels, or
+/// 2. Contain draft messages
+/// The threads are sorted by timestamp, with preview details taken from the latest qualifying message.
+#[tracing::instrument(skip(pool), err)]
+pub(crate) async fn important_preview_cursor(
+ pool: &PgPool,
+ query: &PreviewCursorQuery,
+ user_id: MacroUserIdStr<'_>,
+) -> Result<Vec<ThreadPreviewCursorDbRow>, sqlx::Error> {
+ let query_limit = query.limit as i64;
+ let sort_method_str = query.query.sort_method().to_string();
+ let (cursor_id, cursor_timestamp) = query.query.vals();
+
+ sqlx::query_as!(
+ ThreadPreviewCursorDbRow,
+ r#"
+ WITH ApplicableLabelIDs AS (
+ SELECT id
+ FROM email_labels
+ WHERE link_id = $1
+ AND (name = 'INBOX')
+ ),
+ QualifyingMessages AS (
+ SELECT m.thread_id,
+ m.internal_date_ts,
+ m.is_draft,
+ m.subject,
+ m.snippet,
+ m.from_contact_id
+ FROM email_messages m
+ WHERE m.link_id = $1
+ AND EXISTS (
+ SELECT 1
+ FROM email_message_labels ml
+ JOIN email_labels l ON ml.label_id = l.id
+ WHERE ml.message_id = m.id
+ AND l.name = 'IMPORTANT'
+ )
+ AND EXISTS (
+ SELECT 1
+ FROM email_message_labels ml
+ JOIN ApplicableLabelIDs ali ON ml.label_id = ali.id
+ WHERE ml.message_id = m.id
+ )
+
+ UNION ALL
+
+ SELECT m.thread_id,
+ m.internal_date_ts,
+ m.is_draft,
+ m.subject,
+ m.snippet,
+ m.from_contact_id
+ FROM email_messages m
+ WHERE m.link_id = $1
+ AND m.is_draft = TRUE
+ ),
+ AllImportantThreads AS (
+ -- From all qualifying messages, get the single most recent one per thread.
+ SELECT DISTINCT ON (thread_id)
+ thread_id,
+ internal_date_ts,
+ is_draft,
+ subject,
+ snippet,
+ from_contact_id
+ FROM QualifyingMessages
+ ORDER BY thread_id, internal_date_ts DESC
+ ),
+ ImportantWithSortKey AS (
+ -- Join with user_history to calculate the final effective sort key.
+ SELECT
+ ait.thread_id,
+ ait.internal_date_ts,
+ ait.is_draft,
+ ait.subject,
+ ait.snippet,
+ ait.from_contact_id,
+ ait.internal_date_ts as created_at,
+ ait.internal_date_ts as updated_at,
+ uh.updated_at as viewed_at,
+ -- This CASE statement dynamically selects the correct timestamp for sorting.
+ -- For 'updated_at' and 'created_at', we use the important message timestamp
+ -- For 'viewed_at', we use the history timestamp.
+ -- For 'viewed_updated', we use the history timestamp if it exists, otherwise the important message timestamp.
+ CASE $5 -- sort_method_str
+ WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
+ WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, ait.internal_date_ts)
+ ELSE ait.internal_date_ts
+ END AS effective_ts
+ FROM AllImportantThreads ait
+ -- This has to be a left join to support all sort methods.
+ LEFT JOIN email_user_history uh ON uh.thread_id = ait.thread_id AND uh.link_id = $1
+ -- user_history updated_at (aka last time opened) has to exist when viewed_at sort method is selected.
+ WHERE ait.is_draft = FALSE
+ )
+ SELECT
+ isk.thread_id as "id!",
+ t.provider_id,
+ t.inbox_visible,
+ t.is_read,
+ isk.effective_ts as "sort_ts!",
+ isk.created_at as "created_at!",
+ isk.updated_at as "updated_at!",
+ isk.viewed_at as "viewed_at?",
+ isk.is_draft as "is_draft!",
+ -- It's the important view - all threads here are important
+ true as "is_important!",
+ isk.subject as "name?",
+ isk.snippet as "snippet?",
+ c.email_address AS "sender_email?",
+ c.name AS "sender_name?",
+ c.sfs_photo_url as "sender_photo_url?"
+ FROM ImportantWithSortKey isk
+ JOIN email_threads t ON isk.thread_id = t.id
+ LEFT JOIN email_contacts c ON isk.from_contact_id = c.id
+ WHERE
+ ($3::timestamptz IS NULL) OR (isk.effective_ts, isk.thread_id) < ($3::timestamptz, $4::uuid)
+ ORDER BY isk.effective_ts DESC, isk.thread_id DESC
+ LIMIT $2
+ "#,
+ query.link_id, // $1
+ query_limit, // $2
+ cursor_timestamp, // $3
+ cursor_id, // $4
+ sort_method_str, // $5
+ )
+ .fetch_all(pool)
+ .await
+}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/new_inbox.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/new_inbox.rs
new file mode 100644
index 0000000000..8648d1dc71
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/new_inbox.rs
@@ -0,0 +1,112 @@
+use super::super::db_types::*;
+use crate::domain::models::PreviewCursorQuery;
+use macro_user_id::user_id::MacroUserIdStr;
+use sqlx::PgPool;
+
+/// Fetches a paginated list of thread previews for a given link_id.
+/// Each thread preview includes details from the latest message (inbound or outbound)
+/// that is NOT in the 'TRASH' label.
+/// The sorting and filtering behavior is determined by the `sort_method` parameter.
+#[tracing::instrument(skip(pool), err)]
+pub(crate) async fn new_inbox_preview_cursor(
+ pool: &PgPool,
+ query: &PreviewCursorQuery,
+ user_id: MacroUserIdStr<'_>,
+) -> Result<Vec<ThreadPreviewCursorDbRow>, sqlx::Error> {
+ let query_limit = query.limit as i64;
+ let sort_method_str = query.query.sort_method().to_string();
+ let (cursor_id, cursor_timestamp) = query.query.vals();
+
+ sqlx::query_as!(
+ ThreadPreviewCursorDbRow,
+ r#"
+ SELECT
+ t.id,
+ t.provider_id,
+ TRUE AS "inbox_visible!",
+ t.is_read,
+ t.effective_ts AS "sort_ts!",
+ t.created_at AS "created_at!",
+ t.updated_at AS "updated_at!",
+ t.viewed_at AS "viewed_at?",
+ lmp.subject AS "name?",
+ lmp.snippet AS "snippet?",
+ lmp.is_draft,
+ (
+ SELECT EXISTS (
+ SELECT 1
+ FROM email_messages m_imp
+ JOIN email_message_labels ml ON m_imp.id = ml.message_id
+ JOIN email_labels l ON ml.label_id = l.id
+ WHERE m_imp.thread_id = t.id
+ AND l.name = 'IMPORTANT'
+ AND l.link_id = t.link_id
+ )
+ ) AS "is_important!",
+ c.email_address AS "sender_email?",
+ c.name AS "sender_name?",
+ c.sfs_photo_url as "sender_photo_url?"
+ FROM (
+ -- Step 1: Efficiently find and sort ONLY the top N+1 candidate threads.
+ -- This subquery is fast as it only touches `threads` and `user_history`.
+ SELECT
+ t.id,
+ t.provider_id,
+ t.link_id,
+ t.is_read,
+ t.latest_inbound_message_ts AS created_at,
+ t.latest_inbound_message_ts AS updated_at,
+ uh.updated_at AS viewed_at,
+ CASE $5 -- sort_method_str
+ WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
+ WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_inbound_message_ts)
+ ELSE t.latest_inbound_message_ts
+ END AS effective_ts
+ FROM email_threads t
+ LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id
+ WHERE
+ t.link_id = $1
+ AND t.inbox_visible = TRUE
+ AND t.latest_inbound_message_ts IS NOT NULL
+
+ -- The cursor logic is moved inside this subquery for maximum efficiency.
+ AND (($3::timestamptz IS NULL) OR (
+ -- This CASE must exactly match the one that defines `effective_ts`
+ CASE $5 -- sort_method_str
+ WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
+ WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_inbound_message_ts)
+ ELSE t.latest_inbound_message_ts
+ END, t.id
+ ) < ($3::timestamptz, $4::uuid))
+ ORDER BY effective_ts DESC, t.updated_at DESC -- fall back to updated_at if effective_ts is the same
+ LIMIT $2
+ ) AS t
+ -- Step 2: For EACH of the limited threads from above, find its latest non-trashed message.
+ CROSS JOIN LATERAL (
+ SELECT
+ m.subject,
+ m.snippet,
+ m.from_contact_id,
+ m.is_draft
+ FROM email_messages m
+ WHERE m.thread_id = t.id
+ AND m.is_draft = FALSE
+ AND NOT EXISTS (
+ SELECT 1 FROM email_message_labels ml JOIN email_labels l ON ml.label_id = l.id
+ WHERE ml.message_id = m.id AND l.name = 'TRASH' AND l.link_id = t.link_id
+ )
+ ORDER BY m.internal_date_ts DESC
+ LIMIT 1
+ ) AS lmp
+ -- Step 3: Join to get the sender's details for the final result set.
+ LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id
+ -- Final ordering is preserved because the input `t` is already sorted.
+ ORDER BY t.effective_ts DESC, t.updated_at DESC -- fall back to updated_at if effective_ts is the same
+ "#,
+ query.link_id, // $1
+ query_limit, // $2
+ cursor_timestamp, // $3
+ cursor_id, // $4
+ sort_method_str, // $5
+ ).fetch_all(pool).await
+}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/other_inbox.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/other_inbox.rs
new file mode 100644
index 0000000000..6d8477f98e
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/other_inbox.rs
@@ -0,0 +1,121 @@
+use super::super::db_types::*;
+use crate::domain::models::PreviewCursorQuery;
+use macro_user_id::user_id::MacroUserIdStr;
+use sqlx::PgPool;
+
+/// Fetches a paginated list of thread previews for the "Other" inbox view.
+/// This view includes threads that have a category label (Promotions, Social, etc.)
+/// and are not explicitly spam, trash, or drafts.
+#[tracing::instrument(skip(pool), err)]
+pub(crate) async fn other_inbox_preview_cursor(
+ pool: &PgPool,
+ query: &PreviewCursorQuery,
+ user_id: MacroUserIdStr<'_>,
+) -> Result<Vec<ThreadPreviewCursorDbRow>, sqlx::Error> {
+ let query_limit = query.limit as i64;
+ let sort_method_str = query.query.sort_method().to_string();
+ let (cursor_id, cursor_timestamp) = query.query.vals();
+
+ sqlx::query_as!(
+ ThreadPreviewCursorDbRow,
+ r#"
+ SELECT
+ t.id,
+ t.provider_id,
+ t.inbox_visible,
+ t.is_read,
+ t.effective_ts AS "sort_ts!",
+ t.created_at AS "created_at!",
+ t.updated_at AS "updated_at!",
+ t.viewed_at AS "viewed_at?",
+ lmp.subject AS "name?",
+ lmp.snippet AS "snippet?",
+ lmp.is_draft,
+ -- A thread in "Other" can still be "Important", so we must perform the check.
+ (
+ SELECT EXISTS (
+ SELECT 1
+ FROM email_messages m_imp
+ JOIN email_message_labels ml ON m_imp.id = ml.message_id
+ JOIN email_labels l ON ml.label_id = l.id
+ WHERE m_imp.thread_id = t.id
+ AND l.link_id = t.link_id
+ AND l.name = 'IMPORTANT'
+ )
+ ) AS "is_important!",
+ c.email_address AS "sender_email?",
+ c.name AS "sender_name?",
+ c.sfs_photo_url as "sender_photo_url?"
+ FROM (
+ -- Step 1: Efficiently find, sort, and limit the top N+1 threads that qualify for the "Other" inbox.
+ SELECT
+ t.id,
+ t.provider_id,
+ t.link_id,
+ t.inbox_visible,
+ t.is_read,
+ t.latest_non_spam_message_ts AS created_at,
+ t.latest_non_spam_message_ts AS updated_at,
+ uh.updated_at AS viewed_at,
+ CASE $5 -- sort_method_str
+ WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
+ WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_non_spam_message_ts)
+ ELSE t.latest_non_spam_message_ts
+ END AS effective_ts
+ FROM email_threads t
+ LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id
+ WHERE
+ t.link_id = $1
+ AND t.latest_non_spam_message_ts IS NOT NULL
+ -- Inclusion Criteria: Must have a category label.
+ AND EXISTS (
+ SELECT 1 FROM email_messages m JOIN email_message_labels ml ON m.id = ml.message_id JOIN email_labels l ON ml.label_id = l.id
+ WHERE m.thread_id = t.id AND l.link_id = t.link_id AND l.name IN ('CATEGORY_PROMOTIONS', 'CATEGORY_SOCIAL', 'CATEGORY_FORUMS')
+ )
+ -- ****** CORRECTED EXCLUSION CRITERIA ******
+ -- This now matches the logic of your original query, which did NOT filter out 'INBOX' or 'IMPORTANT'.
+ AND NOT EXISTS (
+ SELECT 1 FROM email_messages m JOIN email_message_labels ml ON m.id = ml.message_id JOIN email_labels l ON ml.label_id = l.id
+ WHERE m.thread_id = t.id AND l.link_id = t.link_id AND l.name IN ('SPAM', 'TRASH', 'DRAFT')
+ )
+
+ AND (($3::timestamptz IS NULL) OR (
+ CASE $5 -- sort_method_str
+ WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
+ WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_non_spam_message_ts)
+ ELSE t.latest_non_spam_message_ts
+ END, t.id
+ ) < ($3::timestamptz, $4::uuid))
+ ORDER BY effective_ts DESC, t.updated_at DESC
+ LIMIT $2
+ ) AS t
+ -- Step 2: For EACH of the limited threads from above, find its latest non-spam/trash message for the preview.
+ CROSS JOIN LATERAL (
+ SELECT
+ m.subject,
+ m.snippet,
+ m.is_draft,
+ m.from_contact_id
+ FROM email_messages m
+ WHERE m.thread_id = t.id
+ AND m.is_draft = FALSE
+ AND NOT EXISTS (
+ SELECT 1 FROM email_message_labels ml JOIN email_labels l ON ml.label_id = l.id
+ WHERE ml.message_id = m.id AND l.link_id = t.link_id AND l.name IN ('SPAM', 'TRASH')
+ )
+ ORDER BY m.internal_date_ts DESC
+ LIMIT 1
+ ) AS lmp
+ -- Step 3: Join to get the sender's details.
+ LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id
+ ORDER BY t.effective_ts DESC, t.updated_at DESC
+ "#,
+ query.link_id, // $1
+ query_limit, // $2
+ cursor_timestamp, // $3
+ cursor_id, // $4
+ sort_method_str, // $5
+ )
+ .fetch_all(pool)
+ .await
+}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/sent.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/sent.rs
new file mode 100644
index 0000000000..c763307a0b
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/sent.rs
@@ -0,0 +1,114 @@
+use super::super::db_types::*;
+use crate::domain::models::PreviewCursorQuery;
+use macro_user_id::user_id::MacroUserIdStr;
+use sqlx::PgPool;
+
+/// Fetches a paginated list of thread previews for the "Sent" view.
+/// This view includes all threads (archived or not) sorted by the timestamp
+/// of the latest sent message. The preview details (subject, snippet) are
+/// taken from the most recent sent message in the thread that is not in the trash.
+#[tracing::instrument(skip(pool), err)]
+pub(crate) async fn sent_preview_cursor(
+ pool: &PgPool,
+ query: &PreviewCursorQuery,
+ user_id: MacroUserIdStr<'_>,
+) -> Result<Vec<ThreadPreviewCursorDbRow>, sqlx::Error> {
+ let query_limit = query.limit as i64;
+ let sort_method_str = query.query.sort_method().to_string();
+ let (cursor_id, cursor_timestamp) = query.query.vals();
+
+ sqlx::query_as!(
+ ThreadPreviewCursorDbRow,
+ r#"
+ SELECT
+ t.id,
+ t.provider_id,
+ t.inbox_visible,
+ t.is_read,
+ t.effective_ts AS "sort_ts!",
+ t.created_at AS "created_at!",
+ t.updated_at AS "updated_at!",
+ t.viewed_at AS "viewed_at?",
+ lmp.subject AS "name?",
+ lmp.snippet AS "snippet?",
+ lmp.is_draft,
+ (
+ SELECT EXISTS (
+ SELECT 1
+ FROM email_messages m_imp
+ JOIN email_message_labels ml ON m_imp.id = ml.message_id
+ JOIN email_labels l ON ml.label_id = l.id
+ WHERE m_imp.thread_id = t.id
+ AND l.name = 'IMPORTANT'
+ AND l.link_id = t.link_id
+ )
+ ) AS "is_important!",
+ c.email_address AS "sender_email?",
+ c.name AS "sender_name?",
+ c.sfs_photo_url as "sender_photo_url?"
+ FROM (
+ -- Step 1: Efficiently find and sort ONLY the top N+1 candidate threads.
+ -- This subquery only touches `threads` and `user_history`.
+ SELECT
+ t.id,
+ t.provider_id,
+ t.link_id,
+ t.inbox_visible,
+ t.is_read,
+ t.latest_outbound_message_ts AS created_at,
+ t.latest_outbound_message_ts AS updated_at,
+ uh.updated_at AS viewed_at,
+ CASE $5 -- sort_method_str
+ WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
+ WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_outbound_message_ts)
+ ELSE t.latest_outbound_message_ts
+ END AS effective_ts
+ FROM email_threads t
+ LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id
+ WHERE
+ t.link_id = $1
+ AND t.latest_outbound_message_ts IS NOT NULL
+
+ -- Cursor logic moved inside for maximum efficiency
+ AND (($3::timestamptz IS NULL) OR (
+ -- This CASE must exactly match the one that defines `effective_ts`
+ CASE $5 -- sort_method_str
+ WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
+ WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_outbound_message_ts)
+ ELSE t.latest_outbound_message_ts
+ END, t.id
+ ) < ($3::timestamptz, $4::uuid))
+ ORDER BY effective_ts DESC, t.updated_at DESC
+ LIMIT $2
+ ) AS t
+ -- Step 2: For EACH of the limited threads from above, find its latest SENT, non-trashed message.
+ CROSS JOIN LATERAL (
+ SELECT
+ m.subject,
+ m.snippet,
+ m.from_contact_id,
+ m.is_draft
+ FROM email_messages m
+ WHERE m.thread_id = t.id
+ AND m.is_sent = TRUE -- This condition is specific to the "Sent" view
+ AND NOT EXISTS (
+ SELECT 1 FROM email_message_labels ml JOIN email_labels l ON ml.label_id = l.id
+ WHERE ml.message_id = m.id AND l.name = 'TRASH' AND l.link_id = t.link_id
+ )
+ ORDER BY m.internal_date_ts DESC
+ LIMIT 1
+ ) AS lmp
+ -- Step 3: Join to get the sender's details for the final result set.
+ LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id
+ -- Final ordering is preserved because the input `t` is already sorted.
+ ORDER BY t.effective_ts DESC, t.updated_at DESC
+ "#,
+ query.link_id, // $1
+ query_limit, // $2
+ cursor_timestamp, // $3
+ cursor_id, // $4
+ sort_method_str, // $5
+ )
+ .fetch_all(pool)
+ .await
+}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/starred.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/starred.rs
new file mode 100644
index 0000000000..ccb01f5036
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/starred.rs
@@ -0,0 +1,112 @@
+use super::super::db_types::*;
+use crate::domain::models::PreviewCursorQuery;
+use macro_user_id::user_id::MacroUserIdStr;
+use sqlx::PgPool;
+
+/// Fetches a paginated list of thread previews for the "Starred" view.
+/// This view includes all threads that contain at least one starred message, sorted by the
+/// timestamp of the most recent starred message within each thread. The preview content is
+/// taken from the most-recent starred message.
+#[tracing::instrument(skip(pool), err)]
+pub(crate) async fn starred_preview_cursor(
+ pool: &PgPool,
+ query: &PreviewCursorQuery,
+ user_id: MacroUserIdStr<'_>,
+) -> Result<Vec<ThreadPreviewCursorDbRow>, sqlx::Error> {
+ let query_limit = query.limit as i64;
+ let sort_method_str = query.query.sort_method().to_string();
+ let (cursor_id, cursor_timestamp) = query.query.vals();
+
+ sqlx::query_as!(
+ ThreadPreviewCursorDbRow,
+ r#"
+ SELECT
+ t.id,
+ t.provider_id,
+ t.inbox_visible,
+ t.is_read,
+ t.effective_ts AS "sort_ts!",
+ t.created_at AS "created_at!",
+ t.updated_at AS "updated_at!",
+ t.viewed_at AS "viewed_at?",
+ lmp.subject AS "name?",
+ lmp.snippet AS "snippet?",
+ lmp.is_draft,
+ (
+ SELECT EXISTS (
+ SELECT 1
+ FROM email_messages m_imp
+ JOIN email_message_labels ml ON m_imp.id = ml.message_id
+ JOIN email_labels l ON ml.label_id = l.id
+ WHERE m_imp.thread_id = t.id
+ AND l.name = 'IMPORTANT'
+ AND l.link_id = t.link_id
+ )
+ ) AS "is_important!",
+ c.email_address AS "sender_email?",
+ c.name AS "sender_name?",
+ c.sfs_photo_url as "sender_photo_url?"
+ FROM (
+ -- Step 1: Find the latest starred timestamp for each thread, calculate the
+ -- effective sort key, then sort and limit the results.
+ SELECT
+ t.id,
+ t.provider_id,
+ t.link_id,
+ t.inbox_visible,
+ t.is_read,
+ lspt.latest_starred_ts AS created_at,
+ lspt.latest_starred_ts AS updated_at,
+ uh.updated_at AS viewed_at,
+ CASE $5 -- sort_method_str
+ WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
+ WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, lspt.latest_starred_ts)
+ ELSE lspt.latest_starred_ts
+ END AS effective_ts
+ FROM (
+ -- This sub-subquery efficiently finds the latest starred timestamp for every thread.
+ SELECT thread_id, MAX(internal_date_ts) as latest_starred_ts
+ FROM email_messages
+ WHERE link_id = $1 AND is_starred = TRUE
+ GROUP BY thread_id
+ ) lspt
+ JOIN email_threads t ON lspt.thread_id = t.id
+ LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id
+ WHERE
+ (($3::timestamptz IS NULL) OR (
+ CASE $5 -- sort_method_str
+ WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
+ WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, lspt.latest_starred_ts)
+ ELSE lspt.latest_starred_ts
+ END, t.id
+ ) < ($3::timestamptz, $4::uuid))
+ ORDER BY effective_ts DESC, t.updated_at DESC
+ LIMIT $2
+ ) AS t
+ -- Step 2: For EACH of the limited threads from above, find the full details of its latest starred message.
+ CROSS JOIN LATERAL (
+ SELECT
+ m.subject,
+ m.snippet,
+ m.from_contact_id,
+ m.is_draft
+ FROM email_messages m
+ WHERE m.thread_id = t.id
+ AND m.is_starred = TRUE
+ AND m.is_draft = FALSE
+ ORDER BY m.internal_date_ts DESC
+ LIMIT 1
+ ) AS lmp
+ -- Step 3: Join to get the sender's details.
+ LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id
+ ORDER BY t.effective_ts DESC, t.updated_at DESC
+ "#,
+ query.link_id, // $1
+ query_limit, // $2
+ cursor_timestamp, // $3
+ cursor_id, // $4
+ sort_method_str, // $5
+ )
+ .fetch_all(pool)
+ .await
+}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/user_label.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/user_label.rs
new file mode 100644
index 0000000000..8b4e2abe74
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/user_label.rs
@@ -0,0 +1,119 @@
+use super::super::db_types::*;
+use crate::domain::models::PreviewCursorQuery;
+use macro_user_id::user_id::MacroUserIdStr;
+use sqlx::PgPool;
+
+/// Fetches a paginated list of thread previews for a user label.
+/// This view includes threads that have at least one message with the given label.
+/// Threads are sorted by the timestamp of the most recent message that has the label.
+/// The preview content is taken from that same most-recent labeled message.
+#[tracing::instrument(skip(pool), err)]
+pub(crate) async fn user_label_preview_cursor(
+ pool: &PgPool,
+ query: &PreviewCursorQuery,
+ label_name: &str,
+ user_id: MacroUserIdStr<'_>,
+) -> Result<Vec<ThreadPreviewCursorDbRow>, sqlx::Error> {
+ let query_limit = query.limit as i64;
+ let sort_method_str = query.query.sort_method().to_string();
+ let (cursor_id, cursor_timestamp) = query.query.vals();
+
+ sqlx::query_as!(
+ ThreadPreviewCursorDbRow,
+ r#"
+ SELECT
+ t.id,
+ t.provider_id,
+ t.inbox_visible,
+ t.is_read,
+ t.effective_ts AS "sort_ts!",
+ t.created_at AS "created_at!",
+ t.updated_at AS "updated_at!",
+ t.viewed_at AS "viewed_at?",
+ lmp.subject AS "name?",
+ lmp.snippet AS "snippet?",
+ lmp.is_draft,
+ (
+ SELECT EXISTS (
+ SELECT 1
+ FROM email_messages m_imp
+ JOIN email_message_labels ml ON m_imp.id = ml.message_id
+ JOIN email_labels l ON ml.label_id = l.id
+ WHERE m_imp.thread_id = t.id
+ AND l.link_id = t.link_id
+ AND l.name = 'IMPORTANT'
+ )
+ ) AS "is_important!",
+ c.email_address AS "sender_email?",
+ c.name AS "sender_name?",
+ c.sfs_photo_url as "sender_photo_url?"
+ FROM (
+ -- Step 1: Find the latest labeled message timestamp for each thread,
+ -- calculate the effective sort key, then sort and limit the results.
+ SELECT
+ t.id,
+ t.provider_id,
+ t.link_id,
+ t.inbox_visible,
+ t.is_read,
+ llpt.latest_labeled_ts AS created_at,
+ llpt.latest_labeled_ts AS updated_at,
+ uh.updated_at AS viewed_at,
+ CASE $6 -- sort_method_str
+ WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
+ WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, llpt.latest_labeled_ts)
+ ELSE llpt.latest_labeled_ts
+ END AS effective_ts
+ FROM (
+ -- This sub-subquery efficiently finds the latest timestamp for every thread
+ -- that has at least one message with the specified label.
+ SELECT
+ m.thread_id,
+ MAX(m.internal_date_ts) as latest_labeled_ts
+ FROM email_messages m
+ JOIN email_message_labels ml ON m.id = ml.message_id
+ JOIN email_labels l ON ml.label_id = l.id
+ WHERE m.link_id = $1 AND l.name = $5
+ GROUP BY m.thread_id
+ ) llpt
+ JOIN email_threads t ON llpt.thread_id = t.id
+ LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = $1
+ WHERE
+ (($3::timestamptz IS NULL) OR (
+ CASE $6 -- sort_method_str
+ WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
+ WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, llpt.latest_labeled_ts)
+ ELSE llpt.latest_labeled_ts
+ END, t.id
+ ) < ($3::timestamptz, $4::uuid))
+ ORDER BY effective_ts DESC, t.updated_at DESC
+ LIMIT $2
+ ) AS t
+ -- Step 2: For EACH of the limited threads from above, find the full details of its latest message with that specific label.
+ CROSS JOIN LATERAL (
+ SELECT
+ m.subject,
+ m.snippet,
+ m.from_contact_id,
+ m.is_draft
+ FROM email_messages m
+ JOIN email_message_labels ml ON m.id = ml.message_id
+ JOIN email_labels l ON ml.label_id = l.id
+ WHERE m.thread_id = t.id AND m.is_draft = FALSE AND l.link_id = t.link_id AND l.name = $5
+ ORDER BY m.internal_date_ts DESC
+ LIMIT 1
+ ) AS lmp
+ -- Step 3: Join to get the sender's details.
+ LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id
+ ORDER BY t.effective_ts DESC, t.updated_at DESC
+ "#,
+ query.link_id, // $1
+ query_limit, // $2
+ cursor_timestamp, // $3
+ cursor_id, // $4
+ label_name, // $5
+ sort_method_str, // $6
+ )
+ .fetch_all(pool)
+ .await
+}
diff --git a/rust/cloud-storage/email_db_client/src/lib.rs b/rust/cloud-storage/email_db_client/src/lib.rs
index 3866799b46..d0ff7aa26c 100644
--- a/rust/cloud-storage/email_db_client/src/lib.rs
+++ b/rust/cloud-storage/email_db_client/src/lib.rs
@@ -6,7 +6,6 @@ pub mod labels;
pub mod links;
pub mod messages;
pub mod parse;
-pub mod previews;
pub mod settings;
pub mod sfs_mappings;
pub mod sync_tokens;
diff --git a/rust/cloud-storage/email_db_client/src/previews/cursor.rs b/rust/cloud-storage/email_db_client/src/previews/cursor.rs
deleted file mode 100644
index b750451dc1..0000000000
--- a/rust/cloud-storage/email_db_client/src/previews/cursor.rs
+++ /dev/null
@@ -1,1043 +0,0 @@
-use anyhow::Context;
-use models_email::email::db;
-use models_email::email::service::thread;
-use models_email::email::service::thread::{
- PreviewCursorQuery, PreviewView, PreviewViewStandardLabel, ThreadPreviewCursor,
-};
-use sqlx::PgPool;
-
-#[tracing::instrument(skip(pool), err)]
-pub async fn fetch_previews_for_view_cursor(
- pool: &PgPool,
- query: PreviewCursorQuery,
- user_id: &str,
-) -> anyhow::Result<Vec<ThreadPreviewCursor>> {
- match query.view {
- PreviewView::StandardLabel(ref label) => match label {
- PreviewViewStandardLabel::Inbox => {
- new_inbox_preview_cursor(pool, &query, user_id).await
- }
- PreviewViewStandardLabel::Sent => sent_preview_cursor(pool, &query, user_id).await,
- PreviewViewStandardLabel::Drafts => drafts_preview_cursor(pool, &query, user_id).await,
- PreviewViewStandardLabel::Starred => {
- starred_preview_cursor(pool, &query, user_id).await
- }
- PreviewViewStandardLabel::All => all_mail_preview_cursor(pool, &query, user_id).await,
- PreviewViewStandardLabel::Important => {
- important_preview_cursor(pool, &query, user_id).await
- }
- PreviewViewStandardLabel::Other => {
- other_inbox_preview_cursor(pool, &query, user_id).await
- }
- },
- PreviewView::UserLabel(ref label_name) => {
- user_label_preview_cursor(pool, &query, label_name, user_id).await
- }
- }
-}
-
-/// Fetches a paginated list of thread previews for a given link_id.
-/// Each thread preview includes details from the latest message (inbound or outbound)
-/// that is NOT in the 'TRASH' label.
-/// The sorting and filtering behavior is determined by the `sort_method` parameter.
-#[tracing::instrument(skip(pool), level = "info")]
-pub async fn new_inbox_preview_cursor(
- pool: &PgPool,
- query: &PreviewCursorQuery,
- user_id: &str,
-) -> anyhow::Result<Vec<thread::ThreadPreviewCursor>> {
- let query_limit = query.limit as i64;
- let sort_method_str = query.query.sort_method().to_string();
- let (cursor_id, cursor_timestamp) = query.query.vals();
-
- let db_previews = sqlx::query_as!(
- db::thread::ThreadPreviewCursor,
- r#"
- SELECT
- t.id,
- t.provider_id,
- TRUE AS "inbox_visible!",
- t.is_read,
- t.effective_ts AS "sort_ts!",
- t.created_at AS "created_at!",
- t.updated_at AS "updated_at!",
- t.viewed_at AS "viewed_at?",
- lmp.subject AS "name?",
- lmp.snippet AS "snippet?",
- lmp.is_draft,
- (
- SELECT EXISTS (
- SELECT 1
- FROM email_messages m_imp
- JOIN email_message_labels ml ON m_imp.id = ml.message_id
- JOIN email_labels l ON ml.label_id = l.id
- WHERE m_imp.thread_id = t.id
- AND l.name = 'IMPORTANT'
- AND l.link_id = t.link_id
- )
- ) AS "is_important!",
- c.email_address AS "sender_email?",
- c.name AS "sender_name?",
- c.sfs_photo_url as "sender_photo_url?"
- FROM (
- -- Step 1: Efficiently find and sort ONLY the top N+1 candidate threads.
- -- This subquery is fast as it only touches `threads` and `user_history`.
- SELECT
- t.id,
- t.provider_id,
- t.link_id,
- t.is_read,
- t.latest_inbound_message_ts AS created_at,
- t.latest_inbound_message_ts AS updated_at,
- uh.updated_at AS viewed_at,
- CASE $5 -- sort_method_str
- WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
- WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_inbound_message_ts)
- ELSE t.latest_inbound_message_ts
- END AS effective_ts
- FROM email_threads t
- LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id
- WHERE
- t.link_id = $1
- AND t.inbox_visible = TRUE
- AND t.latest_inbound_message_ts IS NOT NULL
-
- -- The cursor logic is moved inside this subquery for maximum efficiency.
- AND (($3::timestamptz IS NULL) OR (
- -- This CASE must exactly match the one that defines `effective_ts`
- CASE $5 -- sort_method_str
- WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
- WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_inbound_message_ts)
- ELSE t.latest_inbound_message_ts
- END, t.id
- ) < ($3::timestamptz, $4::uuid))
- ORDER BY effective_ts DESC, t.updated_at DESC -- fall back to updated_at if effective_ts is the same
- LIMIT $2
- ) AS t
- -- Step 2: For EACH of the limited threads from above, find its latest non-trashed message.
- CROSS JOIN LATERAL (
- SELECT
- m.subject,
- m.snippet,
- m.from_contact_id,
- m.is_draft
- FROM email_messages m
- WHERE m.thread_id = t.id
- AND m.is_draft = FALSE
- AND NOT EXISTS (
- SELECT 1 FROM email_message_labels ml JOIN email_labels l ON ml.label_id = l.id
- WHERE ml.message_id = m.id AND l.name = 'TRASH' AND l.link_id = t.link_id
- )
- ORDER BY m.internal_date_ts DESC
- LIMIT 1
- ) AS lmp
- -- Step 3: Join to get the sender's details for the final result set.
- LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id
- -- Final ordering is preserved because the input `t` is already sorted.
- ORDER BY t.effective_ts DESC, t.updated_at DESC -- fall back to updated_at if effective_ts is the same
- "#,
- query.link_id, // $1
- query_limit, // $2
- cursor_timestamp, // $3
- cursor_id, // $4
- sort_method_str, // $5
- ).fetch_all(pool).await.with_context(|| format!("Failed to fetch paginated thread previews for link_id {}", query.link_id))?;
-
- let items = db_previews
- .into_iter()
- .map(|db_preview| ThreadPreviewCursor::new_from(db_preview, user_id.to_string()))
- .collect();
-
- Ok(items)
-}
-
-/// Fetches a paginated list of thread previews for the "Sent" view.
-/// This view includes all threads (archived or not) sorted by the timestamp
-/// of the latest sent message. The preview details (subject, snippet) are
-/// taken from the most recent sent message in the thread that is not in the trash.
-#[tracing::instrument(skip(pool), level = "info")]
-pub async fn sent_preview_cursor(
- pool: &PgPool,
- query: &PreviewCursorQuery,
- user_id: &str,
-) -> anyhow::Result<Vec<ThreadPreviewCursor>> {
- let query_limit = query.limit as i64;
- let sort_method_str = query.query.sort_method().to_string();
- let (cursor_id, cursor_timestamp) = query.query.vals();
-
- let db_previews = sqlx::query_as!(
- db::thread::ThreadPreviewCursor,
- r#"
- SELECT
- t.id,
- t.provider_id,
- t.inbox_visible,
- t.is_read,
- t.effective_ts AS "sort_ts!",
- t.created_at AS "created_at!",
- t.updated_at AS "updated_at!",
- t.viewed_at AS "viewed_at?",
- lmp.subject AS "name?",
- lmp.snippet AS "snippet?",
- lmp.is_draft,
- (
- SELECT EXISTS (
- SELECT 1
- FROM email_messages m_imp
- JOIN email_message_labels ml ON m_imp.id = ml.message_id
- JOIN email_labels l ON ml.label_id = l.id
- WHERE m_imp.thread_id = t.id
- AND l.name = 'IMPORTANT'
- AND l.link_id = t.link_id
- )
- ) AS "is_important!",
- c.email_address AS "sender_email?",
- c.name AS "sender_name?",
- c.sfs_photo_url as "sender_photo_url?"
- FROM (
- -- Step 1: Efficiently find and sort ONLY the top N+1 candidate threads.
- -- This subquery only touches `threads` and `user_history`.
- SELECT
- t.id,
- t.provider_id,
- t.link_id,
- t.inbox_visible,
- t.is_read,
- t.latest_outbound_message_ts AS created_at,
- t.latest_outbound_message_ts AS updated_at,
- uh.updated_at AS viewed_at,
- CASE $5 -- sort_method_str
- WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
- WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_outbound_message_ts)
- ELSE t.latest_outbound_message_ts
- END AS effective_ts
- FROM email_threads t
- LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id
- WHERE
- t.link_id = $1
- AND t.latest_outbound_message_ts IS NOT NULL
-
- -- Cursor logic moved inside for maximum efficiency
- AND (($3::timestamptz IS NULL) OR (
- -- This CASE must exactly match the one that defines `effective_ts`
- CASE $5 -- sort_method_str
- WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
- WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_outbound_message_ts)
- ELSE t.latest_outbound_message_ts
- END, t.id
- ) < ($3::timestamptz, $4::uuid))
- ORDER BY effective_ts DESC, t.updated_at DESC
- LIMIT $2
- ) AS t
- -- Step 2: For EACH of the limited threads from above, find its latest SENT, non-trashed message.
- CROSS JOIN LATERAL (
- SELECT
- m.subject,
- m.snippet,
- m.from_contact_id,
- m.is_draft
- FROM email_messages m
- WHERE m.thread_id = t.id
- AND m.is_sent = TRUE -- This condition is specific to the "Sent" view
- AND NOT EXISTS (
- SELECT 1 FROM email_message_labels ml JOIN email_labels l ON ml.label_id = l.id
- WHERE ml.message_id = m.id AND l.name = 'TRASH' AND l.link_id = t.link_id
- )
- ORDER BY m.internal_date_ts DESC
- LIMIT 1
- ) AS lmp
- -- Step 3: Join to get the sender's details for the final result set.
- LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id
- -- Final ordering is preserved because the input `t` is already sorted.
- ORDER BY t.effective_ts DESC, t.updated_at DESC
- "#,
- query.link_id, // $1
- query_limit, // $2
- cursor_timestamp, // $3
- cursor_id, // $4
- sort_method_str, // $5
- )
- .fetch_all(pool)
- .await
- .with_context(|| {
- format!(
- "Failed to fetch paginated sent preview for link_id {}",
- query.link_id
- )
- })?;
-
- let items = db_previews
- .into_iter()
- .map(|db_preview| ThreadPreviewCursor::new_from(db_preview, user_id.to_string()))
- .collect();
-
- Ok(items)
-}
-
-/// Fetches a paginated list of thread previews for the "Drafts" view.
-/// This view includes all threads that contain at least one draft message, sorted by the
-/// timestamp of the most recent draft within each thread.
-#[tracing::instrument(skip(pool), level = "info", err)]
-pub async fn drafts_preview_cursor(
- pool: &PgPool,
- query: &PreviewCursorQuery,
- user_id: &str,
-) -> anyhow::Result<Vec<thread::ThreadPreviewCursor>> {
- let query_limit = query.limit as i64;
- let sort_method_str = query.query.sort_method().to_string();
- let (cursor_id, cursor_timestamp) = query.query.vals();
-
- let db_previews = sqlx::query_as!(
- db::thread::ThreadPreviewCursor,
- r#"
- SELECT
- t.id,
- t.provider_id,
- t.inbox_visible,
- t.is_read,
- t.effective_ts AS "sort_ts!",
- t.created_at AS "created_at!",
- t.updated_at AS "updated_at!",
- t.viewed_at AS "viewed_at?",
- lmp.subject AS "name?",
- lmp.snippet AS "snippet?",
- lmp.is_draft,
- (
- SELECT EXISTS (
- SELECT 1
- FROM email_messages m_imp
- JOIN email_message_labels ml ON m_imp.id = ml.message_id
- JOIN email_labels l ON ml.label_id = l.id
- WHERE m_imp.thread_id = t.id
- AND l.name = 'IMPORTANT'
- AND l.link_id = t.link_id
- )
- ) AS "is_important!",
- c.email_address AS "sender_email?",
- c.name AS "sender_name?",
- c.sfs_photo_url as "sender_photo_url?"
- FROM (
- -- Step 1: Find the latest draft timestamp for each thread, calculate the
- -- effective sort key, then sort and limit the results. This is the core optimization.
- SELECT
- t.id,
- t.provider_id,
- t.link_id,
- t.inbox_visible,
- t.is_read,
- ldpt.latest_draft_ts AS created_at,
- ldpt.latest_draft_ts AS updated_at,
- uh.updated_at AS viewed_at,
- CASE $5 -- sort_method_str
- WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
- WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, ldpt.latest_draft_ts)
- ELSE ldpt.latest_draft_ts
- END AS effective_ts
- FROM (
- -- This sub-subquery efficiently finds the latest draft timestamp for every thread.
- SELECT thread_id, MAX(updated_at) as latest_draft_ts
- FROM email_messages
- -- we only display macro drafts, not drafts created in gmail
- WHERE link_id = $1 AND is_draft = TRUE AND internal_date_ts IS NULL
- GROUP BY thread_id
- ) ldpt
- JOIN email_threads t ON ldpt.thread_id = t.id
- LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id
- WHERE
- (($3::timestamptz IS NULL) OR (
- CASE $5 -- sort_method_str
- WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
- WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, ldpt.latest_draft_ts)
- ELSE ldpt.latest_draft_ts
- END, t.id
- ) < ($3::timestamptz, $4::uuid))
- ORDER BY effective_ts DESC, t.updated_at DESC
- LIMIT $2
- ) AS t
- -- Step 2: For EACH of the limited threads from above, find the full details of its latest draft.
- CROSS JOIN LATERAL (
- SELECT
- m.subject,
- m.snippet,
- m.from_contact_id,
- m.is_draft
- FROM email_messages m
- WHERE m.thread_id = t.id
- AND m.is_draft = TRUE
- -- we only display macro drafts, not drafts created in gmail
- AND m.internal_date_ts IS NULL
- ORDER BY m.updated_at DESC
- LIMIT 1
- ) AS lmp
- -- Step 3: Join to get the sender's details.
- LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id
- ORDER BY t.effective_ts DESC, t.updated_at DESC
- "#,
- query.link_id, // $1
- query_limit, // $2
- cursor_timestamp, // $3
- cursor_id, // $4
- sort_method_str, // $5
- )
- .fetch_all(pool)
- .await?;
-
- let items = db_previews
- .into_iter()
- .map(|db_preview| ThreadPreviewCursor::new_from(db_preview, user_id.to_string()))
- .collect();
-
- Ok(items)
-}
-
-/// Fetches a paginated list of thread previews for the "Starred" view.
-/// This view includes all threads that contain at least one starred message, sorted by the
-/// timestamp of the most recent starred message within each thread. The preview content is
-/// taken from the most-recent starred message.
-#[tracing::instrument(skip(pool), level = "info")]
-pub async fn starred_preview_cursor(
- pool: &PgPool,
- query: &PreviewCursorQuery,
- user_id: &str,
-) -> anyhow::Result<Vec<thread::ThreadPreviewCursor>> {
- let query_limit = query.limit as i64;
- let sort_method_str = query.query.sort_method().to_string();
- let (cursor_id, cursor_timestamp) = query.query.vals();
-
- let db_previews = sqlx::query_as!(
- db::thread::ThreadPreviewCursor,
- r#"
- SELECT
- t.id,
- t.provider_id,
- t.inbox_visible,
- t.is_read,
- t.effective_ts AS "sort_ts!",
- t.created_at AS "created_at!",
- t.updated_at AS "updated_at!",
- t.viewed_at AS "viewed_at?",
- lmp.subject AS "name?",
- lmp.snippet AS "snippet?",
- lmp.is_draft,
- (
- SELECT EXISTS (
- SELECT 1
- FROM email_messages m_imp
- JOIN email_message_labels ml ON m_imp.id = ml.message_id
- JOIN email_labels l ON ml.label_id = l.id
- WHERE m_imp.thread_id = t.id
- AND l.name = 'IMPORTANT'
- AND l.link_id = t.link_id
- )
- ) AS "is_important!",
- c.email_address AS "sender_email?",
- c.name AS "sender_name?",
- c.sfs_photo_url as "sender_photo_url?"
- FROM (
- -- Step 1: Find the latest starred timestamp for each thread, calculate the
- -- effective sort key, then sort and limit the results.
- SELECT
- t.id,
- t.provider_id,
- t.link_id,
- t.inbox_visible,
- t.is_read,
- lspt.latest_starred_ts AS created_at,
- lspt.latest_starred_ts AS updated_at,
- uh.updated_at AS viewed_at,
- CASE $5 -- sort_method_str
- WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
- WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, lspt.latest_starred_ts)
- ELSE lspt.latest_starred_ts
- END AS effective_ts
- FROM (
- -- This sub-subquery efficiently finds the latest starred timestamp for every thread.
- SELECT thread_id, MAX(internal_date_ts) as latest_starred_ts
- FROM email_messages
- WHERE link_id = $1 AND is_starred = TRUE
- GROUP BY thread_id
- ) lspt
- JOIN email_threads t ON lspt.thread_id = t.id
- LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id
- WHERE
- (($3::timestamptz IS NULL) OR (
- CASE $5 -- sort_method_str
- WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
- WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, lspt.latest_starred_ts)
- ELSE lspt.latest_starred_ts
- END, t.id
- ) < ($3::timestamptz, $4::uuid))
- ORDER BY effective_ts DESC, t.updated_at DESC
- LIMIT $2
- ) AS t
- -- Step 2: For EACH of the limited threads from above, find the full details of its latest starred message.
- CROSS JOIN LATERAL (
- SELECT
- m.subject,
- m.snippet,
- m.from_contact_id,
- m.is_draft
- FROM email_messages m
- WHERE m.thread_id = t.id
- AND m.is_starred = TRUE
- AND m.is_draft = FALSE
- ORDER BY m.internal_date_ts DESC
- LIMIT 1
- ) AS lmp
- -- Step 3: Join to get the sender's details.
- LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id
- ORDER BY t.effective_ts DESC, t.updated_at DESC
- "#,
- query.link_id, // $1
- query_limit, // $2
- cursor_timestamp, // $3
- cursor_id, // $4
- sort_method_str, // $5
- )
- .fetch_all(pool)
- .await
- .with_context(|| {
- format!(
- "Failed to fetch paginated starred preview for link_id {}",
- query.link_id
- )
- })?;
-
- let items = db_previews
- .into_iter()
- .map(|db_preview| ThreadPreviewCursor::new_from(db_preview, user_id.to_string()))
- .collect();
-
- Ok(items)
-}
-
-/// Fetches a paginated list of thread previews for the "All Mail" view using a
-/// denormalized timestamp.
-/// This view includes all threads that have at least one non-spam message, sorted by the
-/// `latest_non_spam_message_ts` column on the `threads` table. The preview shows
-/// details from the latest non-spam message
-#[tracing::instrument(skip(pool), level = "info")]
-pub async fn all_mail_preview_cursor(
- pool: &PgPool,
- query: &PreviewCursorQuery,
- user_id: &str,
-) -> anyhow::Result<Vec<thread::ThreadPreviewCursor>> {
- let query_limit = query.limit as i64;
- let sort_method_str = query.query.sort_method().to_string();
- let (cursor_id, cursor_timestamp) = query.query.vals();
-
- let db_previews = sqlx::query_as!(
- db::thread::ThreadPreviewCursor,
- r#"
- SELECT
- t.id,
- t.provider_id,
- t.inbox_visible,
- t.is_read,
- t.effective_ts AS "sort_ts!",
- t.created_at AS "created_at!",
- t.updated_at AS "updated_at!",
- t.viewed_at AS "viewed_at?",
- lmp.subject AS "name?",
- lmp.snippet AS "snippet?",
- lmp.is_draft,
- (
- SELECT EXISTS (
- SELECT 1
- FROM email_messages m_imp
- JOIN email_message_labels ml ON m_imp.id = ml.message_id
- JOIN email_labels l ON ml.label_id = l.id
- WHERE m_imp.thread_id = t.id
- AND l.name = 'IMPORTANT'
- AND l.link_id = t.link_id
- )
- ) AS "is_important!",
- c.email_address AS "sender_email?",
- c.name AS "sender_name?",
- c.sfs_photo_url as "sender_photo_url?"
- FROM (
- -- Step 1: Efficiently find, sort, and limit the top N+1 threads.
- -- This subquery only touches `threads` and `user_history`, making it very fast.
- SELECT
- t.id,
- t.provider_id,
- t.link_id,
- t.inbox_visible,
- t.is_read,
- t.latest_non_spam_message_ts AS created_at,
- t.latest_non_spam_message_ts AS updated_at,
- uh.updated_at AS viewed_at,
- CASE $5 -- sort_method_str
- WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
- WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_non_spam_message_ts)
- ELSE t.latest_non_spam_message_ts
- END AS effective_ts
- FROM email_threads t
- LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id
- WHERE
- t.link_id = $1
- AND t.latest_non_spam_message_ts IS NOT NULL
-
- -- Cursor logic is moved inside for maximum efficiency
- AND (($3::timestamptz IS NULL) OR (
- -- This CASE must exactly match the one that defines `effective_ts`
- CASE $5 -- sort_method_str
- WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
- WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_non_spam_message_ts)
- ELSE t.latest_non_spam_message_ts
- END, t.id
- ) < ($3::timestamptz, $4::uuid))
- ORDER BY effective_ts DESC, t.updated_at DESC
- LIMIT $2
- ) AS t
- -- Step 2: For EACH of the limited threads from above, find its latest non-SPAM/TRASH message.
- CROSS JOIN LATERAL (
- SELECT
- m.subject,
- m.snippet,
- m.is_draft,
- m.from_contact_id
- FROM email_messages m
- WHERE m.thread_id = t.id
- AND m.is_draft = FALSE
- AND NOT EXISTS (
- SELECT 1
- FROM email_message_labels ml
- JOIN email_labels l ON ml.label_id = l.id
- WHERE ml.message_id = m.id
- AND l.link_id = t.link_id
- AND l.name IN ('SPAM', 'TRASH')
- )
- ORDER BY m.internal_date_ts DESC
- LIMIT 1
- ) AS lmp
- -- Step 3: Join to get the sender's details for the final result set.
- LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id
- ORDER BY t.effective_ts DESC, t.updated_at DESC
- "#,
- query.link_id, // $1
- query_limit, // $2
- cursor_timestamp, // $3
- cursor_id, // $4
- sort_method_str, // $5
- )
- .fetch_all(pool)
- .await
- .with_context(|| {
- format!(
- "Failed to fetch paginated all mail preview for link_id {}",
- query.link_id
- )
- })?;
-
- let items = db_previews
- .into_iter()
- .map(|db_preview| ThreadPreviewCursor::new_from(db_preview, user_id.to_string()))
- .collect();
-
- Ok(items)
-}
-
-/// Fetches a paginated list of thread previews for the "Important" view.
-/// Includes threads that:
-/// 1. Have messages with both 'IMPORTANT' and 'INBOX' labels, or
-/// 2. Contain draft messages
-/// The threads are sorted by timestamp, with preview details taken from the latest qualifying message.
-#[tracing::instrument(skip(pool), level = "info")]
-pub async fn important_preview_cursor(
- pool: &PgPool,
- query: &PreviewCursorQuery,
- user_id: &str,
-) -> anyhow::Result<Vec<thread::ThreadPreviewCursor>> {
- let query_limit = query.limit as i64;
- let sort_method_str = query.query.sort_method().to_string();
- let (cursor_id, cursor_timestamp) = query.query.vals();
-
- let db_previews = sqlx::query_as!(
- db::thread::ThreadPreviewCursor,
- r#"
- WITH ApplicableLabelIDs AS (
- SELECT id
- FROM email_labels
- WHERE link_id = $1
- AND (name = 'INBOX')
- ),
- QualifyingMessages AS (
- SELECT m.thread_id,
- m.internal_date_ts,
- m.is_draft,
- m.subject,
- m.snippet,
- m.from_contact_id
- FROM email_messages m
- WHERE m.link_id = $1
- AND EXISTS (
- SELECT 1
- FROM email_message_labels ml
- JOIN email_labels l ON ml.label_id = l.id
- WHERE ml.message_id = m.id
- AND l.name = 'IMPORTANT'
- )
- AND EXISTS (
- SELECT 1
- FROM email_message_labels ml
- JOIN ApplicableLabelIDs ali ON ml.label_id = ali.id
- WHERE ml.message_id = m.id
- )
-
- UNION ALL
-
- SELECT m.thread_id,
- m.internal_date_ts,
- m.is_draft,
- m.subject,
- m.snippet,
- m.from_contact_id
- FROM email_messages m
- WHERE m.link_id = $1
- AND m.is_draft = TRUE
- ),
- AllImportantThreads AS (
- -- From all qualifying messages, get the single most recent one per thread.
- SELECT DISTINCT ON (thread_id)
- thread_id,
- internal_date_ts,
- is_draft,
- subject,
- snippet,
- from_contact_id
- FROM QualifyingMessages
- ORDER BY thread_id, internal_date_ts DESC
- ),
- ImportantWithSortKey AS (
- -- Join with user_history to calculate the final effective sort key.
- SELECT
- ait.thread_id,
- ait.internal_date_ts,
- ait.is_draft,
- ait.subject,
- ait.snippet,
- ait.from_contact_id,
- ait.internal_date_ts as created_at,
- ait.internal_date_ts as updated_at,
- uh.updated_at as viewed_at,
- -- This CASE statement dynamically selects the correct timestamp for sorting.
- -- For 'updated_at' and 'created_at', we use the important message timestamp
- -- For 'viewed_at', we use the history timestamp.
- -- For 'viewed_updated', we use the history timestamp if it exists, otherwise the important message timestamp.
- CASE $5 -- sort_method_str
- WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
- WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, ait.internal_date_ts)
- ELSE ait.internal_date_ts
- END AS effective_ts
- FROM AllImportantThreads ait
- -- This has to be a left join to support all sort methods.
- LEFT JOIN email_user_history uh ON uh.thread_id = ait.thread_id AND uh.link_id = $1
- -- user_history updated_at (aka last time opened) has to exist when viewed_at sort method is selected.
- WHERE ait.is_draft = FALSE
- )
- SELECT
- isk.thread_id as "id!",
- t.provider_id,
- t.inbox_visible,
- t.is_read,
- isk.effective_ts as "sort_ts!",
- isk.created_at as "created_at!",
- isk.updated_at as "updated_at!",
- isk.viewed_at as "viewed_at?",
- isk.is_draft as "is_draft!",
- -- It's the important view - all threads here are important
- true as "is_important!",
- isk.subject as "name?",
- isk.snippet as "snippet?",
- c.email_address AS "sender_email?",
- c.name AS "sender_name?",
- c.sfs_photo_url as "sender_photo_url?"
- FROM ImportantWithSortKey isk
- JOIN email_threads t ON isk.thread_id = t.id
- LEFT JOIN email_contacts c ON isk.from_contact_id = c.id
- WHERE
- ($3::timestamptz IS NULL) OR (isk.effective_ts, isk.thread_id) < ($3::timestamptz, $4::uuid)
- ORDER BY isk.effective_ts DESC, isk.thread_id DESC
- LIMIT $2
- "#,
- query.link_id, // $1
- query_limit, // $2
- cursor_timestamp, // $3
- cursor_id, // $4
- sort_method_str, // $5
- )
- .fetch_all(pool)
- .await
- .with_context(|| {
- format!(
- "Failed to fetch paginated important preview for link_id {}",
- query.link_id
- )
- })?;
-
- let items = db_previews
- .into_iter()
- .map(|db_preview| ThreadPreviewCursor::new_from(db_preview, user_id.to_string()))
- .collect();
-
- Ok(items)
-}
-
-/// Fetches a paginated list of thread previews for the "Other" inbox view.
-/// This view includes threads that have a category label (Promotions, Social, etc.)
-/// and are not explicitly spam, trash, or drafts.
-#[tracing::instrument(skip(pool), level = "info")]
-pub async fn other_inbox_preview_cursor(
- pool: &PgPool,
- query: &PreviewCursorQuery,
- user_id: &str,
-) -> anyhow::Result<Vec<thread::ThreadPreviewCursor>> {
- let query_limit = query.limit as i64;
- let sort_method_str = query.query.sort_method().to_string();
- let (cursor_id, cursor_timestamp) = query.query.vals();
-
- let db_previews = sqlx::query_as!(
- db::thread::ThreadPreviewCursor,
- r#"
- SELECT
- t.id,
- t.provider_id,
- t.inbox_visible,
- t.is_read,
- t.effective_ts AS "sort_ts!",
- t.created_at AS "created_at!",
- t.updated_at AS "updated_at!",
- t.viewed_at AS "viewed_at?",
- lmp.subject AS "name?",
- lmp.snippet AS "snippet?",
- lmp.is_draft,
- -- A thread in "Other" can still be "Important", so we must perform the check.
- (
- SELECT EXISTS (
- SELECT 1
- FROM email_messages m_imp
- JOIN email_message_labels ml ON m_imp.id = ml.message_id
- JOIN email_labels l ON ml.label_id = l.id
- WHERE m_imp.thread_id = t.id
- AND l.link_id = t.link_id
- AND l.name = 'IMPORTANT'
- )
- ) AS "is_important!",
- c.email_address AS "sender_email?",
- c.name AS "sender_name?",
- c.sfs_photo_url as "sender_photo_url?"
- FROM (
- -- Step 1: Efficiently find, sort, and limit the top N+1 threads that qualify for the "Other" inbox.
- SELECT
- t.id,
- t.provider_id,
- t.link_id,
- t.inbox_visible,
- t.is_read,
- t.latest_non_spam_message_ts AS created_at,
- t.latest_non_spam_message_ts AS updated_at,
- uh.updated_at AS viewed_at,
- CASE $5 -- sort_method_str
- WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
- WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_non_spam_message_ts)
- ELSE t.latest_non_spam_message_ts
- END AS effective_ts
- FROM email_threads t
- LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id
- WHERE
- t.link_id = $1
- AND t.latest_non_spam_message_ts IS NOT NULL
- -- Inclusion Criteria: Must have a category label.
- AND EXISTS (
- SELECT 1 FROM email_messages m JOIN email_message_labels ml ON m.id = ml.message_id JOIN email_labels l ON ml.label_id = l.id
- WHERE m.thread_id = t.id AND l.link_id = t.link_id AND l.name IN ('CATEGORY_PROMOTIONS', 'CATEGORY_SOCIAL', 'CATEGORY_FORUMS')
- )
- -- ****** CORRECTED EXCLUSION CRITERIA ******
- -- This now matches the logic of your original query, which did NOT filter out 'INBOX' or 'IMPORTANT'.
- AND NOT EXISTS (
- SELECT 1 FROM email_messages m JOIN email_message_labels ml ON m.id = ml.message_id JOIN email_labels l ON ml.label_id = l.id
- WHERE m.thread_id = t.id AND l.link_id = t.link_id AND l.name IN ('SPAM', 'TRASH', 'DRAFT')
- )
-
- AND (($3::timestamptz IS NULL) OR (
- CASE $5 -- sort_method_str
- WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
- WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_non_spam_message_ts)
- ELSE t.latest_non_spam_message_ts
- END, t.id
- ) < ($3::timestamptz, $4::uuid))
- ORDER BY effective_ts DESC, t.updated_at DESC
- LIMIT $2
- ) AS t
- -- Step 2: For EACH of the limited threads from above, find its latest non-spam/trash message for the preview.
- CROSS JOIN LATERAL (
- SELECT
- m.subject,
- m.snippet,
- m.is_draft,
- m.from_contact_id
- FROM email_messages m
- WHERE m.thread_id = t.id
- AND m.is_draft = FALSE
- AND NOT EXISTS (
- SELECT 1 FROM email_message_labels ml JOIN email_labels l ON ml.label_id = l.id
- WHERE ml.message_id = m.id AND l.link_id = t.link_id AND l.name IN ('SPAM', 'TRASH')
- )
- ORDER BY m.internal_date_ts DESC
- LIMIT 1
- ) AS lmp
- -- Step 3: Join to get the sender's details.
- LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id
- ORDER BY t.effective_ts DESC, t.updated_at DESC
- "#,
- query.link_id, // $1
- query_limit, // $2
- cursor_timestamp, // $3
- cursor_id, // $4
- sort_method_str, // $5
- )
- .fetch_all(pool)
- .await
- .with_context(|| {
- format!(
- "Failed to fetch paginated other inbox preview for link_id {}",
- query.link_id
- )
- })?;
-
- let items = db_previews
- .into_iter()
- .map(|db_preview| ThreadPreviewCursor::new_from(db_preview, user_id.to_string()))
- .collect();
-
- Ok(items)
-}
-
-/// Fetches a paginated list of thread previews for a user label.
-/// This view includes threads that have at least one message with the given label.
-/// Threads are sorted by the timestamp of the most recent message that has the label.
-/// The preview content is taken from that same most-recent labeled message.
-#[tracing::instrument(skip(pool), level = "info")]
-pub async fn user_label_preview_cursor(
- pool: &PgPool,
- query: &PreviewCursorQuery,
- label_name: &str,
- user_id: &str,
-) -> anyhow::Result<Vec<thread::ThreadPreviewCursor>> {
- let query_limit = query.limit as i64;
- let sort_method_str = query.query.sort_method().to_string();
- let (cursor_id, cursor_timestamp) = query.query.vals();
-
- let db_previews = sqlx::query_as!(
- db::thread::ThreadPreviewCursor,
- r#"
- SELECT
- t.id,
- t.provider_id,
- t.inbox_visible,
- t.is_read,
- t.effective_ts AS "sort_ts!",
- t.created_at AS "created_at!",
- t.updated_at AS "updated_at!",
- t.viewed_at AS "viewed_at?",
- lmp.subject AS "name?",
- lmp.snippet AS "snippet?",
- lmp.is_draft,
- (
- SELECT EXISTS (
- SELECT 1
- FROM email_messages m_imp
- JOIN email_message_labels ml ON m_imp.id = ml.message_id
- JOIN email_labels l ON ml.label_id = l.id
- WHERE m_imp.thread_id = t.id
- AND l.link_id = t.link_id
- AND l.name = 'IMPORTANT'
- )
- ) AS "is_important!",
- c.email_address AS "sender_email?",
- c.name AS "sender_name?",
- c.sfs_photo_url as "sender_photo_url?"
- FROM (
- -- Step 1: Find the latest labeled message timestamp for each thread,
- -- calculate the effective sort key, then sort and limit the results.
- SELECT
- t.id,
- t.provider_id,
- t.link_id,
- t.inbox_visible,
- t.is_read,
- llpt.latest_labeled_ts AS created_at,
- llpt.latest_labeled_ts AS updated_at,
- uh.updated_at AS viewed_at,
- CASE $6 -- sort_method_str
- WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
- WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, llpt.latest_labeled_ts)
- ELSE llpt.latest_labeled_ts
- END AS effective_ts
- FROM (
- -- This sub-subquery efficiently finds the latest timestamp for every thread
- -- that has at least one message with the specified label.
- SELECT
- m.thread_id,
- MAX(m.internal_date_ts) as latest_labeled_ts
- FROM email_messages m
- JOIN email_message_labels ml ON m.id = ml.message_id
- JOIN email_labels l ON ml.label_id = l.id
- WHERE m.link_id = $1 AND l.name = $5
- GROUP BY m.thread_id
- ) llpt
- JOIN email_threads t ON llpt.thread_id = t.id
- LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = $1
- WHERE
- (($3::timestamptz IS NULL) OR (
- CASE $6 -- sort_method_str
- WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
- WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, llpt.latest_labeled_ts)
- ELSE llpt.latest_labeled_ts
- END, t.id
- ) < ($3::timestamptz, $4::uuid))
- ORDER BY effective_ts DESC, t.updated_at DESC
- LIMIT $2
- ) AS t
- -- Step 2: For EACH of the limited threads from above, find the full details of its latest message with that specific label.
- CROSS JOIN LATERAL (
- SELECT
- m.subject,
- m.snippet,
- m.from_contact_id,
- m.is_draft
- FROM email_messages m
- JOIN email_message_labels ml ON m.id = ml.message_id
- JOIN email_labels l ON ml.label_id = l.id
- WHERE m.thread_id = t.id AND m.is_draft = FALSE AND l.link_id = t.link_id AND l.name = $5
- ORDER BY m.internal_date_ts DESC
- LIMIT 1
- ) AS lmp
- -- Step 3: Join to get the sender's details.
- LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id
- ORDER BY t.effective_ts DESC, t.updated_at DESC
- "#,
- query.link_id, // $1
- query_limit, // $2
- cursor_timestamp, // $3
- cursor_id, // $4
- label_name, // $5
- sort_method_str, // $6
- )
- .fetch_all(pool)
- .await
- .with_context(|| {
- format!(
- "Failed to fetch paginated user label preview for link_id {} and label '{}'",
- query.link_id, label_name
- )
- })?;
-
- let items = db_previews
- .into_iter()
- .map(|db_preview| ThreadPreviewCursor::new_from(db_preview, user_id.to_string()))
- .collect();
-
- Ok(items)
-}
diff --git a/rust/cloud-storage/email_db_client/src/previews/mod.rs b/rust/cloud-storage/email_db_client/src/previews/mod.rs
deleted file mode 100644
index 6502d0c0fb..0000000000
--- a/rust/cloud-storage/email_db_client/src/previews/mod.rs
+++ /dev/null
@@ -1 +0,0 @@
-pub mod cursor;
diff --git a/rust/cloud-storage/email_service/Cargo.toml b/rust/cloud-storage/email_service/Cargo.toml
index 3b2b7c3aa1..ed691b868a 100644
--- a/rust/cloud-storage/email_service/Cargo.toml
+++ b/rust/cloud-storage/email_service/Cargo.toml
@@ -38,6 +38,7 @@ cloudfront_sign = { workspace = true }
connection_gateway = { path = "../connection_gateway" }
document_storage_service_client = { path = "../document_storage_service_client" }
ego-tree = { workspace = true }
+email = { path = "../email", features = ["axum"] }
email_db_client = { path = "../email_db_client" }
frecency = { path = "../frecency", features = ["postgres"] }
futures = { workspace = true }
@@ -72,11 +73,12 @@ reqwest = { workspace = true, features = ["stream"] }
s3_client = { path = "../s3_client" }
schemars = { workspace = true }
scraper = { workspace = true }
-sha2 = { workspace = true }
secretsmanager_client = { path = "../secretsmanager_client" }
serde = { workspace = true }
serde_json = { workspace = true }
+sha2 = { workspace = true }
sqlx = { workspace = true }
+sqlx-core = { workspace = true }
sqs_client = { path = "../sqs_client", default-features = false, features = [
"email",
@@ -97,7 +99,6 @@ urlencoding = { workspace = true }
utoipa = { workspace = true }
utoipa-swagger-ui = { workspace = true }
uuid = { workspace = true }
-sqlx-core = { workspace = true }
[dev-dependencies]
macro_auth = { path = "../macro_auth", features = ["testing"] }
diff --git a/rust/cloud-storage/email_service/src/api/context.rs b/rust/cloud-storage/email_service/src/api/context.rs
index 6fca19bfa2..c6268adf88 100644
--- a/rust/cloud-storage/email_service/src/api/context.rs
+++ b/rust/cloud-storage/email_service/src/api/context.rs
@@ -1,7 +1,8 @@
use crate::{config::Config, util::redis::RedisClient};
use axum::extract::FromRef;
use document_storage_service_client::DocumentStorageServiceClient;
-use frecency::outbound::postgres::FrecencyPgStorage;
+use email::{domain::service::EmailServiceImpl, inbound::EmailPreviewState, outbound::EmailPgRepo};
+use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage};
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
use secretsmanager_client::LocalOrRemoteSecret;
@@ -21,5 +22,7 @@ pub(crate) struct ApiContext {
pub jwt_args: JwtValidationArgs,
pub config: Arc<Config>,
pub internal_auth_key: LocalOrRemoteSecret<InternalApiSecretKey>,
- pub frecency_storage: FrecencyPgStorage,
+ pub email_cursor_service: EmailPreviewState<
+ EmailServiceImpl<EmailPgRepo, FrecencyQueryServiceImpl<FrecencyPgStorage>>,
+ >,
}
diff --git a/rust/cloud-storage/email_service/src/api/email/threads/mod.rs b/rust/cloud-storage/email_service/src/api/email/threads/mod.rs
index d066d31e8a..2bbe0b8bd8 100644
--- a/rust/cloud-storage/email_service/src/api/email/threads/mod.rs
+++ b/rust/cloud-storage/email_service/src/api/email/threads/mod.rs
@@ -11,7 +11,10 @@ use crate::api::ApiContext;
pub fn router(state: ApiContext) -> Router<ApiContext> {
Router::new()
- .nest("/previews", previews::router(state.clone()))
+ .nest(
+ "/previews",
+ previews::router(state.email_cursor_service.clone(), state.clone()),
+ )
.route(
"/:id",
get(get::get_thread_handler).layer(axum::middleware::from_fn_with_state(
diff --git a/rust/cloud-storage/email_service/src/api/email/threads/previews/cursor.rs b/rust/cloud-storage/email_service/src/api/email/threads/previews/cursor.rs
deleted file mode 100644
index 353d145735..0000000000
--- a/rust/cloud-storage/email_service/src/api/email/threads/previews/cursor.rs
+++ /dev/null
@@ -1,224 +0,0 @@
-use crate::api::context::ApiContext;
-use crate::api::email::threads::previews::GetPreviewsPaginationCursorParams;
-use axum::extract::rejection::PathRejection;
-use axum::extract::{FromRequestParts, Path, State};
-use axum::http::StatusCode;
-use axum::http::request::Parts;
-use axum::response::{IntoResponse, Response};
-use axum::{Extension, Json, RequestPartsExt, async_trait, extract};
-use email_db_client::attachments::marco::get_macro_attachments_by_thread_ids;
-use email_db_client::attachments::provider::get_attachments_by_thread_ids;
-use email_db_client::contacts::get::get_contacts_by_thread_ids;
-use email_db_client::previews::cursor::fetch_previews_for_view_cursor;
-use frecency::domain::ports::AggregateFrecencyStorage;
-use futures::join;
-use macro_user_id::cowlike::CowLike;
-use macro_user_id::user_id::MacroUserIdStr;
-use model::response::ErrorResponse;
-use model::user::UserContext;
-use model_entity::EntityType;
-use models_email::email::service::thread::{
- GetPreviewsCursorParams, PreviewCursorQuery, PreviewView,
-};
-use models_email::service::link::Link;
-use models_email::service::thread::ThreadPreviewCursor;
-use models_pagination::{
- CursorExtractor, CursorVal, Identify, PaginateOn, Paginated, SimpleSortMethod, SortOn,
- TypeEraseCursor,
-};
-use schemars::JsonSchema;
-use serde::Serialize;
-use std::collections::HashMap;
-use std::str::FromStr;
-use strum_macros::AsRefStr;
-use thiserror::Error;
-use utoipa::ToSchema;
-use uuid::Uuid;
-
-#[derive(Debug, Error, AsRefStr)]
-pub enum GetPreviewsCursorError {
- #[error(transparent)]
- PathErr(#[from] PathRejection),
- #[error("Invalid view parameter: {0}")]
- InvalidView(String),
-
- #[error("Internal server error")]
- DatabaseQueryError(String, anyhow::Error),
-
- #[error("Internal server error")]
- Frecency(#[from] sqlx::Error),
-
- #[error("Invalid user id")]
- Id(#[from] macro_user_id::user_id::ParseErr),
-}
-
-impl IntoResponse for GetPreviewsCursorError {
- fn into_response(self) -> Response {
- let msg = self.to_string();
-
- let status_code = match self {
- GetPreviewsCursorError::InvalidView(_) => StatusCode::BAD_REQUEST,
- GetPreviewsCursorError::DatabaseQueryError(_, _)
- | GetPreviewsCursorError::Frecency(_)
- | GetPreviewsCursorError::Id(_) => StatusCode::INTERNAL_SERVER_ERROR,
- GetPreviewsCursorError::PathErr(path_rejection) => {
- return path_rejection.into_response();
- }
- };
-
- (status_code, msg).into_response()
- }
-}
-
-pub struct PreviewViewExtractor(PreviewView);
-
-#[async_trait]
-impl<S: Send + Sync> FromRequestParts<S> for PreviewViewExtractor {
- type Rejection = GetPreviewsCursorError;
-
- async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
- let Path(view) = parts.extract::<Path<String>>().await?;
- Ok(PreviewViewExtractor(
- PreviewView::from_str(&view).map_err(GetPreviewsCursorError::InvalidView)?,
- ))
- }
-}
-
-#[derive(Debug, Serialize, JsonSchema, ToSchema)]
-pub struct ThreadPreviewFrecency {
- #[serde(flatten)]
- preview: ThreadPreviewCursor,
- frecency_score: f64,
-}
-
-impl Identify for ThreadPreviewFrecency {
- type Id = Uuid;
-
- fn id(&self) -> Self::Id {
- self.preview.id()
- }
-}
-
-impl SortOn<SimpleSortMethod> for ThreadPreviewFrecency {
- fn sort_on(sort: SimpleSortMethod) -> impl FnOnce(&Self) -> CursorVal<SimpleSortMethod> {
- let cb = ThreadPreviewCursor::sort_on(sort);
- move |v| cb(&v.preview)
- }
-}
-
-#[derive(Debug, Serialize, JsonSchema, ToSchema)]
-pub struct ThreadPreviewPagination {
- items: Vec<ThreadPreviewFrecency>,
- next_cursor: Option<String>,
-}
-
-#[derive(Debug, Serialize, JsonSchema, ToSchema)]
-pub struct GetPreviewsFrecencyResponse {
- /// the thread, with messages inside
- pub previews: ThreadPreviewPagination,
-}
-
-/// Get paginated thread previews with cursor-based pagination.
-#[utoipa::path(
- get,
- tag = "Previews",
- path = "/email/threads/previews/cursor/{view}",
- operation_id = "previews_inbox_cursor",
- params(
- GetPreviewsCursorParams,
- ("view" = String, Path, description = "View type. Supported values: inbox, sent, drafts, starred, all, important, other, user:<label>"),
- ("cursor" = Option<String>, Query, description = "Cursor value. Base64 encoded timestamp and item id, separated by |."),
- ),
- responses(
- (status = 200, body=GetPreviewsFrecencyResponse),
- (status = 400, body=ErrorResponse),
- (status = 401, body=ErrorResponse),
- (status = 500, body=ErrorResponse),
- )
-)]
-#[tracing::instrument(skip(ctx, user_context, link), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id))]
-pub async fn previews_handler(
- State(ctx): State<ApiContext>,
- user_context: Extension<UserContext>,
- link: Extension<Link>,
- PreviewViewExtractor(preview_view): PreviewViewExtractor,
- extract::Query(params): extract::Query<GetPreviewsCursorParams>,
- cursor: CursorExtractor<Uuid, SimpleSortMethod, ()>,
-) -> Result<Json<GetPreviewsFrecencyResponse>, GetPreviewsCursorError> {
- let params = GetPreviewsPaginationCursorParams::new_from_params(params);
-
- let query = PreviewCursorQuery {
- view: preview_view,
- link_id: link.id,
- limit: params.limit,
- query: cursor.into_query(params.sort_method, ()),
- };
- let sort_method = *query.query.sort_method();
-
- let previews = fetch_previews_for_view_cursor(&ctx.db, query, &link.macro_id)
- .await
- .map_err(|e| GetPreviewsCursorError::DatabaseQueryError("fetch_previews".to_string(), e))?;
-
- let thread_ids: Vec<Uuid> = previews.iter().map(|p| p.id).collect();
-
- let (attachment_map_result, macro_attachment_map_result, participant_result, frecency_scores) = join!(
- get_attachments_by_thread_ids(&ctx.db, &thread_ids),
- get_macro_attachments_by_thread_ids(&ctx.db, &thread_ids),
- get_contacts_by_thread_ids(&ctx.db, &thread_ids),
- ctx.frecency_storage.get_aggregate_for_user_entities(
- MacroUserIdStr::parse_from_str(&link.macro_id)?.into_owned(),
- thread_ids
- .iter()
- .map(|id| EntityType::Email.with_entity_string(id.to_string()))
- )
- );
-
- let mut attachment_map = attachment_map_result.map_err(|e| {
- GetPreviewsCursorError::DatabaseQueryError("fetch_attachments".to_string(), e)
- })?;
-
- let mut macro_attachment_map = macro_attachment_map_result.map_err(|e| {
- GetPreviewsCursorError::DatabaseQueryError("fetch_macro_attachments".to_string(), e)
- })?;
-
- let mut participant_map = participant_result.map_err(|e| {
- GetPreviewsCursorError::DatabaseQueryError("fetch_participants".to_string(), e)
- })?;
-
- let frecency_scores_map: HashMap<Uuid, f64> = frecency_scores
- .unwrap_or_default()
- .into_iter()
- .filter_map(|v| {
- Some((
- Uuid::from_str(&v.id.entity.entity_id).ok()?,
- v.data.frecency_score,
- ))
- })
- .collect();
-
- let Paginated {
- items, next_cursor, ..
- } = previews
- .into_iter()
- .map(|mut item| {
- item.attachments = attachment_map.remove(&item.id).unwrap_or_default();
- item.attachments_macro = macro_attachment_map.remove(&item.id).unwrap_or_default();
- item.participants = participant_map.remove(&item.id).unwrap_or_default();
- let frecency_score = frecency_scores_map
- .get(&item.id)
- .copied()
- .unwrap_or_default();
-
- ThreadPreviewFrecency {
- preview: item,
- frecency_score,
- }
- })
- .paginate_on(params.limit as usize, sort_method)
- .into_page()
- .type_erase();
-
- Ok(Json(GetPreviewsFrecencyResponse {
- previews: ThreadPreviewPagination { items, next_cursor },
- }))
-}
diff --git a/rust/cloud-storage/email_service/src/api/email/threads/previews/mod.rs b/rust/cloud-storage/email_service/src/api/email/threads/previews/mod.rs
index 63bc58b01d..cfe1d33fe6 100644
--- a/rust/cloud-storage/email_service/src/api/email/threads/previews/mod.rs
+++ b/rust/cloud-storage/email_service/src/api/email/threads/previews/mod.rs
@@ -1,45 +1,38 @@
-pub(crate) mod cursor;
-
-use axum::Router;
-use axum::routing::get;
-use models_email::service::thread::GetPreviewsCursorParams;
-use models_pagination::SimpleSortMethod;
+use axum::extract::Request;
+use axum::middleware::Next;
+use axum::response::Response;
+use axum::{Extension, Router};
+use email::domain::ports::EmailService;
+use email::inbound::EmailPreviewState;
+use tower::ServiceBuilder;
use crate::api::ApiContext;
-pub fn router(state: ApiContext) -> Router<ApiContext> {
- Router::new().route(
- "/cursor/:view",
- get(cursor::previews_handler).layer(axum::middleware::from_fn_with_state(
- state,
- crate::api::middleware::link::attach_link_context,
- )),
+pub fn router<S, T>(state: EmailPreviewState<T>, api_context: ApiContext) -> Router<S>
+where
+ S: Send + Sync + Clone + 'static,
+ T: EmailService,
+{
+ email::inbound::router(state).layer(
+ ServiceBuilder::new()
+ .layer(axum::middleware::from_fn(link_to_link_uuid_extension))
+ .layer(axum::middleware::from_fn_with_state(
+ api_context,
+ crate::api::middleware::link::attach_link_context,
+ )),
)
}
-/// The default number of previews to return
-const DEFAULT_PREVIEW_LIMIT: u32 = 20;
-/// The max number of previews that can be returned in a response
-const PREVIEW_MAX: u32 = 500;
-
-#[derive(Debug, Clone)]
-struct GetPreviewsPaginationCursorParams {
- limit: u32,
- sort_method: SimpleSortMethod,
-}
-
-impl GetPreviewsPaginationCursorParams {
- /// Extracts pagination parameters from query params, using defaults when not specified
- fn new_from_params(params: GetPreviewsCursorParams) -> Self {
- GetPreviewsPaginationCursorParams {
- limit: params
- .limit
- .filter(|&limit| 0 < limit && limit <= PREVIEW_MAX)
- .unwrap_or(DEFAULT_PREVIEW_LIMIT),
- sort_method: params
- .sort_method
- .map(|s| s.into_simple_sort())
- .unwrap_or(SimpleSortMethod::ViewedUpdated),
- }
- }
+/// the email inbound router currently depends on a [email::inbound::LinkUuid] extension
+/// the service itself should be able to extract this but thats too much of a rework for right now
+/// this middleware is used to take a [models_email::service::link::Link] extension and create a [email::inbound::LinkUuid] extension
+async fn link_to_link_uuid_extension(
+ link: Extension<models_email::service::link::Link>,
+ mut req: Request,
+ next: Next,
+) -> Response {
+ let link_uuid = link.0.id;
+ req.extensions_mut()
+ .insert(email::inbound::LinkUuid(link_uuid));
+ next.run(req).await
}
diff --git a/rust/cloud-storage/email_service/src/api/swagger.rs b/rust/cloud-storage/email_service/src/api/swagger.rs
index d37fa1929e..f24501d42f 100644
--- a/rust/cloud-storage/email_service/src/api/swagger.rs
+++ b/rust/cloud-storage/email_service/src/api/swagger.rs
@@ -13,22 +13,19 @@ use crate::api::email::messages::send::{SendMessageRequest, SendMessageResponse}
use crate::api::email::settings::patch::{PatchSettingsRequest, PatchSettingsResponse};
use crate::api::email::threads::archived::ArchiveThreadRequest;
use crate::api::email::threads::get::GetThreadResponse;
-use crate::api::email::threads::previews::cursor::{
- GetPreviewsFrecencyResponse, ThreadPreviewFrecency, ThreadPreviewPagination,
-};
use crate::api::{email, health};
+use ::email::inbound;
+use ::email::inbound::{ApiPaginatedThreadCursor, ApiSortMethod, GetPreviewsCursorParams};
use model::response::EmptyResponse;
use models_email::api::settings::Settings;
use models_email::email::service;
use models_email::email::service::address::ContactInfoWithInteraction;
use models_email::email::service::backfill::BackfillJob;
use models_email::email::service::link::Link;
-use models_email::email::service::thread::{
- GetPreviewsCursorParams, GetPreviewsCursorResponse, PreviewView, PreviewViewStandardLabel,
-};
+use models_email::email::service::thread::{PreviewView, PreviewViewStandardLabel};
use models_email::service::label::Label;
use models_email::service::message::{MessageToSend, ParsedMessage};
-use models_email::service::thread::{APIThread, ApiSortMethod, ThreadPreviewCursor};
+use models_email::service::thread::{APIThread, ThreadPreviewCursor};
use utoipa::OpenApi;
#[derive(OpenApi)]
@@ -53,7 +50,7 @@ use utoipa::OpenApi;
email::threads::get::get_thread_handler,
email::threads::get::get_thread_messages_handler,
email::threads::archived::archived_handler,
- email::threads::previews::cursor::previews_handler,
+ inbound::cursor_handler,
email::links::list::list_links_handler,
email::labels::create::handler,
email::labels::delete::handler,
@@ -95,10 +92,7 @@ use utoipa::OpenApi;
ThreadPreviewCursor,
// Preview types
GetPreviewsCursorParams,
- GetPreviewsCursorResponse,
- GetPreviewsFrecencyResponse,
- ThreadPreviewFrecency,
- ThreadPreviewPagination,
+ ApiPaginatedThreadCursor,
PreviewView,
PreviewViewStandardLabel,
// Attachment types
diff --git a/rust/cloud-storage/email_service/src/main.rs b/rust/cloud-storage/email_service/src/main.rs
index fecf5481f1..ae3f769ebe 100644
--- a/rust/cloud-storage/email_service/src/main.rs
+++ b/rust/cloud-storage/email_service/src/main.rs
@@ -3,7 +3,8 @@ use crate::config::CloudfrontSignerPrivateKey;
use anyhow::Context;
use config::{Config, Environment};
use document_storage_service_client::DocumentStorageServiceClient;
-use frecency::outbound::postgres::FrecencyPgStorage;
+use email::{domain::service::EmailServiceImpl, inbound::EmailPreviewState, outbound::EmailPgRepo};
+use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage};
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_entrypoint::MacroEntrypoint;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
@@ -328,7 +329,10 @@ async fn main() -> anyhow::Result<()> {
dss_client: Arc::new(dss_client),
jwt_args,
internal_auth_key: LocalOrRemoteSecret::Local(internal_auth_key),
- frecency_storage: FrecencyPgStorage::new(db.clone()),
+ email_cursor_service: EmailPreviewState::new(EmailServiceImpl::new(
+ EmailPgRepo::new(db.clone()),
+ FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(db)),
+ )),
})
.await?;
Ok(())
diff --git a/rust/cloud-storage/email_service_client/Cargo.toml b/rust/cloud-storage/email_service_client/Cargo.toml
index 7a02c21d7c..43ccf71d80 100644
--- a/rust/cloud-storage/email_service_client/Cargo.toml
+++ b/rust/cloud-storage/email_service_client/Cargo.toml
@@ -6,6 +6,7 @@ version = "0.1.0"
[dependencies]
anyhow = { workspace = true }
+email = { path = "../email", features = ["axum"] }
model = { path = "../model" }
models_email = { path = "../models_email" }
reqwest = { workspace = true }
diff --git a/rust/cloud-storage/email_service_client/src/external/get_previews.rs b/rust/cloud-storage/email_service_client/src/external/get_previews.rs
index 1777309f03..23eb6ba9f4 100644
--- a/rust/cloud-storage/email_service_client/src/external/get_previews.rs
+++ b/rust/cloud-storage/email_service_client/src/external/get_previews.rs
@@ -1,6 +1,7 @@
use super::EmailServiceClientExternal;
use anyhow::Result;
-use models_email::email::service::thread::{GetPreviewsCursorResponse, PreviewView};
+use email::inbound::ApiPaginatedThreadCursor;
+use models_email::email::service::thread::PreviewView;
use reqwest::Method;
use reqwest::Url;
use std::borrow::Cow;
@@ -11,7 +12,7 @@ impl EmailServiceClientExternal {
params: impl Iterator<Item = (&'static str, Cow<'_, str>)>,
view: PreviewView,
jwt: &str,
- ) -> Result<GetPreviewsCursorResponse> {
+ ) -> Result<ApiPaginatedThreadCursor> {
let url = format!("{}/email/threads/previews/cursor/{}", self.url, view);
let url_with_params = Url::parse_with_params(&url, params)?;
let res = self
@@ -31,7 +32,7 @@ impl EmailServiceClientExternal {
);
Err(anyhow::anyhow!("HTTP {}: {}", code, body))
} else {
- res.json::<GetPreviewsCursorResponse>()
+ res.json::<ApiPaginatedThreadCursor>()
.await
.map_err(anyhow::Error::from)
}
diff --git a/rust/cloud-storage/frecency/src/domain/models.rs b/rust/cloud-storage/frecency/src/domain/models.rs
index 0130f83b35..82d8ca992b 100644
--- a/rust/cloud-storage/frecency/src/domain/models.rs
+++ b/rust/cloud-storage/frecency/src/domain/models.rs
@@ -309,6 +309,14 @@ pub struct FrecencyPageRequest<'a> {
pub filters: Option<EntityFilterAst>,
}
+/// request to get the frecency scores of some list of [Entity] for a specific user [MacroUserIdStr]
+pub struct FrecencyByIdsRequest<'a> {
+ /// the user to fetch the frecency for
+ pub user_id: MacroUserIdStr<'a>,
+ /// the list of entities to fetch
+ pub ids: &'a [Entity<'a>],
+}
+
/// the response which contains the single page of frecency from the service
pub struct FrecencyPageResponse {
results: HashMap<AggregateId<'static>, FrecencyData>,
@@ -328,13 +336,16 @@ impl FrecencyPageResponse {
pub fn new_mock(iter: impl IntoIterator<Item = AggregateFrecency>) -> Self {
Self::new(iter)
}
-}
-impl FrecencyPageResponse {
/// return an iterator over all the ids in the [FrecencyPageResponse]
pub fn ids(&self) -> impl Iterator<Item = &AggregateId<'static>> + '_ {
self.results.keys()
}
+
+ /// return the inner data structure
+ pub fn into_inner(self) -> HashMap<AggregateId<'static>, FrecencyData> {
+ self.results
+ }
}
/// trait for joining the data source
diff --git a/rust/cloud-storage/frecency/src/domain/ports.rs b/rust/cloud-storage/frecency/src/domain/ports.rs
index 76da7299bd..4b2eb38104 100644
--- a/rust/cloud-storage/frecency/src/domain/ports.rs
+++ b/rust/cloud-storage/frecency/src/domain/ports.rs
@@ -7,7 +7,7 @@ use thiserror::Error;
use crate::domain::models::{
AggregateFrecency, AggregateId, EventAggregationStats, EventRecord, EventRecordWithId,
- FrecencyPageRequest, FrecencyPageResponse,
+ FrecencyByIdsRequest, FrecencyPageRequest, FrecencyPageResponse,
};
/// Trait for interacting with the storage of [EventRecord] records
@@ -67,13 +67,11 @@ pub trait AggregateFrecencyStorage: Send + Sync + 'static {
) -> impl Future<Output = Result<(), Self::Err>> + Send;
/// retrieve the specific aggregate record for the input entities + user pair
- fn get_aggregate_for_user_entities<T>(
+ fn get_aggregate_for_user_entities<'a>(
&self,
- user_id: MacroUserIdStr<'static>,
- entities: T,
- ) -> impl Future<Output = Result<Vec<AggregateFrecency>, Self::Err>>
- where
- T: Iterator<Item = Entity<'static>>;
+ user_id: MacroUserIdStr<'a>,
+ entities: &'a [Entity<'a>],
+ ) -> impl Future<Output = Result<Vec<AggregateFrecency>, Self::Err>> + Send;
}
/// port for getting the current system time
@@ -127,4 +125,10 @@ pub trait FrecencyQueryService: Send + Sync + 'static {
&self,
query: FrecencyPageRequest<'a>,
) -> impl Future<Output = Result<FrecencyPageResponse, FrecencyQueryErr>> + Send;
+
+ /// the the [FrecencyPageResponse] for the input [FrecencyByIdsRequest]
+ fn get_frecencies_by_ids<'a>(
+ &self,
+ request: FrecencyByIdsRequest<'a>,
+ ) -> impl Future<Output = Result<FrecencyPageResponse, FrecencyQueryErr>> + Send;
}
diff --git a/rust/cloud-storage/frecency/src/domain/services.rs b/rust/cloud-storage/frecency/src/domain/services.rs
index 1c9d0bd596..897ce3228d 100644
--- a/rust/cloud-storage/frecency/src/domain/services.rs
+++ b/rust/cloud-storage/frecency/src/domain/services.rs
@@ -4,7 +4,7 @@ use crate::{
domain::{
models::{
AggregateFrecency, AggregateId, EventAggregationStats, EventRecordWithId,
- FrecencyPageRequest, FrecencyPageResponse,
+ FrecencyByIdsRequest, FrecencyPageRequest, FrecencyPageResponse,
},
ports::{
AggregateFrecencyStorage, EventIngestorService, EventRecordStorage, FrecencyQueryErr,
@@ -260,4 +260,17 @@ where
.map_err(anyhow::Error::from)?;
Ok(FrecencyPageResponse::new(res))
}
+
+ async fn get_frecencies_by_ids<'a>(
+ &self,
+ request: FrecencyByIdsRequest<'a>,
+ ) -> Result<FrecencyPageResponse, FrecencyQueryErr> {
+ let FrecencyByIdsRequest { user_id, ids } = request;
+ let res = self
+ .storage
+ .get_aggregate_for_user_entities(user_id, ids)
+ .await
+ .map_err(anyhow::Error::from)?;
+ Ok(FrecencyPageResponse::new(res))
+ }
}
diff --git a/rust/cloud-storage/frecency/src/outbound/mock.rs b/rust/cloud-storage/frecency/src/outbound/mock.rs
index 223e87b4f0..62ad4d077c 100644
--- a/rust/cloud-storage/frecency/src/outbound/mock.rs
+++ b/rust/cloud-storage/frecency/src/outbound/mock.rs
@@ -22,11 +22,10 @@ mock! {
fn set_aggregate(&self, frecency: crate::domain::models::AggregateFrecency) -> impl Future<Output = Result<(), Infallible>> + Send;
- #[mockall::concretize]
- fn get_aggregate_for_user_entities<T: Iterator<Item = Entity<'static>>>(
+ fn get_aggregate_for_user_entities<'a>(
&self,
- user_id: MacroUserIdStr<'static>,
- entities: T,
+ user_id: MacroUserIdStr<'a>,
+ entities: &'a [Entity<'a>],
) -> impl Future<Output = Result<Vec<crate::domain::models::AggregateFrecency>, Infallible>> + Send;
}
diff --git a/rust/cloud-storage/frecency/src/outbound/postgres.rs b/rust/cloud-storage/frecency/src/outbound/postgres.rs
index e8e9f7e0dc..bc9ed251f0 100644
--- a/rust/cloud-storage/frecency/src/outbound/postgres.rs
+++ b/rust/cloud-storage/frecency/src/outbound/postgres.rs
@@ -310,33 +310,25 @@ impl AggregateFrecencyStorage for FrecencyPgStorage {
Ok(())
}
- async fn get_aggregate_for_user_entities<T>(
+ async fn get_aggregate_for_user_entities<'a>(
&self,
- user_id: MacroUserIdStr<'static>,
- entities: T,
- ) -> Result<Vec<crate::domain::models::AggregateFrecency>, Self::Err>
- where
- T: Iterator<Item = Entity<'static>>,
- {
- let user_id = user_id.0.as_ref().to_string();
- let entity_pairs: Vec<(String, String)> = entities
- .map(|e| (e.entity_type.to_string(), e.entity_id.into_owned()))
- .collect();
-
+ user_id: MacroUserIdStr<'a>,
+ entities: &'a [Entity<'a>],
+ ) -> Result<Vec<crate::domain::models::AggregateFrecency>, Self::Err> {
// Build the WHERE conditions for each entity
let mut conditions = Vec::new();
let mut params = Vec::new();
- params.push(user_id.clone());
+ params.push(user_id.as_ref());
- for (entity_type, entity_id) in entity_pairs {
+ for entity in entities {
conditions.push(format!(
"(entity_type = ${} AND entity_id = ${})",
params.len() + 1,
params.len() + 2
));
- params.push(entity_type);
- params.push(entity_id);
+ params.push(<&'static str>::from(entity.entity_type));
+ params.push(entity.entity_id.as_ref());
}
if conditions.is_empty() {
diff --git a/rust/cloud-storage/frecency/src/outbound/postgres/tests.rs b/rust/cloud-storage/frecency/src/outbound/postgres/tests.rs
index 192d4982e5..974ae834cc 100644
--- a/rust/cloud-storage/frecency/src/outbound/postgres/tests.rs
+++ b/rust/cloud-storage/frecency/src/outbound/postgres/tests.rs
@@ -248,7 +248,7 @@ async fn test_get_aggregate_for_user_entities(pool: PgPool) {
];
let results = storage
- .get_aggregate_for_user_entities(test_user_id.into_owned(), entities_to_query.into_iter())
+ .get_aggregate_for_user_entities(test_user_id.into_owned(), entities_to_query.as_slice())
.await
.unwrap();
@@ -287,7 +287,7 @@ async fn test_get_aggregate_for_empty_entities_list(pool: PgPool) {
// Query with empty entities list
let results = storage
- .get_aggregate_for_user_entities(test_user_id, std::iter::empty())
+ .get_aggregate_for_user_entities(test_user_id, &[])
.await
.unwrap();
diff --git a/rust/cloud-storage/models_email/src/email/db/thread.rs b/rust/cloud-storage/models_email/src/email/db/thread.rs
index 8ea3f8d76c..aa885caf89 100644
--- a/rust/cloud-storage/models_email/src/email/db/thread.rs
+++ b/rust/cloud-storage/models_email/src/email/db/thread.rs
@@ -35,7 +35,7 @@ pub struct ThreadPreview {
pub sender_name: Option<String>,
}
/// thread summary returned in preview cursor endpoint
-#[derive(FromRow, Debug, Clone, Serialize, Deserialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThreadPreviewCursor {
pub id: Uuid,
pub provider_id: Option<String>,
diff --git a/rust/cloud-storage/models_email/src/email/service/thread.rs b/rust/cloud-storage/models_email/src/email/service/thread.rs
index 06f29e3fdf..cff77a3b94 100644
--- a/rust/cloud-storage/models_email/src/email/service/thread.rs
+++ b/rust/cloud-storage/models_email/src/email/service/thread.rs
@@ -3,7 +3,7 @@ use crate::service::attachment::{Attachment, AttachmentMacro};
use crate::service::contact::Contact;
use crate::service::message::MessageWithBodyReplyless;
use chrono::{DateTime, Utc};
-use models_pagination::{Identify, Query, SimpleSortMethod, SortOn};
+use models_pagination::{Identify, SimpleSortMethod, SortOn};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_with::{DeserializeFromStr, SerializeDisplay};
@@ -11,44 +11,9 @@ use sqlx::FromRow;
use std::collections::HashMap;
use std::str::FromStr;
use strum::{Display, EnumString};
-use utoipa::{IntoParams, ToSchema};
+use utoipa::ToSchema;
use uuid::Uuid;
-/// Parameters for getting thread previews with cursor-based pagination.
-#[derive(serde::Serialize, serde::Deserialize, Debug, ToSchema, IntoParams)]
-#[into_params(parameter_in = Query)]
-pub struct GetPreviewsCursorParams {
- /// Limit for pagination. Default is 20. Max is 500.
- pub limit: Option<u32>,
- /// Sort method. Options are viewed_at, created_at, updated_at, viewed_updated. Defaults to viewed_updated.
- pub sort_method: Option<ApiSortMethod>,
-}
-
-/// common types of sorts based on timestamps
-#[derive(Debug, Clone, Copy, Serialize, Deserialize, ToSchema)]
-#[serde(rename_all = "snake_case")]
-pub enum ApiSortMethod {
- /// we are sorting by the viewed_at time
- ViewedAt,
- /// we are sorting by the updated_at time
- UpdatedAt,
- /// we are sorting by the created_at time
- CreatedAt,
- /// we are sorting by the viewed/updated time
- ViewedUpdated,
-}
-
-impl ApiSortMethod {
- pub fn into_simple_sort(self) -> SimpleSortMethod {
- match self {
- ApiSortMethod::ViewedAt => SimpleSortMethod::ViewedAt,
- ApiSortMethod::UpdatedAt => SimpleSortMethod::UpdatedAt,
- ApiSortMethod::CreatedAt => SimpleSortMethod::CreatedAt,
- ApiSortMethod::ViewedUpdated => SimpleSortMethod::ViewedUpdated,
- }
- }
-}
-
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct ThreadSummary {
pub provider_id: String,
@@ -197,18 +162,6 @@ impl SortOn<SimpleSortMethod> for ThreadPreviewCursor {
}
}
-#[derive(Debug, Serialize, Deserialize, JsonSchema, ToSchema)]
-pub struct PaginatedThreadCursor {
- pub items: Vec<ThreadPreviewCursor>,
- pub next_cursor: Option<String>,
-}
-
-#[derive(Debug, Serialize, Deserialize, JsonSchema, ToSchema)]
-pub struct GetPreviewsCursorResponse {
- /// the thread, with messages inside
- pub previews: PaginatedThreadCursor,
-}
-
impl From<crate::email::db::thread::ThreadPreview> for ThreadPreview {
fn from(db_preview: crate::email::db::thread::ThreadPreview) -> Self {
Self {
@@ -319,6 +272,29 @@ pub enum PreviewView {
UserLabel(String),
}
+impl std::fmt::Display for PreviewView {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ PreviewView::StandardLabel(label) => write!(f, "{}", label),
+ PreviewView::UserLabel(label) => write!(f, "user:{}", label),
+ }
+ }
+}
+
+impl FromStr for PreviewView {
+ type Err = String;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ match PreviewViewStandardLabel::from_str(s) {
+ Ok(label) => Ok(PreviewView::StandardLabel(label)),
+ Err(_) => match s.to_lowercase().as_str() {
+ s if s.starts_with("user:") => Ok(PreviewView::UserLabel(s[5..].to_string())),
+ _ => Err(format!("Unknown preview view: {}", s)),
+ },
+ }
+ }
+}
+
impl utoipa::ToSchema for PreviewView {
fn name() -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed("PreviewView")
@@ -345,29 +321,6 @@ impl utoipa::PartialSchema for PreviewView {
}
}
-impl std::fmt::Display for PreviewView {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- match self {
- PreviewView::StandardLabel(label) => write!(f, "{}", label),
- PreviewView::UserLabel(label) => write!(f, "user:{}", label),
- }
- }
-}
-
-impl FromStr for PreviewView {
- type Err = String;
-
- fn from_str(s: &str) -> Result<Self, Self::Err> {
- match PreviewViewStandardLabel::from_str(s) {
- Ok(label) => Ok(PreviewView::StandardLabel(label)),
- Err(_) => match s.to_lowercase().as_str() {
- s if s.starts_with("user:") => Ok(PreviewView::UserLabel(s[5..].to_string())),
- _ => Err(format!("Unknown preview view: {}", s)),
- },
- }
- }
-}
-
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserThreadsPage {
pub threads: Vec<ThreadUserInfo>,
@@ -384,84 +337,3 @@ pub struct UserThreadIds {
pub struct GetThreadOwnerResponse {
pub user_id: String,
}
-
-#[derive(Debug)]
-pub struct PreviewCursorQuery {
- pub view: PreviewView,
- pub link_id: Uuid,
- pub limit: u32,
- pub query: Query<Uuid, SimpleSortMethod, ()>,
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn test_preview_view_display() {
- assert_eq!(
- PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox).to_string(),
- "inbox"
- );
- assert_eq!(
- PreviewView::StandardLabel(PreviewViewStandardLabel::Sent).to_string(),
- "sent"
- );
- assert_eq!(
- PreviewView::UserLabel("mytag".to_string()).to_string(),
- "user:mytag"
- );
- }
-
- #[test]
- fn test_preview_view_from_str() {
- assert_eq!(
- PreviewView::from_str("inbox").unwrap(),
- PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox)
- );
- assert_eq!(
- PreviewView::from_str("SENT").unwrap(),
- PreviewView::StandardLabel(PreviewViewStandardLabel::Sent)
- );
- assert_eq!(
- PreviewView::from_str("user:mytag").unwrap(),
- PreviewView::UserLabel("mytag".to_string())
- );
- assert!(PreviewView::from_str("invalid").is_err());
- }
-
- #[test]
- fn test_preview_view_serialization() {
- assert_eq!(
- serde_json::to_string(&PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox))
- .unwrap(),
- "\"inbox\""
- );
- assert_eq!(
- serde_json::to_string(&PreviewView::StandardLabel(PreviewViewStandardLabel::Sent))
- .unwrap(),
- "\"sent\""
- );
- assert_eq!(
- serde_json::to_string(&PreviewView::UserLabel("mytag".to_string())).unwrap(),
- "\"user:mytag\""
- );
- }
-
- #[test]
- fn test_preview_view_deserialization() {
- assert_eq!(
- serde_json::from_str::<PreviewView>("\"inbox\"").unwrap(),
- PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox)
- );
- assert_eq!(
- serde_json::from_str::<PreviewView>("\"SENT\"").unwrap(),
- PreviewView::StandardLabel(PreviewViewStandardLabel::Sent)
- );
- assert_eq!(
- serde_json::from_str::<PreviewView>("\"user:mytag\"").unwrap(),
- PreviewView::UserLabel("mytag".to_string())
- );
- assert!(serde_json::from_str::<PreviewView>("\"invalid\"").is_err());
- }
-}
diff --git a/rust/cloud-storage/models_pagination/src/collections.rs b/rust/cloud-storage/models_pagination/src/collections.rs
new file mode 100644
index 0000000000..9a7e407c5e
--- /dev/null
+++ b/rust/cloud-storage/models_pagination/src/collections.rs
@@ -0,0 +1,54 @@
+//! This module provides the abstractions for common collection operations by leveraging the [Identify] trait
+
+use std::collections::HashMap;
+use std::hash::Hash;
+
+use crate::Identify;
+
+/// trait which lets us collect to a HashMap keyed on the Identity value
+pub trait CollectByIds<A>: Iterator<Item = A>
+where
+ A: Identify,
+ <A as Identify>::Id: Hash + Eq,
+{
+ /// collect the iterator by ids for O1 lookup
+ fn collect_by_ids(self) -> HashMap<<A as Identify>::Id, A>;
+}
+
+impl<I, A> CollectByIds<A> for I
+where
+ I: Iterator<Item = A>,
+ A: Identify,
+ <A as Identify>::Id: Hash + Eq,
+{
+ fn collect_by_ids(self) -> HashMap<<A as Identify>::Id, A> {
+ self.map(|item| (item.id(), item)).collect()
+ }
+}
+
+/// iterator extension trait which allows grouping iterator entries in bins via a callback fn
+pub trait CollectBy: Iterator {
+ /// group the items via the output of a callback fn
+ fn group_by<F, Id>(self, cb: F) -> HashMap<Id, Vec<<Self as Iterator>::Item>>
+ where
+ F: FnMut(&<Self as Iterator>::Item) -> Id,
+ Id: Hash + Eq;
+}
+
+impl<I> CollectBy for I
+where
+ I: Iterator,
+{
+ fn group_by<F, Id>(self, mut cb: F) -> HashMap<Id, Vec<<Self as Iterator>::Item>>
+ where
+ F: FnMut(&<Self as Iterator>::Item) -> Id,
+ Id: Hash + Eq,
+ {
+ let mut output = HashMap::new();
+ for item in self {
+ let id = cb(&item);
+ output.entry(id).or_insert_with(Vec::new).push(item);
+ }
+ output
+ }
+}
diff --git a/rust/cloud-storage/models_pagination/src/cursor.rs b/rust/cloud-storage/models_pagination/src/cursor.rs
index 900ebfed3e..bc7a22c2c7 100644
--- a/rust/cloud-storage/models_pagination/src/cursor.rs
+++ b/rust/cloud-storage/models_pagination/src/cursor.rs
@@ -173,6 +173,10 @@ where
}
/// Type alias for a [Paginated] where we still know the underlying type information of the encoded cursor
+/// T: The item type that is listed in each page
+/// I: The identity type that is associated with this T. e.g. Uuid
+/// C: The sort type of this cursor
+/// F: The filter type of this cursor
pub type PaginatedCursor<T, I, C, F> = Paginated<T, Base64Str<CursorWithValAndFilter<I, C, F>>>;
/// Type alias for a [Paginated] where the type information of the cursor has been erased. This is identical in memory layout and serialization shape as [PaginatedTypedCursor]
diff --git a/rust/cloud-storage/models_pagination/src/lib.rs b/rust/cloud-storage/models_pagination/src/lib.rs
index d87cfd8eff..041ddc757a 100644
--- a/rust/cloud-storage/models_pagination/src/lib.rs
+++ b/rust/cloud-storage/models_pagination/src/lib.rs
@@ -7,10 +7,12 @@
#[cfg(feature = "axum")]
mod axum;
+mod collections;
mod cursor;
mod sort;
#[cfg(feature = "axum")]
pub use axum::*;
+pub use collections::*;
pub use cursor::*;
pub use sort::*;