-
Notifications
You must be signed in to change notification settings - Fork 168
/
Copy pathbgs.go
1258 lines (1048 loc) · 36.1 KB
/
bgs.go
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package bgs
import (
"context"
"errors"
"fmt"
"github.com/bluesky-social/indigo/atproto/identity"
"github.com/bluesky-social/indigo/atproto/syntax"
"github.com/ipfs/go-cid"
"io"
"log/slog"
"net"
"net/http"
_ "net/http/pprof"
"net/url"
"strconv"
"strings"
"sync"
"time"
comatproto "github.com/bluesky-social/indigo/api/atproto"
"github.com/bluesky-social/indigo/cmd/relay/events"
"github.com/bluesky-social/indigo/cmd/relay/models"
"github.com/bluesky-social/indigo/xrpc"
"github.com/gorilla/websocket"
lru "github.com/hashicorp/golang-lru/v2"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
promclient "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
dto "github.com/prometheus/client_model/go"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"gorm.io/gorm"
)
var tracer = otel.Tracer("bgs")
// serverListenerBootTimeout is how long to wait for the requested server socket
// to become available for use. This is an arbitrary timeout that should be safe
// on any platform, but there's no great way to weave this timeout without
// adding another parameter to the (at time of writing) long signature of
// NewServer.
const serverListenerBootTimeout = 5 * time.Second
type BGS struct {
db *gorm.DB
slurper *Slurper
events *events.EventManager
didd identity.Directory
// TODO: work on doing away with this flag in favor of more pluggable
// pieces that abstract the need for explicit ssl checks
ssl bool
// extUserLk serializes a section of syncPDSAccount()
// TODO: at some point we will want to lock specific DIDs, this lock as is
// is overly broad, but i dont expect it to be a bottleneck for now
extUserLk sync.Mutex
validator *Validator
// Management of Socket Consumers
consumersLk sync.RWMutex
nextConsumerID uint64
consumers map[uint64]*SocketConsumer
// Account cache
userCache *lru.Cache[string, *Account]
// nextCrawlers gets forwarded POST /xrpc/com.atproto.sync.requestCrawl
nextCrawlers []*url.URL
httpClient http.Client
log *slog.Logger
inductionTraceLog *slog.Logger
config BGSConfig
}
type SocketConsumer struct {
UserAgent string
RemoteAddr string
ConnectedAt time.Time
EventsSent promclient.Counter
}
type BGSConfig struct {
SSL bool
DefaultRepoLimit int64
ConcurrencyPerPDS int64
MaxQueuePerPDS int64
// NextCrawlers gets forwarded POST /xrpc/com.atproto.sync.requestCrawl
NextCrawlers []*url.URL
ApplyPDSClientSettings func(c *xrpc.Client)
InductionTraceLog *slog.Logger
// AdminToken checked against "Authorization: Bearer {}" header
AdminToken string
}
func DefaultBGSConfig() *BGSConfig {
return &BGSConfig{
SSL: true,
DefaultRepoLimit: 100,
ConcurrencyPerPDS: 100,
MaxQueuePerPDS: 1_000,
}
}
func NewBGS(db *gorm.DB, validator *Validator, evtman *events.EventManager, didd identity.Directory, config *BGSConfig) (*BGS, error) {
if config == nil {
config = DefaultBGSConfig()
}
if err := db.AutoMigrate(DomainBan{}); err != nil {
panic(err)
}
if err := db.AutoMigrate(models.PDS{}); err != nil {
panic(err)
}
if err := db.AutoMigrate(Account{}); err != nil {
panic(err)
}
if err := db.AutoMigrate(AccountPreviousState{}); err != nil {
panic(err)
}
uc, _ := lru.New[string, *Account](1_000_000)
bgs := &BGS{
db: db,
validator: validator,
events: evtman,
didd: didd,
ssl: config.SSL,
consumersLk: sync.RWMutex{},
consumers: make(map[uint64]*SocketConsumer),
userCache: uc,
log: slog.Default().With("system", "bgs"),
config: *config,
inductionTraceLog: config.InductionTraceLog,
}
slOpts := DefaultSlurperOptions()
slOpts.SSL = config.SSL
slOpts.DefaultRepoLimit = config.DefaultRepoLimit
slOpts.ConcurrencyPerPDS = config.ConcurrencyPerPDS
slOpts.MaxQueuePerPDS = config.MaxQueuePerPDS
slOpts.Logger = bgs.log
s, err := NewSlurper(db, bgs.handleFedEvent, slOpts)
if err != nil {
return nil, err
}
bgs.slurper = s
if err := bgs.slurper.RestartAll(); err != nil {
return nil, err
}
bgs.nextCrawlers = config.NextCrawlers
bgs.httpClient.Timeout = time.Second * 5
return bgs, nil
}
func (bgs *BGS) StartMetrics(listen string) error {
http.Handle("/metrics", promhttp.Handler())
return http.ListenAndServe(listen, nil)
}
func (bgs *BGS) Start(addr string, logWriter io.Writer) error {
var lc net.ListenConfig
ctx, cancel := context.WithTimeout(context.Background(), serverListenerBootTimeout)
defer cancel()
li, err := lc.Listen(ctx, "tcp", addr)
if err != nil {
return err
}
return bgs.StartWithListener(li, logWriter)
}
func (bgs *BGS) StartWithListener(listen net.Listener, logWriter io.Writer) error {
e := echo.New()
e.Logger.SetOutput(logWriter)
e.HideBanner = true
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
AllowOrigins: []string{"*"},
AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept, echo.HeaderAuthorization},
}))
if !bgs.ssl {
e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
Format: "method=${method}, uri=${uri}, status=${status} latency=${latency_human}\n",
}))
} else {
e.Use(middleware.LoggerWithConfig(middleware.DefaultLoggerConfig))
}
// React uses a virtual router, so we need to serve the index.html for all
// routes that aren't otherwise handled or in the /assets directory.
e.File("/dash", "public/index.html")
e.File("/dash/*", "public/index.html")
e.Static("/assets", "public/assets")
e.Use(MetricsMiddleware)
e.HTTPErrorHandler = func(err error, ctx echo.Context) {
switch err := err.(type) {
case *echo.HTTPError:
if err2 := ctx.JSON(err.Code, map[string]any{
"error": err.Message,
}); err2 != nil {
bgs.log.Error("Failed to write http error", "err", err2)
}
default:
sendHeader := true
if ctx.Path() == "/xrpc/com.atproto.sync.subscribeRepos" {
sendHeader = false
}
bgs.log.Warn("HANDLER ERROR: (%s) %s", ctx.Path(), err)
if strings.HasPrefix(ctx.Path(), "/admin/") {
ctx.JSON(500, map[string]any{
"error": err.Error(),
})
return
}
if sendHeader {
ctx.Response().WriteHeader(500)
}
}
}
// TODO: this API is temporary until we formalize what we want here
e.GET("/xrpc/com.atproto.sync.subscribeRepos", bgs.EventsHandler)
e.POST("/xrpc/com.atproto.sync.requestCrawl", bgs.HandleComAtprotoSyncRequestCrawl)
e.GET("/xrpc/com.atproto.sync.listRepos", bgs.HandleComAtprotoSyncListRepos)
e.GET("/xrpc/com.atproto.sync.getRepo", bgs.HandleComAtprotoSyncGetRepo) // just returns 3xx redirect to source PDS
e.GET("/xrpc/com.atproto.sync.getLatestCommit", bgs.HandleComAtprotoSyncGetLatestCommit)
e.GET("/xrpc/_health", bgs.HandleHealthCheck)
e.GET("/_health", bgs.HandleHealthCheck)
e.GET("/", bgs.HandleHomeMessage)
admin := e.Group("/admin", bgs.checkAdminAuth)
// Slurper-related Admin API
admin.GET("/subs/getUpstreamConns", bgs.handleAdminGetUpstreamConns)
admin.GET("/subs/getEnabled", bgs.handleAdminGetSubsEnabled)
admin.GET("/subs/perDayLimit", bgs.handleAdminGetNewPDSPerDayRateLimit)
admin.POST("/subs/setEnabled", bgs.handleAdminSetSubsEnabled)
admin.POST("/subs/killUpstream", bgs.handleAdminKillUpstreamConn)
admin.POST("/subs/setPerDayLimit", bgs.handleAdminSetNewPDSPerDayRateLimit)
// Domain-related Admin API
admin.GET("/subs/listDomainBans", bgs.handleAdminListDomainBans)
admin.POST("/subs/banDomain", bgs.handleAdminBanDomain)
admin.POST("/subs/unbanDomain", bgs.handleAdminUnbanDomain)
// Repo-related Admin API
admin.POST("/repo/takeDown", bgs.handleAdminTakeDownRepo)
admin.POST("/repo/reverseTakedown", bgs.handleAdminReverseTakedown)
admin.GET("/repo/takedowns", bgs.handleAdminListRepoTakeDowns)
// PDS-related Admin API
admin.POST("/pds/requestCrawl", bgs.handleAdminRequestCrawl)
admin.GET("/pds/list", bgs.handleListPDSs)
admin.POST("/pds/changeLimits", bgs.handleAdminChangePDSRateLimits)
admin.POST("/pds/block", bgs.handleBlockPDS)
admin.POST("/pds/unblock", bgs.handleUnblockPDS)
admin.POST("/pds/addTrustedDomain", bgs.handleAdminAddTrustedDomain)
// Consumer-related Admin API
admin.GET("/consumers/list", bgs.handleAdminListConsumers)
// In order to support booting on random ports in tests, we need to tell the
// Echo instance it's already got a port, and then use its StartServer
// method to re-use that listener.
e.Listener = listen
srv := &http.Server{}
return e.StartServer(srv)
}
func (bgs *BGS) Shutdown() []error {
errs := bgs.slurper.Shutdown()
if err := bgs.events.Shutdown(context.TODO()); err != nil {
errs = append(errs, err)
}
return errs
}
type HealthStatus struct {
Status string `json:"status"`
Message string `json:"msg,omitempty"`
}
func (bgs *BGS) HandleHealthCheck(c echo.Context) error {
if err := bgs.db.Exec("SELECT 1").Error; err != nil {
bgs.log.Error("healthcheck can't connect to database", "err", err)
return c.JSON(500, HealthStatus{Status: "error", Message: "can't connect to database"})
} else {
return c.JSON(200, HealthStatus{Status: "ok"})
}
}
var homeMessage string = `
.########..########.##..........###....##....##
.##.....##.##.......##.........##.##....##..##.
.##.....##.##.......##........##...##....####..
.########..######...##.......##.....##....##...
.##...##...##.......##.......#########....##...
.##....##..##.......##.......##.....##....##...
.##.....##.########.########.##.....##....##...
This is an atproto [https://atproto.com] relay instance, running the 'relay' codebase [https://github.com/bluesky-social/indigo]
The firehose WebSocket path is at: /xrpc/com.atproto.sync.subscribeRepos
`
func (bgs *BGS) HandleHomeMessage(c echo.Context) error {
return c.String(http.StatusOK, homeMessage)
}
const authorizationBearerPrefix = "Bearer "
func (bgs *BGS) checkAdminAuth(next echo.HandlerFunc) echo.HandlerFunc {
return func(e echo.Context) error {
authheader := e.Request().Header.Get("Authorization")
if !strings.HasPrefix(authheader, authorizationBearerPrefix) {
return echo.ErrForbidden
}
token := authheader[len(authorizationBearerPrefix):]
if bgs.config.AdminToken != token {
return echo.ErrForbidden
}
return next(e)
}
}
type Account struct {
ID models.Uid `gorm:"primarykey"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt gorm.DeletedAt `gorm:"index"`
Did string `gorm:"uniqueIndex"`
PDS uint // foreign key on models.PDS.ID
// TakenDown is set to true if the user in question has been taken down by an admin action at this relay.
// A user in this state will have all future events related to it dropped
// and no data about this user will be served.
TakenDown bool
// UpstreamStatus is the state of the user as reported by the upstream PDS through #account messages.
// Additionally, the non-standard string "active" is set to represent an upstream #account message with the active bool true.
UpstreamStatus string `gorm:"index"`
lk sync.Mutex
}
func (account *Account) GetDid() string {
return account.Did
}
func (account *Account) GetUid() models.Uid {
return account.ID
}
func (account *Account) SetTakenDown(v bool) {
account.lk.Lock()
defer account.lk.Unlock()
account.TakenDown = v
}
func (account *Account) GetTakenDown() bool {
account.lk.Lock()
defer account.lk.Unlock()
return account.TakenDown
}
func (account *Account) SetPDS(pdsId uint) {
account.lk.Lock()
defer account.lk.Unlock()
account.PDS = pdsId
}
func (account *Account) GetPDS() uint {
account.lk.Lock()
defer account.lk.Unlock()
return account.PDS
}
func (account *Account) SetUpstreamStatus(v string) {
account.lk.Lock()
defer account.lk.Unlock()
account.UpstreamStatus = v
}
func (account *Account) GetUpstreamStatus() string {
account.lk.Lock()
defer account.lk.Unlock()
return account.UpstreamStatus
}
type AccountPreviousState struct {
Uid models.Uid `gorm:"column:uid;primaryKey"`
Cid models.DbCID `gorm:"column:cid"`
Rev string `gorm:"column:rev"`
Seq int64 `gorm:"column:seq"`
}
func (ups *AccountPreviousState) GetCid() cid.Cid {
return ups.Cid.CID
}
func (ups *AccountPreviousState) GetRev() syntax.TID {
xt, _ := syntax.ParseTID(ups.Rev)
return xt
}
type addTargetBody struct {
Host string `json:"host"`
}
func (bgs *BGS) registerConsumer(c *SocketConsumer) uint64 {
bgs.consumersLk.Lock()
defer bgs.consumersLk.Unlock()
id := bgs.nextConsumerID
bgs.nextConsumerID++
bgs.consumers[id] = c
return id
}
func (bgs *BGS) cleanupConsumer(id uint64) {
bgs.consumersLk.Lock()
defer bgs.consumersLk.Unlock()
c := bgs.consumers[id]
var m = &dto.Metric{}
if err := c.EventsSent.Write(m); err != nil {
bgs.log.Error("failed to get sent counter", "err", err)
}
bgs.log.Info("consumer disconnected",
"consumer_id", id,
"remote_addr", c.RemoteAddr,
"user_agent", c.UserAgent,
"events_sent", m.Counter.GetValue())
delete(bgs.consumers, id)
}
// GET+websocket /xrpc/com.atproto.sync.subscribeRepos
func (bgs *BGS) EventsHandler(c echo.Context) error {
var since *int64
if sinceVal := c.QueryParam("cursor"); sinceVal != "" {
sval, err := strconv.ParseInt(sinceVal, 10, 64)
if err != nil {
return err
}
since = &sval
}
ctx, cancel := context.WithCancel(c.Request().Context())
defer cancel()
conn, err := websocket.Upgrade(c.Response(), c.Request(), c.Response().Header(), 10<<10, 10<<10)
if err != nil {
return fmt.Errorf("upgrading websocket: %w", err)
}
defer conn.Close()
lastWriteLk := sync.Mutex{}
lastWrite := time.Now()
// Start a goroutine to ping the client every 30 seconds to check if it's
// still alive. If the client doesn't respond to a ping within 5 seconds,
// we'll close the connection and teardown the consumer.
go func() {
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
lastWriteLk.Lock()
lw := lastWrite
lastWriteLk.Unlock()
if time.Since(lw) < 30*time.Second {
continue
}
if err := conn.WriteControl(websocket.PingMessage, []byte{}, time.Now().Add(5*time.Second)); err != nil {
bgs.log.Warn("failed to ping client", "err", err)
cancel()
return
}
case <-ctx.Done():
return
}
}
}()
conn.SetPingHandler(func(message string) error {
err := conn.WriteControl(websocket.PongMessage, []byte(message), time.Now().Add(time.Second*60))
if err == websocket.ErrCloseSent {
return nil
} else if e, ok := err.(net.Error); ok && e.Temporary() {
return nil
}
return err
})
// Start a goroutine to read messages from the client and discard them.
go func() {
for {
_, _, err := conn.ReadMessage()
if err != nil {
bgs.log.Warn("failed to read message from client", "err", err)
cancel()
return
}
}
}()
ident := c.RealIP() + "-" + c.Request().UserAgent()
evts, cleanup, err := bgs.events.Subscribe(ctx, ident, func(evt *events.XRPCStreamEvent) bool { return true }, since)
if err != nil {
return err
}
defer cleanup()
// Keep track of the consumer for metrics and admin endpoints
consumer := SocketConsumer{
RemoteAddr: c.RealIP(),
UserAgent: c.Request().UserAgent(),
ConnectedAt: time.Now(),
}
sentCounter := eventsSentCounter.WithLabelValues(consumer.RemoteAddr, consumer.UserAgent)
consumer.EventsSent = sentCounter
consumerID := bgs.registerConsumer(&consumer)
defer bgs.cleanupConsumer(consumerID)
logger := bgs.log.With(
"consumer_id", consumerID,
"remote_addr", consumer.RemoteAddr,
"user_agent", consumer.UserAgent,
)
logger.Info("new consumer", "cursor", since)
for {
select {
case evt, ok := <-evts:
if !ok {
logger.Error("event stream closed unexpectedly")
return nil
}
wc, err := conn.NextWriter(websocket.BinaryMessage)
if err != nil {
logger.Error("failed to get next writer", "err", err)
return err
}
if evt.Preserialized != nil {
_, err = wc.Write(evt.Preserialized)
} else {
err = evt.Serialize(wc)
}
if err != nil {
return fmt.Errorf("failed to write event: %w", err)
}
if err := wc.Close(); err != nil {
logger.Warn("failed to flush-close our event write", "err", err)
return nil
}
lastWriteLk.Lock()
lastWrite = time.Now()
lastWriteLk.Unlock()
sentCounter.Inc()
case <-ctx.Done():
return nil
}
}
}
// domainIsBanned checks if the given host is banned, starting with the host
// itself, then checking every parent domain up to the tld
func (s *BGS) domainIsBanned(ctx context.Context, host string) (bool, error) {
// ignore ports when checking for ban status
hostport := strings.Split(host, ":")
segments := strings.Split(hostport[0], ".")
// TODO: use normalize method once that merges
var cleaned []string
for _, s := range segments {
if s == "" {
continue
}
s = strings.ToLower(s)
cleaned = append(cleaned, s)
}
segments = cleaned
for i := 0; i < len(segments)-1; i++ {
dchk := strings.Join(segments[i:], ".")
found, err := s.findDomainBan(ctx, dchk)
if err != nil {
return false, err
}
if found {
return true, nil
}
}
return false, nil
}
func (s *BGS) findDomainBan(ctx context.Context, host string) (bool, error) {
var db DomainBan
if err := s.db.Find(&db, "domain = ?", host).Error; err != nil {
return false, err
}
if db.ID == 0 {
return false, nil
}
return true, nil
}
var ErrNotFound = errors.New("not found")
func (bgs *BGS) DidToUid(ctx context.Context, did string) (models.Uid, error) {
xu, err := bgs.lookupUserByDid(ctx, did)
if err != nil {
return 0, err
}
if xu == nil {
return 0, ErrNotFound
}
return xu.ID, nil
}
func (bgs *BGS) lookupUserByDid(ctx context.Context, did string) (*Account, error) {
ctx, span := tracer.Start(ctx, "lookupUserByDid")
defer span.End()
cu, ok := bgs.userCache.Get(did)
if ok {
return cu, nil
}
var u Account
if err := bgs.db.Find(&u, "did = ?", did).Error; err != nil {
return nil, err
}
if u.ID == 0 {
return nil, gorm.ErrRecordNotFound
}
bgs.userCache.Add(did, &u)
return &u, nil
}
func (bgs *BGS) lookupUserByUID(ctx context.Context, uid models.Uid) (*Account, error) {
ctx, span := tracer.Start(ctx, "lookupUserByUID")
defer span.End()
var u Account
if err := bgs.db.Find(&u, "id = ?", uid).Error; err != nil {
return nil, err
}
if u.ID == 0 {
return nil, gorm.ErrRecordNotFound
}
return &u, nil
}
// handleFedEvent() is the callback passed to Slurper called from Slurper.handleConnection()
func (bgs *BGS) handleFedEvent(ctx context.Context, host *models.PDS, env *events.XRPCStreamEvent) error {
ctx, span := tracer.Start(ctx, "handleFedEvent")
defer span.End()
start := time.Now()
defer func() {
eventsHandleDuration.WithLabelValues(host.Host).Observe(time.Since(start).Seconds())
}()
eventsReceivedCounter.WithLabelValues(host.Host).Add(1)
switch {
case env.RepoCommit != nil:
repoCommitsReceivedCounter.WithLabelValues(host.Host).Add(1)
return bgs.handleCommit(ctx, host, env.RepoCommit)
case env.RepoSync != nil:
repoSyncReceivedCounter.WithLabelValues(host.Host).Add(1)
return bgs.handleSync(ctx, host, env.RepoSync)
case env.RepoHandle != nil:
eventsWarningsCounter.WithLabelValues(host.Host, "handle").Add(1)
// TODO: rate limit warnings per PDS before we (temporarily?) block them
return nil
case env.RepoIdentity != nil:
bgs.log.Info("bgs got identity event", "did", env.RepoIdentity.Did)
// Flush any cached DID documents for this user
bgs.purgeDidCache(ctx, env.RepoIdentity.Did)
// Refetch the DID doc and update our cached keys and handle etc.
account, err := bgs.syncPDSAccount(ctx, env.RepoIdentity.Did, host, nil)
if err != nil {
return err
}
// Broadcast the identity event to all consumers
err = bgs.events.AddEvent(ctx, &events.XRPCStreamEvent{
RepoIdentity: &comatproto.SyncSubscribeRepos_Identity{
Did: env.RepoIdentity.Did,
Seq: env.RepoIdentity.Seq,
Time: env.RepoIdentity.Time,
Handle: env.RepoIdentity.Handle,
},
PrivUid: account.ID,
})
if err != nil {
bgs.log.Error("failed to broadcast Identity event", "error", err, "did", env.RepoIdentity.Did)
return fmt.Errorf("failed to broadcast Identity event: %w", err)
}
return nil
case env.RepoAccount != nil:
span.SetAttributes(
attribute.String("did", env.RepoAccount.Did),
attribute.Int64("seq", env.RepoAccount.Seq),
attribute.Bool("active", env.RepoAccount.Active),
)
if env.RepoAccount.Status != nil {
span.SetAttributes(attribute.String("repo_status", *env.RepoAccount.Status))
}
bgs.log.Info("bgs got account event", "did", env.RepoAccount.Did)
if !env.RepoAccount.Active && env.RepoAccount.Status == nil {
accountVerifyWarnings.WithLabelValues(host.Host, "nostat").Inc()
return nil
}
// Flush any cached DID documents for this user
bgs.purgeDidCache(ctx, env.RepoAccount.Did)
// Refetch the DID doc to make sure the PDS is still authoritative
account, err := bgs.syncPDSAccount(ctx, env.RepoAccount.Did, host, nil)
if err != nil {
span.RecordError(err)
return err
}
// Check if the PDS is still authoritative
// if not we don't want to be propagating this account event
if account.GetPDS() != host.ID {
bgs.log.Error("account event from non-authoritative pds",
"seq", env.RepoAccount.Seq,
"did", env.RepoAccount.Did,
"event_from", host.Host,
"did_doc_declared_pds", account.GetPDS(),
"account_evt", env.RepoAccount,
)
return fmt.Errorf("event from non-authoritative pds")
}
// Process the account status change
repoStatus := events.AccountStatusActive
if !env.RepoAccount.Active && env.RepoAccount.Status != nil {
repoStatus = *env.RepoAccount.Status
}
account.SetUpstreamStatus(repoStatus)
err = bgs.db.Save(account).Error
if err != nil {
span.RecordError(err)
return fmt.Errorf("failed to update account status: %w", err)
}
shouldBeActive := env.RepoAccount.Active
status := env.RepoAccount.Status
// override with local status
if account.GetTakenDown() {
shouldBeActive = false
status = &events.AccountStatusTakendown
}
// Broadcast the account event to all consumers
err = bgs.events.AddEvent(ctx, &events.XRPCStreamEvent{
RepoAccount: &comatproto.SyncSubscribeRepos_Account{
Active: shouldBeActive,
Did: env.RepoAccount.Did,
Seq: env.RepoAccount.Seq,
Status: status,
Time: env.RepoAccount.Time,
},
PrivUid: account.ID,
})
if err != nil {
bgs.log.Error("failed to broadcast Account event", "error", err, "did", env.RepoAccount.Did)
return fmt.Errorf("failed to broadcast Account event: %w", err)
}
return nil
case env.RepoMigrate != nil:
eventsWarningsCounter.WithLabelValues(host.Host, "migrate").Add(1)
// TODO: rate limit warnings per PDS before we (temporarily?) block them
return nil
case env.RepoTombstone != nil:
eventsWarningsCounter.WithLabelValues(host.Host, "tombstone").Add(1)
// TODO: rate limit warnings per PDS before we (temporarily?) block them
return nil
default:
return fmt.Errorf("invalid fed event")
}
}
func (bgs *BGS) newUser(ctx context.Context, host *models.PDS, did string) (*Account, error) {
newUsersDiscovered.Inc()
start := time.Now()
account, err := bgs.syncPDSAccount(ctx, did, host, nil)
newUserDiscoveryDuration.Observe(time.Since(start).Seconds())
if err != nil {
repoCommitsResultCounter.WithLabelValues(host.Host, "uerr").Inc()
return nil, fmt.Errorf("fed event create external user: %w", err)
}
return account, nil
}
var ErrCommitNoUser = errors.New("commit no user")
func (bgs *BGS) handleCommit(ctx context.Context, host *models.PDS, evt *comatproto.SyncSubscribeRepos_Commit) error {
bgs.log.Debug("bgs got repo append event", "seq", evt.Seq, "pdsHost", host.Host, "repo", evt.Repo)
account, err := bgs.lookupUserByDid(ctx, evt.Repo)
if err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {
repoCommitsResultCounter.WithLabelValues(host.Host, "nou").Inc()
return fmt.Errorf("looking up event user: %w", err)
}
account, err = bgs.newUser(ctx, host, evt.Repo)
if err != nil {
repoCommitsResultCounter.WithLabelValues(host.Host, "nuerr").Inc()
return err
}
}
if account == nil {
repoCommitsResultCounter.WithLabelValues(host.Host, "nou2").Inc()
return ErrCommitNoUser
}
ustatus := account.GetUpstreamStatus()
if account.GetTakenDown() || ustatus == events.AccountStatusTakendown {
bgs.log.Debug("dropping commit event from taken down user", "did", evt.Repo, "seq", evt.Seq, "pdsHost", host.Host)
repoCommitsResultCounter.WithLabelValues(host.Host, "tdu").Inc()
return nil
}
if ustatus == events.AccountStatusSuspended {
bgs.log.Debug("dropping commit event from suspended user", "did", evt.Repo, "seq", evt.Seq, "pdsHost", host.Host)
repoCommitsResultCounter.WithLabelValues(host.Host, "susu").Inc()
return nil
}
if ustatus == events.AccountStatusDeactivated {
bgs.log.Debug("dropping commit event from deactivated user", "did", evt.Repo, "seq", evt.Seq, "pdsHost", host.Host)
repoCommitsResultCounter.WithLabelValues(host.Host, "du").Inc()
return nil
}
if evt.Rebase {
repoCommitsResultCounter.WithLabelValues(host.Host, "rebase").Inc()
return fmt.Errorf("rebase was true in event seq:%d,host:%s", evt.Seq, host.Host)
}
accountPDSId := account.GetPDS()
if host.ID != accountPDSId && accountPDSId != 0 {
bgs.log.Warn("received event for repo from different pds than expected", "repo", evt.Repo, "expPds", accountPDSId, "gotPds", host.Host)
// Flush any cached DID documents for this user
bgs.purgeDidCache(ctx, evt.Repo)
account, err = bgs.syncPDSAccount(ctx, evt.Repo, host, account)
if err != nil {
repoCommitsResultCounter.WithLabelValues(host.Host, "uerr2").Inc()
return err
}
if account.GetPDS() != host.ID {
repoCommitsResultCounter.WithLabelValues(host.Host, "noauth").Inc()
return fmt.Errorf("event from non-authoritative pds")
}
}
var prevState AccountPreviousState
err = bgs.db.First(&prevState, account.ID).Error
prevP := &prevState
if errors.Is(err, gorm.ErrRecordNotFound) {
prevP = nil
} else if err != nil {
bgs.log.Error("failed to get previous root", "err", err)
prevP = nil
}
dbPrevRootStr := ""
dbPrevSeqStr := ""
if prevP != nil {
if prevState.Seq >= evt.Seq && ((prevState.Seq - evt.Seq) < 2000) {
// ignore catchup overlap of 200 on some subscribeRepos restarts
repoCommitsResultCounter.WithLabelValues(host.Host, "dup").Inc()
return nil
}
dbPrevRootStr = prevState.Cid.CID.String()
dbPrevSeqStr = strconv.FormatInt(prevState.Seq, 10)
}
evtPrevDataStr := ""
if evt.PrevData != nil {
evtPrevDataStr = ((*cid.Cid)(evt.PrevData)).String()
}
newRootCid, err := bgs.validator.HandleCommit(ctx, host, account, evt, prevP)
if err != nil {
bgs.inductionTraceLog.Error("commit bad", "seq", evt.Seq, "pseq", dbPrevSeqStr, "pdsHost", host.Host, "repo", evt.Repo, "prev", evtPrevDataStr, "dbprev", dbPrevRootStr, "err", err)
bgs.log.Warn("failed handling event", "err", err, "pdsHost", host.Host, "seq", evt.Seq, "repo", account.Did, "commit", evt.Commit.String())
repoCommitsResultCounter.WithLabelValues(host.Host, "err").Inc()
return fmt.Errorf("handle user event failed: %w", err)
} else {
// store now verified new repo state
err = bgs.upsertPrevState(account.ID, newRootCid, evt.Rev, evt.Seq)
if err != nil {
return fmt.Errorf("failed to set previous root uid=%d: %w", account.ID, err)
}
}
repoCommitsResultCounter.WithLabelValues(host.Host, "ok").Inc()
// Broadcast the identity event to all consumers
commitCopy := *evt
err = bgs.events.AddEvent(ctx, &events.XRPCStreamEvent{
RepoCommit: &commitCopy,
PrivUid: account.GetUid(),
})
if err != nil {
bgs.log.Error("failed to broadcast commit event", "error", err, "did", evt.Repo)
return fmt.Errorf("failed to broadcast commit event: %w", err)
}
return nil
}
// handleSync processes #sync messages
func (bgs *BGS) handleSync(ctx context.Context, host *models.PDS, evt *comatproto.SyncSubscribeRepos_Sync) error {
account, err := bgs.lookupUserByDid(ctx, evt.Did)
if err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {
repoCommitsResultCounter.WithLabelValues(host.Host, "nou").Inc()
return fmt.Errorf("looking up event user: %w", err)
}
account, err = bgs.newUser(ctx, host, evt.Did)
}
if err != nil {