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
package relay
import (
"cmp"
"context"
"crypto/tls"
"errors"
"fmt"
"log/slog"
"net"
"net/http"
"path/filepath"
"strings"
"sync"
"time"
"k8s.io/utils/ptr"
"github.com/johnandersen777/socialweb-computer-kcp/api/v1alpha1"
atrelay "github.com/johnandersen777/socialweb-computer-kcp/internal/atproto/relay"
"github.com/johnandersen777/socialweb-computer-kcp/internal/bus"
"github.com/johnandersen777/socialweb-computer-kcp/internal/component"
contract "github.com/johnandersen777/socialweb-computer-kcp/internal/contract/relay"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/hostport"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/kcp"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/networkdial"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/servetls"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/strs"
"github.com/johnandersen777/socialweb-computer-kcp/internal/relay/local"
)
const (
Kind = "Relay"
PdsKind = "Pds"
AnyName = "*"
)
type Deps struct {
component.Instance
Registry *component.Registry
TLS *tls.Config
Egress component.Egress
}
type Service struct {
spec v1alpha1.RelaySpec
deps Deps
serveHost string
hostnames []string
plcURL string
insecureHTTP bool
allowedHosts []string
crawlInterval time.Duration
tlsConfig *tls.Config
mu sync.Mutex
relay *local.Relay
key component.Key
baseURL string
stopCh chan struct{}
stopOnce sync.Once
ready bool
readiness component.ReadySignal
}
func New(spec v1alpha1.RelaySpec, deps Deps) (*Service, error) {
s := &Service{
spec: spec,
deps: deps,
hostnames: append([]string(nil), spec.Hostnames...),
crawlInterval: time.Duration(ptr.Deref(spec.CrawlIntervalSeconds, 0)) * time.Second,
}
port := 0
if spec.Serve != nil {
s.serveHost = spec.Serve.Host
port = int(spec.Serve.Port)
}
if spec.Network != nil {
s.plcURL = strings.TrimRight(strings.TrimSpace(spec.Network.PLCDirectoryURL), "/")
s.insecureHTTP = strings.HasPrefix(strings.ToLower(s.plcURL), "http://")
}
if spec.TLS != nil {
s.hostnames = strs.AppendUniqueFold(s.hostnames, spec.TLS.Hostnames...)
}
if spec.Network != nil {
s.hostnames = strs.AppendUniqueFold(s.hostnames, hostport.NetworkHostnames(spec.Network, port)...)
}
if len(spec.PdsRefs) > 0 {
s.insecureHTTP = true
}
if !s.anyPDS() {
for _, ref := range spec.PdsRefs {
s.allowedHosts = strs.AppendUniqueFold(s.allowedHosts, pdsHost(refKind(ref.Kind), ref.Name))
}
}
if spec.TLS != nil && spec.TLS.Enabled {
certFile, _ := servetls.CertificateFiles(spec.TLS.CertRef, spec.Storage, s.hostnames)
tlsConfig, err := servetls.Config(certFile, deps.TLS, deps.Log)
if err != nil {
return nil, fmt.Errorf("relay: %w", err)
}
s.tlsConfig = tlsConfig
}
return s, nil
}
var _ component.Service = (*Service)(nil)
func (s *Service) stateDir() string {
if s.spec.Storage != nil && s.spec.Storage.DataDir != "" {
return s.spec.Storage.DataDir
}
return s.deps.StateDir
}
func refKind(kind string) string {
return cmp.Or(strings.TrimSpace(kind), PdsKind)
}
func pdsHost(kind, name string) string {
kind, name = hostport.Normalize(kind), hostport.Normalize(name)
if kind == "" || name == "" || name == AnyName {
return ""
}
return hostport.Normalize(kind + "." + name)
}
func (s *Service) anyPDS() bool {
for _, ref := range s.spec.PdsRefs {
if strings.TrimSpace(ref.Name) == AnyName {
return true
}
}
return false
}
func (s *Service) upstream(key component.Key) (string, bool) {
for _, ref := range s.spec.PdsRefs {
if !strings.EqualFold(refKind(ref.Kind), key.Kind) {
continue
}
name := strings.TrimSpace(ref.Name)
if name != AnyName && !strings.EqualFold(name, key.Name) {
continue
}
if host := pdsHost(key.Kind, key.Name); host != "" {
return host, true
}
}
return "", false
}
func (s *Service) observe(crawler contract.Crawler, key component.Key) {
host, ok := s.upstream(key)
if !ok {
return
}
if _, ok := s.deps.Bus.HandlerForHost(host); ok {
crawler.Crawl(host)
return
}
crawler.Forget(host)
}
func (s *Service) follow(crawler contract.Crawler) func() {
if len(s.spec.PdsRefs) == 0 {
return func() {}
}
cancel := s.deps.Registry.Subscribe(func(key component.Key) { s.observe(crawler, key) })
for _, ref := range s.spec.PdsRefs {
if strings.TrimSpace(ref.Name) != AnyName {
s.observe(crawler, component.Key{Workspace: s.deps.Self.Workspace, Kind: refKind(ref.Kind), Name: strings.TrimSpace(ref.Name)})
}
}
if s.anyPDS() {
for _, entry := range s.deps.Registry.List("") {
s.observe(crawler, entry.Key)
}
}
return cancel
}
func (s *Service) Start(ctx context.Context) error {
ctx = s.deps.Caller(ctx)
handlers := s.deps.Bus
if handlers == nil {
return errors.New("relay: no handler registry is available")
}
log := s.deps.Log
if log == nil {
log = slog.New(slog.DiscardHandler)
}
stateFile := ""
if dir := s.stateDir(); dir != "" {
stateFile = filepath.Join(dir, "relay-state.json")
}
tlsConfig := s.deps.TLS
if tlsConfig == nil {
tlsConfig = s.tlsConfig
}
hostname := hostport.Primary(s.serveHost, s.hostnames)
relay, err := local.New(ctx, local.Config{
Hostname: hostname,
PLCURL: s.plcURL,
InsecureHTTP: s.insecureHTTP,
AllowedHosts: s.allowedHosts,
StateFile: stateFile,
CrawlInterval: s.crawlInterval,
TLS: tlsConfig,
}, local.Deps{
Log: log,
HTTPClient: &http.Client{Transport: handlers.Transport(s.deps.Egress.Client(0).Transport)},
DialContext: handlerDialer(handlers, externalDialContext(s.deps.Egress)),
})
if err != nil {
return fmt.Errorf("relay: opening the crawl state: %w", err)
}
key := s.deps.Key()
key.Kind = cmp.Or(key.Kind, Kind)
key.Name = cmp.Or(key.Name, "default")
stopCh := make(chan struct{})
s.mu.Lock()
if s.stopCh != nil {
s.mu.Unlock()
relay.Core().Close()
return errors.New("relay: the service already started")
}
s.stopCh = stopCh
s.mu.Unlock()
host := kcp.KindServiceHost(key.Kind, key.Workspace)
if err := handlers.RegisterHTTP(key, relay.Handler()); err != nil {
s.mu.Lock()
s.stopCh = nil
s.mu.Unlock()
relay.Core().Close()
return fmt.Errorf("relay: registering the handler: %w", err)
}
s.mu.Lock()
s.relay = relay
s.key = key
s.baseURL = "http://" + host
s.stopOnce = sync.Once{}
s.ready = true
s.mu.Unlock()
log.Info("relay_registered", "host", host, "hostname", hostname)
s.readiness.Signal()
runCtx, cancel := context.WithCancel(ctx)
var stopper sync.WaitGroup
defer stopper.Wait()
defer cancel()
stopper.Go(func() {
select {
case <-stopCh:
cancel()
case <-runCtx.Done():
}
})
unfollow := s.follow(relay)
_ = relay.Run(runCtx)
unfollow()
s.finish()
return nil
}
func (s *Service) Ready() component.Readiness {
return &s.readiness
}
func (s *Service) Endpoints() []component.Endpoint {
s.mu.Lock()
defer s.mu.Unlock()
if !s.ready || s.baseURL == "" {
return nil
}
return []component.Endpoint{
{Name: "http", Protocol: component.ProtocolHTTP, URL: s.baseURL},
{Name: "subscribeRepos", Protocol: component.ProtocolWS, URL: "ws" + strings.TrimPrefix(s.baseURL, "http") + "/xrpc/com.atproto.sync.subscribeRepos"},
}
}
func (s *Service) Stop(ctx context.Context) error {
s.mu.Lock()
stopCh := s.stopCh
s.mu.Unlock()
if stopCh == nil {
return nil
}
s.stopOnce.Do(func() { close(stopCh) })
return nil
}
func (s *Service) Relay() *atrelay.Relay {
s.mu.Lock()
defer s.mu.Unlock()
if s.relay == nil {
return nil
}
return s.relay.Core()
}
func (s *Service) Store() atrelay.Store {
s.mu.Lock()
defer s.mu.Unlock()
if s.relay == nil {
return nil
}
return s.relay.Store()
}
func (s *Service) Address() string {
s.mu.Lock()
defer s.mu.Unlock()
if s.baseURL == "" {
return ""
}
return strings.TrimPrefix(s.baseURL, "http://")
}
func (s *Service) AddSink(sink atrelay.EventSink) {
if relay := s.Relay(); relay != nil {
relay.AddSink(sink)
}
}
func (s *Service) finish() {
s.mu.Lock()
s.ready = false
s.stopCh = nil
s.mu.Unlock()
}
func externalDialContext(egress component.Egress) func(context.Context, string, string) (net.Conn, error) {
dialer, err := networkdial.NewDialerWithOptions(networkdial.DialOptions{
Hosts: egress.Hosts,
TLSConfig: egress.TLS,
AllowSystemDNS: true,
})
if err != nil {
return (&net.Dialer{Timeout: 10 * time.Second}).DialContext
}
return dialer.DialContext
}
func handlerDialer(handlers *bus.Bus, external func(context.Context, string, string) (net.Conn, error)) func(context.Context, string, string) (net.Conn, error) {
return func(ctx context.Context, network, address string) (net.Conn, error) {
if _, ok := handlers.HandlerForHost(address); ok {
return handlers.DialHTTP(ctx, address)
}
return external(ctx, network, address)
}
}