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: make opening documents faster by using loro snapshots (#3781)

Wolf Mermelsteinc6b5f825f8ba
diff --git a/docker-compose.yml b/docker-compose.yml
index d81f6479c8..ffd9b6b402 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -133,10 +133,13 @@ services:
command: ["/app/out/document_storage_service"]
ports:
- "8086:8080"
+ environment:
+ - OVERRIDE_SYNC_SERVICE_URL=http://sync-service:8787
depends_on:
- redis
- connection_gateway
- authentication-service
+ - sync_service
networks:
databases:
services:
@@ -366,6 +369,7 @@ services:
services:
aliases:
- sync-service
+ databases:
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8787/health"]
interval: 30s
diff --git a/js/app/packages/block-md/component/Block.tsx b/js/app/packages/block-md/component/Block.tsx
index dd066a3ddf..5c6496efa1 100644
--- a/js/app/packages/block-md/component/Block.tsx
+++ b/js/app/packages/block-md/component/Block.tsx
@@ -2,17 +2,21 @@ import { useGlobalNotificationSource } from '@app/component/GlobalAppState';
import { useBlockEntityCommands } from '@app/component/next-soup/actions';
import { SidePanel } from '@app/component/side-panel';
import { useBlockId } from '@core/block';
-import { createLoroManager } from '@core/collab/manager';
+import { createLoroManager, type LoroManager } from '@core/collab/manager';
import type { InitialSync, TimeoutError } from '@core/collab/source';
import { DocumentBlockContainer } from '@core/component/DocumentBlockContainer';
import { ENABLE_MARKDOWN_SIDE_PANEL } from '@core/constant/featureFlags';
import { blockErrorSignal } from '@core/signal/load';
import { useCanEdit } from '@core/signal/permissions';
-import { MARKDOWN_LORO_SCHEMA } from '@lexical-core/markdown-loro-schema';
+import {
+ MARKDOWN_LORO_SCHEMA,
+ type MarkdownLoroSchemaType,
+} from '@lexical-core/markdown-loro-schema';
import { DocumentDebouncedNotificationReadMarker } from '@notifications';
import { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';
+import { storageServiceClient } from '@service-storage/client';
import { Scroll } from '@ui';
-import type { Result } from 'neverthrow';
+import { err, ok, type Result } from 'neverthrow';
import {
createEffect,
createMemo,
@@ -37,6 +41,89 @@ export interface BlockMarkdownProps {
optimisticSnapshot?: Uint8Array<ArrayBufferLike>;
}
+type SyncError = 'UNAUTHORIZED' | 'INVALID' | 'GONE';
+
+type BlockData = NonNullable<ReturnType<typeof blockDataSignal>>;
+
+async function syncFromOptimistic({
+ data,
+ loroManager,
+ optimisticSnapshot,
+}: {
+ data: BlockData;
+ loroManager: LoroManager<MarkdownLoroSchemaType>;
+ optimisticSnapshot: Uint8Array<ArrayBufferLike>;
+}): Promise<Result<void, SyncError>> {
+ await loroManager.initializeFromSnapshot(optimisticSnapshot);
+
+ const syncResult: Result<InitialSync, TimeoutError> =
+ await data.doInitialSync();
+
+ if (syncResult.isErr()) {
+ console.error('Failed to receive initial sync', syncResult.error);
+ return err('INVALID');
+ }
+
+ data.syncSource.pushUpdate(
+ loroManager.getDoc().export({ mode: 'update' }),
+ loroManager.getPeerId()
+ );
+
+ return ok();
+}
+
+async function syncFromDO({
+ data,
+ loroManager,
+ blockId,
+}: {
+ data: BlockData;
+ loroManager: LoroManager<MarkdownLoroSchemaType>;
+ blockId: string;
+}): Promise<Result<void, SyncError>> {
+ let gotDoSnapshot = false;
+
+ // unawaited: only use S3 snapshot if DO hasn't responded first
+ // NOTE: gotDoSnapshot flips to true when DO snapshot is used, and it may
+ // happen WHILE we are fetching a cached snapshot THEORETICALLY
+ (async () => {
+ try {
+ const result = await storageServiceClient.fetchCachedSnapshot(blockId);
+ if (!gotDoSnapshot && result.isOk()) {
+ await loroManager.initializeFromSnapshot(result.value);
+ }
+ } catch (error) {
+ console.warn('Failed to load cached snapshot', error);
+ }
+ })();
+
+ try {
+ const syncResult: Result<InitialSync, TimeoutError> =
+ await data.doInitialSync();
+
+ if (syncResult.isErr()) {
+ console.error('Failed to receive initial sync', syncResult.error);
+ return err('INVALID');
+ }
+
+ const result = await loroManager.initializeFromSnapshot(
+ syncResult.value.snapshot
+ );
+
+ gotDoSnapshot = true;
+
+ if (result.isErr()) {
+ console.error('Failed to initialize loro doc', result.error);
+ return err('INVALID');
+ }
+ } catch (error) {
+ console.error('Failed to sync from DO', error);
+ return err('INVALID');
+ }
+
+ return ok();
+}
+
export default function BlockMarkdown(props: BlockMarkdownProps) {
return (
<MarkdownNameProvider>
@@ -62,45 +149,18 @@ function BlockMarkdownContent({ optimisticSnapshot }: BlockMarkdownProps) {
} else {
setBlockError(null);
}
-
if (optimisticSnapshot) {
- loroManager.initializeFromSnapshot(optimisticSnapshot).then(() => {
- data
- .doInitialSync()
- .then((syncResult: Result<InitialSync, TimeoutError>) => {
- if (syncResult.isErr()) {
- console.error(
- 'Failed to receive initial sync',
- syncResult.error
- );
- setBlockError('INVALID');
- return;
- }
- const peerId = loroManager.getPeerId();
- data.syncSource.pushUpdate(
- loroManager.getDoc().export({ mode: 'update' }),
- peerId
- );
- });
- });
+ // unawaited
+ syncFromOptimistic({ data, loroManager, optimisticSnapshot }).then(
+ (r) => {
+ if (r.isErr()) setBlockError(r.error);
+ }
+ );
} else {
- data
- .doInitialSync()
- .then((syncResult: Result<InitialSync, TimeoutError>) => {
- if (syncResult.isErr()) {
- console.error('Failed to receive initial sync', syncResult.error);
- setBlockError('INVALID');
- return;
- }
- loroManager
- .initializeFromSnapshot(syncResult.value.snapshot)
- .then((result) => {
- if (result.isErr()) {
- console.error('Failed to initialize loro doc', result.error);
- setBlockError('INVALID');
- }
- });
- });
+ // unawaited
+ syncFromDO({ data, loroManager, blockId }).then((r) => {
+ if (r.isErr()) setBlockError(r.error);
+ });
}
})
);
diff --git a/js/app/packages/core/component/LexicalMarkdown/collaboration/undo.ts b/js/app/packages/core/component/LexicalMarkdown/collaboration/undo.ts
index 246a85ccbf..2efc645dfa 100644
--- a/js/app/packages/core/component/LexicalMarkdown/collaboration/undo.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/collaboration/undo.ts
@@ -223,6 +223,10 @@ export function registerLoroHistory(
let isGroupActive = false;
let prevChangeTime = Date.now();
let prevChangeType = OTHER;
+ // Don't record history until the editor has been initialized and CLEAR_HISTORY_COMMAND
+ // has been dispatched. Without this guard, setEditorState during initialization triggers
+ // groupStart() on a Loro doc that may have no committed ops, causing a WASM panic.
+ let isReadyForHistory = false;
const getMergeAction = (
prevState: null | EditorState,
@@ -309,6 +313,10 @@ export function registerLoroHistory(
dirtyLeaves: Set<string>;
tags: Set<string>;
}): void => {
+ if (!isReadyForHistory) {
+ return;
+ }
+
const mergeAction = getMergeAction(
prevEditorState,
editorState,
@@ -393,6 +401,7 @@ export function registerLoroHistory(
isGroupActive = false;
}
undoManager.clear();
+ isReadyForHistory = true;
editor.dispatchCommand(CAN_UNDO_COMMAND, false);
editor.dispatchCommand(CAN_REDO_COMMAND, false);
return false;
@@ -410,6 +419,7 @@ export function registerLoroHistory(
isGroupActive = false;
}
undoManager.clear();
+ isReadyForHistory = true;
editor.dispatchCommand(CAN_UNDO_COMMAND, false);
editor.dispatchCommand(CAN_REDO_COMMAND, false);
return true;
diff --git a/js/app/packages/core/util/fetchWithToken.ts b/js/app/packages/core/util/fetchWithToken.ts
index de92596c5c..1347ccdad3 100644
--- a/js/app/packages/core/util/fetchWithToken.ts
+++ b/js/app/packages/core/util/fetchWithToken.ts
@@ -19,7 +19,7 @@ export type FetchWithTokenInit<CustomErrorCode extends string = never> =
};
function fetchWithCredentials<
- T extends ObjectLike,
+ T extends ObjectLike | Uint8Array,
CustomErrorCode extends string = never,
>(
input: RequestInfo,
@@ -109,7 +109,7 @@ export async function fetchToken(): Promise<
* }
*/
export async function fetchWithToken<
- T extends ObjectLike,
+ T extends ObjectLike | Uint8Array,
CustomErrorCode extends string = never,
>(
input: RequestInfo,
diff --git a/js/app/packages/core/util/safeFetch.ts b/js/app/packages/core/util/safeFetch.ts
index 477ee8ddd8..dddb10dcd6 100644
--- a/js/app/packages/core/util/safeFetch.ts
+++ b/js/app/packages/core/util/safeFetch.ts
@@ -153,7 +153,7 @@ export type TextResponse = { contentType: 'text/plain'; body: string };
* }
*/
export async function safeFetch<
- T extends ObjectLike & (TextResponse | {}),
+ T extends (ObjectLike & (TextResponse | {})) | Uint8Array,
CustomErrorCode extends string = never,
>(
input: RequestInfo,
@@ -232,6 +232,10 @@ export async function safeFetch<
return ok({ contentType, body: text } as T);
}
+ if (contentType.includes('application/octet-stream')) {
+ return ok(new Uint8Array(await response.arrayBuffer()) as T);
+ }
+
const data = await response.json();
return ok(data as T);
}
diff --git a/js/app/packages/service-clients/service-storage/client.ts b/js/app/packages/service-clients/service-storage/client.ts
index a9b028ce59..f92d9c6cab 100644
--- a/js/app/packages/service-clients/service-storage/client.ts
+++ b/js/app/packages/service-clients/service-storage/client.ts
@@ -1202,6 +1202,12 @@ export const storageServiceClient = {
).map((result) => result.data);
},
+ async fetchCachedSnapshot(
+ documentId: string
+ ): Promise<Result<Uint8Array, ResultError<FetchWithTokenErrorCode>[]>> {
+ return dssFetch<Uint8Array>(`/documents/${documentId}/cached_snapshot_url`);
+ },
+
async getDocumentShortId({
documentId,
}: {
diff --git a/js/lexical-core/markdown-loro-schema.ts b/js/lexical-core/markdown-loro-schema.ts
index c0f564d1df..98bc1d436d 100644
--- a/js/lexical-core/markdown-loro-schema.ts
+++ b/js/lexical-core/markdown-loro-schema.ts
@@ -30,3 +30,5 @@ markdownNodeSchema.definition.children.itemSchema = markdownNodeSchema;
export const MARKDOWN_LORO_SCHEMA = schema({
root: markdownNodeSchema,
});
+
+export type MarkdownLoroSchemaType = typeof MARKDOWN_LORO_SCHEMA;
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/mod.rs b/rust/cloud-storage/document_storage_service/src/api/documents/mod.rs
index 1672ca0459..2c98193bdd 100644
--- a/rust/cloud-storage/document_storage_service/src/api/documents/mod.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/documents/mod.rs
@@ -134,7 +134,8 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
)
.route(
"/{document_id}/processing",
- get(get_document_processing_result::handler).layer(ensure_document_exists_middleware),
+ get(get_document_processing_result::handler)
+ .layer(ensure_document_exists_middleware.clone()),
)
.with_state(state)
.route(
diff --git a/rust/cloud-storage/document_storage_service/src/api/internal/mod.rs b/rust/cloud-storage/document_storage_service/src/api/internal/mod.rs
index 8fee0eaf93..f49fa1c96a 100644
--- a/rust/cloud-storage/document_storage_service/src/api/internal/mod.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/internal/mod.rs
@@ -123,6 +123,15 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
"/documents/{document_id}/update",
put(put_document_update::handler),
)
+ .route(
+ "/documents/{document_id}/snapshot",
+ put(
+ documents_hex::inbound::axum_router::put_snapshot::put_snapshot_handler::<
+ DocumentService,
+ EntityAccessService,
+ >,
+ ),
+ )
.route("/documents/metadata", post(get_documents_metadata::handler))
// History routes
.route(
diff --git a/rust/cloud-storage/document_storage_service/src/service/s3/internal_presigned_helpers.rs b/rust/cloud-storage/document_storage_service/src/service/s3/internal_presigned_helpers.rs
new file mode 100644
index 0000000000..01c152b6d3
--- /dev/null
+++ b/rust/cloud-storage/document_storage_service/src/service/s3/internal_presigned_helpers.rs
@@ -0,0 +1,54 @@
+use std::time::Duration;
+
+use aws_sdk_s3 as s3;
+use aws_sdk_s3::presigning::PresigningConfig;
+
+const EXPIRY: Duration = Duration::from_secs(5 * 60);
+
+/// Generates a presigned PUT URL for service-to-service uploads of opaque
+/// blobs (e.g. CRDT snapshots). Unlike
+/// [`put_presigned_url::put_presigned_url`], this does not validate a SHA
+/// checksum or content type — the caller is trusted (another internal
+/// service) and the bytes are not user content.
+///
+/// Uses the docker-internal host in local dev so a service inside the docker
+/// network can reach LocalStack.
+pub(in crate::service::s3) async fn put_internal_presigned_url(
+ client: &s3::Client,
+ bucket: &str,
+ key: &str,
+) -> anyhow::Result<String> {
+ if cfg!(feature = "local") {
+ return Ok("fake".to_string());
+ }
+ let presigned = client
+ .put_object()
+ .bucket(bucket)
+ .key(key)
+ .presigned(PresigningConfig::expires_in(EXPIRY)?)
+ .await?;
+ Ok(macro_aws_config::transform_aws_url_for_internal_fetch(
+ presigned.uri(),
+ ))
+}
+
+/// Generates a presigned GET URL for the browser to fetch an opaque blob
+/// directly from S3 (e.g. CRDT snapshots used for optimistic seeds).
+/// Browser-facing transform — the user's browser resolves the URL via the
+/// host-mapped LocalStack port in local dev.
+pub(in crate::service::s3) async fn get_presigned_url(
+ client: &s3::Client,
+ bucket: &str,
+ key: &str,
+) -> anyhow::Result<String> {
+ if cfg!(feature = "local") {
+ return Ok("fake".to_string());
+ }
+ let presigned = client
+ .get_object()
+ .bucket(bucket)
+ .key(key)
+ .presigned(PresigningConfig::expires_in(EXPIRY)?)
+ .await?;
+ Ok(macro_aws_config::transform_aws_url(presigned.uri()))
+}
diff --git a/rust/cloud-storage/document_storage_service/src/service/s3/mod.rs b/rust/cloud-storage/document_storage_service/src/service/s3/mod.rs
index 64213b0b36..6aedc3f57a 100644
--- a/rust/cloud-storage/document_storage_service/src/service/s3/mod.rs
+++ b/rust/cloud-storage/document_storage_service/src/service/s3/mod.rs
@@ -7,6 +7,7 @@ mod delete;
mod exists;
mod get;
mod get_folder;
+mod internal_presigned_helpers;
mod put_presigned_url;
mod upload_document;
@@ -67,6 +68,24 @@ impl S3Client {
.await
}
+ pub async fn get_snapshot_presigned_url(&self, key: &str) -> anyhow::Result<String> {
+ internal_presigned_helpers::get_presigned_url(
+ &self.inner,
+ &self.document_storage_bucket,
+ key,
+ )
+ .await
+ }
+
+ pub async fn put_snapshot_presigned_url(&self, key: &str) -> anyhow::Result<String> {
+ internal_presigned_helpers::put_internal_presigned_url(
+ &self.inner,
+ &self.document_storage_bucket,
+ key,
+ )
+ .await
+ }
+
pub async fn put_document_storage_presigned_url(
&self,
key: &str,
diff --git a/rust/cloud-storage/documents/src/domain/ports/mod.rs b/rust/cloud-storage/documents/src/domain/ports/mod.rs
index 6dddc97291..cb5276c3a9 100644
--- a/rust/cloud-storage/documents/src/domain/ports/mod.rs
+++ b/rust/cloud-storage/documents/src/domain/ports/mod.rs
@@ -248,7 +248,7 @@ pub trait DocumentRepo: Send + Sync + 'static {
) -> impl Future<Output = Result<(), Self::Err>> + Send;
}
-/// Port for generating S3 presigned upload URLs.
+/// Port for generating S3 presigned upload URLs and direct S3 storage operations.
pub trait PresignedUploadUrlPort: Send + Sync + 'static {
/// Generate a presigned URL for uploading to the document storage bucket.
fn put_document_storage_presigned_url(
@@ -272,6 +272,19 @@ pub trait PresignedUploadUrlPort: Send + Sync + 'static {
source_key: &str,
destination_key: &str,
) -> impl Future<Output = anyhow::Result<()>> + Send;
+
+ /// Returns the raw bytes of the cached Loro snapshot, or `None` if no snapshot exists.
+ fn get_snapshot(
+ &self,
+ document_id: &str,
+ ) -> impl Future<Output = anyhow::Result<Option<Vec<u8>>>> + Send;
+
+ /// Stores raw snapshot bytes in object storage for the given document.
+ fn upload_snapshot(
+ &self,
+ document_id: &str,
+ bytes: Vec<u8>,
+ ) -> impl Future<Output = anyhow::Result<()>> + Send;
}
/// Port for attaching task system properties.
@@ -433,6 +446,18 @@ pub trait DocumentService: Send + Sync + 'static {
request: &CreateTaskRequest,
) -> impl Future<Output = Result<(), DocumentError>> + Send;
+ /// Returns the raw bytes of the cached Loro snapshot, or `None` if no snapshot exists.
+ fn get_snapshot(
+ &self,
+ document_id: &str,
+ ) -> impl Future<Output = anyhow::Result<Option<Vec<u8>>>> + Send;
+
+ /// Stores raw snapshot bytes in object storage for the given document.
+ fn upload_snapshot(
+ &self,
+ document_id: &str,
+ bytes: Vec<u8>,
+ ) -> impl Future<Output = anyhow::Result<()>> + Send;
/// Get the team-share state of a document, resolved against the owner's team.
fn get_team_share(
&self,
diff --git a/rust/cloud-storage/documents/src/domain/service.rs b/rust/cloud-storage/documents/src/domain/service.rs
index 6317875e03..d0686b117a 100644
--- a/rust/cloud-storage/documents/src/domain/service.rs
+++ b/rust/cloud-storage/documents/src/domain/service.rs
@@ -1405,6 +1405,16 @@ impl<
Ok(())
}
+ async fn get_snapshot(&self, document_id: &str) -> anyhow::Result<Option<Vec<u8>>> {
+ self.upload_url_service.get_snapshot(document_id).await
+ }
+
+ async fn upload_snapshot(&self, document_id: &str, bytes: Vec<u8>) -> anyhow::Result<()> {
+ self.upload_url_service
+ .upload_snapshot(document_id, bytes)
+ .await
+ }
+
/// 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/service/tests.rs b/rust/cloud-storage/documents/src/domain/service/tests.rs
index 5ec6166361..0409595503 100644
--- a/rust/cloud-storage/documents/src/domain/service/tests.rs
+++ b/rust/cloud-storage/documents/src/domain/service/tests.rs
@@ -106,6 +106,14 @@ impl PresignedUploadUrlPort for TestUploadUrlPort {
async fn copy_object(&self, _source_key: &str, _destination_key: &str) -> anyhow::Result<()> {
Ok(())
}
+
+ async fn get_snapshot(&self, _document_id: &str) -> anyhow::Result<Option<Vec<u8>>> {
+ Ok(None)
+ }
+
+ async fn upload_snapshot(&self, _document_id: &str, _bytes: Vec<u8>) -> anyhow::Result<()> {
+ Ok(())
+ }
}
struct TestTaskPropertiesPort;
diff --git a/rust/cloud-storage/documents/src/inbound/axum_router.rs b/rust/cloud-storage/documents/src/inbound/axum_router.rs
index 1a37249f5c..5cfe43912c 100644
--- a/rust/cloud-storage/documents/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/documents/src/inbound/axum_router.rs
@@ -25,10 +25,12 @@ pub mod create_task;
pub mod delete_document;
pub mod edit_document;
pub mod get_branch_name;
+pub mod get_cached_snapshot_url;
pub mod get_document;
pub mod get_github_pull_requests;
pub mod get_location;
pub mod get_short_id;
+pub mod put_snapshot;
pub mod task_duplicates;
pub mod team_share;
@@ -59,10 +61,12 @@ use self::{
delete_document::delete_document_handler,
edit_document::edit_document_handler,
get_branch_name::get_branch_name_handler,
+ get_cached_snapshot_url::get_cached_snapshot_url_handler,
get_document::get_document_handler,
get_github_pull_requests::get_github_pull_requests_handler,
get_location::get_location_v3_handler,
get_short_id::get_short_id_handler,
+ put_snapshot::put_snapshot_handler,
task_duplicates::{
delete_this_duplicate_task_handler, dismiss_task_duplicates_handler,
get_task_duplicates_handler, task_similarity_search_handler,
@@ -197,6 +201,14 @@ where
"/{document_id}/duplicates/{match_id}/delete_this",
axum::routing::post(delete_this_duplicate_task_handler::<T, Svc>),
)
+ .route(
+ "/{document_id}/cached_snapshot_url",
+ axum::routing::get(get_cached_snapshot_url_handler::<T, Svc>),
+ )
+ .route(
+ "/{document_id}/snapshot",
+ axum::routing::put(put_snapshot_handler::<T, Svc>),
+ )
.route(
"/{document_id}/team_share",
axum::routing::get(get_team_share_handler::<T, Svc>)
diff --git a/rust/cloud-storage/documents/src/inbound/axum_router/get_cached_snapshot_url.rs b/rust/cloud-storage/documents/src/inbound/axum_router/get_cached_snapshot_url.rs
new file mode 100644
index 0000000000..fdf1dc0c20
--- /dev/null
+++ b/rust/cloud-storage/documents/src/inbound/axum_router/get_cached_snapshot_url.rs
@@ -0,0 +1,36 @@
+//! Handler for `GET /documents/{document_id}/cached_snapshot`.
+
+use axum::{
+ body::Body,
+ extract::{Path, State},
+ http::{Response, StatusCode},
+ response::IntoResponse,
+};
+use entity_access::domain::ports::EntityAccessService;
+use entity_access::inbound::axum_extractors::DocumentAccessExtractor;
+use models_permissions::share_permission::access_level::ViewAccessLevel;
+
+use super::{DocumentRouterState, Params};
+use crate::domain::ports::DocumentService;
+
+/// Proxies the cached Loro snapshot bytes, or 404 if none exists.
+#[tracing::instrument(skip(state, _access))]
+pub async fn get_cached_snapshot_url_handler<T: DocumentService, Svc: EntityAccessService>(
+ _access: DocumentAccessExtractor<ViewAccessLevel, Svc>,
+ State(state): State<DocumentRouterState<T, Svc>>,
+ Path(Params { document_id }): Path<Params>,
+) -> impl IntoResponse {
+ match state.service.get_snapshot(&document_id).await {
+ Ok(Some(bytes)) => Response::builder()
+ .status(StatusCode::OK)
+ .header("Content-Type", "application/octet-stream")
+ .body(Body::from(bytes))
+ .unwrap()
+ .into_response(),
+ Ok(None) => StatusCode::NOT_FOUND.into_response(),
+ Err(e) => {
+ tracing::error!(error=?e, document_id=document_id, "failed to get snapshot");
+ StatusCode::INTERNAL_SERVER_ERROR.into_response()
+ }
+ }
+}
diff --git a/rust/cloud-storage/documents/src/inbound/axum_router/put_snapshot.rs b/rust/cloud-storage/documents/src/inbound/axum_router/put_snapshot.rs
new file mode 100644
index 0000000000..cb11d6898c
--- /dev/null
+++ b/rust/cloud-storage/documents/src/inbound/axum_router/put_snapshot.rs
@@ -0,0 +1,32 @@
+//! Handler for `PUT /documents/{document_id}/snapshot`.
+
+use axum::{
+ body::Bytes,
+ extract::{Path, State},
+ http::StatusCode,
+ response::IntoResponse,
+};
+use entity_access::domain::ports::EntityAccessService;
+
+use super::{DocumentRouterState, Params};
+use crate::domain::ports::DocumentService;
+
+/// Accepts raw snapshot bytes and stores them in S3.
+#[tracing::instrument(skip(state, body))]
+pub async fn put_snapshot_handler<T: DocumentService, Svc: EntityAccessService>(
+ State(state): State<DocumentRouterState<T, Svc>>,
+ Path(Params { document_id }): Path<Params>,
+ body: Bytes,
+) -> impl IntoResponse {
+ match state
+ .service
+ .upload_snapshot(&document_id, body.to_vec())
+ .await
+ {
+ Ok(()) => StatusCode::OK.into_response(),
+ Err(e) => {
+ tracing::error!(error=?e, document_id=document_id, "failed to upload snapshot");
+ StatusCode::INTERNAL_SERVER_ERROR.into_response()
+ }
+ }
+}
diff --git a/rust/cloud-storage/documents/src/outbound/markdown_init.rs b/rust/cloud-storage/documents/src/outbound/markdown_init.rs
index 98946e3eca..5d7bd566e4 100644
--- a/rust/cloud-storage/documents/src/outbound/markdown_init.rs
+++ b/rust/cloud-storage/documents/src/outbound/markdown_init.rs
@@ -80,9 +80,12 @@ where
// initialized eventually," in both cases, but just for now we just
// do it for the blank document case only.
tokio::spawn(async move {
- let _ = sync_service_client
+ if let Err(e) = sync_service_client
.initialize_from_snapshot(&document_id, MARKDOWN_GOLDEN_SNAPSHOT)
- .await;
+ .await
+ {
+ tracing::error!(error=?e, "failed to initialize document from snapshot");
+ }
});
Ok(())
diff --git a/rust/cloud-storage/documents/src/outbound/s3_upload_url.rs b/rust/cloud-storage/documents/src/outbound/s3_upload_url.rs
index 370cdf21ec..de603f12c5 100644
--- a/rust/cloud-storage/documents/src/outbound/s3_upload_url.rs
+++ b/rust/cloud-storage/documents/src/outbound/s3_upload_url.rs
@@ -1,14 +1,19 @@
-//! S3 adapter for generating presigned upload URLs.
+//! S3 adapter for generating presigned upload URLs and direct S3 storage operations.
use std::time::Duration;
use anyhow::Context;
-use aws_sdk_s3::presigning::PresigningConfig;
+use aws_sdk_s3::{presigning::PresigningConfig, primitives::ByteStream};
use base64::Engine;
use model::document::ContentType;
+use s3_key::SYNC_SERVICE_SNAPSHOT_PREFIX;
use crate::domain::ports::PresignedUploadUrlPort;
+fn snapshot_key(document_id: &str) -> String {
+ format!("{SYNC_SERVICE_SNAPSHOT_PREFIX}/{document_id}")
+}
+
/// Adapter implementing [`PresignedUploadUrlPort`] backed by an `aws_sdk_s3::Client`.
pub struct S3UploadUrlAdapter {
client: aws_sdk_s3::Client,
@@ -82,6 +87,53 @@ impl PresignedUploadUrlPort for S3UploadUrlAdapter {
Ok(())
}
+
+ #[tracing::instrument(skip(self), err)]
+ async fn get_snapshot(&self, document_id: &str) -> anyhow::Result<Option<Vec<u8>>> {
+ let key = snapshot_key(document_id);
+
+ let resp = self
+ .client
+ .get_object()
+ .bucket(&self.document_storage_bucket)
+ .key(&key)
+ .send()
+ .await;
+
+ match resp {
+ Err(e) if e.as_service_error().map(|e| e.is_no_such_key()) == Some(true) => Ok(None),
+ Err(e) => Err(e).context("failed get_object for snapshot"),
+ Ok(output) => {
+ let bytes = output
+ .body
+ .collect()
+ .await
+ .context("failed to read snapshot body")?
+ .into_bytes()
+ .to_vec();
+ Ok(Some(bytes))
+ }
+ }
+ }
+
+ #[tracing::instrument(skip(self, bytes), err)]
+ async fn upload_snapshot(&self, document_id: &str, bytes: Vec<u8>) -> anyhow::Result<()> {
+ if macro_aws_config::is_local_aws() {
+ return Ok(());
+ }
+
+ let key = snapshot_key(document_id);
+ self.client
+ .put_object()
+ .bucket(&self.document_storage_bucket)
+ .key(&key)
+ .body(ByteStream::from(bytes))
+ .send()
+ .await
+ .context("failed to upload snapshot")?;
+
+ Ok(())
+ }
}
async fn put_presigned_url(
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 5bbb8c00b4..9c46d59869 100644
--- a/rust/cloud-storage/github/src/domain/service/sync/test.rs
+++ b/rust/cloud-storage/github/src/domain/service/sync/test.rs
@@ -272,6 +272,14 @@ impl DocumentService for StubDocumentService {
) -> Result<(), DocumentError> {
unimplemented!()
}
+
+ async fn get_snapshot(&self, _document_id: &str) -> anyhow::Result<Option<Vec<u8>>> {
+ unimplemented!()
+ }
+
+ async fn upload_snapshot(&self, _document_id: &str, _bytes: Vec<u8>) -> anyhow::Result<()> {
+ unimplemented!()
+ }
}
/// Stateful stub repo that tracks task IDs per github key.
diff --git a/rust/cloud-storage/s3_key/src/document_key.rs b/rust/cloud-storage/s3_key/src/document_key.rs
index f2e1259ed5..35bbcac414 100644
--- a/rust/cloud-storage/s3_key/src/document_key.rs
+++ b/rust/cloud-storage/s3_key/src/document_key.rs
@@ -6,6 +6,10 @@ pub const CONVERTED_DOCUMENT_FILE_NAME: &str = "converted";
/// The prefix used for temporary files in S3.
pub const TEMP_FILE_PREFIX: &str = "temp_files";
+/// The prefix used for sync-service CRDT snapshot cache objects in the document
+/// storage bucket. Snapshot keys are `{SYNC_SERVICE_SNAPSHOT_PREFIX}/{document_id}`.
+pub const SYNC_SERVICE_SNAPSHOT_PREFIX: &str = "sync_service_snapshot";
+
/// The file extension for PDF files.
pub const PDF_EXTENSION: &str = "pdf";
diff --git a/rust/cloud-storage/s3_key/src/lib.rs b/rust/cloud-storage/s3_key/src/lib.rs
index 0a1de12a49..3b0d3eab34 100644
--- a/rust/cloud-storage/s3_key/src/lib.rs
+++ b/rust/cloud-storage/s3_key/src/lib.rs
@@ -4,9 +4,10 @@
mod document_key;
pub use document_key::{
- CONVERTED_DOCUMENT_FILE_NAME, DOCX_EXTENSION, DocumentKey, PDF_EXTENSION, TEMP_FILE_PREFIX,
- build_cloud_storage_bucket_document_key, build_docx_staging_bucket_document_key,
- build_docx_to_pdf_converted_document_key, build_temp_docx_key,
+ CONVERTED_DOCUMENT_FILE_NAME, DOCX_EXTENSION, DocumentKey, PDF_EXTENSION,
+ SYNC_SERVICE_SNAPSHOT_PREFIX, TEMP_FILE_PREFIX, build_cloud_storage_bucket_document_key,
+ build_docx_staging_bucket_document_key, build_docx_to_pdf_converted_document_key,
+ build_temp_docx_key,
};
mod bulk_upload_key;
pub use bulk_upload_key::BulkUploadStagingKey;
diff --git a/rust/sync-service/src/constants.rs b/rust/sync-service/src/constants.rs
index 4d3576e5c3..4e534e11ed 100644
--- a/rust/sync-service/src/constants.rs
+++ b/rust/sync-service/src/constants.rs
@@ -1,5 +1,7 @@
pub mod header_names {
pub const MACRO_INTERNAL_AUTH_KEY_HEADER_KEY: &str = "x-internal-auth-key";
+ pub const MACRO_DOCUMENT_STORAGE_SERVICE_AUTH_HEADER_KEY: &str =
+ "x-document-storage-service-auth-key";
pub const AUTHORIZATION: &str = "Authorization";
}
diff --git a/rust/sync-service/src/dss_internal.rs b/rust/sync-service/src/dss_internal.rs
new file mode 100644
index 0000000000..f8db6156b6
--- /dev/null
+++ b/rust/sync-service/src/dss_internal.rs
@@ -0,0 +1,72 @@
+use tracing::error;
+use worker::{Env, Fetch, Method, Request, RequestInit};
+
+use crate::constants::header_names::MACRO_DOCUMENT_STORAGE_SERVICE_AUTH_HEADER_KEY;
+
+pub trait DssInternal {
+ async fn publish_shallow_snapshot(
+ &self,
+ document_id: &str,
+ snapshot: &[u8],
+ ) -> worker::Result<()>;
+}
+
+pub struct DssInternalClient<'a> {
+ env: &'a Env,
+}
+
+impl<'a> DssInternalClient<'a> {
+ pub fn new(env: &'a Env) -> Self {
+ Self { env }
+ }
+
+ fn dss_url(&self) -> worker::Result<String> {
+ Ok(self.env.var("DSS_URL")?.to_string())
+ }
+
+ fn internal_auth_key(&self) -> worker::Result<String> {
+ Ok(self.env.var("DSS_INTERNAL_AUTH_KEY")?.to_string())
+ }
+}
+
+impl DssInternal for DssInternalClient<'_> {
+ async fn publish_shallow_snapshot(
+ &self,
+ document_id: &str,
+ snapshot: &[u8],
+ ) -> worker::Result<()> {
+ let url = format!(
+ "{}/internal/documents/{}/snapshot",
+ self.dss_url()?,
+ document_id
+ );
+ let auth_key = self.internal_auth_key()?;
+
+ let mut req = Request::new_with_init(
+ &url,
+ RequestInit::new()
+ .with_method(Method::Put)
+ .with_body(Some(snapshot.to_vec().into())),
+ )?;
+ req.headers_mut()?
+ .set(MACRO_DOCUMENT_STORAGE_SERVICE_AUTH_HEADER_KEY, &auth_key)?;
+ req.headers_mut()?
+ .set("Content-Type", "application/octet-stream")?;
+
+ let resp = Fetch::Request(req).send().await?;
+ if resp.status_code() != 200 {
+ error!(
+ document_id = document_id,
+ status = resp.status_code(),
+ "DSS snapshot upload failed"
+ );
+ return Err(worker::Error::from(format!(
+ "DSS snapshot upload returned {}",
+ resp.status_code()
+ )));
+ }
+
+ tracing::trace!("snapshot uploaded to DSS");
+ Ok(())
+ }
+}
diff --git a/rust/sync-service/src/durable_object.rs b/rust/sync-service/src/durable_object.rs
index 57f649a67a..c68546ecc4 100644
--- a/rust/sync-service/src/durable_object.rs
+++ b/rust/sync-service/src/durable_object.rs
@@ -11,7 +11,7 @@ use matchit::Router;
use serde::{Deserialize, Serialize};
use tracing::{debug, error, info, instrument, trace, warn};
use worker::{
- Cors, Date, DurableObject, Env, Error, Method, Request, Response, ResponseBody,
+ Context, Cors, Date, DurableObject, Env, Error, Method, Request, Response, ResponseBody,
ResponseBuilder, Result, ScheduledTime, State, WebSocket, WebSocketIncomingMessage,
WebSocketPair, durable_object,
};
@@ -20,6 +20,7 @@ use crate::{
auth::{AccessLevel, TokenFrom, decode_jwt},
constants::USER_PEER_D1_BINDING,
d1::{PeerWithUserId, get_user_id_from_peer_id, insert_user_mapping},
+ dss_internal::{DssInternal, DssInternalClient},
error::ResultExt,
generated::schema::InitializeFromSnapshotRequest,
keepalive::{DEFAULT_TIME_TO_LIVE, keepalive},
@@ -902,6 +903,22 @@ impl DurableObject for DocumentSyncSession {
.context("failed deleting applied ops")?;
state.mark_exported();
+
+ let document_id = self.document_id().await.ok();
+ let env = self.env.clone();
+ self.state.wait_until(async move {
+ if let Some(document_id) = document_id
+ && let Ok(snapshot) = doc_state.export_shallow_snapshot()
+ {
+ // best effort
+ if let Err(err) = DssInternalClient::new(&env)
+ .publish_shallow_snapshot(&document_id, &snapshot)
+ .await
+ {
+ warn!(error =? err, "failed to push snapshot to DSS");
+ }
+ }
+ });
}
// Re-arm the alarm while clients are connected so the in-memory state
diff --git a/rust/sync-service/src/lib.rs b/rust/sync-service/src/lib.rs
index 732e7befce..990a5bc382 100644
--- a/rust/sync-service/src/lib.rs
+++ b/rust/sync-service/src/lib.rs
@@ -2,6 +2,7 @@ mod auth;
mod cf_worker;
mod constants;
mod d1;
+mod dss_internal;
mod durable_object;
mod error;
mod generated;
diff --git a/rust/sync-service/wrangler.docker.toml b/rust/sync-service/wrangler.docker.toml
index 54c02f33b0..607455f598 100644
--- a/rust/sync-service/wrangler.docker.toml
+++ b/rust/sync-service/wrangler.docker.toml
@@ -31,6 +31,8 @@ bucket_name = "document-snapshot-bucket-dev"
[vars]
INTERNAL_API_SECRET_KEY = "LOCAL_API_KEY"
SPS_URL = "https://search-processing-dev.macro.com"
+DSS_URL = "http://document_storage_service:8080"
+DSS_INTERNAL_AUTH_KEY = "local"
[[kv_namespaces]]
binding = "DOCUMENT_VERSIONING_KV"
diff --git a/rust/sync-service/wrangler.toml b/rust/sync-service/wrangler.toml
index 5229b054db..81d2f98b02 100644
--- a/rust/sync-service/wrangler.toml
+++ b/rust/sync-service/wrangler.toml
@@ -32,6 +32,8 @@ bucket_name = "document-snapshot-bucket-dev"
[vars]
INTERNAL_API_SECRET_KEY = "LOCAL_API_KEY"
SPS_URL = "https://search-processing-dev.macro.com"
+DSS_URL = "http://localhost:8086"
+DSS_INTERNAL_AUTH_KEY = "local"
[[kv_namespaces]]
binding = "DOCUMENT_VERSIONING_KV"
@@ -54,6 +56,7 @@ INTERNAL_API_SECRET_KEY = "SYNC_SERVICE_KEY_PLAYGROUND"
DOCUMENT_PERMISSIONS_SECRET = "local"
ENVIRONMENT = "development"
SPS_URL = "https://search-processing-dev.macro.com"
+DSS_URL = "https://document-storage-dev.macro.com"
[env.playground.durable_objects]
bindings = [
@@ -91,6 +94,7 @@ name = "sync-service-dev3"
INTERNAL_API_SECRET_KEY = "SYNC_SERVICE_KEY_DEV"
ENVIRONMENT = "development"
SPS_URL = "https://search-processing-dev.macro.com"
+DSS_URL = "https://document-storage-dev.macro.com"
[env.dev.durable_objects]
bindings = [
@@ -128,6 +132,7 @@ name = "sync-service-prod2"
INTERNAL_API_SECRET_KEY = "SYNC_SERVICE_KEY_PROD"
ENVIRONMENT = "production"
SPS_URL = "https://search-processing.macro.com"
+DSS_URL = "https://document-storage.macro.com"
[env.prod.durable_objects]
bindings = [