-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathclient.go
83 lines (66 loc) · 2.18 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package common
import (
"context"
"fmt"
"os"
"sync"
"time"
"github.com/aiven/aiven-go-client/v2"
avngen "github.com/aiven/go-client-codegen"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
const (
// DefaultStateChangeDelay is the default delay between state change checks.
DefaultStateChangeDelay = 10 * time.Second
// DefaultStateChangeMinTimeout is the default minimum timeout for state change checks.
DefaultStateChangeMinTimeout = 5 * time.Second
)
func NewAivenClient() (*aiven.Client, error) {
return NewAivenClientWithToken(os.Getenv("AIVEN_TOKEN"))
}
func NewAivenClientWithToken(token string) (*aiven.Client, error) {
return NewCustomAivenClient(token, "", "")
}
func NewCustomAivenClient(token, tfVersion, buildVersion string) (*aiven.Client, error) {
if token == "" {
return nil, fmt.Errorf("token is required for Aiven client")
}
return aiven.NewTokenClient(token, buildUserAgent(tfVersion, buildVersion))
}
func buildUserAgent(tfVersion, buildVersion string) string {
if tfVersion == "" {
// Terraform 0.12 introduced this field to the protocol
// We can therefore assume that if it's missing it's 0.10 or 0.11
tfVersion = "0.11+compatible"
}
if buildVersion == "" {
buildVersion = "dev"
}
return fmt.Sprintf("terraform-provider-aiven/%s/%s", tfVersion, buildVersion)
}
var (
clientCache avngen.Client
clientCacheOnce sync.Once
)
func CacheGenAivenClient(token, tfVersion, buildVersion string) error {
if token == "" {
return fmt.Errorf("token is required for Aiven client")
}
c, err := avngen.NewClient(avngen.TokenOpt(token), avngen.UserAgentOpt(buildUserAgent(tfVersion, buildVersion)))
if err != nil {
return err
}
// Runs once
clientCacheOnce.Do(func() {
clientCache = c
})
return nil
}
type crudHandler func(context.Context, *schema.ResourceData, avngen.Client) diag.Diagnostics
// WithGenClient wraps CRUD handlers and runs with avngen.Client
func WithGenClient(handler crudHandler) func(context.Context, *schema.ResourceData, any) diag.Diagnostics {
return func(ctx context.Context, d *schema.ResourceData, _ any) diag.Diagnostics {
return handler(ctx, d, clientCache)
}
}