1use super::builder::OpenInputs;
8use super::{DatabaseBuilder, StoreDatabase};
9use crate::migration::MigrationKind;
10use crate::{DbError, OpenError, SnapshotWriteError};
11use coven_foundation::clock::ClockRef;
12use coven_foundation::files::{FileError, SettingsError, StoreDir, StoreDirAccess};
13use coven_foundation::id_source::IdSourceRef;
14use coven_merge::Audience;
15
16#[derive(Debug, thiserror::Error)]
18pub enum RebuildError {
19 #[error("{circle} at version {version} is not below a breaking migration")]
22 NotBelow {
23 circle: Audience,
25 version: u32,
27 },
28 #[error(transparent)]
30 Open(#[from] OpenError),
31 #[error(transparent)]
33 Export(#[from] SnapshotWriteError<ExportStopped>),
34 #[error(transparent)]
36 Database(#[from] DbError),
37 #[error("the rebuild's store: {0}")]
39 Directory(#[from] SettingsError),
40 #[error("the rebuild's folder: {0}")]
42 Folder(#[from] FileError),
43 #[error("{operation}; removing what it left also failed: {cleanup}")]
45 Cleanup {
46 operation: Box<RebuildError>,
48 cleanup: Box<RebuildError>,
50 },
51}
52
53pub struct RebuildDatabase {
57 database: Option<StoreDatabase>,
59 scratch: StoreDir,
61 inputs: OpenInputs,
63 clock: ClockRef,
64 ids: IdSourceRef,
65 parent: StoreDatabase,
69}
70
71impl StoreDatabase {
72 pub async fn open_rebuild(
79 &self,
80 circle: Audience,
81 version: u32,
82 ) -> Result<RebuildDatabase, RebuildError> {
83 let (real, inputs, clock, ids) = self
84 .call(|inner| {
85 Ok::<_, DbError>((
86 inner.access.directory.clone(),
87 inner.open_inputs.clone(),
88 inner.clock.clone(),
89 inner.ids.clone(),
90 ))
91 })
92 .await?;
93 let first = first_past(&inputs, &circle, version)?;
94 self.remove_rebuild().await?;
97 self.begin_counting_rebuild().await?;
98 let scratch = match real.rebuild_directory().await {
99 Ok(scratch) => scratch,
100 Err(operation) => return Err(removed_after(self, operation.into()).await),
101 };
102 let opened =
103 at_version(&inputs, first, &scratch, &clock, &ids).loading_store().open().await;
104 let database = match opened {
105 Ok(database) => database,
106 Err(operation) => return Err(removed_after(self, operation.into()).await),
107 };
108 let counted = self.count_rebuild(&database).await;
109 let mut rebuild = RebuildDatabase {
110 database: Some(database),
111 scratch,
112 inputs,
113 clock,
114 ids,
115 parent: self.clone(),
116 };
117 match counted {
118 Ok(()) => Ok(rebuild),
119 Err(operation) => Err(match rebuild.discard_inner().await {
120 Ok(()) => operation.into(),
121 Err(cleanup) => RebuildError::Cleanup {
122 operation: Box::new(operation.into()),
123 cleanup: Box::new(cleanup),
124 },
125 }),
126 }
127 }
128}
129
130impl RebuildDatabase {
131 pub async fn stage_snapshot(
133 &self,
134 id: coven_format::admin::SnapshotId,
135 prefix: coven_format::sealed_snapshot::SnapshotObjectPrefix,
136 ) -> Result<crate::SnapshotStaging, DbError> {
137 let Some(database) = &self.database else {
138 return Err(DbError::StoreClosed);
139 };
140 database.stage_snapshot(id, prefix).await
141 }
142
143 pub async fn load<P: crate::PendingValue, W>(
152 &self,
153 reload: crate::SnapshotReload<crate::SnapshotStaging, crate::DownloadedWriteStream<W>>,
154 store_through: u64,
155 ) -> Result<Vec<crate::LoadedSnapshot>, DbError>
156 where
157 W: std::io::Read + Send + 'static,
158 {
159 let Some(database) = &self.database else {
160 return Err(DbError::StoreClosed);
161 };
162 let rebuilding = crate::snapshot_coverage::Rebuilding {
163 store_through,
164 breaking: self
165 .inputs
166 .migrations
167 .iter()
168 .filter(|m| matches!(m.kind, MigrationKind::Breaking(_)))
169 .map(|m| m.version)
170 .collect(),
171 };
172 let loaded = database.load_through::<P, W>(reload, None, Some(rebuilding), None).await;
173 loaded
174 }
175
176 pub async fn discard(mut self) -> Result<(), RebuildError> {
180 self.discard_inner().await
181 }
182
183 async fn discard_inner(&mut self) -> Result<(), RebuildError> {
184 let closed = match self.database.take() {
185 Some(database) => database.close().await.map_err(RebuildError::from),
186 None => Ok(()),
187 };
188 let removed = self.parent.remove_rebuild().await;
189 match (closed, removed) {
190 (Ok(()), Ok(())) => Ok(()),
191 (Ok(()), Err(cleanup)) => Err(cleanup.into()),
192 (Err(operation), Ok(())) => Err(operation),
193 (Err(operation), Err(cleanup)) => Err(RebuildError::Cleanup {
194 operation: Box::new(operation),
195 cleanup: Box::new(cleanup.into()),
196 }),
197 }
198 }
199
200 async fn reopened(&mut self, database: StoreDatabase) -> Result<(), RebuildError> {
203 let counted = self.parent.count_rebuild(&database).await;
204 self.database = Some(database);
205 Ok(counted?)
206 }
207}
208
209fn first_past(inputs: &OpenInputs, circle: &Audience, version: u32) -> Result<usize, RebuildError> {
212 inputs
213 .migrations
214 .iter()
215 .position(|m| m.version > version && matches!(m.kind, MigrationKind::Breaking(_)))
216 .ok_or_else(|| RebuildError::NotBelow { circle: circle.clone(), version })
217}
218
219fn at_version(
223 inputs: &OpenInputs,
224 first: usize,
225 scratch: &StoreDir,
226 clock: &ClockRef,
227 ids: &IdSourceRef,
228) -> DatabaseBuilder {
229 DatabaseBuilder::new(scratch.clone())
230 .synced_tables(inputs.migrations[first].starts_from.clone())
231 .migrations(inputs.migrations[..first].to_vec())
232 .namespaces(inputs.namespaces.clone())
233 .sqlite_settings(inputs.sqlite.clone())
234 .sql_functions(inputs.functions.clone())
235 .sync_functions_as_opened(inputs.sync_functions.clone())
236 .clock(clock.clone())
237 .id_source(ids.clone())
238}
239
240async fn removed_after(parent: &StoreDatabase, operation: RebuildError) -> RebuildError {
243 match parent.remove_rebuild().await {
244 Ok(()) => operation,
245 Err(cleanup) => RebuildError::Cleanup {
246 operation: Box::new(operation),
247 cleanup: Box::new(cleanup.into()),
248 },
249 }
250}
251
252#[path = "circle_rebuild_migration.rs"]
253mod migration;
254pub use migration::ExportStopped;
255
256#[cfg(test)]
257#[path = "circle_rebuild_tests.rs"]
258pub(crate) mod tests;