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: kill scribe (#2981)

Eric Hayes6c3dd830524c
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index e335c26f14..d158d08e34 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -102,7 +102,6 @@ dependencies = [
"connection",
"cool_asserts",
"dateparser",
- "document_storage_service_client",
"documents",
"email",
"email_service_client",
@@ -135,7 +134,6 @@ dependencies = [
"remote_env_var",
"rootcause",
"schemars",
- "scribe",
"search_service_client",
"secretsmanager_client",
"serde",
@@ -143,7 +141,6 @@ dependencies = [
"soup",
"sqlx",
"sqs_client",
- "static_file_service_client",
"strum",
"sync_service_client",
"tokio",
@@ -3095,6 +3092,7 @@ dependencies = [
"chat",
"chrono",
"comms",
+ "comms_db_client",
"comms_service_client",
"connection_gateway",
"cookie",
@@ -3142,7 +3140,6 @@ dependencies = [
"reqwest",
"roles_and_permissions",
"schemars",
- "scribe",
"search_service_client",
"secretsmanager_client",
"serde",
@@ -3151,7 +3148,6 @@ dependencies = [
"sqlx",
"sqs_client",
"static_file",
- "static_file_service_client",
"stream",
"strum",
"sync_service_client",
@@ -6518,7 +6514,6 @@ dependencies = [
"call",
"chat",
"comms",
- "document_storage_service_client",
"documents",
"email",
"email_service_client",
@@ -6540,14 +6535,12 @@ dependencies = [
"readonly_pool",
"redis",
"rmcp",
- "scribe",
"search_service_client",
"secretsmanager_client",
"serde_json",
"soup",
"sqlx",
"sqs_client",
- "static_file_service_client",
"sync_service_client",
"tokio",
"tracing",
@@ -6581,7 +6574,6 @@ dependencies = [
"call",
"chrono",
"comms",
- "document_storage_service_client",
"documents",
"email",
"email_service_client",
@@ -6600,14 +6592,12 @@ dependencies = [
"model_user",
"properties",
"readonly_pool",
- "scribe",
"search_service_client",
"serde",
"serde_json",
"soup",
"sqlx",
"sqs_client",
- "static_file_service_client",
"sync_service_client",
"thiserror 2.0.17",
"tokio",
@@ -9586,49 +9576,6 @@ dependencies = [
"tendril",
]
-[[package]]
-name = "scribe"
-version = "0.1.0"
-dependencies = [
- "ai",
- "ai_format",
- "anyhow",
- "attachment",
- "base64 0.22.1",
- "bytes",
- "chat",
- "chrono",
- "comms_db_client",
- "derive_builder",
- "document_storage_service_client",
- "doppleganger",
- "email_service_client",
- "futures",
- "lexical_client",
- "macro_client_errors",
- "macro_db_client",
- "macro_user_id",
- "model",
- "models_comms",
- "models_dcs",
- "models_email",
- "models_permissions",
- "models_properties",
- "models_sfs",
- "properties_db_client",
- "reqwest",
- "s3_client",
- "serde",
- "serde_json",
- "sqlx",
- "static_file_service_client",
- "sync_service_client",
- "thiserror 2.0.17",
- "tokio",
- "tracing",
- "uuid",
-]
-
[[package]]
name = "sct"
version = "0.7.1"
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index 4019acea3c..d7bc2e5bb8 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -116,7 +116,6 @@ members = [
"rpc/axum_rpc_parse",
"s3_client",
"s3_key",
- "scribe",
"scheduled_action",
"search_processing_service",
"search_service",
diff --git a/rust/cloud-storage/ai_tools/Cargo.toml b/rust/cloud-storage/ai_tools/Cargo.toml
index 6f4b248b5e..b1e384ba38 100644
--- a/rust/cloud-storage/ai_tools/Cargo.toml
+++ b/rust/cloud-storage/ai_tools/Cargo.toml
@@ -27,7 +27,6 @@ comms = { path = "../comms", features = ["outbound"] }
connection = { path = "../connection", default-features = false, features = [
"ports",
] }
-document_storage_service_client = { path = "../document_storage_service_client" }
documents = { path = "../documents", features = ["ai_tools"] }
email = { path = "../email", features = ["ai_schema", "ai_tools", "axum", "outbound"] }
email_service_client = { path = "../email_service_client" }
@@ -56,13 +55,6 @@ rand.workspace = true
readonly_pool = { path = "../readonly_pool" }
rootcause = { workspace = true }
schemars.workspace = true
-scribe = { path = "../scribe", features = [
- "channel",
- "dcs",
- "document",
- "email",
- "static_file",
-] }
search_service_client = { path = "../search_service_client" }
serde.workspace = true
serde_json.workspace = true
@@ -70,7 +62,6 @@ properties = { path = "../properties", features = ["ai_tools"] }
soup = { path = "../soup", features = ["ai_tools", "outbound"] }
sqs_client = { path = "../sqs_client", default-features = false, features = ["email", "gmail"] }
sqlx.workspace = true
-static_file_service_client = { path = "../static_file_service_client" }
strum.workspace = true
sync_service_client = { path = "../sync_service_client" }
tokio.workspace = true
diff --git a/rust/cloud-storage/ai_tools/src/build_context.rs b/rust/cloud-storage/ai_tools/src/build_context.rs
index 0ac08c96d6..79802ae35f 100644
--- a/rust/cloud-storage/ai_tools/src/build_context.rs
+++ b/rust/cloud-storage/ai_tools/src/build_context.rs
@@ -12,7 +12,6 @@ use anyhow::Context;
use comms::domain::service::ChannelServiceImpl;
use comms::outbound::postgres::comms_repo::PgCommsRepo;
use comms::outbound::postgres::user_repo::PgUserRepo;
-use document_storage_service_client::DocumentStorageServiceClient;
use documents::domain::models::CloudFrontConfig;
use documents::inbound::toolset::DocumentToolContext;
use documents::outbound::pg_document_repo::PgDocumentRepo;
@@ -20,7 +19,7 @@ use documents::outbound::s3_upload_url::S3UploadUrlAdapter;
use email::domain::ports::ReadonlyEmailPreviewAdapter;
use email::domain::service::EmailServiceImpl;
use email::outbound::EmailPgRepo;
-use email_service_client::{EmailServiceClient, EmailServiceClientExternal};
+use email_service_client::EmailServiceClientExternal;
use entity_access::domain::service::EntityAccessServiceImpl;
use entity_access::outbound::PgAccessRepository;
use frecency::domain::services::FrecencyQueryServiceImpl;
@@ -29,13 +28,10 @@ use lexical_client::LexicalClient;
use macro_env::Environment;
use macro_env_var::{env_var, maybe_env_var};
use readonly_pool::ReadOnlyPool;
-use scribe::ScribeClient;
-use scribe::document::DocumentClient;
use search_service_client::SearchServiceClient;
use secretsmanager_client::{SecretManager, SecretsManager};
use soup::domain::service::SoupImpl;
use soup::outbound::pg_soup_repo::PgSoupRepo;
-use static_file_service_client::StaticFileServiceClient;
use std::sync::Arc;
use sync_service_client::SyncServiceClient;
@@ -125,10 +121,6 @@ pub async fn build_tool_service_context_from_env(
.as_ref()
.to_string();
- let dss_client = Arc::new(DocumentStorageServiceClient::new(
- internal_api_secret_key.to_string(),
- env.document_storage_service_url.to_string(),
- ));
let search_client = Arc::new(SearchServiceClient::new(
internal_api_secret_key.to_string(),
env.search_service_url.to_string(),
@@ -137,35 +129,11 @@ pub async fn build_tool_service_context_from_env(
sync_service_auth_key.clone(),
env.sync_service_url.to_string(),
));
- let email_client = Arc::new(EmailServiceClient::new(
- internal_api_secret_key.to_string(),
- env.email_service_url.to_string(),
- ));
- let sfs_client = Arc::new(StaticFileServiceClient::new(
- internal_api_secret_key.to_string(),
- env.static_file_service_url.to_string(),
- ));
let email_ext_client = Arc::new(EmailServiceClientExternal::new(
env.email_service_url.to_string(),
));
let lexical_client = LexicalClient::new(sync_service_auth_key, lexical_service_url.to_string());
- let scribe = Arc::new(
- ScribeClient::new()
- .with_document_client(
- DocumentClient::builder()
- .with_dss_client(dss_client.clone())
- .with_lexical_client(Arc::new(lexical_client.clone()))
- .with_sync_service_client(sync_client.clone())
- .with_macro_db(pool.clone())
- .build(),
- )
- .with_channel_client(pool.clone())
- .with_dcs_client(pool.clone())
- .with_email_client(email_client)
- .with_static_file_client(sfs_client),
- );
-
let frecency_storage = FrecencyPgStorage::new(pool.clone());
let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());
let email_service = EmailServiceImpl::new(
@@ -287,7 +255,6 @@ pub async fn build_tool_service_context_from_env(
Ok(ToolServiceContext {
search_service_client: search_client,
email_service_client: email_ext_client,
- scribe,
soup_service,
email_service: email_service_for_tools,
document_tool_context,
diff --git a/rust/cloud-storage/ai_tools/src/rewrite/tool.rs b/rust/cloud-storage/ai_tools/src/rewrite/tool.rs
deleted file mode 100644
index d7c558d137..0000000000
--- a/rust/cloud-storage/ai_tools/src/rewrite/tool.rs
+++ /dev/null
@@ -1,95 +0,0 @@
-use super::types::AIDiffResponse;
-use super::types::{PROMPT, REWRITE_MODEL};
-use crate::tool_context::ToolScribe;
-use ai::types::{MessageBuilder, RequestBuilder};
-use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
-use anyhow::Error;
-use async_trait::async_trait;
-use model::document::FileType;
-use schemars::JsonSchema;
-use serde::Deserialize;
-use std::sync::Arc;
-
-#[derive(Deserialize, JsonSchema, Debug, Clone)]
-#[schemars(
- description = "Instruct an agent to edit a markdown file identified by an id.
- This tool should be used when the user include a markdown file in context and requests a revision or edit to that file"
-)]
-pub struct MarkdownRewrite {
- #[schemars(
- description = "The markdown file id to target for editing. This file id will be in your context and labeled as a markdown (md) document"
- )]
- pub markdown_file_id: String,
- #[schemars(
- description = "Instructions for the revision agent to follow to edit the markdown. These instructions will be provided by the user."
- )]
- pub instructions: String,
-}
-
-#[async_trait]
-impl AsyncTool<Arc<ToolScribe>> for MarkdownRewrite {
- type Output = AIDiffResponse;
-
- #[tracing::instrument(skip_all, fields(user_id=?(*request_context.user_id).as_ref()), err)]
- async fn call(
- &self,
- scribe: ServiceContext<Arc<ToolScribe>>,
- request_context: RequestContext,
- ) -> ToolResult<Self::Output> {
- tracing::info!(markdown_file_id=?self.markdown_file_id, "Rewrite params");
-
- rewrite_markdown(self.clone(), &scribe)
- .await
- .map_err(|err| ToolCallError {
- description: "An internal error occured rewriting generating rewrite".into(),
- internal_error: err,
- })
- }
-}
-
-pub async fn rewrite_markdown(
- request: MarkdownRewrite,
- scribe: &ToolScribe,
-) -> Result<AIDiffResponse, Error> {
- let document = scribe
- .document
- .fetch(request.markdown_file_id.clone())
- .document_content()
- .await?;
- if document.file_type() != FileType::Md {
- Err(anyhow::anyhow!("expected markdown"))
- } else {
- let name = document.metadata().document_name.clone();
- let md_text = document.content.text_content()?;
- generate_patches(request, md_text, name).await
- }
-}
-
-pub async fn generate_patches(
- request: MarkdownRewrite,
- markdown_text: String,
- file_name: String,
-) -> Result<AIDiffResponse, Error> {
- let attachment_content = attachment::AttachmentContent {
- reference: model_entity::EntityType::Document.with_entity_string(request.markdown_file_id),
- name: Some(file_name),
- content: non_empty::NonEmpty::one(attachment::AttachmentPart::Content(markdown_text)),
- };
- let attachments =
- attachment::Attachments::new(non_empty::NonEmpty::one(Ok(attachment_content)));
-
- let request = RequestBuilder::new()
- .max_tokens(32_000)
- .system_prompt(PROMPT)
- .model(REWRITE_MODEL)
- .attachments(attachments)
- .messages(vec![
- MessageBuilder::new()
- .content(request.instructions)
- .user()
- .build(),
- ])
- .build();
-
- ai::structured_output_v2::structured_completion_v2::<AIDiffResponse>(request).await
-}
diff --git a/rust/cloud-storage/ai_tools/src/tool_context.rs b/rust/cloud-storage/ai_tools/src/tool_context.rs
index 7ec7f29d6d..e1313e4e4a 100644
--- a/rust/cloud-storage/ai_tools/src/tool_context.rs
+++ b/rust/cloud-storage/ai_tools/src/tool_context.rs
@@ -18,18 +18,11 @@ use email::{
};
use macro_user_id::user_id::MacroUserIdStr;
use properties::inbound::toolset::PropertiesToolContext;
-use scribe::{
- ScribeClient, channel::ChannelClient, dcs::DcsClient, document::DocumentClient,
- email::EmailClient, static_file::StaticFileClient,
-};
use soup::{domain::service::SoupImpl, inbound::toolset::SoupToolContext};
use std::sync::Arc;
pub use ai_toolset::RequestContext;
-pub type ToolScribe =
- ScribeClient<DocumentClient, ChannelClient, DcsClient, EmailClient, StaticFileClient>;
-
/// Type alias for the frecency service implementation
pub type ToolFrecencyService = frecency::domain::services::FrecencyQueryServiceImpl<
frecency::outbound::postgres::FrecencyPgStorage,
@@ -299,7 +292,6 @@ pub fn no_op_schedule_context() -> NoOpScheduleContext {
pub struct ToolServiceContext {
pub search_service_client: Arc<search_service_client::SearchServiceClient>,
pub email_service_client: Arc<email_service_client::EmailServiceClientExternal>,
- pub scribe: Arc<ToolScribe>,
pub soup_service: Arc<ToolSoupService>,
pub email_service: Arc<ToolEmailService>,
pub document_tool_context: ToolDocumentToolContext,
diff --git a/rust/cloud-storage/document_cognition_service/Cargo.toml b/rust/cloud-storage/document_cognition_service/Cargo.toml
index 4a44afba45..801f785d47 100644
--- a/rust/cloud-storage/document_cognition_service/Cargo.toml
+++ b/rust/cloud-storage/document_cognition_service/Cargo.toml
@@ -98,13 +98,7 @@ regex = { workspace = true }
reqwest.workspace = true
roles_and_permissions = { path = "../roles_and_permissions", default-features = false }
schemars = { workspace = true }
-scribe = { path = "../scribe", features = [
- "channel",
- "dcs",
- "document",
- "email",
- "static_file",
-] }
+comms_db_client = { path = "../comms_db_client" }
search_service_client = { path = "../search_service_client" }
secretsmanager_client = { path = "../secretsmanager_client" }
serde = { workspace = true }
@@ -119,7 +113,6 @@ sqs_client = { path = "../sqs_client", default-features = false, features = [
"search",
] }
static_file = { path = "../static_file", features = ["attachment"] }
-static_file_service_client = { path = "../static_file_service_client" }
stream = { path = "../stream" }
strum = { workspace = true }
sync_service_client = { path = "../sync_service_client" }
diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs
index 74c605d167..80f13ea229 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs
@@ -21,10 +21,6 @@ use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
use notification::domain::service::SqsNotificationIngress;
use notification::outbound::queue::SqsQueue;
-use scribe::{
- ScribeClient, channel::ChannelClient, dcs::DcsClient, document::DocumentClient,
- email::EmailClient, static_file::StaticFileClient,
-};
use search_service_client::SearchServiceClient;
use secretsmanager_client::LocalOrRemoteSecret;
use sqlx::PgPool;
@@ -53,9 +49,6 @@ mod test;
#[cfg(test)]
pub use test::*;
-pub type DcsScribe =
- ScribeClient<DocumentClient, ChannelClient, DcsClient, EmailClient, StaticFileClient>;
-
pub(crate) type NotificationIngressType = SqsNotificationIngress<SqsQueue>;
pub type DcsMemoryService =
@@ -68,7 +61,6 @@ pub struct ApiContext {
pub document_storage_client: Arc<DocumentStorageServiceClient>,
pub comms_service_client: Arc<comms_service_client::CommsServiceClient>,
pub search_service_client: Arc<SearchServiceClient>,
- pub scribe: Arc<DcsScribe>,
pub email_service_client_external: Arc<email_service_client::EmailServiceClientExternal>,
pub jwt_args: JwtValidationArgs,
pub config: Arc<Config>,
diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
index 2758f0bbf7..fa41e58dff 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
@@ -112,7 +112,6 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
use comms::outbound::postgres::comms_repo::PgCommsRepo;
use comms::outbound::postgres::user_repo::PgUserRepo;
use comms_service_client::CommsServiceClient;
- use document_cognition_service_client::DocumentCognitionServiceClient;
use document_storage_service_client::DocumentStorageServiceClient;
use email::domain::ports::ReadonlyEmailPreviewAdapter;
use email::domain::service::EmailServiceImpl;
@@ -123,12 +122,10 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
use lexical_client::LexicalClient;
use notification::domain::service::SqsNotificationIngress;
use notification::outbound::queue::SqsQueue;
- use scribe::ScribeClient;
use search_service_client::SearchServiceClient;
use soup::domain::service::SoupImpl;
use soup::outbound::pg_soup_repo::PgSoupRepo;
use sqs_client::SQS;
- use static_file_service_client::StaticFileServiceClient;
use sync_service_client::SyncServiceClient;
let sqs_config = aws_sdk_sqs::Config::builder()
@@ -144,10 +141,6 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
let comms_service_client = Arc::new(CommsServiceClient::new("http://localhost".into()));
let search_service_client =
SearchServiceClient::new("dummy_auth_key".into(), "http://localhost".into());
- let lexical_client = Arc::new(LexicalClient::new(
- "test".into(),
- "http://nofileshere".into(),
- ));
let sync_service_client = Arc::new(SyncServiceClient::new(
"dummy_auth_key".into(),
"http://localhost".into(),
@@ -156,33 +149,10 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
"dummy_auth_key".into(),
"http://localhost".into(),
));
- let document_cognition_service_client = Arc::new(DocumentCognitionServiceClient::new(
- "dummy_auth_key".into(),
- "http://localhost".into(),
- ));
- let static_file_service_client = Arc::new(StaticFileServiceClient::new(
- "dummy_auth_key".into(),
- "http://localhost".into(),
- ));
-
let email_service_client_external = Arc::new(EmailServiceClientExternal::new(
email_service_client.url().to_owned(),
));
- let content_client = ScribeClient::new()
- .with_document_client(
- DocumentClient::builder()
- .with_dss_client(document_storage_client.clone())
- .with_lexical_client(lexical_client)
- .with_sync_service_client(sync_service_client.clone())
- .with_macro_db(pool.clone())
- .build(),
- )
- .with_channel_client(pool.clone())
- .with_dcs_client(pool.clone())
- .with_email_client(email_service_client)
- .with_static_file_client(static_file_service_client.clone());
-
// Build soup service dependencies
let frecency_storage = FrecencyPgStorage::new(pool.clone());
let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());
@@ -257,7 +227,6 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
);
let search_service_client = Arc::new(search_service_client);
- let scribe = Arc::new(content_client);
// Build properties tool context
let properties_service = properties::PropertiesServiceImpl::new(
@@ -317,7 +286,6 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
let tool_service_context = ai_tools::ToolServiceContext {
search_service_client: search_service_client.clone(),
email_service_client: email_service_client_external.clone(),
- scribe: scribe.clone(),
soup_service: soup_service.clone(),
email_service: email_service_for_tools.clone(),
document_tool_context: document_tool_context.clone(),
@@ -346,7 +314,6 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
document_storage_client,
comms_service_client,
search_service_client,
- scribe,
email_service_client_external,
jwt_args: JwtValidationArgs::new_testing(),
config: Arc::new(Config::new_empty_for_test()),
diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rs
index 0db194cf9e..b8d4cb449f 100644
--- a/rust/cloud-storage/document_cognition_service/src/main.rs
+++ b/rust/cloud-storage/document_cognition_service/src/main.rs
@@ -33,11 +33,9 @@ use macro_middleware::auth::internal_access::InternalApiSecretKey;
use notification::domain::service::SqsNotificationIngress;
use notification::outbound::queue::SqsQueue;
use readonly_pool::ReadOnlyPool;
-use scribe::{ScribeClient, document::DocumentClient};
use search_service_client::SearchServiceClient;
use secretsmanager_client::SecretManager;
use sqlx::postgres::PgPoolOptions;
-use static_file_service_client::StaticFileServiceClient;
use std::sync::Arc;
use stream::outbound::redis_pg::RedisPostgresStreamRepo;
use sync_service_client::SyncServiceClient;
@@ -142,11 +140,6 @@ async fn main() -> anyhow::Result<()> {
config.email_service_url.clone(),
));
- let static_file_service_client = Arc::new(StaticFileServiceClient::new(
- internal_auth_key.as_ref().to_string(),
- config.static_file_service_url.clone(),
- ));
-
tracing::info!("initialized static file service client");
// Initialize Redis client for stream service
@@ -286,21 +279,6 @@ async fn main() -> anyhow::Result<()> {
email_service_client.url().to_owned(),
));
- let scribe = Arc::new(
- ScribeClient::new()
- .with_document_client(
- DocumentClient::builder()
- .with_dss_client(document_storage_client.clone())
- .with_lexical_client(lexical_client)
- .with_sync_service_client(sync_service_client.clone())
- .with_macro_db(db.clone())
- .build(),
- )
- .with_channel_client(db.clone())
- .with_dcs_client(db.clone())
- .with_email_client(email_service_client)
- .with_static_file_client(static_file_service_client.clone()),
- );
let search_service_client = Arc::new(search_service_client);
let properties_service = properties::PropertiesServiceImpl::new(
@@ -366,7 +344,6 @@ async fn main() -> anyhow::Result<()> {
let tool_service_context = ai_tools::ToolServiceContext {
search_service_client: search_service_client.clone(),
email_service_client: email_service_client_external.clone(),
- scribe: scribe.clone(),
soup_service: soup_service.clone(),
email_service: email_service_for_tools.clone(),
document_tool_context: document_tool_context.clone(),
@@ -395,7 +372,6 @@ async fn main() -> anyhow::Result<()> {
api::setup_and_serve(ApiContext {
db: db.clone(),
email_service_client_external,
- scribe,
sqs_client: Arc::new(sqs_client),
document_storage_client: Arc::new(document_storage_client),
comms_service_client: Arc::new(comms_service_client),
diff --git a/rust/cloud-storage/mcp_service/Cargo.toml b/rust/cloud-storage/mcp_service/Cargo.toml
index 91ed37592b..f42726f017 100644
--- a/rust/cloud-storage/mcp_service/Cargo.toml
+++ b/rust/cloud-storage/mcp_service/Cargo.toml
@@ -15,7 +15,6 @@ axum = { workspace = true, features = ["tower-log"] }
call = { path = "../call", default-features = false, features = ["ports"] }
chat = { path = "../chat", features = ["ai_tools", "outbound"] }
comms = { path = "../comms", features = ["outbound"] }
-document_storage_service_client = { path = "../document_storage_service_client" }
documents = { path = "../documents", features = ["ai_tools"] }
email = { path = "../email", features = ["outbound"] }
email_service_client = { path = "../email_service_client" }
@@ -41,13 +40,6 @@ properties = { path = "../properties", features = ["ai_tools"] }
readonly_pool = { path = "../readonly_pool" }
redis = { workspace = true, features = ["aio", "tokio-comp"] }
rmcp = { version = "1.2.0", features = ["transport-streamable-http-server"] }
-scribe = { path = "../scribe", features = [
- "channel",
- "dcs",
- "document",
- "email",
- "static_file",
-] }
search_service_client = { path = "../search_service_client" }
secretsmanager_client = { path = "../secretsmanager_client" }
serde_json = { workspace = true }
@@ -60,7 +52,6 @@ sqs_client = { path = "../sqs_client", default-features = false, features = [
"gmail",
"search",
] }
-static_file_service_client = { path = "../static_file_service_client" }
sync_service_client = { path = "../sync_service_client" }
tokio = { workspace = true }
tracing = { workspace = true }
diff --git a/rust/cloud-storage/mcp_service/src/context.rs b/rust/cloud-storage/mcp_service/src/context.rs
index 0d3499c0d0..0f7e6fc7c4 100644
--- a/rust/cloud-storage/mcp_service/src/context.rs
+++ b/rust/cloud-storage/mcp_service/src/context.rs
@@ -8,7 +8,6 @@ use anyhow::Context;
use comms::domain::service::ChannelServiceImpl;
use comms::outbound::postgres::comms_repo::PgCommsRepo;
use comms::outbound::postgres::user_repo::PgUserRepo;
-use document_storage_service_client::DocumentStorageServiceClient;
use documents::{
domain::{models::CloudFrontConfig, service::DocumentServiceImpl},
inbound::toolset::DocumentToolContext,
@@ -28,7 +27,6 @@ use mcp_auth_proxy::{
domain::service::McpAuthProxyServiceImpl,
outbound::{fusionauth::FusionAuthOAuthProvider, redis::RedisInflightAuth},
};
-use scribe::{ScribeClient, document::DocumentClient};
use search_service_client::SearchServiceClient;
use secretsmanager_client::LocalOrRemoteSecret;
use soup::domain::service::SoupImpl;
@@ -137,9 +135,6 @@ async fn build_tool_context(
let dss_url: String = env_vars.document_storage_service_url.as_ref().to_owned();
let sync_service_url: String = env_vars.sync_service_url.as_ref().to_owned();
- let document_storage_client =
- DocumentStorageServiceClient::new(internal_auth_key.clone(), dss_url.clone());
-
let search_service_client = SearchServiceClient::new(internal_auth_key.clone(), dss_url);
let lexical_client = Arc::new(lexical_client::LexicalClient::new(
@@ -152,12 +147,6 @@ async fn build_tool_context(
env_vars.email_service_url.as_ref().to_owned(),
));
- let static_file_service_client =
- Arc::new(static_file_service_client::StaticFileServiceClient::new(
- internal_auth_key,
- env_vars.static_file_service_url.as_ref().to_owned(),
- ));
-
let frecency_storage = FrecencyPgStorage::new(db.clone());
let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());
let email_service = EmailServiceImpl::new(
@@ -291,24 +280,6 @@ async fn build_tool_context(
email_service_client.url().to_owned(),
)),
search_service_client: Arc::new(search_service_client),
- scribe: Arc::new(
- ScribeClient::new()
- .with_document_client(
- DocumentClient::builder()
- .with_dss_client(document_storage_client)
- .with_lexical_client(lexical_client)
- .with_sync_service_client(SyncServiceClient::new(
- sync_service_auth_key,
- sync_service_url,
- ))
- .with_macro_db(db.clone())
- .build(),
- )
- .with_channel_client(db.clone())
- .with_dcs_client(db.clone())
- .with_email_client(email_service_client)
- .with_static_file_client(static_file_service_client),
- ),
soup_service,
email_service: email_service_for_tools,
document_tool_context,
diff --git a/rust/cloud-storage/memory/Cargo.toml b/rust/cloud-storage/memory/Cargo.toml
index 2af363999b..1527e46769 100644
--- a/rust/cloud-storage/memory/Cargo.toml
+++ b/rust/cloud-storage/memory/Cargo.toml
@@ -30,7 +30,6 @@ utoipa = { workspace = true }
# For building ToolServiceContext
call = { path = "../call", default-features = false, features = ["ai_tools", "outbound", "ports"] }
comms = { path = "../comms" }
-document_storage_service_client = { path = "../document_storage_service_client" }
documents = { path = "../documents" }
email = { path = "../email" }
email_service_client = { path = "../email_service_client" }
@@ -41,14 +40,12 @@ lexical_client = { path = "../lexical_client" }
macro_aws_config = { path = "../macro_aws_config" }
properties = { path = "../properties" }
readonly_pool = { path = "../readonly_pool" }
-scribe = { path = "../scribe" }
search_service_client = { path = "../search_service_client" }
soup = { path = "../soup", features = ["all"] }
sqs_client = { path = "../sqs_client", default-features = false, features = [
"email",
"gmail",
] }
-static_file_service_client = { path = "../static_file_service_client" }
sync_service_client = { path = "../sync_service_client" }
diff --git a/rust/cloud-storage/memory/src/context.rs b/rust/cloud-storage/memory/src/context.rs
index fbc194fdeb..19371393ab 100644
--- a/rust/cloud-storage/memory/src/context.rs
+++ b/rust/cloud-storage/memory/src/context.rs
@@ -4,7 +4,6 @@ use ai_tools::{
use comms::domain::service::ChannelServiceImpl;
use comms::outbound::postgres::comms_repo::PgCommsRepo;
use comms::outbound::postgres::user_repo::PgUserRepo;
-use document_storage_service_client::DocumentStorageServiceClient;
use documents::domain::models::CloudFrontConfig;
use documents::inbound::toolset::DocumentToolContext;
use documents::outbound::pg_document_repo::PgDocumentRepo;
@@ -12,18 +11,15 @@ use documents::outbound::s3_upload_url::S3UploadUrlAdapter;
use email::domain::ports::ReadonlyEmailPreviewAdapter;
use email::domain::service::EmailServiceImpl;
use email::outbound::EmailPgRepo;
-use email_service_client::{EmailServiceClient, EmailServiceClientExternal};
+use email_service_client::EmailServiceClientExternal;
use entity_access::domain::service::EntityAccessServiceImpl;
use entity_access::outbound::PgAccessRepository;
use frecency::domain::services::FrecencyQueryServiceImpl;
use frecency::outbound::postgres::FrecencyPgStorage;
use lexical_client::LexicalClient;
-use scribe::ScribeClient;
-use scribe::document::DocumentClient;
use search_service_client::SearchServiceClient;
use soup::domain::service::SoupImpl;
use soup::outbound::pg_soup_repo::PgSoupRepo;
-use static_file_service_client::StaticFileServiceClient;
use std::sync::Arc;
use sync_service_client::SyncServiceClient;
@@ -49,10 +45,6 @@ pub async fn build_tool_service_context(
.email_scheduled_queue(&config.email_scheduled_queue);
// Service clients
- let dss_client = Arc::new(DocumentStorageServiceClient::new(
- config.internal_api_secret_key.clone(),
- config.document_storage_service_url.clone(),
- ));
let search_client = Arc::new(SearchServiceClient::new(
config.internal_api_secret_key.clone(),
config.search_service_url.clone(),
@@ -61,14 +53,6 @@ pub async fn build_tool_service_context(
config.internal_api_secret_key.clone(),
config.sync_service_url.clone(),
));
- let email_client = Arc::new(EmailServiceClient::new(
- config.internal_api_secret_key.clone(),
- config.email_service_url.clone(),
- ));
- let sfs_client = Arc::new(StaticFileServiceClient::new(
- config.internal_api_secret_key.clone(),
- config.static_file_service_url.clone(),
- ));
let email_ext_client = Arc::new(EmailServiceClientExternal::new(
config.email_service_url.clone(),
));
@@ -77,23 +61,6 @@ pub async fn build_tool_service_context(
config.lexical_service_url.clone(),
);
- // Scribe
- let scribe = Arc::new(
- ScribeClient::new()
- .with_document_client(
- DocumentClient::builder()
- .with_dss_client(dss_client.clone())
- .with_lexical_client(Arc::new(lexical_client.clone()))
- .with_sync_service_client(sync_client.clone())
- .with_macro_db(pool.clone())
- .build(),
- )
- .with_channel_client(pool.clone())
- .with_dcs_client(pool.clone())
- .with_email_client(email_client)
- .with_static_file_client(sfs_client),
- );
-
// Soup service
let frecency_storage = FrecencyPgStorage::new(pool.clone());
let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());
@@ -204,7 +171,6 @@ pub async fn build_tool_service_context(
Ok(ToolServiceContext {
search_service_client: search_client,
email_service_client: email_ext_client,
- scribe,
soup_service,
email_service: email_service_for_tools,
document_tool_context,
diff --git a/rust/cloud-storage/scribe/Cargo.toml b/rust/cloud-storage/scribe/Cargo.toml
deleted file mode 100644
index b9cd57494c..0000000000
--- a/rust/cloud-storage/scribe/Cargo.toml
+++ /dev/null
@@ -1,72 +0,0 @@
-[package]
-edition = "2024"
-name = "scribe"
-publish = false
-version = "0.1.0"
-
-[features]
-
-all = ["channel", "dcs", "document", "email", "static_file"]
-channel = ["comms_db_client", "models_comms", "dep:sqlx"]
-dcs = ["dep:chat", "macro_db_client", "dep:sqlx"]
-default = []
-document = [
- "document_storage_service_client",
- "lexical_client",
- "sync_service_client",
- "properties_db_client",
- "models_properties",
- "macro_db_client",
- "macro_user_id",
- "models_permissions",
- "dep:sqlx",
- # TODO
- # "static_file_service_client??",
-]
-email = ["email_service_client", "models_email"]
-static_file = ["models_sfs", "static_file_service_client"]
-
-[dependencies]
-# Core dependencies
-anyhow = { workspace = true }
-base64 = { workspace = true }
-bytes = { workspace = true }
-chrono = { workspace = true }
-derive_builder = { workspace = true }
-doppleganger = { workspace = true }
-futures = { workspace = true }
-reqwest = { workspace = true }
-serde = { workspace = true }
-serde_json = { workspace = true }
-sqlx = { workspace = true, optional = true }
-thiserror = { workspace = true }
-tokio = { workspace = true }
-tracing = { workspace = true }
-uuid = { workspace = true }
-
-# Internal dependencies
-ai = { path = "../ai" }
-ai_format = { path = "../ai_format" }
-attachment = { path = "../attachment" }
-macro_client_errors = { path = "../macro_client_errors" }
-model = { path = "../model" }
-models_dcs = { path = "../models_dcs" }
-s3_client = { path = "../s3_client" }
-
-# Service client dependencies
-document_storage_service_client = { path = "../document_storage_service_client", optional = true }
-lexical_client = { path = "../lexical_client", optional = true }
-sync_service_client = { path = "../sync_service_client", optional = true }
-
-chat = { path = "../chat", optional = true, default-features = false, features = ["outbound"] }
-comms_db_client = { path = "../comms_db_client", optional = true }
-macro_db_client = { path = "../macro_db_client", optional = true }
-email_service_client = { path = "../email_service_client", optional = true }
-macro_user_id = { path = "../macro_user_id", optional = true }
-models_comms = { path = "../models_comms", optional = true }
-models_permissions = { path = "../models_permissions", optional = true }
-models_email = { path = "../models_email", optional = true }
-models_properties = { path = "../models_properties", optional = true }
-models_sfs = { path = "../models_sfs", optional = true }
-properties_db_client = { path = "../properties_db_client", optional = true }
-static_file_service_client = { path = "../static_file_service_client", optional = true }
diff --git a/rust/cloud-storage/scribe/justfile b/rust/cloud-storage/scribe/justfile
deleted file mode 100644
index 7e66c5e06d..0000000000
--- a/rust/cloud-storage/scribe/justfile
+++ /dev/null
@@ -1,2 +0,0 @@
-build-all:
- cargo build --features all
diff --git a/rust/cloud-storage/scribe/src/channel/client.rs b/rust/cloud-storage/scribe/src/channel/client.rs
deleted file mode 100644
index af5078f662..0000000000
--- a/rust/cloud-storage/scribe/src/channel/client.rs
+++ /dev/null
@@ -1,154 +0,0 @@
-use ai_format::insight_context_log::InsightContextLog;
-use ai_format::util::Indent;
-use anyhow::Error;
-use models_comms::channel::ChannelMetadata;
-use sqlx::{Pool, Postgres};
-use std::fmt::Debug;
-use uuid::Uuid;
-
-#[derive(Clone)]
-pub struct ChannelClient {
- db: Pool<Postgres>,
-}
-
-impl ChannelClient {
- /// Create a new ChannelClient with a database pool for direct DB operations
- pub fn new(db: Pool<Postgres>) -> Self {
- Self { db }
- }
-
- /// Get channel metadata (name and type) by channel ID
- #[tracing::instrument(skip(self), err)]
- pub async fn get_channel_metadata(
- &self,
- channel_id: impl TryInto<Uuid> + Debug,
- ) -> Result<ChannelMetadata, Error> {
- let channel_id = channel_id
- .try_into()
- .map_err(|_| anyhow::anyhow!("invalid uuid"))?;
-
- let channel =
- comms_db_client::channels::get_channel::get_channel(&self.db, &channel_id).await?;
-
- Ok(ChannelMetadata {
- name: channel.name.unwrap_or_default(),
- channel_type: match channel.channel_type {
- model::comms::ChannelType::Public => models_comms::channel::ChannelType::Public,
- model::comms::ChannelType::Organization => {
- models_comms::channel::ChannelType::Organization
- }
- model::comms::ChannelType::Private => models_comms::channel::ChannelType::Private,
- model::comms::ChannelType::DirectMessage => {
- models_comms::channel::ChannelType::DirectMessage
- }
- model::comms::ChannelType::Team => models_comms::channel::ChannelType::Team,
- },
- })
- }
-
- /// Get channel transcript (message history) by channel ID
- #[tracing::instrument(skip(self), err)]
- pub async fn get_channel_transcript(
- &self,
- channel_id: impl TryInto<Uuid> + Debug,
- since: Option<chrono::DateTime<chrono::Utc>>,
- limit: Option<i64>,
- ) -> Result<String, Error> {
- let channel_id = channel_id
- .try_into()
- .map_err(|_| anyhow::anyhow!("invalid uuid"))?;
-
- let transcript = format_channel_transcript(&self.db, &channel_id, since, limit).await?;
- Ok(transcript)
- }
-
- /// Get messages with context around a specific message
- /// Returns formatted conversation with messages before and after the target message
- #[tracing::instrument(skip(self), err)]
- pub async fn get_message_with_context(
- &self,
- message_id: impl TryInto<Uuid> + Debug,
- before: i64,
- after: i64,
- ) -> Result<String, Error> {
- let message_id = message_id
- .try_into()
- .map_err(|_| anyhow::anyhow!("invalid uuid"))?;
-
- let db_messages =
- comms_db_client::messages::read_message_with_context::get_messages_with_context(
- &self.db,
- &message_id,
- before,
- after,
- )
- .await?;
-
- // Format messages using InsightContextLog
- let formatted_messages = db_messages
- .iter()
- .map(|msg| {
- InsightContextLog {
- name: "message".to_string(),
- metadata: vec![
- ("message_id".to_string(), msg.id.to_string()),
- ("sender_id".to_string(), msg.sender_id.to_string()),
- ("created_at".to_string(), msg.created_at.to_rfc3339()),
- ],
- content: msg.content.clone(),
- }
- .to_string()
- })
- .collect::<Vec<_>>()
- .join("\n");
-
- let formatted_text = InsightContextLog {
- name: "conversation".to_string(),
- metadata: vec![],
- content: Indent(4, formatted_messages),
- }
- .to_string();
-
- Ok(formatted_text)
- }
-}
-
-/// Format channel messages into a transcript string
-/// This matches the logic in comms_service/src/api/channels/get_channel_transcript.rs
-async fn format_channel_transcript(
- db: &Pool<Postgres>,
- channel_id: &Uuid,
- since: Option<chrono::DateTime<chrono::Utc>>,
- limit: Option<i64>,
-) -> anyhow::Result<String> {
- let messages =
- comms_db_client::messages::get_messages::get_messages(db, channel_id, since, limit).await?;
-
- let formatted_messages = messages
- .iter()
- .map(|msg| {
- InsightContextLog {
- name: "message".to_string(),
- metadata: vec![
- ("sender_id".to_string(), msg.sender_id.to_string()),
- ("created_at".to_string(), msg.created_at.to_rfc3339()),
- ],
- content: msg.content.clone(),
- }
- .to_string()
- })
- .collect::<Vec<_>>()
- .join("\n");
-
- let formatted_text = InsightContextLog {
- name: "conversation".to_string(),
- metadata: vec![],
- content: Indent(4, formatted_messages),
- }
- .to_string();
-
- let prompt = "The following conversation is limited to the last 1000 messages. Ignore all formatting and do not show the user the formatted conversation.";
- let formatted_messages = format!("{}\n\n{}", prompt, formatted_text);
-
- Ok(formatted_messages)
-}
diff --git a/rust/cloud-storage/scribe/src/channel/mod.rs b/rust/cloud-storage/scribe/src/channel/mod.rs
deleted file mode 100644
index 4b7eb74623..0000000000
--- a/rust/cloud-storage/scribe/src/channel/mod.rs
+++ /dev/null
@@ -1,22 +0,0 @@
-mod client;
-pub use client::ChannelClient;
-use sqlx::{Pool, Postgres};
-
-use crate::client::ScribeClient;
-
-impl<D, C, A, E, S> ScribeClient<D, C, A, E, S> {
- /// Configure the channel client with a database pool for direct DB operations
- pub fn with_channel_client(
- self,
- db: Pool<Postgres>,
- ) -> ScribeClient<D, ChannelClient, A, E, S> {
- let client = ChannelClient::new(db);
- ScribeClient {
- document: self.document,
- channel: client,
- chat: self.chat,
- email: self.email,
- static_file: self.static_file,
- }
- }
-}
diff --git a/rust/cloud-storage/scribe/src/client.rs b/rust/cloud-storage/scribe/src/client.rs
deleted file mode 100644
index b41f931d7d..0000000000
--- a/rust/cloud-storage/scribe/src/client.rs
+++ /dev/null
@@ -1,28 +0,0 @@
-#[derive(Clone)]
-pub struct ScribeClient<DocumentClient, ChannelClient, ChatClient, EmailClient, StaticFileClient> {
- pub document: DocumentClient,
- pub channel: ChannelClient,
- pub chat: ChatClient,
- pub email: EmailClient,
- pub static_file: StaticFileClient,
-}
-
-type NoClient = ();
-
-impl Default for ScribeClient<NoClient, NoClient, NoClient, NoClient, NoClient> {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl ScribeClient<NoClient, NoClient, NoClient, NoClient, NoClient> {
- pub fn new() -> Self {
- ScribeClient {
- document: (),
- channel: (),
- chat: (),
- email: (),
- static_file: (),
- }
- }
-}
diff --git a/rust/cloud-storage/scribe/src/dcs/client.rs b/rust/cloud-storage/scribe/src/dcs/client.rs
deleted file mode 100644
index d78f64ac17..0000000000
--- a/rust/cloud-storage/scribe/src/dcs/client.rs
+++ /dev/null
@@ -1,67 +0,0 @@
-use anyhow::Result;
-use chat::domain::ports::ChatRepo;
-use chat::outbound::postgres::PgChatRepo;
-pub use model::chat::ChatHistory;
-use model::chat::{ConversationRecord, MessageWithAttachments};
-use sqlx::{Pool, Postgres};
-
-#[derive(Clone)]
-pub struct DcsClient {
- chat_repo: PgChatRepo,
- db: Pool<Postgres>,
-}
-
-impl DcsClient {
- pub fn new(db: Pool<Postgres>) -> Self {
- let chat_repo = PgChatRepo::new(db.clone());
- Self { chat_repo, db }
- }
-}
-
-impl DcsClient {
- #[tracing::instrument(skip(self), err)]
- pub async fn get_chat_history(&self, chat_id: &str) -> Result<ChatHistory> {
- let chat = self
- .chat_repo
- .get_chat(chat_id)
- .await
- .map_err(|e| anyhow::anyhow!("failed to get chat: {e}"))?;
-
- let messages = chat
- .messages
- .into_iter()
- .map(|m| {
- let content = match m.content {
- ai::types::ChatMessageContent::Text(s) => s,
- other => serde_json::to_string(&other).unwrap_or_default(),
- };
- MessageWithAttachments {
- content,
- date: chrono::Utc::now(),
- attachment_ids: m
- .attachments
- .iter()
- .map(|a| a.entity_id.clone().into_owned())
- .collect(),
- }
- })
- .collect();
-
- Ok(ChatHistory {
- conversation: vec![ConversationRecord {
- chat_id: chat.id,
- title: chat.name,
- messages,
- }],
- })
- }
-
- /// Get chat history for specific message IDs (may span multiple chats).
- #[tracing::instrument(skip(self), err)]
- pub async fn get_chat_history_for_messages(
- &self,
- message_ids: &[String],
- ) -> Result<ChatHistory> {
- macro_db_client::chat_history::get_chat_history_for_messages(&self.db, message_ids).await
- }
-}
diff --git a/rust/cloud-storage/scribe/src/dcs/mod.rs b/rust/cloud-storage/scribe/src/dcs/mod.rs
deleted file mode 100644
index 0d4afb89c9..0000000000
--- a/rust/cloud-storage/scribe/src/dcs/mod.rs
+++ /dev/null
@@ -1,18 +0,0 @@
-mod client;
-pub use client::DcsClient;
-use sqlx::{Pool, Postgres};
-
-use crate::client::ScribeClient;
-
-impl<D, C, A, E, S> ScribeClient<D, C, A, E, S> {
- pub fn with_dcs_client(self, db: Pool<Postgres>) -> ScribeClient<D, C, DcsClient, E, S> {
- let dcs_client = DcsClient::new(db);
- ScribeClient {
- channel: self.channel,
- chat: dcs_client,
- document: self.document,
- email: self.email,
- static_file: self.static_file,
- }
- }
-}
diff --git a/rust/cloud-storage/scribe/src/document/client.rs b/rust/cloud-storage/scribe/src/document/client.rs
deleted file mode 100644
index 94fbaffd6d..0000000000
--- a/rust/cloud-storage/scribe/src/document/client.rs
+++ /dev/null
@@ -1,174 +0,0 @@
-use super::fetcher::NewDocumentFetcher;
-use super::project::ProjectFetcher;
-use document_storage_service_client::DocumentStorageServiceClient;
-use lexical_client::LexicalClient;
-use sqlx::{Pool, Postgres};
-use std::sync::Arc;
-use sync_service_client::SyncServiceClient;
-
-#[derive(Clone)]
-pub struct DocumentClient {
- pub dss_client: Arc<DocumentStorageServiceClient>,
- pub sync_service_client: Arc<SyncServiceClient>,
- pub lexical_client: Arc<LexicalClient>,
- pub macro_db: Arc<Pool<Postgres>>,
-}
-
-impl DocumentClient {
- pub fn builder() -> NewDocumentClientBuilder {
- NewDocumentClientBuilder::new()
- }
-
- pub fn new(
- dss_client: Arc<DocumentStorageServiceClient>,
- sync_service_client: Arc<SyncServiceClient>,
- lexical_client: Arc<LexicalClient>,
- macro_db: Arc<Pool<Postgres>>,
- ) -> Self {
- Self {
- dss_client,
- sync_service_client,
- lexical_client,
- macro_db,
- }
- }
-}
-
-impl DocumentClient {
- pub fn fetch<T: Into<String>>(&self, document_id: T) -> NewDocumentFetcher {
- NewDocumentFetcher::new(
- self.dss_client.clone(),
- self.sync_service_client.clone(),
- self.lexical_client.clone(),
- self.macro_db.clone(),
- document_id.into(),
- )
- }
-
- /// Create a fetcher with JWT authentication for external API calls
- pub fn fetch_with_auth<T: Into<String>>(
- &self,
- document_id: T,
- jwt_token: String,
- ) -> NewDocumentFetcher {
- NewDocumentFetcher::new(
- self.dss_client.clone(),
- self.sync_service_client.clone(),
- self.lexical_client.clone(),
- self.macro_db.clone(),
- document_id.into(),
- )
- .with_jwt_token(jwt_token)
- }
-
- pub fn fetch_project(&self, id: String) -> ProjectFetcher<()> {
- ProjectFetcher::new(id)
- }
-
- /// Get the database pool for direct DB access
- pub fn db(&self) -> &Pool<Postgres> {
- &self.macro_db
- }
-}
-
-// --- builder --- //
-// slight insanity but its good ong
-pub type NewDocumentClientBuilder = DocumentClientBuilder<(), (), (), ()>;
-impl Default for NewDocumentClientBuilder {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl NewDocumentClientBuilder {
- pub fn new() -> Self {
- Self {
- dss_client: (),
- lexical_client: (),
- sync_service_client: (),
- macro_db: (),
- }
- }
-}
-
-pub struct DocumentClientBuilder<A, B, C, D> {
- pub dss_client: A,
- pub sync_service_client: B,
- pub lexical_client: C,
- pub macro_db: D,
-}
-
-impl<A, B, C, D> DocumentClientBuilder<A, B, C, D> {
- pub fn with_dss_client<T: Into<Arc<DocumentStorageServiceClient>>>(
- self,
- dss_client: T,
- ) -> DocumentClientBuilder<Arc<DocumentStorageServiceClient>, B, C, D> {
- DocumentClientBuilder {
- dss_client: dss_client.into(),
- lexical_client: self.lexical_client,
- sync_service_client: self.sync_service_client,
- macro_db: self.macro_db,
- }
- }
-}
-
-impl<A, B, C, D> DocumentClientBuilder<A, B, C, D> {
- pub fn with_sync_service_client<T: Into<Arc<SyncServiceClient>>>(
- self,
- sync_service_client: T,
- ) -> DocumentClientBuilder<A, Arc<SyncServiceClient>, C, D> {
- DocumentClientBuilder {
- dss_client: self.dss_client,
- lexical_client: self.lexical_client,
- sync_service_client: sync_service_client.into(),
- macro_db: self.macro_db,
- }
- }
-}
-
-impl<A, B, C, D> DocumentClientBuilder<A, B, C, D> {
- pub fn with_lexical_client<T: Into<Arc<LexicalClient>>>(
- self,
- lexical_client: T,
- ) -> DocumentClientBuilder<A, B, Arc<LexicalClient>, D> {
- DocumentClientBuilder {
- dss_client: self.dss_client,
- lexical_client: lexical_client.into(),
- sync_service_client: self.sync_service_client,
- macro_db: self.macro_db,
- }
- }
-}
-
-impl<A, B, C, D> DocumentClientBuilder<A, B, C, D> {
- pub fn with_macro_db<T: Into<Arc<Pool<Postgres>>>>(
- self,
- macro_db: T,
- ) -> DocumentClientBuilder<A, B, C, Arc<Pool<Postgres>>> {
- DocumentClientBuilder {
- dss_client: self.dss_client,
- lexical_client: self.lexical_client,
- sync_service_client: self.sync_service_client,
- macro_db: macro_db.into(),
- }
- }
-}
-
-impl
- DocumentClientBuilder<
- Arc<DocumentStorageServiceClient>,
- Arc<SyncServiceClient>,
- Arc<LexicalClient>,
- Arc<Pool<Postgres>>,
- >
-{
- pub fn build(self) -> DocumentClient {
- DocumentClient {
- dss_client: self.dss_client,
- sync_service_client: self.sync_service_client,
- lexical_client: self.lexical_client,
- macro_db: self.macro_db,
- }
- }
-}
-// --- end builder ---//
diff --git a/rust/cloud-storage/scribe/src/document/fetcher.rs b/rust/cloud-storage/scribe/src/document/fetcher.rs
deleted file mode 100644
index 0e89fe4b48..0000000000
--- a/rust/cloud-storage/scribe/src/document/fetcher.rs
+++ /dev/null
@@ -1,294 +0,0 @@
-use crate::document::types::{Data, DocumentContent};
-use ai_format::document::Document;
-use ai_format::properties::Properties;
-use ai_format::traits::TextAttachment;
-use anyhow::{Context, Error};
-use document_storage_service_client::DocumentStorageServiceClient;
-use lexical_client::LexicalClient;
-use model::document::FileTypeExt;
-use model::document::{DocumentBasic, FileType, response::LocationResponseV3};
-use models_properties::EntityType;
-use sqlx::{Pool, Postgres};
-use std::fmt::Debug;
-use std::sync::Arc;
-use sync_service_client::SyncServiceClient;
-
-pub type NoData = ();
-pub type Fetched<T> = T;
-
-pub type NewDocumentFetcher = DocumentFetcher<NoData, NoData>;
-
-pub struct DocumentFetcher<Location, Content> {
- pub location: Location,
- pub content: Content,
- inner_dss: Arc<DocumentStorageServiceClient>,
- inner_sync_service: Arc<SyncServiceClient>,
- inner_lexical: Arc<LexicalClient>,
- document_id: String,
- jwt_token: Option<String>,
- macro_db: Arc<Pool<Postgres>>,
-}
-
-// A client is a wrapper around methods that may be applied to a single document
-// TODO write `BulkDocumentClient` (same interface over Vec<document_id>)
-impl DocumentFetcher<NoData, NoData> {
- pub fn new(
- dss_client: Arc<DocumentStorageServiceClient>,
- sync_service_client: Arc<SyncServiceClient>,
- lexical_client: Arc<LexicalClient>,
- macro_db: Arc<Pool<Postgres>>,
- document_id: String,
- ) -> Self {
- Self {
- inner_dss: dss_client,
- inner_sync_service: sync_service_client,
- inner_lexical: lexical_client,
- document_id,
- content: (),
- location: (),
- jwt_token: None,
- macro_db,
- }
- }
-
- /// Set JWT token for external API authentication
- pub fn with_jwt_token(mut self, jwt_token: String) -> Self {
- self.jwt_token = Some(jwt_token);
- self
- }
-}
-
-impl DocumentFetcher<NoData, NoData> {
- #[tracing::instrument(err)]
- pub async fn document_location(
- self,
- ) -> Result<DocumentFetcher<Fetched<LocationResponseV3>, NoData>, Error> {
- let location = match &self.jwt_token {
- Some(jwt) => {
- self.inner_dss
- .get_recent_document_location_v3_external(&self.document_id, jwt)
- .await?
- }
- None => {
- self.inner_dss
- .get_recent_document_location_v3(&self.document_id)
- .await?
- }
- };
- Ok(DocumentFetcher {
- content: (),
- location,
- document_id: self.document_id,
- inner_dss: self.inner_dss,
- inner_lexical: self.inner_lexical,
- inner_sync_service: self.inner_sync_service,
- jwt_token: self.jwt_token,
- macro_db: self.macro_db,
- })
- }
-
- #[tracing::instrument(err)]
- pub async fn document_content(
- self,
- ) -> Result<DocumentFetcher<Fetched<LocationResponseV3>, Fetched<DocumentContent>>, Error> {
- let client_with_location = self.document_location().await?;
- client_with_location.document_content().await
- }
-}
-
-impl DocumentFetcher<Fetched<LocationResponseV3>, NoData> {
- #[tracing::instrument(err)]
- pub async fn document_content(
- self,
- ) -> Result<DocumentFetcher<Fetched<LocationResponseV3>, Fetched<DocumentContent>>, Error> {
- let content = self.fetch_content_from_location(&self.location).await?;
- Ok(DocumentFetcher {
- content,
- location: self.location,
- document_id: self.document_id,
- inner_dss: self.inner_dss,
- inner_lexical: self.inner_lexical,
- inner_sync_service: self.inner_sync_service,
- jwt_token: self.jwt_token,
- macro_db: self.macro_db,
- })
- }
-}
-
-impl<T> DocumentFetcher<Fetched<LocationResponseV3>, T> {
- pub fn metadata(&self) -> &DocumentBasic {
- self.location.metadata()
- }
-
- pub fn preview_file_type(&self) -> Result<FileType, Error> {
- self.location.file_type()
- }
-}
-
-impl DocumentFetcher<LocationResponseV3, Fetched<DocumentContent>> {
- pub fn file_type(&self) -> FileType {
- self.content.file_type
- }
-
- pub fn text_attachment(self) -> Option<Box<dyn TextAttachment>> {
- if self.content.file_type.is_image() {
- None
- } else {
- let name = self.location.metadata().document_name.clone();
- let file_type = self.file_type().to_string();
- let properties = self
- .content
- .properties
- .clone()
- .map(|p| Properties::from_properties(EntityType::Task, p));
- let text = self.content.text_content().ok()?;
-
- Some(
- Document {
- content: text,
- file_type,
- id: self.document_id,
- name,
- properties,
- }
- .boxed(),
- )
- }
- }
-}
-
-// -- internal util / fetching logic --
-impl<L: Debug, D: Debug> DocumentFetcher<L, D> {
- #[tracing::instrument(err)]
- async fn fetch_content_from_location(
- &self,
- location: &LocationResponseV3,
- ) -> Result<DocumentContent, Error> {
- let file_type = location.file_type()?;
- match file_type {
- // pdf / docx content is static and always in macrodb
- FileType::Docx | FileType::Pdf => {
- let text = match &self.jwt_token {
- Some(jwt) => {
- self.inner_dss
- .get_document_text_external(self.document_id.as_str(), jwt)
- .await?
- }
- None => {
- self.inner_dss
- .get_document_text(self.document_id.as_str())
- .await?
- }
- };
- Ok(DocumentContent {
- data: Data::Text(text),
- document_id: location.metadata().document_id.clone(),
- file_type,
- location: location.clone(),
- properties: None,
- })
- }
- // md content is usually in sync service but may be in s3
- FileType::Md => self.fetch_ai_markdown(location).await,
- // everything else is in S3 (for now)
- other => match location {
- LocationResponseV3::PresignedUrl { presigned_url, .. } => {
- if other.is_text_content() {
- reqwest::get(presigned_url)
- .await
- .context("HTTP (head) error when fetching from S3 [other]")?
- .text()
- .await
- .context("HTTP (body) error when fetching from S3 [other]")
- .map(|text| DocumentContent {
- properties: None,
- data: Data::Text(text),
- document_id: self.document_id.clone(),
- file_type,
- location: location.clone(),
- })
- } else {
- reqwest::get(presigned_url)
- .await
- .context("HTTP (head) error when fetching from S3 [other]")?
- .bytes()
- .await
- .context("HTTP (body) error when fetching from S3 [other]")
- .map(|bytes| DocumentContent {
- properties: None,
- data: Data::Binary(bytes),
- document_id: self.document_id.clone(),
- file_type,
- location: location.clone(),
- })
- }
- }
- LocationResponseV3::SyncServiceContent { .. } => Err(anyhow::anyhow!(
- "Unexpected location (sync service) for other document type"
- )),
- LocationResponseV3::PresignedUrls { .. } => Err(anyhow::anyhow!(
- "Unexpected location (multi part presigned url) for other document type"
- )),
- },
- }
- }
-
- #[tracing::instrument(err)]
- async fn fetch_ai_markdown(
- &self,
- location: &LocationResponseV3,
- ) -> Result<DocumentContent, Error> {
- let properties =
- properties_db_client::entity_properties::get::get_entity_properties_values(
- &self.macro_db,
- &self.document_id,
- models_properties::EntityType::Task,
- )
- .await;
- if let Err(e) = &properties {
- tracing::warn!(error=?e, location=?location, "no properties found for md");
- }
-
- // Choose endpoint based on document location
- let content = match location {
- LocationResponseV3::PresignedUrl { presigned_url, .. } => {
- // Document is in S3, use presigned URL endpoint
- self.inner_lexical
- .parse_markdown_for_ai_from_url(presigned_url)
- .await?
- }
- LocationResponseV3::SyncServiceContent { .. } => {
- // Document is in sync-service, use standard endpoint
- self.inner_lexical
- .parse_markdown_for_ai(&self.document_id)
- .await?
- }
- LocationResponseV3::PresignedUrls { .. } => {
- anyhow::bail!("Multi-part presigned URLs not supported for markdown documents")
- }
- };
-
- Ok(DocumentContent {
- properties: properties.ok(),
- data: Data::Markdown(content),
- document_id: self.document_id.clone(),
- location: location.clone(),
- file_type: FileType::Md,
- })
- }
-}
-
-// -- internal helper --
-
-impl<L, D> Debug for DocumentFetcher<L, D>
-where
- L: Debug,
- D: Debug,
-{
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- f.debug_struct("DocumentClient")
- .field("location", &self.location)
- .field("content", &self.content)
- .finish()
- }
-}
diff --git a/rust/cloud-storage/scribe/src/document/mod.rs b/rust/cloud-storage/scribe/src/document/mod.rs
deleted file mode 100644
index a509cf0f82..0000000000
--- a/rust/cloud-storage/scribe/src/document/mod.rs
+++ /dev/null
@@ -1,22 +0,0 @@
-use crate::client::ScribeClient;
-mod client;
-mod fetcher;
-mod project;
-pub mod types;
-
-pub use client::DocumentClient;
-
-impl<D, C, A, E, S> ScribeClient<D, C, A, E, S> {
- pub fn with_document_client(
- self,
- document_client: DocumentClient,
- ) -> ScribeClient<DocumentClient, C, A, E, S> {
- ScribeClient {
- document: document_client,
- channel: self.channel,
- chat: self.chat,
- email: self.email,
- static_file: self.static_file,
- }
- }
-}
diff --git a/rust/cloud-storage/scribe/src/document/project.rs b/rust/cloud-storage/scribe/src/document/project.rs
deleted file mode 100644
index 8d35e6fb1b..0000000000
--- a/rust/cloud-storage/scribe/src/document/project.rs
+++ /dev/null
@@ -1,86 +0,0 @@
-use anyhow::Result;
-use macro_user_id::user_id::MacroUserIdStr;
-use model::item::{Item, ItemWithUserAccessLevel};
-use models_permissions::share_permission::access_level::AccessLevel;
-use sqlx::{Pool, Postgres};
-
-#[derive(Debug, Clone)]
-pub struct ScribeProjectPreview(pub Vec<ItemWithUserAccessLevel>);
-
-pub fn format_item_with_access(
- item: &ItemWithUserAccessLevel,
- f: &mut std::fmt::Formatter<'_>,
-) -> std::fmt::Result {
- if let Some(file_type) = item.item.file_type() {
- writeln!(f, "name: {} {}", item.item.name(), file_type)?;
- } else {
- writeln!(f, "name: {}", item.item.name())?;
- }
- writeln!(
- f,
- "id: {}",
- match &item.item {
- Item::Document(doc) => doc.document_id.as_str(),
- Item::Project(project) => project.id.as_str(),
- Item::Chat(chat) => chat.id.as_str(),
- }
- )?;
- writeln!(
- f,
- "type: {}",
- match &item.item {
- Item::Chat(_) => "Chat",
- Item::Project(_) => "Project",
- Item::Document(_) => "Document",
- }
- )?;
- writeln!(f, "access_level: {}", item.user_access_level)
-}
-
-impl std::fmt::Display for ScribeProjectPreview {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- for (i, item) in self.0.iter().enumerate() {
- writeln!(f, "{}.", i)?;
- format_item_with_access(item, f)?;
- }
- Ok(())
- }
-}
-
-pub struct ProjectFetcher<Content> {
- pub content: Content,
- pub id: String,
-}
-
-pub type NoData = ();
-
-impl ProjectFetcher<NoData> {
- pub fn new(id: String) -> Self {
- Self { content: (), id }
- }
-
- pub async fn content(
- &self,
- db: &Pool<Postgres>,
- user_id: MacroUserIdStr<'_>,
- ) -> Result<ProjectFetcher<ScribeProjectPreview>> {
- let items = macro_db_client::projects::get_project::get_project_content_v2(
- db,
- &self.id,
- user_id,
- AccessLevel::View,
- )
- .await?;
-
- Ok(ProjectFetcher {
- content: ScribeProjectPreview(items),
- id: self.id.clone(),
- })
- }
-}
-
-impl std::fmt::Display for ProjectFetcher<ScribeProjectPreview> {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(f, "Items in project {}\n{}", self.id, self.content)
- }
-}
diff --git a/rust/cloud-storage/scribe/src/document/types.rs b/rust/cloud-storage/scribe/src/document/types.rs
deleted file mode 100644
index 58fc930bae..0000000000
--- a/rust/cloud-storage/scribe/src/document/types.rs
+++ /dev/null
@@ -1,99 +0,0 @@
-use anyhow::{Error, bail};
-use attachment::image::ImageData;
-use bytes::Bytes;
-use lexical_client::types::CognitionResponseData;
-use model::document::response::LocationResponseV3;
-use model::document::{DocumentBasic, FileType, FileTypeExt};
-use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;
-
-#[derive(Debug, Clone)]
-pub struct DocumentContent {
- pub(crate) data: Data,
- pub document_id: String,
- pub file_type: FileType,
- pub location: LocationResponseV3,
- pub properties: Option<Vec<EntityPropertyWithDefinition>>,
-}
-
-#[derive(Clone)]
-pub enum Data {
- Text(String),
- Binary(Bytes),
- Markdown(CognitionResponseData),
-}
-
-impl TryFrom<DocumentContent> for ImageData {
- type Error = anyhow::Error;
- fn try_from(value: DocumentContent) -> Result<Self, Self::Error> {
- if value.file_type.is_image()
- && let Data::Binary(bytes) = value.data
- {
- ImageData::try_from_bytes(bytes.into())
- } else {
- bail!("No conversion to image")
- }
- }
-}
-
-impl std::fmt::Debug for Data {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- match self {
- Data::Binary(bytes) => write!(f, "Data::Binary(<{} bytes>)", bytes.len()),
- Data::Text(chars) => write!(f, "Data::Text(<{} characters>)", chars.len()),
- Data::Markdown(nodes) => write!(f, "Data::Markdown(<{} nodes>)", nodes.data.len()),
- }
- }
-}
-
-impl DocumentContent {
- pub fn metadata(&self) -> &DocumentBasic {
- self.location.metadata()
- }
-
- /// stringify content if its mimetype is text and it is not binary
- /// Markdown is stringifyable / preformatted
- #[tracing::instrument(err)]
- pub fn text_content(self) -> Result<String, Error> {
- if self.file_type.is_text_content() {
- Ok(self.data.to_string())
- } else {
- bail!("Document is not text")
- }
- }
-}
-
-impl std::fmt::Display for Data {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- match self {
- Data::Markdown(md) => write!(
- f,
- "{}",
- md.data
- .iter()
- .map(|node| format!("[[node_id: {}]]\n{}", node.node_id, node.content))
- .collect::<Vec<String>>()
- .join("\n")
- ),
- Data::Binary(data) => write!(f, "{}", String::from_utf8_lossy(data)),
- Data::Text(text) => write!(f, "{}", text),
- }
- }
-}
-
-impl Data {
- pub fn binary_data(self) -> Option<Bytes> {
- if let Data::Binary(data) = self {
- Some(data)
- } else {
- None
- }
- }
-
- pub fn text_data(self) -> Option<String> {
- if let Data::Text(data) = self {
- Some(data)
- } else {
- None
- }
- }
-}
diff --git a/rust/cloud-storage/scribe/src/email/client.rs b/rust/cloud-storage/scribe/src/email/client.rs
deleted file mode 100644
index 4b53e12252..0000000000
--- a/rust/cloud-storage/scribe/src/email/client.rs
+++ /dev/null
@@ -1,37 +0,0 @@
-use email_service_client::EmailServiceClient;
-use models_email::email::service::message::ParsedMessage;
-
-use anyhow::Result;
-use std::sync::Arc;
-
-#[derive(Clone)]
-pub struct EmailClient {
- inner: Arc<EmailServiceClient>,
-}
-
-impl EmailClient {
- pub fn new(inner: Arc<EmailServiceClient>) -> Self {
- Self { inner }
- }
-}
-
-impl EmailClient {
- /// Get a single email message by ID
- #[tracing::instrument(skip(self), err)]
- pub async fn get_email_message_by_id(&self, message_id: &str) -> Result<ParsedMessage> {
- self.inner.get_message_by_id_internal(message_id).await
- }
-
- /// Get messages by thread ID with pagination
- #[tracing::instrument(skip(self), err)]
- pub async fn get_email_messages_by_thread_id(
- &self,
- thread_id: &str,
- message_offset: i64,
- message_limit: i64,
- ) -> Result<Vec<ParsedMessage>> {
- self.inner
- .get_messages_by_thread_id_internal(thread_id, message_offset, message_limit)
- .await
- }
-}
diff --git a/rust/cloud-storage/scribe/src/email/mod.rs b/rust/cloud-storage/scribe/src/email/mod.rs
deleted file mode 100644
index 45d44bed4b..0000000000
--- a/rust/cloud-storage/scribe/src/email/mod.rs
+++ /dev/null
@@ -1,22 +0,0 @@
-mod client;
-pub use client::EmailClient;
-
-use crate::client::ScribeClient;
-use email_service_client::EmailServiceClient;
-use std::sync::Arc;
-
-impl<D, C, A, E, S> ScribeClient<D, C, A, E, S> {
- pub fn with_email_client<T: Into<Arc<EmailServiceClient>>>(
- self,
- email: T,
- ) -> ScribeClient<D, C, A, EmailClient, S> {
- let client = EmailClient::new(email.into());
- ScribeClient {
- document: self.document,
- channel: self.channel,
- chat: self.chat,
- email: client,
- static_file: self.static_file,
- }
- }
-}
diff --git a/rust/cloud-storage/scribe/src/lib.rs b/rust/cloud-storage/scribe/src/lib.rs
deleted file mode 100644
index 6d19bd685b..0000000000
--- a/rust/cloud-storage/scribe/src/lib.rs
+++ /dev/null
@@ -1,15 +0,0 @@
-#[cfg(feature = "channel")]
-pub mod channel;
-
-#[cfg(feature = "dcs")]
-pub mod dcs;
-#[cfg(feature = "document")]
-pub mod document;
-
-#[cfg(feature = "email")]
-pub mod email;
-#[cfg(feature = "static_file")]
-pub mod static_file;
-
-mod client;
-pub use client::ScribeClient;
diff --git a/rust/cloud-storage/scribe/src/static_file/client.rs b/rust/cloud-storage/scribe/src/static_file/client.rs
deleted file mode 100644
index f1d455a660..0000000000
--- a/rust/cloud-storage/scribe/src/static_file/client.rs
+++ /dev/null
@@ -1,22 +0,0 @@
-use static_file_service_client::StaticFileServiceClient;
-use std::sync::Arc;
-
-use crate::static_file::{NewStaticFileFetcher, StaticFileFetcher};
-
-#[derive(Clone)]
-pub struct StaticFileClient {
- inner: Arc<StaticFileServiceClient>,
-}
-
-impl StaticFileClient {
- pub fn new(inner: Arc<StaticFileServiceClient>) -> Self {
- Self { inner }
- }
-}
-
-impl StaticFileClient {
- /// Create a new static file fetcher for a given file ID
- pub fn fetch<T: Into<String>>(&self, file_id: T) -> NewStaticFileFetcher {
- StaticFileFetcher::new(self.inner.clone(), file_id.into())
- }
-}
diff --git a/rust/cloud-storage/scribe/src/static_file/fetcher.rs b/rust/cloud-storage/scribe/src/static_file/fetcher.rs
deleted file mode 100644
index 4d6f91465b..0000000000
--- a/rust/cloud-storage/scribe/src/static_file/fetcher.rs
+++ /dev/null
@@ -1,135 +0,0 @@
-use crate::static_file::types::{Data, StaticFileContent};
-use anyhow::{Context, Error};
-use model::document::{ContentType, ContentTypeExt};
-use models_sfs::FileMetadata;
-use static_file_service_client::StaticFileServiceClient;
-use std::fmt::Debug;
-use std::str::FromStr;
-use std::sync::Arc;
-
-pub type NoData = ();
-pub type Fetched<T> = T;
-
-pub type NewStaticFileFetcher = StaticFileFetcher<NoData, NoData>;
-
-pub struct StaticFileFetcher<Metadata, Content> {
- pub metadata: Metadata,
- pub content: Content,
- inner_sfs: Arc<StaticFileServiceClient>,
- file_id: String,
-}
-
-impl StaticFileFetcher<NoData, NoData> {
- pub fn new(sfs_client: Arc<StaticFileServiceClient>, file_id: String) -> Self {
- Self {
- inner_sfs: sfs_client,
- file_id,
- content: (),
- metadata: (),
- }
- }
-
- #[tracing::instrument(err)]
- pub async fn file_metadata(
- self,
- ) -> Result<StaticFileFetcher<Fetched<FileMetadata>, NoData>, Error> {
- let metadata = self
- .inner_sfs
- .get_file_metadata(&self.file_id)
- .await
- .context("Failed to get file metadata")?
- .ok_or_else(|| anyhow::anyhow!("File not found: {}", self.file_id))?;
-
- Ok(StaticFileFetcher {
- content: (),
- metadata,
- file_id: self.file_id,
- inner_sfs: self.inner_sfs,
- })
- }
-
- #[tracing::instrument(err)]
- pub async fn file_content(
- self,
- ) -> Result<StaticFileFetcher<Fetched<FileMetadata>, Fetched<StaticFileContent>>, Error> {
- let fetcher_with_metadata = self.file_metadata().await?;
- fetcher_with_metadata.file_content().await
- }
-}
-
-impl StaticFileFetcher<Fetched<FileMetadata>, NoData> {
- #[tracing::instrument(err)]
- pub async fn file_content(
- self,
- ) -> Result<StaticFileFetcher<Fetched<FileMetadata>, Fetched<StaticFileContent>>, Error> {
- let content = self.fetch_content_from_metadata(&self.metadata).await?;
- Ok(StaticFileFetcher {
- content,
- metadata: self.metadata,
- file_id: self.file_id,
- inner_sfs: self.inner_sfs,
- })
- }
-}
-
-impl<T> StaticFileFetcher<Fetched<FileMetadata>, T> {
- pub fn metadata(&self) -> &FileMetadata {
- &self.metadata
- }
-
- pub fn content_type(&self) -> Result<ContentType, Error> {
- ContentType::from_str(&self.metadata.content_type)
- .map_err(|_| anyhow::anyhow!("Invalid content type: {}", self.metadata.content_type))
- }
-}
-
-// -- internal util / fetching logic --
-impl<L: Debug, D: Debug> StaticFileFetcher<L, D> {
- #[tracing::instrument(err)]
- async fn fetch_content_from_metadata(
- &self,
- metadata: &FileMetadata,
- ) -> Result<StaticFileContent, Error> {
- let content_type =
- ContentType::from_str(&metadata.content_type).unwrap_or(ContentType::Default);
-
- let file_data = self
- .inner_sfs
- .read_file(&self.file_id)
- .await
- .context("Failed to read file data")?;
-
- let data = if content_type.is_image() {
- Data::Binary(file_data)
- } else if content_type.is_text_content() {
- let text = String::from_utf8(file_data.to_vec())
- .context("Failed to convert file data to text")?;
- Data::Text(text)
- } else {
- Data::Binary(file_data)
- };
-
- Ok(StaticFileContent {
- data,
- file_id: metadata.file_id.clone(),
- content_type,
- metadata: metadata.clone(),
- })
- }
-}
-
-// -- internal helper --
-
-impl<L, D> Debug for StaticFileFetcher<L, D>
-where
- L: Debug,
- D: Debug,
-{
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- f.debug_struct("StaticFileFetcher")
- .field("metadata", &self.metadata)
- .field("content", &self.content)
- .field("file_id", &self.file_id)
- .finish()
- }
-}
diff --git a/rust/cloud-storage/scribe/src/static_file/mod.rs b/rust/cloud-storage/scribe/src/static_file/mod.rs
deleted file mode 100644
index c68a3ac250..0000000000
--- a/rust/cloud-storage/scribe/src/static_file/mod.rs
+++ /dev/null
@@ -1,26 +0,0 @@
-use crate::client::ScribeClient;
-mod client;
-mod fetcher;
-mod types;
-
-pub use client::StaticFileClient;
-pub use fetcher::{NewStaticFileFetcher, StaticFileFetcher};
-use static_file_service_client::StaticFileServiceClient;
-use std::sync::Arc;
-pub use types::{Data, StaticFileContent};
-
-impl<D, C, A, E, S> ScribeClient<D, C, A, E, S> {
- pub fn with_static_file_client<T: Into<Arc<StaticFileServiceClient>>>(
- self,
- static_file: T,
- ) -> ScribeClient<D, C, A, E, StaticFileClient> {
- let client = StaticFileClient::new(static_file.into());
- ScribeClient {
- document: self.document,
- channel: self.channel,
- chat: self.chat,
- email: self.email,
- static_file: client,
- }
- }
-}
diff --git a/rust/cloud-storage/scribe/src/static_file/types.rs b/rust/cloud-storage/scribe/src/static_file/types.rs
deleted file mode 100644
index 389ff09294..0000000000
--- a/rust/cloud-storage/scribe/src/static_file/types.rs
+++ /dev/null
@@ -1,44 +0,0 @@
-use anyhow::{Error, bail};
-use attachment::image::ImageData;
-use model::document::{ContentType, ContentTypeExt};
-
-use models_sfs::FileMetadata;
-
-pub type Data = crate::document::types::Data;
-
-#[derive(Debug, Clone)]
-pub struct StaticFileContent {
- pub(crate) data: Data,
- pub file_id: String,
- pub content_type: ContentType,
- pub metadata: FileMetadata,
-}
-
-impl TryFrom<StaticFileContent> for ImageData {
- type Error = anyhow::Error;
- fn try_from(value: StaticFileContent) -> Result<Self, Self::Error> {
- if value.content_type.is_image()
- && let Data::Binary(bytes) = value.data
- {
- ImageData::try_from_bytes(bytes.into())
- } else {
- bail!("No conversion to image")
- }
- }
-}
-
-impl StaticFileContent {
- pub fn metadata(&self) -> &FileMetadata {
- &self.metadata
- }
-
- /// stringify content if its mimetype is text and it is not binary
- #[tracing::instrument(err)]
- pub fn text_content(self) -> Result<String, Error> {
- if self.content_type.is_text_content() {
- Ok(self.data.to_string())
- } else {
- bail!("Static file is not text")
- }
- }
-}