Skip to main content

reddb_server/runtime/
impl_primary_replica_file.rs

1use super::*;
2
3impl RedDBRuntime {
4    pub fn replica_relay_manifest_path(&self, replica_id: &str) -> Option<std::path::PathBuf> {
5        let plan = self.primary_replica_file_plan()?;
6        Some(plan.relay_manifest_path(replica_id))
7    }
8
9    pub fn replica_relay_manifest(
10        &self,
11        replica_id: &str,
12    ) -> RedDBResult<Option<reddb_file::ReplicaRelayLogManifest>> {
13        let key = format!("replication.relay.{}", hex::encode(replica_id));
14        if let Some(bytes) = crate::replication::metadata::read(&self.inner.db.store(), &key)
15            .map_err(|err| RedDBError::Internal(err.to_string()))?
16        {
17            return reddb_file::ReplicaRelayLogManifest::decode(&bytes)
18                .map(Some)
19                .map_err(|err| RedDBError::Internal(err.to_string()));
20        }
21        let Some(path) = self.replica_relay_manifest_path(replica_id) else {
22            return Ok(None);
23        };
24        match reddb_file::ReplicaRelayLogManifest::read_from_path(path) {
25            Ok(manifest) => Ok(Some(manifest)),
26            Err(reddb_file::RdbFileError::Io(error))
27                if error.kind() == std::io::ErrorKind::NotFound =>
28            {
29                Ok(None)
30            }
31            Err(error) => Err(RedDBError::Internal(error.to_string())),
32        }
33    }
34
35    fn current_replica_relay_manifest(
36        &self,
37        replica_id: &str,
38    ) -> RedDBResult<reddb_file::ReplicaRelayLogManifest> {
39        let manifest = match self.replica_relay_manifest(replica_id)? {
40            Some(manifest) => manifest,
41            None => reddb_file::ReplicaRelayLogManifest::new(
42                replica_id,
43                reddb_file::TimelineId::initial(),
44            ),
45        };
46        if manifest.replica_id != replica_id {
47            return Err(RedDBError::Internal(format!(
48                "relay manifest replica_id {} does not match {}",
49                manifest.replica_id, replica_id
50            )));
51        }
52        if manifest.timeline != reddb_file::TimelineId::initial() {
53            return Err(RedDBError::Internal(format!(
54                "relay manifest timeline {} is not current timeline {}",
55                manifest.timeline.0,
56                reddb_file::TimelineId::initial().0
57            )));
58        }
59
60        Ok(manifest)
61    }
62
63    pub(crate) fn validate_replica_relay_history(&self, replica_id: &str) -> RedDBResult<()> {
64        let store = self.inner.db.store();
65        let _publication = store.vault_publication_lock.lock();
66        let Some(plan) = self.primary_replica_file_plan_result()? else {
67            return Ok(());
68        };
69        self.current_replica_relay_manifest(replica_id)?
70            .validate_segments(plan.relay_dir(replica_id))
71            .map_err(|err| {
72                RedDBError::Internal(format!(
73                    "validate replica {replica_id} relay history: {err}"
74                ))
75            })
76    }
77
78    pub fn primary_replica_file_plan(&self) -> Option<reddb_file::PrimaryReplicaFilePlan> {
79        self.primary_replica_file_plan_result().ok().flatten()
80    }
81
82    fn primary_replica_root(&self) -> Option<std::path::PathBuf> {
83        let data_path = self.inner.db.options().data_path.as_ref()?;
84        Some(crate::replication::primary::PrimaryReplication::primary_replica_root_for(data_path))
85    }
86
87    pub fn primary_replica_file_plan_result(
88        &self,
89    ) -> RedDBResult<Option<reddb_file::PrimaryReplicaFilePlan>> {
90        let Some(root) = self.primary_replica_root() else {
91            return Ok(None);
92        };
93        let timeline = self.primary_replica_current_timeline(&root)?;
94        Ok(Some(reddb_file::PrimaryReplicaFilePlan::new(
95            root, timeline,
96        )))
97    }
98
99    fn primary_replica_current_timeline(
100        &self,
101        root: &std::path::Path,
102    ) -> RedDBResult<reddb_file::TimelineId> {
103        let path = reddb_file::PrimaryReplicaFilePlan::new(root, reddb_file::TimelineId::initial())
104            .timeline_history_path();
105        crate::replication::metadata::timeline(&self.inner.db.store(), &path)
106            .map(|history| {
107                history
108                    .current()
109                    .unwrap_or_else(reddb_file::TimelineId::initial)
110            })
111            .map_err(|err| RedDBError::Internal(err.to_string()))
112    }
113
114    pub fn create_primary_replica_basebackup(
115        &self,
116        chunk_bytes: usize,
117    ) -> RedDBResult<Option<reddb_file::PrimaryReplicaBaseBackupManifest>> {
118        let Some(plan) = self.primary_replica_file_plan_result()? else {
119            return Ok(None);
120        };
121        let store = self.inner.db.store();
122        let _publication = store.vault_publication_lock.lock();
123        self.flush()?;
124        let checkpoint_lsn = self
125            .primary_logical_head_lsn()
126            .max(self.replication_commit_lsn());
127        let backup = reddb_file::BaseBackupPlan::new(plan.timeline, 0, checkpoint_lsn);
128        let path = plan.basebackup_path(&backup);
129        if self.inner.db.replication.is_some() && path.try_exists()? {
130            // Registering another replica changes local metadata without advancing the
131            // logical WAL. Resume from the bytes already published for this frontier.
132            let manifest = reddb_file::PrimaryReplicaBaseBackupManifest::read_from_path(&path)
133                .map_err(|err| RedDBError::Internal(err.to_string()))?;
134            if (
135                manifest.timeline,
136                manifest.start_lsn,
137                manifest.checkpoint_lsn,
138            ) != (backup.timeline, backup.start_lsn, backup.checkpoint_lsn)
139            {
140                return Err(RedDBError::Internal(
141                    "basebackup manifest frontier mismatch".into(),
142                ));
143            }
144            manifest
145                .verify_snapshot_parts(plan.basebackup_dir())
146                .map_err(|err| RedDBError::Internal(err.to_string()))?;
147            return Ok(Some(manifest));
148        }
149        let snapshot = store.to_binary_dump_bytes();
150        let manifest = plan
151            .write_basebackup_snapshot_parts(backup, &snapshot, chunk_bytes)
152            .map_err(|err| RedDBError::Internal(err.to_string()))?;
153        manifest
154            .write_to_path(path)
155            .map_err(|err| RedDBError::Internal(err.to_string()))?;
156        Ok(Some(manifest))
157    }
158
159    pub fn materialize_primary_replica_basebackup_snapshot(
160        &self,
161        manifest: &reddb_file::PrimaryReplicaBaseBackupManifest,
162        parts_root: impl AsRef<std::path::Path>,
163        destination: impl AsRef<std::path::Path>,
164    ) -> RedDBResult<u64> {
165        self.materialize_primary_replica_basebackup_snapshot_for_replica(
166            manifest,
167            parts_root,
168            destination,
169            None,
170            None,
171        )
172    }
173
174    fn materialize_primary_replica_basebackup_snapshot_for_replica(
175        &self,
176        manifest: &reddb_file::PrimaryReplicaBaseBackupManifest,
177        parts_root: impl AsRef<std::path::Path>,
178        destination: impl AsRef<std::path::Path>,
179        replica_id: Option<&str>,
180        snapshot_token: Option<&str>,
181    ) -> RedDBResult<u64> {
182        let snapshot = manifest
183            .read_snapshot_parts(parts_root)
184            .map_err(|err| RedDBError::Internal(err.to_string()))?;
185        let loaded = crate::storage::unified::UnifiedStore::load_from_bytes_with_config(
186            &snapshot,
187            crate::storage::unified::UnifiedStoreConfig::default(),
188        )
189        .map_err(|err| RedDBError::Internal(format!("validate basebackup snapshot: {err}")))?;
190        loaded
191            .normalize_red_config_keys()
192            .map_err(RedDBError::from)?;
193        loaded.set_config_tree(
194            "replication",
195            &crate::json!({
196                "last_applied_lsn": manifest.checkpoint_lsn,
197                "state": "healthy",
198                "last_error": "",
199            }),
200        );
201        if let Some(replica_id) = replica_id {
202            loaded.set_config_tree(
203                "replication",
204                &crate::json!({
205                    "replica_id": replica_id,
206                }),
207            );
208        }
209        if let Some(snapshot_token) = snapshot_token {
210            loaded.set_config_tree(
211                "replication",
212                &crate::json!({
213                    "rebootstrap_snapshot_token": snapshot_token,
214                }),
215            );
216        }
217        let snapshot = loaded.to_binary_dump_bytes();
218        let destination = destination.as_ref();
219        if let Some(parent) = destination.parent() {
220            std::fs::create_dir_all(parent)?;
221        }
222        crate::storage::EmbeddedRdbArtifact::create_with_snapshot(destination, &snapshot)?;
223        Ok(manifest.checkpoint_lsn)
224    }
225
226    pub fn replica_rebootstrap_staging_root(&self) -> Option<std::path::PathBuf> {
227        let data_path = self.inner.db.options().data_path.as_ref()?;
228        Some(reddb_file::layout::rebootstrap_staging_root(data_path))
229    }
230
231    pub fn replica_rebootstrap_pending_path(&self) -> Option<std::path::PathBuf> {
232        let data_path = self.inner.db.options().data_path.as_ref()?;
233        Some(reddb_file::layout::rebootstrap_pending_path(data_path))
234    }
235
236    pub(crate) async fn stage_primary_replica_rebootstrap_from_snapshot(
237        &self,
238        client: &mut crate::grpc::proto::red_db_client::RedDbClient<tonic::transport::Channel>,
239        chunk_bytes: usize,
240    ) -> RedDBResult<Option<u64>> {
241        let Some(parts_root) = self.replica_rebootstrap_staging_root() else {
242            return Ok(None);
243        };
244        let Some(pending_path) = self.replica_rebootstrap_pending_path() else {
245            return Ok(None);
246        };
247        let data_path = self
248            .inner
249            .db
250            .options()
251            .data_path
252            .as_ref()
253            .ok_or_else(|| RedDBError::Internal("replica data path unavailable".into()))?;
254        let intent_log_path = reddb_file::layout::rebootstrap_intent_log_path(data_path);
255        let intent_log = crate::telemetry::admin_intent_log::AdminIntentLog::open(intent_log_path)
256            .map_err(|err| RedDBError::Internal(err.to_string()))?;
257        let replica_id = self.resolve_replica_id();
258        let bootstrapper =
259            crate::replication::replica::ReplicaBootstrapper::new(replica_id.clone());
260        let source_lsn = self.config_u64("replication.last_applied_lsn", 0);
261        let _ = std::fs::remove_file(&pending_path);
262
263        let chunk_bytes = chunk_bytes.max(1);
264        let (resume, mut bootstrap_handle) = match bootstrapper.resume(&intent_log) {
265            Some((resume, handle)) => (Some(resume), handle),
266            None => (
267                None,
268                bootstrapper
269                    .begin(&intent_log, source_lsn, 0)
270                    .map_err(|err| RedDBError::Internal(err.to_string()))?,
271            ),
272        };
273        let mut token: Option<String> = resume
274            .as_ref()
275            .and_then(|resume| resume.snapshot_token.clone());
276        let mut manifest: Option<reddb_file::PrimaryReplicaBaseBackupManifest> = None;
277        let mut written = std::collections::BTreeSet::new();
278        let mut offset = resume
279            .as_ref()
280            .map(|resume| resume.snapshot_offset)
281            .unwrap_or(0);
282
283        let request_auth = crate::replication::request_auth::ReplicaRequestAuth::from_env()
284            .map_err(|message| RedDBError::InvalidOperation(message.into()))?;
285        loop {
286            let mut request = tonic::Request::new(crate::grpc::proto::Empty {});
287            request_auth.authorize(&mut request);
288            request.metadata_mut().insert(
289                "x-reddb-replica-id",
290                replica_id
291                    .parse()
292                    .map_err(|err| RedDBError::Internal(format!("replica id metadata: {err}")))?,
293            );
294            request.metadata_mut().insert(
295                "x-reddb-snapshot-max-bytes",
296                chunk_bytes
297                    .to_string()
298                    .parse()
299                    .map_err(|err| RedDBError::Internal(format!("snapshot max bytes: {err}")))?,
300            );
301            request.metadata_mut().insert(
302                "x-reddb-snapshot-offset",
303                offset
304                    .to_string()
305                    .parse()
306                    .map_err(|err| RedDBError::Internal(format!("snapshot offset: {err}")))?,
307            );
308            if let Some(token) = &token {
309                request.metadata_mut().insert(
310                    "x-reddb-snapshot-token",
311                    token.parse().map_err(|err| {
312                        RedDBError::Internal(format!("snapshot token metadata: {err}"))
313                    })?,
314                );
315            }
316
317            let response = client
318                .replication_snapshot(request)
319                .await
320                .map_err(|err| RedDBError::Internal(format!("replication snapshot: {err}")))?;
321            let payload = reddb_wire::replication::BaseBackupChunk::decode_json(
322                response.into_inner().payload.as_bytes(),
323            )
324            .map_err(|err| RedDBError::Internal(format!("parse replication snapshot: {err}")))?;
325            if token.is_none() {
326                token = payload.snapshot_token.clone();
327            }
328            let staged =
329                crate::replication::replica::stage_basebackup_snapshot_chunk(&payload, &parts_root)
330                    .map_err(|err| RedDBError::Internal(err.to_string()))?
331                    .ok_or_else(|| {
332                        RedDBError::Internal(
333                            "replication snapshot did not include basebackup payload".into(),
334                        )
335                    })?;
336            if let Some(existing) = &manifest {
337                if existing != &staged.manifest {
338                    return Err(RedDBError::Internal(
339                        "replication snapshot basebackup manifest changed while downloading".into(),
340                    ));
341                }
342            } else {
343                manifest = Some(staged.manifest.clone());
344                written.extend(
345                    crate::replication::replica::recover_staged_basebackup_chunks(
346                        &staged.manifest,
347                        &parts_root,
348                    )
349                    .map_err(|err| RedDBError::Internal(err.to_string()))?,
350                );
351            }
352            if let Some(ordinal) = staged.chunk_ordinal {
353                written.insert(ordinal);
354            }
355            let current = manifest
356                .as_ref()
357                .expect("manifest set after staging basebackup chunk");
358            if current
359                .chunks
360                .iter()
361                .all(|chunk| written.contains(&chunk.ordinal))
362            {
363                current
364                    .verify_snapshot_parts(&parts_root)
365                    .map_err(|err| RedDBError::Internal(err.to_string()))?;
366                let snapshot_token = token.as_deref().ok_or_else(|| {
367                    RedDBError::Internal(
368                        "replication snapshot omitted its installation token".into(),
369                    )
370                })?;
371                let checkpoint_lsn = self
372                    .materialize_primary_replica_basebackup_snapshot_for_replica(
373                        current,
374                        &parts_root,
375                        &pending_path,
376                        Some(&replica_id),
377                        Some(snapshot_token),
378                    )?;
379                let data_path =
380                    self.inner.db.options().data_path.as_ref().ok_or_else(|| {
381                        RedDBError::Internal("replica data path unavailable".into())
382                    })?;
383                reddb_file::write_rebootstrap_ready_marker(
384                    data_path,
385                    &reddb_file::ReplicaRebootstrapReadyMarker {
386                        pending_path: pending_path.clone(),
387                        checkpoint_lsn,
388                        timeline: current.timeline,
389                    },
390                )
391                .map_err(|err| RedDBError::Internal(err.to_string()))?;
392                self.inner.db.store().set_config_tree(
393                    "replication",
394                    &crate::json!({
395                        "state": "rebootstrap_ready",
396                        "rebootstrap_pending_path": pending_path.display().to_string(),
397                        "rebootstrap_checkpoint_lsn": checkpoint_lsn,
398                        "rebootstrap_timeline": current.timeline.0,
399                    }),
400                );
401                bootstrap_handle
402                    .complete(current.chunks.len() as u64, 0)
403                    .map_err(|err| RedDBError::Internal(err.to_string()))?;
404                return Ok(Some(checkpoint_lsn));
405            }
406            let next = current
407                .chunks
408                .iter()
409                .find(|chunk| !written.contains(&chunk.ordinal))
410                .ok_or_else(|| RedDBError::Internal("basebackup chunk tracking stalled".into()))?;
411            offset = next.snapshot_offset;
412            if let Some(snapshot_token) = token.as_deref() {
413                bootstrap_handle
414                    .checkpoint_snapshot_transfer(
415                        snapshot_token,
416                        offset,
417                        source_lsn,
418                        written.len() as u64,
419                    )
420                    .map_err(|err| RedDBError::Internal(err.to_string()))?;
421            }
422        }
423    }
424
425    pub fn primary_replica_slot_catalog(
426        &self,
427    ) -> RedDBResult<Option<reddb_file::ReplicationSlotCatalog>> {
428        let store = self.inner.db.store();
429        let _publication = store.vault_publication_lock.lock();
430        if let Some(primary) = self.inner.db.replication.as_ref() {
431            primary
432                .ensure_slot_metadata_durable()
433                .map_err(|err| RedDBError::Internal(err.to_string()))?;
434        }
435        if let Some(bytes) = crate::replication::metadata::read(
436            &self.inner.db.store(),
437            crate::replication::metadata::SLOTS,
438        )
439        .map_err(|err| RedDBError::Internal(err.to_string()))?
440        {
441            return reddb_file::ReplicationSlotCatalog::decode(&bytes)
442                .map(Some)
443                .map_err(|err| RedDBError::Internal(err.to_string()));
444        }
445        let Some(plan) = self.primary_replica_file_plan_result()? else {
446            return Ok(None);
447        };
448        match reddb_file::ReplicationSlotCatalog::read_from_path(plan.slots_path()) {
449            Ok(catalog) => Ok(Some(catalog)),
450            Err(reddb_file::RdbFileError::Io(err))
451                if err.kind() == std::io::ErrorKind::NotFound =>
452            {
453                Ok(None)
454            }
455            Err(err) => Err(RedDBError::Internal(err.to_string())),
456        }
457    }
458
459    fn primary_replica_fork_lsns(&self) -> RedDBResult<Vec<u64>> {
460        let Some(data_path) = self.inner.db.options().data_path.as_ref() else {
461            return Ok(Vec::new());
462        };
463        self.inner
464            .db
465            .store()
466            .operational_manifest_for_path(data_path)
467            .list_forks()
468            .map(|forks| forks.into_iter().map(|fork| fork.fork_lsn).collect())
469            .map_err(|err| RedDBError::Internal(err.to_string()))
470    }
471
472    pub fn primary_replica_wal_retention_plan(
473        &self,
474    ) -> RedDBResult<Option<reddb_file::WalRetentionPlan>> {
475        let Some(plan) = self.primary_replica_file_plan_result()? else {
476            return Ok(None);
477        };
478        let Some(catalog) = self.primary_replica_slot_catalog()? else {
479            return Ok(None);
480        };
481        let current_lsn = self
482            .primary_logical_head_lsn()
483            .max(self.replication_commit_lsn());
484        let fork_lsns = self.primary_replica_fork_lsns()?;
485        Ok(Some(
486            plan.plan_wal_retention_with_fork_lsns(&catalog, &fork_lsns, current_lsn)
487                .map_err(|err| RedDBError::Internal(err.to_string()))?,
488        ))
489    }
490
491    pub fn primary_replica_catchup_mode(
492        &self,
493        available_from_lsn: u64,
494        replica_lsn: u64,
495    ) -> RedDBResult<Option<reddb_file::ReplicaCatchupMode>> {
496        let Some(plan) = self.primary_replica_file_plan_result()? else {
497            return Ok(None);
498        };
499        let basebackups = plan
500            .list_basebackups()
501            .map_err(|err| RedDBError::Internal(err.to_string()))?;
502        Ok(Some(plan.catchup_mode_with_basebackups(
503            available_from_lsn,
504            replica_lsn,
505            &basebackups,
506        )))
507    }
508
509    pub fn primary_replica_timeline_history_path(&self) -> Option<std::path::PathBuf> {
510        let root = self.primary_replica_root()?;
511        Some(
512            reddb_file::PrimaryReplicaFilePlan::new(root, reddb_file::TimelineId::initial())
513                .timeline_history_path(),
514        )
515    }
516
517    /// Authoritative history in the database, with read-only legacy import fallback.
518    pub fn primary_replica_timeline_history(
519        &self,
520    ) -> RedDBResult<Option<reddb_file::TimelineHistory>> {
521        let Some(path) = self.primary_replica_timeline_history_path() else {
522            return Ok(None);
523        };
524        crate::replication::metadata::timeline(&self.inner.db.store(), &path)
525            .map(Some)
526            .map_err(|err| RedDBError::Internal(err.to_string()))
527    }
528
529    pub fn primary_replica_rejoin_decision(
530        &self,
531        node_timeline: reddb_file::TimelineId,
532        node_flushed_lsn: u64,
533        available_from_lsn: u64,
534    ) -> RedDBResult<Option<reddb_file::RejoinDecision>> {
535        let Some(history) = self.primary_replica_timeline_history()? else {
536            return Ok(None);
537        };
538        Ok(Some(history.rejoin_decision(
539            node_timeline,
540            node_flushed_lsn,
541            available_from_lsn,
542        )))
543    }
544
545    pub fn persist_primary_replica_rejoin_plan(
546        &self,
547        node_timeline: reddb_file::TimelineId,
548        node_flushed_lsn: u64,
549        available_from_lsn: u64,
550    ) -> RedDBResult<Option<reddb_file::RejoinDecision>> {
551        let Some(decision) = self.primary_replica_rejoin_decision(
552            node_timeline,
553            node_flushed_lsn,
554            available_from_lsn,
555        )?
556        else {
557            return Ok(None);
558        };
559
560        let (state, target_timeline, rewind_to_lsn, start_lsn) = match decision {
561            reddb_file::RejoinDecision::AlreadyCurrent => {
562                ("timeline_current", node_timeline.0, 0, node_flushed_lsn)
563            }
564            reddb_file::RejoinDecision::FollowNewTimeline {
565                target_timeline,
566                start_lsn,
567            } => ("rejoin_follow_wal", target_timeline.0, 0, start_lsn),
568            reddb_file::RejoinDecision::Rewind {
569                target_timeline,
570                rewind_to_lsn,
571            } => (
572                "rejoin_rewind_required",
573                target_timeline.0,
574                rewind_to_lsn,
575                0,
576            ),
577            reddb_file::RejoinDecision::Reclone => ("reclone_required", 0, 0, 0),
578        };
579        self.inner.db.store().set_config_tree(
580            "replication",
581            &crate::json!({
582                "state": state,
583                "rejoin_node_timeline": node_timeline.0,
584                "rejoin_node_flushed_lsn": node_flushed_lsn,
585                "rejoin_available_from_lsn": available_from_lsn,
586                "rejoin_target_timeline": target_timeline,
587                "rejoin_rewind_to_lsn": rewind_to_lsn,
588                "rejoin_start_lsn": start_lsn,
589                "rejoin_rewind_confirmed_timeline": 0,
590                "rejoin_rewind_confirmed_lsn": 0,
591            }),
592        );
593
594        Ok(Some(decision))
595    }
596
597    pub fn prune_primary_replica_wal_segments(
598        &self,
599    ) -> RedDBResult<Option<reddb_file::WalPruneResult>> {
600        let current_lsn = self
601            .primary_logical_head_lsn()
602            .max(self.replication_commit_lsn());
603        self.prune_primary_replica_wal_segments_at(current_lsn)
604    }
605
606    fn prune_primary_replica_wal_segments_at(
607        &self,
608        current_lsn: u64,
609    ) -> RedDBResult<Option<reddb_file::WalPruneResult>> {
610        let Some(plan) = self.primary_replica_file_plan_result()? else {
611            return Ok(None);
612        };
613        let Some(catalog) = self.primary_replica_slot_catalog()? else {
614            return Ok(None);
615        };
616        let fork_lsns = self.primary_replica_fork_lsns()?;
617        Ok(Some(
618            plan.prune_wal_segments_with_fork_lsns(&catalog, &fork_lsns, current_lsn)
619                .map_err(|err| RedDBError::Internal(err.to_string()))?,
620        ))
621    }
622
623    pub fn ack_primary_replica_lsn_and_prune(
624        &self,
625        replica_id: &str,
626        applied_lsn: u64,
627        durable_lsn: u64,
628        apply_errors_total: u64,
629        divergence_total: u64,
630    ) -> RedDBResult<Option<reddb_file::WalPruneResult>> {
631        let Some(repl) = self.inner.db.replication.as_ref() else {
632            return Ok(None);
633        };
634        repl.ack_replica_lsn_with_observability(
635            replica_id,
636            applied_lsn,
637            durable_lsn,
638            apply_errors_total,
639            divergence_total,
640        );
641        self.refresh_replication_flow_control();
642        let current_lsn = self
643            .primary_logical_head_lsn()
644            .max(self.replication_commit_lsn())
645            .max(applied_lsn)
646            .max(durable_lsn);
647        self.prune_primary_replica_wal_segments_at(current_lsn)
648    }
649
650    pub fn record_failover_timeline_promotion(
651        &self,
652        replica_id: &str,
653        applied_lsn: u64,
654    ) -> RedDBResult<reddb_file::TimelineHistory> {
655        let store = self.inner.db.store();
656        let _publication = store.vault_publication_lock.lock();
657        self.validate_replica_relay_history(replica_id)?;
658        self.record_verified_failover_timeline_promotion(replica_id, applied_lsn)
659    }
660
661    /// The HTTP promotion path checks the immutable relay before acquiring the writer lease.
662    pub(crate) fn record_verified_failover_timeline_promotion(
663        &self,
664        replica_id: &str,
665        applied_lsn: u64,
666    ) -> RedDBResult<reddb_file::TimelineHistory> {
667        let store = self.inner.db.store();
668        let _publication = store.vault_publication_lock.lock();
669        let Some(history) = self.primary_replica_timeline_history()? else {
670            return Ok(reddb_file::TimelineHistory::new(
671                crate::utils::now_unix_millis(),
672            ));
673        };
674        let now_ms = crate::utils::now_unix_millis();
675        let parent = history
676            .current()
677            .unwrap_or_else(reddb_file::TimelineId::initial);
678        let candidate = reddb_file::PromotionCandidate {
679            replica_id: replica_id.to_string(),
680            timeline: parent,
681            received_lsn: applied_lsn,
682            flushed_lsn: applied_lsn,
683            applied_lsn,
684        };
685        let promoted = history
686            .promotion_history(&candidate, parent.next(), now_ms)
687            .map_err(|err| RedDBError::Internal(err.to_string()))?;
688        if let Some(mut catalog) = self.primary_replica_slot_catalog()? {
689            if !history
690                .entries
691                .iter()
692                .any(|entry| entry.timeline == catalog.timeline)
693            {
694                return Err(RedDBError::Internal(format!(
695                    "slot catalog timeline {} is outside the promotion history",
696                    catalog.timeline.0
697                )));
698            }
699            let previous_count = catalog.slots.len();
700            catalog.slots.retain(|slot| slot.replica_id != replica_id);
701            if catalog.slots.len() != previous_count {
702                // The candidate is becoming the writer, not a downstream
703                // consumer of itself. Retire its old slot durably before
704                // publishing the timeline so a crash cannot resurrect the pin.
705                crate::replication::metadata::write(
706                    &store,
707                    crate::replication::metadata::SLOTS,
708                    &catalog
709                        .encode()
710                        .map_err(|err| RedDBError::Internal(err.to_string()))?,
711                )
712                .map_err(|err| RedDBError::Internal(err.to_string()))?;
713            }
714        }
715        crate::replication::metadata::write(
716            &self.inner.db.store(),
717            crate::replication::metadata::TIMELINE,
718            &promoted.encode(),
719        )
720        .map_err(|err| RedDBError::Internal(err.to_string()))?;
721        if let Some(path) = self.primary_replica_timeline_history_path() {
722            crate::replication::metadata::retire_legacy(&path)
723                .map_err(|err| RedDBError::Internal(err.to_string()))?;
724        }
725        Ok(promoted)
726    }
727
728    pub fn record_replica_relay_batch<T: AsRef<[u8]>>(
729        &self,
730        replica_id: &str,
731        records: &[(u64, T)],
732        applied_lsn: u64,
733    ) -> RedDBResult<()> {
734        let store = self.inner.db.store();
735        let _publication = store.vault_publication_lock.lock();
736        let Some(plan) = self.primary_replica_file_plan_result()? else {
737            return Ok(());
738        };
739        let path = plan.relay_manifest_path(replica_id);
740        let Some((first_lsn, _)) = records.first() else {
741            return Ok(());
742        };
743        let end_lsn = records
744            .iter()
745            .map(|(lsn, _)| *lsn)
746            .max()
747            .unwrap_or(*first_lsn);
748        let mut manifest = self.current_replica_relay_manifest(replica_id)?;
749
750        if end_lsn > manifest.flushed_lsn {
751            let new_records = records
752                .iter()
753                .filter(|(lsn, _)| *lsn > manifest.flushed_lsn)
754                .map(|(lsn, payload)| {
755                    reddb_file::ReplicaRelayLogRecord::new(*lsn, payload.as_ref().to_vec())
756                })
757                .collect::<Vec<_>>();
758            let segment = reddb_file::ReplicaRelayLogSegment::from_records(
759                reddb_file::TimelineId::initial(),
760                new_records,
761            )
762            .map_err(|err| RedDBError::Internal(err.to_string()))?;
763            let start_lsn = segment.start_lsn;
764            let end_lsn = segment.end_lsn;
765            let relative_path = reddb_file::layout::relay_segment_relative_path(start_lsn, end_lsn);
766            let checksum = segment
767                .write_verified_to_path(&plan.relay_dir(replica_id).join(&relative_path))
768                .map_err(|err| RedDBError::Internal(err.to_string()))?;
769            let segment_ref =
770                reddb_file::RelayLogSegmentRef::new(relative_path, start_lsn, end_lsn, checksum)
771                    .map_err(|err| RedDBError::Internal(err.to_string()))?;
772            manifest
773                .push_segment(segment_ref)
774                .map_err(|err| RedDBError::Internal(err.to_string()))?;
775        }
776        manifest
777            .mark_applied(applied_lsn.min(manifest.flushed_lsn))
778            .map_err(|err| RedDBError::Internal(err.to_string()))?;
779        let bytes = manifest
780            .encode()
781            .map_err(|err| RedDBError::Internal(err.to_string()))?;
782        crate::replication::metadata::write(
783            &self.inner.db.store(),
784            &format!("replication.relay.{}", hex::encode(replica_id)),
785            &bytes,
786        )
787        .map_err(|err| RedDBError::Internal(err.to_string()))?;
788        crate::replication::metadata::retire_legacy(&path)
789            .map_err(|err| RedDBError::Internal(err.to_string()))
790    }
791}