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.

chore: deprecate legacy s3 key (#2209)

gbirmand62401afd455
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 1593061dab..23262db6ec 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -2294,6 +2294,7 @@ dependencies = [
"remote_env_var",
"rs-libreoffice-bindings",
"s3_client",
+ "s3_key",
"secretsmanager_client",
"serde",
"serde_json",
@@ -3047,6 +3048,7 @@ dependencies = [
"redis",
"regex",
"reqwest",
+ "s3_key",
"saved_views",
"schemars",
"search_service",
@@ -3116,6 +3118,7 @@ dependencies = [
"model",
"openssl",
"pdfium-render",
+ "s3_key",
"serde",
"serde_json",
"sqlx",
@@ -3158,6 +3161,7 @@ dependencies = [
"models_permissions",
"models_properties",
"reqwest",
+ "s3_key",
"schemars",
"serde",
"serde_json",
@@ -3198,6 +3202,7 @@ dependencies = [
"openssl",
"redis",
"s3_client",
+ "s3_key",
"serde",
"serde_json",
"sha2",
@@ -3301,6 +3306,7 @@ dependencies = [
"macro_aws_config",
"model",
"models_bulk_upload",
+ "s3_key",
"strum",
"thiserror 2.0.17",
"tokio",
@@ -8584,6 +8590,14 @@ dependencies = [
"tracing",
]
+[[package]]
+name = "s3_key"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "urlencoding",
+]
+
[[package]]
name = "same-file"
version = "1.0.6"
@@ -8767,6 +8781,7 @@ dependencies = [
"pdfium-render",
"rust-embed",
"s3_client",
+ "s3_key",
"secretsmanager_client",
"serde",
"serde_json",
@@ -8852,12 +8867,11 @@ dependencies = [
"lambda_runtime",
"macro_aws_config",
"macro_entrypoint",
- "model_file_type",
"openssl",
+ "s3_key",
"sqs_client",
"tokio",
"tracing",
- "urlencoding",
]
[[package]]
@@ -9768,6 +9782,7 @@ dependencies = [
"model",
"models_email",
"models_opensearch",
+ "s3_key",
"serde",
"serde_json",
"strum",
@@ -9822,6 +9837,7 @@ dependencies = [
"macro_middleware",
"model",
"models_sfs",
+ "s3_key",
"secretsmanager_client",
"serde",
"serde_dynamo",
@@ -10787,6 +10803,7 @@ dependencies = [
"macro_entrypoint",
"models_bulk_upload",
"openssl",
+ "s3_key",
"serde",
"serde_json",
"sqs_client",
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index e7796d65da..16f66c1c00 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -105,6 +105,7 @@ members = [
"rpc/axum_rpc_emit",
"rpc/axum_rpc_parse",
"s3_client",
+ "s3_key",
"scribe",
"search_processing_service",
"search_service",
diff --git a/rust/cloud-storage/convert_service/Cargo.toml b/rust/cloud-storage/convert_service/Cargo.toml
index 475b014838..f0c5e84024 100644
--- a/rust/cloud-storage/convert_service/Cargo.toml
+++ b/rust/cloud-storage/convert_service/Cargo.toml
@@ -29,6 +29,7 @@ macro_middleware = { path = "../macro_middleware", default-features = false, fea
] }
macro_uuid = { path = "../macro_uuid" }
model = { path = "../model" }
+s3_key = { path = "../s3_key" }
nix = { version = "0.29.0", features = ["process", "signal"] }
remote_env_var = { path = "../remote_env_var" }
rs-libreoffice-bindings = "0.0.7"
diff --git a/rust/cloud-storage/convert_service/src/api/backfill/backfill_docx.rs b/rust/cloud-storage/convert_service/src/api/backfill/backfill_docx.rs
index f66985adc7..ce0f531c77 100644
--- a/rust/cloud-storage/convert_service/src/api/backfill/backfill_docx.rs
+++ b/rust/cloud-storage/convert_service/src/api/backfill/backfill_docx.rs
@@ -13,16 +13,14 @@ use axum::{
use futures::StreamExt;
use model::{
convert::ConvertQueueMessage,
- document::{BomPart, BomPartWithContent, CONVERTED_DOCUMENT_FILE_NAME, DocumentMetadata},
+ document::{BomPart, BomPartWithContent, DocumentMetadata},
request::pagination::{Pagination, PaginationQueryParams},
response::ErrorResponse,
};
+use s3_key::{build_docx_to_pdf_converted_document_key, build_temp_docx_key};
use crate::api::context::ApiContext;
-/// All files in temp_files automatically get removed from document storage bucket after 1 day
-static BULK_DOCX_CONVERT_PREFIX: &str = "temp_files";
-
/// Backfill docx all
#[utoipa::path(
post,
@@ -117,9 +115,9 @@ async fn process_docx(
serde_json::from_value(bom_parts).context("unable to serialize bom parts")?;
// check if the converted item exists in s3
- let key = format!(
- "{}/{}/{}.pdf",
- document.owner, document.document_id, CONVERTED_DOCUMENT_FILE_NAME
+ let key = build_docx_to_pdf_converted_document_key(
+ document.owner.as_ref(),
+ &document.document_id,
);
let exists = s3_client
@@ -169,10 +167,10 @@ async fn process_docx(
let zipped_docx = zip_bom_parts(bom_parts_with_content).await?;
- let from_key = format!("{}/{}.docx", BULK_DOCX_CONVERT_PREFIX, document.document_id);
- let to_key = format!(
- "{}/{}/{}.pdf",
- document.owner, document.document_id, CONVERTED_DOCUMENT_FILE_NAME
+ let from_key = build_temp_docx_key(&document.document_id);
+ let to_key = build_docx_to_pdf_converted_document_key(
+ document.owner.as_ref(),
+ &document.document_id,
);
s3_client
diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.toml
index d0af8058aa..6848f69be2 100644
--- a/rust/cloud-storage/document_storage_service/Cargo.toml
+++ b/rust/cloud-storage/document_storage_service/Cargo.toml
@@ -91,6 +91,7 @@ macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
mockall = { workspace = true }
model = { path = "../model" }
+s3_key = { path = "../s3_key" }
model-entity = { path = "../model-entity" }
model_notifications = { path = "../model_notifications" }
model_user = { path = "../model_user", features = ["axum"] }
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/copy_document_v2.rs b/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/copy_document_v2.rs
index e8eed9e028..0ea40698e0 100644
--- a/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/copy_document_v2.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/copy_document_v2.rs
@@ -1,4 +1,4 @@
-use crate::{api::context::ApiContext, service::s3::S3};
+use crate::api::context::ApiContext;
use axum::{http::StatusCode, response::Response};
use document_sub_type::DocumentSubType;
use macro_db_client::history::upsert_user_history;
@@ -7,35 +7,13 @@ use macro_user_id::user_id::MacroUserIdStr;
use model::document::response::{DocumentResponse, DocumentResponseMetadata};
use model::{document::FileTypeExt, sync_service::SyncServiceVersionID};
use model::{
- document::{
- BomPart, CONVERTED_DOCUMENT_FILE_NAME, DocumentMetadata, FileType,
- build_cloud_storage_bucket_document_key, build_extensionless_document_key,
- },
+ document::{BomPart, DocumentMetadata, FileType},
response::GenericResponse,
};
use models_permissions::share_permission::SharePermissionV2;
+use s3_key::{build_cloud_storage_bucket_document_key, build_docx_to_pdf_converted_document_key};
use system_properties::SystemPropertiesService;
-async fn resolve_source_key(
- s3_client: &S3,
- owner: &str,
- document_id: &str,
- document_version_id: i64,
- file_type_str: Option<&str>,
-) -> anyhow::Result<String> {
- let extensionless = build_extensionless_document_key(owner, document_id, document_version_id);
- if s3_client.exists(&extensionless).await? {
- Ok(extensionless)
- } else {
- Ok(build_cloud_storage_bucket_document_key(
- owner,
- document_id,
- document_version_id,
- file_type_str,
- ))
- }
-}
-
#[tracing::instrument(skip(ctx))]
pub async fn copy_document<'a>(
ctx: &'a ApiContext,
@@ -94,16 +72,14 @@ pub async fn copy_document<'a>(
// we need to also copy this over into the new dss file
let url_encoded_owner = urlencoding::encode(original_document_metadata.owner.as_ref());
// Get the source document key
- let source_key = format!(
- "{}/{}/{}.pdf",
- url_encoded_owner,
- original_document_metadata.document_id,
- CONVERTED_DOCUMENT_FILE_NAME
+ let source_key = build_docx_to_pdf_converted_document_key(
+ &url_encoded_owner,
+ &original_document_metadata.document_id,
);
- let dest_key = format!(
- "{}/{}/{}.pdf",
- user_id, updated_document_metadata.document_id, CONVERTED_DOCUMENT_FILE_NAME
+ let dest_key = build_docx_to_pdf_converted_document_key(
+ user_id.as_ref(),
+ &updated_document_metadata.document_id,
);
if let Err(e) = ctx.s3_client.copy_document(&source_key, &dest_key).await {
@@ -153,30 +129,17 @@ pub async fn copy_document<'a>(
})?
.0;
- let file_type_str = file_type.map(|s| s.as_str());
-
- let dest_key = build_extensionless_document_key(
+ let dest_key = build_cloud_storage_bucket_document_key(
user_id.as_ref(),
&updated_document_metadata.document_id,
updated_document_metadata.document_version_id,
);
- let source_key = resolve_source_key(
- &ctx.s3_client,
+ let source_key = build_cloud_storage_bucket_document_key(
original_document_metadata.owner.as_ref(),
&original_document_metadata.document_id,
document_version_id,
- file_type_str,
- )
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "unable to resolve source key");
- (
- Some(updated_document_metadata.document_id.clone()),
- e,
- "unable to resolve source key",
- )
- })?;
+ );
let _ = ctx
.s3_client
@@ -238,30 +201,17 @@ pub async fn copy_document<'a>(
.0
};
- let file_type_str = file_type.map(|s| s.as_str());
-
- let dest_key = build_extensionless_document_key(
+ let dest_key = build_cloud_storage_bucket_document_key(
user_id.as_ref(),
&updated_document_metadata.document_id,
updated_document_metadata.document_version_id,
);
- let source_key = resolve_source_key(
- &ctx.s3_client,
+ let source_key = build_cloud_storage_bucket_document_key(
original_document_metadata.owner.as_ref(),
&original_document_metadata.document_id,
document_version_id,
- file_type_str,
- )
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "unable to resolve source key");
- (
- Some(updated_document_metadata.document_id.clone()),
- e,
- "unable to resolve source key",
- )
- })?;
+ );
// handle non live collab
ctx.s3_client
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/export_document.rs b/rust/cloud-storage/document_storage_service/src/api/documents/export_document.rs
index d5f1bced00..8923f2e31f 100644
--- a/rust/cloud-storage/document_storage_service/src/api/documents/export_document.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/documents/export_document.rs
@@ -3,7 +3,7 @@ use std::{
str::FromStr,
};
-use crate::{api::context::ApiContext, service::s3::TEMP_FILE_PREFIX};
+use crate::api::context::ApiContext;
use axum::{
Extension, Json,
extract::{Path, State},
@@ -17,6 +17,7 @@ use model::{
response::{ErrorResponse, GenericErrorResponse},
user::UserContext,
};
+use s3_key::build_temp_docx_key;
use models_permissions::share_permission::access_level::ViewAccessLevel;
use serde::{Deserialize, Serialize};
@@ -146,7 +147,7 @@ async fn export_basic_document(
}
async fn export_docx_document(state: &ApiContext, document_id: &str) -> anyhow::Result<String> {
- let docx_key = format!("{TEMP_FILE_PREFIX}/{document_id}.docx");
+ let docx_key = build_temp_docx_key(document_id);
let exists = state.s3_client.exists(&docx_key).await?;
if !exists {
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/get_document_key.rs b/rust/cloud-storage/document_storage_service/src/api/documents/get_document_key.rs
index f44a5eeb93..6b81a5bf34 100644
--- a/rust/cloud-storage/document_storage_service/src/api/documents/get_document_key.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/documents/get_document_key.rs
@@ -5,13 +5,11 @@ use crate::model::response::documents::get::{GetDocumentKeyResponse, GetDocument
use axum::extract::State;
use axum::{Extension, extract::Path, http::StatusCode, response::IntoResponse};
use macro_middleware::cloud_storage::ensure_access::document::DocumentAccessExtractor;
-use model::document::{
- CONVERTED_DOCUMENT_FILE_NAME, FileType, build_cloud_storage_bucket_document_key,
- build_extensionless_document_key,
-};
+use model::document::FileType;
use model::response::GenericErrorResponse;
use model::{document::DocumentBasic, response::GenericResponse, user::UserContext};
use models_permissions::share_permission::access_level::ViewAccessLevel;
+use s3_key::{build_cloud_storage_bucket_document_key, build_docx_to_pdf_converted_document_key};
#[derive(serde::Deserialize)]
pub struct Params {
@@ -79,38 +77,14 @@ pub async fn get_document_key_handler(
}
};
- // Try extensionless key first, fall back to legacy key with extension
- let extensionless_key = build_extensionless_document_key(
+ build_cloud_storage_bucket_document_key(
document_context.owner.as_ref(),
&document_id,
document_version_id,
- );
- let extensionless_exists = match state.s3_client.exists(&extensionless_key).await {
- Ok(exists) => exists,
- Err(e) => {
- tracing::error!(error=?e, "unable to check if extensionless key exists");
- return GenericResponse::builder()
- .message("unable to check document key")
- .is_error(true)
- .send(StatusCode::INTERNAL_SERVER_ERROR);
- }
- };
- if extensionless_exists {
- extensionless_key
- } else {
- build_cloud_storage_bucket_document_key(
- document_context.owner.as_ref(),
- &document_id,
- document_version_id,
- Some(file_type.as_str()),
- )
- }
+ )
}
FileType::Docx => {
- format!(
- "{}/{}/{}.pdf",
- document_context.owner, document_id, CONVERTED_DOCUMENT_FILE_NAME
- )
+ build_docx_to_pdf_converted_document_key(document_context.owner.as_ref(), &document_id)
}
_ => {
tracing::error!("invalid file type");
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/initialize_user_documents.rs b/rust/cloud-storage/document_storage_service/src/api/documents/initialize_user_documents.rs
index fbf9848356..6c279bdb41 100644
--- a/rust/cloud-storage/document_storage_service/src/api/documents/initialize_user_documents.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/documents/initialize_user_documents.rs
@@ -6,12 +6,13 @@ use axum::{
use futures::StreamExt;
use macro_user_id::cowlike::CowLike;
use model::{
- document::{BasicDocument, build_extensionless_document_key},
+ document::BasicDocument,
response::{ErrorResponse, GenericErrorResponse, GenericSuccessResponse},
};
use model_user::axum_extractor::MacroUserExtractor;
use models_permissions::share_permission::SharePermissionV2;
use reqwest::StatusCode;
+use s3_key::build_cloud_storage_bucket_document_key;
const ONBOARDING_FOLDER_NAME: &str = "ONBOARDING_DOCUMENTS";
const PROJECT_NAME: &str = "Starter Docs";
@@ -168,7 +169,7 @@ pub async fn handler(
None => format!("{ONBOARDING_FOLDER_NAME}/{}", uri_document_name),
};
- let target_key = build_extensionless_document_key(
+ let target_key = build_cloud_storage_bucket_document_key(
user_id.as_ref(),
&document.document_id,
document.document_version_id,
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/location.rs b/rust/cloud-storage/document_storage_service/src/api/documents/location.rs
index 43bd754b27..87a29fbd81 100644
--- a/rust/cloud-storage/document_storage_service/src/api/documents/location.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/documents/location.rs
@@ -7,10 +7,7 @@ use std::{
time::{SystemTime, UNIX_EPOCH},
};
-use crate::{
- model::request::documents::location::LocationQueryParams,
- service::{self},
-};
+use crate::model::request::documents::location::LocationQueryParams;
use axum::{
Extension,
body::Body,
@@ -20,14 +17,11 @@ use axum::{
};
use cloudfront_sign::{SignedOptions, get_signed_url};
use model::{
- document::{
- CONVERTED_DOCUMENT_FILE_NAME, DocumentBasic, FileType, FileTypeExt,
- build_cloud_storage_bucket_document_key, build_extensionless_document_key,
- response::LocationResponseData,
- },
+ document::{DocumentBasic, FileType, FileTypeExt, response::LocationResponseData},
response::{GenericErrorResponse, GenericResponse, PresignedUrl},
user::UserContext,
};
+use s3_key::{build_cloud_storage_bucket_document_key, build_docx_to_pdf_converted_document_key};
#[derive(serde::Deserialize)]
pub struct Params {
@@ -111,59 +105,19 @@ pub async fn get_location_handler(
.unwrap()
}
-#[tracing::instrument(skip(state))]
-async fn get_editable_url(
+/// Signs a document key and returns a CloudFront presigned URL.
+/// `check_key` is the non-URL-encoded key for S3 existence verification.
+/// `signed_key` is the URL-encoded key for the CloudFront signed URL.
+#[tracing::instrument(skip(state), err)]
+async fn sign_document_key(
state: &ApiContext,
- owner: &str,
- document_id: &str,
- document_version_id: Option<i64>,
- file_type: &str,
+ #[allow(unused_variables)] check_key: &str,
+ signed_key: &str,
) -> anyhow::Result<LocationResponseData> {
- let url_encoded_owner = urlencoding::encode(owner);
- let document_version_id = if let Some(document_version_id) = document_version_id {
- document_version_id
- } else {
- macro_db_client::document::get_latest_document_version_id(&state.db, document_id)
- .await?
- .0
- };
-
- // Try extensionless key first, fall back to legacy key with extension
- let extensionless_key =
- build_extensionless_document_key(owner, document_id, document_version_id);
- let extensionless_exists = verify_file_exists(&state.s3_client, &extensionless_key).await?;
- let document_key = if extensionless_exists {
- build_extensionless_document_key(&url_encoded_owner, document_id, document_version_id)
- } else {
- build_cloud_storage_bucket_document_key(
- &url_encoded_owner,
- document_id,
- document_version_id,
- Some(file_type),
- )
- };
-
- // Check if the item exists in s3
#[cfg(feature = "location_check")]
{
- // NOTE: owner is not url encoded
- let check_key = if verify_file_exists(
- &state.s3_client,
- &build_extensionless_document_key(owner, document_id, document_version_id),
- )
- .await?
- {
- build_extensionless_document_key(owner, document_id, document_version_id)
- } else {
- build_cloud_storage_bucket_document_key(
- owner,
- document_id,
- document_version_id,
- Some(file_type),
- )
- };
tracing::trace!("checking if file exists in s3, key: {}", check_key);
- let exists = verify_file_exists(&state.s3_client, &check_key).await?;
+ let exists = &state.s3_client.exists(check_key).await?;
if !exists {
anyhow::bail!(DOCUMENT_DOES_NOT_EXIST);
}
@@ -188,90 +142,50 @@ async fn get_editable_url(
.config
.vars
.document_storage_service_cloudfront_distribution_url,
- &document_key,
+ signed_key,
&signed_options,
)?;
Ok(LocationResponseData::PresignedUrl(signed_url))
}
+/// Gets a signed CloudFront URL for a versioned document.
+///
+/// For static files (PDF, HTML), the version is always resolved from the DB.
+/// For editable files (MD, Canvas), a caller-provided version ID is used if present,
+/// otherwise the latest version is fetched.
#[tracing::instrument(skip(state))]
-pub(in crate::api::documents) async fn get_static_url(
+pub(in crate::api::documents) async fn get_versioned_url(
state: &ApiContext,
owner: &str,
document_id: &str,
- file_type: &Option<FileType>,
+ document_version_id: Option<i64>,
+ is_static: bool,
) -> anyhow::Result<LocationResponseData> {
- let url_encoded_owner = urlencoding::encode(owner);
- let (document_version_id, _) =
- macro_db_client::document::get_document_version_id(&state.db, document_id).await?;
-
- // Try extensionless key first, fall back to legacy key with extension
- let extensionless_key =
- build_extensionless_document_key(owner, document_id, document_version_id);
- let file_type_str = file_type.as_ref().map(|s| s.as_str());
- let extensionless_exists = verify_file_exists(&state.s3_client, &extensionless_key).await?;
- let document_key = if extensionless_exists {
- build_extensionless_document_key(&url_encoded_owner, document_id, document_version_id)
- } else {
- build_cloud_storage_bucket_document_key(
- &url_encoded_owner,
- document_id,
- document_version_id,
- file_type_str,
- )
- };
-
- // Check if the item exists in s3
- #[cfg(feature = "location_check")]
- {
- // NOTE: owner is not url encoded
- let check_key = if verify_file_exists(
- &state.s3_client,
- &build_extensionless_document_key(owner, document_id, document_version_id),
- )
- .await?
- {
- build_extensionless_document_key(owner, document_id, document_version_id)
- } else {
- build_cloud_storage_bucket_document_key(
- owner,
- document_id,
- document_version_id,
- file_type_str,
- )
- };
- tracing::trace!("checking if file exists in s3, key: {}", check_key);
- let exists = verify_file_exists(&state.s3_client, &check_key).await?;
- if !exists {
- anyhow::bail!(DOCUMENT_DOES_NOT_EXIST);
+ let document_version_id = match document_version_id {
+ Some(v) if !is_static => v,
+ _ if is_static => {
+ macro_db_client::document::get_document_version_id(&state.db, document_id)
+ .await?
+ .0
}
- }
+ _ => {
+ macro_db_client::document::get_latest_document_version_id(&state.db, document_id)
+ .await?
+ .0
+ }
+ };
- let signed_options = get_cloudfront_signed_options(
- &state
- .config
- .vars
- .document_storage_service_cloudfront_signer_public_key_id,
- state
- .config
- .document_storage_service_cloudfront_signer_private_key
- .as_ref(),
- state
- .config
- .document_storage_service_presigned_url_expiry_seconds,
+ let check_key =
+ build_cloud_storage_bucket_document_key(owner, document_id, document_version_id);
+ let url_encoded_owner = urlencoding::encode(owner);
+ let signed_key = build_cloud_storage_bucket_document_key(
+ &url_encoded_owner,
+ document_id,
+ document_version_id,
);
- let signed_url = get_presigned_url(
- &state
- .config
- .vars
- .document_storage_service_cloudfront_distribution_url,
- &document_key,
- &signed_options,
- )?;
-
- Ok(LocationResponseData::PresignedUrl(signed_url))
+ sign_document_key(state, &check_key, &signed_key).await
}
/// Gets the presigned url for the converted docx file
@@ -281,50 +195,11 @@ async fn get_converted_docx_url(
owner: &str,
document_id: &str,
) -> anyhow::Result<LocationResponseData> {
+ let check_key = build_docx_to_pdf_converted_document_key(owner, document_id);
let url_encoded_owner = urlencoding::encode(owner);
- let document_key = format!(
- "{}/{}/{}.pdf",
- url_encoded_owner, document_id, CONVERTED_DOCUMENT_FILE_NAME
- );
+ let signed_key = build_docx_to_pdf_converted_document_key(&url_encoded_owner, document_id);
- // Check if the item exists in s3
- #[cfg(feature = "location_check")]
- {
- let document_key = format!(
- "{}/{}/{}.pdf",
- owner, document_id, CONVERTED_DOCUMENT_FILE_NAME
- );
- tracing::trace!("checking if file exists in s3, key: {}", document_key);
- let exists = verify_file_exists(&state.s3_client, &document_key).await?;
- if !exists {
- anyhow::bail!(DOCUMENT_DOES_NOT_EXIST);
- }
- }
-
- let signed_options = get_cloudfront_signed_options(
- &state
- .config
- .vars
- .document_storage_service_cloudfront_signer_public_key_id,
- state
- .config
- .document_storage_service_cloudfront_signer_private_key
- .as_ref(),
- state
- .config
- .document_storage_service_presigned_url_expiry_seconds,
- );
-
- let signed_url = get_presigned_url(
- &state
- .config
- .vars
- .document_storage_service_cloudfront_distribution_url,
- &document_key,
- &signed_options,
- )?;
-
- Ok(LocationResponseData::PresignedUrl(signed_url))
+ sign_document_key(state, &check_key, &signed_key).await
}
#[tracing::instrument(skip(state))]
@@ -427,10 +302,7 @@ pub(in crate::api::documents) async fn get_presigned_url_by_type(
get_converted_docx: bool,
) -> anyhow::Result<LocationResponseData> {
match file_type {
- None => {
- // no file type will always be static
- get_static_url(state, owner, document_id, &file_type).await
- }
+ None => get_versioned_url(state, owner, document_id, document_version_id, true).await,
Some(file_type) => {
if file_type == FileType::Docx && get_converted_docx {
tracing::debug!("getting converted docx url");
@@ -438,24 +310,16 @@ pub(in crate::api::documents) async fn get_presigned_url_by_type(
} else if file_type == FileType::Docx && !get_converted_docx {
tracing::debug!("getting legacy docx urls");
get_docx_urls(state, document_id, document_version_id).await
- } else if file_type.is_static() {
- get_static_url(state, owner, document_id, &Some(file_type)).await
} else {
- get_editable_url(
- state,
- owner,
- document_id,
- document_version_id,
- file_type.as_str(),
- )
- .await
+ let is_static = file_type.is_static();
+ get_versioned_url(state, owner, document_id, document_version_id, is_static).await
}
}
}
}
/// Makes a cloudfront presigned url for the provided key
-#[tracing::instrument(skip(options))]
+#[tracing::instrument(skip(options), err)]
pub(in crate::api::documents) fn get_presigned_url(
cloudfront_distribution_url: &str,
key: &str,
@@ -471,10 +335,3 @@ pub(in crate::api::documents) fn get_presigned_url(
Ok(signed_url)
}
-
-async fn verify_file_exists(
- s3_client: &service::s3::S3,
- document_key: &str,
-) -> anyhow::Result<bool> {
- s3_client.exists(document_key).await
-}
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/simple_save.rs b/rust/cloud-storage/document_storage_service/src/api/documents/simple_save.rs
index c2e628323f..43b1b09a6e 100644
--- a/rust/cloud-storage/document_storage_service/src/api/documents/simple_save.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/documents/simple_save.rs
@@ -14,11 +14,12 @@ use axum::{
use macro_middleware::cloud_storage::ensure_access::document::DocumentAccessExtractor;
use model::document::response::DocumentResponseMetadata;
use model::{
- document::{DocumentBasic, FileType, FileTypeExt, build_extensionless_document_key},
+ document::{DocumentBasic, FileType, FileTypeExt},
response::{GenericErrorResponse, GenericResponse},
user::UserContext,
};
use models_permissions::share_permission::access_level::EditAccessLevel;
+use s3_key::build_cloud_storage_bucket_document_key;
use serde::Deserialize;
#[derive(Deserialize)]
@@ -114,7 +115,7 @@ pub async fn handler(
}
};
- let key = build_extensionless_document_key(
+ let key = build_cloud_storage_bucket_document_key(
document.owner.as_ref(),
&document.document_id,
document.document_version_id,
diff --git a/rust/cloud-storage/document_storage_service/src/api/projects/upload_folder.rs b/rust/cloud-storage/document_storage_service/src/api/projects/upload_folder.rs
index 18cf7f50fa..d8b5467efa 100644
--- a/rust/cloud-storage/document_storage_service/src/api/projects/upload_folder.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/projects/upload_folder.rs
@@ -11,10 +11,7 @@ use axum::{
};
use macro_user_id::user_id::MacroUserIdStr;
use model::{
- document::{
- ContentType, DocumentMetadata, FileType, build_docx_staging_bucket_document_key,
- build_extensionless_document_key,
- },
+ document::{ContentType, DocumentMetadata, FileType},
folder::{
FileSystemNode, S3Destination, S3DestinationMap, UploadFolderRequest,
UploadFolderResponseData, UploadFolderWithIdsResponse,
@@ -27,6 +24,7 @@ use models_bulk_upload::{
UploadExtractFolderRequest, UploadExtractFolderResponseData,
};
use models_permissions::share_permission::SharePermissionV2;
+use s3_key::{build_cloud_storage_bucket_document_key, build_docx_staging_bucket_document_key};
use sqlx::{Pool, Postgres};
use std::{str::FromStr, sync::Arc};
use uuid::Uuid;
@@ -273,7 +271,7 @@ async fn build_documents(
.transpose()?;
let sha = document.sha.clone().context("document needs a sha")?;
if file_type != Some(FileType::Docx) {
- let key = build_extensionless_document_key(
+ let key = build_cloud_storage_bucket_document_key(
document.owner.as_ref(),
&document.document_id,
document.document_version_id,
diff --git a/rust/cloud-storage/document_storage_service/src/service/s3/mod.rs b/rust/cloud-storage/document_storage_service/src/service/s3/mod.rs
index bdece04546..64213b0b36 100644
--- a/rust/cloud-storage/document_storage_service/src/service/s3/mod.rs
+++ b/rust/cloud-storage/document_storage_service/src/service/s3/mod.rs
@@ -24,8 +24,6 @@ use tokio::sync::Semaphore;
use model::document::{ContentType, FileType};
-pub static TEMP_FILE_PREFIX: &str = "temp_files/";
-
#[derive(Clone, Debug)]
pub struct S3Client {
/// Inner S3 client
diff --git a/rust/cloud-storage/document_text_extractor/Cargo.toml b/rust/cloud-storage/document_text_extractor/Cargo.toml
index f34d52bc06..9f7ef79563 100644
--- a/rust/cloud-storage/document_text_extractor/Cargo.toml
+++ b/rust/cloud-storage/document_text_extractor/Cargo.toml
@@ -25,6 +25,7 @@ macro_entrypoint = { path = "../macro_entrypoint" }
macro_env_var = { path = "../macro_env_var" }
mockall = { workspace = true }
model = { path = "../model" }
+s3_key = { path = "../s3_key" }
openssl = { workspace = true }
pdfium-render = { workspace = true }
serde = { workspace = true }
diff --git a/rust/cloud-storage/document_text_extractor/src/handler/extract_text_citations.rs b/rust/cloud-storage/document_text_extractor/src/handler/extract_text_citations.rs
index 0a86eec537..e421da7d0d 100644
--- a/rust/cloud-storage/document_text_extractor/src/handler/extract_text_citations.rs
+++ b/rust/cloud-storage/document_text_extractor/src/handler/extract_text_citations.rs
@@ -6,7 +6,7 @@ use std::{rc::Rc, sync::Arc};
use uuid::Uuid;
use crate::{
- model::key::DocumentKeyParts,
+ model::key::DocumentKey,
service::{self},
};
@@ -149,41 +149,37 @@ pub async fn extract_text_from_document(
pdfium: Rc<pdfium_render::prelude::Pdfium>,
s3_client: Arc<service::s3::S3>,
db: Arc<service::db::DB>,
-) -> Result<Option<DocumentKeyParts>, Error> {
- let document_key_parts = DocumentKeyParts::from_s3_key(key).map_err(|e| {
+) -> Result<Option<DocumentKey>, Error> {
+ let document_key = DocumentKey::from_s3_key(key).map_err(|e| {
tracing::error!(error=?e, "invalid key format");
Error::from("invalid key format")
})?;
- // For legacy keys with extension, check the extension directly
- // For extensionless keys, look up file type from DB
- if document_key_parts.has_extension {
- if !key.ends_with(".pdf") {
- tracing::info!("skipping non-pdf file for extraction");
- return Ok(None);
- }
+ let document_id = document_key.document_id();
+
+ let file_type = if document_key.is_converted_pdf() {
+ Some(model::document::FileType::Pdf)
+ } else if document_key.is_temp() {
+ None
} else {
- let file_type = db
- .get_document_file_type(&document_key_parts.document_id)
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "unable to get file type from db");
- Error::from("unable to get file type from db")
- })?;
- match file_type {
- Some(model::document::FileType::Pdf) => {}
- _ => {
- tracing::info!(file_type=?file_type, "skipping non-pdf file for extraction");
- return Ok(None);
- }
+ db.get_document_file_type(document_id).await.map_err(|e| {
+ tracing::error!(error=?e, "unable to get file type from db");
+ Error::from("unable to get file type from db")
+ })?
+ };
+
+ match file_type {
+ Some(model::document::FileType::Pdf) => {}
+ _ => {
+ tracing::info!(file_type=?file_type, "skipping non-pdf file for extraction");
+ return Ok(None);
}
}
- let document_id = &document_key_parts.document_id;
tracing::info!(document_id=%document_id, "starting extracting text process for document");
let raw_file = match s3_client
- .get_document_bytes(bucket, &document_key_parts.to_key())
+ .get_document_bytes(bucket, &document_key.to_key())
.await
{
Ok(bytes) => bytes,
@@ -222,7 +218,7 @@ pub async fn extract_text_from_document(
.await
.context("coult not insert sentences")?;
tracing::info!(document_id=%document_id, "extraction complete");
- Ok(Some(document_key_parts))
+ Ok(Some(document_key))
}
// locally run extraction
diff --git a/rust/cloud-storage/document_text_extractor/src/model/key.rs b/rust/cloud-storage/document_text_extractor/src/model/key.rs
index 05e78adc54..2869036eb5 100644
--- a/rust/cloud-storage/document_text_extractor/src/model/key.rs
+++ b/rust/cloud-storage/document_text_extractor/src/model/key.rs
@@ -1,53 +1 @@
-use anyhow::Context;
-use lambda_runtime::tracing;
-
-#[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug)]
-pub struct DocumentKeyParts {
- pub user_id: String,
- pub document_id: String,
- pub document_version_id: String,
- pub has_extension: bool,
-}
-
-impl DocumentKeyParts {
- #[tracing::instrument]
- pub fn from_s3_key(key: &str) -> Result<Self, anyhow::Error> {
- // Supports both legacy keys (user_id/document_id/version.ext)
- // and extensionless keys (user_id/document_id/version)
- let split = key.split("/").collect::<Vec<&str>>();
- if split.len() != 3 {
- anyhow::bail!("invalid key format");
- }
-
- let encoded_user_id = split[0].to_string();
- let user_id = urlencoding::decode(&encoded_user_id).context("UTF-8")?;
-
- let file_parts: Vec<&str> = split[2].split(".").collect();
- let (document_version_id, has_extension) = if file_parts.len() == 2 {
- (file_parts[0].to_string(), true)
- } else {
- (split[2].to_string(), false)
- };
-
- Ok(Self {
- user_id: user_id.to_string(),
- document_id: split[1].to_string(),
- document_version_id,
- has_extension,
- })
- }
-
- pub fn to_key(&self) -> String {
- if self.has_extension {
- format!(
- "{}/{}/{}.pdf",
- self.user_id, self.document_id, self.document_version_id
- )
- } else {
- format!(
- "{}/{}/{}",
- self.user_id, self.document_id, self.document_version_id
- )
- }
- }
-}
+pub use s3_key::DocumentKey;
diff --git a/rust/cloud-storage/documents/Cargo.toml b/rust/cloud-storage/documents/Cargo.toml
index c10c2932ca..51c508a636 100644
--- a/rust/cloud-storage/documents/Cargo.toml
+++ b/rust/cloud-storage/documents/Cargo.toml
@@ -50,6 +50,7 @@ macro_aws_config = { path = "../macro_aws_config", features = ["s3"] }
macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
model = { path = "../model" }
+s3_key = { path = "../s3_key" }
models_permissions = { path = "../models_permissions" }
models_properties = { path = "../models_properties" }
diff --git a/rust/cloud-storage/documents/src/domain/ports.rs b/rust/cloud-storage/documents/src/domain/ports.rs
index b7e6653421..20ff68f327 100644
--- a/rust/cloud-storage/documents/src/domain/ports.rs
+++ b/rust/cloud-storage/documents/src/domain/ports.rs
@@ -146,9 +146,6 @@ pub trait PresignedUploadUrlPort: Send + Sync + 'static {
sha: &str,
content_type: ContentType,
) -> impl Future<Output = anyhow::Result<String>> + Send;
-
- /// Check if a document key exists in the storage bucket.
- fn document_key_exists(&self, key: &str) -> impl Future<Output = anyhow::Result<bool>> + Send;
}
/// Port for attaching task system properties.
diff --git a/rust/cloud-storage/documents/src/domain/service.rs b/rust/cloud-storage/documents/src/domain/service.rs
index a7d31aa361..1c9ce05278 100644
--- a/rust/cloud-storage/documents/src/domain/service.rs
+++ b/rust/cloud-storage/documents/src/domain/service.rs
@@ -21,12 +21,12 @@ use model::document::response::{
CreateDocumentResponseData, DocumentResponse, DocumentResponseMetadata,
GetDocumentResponseData, LocationResponseData, LocationResponseV3,
};
-use model::document::{
- CONVERTED_DOCUMENT_FILE_NAME, ContentType, DocumentBasic, FileType, FileTypeExt,
+use model::document::{ContentType, DocumentBasic, FileType, FileTypeExt};
+use model::response::PresignedUrl;
+use s3_key::{
build_cloud_storage_bucket_document_key, build_docx_staging_bucket_document_key,
- build_extensionless_document_key,
+ build_docx_to_pdf_converted_document_key,
};
-use model::response::PresignedUrl;
use tracing;
use super::models::{
@@ -106,7 +106,7 @@ impl<R: DocumentRepo, U: PresignedUploadUrlPort, T: TaskPropertiesPort, C: Conne
owner: &str,
document_id: &str,
document_version_id: Option<i64>,
- file_type: &str,
+ _file_type: &str,
) -> anyhow::Result<LocationResponseData> {
let url_encoded_owner = urlencoding::encode(owner);
let document_version_id = if let Some(id) = document_version_id {
@@ -119,23 +119,11 @@ impl<R: DocumentRepo, U: PresignedUploadUrlPort, T: TaskPropertiesPort, C: Conne
.0
};
- // Try extensionless key first, fall back to legacy key with extension
- let extensionless_key =
- build_extensionless_document_key(owner, document_id, document_version_id);
- let document_key = if self
- .upload_url_service
- .document_key_exists(&extensionless_key)
- .await?
- {
- build_extensionless_document_key(&url_encoded_owner, document_id, document_version_id)
- } else {
- build_cloud_storage_bucket_document_key(
- &url_encoded_owner,
- document_id,
- document_version_id,
- Some(file_type),
- )
- };
+ let document_key = build_cloud_storage_bucket_document_key(
+ &url_encoded_owner,
+ document_id,
+ document_version_id,
+ );
let signed_url = self.make_presigned_url(&document_key)?;
Ok(LocationResponseData::PresignedUrl(signed_url))
@@ -145,7 +133,7 @@ impl<R: DocumentRepo, U: PresignedUploadUrlPort, T: TaskPropertiesPort, C: Conne
&self,
owner: &str,
document_id: &str,
- file_type: &Option<FileType>,
+ _file_type: &Option<FileType>,
) -> anyhow::Result<LocationResponseData> {
let url_encoded_owner = urlencoding::encode(owner);
let (document_version_id, _) = self
@@ -154,24 +142,11 @@ impl<R: DocumentRepo, U: PresignedUploadUrlPort, T: TaskPropertiesPort, C: Conne
.await
.map_err(Into::into)?;
- // Try extensionless key first, fall back to legacy key with extension
- let extensionless_key =
- build_extensionless_document_key(owner, document_id, document_version_id);
- let file_type_str = file_type.as_ref().map(|s| s.as_str());
- let document_key = if self
- .upload_url_service
- .document_key_exists(&extensionless_key)
- .await?
- {
- build_extensionless_document_key(&url_encoded_owner, document_id, document_version_id)
- } else {
- build_cloud_storage_bucket_document_key(
- &url_encoded_owner,
- document_id,
- document_version_id,
- file_type_str,
- )
- };
+ let document_key = build_cloud_storage_bucket_document_key(
+ &url_encoded_owner,
+ document_id,
+ document_version_id,
+ );
let signed_url = self.make_presigned_url(&document_key)?;
Ok(LocationResponseData::PresignedUrl(signed_url))
@@ -183,10 +158,8 @@ impl<R: DocumentRepo, U: PresignedUploadUrlPort, T: TaskPropertiesPort, C: Conne
document_id: &str,
) -> anyhow::Result<LocationResponseData> {
let url_encoded_owner = urlencoding::encode(owner);
- let document_key = format!(
- "{}/{}/{}.pdf",
- url_encoded_owner, document_id, CONVERTED_DOCUMENT_FILE_NAME
- );
+ let document_key =
+ build_docx_to_pdf_converted_document_key(&url_encoded_owner, document_id);
let signed_url = self.make_presigned_url(&document_key)?;
Ok(LocationResponseData::PresignedUrl(signed_url))
@@ -553,7 +526,7 @@ impl<R: DocumentRepo, U: PresignedUploadUrlPort, T: TaskPropertiesPort, C: Conne
.await
}
_ => {
- let key = build_extensionless_document_key(
+ let key = build_cloud_storage_bucket_document_key(
document_metadata.owner.as_ref(),
&document_id,
document_metadata.document_version_id,
diff --git a/rust/cloud-storage/documents/src/outbound/s3_upload_url.rs b/rust/cloud-storage/documents/src/outbound/s3_upload_url.rs
index b622b7621a..d37b9beaac 100644
--- a/rust/cloud-storage/documents/src/outbound/s3_upload_url.rs
+++ b/rust/cloud-storage/documents/src/outbound/s3_upload_url.rs
@@ -65,28 +65,6 @@ impl PresignedUploadUrlPort for S3UploadUrlAdapter {
)
.await
}
-
- #[tracing::instrument(skip(self), err)]
- async fn document_key_exists(&self, key: &str) -> anyhow::Result<bool> {
- let result = self
- .client
- .head_object()
- .bucket(&self.document_storage_bucket)
- .key(key)
- .send()
- .await;
-
- match result {
- Ok(_) => Ok(true),
- Err(err) => {
- if err.as_service_error().is_some_and(|e| e.is_not_found()) {
- Ok(false)
- } else {
- Err(err.into())
- }
- }
- }
- }
}
async fn put_presigned_url(
diff --git a/rust/cloud-storage/docx_unzip_handler/Cargo.toml b/rust/cloud-storage/docx_unzip_handler/Cargo.toml
index 79e991d2be..facdd007f0 100644
--- a/rust/cloud-storage/docx_unzip_handler/Cargo.toml
+++ b/rust/cloud-storage/docx_unzip_handler/Cargo.toml
@@ -25,6 +25,7 @@ macro_env = { path = "../macro_env" }
macro_sha_count_client = { path = "../macro_sha_count_client" }
macro_uuid = { path = "../macro_uuid" }
model = { path = "../model" }
+s3_key = { path = "../s3_key" }
openssl = { workspace = true }
redis = { workspace = true, features = [
"aio",
diff --git a/rust/cloud-storage/docx_unzip_handler/src/service/document/process_document.rs b/rust/cloud-storage/docx_unzip_handler/src/service/document/process_document.rs
index c29f035355..ec292ce681 100644
--- a/rust/cloud-storage/docx_unzip_handler/src/service/document/process_document.rs
+++ b/rust/cloud-storage/docx_unzip_handler/src/service/document/process_document.rs
@@ -1,9 +1,7 @@
use anyhow::Context;
use lambda_runtime::tracing::{self, Level};
-use model::{
- convert::ConvertQueueMessage,
- document::{CONVERTED_DOCUMENT_FILE_NAME, SaveBomPart},
-};
+use model::{convert::ConvertQueueMessage, document::SaveBomPart};
+use s3_key::build_docx_to_pdf_converted_document_key;
use crate::{
context::{self},
@@ -56,11 +54,9 @@ pub async fn process(
from_key: document_key_parts.to_key(),
// The key for storing a converted version of a file is
// "{user_id}/{document_id}/converted.{file_extension}"
- to_key: format!(
- "{}/{}/{}.pdf",
- document_key_parts.user_id,
- document_key_parts.document_id,
- CONVERTED_DOCUMENT_FILE_NAME
+ to_key: build_docx_to_pdf_converted_document_key(
+ &document_key_parts.user_id,
+ &document_key_parts.document_id,
),
to_bucket: ctx.config.document_storage_bucket.clone(),
})
diff --git a/rust/cloud-storage/dynamodb_client/Cargo.toml b/rust/cloud-storage/dynamodb_client/Cargo.toml
index d0940ff5dc..6a97380ede 100644
--- a/rust/cloud-storage/dynamodb_client/Cargo.toml
+++ b/rust/cloud-storage/dynamodb_client/Cargo.toml
@@ -14,6 +14,7 @@ macro_aws_config = { path = "../macro_aws_config" }
chrono = { workspace = true }
model = { path = "../model" }
models_bulk_upload = { path = "../models_bulk_upload" }
+s3_key = { path = "../s3_key" }
strum = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true, features = ["time"] }
diff --git a/rust/cloud-storage/dynamodb_client/src/lib.rs b/rust/cloud-storage/dynamodb_client/src/lib.rs
index 94809a90a1..c52780151b 100644
--- a/rust/cloud-storage/dynamodb_client/src/lib.rs
+++ b/rust/cloud-storage/dynamodb_client/src/lib.rs
@@ -3,8 +3,7 @@ use macro_aws_config::SdkConfig;
mod bulk_upload;
use models_bulk_upload::{
- BulkUploadRequest, BulkUploadRequestDocuments, EXTRACT_UPLOAD_FOLDER, UploadDocumentStatus,
- UploadFolderStatus,
+ BulkUploadRequest, BulkUploadRequestDocuments, UploadDocumentStatus, UploadFolderStatus,
};
#[derive(Debug, Clone)]
@@ -54,7 +53,7 @@ impl BulkUpload {
parent_id: Option<&str>,
) -> anyhow::Result<BulkUploadRequest> {
let table = self.table()?;
- let key = format!("{}/{}", EXTRACT_UPLOAD_FOLDER, request_id);
+ let key = s3_key::BulkUploadStagingKey::new(request_id).to_key();
bulk_upload::create_bulk_upload_request(
&self.client,
table,
diff --git a/rust/cloud-storage/model/src/document/document_key.rs b/rust/cloud-storage/model/src/document/document_key.rs
deleted file mode 100644
index 93290dfe73..0000000000
--- a/rust/cloud-storage/model/src/document/document_key.rs
+++ /dev/null
@@ -1,77 +0,0 @@
-pub static CONVERTED_DOCUMENT_FILE_NAME: &str = "converted";
-
-/// Builds an extensionless document key for a document in the cloud storage bucket.
-/// This is the new convention — document IDs are unique so extensions are unnecessary in S3 keys.
-pub fn build_extensionless_document_key<T: ToString>(
- user_id: &str,
- document_id: &str,
- document_version_id: T,
-) -> String {
- format!(
- "{}/{}/{}",
- user_id,
- document_id,
- document_version_id.to_string()
- )
-}
-
-/// Builds a document key for a document in the cloud storage bucket.
-/// The document_version_id could be the document's version id (i64) or "converted" for files that
-/// are converted.
-///
-/// DEPRECATED: Prefer `build_extensionless_document_key` for new writes.
-/// This function is kept for building legacy keys during the migration period.
-pub fn build_cloud_storage_bucket_document_key<T: ToString>(
- user_id: &str,
- document_id: &str,
- document_version_id: T,
- file_type: Option<&str>,
-) -> String {
- match file_type {
- Some(file_type) => {
- format!(
- "{}/{}/{}.{}",
- user_id,
- document_id,
- document_version_id.to_string(),
- file_type
- )
- }
- None => {
- format!(
- "{}/{}/{}",
- user_id,
- document_id,
- document_version_id.to_string()
- )
- }
- }
-}
-
-pub fn build_docx_staging_bucket_document_key(
- user_id: &str,
- document_id: &str,
- document_version_id: i64,
-) -> String {
- format!("{}/{}/{}.docx", user_id, document_id, document_version_id)
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn test_build_extensionless_document_key() {
- let key = build_extensionless_document_key("owner", "document-id", 1);
- assert_eq!(key, "owner/document-id/1");
- }
-
- #[test]
- fn test_build_cloud_storage_bucket_document_key() {
- let key = build_cloud_storage_bucket_document_key("owner", "document-id", 1, Some("pdf"));
- assert_eq!(key, "owner/document-id/1.pdf");
-
- let key = build_cloud_storage_bucket_document_key("owner", "document-id", 1, None);
- assert_eq!(key, "owner/document-id/1");
- }
-}
diff --git a/rust/cloud-storage/model/src/document/mod.rs b/rust/cloud-storage/model/src/document/mod.rs
index de53bae104..5b2163c281 100644
--- a/rust/cloud-storage/model/src/document/mod.rs
+++ b/rust/cloud-storage/model/src/document/mod.rs
@@ -17,8 +17,6 @@ mod basic;
pub use basic::*;
mod document_family;
pub use document_family::*;
-pub mod document_key;
-pub use document_key::*;
use models_permissions::share_permission::access_level::AccessLevel;
diff --git a/rust/cloud-storage/models_bulk_upload/src/folder.rs b/rust/cloud-storage/models_bulk_upload/src/folder.rs
index b160b96c19..009ff9dead 100644
--- a/rust/cloud-storage/models_bulk_upload/src/folder.rs
+++ b/rust/cloud-storage/models_bulk_upload/src/folder.rs
@@ -1,8 +1,6 @@
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
-pub static EXTRACT_UPLOAD_FOLDER: &str = "extract";
-
#[derive(Serialize, Deserialize, Eq, PartialEq, Debug, ToSchema, Clone)]
#[serde(rename_all = "camelCase")]
pub struct S3ObjectInfo {
diff --git a/rust/cloud-storage/s3_key/Cargo.toml b/rust/cloud-storage/s3_key/Cargo.toml
new file mode 100644
index 0000000000..03d4639c44
--- /dev/null
+++ b/rust/cloud-storage/s3_key/Cargo.toml
@@ -0,0 +1,9 @@
+[package]
+name = "s3_key"
+version = "0.1.0"
+edition = "2024"
+publish = false
+
+[dependencies]
+anyhow = { workspace = true }
+urlencoding = { workspace = true }
diff --git a/rust/cloud-storage/s3_key/src/bulk_upload_key.rs b/rust/cloud-storage/s3_key/src/bulk_upload_key.rs
new file mode 100644
index 0000000000..ad31d6c37f
--- /dev/null
+++ b/rust/cloud-storage/s3_key/src/bulk_upload_key.rs
@@ -0,0 +1,51 @@
+const BULK_UPLOAD_STAGING_PREFIX: &str = "extract";
+
+/// Represents an S3 key in the bulk upload staging bucket.
+/// Format: `extract/{request_id}`
+#[derive(Eq, PartialEq, Debug, Clone)]
+pub struct BulkUploadStagingKey {
+ /// The bulk upload request ID.
+ pub request_id: String,
+}
+
+impl BulkUploadStagingKey {
+ /// Creates a new bulk upload staging key from a request ID.
+ pub fn new(request_id: impl Into<String>) -> Self {
+ Self {
+ request_id: request_id.into(),
+ }
+ }
+
+ /// Parses an S3 key from the bulk upload staging bucket.
+ pub fn from_s3_key(key: &str) -> Result<Self, anyhow::Error> {
+ let request_id = key
+ .strip_prefix(&format!("{BULK_UPLOAD_STAGING_PREFIX}/"))
+ .ok_or_else(|| {
+ anyhow::anyhow!(
+ "expected key to start with '{BULK_UPLOAD_STAGING_PREFIX}/', got '{key}'"
+ )
+ })?;
+
+ if request_id.is_empty() {
+ anyhow::bail!("request_id is empty");
+ }
+
+ Ok(Self {
+ request_id: request_id.to_string(),
+ })
+ }
+
+ /// Reconstructs the S3 key string.
+ pub fn to_key(&self) -> String {
+ format!("{BULK_UPLOAD_STAGING_PREFIX}/{}", self.request_id)
+ }
+}
+
+impl std::fmt::Display for BulkUploadStagingKey {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}", self.to_key())
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/rust/cloud-storage/s3_key/src/bulk_upload_key/test.rs b/rust/cloud-storage/s3_key/src/bulk_upload_key/test.rs
new file mode 100644
index 0000000000..e67acdb8e7
--- /dev/null
+++ b/rust/cloud-storage/s3_key/src/bulk_upload_key/test.rs
@@ -0,0 +1,31 @@
+use super::*;
+
+#[test]
+fn test_new() {
+ let key = BulkUploadStagingKey::new("request-123");
+ assert_eq!(key.to_key(), "extract/request-123");
+ assert_eq!(key.request_id, "request-123");
+}
+
+#[test]
+fn test_from_s3_key() {
+ let key = BulkUploadStagingKey::from_s3_key("extract/request-123").unwrap();
+ assert_eq!(key.request_id, "request-123");
+ assert_eq!(key.to_key(), "extract/request-123");
+}
+
+#[test]
+fn test_display() {
+ let key = BulkUploadStagingKey::new("request-123");
+ assert_eq!(format!("{key}"), "extract/request-123");
+}
+
+#[test]
+fn test_invalid_prefix() {
+ assert!(BulkUploadStagingKey::from_s3_key("other/request-123").is_err());
+}
+
+#[test]
+fn test_empty_request_id() {
+ assert!(BulkUploadStagingKey::from_s3_key("extract/").is_err());
+}
diff --git a/rust/cloud-storage/s3_key/src/document_key.rs b/rust/cloud-storage/s3_key/src/document_key.rs
new file mode 100644
index 0000000000..69ee84aab4
--- /dev/null
+++ b/rust/cloud-storage/s3_key/src/document_key.rs
@@ -0,0 +1,213 @@
+use anyhow::Context;
+
+/// The file name used for converted DOCX-to-PDF documents.
+pub const CONVERTED_DOCUMENT_FILE_NAME: &str = "converted";
+
+/// The prefix used for temporary files in S3.
+pub const TEMP_FILE_PREFIX: &str = "temp_files";
+
+/// The file extension for PDF files.
+pub const PDF_EXTENSION: &str = "pdf";
+
+/// The file extension for DOCX files.
+pub const DOCX_EXTENSION: &str = "docx";
+
+/// Represents an S3 key in the document storage bucket.
+///
+/// Covers all known key shapes:
+/// - `Versioned`: `{user_id}/{document_id}/{version_id}` — a specific document version
+/// - `ConvertedPdf`: `{user_id}/{document_id}/converted.pdf` — a DOCX converted to PDF
+/// - `TempDocx`: `temp_files/{document_id}.docx` — a temporary DOCX export
+#[derive(Eq, PartialEq, Debug, Clone)]
+pub enum DocumentKey {
+ /// A versioned document: `{user_id}/{document_id}/{version_id}`
+ Versioned {
+ /// The owner's user ID.
+ user_id: String,
+ /// The document ID.
+ document_id: String,
+ /// The document version ID (document_instance_id or document_bom_id).
+ version_id: i64,
+ },
+ /// A DOCX file converted to PDF: `{user_id}/{document_id}/converted.pdf`
+ ConvertedPdf {
+ /// The owner's user ID.
+ user_id: String,
+ /// The document ID.
+ document_id: String,
+ },
+ /// A temporary DOCX export: `temp_files/{document_id}.docx`
+ TempDocx {
+ /// The document ID.
+ document_id: String,
+ },
+}
+
+impl DocumentKey {
+ /// Parses an S3 key from the document storage bucket into a `DocumentKey`.
+ pub fn from_s3_key(key: &str) -> Result<Self, anyhow::Error> {
+ let split: Vec<&str> = key.split('/').collect();
+
+ match split.len() {
+ 2 if split[0] == TEMP_FILE_PREFIX => {
+ let filename = split[1];
+ let docx_suffix = format!(".{DOCX_EXTENSION}");
+ let document_id = filename
+ .strip_suffix(&docx_suffix)
+ .context(format!("expected .docx extension, got '{filename}'"))?;
+ Ok(Self::TempDocx {
+ document_id: document_id.to_string(),
+ })
+ }
+ 3 => {
+ let user_id = urlencoding::decode(split[0]).context("UTF-8")?.into_owned();
+ let document_id = split[1].to_string();
+ let tail = split[2];
+
+ let converted_pdf_suffix =
+ format!("{CONVERTED_DOCUMENT_FILE_NAME}.{PDF_EXTENSION}");
+ if tail == converted_pdf_suffix {
+ Ok(Self::ConvertedPdf {
+ user_id,
+ document_id,
+ })
+ } else {
+ let version_id: i64 = tail.parse().context(format!(
+ "invalid version id: expected integer, got '{tail}'"
+ ))?;
+ Ok(Self::Versioned {
+ user_id,
+ document_id,
+ version_id,
+ })
+ }
+ }
+ n => anyhow::bail!("invalid key format: expected 2 or 3 segments, got {n}"),
+ }
+ }
+
+ /// Returns the document ID for all key variants.
+ pub fn document_id(&self) -> &str {
+ match self {
+ Self::Versioned { document_id, .. }
+ | Self::ConvertedPdf { document_id, .. }
+ | Self::TempDocx { document_id } => document_id,
+ }
+ }
+
+ /// Returns `true` if this is a versioned document key. This is the default.
+ pub fn is_versioned(&self) -> bool {
+ matches!(self, Self::Versioned { .. })
+ }
+
+ /// Returns `true` if this is a temporary DOCX export key.
+ pub fn is_temp(&self) -> bool {
+ matches!(self, Self::TempDocx { .. })
+ }
+
+ /// Returns `true` if this is a converted DOCX-to-PDF key.
+ pub fn is_converted_pdf(&self) -> bool {
+ matches!(self, Self::ConvertedPdf { .. })
+ }
+
+ /// Returns the version ID as a string suitable for `SearchExtractorMessage`.
+ ///
+ /// - `Versioned` → the integer version ID as a string
+ /// - `ConvertedPdf` → `"converted"`
+ /// - `TempDocx` → `None`
+ pub fn version_id_string(&self) -> Option<String> {
+ match self {
+ Self::Versioned { version_id, .. } => Some(version_id.to_string()),
+ Self::ConvertedPdf { .. } => Some(CONVERTED_DOCUMENT_FILE_NAME.to_string()),
+ Self::TempDocx { .. } => None,
+ }
+ }
+
+ /// Reconstructs the S3 key string.
+ pub fn to_key(&self) -> String {
+ match self {
+ Self::Versioned {
+ user_id,
+ document_id,
+ version_id,
+ } => build_cloud_storage_bucket_document_key(user_id, document_id, version_id),
+ Self::ConvertedPdf {
+ user_id,
+ document_id,
+ } => build_docx_to_pdf_converted_document_key(user_id, document_id),
+ Self::TempDocx { document_id } => build_temp_docx_key(document_id),
+ }
+ }
+}
+
+fn build_cloud_storage_bucket_document_key_helper<T: ToString>(
+ user_id: &str,
+ document_id: &str,
+ document_version_id: T,
+ file_type: Option<&str>,
+) -> String {
+ match file_type {
+ Some(file_type) => {
+ format!(
+ "{}/{}/{}.{}",
+ user_id,
+ document_id,
+ document_version_id.to_string(),
+ file_type
+ )
+ }
+ None => {
+ format!(
+ "{}/{}/{}",
+ user_id,
+ document_id,
+ document_version_id.to_string()
+ )
+ }
+ }
+}
+
+/// Builds a document key for a document in the cloud storage bucket.
+/// The format is `{user_id}/{document_id}/{document_version_id}`.
+pub fn build_cloud_storage_bucket_document_key<T: ToString>(
+ user_id: &str,
+ document_id: &str,
+ document_version_id: T,
+) -> String {
+ build_cloud_storage_bucket_document_key_helper(user_id, document_id, document_version_id, None)
+}
+
+/// Builds the S3 key for a converted DOCX document's PDF output.
+/// Format: `{user_id}/{document_id}/converted.pdf`
+pub fn build_docx_to_pdf_converted_document_key(user_id: &str, document_id: &str) -> String {
+ build_cloud_storage_bucket_document_key_helper(
+ user_id,
+ document_id,
+ CONVERTED_DOCUMENT_FILE_NAME,
+ Some(PDF_EXTENSION),
+ )
+}
+
+/// Builds the S3 key for a DOCX document's staging bucket.
+/// Format: `{user_id}/{document_id}/{document_version_id}.docx`
+pub fn build_docx_staging_bucket_document_key(
+ user_id: &str,
+ document_id: &str,
+ document_version_id: i64,
+) -> String {
+ build_cloud_storage_bucket_document_key_helper(
+ user_id,
+ document_id,
+ document_version_id,
+ Some(DOCX_EXTENSION),
+ )
+}
+
+/// Builds the S3 key for a temporary DOCX export file.
+/// Format: `temp_files/{document_id}.docx`
+pub fn build_temp_docx_key(document_id: &str) -> String {
+ format!("{}/{}.{}", TEMP_FILE_PREFIX, document_id, DOCX_EXTENSION)
+}
+
+#[cfg(test)]
+mod test;
diff --git a/rust/cloud-storage/s3_key/src/document_key/test.rs b/rust/cloud-storage/s3_key/src/document_key/test.rs
new file mode 100644
index 0000000000..9c8b7849fe
--- /dev/null
+++ b/rust/cloud-storage/s3_key/src/document_key/test.rs
@@ -0,0 +1,122 @@
+use super::*;
+
+#[test]
+fn test_versioned_key_from_s3_key() {
+ let key = DocumentKey::from_s3_key("user123/doc456/789").unwrap();
+ assert_eq!(
+ key,
+ DocumentKey::Versioned {
+ user_id: "user123".to_string(),
+ document_id: "doc456".to_string(),
+ version_id: 789,
+ }
+ );
+ assert_eq!(key.to_key(), "user123/doc456/789");
+}
+
+#[test]
+fn test_converted_key_from_s3_key() {
+ let key = DocumentKey::from_s3_key("user123/doc456/converted.pdf").unwrap();
+ assert_eq!(
+ key,
+ DocumentKey::ConvertedPdf {
+ user_id: "user123".to_string(),
+ document_id: "doc456".to_string(),
+ }
+ );
+ assert_eq!(key.to_key(), "user123/doc456/converted.pdf");
+ assert!(key.is_converted_pdf());
+ assert!(!key.is_temp());
+}
+
+#[test]
+fn test_temp_docx_key_from_s3_key() {
+ let key = DocumentKey::from_s3_key("temp_files/doc456.docx").unwrap();
+ assert_eq!(
+ key,
+ DocumentKey::TempDocx {
+ document_id: "doc456".to_string(),
+ }
+ );
+ assert_eq!(key.to_key(), "temp_files/doc456.docx");
+ assert!(key.is_temp());
+ assert!(!key.is_converted_pdf());
+}
+
+#[test]
+fn test_url_encoded_user_id() {
+ let key = DocumentKey::from_s3_key("user%20123/doc456/789").unwrap();
+ assert_eq!(
+ key,
+ DocumentKey::Versioned {
+ user_id: "user 123".to_string(),
+ document_id: "doc456".to_string(),
+ version_id: 789,
+ }
+ );
+}
+
+#[test]
+fn test_invalid_key_format() {
+ assert!(DocumentKey::from_s3_key("only-one").is_err());
+ assert!(DocumentKey::from_s3_key("too/many/segments/here").is_err());
+}
+
+#[test]
+fn test_invalid_version_id() {
+ assert!(DocumentKey::from_s3_key("user123/doc456/not_a_number").is_err());
+ assert!(DocumentKey::from_s3_key("user123/doc456/abc.pdf").is_err());
+}
+
+#[test]
+fn test_invalid_temp_file_extension() {
+ assert!(DocumentKey::from_s3_key("temp_files/doc456.pdf").is_err());
+}
+
+#[test]
+fn test_document_id_accessor() {
+ let versioned = DocumentKey::from_s3_key("user/doc1/1").unwrap();
+ assert_eq!(versioned.document_id(), "doc1");
+
+ let converted = DocumentKey::from_s3_key("user/doc2/converted.pdf").unwrap();
+ assert_eq!(converted.document_id(), "doc2");
+
+ let temp = DocumentKey::from_s3_key("temp_files/doc3.docx").unwrap();
+ assert_eq!(temp.document_id(), "doc3");
+}
+
+#[test]
+fn test_version_id_string() {
+ let versioned = DocumentKey::from_s3_key("user/doc/42").unwrap();
+ assert_eq!(versioned.version_id_string(), Some("42".to_string()));
+
+ let converted = DocumentKey::from_s3_key("user/doc/converted.pdf").unwrap();
+ assert_eq!(converted.version_id_string(), Some("converted".to_string()));
+
+ let temp = DocumentKey::from_s3_key("temp_files/doc.docx").unwrap();
+ assert_eq!(temp.version_id_string(), None);
+}
+
+#[test]
+fn test_build_cloud_storage_bucket_document_key() {
+ let key = build_cloud_storage_bucket_document_key("owner", "document-id", 1);
+ assert_eq!(key, "owner/document-id/1");
+}
+
+#[test]
+fn test_build_docx_to_pdf_converted_document_key() {
+ let key = build_docx_to_pdf_converted_document_key("owner", "document-id");
+ assert_eq!(key, "owner/document-id/converted.pdf");
+}
+
+#[test]
+fn test_build_docx_staging_bucket_document_key() {
+ let key = build_docx_staging_bucket_document_key("owner", "document-id", 1);
+ assert_eq!(key, "owner/document-id/1.docx");
+}
+
+#[test]
+fn test_build_temp_docx_key() {
+ let key = build_temp_docx_key("document-id");
+ assert_eq!(key, "temp_files/document-id.docx");
+}
diff --git a/rust/cloud-storage/s3_key/src/lib.rs b/rust/cloud-storage/s3_key/src/lib.rs
new file mode 100644
index 0000000000..53da18d23c
--- /dev/null
+++ b/rust/cloud-storage/s3_key/src/lib.rs
@@ -0,0 +1,12 @@
+#![deny(missing_docs)]
+
+//! S3 key building and parsing for cloud storage buckets.
+
+mod document_key;
+pub use document_key::*;
+
+mod bulk_upload_key;
+pub use bulk_upload_key::*;
+
+mod static_file_key;
+pub use static_file_key::*;
diff --git a/rust/cloud-storage/s3_key/src/static_file_key.rs b/rust/cloud-storage/s3_key/src/static_file_key.rs
new file mode 100644
index 0000000000..4a897b0026
--- /dev/null
+++ b/rust/cloud-storage/s3_key/src/static_file_key.rs
@@ -0,0 +1,47 @@
+const STATIC_FILE_PREFIX: &str = "file";
+
+/// Represents an S3 key in the static file storage bucket.
+/// Format: `file/{file_id}`
+#[derive(Eq, PartialEq, Debug, Clone)]
+pub struct StaticFileKey {
+ /// The file ID (UUID).
+ pub file_id: String,
+}
+
+impl StaticFileKey {
+ /// Creates a new static file key from a file ID.
+ pub fn new(file_id: impl Into<String>) -> Self {
+ Self {
+ file_id: file_id.into(),
+ }
+ }
+
+ /// Parses an S3 key from the static file storage bucket.
+ pub fn from_s3_key(key: &str) -> Result<Self, anyhow::Error> {
+ let file_id = key
+ .strip_prefix(&format!("{STATIC_FILE_PREFIX}/"))
+ .ok_or_else(|| anyhow::anyhow!("expected key to start with '{STATIC_FILE_PREFIX}/'"))?;
+
+ if file_id.is_empty() {
+ anyhow::bail!("file_id is empty");
+ }
+
+ Ok(Self {
+ file_id: file_id.to_string(),
+ })
+ }
+
+ /// Reconstructs the S3 key string.
+ pub fn to_key(&self) -> String {
+ format!("{STATIC_FILE_PREFIX}/{}", self.file_id)
+ }
+}
+
+impl std::fmt::Display for StaticFileKey {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}", self.to_key())
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/rust/cloud-storage/s3_key/src/static_file_key/test.rs b/rust/cloud-storage/s3_key/src/static_file_key/test.rs
new file mode 100644
index 0000000000..fc21272449
--- /dev/null
+++ b/rust/cloud-storage/s3_key/src/static_file_key/test.rs
@@ -0,0 +1,31 @@
+use super::*;
+
+#[test]
+fn test_new() {
+ let key = StaticFileKey::new("abc-123");
+ assert_eq!(key.to_key(), "file/abc-123");
+ assert_eq!(key.file_id, "abc-123");
+}
+
+#[test]
+fn test_from_s3_key() {
+ let key = StaticFileKey::from_s3_key("file/abc-123").unwrap();
+ assert_eq!(key.file_id, "abc-123");
+ assert_eq!(key.to_key(), "file/abc-123");
+}
+
+#[test]
+fn test_display() {
+ let key = StaticFileKey::new("abc-123");
+ assert_eq!(format!("{key}"), "file/abc-123");
+}
+
+#[test]
+fn test_invalid_prefix() {
+ assert!(StaticFileKey::from_s3_key("other/abc-123").is_err());
+}
+
+#[test]
+fn test_empty_file_id() {
+ assert!(StaticFileKey::from_s3_key("file/").is_err());
+}
diff --git a/rust/cloud-storage/search_processing_service/Cargo.toml b/rust/cloud-storage/search_processing_service/Cargo.toml
index 169d8eafb6..7a92413764 100644
--- a/rust/cloud-storage/search_processing_service/Cargo.toml
+++ b/rust/cloud-storage/search_processing_service/Cargo.toml
@@ -45,6 +45,7 @@ macro_uuid = { path = "../macro_uuid" }
mention_utils = { path = "../mention_utils" }
document_sub_type = { path = "../document_sub_type" }
model = { path = "../model" }
+s3_key = { path = "../s3_key" }
models_email = { path = "../models_email" }
model_file_type = { path = "../model_file_type" }
models_opensearch = { path = "../models_opensearch" }
diff --git a/rust/cloud-storage/search_processing_service/src/process/document/raw_document.rs b/rust/cloud-storage/search_processing_service/src/process/document/raw_document.rs
index 2c90749c53..d85a3d3d7f 100644
--- a/rust/cloud-storage/search_processing_service/src/process/document/raw_document.rs
+++ b/rust/cloud-storage/search_processing_service/src/process/document/raw_document.rs
@@ -2,15 +2,16 @@ use std::str::FromStr;
use anyhow::Context;
use chrono::Utc;
-use model::document::{
- CONVERTED_DOCUMENT_FILE_NAME, DocumentMetadata, FileType,
- build_cloud_storage_bucket_document_key, build_extensionless_document_key,
-};
+use model::document::{DocumentMetadata, FileType};
use model_file_type::FileAssociation;
use models_search::document::MarkdownParseResult;
use opensearch_client::{
OpensearchClient, date_format::EpochSeconds, upsert::document::UpsertDocumentArgs,
};
+use s3_key::{
+ CONVERTED_DOCUMENT_FILE_NAME, build_cloud_storage_bucket_document_key,
+ build_docx_to_pdf_converted_document_key,
+};
use crate::{
parsers::{canvas::parse_canvas, markdown::parse_markdown_legacy, pdf::parse_pdf_pages},
@@ -98,6 +99,8 @@ pub async fn update_search_with_raw_document(
let document_name = document_info.document_name;
let sub_type = document_info.sub_type.map(|st| st.to_string());
+ // TODO: this is hacky, update the search event message to use the correctly serialized
+ // document key parts from the s3_key crate
let document_version_id = match search_extractor_message.file_type {
// For static/converted files, we want to use the version from the search extractor message since
// that is what is in s3 and document saves don't change the actual file in s3.
@@ -122,41 +125,25 @@ pub async fn update_search_with_raw_document(
.as_str(),
)?;
- // This is a check to see if the document version id in the message matches the document version
- if let Some(search_message_document_version_id) =
- search_extractor_message.document_version_id.as_ref()
- && !search_message_document_version_id.eq(&document_version_id)
- {
- if search_message_document_version_id.eq(CONVERTED_DOCUMENT_FILE_NAME) {
- tracing::debug!("document is a convert document, continue");
- } else {
- tracing::debug!(
- search_message_document_version_id = search_message_document_version_id,
- document_version_id = document_version_id,
- "document version is not latest, skipping"
- );
- return Ok(());
- }
- }
-
- // Try extensionless key first, fall back to legacy key with extension
- // document_version_id will be "converted" or document version id
- let extensionless_key = build_extensionless_document_key(
- &search_extractor_message.user_id,
- &search_extractor_message.document_id,
- &document_version_id,
- );
- let key = if s3_client
- .exists(document_storage_bucket, &extensionless_key)
- .await?
+ let key = if document_version_id == CONVERTED_DOCUMENT_FILE_NAME {
+ build_docx_to_pdf_converted_document_key(
+ &search_extractor_message.user_id,
+ &search_extractor_message.document_id,
+ )
+ } else if let Some(msg_version_id) = search_extractor_message.document_version_id.as_ref()
+ && msg_version_id != &document_version_id
{
- extensionless_key
+ tracing::debug!(
+ msg_version_id,
+ document_version_id,
+ "document version is not latest, skipping"
+ );
+ return Ok(());
} else {
build_cloud_storage_bucket_document_key(
&search_extractor_message.user_id,
&search_extractor_message.document_id,
- document_version_id,
- Some(search_extractor_message.file_type.as_str()),
+ &document_version_id,
)
};
diff --git a/rust/cloud-storage/search_upload_handler/Cargo.toml b/rust/cloud-storage/search_upload_handler/Cargo.toml
index 64ef5f9ddf..9e96904959 100644
--- a/rust/cloud-storage/search_upload_handler/Cargo.toml
+++ b/rust/cloud-storage/search_upload_handler/Cargo.toml
@@ -12,14 +12,13 @@ macro_aws_config = { path = "../macro_aws_config" }
aws_lambda_events = { workspace = true, features = ["eventbridge"] }
lambda_runtime = { workspace = true }
macro_entrypoint = { path = "../macro_entrypoint" }
-model_file_type = { path = "../model_file_type" }
openssl = { workspace = true }
+s3_key = { path = "../s3_key" }
sqs_client = { path = "../sqs_client", default-features = false, features = [
"search",
] }
tokio = { workspace = true }
tracing = { workspace = true }
-urlencoding = { workspace = true }
[package.metadata.cargo-machete]
ignored = ["openssl"]
diff --git a/rust/cloud-storage/search_upload_handler/src/handler.rs b/rust/cloud-storage/search_upload_handler/src/handler.rs
index 8059877adc..49b6d8bbd9 100644
--- a/rust/cloud-storage/search_upload_handler/src/handler.rs
+++ b/rust/cloud-storage/search_upload_handler/src/handler.rs
@@ -1,5 +1,3 @@
-use std::str::FromStr;
-
use anyhow::Context;
use aws_lambda_events::event::eventbridge::EventBridgeEvent;
use document_storage_service_client::DocumentStorageServiceClient;
@@ -7,47 +5,9 @@ use lambda_runtime::{
Error, LambdaEvent,
tracing::{self},
};
-use model_file_type::FileType;
+use s3_key::DocumentKey;
use sqs_client::search::{SearchQueueMessage, document::SearchExtractorMessage};
-#[derive(Debug)]
-struct DocumentKeyParts {
- pub user_id: String,
- pub document_id: String,
- pub document_version_id: String,
- pub file_type: Option<String>,
-}
-
-impl TryFrom<String> for DocumentKeyParts {
- type Error = anyhow::Error;
-
- /// Tries to convert the document key into it's parts
- /// Supports both extensionless keys (`user_id/document_id/version_id`)
- /// and legacy keys with extension (`user_id/document_id/version_id.file_type`)
- fn try_from(value: String) -> Result<Self, Self::Error> {
- let parts: Vec<&str> = value.split('/').collect();
-
- if parts.len() != 3 {
- anyhow::bail!("expected 3 parts, got {}", parts.len());
- }
-
- let file: Vec<&str> = parts[2].split('.').collect::<Vec<&str>>();
-
- let (document_version_id, file_type) = if file.len() == 2 {
- (file[0].to_string(), Some(file[1].to_string()))
- } else {
- (parts[2].to_string(), None)
- };
-
- Ok(Self {
- user_id: parts[0].to_string(),
- document_id: parts[1].to_string(),
- document_version_id,
- file_type,
- })
- }
-}
-
/// Handles the Eventbridge event
#[tracing::instrument(skip(sqs_client, dss_client), err)]
pub async fn handler(
@@ -66,50 +26,37 @@ pub async fn handler(
.unwrap_or("")
.to_string();
- let key = match urlencoding::decode(&key) {
- Ok(decoded) => decoded.to_string(),
+ let document_key = match DocumentKey::from_s3_key(&key) {
+ Ok(key) => key,
Err(e) => {
- tracing::warn!(error=?e, key=%key, "unable to decode key");
- return Ok(()); // Skip processing if key cannot be decoded
+ tracing::warn!(error=?e, "unable to parse key");
+ return Ok(());
}
};
- // Ignore temp files as it leads to failures
- if key.starts_with("temp_files/") {
+ if document_key.is_temp() {
tracing::trace!("skipping temp file");
return Ok(());
}
- let document_key_parts: DocumentKeyParts = match key.try_into() {
- Ok(parts) => parts,
- Err(e) => {
- tracing::warn!(error=?e, "unable to decode key");
- return Ok(()); // Skip processing if key cannot be decoded
- }
- };
+ let document_id = document_key.document_id();
- tracing::trace!(document_key_parts=?document_key_parts, "processing document key");
+ tracing::trace!(?document_key, "processing document key");
- // Resolve file type: use key extension if available (legacy), fall back to DSS lookup (extensionless)
- let file_type = match &document_key_parts.file_type {
- Some(ft) => FileType::from_str(ft).context("unable to parse file type")?,
- None => {
- let document_basic = dss_client
- .get_document_basic(&document_key_parts.document_id)
- .await
- .context("Failed to fetch document basic info")?
- .ok_or_else(|| anyhow::anyhow!("document not found"))?;
+ let document_basic = dss_client
+ .get_document_basic(document_id)
+ .await
+ .context("Failed to fetch document basic info")?
+ .ok_or_else(|| anyhow::anyhow!("document not found"))?;
- document_basic
- .try_file_type()
- .ok_or_else(|| anyhow::anyhow!("file type not found"))?
- }
- };
+ let file_type = document_basic
+ .try_file_type()
+ .ok_or_else(|| anyhow::anyhow!("file type not found"))?;
let search_extractor_message = SearchExtractorMessage {
- user_id: document_key_parts.user_id,
- document_id: document_key_parts.document_id,
- document_version_id: Some(document_key_parts.document_version_id),
+ user_id: document_basic.owner.to_string(),
+ document_id: document_id.to_string(),
+ document_version_id: document_key.version_id_string(),
file_type,
};
diff --git a/rust/cloud-storage/sqs_client/Cargo.toml b/rust/cloud-storage/sqs_client/Cargo.toml
index 9999eed3c0..07eeceda1f 100644
--- a/rust/cloud-storage/sqs_client/Cargo.toml
+++ b/rust/cloud-storage/sqs_client/Cargo.toml
@@ -38,6 +38,7 @@ aws-sdk-sqs = { workspace = true }
chrono = { workspace = true, optional = true }
email = { path = "../email", features = ["ports"], optional = true }
model = { path = "../model", optional = true }
+s3_key = { path = "../s3_key" }
models_email = { path = "../models_email", optional = true }
serde = { workspace = true }
serde_json = { workspace = true }
diff --git a/rust/cloud-storage/sqs_client/src/search/document.rs b/rust/cloud-storage/sqs_client/src/search/document.rs
index bf64d329b6..08d516ab93 100644
--- a/rust/cloud-storage/sqs_client/src/search/document.rs
+++ b/rust/cloud-storage/sqs_client/src/search/document.rs
@@ -1,5 +1,6 @@
// TODO: remove dependency on model crate
-use model::document::{BackfillSearchDocumentInformation, CONVERTED_DOCUMENT_FILE_NAME, FileType};
+use model::document::{BackfillSearchDocumentInformation, FileType};
+use s3_key::CONVERTED_DOCUMENT_FILE_NAME;
#[derive(serde::Serialize, serde::Deserialize, PartialEq, Eq, Debug)]
pub struct DocumentId {
diff --git a/rust/cloud-storage/static_file_service/Cargo.toml b/rust/cloud-storage/static_file_service/Cargo.toml
index c40341bfb2..88a363fa89 100644
--- a/rust/cloud-storage/static_file_service/Cargo.toml
+++ b/rust/cloud-storage/static_file_service/Cargo.toml
@@ -34,6 +34,7 @@ macro_middleware = { path = "../macro_middleware", default-features = false, fea
"auth",
] }
model = { path = "../model" }
+s3_key = { path = "../s3_key" }
models_sfs = { path = "../models_sfs" }
secretsmanager_client = { path = "../secretsmanager_client" }
serde = { workspace = true }
diff --git a/rust/cloud-storage/static_file_service/src/api/file/get_file.rs b/rust/cloud-storage/static_file_service/src/api/file/get_file.rs
index e99ee32bd8..9ef09d5346 100644
--- a/rust/cloud-storage/static_file_service/src/api/file/get_file.rs
+++ b/rust/cloud-storage/static_file_service/src/api/file/get_file.rs
@@ -44,8 +44,7 @@ pub async fn handle_get_presigned_url(
return Err((StatusCode::NOT_FOUND, "file not yet uploaded").into_response());
}
- // Get presigned URL for file
- let s3_key = format!("file/{}", file_id);
+ let s3_key = s3_key::StaticFileKey::new(&file_id).to_key();
let presigned_url = storage_client
.get_presigned_url(s3_key)
.await
diff --git a/rust/cloud-storage/static_file_service/src/api/file/put_presigned_url.rs b/rust/cloud-storage/static_file_service/src/api/file/put_presigned_url.rs
index 24b1e3ada5..f8a8b2f982 100644
--- a/rust/cloud-storage/static_file_service/src/api/file/put_presigned_url.rs
+++ b/rust/cloud-storage/static_file_service/src/api/file/put_presigned_url.rs
@@ -48,7 +48,8 @@ pub async fn put_presigned_url(
}?;
let id: String = Uuid::new_v4().to_string();
- let s3_key = format!("file/{}", id);
+ let static_file_key = s3_key::StaticFileKey::new(&id);
+ let s3_key = static_file_key.to_key();
let permalink = format!("{}/{}", ctx.config.service_url, s3_key);
let owner_id = if !user.user_id.is_empty() {
diff --git a/rust/cloud-storage/target/lambda/dataloss_prevention_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/dataloss_prevention_handler/bootstrap.zip
index 56f82720ea..e75c8715c8 100644
Binary files a/rust/cloud-storage/target/lambda/dataloss_prevention_handler/bootstrap.zip and b/rust/cloud-storage/target/lambda/dataloss_prevention_handler/bootstrap.zip differ
diff --git a/rust/cloud-storage/target/lambda/delete_chat_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/delete_chat_handler/bootstrap.zip
index 63e32dee54..8517f6299f 100644
Binary files a/rust/cloud-storage/target/lambda/delete_chat_handler/bootstrap.zip and b/rust/cloud-storage/target/lambda/delete_chat_handler/bootstrap.zip differ
diff --git a/rust/cloud-storage/target/lambda/deleted_item_poller/bootstrap.zip b/rust/cloud-storage/target/lambda/deleted_item_poller/bootstrap.zip
index eee99b78e9..fdec71bd1d 100644
Binary files a/rust/cloud-storage/target/lambda/deleted_item_poller/bootstrap.zip and b/rust/cloud-storage/target/lambda/deleted_item_poller/bootstrap.zip differ
diff --git a/rust/cloud-storage/target/lambda/document_text_extractor/bootstrap.zip b/rust/cloud-storage/target/lambda/document_text_extractor/bootstrap.zip
index 5d9b4865e3..5a9048d280 100644
Binary files a/rust/cloud-storage/target/lambda/document_text_extractor/bootstrap.zip and b/rust/cloud-storage/target/lambda/document_text_extractor/bootstrap.zip differ
diff --git a/rust/cloud-storage/target/lambda/docx_unzip_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/docx_unzip_handler/bootstrap.zip
index c690faa013..fafdc845ff 100644
Binary files a/rust/cloud-storage/target/lambda/docx_unzip_handler/bootstrap.zip and b/rust/cloud-storage/target/lambda/docx_unzip_handler/bootstrap.zip differ
diff --git a/rust/cloud-storage/target/lambda/email_refresh_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/email_refresh_handler/bootstrap.zip
index e8312a9e46..560e869d5c 100644
Binary files a/rust/cloud-storage/target/lambda/email_refresh_handler/bootstrap.zip and b/rust/cloud-storage/target/lambda/email_refresh_handler/bootstrap.zip differ
diff --git a/rust/cloud-storage/target/lambda/email_scheduled_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/email_scheduled_handler/bootstrap.zip
index 0c679354cd..1600af638d 100644
Binary files a/rust/cloud-storage/target/lambda/email_scheduled_handler/bootstrap.zip and b/rust/cloud-storage/target/lambda/email_scheduled_handler/bootstrap.zip differ
diff --git a/rust/cloud-storage/target/lambda/email_sfs_delete_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/email_sfs_delete_handler/bootstrap.zip
index 443d3ec0f1..f1e42bc12a 100644
Binary files a/rust/cloud-storage/target/lambda/email_sfs_delete_handler/bootstrap.zip and b/rust/cloud-storage/target/lambda/email_sfs_delete_handler/bootstrap.zip differ
diff --git a/rust/cloud-storage/target/lambda/email_suppression_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/email_suppression_handler/bootstrap.zip
index 148b5bd6b4..cef39e46a1 100644
Binary files a/rust/cloud-storage/target/lambda/email_suppression_handler/bootstrap.zip and b/rust/cloud-storage/target/lambda/email_suppression_handler/bootstrap.zip differ
diff --git a/rust/cloud-storage/target/lambda/organization_retention_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/organization_retention_handler/bootstrap.zip
index b8f4524f36..e434eae691 100644
Binary files a/rust/cloud-storage/target/lambda/organization_retention_handler/bootstrap.zip and b/rust/cloud-storage/target/lambda/organization_retention_handler/bootstrap.zip differ
diff --git a/rust/cloud-storage/target/lambda/organization_retention_trigger/bootstrap.zip b/rust/cloud-storage/target/lambda/organization_retention_trigger/bootstrap.zip
index ea0a2089a2..1cc3dca60d 100644
Binary files a/rust/cloud-storage/target/lambda/organization_retention_trigger/bootstrap.zip and b/rust/cloud-storage/target/lambda/organization_retention_trigger/bootstrap.zip differ
diff --git a/rust/cloud-storage/target/lambda/search_upload_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/search_upload_handler/bootstrap.zip
index d0271916ba..a97e2e6388 100644
Binary files a/rust/cloud-storage/target/lambda/search_upload_handler/bootstrap.zip and b/rust/cloud-storage/target/lambda/search_upload_handler/bootstrap.zip differ
diff --git a/rust/cloud-storage/target/lambda/upload_extractor_lambda_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/upload_extractor_lambda_handler/bootstrap.zip
index 53bef4945a..ed61c35d82 100644
Binary files a/rust/cloud-storage/target/lambda/upload_extractor_lambda_handler/bootstrap.zip and b/rust/cloud-storage/target/lambda/upload_extractor_lambda_handler/bootstrap.zip differ
diff --git a/rust/cloud-storage/target/lambda/upload_extractor_lambda_trigger/bootstrap.zip b/rust/cloud-storage/target/lambda/upload_extractor_lambda_trigger/bootstrap.zip
index 8aba093b80..0be33dc684 100644
Binary files a/rust/cloud-storage/target/lambda/upload_extractor_lambda_trigger/bootstrap.zip and b/rust/cloud-storage/target/lambda/upload_extractor_lambda_trigger/bootstrap.zip differ
diff --git a/rust/cloud-storage/target/lambda/user_link_cleanup_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/user_link_cleanup_handler/bootstrap.zip
index 71419bd7e1..9f654b21fa 100644
Binary files a/rust/cloud-storage/target/lambda/user_link_cleanup_handler/bootstrap.zip and b/rust/cloud-storage/target/lambda/user_link_cleanup_handler/bootstrap.zip differ
diff --git a/rust/cloud-storage/target/lambda/worker_trigger/bootstrap.zip b/rust/cloud-storage/target/lambda/worker_trigger/bootstrap.zip
index 7b78cb39d6..4be2371584 100644
Binary files a/rust/cloud-storage/target/lambda/worker_trigger/bootstrap.zip and b/rust/cloud-storage/target/lambda/worker_trigger/bootstrap.zip differ
diff --git a/rust/cloud-storage/upload_extractor_lambda_trigger/Cargo.toml b/rust/cloud-storage/upload_extractor_lambda_trigger/Cargo.toml
index 5360f39a85..232031b950 100644
--- a/rust/cloud-storage/upload_extractor_lambda_trigger/Cargo.toml
+++ b/rust/cloud-storage/upload_extractor_lambda_trigger/Cargo.toml
@@ -13,6 +13,7 @@ lambda_runtime = { workspace = true }
macro_aws_config = { path = "../macro_aws_config" }
macro_entrypoint = { path = "../macro_entrypoint" }
models_bulk_upload = { path = "../models_bulk_upload" }
+s3_key = { path = "../s3_key" }
openssl = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
diff --git a/rust/cloud-storage/upload_extractor_lambda_trigger/src/main.rs b/rust/cloud-storage/upload_extractor_lambda_trigger/src/main.rs
index c32a6fe207..569e8ebca0 100644
--- a/rust/cloud-storage/upload_extractor_lambda_trigger/src/main.rs
+++ b/rust/cloud-storage/upload_extractor_lambda_trigger/src/main.rs
@@ -36,14 +36,12 @@ async fn handler(
) -> Result<(), Error> {
let key = event.payload.detail.object.key;
- if !key.starts_with("extract/") {
- tracing::warn!("Skipping object that doesn't start with extract/: {}", key);
- return Err(Error::from(
- "Skipping object that doesn't start with extract/: {}",
- ));
- }
+ let staging_key = s3_key::BulkUploadStagingKey::from_s3_key(&key).map_err(|e| {
+ tracing::warn!(error=?e, key=%key, "skipping non-extract key");
+ Error::from("key is not a bulk upload staging key")
+ })?;
- let upload_request_id = key.trim_start_matches("extract/");
+ let upload_request_id = staging_key.request_id.as_str();
tracing::info!("Processing request: {}", upload_request_id);
@@ -74,7 +72,7 @@ async fn handler(
sqs_client
.enqueue_upload_extractor_unzip(
upload_request_id,
- key.as_str(),
+ &staging_key.to_key(),
bulk_upload_request.user_id.as_str(),
&bulk_upload_request.name,
&bulk_upload_request.parent_id,