newgit-core 0.1.0

Core domain model for newgit: branch instances, tracker lanes, and resource lifecycles
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
use std::collections::{BTreeMap, BTreeSet};

use camino::{Utf8Path, Utf8PathBuf};
use serde::Deserialize;
use sha2::{Digest, Sha256};

use crate::error::{NewgitError, Result};

/// A lifecycle unit that re-establishes per-branch state that can't travel
/// as content. Parsed from `.newgit/resources/<name>.toml`; the name comes
/// from the filename.
#[derive(Debug, Clone, PartialEq)]
pub struct ResourceDefinition {
    pub name: String,
    pub kind: String,
    pub ownership: Ownership,
    pub depends_on: Vec<String>,
    pub identity: Option<IdentitySpec>,
    pub ports: BTreeMap<String, PortRequest>,
    pub exports: BTreeMap<String, String>,
    pub actions: BTreeMap<String, ActionSpec>,
    pub checkpoint: Option<CheckpointSpec>,
    pub restore: Option<RestoreSpec>,
    pub cleanup: Option<CleanupSpec>,
    /// `sha256:<hex12>` of the definition file contents.
    pub definition_rev: String,
}

/// Who owns the concrete instance and what cleanup may touch. Operational,
/// not a security label.
#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum Ownership {
    Branch,
    Workspace,
    Project,
    User,
    External,
}

impl Ownership {
    /// Whether tearing down one branch instance may touch the concrete
    /// resource. `project` is shared by the project's instances and `user`
    /// is shared beyond it, so per-branch teardown must leave both alone —
    /// this is the conservative half of the ownership table, and the reason
    /// a pnpm store survives `newgit remove`.
    pub fn per_branch_teardown_may_touch(self) -> bool {
        match self {
            Self::Branch | Self::Workspace | Self::External => true,
            Self::Project | Self::User => false,
        }
    }

    pub fn label(self) -> &'static str {
        match self {
            Self::Branch => "branch",
            Self::Workspace => "workspace",
            Self::Project => "project",
            Self::User => "user",
            Self::External => "external",
        }
    }
}

#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct IdentitySpec {
    pub paths: Vec<Utf8PathBuf>,
}

#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct PortRequest {
    pub start: u16,
    #[serde(default)]
    pub env: Option<String>,
}

#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct ActionSpec {
    #[serde(default)]
    pub command: Option<String>,
    #[serde(default)]
    pub long_running: bool,
    /// Signal sent by `stop` for a long-running sibling `start`.
    #[serde(default)]
    pub signal: Option<String>,
    /// Names to read out of the command's stdout and merge into this
    /// resource's binding exports — how a resource that mints an external
    /// handle (a preview id, a tunnel URL) publishes it. See
    /// [`parse_captures`] for the accepted output shapes.
    #[serde(default)]
    pub captures: Vec<String>,
}

/// How a resource tears its concrete instance down. Ownership decides
/// whether the hook may run at all; this decides what running it means.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct CleanupSpec {
    /// May use `{{state_ref}}` (from the instance's latest checkpoint) and
    /// `{{exports.<name>}}` (from the binding).
    pub command: Option<String>,
}

/// How a resource captures branch-local state at checkpoint time.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct CheckpointSpec {
    pub mode: CheckpointMode,
    /// `hash`: identity files whose content hash is the captured state.
    #[serde(default)]
    pub paths: Vec<Utf8PathBuf>,
    /// `command`: emits the state; trimmed stdout becomes the state ref.
    #[serde(default)]
    pub command: Option<String>,
    /// `command`: deposit `{{snapshot.path}}` into this tracker's lane.
    #[serde(default)]
    pub into_tracker: Option<String>,
    /// `external`: template for the opaque ref (may use `{{exports.<name>}}`).
    #[serde(default)]
    pub state_ref: Option<String>,
}

#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub enum CheckpointMode {
    None,
    Hash,
    Command,
    External,
}

/// How a resource re-establishes checkpointed state during undo.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct RestoreSpec {
    pub mode: RestoreMode,
    /// `command`: may use `{{state_ref}}`.
    #[serde(default)]
    pub command: Option<String>,
    /// `recompute`: the action to re-run (default `prepare`).
    #[serde(default)]
    pub action: Option<String>,
}

#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub enum RestoreMode {
    None,
    Command,
    Recompute,
    External,
}

impl RestoreSpec {
    /// The action a `recompute` restore re-runs.
    pub fn recompute_action(&self) -> &str {
        self.action.as_deref().unwrap_or("prepare")
    }
}

#[derive(Debug, Deserialize)]
struct ResourceDefinitionFile {
    kind: String,
    ownership: Ownership,
    #[serde(default)]
    depends_on: Vec<String>,
    #[serde(default)]
    identity: Option<IdentitySpec>,
    #[serde(default)]
    ports: BTreeMap<String, PortRequest>,
    #[serde(default)]
    exports: BTreeMap<String, String>,
    #[serde(default)]
    actions: BTreeMap<String, ActionSpec>,
    #[serde(default)]
    checkpoint: Option<CheckpointSpec>,
    #[serde(default)]
    restore: Option<RestoreSpec>,
    #[serde(default)]
    cleanup: Option<CleanupSpec>,
}

