fix(temporal): use retry logic when connecting

This commit is contained in:
Tine 2024-02-16 14:50:35 +01:00
parent 3ef1a37046
commit ccba0a9e18
Signed by: mentos1386
SSH key fingerprint: SHA256:MNtTsLbihYaWF8j1fkOHfkKNlnN1JQfxEU/rBU8nCGw
3 changed files with 36 additions and 15 deletions

View file

@ -3,25 +3,19 @@ package main
import ( import (
"log" "log"
"code.tjo.space/mentos1386/zdravko/internal"
"code.tjo.space/mentos1386/zdravko/internal/activities" "code.tjo.space/mentos1386/zdravko/internal/activities"
"code.tjo.space/mentos1386/zdravko/internal/config" "code.tjo.space/mentos1386/zdravko/internal/config"
"code.tjo.space/mentos1386/zdravko/internal/workflows" "code.tjo.space/mentos1386/zdravko/internal/workflows"
"go.temporal.io/sdk/client"
"go.temporal.io/sdk/worker" "go.temporal.io/sdk/worker"
) )
func main() { func main() {
config := config.NewConfig() cfg := config.NewConfig()
// Initialize a Temporal Client temporalClient, err := internal.ConnectToTemporal(cfg)
// Specify the Namespace in the Client options
clientOptions := client.Options{
HostPort: config.Temporal.ServerHost,
Namespace: "default",
}
temporalClient, err := client.Dial(clientOptions)
if err != nil { if err != nil {
log.Fatalln("Unable to create a Temporal Client", err) log.Fatal(err)
} }
defer temporalClient.Close() defer temporalClient.Close()

View file

@ -1,14 +1,18 @@
package internal package internal
import ( import (
"time"
"code.tjo.space/mentos1386/zdravko/internal/config" "code.tjo.space/mentos1386/zdravko/internal/config"
"code.tjo.space/mentos1386/zdravko/pkg/retry"
"go.temporal.io/sdk/client" "go.temporal.io/sdk/client"
) )
func ConnectToTemporal(cfg *config.Config) (client.Client, error) { func ConnectToTemporal(cfg *config.Config) (client.Client, error) {
c, err := client.Dial(client.Options{HostPort: cfg.Temporal.ServerHost}) // Try to connect to the Temporal Server
if err != nil { return retry.Retry(5, 6*time.Second, func() (client.Client, error) {
return nil, err return client.Dial(client.Options{
} HostPort: cfg.Temporal.ServerHost,
return c, nil })
})
} }

23
pkg/retry/retry.go Normal file
View file

@ -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)
}