Skip to content

Commit

Permalink
refactor: Encapsulate runner config operations (#30)
Browse files Browse the repository at this point in the history
  • Loading branch information
ivov authored Nov 27, 2024
1 parent c08c849 commit ba438fa
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 27 deletions.
29 changes: 3 additions & 26 deletions internal/commands/launch.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,34 +34,11 @@ func (l *LaunchCommand) Execute() error {
return fmt.Errorf("env vars failed validation: %w", err)
}

// 1. read configuration
// 1. read runner config

fileCfg, err := config.ReadConfig()
runnerCfg, err := config.GetRunnerConfig(l.RunnerType)
if err != nil {
logs.Errorf("Error reading config file: %v", err)
return err
}

var runnerCfg config.TaskRunnerConfig
found := false
for _, r := range fileCfg.TaskRunners {
if r.RunnerType == l.RunnerType {
runnerCfg = r
found = true
break
}
}

if !found {
return fmt.Errorf("config file does not contain requested runner type: %s", l.RunnerType)
}

taskRunnersNum := len(fileCfg.TaskRunners)

if taskRunnersNum == 1 {
logs.Debug("Loaded config file loaded with a single runner config")
} else {
logs.Debugf("Loaded config file with %d runner configs", taskRunnersNum)
return fmt.Errorf("failed to get runner config: %w", err)
}

// 2. change into working directory
Expand Down
34 changes: 33 additions & 1 deletion internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"os"
"task-runner-launcher/internal/logs"
)

const configPath = "/etc/n8n-task-runners.json"
Expand All @@ -30,7 +31,7 @@ type LauncherConfig struct {
TaskRunners []TaskRunnerConfig `json:"task-runners"`
}

func ReadConfig() (*LauncherConfig, error) {
func readConfig() (*LauncherConfig, error) {
data, err := os.ReadFile(configPath)
if err != nil {
return nil, fmt.Errorf("failed to open config file at %s: %w", configPath, err)
Expand All @@ -47,3 +48,34 @@ func ReadConfig() (*LauncherConfig, error) {

return &config, nil
}

// GetRunnerConfig retrieves and validates the runner configuration for a given runner type.
func GetRunnerConfig(runnerType string) (*TaskRunnerConfig, error) {
fileCfg, err := readConfig()
if err != nil {
return nil, fmt.Errorf("error reading config file: %w", err)
}

var runnerCfg TaskRunnerConfig
found := false
for _, r := range fileCfg.TaskRunners {
if r.RunnerType == runnerType {
runnerCfg = r
found = true
break
}
}

if !found {
return nil, fmt.Errorf("config file does not contain requested runner type: %s", runnerType)
}

taskRunnersNum := len(fileCfg.TaskRunners)
if taskRunnersNum == 1 {
logs.Debug("Loaded config file with a single runner config")
} else {
logs.Debugf("Loaded config file with %d runner configs", taskRunnersNum)
}

return &runnerCfg, nil
}

0 comments on commit ba438fa

Please sign in to comment.