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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
package market
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"slices"
"strings"
"sync"
"time"
"github.com/bluesky-social/indigo/atproto/syntax"
"github.com/johnandersen777/socialweb-computer-kcp/internal/atproto/xrpc"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/opt"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/ttlcache"
)
const (
RelayDiscoveryCacheTTL = 180 * time.Second
OfferingsCacheTTL = 120 * time.Second
RelaysCacheTTL = 60 * time.Second
HeartbeatMaxSkew = 60 * time.Second
)
type RelayFailure struct {
URL string
Reason string
}
type RelayVisibilityResult struct {
OK bool
CapableRelays []string
IndexedBy []string
Failures []RelayFailure
}
type RelayVisibilityOptions struct {
RelayURLs []string
BidderDID string
Collection string
Log LogFunc
PollTimeout time.Duration
PollInterval time.Duration
Client HTTPDoer
}
func relayCollectionURL(relayURL, collection string) string {
return strings.TrimRight(relayURL, "/") +
"/xrpc/com.atproto.sync.listReposByCollection?collection=" +
url.QueryEscape(collection) + "&limit=1000"
}
func relayGET(ctx context.Context, client HTTPDoer, rawURL string) (int, []byte, error) {
if client == nil {
client = http.DefaultClient
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
if err != nil {
return 0, nil, err
}
req.Header.Set("Accept", "application/json")
res, err := client.Do(req)
if err != nil {
return 0, nil, err
}
defer res.Body.Close()
body, err := io.ReadAll(io.LimitReader(res.Body, 1<<22))
if err != nil {
return res.StatusCode, nil, err
}
return res.StatusCode, body, nil
}
func relayDIDs(body []byte) []string {
var parsed struct {
Repos []struct {
DID string `json:"did"`
} `json:"repos"`
}
if err := json.Unmarshal(body, &parsed); err != nil {
return nil
}
out := make([]string, 0, len(parsed.Repos))
for _, repo := range parsed.Repos {
if repo.DID != "" {
out = append(out, repo.DID)
}
}
return out
}
func VerifyRelayVisibility(ctx context.Context, opts RelayVisibilityOptions) RelayVisibilityResult {
logf := opts.Log
if logf == nil {
logf = NoopLog
}
client := opts.Client
if client == nil {
client = http.DefaultClient
}
timeout := opts.PollTimeout
timeout = opt.Positive(timeout, 15*time.Second)
interval := opts.PollInterval
interval = opt.Positive(interval, 2*time.Second)
collectionPath := "/xrpc/com.atproto.sync.listReposByCollection?collection=" +
url.QueryEscape(opts.Collection) + "&limit=1000"
result := RelayVisibilityResult{CapableRelays: []string{}, IndexedBy: []string{}, Failures: []RelayFailure{}}
for _, relay := range opts.RelayURLs {
status, _, err := relayGET(ctx, client, strings.TrimRight(relay, "/")+collectionPath)
switch {
case err != nil:
result.Failures = append(result.Failures, RelayFailure{URL: relay, Reason: err.Error()})
case status == http.StatusOK:
result.CapableRelays = append(result.CapableRelays, relay)
logf("info", "relay_capable", map[string]any{"url": relay})
case status == http.StatusNotFound:
logf("info", "relay_no_collection_support", map[string]any{"url": relay})
result.Failures = append(result.Failures, RelayFailure{URL: relay, Reason: "listReposByCollection not supported (404)"})
default:
result.Failures = append(result.Failures, RelayFailure{URL: relay, Reason: fmt.Sprintf("HTTP %d", status)})
}
}
if len(result.CapableRelays) == 0 {
logf("warn", "relay_no_capable_relays", map[string]any{"total": len(opts.RelayURLs), "failures": result.Failures})
return result
}
logf("info", "relay_capable_relays", map[string]any{"count": len(result.CapableRelays), "relays": result.CapableRelays})
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) && len(result.IndexedBy) == 0 {
for _, relay := range result.CapableRelays {
status, body, err := relayGET(ctx, client, strings.TrimRight(relay, "/")+collectionPath)
if err != nil || status != http.StatusOK {
continue
}
if slices.Contains(relayDIDs(body), opts.BidderDID) {
result.IndexedBy = append(result.IndexedBy, relay)
}
}
if len(result.IndexedBy) == 0 {
select {
case <-ctx.Done():
deadline = time.Now()
case <-time.After(interval):
}
}
}
result.OK = len(result.IndexedBy) > 0
if !result.OK {
logf("warn", "relay_visibility_timeout", map[string]any{"capableRelays": result.CapableRelays, "pollTimeoutMs": timeout.Milliseconds(), "failures": result.Failures})
} else {
logf("info", "relay_visibility_confirmed", map[string]any{"indexedBy": result.IndexedBy, "capableRelays": result.CapableRelays})
}
return result
}
func DiscoverBiddersFromRelay(ctx context.Context, relayURL, collection string, timeout time.Duration, client HTTPDoer, logf LogFunc) []string {
if logf == nil {
logf = NoopLog
}
rawURL := relayCollectionURL(relayURL, collection)
if timeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, timeout)
defer cancel()
}
logf("info", "relay_discovery_query", map[string]any{"url": rawURL, "collection": collection})
status, body, err := relayGET(ctx, client, rawURL)
if err != nil {
logf("warn", "relay_discovery_error", map[string]any{"relayUrl": relayURL, "error": err.Error()})
return nil
}
if status != http.StatusOK {
logf("warn", "relay_discovery_http_error", map[string]any{"relayUrl": relayURL, "status": status, "collection": collection})
return nil
}
seen := map[string]bool{}
out := []string{}
for _, did := range relayDIDs(body) {
if seen[did] {
continue
}
seen[did] = true
out = append(out, did)
}
logf("info", "relay_discovery_result", map[string]any{"relayUrl": relayURL, "collection": collection, "count": len(out)})
return out
}
func DiscoverBiddersFromRelays(ctx context.Context, relayURLs []string, collection string, timeout time.Duration, client HTTPDoer, logf LogFunc) []string {
seen := map[string]bool{}
out := []string{}
for _, relay := range relayURLs {
for _, did := range DiscoverBiddersFromRelay(ctx, relay, collection, timeout, client, logf) {
if seen[did] {
continue
}
seen[did] = true
out = append(out, did)
}
}
return out
}
var relaysOf = ttlcache.New[string, []string](ttlcache.Options{TTL: RelaysCacheTTL, MaxEntries: 1024})
func RelayURLsOf(ctx context.Context, getter RecordGetter, did string) []string {
if getter == nil || did == "" {
return nil
}
urls, err := relaysOf.GetOrLoad(ctx, did, func(ctx context.Context) ([]string, time.Duration, error) {
rec, err := getter.GetRecord(ctx, did, RelaysNSID, RelaysRKey)
if RecordAbsent(err) {
return []string{}, RelaysCacheTTL, nil
}
if err != nil {
return nil, 0, err
}
return relayURLsIn(rec.Value), RelaysCacheTTL, nil
})
if err != nil {
return nil
}
return slices.Clone(urls)
}
func RecordAbsent(err error) bool {
if !errors.Is(err, ErrNotFound) {
return false
}
failure, ok := errors.AsType[*xrpc.Error](err)
if !ok {
return true
}
return failure.Status == http.StatusNotFound || (failure.Status == http.StatusBadRequest && failure.Name == "RecordNotFound")
}
func relayURLsIn(value map[string]any) []string {
raw, _ := value["relays"].([]any)
urls := []string{}
for _, item := range raw {
s, ok := item.(string)
if !ok {
continue
}
s = strings.TrimSpace(s)
if !(strings.HasPrefix(s, "https://") || strings.HasPrefix(s, "http://")) || slices.Contains(urls, s) {
continue
}
urls = append(urls, s)
}
return urls
}
func OfferingURI(did string) string {
return "at://" + did + "/" + OfferingNSID + "/" + OfferingRKey
}
func HeartbeatOfferingRKey(ctx context.Context, getter RecordGetter, did string) (string, error) {
rec, err := getter.GetRecord(ctx, did, HeartbeatNSID, HeartbeatRKey)
if err != nil {
return "", err
}
heartbeat, err := ParseHeartbeat(rec.Value)
if err != nil {
return "", err
}
aturi, err := syntax.ParseATURI(heartbeat.Offering)
if err != nil || aturi.Authority().String() != did || aturi.Collection().String() != OfferingNSID || aturi.RecordKey() == "" {
return "", fmt.Errorf("%w: the heartbeat of %s names %q, not an offering in its own repo", ErrInvalidRecord, did, heartbeat.Offering)
}
return aturi.RecordKey().String(), nil
}
func ReadOffering(ctx context.Context, getter RecordGetter, did string) (Offering, string, error) {
if getter == nil {
return Offering{}, "", fmt.Errorf("%w: no record getter", ErrInvalidRecord)
}
rec, err := getter.GetRecord(ctx, did, OfferingNSID, OfferingRKey)
if errors.Is(err, ErrNotFound) {
rkey, herr := HeartbeatOfferingRKey(ctx, getter, did)
switch {
case errors.Is(herr, ErrNotFound) || rkey == OfferingRKey:
return Offering{}, "", err
case herr != nil:
return Offering{}, "", herr
}
rec, err = getter.GetRecord(ctx, did, OfferingNSID, rkey)
}
if err != nil {
return Offering{}, "", err
}
offering, err := ParseOffering(rec.Value)
if err != nil {
return Offering{}, "", err
}
return *offering, rec.URI, nil
}
func OfferingApplies(offering Offering, payloadNSID string) bool {
return slices.Contains(offering.AppliesTo, payloadNSID)
}
func HeartbeatFresh(createdAt time.Time, now time.Time) bool {
return now.Sub(createdAt) <= HeartbeatTTL
}
func ReadHeartbeat(ctx context.Context, getter RecordGetter, did string, now time.Time) bool {
if getter == nil {
return false
}
rec, err := getter.GetRecord(ctx, did, HeartbeatNSID, HeartbeatRKey)
if err != nil {
return false
}
value, _ := rec.Value["createdAt"].(string)
at, err := ParseTime(value)
if err != nil || at.After(now.Add(HeartbeatMaxSkew)) {
return false
}
return HeartbeatFresh(at, now)
}
func FreshBidderDIDs(ctx context.Context, getter RecordGetter, dids []string, now time.Time) []string {
out := make([]string, 0, len(dids))
for _, did := range dids {
if ReadHeartbeat(ctx, getter, did, now) {
out = append(out, did)
}
}
return out
}
func StartOfferingRefresh(ctx context.Context, interval time.Duration, refresh func(context.Context) error, logf LogFunc) (stop func()) {
if logf == nil {
logf = NoopLog
}
interval = opt.Positive(interval, HeartbeatInterval)
runCtx, cancel := context.WithCancel(ctx)
var wg sync.WaitGroup
wg.Go(func() {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-runCtx.Done():
return
case <-ticker.C:
if err := refresh(runCtx); err != nil {
logf("warn", "offering refresh failed", map[string]any{"err": err.Error()})
}
}
}
})
return func() {
cancel()
wg.Wait()
}
}