-
Notifications
You must be signed in to change notification settings - Fork 74
/
client.go
441 lines (379 loc) · 12.2 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
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package azuredevops
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"io/ioutil"
"net/http"
"net/url"
"reflect"
"regexp"
"runtime"
"strings"
"sync"
"github.com/google/uuid"
)
const (
// header keys
headerKeyAccept = "Accept"
headerKeyAuthorization = "Authorization"
headerKeyContentType = "Content-Type"
HeaderKeyContinuationToken = "X-MS-ContinuationToken"
headerKeyFedAuthRedirect = "X-TFS-FedAuthRedirect"
headerKeyForceMsaPassThrough = "X-VSS-ForceMsaPassThrough"
headerKeySession = "X-TFS-Session"
headerUserAgent = "User-Agent"
// media types
MediaTypeTextPlain = "text/plain"
MediaTypeApplicationJson = "application/json"
)
// Unique session id to be used by all requests of this session.
var SessionId = uuid.New().String()
// ApiResourceLocation Cache by Url
var apiResourceLocationCache = make(map[string]*map[uuid.UUID]ApiResourceLocation)
var apiResourceLocationCacheLock = sync.RWMutex{}
var version = "1.1.0-b3" // todo: remove hardcoded version
var versionSuffix = " (dev)"
// Base user agent string. The UserAgent set on the connection will be appended to this.
var baseUserAgent = "go/" + runtime.Version() + " (" + runtime.GOOS + " " + runtime.GOARCH + ") azure-devops-go-api/" + version + versionSuffix
func NewClient(connection *Connection, baseUrl string) *Client {
var client *http.Client
if connection.TlsConfig != nil {
client = &http.Client{Transport: &http.Transport{TLSClientConfig: connection.TlsConfig}}
} else {
client = &http.Client{}
}
if connection.Timeout != nil {
client.Timeout = *connection.Timeout
}
return &Client{
baseUrl: baseUrl,
client: client,
authorization: connection.AuthorizationString,
suppressFedAuthRedirect: connection.SuppressFedAuthRedirect,
forceMsaPassThrough: connection.ForceMsaPassThrough,
userAgent: connection.UserAgent,
}
}
type Client struct {
baseUrl string
client *http.Client
authorization string
suppressFedAuthRedirect bool
forceMsaPassThrough bool
userAgent string
}
func (client *Client) SendRequest(request *http.Request) (response *http.Response, err error) {
resp, err := client.client.Do(request) // todo: add retry logic
if resp != nil && (resp.StatusCode < 200 || resp.StatusCode >= 300) {
err = client.UnwrapError(resp)
}
return resp, err
}
func (client *Client) Send(ctx context.Context,
httpMethod string,
locationId uuid.UUID,
apiVersion string,
routeValues map[string]string,
queryParameters url.Values,
body io.Reader,
mediaType string,
acceptMediaType string,
additionalHeaders map[string]string) (response *http.Response, err error) {
location, err := client.getResourceLocation(ctx, locationId)
if err != nil {
return nil, err
}
generatedUrl := client.GenerateUrl(location, routeValues, queryParameters)
fullUrl := combineUrl(client.baseUrl, generatedUrl)
negotiatedVersion, err := negotiateRequestVersion(location, apiVersion)
if err != nil {
return nil, err
}
req, err := client.CreateRequestMessage(ctx, httpMethod, fullUrl, negotiatedVersion, body, mediaType, acceptMediaType, additionalHeaders)
if err != nil {
return nil, err
}
resp, err := client.SendRequest(req)
if err != nil {
return nil, err
}
// Set session if one was supplied in the response.
session, ok := resp.Header[headerKeySession]
if ok && len(session) > 0 {
SessionId = session[0]
}
return resp, err
}
func (client *Client) GenerateUrl(apiResourceLocation *ApiResourceLocation, routeValues map[string]string, queryParameters url.Values) (request string) {
builtUrl := *apiResourceLocation.RouteTemplate
if routeValues == nil {
routeValues = make(map[string]string)
}
routeValues["area"] = *apiResourceLocation.Area
routeValues["resource"] = *apiResourceLocation.ResourceName
builtUrl = transformRouteTemplate(builtUrl, routeValues)
if queryParameters != nil && len(queryParameters) > 0 {
builtUrl += "?" + queryParameters.Encode()
}
return builtUrl
}
func (client *Client) CreateRequestMessage(ctx context.Context,
httpMethod string,
url string,
apiVersion string,
body io.Reader,
mediaType string,
acceptMediaType string,
additionalHeaders map[string]string) (request *http.Request, err error) {
req, err := http.NewRequest(httpMethod, url, body)
if err != nil {
return nil, err
}
if ctx != nil {
req = req.WithContext(ctx)
}
if client.authorization != "" {
req.Header.Add(headerKeyAuthorization, client.authorization)
}
accept := acceptMediaType
if apiVersion != "" {
accept += ";api-version=" + apiVersion
}
req.Header.Add(headerKeyAccept, accept)
if mediaType != "" {
req.Header.Add(headerKeyContentType, mediaType+";charset=utf-8")
}
if client.suppressFedAuthRedirect {
req.Header.Add(headerKeyFedAuthRedirect, "Suppress")
}
if client.forceMsaPassThrough {
req.Header.Add(headerKeyForceMsaPassThrough, "true")
}
// set session if it has not already been set
_, ok := req.Header[headerKeySession]
if !ok {
req.Header.Add(headerKeySession, SessionId)
}
userAgent := baseUserAgent
if client.userAgent != "" {
userAgent += " " + client.userAgent
}
req.Header.Add(headerUserAgent, userAgent)
for key, value := range additionalHeaders {
req.Header.Add(key, value)
}
return req, err
}
func (client *Client) getResourceLocation(ctx context.Context, locationId uuid.UUID) (*ApiResourceLocation, error) {
locationsMap, ok := getApiResourceLocationCache(client.baseUrl)
if !ok {
locations, err := client.getResourceLocationsFromServer(ctx)
if err != nil {
return nil, err
}
newMap := make(map[uuid.UUID]ApiResourceLocation)
locationsMap = &newMap
for _, locationEntry := range locations {
(*locationsMap)[*locationEntry.Id] = locationEntry
}
setApiResourceLocationCache(client.baseUrl, locationsMap)
}
location, ok := (*locationsMap)[locationId]
if ok {
return &location, nil
}
return nil, &LocationIdNotRegisteredError{locationId, client.baseUrl}
}
func getApiResourceLocationCache(url string) (*map[uuid.UUID]ApiResourceLocation, bool) {
apiResourceLocationCacheLock.RLock()
defer apiResourceLocationCacheLock.RUnlock()
locationsMap, ok := apiResourceLocationCache[url]
return locationsMap, ok
}
func setApiResourceLocationCache(url string, locationsMap *map[uuid.UUID]ApiResourceLocation) {
apiResourceLocationCacheLock.Lock()
defer apiResourceLocationCacheLock.Unlock()
apiResourceLocationCache[url] = locationsMap
}
func (client *Client) getResourceLocationsFromServer(ctx context.Context) ([]ApiResourceLocation, error) {
optionsUri := combineUrl(client.baseUrl, "_apis")
request, err := client.CreateRequestMessage(ctx, http.MethodOptions, optionsUri, "", nil, "", MediaTypeApplicationJson, nil)
if err != nil {
return nil, err
}
resp, err := client.SendRequest(request)
if err != nil {
return nil, err
}
// Set session if one was supplied in the response.
session, ok := resp.Header[headerKeySession]
if ok && len(session) > 0 {
SessionId = session[0]
}
if resp != nil && (resp.StatusCode < 200 || resp.StatusCode >= 300) {
return nil, client.UnwrapError(resp)
}
var locations []ApiResourceLocation
err = client.UnmarshalCollectionBody(resp, &locations)
return locations, err
}
// Examples of api-version: 5.1, 5.1-preview, 5.1-preview.1
var apiVersionRegEx = regexp.MustCompile(`(\d+(\.\d)?)(-preview(.(\d+))?)?`)
func combineUrl(part1 string, part2 string) string {
return strings.TrimRight(part1, "/") + "/" + strings.TrimLeft(part2, "/")
}
func transformRouteTemplate(routeTemplate string, routeValues map[string]string) string {
newTemplate := ""
routeTemplate = strings.Replace(routeTemplate, "{*", "{", -1)
segments := strings.Split(routeTemplate, "/")
for _, segment := range segments {
length := len(segment)
if length <= 2 || segment[0] != '{' || segment[length-1] != '}' {
newTemplate += "/" + segment
} else {
value, ok := routeValues[segment[1:length-1]]
if ok {
newTemplate += "/" + url.PathEscape(value)
}
// else this is an optional parameter that has not been supplied, so don't add it back
}
}
// following covers oddball templates with segments that include the token and additional constants
for key, value := range routeValues {
newTemplate = strings.Replace(newTemplate, "{"+key+"}", value, -1)
}
return newTemplate
}
func (client *Client) UnmarshalBody(response *http.Response, v interface{}) (err error) {
if response != nil && response.Body != nil {
var err error
defer func() {
if closeError := response.Body.Close(); closeError != nil {
err = closeError
}
}()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return err
}
body = trimByteOrderMark(body)
return json.Unmarshal(body, &v)
}
return nil
}
func (client *Client) UnmarshalCollectionBody(response *http.Response, v interface{}) (err error) {
if response != nil && response.Body != nil {
var err error
defer func() {
if closeError := response.Body.Close(); closeError != nil {
err = closeError
}
}()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return err
}
body = trimByteOrderMark(body)
err = client.UnmarshalCollectionJson(body, v)
if err != nil {
return err
}
}
return nil
}
func (client *Client) UnmarshalCollectionJson(jsonValue []byte, v interface{}) (err error) {
t := reflect.TypeOf(v)
if t.Kind() == reflect.Ptr {
t = t.Elem()
} else {
return errors.New("value type must be a pointer")
}
sType := reflect.StructOf([]reflect.StructField{
{Name: "Count", Type: reflect.TypeOf(0)},
{Name: "Value", Type: t},
})
sv := reflect.New(sType)
err = json.Unmarshal(jsonValue, sv.Interface())
if err != nil {
return err
}
rv := reflect.ValueOf(v)
rv.Elem().Set(sv.Elem().FieldByName("Value"))
return nil
}
// Returns slice of body without utf-8 byte order mark.
// If BOM does not exist body is returned unchanged.
func trimByteOrderMark(body []byte) []byte {
return bytes.TrimPrefix(body, []byte("\xef\xbb\xbf"))
}
func (client *Client) UnwrapError(response *http.Response) (err error) {
if response.ContentLength == 0 {
message := "Request returned status: " + response.Status
return &WrappedError{
Message: &message,
StatusCode: &response.StatusCode,
}
}
defer func() {
if closeError := response.Body.Close(); closeError != nil {
err = closeError
}
}()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return err
}
body = trimByteOrderMark(body)
contentType, ok := response.Header[headerKeyContentType]
if ok && len(contentType) > 0 && strings.Index(contentType[0], MediaTypeTextPlain) >= 0 {
message := string(body)
statusCode := response.StatusCode
return WrappedError{Message: &message, StatusCode: &statusCode}
}
var wrappedError WrappedError
err = json.Unmarshal(body, &wrappedError)
wrappedError.StatusCode = &response.StatusCode
if err != nil {
return err
}
if wrappedError.Message == nil {
var wrappedImproperError WrappedImproperError
err = json.Unmarshal(body, &wrappedImproperError)
if err == nil && wrappedImproperError.Value != nil && wrappedImproperError.Value.Message != nil {
return &WrappedError{
Message: wrappedImproperError.Value.Message,
StatusCode: &response.StatusCode,
}
}
}
return wrappedError
}
func (client *Client) GetResourceAreas(ctx context.Context) (*[]ResourceAreaInfo, error) {
queryParams := url.Values{}
locationId, _ := uuid.Parse("e81700f7-3be2-46de-8624-2eb35882fcaa")
resp, err := client.Send(ctx, http.MethodGet, locationId, "5.1-preview.1", nil, queryParams, nil, "", "application/json", nil)
if err != nil {
return nil, err
}
var responseValue []ResourceAreaInfo
err = client.UnmarshalCollectionBody(resp, &responseValue)
return &responseValue, err
}
type LocationIdNotRegisteredError struct {
LocationId uuid.UUID
Url string
}
func (e LocationIdNotRegisteredError) Error() string {
return "API resource location " + e.LocationId.String() + " is not registered on " + e.Url + "."
}
type InvalidApiVersion struct {
ApiVersion string
}
func (e InvalidApiVersion) Error() string {
return "The requested api-version is not in a valid format: " + e.ApiVersion
}