mirror of
https://github.com/nbd-wtf/go-nostr.git
synced 2025-10-04 17:40:04 +02:00
pool.BatchedSubMany()
This commit is contained in:
53
pool.go
53
pool.go
@@ -4,12 +4,11 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"slices"
|
|
||||||
|
|
||||||
"github.com/puzpuzpuz/xsync/v3"
|
"github.com/puzpuzpuz/xsync/v3"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -25,6 +24,11 @@ type SimplePool struct {
|
|||||||
cancel context.CancelFunc
|
cancel context.CancelFunc
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type DirectedFilter struct {
|
||||||
|
Filter
|
||||||
|
Relay string
|
||||||
|
}
|
||||||
|
|
||||||
type IncomingEvent struct {
|
type IncomingEvent struct {
|
||||||
*Event
|
*Event
|
||||||
Relay *Relay
|
Relay *Relay
|
||||||
@@ -310,3 +314,48 @@ func (pool *SimplePool) QuerySingle(ctx context.Context, urls []string, filter F
|
|||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (pool *SimplePool) batchedSubMany(
|
||||||
|
ctx context.Context,
|
||||||
|
dfs []DirectedFilter,
|
||||||
|
subFn func(context.Context, []string, Filters, bool) chan IncomingEvent,
|
||||||
|
) chan IncomingEvent {
|
||||||
|
type batch struct {
|
||||||
|
filter Filter
|
||||||
|
relays []string
|
||||||
|
}
|
||||||
|
|
||||||
|
batches := make([]batch, 0, len(dfs))
|
||||||
|
for _, df := range dfs {
|
||||||
|
idx := slices.IndexFunc(batches, func(b batch) bool { return FilterEqual(b.filter, df.Filter) })
|
||||||
|
if idx != -1 {
|
||||||
|
batches[idx].relays = append(batches[idx].relays, df.Relay)
|
||||||
|
} else {
|
||||||
|
relays := make([]string, 0, 10)
|
||||||
|
relays = append(relays, df.Relay)
|
||||||
|
batches = append(batches, batch{filter: df.Filter, relays: relays})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
res := make(chan IncomingEvent)
|
||||||
|
|
||||||
|
for _, b := range batches {
|
||||||
|
go func(b batch) {
|
||||||
|
for ie := range subFn(ctx, b.relays, Filters{b.filter}, true) {
|
||||||
|
res <- ie
|
||||||
|
}
|
||||||
|
}(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
// BatchedSubMany fires subscriptions only to specific relays, but batches them when they are the same.
|
||||||
|
func (pool *SimplePool) BatchedSubMany(ctx context.Context, dfs []DirectedFilter) chan IncomingEvent {
|
||||||
|
return pool.batchedSubMany(ctx, dfs, pool.subMany)
|
||||||
|
}
|
||||||
|
|
||||||
|
// BatchedSubManyEose is like BatchedSubMany, but ends upon receiving EOSE from all relays.
|
||||||
|
func (pool *SimplePool) BatchedSubManyEose(ctx context.Context, dfs []DirectedFilter) chan IncomingEvent {
|
||||||
|
return pool.batchedSubMany(ctx, dfs, pool.subManyEose)
|
||||||
|
}
|
||||||
|
Reference in New Issue
Block a user