added sub.mutex handling in the relay Connect() function (#37)

This commit is contained in:
barkyq
2023-01-15 07:19:00 -05:00
committed by GitHub
parent 635c1b0132
commit a37ffacc74
3 changed files with 25 additions and 8 deletions

View File

@@ -46,6 +46,9 @@ type Relay struct {
okCallbacks s.MapOf[string, func(bool)]
}
// RelayConnect returns a relay object connected to url
// Once successfully connected, cancelling ctx has no effect
// To close the connection, call r.Close()
func RelayConnect(ctx context.Context, url string) (*Relay, error) {
r := &Relay{URL: NormalizeURL(url)}
err := r.Connect(ctx)
@@ -141,13 +144,14 @@ func (r *Relay) Connect(ctx context.Context) error {
}
// check if the event matches the desired filter, ignore otherwise
if !subscription.Filters.Match(&event) {
continue
}
if !subscription.stopped {
func() {
subscription.mutex.Lock()
defer subscription.mutex.Unlock()
if !subscription.Filters.Match(&event) || subscription.stopped {
return
}
subscription.Events <- event
}
}()
}
case "EOSE":
if len(jsonMessage) < 2 {
@@ -181,6 +185,8 @@ func (r *Relay) Connect(ctx context.Context) error {
return nil
}
// Publish sends an "EVENT" command to the relay r as in NIP-01
// status can be: success, failed, or sent (no response from relay before ctx times out)
func (r *Relay) Publish(ctx context.Context, event Event) Status {
status := PublishStatusFailed
@@ -236,6 +242,9 @@ func (r *Relay) Publish(ctx context.Context, event Event) Status {
}
}
// Subscribe sends a "REQ" command to the relay r as in NIP-01
// Events are returned through the channel sub.Events
// the subscription is closed when context ctx is cancelled ("CLOSE" in NIP-01)
func (r *Relay) Subscribe(ctx context.Context, filters Filters) *Subscription {
if r.Connection == nil {
panic(fmt.Errorf("must call .Connect() first before calling .Subscribe()"))