-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrelay.go
More file actions
444 lines (377 loc) · 10.2 KB
/
relay.go
File metadata and controls
444 lines (377 loc) · 10.2 KB
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//go:build goexperiment.jsonv2
package mocrelay
import (
"context"
"encoding/json/v2"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"strconv"
"sync"
"time"
"unicode/utf8"
"github.com/coder/websocket"
)
// Relay wraps a Handler to serve it over HTTP/WebSocket.
// It implements http.Handler.
type Relay struct {
Handler Handler
Logger *slog.Logger
// MaxMessageLength is the maximum size of a WebSocket message.
// Default: 100KB
MaxMessageLength int64
// PingInterval is the interval between WebSocket pings.
// Set to 0 to disable pings.
// Default: 30 seconds
PingInterval time.Duration
// PingTimeout is the timeout for WebSocket ping responses.
// If a pong is not received within this duration, the connection is closed.
// Default: 10 seconds
PingTimeout time.Duration
// Info is the NIP-11 Relay Information Document.
// If set, the relay will respond to HTTP requests with
// Accept: application/nostr+json header.
Info *RelayInfo
// Metrics is the Prometheus metrics collector.
// If set, the relay will collect connection and message metrics.
Metrics *RelayMetrics
mu sync.Mutex
wg sync.WaitGroup
connID uint64
cancels map[uint64]context.CancelFunc
closed bool
}
// NewRelay creates a new Relay with the given handler.
func NewRelay(handler Handler) *Relay {
return &Relay{
Handler: handler,
MaxMessageLength: 100_000,
}
}
// Wait blocks until all connections have finished.
func (r *Relay) Wait() {
r.wg.Wait()
}
// Shutdown gracefully shuts down the relay.
// It closes all WebSocket connections and waits for them to finish.
// If ctx is canceled before all connections finish, it returns ctx.Err().
func (r *Relay) Shutdown(ctx context.Context) error {
r.mu.Lock()
r.closed = true
for _, cancel := range r.cancels {
cancel()
}
r.mu.Unlock()
done := make(chan struct{})
go func() {
r.wg.Wait()
close(done)
}()
select {
case <-done:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func (r *Relay) registerConn(cancel context.CancelFunc) uint64 {
r.mu.Lock()
defer r.mu.Unlock()
if r.cancels == nil {
r.cancels = make(map[uint64]context.CancelFunc)
}
r.connID++
id := r.connID
r.cancels[id] = cancel
return id
}
func (r *Relay) unregisterConn(id uint64) {
r.mu.Lock()
defer r.mu.Unlock()
delete(r.cancels, id)
}
// ServeHTTP implements http.Handler.
func (r *Relay) ServeHTTP(w http.ResponseWriter, req *http.Request) {
// Check if relay is shutting down (for all requests)
r.mu.Lock()
closed := r.closed
r.mu.Unlock()
if closed {
http.Error(w, "relay is shutting down", http.StatusServiceUnavailable)
return
}
// NIP-11: Respond with relay info if Accept header is application/nostr+json
if r.Info != nil && req.Header.Get("Accept") == "application/nostr+json" {
r.serveNIP11(w, req)
return
}
// Non-WebSocket GET: return simple message instead of upgrade error
if req.Header.Get("Upgrade") == "" {
r.serveWelcome(w, req)
return
}
// WebSocket connection: track with WaitGroup
r.mu.Lock()
if r.closed {
r.mu.Unlock()
http.Error(w, "relay is shutting down", http.StatusServiceUnavailable)
return
}
r.wg.Add(1)
r.mu.Unlock()
defer r.wg.Done()
ctx := req.Context()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
connID := r.registerConn(cancel)
defer r.unregisterConn(connID)
// Metrics: connection tracking
if r.Metrics != nil {
r.Metrics.ConnectionsTotal.Inc()
r.Metrics.ConnectionsCurrent.Inc()
defer r.Metrics.ConnectionsCurrent.Dec()
}
r.logInfo(ctx, "connection start")
// Upgrade to WebSocket
conn, err := websocket.Accept(w, req, &websocket.AcceptOptions{
InsecureSkipVerify: true,
CompressionMode: websocket.CompressionDisabled,
})
if err != nil {
r.logWarn(ctx, "failed to upgrade to websocket", "error", err)
return
}
defer conn.Close(websocket.StatusInternalError, "")
if r.MaxMessageLength > 0 {
conn.SetReadLimit(r.MaxMessageLength)
}
recv := make(chan *ClientMsg)
send := make(chan *ServerMsg)
errs := make(chan error, 4)
var wg sync.WaitGroup
// Read loop: WebSocket -> recv channel
wg.Go(func() {
defer cancel()
defer close(recv)
err := r.readLoop(ctx, conn, recv, send)
errs <- fmt.Errorf("readLoop: %w", err)
})
// Write loop: send channel -> WebSocket
wg.Go(func() {
defer cancel()
err := r.writeLoop(ctx, conn, send)
errs <- fmt.Errorf("writeLoop: %w", err)
})
// Ping loop: keep-alive and detect dead connections
wg.Go(func() {
defer cancel()
err := r.pingLoop(ctx, conn)
if err != nil {
errs <- fmt.Errorf("pingLoop: %w", err)
}
})
// Handler
wg.Go(func() {
defer cancel()
err := r.Handler.ServeNostr(ctx, send, recv)
errs <- fmt.Errorf("handler: %w", err)
})
// Wait for cancellation
<-ctx.Done()
conn.Close(websocket.StatusNormalClosure, "")
wg.Wait()
close(errs)
// Collect errors for logging
var allErrs error
for e := range errs {
allErrs = errors.Join(allErrs, e)
}
var wsErr websocket.CloseError
if errors.Is(allErrs, io.EOF) {
r.logInfo(ctx, "connection end")
} else if errors.As(allErrs, &wsErr) {
r.logInfo(ctx, "connection end", "code", wsErr.Code, "reason", wsErr.Reason)
} else if errors.Is(allErrs, context.Canceled) {
r.logInfo(ctx, "connection end (canceled)")
} else {
r.logWarn(ctx, "connection end with error", "error", allErrs)
}
}
// readLoop reads messages from WebSocket and sends them to recv channel.
func (r *Relay) readLoop(
ctx context.Context,
conn *websocket.Conn,
recv chan<- *ClientMsg,
send chan<- *ServerMsg,
) error {
for {
typ, payload, err := conn.Read(ctx)
if err != nil {
return err
}
// Must be text message
if typ != websocket.MessageText {
r.logWarn(ctx, "received binary message")
r.sendNotice(ctx, send, "binary message not allowed")
continue
}
// Must be valid UTF-8
if !utf8.Valid(payload) {
r.logWarn(ctx, "received invalid UTF-8")
r.sendNotice(ctx, send, "invalid UTF-8")
continue
}
// Parse client message
msg, err := ParseClientMsg(payload)
if err != nil {
r.logWarn(ctx, "failed to parse client message", "error", err)
r.sendNotice(ctx, send, "invalid message format")
continue
}
// Verify event signature if EVENT message
if msg.Type == MsgTypeEvent && msg.Event != nil {
valid, err := msg.Event.Verify()
if err != nil {
r.logWarn(ctx, "failed to verify event", "error", err)
r.sendNotice(ctx, send, "verification error")
continue
}
if !valid {
r.logWarn(ctx, "invalid event signature", "id", msg.Event.ID)
r.sendNotice(ctx, send, "invalid signature")
continue
}
}
// Metrics: message received
if r.Metrics != nil {
r.Metrics.MessagesReceived.WithLabelValues(string(msg.Type)).Inc()
if msg.Type == MsgTypeEvent && msg.Event != nil {
kindStr := strconv.FormatInt(msg.Event.Kind, 10)
r.Metrics.EventsReceived.WithLabelValues(kindStr).Inc()
}
}
// Send to handler
select {
case <-ctx.Done():
return ctx.Err()
case recv <- msg:
}
}
}
// writeLoop reads messages from send channel and writes them to WebSocket.
func (r *Relay) writeLoop(
ctx context.Context,
conn *websocket.Conn,
send <-chan *ServerMsg,
) error {
for {
select {
case <-ctx.Done():
return ctx.Err()
case msg, ok := <-send:
if !ok {
return nil
}
data, err := json.Marshal(msg)
if err != nil {
r.logWarn(ctx, "failed to marshal server message", "error", err)
continue
}
if err := conn.Write(ctx, websocket.MessageText, data); err != nil {
return err
}
// Metrics: message sent
if r.Metrics != nil {
r.Metrics.MessagesSent.WithLabelValues(string(msg.Type)).Inc()
}
}
}
}
// pingLoop sends periodic pings to detect dead connections.
// It returns nil if pings are disabled (PingInterval == 0) or context is canceled.
// It returns an error if a ping times out (connection is dead).
func (r *Relay) pingLoop(ctx context.Context, conn *websocket.Conn) error {
interval := r.PingInterval
if interval == 0 {
interval = 30 * time.Second
}
if interval < 0 {
// Negative interval disables pings
<-ctx.Done()
return nil
}
timeout := r.PingTimeout
if timeout == 0 {
timeout = 10 * time.Second
}
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return nil
case <-ticker.C:
pingCtx, cancel := context.WithTimeout(ctx, timeout)
err := conn.Ping(pingCtx)
cancel()
if err != nil {
return fmt.Errorf("ping timeout: %w", err)
}
}
}
}
// sendNotice sends a NOTICE message to the client.
func (r *Relay) sendNotice(ctx context.Context, send chan<- *ServerMsg, message string) {
select {
case <-ctx.Done():
case send <- NewServerNoticeMsg(message):
}
}
func (r *Relay) logInfo(ctx context.Context, msg string, args ...any) {
if r.Logger != nil {
r.Logger.InfoContext(ctx, msg, args...)
}
}
func (r *Relay) logWarn(ctx context.Context, msg string, args ...any) {
if r.Logger != nil {
r.Logger.WarnContext(ctx, msg, args...)
}
}
// serveWelcome responds with a simple welcome message for non-WebSocket requests.
// If RelayInfo.Name is set, it returns the name. Otherwise, returns empty 200 OK.
func (r *Relay) serveWelcome(w http.ResponseWriter, req *http.Request) {
if r.Info != nil && r.Info.Name != "" {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Write([]byte(r.Info.Name))
return
}
// Empty 200 OK
w.WriteHeader(http.StatusOK)
}
// serveNIP11 responds with the NIP-11 Relay Information Document.
func (r *Relay) serveNIP11(w http.ResponseWriter, req *http.Request) {
// CORS headers (required by NIP-11)
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Accept")
w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
// Handle preflight request
if req.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
// Only GET is allowed for NIP-11
if req.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "application/nostr+json")
data, err := json.Marshal(r.Info)
if err != nil {
r.logWarn(req.Context(), "failed to marshal relay info", "error", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
w.Write(data)
}