package platform import ( "bytes" "context" "encoding/json" "fmt" "io" "net/http" "net/url" "strings" ) type httpClient struct { console, account string instanceToken, opToken string hc *http.Client } // NewHTTP returns a Client for the Platform console at console (a base URL), // acting on the account with the given sqid. CreateInstance and // DeleteInstance use instanceToken; SetEnv uses operateToken. If hc is nil, // http.DefaultClient is used. func NewHTTP(console, account, instanceToken, operateToken string, hc *http.Client) Client { if hc == nil { hc = http.DefaultClient } return &httpClient{strings.TrimRight(console, "/"), account, instanceToken, operateToken, hc} } func (c *httpClient) appURL(app, rest string) string { return c.console + "/api/cli/apps/" + url.PathEscape(c.account) + "/" + url.PathEscape(app) + rest } // do sends one request and answers its status, nil for any 2xx. Errors name // the call and the status only: a response body can echo secrets. When out // is not nil, a 2xx body (at most 1 MiB) is decoded into it. func (c *httpClient) do(ctx context.Context, call, method, u, token, message string, body, out any) (int, error) { var rd io.Reader if body != nil { b, err := json.Marshal(body) if err != nil { return 0, fmt.Errorf("platform %s: %w", call, err) } rd = bytes.NewReader(b) } req, err := http.NewRequestWithContext(ctx, method, u, rd) if err != nil { return 0, fmt.Errorf("platform %s: bad request", call) } req.Header.Set("Authorization", "Bearer "+token) if body != nil { req.Header.Set("Content-Type", "application/json") } if message != "" { req.Header.Set("X-Carlos-Message", message) } resp, err := c.hc.Do(req) if err != nil { // url.Error repeats the URL, which holds no secret; drop it anyway. if ue, ok := err.(*url.Error); ok { err = ue.Err } return 0, fmt.Errorf("platform %s: %w", call, err) } defer resp.Body.Close() raw, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) if resp.StatusCode/100 != 2 { return resp.StatusCode, fmt.Errorf("platform %s: status %d", call, resp.StatusCode) } if out != nil { if err != nil { return resp.StatusCode, fmt.Errorf("platform %s: reading the answer: %w", call, err) } if json.Unmarshal(raw, out) != nil { return resp.StatusCode, fmt.Errorf("platform %s: the answer is not the expected JSON", call) } } return resp.StatusCode, nil } type envVar struct { Kind string `json:"kind"` Value string `json:"value"` } func (c *httpClient) SetEnv(ctx context.Context, app, environment string, vars map[string]string) error { set := make(map[string]envVar, len(vars)) for k, v := range vars { set[k] = envVar{"env", v} } body := struct { Environment string `json:"environment"` Message string `json:"message"` Set map[string]envVar `json:"set"` }{environment, "Base: install", set} _, err := c.do(ctx, "SetEnv", http.MethodPut, c.appURL(app, "/config"), c.opToken, "", body, nil) return err } // Channel is the release channel every instance Base creates follows. Everything // runs on edge: there is no stable release, and promoting to it needs a passkey. const Channel = "edge" // CreateInstance treats 409 as success only when the record already at host // is this app's, bound to environment: Platform also answers 409 when host // collides with another app's reserved name, and that is not an install. func (c *httpClient) CreateInstance(ctx context.Context, app, host, environment string) error { body := struct { Host string `json:"host"` Environment string `json:"environment"` Channel string `json:"channel"` Message string `json:"message"` }{host, environment, Channel, "Base: install"} status, err := c.do(ctx, "CreateInstance", http.MethodPost, c.appURL(app, "/instances"), c.instanceToken, "", body, nil) if status != http.StatusConflict { return err } var rec struct { App string `json:"app"` Host string `json:"host"` Environment string `json:"environment"` } if _, err := c.do(ctx, "CreateInstance (reading the existing instance)", http.MethodGet, c.appURL(app, "/instances/"+url.PathEscape(host)), c.instanceToken, "", nil, &rec); err != nil { return fmt.Errorf("platform CreateInstance: status 409, and %w", err) } if rec.App != app || rec.Host != host || rec.Environment != environment { return fmt.Errorf("platform CreateInstance: status 409: %s is taken by another instance", host) } return nil } func (c *httpClient) DeleteInstance(ctx context.Context, app, host string) error { _, err := c.do(ctx, "DeleteInstance", http.MethodDelete, c.appURL(app, "/instances/"+url.PathEscape(host)), c.instanceToken, "Base: uninstall", nil, nil) return err }