Skip to content

Commit

Permalink
support handling CLOSED messages from relay client.
Browse files Browse the repository at this point in the history
  • Loading branch information
fiatjaf committed Nov 28, 2023
1 parent fa20f84 commit 7449f25
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 1 deletion.
5 changes: 5 additions & 0 deletions relay.go
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,10 @@ func (r *Relay) Connect(ctx context.Context) error {
if subscription, ok := r.Subscriptions.Load(string(*env)); ok {
subscription.dispatchEose()
}
case *ClosedEnvelope:
if subscription, ok := r.Subscriptions.Load(string(env.SubscriptionID)); ok {
subscription.dispatchClosed(env.Reason)
}
case *CountEnvelope:
if subscription, ok := r.Subscriptions.Load(string(env.SubscriptionID)); ok && env.Count != nil && subscription.countResult != nil {
subscription.countResult <- *env.Count
Expand Down Expand Up @@ -478,6 +482,7 @@ func (r *Relay) PrepareSubscription(ctx context.Context, filters Filters, opts .
counter: int(current),
Events: make(chan *Event),
EndOfStoredEvents: make(chan struct{}),
ClosedReason: make(chan string, 1),
Filters: filters,
}

Expand Down
11 changes: 11 additions & 0 deletions subscription.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,15 @@ type Subscription struct {
// the EndOfStoredEvents channel gets closed when an EOSE comes for that subscription
EndOfStoredEvents chan struct{}

// the ClosedReason channel emits the reason when a CLOSED message is received
ClosedReason chan string

// Context will be .Done() when the subscription ends
Context context.Context

live atomic.Bool
eosed atomic.Bool
closed atomic.Bool
cancel context.CancelFunc

// this keeps track of the events we've received before the EOSE that we must dispatch before
Expand Down Expand Up @@ -107,6 +111,13 @@ func (sub *Subscription) dispatchEose() {
}
}

func (sub *Subscription) dispatchClosed(reason string) {
if sub.closed.CompareAndSwap(false, true) {
sub.ClosedReason <- reason
close(sub.ClosedReason)
}
}

// Unsub closes the subscription, sending "CLOSE" to relay as in NIP-01.
// Unsub() also closes the channel sub.Events and makes a new one.
func (sub *Subscription) Unsub() {
Expand Down
2 changes: 1 addition & 1 deletion subscription_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
"time"
)

const RELAY = "wss://nostr.mom"
const RELAY = "wss://relay.nostr.bg"

// test if we can fetch a couple of random events
func TestSubscribe(t *testing.T) {
Expand Down

0 comments on commit 7449f25

Please sign in to comment.