1mod 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
31pub 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 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 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 #[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 #[macro_export]
161 macro_rules! claim_vars {
162 ($ctx:ident, ($($var:ident),* $(,)?)) => {
163 $(let $var = $var.claim($ctx);)*
164 };
165 }
166
167 #[macro_export]
169 macro_rules! read_vars {
170 ($rt:ident, ($($var:ident),* $(,)?)) => {
171 $(let $var = $rt.read($var);)*
172 };
173 }
174}
175
176pub trait VarEqBacking {
200 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
222impl<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#[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
280pub type SideEffect = ();
287
288#[derive(Clone, Debug, Serialize, Deserialize)]
291pub enum VarNotClaimed {}
292
293#[derive(Clone, Debug, Serialize, Deserialize)]
296pub enum VarClaimed {}
297
298#[derive(Debug, Serialize, Deserialize)]
318pub struct WriteVar<T: Serialize + DeserializeOwned, C = VarNotClaimed> {
319 backing_var: String,
320 is_side_effect: bool,
323
324 #[serde(skip)]
325 _kind: core::marker::PhantomData<(T, C)>,
326}
327
328pub type ClaimedWriteVar<T> = WriteVar<T, VarClaimed>;
331
332impl<T: Serialize + DeserializeOwned> WriteVar<T, VarNotClaimed> {
333 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 #[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 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
381pub trait ClaimVar {
389 type Claimed;
391 fn claim(self, ctx: &mut StepCtx<'_>) -> Self::Claimed;
393}
394
395pub trait ReadVarValue {
401 type Value;
403 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 let data = rt.get_var(&var, is_side_effect);
444 if is_side_effect {
445 serde_json::from_slice(b"null").expect("should be deserializing into ()")
449 } else {
450 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#[derive(Serialize, Deserialize, Clone)]
567pub struct GhUserSecretVar(pub(crate) String);
568
569#[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
594pub type ClaimedReadVar<T> = ReadVar<T, VarClaimed>;
597
598impl<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 is_side_effect: bool,
619 },
620 Inline(T),
621}
622
623impl<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 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 #[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 #[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 #[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 #[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 #[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 #[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 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 #[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 #[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 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 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#[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#[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
896pub 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
917pub struct ImportCtx<'a> {
919 backend: &'a mut dyn ImportCtxBackend,
920}
921
922impl ImportCtx<'_> {
923 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 fn current_node(&self) -> NodeHandle;
936
937 fn on_new_var(&mut self) -> String;
942
943 fn on_claimed_runtime_var(&mut self, var: &str, is_read: bool);
945
946 fn on_unused_read_var(&mut self, var: &str);
948
949 fn on_request(&mut self, node_handle: NodeHandle, req: anyhow::Result<Box<[u8]>>);
957
958 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1012pub enum FlowBackend {
1013 Local,
1015 Ado,
1017 Github,
1019}
1020
1021#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1023pub enum FlowPlatformKind {
1024 Windows,
1025 Unix,
1026}
1027
1028#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
1030pub enum FlowPlatformLinuxDistro {
1031 Fedora,
1033 Ubuntu,
1035 AzureLinux,
1037 Arch,
1039 OpenSuse,
1041 Nix,
1043 Unknown,
1045}
1046
1047#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
1049#[non_exhaustive]
1050pub enum FlowPlatform {
1051 Windows,
1053 Linux(FlowPlatformLinuxDistro),
1055 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 pub fn exe_suffix(&self) -> &'static str {
1077 if self == &Self::Windows { ".exe" } else { "" }
1078 }
1079
1080 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#[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
1115pub struct StepCtx<'a> {
1117 backend: Rc<RefCell<&'a mut dyn NodeCtxBackend>>,
1118}
1119
1120impl StepCtx<'_> {
1121 pub fn backend(&self) -> FlowBackend {
1124 self.backend.borrow_mut().backend()
1125 }
1126
1127 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
1138pub struct NodeCtx<'a> {
1140 backend: Rc<RefCell<&'a mut dyn NodeCtxBackend>>,
1141}
1142
1143impl<'ctx> NodeCtx<'ctx> {
1144 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 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 #[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 #[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 #[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 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 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 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 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 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 #[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 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 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 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 pub fn backend(&self) -> FlowBackend {
1587 self.backend.borrow_mut().backend()
1588 }
1589
1590 pub fn platform(&self) -> FlowPlatform {
1593 self.backend.borrow_mut().platform()
1594 }
1595
1596 pub fn arch(&self) -> FlowArch {
1598 self.backend.borrow_mut().arch()
1599 }
1600
1601 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 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 #[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 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 #[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 let caller = std::panic::Location::caller().file().replace('\\', "/");
1684
1685 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 #[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 #[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 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
1792pub 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 #[derive(Debug, Clone, Serialize, Deserialize)]
1829 pub struct AdoResourcesRepositoryId {
1830 pub(crate) repo_id: String,
1831 }
1832
1833 impl AdoResourcesRepositoryId {
1834 pub fn new_self() -> Self {
1840 Self {
1841 repo_id: "self".into(),
1842 }
1843 }
1844
1845 pub fn dangerous_get_raw_id(&self) -> &str {
1851 &self.repo_id
1852 }
1853
1854 pub fn dangerous_new(repo_id: &str) -> Self {
1860 Self {
1861 repo_id: repo_id.into(),
1862 }
1863 }
1864 }
1865
1866 #[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 pub const BUILD_SOURCE_BRANCH: AdoRuntimeVar = AdoRuntimeVar::new("build.SourceBranch");
1883
1884 pub const BUILD_BUILD_NUMBER: AdoRuntimeVar = AdoRuntimeVar::new("build.BuildNumber");
1886
1887 pub const BUILD_BUILD_ID: AdoRuntimeVar = AdoRuntimeVar::new("Build.BuildId");
1889
1890 pub const SYSTEM_COLLECTION_URI: AdoRuntimeVar =
1892 AdoRuntimeVar::new("System.CollectionUri");
1893
1894 pub const SYSTEM_TEAM_PROJECT_ID: AdoRuntimeVar =
1896 AdoRuntimeVar::new("System.TeamProjectId");
1897
1898 pub const SYSTEM_ACCESS_TOKEN: AdoRuntimeVar =
1900 AdoRuntimeVar::new_secret("System.AccessToken");
1901
1902 pub const SYSTEM_JOB_ATTEMPT: AdoRuntimeVar =
1904 AdoRuntimeVar::new_secret("System.JobAttempt");
1905
1906 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 pub fn is_secret(&self) -> bool {
1927 self.is_secret
1928 }
1929
1930 pub fn as_raw_var_name(&self) -> String {
1932 self.ado_var.as_ref().into()
1933 }
1934
1935 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 pub fn resolve_repository_id(&self, repo_id: AdoResourcesRepositoryId) -> String {
1990 repo_id.repo_id
1991 }
1992
1993 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 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 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 pub fn condition(mut self, cond: ReadVar<bool>) -> Self {
2084 self.cond = Some(cond);
2085 self
2086 }
2087
2088 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 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 pub fn run_after(mut self, side_effect: ReadVar<SideEffect>) -> Self {
2139 self.run_after.push(side_effect);
2140 self
2141 }
2142
2143 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 #[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 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd)]
2226 pub enum GhPermissionValue {
2227 None = 0,
2228 Read = 1,
2229 Write = 2,
2230 }
2231
2232 #[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 pub sh: FloweyShell,
2296 }
2297
2298 impl RustRuntimeServices<'_> {
2299 pub fn backend(&self) -> FlowBackend {
2302 self.backend
2303 }
2304
2305 pub fn platform(&self) -> FlowPlatform {
2308 self.platform
2309 }
2310
2311 pub fn arch(&self) -> FlowArch {
2313 self.arch
2314 }
2315
2316 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 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 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 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
2426pub 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 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 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#[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 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
2552mod 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 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 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 #[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 #[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
2704pub trait FlowNode {
2791 type Request: Serialize + DeserializeOwned;
2795
2796 fn imports(ctx: &mut ImportCtx<'_>);
2808
2809 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
2843pub trait SimpleFlowNode {
2864 type Request: Serialize + DeserializeOwned;
2865
2866 fn imports(ctx: &mut ImportCtx<'_>);
2878
2879 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
2916pub trait FlowNodeWithConfig {
2963 type Request: Serialize + DeserializeOwned;
2965
2966 type Config: ConfigMerge;
2973
2974 fn imports(ctx: &mut ImportCtx<'_>);
2976
2977 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
3024pub trait IntoRequest {
3032 type Node: FlowNodeBase;
3033 fn into_request(self) -> <Self::Node as FlowNodeBase>::Request;
3034
3035 #[doc(hidden)]
3038 #[expect(nonstandard_style)]
3039 fn do_not_manually_impl_this_trait__use_the_flowey_request_macro_instead(&mut self);
3040}
3041
3042pub trait IntoConfig: Serialize {
3048 type Node: FlowNodeBase;
3049
3050 #[doc(hidden)]
3053 #[expect(nonstandard_style)]
3054 fn do_not_manually_impl_this_trait__use_the_flowey_config_macro_instead(&mut self);
3055}
3056
3057pub trait ConfigMerge: Serialize + DeserializeOwned + Default {
3060 fn merge(&mut self, other: Self) -> anyhow::Result<()>;
3063}
3064
3065pub 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 (@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 (@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#[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#[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#[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}