-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
191 lines (147 loc) · 4.62 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package dynu
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"sync"
"time"
"github.com/cenkalti/backoff/v4"
)
const defaultBaseURL = "https://api.dynu.com/v2"
type Client struct {
baseURL *url.URL
HTTPClient *http.Client
APIToken string
mutex sync.Mutex
}
func NewClient(APIToken string) *Client {
baseURL, _ := url.Parse(defaultBaseURL)
return &Client{
HTTPClient: &http.Client{Timeout: 30 * time.Second},
baseURL: baseURL,
APIToken: APIToken,
}
}
func (c *Client) joinUrlPath(elem ...string) *url.URL {
return c.baseURL.JoinPath(elem...)
}
func (c *Client) GetRootDomain(ctx context.Context, hostname string) (*DNSHostname, error) {
c.mutex.Lock()
defer c.mutex.Unlock()
endpoint := c.joinUrlPath("dns", "getroot", hostname)
apiResponse := DNSHostname{}
apiException := APIException{}
err := c.doRetryWithCustomError(ctx, http.MethodGet, endpoint.String(), nil, &apiResponse, &apiException)
if err != nil {
return nil, err
}
if apiResponse.StatusCode != 200 {
return nil, fmt.Errorf("API error: %w", apiException)
}
return &apiResponse, nil
}
func (c *Client) GetRecords(ctx context.Context, hostnameId int64) ([]DNSRecord, error) {
c.mutex.Lock()
defer c.mutex.Unlock()
endpoint := c.joinUrlPath("dns", fmt.Sprint(hostnameId), "record")
apiResponse := RecordsResponse{}
apiException := APIException{}
err := c.doRetryWithCustomError(ctx, http.MethodGet, endpoint.String(), nil, &apiResponse, &apiException)
if err != nil {
return nil, err
}
if apiResponse.StatusCode != 200 {
return nil, fmt.Errorf("API error: %w", apiException)
}
return apiResponse.DNSRecords, nil
}
func (c *Client) AddOrUpdateRecord(ctx context.Context, hostnameId int64, record DNSRecord, ignoreRecordId bool) (*DNSRecord, error) {
c.mutex.Lock()
defer c.mutex.Unlock()
urlPaths := []string{"dns", fmt.Sprint(hostnameId), "record"}
if record.ID != 0 && !ignoreRecordId {
urlPaths = append(urlPaths, fmt.Sprint(record.ID))
}
endpoint := c.joinUrlPath(urlPaths...)
reqBody, err := json.Marshal(record)
if err != nil {
return nil, fmt.Errorf("failed to create request JSON body: %w", err)
}
apiResponse := DNSRecord{}
apiException := APIException{}
err = c.doRetryWithCustomError(ctx, http.MethodPost, endpoint.String(), reqBody, &apiResponse, &apiException)
if err != nil {
return nil, err
}
if apiResponse.StatusCode != 200 {
return nil, fmt.Errorf("API error: %w", apiException)
}
return &apiResponse, nil
}
func (c *Client) DeleteRecord(ctx context.Context, hostnameId int64, dnsRecordId string) error {
c.mutex.Lock()
defer c.mutex.Unlock()
endpoint := c.joinUrlPath("dns", fmt.Sprint(hostnameId), "record", dnsRecordId)
apiResponse := DeleteResponse{}
apiException := APIException{}
err := c.doRetryWithCustomError(ctx, http.MethodDelete, endpoint.String(), nil, &apiResponse, &apiException)
if err != nil {
return err
}
if apiResponse.StatusCode != 200 {
return fmt.Errorf("API error: %w", apiException)
}
return nil
}
// retry with exponential backoff on EOF
func (c *Client) doRetryWithCustomError(ctx context.Context, method, uri string, body []byte, result any, errorResult any) error {
operation := func() error {
return c.doWithCustomError(ctx, method, uri, body, result, errorResult)
}
notify := func(err error, duration time.Duration) {
log.Printf("client retrying in %s because of %v", duration, err)
}
bo := backoff.NewExponentialBackOff(backoff.WithInitialInterval(1 * time.Second))
err := backoff.RetryNotify(operation, bo, notify)
return err
}
// exception fields are at the top level of json rather than nested under exception object; parse json again as custom exception object for error logging
func (c *Client) doWithCustomError(ctx context.Context, method, uri string, body []byte, result any, errorResult any) error {
var reqBody io.Reader
if len(body) > 0 {
reqBody = bytes.NewReader(body)
}
req, err := http.NewRequestWithContext(ctx, method, uri, reqBody)
if err != nil {
return backoff.Permanent(fmt.Errorf("unable to create request: %w", err))
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("API-Key", c.APIToken)
resp, err := c.HTTPClient.Do(req)
if errors.Is(err, io.EOF) {
return err
}
if err != nil {
return backoff.Permanent(err)
}
defer func() { _ = resp.Body.Close() }()
raw, err := io.ReadAll(resp.Body)
if err != nil {
return backoff.Permanent(err)
}
err = json.Unmarshal(raw, result)
if err != nil {
return backoff.Permanent(err)
}
if errorResult != nil {
_ = json.Unmarshal(raw, errorResult)
}
return nil
}