Skip to main content

ossctl_core/
ports.rs

1//! Injected effect ports — the seam that keeps every domain testable in
2//! isolation without touching the real filesystem, git, network, or clock
3//! (ADR-0001 §2).
4//!
5//! Domain code (`contract`, `facts`, `audit`, `release`) takes these traits by
6//! reference instead of calling `std::process`, `std::time`, or the network
7//! directly. Production supplies real implementations in `ossctl-cli`; tests
8//! supply deterministic fakes. At founding these are the **trait shapes** only;
9//! concrete implementations land with their consuming units.
10
11use std::io;
12
13/// Output of a subprocess run through a [`CommandRunner`].
14#[derive(Debug, Clone)]
15pub struct CommandOutput {
16    /// Process exit status code (`None` if terminated by a signal).
17    pub status: Option<i32>,
18    /// Captured standard output.
19    pub stdout: String,
20    /// Captured standard error.
21    pub stderr: String,
22}
23
24/// Runs external commands (git, package-manager, registry CLIs) on behalf of a
25/// domain, capturing their output. The single seam for shelling out — nothing
26/// in `ossctl-core` calls `std::process::Command` directly.
27pub trait CommandRunner {
28    /// Run `program` with `args` in `cwd`, capturing stdout/stderr.
29    fn run(&self, program: &str, args: &[&str], cwd: &std::path::Path)
30        -> io::Result<CommandOutput>;
31}
32
33/// Supplies the current time. Injected so time-dependent logic (journal
34/// timestamps, run ages) is deterministic under test.
35pub trait Clock {
36    /// Current time as whole seconds since the Unix epoch.
37    fn now_unix(&self) -> u64;
38}
39
40/// Generates opaque, unique, non-deterministic identifiers — run ids and the
41/// like. Injected so id-dependent output is deterministic under test.
42///
43/// Note: this is **not** the source of `plan_id`. A release plan id is
44/// *content-addressed* — derived deterministically from the sealed plan's
45/// canonical bytes (ADR-0002), not generated here. Do not route plan sealing
46/// through this port.
47pub trait IdGen {
48    /// Produce a fresh, unique identifier.
49    fn new_id(&self) -> String;
50}
51
52/// Read/write access to the filesystem — the `Fs` half of the `Fs/Git` seam
53/// (ADR-0001 §2). Domain code (contract loading, journal persistence, sealed
54/// plans) goes through this port rather than calling `std::fs` directly, so it
55/// is testable against an in-memory fake. At founding this is a deliberately
56/// small surface; it grows (atomic writes, dir listing, metadata) as the
57/// journal and plan-sealing units land.
58pub trait Fs {
59    /// Read a file's full contents as bytes.
60    fn read(&self, path: &std::path::Path) -> io::Result<Vec<u8>>;
61    /// Whether `path` exists.
62    fn exists(&self, path: &std::path::Path) -> bool;
63    /// Whether `path` exists and is a directory (used for the contract's
64    /// fragment-dir producer check, which is a *directory*, not a file).
65    fn is_dir(&self, path: &std::path::Path) -> bool;
66    /// Whether `path` exists and is a *regular file* — not a directory, FIFO,
67    /// socket, or device (mirrors `os.path.isfile`). The facts detector gates
68    /// every manifest/config read on this so a non-regular node named
69    /// `Cargo.toml` neither marks an ecosystem nor blocks [`Self::read`] (a
70    /// blocking `read` on a FIFO is a real hang the `exists && !is_dir`
71    /// approximation would not prevent).
72    fn is_file(&self, path: &std::path::Path) -> bool;
73    /// List the immediate entry *names* (not full paths) within `dir` — the
74    /// facts detector's CI probe needs to know whether `.github/workflows`
75    /// holds at least one entry, not merely that the directory exists.
76    /// `Ok(vec![])` for an empty directory; `Err` when `dir` is absent or
77    /// unreadable (the detector treats that as "no entries").
78    fn read_dir(&self, dir: &std::path::Path) -> io::Result<Vec<String>>;
79}
80
81/// Queries a package registry for already-published state — the "remote is
82/// ground truth" source the release reconciler consults (ADR-0003).
83pub trait RegistryQuery {
84    /// Versions of `package` already published to `ecosystem`'s registry.
85    fn published_versions(&self, ecosystem: &str, package: &str) -> io::Result<Vec<String>>;
86}
87
88/// Read-only view of the git repository under audit/release. The detector and
89/// release engine read repo facts through this port rather than shelling out
90/// to `git` themselves.
91///
92/// The detector's queries are deliberately *best-effort*: an unborn or
93/// non-repository root makes several of these fail, and the detector treats
94/// every such failure as "absent" (no committers, no tags) rather than an
95/// error — mirroring the read-only, never-mutating `infer-repo-facts.py`.
96pub trait GitRepo {
97    /// The full commit hash of `HEAD`. `Err` on an unborn repository (no
98    /// commits yet) or a non-repository root — the detector reads this as
99    /// "the repo has no commits".
100    fn head_commit(&self) -> io::Result<String>;
101    /// Whether the root is inside a git work tree (`git rev-parse
102    /// --is-inside-work-tree` succeeds). `false` for a non-repository root or
103    /// on any git error.
104    fn is_work_tree(&self) -> bool;
105    /// Raw `git shortlog -sne --all HEAD` output — one line per distinct
106    /// committer. When `since` is set (a git date expression such as
107    /// `"1 year ago"`), the log is limited to commits at or after it. `Err` on
108    /// any git failure (an unborn/empty repo); the detector counts that as zero
109    /// committers.
110    fn shortlog(&self, since: Option<&str>) -> io::Result<String>;
111    /// The repository's tag names (`git tag --list`), trimmed and with empty
112    /// lines dropped. `Err` on any git failure; the detector reads that as "no
113    /// tags".
114    fn tags(&self) -> io::Result<Vec<String>>;
115    /// The **common** git directory (`git rev-parse --git-common-dir`), resolved
116    /// to an absolute path. The release journal roots its state under here so all
117    /// linked worktrees of one repo share a single release-state root, and
118    /// submodules / bare repos / `GIT_DIR` overrides resolve correctly — a
119    /// literal `.git/` concatenation is *not* a portable substitute (ADR-0003
120    /// §3, the panel's repeated correctness landmine). `Err` on any git failure.
121    fn git_common_dir(&self) -> io::Result<std::path::PathBuf>;
122}
123
124/// Durable, atomic, lockable storage for the release journal — the seam that
125/// keeps the event-sourced journal (ADR-0003) testable without touching the real
126/// filesystem, while pinning down the atomicity discipline its production impl
127/// **must** honor.
128///
129/// The append-then-apply contract (ADR-0003 §2, borrowed from `octl-core`) maps
130/// onto these operations:
131///
132/// 1. [`Self::append_line`] fsyncs the event so it is durable **before** the
133///    reducer applies it — a crash between append and apply replays as a clean
134///    no-op-or-apply, because the journal (read back by [`Self::read_lines`]) is
135///    the single source of truth.
136/// 2. [`Self::write_atomic`] persists the derived manifest via temp-file → flush
137///    → atomic rename → directory fsync, so a torn write can never leave a
138///    half-written manifest (it is disposable and rebuildable regardless).
139/// 3. [`Self::lock_exclusive`] enforces a single active cut per repo (a `flock`
140///    on the releases-dir `.lock`): a concurrent cut/resume fails fast rather
141///    than corrupting a run.
142///
143/// The port is deliberately path-driven (the journal computes paths via
144/// [`crate::release::journal::JournalPaths`]); the impl adds no policy, only the
145/// durability guarantees documented per method.
146pub trait JournalStore {
147    /// Take the single-active-cut exclusive lock at `lock_path` (creating parent
148    /// directories as needed). The returned guard holds the lock until dropped.
149    /// `Err` with [`io::ErrorKind::WouldBlock`] when another holder is active, so
150    /// the caller can fail fast and name the active run.
151    fn lock_exclusive(&self, lock_path: &std::path::Path) -> io::Result<Box<dyn JournalLock>>;
152    /// Append `line` (one serialized event, no embedded newline — the store adds
153    /// the single trailing `\n`) to the JSONL file at `path`, creating the file
154    /// and parent directories if absent, and **fsync** so it is durable before
155    /// returning. This is the append half of append-then-apply.
156    ///
157    /// The write must be **atomic at line granularity**: on return the line is
158    /// either fully present or not present, never truncated. The production impl
159    /// opens with `O_APPEND`, `write_all`s the line + newline, and fsyncs the file
160    /// **and** — when it created the file or a parent directory — the containing
161    /// directory, so a newly created `RunCreated` survives power loss (fsyncing
162    /// only the file leaves the new directory entry non-durable). A torn *final*
163    /// line from a hard kill mid-write is still possible in theory; recovering it
164    /// (truncate-to-last-good under the lock) is a documented follow-up, not part
165    /// of this port yet — [`crate::release::journal::read_events`] currently
166    /// rejects any malformed line.
167    fn append_line(&self, path: &std::path::Path, line: &str) -> io::Result<()>;
168    /// Read every line of the JSONL file at `path`. `Ok(vec![])` when the file is
169    /// absent (a not-yet-written journal is empty, not an error).
170    fn read_lines(&self, path: &std::path::Path) -> io::Result<Vec<String>>;
171    /// Read the full contents of the (atomically-written) file at `path`, or
172    /// `Ok(None)` when it is absent. Used for the torn-free fast-path read of the
173    /// `manifest.json` cache; unlike [`Self::read_lines`] it returns raw bytes.
174    fn read(&self, path: &std::path::Path) -> io::Result<Option<Vec<u8>>>;
175    /// Atomically replace the file at `path` with `bytes`: write a temp file in
176    /// the same directory, flush + fsync it, rename it over `path`, then fsync the
177    /// directory. Creates parent directories as needed.
178    fn write_atomic(&self, path: &std::path::Path, bytes: &[u8]) -> io::Result<()>;
179    /// The immediate entry *names* (not full paths) within `dir`, or `Ok(vec![])`
180    /// when `dir` is absent — used to enumerate run-id subdirectories for
181    /// `release list`.
182    fn list_dir(&self, dir: &std::path::Path) -> io::Result<Vec<String>>;
183}
184
185/// An opaque RAII guard for the single-active-cut lock taken by
186/// [`JournalStore::lock_exclusive`]. Dropping it releases the lock; there are no
187/// methods — its lifetime *is* the contract.
188pub trait JournalLock {}
189
190/// Creates and publishes the **one** shared release tag + GitHub Release for a
191/// cut — the external side of the coordinator's coordinator-only tag phase
192/// (ADR-0002 §2).
193///
194/// Tagging is deliberately **not** on the [`crate::release::adapters::ReleaseAdapter`]
195/// trait: no per-ecosystem adapter can create the shared tag, which is what makes
196/// "tag once, after every publish succeeds" a structural guarantee. The
197/// coordinator drives these three steps in order and journals each as its own
198/// resumable event (`tag_created_local` → `tag_pushed_remote` →
199/// `github_release_created`), so an interrupted tag phase resumes from the first
200/// incomplete step rather than re-tagging.
201///
202/// Every method is **idempotent-friendly**: the coordinator only calls a step
203/// whose journalled fact is not yet present, but a production impl should still
204/// treat "already exists" as success (a pushed tag that is already on the remote,
205/// a Release that already exists) rather than an error, so a resume after a crash
206/// *between* the external action and its journal write reconciles cleanly.
207pub trait Tagger {
208    /// Create the annotated tag `tag` (message `message`) pointing at the sealed
209    /// `commit` in the local repository.
210    ///
211    /// `commit` is the plan's sealed `HEAD` (not whatever `HEAD` happens to be at
212    /// tag time), so the tag authenticates the approved commit even if `HEAD`
213    /// moved during the cut. Idempotent-friendly: if the tag already exists **at
214    /// `commit`** this is success (a resumed cut re-reaching this step after a
215    /// crash between the tag and its journal write); a tag that exists pointing
216    /// **elsewhere** is a genuine conflict (`Err`), never silently overwritten.
217    fn create_tag(&self, tag: &str, commit: &str, message: &str) -> io::Result<()>;
218    /// Push the already-created tag `tag` to the remote. Idempotent-friendly: an
219    /// already-present identical remote tag is success; `Err` on a real push
220    /// failure (network, auth, a conflicting remote ref).
221    fn push_tag(&self, tag: &str) -> io::Result<()>;
222    /// Create the GitHub Release for `tag` (titled `title`), returning its URL
223    /// when the host reports one. Idempotent-friendly: an already-existing Release
224    /// is success (returning its URL); `Err` on a real creation failure.
225    fn create_github_release(&self, tag: &str, title: &str) -> io::Result<Option<String>>;
226}