-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpool.go
More file actions
962 lines (844 loc) · 23.6 KB
/
Copy pathpool.go
File metadata and controls
962 lines (844 loc) · 23.6 KB
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
package nostr
import (
"context"
"errors"
"fmt"
"math"
"slices"
"strings"
"sync"
"sync/atomic"
"time"
"fiatjaf.com/nostr/nip45/hyperloglog"
)
const (
seenAlreadyDropTick = time.Minute
)
// Pool manages connections to multiple relays, ensures they are reopened when necessary and not duplicated.
type Pool struct {
Relays *MapOf[string, *Relay]
Context context.Context
authRequiredHandler func(context.Context, *Event) error
cancel context.CancelCauseFunc
eventMiddleware func(RelayEvent)
duplicateMiddleware func(relay string, id ID)
queryMiddleware func(relay string, pubkey PubKey, kind Kind)
relayOptions RelayOptions
// custom things not often used
penaltyBoxMu sync.Mutex
penaltyBox map[string][2]float64
}
// DirectedFilter combines a Filter with a specific relay URL.
type DirectedFilter struct {
Filter
Relay string
}
func (df DirectedFilter) String() string {
return fmt.Sprintf("%s(%s)", df.Relay, df.Filter)
}
func (ie RelayEvent) String() string { return fmt.Sprintf("[%s] >> %s", ie.Relay.URL, ie.Event) }
// NewPool creates a new Pool with the given context and options.
func NewPool(opts PoolOptions) *Pool {
ctx, cancel := context.WithCancelCause(context.Background())
pool := &Pool{
Relays: NewMapOf[string, *Relay](),
Context: ctx,
cancel: cancel,
authRequiredHandler: opts.AuthRequiredHandler,
eventMiddleware: opts.EventMiddleware,
duplicateMiddleware: opts.DuplicateMiddleware,
queryMiddleware: opts.AuthorKindQueryMiddleware,
relayOptions: opts.RelayOptions,
}
if opts.PenaltyBox {
go pool.startPenaltyBox()
}
return pool
}
type PoolOptions struct {
// AuthRequiredHandler, if given, must be a function that signs the auth event when called.
// it will be called whenever any relay in the pool returns a `CLOSED` or `OK` message
// with the "auth-required:" prefix, only once for each relay
AuthRequiredHandler func(context.Context, *Event) error
// PenaltyBox just sets the penalty box mechanism so relays that fail to connect
// or that disconnect will be ignored for a while and we won't attempt to connect again.
PenaltyBox bool
// EventMiddleware is a function that will be called with all events received.
EventMiddleware func(RelayEvent)
// DuplicateMiddleware is a function that will be called with all duplicate ids received.
DuplicateMiddleware func(relay string, id ID)
// AuthorKindQueryMiddleware is a function that will be called with every combination of
// relay+pubkey+kind queried in a .SubscribeMany*() call -- when applicable (i.e. when the query
// contains a pubkey and a kind).
AuthorKindQueryMiddleware func(relay string, pubkey PubKey, kind Kind)
// RelayOptions are any options that should be passed to Relays instantiated by this pool
RelayOptions RelayOptions
}
func (pool *Pool) startPenaltyBox() {
pool.penaltyBox = make(map[string][2]float64)
go func() {
sleep := 30.0
for {
time.Sleep(time.Duration(sleep) * time.Second)
pool.penaltyBoxMu.Lock()
nextSleep := 300.0
for url, v := range pool.penaltyBox {
remainingSeconds := v[1]
remainingSeconds -= sleep
if remainingSeconds <= 0 {
pool.penaltyBox[url] = [2]float64{v[0], 0}
continue
} else {
pool.penaltyBox[url] = [2]float64{v[0], remainingSeconds}
}
if remainingSeconds < nextSleep {
nextSleep = remainingSeconds
}
}
sleep = nextSleep
pool.penaltyBoxMu.Unlock()
}
}()
}
// EnsureRelay ensures that a relay connection exists and is active.
// If the relay is not connected, it attempts to connect.
func (pool *Pool) EnsureRelay(url string) (*Relay, error) {
nm := NormalizeURL(url)
defer namedLock(nm)()
relay, ok := pool.Relays.Load(nm)
if ok && relay == nil {
if pool.penaltyBox != nil {
pool.penaltyBoxMu.Lock()
defer pool.penaltyBoxMu.Unlock()
v, _ := pool.penaltyBox[nm]
if v[1] > 0 {
return nil, fmt.Errorf("in penalty box, %fs remaining", v[1])
}
}
} else if ok && relay.IsConnected() {
// already connected, unlock and return
return relay, nil
}
relay = NewRelay(pool.Context, url, pool.relayOptions)
// try to connect
// we use this ctx here so when the pool dies everything dies
if err := relay.Connect(pool.Context); err != nil {
if pool.penaltyBox != nil {
// putting relay in penalty box
pool.penaltyBoxMu.Lock()
defer pool.penaltyBoxMu.Unlock()
v, _ := pool.penaltyBox[nm]
pool.penaltyBox[nm] = [2]float64{v[0] + 1, 30.0 + math.Pow(2, v[0]+1)}
}
return nil, fmt.Errorf("failed to connect: %w", err)
}
pool.Relays.Store(nm, relay)
go func(r *Relay, relayURL string) {
<-r.Context().Done()
if current, ok := pool.Relays.Load(relayURL); ok && current == r {
pool.Relays.Delete(relayURL)
}
}(relay, nm)
return relay, nil
}
// PublishResult represents the result of publishing an event to a relay.
type PublishResult struct {
Error error
RelayURL string
Relay *Relay
}
// PublishMany publishes an event to multiple relays and returns a channel of results emitted as they're received.
func (pool *Pool) PublishMany(ctx context.Context, urls []string, evt Event) chan PublishResult {
ch := make(chan PublishResult, len(urls))
wg := sync.WaitGroup{}
wg.Add(len(urls))
go func() {
for i, url := range urls {
if slices.IndexFunc(urls[0:i], func(iurl string) bool {
return NormalizeURL(url) == NormalizeURL(iurl)
}) != -1 {
// duplicated URL
wg.Done()
continue
}
go func() {
defer wg.Done()
relay, err := pool.EnsureRelay(url)
if err != nil {
ch <- PublishResult{err, url, nil}
return
}
if err := relay.Publish(ctx, evt); err == nil {
// success with no auth required
ch <- PublishResult{nil, url, relay}
} else if strings.HasPrefix(err.Error(), "msg: auth-required:") && pool.authRequiredHandler != nil {
// try to authenticate if we can
if authErr := relay.Auth(ctx, pool.authRequiredHandler); authErr == nil {
if err := relay.Publish(ctx, evt); err == nil {
// success after auth
ch <- PublishResult{nil, url, relay}
} else {
// failure after auth
ch <- PublishResult{err, url, relay}
}
} else {
// failure to auth
ch <- PublishResult{fmt.Errorf("failed to auth: %w", authErr), url, relay}
}
} else {
// direct failure
ch <- PublishResult{err, url, relay}
}
}()
}
wg.Wait()
close(ch)
}()
return ch
}
// SubscribeMany opens a subscription with the given filter to multiple relays
// the subscriptions ends when the context is canceled or when all relays return a CLOSED.
func (pool *Pool) SubscribeMany(
ctx context.Context,
urls []string,
filter Filter,
opts SubscriptionOptions,
) chan RelayEvent {
return pool.subMany(ctx, urls, filter, nil, nil, opts)
}
func (pool *Pool) FetchManyNotifyClosed(
ctx context.Context,
urls []string,
filter Filter,
opts SubscriptionOptions,
) (chan RelayEvent, chan RelayClosed) {
closedChan := make(chan RelayClosed)
events := pool.fetchMany(ctx, urls, filter, closedChan, opts)
return events, closedChan
}
// FetchMany opens a subscription, much like SubscribeMany, but it ends as soon as all Relays
// return an EOSE message.
func (pool *Pool) FetchMany(
ctx context.Context,
urls []string,
filter Filter,
opts SubscriptionOptions,
) chan RelayEvent {
return pool.fetchMany(ctx, urls, filter, nil, opts)
}
func (pool *Pool) fetchMany(
ctx context.Context,
urls []string,
filter Filter,
closedChan chan RelayClosed,
opts SubscriptionOptions,
) chan RelayEvent {
seenAlready := NewMapOf[ID, struct{}]()
if opts.CheckDuplicate == nil {
opts.CheckDuplicate = func(id ID, relay string) bool {
_, exists := seenAlready.LoadOrStore(id, struct{}{})
if exists && pool.duplicateMiddleware != nil {
pool.duplicateMiddleware(relay, id)
}
return exists
}
}
return pool.subManyEose(ctx, urls, filter, closedChan, opts)
}
// SubscribeManyNotifyEOSE is like SubscribeMany, but also returns a channel that is closed when all subscriptions have received an EOSE
func (pool *Pool) SubscribeManyNotifyEOSE(
ctx context.Context,
urls []string,
filter Filter,
opts SubscriptionOptions,
) (chan RelayEvent, chan struct{}) {
eoseChan := make(chan struct{})
events := pool.subMany(ctx, urls, filter, eoseChan, nil, opts)
return events, eoseChan
}
type RelayClosed struct {
Reason string
Relay *Relay
// this is true when the close reason was "auth-required" and already handled internally
HandledAuth bool
}
// SubscribeManyNotifyClosed is like SubscribeMany, but also returns a channel that emits every time a subscription receives a CLOSED message
func (pool *Pool) SubscribeManyNotifyClosed(
ctx context.Context,
urls []string,
filter Filter,
opts SubscriptionOptions,
) (chan RelayEvent, chan RelayClosed) {
closedChan := make(chan RelayClosed)
events := pool.subMany(ctx, urls, filter, nil, closedChan, opts)
return events, closedChan
}
type ReplaceableKey struct {
PubKey PubKey
D string
}
// FetchManyReplaceable is like FetchMany, but deduplicates replaceable and addressable events and returns
// only the latest for each "d" tag.
func (pool *Pool) FetchManyReplaceable(
ctx context.Context,
urls []string,
filter Filter,
opts SubscriptionOptions,
) *MapOf[ReplaceableKey, Event] {
ctx, cancel := context.WithCancelCause(ctx)
results := NewMapOf[ReplaceableKey, Event]()
wg := sync.WaitGroup{}
wg.Add(len(urls))
seenAlreadyLatest := NewMapOf[ReplaceableKey, Timestamp]()
opts.CheckDuplicateReplaceable = func(rk ReplaceableKey, ts Timestamp) bool {
discard := true
seenAlreadyLatest.Compute(rk, func(latest Timestamp, _ bool) (newValue Timestamp, delete bool) {
if ts > latest {
discard = false // we are going to use this, so don't discard it
return ts, false
}
return latest, false // the one we had was already more recent, so discard this
})
return discard
}
if opts.MaxWaitForEOSE == 0 {
opts.MaxWaitForEOSE = time.Second * 4
}
for _, url := range urls {
go func(nm string) {
defer wg.Done()
if mh := pool.queryMiddleware; mh != nil {
if filter.Kinds != nil && filter.Authors != nil {
for _, kind := range filter.Kinds {
for _, author := range filter.Authors {
mh(nm, author, kind)
}
}
}
}
relay, err := pool.EnsureRelay(nm)
if err != nil {
debugLogf("[pool] error connecting to %s with %v: %s", nm, filter, err)
return
}
hasAuthed := false
subscribe:
sub, err := relay.Subscribe(ctx, filter, opts)
if err != nil {
debugLogf("[pool] error subscribing to %s with %v: %s", relay, filter, err)
return
}
for {
select {
case <-ctx.Done():
return
case <-sub.EndOfStoredEvents:
return
case reason := <-sub.ClosedReason:
if strings.HasPrefix(reason, "auth-required:") && pool.authRequiredHandler != nil && !hasAuthed {
// relay is requesting auth. if we can we will perform auth and try again
err := relay.Auth(ctx, pool.authRequiredHandler)
if err == nil {
hasAuthed = true // so we don't keep doing AUTH again and again
goto subscribe
}
}
debugLogf("[pool] CLOSED from %s: '%s'\n", nm, reason)
return
case evt, more := <-sub.Events:
if !more {
return
}
ie := RelayEvent{Event: evt, Relay: relay}
if mh := pool.eventMiddleware; mh != nil {
mh(ie)
}
results.Store(ReplaceableKey{evt.PubKey, evt.Tags.GetD()}, evt)
}
}
}(NormalizeURL(url))
}
// this will happen when all subscriptions get an eose (or when they die)
wg.Wait()
cancel(errors.New("all subscriptions ended"))
return results
}
func (pool *Pool) subMany(
ctx context.Context,
urls []string,
filter Filter,
eoseChan chan struct{},
closedChan chan RelayClosed,
opts SubscriptionOptions,
) chan RelayEvent {
ctx, cancel := context.WithCancelCause(ctx)
_ = cancel // do this so `go vet` will stop complaining
events := make(chan RelayEvent)
seenAlready := NewMapOf[ID, Timestamp]()
ticker := time.NewTicker(seenAlreadyDropTick)
eoseWg := sync.WaitGroup{}
eoseWg.Add(len(urls))
if eoseChan != nil {
go func() {
eoseWg.Wait()
close(eoseChan)
}()
}
if opts.CheckDuplicate == nil {
opts.CheckDuplicate = func(id ID, relay string) bool {
_, exists := seenAlready.LoadOrStore(id, Now())
if exists && pool.duplicateMiddleware != nil {
pool.duplicateMiddleware(relay, id)
}
return exists
}
}
pendingWg := sync.WaitGroup{}
pendingWg.Add(len(urls))
go func() {
pendingWg.Wait()
close(events)
cancel(fmt.Errorf("aborted: %w", context.Cause(ctx)))
if closedChan != nil {
close(closedChan)
}
}()
for i, url := range urls {
url = NormalizeURL(url)
urls[i] = url
if idx := slices.Index(urls, url); idx != i {
// skip duplicate relays in the list
eoseWg.Done()
pendingWg.Done()
continue
}
eosed := atomic.Bool{}
go func(nm string) {
defer func() {
if eosed.CompareAndSwap(false, true) {
eoseWg.Done()
}
pendingWg.Done()
}()
hasAuthed := false
interval := 3 * time.Second
for {
if ctx.Err() != nil {
return
}
var sub *Subscription
if mh := pool.queryMiddleware; mh != nil {
if filter.Kinds != nil && filter.Authors != nil {
for _, kind := range filter.Kinds {
for _, author := range filter.Authors {
mh(nm, author, kind)
}
}
}
}
relay, err := pool.EnsureRelay(nm)
if err != nil {
// otherwise (if we were connected and got disconnected) keep trying to reconnect
debugLogf("[pool] connection to %s failed, will retry\n", nm)
goto reconnect
}
hasAuthed = false
subscribe:
sub, err = relay.Subscribe(ctx, filter, opts)
if err != nil {
debugLogf("[pool] subscription to %s failed: %s -- will retry\n", nm, err)
goto reconnect
}
go func() {
<-sub.EndOfStoredEvents
// guard here otherwise a resubscription will trigger a duplicate call to eoseWg.Done()
if eosed.CompareAndSwap(false, true) {
eoseWg.Done()
}
}()
// reset interval when we get a good subscription
interval = 3 * time.Second
for {
select {
case evt, more := <-sub.Events:
if !more {
// this means the connection was closed for weird reasons, like the server shut down
// so we will update the filters here to include only events seem from now on
// and try to reconnect until we succeed
filter.Since = Now()
debugLogf("[pool] retrying %s because sub.Events is broken\n", nm)
goto reconnect
}
ie := RelayEvent{Event: evt, Relay: relay}
if mh := pool.eventMiddleware; mh != nil {
mh(ie)
}
select {
case events <- ie:
case <-ctx.Done():
return
}
case <-ticker.C:
if eosed.Load() {
old := Timestamp(time.Now().Add(-seenAlreadyDropTick).Unix())
for id, value := range seenAlready.Range {
if value < old {
seenAlready.Delete(id)
}
}
}
case reason := <-sub.ClosedReason:
if strings.HasPrefix(reason, "auth-required:") && pool.authRequiredHandler != nil && !hasAuthed {
// relay is requesting auth. if we can we will perform auth and try again
err := relay.Auth(ctx, pool.authRequiredHandler)
if err == nil {
hasAuthed = true // so we don't keep doing AUTH again and again
if closedChan != nil {
select {
case closedChan <- RelayClosed{
Reason: reason,
Relay: relay,
HandledAuth: true,
}:
case <-ctx.Done():
}
}
goto subscribe
}
}
debugLogf("CLOSED from %s: '%s'\n", nm, reason)
if closedChan != nil {
select {
case closedChan <- RelayClosed{
Reason: reason,
Relay: relay,
}:
case <-ctx.Done():
}
}
return
case <-ctx.Done():
return
}
}
reconnect:
// we will go back to the beginning of the loop and try to connect again and again
// until the context is canceled
debugLogf("[pool] retrying %s in %s\n", nm, interval)
time.Sleep(interval)
interval = min(10*time.Minute, interval*17/10) // the next time we try we will wait longer
}
}(url)
}
return events
}
func (pool *Pool) subManyEose(
ctx context.Context,
urls []string,
filter Filter,
closedChan chan RelayClosed,
opts SubscriptionOptions,
) chan RelayEvent {
ctx, cancel := context.WithCancelCause(ctx)
events := make(chan RelayEvent)
wg := sync.WaitGroup{}
wg.Add(len(urls))
go func() {
// this will happen when all subscriptions get an eose (or when they die)
wg.Wait()
cancel(errors.New("all subscriptions ended"))
close(events)
if closedChan != nil {
close(closedChan)
}
}()
for _, url := range urls {
go func(nm string) {
defer wg.Done()
if mh := pool.queryMiddleware; mh != nil {
if filter.Kinds != nil && filter.Authors != nil {
for _, kind := range filter.Kinds {
for _, author := range filter.Authors {
mh(nm, author, kind)
}
}
}
}
relay, err := pool.EnsureRelay(nm)
if err != nil {
debugLogf("[pool] error connecting to %s with %v: %s", nm, filter, err)
return
}
hasAuthed := false
subscribe:
sub, err := relay.Subscribe(ctx, filter, opts)
if err != nil {
debugLogf("[pool] error subscribing to %s with %v: %s", relay, filter, err)
return
}
for {
select {
case <-ctx.Done():
return
case <-sub.EndOfStoredEvents:
return
case reason := <-sub.ClosedReason:
if strings.HasPrefix(reason, "auth-required:") && pool.authRequiredHandler != nil && !hasAuthed {
// relay is requesting auth. if we can we will perform auth and try again
err := relay.Auth(ctx, pool.authRequiredHandler)
if err == nil {
hasAuthed = true // so we don't keep doing AUTH again and again
if closedChan != nil {
select {
case closedChan <- RelayClosed{
Relay: relay,
Reason: reason,
HandledAuth: true,
}:
case <-ctx.Done():
}
}
goto subscribe
}
}
debugLogf("[pool] CLOSED from %s: '%s'\n", nm, reason)
if closedChan != nil {
select {
case closedChan <- RelayClosed{
Relay: relay,
Reason: reason,
}:
case <-ctx.Done():
}
}
return
case evt, more := <-sub.Events:
if !more {
return
}
ie := RelayEvent{Event: evt, Relay: relay}
if mh := pool.eventMiddleware; mh != nil {
mh(ie)
}
select {
case events <- ie:
case <-ctx.Done():
return
}
}
}
}(NormalizeURL(url))
}
return events
}
// CountMany aggregates count results from multiple relays using NIP-45 HyperLogLog
func (pool *Pool) CountMany(
ctx context.Context,
urls []string,
filter Filter,
opts SubscriptionOptions,
) int {
hll := hyperloglog.New(0) // offset is irrelevant here
wg := sync.WaitGroup{}
wg.Add(len(urls))
for _, url := range urls {
go func(nm string) {
defer wg.Done()
relay, err := pool.EnsureRelay(url)
if err != nil {
return
}
ce, err := relay.countInternal(ctx, filter, opts)
if err != nil {
return
}
if len(ce.HyperLogLog) != 256 {
return
}
hll.MergeRegisters(ce.HyperLogLog)
}(NormalizeURL(url))
}
wg.Wait()
return int(hll.Count())
}
// QuerySingle returns the first event returned by the first relay, cancels everything else.
func (pool *Pool) QuerySingle(
ctx context.Context,
urls []string,
filter Filter,
opts SubscriptionOptions,
) *RelayEvent {
ctx, cancel := context.WithCancelCause(ctx)
for ievt := range pool.FetchMany(ctx, urls, filter, opts) {
cancel(errors.New("got the first event and ended successfully"))
return &ievt
}
cancel(errors.New("SubManyEose() didn't get yield events"))
return nil
}
func (pool *Pool) BatchedQueryManyNotifyClosed(
ctx context.Context,
dfs []DirectedFilter,
opts SubscriptionOptions,
) (chan RelayEvent, chan RelayClosed) {
closedChan := make(chan RelayClosed)
events := pool.batchedQueryMany(ctx, dfs, closedChan, opts)
return events, closedChan
}
// BatchedQueryMany takes a bunch of filters and sends each to the target relay but deduplicates results smartly.
func (pool *Pool) BatchedQueryMany(
ctx context.Context,
dfs []DirectedFilter,
opts SubscriptionOptions,
) chan RelayEvent {
return pool.batchedQueryMany(ctx, dfs, nil, opts)
}
func (pool *Pool) batchedQueryMany(
ctx context.Context,
dfs []DirectedFilter,
closedChan chan RelayClosed,
opts SubscriptionOptions,
) chan RelayEvent {
res := make(chan RelayEvent)
wg := sync.WaitGroup{}
wg.Add(len(dfs))
seenAlready := NewMapOf[ID, struct{}]()
forwardWg := sync.WaitGroup{}
opts.CheckDuplicate = func(id ID, relay string) bool {
_, exists := seenAlready.LoadOrStore(id, struct{}{})
if exists && pool.duplicateMiddleware != nil {
pool.duplicateMiddleware(relay, id)
}
return exists
}
for _, df := range dfs {
go func(df DirectedFilter) {
var innerClosed chan RelayClosed
if closedChan != nil {
innerClosed = make(chan RelayClosed)
forwardWg.Add(1)
go func() {
defer forwardWg.Done()
for rc := range innerClosed {
select {
case closedChan <- rc:
case <-ctx.Done():
for range innerClosed {
}
return
}
}
}()
}
for ie := range pool.subManyEose(ctx,
[]string{df.Relay},
df.Filter,
innerClosed,
opts,
) {
select {
case res <- ie:
case <-ctx.Done():
wg.Done()
return
}
}
wg.Done()
}(df)
}
go func() {
wg.Wait()
close(res)
if closedChan != nil {
forwardWg.Wait()
close(closedChan)
}
}()
return res
}
func (pool *Pool) BatchedSubscribeManyNotifyClosed(
ctx context.Context,
dfs []DirectedFilter,
opts SubscriptionOptions,
) (chan RelayEvent, chan RelayClosed) {
closedChan := make(chan RelayClosed)
events := pool.batchedSubscribeMany(ctx, dfs, closedChan, opts)
return events, closedChan
}
// BatchedSubscribeMany is like BatchedQueryMany but keeps the subscription open.
func (pool *Pool) BatchedSubscribeMany(
ctx context.Context,
dfs []DirectedFilter,
opts SubscriptionOptions,
) chan RelayEvent {
return pool.batchedSubscribeMany(ctx, dfs, nil, opts)
}
// BatchedSubscribeMany is like BatchedQueryMany but keeps the subscription open.
func (pool *Pool) batchedSubscribeMany(
ctx context.Context,
dfs []DirectedFilter,
closedChan chan RelayClosed,
opts SubscriptionOptions,
) chan RelayEvent {
res := make(chan RelayEvent)
wg := sync.WaitGroup{}
wg.Add(len(dfs))
seenAlready := NewMapOf[ID, struct{}]()
forwardWg := sync.WaitGroup{}
opts.CheckDuplicate = func(id ID, relay string) bool {
_, exists := seenAlready.LoadOrStore(id, struct{}{})
if exists && pool.duplicateMiddleware != nil {
pool.duplicateMiddleware(relay, id)
}
return exists
}
for _, df := range dfs {
go func(df DirectedFilter) {
var innerClosed chan RelayClosed
if closedChan != nil {
innerClosed = make(chan RelayClosed)
forwardWg.Add(1)
go func() {
defer forwardWg.Done()
for rc := range innerClosed {
select {
case closedChan <- rc:
case <-ctx.Done():
for range innerClosed {
}
return
}
}
}()
}
for ie := range pool.subMany(ctx,
[]string{df.Relay},
df.Filter,
nil,
innerClosed,
opts,
) {
select {
case res <- ie:
case <-ctx.Done():
wg.Done()
return
}
}
wg.Done()
}(df)
}
go func() {
wg.Wait()
close(res)
if closedChan != nil {
forwardWg.Wait()
close(closedChan)
}
}()
return res
}
// Close closes the pool with the given reason.
func (pool *Pool) Close(reason string) {
pool.cancel(fmt.Errorf("pool closed with reason: '%s'", reason))
}