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 create document to documents hex (#1609)

Will Hutchinson04dd6a67bc46
diff --git a/js/app/packages/service-clients/service-storage/client.ts b/js/app/packages/service-clients/service-storage/client.ts
index 3c2344ffc8..05e279f98c 100644
--- a/js/app/packages/service-clients/service-storage/client.ts
+++ b/js/app/packages/service-clients/service-storage/client.ts
@@ -43,7 +43,7 @@ import {
CloudStorageItemType as CloudStorageItemTypeMap,
} from './generated/schemas/cloudStorageItemType';
import type { CreateCommentResponse } from './generated/schemas/createCommentResponse';
-import type { CreateDocumentHandler200 as CreateDocumentResponse } from './generated/schemas/createDocumentHandler200';
+import type { CreateDocument200 as CreateDocumentResponse } from './generated/schemas/createDocument200';
import type { CreateDocumentRequest } from './generated/schemas/createDocumentRequest';
import type { CreateInstructionsDocumentResponse } from './generated/schemas/createInstructionsDocumentResponse';
import type { CreateProjectResponse } from './generated/schemas/createProjectResponse';
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createDocumentHandler200.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createDocument200.ts
similarity index 55%
rename from js/app/packages/service-clients/service-storage/generated/schemas/createDocumentHandler200.ts
rename to js/app/packages/service-clients/service-storage/generated/schemas/createDocument200.ts
index c42d7e5533..5b2a5c4df1 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/createDocumentHandler200.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createDocument200.ts
@@ -4,11 +4,11 @@
* document_storage_service
* OpenAPI spec version: 0.1.0
*/
-import type { CreateDocumentHandler200DataOneOf } from './createDocumentHandler200DataOneOf';
+import type { CreateDocument200DataOneOf } from './createDocument200DataOneOf';
-export type CreateDocumentHandler200 = {
+export type CreateDocument200 = {
/** Data to be returned */
- data: CreateDocumentHandler200DataOneOf;
+ data: CreateDocument200DataOneOf;
/** Indicates if an error occurred */
error: boolean;
};
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createDocument200DataOneOf.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createDocument200DataOneOf.ts
new file mode 100644
index 0000000000..9e98bb4b8b
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createDocument200DataOneOf.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+import type { CreateDocument200DataOneOfAllOf } from './createDocument200DataOneOfAllOf';
+import type { DocumentResponse } from './documentResponse';
+
+export type CreateDocument200DataOneOf = DocumentResponse &
+ CreateDocument200DataOneOfAllOf;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createDocumentHandler200DataOneOfAllOf.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createDocument200DataOneOfAllOf.ts
similarity index 52%
rename from js/app/packages/service-clients/service-storage/generated/schemas/createDocumentHandler200DataOneOfAllOf.ts
rename to js/app/packages/service-clients/service-storage/generated/schemas/createDocument200DataOneOfAllOf.ts
index 175ae3b3ef..8aff06ec9b 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/createDocumentHandler200DataOneOfAllOf.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createDocument200DataOneOfAllOf.ts
@@ -4,11 +4,11 @@
* document_storage_service
* OpenAPI spec version: 0.1.0
*/
-import type { CreateDocumentHandler200DataOneOfAllOfFileType } from './createDocumentHandler200DataOneOfAllOfFileType';
+import type { CreateDocument200DataOneOfAllOfFileType } from './createDocument200DataOneOfAllOfFileType';
-export type CreateDocumentHandler200DataOneOfAllOf = {
+export type CreateDocument200DataOneOfAllOf = {
/** Content type of the document converted from file type */
contentType: string;
/** The file type of the document */
- fileType?: CreateDocumentHandler200DataOneOfAllOfFileType;
+ fileType?: CreateDocument200DataOneOfAllOfFileType;
};
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createDocumentHandler200DataOneOfAllOfFileType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createDocument200DataOneOfAllOfFileType.ts
similarity index 68%
rename from js/app/packages/service-clients/service-storage/generated/schemas/createDocumentHandler200DataOneOfAllOfFileType.ts
rename to js/app/packages/service-clients/service-storage/generated/schemas/createDocument200DataOneOfAllOfFileType.ts
index 1ef753feb6..ba5a7bd225 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/createDocumentHandler200DataOneOfAllOfFileType.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createDocument200DataOneOfAllOfFileType.ts
@@ -8,4 +8,4 @@
/**
* The file type of the document
*/
-export type CreateDocumentHandler200DataOneOfAllOfFileType = string | null;
+export type CreateDocument200DataOneOfAllOfFileType = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createDocumentHandler200DataOneOf.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createDocumentHandler200DataOneOf.ts
deleted file mode 100644
index 19cbf2b1a8..0000000000
--- a/js/app/packages/service-clients/service-storage/generated/schemas/createDocumentHandler200DataOneOf.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * document_storage_service
- * OpenAPI spec version: 0.1.0
- */
-
-import type { CreateDocumentHandler200DataOneOfAllOf } from './createDocumentHandler200DataOneOfAllOf';
-import type { DocumentResponse } from './documentResponse';
-
-export type CreateDocumentHandler200DataOneOf = DocumentResponse &
- CreateDocumentHandler200DataOneOfAllOf;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
index c841d0228b..7c96e33590 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
@@ -122,10 +122,10 @@ export * from './createCommentRequestThreadId';
export * from './createCommentResponse';
export * from './createCommentResponseAllOf';
export * from './createCommentResponseAllOfAnchor';
-export * from './createDocumentHandler200';
-export * from './createDocumentHandler200DataOneOf';
-export * from './createDocumentHandler200DataOneOfAllOf';
-export * from './createDocumentHandler200DataOneOfAllOfFileType';
+export * from './createDocument200';
+export * from './createDocument200DataOneOf';
+export * from './createDocument200DataOneOfAllOf';
+export * from './createDocument200DataOneOfAllOfFileType';
export * from './createDocumentRequest';
export * from './createDocumentRequestBranchedFromId';
export * from './createDocumentRequestBranchedFromVersionId';
diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.ts
index 13a289b31d..dbf102a5a4 100644
--- a/js/app/packages/service-clients/service-storage/generated/zod.ts
+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts
@@ -1182,9 +1182,11 @@ export const getUserDocumentsHandlerResponse = zod.object({
});
/**
- * @summary Handles creating a document
+ * Creates a new document, generates an S3 presigned upload URL, and returns
+the document metadata with the URL for the client to upload to.
+ * @summary Handler for `POST /documents`.
*/
-export const createDocumentHandlerBody = zod.object({
+export const createDocumentBody = zod.object({
branchedFromId: zod
.string()
.nullish()
@@ -1218,7 +1220,11 @@ export const createDocumentHandlerBody = zod.object({
.string()
.nullish()
.describe('Optional file type of the document.'),
- id: zod.string().nullish().describe('The id of the document in the database'),
+ id: zod
+ .string()
+ .uuid()
+ .nullish()
+ .describe('The id of the document in the database'),
isTask: zod
.boolean()
.optional()
@@ -1237,7 +1243,7 @@ export const createDocumentHandlerBody = zod.object({
.describe(
'The content type of the document (currently only used for logging matches against file type).'
),
- projectId: zod.string().nullish(),
+ projectId: zod.string().uuid().nullish(),
sha: zod.string().describe('The sha of the document.'),
skipHistory: zod
.boolean()
@@ -1247,7 +1253,7 @@ export const createDocumentHandlerBody = zod.object({
),
});
-export const createDocumentHandlerResponse = zod.object({
+export const createDocumentResponse = zod.object({
data: zod
.object({
documentMetadata: zod.object({
@@ -1360,6 +1366,7 @@ export const createTaskHandlerBody = zod
.object({
projectId: zod
.string()
+ .uuid()
.nullish()
.describe('Optional project id to associate the task with'),
propertyValues: zod
diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.json
index 1d787b79f8..7d3c715715 100644
--- a/js/app/packages/service-clients/service-storage/openapi.json
+++ b/js/app/packages/service-clients/service-storage/openapi.json
@@ -884,8 +884,9 @@
},
"post": {
"tags": ["document"],
- "summary": "Handles creating a document",
- "operationId": "create_document_handler",
+ "summary": "Handler for `POST /documents`.",
+ "description": "Creates a new document, generates an S3 presigned upload URL, and returns\nthe document metadata with the URL for the client to upload to.",
+ "operationId": "create_document",
"requestBody": {
"content": {
"application/json": {
@@ -945,7 +946,7 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/GenericErrorResponse"
+ "$ref": "#/components/schemas/ErrorResponse"
}
}
}
@@ -955,17 +956,17 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/GenericErrorResponse"
+ "$ref": "#/components/schemas/ErrorResponse"
}
}
}
},
- "403": {
+ "409": {
"description": "",
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/GenericErrorResponse"
+ "$ref": "#/components/schemas/ErrorResponse"
}
}
}
@@ -975,7 +976,7 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/GenericErrorResponse"
+ "$ref": "#/components/schemas/ErrorResponse"
}
}
}
@@ -5756,6 +5757,7 @@
},
"id": {
"type": ["string", "null"],
+ "format": "uuid",
"description": "The id of the document in the database"
},
"isTask": {
@@ -5771,7 +5773,8 @@
"description": "The content type of the document (currently only used for logging matches against file type)."
},
"projectId": {
- "type": ["string", "null"]
+ "type": ["string", "null"],
+ "format": "uuid"
},
"sha": {
"type": "string",
@@ -5848,6 +5851,7 @@
"properties": {
"projectId": {
"type": ["string", "null"],
+ "format": "uuid",
"description": "Optional project id to associate the task with"
},
"propertyValues": {
diff --git a/js/app/packages/service-clients/service-storage/service.ts b/js/app/packages/service-clients/service-storage/service.ts
index 8b58add12d..33ca019ae7 100644
--- a/js/app/packages/service-clients/service-storage/service.ts
+++ b/js/app/packages/service-clients/service-storage/service.ts
@@ -403,21 +403,18 @@ export const StorageService = new Svc('Document++ Storage Service API')
throws: withFetchErrors(),
})
.fn('createDocument', {
- description: schemas.createDocumentHandlerResponse.description!,
- args: schemas.createDocumentHandlerBody.shape,
+ description: schemas.createDocumentResponse.description!,
+ args: schemas.createDocumentBody.shape,
result: {
metadata:
- schemas.createDocumentHandlerResponse.shape.data._def.left.shape
+ schemas.createDocumentResponse.shape.data._def.left.shape
.documentMetadata,
presignedUrl:
- schemas.createDocumentHandlerResponse.shape.data._def.left.shape
- .presignedUrl,
+ schemas.createDocumentResponse.shape.data._def.left.shape.presignedUrl,
contentType:
- schemas.createDocumentHandlerResponse.shape.data._def.right.shape
- .contentType,
+ schemas.createDocumentResponse.shape.data._def.right.shape.contentType,
fileType:
- schemas.createDocumentHandlerResponse.shape.data._def.right.shape
- .fileType,
+ schemas.createDocumentResponse.shape.data._def.right.shape.fileType,
},
modifies: true,
throws: withFetchErrors('INVALID_RESPONSE'),
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 6a6535584b..ef492432c5 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -2911,20 +2911,24 @@ dependencies = [
"ai",
"anyhow",
"async-trait",
+ "aws-sdk-s3",
"axum",
"axum-extra",
+ "base64 0.22.1",
"chrono",
"cloudfront_sign",
"document_sub_type",
"dotenvy",
"entity_access",
"futures",
+ "hex",
"http-body-util",
"lexical_client",
"macro_aws_config",
"macro_db_migrator",
"macro_project_utils",
"macro_user_id",
+ "macro_uuid",
"mockall",
"model",
"model-error-response",
diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rs
index 07707c9b87..ed3b6ae567 100644
--- a/rust/cloud-storage/document_storage_service/src/api/context.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs
@@ -12,9 +12,11 @@ use comms::{
};
use comms_service::CommsHandlerState;
use connection_gateway_client::client::ConnectionGatewayClient;
+use documents_hex::domain::ports::TaskPropertiesPort;
use documents_hex::domain::service::DocumentServiceImpl;
use documents_hex::inbound::axum_router::DocumentRouterState;
use documents_hex::outbound::pg_document_repo::PgDocumentRepo;
+use documents_hex::outbound::s3_upload_url::S3UploadUrlAdapter;
use dynamodb_client::DynamodbClient;
use email::{domain::service::EmailServiceImpl, outbound::EmailPgRepo};
use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};
@@ -43,7 +45,9 @@ use soup::{
use sqlx::PgPool;
use std::sync::Arc;
use sync_service_client::SyncServiceClient;
-use system_properties::{PgSystemPropertiesRepository, SystemPropertiesServiceImpl};
+use system_properties::{
+ PgSystemPropertiesRepository, SystemPropertiesService as _, SystemPropertiesServiceImpl,
+};
#[derive(Debug, Clone)]
pub struct InternalFlag {
@@ -84,9 +88,23 @@ type PropertiesService = PropertiesServiceImpl<
/// Type alias for the entity access service.
pub(crate) type EntityAccessService = EntityAccessServiceImpl<PgAccessRepository>;
+/// Adapter implementing [`TaskPropertiesPort`] for the system properties service.
+pub(crate) struct TaskPropertiesAdapter(pub Arc<SystemPropertiesService>);
+
+impl TaskPropertiesPort for TaskPropertiesAdapter {
+ async fn attach_task_properties(&self, entity_ids: Vec<String>) -> anyhow::Result<()> {
+ self.0
+ .attach_task_properties(entity_ids)
+ .await
+ .map_err(Into::into)
+ }
+}
+
/// Type alias for the documents router state.
-pub(crate) type DocumentsState =
- DocumentRouterState<DocumentServiceImpl<PgDocumentRepo>, EntityAccessService>;
+pub(crate) type DocumentsState = DocumentRouterState<
+ DocumentServiceImpl<PgDocumentRepo, S3UploadUrlAdapter, TaskPropertiesAdapter>,
+ EntityAccessService,
+>;
/// Type alias for the ChannelServiceImpl used by comms
pub(crate) type CommsChannelService =
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_handler.rs b/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_handler.rs
deleted file mode 100644
index 3c70df9abc..0000000000
--- a/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_handler.rs
+++ /dev/null
@@ -1,120 +0,0 @@
-use crate::api::middleware::internal_access::InternalUser;
-use crate::api::{
- context::ApiContext,
- documents::{
- create_document::create_document_v2,
- utils::{self},
- },
-};
-use axum::{Extension, extract::State, http::StatusCode, response::IntoResponse};
-use macro_middleware::cloud_storage::ensure_access::project::ProjectBodyAccessLevelExtractor;
-use model::document::FileTypeExt;
-use model::document::response::{CreateDocumentRequest, CreateDocumentResponse};
-use model::{
- document::FileType,
- response::{GenericErrorResponse, GenericResponse},
-};
-use model_user::axum_extractor::MacroUserExtractor;
-use models_permissions::share_permission::access_level::EditAccessLevel;
-use std::str::FromStr;
-
-/// Handles creating a document
-#[utoipa::path(
- post,
- tag = "document",
- path = "/documents",
- request_body = CreateDocumentRequest,
- responses(
- (status = 200, body=inline(CreateDocumentResponse)),
- (status = 401, body=GenericErrorResponse),
- (status = 403, body=GenericErrorResponse),
- (status = 400, body=GenericErrorResponse),
- (status = 500, body=GenericErrorResponse),
- )
- )]
-#[tracing::instrument(skip(state, user_context, project), fields(user_id=?user_context.macro_user_id))]
-#[axum::debug_handler(state = ApiContext)]
-pub(in crate::api) async fn create_document_handler(
- State(state): State<ApiContext>,
- internal_user: Option<Extension<InternalUser>>,
- user_context: MacroUserExtractor,
- project: ProjectBodyAccessLevelExtractor<EditAccessLevel, CreateDocumentRequest>,
-) -> impl IntoResponse {
- let req = project.into_inner();
-
- // email linking is internal only
- if req.email_attachment_id.is_some() && internal_user.is_none() {
- return GenericResponse::builder()
- .message("can't link email in external request")
- .is_error(true)
- .send(StatusCode::UNAUTHORIZED);
- }
-
- let user_provided_file_type: Option<FileType> = req
- .file_type
- .as_deref()
- .and_then(|f| FileType::from_str(f).ok());
-
- let (document_name, file_type) = match user_provided_file_type {
- Some(file_type) => {
- // Strips any accidentally added extension from document name
- let document_name = FileType::clean_document_name(&req.document_name);
- (document_name.unwrap_or(req.document_name), Some(file_type))
- }
- None => match FileType::split_suffix_match(req.document_name.as_str()) {
- Some((file_name, extension)) => {
- let file_type: Option<FileType> = FileType::from_str(extension).ok();
- (file_name.to_string(), file_type)
- }
- None => (req.document_name, None),
- },
- };
-
- // Log if the user provided mime type does not match the file type
- if let (Some(file_type), Some(user_mime_type)) = (file_type, req.mime_type)
- && user_mime_type != file_type.mime_type()
- {
- tracing::warn!(
- file_type=?file_type,
- mime_type=?user_mime_type,
- "provided mime type does not match file type"
- );
- }
-
- let create_document_response_data = create_document_v2::create_document(
- &state,
- create_document_v2::CreateDocumentParams {
- id: req.id.as_deref(),
- sha: &req.sha,
- document_name: &document_name,
- owner: user_context.macro_user_id,
- file_type,
- job_id: req.job_id.as_deref(),
- project_id: req.project_id.as_deref(),
- email_attachment_id: req.email_attachment_id,
- created_at: req.created_at.as_ref(),
- is_task: req.is_task,
- skip_history: req.skip_history,
- },
- )
- .await;
-
- let response_data = match create_document_response_data {
- Ok(response_data) => response_data,
- Err((status_code, message, document_id)) => {
- tracing::error!(error=?message, "unable to create document");
- if let Some(document_id) = document_id {
- tracing::info!(document_id=?document_id, "cleaning up document");
- utils::handle_document_creation_error_cleanup(&state.db, document_id).await;
- }
- return GenericResponse::builder()
- .message(message.as_str())
- .is_error(true)
- .send(status_code);
- }
- };
-
- return GenericResponse::builder()
- .data(&response_data)
- .send(StatusCode::OK);
-}
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_v2.rs b/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_v2.rs
deleted file mode 100644
index 09f31364b7..0000000000
--- a/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_v2.rs
+++ /dev/null
@@ -1,196 +0,0 @@
-use crate::api::context::ApiContext;
-use axum::http::StatusCode;
-use chrono::{DateTime, Utc};
-use document_sub_type::DocumentSubType;
-use macro_user_id::cowlike::CowLike;
-use macro_user_id::user_id::MacroUserIdStr;
-use model::document::response::CreateDocumentResponseData;
-use model::document::response::{DocumentResponse, DocumentResponseMetadata};
-use model::document::{ContentType, FileType, build_cloud_storage_bucket_document_key};
-use models_permissions::share_permission::SharePermissionV2;
-use system_properties::SystemPropertiesService;
-use uuid::Uuid;
-
-/// Parameters for creating a document
-pub struct CreateDocumentParams<'a> {
- pub id: Option<&'a str>,
- pub sha: &'a str,
- pub document_name: &'a str,
- pub owner: MacroUserIdStr<'a>,
- pub file_type: Option<FileType>,
- pub job_id: Option<&'a str>,
- pub project_id: Option<&'a str>,
- pub email_attachment_id: Option<Uuid>,
- pub created_at: Option<&'a DateTime<Utc>>,
- pub is_task: bool,
- pub skip_history: bool,
-}
-
-/// Creates a document in the database
-/// Creates a presigned post url to upload the document to the required bucket
-/// In the event of an error, returns status code, error message and optional document id.
-/// **note** If document id is present, cleanup is necessary.
-#[tracing::instrument(skip(ctx, params), fields(user_id=?params.owner))]
-pub async fn create_document(
- ctx: &ApiContext,
- params: CreateDocumentParams<'_>,
-) -> Result<CreateDocumentResponseData, (StatusCode, String, Option<String>)> {
- let CreateDocumentParams {
- id,
- sha,
- document_name,
- owner,
- file_type,
- job_id,
- project_id,
- email_attachment_id,
- created_at,
- is_task,
- skip_history,
- } = params;
-
- let owner = owner.into_owned();
-
- tracing::trace!("creating document v2");
-
- let share_permission = SharePermissionV2::new_document_share_permission(file_type);
-
- // create document metadata
- let document_metadata = macro_db_client::document::v2::create::create_document(
- &ctx.db,
- macro_db_client::document::v2::create::CreateDocumentArgs {
- id,
- sha,
- document_name,
- user_id: owner.clone(),
- file_type,
- project_id,
- project_name: None,
- share_permission: &share_permission,
- skip_history,
- email_attachment_id,
- created_at,
- is_task,
- },
- )
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "unable to create document metadata");
- if e.to_string().contains("document with ID already exists") {
- (
- StatusCode::CONFLICT,
- "document with ID already exists".to_string(),
- None,
- )
- } else {
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- "unable to create document metadata".to_string(),
- None,
- )
- }
- })?;
-
- // Some file types have upload jobs
- if let Some(job_id) = job_id {
- tracing::trace!(job_id=?job_id, document_id=?document_metadata.document_id, "updating upload job");
- if let Err(e) = macro_db_client::job::upload_job::update_upload_job(
- ctx.db.clone(),
- document_metadata.document_id.as_str(),
- job_id,
- )
- .await
- {
- tracing::error!(error=?e, document_id=?document_metadata.document_id, "failed to update upload job");
- return Err((
- StatusCode::INTERNAL_SERVER_ERROR,
- "unable to update upload job".to_string(),
- Some(document_metadata.document_id),
- ));
- }
- }
-
- let key = build_cloud_storage_bucket_document_key(
- document_metadata.owner.as_ref(),
- &document_metadata.document_id,
- document_metadata.document_version_id,
- file_type.as_ref().map(|s| s.as_str()),
- );
-
- let content_type = match file_type {
- Some(FileType::Docx) => ContentType::Docx,
- _ => file_type.into(),
- };
-
- let mime_type = content_type.mime_type().to_string();
-
- let presigned_url: String = match file_type {
- Some(FileType::Docx) => ctx.s3_client.put_docx_upload_presigned_url(key.as_str(), sha, content_type).await.map_err(|err| {
- tracing::error!(error=?err, key=?key, document_id=?document_metadata.document_id, "unable to generate presigned url");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- "unable to generate presigned url".to_string(),
- Some(document_metadata.document_id.clone()),
- )
- })?,
- _ => ctx.s3_client.put_document_storage_presigned_url(key.as_str(), sha, content_type).await.map_err(|err| {
- tracing::error!(error=?err, key=?key, document_id=?document_metadata.document_id, "unable to generate presigned url");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- "unable to generate presigned url".to_string(),
- Some(document_metadata.document_id.clone()),
- )
- })?,
- };
-
- let document_response_metadata = match DocumentResponseMetadata::from_document_metadata(
- &document_metadata,
- ) {
- Ok(document_response_metadata) => document_response_metadata,
- Err(e) => {
- tracing::error!(error=?e, document_id=?document_metadata.document_id, "unable to convert document metadata. this should never happen");
- return Err((
- StatusCode::INTERNAL_SERVER_ERROR,
- "unable to convert document metadata".to_string(),
- Some(document_metadata.document_id),
- ));
- }
- };
-
- // update project modified if necessary
- macro_project_utils::update_project_modified(
- &ctx.db,
- macro_project_utils::ProjectModifiedArgs {
- project_id,
- old_project_id: None,
- user_id: owner.to_string(),
- },
- )
- .await;
-
- // Attach task properties if creating a task
- if document_response_metadata.sub_type == Some(DocumentSubType::Task)
- && let Err(e) = ctx
- .system_properties_service
- .attach_task_properties(vec![document_response_metadata.document_id.clone()])
- .await
- {
- tracing::error!(error=?e, document_id=?document_response_metadata.document_id, "failed to attach task properties");
- return Err((
- StatusCode::INTERNAL_SERVER_ERROR,
- "failed to attach task properties".to_string(),
- Some(document_response_metadata.document_id),
- ));
- }
-
- let response_data = CreateDocumentResponseData {
- document_response: DocumentResponse {
- document_metadata: document_response_metadata,
- presigned_url: Some(presigned_url),
- },
- content_type: mime_type,
- file_type: file_type.map(|f| f.to_string()),
- };
-
- Ok(response_data)
-}
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/create_document/mod.rs b/rust/cloud-storage/document_storage_service/src/api/documents/create_document/mod.rs
deleted file mode 100644
index f021cc0d6a..0000000000
--- a/rust/cloud-storage/document_storage_service/src/api/documents/create_document/mod.rs
+++ /dev/null
@@ -1,4 +0,0 @@
-mod create_document_handler;
-pub(in crate::api) mod create_document_v2;
-
-pub(in crate::api) use create_document_handler::*;
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/create_task.rs b/rust/cloud-storage/document_storage_service/src/api/documents/create_task.rs
index 4e9a4aafbf..ce00e4ab08 100644
--- a/rust/cloud-storage/document_storage_service/src/api/documents/create_task.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/documents/create_task.rs
@@ -1,4 +1,6 @@
use axum::{Json, extract::State, http::StatusCode};
+use documents_hex::domain::models::CreateDocumentRepoArgs;
+use documents_hex::domain::ports::DocumentService;
use macro_middleware::cloud_storage::ensure_access::project::ProjectBodyAccessLevelExtractor;
use model::document::FileType;
use model::response::ErrorResponse;
@@ -9,13 +11,7 @@ use models_properties::api::requests::SetPropertyValue;
use properties::PropertiesService;
use uuid::Uuid;
-use crate::api::{
- context::ApiContext,
- documents::{
- create_document::create_document_v2,
- utils::{self},
- },
-};
+use crate::api::context::ApiContext;
/// SHA256 hash of empty string - for an empty markdown document
const EMPTY_SHA256: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
@@ -37,7 +33,7 @@ pub struct CreateTaskRequest {
/// The name of the task
pub task_name: String,
/// Optional project id to associate the task with
- pub project_id: Option<String>,
+ pub project_id: Option<uuid::Uuid>,
/// Optional property values to set on the task
pub property_values: Option<Vec<PropertyInput>>,
}
@@ -81,41 +77,38 @@ pub(in crate::api) async fn create_task_handler(
let req = project.into_inner();
let user_id = user_context.user_context.user_id.clone();
- // Create task document metadata (empty content - client sets via sync service)
- let create_document_response_data = create_document_v2::create_document(
- &state,
- create_document_v2::CreateDocumentParams {
- id: None,
- sha: EMPTY_SHA256,
- document_name: &req.task_name,
- owner: user_context.macro_user_id,
- file_type: Some(FileType::Md),
- job_id: None,
- project_id: req.project_id.as_deref(),
- email_attachment_id: None,
- created_at: None,
- is_task: true,
- skip_history: false,
- },
- )
- .await;
+ let macro_user_id = user_context.macro_user_id;
- let response_data = match create_document_response_data {
- Ok(response_data) => response_data,
- Err((status_code, message, document_id)) => {
- tracing::error!(error=?message, "unable to create task document");
- if let Some(document_id) = document_id {
- tracing::info!(document_id=?document_id, "cleaning up document");
- utils::handle_document_creation_error_cleanup(&state.db, document_id).await;
- }
- return Err((
- status_code,
+ // Create task document metadata (empty content - client sets via sync service)
+ let response_data = state
+ .documents_state
+ .service
+ .create_document(
+ macro_user_id.clone(),
+ CreateDocumentRepoArgs {
+ id: None,
+ sha: EMPTY_SHA256.to_string(),
+ document_name: req.task_name,
+ user_id: macro_user_id,
+ file_type: Some(FileType::Md),
+ project_id: req.project_id,
+ email_attachment_id: None,
+ created_at: None,
+ is_task: true,
+ skip_history: false,
+ },
+ None,
+ )
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, "unable to create task document");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
message: "failed to create task document",
}),
- ));
- }
- };
+ )
+ })?;
let document_id = response_data
.document_response
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/mod.rs b/rust/cloud-storage/document_storage_service/src/api/documents/mod.rs
index ca0d4f5e8b..054e17f50c 100644
--- a/rust/cloud-storage/document_storage_service/src/api/documents/mod.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/documents/mod.rs
@@ -7,7 +7,6 @@ use tower::ServiceBuilder;
// needs to be public in api crate for swagger
pub(in crate::api) mod copy_document;
-pub(in crate::api) mod create_document;
pub(in crate::api) mod create_task;
pub(in crate::api) mod delete_document;
pub(in crate::api) mod edit_document;
@@ -55,23 +54,7 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
macro_middleware::auth::ensure_user_exists::handler,
)),
)
- .route(
- "/",
- post(create_document::create_document_handler).layer(
- ServiceBuilder::new()
- .layer(axum::middleware::from_fn(
- macro_middleware::auth::ensure_user_exists::handler,
- ))
- .layer(axum::middleware::from_fn_with_state(
- state.clone(),
- macro_middleware::user_permissions::attach_user_permissions::handler,
- ))
- .layer(axum::middleware::from_fn_with_state(
- state.clone(),
- macro_middleware::user_permissions::validate_user_quota::document_handler,
- )),
- ),
- )
+ // NOTE: POST / (create_document) is now served by the documents hex crate router
.route(
"/create_task",
post(create_task::create_task_handler).layer(
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/utils/mod.rs b/rust/cloud-storage/document_storage_service/src/api/documents/utils/mod.rs
index cde69340c4..948d12ebdb 100644
--- a/rust/cloud-storage/document_storage_service/src/api/documents/utils/mod.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/documents/utils/mod.rs
@@ -1,20 +1,6 @@
-use sqlx::{PgPool, Pool, Postgres};
+use sqlx::{Pool, Postgres};
use tracing::instrument;
-/// Deletes the document
-/// This is to only be used if document creation fails
-/// Normal document deletion is a "soft delete"
-#[instrument(skip(db))]
-pub(in crate::api::documents) async fn handle_document_creation_error_cleanup(
- db: &PgPool,
- document_id: String,
-) {
- // Delete from db
- let _ = macro_db_client::document::delete_document(db, &document_id)
- .await
- .map_err(|e| tracing::error!(error=?e, "failed to delete document"));
-}
-
/// Deletes a given document version if there was an error saving it
#[instrument(skip(db))]
pub(in crate::api::documents) async fn cleanup_document_version_on_error(
diff --git a/rust/cloud-storage/document_storage_service/src/api/internal/mod.rs b/rust/cloud-storage/document_storage_service/src/api/internal/mod.rs
index d6755c995c..60454c9a0f 100644
--- a/rust/cloud-storage/document_storage_service/src/api/internal/mod.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/internal/mod.rs
@@ -1,3 +1,4 @@
+use super::context::TaskPropertiesAdapter;
use super::{
context::{ApiContext, EntityAccessService},
documents::{export_document, get_document_version},
@@ -5,11 +6,8 @@ use super::{
permissions,
projects::upload_folder,
};
+use super::{documents::get_document_access_level, user::delete_user_items};
use super::{documents::save_document, history::delete_history};
-use super::{
- documents::{create_document, get_document_access_level},
- user::delete_user_items,
-};
use super::{
documents::{
get_document, get_document_key, get_document_permissions, get_document_text,
@@ -26,6 +24,7 @@ use axum::{
};
use documents_hex::domain::service::DocumentServiceImpl;
use documents_hex::outbound::pg_document_repo::PgDocumentRepo;
+use documents_hex::outbound::s3_upload_url::S3UploadUrlAdapter;
use macro_middleware::{
auth::ensure_user_exists,
cloud_storage::{document::ensure_document_exists, thread::ensure_thread_exists},
@@ -54,7 +53,7 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
.route(
"/documents/:document_id",
get(documents_hex::inbound::axum_router::get_document_handler::<
- DocumentServiceImpl<PgDocumentRepo>,
+ DocumentServiceImpl<PgDocumentRepo, S3UploadUrlAdapter, TaskPropertiesAdapter>,
EntityAccessService,
>)
.layer(ensure_document_exists_middleware.clone()),
@@ -85,7 +84,7 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
"/documents/:document_id/location_v3",
get(
documents_hex::inbound::axum_router::get_location_v3_handler::<
- DocumentServiceImpl<PgDocumentRepo>,
+ DocumentServiceImpl<PgDocumentRepo, S3UploadUrlAdapter, TaskPropertiesAdapter>,
EntityAccessService,
>,
)
@@ -99,7 +98,15 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
"/documents/:document_id/access_level",
get(get_document_access_level::handler),
)
- .route("/documents", post(create_document::create_document_handler))
+ .route(
+ "/documents",
+ post(
+ documents_hex::inbound::axum_router::create_document_handler::<
+ DocumentServiceImpl<PgDocumentRepo, S3UploadUrlAdapter, TaskPropertiesAdapter>,
+ EntityAccessService,
+ >,
+ ),
+ )
.route(
"/documents/list_with_access",
get(list_documents_with_access::list_documents_with_access_handler),
diff --git a/rust/cloud-storage/document_storage_service/src/api/swagger.rs b/rust/cloud-storage/document_storage_service/src/api/swagger.rs
index 29fbf3fb1e..f7e180fe27 100644
--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs
@@ -141,7 +141,7 @@ use utoipa::OpenApi;
documents::get_user_documents::get_user_documents_handler,
documents_hex::inbound::axum_router::get_document_handler,
documents::get_document_version::handler,
- documents::create_document::create_document_handler,
+ documents_hex::inbound::axum_router::create_document_handler,
documents::copy_document::copy_document_handler,
documents::save_document::save_document_handler,
documents::pre_save::presave_document_handler,
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index fa282a08e2..78189ba84f 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -1,5 +1,5 @@
use crate::{
- api::context::{ApiContext, DocumentStorageServiceAuthKey},
+ api::context::{ApiContext, DocumentStorageServiceAuthKey, TaskPropertiesAdapter},
config::{
DocumentPermissionJwtSecretKey, DocumentStorageServiceCloudfrontSignerPrivateKeySecretName,
},
@@ -22,6 +22,7 @@ use documents_hex::domain::models::CloudFrontConfig;
use documents_hex::domain::service::DocumentServiceImpl;
use documents_hex::inbound::axum_router::DocumentRouterState;
use documents_hex::outbound::pg_document_repo::PgDocumentRepo;
+use documents_hex::outbound::s3_upload_url::S3UploadUrlAdapter;
use dynamodb_client::DynamodbClient;
use email::{domain::service::EmailServiceImpl, outbound::EmailPgRepo};
use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage};
@@ -288,6 +289,14 @@ async fn main() -> anyhow::Result<()> {
),
);
+ let s3 = Arc::new(S3::new(
+ s3_client,
+ config.vars.document_storage_bucket.as_ref(),
+ config.vars.docx_document_upload_bucket.as_ref(),
+ config.vars.upload_staging_bucket.as_ref(),
+ ));
+ let system_properties_service = Arc::new(system_properties_service);
+
let document_repo = PgDocumentRepo::new(db.clone());
let cloudfront_config = CloudFrontConfig {
distribution_url: config
@@ -308,10 +317,17 @@ async fn main() -> anyhow::Result<()> {
browser_cache_expiry_seconds: config
.document_storage_service_presigned_url_browser_cache_expiry_seconds,
};
+ let s3_upload_adapter = S3UploadUrlAdapter::new(
+ macro_aws_config::s3_client().await,
+ config.vars.document_storage_bucket.as_ref(),
+ config.vars.docx_document_upload_bucket.as_ref(),
+ );
let document_service = DocumentServiceImpl::new(
document_repo,
cloudfront_config,
sync_service_client.clone(),
+ s3_upload_adapter,
+ TaskPropertiesAdapter(system_properties_service.clone()),
db.clone(),
);
@@ -327,19 +343,14 @@ async fn main() -> anyhow::Result<()> {
),
db: db.clone(),
redis_client: Arc::new(Redis::new(redis_client)),
- s3_client: Arc::new(S3::new(
- s3_client,
- config.vars.document_storage_bucket.as_ref(),
- config.vars.docx_document_upload_bucket.as_ref(),
- config.vars.upload_staging_bucket.as_ref(),
- )),
+ s3_client: s3,
dynamodb_client: Arc::new(dynamodb_client),
dynamo_db,
sqs_client: Arc::new(sqs_client),
notification_ingress_service,
conn_gateway_client: Arc::new(conn_gateway_client),
sync_service_client: Arc::new(sync_service_client),
- system_properties_service: Arc::new(system_properties_service),
+ system_properties_service: system_properties_service.clone(),
properties_service: Arc::new(properties_service),
opensearch_client: Arc::new(opensearch_client),
config: Arc::new(config),
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 e1c4c3be9f..bdece04546 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
@@ -1,3 +1,7 @@
+// S3Client is replaced by MockS3Client in test builds via automock,
+// so the real struct and all helper functions appear unused during `cargo test`.
+#![cfg_attr(test, allow(dead_code))]
+
mod copy_document;
mod delete;
mod exists;
diff --git a/rust/cloud-storage/documents/.sqlx/query-0322d49329ea2e6d6bd515f2013a3bc08f9153d9fb263062a46a80cec5c151f0.json b/rust/cloud-storage/documents/.sqlx/query-0322d49329ea2e6d6bd515f2013a3bc08f9153d9fb263062a46a80cec5c151f0.json
new file mode 100644
index 0000000000..a446ea39b0
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-0322d49329ea2e6d6bd515f2013a3bc08f9153d9fb263062a46a80cec5c151f0.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"DocumentPermission\" (\"documentId\", \"sharePermissionId\")\n VALUES ($1, $2)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "0322d49329ea2e6d6bd515f2013a3bc08f9153d9fb263062a46a80cec5c151f0"
+}
diff --git a/rust/cloud-storage/documents/.sqlx/query-31dbb9af47386234da706e7c3175a7a2e43c2231040cc399488418eab9f6023a.json b/rust/cloud-storage/documents/.sqlx/query-31dbb9af47386234da706e7c3175a7a2e43c2231040cc399488418eab9f6023a.json
new file mode 100644
index 0000000000..78b3aa1bb0
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-31dbb9af47386234da706e7c3175a7a2e43c2231040cc399488418eab9f6023a.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO document_sub_type (document_id, sub_type)\n VALUES ($1, $2)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ {
+ "Custom": {
+ "name": "document_sub_type_value",
+ "kind": {
+ "Enum": [
+ "task"
+ ]
+ }
+ }
+ }
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "31dbb9af47386234da706e7c3175a7a2e43c2231040cc399488418eab9f6023a"
+}
diff --git a/rust/cloud-storage/documents/.sqlx/query-45267fb7a6016603a87fca1f2314d86540a99362db746fa2a04a2369bac18095.json b/rust/cloud-storage/documents/.sqlx/query-45267fb7a6016603a87fca1f2314d86540a99362db746fa2a04a2369bac18095.json
new file mode 100644
index 0000000000..945660d977
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-45267fb7a6016603a87fca1f2314d86540a99362db746fa2a04a2369bac18095.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT name FROM \"Project\" WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "name",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "45267fb7a6016603a87fca1f2314d86540a99362db746fa2a04a2369bac18095"
+}
diff --git a/rust/cloud-storage/documents/.sqlx/query-650ab172f8fa2dd93e941fc49ce22a86ce4333805799488d1c37df47d928ddc2.json b/rust/cloud-storage/documents/.sqlx/query-650ab172f8fa2dd93e941fc49ce22a86ce4333805799488d1c37df47d928ddc2.json
new file mode 100644
index 0000000000..7a14f8736e
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-650ab172f8fa2dd93e941fc49ce22a86ce4333805799488d1c37df47d928ddc2.json
@@ -0,0 +1,35 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"DocumentBom\" (\"documentId\", \"createdAt\", \"updatedAt\")\n VALUES ($1, $2, $2)\n RETURNING id, \"createdAt\"::timestamptz as \"created_at\", \"updatedAt\"::timestamptz as \"updated_at\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 2,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Timestamp"
+ ]
+ },
+ "nullable": [
+ false,
+ null,
+ null
+ ]
+ },
+ "hash": "650ab172f8fa2dd93e941fc49ce22a86ce4333805799488d1c37df47d928ddc2"
+}
diff --git a/rust/cloud-storage/documents/.sqlx/query-68ab26135b27913a38d7670c8c1a304b0d9676ba2fb8cd7ac3e9c9906e5726d7.json b/rust/cloud-storage/documents/.sqlx/query-68ab26135b27913a38d7670c8c1a304b0d9676ba2fb8cd7ac3e9c9906e5726d7.json
new file mode 100644
index 0000000000..60b912d427
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-68ab26135b27913a38d7670c8c1a304b0d9676ba2fb8cd7ac3e9c9906e5726d7.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "DELETE FROM \"Document\" WHERE id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "68ab26135b27913a38d7670c8c1a304b0d9676ba2fb8cd7ac3e9c9906e5726d7"
+}
diff --git a/rust/cloud-storage/documents/.sqlx/query-7ce336a58021f98fbb7c87b42ed827d0aee69ec593e923e41d2545b75d1def37.json b/rust/cloud-storage/documents/.sqlx/query-7ce336a58021f98fbb7c87b42ed827d0aee69ec593e923e41d2545b75d1def37.json
new file mode 100644
index 0000000000..373d36db6e
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-7ce336a58021f98fbb7c87b42ed827d0aee69ec593e923e41d2545b75d1def37.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE \"UploadJob\" SET \"documentId\" = $1 WHERE \"jobId\" = $2\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "7ce336a58021f98fbb7c87b42ed827d0aee69ec593e923e41d2545b75d1def37"
+}
diff --git a/rust/cloud-storage/documents/.sqlx/query-7d5fe2bfe9751516c5e9b4315c74138f065c6c9b2a92c0de4d048dc72fdfe369.json b/rust/cloud-storage/documents/.sqlx/query-7d5fe2bfe9751516c5e9b4315c74138f065c6c9b2a92c0de4d048dc72fdfe369.json
new file mode 100644
index 0000000000..ad3cf25985
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-7d5fe2bfe9751516c5e9b4315c74138f065c6c9b2a92c0de4d048dc72fdfe369.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"UserHistory\" (\"userId\", \"itemId\", \"itemType\", \"createdAt\", \"updatedAt\")\n VALUES ($1, $2, $3, $4, $4)\n ON CONFLICT (\"userId\", \"itemId\", \"itemType\") DO UPDATE\n SET \"updatedAt\" = $4\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Text",
+ "Timestamp"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "7d5fe2bfe9751516c5e9b4315c74138f065c6c9b2a92c0de4d048dc72fdfe369"
+}
diff --git a/rust/cloud-storage/documents/.sqlx/query-7e076694e17fe7c86e7a948ab72e4a2a56f301223b62413247ac15bd5fef29c5.json b/rust/cloud-storage/documents/.sqlx/query-7e076694e17fe7c86e7a948ab72e4a2a56f301223b62413247ac15bd5fef29c5.json
new file mode 100644
index 0000000000..35ccaa385e
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-7e076694e17fe7c86e7a948ab72e4a2a56f301223b62413247ac15bd5fef29c5.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"document_email\" (document_id, email_attachment_id)\n VALUES ($1, $2)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "7e076694e17fe7c86e7a948ab72e4a2a56f301223b62413247ac15bd5fef29c5"
+}
diff --git a/rust/cloud-storage/documents/.sqlx/query-baf9495b799086982dd4aac55683482fce25612d56dfdf78872d74019d8b5429.json b/rust/cloud-storage/documents/.sqlx/query-baf9495b799086982dd4aac55683482fce25612d56dfdf78872d74019d8b5429.json
new file mode 100644
index 0000000000..df03eb38fa
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-baf9495b799086982dd4aac55683482fce25612d56dfdf78872d74019d8b5429.json
@@ -0,0 +1,42 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"DocumentInstance\" (\"documentId\", \"sha\", \"createdAt\", \"updatedAt\")\n VALUES ($1, $2, $3, $3)\n RETURNING id, sha, \"createdAt\"::timestamptz as \"created_at\", \"updatedAt\"::timestamptz as \"updated_at\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "sha",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 3,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Timestamp"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ null,
+ null
+ ]
+ },
+ "hash": "baf9495b799086982dd4aac55683482fce25612d56dfdf78872d74019d8b5429"
+}
diff --git a/rust/cloud-storage/documents/.sqlx/query-c6aec8f042b91f510b47cc9cf9a48ab072c216515c897a4a1e10f310cc63b4c4.json b/rust/cloud-storage/documents/.sqlx/query-c6aec8f042b91f510b47cc9cf9a48ab072c216515c897a4a1e10f310cc63b4c4.json
new file mode 100644
index 0000000000..9979d4d6f7
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-c6aec8f042b91f510b47cc9cf9a48ab072c216515c897a4a1e10f310cc63b4c4.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"ItemLastAccessed\" (\"item_id\", \"item_type\", \"last_accessed\")\n VALUES ($1, $2, $3)\n ON CONFLICT (\"item_id\", \"item_type\") DO UPDATE\n SET \"last_accessed\" = $3\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Timestamp"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "c6aec8f042b91f510b47cc9cf9a48ab072c216515c897a4a1e10f310cc63b4c4"
+}
diff --git a/rust/cloud-storage/documents/.sqlx/query-e3ceebff1df78cef1b26e165cc4967a55f7b5355b7ff835eed0f93b4b8458ceb.json b/rust/cloud-storage/documents/.sqlx/query-e3ceebff1df78cef1b26e165cc4967a55f7b5355b7ff835eed0f93b4b8458ceb.json
new file mode 100644
index 0000000000..b6ac45e454
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-e3ceebff1df78cef1b26e165cc4967a55f7b5355b7ff835eed0f93b4b8458ceb.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"SharePermission\" (\"isPublic\", \"publicAccessLevel\", \"createdAt\", \"updatedAt\")\n VALUES ($1, $2, NOW(), NOW())\n RETURNING id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Bool",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "e3ceebff1df78cef1b26e165cc4967a55f7b5355b7ff835eed0f93b4b8458ceb"
+}
diff --git a/rust/cloud-storage/documents/.sqlx/query-f249e23685d626a0e63015828655a4dc7053d1e1d6425b9de339986d41c8e180.json b/rust/cloud-storage/documents/.sqlx/query-f249e23685d626a0e63015828655a4dc7053d1e1d6425b9de339986d41c8e180.json
new file mode 100644
index 0000000000..4153fa8d99
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-f249e23685d626a0e63015828655a4dc7053d1e1d6425b9de339986d41c8e180.json
@@ -0,0 +1,19 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"Document\" (id, owner, name, \"fileType\", \"projectId\", \"createdAt\", \"updatedAt\")\n VALUES ($1, $2, $3, $4, $5, $6, $6)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Text",
+ "Text",
+ "Text",
+ "Timestamp"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "f249e23685d626a0e63015828655a4dc7053d1e1d6425b9de339986d41c8e180"
+}
diff --git a/rust/cloud-storage/documents/.sqlx/query-fc034d46b4247730fc6f69c8dc5070f2c9776b5c6dca78b7927a0e2d2d8306ed.json b/rust/cloud-storage/documents/.sqlx/query-fc034d46b4247730fc6f69c8dc5070f2c9776b5c6dca78b7927a0e2d2d8306ed.json
new file mode 100644
index 0000000000..ebd34825d8
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-fc034d46b4247730fc6f69c8dc5070f2c9776b5c6dca78b7927a0e2d2d8306ed.json
@@ -0,0 +1,31 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"UserItemAccess\" (\n \"id\", \"user_id\", \"item_id\", \"item_type\", \"access_level\",\n \"granted_from_channel_id\", \"created_at\", \"updated_at\"\n )\n VALUES ($1, $2, $3, $4, $5, $6, NOW(), NOW())\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Text",
+ {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ },
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "fc034d46b4247730fc6f69c8dc5070f2c9776b5c6dca78b7927a0e2d2d8306ed"
+}
diff --git a/rust/cloud-storage/documents/Cargo.toml b/rust/cloud-storage/documents/Cargo.toml
index 6a99afd2c5..063a8bdd36 100644
--- a/rust/cloud-storage/documents/Cargo.toml
+++ b/rust/cloud-storage/documents/Cargo.toml
@@ -8,7 +8,7 @@ version = "0.1.0"
default = ["ports", "inbound", "outbound", "axum", "ai_tools"]
ports = ["dep:tokio"]
inbound = ["axum", "ports"]
-outbound = ["ports"]
+outbound = ["ports", "dep:aws-sdk-s3", "dep:base64", "dep:hex"]
ai_tools = [
"dep:ai",
"dep:async-trait",
@@ -42,6 +42,7 @@ uuid = { workspace = true }
document_sub_type = { path = "../document_sub_type" }
entity_access = { path = "../entity_access" }
macro_user_id = { path = "../macro_user_id" }
+macro_uuid = { path = "../macro_uuid" }
model = { path = "../model" }
models_permissions = { path = "../models_permissions" }
macro_aws_config = { path = "../macro_aws_config" }
@@ -57,8 +58,11 @@ model-error-response = { path = "../model-error-response", optional = true }
utoipa = { workspace = true, optional = true }
# Outbound dependencies
+aws-sdk-s3 = { workspace = true, optional = true }
+base64 = { workspace = true, optional = true }
cloudfront_sign = { workspace = true }
futures = { workspace = true }
+hex = { workspace = true, optional = true }
macro_project_utils = { path = "../macro_project_utils" }
sqlx = { workspace = true }
sync_service_client = { path = "../sync_service_client" }
diff --git a/rust/cloud-storage/documents/examples/documents_toolset.rs b/rust/cloud-storage/documents/examples/documents_toolset.rs
index 09a994ed0f..c58e5d2cbe 100644
--- a/rust/cloud-storage/documents/examples/documents_toolset.rs
+++ b/rust/cloud-storage/documents/examples/documents_toolset.rs
@@ -20,6 +20,7 @@ use ai::tool::tool_loop::cli::Cli;
use ai::tool::types::RequestContext;
use ai::types::Model;
use documents::domain::models::CloudFrontConfig;
+use documents::domain::ports::{PresignedUploadUrlPort, TaskPropertiesPort};
use documents::domain::service::DocumentServiceImpl;
use documents::inbound::toolset::{DocumentToolContext, document_toolset};
use documents::outbound::pg_document_repo::PgDocumentRepo;
@@ -27,10 +28,45 @@ use entity_access::domain::service::EntityAccessServiceImpl;
use entity_access::outbound::PgAccessRepository;
use lexical_client::LexicalClient;
use macro_user_id::user_id::MacroUserIdStr;
+use model::document::ContentType;
use sqlx::PgPool;
use std::sync::Arc;
use sync_service_client::SyncServiceClient;
+/// No-op presigned upload URL service (not needed for toolset example).
+#[derive(Clone)]
+struct NoOpUploadUrl;
+
+impl PresignedUploadUrlPort for NoOpUploadUrl {
+ async fn put_document_storage_presigned_url(
+ &self,
+ _key: &str,
+ _sha: &str,
+ _content_type: ContentType,
+ ) -> anyhow::Result<String> {
+ anyhow::bail!("not implemented in example")
+ }
+
+ async fn put_docx_upload_presigned_url(
+ &self,
+ _key: &str,
+ _sha: &str,
+ _content_type: ContentType,
+ ) -> anyhow::Result<String> {
+ anyhow::bail!("not implemented in example")
+ }
+}
+
+/// No-op task properties service (not needed for toolset example).
+#[derive(Clone)]
+struct NoOpTaskProperties;
+
+impl TaskPropertiesPort for NoOpTaskProperties {
+ async fn attach_task_properties(&self, _entity_ids: Vec<String>) -> anyhow::Result<()> {
+ Ok(())
+ }
+}
+
/// The prompt to use in the example.
const PROMPT: &str = "You are an assistant that helps users explore and manage their documents. Use the available tools to read document metadata.";
@@ -81,6 +117,8 @@ async fn main() {
browser_cache_expiry_seconds: 900,
},
SyncServiceClient::new(sync_service_auth_key.clone(), sync_service_url),
+ NoOpUploadUrl,
+ NoOpTaskProperties,
pool,
);
diff --git a/rust/cloud-storage/documents/src/domain/models.rs b/rust/cloud-storage/documents/src/domain/models.rs
index d4259444cb..22ef9d1137 100644
--- a/rust/cloud-storage/documents/src/domain/models.rs
+++ b/rust/cloud-storage/documents/src/domain/models.rs
@@ -1,5 +1,8 @@
//! Domain models for the documents crate.
+use macro_user_id::user_id::MacroUserIdStr;
+use model::document::FileType;
+
/// Errors that can occur during document operations.
#[derive(Debug, thiserror::Error)]
pub enum DocumentError {
@@ -12,11 +15,41 @@ pub enum DocumentError {
/// The document does not exist in storage (S3/sync service).
#[error("document does not exist in storage")]
Gone,
+ /// A conflict occurred (e.g. duplicate document ID).
+ #[error("conflict: {0}")]
+ Conflict(String),
+ /// A bad request was made.
+ #[error("bad request: {0}")]
+ BadRequest(String),
/// An internal error occurred.
#[error("{0}")]
Internal(#[from] anyhow::Error),
}
+/// Arguments for creating a document in the repository.
+pub struct CreateDocumentRepoArgs {
+ /// Optional user-provided document ID.
+ pub id: Option<uuid::Uuid>,
+ /// SHA256 hash of the document content.
+ pub sha: String,
+ /// Document name without extension.
+ pub document_name: String,
+ /// The owner/creator of the document.
+ pub user_id: MacroUserIdStr<'static>,
+ /// File type of the document.
+ pub file_type: Option<FileType>,
+ /// Project to associate the document with.
+ pub project_id: Option<uuid::Uuid>,
+ /// Email attachment to link (internal only).
+ pub email_attachment_id: Option<uuid::Uuid>,
+ /// Custom creation timestamp.
+ pub created_at: Option<chrono::DateTime<chrono::Utc>>,
+ /// Whether the document is a task (MD files only).
+ pub is_task: bool,
+ /// Whether to skip adding to user history.
+ pub skip_history: bool,
+}
+
/// Configuration for CloudFront presigned URL generation.
pub struct CloudFrontConfig {
/// The CloudFront distribution URL.
diff --git a/rust/cloud-storage/documents/src/domain/ports.rs b/rust/cloud-storage/documents/src/domain/ports.rs
index 3876ac29b1..feaa342cf6 100644
--- a/rust/cloud-storage/documents/src/domain/ports.rs
+++ b/rust/cloud-storage/documents/src/domain/ports.rs
@@ -5,10 +5,13 @@
use std::future::Future;
use entity_access::domain::models::EntityAccessReceipt;
-use model::document::response::{GetDocumentResponseData, LocationResponseV3};
-use model::document::{DocumentBasic, DocumentMetadata};
+use macro_user_id::user_id::MacroUserIdStr;
+use model::document::response::{
+ CreateDocumentResponseData, GetDocumentResponseData, LocationResponseV3,
+};
+use model::document::{ContentType, DocumentBasic, DocumentMetadata};
-use super::models::{DocumentError, LocationQueryParams};
+use super::models::{CreateDocumentRepoArgs, DocumentError, LocationQueryParams};
/// Repository for accessing document data from the database.
///
@@ -17,7 +20,7 @@ use super::models::{DocumentError, LocationQueryParams};
#[cfg_attr(test, mockall::automock(type Err = anyhow::Error;))]
pub trait DocumentRepo: Send + Sync + 'static {
/// The error type returned by repository operations.
- type Err: Into<anyhow::Error> + Send;
+ type Err: Into<anyhow::Error> + Send + std::fmt::Debug;
/// Get full document metadata (including latest version, BOM, project info).
fn get_document_metadata(
@@ -75,6 +78,57 @@ pub trait DocumentRepo: Send + Sync + 'static {
&self,
document_id: &str,
) -> impl Future<Output = Result<String, Self::Err>> + Send;
+
+ /// Create a new document with all associated records in a single transaction.
+ ///
+ /// Handles: Document row, version (DocumentInstance or DocumentBom),
+ /// document_sub_type, SharePermission, DocumentPermission, UserHistory,
+ /// ItemLastAccessed, UserItemAccess, and document_email.
+ fn create_document(
+ &self,
+ args: CreateDocumentRepoArgs,
+ ) -> impl Future<Output = Result<DocumentMetadata, Self::Err>> + Send;
+
+ /// Update an upload job to associate it with a document.
+ fn update_upload_job(
+ &self,
+ document_id: &str,
+ job_id: &str,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Delete a document by ID (used for error cleanup).
+ fn delete_document_by_id(
+ &self,
+ document_id: &str,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+}
+
+/// Port for generating S3 presigned upload URLs.
+pub trait PresignedUploadUrlPort: Send + Sync + 'static {
+ /// Generate a presigned URL for uploading to the document storage bucket.
+ fn put_document_storage_presigned_url(
+ &self,
+ key: &str,
+ sha: &str,
+ content_type: ContentType,
+ ) -> impl Future<Output = anyhow::Result<String>> + Send;
+
+ /// Generate a presigned URL for uploading to the docx upload bucket.
+ fn put_docx_upload_presigned_url(
+ &self,
+ key: &str,
+ sha: &str,
+ content_type: ContentType,
+ ) -> impl Future<Output = anyhow::Result<String>> + Send;
+}
+
+/// Port for attaching task system properties.
+pub trait TaskPropertiesPort: Send + Sync + 'static {
+ /// Attach initial (null-valued) task properties to entities.
+ fn attach_task_properties(
+ &self,
+ entity_ids: Vec<String>,
+ ) -> impl Future<Output = anyhow::Result<()>> + Send;
}
/// Service interface for document operations.
@@ -113,4 +167,13 @@ pub trait DocumentService: Send + Sync + 'static {
&self,
entity_access_receipt: EntityAccessReceipt,
) -> impl Future<Output = Result<String, DocumentError>> + Send;
+
+ /// Create a new document, generate an S3 presigned upload URL, and
+ /// optionally attach task properties and update project modified.
+ fn create_document(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ args: CreateDocumentRepoArgs,
+ job_id: Option<String>,
+ ) -> impl Future<Output = Result<CreateDocumentResponseData, DocumentError>> + Send;
}
diff --git a/rust/cloud-storage/documents/src/domain/service.rs b/rust/cloud-storage/documents/src/domain/service.rs
index 2a9bfd8f8c..dcb01dddf4 100644
--- a/rust/cloud-storage/documents/src/domain/service.rs
+++ b/rust/cloud-storage/documents/src/domain/service.rs
@@ -8,41 +8,52 @@ use std::time::{SystemTime, UNIX_EPOCH};
use anyhow::anyhow;
use cloudfront_sign::{SignedOptions, get_signed_url};
+use document_sub_type::DocumentSubType;
use entity_access::domain::models::{EntityAccessAuth, EntityAccessReceipt};
+use macro_user_id::user_id::MacroUserIdStr;
use model::document::response::{
+ CreateDocumentResponseData, DocumentResponse, DocumentResponseMetadata,
GetDocumentResponseData, LocationResponseData, LocationResponseV3,
};
use model::document::{
- CONVERTED_DOCUMENT_FILE_NAME, DocumentBasic, FileType, FileTypeExt,
+ CONVERTED_DOCUMENT_FILE_NAME, ContentType, DocumentBasic, FileType, FileTypeExt,
build_cloud_storage_bucket_document_key,
};
use model::response::PresignedUrl;
use sqlx::PgPool;
use tracing;
-use super::models::{CloudFrontConfig, DocumentError, LocationQueryParams};
-use super::ports::{DocumentRepo, DocumentService};
+use super::models::{CloudFrontConfig, CreateDocumentRepoArgs, DocumentError, LocationQueryParams};
+use super::ports::{DocumentRepo, DocumentService, PresignedUploadUrlPort, TaskPropertiesPort};
/// The concrete document service implementation.
-pub struct DocumentServiceImpl<R: DocumentRepo> {
+pub struct DocumentServiceImpl<R: DocumentRepo, U: PresignedUploadUrlPort, T: TaskPropertiesPort> {
repo: R,
cloudfront_config: CloudFrontConfig,
sync_service_client: sync_service_client::SyncServiceClient,
+ upload_url_service: U,
+ task_properties_service: T,
db: PgPool,
}
-impl<R: DocumentRepo> DocumentServiceImpl<R> {
+impl<R: DocumentRepo, U: PresignedUploadUrlPort, T: TaskPropertiesPort>
+ DocumentServiceImpl<R, U, T>
+{
/// Create a new document service.
pub fn new(
repo: R,
cloudfront_config: CloudFrontConfig,
sync_service_client: sync_service_client::SyncServiceClient,
+ upload_url_service: U,
+ task_properties_service: T,
db: PgPool,
) -> Self {
Self {
repo,
cloudfront_config,
sync_service_client,
+ upload_url_service,
+ task_properties_service,
db,
}
}
@@ -247,9 +258,18 @@ impl<R: DocumentRepo> DocumentServiceImpl<R> {
}
}
}
+
+ /// Clean up a document on creation error.
+ async fn cleanup_document(&self, document_id: &str) {
+ if let Err(e) = self.repo.delete_document_by_id(document_id).await {
+ tracing::error!(error=?e, document_id=?document_id, "failed to clean up document");
+ }
+ }
}
-impl<R: DocumentRepo> DocumentService for DocumentServiceImpl<R> {
+impl<R: DocumentRepo, U: PresignedUploadUrlPort, T: TaskPropertiesPort> DocumentService
+ for DocumentServiceImpl<R, U, T>
+{
#[tracing::instrument(err, skip(self))]
async fn get_document(
&self,
@@ -418,4 +438,108 @@ impl<R: DocumentRepo> DocumentService for DocumentServiceImpl<R> {
.await
.map_err(|e| DocumentError::Internal(e.into()))
}
+
+ #[tracing::instrument(err, skip(self, args))]
+ async fn create_document(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ args: CreateDocumentRepoArgs,
+ job_id: Option<String>,
+ ) -> Result<CreateDocumentResponseData, DocumentError> {
+ let file_type = args.file_type;
+ let project_id = args.project_id;
+ let sha = args.sha.clone();
+
+ // Create document metadata in the database (full transaction)
+ let document_metadata = self.repo.create_document(args).await.map_err(|e| {
+ let err: anyhow::Error = e.into();
+ if err.to_string().contains("document with ID already exists") {
+ DocumentError::Conflict("document with ID already exists".to_string())
+ } else {
+ DocumentError::Internal(err)
+ }
+ })?;
+
+ let document_id = document_metadata.document_id.clone();
+
+ // Update upload job if job_id provided (outside the main transaction)
+ if let Some(job_id) = &job_id
+ && let Err(e) = self.repo.update_upload_job(&document_id, job_id).await
+ {
+ tracing::error!(error=?e, document_id=?document_id, "failed to update upload job");
+ self.cleanup_document(&document_id).await;
+ return Err(DocumentError::Internal(anyhow!(
+ "unable to update upload job"
+ )));
+ }
+
+ // Build the S3 key for upload
+ let key = build_cloud_storage_bucket_document_key(
+ document_metadata.owner.as_ref(),
+ &document_id,
+ document_metadata.document_version_id,
+ file_type.as_ref().map(|s| s.as_str()),
+ );
+
+ let content_type = match file_type {
+ Some(FileType::Docx) => ContentType::Docx,
+ _ => file_type.into(),
+ };
+
+ let mime_type = content_type.mime_type().to_string();
+
+ // Generate presigned upload URL
+ let presigned_url = match file_type {
+ Some(FileType::Docx) => self
+ .upload_url_service
+ .put_docx_upload_presigned_url(&key, &sha, content_type)
+ .await,
+ _ => self
+ .upload_url_service
+ .put_document_storage_presigned_url(&key, &sha, content_type)
+ .await,
+ }
+ .map_err(|e| {
+ tracing::error!(error=?e, key=?key, document_id=?document_id, "unable to generate presigned url");
+ DocumentError::Internal(anyhow!("unable to generate presigned url"))
+ })?;
+
+ // Convert metadata to response format
+ let document_response_metadata =
+ DocumentResponseMetadata::from_document_metadata(&document_metadata).map_err(|e| {
+ tracing::error!(error=?e, document_id=?document_id, "unable to convert document metadata");
+ DocumentError::Internal(anyhow!("unable to convert document metadata"))
+ })?;
+
+ // Update project modified timestamp (fire-and-forget)
+ macro_project_utils::update_project_modified(
+ &self.db,
+ macro_project_utils::ProjectModifiedArgs {
+ project_id,
+ old_project_id: None,
+ user_id: user_id.as_ref().to_string(),
+ },
+ )
+ .await;
+
+ // Attach task properties if creating a task
+ if document_response_metadata.sub_type == Some(DocumentSubType::Task) {
+ self.task_properties_service
+ .attach_task_properties(vec![document_response_metadata.document_id.clone()])
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, document_id=?document_id, "failed to attach task properties");
+ DocumentError::Internal(anyhow!("failed to attach task properties"))
+ })?;
+ }
+
+ Ok(CreateDocumentResponseData {
+ document_response: DocumentResponse {
+ document_metadata: document_response_metadata,
+ presigned_url: Some(presigned_url),
+ },
+ content_type: mime_type,
+ file_type: file_type.map(|f| f.to_string()),
+ })
+ }
}
diff --git a/rust/cloud-storage/documents/src/inbound/axum_router.rs b/rust/cloud-storage/documents/src/inbound/axum_router.rs
index ffc4b85feb..7ab431eb91 100644
--- a/rust/cloud-storage/documents/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/documents/src/inbound/axum_router.rs
@@ -1,6 +1,7 @@
//! Axum router for document endpoints.
//!
-//! Provides three routes:
+//! Provides four routes:
+//! - `POST /` — create a new document
//! - `GET /:document_id` — get document metadata
//! - `GET /:document_id/location_v3` — get document content location (presigned URL)
//! - `DELETE /:document_id` — soft-delete a document
@@ -8,6 +9,7 @@
#[cfg(test)]
mod tests;
+use std::str::FromStr;
use std::sync::Arc;
use axum::{
@@ -19,17 +21,24 @@ use axum::{
response::IntoResponse,
};
use entity_access::domain::ports::EntityAccessService;
-use entity_access::inbound::axum_extractors::DocumentAccessExtractor;
-use model::document::response::GetDocumentResponse;
-use model::document::{DocumentBasic, response::LocationResponseV3};
+use entity_access::inbound::axum_extractors::{
+ DocumentAccessExtractor, InternalUser, ProjectBodyAccessLevelExtractor,
+};
+use model::document::response::{
+ CreateDocumentRequest, CreateDocumentResponse, GetDocumentResponse,
+};
+use model::document::{DocumentBasic, FileType, FileTypeExt, response::LocationResponseV3};
use model::response::GenericSuccessResponse;
use model::user::UserContext;
use model_error_response::ErrorResponse;
-use models_permissions::share_permission::access_level::{OwnerAccessLevel, ViewAccessLevel};
+use model_user::axum_extractor::MacroUserExtractor;
+use models_permissions::share_permission::access_level::{
+ EditAccessLevel, OwnerAccessLevel, ViewAccessLevel,
+};
use serde::Deserialize;
use sqlx::PgPool;
-use crate::domain::models::{DocumentError, LocationQueryParams};
+use crate::domain::models::{CreateDocumentRepoArgs, DocumentError, LocationQueryParams};
use crate::domain::ports::DocumentService;
impl IntoResponse for DocumentError {
@@ -38,6 +47,8 @@ impl IntoResponse for DocumentError {
DocumentError::NotFound(_) => StatusCode::NOT_FOUND,
DocumentError::Unauthorized => StatusCode::UNAUTHORIZED,
DocumentError::Gone => StatusCode::GONE,
+ DocumentError::Conflict(_) => StatusCode::CONFLICT,
+ DocumentError::BadRequest(_) => StatusCode::BAD_REQUEST,
DocumentError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
};
@@ -83,14 +94,15 @@ pub struct Params {
document_id: String,
}
-/// Build the documents router with all three endpoints.
+/// Build the documents router with all four endpoints.
pub fn documents_router<T, Svc, S>(state: DocumentRouterState<T, Svc>) -> Router<S>
where
T: DocumentService,
Svc: EntityAccessService,
S: Send + Sync + 'static,
{
- Router::new()
+ // Routes that need ensure_document_exists middleware
+ let document_id_routes = Router::new()
.route(
"/:document_id",
axum::routing::get(get_document_handler::<T, Svc>)
@@ -103,7 +115,11 @@ where
.layer(middleware::from_fn_with_state(
state.clone(),
ensure_document_exists,
- ))
+ ));
+
+ Router::new()
+ .merge(document_id_routes)
+ .route("/", axum::routing::post(create_document_handler::<T, Svc>))
.with_state(state)
}
@@ -276,3 +292,90 @@ pub async fn delete_document_handler<T: DocumentService, Svc: EntityAccessServic
Ok(Json(GenericSuccessResponse { success: true }))
}
+
+/// Handler for `POST /documents`.
+///
+/// Creates a new document, generates an S3 presigned upload URL, and returns
+/// the document metadata with the URL for the client to upload to.
+#[utoipa::path(
+ tag = "document",
+ post,
+ path = "/documents",
+ operation_id = "create_document",
+ request_body = CreateDocumentRequest,
+ responses(
+ (status = 200, body = inline(CreateDocumentResponse)),
+ (status = 400, body = ErrorResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 409, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip(state, user_context, project), fields(user_id=?user_context.macro_user_id))]
+pub async fn create_document_handler<T: DocumentService, Svc: EntityAccessService>(
+ State(state): State<DocumentRouterState<T, Svc>>,
+ internal_user: Option<Extension<InternalUser>>,
+ user_context: MacroUserExtractor,
+ project: ProjectBodyAccessLevelExtractor<EditAccessLevel, CreateDocumentRequest, Svc>,
+) -> Result<Json<CreateDocumentResponse>, DocumentError> {
+ let req = project.into_inner();
+
+ // Email linking is internal only
+ if req.email_attachment_id.is_some() && internal_user.is_none() {
+ return Err(DocumentError::Unauthorized);
+ }
+
+ // Parse file type from the request
+ let user_provided_file_type: Option<FileType> = req
+ .file_type
+ .as_deref()
+ .and_then(|f| FileType::from_str(f).ok());
+
+ let (document_name, file_type) = match user_provided_file_type {
+ Some(file_type) => {
+ let document_name = FileType::clean_document_name(&req.document_name);
+ (document_name.unwrap_or(req.document_name), Some(file_type))
+ }
+ None => match FileType::split_suffix_match(req.document_name.as_str()) {
+ Some((file_name, extension)) => {
+ let file_type: Option<FileType> = FileType::from_str(extension).ok();
+ (file_name.to_string(), file_type)
+ }
+ None => (req.document_name, None),
+ },
+ };
+
+ // Log if the user-provided mime type does not match the file type
+ if let (Some(ft), Some(user_mime_type)) = (file_type, &req.mime_type)
+ && *user_mime_type != ft.mime_type()
+ {
+ tracing::warn!(
+ file_type=?ft,
+ mime_type=?user_mime_type,
+ "provided mime type does not match file type"
+ );
+ }
+
+ let args = CreateDocumentRepoArgs {
+ id: req.id,
+ sha: req.sha,
+ document_name,
+ user_id: user_context.macro_user_id.clone(),
+ file_type,
+ project_id: req.project_id,
+ email_attachment_id: req.email_attachment_id,
+ created_at: req.created_at,
+ is_task: req.is_task,
+ skip_history: req.skip_history,
+ };
+
+ let response_data = state
+ .service
+ .create_document(user_context.macro_user_id, args, req.job_id)
+ .await?;
+
+ Ok(Json(CreateDocumentResponse {
+ error: false,
+ data: response_data,
+ }))
+}
diff --git a/rust/cloud-storage/documents/src/outbound.rs b/rust/cloud-storage/documents/src/outbound.rs
index e028988102..eae598689a 100644
--- a/rust/cloud-storage/documents/src/outbound.rs
+++ b/rust/cloud-storage/documents/src/outbound.rs
@@ -1,3 +1,4 @@
//! Outbound adapters for the documents domain.
pub mod pg_document_repo;
+pub mod s3_upload_url;
diff --git a/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs b/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs
index b6dca69704..3cccfbbb3f 100644
--- a/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs
+++ b/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs
@@ -5,11 +5,14 @@
#[cfg(test)]
mod tests;
+mod create;
+
use document_sub_type::DocumentSubType;
use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use model::document::{DocumentBasic, DocumentMetadata};
use sqlx::PgPool;
+use crate::domain::models::CreateDocumentRepoArgs;
use crate::domain::ports::DocumentRepo;
/// PostgreSQL-backed document repository.
@@ -370,4 +373,137 @@ impl DocumentRepo for PgDocumentRepo {
Ok(content.content)
}
+
+ #[tracing::instrument(err, skip(self, args))]
+ async fn create_document(
+ &self,
+ args: CreateDocumentRepoArgs,
+ ) -> Result<DocumentMetadata, Self::Err> {
+ let CreateDocumentRepoArgs {
+ id,
+ sha,
+ document_name,
+ user_id,
+ file_type,
+ project_id,
+ email_attachment_id,
+ created_at: provided_created_at,
+ is_task,
+ skip_history,
+ } = args;
+
+ let now = chrono::Utc::now();
+ let created_at = provided_created_at.as_ref().unwrap_or(&now);
+
+ let mut transaction = self.pool.begin().await?;
+
+ // Fetch project name if project_id provided
+ let project_name: Option<String> = if let Some(ref proj_id) = project_id {
+ sqlx::query_scalar!(
+ r#"SELECT name FROM "Project" WHERE id = $1"#,
+ &proj_id.to_string(),
+ )
+ .fetch_optional(&mut *transaction)
+ .await?
+ } else {
+ None
+ };
+
+ let document_id = create::insert_document_row(
+ &mut transaction,
+ id.as_ref(),
+ &user_id,
+ &document_name,
+ file_type,
+ project_id.as_ref(),
+ created_at,
+ )
+ .await?;
+
+ // Insert document sub-type
+ let sub_type: Option<DocumentSubType> =
+ create::set_document_sub_type(&mut transaction, &document_id, is_task).await?;
+
+ // Insert document version (DocumentBom for docx, DocumentInstance for others)
+ let document_version = create::set_document_version(
+ &mut transaction,
+ &document_id,
+ file_type,
+ sha,
+ created_at,
+ )
+ .await?;
+
+ // Create share permission
+ create::set_share_permission(&mut transaction, &document_id, file_type).await?;
+
+ // Add to user history (if not skipped)
+ if !skip_history {
+ create::insert_history(&mut transaction, &document_id, &user_id, created_at).await?;
+ }
+
+ // Insert user item access (Owner level)
+ create::insert_item_access(&mut transaction, &document_id, &user_id).await?;
+
+ // Link to email attachment if provided
+ if let Some(attachment_id) = email_attachment_id {
+ sqlx::query!(
+ r#"
+ INSERT INTO "document_email" (document_id, email_attachment_id)
+ VALUES ($1, $2)
+ "#,
+ &document_id.to_string(),
+ attachment_id,
+ )
+ .execute(&mut *transaction)
+ .await?;
+ }
+
+ transaction.commit().await?;
+
+ Ok(DocumentMetadata::new_document(
+ &document_id.to_string(),
+ document_version.id,
+ user_id,
+ &document_name,
+ file_type,
+ &document_version.sha,
+ None,
+ None,
+ None,
+ project_id.map(|s| s.to_string()).as_deref(),
+ project_name.as_deref(),
+ document_version.created_at,
+ document_version.updated_at,
+ sub_type,
+ ))
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn update_upload_job(&self, document_id: &str, job_id: &str) -> Result<(), Self::Err> {
+ let result = sqlx::query!(
+ r#"
+ UPDATE "UploadJob" SET "documentId" = $1 WHERE "jobId" = $2
+ "#,
+ document_id,
+ job_id,
+ )
+ .execute(&self.pool)
+ .await?;
+
+ if result.rows_affected() == 0 {
+ return Err(sqlx::Error::RowNotFound);
+ }
+
+ Ok(())
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn delete_document_by_id(&self, document_id: &str) -> Result<(), Self::Err> {
+ sqlx::query!(r#"DELETE FROM "Document" WHERE id = $1"#, document_id,)
+ .execute(&self.pool)
+ .await?;
+
+ Ok(())
+ }
}
diff --git a/rust/cloud-storage/documents/src/outbound/pg_document_repo/create.rs b/rust/cloud-storage/documents/src/outbound/pg_document_repo/create.rs
new file mode 100644
index 0000000000..84dad7592c
--- /dev/null
+++ b/rust/cloud-storage/documents/src/outbound/pg_document_repo/create.rs
@@ -0,0 +1,228 @@
+use document_sub_type::DocumentSubType;
+use entity_access::domain::models::AccessLevel;
+use macro_user_id::user_id::MacroUserIdStr;
+use model::document::VersionIDWithTimeStamps;
+use model_file_type::FileType;
+use models_permissions::share_permission::SharePermissionV2;
+
+/// Inserts a record into the document table
+/// Returns the document id
+#[tracing::instrument(skip(transaction), err)]
+pub async fn insert_document_row<'a>(
+ transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
+ document_id: Option<&uuid::Uuid>,
+ user_id: &MacroUserIdStr<'a>,
+ document_name: &str,
+ file_type: Option<FileType>,
+ project_id: Option<&uuid::Uuid>,
+ created_at: &chrono::DateTime<chrono::Utc>,
+) -> Result<uuid::Uuid, sqlx::Error> {
+ // Generate id if one is not provided
+ let id = macro_uuid::generate_uuid_v7();
+ let document_id: uuid::Uuid = if let Some(id) = document_id { *id } else { id };
+
+ // Insert document (with or without user-provided ID)
+ let result = sqlx::query!(
+ r#"
+ INSERT INTO "Document" (id, owner, name, "fileType", "projectId", "createdAt", "updatedAt")
+ VALUES ($1, $2, $3, $4, $5, $6, $6)
+ "#,
+ &document_id.to_string(),
+ user_id.as_ref(),
+ document_name,
+ file_type.map(|ft| ft.as_str().to_string()),
+ project_id.map(|s| s.to_string()),
+ created_at.naive_utc()
+ )
+ .execute(transaction.as_mut())
+ .await;
+
+ match result {
+ Ok(_) => id.to_string().clone(),
+ Err(sqlx::Error::Database(ref db_err)) if db_err.is_unique_violation() => {
+ return Err(sqlx::Error::Protocol(format!(
+ "document with ID already exists: {id}"
+ )));
+ }
+ Err(e) => return Err(e),
+ };
+
+ Ok(document_id)
+}
+
+/// sets the document sub type if necessary
+#[tracing::instrument(skip(transaction), err)]
+pub async fn set_document_sub_type(
+ transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
+ document_id: &uuid::Uuid,
+ is_task: bool,
+) -> Result<Option<DocumentSubType>, sqlx::Error> {
+ // Insert document sub-type (for tasks)
+ if is_task {
+ sqlx::query!(
+ r#"
+ INSERT INTO document_sub_type (document_id, sub_type)
+ VALUES ($1, $2)
+ "#,
+ &document_id.to_string(),
+ DocumentSubType::Task as _
+ )
+ .execute(transaction.as_mut())
+ .await?;
+
+ Ok(Some(DocumentSubType::Task))
+ } else {
+ Ok(None)
+ }
+}
+
+pub async fn set_document_version(
+ transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
+ document_id: &uuid::Uuid,
+ file_type: Option<FileType>,
+ sha: String,
+ created_at: &chrono::DateTime<chrono::Utc>,
+) -> Result<VersionIDWithTimeStamps, sqlx::Error> {
+ match file_type {
+ Some(FileType::Docx) => {
+ let row = sqlx::query!(
+ r#"
+ INSERT INTO "DocumentBom" ("documentId", "createdAt", "updatedAt")
+ VALUES ($1, $2, $2)
+ RETURNING id, "createdAt"::timestamptz as "created_at", "updatedAt"::timestamptz as "updated_at"
+ "#,
+ &document_id.to_string(),
+ created_at.naive_utc(),
+ )
+ .fetch_one(transaction.as_mut())
+ .await?;
+
+ Ok(VersionIDWithTimeStamps {
+ id: row.id,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ sha: sha.clone(),
+ })
+ }
+ _ => {
+ sqlx::query_as!(
+ VersionIDWithTimeStamps,
+ r#"
+ INSERT INTO "DocumentInstance" ("documentId", "sha", "createdAt", "updatedAt")
+ VALUES ($1, $2, $3, $3)
+ RETURNING id, sha, "createdAt"::timestamptz as "created_at", "updatedAt"::timestamptz as "updated_at"
+ "#,
+ &document_id.to_string(),
+ sha,
+ created_at.naive_utc()
+ )
+ .fetch_one(transaction.as_mut())
+ .await
+ }
+ }
+}
+
+/// Sets share permission for the document
+#[tracing::instrument(skip(transaction), err)]
+pub async fn set_share_permission(
+ transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
+ document_id: &uuid::Uuid,
+ file_type: Option<FileType>,
+) -> Result<SharePermissionV2, sqlx::Error> {
+ // Create share permission
+ let share_permission = SharePermissionV2::new_document_share_permission(file_type);
+ let share_permission_row = sqlx::query!(
+ r#"
+ INSERT INTO "SharePermission" ("isPublic", "publicAccessLevel", "createdAt", "updatedAt")
+ VALUES ($1, $2, NOW(), NOW())
+ RETURNING id
+ "#,
+ share_permission.is_public,
+ share_permission.public_access_level.map(|s| s.to_string()),
+ )
+ .fetch_one(transaction.as_mut())
+ .await?;
+
+ // Link share permission to document
+ sqlx::query!(
+ r#"
+ INSERT INTO "DocumentPermission" ("documentId", "sharePermissionId")
+ VALUES ($1, $2)
+ "#,
+ &document_id.to_string(),
+ share_permission_row.id,
+ )
+ .execute(transaction.as_mut())
+ .await?;
+
+ Ok(share_permission)
+}
+
+/// Set user history
+#[tracing::instrument(skip(transaction), err)]
+pub async fn insert_history<'a>(
+ transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
+ document_id: &uuid::Uuid,
+ user_id: &MacroUserIdStr<'a>,
+ created_at: &chrono::DateTime<chrono::Utc>,
+) -> Result<(), sqlx::Error> {
+ sqlx::query!(
+ r#"
+ INSERT INTO "UserHistory" ("userId", "itemId", "itemType", "createdAt", "updatedAt")
+ VALUES ($1, $2, $3, $4, $4)
+ ON CONFLICT ("userId", "itemId", "itemType") DO UPDATE
+ SET "updatedAt" = $4
+ "#,
+ user_id.as_ref(),
+ &document_id.to_string(),
+ "document",
+ created_at.naive_utc()
+ )
+ .execute(transaction.as_mut())
+ .await?;
+
+ sqlx::query!(
+ r#"
+ INSERT INTO "ItemLastAccessed" ("item_id", "item_type", "last_accessed")
+ VALUES ($1, $2, $3)
+ ON CONFLICT ("item_id", "item_type") DO UPDATE
+ SET "last_accessed" = $3
+ "#,
+ &document_id.to_string(),
+ "document",
+ created_at.naive_utc()
+ )
+ .execute(transaction.as_mut())
+ .await?;
+
+ Ok(())
+}
+
+/// Inserts user item access
+#[tracing::instrument(skip(transaction), err)]
+pub async fn insert_item_access<'a>(
+ transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
+ document_id: &uuid::Uuid,
+ user_id: &MacroUserIdStr<'a>,
+) -> Result<(), sqlx::Error> {
+ let access_id = macro_uuid::generate_uuid_v7();
+ sqlx::query!(
+ r#"
+ INSERT INTO "UserItemAccess" (
+ "id", "user_id", "item_id", "item_type", "access_level",
+ "granted_from_channel_id", "created_at", "updated_at"
+ )
+ VALUES ($1, $2, $3, $4, $5, $6, NOW(), NOW())
+ "#,
+ access_id,
+ user_id.as_ref(),
+ &document_id.to_string(),
+ "document",
+ AccessLevel::Owner as _,
+ None::<uuid::Uuid>,
+ )
+ .execute(transaction.as_mut())
+ .await?;
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/documents/src/outbound/s3_upload_url.rs b/rust/cloud-storage/documents/src/outbound/s3_upload_url.rs
new file mode 100644
index 0000000000..d37b9beaac
--- /dev/null
+++ b/rust/cloud-storage/documents/src/outbound/s3_upload_url.rs
@@ -0,0 +1,94 @@
+//! S3 adapter for generating presigned upload URLs.
+
+use std::time::Duration;
+
+use anyhow::Context;
+use aws_sdk_s3::presigning::PresigningConfig;
+use base64::Engine;
+use model::document::ContentType;
+
+use crate::domain::ports::PresignedUploadUrlPort;
+
+/// Adapter implementing [`PresignedUploadUrlPort`] backed by an `aws_sdk_s3::Client`.
+pub struct S3UploadUrlAdapter {
+ client: aws_sdk_s3::Client,
+ document_storage_bucket: String,
+ docx_upload_bucket: String,
+}
+
+impl S3UploadUrlAdapter {
+ /// Create a new adapter with the given S3 client and bucket names.
+ pub fn new(
+ client: aws_sdk_s3::Client,
+ document_storage_bucket: impl Into<String>,
+ docx_upload_bucket: impl Into<String>,
+ ) -> Self {
+ Self {
+ client,
+ document_storage_bucket: document_storage_bucket.into(),
+ docx_upload_bucket: docx_upload_bucket.into(),
+ }
+ }
+}
+
+impl PresignedUploadUrlPort for S3UploadUrlAdapter {
+ #[tracing::instrument(skip(self), err)]
+ async fn put_document_storage_presigned_url(
+ &self,
+ key: &str,
+ sha: &str,
+ content_type: ContentType,
+ ) -> anyhow::Result<String> {
+ put_presigned_url(
+ &self.client,
+ &self.document_storage_bucket,
+ key,
+ sha,
+ content_type,
+ )
+ .await
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn put_docx_upload_presigned_url(
+ &self,
+ key: &str,
+ sha: &str,
+ content_type: ContentType,
+ ) -> anyhow::Result<String> {
+ put_presigned_url(
+ &self.client,
+ &self.docx_upload_bucket,
+ key,
+ sha,
+ content_type,
+ )
+ .await
+ }
+}
+
+async fn put_presigned_url(
+ client: &aws_sdk_s3::Client,
+ bucket: &str,
+ key: &str,
+ sha: &str,
+ content_type: ContentType,
+) -> anyhow::Result<String> {
+ let expiry_duration = Duration::from_secs(2 * 60);
+
+ let payload_sha256_bytes = hex::decode(sha).context("able to decode hex sha")?;
+ let base64_encoded_sha = base64::engine::general_purpose::STANDARD.encode(payload_sha256_bytes);
+
+ tracing::trace!("sha info {sha} {base64_encoded_sha}");
+
+ let presigned_url = client
+ .put_object()
+ .bucket(bucket)
+ .key(key)
+ .content_type(content_type.mime_type())
+ .checksum_sha256(base64_encoded_sha)
+ .presigned(PresigningConfig::expires_in(expiry_duration)?)
+ .await?;
+
+ Ok(presigned_url.uri().to_string())
+}
diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfile
index f23294d459..99b64a6af2 100644
--- a/rust/cloud-storage/justfile
+++ b/rust/cloud-storage/justfile
@@ -83,6 +83,8 @@ setup_test_envs:
echo "DATABASE_URL={{ MACRODB }}" >> ./comms_service/.env
echo "DATABASE_URL={{ MACRODB }}" >> ./documents/.env
echo "DATABASE_URL={{ MACRODB }}" >> ./stream/.env
+ echo "DATABASE_URL={{ MACRODB }}" >> ./macro_project_utils/.env
+ echo "DATABASE_URL={{ MACRODB }}" >> ./entity_access/.env
setup_macrodb:
just macro_db_client/create_db
diff --git a/rust/cloud-storage/model/src/document/response/mod.rs b/rust/cloud-storage/model/src/document/response/mod.rs
index bd479193de..8ac2747633 100644
--- a/rust/cloud-storage/model/src/document/response/mod.rs
+++ b/rust/cloud-storage/model/src/document/response/mod.rs
@@ -191,7 +191,7 @@ pub type CreateDocumentResponse = TypedSuccessResponse<CreateDocumentResponseDat
#[serde(rename_all = "camelCase")]
pub struct CreateDocumentRequest {
/// The id of the document in the database
- pub id: Option<String>,
+ pub id: Option<uuid::Uuid>,
/// The sha of the document.
pub sha: String,
/// The name of the document without extension.
@@ -210,7 +210,7 @@ pub struct CreateDocumentRequest {
/// Will need to have a corresponding job initiated for the file beforehand.
pub job_id: Option<String>,
//// Optional project id to be used to what project the document belongs to.
- pub project_id: Option<String>,
+ pub project_id: Option<uuid::Uuid>,
/// Internal only field that links the document created to the specified email attachment by
/// creating a row in the document_email table.
pub email_attachment_id: Option<Uuid>,