1mod bootstrap;
19pub mod diff;
20mod lock;
21mod log;
22pub mod merge;
23pub mod restore;
24mod revision;
25pub mod tags;
26mod trailers;
27mod transaction;
28
29use std::fmt;
30use std::path::{Path, PathBuf};
31use std::sync::Arc;
32use std::time::{SystemTime, UNIX_EPOCH};
33
34use git2::{Commit, Repository, RepositoryInitOptions, Signature};
35use schemars::JsonSchema;
36use serde::{Deserialize, Serialize};
37use toml::value::{Date, Datetime, Offset, Time};
38
39use crate::brand;
40use crate::env::Env;
41use crate::error::{CoreError, ErrorCode};
42use crate::fs::Fs;
43use crate::model::ids::{self, IdKind};
44use crate::model::server::Server;
45use crate::model::{SCHEMA_VERSION, StoreModel, TomlDocument};
46use crate::paths::SurjectionHome;
47use crate::secrets::scanner::SecretMemory;
48
49pub use bootstrap::{bare_commit_subject, bare_refs, bare_store_id, check_bare, export_store_id};
50pub use lock::{LOCK_FILE, LOCK_TIMEOUT, StoreLock};
51pub use log::{HistoryFinding, LogEntry, LogFilter, entity_paths};
52pub use revision::Revision;
53pub use trailers::{ApplyRef, MachineRef, Scope, Trailers, compose_message, message_summary};
54pub use transaction::{Committed, Operation, Transaction};
55
56pub trait StoreRead {
60 fn read_file(&self, relative: &str) -> Result<Option<String>, CoreError>;
62
63 fn list_files(&self, dir: &str) -> Result<Vec<String>, CoreError>;
66}
67
68impl StoreRead for Store<'_> {
69 fn read_file(&self, relative: &str) -> Result<Option<String>, CoreError> {
70 self.read_to_string(relative)
71 }
72
73 fn list_files(&self, dir: &str) -> Result<Vec<String>, CoreError> {
74 let path = self.path(dir)?;
75 if !self.fs.is_dir(&path) {
76 return Ok(Vec::new());
77 }
78 let entries = self
79 .fs
80 .read_dir(&path)
81 .map_err(|err| io_error("cannot list directory", &path, &err))?;
82 let mut names: Vec<String> = entries
83 .iter()
84 .filter(|entry| !self.fs.is_dir(entry))
85 .filter_map(|entry| entry.file_name()?.to_str().map(str::to_owned))
86 .collect();
87 names.sort();
88 Ok(names)
89 }
90}
91
92pub const BRANCH: &str = "main";
94pub const IDENTITY_FILE: &str = "loadout.toml";
96pub const MACHINE_FILE: &str = "machine.toml";
98const GITATTRIBUTES: (&str, &str) = (".gitattributes", "* -text\n");
101
102#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
104#[schemars(title = "Surjection store identity (store/loadout.toml)")]
105pub struct StoreIdentity {
106 pub schema: i64,
108 pub store_id: String,
110 #[schemars(with = "String")]
111 pub created_at: Datetime,
112 #[serde(flatten)]
113 #[schemars(skip)]
114 pub extra: toml::Table,
115}
116
117impl StoreModel for StoreIdentity {
118 const SCHEMA_NAME: &'static str = "store-identity";
119}
120
121#[derive(Debug, Clone, PartialEq, Eq)]
124pub struct Machine {
125 pub id: String,
127 pub label: String,
129}
130
131#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
132#[schemars(title = "Surjection machine identity (state/machine.toml)")]
133struct MachineFile {
134 schema: i64,
135 machine_id: String,
136 label: String,
137 #[serde(flatten)]
138 #[schemars(skip)]
139 extra: toml::Table,
140}
141
142impl StoreModel for MachineFile {
143 const SCHEMA_NAME: &'static str = "machine-identity";
144}
145
146const DEFAULT_LABEL: &str = "machine";
148
149impl Machine {
150 pub fn load(fs: &dyn Fs, state_dir: &Path) -> Result<Option<Self>, CoreError> {
152 let path = state_dir.join(MACHINE_FILE);
153 if !fs.exists(&path) {
154 return Ok(None);
155 }
156 let file = TomlDocument::<MachineFile>::load(fs, &path)?.into_value();
157 ids::check(IdKind::Machine, &file.machine_id).map_err(|err| err.with_path(&path))?;
158 Ok(Some(Self {
159 id: file.machine_id,
160 label: clean_label(&file.label),
161 }))
162 }
163
164 pub fn load_or_create(env: &Env, fs: &dyn Fs, state_dir: &Path) -> Result<Self, CoreError> {
167 if let Some(machine) = Self::load(fs, state_dir)? {
168 return Ok(machine);
169 }
170 let machine = Self {
171 id: ids::new_ulid(env.now())?,
172 label: clean_label(env.hostname().unwrap_or(DEFAULT_LABEL)),
173 };
174 let path = state_dir.join(MACHINE_FILE);
175 fs.create_dir_all(state_dir)
176 .map_err(|err| io_error("cannot create directory", state_dir, &err))?;
177 TomlDocument::new(MachineFile {
178 schema: SCHEMA_VERSION,
179 machine_id: machine.id.clone(),
180 label: machine.label.clone(),
181 extra: toml::Table::new(),
182 })
183 .save(fs, &path)?;
184 Ok(machine)
185 }
186
187 fn signature(&self, time: SystemTime) -> Result<Signature<'static>, CoreError> {
189 let seconds = time
190 .duration_since(UNIX_EPOCH)
191 .map_or(0, |elapsed| elapsed.as_secs());
192 Signature::new(
193 &format!("{} {}", brand::COMMIT_AUTHOR_NAME, self.label),
194 &format!("{}@{}", self.id, brand::COMMIT_EMAIL_DOMAIN),
195 &git2::Time::new(i64::try_from(seconds).unwrap_or(i64::MAX), 0),
196 )
197 .map_err(git_error)
198 }
199}
200
201fn clean_label(raw: &str) -> String {
204 let cleaned = raw
205 .chars()
206 .map(|c| if c.is_control() { ' ' } else { c })
207 .filter(|c| !matches!(c, '<' | '>'))
208 .collect::<String>()
209 .split_whitespace()
210 .collect::<Vec<_>>()
211 .join(" ");
212 if cleaned.is_empty() {
213 DEFAULT_LABEL.to_owned()
214 } else {
215 cleaned
216 }
217}
218
219#[derive(Debug, Clone, PartialEq, Eq, Hash)]
221pub struct CommitId(String);
222
223impl CommitId {
224 fn from_oid(oid: git2::Oid) -> Self {
225 Self(oid.to_string())
226 }
227
228 pub fn from_text(text: &str) -> Result<Self, CoreError> {
230 git2::Oid::from_str(text)
231 .ok()
232 .filter(|_| text.len() == 40)
233 .map(Self::from_oid)
234 .ok_or_else(|| {
235 CoreError::new(
236 ErrorCode::InvalidValue,
237 format!("{text:?} is not a commit id"),
238 )
239 })
240 }
241
242 pub fn as_str(&self) -> &str {
243 &self.0
244 }
245
246 pub fn short(&self) -> &str {
248 &self.0[..self.0.len().min(7)]
249 }
250}
251
252impl fmt::Display for CommitId {
253 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
254 f.write_str(&self.0)
255 }
256}
257
258#[derive(Debug)]
261pub struct ServerEntry {
262 pub id: String,
264 pub document: Result<TomlDocument<Server>, CoreError>,
265}
266
267pub struct Store<'a> {
269 env: Env,
270 fs: &'a dyn Fs,
271 root: PathBuf,
272 state_dir: PathBuf,
273 repo: Repository,
274 identity: StoreIdentity,
275 client: String,
276 secrets: Arc<SecretMemory>,
278}
279
280impl fmt::Debug for Store<'_> {
281 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
282 f.debug_struct("Store")
283 .field("root", &self.root)
284 .field("store_id", &self.identity.store_id)
285 .field("client", &self.client)
286 .finish_non_exhaustive()
287 }
288}
289
290impl<'a> Store<'a> {
291 fn from_parts(
293 env: &Env,
294 fs: &'a dyn Fs,
295 home: &SurjectionHome,
296 client: &str,
297 repo: Repository,
298 identity: StoreIdentity,
299 ) -> Result<Self, CoreError> {
300 Ok(Self {
301 env: env.clone(),
302 fs,
303 root: home.store_dir(),
304 state_dir: home.state_dir(),
305 repo,
306 identity,
307 client: client.to_owned(),
308 secrets: Arc::new(SecretMemory::new()?),
309 })
310 }
311
312 pub fn open(
316 env: &Env,
317 fs: &'a dyn Fs,
318 home: &SurjectionHome,
319 client: &str,
320 ) -> Result<Option<Self>, CoreError> {
321 let root = home.store_dir();
322 if !fs.exists(&root.join(".git")) {
323 return Ok(None);
324 }
325 let repo = Repository::open(&root).map_err(git_error)?;
326 if repo.head().is_err() {
327 return Ok(None);
329 }
330 let path = root.join(IDENTITY_FILE);
331 let identity = TomlDocument::<StoreIdentity>::load(fs, &path)?.into_value();
332 ids::check(IdKind::Store, &identity.store_id).map_err(|err| err.with_path(&path))?;
333 Ok(Some(Self {
334 env: env.clone(),
335 fs,
336 root,
337 state_dir: home.state_dir(),
338 repo,
339 identity,
340 client: client.to_owned(),
341 secrets: Arc::new(SecretMemory::new()?),
342 }))
343 }
344
345 pub(crate) fn open_raw(
350 env: &Env,
351 fs: &'a dyn Fs,
352 home: &SurjectionHome,
353 client: &str,
354 ) -> Result<Option<Self>, CoreError> {
355 let root = home.store_dir();
356 if !fs.exists(&root.join(".git")) {
357 return Ok(None);
358 }
359 let repo = Repository::open(&root).map_err(git_error)?;
360 if repo.head().is_err() {
361 return Ok(None);
362 }
363 let path = root.join(IDENTITY_FILE);
364 let text = fs
365 .read_to_string(&path)
366 .map_err(|err| io_error("cannot read file", &path, &err))?;
367 let table: toml::Table =
368 text.trim_start_matches('\u{feff}')
369 .parse()
370 .map_err(|err: toml::de::Error| {
371 CoreError::new(ErrorCode::ParseError, err.message().to_owned()).with_path(&path)
372 })?;
373 let identity = StoreIdentity {
374 schema: table
375 .get("schema")
376 .and_then(toml::Value::as_integer)
377 .unwrap_or(SCHEMA_VERSION),
378 store_id: table
379 .get("store_id")
380 .and_then(toml::Value::as_str)
381 .unwrap_or_default()
382 .to_owned(),
383 created_at: table
384 .get("created_at")
385 .and_then(toml::Value::as_datetime)
386 .copied()
387 .unwrap_or_else(|| utc_datetime(env.now())),
388 extra: toml::Table::new(),
389 };
390 Self::from_parts(env, fs, home, client, repo, identity).map(Some)
391 }
392
393 pub fn open_or_init(
397 env: &Env,
398 fs: &'a dyn Fs,
399 home: &SurjectionHome,
400 client: &str,
401 ) -> Result<Self, CoreError> {
402 if let Some(store) = Self::open(env, fs, home, client)? {
403 return Ok(store);
404 }
405 let state_dir = home.state_dir();
406 let _lock = StoreLock::acquire(fs, &state_dir, LOCK_TIMEOUT)?;
407 if let Some(store) = Self::open(env, fs, home, client)? {
409 return Ok(store);
410 }
411 let machine = Machine::load_or_create(env, fs, &state_dir)?;
412 let root = home.store_dir();
413 fs.create_dir_all(&root)
415 .map_err(|err| io_error("cannot create directory", &root, &err))?;
416 let repo = if fs.exists(&root.join(".git")) {
417 Repository::open(&root)
418 } else {
419 let mut options = RepositoryInitOptions::new();
420 options
421 .bare(false)
422 .no_reinit(true)
423 .mkdir(true)
424 .external_template(false)
425 .initial_head(BRANCH);
426 Repository::init_opts(&root, &options)
427 }
428 .map_err(git_error)?;
429
430 let identity_path = root.join(IDENTITY_FILE);
432 let identity = TomlDocument::<StoreIdentity>::load(fs, &identity_path)
433 .ok()
434 .map(TomlDocument::into_value)
435 .filter(|identity| ids::is_valid(IdKind::Store, &identity.store_id));
436 let identity = match identity {
437 Some(identity) => identity,
438 None => StoreIdentity {
439 schema: SCHEMA_VERSION,
440 store_id: ids::new_ulid(env.now())?,
441 created_at: utc_datetime(env.now()),
442 extra: toml::Table::new(),
443 },
444 };
445 let identity_text = TomlDocument::new(identity.clone()).to_text()?;
446 let store = Self {
447 env: env.clone(),
448 fs,
449 root,
450 state_dir,
451 repo,
452 identity,
453 client: client.to_owned(),
454 secrets: Arc::new(SecretMemory::new()?),
455 };
456 let operation = Operation::new(
457 "store.init",
458 format!("init: store {}", store.identity.store_id),
459 );
460 let changes = [
461 (IDENTITY_FILE.to_owned(), Some(identity_text.into_bytes())),
462 (GITATTRIBUTES.0.to_owned(), Some(GITATTRIBUTES.1.into())),
463 ]
464 .into_iter()
465 .collect();
466 store.commit_changes(&machine, &operation, changes)?;
467 Ok(store)
468 }
469
470 pub fn root(&self) -> &Path {
472 &self.root
473 }
474
475 pub fn fs(&self) -> &'a dyn Fs {
477 self.fs
478 }
479
480 pub fn state_dir(&self) -> &Path {
482 &self.state_dir
483 }
484
485 pub fn contains(&self, id: &CommitId) -> bool {
487 let (Ok(head), Ok(oid)) = (self.head(), git2::Oid::from_str(id.as_str())) else {
488 return false;
489 };
490 let Ok(head) = git2::Oid::from_str(head.as_str()) else {
491 return false;
492 };
493 head == oid || self.repo.graph_descendant_of(head, oid).unwrap_or(false)
494 }
495
496 pub fn reference_target(&self, name: &str) -> Result<Option<CommitId>, CoreError> {
499 match self.repo.find_reference(name) {
500 Ok(reference) => {
501 let commit = reference.peel_to_commit().map_err(git_error)?;
502 Ok(Some(CommitId::from_oid(commit.id())))
503 }
504 Err(err) if err.code() == git2::ErrorCode::NotFound => Ok(None),
505 Err(err) => Err(git_error(err)),
506 }
507 }
508
509 pub fn env(&self) -> &Env {
511 &self.env
512 }
513
514 pub fn secret_memory(&self) -> &Arc<SecretMemory> {
518 &self.secrets
519 }
520
521 pub fn identity(&self) -> &StoreIdentity {
522 &self.identity
523 }
524
525 pub fn store_id(&self) -> &str {
526 &self.identity.store_id
527 }
528
529 pub fn head(&self) -> Result<CommitId, CoreError> {
531 Ok(CommitId::from_oid(self.head_commit()?.id()))
532 }
533
534 pub fn path(&self, relative: &str) -> Result<PathBuf, CoreError> {
536 check_relative(relative)?;
537 Ok(relative
538 .split('/')
539 .fold(self.root.clone(), |path, part| path.join(part)))
540 }
541
542 pub fn read_to_string(&self, relative: &str) -> Result<Option<String>, CoreError> {
544 let path = self.path(relative)?;
545 if !self.fs.exists(&path) {
546 return Ok(None);
547 }
548 self.fs
549 .read_to_string(&path)
550 .map(Some)
551 .map_err(|err| io_error("cannot read file", &path, &err))
552 }
553
554 pub fn server(&self, id: &str) -> Result<Option<TomlDocument<Server>>, CoreError> {
556 let path = self.path(&server_path(id)?)?;
557 if !self.fs.exists(&path) {
558 return Ok(None);
559 }
560 TomlDocument::load(self.fs, &path).map(Some)
561 }
562
563 pub fn servers(&self) -> Result<Vec<ServerEntry>, CoreError> {
565 let dir = self.root.join("servers");
566 if !self.fs.is_dir(&dir) {
567 return Ok(Vec::new());
568 }
569 let paths = self
570 .fs
571 .read_dir(&dir)
572 .map_err(|err| io_error("cannot list directory", &dir, &err))?;
573 let entries = paths
574 .into_iter()
575 .filter_map(|path| {
576 let id = path
577 .file_name()?
578 .to_str()?
579 .strip_suffix(".toml")?
580 .to_owned();
581 Some((id, path))
582 })
583 .map(|(id, path)| {
584 let document =
585 TomlDocument::<Server>::load(self.fs, &path).and_then(|doc| {
586 match doc.value().validate(Some(&id)).first_error(Some(&path)) {
587 Some(err) => Err(err),
588 None => Ok(doc),
589 }
590 });
591 ServerEntry { id, document }
592 })
593 .collect();
594 Ok(entries)
595 }
596
597 fn head_commit(&self) -> Result<Commit<'_>, CoreError> {
598 self.repo
599 .head()
600 .and_then(|head| head.peel_to_commit())
601 .map_err(git_error)
602 }
603}
604
605pub fn server_path(id: &str) -> Result<String, CoreError> {
607 ids::check(IdKind::Server, id)?;
608 Ok(format!("servers/{id}.toml"))
609}
610
611fn check_relative(relative: &str) -> Result<(), CoreError> {
614 let valid = !relative.is_empty()
615 && relative.split('/').all(|part| {
616 !part.is_empty() && part != "." && part != ".." && !part.contains(['\\', ':'])
617 })
618 && !relative
619 .split('/')
620 .next()
621 .is_some_and(|first| first.eq_ignore_ascii_case(".git"));
622 if valid {
623 Ok(())
624 } else {
625 Err(CoreError::new(
626 ErrorCode::InvalidPath,
627 format!("{relative:?} is not a store-relative path"),
628 ))
629 }
630}
631
632pub fn utc_datetime(time: SystemTime) -> Datetime {
634 let seconds = time
635 .duration_since(UNIX_EPOCH)
636 .map_or(0, |elapsed| elapsed.as_secs());
637 let seconds = i64::try_from(seconds).unwrap_or(i64::MAX);
638 let (year, month, day) = civil_from_days(seconds.div_euclid(86_400));
639 let of_day = seconds.rem_euclid(86_400);
640 Datetime {
641 date: Some(Date {
642 year: u16::try_from(year).unwrap_or(u16::MAX),
643 month,
644 day,
645 }),
646 time: Some(Time {
647 hour: (of_day / 3600) as u8,
648 minute: (of_day % 3600 / 60) as u8,
649 second: Some((of_day % 60) as u8),
650 nanosecond: None,
651 }),
652 offset: Some(Offset::Z),
653 }
654}
655
656fn civil_from_days(days: i64) -> (i64, u8, u8) {
659 let z = days + 719_468;
660 let era = z.div_euclid(146_097);
661 let doe = z.rem_euclid(146_097);
662 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
663 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
664 let mp = (5 * doy + 2) / 153;
665 let day = (doy - (153 * mp + 2) / 5 + 1) as u8;
666 let month = if mp < 10 { mp + 3 } else { mp - 9 } as u8;
667 let year = yoe + era * 400 + i64::from(month <= 2);
668 (year, month, day)
669}
670
671fn git_error(err: git2::Error) -> CoreError {
672 CoreError::new(ErrorCode::GitError, err.message().to_owned())
673}
674
675fn io_error(what: &str, path: &Path, err: &std::io::Error) -> CoreError {
676 CoreError::new(ErrorCode::IoError, format!("{what}: {err}")).with_path(path)
677}