Skip to main content

haste_worker/search_indexing/
mod.rs

1use crate::{
2    indexing_lock::{IndexLockProvider, postgres::ProjectLockIndex},
3    traits::Worker,
4};
5use haste_fhir_model::r4::generated::resources::ResourceTypeError;
6use haste_fhir_operation_error::{OperationOutcomeError, derive::OperationOutcomeError};
7use haste_fhir_search::config::{SearchConfig, SearchEngineBackend};
8use haste_fhir_search::{IndexResource, SearchEngine};
9use haste_fhirpath::FHIRPathError;
10use haste_jwt::{ProjectId, TenantId, VersionId};
11use haste_repository::config::{RepoConfig, create_repo};
12use haste_repository::{
13    failed_indexing::{FailedIndexRecord, FailedIndexingProvider},
14    fhir::FHIRRepository,
15    pg::PGConnection,
16    sequence::{ResourcePollingValue, ResourceSequential},
17    types::{SearchIndexBackend, SupportedFHIRVersions},
18};
19use serde::{Deserialize, Serialize};
20use sqlx::{Acquire, query_as};
21use std::{
22    sync::Arc,
23    time::{Duration, Instant},
24};
25use tokio::{
26    sync::{Mutex, OwnedSemaphorePermit, Semaphore},
27    task::{JoinError, JoinHandle, JoinSet},
28};
29
30#[derive(OperationOutcomeError, Debug)]
31pub enum IndexingWorkerError {
32    #[fatal(code = "exception", diagnostic = "Database error: '{arg0}'")]
33    DatabaseConnectionError(#[from] sqlx::Error),
34    #[fatal(code = "exception", diagnostic = "Lock error: '{arg0}'")]
35    OperationError(#[from] OperationOutcomeError),
36    #[fatal(code = "exception", diagnostic = "Elasticsearch error: '{arg0}'")]
37    ElasticsearchError(#[from] elasticsearch::Error),
38    #[fatal(code = "exception", diagnostic = "FHIRPath error: '{arg0}'")]
39    FHIRPathError(#[from] FHIRPathError),
40    #[fatal(
41        code = "exception",
42        diagnostic = "Missing search parameters for resource: '{arg0}'"
43    )]
44    MissingSearchParameters(String),
45    #[fatal(
46        code = "exception",
47        diagnostic = "Fatal error occurred during indexing"
48    )]
49    Fatal,
50    #[fatal(
51        code = "exception",
52        diagnostic = "Artifact error: Invalid resource type '{arg0}'"
53    )]
54    ResourceTypeError(#[from] ResourceTypeError),
55}
56
57struct ProjectReturn {
58    tenant: TenantId,
59    project: ProjectId,
60}
61
62/// Reads projects in primary key order, `page_size` at a time, reading the
63/// next page only once the current one has been handed out. Each page starts
64/// after the last project of the one before rather than at an offset, so a
65/// project created or deleted meanwhile moves no other project across a page
66/// boundary.
67struct ProjectPages {
68    page_size: u64,
69    page: std::vec::IntoIter<ProjectReturn>,
70    after: Option<(TenantId, ProjectId)>,
71    read_all: bool,
72}
73
74impl ProjectPages {
75    fn new(page_size: u64) -> Self {
76        Self {
77            page_size,
78            page: Vec::new().into_iter(),
79            after: None,
80            read_all: false,
81        }
82    }
83
84    /// Returns the next project, or `None` once every project has been
85    /// returned.
86    async fn next(
87        &mut self,
88        repo: &PGConnection,
89    ) -> Result<Option<ProjectReturn>, OperationOutcomeError> {
90        loop {
91            if let Some(project) = self.page.next() {
92                return Ok(Some(project));
93            }
94            if self.read_all {
95                return Ok(None);
96            }
97            let after = self
98                .after
99                .as_ref()
100                .map(|(tenant, project)| (tenant, project));
101            let page = get_projects(repo, after, self.page_size.cast_signed()).await?;
102            // A short page is the last one. A full one may be followed by an empty one.
103            self.read_all = page.is_empty() || (page.len() as u64) < self.page_size;
104            if let Some(last) = page.last() {
105                self.after = Some((last.tenant.clone(), last.project.clone()));
106            }
107            self.page = page.into_iter();
108        }
109    }
110}
111
112/// Returns up to `count` projects in primary key order, starting after
113/// `after`, or from the first project when it is `None`.
114async fn get_projects(
115    repo: &PGConnection,
116    after: Option<(&TenantId, &ProjectId)>,
117    count: i64,
118) -> Result<Vec<ProjectReturn>, OperationOutcomeError> {
119    // Tenant and project ids are never empty, so ('', '') sorts before every
120    // project and the first page needs no query of its own.
121    let (after_tenant, after_project) = after.map_or(("", ""), |(tenant, project)| {
122        (tenant.as_ref(), project.as_ref())
123    });
124    match repo {
125        PGConnection::Pool(pool, _) => {
126            let mut connection = pool.acquire().await.map_err(IndexingWorkerError::from)?;
127            let conn = connection
128                .acquire()
129                .await
130                .map_err(IndexingWorkerError::from)?;
131            let result = query_as!(
132                ProjectReturn,
133                r#"SELECT tenant as "tenant: TenantId", id as "project: ProjectId" FROM projects WHERE (tenant, id) > ($1, $2) ORDER BY tenant, id LIMIT $3"#,
134                after_tenant,
135                after_project,
136                count
137            )
138            .fetch_all(&mut *conn)
139            .await
140            .map_err(IndexingWorkerError::from)?;
141
142            Ok(result)
143        }
144        PGConnection::Transaction(tx, _, _) => {
145            let mut connection = tx.lock().await;
146            let conn = connection
147                .acquire()
148                .await
149                .map_err(IndexingWorkerError::from)?;
150            let result = query_as!(
151                ProjectReturn,
152                r#"SELECT tenant as "tenant: TenantId", id as "project: ProjectId" FROM projects WHERE (tenant, id) > ($1, $2) ORDER BY tenant, id LIMIT $3"#,
153                after_tenant,
154                after_project,
155                count
156            )
157            .fetch_all(&mut *conn)
158            .await
159            .map_err(IndexingWorkerError::from)?;
160
161            Ok(result)
162        }
163    }
164}
165
166/// Records in `FailedIndexingProvider` if any resources failed to index. This is a no-op if the list is empty.
167async fn record_failures(
168    tenant: &TenantId,
169    project: &ProjectId,
170    indexing_error_provider: &impl FailedIndexingProvider,
171    failures: &[FailedIndexRecord],
172) -> Result<(), IndexingWorkerError> {
173    if failures.is_empty() {
174        return Ok(());
175    }
176
177    tracing::warn!(
178        "Parking {} resource(s) that failed indexing for tenant '{}' project '{}'.",
179        failures.len(),
180        tenant,
181        project.as_ref()
182    );
183
184    for failure in failures {
185        tracing::error!(
186            tenant = %tenant,
187            project = %project.as_ref(),
188            resource_type = %failure.resource_type,
189            version_id = failure.version_id.as_ref(),
190            fhir_method = failure.fhir_method.as_str(),
191            error = %failure.error_message,
192            "Search indexing failed for resource"
193        );
194    }
195
196    indexing_error_provider.record_failures(failures).await?;
197
198    Ok(())
199}
200
201/// The batch of resources indexed in one `index_project_next_sequence` pass,
202/// as measured just before and after the indexing call.
203struct IndexingBatchStats {
204    start_sequence: Option<i64>,
205    resources_total: usize,
206    start: Instant,
207    last_polling_value: ResourcePollingValue,
208}
209
210async fn update_lock_sequence_position<
211    Repo: ResourceSequential + IndexLockProvider<(TenantId, ProjectId), ProjectLockIndex>,
212>(
213    tenant_id: &TenantId,
214    project_id: &ProjectId,
215    backend: SearchIndexBackend,
216    repo: &Repo,
217    batch: IndexingBatchStats,
218) -> Result<(), OperationOutcomeError> {
219    let IndexingBatchStats {
220        start_sequence,
221        resources_total,
222        start,
223        last_polling_value,
224    } = batch;
225    let diff = (last_polling_value.sequence + 1) - start_sequence.unwrap_or(0);
226    let total = resources_total;
227
228    if total as u64 != diff.unsigned_abs() {
229        tracing::event!(
230            tracing::Level::WARN,
231            // safe_seq = resource.max_safe_seq.unwrap_or(0),
232            first_seq = start_sequence.unwrap_or(0),
233            last_seq = last_polling_value.sequence,
234            total = resources_total,
235            diff = (last_polling_value.sequence + 1) - start_sequence.unwrap_or(0),
236            "Sequence gap detected while indexing tenant '{}' project '{}' ({}) - resources may have been skipped.",
237            tenant_id,
238            project_id.as_ref(),
239            backend
240        );
241    }
242
243    tracing::trace!(
244        "Updating {} lock for tenant '{}' project '{}' to sequence position {}.",
245        backend,
246        tenant_id,
247        project_id.as_ref(),
248        last_polling_value.sequence
249    );
250
251    repo.update_lock(
252        backend,
253        &(tenant_id.clone(), project_id.clone()),
254        ProjectLockIndex {
255            tenant: tenant_id.clone(),
256            project: project_id.clone(),
257            index_sequence_position: last_polling_value.sequence,
258        },
259    )
260    .await?;
261
262    tracing::trace!(
263        "Indexed {} resources for tenant '{}' project '{}' in {:.2?} (up to sequence {})",
264        resources_total,
265        tenant_id.as_ref(),
266        project_id.as_ref(),
267        start.elapsed(),
268        last_polling_value.sequence
269    );
270
271    Ok(())
272}
273
274static TOTAL_INDEXED: std::sync::LazyLock<Mutex<usize>> =
275    std::sync::LazyLock::new(|| Mutex::new(0));
276
277async fn index_project_next_sequence<
278    Repo: ResourceSequential
279        + IndexLockProvider<(TenantId, ProjectId), ProjectLockIndex>
280        + FailedIndexingProvider,
281    Engine: SearchEngine,
282>(
283    max_concurrent_limit: u64,
284    backend: SearchIndexBackend,
285    search_client: Arc<Engine>,
286    repo: &Repo,
287    tenant_id: &TenantId,
288    project_id: &ProjectId,
289    safe_sequence: i64,
290) -> Result<usize, IndexingWorkerError> {
291    let start = std::time::Instant::now();
292    let lock_key = (tenant_id.clone(), project_id.clone());
293    let project_locks = repo.get_available_locks(backend, vec![&lock_key]).await?;
294
295    if project_locks.is_empty() {
296        tracing::info!(
297            "No available {} lock for tenant '{}' project '{}', skipping indexing.",
298            backend,
299            tenant_id,
300            project_id.as_ref()
301        );
302        return Ok(0);
303    }
304
305    tracing::trace!(
306        "Acquired {} lock for tenant '{}' project '{}', starting indexing from sequence {}.",
307        backend,
308        tenant_id,
309        project_id.as_ref(),
310        project_locks[0].index_sequence_position
311    );
312
313    let resources = repo
314        .get_sequence(
315            tenant_id,
316            project_id,
317            project_locks[0].index_sequence_position.cast_unsigned(),
318            safe_sequence,
319            Some(max_concurrent_limit),
320        )
321        .await?;
322
323    let resources_total = resources.len();
324    let start_sequence = resources.first().map(|r| r.sequence);
325    let last_value = resources.last().cloned();
326
327    // Perform indexing if there are resources to index.
328    if !resources.is_empty() {
329        let outcome = search_client
330            .index(
331                SupportedFHIRVersions::R4,
332                resources
333                    .into_iter()
334                    .map(|r| IndexResource {
335                        tenant: r.tenant,
336                        id: r.id,
337                        version_id: VersionId::new(r.version_id),
338                        project: r.project,
339                        fhir_method: r.fhir_method,
340                        resource_type: r.resource_type,
341                        resource: r.resource.0,
342                        sequence: r.sequence,
343                    })
344                    .collect(),
345            )
346            .await?;
347        let resources_attempted_to_index_count = outcome.succeeded + outcome.failed.len();
348
349        if resources_attempted_to_index_count != resources_total {
350            tracing::error!(
351                "Indexed+failed resource count '{}' does not match retrieved resource count '{}' for tenant '{}' project '{}'",
352                resources_attempted_to_index_count,
353                resources_total,
354                tenant_id,
355                project_id.as_ref()
356            );
357            return Err(IndexingWorkerError::Fatal);
358        }
359
360        let failures = outcome
361            .failed
362            .into_iter()
363            .map(|failure| FailedIndexRecord {
364                tenant: failure.resource.tenant,
365                project: failure.resource.project,
366                version_id: failure.resource.version_id,
367                resource_type: failure.resource.resource_type.as_ref().to_string(),
368                fhir_method: failure.resource.fhir_method,
369                error_message: failure.error.to_string(),
370            })
371            .collect::<Vec<_>>();
372
373        record_failures(tenant_id, project_id, repo, &failures).await?;
374
375        if let Some(last_polling_value) = last_value {
376            update_lock_sequence_position(
377                tenant_id,
378                project_id,
379                backend,
380                repo,
381                IndexingBatchStats {
382                    start_sequence,
383                    resources_total,
384                    start,
385                    last_polling_value,
386                },
387            )
388            .await?;
389        }
390
391        *(TOTAL_INDEXED.lock().await) += outcome.succeeded;
392    }
393
394    Ok(resources_total)
395}
396
397async fn index_for_project<
398    Search: SearchEngine,
399    Repository: FHIRRepository
400        + ResourceSequential
401        + IndexLockProvider<(TenantId, ProjectId), ProjectLockIndex>
402        + FailedIndexingProvider,
403>(
404    max_concurrent_limit: u64,
405    backend: SearchIndexBackend,
406    repo: Arc<Repository>,
407    search_client: Arc<Search>,
408    tenant_id: &TenantId,
409    project_id: &ProjectId,
410    safe_sequence: i64,
411) -> Result<usize, IndexingWorkerError> {
412    let tx = repo
413        .transaction(false)
414        .await
415        .map_err(IndexingWorkerError::from)?;
416    let res = index_project_next_sequence(
417        max_concurrent_limit,
418        backend,
419        search_client,
420        &tx,
421        tenant_id,
422        project_id,
423        safe_sequence,
424    )
425    .await;
426
427    match res {
428        Ok(res) => {
429            tx.commit().await?;
430            Ok(res)
431        }
432        Err(e) => {
433            if let Err(rollback_err) = tx.rollback().await {
434                tracing::error!(
435                    "Failed to roll back transaction for tenant '{}' project '{}' (original error: '{:?}'): '{:?}'",
436                    tenant_id,
437                    project_id.as_ref(),
438                    e,
439                    rollback_err
440                );
441                return Err(rollback_err.into());
442            }
443            Err(e)
444        }
445    }
446}
447
448/// Indexes every project up to `safe_sequence`. A project is read and its task
449/// spawned only once a permit of `semaphore` is free, so however many projects
450/// there are, at most that many are in flight and one page of them is held,
451/// and a slow project holds one permit while the others move on through the
452/// pages. Returns how many projects there were and the rows handed to the
453/// search engine across all of them; zero rows means every project was
454/// already caught up to the watermark (or locked by another worker). A failed
455/// page read is returned once the projects already started have finished.
456async fn index_all_projects(
457    repo: &Arc<PGConnection>,
458    search_engine: &Arc<SearchEngineBackend>,
459    semaphore: &Arc<Semaphore>,
460    max_concurrent_limit: u64,
461    backend: SearchIndexBackend,
462    safe_sequence: i64,
463    page_size: u64,
464) -> Result<(usize, usize), OperationOutcomeError> {
465    let mut pages = ProjectPages::new(page_size);
466    let mut in_flight = JoinSet::new();
467    let mut projects = 0usize;
468    let mut fetched = 0usize;
469
470    let read = loop {
471        let Ok(permit) = semaphore.clone().acquire_owned().await else {
472            tracing::warn!("Project semaphore closed; ending the indexing pass early.");
473            break Ok(());
474        };
475        let project = match pages.next(repo).await {
476            Ok(Some(project)) => project,
477            Ok(None) => break Ok(()),
478            Err(error) => break Err(error),
479        };
480        projects += 1;
481        in_flight.spawn(index_one_project(
482            project,
483            permit,
484            repo.clone(),
485            search_engine.clone(),
486            max_concurrent_limit,
487            backend,
488            safe_sequence,
489        ));
490        // Collect finished projects as we go, so the set holds little more
491        // than the projects in flight.
492        while let Some(joined) = in_flight.try_join_next() {
493            fetched += rows_fetched(joined);
494        }
495    };
496
497    while let Some(joined) = in_flight.join_next().await {
498        fetched += rows_fetched(joined);
499    }
500    read.map(|()| (projects, fetched))
501}
502
503/// The rows a project's indexing task handed to the search engine, or zero
504/// if it panicked, which is logged.
505fn rows_fetched(joined: Result<usize, JoinError>) -> usize {
506    joined.unwrap_or_else(|join_error| {
507        tracing::error!("Project indexing task panicked: '{:?}'", join_error);
508        0
509    })
510}
511
512/// Indexes one project up to `safe_sequence`, holding `_permit` until it is
513/// done, and returns the rows handed to the search engine (zero on failure,
514/// which is logged).
515async fn index_one_project(
516    project: ProjectReturn,
517    _permit: OwnedSemaphorePermit,
518    repo: Arc<PGConnection>,
519    search_engine: Arc<SearchEngineBackend>,
520    max_concurrent_limit: u64,
521    backend: SearchIndexBackend,
522    safe_sequence: i64,
523) -> usize {
524    tracing::trace!(
525        "Indexing tenant: '{}' project: '{}'",
526        &project.tenant,
527        project.project.as_ref()
528    );
529
530    // Boxed: the search engine's indexing future is large, and this one is
531    // spawned per project.
532    let result = Box::pin(index_for_project(
533        max_concurrent_limit,
534        backend,
535        repo,
536        search_engine,
537        &project.tenant,
538        &project.project,
539        safe_sequence,
540    ))
541    .await;
542
543    match result {
544        Ok(fetched) => fetched,
545        Err(error) => {
546            tracing::error!(
547                "Failed to index tenant: '{}' project: '{}' cause: '{:?}'",
548                &project.tenant,
549                project.project.as_ref(),
550                error
551            );
552            0
553        }
554    }
555}
556
557/// Default `poll_interval_ms`: short enough that a write is searchable within
558/// one poll of the `TestScript` runner's 100 ms wait, long enough to cap idle
559/// polling (and with it the watermark scans) at ten passes a second.
560const DEFAULT_POLL_INTERVAL_MS: u64 = 100;
561
562pub struct IndexingWorker {
563    max_concurrent_limit: Option<u64>,
564    tenant_concurrency: Option<u64>,
565    poll_interval: Duration,
566    running: Arc<tokio::sync::Mutex<bool>>,
567    repo: Arc<PGConnection>,
568    search_engine: Arc<SearchEngineBackend>,
569}
570
571#[derive(Clone, Deserialize, Serialize)]
572#[serde(default)]
573pub struct WorkerEnvironment {
574    pub max_concurrent_limit: Option<u64>,
575    /// Maximum number of projects indexed concurrently within one poll.
576    /// Field name kept as `tenant_concurrency` for config compatibility -
577    /// locking moved from tenant- to project-level, but this still bounds
578    /// the same underlying semaphore.
579    pub tenant_concurrency: Option<u64>,
580    /// How long a pass sleeps before polling again when no project had
581    /// anything new to index. Bounds the idle poll rate, and with it the
582    /// `max_safe_seq` watermark scans; passes that found rows run back to
583    /// back.
584    pub poll_interval_ms: Option<u64>,
585    pub repo: RepoConfig,
586    pub search: SearchConfig,
587}
588
589impl Default for WorkerEnvironment {
590    fn default() -> Self {
591        Self {
592            max_concurrent_limit: Some(1000),
593            // Matches `PostgresRepoConfig::default`'s `max_connections`.
594            tenant_concurrency: Some(10),
595            poll_interval_ms: Some(DEFAULT_POLL_INTERVAL_MS),
596            repo: RepoConfig::default(),
597            search: SearchConfig::default(),
598        }
599    }
600}
601
602impl IndexingWorker {
603    /// Creates and initializes a new worker.
604    ///
605    /// This initializes the repository and search engine using the provided
606    /// configuration, then waits for the search engine to become available.
607    /// The search engine connection is retried up to 5 times, with a 5-second
608    /// delay between attempts.
609    ///
610    /// # Arguments
611    ///
612    /// * `config` - Shared worker configuration containing the repository,
613    ///   search engine, and concurrency settings.
614    ///
615    /// # Errors
616    ///
617    /// Returns an error if:
618    /// - creating the repository fails.
619    /// - creating the search engine fails.
620    /// - the search engine remains unavailable after 5 connection attempts.
621    ///
622    /// # Returns
623    ///
624    /// Returns an initialized [`Self`] with the repository and search engine
625    /// ready for use.
626    pub async fn new(config: Arc<WorkerEnvironment>) -> Result<Self, OperationOutcomeError> {
627        let repo = create_repo(&config.repo).await?;
628
629        // This worker only writes documents, so it is never allowed to change
630        // the index's shape out from under a running server.
631        let search_engine =
632            haste_fhir_search::config::create_search_engine(&config.search, repo.clone(), false)
633                .await?;
634
635        let mut attempts = 0;
636        while search_engine.is_connected().await.is_err() && attempts < 5 {
637            tracing::error!(
638                "{} is not connected, retrying in 5 seconds...",
639                search_engine.name()
640            );
641            tokio::time::sleep(std::time::Duration::from_secs(5)).await;
642            attempts += 1;
643        }
644
645        search_engine.is_connected().await?;
646
647        Ok(Self {
648            max_concurrent_limit: config.max_concurrent_limit,
649            tenant_concurrency: config.tenant_concurrency,
650            poll_interval: Duration::from_millis(
651                config.poll_interval_ms.unwrap_or(DEFAULT_POLL_INTERVAL_MS),
652            ),
653            running: Arc::new(tokio::sync::Mutex::new(true)),
654            repo,
655            search_engine,
656        })
657    }
658}
659
660impl Worker for IndexingWorker {
661    async fn run(&self) -> Result<JoinHandle<()>, OperationOutcomeError> {
662        let projects_page_size: u64 = 100;
663
664        tracing::info!("Starting indexing worker...");
665
666        let mut k = *TOTAL_INDEXED.lock().await;
667
668        let repo = self.repo.clone();
669        let search_engine: Arc<SearchEngineBackend> = self.search_engine.clone();
670        let backend = search_engine.lock_kind();
671        let running = self.running.clone();
672        let max_concurrent_limit = self.max_concurrent_limit.unwrap_or(1000);
673        let poll_interval = self.poll_interval;
674        // With nothing to poll at all (no projects, or the fetch failed) there
675        // is no reason to look again soon.
676        let idle_backoff = Duration::from_secs(1);
677        let project_semaphore = Arc::new(Semaphore::new(
678            usize::try_from(self.tenant_concurrency.unwrap_or(10).max(1)).unwrap_or(usize::MAX),
679        ));
680
681        let spawned = tokio::spawn(async move {
682            while *running.lock().await {
683                // One watermark per pass. It is a property of the sequence, not
684                // of a project, and it is the expensive half of a poll (a scan
685                // of `pg_locks`), so every project in this pass reads up to the
686                // same value.
687                let safe_sequence = match repo.max_safe_sequence().await {
688                    Ok(safe_sequence) => safe_sequence,
689                    Err(error) => {
690                        tracing::error!("Failed to read the safe sequence watermark: {:?}", error);
691                        tokio::time::sleep(idle_backoff).await;
692                        continue;
693                    }
694                };
695
696                // Every pass polls every project.
697                let pass = index_all_projects(
698                    &repo,
699                    &search_engine,
700                    &project_semaphore,
701                    max_concurrent_limit,
702                    backend,
703                    safe_sequence,
704                    projects_page_size,
705                )
706                .await;
707
708                // How long to wait before the next pass: `idle_backoff` with
709                // nothing to poll (no projects, or the fetch failed), the poll
710                // interval when the projects had nothing new, and none at all
711                // while rows are flowing.
712                let backoff = match pass {
713                    Ok((0, _)) => Some(idle_backoff),
714                    Ok((_, 0)) => Some(poll_interval),
715                    Ok(_) => None,
716                    Err(error) => {
717                        tracing::error!("Failed to retrieve projects: {:?}", error);
718                        Some(idle_backoff)
719                    }
720                };
721
722                if k != *TOTAL_INDEXED.lock().await {
723                    k = *TOTAL_INDEXED.lock().await;
724                    tracing::info!("TOTAL INDEXED SO FAR: {}", k);
725                }
726
727                if let Some(backoff) = backoff {
728                    tokio::time::sleep(backoff).await;
729                }
730            }
731        });
732
733        Ok(spawned)
734    }
735
736    async fn stop(&mut self) -> Result<(), OperationOutcomeError> {
737        let mut running = self.running.lock().await;
738        *running = false;
739        Ok(())
740    }
741}
742
743#[cfg(test)]
744mod tests {
745    use super::*;
746    use sqlx::PgPool;
747
748    /// Walks `pages` to the end, as a pass does.
749    async fn rest_of(pages: &mut ProjectPages, repo: &PGConnection) -> Vec<(String, String)> {
750        let mut returned = Vec::new();
751        while let Some(project) = pages.next(repo).await.expect("projects are read") {
752            returned.push((
753                project.tenant.as_ref().to_owned(),
754                project.project.as_ref().to_owned(),
755            ));
756        }
757        returned
758    }
759
760    /// Every project comes back once, in key order, whether the last page is
761    /// short, exactly full or the only one. The worker used to read only the
762    /// newest page, so projects past the first page were never indexed.
763    #[sqlx::test(migrations = "../repository/pg-migrations")]
764    async fn project_pages_return_every_project_once(pool: PgPool) -> sqlx::Result<()> {
765        sqlx::query("INSERT INTO tenants (id) VALUES ('tenant-a'), ('tenant-b')")
766            .execute(&pool)
767            .await?;
768        // One statement, so these projects all share one `created_at`.
769        sqlx::query(
770            "INSERT INTO projects (tenant, id, fhir_version)
771             SELECT tenant, 'project-' || n, 'r4'
772             FROM unnest(ARRAY['tenant-a', 'tenant-b']) AS tenant, generate_series(1, 6) AS n",
773        )
774        .execute(&pool)
775        .await?;
776        let expected: Vec<(String, String)> =
777            sqlx::query_as("SELECT tenant, id FROM projects ORDER BY tenant, id")
778                .fetch_all(&pool)
779                .await?;
780
781        let repo = PGConnection::pool(pool.clone());
782        let total = expected.len() as u64;
783        for page_size in [1, 4, total - 1, total, total + 1] {
784            let mut pages = ProjectPages::new(page_size);
785            assert_eq!(
786                rest_of(&mut pages, &repo).await,
787                expected,
788                "page size {page_size}"
789            );
790            assert!(
791                pages
792                    .next(&repo)
793                    .await
794                    .expect("projects are read")
795                    .is_none(),
796                "page size {page_size}"
797            );
798        }
799
800        sqlx::query("DELETE FROM projects").execute(&pool).await?;
801        let mut pages = ProjectPages::new(4);
802        assert!(rest_of(&mut pages, &repo).await.is_empty());
803        Ok(())
804    }
805
806    /// A page is read only once the one before has been handed out, so a
807    /// project created mid-pass after the pages read so far is still polled
808    /// in that pass.
809    #[sqlx::test(migrations = "../repository/pg-migrations")]
810    async fn project_pages_read_each_page_when_needed(pool: PgPool) -> sqlx::Result<()> {
811        sqlx::query("INSERT INTO tenants (id) VALUES ('tenant-a'), ('tenant-b')")
812            .execute(&pool)
813            .await?;
814        sqlx::query(
815            "INSERT INTO projects (tenant, id, fhir_version)
816             SELECT 'tenant-a', 'project-' || n, 'r4' FROM generate_series(1, 6) AS n",
817        )
818        .execute(&pool)
819        .await?;
820
821        let repo = PGConnection::pool(pool.clone());
822        let mut pages = ProjectPages::new(4);
823        let first = pages
824            .next(&repo)
825            .await
826            .expect("projects are read")
827            .expect("there are projects");
828        sqlx::query(
829            "INSERT INTO projects (tenant, id, fhir_version) VALUES ('tenant-b', 'late', 'r4')",
830        )
831        .execute(&pool)
832        .await?;
833
834        let mut returned = vec![(
835            first.tenant.as_ref().to_owned(),
836            first.project.as_ref().to_owned(),
837        )];
838        returned.extend(rest_of(&mut pages, &repo).await);
839        let expected: Vec<(String, String)> =
840            sqlx::query_as("SELECT tenant, id FROM projects ORDER BY tenant, id")
841                .fetch_all(&pool)
842                .await?;
843        assert_eq!(returned, expected);
844        assert_eq!(
845            returned.last(),
846            Some(&("tenant-b".to_owned(), "late".to_owned()))
847        );
848        Ok(())
849    }
850}