1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
package xrpc
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/bluesky-social/indigo/atproto/syntax"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/authretry"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/opt"
)
const (
DefaultLimit int64 = 1 << 20
Prefix = "/xrpc/"
HealthPath = Prefix + "_health"
)
var ErrTooLarge = errors.New("xrpc: the response body is too large")
type Client struct {
Host string
HTTP *http.Client
Auth Auth
Header http.Header
Limit int64
}
type Reply struct {
Status int
Header http.Header
Body []byte
}
func Query[Out any](ctx context.Context, c *Client, nsid string, params url.Values) (Out, error) {
var out Out
target, err := c.target(nsid, params)
if err != nil {
return out, err
}
reply, err := c.do(ctx, http.MethodGet, nsid, target, nil)
return decode[Out](nsid, reply, err)
}
func Procedure[In, Out any](ctx context.Context, c *Client, nsid string, in In) (Out, error) {
var out Out
target, err := c.target(nsid, nil)
if err != nil {
return out, err
}
body, err := json.Marshal(in)
if err != nil {
return out, fmt.Errorf("xrpc: encoding %s: %w", nsid, err)
}
reply, err := c.do(ctx, http.MethodPost, nsid, target, body)
return decode[Out](nsid, reply, err)
}
func Health(ctx context.Context, c *Client) error {
if c == nil || strings.TrimSpace(c.Host) == "" {
return errors.New("xrpc: the client has no host")
}
reply, err := c.do(ctx, http.MethodGet, "_health", c.base()+HealthPath, nil)
if err != nil {
return err
}
if reply.Status != http.StatusOK {
return &Error{Status: reply.Status, Body: reply.Body}
}
return nil
}
func (c *Client) base() string {
return strings.TrimSuffix(strings.TrimRight(c.Host, "/"), "/xrpc")
}
func (c *Client) target(nsid string, params url.Values) (string, error) {
if c == nil || strings.TrimSpace(c.Host) == "" {
return "", errors.New("xrpc: the client has no host")
}
if _, err := syntax.ParseNSID(nsid); err != nil {
return "", fmt.Errorf("xrpc: %w", err)
}
target := c.base() + Prefix + nsid
if len(params) > 0 {
target += "?" + params.Encode()
}
return target, nil
}
func (c *Client) do(ctx context.Context, method, nsid, target string, body []byte) (Reply, error) {
client := c.HTTP
if client == nil {
client = http.DefaultClient
}
limit := c.Limit
limit = opt.Positive(limit, DefaultLimit)
nonceRetried := false
var rejected error
send := func(ctx context.Context) (Reply, error) {
for {
reply, over, verdict, applied, err := c.attempt(ctx, client, method, nsid, target, body, limit)
if err != nil {
if !applied && rejected != nil {
return Reply{}, fmt.Errorf("%w (renewing the credentials: %v)", rejected, err)
}
return Reply{}, err
}
if verdict == RetryNonce && !nonceRetried {
nonceRetried = true
continue
}
if reply.Status < 200 || reply.Status > 299 {
failure := newError(reply.Status, reply.Body)
failure.verdict = verdict
failure.Wait = retryAfter(reply.Status, reply.Header, time.Now())
return Reply{}, failure
}
if over {
return reply, fmt.Errorf("%w: %s answered more than %d bytes", ErrTooLarge, nsid, limit)
}
return reply, nil
}
}
if c.Auth == nil {
return send(ctx)
}
return authretry.Do(ctx, c.Auth, func(ctx context.Context) (Reply, error) {
reply, err := send(ctx)
if rejected == nil && authRejected(err) {
rejected = err
}
return reply, err
}, authRejected)
}
func authRejected(err error) bool {
failure, ok := errors.AsType[*Error](err)
return ok && failure.verdict == RetryAuth
}
func (c *Client) attempt(ctx context.Context, client *http.Client, method, nsid, target string, body []byte, limit int64) (Reply, bool, Verdict, bool, error) {
var reader io.Reader
if body != nil {
reader = bytes.NewReader(body)
}
req, err := http.NewRequestWithContext(ctx, method, target, reader)
if err != nil {
return Reply{}, false, Done, true, fmt.Errorf("xrpc: building %s: %w", nsid, err)
}
for key, values := range c.Header {
req.Header[key] = append([]string(nil), values...)
}
req.Header.Set("Accept", "application/json")
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if c.Auth != nil {
if err := c.Auth.Apply(req); err != nil {
return Reply{}, false, Done, false, err
}
}
resp, err := client.Do(req)
if err != nil {
return Reply{}, false, Done, true, fmt.Errorf("xrpc: %s: %w", nsid, err)
}
raw, err := io.ReadAll(io.LimitReader(resp.Body, limit+1))
resp.Body.Close()
if err != nil {
return Reply{}, false, Done, true, fmt.Errorf("xrpc: reading %s: %w", nsid, err)
}
over := int64(len(raw)) > limit
if over {
raw = raw[:limit]
}
verdict := Done
if c.Auth != nil {
verdict = c.verdict(resp)
}
return Reply{Status: resp.StatusCode, Header: resp.Header, Body: raw}, over, verdict, true, nil
}
func (c *Client) verdict(resp *http.Response) Verdict {
if challenger, ok := c.Auth.(Challenger); ok {
return challenger.Challenge(resp)
}
if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {
return RetryAuth
}
return Done
}
func decode[Out any](nsid string, reply Reply, err error) (Out, error) {
var out Out
if _, discard := any(&out).(*struct{}); discard && errors.Is(err, ErrTooLarge) {
return out, nil
}
if err != nil {
return out, err
}
switch target := any(&out).(type) {
case *Reply:
*target = reply
return out, nil
case *struct{}:
return out, nil
}
if len(bytes.TrimSpace(reply.Body)) == 0 {
return out, nil
}
if err := json.Unmarshal(reply.Body, &out); err != nil {
return out, fmt.Errorf("xrpc: decoding %s: %w", nsid, err)
}
return out, nil
}