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(ai): Attachment infra (#2809)

Eric Hayes780a451059e6
diff --git a/.gitignore b/.gitignore
index 6a18060116..f297dd0cac 100644
--- a/.gitignore
+++ b/.gitignore
@@ -8,4 +8,4 @@
temp/
.env.local
run-local.fish
-node_modules/
+**/node_modules
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 340d975ada..ca2c302979 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -588,6 +588,18 @@ version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
+[[package]]
+name = "attachment"
+version = "0.1.0"
+dependencies = [
+ "ai",
+ "anyhow",
+ "futures",
+ "macro_user_id",
+ "non_empty",
+ "thiserror 2.0.17",
+]
+
[[package]]
name = "authentication_service"
version = "0.1.0"
@@ -1909,11 +1921,13 @@ dependencies = [
"ai",
"ai_toolset",
"anyhow",
+ "attachment",
"axum",
"chrono",
"entity_access",
"entity_access_db_utils",
"entity_access_management",
+ "futures",
"http-body-util",
"macro_db_migrator",
"macro_user_id",
@@ -1923,6 +1937,7 @@ dependencies = [
"model_user",
"models_entity_access_management",
"models_permissions",
+ "non_empty",
"roles_and_permissions",
"serde",
"serde_json",
@@ -2074,11 +2089,14 @@ name = "comms"
version = "0.1.0"
dependencies = [
"anyhow",
+ "attachment",
"axum",
"chrono",
"doppleganger",
+ "entity_access",
"filter_ast",
"frecency",
+ "futures",
"item_filters",
"macro_db_migrator",
"macro_user_id",
@@ -2086,6 +2104,7 @@ dependencies = [
"model_user",
"models_comms",
"models_pagination",
+ "non_empty",
"readonly_pool",
"recursion",
"rootcause",
@@ -3313,6 +3332,7 @@ dependencies = [
"ai",
"anyhow",
"async-trait",
+ "attachment",
"aws-sdk-s3",
"axum",
"axum-extra",
@@ -3341,6 +3361,7 @@ dependencies = [
"model_user",
"models_permissions",
"models_properties",
+ "non_empty",
"reqwest",
"s3_key",
"schemars",
@@ -3607,6 +3628,7 @@ dependencies = [
"ai",
"anyhow",
"async-trait",
+ "attachment",
"authentication_service_client",
"axum",
"axum-extra",
@@ -3628,6 +3650,7 @@ dependencies = [
"model-error-response",
"model_user",
"models_pagination",
+ "non_empty",
"recursion",
"redis",
"schemars",
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index 0cfcc02098..f87446b36a 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -141,7 +141,7 @@ members = [
"user_link_cleanup_handler",
"user_quota",
"worker_trigger",
- "tools/native_app_server",
+ "tools/native_app_server", "attachment",
]
[workspace.dependencies]
diff --git a/rust/cloud-storage/ai/src/types/message/base_64_image.rs b/rust/cloud-storage/ai/src/types/image/base_64_image.rs
similarity index 86%
rename from rust/cloud-storage/ai/src/types/message/base_64_image.rs
rename to rust/cloud-storage/ai/src/types/image/base_64_image.rs
index fb34e96e00..7f84c9b6dd 100644
--- a/rust/cloud-storage/ai/src/types/message/base_64_image.rs
+++ b/rust/cloud-storage/ai/src/types/image/base_64_image.rs
@@ -41,14 +41,22 @@ impl Base64Image {
Self::make_compressed_base64_webp(bytes)
}
- pub(crate) fn dangerously_try_from_string(s: String) -> Result<Self, anyhow::Error> {
- let prefix = s.split_once(";").ok_or(anyhow!("Unexpected format"))?.0;
- let image = prefix
- .split_once("/")
- .ok_or(anyhow!("Unexpected format"))?
- .1;
- let format = ImageFormat::try_from(image)?;
- Ok(Self { data: s, format })
+ pub(crate) fn try_from_string(s: &str) -> Result<Self, anyhow::Error> {
+ if s.starts_with("data:") {
+ let prefix = s.split_once(";").ok_or(anyhow!("Unexpected format"))?.0;
+ let image = prefix
+ .split_once("/")
+ .ok_or(anyhow!("Unexpected format"))?
+ .1;
+ let format = ImageFormat::try_from(image)?;
+
+ Ok(Self {
+ data: s.to_owned(),
+ format,
+ })
+ } else {
+ Err(anyhow::anyhow!("not a base64 encoded image"))
+ }
}
}
diff --git a/rust/cloud-storage/ai/src/types/image/mod.rs b/rust/cloud-storage/ai/src/types/image/mod.rs
new file mode 100644
index 0000000000..b5f62e152c
--- /dev/null
+++ b/rust/cloud-storage/ai/src/types/image/mod.rs
@@ -0,0 +1,22 @@
+mod base_64_image;
+
+pub use base_64_image::*;
+
+#[derive(PartialEq, Eq, Clone)]
+pub enum ImageData {
+ Base64(Base64Image),
+ StaticUrl(String),
+}
+
+impl ImageData {
+ /// convert image bytes into a downscaled webp
+ pub fn try_from_bytes(bytes: Vec<u8>) -> Result<Self, anyhow::Error> {
+ Base64Image::compress_and_reencode(bytes).map(Self::Base64)
+ }
+
+ pub(crate) fn dangerously_try_from_string(s: String) -> Result<Self, anyhow::Error> {
+ Base64Image::try_from_string(&s)
+ .map(Self::Base64)
+ .or_else(|_| Ok(Self::StaticUrl(s)))
+ }
+}
diff --git a/rust/cloud-storage/ai/src/types/message/chat_message.rs b/rust/cloud-storage/ai/src/types/message/chat_message.rs
index 5793d2d888..ffe2d7f6f6 100644
--- a/rust/cloud-storage/ai/src/types/message/chat_message.rs
+++ b/rust/cloud-storage/ai/src/types/message/chat_message.rs
@@ -1,6 +1,6 @@
use super::Role;
use crate::tokens::{TokenCount, count_tokens};
-use crate::types::request::ImageData;
+use crate::types::ImageData;
use anyhow::Result;
use async_openai::types::ChatCompletionRequestMessage;
use serde::{self, Deserialize, Serialize};
diff --git a/rust/cloud-storage/ai/src/types/message/mod.rs b/rust/cloud-storage/ai/src/types/message/mod.rs
index 4123d7434c..9a86147076 100644
--- a/rust/cloud-storage/ai/src/types/message/mod.rs
+++ b/rust/cloud-storage/ai/src/types/message/mod.rs
@@ -1,10 +1,8 @@
-mod base_64_image;
mod chat_message;
mod message_builder;
mod prompt_attachments;
mod system_prompt;
-pub use base_64_image::*;
pub use chat_message::*;
pub use message_builder::*;
pub use prompt_attachments::*;
diff --git a/rust/cloud-storage/ai/src/types/mod.rs b/rust/cloud-storage/ai/src/types/mod.rs
index aff1b02e5a..7ec6a48091 100644
--- a/rust/cloud-storage/ai/src/types/mod.rs
+++ b/rust/cloud-storage/ai/src/types/mod.rs
@@ -1,5 +1,6 @@
mod client;
mod error;
+mod image;
mod message;
mod model;
mod providers;
@@ -9,6 +10,7 @@ mod response;
pub use client::*;
pub use error::*;
+pub use image::*;
pub use message::*;
pub use model::*;
pub(crate) use providers::*;
diff --git a/rust/cloud-storage/ai/src/types/providers/openai/message.rs b/rust/cloud-storage/ai/src/types/providers/openai/message.rs
index 88d560fd1f..ec37a7bec6 100644
--- a/rust/cloud-storage/ai/src/types/providers/openai/message.rs
+++ b/rust/cloud-storage/ai/src/types/providers/openai/message.rs
@@ -18,11 +18,11 @@ const IMAGE_PROCESS_QUALITY: Option<ImageDetail> = Some(ImageDetail::High);
impl From<ImageData> for ImageUrl {
fn from(value: ImageData) -> Self {
match value {
- ImageData::Url(url) => Self {
+ ImageData::StaticUrl(url) => Self {
url,
detail: IMAGE_PROCESS_QUALITY,
},
- ImageData::Bytes(base_64_image) => Self {
+ ImageData::Base64(base_64_image) => Self {
url: base_64_image.to_string(),
detail: IMAGE_PROCESS_QUALITY,
},
@@ -480,7 +480,7 @@ mod tests {
let original = ChatMessage {
role: Role::User,
content: ChatMessageContent::Text("What's in this image?".to_string()),
- image_urls: Some(vec![ImageData::Url(
+ image_urls: Some(vec![ImageData::StaticUrl(
"https://example.com/image.jpg".to_string(),
)]),
};
@@ -652,8 +652,8 @@ mod tests {
role: Role::User,
content: ChatMessageContent::Text("Compare these images".to_string()),
image_urls: Some(vec![
- ImageData::Url("https://example.com/image1.jpg".to_string()),
- ImageData::Url("https://example.com/image2.jpg".to_string()),
+ ImageData::StaticUrl("https://example.com/image1.jpg".to_string()),
+ ImageData::StaticUrl("https://example.com/image2.jpg".to_string()),
]),
};
diff --git a/rust/cloud-storage/ai/src/types/request.rs b/rust/cloud-storage/ai/src/types/request.rs
index 8f4dddc627..42221370e9 100644
--- a/rust/cloud-storage/ai/src/types/request.rs
+++ b/rust/cloud-storage/ai/src/types/request.rs
@@ -1,7 +1,4 @@
-use super::{
- message::{Base64Image, ChatMessage, SystemPrompt},
- model::Model,
-};
+use super::{ChatMessage, ImageData, SystemPrompt, model::Model};
#[derive(Debug, Clone)]
pub struct ChatCompletionRequest {
@@ -13,34 +10,13 @@ pub struct ChatCompletionRequest {
pub(crate) system_prompt: SystemPrompt,
}
-#[derive(PartialEq, Eq, Clone)]
-pub enum ImageData {
- Bytes(Base64Image),
- Url(String),
-}
-
-impl ImageData {
- /// convert image bytes into a downscaled webp
- pub fn try_from_bytes(bytes: Vec<u8>) -> Result<Self, anyhow::Error> {
- Base64Image::compress_and_reencode(bytes).map(Self::Bytes)
- }
-
- pub(crate) fn dangerously_try_from_string(s: String) -> Result<Self, anyhow::Error> {
- if s.starts_with("data:") {
- Ok(Self::Bytes(Base64Image::dangerously_try_from_string(s)?))
- } else {
- Ok(Self::Url(s))
- }
- }
-}
-
impl std::fmt::Debug for ImageData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
- Self::Bytes(base_64) => {
+ Self::Base64(base_64) => {
write!(f, "bytes {:?}", base_64)
}
- Self::Url(url) => write!(f, "url {}", url),
+ Self::StaticUrl(url) => write!(f, "url {}", url),
}
}
}
diff --git a/rust/cloud-storage/attachment/.claude/skills/WRITE_ATTACHMENT_SERVICE/SKILL.md b/rust/cloud-storage/attachment/.claude/skills/WRITE_ATTACHMENT_SERVICE/SKILL.md
new file mode 100644
index 0000000000..7c99cc171e
--- /dev/null
+++ b/rust/cloud-storage/attachment/.claude/skills/WRITE_ATTACHMENT_SERVICE/SKILL.md
@@ -0,0 +1,150 @@
+# Implementing an Attachment Service
+
+You are adding an `inbound/attachment` module to a domain crate. This module implements the `attachment::AttachmentService` trait so the crate can resolve its entity IDs into AI-consumable attachment content.
+
+## Context files to read first
+
+Read these files in order to understand the patterns:
+
+1. `attachment/src/lib.rs` — the `AttachmentService` trait and `Attachable` trait
+2. `attachment/src/models.rs` — `AttachmentContent`, `AttachmentPart`, `Attachments`, `ResolutionError`, `AttachmentError`
+3. `attachment/src/fmt.rs` — `XmlTag`, `ClosedXmlTag`, `Indent` formatting utilities
+4. `attachment/src/attachable.rs` — `Attachable` impls that convert the attachment tree into `FormattedParts`
+5. `documents/src/inbound/attachment/` — reference implementation (module structure, service, markdown submodule)
+6. `chat/src/inbound/attachment/service.rs` — example using `fmt::XmlTag` for structured message formatting
+
+All paths are relative to `rust/cloud-storage/`.
+
+## What you're building
+
+A struct that implements `AttachmentService`:
+
+```rust
+pub trait AttachmentService: Send + Sync + 'static {
+ fn resolve_attachments(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ ids: NonEmpty<&[&str]>,
+ ) -> impl Future<Output = Attachments> + Send;
+}
+```
+
+It takes entity IDs and returns `Attachments` — a non-empty vec of `Result<AttachmentContent, ResolutionError>`. Individual failures never fail the batch.
+
+## Key types
+
+- `AttachmentReference` — typed enum identifying the source entity (`DssFile`, `SfsImage`, `EmailThread`, `Chat`, `Channel`). Produces XML attributes via `as_attributes()`.
+- `AttachmentContent { reference: AttachmentReference, name: Option<String>, content: NonEmpty<Vec<AttachmentPart>> }` — a resolved attachment
+- `AttachmentPart::Content(String)` — text content
+- `AttachmentPart::Image(ImageData)` — image data (from `ai::types::ImageData`)
+- `AttachmentPart::Child(Box<Result<AttachmentContent, ResolutionError>>)` — nested sub-attachment with its own `AttachmentReference`
+- `AttachmentPart::ChildReference(AttachmentReference)` — unresolved reference to a child attachment
+- `AttachmentPart::Metadata { key, value }` — key-value metadata (formatted as `<metadata key="..." value="..."/>`)
+- `ResolutionError::new(id, AttachmentError)` — a per-attachment failure
+- `Attachments::new(NonEmpty<Vec<Result<AttachmentContent, ResolutionError>>>)` — the batch result
+
+### Formatting types (`attachment::fmt`)
+
+- `XmlTag { name, attrs, body }` — wraps body content in `<name attrs>...</name>`. Implements both `Display` (for producing `String`) and `Attachable` (for producing `FormattedParts` with images preserved).
+- `ClosedXmlTag { name, attrs }` — self-closing `<name attrs/>`. Use for metadata and unresolved references.
+- `Indent(T)` — indents all text lines of the wrapped value.
+
+## Steps
+
+### 1. Add dependencies to the crate's Cargo.toml
+
+Add an `attachment` feature that pulls in what you need:
+
+```toml
+[features]
+attachment = [
+ "dep:attachment",
+ # add other deps your resolver needs (dep:ai, dep:reqwest, etc.)
+ "ports", # if the crate gates its domain traits behind a feature
+]
+
+[dependencies]
+attachment = { path = "../attachment", optional = true }
+non_empty = { path = "../non_empty" }
+```
+
+### 2. Wire up the inbound module
+
+In `src/inbound.rs` (or equivalent), add:
+
+```rust
+#[cfg(feature = "attachment")]
+pub mod attachment;
+```
+
+Make sure `lib.rs` compiles the `inbound` module when the `attachment` feature is active.
+
+### 3. Create the module structure
+
+```
+src/inbound/attachment/
+├── mod.rs — declares submodules, re-exports the service struct
+└── service.rs — the AttachmentService implementation
+```
+
+Add more files if you need type-specific resolution logic (like `markdown.rs` in the documents reference impl).
+
+### 4. Implement the service
+
+Your service struct holds `Arc` references to whatever domain services and clients it needs. Follow this pattern:
+
+```rust
+pub struct FooAttachmentService<Svc> {
+ service: Arc<Svc>,
+}
+
+impl<Svc: FooService> AttachmentService for FooAttachmentService<Svc> {
+ async fn resolve_attachments(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ ids: NonEmpty<&[&str]>,
+ ) -> Attachments {
+ let user_id = &user_id;
+ let results = join_all(ids.iter().map(|id| async move {
+ self.resolve_one(user_id, id)
+ .await
+ .map_err(|error| ResolutionError::new(id.to_string(), error))
+ }))
+ .await;
+ Attachments::new(NonEmpty::new(results).expect("ids was non-empty"))
+ }
+}
+```
+
+Then implement `resolve_one` which returns `Result<AttachmentContent, AttachmentError>` for a single entity. This is where the domain-specific logic lives.
+
+### 5. Add the `AttachmentReference` variant
+
+If your entity type doesn't have a variant in `AttachmentReference` yet, add one in `attachment/src/models.rs`. Update `id()`, `as_attributes()`, and the `AttachmentProvider` router in `provider.rs`.
+
+### 6. Register with the provider
+
+Add your service as a type parameter to `AttachmentProvider` in `attachment/src/provider.rs` and wire up the dispatch.
+
+## Conventions
+
+- Use `join_all` to resolve IDs concurrently.
+- Map domain errors to `AttachmentError::Internal(e.into())` unless a more specific variant fits (`PermissionDenied`, `UnknownFileType`, `UnsupportedFileType`, `NoContent`).
+- Access-check each entity via `EntityAccessService::generate_entity_access_receipt` before reading content.
+- Use `tracing::instrument` on `resolve_one` with `skip(self)` and `err`.
+- Use `attachment::fmt` utilities (`XmlTag`, `ClosedXmlTag`) for structured text formatting (e.g. wrapping messages in `<message role="user">` tags). Use `XmlTag.to_string()` when producing an `AttachmentPart::Content(String)`.
+- For sub-attachments (e.g. inline images within a document), use `AttachmentPart::Child` with the appropriate `AttachmentReference` variant. This flows through the `Attachable` formatting system and produces properly tagged XML output.
+
+### NonEmpty rules
+
+**Never insert empty or placeholder strings into `NonEmpty` to satisfy the non-empty constraint.** The `NonEmpty<Vec<AttachmentPart>>` in `AttachmentContent.content` means "this attachment has content." If resolution produces zero parts, return `AttachmentError::NoContent` instead.
+
+```rust
+// WRONG — defeats the purpose of NonEmpty
+let content = NonEmpty::new(parts).unwrap_or_else(|_| {
+ NonEmpty::new(vec![AttachmentPart::Content(String::new())]).expect("single element")
+});
+
+// RIGHT — signal that this attachment has no content
+let content = NonEmpty::new(parts).map_err(|_| AttachmentError::NoContent)?;
+```
diff --git a/rust/cloud-storage/attachment/CLAUDE.md b/rust/cloud-storage/attachment/CLAUDE.md
new file mode 100644
index 0000000000..5c5807ca2c
--- /dev/null
+++ b/rust/cloud-storage/attachment/CLAUDE.md
@@ -0,0 +1,29 @@
+# attachment
+
+Shared crate that defines the `AttachmentService` trait and supporting types for resolving entity references into AI-consumable content.
+
+## Architecture
+
+This crate has two roles:
+
+1. **Trait definition** — `AttachmentService` and `Attachable` in `lib.rs`
+2. **Provider router** — `AttachmentProvider` (behind the `provider` feature) dispatches `AttachmentReference` variants to per-domain `AttachmentService` implementations
+
+Domain crates (documents, chat, email, comms) each implement `AttachmentService` in their own `inbound/attachment/` module. This crate does not depend on any domain crate.
+
+## Module map
+
+- `lib.rs` — `AttachmentService` trait, `Attachable` trait
+- `models.rs` — `AttachmentContent`, `AttachmentPart`, `AttachmentReference`, `AttachmentError`, `Attachments`, `FormattedParts`, `TextOrImage`
+- `fmt.rs` — XML formatting utilities (`XmlTag`, `ClosedXmlTag`, `Indent`) used by `Attachable` impls and by domain crates directly
+- `attachable.rs` — `Attachable` impls for all model types; converts the attachment tree into `FormattedParts`
+- `macros.rs` — `non_empty_collection!` macro for newtype wrappers around `NonEmpty<Vec<T>>`
+- `provider.rs` — `AttachmentProvider` router (feature-gated behind `provider`)
+
+## Key rules
+
+- `AttachmentContent.content` is `NonEmpty<Vec<AttachmentPart>>`. Never insert empty or placeholder strings to satisfy the non-empty constraint. If resolution produces zero parts, return `AttachmentError::NoContent`.
+- Use `AttachmentReference` variants to identify the source entity. The `Attachable` impl for `AttachmentContent` calls `reference.as_attributes()` to produce XML tags via `fmt::XmlTag`.
+- Use `AttachmentPart::Child` with the appropriate `AttachmentReference` for sub-attachments (e.g. inline images within a markdown document). This flows through the `Attachable` formatting system.
+- Use `fmt::XmlTag` / `fmt::ClosedXmlTag` for structured text formatting within attachment services (e.g. wrapping chat messages, channel messages).
+- Individual resolution failures surface as `ResolutionError` entries in the `Attachments` batch — they never fail the entire batch.
diff --git a/rust/cloud-storage/attachment/Cargo.toml b/rust/cloud-storage/attachment/Cargo.toml
new file mode 100644
index 0000000000..412cb832aa
--- /dev/null
+++ b/rust/cloud-storage/attachment/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+edition = "2024"
+name = "attachment"
+publish = false
+version = "0.1.0"
+
+[features]
+provider = ["dep:futures"]
+
+[dependencies]
+anyhow = { workspace = true }
+thiserror = { workspace = true }
+ai = { path = "../ai" }
+macro_user_id = { path = "../macro_user_id" }
+non_empty = { path = "../non_empty" }
+futures = { workspace = true, optional = true }
diff --git a/rust/cloud-storage/attachment/src/attachable.rs b/rust/cloud-storage/attachment/src/attachable.rs
new file mode 100644
index 0000000000..476db562e8
--- /dev/null
+++ b/rust/cloud-storage/attachment/src/attachable.rs
@@ -0,0 +1,100 @@
+//! impls for Attachable
+
+use crate::Attachable;
+use crate::fmt::{ClosedXmlTag, XmlTag};
+use crate::models::*;
+use non_empty::NonEmpty;
+
+impl Attachable for Attachments {
+ fn into_formatted_parts(self) -> FormattedParts {
+ let parts = self
+ .into_parts()
+ .into_inner()
+ .into_iter()
+ .map(|result| match result {
+ Ok(content) => content.into_formatted_parts(),
+ Err(e) => e.into_formatted_parts(),
+ })
+ .fold(vec![], |mut acc, current| {
+ acc.append(&mut current.into_parts().into_inner());
+ acc
+ });
+
+ FormattedParts::new(NonEmpty::new(parts).expect("attachments is non-empty"))
+ }
+}
+
+impl Attachable for ResolutionError {
+ fn into_formatted_parts(self) -> FormattedParts {
+ XmlTag {
+ name: "unavailable_attachment",
+ attrs: &[("id", self.id.as_str())],
+ body: self.error,
+ }
+ .into_formatted_parts()
+ }
+}
+
+impl Attachable for AttachmentPart {
+ fn into_formatted_parts(self) -> FormattedParts {
+ match self {
+ AttachmentPart::Content(text) => FormattedParts::one(TextOrImage::Text(text)),
+ AttachmentPart::Image(data) => FormattedParts::one(TextOrImage::Image(data)),
+ AttachmentPart::ImageError(e) => e.into_formatted_parts(),
+ AttachmentPart::Metadata { key, value } => ClosedXmlTag {
+ name: "metadata",
+ attrs: &[("key", &key), ("value", &value)],
+ }
+ .into_formatted_parts(),
+ AttachmentPart::Child(child) => match *child {
+ Ok(content) => content.into_formatted_parts(),
+ Err(e) => e.into_formatted_parts(),
+ },
+ AttachmentPart::ChildReference(reference) => reference.into_formatted_parts(),
+ }
+ }
+}
+
+impl Attachable for NonEmpty<Vec<AttachmentPart>> {
+ fn into_formatted_parts(self) -> FormattedParts {
+ let parts = self
+ .into_inner()
+ .into_iter()
+ .map(Attachable::into_formatted_parts)
+ .fold(vec![], |mut acc, current| {
+ acc.append(&mut current.into_parts().into_inner());
+ acc
+ });
+
+ FormattedParts::new(NonEmpty::new(parts).expect("this will not be empty"))
+ }
+}
+
+impl Attachable for AttachmentContent {
+ fn into_formatted_parts(self) -> FormattedParts {
+ let attributes = self.reference.as_attributes();
+ let tag = XmlTag {
+ attrs: attributes.as_slice(),
+ name: "attachment",
+ body: self.content,
+ };
+ tag.into_formatted_parts()
+ }
+}
+
+impl Attachable for AttachmentReference {
+ fn into_formatted_parts(self) -> FormattedParts {
+ let attrs = self.as_attributes();
+ ClosedXmlTag {
+ name: "attachment_reference",
+ attrs: &attrs,
+ }
+ .into_formatted_parts()
+ }
+}
+
+impl Attachable for AttachmentError {
+ fn into_formatted_parts(self) -> FormattedParts {
+ FormattedParts::one(TextOrImage::Text(self.to_string()))
+ }
+}
diff --git a/rust/cloud-storage/attachment/src/fmt.rs b/rust/cloud-storage/attachment/src/fmt.rs
new file mode 100644
index 0000000000..6639354e8f
--- /dev/null
+++ b/rust/cloud-storage/attachment/src/fmt.rs
@@ -0,0 +1,111 @@
+//! Formatting utilities
+use std::fmt;
+
+use non_empty::NonEmpty;
+
+use crate::Attachable;
+use crate::FormattedParts;
+use crate::models::TextOrImage;
+
+const INDENT: &str = " ";
+
+/// Indent
+pub struct Indent<T>(pub T);
+
+/// XmlTag
+pub struct XmlTag<'a, T: Sized> {
+ /// Tag name.
+ pub name: &'a str,
+ /// Attributes as `(key, value)` pairs. Rendered in order, space-separated,
+ /// with double-quoted values. Values are not escaped — callers are
+ /// expected to pass attribute-safe text.
+ pub attrs: &'a [(&'a str, &'a str)],
+ /// Body content. Indented under the opening tag.
+ pub body: T,
+}
+
+/// An XML tag with no body
+pub struct ClosedXmlTag<'a> {
+ /// tag name
+ pub name: &'a str,
+ /// attributes
+ pub attrs: &'a [(&'a str, &'a str)],
+}
+
+fn format_attrs(attrs: &[(&str, &str)]) -> String {
+ attrs
+ .iter()
+ .map(|(k, v)| format!("{k}={v}"))
+ .collect::<Vec<_>>()
+ .join(" ")
+}
+
+fn open_tag(name: &str, attrs: &[(&str, &str)]) -> String {
+ format!("<{name} {}>", format_attrs(attrs))
+}
+
+fn close_tag(name: &str) -> String {
+ format!("</{name}>")
+}
+
+fn self_closing_tag(name: &str, attrs: &[(&str, &str)]) -> String {
+ format!("<{name} {}/>", format_attrs(attrs))
+}
+
+fn indent_line(line: &str) -> String {
+ format!("{INDENT}{line}")
+}
+
+impl<'a, T: Attachable> Attachable for XmlTag<'a, T> {
+ fn into_formatted_parts(self) -> FormattedParts {
+ Indent(self.body)
+ .into_formatted_parts()
+ .prepend(TextOrImage::Text(open_tag(self.name, self.attrs)))
+ .append(TextOrImage::Text(close_tag(self.name)))
+ }
+}
+
+impl<T: Attachable> Attachable for Indent<T> {
+ fn into_formatted_parts(self) -> FormattedParts {
+ self.0.into_formatted_parts().map(|p| match p {
+ img @ TextOrImage::Image(_) => img,
+ TextOrImage::Text(t) => TextOrImage::Text(indent_line(&t)),
+ })
+ }
+}
+
+impl<'a> Attachable for ClosedXmlTag<'a> {
+ fn into_formatted_parts(self) -> FormattedParts {
+ let tag = self_closing_tag(self.name, self.attrs);
+ FormattedParts::new(NonEmpty::new(vec![TextOrImage::Text(tag)]).expect("one tag"))
+ }
+}
+
+impl<T: fmt::Display> fmt::Display for Indent<T> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ let content = self.0.to_string();
+ let mut first = true;
+ for line in content.lines() {
+ if !first {
+ writeln!(f)?;
+ }
+ write!(f, "{INDENT}{line}")?;
+ first = false;
+ }
+ Ok(())
+ }
+}
+
+impl<'a, T: fmt::Display> fmt::Display for XmlTag<'a, T> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ writeln!(f, "{}", open_tag(self.name, self.attrs))?;
+ writeln!(f, "{}", Indent(&self.body))?;
+ write!(f, "{}", close_tag(self.name))
+ }
+}
+
+impl fmt::Display for ClosedXmlTag<'_> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{}", self_closing_tag(self.name, self.attrs))
+ }
+}
diff --git a/rust/cloud-storage/attachment/src/lib.rs b/rust/cloud-storage/attachment/src/lib.rs
new file mode 100644
index 0000000000..dd6fb09660
--- /dev/null
+++ b/rust/cloud-storage/attachment/src/lib.rs
@@ -0,0 +1,36 @@
+//! A lib crate to support AI attachment consumers and providers
+#![deny(missing_docs)]
+use macro_user_id::user_id::MacroUserIdStr;
+use non_empty::NonEmpty;
+
+mod attachable;
+pub mod fmt;
+mod macros;
+mod models;
+pub use models::*;
+
+#[cfg(feature = "provider")]
+pub mod provider;
+
+/// Service interface for resolving attachment references into their contents.
+pub trait AttachmentService: Send + Sync + 'static {
+ /// Resolve a batch of attachment references.
+ ///
+ /// Each reference is access-checked against `user_id` (where applicable)
+ /// and turned into a concrete
+ /// [`AttachmentContent`](super::models::AttachmentContent). Individual
+ /// failures never fail the batch — they surface as
+ /// [`FailedAttachment`](super::models::FailedAttachment) entries in the
+ /// returned [`AttachmentContents`](super::models::AttachmentContents).
+ fn resolve_attachments(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ ids: NonEmpty<&[&str]>,
+ ) -> impl Future<Output = Attachments> + Send;
+}
+
+/// An attachable is something that can be represented to AI as a [`FormattedAttachment`]
+pub trait Attachable {
+ /// transform into formatted attachment
+ fn into_formatted_parts(self) -> FormattedParts;
+}
diff --git a/rust/cloud-storage/attachment/src/macros.rs b/rust/cloud-storage/attachment/src/macros.rs
new file mode 100644
index 0000000000..ae9defe29e
--- /dev/null
+++ b/rust/cloud-storage/attachment/src/macros.rs
@@ -0,0 +1,55 @@
+#[macro_export]
+/// A tuple struct with a [`NonEmpty`] collection and some helper methods
+macro_rules! non_empty_collection {
+ (
+ $(#[$meta:meta])*
+ $vis:vis struct $name:ident($item:ty);
+ ) => {
+ $(#[$meta])*
+ $vis struct $name(NonEmpty<Vec<$item>>);
+
+ impl $name {
+ /// Wrap a non-empty vec.
+ $vis fn new(parts: NonEmpty<Vec<$item>>) -> Self {
+ Self(parts)
+ }
+
+ /// Build from a single item.
+ $vis fn one(part: $item) -> Self {
+ Self(NonEmpty::new(vec![part]).expect("single element is non-empty"))
+ }
+
+ /// Borrow the underlying parts.
+ $vis fn parts(&self) -> &NonEmpty<Vec<$item>> {
+ &self.0
+ }
+
+ /// Consume into the underlying parts.
+ $vis fn into_parts(self) -> NonEmpty<Vec<$item>> {
+ self.0
+ }
+ /// Prepend an item to the front of the collection.
+ $vis fn prepend(self, item: $item) -> Self {
+ let mut inner = self.0.into_inner();
+ inner.insert(0, item);
+ Self(NonEmpty::new(inner).expect("prepend cannot be empty"))
+ }
+ /// Append an item to the end of the collection.
+ $vis fn append(self, item: $item) -> Self {
+ let mut inner = self.0.into_inner();
+ inner.push(item);
+ Self(NonEmpty::new(inner).expect("append cannot be empty"))
+ }
+
+ /// Apply a function to each item.
+ $vis fn map(self, f: impl FnMut($item) -> $item) -> Self {
+ Self(NonEmpty::new(self.0
+ .into_inner()
+ .into_iter()
+ .map(f)
+ .collect())
+ .expect("map cannot be empty"))
+ }
+ }
+ };
+}
diff --git a/rust/cloud-storage/attachment/src/models.rs b/rust/cloud-storage/attachment/src/models.rs
new file mode 100644
index 0000000000..2466c2dbbb
--- /dev/null
+++ b/rust/cloud-storage/attachment/src/models.rs
@@ -0,0 +1,201 @@
+use std::fmt;
+
+use ai::types::ImageData;
+use non_empty::NonEmpty;
+use thiserror::Error;
+
+/// A typed reference to an attachment source.
+#[derive(Debug)]
+pub enum AttachmentReference {
+ /// A file that lives in DSS (including MD)
+ DssFile {
+ /// Document ID
+ id: String,
+ },
+ /// An image that lives in static file service
+ SfsImage {
+ /// image url
+ url: String,
+ },
+ /// An email thread
+ EmailThread {
+ /// Thread ID
+ id: String,
+ },
+ /// An AI chat
+ Chat {
+ /// Chat ID
+ id: String,
+ },
+ /// Channels thread
+ Channel {
+ /// Channel ID
+ id: String,
+ },
+}
+
+impl AttachmentReference {
+ /// The entity ID for this reference, if it has one.
+ pub fn id(&self) -> Option<&str> {
+ match self {
+ Self::DssFile { id }
+ | Self::EmailThread { id }
+ | Self::Chat { id }
+ | Self::Channel { id } => Some(id),
+ Self::SfsImage { .. } => None,
+ }
+ }
+ /// Convert this reference into XML attribute pairs.
+ pub fn as_attributes(&self) -> Vec<(&'static str, &str)> {
+ let mut attrs = vec![];
+ if let Some(id) = self.id() {
+ attrs.push(("id", id));
+ }
+ match self {
+ AttachmentReference::Channel { .. } => attrs.push(("kind", "channel")),
+ AttachmentReference::Chat { .. } => attrs.push(("kind", "chat")),
+ AttachmentReference::DssFile { .. } => attrs.push(("kind", "file")),
+ AttachmentReference::EmailThread { .. } => attrs.push(("kind", "email-thread")),
+ AttachmentReference::SfsImage { .. } => attrs.push(("kind", "static-image")),
+ }
+
+ attrs
+ }
+}
+
+/// Errors that can occur while resolving attachments.
+#[derive(Debug, Error)]
+pub enum AttachmentError {
+ /// The caller does not have read access to the referenced document.
+ #[error("no read access to document {id}")]
+ PermissionDenied {
+ /// The id of the document the user lacks access to.
+ id: String,
+ },
+ /// The referenced document has no file type recorded.
+ #[error("unknown file type")]
+ UnknownFileType,
+ /// The referenced document's file type is not supported as an attachment.
+ #[error("unsupported file type: {0}")]
+ UnsupportedFileType(String),
+ /// Resolved with no content
+ #[error("no content")]
+ NoContent,
+ /// An internal error occurred while resolving the attachment.
+ #[error(transparent)]
+ Internal(#[from] anyhow::Error),
+}
+
+/// An attachment or attachment part that failed to resolve with its id
+#[derive(Debug)]
+pub struct ResolutionError {
+ /// Id of attachment that failed to resolve
+ pub id: String,
+ /// Reason
+ pub error: AttachmentError,
+}
+
+impl ResolutionError {
+ /// Create a new resolution error.
+ pub fn new(id: String, error: AttachmentError) -> Self {
+ Self { id, error }
+ }
+}
+
+/// Rich representation of attachment content
+pub enum AttachmentPart {
+ /// An image that failed to resolve
+ ImageError(ResolutionError),
+ /// Attachment text
+ Content(String),
+ /// Attachment image data.
+ Image(ImageData),
+ /// A resolved child attachment
+ Child(Box<Result<AttachmentContent, ResolutionError>>),
+ /// A reference to a child attachment
+ ChildReference(AttachmentReference),
+ /// KV metadata
+ Metadata {
+ /// key
+ key: String,
+ /// value
+ value: String,
+ },
+}
+
+// manual impl to prevent excessive logging
+impl std::fmt::Debug for AttachmentPart {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Self::Content(s) => write!(f, "Content([{} chars])", s.chars().count()),
+ Self::ImageError(e) => e.fmt(f),
+ Self::Child(c) => c.fmt(f),
+ Self::ChildReference(r) => r.fmt(f),
+ Self::Image(i) => i.fmt(f),
+ Self::Metadata { key, value } => write!(f, "{}: {}", key, value),
+ }
+ }
+}
+
+/// A resolved attachment
+#[derive(Debug)]
+pub struct AttachmentContent {
+ /// name + kind
+ pub reference: AttachmentReference,
+ /// name
+ pub name: Option<String>,
+ /// content
+ pub content: NonEmpty<Vec<AttachmentPart>>,
+}
+
+crate::non_empty_collection! {
+ /// The full attachment represented as an ordered collection of parts.
+ ///
+ /// Produced by [`Attachable`](super::ports::Attachable) implementations.
+ /// Guaranteed to contain at least one part via [`NonEmpty`].
+ #[derive(Debug)]
+ pub struct Attachments(Result<AttachmentContent, ResolutionError>);
+}
+
+/// The primitive form of attachment data sent to AI providers
+pub enum TextOrImage {
+ /// All non-image dats is represented as text
+ Text(String),
+ /// Images may be links or base64
+ Image(ImageData),
+}
+
+crate::non_empty_collection! {
+ /// A collection of attachment data constructed from one or more attachments
+ pub struct FormattedParts(TextOrImage);
+}
+
+impl FormattedParts {
+ /// Merge adjacent text parts into single parts.
+ pub fn compact(self) -> Self {
+ let (mut all, last) =
+ self.0
+ .into_inner()
+ .into_iter()
+ .fold((Vec::new(), None), |(mut acc, prev), current| {
+ if let TextOrImage::Image(c) = current {
+ if let Some(p) = prev {
+ acc.push(p)
+ }
+ acc.push(TextOrImage::Image(c));
+ (acc, None)
+ } else if let TextOrImage::Text(ref c) = current
+ && let Some(TextOrImage::Text(p)) = prev
+ {
+ (acc, Some(TextOrImage::Text(format!("{}\n{}", p, c))))
+ } else {
+ (acc, Some(current))
+ }
+ });
+
+ if let Some(last) = last {
+ all.push(last)
+ }
+ Self(NonEmpty::new(all).expect("compaction should always be non-empty"))
+ }
+}
diff --git a/rust/cloud-storage/attachment/src/provider.rs b/rust/cloud-storage/attachment/src/provider.rs
new file mode 100644
index 0000000000..821ad2bd9d
--- /dev/null
+++ b/rust/cloud-storage/attachment/src/provider.rs
@@ -0,0 +1,90 @@
+//! Attachment provider — a router that dispatches [`AttachmentReference`]s
+//! to the correct [`AttachmentService`] by variant.
+
+use macro_user_id::user_id::MacroUserIdStr;
+use non_empty::NonEmpty;
+
+use crate::{
+ AttachmentContent, AttachmentReference, AttachmentService, Attachments, ResolutionError,
+};
+
+/// Routes [`AttachmentReference`]s to per-variant [`AttachmentService`] implementations.
+pub struct AttachmentProvider<Dss, Sfs, Email, Chat, Chan> {
+ /// Resolves [`AttachmentReference::DssFile`] references.
+ pub dss_file: Dss,
+ /// Resolves [`AttachmentReference::SfsImage`] references.
+ pub sfs_image: Sfs,
+ /// Resolves [`AttachmentReference::EmailThread`] references.
+ pub email_thread: Email,
+ /// Resolves [`AttachmentReference::Chat`] references.
+ pub chat: Chat,
+ /// Resolves [`AttachmentReference::Channel`] references.
+ pub channel: Chan,
+}
+
+impl<Dss, Sfs, Email, Chat, Chan> AttachmentProvider<Dss, Sfs, Email, Chat, Chan>
+where
+ Dss: AttachmentService,
+ Sfs: AttachmentService,
+ Email: AttachmentService,
+ Chat: AttachmentService,
+ Chan: AttachmentService,
+{
+ /// Resolve a batch of references, routing each to the service for
+ /// its variant. Groups are dispatched concurrently.
+ pub async fn resolve(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ references: NonEmpty<Vec<AttachmentReference>>,
+ ) -> Attachments {
+ let mut dss_ids = Vec::new();
+ let mut sfs_ids = Vec::new();
+ let mut email_ids = Vec::new();
+ let mut chat_ids = Vec::new();
+ let mut chan_ids = Vec::new();
+
+ for r in references.into_inner() {
+ match r {
+ AttachmentReference::DssFile { id } => dss_ids.push(id),
+ AttachmentReference::SfsImage { url } => sfs_ids.push(url),
+ AttachmentReference::EmailThread { id } => email_ids.push(id),
+ AttachmentReference::Chat { id } => chat_ids.push(id),
+ AttachmentReference::Channel { id } => chan_ids.push(id),
+ }
+ }
+
+ let (a, b, c, d, e) = futures::join!(
+ dispatch(&self.dss_file, user_id.clone(), dss_ids),
+ dispatch(&self.sfs_image, user_id.clone(), sfs_ids),
+ dispatch(&self.email_thread, user_id.clone(), email_ids),
+ dispatch(&self.chat, user_id.clone(), chat_ids),
+ dispatch(&self.channel, user_id, chan_ids),
+ );
+
+ let mut results = Vec::with_capacity(a.len() + b.len() + c.len() + d.len() + e.len());
+ results.extend(a);
+ results.extend(b);
+ results.extend(c);
+ results.extend(d);
+ results.extend(e);
+
+ Attachments::new(NonEmpty::new(results).expect("references was non-empty"))
+ }
+}
+
+async fn dispatch<S: AttachmentService>(
+ service: &S,
+ user_id: MacroUserIdStr<'_>,
+ ids: Vec<String>,
+) -> Vec<Result<AttachmentContent, ResolutionError>> {
+ if ids.is_empty() {
+ return Vec::new();
+ }
+ let refs: Vec<&str> = ids.iter().map(|s| s.as_str()).collect();
+ let ne = NonEmpty::new(refs.as_slice()).expect("checked non-empty");
+ service
+ .resolve_attachments(user_id, ne)
+ .await
+ .into_parts()
+ .into_inner()
+}
diff --git a/rust/cloud-storage/chat/Cargo.toml b/rust/cloud-storage/chat/Cargo.toml
index eed90913e4..b122da2550 100644
--- a/rust/cloud-storage/chat/Cargo.toml
+++ b/rust/cloud-storage/chat/Cargo.toml
@@ -6,6 +6,11 @@ version = "0.1.0"
[features]
default = ["inbound", "outbound", "ports"]
+attachment = [
+ "dep:attachment",
+ "dep:futures",
+ "inbound",
+]
inbound = [
"dep:axum",
"dep:model_user",
@@ -29,6 +34,7 @@ entity_access_management = { path = "../entity_access_management", default-featu
] }
macro_user_id = { path = "../macro_user_id" }
model = { path = "../model" }
+non_empty = { path = "../non_empty" }
model-entity = { path = "../model-entity" }
models_entity_access_management = { path = "../models_entity_access_management", default-features = false }
models_permissions = { path = "../models_permissions" }
@@ -40,6 +46,10 @@ tracing = { workspace = true }
unicode-segmentation = { workspace = true }
uuid = { workspace = true }
+# Attachment (attachment provider)
+attachment = { path = "../attachment", optional = true }
+futures = { workspace = true, optional = true }
+
# Inbound (HTTP handlers)
axum = { workspace = true, optional = true }
model_user = { path = "../model_user", optional = true }
diff --git a/rust/cloud-storage/chat/src/inbound/attachment.rs b/rust/cloud-storage/chat/src/inbound/attachment.rs
new file mode 100644
index 0000000000..d3bb7ecc95
--- /dev/null
+++ b/rust/cloud-storage/chat/src/inbound/attachment.rs
@@ -0,0 +1,100 @@
+//! Attachment inbound adapter for the chat domain.
+
+use std::sync::Arc;
+
+use attachment::{
+ AttachmentContent, AttachmentError, AttachmentPart, AttachmentReference, AttachmentService,
+ Attachments, ResolutionError, fmt::XmlTag,
+};
+use entity_access::domain::{models::ViewAccessLevel, ports::EntityAccessService};
+use futures::future::join_all;
+use macro_user_id::user_id::MacroUserIdStr;
+use model::chat::ChatMessageWithAttachments;
+use model_entity::EntityType;
+use non_empty::NonEmpty;
+
+use crate::domain::ports::ChatRepo;
+
+/// Resolves chat IDs into [`Attachments`].
+pub struct ChatAttachmentService<R, ESvc> {
+ repo: Arc<R>,
+ entity_access_service: Arc<ESvc>,
+}
+
+impl<R, ESvc> ChatAttachmentService<R, ESvc> {
+ /// Create a new chat attachment service.
+ pub fn new(repo: Arc<R>, entity_access_service: Arc<ESvc>) -> Self {
+ Self {
+ repo,
+ entity_access_service,
+ }
+ }
+}
+
+impl<R: ChatRepo, ESvc: EntityAccessService> AttachmentService for ChatAttachmentService<R, ESvc> {
+ #[tracing::instrument(skip_all)]
+ async fn resolve_attachments(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ ids: NonEmpty<&[&str]>,
+ ) -> Attachments {
+ let user_id = &user_id;
+ let results = join_all(ids.iter().map(|id| async move {
+ self.resolve_one(user_id, id)
+ .await
+ .map_err(|error| ResolutionError::new(id.to_string(), error))
+ }))
+ .await;
+
+ Attachments::new(NonEmpty::new(results).expect("ids was non-empty"))
+ }
+}
+
+impl<R: ChatRepo, ESvc: EntityAccessService> ChatAttachmentService<R, ESvc> {
+ #[tracing::instrument(skip(self), err)]
+ async fn resolve_one(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ id: &str,
+ ) -> Result<AttachmentContent, AttachmentError> {
+ self.entity_access_service
+ .generate_entity_access_receipt::<ViewAccessLevel>(user_id, None, id, EntityType::Chat)
+ .await
+ .map_err(|e| AttachmentError::Internal(e.into()))?;
+
+ let chat = self
+ .repo
+ .get_chat(id)
+ .await
+ .map_err(|e| AttachmentError::Internal(e.into()))?;
+
+ let parts: Vec<AttachmentPart> = chat.messages.iter().filter_map(format_message).collect();
+
+ let content = NonEmpty::new(parts).map_err(|_| AttachmentError::NoContent)?;
+
+ Ok(AttachmentContent {
+ reference: AttachmentReference::Chat { id: id.to_string() },
+ name: Some(chat.name),
+ content,
+ })
+ }
+}
+
+fn format_message(msg: &ChatMessageWithAttachments) -> Option<AttachmentPart> {
+ let text = msg.content_text()?;
+ if text.is_empty() {
+ return None;
+ }
+ let role = match msg.role {
+ ai::types::Role::User => "user",
+ ai::types::Role::Assistant => "assistant",
+ ai::types::Role::System => "system",
+ };
+ let formatted = XmlTag {
+ name: "message",
+ attrs: &[("role", role)],
+ body: &text,
+ }
+ .to_string();
+ Some(AttachmentPart::Content(formatted))
+}
diff --git a/rust/cloud-storage/chat/src/inbound/mod.rs b/rust/cloud-storage/chat/src/inbound/mod.rs
index 0f3951a6d5..97f4664b3a 100644
--- a/rust/cloud-storage/chat/src/inbound/mod.rs
+++ b/rust/cloud-storage/chat/src/inbound/mod.rs
@@ -1,4 +1,7 @@
-//! Inbound HTTP adapters for the chat domain.
+//! Inbound adapters for the chat domain.
+
+#[cfg(feature = "attachment")]
+pub mod attachment;
#[cfg(test)]
mod test;
diff --git a/rust/cloud-storage/comms/.sqlx/query-993f8bd336bc9ba45ab51edac700887af626bf74de28e395ab8a1875bc9fe9ac.json b/rust/cloud-storage/comms/.sqlx/query-993f8bd336bc9ba45ab51edac700887af626bf74de28e395ab8a1875bc9fe9ac.json
new file mode 100644
index 0000000000..44028b170c
--- /dev/null
+++ b/rust/cloud-storage/comms/.sqlx/query-993f8bd336bc9ba45ab51edac700887af626bf74de28e395ab8a1875bc9fe9ac.json
@@ -0,0 +1,65 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n m.id AS \"message_id!\",\n m.thread_id,\n m.sender_id AS \"sender_id!\",\n m.content AS \"content!\",\n m.created_at AS \"created_at!\",\n m.updated_at AS \"updated_at!\",\n m.deleted_at::timestamptz AS \"deleted_at?\",\n COALESCE(\n ARRAY(\n SELECT entity_type || ':' || entity_id\n FROM comms_entity_mentions em\n WHERE em.source_entity_type = 'message'\n AND em.source_entity_id = m.id::text\n ),\n '{}'::text[]\n ) AS \"mentions!\"\n FROM comms_messages m\n WHERE m.channel_id = $1\n AND m.deleted_at IS NULL\n ORDER BY m.created_at DESC\n LIMIT $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "message_id!",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "thread_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "sender_id!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "content!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "created_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "updated_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "deleted_at?",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "mentions!",
+ "type_info": "TextArray"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ false,
+ false,
+ false,
+ false,
+ null,
+ null
+ ]
+ },
+ "hash": "993f8bd336bc9ba45ab51edac700887af626bf74de28e395ab8a1875bc9fe9ac"
+}
diff --git a/rust/cloud-storage/comms/.sqlx/query-9a32d4826e372e762f828cb5aed93f60b6731fa2c553f3fda711cf72f1574fae.json b/rust/cloud-storage/comms/.sqlx/query-9a32d4826e372e762f828cb5aed93f60b6731fa2c553f3fda711cf72f1574fae.json
new file mode 100644
index 0000000000..0e586ce9a4
--- /dev/null
+++ b/rust/cloud-storage/comms/.sqlx/query-9a32d4826e372e762f828cb5aed93f60b6731fa2c553f3fda711cf72f1574fae.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT name FROM comms_channels WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "name",
+ "type_info": "Varchar"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "9a32d4826e372e762f828cb5aed93f60b6731fa2c553f3fda711cf72f1574fae"
+}
diff --git a/rust/cloud-storage/comms/Cargo.toml b/rust/cloud-storage/comms/Cargo.toml
index 3690a80b5d..ffbef8ce02 100644
--- a/rust/cloud-storage/comms/Cargo.toml
+++ b/rust/cloud-storage/comms/Cargo.toml
@@ -5,11 +5,23 @@ publish = false
version = "0.1.0"
[features]
+attachment = [
+ "dep:anyhow",
+ "dep:attachment",
+ "dep:entity_access",
+ "dep:futures",
+ "dep:non_empty",
+]
inbound = ["dep:axum", "dep:model_user", "dep:utoipa"]
outbound = ["dep:readonly_pool", "dep:sqlx"]
[dependencies]
+anyhow = { workspace = true, optional = true }
+attachment = { path = "../attachment", optional = true }
+entity_access = { path = "../entity_access", optional = true, default-features = false, features = ["ports"] }
+futures = { workspace = true, optional = true }
+non_empty = { path = "../non_empty", optional = true }
axum = { workspace = true, optional = true }
chrono = { workspace = true }
doppleganger = { workspace = true, features = ["chrono", "uuid"] }
diff --git a/rust/cloud-storage/comms/src/domain/ports.rs b/rust/cloud-storage/comms/src/domain/ports.rs
index 47602b0c41..7d595d04aa 100644
--- a/rust/cloud-storage/comms/src/domain/ports.rs
+++ b/rust/cloud-storage/comms/src/domain/ports.rs
@@ -2,7 +2,7 @@ use std::collections::{HashMap, HashSet};
use macro_user_id::user_id::MacroUserIdStr;
use models_comms::channel::{
- Activity, ChannelId, ChannelWithLatest, ChannelWithParticipants, LatestMessage,
+ Activity, ChannelId, ChannelMessage, ChannelWithLatest, ChannelWithParticipants, LatestMessage,
};
use rootcause::Report;
@@ -23,6 +23,17 @@ pub trait CommsRepo: Send + Sync + 'static {
&self,
user_id: MacroUserIdStr<'_>,
) -> impl Future<Output = Result<Vec<Activity>, Report>> + Send;
+
+ fn get_channel_name(
+ &self,
+ channel_id: ChannelId,
+ ) -> impl Future<Output = Result<Option<String>, Report>> + Send;
+
+ fn get_recent_messages(
+ &self,
+ channel_id: ChannelId,
+ limit: u32,
+ ) -> impl Future<Output = Result<Vec<ChannelMessage>, Report>> + Send;
}
pub trait UserRepo: Send + Sync + 'static {
diff --git a/rust/cloud-storage/comms/src/inbound.rs b/rust/cloud-storage/comms/src/inbound.rs
index f368b57c32..50f0e4481f 100644
--- a/rust/cloud-storage/comms/src/inbound.rs
+++ b/rust/cloud-storage/comms/src/inbound.rs
@@ -1,232 +1,7 @@
-use axum::{Json, Router, extract::State, http::StatusCode, response::IntoResponse, routing::get};
-use doppleganger::{Doppleganger, Mirror};
-use frecency::domain::models::AggregateFrecency;
-use macro_user_id::user_id::MacroUserIdStr;
-use model_user::axum_extractor::MacroUserExtractor;
-use models_comms::channel::{ChannelId, OrganizationId};
-use serde::Serialize;
-use std::sync::Arc;
-use thiserror::Error;
-use utoipa::ToSchema;
-use uuid::Uuid;
+#[cfg(feature = "inbound")]
+mod router;
+#[cfg(feature = "inbound")]
+pub use router::*;
-use crate::domain::{models::GetChannelsRequest, ports::ChannelsService};
-
-pub struct CommsRouterState<S> {
- pub inner: Arc<S>,
-}
-
-impl<S> Clone for CommsRouterState<S> {
- fn clone(&self) -> Self {
- Self {
- inner: Arc::clone(&self.inner),
- }
- }
-}
-
-impl<S: ChannelsService> CommsRouterState<S> {
- pub fn new(s: S) -> Self {
- CommsRouterState { inner: Arc::new(s) }
- }
-}
-
-pub fn comms_router<S: ChannelsService, T: Send + Sync + 'static>(
- s: CommsRouterState<S>,
-) -> Router<T> {
- Router::new()
- .route("/channels", get(get_channels_handler))
- .route("/activity", get(get_activity_handler))
- .with_state(s)
-}
-
-#[derive(Debug, Error)]
-pub enum CommsErr {
- #[error("Internal server error")]
- Internal,
-}
-
-impl IntoResponse for CommsErr {
- fn into_response(self) -> axum::response::Response {
- let status = match self {
- CommsErr::Internal => StatusCode::INTERNAL_SERVER_ERROR,
- };
-
- (status, self.to_string()).into_response()
- }
-}
-
-#[utoipa::path(
- get,
- path = "/channels",
- tag = "channels",
- operation_id = "get_channels",
- responses(
- (status = 200, body=Vec<ApiChannelWithLatest>),
- (status = 401, body=String),
- (status = 404, body=String),
- (status = 500, body=String),
- )
-)]
-async fn get_channels_handler<S: ChannelsService>(
- State(service): State<CommsRouterState<S>>,
- MacroUserExtractor { macro_user_id, .. }: MacroUserExtractor,
-) -> Result<Json<Vec<ApiChannelWithLatest>>, CommsErr> {
- let res = service
- .inner
- .get_channels(GetChannelsRequest {
- macro_id: macro_user_id,
- limit: None,
- query: models_pagination::Query::Sort(
- models_pagination::SimpleSortMethod::UpdatedAt,
- None,
- ),
- })
- .await
- .map_err(|_| CommsErr::Internal)?;
-
- Ok(Json(<Vec<ApiChannelWithLatest>>::mirror(res)))
-}
-
-#[tracing::instrument(skip(service))]
-#[utoipa::path(get,
- tag = "activity",
- operation_id = "get_activity",
- path = "/activity", responses(
- (status = 200, body=Vec<ApiActivity>),
- (status = 401, body=String),
- (status = 404, body=String),
- (status = 500, body=String),
-))]
-pub async fn get_activity_handler<S: ChannelsService>(
- State(service): State<CommsRouterState<S>>,
- MacroUserExtractor { macro_user_id, .. }: MacroUserExtractor,
-) -> Result<Json<Vec<ApiActivity>>, CommsErr> {
- let res = service
- .inner
- .get_activities(macro_user_id)
- .await
- .map_err(|_| CommsErr::Internal)?;
-
- Ok(Json(<Vec<ApiActivity>>::mirror(res)))
-}
-
-#[derive(Debug, Clone, Copy, Serialize, ToSchema, Doppleganger)]
-#[serde(rename_all = "snake_case")]
-#[dg(backward = models_comms::channel::ParticipantRole)]
-pub enum ParticipantRole {
- Owner,
- Admin,
- Member,
-}
-
-#[derive(Debug, Clone, Serialize, ToSchema, Doppleganger)]
-#[dg(backward = models_comms::channel::ChannelParticipant)]
-pub struct ChannelParticipant {
- /// id of the channel
- #[schema(value_type = Uuid)]
- pub channel_id: ChannelId,
- /// id of the user
- #[schema(value_type = String)]
- pub user_id: MacroUserIdStr<'static>,
- /// type of the participant
- pub role: ParticipantRole,
- /// timestamp of when the user joined the channel
- pub joined_at: chrono::DateTime<chrono::Utc>,
- /// timestamp of when the user left the channel
- pub left_at: Option<chrono::DateTime<chrono::Utc>>,
-}
-
-#[derive(Debug, Clone, Serialize, ToSchema, Doppleganger)]
-#[dg(backward = models_comms::channel::ChannelWithParticipants)]
-pub struct ChannelWithParticipants {
- #[serde(flatten)]
- pub channel: Channel,
- pub participants: Vec<ChannelParticipant>,
-}
-
-#[derive(Debug, Clone, Serialize, ToSchema, Doppleganger)]
-#[dg(backward = models_comms::channel::ChannelWithLatest)]
-pub struct ApiChannelWithLatest {
- #[serde(flatten)]
- pub channel: ChannelWithParticipants,
- #[serde(flatten)]
- pub latest_message: LatestMessage,
- pub viewed_at: Option<chrono::DateTime<chrono::Utc>>,
- pub interacted_at: Option<chrono::DateTime<chrono::Utc>>,
- #[dg(map = map_frecency)]
- pub frecency_score: Option<f64>,
-}
-
-fn map_frecency(f: Option<AggregateFrecency>) -> Option<f64> {
- f.map(|f| f.data.frecency_score)
-}
-
-#[derive(Debug, Clone, Serialize, ToSchema, Doppleganger)]
-#[dg(backward = models_comms::channel::Channel)]
-pub struct Channel {
- /// uuid of the channel
- #[schema(value_type = Uuid)]
- pub id: ChannelId,
- /// string name of the channel
- pub name: Option<String>,
- /// type of the channel
- pub channel_type: ChannelType,
- /// id of the organization this channel belongs too
- #[schema(value_type = Option<u32>)]
- pub org_id: Option<OrganizationId>,
- /// timestamp of when the channel was created
- pub created_at: chrono::DateTime<chrono::Utc>,
- /// timestamp of when the channel was last updated
- pub updated_at: chrono::DateTime<chrono::Utc>,
- /// id of the user who created the channel
- #[schema(value_type = String)]
- pub owner_id: MacroUserIdStr<'static>,
-}
-
-#[derive(Debug, Clone, ToSchema, Serialize, Doppleganger)]
-#[dg(backward = models_comms::channel::LatestMessage)]
-pub struct LatestMessage {
- pub latest_message: Option<ChannelMessage>,
- pub latest_non_thread_message: Option<ChannelMessage>,
-}
-
-#[derive(Debug, Clone, Copy, Serialize, Doppleganger, ToSchema)]
-#[dg(backward = models_comms::channel::ChannelType)]
-#[serde(rename_all = "snake_case")]
-pub enum ChannelType {
- Public,
- Organization,
- Private,
- DirectMessage,
- Team,
-}
-
-#[derive(Debug, Clone, Serialize, ToSchema, Doppleganger)]
-#[dg(backward = models_comms::channel::ChannelMessage)]
-pub struct ChannelMessage {
- pub message_id: Uuid,
- pub thread_id: Option<Uuid>,
- pub sender_id: String,
- pub content: String,
- pub created_at: chrono::DateTime<chrono::Utc>,
- pub updated_at: chrono::DateTime<chrono::Utc>,
- pub deleted_at: Option<chrono::DateTime<chrono::Utc>>,
- /// message mentions formatted as `{ENTITY_TYPE}:{ENTITY_ID}`
- pub mentions: Vec<String>,
-}
-
-#[derive(Debug, ToSchema, Doppleganger, Serialize)]
-#[dg(backward = models_comms::channel::Activity)]
-pub struct ApiActivity {
- pub id: Uuid,
- pub user_id: String,
- #[schema(value_type = Uuid)]
- pub channel_id: ChannelId,
- pub created_at: chrono::DateTime<chrono::Utc>,
- pub updated_at: chrono::DateTime<chrono::Utc>,
- /// the last time the user viewed the channel
- pub viewed_at: Option<chrono::DateTime<chrono::Utc>>,
- /// the last time the user intereacted with the channel
- /// eg. reacting, replying, sending a message
- pub interacted_at: Option<chrono::DateTime<chrono::Utc>>,
-}
+#[cfg(feature = "attachment")]
+pub mod attachment;
diff --git a/rust/cloud-storage/comms/src/inbound/attachment.rs b/rust/cloud-storage/comms/src/inbound/attachment.rs
new file mode 100644
index 0000000000..c417695b98
--- /dev/null
+++ b/rust/cloud-storage/comms/src/inbound/attachment.rs
@@ -0,0 +1,125 @@
+//! Attachment inbound adapter for the comms domain.
+
+use std::fmt::Write;
+use std::sync::Arc;
+
+use attachment::fmt::XmlTag;
+use attachment::{
+ AttachmentContent, AttachmentError, AttachmentPart, AttachmentReference, AttachmentService,
+ Attachments, ResolutionError,
+};
+use entity_access::domain::{
+ models::{AccessError, MemberParticipantRole},
+ ports::EntityAccessService,
+};
+use futures::future::join_all;
+use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::EntityType;
+use models_comms::channel::{ChannelId, ChannelMessage};
+use non_empty::NonEmpty;
+
+use crate::domain::ports::CommsRepo;
+
+const MESSAGE_LIMIT: u32 = 50;
+
+/// Resolves channel IDs into [`Attachments`].
+pub struct CommsAttachmentService<C, E> {
+ comms_repo: Arc<C>,
+ entity_access_service: Arc<E>,
+}
+
+impl<C, E> CommsAttachmentService<C, E> {
+ /// Create a new comms attachment service.
+ pub fn new(comms_repo: Arc<C>, entity_access_service: Arc<E>) -> Self {
+ Self {
+ comms_repo,
+ entity_access_service,
+ }
+ }
+}
+
+impl<C: CommsRepo, E: EntityAccessService> AttachmentService for CommsAttachmentService<C, E> {
+ #[tracing::instrument(skip_all)]
+ async fn resolve_attachments(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ ids: NonEmpty<&[&str]>,
+ ) -> Attachments {
+ let user_id = &user_id;
+ let results = join_all(ids.iter().map(|id| async move {
+ self.resolve_one(user_id, id)
+ .await
+ .map_err(|error| ResolutionError::new(id.to_string(), error))
+ }))
+ .await;
+ Attachments::new(NonEmpty::new(results).expect("ids was non-empty"))
+ }
+}
+
+impl<C: CommsRepo, E: EntityAccessService> CommsAttachmentService<C, E> {
+ #[tracing::instrument(skip(self), err)]
+ async fn resolve_one(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ id: &str,
+ ) -> Result<AttachmentContent, AttachmentError> {
+ let channel_id =
+ ChannelId(uuid::Uuid::parse_str(id).map_err(|e| AttachmentError::Internal(e.into()))?);
+
+ self.entity_access_service
+ .generate_entity_access_receipt::<MemberParticipantRole>(
+ user_id,
+ None,
+ id,
+ EntityType::Channel,
+ )
+ .await
+ .map_err(|e| match e {
+ AccessError::Unauthorized | AccessError::UnauthorizedWithMessage(_) => {
+ AttachmentError::PermissionDenied { id: id.to_string() }
+ }
+ other => AttachmentError::Internal(anyhow::anyhow!("{other:#}")),
+ })?;
+
+ let (name, messages) = tokio::join!(
+ self.comms_repo.get_channel_name(channel_id),
+ self.comms_repo
+ .get_recent_messages(channel_id, MESSAGE_LIMIT),
+ );
+
+ let name = name.map_err(|e| AttachmentError::Internal(anyhow::anyhow!("{e:#}")))?;
+ let mut messages =
+ messages.map_err(|e| AttachmentError::Internal(anyhow::anyhow!("{e:#}")))?;
+ messages.reverse();
+
+ let parts = format_messages(&messages);
+
+ Ok(AttachmentContent {
+ reference: AttachmentReference::Channel { id: id.to_string() },
+ name,
+ content: NonEmpty::new(vec![AttachmentPart::Content(parts)])
+ .expect("single element is non-empty"),
+ })
+ }
+}
+
+fn format_messages(messages: &[ChannelMessage]) -> String {
+ if messages.is_empty() {
+ return "(no messages)".to_string();
+ }
+
+ let mut body = String::new();
+ for msg in messages {
+ let timestamp = msg.created_at.format("%Y-%m-%d %H:%M");
+ let tag = XmlTag {
+ name: "message",
+ attrs: &[
+ ("sender", &msg.sender_id),
+ ("timestamp", &timestamp.to_string()),
+ ],
+ body: &msg.content,
+ };
+ writeln!(&mut body, "{tag}").expect("write to string");
+ }
+ body
+}
diff --git a/rust/cloud-storage/comms/src/inbound/router.rs b/rust/cloud-storage/comms/src/inbound/router.rs
new file mode 100644
index 0000000000..f368b57c32
--- /dev/null
+++ b/rust/cloud-storage/comms/src/inbound/router.rs
@@ -0,0 +1,232 @@
+use axum::{Json, Router, extract::State, http::StatusCode, response::IntoResponse, routing::get};
+use doppleganger::{Doppleganger, Mirror};
+use frecency::domain::models::AggregateFrecency;
+use macro_user_id::user_id::MacroUserIdStr;
+use model_user::axum_extractor::MacroUserExtractor;
+use models_comms::channel::{ChannelId, OrganizationId};
+use serde::Serialize;
+use std::sync::Arc;
+use thiserror::Error;
+use utoipa::ToSchema;
+use uuid::Uuid;
+
+use crate::domain::{models::GetChannelsRequest, ports::ChannelsService};
+
+pub struct CommsRouterState<S> {
+ pub inner: Arc<S>,
+}
+
+impl<S> Clone for CommsRouterState<S> {
+ fn clone(&self) -> Self {
+ Self {
+ inner: Arc::clone(&self.inner),
+ }
+ }
+}
+
+impl<S: ChannelsService> CommsRouterState<S> {
+ pub fn new(s: S) -> Self {
+ CommsRouterState { inner: Arc::new(s) }
+ }
+}
+
+pub fn comms_router<S: ChannelsService, T: Send + Sync + 'static>(
+ s: CommsRouterState<S>,
+) -> Router<T> {
+ Router::new()
+ .route("/channels", get(get_channels_handler))
+ .route("/activity", get(get_activity_handler))
+ .with_state(s)
+}
+
+#[derive(Debug, Error)]
+pub enum CommsErr {
+ #[error("Internal server error")]
+ Internal,
+}
+
+impl IntoResponse for CommsErr {
+ fn into_response(self) -> axum::response::Response {
+ let status = match self {
+ CommsErr::Internal => StatusCode::INTERNAL_SERVER_ERROR,
+ };
+
+ (status, self.to_string()).into_response()
+ }
+}
+
+#[utoipa::path(
+ get,
+ path = "/channels",
+ tag = "channels",
+ operation_id = "get_channels",
+ responses(
+ (status = 200, body=Vec<ApiChannelWithLatest>),
+ (status = 401, body=String),
+ (status = 404, body=String),
+ (status = 500, body=String),
+ )
+)]
+async fn get_channels_handler<S: ChannelsService>(
+ State(service): State<CommsRouterState<S>>,
+ MacroUserExtractor { macro_user_id, .. }: MacroUserExtractor,
+) -> Result<Json<Vec<ApiChannelWithLatest>>, CommsErr> {
+ let res = service
+ .inner
+ .get_channels(GetChannelsRequest {
+ macro_id: macro_user_id,
+ limit: None,
+ query: models_pagination::Query::Sort(
+ models_pagination::SimpleSortMethod::UpdatedAt,
+ None,
+ ),
+ })
+ .await
+ .map_err(|_| CommsErr::Internal)?;
+
+ Ok(Json(<Vec<ApiChannelWithLatest>>::mirror(res)))
+}
+
+#[tracing::instrument(skip(service))]
+#[utoipa::path(get,
+ tag = "activity",
+ operation_id = "get_activity",
+ path = "/activity", responses(
+ (status = 200, body=Vec<ApiActivity>),
+ (status = 401, body=String),
+ (status = 404, body=String),
+ (status = 500, body=String),
+))]
+pub async fn get_activity_handler<S: ChannelsService>(
+ State(service): State<CommsRouterState<S>>,
+ MacroUserExtractor { macro_user_id, .. }: MacroUserExtractor,
+) -> Result<Json<Vec<ApiActivity>>, CommsErr> {
+ let res = service
+ .inner
+ .get_activities(macro_user_id)
+ .await
+ .map_err(|_| CommsErr::Internal)?;
+
+ Ok(Json(<Vec<ApiActivity>>::mirror(res)))
+}
+
+#[derive(Debug, Clone, Copy, Serialize, ToSchema, Doppleganger)]
+#[serde(rename_all = "snake_case")]
+#[dg(backward = models_comms::channel::ParticipantRole)]
+pub enum ParticipantRole {
+ Owner,
+ Admin,
+ Member,
+}
+
+#[derive(Debug, Clone, Serialize, ToSchema, Doppleganger)]
+#[dg(backward = models_comms::channel::ChannelParticipant)]
+pub struct ChannelParticipant {
+ /// id of the channel
+ #[schema(value_type = Uuid)]
+ pub channel_id: ChannelId,
+ /// id of the user
+ #[schema(value_type = String)]
+ pub user_id: MacroUserIdStr<'static>,
+ /// type of the participant
+ pub role: ParticipantRole,
+ /// timestamp of when the user joined the channel
+ pub joined_at: chrono::DateTime<chrono::Utc>,
+ /// timestamp of when the user left the channel
+ pub left_at: Option<chrono::DateTime<chrono::Utc>>,
+}
+
+#[derive(Debug, Clone, Serialize, ToSchema, Doppleganger)]
+#[dg(backward = models_comms::channel::ChannelWithParticipants)]
+pub struct ChannelWithParticipants {
+ #[serde(flatten)]
+ pub channel: Channel,
+ pub participants: Vec<ChannelParticipant>,
+}
+
+#[derive(Debug, Clone, Serialize, ToSchema, Doppleganger)]
+#[dg(backward = models_comms::channel::ChannelWithLatest)]
+pub struct ApiChannelWithLatest {
+ #[serde(flatten)]
+ pub channel: ChannelWithParticipants,
+ #[serde(flatten)]
+ pub latest_message: LatestMessage,
+ pub viewed_at: Option<chrono::DateTime<chrono::Utc>>,
+ pub interacted_at: Option<chrono::DateTime<chrono::Utc>>,
+ #[dg(map = map_frecency)]
+ pub frecency_score: Option<f64>,
+}
+
+fn map_frecency(f: Option<AggregateFrecency>) -> Option<f64> {
+ f.map(|f| f.data.frecency_score)
+}
+
+#[derive(Debug, Clone, Serialize, ToSchema, Doppleganger)]
+#[dg(backward = models_comms::channel::Channel)]
+pub struct Channel {
+ /// uuid of the channel
+ #[schema(value_type = Uuid)]
+ pub id: ChannelId,
+ /// string name of the channel
+ pub name: Option<String>,
+ /// type of the channel
+ pub channel_type: ChannelType,
+ /// id of the organization this channel belongs too
+ #[schema(value_type = Option<u32>)]
+ pub org_id: Option<OrganizationId>,
+ /// timestamp of when the channel was created
+ pub created_at: chrono::DateTime<chrono::Utc>,
+ /// timestamp of when the channel was last updated
+ pub updated_at: chrono::DateTime<chrono::Utc>,
+ /// id of the user who created the channel
+ #[schema(value_type = String)]
+ pub owner_id: MacroUserIdStr<'static>,
+}
+
+#[derive(Debug, Clone, ToSchema, Serialize, Doppleganger)]
+#[dg(backward = models_comms::channel::LatestMessage)]
+pub struct LatestMessage {
+ pub latest_message: Option<ChannelMessage>,
+ pub latest_non_thread_message: Option<ChannelMessage>,
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Doppleganger, ToSchema)]
+#[dg(backward = models_comms::channel::ChannelType)]
+#[serde(rename_all = "snake_case")]
+pub enum ChannelType {
+ Public,
+ Organization,
+ Private,
+ DirectMessage,
+ Team,
+}
+
+#[derive(Debug, Clone, Serialize, ToSchema, Doppleganger)]
+#[dg(backward = models_comms::channel::ChannelMessage)]
+pub struct ChannelMessage {
+ pub message_id: Uuid,
+ pub thread_id: Option<Uuid>,
+ pub sender_id: String,
+ pub content: String,
+ pub created_at: chrono::DateTime<chrono::Utc>,
+ pub updated_at: chrono::DateTime<chrono::Utc>,
+ pub deleted_at: Option<chrono::DateTime<chrono::Utc>>,
+ /// message mentions formatted as `{ENTITY_TYPE}:{ENTITY_ID}`
+ pub mentions: Vec<String>,
+}
+
+#[derive(Debug, ToSchema, Doppleganger, Serialize)]
+#[dg(backward = models_comms::channel::Activity)]
+pub struct ApiActivity {
+ pub id: Uuid,
+ pub user_id: String,
+ #[schema(value_type = Uuid)]
+ pub channel_id: ChannelId,
+ pub created_at: chrono::DateTime<chrono::Utc>,
+ pub updated_at: chrono::DateTime<chrono::Utc>,
+ /// the last time the user viewed the channel
+ pub viewed_at: Option<chrono::DateTime<chrono::Utc>>,
+ /// the last time the user intereacted with the channel
+ /// eg. reacting, replying, sending a message
+ pub interacted_at: Option<chrono::DateTime<chrono::Utc>>,
+}
diff --git a/rust/cloud-storage/comms/src/lib.rs b/rust/cloud-storage/comms/src/lib.rs
index f76105df0f..5702002c94 100644
--- a/rust/cloud-storage/comms/src/lib.rs
+++ b/rust/cloud-storage/comms/src/lib.rs
@@ -1,5 +1,5 @@
pub mod domain;
-#[cfg(feature = "inbound")]
+#[cfg(any(feature = "inbound", feature = "attachment"))]
pub mod inbound;
#[cfg(feature = "outbound")]
pub mod outbound;
diff --git a/rust/cloud-storage/comms/src/outbound/postgres/comms_repo.rs b/rust/cloud-storage/comms/src/outbound/postgres/comms_repo.rs
index 2b8bab9572..5a6e320843 100644
--- a/rust/cloud-storage/comms/src/outbound/postgres/comms_repo.rs
+++ b/rust/cloud-storage/comms/src/outbound/postgres/comms_repo.rs
@@ -318,6 +318,68 @@ pub async fn get_activities(
.await?)
}
+#[tracing::instrument(skip(db), err)]
+pub async fn get_channel_name(
+ db: &PgPool,
+ channel_id: ChannelId,
+) -> Result<Option<String>, sqlx::Error> {
+ sqlx::query_scalar!(
+ "SELECT name FROM comms_channels WHERE id = $1",
+ channel_id.0
+ )
+ .fetch_optional(db)
+ .await
+ .map(|row| row.flatten())
+}
+
+#[tracing::instrument(skip(db), err)]
+pub async fn get_recent_messages(
+ db: &PgPool,
+ channel_id: ChannelId,
+ limit: u32,
+) -> Result<Vec<ChannelMessage>, sqlx::Error> {
+ sqlx::query!(
+ r#"
+ SELECT
+ m.id AS "message_id!",
+ m.thread_id,
+ m.sender_id AS "sender_id!",
+ m.content AS "content!",
+ m.created_at AS "created_at!",
+ m.updated_at AS "updated_at!",
+ m.deleted_at::timestamptz AS "deleted_at?",
+ COALESCE(
+ ARRAY(
+ SELECT entity_type || ':' || entity_id
+ FROM comms_entity_mentions em
+ WHERE em.source_entity_type = 'message'
+ AND em.source_entity_id = m.id::text
+ ),
+ '{}'::text[]
+ ) AS "mentions!"
+ FROM comms_messages m
+ WHERE m.channel_id = $1
+ AND m.deleted_at IS NULL
+ ORDER BY m.created_at DESC
+ LIMIT $2
+ "#,
+ channel_id.0,
+ i64::from(limit)
+ )
+ .map(|row| ChannelMessage {
+ message_id: row.message_id,
+ thread_id: row.thread_id,
+ sender_id: row.sender_id,
+ content: row.content,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ deleted_at: row.deleted_at,
+ mentions: row.mentions,
+ })
+ .fetch_all(db)
+ .await
+}
+
pub struct PgCommsRepo {
pool: readonly_pool::ReadOnlyPool,
}
@@ -352,4 +414,19 @@ impl CommsRepo for PgCommsRepo {
) -> Result<Vec<models_comms::channel::Activity>, rootcause::Report> {
get_activities(&self.pool.0, user_id).await
}
+
+ async fn get_channel_name(
+ &self,
+ channel_id: ChannelId,
+ ) -> Result<Option<String>, rootcause::Report> {
+ Ok(get_channel_name(&self.pool.0, channel_id).await?)
+ }
+
+ async fn get_recent_messages(
+ &self,
+ channel_id: ChannelId,
+ limit: u32,
+ ) -> Result<Vec<ChannelMessage>, rootcause::Report> {
+ Ok(get_recent_messages(&self.pool.0, channel_id, limit).await?)
+ }
}
diff --git a/rust/cloud-storage/documents/Cargo.toml b/rust/cloud-storage/documents/Cargo.toml
index 8085d6b9fa..ff70e99e7d 100644
--- a/rust/cloud-storage/documents/Cargo.toml
+++ b/rust/cloud-storage/documents/Cargo.toml
@@ -5,6 +5,14 @@ publish = false
version = "0.1.0"
[features]
+attachment = [
+ "dep:attachment",
+ "dep:ai",
+ "dep:lexical_client",
+ "dep:model_file_type",
+ "dep:reqwest",
+ "ports",
+]
ai_tools = [
"dep:ai",
"dep:async-trait",
@@ -96,6 +104,10 @@ reqwest = { workspace = true, optional = true }
schemars = { workspace = true, optional = true }
sha2 = { workspace = true, optional = true }
+# Attachment
+attachment = { path = "../attachment", optional = true }
+non_empty = { path = "../non_empty" }
+
[dev-dependencies]
dotenvy = { workspace = true }
http-body-util = { workspace = true }
diff --git a/rust/cloud-storage/documents/src/inbound.rs b/rust/cloud-storage/documents/src/inbound.rs
index 97b86a8e0b..ef096e9204 100644
--- a/rust/cloud-storage/documents/src/inbound.rs
+++ b/rust/cloud-storage/documents/src/inbound.rs
@@ -5,3 +5,6 @@ pub mod axum_router;
#[cfg(feature = "ai_tools")]
pub mod toolset;
+
+#[cfg(feature = "attachment")]
+pub mod attachment;
diff --git a/rust/cloud-storage/documents/src/inbound/attachment/markdown.rs b/rust/cloud-storage/documents/src/inbound/attachment/markdown.rs
new file mode 100644
index 0000000000..b8c7102bc7
--- /dev/null
+++ b/rust/cloud-storage/documents/src/inbound/attachment/markdown.rs
@@ -0,0 +1,108 @@
+//! Markdown document resolution via the lexical client.
+
+use ai::types::ImageData;
+use attachment::{
+ AttachmentContent, AttachmentError, AttachmentPart, AttachmentReference, ResolutionError,
+};
+use entity_access::domain::ports::EntityAccessService;
+use futures::future::join_all;
+use lexical_client::types::NewMdNode;
+use macro_user_id::user_id::MacroUserIdStr;
+use model::document::DocumentBasic;
+use model_entity::EntityType;
+use non_empty::NonEmpty;
+
+use crate::domain::ports::DocumentService;
+
+use super::service::DocumentAttachmentService;
+
+/// Resolve a markdown document into an [`AttachmentContent`] with interleaved
+/// text and image parts.
+pub(super) async fn resolve_markdown<DSvc: DocumentService, ESvc: EntityAccessService>(
+ svc: &DocumentAttachmentService<DSvc, ESvc>,
+ user_id: &MacroUserIdStr<'_>,
+ id: &str,
+ document: &DocumentBasic,
+) -> Result<AttachmentContent, AttachmentError> {
+ let response = svc
+ .lexical_client
+ .parse_cognition_v2(id)
+ .await
+ .map_err(AttachmentError::Internal)?;
+
+ let parts = join_all(response.data.into_iter().map(|node| async {
+ match node {
+ NewMdNode::Generic(n) => AttachmentPart::Content(n.content),
+ NewMdNode::DssImage { id } => resolve_dss_image(svc, user_id, &id).await,
+ NewMdNode::StaticImage { url } => resolve_static_image(&url).await,
+ }
+ }))
+ .await;
+
+ let content = NonEmpty::new(parts).map_err(|_| AttachmentError::NoContent)?;
+
+ Ok(AttachmentContent {
+ reference: AttachmentReference::DssFile { id: id.to_string() },
+ name: Some(document.document_name.clone()),
+ content,
+ })
+}
+
+async fn resolve_dss_image<DSvc: DocumentService, ESvc: EntityAccessService>(
+ svc: &DocumentAttachmentService<DSvc, ESvc>,
+ user_id: &MacroUserIdStr<'_>,
+ image_id: &str,
+) -> AttachmentPart {
+ let reference = AttachmentReference::DssFile {
+ id: image_id.to_string(),
+ };
+ let result = try_resolve_dss_image(svc, user_id, image_id)
+ .await
+ .map(|data| AttachmentContent {
+ reference,
+ name: None,
+ content: NonEmpty::new(vec![AttachmentPart::Image(data)]).expect("single element"),
+ })
+ .map_err(|error| ResolutionError::new(image_id.to_string(), error));
+ AttachmentPart::Child(Box::new(result))
+}
+
+async fn try_resolve_dss_image<DSvc: DocumentService, ESvc: EntityAccessService>(
+ svc: &DocumentAttachmentService<DSvc, ESvc>,
+ user_id: &MacroUserIdStr<'_>,
+ image_id: &str,
+) -> Result<ImageData, AttachmentError> {
+ let receipt = svc
+ .entity_access_service
+ .generate_entity_access_receipt(user_id, None, image_id, EntityType::Document)
+ .await
+ .map_err(|e| AttachmentError::Internal(e.into()))?;
+
+ let document = svc
+ .document_service
+ .internal_get_basic_document(image_id)
+ .await
+ .map_err(|e| AttachmentError::Internal(e.into()))?;
+
+ svc.get_image_from_location(&document, receipt).await
+}
+
+async fn resolve_static_image(url: &str) -> AttachmentPart {
+ let reference = AttachmentReference::SfsImage {
+ url: url.to_string(),
+ };
+ let result = try_resolve_static_image(url)
+ .await
+ .map(|data| AttachmentContent {
+ reference,
+ name: None,
+ content: NonEmpty::new(vec![AttachmentPart::Image(data)]).expect("single element"),
+ })
+ .map_err(|error| ResolutionError::new(url.to_string(), error));
+ AttachmentPart::Child(Box::new(result))
+}
+
+async fn try_resolve_static_image(url: &str) -> Result<ImageData, AttachmentError> {
+ let bytes = super::service::fetch_url_bytes(url).await?;
+ ImageData::try_from_bytes(bytes).map_err(AttachmentError::Internal)
+}
diff --git a/rust/cloud-storage/documents/src/inbound/attachment/mod.rs b/rust/cloud-storage/documents/src/inbound/attachment/mod.rs
new file mode 100644
index 0000000000..75fe8e0203
--- /dev/null
+++ b/rust/cloud-storage/documents/src/inbound/attachment/mod.rs
@@ -0,0 +1,6 @@
+//! Attachment inbound adapter for the documents domain.
+
+mod markdown;
+mod service;
+
+pub use service::DocumentAttachmentService;
diff --git a/rust/cloud-storage/documents/src/inbound/attachment/service.rs b/rust/cloud-storage/documents/src/inbound/attachment/service.rs
new file mode 100644
index 0000000000..361cc504bd
--- /dev/null
+++ b/rust/cloud-storage/documents/src/inbound/attachment/service.rs
@@ -0,0 +1,193 @@
+//! [`AttachmentService`] implementation for documents.
+
+use std::str::FromStr;
+use std::sync::Arc;
+
+use ai::types::ImageData;
+use attachment::{
+ AttachmentContent, AttachmentError, AttachmentPart, AttachmentReference, AttachmentService,
+ Attachments, ResolutionError,
+};
+use entity_access::domain::{
+ models::{EntityAccessReceipt, ViewAccessLevel},
+ ports::EntityAccessService,
+};
+use futures::future::join_all;
+use lexical_client::LexicalClient;
+use macro_user_id::user_id::MacroUserIdStr;
+use model::document::DocumentBasic;
+use model_entity::EntityType;
+use model_file_type::{FileAssociation, FileType};
+use non_empty::NonEmpty;
+
+use crate::domain::{models::LocationQueryParams, ports::DocumentService};
+
+use super::markdown;
+
+/// Resolves document IDs into [`Attachments`].
+pub struct DocumentAttachmentService<DSvc, ESvc> {
+ pub(super) document_service: Arc<DSvc>,
+ pub(super) entity_access_service: Arc<ESvc>,
+ pub(super) lexical_client: Arc<LexicalClient>,
+}
+
+impl<DSvc, ESvc> DocumentAttachmentService<DSvc, ESvc> {
+ /// Create a new document attachment service.
+ pub fn new(
+ document_service: Arc<DSvc>,
+ entity_access_service: Arc<ESvc>,
+ lexical_client: Arc<LexicalClient>,
+ ) -> Self {
+ Self {
+ document_service,
+ entity_access_service,
+ lexical_client,
+ }
+ }
+}
+
+impl<DSvc: DocumentService, ESvc: EntityAccessService> AttachmentService
+ for DocumentAttachmentService<DSvc, ESvc>
+{
+ #[tracing::instrument(skip_all)]
+ async fn resolve_attachments(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ ids: NonEmpty<&[&str]>,
+ ) -> Attachments {
+ let user_id = &user_id;
+ let results = join_all(ids.iter().map(|id| async move {
+ self.resolve_one(user_id, id)
+ .await
+ .map_err(|error| ResolutionError::new(id.to_string(), error))
+ }))
+ .await;
+
+ Attachments::new(NonEmpty::new(results).expect("ids was non-empty"))
+ }
+}
+
+impl<DSvc: DocumentService, ESvc: EntityAccessService> DocumentAttachmentService<DSvc, ESvc> {
+ #[tracing::instrument(skip(self), err)]
+ async fn resolve_one(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ id: &str,
+ ) -> Result<AttachmentContent, AttachmentError> {
+ let receipt = self
+ .entity_access_service
+ .generate_entity_access_receipt(user_id, None, id, EntityType::Document)
+ .await
+ .map_err(|e| AttachmentError::Internal(e.into()))?;
+
+ let document = self
+ .document_service
+ .internal_get_basic_document(id)
+ .await
+ .map_err(|e| AttachmentError::Internal(e.into()))?;
+
+ let file_type = document
+ .file_type
+ .as_ref()
+ .ok_or(AttachmentError::UnknownFileType)
+ .and_then(|ft| {
+ FileType::from_str(ft).map_err(|_| AttachmentError::UnsupportedFileType(ft.clone()))
+ })?;
+
+ let parts = match file_type.macro_app_path() {
+ FileAssociation::Pdf(_) | FileAssociation::Write(_) => {
+ let text = self
+ .document_service
+ .get_document_text(receipt)
+ .await
+ .map_err(|e| AttachmentError::Internal(e.into()))?;
+ vec![AttachmentPart::Content(text)]
+ }
+ FileAssociation::Md(_) => {
+ return markdown::resolve_markdown(self, user_id, id, &document).await;
+ }
+ FileAssociation::Code(_) | FileAssociation::Document(_) => {
+ let text = self.get_text_from_location(&document, receipt).await?;
+ vec![AttachmentPart::Content(text)]
+ }
+ FileAssociation::Image(_) => {
+ let data = self.get_image_from_location(&document, receipt).await?;
+ vec![AttachmentPart::Image(data)]
+ }
+ _ => return Err(AttachmentError::UnsupportedFileType(file_type.to_string())),
+ };
+
+ Ok(AttachmentContent {
+ reference: AttachmentReference::DssFile { id: id.to_string() },
+ name: Some(document.document_name.clone()),
+ content: NonEmpty::new(parts).expect("parts has one element"),
+ })
+ }
+
+ pub(super) async fn get_text_from_location(
+ &self,
+ document: &DocumentBasic,
+ receipt: EntityAccessReceipt<ViewAccessLevel>,
+ ) -> Result<String, AttachmentError> {
+ let url = self.presigned_url_for(document, receipt).await?;
+ let bytes = fetch_url_bytes(&url).await?;
+ String::from_utf8(bytes).map_err(|e| {
+ AttachmentError::Internal(anyhow::anyhow!("document content is not valid UTF-8: {e}"))
+ })
+ }
+
+ pub(super) async fn get_image_from_location(
+ &self,
+ document: &DocumentBasic,
+ receipt: EntityAccessReceipt<ViewAccessLevel>,
+ ) -> Result<ImageData, AttachmentError> {
+ let url = self.presigned_url_for(document, receipt).await?;
+ let bytes = fetch_url_bytes(&url).await?;
+ ImageData::try_from_bytes(bytes).map_err(AttachmentError::Internal)
+ }
+
+ pub(super) async fn presigned_url_for(
+ &self,
+ document: &DocumentBasic,
+ receipt: EntityAccessReceipt<ViewAccessLevel>,
+ ) -> Result<String, AttachmentError> {
+ let location = self
+ .document_service
+ .get_document_location(
+ document,
+ receipt,
+ LocationQueryParams {
+ get_converted_docx_url: Some(true),
+ document_version_id: None,
+ },
+ )
+ .await
+ .map_err(|e| AttachmentError::Internal(e.into()))?;
+
+ match location {
+ model::document::response::LocationResponseV3::PresignedUrl {
+ presigned_url, ..
+ } => Ok(presigned_url),
+ _ => Err(AttachmentError::Internal(anyhow::anyhow!(
+ "unexpected location response for document"
+ ))),
+ }
+ }
+}
+
+pub(super) async fn fetch_url_bytes(url: &str) -> Result<Vec<u8>, AttachmentError> {
+ let response = reqwest::get(url)
+ .await
+ .map_err(|e| AttachmentError::Internal(e.into()))?;
+ if !response.status().is_success() {
+ return Err(AttachmentError::Internal(anyhow::anyhow!(
+ "failed to fetch {url}: HTTP {}",
+ response.status()
+ )));
+ }
+ response
+ .bytes()
+ .await
+ .map(|b| b.to_vec())
+ .map_err(|e| AttachmentError::Internal(e.into()))
+}
diff --git a/rust/cloud-storage/documents/src/lib.rs b/rust/cloud-storage/documents/src/lib.rs
index 4cafcec210..6c4a1f28a9 100644
--- a/rust/cloud-storage/documents/src/lib.rs
+++ b/rust/cloud-storage/documents/src/lib.rs
@@ -12,7 +12,7 @@
pub mod domain;
-#[cfg(any(feature = "inbound", feature = "ai_tools"))]
+#[cfg(any(feature = "inbound", feature = "ai_tools", feature = "attachment"))]
pub mod inbound;
#[cfg(feature = "outbound")]
diff --git a/rust/cloud-storage/email/Cargo.toml b/rust/cloud-storage/email/Cargo.toml
index 33501e32fb..2f57d2f12c 100644
--- a/rust/cloud-storage/email/Cargo.toml
+++ b/rust/cloud-storage/email/Cargo.toml
@@ -12,6 +12,11 @@ all = [
"outbound",
"ports",
]
+attachment = [
+ "dep:attachment",
+ "dep:non_empty",
+ "ports",
+]
ai_schema = ["dep:schemars"]
ai_tools = [
"dep:ai",
@@ -35,6 +40,7 @@ ports = ["dep:tokio", "frecency/ports"]
[dependencies]
ai = { path = "../ai", optional = true }
+attachment = { path = "../attachment", optional = true }
anyhow = { workspace = true }
async-trait = { workspace = true, optional = true }
base64 = { workspace = true }
@@ -53,6 +59,7 @@ item_filters = { path = "../item_filters" }
macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
model-entity = { path = "../model-entity" }
+non_empty = { path = "../non_empty", optional = true }
model-error-response = { path = "../model-error-response", optional = true }
model_user = { path = "../model_user", optional = true }
models_pagination = { path = "../models_pagination" }
diff --git a/rust/cloud-storage/email/src/domain/models/attachment.rs b/rust/cloud-storage/email/src/domain/models/attachment.rs
index ad5389d67a..1137534818 100644
--- a/rust/cloud-storage/email/src/domain/models/attachment.rs
+++ b/rust/cloud-storage/email/src/domain/models/attachment.rs
@@ -6,6 +6,7 @@ use uuid::Uuid;
#[non_exhaustive]
pub struct Attachment {
pub id: Uuid,
+ #[allow(unused)]
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 -
diff --git a/rust/cloud-storage/email/src/domain/models/contact.rs b/rust/cloud-storage/email/src/domain/models/contact.rs
index 62139e6941..5f9f299481 100644
--- a/rust/cloud-storage/email/src/domain/models/contact.rs
+++ b/rust/cloud-storage/email/src/domain/models/contact.rs
@@ -4,6 +4,7 @@ use uuid::Uuid;
#[non_exhaustive]
pub struct Contact {
pub id: Uuid,
+ #[allow(unused)]
pub(crate) thread_id: Uuid,
pub link_id: Uuid,
pub name: Option<String>,
diff --git a/rust/cloud-storage/email/src/domain/models/label.rs b/rust/cloud-storage/email/src/domain/models/label.rs
index 1809482aaf..c2e13e9eb7 100644
--- a/rust/cloud-storage/email/src/domain/models/label.rs
+++ b/rust/cloud-storage/email/src/domain/models/label.rs
@@ -23,6 +23,7 @@ pub enum LabelType {
#[derive(Debug, Clone)]
pub struct Label {
pub id: Uuid,
+ #[allow(unused)]
pub(crate) thread_id: Uuid,
pub link_id: Uuid,
pub provider_label_id: String,
diff --git a/rust/cloud-storage/email/src/inbound.rs b/rust/cloud-storage/email/src/inbound.rs
index fedd10c42c..5f34c389b1 100644
--- a/rust/cloud-storage/email/src/inbound.rs
+++ b/rust/cloud-storage/email/src/inbound.rs
@@ -1,3 +1,6 @@
+#[cfg(feature = "attachment")]
+pub mod attachment;
+
#[cfg(feature = "axum")]
mod axum;
diff --git a/rust/cloud-storage/email/src/inbound/attachment.rs b/rust/cloud-storage/email/src/inbound/attachment.rs
new file mode 100644
index 0000000000..2198232137
--- /dev/null
+++ b/rust/cloud-storage/email/src/inbound/attachment.rs
@@ -0,0 +1,172 @@
+//! Attachment inbound adapter for the email domain.
+
+use std::sync::Arc;
+
+use attachment::{
+ AttachmentContent, AttachmentError, AttachmentPart, AttachmentReference, AttachmentService,
+ Attachments, ResolutionError,
+};
+use entity_access::domain::{
+ models::{EntityType, ViewAccessLevel},
+ ports::EntityAccessService,
+};
+use futures::future::join_all;
+use macro_user_id::user_id::MacroUserIdStr;
+use non_empty::NonEmpty;
+use uuid::Uuid;
+
+use crate::domain::{
+ models::{ContactInfo, ParsedMessage, ParsedThread},
+ ports::EmailService,
+};
+
+const MAX_MESSAGES: i64 = 50;
+
+/// Resolves email thread IDs into [`Attachments`].
+pub struct EmailAttachmentService<Svc, ESvc> {
+ service: Arc<Svc>,
+ entity_access_service: Arc<ESvc>,
+}
+
+impl<Svc, ESvc> EmailAttachmentService<Svc, ESvc> {
+ /// Create a new email attachment service.
+ pub fn new(service: Arc<Svc>, entity_access_service: Arc<ESvc>) -> Self {
+ Self {
+ service,
+ entity_access_service,
+ }
+ }
+}
+
+impl<Svc: EmailService, ESvc: EntityAccessService> AttachmentService
+ for EmailAttachmentService<Svc, ESvc>
+{
+ #[tracing::instrument(skip_all)]
+ async fn resolve_attachments(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ ids: NonEmpty<&[&str]>,
+ ) -> Attachments {
+ let user_id = &user_id;
+ let results = join_all(ids.iter().map(|id| async move {
+ self.resolve_one(user_id, id)
+ .await
+ .map_err(|error| ResolutionError::new(id.to_string(), error))
+ }))
+ .await;
+
+ Attachments::new(NonEmpty::new(results).expect("ids was non-empty"))
+ }
+}
+
+impl<Svc: EmailService, ESvc: EntityAccessService> EmailAttachmentService<Svc, ESvc> {
+ #[tracing::instrument(skip(self), err)]
+ async fn resolve_one(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ id: &str,
+ ) -> Result<AttachmentContent, AttachmentError> {
+ let thread_id = Uuid::parse_str(id)
+ .map_err(|e| AttachmentError::Internal(anyhow::anyhow!("invalid thread ID: {e}")))?;
+
+ let receipt = self
+ .entity_access_service
+ .generate_entity_access_receipt::<ViewAccessLevel>(
+ user_id,
+ None,
+ id,
+ EntityType::EmailThread,
+ )
+ .await
+ .map_err(|_| AttachmentError::PermissionDenied { id: id.to_string() })?;
+
+ let thread = self
+ .service
+ .get_thread_parsed(receipt, 0, MAX_MESSAGES)
+ .await
+ .map_err(|e| AttachmentError::Internal(e.into()))?
+ .ok_or_else(|| {
+ AttachmentError::Internal(anyhow::anyhow!("thread {thread_id} not found"))
+ })?;
+
+ format_thread(id, &thread)
+ }
+}
+
+fn format_thread(id: &str, thread: &ParsedThread) -> Result<AttachmentContent, AttachmentError> {
+ let subject = thread
+ .messages
+ .first()
+ .and_then(|m| m.subject.as_deref())
+ .map(String::from);
+
+ let parts: Vec<AttachmentPart> = thread.messages.iter().flat_map(format_message).collect();
+
+ let content = NonEmpty::new(parts).map_err(|_| AttachmentError::NoContent)?;
+
+ Ok(AttachmentContent {
+ reference: AttachmentReference::EmailThread { id: id.to_string() },
+ name: subject,
+ content,
+ })
+}
+
+fn format_message(msg: &ParsedMessage) -> Vec<AttachmentPart> {
+ let mut parts = Vec::new();
+
+ if let Some(subject) = &msg.subject {
+ parts.push(AttachmentPart::Metadata {
+ key: "subject".to_string(),
+ value: subject.clone(),
+ });
+ }
+
+ if let Some(from) = &msg.from {
+ parts.push(AttachmentPart::Metadata {
+ key: "from".to_string(),
+ value: format_contact(from),
+ });
+ }
+
+ if !msg.to.is_empty() {
+ parts.push(AttachmentPart::Metadata {
+ key: "to".to_string(),
+ value: format_contacts(&msg.to),
+ });
+ }
+
+ if !msg.cc.is_empty() {
+ parts.push(AttachmentPart::Metadata {
+ key: "cc".to_string(),
+ value: format_contacts(&msg.cc),
+ });
+ }
+
+ if let Some(date) = msg.internal_date_ts {
+ parts.push(AttachmentPart::Metadata {
+ key: "date".to_string(),
+ value: date.to_rfc3339(),
+ });
+ }
+
+ if let Some(body) = &msg.body_parsed {
+ parts.push(AttachmentPart::Content(body.clone()));
+ }
+
+ parts
+}
+
+fn format_contact(contact: &ContactInfo) -> String {
+ match &contact.name {
+ Some(name) => format!("{name} <{}>", contact.email),
+ None => contact.email.clone(),
+ }
+}
+
+fn format_contacts(contacts: &[ContactInfo]) -> String {
+ contacts
+ .iter()
+ .map(format_contact)
+ .collect::<Vec<_>>()
+ .join(", ")
+}