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
|
package client
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
"github.com/hashicorp/go-retryablehttp"
"github.com/vercel/turbo/cli/internal/ci"
"github.com/vercel/turbo/cli/internal/util"
)
// PutArtifact uploads an artifact associated with a given hash string to the remote cache
func (c *APIClient) PutArtifact(hash string, artifactBody []byte, duration int, tag string) error {
if err := c.okToRequest(); err != nil {
return err
}
params := url.Values{}
c.addTeamParam(¶ms)
// only add a ? if it's actually needed (makes logging cleaner)
encoded := params.Encode()
if encoded != "" {
encoded = "?" + encoded
}
requestURL := c.makeURL("/v8/artifacts/" + hash + encoded)
allowAuth := true
if c.usePreflight {
resp, latestRequestURL, err := c.doPreflight(requestURL, http.MethodPut, "Content-Type, x-artifact-duration, Authorization, User-Agent, x-artifact-tag")
if err != nil {
return fmt.Errorf("pre-flight request failed before trying to store in HTTP cache: %w", err)
}
requestURL = latestRequestURL
headers := resp.Header.Get("Access-Control-Allow-Headers")
allowAuth = strings.Contains(strings.ToLower(headers), strings.ToLower("Authorization"))
}
req, err := retryablehttp.NewRequest(http.MethodPut, requestURL, artifactBody)
req.Header.Set("Content-Type", "application/octet-stream")
req.Header.Set("x-artifact-duration", fmt.Sprintf("%v", duration))
if allowAuth {
req.Header.Set("Authorization", "Bearer "+c.token)
}
req.Header.Set("User-Agent", c.userAgent())
if ci.IsCi() {
req.Header.Set("x-artifact-client-ci", ci.Constant())
}
if tag != "" {
req.Header.Set("x-artifact-tag", tag)
}
if err != nil {
return fmt.Errorf("[WARNING] Invalid cache URL: %w", err)
}
resp, err := c.HTTPClient.Do(req)
if err != nil {
return fmt.Errorf("[ERROR] Failed to store files in HTTP cache: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode == http.StatusForbidden {
return c.handle403(resp.Body)
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("[ERROR] Failed to store files in HTTP cache: %s against URL %s", resp.Status, requestURL)
}
return nil
}
// FetchArtifact attempts to retrieve the build artifact with the given hash from the remote cache
func (c *APIClient) FetchArtifact(hash string) (*http.Response, error) {
return c.getArtifact(hash, http.MethodGet)
}
// ArtifactExists attempts to determine if the build artifact with the given hash exists in the Remote Caching server
func (c *APIClient) ArtifactExists(hash string) (*http.Response, error) {
return c.getArtifact(hash, http.MethodHead)
}
// getArtifact attempts to retrieve the build artifact with the given hash from the remote cache
func (c *APIClient) getArtifact(hash string, httpMethod string) (*http.Response, error) {
if httpMethod != http.MethodHead && httpMethod != http.MethodGet {
return nil, fmt.Errorf("invalid httpMethod %v, expected GET or HEAD", httpMethod)
}
if err := c.okToRequest(); err != nil {
return nil, err
}
params := url.Values{}
c.addTeamParam(¶ms)
// only add a ? if it's actually needed (makes logging cleaner)
encoded := params.Encode()
if encoded != "" {
encoded = "?" + encoded
}
requestURL := c.makeURL("/v8/artifacts/" + hash + encoded)
allowAuth := true
if c.usePreflight {
resp, latestRequestURL, err := c.doPreflight(requestURL, http.MethodGet, "Authorization, User-Agent")
if err != nil {
return nil, fmt.Errorf("pre-flight request failed before trying to fetch files in HTTP cache: %w", err)
}
requestURL = latestRequestURL
headers := resp.Header.Get("Access-Control-Allow-Headers")
allowAuth = strings.Contains(strings.ToLower(headers), strings.ToLower("Authorization"))
}
req, err := retryablehttp.NewRequest(httpMethod, requestURL, nil)
if allowAuth {
req.Header.Set("Authorization", "Bearer "+c.token)
}
req.Header.Set("User-Agent", c.userAgent())
if err != nil {
return nil, fmt.Errorf("invalid cache URL: %w", err)
}
resp, err := c.HTTPClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to fetch artifact: %v", err)
} else if resp.StatusCode == http.StatusForbidden {
err = c.handle403(resp.Body)
_ = resp.Body.Close()
return nil, err
}
return resp, nil
}
func (c *APIClient) handle403(body io.Reader) error {
raw, err := ioutil.ReadAll(body)
if err != nil {
return fmt.Errorf("failed to read response %v", err)
}
apiError := &apiError{}
err = json.Unmarshal(raw, apiError)
if err != nil {
return fmt.Errorf("failed to read response (%v): %v", string(raw), err)
}
disabledErr, err := apiError.cacheDisabled()
if err != nil {
return err
}
return disabledErr
}
type apiError struct {
Code string `json:"code"`
Message string `json:"message"`
}
func (ae *apiError) cacheDisabled() (*util.CacheDisabledError, error) {
if strings.HasPrefix(ae.Code, "remote_caching_") {
statusString := ae.Code[len("remote_caching_"):]
status, err := util.CachingStatusFromString(statusString)
if err != nil {
return nil, err
}
return &util.CacheDisabledError{
Status: status,
Message: ae.Message,
}, nil
}
return nil, fmt.Errorf("unknown status %v: %v", ae.Code, ae.Message)
}
|