steid

@jamesgill /

steid/src/cli/restore.rs
Rust10.6 KBCode·Blame·History·Raw
1//! `steid restore <archive>`, and `steid restore --replace <archive>`.
2
3use std::{path::Path, time::SystemTime};
4
5use crate::{
6 application::{AppConfig, RestoreMode, restore},
7 infrastructure::{
8 self,
9 backup::{SqliteDatabaseSnapshot, TarGzBackupArchive, database_file},
10 git::DiskGitStorage,
11 repository::SqliteUserRepo,
12 },
13};
14
15use super::BACKUP_WORKSPACE;
16
17/// Restores an archive into an empty instance — or, with
18/// [`RestoreMode::Replace`], over whatever is already in it.
19///
20/// [`RestoreMode::OnlyIfEmpty`] is the default and only ever restores into an instance
21/// with nothing in it. The refusals are the use case's, and they all happen before a
22/// byte is written — see [`restore`](crate::application::restore).
23///
24/// **Stop Steid first.** Neither this nor the use case checks: the data directory is
25/// being moved out from under a process that serves out of it, and nothing portable can
26/// tell whether one is running. The managed console stops the service, restores, and
27/// starts it again; a self-hoster running `--replace` by hand should do the same. The
28/// old state is moved aside rather than deleted, and where it went is printed.
29///
30/// # Errors
31///
32/// Returns the reason as a sentence: the database URL names no file, or the use case
33/// refused — most often because the instance already holds a user and `--replace` was
34/// not given.
35pub async fn run_restore(
36 config: &AppConfig,
37 archive: &Path,
38 mode: RestoreMode,
39) -> Result<(), Box<dyn std::error::Error>> {
40 let database = database_file(&config.database_url)
41 .ok_or("STEID_DATABASE_URL names no file, so there is nothing to restore into")?;
42
43 // `connect`, not `open`: a fresh install has no database file at all, and a restore
44 // has to be able to ask "does this hold a user" before it can answer. Migrating an
45 // empty file costs nothing and the file is replaced wholesale a moment later anyway.
46 let pool = infrastructure::database::connect(&config.database_url).await?;
47
48 let workspace = config.data_dir.join(BACKUP_WORKSPACE);
49 tokio::fs::create_dir_all(&workspace).await?;
50
51 let outcome = restore(
52 SystemTime::now(),
53 archive,
54 &config.data_dir,
55 &workspace,
56 mode,
57 &SqliteUserRepo::new(pool.clone()),
58 &DiskGitStorage::new(config.data_dir.clone()),
59 &SqliteDatabaseSnapshot::new(pool.clone(), database),
60 &TarGzBackupArchive::new(),
61 )
62 .await;
63
64 let _ = tokio::fs::remove_dir_all(&workspace).await;
65
66 let restored = outcome?;
67 let counts = restored.manifest.counts;
68
69 println!(
70 "steid: restored a backup taken at {} by Steid {}",
71 restored.manifest.taken_at, restored.manifest.version
72 );
73 println!(
74 " {} user(s), {} organisation(s), {} repository/repositories into {}",
75 counts.users,
76 counts.organisations,
77 counts.repositories,
78 config.data_dir.display()
79 );
80
81 // Said plainly and last, because it is the part somebody has to act on: the previous
82 // instance is still on the disk, in full, and nothing will ever remove it.
83 if let Some(aside) = &restored.replaced {
84 println!(
85 " what was here was moved to {} — nothing deletes it, and it is as large as",
86 aside.display()
87 );
88 println!(
89 " the instance was. Check the restore, then: rm -rf {}",
90 aside.display()
91 );
92 }
93
94 println!(" Start Steid to use it.");
95
96 Ok(())
97}
98
99#[cfg(test)]
100mod tests {
101 use super::*;
102 use crate::cli::fixture;
103
104 #[tokio::test]
105 async fn an_instance_that_already_has_a_user_is_refused() {
106 let instance = fixture::claimed("ada").await;
107
108 // The archive need not exist: the refusal happens before anything is read, which
109 // is the property worth pinning — a restore that got as far as unpacking would
110 // already have written into somebody's live data directory.
111 let error = run_restore(
112 &instance.config,
113 &instance.dir.path().join("absent.tar.gz"),
114 RestoreMode::OnlyIfEmpty,
115 )
116 .await
117 .expect_err("a claimed instance is not restored into");
118
119 assert!(
120 error.to_string().contains("unclaimed instance"),
121 "{error} does not say why"
122 );
123 }
124
125 #[tokio::test]
126 async fn a_backup_of_a_claimed_instance_restores_into_an_empty_one() {
127 let source = fixture::claimed("ada").await;
128 let archive = source.dir.path().join("one.tar.gz");
129 crate::cli::run_backup(&source.config, &archive)
130 .await
131 .expect("the backup is written");
132
133 let target = fixture::empty().await;
134 // The pool the fixture opened holds the file this is about to replace; SQLite on
135 // macOS is content to overwrite underneath it, but the assertion below has to
136 // read the restored file rather than a cached page.
137 target.pool.close().await;
138
139 run_restore(&target.config, &archive, RestoreMode::OnlyIfEmpty)
140 .await
141 .expect("the restore succeeds");
142
143 let pool = crate::infrastructure::database::connect(&target.config.database_url)
144 .await
145 .expect("the restored database opens");
146 let users = crate::infrastructure::repository::SqliteUserRepo::new(pool);
147
148 assert!(
149 crate::application::is_claimed(&users)
150 .await
151 .expect("the query runs"),
152 "the restored instance has no owner"
153 );
154 }
155
156 /// A bare repository on disk under `handle`, so "the data directory holds
157 /// something" is a real directory rather than a row.
158 async fn init_repo(
159 instance: &fixture::Instance,
160 handle: &str,
161 name: &str,
162 ) -> std::path::PathBuf {
163 use crate::{
164 application::port::GitStorage,
165 domain::{OrgName, RepoName},
166 };
167
168 let storage = DiskGitStorage::new(instance.config.data_dir.clone());
169 let handle = OrgName::new(handle).expect("a valid handle");
170 let name = RepoName::new(name).expect("a valid name");
171
172 storage.init_bare(&handle, &name).await.expect("init bare");
173
174 storage.repo_path(&handle, &name)
175 }
176
177 #[tokio::test]
178 async fn replace_puts_the_archive_in_and_moves_what_was_there_aside() {
179 // The case the whole flag exists for: a managed instance is born owned, so it
180 // always holds a user, and the console's restore could otherwise never succeed.
181 let source = fixture::claimed("ada").await;
182 init_repo(&source, "ada", "one").await;
183 let archive = source.dir.path().join("ada.tar.gz");
184 crate::cli::run_backup(&source.config, &archive)
185 .await
186 .expect("the backup is written");
187
188 let target = fixture::claimed("bob").await;
189 init_repo(&target, "bob", "two").await;
190 target.pool.close().await;
191
192 run_restore(&target.config, &archive, RestoreMode::Replace)
193 .await
194 .expect("--replace restores over a claimed instance");
195
196 let data_dir = &target.config.data_dir;
197 assert!(
198 data_dir.join("ada").join("one.git").is_dir(),
199 "the archive's repository is not in place"
200 );
201 assert!(
202 !data_dir.join("bob").join("two.git").exists(),
203 "the old repository is still where it was"
204 );
205
206 let pool = crate::infrastructure::database::connect(&target.config.database_url)
207 .await
208 .expect("the restored database opens");
209 let users = crate::infrastructure::repository::SqliteUserRepo::new(pool.clone());
210 let found = crate::domain::repository::UserRepository::find_by_email(
211 &users,
212 &crate::domain::Email::new("ada@example.com").expect("valid"),
213 )
214 .await
215 .expect("the query runs");
216 assert!(
217 found.is_some(),
218 "the archive's owner is not in the database"
219 );
220
221 let stale = crate::domain::repository::UserRepository::find_by_email(
222 &users,
223 &crate::domain::Email::new("bob@example.com").expect("valid"),
224 )
225 .await
226 .expect("the query runs");
227 assert!(
228 stale.is_none(),
229 "the replaced instance still holds its old owner"
230 );
231 pool.close().await;
232
233 // Moved, never deleted — and the whole previous instance is there, the database
234 // included, or the aside directory would only be half a way back.
235 let aside: Vec<_> = std::fs::read_dir(data_dir)
236 .expect("readable")
237 .map(|entry| entry.expect("an entry").path())
238 .filter(|path| {
239 path.file_name()
240 .and_then(|name| name.to_str())
241 .is_some_and(|name| name.starts_with(".replaced-"))
242 })
243 .collect();
244
245 assert_eq!(aside.len(), 1, "expected one aside directory in {aside:?}");
246 assert!(
247 aside[0].join("bob").join("two.git").is_dir(),
248 "the old repository was not moved aside"
249 );
250 assert!(
251 std::fs::read_dir(&aside[0])
252 .expect("readable")
253 .any(|entry| entry
254 .expect("an entry")
255 .file_name()
256 .to_string_lossy()
257 .ends_with(".db")),
258 "the old database was not copied aside"
259 );
260 }
261
262 #[tokio::test]
263 async fn without_replace_the_same_restore_is_refused_and_changes_nothing() {
264 let source = fixture::claimed("ada").await;
265 let archive = source.dir.path().join("ada.tar.gz");
266 crate::cli::run_backup(&source.config, &archive)
267 .await
268 .expect("the backup is written");
269
270 let target = fixture::claimed("bob").await;
271 let kept = init_repo(&target, "bob", "two").await;
272
273 let error = run_restore(&target.config, &archive, RestoreMode::OnlyIfEmpty)
274 .await
275 .expect_err("the refusal is the default");
276
277 assert!(
278 error.to_string().contains("--replace"),
279 "{error} does not say what to do"
280 );
281 assert!(kept.is_dir(), "the refusal touched the data directory");
282 }
283
284 #[tokio::test]
285 async fn the_workspace_does_not_survive_the_restore() {
286 let instance = fixture::claimed("ada").await;
287
288 let _ = run_restore(
289 &instance.config,
290 &instance.dir.path().join("absent.tar.gz"),
291 RestoreMode::OnlyIfEmpty,
292 )
293 .await;
294
295 assert!(!instance.config.data_dir.join(BACKUP_WORKSPACE).exists());
296 }
297}