impl ResourceDefinition {
    pub fn from_file(name: &str, path: &Utf8Path) -> Result<Self> {
        let contents =
            std::fs::read_to_string(path).map_err(|source| NewgitError::io(path, source))?;
        let file: ResourceDefinitionFile =
            toml::from_str(&contents).map_err(|source| NewgitError::TomlRead {
                path: path.to_path_buf(),
                source,
            })?;

        let digest = Sha256::digest(contents.as_bytes());
        let hex: String = digest[..6]
            .iter()
            .map(|byte| format!("{byte:02x}"))
            .collect();

        let definition = Self {
            name: name.to_owned(),
            kind: file.kind,
            ownership: file.ownership,
            depends_on: file.depends_on,
            identity: file.identity,
            ports: file.ports,
            exports: file.exports,
            actions: file.actions,
            checkpoint: file.checkpoint,
            restore: file.restore,
            cleanup: file.cleanup,
            definition_rev: format!("sha256:{hex}"),
        };
        definition.validate()?;
        Ok(definition)
    }

    /// The action `stop` signals, resolved: explicit `signal`, default TERM.
    pub fn stop_signal(&self) -> String {
        self.actions
            .get("stop")
            .and_then(|action| action.signal.clone())
            .unwrap_or_else(|| "term".to_owned())
    }

    pub fn has_long_running_action(&self) -> bool {
        self.actions.values().any(|action| action.long_running)
    }

    fn validate(&self) -> Result<()> {
        if let Some(checkpoint) = &self.checkpoint {
            match checkpoint.mode {
                CheckpointMode::None => {}
                CheckpointMode::Hash => {
                    if checkpoint.paths.is_empty() {
                        return Err(
                            self.invalid("checkpoint mode `hash` requires `paths`".to_owned())
                        );
                    }
                }
                CheckpointMode::Command => {
                    if checkpoint.command.is_none() {
                        return Err(
                            self.invalid("checkpoint mode `command` requires `command`".to_owned())
                        );
                    }
                }
                CheckpointMode::External => {
                    if checkpoint.state_ref.is_none() {
                        return Err(self.invalid(
                            "checkpoint mode `external` requires `state_ref`".to_owned(),
                        ));
                    }
                }
            }
        }
        if let Some(restore) = &self.restore {
            match restore.mode {
                RestoreMode::Command if restore.command.is_none() => {
                    return Err(
                        self.invalid("restore mode `command` requires `command`".to_owned())
                    );
                }
                RestoreMode::Recompute
                    if !self.actions.contains_key(restore.recompute_action()) =>
                {
                    return Err(self.invalid(format!(
                        "restore mode `recompute` re-runs action `{}`, which is not defined",
                        restore.recompute_action()
                    )));
                }
                _ => {}
            }
        }
        for (action_name, action) in &self.actions {
            let is_signal_only = action.command.is_none() && action.signal.is_some();
            if action.command.is_none() && !is_signal_only {
                return Err(self.invalid(format!(
                    "action `{action_name}` has neither a command nor a signal"
                )));
            }
            if action.long_running && action.command.is_none() {
                return Err(self.invalid(format!(
                    "action `{action_name}` is long_running but has no command"
                )));
            }
        }
        Ok(())
    }

    fn invalid(&self, reason: String) -> NewgitError {
        NewgitError::InvalidDefinition {
            tracker: self.name.clone(),
            reason,
        }
    }
}

/// Read an action's declared `captures` out of its stdout.
///
/// Two shapes are accepted, because both are what a real command already
/// emits: stdout whose first non-whitespace character is `{` is parsed as a
/// flat JSON object (`cloudctl ... --json`), and anything else is read as
/// `KEY=VALUE` lines (`echo PREVIEW_ID=pv_9`). Only declared names are
/// taken, JSON scalars are stringified, and a name the command did not emit
/// is simply absent rather than an error — a resource may legitimately
/// publish a handle only on some runs.
pub fn parse_captures(stdout: &str, wanted: &[String]) -> BTreeMap<String, String> {
    if wanted.is_empty() {
        return BTreeMap::new();
    }
    let trimmed = stdout.trim_start();

    let mut found: BTreeMap<String, String> = BTreeMap::new();
    if trimmed.starts_with('{') {
        if let Ok(serde_json::Value::Object(object)) =
            serde_json::from_str::<serde_json::Value>(trimmed)
        {
            for (key, value) in object {
                if let Some(text) = json_scalar(&value) {
                    found.insert(key, text);
                }
            }
        }
    } else {
        for line in stdout.lines() {
            if let Some((key, value)) = line.split_once('=') {
                found.insert(key.trim().to_owned(), value.trim().to_owned());
            }
        }
    }

    wanted
        .iter()
        .filter_map(|name| found.remove_entry(name))
        .collect()
}

