fix atomicity of subscription ids.

This commit is contained in:
fiatjaf
2023-06-09 11:01:42 -03:00
parent b7ec430166
commit bc783a3a24
2 changed files with 6 additions and 7 deletions

View File

@ -5,6 +5,7 @@ import (
"fmt" "fmt"
"net/http" "net/http"
"sync" "sync"
"sync/atomic"
"time" "time"
"github.com/puzpuzpuz/xsync" "github.com/puzpuzpuz/xsync"
@ -18,7 +19,7 @@ const (
PublishStatusSucceeded Status = 1 PublishStatusSucceeded Status = 1
) )
var subscriptionIdCounter xsync.Counter var subscriptionIdCounter atomic.Int32
func (s Status) String() string { func (s Status) String() string {
switch s { switch s {
@ -403,9 +404,7 @@ func (r *Relay) QuerySync(ctx context.Context, filter Filter) ([]*Event, error)
} }
func (r *Relay) PrepareSubscription(ctx context.Context) *Subscription { func (r *Relay) PrepareSubscription(ctx context.Context) *Subscription {
current := subscriptionIdCounter.Value() current := subscriptionIdCounter.Add(1)
subscriptionIdCounter.Inc()
ctx, cancel := context.WithCancel(ctx) ctx, cancel := context.WithCancel(ctx)
return &Subscription{ return &Subscription{
@ -413,7 +412,7 @@ func (r *Relay) PrepareSubscription(ctx context.Context) *Subscription {
Context: ctx, Context: ctx,
cancel: cancel, cancel: cancel,
conn: r.Connection, conn: r.Connection,
counter: current, counter: int(current),
Events: make(chan *Event), Events: make(chan *Event),
EndOfStoredEvents: make(chan struct{}, 1), EndOfStoredEvents: make(chan struct{}, 1),
} }

View File

@ -9,7 +9,7 @@ import (
type Subscription struct { type Subscription struct {
label string label string
counter int64 counter int
conn *Connection conn *Connection
mutex sync.Mutex mutex sync.Mutex
@ -38,7 +38,7 @@ func (sub *Subscription) SetLabel(label string) {
// GetID return the Nostr subscription ID as given to the relay, it will be a sequential number, stringified. // GetID return the Nostr subscription ID as given to the relay, it will be a sequential number, stringified.
func (sub *Subscription) GetID() string { func (sub *Subscription) GetID() string {
return sub.label + ":" + strconv.FormatInt(sub.counter, 10) return sub.label + ":" + strconv.Itoa(sub.counter)
} }
// Unsub closes the subscription, sending "CLOSE" to relay as in NIP-01. // Unsub closes the subscription, sending "CLOSE" to relay as in NIP-01.