exponential backoff on SimplePool reconnections and only update since once.

This commit is contained in:
fiatjaf
2023-12-02 15:12:45 -03:00
parent 0e0ecb2412
commit 15f026d2c5

22
pool.go
View File

@ -91,6 +91,7 @@ func (pool *SimplePool) subMany(ctx context.Context, urls []string, filters Filt
cancel() cancel()
}() }()
interval := 3 * time.Second
for { for {
select { select {
case <-ctx.Done(): case <-ctx.Done():
@ -102,20 +103,28 @@ func (pool *SimplePool) subMany(ctx context.Context, urls []string, filters Filt
relay, err := pool.EnsureRelay(nm) relay, err := pool.EnsureRelay(nm)
if err != nil { if err != nil {
time.Sleep(3 * time.Second)
goto reconnect goto reconnect
} }
sub, err = relay.Subscribe(ctx, filters) sub, err = relay.Subscribe(ctx, filters)
if err != nil { if err != nil {
time.Sleep(3 * time.Second)
goto reconnect goto reconnect
} }
// reset interval when we get a good subscription
interval = 3 * time.Second
for { for {
select { select {
case evt, more := <-sub.Events: case evt, more := <-sub.Events:
if !more { 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
now := Now()
for i := range filters {
filters[i].Since = &now
}
goto reconnect goto reconnect
} }
if unique { if unique {
@ -148,11 +157,10 @@ func (pool *SimplePool) subMany(ctx context.Context, urls []string, filters Filt
} }
reconnect: reconnect:
// when attempting to reconnect update the `since` in filters so old events are not retrieved // we will go back to the beginning of the loop and try to connect again and again
now := Now() // until the context is canceled
for i := range filters { time.Sleep(interval)
filters[i].Since = &now interval = interval * 17 / 10 // the next time we try we will wait longer
}
} }
}(NormalizeURL(url)) }(NormalizeURL(url))
} }