go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/projects/nodes/pkg/temporalutil/try_connect.go (about)

     1  /*
     2  
     3  Copyright (c) 2024 - Present. Will Charczuk. All rights reserved.
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository.
     5  
     6  */
     7  
     8  package temporalutil
     9  
    10  import (
    11  	"context"
    12  	"fmt"
    13  	"time"
    14  
    15  	"go.charczuk.com/sdk/logutil"
    16  	"go.temporal.io/sdk/client"
    17  
    18  	"go.charczuk.com/projects/nodes/pkg/config"
    19  )
    20  
    21  // TryConnect attempts to connect to temporal (5) times, waiting 5 seconds between attempts.
    22  func TryConnect(ctx context.Context, cfg config.Temporal) (client.Client, error) {
    23  	logger := logutil.GetLogger(ctx)
    24  	var err error
    25  	var client client.Client
    26  	for x := 0; x < 5; x++ {
    27  		client, err = cfg.Client()
    28  		if err != nil {
    29  			logutil.Debugf(logger, "temporal client connection error: %v", err)
    30  			logutil.Debugf(logger, "waiting 5s and retrying...")
    31  			select {
    32  			case <-ctx.Done():
    33  				return nil, context.Canceled
    34  			case <-time.After(5 * time.Second):
    35  				continue
    36  			}
    37  		}
    38  		return client, nil
    39  	}
    40  	return nil, fmt.Errorf("%w; attempts exhausted connecting to temporal", err)
    41  }