/// JSON scalars render as themselves; containers have no obvious env-var
/// spelling, so they are skipped rather than guessed at.
fn json_scalar(value: &serde_json::Value) -> Option<String> {
    match value {
        serde_json::Value::String(text) => Some(text.clone()),
        serde_json::Value::Number(number) => Some(number.to_string()),
        serde_json::Value::Bool(flag) => Some(flag.to_string()),
        _ => None,
    }
}

/// Order resources so dependencies come before dependents. Dependencies may
/// name trackers (which only need to exist) or other resources.
pub fn topological_order(
    resources: &[ResourceDefinition],
    tracker_names: &BTreeSet<String>,
) -> Result<Vec<String>> {
    let mut ordered = Vec::new();
    let mut state: BTreeMap<&str, Visit> = BTreeMap::new();

    fn visit<'a>(
        name: &'a str,
        resources: &'a [ResourceDefinition],
        tracker_names: &BTreeSet<String>,
        state: &mut BTreeMap<&'a str, Visit>,
        ordered: &mut Vec<String>,
        stack: &mut Vec<String>,
    ) -> Result<()> {
        match state.get(name) {
            Some(Visit::Done) => return Ok(()),
            Some(Visit::InProgress) => {
                stack.push(name.to_owned());
                return Err(NewgitError::DependencyCycle(stack.clone()));
            }
            None => {}
        }
        let Some(resource) = resources.iter().find(|r| r.name == name) else {
            // Caller verified membership; only reachable for dependencies.
            return Ok(());
        };
        state.insert(&resource.name, Visit::InProgress);
        stack.push(name.to_owned());
        for dependency in &resource.depends_on {
            if tracker_names.contains(dependency) {
                continue;
            }
            if !resources.iter().any(|r| &r.name == dependency) {
                return Err(NewgitError::MissingDependency {
                    resource: resource.name.clone(),
                    dependency: dependency.clone(),
                });
            }
            visit(dependency, resources, tracker_names, state, ordered, stack)?;
        }
        stack.pop();
        state.insert(&resource.name, Visit::Done);
        ordered.push(resource.name.clone());
        Ok(())
    }

    #[derive(Clone, Copy)]
    enum Visit {
        InProgress,
        Done,
    }

    for resource in resources {
        visit(
            &resource.name,
            resources,
            tracker_names,
            &mut state,
            &mut ordered,
            &mut Vec::new(),
        )?;
    }
    Ok(ordered)
}

#[cfg(test)]
mod tests {
    use std::collections::{BTreeMap, BTreeSet};

    use super::*;

    fn resource(name: &str, deps: &[&str]) -> ResourceDefinition {
        ResourceDefinition {
            name: name.to_owned(),
            kind: "command".to_owned(),
            ownership: Ownership::Branch,
            depends_on: deps.iter().map(ToString::to_string).collect(),
            identity: None,
            ports: BTreeMap::new(),
            exports: BTreeMap::new(),
            actions: BTreeMap::new(),
            checkpoint: None,
            restore: None,
            cleanup: None,
            definition_rev: "sha256:000000000000".to_owned(),
        }
    }

    #[test]
    fn captures_read_json_objects_and_key_value_lines() {
        let wanted = ["PREVIEW_ID".to_owned(), "PREVIEW_URL".to_owned()];

        let json = parse_captures(
            r#"{"PREVIEW_ID": "pv_9", "PREVIEW_URL": "https://pv9.example", "extra": 1}"#,
            &wanted,
        );
        assert_eq!(json["PREVIEW_ID"], "pv_9");
        assert_eq!(json["PREVIEW_URL"], "https://pv9.example");
        assert_eq!(json.len(), 2, "undeclared keys are not captured");

        let lines = parse_captures("noise\nPREVIEW_ID=pv_9\n", &wanted);
        assert_eq!(lines["PREVIEW_ID"], "pv_9");
        assert!(
            !lines.contains_key("PREVIEW_URL"),
            "a name the command did not emit is absent, not empty"
        );

        // Non-string scalars stringify; unparseable output captures nothing.
        assert_eq!(
            parse_captures(r#"{"PORT": 5432}"#, &["PORT".to_owned()])["PORT"],
            "5432"
        );
        assert!(parse_captures("{not json", &wanted).is_empty());
        assert!(parse_captures("PREVIEW_ID=pv_9", &[]).is_empty());
    }

    #[test]
    fn orders_dependencies_first_and_detects_cycles() {
        let trackers = BTreeSet::from(["runtime-env".to_owned()]);
        let resources = vec![
            resource("app", &["deps", "runtime-env"]),
            resource("deps", &[]),
        ];
        let order = topological_order(&resources, &trackers).expect("order");
        assert_eq!(order, vec!["deps".to_owned(), "app".to_owned()]);

        let cyclic = vec![resource("a", &["b"]), resource("b", &["a"])];
        assert!(matches!(
            topological_order(&cyclic, &trackers),
            Err(NewgitError::DependencyCycle(_))
        ));

        let missing = vec![resource("app", &["nope"])];
        assert!(matches!(
            topological_order(&missing, &trackers),
            Err(NewgitError::MissingDependency { .. })
        ));
    }
}