Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(dss/sync): backfill script (#3263)
teo071e1380d470
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 336c662233..a1d46895f6 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -3476,6 +3476,7 @@ dependencies = ["axum-extra","base64 0.22.1","chrono",+ "clap","cloudfront_sign","connection","document_sub_type",@@ -3489,6 +3490,7 @@ dependencies = ["lexical_client","macro_aws_config","macro_db_migrator",+ "macro_entrypoint","macro_user_id","macro_uuid","mockall",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.rsdeleted file mode 100644index 6ceb35215d..0000000000--- a/rust/cloud-storage/document_storage_service/src/bin/backfill_markdown_content_location.rs+++ /dev/null@@ -1,206 +0,0 @@-//! 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_upload_finalizer_handler/src/outbound.rs b/rust/cloud-storage/document_upload_finalizer_handler/src/outbound.rsindex 9102b17c24..f7b6a6c02d 100644--- a/rust/cloud-storage/document_upload_finalizer_handler/src/outbound.rs+++ b/rust/cloud-storage/document_upload_finalizer_handler/src/outbound.rs@@ -1,8 +1,8 @@-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 documents::outbound::s3_utf8_object_reader::S3Utf8ObjectReader;use model::document::DocumentBasic;use crate::ports::{DocumentObjectReader, DocumentUploadMetadataPort};@@ -10,36 +10,26 @@ use crate::ports::{DocumentObjectReader, DocumentUploadMetadataPort};/// S3-backed object reader for uploaded document bytes.#[derive(Clone)]pub struct S3DocumentObjectReader {- s3_client: aws_sdk_s3::Client,+ utf8_reader: S3Utf8ObjectReader,}impl S3DocumentObjectReader {/// Construct an S3 object reader.pub fn new(s3_client: aws_sdk_s3::Client) -> Self {- Self { s3_client }+ Self {+ utf8_reader: S3Utf8ObjectReader::new(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()+ self.utf8_reader+ .read_utf8(bucket, key).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}"))+ .map_err(|error| {+ anyhow::anyhow!("failed to read upload from s3://{bucket}/{key}: {error:?}")+ })}}diff --git a/rust/cloud-storage/documents/Cargo.toml b/rust/cloud-storage/documents/Cargo.tomlindex 032b903929..1144f9a592 100644--- a/rust/cloud-storage/documents/Cargo.toml+++ b/rust/cloud-storage/documents/Cargo.toml@@ -4,6 +4,11 @@ name = "documents"publish = falseversion = "0.1.0"+[[bin]]+name = "backfill_markdown_content_location"+path = "src/bin/backfill_markdown_content_location.rs"+required-features = ["backfill_binary"]+[features]attachment = ["dep:attachment",@@ -42,6 +47,7 @@ document_create_adapters = ["document_create","markdown_init",]+backfill_binary = ["dep:clap", "dep:macro_entrypoint", "markdown_init", "outbound", "ports"]inbound = ["axum", "document_create_adapters", "ports"]markdown_init = ["dep:lexical_client"]outbound = [@@ -59,6 +65,7 @@ service = ["dep:entity_access_management", "ports"]# Coreanyhow = { workspace = true }chrono = { workspace = true }+clap = { workspace = true, optional = true }serde = { workspace = true }serde_json = { workspace = true }thiserror = { workspace = true }@@ -77,6 +84,7 @@ entity_access_management = { path = "../entity_access_management", default-featu"ports",], optional = true }macro_aws_config = { path = "../macro_aws_config", features = ["s3"] }+macro_entrypoint = { path = "../macro_entrypoint", optional = true }macro_user_id = { path = "../macro_user_id" }macro_uuid = { path = "../macro_uuid" }model = { path = "../model" }diff --git a/rust/cloud-storage/documents/justfile b/rust/cloud-storage/documents/justfileindex 38c004ab6d..46e79a7f7c 100644--- a/rust/cloud-storage/documents/justfile+++ b/rust/cloud-storage/documents/justfile@@ -7,3 +7,82 @@ prepare_db:check:cargo check --all-features++# Dry-run markdown lifecycle backfill against dev DB/sync-service.+# Extra script flags can be passed directly after the recipe name, for example:+# just backfill_markdown_content_location_dev --limit 100 --batch-size 25+backfill_markdown_content_location_dev *FLAGS:+ #!/usr/bin/env bash+ set -euo pipefail+ DATABASE_URL="$(../scripts/rds_database_url.sh macro-db-dev macrodb-password-dev macrodb)"+ SYNC_SERVICE_AUTH_KEY="$(aws secretsmanager get-secret-value --secret-id sync-service-key-dev --query SecretString --output text)"+ INTERNAL_API_SECRET_KEY="$(aws secretsmanager get-secret-value --secret-id document-storage-service-auth-key-dev --query SecretString --output text)"+ eval "$(aws configure export-credentials --format env)"+ SYNC_SERVICE_URL="https://sync-service-dev3.macroverse.workers.dev"+ LEXICAL_SERVICE_URL="https://lexical-service-dev.macroverse.workers.dev"+ DOCUMENT_STORAGE_BUCKET="doc-storage-dev"+ RUST_LOG="${RUST_LOG:-info}" DATABASE_URL="$DATABASE_URL" SYNC_SERVICE_AUTH_KEY="$SYNC_SERVICE_AUTH_KEY" INTERNAL_API_SECRET_KEY="$INTERNAL_API_SECRET_KEY" SYNC_SERVICE_URL="$SYNC_SERVICE_URL" LEXICAL_SERVICE_URL="$LEXICAL_SERVICE_URL" DOCUMENT_STORAGE_BUCKET="$DOCUMENT_STORAGE_BUCKET" \+ cargo run -p documents --features backfill_binary --bin backfill_markdown_content_location -- {{ FLAGS }}++# Apply markdown lifecycle backfill against dev DB/sync-service.+# Extra script flags can be passed directly after the recipe name, for example:+# just backfill_markdown_content_location_dev_apply --limit 100 --batch-size 25+backfill_markdown_content_location_dev_apply *FLAGS:+ #!/usr/bin/env bash+ set -euo pipefail+ echo -e "\033[33mWARNING: this will update dev Document.contentState/contentLocation for markdown documents found in sync-service.\033[0m"+ echo -n "Continue? [y/N] "+ read -r response+ if [[ ! "$response" =~ ^[Yy]$ ]]; then+ echo "Backfill cancelled."+ exit 0+ fi+ DATABASE_URL="$(../scripts/rds_database_url.sh macro-db-dev macrodb-password-dev macrodb)"+ SYNC_SERVICE_AUTH_KEY="$(aws secretsmanager get-secret-value --secret-id sync-service-key-dev --query SecretString --output text)"+ INTERNAL_API_SECRET_KEY="$(aws secretsmanager get-secret-value --secret-id document-storage-service-auth-key-dev --query SecretString --output text)"+ eval "$(aws configure export-credentials --format env)"+ SYNC_SERVICE_URL="https://sync-service-dev3.macroverse.workers.dev"+ LEXICAL_SERVICE_URL="https://lexical-service-dev.macroverse.workers.dev"+ DOCUMENT_STORAGE_BUCKET="doc-storage-dev"+ RUST_LOG="${RUST_LOG:-info}" DATABASE_URL="$DATABASE_URL" SYNC_SERVICE_AUTH_KEY="$SYNC_SERVICE_AUTH_KEY" INTERNAL_API_SECRET_KEY="$INTERNAL_API_SECRET_KEY" SYNC_SERVICE_URL="$SYNC_SERVICE_URL" LEXICAL_SERVICE_URL="$LEXICAL_SERVICE_URL" DOCUMENT_STORAGE_BUCKET="$DOCUMENT_STORAGE_BUCKET" \+ cargo run -p documents --features backfill_binary --bin backfill_markdown_content_location -- --apply {{ FLAGS }}++# Dry-run markdown lifecycle backfill against prod DB/sync-service.+# Extra script flags can be passed directly after the recipe name, for example:+# just backfill_markdown_content_location_prod --limit 100 --batch-size 25+backfill_markdown_content_location_prod *FLAGS:+ #!/usr/bin/env bash+ set -euo pipefail+ DATABASE_URL="$(../scripts/rds_database_url.sh macro-db-prod macrodb-password-prod macrodb)"+ SYNC_SERVICE_AUTH_KEY="$(aws secretsmanager get-secret-value --secret-id sync-service-key-prod --query SecretString --output text)"+ INTERNAL_API_SECRET_KEY="$(aws secretsmanager get-secret-value --secret-id document-storage-service-auth-key-prod --query SecretString --output text)"+ eval "$(aws configure export-credentials --format env)"+ SYNC_SERVICE_URL="https://sync-service-prod2.macroverse.workers.dev"+ LEXICAL_SERVICE_URL="https://lexical-service.macroverse.workers.dev"+ DOCUMENT_STORAGE_BUCKET="macro-document-storage-prod"+ RUST_LOG="${RUST_LOG:-info}" DATABASE_URL="$DATABASE_URL" SYNC_SERVICE_AUTH_KEY="$SYNC_SERVICE_AUTH_KEY" INTERNAL_API_SECRET_KEY="$INTERNAL_API_SECRET_KEY" SYNC_SERVICE_URL="$SYNC_SERVICE_URL" LEXICAL_SERVICE_URL="$LEXICAL_SERVICE_URL" DOCUMENT_STORAGE_BUCKET="$DOCUMENT_STORAGE_BUCKET" \+ cargo run -p documents --features backfill_binary --bin backfill_markdown_content_location -- {{ FLAGS }}++# Apply markdown lifecycle backfill against prod DB/sync-service.+# Extra script flags can be passed directly after the recipe name, for example:+# just backfill_markdown_content_location_prod_apply --limit 100 --batch-size 25+backfill_markdown_content_location_prod_apply *FLAGS:+ #!/usr/bin/env bash+ set -euo pipefail+ echo -e "\033[31mWARNING: this will update PRODUCTION Document.contentState/contentLocation for markdown documents found in sync-service.\033[0m"+ echo -e "\033[31mThis may also initialize missing PRODUCTION sync-service documents if --initialize-missing is passed.\033[0m"+ echo -n "Type 'prod backfill' to continue: "+ read -r response+ if [[ "$response" != "prod backfill" ]]; then+ echo "Production backfill cancelled."+ exit 0+ fi+ DATABASE_URL="$(../scripts/rds_database_url.sh macro-db-prod macrodb-password-prod macrodb)"+ SYNC_SERVICE_AUTH_KEY="$(aws secretsmanager get-secret-value --secret-id sync-service-key-prod --query SecretString --output text)"+ INTERNAL_API_SECRET_KEY="$(aws secretsmanager get-secret-value --secret-id document-storage-service-auth-key-prod --query SecretString --output text)"+ eval "$(aws configure export-credentials --format env)"+ SYNC_SERVICE_URL="https://sync-service-prod2.macroverse.workers.dev"+ LEXICAL_SERVICE_URL="https://lexical-service.macroverse.workers.dev"+ DOCUMENT_STORAGE_BUCKET="macro-document-storage-prod"+ RUST_LOG="${RUST_LOG:-info}" DATABASE_URL="$DATABASE_URL" SYNC_SERVICE_AUTH_KEY="$SYNC_SERVICE_AUTH_KEY" INTERNAL_API_SECRET_KEY="$INTERNAL_API_SECRET_KEY" SYNC_SERVICE_URL="$SYNC_SERVICE_URL" LEXICAL_SERVICE_URL="$LEXICAL_SERVICE_URL" DOCUMENT_STORAGE_BUCKET="$DOCUMENT_STORAGE_BUCKET" \+ cargo run -p documents --features backfill_binary --bin backfill_markdown_content_location -- --apply {{ FLAGS }}diff --git a/rust/cloud-storage/documents/src/bin/backfill_markdown_content_location.rs b/rust/cloud-storage/documents/src/bin/backfill_markdown_content_location.rsnew file mode 100644index 0000000000..a8ba636b4b--- /dev/null+++ b/rust/cloud-storage/documents/src/bin/backfill_markdown_content_location.rs@@ -0,0 +1,264 @@+//! CLI for markdown document content lifecycle backfill.++use std::{env, time::Duration};++use anyhow::Context as _;+use clap::Parser;+use documents::domain::markdown_backfill::{+ MarkdownBackfillOptions, MarkdownBackfillReport, MarkdownBackfillService,+ MarkdownBackfillStats, MarkdownObjectReadError, MarkdownObjectReader,+};+use documents::domain::models::DocumentError;+use documents::domain::ports::markdown::MarkdownInitializationPort;+use documents::outbound::markdown_init::LexicalSyncMarkdownInitializer;+use documents::outbound::pg_document_repo::PgDocumentRepo;+use documents::outbound::s3_markdown_source::S3MarkdownObjectReader;+use lexical_client::LexicalClient;+use sqlx::postgres::PgPoolOptions;+use sync_service_client::SyncServiceClient;++/// Backfill markdown document content lifecycle from sync-service state.+#[derive(Clone, Debug, Parser)]+#[command(version, about)]+struct Args {+ /// Persist updates. Omit for dry-run.+ #[arg(long)]+ apply: bool,++ /// Initialize sync-service for missing markdown documents from S3 source bytes.+ #[arg(long)]+ initialize_missing: bool,++ /// Candidate rows fetched per DB batch.+ #[arg(long, default_value_t = 100)]+ batch_size: i64,++ /// Concurrent per-document sync/S3/init operations per batch.+ #[arg(long, default_value_t = 10)]+ concurrency: usize,++ /// Retries after the first sync-service exists attempt.+ #[arg(long, default_value_t = 2)]+ exists_retries: usize,++ /// Per-attempt sync-service exists timeout in seconds.+ #[arg(long, default_value_t = 10)]+ exists_timeout_secs: u64,++ /// Optional maximum candidate rows to scan.+ #[arg(long)]+ limit: Option<usize>,++ /// Optional exclusive document id cursor.+ #[arg(long)]+ start_after: Option<String>,+}++impl Args {+ fn options(&self) -> anyhow::Result<MarkdownBackfillOptions> {+ anyhow::ensure!(self.batch_size > 0, "--batch-size must be positive");+ anyhow::ensure!(self.concurrency > 0, "--concurrency must be positive");+ anyhow::ensure!(+ self.exists_timeout_secs > 0,+ "--exists-timeout-secs must be positive"+ );++ Ok(MarkdownBackfillOptions {+ apply: self.apply,+ batch_size: self.batch_size,+ concurrency: self.concurrency,+ exists_retries: self.exists_retries,+ exists_timeout: Duration::from_secs(self.exists_timeout_secs),+ limit: self.limit,+ start_after: self.start_after.clone(),+ initialize_missing: self.initialize_missing,+ })+ }+}++#[tokio::main]+async fn main() -> anyhow::Result<()> {+ macro_entrypoint::MacroEntrypoint::default().init();++ let args = Args::parse();+ let options = args.options()?;+ if !options.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")?;++ tracing::info!(+ apply = options.apply,+ initialize_missing = options.initialize_missing,+ batch_size = options.batch_size,+ concurrency = options.concurrency,+ exists_retries = options.exists_retries,+ exists_timeout_secs = options.exists_timeout.as_secs(),+ limit = ?options.limit,+ start_after = ?options.start_after,+ sync_service_url = %sync_service_url,+ "starting markdown content-location backfill"+ );++ let db = PgPoolOptions::new()+ .max_connections(5)+ .connect(&database_url)+ .await+ .context("failed to connect to postgres")?;++ let repo = PgDocumentRepo::new(db);+ let sync_probe =+ SyncServiceClient::new(sync_service_auth_key.clone(), sync_service_url.clone());+ let object_reader = build_object_reader(options.initialize_missing).await?;+ let markdown_initializer = build_markdown_initializer(+ options.apply && options.initialize_missing,+ sync_service_auth_key,+ sync_service_url,+ )?;++ let service =+ MarkdownBackfillService::new(repo, sync_probe, object_reader, markdown_initializer);+ let report = service.run(options.clone()).await?;++ tracing::info!(+ scanned = report.stats.scanned,+ sync_exists = report.stats.sync_exists,+ sync_missing = report.stats.sync_missing,+ would_update = report.stats.would_update,+ updated = report.stats.updated,+ would_initialize = report.stats.would_initialize,+ initialized = report.stats.initialized,+ object_missing = report.stats.object_missing,+ object_read_errors = report.stats.object_read_errors,+ invalid_utf8 = report.stats.invalid_utf8,+ initialize_errors = report.stats.initialize_errors,+ missing_document_instance = report.stats.missing_document_instance,+ sync_errors = report.stats.sync_errors,+ last_id = ?report.last_id,+ apply = options.apply,+ "markdown content-location backfill complete"+ );+ print_summary(&report, options.apply);++ Ok(())+}++fn build_markdown_initializer(+ enabled: bool,+ sync_service_auth_key: String,+ sync_service_url: String,+) -> anyhow::Result<OptionalMarkdownInitializer> {+ if !enabled {+ return Ok(OptionalMarkdownInitializer::Disabled);+ }++ let internal_api_secret_key = env::var("INTERNAL_API_SECRET_KEY")+ .context("INTERNAL_API_SECRET_KEY must be set when --initialize-missing is used")?;+ let lexical_service_url = env::var("LEXICAL_SERVICE_URL")+ .context("LEXICAL_SERVICE_URL must be set when --initialize-missing is used")?;++ Ok(OptionalMarkdownInitializer::Enabled(+ LexicalSyncMarkdownInitializer::new(+ LexicalClient::new(internal_api_secret_key, lexical_service_url),+ SyncServiceClient::new(sync_service_auth_key, sync_service_url),+ ),+ ))+}++async fn build_object_reader(enabled: bool) -> anyhow::Result<OptionalMarkdownObjectReader> {+ if !enabled {+ return Ok(OptionalMarkdownObjectReader::Disabled);+ }++ let document_storage_bucket = env::var("DOCUMENT_STORAGE_BUCKET")+ .context("DOCUMENT_STORAGE_BUCKET must be set when --initialize-missing is used")?;++ Ok(OptionalMarkdownObjectReader::Enabled(+ S3MarkdownObjectReader::new(document_storage_bucket, macro_aws_config::s3_client().await),+ ))+}++#[derive(Clone)]+enum OptionalMarkdownObjectReader {+ Disabled,+ Enabled(S3MarkdownObjectReader),+}++impl MarkdownObjectReader for OptionalMarkdownObjectReader {+ async fn read_markdown(+ &self,+ candidate: &documents::domain::markdown_backfill::MarkdownBackfillCandidate,+ ) -> Result<String, MarkdownObjectReadError> {+ match self {+ Self::Disabled => Err(MarkdownObjectReadError::Read {+ key: "<disabled>".to_string(),+ error: "markdown object reader disabled".to_string(),+ }),+ Self::Enabled(reader) => reader.read_markdown(candidate).await,+ }+ }+}++#[derive(Clone)]+enum OptionalMarkdownInitializer {+ Disabled,+ Enabled(LexicalSyncMarkdownInitializer),+}++impl MarkdownInitializationPort for OptionalMarkdownInitializer {+ async fn initialize_existing_markdown(+ &self,+ document_id: &str,+ markdown: &str,+ ) -> Result<(), DocumentError> {+ match self {+ Self::Disabled => Err(DocumentError::Internal(anyhow::anyhow!(+ "markdown initializer disabled"+ ))),+ Self::Enabled(initializer) => {+ initializer+ .initialize_existing_markdown(document_id, markdown)+ .await+ }+ }+ }+}++fn print_summary(report: &MarkdownBackfillReport, apply: bool) {+ let MarkdownBackfillStats {+ scanned,+ sync_exists,+ sync_missing,+ would_update,+ updated,+ would_initialize,+ initialized,+ object_missing,+ object_read_errors,+ invalid_utf8,+ initialize_errors,+ missing_document_instance,+ sync_errors,+ } = report.stats;++ println!("\nMarkdown backfill summary");+ println!(" apply: {apply}");+ println!(" scanned: {scanned}");+ println!(" sync_exists: {sync_exists}");+ println!(" sync_missing: {sync_missing}");+ println!(" would_update: {would_update}");+ println!(" updated: {updated}");+ println!(" would_initialize: {would_initialize}");+ println!(" initialized: {initialized}");+ println!(" object_missing: {object_missing}");+ println!(" object_read_errors: {object_read_errors}");+ println!(" invalid_utf8: {invalid_utf8}");+ println!(" initialize_errors: {initialize_errors}");+ println!(" missing_document_instance: {missing_document_instance}");+ println!(" sync_errors: {sync_errors}");+ println!(" last_id: {:?}", report.last_id);+}diff --git a/rust/cloud-storage/documents/src/domain.rs b/rust/cloud-storage/documents/src/domain.rsindex adfc88193e..137c5965cb 100644--- a/rust/cloud-storage/documents/src/domain.rs+++ b/rust/cloud-storage/documents/src/domain.rs@@ -2,6 +2,8 @@pub mod branch_name;pub mod content;+#[cfg(feature = "ports")]+pub mod markdown_backfill;#[cfg(feature = "document_create")]pub mod create;diff --git a/rust/cloud-storage/documents/src/domain/markdown_backfill.rs b/rust/cloud-storage/documents/src/domain/markdown_backfill.rsnew file mode 100644index 0000000000..bcacbc8834--- /dev/null+++ b/rust/cloud-storage/documents/src/domain/markdown_backfill.rs@@ -0,0 +1,483 @@+//! Domain service for backfilling markdown content lifecycle from sync-service state.++use std::{future::Future, time::Duration};++use anyhow::Context;+use futures::stream::{self, StreamExt};+use tokio::time::{sleep, timeout};++use crate::domain::models::DocumentError;+use crate::domain::ports::markdown::MarkdownInitializationPort;++/// Runtime options for markdown lifecycle backfill.+#[derive(Clone, Debug)]+pub struct MarkdownBackfillOptions {+ /// Persist DB lifecycle updates when true. Dry-run when false.+ pub apply: bool,+ /// Number of candidates to fetch per DB page.+ pub batch_size: i64,+ /// Maximum concurrent per-document sync/S3/init checks per batch.+ pub concurrency: usize,+ /// Number of retries after the first sync-service exists attempt.+ pub exists_retries: usize,+ /// Per-attempt sync-service exists timeout.+ pub exists_timeout: Duration,+ /// Optional maximum number of candidates to scan.+ pub limit: Option<usize>,+ /// Optional exclusive document-id cursor.+ pub start_after: Option<String>,+ /// Initialize missing sync-service documents from object storage.+ pub initialize_missing: bool,+}++/// One markdown document candidate for lifecycle backfill.+#[derive(Clone, Debug)]+pub struct MarkdownBackfillCandidate {+ /// Document id.+ pub id: String,+ /// Document owner user id.+ pub owner: String,+ /// Latest document instance id containing object-storage markdown bytes.+ pub document_instance_id: Option<i64>,+ /// Legacy uploaded flag.+ pub uploaded: bool,+ /// Current persisted content state.+ pub content_state: String,+ /// Current persisted content location.+ pub content_location: Option<String>,+}++/// Fetch and update markdown lifecycle metadata.+pub trait MarkdownBackfillRepo: Send + Sync {+ /// Fetch a page of markdown candidates not already `ready / sync_service`.+ fn fetch_markdown_backfill_candidates(+ &self,+ start_after: Option<&str>,+ limit: i64,+ ) -> impl Future<Output = anyhow::Result<Vec<MarkdownBackfillCandidate>>> + Send;++ /// Mark inspected candidate documents as `ready / sync_service` in one+ /// batch update. Implementations should use optimistic guards so rows are+ /// updated only if the latest document instance and lifecycle still match+ /// the inspected candidate values.+ fn mark_markdown_sync_service_ready(+ &self,+ candidates: &[MarkdownBackfillCandidate],+ ) -> impl Future<Output = anyhow::Result<u64>> + Send;+}++/// Checks sync-service document existence.+pub trait SyncServiceProbe: Send + Sync {+ /// Return true if sync-service already has the document.+ fn exists(&self, document_id: &str) -> impl Future<Output = anyhow::Result<bool>> + Send;+}++/// Reads original markdown content from object storage.+pub trait MarkdownObjectReader: Send + Sync {+ /// Read UTF-8 markdown content for a candidate.+ fn read_markdown(+ &self,+ candidate: &MarkdownBackfillCandidate,+ ) -> impl Future<Output = Result<String, MarkdownObjectReadError>> + Send;+}++/// Object-storage markdown read failure.+#[derive(Clone, Debug, thiserror::Error)]+pub enum MarkdownObjectReadError {+ /// The expected object-storage key does not exist.+ #[error("markdown object missing: {key}")]+ Missing {+ /// Expected S3 key.+ key: String,+ },+ /// Object read failed for reasons other than missing key.+ #[error("failed to read markdown object {key}: {error}")]+ Read {+ /// Expected S3 key.+ key: String,+ /// Read error details.+ error: String,+ },+ /// Object bytes were not valid UTF-8.+ #[error("markdown object {key} is not valid UTF-8: {error}")]+ InvalidUtf8 {+ /// Expected S3 key.+ key: String,+ /// UTF-8 decode error details.+ error: String,+ },+}++/// Accumulated markdown backfill counters.+#[derive(Clone, Debug, Default)]+pub struct MarkdownBackfillStats {+ /// Number of candidate rows scanned.+ pub scanned: usize,+ /// Number of scanned documents that already existed in sync-service.+ pub sync_exists: usize,+ /// Number of scanned documents missing from sync-service.+ pub sync_missing: usize,+ /// Dry-run count that would be marked ready because sync-service exists.+ pub would_update: usize,+ /// DB rows updated in apply mode.+ pub updated: usize,+ /// Dry-run count that would be initialized from object storage.+ pub would_initialize: usize,+ /// Apply count successfully initialized in sync-service.+ pub initialized: usize,+ /// Missing original markdown object count.+ pub object_missing: usize,+ /// Failed object read count.+ pub object_read_errors: usize,+ /// Invalid UTF-8 object count.+ pub invalid_utf8: usize,+ /// Failed sync-service initialization count.+ pub initialize_errors: usize,+ /// Missing document instance id count.+ pub missing_document_instance: usize,+ /// Sync-service exists check error count.+ pub sync_errors: usize,+}++impl MarkdownBackfillStats {+ fn add(&mut self, other: &Self) {+ self.scanned += other.scanned;+ self.sync_exists += other.sync_exists;+ self.sync_missing += other.sync_missing;+ self.would_update += other.would_update;+ self.updated += other.updated;+ self.would_initialize += other.would_initialize;+ self.initialized += other.initialized;+ self.object_missing += other.object_missing;+ self.object_read_errors += other.object_read_errors;+ self.invalid_utf8 += other.invalid_utf8;+ self.initialize_errors += other.initialize_errors;+ self.missing_document_instance += other.missing_document_instance;+ self.sync_errors += other.sync_errors;+ }+}++/// Final report returned by the backfill service.+#[derive(Clone, Debug)]+pub struct MarkdownBackfillReport {+ /// Aggregate counters.+ pub stats: MarkdownBackfillStats,+ /// Last scanned document id, usable with `start_after`.+ pub last_id: Option<String>,+}++/// Backfill service composed from hexagonal ports.+#[derive(Clone)]+pub struct MarkdownBackfillService<R, S, O, M> {+ repo: R,+ sync_service: S,+ object_reader: O,+ markdown_initializer: M,+}++impl<R, S, O, M> MarkdownBackfillService<R, S, O, M> {+ /// Construct a markdown backfill service.+ pub fn new(repo: R, sync_service: S, object_reader: O, markdown_initializer: M) -> Self {+ Self {+ repo,+ sync_service,+ object_reader,+ markdown_initializer,+ }+ }+}++impl<R, S, O, M> MarkdownBackfillService<R, S, O, M>+where+ R: MarkdownBackfillRepo + Clone,+ S: SyncServiceProbe + Clone,+ O: MarkdownObjectReader + Clone,+ M: MarkdownInitializationPort + Clone,+{+ /// Run the backfill until no candidates remain or `options.limit` is reached.+ pub async fn run(+ &self,+ options: MarkdownBackfillOptions,+ ) -> anyhow::Result<MarkdownBackfillReport> {+ let mut stats = MarkdownBackfillStats::default();+ let mut last_id = options.start_after.clone();++ loop {+ if options.limit.is_some_and(|limit| stats.scanned >= limit) {+ break;+ }++ let remaining_limit = options+ .limit+ .map(|limit| limit.saturating_sub(stats.scanned) as i64)+ .unwrap_or(options.batch_size);+ let batch_limit = options.batch_size.min(remaining_limit);+ if batch_limit == 0 {+ break;+ }++ let rows = self+ .repo+ .fetch_markdown_backfill_candidates(last_id.as_deref(), batch_limit)+ .await?;+ if rows.is_empty() {+ break;+ }++ tracing::info!(+ batch_len = rows.len(),+ batch_limit,+ "fetched markdown candidate batch"+ );++ last_id = rows.last().map(|row| row.id.clone());++ let outcomes = stream::iter(rows)+ .map(|candidate| {+ let service = self.clone();+ let options = options.clone();+ async move { service.process_candidate(candidate, &options).await }+ })+ .buffer_unordered(options.concurrency)+ .collect::<Vec<_>>()+ .await;++ let mut batch_stats = MarkdownBackfillStats::default();+ let mut ready_candidates = Vec::new();+ for outcome in outcomes {+ record_outcome(outcome, &mut batch_stats, &mut ready_candidates);+ }++ if options.apply && !ready_candidates.is_empty() {+ batch_stats.updated = self+ .repo+ .mark_markdown_sync_service_ready(&ready_candidates)+ .await? as usize;+ }++ stats.add(&batch_stats);++ tracing::info!(+ scanned = batch_stats.scanned,+ sync_exists = batch_stats.sync_exists,+ sync_missing = batch_stats.sync_missing,+ would_update = batch_stats.would_update,+ updated = batch_stats.updated,+ would_initialize = batch_stats.would_initialize,+ initialized = batch_stats.initialized,+ object_missing = batch_stats.object_missing,+ object_read_errors = batch_stats.object_read_errors,+ invalid_utf8 = batch_stats.invalid_utf8,+ initialize_errors = batch_stats.initialize_errors,+ missing_document_instance = batch_stats.missing_document_instance,+ sync_errors = batch_stats.sync_errors,+ total_scanned = stats.scanned,+ last_id = ?last_id,+ "processed markdown candidate batch"+ );+ }++ Ok(MarkdownBackfillReport { stats, last_id })+ }++ async fn process_candidate(+ &self,+ candidate: MarkdownBackfillCandidate,+ options: &MarkdownBackfillOptions,+ ) -> CandidateOutcome {+ let result = match sync_exists_with_retries(+ &self.sync_service,+ &candidate.id,+ options.exists_retries,+ options.exists_timeout,+ )+ .await+ {+ Ok(true) if options.apply => CandidateResult::SyncExists,+ Ok(true) => CandidateResult::WouldUpdate,+ Ok(false) if options.initialize_missing => {+ self.initialize_missing_markdown(&candidate, options.apply)+ .await+ }+ Ok(false) => CandidateResult::SyncMissing,+ Err(error) => CandidateResult::SyncError {+ error: format!("{error:?}"),+ },+ };++ CandidateOutcome { candidate, result }+ }++ async fn initialize_missing_markdown(+ &self,+ candidate: &MarkdownBackfillCandidate,+ apply: bool,+ ) -> CandidateResult {+ if candidate.document_instance_id.is_none() {+ return CandidateResult::MissingDocumentInstance;+ }++ let markdown = match self.object_reader.read_markdown(candidate).await {+ Ok(markdown) => markdown,+ Err(MarkdownObjectReadError::Missing { key }) => {+ return CandidateResult::ObjectMissing { key };+ }+ Err(MarkdownObjectReadError::Read { key, error }) => {+ return CandidateResult::ObjectReadError { key, error };+ }+ Err(MarkdownObjectReadError::InvalidUtf8 { key, error }) => {+ return CandidateResult::InvalidUtf8 { key, error };+ }+ };++ if !apply {+ return CandidateResult::WouldInitialize;+ }++ match self+ .markdown_initializer+ .initialize_existing_markdown(&candidate.id, &markdown)+ .await+ {+ Ok(()) => CandidateResult::Initialized,+ Err(error) if sync_snapshot_already_exists(&error) => CandidateResult::Initialized,+ Err(error) => CandidateResult::InitializeError {+ error: error.to_string(),+ },+ }+ }+}++#[derive(Debug)]+enum CandidateResult {+ WouldUpdate,+ SyncExists,+ SyncMissing,+ WouldInitialize,+ Initialized,+ ObjectMissing { key: String },+ ObjectReadError { key: String, error: String },+ InvalidUtf8 { key: String, error: String },+ InitializeError { error: String },+ MissingDocumentInstance,+ SyncError { error: String },+}++#[derive(Debug)]+struct CandidateOutcome {+ candidate: MarkdownBackfillCandidate,+ result: CandidateResult,+}++fn record_outcome(+ outcome: CandidateOutcome,+ stats: &mut MarkdownBackfillStats,+ ready_candidates: &mut Vec<MarkdownBackfillCandidate>,+) {+ stats.scanned += 1;+ let candidate = outcome.candidate;++ match outcome.result {+ CandidateResult::WouldUpdate => {+ stats.sync_exists += 1;+ stats.would_update += 1;+ tracing::debug!(document_id = %candidate.id, "markdown document exists in sync-service; would mark ready/sync_service");+ }+ CandidateResult::SyncExists => {+ stats.sync_exists += 1;+ ready_candidates.push(candidate.clone());+ tracing::debug!(document_id = %candidate.id, "markdown document exists in sync-service; will mark ready/sync_service");+ }+ CandidateResult::SyncMissing => {+ stats.sync_missing += 1;+ tracing::debug!(document_id = %candidate.id, "markdown document does not exist in sync-service; leaving lifecycle unchanged");+ }+ CandidateResult::WouldInitialize => {+ stats.sync_missing += 1;+ stats.would_initialize += 1;+ tracing::debug!(document_id = %candidate.id, "markdown document does not exist in sync-service; would initialize from object storage");+ }+ CandidateResult::Initialized => {+ stats.sync_missing += 1;+ stats.initialized += 1;+ ready_candidates.push(candidate.clone());+ tracing::debug!(document_id = %candidate.id, "markdown document initialized in sync-service; will mark ready/sync_service");+ }+ CandidateResult::ObjectMissing { key } => {+ stats.sync_missing += 1;+ stats.object_missing += 1;+ tracing::debug!(document_id = %candidate.id, s3_key = %key, "markdown source object missing; leaving lifecycle unchanged");+ }+ CandidateResult::ObjectReadError { key, error } => {+ stats.sync_missing += 1;+ stats.object_read_errors += 1;+ tracing::warn!(document_id = %candidate.id, s3_key = %key, error = %error, "failed to read markdown object; leaving lifecycle unchanged");+ }+ CandidateResult::InvalidUtf8 { key, error } => {+ stats.sync_missing += 1;+ stats.invalid_utf8 += 1;+ tracing::warn!(document_id = %candidate.id, s3_key = %key, error = %error, "markdown source object is not valid UTF-8; leaving lifecycle unchanged");+ }+ CandidateResult::InitializeError { error } => {+ stats.sync_missing += 1;+ stats.initialize_errors += 1;+ tracing::warn!(document_id = %candidate.id, error = %error, "failed to initialize markdown in sync-service; leaving lifecycle unchanged");+ }+ CandidateResult::MissingDocumentInstance => {+ stats.sync_missing += 1;+ stats.missing_document_instance += 1;+ tracing::debug!(document_id = %candidate.id, "markdown document has no document instance; leaving lifecycle unchanged");+ }+ CandidateResult::SyncError { error } => {+ stats.sync_errors += 1;+ tracing::warn!(document_id = %candidate.id, error = %error, "failed to query sync-service; leaving lifecycle unchanged");+ }+ }+}++async fn sync_exists_with_retries<S>(+ sync_service: &S,+ document_id: &str,+ retries: usize,+ request_timeout: Duration,+) -> anyhow::Result<bool>+where+ S: SyncServiceProbe,+{+ let attempts = retries + 1;++ for attempt_index in 0..attempts {+ let attempt = attempt_index + 1;++ match timeout(request_timeout, sync_service.exists(document_id)).await {+ Ok(Ok(exists)) => return Ok(exists),+ Ok(Err(error)) if attempt < attempts => {+ tracing::debug!(%document_id, attempt, attempts, error = ?error, "sync-service exists request failed; retrying");+ }+ Ok(Err(error)) => {+ return Err(error).with_context(|| {+ format!("sync-service exists request failed after {attempts} attempts")+ });+ }+ Err(error) if attempt < attempts => {+ tracing::debug!(%document_id, attempt, attempts, timeout_secs = request_timeout.as_secs(), error = ?error, "sync-service exists request timed out; retrying");+ }+ Err(error) => {+ return Err(error).with_context(|| {+ format!(+ "sync-service exists request timed out after {attempts} attempts of {}s",+ request_timeout.as_secs()+ )+ });+ }+ }++ sleep(Duration::from_millis(250 * attempt as u64)).await;+ }++ unreachable!("retry loop should return before exhausting attempts")+}++fn sync_snapshot_already_exists(error: &DocumentError) -> bool {+ error.to_string().contains("snapshot already exists")+}diff --git a/rust/cloud-storage/documents/src/outbound.rs b/rust/cloud-storage/documents/src/outbound.rsindex 7aab536fb5..29b2243e03 100644--- a/rust/cloud-storage/documents/src/outbound.rs+++ b/rust/cloud-storage/documents/src/outbound.rs@@ -7,4 +7,10 @@ pub mod markdown_init;#[cfg(feature = "outbound")]pub mod pg_document_repo;#[cfg(feature = "outbound")]+pub mod s3_markdown_source;+#[cfg(feature = "outbound")]pub mod s3_upload_url;+#[cfg(feature = "outbound")]+pub mod s3_utf8_object_reader;+#[cfg(feature = "outbound")]+pub mod sync_service_probe;diff --git a/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs b/rust/cloud-storage/documents/src/outbound/pg_document_repo.rsindex 8a33ef3d99..90f6e7a61e 100644--- a/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs+++ b/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs@@ -8,6 +8,7 @@ mod tests;mod copy;mod create;mod edit;+mod markdown_backfill;mod share;use document_sub_type::DocumentSubType;diff --git a/rust/cloud-storage/documents/src/outbound/pg_document_repo/markdown_backfill.rs b/rust/cloud-storage/documents/src/outbound/pg_document_repo/markdown_backfill.rsnew file mode 100644index 0000000000..f72abe7938--- /dev/null+++ b/rust/cloud-storage/documents/src/outbound/pg_document_repo/markdown_backfill.rs@@ -0,0 +1,126 @@+//! PostgreSQL adapter for markdown lifecycle backfill.++use crate::domain::markdown_backfill::{MarkdownBackfillCandidate, MarkdownBackfillRepo};+use crate::outbound::pg_document_repo::PgDocumentRepo;++impl MarkdownBackfillRepo for PgDocumentRepo {+ #[tracing::instrument(err, skip(self))]+ async fn fetch_markdown_backfill_candidates(+ &self,+ start_after: Option<&str>,+ limit: i64,+ ) -> anyhow::Result<Vec<MarkdownBackfillCandidate>> {+ let rows =+ sqlx::query_as::<_, (String, String, Option<i64>, bool, String, Option<String>)>(+ r#"+ SELECT+ d.id,+ d.owner,+ di.id AS document_instance_id,+ d.uploaded,+ d."contentState" AS content_state,+ d."contentLocation" AS content_location+ FROM "Document" d+ LEFT JOIN LATERAL (+ SELECT i.id+ FROM "DocumentInstance" i+ WHERE i."documentId" = d.id+ ORDER BY i."createdAt" DESC+ LIMIT 1+ ) di ON TRUE+ WHERE d."fileType" = 'md'+ AND (+ d."contentState" IS DISTINCT FROM 'ready'+ OR d."contentLocation" IS DISTINCT FROM 'sync_service'+ )+ AND ($1::text IS NULL OR d.id > $1)+ ORDER BY d.id+ LIMIT $2+ "#,+ )+ .bind(start_after)+ .bind(limit)+ .fetch_all(&self.pool)+ .await?;++ Ok(rows+ .into_iter()+ .map(+ |(id, owner, document_instance_id, uploaded, content_state, content_location)| {+ MarkdownBackfillCandidate {+ id,+ owner,+ document_instance_id,+ uploaded,+ content_state,+ content_location,+ }+ },+ )+ .collect())+ }++ #[tracing::instrument(err, skip(self, candidates), fields(count = candidates.len()))]+ async fn mark_markdown_sync_service_ready(+ &self,+ candidates: &[MarkdownBackfillCandidate],+ ) -> anyhow::Result<u64> {+ if candidates.is_empty() {+ return Ok(0);+ }++ let ids = candidates+ .iter()+ .map(|candidate| candidate.id.clone())+ .collect::<Vec<_>>();+ let document_instance_ids = candidates+ .iter()+ .map(|candidate| candidate.document_instance_id)+ .collect::<Vec<_>>();+ let content_states = candidates+ .iter()+ .map(|candidate| candidate.content_state.clone())+ .collect::<Vec<_>>();+ let content_locations = candidates+ .iter()+ .map(|candidate| candidate.content_location.clone())+ .collect::<Vec<_>>();++ sqlx::query(+ r#"+ WITH input AS (+ SELECT *+ FROM UNNEST(+ $1::text[],+ $2::bigint[],+ $3::text[],+ $4::text[]+ ) AS input(id, document_instance_id, content_state, content_location)+ )+ UPDATE "Document" d+ SET "contentState" = 'ready',+ "contentLocation" = 'sync_service',+ "updatedAt" = NOW()+ FROM input+ WHERE d.id = input.id+ AND d."contentState" IS NOT DISTINCT FROM input.content_state+ AND d."contentLocation" IS NOT DISTINCT FROM input.content_location+ AND (+ SELECT i.id+ FROM "DocumentInstance" i+ WHERE i."documentId" = d.id+ ORDER BY i."createdAt" DESC+ LIMIT 1+ ) IS NOT DISTINCT FROM input.document_instance_id+ "#,+ )+ .bind(ids)+ .bind(document_instance_ids)+ .bind(content_states)+ .bind(content_locations)+ .execute(&self.pool)+ .await+ .map(|result| result.rows_affected())+ .map_err(Into::into)+ }+}diff --git a/rust/cloud-storage/documents/src/outbound/s3_markdown_source.rs b/rust/cloud-storage/documents/src/outbound/s3_markdown_source.rsnew file mode 100644index 0000000000..3562cfa5f8--- /dev/null+++ b/rust/cloud-storage/documents/src/outbound/s3_markdown_source.rs@@ -0,0 +1,58 @@+//! S3 adapter for reading uploaded markdown source bytes.++use s3_key::build_cloud_storage_bucket_document_key;++use crate::domain::markdown_backfill::{+ MarkdownBackfillCandidate, MarkdownObjectReadError, MarkdownObjectReader,+};+use crate::outbound::s3_utf8_object_reader::{S3Utf8ObjectReadError, S3Utf8ObjectReader};++/// S3-backed markdown object reader.+#[derive(Clone)]+pub struct S3MarkdownObjectReader {+ bucket: String,+ utf8_reader: S3Utf8ObjectReader,+}++impl S3MarkdownObjectReader {+ /// Construct an S3 markdown reader for a document storage bucket.+ pub fn new(bucket: String, s3_client: aws_sdk_s3::Client) -> Self {+ Self {+ bucket,+ utf8_reader: S3Utf8ObjectReader::new(s3_client),+ }+ }+}++impl MarkdownObjectReader for S3MarkdownObjectReader {+ #[tracing::instrument(err, skip(self))]+ async fn read_markdown(+ &self,+ candidate: &MarkdownBackfillCandidate,+ ) -> Result<String, MarkdownObjectReadError> {+ let document_instance_id =+ candidate+ .document_instance_id+ .ok_or_else(|| MarkdownObjectReadError::Read {+ key: "<missing-document-instance-id>".to_string(),+ error: "candidate did not include a document instance id".to_string(),+ })?;++ let key = build_cloud_storage_bucket_document_key(+ &candidate.owner,+ &candidate.id,+ document_instance_id,+ );++ self.utf8_reader+ .read_utf8(&self.bucket, &key)+ .await+ .map_err(|error| match error {+ S3Utf8ObjectReadError::Missing => MarkdownObjectReadError::Missing { key },+ S3Utf8ObjectReadError::Read(error) => MarkdownObjectReadError::Read { key, error },+ S3Utf8ObjectReadError::InvalidUtf8(error) => {+ MarkdownObjectReadError::InvalidUtf8 { key, error }+ }+ })+ }+}diff --git a/rust/cloud-storage/documents/src/outbound/s3_utf8_object_reader.rs b/rust/cloud-storage/documents/src/outbound/s3_utf8_object_reader.rsnew file mode 100644index 0000000000..f39e763e22--- /dev/null+++ b/rust/cloud-storage/documents/src/outbound/s3_utf8_object_reader.rs@@ -0,0 +1,69 @@+//! Shared S3 UTF-8 object reader adapter.++/// Error while reading an S3 object as UTF-8 text.+#[derive(Clone, Debug, thiserror::Error)]+pub enum S3Utf8ObjectReadError {+ /// The object does not exist at the requested key.+ #[error("object missing")]+ Missing,+ /// The object read failed for a reason other than missing key.+ #[error("failed to read object: {0}")]+ Read(String),+ /// The object bytes were not valid UTF-8.+ #[error("object is not valid UTF-8: {0}")]+ InvalidUtf8(String),+}++/// S3-backed UTF-8 object reader.+#[derive(Clone)]+pub struct S3Utf8ObjectReader {+ s3_client: aws_sdk_s3::Client,+}++impl S3Utf8ObjectReader {+ /// Construct an S3 UTF-8 object reader.+ pub fn new(s3_client: aws_sdk_s3::Client) -> Self {+ Self { s3_client }+ }++ /// Read an S3 object body as UTF-8 text.+ #[tracing::instrument(err, skip(self))]+ pub async fn read_utf8(+ &self,+ bucket: &str,+ key: &str,+ ) -> Result<String, S3Utf8ObjectReadError> {+ let response = self+ .s3_client+ .get_object()+ .bucket(bucket)+ .key(key)+ .send()+ .await+ .map_err(|error| {+ if is_no_such_key_error(&error) {+ S3Utf8ObjectReadError::Missing+ } else {+ S3Utf8ObjectReadError::Read(format!("{error:?}"))+ }+ })?;++ let bytes = response+ .body+ .collect()+ .await+ .map_err(|error| S3Utf8ObjectReadError::Read(format!("{error:?}")))?+ .into_bytes();++ String::from_utf8(bytes.to_vec())+ .map_err(|error| S3Utf8ObjectReadError::InvalidUtf8(error.to_string()))+ }+}++fn is_no_such_key_error(+ error: &aws_sdk_s3::error::SdkError<aws_sdk_s3::operation::get_object::GetObjectError>,+) -> bool {+ error+ .as_service_error()+ .is_some_and(|error| error.is_no_such_key())+}diff --git a/rust/cloud-storage/documents/src/outbound/sync_service_probe.rs b/rust/cloud-storage/documents/src/outbound/sync_service_probe.rsnew file mode 100644index 0000000000..a6c0373b1e--- /dev/null+++ b/rust/cloud-storage/documents/src/outbound/sync_service_probe.rs@@ -0,0 +1,11 @@+//! Sync-service adapter for markdown lifecycle backfill.++use crate::domain::markdown_backfill::SyncServiceProbe;++/// Implements [`SyncServiceProbe`] by delegating to the HTTP sync-service client.+impl SyncServiceProbe for sync_service_client::SyncServiceClient {+ #[tracing::instrument(err, skip(self))]+ async fn exists(&self, document_id: &str) -> anyhow::Result<bool> {+ sync_service_client::SyncServiceClient::exists(self, document_id).await+ }+}