From 6112106b7aaca276b3be5d15d57a4e723b89aa33 Mon Sep 17 00:00:00 2001
From: Volker Schukai <volker.schukai@schukai.com>
Date: Wed, 6 Dec 2023 01:39:28 +0100
Subject: [PATCH] fix: parse duration #34

---
 errors.go                 |  1 +
 schedule-interval_test.go | 31 +++++++++++++++++++++++++++++
 scheduler.go              | 41 +++++++++++++++++++++++++++++++++++++++
 3 files changed, 73 insertions(+)
 create mode 100644 schedule-interval_test.go

diff --git a/errors.go b/errors.go
index 3e1294e..94e08d6 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 0000000..198e571
--- /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 7944056..2f882ef 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
+}
-- 
GitLab