Skip to main content

ai6_safehouse_git/
lib.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! `ai6-safehouse-git`: the `git` safe-house provider. Each Mission gets a worktree of the
6//! Operation's checkout on a new branch; the work is read back as commits. A spec with
7//! `clone_to` gets a clone of a repository instead, saved to a branch it shares. The Git logic
8//! is plain Rust in `worktree.rs` and `clone.rs`; this file is the thin layer that implements
9//! the kind.
10
11#![doc = include_str!("../README.md")]
12
13ai6::guatiao::providers!(Git);
14
15mod clone;
16mod worktree;
17
18use ai6::directorates::q::safehouse::{
19    ChangeLog, CheckpointSpec, SafeHouseInfo, SafeHouseProvider, SafeHouseRun, SafeHouseSpec,
20};
21use ai6::guatiao::library::{Object, ProviderError};
22use ai6::guatiao::{FromValue, Schema, Status, ToValue, Value};
23
24use worktree::{Runner, Worktree};
25
26/// `git` provider configuration; every field has a default. The fields in the `operation`
27/// section are an Operation's to set (`workspace.settings`); the Station's placement reads them
28/// to build each Mission's [`SafeHouseSpec`] and its checkpoints. The others are the Station's.
29#[derive(ToValue, FromValue, Schema, Debug, Clone, PartialEq, Eq)]
30#[map(crate = ::ai6::guatiao)]
31pub struct GitConfig {
32    /// The revision each Mission starts from.
33    #[schema(title = "Start from revision", section = "operation")]
34    #[map(default = "HEAD".to_owned())]
35    pub base: String,
36    /// The name each Mission's branch gets; {id}, {slug} and {operation} are filled in.
37    #[schema(title = "Branch name", section = "operation")]
38    #[map(default = "{id}-{slug}".to_owned())]
39    pub branch: String,
40    /// Give each Mission its own copy. Off, Missions work in the source itself.
41    #[schema(title = "A copy for each Mission", section = "operation")]
42    #[map(default = true)]
43    pub isolate: bool,
44    /// The git remote, by name or address, each Mission's work is saved to, so a later run
45    /// on another Station carries on from it. Empty pushes nothing.
46    #[schema(title = "Save work to remote", section = "operation")]
47    pub checkpoint_remote: Option<String>,
48    /// Seconds between saves of a running Mission's work.
49    #[schema(title = "Save every", format = "seconds", section = "operation")]
50    #[map(default = 300)]
51    pub checkpoint_secs: u64,
52    /// Milliseconds one Git command may run before it is killed. Default 120000.
53    #[map(default = 120_000)]
54    pub git_timeout_ms: u64,
55    /// Milliseconds between measurements of the directories a size-bounded command (a clone)
56    /// fills. Default 250.
57    #[map(default = 250)]
58    pub measure_every_ms: u64,
59    /// Refuse to push work that shares no history with the branch it is based on or saved to,
60    /// which is what a Mission started before a history reset would push back. Set `false` to
61    /// push such work anyway. Default true.
62    #[map(default = true)]
63    pub require_shared_root: bool,
64}
65
66impl Default for GitConfig {
67    fn default() -> Self {
68        Self {
69            base: "HEAD".to_owned(),
70            branch: "{id}-{slug}".to_owned(),
71            isolate: true,
72            checkpoint_remote: None,
73            checkpoint_secs: 300,
74            git_timeout_ms: 120_000,
75            measure_every_ms: 250,
76            require_shared_root: true,
77        }
78    }
79}
80
81/// Makes a Mission's workspace with Git: a worktree, or a clone.
82#[derive(Debug, Clone, Default, ai6::guatiao::Provider)]
83#[provider(
84    SafeHouseProvider,
85    id = "git",
86    name = "git",
87    crate = ::ai6::guatiao,
88    config = GitConfig
89)]
90pub struct Git {
91    config: GitConfig,
92}
93
94impl Git {
95    /// A provider with `config`.
96    pub fn new(config: GitConfig) -> Self {
97        Self { config }
98    }
99}
100
101impl TryFrom<GitConfig> for Git {
102    type Error = ProviderError;
103
104    fn try_from(config: GitConfig) -> Result<Self, Self::Error> {
105        Ok(Self::new(config))
106    }
107}
108
109impl SafeHouseProvider for Git {
110    fn open(&self, spec: &Value) -> Result<Object<dyn SafeHouseRun>, ProviderError> {
111        let spec = SafeHouseSpec::from_value(spec)
112            .map_err(|error| refuse(Status::GUATIAO_ERR_BAD_VALUE, error))?;
113        let worktree = Worktree::open(
114            &spec,
115            Runner {
116                timeout: std::time::Duration::from_millis(self.config.git_timeout_ms),
117                measure_every: std::time::Duration::from_millis(self.config.measure_every_ms),
118                require_shared_root: self.config.require_shared_root,
119            },
120        )
121        .map_err(|error| refuse(Status::GUATIAO_ERR_INTERNAL, error))?;
122        Ok(GitSafeHouse(worktree).into_object())
123    }
124}
125
126struct GitSafeHouse(Worktree);
127
128impl SafeHouseRun for GitSafeHouse {
129    fn info(&self) -> Result<Value, ProviderError> {
130        value(&SafeHouseInfo {
131            path: self.0.path.to_string_lossy().into_owned(),
132            branch: self.0.branch.clone(),
133            base: Some(self.0.base.clone()),
134            supports_history: true,
135            isolated: self.0.isolated,
136        })
137    }
138
139    fn changes(&self) -> Result<Value, ProviderError> {
140        let changes = self
141            .0
142            .changes()
143            .map_err(|error| refuse(Status::GUATIAO_ERR_INTERNAL, error))?;
144        value(&ChangeLog { changes })
145    }
146
147    fn finish(&self) -> Result<Value, ProviderError> {
148        let report = self
149            .0
150            .finish()
151            .map_err(|error| refuse(Status::GUATIAO_ERR_INTERNAL, error))?;
152        value(&report)
153    }
154
155    fn checkpoint(&self, spec: &Value) -> Result<Value, ProviderError> {
156        let spec = CheckpointSpec::from_value(spec)
157            .map_err(|error| refuse(Status::GUATIAO_ERR_BAD_VALUE, error))?;
158        let saved = self
159            .0
160            .checkpoint(&spec)
161            .map_err(|error| refuse(Status::GUATIAO_ERR_INTERNAL, error))?;
162        value(&saved)
163    }
164
165    fn diff(&self, bytes: u64) -> Result<Value, ProviderError> {
166        let diff = self
167            .0
168            .diff(usize::try_from(bytes).unwrap_or(usize::MAX))
169            .map_err(|error| refuse(Status::GUATIAO_ERR_INTERNAL, error))?;
170        value(&diff)
171    }
172
173    fn exports(&self) -> Result<Value, ProviderError> {
174        let exports = self
175            .0
176            .exports()
177            .map_err(|error| refuse(Status::GUATIAO_ERR_INTERNAL, error))?;
178        value(&exports)
179    }
180
181    fn discard(&self) -> Result<(), ProviderError> {
182        self.0
183            .discard()
184            .map_err(|error| refuse(Status::GUATIAO_ERR_INTERNAL, error))
185    }
186}
187
188fn value(model: &impl ToValue) -> Result<Value, ProviderError> {
189    model
190        .to_value()
191        .map_err(|error| refuse(Status::GUATIAO_ERR_INTERNAL, error))
192}
193
194fn refuse(status: Status, error: impl std::fmt::Display) -> ProviderError {
195    ProviderError::new(status, &error.to_string())
196}