-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgraph.go
More file actions
1250 lines (1068 loc) · 34.2 KB
/
graph.go
File metadata and controls
1250 lines (1068 loc) · 34.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package core
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"sync"
"time"
"github.com/actionforge/actrun-cli/github/server"
"github.com/actionforge/actrun-cli/utils"
"github.com/google/uuid"
"go.yaml.in/yaml/v4"
)
type DebugCallback func(ec *ExecutionState, nodeVisit ContextVisit)
type RunOpts struct {
ConfigFile string
OverrideSecrets map[string]string
OverrideInputs map[string]any
OverrideEnv map[string]string
Args []string
LocalGhServer bool
}
type ActionGraph struct {
Nodes map[string]NodeBaseInterface
Inputs map[InputId]InputDefinition `yaml:"inputs" json:"inputs" bson:"inputs"`
Outputs map[OutputId]OutputDefinition `yaml:"outputs" json:"outputs" bson:"outputs"`
Entry string
}
func (ag *ActionGraph) AddNode(nodeId string, node NodeBaseInterface) {
ag.Nodes[nodeId] = node
}
func (ag *ActionGraph) FindNode(nodeId string) (NodeBaseInterface, bool) {
node, exists := ag.Nodes[nodeId]
if !exists {
return nil, false
}
return node, true
}
func (ag *ActionGraph) GetNodes() map[string]NodeBaseInterface {
return ag.Nodes
}
func (ag *ActionGraph) SetEntry(entryName string) {
ag.Entry = entryName
}
func (ag *ActionGraph) GetEntry() (NodeEntryInterface, error) {
node, exists := ag.Nodes[ag.Entry]
if !exists {
return nil, fmt.Errorf("entry '%s' not found", ag.Entry)
}
execNode, ok := node.(NodeEntryInterface)
if !ok {
return nil, fmt.Errorf("entry '%s' is not an entry node", ag.Entry)
}
return execNode, nil
}
func NewActionGraph() ActionGraph {
return ActionGraph{
Nodes: make(map[string]NodeBaseInterface),
}
}
// helper to handle error collection
func collectOrReturn(err error, validate bool, errList *[]error) error {
if err == nil {
return nil
}
if validate {
*errList = append(*errList, err)
return nil
}
return err
}
func LoadEntry(ag *ActionGraph, nodesYaml map[string]any, validate bool, errs *[]error) error {
entryAny, exists := nodesYaml["entry"]
if !exists {
return collectOrReturn(CreateErr(nil, nil, "entry is missing"), validate, errs)
}
entry, ok := entryAny.(string)
if !ok {
return collectOrReturn(CreateErr(nil, nil, "entry is not a string"), validate, errs)
}
ag.SetEntry(entry)
return nil
}
type trackedValue[T any] struct {
Key string
Value T
Source string
Category string
IsExplicit bool
}
type valueMap[T any] struct {
data map[string]trackedValue[T]
category string
}
func newValueMap[T any](category string) valueMap[T] {
return valueMap[T]{
data: make(map[string]trackedValue[T]),
category: category,
}
}
func (m valueMap[T]) set(source map[string]T, sourceName string, explicit bool, hideValue bool) {
keys := make([]string, 0, len(m.data))
for k := range source {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
v := source[k]
m.setSingle(k, v, sourceName, explicit, hideValue)
}
}
func (m valueMap[T]) setSingle(key string, value T, sourceName string, explicit bool, hideValue bool) {
newVal := formatValue(key, value, hideValue)
if !IsTestE2eRunning() {
if existing, exists := m.data[key]; exists {
oldVal := formatValue(existing.Key, existing.Value, hideValue)
utils.LogOut.Debugf("overwriting %s '%s=%s' (from %s) -> '%s' (from %s)\n",
m.category, key, oldVal, existing.Source, newVal, sourceName)
} else {
utils.LogOut.Debugf("setting %s '%s=%s' (from %s)\n",
m.category, key, newVal, sourceName)
}
}
m.data[key] = trackedValue[T]{
Key: key,
Value: value,
Source: sourceName,
Category: m.category,
IsExplicit: explicit,
}
}
func (m valueMap[T]) toSimpleMap() map[string]T {
res := make(map[string]T)
for k, v := range m.data {
res[k] = v.Value
}
return res
}
func (m valueMap[T]) toSimpleMapWithLowercaseKeys() map[string]T {
res := make(map[string]T)
for k, v := range m.data {
res[strings.ToLower(k)] = v.Value
}
return res
}
func printExplicit[T any](m valueMap[T], hideValue bool) {
keys := make([]string, 0, len(m.data))
for k := range m.data {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
v := m.data[k]
// we dont flood logs with shell values, there can be too many of them
if !v.IsExplicit || v.Source == utils.ORIGIN_ENV_SHELL {
continue
}
displayValue := formatValue(v.Key, v.Value, hideValue)
utils.LogOut.Debugf("final %s '%s=%s' set by %s\n",
v.Category, k, displayValue, v.Source)
}
}
func formatValue[T any](key string, val T, hide bool) string {
str := fmt.Sprintf("%v", val)
if str == "" {
return "(empty)"
}
filterWords := []string{"key", "access", "secret", "token", "password"}
lowerStr := strings.ToLower(key)
for _, word := range filterWords {
if strings.Contains(lowerStr, word) {
hide = true
break
}
}
if hide {
return strings.Repeat("*", len(str))
}
const maxLen = 256
if len(str) > maxLen {
return str[:maxLen] + "..."
}
return str
}
func NewExecutionState(
ctx context.Context,
graph *ActionGraph,
graphName string,
isGitHubWorkflow bool,
debugCb DebugCallback,
env map[string]string,
inputs map[string]any,
secrets map[string]string,
ghContext map[string]any,
ghMatrix map[string]any,
ghNeeds map[string]any,
) *ExecutionState {
ctx, cancel := context.WithCancel(ctx)
return &ExecutionState{
Graph: graph,
Hierarchy: make([]NodeBaseInterface, 0),
ContextStackLock: &sync.RWMutex{},
OutputCacheLock: &sync.RWMutex{},
IsDebugSession: debugCb != nil,
DebugCallback: debugCb,
IsGitHubWorkflow: isGitHubWorkflow,
Ctx: ctx,
CtxCancel: cancel,
GraphFile: graphName,
Id: uuid.New().String(),
Env: env,
Inputs: inputs,
Secrets: secrets,
GhContext: ghContext,
GhMatrix: ghMatrix,
GhNeeds: ghNeeds,
DataOutputCache: make(map[string]any),
ExecutionOutputCache: make(map[string]any),
StepCache: NewStepCache(nil),
PostSteps: NewPostStepQueue(),
JobConclusion: "success",
}
}
func RunGraph(ctx context.Context, graphName string, graphContent []byte, opts RunOpts, debugCb DebugCallback) error {
graphYaml := make(map[string]any)
if err := yaml.Unmarshal(graphContent, &graphYaml); err != nil {
return CreateErr(nil, err, "failed to load yaml")
}
// Capture GITHUB_TOKEN / INPUT_GITHUB_TOKEN from the OS environment and store in
// OverrideSecrets so it remains available for repo cloning (gh-action) and
// is properly surfaced as secrets.GITHUB_TOKEN / github.token. Then remove
// from the OS environment to prevent subprocesses from extracting it via
// /proc/<ppid>/environ or similar.
if opts.OverrideSecrets == nil {
opts.OverrideSecrets = make(map[string]string)
}
if _, exists := opts.OverrideSecrets["GITHUB_TOKEN"]; !exists {
if ghToken, ok := opts.OverrideEnv["GITHUB_TOKEN"]; ok && ghToken != "" {
opts.OverrideSecrets["GITHUB_TOKEN"] = ghToken
} else if ghToken := os.Getenv("GITHUB_TOKEN"); ghToken != "" {
opts.OverrideSecrets["GITHUB_TOKEN"] = ghToken
} else if inputToken := os.Getenv("INPUT_GITHUB_TOKEN"); inputToken != "" {
opts.OverrideSecrets["GITHUB_TOKEN"] = inputToken
} else if inputToken := os.Getenv("INPUT_TOKEN"); inputToken != "" {
opts.OverrideSecrets["GITHUB_TOKEN"] = inputToken
}
}
delete(opts.OverrideEnv, "GITHUB_TOKEN")
os.Unsetenv("GITHUB_TOKEN")
os.Unsetenv("INPUT_GITHUB_TOKEN")
os.Unsetenv("INPUT_TOKEN")
ag, errs := LoadGraph(graphYaml, nil, "", false, opts)
if len(errs) > 0 {
return CreateErr(nil, errs[0], "failed to load graph")
}
entry, err := ag.GetEntry()
if err != nil {
return CreateErr(nil, err, "failed to load graph")
}
entryNode, isBaseNode := entry.(NodeBaseInterface)
// isGitHubWorkflow: Determines if this run should behave as a GitHub Action.
// True when either running on actual GitHub Actions (system env), or an external
// caller (e.g., web app) explicitly requests GitHub Actions behavior via OverrideEnv.
// This affects input variable handling, context loading, and other GitHub-specific behavior.
//
// **Important** we haven't loaded the config file yet, so we can only look at overriden envs,
// .env (already set in os.GetEnv) or shell.
isGitHubWorkflow := false
if opts.OverrideEnv["GITHUB_ACTIONS"] == "true" {
isGitHubWorkflow = true
utils.LogOut.Info("GitHub workflow detected via OverrideEnv\n")
} else if os.Getenv("GITHUB_ACTIONS") == "true" {
isGitHubWorkflow = true
utils.LogOut.Info("GitHub workflow detected via GITHUB_ACTIONS environment variable (.env or shell)\n")
} else if entryNode.GetNodeTypeId() == "core/gh-start@v1" {
isGitHubWorkflow = true
utils.LogOut.Info("GitHub workflow detected via entry node type: core/gh-start@v1\n")
}
// mimickGitHubEnv: Determines if we need to set up a simulated GitHub environment. The easiest
// approach for now is to just check a bunch of env vars. The user may have set one or the other
// (through .env or shell) but unlikely all of them but they are by a real GitHub Actions runner.
mimickGitHubEnv := isGitHubWorkflow && os.Getenv("GITHUB_RUN_ID") == "" &&
os.Getenv("RUNNER_TEMP") == "" &&
os.Getenv("GITHUB_API_URL") == "" &&
os.Getenv("GITHUB_RETENTION_DAYS") == ""
// Initialize trackers with their respective categories
envTracker := newValueMap[string]("env")
inputTracker := newValueMap[any]("input")
secretTracker := newValueMap[string]("secret")
matrixTracker := newValueMap[any]("matrix")
needsTracker := newValueMap[any]("needs")
// Priority 1 (Lowest): Config file
if opts.ConfigFile != "" {
cleanConfigPath, err := utils.ValidatePath(opts.ConfigFile)
if err != nil {
return CreateErr(nil, err, "invalid config file path")
}
if _, err := os.Stat(cleanConfigPath); err == nil {
localConfig, err := utils.LoadConfig(cleanConfigPath)
if err != nil {
return CreateErr(nil, err, "failed to load config file")
}
configName := filepath.Base(cleanConfigPath)
envTracker.set(localConfig.Env, configName, true, false)
inputTracker.set(localConfig.Inputs, configName, true, false)
secretTracker.set(localConfig.Secrets, configName, true, true)
}
}
rawEnv := utils.GetAllEnvMapCopy()
// normalize all inputs/secrets with ACT_* iif we're in GitHub
if isGitHubWorkflow {
prefixedRawEnv := make(map[string]utils.EnvKV)
for k, v := range rawEnv {
prefixedKey := k
if strings.HasPrefix(k, "INPUT_") {
prefixedKey = "ACT_" + k
}
prefixedRawEnv[prefixedKey] = v
}
rawEnv = prefixedRawEnv
}
// prio 2: bulk json from env (has a lower precedence than individual inputs/secrets)
for k, v := range rawEnv {
source := "shell"
if v.DotEnvFile {
source = ".env"
}
switch k {
case "ACT_INPUT_INPUTS":
if m, err := decodeJsonFromEnvValue[any](v.Value); err == nil {
inputTracker.set(m, fmt.Sprintf("%s (%s)", source, k), true, false)
}
case "ACT_INPUT_SECRETS":
if m, err := decodeJsonFromEnvValue[string](v.Value); err == nil {
secretTracker.set(m, fmt.Sprintf("%s (%s)", source, k), true, true)
}
}
}
// prio 3: individual env vars & GitHub contexts
for k, v := range rawEnv {
source := "shell"
if v.DotEnvFile {
source = ".env"
}
switch {
// Skip bulk values processed in Priority 2
case k == "ACT_INPUT_INPUTS" || k == "ACT_INPUT_SECRETS":
continue
// individual inputs/secrets (High precedence: will overwrite bulk if key matches)
case strings.HasPrefix(k, "ACT_INPUT_INPUT_"):
key := strings.TrimPrefix(k, "ACT_INPUT_INPUT_")
inputTracker.setSingle(key, v.Value, fmt.Sprintf("%s (%s)", source, k), true, false)
case strings.HasPrefix(k, "ACT_INPUT_SECRET_"):
key := strings.TrimPrefix(k, "ACT_INPUT_SECRET_")
secretTracker.setSingle(key, v.Value, fmt.Sprintf("%s (%s)", source, k), true, true)
// GitHub specifics
case isGitHubWorkflow && k == "ACT_INPUT_MATRIX":
if m, err := decodeJsonFromEnvValue[any](v.Value); err == nil {
matrixTracker.set(m, source, true, true)
}
case isGitHubWorkflow && k == "ACT_INPUT_NEEDS":
if m, err := decodeJsonFromEnvValue[any](v.Value); err == nil {
needsTracker.set(m, source, true, true)
}
case isGitHubWorkflow && (k == "ACT_INPUT_TOKEN" || k == "ACT_INPUT_GITHUB_TOKEN"):
secretTracker.setSingle("GITHUB_TOKEN", v.Value, source, true, true)
default:
envTracker.setSingle(k, v.Value, source, v.DotEnvFile, false)
}
}
// prio 4 (highest): explicit overrides (eg from the web app)
envTracker.set(opts.OverrideEnv, "override", true, false)
inputTracker.set(opts.OverrideInputs, "override", true, false)
secretTracker.set(opts.OverrideSecrets, "override", true, true)
finalEnv := envTracker.toSimpleMap()
finalInputs := inputTracker.toSimpleMapWithLowercaseKeys()
finalSecrets := secretTracker.toSimpleMap()
// some debug printing the final values
if !IsTestE2eRunning() {
printExplicit(inputTracker, false)
printExplicit(secretTracker, true)
printExplicit(matrixTracker, true)
printExplicit(needsTracker, true)
printExplicit(envTracker, false)
}
var newCwd string
if cwd, ok := finalEnv["ACT_CWD"]; ok {
newCwd = cwd
utils.LogOut.Debugf("changing working directory to ACT_CWD: %s\n", newCwd)
}
if mimickGitHubEnv {
// If we are running a github actions workflow, then mimic a GitHub Actions environment
// But only do is if we are NOT already in GitHub Actions
err = SetupGitHubActionsEnv(finalEnv)
if err != nil {
return CreateErr(nil, err, "failed to setup GitHub Actions environment")
}
if opts.LocalGhServer {
// RUNNER_TEMP is provided by the local editor over a 127.0.0.1-only WebSocket; not an external input.
storageDir, mkErr := os.MkdirTemp(finalEnv["RUNNER_TEMP"], "gh-server-storage-") // lgtm[go/path-injection]
if mkErr != nil {
return CreateErr(nil, mkErr, "failed to create storage directory for local GitHub Actions server")
}
rs, srvErr := server.StartServer(server.Config{StorageDir: storageDir})
if srvErr != nil {
return CreateErr(nil, srvErr, "failed to start GitHub Actions mock server")
}
defer rs.Stop()
rs.InjectEnv(finalEnv)
utils.LogOut.Infof("GitHub Actions mock server started at %s\n", rs.URL)
}
// Use the updated GITHUB_WORKSPACE as the working directory.
// SetupGitHubActionsEnv replaces GITHUB_WORKSPACE with a fresh temp folder.
if cwd, ok := finalEnv["GITHUB_WORKSPACE"]; ok {
newCwd = cwd
utils.LogOut.Debugf("changing working directory to GITHUB_WORKSPACE: %s\n", newCwd)
}
} else if debugCb != nil && newCwd == "" {
// for debug sessions, always create a temp working directory if none is set
tmpDir, tmpErr := os.MkdirTemp("", "actrun-debug-*")
if tmpErr != nil {
return CreateErr(nil, tmpErr, "failed to create temp working directory for debug session")
}
newCwd = tmpDir
utils.LogOut.Infof("created temp working directory for debug session: %s\n", newCwd)
defer func() {
_ = os.RemoveAll(tmpDir)
}()
}
if newCwd != "" {
cleanCwd, err := utils.ValidatePath(newCwd)
if err != nil {
return CreateErr(nil, err, "invalid working directory path")
}
originalCwd, err := os.Getwd()
if err != nil {
return CreateErr(nil, err, "failed to get current working directory")
}
if err := os.Chdir(cleanCwd); err != nil {
return CreateErr(nil, err, "failed to change working directory to ACT_CWD/GITHUB_WORKSPACE")
}
defer func() {
_ = os.Chdir(originalCwd)
}()
}
// construct the `github` context
var ghContext map[string]any
var errGh error
if isGitHubWorkflow {
ghContext, errGh = LoadGitHubContext(finalEnv, finalInputs, finalSecrets)
if errGh != nil {
return CreateErr(nil, errGh, "failed to load github context")
}
}
c := NewExecutionState(
ctx,
&ag,
graphName,
isGitHubWorkflow,
debugCb,
finalEnv,
finalInputs,
finalSecrets,
ghContext,
matrixTracker.toSimpleMap(),
needsTracker.toSimpleMap(),
)
if isBaseNode {
c.PushNodeVisit(entryNode, true)
}
mainErr := entry.ExecuteEntry(c, nil, opts.Args)
if mainErr != nil {
c.JobConclusion = "failure"
}
if c.PostSteps.Len() > 0 {
executePostSteps(c, c.PostSteps.DrainLIFO())
}
return mainErr
}
func LoadGraph(graphYaml map[string]any, parent NodeBaseInterface, parentId string, validate bool, opts RunOpts) (ActionGraph, []error) {
var (
collectedErrors []error
err error
)
ag := NewActionGraph()
ag.Inputs, err = LoadGraphInputs(graphYaml)
if err != nil {
if !validate {
return ActionGraph{}, []error{err}
}
collectedErrors = append(collectedErrors, err)
}
ag.Outputs, err = LoadGraphOutputs(graphYaml)
if err != nil {
if !validate {
return ActionGraph{}, []error{err}
}
collectedErrors = append(collectedErrors, err)
}
err = LoadNodes(&ag, parent, parentId, graphYaml, validate, &collectedErrors, opts)
if err != nil && !validate {
return ActionGraph{}, []error{err}
}
err = LoadExecutions(&ag, graphYaml, validate, &collectedErrors)
if err != nil && !validate {
return ActionGraph{}, []error{err}
}
err = LoadConnections(&ag, graphYaml, parent, validate, &collectedErrors)
if err != nil && !validate {
return ActionGraph{}, []error{err}
}
err = LoadEntry(&ag, graphYaml, validate, &collectedErrors)
if err != nil && !validate {
return ActionGraph{}, []error{err}
}
return ag, collectedErrors
}
func LoadGraphInputs(graphYaml map[string]any) (map[InputId]InputDefinition, error) {
inputs, ok := graphYaml["inputs"]
if !ok {
return nil, nil
}
idefs := make(map[InputId]InputDefinition)
for k, v := range inputs.(map[string]any) {
idef, err := anyToPortDefinition[InputDefinition](v)
if err != nil {
return nil, err
}
idefs[InputId(k)] = idef
}
return idefs, nil
}
func LoadGraphOutputs(graphYaml map[string]any) (map[OutputId]OutputDefinition, error) {
outputs, ok := graphYaml["outputs"]
if !ok {
return nil, nil
}
odefs := make(map[OutputId]OutputDefinition)
for k, v := range outputs.(map[string]any) {
odef, err := anyToPortDefinition[OutputDefinition](v)
if err != nil {
return nil, err
}
odefs[OutputId(k)] = odef
}
return odefs, nil
}
func anyToPortDefinition[T any](o any) (T, error) {
var (
tmp bytes.Buffer
ret T
)
err := yaml.NewEncoder(&tmp).Encode(o)
if err != nil {
return ret, err
}
err = yaml.NewDecoder(&tmp).Decode(&ret)
if err != nil {
return ret, err
}
return ret, err
}
func LoadNodes(ag *ActionGraph, parent NodeBaseInterface, parentId string, nodesYaml map[string]any, validate bool, errs *[]error, opts RunOpts) error {
nodesList, err := utils.GetTypedPropertyByPath[[]any](nodesYaml, "nodes")
if err != nil {
return collectOrReturn(err, validate, errs)
}
for _, nodeData := range nodesList {
n, id, err := LoadNode(parent, parentId, nodeData, validate, errs, opts)
if err != nil {
return err
}
// Only add to the graph if a valid node instance and ID were returned.
// If n is nil, it means the node was invalid (e.g. missing ID, missing Type,
// or factory failure), and errors have already been collected.
if n != nil {
ag.AddNode(id, n)
}
}
return nil
}
func LoadNode(parent NodeBaseInterface, parentId string, nodeData any, validate bool, errs *[]error, opts RunOpts) (NodeBaseInterface, string, error) {
nodeI, ok := nodeData.(map[string]any)
if !ok {
err := CreateErr(nil, nil, "node is not a map")
if collectOrReturn(err, validate, errs) != nil {
return nil, "", err
}
return nil, "", nil
}
// We attempt to get the ID. If it fails, we record the error but CONTINUE
// processing (if validating) to check Type, Inputs, and Outputs.
id, idErr := utils.GetTypedPropertyByPath[string](nodeI, "id")
if idErr != nil {
if err := collectOrReturn(idErr, validate, errs); err != nil {
return nil, "", err
}
}
// If Type is missing, loading "makes no sense" as we cannot select a factory.
// We must early out here.
nodeType, typeErr := utils.GetTypedPropertyByPath[string](nodeI, "type")
if typeErr != nil {
if err := collectOrReturn(typeErr, validate, errs); err != nil {
return nil, "", err
}
return nil, "", nil
}
nodeLabel, _ := utils.GetTypedPropertyByPath[string](nodeI, "label")
var (
n NodeBaseInterface
factoryErrs []error
)
var fullPath string
if parentId == "" {
fullPath = id
} else {
fullPath = parentId + "/" + id
}
if strings.HasPrefix(nodeType, "github.com/") {
n, factoryErrs = NewGhActionNode(nodeType, parent, fullPath, validate, opts)
} else {
n, factoryErrs = NewNodeInstance(nodeType, parent, fullPath, nodeI, validate, opts)
}
if len(factoryErrs) > 0 {
if !validate {
// Early out on first error if not validating
return nil, "", factoryErrs[0]
}
// Collect errors and proceed IF we have a valid node instance 'n'
*errs = append(*errs, factoryErrs...)
}
// If the factory failed to produce a node instance completely (n is nil),
// we cannot proceed to check inputs/outputs.
if n == nil {
return nil, "", nil
}
if idErr == nil {
if nodeLabel != "" {
n.SetLabel(nodeLabel)
}
n.SetId(id)
if parentId != "" {
n.SetFullPath(parentId + "/" + id)
} else {
n.SetFullPath(id)
}
}
// We continue to check inputs/outputs even if factoryErrs occurred,
// provided 'n' exists.
inputErr := LoadInputValues(n, nodeI, validate, errs)
if inputErr != nil && !validate {
return nil, "", inputErr
}
// Validate Outputs
outputErr := LoadOutputValues(n, nodeI, validate, errs)
if outputErr != nil && !validate {
return nil, "", outputErr
}
outputNode, ok := n.(HasOutputsInterface)
if ok {
outputNode.SetOwner(n)
}
// If the ID was missing (idErr != nil), we cannot return this node to be
// added to the ActionGraph map (as the key is missing), even though we
// successfully validated its internals.
if idErr != nil {
return nil, "", nil
}
return n, id, nil
}
func LoadInputValues(node NodeBaseInterface, nodeI map[string]any, validate bool, errs *[]error) error {
inputs, hasInputs := node.(HasInputsInterface)
inputValues, err := utils.GetTypedPropertyByPath[map[string]any](nodeI, "inputs")
if err != nil {
if errors.Is(err, &utils.ErrPropertyNotFound{}) {
return nil
}
return collectOrReturn(err, validate, errs)
}
if !hasInputs {
return collectOrReturn(CreateErr(nil, nil, "dst node '%s' (%s) does not have inputs but inputs are defined", node.GetName(), node.GetId()), validate, errs)
}
type subInput struct {
PortId string
PortIndex int
}
subInputs := map[string][]subInput{}
for portId, inputValue := range inputValues {
groupInputId, portIndex, isIndexPort := IsValidIndexPortId(portId)
if isIndexPort {
_, _, ok := inputs.InputDefByPortId(groupInputId)
if !ok {
err := CreateErr(nil, nil, "dst node '%s' (%s) has no array input '%s'", node.GetName(), node.GetId(), groupInputId)
if collectOrReturn(err, validate, errs) != nil {
return err
}
continue
}
subInputs[groupInputId] = append(subInputs[groupInputId], subInput{
PortId: portId,
PortIndex: portIndex,
})
}
err = inputs.SetInputValue(InputId(portId), inputValue)
if err != nil {
if collectOrReturn(err, validate, errs) != nil {
return err
}
continue
}
}
for _, subInputs := range subInputs {
sort.Slice(subInputs, func(i, j int) bool {
return subInputs[i].PortIndex < subInputs[j].PortIndex
})
}
for groupInputId, subInputs := range subInputs {
for _, subInput := range subInputs {
err = inputs.AddSubInput(subInput.PortId, groupInputId, subInput.PortIndex)
if err != nil {
if collectOrReturn(err, validate, errs) != nil {
return err
}
}
}
}
return nil
}
func LoadOutputValues(node NodeBaseInterface, nodeI map[string]any, validate bool, errs *[]error) error {
outputs, hasOutputs := node.(HasOutputsInterface)
outputValues, err := utils.GetTypedPropertyByPath[map[string]any](nodeI, "outputs")
if err != nil {
if errors.Is(err, &utils.ErrPropertyNotFound{}) {
return nil
}
}
if !hasOutputs {
return collectOrReturn(CreateErr(nil, nil, "node '%s' (%s) does not have outputs but outputs are defined", node.GetName(), node.GetId()), validate, errs)
}
type subOutput struct {
PortId string
PortIndex int
}
subOutputs := map[string][]subOutput{}
for portId := range outputValues {
arrayOutputId, portIndex, isIndexPort := IsValidIndexPortId(portId)
if isIndexPort {
_, _, ok := outputs.OutputDefByPortId(arrayOutputId)
if !ok {
err := CreateErr(nil, nil, "source node '%s' (%s) has no array output '%s'", node.GetName(), node.GetId(), arrayOutputId)
if collectOrReturn(err, validate, errs) != nil {
return err
}
continue
}
subOutputs[arrayOutputId] = append(subOutputs[arrayOutputId], subOutput{
PortId: portId,
PortIndex: portIndex,
})
} else {
// at the moment output values can only be used to define an output port
err := CreateErr(nil, nil, "source node '%s' (%s) has no output '%s'", node.GetName(), node.GetId(), portId)
if collectOrReturn(err, validate, errs) != nil {
return err
}
}
}
for _, subOutputs := range subOutputs {
sort.Slice(subOutputs, func(i, j int) bool {
return subOutputs[i].PortIndex < subOutputs[j].PortIndex
})
}
for arrayOutputId, subOutputs := range subOutputs {
for _, subOutput := range subOutputs {
err = outputs.AddSubOutput(subOutput.PortId, arrayOutputId, subOutput.PortIndex)
if err != nil {
if collectOrReturn(err, validate, errs) != nil {
return err
}
}
}
}
return nil
}
func LoadExecutions(ag *ActionGraph, nodesYaml map[string]any, validate bool, errs *[]error) error {
executionsList, err := utils.GetTypedPropertyByPath[[]any](nodesYaml, "executions")
if err != nil {
return collectOrReturn(err, validate, errs)
}
for _, executions := range executionsList {
c, ok := executions.(map[string]any)
if !ok {
err := CreateErr(nil, nil, "execution is not a map")
if collectOrReturn(err, validate, errs) != nil {
return err
}
continue
}
srcNodeId, err := utils.GetTypedPropertyByPath[string](c, "src.node")
if err != nil {
if collectOrReturn(err, validate, errs) != nil {
return err
}
continue
}
dstNodeId, err := utils.GetTypedPropertyByPath[string](c, "dst.node")
if err != nil {
if collectOrReturn(err, validate, errs) != nil {
return err
}
continue
}
srcPort, err := utils.GetTypedPropertyByPath[string](c, "src.port")
if err != nil {
if collectOrReturn(err, validate, errs) != nil {
return err
}
continue
}
dstPort, err := utils.GetTypedPropertyByPath[string](c, "dst.port")
if err != nil {
if collectOrReturn(err, validate, errs) != nil {
return err
}
continue
}
srcNode, ok := ag.FindNode(srcNodeId)
if !ok {
err := CreateErr(nil, nil, "src node '%s' does not exist", srcNodeId)
if collectOrReturn(err, validate, errs) != nil {
return err
}
continue
}
dstNode, ok := ag.FindNode(dstNodeId)
if !ok {
err := CreateErr(nil, nil, "connection dst node '%s' does not exist", dstNodeId)
if collectOrReturn(err, validate, errs) != nil {
return err
}
continue
}
srcExecNode, ok := srcNode.(HasExecutionInterface)
if !ok {
err := CreateErr(nil, err, "src node '%s' (%s) does not have an execution interface", srcNode.GetName(), srcNodeId)
if collectOrReturn(err, validate, errs) != nil {
return err
}
continue