Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat!(documents): document creation centralization, richer location metadata / state, backend markdown initialization (#3156)

teof99a6d0d4161
diff --git a/.gitignore b/.gitignore
index 8212f774b6..969a0e101f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -11,3 +11,4 @@ run-local.fish
**/node_modules
**/result
**/result-*
+.pi/
diff --git a/changes.md b/changes.md
new file mode 100644
index 0000000000..6733c68c38
--- /dev/null
+++ b/changes.md
@@ -0,0 +1,7 @@
+# Changes
+
+- New endpoint for creating a simple new markdown file. Use this endpoint in both `create.ts` and in `instructions.md` creation
+- backend now does checking for wether user already has an instructions.md document before creating a new one
+- location / metadata response now includes a `content` fiels which describes where and what state the content of the document is in.
+- create task now initializes the tasks content on the backend instead of on the frontend. using the document creator
+- simplifies document creation in ai tool calls
diff --git a/docker-compose.yml b/docker-compose.yml
index df0e0d2e7e..20a28fc163 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -149,6 +149,25 @@ services:
retries: 3
start_period: 10s
+ # ============================================================================
+ # document_upload_finalizer (local worker)
+ # LocalStack S3 ObjectCreated -> SQS consumer for document upload finalization.
+ # Production uses the document_upload_finalizer_handler Lambda.
+ # ============================================================================
+ document_upload_finalizer:
+ <<: [*common-env, *rust-services-image]
+ command: ["/app/out/document_upload_finalizer_local_worker"]
+ environment:
+ LOCAL_AWS_URL: ${LOCAL_AWS_URL:-http://localstack:4566}
+ DOCUMENT_UPLOAD_FINALIZER_QUEUE_URL: ${DOCUMENT_UPLOAD_FINALIZER_QUEUE_URL:-http://localstack:4566/000000000000/document-upload-finalizer-queue}
+ depends_on:
+ - postgres
+ - sync_service
+ - lexical_service
+ networks:
+ - databases
+ - services
+
# ============================================================================
# email_service (Port 8087)
# Email processing and management
diff --git a/infra/stacks/bulk-upload/Pulumi.dev.yaml b/infra/stacks/bulk-upload/Pulumi.dev.yaml
index 6db8a7248e..91b543f2e0 100644
--- a/infra/stacks/bulk-upload/Pulumi.dev.yaml
+++ b/infra/stacks/bulk-upload/Pulumi.dev.yaml
@@ -1,3 +1,4 @@
config:
aws:region: us-east-1
bulk-upload:document_storage_service_auth_key: document-storage-service-auth-key-dev
+ bulk-upload:sync_service_auth_key: sync-service-key-dev
diff --git a/infra/stacks/bulk-upload/Pulumi.prod.yaml b/infra/stacks/bulk-upload/Pulumi.prod.yaml
index 891ff31617..8c9fcd60c8 100644
--- a/infra/stacks/bulk-upload/Pulumi.prod.yaml
+++ b/infra/stacks/bulk-upload/Pulumi.prod.yaml
@@ -1,3 +1,4 @@
config:
aws:region: us-east-1
bulk-upload:document_storage_service_auth_key: document-storage-service-auth-key-prod
+ bulk-upload:sync_service_auth_key: sync-service-key-prod
diff --git a/infra/stacks/bulk-upload/index.ts b/infra/stacks/bulk-upload/index.ts
index a07efecbcd..f429a76f2c 100644
--- a/infra/stacks/bulk-upload/index.ts
+++ b/infra/stacks/bulk-upload/index.ts
@@ -118,19 +118,11 @@ export let cloudStorageServiceUrl: pulumi.Output<string>;
// use the invoke the lambdas locally with a local dss server for testing
if (stack !== 'local') {
- const documentStorageServiceAuthKeyName = config.get(
- `document_storage_service_auth_key`
- );
- if (!documentStorageServiceAuthKeyName) {
- throw new Error('document_storage_service_auth_key must be set');
- }
-
const documentStorageServiceAuthKey = aws.secretsmanager
.getSecretVersionOutput({
- secretId: documentStorageServiceAuthKeyName,
+ secretId: config.require(`document_storage_service_auth_key`),
})
.apply((secret) => secret.secretString);
-
cloudStorageServiceUrl = cloudStorageServiceStack!
.getOutput('cloudStorageServiceUrl')
.apply((url) => url as string);
diff --git a/infra/stacks/cloud-storage-service/document-upload-finalizer-lambda.ts b/infra/stacks/cloud-storage-service/document-upload-finalizer-lambda.ts
new file mode 100644
index 0000000000..c1f960766b
--- /dev/null
+++ b/infra/stacks/cloud-storage-service/document-upload-finalizer-lambda.ts
@@ -0,0 +1,158 @@
+import * as aws from '@pulumi/aws';
+import * as pulumi from '@pulumi/pulumi';
+import { Lambda } from '../../packages/lambda';
+import { CLOUD_TRAIL_SNS_TOPIC_ARN, stack } from '../../packages/shared';
+
+const BASE_NAME = 'document-upload-finalizer-lambda';
+const CLOUD_STORAGE_BASE = `../../../rust/cloud-storage`;
+const ZIP_FOLDER_NAME = 'document_upload_finalizer_handler';
+const ZIP_LOCATION = `${CLOUD_STORAGE_BASE}/target/lambda/${ZIP_FOLDER_NAME}/bootstrap.zip`;
+
+export type DocumentUploadFinalizerLambdaEnvVars = {
+ DATABASE_URL: pulumi.Output<string> | string;
+ INTERNAL_API_SECRET_KEY: pulumi.Output<string> | string;
+ SYNC_SERVICE_AUTH_KEY: pulumi.Output<string> | string;
+ LEXICAL_SERVICE_URL: pulumi.Output<string> | string;
+ SYNC_SERVICE_URL: pulumi.Output<string> | string;
+ RUST_LOG: pulumi.Output<string> | string;
+};
+
+type DocumentUploadFinalizerLambdaArgs = {
+ envVars: DocumentUploadFinalizerLambdaEnvVars;
+ documentStorageBucketArn: pulumi.Output<string> | string;
+ vpc: {
+ vpcId: pulumi.Output<string> | string;
+ publicSubnetIds: pulumi.Output<string[]> | string[];
+ privateSubnetIds: pulumi.Output<string[]> | string[];
+ };
+ tags: { [key: string]: string };
+};
+
+export class DocumentUploadFinalizerLambda extends pulumi.ComponentResource {
+ role: aws.iam.Role;
+ lambda: aws.lambda.Function;
+ tags: { [key: string]: string };
+
+ constructor(
+ name: string,
+ args: DocumentUploadFinalizerLambdaArgs,
+ opts?: pulumi.ComponentResourceOptions
+ ) {
+ super('my:components:DocumentUploadFinalizerLambda', name, {}, opts);
+ const { documentStorageBucketArn, vpc, envVars, tags } = args;
+
+ this.tags = tags;
+
+ const s3Policy = new aws.iam.Policy(
+ `${BASE_NAME}-s3-policy`,
+ {
+ name: `${BASE_NAME}-s3-policy-${stack}`,
+ policy: pulumi.output({
+ Version: '2012-10-17',
+ Statement: [
+ {
+ Effect: 'Allow',
+ Action: ['s3:GetObject'],
+ Resource: [pulumi.interpolate`${documentStorageBucketArn}/*`],
+ },
+ ],
+ }),
+ tags: this.tags,
+ },
+ { parent: this }
+ );
+
+ this.role = new aws.iam.Role(
+ `${BASE_NAME}-role`,
+ {
+ name: `${BASE_NAME}-role-${stack}`,
+ assumeRolePolicy: JSON.stringify({
+ Version: '2012-10-17',
+ Statement: [
+ {
+ Action: 'sts:AssumeRole',
+ Effect: 'Allow',
+ Principal: {
+ Service: 'lambda.amazonaws.com',
+ },
+ },
+ ],
+ }),
+ managedPolicyArns: [
+ aws.iam.ManagedPolicy.AWSLambdaBasicExecutionRole,
+ aws.iam.ManagedPolicy.AWSLambdaVPCAccessExecutionRole,
+ aws.iam.ManagedPolicy.CloudWatchLogsFullAccess,
+ s3Policy.arn,
+ ],
+ tags: this.tags,
+ },
+ { parent: this }
+ );
+
+ const lambda = new Lambda<DocumentUploadFinalizerLambdaEnvVars>(
+ `${BASE_NAME}-lambda`,
+ {
+ baseName: BASE_NAME,
+ handlerBase: CLOUD_STORAGE_BASE,
+ zipLocation: ZIP_LOCATION,
+ vpc,
+ envVars,
+ role: this.role,
+ timeout: 60,
+ memorySize: 512,
+ tags: this.tags,
+ },
+ { parent: this }
+ );
+
+ this.lambda = lambda.lambda;
+
+ this.setupLambdaAlarms();
+ }
+
+ setupLambdaAlarms() {
+ new aws.cloudwatch.MetricAlarm(
+ `${BASE_NAME}-throttle-alarm`,
+ {
+ name: `${BASE_NAME}-throttle-count-${stack}`,
+ metricName: 'Throttles',
+ namespace: 'AWS/Lambda',
+ statistic: 'Sum',
+ period: 300,
+ evaluationPeriods: 1,
+ threshold: 1,
+ comparisonOperator: 'GreaterThanOrEqualToThreshold',
+ dimensions: {
+ FunctionName: this.lambda.name,
+ },
+ alarmDescription: `Alarm when ${BASE_NAME} lambda experiences throttling.`,
+ actionsEnabled: true,
+ alarmActions: [CLOUD_TRAIL_SNS_TOPIC_ARN],
+ tags: this.tags,
+ },
+ { parent: this }
+ );
+
+ new aws.cloudwatch.MetricAlarm(
+ `${BASE_NAME}-error-alarm`,
+ {
+ name: `${BASE_NAME}-error-count-${stack}`,
+ metricName: 'Errors',
+ namespace: 'AWS/Lambda',
+ statistic: 'Sum',
+ period: 300,
+ evaluationPeriods: 1,
+ threshold: 1,
+ comparisonOperator: 'GreaterThanOrEqualToThreshold',
+ dimensions: {
+ FunctionName: this.lambda.name,
+ },
+ alarmDescription: `Alarm when ${BASE_NAME} lambda experiences errors.`,
+ actionsEnabled: true,
+ alarmActions: [CLOUD_TRAIL_SNS_TOPIC_ARN],
+ tags: this.tags,
+ },
+ { parent: this }
+ );
+ }
+}
diff --git a/infra/stacks/cloud-storage-service/index.ts b/infra/stacks/cloud-storage-service/index.ts
index c6fbec3810..32abb29434 100644
--- a/infra/stacks/cloud-storage-service/index.ts
+++ b/infra/stacks/cloud-storage-service/index.ts
@@ -19,6 +19,10 @@ import {
DocxUnzipHandlerLambda,
type DocxUnzipLambdaEnvVars,
} from './docx-unzip-handler-lambda';
+import {
+ DocumentUploadFinalizerLambda,
+ type DocumentUploadFinalizerLambdaEnvVars,
+} from './document-upload-finalizer-lambda';
const tags = {
environment: stack,
@@ -62,14 +66,24 @@ const jwtSecretKeyArn: pulumi.Output<string> = aws.secretsmanager
.apply((secret) => secret.arn);
const INTERNAL_API_SECRET_KEY = config.require(`internal_api_key`);
-const internalApiKeyArn: pulumi.Output<string> = aws.secretsmanager
- .getSecretVersionOutput({ secretId: INTERNAL_API_SECRET_KEY })
- .apply((secret) => secret.arn);
+const internalApiSecret = aws.secretsmanager.getSecretVersionOutput({
+ secretId: INTERNAL_API_SECRET_KEY,
+});
+const internalApiKeyArn: pulumi.Output<string> = internalApiSecret.apply(
+ (secret) => secret.arn
+);
+const internalApiSecretValue: pulumi.Output<string> = internalApiSecret.apply(
+ (secret) => secret.secretString
+);
const SYNC_SERVICE_AUTH_KEY = config.require(`sync_service_auth_key`);
-const syncServiceAuthKeyArn: pulumi.Output<string> = aws.secretsmanager
- .getSecretVersionOutput({ secretId: SYNC_SERVICE_AUTH_KEY })
- .apply((secret) => secret.arn);
+const syncServiceAuthSecret = aws.secretsmanager.getSecretVersionOutput({
+ secretId: SYNC_SERVICE_AUTH_KEY,
+});
+const syncServiceAuthKeyArn: pulumi.Output<string> =
+ syncServiceAuthSecret.apply((secret) => secret.arn);
+const syncServiceAuthKeyValue: pulumi.Output<string> =
+ syncServiceAuthSecret.apply((secret) => secret.secretString);
const AUTHENTICATION_SERVICE_SECRET_KEY = config.require(
`authentication_service_secret_key`
@@ -548,6 +562,10 @@ const cloudStorageService = new CloudStorageService(
name: ServiceUrl.SYNC_SERVICE_URL,
value: getServiceUrl(ServiceUrl.SYNC_SERVICE_URL),
},
+ {
+ name: ServiceUrl.LEXICAL_SERVICE_URL,
+ value: getServiceUrl(ServiceUrl.LEXICAL_SERVICE_URL),
+ },
{
name: 'AUTHENTICATION_SERVICE_SECRET_KEY',
value: pulumi.interpolate`${AUTHENTICATION_SERVICE_SECRET_KEY}`,
@@ -677,6 +695,30 @@ const docxUnzipHandler = new DocxUnzipHandlerLambda(
export const docxUnzipHandlerRoleArn = docxUnzipHandler.role.arn;
export const docxUnzipHandlerName = docxUnzipHandler.lambda.name;
+// ------------------------------------------- Document Upload Finalizer -------------------------------------------
+const documentUploadFinalizerEnvVars: DocumentUploadFinalizerLambdaEnvVars = {
+ DATABASE_URL: pulumi.interpolate`${DATABASE_URL_PROXY}`,
+ INTERNAL_API_SECRET_KEY: pulumi.interpolate`${internalApiSecretValue}`,
+ SYNC_SERVICE_AUTH_KEY: pulumi.interpolate`${syncServiceAuthKeyValue}`,
+ LEXICAL_SERVICE_URL: getServiceUrl(ServiceUrl.LEXICAL_SERVICE_URL),
+ SYNC_SERVICE_URL: getServiceUrl(ServiceUrl.SYNC_SERVICE_URL),
+ RUST_LOG: 'document_upload_finalizer_handler=info,documents=info',
+};
+
+const documentUploadFinalizer = new DocumentUploadFinalizerLambda(
+ `document-upload-finalizer-${stack}`,
+ {
+ documentStorageBucketArn,
+ envVars: documentUploadFinalizerEnvVars,
+ vpc: coparse_api_vpc,
+ tags,
+ }
+);
+
+export const documentUploadFinalizerRoleArn = documentUploadFinalizer.role.arn;
+export const documentUploadFinalizerName = documentUploadFinalizer.lambda.name;
+export const documentUploadFinalizerArn = documentUploadFinalizer.lambda.arn;
+
// attach lambda to s3 event
// disabling in dev to test theory of editor crash in web app and potentially use a new paradigm for docx file upload
new aws.s3.BucketEventSubscription(
diff --git a/infra/stacks/document-storage-bucket-integrations/index.ts b/infra/stacks/document-storage-bucket-integrations/index.ts
index 9f001b3e53..4114d81d50 100644
--- a/infra/stacks/document-storage-bucket-integrations/index.ts
+++ b/infra/stacks/document-storage-bucket-integrations/index.ts
@@ -37,6 +37,13 @@ export const setupS3EventBridgeTriggers = () => {
.getOutput('documentTextExtractorLambdaArn')
.apply((id) => id as string);
+ const documentUploadFinalizerLambdaArn = new pulumi.StackReference(
+ 'cloud-storage-service',
+ { name: `macro-inc/cloud-storage-service/${stack}` }
+ )
+ .getOutput('documentUploadFinalizerArn')
+ .apply((id) => id as string);
+
// Enable EventBridge notifications for the S3 bucket
new aws.s3.BucketNotification('eventbridge-notification', {
bucket: bucketId,
@@ -50,9 +57,13 @@ export const setupS3EventBridgeTriggers = () => {
const searchUploadRuleName = `search-upload-rule-${stack}`;
const textExtractorRuleName = `text-extractor-rule-${stack}`;
+ const documentUploadFinalizerRuleName = `document-upload-finalizer-rule-${stack}`;
const searchUploadRuleArn = getEventRuleArn(searchUploadRuleName);
const textExtractorRuleArn = getEventRuleArn(textExtractorRuleName);
+ const documentUploadFinalizerRuleArn = getEventRuleArn(
+ documentUploadFinalizerRuleName
+ );
const createDlqPolicy = (
name: string,
@@ -91,6 +102,20 @@ export const setupS3EventBridgeTriggers = () => {
createDlqPolicy('text-extractor', textExtractorDlq, textExtractorRuleArn);
+ const documentUploadFinalizerDlq = new aws.sqs.Queue(
+ `document-upload-finalizer-dlq-${stack}`,
+ {
+ name: `document-upload-finalizer-dlq-${stack}`,
+ messageRetentionSeconds: 14 * 24 * 60 * 60,
+ }
+ );
+
+ createDlqPolicy(
+ 'document-upload-finalizer',
+ documentUploadFinalizerDlq,
+ documentUploadFinalizerRuleArn
+ );
+
// Configure EventBridge rules for each Lambda
pulumi
.all([bucketId, searchUploadHandlerLambdaArn, searchUploadDlq.arn])
@@ -154,6 +179,40 @@ export const setupS3EventBridgeTriggers = () => {
});
});
+ pulumi
+ .all([
+ bucketId,
+ documentUploadFinalizerLambdaArn,
+ documentUploadFinalizerDlq.arn,
+ ])
+ .apply(([bucketId, finalizerArn, dlqArn]) => {
+ const documentUploadFinalizerRule = new aws.cloudwatch.EventRule(
+ `document-upload-finalizer-rule-${stack}`,
+ {
+ name: documentUploadFinalizerRuleName,
+ description:
+ 'Finalize documents when their versioned storage object is created',
+ eventPattern: JSON.stringify({
+ source: ['aws.s3'],
+ 'detail-type': ['Object Created'],
+ detail: {
+ bucket: {
+ name: [bucketId],
+ },
+ },
+ }),
+ }
+ );
+
+ new aws.cloudwatch.EventTarget('document-upload-finalizer-target', {
+ rule: documentUploadFinalizerRule.name,
+ arn: finalizerArn,
+ deadLetterConfig: {
+ arn: dlqArn,
+ },
+ });
+ });
+
// Add necessary permissions for EventBridge to invoke Lambda functions
const createLambdaPermission = (functionArn: string, ruleName: string) => {
return new aws.lambda.Permission(`eventbridge-permission-${ruleName}`, {
@@ -166,13 +225,18 @@ export const setupS3EventBridgeTriggers = () => {
// Create permissions for all Lambda functions
pulumi
- .all([searchUploadHandlerLambdaArn, documentTextExtractorLambdaArn])
- .apply(([searchUploadHandlerLambdaArn, extractorArn]) => {
+ .all([
+ searchUploadHandlerLambdaArn,
+ documentTextExtractorLambdaArn,
+ documentUploadFinalizerLambdaArn,
+ ])
+ .apply(([searchUploadHandlerLambdaArn, extractorArn, finalizerArn]) => {
createLambdaPermission(
searchUploadHandlerLambdaArn,
searchUploadRuleName
);
createLambdaPermission(extractorArn, textExtractorRuleName);
+ createLambdaPermission(finalizerArn, documentUploadFinalizerRuleName);
});
};
diff --git a/js/app/packages/block-canvas/component/nodes/DSSMedia.tsx b/js/app/packages/block-canvas/component/nodes/DSSMedia.tsx
index 3f26a3e24e..686893b576 100644
--- a/js/app/packages/block-canvas/component/nodes/DSSMedia.tsx
+++ b/js/app/packages/block-canvas/component/nodes/DSSMedia.tsx
@@ -8,7 +8,7 @@ import PlayIcon from '@icon/regular/play.svg';
import ArrowCounterClockwise from '@phosphor-icons/core/regular/arrow-counter-clockwise.svg?component-solid';
import LockKey from '@phosphor-icons/core/regular/lock-key.svg?component-solid';
import Question from '@phosphor-icons/core/regular/question.svg?component-solid';
-import { storageServiceClient } from '@service-storage/client';
+import { fetchBinaryDocumentData } from '@queries/storage/binary-document';
import { fetchBinary } from '@service-storage/util/fetchBinary';
import {
createEffect,
@@ -170,9 +170,7 @@ export function DSSMedia(props: { node: MediaNode; mode: RenderMode }) {
createEffect(async () => {
if (props.node.status === 'dss' || !props.node.status) {
- const res = await storageServiceClient.getBinaryDocument({
- documentId: props.node.uuid,
- });
+ const res = await fetchBinaryDocumentData(props.node.uuid);
if (isErr(res, 'UNAUTHORIZED') || isErr(res, 'HTTP_ERROR')) {
setError();
diff --git a/js/app/packages/block-canvas/definition.ts b/js/app/packages/block-canvas/definition.ts
index 5c63f11da2..40d98c3bc4 100644
--- a/js/app/packages/block-canvas/definition.ts
+++ b/js/app/packages/block-canvas/definition.ts
@@ -6,7 +6,7 @@ import {
} from '@core/block';
import { blockAcceptedFileExtensionToMimeType } from '@core/constant/allBlocks';
import { isErr, ok } from '@core/util/maybeResult';
-import { storageServiceClient } from '@service-storage/client';
+import { fetchBinaryDocumentData } from '@queries/storage/binary-document';
import { fetchBinary } from '@service-storage/util/fetchBinary';
import { makeFileFromBlob } from '@service-storage/util/makeFileFromBlob';
import CanvasBlock from './component/Block';
@@ -23,7 +23,7 @@ export const definition = defineBlock({
async load(source, intent) {
if (source.type === 'dss') {
const maybeDocument = await loadResult(
- storageServiceClient.getBinaryDocument({ documentId: source.id })
+ fetchBinaryDocumentData(source.id)
);
if (intent === 'preload') {
diff --git a/js/app/packages/block-image/definition.ts b/js/app/packages/block-image/definition.ts
index 138f90d6f9..66d7d94bb5 100644
--- a/js/app/packages/block-image/definition.ts
+++ b/js/app/packages/block-image/definition.ts
@@ -5,7 +5,7 @@ import {
loadResult,
} from '@core/block';
import { isErr, ok } from '@core/util/maybeResult';
-import { storageServiceClient } from '@service-storage/client';
+import { fetchBinaryDocumentData } from '@queries/storage/binary-document';
import { fetchBinary } from '@service-storage/util/fetchBinary';
import { makeFileFromBlob } from '@service-storage/util/makeFileFromBlob';
import { lazy } from 'solid-js';
@@ -25,7 +25,7 @@ export const definition = defineBlock({
async load(source, intent) {
if (source.type === 'dss') {
const maybeDocument = await loadResult(
- storageServiceClient.getBinaryDocument({ documentId: source.id })
+ fetchBinaryDocumentData(source.id)
);
if (intent === 'preload')
diff --git a/js/app/packages/block-md/definition.ts b/js/app/packages/block-md/definition.ts
index 22c56cde6c..0c83455da5 100644
--- a/js/app/packages/block-md/definition.ts
+++ b/js/app/packages/block-md/definition.ts
@@ -5,108 +5,16 @@ import {
loadResult,
} from '@core/block';
import { createLoroManager } from '@core/collab/manager';
-import { serializedStateFromBlob } from '@core/component/LexicalMarkdown/collaboration/utils';
import { ENABLE_MARKDOWN_LIVE_COLLABORATION } from '@core/constant/featureFlags';
import { isErr, ok } from '@core/util/maybeResult';
import { MARKDOWN_LORO_SCHEMA } from '@lexical-core/markdown-loro-schema';
-import { rawMarkdownStateToLoroSnapshot } from '@lexical-core/markdown-loro-snapshot';
+import { waitForDocumentSyncServiceReady } from '@queries/storage/document-location';
import { storageServiceClient } from '@service-storage/client';
-import { fetchBinary } from '@service-storage/util/fetchBinary';
import { makeFileFromBlob } from '@service-storage/util/makeFileFromBlob';
-import { syncServiceClient } from '@service-sync/client';
import { createSyncServiceSource } from '@service-sync/source';
-import { untrack } from 'solid-js';
-import { createStore } from 'solid-js/store';
import MarkdownBlock from './component/Block';
import type { MarkdownRewriteOutput } from './signal/rewriteSignal';
-/** 5 second cache timeout */
-const CACHE_THRESHOLD = 5000;
-const [existsCache, setExistsCache] = createStore<
- Record<
- string,
- | {
- exists: boolean;
- fetchedAt: number;
- }
- | undefined
- >
->({});
-
-const getExists = async (documentId: string): Promise<boolean> => {
- const existsResult = await syncServiceClient.exists({
- documentId,
- });
- if (isErr(existsResult)) return false;
- const [, { exists: existsResultExists }] = existsResult;
- return existsResultExists;
-};
-
-const prefetchExists = async (documentId: string) => {
- const exists = await getExists(documentId);
- setExistsCache(documentId, {
- exists,
- fetchedAt: Date.now(),
- });
-};
-
-const fetchExists = async (documentId: string) => {
- const cached = untrack(() => existsCache[documentId]);
- if (cached && cached.fetchedAt + CACHE_THRESHOLD > Date.now()) {
- setExistsCache(documentId, undefined);
- return cached.exists;
- }
- const exists = await getExists(documentId);
- return exists;
-};
-
-/**
- * Migrates a document from dss to the sync-service.
- * Should only be called if the document does not exist in the sync-service
- *
- * @param documentId - The document id to migrate
- **/
-const migrateToSyncService = async (documentId: string) => {
- const maybeFullDocument = await loadResult(
- storageServiceClient.getBinaryDocument({ documentId })
- );
-
- if (isErr(maybeFullDocument)) return maybeFullDocument;
- const [, { blobUrl }] = maybeFullDocument;
-
- const blobResult = await loadResult(fetchBinary(blobUrl, 'blob'));
-
- if (isErr(blobResult)) return blobResult;
-
- const [, blob] = blobResult;
-
- const state = await serializedStateFromBlob(blob);
-
- if (!state) {
- console.error('Failed to parse blob as serialized state');
- return LoadErrors.INVALID;
- }
-
- const snapshot = await rawMarkdownStateToLoroSnapshot(state as any);
-
- if (!snapshot) {
- console.error('Failed to create snapshot from blob');
- return LoadErrors.INVALID;
- }
-
- let res = await syncServiceClient.initializeFromSnapshot({
- snapshot: snapshot as any,
- documentId: documentId,
- });
-
- if (isErr(res)) {
- console.error('Failed to initialize from snapshot', res);
- return LoadErrors.INVALID;
- }
-
- return ok(undefined);
-};
-
export const definition = defineBlock({
name: 'md',
description: 'write markdown notes',
@@ -120,16 +28,15 @@ export const definition = defineBlock({
if (source.type === 'sync-service') {
const documentId = source.id;
if (intent === 'preload') {
- await prefetchExists(documentId);
return ok({
type: 'preload',
origin: source,
});
}
- const [maybeDocument, exists, maybeToken] = await Promise.all([
+ const [maybeDocument, maybeLocation, maybeToken] = await Promise.all([
loadResult(storageServiceClient.getDocumentMetadata({ documentId })),
- fetchExists(documentId),
+ loadResult(storageServiceClient.getDocumentLocation({ documentId })),
storageServiceClient.permissionsTokens.createPermissionToken({
document_id: documentId,
}),
@@ -142,15 +49,38 @@ export const definition = defineBlock({
const [, { token }] = maybeToken;
if (isErr(maybeDocument)) return maybeDocument;
+ if (isErr(maybeLocation)) return maybeLocation;
const [, documentResult] = maybeDocument;
const { documentMetadata, userAccessLevel } = documentResult;
+ let [, { data: location }] = maybeLocation;
+
+ if (
+ location.type === 'presignedUrl' &&
+ location.content.state === 'pending'
+ ) {
+ location = await waitForDocumentSyncServiceReady({
+ documentId,
+ }).catch((error) => {
+ console.error(
+ 'Failed waiting for markdown sync-service location',
+ error
+ );
+ return location;
+ });
+ }
- // If the document does not exist in the sync-service,
- // but it does exist in dss we should try and initialize it.
- if (!exists) {
- const migrationResult = await migrateToSyncService(documentId);
- if (isErr(migrationResult)) return migrationResult;
+ // Markdown initialization and lifecycle persistence are backend-owned.
+ // If a markdown document still resolves to object storage here, opening
+ // it would require a backend repair/backfill path rather than a frontend
+ // sync-service mutation that leaves DB content metadata inconsistent.
+ if (location.type !== 'syncServiceContent') {
+ console.error(
+ 'Markdown document is not available in sync-service',
+ documentId,
+ location.content
+ );
+ return LoadErrors.INVALID;
}
const syncServiceResult = await createSyncServiceSource(source.id, token);
diff --git a/js/app/packages/block-pdf/definition.ts b/js/app/packages/block-pdf/definition.ts
index f859f799a3..90fa665f6b 100644
--- a/js/app/packages/block-pdf/definition.ts
+++ b/js/app/packages/block-pdf/definition.ts
@@ -5,7 +5,7 @@ import {
loadResult,
} from '@core/block';
import { isErr, ok } from '@core/util/maybeResult';
-import { storageServiceClient } from '@service-storage/client';
+import { fetchBinaryDocumentData } from '@queries/storage/binary-document';
import { fetchBinary } from '@service-storage/util/fetchBinary';
import BlockPdf from './component/Block';
import PdfJsWorker from './PdfViewer/pdfjs-worker?worker';
@@ -26,9 +26,7 @@ export const definition = defineBlock({
GlobalWorkerOptions.workerPort = new PdfJsWorker();
const maybeDocument = await loadResult(
- storageServiceClient.getBinaryDocument({
- documentId: source.id,
- })
+ fetchBinaryDocumentData(source.id)
);
if (intent === 'preload')
diff --git a/js/app/packages/core/component/ImagePreview.tsx b/js/app/packages/core/component/ImagePreview.tsx
index d00b7c1992..43e52d4b81 100644
--- a/js/app/packages/core/component/ImagePreview.tsx
+++ b/js/app/packages/core/component/ImagePreview.tsx
@@ -14,7 +14,7 @@ import { Dialog } from '@kobalte/core/dialog';
import { DropdownMenu } from '@kobalte/core/dropdown-menu';
import { constrainImageDimensions } from '@lexical-core/utils/media';
import Spinner from '@phosphor-icons/core/bold/spinner-gap-bold.svg?component-solid';
-import { storageServiceClient } from '@service-storage/client';
+import { fetchBinaryDocumentData } from '@queries/storage/binary-document';
import { fetchBinary } from '@service-storage/util/fetchBinary';
import { Button, cn } from '@ui';
import { createEffect, createSignal, onCleanup, Show } from 'solid-js';
@@ -55,9 +55,7 @@ const THEMES = {
// NOTE: copied logic from block-image
const getDssImageBlob = async (documentId: string) => {
- const maybeDocument = await storageServiceClient.getBinaryDocument({
- documentId,
- });
+ const maybeDocument = await fetchBinaryDocumentData(documentId);
const documentResult = maybeThrow(maybeDocument);
// presigned url with expiry
const { blobUrl } = documentResult;
diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/media/mediaPlugin.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/media/mediaPlugin.ts
index aaffb58b23..908dd490c8 100644
--- a/js/app/packages/core/component/LexicalMarkdown/plugins/media/mediaPlugin.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/media/mediaPlugin.ts
@@ -15,7 +15,7 @@ import {
type MediaType,
type VideoNode,
} from '@lexical-core';
-import { storageServiceClient } from '@service-storage/client';
+import { fetchBinaryDocumentData } from '@queries/storage/binary-document';
import { fileExtension } from '@service-storage/util/filename';
import {
$createNodeSelection,
@@ -129,12 +129,7 @@ export async function getMediaUrl(src: {
return [null, url];
}
if (src.type === 'dss') {
- return mapOk(
- await storageServiceClient.getBinaryDocument({
- documentId: src.id,
- }),
- (res) => res.blobUrl
- );
+ return mapOk(await fetchBinaryDocumentData(src.id), (res) => res.blobUrl);
}
console.warn('Get media url failed for src:', src);
return [null, ''];
diff --git a/js/app/packages/core/util/create.ts b/js/app/packages/core/util/create.ts
index a3d8633b94..0d4f9c400d 100644
--- a/js/app/packages/core/util/create.ts
+++ b/js/app/packages/core/util/create.ts
@@ -1,13 +1,11 @@
import { DEFAULT_CHAT_NAME } from '@block-chat/definition';
import type { CodeFileExtension } from '@block-code/util/languageSupport';
-import { createMarkdownStateFromContent } from '@core/component/LexicalMarkdown/collaboration/utils';
import {
PROPERTY_OPTION_IDS,
SYSTEM_PROPERTY_IDS,
} from '@core/component/Properties/constants';
import { PaywallKey, usePaywallState } from '@core/constant/PaywallState';
import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
-import { rawMarkdownStateToLoroSnapshot } from '@lexical-core/markdown-loro-snapshot';
import {
authKeys,
invalidateUserQuota,
@@ -23,7 +21,6 @@ import { staticFileClient } from '@service-static-files/client';
import { storageServiceClient } from '@service-storage/client';
import type { PropertyInput } from '@service-storage/generated/schemas/propertyInput';
import { uploadToPresignedUrl } from '@service-storage/util/uploadToPresignedUrl';
-import { syncServiceClient } from '@service-sync/client';
import { isPaymentError } from './handlePaymentError';
import { contentHash } from './hash';
import {
@@ -33,18 +30,6 @@ import {
} from './languageQuery';
import { err, isErr, ok } from './maybeResult';
-/**
- * Generate a fake sha256 hash
- *
- * HACK: Since we don't actually store markdown files in dss, we need to provide a fake sha256 hash
- * to dss.
- */
-function fakeSha256() {
- const bytes = new Uint8Array(32);
- crypto.getRandomValues(bytes); // secure RNG
- return [...bytes].map((b) => b.toString(16).padStart(2, '0')).join('');
-}
-
type CreateMarkdownFileArgs = {
title?: string;
content?: string;
@@ -52,44 +37,24 @@ type CreateMarkdownFileArgs = {
};
/**
- * Initializes a new markdown file in dss & sync_service given a content string.
+ * Creates a new markdown file and initializes sync-service on the backend.
* Use createTask for the task subtype.
*/
export async function createMarkdownFile(
args?: CreateMarkdownFileArgs
): Promise<string | undefined> {
- const emptyMarkdownState = await createMarkdownStateFromContent(
- args?.content
- );
- const snapshot = await rawMarkdownStateToLoroSnapshot(
- emptyMarkdownState as any
- );
- const fakeSha = fakeSha256();
- const result = await storageServiceClient.createDocument({
+ const result = await storageServiceClient.createMarkdownDocument({
documentName: args?.title ?? '',
- fileType: 'md',
- sha: fakeSha,
+ markdown: args?.content ?? '',
projectId: args?.projectId,
- isTask: false,
});
invalidateUserQuota();
- if (isErr(result) || !snapshot) return;
- let [
- ,
- {
- metadata: { documentId },
- },
- ] = result;
-
- let res = await syncServiceClient.initializeFromSnapshot({
- snapshot,
- documentId: documentId,
- });
- if (isErr(res)) {
- return;
- }
+ if (isErr(result)) return;
+
+ const { documentId } = result[1];
+
setPreviewOnCreate({
itemId: documentId,
itemType: 'document',
@@ -114,12 +79,6 @@ type CreateTaskArgs = {
export async function createTask(
args?: CreateTaskArgs
): Promise<string | undefined> {
- // Convert content to loro snapshot for sync service
- const markdownState = await createMarkdownStateFromContent(args?.content);
- const snapshot = await rawMarkdownStateToLoroSnapshot(markdownState as any);
-
- if (!snapshot) return;
-
// Ensure status is always set, defaulting to NOT_STARTED
const existingPropertyValues = args?.propertyValues ?? [];
const hasStatus = existingPropertyValues.some(
@@ -138,9 +97,10 @@ export async function createTask(
},
];
- // Create task with properties in one call
+ // Create task, properties, and sync-service content in one backend-owned lifecycle.
const result = await storageServiceClient.createTask({
taskName: args?.title ?? '',
+ markdown: args?.content ?? '',
projectId: args?.projectId,
propertyValues,
});
@@ -151,17 +111,6 @@ export async function createTask(
const { documentId } = result[1];
- // Initialize sync service with content
- const syncRes = await syncServiceClient.initializeFromSnapshot({
- snapshot,
- documentId,
- });
-
- if (isErr(syncRes)) {
- console.error('Failed to initialize task content in sync service');
- // Task was created, just without content - still return the id
- }
-
setPreviewOnCreate({
itemId: documentId,
itemType: 'document',
diff --git a/js/app/packages/queries/storage/binary-document.ts b/js/app/packages/queries/storage/binary-document.ts
index 22e6776ef4..9f26ef9fa4 100644
--- a/js/app/packages/queries/storage/binary-document.ts
+++ b/js/app/packages/queries/storage/binary-document.ts
@@ -1,14 +1,68 @@
-import { maybeThrow } from '@core/util/maybeResult';
+import type { FetchError } from '@core/service';
+import {
+ isErr,
+ type MaybeResult,
+ maybeThrow,
+ ok,
+} from '@core/util/maybeResult';
import { storageServiceClient } from '@service-storage/client';
+import type { GetDocumentResponseData } from '@service-storage/generated/schemas';
import { useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
+import { queryClient } from '../client';
+import { waitForDocumentPresignedUrlReady } from './document-location';
import { binaryDocumentKeys } from './keys';
const BINARY_DOCUMENT_STALE_TIME = 5 * 60 * 1000; // 5 minutes
const BINARY_DOCUMENT_GC_TIME = 10 * 60 * 1000; // 10 minutes
+type BinaryDocumentData = GetDocumentResponseData & { blobUrl: string };
+type BinaryDocumentError = FetchError | 'INVALID_DOCUMENT';
+
+export async function fetchBinaryDocumentData(
+ documentId: string
+): Promise<MaybeResult<BinaryDocumentError, BinaryDocumentData>> {
+ const maybeDocument = await storageServiceClient.getDocumentMetadata({
+ documentId,
+ });
+ if (isErr(maybeDocument)) return maybeDocument;
+
+ const [, documentData] = maybeDocument;
+ const versionId = documentData.documentMetadata.documentVersionId;
+
+ const location = await waitForDocumentPresignedUrlReady({
+ documentId,
+ versionId,
+ }).catch((error) => {
+ console.error('error waiting for binary document location', error);
+ return undefined;
+ });
+
+ if (
+ !location ||
+ location.content.state !== 'ready' ||
+ location.type !== 'presignedUrl' ||
+ !location.presignedUrl
+ ) {
+ return [
+ [
+ {
+ code: 'INVALID_DOCUMENT',
+ message: 'Document location is not ready as a presigned URL',
+ },
+ ],
+ null,
+ ];
+ }
+
+ return ok({
+ ...documentData,
+ blobUrl: location.presignedUrl,
+ });
+}
+
async function fetchBinaryDocument(documentId: string): Promise<string> {
- const result = await storageServiceClient.getBinaryDocument({ documentId });
+ const result = await fetchBinaryDocumentData(documentId);
const data = maybeThrow(result);
return data.blobUrl;
}
@@ -26,3 +80,9 @@ function binaryDocumentQueryOptions(documentId: string) {
export function useBinaryDocumentQuery(documentId: Accessor<string>) {
return useQuery(() => binaryDocumentQueryOptions(documentId()));
}
+
+export function invalidateBinaryDocument(documentId: string) {
+ return queryClient.invalidateQueries({
+ queryKey: binaryDocumentKeys.document(documentId).queryKey,
+ });
+}
diff --git a/js/app/packages/queries/storage/document-location.ts b/js/app/packages/queries/storage/document-location.ts
new file mode 100644
index 0000000000..6b9bbee0c6
--- /dev/null
+++ b/js/app/packages/queries/storage/document-location.ts
@@ -0,0 +1,203 @@
+import {
+ isErr,
+ type MaybeResult,
+ type ResultType,
+ throwOnErr,
+} from '@core/util/maybeResult';
+import { storageServiceClient } from '@service-storage/client';
+import { DocumentContentState } from '@service-storage/generated/schemas/documentContentState';
+import { queryClient } from '../client';
+import { documentLocationKeys } from './keys';
+
+type DocumentLocationArgs = {
+ documentId: string;
+ versionId?: number;
+};
+
+type GetDocumentLocationResult = Awaited<
+ ReturnType<typeof storageServiceClient.getDocumentLocation>
+>;
+
+export type DocumentLocation = ResultType<GetDocumentLocationResult>['data'];
+
+type WaitForDocumentLocationOptions = {
+ target: string;
+ timeoutMs?: number;
+ initialDelayMs?: number;
+ maxDelayMs?: number;
+ isReady: (location: DocumentLocation) => boolean;
+};
+
+const DEFAULT_TIMEOUT_MS = 15_000;
+const DEFAULT_INITIAL_DELAY_MS = 250;
+const DEFAULT_MAX_DELAY_MS = 1_000;
+
+class DocumentLocationNotReadyError extends Error {
+ constructor(public readonly location: DocumentLocation) {
+ super('Document location is not ready');
+ this.name = 'DocumentLocationNotReadyError';
+ }
+}
+
+function retryDelay(
+ attempt: number,
+ initialDelayMs: number,
+ maxDelayMs: number
+) {
+ return Math.min(initialDelayMs * 2 ** attempt, maxDelayMs);
+}
+
+export function documentLocationQueryOptions(args: DocumentLocationArgs) {
+ return {
+ queryKey: documentLocationKeys.location(args.documentId, args.versionId)
+ .queryKey,
+ queryFn: () => fetchDocumentLocation(args),
+ staleTime: 5 * 60 * 1000,
+ gcTime: 10 * 60 * 1000,
+ enabled: !!args.documentId,
+ };
+}
+
+export async function fetchDocumentLocation(
+ args: DocumentLocationArgs
+): Promise<DocumentLocation> {
+ return throwOnErr(async () =>
+ storageServiceClient.getDocumentLocation(args)
+ ).then((result) => result.data);
+}
+
+export function invalidateDocumentLocation(args: DocumentLocationArgs) {
+ storageServiceClient.getDocumentLocation.invalidate({
+ documentId: args.documentId,
+ });
+ if (args.versionId != null) {
+ storageServiceClient.getDocumentLocation.invalidate(args);
+ }
+
+ return queryClient.invalidateQueries({
+ queryKey: documentLocationKeys.location(args.documentId, args.versionId)
+ .queryKey,
+ });
+}
+
+export async function waitForDocumentLocation(
+ args: DocumentLocationArgs,
+ options: WaitForDocumentLocationOptions
+): Promise<DocumentLocation> {
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
+ const initialDelayMs = options.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;
+ const maxDelayMs = options.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;
+ const deadline = Date.now() + timeoutMs;
+ let lastLocation: DocumentLocation | undefined;
+
+ try {
+ return await queryClient.fetchQuery({
+ queryKey: documentLocationKeys.wait(
+ args.documentId,
+ args.versionId,
+ options.target,
+ timeoutMs
+ ).queryKey,
+ queryFn: async () => {
+ await invalidateDocumentLocation(args);
+ const location = await fetchDocumentLocation(args);
+ lastLocation = location;
+
+ if (!options.isReady(location)) {
+ throw new DocumentLocationNotReadyError(location);
+ }
+
+ queryClient.setQueryData(
+ documentLocationKeys.location(args.documentId, args.versionId)
+ .queryKey,
+ location
+ );
+
+ return location;
+ },
+ retry: (_failureCount, error) =>
+ error instanceof DocumentLocationNotReadyError && Date.now() < deadline,
+ retryDelay: (attempt) => retryDelay(attempt, initialDelayMs, maxDelayMs),
+ staleTime: 0,
+ gcTime: 0,
+ });
+ } catch (error) {
+ if (error instanceof DocumentLocationNotReadyError) {
+ return error.location;
+ }
+ if (lastLocation) return lastLocation;
+ throw error;
+ }
+}
+
+export function waitForDocumentContentReady(
+ args: DocumentLocationArgs & {
+ timeoutMs?: number;
+ initialDelayMs?: number;
+ maxDelayMs?: number;
+ }
+): Promise<DocumentLocation> {
+ const { timeoutMs, initialDelayMs, maxDelayMs, ...locationArgs } = args;
+ return waitForDocumentLocation(locationArgs, {
+ target: 'content-ready',
+ timeoutMs,
+ initialDelayMs,
+ maxDelayMs,
+ isReady: (location) =>
+ location.content.state === DocumentContentState.ready,
+ });
+}
+
+export function waitForDocumentSyncServiceReady(
+ args: DocumentLocationArgs & {
+ timeoutMs?: number;
+ initialDelayMs?: number;
+ maxDelayMs?: number;
+ }
+): Promise<DocumentLocation> {
+ const { timeoutMs, initialDelayMs, maxDelayMs, ...locationArgs } = args;
+ return waitForDocumentLocation(locationArgs, {
+ target: 'sync-service-ready',
+ timeoutMs,
+ initialDelayMs,
+ maxDelayMs,
+ isReady: (location) =>
+ location.content.state === DocumentContentState.ready &&
+ location.type === 'syncServiceContent',
+ });
+}
+
+export function waitForDocumentPresignedUrlReady(
+ args: DocumentLocationArgs & {
+ timeoutMs?: number;
+ initialDelayMs?: number;
+ maxDelayMs?: number;
+ }
+): Promise<DocumentLocation> {
+ const { timeoutMs, initialDelayMs, maxDelayMs, ...locationArgs } = args;
+ return waitForDocumentLocation(locationArgs, {
+ target: 'presigned-url-ready',
+ timeoutMs,
+ initialDelayMs,
+ maxDelayMs,
+ isReady: (location) =>
+ location.content.state === DocumentContentState.ready &&
+ location.type === 'presignedUrl',
+ });
+}
+
+export function locationToMaybeResult(
+ location: DocumentLocation
+): MaybeResult<string, { data: DocumentLocation }> {
+ return [null, { data: location }];
+}
+
+export function isDocumentLocationReady(location: DocumentLocation) {
+ return location.content.state === DocumentContentState.ready;
+}
+
+export function isDocumentLocationResultReady(
+ result: MaybeResult<string, { data: DocumentLocation }>
+) {
+ return !isErr(result) && isDocumentLocationReady(result[1].data);
+}
diff --git a/js/app/packages/queries/storage/instructions-md.ts b/js/app/packages/queries/storage/instructions-md.ts
index ea1fb67bcb..23c8b51b36 100644
--- a/js/app/packages/queries/storage/instructions-md.ts
+++ b/js/app/packages/queries/storage/instructions-md.ts
@@ -1,11 +1,9 @@
-import { createMarkdownStateFromContent } from '@core/component/LexicalMarkdown/collaboration/utils';
import { createLexicalWrapper } from '@core/component/LexicalMarkdown/context/LexicalWrapperContext';
import {
getTextContent,
initializeEditorWithState,
} from '@core/component/LexicalMarkdown/utils';
import { isOk } from '@core/util/maybeResult';
-import { rawMarkdownStateToLoroSnapshot } from '@lexical-core/markdown-loro-snapshot';
import { storageServiceClient } from '@service-storage/client';
import { syncServiceClient } from '@service-sync/client';
import { useQuery } from '@tanstack/solid-query';
@@ -101,25 +99,9 @@ export function useInstructionsMdTextQuery() {
/** Creates the instructions md document. Backend prevents duplicates */
export function useCreateInstructionsMd() {
return async () => {
- const emptyMarkdownState = await createMarkdownStateFromContent(undefined);
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const snapshot = await rawMarkdownStateToLoroSnapshot(
- emptyMarkdownState as any
- );
- if (!snapshot) return;
const createResult = await storageServiceClient.instructions.create();
if (isOk(createResult)) {
const [, { documentId }] = createResult;
- const res = await syncServiceClient.initializeFromSnapshot({
- snapshot,
- documentId: documentId,
- });
- if (!isOk(res)) {
- console.error(
- 'Failed to initialize instructions document from snapshot'
- );
- return;
- }
queryClient.setQueryData(instructionsMdKeys.id.queryKey, documentId);
return documentId;
}
diff --git a/js/app/packages/queries/storage/keys.ts b/js/app/packages/queries/storage/keys.ts
index 1d3983b483..6ca2d7fbcd 100644
--- a/js/app/packages/queries/storage/keys.ts
+++ b/js/app/packages/queries/storage/keys.ts
@@ -11,6 +11,20 @@ export const deletedKeys = createQueryKeys('deleted', {
list: null,
});
+export const documentLocationKeys = createQueryKeys('documentLocation', {
+ location: (documentId: string, versionId?: number) => ({
+ queryKey: [documentId, versionId],
+ }),
+ wait: (
+ documentId: string,
+ versionId: number | undefined,
+ target: string,
+ timeoutMs: number
+ ) => ({
+ queryKey: ['wait', target, documentId, versionId, timeoutMs],
+ }),
+});
+
export const binaryDocumentKeys = createQueryKeys('binaryDocument', {
document: (documentId: string) => ({
queryKey: [documentId],
diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts
index 89bb8236bd..22d4760d4d 100644
--- a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts
@@ -1525,6 +1525,60 @@ export const ReadMetadataResponse = z.object({
branchName: z.union([z.string(), z.null()]).optional(),
branchedFromId: z.union([z.string(), z.null()]).optional(),
branchedFromVersionId: z.union([z.number().int(), z.null()]).optional(),
+ content: z.object({
+ location: z
+ .union([
+ z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('object_storage'),
+ z.literal('sync_service'),
+ z.literal('docx_bom_parts'),
+ z.literal('converted_pdf'),
+ z.literal('unknown'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) =>
+ result.error ? [...errors, result.error] : errors)(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ z.null(),
+ ])
+ .optional(),
+ state: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('unknown'),
+ z.literal('pending'),
+ z.literal('ready'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) => (result.error ? [...errors, result.error] : errors))(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ }),
createdAt: z
.union([z.string().datetime({ offset: true }), z.null()])
.optional(),
diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts b/js/app/packages/service-clients/service-cognition/generated/tools/types.ts
index 59a62af08b..ce410363c4 100644
--- a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/tools/types.ts
@@ -69,6 +69,19 @@ export type ContentType =
| 'chat-thread'
| 'chat-message'
| 'project';
+/**
+ * Where document content is, or is expected to be, read from.
+ */
+export type DocumentContentLocation =
+ | 'object_storage'
+ | 'sync_service'
+ | 'docx_bom_parts'
+ | 'converted_pdf'
+ | 'unknown';
+/**
+ * API-visible content lifecycle state derived from current document metadata.
+ */
+export type DocumentContentState = 'unknown' | 'pending' | 'ready';
/**
* The document sub type enum represents all values of document sub types.
* These values should match the `document_sub_type_value` table in macrodb.
@@ -769,6 +782,16 @@ export interface CreateDocumentResponse {
*/
documentId: string;
}
+/**
+ * API-visible content lifecycle and location metadata.
+ */
+export interface DocumentContent {
+ /**
+ * The content location, when known.
+ */
+ location?: DocumentContentLocation | null;
+ state: DocumentContentState;
+}
/**
* Metadata for a document fetched from the database
*/
@@ -1898,6 +1921,9 @@ export interface ReadContentResponse {
comments: CommentThread[];
content: Content;
}
+/**
+ * Full document metadata plus content lifecycle metadata.
+ */
export interface ReadDocumentMetadata {
/**
* If the document is a "task" the branch name of the document will be provided.
@@ -1913,6 +1939,7 @@ export interface ReadDocumentMetadata {
* the file type
*/
branchedFromVersionId?: number | null;
+ content: DocumentContent;
/**
* The time the document was created
*/
diff --git a/js/app/packages/service-clients/service-storage/client.ts b/js/app/packages/service-clients/service-storage/client.ts
index 386cbc15b9..b976733048 100644
--- a/js/app/packages/service-clients/service-storage/client.ts
+++ b/js/app/packages/service-clients/service-storage/client.ts
@@ -51,14 +51,17 @@ import type { CreateCommentResponse } from './generated/schemas/createCommentRes
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 { CreateMarkdownDocumentRequest } from './generated/schemas/createMarkdownDocumentRequest';
+import type { CreateMarkdownHandler200 } from './generated/schemas/createMarkdownHandler200';
import type { CreateProjectResponse } from './generated/schemas/createProjectResponse';
-import type { CreateTaskHandler200 as CreateTaskResponse } from './generated/schemas/createTaskHandler200';
+import type { CreateTaskHandler200 } from './generated/schemas/createTaskHandler200';
import type { CreateTaskRequest } from './generated/schemas/createTaskRequest';
import type { CreateUnthreadedAnchorResponse } from './generated/schemas/createUnthreadedAnchorResponse';
import type { DeleteCommentResponse } from './generated/schemas/deleteCommentResponse';
import type { DeleteUnthreadedAnchorResponse } from './generated/schemas/deleteUnthreadedAnchorResponse';
import type { DocumentMetadata } from './generated/schemas/documentMetadata';
import type { DocumentPreview } from './generated/schemas/documentPreview';
+import type { DocumentResponseMetadataWithContent } from './generated/schemas/documentResponseMetadataWithContent';
import type { EditAnchorResponse } from './generated/schemas/editAnchorResponse';
import type { EditCommentResponse } from './generated/schemas/editCommentResponse';
import type { ExportDocumentResponse } from './generated/schemas/exportDocumentResponse';
@@ -72,7 +75,7 @@ import type { GetPendingProjectsHandler200 } from './generated/schemas/getPendin
import type { GetProjectContentResponse } from './generated/schemas/getProjectContentResponse';
import type { GetProjectResponse } from './generated/schemas/getProjectResponse';
import type { Item } from './generated/schemas/item';
-import type { LocationResponseData } from './generated/schemas/locationResponseData';
+import type { LocationResponseV3 } from './generated/schemas/locationResponseV3';
import type { PinRequest } from './generated/schemas/pinRequest';
import type { Project } from './generated/schemas/project';
import type { ReorderPinRequest } from './generated/schemas/reorderPinRequest';
@@ -96,6 +99,10 @@ import {
getDocxExpandedParts,
} from './util/getDocxFile';
+function normalizeLocationResponseV3(response: LocationResponseV3) {
+ return response;
+}
+
// the server is set to expire at 15 minutes, so expire just before that
const MINUTES_BEFORE_PRESIGNED_EXPIRES = 14;
@@ -461,11 +468,34 @@ export const storageServiceClient = {
},
/**
- * Creates a task with properties in a single call.
- * NOTE: Content must be initialized separately via sync service (initializeFromSnapshot).
+ * Creates a markdown document and initializes its sync-service content on the backend.
+ */
+ async createMarkdownDocument(request: CreateMarkdownDocumentRequest) {
+ const result = await dssFetch<CreateMarkdownHandler200>(
+ `/documents/create_markdown`,
+ {
+ method: 'POST',
+ body: JSON.stringify(request),
+ }
+ );
+
+ if (!isOk(result)) {
+ const err = result[0];
+ if (err[0].message.includes('403')) {
+ showPaywall(PaywallKey.FILE_LIMIT);
+ }
+ return result;
+ }
+
+ const [, response] = result;
+ return ok({ documentId: response.documentId });
+ },
+
+ /**
+ * Creates a task with properties and initializes its sync-service content on the backend.
*/
async createTask(request: CreateTaskRequest) {
- const result = await dssFetch<CreateTaskResponse>(
+ const result = await dssFetch<CreateTaskHandler200>(
`/documents/create_task`,
{
method: 'POST',
@@ -482,7 +512,7 @@ export const storageServiceClient = {
}
const [, response] = result;
- return ok({ documentId: response.documentId });
+ return ok(response);
},
async copyDocument(params: {
@@ -493,20 +523,23 @@ export const storageServiceClient = {
}) {
const { documentId, documentVersionId, syncServiceVersion, ...body } =
params;
- const result: MaybeResult<FetchWithTokenErrorCode, DocumentMetadata> =
- mapOk(
- await dssFetch<{ data: { documentMetadata: DocumentMetadata } }>(
- `/documents/${documentId}/copy${documentVersionId ? `?version_id=${documentVersionId}` : ''}`,
- {
- method: 'POST',
- body: JSON.stringify({
- ...body,
- versionId: syncServiceVersion,
- }),
- }
- ),
- (result) => result.data.documentMetadata
- );
+ const copyResult = await dssFetch<{
+ data: { documentMetadata: DocumentResponseMetadataWithContent };
+ }>(
+ `/documents/${documentId}/copy${documentVersionId ? `?version_id=${documentVersionId}` : ''}`,
+ {
+ method: 'POST',
+ body: JSON.stringify({
+ ...body,
+ versionId: syncServiceVersion,
+ }),
+ }
+ );
+
+ const result: MaybeResult<
+ FetchWithTokenErrorCode,
+ DocumentResponseMetadataWithContent
+ > = mapOk(copyResult, (result) => result.data.documentMetadata);
if (isErr(result)) {
const err = result[0];
@@ -937,7 +970,7 @@ export const storageServiceClient = {
return err('NOT_FOUND', 'The document resource is no longer available');
else if (isErr(locationResult)) return locationResult;
const [, { data }] = locationResult;
- if (!('presignedUrl' in data)) {
+ if (data.type !== 'presignedUrl') {
return err(
'INVALID_DOCUMENT',
'Document location is missing presignedUrl'
@@ -987,7 +1020,7 @@ export const storageServiceClient = {
}
const [, { data }] = maybeLocation;
- if (!('presignedUrl' in data)) {
+ if (data.type !== 'presignedUrl') {
return err(
'INVALID_DOCUMENT',
'Document location is missing presignedUrl'
@@ -1053,12 +1086,18 @@ export const storageServiceClient = {
async function getDocumentLocation(args) {
const { documentId, versionId } = args;
// we want to ensure we get the converted docx url if we have enabled the DOCX to PDF feature flag
- const maybeResult = await dssFetch<LocationResponseData>(
- `/documents/${documentId}/location?document_version_id=${versionId}&get_converted_docx_url=${ENABLE_DOCX_TO_PDF}`
+ const params = new URLSearchParams({
+ get_converted_docx_url: String(ENABLE_DOCX_TO_PDF),
+ });
+ if (versionId != null)
+ params.set('document_version_id', String(versionId));
+
+ const maybeResult = await dssFetch<LocationResponseV3>(
+ `/documents/${documentId}/location_v3?${params.toString()}`
);
return mapOk(maybeResult, (result) => ({
- data: result,
+ data: normalizeLocationResponseV3(result),
}));
},
{
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
index 811b3be910..e63df91bfe 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/createDocument200DataOneOf.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createDocument200DataOneOf.ts
@@ -8,5 +8,8 @@
import type { CreateDocument200DataOneOfAllOf } from './createDocument200DataOneOfAllOf';
import type { DocumentResponse } from './documentResponse';
+/**
+ * Create document response data with content lifecycle metadata.
+ */
export type CreateDocument200DataOneOf = DocumentResponse &
CreateDocument200DataOneOfAllOf;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createDocument200DataOneOfAllOf.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createDocument200DataOneOfAllOf.ts
index 8277c44328..8caf461ed8 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/createDocument200DataOneOfAllOf.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createDocument200DataOneOfAllOf.ts
@@ -7,8 +7,8 @@
import type { CreateDocument200DataOneOfAllOfFileType } from './createDocument200DataOneOfAllOfFileType';
export type CreateDocument200DataOneOfAllOf = {
- /** Content type of the document converted from file type */
+ /** Content type of the document converted from file type. */
contentType: string;
- /** The file type of the document */
+ /** The file type of the document. */
fileType?: CreateDocument200DataOneOfAllOfFileType;
};
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createDocument200DataOneOfAllOfFileType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createDocument200DataOneOfAllOfFileType.ts
index a1fbc54cd3..c83a97f3e6 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/createDocument200DataOneOfAllOfFileType.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createDocument200DataOneOfAllOfFileType.ts
@@ -6,6 +6,6 @@
*/
/**
- * The file type of the document
+ * The file type of the document.
*/
export type CreateDocument200DataOneOfAllOfFileType = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createMarkdownDocumentRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createMarkdownDocumentRequest.ts
new file mode 100644
index 0000000000..27374d737b
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createMarkdownDocumentRequest.ts
@@ -0,0 +1,23 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { CreateMarkdownDocumentRequestMarkdown } from './createMarkdownDocumentRequestMarkdown';
+import type { CreateMarkdownDocumentRequestProjectId } from './createMarkdownDocumentRequestProjectId';
+
+/**
+ * Request body for creating a markdown document whose content is initialized
+by the backend.
+ */
+export interface CreateMarkdownDocumentRequest {
+ /** The document name. */
+ documentName: string;
+ /** Markdown source text. Defaults to an empty document. */
+ markdown?: CreateMarkdownDocumentRequestMarkdown;
+ /** Optional project ID to associate the document with. */
+ projectId?: CreateMarkdownDocumentRequestProjectId;
+ /** Whether to add a viewed_at record for this document upon creation. */
+ skipHistory?: boolean;
+}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createMarkdownDocumentRequestMarkdown.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createMarkdownDocumentRequestMarkdown.ts
new file mode 100644
index 0000000000..19690727f3
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createMarkdownDocumentRequestMarkdown.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Markdown source text. Defaults to an empty document.
+ */
+export type CreateMarkdownDocumentRequestMarkdown = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createMarkdownDocumentRequestProjectId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createMarkdownDocumentRequestProjectId.ts
new file mode 100644
index 0000000000..bef5afba15
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createMarkdownDocumentRequestProjectId.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Optional project ID to associate the document with.
+ */
+export type CreateMarkdownDocumentRequestProjectId = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createMarkdownDocumentResponse.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createMarkdownDocumentResponse.ts
new file mode 100644
index 0000000000..69f15b4a49
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createMarkdownDocumentResponse.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Response for creating a markdown document.
+ */
+export interface CreateMarkdownDocumentResponse {
+ /** The document ID of the created markdown document. */
+ documentId: string;
+}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createMarkdownHandler200.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createMarkdownHandler200.ts
new file mode 100644
index 0000000000..90d125dba2
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createMarkdownHandler200.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Response for creating a markdown document.
+ */
+export type CreateMarkdownHandler200 = {
+ /** The document ID of the created markdown document. */
+ documentId: string;
+};
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createTaskRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createTaskRequest.ts
index cc1e2a194b..f5fa0b7fcc 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/createTaskRequest.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createTaskRequest.ts
@@ -4,6 +4,7 @@
* document_storage_service
* OpenAPI spec version: 0.1.0
*/
+import type { CreateTaskRequestMarkdown } from './createTaskRequestMarkdown';
import type { CreateTaskRequestProjectId } from './createTaskRequestProjectId';
import type { CreateTaskRequestPropertyValues } from './createTaskRequestPropertyValues';
@@ -11,6 +12,8 @@ import type { CreateTaskRequestPropertyValues } from './createTaskRequestPropert
* Request body for creating a task.
*/
export interface CreateTaskRequest {
+ /** Markdown source text. Defaults to an empty task document. */
+ markdown?: CreateTaskRequestMarkdown;
/** Optional project ID to associate the task with. */
projectId?: CreateTaskRequestProjectId;
/** Optional property values to set on the task. */
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createTaskRequestMarkdown.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createTaskRequestMarkdown.ts
new file mode 100644
index 0000000000..a2c9438ad9
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createTaskRequestMarkdown.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Markdown source text. Defaults to an empty task document.
+ */
+export type CreateTaskRequestMarkdown = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/documentBasic.ts b/js/app/packages/service-clients/service-storage/generated/schemas/documentBasic.ts
new file mode 100644
index 0000000000..e65b020882
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/documentBasic.ts
@@ -0,0 +1,27 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { DocumentBasicBranchedFromId } from './documentBasicBranchedFromId';
+import type { DocumentBasicBranchedFromVersionId } from './documentBasicBranchedFromVersionId';
+import type { DocumentBasicDeletedAt } from './documentBasicDeletedAt';
+import type { DocumentBasicDocumentFamilyId } from './documentBasicDocumentFamilyId';
+import type { DocumentBasicFileType } from './documentBasicFileType';
+import type { DocumentBasicProjectId } from './documentBasicProjectId';
+
+/**
+ * Returns basic information of a document used for some db queries
+ */
+export interface DocumentBasic {
+ branchedFromId?: DocumentBasicBranchedFromId;
+ branchedFromVersionId?: DocumentBasicBranchedFromVersionId;
+ deletedAt?: DocumentBasicDeletedAt;
+ documentFamilyId?: DocumentBasicDocumentFamilyId;
+ documentId: string;
+ documentName: string;
+ fileType?: DocumentBasicFileType;
+ owner: string;
+ projectId?: DocumentBasicProjectId;
+}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/documentBasicBranchedFromId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/documentBasicBranchedFromId.ts
new file mode 100644
index 0000000000..dc7228d8a1
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/documentBasicBranchedFromId.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type DocumentBasicBranchedFromId = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/documentBasicBranchedFromVersionId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/documentBasicBranchedFromVersionId.ts
new file mode 100644
index 0000000000..c7f7791e9d
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/documentBasicBranchedFromVersionId.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type DocumentBasicBranchedFromVersionId = number | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/documentBasicDeletedAt.ts b/js/app/packages/service-clients/service-storage/generated/schemas/documentBasicDeletedAt.ts
new file mode 100644
index 0000000000..edea9350f7
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/documentBasicDeletedAt.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type DocumentBasicDeletedAt = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/documentBasicDocumentFamilyId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/documentBasicDocumentFamilyId.ts
new file mode 100644
index 0000000000..f860708514
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/documentBasicDocumentFamilyId.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type DocumentBasicDocumentFamilyId = number | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/documentBasicFileType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/documentBasicFileType.ts
new file mode 100644
index 0000000000..123bf02f28
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/documentBasicFileType.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type DocumentBasicFileType = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/documentBasicProjectId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/documentBasicProjectId.ts
new file mode 100644
index 0000000000..c7135ac47f
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/documentBasicProjectId.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type DocumentBasicProjectId = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/documentContent.ts b/js/app/packages/service-clients/service-storage/generated/schemas/documentContent.ts
new file mode 100644
index 0000000000..c5b054adbd
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/documentContent.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { DocumentContentLocationProperty } from './documentContentLocationProperty';
+import type { DocumentContentState } from './documentContentState';
+
+/**
+ * API-visible content lifecycle and location metadata.
+ */
+export interface DocumentContent {
+ location?: DocumentContentLocationProperty;
+ /** The current lifecycle state of the content. */
+ state: DocumentContentState;
+}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/documentContentLocation.ts b/js/app/packages/service-clients/service-storage/generated/schemas/documentContentLocation.ts
new file mode 100644
index 0000000000..eb86a7564d
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/documentContentLocation.ts
@@ -0,0 +1,21 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Where document content is, or is expected to be, read from.
+ */
+export type DocumentContentLocation =
+ (typeof DocumentContentLocation)[keyof typeof DocumentContentLocation];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const DocumentContentLocation = {
+ object_storage: 'object_storage',
+ sync_service: 'sync_service',
+ docx_bom_parts: 'docx_bom_parts',
+ converted_pdf: 'converted_pdf',
+ unknown: 'unknown',
+} as const;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/documentContentLocationProperty.ts b/js/app/packages/service-clients/service-storage/generated/schemas/documentContentLocationProperty.ts
new file mode 100644
index 0000000000..e816d1d8bb
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/documentContentLocationProperty.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { DocumentContentLocation } from './documentContentLocation';
+
+export type DocumentContentLocationProperty = null | DocumentContentLocation;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/documentContentState.ts b/js/app/packages/service-clients/service-storage/generated/schemas/documentContentState.ts
new file mode 100644
index 0000000000..5fa6c0f5c7
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/documentContentState.ts
@@ -0,0 +1,19 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * API-visible content lifecycle state derived from current document metadata.
+ */
+export type DocumentContentState =
+ (typeof DocumentContentState)[keyof typeof DocumentContentState];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const DocumentContentState = {
+ unknown: 'unknown',
+ pending: 'pending',
+ ready: 'ready',
+} as const;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/documentMetadataWithContent.ts b/js/app/packages/service-clients/service-storage/generated/schemas/documentMetadataWithContent.ts
new file mode 100644
index 0000000000..427eee2f77
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/documentMetadataWithContent.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { DocumentMetadata } from './documentMetadata';
+import type { DocumentMetadataWithContentAllOf } from './documentMetadataWithContentAllOf';
+
+/**
+ * Full document metadata plus content lifecycle metadata.
+ */
+export type DocumentMetadataWithContent = DocumentMetadata &
+ DocumentMetadataWithContentAllOf;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/documentMetadataWithContentAllOf.ts b/js/app/packages/service-clients/service-storage/generated/schemas/documentMetadataWithContentAllOf.ts
new file mode 100644
index 0000000000..adcff6c834
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/documentMetadataWithContentAllOf.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { DocumentContent } from './documentContent';
+
+export type DocumentMetadataWithContentAllOf = {
+ /** Content lifecycle and location metadata. */
+ content: DocumentContent;
+};
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/documentResponse.ts b/js/app/packages/service-clients/service-storage/generated/schemas/documentResponse.ts
index 385049656d..56855a02f5 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/documentResponse.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/documentResponse.ts
@@ -4,10 +4,15 @@
* document_storage_service
* OpenAPI spec version: 0.1.0
*/
-import type { DocumentResponseMetadata } from './documentResponseMetadata';
+import type { DocumentResponseMetadataWithContent } from './documentResponseMetadataWithContent';
import type { DocumentResponsePresignedUrl } from './documentResponsePresignedUrl';
+/**
+ * Document response with content lifecycle metadata.
+ */
export interface DocumentResponse {
- documentMetadata: DocumentResponseMetadata;
+ /** The document metadata. */
+ documentMetadata: DocumentResponseMetadataWithContent;
+ /** Presigned upload URL, when the caller still needs to upload bytes. */
presignedUrl?: DocumentResponsePresignedUrl;
}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/documentResponseMetadataWithContent.ts b/js/app/packages/service-clients/service-storage/generated/schemas/documentResponseMetadataWithContent.ts
new file mode 100644
index 0000000000..40e6e39ae3
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/documentResponseMetadataWithContent.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { DocumentResponseMetadata } from './documentResponseMetadata';
+import type { DocumentResponseMetadataWithContentAllOf } from './documentResponseMetadataWithContentAllOf';
+
+/**
+ * Create/copy response metadata plus content lifecycle metadata.
+ */
+export type DocumentResponseMetadataWithContent = DocumentResponseMetadata &
+ DocumentResponseMetadataWithContentAllOf;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/documentResponseMetadataWithContentAllOf.ts b/js/app/packages/service-clients/service-storage/generated/schemas/documentResponseMetadataWithContentAllOf.ts
new file mode 100644
index 0000000000..a061dd5d28
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/documentResponseMetadataWithContentAllOf.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { DocumentContent } from './documentContent';
+
+export type DocumentResponseMetadataWithContentAllOf = {
+ /** Content lifecycle and location metadata. */
+ content: DocumentContent;
+};
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/documentResponsePresignedUrl.ts b/js/app/packages/service-clients/service-storage/generated/schemas/documentResponsePresignedUrl.ts
index da7844e4d8..39c70a22c4 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/documentResponsePresignedUrl.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/documentResponsePresignedUrl.ts
@@ -5,4 +5,7 @@
* OpenAPI spec version: 0.1.0
*/
+/**
+ * Presigned upload URL, when the caller still needs to upload bytes.
+ */
export type DocumentResponsePresignedUrl = string | null;
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 d3feae3cfe..c4247d913c 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
@@ -185,11 +185,17 @@ export * from './createDocumentResponseData';
export * from './createDocumentResponseDataAllOf';
export * from './createDocumentResponseDataAllOfFileType';
export * from './createInstructionsDocumentResponse';
+export * from './createMarkdownDocumentRequest';
+export * from './createMarkdownDocumentRequestMarkdown';
+export * from './createMarkdownDocumentRequestProjectId';
+export * from './createMarkdownDocumentResponse';
+export * from './createMarkdownHandler200';
export * from './createProjectRequest';
export * from './createProjectRequestProjectParentId';
export * from './createProjectResponse';
export * from './createTaskHandler200';
export * from './createTaskRequest';
+export * from './createTaskRequestMarkdown';
export * from './createTaskRequestProjectId';
export * from './createTaskRequestPropertyValues';
export * from './createTaskResponse';
@@ -225,6 +231,17 @@ export * from './deleteUnthreadedAnchorResponseAllOfThreadId';
export * from './deleteUnthreadedPdfAnchorRequest';
export * from './deleteUnthreadedPdfAnchorRequestOneOf';
export * from './deleteUnthreadedPdfAnchorRequestOneOfAnchorType';
+export * from './documentBasic';
+export * from './documentBasicBranchedFromId';
+export * from './documentBasicBranchedFromVersionId';
+export * from './documentBasicDeletedAt';
+export * from './documentBasicDocumentFamilyId';
+export * from './documentBasicFileType';
+export * from './documentBasicProjectId';
+export * from './documentContent';
+export * from './documentContentLocation';
+export * from './documentContentLocationProperty';
+export * from './documentContentState';
export * from './documentFilters';
export * from './documentFiltersImportance';
export * from './documentFiltersIsEmailAttachment';
@@ -241,6 +258,8 @@ export * from './documentMetadataProjectName';
export * from './documentMetadataSha';
export * from './documentMetadataSubType';
export * from './documentMetadataUpdatedAt';
+export * from './documentMetadataWithContent';
+export * from './documentMetadataWithContentAllOf';
export * from './documentPermissionsToken';
export * from './documentPermissionsTokenRequest';
export * from './documentPermissionsTokenResponse';
@@ -273,6 +292,8 @@ export * from './documentResponseMetadataFileType';
export * from './documentResponseMetadataSha';
export * from './documentResponseMetadataSubType';
export * from './documentResponseMetadataUpdatedAt';
+export * from './documentResponseMetadataWithContent';
+export * from './documentResponseMetadataWithContentAllOf';
export * from './documentResponsePresignedUrl';
export * from './documentStorageServiceApiVersion';
export * from './documentSubType';
@@ -420,6 +441,13 @@ export * from './leaveCallResponse';
export * from './locationResponseData';
export * from './locationResponseDataOneOf';
export * from './locationResponseDataOneOfTwo';
+export * from './locationResponseV3';
+export * from './locationResponseV3OneOf';
+export * from './locationResponseV3OneOfFive';
+export * from './locationResponseV3OneOfFiveType';
+export * from './locationResponseV3OneOfThree';
+export * from './locationResponseV3OneOfThreeType';
+export * from './locationResponseV3OneOfType';
export * from './mentions';
export * from './notificationFilters';
export * from './notificationFiltersDone';
@@ -649,6 +677,8 @@ export * from './soupProjectViewedAt';
export * from './soupProperty';
export * from './soupPropertyValue';
export * from './successResponse';
+export * from './syncServiceDocumentMetadata';
+export * from './syncServicePeerWithUserId';
export * from './syncServiceVersionID';
export * from './taskFilters';
export * from './taskFiltersIncludeCbmAtmNc';
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/locationResponseV3.ts b/js/app/packages/service-clients/service-storage/generated/schemas/locationResponseV3.ts
new file mode 100644
index 0000000000..6ebd465335
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/locationResponseV3.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { LocationResponseV3OneOf } from './locationResponseV3OneOf';
+import type { LocationResponseV3OneOfFive } from './locationResponseV3OneOfFive';
+import type { LocationResponseV3OneOfThree } from './locationResponseV3OneOfThree';
+
+/**
+ * Location response with content lifecycle metadata.
+ */
+export type LocationResponseV3 =
+ | LocationResponseV3OneOf
+ | LocationResponseV3OneOfThree
+ | LocationResponseV3OneOfFive;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/locationResponseV3OneOf.ts b/js/app/packages/service-clients/service-storage/generated/schemas/locationResponseV3OneOf.ts
new file mode 100644
index 0000000000..2d80f9dfa1
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/locationResponseV3OneOf.ts
@@ -0,0 +1,23 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+import type { DocumentBasic } from './documentBasic';
+import type { DocumentContent } from './documentContent';
+import type { LocationResponseV3OneOfType } from './locationResponseV3OneOfType';
+
+/**
+ * A single document-storage URL.
+ */
+export type LocationResponseV3OneOf = {
+ /** Content lifecycle and location metadata. */
+ content: DocumentContent;
+ /** Basic document metadata. */
+ metadata: DocumentBasic;
+ /** Presigned URL. */
+ presignedUrl: string;
+ type: LocationResponseV3OneOfType;
+};
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/locationResponseV3OneOfFive.ts b/js/app/packages/service-clients/service-storage/generated/schemas/locationResponseV3OneOfFive.ts
new file mode 100644
index 0000000000..86f247f172
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/locationResponseV3OneOfFive.ts
@@ -0,0 +1,24 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+import type { DocumentBasic } from './documentBasic';
+import type { DocumentContent } from './documentContent';
+import type { LocationResponseV3OneOfFiveType } from './locationResponseV3OneOfFiveType';
+import type { SyncServiceDocumentMetadata } from './syncServiceDocumentMetadata';
+
+/**
+ * Sync-service backed content.
+ */
+export type LocationResponseV3OneOfFive = {
+ /** Content lifecycle and location metadata. */
+ content: DocumentContent;
+ /** Basic document metadata. */
+ metadata: DocumentBasic;
+ /** Sync-service metadata. */
+ syncServiceMetadata: SyncServiceDocumentMetadata;
+ type: LocationResponseV3OneOfFiveType;
+};
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/locationResponseV3OneOfFiveType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/locationResponseV3OneOfFiveType.ts
new file mode 100644
index 0000000000..48dec638e4
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/locationResponseV3OneOfFiveType.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type LocationResponseV3OneOfFiveType =
+ (typeof LocationResponseV3OneOfFiveType)[keyof typeof LocationResponseV3OneOfFiveType];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const LocationResponseV3OneOfFiveType = {
+ syncServiceContent: 'syncServiceContent',
+} as const;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/locationResponseV3OneOfThree.ts b/js/app/packages/service-clients/service-storage/generated/schemas/locationResponseV3OneOfThree.ts
new file mode 100644
index 0000000000..8305eb3dfb
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/locationResponseV3OneOfThree.ts
@@ -0,0 +1,24 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+import type { DocumentBasic } from './documentBasic';
+import type { DocumentContent } from './documentContent';
+import type { LocationResponseV3OneOfThreeType } from './locationResponseV3OneOfThreeType';
+import type { PresignedUrl } from './presignedUrl';
+
+/**
+ * Multiple document-storage URLs, currently for DOCX BOM parts.
+ */
+export type LocationResponseV3OneOfThree = {
+ /** Content lifecycle and location metadata. */
+ content: DocumentContent;
+ /** Basic document metadata. */
+ metadata: DocumentBasic;
+ /** Presigned URLs. */
+ presignedUrls: PresignedUrl[];
+ type: LocationResponseV3OneOfThreeType;
+};
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/locationResponseV3OneOfThreeType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/locationResponseV3OneOfThreeType.ts
new file mode 100644
index 0000000000..e3ce37c12c
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/locationResponseV3OneOfThreeType.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type LocationResponseV3OneOfThreeType =
+ (typeof LocationResponseV3OneOfThreeType)[keyof typeof LocationResponseV3OneOfThreeType];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const LocationResponseV3OneOfThreeType = {
+ presignedUrls: 'presignedUrls',
+} as const;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/locationResponseV3OneOfType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/locationResponseV3OneOfType.ts
new file mode 100644
index 0000000000..1e670ea045
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/locationResponseV3OneOfType.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type LocationResponseV3OneOfType =
+ (typeof LocationResponseV3OneOfType)[keyof typeof LocationResponseV3OneOfType];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const LocationResponseV3OneOfType = {
+ presignedUrl: 'presignedUrl',
+} as const;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/syncServiceDocumentMetadata.ts b/js/app/packages/service-clients/service-storage/generated/schemas/syncServiceDocumentMetadata.ts
new file mode 100644
index 0000000000..93b430c444
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/syncServiceDocumentMetadata.ts
@@ -0,0 +1,19 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { SyncServicePeerWithUserId } from './syncServicePeerWithUserId';
+
+/**
+ * Sync-service document metadata exposed through document location responses.
+ */
+export interface SyncServiceDocumentMetadata {
+ /** Sync-service document id. */
+ id: string;
+ /** Known peers for the sync document. */
+ peers: SyncServicePeerWithUserId[];
+ /** Current sync-service version id. */
+ version_id: string;
+}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/syncServicePeerWithUserId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/syncServicePeerWithUserId.ts
new file mode 100644
index 0000000000..3c28d4068e
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/syncServicePeerWithUserId.ts
@@ -0,0 +1,16 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Peer/user mapping returned by sync-service metadata.
+ */
+export interface SyncServicePeerWithUserId {
+ /** Sync-service peer id. */
+ peer_id: string;
+ /** Macro user id. */
+ user_id: string;
+}
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 eb767779dc..00e19210db 100644
--- a/js/app/packages/service-clients/service-storage/generated/zod.ts
+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts
@@ -1974,108 +1974,184 @@ export const createDocumentBody = zod.object({
export const createDocumentResponse = zod.object({
data: zod
.object({
- documentMetadata: zod.object({
- branchedFromId: zod
- .string()
- .nullish()
- .describe('The id of the document this document branched from'),
- branchedFromVersionId: zod
- .number()
- .nullish()
- .describe(
- 'The id of the version this document branched from\nThis could be either DocumentInstance or DocumentBom id depending on\nthe file type'
- ),
- createdAt: zod.iso
- .datetime({})
- .nullish()
- .describe('The time the document was created'),
- documentBom: zod
- .array(
- zod.object({
- id: zod.string().describe('The uuid of the bom part'),
- path: zod
- .string()
- .describe('The file path of the bom part content'),
- sha: zod
- .string()
+ documentMetadata: zod
+ .object({
+ branchedFromId: zod
+ .string()
+ .nullish()
+ .describe('The id of the document this document branched from'),
+ branchedFromVersionId: zod
+ .number()
+ .nullish()
+ .describe(
+ 'The id of the version this document branched from\nThis could be either DocumentInstance or DocumentBom id depending on\nthe file type'
+ ),
+ createdAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe('The time the document was created'),
+ documentBom: zod
+ .array(
+ zod.object({
+ id: zod.string().describe('The uuid of the bom part'),
+ path: zod
+ .string()
+ .describe('The file path of the bom part content'),
+ sha: zod
+ .string()
+ .describe(
+ 'The sha of the bom part content\nThere is an index on sha for more performant queries based on it.'
+ ),
+ })
+ )
+ .nullish()
+ .describe(
+ 'If the document is a DOCX document, the document_bom will be present'
+ ),
+ documentFamilyId: zod
+ .number()
+ .nullish()
+ .describe('The id of the document family this document belongs to'),
+ documentId: zod.string().describe('The document id'),
+ documentName: zod.string().describe('The name of the document'),
+ documentVersionId: zod
+ .number()
+ .describe(
+ 'The version of the document\nThis could be the document_instance_id or document_bom_id depending on\nthe file type'
+ ),
+ fileType: zod
+ .string()
+ .nullish()
+ .describe('The file type of the document'),
+ modificationData: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'The modification data for the document instance.\nThis is only used for PDF documents.'
+ ),
+ owner: zod.string().describe('The owner of the document'),
+ sha: zod
+ .string()
+ .nullish()
+ .describe(
+ 'If the document is a PDF, this is the SHA of the pdf\nIf the document is a DOCX, this will not be present'
+ ),
+ subType: zod
+ .union([
+ zod.null(),
+ zod
+ .enum(['task'])
.describe(
- 'The sha of the bom part content\nThere is an index on sha for more performant queries based on it.'
+ 'The document sub type enum represents all values of document sub types.\nThese values should match the `document_sub_type_value` table in macrodb.'
),
- })
- )
- .nullish()
- .describe(
- 'If the document is a DOCX document, the document_bom will be present'
- ),
- documentFamilyId: zod
- .number()
- .nullish()
- .describe('The id of the document family this document belongs to'),
- documentId: zod.string().describe('The document id'),
- documentName: zod.string().describe('The name of the document'),
- documentVersionId: zod
- .number()
- .describe(
- 'The version of the document\nThis could be the document_instance_id or document_bom_id depending on\nthe file type'
- ),
- fileType: zod
- .string()
- .nullish()
- .describe('The file type of the document'),
- modificationData: zod
- .unknown()
- .optional()
- .describe(
- 'The modification data for the document instance.\nThis is only used for PDF documents.'
- ),
- owner: zod.string().describe('The owner of the document'),
- sha: zod
- .string()
- .nullish()
- .describe(
- 'If the document is a PDF, this is the SHA of the pdf\nIf the document is a DOCX, this will not be present'
- ),
- subType: zod
- .union([
- zod.null(),
- zod
- .enum(['task'])
- .describe(
- 'The document sub type enum represents all values of document sub types.\nThese values should match the `document_sub_type_value` table in macrodb.'
- ),
- ])
- .optional(),
- updatedAt: zod.iso
- .datetime({})
- .nullish()
- .describe(
- 'The time the document instance \/ document BOM was updated'
- ),
- }),
- presignedUrl: zod.string().nullish(),
+ ])
+ .optional(),
+ updatedAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe(
+ 'The time the document instance \/ document BOM was updated'
+ ),
+ })
+ .and(
+ zod.object({
+ content: zod
+ .object({
+ location: zod
+ .union([
+ zod.null(),
+ zod
+ .enum([
+ 'object_storage',
+ 'sync_service',
+ 'docx_bom_parts',
+ 'converted_pdf',
+ 'unknown',
+ ])
+ .describe(
+ 'Where document content is, or is expected to be, read from.'
+ ),
+ ])
+ .optional(),
+ state: zod
+ .enum(['unknown', 'pending', 'ready'])
+ .describe(
+ 'API-visible content lifecycle state derived from current document metadata.'
+ ),
+ })
+ .describe('API-visible content lifecycle and location metadata.'),
+ })
+ )
+ .describe(
+ 'Create\/copy response metadata plus content lifecycle metadata.'
+ ),
+ presignedUrl: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Presigned upload URL, when the caller still needs to upload bytes.'
+ ),
})
+ .describe('Document response with content lifecycle metadata.')
.and(
zod.object({
contentType: zod
.string()
- .describe('Content type of the document converted from file type'),
+ .describe('Content type of the document converted from file type.'),
fileType: zod
.string()
.nullish()
- .describe('The file type of the document'),
+ .describe('The file type of the document.'),
})
)
+ .describe('Create document response data with content lifecycle metadata.')
.describe('Data to be returned'),
error: zod.boolean().describe('Indicates if an error occurred'),
});
/**
- * This endpoint creates task metadata and sets properties atomically.
-Task content should be set separately via the sync service.
- * @summary Creates a task document with properties in a single call.
+ * @summary Creates and initializes a markdown document in one backend-owned lifecycle.
+ */
+export const createMarkdownHandlerBody = zod
+ .object({
+ documentName: zod.string().describe('The document name.'),
+ markdown: zod
+ .string()
+ .nullish()
+ .describe('Markdown source text. Defaults to an empty document.'),
+ projectId: zod
+ .uuid()
+ .nullish()
+ .describe('Optional project ID to associate the document with.'),
+ skipHistory: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether to add a viewed_at record for this document upon creation.'
+ ),
+ })
+ .describe(
+ 'Request body for creating a markdown document whose content is initialized\nby the backend.'
+ );
+
+export const createMarkdownHandlerResponse = zod
+ .object({
+ documentId: zod
+ .string()
+ .describe('The document ID of the created markdown document.'),
+ })
+ .describe('Response for creating a markdown document.');
+
+/**
+ * @summary Creates a task document with properties and initialized markdown content in
+one backend-owned lifecycle.
*/
export const createTaskHandlerBody = zod
.object({
+ markdown: zod
+ .string()
+ .nullish()
+ .describe('Markdown source text. Defaults to an empty task document.'),
projectId: zod
.uuid()
.nullish()
@@ -2434,103 +2510,140 @@ export const getDocumentParams = zod.object({
});
export const getDocumentResponse = zod.object({
- data: zod.object({
- documentMetadata: zod.object({
- branchedFromId: zod
- .string()
- .nullish()
- .describe('The id of the document this document branched from'),
- branchedFromVersionId: zod
- .number()
- .nullish()
- .describe(
- 'The id of the version this document branched from\nThis could be either DocumentInstance or DocumentBom id depending on\nthe file type'
- ),
- createdAt: zod.iso
- .datetime({})
- .nullish()
- .describe('The time the document was created'),
- deletedAt: zod.iso
- .datetime({})
- .nullish()
- .describe('The time the document was deleted'),
- documentBom: zod
+ data: zod
+ .object({
+ items: zod
.array(
- zod.object({
- id: zod.string().describe('The uuid of the bom part'),
- path: zod
- .string()
- .describe('The file path of the bom part content'),
- sha: zod
- .string()
- .describe(
- 'The sha of the bom part content\nThere is an index on sha for more performant queries based on it.'
- ),
- })
- )
- .nullish()
- .describe(
- 'If the document is a DOCX document and unzipped, the document_bom will be present'
- ),
- documentFamilyId: zod
- .number()
- .nullish()
- .describe('The id of the document family this document belongs to'),
- documentId: zod.string().describe('The document id'),
- documentName: zod.string().describe('The name of the document'),
- documentVersionId: zod
- .number()
- .describe(
- 'The version of the document\nThis could be the document_instance_id or document_bom_id depending on\nthe file type'
- ),
- fileType: zod
- .string()
- .nullish()
- .describe('The file type of the document (file extension)'),
- modificationData: zod
- .unknown()
- .optional()
- .describe(
- 'The modification data for the document instance.\nThis is only used for PDF documents.'
- ),
- owner: zod.string().describe('The owner of the document'),
- projectId: zod
- .string()
- .nullish()
- .describe('The id of the project that this document belongs to'),
- projectName: zod
- .string()
- .nullish()
- .describe('The name of the project that this document belongs to'),
- sha: zod
- .string()
- .nullish()
- .describe(
- 'If the document is a PDF, this is the SHA of the pdf\nIf the document is a DOCX, this will not be present'
- ),
- subType: zod
- .union([
- zod.null(),
- zod
- .enum(['task'])
- .describe(
- 'The document sub type enum represents all values of document sub types.\nThese values should match the `document_sub_type_value` table in macrodb.'
- ),
- ])
- .optional(),
- updatedAt: zod.iso
- .datetime({})
- .nullish()
- .describe('The time the document instance \/ document BOM was updated'),
- }),
- userAccessLevel: zod
- .enum(['view', 'comment', 'edit', 'owner'])
- .describe('Ordered from least to most access top -> bottom'),
- viewLocation: zod
- .string()
- .nullish()
- .describe('The users view location if there is one'),
- }),
+ zod.union([
+ zod.object({
+ branchedFromId: zod
+ .string()
+ .nullish()
+ .describe('The id of the document this document branched from'),
+ branchedFromVersionId: zod
+ .number()
+ .nullish()
+ .describe(
+ 'The id of the version this document branched from\nThis could be either DocumentInstance or DocumentBom id depending on\nthe file type'
+ ),
+ createdAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe('The time the document was created'),
+ deletedAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe('The time the document was deleted'),
+ documentFamilyId: zod
+ .number()
+ .nullish()
+ .describe(
+ 'The id of the document family this document belongs to'
+ ),
+ documentVersionId: zod
+ .number()
+ .describe(
+ 'The version of the document\nThis could be the document_instance_id or document_bom_id depending on\nthe file type'
+ ),
+ fileType: zod
+ .string()
+ .nullish()
+ .describe('The file type of the document (e.g. pdf, docx)'),
+ id: zod.string().describe('The document id'),
+ name: zod.string().describe('The name of the document'),
+ owner: zod.string().describe('The owner of the document'),
+ projectId: zod
+ .string()
+ .nullish()
+ .describe(
+ 'The id of the project that this document belongs to'
+ ),
+ sha: zod
+ .string()
+ .nullish()
+ .describe(
+ 'If the document is a PDF, this is the SHA of the pdf\nIf the document is a DOCX, this will not be present'
+ ),
+ subType: zod
+ .union([
+ zod.null(),
+ zod
+ .object({
+ is_completed: zod
+ .boolean()
+ .describe(
+ 'Whether the task is completed.\nTrue if the Status property is set to \"Completed\".'
+ ),
+ type: zod.enum(['task']),
+ })
+ .describe('A task document with its associated properties')
+ .describe(
+ 'Sub type of a document with associated properties encoded in each variant.\nThis ensures type-safety: task properties only exist when the document is a task.'
+ ),
+ ])
+ .optional(),
+ updatedAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe(
+ 'The time the document instance \/ document BOM was updated'
+ ),
+ type: zod.enum(['document']),
+ }),
+ zod.object({
+ createdAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe('The time the chat was created'),
+ deletedAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe('The time the chat was deleted'),
+ id: zod.string().describe('The chat uuid'),
+ isPersistent: zod.boolean(),
+ model: zod
+ .string()
+ .nullish()
+ .describe('The model used to generate the chat'),
+ name: zod.string().describe('The name of the chat'),
+ projectId: zod
+ .string()
+ .nullish()
+ .describe('The project id of the chat'),
+ tokenCount: zod.number().nullish(),
+ updatedAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe('The time the chat was last updated'),
+ userId: zod.string().describe('Who the chat belongs to'),
+ type: zod.enum(['chat']),
+ }),
+ zod.object({
+ createdAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe('The time the project was created'),
+ deletedAt: zod.iso.datetime({}).nullish(),
+ id: zod.string().describe('The id of the project'),
+ name: zod.string().describe('The name of the project'),
+ parentId: zod
+ .string()
+ .nullish()
+ .describe('The parent project id'),
+ updatedAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe('The time the project was updated'),
+ userId: zod
+ .string()
+ .describe('The user id of who created the project'),
+ type: zod.enum(['project']),
+ }),
+ ])
+ )
+ .describe('The items returned from the call'),
+ })
+ .describe('Data to be returned'),
error: zod.boolean().describe('Indicates if an error occurred'),
});
@@ -3241,87 +3354,131 @@ export const copyDocumentBody = zod
export const copyDocumentResponse = zod
.object({
- data: zod.object({
- documentMetadata: zod.object({
- branchedFromId: zod
- .string()
- .nullish()
- .describe('The id of the document this document branched from'),
- branchedFromVersionId: zod
- .number()
- .nullish()
- .describe(
- 'The id of the version this document branched from\nThis could be either DocumentInstance or DocumentBom id depending on\nthe file type'
- ),
- createdAt: zod.iso
- .datetime({})
- .nullish()
- .describe('The time the document was created'),
- documentBom: zod
- .array(
+ data: zod
+ .object({
+ documentMetadata: zod
+ .object({
+ branchedFromId: zod
+ .string()
+ .nullish()
+ .describe('The id of the document this document branched from'),
+ branchedFromVersionId: zod
+ .number()
+ .nullish()
+ .describe(
+ 'The id of the version this document branched from\nThis could be either DocumentInstance or DocumentBom id depending on\nthe file type'
+ ),
+ createdAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe('The time the document was created'),
+ documentBom: zod
+ .array(
+ zod.object({
+ id: zod.string().describe('The uuid of the bom part'),
+ path: zod
+ .string()
+ .describe('The file path of the bom part content'),
+ sha: zod
+ .string()
+ .describe(
+ 'The sha of the bom part content\nThere is an index on sha for more performant queries based on it.'
+ ),
+ })
+ )
+ .nullish()
+ .describe(
+ 'If the document is a DOCX document, the document_bom will be present'
+ ),
+ documentFamilyId: zod
+ .number()
+ .nullish()
+ .describe(
+ 'The id of the document family this document belongs to'
+ ),
+ documentId: zod.string().describe('The document id'),
+ documentName: zod.string().describe('The name of the document'),
+ documentVersionId: zod
+ .number()
+ .describe(
+ 'The version of the document\nThis could be the document_instance_id or document_bom_id depending on\nthe file type'
+ ),
+ fileType: zod
+ .string()
+ .nullish()
+ .describe('The file type of the document'),
+ modificationData: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'The modification data for the document instance.\nThis is only used for PDF documents.'
+ ),
+ owner: zod.string().describe('The owner of the document'),
+ sha: zod
+ .string()
+ .nullish()
+ .describe(
+ 'If the document is a PDF, this is the SHA of the pdf\nIf the document is a DOCX, this will not be present'
+ ),
+ subType: zod
+ .union([
+ zod.null(),
+ zod
+ .enum(['task'])
+ .describe(
+ 'The document sub type enum represents all values of document sub types.\nThese values should match the `document_sub_type_value` table in macrodb.'
+ ),
+ ])
+ .optional(),
+ updatedAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe(
+ 'The time the document instance \/ document BOM was updated'
+ ),
+ })
+ .and(
zod.object({
- id: zod.string().describe('The uuid of the bom part'),
- path: zod
- .string()
- .describe('The file path of the bom part content'),
- sha: zod
- .string()
+ content: zod
+ .object({
+ location: zod
+ .union([
+ zod.null(),
+ zod
+ .enum([
+ 'object_storage',
+ 'sync_service',
+ 'docx_bom_parts',
+ 'converted_pdf',
+ 'unknown',
+ ])
+ .describe(
+ 'Where document content is, or is expected to be, read from.'
+ ),
+ ])
+ .optional(),
+ state: zod
+ .enum(['unknown', 'pending', 'ready'])
+ .describe(
+ 'API-visible content lifecycle state derived from current document metadata.'
+ ),
+ })
.describe(
- 'The sha of the bom part content\nThere is an index on sha for more performant queries based on it.'
+ 'API-visible content lifecycle and location metadata.'
),
})
)
- .nullish()
- .describe(
- 'If the document is a DOCX document, the document_bom will be present'
- ),
- documentFamilyId: zod
- .number()
- .nullish()
- .describe('The id of the document family this document belongs to'),
- documentId: zod.string().describe('The document id'),
- documentName: zod.string().describe('The name of the document'),
- documentVersionId: zod
- .number()
.describe(
- 'The version of the document\nThis could be the document_instance_id or document_bom_id depending on\nthe file type'
+ 'Create\/copy response metadata plus content lifecycle metadata.'
),
- fileType: zod
- .string()
- .nullish()
- .describe('The file type of the document'),
- modificationData: zod
- .unknown()
- .optional()
- .describe(
- 'The modification data for the document instance.\nThis is only used for PDF documents.'
- ),
- owner: zod.string().describe('The owner of the document'),
- sha: zod
+ presignedUrl: zod
.string()
.nullish()
.describe(
- 'If the document is a PDF, this is the SHA of the pdf\nIf the document is a DOCX, this will not be present'
- ),
- subType: zod
- .union([
- zod.null(),
- zod
- .enum(['task'])
- .describe(
- 'The document sub type enum represents all values of document sub types.\nThese values should match the `document_sub_type_value` table in macrodb.'
- ),
- ])
- .optional(),
- updatedAt: zod.iso
- .datetime({})
- .nullish()
- .describe(
- 'The time the document instance \/ document BOM was updated'
+ 'Presigned upload URL, when the caller still needs to upload bytes.'
),
- }),
- presignedUrl: zod.string().nullish(),
- }),
+ })
+ .describe('Document response with content lifecycle metadata.'),
error: zod.boolean().describe('Indicates if an error occurred.'),
})
.describe('Response wrapper for the copy document endpoint.');
@@ -3399,6 +3556,181 @@ export const getDocumentLocationV3QueryParams = zod.object({
.describe('If true, this will return the converted docx url.'),
});
+export const getDocumentLocationV3Response = zod
+ .union([
+ zod
+ .object({
+ content: zod
+ .object({
+ location: zod
+ .union([
+ zod.null(),
+ zod
+ .enum([
+ 'object_storage',
+ 'sync_service',
+ 'docx_bom_parts',
+ 'converted_pdf',
+ 'unknown',
+ ])
+ .describe(
+ 'Where document content is, or is expected to be, read from.'
+ ),
+ ])
+ .optional(),
+ state: zod
+ .enum(['unknown', 'pending', 'ready'])
+ .describe(
+ 'API-visible content lifecycle state derived from current document metadata.'
+ ),
+ })
+ .describe('API-visible content lifecycle and location metadata.'),
+ metadata: zod
+ .object({
+ branchedFromId: zod.string().nullish(),
+ branchedFromVersionId: zod.number().nullish(),
+ deletedAt: zod.iso.datetime({}).nullish(),
+ documentFamilyId: zod.number().nullish(),
+ documentId: zod.string(),
+ documentName: zod.string(),
+ fileType: zod.string().nullish(),
+ owner: zod.string(),
+ projectId: zod.string().nullish(),
+ })
+ .describe(
+ 'Returns basic information of a document used for some db queries'
+ ),
+ presignedUrl: zod.string().describe('Presigned URL.'),
+ type: zod.enum(['presignedUrl']),
+ })
+ .describe('A single document-storage URL.'),
+ zod
+ .object({
+ content: zod
+ .object({
+ location: zod
+ .union([
+ zod.null(),
+ zod
+ .enum([
+ 'object_storage',
+ 'sync_service',
+ 'docx_bom_parts',
+ 'converted_pdf',
+ 'unknown',
+ ])
+ .describe(
+ 'Where document content is, or is expected to be, read from.'
+ ),
+ ])
+ .optional(),
+ state: zod
+ .enum(['unknown', 'pending', 'ready'])
+ .describe(
+ 'API-visible content lifecycle state derived from current document metadata.'
+ ),
+ })
+ .describe('API-visible content lifecycle and location metadata.'),
+ metadata: zod
+ .object({
+ branchedFromId: zod.string().nullish(),
+ branchedFromVersionId: zod.number().nullish(),
+ deletedAt: zod.iso.datetime({}).nullish(),
+ documentFamilyId: zod.number().nullish(),
+ documentId: zod.string(),
+ documentName: zod.string(),
+ fileType: zod.string().nullish(),
+ owner: zod.string(),
+ projectId: zod.string().nullish(),
+ })
+ .describe(
+ 'Returns basic information of a document used for some db queries'
+ ),
+ presignedUrls: zod
+ .array(
+ zod.object({
+ presignedUrl: zod
+ .string()
+ .describe('The presigned url used to upload the sha'),
+ sha: zod.string().describe('The sha of the item'),
+ })
+ )
+ .describe('Presigned URLs.'),
+ type: zod.enum(['presignedUrls']),
+ })
+ .describe(
+ 'Multiple document-storage URLs, currently for DOCX BOM parts.'
+ ),
+ zod
+ .object({
+ content: zod
+ .object({
+ location: zod
+ .union([
+ zod.null(),
+ zod
+ .enum([
+ 'object_storage',
+ 'sync_service',
+ 'docx_bom_parts',
+ 'converted_pdf',
+ 'unknown',
+ ])
+ .describe(
+ 'Where document content is, or is expected to be, read from.'
+ ),
+ ])
+ .optional(),
+ state: zod
+ .enum(['unknown', 'pending', 'ready'])
+ .describe(
+ 'API-visible content lifecycle state derived from current document metadata.'
+ ),
+ })
+ .describe('API-visible content lifecycle and location metadata.'),
+ metadata: zod
+ .object({
+ branchedFromId: zod.string().nullish(),
+ branchedFromVersionId: zod.number().nullish(),
+ deletedAt: zod.iso.datetime({}).nullish(),
+ documentFamilyId: zod.number().nullish(),
+ documentId: zod.string(),
+ documentName: zod.string(),
+ fileType: zod.string().nullish(),
+ owner: zod.string(),
+ projectId: zod.string().nullish(),
+ })
+ .describe(
+ 'Returns basic information of a document used for some db queries'
+ ),
+ syncServiceMetadata: zod
+ .object({
+ id: zod.string().describe('Sync-service document id.'),
+ peers: zod
+ .array(
+ zod
+ .object({
+ peer_id: zod.string().describe('Sync-service peer id.'),
+ user_id: zod.string().describe('Macro user id.'),
+ })
+ .describe(
+ 'Peer\/user mapping returned by sync-service metadata.'
+ )
+ )
+ .describe('Known peers for the sync document.'),
+ version_id: zod
+ .string()
+ .describe('Current sync-service version id.'),
+ })
+ .describe(
+ 'Sync-service document metadata exposed through document location responses.'
+ ),
+ type: zod.enum(['syncServiceContent']),
+ })
+ .describe('Sync-service backed content.'),
+ ])
+ .describe('Location response with content lifecycle metadata.');
+
/**
* @summary Permanently deletes a document.
*/
diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.json
index 1ddea63719..fa45f6fba4 100644
--- a/js/app/packages/service-clients/service-storage/openapi.json
+++ b/js/app/packages/service-clients/service-storage/openapi.json
@@ -1861,7 +1861,8 @@
{
"allOf": [
{
- "$ref": "#/components/schemas/DocumentResponse"
+ "$ref": "#/components/schemas/DocumentResponse",
+ "description": "Document metadata and upload URL."
},
{
"type": "object",
@@ -1869,15 +1870,16 @@
"properties": {
"contentType": {
"type": "string",
- "description": "Content type of the document converted from file type"
+ "description": "Content type of the document converted from file type."
},
"fileType": {
"type": ["string", "null"],
- "description": "The file type of the document"
+ "description": "The file type of the document."
}
}
}
- ]
+ ],
+ "description": "Create document response data with content lifecycle metadata."
}
],
"description": "Data to be returned"
@@ -1934,11 +1936,87 @@
}
}
},
+ "/documents/create_markdown": {
+ "post": {
+ "tags": ["document"],
+ "summary": "Creates and initializes a markdown document in one backend-owned lifecycle.",
+ "operationId": "create_markdown_handler",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreateMarkdownDocumentRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "description": "Response for creating a markdown document.",
+ "required": ["documentId"],
+ "properties": {
+ "documentId": {
+ "type": "string",
+ "description": "The document ID of the created markdown document."
+ }
+ }
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "409": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/documents/create_task": {
"post": {
"tags": ["document"],
- "summary": "Creates a task document with properties in a single call.",
- "description": "This endpoint creates task metadata and sets properties atomically.\nTask content should be set separately via the sync service.",
+ "summary": "Creates a task document with properties and initialized markdown content in\none backend-owned lifecycle.",
"operationId": "create_task_handler",
"requestBody": {
"content": {
@@ -2370,7 +2448,7 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/GetDocumentResponse"
+ "$ref": "#/components/schemas/TypedSuccessResponse"
}
}
}
@@ -2983,7 +3061,14 @@
],
"responses": {
"200": {
- "description": ""
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/LocationResponseV3"
+ }
+ }
+ }
},
"401": {
"description": "",
@@ -7472,6 +7557,41 @@
}
}
},
+ "CreateMarkdownDocumentRequest": {
+ "type": "object",
+ "description": "Request body for creating a markdown document whose content is initialized\nby the backend.",
+ "required": ["documentName"],
+ "properties": {
+ "documentName": {
+ "type": "string",
+ "description": "The document name."
+ },
+ "markdown": {
+ "type": ["string", "null"],
+ "description": "Markdown source text. Defaults to an empty document."
+ },
+ "projectId": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "Optional project ID to associate the document with."
+ },
+ "skipHistory": {
+ "type": "boolean",
+ "description": "Whether to add a viewed_at record for this document upon creation."
+ }
+ }
+ },
+ "CreateMarkdownDocumentResponse": {
+ "type": "object",
+ "description": "Response for creating a markdown document.",
+ "required": ["documentId"],
+ "properties": {
+ "documentId": {
+ "type": "string",
+ "description": "The document ID of the created markdown document."
+ }
+ }
+ },
"CreateProjectRequest": {
"type": "object",
"required": ["name"],
@@ -7506,6 +7626,10 @@
"description": "Request body for creating a task.",
"required": ["taskName"],
"properties": {
+ "markdown": {
+ "type": ["string", "null"],
+ "description": "Markdown source text. Defaults to an empty task document."
+ },
"projectId": {
"type": ["string", "null"],
"format": "uuid",
@@ -7759,6 +7883,81 @@
}
]
},
+ "DocumentBasic": {
+ "type": "object",
+ "description": "Returns basic information of a document used for some db queries",
+ "required": ["documentId", "documentName", "owner"],
+ "properties": {
+ "branchedFromId": {
+ "type": ["string", "null"]
+ },
+ "branchedFromVersionId": {
+ "type": ["integer", "null"],
+ "format": "int64"
+ },
+ "deletedAt": {
+ "type": ["string", "null"],
+ "format": "date-time"
+ },
+ "documentFamilyId": {
+ "type": ["integer", "null"],
+ "format": "int64"
+ },
+ "documentId": {
+ "type": "string"
+ },
+ "documentName": {
+ "type": "string"
+ },
+ "fileType": {
+ "type": ["string", "null"]
+ },
+ "owner": {
+ "type": "string"
+ },
+ "projectId": {
+ "type": ["string", "null"]
+ }
+ }
+ },
+ "DocumentContent": {
+ "type": "object",
+ "description": "API-visible content lifecycle and location metadata.",
+ "required": ["state"],
+ "properties": {
+ "location": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/DocumentContentLocation",
+ "description": "The content location, when known."
+ }
+ ]
+ },
+ "state": {
+ "$ref": "#/components/schemas/DocumentContentState",
+ "description": "The current lifecycle state of the content."
+ }
+ }
+ },
+ "DocumentContentLocation": {
+ "type": "string",
+ "description": "Where document content is, or is expected to be, read from.",
+ "enum": [
+ "object_storage",
+ "sync_service",
+ "docx_bom_parts",
+ "converted_pdf",
+ "unknown"
+ ]
+ },
+ "DocumentContentState": {
+ "type": "string",
+ "description": "API-visible content lifecycle state derived from current document metadata.",
+ "enum": ["unknown", "pending", "ready"]
+ },
"DocumentFilters": {
"type": "object",
"description": "The document filters used to filter down what documents you search over.",
@@ -7910,6 +8109,25 @@
}
}
},
+ "DocumentMetadataWithContent": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/DocumentMetadata",
+ "description": "Legacy document metadata."
+ },
+ {
+ "type": "object",
+ "required": ["content"],
+ "properties": {
+ "content": {
+ "$ref": "#/components/schemas/DocumentContent",
+ "description": "Content lifecycle and location metadata."
+ }
+ }
+ }
+ ],
+ "description": "Full document metadata plus content lifecycle metadata."
+ },
"DocumentPermissionsToken": {
"type": "object",
"required": ["document_id", "access_level", "exp", "iss"],
@@ -8072,13 +8290,16 @@
},
"DocumentResponse": {
"type": "object",
+ "description": "Document response with content lifecycle metadata.",
"required": ["documentMetadata"],
"properties": {
"documentMetadata": {
- "$ref": "#/components/schemas/DocumentResponseMetadata"
+ "$ref": "#/components/schemas/DocumentResponseMetadataWithContent",
+ "description": "The document metadata."
},
"presignedUrl": {
- "type": ["string", "null"]
+ "type": ["string", "null"],
+ "description": "Presigned upload URL, when the caller still needs to upload bytes."
}
}
},
@@ -8163,6 +8384,25 @@
}
}
},
+ "DocumentResponseMetadataWithContent": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/DocumentResponseMetadata",
+ "description": "Legacy create/copy response metadata."
+ },
+ {
+ "type": "object",
+ "required": ["content"],
+ "properties": {
+ "content": {
+ "$ref": "#/components/schemas/DocumentContent",
+ "description": "Content lifecycle and location metadata."
+ }
+ }
+ }
+ ],
+ "description": "Create/copy response metadata plus content lifecycle metadata."
+ },
"DocumentStorageServiceApiVersion": {
"type": "string",
"enum": ["v1", "v2"]
@@ -9842,6 +10082,83 @@
}
]
},
+ "LocationResponseV3": {
+ "oneOf": [
+ {
+ "type": "object",
+ "description": "A single document-storage URL.",
+ "required": ["presignedUrl", "metadata", "content", "type"],
+ "properties": {
+ "content": {
+ "$ref": "#/components/schemas/DocumentContent",
+ "description": "Content lifecycle and location metadata."
+ },
+ "metadata": {
+ "$ref": "#/components/schemas/DocumentBasic",
+ "description": "Basic document metadata."
+ },
+ "presignedUrl": {
+ "type": "string",
+ "description": "Presigned URL."
+ },
+ "type": {
+ "type": "string",
+ "enum": ["presignedUrl"]
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "Multiple document-storage URLs, currently for DOCX BOM parts.",
+ "required": ["presignedUrls", "metadata", "content", "type"],
+ "properties": {
+ "content": {
+ "$ref": "#/components/schemas/DocumentContent",
+ "description": "Content lifecycle and location metadata."
+ },
+ "metadata": {
+ "$ref": "#/components/schemas/DocumentBasic",
+ "description": "Basic document metadata."
+ },
+ "presignedUrls": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/PresignedUrl"
+ },
+ "description": "Presigned URLs."
+ },
+ "type": {
+ "type": "string",
+ "enum": ["presignedUrls"]
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "Sync-service backed content.",
+ "required": ["metadata", "syncServiceMetadata", "content", "type"],
+ "properties": {
+ "content": {
+ "$ref": "#/components/schemas/DocumentContent",
+ "description": "Content lifecycle and location metadata."
+ },
+ "metadata": {
+ "$ref": "#/components/schemas/DocumentBasic",
+ "description": "Basic document metadata."
+ },
+ "syncServiceMetadata": {
+ "$ref": "#/components/schemas/SyncServiceDocumentMetadata",
+ "description": "Sync-service metadata."
+ },
+ "type": {
+ "type": "string",
+ "enum": ["syncServiceContent"]
+ }
+ }
+ }
+ ],
+ "description": "Location response with content lifecycle metadata."
+ },
"Mentions": {
"type": "object",
"required": ["users", "mentionId"],
@@ -12049,6 +12366,43 @@
}
}
},
+ "SyncServiceDocumentMetadata": {
+ "type": "object",
+ "description": "Sync-service document metadata exposed through document location responses.",
+ "required": ["id", "peers", "version_id"],
+ "properties": {
+ "id": {
+ "type": "string",
+ "description": "Sync-service document id."
+ },
+ "peers": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/SyncServicePeerWithUserId"
+ },
+ "description": "Known peers for the sync document."
+ },
+ "version_id": {
+ "type": "string",
+ "description": "Current sync-service version id."
+ }
+ }
+ },
+ "SyncServicePeerWithUserId": {
+ "type": "object",
+ "description": "Peer/user mapping returned by sync-service metadata.",
+ "required": ["peer_id", "user_id"],
+ "properties": {
+ "peer_id": {
+ "type": "string",
+ "description": "Sync-service peer id."
+ },
+ "user_id": {
+ "type": "string",
+ "description": "Macro user id."
+ }
+ }
+ },
"SyncServiceVersionID": {
"type": "object",
"required": ["peer", "counter"],
diff --git a/js/app/packages/service-clients/service-storage/service.ts b/js/app/packages/service-clients/service-storage/service.ts
index 4b252fa2a6..a3e24ef974 100644
--- a/js/app/packages/service-clients/service-storage/service.ts
+++ b/js/app/packages/service-clients/service-storage/service.ts
@@ -425,8 +425,7 @@ export const StorageService = new Svc('Document++ Storage Service API')
...schemas.copyDocumentQueryParams.shape,
...schemas.copyDocumentBody.shape,
},
- result:
- schemas.copyDocumentResponse.shape.data.shape.documentMetadata.shape,
+ result: schemas.copyDocumentResponse.shape.data.shape.documentMetadata,
modifies: true,
throws: withFetchErrors(),
})
@@ -583,12 +582,11 @@ export const StorageService = new Svc('Document++ Storage Service API')
schemas.getLocationHandlerParams.shape.document_id.describe(
`Document UUID`
),
- versionId:
- schemas.getLocationHandlerQueryParams.shape.document_version_id.describe(
- `A specific document version id to get the location for.`
- ),
+ versionId: schemas.getLocationHandlerQueryParams.shape.document_version_id
+ .optional()
+ .describe(`A specific document version id to get the location for.`),
},
- result: z.object({ data: schemas.getLocationHandlerResponse }).shape,
+ result: z.object({ data: z.any() }).shape,
throws: withFetchErrors(),
})
.fn('getDocumentPermissions', {
diff --git a/js/app/packages/service-clients/service-storage/util/presignedUrl.ts b/js/app/packages/service-clients/service-storage/util/presignedUrl.ts
index dd3750c76d..6c29257670 100644
--- a/js/app/packages/service-clients/service-storage/util/presignedUrl.ts
+++ b/js/app/packages/service-clients/service-storage/util/presignedUrl.ts
@@ -44,7 +44,7 @@ export const getPresignedUrl = async ({
}
const [, { data }] = maybeLocation;
- if (!('presignedUrl' in data)) {
+ if (data.type !== 'presignedUrl') {
throw new Error('presignedUrl not found in location data');
}
diff --git a/js/app/packages/service-clients/service-storage/util/upload.ts b/js/app/packages/service-clients/service-storage/util/upload.ts
index cc136dc8db..e7c995b951 100644
--- a/js/app/packages/service-clients/service-storage/util/upload.ts
+++ b/js/app/packages/service-clients/service-storage/util/upload.ts
@@ -5,6 +5,7 @@ import { PaywallKey, usePaywallState } from '@core/constant/PaywallState';
import { contentHash } from '@core/util/hash';
import { isErr, type ResultError } from '@core/util/maybeResult';
import { toaster } from '@kobalte/core/toast';
+import { waitForDocumentContentReady } from '@queries/storage/document-location';
import { waitBulkUploadStatus } from '@service-connection/bulkUpload';
import { storageServiceClient } from '@service-storage/client';
import { filenameWithoutExtension } from '@service-storage/util/filename';
@@ -198,15 +199,8 @@ export async function upload(
return handleUploadError(newfile[0], toastId);
}
- const [
- ,
- {
- metadata: { documentId },
- presignedUrl,
- contentType,
- fileType,
- },
- ] = newfile;
+ const [, { metadata, presignedUrl, contentType, fileType }] = newfile;
+ const { documentId, documentVersionId } = metadata;
const fallbackMime = fileType
? (FileTypeMap[fileType as keyof typeof FileTypeMap]?.mime as
@@ -227,7 +221,26 @@ export async function upload(
) {
console.error('failed to upload', documentId, 'removing...');
await storageServiceClient.deleteDocument({ documentId });
- return handleUploadError('Failed to upload docx file', toastId);
+ return handleUploadError('Failed to upload file', toastId);
+ }
+
+ // Document upload finalization is owned by the backend S3 ObjectCreated
+ // pipeline. The event finalizer marks object-storage documents uploaded and
+ // initializes markdown documents in sync-service.
+ if (fileType !== 'docx') {
+ const readyLocation = await waitForDocumentContentReady({
+ documentId,
+ versionId: documentVersionId,
+ }).catch((error) => {
+ console.warn('failed while waiting for document upload readiness', error);
+ return undefined;
+ });
+ if (readyLocation?.content.state !== 'ready') {
+ console.warn('document upload did not become ready before timeout', {
+ documentId,
+ fileType,
+ });
+ }
}
if (docxProcessingPromise) {
diff --git a/local_stack.just b/local_stack.just
index 9733edeab5..c92a234b3e 100644
--- a/local_stack.just
+++ b/local_stack.just
@@ -21,6 +21,7 @@ create_local_queues:
aws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name contacts-queue || true
aws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name convert-service-queue || true
aws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name delete-document-handler-queue || true
+ aws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name document-upload-finalizer-queue || true
aws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name document-text-extractor-lambda-queue || true
aws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name email-service-scheduled-queue || true
aws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name email-service-gmail-inbox-sync-queue || true
@@ -82,6 +83,35 @@ create_local_buckets:
done
@echo "S3 buckets created"
+# Wire document-storage ObjectCreated events to the local upload finalizer worker.
+configure_document_upload_finalizer_notifications:
+ #!/usr/bin/env bash
+ set -euo pipefail
+ queue_url="http://localhost:4566/000000000000/document-upload-finalizer-queue"
+ queue_arn="arn:aws:sqs:us-east-1:000000000000:document-upload-finalizer-queue"
+ policy=$(python3 - <<'PY'
+ import json
+ policy = {
+ "Version": "2012-10-17",
+ "Statement": [{
+ "Effect": "Allow",
+ "Principal": "*",
+ "Action": "sqs:SendMessage",
+ "Resource": "arn:aws:sqs:us-east-1:000000000000:document-upload-finalizer-queue",
+ "Condition": {"ArnEquals": {"aws:SourceArn": "arn:aws:s3:::doc-storage"}},
+ }],
+ }
+ print(json.dumps({"Policy": json.dumps(policy)}))
+ PY
+ )
+ aws --endpoint-url=http://localhost:4566 sqs set-queue-attributes \
+ --queue-url "$queue_url" \
+ --attributes "$policy" || true
+ aws --endpoint-url=http://localhost:4566 s3api put-bucket-notification-configuration \
+ --bucket doc-storage \
+ --notification-configuration "{\"QueueConfigurations\":[{\"Id\":\"document-upload-finalizer\",\"QueueArn\":\"$queue_arn\",\"Events\":[\"s3:ObjectCreated:*\"]}]}"
+ echo "Document upload finalizer S3 notification configured"
+
# Full LocalStack setup
setup_localstack:
just start_localstack
@@ -89,3 +119,4 @@ setup_localstack:
just create_local_queues
just create_local_tables
just create_local_buckets
+ just configure_document_upload_finalizer_notifications
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 92c3301812..fff04d64f7 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -3282,6 +3282,7 @@ dependencies = [
"jsonwebtoken 10.3.0 (git+https://github.com/whutchinson98/jsonwebtoken)",
"last_online_tracker",
"lazy_static",
+ "lexical_client",
"macro_auth",
"macro_aws_config",
"macro_axum_utils",
@@ -3301,6 +3302,7 @@ dependencies = [
"model_notifications",
"model_user",
"models_bulk_upload",
+ "models_dcs",
"models_opensearch",
"models_pagination",
"models_permissions",
@@ -3399,6 +3401,31 @@ dependencies = [
"uuid",
]
+[[package]]
+name = "document_upload_finalizer_handler"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "aws-sdk-s3",
+ "aws-sdk-sqs",
+ "aws_lambda_events",
+ "documents",
+ "lambda_runtime",
+ "lexical_client",
+ "macro_aws_config",
+ "macro_entrypoint",
+ "model",
+ "openssl",
+ "s3_key",
+ "serde",
+ "serde_json",
+ "sqlx",
+ "sync_service_client",
+ "tokio",
+ "tracing",
+ "urlencoding",
+]
+
[[package]]
name = "documents"
version = "0.1.0"
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index af08fbcb60..34b8611478 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -35,6 +35,7 @@ members = [
"document_storage_service_client",
"document_sub_type",
"document_text_extractor",
+ "document_upload_finalizer_handler",
"documents",
"docx_unzip_handler",
"dynamodb_client",
diff --git a/rust/cloud-storage/Dockerfile.dev b/rust/cloud-storage/Dockerfile.dev
index 661355219c..cdf8a59d12 100644
--- a/rust/cloud-storage/Dockerfile.dev
+++ b/rust/cloud-storage/Dockerfile.dev
@@ -20,6 +20,7 @@ RUN --mount=type=cache,target=/usr/local/cargo/registry,sharing=shared \
--bin contacts_service \
--bin document_cognition_service \
--bin document_storage_service \
+ --bin document_upload_finalizer_local_worker \
--bin email_service \
--bin notification_service \
--bin static_file_service \
@@ -31,6 +32,7 @@ RUN --mount=type=cache,target=/usr/local/cargo/registry,sharing=shared \
&& cp /app/target/debug/contacts_service /app/out/ \
&& cp /app/target/debug/document_cognition_service /app/out/ \
&& cp /app/target/debug/document_storage_service /app/out/ \
+ && cp /app/target/debug/document_upload_finalizer_local_worker /app/out/ \
&& cp /app/target/debug/email_service /app/out/ \
&& cp /app/target/debug/notification_service /app/out/ \
&& cp /app/target/debug/static_file_service /app/out/ \
diff --git a/rust/cloud-storage/ai_tools/src/build_context.rs b/rust/cloud-storage/ai_tools/src/build_context.rs
index abd48b34c2..569d49089c 100644
--- a/rust/cloud-storage/ai_tools/src/build_context.rs
+++ b/rust/cloud-storage/ai_tools/src/build_context.rs
@@ -206,6 +206,7 @@ pub async fn build_tool_service_context_from_env(
document_service,
(*entity_access_service).clone(),
lexical_client,
+ sync_client.as_ref().clone(),
);
let properties_service = properties::PropertiesServiceImpl::new(
diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
index f9e1da530c..7d6dfe2ebd 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
@@ -244,6 +244,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
document_service,
(*entity_access_service).clone(),
test_lexical_client,
+ sync_service_client.as_ref().clone(),
);
let search_service_client = Arc::new(search_service_client);
diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rs
index fe692418f9..a326c31fb5 100644
--- a/rust/cloud-storage/document_cognition_service/src/main.rs
+++ b/rust/cloud-storage/document_cognition_service/src/main.rs
@@ -262,6 +262,7 @@ async fn main() -> anyhow::Result<()> {
document_service,
(*entity_access_service).clone(),
lexical_client_for_tools,
+ sync_service_client.clone(),
);
tracing::info!("initialized document tool context");
diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.toml
index 84a3e0987a..b3cbcc46f9 100644
--- a/rust/cloud-storage/document_storage_service/Cargo.toml
+++ b/rust/cloud-storage/document_storage_service/Cargo.toml
@@ -69,6 +69,7 @@ http-body-util = { workspace = true }
jsonwebtoken = { workspace = true }
last_online_tracker = { path = "../last_online_tracker" }
lazy_static = { workspace = true }
+lexical_client = { path = "../lexical_client" }
macro_auth = { path = "../macro_auth" }
macro_aws_config = { path = "../macro_aws_config", features = ["s3"] }
macro_axum_utils = { path = "../macro_axum_utils" }
@@ -92,6 +93,7 @@ model-entity = { path = "../model-entity" }
model_notifications = { path = "../model_notifications" }
model_user = { path = "../model_user", features = ["axum"] }
models_bulk_upload = { path = "../models_bulk_upload" }
+models_dcs = { path = "../models_dcs" }
models_opensearch = { path = "../models_opensearch" }
models_pagination = { path = "../models_pagination", features = ["axum"] }
models_permissions = { path = "../models_permissions" }
diff --git a/rust/cloud-storage/document_storage_service/src/api/instructions/create_instructions.rs b/rust/cloud-storage/document_storage_service/src/api/instructions/create_instructions.rs
index 74afaef7d8..ddc8d9ed3b 100644
--- a/rust/cloud-storage/document_storage_service/src/api/instructions/create_instructions.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/instructions/create_instructions.rs
@@ -1,10 +1,17 @@
use crate::{
api::context::ApiContext, model::response::instructions::CreateInstructionsDocumentResponse,
};
-use axum::{Json, extract::State, http::StatusCode, response::IntoResponse};
-use macro_db_client::instructions::create::CreateInstructionsError;
-use model::response::{GenericErrorResponse, GenericResponse};
+use axum::{Json, extract::State};
+use documents_hex::domain::create::{NewDocumentMetadata, NewMarkdownTextDocument};
+use documents_hex::domain::models::DocumentError;
+use documents_hex::domain::ports::create::DocumentCreationService as _;
+use macro_db_client::instructions::create::{
+ CreateInstructionsError, insert_instructions_document,
+};
+use macro_db_client::instructions::get::get_instructions_document;
+use model::response::GenericErrorResponse;
use model_user::axum_extractor::MacroUserExtractor;
+use models_dcs::constants::INSTRUCTIONS_FILE_NAME;
/// Creates an instructions document for the current user
#[utoipa::path(
@@ -21,28 +28,71 @@ use model_user::axum_extractor::MacroUserExtractor;
pub async fn create_instructions_handler(
State(ctx): State<ApiContext>,
user_context: MacroUserExtractor,
-) -> impl IntoResponse {
- // Create the instructions document - database handles uniqueness constraint
- match macro_db_client::instructions::create::create_instructions_document(
- &ctx.db,
- user_context.macro_user_id.clone(),
- )
- .await
+) -> Result<Json<CreateInstructionsDocumentResponse>, DocumentError> {
+ let user_id = user_context.macro_user_id;
+
+ if get_instructions_document(&ctx.db, user_id.clone())
+ .await
+ .map_err(DocumentError::Internal)?
+ .is_some()
{
- Ok(document_id) => {
- let response_data = CreateInstructionsDocumentResponse { document_id };
- (StatusCode::OK, Json(response_data)).into_response()
+ return Err(DocumentError::Conflict(
+ "User already has an instructions document".to_string(),
+ ));
+ }
+
+ let created = ctx
+ .documents_state
+ .creator
+ .create_markdown_text(
+ user_id.clone(),
+ NewMarkdownTextDocument::empty_note(NewDocumentMetadata::new(INSTRUCTIONS_FILE_NAME)),
+ )
+ .await?;
+ let document_id = created.document_id().to_string();
+
+ match insert_instructions_document_with_stale_cleanup(&ctx, user_id, &document_id).await {
+ Ok(()) => Ok(Json(CreateInstructionsDocumentResponse { document_id })),
+ Err(error) => {
+ ctx.documents_state
+ .service
+ .cleanup_created_document(&document_id)
+ .await;
+ Err(error)
}
- Err(CreateInstructionsError::UserAlreadyHasInstructions) => GenericResponse::builder()
- .message("User already has an instructions document")
- .is_error(true)
- .send(StatusCode::CONFLICT),
- Err(CreateInstructionsError::DatabaseError(err)) => {
- tracing::error!(error=?err, user_id=%user_context.macro_user_id, "failed to create instructions document");
- GenericResponse::builder()
- .message("Failed to create instructions document")
- .is_error(true)
- .send(StatusCode::INTERNAL_SERVER_ERROR)
+ }
+}
+
+async fn insert_instructions_document_with_stale_cleanup(
+ ctx: &ApiContext,
+ user_id: macro_user_id::user_id::MacroUserIdStr<'static>,
+ document_id: &str,
+) -> Result<(), DocumentError> {
+ match insert_instructions_document(&ctx.db, user_id.clone(), document_id).await {
+ Ok(()) => Ok(()),
+ Err(CreateInstructionsError::UserAlreadyHasInstructions) => {
+ if get_instructions_document(&ctx.db, user_id.clone())
+ .await
+ .map_err(DocumentError::Internal)?
+ .is_some()
+ {
+ return Err(DocumentError::Conflict(
+ "User already has an instructions document".to_string(),
+ ));
+ }
+
+ sqlx::query!(
+ r#"DELETE FROM "InstructionsDocuments" WHERE "userId" = $1"#,
+ user_id.as_ref()
+ )
+ .execute(&ctx.db)
+ .await
+ .map_err(|error| DocumentError::Internal(error.into()))?;
+
+ insert_instructions_document(&ctx.db, user_id, document_id)
+ .await
+ .map_err(|error| DocumentError::Internal(anyhow::anyhow!(error)))
}
+ Err(error) => Err(DocumentError::Internal(anyhow::anyhow!(error))),
}
}
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 975c307646..1212aa5b90 100644
--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs
@@ -142,6 +142,7 @@ use utoipa::OpenApi;
documents_hex::inbound::axum_router::get_document_handler,
documents::get_document_version::handler,
documents_hex::inbound::axum_router::create_document_handler,
+ documents_hex::inbound::axum_router::create_markdown_handler,
documents_hex::inbound::axum_router::copy_document_handler,
documents::save_document::save_document_handler,
documents::pre_save::presave_document_handler,
@@ -270,6 +271,8 @@ use utoipa::OpenApi;
CreateDocumentRequest,
CreateDocumentResponse,
CreateDocumentResponseData, // Create document
+ documents_hex::domain::models::CreateMarkdownDocumentRequest,
+ documents_hex::domain::models::CreateMarkdownDocumentResponse,
documents_hex::domain::models::CreateTaskRequest,
documents_hex::domain::models::CreateTaskResponse,
documents_hex::domain::models::PropertyInput,
diff --git a/rust/cloud-storage/document_storage_service/src/bin/backfill_markdown_content_location.rs b/rust/cloud-storage/document_storage_service/src/bin/backfill_markdown_content_location.rs
new file mode 100644
index 0000000000..6ceb35215d
--- /dev/null
+++ b/rust/cloud-storage/document_storage_service/src/bin/backfill_markdown_content_location.rs
@@ -0,0 +1,206 @@
+//! Backfill markdown document content locations from sync-service state.
+//!
+//! This is intentionally a custom operational script, not a SQL migration:
+//! deciding whether an existing markdown document is sync-backed requires an
+//! external sync-service lookup.
+//!
+//! Dry-run is the default. Pass `--apply` to write updates.
+//!
+//! Required env vars:
+//! - `DATABASE_URL`
+//! - `SYNC_SERVICE_AUTH_KEY`
+//! - `SYNC_SERVICE_URL`
+//!
+//! Example dry-run:
+//! `cargo run -p document_storage_service --bin backfill_markdown_content_location`
+//!
+//! Example apply:
+//! `cargo run -p document_storage_service --bin backfill_markdown_content_location -- --apply`
+
+use std::env;
+
+use anyhow::Context;
+use sqlx::postgres::PgPoolOptions;
+use sync_service_client::SyncServiceClient;
+
+#[derive(Debug, Clone)]
+struct Args {
+ apply: bool,
+ batch_size: i64,
+ limit: Option<usize>,
+ start_after: Option<String>,
+}
+
+impl Args {
+ fn parse() -> anyhow::Result<Self> {
+ let mut apply = false;
+ let mut batch_size = 100_i64;
+ let mut limit = None;
+ let mut start_after = None;
+
+ let mut args = env::args().skip(1);
+ while let Some(arg) = args.next() {
+ match arg.as_str() {
+ "--apply" => apply = true,
+ "--batch-size" => {
+ let value = args.next().context("--batch-size requires a value")?;
+ batch_size = value
+ .parse::<i64>()
+ .context("--batch-size must be an integer")?;
+ anyhow::ensure!(batch_size > 0, "--batch-size must be positive");
+ }
+ "--limit" => {
+ let value = args.next().context("--limit requires a value")?;
+ limit = Some(
+ value
+ .parse::<usize>()
+ .context("--limit must be an integer")?,
+ );
+ }
+ "--start-after" => {
+ start_after = Some(args.next().context("--start-after requires a value")?);
+ }
+ "--help" | "-h" => {
+ println!(
+ "Usage: backfill_markdown_content_location [--apply] [--batch-size N] [--limit N] [--start-after DOCUMENT_ID]"
+ );
+ std::process::exit(0);
+ }
+ other => anyhow::bail!("unknown argument: {other}"),
+ }
+ }
+
+ Ok(Self {
+ apply,
+ batch_size,
+ limit,
+ start_after,
+ })
+ }
+}
+
+#[derive(Debug, Default)]
+struct Stats {
+ scanned: usize,
+ sync_exists: usize,
+ sync_missing: usize,
+ updated: usize,
+ sync_errors: usize,
+}
+
+#[tokio::main]
+async fn main() -> anyhow::Result<()> {
+ macro_entrypoint::MacroEntrypoint::default().init();
+
+ let args = Args::parse()?;
+ if !args.apply {
+ tracing::warn!("dry-run mode: pass --apply to update Document.contentLocation");
+ }
+
+ let database_url = env::var("DATABASE_URL").context("DATABASE_URL must be set")?;
+ let sync_service_auth_key =
+ env::var("SYNC_SERVICE_AUTH_KEY").context("SYNC_SERVICE_AUTH_KEY must be set")?;
+ let sync_service_url = env::var("SYNC_SERVICE_URL").context("SYNC_SERVICE_URL must be set")?;
+
+ let db = PgPoolOptions::new()
+ .max_connections(5)
+ .connect(&database_url)
+ .await
+ .context("failed to connect to postgres")?;
+ let sync_service_client = SyncServiceClient::new(sync_service_auth_key, sync_service_url);
+
+ let mut stats = Stats::default();
+ let mut last_id = args.start_after;
+
+ loop {
+ if args.limit.is_some_and(|limit| stats.scanned >= limit) {
+ break;
+ }
+
+ let remaining_limit = args
+ .limit
+ .map(|limit| limit.saturating_sub(stats.scanned) as i64)
+ .unwrap_or(args.batch_size);
+ let batch_limit = args.batch_size.min(remaining_limit);
+ if batch_limit == 0 {
+ break;
+ }
+
+ let rows = sqlx::query_scalar::<_, String>(
+ r#"
+ SELECT id
+ FROM "Document"
+ WHERE "fileType" = 'md'
+ AND uploaded = true
+ AND "contentState" = 'ready'
+ AND "contentLocation" IS DISTINCT FROM 'sync_service'
+ AND ($1::text IS NULL OR id > $1)
+ ORDER BY id
+ LIMIT $2
+ "#,
+ )
+ .bind(last_id.as_deref())
+ .bind(batch_limit)
+ .fetch_all(&db)
+ .await
+ .context("failed to fetch markdown document batch")?;
+
+ if rows.is_empty() {
+ break;
+ }
+
+ for document_id in rows {
+ last_id = Some(document_id.clone());
+ stats.scanned += 1;
+
+ match sync_service_client.exists(&document_id).await {
+ Ok(true) => {
+ stats.sync_exists += 1;
+ tracing::info!(%document_id, "markdown document exists in sync-service");
+
+ if args.apply {
+ let result = sqlx::query(
+ r#"
+ UPDATE "Document"
+ SET "contentState" = 'ready',
+ "contentLocation" = 'sync_service',
+ "updatedAt" = NOW()
+ WHERE id = $1
+ "#,
+ )
+ .bind(&document_id)
+ .execute(&db)
+ .await
+ .with_context(|| {
+ format!("failed to update content location for {document_id}")
+ })?;
+
+ if result.rows_affected() > 0 {
+ stats.updated += 1;
+ }
+ }
+ }
+ Ok(false) => {
+ stats.sync_missing += 1;
+ tracing::info!(%document_id, "markdown document does not exist in sync-service; leaving location unchanged");
+ }
+ Err(error) => {
+ stats.sync_errors += 1;
+ tracing::warn!(%document_id, error=?error, "failed to query sync-service; leaving location unchanged");
+ }
+ }
+ }
+ }
+
+ tracing::info!(
+ scanned = stats.scanned,
+ sync_exists = stats.sync_exists,
+ sync_missing = stats.sync_missing,
+ updated = stats.updated,
+ sync_errors = stats.sync_errors,
+ apply = args.apply,
+ "markdown content-location backfill complete"
+ );
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/document_storage_service/src/config.rs b/rust/cloud-storage/document_storage_service/src/config.rs
index bed87e1be9..805849dedb 100644
--- a/rust/cloud-storage/document_storage_service/src/config.rs
+++ b/rust/cloud-storage/document_storage_service/src/config.rs
@@ -53,6 +53,7 @@ env_var! {
pub UploadStagingBucket,
pub SyncServiceUrl,
pub SyncServiceAuthKey,
+ pub LexicalServiceUrl,
pub AuthenticationServiceUrl,
pub AuthenticationServiceSecretKey,
pub OpensearchUrl,
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index 1753edc420..2c6f98a5d0 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -52,6 +52,7 @@ use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::F
use github::domain::service::{GithubSyncConfig, GithubSyncServiceImpl};
use github::outbound::github_sync_client::GithubSyncClientImpl;
use github::outbound::pg_github_sync_repo::PgGithubSyncRepo;
+use lexical_client::LexicalClient;
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_entrypoint::MacroEntrypoint;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
@@ -207,10 +208,15 @@ async fn main() -> anyhow::Result<()> {
.to_string(),
};
- let sync_service_client = SyncServiceClient::new(
+ let sync_service_client = Arc::new(SyncServiceClient::new(
sync_service_auth_key,
config.vars.sync_service_url.as_ref().to_string(),
- );
+ ));
+
+ let lexical_client = Arc::new(LexicalClient::new(
+ internal_api_secret.as_ref().to_string(),
+ config.vars.lexical_service_url.as_ref().to_string(),
+ ));
let jwt_validation_args =
JwtValidationArgs::new_with_secret_manager(config.environment, &secretsmanager_client)
@@ -328,6 +334,11 @@ async fn main() -> anyhow::Result<()> {
config.vars.document_storage_bucket.as_ref(),
config.vars.docx_document_upload_bucket.as_ref(),
);
+ let markdown_initializer =
+ documents_hex::outbound::markdown_init::LexicalSyncMarkdownInitializer::new(
+ lexical_client.as_ref().clone(),
+ sync_service_client.as_ref().clone(),
+ );
let connection_gateway = Arc::new(ConnectionGatewayImpl::new(conn_gateway_client.clone()));
@@ -342,7 +353,7 @@ async fn main() -> anyhow::Result<()> {
let document_service = Arc::new(DocumentServiceImpl::new(
document_repo,
cloudfront_config,
- sync_service_client.clone(),
+ sync_service_client.as_ref().clone(),
s3_upload_adapter,
TaskPropertiesAdapter {
system_properties: system_properties_service.clone(),
@@ -542,7 +553,7 @@ async fn main() -> anyhow::Result<()> {
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),
+ sync_service_client: sync_service_client.clone(),
system_properties_service: system_properties_service.clone(),
properties_service: properties_service.clone(),
opensearch_client: Arc::new(opensearch_client),
@@ -555,9 +566,14 @@ async fn main() -> anyhow::Result<()> {
permissions_token_secret: comms_permissions_token_secret,
entity_access_service: entity_access_service.clone(),
documents_state: DocumentRouterState {
- service: document_service,
+ service: document_service.clone(),
access_service: entity_access_service.clone(),
pool: db.clone(),
+ creator: documents_hex::domain::create::DocumentCreator::new(
+ document_service,
+ markdown_initializer,
+ documents_hex::outbound::document_bytes_upload::ReqwestDocumentBytesUploader::default(),
+ ),
},
channels_state: ChannelsRouterState::new(
ChannelMessagesServiceImpl::new(PgChannelMessagesRepo::new(db.clone())),
diff --git a/rust/cloud-storage/document_storage_service/src/service/s3/delete.rs b/rust/cloud-storage/document_storage_service/src/service/s3/delete.rs
index 1db847a95e..9e00b7845a 100644
--- a/rust/cloud-storage/document_storage_service/src/service/s3/delete.rs
+++ b/rust/cloud-storage/document_storage_service/src/service/s3/delete.rs
@@ -84,8 +84,8 @@ mod tests {
.with(eq("user_id"), eq("document_id"))
.return_once(|_, _| Ok(()));
- let result = mock.delete_document(&"user_id", &"document_id").await;
+ let result = mock.delete_document("user_id", "document_id").await;
- assert_eq!(result.is_ok(), true);
+ assert!(result.is_ok());
}
}
diff --git a/rust/cloud-storage/document_storage_service/src/service/s3/put_presigned_url.rs b/rust/cloud-storage/document_storage_service/src/service/s3/put_presigned_url.rs
index fe9a11d066..aa66b9b9b2 100644
--- a/rust/cloud-storage/document_storage_service/src/service/s3/put_presigned_url.rs
+++ b/rust/cloud-storage/document_storage_service/src/service/s3/put_presigned_url.rs
@@ -39,5 +39,5 @@ pub(in crate::service::s3) async fn put_presigned_url(
.presigned(PresigningConfig::expires_in(expiry_duration)?)
.await?;
- Ok(presigned_url.uri().to_string())
+ Ok(macro_aws_config::transform_aws_url(presigned_url.uri()))
}
diff --git a/rust/cloud-storage/document_upload_finalizer_handler/Cargo.toml b/rust/cloud-storage/document_upload_finalizer_handler/Cargo.toml
new file mode 100644
index 0000000000..01dab37ea0
--- /dev/null
+++ b/rust/cloud-storage/document_upload_finalizer_handler/Cargo.toml
@@ -0,0 +1,37 @@
+[package]
+edition = "2024"
+name = "document_upload_finalizer_handler"
+publish = false
+version = "0.1.0"
+
+[dependencies]
+anyhow = { workspace = true }
+aws_lambda_events = { workspace = true, features = ["eventbridge"] }
+aws-sdk-s3 = { workspace = true }
+aws-sdk-sqs = { workspace = true }
+documents = { path = "../documents", default-features = false, features = [
+ "markdown_init",
+ "outbound",
+ "ports",
+] }
+lambda_runtime = { workspace = true }
+lexical_client = { path = "../lexical_client" }
+macro_aws_config = { path = "../macro_aws_config", features = ["s3"] }
+macro_entrypoint = { path = "../macro_entrypoint" }
+model = { path = "../model" }
+openssl = { workspace = true }
+s3_key = { path = "../s3_key" }
+serde = { workspace = true }
+serde_json = { workspace = true }
+sqlx = { workspace = true, features = ["postgres", "runtime-tokio"] }
+sync_service_client = { path = "../sync_service_client" }
+tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
+tracing = { workspace = true }
+urlencoding = { workspace = true }
+
+[[bin]]
+name = "document_upload_finalizer_local_worker"
+path = "src/bin/local_worker.rs"
+
+[package.metadata.cargo-machete]
+ignored = ["openssl"]
diff --git a/rust/cloud-storage/document_upload_finalizer_handler/justfile b/rust/cloud-storage/document_upload_finalizer_handler/justfile
new file mode 100644
index 0000000000..8e00362381
--- /dev/null
+++ b/rust/cloud-storage/document_upload_finalizer_handler/justfile
@@ -0,0 +1,7 @@
+lambda_name := file_name(justfile_directory())
+
+test:
+ cargo test --all-features
+
+build compiler="":
+ SQLX_OFFLINE=true cargo lambda build {{ if compiler == "" { "" } else { "--compiler " + compiler } }} --release --bin {{lambda_name}} --output-format zip
diff --git a/rust/cloud-storage/document_upload_finalizer_handler/src/app.rs b/rust/cloud-storage/document_upload_finalizer_handler/src/app.rs
new file mode 100644
index 0000000000..662eca6c6c
--- /dev/null
+++ b/rust/cloud-storage/document_upload_finalizer_handler/src/app.rs
@@ -0,0 +1,111 @@
+use documents::domain::ports::markdown::MarkdownInitializationPort;
+use documents::domain::upload_finalize::{UploadFinalizeDocumentPort, UploadedDocumentFinalizer};
+use model::document::FileType;
+use s3_key::DocumentKey;
+
+use crate::ports::{DocumentObjectReader, DocumentUploadMetadataPort};
+
+/// Storage object-created event normalized at the inbound adapter boundary.
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub struct ObjectCreated {
+ /// S3 bucket name.
+ pub bucket: String,
+ /// S3 object key.
+ pub key: String,
+}
+
+/// Application use case for finalizing document uploads from object-created events.
+pub struct DocumentUploadFinalizer<P, O> {
+ document_port: P,
+ object_reader: O,
+}
+
+impl<P, O> DocumentUploadFinalizer<P, O> {
+ /// Construct the upload finalization use case.
+ pub fn new(document_port: P, object_reader: O) -> Self {
+ Self {
+ document_port,
+ object_reader,
+ }
+ }
+}
+
+impl<P, O> DocumentUploadFinalizer<P, O>
+where
+ P: DocumentUploadMetadataPort + UploadFinalizeDocumentPort,
+ O: DocumentObjectReader,
+{
+ /// Handle one object-created event.
+ #[tracing::instrument(skip(self, markdown_initializer), err)]
+ pub async fn handle_object_created<M>(
+ &self,
+ event: ObjectCreated,
+ markdown_initializer: &M,
+ ) -> Result<(), anyhow::Error>
+ where
+ M: MarkdownInitializationPort,
+ {
+ let document_key = match DocumentKey::from_s3_key(&event.key) {
+ Ok(document_key) => document_key,
+ Err(error) => {
+ tracing::warn!(key=%event.key, error=?error, "skipping unparseable document storage key");
+ return Ok(());
+ }
+ };
+
+ let is_finalizable_key = matches!(
+ document_key,
+ DocumentKey::Versioned { .. } | DocumentKey::ConvertedPdf { .. }
+ );
+ if !is_finalizable_key {
+ tracing::trace!(key=%event.key, ?document_key, "skipping non-finalizable document storage key");
+ return Ok(());
+ }
+
+ let document_id = document_key.document_id().ok_or_else(|| {
+ anyhow::anyhow!(
+ "finalizable document key did not include a document id: {}",
+ event.key
+ )
+ })?;
+
+ let Some(document_context) = self.document_port.get_basic_document(document_id).await?
+ else {
+ tracing::warn!(%document_id, key=%event.key, "document storage object exists but document metadata does not");
+ return Ok(());
+ };
+
+ let markdown = if matches!(document_context.try_file_type(), Some(FileType::Md)) {
+ Some(
+ self.object_reader
+ .read_utf8_object(&event.bucket, &event.key)
+ .await?,
+ )
+ } else {
+ None
+ };
+
+ let finalizer = UploadedDocumentFinalizer::new(&self.document_port, markdown_initializer);
+ let result = match document_key {
+ DocumentKey::ConvertedPdf { .. } => {
+ finalizer
+ .finalize_converted_pdf_document(&document_context)
+ .await
+ }
+ DocumentKey::Versioned { .. } => {
+ finalizer
+ .finalize_uploaded_document(&document_context, markdown.as_deref())
+ .await
+ }
+ _ => unreachable!("non-finalizable keys returned earlier"),
+ };
+
+ match result {
+ Ok(()) => {
+ tracing::info!(%document_id, key=%event.key, "finalized document upload");
+ Ok(())
+ }
+ Err(error) => Err(anyhow::anyhow!(error)),
+ }
+ }
+}
diff --git a/rust/cloud-storage/document_upload_finalizer_handler/src/bin/local_worker.rs b/rust/cloud-storage/document_upload_finalizer_handler/src/bin/local_worker.rs
new file mode 100644
index 0000000000..9548b826b5
--- /dev/null
+++ b/rust/cloud-storage/document_upload_finalizer_handler/src/bin/local_worker.rs
@@ -0,0 +1,13 @@
+use std::sync::Arc;
+
+use document_upload_finalizer_handler::{AppContext, inbound::local_sqs::run_local_sqs_worker};
+use lambda_runtime::tracing;
+
+#[tokio::main]
+async fn main() -> Result<(), anyhow::Error> {
+ macro_entrypoint::MacroEntrypoint::default().init();
+ tracing::trace!("initiating local document upload finalizer worker");
+
+ let context = Arc::new(AppContext::from_env().await?);
+ run_local_sqs_worker(context).await
+}
diff --git a/rust/cloud-storage/document_upload_finalizer_handler/src/inbound/eventbridge.rs b/rust/cloud-storage/document_upload_finalizer_handler/src/inbound/eventbridge.rs
new file mode 100644
index 0000000000..be87808d3d
--- /dev/null
+++ b/rust/cloud-storage/document_upload_finalizer_handler/src/inbound/eventbridge.rs
@@ -0,0 +1,22 @@
+use aws_lambda_events::event::eventbridge::EventBridgeEvent;
+
+use crate::app::ObjectCreated;
+
+/// Convert an EventBridge S3 object-created payload to the domain event.
+pub fn object_created_from_event(event: &EventBridgeEvent) -> Option<ObjectCreated> {
+ let detail = &event.detail;
+
+ let bucket = detail
+ .get("bucket")
+ .and_then(|bucket| bucket.get("name"))
+ .and_then(|name| name.as_str())?;
+ let key = detail
+ .get("object")
+ .and_then(|object| object.get("key"))
+ .and_then(|key| key.as_str())?;
+
+ Some(ObjectCreated {
+ bucket: bucket.to_string(),
+ key: key.to_string(),
+ })
+}
diff --git a/rust/cloud-storage/document_upload_finalizer_handler/src/inbound/local_sqs.rs b/rust/cloud-storage/document_upload_finalizer_handler/src/inbound/local_sqs.rs
new file mode 100644
index 0000000000..682da31a75
--- /dev/null
+++ b/rust/cloud-storage/document_upload_finalizer_handler/src/inbound/local_sqs.rs
@@ -0,0 +1,110 @@
+use std::sync::Arc;
+use std::time::Duration;
+
+use anyhow::Context as _;
+use aws_sdk_sqs::types::Message;
+use lambda_runtime::tracing;
+
+use crate::AppContext;
+use crate::inbound::s3_notification::object_created_events_from_body;
+
+const LOCALSTACK_ACCOUNT_ID: &str = "000000000000";
+const QUEUE_NAME: &str = "document-upload-finalizer-queue";
+
+/// Run the LocalStack SQS polling adapter.
+pub async fn run_local_sqs_worker(context: Arc<AppContext>) -> Result<(), anyhow::Error> {
+ let queue_url = std::env::var("DOCUMENT_UPLOAD_FINALIZER_QUEUE_URL")
+ .unwrap_or_else(|_| default_queue_url());
+ let sqs_client = aws_sdk_sqs::Client::new(&macro_aws_config::get_macro_aws_config().await);
+
+ poll_forever(context, sqs_client, queue_url).await
+}
+
+fn default_queue_url() -> String {
+ let local_aws_url =
+ std::env::var("LOCAL_AWS_URL").unwrap_or_else(|_| "http://localstack:4566".to_string());
+ format!(
+ "{}/{LOCALSTACK_ACCOUNT_ID}/{QUEUE_NAME}",
+ local_aws_url.trim_end_matches('/')
+ )
+}
+
+async fn poll_forever(
+ context: Arc<AppContext>,
+ sqs_client: aws_sdk_sqs::Client,
+ queue_url: String,
+) -> Result<(), anyhow::Error> {
+ loop {
+ let response = match sqs_client
+ .receive_message()
+ .queue_url(&queue_url)
+ .wait_time_seconds(20)
+ .max_number_of_messages(10)
+ .send()
+ .await
+ {
+ Ok(response) => response,
+ Err(error) => {
+ tracing::warn!(error=?error, %queue_url, "failed to poll document upload finalizer queue");
+ tokio::time::sleep(Duration::from_secs(5)).await;
+ continue;
+ }
+ };
+
+ for message in response.messages.unwrap_or_default() {
+ let processed = handle_message(context.clone(), &message).await;
+
+ match processed {
+ Ok(()) => delete_message(&sqs_client, &queue_url, &message).await,
+ Err(error) => {
+ tracing::error!(error=?error, "failed to process document upload finalizer message; leaving it on the queue");
+ }
+ }
+ }
+ }
+}
+
+async fn delete_message(sqs_client: &aws_sdk_sqs::Client, queue_url: &str, message: &Message) {
+ let Some(receipt_handle) = &message.receipt_handle else {
+ tracing::warn!(?message, "processed SQS message had no receipt handle");
+ return;
+ };
+
+ if let Err(error) = sqs_client
+ .delete_message()
+ .queue_url(queue_url)
+ .receipt_handle(receipt_handle)
+ .send()
+ .await
+ {
+ tracing::error!(error=?error, "failed to delete processed document upload finalizer message");
+ }
+}
+
+async fn handle_message(context: Arc<AppContext>, message: &Message) -> Result<(), anyhow::Error> {
+ let Some(body) = &message.body else {
+ tracing::warn!(
+ ?message,
+ "document upload finalizer SQS message had no body"
+ );
+ return Ok(());
+ };
+
+ let events = match object_created_events_from_body(body) {
+ Ok(events) => events,
+ Err(error) => {
+ tracing::warn!(error=?error, body, "discarding malformed document upload finalizer SQS message");
+ return Ok(());
+ }
+ };
+
+ for event in events {
+ let key = event.key.clone();
+ context
+ .handle_object_created(event)
+ .await
+ .with_context(|| format!("failed to finalize upload for s3 key {key}"))?;
+ }
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/document_upload_finalizer_handler/src/inbound/mod.rs b/rust/cloud-storage/document_upload_finalizer_handler/src/inbound/mod.rs
new file mode 100644
index 0000000000..3e0b0d5ca6
--- /dev/null
+++ b/rust/cloud-storage/document_upload_finalizer_handler/src/inbound/mod.rs
@@ -0,0 +1,5 @@
+//! Inbound transport adapters for upload finalization events.
+
+pub mod eventbridge;
+pub mod local_sqs;
+pub mod s3_notification;
diff --git a/rust/cloud-storage/document_upload_finalizer_handler/src/inbound/s3_notification.rs b/rust/cloud-storage/document_upload_finalizer_handler/src/inbound/s3_notification.rs
new file mode 100644
index 0000000000..bbe1732d01
--- /dev/null
+++ b/rust/cloud-storage/document_upload_finalizer_handler/src/inbound/s3_notification.rs
@@ -0,0 +1,63 @@
+use serde::Deserialize;
+
+use crate::app::ObjectCreated;
+
+/// Parse S3 event-notification JSON into normalized object-created events.
+pub fn object_created_events_from_body(
+ body: &str,
+) -> Result<Vec<ObjectCreated>, serde_json::Error> {
+ let event = serde_json::from_str::<S3EventNotification>(body)?;
+
+ Ok(event
+ .records
+ .into_iter()
+ .filter(|record| is_object_created_event(&record.event_name))
+ .map(|record| ObjectCreated {
+ bucket: record.s3.bucket.name,
+ key: decode_s3_event_key(&record.s3.object.key),
+ })
+ .collect())
+}
+
+fn is_object_created_event(event_name: &str) -> bool {
+ event_name.starts_with("ObjectCreated:") || event_name.starts_with("s3:ObjectCreated:")
+}
+
+fn decode_s3_event_key(key: &str) -> String {
+ let form_encoded = key.replace('+', " ");
+ urlencoding::decode(&form_encoded)
+ .map(|decoded| decoded.into_owned())
+ .unwrap_or_else(|error| {
+ tracing::warn!(%key, error=?error, "failed to URL-decode S3 event key; using raw key");
+ key.to_string()
+ })
+}
+
+#[derive(Deserialize)]
+struct S3EventNotification {
+ #[serde(rename = "Records")]
+ records: Vec<S3EventRecord>,
+}
+
+#[derive(Deserialize)]
+struct S3EventRecord {
+ #[serde(rename = "eventName")]
+ event_name: String,
+ s3: S3Entity,
+}
+
+#[derive(Deserialize)]
+struct S3Entity {
+ bucket: S3Bucket,
+ object: S3Object,
+}
+
+#[derive(Deserialize)]
+struct S3Bucket {
+ name: String,
+}
+
+#[derive(Deserialize)]
+struct S3Object {
+ key: String,
+}
diff --git a/rust/cloud-storage/document_upload_finalizer_handler/src/lib.rs b/rust/cloud-storage/document_upload_finalizer_handler/src/lib.rs
new file mode 100644
index 0000000000..a4f27ff9a9
--- /dev/null
+++ b/rust/cloud-storage/document_upload_finalizer_handler/src/lib.rs
@@ -0,0 +1,13 @@
+//! Document upload finalizer application.
+//!
+//! Production invokes this through an EventBridge Lambda adapter. Local development
+//! uses a LocalStack SQS polling adapter. Both adapters normalize transport events
+//! into [`app::ObjectCreated`] and call the same use case.
+
+pub mod app;
+pub mod inbound;
+pub mod outbound;
+pub mod ports;
+pub mod runtime;
+
+pub use runtime::AppContext;
diff --git a/rust/cloud-storage/document_upload_finalizer_handler/src/main.rs b/rust/cloud-storage/document_upload_finalizer_handler/src/main.rs
new file mode 100644
index 0000000000..d263948610
--- /dev/null
+++ b/rust/cloud-storage/document_upload_finalizer_handler/src/main.rs
@@ -0,0 +1,47 @@
+#![recursion_limit = "256"]
+
+use std::sync::Arc;
+
+use aws_lambda_events::event::eventbridge::EventBridgeEvent;
+use document_upload_finalizer_handler::{
+ AppContext, inbound::eventbridge::object_created_from_event,
+};
+use lambda_runtime::{Error, LambdaEvent, run, service_fn, tracing};
+
+#[tokio::main]
+async fn main() -> Result<(), Error> {
+ MacroEntrypointExt::init();
+
+ let context = Arc::new(AppContext::from_env().await?);
+
+ let func = service_fn(move |event: LambdaEvent<EventBridgeEvent>| {
+ let context = context.clone();
+ async move { handler(context, event).await }
+ });
+
+ run(func).await
+}
+
+#[tracing::instrument(skip(context, event), err)]
+async fn handler(
+ context: Arc<AppContext>,
+ event: LambdaEvent<EventBridgeEvent>,
+) -> Result<(), Error> {
+ let Some(object_created) = object_created_from_event(&event.payload) else {
+ tracing::warn!(detail=?event.payload.detail, "object-created event did not include bucket/key");
+ return Ok(());
+ };
+
+ context.handle_object_created(object_created).await?;
+
+ Ok(())
+}
+
+struct MacroEntrypointExt;
+
+impl MacroEntrypointExt {
+ fn init() {
+ macro_entrypoint::MacroEntrypoint::default().init();
+ tracing::trace!("initiating document upload finalizer lambda");
+ }
+}
diff --git a/rust/cloud-storage/document_upload_finalizer_handler/src/outbound.rs b/rust/cloud-storage/document_upload_finalizer_handler/src/outbound.rs
new file mode 100644
index 0000000000..9102b17c24
--- /dev/null
+++ b/rust/cloud-storage/document_upload_finalizer_handler/src/outbound.rs
@@ -0,0 +1,99 @@
+use anyhow::Context as _;
+use documents::domain::content::DocumentContent;
+use documents::domain::models::DocumentError;
+use documents::domain::upload_finalize::{RepoUploadFinalizePort, UploadFinalizeDocumentPort};
+use documents::outbound::pg_document_repo::PgDocumentRepo;
+use model::document::DocumentBasic;
+
+use crate::ports::{DocumentObjectReader, DocumentUploadMetadataPort};
+
+/// S3-backed object reader for uploaded document bytes.
+#[derive(Clone)]
+pub struct S3DocumentObjectReader {
+ s3_client: aws_sdk_s3::Client,
+}
+
+impl S3DocumentObjectReader {
+ /// Construct an S3 object reader.
+ pub fn new(s3_client: aws_sdk_s3::Client) -> Self {
+ Self { s3_client }
+ }
+}
+
+impl DocumentObjectReader for S3DocumentObjectReader {
+ async fn read_utf8_object(&self, bucket: &str, key: &str) -> Result<String, anyhow::Error> {
+ let response = self
+ .s3_client
+ .get_object()
+ .bucket(bucket)
+ .key(key)
+ .send()
+ .await
+ .with_context(|| format!("failed to read upload from s3://{bucket}/{key}"))?;
+
+ let bytes = response
+ .body
+ .collect()
+ .await
+ .context("failed to collect object body")?
+ .into_bytes();
+
+ String::from_utf8(bytes.to_vec())
+ .with_context(|| format!("uploaded object is not valid utf-8: s3://{bucket}/{key}"))
+ }
+}
+
+/// Postgres-backed document port for upload finalization.
+#[derive(Clone)]
+pub struct PgDocumentUploadPort {
+ repo: PgDocumentRepo,
+}
+
+impl PgDocumentUploadPort {
+ /// Construct a Postgres document upload port.
+ pub fn new(repo: PgDocumentRepo) -> Self {
+ Self { repo }
+ }
+}
+
+impl DocumentUploadMetadataPort for PgDocumentUploadPort {
+ async fn get_basic_document(
+ &self,
+ document_id: &str,
+ ) -> Result<Option<DocumentBasic>, DocumentError> {
+ match documents::domain::ports::DocumentRepo::get_basic_document(&self.repo, document_id)
+ .await
+ {
+ Ok(document) => Ok(Some(document)),
+ Err(sqlx::Error::RowNotFound) => Ok(None),
+ Err(error) => Err(DocumentError::Internal(error.into())),
+ }
+ }
+}
+
+impl UploadFinalizeDocumentPort for PgDocumentUploadPort {
+ async fn get_document_content(
+ &self,
+ document_context: &DocumentBasic,
+ ) -> Result<DocumentContent, DocumentError> {
+ RepoUploadFinalizePort::new(self.repo.clone())
+ .get_document_content(document_context)
+ .await
+ }
+
+ async fn mark_document_uploaded(&self, document_id: &str) -> Result<(), DocumentError> {
+ RepoUploadFinalizePort::new(self.repo.clone())
+ .mark_document_uploaded(document_id)
+ .await
+ }
+
+ async fn set_document_content(
+ &self,
+ document_id: &str,
+ content: DocumentContent,
+ ) -> Result<(), DocumentError> {
+ RepoUploadFinalizePort::new(self.repo.clone())
+ .set_document_content(document_id, content)
+ .await
+ }
+}
diff --git a/rust/cloud-storage/document_upload_finalizer_handler/src/ports.rs b/rust/cloud-storage/document_upload_finalizer_handler/src/ports.rs
new file mode 100644
index 0000000000..c90e393e69
--- /dev/null
+++ b/rust/cloud-storage/document_upload_finalizer_handler/src/ports.rs
@@ -0,0 +1,23 @@
+use std::future::Future;
+
+use documents::domain::models::DocumentError;
+use model::document::DocumentBasic;
+
+/// Document metadata lookup needed by the upload finalization use case.
+pub trait DocumentUploadMetadataPort: Send + Sync {
+ /// Fetch the basic document context for a document id.
+ fn get_basic_document(
+ &self,
+ document_id: &str,
+ ) -> impl Future<Output = Result<Option<DocumentBasic>, DocumentError>> + Send;
+}
+
+/// Object storage read operations needed by the upload finalization use case.
+pub trait DocumentObjectReader: Send + Sync {
+ /// Read an object as UTF-8 text.
+ fn read_utf8_object(
+ &self,
+ bucket: &str,
+ key: &str,
+ ) -> impl Future<Output = Result<String, anyhow::Error>> + Send;
+}
diff --git a/rust/cloud-storage/document_upload_finalizer_handler/src/runtime.rs b/rust/cloud-storage/document_upload_finalizer_handler/src/runtime.rs
new file mode 100644
index 0000000000..e06f03780f
--- /dev/null
+++ b/rust/cloud-storage/document_upload_finalizer_handler/src/runtime.rs
@@ -0,0 +1,61 @@
+use anyhow::Context as _;
+use documents::outbound::markdown_init::LexicalSyncMarkdownInitializer;
+use documents::outbound::pg_document_repo::PgDocumentRepo;
+use lexical_client::LexicalClient;
+use sqlx::postgres::PgPoolOptions;
+use sync_service_client::SyncServiceClient;
+
+use crate::app::{DocumentUploadFinalizer, ObjectCreated};
+use crate::outbound::{PgDocumentUploadPort, S3DocumentObjectReader};
+
+/// Concrete app context used by Lambda and local worker entrypoints.
+pub struct AppContext {
+ finalizer: DocumentUploadFinalizer<PgDocumentUploadPort, S3DocumentObjectReader>,
+ lexical_client: LexicalClient,
+ sync_service_client: SyncServiceClient,
+}
+
+impl AppContext {
+ /// Build the shared finalizer context from environment variables.
+ pub async fn from_env() -> Result<Self, anyhow::Error> {
+ let database_url =
+ std::env::var("DATABASE_URL").context("DATABASE_URL must be provided")?;
+ let internal_api_secret = std::env::var("INTERNAL_API_SECRET_KEY")
+ .context("INTERNAL_API_SECRET_KEY must be provided")?;
+ let sync_service_auth_key = std::env::var("SYNC_SERVICE_AUTH_KEY")
+ .context("SYNC_SERVICE_AUTH_KEY must be provided")?;
+ let lexical_service_url =
+ std::env::var("LEXICAL_SERVICE_URL").context("LEXICAL_SERVICE_URL must be provided")?;
+ let sync_service_url =
+ std::env::var("SYNC_SERVICE_URL").context("SYNC_SERVICE_URL must be provided")?;
+
+ let db_pool = PgPoolOptions::new()
+ .max_connections(5)
+ .connect(&database_url)
+ .await
+ .context("failed to connect to postgres")?;
+
+ let repo = PgDocumentRepo::new(db_pool);
+ let document_port = PgDocumentUploadPort::new(repo);
+ let object_reader = S3DocumentObjectReader::new(macro_aws_config::s3_client().await);
+ let finalizer = DocumentUploadFinalizer::new(document_port, object_reader);
+
+ Ok(Self {
+ finalizer,
+ lexical_client: LexicalClient::new(internal_api_secret, lexical_service_url),
+ sync_service_client: SyncServiceClient::new(sync_service_auth_key, sync_service_url),
+ })
+ }
+
+ /// Handle one normalized object-created event.
+ pub async fn handle_object_created(&self, event: ObjectCreated) -> Result<(), anyhow::Error> {
+ let markdown_initializer = LexicalSyncMarkdownInitializer::new(
+ self.lexical_client.clone(),
+ self.sync_service_client.clone(),
+ );
+
+ self.finalizer
+ .handle_object_created(event, &markdown_initializer)
+ .await
+ }
+}
diff --git a/rust/cloud-storage/documents/Cargo.toml b/rust/cloud-storage/documents/Cargo.toml
index 3c192bab4d..032b903929 100644
--- a/rust/cloud-storage/documents/Cargo.toml
+++ b/rust/cloud-storage/documents/Cargo.toml
@@ -16,11 +16,10 @@ attachment = [
ai_tools = [
"dep:ai",
"dep:async-trait",
- "dep:lexical_client",
"dep:model_file_type",
- "dep:reqwest",
"dep:schemars",
"dep:sha2",
+ "document_create_adapters",
"outbound",
"ports",
]
@@ -32,8 +31,18 @@ axum = [
"dep:utoipa",
"entity_access/axum",
]
-default = ["ai_tools", "axum", "inbound", "outbound", "ports"]
-inbound = ["axum", "ports"]
+default = ["ai_tools", "axum", "inbound", "outbound", "ports", "service"]
+document_create = [
+ "dep:base64",
+ "dep:sha2",
+ "ports",
+]
+document_create_adapters = [
+ "dep:reqwest",
+ "document_create",
+ "markdown_init",
+]
+inbound = ["axum", "document_create_adapters", "ports"]
markdown_init = ["dep:lexical_client"]
outbound = [
"dep:aws-sdk-s3",
@@ -43,7 +52,8 @@ outbound = [
"dep:sqlx",
"ports",
]
-ports = ["dep:entity_access_management", "dep:tokio"]
+ports = ["dep:tokio"]
+service = ["dep:entity_access_management", "ports"]
[dependencies]
# Core
diff --git a/rust/cloud-storage/documents/examples/documents_toolset.rs b/rust/cloud-storage/documents/examples/documents_toolset.rs
index 6420af5169..49ef9bc2f2 100644
--- a/rust/cloud-storage/documents/examples/documents_toolset.rs
+++ b/rust/cloud-storage/documents/examples/documents_toolset.rs
@@ -184,17 +184,22 @@ async fn main() {
presigned_url_expiry_seconds: 840,
browser_cache_expiry_seconds: 900,
},
- SyncServiceClient::new(sync_service_auth_key.clone(), sync_service_url),
+ SyncServiceClient::new(sync_service_auth_key.clone(), sync_service_url.clone()),
s3_upload_adapter,
NoOpTaskProperties,
NoOpConnectionService,
NoOpEntityAccessManagementService,
);
- let lexical_client = LexicalClient::new(sync_service_auth_key, lexical_service_url);
+ let lexical_client = LexicalClient::new(sync_service_auth_key.clone(), lexical_service_url);
- let document_tool_context =
- DocumentToolContext::new(documents_service, entity_access_service, lexical_client);
+ let sync_service_client = SyncServiceClient::new(sync_service_auth_key, sync_service_url);
+ let document_tool_context = DocumentToolContext::new(
+ documents_service,
+ entity_access_service,
+ lexical_client,
+ sync_service_client,
+ );
let toolset = document_toolset();
diff --git a/rust/cloud-storage/documents/src/domain.rs b/rust/cloud-storage/documents/src/domain.rs
index 7fc88ab36f..adfc88193e 100644
--- a/rust/cloud-storage/documents/src/domain.rs
+++ b/rust/cloud-storage/documents/src/domain.rs
@@ -1,14 +1,19 @@
//! Domain layer: models, ports (trait interfaces), and service implementation.
pub mod branch_name;
+pub mod content;
-#[cfg(feature = "markdown_init")]
-pub mod markdown_init;
+#[cfg(feature = "document_create")]
+pub mod create;
+
+#[cfg(feature = "ports")]
+pub mod upload_finalize;
pub mod models;
+pub mod response;
#[cfg(feature = "ports")]
pub mod ports;
-#[cfg(feature = "ports")]
+#[cfg(feature = "service")]
pub mod service;
diff --git a/rust/cloud-storage/documents/src/domain/content.rs b/rust/cloud-storage/documents/src/domain/content.rs
new file mode 100644
index 0000000000..cf243614df
--- /dev/null
+++ b/rust/cloud-storage/documents/src/domain/content.rs
@@ -0,0 +1,212 @@
+//! Document content lifecycle API shapes and domain policy.
+
+use std::str::FromStr;
+
+use model::document::FileType;
+
+/// API-visible content lifecycle state derived from current document metadata.
+#[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug, Clone, Copy)]
+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]
+#[serde(rename_all = "snake_case")]
+pub enum DocumentContentState {
+ /// The service cannot determine the content lifecycle state from current metadata.
+ Unknown,
+ /// Metadata exists, but canonical content is not ready to consume yet.
+ Pending,
+ /// Content is finalized and should be readable from `location`.
+ Ready,
+}
+
+/// Where document content is, or is expected to be, read from.
+#[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug, Clone, Copy)]
+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]
+#[serde(rename_all = "snake_case")]
+pub enum DocumentContentLocation {
+ /// Content is stored as a document-storage object.
+ ObjectStorage,
+ /// Content is stored in sync-service.
+ SyncService,
+ /// DOCX content is stored as document-storage BOM parts.
+ DocxBomParts,
+ /// DOCX content is exposed through a converted PDF object in document storage.
+ ConvertedPdf,
+ /// Legacy metadata says content is uploaded, but not where the canonical
+ /// finalized content lives.
+ Unknown,
+}
+
+/// API-visible content lifecycle and location metadata.
+#[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug, Clone)]
+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct DocumentContent {
+ /// The current lifecycle state of the content.
+ pub state: DocumentContentState,
+ /// The content location, when known.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub location: Option<DocumentContentLocation>,
+}
+
+impl Default for DocumentContent {
+ fn default() -> Self {
+ Self::unknown()
+ }
+}
+
+impl DocumentContent {
+ /// The content state/location cannot be determined from current metadata.
+ pub fn unknown() -> Self {
+ Self {
+ state: DocumentContentState::Unknown,
+ location: None,
+ }
+ }
+
+ /// Metadata exists, but canonical content is not ready to consume yet.
+ pub fn pending() -> Self {
+ Self {
+ state: DocumentContentState::Pending,
+ location: None,
+ }
+ }
+
+ /// Metadata exists, content is not ready yet, and the expected canonical
+ /// location is known.
+ pub fn pending_at(location: DocumentContentLocation) -> Self {
+ Self {
+ state: DocumentContentState::Pending,
+ location: Some(location),
+ }
+ }
+
+ /// Content is finalized at a known location.
+ pub fn ready(location: DocumentContentLocation) -> Self {
+ Self {
+ state: DocumentContentState::Ready,
+ location: Some(location),
+ }
+ }
+
+ /// Derive the best content metadata available from the legacy
+ /// `Document.uploaded` boolean and file type.
+ pub fn from_legacy_uploaded(uploaded: bool, file_type: Option<FileType>) -> Self {
+ if !uploaded {
+ return Self::pending();
+ }
+
+ let location = match file_type {
+ Some(FileType::Docx) => DocumentContentLocation::ConvertedPdf,
+ // Historical markdown documents may be in sync-service, S3, or both.
+ // A backfill can replace this legacy ambiguity with SyncService.
+ Some(FileType::Md) => DocumentContentLocation::Unknown,
+ _ => DocumentContentLocation::ObjectStorage,
+ };
+
+ Self::ready(location)
+ }
+
+ /// Derive content metadata from legacy DB columns where file type is stored
+ /// as a string extension.
+ pub fn from_legacy_uploaded_str(uploaded: bool, file_type: Option<&str>) -> Self {
+ Self::from_legacy_uploaded(
+ uploaded,
+ file_type.and_then(|file_type| FileType::from_str(file_type).ok()),
+ )
+ }
+
+ /// Convert database column values into content metadata.
+ pub fn from_db_columns(state: &str, location: Option<&str>) -> Option<Self> {
+ Some(Self {
+ state: DocumentContentState::from_db_value(state)?,
+ location: location.and_then(DocumentContentLocation::from_db_value),
+ })
+ }
+
+ /// Database value for the state column.
+ pub fn state_db_value(&self) -> &'static str {
+ self.state.db_value()
+ }
+
+ /// Database value for the location column.
+ pub fn location_db_value(&self) -> Option<&'static str> {
+ self.location.map(|location| location.db_value())
+ }
+}
+
+impl DocumentContentState {
+ fn db_value(self) -> &'static str {
+ match self {
+ Self::Unknown => "unknown",
+ Self::Pending => "pending",
+ Self::Ready => "ready",
+ }
+ }
+
+ fn from_db_value(value: &str) -> Option<Self> {
+ match value {
+ "unknown" => Some(Self::Unknown),
+ "pending" => Some(Self::Pending),
+ "ready" => Some(Self::Ready),
+ _ => None,
+ }
+ }
+}
+
+impl DocumentContentLocation {
+ fn db_value(self) -> &'static str {
+ match self {
+ Self::ObjectStorage => "object_storage",
+ Self::SyncService => "sync_service",
+ Self::DocxBomParts => "docx_bom_parts",
+ Self::ConvertedPdf => "converted_pdf",
+ Self::Unknown => "unknown",
+ }
+ }
+
+ fn from_db_value(value: &str) -> Option<Self> {
+ match value {
+ "object_storage" => Some(Self::ObjectStorage),
+ "sync_service" => Some(Self::SyncService),
+ "docx_bom_parts" => Some(Self::DocxBomParts),
+ "converted_pdf" => Some(Self::ConvertedPdf),
+ "unknown" => Some(Self::Unknown),
+ _ => None,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{DocumentContent, DocumentContentLocation, DocumentContentState};
+ use model::document::FileType;
+
+ #[test]
+ fn legacy_not_uploaded_is_pending() {
+ assert_eq!(
+ DocumentContent::from_legacy_uploaded(false, Some(FileType::Pdf)),
+ DocumentContent {
+ state: DocumentContentState::Pending,
+ location: None,
+ }
+ );
+ }
+
+ #[test]
+ fn legacy_uploaded_markdown_location_is_unknown() {
+ assert_eq!(
+ DocumentContent::from_legacy_uploaded(true, Some(FileType::Md)),
+ DocumentContent::ready(DocumentContentLocation::Unknown)
+ );
+ }
+
+ #[test]
+ fn legacy_uploaded_non_markdown_uses_object_storage() {
+ assert_eq!(
+ DocumentContent::from_legacy_uploaded(true, Some(FileType::Pdf)),
+ DocumentContent::ready(DocumentContentLocation::ObjectStorage)
+ );
+ }
+}
diff --git a/rust/cloud-storage/documents/src/domain/create/mod.rs b/rust/cloud-storage/documents/src/domain/create/mod.rs
new file mode 100644
index 0000000000..3e5ffff183
--- /dev/null
+++ b/rust/cloud-storage/documents/src/domain/create/mod.rs
@@ -0,0 +1,711 @@
+//! Backend-owned document creation orchestration.
+//!
+//! This module keeps creation policy in one place. It intentionally exposes
+//! explicit creation methods rather than a generic document-kind dispatcher:
+//! call sites should choose the lifecycle they need (`create_markdown_text` or
+//! `create_text_file`).
+
+use anyhow::Context;
+use base64::Engine;
+use macro_user_id::user_id::MacroUserIdStr;
+use model::document::FileType;
+use sha2::{Digest, Sha256};
+
+use crate::domain::content::{DocumentContent, DocumentContentLocation};
+use crate::domain::models::{
+ CreateDocumentRepoArgs, CreateTaskRequest, DocumentError, EMPTY_SHA256, PropertyInput,
+};
+use crate::domain::ports::create::{
+ DocumentBytesUpload, DocumentBytesUploadPort, DocumentCreationService,
+};
+use crate::domain::ports::markdown::MarkdownInitializationPort;
+use crate::domain::response::CreateDocumentResponseData;
+
+/// Common metadata for a document that has not been created yet.
+#[derive(Debug, Clone)]
+pub struct NewDocumentMetadata {
+ id: Option<uuid::Uuid>,
+ document_name: String,
+ project_id: Option<uuid::Uuid>,
+ email_attachment_id: Option<uuid::Uuid>,
+ created_at: Option<chrono::DateTime<chrono::Utc>>,
+ skip_history: bool,
+}
+
+impl NewDocumentMetadata {
+ /// Construct metadata with default optional fields.
+ pub fn new(document_name: impl Into<String>) -> Self {
+ Self::builder(document_name).build()
+ }
+
+ /// Build document metadata with optional fields.
+ pub fn builder(document_name: impl Into<String>) -> NewDocumentMetadataBuilder {
+ NewDocumentMetadataBuilder {
+ metadata: Self {
+ id: None,
+ document_name: document_name.into(),
+ project_id: None,
+ email_attachment_id: None,
+ created_at: None,
+ skip_history: false,
+ },
+ }
+ }
+
+ fn into_repo_args(
+ self,
+ user_id: MacroUserIdStr<'static>,
+ kind: RepoDocumentKind,
+ ) -> CreateDocumentRepoArgs {
+ CreateDocumentRepoArgs {
+ id: self.id,
+ sha: kind.sha,
+ document_name: self.document_name,
+ user_id,
+ file_type: kind.file_type,
+ project_id: self.project_id,
+ email_attachment_id: self.email_attachment_id,
+ created_at: self.created_at,
+ is_task: kind.subtype.is_task(),
+ skip_history: self.skip_history,
+ }
+ }
+}
+
+/// Builder for [`NewDocumentMetadata`].
+#[derive(Debug, Clone)]
+pub struct NewDocumentMetadataBuilder {
+ metadata: NewDocumentMetadata,
+}
+
+impl NewDocumentMetadataBuilder {
+ /// Set a caller-provided document id.
+ pub fn id(mut self, id: uuid::Uuid) -> Self {
+ self.metadata.id = Some(id);
+ self
+ }
+
+ /// Set the project to associate with the document.
+ pub fn project_id(mut self, project_id: uuid::Uuid) -> Self {
+ self.metadata.project_id = Some(project_id);
+ self
+ }
+
+ /// Set an email attachment to link to this document.
+ pub fn email_attachment_id(mut self, email_attachment_id: uuid::Uuid) -> Self {
+ self.metadata.email_attachment_id = Some(email_attachment_id);
+ self
+ }
+
+ /// Set a custom creation timestamp.
+ pub fn created_at(mut self, created_at: chrono::DateTime<chrono::Utc>) -> Self {
+ self.metadata.created_at = Some(created_at);
+ self
+ }
+
+ /// Skip adding this document to user history.
+ pub fn skip_history(mut self) -> Self {
+ self.metadata.skip_history = true;
+ self
+ }
+
+ /// Build the metadata value.
+ pub fn build(self) -> NewDocumentMetadata {
+ self.metadata
+ }
+}
+
+struct RepoDocumentKind {
+ file_type: Option<FileType>,
+ sha: String,
+ subtype: RepoDocumentSubtype,
+}
+
+enum RepoDocumentSubtype {
+ Regular,
+ MarkdownTask,
+}
+
+impl RepoDocumentSubtype {
+ fn is_task(&self) -> bool {
+ matches!(self, RepoDocumentSubtype::MarkdownTask)
+ }
+}
+
+/// Markdown-specific subtype. Task-ness only exists for markdown documents.
+#[derive(Debug, Clone)]
+pub enum MarkdownSubtype {
+ /// A regular markdown note.
+ Note,
+ /// A task document.
+ Task {
+ /// Optional property values to assign. Defaults are used when omitted.
+ property_values: Option<Vec<PropertyInput>>,
+ /// Whether to share the task with the user's team.
+ share_with_team: bool,
+ },
+}
+
+impl MarkdownSubtype {
+ /// Convert a simple task flag into the default markdown subtype.
+ pub fn from_task_flag(is_task: bool) -> Self {
+ if is_task {
+ Self::Task {
+ property_values: None,
+ share_with_team: true,
+ }
+ } else {
+ Self::Note
+ }
+ }
+}
+
+/// A backend-created markdown document.
+///
+/// Creation writes document metadata, initializes sync-service from `markdown`,
+/// and applies task properties when `subtype` is [`MarkdownSubtype::Task`].
+#[derive(Debug, Clone)]
+pub struct NewMarkdownTextDocument {
+ /// Common document metadata.
+ pub metadata: NewDocumentMetadata,
+ /// Markdown source text.
+ pub markdown: String,
+ /// Markdown subtype.
+ pub subtype: MarkdownSubtype,
+}
+
+impl NewMarkdownTextDocument {
+ /// Construct an empty markdown note.
+ pub fn empty_note(metadata: NewDocumentMetadata) -> Self {
+ Self {
+ metadata,
+ markdown: String::new(),
+ subtype: MarkdownSubtype::Note,
+ }
+ }
+}
+
+/// A backend-created plaintext document whose file type determines the
+/// creation lifecycle.
+#[derive(Debug, Clone)]
+pub struct NewPlainTextDocument {
+ metadata: NewDocumentMetadata,
+ text: String,
+ kind: PlainTextDocumentKind,
+}
+
+#[derive(Debug, Clone)]
+enum PlainTextDocumentKind {
+ Markdown(MarkdownSubtype),
+ Text(NonMarkdownFileType),
+}
+
+/// Marker for a plaintext document builder missing a file type.
+#[derive(Debug, Clone)]
+pub struct MissingPlainTextFileType;
+
+/// Marker for a plaintext document builder missing text content.
+#[derive(Debug, Clone)]
+pub struct MissingPlainTextContent;
+
+/// Builder for [`NewPlainTextDocument`].
+#[derive(Debug, Clone)]
+pub struct NewPlainTextDocumentBuilder<FileTypeState, TextState> {
+ metadata: NewDocumentMetadata,
+ file_type: FileTypeState,
+ text: TextState,
+ markdown_subtype: MarkdownSubtype,
+}
+
+impl NewPlainTextDocument {
+ /// Start building a plaintext document.
+ pub fn builder(
+ metadata: NewDocumentMetadata,
+ ) -> NewPlainTextDocumentBuilder<MissingPlainTextFileType, MissingPlainTextContent> {
+ NewPlainTextDocumentBuilder {
+ metadata,
+ file_type: MissingPlainTextFileType,
+ text: MissingPlainTextContent,
+ markdown_subtype: MarkdownSubtype::Note,
+ }
+ }
+
+ /// Construct a plaintext document from a file type, rejecting impossible
+ /// combinations like task documents with non-markdown file types.
+ pub fn new(
+ metadata: NewDocumentMetadata,
+ file_type: FileType,
+ text: String,
+ markdown_subtype: MarkdownSubtype,
+ ) -> Result<Self, DocumentError> {
+ Self::builder(metadata)
+ .file_type(file_type)
+ .text(text)
+ .markdown_subtype(markdown_subtype)
+ .build()
+ }
+}
+
+impl<TextState> NewPlainTextDocumentBuilder<MissingPlainTextFileType, TextState> {
+ /// Set the document file type.
+ pub fn file_type(
+ self,
+ file_type: FileType,
+ ) -> NewPlainTextDocumentBuilder<FileType, TextState> {
+ NewPlainTextDocumentBuilder {
+ metadata: self.metadata,
+ file_type,
+ text: self.text,
+ markdown_subtype: self.markdown_subtype,
+ }
+ }
+}
+
+impl<FileTypeState> NewPlainTextDocumentBuilder<FileTypeState, MissingPlainTextContent> {
+ /// Set the text content.
+ pub fn text(
+ self,
+ text: impl Into<String>,
+ ) -> NewPlainTextDocumentBuilder<FileTypeState, String> {
+ NewPlainTextDocumentBuilder {
+ metadata: self.metadata,
+ file_type: self.file_type,
+ text: text.into(),
+ markdown_subtype: self.markdown_subtype,
+ }
+ }
+}
+
+impl<FileTypeState, TextState> NewPlainTextDocumentBuilder<FileTypeState, TextState> {
+ /// Set the markdown subtype used when `file_type` is markdown.
+ pub fn markdown_subtype(mut self, markdown_subtype: MarkdownSubtype) -> Self {
+ self.markdown_subtype = markdown_subtype;
+ self
+ }
+
+ /// Set the markdown subtype from a simple task flag.
+ pub fn task_flag(self, is_task: bool) -> Self {
+ self.markdown_subtype(MarkdownSubtype::from_task_flag(is_task))
+ }
+}
+
+impl NewPlainTextDocumentBuilder<FileType, String> {
+ /// Build the document description.
+ pub fn build(self) -> Result<NewPlainTextDocument, DocumentError> {
+ let kind = if self.file_type == FileType::Md {
+ PlainTextDocumentKind::Markdown(self.markdown_subtype)
+ } else {
+ if matches!(self.markdown_subtype, MarkdownSubtype::Task { .. }) {
+ return Err(DocumentError::BadRequest(
+ "tasks must be markdown documents".to_string(),
+ ));
+ }
+ PlainTextDocumentKind::Text(NonMarkdownFileType::new(self.file_type)?)
+ };
+
+ Ok(NewPlainTextDocument {
+ metadata: self.metadata,
+ text: self.text,
+ kind,
+ })
+ }
+}
+
+/// A file type that is known not to be markdown.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct NonMarkdownFileType(FileType);
+
+impl NonMarkdownFileType {
+ /// Create a non-markdown file type, rejecting [`FileType::Md`].
+ pub fn new(file_type: FileType) -> Result<Self, DocumentError> {
+ if file_type == FileType::Md {
+ return Err(DocumentError::BadRequest(
+ "md documents must use NewMarkdownTextDocument".to_string(),
+ ));
+ }
+
+ Ok(Self(file_type))
+ }
+
+ /// Get the underlying file type.
+ pub fn as_file_type(&self) -> FileType {
+ self.0
+ }
+
+ fn into_file_type(self) -> FileType {
+ self.0
+ }
+}
+
+impl TryFrom<FileType> for NonMarkdownFileType {
+ type Error = DocumentError;
+
+ fn try_from(file_type: FileType) -> Result<Self, Self::Error> {
+ Self::new(file_type)
+ }
+}
+
+/// A backend-created non-markdown text file.
+///
+/// Creation writes document metadata and uploads `text` to the presigned
+/// document-storage URL returned by the document service.
+#[derive(Debug, Clone)]
+pub struct NewTextFileDocument {
+ /// Common document metadata.
+ pub metadata: NewDocumentMetadata,
+ /// Text document file type. Markdown is excluded by construction.
+ pub file_type: NonMarkdownFileType,
+ /// Text content to upload.
+ pub text: String,
+}
+
+impl NewTextFileDocument {
+ /// Construct a text file document, rejecting markdown file types.
+ pub fn new(
+ metadata: NewDocumentMetadata,
+ file_type: FileType,
+ text: String,
+ ) -> Result<Self, DocumentError> {
+ Ok(Self {
+ metadata,
+ file_type: NonMarkdownFileType::new(file_type)?,
+ text,
+ })
+ }
+}
+
+/// A fully created document.
+#[derive(Debug)]
+pub struct CreatedDocument {
+ response: CreateDocumentResponseData,
+}
+
+impl CreatedDocument {
+ fn new(response: CreateDocumentResponseData) -> Self {
+ Self { response }
+ }
+
+ /// The created document id.
+ pub fn document_id(&self) -> &str {
+ &self
+ .response
+ .document_response
+ .document_metadata
+ .metadata
+ .document_id
+ }
+
+ /// Get the underlying create response.
+ pub fn response(&self) -> &CreateDocumentResponseData {
+ &self.response
+ }
+
+ /// Consume into the raw create response.
+ pub fn into_response(self) -> CreateDocumentResponseData {
+ self.response
+ }
+}
+
+/// Service for creating backend-owned document content.
+#[derive(Clone)]
+pub struct DocumentCreator<Svc, MarkdownInit, BytesUpload> {
+ document_service: Svc,
+ markdown_initializer: MarkdownInit,
+ bytes_uploader: BytesUpload,
+}
+
+impl<Svc, MarkdownInit, BytesUpload> DocumentCreator<Svc, MarkdownInit, BytesUpload> {
+ /// Construct a document creator.
+ pub fn new(
+ document_service: Svc,
+ markdown_initializer: MarkdownInit,
+ bytes_uploader: BytesUpload,
+ ) -> Self {
+ Self {
+ document_service,
+ markdown_initializer,
+ bytes_uploader,
+ }
+ }
+}
+
+impl<Svc, MarkdownInit, BytesUpload> DocumentCreator<Svc, MarkdownInit, BytesUpload>
+where
+ Svc: DocumentCreationService,
+ MarkdownInit: MarkdownInitializationPort,
+ BytesUpload: DocumentBytesUploadPort,
+{
+ /// Create a plaintext document using the lifecycle implied by its file type.
+ #[tracing::instrument(skip(self, document), err)]
+ pub async fn create_plain_text(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ document: NewPlainTextDocument,
+ ) -> Result<CreatedDocument, DocumentError> {
+ let NewPlainTextDocument {
+ metadata,
+ text,
+ kind,
+ } = document;
+
+ match kind {
+ PlainTextDocumentKind::Markdown(subtype) => {
+ self.create_markdown_text(
+ user_id,
+ NewMarkdownTextDocument {
+ metadata,
+ markdown: text,
+ subtype,
+ },
+ )
+ .await
+ }
+ PlainTextDocumentKind::Text(file_type) => {
+ self.create_text_file(
+ user_id,
+ NewTextFileDocument {
+ metadata,
+ file_type,
+ text,
+ },
+ )
+ .await
+ }
+ }
+ }
+
+ /// Create a markdown text document and initialize sync-service.
+ #[tracing::instrument(skip(self, document), err)]
+ pub async fn create_markdown_text(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ document: NewMarkdownTextDocument,
+ ) -> Result<CreatedDocument, DocumentError> {
+ let NewMarkdownTextDocument {
+ metadata,
+ markdown,
+ subtype,
+ } = document;
+ let task = match &subtype {
+ MarkdownSubtype::Note => None,
+ MarkdownSubtype::Task {
+ property_values,
+ share_with_team,
+ } => Some((property_values.clone(), *share_with_team)),
+ };
+
+ let task_name = metadata.document_name.clone();
+ let project_id = metadata.project_id;
+ let args = metadata.into_repo_args(
+ user_id.clone(),
+ RepoDocumentKind {
+ file_type: Some(FileType::Md),
+ sha: EMPTY_SHA256.to_string(),
+ subtype: if task.is_some() {
+ RepoDocumentSubtype::MarkdownTask
+ } else {
+ RepoDocumentSubtype::Regular
+ },
+ },
+ );
+
+ let mut response = self
+ .document_service
+ .create_document(user_id.clone(), args, None)
+ .await?;
+
+ let document_id = response
+ .document_response
+ .document_metadata
+ .metadata
+ .document_id
+ .clone();
+
+ let finalize_result = async {
+ if let Some((property_values, share_with_team)) = task {
+ self.document_service
+ .handle_task_properties(
+ user_id,
+ &document_id,
+ &CreateTaskRequest {
+ task_name,
+ markdown: None,
+ project_id,
+ property_values,
+ share_with_team,
+ },
+ )
+ .await?;
+ }
+
+ self.markdown_initializer
+ .initialize_existing_markdown(&document_id, &markdown)
+ .await?;
+
+ self.document_service
+ .set_document_content(
+ &document_id,
+ DocumentContent::ready(DocumentContentLocation::SyncService),
+ )
+ .await?;
+
+ Ok(())
+ }
+ .await;
+
+ if let Err(error) = finalize_result {
+ self.cleanup_created_document(&document_id).await;
+ return Err(error);
+ }
+
+ response.document_response.document_metadata.content =
+ DocumentContent::ready(DocumentContentLocation::SyncService);
+
+ Ok(CreatedDocument::new(response))
+ }
+
+ /// Create a text file and upload it to document storage.
+ #[tracing::instrument(skip(self, document), err)]
+ pub async fn create_text_file(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ document: NewTextFileDocument,
+ ) -> Result<CreatedDocument, DocumentError> {
+ let NewTextFileDocument {
+ metadata,
+ file_type,
+ text,
+ } = document;
+
+ let bytes = text.into_bytes();
+ let hashes = file_shas(&bytes);
+ let args = metadata.into_repo_args(
+ user_id.clone(),
+ RepoDocumentKind {
+ file_type: Some(file_type.into_file_type()),
+ sha: hashes.hex,
+ subtype: RepoDocumentSubtype::Regular,
+ },
+ );
+
+ let mut response = self
+ .document_service
+ .create_document(user_id, args, None)
+ .await?;
+
+ let document_id = response
+ .document_response
+ .document_metadata
+ .metadata
+ .document_id
+ .clone();
+
+ let finalize_result = async {
+ let presigned_url = response
+ .document_response
+ .presigned_url
+ .as_ref()
+ .context("expected presigned url")
+ .map_err(DocumentError::Internal)?;
+
+ self.bytes_uploader
+ .upload_document_bytes(DocumentBytesUpload {
+ presigned_url: presigned_url.clone(),
+ content_type: response.content_type.clone(),
+ base64_sha256: hashes.base64,
+ bytes,
+ })
+ .await?;
+
+ self.document_service
+ .set_document_content(
+ &document_id,
+ DocumentContent::ready(DocumentContentLocation::ObjectStorage),
+ )
+ .await?;
+
+ Ok(())
+ }
+ .await;
+
+ if let Err(error) = finalize_result {
+ self.cleanup_created_document(&document_id).await;
+ return Err(error);
+ }
+
+ response.document_response.document_metadata.content =
+ DocumentContent::ready(DocumentContentLocation::ObjectStorage);
+
+ Ok(CreatedDocument::new(response))
+ }
+
+ async fn cleanup_created_document(&self, document_id: &str) {
+ self.document_service
+ .cleanup_created_document(document_id)
+ .await;
+ }
+}
+
+#[derive(Debug)]
+struct FileShas {
+ hex: String,
+ base64: String,
+}
+
+fn file_shas(file_content: &[u8]) -> FileShas {
+ let mut hasher = Sha256::new();
+ hasher.update(file_content);
+ let file_hash_result = hasher.finalize();
+ let hex = format!("{file_hash_result:x}");
+ let base64 = base64::engine::general_purpose::STANDARD.encode(file_hash_result);
+
+ FileShas { hex, base64 }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{MarkdownSubtype, NewDocumentMetadata, NewPlainTextDocument, file_shas};
+ use model::document::FileType;
+
+ fn metadata() -> NewDocumentMetadata {
+ NewDocumentMetadata::new("test")
+ }
+
+ #[test]
+ fn new_plain_text_rejects_non_markdown_task() {
+ let err = NewPlainTextDocument::builder(metadata())
+ .file_type(FileType::Txt)
+ .text("hello")
+ .markdown_subtype(MarkdownSubtype::from_task_flag(true))
+ .build()
+ .unwrap_err();
+
+ assert_eq!(
+ err.to_string(),
+ "bad request: tasks must be markdown documents"
+ );
+ }
+
+ #[test]
+ fn new_plain_text_accepts_markdown_task() {
+ NewPlainTextDocument::builder(metadata())
+ .file_type(FileType::Md)
+ .text("# hello")
+ .task_flag(true)
+ .build()
+ .unwrap();
+ }
+
+ #[test]
+ fn test_file_shas() {
+ let hashes = file_shas(b"hello");
+ assert_eq!(
+ hashes.hex,
+ "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
+ );
+ assert_eq!(
+ hashes.base64,
+ "LPJNul+wow4m6DsqxbninhsWHlwfp0JecwQzYpOLmCQ="
+ );
+ }
+}
diff --git a/rust/cloud-storage/documents/src/domain/markdown_init.rs b/rust/cloud-storage/documents/src/domain/markdown_init.rs
deleted file mode 100644
index 2f2c293008..0000000000
--- a/rust/cloud-storage/documents/src/domain/markdown_init.rs
+++ /dev/null
@@ -1,20 +0,0 @@
-//! Helpers for initializing markdown documents in sync-service.
-
-use lexical_client::LexicalClient;
-use sync_service_client::SyncServiceClient;
-
-/// Converts markdown to a Loro snapshot using lexical-service and initializes
-/// the corresponding document in sync-service.
-#[tracing::instrument(skip(markdown, lexical_client, sync_service_client), err)]
-pub async fn initialize_markdown_document(
- lexical_client: &LexicalClient,
- sync_service_client: &SyncServiceClient,
- document_id: &str,
- markdown: &str,
-) -> anyhow::Result<()> {
- let snapshot = lexical_client.markdown_to_loro_snapshot(markdown).await?;
- sync_service_client
- .initialize_from_snapshot(document_id, &snapshot)
- .await?;
- Ok(())
-}
diff --git a/rust/cloud-storage/documents/src/domain/models.rs b/rust/cloud-storage/documents/src/domain/models.rs
index af69072849..5d18a9bb59 100644
--- a/rust/cloud-storage/documents/src/domain/models.rs
+++ b/rust/cloud-storage/documents/src/domain/models.rs
@@ -3,6 +3,8 @@
use chrono::{DateTime, Utc};
use macro_user_id::user_id::MacroUserIdStr;
use model::document::{DocumentMetadata, FileType};
+
+use super::response::DocumentResponse;
use model::sync_service::SyncServiceVersionID;
use models_properties::api::requests::SetPropertyValue;
use serde_json::Value;
@@ -51,7 +53,7 @@ pub struct CopyDocumentResponse {
/// Indicates if an error occurred.
pub error: bool,
/// The copied document data.
- pub data: model::document::response::DocumentResponse,
+ pub data: DocumentResponse,
}
/// Arguments for copying a document in the repository.
@@ -190,6 +192,32 @@ fn default_true() -> bool {
true
}
+/// Request body for creating a markdown document whose content is initialized
+/// by the backend.
+#[derive(serde::Serialize, serde::Deserialize, Debug)]
+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct CreateMarkdownDocumentRequest {
+ /// The document name.
+ pub document_name: String,
+ /// Markdown source text. Defaults to an empty document.
+ pub markdown: Option<String>,
+ /// Optional project ID to associate the document with.
+ pub project_id: Option<uuid::Uuid>,
+ /// Whether to add a viewed_at record for this document upon creation.
+ #[serde(default)]
+ pub skip_history: bool,
+}
+
+/// Response for creating a markdown document.
+#[derive(serde::Serialize, serde::Deserialize, Debug)]
+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct CreateMarkdownDocumentResponse {
+ /// The document ID of the created markdown document.
+ pub document_id: String,
+}
+
/// Request body for creating a task.
#[derive(serde::Serialize, serde::Deserialize, Debug)]
#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
@@ -197,6 +225,8 @@ fn default_true() -> bool {
pub struct CreateTaskRequest {
/// The name of the task.
pub task_name: String,
+ /// Markdown source text. Defaults to an empty task document.
+ pub markdown: Option<String>,
/// Optional project ID to associate the task with.
pub project_id: Option<uuid::Uuid>,
/// Optional property values to set on the task.
diff --git a/rust/cloud-storage/documents/src/domain/ports/create/mod.rs b/rust/cloud-storage/documents/src/domain/ports/create/mod.rs
new file mode 100644
index 0000000000..ed22c3fe29
--- /dev/null
+++ b/rust/cloud-storage/documents/src/domain/ports/create/mod.rs
@@ -0,0 +1,107 @@
+//! Port definitions for backend-owned document creation.
+
+use std::future::Future;
+use std::sync::Arc;
+
+use macro_user_id::user_id::MacroUserIdStr;
+
+use crate::domain::content::DocumentContent;
+use crate::domain::models::{CreateDocumentRepoArgs, CreateTaskRequest, DocumentError};
+use crate::domain::response::CreateDocumentResponseData;
+
+/// Uploaded document bytes and metadata for a presigned object-storage URL.
+pub struct DocumentBytesUpload {
+ /// Presigned URL to upload bytes to.
+ pub presigned_url: String,
+ /// Content type to send with the upload.
+ pub content_type: String,
+ /// Base64-encoded SHA-256 checksum to send with the upload.
+ pub base64_sha256: String,
+ /// Bytes to upload.
+ pub bytes: Vec<u8>,
+}
+
+/// Uploads document bytes to object storage using a presigned URL.
+pub trait DocumentBytesUploadPort: Send + Sync {
+ /// Upload document bytes.
+ fn upload_document_bytes(
+ &self,
+ upload: DocumentBytesUpload,
+ ) -> impl Future<Output = Result<(), DocumentError>> + Send;
+}
+
+/// Service operations needed by backend-owned document creation.
+pub trait DocumentCreationService: Send + Sync {
+ /// Create a document metadata row and any service-owned creation side effects.
+ fn create_document(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ args: CreateDocumentRepoArgs,
+ job_id: Option<String>,
+ ) -> impl Future<Output = Result<CreateDocumentResponseData, DocumentError>> + Send;
+
+ /// Assign task properties to a markdown task document.
+ fn handle_task_properties(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ document_id: &str,
+ request: &CreateTaskRequest,
+ ) -> impl Future<Output = Result<(), DocumentError>> + Send;
+
+ /// Mark a created document's upload/finalization lifecycle as complete.
+ fn mark_document_uploaded(
+ &self,
+ document_id: &str,
+ ) -> impl Future<Output = Result<(), DocumentError>> + Send;
+
+ /// Set a created document's persisted content lifecycle metadata.
+ fn set_document_content(
+ &self,
+ document_id: &str,
+ content: DocumentContent,
+ ) -> impl Future<Output = Result<(), DocumentError>> + Send;
+
+ /// Clean up a document that failed after its database row was created.
+ fn cleanup_created_document(&self, document_id: &str) -> impl Future<Output = ()> + Send;
+}
+
+impl<T> DocumentCreationService for Arc<T>
+where
+ T: DocumentCreationService + ?Sized,
+{
+ async fn create_document(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ args: CreateDocumentRepoArgs,
+ job_id: Option<String>,
+ ) -> Result<CreateDocumentResponseData, DocumentError> {
+ (**self).create_document(user_id, args, job_id).await
+ }
+
+ async fn handle_task_properties(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ document_id: &str,
+ request: &CreateTaskRequest,
+ ) -> Result<(), DocumentError> {
+ (**self)
+ .handle_task_properties(user_id, document_id, request)
+ .await
+ }
+
+ async fn mark_document_uploaded(&self, document_id: &str) -> Result<(), DocumentError> {
+ (**self).mark_document_uploaded(document_id).await
+ }
+
+ async fn set_document_content(
+ &self,
+ document_id: &str,
+ content: DocumentContent,
+ ) -> Result<(), DocumentError> {
+ (**self).set_document_content(document_id, content).await
+ }
+
+ async fn cleanup_created_document(&self, document_id: &str) {
+ (**self).cleanup_created_document(document_id).await
+ }
+}
diff --git a/rust/cloud-storage/documents/src/domain/ports/markdown.rs b/rust/cloud-storage/documents/src/domain/ports/markdown.rs
new file mode 100644
index 0000000000..dcd232084d
--- /dev/null
+++ b/rust/cloud-storage/documents/src/domain/ports/markdown.rs
@@ -0,0 +1,15 @@
+//! Port definitions for markdown document initialization.
+
+use std::future::Future;
+
+use crate::domain::models::DocumentError;
+
+/// Initializes markdown document content in the collaborative editor backend.
+pub trait MarkdownInitializationPort: Send + Sync {
+ /// Initialize an already-created markdown document from markdown text.
+ fn initialize_existing_markdown(
+ &self,
+ document_id: &str,
+ markdown: &str,
+ ) -> impl Future<Output = Result<(), DocumentError>> + Send;
+}
diff --git a/rust/cloud-storage/documents/src/domain/ports.rs b/rust/cloud-storage/documents/src/domain/ports/mod.rs
similarity index 89%
rename from rust/cloud-storage/documents/src/domain/ports.rs
rename to rust/cloud-storage/documents/src/domain/ports/mod.rs
index 90960320d9..0f68b425cb 100644
--- a/rust/cloud-storage/documents/src/domain/ports.rs
+++ b/rust/cloud-storage/documents/src/domain/ports/mod.rs
@@ -2,25 +2,30 @@
//!
//! These traits define the contracts that adapters must implement.
+#[cfg(feature = "document_create")]
+pub mod create;
+pub mod markdown;
+
use std::future::Future;
use entity_access::domain::models::{
EditAccessLevel, EntityAccessReceipt, OwnerAccessLevel, ViewAccessLevel,
};
use macro_user_id::user_id::MacroUserIdStr;
-use model::document::response::{
- CreateDocumentResponseData, GetDocumentResponseData, LocationResponseV3,
-};
use model::document::{ContentType, DocumentBasic, DocumentMetadata};
+use super::content::DocumentContent;
+use super::response::{
+ CreateDocumentResponseData, DocumentResponse, GetDocumentResponseData, LocationResponseV3,
+};
+
use model::sync_service::SyncServiceVersionID;
use model_entity::Entity;
use super::models::{
- CommentThread, CopyDocumentRepoArgs, CreateDocumentRepoArgs, CreateTaskRequest,
- CreateTaskResponse, DocumentError, EditDocumentRepoArgs, EditDocumentServiceArgs,
- LocationQueryParams,
+ CommentThread, CopyDocumentRepoArgs, CreateDocumentRepoArgs, CreateTaskRequest, DocumentError,
+ EditDocumentRepoArgs, EditDocumentServiceArgs, LocationQueryParams,
};
/// Repository for accessing document data from the database.
@@ -57,6 +62,28 @@ pub trait DocumentRepo: Send + Sync + 'static {
document_id: &str,
) -> impl Future<Output = Result<(), Self::Err>> + Send;
+ /// Mark a document's upload/finalization lifecycle as complete.
+ fn mark_document_uploaded(
+ &self,
+ document_id: &str,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Get persisted content lifecycle metadata for a document.
+ fn get_persisted_document_content(
+ &self,
+ document_id: &str,
+ ) -> impl Future<Output = Result<Option<DocumentContent>, Self::Err>> + Send;
+
+ /// Set persisted content lifecycle metadata for a document.
+ ///
+ /// Implementations should keep legacy upload state in sync with the new
+ /// lifecycle metadata while legacy consumers still read that column.
+ fn set_document_content(
+ &self,
+ document_id: &str,
+ content: DocumentContent,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
/// Get the latest document version ID (for editable files: js, py).
/// Returns (version_id, uploaded).
fn get_latest_document_version_id(
@@ -291,6 +318,12 @@ pub trait DocumentService: Send + Sync + 'static {
job_id: Option<String>,
) -> impl Future<Output = Result<CreateDocumentResponseData, DocumentError>> + Send;
+ /// Get content lifecycle metadata for a document.
+ fn get_document_content(
+ &self,
+ document_context: &DocumentBasic,
+ ) -> impl Future<Output = Result<DocumentContent, DocumentError>> + Send;
+
/// Convert a document's entity_id to a short UUID.
fn get_short_id(
&self,
@@ -324,7 +357,7 @@ pub trait DocumentService: Send + Sync + 'static {
document_name: String,
query_version_id: Option<i64>,
sync_version_id: Option<SyncServiceVersionID>,
- ) -> impl Future<Output = Result<model::document::response::DocumentResponse, DocumentError>> + Send;
+ ) -> impl Future<Output = Result<DocumentResponse, DocumentError>> + Send;
/// Get the name of a project by ID.
fn get_project_name(
@@ -338,14 +371,6 @@ pub trait DocumentService: Send + Sync + 'static {
project_id: &str,
) -> impl Future<Output = Result<Vec<Entity<'static>>, DocumentError>> + Send;
- /// Create a task document and optionally set property values on it.
- fn create_task(
- &self,
- user_id: MacroUserIdStr<'static>,
- plain_user_id: String,
- request: CreateTaskRequest,
- ) -> impl Future<Output = Result<CreateTaskResponse, DocumentError>> + Send;
-
/// Assigns the task properties to a document
fn handle_task_properties(
&self,
diff --git a/rust/cloud-storage/documents/src/domain/response.rs b/rust/cloud-storage/documents/src/domain/response.rs
new file mode 100644
index 0000000000..3dc09e81d9
--- /dev/null
+++ b/rust/cloud-storage/documents/src/domain/response.rs
@@ -0,0 +1,244 @@
+//! Document API response shapes owned by the documents domain.
+
+use std::str::FromStr;
+
+use model::document::response::DocumentResponseMetadata;
+use model::document::{DocumentBasic, DocumentMetadata, FileType};
+use model::response::{PresignedUrl, TypedSuccessResponse};
+use models_permissions::share_permission::access_level::AccessLevel;
+
+use super::content::DocumentContent;
+
+/// Peer/user mapping returned by sync-service metadata.
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
+#[serde(rename_all = "snake_case")]
+pub struct SyncServicePeerWithUserId {
+ /// Sync-service peer id.
+ pub peer_id: String,
+ /// Macro user id.
+ pub user_id: String,
+}
+
+impl From<model::sync_service::PeerWithUserId> for SyncServicePeerWithUserId {
+ fn from(peer: model::sync_service::PeerWithUserId) -> Self {
+ Self {
+ peer_id: peer.peer_id,
+ user_id: peer.user_id,
+ }
+ }
+}
+
+/// Sync-service document metadata exposed through document location responses.
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
+#[serde(rename_all = "snake_case")]
+pub struct SyncServiceDocumentMetadata {
+ /// Sync-service document id.
+ pub id: String,
+ /// Known peers for the sync document.
+ pub peers: Vec<SyncServicePeerWithUserId>,
+ /// Current sync-service version id.
+ pub version_id: String,
+}
+
+impl From<model::sync_service::DocumentMetadata> for SyncServiceDocumentMetadata {
+ fn from(metadata: model::sync_service::DocumentMetadata) -> Self {
+ Self {
+ id: metadata.id,
+ peers: metadata.peers.into_iter().map(Into::into).collect(),
+ version_id: metadata.version_id,
+ }
+ }
+}
+
+/// Full document metadata plus content lifecycle metadata.
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct DocumentMetadataWithContent {
+ /// Legacy document metadata.
+ #[serde(flatten)]
+ pub metadata: DocumentMetadata,
+ /// Content lifecycle and location metadata.
+ pub content: DocumentContent,
+}
+
+impl DocumentMetadataWithContent {
+ /// Attach content metadata to legacy document metadata.
+ pub fn new(metadata: DocumentMetadata, content: DocumentContent) -> Self {
+ Self { metadata, content }
+ }
+}
+
+/// Create/copy response metadata plus content lifecycle metadata.
+#[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug, Clone)]
+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct DocumentResponseMetadataWithContent {
+ /// Legacy create/copy response metadata.
+ #[serde(flatten)]
+ pub metadata: DocumentResponseMetadata,
+ /// Content lifecycle and location metadata.
+ pub content: DocumentContent,
+}
+
+impl DocumentResponseMetadataWithContent {
+ /// Attach content metadata to legacy response metadata.
+ pub fn new(metadata: DocumentResponseMetadata, content: DocumentContent) -> Self {
+ Self { metadata, content }
+ }
+}
+
+/// Document response with content lifecycle metadata.
+#[derive(serde::Serialize, serde::Deserialize, Debug)]
+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct DocumentResponse {
+ /// The document metadata.
+ pub document_metadata: DocumentResponseMetadataWithContent,
+ /// Presigned upload URL, when the caller still needs to upload bytes.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub presigned_url: Option<String>,
+}
+
+/// Create document response data with content lifecycle metadata.
+#[derive(serde::Serialize, serde::Deserialize, Debug)]
+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct CreateDocumentResponseData {
+ /// Document metadata and upload URL.
+ #[serde(flatten)]
+ pub document_response: DocumentResponse,
+ /// Content type of the document converted from file type.
+ pub content_type: String,
+ /// The file type of the document.
+ pub file_type: Option<String>,
+}
+
+impl CreateDocumentResponseData {
+ /// Attach content metadata to a legacy create response.
+ pub fn from_legacy(
+ legacy: model::document::response::CreateDocumentResponseData,
+ content: DocumentContent,
+ ) -> Self {
+ Self {
+ document_response: DocumentResponse {
+ document_metadata: DocumentResponseMetadataWithContent::new(
+ legacy.document_response.document_metadata,
+ content,
+ ),
+ presigned_url: legacy.document_response.presigned_url,
+ },
+ content_type: legacy.content_type,
+ file_type: legacy.file_type,
+ }
+ }
+}
+
+/// Create document HTTP response.
+pub type CreateDocumentResponse = TypedSuccessResponse<CreateDocumentResponseData>;
+
+/// Get document response data with content lifecycle metadata.
+#[derive(serde::Serialize, serde::Deserialize, Debug)]
+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct GetDocumentResponseData {
+ /// The metadata of the document.
+ pub document_metadata: DocumentMetadataWithContent,
+ /// The user's level of access to the document.
+ pub user_access_level: AccessLevel,
+ /// The user's view location if there is one.
+ pub view_location: Option<String>,
+}
+
+/// Get document HTTP response.
+pub type GetDocumentResponse = TypedSuccessResponse<GetDocumentResponseData>;
+
+/// Location response with content lifecycle metadata.
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
+#[serde(
+ tag = "type",
+ rename_all = "camelCase",
+ rename_all_fields = "camelCase"
+)]
+pub enum LocationResponseV3 {
+ /// A single document-storage URL.
+ PresignedUrl {
+ /// Presigned URL.
+ #[serde(rename = "presignedUrl")]
+ #[cfg_attr(feature = "axum", schema(rename = "presignedUrl"))]
+ presigned_url: String,
+ /// Basic document metadata.
+ metadata: DocumentBasic,
+ /// Content lifecycle and location metadata.
+ content: DocumentContent,
+ },
+ /// Multiple document-storage URLs, currently for DOCX BOM parts.
+ PresignedUrls {
+ /// Presigned URLs.
+ #[serde(rename = "presignedUrls")]
+ #[cfg_attr(feature = "axum", schema(rename = "presignedUrls"))]
+ presigned_urls: Vec<PresignedUrl>,
+ /// Basic document metadata.
+ metadata: DocumentBasic,
+ /// Content lifecycle and location metadata.
+ content: DocumentContent,
+ },
+ /// Sync-service backed content.
+ SyncServiceContent {
+ /// Basic document metadata.
+ metadata: DocumentBasic,
+ /// Sync-service metadata.
+ #[serde(rename = "syncServiceMetadata")]
+ #[cfg_attr(feature = "axum", schema(rename = "syncServiceMetadata"))]
+ sync_service_metadata: SyncServiceDocumentMetadata,
+ /// Content lifecycle and location metadata.
+ content: DocumentContent,
+ },
+}
+
+impl LocationResponseV3 {
+ /// Basic document metadata for the location response.
+ pub fn metadata(&self) -> &DocumentBasic {
+ match self {
+ Self::PresignedUrl { metadata, .. } => metadata,
+ Self::PresignedUrls { metadata, .. } => metadata,
+ Self::SyncServiceContent { metadata, .. } => metadata,
+ }
+ }
+
+ /// Content lifecycle metadata for the location response.
+ pub fn content(&self) -> &DocumentContent {
+ match self {
+ Self::PresignedUrl { content, .. } => content,
+ Self::PresignedUrls { content, .. } => content,
+ Self::SyncServiceContent { content, .. } => content,
+ }
+ }
+
+ /// Sync-service metadata, when this location is sync-backed.
+ pub fn sync_service_metadata(&self) -> Option<&SyncServiceDocumentMetadata> {
+ if let Self::SyncServiceContent {
+ sync_service_metadata,
+ ..
+ } = self
+ {
+ Some(sync_service_metadata)
+ } else {
+ None
+ }
+ }
+
+ /// Parsed file type from metadata.
+ pub fn file_type(&self) -> anyhow::Result<FileType> {
+ self.metadata()
+ .file_type
+ .as_deref()
+ .map(FileType::from_str)
+ .and_then(Result::ok)
+ .ok_or_else(|| anyhow::anyhow!("unexpected file type {:?}", self.metadata().file_type))
+ }
+}
diff --git a/rust/cloud-storage/documents/src/domain/service.rs b/rust/cloud-storage/documents/src/domain/service.rs
index f5175b19f6..07e5ef2bf7 100644
--- a/rust/cloud-storage/documents/src/domain/service.rs
+++ b/rust/cloud-storage/documents/src/domain/service.rs
@@ -21,10 +21,7 @@ use entity_access::domain::models::{
EditAccessLevel, EntityAccessAuth, EntityAccessReceipt, OwnerAccessLevel, ViewAccessLevel,
};
use macro_user_id::user_id::MacroUserIdStr;
-use model::document::response::{
- CreateDocumentResponseData, DocumentResponse, DocumentResponseMetadata,
- GetDocumentResponseData, LocationResponseData, LocationResponseV3,
-};
+use model::document::response::{DocumentResponseMetadata, LocationResponseData};
use model::document::{ContentType, DocumentBasic, FileAssociation, FileType, FileTypeExt};
use model::response::PresignedUrl;
use s3_key::{
@@ -37,12 +34,19 @@ use crate::domain::models::{
ASSIGNEES_PROPERTY_ID, NOT_STARTED_STATUS_OPTION_ID, PropertyInput, STATUS_PROPERTY_ID,
};
+use super::content::{DocumentContent, DocumentContentLocation, DocumentContentState};
use super::models::{
CloudFrontConfig, CommentThread, CopyDocumentRepoArgs, CreateDocumentRepoArgs,
- CreateTaskRequest, CreateTaskResponse, DocumentError, EMPTY_SHA256, EditDocumentRepoArgs,
- EditDocumentServiceArgs, FileTypeUpdate, LocationQueryParams,
+ CreateTaskRequest, DocumentError, EditDocumentRepoArgs, EditDocumentServiceArgs,
+ FileTypeUpdate, LocationQueryParams,
};
+#[cfg(feature = "document_create")]
+use super::ports::create::DocumentCreationService;
use super::ports::{DocumentRepo, DocumentService, PresignedUploadUrlPort, TaskPropertiesPort};
+use super::response::{
+ CreateDocumentResponseData, DocumentMetadataWithContent, DocumentResponse,
+ DocumentResponseMetadataWithContent, GetDocumentResponseData, LocationResponseV3,
+};
/// The concrete document service implementation.
pub struct DocumentServiceImpl<
@@ -62,6 +66,45 @@ pub struct DocumentServiceImpl<
entity_access_management_service: Eam,
}
+fn ready_content_for_file_type(file_type: Option<FileType>) -> DocumentContent {
+ match file_type {
+ Some(FileType::Md) => DocumentContent::ready(DocumentContentLocation::SyncService),
+ Some(FileType::Docx) => DocumentContent::ready(DocumentContentLocation::ConvertedPdf),
+ _ => DocumentContent::ready(DocumentContentLocation::ObjectStorage),
+ }
+}
+
+fn content_at_location(
+ state: DocumentContentState,
+ location: DocumentContentLocation,
+) -> DocumentContent {
+ DocumentContent {
+ state,
+ location: Some(location),
+ }
+}
+
+fn presigned_location_content(
+ state: DocumentContentState,
+ file_type: Option<FileType>,
+ get_converted_docx: bool,
+) -> DocumentContent {
+ let location = match (file_type, get_converted_docx) {
+ (Some(FileType::Docx), true) => DocumentContentLocation::ConvertedPdf,
+ (Some(FileType::Docx), false) => DocumentContentLocation::DocxBomParts,
+ _ => DocumentContentLocation::ObjectStorage,
+ };
+
+ content_at_location(state, location)
+}
+
+fn pending_content_for_file_type(file_type: Option<FileType>) -> DocumentContent {
+ match file_type {
+ Some(FileType::Docx) => DocumentContent::pending_at(DocumentContentLocation::ConvertedPdf),
+ _ => DocumentContent::pending_at(DocumentContentLocation::ObjectStorage),
+ }
+}
+
impl<
R: DocumentRepo,
U: PresignedUploadUrlPort,
@@ -253,36 +296,84 @@ impl<
}
}
- async fn try_get_from_sync_service(
+ async fn content_for_document(
&self,
document_id: &str,
- ) -> Result<Option<model::sync_service::DocumentMetadata>, anyhow::Error> {
- use futures::{FutureExt, pin_mut, select};
+ file_type: Option<FileType>,
+ ) -> Result<DocumentContent, DocumentError> {
+ if let Some(content) = self
+ .repo
+ .get_persisted_document_content(document_id)
+ .await
+ .map_err(|e| DocumentError::Internal(e.into()))?
+ {
+ return Ok(content);
+ }
- let exists_fut = self.sync_service_client.exists(document_id).fuse();
- let metadata_fut = self.sync_service_client.get_metadata(document_id).fuse();
+ let (_, uploaded) = if file_type
+ .is_none_or(|file_type| file_type == FileType::Docx || file_type.is_static())
+ {
+ self.repo
+ .get_document_version_id(document_id)
+ .await
+ .map_err(|e| DocumentError::Internal(e.into()))?
+ } else {
+ self.repo
+ .get_latest_document_version_id(document_id)
+ .await
+ .map_err(|e| DocumentError::Internal(e.into()))?
+ };
- pin_mut!(exists_fut, metadata_fut);
+ Ok(DocumentContent::from_legacy_uploaded(uploaded, file_type))
+ }
- select! {
- exists_result = exists_fut => {
- match exists_result {
- Ok(false) => Ok(None),
- Ok(true) | Err(_) => {
- metadata_fut.await.map(Some)
- }
- }
- },
- metadata_result = metadata_fut => {
- match metadata_result {
- Ok(metadata) => Ok(Some(metadata)),
- Err(e) => {
- match exists_fut.await {
- Ok(false) => Ok(None),
- _ => Err(e),
- }
- }
- }
+ async fn markdown_sync_service_location_response(
+ &self,
+ document_context: &DocumentBasic,
+ document_id: &str,
+ content: DocumentContent,
+ ) -> Result<LocationResponseV3, DocumentError> {
+ let sync_service_metadata = self
+ .sync_service_client
+ .get_metadata(document_id)
+ .await
+ .map_err(DocumentError::Internal)?;
+
+ Ok(LocationResponseV3::SyncServiceContent {
+ metadata: document_context.clone(),
+ sync_service_metadata: sync_service_metadata.into(),
+ content,
+ })
+ }
+
+ async fn resolve_markdown_sync_service_location(
+ &self,
+ document_context: &DocumentBasic,
+ document_id: &str,
+ content: DocumentContent,
+ ) -> Result<Option<LocationResponseV3>, DocumentError> {
+ if content.state == DocumentContentState::Ready
+ && content.location == Some(DocumentContentLocation::SyncService)
+ {
+ return self
+ .markdown_sync_service_location_response(document_context, document_id, content)
+ .await
+ .map(Some);
+ }
+
+ match self.sync_service_client.get_metadata(document_id).await {
+ Ok(sync_service_metadata) => Ok(Some(LocationResponseV3::SyncServiceContent {
+ metadata: document_context.clone(),
+ sync_service_metadata: sync_service_metadata.into(),
+ content: DocumentContent::ready(DocumentContentLocation::SyncService),
+ })),
+ Err(error) => {
+ tracing::warn!(
+ error=?error,
+ document_id=?document_id,
+ "temporary markdown location fallback did not find sync-service state"
+ );
+ Ok(None)
}
}
}
@@ -295,6 +386,59 @@ impl<
}
}
+#[cfg(feature = "document_create")]
+impl<
+ R: DocumentRepo,
+ U: PresignedUploadUrlPort,
+ T: TaskPropertiesPort,
+ C: ConnectionService,
+ Eam: EntityAccessManagementService,
+> DocumentCreationService for DocumentServiceImpl<R, U, T, C, Eam>
+{
+ async fn create_document(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ args: CreateDocumentRepoArgs,
+ job_id: Option<String>,
+ ) -> Result<CreateDocumentResponseData, DocumentError> {
+ <Self as DocumentService>::create_document(self, user_id, args, job_id).await
+ }
+
+ async fn handle_task_properties(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ document_id: &str,
+ request: &CreateTaskRequest,
+ ) -> Result<(), DocumentError> {
+ <Self as DocumentService>::handle_task_properties(self, user_id, document_id, request).await
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn mark_document_uploaded(&self, document_id: &str) -> Result<(), DocumentError> {
+ self.repo
+ .mark_document_uploaded(document_id)
+ .await
+ .map_err(|e| DocumentError::Internal(e.into()))
+ }
+
+ #[tracing::instrument(err, skip(self, content))]
+ async fn set_document_content(
+ &self,
+ document_id: &str,
+ content: DocumentContent,
+ ) -> Result<(), DocumentError> {
+ self.repo
+ .set_document_content(document_id, content)
+ .await
+ .map_err(|e| DocumentError::Internal(e.into()))
+ }
+
+ #[tracing::instrument(skip(self))]
+ async fn cleanup_created_document(&self, document_id: &str) {
+ self.cleanup_document(document_id).await;
+ }
+}
+
impl<
R: DocumentRepo,
U: PresignedUploadUrlPort,
@@ -343,8 +487,14 @@ impl<
_ => unreachable!(),
};
+ let file_type = document_metadata
+ .file_type
+ .as_deref()
+ .and_then(|file_type| FileType::from_str(file_type).ok());
+ let content = self.content_for_document(&document_id, file_type).await?;
+
Ok(GetDocumentResponseData {
- document_metadata,
+ document_metadata: DocumentMetadataWithContent::new(document_metadata, content),
user_access_level: *access_level,
view_location,
})
@@ -363,45 +513,53 @@ impl<
.and_then(|f| FileType::from_str(f).ok());
let document_id = entity_access_receipt.entity().entity_id.clone();
+ let content = self.content_for_document(&document_id, file_type).await?;
- // For markdown files, check sync service first
- if matches!(file_type, Some(FileType::Md)) {
- match self.try_get_from_sync_service(&document_id).await {
- Ok(Some(sync_service_metadata)) => {
- return Ok(LocationResponseV3::SyncServiceContent {
- metadata: document_context.clone(),
- sync_service_metadata,
- });
- }
- Ok(None) => {
- // Continue to S3 check
- }
- Err(e) => {
- tracing::error!(error=?e, "sync service failed");
- return Err(DocumentError::Internal(e));
- }
- }
+ if matches!(file_type, Some(FileType::Md))
+ && let Some(response) = self
+ .resolve_markdown_sync_service_location(
+ document_context,
+ &document_id,
+ content.clone(),
+ )
+ .await?
+ {
+ return Ok(response);
}
let owner = document_context.owner.as_ref();
+ let get_converted_docx_url = params.get_converted_docx_url.unwrap_or(false);
let response_data = self
.get_presigned_url_by_type(
owner,
&document_id,
file_type,
params.document_version_id,
- params.get_converted_docx_url.unwrap_or(false),
+ get_converted_docx_url,
)
.await
.map(|response| match response {
- LocationResponseData::PresignedUrl(url) => LocationResponseV3::PresignedUrl {
- presigned_url: url,
- metadata: document_context.clone(),
- },
- LocationResponseData::PresignedUrls(urls) => LocationResponseV3::PresignedUrls {
- presigned_urls: urls,
- metadata: document_context.clone(),
- },
+ LocationResponseData::PresignedUrl(url) => {
+ let content = presigned_location_content(
+ content.state,
+ file_type,
+ get_converted_docx_url,
+ );
+ LocationResponseV3::PresignedUrl {
+ presigned_url: url,
+ metadata: document_context.clone(),
+ content,
+ }
+ }
+ LocationResponseData::PresignedUrls(urls) => {
+ let content =
+ content_at_location(content.state, DocumentContentLocation::DocxBomParts);
+ LocationResponseV3::PresignedUrls {
+ presigned_urls: urls,
+ metadata: document_context.clone(),
+ content,
+ }
+ }
})
.map_err(|e| {
if e.to_string() == "document does not exist in s3" {
@@ -519,6 +677,18 @@ impl<
Ok(short_id)
}
+ #[tracing::instrument(err, skip(self, document_context))]
+ async fn get_document_content(
+ &self,
+ document_context: &DocumentBasic,
+ ) -> Result<DocumentContent, DocumentError> {
+ self.content_for_document(
+ &document_context.document_id,
+ document_context.try_file_type(),
+ )
+ .await
+ }
+
#[tracing::instrument(err, skip(self, args))]
async fn create_document(
&self,
@@ -546,6 +716,17 @@ impl<
let document_id = document_metadata.document_id.clone();
+ let initial_content = pending_content_for_file_type(file_type);
+ if let Err(e) = self
+ .repo
+ .set_document_content(&document_id, initial_content.clone())
+ .await
+ {
+ tracing::error!(error=?e, document_id=?document_id, "failed to initialize document content metadata");
+ self.cleanup_document(&document_id).await;
+ return Err(DocumentError::Internal(e.into()));
+ }
+
// 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
@@ -629,7 +810,10 @@ impl<
Ok(CreateDocumentResponseData {
document_response: DocumentResponse {
- document_metadata: document_response_metadata,
+ document_metadata: DocumentResponseMetadataWithContent::new(
+ document_response_metadata,
+ initial_content,
+ ),
presigned_url: Some(presigned_url),
},
content_type: mime_type,
@@ -963,6 +1147,17 @@ impl<
return Err(DocumentError::Internal(e));
}
+ let content = ready_content_for_file_type(file_type);
+ if let Err(e) = self
+ .repo
+ .set_document_content(&new_document_id, content.clone())
+ .await
+ {
+ tracing::error!(error=?e, document_id=?new_document_id, "failed to mark copied document content ready");
+ self.cleanup_document(&new_document_id).await;
+ return Err(DocumentError::Internal(e.into()));
+ }
+
let document_response_metadata =
DocumentResponseMetadata::from_document_metadata(&new_metadata).map_err(|e| {
tracing::error!(error=?e, "unable to convert document metadata");
@@ -970,7 +1165,10 @@ impl<
})?;
Ok(DocumentResponse {
- document_metadata: document_response_metadata,
+ document_metadata: DocumentResponseMetadataWithContent::new(
+ document_response_metadata,
+ content,
+ ),
presigned_url: None,
})
}
@@ -1003,52 +1201,6 @@ impl<
Ok(())
}
- #[tracing::instrument(err, skip(self, request))]
- async fn create_task(
- &self,
- user_id: MacroUserIdStr<'static>,
- plain_user_id: String,
- request: CreateTaskRequest,
- ) -> Result<CreateTaskResponse, DocumentError> {
- let response_data = self
- .create_document(
- user_id.clone(),
- CreateDocumentRepoArgs {
- id: None,
- sha: EMPTY_SHA256.to_string(),
- document_name: request.task_name.clone(),
- user_id: user_id.clone(),
- file_type: Some(FileType::Md),
- project_id: request.project_id,
- email_attachment_id: None,
- created_at: None,
- is_task: true,
- skip_history: false,
- },
- None,
- )
- .await?;
-
- let document_id = response_data
- .document_response
- .document_metadata
- .document_id
- .clone();
-
- let _ = self
- .handle_task_properties(user_id, &document_id, &request)
- .await
- .inspect_err(|e| {
- tracing::error!(
- error=?e,
- document_id=?document_id,
- "failed to assign task properties",
- );
- });
-
- Ok(CreateTaskResponse { document_id })
- }
-
/// Assigns the task properties to a document
#[tracing::instrument(skip(self, request), err)]
async fn handle_task_properties(
diff --git a/rust/cloud-storage/documents/src/domain/upload_finalize.rs b/rust/cloud-storage/documents/src/domain/upload_finalize.rs
new file mode 100644
index 0000000000..3c29e4eaea
--- /dev/null
+++ b/rust/cloud-storage/documents/src/domain/upload_finalize.rs
@@ -0,0 +1,215 @@
+//! Domain helpers for finalizing uploaded document bytes.
+
+use std::future::Future;
+
+use model::document::{DocumentBasic, FileType, FileTypeExt};
+
+use super::content::{DocumentContent, DocumentContentLocation, DocumentContentState};
+use super::models::DocumentError;
+use super::ports::DocumentRepo;
+use super::ports::markdown::MarkdownInitializationPort;
+
+/// Minimal document operations needed to finalize an uploaded object.
+pub trait UploadFinalizeDocumentPort: Send + Sync {
+ /// Get content lifecycle metadata for a document.
+ fn get_document_content(
+ &self,
+ document_context: &DocumentBasic,
+ ) -> impl Future<Output = Result<DocumentContent, DocumentError>> + Send;
+
+ /// Mark document upload/finalization complete.
+ fn mark_document_uploaded(
+ &self,
+ document_id: &str,
+ ) -> impl Future<Output = Result<(), DocumentError>> + Send;
+
+ /// Persist content lifecycle metadata.
+ fn set_document_content(
+ &self,
+ document_id: &str,
+ content: DocumentContent,
+ ) -> impl Future<Output = Result<(), DocumentError>> + Send;
+}
+
+/// Repo-backed upload-finalization port for infrastructure workers.
+pub struct RepoUploadFinalizePort<R> {
+ repo: R,
+}
+
+impl<R> RepoUploadFinalizePort<R> {
+ /// Construct a repo-backed finalization port.
+ pub fn new(repo: R) -> Self {
+ Self { repo }
+ }
+}
+
+impl<R> UploadFinalizeDocumentPort for RepoUploadFinalizePort<R>
+where
+ R: DocumentRepo,
+{
+ async fn get_document_content(
+ &self,
+ document_context: &DocumentBasic,
+ ) -> Result<DocumentContent, DocumentError> {
+ let file_type = document_context.try_file_type();
+ let (_, uploaded) = if file_type
+ .is_none_or(|file_type| file_type == FileType::Docx || file_type.is_static())
+ {
+ self.repo
+ .get_document_version_id(&document_context.document_id)
+ .await
+ .map_err(|error| DocumentError::Internal(error.into()))?
+ } else {
+ self.repo
+ .get_latest_document_version_id(&document_context.document_id)
+ .await
+ .map_err(|error| DocumentError::Internal(error.into()))?
+ };
+
+ Ok(DocumentContent::from_legacy_uploaded(uploaded, file_type))
+ }
+
+ async fn mark_document_uploaded(&self, document_id: &str) -> Result<(), DocumentError> {
+ self.repo
+ .mark_document_uploaded(document_id)
+ .await
+ .map_err(|error| DocumentError::Internal(error.into()))
+ }
+
+ async fn set_document_content(
+ &self,
+ document_id: &str,
+ content: DocumentContent,
+ ) -> Result<(), DocumentError> {
+ self.repo
+ .set_document_content(document_id, content)
+ .await
+ .map_err(|error| DocumentError::Internal(error.into()))
+ }
+}
+
+/// Finalizes uploaded document bytes once object storage reports them present.
+pub struct UploadedDocumentFinalizer<'a, P, M> {
+ document_port: &'a P,
+ markdown_initializer: &'a M,
+}
+
+impl<'a, P, M> UploadedDocumentFinalizer<'a, P, M>
+where
+ P: UploadFinalizeDocumentPort,
+ M: MarkdownInitializationPort,
+{
+ /// Construct a finalizer.
+ pub fn new(document_port: &'a P, markdown_initializer: &'a M) -> Self {
+ Self {
+ document_port,
+ markdown_initializer,
+ }
+ }
+
+ /// Finalize a document whose uploaded object is now present.
+ ///
+ /// Markdown uploads require the uploaded markdown body so sync-service can
+ /// be initialized. Non-markdown uploads are finalized by marking them
+ /// uploaded. DOCX upload objects are finalized by their conversion pipeline;
+ /// the converted PDF object finalizes DOCX user-readable content.
+ #[tracing::instrument(skip(self, document_context, markdown), err)]
+ pub async fn finalize_uploaded_document(
+ &self,
+ document_context: &DocumentBasic,
+ markdown: Option<&str>,
+ ) -> Result<(), DocumentError> {
+ let file_type = document_context.try_file_type();
+
+ if matches!(file_type, Some(FileType::Docx)) {
+ return Ok(());
+ }
+
+ self.finalize_ready_content(
+ document_context,
+ markdown,
+ DocumentContentLocation::ObjectStorage,
+ )
+ .await
+ }
+
+ /// Finalize the converted PDF representation of a DOCX document.
+ #[tracing::instrument(skip(self, document_context), err)]
+ pub async fn finalize_converted_pdf_document(
+ &self,
+ document_context: &DocumentBasic,
+ ) -> Result<(), DocumentError> {
+ if !matches!(document_context.try_file_type(), Some(FileType::Docx)) {
+ return Ok(());
+ }
+
+ let content = self
+ .document_port
+ .get_document_content(document_context)
+ .await?;
+ if content.state == DocumentContentState::Ready
+ && content.location == Some(DocumentContentLocation::ConvertedPdf)
+ {
+ return Ok(());
+ }
+
+ self.document_port
+ .set_document_content(
+ &document_context.document_id,
+ DocumentContent::ready(DocumentContentLocation::ConvertedPdf),
+ )
+ .await
+ }
+
+ async fn finalize_ready_content(
+ &self,
+ document_context: &DocumentBasic,
+ markdown: Option<&str>,
+ ready_location: DocumentContentLocation,
+ ) -> Result<(), DocumentError> {
+ let file_type = document_context.try_file_type();
+
+ let content = self
+ .document_port
+ .get_document_content(document_context)
+ .await?;
+ if content.state == DocumentContentState::Ready {
+ return Ok(());
+ }
+
+ if matches!(file_type, Some(FileType::Md)) {
+ let markdown = markdown.ok_or_else(|| {
+ DocumentError::BadRequest(
+ "markdown upload finalization requires uploaded markdown".to_string(),
+ )
+ })?;
+
+ match self
+ .markdown_initializer
+ .initialize_existing_markdown(&document_context.document_id, markdown)
+ .await
+ {
+ Ok(()) => {}
+ Err(error) if sync_snapshot_already_exists(&error) => {}
+ Err(error) => return Err(error),
+ }
+ }
+
+ let location = if matches!(file_type, Some(FileType::Md)) {
+ DocumentContentLocation::SyncService
+ } else {
+ ready_location
+ };
+
+ self.document_port
+ .set_document_content(
+ &document_context.document_id,
+ DocumentContent::ready(location),
+ )
+ .await
+ }
+}
+
+fn sync_snapshot_already_exists(error: &DocumentError) -> bool {
+ error.to_string().contains("snapshot already exists")
+}
diff --git a/rust/cloud-storage/documents/src/inbound/attachment/service.rs b/rust/cloud-storage/documents/src/inbound/attachment/service.rs
index cc019a4759..0bac6cdeea 100644
--- a/rust/cloud-storage/documents/src/inbound/attachment/service.rs
+++ b/rust/cloud-storage/documents/src/inbound/attachment/service.rs
@@ -20,7 +20,9 @@ use model_entity::{Entity, EntityType};
use model_file_type::{FileAssociation, FileType};
use non_empty::NonEmpty;
-use crate::domain::{models::LocationQueryParams, ports::DocumentService};
+use crate::domain::{
+ models::LocationQueryParams, ports::DocumentService, response::LocationResponseV3,
+};
use super::markdown;
@@ -220,9 +222,7 @@ impl<DSvc: DocumentService, ESvc: EntityAccessService> DocumentAttachmentService
.map_err(|e| AttachmentError::Internal(e.into()))?;
match location {
- model::document::response::LocationResponseV3::PresignedUrl {
- presigned_url, ..
- } => Ok(presigned_url),
+ LocationResponseV3::PresignedUrl { presigned_url, .. } => Ok(presigned_url),
_ => Err(AttachmentError::Internal(anyhow::anyhow!(
"unexpected location response for document"
))),
diff --git a/rust/cloud-storage/documents/src/inbound/axum_router.rs b/rust/cloud-storage/documents/src/inbound/axum_router.rs
index 8798df406e..377b317bcb 100644
--- a/rust/cloud-storage/documents/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/documents/src/inbound/axum_router.rs
@@ -6,6 +6,7 @@
//! - `GET /{document_id}/location_v3` — get document content location (presigned URL)
//! - `GET /{document_id}/branch_name` — get short ID + git branch name (when the document is a task)
//! - `GET /{document_id}/short_id` — get document short ID
+//! - `POST /create_markdown` — create and initialize a markdown document
//! - `DELETE /{document_id}` — soft-delete a document
#[cfg(test)]
@@ -13,6 +14,8 @@ mod tests;
mod copy_document;
mod create_document;
+#[cfg(feature = "document_create")]
+mod create_markdown;
mod create_task;
mod delete_document;
mod edit_document;
@@ -38,10 +41,14 @@ use sqlx::PgPool;
use crate::domain::models::DocumentError;
use crate::domain::ports::DocumentService;
+#[cfg(feature = "document_create")]
+use crate::domain::ports::create::DocumentCreationService;
// Re-export handlers and utoipa path types for external use (swagger, internal routes)
pub use copy_document::*;
pub use create_document::*;
+#[cfg(feature = "document_create")]
+pub use create_markdown::*;
pub use create_task::*;
pub use delete_document::*;
pub use edit_document::*;
@@ -76,7 +83,15 @@ impl IntoResponse for DocumentError {
}
}
-/// Router state containing the document service, entity access service, and DB pool.
+/// Default backend-owned document creation use case for the document router.
+#[cfg(feature = "document_create_adapters")]
+pub type DefaultDocumentCreator<T> = crate::domain::create::DocumentCreator<
+ Arc<T>,
+ crate::outbound::markdown_init::LexicalSyncMarkdownInitializer,
+ crate::outbound::document_bytes_upload::ReqwestDocumentBytesUploader,
+>;
+
+/// Router state containing document router dependencies.
pub struct DocumentRouterState<T, Svc> {
/// The document service implementation.
pub service: Arc<T>,
@@ -84,6 +99,9 @@ pub struct DocumentRouterState<T, Svc> {
pub access_service: Arc<Svc>,
/// The database pool (used by middleware for document lookups).
pub pool: PgPool,
+ /// Backend-owned document creation use case.
+ #[cfg(feature = "document_create_adapters")]
+ pub creator: DefaultDocumentCreator<T>,
}
// Manual Clone impl so T and Svc don't need to be Clone (they're behind Arc).
@@ -93,6 +111,8 @@ impl<T, Svc> Clone for DocumentRouterState<T, Svc> {
service: self.service.clone(),
access_service: self.access_service.clone(),
pool: self.pool.clone(),
+ #[cfg(feature = "document_create_adapters")]
+ creator: self.creator.clone(),
}
}
}
@@ -112,7 +132,7 @@ pub struct Params {
/// Build the documents router with all endpoints.
pub fn documents_router<T, Svc, S>(state: DocumentRouterState<T, Svc>) -> Router<S>
where
- T: DocumentService,
+ T: DocumentService + DocumentCreationService,
Svc: EntityAccessService,
S: Send + Sync + 'static,
{
@@ -139,20 +159,28 @@ where
.route(
"/{document_id}/copy",
axum::routing::post(copy_document_handler::<T, Svc>),
- )
- .layer(middleware::from_fn_with_state(
- state.clone(),
- ensure_document_exists,
- ));
+ );
+
+ let document_id_routes = document_id_routes.layer(middleware::from_fn_with_state(
+ state.clone(),
+ ensure_document_exists,
+ ));
- Router::new()
+ let router = Router::new()
.merge(document_id_routes)
.route("/", axum::routing::post(create_document_handler::<T, Svc>))
.route(
"/create_task",
axum::routing::post(create_task_handler::<T, Svc>),
- )
- .with_state(state)
+ );
+
+ #[cfg(feature = "document_create")]
+ let router = router.route(
+ "/create_markdown",
+ axum::routing::post(create_markdown_handler::<T, Svc>),
+ );
+
+ router.with_state(state)
}
/// Path parameters for document endpoints.
diff --git a/rust/cloud-storage/documents/src/inbound/axum_router/create_document.rs b/rust/cloud-storage/documents/src/inbound/axum_router/create_document.rs
index 4499a34602..87e6225017 100644
--- a/rust/cloud-storage/documents/src/inbound/axum_router/create_document.rs
+++ b/rust/cloud-storage/documents/src/inbound/axum_router/create_document.rs
@@ -5,7 +5,7 @@ use std::str::FromStr;
use axum::{Extension, Json, extract::State};
use entity_access::domain::ports::EntityAccessService;
use entity_access::inbound::axum_extractors::{InternalUser, ProjectBodyAccessLevelExtractor};
-use model::document::response::{CreateDocumentRequest, CreateDocumentResponse};
+use model::document::response::CreateDocumentRequest;
use model::document::{FileType, FileTypeExt};
use model_user::axum_extractor::MacroUserExtractor;
use models_permissions::share_permission::access_level::EditAccessLevel;
@@ -13,6 +13,7 @@ use models_permissions::share_permission::access_level::EditAccessLevel;
use super::DocumentRouterState;
use crate::domain::models::{CreateDocumentRepoArgs, DocumentError};
use crate::domain::ports::DocumentService;
+use crate::domain::response::CreateDocumentResponse;
/// Handler for `POST /documents`.
///
diff --git a/rust/cloud-storage/documents/src/inbound/axum_router/create_markdown.rs b/rust/cloud-storage/documents/src/inbound/axum_router/create_markdown.rs
new file mode 100644
index 0000000000..b900a38e3d
--- /dev/null
+++ b/rust/cloud-storage/documents/src/inbound/axum_router/create_markdown.rs
@@ -0,0 +1,65 @@
+//! Handler for `POST /documents/create_markdown`.
+
+use axum::{Json, extract::State};
+use entity_access::domain::ports::EntityAccessService;
+use entity_access::inbound::axum_extractors::ProjectBodyAccessLevelExtractor;
+use model_user::axum_extractor::MacroUserExtractor;
+use models_permissions::share_permission::access_level::EditAccessLevel;
+
+use super::DocumentRouterState;
+use crate::domain::create::{MarkdownSubtype, NewDocumentMetadata, NewMarkdownTextDocument};
+use crate::domain::models::{
+ CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, DocumentError,
+};
+use crate::domain::ports::DocumentService;
+use crate::domain::ports::create::DocumentCreationService;
+
+/// Creates and initializes a markdown document in one backend-owned lifecycle.
+#[utoipa::path(
+ tag = "document",
+ post,
+ path = "/documents/create_markdown",
+ request_body = CreateMarkdownDocumentRequest,
+ responses(
+ (status = 200, body = inline(CreateMarkdownDocumentResponse)),
+ (status = 400, body = model_error_response::ErrorResponse),
+ (status = 401, body = model_error_response::ErrorResponse),
+ (status = 409, body = model_error_response::ErrorResponse),
+ (status = 500, body = model_error_response::ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip(state, user_context, project), fields(user_id=?user_context.macro_user_id))]
+pub async fn create_markdown_handler<
+ T: DocumentService + DocumentCreationService,
+ Svc: EntityAccessService,
+>(
+ State(state): State<DocumentRouterState<T, Svc>>,
+ user_context: MacroUserExtractor,
+ project: ProjectBodyAccessLevelExtractor<EditAccessLevel, CreateMarkdownDocumentRequest, Svc>,
+) -> Result<Json<CreateMarkdownDocumentResponse>, DocumentError> {
+ let req = project.into_inner();
+
+ let mut metadata = NewDocumentMetadata::builder(req.document_name);
+ if let Some(project_id) = req.project_id {
+ metadata = metadata.project_id(project_id);
+ }
+ if req.skip_history {
+ metadata = metadata.skip_history();
+ }
+
+ let created = state
+ .creator
+ .create_markdown_text(
+ user_context.macro_user_id,
+ NewMarkdownTextDocument {
+ metadata: metadata.build(),
+ markdown: req.markdown.unwrap_or_default(),
+ subtype: MarkdownSubtype::Note,
+ },
+ )
+ .await?;
+
+ Ok(Json(CreateMarkdownDocumentResponse {
+ document_id: created.document_id().to_string(),
+ }))
+}
diff --git a/rust/cloud-storage/documents/src/inbound/axum_router/create_task.rs b/rust/cloud-storage/documents/src/inbound/axum_router/create_task.rs
index bc84279d9b..e217d502cb 100644
--- a/rust/cloud-storage/documents/src/inbound/axum_router/create_task.rs
+++ b/rust/cloud-storage/documents/src/inbound/axum_router/create_task.rs
@@ -7,13 +7,13 @@ use model_user::axum_extractor::MacroUserExtractor;
use models_permissions::share_permission::access_level::EditAccessLevel;
use super::DocumentRouterState;
+use crate::domain::create::{MarkdownSubtype, NewDocumentMetadata, NewMarkdownTextDocument};
use crate::domain::models::{CreateTaskRequest, CreateTaskResponse, DocumentError};
use crate::domain::ports::DocumentService;
+use crate::domain::ports::create::DocumentCreationService;
-/// Creates a task document with properties in a single call.
-///
-/// This endpoint creates task metadata and sets properties atomically.
-/// Task content should be set separately via the sync service.
+/// Creates a task document with properties and initialized markdown content in
+/// one backend-owned lifecycle.
#[utoipa::path(
tag = "document",
post,
@@ -27,19 +27,37 @@ use crate::domain::ports::DocumentService;
)
)]
#[tracing::instrument(skip(state, user_context, project), fields(user_id=?user_context.macro_user_id))]
-pub async fn create_task_handler<T: DocumentService, Svc: EntityAccessService>(
+pub async fn create_task_handler<
+ T: DocumentService + DocumentCreationService,
+ Svc: EntityAccessService,
+>(
State(state): State<DocumentRouterState<T, Svc>>,
user_context: MacroUserExtractor,
project: ProjectBodyAccessLevelExtractor<EditAccessLevel, CreateTaskRequest, Svc>,
) -> Result<Json<CreateTaskResponse>, DocumentError> {
let req = project.into_inner();
- let user_id = user_context.user_context.user_id.clone();
- let macro_user_id = user_context.macro_user_id;
- let response = state
- .service
- .create_task(macro_user_id, user_id, req)
+ let mut metadata = NewDocumentMetadata::builder(req.task_name.clone());
+ if let Some(project_id) = req.project_id {
+ metadata = metadata.project_id(project_id);
+ }
+
+ let created = state
+ .creator
+ .create_markdown_text(
+ user_context.macro_user_id,
+ NewMarkdownTextDocument {
+ metadata: metadata.build(),
+ markdown: req.markdown.unwrap_or_default(),
+ subtype: MarkdownSubtype::Task {
+ property_values: req.property_values,
+ share_with_team: req.share_with_team,
+ },
+ },
+ )
.await?;
- Ok(Json(response))
+ Ok(Json(CreateTaskResponse {
+ document_id: created.document_id().to_string(),
+ }))
}
diff --git a/rust/cloud-storage/documents/src/inbound/axum_router/get_branch_name.rs b/rust/cloud-storage/documents/src/inbound/axum_router/get_branch_name.rs
index c4f7d0ff86..50d61486d4 100644
--- a/rust/cloud-storage/documents/src/inbound/axum_router/get_branch_name.rs
+++ b/rust/cloud-storage/documents/src/inbound/axum_router/get_branch_name.rs
@@ -55,10 +55,12 @@ pub async fn get_branch_name_handler<T: DocumentService, Svc: EntityAccessServic
let document = state.service.get_document(receipt.clone()).await?;
let short_id = state.service.get_short_id(receipt).await?;
- match document.document_metadata.sub_type {
+ match document.document_metadata.metadata.sub_type {
Some(DocumentSubType::Task) => {
- let branch_name =
- build_task_branch_name(&short_id, &document.document_metadata.document_name);
+ let branch_name = build_task_branch_name(
+ &short_id,
+ &document.document_metadata.metadata.document_name,
+ );
Ok(Json(BranchNameResponse {
short_id,
branch_name,
diff --git a/rust/cloud-storage/documents/src/inbound/axum_router/get_document.rs b/rust/cloud-storage/documents/src/inbound/axum_router/get_document.rs
index 56a3303166..4ad18530f1 100644
--- a/rust/cloud-storage/documents/src/inbound/axum_router/get_document.rs
+++ b/rust/cloud-storage/documents/src/inbound/axum_router/get_document.rs
@@ -6,13 +6,13 @@ use axum::{
};
use entity_access::domain::ports::EntityAccessService;
use entity_access::inbound::axum_extractors::DocumentAccessExtractor;
-use model::document::response::GetDocumentResponse;
use model::user::UserContext;
use models_permissions::share_permission::access_level::ViewAccessLevel;
use super::{DocumentRouterState, Params};
use crate::domain::models::DocumentError;
use crate::domain::ports::DocumentService;
+use crate::domain::response::GetDocumentResponse;
/// Handler for `GET /documents/{document_id}`.
///
diff --git a/rust/cloud-storage/documents/src/inbound/axum_router/get_location.rs b/rust/cloud-storage/documents/src/inbound/axum_router/get_location.rs
index 83828f49a4..eb91e926c7 100644
--- a/rust/cloud-storage/documents/src/inbound/axum_router/get_location.rs
+++ b/rust/cloud-storage/documents/src/inbound/axum_router/get_location.rs
@@ -8,12 +8,13 @@ use axum::{
use entity_access::domain::ports::EntityAccessService;
use entity_access::inbound::axum_extractors::DocumentAccessExtractor;
use model::document::DocumentBasic;
-use model::document::response::LocationResponseV3;
use models_permissions::share_permission::access_level::ViewAccessLevel;
use super::{DocumentRouterState, Params};
+use crate::domain::content::DocumentContentState;
use crate::domain::models::{DocumentError, LocationQueryParams};
use crate::domain::ports::DocumentService;
+use crate::domain::response::LocationResponseV3;
/// Handler for `GET /documents/{document_id}/location_v3`.
///
@@ -29,7 +30,7 @@ use crate::domain::ports::DocumentService;
("get_converted_docx_url" = Option<bool>, Query, description = "If true, this will return the converted docx url.")
),
responses(
- (status = 200),
+ (status = 200, body = LocationResponseV3),
(status = 401, body = model_error_response::ErrorResponse),
(status = 404, body = model_error_response::ErrorResponse),
(status = 410, body = model_error_response::ErrorResponse),
@@ -51,7 +52,12 @@ pub async fn get_location_v3_handler<T: DocumentService, Svc: EntityAccessServic
let mut header_map = HeaderMap::new();
header_map.append("content-type", "application/json".parse().unwrap());
- header_map.append("Cache-Control", "max-age-300".parse().unwrap());
+ let cache_control = if response_data.content().state == DocumentContentState::Ready {
+ "max-age=300"
+ } else {
+ "no-store"
+ };
+ header_map.append("Cache-Control", cache_control.parse().unwrap());
Ok((header_map, Json(response_data)))
}
diff --git a/rust/cloud-storage/documents/src/inbound/toolset/create_document.rs b/rust/cloud-storage/documents/src/inbound/toolset/create_document.rs
index 0e80168de3..55078d1b7d 100644
--- a/rust/cloud-storage/documents/src/inbound/toolset/create_document.rs
+++ b/rust/cloud-storage/documents/src/inbound/toolset/create_document.rs
@@ -2,22 +2,33 @@
use std::str::FromStr;
-use crate::domain::models::CreateTaskRequest;
-use crate::domain::{models::CreateDocumentRepoArgs, ports::DocumentService};
+use crate::domain::create::{NewDocumentMetadata, NewPlainTextDocument};
+use crate::domain::models::DocumentError;
+use crate::domain::ports::DocumentService;
+use crate::domain::ports::create::DocumentCreationService;
use ai::tool::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
use anyhow::Context;
use async_trait::async_trait;
-use base64::Engine;
use entity_access::domain::ports::EntityAccessService;
use macro_user_id::user_id::MacroUserIdStr;
-use model_file_type::FileType;
+use model::document::FileType;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
-use sha2::Digest;
-use sha2::Sha256;
use super::DocumentToolContext;
+fn failed_to_create_document(error: DocumentError) -> ToolCallError {
+ let description = match &error {
+ DocumentError::BadRequest(message) => message.clone(),
+ _ => "failed to create document".to_string(),
+ };
+
+ ToolCallError {
+ description,
+ internal_error: error.into(),
+ }
+}
+
/// The read content response
#[derive(Debug, Serialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
@@ -47,12 +58,11 @@ pub struct CreateDocument {
#[async_trait]
impl<DSvc, ESvc> AsyncTool<DocumentToolContext<DSvc, ESvc>> for CreateDocument
where
- DSvc: DocumentService,
+ DSvc: DocumentService + DocumentCreationService,
ESvc: EntityAccessService,
{
type Output = CreateDocumentResponse;
- #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]
async fn call(
&self,
service_context: ServiceContext<DocumentToolContext<DSvc, ESvc>>,
@@ -65,129 +75,41 @@ where
description: format!("invalid file extension {}", self.file_extension),
internal_error: e.into(),
})?;
- let content_type = parsed_file_type.mime_type();
-
let user_id: MacroUserIdStr<'static> = request_context.user_id.clone();
- let file_bytes = self.file_content.as_bytes();
-
- let hashes = get_file_shas(file_bytes).map_err(|e| ToolCallError {
- description: "could not get file content shas".to_string(),
- internal_error: e,
- })?;
- tracing::trace!("got file shas");
-
- let document_response = service_context
- .service
- .create_document(
- user_id.clone(),
- CreateDocumentRepoArgs {
- id: None,
- sha: hashes.0,
- document_name: self.document_name.clone(),
- user_id: user_id.clone(),
- file_type: Some(parsed_file_type),
- project_id: None,
- email_attachment_id: None,
- created_at: None,
- is_task: self.is_task,
- skip_history: false,
- },
- None, // job_id
- )
+ let document =
+ NewPlainTextDocument::builder(NewDocumentMetadata::new(self.document_name.clone()))
+ .file_type(parsed_file_type)
+ .text(self.file_content.clone())
+ .task_flag(self.is_task)
+ .build()
+ .map_err(failed_to_create_document)?;
+
+ let response = service_context
+ .creator
+ .create_plain_text(user_id, document)
.await
- .map_err(|e| ToolCallError {
- description: "failed to create document".to_string(),
- internal_error: e.into(),
- })?;
- tracing::trace!("created document");
-
- // if the document is a task we need to assign the default properties for the task like status and assignee
- if self.is_task {
- let document_id = &document_response
- .document_response
- .document_metadata
- .document_id;
-
- tracing::trace!("assigning task properties");
- service_context
- .service
- .handle_task_properties(
- user_id.clone(),
- document_id,
- &CreateTaskRequest {
- task_name: self.document_name.clone(), // doesn't actually matter
- project_id: None,
- property_values: None, // uses default properties
- share_with_team: true,
- },
- )
- .await
- .map_err(|e| ToolCallError {
- description: "unable to assign task properties".to_string(),
- internal_error: e.into(),
- })?;
- }
-
- let document_response = document_response.document_response;
- let document_metadata = document_response.document_metadata;
-
- let presigned_url = document_response
- .presigned_url
- .context("expected presigned url")
- .map_err(|e| ToolCallError {
- description: "presigned url was not generated".to_string(),
- internal_error: e,
- })?;
+ .map(|document| document.into_response())
+ .map_err(failed_to_create_document)?;
- let upload_response = reqwest::Client::new()
- .put(&presigned_url)
- .header("content-type", content_type)
- .header("x-amz-checksum-sha256", &hashes.1)
- .body(file_bytes.to_vec())
- .send()
- .await
- .map_err(|e| ToolCallError {
- description: "failed to upload file to presigned url".to_string(),
- internal_error: e.into(),
- })?;
-
- if !upload_response.status().is_success() {
- let status = upload_response.status();
- let body = upload_response.text().await.unwrap_or_default();
- return Err(ToolCallError {
- description: format!("presigned url upload failed with status {status}"),
- internal_error: anyhow::anyhow!("upload failed: {status} {body}"),
- });
- }
-
- tracing::info!("uploaded file");
+ tracing::trace!("created document");
- let document_id = document_metadata
+ let document_id_str = response
+ .document_response
+ .document_metadata
+ .metadata
.document_id
+ .to_string();
+
+ let document_id = document_id_str
.parse()
.context("expected valid uuid")
.map_err(|e| ToolCallError {
internal_error: e,
- description: format!(
- "invalid document id was output {}",
- document_metadata.document_id
- ),
+ description: format!("invalid document id was output {}", document_id_str),
})?;
tracing::info!("got to end");
Ok(CreateDocumentResponse { document_id })
}
}
-
-#[tracing::instrument(skip(file_content), err)]
-pub fn get_file_shas(file_content: &[u8]) -> anyhow::Result<(String, String)> {
- let mut hasher = Sha256::new();
- hasher.update(file_content);
- let file_hash_result = hasher.finalize();
- let base64_encoded_sha = base64::engine::general_purpose::STANDARD.encode(file_hash_result);
-
- let hash = format!("{:x}", file_hash_result);
-
- Ok((hash, base64_encoded_sha))
-}
diff --git a/rust/cloud-storage/documents/src/inbound/toolset/mod.rs b/rust/cloud-storage/documents/src/inbound/toolset/mod.rs
index 4949458e2d..126866af6f 100644
--- a/rust/cloud-storage/documents/src/inbound/toolset/mod.rs
+++ b/rust/cloud-storage/documents/src/inbound/toolset/mod.rs
@@ -8,18 +8,32 @@ mod read_metadata;
mod test;
use crate::{
+ domain::create::DocumentCreator,
domain::ports::DocumentService,
+ domain::ports::create::DocumentCreationService,
inbound::toolset::{
create_document::CreateDocument, read_content::ReadContent, read_metadata::ReadMetadata,
},
+ outbound::{
+ document_bytes_upload::ReqwestDocumentBytesUploader,
+ markdown_init::LexicalSyncMarkdownInitializer,
+ },
};
use ai::tool::AsyncToolSet;
use entity_access::domain::ports::EntityAccessService;
use lexical_client::LexicalClient;
use std::sync::Arc;
+use sync_service_client::SyncServiceClient;
+
+/// Default backend-owned document creation use case for document tools.
+pub type DefaultDocumentToolCreator<DSvc> =
+ DocumentCreator<Arc<DSvc>, LexicalSyncMarkdownInitializer, ReqwestDocumentBytesUploader>;
/// Service context for document AI tools
-pub struct DocumentToolContext<DSvc: DocumentService, ESvc: EntityAccessService> {
+pub struct DocumentToolContext<
+ DSvc: DocumentService + DocumentCreationService,
+ ESvc: EntityAccessService,
+> {
/// The document service instance
pub service: Arc<DSvc>,
/// The entity access service instance
@@ -27,25 +41,56 @@ pub struct DocumentToolContext<DSvc: DocumentService, ESvc: EntityAccessService>
/// The lexical client
pub lexical_client: Arc<LexicalClient>,
+
+ /// The sync-service client
+ pub sync_service_client: Arc<SyncServiceClient>,
+
+ /// Backend-owned document creation use case.
+ pub creator: DefaultDocumentToolCreator<DSvc>,
}
-impl<DSvc: DocumentService, ESvc: EntityAccessService> Clone for DocumentToolContext<DSvc, ESvc> {
+impl<DSvc: DocumentService + DocumentCreationService, ESvc: EntityAccessService> Clone
+ for DocumentToolContext<DSvc, ESvc>
+{
fn clone(&self) -> Self {
Self {
service: self.service.clone(),
entity_access_service: self.entity_access_service.clone(),
lexical_client: self.lexical_client.clone(),
+ sync_service_client: self.sync_service_client.clone(),
+ creator: self.creator.clone(),
}
}
}
-impl<DSvc: DocumentService, ESvc: EntityAccessService> DocumentToolContext<DSvc, ESvc> {
+impl<DSvc: DocumentService + DocumentCreationService, ESvc: EntityAccessService>
+ DocumentToolContext<DSvc, ESvc>
+{
/// Create a new document tool context
- pub fn new(service: DSvc, entity_access_service: ESvc, lexical_client: LexicalClient) -> Self {
+ pub fn new(
+ service: DSvc,
+ entity_access_service: ESvc,
+ lexical_client: LexicalClient,
+ sync_service_client: SyncServiceClient,
+ ) -> Self {
+ let service = Arc::new(service);
+ let lexical_client = Arc::new(lexical_client);
+ let sync_service_client = Arc::new(sync_service_client);
+ let creator = DocumentCreator::new(
+ service.clone(),
+ LexicalSyncMarkdownInitializer::new(
+ lexical_client.as_ref().clone(),
+ sync_service_client.as_ref().clone(),
+ ),
+ ReqwestDocumentBytesUploader::default(),
+ );
+
Self {
- service: Arc::new(service),
+ service,
entity_access_service: Arc::new(entity_access_service),
- lexical_client: Arc::new(lexical_client),
+ lexical_client,
+ sync_service_client,
+ creator,
}
}
}
@@ -53,7 +98,7 @@ impl<DSvc: DocumentService, ESvc: EntityAccessService> DocumentToolContext<DSvc,
/// Create a document toolset
pub fn document_toolset<DSvc, ESvc>() -> AsyncToolSet<DocumentToolContext<DSvc, ESvc>>
where
- DSvc: DocumentService,
+ DSvc: DocumentService + DocumentCreationService,
ESvc: EntityAccessService,
{
AsyncToolSet::new()
diff --git a/rust/cloud-storage/documents/src/inbound/toolset/read_content.rs b/rust/cloud-storage/documents/src/inbound/toolset/read_content.rs
index cd6d7814ab..766bf4a13e 100644
--- a/rust/cloud-storage/documents/src/inbound/toolset/read_content.rs
+++ b/rust/cloud-storage/documents/src/inbound/toolset/read_content.rs
@@ -4,7 +4,8 @@ use std::str::FromStr;
use crate::domain::{
models::{CommentThread, LocationQueryParams},
- ports::DocumentService,
+ ports::{DocumentService, create::DocumentCreationService},
+ response::LocationResponseV3,
};
use ai::tool::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
use async_trait::async_trait;
@@ -75,7 +76,7 @@ pub struct ReadContent {
#[async_trait]
impl<DSvc, ESvc> AsyncTool<DocumentToolContext<DSvc, ESvc>> for ReadContent
where
- DSvc: DocumentService,
+ DSvc: DocumentService + DocumentCreationService,
ESvc: EntityAccessService,
{
type Output = ReadContentResponse;
@@ -187,7 +188,10 @@ where
/// Gets the document content from location
#[tracing::instrument(skip(service_context), err)]
-async fn get_document_content_from_location<DSvc: DocumentService, ESvc: EntityAccessService>(
+async fn get_document_content_from_location<
+ DSvc: DocumentService + DocumentCreationService,
+ ESvc: EntityAccessService,
+>(
service_context: ServiceContext<DocumentToolContext<DSvc, ESvc>>,
document_context: &DocumentBasic,
entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,
@@ -205,9 +209,10 @@ async fn get_document_content_from_location<DSvc: DocumentService, ESvc: EntityA
.await?;
let presigned_url = match location {
- model::document::response::LocationResponseV3::PresignedUrl {
+ LocationResponseV3::PresignedUrl {
presigned_url,
metadata: _metadata,
+ content: _content,
} => presigned_url,
// This should only be called with text documents which result in 1 presigned url
_ => unreachable!(),
diff --git a/rust/cloud-storage/documents/src/inbound/toolset/read_metadata.rs b/rust/cloud-storage/documents/src/inbound/toolset/read_metadata.rs
index 7c2f3df4ed..544bafe1bb 100644
--- a/rust/cloud-storage/documents/src/inbound/toolset/read_metadata.rs
+++ b/rust/cloud-storage/documents/src/inbound/toolset/read_metadata.rs
@@ -1,13 +1,13 @@
//! ReadMetadata tool for reading document metadata.
-use crate::domain::ports::DocumentService;
+use crate::domain::ports::{DocumentService, create::DocumentCreationService};
+use crate::domain::response::DocumentMetadataWithContent;
use ai::tool::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
use async_trait::async_trait;
use entity_access::domain::{
models::{AccessLevel, EntityType},
ports::EntityAccessService,
};
-use model::document::DocumentMetadata;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
@@ -20,7 +20,7 @@ use crate::domain::branch_name::build_task_branch_name;
pub struct ReadDocumentMetadata {
/// The document metadata
#[serde(flatten)]
- document: DocumentMetadata,
+ document: DocumentMetadataWithContent,
/// If the document is a "task" the branch name of the document will be provided.
#[serde(skip_serializing_if = "Option::is_none")]
branch_name: Option<String>,
@@ -46,7 +46,7 @@ pub struct ReadMetadata {
#[async_trait]
impl<DSvc, ESvc> AsyncTool<DocumentToolContext<DSvc, ESvc>> for ReadMetadata
where
- DSvc: DocumentService,
+ DSvc: DocumentService + DocumentCreationService,
ESvc: EntityAccessService,
{
type Output = ReadMetadataResponse;
@@ -83,7 +83,7 @@ where
internal_error: e.into(),
})?;
- let branch_name = if let Some(sub_type) = result.document_metadata.sub_type {
+ let branch_name = if let Some(sub_type) = result.document_metadata.metadata.sub_type {
match sub_type {
document_sub_type::DocumentSubType::Task => {
let short_id = service_context
@@ -97,7 +97,7 @@ where
Some(build_task_branch_name(
&short_id,
- &result.document_metadata.document_name,
+ &result.document_metadata.metadata.document_name,
))
}
}
diff --git a/rust/cloud-storage/documents/src/lib.rs b/rust/cloud-storage/documents/src/lib.rs
index 6c4a1f28a9..be13da0013 100644
--- a/rust/cloud-storage/documents/src/lib.rs
+++ b/rust/cloud-storage/documents/src/lib.rs
@@ -15,5 +15,9 @@ pub mod domain;
#[cfg(any(feature = "inbound", feature = "ai_tools", feature = "attachment"))]
pub mod inbound;
-#[cfg(feature = "outbound")]
+#[cfg(any(
+ feature = "outbound",
+ feature = "markdown_init",
+ feature = "document_create_adapters"
+))]
pub mod outbound;
diff --git a/rust/cloud-storage/documents/src/outbound.rs b/rust/cloud-storage/documents/src/outbound.rs
index eae598689a..7aab536fb5 100644
--- a/rust/cloud-storage/documents/src/outbound.rs
+++ b/rust/cloud-storage/documents/src/outbound.rs
@@ -1,4 +1,10 @@
//! Outbound adapters for the documents domain.
+#[cfg(feature = "document_create_adapters")]
+pub mod document_bytes_upload;
+#[cfg(feature = "markdown_init")]
+pub mod markdown_init;
+#[cfg(feature = "outbound")]
pub mod pg_document_repo;
+#[cfg(feature = "outbound")]
pub mod s3_upload_url;
diff --git a/rust/cloud-storage/documents/src/outbound/document_bytes_upload.rs b/rust/cloud-storage/documents/src/outbound/document_bytes_upload.rs
new file mode 100644
index 0000000000..3d084b44a2
--- /dev/null
+++ b/rust/cloud-storage/documents/src/outbound/document_bytes_upload.rs
@@ -0,0 +1,50 @@
+//! Outbound adapter for uploading document bytes to presigned object-storage URLs.
+
+use crate::domain::models::DocumentError;
+use crate::domain::ports::create::{DocumentBytesUpload, DocumentBytesUploadPort};
+
+/// Document bytes uploader backed by reqwest.
+#[derive(Clone)]
+pub struct ReqwestDocumentBytesUploader {
+ http_client: reqwest::Client,
+}
+
+impl ReqwestDocumentBytesUploader {
+ /// Construct a reqwest-backed document bytes uploader.
+ pub fn new(http_client: reqwest::Client) -> Self {
+ Self { http_client }
+ }
+}
+
+impl Default for ReqwestDocumentBytesUploader {
+ fn default() -> Self {
+ Self::new(reqwest::Client::new())
+ }
+}
+
+impl DocumentBytesUploadPort for ReqwestDocumentBytesUploader {
+ async fn upload_document_bytes(
+ &self,
+ upload: DocumentBytesUpload,
+ ) -> Result<(), DocumentError> {
+ let upload_response = self
+ .http_client
+ .put(&upload.presigned_url)
+ .header("content-type", &upload.content_type)
+ .header("x-amz-checksum-sha256", &upload.base64_sha256)
+ .body(upload.bytes)
+ .send()
+ .await
+ .map_err(|error| DocumentError::Internal(error.into()))?;
+
+ if !upload_response.status().is_success() {
+ let status = upload_response.status();
+ let body = upload_response.text().await.unwrap_or_default();
+ return Err(DocumentError::Internal(anyhow::anyhow!(
+ "presigned url upload failed: {status} {body}"
+ )));
+ }
+
+ Ok(())
+ }
+}
diff --git a/rust/cloud-storage/documents/src/outbound/markdown_init.rs b/rust/cloud-storage/documents/src/outbound/markdown_init.rs
new file mode 100644
index 0000000000..74db7ee61c
--- /dev/null
+++ b/rust/cloud-storage/documents/src/outbound/markdown_init.rs
@@ -0,0 +1,44 @@
+//! Outbound adapter for initializing markdown content through lexical-service and sync-service.
+
+use lexical_client::LexicalClient;
+use sync_service_client::SyncServiceClient;
+
+use crate::domain::models::DocumentError;
+use crate::domain::ports::markdown::MarkdownInitializationPort;
+
+/// Markdown initializer backed by lexical-service and sync-service clients.
+#[derive(Clone)]
+pub struct LexicalSyncMarkdownInitializer {
+ lexical_client: LexicalClient,
+ sync_service_client: SyncServiceClient,
+}
+
+impl LexicalSyncMarkdownInitializer {
+ /// Construct a lexical/sync-backed markdown initializer.
+ pub fn new(lexical_client: LexicalClient, sync_service_client: SyncServiceClient) -> Self {
+ Self {
+ lexical_client,
+ sync_service_client,
+ }
+ }
+}
+
+impl MarkdownInitializationPort for LexicalSyncMarkdownInitializer {
+ #[tracing::instrument(skip(self, markdown), err)]
+ async fn initialize_existing_markdown(
+ &self,
+ document_id: &str,
+ markdown: &str,
+ ) -> Result<(), DocumentError> {
+ let snapshot = self
+ .lexical_client
+ .markdown_to_loro_snapshot(markdown)
+ .await
+ .map_err(DocumentError::Internal)?;
+
+ self.sync_service_client
+ .initialize_from_snapshot(document_id, &snapshot)
+ .await
+ .map_err(DocumentError::Internal)
+ }
+}
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 673e40296c..8a33ef3d99 100644
--- a/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs
+++ b/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs
@@ -16,7 +16,9 @@ use model::document::{DocumentBasic, DocumentMetadata};
use sqlx::PgPool;
use model_entity::{Entity, EntityType};
+use sqlx::Row;
+use crate::domain::content::{DocumentContent, DocumentContentState};
use crate::domain::models::{
Comment, CommentThread, CopyDocumentRepoArgs, CreateDocumentRepoArgs, EditDocumentRepoArgs,
Thread,
@@ -563,6 +565,86 @@ impl DocumentRepo for PgDocumentRepo {
Ok(())
}
+ #[tracing::instrument(err, skip(self))]
+ async fn mark_document_uploaded(&self, document_id: &str) -> Result<(), Self::Err> {
+ let result = sqlx::query(
+ r#"
+ UPDATE "Document"
+ SET "uploaded" = true,
+ "contentState" = 'ready',
+ "contentLocation" = COALESCE("contentLocation", 'unknown'),
+ "updatedAt" = NOW()
+ WHERE id = $1
+ "#,
+ )
+ .bind(document_id)
+ .execute(&self.pool)
+ .await?;
+
+ if result.rows_affected() == 0 {
+ return Err(sqlx::Error::RowNotFound);
+ }
+
+ Ok(())
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn get_persisted_document_content(
+ &self,
+ document_id: &str,
+ ) -> Result<Option<DocumentContent>, Self::Err> {
+ let Some(row) = sqlx::query(
+ r#"
+ SELECT "contentState", "contentLocation"
+ FROM "Document"
+ WHERE id = $1
+ LIMIT 1
+ "#,
+ )
+ .bind(document_id)
+ .fetch_optional(&self.pool)
+ .await?
+ else {
+ return Ok(None);
+ };
+
+ let state: Option<String> = row.try_get("contentState")?;
+ let location: Option<String> = row.try_get("contentLocation")?;
+
+ Ok(state.and_then(|state| DocumentContent::from_db_columns(&state, location.as_deref())))
+ }
+
+ #[tracing::instrument(err, skip(self, content))]
+ async fn set_document_content(
+ &self,
+ document_id: &str,
+ content: DocumentContent,
+ ) -> Result<(), Self::Err> {
+ let uploaded = content.state == DocumentContentState::Ready;
+ let result = sqlx::query(
+ r#"
+ UPDATE "Document"
+ SET "uploaded" = $2,
+ "contentState" = $3,
+ "contentLocation" = $4,
+ "updatedAt" = NOW()
+ WHERE id = $1
+ "#,
+ )
+ .bind(document_id)
+ .bind(uploaded)
+ .bind(content.state_db_value())
+ .bind(content.location_db_value())
+ .execute(&self.pool)
+ .await?;
+
+ if result.rows_affected() == 0 {
+ return Err(sqlx::Error::RowNotFound);
+ }
+
+ Ok(())
+ }
+
#[tracing::instrument(err, skip(self))]
async fn share_with_team(&self, user_id: &str, document_id: &str) -> Result<(), Self::Err> {
share::share_with_team(&self.pool, user_id, document_id).await
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
index de7b21b7ba..0be485477e 100644
--- a/rust/cloud-storage/documents/src/outbound/pg_document_repo/create.rs
+++ b/rust/cloud-storage/documents/src/outbound/pg_document_repo/create.rs
@@ -1,7 +1,6 @@
use document_sub_type::DocumentSubType;
use macro_user_id::user_id::MacroUserIdStr;
-use model::document::VersionIDWithTimeStamps;
-use model_file_type::FileType;
+use model::document::{FileType, VersionIDWithTimeStamps};
use models_permissions::share_permission::SharePermissionV2;
/// Inserts a record into the document table
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 fa811f3b77..370cdf21ec 100644
--- a/rust/cloud-storage/documents/src/outbound/s3_upload_url.rs
+++ b/rust/cloud-storage/documents/src/outbound/s3_upload_url.rs
@@ -107,5 +107,5 @@ async fn put_presigned_url(
.presigned(PresigningConfig::expires_in(expiry_duration)?)
.await?;
- Ok(presigned_url.uri().to_string())
+ Ok(macro_aws_config::transform_aws_url(presigned_url.uri()))
}
diff --git a/rust/cloud-storage/github/src/domain/service/sync/mod.rs b/rust/cloud-storage/github/src/domain/service/sync/mod.rs
index 555bd33faf..d3d7c57a06 100644
--- a/rust/cloud-storage/github/src/domain/service/sync/mod.rs
+++ b/rust/cloud-storage/github/src/domain/service/sync/mod.rs
@@ -171,11 +171,11 @@ impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient> GithubSyncServi
match self.document_service.get_document(entity_access).await {
Ok(document) => {
- if let Some(sub_type) = document.document_metadata.sub_type
+ if let Some(sub_type) = document.document_metadata.metadata.sub_type
&& sub_type.to_string() == "task"
{
- let doc_name = &document.document_metadata.document_name;
- let doc_id = &document.document_metadata.document_id;
+ let doc_name = &document.document_metadata.metadata.document_name;
+ let doc_id = &document.document_metadata.metadata.document_id;
tracing::trace!(task_id=%uuid, doc_id, doc_name, "resolved task document");
doc_ids.push(doc_id.clone());
diff --git a/rust/cloud-storage/github/src/domain/service/sync/test.rs b/rust/cloud-storage/github/src/domain/service/sync/test.rs
index 594db4344f..424c56c18a 100644
--- a/rust/cloud-storage/github/src/domain/service/sync/test.rs
+++ b/rust/cloud-storage/github/src/domain/service/sync/test.rs
@@ -11,17 +11,19 @@ use crate::domain::{
use document_sub_type::DocumentSubType;
use documents::domain::models::EditDocumentServiceArgs;
use documents::domain::{
+ content::{DocumentContent, DocumentContentLocation},
models::{CreateDocumentRepoArgs, DocumentError, LocationQueryParams},
ports::DocumentService,
+ response::{
+ CreateDocumentResponseData, DocumentMetadataWithContent, DocumentResponse,
+ GetDocumentResponseData, LocationResponseV3,
+ },
};
use entity_access::domain::models::{
EditAccessLevel, EntityAccessReceipt, OwnerAccessLevel, ViewAccessLevel,
};
use macro_user_id::user_id::MacroUserIdStr;
-use model::document::{
- DocumentBasic, DocumentMetadata,
- response::{CreateDocumentResponseData, GetDocumentResponseData, LocationResponseV3},
-};
+use model::document::{DocumentBasic, DocumentMetadata};
use model_entity::Entity;
use models_permissions::share_permission::access_level::AccessLevel;
@@ -134,7 +136,10 @@ impl DocumentService for StubDocumentService {
let document_id = receipt.entity().entity_id.clone();
if document_id == KNOWN_TASK_UUID {
Ok(GetDocumentResponseData {
- document_metadata: Self::task_metadata(&document_id),
+ document_metadata: DocumentMetadataWithContent::new(
+ Self::task_metadata(&document_id),
+ DocumentContent::ready(DocumentContentLocation::SyncService),
+ ),
user_access_level: AccessLevel::Owner,
view_location: None,
})
@@ -171,6 +176,12 @@ impl DocumentService for StubDocumentService {
) -> Result<CreateDocumentResponseData, DocumentError> {
unimplemented!()
}
+ async fn get_document_content(
+ &self,
+ _document_context: &DocumentBasic,
+ ) -> Result<DocumentContent, DocumentError> {
+ unimplemented!()
+ }
async fn update_task_status(
&self,
receipt: EntityAccessReceipt<EditAccessLevel>,
@@ -200,16 +211,7 @@ impl DocumentService for StubDocumentService {
_document_name: String,
_query_version_id: Option<i64>,
_sync_version_id: Option<model::sync_service::SyncServiceVersionID>,
- ) -> Result<model::document::response::DocumentResponse, DocumentError> {
- unimplemented!()
- }
-
- async fn create_task(
- &self,
- _user_id: MacroUserIdStr<'static>,
- _plain_user_id: String,
- _request: documents::domain::models::CreateTaskRequest,
- ) -> Result<documents::domain::models::CreateTaskResponse, DocumentError> {
+ ) -> Result<DocumentResponse, DocumentError> {
unimplemented!()
}
diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfile
index a688e66f2c..3400824eca 100644
--- a/rust/cloud-storage/justfile
+++ b/rust/cloud-storage/justfile
@@ -40,6 +40,7 @@ build_lambdas compiler="":
ulimit -n 10240 && just dataloss_prevention_handler/build {{compiler}}
ulimit -n 10240 && just search_upload_handler/build {{compiler}}
ulimit -n 10240 && just document_text_extractor/build {{compiler}}
+ ulimit -n 10240 && just document_upload_finalizer_handler/build {{compiler}}
ulimit -n 10240 && just email_suppression_handler/build {{compiler}}
ulimit -n 10240 && just deleted_item_poller/build {{compiler}}
ulimit -n 10240 && just email_refresh_handler/build {{compiler}}
diff --git a/rust/cloud-storage/macro_aws_config/src/lib.rs b/rust/cloud-storage/macro_aws_config/src/lib.rs
index e03625f19b..44b0ca5c5c 100644
--- a/rust/cloud-storage/macro_aws_config/src/lib.rs
+++ b/rust/cloud-storage/macro_aws_config/src/lib.rs
@@ -55,6 +55,16 @@ fn transform_local_url(url: &str) -> String {
// NOTE: it is ok to use expect as this is only run locally
let parsed = url::Url::parse(url).expect("valid url");
let host = parsed.host_str().unwrap();
+ let port = parsed.port().unwrap_or(4566);
+ let path = parsed.path();
+ let query = parsed.query().map(|q| format!("?{q}")).unwrap_or_default();
+
+ // Path-style LocalStack URLs generated inside Docker use `localstack` as
+ // the host, which the browser on the host machine cannot resolve. Keep the
+ // existing path (`/{bucket}/{key}`) and only swap the host to localhost.
+ if host == "localstack" || host == "localhost" {
+ return format!("http://localhost:{port}{path}{query}");
+ }
// hostname should be in the form {asset}.localstack or {asset}.localhost
let asset = host
@@ -62,10 +72,6 @@ fn transform_local_url(url: &str) -> String {
.or_else(|| host.strip_suffix(".localhost"))
.unwrap();
- let port = parsed.port().unwrap_or(4566);
- let path = parsed.path();
- let query = parsed.query().map(|q| format!("?{q}")).unwrap_or_default();
-
format!("http://localhost:{port}/{asset}{path}{query}")
}
diff --git a/rust/cloud-storage/macro_aws_config/src/test.rs b/rust/cloud-storage/macro_aws_config/src/test.rs
index 22052b46ec..0f696f48f9 100644
--- a/rust/cloud-storage/macro_aws_config/src/test.rs
+++ b/rust/cloud-storage/macro_aws_config/src/test.rs
@@ -1,5 +1,23 @@
use super::*;
+#[test]
+fn test_transform_path_style_localstack() {
+ let input = "http://localstack:4566/doc-storage/macro%7Cteo%40macro.com/doc/1?x-id=PutObject";
+ let expected = "http://localhost:4566/doc-storage/macro%7Cteo%40macro.com/doc/1?x-id=PutObject";
+
+ let result = transform_local_url(input);
+ assert_eq!(result, expected);
+}
+
+#[test]
+fn test_transform_path_style_localhost() {
+ let input = "http://localhost:4566/doc-storage/macro%7Cteo%40macro.com/doc/1?x-id=PutObject";
+ let expected = "http://localhost:4566/doc-storage/macro%7Cteo%40macro.com/doc/1?x-id=PutObject";
+
+ let result = transform_local_url(input);
+ assert_eq!(result, expected);
+}
+
#[test]
fn test_transform_presigned_url_with_query_params_localstack() {
let input = "http://static-file-storage.localstack:4566/file/a31e9af3-dd26-4531-b367-bfbbbac706cc?x-id=PutObject&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=ANOTREAL%2F20260203%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20260203T184319Z&X-Amz-Expires=120&X-Amz-SignedHeaders=content-type%3Bhost&X-Amz-Signature=deed6b123a18335b61567eaf8ddb7ea6e00bf264cfd80cb0f4031860235dc077";
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260511223000_document_content_lifecycle.sql b/rust/cloud-storage/macro_db_client/migrations/20260511223000_document_content_lifecycle.sql
new file mode 100644
index 0000000000..0a495ae4d2
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260511223000_document_content_lifecycle.sql
@@ -0,0 +1,39 @@
+-- Markdown rows are initialized to `unknown` when already uploaded because the
+-- authoritative location requires checking sync-service. Run the custom
+-- dry-run/apply script after this schema migration:
+-- cargo run -p document_storage_service --bin backfill_markdown_content_location -- --apply
+
+ALTER TABLE "Document"
+ ADD COLUMN "contentState" TEXT,
+ ADD COLUMN "contentLocation" TEXT;
+
+UPDATE "Document"
+SET
+ "contentState" = CASE
+ WHEN uploaded THEN 'ready'
+ ELSE 'pending'
+ END,
+ "contentLocation" = CASE
+ WHEN uploaded AND "fileType" = 'docx' THEN 'converted_pdf'
+ WHEN uploaded AND "fileType" = 'md' THEN 'unknown'
+ WHEN uploaded THEN 'object_storage'
+ WHEN "fileType" = 'docx' THEN 'converted_pdf'
+ ELSE 'object_storage'
+ END;
+
+ALTER TABLE "Document"
+ ALTER COLUMN "contentState" SET DEFAULT 'pending',
+ ALTER COLUMN "contentState" SET NOT NULL,
+ ADD CONSTRAINT "Document_contentState_check"
+ CHECK ("contentState" IN ('unknown', 'pending', 'ready')),
+ ADD CONSTRAINT "Document_contentLocation_check"
+ CHECK (
+ "contentLocation" IS NULL OR
+ "contentLocation" IN (
+ 'object_storage',
+ 'sync_service',
+ 'docx_bom_parts',
+ 'converted_pdf',
+ 'unknown'
+ )
+ );
diff --git a/rust/cloud-storage/macro_db_client/src/document/get_document_list.rs b/rust/cloud-storage/macro_db_client/src/document/get_document_list.rs
index 536514812c..9f965cd355 100644
--- a/rust/cloud-storage/macro_db_client/src/document/get_document_list.rs
+++ b/rust/cloud-storage/macro_db_client/src/document/get_document_list.rs
@@ -58,6 +58,7 @@ pub async fn get_document_list(
mod tests {
use super::*;
use sqlx::{Pool, Postgres};
+ use std::collections::HashSet;
#[sqlx::test(fixtures(path = "../../fixtures", scripts("basic_user_with_lots_of_documents")))]
async fn test_get_document_search(pool: Pool<Postgres>) {
@@ -67,22 +68,22 @@ mod tests {
assert_eq!(documents.len(), 7);
- let document_ids: Vec<(String, i64)> = documents
+ let document_ids: HashSet<(String, i64)> = documents
.iter()
.map(|doc| (doc.document_id.clone(), doc.document_version_id))
.collect();
assert_eq!(
document_ids,
- vec![
+ HashSet::from([
("document-one".to_string(), 1),
("document-two".to_string(), 2),
("document-three".to_string(), 3),
("document-four".to_string(), 4),
("document-five".to_string(), 5),
("document-six".to_string(), 6),
- ("document-seven".to_string(), 1)
- ]
+ ("document-seven".to_string(), 1),
+ ])
);
}
}
diff --git a/rust/cloud-storage/macro_db_client/src/docx_unzip/mod.rs b/rust/cloud-storage/macro_db_client/src/docx_unzip/mod.rs
index 02039ac631..f6ef5dee8f 100644
--- a/rust/cloud-storage/macro_db_client/src/docx_unzip/mod.rs
+++ b/rust/cloud-storage/macro_db_client/src/docx_unzip/mod.rs
@@ -40,10 +40,20 @@ pub async fn update_uploaded_status(
db: &sqlx::Pool<sqlx::Postgres>,
document_id: &str,
) -> anyhow::Result<()> {
- sqlx::query!(
- r#"UPDATE "Document" SET "uploaded" = true WHERE id = $1"#,
- document_id
+ sqlx::query(
+ r#"
+ UPDATE "Document"
+ SET "uploaded" = true,
+ "contentState" = CASE
+ WHEN "contentState" = 'ready' AND "contentLocation" = 'converted_pdf'
+ THEN 'ready'
+ ELSE 'pending'
+ END,
+ "contentLocation" = 'converted_pdf'
+ WHERE id = $1
+ "#,
)
+ .bind(document_id)
.execute(db)
.await?;
@@ -130,17 +140,18 @@ mod tests {
let uploaded = sqlx::query!(
r#"
- SELECT uploaded
+ SELECT uploaded, "contentState", "contentLocation"
FROM "Document"
WHERE id = $1
"#,
"document-one"
)
- .map(|row| row.uploaded)
.fetch_one(&pool)
.await?;
- assert!(uploaded);
+ assert!(uploaded.uploaded);
+ assert_eq!(uploaded.contentState, "pending");
+ assert_eq!(uploaded.contentLocation.as_deref(), Some("converted_pdf"));
Ok(())
}
diff --git a/rust/cloud-storage/mcp_service/src/context.rs b/rust/cloud-storage/mcp_service/src/context.rs
index 1565a2b151..cf3569683c 100644
--- a/rust/cloud-storage/mcp_service/src/context.rs
+++ b/rust/cloud-storage/mcp_service/src/context.rs
@@ -220,6 +220,7 @@ async fn build_tool_context(
document_service,
entity_access_service,
lexical_client_for_tools,
+ sync_service_client.clone(),
);
let properties_service = properties::PropertiesServiceImpl::new(
diff --git a/rust/cloud-storage/memory/src/context.rs b/rust/cloud-storage/memory/src/context.rs
index 6fea68add4..3c9ea6e937 100644
--- a/rust/cloud-storage/memory/src/context.rs
+++ b/rust/cloud-storage/memory/src/context.rs
@@ -126,6 +126,7 @@ pub async fn build_tool_service_context(
document_service,
(*entity_access_service).clone(),
lexical_client,
+ sync_client.as_ref().clone(),
);
// Properties tool context