|
| 1 | +package api |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "encoding/json" |
| 7 | + "fmt" |
| 8 | + "io" |
| 9 | + "net/http" |
| 10 | + "net/url" |
| 11 | + "strings" |
| 12 | + "time" |
| 13 | + |
| 14 | + "github.com/404tk/cloudtoolkit/pkg/providers/huawei/auth" |
| 15 | + "github.com/404tk/cloudtoolkit/pkg/providers/huawei/endpoint" |
| 16 | +) |
| 17 | + |
| 18 | +type Request struct { |
| 19 | + Service string |
| 20 | + Region string |
| 21 | + Intl bool |
| 22 | + Method string |
| 23 | + Path string |
| 24 | + Query url.Values |
| 25 | + Body []byte |
| 26 | + Headers http.Header |
| 27 | + Idempotent bool |
| 28 | +} |
| 29 | + |
| 30 | +type Option func(*Client) |
| 31 | + |
| 32 | +type Client struct { |
| 33 | + credential auth.Credential |
| 34 | + httpClient *http.Client |
| 35 | + retryPolicy RetryPolicy |
| 36 | + now func() time.Time |
| 37 | + baseURL *url.URL |
| 38 | +} |
| 39 | + |
| 40 | +func NewClient(cred auth.Credential, opts ...Option) *Client { |
| 41 | + client := &Client{ |
| 42 | + credential: cred, |
| 43 | + httpClient: NewHTTPClient(), |
| 44 | + retryPolicy: DefaultRetryPolicy(), |
| 45 | + now: time.Now, |
| 46 | + } |
| 47 | + for _, opt := range opts { |
| 48 | + opt(client) |
| 49 | + } |
| 50 | + return client |
| 51 | +} |
| 52 | + |
| 53 | +func WithHTTPClient(hc *http.Client) Option { |
| 54 | + return func(c *Client) { |
| 55 | + if hc != nil { |
| 56 | + c.httpClient = hc |
| 57 | + } |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +func WithRetryPolicy(p RetryPolicy) Option { |
| 62 | + return func(c *Client) { |
| 63 | + if p != nil { |
| 64 | + c.retryPolicy = p |
| 65 | + } |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +func WithClock(now func() time.Time) Option { |
| 70 | + return func(c *Client) { |
| 71 | + if now != nil { |
| 72 | + c.now = now |
| 73 | + } |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +func WithBaseURL(raw string) Option { |
| 78 | + return func(c *Client) { |
| 79 | + if raw == "" { |
| 80 | + return |
| 81 | + } |
| 82 | + if u, err := url.Parse(raw); err == nil { |
| 83 | + c.baseURL = u |
| 84 | + } |
| 85 | + } |
| 86 | +} |
| 87 | + |
| 88 | +func (c *Client) DoJSON(ctx context.Context, req Request, out any) error { |
| 89 | + if ctx == nil { |
| 90 | + ctx = context.Background() |
| 91 | + } |
| 92 | + if err := c.credential.Validate(); err != nil { |
| 93 | + return err |
| 94 | + } |
| 95 | + |
| 96 | + service := strings.TrimSpace(strings.ToLower(req.Service)) |
| 97 | + if service == "" { |
| 98 | + return fmt.Errorf("huawei client: empty service") |
| 99 | + } |
| 100 | + method := strings.ToUpper(strings.TrimSpace(req.Method)) |
| 101 | + if method == "" { |
| 102 | + method = http.MethodGet |
| 103 | + } |
| 104 | + scheme, host, path, err := c.resolveEndpoint(req, service) |
| 105 | + if err != nil { |
| 106 | + return err |
| 107 | + } |
| 108 | + |
| 109 | + body := append([]byte(nil), req.Body...) |
| 110 | + headers := cloneHeader(req.Headers) |
| 111 | + if len(body) > 0 && strings.TrimSpace(headers.Get("Content-Type")) == "" { |
| 112 | + headers.Set("Content-Type", "application/json;charset=UTF-8") |
| 113 | + } |
| 114 | + timestamp := c.now().UTC() |
| 115 | + signed, err := Sign(&SignRequest{ |
| 116 | + Method: method, |
| 117 | + Host: host, |
| 118 | + Path: path, |
| 119 | + Query: cloneValues(req.Query), |
| 120 | + Headers: flattenHeaders(headers), |
| 121 | + Body: body, |
| 122 | + AccessKey: c.credential.AK, |
| 123 | + SecretKey: c.credential.SK, |
| 124 | + Timestamp: timestamp, |
| 125 | + }) |
| 126 | + if err != nil { |
| 127 | + return err |
| 128 | + } |
| 129 | + |
| 130 | + finalHeaders := headers.Clone() |
| 131 | + for key, value := range signed { |
| 132 | + if value == "" { |
| 133 | + continue |
| 134 | + } |
| 135 | + finalHeaders.Set(key, value) |
| 136 | + } |
| 137 | + removeReservedHeader(finalHeaders, "Host") |
| 138 | + |
| 139 | + requestURL := url.URL{ |
| 140 | + Scheme: scheme, |
| 141 | + Host: host, |
| 142 | + Path: path, |
| 143 | + RawQuery: cloneValues(req.Query).Encode(), |
| 144 | + } |
| 145 | + |
| 146 | + idempotent := req.Idempotent || method == http.MethodGet |
| 147 | + httpResp, err := c.retryPolicy.Do(ctx, idempotent, func() (*http.Response, error) { |
| 148 | + httpReq, err := http.NewRequestWithContext(ctx, method, requestURL.String(), bytes.NewReader(body)) |
| 149 | + if err != nil { |
| 150 | + return nil, err |
| 151 | + } |
| 152 | + httpReq.Host = host |
| 153 | + httpReq.Header = finalHeaders.Clone() |
| 154 | + return c.httpClient.Do(httpReq) |
| 155 | + }) |
| 156 | + if err != nil { |
| 157 | + return err |
| 158 | + } |
| 159 | + defer closeResponse(httpResp) |
| 160 | + |
| 161 | + respBody, err := io.ReadAll(httpResp.Body) |
| 162 | + if err != nil { |
| 163 | + return fmt.Errorf("read huawei response: %w", err) |
| 164 | + } |
| 165 | + if err := withRequestID(DecodeError(httpResp.StatusCode, respBody), httpResp.Header.Get("X-Request-Id")); err != nil { |
| 166 | + return err |
| 167 | + } |
| 168 | + if out == nil || len(respBody) == 0 { |
| 169 | + return nil |
| 170 | + } |
| 171 | + if err := json.Unmarshal(respBody, out); err != nil { |
| 172 | + return fmt.Errorf("decode huawei response: %w", err) |
| 173 | + } |
| 174 | + return nil |
| 175 | +} |
| 176 | + |
| 177 | +func (c *Client) resolveEndpoint(req Request, service string) (string, string, string, error) { |
| 178 | + base := endpoint.For(service, strings.TrimSpace(req.Region), req.Intl) |
| 179 | + if c.baseURL != nil { |
| 180 | + base = c.baseURL.String() |
| 181 | + } |
| 182 | + if strings.TrimSpace(base) == "" { |
| 183 | + return "", "", "", fmt.Errorf("huawei client: empty endpoint") |
| 184 | + } |
| 185 | + u, err := url.Parse(base) |
| 186 | + if err != nil { |
| 187 | + return "", "", "", fmt.Errorf("huawei client: invalid endpoint %q: %w", base, err) |
| 188 | + } |
| 189 | + if u.Scheme == "" || u.Host == "" { |
| 190 | + return "", "", "", fmt.Errorf("huawei client: invalid endpoint %q", base) |
| 191 | + } |
| 192 | + return u.Scheme, u.Host, joinPath(u.Path, ensureLeadingSlash(req.Path)), nil |
| 193 | +} |
| 194 | + |
| 195 | +func flattenHeaders(headers http.Header) map[string]string { |
| 196 | + flattened := make(map[string]string, len(headers)) |
| 197 | + for key, values := range headers { |
| 198 | + name := strings.TrimSpace(key) |
| 199 | + if name == "" || isReservedHeader(name) { |
| 200 | + continue |
| 201 | + } |
| 202 | + flattened[name] = strings.Join(values, ",") |
| 203 | + } |
| 204 | + return flattened |
| 205 | +} |
| 206 | + |
| 207 | +func cloneHeader(headers http.Header) http.Header { |
| 208 | + if headers == nil { |
| 209 | + return http.Header{} |
| 210 | + } |
| 211 | + return headers.Clone() |
| 212 | +} |
| 213 | + |
| 214 | +func cloneValues(values url.Values) url.Values { |
| 215 | + if values == nil { |
| 216 | + return url.Values{} |
| 217 | + } |
| 218 | + cloned := make(url.Values, len(values)) |
| 219 | + for key, items := range values { |
| 220 | + cloned[key] = append([]string(nil), items...) |
| 221 | + } |
| 222 | + return cloned |
| 223 | +} |
| 224 | + |
| 225 | +func joinPath(basePath, requestPath string) string { |
| 226 | + switch { |
| 227 | + case basePath == "", basePath == "/": |
| 228 | + return ensureLeadingSlash(requestPath) |
| 229 | + case requestPath == "", requestPath == "/": |
| 230 | + return ensureLeadingSlash(basePath) |
| 231 | + default: |
| 232 | + return strings.TrimRight(basePath, "/") + ensureLeadingSlash(requestPath) |
| 233 | + } |
| 234 | +} |
| 235 | + |
| 236 | +func isReservedHeader(name string) bool { |
| 237 | + switch strings.ToLower(strings.TrimSpace(name)) { |
| 238 | + case strings.ToLower(HeaderAuthorization), strings.ToLower(HeaderXDate), strings.ToLower(HeaderContentSha256), "host": |
| 239 | + return true |
| 240 | + default: |
| 241 | + return false |
| 242 | + } |
| 243 | +} |
| 244 | + |
| 245 | +func removeReservedHeader(headers http.Header, name string) { |
| 246 | + for key := range headers { |
| 247 | + if strings.EqualFold(key, name) { |
| 248 | + headers.Del(key) |
| 249 | + } |
| 250 | + } |
| 251 | +} |
0 commit comments