nip77: more interface fixes to prevent channel deadlock.

This commit is contained in:
fiatjaf
2025-11-13 16:11:21 -03:00
parent e6dd124042
commit c20ca669cd
4 changed files with 50 additions and 62 deletions

View File

@@ -41,11 +41,10 @@ func (r *Relay) newConnection(ctx context.Context, tlsConfig *tls.Config) error
ticker := time.NewTicker(29 * time.Second) ticker := time.NewTicker(29 * time.Second)
// main websocket loop // main websocket loop
writeQueue := make(chan writeRequest)
readQueue := make(chan string) readQueue := make(chan string)
r.conn = c r.conn = c
r.writeQueue = writeQueue r.writeQueue = make(chan writeRequest)
r.closed = &atomic.Bool{} r.closed = &atomic.Bool{}
r.closedNotify = make(chan struct{}) r.closedNotify = make(chan struct{})
@@ -67,7 +66,7 @@ func (r *Relay) newConnection(ctx context.Context, tlsConfig *tls.Config) error
r.closeConnection(ws.StatusAbnormalClosure, "ping took too long") r.closeConnection(ws.StatusAbnormalClosure, "ping took too long")
return return
} }
case wr := <-writeQueue: case wr := <-r.writeQueue:
debugLogf("{%s} sending '%v'\n", r.URL, string(wr.msg)) debugLogf("{%s} sending '%v'\n", r.URL, string(wr.msg))
ctx, cancel := context.WithTimeoutCause(ctx, time.Second*10, errors.New("write took too long")) ctx, cancel := context.WithTimeoutCause(ctx, time.Second*10, errors.New("write took too long"))
err := c.Write(ctx, ws.MessageText, wr.msg) err := c.Write(ctx, ws.MessageText, wr.msg)

View File

@@ -192,13 +192,15 @@ func (n *Negentropy) reconcileAux(reader *bytes.Reader) ([]byte, error) {
if _, theyHave := theirItems[item.ID]; theyHave { if _, theyHave := theirItems[item.ID]; theyHave {
// if we have and they have, ignore // if we have and they have, ignore
delete(theirItems, item.ID) delete(theirItems, item.ID)
} else if n.Haves != nil { } else {
if n.Haves != nil {
// if we have and they don't, notify client // if we have and they don't, notify client
if n.isClient { if n.isClient {
n.Haves <- item.ID n.Haves <- item.ID
} }
} }
} }
}
if n.isClient && n.HaveNots != nil { if n.isClient && n.HaveNots != nil {
// notify client of what they have and we don't // notify client of what they have and we don't

View File

@@ -34,7 +34,7 @@ func NegentropySync(
// handle ids received on each direction, usually called with Sync() so the corresponding events are // handle ids received on each direction, usually called with Sync() so the corresponding events are
// fetched from the source and published to the target // fetched from the source and published to the target
handle func(ctx context.Context, wg *sync.WaitGroup, directions []Direction), handle func(ctx context.Context, directions Direction),
) error { ) error {
id := "nl-tmp" // for now we can't have more than one subscription in the same connection id := "nl-tmp" // for now we can't have more than one subscription in the same connection
@@ -76,23 +76,6 @@ func NegentropySync(
return err return err
} }
// setup sync flows: up, down or both
directions := make([]Direction, 0, 2)
if source != nil {
directions = append(directions, Direction{
From: source,
To: relay,
Items: neg.Haves,
})
}
if target != nil {
directions = append(directions, Direction{
From: relay,
To: target,
Items: neg.HaveNots,
})
}
// fill our local vector // fill our local vector
var usedSource nostr.Querier var usedSource nostr.Querier
if source != nil { if source != nil {
@@ -125,8 +108,25 @@ func NegentropySync(
wg := sync.WaitGroup{} wg := sync.WaitGroup{}
// handle emitted events // handle emitted events from either direction
wg.Go(func() { handle(ctx, &wg, directions) }) if source != nil {
wg.Go(func() {
handle(ctx, Direction{
From: source,
To: relay,
Items: neg.Haves,
})
})
}
if target != nil {
wg.Go(func() {
handle(ctx, Direction{
From: relay,
To: target,
Items: neg.HaveNots,
})
})
}
go func() { go func() {
wg.Wait() wg.Wait()
@@ -141,41 +141,27 @@ func NegentropySync(
return nil return nil
} }
func SyncEventsFromIDs(ctx context.Context, wg *sync.WaitGroup, directions []Direction) { func SyncEventsFromIDs(ctx context.Context, dir Direction) {
pool := sync.Pool{ // this is only necessary because relays are too ratelimiting
New: func() any { return make([]nostr.ID, 0, 50) }, batch := make([]nostr.ID, 0, 50)
}
for _, dir := range directions {
wg.Go(func() {
seen := make(map[nostr.ID]struct{}) seen := make(map[nostr.ID]struct{})
doSync := func(ids []nostr.ID) {
defer pool.Put(ids)
if len(ids) == 0 {
return
}
for evt := range dir.From.QueryEvents(nostr.Filter{IDs: ids}) {
dir.To.Publish(ctx, evt)
}
}
ids := pool.Get().([]nostr.ID)
for item := range dir.Items { for item := range dir.Items {
if _, ok := seen[item]; ok { if _, ok := seen[item]; ok {
continue continue
} }
seen[item] = struct{}{} seen[item] = struct{}{}
ids = append(ids, item) batch = append(batch, item)
if len(ids) == 50 { if len(batch) == 50 {
wg.Add(1) for evt := range dir.From.QueryEvents(nostr.Filter{IDs: batch}) {
wg.Go(func() { doSync(ids) }) dir.To.Publish(ctx, evt)
ids = pool.Get().([]nostr.ID) }
batch = batch[:0]
} }
} }
wg.Go(func() { doSync(ids) })
}) for evt := range dir.From.QueryEvents(nostr.Filter{IDs: batch}) {
dir.To.Publish(ctx, evt)
} }
} }

View File

@@ -157,7 +157,7 @@ func (r *Relay) handleMessage(message string) {
envelope, err := ParseMessage(message) envelope, err := ParseMessage(message)
if envelope == nil { if envelope == nil {
if r.customHandler != nil && err == UnknownLabel { if r.customHandler != nil && err == UnknownLabel {
r.customHandler(message) go r.customHandler(message)
} }
return return
} }
@@ -230,6 +230,7 @@ func (r *Relay) Write(msg []byte) {
return return
default: default:
} }
select { select {
case <-r.connectionContext.Done(): case <-r.connectionContext.Done():
case r.writeQueue <- writeRequest{msg: msg, answer: nil}: case r.writeQueue <- writeRequest{msg: msg, answer: nil}: