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
package local
import (
"context"
"crypto/tls"
"log/slog"
"net"
"net/http"
"strings"
"sync"
"time"
"github.com/bluesky-social/indigo/atproto/identity"
atrelay "github.com/johnandersen777/socialweb-computer-kcp/internal/atproto/relay"
contract "github.com/johnandersen777/socialweb-computer-kcp/internal/contract/relay"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/clock"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/debounce"
)
const (
FlushDelay = time.Second
CrawlTimeout = 15 * time.Second
MinCrawlBackoff = time.Second
MaxCrawlBackoff = 30 * time.Second
RecrawlParallel = 8
)
type Config struct {
Hostname string
PLCURL string
InsecureHTTP bool
AllowedHosts []string
StateFile string
CrawlInterval time.Duration
TLS *tls.Config
SeedHostsFile string
Recrawl bool
RecrawlWindow time.Duration
IdleAfter time.Duration
MaxBacklog int
StartSeq int64
}
type Deps struct {
Log *slog.Logger
HTTPClient *http.Client
DialContext func(ctx context.Context, network, address string) (net.Conn, error)
}
type Relay struct {
cfg Config
log *slog.Logger
core *atrelay.Relay
store atrelay.Store
file *fileStore
flush *debounce.Debounce
mu sync.Mutex
ctx context.Context
hosts map[string]context.CancelFunc
crawls sync.WaitGroup
}
var _ contract.Relay = (*Relay)(nil)
func New(ctx context.Context, cfg Config, deps Deps) (*Relay, error) {
log := deps.Log
if log == nil {
log = slog.New(slog.DiscardHandler)
}
r := &Relay{cfg: cfg, log: log, hosts: map[string]context.CancelFunc{}}
r.store = atrelay.NewMemoryStore()
if path := strings.TrimSpace(cfg.StateFile); path != "" {
fs, err := openFileStore(path)
if err != nil {
return nil, err
}
r.file = fs
r.store = fs
r.flush = debounce.New(FlushDelay, r.flushFile)
fs.changed = r.flush.Mark
}
if path := strings.TrimSpace(cfg.SeedHostsFile); path != "" {
added, err := seedHosts(r.store, path)
if err != nil {
return nil, err
}
log.Info("relay_seed_hosts", "path", path, "added", added)
}
startSeq := cfg.StartSeq
if r.file != nil {
startSeq = max(startSeq, r.file.seq)
}
var directory identity.Directory
plcURL := strings.TrimSuffix(strings.TrimSpace(cfg.PLCURL), "/")
if plcURL != "" && deps.HTTPClient != nil {
base := &identity.BaseDirectory{
PLCURL: plcURL,
HTTPClient: *deps.HTTPClient,
PLCClient: deps.HTTPClient,
SkipHandleVerification: true,
}
directory = identity.NewCacheDirectory(base, 100_000, time.Hour, 2*time.Minute, 5*time.Minute)
}
r.core = atrelay.New(ctx, atrelay.Config{
Hostname: cfg.Hostname,
Logger: log,
Store: r.store,
Directory: directory,
PLCURL: cfg.PLCURL,
InsecureHTTP: cfg.InsecureHTTP,
AllowedHosts: append([]string(nil), cfg.AllowedHosts...),
HTTPClient: deps.HTTPClient,
DialContext: deps.DialContext,
TLSConfig: cfg.TLS,
MaxBacklog: cfg.MaxBacklog,
StartSeq: startSeq,
IdleAfter: cfg.IdleAfter,
})
if r.file != nil {
r.file.head = r.core.Sequencer().Head
}
return r, nil
}
func (r *Relay) Handler() http.Handler { return r.core.Handler() }
func (r *Relay) Core() *atrelay.Relay { return r.core }
func (r *Relay) Store() atrelay.Store { return r.store }
func (r *Relay) Crawl(hostname string) {
hostname = strings.TrimSpace(hostname)
if hostname == "" {
return
}
r.mu.Lock()
defer r.mu.Unlock()
if cancel := r.hosts[hostname]; cancel != nil {
cancel()
}
r.hosts[hostname] = nil
if r.ctx != nil {
r.startLocked(hostname)
}
}
func (r *Relay) Forget(hostname string) {
hostname = strings.TrimSpace(hostname)
r.mu.Lock()
defer r.mu.Unlock()
if cancel := r.hosts[hostname]; cancel != nil {
cancel()
}
delete(r.hosts, hostname)
}
func (r *Relay) Run(ctx context.Context) error {
r.mu.Lock()
r.ctx = ctx
for hostname := range r.hosts {
r.startLocked(hostname)
}
r.mu.Unlock()
if r.cfg.Recrawl {
r.recrawl(ctx)
}
if r.cfg.CrawlInterval > 0 {
r.refresh(ctx, r.cfg.CrawlInterval)
} else {
<-ctx.Done()
}
r.mu.Lock()
r.ctx = nil
for hostname, cancel := range r.hosts {
if cancel != nil {
cancel()
}
r.hosts[hostname] = nil
}
r.mu.Unlock()
r.crawls.Wait()
r.core.Close()
if r.file != nil {
r.flush.Stop()
r.flushFile()
}
return nil
}
func (r *Relay) refresh(ctx context.Context, period time.Duration) {
ticker := time.NewTicker(period)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
r.mu.Lock()
hostnames := make([]string, 0, len(r.hosts))
for hostname := range r.hosts {
hostnames = append(hostnames, hostname)
}
r.mu.Unlock()
for _, hostname := range hostnames {
r.Crawl(hostname)
}
}
}
}
func (r *Relay) startLocked(hostname string) {
ctx, cancel := context.WithCancel(r.ctx)
r.hosts[hostname] = cancel
r.crawls.Go(func() {
defer cancel()
r.crawl(ctx, hostname)
})
}
func (r *Relay) crawl(ctx context.Context, hostname string) {
backoff := time.Duration(0)
for {
reqCtx, cancel := context.WithTimeout(ctx, CrawlTimeout)
err := r.core.RequestCrawl(reqCtx, hostname)
cancel()
if err == nil {
r.log.Info("relay_crawl_started", "hostname", hostname)
return
}
if ctx.Err() != nil {
return
}
backoff = min(max(backoff*2, MinCrawlBackoff), MaxCrawlBackoff)
r.log.Warn("relay_crawl_failed", "hostname", hostname, "err", err, "retry", backoff)
if !clock.Sleep(ctx, backoff) {
return
}
}
}
func (r *Relay) recrawl(ctx context.Context) {
cutoff := time.Now().Add(-r.cfg.RecrawlWindow).UnixMilli()
known := r.store.ListHosts()
var due []string
r.mu.Lock()
for _, h := range known {
if _, managed := r.hosts[h.Hostname]; managed {
continue
}
switch h.State {
case atrelay.HostTakedown:
case atrelay.HostIdle:
if r.cfg.RecrawlWindow > 0 && h.LastSeen >= cutoff {
due = append(due, h.Hostname)
}
default:
due = append(due, h.Hostname)
}
}
r.mu.Unlock()
r.log.Info("relay_recrawl", "known", len(known), "due", len(due), "window", r.cfg.RecrawlWindow.String())
slots := make(chan struct{}, RecrawlParallel)
for _, hostname := range due {
r.crawls.Go(func() {
select {
case slots <- struct{}{}:
case <-ctx.Done():
return
}
defer func() { <-slots }()
reqCtx, cancel := context.WithTimeout(ctx, CrawlTimeout)
err := r.core.RequestCrawl(reqCtx, hostname)
cancel()
if err != nil {
if ctx.Err() == nil {
r.core.SetHostState(hostname, atrelay.HostIdle)
r.log.Warn("relay_recrawl_failed", "hostname", hostname, "err", err)
}
return
}
r.log.Info("relay_recrawl_started", "hostname", hostname)
})
}
}
func (r *Relay) flushFile() {
if err := r.file.flush(); err != nil {
r.log.Warn("relay_state_flush_failed", "path", r.file.path, "err", err)
r.flush.Mark()
}
}