summaryrefslogtreecommitdiffstats
path: root/relay.go
blob: 45f6119e35afe3963a54d9339ff253bfaaae6ea8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
package nostr

import (
	"context"
	"fmt"
	"sync"

	"github.com/coder/websocket"
)

// Relay represents a connection to a Nostr relay.
type Relay struct {
	URL  string
	conn *websocket.Conn
	mu   sync.Mutex

	subscriptions   map[string]*Subscription
	subscriptionsMu sync.RWMutex
}

// Connect establishes a WebSocket connection to the relay.
func Connect(ctx context.Context, url string) (*Relay, error) {
	conn, _, err := websocket.Dial(ctx, url, nil)
	if err != nil {
		return nil, fmt.Errorf("failed to connect to relay: %w", err)
	}

	return &Relay{
		URL:           url,
		conn:          conn,
		subscriptions: make(map[string]*Subscription),
	}, nil
}

// Close closes the WebSocket connection.
func (r *Relay) Close() error {
	r.mu.Lock()
	defer r.mu.Unlock()

	if r.conn == nil {
		return nil
	}

	err := r.conn.Close(websocket.StatusNormalClosure, "")
	r.conn = nil
	return err
}

// Send sends an envelope to the relay.
func (r *Relay) Send(ctx context.Context, env Envelope) error {
	data, err := env.MarshalJSON()
	if err != nil {
		return fmt.Errorf("failed to marshal envelope: %w", err)
	}

	r.mu.Lock()
	defer r.mu.Unlock()

	if r.conn == nil {
		return fmt.Errorf("connection closed")
	}

	return r.conn.Write(ctx, websocket.MessageText, data)
}

// Receive reads the next envelope from the relay.
func (r *Relay) Receive(ctx context.Context) (Envelope, error) {
	r.mu.Lock()
	conn := r.conn
	r.mu.Unlock()

	if conn == nil {
		return nil, fmt.Errorf("connection closed")
	}

	_, data, err := conn.Read(ctx)
	if err != nil {
		return nil, fmt.Errorf("failed to read message: %w", err)
	}

	return ParseEnvelope(data)
}

// Publish sends an event to the relay and waits for the OK response.
func (r *Relay) Publish(ctx context.Context, event *Event) error {
	env := EventEnvelope{Event: event}
	if err := r.Send(ctx, env); err != nil {
		return fmt.Errorf("failed to send event: %w", err)
	}

	// Wait for OK response
	for {
		resp, err := r.Receive(ctx)
		if err != nil {
			return fmt.Errorf("failed to receive response: %w", err)
		}

		if ok, isOK := resp.(*OKEnvelope); isOK {
			if ok.EventID == event.ID {
				if !ok.OK {
					return fmt.Errorf("event rejected: %s", ok.Message)
				}
				return nil
			}
		}

		// Dispatch other messages to subscriptions
		r.dispatchEnvelope(resp)
	}
}

// Subscribe creates a subscription with the given filters.
func (r *Relay) Subscribe(ctx context.Context, id string, filters ...Filter) (*Subscription, error) {
	sub := &Subscription{
		ID:      id,
		relay:   r,
		Filters: filters,
		Events:  make(chan *Event, 100),
		EOSE:    make(chan struct{}, 1),
		closed:  make(chan struct{}),
	}

	r.subscriptionsMu.Lock()
	r.subscriptions[id] = sub
	r.subscriptionsMu.Unlock()

	env := ReqEnvelope{
		SubscriptionID: id,
		Filters:        filters,
	}
	if err := r.Send(ctx, env); err != nil {
		r.subscriptionsMu.Lock()
		delete(r.subscriptions, id)
		r.subscriptionsMu.Unlock()
		return nil, fmt.Errorf("failed to send subscription request: %w", err)
	}

	return sub, nil
}

// dispatchEnvelope routes incoming messages to the appropriate subscription.
func (r *Relay) dispatchEnvelope(env Envelope) {
	switch e := env.(type) {
	case *EventEnvelope:
		r.subscriptionsMu.RLock()
		sub, ok := r.subscriptions[e.SubscriptionID]
		r.subscriptionsMu.RUnlock()
		if ok {
			select {
			case sub.Events <- e.Event:
			default:
				// Channel full, drop event
			}
		}
	case *EOSEEnvelope:
		r.subscriptionsMu.RLock()
		sub, ok := r.subscriptions[e.SubscriptionID]
		r.subscriptionsMu.RUnlock()
		if ok {
			select {
			case sub.EOSE <- struct{}{}:
			default:
			}
		}
	case *ClosedEnvelope:
		r.subscriptionsMu.Lock()
		if sub, ok := r.subscriptions[e.SubscriptionID]; ok {
			close(sub.closed)
			delete(r.subscriptions, e.SubscriptionID)
		}
		r.subscriptionsMu.Unlock()
	}
}

// Listen reads messages from the relay and dispatches them to subscriptions.
// This should be called in a goroutine when using multiple subscriptions.
func (r *Relay) Listen(ctx context.Context) error {
	for {
		select {
		case <-ctx.Done():
			return ctx.Err()
		default:
		}

		env, err := r.Receive(ctx)
		if err != nil {
			return err
		}

		r.dispatchEnvelope(env)
	}
}

// Subscription represents an active subscription to a relay.
type Subscription struct {
	ID      string
	relay   *Relay
	Filters []Filter
	Events  chan *Event
	EOSE    chan struct{}
	closed  chan struct{}
}

// Close unsubscribes from the relay.
func (s *Subscription) Close(ctx context.Context) error {
	s.relay.subscriptionsMu.Lock()
	delete(s.relay.subscriptions, s.ID)
	s.relay.subscriptionsMu.Unlock()

	env := CloseEnvelope{SubscriptionID: s.ID}
	return s.relay.Send(ctx, env)
}

// Closed returns a channel that's closed when the subscription is terminated.
func (s *Subscription) Closed() <-chan struct{} {
	return s.closed
}