zdravko/internal/temporal/temporal.go

76 lines
1.9 KiB
Go
Raw Permalink Normal View History

2024-02-16 21:31:00 +00:00
package temporal
import (
"context"
2024-02-27 11:04:05 +00:00
"log/slog"
"time"
"github.com/mentos1386/zdravko/internal/config"
"github.com/mentos1386/zdravko/pkg/jwt"
"github.com/mentos1386/zdravko/pkg/retry"
"github.com/pkg/errors"
"go.temporal.io/sdk/client"
)
type Target struct {
2024-05-25 11:45:25 +00:00
Id string
Name string
Group string
Metadata string
}
// Must be default, as we are also processing
// some temporal things.
const TEMPORAL_SERVER_QUEUE = "default"
type AuthHeadersProvider struct {
Token string
}
func (p *AuthHeadersProvider) GetHeaders(ctx context.Context) (map[string]string, error) {
return map[string]string{
"authorization": "Bearer " + p.Token,
}, nil
}
2024-02-27 11:04:05 +00:00
func ConnectServerToTemporal(logger *slog.Logger, cfg *config.ServerConfig) (client.Client, error) {
// For server we generate new token with admin permissions
token, err := jwt.NewTokenForServer(cfg.Jwt.PrivateKey, cfg.Jwt.PublicKey)
if err != nil {
return nil, err
}
provider := &AuthHeadersProvider{token}
// Try to connect to the Temporal Server
2024-02-27 11:04:05 +00:00
c, err := retry.Retry(10, 2*time.Second, func() (client.Client, error) {
return client.Dial(client.Options{
HostPort: cfg.Temporal.ServerHost,
HeadersProvider: provider,
})
})
2024-02-27 11:04:05 +00:00
if err != nil {
logger.Error("Failed to connect to Temporal Server after retries")
return nil, errors.Wrap(err, "failed to connect to Temporal Server after retries")
}
return c, nil
}
2024-02-24 21:07:49 +00:00
func ConnectWorkerToTemporal(token string, temporalHost string) (client.Client, error) {
provider := &AuthHeadersProvider{token}
// Try to connect to the Temporal Server
return retry.Retry(5, 6*time.Second, func() (client.Client, error) {
client, err := client.Dial(client.Options{
HostPort: temporalHost,
HeadersProvider: provider,
Namespace: "default",
})
if err != nil {
return nil, errors.Wrap(err, "failed to connect to Temporal Server: "+temporalHost)
}
return client, nil
})
}