diff --git a/internal/templatex/functions.go b/internal/templatex/functions.go index 95342b5f..8f164def 100644 --- a/internal/templatex/functions.go +++ b/internal/templatex/functions.go @@ -15,6 +15,7 @@ import ( "strconv" "strings" "text/template" + "time" "github.com/sap/go-generics/slices" "github.com/spf13/cast" @@ -26,6 +27,8 @@ import ( "k8s.io/client-go/tools/clientcmd" "sigs.k8s.io/controller-runtime/pkg/client" kyaml "sigs.k8s.io/yaml" + + "github.com/sap/component-operator-runtime/pkg/types" ) // TODO: review the usage of the cast.To* function; they seem to be a little unsafe (e.g. with range overflows) @@ -50,6 +53,7 @@ func FuncMap() template.FuncMap { "fromJsonArray": fromJsonArray, "mustFromJsonArray": fromJsonArray, "required": required, + "failRetriable": failRetriable, "bitwiseShiftLeft": bitwiseShiftLeft, "bitwiseShiftRight": bitwiseShiftRight, "bitwiseAnd": bitwiseAnd, @@ -167,6 +171,15 @@ func required(warn string, data any) (any, error) { return data, nil } +func failRetriable(after string, msg string) (string, error) { + retryAfter, err := time.ParseDuration(after) + if err != nil { + // TODO: we could even panic here ... + return "", err + } + return "", types.NewRetriableError(errors.New(msg), &retryAfter) +} + func bitwiseShiftLeft(by any, arg any) (uint64, error) { a, err := cast.ToUint64E(arg) if err != nil { diff --git a/internal/templatex/functions_test.go b/internal/templatex/functions_test.go index 4ad703e7..97aa7dac 100644 --- a/internal/templatex/functions_test.go +++ b/internal/templatex/functions_test.go @@ -18,6 +18,8 @@ import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" . "github.com/onsi/gomega/gcustom" + + "github.com/sap/component-operator-runtime/pkg/types" ) var _ = Describe("testing: functions.go", func() { @@ -314,6 +316,21 @@ var _ = Describe("testing: functions.go", func() { }) + Describe("testing: failRetriable", func() { + + It("should return a retriable error", func() { + res, err := failRetriable("5s", "test error") + Expect(res).To(Equal("")) + Expect(err).To(HaveOccurred()) + Expect(err.Error()).To(Equal("test error")) + Expect(err).To(BeAssignableToTypeOf(types.RetriableError{})) + retryAfter := err.(types.RetriableError).RetryAfter() + Expect(retryAfter).NotTo(BeNil()) + Expect(*retryAfter).To(Equal(5 * time.Second)) + }) + + }) + Describe("testing: bitwiseShiftLeft", func() { It("should calculate the bitwise left shift correctly", func() {