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.

fix(search): convert documents backfill to keyset pagination (#3412)

gbirmancf30dc627a27
diff --git a/rust/cloud-storage/.sqlx/query-800de0c6f22c73c54578e396f83b4a8f8673487c3af5b163f9bd60d7b418bda4.json b/rust/cloud-storage/.sqlx/query-91368040542b31a69ae76bfc12b127970920fb761ec08d3303bffc94402b984e.json
similarity index 78%
rename from rust/cloud-storage/.sqlx/query-800de0c6f22c73c54578e396f83b4a8f8673487c3af5b163f9bd60d7b418bda4.json
rename to rust/cloud-storage/.sqlx/query-91368040542b31a69ae76bfc12b127970920fb761ec08d3303bffc94402b984e.json
index 57e71652d1..f0c34eccbd 100644
--- a/rust/cloud-storage/.sqlx/query-800de0c6f22c73c54578e396f83b4a8f8673487c3af5b163f9bd60d7b418bda4.json
+++ b/rust/cloud-storage/.sqlx/query-91368040542b31a69ae76bfc12b127970920fb761ec08d3303bffc94402b984e.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n d.id as document_id,\n d.owner as owner,\n d.\"fileType\" as \"file_type!\",\n COALESCE(db.id, di.id, dipdf.id) as \"document_version_id!\",\n d.\"createdAt\"::timestamptz as \"created_at\"\n FROM\n \"Document\" d\n LEFT JOIN document_sub_type dst ON dst.document_id = d.id\n LEFT JOIN LATERAL (\n SELECT\n b.id\n FROM\n \"DocumentBom\" b\n WHERE\n b.\"documentId\" = d.id\n ORDER BY\n b.\"createdAt\" DESC\n LIMIT 1\n ) db ON d.\"fileType\" = 'docx'\n LEFT JOIN LATERAL (\n SELECT\n i.id\n FROM\n \"DocumentInstance\" i\n WHERE\n i.\"documentId\" = d.id\n ORDER BY\n i.\"updatedAt\" ASC\n LIMIT 1\n ) dipdf ON d.\"fileType\" = 'pdf'\n LEFT JOIN LATERAL (\n SELECT\n i.id\n FROM\n \"DocumentInstance\" i\n WHERE\n i.\"documentId\" = d.id\n ORDER BY\n i.\"createdAt\" DESC\n LIMIT 1\n ) di ON d.\"fileType\" IS DISTINCT FROM 'docx' AND d.\"fileType\" IS DISTINCT FROM 'pdf'\n WHERE\n d.\"fileType\" IS NOT NULL\n AND ($3::text[] IS NULL OR d.\"fileType\" = ANY($3))\n AND ($4::text IS NULL OR dst.sub_type::text = $4)\n AND ($5::timestamptz IS NULL OR d.\"createdAt\" >= $5)\n AND ($6::timestamptz IS NULL OR d.\"createdAt\" < $6)\n AND (\n $7::bool IS NULL\n OR ($7 AND d.\"deletedAt\" IS NOT NULL)\n OR (NOT $7 AND d.\"deletedAt\" IS NULL)\n )\n ORDER BY d.\"createdAt\" ASC, d.id ASC\n LIMIT $1 OFFSET $2\n ",
+ "query": "\n SELECT\n d.id as document_id,\n d.owner as owner,\n d.\"fileType\" as \"file_type!\",\n COALESCE(db.id, di.id, dipdf.id) as \"document_version_id!\",\n d.\"updatedAt\"::timestamptz as \"updated_at\"\n FROM\n \"Document\" d\n LEFT JOIN document_sub_type dst ON dst.document_id = d.id\n LEFT JOIN LATERAL (\n SELECT\n b.id\n FROM\n \"DocumentBom\" b\n WHERE\n b.\"documentId\" = d.id\n ORDER BY\n b.\"createdAt\" DESC\n LIMIT 1\n ) db ON d.\"fileType\" = 'docx'\n LEFT JOIN LATERAL (\n SELECT\n i.id\n FROM\n \"DocumentInstance\" i\n WHERE\n i.\"documentId\" = d.id\n ORDER BY\n i.\"updatedAt\" ASC\n LIMIT 1\n ) dipdf ON d.\"fileType\" = 'pdf'\n LEFT JOIN LATERAL (\n SELECT\n i.id\n FROM\n \"DocumentInstance\" i\n WHERE\n i.\"documentId\" = d.id\n ORDER BY\n i.\"createdAt\" DESC\n LIMIT 1\n ) di ON d.\"fileType\" IS DISTINCT FROM 'docx' AND d.\"fileType\" IS DISTINCT FROM 'pdf'\n WHERE\n d.\"fileType\" IS NOT NULL\n AND ($3::text[] IS NULL OR d.\"fileType\" = ANY($3))\n AND ($4::text IS NULL OR dst.sub_type::text = $4)\n AND ($5::timestamptz IS NULL OR d.\"updatedAt\" >= $5)\n AND ($6::timestamptz IS NULL OR d.\"updatedAt\" < $6)\n AND (\n $7::bool IS NULL\n OR ($7 AND d.\"deletedAt\" IS NOT NULL)\n OR (NOT $7 AND d.\"deletedAt\" IS NULL)\n )\n AND (\n $2::timestamptz IS NULL\n OR (d.\"updatedAt\", d.id) > ($2, $8::text)\n )\n ORDER BY d.\"updatedAt\" ASC, d.id ASC\n LIMIT $1\n ",
"describe": {
"columns": [
{
@@ -25,19 +25,20 @@
},
{
"ordinal": 4,
- "name": "created_at",
+ "name": "updated_at",
"type_info": "Timestamptz"
}
],
"parameters": {
"Left": [
"Int8",
- "Int8",
+ "Timestamptz",
"TextArray",
"Text",
"Timestamptz",
"Timestamptz",
- "Bool"
+ "Bool",
+ "Text"
]
},
"nullable": [
@@ -48,5 +49,5 @@
null
]
},
- "hash": "800de0c6f22c73c54578e396f83b4a8f8673487c3af5b163f9bd60d7b418bda4"
+ "hash": "91368040542b31a69ae76bfc12b127970920fb761ec08d3303bffc94402b984e"
}
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260520180000_document_updated_at_id_keyset_index.sql b/rust/cloud-storage/macro_db_client/migrations/20260520180000_document_updated_at_id_keyset_index.sql
new file mode 100644
index 0000000000..c7055bad6e
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260520180000_document_updated_at_id_keyset_index.sql
@@ -0,0 +1,5 @@
+-- no-transaction
+-- Supports keyset pagination over Document for the search backfill
+-- orchestrator, which sorts by ("updatedAt" ASC, id ASC).
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_document_updated_at_id
+ ON "Document" ("updatedAt", id);
diff --git a/rust/cloud-storage/macro_db_client/src/document/get_documents_search.rs b/rust/cloud-storage/macro_db_client/src/document/get_documents_search.rs
index bb3d66cd64..1604c67c26 100644
--- a/rust/cloud-storage/macro_db_client/src/document/get_documents_search.rs
+++ b/rust/cloud-storage/macro_db_client/src/document/get_documents_search.rs
@@ -8,18 +8,30 @@ use model::document::{BackfillSearchDocumentInformation, FileType};
/// Used to get all documents in a paginated format
/// This will get the latest version of the document for non-pdf documents
/// For pdf documents, this will get the oldest version of the document
+///
+/// Pagination is **keyset (seek-method)**: pass `cursor` as the last row's
+/// `(updated_at, document_id)` pair from the previous page (or `None` for
+/// the first page).
+///
+/// Sorting and filtering use `updatedAt` rather than `createdAt` so that
+/// incremental backfills (e.g. "anything changed since X") catch documents
+/// that already existed but were modified after the cutoff.
#[allow(clippy::too_many_arguments)]
#[tracing::instrument(skip(db))]
pub async fn get_documents_for_search(
db: &Pool<Postgres>,
limit: i64,
- offset: i64,
+ cursor: Option<(DateTime<Utc>, String)>,
file_types: &Option<Vec<String>>,
sub_type: &Option<String>,
- created_after: &Option<DateTime<Utc>>,
- created_before: &Option<DateTime<Utc>>,
+ updated_after: &Option<DateTime<Utc>>,
+ updated_before: &Option<DateTime<Utc>>,
only_deleted: Option<bool>,
) -> anyhow::Result<Vec<BackfillSearchDocumentInformation>> {
+ let (cursor_updated_at, cursor_id) = match cursor {
+ Some((t, id)) => (Some(t), Some(id)),
+ None => (None, None),
+ };
let result = sqlx::query!(
r#"
SELECT
@@ -27,7 +39,7 @@ pub async fn get_documents_for_search(
d.owner as owner,
d."fileType" as "file_type!",
COALESCE(db.id, di.id, dipdf.id) as "document_version_id!",
- d."createdAt"::timestamptz as "created_at"
+ d."updatedAt"::timestamptz as "updated_at"
FROM
"Document" d
LEFT JOIN document_sub_type dst ON dst.document_id = d.id
@@ -68,23 +80,28 @@ pub async fn get_documents_for_search(
d."fileType" IS NOT NULL
AND ($3::text[] IS NULL OR d."fileType" = ANY($3))
AND ($4::text IS NULL OR dst.sub_type::text = $4)
- AND ($5::timestamptz IS NULL OR d."createdAt" >= $5)
- AND ($6::timestamptz IS NULL OR d."createdAt" < $6)
+ AND ($5::timestamptz IS NULL OR d."updatedAt" >= $5)
+ AND ($6::timestamptz IS NULL OR d."updatedAt" < $6)
AND (
$7::bool IS NULL
OR ($7 AND d."deletedAt" IS NOT NULL)
OR (NOT $7 AND d."deletedAt" IS NULL)
)
- ORDER BY d."createdAt" ASC, d.id ASC
- LIMIT $1 OFFSET $2
+ AND (
+ $2::timestamptz IS NULL
+ OR (d."updatedAt", d.id) > ($2, $8::text)
+ )
+ ORDER BY d."updatedAt" ASC, d.id ASC
+ LIMIT $1
"#,
limit,
- offset,
+ cursor_updated_at as Option<DateTime<Utc>>,
file_types.as_deref() as Option<&[String]>,
sub_type.as_deref() as Option<&str>,
- *created_after as Option<DateTime<Utc>>,
- *created_before as Option<DateTime<Utc>>,
+ *updated_after as Option<DateTime<Utc>>,
+ *updated_before as Option<DateTime<Utc>>,
only_deleted,
+ cursor_id as Option<String>,
)
.try_map(|row| {
Ok(BackfillSearchDocumentInformation {
@@ -97,7 +114,7 @@ pub async fn get_documents_for_search(
source: e.into(),
}
})?,
- created_at: row.created_at,
+ updated_at: row.updated_at,
})
})
.fetch_all(db)
diff --git a/rust/cloud-storage/model/src/document/mod.rs b/rust/cloud-storage/model/src/document/mod.rs
index 551050c41e..e618b4375d 100644
--- a/rust/cloud-storage/model/src/document/mod.rs
+++ b/rust/cloud-storage/model/src/document/mod.rs
@@ -141,7 +141,7 @@ pub struct BackfillSearchDocumentInformation {
pub document_version_id: i64,
pub owner: String,
pub file_type: FileType,
- pub created_at: Option<chrono::DateTime<chrono::Utc>>,
+ pub updated_at: Option<chrono::DateTime<chrono::Utc>>,
}
#[derive(
sqlx::FromRow,
diff --git a/rust/cloud-storage/search_processing_service/src/domain/models.rs b/rust/cloud-storage/search_processing_service/src/domain/models.rs
index bd2d4a4365..7b1a131894 100644
--- a/rust/cloud-storage/search_processing_service/src/domain/models.rs
+++ b/rust/cloud-storage/search_processing_service/src/domain/models.rs
@@ -89,15 +89,31 @@ pub struct ChannelBackfillRequest {
pub index_override: Option<String>,
}
+/// Keyset (seek-method) pagination cursor for document backfills.
+///
+/// `get_documents_for_search` walks `"Document"` in
+/// `(updatedAt ASC, id ASC)` order; the cursor carries the last row's
+/// pair so the next page resumes with `WHERE (updatedAt, id) > cursor`.
+/// `None` starts at the beginning.
+#[derive(Debug, Clone)]
+pub struct DocumentBackfillCursor {
+ pub updated_at: DateTime<Utc>,
+ pub document_id: String,
+}
+
/// Document backfill filter. Every field is additive — all `None` means "every
/// document this service knows about".
+///
+/// `updated_after` / `updated_before` filter on `updatedAt`, not `createdAt`,
+/// so incremental runs (e.g. "anything changed since X") catch documents that
+/// existed before the cutoff but were modified after it.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct DocumentBackfillRequest {
pub file_types: Option<Vec<String>>,
pub sub_type: Option<String>,
- pub created_after: Option<DateTime<Utc>>,
- pub created_before: Option<DateTime<Utc>>,
+ pub updated_after: Option<DateTime<Utc>>,
+ pub updated_before: Option<DateTime<Utc>>,
pub deletion_filter: DeletionFilter,
/// Override the OpenSearch target index for upserts (e.g. blue/green swap).
pub index_override: Option<String>,
diff --git a/rust/cloud-storage/search_processing_service/src/domain/ports.rs b/rust/cloud-storage/search_processing_service/src/domain/ports.rs
index 7e7b982b44..eadf2ebd38 100644
--- a/rust/cloud-storage/search_processing_service/src/domain/ports.rs
+++ b/rust/cloud-storage/search_processing_service/src/domain/ports.rs
@@ -18,7 +18,7 @@ use sqs_client::search::SearchQueueMessage;
use super::models::{
BackfillError, CallBackfillRequest, ChannelBackfillRequest, ChatBackfillRequest,
- DocumentBackfillRequest, EmailBackfillRequest, SourcePage,
+ DocumentBackfillCursor, DocumentBackfillRequest, EmailBackfillRequest, SourcePage,
};
/// Publishes batches of search-event messages.
@@ -56,11 +56,16 @@ pub trait BackfillSource: Send + Sync + 'static {
offset: usize,
) -> impl Future<Output = Result<SourcePage, BackfillError>> + Send;
+ /// Documents paginate by keyset cursor: each call passes the cursor
+ /// of the last row from the previous page (or `None` for the first
+ /// page), and the implementation returns the page plus the cursor
+ /// to feed back into the next call. An empty page signals
+ /// end-of-source.
fn fetch_documents(
&self,
req: &DocumentBackfillRequest,
- offset: usize,
- ) -> impl Future<Output = Result<SourcePage, BackfillError>> + Send;
+ cursor: Option<DocumentBackfillCursor>,
+ ) -> impl Future<Output = Result<(SourcePage, Option<DocumentBackfillCursor>), BackfillError>> + Send;
fn fetch_emails(
&self,
diff --git a/rust/cloud-storage/search_processing_service/src/domain/service.rs b/rust/cloud-storage/search_processing_service/src/domain/service.rs
index a4a6a409e9..b61ca3a31b 100644
--- a/rust/cloud-storage/search_processing_service/src/domain/service.rs
+++ b/rust/cloud-storage/search_processing_service/src/domain/service.rs
@@ -19,6 +19,49 @@ use super::models::{
};
use super::ports::{BackfillSource, SearchEventPublisher};
+/// Drive a source by repeatedly calling `fetch(cursor)`, publishing each
+/// page's messages, and stopping when the source reports zero rows
+/// consumed. Identical loop shape to [`drain_source`] but the state
+/// advanced between pages is an opaque cursor returned by the fetcher
+/// rather than an integer offset — used by entities (documents) that
+/// paginate by sort-key.
+async fn drain_source_with_cursor<C, Fut, P>(
+ publisher: &P,
+ progress: &JobProgress,
+ cancel: &CancellationToken,
+ fetch: impl Fn(Option<C>) -> Fut,
+) -> Result<BackfillReceipt, BackfillError>
+where
+ Fut: Future<Output = Result<(SourcePage, Option<C>), BackfillError>>,
+ P: SearchEventPublisher,
+{
+ let mut cursor: Option<C> = None;
+ let mut enqueued = 0usize;
+
+ loop {
+ if cancel.is_cancelled() {
+ tracing::info!(enqueued, "backfill cancelled between pages");
+ break;
+ }
+ let (page, next_cursor) = fetch(cursor).await?;
+ if page.rows_consumed == 0 {
+ break;
+ }
+ publisher.publish(page.messages).await?;
+ enqueued += page.rows_consumed;
+ progress.add(page.rows_consumed).await;
+ // Source signals end-of-stream by returning `None` for the next
+ // cursor on a non-empty page (e.g. last row's sort-key column was
+ // unexpectedly NULL). Treat that as termination; otherwise we'd
+ // pass `None` to the next `fetch` and restart pagination from the
+ // beginning.
+ let Some(next) = next_cursor else { break };
+ cursor = Some(next);
+ }
+
+ Ok(BackfillReceipt { enqueued })
+}
+
/// Inbound contract for all backfill HTTP routes. Each call drives a single
/// orchestration to completion (or to cancellation via `cancel`); the HTTP
/// layer is responsible for spawning these onto a background task and
@@ -158,8 +201,8 @@ where
progress: Arc<JobProgress>,
cancel: CancellationToken,
) -> Result<BackfillReceipt, BackfillError> {
- drain_source(&self.publisher, &progress, &cancel, |offset| {
- self.source.fetch_documents(&req, offset)
+ drain_source_with_cursor(&self.publisher, &progress, &cancel, |cursor| {
+ self.source.fetch_documents(&req, cursor)
})
.await
}
diff --git a/rust/cloud-storage/search_processing_service/src/domain/service/test.rs b/rust/cloud-storage/search_processing_service/src/domain/service/test.rs
index 5282eae0e6..b4ab729921 100644
--- a/rust/cloud-storage/search_processing_service/src/domain/service/test.rs
+++ b/rust/cloud-storage/search_processing_service/src/domain/service/test.rs
@@ -278,6 +278,166 @@ async fn cancel_before_first_fetch_returns_empty_receipt() {
assert!(source.observed_offsets().is_empty());
}
+/// Fake source for the cursor-based loop. Pages out a programmed
+/// sequence and records the cursor it was called with each time so
+/// tests can assert the cursor advances correctly.
+struct CursorFakeSource {
+ pages: Mutex<std::collections::VecDeque<(SourcePage, Option<usize>)>>,
+ cursors: Mutex<Vec<Option<usize>>>,
+}
+
+impl CursorFakeSource {
+ fn new(pages: Vec<(SourcePage, Option<usize>)>) -> Self {
+ Self {
+ pages: Mutex::new(pages.into_iter().collect()),
+ cursors: Mutex::new(Vec::new()),
+ }
+ }
+
+ async fn fetch_page(
+ &self,
+ cursor: Option<usize>,
+ ) -> Result<(SourcePage, Option<usize>), BackfillError> {
+ self.cursors.lock().unwrap().push(cursor);
+ Ok(self
+ .pages
+ .lock()
+ .unwrap()
+ .pop_front()
+ .unwrap_or_else(|| (SourcePage::empty(), None)))
+ }
+
+ fn observed_cursors(&self) -> Vec<Option<usize>> {
+ self.cursors.lock().unwrap().clone()
+ }
+}
+
+#[tokio::test]
+async fn cursor_drain_threads_cursor_through_pages() {
+ // Three pages: first call passes None; subsequent calls pass the
+ // cursor each previous page returned. Loop stops on empty page.
+ let source = CursorFakeSource::new(vec![
+ (
+ page((0..5).map(|i| msg(&format!("p1-{i}"))).collect()),
+ Some(10),
+ ),
+ (
+ page((0..5).map(|i| msg(&format!("p2-{i}"))).collect()),
+ Some(20),
+ ),
+ (
+ page((0..3).map(|i| msg(&format!("p3-{i}"))).collect()),
+ Some(30),
+ ),
+ ]);
+ let publisher = RecordingPublisher::default();
+ let (progress, cancel) = detached();
+
+ let receipt = drain_source_with_cursor(&publisher, &progress, &cancel, |cursor| {
+ source.fetch_page(cursor)
+ })
+ .await
+ .unwrap();
+
+ assert_eq!(receipt.enqueued, 13);
+ assert_eq!(publisher.batch_sizes(), vec![5, 5, 3]);
+ // Cursors: None (first), Some(10), Some(20), Some(30) (empty terminator).
+ assert_eq!(
+ source.observed_cursors(),
+ vec![None, Some(10), Some(20), Some(30)]
+ );
+}
+
+#[tokio::test]
+async fn cursor_drain_stops_when_non_empty_page_returns_no_cursor() {
+ // Defensive path: source returns a non-empty page but `None` for the
+ // next cursor (e.g. the last row's sort-key column came back NULL).
+ // The loop must treat this as terminator — passing `None` back into
+ // `fetch` would restart pagination from page one.
+ let source = CursorFakeSource::new(vec![
+ (
+ page((0..3).map(|i| msg(&format!("p1-{i}"))).collect()),
+ None,
+ ),
+ (
+ page((0..3).map(|i| msg(&format!("never-{i}"))).collect()),
+ Some(99),
+ ),
+ ]);
+ let publisher = RecordingPublisher::default();
+ let (progress, cancel) = detached();
+
+ let receipt = drain_source_with_cursor(&publisher, &progress, &cancel, |cursor| {
+ source.fetch_page(cursor)
+ })
+ .await
+ .unwrap();
+
+ assert_eq!(receipt.enqueued, 3);
+ assert_eq!(publisher.batch_sizes(), vec![3]);
+ // Only the first fetch happens; the loop bails before re-entering with `None`.
+ assert_eq!(source.observed_cursors(), vec![None]);
+}
+
+#[tokio::test]
+async fn cursor_drain_stops_on_empty_page() {
+ let source = CursorFakeSource::new(vec![]);
+ let publisher = RecordingPublisher::default();
+ let (progress, cancel) = detached();
+
+ let receipt = drain_source_with_cursor(&publisher, &progress, &cancel, |cursor| {
+ source.fetch_page(cursor)
+ })
+ .await
+ .unwrap();
+
+ assert_eq!(receipt.enqueued, 0);
+ assert_eq!(publisher.batch_count(), 0);
+ // Probed once with no cursor, got empty, terminated.
+ assert_eq!(source.observed_cursors(), vec![None]);
+}
+
+#[tokio::test]
+async fn cursor_drain_cancellation_stops_between_pages() {
+ let source = CursorFakeSource::new(vec![
+ (
+ page((0..3).map(|i| msg(&format!("a{i}"))).collect()),
+ Some(7),
+ ),
+ (
+ page((0..3).map(|i| msg(&format!("never-{i}"))).collect()),
+ Some(99),
+ ),
+ ]);
+ let (progress, cancel) = detached();
+ let cancel_clone = cancel.clone();
+ struct CancellingPublisher {
+ cancel: CancellationToken,
+ seen: Mutex<Vec<usize>>,
+ }
+ impl SearchEventPublisher for CancellingPublisher {
+ async fn publish(&self, messages: Vec<SearchQueueMessage>) -> Result<(), BackfillError> {
+ self.seen.lock().unwrap().push(messages.len());
+ self.cancel.cancel();
+ Ok(())
+ }
+ }
+ let publisher = CancellingPublisher {
+ cancel: cancel_clone,
+ seen: Mutex::new(Vec::new()),
+ };
+
+ let receipt = drain_source_with_cursor(&publisher, &progress, &cancel, |cursor| {
+ source.fetch_page(cursor)
+ })
+ .await
+ .unwrap();
+
+ assert_eq!(receipt.enqueued, 3);
+ // First page fetched + published; cancellation stops the second fetch.
+ assert_eq!(source.observed_cursors(), vec![None]);
+}
+
#[tokio::test]
async fn cancel_between_pages_stops_drain_after_current_page() {
// Cancel the token from inside the publisher: the page that triggered
diff --git a/rust/cloud-storage/search_processing_service/src/outbound/source.rs b/rust/cloud-storage/search_processing_service/src/outbound/source.rs
index d84c6d5d68..437e34e13d 100644
--- a/rust/cloud-storage/search_processing_service/src/outbound/source.rs
+++ b/rust/cloud-storage/search_processing_service/src/outbound/source.rs
@@ -10,7 +10,7 @@ use sqs_client::search::{
use crate::config::BackfillPageSizes;
use crate::domain::models::{
BackfillError, CallBackfillRequest, ChannelBackfillRequest, ChatBackfillRequest,
- DocumentBackfillRequest, EmailBackfillRequest, SourcePage,
+ DocumentBackfillCursor, DocumentBackfillRequest, EmailBackfillRequest, SourcePage,
};
use crate::domain::ports::BackfillSource;
@@ -163,21 +163,35 @@ impl BackfillSource for PgBackfillSource {
async fn fetch_documents(
&self,
req: &DocumentBackfillRequest,
- offset: usize,
- ) -> Result<SourcePage, BackfillError> {
+ cursor: Option<DocumentBackfillCursor>,
+ ) -> Result<(SourcePage, Option<DocumentBackfillCursor>), BackfillError> {
+ let db_cursor = cursor.map(|c| (c.updated_at, c.document_id));
let batch = macro_db_client::document::get_documents_search::get_documents_for_search(
&self.db,
self.page_sizes.documents as i64,
- offset as i64,
+ db_cursor,
&req.file_types,
&req.sub_type,
- &req.created_after,
- &req.created_before,
+ &req.updated_after,
+ &req.updated_before,
req.deletion_filter.as_only_deleted(),
)
.await
.map_err(BackfillError::Source)?;
+ // Build the next cursor from the last row before we move the
+ // batch into the messages mapper. The query sorts ascending so
+ // the last row carries the sort-tuple that resumes the scan.
+ // `updated_at` is NOT NULL in the schema but sqlx types it as
+ // Option because of the timestamptz cast; if it ever did come
+ // back None we'd rather stop pagination than build a bogus
+ // cursor — `and_then` does exactly that.
+ let next_cursor = batch.last().and_then(|d| {
+ d.updated_at.map(|updated_at| DocumentBackfillCursor {
+ updated_at,
+ document_id: d.document_id.clone(),
+ })
+ });
let rows_consumed = batch.len();
let messages: Vec<SearchQueueMessage> = batch
.iter()
@@ -192,10 +206,13 @@ impl BackfillSource for PgBackfillSource {
})
.collect();
- Ok(SourcePage {
- messages,
- rows_consumed,
- })
+ Ok((
+ SourcePage {
+ messages,
+ rows_consumed,
+ },
+ next_cursor,
+ ))
}
async fn fetch_emails(