From 5ea0d36ba313a0da34dd9570d572950a942b28d1 Mon Sep 17 00:00:00 2001 From: Chris kerr Date: Wed, 31 Jul 2024 20:09:47 -0400 Subject: [PATCH] properly update subscriptions, sub ID's per connection --- server/handlers/req.go | 13 ++++--------- server/relay.go | 7 +++++-- 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/server/handlers/req.go b/server/handlers/req.go index 71a9496..21dc925 100644 --- a/server/handlers/req.go +++ b/server/handlers/req.go @@ -17,7 +17,7 @@ import ( var subscriptions = make(map[string]relay.Subscription) -func HandleReq(ws *websocket.Conn, message []interface{}) { +func HandleReq(ws *websocket.Conn, message []interface{}, subscriptions map[string][]relay.Filter) { if len(message) < 3 { fmt.Println("Invalid REQ message format") response.SendClosed(ws, "", "invalid: invalid REQ message format") @@ -52,14 +52,9 @@ func HandleReq(ws *websocket.Conn, message []interface{}) { filters[i] = f } - // Check if subscription already exists - if _, exists := subscriptions[subID]; exists { - response.SendClosed(ws, subID, "duplicate: subID already opened") - return - } - - subscriptions[subID] = relay.Subscription{ID: subID, Filters: filters} - fmt.Println("Subscription added:", subID) + // Update or add the subscription for the given subID + subscriptions[subID] = filters + fmt.Println("Subscription updated:", subID) // Query the database with filters and send back the results queriedEvents, err := QueryEvents(filters, db.GetClient(), "grain") diff --git a/server/relay.go b/server/relay.go index e72e3d8..d092ba9 100644 --- a/server/relay.go +++ b/server/relay.go @@ -7,6 +7,8 @@ import ( "grain/config" + relay "grain/server/types" + "golang.org/x/net/websocket" ) @@ -16,11 +18,12 @@ func WebSocketHandler(ws *websocket.Conn) { var msg string rateLimiter := config.GetRateLimiter() + subscriptions := make(map[string][]relay.Filter) // Subscription map scoped to the connection + for { err := websocket.Message.Receive(ws, &msg) if err != nil { fmt.Println("Error receiving message:", err) - // Send a close message with an error code and reason ws.Close() return } @@ -59,7 +62,7 @@ func WebSocketHandler(ws *websocket.Conn) { ws.Close() return } - handlers.HandleReq(ws, message) + handlers.HandleReq(ws, message, subscriptions) case "CLOSE": handlers.HandleClose(ws, message) default: