oficina / base Public

Clone
git clone https://amadan.net/oficina/base

Plain git — no account needed to clone.

Download

Download this file

1package platform
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "fmt"
8 "io"
9 "net/http"
10 "net/url"
11 "strings"
12)
13
14type httpClient struct {
15 console, account string
16 instanceToken, opToken string
17 hc *http.Client
18}
19
20// NewHTTP returns a Client for the Platform console at console (a base URL),
21// acting on the account with the given sqid. CreateInstance and
22// DeleteInstance use instanceToken; SetEnv uses operateToken. If hc is nil,
23// http.DefaultClient is used.
24func NewHTTP(console, account, instanceToken, operateToken string, hc *http.Client) Client {
25 if hc == nil {
26 hc = http.DefaultClient
27 }
28 return &httpClient{strings.TrimRight(console, "/"), account, instanceToken, operateToken, hc}
29}
30
31func (c *httpClient) appURL(app, rest string) string {
32 return c.console + "/api/cli/apps/" + url.PathEscape(c.account) + "/" + url.PathEscape(app) + rest
33}
34
35// do sends one request and answers its status, nil for any 2xx. Errors name
36// the call and the status only: a response body can echo secrets. When out
37// is not nil, a 2xx body (at most 1 MiB) is decoded into it.
38func (c *httpClient) do(ctx context.Context, call, method, u, token, message string, body, out any) (int, error) {
39 var rd io.Reader
40 if body != nil {
41 b, err := json.Marshal(body)
42 if err != nil {
43 return 0, fmt.Errorf("platform %s: %w", call, err)
44 }
45 rd = bytes.NewReader(b)
46 }
47 req, err := http.NewRequestWithContext(ctx, method, u, rd)
48 if err != nil {
49 return 0, fmt.Errorf("platform %s: bad request", call)
50 }
51 req.Header.Set("Authorization", "Bearer "+token)
52 if body != nil {
53 req.Header.Set("Content-Type", "application/json")
54 }
55 if message != "" {
56 req.Header.Set("X-Carlos-Message", message)
57 }
58 resp, err := c.hc.Do(req)
59 if err != nil {
60 // url.Error repeats the URL, which holds no secret; drop it anyway.
61 if ue, ok := err.(*url.Error); ok {
62 err = ue.Err
63 }
64 return 0, fmt.Errorf("platform %s: %w", call, err)
65 }
66 defer resp.Body.Close()
67 raw, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
68 if resp.StatusCode/100 != 2 {
69 return resp.StatusCode, fmt.Errorf("platform %s: status %d", call, resp.StatusCode)
70 }
71 if out != nil {
72 if err != nil {
73 return resp.StatusCode, fmt.Errorf("platform %s: reading the answer: %w", call, err)
74 }
75 if json.Unmarshal(raw, out) != nil {
76 return resp.StatusCode, fmt.Errorf("platform %s: the answer is not the expected JSON", call)
77 }
78 }
79 return resp.StatusCode, nil
80}
81
82type envVar struct {
83 Kind string `json:"kind"`
84 Value string `json:"value"`
85}
86
87func (c *httpClient) SetEnv(ctx context.Context, app, environment string, vars map[string]string) error {
88 set := make(map[string]envVar, len(vars))
89 for k, v := range vars {
90 set[k] = envVar{"env", v}
91 }
92 body := struct {
93 Environment string `json:"environment"`
94 Message string `json:"message"`
95 Set map[string]envVar `json:"set"`
96 }{environment, "Base: install", set}
97 _, err := c.do(ctx, "SetEnv", http.MethodPut, c.appURL(app, "/config"), c.opToken, "", body, nil)
98 return err
99}
100
101// Channel is the release channel every instance Base creates follows. Everything
102// runs on edge: there is no stable release, and promoting to it needs a passkey.
103const Channel = "edge"
104
105// CreateInstance treats 409 as success only when the record already at host
106// is this app's, bound to environment: Platform also answers 409 when host
107// collides with another app's reserved name, and that is not an install.
108func (c *httpClient) CreateInstance(ctx context.Context, app, host, environment string) error {
109 body := struct {
110 Host string `json:"host"`
111 Environment string `json:"environment"`
112 Channel string `json:"channel"`
113 Message string `json:"message"`
114 }{host, environment, Channel, "Base: install"}
115 status, err := c.do(ctx, "CreateInstance", http.MethodPost, c.appURL(app, "/instances"), c.instanceToken, "", body, nil)
116 if status != http.StatusConflict {
117 return err
118 }
119 var rec struct {
120 App string `json:"app"`
121 Host string `json:"host"`
122 Environment string `json:"environment"`
123 }
124 if _, err := c.do(ctx, "CreateInstance (reading the existing instance)", http.MethodGet,
125 c.appURL(app, "/instances/"+url.PathEscape(host)), c.instanceToken, "", nil, &rec); err != nil {
126 return fmt.Errorf("platform CreateInstance: status 409, and %w", err)
127 }
128 if rec.App != app || rec.Host != host || rec.Environment != environment {
129 return fmt.Errorf("platform CreateInstance: status 409: %s is taken by another instance", host)
130 }
131 return nil
132}
133
134func (c *httpClient) DeleteInstance(ctx context.Context, app, host string) error {
135 _, err := c.do(ctx, "DeleteInstance", http.MethodDelete, c.appURL(app, "/instances/"+url.PathEscape(host)), c.instanceToken, "Base: uninstall", nil, nil)
136 return err
137}
138