terraform-provider-mozoutmz/internal/client/client.go
2026-11-28 15:28:10 +02:00

314 lines
8.9 KiB
Go

// Package client is a small HTTP client for the public API, limited to what the provider needs.
package client
import (
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/mozout-mz/terraform-provider-mozoutmz/internal/brand"
)
// Client calls the API with one key.
type Client struct {
BaseURL string
APIKey string
UserAgent string
HTTP *http.Client
MaxRetries int
}
// New returns a client for the fixed API address of this edition.
func New(apiKey, userAgent string) *Client {
return &Client{
BaseURL: strings.TrimRight(brand.APIURL, "/"),
APIKey: apiKey,
UserAgent: userAgent,
HTTP: &http.Client{Timeout: 60 * time.Second},
MaxRetries: 4,
}
}
// Meta is the "meta" object of a response. Lists carry the paging fields.
type Meta struct {
Page int `json:"page"`
PerPage int `json:"per_page"`
Total int `json:"total"`
TotalPages int `json:"total_pages"`
}
type envelope struct {
Data json.RawMessage `json:"data"`
Meta json.RawMessage `json:"meta"`
Error *struct {
Code string `json:"code"`
Message string `json:"message"`
CorrelationID string `json:"correlation_id"`
Details map[string]interface{} `json:"details"`
} `json:"error"`
}
// APIError is an error answered by the API.
type APIError struct {
Status int
Code string
Message string
CorrelationID string
Details map[string]interface{}
RetryAfter time.Duration
}
// Reason returns details.reason, when the API sends one.
func (e *APIError) Reason() string {
if e.Details == nil {
return ""
}
if r, ok := e.Details["reason"].(string); ok {
return r
}
return ""
}
func (e *APIError) Error() string {
msg := e.Message
switch e.Code {
case "unauthorized":
msg = "the API key is missing, not valid, revoked or expired. Check the key or create another one in " + brand.PanelName
case "insufficient_credit":
msg = "the account does not have enough credit, nothing was charged"
if u, ok := e.Details["add_funds_url"].(string); ok && u != "" {
msg += ". Add funds at " + u + " and run again"
}
case "insufficient_scope":
msg = "the API key does not have the permission this operation needs: " + e.Message
case "spending_limit_exceeded":
msg = "the operation goes over the spending limit of the API key, nothing was charged"
case "rate_limited":
msg = "too many requests, the API asked to wait"
if e.RetryAfter > 0 {
msg += fmt.Sprintf(" %d seconds", int(e.RetryAfter.Seconds()))
}
case "account_email_domain":
msg = "this change touches the mail of the domain of the account email and must be made in " + brand.PanelName
}
if r := e.Reason(); r != "" && e.Code != "account_email_domain" {
msg += " (reason: " + r + ")"
}
out := fmt.Sprintf("%s API error %d %s: %s", brand.Name, e.Status, e.Code, msg)
if e.CorrelationID != "" {
out += " [correlation_id " + e.CorrelationID + "]"
}
return out
}
// IsNotFound tells whether err is a 404 from the API.
func IsNotFound(err error) bool {
var e *APIError
return errors.As(err, &e) && e.Status == http.StatusNotFound
}
// HasCode tells whether err is an API error with this code or details.reason.
func HasCode(err error, code string) bool {
var e *APIError
return errors.As(err, &e) && (e.Code == code || e.Reason() == code)
}
// NewIdempotencyKey returns a random value for the Idempotency-Key header.
func NewIdempotencyKey() string {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return strconv.FormatInt(time.Now().UnixNano(), 36)
}
return hex.EncodeToString(b)
}
// Result holds what came back from one request.
type Result struct {
Meta Meta
Simulated bool
Mode string
}
// Do sends one request and decodes "data" into out (when out is not nil).
// Reads, PUT and DELETE are retried on 429 and 5xx. POST is retried only when it carries an Idempotency-Key.
func (c *Client) Do(ctx context.Context, method, path string, query url.Values, body interface{}, idemKey string, out interface{}) (*Result, error) {
var payload []byte
if body != nil {
var err error
if payload, err = json.Marshal(body); err != nil {
return nil, err
}
}
u := c.BaseURL + path
if len(query) > 0 {
u += "?" + query.Encode()
}
retryable := method != http.MethodPost || idemKey != ""
var lastErr error
for attempt := 0; attempt <= c.MaxRetries; attempt++ {
if attempt > 0 {
wait := time.Duration(1<<uint(attempt-1)) * time.Second
var ae *APIError
if errors.As(lastErr, &ae) && ae.RetryAfter > 0 {
wait = ae.RetryAfter
}
if wait > 60*time.Second {
wait = 60 * time.Second
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(wait):
}
}
res, err := c.once(ctx, method, u, payload, idemKey, out)
if err == nil {
return res, nil
}
lastErr = err
var ae *APIError
if errors.As(err, &ae) {
again := ae.Status == http.StatusTooManyRequests ||
(ae.Status >= 500 && retryable) ||
(ae.Code == "idempotency_conflict" && idemKey != "")
if !again {
return nil, err
}
} else if !retryable {
// Network error on a POST without a key: we cannot know whether it went through.
return nil, err
}
}
return nil, lastErr
}
func (c *Client) once(ctx context.Context, method, u string, payload []byte, idemKey string, out interface{}) (*Result, error) {
var rdr io.Reader
if payload != nil {
rdr = bytes.NewReader(payload)
}
req, err := http.NewRequestWithContext(ctx, method, u, rdr)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+c.APIKey)
req.Header.Set("Accept", "application/json")
req.Header.Set("Accept-Language", "en")
req.Header.Set("User-Agent", c.UserAgent)
if payload != nil {
req.Header.Set("Content-Type", "application/json")
}
if idemKey != "" {
req.Header.Set("Idempotency-Key", idemKey)
}
resp, err := c.HTTP.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
raw, err := io.ReadAll(io.LimitReader(resp.Body, 32<<20))
if err != nil {
return nil, err
}
var env envelope
if len(raw) > 0 {
if jerr := json.Unmarshal(raw, &env); jerr != nil && resp.StatusCode < 300 {
return nil, fmt.Errorf("%s API: response is not JSON (HTTP %d)", brand.Name, resp.StatusCode)
}
}
if resp.StatusCode >= 300 {
ae := &APIError{Status: resp.StatusCode, Code: http.StatusText(resp.StatusCode)}
if env.Error != nil {
ae.Code, ae.Message, ae.CorrelationID, ae.Details = env.Error.Code, env.Error.Message, env.Error.CorrelationID, env.Error.Details
}
if ae.CorrelationID == "" {
ae.CorrelationID = resp.Header.Get("X-Correlation-ID")
}
if s := resp.Header.Get("Retry-After"); s != "" {
if n, perr := strconv.Atoi(s); perr == nil {
ae.RetryAfter = time.Duration(n) * time.Second
}
}
return nil, ae
}
res := &Result{
Simulated: strings.EqualFold(resp.Header.Get("X-API-Simulated"), "true"),
Mode: resp.Header.Get("X-API-Mode"),
}
if len(env.Meta) > 0 {
_ = json.Unmarshal(env.Meta, &res.Meta)
}
if out != nil && len(env.Data) > 0 {
if err := json.Unmarshal(env.Data, out); err != nil {
return nil, fmt.Errorf("%s API: cannot read the response: %w", brand.Name, err)
}
}
return res, nil
}
// ListAll walks every page of a list, 100 items at a time, and calls add for each page.
func (c *Client) ListAll(ctx context.Context, path string, query url.Values, add func(json.RawMessage) error) error {
q := url.Values{}
for k, v := range query {
q[k] = v
}
q.Set("per_page", "100")
for page := 1; ; page++ {
q.Set("page", strconv.Itoa(page))
var raw json.RawMessage
res, err := c.Do(ctx, http.MethodGet, path, q, nil, "", &raw)
if err != nil {
return err
}
if err := add(raw); err != nil {
return err
}
if res.Meta.TotalPages <= page || page >= 1000 {
return nil
}
}
}
// Action is a long operation, followed with GET /v1/actions/{id}.
type Action struct {
ID string `json:"id"`
Type string `json:"type"`
Target string `json:"target"`
Status string `json:"status"`
Result json.RawMessage `json:"result"`
}
// WaitAction polls an action until it is done or failed, or the timeout passes.
func (c *Client) WaitAction(ctx context.Context, id string, timeout time.Duration) (*Action, error) {
deadline := time.Now().Add(timeout)
for {
var a Action
if _, err := c.Do(ctx, http.MethodGet, "/v1/actions/"+url.PathEscape(id), nil, nil, "", &a); err != nil {
return nil, err
}
switch a.Status {
case "done":
return &a, nil
case "failed":
return &a, fmt.Errorf("%s API: action %s failed: %s", brand.Name, id, string(a.Result))
}
if time.Now().After(deadline) {
return &a, fmt.Errorf("%s API: action %s still %s after %s", brand.Name, id, a.Status, timeout)
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(10 * time.Second):
}
}
}