go-nostr/subscription.go

95 lines
2.1 KiB
Go
Raw Permalink Normal View History

2022-01-02 08:44:18 -03:00
package nostr
2021-02-20 17:44:05 -03:00
import (
2023-01-01 20:22:40 -03:00
"context"
"fmt"
"strconv"
"sync"
)
2021-02-20 17:44:05 -03:00
type Subscription struct {
2023-03-18 15:09:49 -03:00
label string
counter int
conn *Connection
mutex sync.Mutex
2021-02-20 17:44:05 -03:00
Relay *Relay
Filters Filters
2023-01-26 09:04:27 -03:00
Events chan *Event
EndOfStoredEvents chan struct{}
Context context.Context
cancel context.CancelFunc
stopped bool
emitEose sync.Once
}
type EventMessage struct {
2022-01-02 08:44:18 -03:00
Event Event
Relay string
2021-02-20 17:44:05 -03:00
}
// SetLabel puts a label on the subscription that is prepended to the id that is sent to relays,
// it's only useful for debugging and sanity purposes.
func (sub *Subscription) SetLabel(label string) {
sub.label = label
}
// GetID return the Nostr subscription ID as given to the relay, it will be a sequential number, stringified.
func (sub *Subscription) GetID() string {
2023-03-18 15:09:49 -03:00
return sub.label + ":" + strconv.Itoa(sub.counter)
}
// Unsub closes the subscription, sending "CLOSE" to relay as in NIP-01.
// Unsub() also closes the channel sub.Events.
func (sub *Subscription) Unsub() {
sub.mutex.Lock()
defer sub.mutex.Unlock()
2021-02-20 17:44:05 -03:00
sub.conn.WriteJSON([]interface{}{"CLOSE", sub.GetID()})
if sub.stopped == false && sub.Events != nil {
close(sub.Events)
2021-02-20 17:44:05 -03:00
}
sub.stopped = true
2021-02-20 17:44:05 -03:00
}
// Sub sets sub.Filters and then calls sub.Fire(ctx).
2023-01-01 20:22:40 -03:00
func (sub *Subscription) Sub(ctx context.Context, filters Filters) {
sub.Filters = filters
sub.Fire()
}
// Fire sends the "REQ" command to the relay.
func (sub *Subscription) Fire() error {
2023-03-18 15:09:49 -03:00
sub.Relay.subscriptions.Store(sub.GetID(), sub)
message := []interface{}{"REQ", sub.GetID()}
for _, filter := range sub.Filters {
message = append(message, filter)
}
debugLog("{%s} sending %v", sub.Relay.URL, message)
err := sub.conn.WriteJSON(message)
if err != nil {
sub.cancel()
return fmt.Errorf("failed to write: %w", err)
}
2023-01-01 20:22:40 -03:00
// the subscription ends once the context is canceled
go func() {
<-sub.Context.Done()
2023-01-01 20:22:40 -03:00
sub.Unsub()
}()
// or when the relay connection is closed
go func() {
<-sub.Relay.ConnectionContext.Done()
// cancel the context -- this will cause the other context cancelation cause above to be called
sub.cancel()
}()
return nil
2021-02-20 17:44:05 -03:00
}