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