diff --git a/cmd/worker/main.go b/cmd/worker/main.go index c574ca1..d0970d9 100644 --- a/cmd/worker/main.go +++ b/cmd/worker/main.go @@ -3,25 +3,19 @@ package main import ( "log" + "code.tjo.space/mentos1386/zdravko/internal" "code.tjo.space/mentos1386/zdravko/internal/activities" "code.tjo.space/mentos1386/zdravko/internal/config" "code.tjo.space/mentos1386/zdravko/internal/workflows" - "go.temporal.io/sdk/client" "go.temporal.io/sdk/worker" ) func main() { - config := config.NewConfig() + cfg := config.NewConfig() - // Initialize a Temporal Client - // Specify the Namespace in the Client options - clientOptions := client.Options{ - HostPort: config.Temporal.ServerHost, - Namespace: "default", - } - temporalClient, err := client.Dial(clientOptions) + temporalClient, err := internal.ConnectToTemporal(cfg) if err != nil { - log.Fatalln("Unable to create a Temporal Client", err) + log.Fatal(err) } defer temporalClient.Close() diff --git a/internal/temporal.go b/internal/temporal.go index e22ca84..a32cdfd 100644 --- a/internal/temporal.go +++ b/internal/temporal.go @@ -1,14 +1,18 @@ package internal import ( + "time" + "code.tjo.space/mentos1386/zdravko/internal/config" + "code.tjo.space/mentos1386/zdravko/pkg/retry" "go.temporal.io/sdk/client" ) func ConnectToTemporal(cfg *config.Config) (client.Client, error) { - c, err := client.Dial(client.Options{HostPort: cfg.Temporal.ServerHost}) - if err != nil { - return nil, err - } - return c, nil + // Try to connect to the Temporal Server + return retry.Retry(5, 6*time.Second, func() (client.Client, error) { + return client.Dial(client.Options{ + HostPort: cfg.Temporal.ServerHost, + }) + }) } diff --git a/pkg/retry/retry.go b/pkg/retry/retry.go new file mode 100644 index 0000000..ed14532 --- /dev/null +++ b/pkg/retry/retry.go @@ -0,0 +1,23 @@ +package retry + +import ( + "fmt" + "log" + "time" +) + +// https://stackoverflow.com/questions/67069723/keep-retrying-a-function-in-golang +func Retry[T any](attempts int, sleep time.Duration, f func() (T, error)) (result T, err error) { + for i := 0; i < attempts; i++ { + if i > 0 { + log.Println("retrying after error:", err) + time.Sleep(sleep) + sleep *= 2 + } + result, err = f() + if err == nil { + return result, nil + } + } + return result, fmt.Errorf("after %d attempts, last error: %s", attempts, err) +}