1#![expect(missing_docs)]
16
17use std::any::Any;
18use std::fmt::Debug;
19use std::pin::Pin;
20use std::slice;
21use std::time::SystemTime;
22
23use async_trait::async_trait;
24use chrono::TimeZone as _;
25use futures::stream::BoxStream;
26use thiserror::Error;
27use tokio::io::AsyncRead;
28
29use crate::content_hash::ContentHash;
30use crate::hex_util;
31use crate::index::Index;
32use crate::merge::Merge;
33use crate::object_id::ObjectId as _;
34use crate::object_id::id_type;
35use crate::repo_path::RepoPath;
36use crate::repo_path::RepoPathBuf;
37use crate::repo_path::RepoPathComponent;
38use crate::repo_path::RepoPathComponentBuf;
39use crate::signing::SignResult;
40
41id_type!(
42 pub CommitId { hex() }
45);
46id_type!(
47 pub ChangeId { reverse_hex() }
50);
51id_type!(pub TreeId { hex() });
52id_type!(pub FileId { hex() });
53id_type!(pub SymlinkId { hex() });
54id_type!(pub CopyId { hex() });
55
56impl ChangeId {
57 pub fn try_from_reverse_hex(hex: impl AsRef<[u8]>) -> Option<Self> {
59 hex_util::decode_reverse_hex(hex).map(Self)
60 }
61
62 pub fn reverse_hex(&self) -> String {
65 hex_util::encode_reverse_hex(&self.0)
66 }
67}
68
69impl CopyId {
70 pub fn placeholder() -> Self {
74 Self::new(vec![])
75 }
76}
77
78#[derive(Debug, Error)]
79#[error("Out-of-range date")]
80pub struct TimestampOutOfRange;
81
82#[derive(ContentHash, Debug, PartialEq, Eq, Clone, Copy, PartialOrd, Ord)]
83pub struct MillisSinceEpoch(pub i64);
84
85#[derive(ContentHash, Debug, PartialEq, Eq, Clone, Copy, PartialOrd, Ord)]
86pub struct Timestamp {
87 pub timestamp: MillisSinceEpoch,
88 pub tz_offset: i32,
90}
91
92impl Timestamp {
93 pub fn now() -> Self {
94 Self::from_datetime(chrono::offset::Local::now())
95 }
96
97 pub fn from_datetime<Tz: chrono::TimeZone<Offset = chrono::offset::FixedOffset>>(
98 datetime: chrono::DateTime<Tz>,
99 ) -> Self {
100 Self {
101 timestamp: MillisSinceEpoch(datetime.timestamp_millis()),
102 tz_offset: datetime.offset().local_minus_utc() / 60,
103 }
104 }
105
106 pub fn to_datetime(
107 &self,
108 ) -> Result<chrono::DateTime<chrono::FixedOffset>, TimestampOutOfRange> {
109 let utc = match chrono::Utc.timestamp_opt(
110 self.timestamp.0.div_euclid(1000),
111 (self.timestamp.0.rem_euclid(1000)) as u32 * 1000000,
112 ) {
113 chrono::LocalResult::None => {
114 return Err(TimestampOutOfRange);
115 }
116 chrono::LocalResult::Single(x) => x,
117 chrono::LocalResult::Ambiguous(y, _z) => y,
118 };
119
120 Ok(utc.with_timezone(
121 &chrono::FixedOffset::east_opt(self.tz_offset * 60)
122 .unwrap_or_else(|| chrono::FixedOffset::east_opt(0).unwrap()),
123 ))
124 }
125}
126
127impl serde::Serialize for Timestamp {
128 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
129 where
130 S: serde::Serializer,
131 {
132 let t = self.to_datetime().map_err(serde::ser::Error::custom)?;
134 t.serialize(serializer)
135 }
136}
137
138#[derive(ContentHash, Debug, PartialEq, Eq, Clone, serde::Serialize)]
140pub struct Signature {
141 pub name: String,
142 pub email: String,
143 pub timestamp: Timestamp,
144}
145
146#[derive(ContentHash, Debug, PartialEq, Eq, Clone)]
148pub struct SecureSig {
149 pub data: Vec<u8>,
150 pub sig: Vec<u8>,
151}
152
153pub type SigningFn<'a> = dyn FnMut(&[u8]) -> SignResult<Vec<u8>> + Send + 'a;
154
155#[derive(ContentHash, Debug, PartialEq, Eq, Clone)]
159pub struct MergedTreeId {
160 tree_ids: Merge<TreeId>,
162}
163
164impl MergedTreeId {
165 pub fn resolved(tree_id: TreeId) -> Self {
167 Self::new(Merge::resolved(tree_id))
168 }
169
170 pub fn new(tree_ids: Merge<TreeId>) -> Self {
172 Self { tree_ids }
173 }
174
175 pub fn as_merge(&self) -> &Merge<TreeId> {
177 &self.tree_ids
178 }
179
180 pub fn into_merge(self) -> Merge<TreeId> {
182 self.tree_ids
183 }
184}
185
186#[derive(ContentHash, Debug, PartialEq, Eq, Clone, serde::Serialize)]
187pub struct Commit {
188 pub parents: Vec<CommitId>,
189 #[serde(skip)] pub predecessors: Vec<CommitId>,
193 #[serde(skip)] pub root_tree: MergedTreeId,
195 pub change_id: ChangeId,
196 pub description: String,
197 pub author: Signature,
198 pub committer: Signature,
199 #[serde(skip)] pub secure_sig: Option<SecureSig>,
201}
202
203#[derive(Debug, PartialEq, Eq, Clone)]
205pub struct CopyRecord {
206 pub target: RepoPathBuf,
208 pub target_commit: CommitId,
210 pub source: RepoPathBuf,
216 pub source_file: FileId,
217 pub source_commit: CommitId,
228}
229
230#[derive(ContentHash, Debug, PartialEq, Eq, Clone, PartialOrd, Ord)]
233pub struct CopyHistory {
234 pub current_path: RepoPathBuf,
236 pub parents: Vec<CopyId>,
241 pub salt: Vec<u8>,
246}
247
248#[derive(Debug, Error)]
250#[error(transparent)]
251pub struct BackendInitError(pub Box<dyn std::error::Error + Send + Sync>);
252
253#[derive(Debug, Error)]
255#[error(transparent)]
256pub struct BackendLoadError(pub Box<dyn std::error::Error + Send + Sync>);
257
258#[derive(Debug, Error)]
260pub enum BackendError {
261 #[error(
262 "Invalid hash length for object of type {object_type} (expected {expected} bytes, got \
263 {actual} bytes): {hash}"
264 )]
265 InvalidHashLength {
266 expected: usize,
267 actual: usize,
268 object_type: String,
269 hash: String,
270 },
271 #[error("Invalid UTF-8 for object {hash} of type {object_type}")]
272 InvalidUtf8 {
273 object_type: String,
274 hash: String,
275 source: std::str::Utf8Error,
276 },
277 #[error("Object {hash} of type {object_type} not found")]
278 ObjectNotFound {
279 object_type: String,
280 hash: String,
281 source: Box<dyn std::error::Error + Send + Sync>,
282 },
283 #[error("Error when reading object {hash} of type {object_type}")]
284 ReadObject {
285 object_type: String,
286 hash: String,
287 source: Box<dyn std::error::Error + Send + Sync>,
288 },
289 #[error("Access denied to read object {hash} of type {object_type}")]
290 ReadAccessDenied {
291 object_type: String,
292 hash: String,
293 source: Box<dyn std::error::Error + Send + Sync>,
294 },
295 #[error(
296 "Error when reading file content for file {path} with id {id}",
297 path = path.as_internal_file_string()
298 )]
299 ReadFile {
300 path: RepoPathBuf,
301 id: FileId,
302 source: Box<dyn std::error::Error + Send + Sync>,
303 },
304 #[error("Could not write object of type {object_type}")]
305 WriteObject {
306 object_type: &'static str,
307 source: Box<dyn std::error::Error + Send + Sync>,
308 },
309 #[error(transparent)]
310 Other(Box<dyn std::error::Error + Send + Sync>),
311 #[error("{0}")]
314 Unsupported(String),
315}
316
317pub type BackendResult<T> = Result<T, BackendError>;
318
319#[derive(ContentHash, Debug, PartialEq, Eq, Clone, Hash)]
320pub enum TreeValue {
321 File {
324 id: FileId,
325 executable: bool,
326 copy_id: CopyId,
327 },
328 Symlink(SymlinkId),
329 Tree(TreeId),
330 GitSubmodule(CommitId),
331}
332
333impl TreeValue {
334 pub fn hex(&self) -> String {
335 match self {
336 Self::File { id, .. } => id.hex(),
337 Self::Symlink(id) => id.hex(),
338 Self::Tree(id) => id.hex(),
339 Self::GitSubmodule(id) => id.hex(),
340 }
341 }
342}
343
344#[derive(Debug, PartialEq, Eq, Clone)]
345pub struct TreeEntry<'a> {
346 name: &'a RepoPathComponent,
347 value: &'a TreeValue,
348}
349
350impl<'a> TreeEntry<'a> {
351 pub fn new(name: &'a RepoPathComponent, value: &'a TreeValue) -> Self {
352 Self { name, value }
353 }
354
355 pub fn name(&self) -> &'a RepoPathComponent {
356 self.name
357 }
358
359 pub fn value(&self) -> &'a TreeValue {
360 self.value
361 }
362}
363
364pub struct TreeEntriesNonRecursiveIterator<'a> {
365 iter: slice::Iter<'a, (RepoPathComponentBuf, TreeValue)>,
366}
367
368impl<'a> Iterator for TreeEntriesNonRecursiveIterator<'a> {
369 type Item = TreeEntry<'a>;
370
371 fn next(&mut self) -> Option<Self::Item> {
372 self.iter
373 .next()
374 .map(|(name, value)| TreeEntry { name, value })
375 }
376}
377
378#[derive(ContentHash, Default, PartialEq, Eq, Debug, Clone)]
379pub struct Tree {
380 entries: Vec<(RepoPathComponentBuf, TreeValue)>,
381}
382
383impl Tree {
384 pub fn from_sorted_entries(entries: Vec<(RepoPathComponentBuf, TreeValue)>) -> Self {
385 debug_assert!(entries.is_sorted_by(|(a, _), (b, _)| a < b));
386 Self { entries }
387 }
388
389 pub fn is_empty(&self) -> bool {
390 self.entries.is_empty()
391 }
392
393 pub fn names(&self) -> impl Iterator<Item = &RepoPathComponent> {
394 self.entries.iter().map(|(name, _)| name.as_ref())
395 }
396
397 pub fn entries(&self) -> TreeEntriesNonRecursiveIterator<'_> {
398 TreeEntriesNonRecursiveIterator {
399 iter: self.entries.iter(),
400 }
401 }
402
403 pub fn entry(&self, name: &RepoPathComponent) -> Option<TreeEntry<'_>> {
404 let index = self
405 .entries
406 .binary_search_by_key(&name, |(name, _)| name)
407 .ok()?;
408 let (name, value) = &self.entries[index];
409 Some(TreeEntry { name, value })
410 }
411
412 pub fn value(&self, name: &RepoPathComponent) -> Option<&TreeValue> {
413 self.entry(name).map(|entry| entry.value)
414 }
415}
416
417pub fn make_root_commit(root_change_id: ChangeId, empty_tree_id: TreeId) -> Commit {
418 let timestamp = Timestamp {
419 timestamp: MillisSinceEpoch(0),
420 tz_offset: 0,
421 };
422 let signature = Signature {
423 name: String::new(),
424 email: String::new(),
425 timestamp,
426 };
427 Commit {
428 parents: vec![],
429 predecessors: vec![],
430 root_tree: MergedTreeId::resolved(empty_tree_id),
431 change_id: root_change_id,
432 description: String::new(),
433 author: signature.clone(),
434 committer: signature,
435 secure_sig: None,
436 }
437}
438
439#[async_trait]
441pub trait Backend: Any + Send + Sync + Debug {
442 fn name(&self) -> &str;
445
446 fn commit_id_length(&self) -> usize;
448
449 fn change_id_length(&self) -> usize;
451
452 fn root_commit_id(&self) -> &CommitId;
453
454 fn root_change_id(&self) -> &ChangeId;
455
456 fn empty_tree_id(&self) -> &TreeId;
457
458 fn concurrency(&self) -> usize;
466
467 async fn read_file(
468 &self,
469 path: &RepoPath,
470 id: &FileId,
471 ) -> BackendResult<Pin<Box<dyn AsyncRead + Send>>>;
472
473 async fn write_file(
474 &self,
475 path: &RepoPath,
476 contents: &mut (dyn AsyncRead + Send + Unpin),
477 ) -> BackendResult<FileId>;
478
479 async fn read_symlink(&self, path: &RepoPath, id: &SymlinkId) -> BackendResult<String>;
480
481 async fn write_symlink(&self, path: &RepoPath, target: &str) -> BackendResult<SymlinkId>;
482
483 async fn read_copy(&self, id: &CopyId) -> BackendResult<CopyHistory>;
488
489 async fn write_copy(&self, copy: &CopyHistory) -> BackendResult<CopyId>;
494
495 async fn get_related_copies(&self, copy_id: &CopyId) -> BackendResult<Vec<CopyHistory>>;
505
506 async fn read_tree(&self, path: &RepoPath, id: &TreeId) -> BackendResult<Tree>;
507
508 async fn write_tree(&self, path: &RepoPath, contents: &Tree) -> BackendResult<TreeId>;
509
510 async fn read_commit(&self, id: &CommitId) -> BackendResult<Commit>;
511
512 async fn write_commit(
526 &self,
527 contents: Commit,
528 sign_with: Option<&mut SigningFn>,
529 ) -> BackendResult<(CommitId, Commit)>;
530
531 fn get_copy_records(
544 &self,
545 paths: Option<&[RepoPathBuf]>,
546 root: &CommitId,
547 head: &CommitId,
548 ) -> BackendResult<BoxStream<'_, BackendResult<CopyRecord>>>;
549
550 fn gc(&self, index: &dyn Index, keep_newer: SystemTime) -> BackendResult<()>;
556}
557
558impl dyn Backend {
559 pub fn downcast_ref<T: Backend>(&self) -> Option<&T> {
561 (self as &dyn Any).downcast_ref()
562 }
563}