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.

move delete_document_worker into DSS (#1859)

Will Hutchinsonf585c9be4df0
diff --git a/.github/services-config.json b/.github/services-config.json
index 61417f8fb6..948d0f8ea3 100644
--- a/.github/services-config.json
+++ b/.github/services-config.json
@@ -31,12 +31,6 @@
],
"stack_path": "infra/stacks/convert-service/**"
},
- "delete-document-worker": {
- "source_paths": [
- "rust/cloud-storage/delete_document_worker/**"
- ],
- "stack_path": "infra/stacks/delete-document-worker/**"
- },
"deleted-item-poller": {
"source_paths": [
"rust/cloud-storage/deleted_item_poller/**"
diff --git a/.github/workflows/deploy-service-generic.yml b/.github/workflows/deploy-service-generic.yml
index 46a2f24cfa..6cf2df1072 100644
--- a/.github/workflows/deploy-service-generic.yml
+++ b/.github/workflows/deploy-service-generic.yml
@@ -12,7 +12,6 @@ on:
- connection-gateway
- contacts-service
- convert-service
- - delete-document-worker
- deleted-item-poller
- dlp-handler
- document-cognition-service
diff --git a/infra/stacks/link-sharing/file-storage-bucket.ts b/infra/stacks/link-sharing/file-storage-bucket.ts
index abb2108efc..171c8eb2d7 100644
--- a/infra/stacks/link-sharing/file-storage-bucket.ts
+++ b/infra/stacks/link-sharing/file-storage-bucket.ts
@@ -41,7 +41,6 @@ export const attachPolicyToBucket = ({
documentProcessingServiceRoleArn,
pdfPreprocessLambdaRoleArn,
documentStorageBucketReplicationRoleArn,
- deleteDocumentWorkerRoleArn,
searchProcessingServiceRoleArn,
bulkUploadLambdaRoleArn,
convertServiceRoleArn,
@@ -56,7 +55,6 @@ export const attachPolicyToBucket = ({
documentProcessingServiceRoleArn: pulumi.Output<string>;
pdfPreprocessLambdaRoleArn: pulumi.Output<string>;
documentStorageBucketReplicationRoleArn: pulumi.Output<string>;
- deleteDocumentWorkerRoleArn: pulumi.Output<string>;
searchProcessingServiceRoleArn: pulumi.Output<string>;
bulkUploadLambdaRoleArn: pulumi.Output<string>;
convertServiceRoleArn: pulumi.Output<string>;
@@ -85,7 +83,6 @@ export const attachPolicyToBucket = ({
documentProcessingServiceRoleArn,
pdfPreprocessLambdaRoleArn,
documentStorageBucketReplicationRoleArn,
- deleteDocumentWorkerRoleArn,
documentTextExtractorArn,
searchProcessingServiceRoleArn,
bulkUploadLambdaRoleArn,
@@ -178,15 +175,6 @@ export const attachPolicyToBucket = ({
Action: ['s3:PutObject'],
Resource: [bucket.arn, pulumi.interpolate`${bucket.arn}/*`],
},
- {
- Sid: 'AllowAccessForDeleteDocumentWorker',
- Effect: 'Allow',
- Principal: {
- AWS: deleteDocumentWorkerRoleArn,
- },
- Action: ['s3:ListBucket', 's3:GetObject', 's3:DeleteObject'],
- Resource: [bucket.arn, pulumi.interpolate`${bucket.arn}/*`],
- },
{
Sid: 'AllowAccessForShaCleanupWorker',
Effect: 'Allow',
diff --git a/infra/stacks/link-sharing/index.ts b/infra/stacks/link-sharing/index.ts
index 23e84dbc33..7a681ca949 100644
--- a/infra/stacks/link-sharing/index.ts
+++ b/infra/stacks/link-sharing/index.ts
@@ -50,13 +50,6 @@ const bulkUploadStack = new pulumi.StackReference('bulk-upload-stack', {
name: `macro-inc/bulk-upload/${stack}`,
});
-const deleteDocumentWorkerStack = new pulumi.StackReference(
- 'delete-document-worker-stack',
- {
- name: `macro-inc/delete-document-worker/${stack}`,
- }
-);
-
export const searchProcessingServiceRoleArn: pulumi.Output<string> =
searchProcessingStack
.getOutput('searchProcessingServiceRoleArn')
@@ -93,11 +86,6 @@ const docxUnzipRoleArn: pulumi.Output<string> = cloudStorageServiceStack
.getOutput('docxUnzipHandlerRoleArn')
.apply((arn) => arn as string);
-const deleteDocumentWorkerRoleArn: pulumi.Output<string> =
- deleteDocumentWorkerStack
- .getOutput('deleteDocumentWorkerRoleArn')
- .apply((arn) => arn as string);
-
const shaCleanupWorkerArn: pulumi.Output<string> = shaCleanupStack
.getOutput('shaCleanupWorkerRoleArn')
.apply((shaCleanupWorkerArn) => shaCleanupWorkerArn as string);
@@ -154,7 +142,6 @@ export const bucketPolicy = attachPolicyToBucket({
documentProcessingServiceRoleArn,
pdfPreprocessLambdaRoleArn,
documentStorageBucketReplicationRoleArn,
- deleteDocumentWorkerRoleArn,
documentTextExtractorArn,
searchProcessingServiceRoleArn,
bulkUploadLambdaRoleArn,
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 430268a810..9b2fa84ce8 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -2638,41 +2638,6 @@ dependencies = [
"tracing",
]
-[[package]]
-name = "delete_document_worker"
-version = "0.1.0"
-dependencies = [
- "anyhow",
- "aws-sdk-s3",
- "aws-sdk-secretsmanager",
- "aws-sdk-sqs",
- "axum",
- "chrono",
- "comms_db_client",
- "futures",
- "macro_aws_config",
- "macro_cors",
- "macro_db_client",
- "macro_entrypoint",
- "macro_env",
- "macro_sha_count_client",
- "model",
- "models_properties",
- "openssl",
- "properties_db_client",
- "redis",
- "s3_client",
- "secretsmanager_client",
- "serde",
- "sqlx",
- "sqs_worker",
- "sync_service_client",
- "tokio",
- "tower 0.5.2",
- "tower-http",
- "tracing",
-]
-
[[package]]
name = "deleted_item_poller"
version = "0.1.0"
@@ -2976,6 +2941,7 @@ dependencies = [
"opensearch_client",
"ordered-float",
"properties",
+ "properties_db_client",
"properties_service",
"rayon",
"redis",
@@ -2990,6 +2956,7 @@ dependencies = [
"soup",
"sqlx",
"sqs_client",
+ "sqs_worker",
"sync_service_client",
"system_properties",
"thiserror 2.0.17",
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index 1279dba9f7..7d9947b978 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -22,7 +22,6 @@ members = [
"cowlike",
"dataloss_prevention_handler",
"delete_chat_handler",
- "delete_document_worker",
"deleted_item_poller",
"document_cognition_service",
"document_cognition_service_client",
diff --git a/rust/cloud-storage/delete_document_worker/Cargo.toml b/rust/cloud-storage/delete_document_worker/Cargo.toml
deleted file mode 100644
index 976a7b0325..0000000000
--- a/rust/cloud-storage/delete_document_worker/Cargo.toml
+++ /dev/null
@@ -1,46 +0,0 @@
-[package]
-edition = "2024"
-name = "delete_document_worker"
-publish = false
-version = "0.1.0"
-
-
-[features]
-local_queue = []
-
-[dependencies]
-anyhow = { workspace = true }
-aws-sdk-s3 = { workspace = true }
-macro_aws_config = { path = "../macro_aws_config", features = ["s3"] }
-aws-sdk-secretsmanager = { workspace = true }
-aws-sdk-sqs = { workspace = true }
-axum = { workspace = true }
-chrono = { workspace = true }
-comms_db_client = { path = "../comms_db_client" }
-futures = { workspace = true }
-macro_cors = { path = "../macro_cors" }
-macro_db_client = { path = "../macro_db_client" }
-macro_entrypoint = { path = "../macro_entrypoint" }
-macro_env = { path = "../macro_env" }
-macro_sha_count_client = { path = "../macro_sha_count_client" }
-model = { path = "../model" }
-openssl = { workspace = true }
-redis = { workspace = true, features = [
- "aio",
- "tokio-native-tls-comp",
-] }
-s3_client = { path = "../s3_client" }
-secretsmanager_client = { path = "../secretsmanager_client" }
-serde = { workspace = true }
-sqlx = { workspace = true }
-sqs_worker = { path = "../sqs_worker" }
-sync_service_client = { path = "../sync_service_client" }
-tokio = { workspace = true }
-tower = { workspace = true }
-tower-http = { workspace = true }
-tracing = { workspace = true }
-properties_db_client = { path = "../properties_db_client" }
-models_properties = { path = "../models_properties" }
-
-[package.metadata.cargo-machete]
-ignored = ["openssl"]
diff --git a/rust/cloud-storage/delete_document_worker/justfile b/rust/cloud-storage/delete_document_worker/justfile
deleted file mode 100644
index 6ff97f9626..0000000000
--- a/rust/cloud-storage/delete_document_worker/justfile
+++ /dev/null
@@ -1,16 +0,0 @@
-mod ci '../ci.just'
-
-deploy-dev:
- just ci::deploy-dev delete-document-worker
-
-check:
- SQLX_OFFLINE=true cargo check
-
-create-localstack:
- docker run -d --name localstack -p 4566:4566 -e SERVICES=sqs localstack/localstack
-
-start-localstack:
- docker run -p 4566:4566 -e SERVICES=sqs localstack/localstack
-
-create-queue:
- AWS_REGION=us-east-1 aws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name delete_document_queue
diff --git a/rust/cloud-storage/delete_document_worker/src/api/health.rs b/rust/cloud-storage/delete_document_worker/src/api/health.rs
deleted file mode 100644
index baba37632a..0000000000
--- a/rust/cloud-storage/delete_document_worker/src/api/health.rs
+++ /dev/null
@@ -1,11 +0,0 @@
-use axum::{Json, Router, http::StatusCode, response::IntoResponse, routing::get};
-use model::response::EmptyResponse;
-
-/// Health check
-pub async fn health_handler() -> impl IntoResponse {
- (StatusCode::OK, Json(EmptyResponse::default()))
-}
-
-pub fn router() -> Router {
- Router::new().route("/health", get(health_handler))
-}
diff --git a/rust/cloud-storage/delete_document_worker/src/api/mod.rs b/rust/cloud-storage/delete_document_worker/src/api/mod.rs
deleted file mode 100644
index ad4ea399f2..0000000000
--- a/rust/cloud-storage/delete_document_worker/src/api/mod.rs
+++ /dev/null
@@ -1,27 +0,0 @@
-use crate::config::Config;
-use anyhow::Context;
-use axum::Router;
-
-mod health;
-
-pub async fn setup_and_serve(config: &Config) -> anyhow::Result<()> {
- let cors = macro_cors::cors_layer();
-
- let app = api_router().merge(health::router()).layer(cors.clone());
-
- let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", config.port))
- .await
- .unwrap();
- tracing::info!(
- "notification service is up and running with environment {:?} on port {}",
- &config.environment,
- &config.port
- );
- axum::serve(listener, app.into_make_service())
- .await
- .context("error starting service")
-}
-
-fn api_router() -> Router {
- Router::new()
-}
diff --git a/rust/cloud-storage/delete_document_worker/src/config.rs b/rust/cloud-storage/delete_document_worker/src/config.rs
deleted file mode 100644
index 3fdead4700..0000000000
--- a/rust/cloud-storage/delete_document_worker/src/config.rs
+++ /dev/null
@@ -1,79 +0,0 @@
-use anyhow::Context;
-pub use macro_env::Environment;
-
-#[derive(Debug, Clone)]
-pub struct Config {
- /// The connection URL for the Postgres database this application should use.
- pub database_url: String,
-
- /// The connection URI for the redis cluster this application should use.
- pub redis_uri: String,
-
- /// The document storage s3 bucket
- pub document_storage_bucket: String,
-
- /// The queue to use for the delete document worker
- pub delete_document_queue: String,
- pub queue_max_messages: i32,
- pub queue_wait_time_seconds: i32,
-
- /// The environment we are in
- pub environment: Environment,
-
- pub port: usize,
-
- /// API key for sync service
- pub sync_service_auth_key: String,
-
- /// sync service URL
- pub sync_service_url: String,
-}
-
-impl Config {
- pub fn from_env() -> anyhow::Result<Self> {
- let database_url =
- std::env::var("DATABASE_URL").context("DATABASE_URL must be provided")?;
- let redis_uri = std::env::var("REDIS_URI").context("REDIS_URI must be provided")?;
- let document_storage_bucket = std::env::var("DOCUMENT_STORAGE_BUCKET")
- .context("DOCUMENT_STORAGE_BUCKET must be provided")?;
-
- let delete_document_queue = std::env::var("DELETE_DOCUMENT_QUEUE")
- .context("DELETE_DOCUMENT_QUEUE must be provided")?;
-
- let queue_max_messages: i32 = std::env::var("QUEUE_MAX_MESSAGES")
- .unwrap_or("10".to_string())
- .parse::<i32>()
- .unwrap();
-
- let queue_wait_time_seconds: i32 = std::env::var("QUEUE_WAIT_TIME_SECONDS")
- .unwrap_or("4".to_string())
- .parse::<i32>()
- .unwrap();
-
- let environment = Environment::new_or_prod();
-
- let port = std::env::var("PORT")
- .unwrap_or("8080".to_string())
- .parse::<usize>()
- .context("PORT must be a valid number")?;
-
- let sync_service_auth_key = std::env::var("SYNC_SERVICE_AUTH_KEY")
- .context("SYNC_SERVICE_AUTH_KEY must be provided")?;
-
- let sync_service_url =
- std::env::var("SYNC_SERVICE_URL").context("SYNC_SERVICE_URL must be provided")?;
-
- Ok(Config {
- database_url,
- redis_uri,
- document_storage_bucket,
- queue_max_messages,
- queue_wait_time_seconds,
- environment,
- port,
- delete_document_queue,
- sync_service_auth_key,
- sync_service_url,
- })
- }
-}
diff --git a/rust/cloud-storage/delete_document_worker/src/context.rs b/rust/cloud-storage/delete_document_worker/src/context.rs
deleted file mode 100644
index 9a697b1ccb..0000000000
--- a/rust/cloud-storage/delete_document_worker/src/context.rs
+++ /dev/null
@@ -1,15 +0,0 @@
-use std::sync::Arc;
-
-use macro_sha_count_client::Redis;
-
-use crate::config::Config;
-
-#[derive(Clone)]
-pub struct QueueWorkerContext {
- pub worker: Arc<sqs_worker::SQSWorker>,
- pub db: sqlx::Pool<sqlx::Postgres>,
- pub s3_client: Arc<s3_client::S3>,
- pub redis_client: Arc<Redis>,
- pub sync_service_client: Arc<sync_service_client::SyncServiceClient>,
- pub config: Config,
-}
diff --git a/rust/cloud-storage/delete_document_worker/src/main.rs b/rust/cloud-storage/delete_document_worker/src/main.rs
deleted file mode 100644
index c73a9a0a7e..0000000000
--- a/rust/cloud-storage/delete_document_worker/src/main.rs
+++ /dev/null
@@ -1,97 +0,0 @@
-#![recursion_limit = "256"]
-use anyhow::Context;
-use config::{Config, Environment};
-use macro_entrypoint::MacroEntrypoint;
-use macro_sha_count_client::Redis;
-use secretsmanager_client::SecretManager;
-use sqlx::postgres::PgPoolOptions;
-use std::sync::Arc;
-
-use crate::context::QueueWorkerContext;
-
-mod api;
-mod config;
-mod context;
-mod process;
-
-#[tokio::main]
-pub async fn main() -> anyhow::Result<()> {
- MacroEntrypoint::default().init();
- // Parse our configuration from the environment.
- let config = Config::from_env().context("expected to be able to generate config")?;
-
- tracing::trace!("initialized config");
-
- let (min_connections, max_connections): (u32, u32) = match config.environment {
- Environment::Production => (1, 30),
- Environment::Develop => (1, 25),
- Environment::Local => (1, 10),
- };
-
- let db = PgPoolOptions::new()
- .min_connections(min_connections)
- .max_connections(max_connections)
- .connect(&config.database_url)
- .await
- .context("could not connect to db")?;
-
- tracing::trace!(
- min_connections,
- max_connections,
- "initialized db connection"
- );
-
- let aws_config = macro_aws_config::get_macro_aws_config().await;
-
- let s3_client = s3_client::S3::new(macro_aws_config::s3_client().await);
-
- let delete_document_worker = sqs_worker::SQSWorker::new(
- aws_sdk_sqs::Client::new(&aws_config),
- config.delete_document_queue.clone(),
- config.queue_max_messages,
- config.queue_wait_time_seconds,
- );
-
- let redis_client = redis::Client::open(config.redis_uri.clone())
- .map_err(|e| anyhow::Error::msg(format!("unable to connect to redis {:?}", e)))
- .context("could not connect to redis client")?;
- if let Err(e) = redis_client.get_connection() {
- tracing::error!(error=?e, "unable to connect to redis");
- return Err(e.into());
- }
- let redis_client = Redis::new(redis_client);
-
- let secretsmanager_client = secretsmanager_client::SecretsManager::new(
- aws_sdk_secretsmanager::Client::new(&aws_config),
- );
-
- let sync_service_auth_key = match config.environment {
- Environment::Local => config.sync_service_auth_key.clone(),
- _ => secretsmanager_client
- .get_secret_value(&config.sync_service_auth_key)
- .await
- .context("unable to get secret")?
- .to_string(),
- };
-
- let sync_service_client = sync_service_client::SyncServiceClient::new(
- sync_service_auth_key,
- config.sync_service_url.clone(),
- );
-
- let queue_worker_context = QueueWorkerContext {
- db: db.clone(),
- worker: Arc::new(delete_document_worker),
- s3_client: Arc::new(s3_client),
- redis_client: Arc::new(redis_client),
- sync_service_client: Arc::new(sync_service_client),
- config: config.clone(),
- };
-
- // Spawn the runner in a task of it's own so we don't block the main thread
- tokio::spawn(async move { process::run_worker(queue_worker_context).await });
-
- api::setup_and_serve(&config).await?;
-
- Ok(())
-}
diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.toml
index da266551b7..1ac1b56237 100644
--- a/rust/cloud-storage/document_storage_service/Cargo.toml
+++ b/rust/cloud-storage/document_storage_service/Cargo.toml
@@ -103,6 +103,7 @@ models_soup = { path = "../models_soup", features = ["schema"] }
notification = { path = "../notification" }
opensearch_client = { path = "../opensearch_client" }
properties = { path = "../properties" }
+properties_db_client = { path = "../properties_db_client" }
properties_service = { path = "../properties_service" }
rayon = "1.10.0"
redis = { workspace = true, features = [
@@ -125,6 +126,7 @@ sqs_client = { path = "../sqs_client", default-features = false, features = [
"document",
"search",
] }
+sqs_worker = { path = "../sqs_worker" }
sync_service_client = { path = "../sync_service_client" }
system_properties = { path = "../system_properties" }
thiserror = { workspace = true }
diff --git a/rust/cloud-storage/document_storage_service/src/config.rs b/rust/cloud-storage/document_storage_service/src/config.rs
index 65f44c0bc6..9d5de7f8d1 100644
--- a/rust/cloud-storage/document_storage_service/src/config.rs
+++ b/rust/cloud-storage/document_storage_service/src/config.rs
@@ -18,6 +18,11 @@ pub struct Config {
/// The environment we are in
pub environment: Environment,
+ /// Maximum number of SQS messages to receive per poll for the delete document worker
+ pub queue_max_messages: i32,
+ /// SQS long-poll wait time in seconds for the delete document worker
+ pub queue_wait_time_seconds: i32,
+
/// The document limit for free users
pub document_limit: u64,
@@ -106,12 +111,24 @@ impl Config {
.and_then(|v| v.as_ref().parse::<u64>().ok())
.unwrap_or(DEFAULT_PRESIGNED_URL_BROWSER_CACHE_EXPIRY_SECONDS);
+ let queue_max_messages: i32 = std::env::var("QUEUE_MAX_MESSAGES")
+ .unwrap_or("10".to_string())
+ .parse()
+ .unwrap_or(10);
+
+ let queue_wait_time_seconds: i32 = std::env::var("QUEUE_WAIT_TIME_SECONDS")
+ .unwrap_or("4".to_string())
+ .parse()
+ .unwrap_or(4);
+
let vars = EnvVars::new()?;
Ok(Config {
vars,
port,
environment,
+ queue_max_messages,
+ queue_wait_time_seconds,
document_limit,
document_storage_service_presigned_url_expiry_seconds,
document_storage_service_presigned_url_browser_cache_expiry_seconds,
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index 16e0720331..73deb63c32 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -352,6 +352,14 @@ async fn main() -> anyhow::Result<()> {
GithubSyncClientImpl::default(),
);
+ // Create the SQS worker for delete document processing before config is moved
+ let delete_document_worker = sqs_worker::SQSWorker::new(
+ aws_sdk_sqs::Client::new(&aws_config),
+ config.vars.document_delete_queue.as_ref().to_string(),
+ config.queue_max_messages,
+ config.queue_wait_time_seconds,
+ );
+
let api_context = ApiContext {
soup_router_state: SoupRouterState::new(
SoupImpl::new(
@@ -394,6 +402,19 @@ async fn main() -> anyhow::Result<()> {
),
};
+ // Spawn the delete document worker
+ let delete_worker_ctx = service::delete_document_worker::DeleteDocumentWorkerContext {
+ worker: Arc::new(delete_document_worker),
+ db: db.clone(),
+ s3_client: api_context.s3_client.clone(),
+ redis_client: api_context.redis_client.clone(),
+ sync_service_client: api_context.sync_service_client.clone(),
+ };
+
+ tokio::spawn(async move {
+ service::delete_document_worker::run_worker(delete_worker_ctx).await;
+ });
+
api::setup_and_serve(api_context).await?;
Ok(())
diff --git a/rust/cloud-storage/delete_document_worker/src/process/handle.rs b/rust/cloud-storage/document_storage_service/src/service/delete_document_worker/handle.rs
similarity index 74%
rename from rust/cloud-storage/delete_document_worker/src/process/handle.rs
rename to rust/cloud-storage/document_storage_service/src/service/delete_document_worker/handle.rs
index 82e4779f41..2555aee612 100644
--- a/rust/cloud-storage/delete_document_worker/src/process/handle.rs
+++ b/rust/cloud-storage/document_storage_service/src/service/delete_document_worker/handle.rs
@@ -2,18 +2,23 @@ use anyhow::Context;
use models_properties::{EntityReference, EntityType};
use properties_db_client::entity_properties::delete as entity_properties_delete;
-#[tracing::instrument(skip(ctx, message), fields(message_id=message.message_id))]
+use super::DeleteDocumentWorkerContext;
+
+#[tracing::instrument(skip(ctx, message), fields(message_id=message.message_id), err)]
pub async fn handle(
- ctx: &crate::context::QueueWorkerContext,
+ ctx: &DeleteDocumentWorkerContext,
message: &aws_sdk_sqs::types::Message,
) -> anyhow::Result<()> {
- tracing::debug!("processing message");
+ tracing::debug!("processing delete document message");
let (document_id, mut user_id) = if let Some(attributes) = message.message_attributes.as_ref() {
- let document_id = attributes.get("document_id").map(|document_id| {
- tracing::trace!(document_id=?document_id, "found document_id in message attributes");
- document_id.string_value().unwrap_or_default()
- }).context("document_id should be a message attribute")?;
+ let document_id = attributes
+ .get("document_id")
+ .map(|document_id| {
+ tracing::trace!(document_id=?document_id, "found document_id in message attributes");
+ document_id.string_value().unwrap_or_default()
+ })
+ .context("document_id should be a message attribute")?;
let user_id = attributes.get("user_id").map(|user_id| {
tracing::trace!(user_id=?user_id, "found user_id in message attributes");
@@ -77,15 +82,13 @@ pub async fn handle(
let user_id = user_id.context("user_id should be some")?;
- let folder = format!("{user_id}/{document_id}");
-
// Delete files from s3
- tracing::trace!(folder=%folder, "deleting files from s3");
+ tracing::trace!(user_id=%user_id, document_id=%document_id, "deleting files from s3");
ctx.s3_client
- .delete_folder(&ctx.config.document_storage_bucket, &folder)
+ .delete_document(&user_id, document_id)
.await
.context("failed to delete files from s3")?;
- tracing::trace!(folder=%folder, "deleted files from s3");
+ tracing::trace!(document_id=%document_id, "deleted files from s3");
// Delete files from sync service
let _ = ctx
@@ -112,47 +115,17 @@ pub async fn handle(
Ok(())
}
-pub fn count_occurrences(strings: Vec<String>) -> Vec<(String, i64)> {
+pub(crate) fn count_occurrences(strings: Vec<String>) -> Vec<(String, i64)> {
use std::collections::HashMap;
let mut counts = HashMap::new();
- // Count each SHA's occurrences
for string in strings {
*counts.entry(string).or_insert(0) += 1;
}
- // Convert the HashMap into a Vec of tuples
counts
.into_iter()
.map(|(string, count)| (string, count as i64))
.collect()
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn test_count_occurences() {
- let shas = vec![
- "a1b2c3".to_string(),
- "d4e5f6".to_string(),
- "a1b2c3".to_string(),
- "g7h8i9".to_string(),
- "a1b2c3".to_string(),
- "d4e5f6".to_string(),
- ];
-
- let mut result = count_occurrences(shas);
- result.sort();
- assert_eq!(
- result,
- vec![
- ("a1b2c3".to_string(), 3),
- ("d4e5f6".to_string(), 2),
- ("g7h8i9".to_string(), 1),
- ]
- );
- }
-}
diff --git a/rust/cloud-storage/delete_document_worker/src/process/mod.rs b/rust/cloud-storage/document_storage_service/src/service/delete_document_worker/mod.rs
similarity index 55%
rename from rust/cloud-storage/delete_document_worker/src/process/mod.rs
rename to rust/cloud-storage/document_storage_service/src/service/delete_document_worker/mod.rs
index f3b4f9d1d4..5385144fda 100644
--- a/rust/cloud-storage/delete_document_worker/src/process/mod.rs
+++ b/rust/cloud-storage/document_storage_service/src/service/delete_document_worker/mod.rs
@@ -1,50 +1,62 @@
-use crate::context::QueueWorkerContext;
+use std::sync::Arc;
+
+use macro_sha_count_client::Redis;
+use sync_service_client::SyncServiceClient;
+
+use crate::service::s3::S3;
mod handle;
+#[cfg(test)]
+mod test;
-/// Runs the worker in a loop to handle restarting should it fail.
-pub async fn run_worker(context: QueueWorkerContext) {
+/// Context for the delete document worker, holding all clients needed to process deletions.
+#[derive(Clone)]
+pub struct DeleteDocumentWorkerContext {
+ pub worker: Arc<sqs_worker::SQSWorker>,
+ pub db: sqlx::Pool<sqlx::Postgres>,
+ pub s3_client: Arc<S3>,
+ pub redis_client: Arc<Redis>,
+ pub sync_service_client: Arc<SyncServiceClient>,
+}
+
+/// Runs the delete document worker in an infinite loop, restarting on failure.
+pub async fn run_worker(ctx: DeleteDocumentWorkerContext) {
loop {
let worker_result = tokio::spawn({
- let context = context.clone();
+ let ctx = ctx.clone();
async move {
- tracing::info!("worker started");
+ tracing::info!("delete document worker started");
loop {
- match context.worker.receive_messages().await {
+ match ctx.worker.receive_messages().await {
Ok(messages) => {
if messages.is_empty() {
continue;
}
let tasks = messages.clone().into_iter().map(|message| {
- let context = context.clone();
+ let ctx = ctx.clone();
tokio::spawn(async move {
- let result = handle::handle(&context, &message).await;
+ let result = handle::handle(&ctx, &message).await;
if let Err(e) = &result {
- tracing::error!(message_id=?message.message_id, error=?e, "error processing message");
+ tracing::error!(message_id=?message.message_id, error=?e, "error processing delete document message");
}
result
})
});
- // Collect all tasks into a Vec
let handles: Vec<_> = tasks.collect();
-
- // Await all tasks to complete
let results = futures::future::join_all(handles).await;
- // Process results if needed
for result in results {
- // Handle JoinError (if the task panicked)
if let Err(join_err) = result {
- tracing::error!(error=?join_err, "task join error");
+ tracing::error!(error=?join_err, "delete document task join error");
}
}
}
Err(e) => {
- tracing::error!(error=?e, "error receiving messages");
+ tracing::error!(error=?e, "error receiving delete document messages");
}
}
}
@@ -54,16 +66,14 @@ pub async fn run_worker(context: QueueWorkerContext) {
match worker_result {
Ok(_) => {
- // This should never be hit
- tracing::error!("worker exited successfully?");
+ tracing::error!("delete document worker exited successfully?");
}
Err(e) => {
- tracing::error!(error=?e, "worker crashed with error");
+ tracing::error!(error=?e, "delete document worker crashed with error");
}
}
- // Add a delay before restarting to avoid rapid restart loops
- tracing::info!("WORKER RESTARTING...");
+ tracing::info!("DELETE DOCUMENT WORKER RESTARTING...");
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
}
}
diff --git a/rust/cloud-storage/document_storage_service/src/service/delete_document_worker/test.rs b/rust/cloud-storage/document_storage_service/src/service/delete_document_worker/test.rs
new file mode 100644
index 0000000000..c3b3b3b873
--- /dev/null
+++ b/rust/cloud-storage/document_storage_service/src/service/delete_document_worker/test.rs
@@ -0,0 +1,24 @@
+use super::handle::count_occurrences;
+
+#[test]
+fn test_count_occurrences() {
+ let shas = vec![
+ "a1b2c3".to_string(),
+ "d4e5f6".to_string(),
+ "a1b2c3".to_string(),
+ "g7h8i9".to_string(),
+ "a1b2c3".to_string(),
+ "d4e5f6".to_string(),
+ ];
+
+ let mut result = count_occurrences(shas);
+ result.sort();
+ assert_eq!(
+ result,
+ vec![
+ ("a1b2c3".to_string(), 3),
+ ("d4e5f6".to_string(), 2),
+ ("g7h8i9".to_string(), 1),
+ ]
+ );
+}
diff --git a/rust/cloud-storage/document_storage_service/src/service/mod.rs b/rust/cloud-storage/document_storage_service/src/service/mod.rs
index fc0e82a88f..6d635845c7 100644
--- a/rust/cloud-storage/document_storage_service/src/service/mod.rs
+++ b/rust/cloud-storage/document_storage_service/src/service/mod.rs
@@ -1,2 +1,3 @@
pub mod conn_gateway;
+pub mod delete_document_worker;
pub mod s3;