oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package assist
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "io"
9 "net/http"
10 "net/url"
11 "strings"
12 "time"
13)
14
15const (
16 httpTimeout = 20 * time.Second
17 maxBody = 256 << 10
18)
19
20type httpProvider struct {
21 name string
22 host func(ctx context.Context, person string) (origin, token string, ok bool, err error)
23 client *http.Client
24 // beforeSend, when set, runs right before every request is sent,
25 // after its host and token are ready (the Oficina provider's
26 // apps_read): a refusal sends nothing.
27 beforeSend func(ctx context.Context, person string) error
28}
29
30// NewHTTPProvider speaks agent-access's operations contract to the origin
31// that host returns for a person. It never follows a redirect, gives up after
32// 20 seconds and reads at most 256 KiB. When host reports not ok it makes no
33// request. A nil client means a default one.
34func NewHTTPProvider(name string, host func(ctx context.Context, person string) (origin, token string, ok bool, err error), client *http.Client) Provider {
35 return newHTTPProvider(name, host, client)
36}
37
38func newHTTPProvider(name string, host func(ctx context.Context, person string) (origin, token string, ok bool, err error), client *http.Client) *httpProvider {
39 c := http.Client{}
40 if client != nil {
41 c = *client
42 }
43 c.Timeout = httpTimeout
44 c.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
45 return &httpProvider{name: name, host: host, client: &c}
46}
47
48func (p *httpProvider) Name() string { return p.name }
49
50func (p *httpProvider) List(ctx context.Context, person string) ([]Operation, error) {
51 body, err := p.do(ctx, person, http.MethodGet, "/api/v1/operations", nil, "", maxBody, nil)
52 if err != nil {
53 return nil, err
54 }
55 var env struct {
56 Operations []Operation `json:"operations"`
57 }
58 if err := json.Unmarshal(body, &env); err != nil {
59 return nil, Failure{Code: "bad_response", Message: "The provider's list was not understood."}
60 }
61 for i := range env.Operations {
62 env.Operations[i].Provider = p.name
63 }
64 return env.Operations, nil
65}
66
67func (p *httpProvider) Invoke(ctx context.Context, person, operation string, input json.RawMessage, key string) (json.RawMessage, error) {
68 if len(bytes.TrimSpace(input)) == 0 {
69 input = json.RawMessage(`{}`)
70 }
71 // The request that performs the operation: the gate runs right
72 // before it is sent, after its host and token are ready.
73 gate := func() error { return Gate(ctx, resolved(ctx, p.name, operation)) }
74 body, err := p.do(ctx, person, http.MethodPost, "/api/v1/operations/"+url.PathEscape(operation), input, key, maxBody, gate)
75 if err != nil {
76 return nil, err
77 }
78 if len(body) > MaxResult {
79 return nil, Failure{Code: "too_large", Message: "The result is too large to return."}
80 }
81 return body, nil
82}
83
84func (p *httpProvider) do(ctx context.Context, person, method, path string, in []byte, key string, limit int64, gate func() error) ([]byte, error) {
85 origin, token, ok, err := p.host(ctx, person)
86 if r := (Refusal{}); errors.As(err, &r) {
87 // The instance's own refusal (an ability off), as it is.
88 return nil, r
89 }
90 if err != nil {
91 return nil, Failure{Code: "unavailable", Message: "The provider could not be reached."}
92 }
93 if !ok {
94 return nil, Failure{Code: "not_connected", Message: "This is not connected."}
95 }
96 var rd io.Reader
97 if in != nil {
98 rd = bytes.NewReader(in)
99 }
100 req, err := http.NewRequestWithContext(ctx, method, strings.TrimRight(origin, "/")+path, rd)
101 if err != nil {
102 return nil, Failure{Code: "unavailable", Message: "The provider could not be reached."}
103 }
104 req.Header.Set("Authorization", "Bearer "+token)
105 req.Header.Set("Accept", "application/json")
106 if in != nil {
107 req.Header.Set("Content-Type", "application/json")
108 }
109 if key != "" {
110 req.Header.Set("Idempotency-Key", key)
111 }
112 if p.beforeSend != nil {
113 if err := p.beforeSend(ctx, person); err != nil {
114 return nil, err
115 }
116 }
117 if gate != nil {
118 if err := gate(); err != nil {
119 return nil, err
120 }
121 }
122 resp, err := p.client.Do(req)
123 if err != nil {
124 return nil, Failure{Code: "unavailable", Message: "The provider could not be reached."}
125 }
126 defer resp.Body.Close()
127 body, err := io.ReadAll(io.LimitReader(resp.Body, limit+1))
128 if err != nil {
129 return nil, Failure{Code: "unavailable", Message: "The provider could not be reached."}
130 }
131 if int64(len(body)) > limit {
132 return nil, Failure{Code: "too_large", Message: "The provider's answer is too large."}
133 }
134 if resp.StatusCode >= 200 && resp.StatusCode < 300 {
135 return body, nil
136 }
137 return nil, failureFrom(resp.StatusCode, body)
138}
139
140func failureFrom(status int, body []byte) error {
141 if status == http.StatusUnauthorized {
142 return Failure{Code: "unauthenticated", Message: "The provider did not accept the connection."}
143 }
144 var env struct {
145 Error struct{ Code, Message string }
146 }
147 if json.Unmarshal(body, &env) == nil && env.Error.Code != "" {
148 if instanceCodes[env.Error.Code] {
149 // A provider can't speak as the instance.
150 return Failure{Code: "provider_error", Message: env.Error.Message}
151 }
152 return Failure{Code: env.Error.Code, Message: env.Error.Message}
153 }
154 if status >= 300 && status < 400 {
155 return Failure{Code: "redirected", Message: "The provider answered with a redirect."}
156 }
157 return Failure{Code: "provider_error", Message: "The provider answered with an error."}
158}
159