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(soup): expose soup ast endpoint (#2287)

Sean Aye2ab19c06368f
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/entityFilterAst.ts b/js/app/packages/service-clients/service-storage/generated/schemas/entityFilterAst.ts
new file mode 100644
index 0000000000..93312076ba
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/entityFilterAst.ts
@@ -0,0 +1,24 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Describes a bundle of filters that should be applied across different entity types
+ */
+export interface EntityFilterAst {
+ /** the filters that should be applied to the chat entity */
+ cf?: unknown;
+ /** the filters that should be applied to the channel entity */
+ chanf?: unknown;
+ /** the filters that should be applied to the document entity */
+ df?: unknown;
+ /** the filters that should be applied to the email entity */
+ ef?: unknown;
+ /** the filters that should be applied to the project entity */
+ pf?: unknown;
+ /** the filters that should be applied based on entity properties */
+ propf?: unknown;
+}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
index adcc1c84ab..e4e5b69923 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
@@ -271,6 +271,7 @@ export * from './editPdfPlaceableCommentAnchorRequestYPct';
export * from './emailFilters';
export * from './emailFiltersImportance';
export * from './emptyResponse';
+export * from './entityFilterAst';
export * from './entityFilters';
export * from './entityPermission';
export * from './entityPermissionOneOf';
@@ -416,7 +417,10 @@ export * from './pdfPlaceableCommentAnchorRequest';
export * from './pdfPlaceableCommentAnchorRequestUuid';
export * from './pinnedItem';
export * from './pinRequest';
+export * from './postItemsSoupAstParams';
export * from './postItemsSoupParams';
+export * from './postSoupAstRequest';
+export * from './postSoupAstRequestAllOf';
export * from './postSoupRequest';
export * from './postSoupRequestAllOf';
export * from './preSaveDocumentRequest';
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/postItemsSoupAstParams.ts b/js/app/packages/service-clients/service-storage/generated/schemas/postItemsSoupAstParams.ts
new file mode 100644
index 0000000000..ccd207f22f
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/postItemsSoupAstParams.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type PostItemsSoupAstParams = {
+ /**
+ * Base64 encoded cursor value.
+ */
+ cursor?: string;
+};
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/postSoupAstRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/postSoupAstRequest.ts
new file mode 100644
index 0000000000..106c2cd4fb
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/postSoupAstRequest.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { EntityFilterAst } from './entityFilterAst';
+import type { Params } from './params';
+import type { PostSoupAstRequestAllOf } from './postSoupAstRequestAllOf';
+
+export type PostSoupAstRequest = EntityFilterAst &
+ Params &
+ PostSoupAstRequestAllOf;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/postSoupAstRequestAllOf.ts b/js/app/packages/service-clients/service-storage/generated/schemas/postSoupAstRequestAllOf.ts
new file mode 100644
index 0000000000..72f72fae43
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/postSoupAstRequestAllOf.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type PostSoupAstRequestAllOf = {
+ /** the view of specific emails to display */
+ emailView?: string;
+};
diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.ts
index ac808ea383..11d6d46903 100644
--- a/js/app/packages/service-clients/service-storage/generated/zod.ts
+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts
@@ -5695,6 +5695,1279 @@ export const postItemsSoupResponse = zod.object({
next_cursor: zod.string().nullish(),
});
+/**
+ * @summary Gets the items the user has access to using AST filters
+ */
+export const postItemsSoupAstQueryParams = zod.object({
+ cursor: zod.string().optional().describe('Base64 encoded cursor value.'),
+});
+
+export const postItemsSoupAstBodyLimitMin = 0;
+
+export const postItemsSoupAstBody = zod
+ .object({
+ cf: zod
+ .any()
+ .optional()
+ .describe('the filters that should be applied to the chat entity'),
+ chanf: zod
+ .any()
+ .optional()
+ .describe('the filters that should be applied to the channel entity'),
+ df: zod
+ .any()
+ .optional()
+ .describe('the filters that should be applied to the document entity'),
+ ef: zod
+ .any()
+ .optional()
+ .describe('the filters that should be applied to the email entity'),
+ pf: zod
+ .any()
+ .optional()
+ .describe('the filters that should be applied to the project entity'),
+ propf: zod
+ .any()
+ .optional()
+ .describe(
+ 'the filters that should be applied based on entity properties'
+ ),
+ })
+ .describe(
+ 'Describes a bundle of filters that should be applied across different entity types'
+ )
+ .and(
+ zod.object({
+ expand: zod
+ .boolean()
+ .nullish()
+ .describe('Whether to expand projects. Defaults to true.'),
+ limit: zod
+ .number()
+ .min(postItemsSoupAstBodyLimitMin)
+ .nullish()
+ .describe(
+ 'Limit the number of items returned. Defaults to 20. Max 500.'
+ ),
+ sort_method: zod
+ .union([
+ zod.null(),
+ zod.enum([
+ 'viewed_at',
+ 'created_at',
+ 'updated_at',
+ 'viewed_updated',
+ 'frecency',
+ ]),
+ ])
+ .optional(),
+ })
+ )
+ .and(
+ zod.object({
+ emailView: zod
+ .string()
+ .optional()
+ .describe('the view of specific emails to display'),
+ })
+ );
+
+export const postItemsSoupAstResponseItemsItemDataChannelOrgIdMin = 0;
+
+export const postItemsSoupAstResponse = zod.object({
+ items: zod.array(
+ zod
+ .union([
+ zod.object({
+ data: zod.object({
+ branchedFromId: zod
+ .string()
+ .uuid()
+ .nullish()
+ .describe('The id of the document this document branched from'),
+ branchedFromVersionId: zod
+ .number()
+ .nullish()
+ .describe(
+ 'The id of the version this document branched from\nThis could be either DocumentInstance or DocumentBom id depending on the file type'
+ ),
+ createdAt: zod
+ .string()
+ .datetime({})
+ .describe('The time the document was created'),
+ deletedAt: zod
+ .string()
+ .datetime({})
+ .nullish()
+ .describe('The time the document was deleted'),
+ documentFamilyId: zod
+ .number()
+ .nullish()
+ .describe(
+ 'The id of the document family this document belongs to'
+ ),
+ documentVersionId: zod
+ .number()
+ .describe(
+ 'The version of the document\nThis could be the document_instance_id or document_bom_id depending on the file type'
+ ),
+ fileType: zod
+ .string()
+ .nullish()
+ .describe('The file type of the document (e.g. pdf, docx)'),
+ id: zod.string().uuid().describe('The document id'),
+ name: zod.string().describe('The name of the document'),
+ ownerId: zod.string().describe('The owner of the document'),
+ projectId: zod
+ .string()
+ .uuid()
+ .nullish()
+ .describe('The id of the project that this document belongs to'),
+ properties: zod
+ .array(
+ zod
+ .object({
+ definition: zod
+ .object({
+ created_at: zod.string().datetime({}),
+ data_type: zod
+ .enum([
+ 'BOOLEAN',
+ 'DATE',
+ 'NUMBER',
+ 'STRING',
+ 'SELECT_NUMBER',
+ 'SELECT_STRING',
+ 'ENTITY',
+ 'LINK',
+ ])
+ .describe(
+ 'Data type for property values, determining storage and validation.'
+ ),
+ display_name: zod.string(),
+ id: zod.string().uuid(),
+ is_metadata: zod
+ .boolean()
+ .describe(
+ 'Flag to indicate if this is a system-generated metadata property.\nNot stored in database - computed at service layer.'
+ ),
+ is_multi_select: zod.boolean(),
+ is_system: zod
+ .boolean()
+ .describe(
+ 'Flag to indicate if this is a system property (stored in DB).'
+ ),
+ owner: zod
+ .union([
+ zod
+ .object({
+ scope: zod.enum(['user']),
+ user_id: zod.string(),
+ })
+ .describe('User-scoped property only'),
+ zod
+ .object({
+ organization_id: zod.number(),
+ scope: zod.enum(['organization']),
+ })
+ .describe('Organization-scoped property only'),
+ zod
+ .object({
+ organization_id: zod.number(),
+ scope: zod.enum(['user_and_organization']),
+ user_id: zod.string(),
+ })
+ .describe('Both user and organization-scoped'),
+ zod
+ .object({
+ scope: zod.enum(['system']),
+ })
+ .describe(
+ 'System-owned property (no user or org owner)'
+ ),
+ ])
+ .describe(
+ 'Defines who owns a property - user-scoped, org-scoped, system, or both user and org.'
+ ),
+ specific_entity_type: zod
+ .union([
+ zod.null(),
+ zod
+ .enum([
+ 'CHANNEL',
+ 'CHAT',
+ 'COMPANY',
+ 'DOCUMENT',
+ 'PROJECT',
+ 'TASK',
+ 'THREAD',
+ 'USER',
+ ])
+ .describe(
+ 'Type of entity that can be referenced by entity properties.'
+ ),
+ ])
+ .optional(),
+ updated_at: zod.string().datetime({}),
+ })
+ .describe(
+ 'Property definition model (service representation).'
+ ),
+ value: zod
+ .union([
+ zod.null(),
+ zod
+ .union([
+ zod
+ .object({
+ type: zod.enum(['Boolean']),
+ value: zod
+ .boolean()
+ .describe(
+ 'Boolean value\nSerializes as: {\"type\": \"Boolean\", \"value\": true}'
+ ),
+ })
+ .describe(
+ 'Boolean value\nSerializes as: {\"type\": \"Boolean\", \"value\": true}'
+ ),
+ zod
+ .object({
+ type: zod.enum(['Number']),
+ value: zod
+ .number()
+ .describe(
+ 'Numeric value\nSerializes as: {\"type\": \"Number\", \"value\": 42.5}'
+ ),
+ })
+ .describe(
+ 'Numeric value\nSerializes as: {\"type\": \"Number\", \"value\": 42.5}'
+ ),
+ zod
+ .object({
+ type: zod.enum(['String']),
+ value: zod
+ .string()
+ .describe(
+ 'String value\nSerializes as: {\"type\": \"String\", \"value\": \"text\"}'
+ ),
+ })
+ .describe(
+ 'String value\nSerializes as: {\"type\": \"String\", \"value\": \"text\"}'
+ ),
+ zod
+ .object({
+ type: zod.enum(['Date']),
+ value: zod
+ .string()
+ .datetime({})
+ .describe(
+ 'Date/timestamp value\nSerializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"}'
+ ),
+ })
+ .describe(
+ 'Date/timestamp value\nSerializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"}'
+ ),
+ zod
+ .object({
+ type: zod.enum(['SelectOption']),
+ value: zod
+ .array(zod.string().uuid())
+ .describe(
+ 'Select option(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1)\nMulti-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+)'
+ ),
+ })
+ .describe(
+ 'Select option(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1)\nMulti-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+)'
+ ),
+ zod
+ .object({
+ type: zod.enum(['EntityReference']),
+ value: zod
+ .array(
+ zod
+ .object({
+ entity_id: zod.string(),
+ entity_type: zod
+ .enum([
+ 'CHANNEL',
+ 'CHAT',
+ 'COMPANY',
+ 'DOCUMENT',
+ 'PROJECT',
+ 'TASK',
+ 'THREAD',
+ 'USER',
+ ])
+ .describe(
+ 'Type of entity that can be referenced by entity properties.'
+ ),
+ specific_message_id: zod
+ .string()
+ .uuid()
+ .nullish()
+ .describe(
+ 'For CHANNEL, CHAT, THREAD entity types - optional specific message ID.\nThis allows referencing a specific message within a thread/channel/chat.'
+ ),
+ })
+ .describe(
+ 'Entity reference for entity-type property values.'
+ )
+ )
+ .describe(
+ 'Entity reference(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1)\nMulti-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+)'
+ ),
+ })
+ .describe(
+ 'Entity reference(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1)\nMulti-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+)'
+ ),
+ zod
+ .object({
+ type: zod.enum(['Link']),
+ value: zod
+ .array(zod.string())
+ .describe(
+ 'Link value(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"Link\", \"value\": [\"https://example.com\"]} (length 0 or 1)\nMulti-select: {\"type\": \"Link\", \"value\": [\"https://example.com\", \"https://other.com\"]} (length 0+)'
+ ),
+ })
+ .describe(
+ 'Link value(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"Link\", \"value\": [\"https://example.com\"]} (length 0 or 1)\nMulti-select: {\"type\": \"Link\", \"value\": [\"https://example.com\", \"https://other.com\"]} (length 0+)'
+ ),
+ ])
+ .describe(
+ 'Property value (service representation).\n\nRepresents the actual value stored for an entity property.\nThis is serialized to/from JSONB in the database.'
+ ),
+ ])
+ .optional(),
+ })
+ .describe(
+ 'A property attached to a Soup item.\n\nThis is a simplified representation that includes only the definition and value,\nomitting the entity property assignment metadata and options.'
+ )
+ )
+ .describe('Properties'),
+ sha: zod
+ .string()
+ .nullish()
+ .describe(
+ 'If the document is a PDF, this is the SHA of the pdf\nIf the document is a DOCX, this will not be present'
+ ),
+ subType: zod
+ .union([
+ zod.null(),
+ zod
+ .object({
+ is_completed: zod
+ .boolean()
+ .describe(
+ 'Whether the task is completed.\nTrue if the Status property is set to \"Completed\".'
+ ),
+ type: zod.enum(['task']),
+ })
+ .describe('A task document with its associated properties')
+ .describe(
+ 'Sub type of a document with associated properties encoded in each variant.\nThis ensures type-safety: task properties only exist when the document is a task.'
+ ),
+ ])
+ .optional(),
+ updatedAt: zod
+ .string()
+ .datetime({})
+ .describe(
+ 'The time the document instance / document BOM was updated'
+ ),
+ viewedAt: zod
+ .string()
+ .datetime({})
+ .nullish()
+ .describe('The time the document was last viewed'),
+ }),
+ tag: zod.enum(['document']),
+ }),
+ zod.object({
+ data: zod.object({
+ createdAt: zod
+ .string()
+ .datetime({})
+ .describe('The time the chat was created'),
+ deletedAt: zod
+ .string()
+ .datetime({})
+ .nullish()
+ .describe('The time the chat was deleted'),
+ id: zod.string().uuid().describe('The chat uuid'),
+ isPersistent: zod
+ .boolean()
+ .describe('Whether the chat is persistent or not'),
+ name: zod.string().describe('The name of the chat'),
+ ownerId: zod.string().describe('Who the chat belongs to'),
+ projectId: zod
+ .string()
+ .uuid()
+ .nullish()
+ .describe('The project id of the chat'),
+ properties: zod
+ .array(
+ zod
+ .object({
+ definition: zod
+ .object({
+ created_at: zod.string().datetime({}),
+ data_type: zod
+ .enum([
+ 'BOOLEAN',
+ 'DATE',
+ 'NUMBER',
+ 'STRING',
+ 'SELECT_NUMBER',
+ 'SELECT_STRING',
+ 'ENTITY',
+ 'LINK',
+ ])
+ .describe(
+ 'Data type for property values, determining storage and validation.'
+ ),
+ display_name: zod.string(),
+ id: zod.string().uuid(),
+ is_metadata: zod
+ .boolean()
+ .describe(
+ 'Flag to indicate if this is a system-generated metadata property.\nNot stored in database - computed at service layer.'
+ ),
+ is_multi_select: zod.boolean(),
+ is_system: zod
+ .boolean()
+ .describe(
+ 'Flag to indicate if this is a system property (stored in DB).'
+ ),
+ owner: zod
+ .union([
+ zod
+ .object({
+ scope: zod.enum(['user']),
+ user_id: zod.string(),
+ })
+ .describe('User-scoped property only'),
+ zod
+ .object({
+ organization_id: zod.number(),
+ scope: zod.enum(['organization']),
+ })
+ .describe('Organization-scoped property only'),
+ zod
+ .object({
+ organization_id: zod.number(),
+ scope: zod.enum(['user_and_organization']),
+ user_id: zod.string(),
+ })
+ .describe('Both user and organization-scoped'),
+ zod
+ .object({
+ scope: zod.enum(['system']),
+ })
+ .describe(
+ 'System-owned property (no user or org owner)'
+ ),
+ ])
+ .describe(
+ 'Defines who owns a property - user-scoped, org-scoped, system, or both user and org.'
+ ),
+ specific_entity_type: zod
+ .union([
+ zod.null(),
+ zod
+ .enum([
+ 'CHANNEL',
+ 'CHAT',
+ 'COMPANY',
+ 'DOCUMENT',
+ 'PROJECT',
+ 'TASK',
+ 'THREAD',
+ 'USER',
+ ])
+ .describe(
+ 'Type of entity that can be referenced by entity properties.'
+ ),
+ ])
+ .optional(),
+ updated_at: zod.string().datetime({}),
+ })
+ .describe(
+ 'Property definition model (service representation).'
+ ),
+ value: zod
+ .union([
+ zod.null(),
+ zod
+ .union([
+ zod
+ .object({
+ type: zod.enum(['Boolean']),
+ value: zod
+ .boolean()
+ .describe(
+ 'Boolean value\nSerializes as: {\"type\": \"Boolean\", \"value\": true}'
+ ),
+ })
+ .describe(
+ 'Boolean value\nSerializes as: {\"type\": \"Boolean\", \"value\": true}'
+ ),
+ zod
+ .object({
+ type: zod.enum(['Number']),
+ value: zod
+ .number()
+ .describe(
+ 'Numeric value\nSerializes as: {\"type\": \"Number\", \"value\": 42.5}'
+ ),
+ })
+ .describe(
+ 'Numeric value\nSerializes as: {\"type\": \"Number\", \"value\": 42.5}'
+ ),
+ zod
+ .object({
+ type: zod.enum(['String']),
+ value: zod
+ .string()
+ .describe(
+ 'String value\nSerializes as: {\"type\": \"String\", \"value\": \"text\"}'
+ ),
+ })
+ .describe(
+ 'String value\nSerializes as: {\"type\": \"String\", \"value\": \"text\"}'
+ ),
+ zod
+ .object({
+ type: zod.enum(['Date']),
+ value: zod
+ .string()
+ .datetime({})
+ .describe(
+ 'Date/timestamp value\nSerializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"}'
+ ),
+ })
+ .describe(
+ 'Date/timestamp value\nSerializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"}'
+ ),
+ zod
+ .object({
+ type: zod.enum(['SelectOption']),
+ value: zod
+ .array(zod.string().uuid())
+ .describe(
+ 'Select option(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1)\nMulti-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+)'
+ ),
+ })
+ .describe(
+ 'Select option(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1)\nMulti-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+)'
+ ),
+ zod
+ .object({
+ type: zod.enum(['EntityReference']),
+ value: zod
+ .array(
+ zod
+ .object({
+ entity_id: zod.string(),
+ entity_type: zod
+ .enum([
+ 'CHANNEL',
+ 'CHAT',
+ 'COMPANY',
+ 'DOCUMENT',
+ 'PROJECT',
+ 'TASK',
+ 'THREAD',
+ 'USER',
+ ])
+ .describe(
+ 'Type of entity that can be referenced by entity properties.'
+ ),
+ specific_message_id: zod
+ .string()
+ .uuid()
+ .nullish()
+ .describe(
+ 'For CHANNEL, CHAT, THREAD entity types - optional specific message ID.\nThis allows referencing a specific message within a thread/channel/chat.'
+ ),
+ })
+ .describe(
+ 'Entity reference for entity-type property values.'
+ )
+ )
+ .describe(
+ 'Entity reference(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1)\nMulti-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+)'
+ ),
+ })
+ .describe(
+ 'Entity reference(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1)\nMulti-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+)'
+ ),
+ zod
+ .object({
+ type: zod.enum(['Link']),
+ value: zod
+ .array(zod.string())
+ .describe(
+ 'Link value(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"Link\", \"value\": [\"https://example.com\"]} (length 0 or 1)\nMulti-select: {\"type\": \"Link\", \"value\": [\"https://example.com\", \"https://other.com\"]} (length 0+)'
+ ),
+ })
+ .describe(
+ 'Link value(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"Link\", \"value\": [\"https://example.com\"]} (length 0 or 1)\nMulti-select: {\"type\": \"Link\", \"value\": [\"https://example.com\", \"https://other.com\"]} (length 0+)'
+ ),
+ ])
+ .describe(
+ 'Property value (service representation).\n\nRepresents the actual value stored for an entity property.\nThis is serialized to/from JSONB in the database.'
+ ),
+ ])
+ .optional(),
+ })
+ .describe(
+ 'A property attached to a Soup item.\n\nThis is a simplified representation that includes only the definition and value,\nomitting the entity property assignment metadata and options.'
+ )
+ )
+ .describe('Properties'),
+ updatedAt: zod
+ .string()
+ .datetime({})
+ .describe('The time the chat was last updated'),
+ viewedAt: zod
+ .string()
+ .datetime({})
+ .nullish()
+ .describe('The time the chat was last viewed'),
+ }),
+ tag: zod.enum(['chat']),
+ }),
+ zod.object({
+ data: zod.object({
+ createdAt: zod
+ .string()
+ .datetime({})
+ .describe('The time the project was created'),
+ deletedAt: zod
+ .string()
+ .datetime({})
+ .nullish()
+ .describe('The time the project was deleted'),
+ id: zod.string().uuid().describe('The id of the project'),
+ name: zod.string().describe('The name of the project'),
+ ownerId: zod
+ .string()
+ .describe('The user id of who created the project'),
+ parentId: zod
+ .string()
+ .uuid()
+ .nullish()
+ .describe('The parent project id'),
+ properties: zod
+ .array(
+ zod
+ .object({
+ definition: zod
+ .object({
+ created_at: zod.string().datetime({}),
+ data_type: zod
+ .enum([
+ 'BOOLEAN',
+ 'DATE',
+ 'NUMBER',
+ 'STRING',
+ 'SELECT_NUMBER',
+ 'SELECT_STRING',
+ 'ENTITY',
+ 'LINK',
+ ])
+ .describe(
+ 'Data type for property values, determining storage and validation.'
+ ),
+ display_name: zod.string(),
+ id: zod.string().uuid(),
+ is_metadata: zod
+ .boolean()
+ .describe(
+ 'Flag to indicate if this is a system-generated metadata property.\nNot stored in database - computed at service layer.'
+ ),
+ is_multi_select: zod.boolean(),
+ is_system: zod
+ .boolean()
+ .describe(
+ 'Flag to indicate if this is a system property (stored in DB).'
+ ),
+ owner: zod
+ .union([
+ zod
+ .object({
+ scope: zod.enum(['user']),
+ user_id: zod.string(),
+ })
+ .describe('User-scoped property only'),
+ zod
+ .object({
+ organization_id: zod.number(),
+ scope: zod.enum(['organization']),
+ })
+ .describe('Organization-scoped property only'),
+ zod
+ .object({
+ organization_id: zod.number(),
+ scope: zod.enum(['user_and_organization']),
+ user_id: zod.string(),
+ })
+ .describe('Both user and organization-scoped'),
+ zod
+ .object({
+ scope: zod.enum(['system']),
+ })
+ .describe(
+ 'System-owned property (no user or org owner)'
+ ),
+ ])
+ .describe(
+ 'Defines who owns a property - user-scoped, org-scoped, system, or both user and org.'
+ ),
+ specific_entity_type: zod
+ .union([
+ zod.null(),
+ zod
+ .enum([
+ 'CHANNEL',
+ 'CHAT',
+ 'COMPANY',
+ 'DOCUMENT',
+ 'PROJECT',
+ 'TASK',
+ 'THREAD',
+ 'USER',
+ ])
+ .describe(
+ 'Type of entity that can be referenced by entity properties.'
+ ),
+ ])
+ .optional(),
+ updated_at: zod.string().datetime({}),
+ })
+ .describe(
+ 'Property definition model (service representation).'
+ ),
+ value: zod
+ .union([
+ zod.null(),
+ zod
+ .union([
+ zod
+ .object({
+ type: zod.enum(['Boolean']),
+ value: zod
+ .boolean()
+ .describe(
+ 'Boolean value\nSerializes as: {\"type\": \"Boolean\", \"value\": true}'
+ ),
+ })
+ .describe(
+ 'Boolean value\nSerializes as: {\"type\": \"Boolean\", \"value\": true}'
+ ),
+ zod
+ .object({
+ type: zod.enum(['Number']),
+ value: zod
+ .number()
+ .describe(
+ 'Numeric value\nSerializes as: {\"type\": \"Number\", \"value\": 42.5}'
+ ),
+ })
+ .describe(
+ 'Numeric value\nSerializes as: {\"type\": \"Number\", \"value\": 42.5}'
+ ),
+ zod
+ .object({
+ type: zod.enum(['String']),
+ value: zod
+ .string()
+ .describe(
+ 'String value\nSerializes as: {\"type\": \"String\", \"value\": \"text\"}'
+ ),
+ })
+ .describe(
+ 'String value\nSerializes as: {\"type\": \"String\", \"value\": \"text\"}'
+ ),
+ zod
+ .object({
+ type: zod.enum(['Date']),
+ value: zod
+ .string()
+ .datetime({})
+ .describe(
+ 'Date/timestamp value\nSerializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"}'
+ ),
+ })
+ .describe(
+ 'Date/timestamp value\nSerializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"}'
+ ),
+ zod
+ .object({
+ type: zod.enum(['SelectOption']),
+ value: zod
+ .array(zod.string().uuid())
+ .describe(
+ 'Select option(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1)\nMulti-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+)'
+ ),
+ })
+ .describe(
+ 'Select option(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1)\nMulti-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+)'
+ ),
+ zod
+ .object({
+ type: zod.enum(['EntityReference']),
+ value: zod
+ .array(
+ zod
+ .object({
+ entity_id: zod.string(),
+ entity_type: zod
+ .enum([
+ 'CHANNEL',
+ 'CHAT',
+ 'COMPANY',
+ 'DOCUMENT',
+ 'PROJECT',
+ 'TASK',
+ 'THREAD',
+ 'USER',
+ ])
+ .describe(
+ 'Type of entity that can be referenced by entity properties.'
+ ),
+ specific_message_id: zod
+ .string()
+ .uuid()
+ .nullish()
+ .describe(
+ 'For CHANNEL, CHAT, THREAD entity types - optional specific message ID.\nThis allows referencing a specific message within a thread/channel/chat.'
+ ),
+ })
+ .describe(
+ 'Entity reference for entity-type property values.'
+ )
+ )
+ .describe(
+ 'Entity reference(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1)\nMulti-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+)'
+ ),
+ })
+ .describe(
+ 'Entity reference(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1)\nMulti-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+)'
+ ),
+ zod
+ .object({
+ type: zod.enum(['Link']),
+ value: zod
+ .array(zod.string())
+ .describe(
+ 'Link value(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"Link\", \"value\": [\"https://example.com\"]} (length 0 or 1)\nMulti-select: {\"type\": \"Link\", \"value\": [\"https://example.com\", \"https://other.com\"]} (length 0+)'
+ ),
+ })
+ .describe(
+ 'Link value(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"Link\", \"value\": [\"https://example.com\"]} (length 0 or 1)\nMulti-select: {\"type\": \"Link\", \"value\": [\"https://example.com\", \"https://other.com\"]} (length 0+)'
+ ),
+ ])
+ .describe(
+ 'Property value (service representation).\n\nRepresents the actual value stored for an entity property.\nThis is serialized to/from JSONB in the database.'
+ ),
+ ])
+ .optional(),
+ })
+ .describe(
+ 'A property attached to a Soup item.\n\nThis is a simplified representation that includes only the definition and value,\nomitting the entity property assignment metadata and options.'
+ )
+ )
+ .describe('Properties'),
+ updatedAt: zod
+ .string()
+ .datetime({})
+ .describe('The time the project was updated'),
+ viewedAt: zod
+ .string()
+ .datetime({})
+ .nullish()
+ .describe('The time the document was last viewed'),
+ }),
+ tag: zod.enum(['project']),
+ }),
+ zod.object({
+ data: zod
+ .object({
+ createdAt: zod.string().datetime({}),
+ id: zod.string().uuid(),
+ inboxVisible: zod.boolean(),
+ isDraft: zod.boolean(),
+ isImportant: zod.boolean(),
+ isRead: zod.boolean(),
+ name: zod.string().nullish(),
+ ownerId: zod.string(),
+ projectId: zod.string().nullish(),
+ providerId: zod.string().nullish(),
+ senderEmail: zod.string().nullish(),
+ senderName: zod.string().nullish(),
+ senderPhotoUrl: zod.string().nullish(),
+ snippet: zod.string().nullish(),
+ sortTs: zod.string().datetime({}),
+ updatedAt: zod.string().datetime({}),
+ viewedAt: zod.string().datetime({}).nullish(),
+ })
+ .and(
+ zod.object({
+ attachments: zod.array(
+ zod.object({
+ contentId: zod.string().nullish(),
+ createdAt: zod.string().datetime({}),
+ filename: zod.string().nullish(),
+ id: zod.string().uuid(),
+ messageId: zod.string().uuid(),
+ mimeType: zod.string().nullish(),
+ providerAttachmentId: zod.string().nullish(),
+ sizeBytes: zod.number().nullish(),
+ })
+ ),
+ labels: zod.array(
+ zod.object({
+ createdAt: zod.string().datetime({}),
+ id: zod.string().uuid(),
+ labelListVisibility: zod.enum([
+ 'labelShow',
+ 'labelShowIfUnread',
+ 'labelHide',
+ ]),
+ linkId: zod.string().uuid(),
+ messageListVisibility: zod.enum(['show', 'hide']),
+ name: zod.string(),
+ providerLabelId: zod.string(),
+ type: zod.enum(['system', 'user']),
+ })
+ ),
+ participants: zod.array(
+ zod.object({
+ emailAddress: zod.string().nullish(),
+ id: zod.string().uuid(),
+ linkId: zod.string().uuid(),
+ name: zod.string().nullish(),
+ sfsPhotoUrl: zod.string().nullish(),
+ })
+ ),
+ properties: zod.array(
+ zod
+ .object({
+ definition: zod
+ .object({
+ created_at: zod.string().datetime({}),
+ data_type: zod
+ .enum([
+ 'BOOLEAN',
+ 'DATE',
+ 'NUMBER',
+ 'STRING',
+ 'SELECT_NUMBER',
+ 'SELECT_STRING',
+ 'ENTITY',
+ 'LINK',
+ ])
+ .describe(
+ 'Data type for property values, determining storage and validation.'
+ ),
+ display_name: zod.string(),
+ id: zod.string().uuid(),
+ is_metadata: zod
+ .boolean()
+ .describe(
+ 'Flag to indicate if this is a system-generated metadata property.\nNot stored in database - computed at service layer.'
+ ),
+ is_multi_select: zod.boolean(),
+ is_system: zod
+ .boolean()
+ .describe(
+ 'Flag to indicate if this is a system property (stored in DB).'
+ ),
+ owner: zod
+ .union([
+ zod
+ .object({
+ scope: zod.enum(['user']),
+ user_id: zod.string(),
+ })
+ .describe('User-scoped property only'),
+ zod
+ .object({
+ organization_id: zod.number(),
+ scope: zod.enum(['organization']),
+ })
+ .describe('Organization-scoped property only'),
+ zod
+ .object({
+ organization_id: zod.number(),
+ scope: zod.enum(['user_and_organization']),
+ user_id: zod.string(),
+ })
+ .describe('Both user and organization-scoped'),
+ zod
+ .object({
+ scope: zod.enum(['system']),
+ })
+ .describe(
+ 'System-owned property (no user or org owner)'
+ ),
+ ])
+ .describe(
+ 'Defines who owns a property - user-scoped, org-scoped, system, or both user and org.'
+ ),
+ specific_entity_type: zod
+ .union([
+ zod.null(),
+ zod
+ .enum([
+ 'CHANNEL',
+ 'CHAT',
+ 'COMPANY',
+ 'DOCUMENT',
+ 'PROJECT',
+ 'TASK',
+ 'THREAD',
+ 'USER',
+ ])
+ .describe(
+ 'Type of entity that can be referenced by entity properties.'
+ ),
+ ])
+ .optional(),
+ updated_at: zod.string().datetime({}),
+ })
+ .describe(
+ 'Property definition model (service representation).'
+ ),
+ value: zod
+ .union([
+ zod.null(),
+ zod
+ .union([
+ zod
+ .object({
+ type: zod.enum(['Boolean']),
+ value: zod
+ .boolean()
+ .describe(
+ 'Boolean value\nSerializes as: {\"type\": \"Boolean\", \"value\": true}'
+ ),
+ })
+ .describe(
+ 'Boolean value\nSerializes as: {\"type\": \"Boolean\", \"value\": true}'
+ ),
+ zod
+ .object({
+ type: zod.enum(['Number']),
+ value: zod
+ .number()
+ .describe(
+ 'Numeric value\nSerializes as: {\"type\": \"Number\", \"value\": 42.5}'
+ ),
+ })
+ .describe(
+ 'Numeric value\nSerializes as: {\"type\": \"Number\", \"value\": 42.5}'
+ ),
+ zod
+ .object({
+ type: zod.enum(['String']),
+ value: zod
+ .string()
+ .describe(
+ 'String value\nSerializes as: {\"type\": \"String\", \"value\": \"text\"}'
+ ),
+ })
+ .describe(
+ 'String value\nSerializes as: {\"type\": \"String\", \"value\": \"text\"}'
+ ),
+ zod
+ .object({
+ type: zod.enum(['Date']),
+ value: zod
+ .string()
+ .datetime({})
+ .describe(
+ 'Date/timestamp value\nSerializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"}'
+ ),
+ })
+ .describe(
+ 'Date/timestamp value\nSerializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"}'
+ ),
+ zod
+ .object({
+ type: zod.enum(['SelectOption']),
+ value: zod
+ .array(zod.string().uuid())
+ .describe(
+ 'Select option(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1)\nMulti-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+)'
+ ),
+ })
+ .describe(
+ 'Select option(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1)\nMulti-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+)'
+ ),
+ zod
+ .object({
+ type: zod.enum(['EntityReference']),
+ value: zod
+ .array(
+ zod
+ .object({
+ entity_id: zod.string(),
+ entity_type: zod
+ .enum([
+ 'CHANNEL',
+ 'CHAT',
+ 'COMPANY',
+ 'DOCUMENT',
+ 'PROJECT',
+ 'TASK',
+ 'THREAD',
+ 'USER',
+ ])
+ .describe(
+ 'Type of entity that can be referenced by entity properties.'
+ ),
+ specific_message_id: zod
+ .string()
+ .uuid()
+ .nullish()
+ .describe(
+ 'For CHANNEL, CHAT, THREAD entity types - optional specific message ID.\nThis allows referencing a specific message within a thread/channel/chat.'
+ ),
+ })
+ .describe(
+ 'Entity reference for entity-type property values.'
+ )
+ )
+ .describe(
+ 'Entity reference(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1)\nMulti-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+)'
+ ),
+ })
+ .describe(
+ 'Entity reference(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1)\nMulti-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+)'
+ ),
+ zod
+ .object({
+ type: zod.enum(['Link']),
+ value: zod
+ .array(zod.string())
+ .describe(
+ 'Link value(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"Link\", \"value\": [\"https://example.com\"]} (length 0 or 1)\nMulti-select: {\"type\": \"Link\", \"value\": [\"https://example.com\", \"https://other.com\"]} (length 0+)'
+ ),
+ })
+ .describe(
+ 'Link value(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"Link\", \"value\": [\"https://example.com\"]} (length 0 or 1)\nMulti-select: {\"type\": \"Link\", \"value\": [\"https://example.com\", \"https://other.com\"]} (length 0+)'
+ ),
+ ])
+ .describe(
+ 'Property value (service representation).\n\nRepresents the actual value stored for an entity property.\nThis is serialized to/from JSONB in the database.'
+ ),
+ ])
+ .optional(),
+ })
+ .describe(
+ 'A property attached to a Soup item.\n\nThis is a simplified representation that includes only the definition and value,\nomitting the entity property assignment metadata and options.'
+ )
+ ),
+ })
+ ),
+ tag: zod.enum(['emailThread']),
+ }),
+ zod.object({
+ data: zod
+ .object({
+ channel: zod.object({
+ channel_type: zod.enum([
+ 'public',
+ 'organization',
+ 'private',
+ 'direct_message',
+ 'team',
+ ]),
+ created_at: zod.string().datetime({}),
+ id: zod.string().uuid(),
+ name: zod.string().nullish(),
+ org_id: zod
+ .number()
+ .min(postItemsSoupAstResponseItemsItemDataChannelOrgIdMin)
+ .nullish(),
+ owner_id: zod.string(),
+ team_id: zod.string().uuid().nullish(),
+ updated_at: zod.string().datetime({}),
+ }),
+ participants: zod.array(
+ zod.object({
+ channel_id: zod.string().uuid(),
+ joined_at: zod.string().datetime({}),
+ left_at: zod.string().datetime({}).nullish(),
+ role: zod
+ .enum(['owner', 'admin', 'member'])
+ .describe('The role a user has within a channel.'),
+ user_id: zod.string(),
+ })
+ ),
+ })
+ .and(
+ zod.object({
+ latest_message: zod
+ .union([
+ zod.null(),
+ zod.object({
+ content: zod.string(),
+ created_at: zod.string().datetime({}),
+ deleted_at: zod.string().datetime({}).nullish(),
+ mentions: zod
+ .array(zod.string())
+ .describe(
+ 'message mentions formatted as `{ENTITY_TYPE}:{ENTITY_ID}`'
+ ),
+ message_id: zod.string().uuid(),
+ sender_id: zod.string(),
+ thread_id: zod.string().uuid().nullish(),
+ updated_at: zod.string().datetime({}),
+ }),
+ ])
+ .optional(),
+ latest_non_thread_message: zod
+ .union([
+ zod.null(),
+ zod.object({
+ content: zod.string(),
+ created_at: zod.string().datetime({}),
+ deleted_at: zod.string().datetime({}).nullish(),
+ mentions: zod
+ .array(zod.string())
+ .describe(
+ 'message mentions formatted as `{ENTITY_TYPE}:{ENTITY_ID}`'
+ ),
+ message_id: zod.string().uuid(),
+ sender_id: zod.string(),
+ thread_id: zod.string().uuid().nullish(),
+ updated_at: zod.string().datetime({}),
+ }),
+ ])
+ .optional(),
+ })
+ )
+ .and(
+ zod.object({
+ interacted_at: zod.string().datetime({}).nullish(),
+ viewed_at: zod.string().datetime({}).nullish(),
+ })
+ ),
+ tag: zod.enum(['channel']),
+ }),
+ ])
+ .and(
+ zod.object({
+ frecency_score: zod.number(),
+ })
+ )
+ ),
+ next_cursor: zod.string().nullish(),
+});
+
/**
* @summary Gets the users pinned items
*/
diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.json
index b83b6652bf..36cfa6e90b 100644
--- a/js/app/packages/service-clients/service-storage/openapi.json
+++ b/js/app/packages/service-clients/service-storage/openapi.json
@@ -3103,6 +3103,56 @@
}
}
},
+ "/items/soup/ast": {
+ "post": {
+ "tags": ["soup::inbound::axum_router"],
+ "summary": "Gets the items the user has access to using AST filters",
+ "operationId": "post_items_soup_ast",
+ "parameters": [
+ {
+ "name": "cursor",
+ "in": "query",
+ "description": "Base64 encoded cursor value.",
+ "required": false,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PostSoupAstRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SoupPage"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/pins": {
"get": {
"tags": ["pins::get_pins"],
@@ -7000,6 +7050,30 @@
"type": "object",
"description": "Empty response is required due to custom fetch forcing `response.json()`"
},
+ "EntityFilterAst": {
+ "type": "object",
+ "description": "Describes a bundle of filters that should be applied across different entity types",
+ "properties": {
+ "cf": {
+ "description": "the filters that should be applied to the chat entity"
+ },
+ "chanf": {
+ "description": "the filters that should be applied to the channel entity"
+ },
+ "df": {
+ "description": "the filters that should be applied to the document entity"
+ },
+ "ef": {
+ "description": "the filters that should be applied to the email entity"
+ },
+ "pf": {
+ "description": "the filters that should be applied to the project entity"
+ },
+ "propf": {
+ "description": "the filters that should be applied based on entity properties"
+ }
+ }
+ },
"EntityFilters": {
"type": "object",
"description": "a bundle of all of the filters for each entity type",
@@ -8827,6 +8901,25 @@
}
}
},
+ "PostSoupAstRequest": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/EntityFilterAst"
+ },
+ {
+ "$ref": "#/components/schemas/Params"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "emailView": {
+ "type": "string",
+ "description": "the view of specific emails to display"
+ }
+ }
+ }
+ ]
+ },
"PostSoupRequest": {
"allOf": [
{
diff --git a/rust/cloud-storage/channels/src/inbound/axum_router.rs b/rust/cloud-storage/channels/src/inbound/axum_router.rs
index 015becc9c1..15aba130da 100644
--- a/rust/cloud-storage/channels/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/channels/src/inbound/axum_router.rs
@@ -25,8 +25,8 @@ use entity_access::{
};
use model_error_response::ErrorResponse;
use models_pagination::{
- Base64Str, BidirectionalCursor, BidirectionalCursorExtractor, CreatedAt, Cursor,
- CursorExtractor, CursorVal, PaginatedOpaqueCursor, Query as PaginationQuery, TypeEraseCursor,
+ Base64Str, BidirectionalCursor, CreatedAt, Cursor, CursorOptionExt, CursorVal,
+ CursorWithValAndFilter, PaginatedOpaqueCursor, Query as PaginationQuery, TypeEraseCursor,
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
@@ -92,24 +92,24 @@ pub struct ThreadRepliesPath {
}
fn parse_messages_query(
- cursor: BidirectionalCursorExtractor<Uuid, CreatedAt, ()>,
+ cursor: Option<BidirectionalCursor<Uuid, CreatedAt, ()>>,
) -> (
PaginationQuery<Uuid, CreatedAt, ()>,
MessagePageDirection,
bool,
) {
match cursor {
- BidirectionalCursorExtractor::Some(BidirectionalCursor::Next(cursor)) => (
+ Some(BidirectionalCursor::Next(cursor)) => (
PaginationQuery::Cursor(cursor),
MessagePageDirection::Older,
true,
),
- BidirectionalCursorExtractor::Some(BidirectionalCursor::Previous(cursor)) => (
+ Some(BidirectionalCursor::Previous(cursor)) => (
PaginationQuery::Cursor(cursor),
MessagePageDirection::Newer,
true,
),
- BidirectionalCursorExtractor::None => (
+ None => (
PaginationQuery::Sort(CreatedAt, ()),
MessagePageDirection::Older,
false,
@@ -184,7 +184,7 @@ pub async fn get_channel_messages_handler<S: ChannelMessagesService, Svc: Entity
State(state): State<ChannelsRouterState<S, Svc>>,
access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
Query(params): Query<Params>,
- cursor: BidirectionalCursorExtractor<Uuid, CreatedAt, ()>,
+ cursor: Option<BidirectionalCursor<Uuid, CreatedAt, ()>>,
) -> Result<Json<ApiChannelMessagesPage>, ChannelsHandlerErr> {
let limit = params.limit.unwrap_or(50).clamp(1, 100);
let (query, direction, has_cursor) = parse_messages_query(cursor);
@@ -295,7 +295,7 @@ pub async fn get_channel_attachments_handler<
State(state): State<ChannelsRouterState<S, Svc>>,
access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,
Query(params): Query<Params>,
- cursor: CursorExtractor<Uuid, CreatedAt, ()>,
+ cursor: Option<CursorWithValAndFilter<Uuid, CreatedAt, ()>>,
) -> Result<Json<PaginatedOpaqueCursor<ApiChannelAttachment>>, ChannelsHandlerErr> {
let limit = params.limit.unwrap_or(50);
let query = cursor.into_query(CreatedAt, ());
diff --git a/rust/cloud-storage/document_storage_service/src/api/items/soup.rs b/rust/cloud-storage/document_storage_service/src/api/items/soup.rs
deleted file mode 100644
index d198f162ad..0000000000
--- a/rust/cloud-storage/document_storage_service/src/api/items/soup.rs
+++ /dev/null
@@ -1,239 +0,0 @@
-use crate::api::MACRO_INTERLNA_USER_ID;
-use crate::api::context::ApiContext;
-use axum::Extension;
-use axum::Json;
-use axum::extract::Query;
-use axum::extract::State;
-use axum::http::StatusCode;
-use axum::response::{IntoResponse, Response};
-use frecency::domain::models::AggregateId;
-use frecency::domain::models::FrecencyPageRequest;
-use frecency::domain::models::JoinFrecency;
-use frecency::domain::ports::FrecencyQueryService;
-use frecency::domain::services::FrecencyQueryServiceImpl;
-use frecency::outbound::postgres::FrecencyPgStorage;
-use cowlike::CowLike;
-use macro_user_id::cowlike::CowLike as _;
-use macro_user_id::user_id::MacroUserIdStr;
-use model::response::ErrorResponse;
-use model::response::GenericErrorResponse;
-use model::user::UserContext;
-use models_pagination::CursorExtractor;
-use models_pagination::CursorVal;
-use models_pagination::CursorWithVal;
-use models_pagination::Frecency;
-use models_pagination::Identify;
-use models_pagination::PaginateOn;
-use models_pagination::PaginatedOpaqueCursor;
-use models_pagination::SimpleSortMethod;
-use models_pagination::SortMethod;
-use models_pagination::SortOn;
-use models_soup::item::SoupItem;
-use serde::Serialize;
-use soup::domain::models::{AdvancedSortParams, FrecencySoupItem, SimpleSortRequest, SoupType};
-use sqlx::PgPool;
-use thiserror::Error;
-use utoipa::IntoParams;
-use utoipa::ToSchema;
-
-#[cfg(test)]
-mod tests;
-
-#[derive(Debug, Default, serde::Deserialize, IntoParams)]
-#[into_params(parameter_in = Query)]
-pub struct Params {
- /// Whether to expand projects. Defaults to false.
- expand: Option<bool>,
- /// Limit the number of items returned. Defaults to 20. Max 500.
- limit: Option<u16>,
- /// Sort method. Options are viewed_at, created_at, updated_at, viewed_updated. Defaults to viewed_at.
- sort_method: Option<SortMethod>,
-}
-
-/// Gets the items the user has access to
-#[utoipa::path(
- get,
- operation_id = "get_items_soup",
- path = "/items/soup",
- params(
- Params,
- ("cursor" = Option<String>, Query, description = "Cursor value. Base64 encoded timestamp and item id, separated by |."),
- ),
- responses(
- (status = 200, body=PaginatedOpaqueCursor<FrecencySoupItem>),
- (status = 401, body=GenericErrorResponse),
- (status = 500, body=GenericErrorResponse),
- )
-)]
-#[tracing::instrument(skip(pg, user_context, frecency_interface), fields(user_id=?user_context.user_id))]
-#[axum::debug_handler(state = ApiContext)]
-pub async fn soup_handler(
- State(pg): State<PgPool>,
- State(frecency_interface): State<FrecencyQueryServiceImpl<FrecencyPgStorage>>,
- Extension(user_context): Extension<UserContext>,
- Query(params): Query<Params>,
- cursor: CursorExtractor<String, SimpleSortMethod>,
-) -> Result<Json<PaginatedOpaqueCursor<FrecencySoupItem>>, SoupHandlerErr> {
- SoupImpl {
- soup_storage: pg,
- frecency_interface,
- }
- .handle_soup_request(user_context, params, cursor.into_option())
- .await
- .map(Json)
-}
-
-#[derive(Debug, Error)]
-pub enum SoupHandlerErr {
- #[error("An unknown error has occurred")]
- DbErr(#[from] anyhow::Error),
- #[error("An unknown error has occurred")]
- FailedToQueryFrecency,
- #[error("You are not authorized to access this")]
- Unauthorized,
-}
-
-impl IntoResponse for SoupHandlerErr {
- fn into_response(self) -> Response {
- let status = match &self {
- SoupHandlerErr::DbErr(_) | SoupHandlerErr::FailedToQueryFrecency => {
- StatusCode::INTERNAL_SERVER_ERROR
- }
- SoupHandlerErr::Unauthorized => StatusCode::UNAUTHORIZED,
- };
- (
- status,
- Json(ErrorResponse {
- message: &self.to_string(),
- }),
- )
- .into_response()
- }
-}
-
-impl Identify for FrecencySoupItem {
- type Id = String;
-
- fn id(&self) -> String {
- self.item.id()
- }
-}
-
-impl SortOn<SimpleSortMethod> for FrecencySoupItem {
- fn sort_on(sort: SimpleSortMethod) -> impl FnOnce(&Self) -> CursorVal<SimpleSortMethod> {
- let cb = SoupItem::sort_on(sort);
- move |v| cb(&v.item)
- }
-}
-
-/// struct which handles the actual implementation of soup with abstracted interfaces for mocking
-struct SoupImpl<T, U> {
- /// the interface for interacting with the db
- soup_storage: T,
- /// the interface for interacting with frecency
- frecency_interface: U,
-}
-
-impl<T, U> SoupImpl<T, U>
-where
- T: SoupStorage + Send,
- U: FrecencyQueryService,
-{
- async fn handle_soup_request(
- self,
- user_context: UserContext,
- Params {
- expand,
- limit,
- sort_method,
- }: Params,
- cursor: Option<CursorWithVal<String, SimpleSortMethod>>,
- ) -> Result<PaginatedOpaqueCursor<FrecencySoupItem>, SoupHandlerErr> {
- if matches!(user_context.user_id.as_str(), "" | MACRO_INTERNAL_USER_ID) {
- return Err(SoupHandlerErr::Unauthorized);
- }
-
- let limit = limit.unwrap_or(20).min(500);
- let expanded = match expand {
- Some(true) | None => SoupType::Expanded,
- Some(false) => SoupType::UnExpanded,
- };
-
- Ok(
- match sort_method.unwrap_or(SortMethod::Simple(SimpleSortMethod::ViewedUpdated)) {
- SortMethod::Simple(sort) => self
- .soup_storage
- .get_user_items_soup(SimpleSortRequest {
- limit,
- user_id: &user_context.user_id,
- cursor: models_pagination::Query::new(cursor, sort),
- expanded,
- })
- .await?
- .into_iter()
- .map(|item| FrecencySoupItem {
- item,
- frecency_score: Default::default(),
- })
- .paginate_on(limit as usize, sort)
- .into_page()
- .type_erase(),
- SortMethod::Advanced(sort) => {
- self.handle_advanced_sort(sort, user_context, expanded, limit)
- .await?
- .into_iter()
- // TODO: fix this for correct frecency sorting/pagination
- .paginate_on(limit.into(), SimpleSortMethod::CreatedAt)
- .into_page()
- .type_erase()
- }
- },
- )
- }
-
- async fn handle_advanced_sort(
- self,
- sort: Frecency,
- user: UserContext,
- expanded: SoupType,
- limit: u16,
- ) -> Result<Vec<FrecencySoupItem>, SoupHandlerErr> {
- let user_id = MacroUserIdStr::parse_from_str(&user.user_id)
- .map_err(|_| SoupHandlerErr::Unauthorized)?;
- let res = self
- .frecency_interface
- .get_frecency_page(FrecencyPageRequest {
- user_id: user_id.copied(),
- from_score: None,
- limit: limit as u32,
- })
- .await?;
-
- let entities: Vec<_> = res.ids().map(|f| f.entity.copied()).collect();
-
- let res: Vec<_> = self
- .soup_storage
- .get_user_soup_by_ids(
- sort,
- AdvancedSortParams {
- entities: &entities,
- user_id: &user.user_id,
- expanded,
- },
- )
- .await?
- .into_iter()
- .join_frecency(res, |id| AggregateId {
- entity: id.entity(),
- user_id: user_id.copied().into_owned(),
- })
- .into_iter()
- .map(|(soup_item, frecency)| FrecencySoupItem {
- item: soup_item,
- frecency_score: frecency.map(|f| f.data.frecency_score).unwrap_or_default(),
- })
- .collect();
-
- Ok(res)
- }
-}
diff --git a/rust/cloud-storage/document_storage_service/src/api/swagger.rs b/rust/cloud-storage/document_storage_service/src/api/swagger.rs
index bc26cb84e2..eb2515c9da 100644
--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs
@@ -183,6 +183,7 @@ use utoipa::OpenApi;
// items
soup::inbound::axum_router::get_soup_handler,
soup::inbound::axum_router::post_soup_handler,
+ soup::inbound::axum_router::post_soup_ast_handler,
// channels
channels::inbound::axum_router::get_channel_messages_handler,
diff --git a/rust/cloud-storage/email/src/inbound/axum/previews_router.rs b/rust/cloud-storage/email/src/inbound/axum/previews_router.rs
index 1d5df12eb5..66a54497a1 100644
--- a/rust/cloud-storage/email/src/inbound/axum/previews_router.rs
+++ b/rust/cloud-storage/email/src/inbound/axum/previews_router.rs
@@ -6,7 +6,9 @@ use axum::{
use axum_extra::extract::Cached;
use model_error_response::ErrorResponse;
use model_user::axum_extractor::MacroUserExtractor;
-use models_pagination::{CursorExtractor, SimpleSortMethod, TypeEraseCursor};
+use models_pagination::{
+ CursorOptionExt, CursorWithValAndFilter, SimpleSortMethod, TypeEraseCursor,
+};
use std::sync::Arc;
use uuid::Uuid;
@@ -83,7 +85,7 @@ async fn cursor_handler<T: EmailService>(
Cached(EmailLinkExtractor(link, _)): Cached<EmailLinkExtractor<T>>,
PreviewViewPathExtractor(preview_view): PreviewViewPathExtractor,
extract::Query(params): extract::Query<GetPreviewsCursorParams>,
- cursor: CursorExtractor<Uuid, SimpleSortMethod, ()>,
+ cursor: Option<CursorWithValAndFilter<Uuid, SimpleSortMethod, ()>>,
) -> Result<Json<ApiPaginatedThreadCursor>, GetPreviewsCursorError> {
Ok(Json(ApiPaginatedThreadCursor::new(
service
diff --git a/rust/cloud-storage/item_filters/src/ast.rs b/rust/cloud-storage/item_filters/src/ast.rs
index 4e2d7263b8..03b66e10f5 100644
--- a/rust/cloud-storage/item_filters/src/ast.rs
+++ b/rust/cloud-storage/item_filters/src/ast.rs
@@ -72,25 +72,32 @@ pub type LiteralTree<T> = Option<Arc<Expr<T>>>;
/// Describes a bundle of filters that should be applied across different entity types
#[derive(Debug, Serialize, Deserialize, Clone)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[non_exhaustive]
pub struct EntityFilterAst {
/// the filters that should be applied to the document entity
#[serde(default, rename = "df")]
+ #[cfg_attr(feature = "schema", schema(value_type = serde_json::Value))]
pub document_filter: LiteralTree<DocumentLiteral>,
/// the filters that should be applied to the project entity
#[serde(default, rename = "pf")]
+ #[cfg_attr(feature = "schema", schema(value_type = serde_json::Value))]
pub project_filter: LiteralTree<ProjectLiteral>,
/// the filters that should be applied to the chat entity
#[serde(default, rename = "cf")]
+ #[cfg_attr(feature = "schema", schema(value_type = serde_json::Value))]
pub chat_filter: LiteralTree<ChatLiteral>,
/// the filters that should be applied to the email entity
#[serde(default, rename = "ef")]
+ #[cfg_attr(feature = "schema", schema(value_type = serde_json::Value))]
pub email_filter: LiteralTree<EmailLiteral>,
- /// the filters taht should be applied to the channel entity
+ /// the filters that should be applied to the channel entity
#[serde(default, rename = "chanf")]
+ #[cfg_attr(feature = "schema", schema(value_type = serde_json::Value))]
pub channel_filter: LiteralTree<ChannelLiteral>,
/// the filters that should be applied based on entity properties
#[serde(default, rename = "propf")]
+ #[cfg_attr(feature = "schema", schema(value_type = serde_json::Value))]
pub properties_filter: LiteralTree<PropertiesLiteral>,
}
diff --git a/rust/cloud-storage/models_pagination/src/axum.rs b/rust/cloud-storage/models_pagination/src/axum.rs
index d0c73c84ca..d6b87fe496 100644
--- a/rust/cloud-storage/models_pagination/src/axum.rs
+++ b/rust/cloud-storage/models_pagination/src/axum.rs
@@ -1,6 +1,6 @@
use crate::{Base64SerdeErr, Base64Str, Cursor, CursorVal, CursorWithValAndFilter, Sortable};
use axum::Json;
-use axum::extract::{FromRequestParts, Query};
+use axum::extract::{FromRequestParts, OptionalFromRequestParts, Query};
use axum::http::{StatusCode, request::Parts};
use axum::response::IntoResponse;
use model_error_response::ErrorResponse;
@@ -8,33 +8,20 @@ use serde::Deserialize;
use serde::de::DeserializeOwned;
use thiserror::Error;
-/// An enum which denotes either the client did not provide a cursor value
-/// or the cursor was provided and parsed.
-/// Provided but invalid cursors will be rejected as 400
-// TODO: in axum 0.8 there is OptionalFromRequestParts which is preferable to this
-#[derive(Debug)]
-pub enum CursorExtractor<Id, S: Sortable, F> {
- /// the client provided a valid parsed cursor
- Some(Cursor<Id, CursorVal<S>, F>),
- /// the client did not provide a cursor param
- None,
+/// Extension trait adding `into_query` to `Option<CursorWithValAndFilter<...>>`
+/// for convenient conversion from an optional extracted cursor to a pagination query.
+pub trait CursorOptionExt<Id, S: Sortable, F> {
+ /// Convert into a [Query] by supplying a fallback sort and filter.
+ fn into_query(self, sort: S, filter: F) -> crate::cursor::Query<Id, S, F>;
}
-impl<Id, S: Sortable, F> CursorExtractor<Id, S, F> {
- /// convert self into an [Option]CursorWithVal
- pub fn into_option(self) -> Option<CursorWithValAndFilter<Id, S, F>> {
- match self {
- CursorExtractor::Some(parsed_cursor) => Some(parsed_cursor),
- CursorExtractor::None => None,
- }
- }
- /// convert self into a [Query] by supplying a fallback
- pub fn into_query(self, sort: S, filter: F) -> crate::cursor::Query<Id, S, F> {
- crate::cursor::Query::new(self.into_option(), sort, filter)
+impl<Id, S: Sortable, F> CursorOptionExt<Id, S, F> for Option<CursorWithValAndFilter<Id, S, F>> {
+ fn into_query(self, sort: S, filter: F) -> crate::cursor::Query<Id, S, F> {
+ crate::cursor::Query::new(self, sort, filter)
}
}
-/// represents an error that can occur while extracting a [CursorExtractor]
+/// represents an error that can occur while extracting a cursor
/// from the axum request parts
#[derive(Debug, Error)]
pub enum CursorExtractErr {
@@ -112,7 +99,7 @@ where
.map_err(CursorExtractErr::DecodeErr)
}
-impl<S, Id, Sort, F> FromRequestParts<S> for CursorExtractor<Id, Sort, F>
+impl<S, Id, Sort, F> OptionalFromRequestParts<S> for Cursor<Id, CursorVal<Sort>, F>
where
S: Send + Sync,
Sort: Sortable + DeserializeOwned,
@@ -123,7 +110,10 @@ where
type Rejection = CursorExtractErr;
#[tracing::instrument(err, skip(parts, state))]
- async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
+ async fn from_request_parts(
+ parts: &mut Parts,
+ state: &S,
+ ) -> Result<Option<Self>, Self::Rejection> {
#[derive(Deserialize)]
struct Params {
cursor: Option<String>,
@@ -133,7 +123,7 @@ where
.map_err(|_| CursorExtractErr::InvalidQueryParamsErr)?;
let Some(cursor) = cursor else {
- return Ok(CursorExtractor::None);
+ return Ok(None);
};
let encoded: Base64Str<CursorWithValAndFilter<Id, Sort, F>> =
@@ -141,7 +131,7 @@ where
let decoded = decode_cursor(encoded)?;
- Ok(CursorExtractor::Some(decoded))
+ Ok(Some(decoded))
}
}
@@ -154,29 +144,7 @@ pub enum BidirectionalCursor<Id, S: Sortable, F> {
Previous(Cursor<Id, CursorVal<S>, F>),
}
-/// An enum which denotes either the client did not provide cursor params
-/// or exactly one cursor direction was provided and parsed.
-/// Provided but invalid cursors will be rejected as 400.
-// TODO: in axum 0.8 there is OptionalFromRequestParts which is preferable to this
-#[derive(Debug)]
-pub enum BidirectionalCursorExtractor<Id, S: Sortable, F> {
- /// The client provided a valid parsed cursor.
- Some(BidirectionalCursor<Id, S, F>),
- /// The client did not provide cursor params.
- None,
-}
-
-impl<Id, S: Sortable, F> BidirectionalCursorExtractor<Id, S, F> {
- /// convert self into an optional [BidirectionalCursor]
- pub fn into_option(self) -> Option<BidirectionalCursor<Id, S, F>> {
- match self {
- BidirectionalCursorExtractor::Some(parsed_cursor) => Some(parsed_cursor),
- BidirectionalCursorExtractor::None => None,
- }
- }
-}
-
-impl<S, Id, Sort, F> FromRequestParts<S> for BidirectionalCursorExtractor<Id, Sort, F>
+impl<S, Id, Sort, F> OptionalFromRequestParts<S> for BidirectionalCursor<Id, Sort, F>
where
S: Send + Sync,
Sort: Sortable + DeserializeOwned,
@@ -187,7 +155,10 @@ where
type Rejection = CursorExtractErr;
#[tracing::instrument(err, skip(parts, state))]
- async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
+ async fn from_request_parts(
+ parts: &mut Parts,
+ state: &S,
+ ) -> Result<Option<Self>, Self::Rejection> {
#[derive(Deserialize)]
struct Params {
cursor: Option<String>,
@@ -206,19 +177,15 @@ where
let encoded: Base64Str<CursorWithValAndFilter<Id, Sort, F>> =
Base64Str::new_from_string(cursor);
let decoded = decode_cursor(encoded)?;
- Ok(BidirectionalCursorExtractor::Some(
- BidirectionalCursor::Next(decoded),
- ))
+ Ok(Some(BidirectionalCursor::Next(decoded)))
}
(None, Some(previous_cursor)) => {
let encoded: Base64Str<CursorWithValAndFilter<Id, Sort, F>> =
Base64Str::new_from_string(previous_cursor);
let decoded = decode_cursor(encoded)?;
- Ok(BidirectionalCursorExtractor::Some(
- BidirectionalCursor::Previous(decoded),
- ))
+ Ok(Some(BidirectionalCursor::Previous(decoded)))
}
- (None, None) => Ok(BidirectionalCursorExtractor::None),
+ (None, None) => Ok(None),
}
}
}
diff --git a/rust/cloud-storage/notification/src/inbound/http/mod.rs b/rust/cloud-storage/notification/src/inbound/http/mod.rs
index b60d77e9c6..fe6099124b 100644
--- a/rust/cloud-storage/notification/src/inbound/http/mod.rs
+++ b/rust/cloud-storage/notification/src/inbound/http/mod.rs
@@ -9,7 +9,7 @@ use axum::{
};
use model_error_response::ErrorResponse;
use model_user::axum_extractor::MacroUserExtractor;
-use models_pagination::{CreatedAt, CursorExtractor};
+use models_pagination::{CreatedAt, CursorOptionExt, CursorWithValAndFilter};
use reqwest::StatusCode;
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use std::sync::Arc;
@@ -100,7 +100,7 @@ pub async fn list_user_notifications<
service: &NotificationRouterState<S>,
macro_user: MacroUserExtractor,
Query(Params { limit }): Query<Params>,
- cursor: CursorExtractor<Uuid, CreatedAt, ()>,
+ cursor: Option<CursorWithValAndFilter<Uuid, CreatedAt, ()>>,
) -> Result<Json<GetAllUserNotificationsResponse<T>>, (StatusCode, Json<ErrorResponse<'static>>)> {
let query = cursor.into_query(CreatedAt, ());
let result = service
@@ -155,7 +155,7 @@ pub async fn bulk_get_by_event_item_ids<
State(service): State<NotificationRouterState<S>>,
macro_user: MacroUserExtractor,
Query(Params { limit }): Query<Params>,
- cursor: CursorExtractor<Uuid, CreatedAt, ()>,
+ cursor: Option<CursorWithValAndFilter<Uuid, CreatedAt, ()>>,
Json(req): Json<BulkGetByEventItemIdsRequest>,
) -> Result<Json<GetAllUserNotificationsResponse<T>>, (StatusCode, Json<ErrorResponse<'static>>)> {
let result = service
@@ -303,7 +303,7 @@ pub async fn get_by_event_item_id<S: NotificationReader, T: Serialize + Deserial
macro_user: MacroUserExtractor,
Path(EventItemIdPath { event_item_id }): Path<EventItemIdPath>,
Query(Params { limit }): Query<Params>,
- cursor: CursorExtractor<Uuid, CreatedAt, ()>,
+ cursor: Option<CursorWithValAndFilter<Uuid, CreatedAt, ()>>,
) -> Result<Json<GetAllUserNotificationsResponse<T>>, (StatusCode, Json<ErrorResponse<'static>>)> {
let result = service
.inner
diff --git a/rust/cloud-storage/notification_service/src/api/user_notification.rs b/rust/cloud-storage/notification_service/src/api/user_notification.rs
index 7f2d4a4a23..8815512ca9 100644
--- a/rust/cloud-storage/notification_service/src/api/user_notification.rs
+++ b/rust/cloud-storage/notification_service/src/api/user_notification.rs
@@ -170,7 +170,9 @@ async fn list_typed_notifications<S: ::notification::domain::service::Notificati
State(state): State<::notification::inbound::http::NotificationRouterState<S>>,
macro_user: model_user::axum_extractor::MacroUserExtractor,
query: axum::extract::Query<::notification::inbound::http::Params>,
- cursor: models_pagination::CursorExtractor<uuid::Uuid, models_pagination::CreatedAt, ()>,
+ cursor: Option<
+ models_pagination::CursorWithValAndFilter<uuid::Uuid, models_pagination::CreatedAt, ()>,
+ >,
) -> Result<
axum::Json<GetAllUserNotificationsResponse>,
(
@@ -276,7 +278,9 @@ async fn bulk_get_typed_notifications_by_event_item_ids<
state: axum::extract::State<::notification::inbound::http::NotificationRouterState<S>>,
macro_user: model_user::axum_extractor::MacroUserExtractor,
query: axum::extract::Query<::notification::inbound::http::Params>,
- cursor: models_pagination::CursorExtractor<uuid::Uuid, models_pagination::CreatedAt, ()>,
+ cursor: Option<
+ models_pagination::CursorWithValAndFilter<uuid::Uuid, models_pagination::CreatedAt, ()>,
+ >,
body: axum::Json<::notification::inbound::http::BulkGetByEventItemIdsRequest>,
) -> Result<
axum::Json<GetAllUserNotificationsResponse>,
@@ -330,7 +334,9 @@ async fn get_typed_by_event_item_id<S: ::notification::domain::service::Notifica
macro_user: model_user::axum_extractor::MacroUserExtractor,
path: axum::extract::Path<::notification::inbound::http::EventItemIdPath>,
query: axum::extract::Query<::notification::inbound::http::Params>,
- cursor: models_pagination::CursorExtractor<uuid::Uuid, models_pagination::CreatedAt, ()>,
+ cursor: Option<
+ models_pagination::CursorWithValAndFilter<uuid::Uuid, models_pagination::CreatedAt, ()>,
+ >,
) -> Result<
axum::Json<GetAllUserNotificationsResponse>,
(
diff --git a/rust/cloud-storage/soup/src/domain/models.rs b/rust/cloud-storage/soup/src/domain/models.rs
index 081ae709b4..bc67833a4a 100644
--- a/rust/cloud-storage/soup/src/domain/models.rs
+++ b/rust/cloud-storage/soup/src/domain/models.rs
@@ -12,6 +12,7 @@ use models_pagination::{
SimpleSortMethod, SortOn,
};
use models_soup::item::SoupItem;
+use non_empty::IsEmpty;
use thiserror::Error;
use uuid::Uuid;
@@ -101,6 +102,22 @@ pub enum SoupQuery<T> {
Frecency(FrecencyQueryInner<T>),
}
+impl<T> SoupQuery<T> {
+ pub(crate) fn map<F, U>(self, f: F) -> SoupQuery<U>
+ where
+ F: FnOnce(T) -> U,
+ {
+ match self {
+ SoupQuery::Simple(SimpleQueryInner(i)) => {
+ SoupQuery::Simple(SimpleQueryInner(i.map_filter(f)))
+ }
+ SoupQuery::Frecency(FrecencyQueryInner(i)) => {
+ SoupQuery::Frecency(FrecencyQueryInner(i.map_filter(f)))
+ }
+ }
+ }
+}
+
/// the inner private type for [SoupQuery::Simple]
#[derive(Debug)]
pub struct SimpleQueryInner<T>(pub(crate) Query<Uuid, SimpleSortMethod, T>);
@@ -109,48 +126,46 @@ pub struct SimpleQueryInner<T>(pub(crate) Query<Uuid, SimpleSortMethod, T>);
#[derive(Debug)]
pub struct FrecencyQueryInner<T>(pub(crate) Query<Uuid, Frecency, T>);
-impl SoupQuery<EntityFilters> {
- /// create a new instance of a [SimpleSortMethod] with [EntityFilters] this is used to
+impl<T> SoupQuery<T> {
+ /// create a new instance of a [SimpleSortMethod] with [T] this is used to
/// construct the initial page request. To paginate an existing cursor see [Self::new_cursor_simple]
- pub fn new_sort_simple(method: SimpleSortMethod, filters: EntityFilters) -> Self {
+ pub fn new_sort_simple(method: SimpleSortMethod, filters: T) -> Self {
SoupQuery::Simple(SimpleQueryInner(models_pagination::Query::Sort(
method, filters,
)))
}
- /// create a new instance of a [Frecency] with [EntityFilters] this is used to
+ /// create a new instance of a [Frecency] with [T] this is used to
/// construct the initial page request. To paginate an existing cursor see [Self::new_cursor_frecency]
- pub fn new_sort_frecency(method: Frecency, filters: EntityFilters) -> Self {
+ pub fn new_sort_frecency(method: Frecency, filters: T) -> Self {
SoupQuery::Frecency(FrecencyQueryInner(models_pagination::Query::Sort(
method, filters,
)))
}
- /// create a new instance of a [SimpleSortMethod] with an existing cursor on [EntityFilters].
+ /// create a new instance of a [SimpleSortMethod] with an existing cursor on [T].
/// This is used to continue paginating on an existing cursor.
/// To create a new initial page see [Self::new_sort_simple]
- pub fn new_cursor_simple(
- cursor: CursorWithValAndFilter<Uuid, SimpleSortMethod, EntityFilters>,
- ) -> Self {
+ pub fn new_cursor_simple(cursor: CursorWithValAndFilter<Uuid, SimpleSortMethod, T>) -> Self {
SoupQuery::Simple(SimpleQueryInner(models_pagination::Query::Cursor(cursor)))
}
- /// create a new instance of a [Frecency] with an existing cursor on [EntityFilters].
+ /// create a new instance of a [Frecency] with an existing cursor on [T].
/// This is used to continue paginating on an existing cursor.
/// To create a new initial page see [Self::new_sort_simple]
- pub fn new_cursor_frecency(
- cursor: CursorWithValAndFilter<Uuid, Frecency, EntityFilters>,
- ) -> Self {
+ pub fn new_cursor_frecency(cursor: CursorWithValAndFilter<Uuid, Frecency, T>) -> Self {
SoupQuery::Frecency(FrecencyQueryInner(models_pagination::Query::Cursor(cursor)))
}
- pub fn filter(&self) -> &EntityFilters {
+ pub fn filter(&self) -> &T {
match self {
SoupQuery::Simple(SimpleQueryInner(query)) => query.filter(),
SoupQuery::Frecency(FrecencyQueryInner(query)) => query.filter(),
}
}
+}
+impl SoupQuery<EntityFilters> {
pub fn into_ast(self) -> Result<SoupQuery<Option<EntityFilterAst>>, ExpandErr> {
match self {
SoupQuery::Simple(SimpleQueryInner(query)) => Ok(SoupQuery::Simple(SimpleQueryInner(
@@ -173,14 +188,14 @@ pub struct SoupRequest<T> {
pub link_id: Option<Uuid>,
}
-impl SoupRequest<EntityFilters> {
- /// returns a reference to the filters to pass to the paginator
- /// this is used to prevent passing back the full ast on each server request
- pub(crate) fn filters(&self) -> &EntityFilters {
- self.cursor.filter()
- }
+/// trait which defines a type which can be fallibly converted into a SoupRequest with ast
+pub trait IntoSoupReqAst {
+ /// perform the conversion
+ fn into_ast(self) -> Result<SoupRequest<Option<EntityFilterAst>>, ExpandErr>;
+}
- pub(crate) fn into_ast(self) -> Result<SoupRequest<Option<EntityFilterAst>>, ExpandErr> {
+impl IntoSoupReqAst for SoupRequest<EntityFilters> {
+ fn into_ast(self) -> Result<SoupRequest<Option<EntityFilterAst>>, ExpandErr> {
let SoupRequest {
soup_type,
limit,
@@ -201,6 +216,36 @@ impl SoupRequest<EntityFilters> {
}
}
+impl IntoSoupReqAst for SoupRequest<EntityFilterAst> {
+ fn into_ast(self) -> Result<SoupRequest<Option<EntityFilterAst>>, ExpandErr> {
+ let SoupRequest {
+ soup_type,
+ limit,
+ cursor,
+ user,
+ email_preview_view,
+ link_id,
+ } = self;
+
+ Ok(SoupRequest {
+ soup_type,
+ limit,
+ cursor: cursor.map(|f| if f.is_empty() { None } else { Some(f) }),
+ user,
+ email_preview_view,
+ link_id,
+ })
+ }
+}
+
+impl<T> SoupRequest<T> {
+ /// returns a reference to the filters to pass to the paginator
+ /// this is used to prevent passing back the full ast on each server request
+ pub(crate) fn filters(&self) -> &T {
+ self.cursor.filter()
+ }
+}
+
impl SoupRequest<Option<EntityFilterAst>> {
/// take the parts of the [SoupRequest] that are only relevant to email
/// and move them into a [GetEmailsRequest] if it is possible to create one
diff --git a/rust/cloud-storage/soup/src/domain/ports.rs b/rust/cloud-storage/soup/src/domain/ports.rs
index 07b5a855dc..e13631fc63 100644
--- a/rust/cloud-storage/soup/src/domain/ports.rs
+++ b/rust/cloud-storage/soup/src/domain/ports.rs
@@ -1,10 +1,10 @@
use crate::domain::models::{
- AdvancedSortParams, FrecencySoupItem, SimpleSortRequest, SoupErr, SoupRequest,
+ AdvancedSortParams, FrecencySoupItem, IntoSoupReqAst, SimpleSortRequest, SoupErr, SoupRequest,
};
use either::Either;
-use item_filters::EntityFilters;
use models_pagination::{Frecency, PaginatedCursor, SimpleSortMethod};
use models_soup::item::SoupItem;
+use serde::Serialize;
#[cfg_attr(test, mockall::automock(type Err = anyhow::Error;))]
pub trait SoupRepo: Send + Sync + 'static {
@@ -42,14 +42,17 @@ pub trait SoupRepo: Send + Sync + 'static {
/// 1. The id type is [String] (this should be changed to uuid)
/// 1. The sort method is [Either] [SimpleSortMethod] or [Frecency]
/// 1. The filter type is an [Option] [EntityFilterAst]
-pub type SoupOutput = Either<
- PaginatedCursor<FrecencySoupItem, String, SimpleSortMethod, EntityFilters>,
- PaginatedCursor<FrecencySoupItem, String, Frecency, EntityFilters>,
+pub type SoupOutput<T> = Either<
+ PaginatedCursor<FrecencySoupItem, String, SimpleSortMethod, T>,
+ PaginatedCursor<FrecencySoupItem, String, Frecency, T>,
>;
pub trait SoupService: Send + Sync + 'static {
- fn get_user_soup(
+ fn get_user_soup<T>(
&self,
- req: SoupRequest<EntityFilters>,
- ) -> impl Future<Output = Result<SoupOutput, SoupErr>> + Send;
+ req: SoupRequest<T>,
+ ) -> impl Future<Output = Result<SoupOutput<T>, SoupErr>> + Send
+ where
+ SoupRequest<T>: IntoSoupReqAst,
+ T: Clone + Serialize + Send;
}
diff --git a/rust/cloud-storage/soup/src/domain/service.rs b/rust/cloud-storage/soup/src/domain/service.rs
index a1b5b42965..27ea07a553 100644
--- a/rust/cloud-storage/soup/src/domain/service.rs
+++ b/rust/cloud-storage/soup/src/domain/service.rs
@@ -1,6 +1,6 @@
use crate::domain::{
models::{
- AdvancedSortParams, FrecencyQueryInner, FrecencySoupItem, SimpleQueryInner,
+ AdvancedSortParams, FrecencyQueryInner, FrecencySoupItem, IntoSoupReqAst, SimpleQueryInner,
SimpleSortQuery, SimpleSortRequest, SoupErr, SoupQuery, SoupRequest, SoupType,
},
ports::{SoupOutput, SoupRepo, SoupService},
@@ -17,7 +17,7 @@ use frecency::domain::{
models::{AggregateId, FrecencyPageRequest, JoinFrecency},
ports::FrecencyQueryService,
};
-use item_filters::{EntityFilters, ast::EntityFilterAst};
+use item_filters::ast::EntityFilterAst;
use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{
Cursor, CursorVal, Frecency, FrecencyValue, PaginateOn, Query, SimpleSortMethod,
@@ -30,6 +30,7 @@ use models_soup::{
},
item::SoupItem,
};
+use serde::Serialize;
use std::cmp::Ordering;
use uuid::Uuid;
@@ -351,8 +352,12 @@ where
V: EmailService,
C: ChannelsService,
{
- #[tracing::instrument(err, skip(self))]
- async fn get_user_soup(&self, req: SoupRequest<EntityFilters>) -> Result<SoupOutput, SoupErr> {
+ #[tracing::instrument(err, skip(self, req))]
+ async fn get_user_soup<R>(&self, req: SoupRequest<R>) -> Result<SoupOutput<R>, SoupErr>
+ where
+ SoupRequest<R>: IntoSoupReqAst,
+ R: Clone + Serialize + Send,
+ {
let entity_filter = req.filters().clone();
let req = req.into_ast()?;
let limit = req.limit.clamp(20, 500);
diff --git a/rust/cloud-storage/soup/src/inbound/axum_router.rs b/rust/cloud-storage/soup/src/inbound/axum_router.rs
index d385ae609b..d9e1c5558e 100644
--- a/rust/cloud-storage/soup/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/soup/src/inbound/axum_router.rs
@@ -1,5 +1,5 @@
use crate::domain::{
- models::{FrecencySoupItem, SoupErr, SoupQuery, SoupRequest, SoupType},
+ models::{FrecencySoupItem, IntoSoupReqAst, SoupErr, SoupQuery, SoupRequest, SoupType},
ports::SoupService,
};
use axum::{
@@ -17,12 +17,16 @@ use email::{
},
inbound::{EmailLinkErr, EmailLinkExtractor, EmailRouterState},
};
-use item_filters::{EntityFilters, ast::ExpandErr};
+use item_filters::{
+ EntityFilters,
+ ast::{EntityFilterAst, ExpandErr},
+};
use macro_user_id::user_id::MacroUserIdStr;
use model_error_response::ErrorResponse;
use model_user::axum_extractor::MacroUserExtractor;
use models_pagination::{
- CursorExtractor, Frecency, PaginatedOpaqueCursor, SimpleSortMethod, SortMethod, TypeEraseCursor,
+ CursorWithValAndFilter, Frecency, PaginatedOpaqueCursor, SimpleSortMethod, SortMethod,
+ TypeEraseCursor,
};
use models_soup::item::SoupItem;
use serde::{Deserialize, Serialize};
@@ -108,18 +112,22 @@ where
}
}
- async fn handle(
+ async fn handle<R>(
&self,
macro_user_id: MacroUserIdStr<'static>,
email_link: Option<Link>,
- PostSoupRequest {
+ ApiSoupRequestInner {
filters,
params,
email_view,
- }: PostSoupRequest,
- cursor: SoupCursor,
- ) -> Result<Json<PaginatedOpaqueCursor<SoupApiItem>>, SoupHandlerErr> {
- let create_fallback = move || {
+ }: ApiSoupRequestInner<R>,
+ cursor: SoupCursor<R>,
+ ) -> Result<Json<PaginatedOpaqueCursor<SoupApiItem>>, SoupHandlerErr>
+ where
+ SoupRequest<R>: IntoSoupReqAst,
+ R: Clone + Serialize + Send,
+ {
+ let create_fallback = move || -> SoupQuery<R> {
let params_sort = params
.sort_method
.map(|s| s.into_sort_method())
@@ -132,13 +140,11 @@ where
}
};
- let cursor = match cursor {
+ let cursor: SoupQuery<R> = match cursor {
Either::E1(l) => l
- .into_option()
.map(SoupQuery::new_cursor_simple)
.unwrap_or_else(create_fallback),
Either::E2(r) => r
- .into_option()
.map(SoupQuery::new_cursor_frecency)
.unwrap_or_else(create_fallback),
};
@@ -173,6 +179,7 @@ where
Router::new()
.route("/soup", get(get_soup_handler))
.route("/soup", post(post_soup_handler))
+ .route("/soup/ast", post(post_soup_ast_handler))
.with_state(state)
}
@@ -252,7 +259,7 @@ pub async fn get_soup_handler<T, U>(
Cached(MacroUserExtractor { macro_user_id, .. }): Cached<MacroUserExtractor>,
email_link: Result<Cached<EmailLinkExtractor<U>>, EmailLinkErr>,
Query(params): Query<Params>,
- cursor: SoupCursor,
+ cursor: SoupCursor<EntityFilters>,
) -> Result<Json<PaginatedOpaqueCursor<SoupApiItem>>, SoupHandlerErr>
where
T: SoupService,
@@ -267,9 +274,9 @@ where
.handle(
macro_user_id,
link,
- PostSoupRequest {
+ ApiSoupRequestInner {
params,
- filters: Default::default(),
+ filters: EntityFilters::default(),
email_view: Default::default(),
},
cursor,
@@ -290,9 +297,15 @@ pub struct PostSoupRequest {
email_view: PreviewView,
}
-type SoupCursor = axum_extra::either::Either<
- CursorExtractor<Uuid, SimpleSortMethod, EntityFilters>,
- CursorExtractor<Uuid, Frecency, EntityFilters>,
+struct ApiSoupRequestInner<T> {
+ filters: T,
+ params: Params,
+ email_view: PreviewView,
+}
+
+type SoupCursor<R> = axum_extra::either::Either<
+ Option<CursorWithValAndFilter<Uuid, SimpleSortMethod, R>>,
+ Option<CursorWithValAndFilter<Uuid, Frecency, R>>,
>;
/// Gets the items the user has access to
@@ -313,8 +326,74 @@ pub async fn post_soup_handler<T, U>(
State(service): State<SoupRouterState<T, U>>,
Cached(MacroUserExtractor { macro_user_id, .. }): Cached<MacroUserExtractor>,
email_link: Result<Cached<EmailLinkExtractor<U>>, EmailLinkErr>,
- cursor: SoupCursor,
- Json(post_soup_request): Json<PostSoupRequest>,
+ cursor: SoupCursor<EntityFilters>,
+ Json(PostSoupRequest {
+ filters,
+ params,
+ email_view,
+ }): Json<PostSoupRequest>,
+) -> Result<Json<PaginatedOpaqueCursor<SoupApiItem>>, SoupHandlerErr>
+where
+ T: SoupService,
+ U: EmailService,
+{
+ let link = match email_link {
+ Ok(l) => Some(l.0.0),
+ Err(EmailLinkErr::NotFound) => None,
+ Err(e) => Err(e)?,
+ };
+ service
+ .handle(
+ macro_user_id,
+ link,
+ ApiSoupRequestInner {
+ filters,
+ params,
+ email_view,
+ },
+ cursor,
+ )
+ .await
+}
+
+#[derive(Debug, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct PostSoupAstRequest {
+ #[serde(default, flatten)]
+ filters: EntityFilterAst,
+ #[serde(default, flatten)]
+ params: Params,
+ /// the view of specific emails to display
+ #[serde(default)]
+ #[schema(value_type = String)]
+ email_view: PreviewView,
+}
+
+/// Gets the items the user has access to using AST filters
+#[utoipa::path(
+ post,
+ operation_id = "post_items_soup_ast",
+ path = "/items/soup/ast",
+ params(
+ ("cursor" = Option<String>, Query, description = "Base64 encoded cursor value."),
+ ),
+ request_body = PostSoupAstRequest,
+ responses(
+ (status = 200, body=SoupPage),
+ (status = 500, body=ErrorResponse),
+ )
+)]
+#[tracing::instrument(err, skip_all)]
+pub async fn post_soup_ast_handler<T, U>(
+ State(service): State<SoupRouterState<T, U>>,
+ Cached(MacroUserExtractor { macro_user_id, .. }): Cached<MacroUserExtractor>,
+ email_link: Result<Cached<EmailLinkExtractor<U>>, EmailLinkErr>,
+ cursor: SoupCursor<EntityFilterAst>,
+ Json(PostSoupAstRequest {
+ filters,
+ params,
+ email_view,
+ }): Json<PostSoupAstRequest>,
) -> Result<Json<PaginatedOpaqueCursor<SoupApiItem>>, SoupHandlerErr>
where
T: SoupService,
@@ -326,6 +405,15 @@ where
Err(e) => Err(e)?,
};
service
- .handle(macro_user_id, link, post_soup_request, cursor)
+ .handle(
+ macro_user_id,
+ link,
+ ApiSoupRequestInner {
+ filters,
+ params,
+ email_view,
+ },
+ cursor,
+ )
.await
}
diff --git a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
index 8b82e5c152..375aeacd8c 100644
--- a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
+++ b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
@@ -2,7 +2,6 @@ use axum::{
Extension, Router,
http::{Method, Request, StatusCode},
};
-use cool_asserts::assert_matches;
use email::domain::{
models::{EmailErr, PreviewView, PreviewViewStandardLabel, UserProvider},
ports::EmailService,
@@ -13,8 +12,7 @@ use item_filters::EntityFilters;
use macro_user_id::{email::EmailStr, user_id::MacroUserIdStr};
use model_user::UserContext;
use models_pagination::{
- Cursor, CursorVal, Frecency, FrecencyValue, Identify, PaginateOn, Query, SimpleSortMethod,
- SortOn, TypeEraseCursor,
+ CursorVal, Frecency, FrecencyValue, Identify, PaginateOn, Query, SortOn, TypeEraseCursor,
};
use serde::Serialize;
use serde_json::json;
@@ -24,7 +22,10 @@ use uuid::Uuid;
use crate::{
domain::{
- models::{FrecencyQueryInner, SimpleQueryInner, SoupErr, SoupQuery, SoupRequest, SoupType},
+ models::{
+ FrecencyQueryInner, IntoSoupReqAst, SimpleQueryInner, SoupErr, SoupQuery, SoupRequest,
+ SoupType,
+ },
ports::{SoupOutput, SoupService},
},
inbound::axum_router::{SoupRouterState, soup_router},
@@ -32,9 +33,26 @@ use crate::{
static CURSOR: &str = "eyJpZCI6ImUzNmM5MTJlLTU2M2MtNDIxZS1iMTAzLWE0YjAwY2ZmMzBlZSIsImxpbWl0IjoxMDAsInZhbCI6eyJzb3J0X3R5cGUiOiJ1cGRhdGVkX2F0IiwibGFzdF92YWwiOiIyMDI1LTExLTA3VDE5OjEyOjU5Ljc4MFoifSwiZmlsdGVyIjp7fX0=";
+#[derive(Debug)]
+enum MockCursorKind {
+ SimpleSort,
+ SimpleCursor,
+ FrecencySort,
+ FrecencyCursor,
+}
+
+#[derive(Debug)]
+struct MockSoupCall {
+ soup_type: SoupType,
+ email_preview_view: PreviewView,
+ link_id: Option<Uuid>,
+ cursor_kind: MockCursorKind,
+ filter: serde_json::Value,
+}
+
#[derive(Clone)]
struct MockSoup {
- called: Arc<std::sync::Mutex<Vec<SoupRequest<EntityFilters>>>>,
+ called: Arc<std::sync::Mutex<Vec<MockSoupCall>>>,
}
impl MockSoup {
@@ -46,12 +64,30 @@ impl MockSoup {
}
impl SoupService for MockSoup {
- async fn get_user_soup(
- &self,
- req: crate::domain::models::SoupRequest<EntityFilters>,
- ) -> Result<SoupOutput, SoupErr> {
+ async fn get_user_soup<T>(&self, req: SoupRequest<T>) -> Result<SoupOutput<T>, SoupErr>
+ where
+ SoupRequest<T>: IntoSoupReqAst,
+ T: Clone + Serialize + Send,
+ {
+ let cursor_kind = match &req.cursor {
+ SoupQuery::Simple(SimpleQueryInner(Query::Sort(..))) => MockCursorKind::SimpleSort,
+ SoupQuery::Simple(SimpleQueryInner(Query::Cursor(..))) => MockCursorKind::SimpleCursor,
+ SoupQuery::Frecency(FrecencyQueryInner(Query::Sort(..))) => {
+ MockCursorKind::FrecencySort
+ }
+ SoupQuery::Frecency(FrecencyQueryInner(Query::Cursor(..))) => {
+ MockCursorKind::FrecencyCursor
+ }
+ };
+ let filter = serde_json::to_value(req.cursor.filter()).unwrap();
let mut guard = self.called.lock().unwrap();
- guard.push(req);
+ guard.push(MockSoupCall {
+ soup_type: req.soup_type,
+ email_preview_view: req.email_preview_view,
+ link_id: req.link_id,
+ cursor_kind,
+ filter,
+ });
Err(SoupErr::SoupDbErr(anyhow::anyhow!("Not implemented")))
}
}
@@ -366,7 +402,7 @@ async fn it_calls_soup_with_missing_link() {
let guard = inner_counter.lock().unwrap();
assert_eq!(guard.len(), 1);
- assert_matches!(guard.first().unwrap(), SoupRequest { link_id: None, .. })
+ assert!(guard.first().unwrap().link_id.is_none())
}
#[tokio::test]
@@ -433,17 +469,11 @@ async fn it_loads_email_all_view() {
let guard = inner_counter.lock().unwrap();
let arg = guard.first().unwrap();
- assert_matches!(
- arg,
- SoupRequest {
- soup_type: SoupType::Expanded,
- limit: _,
- cursor: _,
- user: _,
- email_preview_view: PreviewView::StandardLabel(PreviewViewStandardLabel::All),
- link_id: _
- }
- )
+ assert!(matches!(arg.soup_type, SoupType::Expanded));
+ assert_eq!(
+ arg.email_preview_view,
+ PreviewView::StandardLabel(PreviewViewStandardLabel::All)
+ );
}
#[tokio::test]
@@ -479,17 +509,11 @@ async fn it_loads_email_sent_view() {
let guard = inner_counter.lock().unwrap();
let arg = guard.first().unwrap();
- assert_matches!(
- arg,
- SoupRequest {
- soup_type: SoupType::Expanded,
- limit: _,
- cursor: _,
- user: _,
- email_preview_view: PreviewView::StandardLabel(PreviewViewStandardLabel::Sent),
- link_id: _
- }
- )
+ assert!(matches!(arg.soup_type, SoupType::Expanded));
+ assert_eq!(
+ arg.email_preview_view,
+ PreviewView::StandardLabel(PreviewViewStandardLabel::Sent)
+ );
}
#[tokio::test]
@@ -527,20 +551,8 @@ async fn it_parses_file_assoc_filters() {
let guard = inner_counter.lock().unwrap();
let arg = guard.first().unwrap();
- assert_matches!(
- arg,
- SoupRequest {
- soup_type: SoupType::Expanded,
- limit: _,
- cursor: SoupQuery::Simple(SimpleQueryInner(Query::Sort(
- SimpleSortMethod::ViewedAt,
- _filters
- ))),
- user: _,
- email_preview_view: _,
- link_id: _
- }
- )
+ assert!(matches!(arg.soup_type, SoupType::Expanded));
+ assert!(matches!(arg.cursor_kind, MockCursorKind::SimpleSort));
}
#[tokio::test]
@@ -581,6 +593,8 @@ async fn cursor_with_assoc_works() {
guard.pop().unwrap()
};
+ let filter: EntityFilters = serde_json::from_value(arg.filter).unwrap();
+
#[derive(Serialize)]
struct Data(usize, Uuid);
@@ -605,7 +619,7 @@ async fn cursor_with_assoc_works() {
let res = (0..1000)
.map(|x| Data(x, Uuid::new_v4()))
.paginate_on(100, Frecency)
- .filter_on(arg.cursor.filter().clone())
+ .filter_on(filter)
.into_page();
let cursor = res.type_erase().next_cursor.unwrap();
@@ -635,16 +649,7 @@ async fn cursor_with_assoc_works() {
let _res = router.oneshot(request2).await.unwrap();
let guard2 = inner_counter.lock().unwrap();
let req = guard2.first().unwrap();
- assert_matches!(
- req,
- SoupRequest {
- cursor: SoupQuery::Frecency(FrecencyQueryInner(Query::Cursor(Cursor {
- filter: _f,
- ..
- }))),
- ..
- }
- )
+ assert!(matches!(req.cursor_kind, MockCursorKind::FrecencyCursor));
}
#[tokio::test]
@@ -685,6 +690,8 @@ async fn cursor_with_all_works() {
guard.pop().unwrap()
};
+ let filter: EntityFilters = serde_json::from_value(arg.filter).unwrap();
+
#[derive(Serialize)]
struct Data(usize, Uuid);
@@ -709,7 +716,7 @@ async fn cursor_with_all_works() {
let res = (0..1000)
.map(|x| Data(x, Uuid::new_v4()))
.paginate_on(100, Frecency)
- .filter_on(arg.cursor.filter().clone())
+ .filter_on(filter)
.into_page();
let cursor = res.type_erase().next_cursor.unwrap();
@@ -739,16 +746,7 @@ async fn cursor_with_all_works() {
let _res = router.oneshot(request2).await.unwrap();
let guard2 = inner_counter.lock().unwrap();
let req = guard2.first().unwrap();
- assert_matches!(
- req,
- SoupRequest {
- cursor: SoupQuery::Frecency(FrecencyQueryInner(Query::Cursor(Cursor {
- filter: _f,
- ..
- }))),
- ..
- }
- )
+ assert!(matches!(req.cursor_kind, MockCursorKind::FrecencyCursor));
}
#[tokio::test]
@@ -791,22 +789,8 @@ async fn it_parses_channel_filters() {
guard.pop().unwrap()
};
- // Check that channel_filters were parsed correctly
- assert_matches!(
- arg,
- SoupRequest {
- cursor: SoupQuery::Simple(SimpleQueryInner(Query::Sort(
- _,
- EntityFilters {
- channel_filters,
- ..
- },
- ))),
- ..
- } => {
- assert!(!channel_filters.channel_ids.is_empty());
- }
- )
+ let filter: EntityFilters = serde_json::from_value(arg.filter).unwrap();
+ assert!(!filter.channel_filters.channel_ids.is_empty());
}
#[tokio::test]
@@ -857,32 +841,37 @@ async fn it_parses_notification_and_task_filters() {
guard.pop().unwrap()
};
- assert_matches!(
- arg,
- SoupRequest {
- cursor: SoupQuery::Simple(SimpleQueryInner(Query::Sort(
- _,
- EntityFilters {
- document_filters,
- chat_filters,
- project_filters,
- channel_filters,
- ..
- },
- ))),
- ..
- } => {
- assert_eq!(document_filters.notification_filters.done, Some(false));
- assert_eq!(document_filters.notification_filters.seen, Some(false));
- assert_eq!(document_filters.task_filters.include_cbm_atm_nc, Some(true));
- assert_eq!(chat_filters.notification_filters.done, Some(false));
- assert_eq!(chat_filters.notification_filters.seen, Some(false));
- assert_eq!(project_filters.notification_filters.done, Some(false));
- assert_eq!(project_filters.notification_filters.seen, Some(false));
- assert_eq!(channel_filters.notification_filters.done, Some(false));
- assert_eq!(channel_filters.notification_filters.seen, Some(false));
- }
- )
+ let filter: EntityFilters = serde_json::from_value(arg.filter).unwrap();
+ assert_eq!(
+ filter.document_filters.notification_filters.done,
+ Some(false)
+ );
+ assert_eq!(
+ filter.document_filters.notification_filters.seen,
+ Some(false)
+ );
+ assert_eq!(
+ filter.document_filters.task_filters.include_cbm_atm_nc,
+ Some(true)
+ );
+ assert_eq!(filter.chat_filters.notification_filters.done, Some(false));
+ assert_eq!(filter.chat_filters.notification_filters.seen, Some(false));
+ assert_eq!(
+ filter.project_filters.notification_filters.done,
+ Some(false)
+ );
+ assert_eq!(
+ filter.project_filters.notification_filters.seen,
+ Some(false)
+ );
+ assert_eq!(
+ filter.channel_filters.notification_filters.done,
+ Some(false)
+ );
+ assert_eq!(
+ filter.channel_filters.notification_filters.seen,
+ Some(false)
+ );
}
#[tokio::test]
@@ -947,19 +936,9 @@ async fn it_can_filter_chat_owners() {
guard.pop().unwrap()
};
- assert_matches!(
- arg,
- SoupRequest {
- cursor: SoupQuery::Simple(SimpleQueryInner(Query::Sort(
- _,
- EntityFilters {
- chat_filters,
- ..
- },
- ))),
- ..
- } => {
- assert_eq!(chat_filters.owners, vec!["macro|[email protected]".to_string()]);
- }
- )
+ let filter: EntityFilters = serde_json::from_value(arg.filter).unwrap();
+ assert_eq!(
+ filter.chat_filters.owners,
+ vec!["macro|[email protected]".to_string()]
+ );
}
diff --git a/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs b/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs
index 6a12844551..0344aeada8 100644
--- a/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs
+++ b/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs
@@ -7,6 +7,7 @@ use crate::domain::{
use ai::tool::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
use async_trait::async_trait;
use email::domain::models::PreviewView;
+use item_filters::EntityFilters;
use models_pagination::{SimpleSortMethod, TypeEraseCursor};
use models_soup::item::SoupItem;
use schemars::JsonSchema;
@@ -150,7 +151,7 @@ where
.get_user_soup(SoupRequest {
soup_type: SoupType::Expanded,
limit: RESULT_LIMIT,
- cursor: SoupQuery::new_sort_simple(sort_method, Default::default()),
+ cursor: SoupQuery::new_sort_simple(sort_method, EntityFilters::default()),
user: request_context.user_id,
email_preview_view: PreviewView::default(),
link_id: None,