Skip to main content

anodizer_core/
publisher.rs

1//! Publisher trait + preflight result type.
2//!
3//! Defines the polymorphic interface that every publisher (cargo, homebrew,
4//! scoop, chocolatey, nix, AUR, krew, winget, snapcraft, blob, release, ...)
5//! implements. Lives in `anodizer-core` rather than `stage-publish` so that
6//! `stage-blob`, `stage-release`, and `stage-snapcraft` can implement
7//! `Publisher` without taking a circular dependency on `stage-publish`.
8
9use crate::context::Context;
10use crate::{PublishEvidence, PublisherGroup};
11
12/// Outcome of a publisher's pre-flight self-check.
13///
14/// Each variant signals a different release-pipeline reaction:
15///
16/// * `Pass` — no concern detected; publishing may proceed.
17/// * `Warning(msg)` — surface the message to the operator (and review log)
18///   but do not block the publish. Use for soft signals like "remote
19///   already has a tag at this version but contents match".
20/// * `Blocker(msg)` — abort before the publish stage runs. Use for hard
21///   prerequisites the publisher knows it cannot satisfy at runtime, e.g.
22///   "homebrew tap repo not reachable", "winget-pkgs fork not configured".
23///
24/// Named `Pass` (not `Clean`) to avoid nominal collision with
25/// [`crate::preflight::PublisherState::Clean`], which describes the
26/// already-published state of a publisher rather than a self-check result.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub enum PreflightCheck {
29    /// Publisher's pre-flight checks completed with no concerns.
30    Pass,
31    /// Publisher detected a non-blocking concern; surface it but continue.
32    Warning(String),
33    /// Publisher detected a blocking concern; abort before the publish stage.
34    Blocker(String),
35}
36
37impl PreflightCheck {
38    /// Fold two pre-flight outcomes into the most severe, escalating
39    /// `Blocker` > `Warning` > `Pass`. Within a severity the first-seen
40    /// message (`self`'s) wins, so a left-fold over many targets yields a
41    /// stable, deterministic line rather than whichever target iterated last.
42    pub fn merge(self, next: Self) -> Self {
43        use PreflightCheck::{Blocker, Pass, Warning};
44        match (self, next) {
45            (Blocker(m), _) => Blocker(m),
46            (_, Blocker(m)) => Blocker(m),
47            (Warning(m), _) => Warning(m),
48            (_, Warning(m)) => Warning(m),
49            (Pass, Pass) => Pass,
50        }
51    }
52}
53
54/// Publisher contract — one implementer per upstream registry / channel.
55///
56/// Required methods describe the publisher's identity, behavior, and how
57/// it participates in [`PublisherGroup`]-based scheduling:
58///
59/// * [`Publisher::name`] — stable identifier used in logs, evidence, and
60///   review findings (e.g. `"cargo"`, `"homebrew"`, `"winget"`).
61/// * [`Publisher::run`] — perform the actual publish and emit a
62///   [`PublishEvidence`] record describing what was sent upstream.
63/// * [`Publisher::group`] — which [`PublisherGroup`] this publisher belongs
64///   to; used by the publish stage to order and parallelize work.
65/// * [`Publisher::required`] — whether a failure in this publisher should
66///   fail the overall release.
67///
68/// Default-implemented hooks describe optional behavior:
69///
70/// * [`Publisher::rollback`] — best-effort undo of a successful publish.
71///   The default is a no-op so publishers that target irreversible
72///   registries (most of them) do not need to override.
73/// * [`Publisher::preflight`] — fast self-check executed before any
74///   publisher in the pipeline runs. Defaults to [`PreflightCheck::Pass`].
75/// * [`Publisher::rollback_scope_needed`] — declare an opt-in OAuth /
76///   token scope that rollback would require (e.g. `"delete_repo"` for
77///   GitHub-fork-based publishers). Defaults to `None`. Surfaced by
78///   the CLI when explaining why a rollback path is unavailable.
79///
80/// Implementations must be `Send + Sync` so the publish stage can fan out
81/// across publisher groups in parallel. Wrap non-`Send` clients (Rc-based,
82/// thread-local channels) behind an `Arc<Mutex<_>>` or move them inside
83/// `run()`'s scope rather than holding them on `self`.
84pub trait Publisher: Send + Sync {
85    /// Stable, lowercase identifier for this publisher (e.g. `"cargo"`).
86    fn name(&self) -> &str;
87
88    /// Execute the publish and emit evidence describing what was sent.
89    fn run(&self, ctx: &mut Context) -> anyhow::Result<PublishEvidence>;
90
91    /// Scheduling group — controls ordering and parallelism in the publish stage.
92    fn group(&self) -> PublisherGroup;
93
94    /// Whether a failure here should fail the overall release.
95    fn required(&self) -> bool;
96
97    /// Best-effort rollback of a successful publish, given its evidence.
98    ///
99    /// Default is a no-op: most upstream registries are append-only or
100    /// require human moderation to revoke, so the publisher opts in by
101    /// overriding only when it actually has a rollback path.
102    fn rollback(&self, _ctx: &mut Context, _evidence: &PublishEvidence) -> anyhow::Result<()> {
103        Ok(())
104    }
105
106    /// Fast self-check executed before any publisher runs.
107    ///
108    /// Default returns [`PreflightCheck::Pass`]. Override to surface
109    /// publisher-specific blockers (missing tap, missing fork, network
110    /// unreachable) or warnings (duplicate-but-matching upload).
111    fn preflight(&self, _ctx: &Context) -> anyhow::Result<PreflightCheck> {
112        Ok(PreflightCheck::Pass)
113    }
114
115    /// Opt-in OAuth / token scope rollback would require, if any.
116    ///
117    /// Default is `None`. Used by the CLI to explain why a `--rollback`
118    /// invocation cannot recover a given publisher without elevating the
119    /// release token's permissions.
120    fn rollback_scope_needed(&self) -> Option<&'static str> {
121        None
122    }
123
124    /// Environment requirements this publisher derives from the resolved
125    /// config: CLI tools it spawns, env vars/secrets it reads, endpoints
126    /// it talks to, key material it loads.
127    ///
128    /// Consumed by the config-aware preflight (`anodizer preflight` and the
129    /// in-process phase at the head of `anodizer release`). Declared next
130    /// to each publisher's implementation — derived from the same config
131    /// fields `run()` reads — so the preflight cannot drift from the
132    /// publish path. Default is empty for publishers with no external
133    /// prerequisites beyond what their stage already declares.
134    fn requirements(&self, _ctx: &Context) -> Vec<crate::env_preflight::EnvRequirement> {
135        Vec::new()
136    }
137
138    /// Whether this publisher opts out of nightly runs (the
139    /// `customization/publish/nightlies.md` skip-list).
140    ///
141    /// Each `Publisher` must declare its nightly behavior explicitly — there
142    /// is no default — so adding a new publisher forces a deliberate decision.
143    /// Return `true` for publishers that push to long-lived registries where a
144    /// nightly clobber is either disruptive (homebrew taps, scoop buckets,
145    /// AUR, krew-index, nix overlays) or outright forbidden by registry policy.
146    fn skips_on_nightly(&self) -> bool;
147
148    /// Whether a *failed* run of this publisher still has a real,
149    /// programmatic rollback to perform against `evidence`.
150    ///
151    /// Default `false`: a publisher's failure leaves nothing to undo (or
152    /// only an informational, human-driven unwind). The orchestration
153    /// rolls back **succeeded** Assets/Manager publishers; a failed
154    /// Submitter is normally inert.
155    ///
156    /// The cargo publisher is the exception. A multi-crate `cargo publish`
157    /// can succeed on crate A, go live on crates.io, then fail on crate B
158    /// — leaving A published under a *failed* Submitter row. cargo records
159    /// the succeeded crates in `evidence` and overrides this to `true`
160    /// when that set is non-empty, so the rollback path yanks A even
161    /// though the publisher's overall outcome is `Failed`. Returning
162    /// `false` for an empty record keeps a clean failure (nothing went
163    /// live) from arming the rollback machinery for no reason.
164    fn programmatic_rollback_on_failure(&self, _evidence: &PublishEvidence) -> bool {
165        false
166    }
167
168    /// When `true`, this publisher's successful work is left in place even
169    /// when a rollback is triggered — it is never passed to `rollback()`.
170    /// Default `false` (rollback runs if the publisher implements it).
171    fn retain_on_rollback(&self) -> bool {
172        false
173    }
174}
175
176/// The exact warn message a publisher emits when `rollback()` is invoked
177/// with no evidence to act on (empty `artifact_paths`, no `primary_ref`).
178/// Each publisher's empty-evidence branch calls this helper; tests can
179/// assert on the returned string without having to intercept stderr
180/// (`eprintln!` cannot be portably captured from the same process).
181///
182/// Lives in `anodizer_core` because the rollback shape is shared across
183/// publishers spread between `stage-publish` and `stage-blob` (and any
184/// future stage crate that implements `Publisher`).
185pub fn rollback_empty_warning_msg(publisher: &str, target_label: &str) -> String {
186    format!(
187        "no {} recorded in {} evidence — verify {} state manually",
188        target_label, publisher, publisher
189    )
190}
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195
196    struct MinimalPublisher;
197    impl Publisher for MinimalPublisher {
198        fn name(&self) -> &str {
199            "minimal"
200        }
201        fn run(&self, _ctx: &mut Context) -> anyhow::Result<PublishEvidence> {
202            Ok(PublishEvidence::new("minimal"))
203        }
204        fn group(&self) -> PublisherGroup {
205            PublisherGroup::Manager
206        }
207        fn required(&self) -> bool {
208            false
209        }
210        fn skips_on_nightly(&self) -> bool {
211            false
212        }
213    }
214
215    #[test]
216    fn rollback_default_is_noop_ok() {
217        let p = MinimalPublisher;
218        let mut ctx = Context::test_fixture();
219        let evidence = PublishEvidence::new("minimal");
220        assert!(p.rollback(&mut ctx, &evidence).is_ok());
221    }
222
223    #[test]
224    fn preflight_default_is_pass() {
225        let p = MinimalPublisher;
226        let ctx = Context::test_fixture();
227        assert!(matches!(p.preflight(&ctx).unwrap(), PreflightCheck::Pass));
228    }
229
230    #[test]
231    fn rollback_scope_needed_default_is_none() {
232        let p = MinimalPublisher;
233        assert!(p.rollback_scope_needed().is_none());
234    }
235
236    #[test]
237    fn pending_outcome_round_trips_through_context() {
238        // The slot is single-shot: write once, drain once, then empty.
239        // Without single-shot semantics, a chocolatey moderation skip
240        // would bleed into the next publisher's row at dispatch time.
241        let mut ctx = Context::test_fixture();
242        assert!(ctx.take_pending_outcome().is_none());
243
244        ctx.record_publisher_outcome(crate::PublisherOutcome::PendingModeration);
245        assert!(matches!(
246            ctx.take_pending_outcome(),
247            Some(crate::PublisherOutcome::PendingModeration)
248        ));
249        assert!(
250            ctx.take_pending_outcome().is_none(),
251            "slot must be empty after take"
252        );
253
254        // Overwrite semantics: last writer wins (no implicit accumulation).
255        ctx.record_publisher_outcome(crate::PublisherOutcome::PendingModeration);
256        ctx.record_publisher_outcome(crate::PublisherOutcome::PendingValidation);
257        assert!(matches!(
258            ctx.take_pending_outcome(),
259            Some(crate::PublisherOutcome::PendingValidation)
260        ));
261    }
262
263    #[test]
264    fn rollback_empty_warning_msg_interpolates_all_three_slots() {
265        let msg = rollback_empty_warning_msg("homebrew", "tap commit");
266        assert_eq!(
267            msg,
268            "no tap commit recorded in homebrew evidence — verify homebrew state manually"
269        );
270    }
271
272    #[test]
273    fn rollback_empty_warning_msg_distinct_per_publisher() {
274        let a = rollback_empty_warning_msg("cargo", "crate");
275        let b = rollback_empty_warning_msg("aur", "commit");
276        assert_ne!(a, b);
277        assert!(a.contains("cargo") && a.contains("crate"));
278        assert!(b.contains("aur") && b.contains("commit"));
279    }
280
281    #[test]
282    fn programmatic_rollback_on_failure_defaults_false() {
283        let p = MinimalPublisher;
284        let evidence = PublishEvidence::new("minimal");
285        assert!(!p.programmatic_rollback_on_failure(&evidence));
286    }
287
288    #[test]
289    fn retain_on_rollback_defaults_false() {
290        assert!(!MinimalPublisher.retain_on_rollback());
291    }
292
293    #[test]
294    fn requirements_default_is_empty() {
295        let p = MinimalPublisher;
296        let ctx = Context::test_fixture();
297        assert!(p.requirements(&ctx).is_empty());
298    }
299
300    #[test]
301    fn preflight_check_variants_compare_by_value() {
302        assert_eq!(PreflightCheck::Pass, PreflightCheck::Pass);
303        assert_eq!(
304            PreflightCheck::Warning("dup".into()),
305            PreflightCheck::Warning("dup".into())
306        );
307        // same variant, different payload, must not be equal
308        assert_ne!(
309            PreflightCheck::Blocker("a".into()),
310            PreflightCheck::Blocker("b".into())
311        );
312        // different variants with same string must not be equal
313        assert_ne!(
314            PreflightCheck::Warning("x".into()),
315            PreflightCheck::Blocker("x".into())
316        );
317    }
318
319    #[test]
320    fn minimal_publisher_carries_its_declared_identity() {
321        let p = MinimalPublisher;
322        assert_eq!(p.name(), "minimal");
323        assert_eq!(p.group(), PublisherGroup::Manager);
324        assert!(!p.required());
325        assert!(!p.skips_on_nightly());
326    }
327
328    /// A publisher that overrides every default-implemented hook, so the
329    /// trait dispatch is proven to reach the override (not silently shadowed
330    /// by the default body).
331    struct OverridingPublisher;
332    impl Publisher for OverridingPublisher {
333        fn name(&self) -> &str {
334            "overriding"
335        }
336        fn run(&self, _ctx: &mut Context) -> anyhow::Result<PublishEvidence> {
337            Ok(PublishEvidence::new("overriding"))
338        }
339        fn group(&self) -> PublisherGroup {
340            PublisherGroup::Assets
341        }
342        fn required(&self) -> bool {
343            true
344        }
345        fn skips_on_nightly(&self) -> bool {
346            true
347        }
348        fn preflight(&self, _ctx: &Context) -> anyhow::Result<PreflightCheck> {
349            Ok(PreflightCheck::Blocker("fork missing".into()))
350        }
351        fn rollback_scope_needed(&self) -> Option<&'static str> {
352            Some("delete_repo")
353        }
354        fn programmatic_rollback_on_failure(&self, _evidence: &PublishEvidence) -> bool {
355            true
356        }
357        fn retain_on_rollback(&self) -> bool {
358            true
359        }
360    }
361
362    #[test]
363    fn override_publisher_preflight_returns_blocker() {
364        let p = OverridingPublisher;
365        let ctx = Context::test_fixture();
366        assert_eq!(
367            p.preflight(&ctx).unwrap(),
368            PreflightCheck::Blocker("fork missing".into())
369        );
370    }
371
372    #[test]
373    fn override_publisher_exposes_rollback_scope_and_flags() {
374        let p = OverridingPublisher;
375        let evidence = PublishEvidence::new("overriding");
376        assert_eq!(p.rollback_scope_needed(), Some("delete_repo"));
377        assert!(p.programmatic_rollback_on_failure(&evidence));
378        assert!(p.retain_on_rollback());
379        assert!(p.required());
380        assert!(p.skips_on_nightly());
381        assert_eq!(p.group(), PublisherGroup::Assets);
382    }
383
384    #[test]
385    fn preflight_check_clone_preserves_payload() {
386        let warn = PreflightCheck::Warning("dup upload".into());
387        assert_eq!(warn.clone(), warn);
388        let blocker = PreflightCheck::Blocker("no tap".into());
389        let cloned = blocker.clone();
390        assert_eq!(cloned, PreflightCheck::Blocker("no tap".into()));
391        // Clone must not collapse a Warning into the same value as a Blocker.
392        assert_ne!(warn, blocker);
393    }
394
395    #[test]
396    fn merge_escalates_to_worst_severity_keeping_first_message() {
397        use PreflightCheck::{Blocker, Pass, Warning};
398
399        // Blocker dominates regardless of position, keeping its own message.
400        assert_eq!(
401            Blocker("b".into()).merge(Warning("w".into())),
402            Blocker("b".into())
403        );
404        assert_eq!(
405            Warning("w".into()).merge(Blocker("b".into())),
406            Blocker("b".into())
407        );
408        assert_eq!(Pass.merge(Blocker("b".into())), Blocker("b".into()));
409        assert_eq!(Blocker("b".into()).merge(Pass), Blocker("b".into()));
410
411        // Warning dominates Pass.
412        assert_eq!(Warning("w".into()).merge(Pass), Warning("w".into()));
413        assert_eq!(Pass.merge(Warning("w".into())), Warning("w".into()));
414
415        // Pass + Pass stays Pass.
416        assert_eq!(Pass.merge(Pass), Pass);
417
418        // Within a severity the first-seen (left) message wins.
419        assert_eq!(
420            Blocker("first".into()).merge(Blocker("second".into())),
421            Blocker("first".into())
422        );
423        assert_eq!(
424            Warning("first".into()).merge(Warning("second".into())),
425            Warning("first".into())
426        );
427    }
428}