Skip to content

Commit

Permalink
fix(temporal): use retry logic when connecting
Browse files Browse the repository at this point in the history
  • Loading branch information
mentos1386 committed Feb 16, 2024
1 parent 3ef1a37 commit ccba0a9
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 15 deletions.
14 changes: 4 additions & 10 deletions cmd/worker/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
14 changes: 9 additions & 5 deletions internal/temporal.go
Original file line number Diff line number Diff line change
@@ -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,
})
})
}
23 changes: 23 additions & 0 deletions pkg/retry/retry.go
Original file line number Diff line number Diff line change
@@ -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)
}

0 comments on commit ccba0a9

Please sign in to comment.