diff --git a/errors.go b/errors.go index 3e1294e4a44fb9f866c436c9e85f508009fc3340..94e08d647da31650a0acad04d1d266aa1890cba1 100644 --- a/errors.go +++ b/errors.go @@ -49,4 +49,5 @@ var ( ErrCannotLoadStatsFromDatabase = fmt.Errorf("errors while loading stats from database") ErrInvalidTime = fmt.Errorf("invalid time") ErrSchedulerMisconfiguration = fmt.Errorf("scheduler misconfiguration") + ErrInvalidDuration = fmt.Errorf("invalid duration") ) diff --git a/schedule-interval_test.go b/schedule-interval_test.go new file mode 100644 index 0000000000000000000000000000000000000000..198e5716a1f3eaf6f995120751a8f5107e65ec6c --- /dev/null +++ b/schedule-interval_test.go @@ -0,0 +1,31 @@ +// Copyright 2023 schukai GmbH +// SPDX-License-Identifier: AGPL-3.0 + +package jobqueue + +import ( + "github.com/stretchr/testify/assert" + "gopkg.in/yaml.v3" + "testing" + "time" +) + +// TestUnmarshalYAML tests the unmarshalling of the SchedulerPersistence struct +func TestUnmarshalYAML(t *testing.T) { + + yamlStr := ` +time: "2023-12-06T15:04:05Z" +interval: "1h30m" +` + + sp := SchedulerPersistence{} + + err := yaml.Unmarshal([]byte(yamlStr), &sp) + assert.NoError(t, err) + + expectedTime, _ := time.Parse(time.RFC3339, "2023-12-06T15:04:05Z") + assert.Equal(t, expectedTime, *sp.Time, "the time should be parsed correctly") + + expectedInterval, _ := time.ParseDuration("1h30m") + assert.Equal(t, expectedInterval, sp.Delay, "the interval should be parsed correctly") +} diff --git a/scheduler.go b/scheduler.go index 79440562171fbac856ac295263805c2d4ff544ac..2f882efdd1ef42b42501e17d4682b4d929f37a17 100644 --- a/scheduler.go +++ b/scheduler.go @@ -68,3 +68,44 @@ func (sp *SchedulerPersistence) UnmarshalJSON(data []byte) error { return nil } + +func (sp *SchedulerPersistence) UnmarshalYAML(unmarshal func(interface{}) error) error { + // Anonymous structure to avoid endless recursion + type Alias SchedulerPersistence + aux := &struct { + Time *string `yaml:"time,omitempty"` + Interval *string `yaml:"interval,omitempty"` + *Alias + }{ + Alias: (*Alias)(sp), + } + + if err := unmarshal(&aux); err != nil { + return err + } + + if aux.Time != nil { + var t time.Time + var err error + for _, format := range SupportedTimeFormats { + t, err = time.Parse(format, *aux.Time) + if err == nil { + break + } + } + if err != nil { + return err + } + sp.Time = &t + } + + if aux.Interval != nil { + d, err := time.ParseDuration(*aux.Interval) + if err != nil { + return err + } + sp.Delay = d + } + + return nil +}