generated from davidji99/terraform-provider-scaffolding
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathapi.go
218 lines (183 loc) · 6.12 KB
/
api.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
package api
import (
"errors"
"fmt"
"log"
"strconv"
"time"
"github.com/davidji99/simpleresty"
)
const (
// DefaultAPIBaseURL is the base API url.
DefaultAPIBaseURL = "https://api.split.io/internal/api/v2"
// DefaultUserAgent is the user agent used when making API calls.
DefaultUserAgent = "split-go"
// DefaultContentTypeHeader is the default and Content-Type header.
DefaultContentTypeHeader = "application/json"
// DefaultAcceptHeader is the default and Content-Type header.
DefaultAcceptHeader = "application/json"
//DefaultClientTimeout is the default timeout before the client stops making api calls, will be overriden by split/config.go when instantiate
DefaultClientTimeout = 300 // 5 min
UserStatusPending = "PENDING"
UserStatusActive = "ACTIVE"
UserStatusDeactivated = "DEACTIVATED"
timeoutError = "reached maximum client timeout"
)
// Client manages communication with Sendgrid APIs.
type Client struct {
// HTTP client used to communicate with the API.
http *simpleresty.Client
// Reuse a single struct instead of allocating one for each service on the heap.
common service
// config represents all of the API's configurations.
config *Config
//expiresAt is a property that contains the time when the timeout happens
expiresAt time.Time
// Services used for talking to different parts of the Sendgrid APIv3.
ApiKeys *KeysService
Attributes *AttributesService
Environments *EnvironmentsService
Groups *GroupsService
TrafficTypes *TrafficTypesService
Segments *SegmentsService
Splits *SplitsService
Users *UsersService
Workspaces *WorkspacesService
}
// service represents the API service client.
type service struct {
client *Client
}
// GenericListResult is the generic list result.
type GenericListResult struct {
Offset *int `json:"offset"`
Limit *int `json:"limit"`
TotalCount *int `json:"totalCount"`
}
// GenericListQueryParams are parameters for any resource.
type GenericListQueryParams struct {
// The offset to retrieve. Useful for pagination
Offset int `url:"offset,omitempty"`
// The maximum limit to return per call. Max=20-50.
Limit int `url:"limit,omitempty"`
}
// New constructs a new Client.
func New(opts ...Option) (*Client, error) {
config := &Config{
APIBaseURL: DefaultAPIBaseURL,
UserAgent: DefaultUserAgent,
ContentTypeHeader: DefaultContentTypeHeader,
AcceptHeader: DefaultAcceptHeader,
ClientTimeout: DefaultClientTimeout,
APIKey: "",
}
// Define any user custom Client settings
if optErr := config.ParseOptions(opts...); optErr != nil {
return nil, optErr
}
expiresAt := time.Now().Add(time.Duration(config.ClientTimeout) * time.Second)
client := &Client{
config: config,
http: simpleresty.NewWithBaseURL(config.APIBaseURL),
expiresAt: expiresAt,
}
// Set headers
client.setHeaders()
// Inject services
client.injectServices()
return client, nil
}
// injectServices adds the services to the client.
func (c *Client) injectServices() {
c.common.client = c
c.ApiKeys = (*KeysService)(&c.common)
c.Attributes = (*AttributesService)(&c.common)
c.Environments = (*EnvironmentsService)(&c.common)
c.Groups = (*GroupsService)(&c.common)
c.TrafficTypes = (*TrafficTypesService)(&c.common)
c.Segments = (*SegmentsService)(&c.common)
c.Splits = (*SplitsService)(&c.common)
c.Users = (*UsersService)(&c.common)
c.Workspaces = (*WorkspacesService)(&c.common)
}
func (c *Client) setHeaders() {
c.http.SetHeader("Content-type", c.config.ContentTypeHeader).
SetHeader("Accept", c.config.AcceptHeader).
SetHeader("User-Agent", c.config.UserAgent).
SetHeader("Authorization", fmt.Sprintf("Bearer %s", c.config.APIKey)).
SetTimeout(2 * time.Minute).
SetAllowGetMethodPayload(true)
// Set additional headers
if c.config.CustomHTTPHeaders != nil {
c.http.SetHeaders(c.config.CustomHTTPHeaders)
}
}
func (c *Client) checkRateLimit(resp *simpleresty.Response) bool {
if resp != nil && resp.StatusCode == 429 {
remainingOrgSeconds, _ := strconv.Atoi((resp.Resp.Header().Get("X-RateLimit-Reset-Seconds-Org")))
timeToSleep, _ := strconv.Atoi(resp.Resp.Header().Get("X-RateLimit-Reset-Seconds-IP"))
if remainingOrgSeconds != 0 {
// Got rate-limit by Organization
timeToSleep = remainingOrgSeconds
}
// Got rate-limit by IP-addr
log.Printf("[DEBUG] Got rate-limited, sleeping for %d seconds", timeToSleep)
time.Sleep(time.Duration(timeToSleep) * time.Second)
return true
}
return false
}
// checkTimeout returns true if timeout, false if still have time
func (c *Client) checkTimeout() bool {
return time.Now().After(c.expiresAt)
}
func (c *Client) get(url string, r, body interface{}) (*simpleresty.Response, error) {
if !c.checkTimeout() {
response, getErr := c.http.Get(url, &r, body)
if c.checkRateLimit(response) {
response, getErr = c.get(url, &r, body)
}
return response, getErr
}
return nil, errors.New(timeoutError)
}
func (c *Client) post(url string, r, opts interface{}) (*simpleresty.Response, error) {
if !c.checkTimeout() {
response, getErr := c.http.Post(url, &r, opts)
if c.checkRateLimit(response) {
response, getErr = c.post(url, &r, opts)
}
return response, getErr
}
return nil, errors.New(timeoutError)
}
func (c *Client) put(url string, r, opts interface{}) (*simpleresty.Response, error) {
if !c.checkTimeout() {
response, getErr := c.http.Put(url, &r, opts)
if c.checkRateLimit(response) {
response, getErr = c.put(url, &r, opts)
}
return response, getErr
}
return nil, errors.New(timeoutError)
}
func (c *Client) patch(url string, r, opts interface{}) (*simpleresty.Response, error) {
if !c.checkTimeout() {
response, getErr := c.http.Patch(url, &r, opts)
if c.checkRateLimit(response) {
response, getErr = c.patch(url, &r, opts)
}
return response, getErr
}
return nil, errors.New(timeoutError)
}
func (c *Client) delete(url string, r, opts interface{}) (*simpleresty.Response, error) {
if !c.checkTimeout() {
response, getErr := c.http.Delete(url, &r, opts)
if c.checkRateLimit(response) {
response, getErr = c.delete(url, &r, opts)
}
return response, getErr
}
return nil, errors.New(timeoutError)
}