summaryrefslogtreecommitdiffstats
path: root/internal/handler/websocket/handler.go
blob: 224a2f8c3cbba89fc7fafcdbf6f2e73a090fe000 (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
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
package websocket

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"net/http"

	pb "northwest.io/nostr-grpc/api/nostr/v1"
	"northwest.io/nostr-grpc/internal/nostr"
	"northwest.io/nostr-grpc/internal/storage"
	"northwest.io/nostr-grpc/internal/subscription"
	"northwest.io/nostr-grpc/internal/websocket"
)

type EventStore interface {
	StoreEvent(context.Context, *storage.EventData) error
	QueryEvents(context.Context, []*pb.Filter, *storage.QueryOptions) ([]*pb.Event, error)
	ProcessDeletion(context.Context, *pb.Event) error
}

type Handler struct {
	store EventStore
	subs  *subscription.Manager
}

func NewHandler(store EventStore, subs *subscription.Manager) *Handler {
	return &Handler{
		store: store,
		subs:  subs,
	}
}

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" && r.Header.Get("Accept") == "application/nostr+json" {
		h.ServeNIP11(w, r)
		return
	}

	conn, err := websocket.Accept(w, r)
	if err != nil {
		log.Printf("WebSocket accept failed: %v", err)
		return
	}
	defer conn.Close(websocket.StatusNormalClosure, "")

	ctx := r.Context()
	clientSubs := make(map[string]*subscription.Subscription)
	defer func() {
		for subID := range clientSubs {
			h.subs.Remove(subID)
		}
	}()

	for {
		_, data, err := conn.Read(ctx)
		if err != nil {
			return
		}

		if err := h.handleMessage(ctx, conn, data, clientSubs); err != nil {
			log.Printf("Message handling error: %v", err)
			h.sendNotice(ctx, conn, err.Error())
		}
	}
}

func (h *Handler) handleMessage(ctx context.Context, conn *websocket.Conn, data []byte, clientSubs map[string]*subscription.Subscription) error {
	var raw []json.RawMessage
	if err := json.Unmarshal(data, &raw); err != nil {
		return fmt.Errorf("invalid JSON")
	}

	if len(raw) == 0 {
		return fmt.Errorf("empty message")
	}

	var msgType string
	if err := json.Unmarshal(raw[0], &msgType); err != nil {
		return fmt.Errorf("invalid message type")
	}

	switch msgType {
	case "EVENT":
		return h.handleEvent(ctx, conn, raw)
	case "REQ":
		return h.handleReq(ctx, conn, raw, clientSubs)
	case "CLOSE":
		return h.handleClose(raw, clientSubs)
	default:
		return fmt.Errorf("unknown message type: %s", msgType)
	}
}

func (h *Handler) handleEvent(ctx context.Context, conn *websocket.Conn, raw []json.RawMessage) error {
	if len(raw) != 2 {
		return fmt.Errorf("EVENT expects 2 elements")
	}

	var event nostr.Event
	if err := json.Unmarshal(raw[1], &event); err != nil {
		return fmt.Errorf("invalid event: %w", err)
	}

	if !event.CheckID() {
		h.sendOK(ctx, conn, event.ID, false, "invalid: event ID mismatch")
		return nil
	}

	if !event.Verify() {
		h.sendOK(ctx, conn, event.ID, false, "invalid: signature verification failed")
		return nil
	}

	pbEvent := NostrToPB(&event)
	canonicalJSON := event.Serialize()

	// Handle deletion events (kind 5) - process but don't store
	if pbEvent.Kind == 5 {
		if err := h.store.ProcessDeletion(ctx, pbEvent); err != nil {
			h.sendOK(ctx, conn, event.ID, false, fmt.Sprintf("deletion failed: %v", err))
			return nil
		}
		h.sendOK(ctx, conn, event.ID, true, "deleted")
		return nil
	}

	eventData := &storage.EventData{
		Event:         pbEvent,
		CanonicalJSON: canonicalJSON,
	}

	err := h.store.StoreEvent(ctx, eventData)
	if err == storage.ErrEventExists {
		h.sendOK(ctx, conn, event.ID, true, "duplicate: already have this event")
		return nil
	}
	if err != nil {
		h.sendOK(ctx, conn, event.ID, false, fmt.Sprintf("error: %v", err))
		return nil
	}

	h.subs.MatchAndFan(pbEvent)

	h.sendOK(ctx, conn, event.ID, true, "")
	return nil
}

