Skip to main content

flowey_core/
node.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Core types and traits used to create and work with flowey nodes.
5
6mod github_context;
7mod spec;
8
9pub use github_context::GhOutput;
10pub use github_context::GhToRust;
11pub use github_context::RustToGh;
12
13use self::steps::ado::AdoRuntimeVar;
14use self::steps::ado::AdoStepServices;
15use self::steps::github::GhStepBuilder;
16use self::steps::rust::RustRuntimeServices;
17use self::user_facing::ClaimedGhParam;
18use self::user_facing::GhPermission;
19use self::user_facing::GhPermissionValue;
20use crate::node::github_context::GhContextVarReader;
21use github_context::state::Root;
22use serde::Deserialize;
23use serde::Serialize;
24use serde::de::DeserializeOwned;
25use std::cell::RefCell;
26use std::collections::BTreeMap;
27use std::path::PathBuf;
28use std::rc::Rc;
29use user_facing::GhParam;
30
31/// Node types which are considered "user facing", and re-exported in the
32/// `flowey` crate.
33pub mod user_facing {
34    pub use super::ClaimVar;
35    pub use super::ClaimedReadVar;
36    pub use super::ClaimedWriteVar;
37    pub use super::ConfigField;
38    pub use super::ConfigMerge;
39    pub use super::ConfigVar;
40    pub use super::FlowArch;
41    pub use super::FlowBackend;
42    pub use super::FlowNode;
43    pub use super::FlowNodeWithConfig;
44    pub use super::FlowPlatform;
45    pub use super::FlowPlatformKind;
46    pub use super::GhUserSecretVar;
47    pub use super::ImportCtx;
48    pub use super::IntoConfig;
49    pub use super::IntoRequest;
50    pub use super::NodeCtx;
51    pub use super::ReadVar;
52    pub use super::SideEffect;
53    pub use super::SimpleFlowNode;
54    pub use super::StepCtx;
55    pub use super::VarClaimed;
56    pub use super::VarEqBacking;
57    pub use super::VarNotClaimed;
58    pub use super::WriteVar;
59    pub use super::steps::ado::AdoResourcesRepositoryId;
60    pub use super::steps::ado::AdoRuntimeVar;
61    pub use super::steps::ado::AdoStepServices;
62    pub use super::steps::github::ClaimedGhParam;
63    pub use super::steps::github::GhParam;
64    pub use super::steps::github::GhPermission;
65    pub use super::steps::github::GhPermissionValue;
66    pub use super::steps::rust::RustRuntimeServices;
67    pub use crate::flowey_config;
68    pub use crate::flowey_request;
69    pub use crate::new_flow_node;
70    pub use crate::new_flow_node_with_config;
71    pub use crate::new_simple_flow_node;
72    pub use crate::node::FlowPlatformLinuxDistro;
73    pub use crate::pipeline::Artifact;
74    pub use crate::pipeline::ArtifactType;
75    pub use crate::pipeline::resolve as resolve_artifact;
76
77    /// Helper method to streamline request validation in cases where a value is
78    /// expected to be identical across all incoming requests.
79    ///
80    /// # Example: Request Aggregation Pattern
81    ///
82    /// When a node receives multiple requests, it often needs to ensure certain
83    /// values are consistent across all requests. This helper simplifies that pattern:
84    ///
85    /// ```rust,ignore
86    /// fn emit(requests: Vec<Self::Request>, ctx: &mut NodeCtx<'_>) -> anyhow::Result<()> {
87    ///     let mut version = None;
88    ///     let mut ensure_installed = Vec::new();
89    ///
90    ///     for req in requests {
91    ///         match req {
92    ///             Request::Version(v) => {
93    ///                 // Ensure all requests agree on the version
94    ///                 same_across_all_reqs("Version", &mut version, v)?;
95    ///             }
96    ///             Request::EnsureInstalled(v) => {
97    ///                 ensure_installed.push(v);
98    ///             }
99    ///         }
100    ///     }
101    ///
102    ///     let version = version.ok_or(anyhow::anyhow!("Missing required request: Version"))?;
103    ///
104    ///     // ... emit steps using aggregated requests
105    ///     Ok(())
106    /// }
107    /// ```
108    pub fn same_across_all_reqs<T: PartialEq>(
109        req_name: &str,
110        var: &mut Option<T>,
111        new: T,
112    ) -> anyhow::Result<()> {
113        match (var.as_ref(), new) {
114            (None, v) => *var = Some(v),
115            (Some(old), new) => {
116                if *old != new {
117                    anyhow::bail!("`{}` must be consistent across requests", req_name);
118                }
119            }
120        }
121
122        Ok(())
123    }
124
125    /// Helper method to streamline request validation in cases where a value is
126    /// expected to be identical across all incoming requests, using a custom
127    /// comparison function.
128    pub fn same_across_all_reqs_backing_var<V: VarEqBacking>(
129        req_name: &str,
130        var: &mut Option<V>,
131        new: V,
132    ) -> anyhow::Result<()> {
133        match (var.as_ref(), new) {
134            (None, v) => *var = Some(v),
135            (Some(old), new) => {
136                if !old.eq(&new) {
137                    anyhow::bail!("`{}` must be consistent across requests", req_name);
138                }
139            }
140        }
141
142        Ok(())
143    }
144
145    /// Helper method to handle Linux distros that are supported only on one
146    /// host architecture.
147    /// match_arch!(var, arch, result)
148    #[macro_export]
149    macro_rules! match_arch {
150        ($host_arch:expr, $match_arch:pat, $expr:expr) => {
151            if matches!($host_arch, $match_arch) {
152                $expr
153            } else {
154                anyhow::bail!("Linux distro not supported on host arch {}", $host_arch);
155            }
156        };
157    }
158
159    /// Claim a set of vars
160    #[macro_export]
161    macro_rules! claim_vars {
162        ($ctx:ident, ($($var:ident),* $(,)?)) => {
163            $(let $var = $var.claim($ctx);)*
164        };
165    }
166
167    /// Read a set of vars
168    #[macro_export]
169    macro_rules! read_vars {
170        ($rt:ident, ($($var:ident),* $(,)?)) => {
171            $(let $var = $rt.read($var);)*
172        };
173    }
174}
175
176/// Check if `ReadVar` / `WriteVar` instances are backed by the same underlying
177/// flowey Var.
178///
179/// # Why not use `Eq`? Why have a whole separate trait?
180///
181/// `ReadVar` and `WriteVar` are, in some sense, flowey's analog to
182/// "pointers", insofar as these types primary purpose is to mediate access to
183/// some contained value, as opposed to being "values" themselves.
184///
185/// Assuming you agree with this analogy, then we can apply the same logic to
186/// `ReadVar` and `WriteVar` as Rust does to `Box<T>` wrt. what the `Eq`
187/// implementation should mean.
188///
189/// Namely: `Eq` should check the equality of the _contained objects_, as
190/// opposed to the pointers themselves.
191///
192/// Unfortunately, unlike `Box<T>`, it is _impossible_ to have an `Eq` impl for
193/// `ReadVar` / `WriteVar` that checks contents for equality, due to the fact
194/// that these types exist at flow resolution time, whereas the values they
195/// contain only exist at flow runtime.
196///
197/// As such, we have a separate trait to perform different kinds of equality
198/// checks on Vars.
199pub trait VarEqBacking {
200    /// Check if `self` is backed by the same variable as `other`.
201    fn eq(&self, other: &Self) -> bool;
202}
203
204impl<T> VarEqBacking for WriteVar<T>
205where
206    T: Serialize + DeserializeOwned,
207{
208    fn eq(&self, other: &Self) -> bool {
209        self.backing_var == other.backing_var
210    }
211}
212
213impl<T> VarEqBacking for ReadVar<T>
214where
215    T: Serialize + DeserializeOwned + PartialEq + Eq + Clone,
216{
217    fn eq(&self, other: &Self) -> bool {
218        self.backing_var == other.backing_var
219    }
220}
221
222// TODO: this should be generic across all tuple sizes
223impl<T, U> VarEqBacking for (T, U)
224where
225    T: VarEqBacking,
226    U: VarEqBacking,
227{
228    fn eq(&self, other: &Self) -> bool {
229        (self.0.eq(&other.0)) && (self.1.eq(&other.1))
230    }
231}
232
233/// A wrapper around [`ReadVar<T>`] that implements [`PartialEq`] via
234/// backing-variable identity ([`VarEqBacking`]).
235///
236/// Use this in config structs where a `ReadVar` field needs equality
237/// comparison for config merging. Since `ReadVar` deliberately does not
238/// implement `PartialEq` (its values aren't known at flow-resolution time),
239/// `ConfigVar` provides identity-based comparison instead.
240///
241/// # Example
242///
243/// ```rust,ignore
244/// flowey_config! {
245///     pub struct Config {
246///         pub verbose: Option<ConfigVar<bool>>,
247///     }
248/// }
249/// ```
250#[derive(Serialize, Deserialize)]
251#[serde(bound(serialize = "T: Serialize", deserialize = "T: DeserializeOwned"))]
252pub struct ConfigVar<T>(pub ReadVar<T>);
253
254impl<T: Serialize + DeserializeOwned> Clone for ConfigVar<T> {
255    fn clone(&self) -> Self {
256        ConfigVar(self.0.clone())
257    }
258}
259
260impl<T: Serialize + DeserializeOwned + PartialEq + Eq + Clone> PartialEq for ConfigVar<T> {
261    fn eq(&self, other: &Self) -> bool {
262        VarEqBacking::eq(&self.0, &other.0)
263    }
264}
265
266impl<T: Serialize + DeserializeOwned + PartialEq + Eq + Clone> ClaimVar for ConfigVar<T> {
267    type Claimed = ClaimedReadVar<T>;
268
269    fn claim(self, ctx: &mut StepCtx<'_>) -> ClaimedReadVar<T> {
270        self.0.claim(ctx)
271    }
272}
273
274impl<T: Serialize + DeserializeOwned + PartialEq + Eq + Clone> From<ReadVar<T>> for ConfigVar<T> {
275    fn from(v: ReadVar<T>) -> Self {
276        ConfigVar(v)
277    }
278}
279
280/// Type corresponding to a step which performs a side-effect,
281/// without returning a specific value.
282///
283/// e.g: A step responsible for installing a package from `apt` might claim a
284/// `WriteVar<SideEffect>`, with any step requiring the package to have been
285/// installed prior being able to claim the corresponding `ReadVar<SideEffect>.`
286pub type SideEffect = ();
287
288/// Uninhabited type used to denote that a particular [`WriteVar`] / [`ReadVar`]
289/// is not currently claimed by any step, and cannot be directly accessed.
290#[derive(Clone, Debug, Serialize, Deserialize)]
291pub enum VarNotClaimed {}
292
293/// Uninhabited type used to denote that a particular [`WriteVar`] / [`ReadVar`]
294/// is currently claimed by a step, and can be read/written to.
295#[derive(Clone, Debug, Serialize, Deserialize)]
296pub enum VarClaimed {}
297
298/// Write a value into a flowey Var at runtime, which can then be read via a
299/// corresponding [`ReadVar`].
300///
301/// Vars in flowey must be serde de/serializable, in order to be de/serialized
302/// between multiple steps/nodes.
303///
304/// In order to write a value into a `WriteVar`, it must first be _claimed_ by a
305/// particular step (using the [`ClaimVar::claim`] API). Once claimed, the Var
306/// can be written to using APIs such as [`RustRuntimeServices::write`], or
307/// [`AdoStepServices::set_var`]
308///
309/// Note that it is only possible to write a value into a `WriteVar` _once_.
310/// Once the value has been written, the `WriteVar` type is immediately
311/// consumed, making it impossible to overwrite the stored value at some later
312/// point in execution.
313///
314/// This "write-once" property is foundational to flowey's execution model, as
315/// by recoding what step wrote to a Var, and what step(s) read from the Var, it
316/// is possible to infer what order steps must be run in.
317#[derive(Debug, Serialize, Deserialize)]
318pub struct WriteVar<T: Serialize + DeserializeOwned, C = VarNotClaimed> {
319    backing_var: String,
320    /// If true, then readers on this var expect to read a side effect (`()`)
321    /// and not `T`.
322    is_side_effect: bool,
323
324    #[serde(skip)]
325    _kind: core::marker::PhantomData<(T, C)>,
326}
327
328/// A [`WriteVar`] which has been claimed by a particular step, allowing it
329/// to be written to at runtime.
330pub type ClaimedWriteVar<T> = WriteVar<T, VarClaimed>;
331
332impl<T: Serialize + DeserializeOwned> WriteVar<T, VarNotClaimed> {
333    /// (Internal API) Switch the claim marker to "claimed".
334    fn into_claimed(self) -> WriteVar<T, VarClaimed> {
335        let Self {
336            backing_var,
337            is_side_effect,
338            _kind,
339        } = self;
340
341        WriteVar {
342            backing_var,
343            is_side_effect,
344            _kind: std::marker::PhantomData,
345        }
346    }
347
348    /// Write a static value into the Var.
349    #[track_caller]
350    pub fn write_static(self, ctx: &mut NodeCtx<'_>, val: T)
351    where
352        T: 'static,
353    {
354        let val = ReadVar::from_static(val);
355        val.write_into(ctx, self);
356    }
357
358    pub(crate) fn into_json(self) -> WriteVar<serde_json::Value> {
359        WriteVar {
360            backing_var: self.backing_var,
361            is_side_effect: self.is_side_effect,
362            _kind: std::marker::PhantomData,
363        }
364    }
365}
366
367impl WriteVar<SideEffect, VarNotClaimed> {
368    /// Transforms this writer into one that can be used to write a `T`.
369    ///
370    /// This is useful when a reader only cares about the side effect of an
371    /// operation, but the writer wants to provide output as well.
372    pub fn discard_result<T: Serialize + DeserializeOwned>(self) -> WriteVar<T> {
373        WriteVar {
374            backing_var: self.backing_var,
375            is_side_effect: true,
376            _kind: std::marker::PhantomData,
377        }
378    }
379}
380
381/// Claim one or more flowey Vars for a particular step.
382///
383/// By having this be a trait, it is possible to `claim` both single instances
384/// of `ReadVar` / `WriteVar`, as well as whole _collections_ of Vars.
385//
386// FUTURE: flowey should include a derive macro for easily claiming read/write
387// vars in user-defined structs / enums.
388pub trait ClaimVar {
389    /// The claimed version of Self.
390    type Claimed;
391    /// Claim the Var for this step, allowing it to be accessed at runtime.
392    fn claim(self, ctx: &mut StepCtx<'_>) -> Self::Claimed;
393}
394
395/// Read the value of one or more flowey Vars.
396///
397/// By having this be a trait, it is possible to `read` both single
398/// instances of `ReadVar` / `WriteVar`, as well as whole _collections_ of
399/// Vars.
400pub trait ReadVarValue {
401    /// The read value of Self.
402    type Value;
403    /// Read the value of the Var at runtime.
404    fn read_value(self, rt: &mut RustRuntimeServices<'_>) -> Self::Value;
405}
406
407impl<T: Serialize + DeserializeOwned> ClaimVar for ReadVar<T> {
408    type Claimed = ClaimedReadVar<T>;
409
410    fn claim(self, ctx: &mut StepCtx<'_>) -> ClaimedReadVar<T> {
411        if let ReadVarBacking::RuntimeVar {
412            var,
413            is_side_effect: _,
414        } = &self.backing_var
415        {
416            ctx.backend.borrow_mut().on_claimed_runtime_var(var, true);
417        }
418        self.into_claimed()
419    }
420}
421
422impl<T: Serialize + DeserializeOwned> ClaimVar for WriteVar<T> {
423    type Claimed = ClaimedWriteVar<T>;
424
425    fn claim(self, ctx: &mut StepCtx<'_>) -> ClaimedWriteVar<T> {
426        ctx.backend
427            .borrow_mut()
428            .on_claimed_runtime_var(&self.backing_var, false);
429        self.into_claimed()
430    }
431}
432
433impl<T: Serialize + DeserializeOwned> ReadVarValue for ClaimedReadVar<T> {
434    type Value = T;
435
436    fn read_value(self, rt: &mut RustRuntimeServices<'_>) -> Self::Value {
437        match self.backing_var {
438            ReadVarBacking::RuntimeVar {
439                var,
440                is_side_effect,
441            } => {
442                // Always get the data to validate that the variable is actually there.
443                let data = rt.get_var(&var, is_side_effect);
444                if is_side_effect {
445                    // This was converted into a `ReadVar<SideEffect>` from
446                    // another type, so parse the value that a
447                    // `WriteVar<SideEffect>` would have written.
448                    serde_json::from_slice(b"null").expect("should be deserializing into ()")
449                } else {
450                    // This is a normal variable.
451                    serde_json::from_slice(&data).expect("improve this error path")
452                }
453            }
454            ReadVarBacking::Inline(val) => val,
455        }
456    }
457}
458
459impl<T: ClaimVar> ClaimVar for Vec<T> {
460    type Claimed = Vec<T::Claimed>;
461
462    fn claim(self, ctx: &mut StepCtx<'_>) -> Vec<T::Claimed> {
463        self.into_iter().map(|v| v.claim(ctx)).collect()
464    }
465}
466
467impl<T: ReadVarValue> ReadVarValue for Vec<T> {
468    type Value = Vec<T::Value>;
469
470    fn read_value(self, rt: &mut RustRuntimeServices<'_>) -> Self::Value {
471        self.into_iter().map(|v| v.read_value(rt)).collect()
472    }
473}
474
475impl<T: ClaimVar> ClaimVar for Option<T> {
476    type Claimed = Option<T::Claimed>;
477
478    fn claim(self, ctx: &mut StepCtx<'_>) -> Option<T::Claimed> {
479        self.map(|x| x.claim(ctx))
480    }
481}
482
483impl<T: ReadVarValue> ReadVarValue for Option<T> {
484    type Value = Option<T::Value>;
485
486    fn read_value(self, rt: &mut RustRuntimeServices<'_>) -> Self::Value {
487        self.map(|x| x.read_value(rt))
488    }
489}
490
491impl<U: Ord, T: ClaimVar> ClaimVar for BTreeMap<U, T> {
492    type Claimed = BTreeMap<U, T::Claimed>;
493
494    fn claim(self, ctx: &mut StepCtx<'_>) -> BTreeMap<U, T::Claimed> {
495        self.into_iter().map(|(k, v)| (k, v.claim(ctx))).collect()
496    }
497}
498
499impl<U: Ord, T: ReadVarValue> ReadVarValue for BTreeMap<U, T> {
500    type Value = BTreeMap<U, T::Value>;
501
502    fn read_value(self, rt: &mut RustRuntimeServices<'_>) -> Self::Value {
503        self.into_iter()
504            .map(|(k, v)| (k, v.read_value(rt)))
505            .collect()
506    }
507}
508
509macro_rules! impl_tuple_claim {
510    ($($T:tt)*) => {
511        impl<$($T,)*> $crate::node::ClaimVar for ($($T,)*)
512        where
513            $($T: $crate::node::ClaimVar,)*
514        {
515            type Claimed = ($($T::Claimed,)*);
516
517            #[expect(non_snake_case)]
518            fn claim(self, ctx: &mut $crate::node::StepCtx<'_>) -> Self::Claimed {
519                let ($($T,)*) = self;
520                ($($T.claim(ctx),)*)
521            }
522        }
523
524        impl<$($T,)*> $crate::node::ReadVarValue for ($($T,)*)
525        where
526            $($T: $crate::node::ReadVarValue,)*
527        {
528            type Value = ($($T::Value,)*);
529
530            #[expect(non_snake_case)]
531            fn read_value(self, rt: &mut $crate::node::RustRuntimeServices<'_>) -> Self::Value {
532                let ($($T,)*) = self;
533                ($($T.read_value(rt),)*)
534            }
535        }
536    };
537}
538
539impl_tuple_claim!(A B C D E F G H I J);
540impl_tuple_claim!(A B C D E F G H I);
541impl_tuple_claim!(A B C D E F G H);
542impl_tuple_claim!(A B C D E F G);
543impl_tuple_claim!(A B C D E F);
544impl_tuple_claim!(A B C D E);
545impl_tuple_claim!(A B C D);
546impl_tuple_claim!(A B C);
547impl_tuple_claim!(A B);
548impl_tuple_claim!(A);
549
550impl ClaimVar for () {
551    type Claimed = ();
552
553    fn claim(self, _ctx: &mut StepCtx<'_>) -> Self::Claimed {}
554}
555
556impl ReadVarValue for () {
557    type Value = ();
558
559    fn read_value(self, _rt: &mut RustRuntimeServices<'_>) -> Self::Value {}
560}
561
562/// Read a custom, user-defined secret by passing in the secret name.
563///
564/// Intended usage is to get a secret using the [`crate::pipeline::Pipeline::gh_use_secret`] API
565/// and to use the returned value through the [`NodeCtx::get_gh_context_var`] API.
566#[derive(Serialize, Deserialize, Clone)]
567pub struct GhUserSecretVar(pub(crate) String);
568
569/// Read a value from a flowey Var at runtime, returning the value written by
570/// the Var's corresponding [`WriteVar`].
571///
572/// Vars in flowey must be serde de/serializable, in order to be de/serialized
573/// between multiple steps/nodes.
574///
575/// In order to read the value contained within a `ReadVar`, it must first be
576/// _claimed_ by a particular step (using the [`ClaimVar::claim`] API). Once
577/// claimed, the Var can be read using APIs such as
578/// [`RustRuntimeServices::read`], or [`AdoStepServices::get_var`]
579///
580/// Note that all `ReadVar`s in flowey are _immutable_. In other words:
581/// reading the value of a `ReadVar` multiple times from multiple nodes will
582/// _always_ return the same value.
583///
584/// This is a natural consequence `ReadVar` obtaining its value from the result
585/// of a write into [`WriteVar`], whose API enforces that there can only ever be
586/// a single Write to a `WriteVar`.
587#[derive(Debug, Serialize, Deserialize)]
588pub struct ReadVar<T, C = VarNotClaimed> {
589    backing_var: ReadVarBacking<T>,
590    #[serde(skip)]
591    _kind: std::marker::PhantomData<C>,
592}
593
594/// A [`ReadVar`] which has been claimed by a particular step, allowing it to
595/// be read at runtime.
596pub type ClaimedReadVar<T> = ReadVar<T, VarClaimed>;
597
598// cloning is fine, since you can totally have multiple dependents
599impl<T: Serialize + DeserializeOwned, C> Clone for ReadVar<T, C> {
600    fn clone(&self) -> Self {
601        ReadVar {
602            backing_var: self.backing_var.clone(),
603            _kind: std::marker::PhantomData,
604        }
605    }
606}
607
608#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
609enum ReadVarBacking<T> {
610    RuntimeVar {
611        var: String,
612        /// If true, then don't try to parse this variable--it was converted
613        /// into a side effect (of type `()`) from another type, so the
614        /// serialization will not match.
615        ///
616        /// If false, it may still be a "side effect" variable, but type `T`
617        /// matches its serialization.
618        is_side_effect: bool,
619    },
620    Inline(T),
621}
622
623// avoid requiring types to include an explicit clone bound
624impl<T: Serialize + DeserializeOwned> Clone for ReadVarBacking<T> {
625    fn clone(&self) -> Self {
626        match self {
627            Self::RuntimeVar {
628                var,
629                is_side_effect,
630            } => Self::RuntimeVar {
631                var: var.clone(),
632                is_side_effect: *is_side_effect,
633            },
634            Self::Inline(v) => {
635                Self::Inline(serde_json::from_value(serde_json::to_value(v).unwrap()).unwrap())
636            }
637        }
638    }
639}
640
641impl<T: Serialize + DeserializeOwned> ReadVar<T> {
642    /// (Internal API) Switch the claim marker to "claimed".
643    fn into_claimed(self) -> ReadVar<T, VarClaimed> {
644        let Self { backing_var, _kind } = self;
645
646        ReadVar {
647            backing_var,
648            _kind: std::marker::PhantomData,
649        }
650    }
651
652    /// Discard any type information associated with the Var, and treat the Var
653    /// as through it was only a side effect.
654    ///
655    /// e.g: if a Node returns a `ReadVar<PathBuf>`, but you know that the mere
656    /// act of having _run_ the node has ensured the file is placed in a "magic
657    /// location" for some other node, then it may be useful to treat the
658    /// `ReadVar<PathBuf>` as a simple `ReadVar<SideEffect>`, which can be
659    /// passed along as part of a larger bundle of `Vec<ReadVar<SideEffect>>`.
660    #[must_use]
661    pub fn into_side_effect(self) -> ReadVar<SideEffect> {
662        ReadVar {
663            backing_var: match self.backing_var {
664                ReadVarBacking::RuntimeVar {
665                    var,
666                    is_side_effect: _,
667                } => ReadVarBacking::RuntimeVar {
668                    var,
669                    is_side_effect: true,
670                },
671                ReadVarBacking::Inline(_) => ReadVarBacking::Inline(()),
672            },
673            _kind: std::marker::PhantomData,
674        }
675    }
676
677    /// Maps a `ReadVar<T>` to a new `ReadVar<U>`, by applying a function to the
678    /// Var at runtime.
679    #[track_caller]
680    #[must_use]
681    pub fn map<F, U>(&self, ctx: &mut NodeCtx<'_>, f: F) -> ReadVar<U>
682    where
683        T: 'static,
684        U: Serialize + DeserializeOwned + 'static,
685        F: FnOnce(T) -> U + 'static,
686    {
687        let (read_from, write_into) = ctx.new_var();
688        self.write_into_with(ctx, write_into, f);
689        read_from
690    }
691
692    /// Maps a `ReadVar<T>` into an existing `WriteVar<U>` by applying a
693    /// function to the Var at runtime.
694    #[track_caller]
695    pub fn write_into_with<F, U>(&self, ctx: &mut NodeCtx<'_>, write_into: WriteVar<U>, f: F)
696    where
697        T: 'static,
698        U: Serialize + DeserializeOwned + 'static,
699        F: FnOnce(T) -> U + 'static,
700    {
701        let this = self.clone();
702        ctx.emit_minor_rust_step("🌼 write_into Var", move |ctx| {
703            let this = this.claim(ctx);
704            let write_into = write_into.claim(ctx);
705            move |rt| {
706                let this = rt.read(this);
707                rt.write(write_into, &f(this));
708            }
709        });
710    }
711
712    /// Maps a `ReadVar<T>` into an existing `WriteVar<U>`
713    #[track_caller]
714    pub fn write_into(&self, ctx: &mut NodeCtx<'_>, write_into: WriteVar<T>)
715    where
716        T: 'static,
717    {
718        self.write_into_with(ctx, write_into, |x| x);
719    }
720
721    /// Zips self (`ReadVar<T>`) with another `ReadVar<U>`, returning a new
722    /// `ReadVar<(T, U)>`
723    #[track_caller]
724    #[must_use]
725    pub fn zip<U>(&self, ctx: &mut NodeCtx<'_>, other: ReadVar<U>) -> ReadVar<(T, U)>
726    where
727        T: 'static,
728        U: Serialize + DeserializeOwned + 'static,
729    {
730        let (read_from, write_into) = ctx.new_var();
731        let this = self.clone();
732        ctx.emit_minor_rust_step("🌼 Zip Vars", move |ctx| {
733            let this = this.claim(ctx);
734            let other = other.claim(ctx);
735            let write_into = write_into.claim(ctx);
736            move |rt| {
737                let this = rt.read(this);
738                let other = rt.read(other);
739                rt.write(write_into, &(this, other));
740            }
741        });
742        read_from
743    }
744
745    /// Create a new `ReadVar` from a static value.
746    ///
747    /// **WARNING:** Static values **CANNOT BE SECRETS**, as they are encoded as
748    /// plain-text in the output flow.
749    #[track_caller]
750    #[must_use]
751    pub fn from_static(val: T) -> ReadVar<T>
752    where
753        T: 'static,
754    {
755        ReadVar {
756            backing_var: ReadVarBacking::Inline(val),
757            _kind: std::marker::PhantomData,
758        }
759    }
760
761    /// If this [`ReadVar`] contains a static value, return it.
762    ///
763    /// Nodes can opt-in to using this method as a way to generate optimized
764    /// steps in cases where the value of a variable is known ahead of time.
765    ///
766    /// e.g: a node doing a git checkout could leverage this method to decide
767    /// whether its ADO backend should emit a conditional step for checking out
768    /// a repo, or if it can statically include / exclude the checkout request.
769    pub fn get_static(&self) -> Option<T> {
770        match self.clone().backing_var {
771            ReadVarBacking::Inline(v) => Some(v),
772            _ => None,
773        }
774    }
775
776    /// Transpose a `Vec<ReadVar<T>>` into a `ReadVar<Vec<T>>`
777    #[track_caller]
778    #[must_use]
779    pub fn transpose_vec(ctx: &mut NodeCtx<'_>, vec: Vec<ReadVar<T>>) -> ReadVar<Vec<T>>
780    where
781        T: 'static,
782    {
783        let (read_from, write_into) = ctx.new_var();
784        ctx.emit_minor_rust_step("🌼 Transpose Vec<ReadVar<T>>", move |ctx| {
785            let vec = vec.claim(ctx);
786            let write_into = write_into.claim(ctx);
787            move |rt| {
788                let mut v = Vec::new();
789                for var in vec {
790                    v.push(rt.read(var));
791                }
792                rt.write(write_into, &v);
793            }
794        });
795        read_from
796    }
797
798    /// Returns a new instance of this variable with an artificial dependency on
799    /// `other`.
800    ///
801    /// This is useful for making explicit a non-explicit dependency between the
802    /// two variables. For example, if `self` contains a path to a file, and
803    /// `other` is only written once that file has been created, then this
804    /// method can be used to return a new `ReadVar` which depends on `other`
805    /// but is otherwise identical to `self`. This ensures that when the new
806    /// variable is read, the file has been created.
807    ///
808    /// In general, it is better to ensure that the dependency is explicit, so
809    /// that if you have a variable with a path, then you know that the file
810    /// exists when you read it. This method is useful in cases where this is
811    /// not naturally the case, e.g., when you are providing a path as part of a
812    /// request, as opposed to the path being returned to you.
813    #[must_use]
814    pub fn depending_on<U>(&self, ctx: &mut NodeCtx<'_>, other: &ReadVar<U>) -> Self
815    where
816        T: 'static,
817        U: Serialize + DeserializeOwned + 'static,
818    {
819        // This could probably be handled without an additional Rust step with some
820        // additional work in the backend, but this is simple enough for now.
821        ctx.emit_minor_rust_stepv("🌼 Add dependency", |ctx| {
822            let this = self.clone().claim(ctx);
823            other.clone().claim(ctx);
824            move |rt| rt.read(this)
825        })
826    }
827
828    /// Consume this `ReadVar` outside the context of a step, signalling that it
829    /// won't be used.
830    pub fn claim_unused(self, ctx: &mut NodeCtx<'_>) {
831        match self.backing_var {
832            ReadVarBacking::RuntimeVar {
833                var,
834                is_side_effect: _,
835            } => ctx.backend.borrow_mut().on_unused_read_var(&var),
836            ReadVarBacking::Inline(_) => {}
837        }
838    }
839
840    pub(crate) fn into_json(self) -> ReadVar<serde_json::Value> {
841        match self.backing_var {
842            ReadVarBacking::RuntimeVar {
843                var,
844                is_side_effect,
845            } => ReadVar {
846                backing_var: ReadVarBacking::RuntimeVar {
847                    var,
848                    is_side_effect,
849                },
850                _kind: std::marker::PhantomData,
851            },
852            ReadVarBacking::Inline(v) => ReadVar {
853                backing_var: ReadVarBacking::Inline(serde_json::to_value(v).unwrap()),
854                _kind: std::marker::PhantomData,
855            },
856        }
857    }
858}
859
860/// DANGER: obtain a handle to a [`ReadVar`] "out of thin air".
861///
862/// This should NEVER be used from within a flowey node. This is a sharp tool,
863/// and should only be used by code implementing flow / pipeline resolution
864/// logic.
865#[must_use]
866pub fn thin_air_read_runtime_var<T>(backing_var: String) -> ReadVar<T>
867where
868    T: Serialize + DeserializeOwned,
869{
870    ReadVar {
871        backing_var: ReadVarBacking::RuntimeVar {
872            var: backing_var,
873            is_side_effect: false,
874        },
875        _kind: std::marker::PhantomData,
876    }
877}
878
879/// DANGER: obtain a handle to a [`WriteVar`] "out of thin air".
880///
881/// This should NEVER be used from within a flowey node. This is a sharp tool,
882/// and should only be used by code implementing flow / pipeline resolution
883/// logic.
884#[must_use]
885pub fn thin_air_write_runtime_var<T>(backing_var: String) -> WriteVar<T>
886where
887    T: Serialize + DeserializeOwned,
888{
889    WriteVar {
890        backing_var,
891        is_side_effect: false,
892        _kind: std::marker::PhantomData,
893    }
894}
895
896/// DANGER: obtain a [`ReadVar`] backing variable and side effect status.
897///
898/// This should NEVER be used from within a flowey node. This relies on
899/// flowey variable implementation details, and should only be used by code
900/// implementing flow / pipeline resolution logic.
901pub fn read_var_internals<T: Serialize + DeserializeOwned, C>(
902    var: &ReadVar<T, C>,
903) -> (Option<String>, bool) {
904    match var.backing_var {
905        ReadVarBacking::RuntimeVar {
906            var: ref s,
907            is_side_effect,
908        } => (Some(s.clone()), is_side_effect),
909        ReadVarBacking::Inline(_) => (None, false),
910    }
911}
912
913pub trait ImportCtxBackend {
914    fn on_possible_dep(&mut self, node_handle: NodeHandle);
915}
916
917/// Context passed to [`FlowNode::imports`].
918pub struct ImportCtx<'a> {
919    backend: &'a mut dyn ImportCtxBackend,
920}
921
922impl ImportCtx<'_> {
923    /// Declare that a Node can be referenced in [`FlowNode::emit`]
924    pub fn import<N: FlowNodeBase + 'static>(&mut self) {
925        self.backend.on_possible_dep(NodeHandle::from_type::<N>())
926    }
927}
928
929pub fn new_import_ctx(backend: &mut dyn ImportCtxBackend) -> ImportCtx<'_> {
930    ImportCtx { backend }
931}
932
933pub trait NodeCtxBackend {
934    /// Handle to the current node this `ctx` corresponds to
935    fn current_node(&self) -> NodeHandle;
936
937    /// Return a string which uniquely identifies this particular Var
938    /// registration.
939    ///
940    /// Typically consists of `{current node handle}{ordinal}`
941    fn on_new_var(&mut self) -> String;
942
943    /// Invoked when a node claims a particular runtime variable
944    fn on_claimed_runtime_var(&mut self, var: &str, is_read: bool);
945
946    /// Invoked when a node marks a particular runtime variable as unused
947    fn on_unused_read_var(&mut self, var: &str);
948
949    /// Invoked when a node sets a request on a node.
950    ///
951    /// - `node_typeid` will always correspond to a node that was previously
952    ///   passed to `on_register`.
953    /// - `req` may be an error, in the case where the NodeCtx failed to
954    ///   serialize the provided request.
955    // FIXME: this should be using type-erased serde
956    fn on_request(&mut self, node_handle: NodeHandle, req: anyhow::Result<Box<[u8]>>);
957
958    /// Invoked when a node sets config on another node.
959    ///
960    /// Config is merged by the resolver and delivered before action requests.
961    fn on_config(&mut self, node_handle: NodeHandle, config: anyhow::Result<Box<[u8]>>);
962
963    fn on_emit_rust_step(
964        &mut self,
965        label: &str,
966        can_merge: bool,
967        code: Box<dyn for<'a> FnOnce(&'a mut RustRuntimeServices<'_>) -> anyhow::Result<()>>,
968    );
969
970    fn on_emit_ado_step(
971        &mut self,
972        label: &str,
973        yaml_snippet: Box<dyn for<'a> FnOnce(&'a mut AdoStepServices<'_>) -> String>,
974        inline_script: Option<
975            Box<dyn for<'a> FnOnce(&'a mut RustRuntimeServices<'_>) -> anyhow::Result<()>>,
976        >,
977        condvar: Option<String>,
978    );
979
980    fn on_emit_gh_step(
981        &mut self,
982        label: &str,
983        uses: &str,
984        with: BTreeMap<String, ClaimedGhParam>,
985        condvar: Option<String>,
986        outputs: BTreeMap<String, Vec<GhOutput>>,
987        permissions: BTreeMap<GhPermission, GhPermissionValue>,
988        gh_to_rust: Vec<GhToRust>,
989        rust_to_gh: Vec<RustToGh>,
990    );
991
992    fn on_emit_side_effect_step(&mut self);
993
994    fn backend(&mut self) -> FlowBackend;
995    fn platform(&mut self) -> FlowPlatform;
996    fn arch(&mut self) -> FlowArch;
997
998    /// Return a node-specific persistent store path. The backend does not need
999    /// to ensure that the path exists - flowey will automatically emit a step
1000    /// to construct the directory at runtime.
1001    fn persistent_dir_path_var(&mut self) -> Option<String>;
1002}
1003
1004pub fn new_node_ctx(backend: &mut dyn NodeCtxBackend) -> NodeCtx<'_> {
1005    NodeCtx {
1006        backend: Rc::new(RefCell::new(backend)),
1007    }
1008}
1009
1010/// What backend the flow is being running on.
1011#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1012pub enum FlowBackend {
1013    /// Running locally.
1014    Local,
1015    /// Running on ADO.
1016    Ado,
1017    /// Running on GitHub Actions
1018    Github,
1019}
1020
1021/// The kind platform the flow is being running on, Windows or Unix.
1022#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1023pub enum FlowPlatformKind {
1024    Windows,
1025    Unix,
1026}
1027
1028/// The kind platform the flow is being running on, Windows or Unix.
1029#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
1030pub enum FlowPlatformLinuxDistro {
1031    /// Fedora (including WSL2)
1032    Fedora,
1033    /// Ubuntu (including WSL2)
1034    Ubuntu,
1035    /// Azure Linux (tdnf-based)
1036    AzureLinux,
1037    /// Arch Linux (including WSL2)
1038    Arch,
1039    /// openSUSE (including WSL2)
1040    OpenSuse,
1041    /// Nix environment (detected via IN_NIX_SHELL env var or having a `/nix/store` in PATH)
1042    Nix,
1043    /// An unknown distribution
1044    Unknown,
1045}
1046
1047/// What platform the flow is being running on.
1048#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
1049#[non_exhaustive]
1050pub enum FlowPlatform {
1051    /// Windows
1052    Windows,
1053    /// Linux (including WSL2)
1054    Linux(FlowPlatformLinuxDistro),
1055    /// macOS
1056    MacOs,
1057}
1058
1059impl FlowPlatform {
1060    pub fn kind(&self) -> FlowPlatformKind {
1061        match self {
1062            Self::Windows => FlowPlatformKind::Windows,
1063            Self::Linux(_) | Self::MacOs => FlowPlatformKind::Unix,
1064        }
1065    }
1066
1067    fn as_str(&self) -> &'static str {
1068        match self {
1069            Self::Windows => "windows",
1070            Self::Linux(_) => "linux",
1071            Self::MacOs => "macos",
1072        }
1073    }
1074
1075    /// The suffix to use for executables on this platform.
1076    pub fn exe_suffix(&self) -> &'static str {
1077        if self == &Self::Windows { ".exe" } else { "" }
1078    }
1079
1080    /// The full name for a binary on this platform (i.e. `name + self.exe_suffix()`).
1081    pub fn binary(&self, name: &str) -> String {
1082        format!("{}{}", name, self.exe_suffix())
1083    }
1084}
1085
1086impl std::fmt::Display for FlowPlatform {
1087    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1088        f.pad(self.as_str())
1089    }
1090}
1091
1092/// What architecture the flow is being running on.
1093#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
1094#[non_exhaustive]
1095pub enum FlowArch {
1096    X86_64,
1097    Aarch64,
1098}
1099
1100impl FlowArch {
1101    fn as_str(&self) -> &'static str {
1102        match self {
1103            Self::X86_64 => "x86_64",
1104            Self::Aarch64 => "aarch64",
1105        }
1106    }
1107}
1108
1109impl std::fmt::Display for FlowArch {
1110    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1111        f.pad(self.as_str())
1112    }
1113}
1114
1115/// Context object for an individual step.
1116pub struct StepCtx<'a> {
1117    backend: Rc<RefCell<&'a mut dyn NodeCtxBackend>>,
1118}
1119
1120impl StepCtx<'_> {
1121    /// What backend the flow is being running on (e.g: locally, ADO, GitHub,
1122    /// etc...)
1123    pub fn backend(&self) -> FlowBackend {
1124        self.backend.borrow_mut().backend()
1125    }
1126
1127    /// What platform the flow is being running on (e.g: windows, linux, wsl2,
1128    /// etc...).
1129    pub fn platform(&self) -> FlowPlatform {
1130        self.backend.borrow_mut().platform()
1131    }
1132}
1133
1134const NO_ADO_INLINE_SCRIPT: Option<
1135    for<'a> fn(&'a mut RustRuntimeServices<'_>) -> anyhow::Result<()>,
1136> = None;
1137
1138/// Context object for a `FlowNode`.
1139pub struct NodeCtx<'a> {
1140    backend: Rc<RefCell<&'a mut dyn NodeCtxBackend>>,
1141}
1142
1143impl<'ctx> NodeCtx<'ctx> {
1144    /// Emit a Rust-based step.
1145    ///
1146    /// As a convenience feature, this function returns a special _optional_
1147    /// [`ReadVar<SideEffect>`], which will not result in a "unused variable"
1148    /// error if no subsequent step ends up claiming it.
1149    pub fn emit_rust_step<F, G>(&mut self, label: impl AsRef<str>, code: F) -> ReadVar<SideEffect>
1150    where
1151        F: for<'a> FnOnce(&'a mut StepCtx<'_>) -> G,
1152        G: for<'a> FnOnce(&'a mut RustRuntimeServices<'_>) -> anyhow::Result<()> + 'static,
1153    {
1154        self.emit_rust_step_inner(label.as_ref(), false, code)
1155    }
1156
1157    /// Emit a Rust-based step that cannot fail.
1158    ///
1159    /// This is equivalent to [`NodeCtx::emit_rust_step`], but it is for steps that cannot
1160    /// fail and that do not need to be emitted as a separate step in a YAML
1161    /// pipeline. This simplifies the pipeline logs.
1162    pub fn emit_minor_rust_step<F, G>(
1163        &mut self,
1164        label: impl AsRef<str>,
1165        code: F,
1166    ) -> ReadVar<SideEffect>
1167    where
1168        F: for<'a> FnOnce(&'a mut StepCtx<'_>) -> G,
1169        G: for<'a> FnOnce(&'a mut RustRuntimeServices<'_>) + 'static,
1170    {
1171        self.emit_rust_step_inner(label.as_ref(), true, |ctx| {
1172            let f = code(ctx);
1173            |rt| {
1174                f(rt);
1175                Ok(())
1176            }
1177        })
1178    }
1179
1180    /// Emit a Rust-based step, creating a new `ReadVar<T>` from the step's
1181    /// return value.
1182    ///
1183    /// This is a convenience function that streamlines the following common
1184    /// flowey pattern:
1185    ///
1186    /// ```ignore
1187    /// // creating a new Var explicitly
1188    /// let (read_foo, write_foo) = ctx.new_var();
1189    /// ctx.emit_rust_step("foo", |ctx| {
1190    ///     let write_foo = write_foo.claim(ctx);
1191    ///     |rt| {
1192    ///         rt.write(write_foo, &get_foo());
1193    ///         Ok(())
1194    ///     }
1195    /// });
1196    ///
1197    /// // creating a new Var automatically
1198    /// let read_foo = ctx.emit_rust_stepv("foo", |ctx| |rt| Ok(get_foo()));
1199    /// ```
1200    #[must_use]
1201    #[track_caller]
1202    pub fn emit_rust_stepv<T, F, G>(&mut self, label: impl AsRef<str>, code: F) -> ReadVar<T>
1203    where
1204        T: Serialize + DeserializeOwned + 'static,
1205        F: for<'a> FnOnce(&'a mut StepCtx<'_>) -> G,
1206        G: for<'a> FnOnce(&'a mut RustRuntimeServices<'_>) -> anyhow::Result<T> + 'static,
1207    {
1208        self.emit_rust_stepv_inner(label.as_ref(), false, code)
1209    }
1210
1211    /// Emit a Rust-based step, creating a new `ReadVar<T>` from the step's
1212    /// return value.
1213    ///
1214    /// This is equivalent to `emit_rust_stepv`, but it is for steps that cannot
1215    /// fail and that do not need to be emitted as a separate step in a YAML
1216    /// pipeline. This simplifies the pipeline logs.
1217    ///
1218    /// This is a convenience function that streamlines the following common
1219    /// flowey pattern:
1220    ///
1221    /// ```ignore
1222    /// // creating a new Var explicitly
1223    /// let (read_foo, write_foo) = ctx.new_var();
1224    /// ctx.emit_minor_rust_step("foo", |ctx| {
1225    ///     let write_foo = write_foo.claim(ctx);
1226    ///     |rt| {
1227    ///         rt.write(write_foo, &get_foo());
1228    ///     }
1229    /// });
1230    ///
1231    /// // creating a new Var automatically
1232    /// let read_foo = ctx.emit_minor_rust_stepv("foo", |ctx| |rt| get_foo());
1233    /// ```
1234    #[must_use]
1235    #[track_caller]
1236    pub fn emit_minor_rust_stepv<T, F, G>(&mut self, label: impl AsRef<str>, code: F) -> ReadVar<T>
1237    where
1238        T: Serialize + DeserializeOwned + 'static,
1239        F: for<'a> FnOnce(&'a mut StepCtx<'_>) -> G,
1240        G: for<'a> FnOnce(&'a mut RustRuntimeServices<'_>) -> T + 'static,
1241    {
1242        self.emit_rust_stepv_inner(label.as_ref(), true, |ctx| {
1243            let f = code(ctx);
1244            |rt| Ok(f(rt))
1245        })
1246    }
1247
1248    fn emit_rust_step_inner<F, G>(
1249        &mut self,
1250        label: &str,
1251        can_merge: bool,
1252        code: F,
1253    ) -> ReadVar<SideEffect>
1254    where
1255        F: for<'a> FnOnce(&'a mut StepCtx<'_>) -> G,
1256        G: for<'a> FnOnce(&'a mut RustRuntimeServices<'_>) -> anyhow::Result<()> + 'static,
1257    {
1258        let (read, write) = self.new_prefixed_var("auto_se");
1259
1260        let ctx = &mut StepCtx {
1261            backend: self.backend.clone(),
1262        };
1263        write.claim(ctx);
1264
1265        let code = code(ctx);
1266        self.backend
1267            .borrow_mut()
1268            .on_emit_rust_step(label.as_ref(), can_merge, Box::new(code));
1269        read
1270    }
1271
1272    #[must_use]
1273    #[track_caller]
1274    fn emit_rust_stepv_inner<T, F, G>(
1275        &mut self,
1276        label: impl AsRef<str>,
1277        can_merge: bool,
1278        code: F,
1279    ) -> ReadVar<T>
1280    where
1281        T: Serialize + DeserializeOwned + 'static,
1282        F: for<'a> FnOnce(&'a mut StepCtx<'_>) -> G,
1283        G: for<'a> FnOnce(&'a mut RustRuntimeServices<'_>) -> anyhow::Result<T> + 'static,
1284    {
1285        let (read, write) = self.new_var();
1286
1287        let ctx = &mut StepCtx {
1288            backend: self.backend.clone(),
1289        };
1290        let write = write.claim(ctx);
1291
1292        let code = code(ctx);
1293        self.backend.borrow_mut().on_emit_rust_step(
1294            label.as_ref(),
1295            can_merge,
1296            Box::new(|rt| {
1297                let val = code(rt)?;
1298                rt.write(write, &val);
1299                Ok(())
1300            }),
1301        );
1302        read
1303    }
1304
1305    /// Load an ADO global runtime variable into a flowey [`ReadVar`].
1306    #[track_caller]
1307    #[must_use]
1308    pub fn get_ado_variable(&mut self, ado_var: AdoRuntimeVar) -> ReadVar<String> {
1309        let (var, write_var) = self.new_var();
1310        self.emit_ado_step(format!("🌼 read {}", ado_var.as_raw_var_name()), |ctx| {
1311            let write_var = write_var.claim(ctx);
1312            |rt| {
1313                rt.set_var(write_var, ado_var);
1314                "".into()
1315            }
1316        });
1317        var
1318    }
1319
1320    /// Emit an ADO step.
1321    pub fn emit_ado_step<F, G>(&mut self, display_name: impl AsRef<str>, yaml_snippet: F)
1322    where
1323        F: for<'a> FnOnce(&'a mut StepCtx<'_>) -> G,
1324        G: for<'a> FnOnce(&'a mut AdoStepServices<'_>) -> String + 'static,
1325    {
1326        self.emit_ado_step_inner(display_name, None, |ctx| {
1327            (yaml_snippet(ctx), NO_ADO_INLINE_SCRIPT)
1328        })
1329    }
1330
1331    /// Emit an ADO step, conditionally executed based on the value of `cond` at
1332    /// runtime.
1333    pub fn emit_ado_step_with_condition<F, G>(
1334        &mut self,
1335        display_name: impl AsRef<str>,
1336        cond: ReadVar<bool>,
1337        yaml_snippet: F,
1338    ) where
1339        F: for<'a> FnOnce(&'a mut StepCtx<'_>) -> G,
1340        G: for<'a> FnOnce(&'a mut AdoStepServices<'_>) -> String + 'static,
1341    {
1342        self.emit_ado_step_inner(display_name, Some(cond), |ctx| {
1343            (yaml_snippet(ctx), NO_ADO_INLINE_SCRIPT)
1344        })
1345    }
1346
1347    /// Emit an ADO step, conditionally executed based on the value of`cond` at
1348    /// runtime.
1349    pub fn emit_ado_step_with_condition_optional<F, G>(
1350        &mut self,
1351        display_name: impl AsRef<str>,
1352        cond: Option<ReadVar<bool>>,
1353        yaml_snippet: F,
1354    ) where
1355        F: for<'a> FnOnce(&'a mut StepCtx<'_>) -> G,
1356        G: for<'a> FnOnce(&'a mut AdoStepServices<'_>) -> String + 'static,
1357    {
1358        self.emit_ado_step_inner(display_name, cond, |ctx| {
1359            (yaml_snippet(ctx), NO_ADO_INLINE_SCRIPT)
1360        })
1361    }
1362
1363    /// Emit an ADO step which invokes a rust callback using an inline script.
1364    ///
1365    /// By using the `{{FLOWEY_INLINE_SCRIPT}}` template in the returned yaml
1366    /// snippet, flowey will interpolate a command ~roughly akin to `flowey
1367    /// exec-snippet <rust-snippet-id>` into the generated yaml.
1368    ///
1369    /// e.g: if we wanted to _manually_ wrap the bash ADO snippet for whatever
1370    /// reason:
1371    ///
1372    /// ```text
1373    /// - bash: |
1374    ///     echo "hello there!"
1375    ///     {{FLOWEY_INLINE_SCRIPT}}
1376    ///     echo echo "bye!"
1377    /// ```
1378    ///
1379    /// # Limitations
1380    ///
1381    /// At the moment, due to flowey API limitations, it is only possible to
1382    /// embed a single inline script into a YAML step.
1383    ///
1384    /// In the future, rather than having separate methods for "emit step with X
1385    /// inline scripts", flowey should support declaring "first-class" callbacks
1386    /// via a (hypothetical) `ctx.new_callback_var(|ctx| |rt, input: Input| ->
1387    /// Output { ... })` API, at which point.
1388    ///
1389    /// If such an API were to exist, one could simply use the "vanilla" emit
1390    /// yaml step functions with these first-class callbacks.
1391    pub fn emit_ado_step_with_inline_script<F, G, H>(
1392        &mut self,
1393        display_name: impl AsRef<str>,
1394        yaml_snippet: F,
1395    ) where
1396        F: for<'a> FnOnce(&'a mut StepCtx<'_>) -> (G, H),
1397        G: for<'a> FnOnce(&'a mut AdoStepServices<'_>) -> String + 'static,
1398        H: for<'a> FnOnce(&'a mut RustRuntimeServices<'_>) -> anyhow::Result<()> + 'static,
1399    {
1400        self.emit_ado_step_inner(display_name, None, |ctx| {
1401            let (f, g) = yaml_snippet(ctx);
1402            (f, Some(g))
1403        })
1404    }
1405
1406    fn emit_ado_step_inner<F, G, H>(
1407        &mut self,
1408        display_name: impl AsRef<str>,
1409        cond: Option<ReadVar<bool>>,
1410        yaml_snippet: F,
1411    ) where
1412        F: for<'a> FnOnce(&'a mut StepCtx<'_>) -> (G, Option<H>),
1413        G: for<'a> FnOnce(&'a mut AdoStepServices<'_>) -> String + 'static,
1414        H: for<'a> FnOnce(&'a mut RustRuntimeServices<'_>) -> anyhow::Result<()> + 'static,
1415    {
1416        let condvar = match cond.map(|c| c.backing_var) {
1417            // it seems silly to allow this... but it's not hard so why not?
1418            Some(ReadVarBacking::Inline(cond)) => {
1419                if !cond {
1420                    return;
1421                } else {
1422                    None
1423                }
1424            }
1425            Some(ReadVarBacking::RuntimeVar {
1426                var,
1427                is_side_effect,
1428            }) => {
1429                assert!(!is_side_effect);
1430                self.backend.borrow_mut().on_claimed_runtime_var(&var, true);
1431                Some(var)
1432            }
1433            None => None,
1434        };
1435
1436        let (yaml_snippet, inline_script) = yaml_snippet(&mut StepCtx {
1437            backend: self.backend.clone(),
1438        });
1439        self.backend.borrow_mut().on_emit_ado_step(
1440            display_name.as_ref(),
1441            Box::new(yaml_snippet),
1442            if let Some(inline_script) = inline_script {
1443                Some(Box::new(inline_script))
1444            } else {
1445                None
1446            },
1447            condvar,
1448        );
1449    }
1450
1451    /// Load a GitHub context variable into a flowey [`ReadVar`].
1452    #[track_caller]
1453    #[must_use]
1454    pub fn get_gh_context_var(&mut self) -> GhContextVarReader<'ctx, Root> {
1455        GhContextVarReader {
1456            ctx: NodeCtx {
1457                backend: self.backend.clone(),
1458            },
1459            _state: std::marker::PhantomData,
1460        }
1461    }
1462
1463    /// Emit a GitHub Actions action step.
1464    pub fn emit_gh_step(
1465        &mut self,
1466        display_name: impl AsRef<str>,
1467        uses: impl AsRef<str>,
1468    ) -> GhStepBuilder {
1469        GhStepBuilder::new(display_name, uses)
1470    }
1471
1472    fn emit_gh_step_inner(
1473        &mut self,
1474        display_name: impl AsRef<str>,
1475        cond: Option<ReadVar<bool>>,
1476        uses: impl AsRef<str>,
1477        with: Option<BTreeMap<String, GhParam>>,
1478        outputs: BTreeMap<String, Vec<WriteVar<String>>>,
1479        run_after: Vec<ReadVar<SideEffect>>,
1480        permissions: BTreeMap<GhPermission, GhPermissionValue>,
1481    ) {
1482        let condvar = match cond.map(|c| c.backing_var) {
1483            // it seems silly to allow this... but it's not hard so why not?
1484            Some(ReadVarBacking::Inline(cond)) => {
1485                if !cond {
1486                    return;
1487                } else {
1488                    None
1489                }
1490            }
1491            Some(ReadVarBacking::RuntimeVar {
1492                var,
1493                is_side_effect,
1494            }) => {
1495                assert!(!is_side_effect);
1496                self.backend.borrow_mut().on_claimed_runtime_var(&var, true);
1497                Some(var)
1498            }
1499            None => None,
1500        };
1501
1502        let with = with
1503            .unwrap_or_default()
1504            .into_iter()
1505            .map(|(k, v)| {
1506                (
1507                    k.clone(),
1508                    v.claim(&mut StepCtx {
1509                        backend: self.backend.clone(),
1510                    }),
1511                )
1512            })
1513            .collect();
1514
1515        for var in run_after {
1516            var.claim(&mut StepCtx {
1517                backend: self.backend.clone(),
1518            });
1519        }
1520
1521        let outputvars = outputs
1522            .into_iter()
1523            .map(|(name, vars)| {
1524                (
1525                    name,
1526                    vars.into_iter()
1527                        .map(|var| {
1528                            let var = var.claim(&mut StepCtx {
1529                                backend: self.backend.clone(),
1530                            });
1531                            GhOutput {
1532                                backing_var: var.backing_var,
1533                                is_secret: false,
1534                                is_object: false,
1535                            }
1536                        })
1537                        .collect(),
1538                )
1539            })
1540            .collect();
1541
1542        self.backend.borrow_mut().on_emit_gh_step(
1543            display_name.as_ref(),
1544            uses.as_ref(),
1545            with,
1546            condvar,
1547            outputvars,
1548            permissions,
1549            Vec::new(),
1550            Vec::new(),
1551        );
1552    }
1553
1554    /// Emit a "side-effect" step, which simply claims a set of side-effects in
1555    /// order to resolve another set of side effects.
1556    ///
1557    /// The same functionality could be achieved (less efficiently) by emitting
1558    /// a Rust step (or ADO step, or github step, etc...) that claims both sets
1559    /// of side-effects, and then does nothing. By using this method - flowey is
1560    /// able to avoid emitting that additional noop step at runtime.
1561    pub fn emit_side_effect_step(
1562        &mut self,
1563        use_side_effects: impl IntoIterator<Item = ReadVar<SideEffect>>,
1564        resolve_side_effects: impl IntoIterator<Item = WriteVar<SideEffect>>,
1565    ) {
1566        let mut backend = self.backend.borrow_mut();
1567        for var in use_side_effects.into_iter() {
1568            if let ReadVarBacking::RuntimeVar {
1569                var,
1570                is_side_effect: _,
1571            } = &var.backing_var
1572            {
1573                backend.on_claimed_runtime_var(var, true);
1574            }
1575        }
1576
1577        for var in resolve_side_effects.into_iter() {
1578            backend.on_claimed_runtime_var(&var.backing_var, false);
1579        }
1580
1581        backend.on_emit_side_effect_step();
1582    }
1583
1584    /// What backend the flow is being running on (e.g: locally, ADO, GitHub,
1585    /// etc...)
1586    pub fn backend(&self) -> FlowBackend {
1587        self.backend.borrow_mut().backend()
1588    }
1589
1590    /// What platform the flow is being running on (e.g: windows, linux, wsl2,
1591    /// etc...).
1592    pub fn platform(&self) -> FlowPlatform {
1593        self.backend.borrow_mut().platform()
1594    }
1595
1596    /// What architecture the flow is being running on (x86_64 or Aarch64)
1597    pub fn arch(&self) -> FlowArch {
1598        self.backend.borrow_mut().arch()
1599    }
1600
1601    /// Set a request on a particular node.
1602    pub fn req<R>(&mut self, req: R)
1603    where
1604        R: IntoRequest + 'static,
1605    {
1606        let mut backend = self.backend.borrow_mut();
1607        backend.on_request(
1608            NodeHandle::from_type::<R::Node>(),
1609            serde_json::to_vec(&req.into_request())
1610                .map(Into::into)
1611                .map_err(Into::into),
1612        );
1613    }
1614
1615    /// Set config on a particular node.
1616    ///
1617    /// Config is merged by the resolver (all callers must agree on values)
1618    /// and delivered to the target node before any action requests.
1619    pub fn config<C>(&mut self, config: C)
1620    where
1621        C: IntoConfig + 'static,
1622    {
1623        let mut backend = self.backend.borrow_mut();
1624        backend.on_config(
1625            NodeHandle::from_type::<C::Node>(),
1626            serde_json::to_vec(&config)
1627                .map(Into::into)
1628                .map_err(Into::into),
1629        );
1630    }
1631
1632    /// Set a request on a particular node, simultaneously creating a new flowey
1633    /// Var in the process.
1634    #[track_caller]
1635    #[must_use]
1636    pub fn reqv<T, R>(&mut self, f: impl FnOnce(WriteVar<T>) -> R) -> ReadVar<T>
1637    where
1638        T: Serialize + DeserializeOwned,
1639        R: IntoRequest + 'static,
1640    {
1641        let (read, write) = self.new_var();
1642        self.req::<R>(f(write));
1643        read
1644    }
1645
1646    /// Set multiple requests on a particular node.
1647    pub fn requests<N>(&mut self, reqs: impl IntoIterator<Item = N::Request>)
1648    where
1649        N: FlowNodeBase + 'static,
1650    {
1651        let mut backend = self.backend.borrow_mut();
1652        for req in reqs.into_iter() {
1653            backend.on_request(
1654                NodeHandle::from_type::<N>(),
1655                serde_json::to_vec(&req).map(Into::into).map_err(Into::into),
1656            );
1657        }
1658    }
1659
1660    /// Allocate a new flowey Var, returning two handles: one for reading the
1661    /// value, and another for writing the value.
1662    #[track_caller]
1663    #[must_use]
1664    pub fn new_var<T>(&self) -> (ReadVar<T>, WriteVar<T>)
1665    where
1666        T: Serialize + DeserializeOwned,
1667    {
1668        self.new_prefixed_var("")
1669    }
1670
1671    #[track_caller]
1672    #[must_use]
1673    fn new_prefixed_var<T>(&self, prefix: &'static str) -> (ReadVar<T>, WriteVar<T>)
1674    where
1675        T: Serialize + DeserializeOwned,
1676    {
1677        // normalize call path to ensure determinism between windows and linux
1678        //
1679        // Only the source file is kept, not line/column: `{modpath}:{ordinal}`
1680        // already uniquely identifies the var, so including line/column would
1681        // needlessly churn every generated pipeline whenever unrelated edits
1682        // shift line numbers.
1683        let caller = std::panic::Location::caller().file().replace('\\', "/");
1684
1685        // until we have a proper way to "split" debug info related to vars, we
1686        // kinda just lump it in with the var name itself.
1687        //
1688        // HACK: to work around cases where - depending on what the
1689        // current-working-dir is when incoking flowey - the returned
1690        // caller.file() path may leak the full path of the file (as opposed to
1691        // the relative path), resulting in inconsistencies between build
1692        // environments.
1693        //
1694        // For expediency, and to preserve some semblance of useful error
1695        // messages, we decided to play some sketchy games with the resulting
1696        // string to only preserve the _consistent_ bit of the path for a human
1697        // to use as reference.
1698        //
1699        // This is not ideal in the slightest, but it works OK for now
1700        let caller = caller
1701            .split_once("flowey/")
1702            .expect("due to a known limitation with flowey, all flowey code must have an ancestor dir called 'flowey/' somewhere in its full path")
1703            .1;
1704
1705        let colon = if prefix.is_empty() { "" } else { ":" };
1706        let ordinal = self.backend.borrow_mut().on_new_var();
1707        let backing_var = format!("{prefix}{colon}{ordinal}:{caller}");
1708
1709        (
1710            ReadVar {
1711                backing_var: ReadVarBacking::RuntimeVar {
1712                    var: backing_var.clone(),
1713                    is_side_effect: false,
1714                },
1715                _kind: std::marker::PhantomData,
1716            },
1717            WriteVar {
1718                backing_var,
1719                is_side_effect: false,
1720                _kind: std::marker::PhantomData,
1721            },
1722        )
1723    }
1724
1725    /// Allocate special [`SideEffect`] var which can be used to schedule a
1726    /// "post-job" step associated with some existing step.
1727    ///
1728    /// This "post-job" step will then only run after all other regular steps
1729    /// have run (i.e: steps required to complete any top-level objectives
1730    /// passed in via [`crate::pipeline::PipelineJob::dep_on`]). This makes it
1731    /// useful for implementing various "cleanup" or "finalize" tasks.
1732    ///
1733    /// e.g: the Cache node uses this to upload the contents of a cache
1734    /// directory at the end of a Job.
1735    #[track_caller]
1736    #[must_use]
1737    pub fn new_post_job_side_effect(&self) -> (ReadVar<SideEffect>, WriteVar<SideEffect>) {
1738        self.new_prefixed_var("post_job")
1739    }
1740
1741    /// Return a flowey Var pointing to a **node-specific** directory which
1742    /// will be persisted between runs, if such a directory is available.
1743    ///
1744    /// WARNING: this method is _very likely_ to return None when running on CI
1745    /// machines, as most CI agents are wiped between jobs!
1746    ///
1747    /// As such, it is NOT recommended that node authors reach for this method
1748    /// directly, and instead use abstractions such as the
1749    /// `flowey_lib_common::cache` Node, which implements node-level persistence
1750    /// in a way that works _regardless_ if a persistent_dir is available (e.g:
1751    /// by falling back to uploading / downloading artifacts to a "cache store"
1752    /// on platforms like ADO or Github Actions).
1753    #[track_caller]
1754    #[must_use]
1755    pub fn persistent_dir(&mut self) -> Option<ReadVar<PathBuf>> {
1756        let path: ReadVar<PathBuf> = ReadVar {
1757            backing_var: ReadVarBacking::RuntimeVar {
1758                var: self.backend.borrow_mut().persistent_dir_path_var()?,
1759                is_side_effect: false,
1760            },
1761            _kind: std::marker::PhantomData,
1762        };
1763
1764        let folder_name = self
1765            .backend
1766            .borrow_mut()
1767            .current_node()
1768            .modpath()
1769            .replace("::", "__");
1770
1771        Some(
1772            self.emit_rust_stepv("🌼 Create persistent store dir", |ctx| {
1773                let path = path.claim(ctx);
1774                |rt| {
1775                    let dir = rt.read(path).join(folder_name);
1776                    fs_err::create_dir_all(&dir)?;
1777                    Ok(dir)
1778                }
1779            }),
1780        )
1781    }
1782
1783    /// Check to see if a persistent dir is available, without yet creating it.
1784    pub fn supports_persistent_dir(&mut self) -> bool {
1785        self.backend
1786            .borrow_mut()
1787            .persistent_dir_path_var()
1788            .is_some()
1789    }
1790}
1791
1792// FUTURE: explore using type-erased serde here, instead of relying on
1793// `serde_json` in `flowey_core`.
1794pub trait RuntimeVarDb {
1795    fn get_var(&mut self, var_name: &str) -> (Vec<u8>, bool) {
1796        self.try_get_var(var_name)
1797            .unwrap_or_else(|| panic!("db is missing var {}", var_name))
1798    }
1799
1800    fn try_get_var(&mut self, var_name: &str) -> Option<(Vec<u8>, bool)>;
1801    fn set_var(&mut self, var_name: &str, is_secret: bool, value: Vec<u8>);
1802}
1803
1804impl RuntimeVarDb for Box<dyn RuntimeVarDb> {
1805    fn try_get_var(&mut self, var_name: &str) -> Option<(Vec<u8>, bool)> {
1806        (**self).try_get_var(var_name)
1807    }
1808
1809    fn set_var(&mut self, var_name: &str, is_secret: bool, value: Vec<u8>) {
1810        (**self).set_var(var_name, is_secret, value)
1811    }
1812}
1813
1814pub mod steps {
1815    pub mod ado {
1816        use crate::node::ClaimedReadVar;
1817        use crate::node::ClaimedWriteVar;
1818        use crate::node::ReadVarBacking;
1819        use serde::Deserialize;
1820        use serde::Serialize;
1821        use std::borrow::Cow;
1822
1823        /// An ADO repository declared as a resource in the top-level pipeline.
1824        ///
1825        /// Created via [`crate::pipeline::Pipeline::ado_add_resources_repository`].
1826        ///
1827        /// Consumed via [`AdoStepServices::resolve_repository_id`].
1828        #[derive(Debug, Clone, Serialize, Deserialize)]
1829        pub struct AdoResourcesRepositoryId {
1830            pub(crate) repo_id: String,
1831        }
1832
1833        impl AdoResourcesRepositoryId {
1834            /// Create a `AdoResourcesRepositoryId` corresponding to `self`
1835            /// (i.e: the repo which stores the current pipeline).
1836            ///
1837            /// This is safe to do from any context, as the `self` resource will
1838            /// _always_ be available.
1839            pub fn new_self() -> Self {
1840                Self {
1841                    repo_id: "self".into(),
1842                }
1843            }
1844
1845            /// (dangerous) get the raw ID associated with this resource.
1846            ///
1847            /// It is highly recommended to avoid losing type-safety, and
1848            /// sticking to [`AdoStepServices::resolve_repository_id`].in order
1849            /// to resolve this type to a String.
1850            pub fn dangerous_get_raw_id(&self) -> &str {
1851                &self.repo_id
1852            }
1853
1854            /// (dangerous) create a new ID out of thin air.
1855            ///
1856            /// It is highly recommended to avoid losing type-safety, and
1857            /// sticking to [`AdoStepServices::resolve_repository_id`].in order
1858            /// to resolve this type to a String.
1859            pub fn dangerous_new(repo_id: &str) -> Self {
1860                Self {
1861                    repo_id: repo_id.into(),
1862                }
1863            }
1864        }
1865
1866        /// Handle to an ADO variable.
1867        ///
1868        /// Includes a (non-exhaustive) list of associated constants
1869        /// corresponding to global ADO vars which are _always_ available.
1870        #[derive(Clone, Debug, Serialize, Deserialize)]
1871        pub struct AdoRuntimeVar {
1872            is_secret: bool,
1873            ado_var: Cow<'static, str>,
1874        }
1875
1876        impl AdoRuntimeVar {
1877            /// `build.SourceBranch`
1878            ///
1879            /// NOTE: Includes the full branch ref (ex: `refs/heads/main`) so
1880            /// unlike `build.SourceBranchName`, a branch like `user/foo/bar`
1881            /// won't be stripped to just `bar`
1882            pub const BUILD_SOURCE_BRANCH: AdoRuntimeVar = AdoRuntimeVar::new("build.SourceBranch");
1883
1884            /// `build.BuildNumber`
1885            pub const BUILD_BUILD_NUMBER: AdoRuntimeVar = AdoRuntimeVar::new("build.BuildNumber");
1886
1887            /// `Build.BuildId`
1888            pub const BUILD_BUILD_ID: AdoRuntimeVar = AdoRuntimeVar::new("Build.BuildId");
1889
1890            /// `System.CollectionUri`
1891            pub const SYSTEM_COLLECTION_URI: AdoRuntimeVar =
1892                AdoRuntimeVar::new("System.CollectionUri");
1893
1894            /// `System.TeamProjectId`
1895            pub const SYSTEM_TEAM_PROJECT_ID: AdoRuntimeVar =
1896                AdoRuntimeVar::new("System.TeamProjectId");
1897
1898            /// `System.AccessToken`
1899            pub const SYSTEM_ACCESS_TOKEN: AdoRuntimeVar =
1900                AdoRuntimeVar::new_secret("System.AccessToken");
1901
1902            /// `System.System.JobAttempt`
1903            pub const SYSTEM_JOB_ATTEMPT: AdoRuntimeVar =
1904                AdoRuntimeVar::new_secret("System.JobAttempt");
1905
1906            /// `Pipeline.Workspace`
1907            pub const PIPELINE_WORKSPACE: AdoRuntimeVar = AdoRuntimeVar::new("Pipeline.Workspace");
1908        }
1909
1910        impl AdoRuntimeVar {
1911            const fn new(s: &'static str) -> Self {
1912                Self {
1913                    is_secret: false,
1914                    ado_var: Cow::Borrowed(s),
1915                }
1916            }
1917
1918            const fn new_secret(s: &'static str) -> Self {
1919                Self {
1920                    is_secret: true,
1921                    ado_var: Cow::Borrowed(s),
1922                }
1923            }
1924
1925            /// Check if the ADO var is tagged as being a secret
1926            pub fn is_secret(&self) -> bool {
1927                self.is_secret
1928            }
1929
1930            /// Get the raw underlying ADO variable name
1931            pub fn as_raw_var_name(&self) -> String {
1932                self.ado_var.as_ref().into()
1933            }
1934
1935            /// Get a handle to an ADO runtime variable corresponding to a
1936            /// global ADO variable with the given name.
1937            ///
1938            /// This method should be used rarely and with great care!
1939            ///
1940            /// ADO variables are global, and sidestep the type-safe data flow
1941            /// between flowey nodes entirely!
1942            pub fn dangerous_from_global(ado_var_name: impl AsRef<str>, is_secret: bool) -> Self {
1943                Self {
1944                    is_secret,
1945                    ado_var: ado_var_name.as_ref().to_owned().into(),
1946                }
1947            }
1948        }
1949
1950        pub fn new_ado_step_services(
1951            fresh_ado_var: &mut dyn FnMut() -> String,
1952        ) -> AdoStepServices<'_> {
1953            AdoStepServices {
1954                fresh_ado_var,
1955                ado_to_rust: Vec::new(),
1956                rust_to_ado: Vec::new(),
1957            }
1958        }
1959
1960        pub struct CompletedAdoStepServices {
1961            pub ado_to_rust: Vec<(String, String, bool)>,
1962            pub rust_to_ado: Vec<(String, String)>,
1963        }
1964
1965        impl CompletedAdoStepServices {
1966            pub fn from_ado_step_services(access: AdoStepServices<'_>) -> Self {
1967                let AdoStepServices {
1968                    fresh_ado_var: _,
1969                    ado_to_rust,
1970                    rust_to_ado,
1971                } = access;
1972
1973                Self {
1974                    ado_to_rust,
1975                    rust_to_ado,
1976                }
1977            }
1978        }
1979
1980        pub struct AdoStepServices<'a> {
1981            fresh_ado_var: &'a mut dyn FnMut() -> String,
1982            ado_to_rust: Vec<(String, String, bool)>,
1983            rust_to_ado: Vec<(String, String)>,
1984        }
1985
1986        impl AdoStepServices<'_> {
1987            /// Return the raw string identifier for the given
1988            /// [`AdoResourcesRepositoryId`].
1989            pub fn resolve_repository_id(&self, repo_id: AdoResourcesRepositoryId) -> String {
1990                repo_id.repo_id
1991            }
1992
1993            /// Set the specified flowey Var using the value of the given ADO var.
1994            // TODO: is there a good way to allow auto-casting the ADO var back
1995            // to a WriteVar<T>, instead of just a String? It's complicated by
1996            // the fact that the ADO var to flowey bridge is handled by the ADO
1997            // backend, which itself needs to know type info...
1998            pub fn set_var(&mut self, var: ClaimedWriteVar<String>, from_ado_var: AdoRuntimeVar) {
1999                self.ado_to_rust.push((
2000                    from_ado_var.ado_var.into(),
2001                    var.backing_var,
2002                    from_ado_var.is_secret,
2003                ))
2004            }
2005
2006            /// Get the value of a flowey Var as a ADO runtime variable.
2007            pub fn get_var(&mut self, var: ClaimedReadVar<String>) -> AdoRuntimeVar {
2008                let backing_var = if let ReadVarBacking::RuntimeVar {
2009                    var,
2010                    is_side_effect,
2011                } = &var.backing_var
2012                {
2013                    assert!(!is_side_effect);
2014                    var
2015                } else {
2016                    todo!("support inline ado read vars")
2017                };
2018
2019                let new_ado_var_name = (self.fresh_ado_var)();
2020
2021                self.rust_to_ado
2022                    .push((backing_var.clone(), new_ado_var_name.clone()));
2023                AdoRuntimeVar::dangerous_from_global(new_ado_var_name, false)
2024            }
2025        }
2026    }
2027
2028    pub mod github {
2029        use crate::node::ClaimVar;
2030        use crate::node::NodeCtx;
2031        use crate::node::ReadVar;
2032        use crate::node::ReadVarBacking;
2033        use crate::node::SideEffect;
2034        use crate::node::StepCtx;
2035        use crate::node::VarClaimed;
2036        use crate::node::VarNotClaimed;
2037        use crate::node::WriteVar;
2038        use std::collections::BTreeMap;
2039
2040        pub struct GhStepBuilder {
2041            display_name: String,
2042            cond: Option<ReadVar<bool>>,
2043            uses: String,
2044            with: Option<BTreeMap<String, GhParam>>,
2045            outputs: BTreeMap<String, Vec<WriteVar<String>>>,
2046            run_after: Vec<ReadVar<SideEffect>>,
2047            permissions: BTreeMap<GhPermission, GhPermissionValue>,
2048        }
2049
2050        impl GhStepBuilder {
2051            /// Creates a new GitHub step builder, with the given display name and
2052            /// action to use. For example, the following code generates the following yaml:
2053            ///
2054            /// ```ignore
2055            /// GhStepBuilder::new("Check out repository code", "actions/checkout@v6").finish()
2056            /// ```
2057            ///
2058            /// ```ignore
2059            /// - name: Check out repository code
2060            ///   uses: actions/checkout@v6
2061            /// ```
2062            ///
2063            /// For more information on the yaml syntax for the `name` and `uses` parameters,
2064            /// see <https://docs.github.com/en/actions/writing-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsname>
2065            pub fn new(display_name: impl AsRef<str>, uses: impl AsRef<str>) -> Self {
2066                Self {
2067                    display_name: display_name.as_ref().into(),
2068                    cond: None,
2069                    uses: uses.as_ref().into(),
2070                    with: None,
2071                    outputs: BTreeMap::new(),
2072                    run_after: Vec::new(),
2073                    permissions: BTreeMap::new(),
2074                }
2075            }
2076
2077            /// Adds a condition [`ReadVar<bool>`] to the step,
2078            /// such that the step only executes if the condition is true.
2079            /// This is equivalent to using an `if` conditional in the yaml.
2080            ///
2081            /// For more information on the yaml syntax for `if` conditionals, see
2082            /// <https://docs.github.com/en/actions/writing-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsname>
2083            pub fn condition(mut self, cond: ReadVar<bool>) -> Self {
2084                self.cond = Some(cond);
2085                self
2086            }
2087
2088            /// Adds a parameter to the step, specified as a key-value pair corresponding
2089            /// to the param name and value. For example the following code generates the following yaml:
2090            ///
2091            /// ```rust,ignore
2092            /// let (client_id, write_client_id) = ctx.new_var();
2093            /// let (tenant_id, write_tenant_id) = ctx.new_var();
2094            /// let (subscription_id, write_subscription_id) = ctx.new_var();
2095            /// // ... insert rust step writing to each of those secrets ...
2096            /// GhStepBuilder::new("Azure Login", "Azure/login@v2")
2097            ///               .with("client-id", client_id)
2098            ///               .with("tenant-id", tenant_id)
2099            ///               .with("subscription-id", subscription_id)
2100            /// ```
2101            ///
2102            /// ```text
2103            /// - name: Azure Login
2104            ///   uses: Azure/login@v2
2105            ///   with:
2106            ///     client-id: ${{ env.floweyvar1 }} // Assuming the backend wrote client_id to floweyvar1
2107            ///     tenant-id: ${{ env.floweyvar2 }} // Assuming the backend wrote tenant-id to floweyvar2
2108            ///     subscription-id: ${{ env.floweyvar3 }} // Assuming the backend wrote subscription-id to floweyvar3
2109            /// ```
2110            ///
2111            /// For more information on the yaml syntax for the `with` parameters,
2112            /// see <https://docs.github.com/en/actions/writing-workflows/workflow-syntax-for-github-actions#jobsjob_idstepswith>
2113            pub fn with(mut self, k: impl AsRef<str>, v: impl Into<GhParam>) -> Self {
2114                self.with.get_or_insert_with(BTreeMap::new);
2115                if let Some(with) = &mut self.with {
2116                    with.insert(k.as_ref().to_string(), v.into());
2117                }
2118                self
2119            }
2120
2121            /// Specifies an output to read from the step, specified as a key-value pair
2122            /// corresponding to the output name and the flowey var to write the output to.
2123            ///
2124            /// This is equivalent to writing into `v` the output of a step in the yaml using:
2125            /// `${{ steps.<backend-assigned-step-id>.outputs.<k> }}`
2126            ///
2127            /// For more information on step outputs, see
2128            /// <https://docs.github.com/en/actions/sharing-automations/creating-actions/metadata-syntax-for-github-actions#outputs-for-composite-actions>
2129            pub fn output(mut self, k: impl AsRef<str>, v: WriteVar<String>) -> Self {
2130                self.outputs
2131                    .entry(k.as_ref().to_string())
2132                    .or_default()
2133                    .push(v);
2134                self
2135            }
2136
2137            /// Specifies a side-effect that must be resolved before this step can run.
2138            pub fn run_after(mut self, side_effect: ReadVar<SideEffect>) -> Self {
2139                self.run_after.push(side_effect);
2140                self
2141            }
2142
2143            /// Declare that this step requires a certain GITHUB_TOKEN permission in order to run.
2144            ///
2145            /// For more info about Github Actions permissions, see [`gh_grant_permissions`](crate::pipeline::PipelineJob::gh_grant_permissions) and
2146            /// <https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/assigning-permissions-to-jobs>
2147            pub fn requires_permission(
2148                mut self,
2149                perm: GhPermission,
2150                value: GhPermissionValue,
2151            ) -> Self {
2152                self.permissions.insert(perm, value);
2153                self
2154            }
2155
2156            /// Finish building the step, emitting it to the backend and returning a side-effect.
2157            #[track_caller]
2158            pub fn finish(self, ctx: &mut NodeCtx<'_>) -> ReadVar<SideEffect> {
2159                let (side_effect, claim_side_effect) = ctx.new_prefixed_var("auto_se");
2160                ctx.backend
2161                    .borrow_mut()
2162                    .on_claimed_runtime_var(&claim_side_effect.backing_var, false);
2163
2164                ctx.emit_gh_step_inner(
2165                    self.display_name,
2166                    self.cond,
2167                    self.uses,
2168                    self.with,
2169                    self.outputs,
2170                    self.run_after,
2171                    self.permissions,
2172                );
2173
2174                side_effect
2175            }
2176        }
2177
2178        #[derive(Clone, Debug)]
2179        pub enum GhParam<C = VarNotClaimed> {
2180            Static(String),
2181            FloweyVar(ReadVar<String, C>),
2182        }
2183
2184        impl From<String> for GhParam {
2185            fn from(param: String) -> GhParam {
2186                GhParam::Static(param)
2187            }
2188        }
2189
2190        impl From<&str> for GhParam {
2191            fn from(param: &str) -> GhParam {
2192                GhParam::Static(param.to_string())
2193            }
2194        }
2195
2196        impl From<ReadVar<String>> for GhParam {
2197            fn from(param: ReadVar<String>) -> GhParam {
2198                GhParam::FloweyVar(param)
2199            }
2200        }
2201
2202        pub type ClaimedGhParam = GhParam<VarClaimed>;
2203
2204        impl ClaimVar for GhParam {
2205            type Claimed = ClaimedGhParam;
2206
2207            fn claim(self, ctx: &mut StepCtx<'_>) -> ClaimedGhParam {
2208                match self {
2209                    GhParam::Static(s) => ClaimedGhParam::Static(s),
2210                    GhParam::FloweyVar(var) => match &var.backing_var {
2211                        ReadVarBacking::RuntimeVar { is_side_effect, .. } => {
2212                            assert!(!is_side_effect);
2213                            ClaimedGhParam::FloweyVar(var.claim(ctx))
2214                        }
2215                        ReadVarBacking::Inline(var) => ClaimedGhParam::Static(var.clone()),
2216                    },
2217                }
2218            }
2219        }
2220
2221        /// The assigned permission value for a scope.
2222        ///
2223        /// For more details on how these values affect a particular scope, refer to:
2224        /// <https://docs.github.com/en/actions/using-jobs/assigning-permissions-to-jobs>
2225        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd)]
2226        pub enum GhPermissionValue {
2227            None = 0,
2228            Read = 1,
2229            Write = 2,
2230        }
2231
2232        /// Refers to the scope of a permission granted to the GITHUB_TOKEN
2233        /// for a job.
2234        ///
2235        /// For more details on each scope, refer to:
2236        /// <https://docs.github.com/en/actions/using-jobs/assigning-permissions-to-jobs>
2237        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
2238        pub enum GhPermission {
2239            Actions,
2240            ArtifactMetadata,
2241            Attestations,
2242            Checks,
2243            Contents,
2244            Deployments,
2245            Discussions,
2246            IdToken,
2247            Issues,
2248            Packages,
2249            Pages,
2250            PullRequests,
2251            RepositoryProjects,
2252            SecurityEvents,
2253            Statuses,
2254        }
2255    }
2256
2257    pub mod rust {
2258        use crate::node::ClaimedWriteVar;
2259        use crate::node::FlowArch;
2260        use crate::node::FlowBackend;
2261        use crate::node::FlowPlatform;
2262        use crate::node::ReadVarValue;
2263        use crate::node::RuntimeVarDb;
2264        use crate::shell::FloweyShell;
2265        use serde::Serialize;
2266        use serde::de::DeserializeOwned;
2267
2268        pub fn new_rust_runtime_services(
2269            runtime_var_db: &mut dyn RuntimeVarDb,
2270            backend: FlowBackend,
2271            platform: FlowPlatform,
2272            arch: FlowArch,
2273        ) -> anyhow::Result<RustRuntimeServices<'_>> {
2274            Ok(RustRuntimeServices {
2275                runtime_var_db,
2276                backend,
2277                platform,
2278                arch,
2279                has_read_secret: false,
2280                sh: FloweyShell::new()?,
2281            })
2282        }
2283
2284        pub struct RustRuntimeServices<'a> {
2285            runtime_var_db: &'a mut dyn RuntimeVarDb,
2286            backend: FlowBackend,
2287            platform: FlowPlatform,
2288            arch: FlowArch,
2289            has_read_secret: bool,
2290            /// A pre-initialized [`FloweyShell`] for running commands.
2291            ///
2292            /// This wraps [`xshell::Shell`] and supports transparent command
2293            /// wrapping. Implements [`Deref<Target = xshell::Shell>`](std::ops::Deref)
2294            /// so methods like `change_dir()`, `set_var()`, etc. work directly.
2295            pub sh: FloweyShell,
2296        }
2297
2298        impl RustRuntimeServices<'_> {
2299            /// What backend the flow is being running on (e.g: locally, ADO,
2300            /// GitHub, etc...)
2301            pub fn backend(&self) -> FlowBackend {
2302                self.backend
2303            }
2304
2305            /// What platform the flow is being running on (e.g: windows, linux,
2306            /// etc...).
2307            pub fn platform(&self) -> FlowPlatform {
2308                self.platform
2309            }
2310
2311            /// What arch the flow is being running on (X86_64 or Aarch64)
2312            pub fn arch(&self) -> FlowArch {
2313                self.arch
2314            }
2315
2316            /// Write a value.
2317            ///
2318            /// If this step has already read a secret value, then this will be
2319            /// written as a secret value, as a conservative estimate to avoid
2320            /// leaking secrets. Use [`write_secret`](Self::write_secret) or
2321            /// [`write_not_secret`](Self::write_not_secret) to override this
2322            /// behavior.
2323            pub fn write<T>(&mut self, var: ClaimedWriteVar<T>, val: &T)
2324            where
2325                T: Serialize + DeserializeOwned,
2326            {
2327                self.write_maybe_secret(var, val, self.has_read_secret)
2328            }
2329
2330            /// Write a secret value, such as a key or token.
2331            ///
2332            /// Flowey will avoid logging this value, and if the value is
2333            /// converted to a CI environment variable, the CI system will be
2334            /// told not to print the value either.
2335            pub fn write_secret<T>(&mut self, var: ClaimedWriteVar<T>, val: &T)
2336            where
2337                T: Serialize + DeserializeOwned,
2338            {
2339                self.write_maybe_secret(var, val, true)
2340            }
2341
2342            /// Write a value that is not secret, even if this step has already
2343            /// read secret values.
2344            ///
2345            /// Usually [`write`](Self::write) is preferred--use this only when
2346            /// your step reads secret values and you explicitly want to write a
2347            /// non-secret value.
2348            pub fn write_not_secret<T>(&mut self, var: ClaimedWriteVar<T>, val: &T)
2349            where
2350                T: Serialize + DeserializeOwned,
2351            {
2352                self.write_maybe_secret(var, val, false)
2353            }
2354
2355            fn write_maybe_secret<T>(&mut self, var: ClaimedWriteVar<T>, val: &T, is_secret: bool)
2356            where
2357                T: Serialize + DeserializeOwned,
2358            {
2359                let val = if var.is_side_effect {
2360                    b"null".to_vec()
2361                } else {
2362                    serde_json::to_vec(val).expect("improve this error path")
2363                };
2364                self.runtime_var_db
2365                    .set_var(&var.backing_var, is_secret, val);
2366            }
2367
2368            pub fn write_all<T>(
2369                &mut self,
2370                vars: impl IntoIterator<Item = ClaimedWriteVar<T>>,
2371                val: &T,
2372            ) where
2373                T: Serialize + DeserializeOwned,
2374            {
2375                for var in vars {
2376                    self.write(var, val)
2377                }
2378            }
2379
2380            pub fn read<T: ReadVarValue>(&mut self, var: T) -> T::Value {
2381                var.read_value(self)
2382            }
2383
2384            pub(crate) fn get_var(&mut self, var: &str, is_side_effect: bool) -> Vec<u8> {
2385                let (v, is_secret) = self.runtime_var_db.get_var(var);
2386                self.has_read_secret |= is_secret && !is_side_effect;
2387                v
2388            }
2389
2390            /// DANGEROUS: Set the value of _Global_ Environment Variable (GitHub Actions only).
2391            ///
2392            /// It is up to the caller to ensure that the variable does not get
2393            /// unintentionally overwritten or used.
2394            ///
2395            /// This method should be used rarely and with great care!
2396            pub fn dangerous_gh_set_global_env_var(
2397                &mut self,
2398                var: String,
2399                gh_env_var: String,
2400            ) -> anyhow::Result<()> {
2401                if !matches!(self.backend, FlowBackend::Github) {
2402                    return Err(anyhow::anyhow!(
2403                        "dangerous_set_gh_env_var can only be used on GitHub Actions"
2404                    ));
2405                }
2406
2407                let gh_env_file_path = std::env::var("GITHUB_ENV")?;
2408                let mut gh_env_file = fs_err::OpenOptions::new()
2409                    .append(true)
2410                    .open(gh_env_file_path)?;
2411                let gh_env_var_assignment = format!(
2412                    r#"{}<<EOF
2413{}
2414EOF
2415"#,
2416                    gh_env_var, var
2417                );
2418                std::io::Write::write_all(&mut gh_env_file, gh_env_var_assignment.as_bytes())?;
2419
2420                Ok(())
2421            }
2422        }
2423    }
2424}
2425
2426/// The base underlying implementation of all FlowNode variants.
2427///
2428/// Do not implement this directly! Use the `new_flow_node!` family of macros
2429/// instead!
2430pub trait FlowNodeBase {
2431    type Request: Serialize + DeserializeOwned;
2432
2433    fn imports(&mut self, ctx: &mut ImportCtx<'_>);
2434    fn emit(
2435        &mut self,
2436        config_bytes: Vec<Box<[u8]>>,
2437        requests: Vec<Self::Request>,
2438        ctx: &mut NodeCtx<'_>,
2439    ) -> anyhow::Result<()>;
2440
2441    /// A noop method that all human-written impls of `FlowNodeBase` are
2442    /// required to implement.
2443    ///
2444    /// By implementing this method, you're stating that you "know what you're
2445    /// doing" by having this manual impl.
2446    fn i_know_what_im_doing_with_this_manual_impl(&mut self);
2447}
2448
2449pub mod erased {
2450    use crate::node::FlowNodeBase;
2451    use crate::node::NodeCtx;
2452    use crate::node::user_facing::*;
2453
2454    pub struct ErasedNode<N: FlowNodeBase>(pub N);
2455
2456    impl<N: FlowNodeBase> ErasedNode<N> {
2457        pub fn from_node(node: N) -> Self {
2458            Self(node)
2459        }
2460    }
2461
2462    impl<N> FlowNodeBase for ErasedNode<N>
2463    where
2464        N: FlowNodeBase,
2465    {
2466        // FIXME: this should be using type-erased serde
2467        type Request = Box<[u8]>;
2468
2469        fn imports(&mut self, ctx: &mut ImportCtx<'_>) {
2470            self.0.imports(ctx)
2471        }
2472
2473        fn emit(
2474            &mut self,
2475            config_bytes: Vec<Box<[u8]>>,
2476            requests: Vec<Box<[u8]>>,
2477            ctx: &mut NodeCtx<'_>,
2478        ) -> anyhow::Result<()> {
2479            let mut converted_requests = Vec::new();
2480            for req in requests {
2481                converted_requests.push(serde_json::from_slice(&req)?)
2482            }
2483
2484            self.0.emit(config_bytes, converted_requests, ctx)
2485        }
2486
2487        fn i_know_what_im_doing_with_this_manual_impl(&mut self) {}
2488    }
2489}
2490
2491/// Cheap handle to a registered [`FlowNode`]
2492#[derive(Clone, Copy, PartialEq, Eq, Hash)]
2493pub struct NodeHandle(std::any::TypeId);
2494
2495impl Ord for NodeHandle {
2496    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
2497        self.modpath().cmp(other.modpath())
2498    }
2499}
2500
2501impl PartialOrd for NodeHandle {
2502    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2503        Some(self.cmp(other))
2504    }
2505}
2506
2507impl std::fmt::Debug for NodeHandle {
2508    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2509        std::fmt::Debug::fmt(&self.try_modpath(), f)
2510    }
2511}
2512
2513impl NodeHandle {
2514    pub const fn from_type<N: FlowNodeBase + 'static>() -> NodeHandle {
2515        NodeHandle(std::any::TypeId::of::<N>())
2516    }
2517
2518    pub fn from_modpath(modpath: &str) -> NodeHandle {
2519        node_luts::erased_node_by_modpath().get(modpath).unwrap().0
2520    }
2521
2522    pub fn try_from_modpath(modpath: &str) -> Option<NodeHandle> {
2523        node_luts::erased_node_by_modpath()
2524            .get(modpath)
2525            .map(|(s, _)| *s)
2526    }
2527
2528    pub fn new_erased_node(&self) -> Box<dyn FlowNodeBase<Request = Box<[u8]>>> {
2529        let ctor = node_luts::erased_node_by_typeid().get(self).unwrap();
2530        ctor()
2531    }
2532
2533    pub fn modpath(&self) -> &'static str {
2534        node_luts::modpath_by_node_typeid().get(self).unwrap()
2535    }
2536
2537    pub fn try_modpath(&self) -> Option<&'static str> {
2538        node_luts::modpath_by_node_typeid().get(self).cloned()
2539    }
2540
2541    /// Return a dummy NodeHandle, which will panic if `new_erased_node` is ever
2542    /// called on it.
2543    pub const fn dummy() -> NodeHandle {
2544        NodeHandle(std::any::TypeId::of::<()>())
2545    }
2546}
2547
2548pub fn list_all_registered_nodes() -> impl Iterator<Item = NodeHandle> {
2549    node_luts::modpath_by_node_typeid().keys().cloned()
2550}
2551
2552// Encapsulate these look up tables in their own module to limit the scope of
2553// the HashMap import.
2554//
2555// In general, using HashMap in flowey is a recipe for disaster, given that
2556// iterating through the hash-map will result in non-deterministic orderings,
2557// which can cause annoying ordering churn.
2558//
2559// That said, in this case, it's OK since the code using these LUTs won't ever
2560// iterate through the map.
2561//
2562// Why is the HashMap even necessary vs. a BTreeMap?
2563//
2564// Well... NodeHandle's `Ord` impl does a `modpath` comparison instead of a
2565// TypeId comparison, since TypeId will vary between compilations.
2566mod node_luts {
2567    use super::FlowNodeBase;
2568    use super::NodeHandle;
2569    use std::collections::HashMap;
2570    use std::sync::OnceLock;
2571
2572    pub(super) fn modpath_by_node_typeid() -> &'static HashMap<NodeHandle, &'static str> {
2573        static TYPEID_TO_MODPATH: OnceLock<HashMap<NodeHandle, &'static str>> = OnceLock::new();
2574
2575        TYPEID_TO_MODPATH.get_or_init(|| {
2576            let mut lookup = HashMap::new();
2577            for crate::node::private::FlowNodeMeta {
2578                module_path,
2579                ctor: _,
2580                typeid,
2581            } in crate::node::private::FLOW_NODES
2582            {
2583                let existing = lookup.insert(
2584                    NodeHandle(*typeid),
2585                    module_path
2586                        .strip_suffix("::_only_one_call_to_flowey_node_per_module")
2587                        .unwrap(),
2588                );
2589                // if this were to fire for an array where the key is a TypeId...
2590                // something has gone _terribly_ wrong
2591                assert!(existing.is_none())
2592            }
2593
2594            lookup
2595        })
2596    }
2597
2598    pub(super) fn erased_node_by_typeid()
2599    -> &'static HashMap<NodeHandle, fn() -> Box<dyn FlowNodeBase<Request = Box<[u8]>>>> {
2600        static LOOKUP: OnceLock<
2601            HashMap<NodeHandle, fn() -> Box<dyn FlowNodeBase<Request = Box<[u8]>>>>,
2602        > = OnceLock::new();
2603
2604        LOOKUP.get_or_init(|| {
2605            let mut lookup = HashMap::new();
2606            for crate::node::private::FlowNodeMeta {
2607                module_path: _,
2608                ctor,
2609                typeid,
2610            } in crate::node::private::FLOW_NODES
2611            {
2612                let existing = lookup.insert(NodeHandle(*typeid), *ctor);
2613                // if this were to fire for an array where the key is a TypeId...
2614                // something has gone _terribly_ wrong
2615                assert!(existing.is_none())
2616            }
2617
2618            lookup
2619        })
2620    }
2621
2622    pub(super) fn erased_node_by_modpath() -> &'static HashMap<
2623        &'static str,
2624        (
2625            NodeHandle,
2626            fn() -> Box<dyn FlowNodeBase<Request = Box<[u8]>>>,
2627        ),
2628    > {
2629        static MODPATH_LOOKUP: OnceLock<
2630            HashMap<
2631                &'static str,
2632                (
2633                    NodeHandle,
2634                    fn() -> Box<dyn FlowNodeBase<Request = Box<[u8]>>>,
2635                ),
2636            >,
2637        > = OnceLock::new();
2638
2639        MODPATH_LOOKUP.get_or_init(|| {
2640            let mut lookup = HashMap::new();
2641            for crate::node::private::FlowNodeMeta { module_path, ctor, typeid } in crate::node::private::FLOW_NODES {
2642                let existing = lookup.insert(module_path.strip_suffix("::_only_one_call_to_flowey_node_per_module").unwrap(), (NodeHandle(*typeid), *ctor));
2643                if existing.is_some() {
2644                    panic!("conflicting node registrations at {module_path}! please ensure there is a single node per module!")
2645                }
2646            }
2647            lookup
2648        })
2649    }
2650}
2651
2652#[doc(hidden)]
2653pub mod private {
2654    pub use linkme;
2655
2656    pub struct FlowNodeMeta {
2657        pub module_path: &'static str,
2658        pub ctor: fn() -> Box<dyn super::FlowNodeBase<Request = Box<[u8]>>>,
2659        pub typeid: std::any::TypeId,
2660    }
2661
2662    #[linkme::distributed_slice]
2663    pub static FLOW_NODES: [FlowNodeMeta] = [..];
2664
2665    // UNSAFETY: linkme uses manual link sections, which are unsafe.
2666    #[expect(unsafe_code)]
2667    #[linkme::distributed_slice(FLOW_NODES)]
2668    static DUMMY_FLOW_NODE: FlowNodeMeta = FlowNodeMeta {
2669        module_path: "<dummy>::_only_one_call_to_flowey_node_per_module",
2670        ctor: || unreachable!(),
2671        typeid: std::any::TypeId::of::<()>(),
2672    };
2673}
2674
2675#[doc(hidden)]
2676#[macro_export]
2677macro_rules! new_flow_node_base {
2678    (struct Node) => {
2679        /// (see module-level docs)
2680        #[non_exhaustive]
2681        pub struct Node;
2682
2683        mod _only_one_call_to_flowey_node_per_module {
2684            const _: () = {
2685                use $crate::node::private::linkme;
2686
2687                fn new_erased() -> Box<dyn $crate::node::FlowNodeBase<Request = Box<[u8]>>> {
2688                    Box::new($crate::node::erased::ErasedNode(super::Node))
2689                }
2690
2691                #[linkme::distributed_slice($crate::node::private::FLOW_NODES)]
2692                #[linkme(crate = linkme)]
2693                static FLOW_NODE: $crate::node::private::FlowNodeMeta =
2694                    $crate::node::private::FlowNodeMeta {
2695                        module_path: module_path!(),
2696                        ctor: new_erased,
2697                        typeid: std::any::TypeId::of::<super::Node>(),
2698                    };
2699            };
2700        }
2701    };
2702}
2703
2704/// A reusable unit of automation logic in flowey.
2705///
2706/// FlowNodes process requests, emit steps, and can depend on other nodes. They are
2707/// the building blocks for creating complex automation workflows.
2708///
2709/// # The Node/Request Pattern
2710///
2711/// Every node has an associated **Request** type that defines what the node can do.
2712/// Nodes receive a vector of requests and process them together, allowing for
2713/// aggregation and conflict resolution.
2714///
2715/// # Example: Basic FlowNode Implementation
2716///
2717/// ```rust,ignore
2718/// use flowey_core::node::*;
2719///
2720/// // Define the node
2721/// new_flow_node!(struct Node);
2722///
2723/// // Define requests using the flowey_request! macro
2724/// flowey_request! {
2725///     pub enum Request {
2726///         InstallRust(String),                    // Install specific version
2727///         EnsureInstalled(WriteVar<SideEffect>),  // Ensure it's installed
2728///         GetCargoHome(WriteVar<PathBuf>),        // Get CARGO_HOME path
2729///     }
2730/// }
2731///
2732/// impl FlowNode for Node {
2733///     type Request = Request;
2734///
2735///     fn imports(ctx: &mut ImportCtx<'_>) {
2736///         // Declare node dependencies
2737///         ctx.import::<other_node::Node>();
2738///     }
2739///
2740///     fn emit(requests: Vec<Self::Request>, ctx: &mut NodeCtx<'_>) -> anyhow::Result<()> {
2741///         // 1. Aggregate and validate requests
2742///         let mut version = None;
2743///         let mut ensure_installed = Vec::new();
2744///         let mut get_cargo_home = Vec::new();
2745///
2746///         for req in requests {
2747///             match req {
2748///                 Request::InstallRust(v) => {
2749///                     same_across_all_reqs("version", &mut version, v)?;
2750///                 }
2751///                 Request::EnsureInstalled(var) => ensure_installed.push(var),
2752///                 Request::GetCargoHome(var) => get_cargo_home.push(var),
2753///             }
2754///         }
2755///
2756///         let version = version.ok_or(anyhow::anyhow!("Version not specified"))?;
2757///
2758///         // 2. Emit steps to do the work
2759///         ctx.emit_rust_step("install rust", |ctx| {
2760///             let ensure_installed = ensure_installed.claim(ctx);
2761///             let get_cargo_home = get_cargo_home.claim(ctx);
2762///             move |rt| {
2763///                 // Install rust with the specified version
2764///                 // Write to all the output variables
2765///                 for var in ensure_installed {
2766///                     rt.write(var, &());
2767///                 }
2768///                 for var in get_cargo_home {
2769///                     rt.write(var, &PathBuf::from("/path/to/cargo"));
2770///                 }
2771///                 Ok(())
2772///             }
2773///         });
2774///
2775///         Ok(())
2776///     }
2777/// }
2778/// ```
2779///
2780/// # When to Use FlowNode vs SimpleFlowNode
2781///
2782/// **Use `FlowNode`** when you need to:
2783/// - Aggregate multiple requests and process them together
2784/// - Resolve conflicts between requests
2785/// - Perform complex request validation
2786///
2787/// **Use [`SimpleFlowNode`]** when:
2788/// - Each request can be processed independently
2789/// - No aggregation logic is needed
2790pub trait FlowNode {
2791    /// The request type that defines what operations this node can perform.
2792    ///
2793    /// Use the [`crate::flowey_request!`] macro to define this type.
2794    type Request: Serialize + DeserializeOwned;
2795
2796    /// A list of nodes that this node is capable of taking a dependency on.
2797    ///
2798    /// Attempting to take a dep on a node that wasn't imported via this method
2799    /// will result in an error during flow resolution time.
2800    ///
2801    /// * * *
2802    ///
2803    /// To put it bluntly: This is boilerplate.
2804    ///
2805    /// We (the flowey devs) are thinking about ways to avoid requiring this
2806    /// method, but do not have a good solution at this time.
2807    fn imports(ctx: &mut ImportCtx<'_>);
2808
2809    /// Given a set of incoming `requests`, emit various steps to run, set
2810    /// various dependencies, etc...
2811    fn emit(requests: Vec<Self::Request>, ctx: &mut NodeCtx<'_>) -> anyhow::Result<()>;
2812}
2813
2814#[macro_export]
2815macro_rules! new_flow_node {
2816    (struct Node) => {
2817        $crate::new_flow_node_base!(struct Node);
2818
2819        impl $crate::node::FlowNodeBase for Node
2820        where
2821            Node: FlowNode,
2822        {
2823            type Request = <Node as FlowNode>::Request;
2824
2825            fn imports(&mut self, dep: &mut $crate::node::ImportCtx<'_>) {
2826                <Node as FlowNode>::imports(dep)
2827            }
2828
2829            fn emit(
2830                &mut self,
2831                _config_bytes: Vec<Box<[u8]>>,
2832                requests: Vec<Self::Request>,
2833                ctx: &mut $crate::node::NodeCtx<'_>,
2834            ) -> anyhow::Result<()> {
2835                <Node as FlowNode>::emit(requests, ctx)
2836            }
2837
2838            fn i_know_what_im_doing_with_this_manual_impl(&mut self) {}
2839        }
2840    };
2841}
2842
2843/// A helper trait to streamline implementing [`FlowNode`] instances that only
2844/// ever operate on a single request at a time.
2845///
2846/// In essence, [`SimpleFlowNode`] handles the boilerplate (and rightward-drift)
2847/// of manually writing:
2848///
2849/// ```ignore
2850/// impl FlowNode for Node {
2851///     fn imports(dep: &mut ImportCtx<'_>) { ... }
2852///     fn emit(requests: Vec<Self::Request>, ctx: &mut NodeCtx<'_>) {
2853///         for req in requests {
2854///             Node::process_request(req, ctx)
2855///         }
2856///     }
2857/// }
2858/// ```
2859///
2860/// Nodes which accept a `struct Request` often fall into this pattern, whereas
2861/// nodes which accept a `enum Request` typically require additional logic to
2862/// aggregate / resolve incoming requests.
2863pub trait SimpleFlowNode {
2864    type Request: Serialize + DeserializeOwned;
2865
2866    /// A list of nodes that this node is capable of taking a dependency on.
2867    ///
2868    /// Attempting to take a dep on a node that wasn't imported via this method
2869    /// will result in an error during flow resolution time.
2870    ///
2871    /// * * *
2872    ///
2873    /// To put it bluntly: This is boilerplate.
2874    ///
2875    /// We (the flowey devs) are thinking about ways to avoid requiring this
2876    /// method, but do not have a good solution at this time.
2877    fn imports(ctx: &mut ImportCtx<'_>);
2878
2879    /// Process a single incoming `Self::Request`
2880    fn process_request(request: Self::Request, ctx: &mut NodeCtx<'_>) -> anyhow::Result<()>;
2881}
2882
2883#[macro_export]
2884macro_rules! new_simple_flow_node {
2885    (struct Node) => {
2886        $crate::new_flow_node_base!(struct Node);
2887
2888        impl $crate::node::FlowNodeBase for Node
2889        where
2890            Node: $crate::node::SimpleFlowNode,
2891        {
2892            type Request = <Node as $crate::node::SimpleFlowNode>::Request;
2893
2894            fn imports(&mut self, dep: &mut $crate::node::ImportCtx<'_>) {
2895                <Node as $crate::node::SimpleFlowNode>::imports(dep)
2896            }
2897
2898            fn emit(
2899                &mut self,
2900                _config_bytes: Vec<Box<[u8]>>,
2901                requests: Vec<Self::Request>,
2902                ctx: &mut $crate::node::NodeCtx<'_>,
2903            ) -> anyhow::Result<()> {
2904                for req in requests {
2905                    <Node as $crate::node::SimpleFlowNode>::process_request(req, ctx)?
2906                }
2907
2908                Ok(())
2909            }
2910
2911            fn i_know_what_im_doing_with_this_manual_impl(&mut self) {}
2912        }
2913    };
2914}
2915
2916/// A [`FlowNode`] variant that receives a typed, pre-merged config alongside
2917/// its requests.
2918///
2919/// Use this when a node has "config" values (e.g., version strings, feature
2920/// flags) that must agree across all callers AND are needed to emit outgoing
2921/// requests or steps.
2922///
2923/// The framework merges config from all callers (validating equality) and
2924/// delivers the finalized `Config` to `emit()`. The node never sees raw
2925/// config requests — they are handled by the infrastructure.
2926///
2927/// # Example
2928///
2929/// ```rust,ignore
2930/// flowey_config! {
2931///     pub struct Config {
2932///         pub version: Option<String>,
2933///     }
2934/// }
2935///
2936/// flowey_request! {
2937///     pub enum Request {
2938///         GetAzCopy(WriteVar<PathBuf>),
2939///     }
2940/// }
2941///
2942/// new_flow_node_with_config!(struct Node);
2943///
2944/// impl FlowNodeWithConfig for Node {
2945///     type Request = Request;
2946///     type Config = Config;
2947///
2948///     fn imports(ctx: &mut ImportCtx<'_>) { /* ... */ }
2949///
2950///     fn emit(
2951///         config: Config,
2952///         requests: Vec<Self::Request>,
2953///         ctx: &mut NodeCtx<'_>,
2954///     ) -> anyhow::Result<()> {
2955///         let version = config.version
2956///             .ok_or(anyhow::anyhow!("missing config: version"))?;
2957///         // ...
2958///         Ok(())
2959///     }
2960/// }
2961/// ```
2962pub trait FlowNodeWithConfig {
2963    /// The request type (action requests only — no config variants).
2964    type Request: Serialize + DeserializeOwned;
2965
2966    /// The config type generated by [`flowey_config!`](crate::flowey_config).
2967    ///
2968    /// Scalar fields are typically wrapped in `Option<T>`, and the node decides which
2969    /// options are treated as required vs optional. Configs may also include
2970    /// non-`Option` mergeable fields (for example, maps) that are combined according
2971    /// to the [`ConfigMerge`] implementation.
2972    type Config: ConfigMerge;
2973
2974    /// Declare node dependencies.
2975    fn imports(ctx: &mut ImportCtx<'_>);
2976
2977    /// Process requests with the merged config.
2978    fn emit(
2979        config: Self::Config,
2980        requests: Vec<Self::Request>,
2981        ctx: &mut NodeCtx<'_>,
2982    ) -> anyhow::Result<()>;
2983}
2984
2985#[macro_export]
2986macro_rules! new_flow_node_with_config {
2987    (struct Node) => {
2988        $crate::new_flow_node_base!(struct Node);
2989
2990        impl $crate::node::FlowNodeBase for Node
2991        where
2992            Node: $crate::node::FlowNodeWithConfig,
2993        {
2994            type Request = <Node as $crate::node::FlowNodeWithConfig>::Request;
2995
2996            fn imports(&mut self, dep: &mut $crate::node::ImportCtx<'_>) {
2997                <Node as $crate::node::FlowNodeWithConfig>::imports(dep)
2998            }
2999
3000            fn emit(
3001                &mut self,
3002                config_bytes: Vec<Box<[u8]>>,
3003                requests: Vec<Self::Request>,
3004                ctx: &mut $crate::node::NodeCtx<'_>,
3005            ) -> anyhow::Result<()> {
3006                use $crate::node::ConfigMerge;
3007
3008                type C = <Node as $crate::node::FlowNodeWithConfig>::Config;
3009
3010                let mut merged = <C as Default>::default();
3011                for bytes in config_bytes {
3012                    let partial: C = serde_json::from_slice(&bytes)?;
3013                    merged.merge(partial)?;
3014                }
3015
3016                <Node as $crate::node::FlowNodeWithConfig>::emit(merged, requests, ctx)
3017            }
3018
3019            fn i_know_what_im_doing_with_this_manual_impl(&mut self) {}
3020        }
3021    };
3022}
3023
3024/// A "glue" trait which improves [`NodeCtx::req`] ergonomics, by tying a
3025/// particular `Request` type to its corresponding [`FlowNode`].
3026///
3027/// This trait should be autogenerated via [`flowey_request!`] - do not try to
3028/// implement it manually!
3029///
3030/// [`flowey_request!`]: crate::flowey_request
3031pub trait IntoRequest {
3032    type Node: FlowNodeBase;
3033    fn into_request(self) -> <Self::Node as FlowNodeBase>::Request;
3034
3035    /// By implementing this method manually, you're indicating that you know what you're
3036    /// doing,
3037    #[doc(hidden)]
3038    #[expect(nonstandard_style)]
3039    fn do_not_manually_impl_this_trait__use_the_flowey_request_macro_instead(&mut self);
3040}
3041
3042/// A "glue" trait for routing config to the correct node, analogous to
3043/// [`IntoRequest`].
3044///
3045/// This trait should be autogenerated via the `flowey_config!` macro - do not
3046/// try to implement it manually!
3047pub trait IntoConfig: Serialize {
3048    type Node: FlowNodeBase;
3049
3050    /// By implementing this method manually, you're indicating that you know what you're
3051    /// doing,
3052    #[doc(hidden)]
3053    #[expect(nonstandard_style)]
3054    fn do_not_manually_impl_this_trait__use_the_flowey_config_macro_instead(&mut self);
3055}
3056
3057/// Trait for merging config values. Implemented by the `flowey_config!`
3058/// macro on the generated `Config` type.
3059pub trait ConfigMerge: Serialize + DeserializeOwned + Default {
3060    /// Merge another config into this one. Fields that are already set
3061    /// must agree with the incoming values.
3062    fn merge(&mut self, other: Self) -> anyhow::Result<()>;
3063}
3064
3065/// Trait for merging a single config field. The `flowey_config!` macro calls
3066/// `ConfigField::merge_field` on each field during config merging.
3067///
3068/// Implemented for:
3069/// - `Option<T>`: first setter wins, subsequent must agree (`PartialEq`)
3070/// - `BTreeMap<K, V>`: per-key merge, each key's value must agree
3071pub trait ConfigField {
3072    fn merge_field(&mut self, field_name: &str, other: Self) -> anyhow::Result<()>;
3073}
3074
3075impl<T: PartialEq> ConfigField for Option<T> {
3076    fn merge_field(&mut self, field_name: &str, other: Self) -> anyhow::Result<()> {
3077        if let Some(new) = other {
3078            match self {
3079                None => *self = Some(new),
3080                Some(old) if *old == new => {}
3081                Some(_) => {
3082                    anyhow::bail!("config field `{field_name}` mismatch");
3083                }
3084            }
3085        }
3086        Ok(())
3087    }
3088}
3089
3090impl<K: Ord + std::fmt::Debug, V: PartialEq> ConfigField for BTreeMap<K, V> {
3091    fn merge_field(&mut self, field_name: &str, other: Self) -> anyhow::Result<()> {
3092        for (k, v) in other {
3093            use std::collections::btree_map::Entry;
3094            match self.entry(k) {
3095                Entry::Vacant(e) => {
3096                    e.insert(v);
3097                }
3098                Entry::Occupied(e) if *e.get() == v => {}
3099                Entry::Occupied(e) => {
3100                    anyhow::bail!("config field `{field_name}` mismatch for key {:?}", e.key(),);
3101                }
3102            }
3103        }
3104        Ok(())
3105    }
3106}
3107
3108#[doc(hidden)]
3109#[macro_export]
3110macro_rules! __flowey_request_inner {
3111    //
3112    // @emit_struct: emit structs for each variant of the request enum
3113    //
3114    (@emit_struct [$req:ident]
3115        $(#[$a:meta])*
3116        $variant:ident($($tt:tt)*),
3117        $($rest:tt)*
3118    ) => {
3119        $(#[$a])*
3120        #[derive($crate::reexports::Serialize, $crate::reexports::Deserialize)]
3121        pub struct $variant($($tt)*);
3122
3123        impl IntoRequest for $variant {
3124            type Node = Node;
3125            fn into_request(self) -> $req {
3126                $req::$variant(self)
3127            }
3128            fn do_not_manually_impl_this_trait__use_the_flowey_request_macro_instead(&mut self) {}
3129        }
3130
3131        $crate::__flowey_request_inner!(@emit_struct [$req] $($rest)*);
3132    };
3133    (@emit_struct [$req:ident]
3134        $(#[$a:meta])*
3135        $variant:ident { $($tt:tt)* },
3136        $($rest:tt)*
3137    ) => {
3138        $(#[$a])*
3139        #[derive($crate::reexports::Serialize, $crate::reexports::Deserialize)]
3140        pub struct $variant {
3141            $($tt)*
3142        }
3143
3144        impl IntoRequest for $variant {
3145            type Node = Node;
3146            fn into_request(self) -> $req {
3147                $req::$variant(self)
3148            }
3149            fn do_not_manually_impl_this_trait__use_the_flowey_request_macro_instead(&mut self) {}
3150        }
3151
3152        $crate::__flowey_request_inner!(@emit_struct [$req] $($rest)*);
3153    };
3154    (@emit_struct [$req:ident]
3155        $(#[$a:meta])*
3156        $variant:ident,
3157        $($rest:tt)*
3158    ) => {
3159        $(#[$a])*
3160        #[derive(Serialize, Deserialize)]
3161        pub struct $variant;
3162
3163        impl IntoRequest for $variant {
3164            type Node = Node;
3165            fn into_request(self) -> $req {
3166                $req::$variant(self)
3167            }
3168            fn do_not_manually_impl_this_trait__use_the_flowey_request_macro_instead(&mut self) {}
3169        }
3170
3171        $crate::__flowey_request_inner!(@emit_struct [$req] $($rest)*);
3172    };
3173    (@emit_struct [$req:ident]
3174    ) => {};
3175
3176    //
3177    // @emit_req_enum: build up root request enum
3178    //
3179    (@emit_req_enum [$req:ident($($root_a:meta,)*), $($prev:ident[$($prev_a:meta,)*])*]
3180        $(#[$a:meta])*
3181        $variant:ident($($tt:tt)*),
3182        $($rest:tt)*
3183    ) => {
3184        $crate::__flowey_request_inner!(@emit_req_enum [$req($($root_a,)*), $($prev[$($prev_a,)*])* $variant[$($a,)*]] $($rest)*);
3185    };
3186    (@emit_req_enum [$req:ident($($root_a:meta,)*), $($prev:ident[$($prev_a:meta,)*])*]
3187        $(#[$a:meta])*
3188        $variant:ident { $($tt:tt)* },
3189        $($rest:tt)*
3190    ) => {
3191        $crate::__flowey_request_inner!(@emit_req_enum [$req($($root_a,)*), $($prev[$($prev_a,)*])* $variant[$($a,)*]] $($rest)*);
3192    };
3193    (@emit_req_enum [$req:ident($($root_a:meta,)*), $($prev:ident[$($prev_a:meta,)*])*]
3194        $(#[$a:meta])*
3195        $variant:ident,
3196        $($rest:tt)*
3197    ) => {
3198        $crate::__flowey_request_inner!(@emit_req_enum [$req($($root_a,)*), $($prev[$($prev_a,)*])* $variant[$($a,)*]] $($rest)*);
3199    };
3200    (@emit_req_enum [$req:ident($($root_a:meta,)*), $($prev:ident[$($prev_a:meta,)*])*]
3201    ) => {
3202        #[derive(Serialize, Deserialize)]
3203        pub enum $req {$(
3204            $(#[$prev_a])*
3205            $prev(self::req::$prev),
3206        )*}
3207
3208        impl IntoRequest for $req {
3209            type Node = Node;
3210            fn into_request(self) -> $req {
3211                self
3212            }
3213            fn do_not_manually_impl_this_trait__use_the_flowey_request_macro_instead(&mut self) {}
3214        }
3215    };
3216}
3217
3218/// Declare a new `Request` type for the current `Node`.
3219///
3220/// ## `struct` and `enum` Requests
3221///
3222/// When wrapping a vanilla Rust `struct` and `enum` declaration, this macro
3223/// simply derives [`Serialize`], [`Deserialize`], and [`IntoRequest`] for the
3224/// type, and does nothing else.
3225///
3226/// ## `enum_struct` Requests
3227///
3228/// This macro also supports a special kind of `enum_struct` derive, which
3229/// allows declaring a Request enum where each variant is split off into its own
3230/// separate (named) `struct`.
3231///
3232/// e.g:
3233///
3234/// ```ignore
3235/// flowey_request! {
3236///     pub enum_struct Foo {
3237///         Bar,
3238///         Baz(pub usize),
3239///         Qux(pub String),
3240///     }
3241/// }
3242/// ```
3243///
3244/// will be expanded into:
3245///
3246/// ```ignore
3247/// #[derive(Serialize, Deserialize)]
3248/// pub enum Foo {
3249///    Bar(req::Bar),
3250///    Baz(req::Baz),
3251///    Qux(req::Qux),
3252/// }
3253///
3254/// pud mod req {
3255///     #[derive(Serialize, Deserialize)]
3256///     pub struct Bar;
3257///
3258///     #[derive(Serialize, Deserialize)]
3259///     pub struct Baz(pub usize);
3260///
3261///     #[derive(Serialize, Deserialize)]
3262///     pub struct Qux(pub String);
3263/// }
3264/// ```
3265#[macro_export]
3266macro_rules! flowey_request {
3267    (
3268        $(#[$root_a:meta])*
3269        pub enum_struct $req:ident {
3270            $($tt:tt)*
3271        }
3272    ) => {
3273        $crate::__flowey_request_inner!(@emit_req_enum [$req($($root_a,)*),] $($tt)*);
3274        pub mod req {
3275            use super::*;
3276            $crate::__flowey_request_inner!(@emit_struct [$req] $($tt)*);
3277        }
3278    };
3279
3280    (
3281        $(#[$a:meta])*
3282        pub enum $req:ident {
3283            $($tt:tt)*
3284        }
3285    ) => {
3286        $(#[$a])*
3287        #[derive($crate::reexports::Serialize, $crate::reexports::Deserialize)]
3288        pub enum $req {
3289            $($tt)*
3290        }
3291
3292        impl $crate::node::IntoRequest for $req {
3293            type Node = Node;
3294            fn into_request(self) -> $req {
3295                self
3296            }
3297            fn do_not_manually_impl_this_trait__use_the_flowey_request_macro_instead(&mut self) {}
3298        }
3299    };
3300
3301    (
3302        $(#[$a:meta])*
3303        pub struct $req:ident {
3304            $($tt:tt)*
3305        }
3306    ) => {
3307        $(#[$a])*
3308        #[derive($crate::reexports::Serialize, $crate::reexports::Deserialize)]
3309        pub struct $req {
3310            $($tt)*
3311        }
3312
3313        impl $crate::node::IntoRequest for $req {
3314            type Node = Node;
3315            fn into_request(self) -> $req {
3316                self
3317            }
3318            fn do_not_manually_impl_this_trait__use_the_flowey_request_macro_instead(&mut self) {}
3319        }
3320    };
3321
3322    (
3323        $(#[$a:meta])*
3324        pub struct $req:ident($($tt:tt)*);
3325    ) => {
3326        $(#[$a])*
3327        #[derive($crate::reexports::Serialize, $crate::reexports::Deserialize)]
3328        pub struct $req($($tt)*);
3329
3330        impl $crate::node::IntoRequest for $req {
3331            type Node = Node;
3332            fn into_request(self) -> $req {
3333                self
3334            }
3335            fn do_not_manually_impl_this_trait__use_the_flowey_request_macro_instead(&mut self) {}
3336        }
3337    };
3338}
3339
3340/// Declare a config struct for a flowey node.
3341///
3342/// Fields should be `Option<T>` or `BTreeMap<K, V>`:
3343///
3344/// - `Option<T>` — callers set only the fields they care about. The first
3345///   caller to set a field wins; subsequent callers must agree on the same
3346///   value or merging will fail. The node decides which fields are required
3347///   vs optional in its `emit()`.
3348///
3349/// - `BTreeMap<K, V>` — callers contribute entries independently. Each key
3350///   may only be set once; if two callers set the same key, the values must
3351///   agree. Useful for per-variant or per-target configuration maps.
3352///
3353/// Generates:
3354/// - The `Config` struct with `Serialize`, `Deserialize`, `Default` derives
3355/// - `ConfigMerge` impl with field-level equality merging
3356/// - `IntoConfig` impl tying it to `Node`
3357///
3358/// # Example
3359///
3360/// ```rust,ignore
3361/// flowey_config! {
3362///     pub struct Config {
3363///         pub version: Option<String>,
3364///         pub auto_install: Option<bool>,
3365///         pub target_flags: BTreeMap<String, String>,
3366///     }
3367/// }
3368/// ```
3369///
3370/// Callers send config via:
3371/// ```rust,ignore
3372/// ctx.config(node::Config {
3373///     version: Some("10.31.0".into()),
3374///     ..Default::default()
3375/// });
3376/// ```
3377#[macro_export]
3378macro_rules! flowey_config {
3379    (
3380        $(#[$meta:meta])*
3381        pub struct $Config:ident {
3382            $(
3383                $(#[$field_meta:meta])*
3384                pub $field:ident : $ty:ty
3385            ),* $(,)?
3386        }
3387    ) => {
3388        $(#[$meta])*
3389        #[derive(
3390            $crate::reexports::Serialize,
3391            $crate::reexports::Deserialize,
3392            Default,
3393        )]
3394        pub struct $Config {
3395            $(
3396                $(#[$field_meta])*
3397                pub $field: $ty,
3398            )*
3399        }
3400
3401        impl $crate::node::ConfigMerge for $Config {
3402            fn merge(&mut self, other: Self) -> anyhow::Result<()> {
3403                $(
3404                    $crate::node::ConfigField::merge_field(
3405                        &mut self.$field,
3406                        stringify!($field),
3407                        other.$field,
3408                    )?;
3409                )*
3410                Ok(())
3411            }
3412        }
3413
3414        impl $crate::node::IntoConfig for $Config {
3415            type Node = Node;
3416
3417            fn do_not_manually_impl_this_trait__use_the_flowey_config_macro_instead(&mut self) {}
3418        }
3419    };
3420}
3421
3422/// Construct a command to run via the flowey shell.
3423///
3424/// This is a wrapper around [`xshell::cmd!`] that returns a [`FloweyCmd`]
3425/// instead of a raw [`xshell::Cmd`]. The [`FloweyCmd`] applies any
3426/// [`CommandWrapperKind`] configured on the shell at execution time, making it
3427/// possible to transparently wrap commands (e.g. in `nix-shell --pure`)
3428/// without touching every callsite.
3429///
3430/// [`FloweyCmd`]: crate::shell::FloweyCmd
3431/// [`CommandWrapperKind`]: crate::shell::CommandWrapperKind
3432///
3433/// # Example
3434///
3435/// ```ignore
3436/// flowey::shell_cmd!(rt, "cargo build --release").run()?;
3437/// ```
3438#[macro_export]
3439macro_rules! shell_cmd {
3440    ($rt:expr, $cmd:literal) => {{
3441        let flowey_sh = &$rt.sh;
3442        #[expect(clippy::disallowed_macros)]
3443        flowey_sh.wrap($crate::reexports::xshell::cmd!(flowey_sh.xshell(), $cmd))
3444    }};
3445}