func (h *Handler) handleReq(ctx context.Context, conn *websocket.Conn, raw []json.RawMessage, clientSubs map[string]*subscription.Subscription) error {
	if len(raw) < 3 {
		return fmt.Errorf("REQ expects at least 3 elements")
	}

	var subID string
	if err := json.Unmarshal(raw[1], &subID); err != nil {
		return fmt.Errorf("invalid subscription ID")
	}

	var filters []*pb.Filter
	for i := 2; i < len(raw); i++ {
		var nostrFilter nostr.Filter
		if err := json.Unmarshal(raw[i], &nostrFilter); err != nil {
			return fmt.Errorf("invalid filter: %w", err)
		}

		pbFilter := NostrFilterToPB(&nostrFilter)
		filters = append(filters, pbFilter)
	}

	if existing, ok := clientSubs[subID]; ok {
		h.subs.Remove(existing.ID)
		delete(clientSubs, subID)
	}

	storedEvents, err := h.store.QueryEvents(ctx, filters, &storage.QueryOptions{Limit: 0})
	if err != nil {
		return fmt.Errorf("query failed: %w", err)
	}

	for _, pbEvent := range storedEvents {
		event := PBToNostr(pbEvent)
		h.sendEvent(ctx, conn, subID, event)
	}

	h.sendEOSE(ctx, conn, subID)

	sub := &subscription.Subscription{
		ID:      subID,
		Filters: filters,
		Events:  make(chan *pb.Event, 100),
	}
	sub.InitDone()

	h.subs.Add(sub)
	clientSubs[subID] = sub

	go h.streamEvents(ctx, conn, sub)

	return nil
}

func (h *Handler) handleClose(raw []json.RawMessage, clientSubs map[string]*subscription.Subscription) error {
	if len(raw) != 2 {
		return fmt.Errorf("CLOSE expects 2 elements")
	}

	var subID string
	if err := json.Unmarshal(raw[1], &subID); err != nil {
		return fmt.Errorf("invalid subscription ID")
	}

	if sub, ok := clientSubs[subID]; ok {
		h.subs.Remove(sub.ID)
		delete(clientSubs, subID)
	}

	return nil
}

func (h *Handler) streamEvents(ctx context.Context, conn *websocket.Conn, sub *subscription.Subscription) {
	for {
		select {
		case pbEvent, ok := <-sub.Events:
			if !ok {
				return
			}
			event := PBToNostr(pbEvent)
			h.sendEvent(ctx, conn, sub.ID, event)

		case <-ctx.Done():
			return

		case <-sub.Done():
			return
		}
	}
}

func (h *Handler) sendEvent(ctx context.Context, conn *websocket.Conn, subID string, event *nostr.Event) error {
	msg := []interface{}{"EVENT", subID, event}
	data, _ := json.Marshal(msg)
	return conn.Write(ctx, websocket.MessageText, data)
}

func (h *Handler) sendOK(ctx context.Context, conn *websocket.Conn, eventID string, accepted bool, message string) error {
	msg := []interface{}{"OK", eventID, accepted, message}
	data, _ := json.Marshal(msg)
	return conn.Write(ctx, websocket.MessageText, data)
}

func (h *Handler) sendEOSE(ctx context.Context, conn *websocket.Conn, subID string) error {
	msg := []interface{}{"EOSE", subID}
	data, _ := json.Marshal(msg)
	return conn.Write(ctx, websocket.MessageText, data)
}

func (h *Handler) sendNotice(ctx context.Context, conn *websocket.Conn, notice string) error {
	msg := []interface{}{"NOTICE", notice}
	data, _ := json.Marshal(msg)
	return conn.Write(ctx, websocket.MessageText, data)
}