|
| 1 | +package handlers |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "log" |
| 6 | + "matching-service/models" |
| 7 | + "matching-service/processes" |
| 8 | + "matching-service/utils" |
| 9 | + "net/http" |
| 10 | + |
| 11 | + "github.com/gorilla/websocket" |
| 12 | +) |
| 13 | + |
| 14 | +var upgrader = websocket.Upgrader{ |
| 15 | + CheckOrigin: func(r *http.Request) bool { |
| 16 | + // Allow all connections by skipping the origin check (set more restrictions in production) |
| 17 | + return true |
| 18 | + }, |
| 19 | +} |
| 20 | + |
| 21 | +// handleConnections manages WebSocket connections and matching logic. |
| 22 | +func HandleWebSocketConnections(w http.ResponseWriter, r *http.Request) { |
| 23 | + // TODO: Parse the authorization header to validate the JWT token and get the user ID claim. |
| 24 | + |
| 25 | + ws, err := upgrader.Upgrade(w, r, nil) |
| 26 | + if err != nil { |
| 27 | + log.Fatal(err) |
| 28 | + http.Error(w, "Could not open websocket connection", http.StatusBadRequest) |
| 29 | + return |
| 30 | + } |
| 31 | + defer func() { |
| 32 | + if closeErr := ws.Close(); closeErr != nil { |
| 33 | + log.Printf("WebSocket close error: %v", closeErr) |
| 34 | + } |
| 35 | + }() |
| 36 | + |
| 37 | + log.Println("WebSocket connection established") |
| 38 | + |
| 39 | + matchRequest, err := readMatchRequest(ws) |
| 40 | + if err != nil { |
| 41 | + log.Printf("Error reading match request: %v", err) |
| 42 | + return |
| 43 | + } |
| 44 | + |
| 45 | + // Create a context for cancellation |
| 46 | + ctx, cancel := context.WithCancel(context.Background()) |
| 47 | + defer cancel() // Ensure cancel is called to release resources |
| 48 | + |
| 49 | + timeoutCtx, timeoutCancel, err := createTimeoutContext() |
| 50 | + if err != nil { |
| 51 | + log.Printf("Error creating timeout context: %v", err) |
| 52 | + return |
| 53 | + } |
| 54 | + defer timeoutCancel() |
| 55 | + |
| 56 | + matchFoundChan := make(chan models.MatchFound) |
| 57 | + |
| 58 | + // Start goroutines for handling messages and performing matching. |
| 59 | + go processes.ReadMessages(ws, ctx, cancel) |
| 60 | + go processes.PerformMatching(matchRequest, ctx, matchFoundChan) // Perform matching |
| 61 | + |
| 62 | + // Wait for a match, timeout, or cancellation. |
| 63 | + waitForResult(ws, ctx, timeoutCtx, matchFoundChan) |
| 64 | +} |
| 65 | + |
| 66 | +// readMatchRequest reads the initial match request from the WebSocket connection. |
| 67 | +func readMatchRequest(ws *websocket.Conn) (models.MatchRequest, error) { |
| 68 | + var matchRequest models.MatchRequest |
| 69 | + if err := ws.ReadJSON(&matchRequest); err != nil { |
| 70 | + return matchRequest, err |
| 71 | + } |
| 72 | + log.Printf("Received match request: %v", matchRequest) |
| 73 | + return matchRequest, nil |
| 74 | +} |
| 75 | + |
| 76 | +// createTimeoutContext sets up a timeout context based on configuration. |
| 77 | +func createTimeoutContext() (context.Context, context.CancelFunc, error) { |
| 78 | + timeoutDuration, err := utils.GetTimeoutDuration() |
| 79 | + if err != nil { |
| 80 | + return nil, nil, err |
| 81 | + } |
| 82 | + ctx, cancel := context.WithTimeout(context.Background(), timeoutDuration) |
| 83 | + return ctx, cancel, nil |
| 84 | +} |
| 85 | + |
| 86 | +// waitForResult waits for a match result, timeout, or cancellation. |
| 87 | +func waitForResult(ws *websocket.Conn, ctx, timeoutCtx context.Context, matchFoundChan chan models.MatchFound) { |
| 88 | + select { |
| 89 | + case <-ctx.Done(): |
| 90 | + log.Println("Matching cancelled") |
| 91 | + return |
| 92 | + case <-timeoutCtx.Done(): |
| 93 | + log.Println("Connection timed out") |
| 94 | + sendTimeoutResponse(ws) |
| 95 | + return |
| 96 | + case result, ok := <-matchFoundChan: |
| 97 | + if !ok { |
| 98 | + // Channel closed without a match, possibly due to context cancellation |
| 99 | + log.Println("Match channel closed without finding a match") |
| 100 | + return |
| 101 | + } |
| 102 | + log.Println("Match found") |
| 103 | + if err := ws.WriteJSON(result); err != nil { |
| 104 | + log.Printf("write error: %v", err) |
| 105 | + } |
| 106 | + return |
| 107 | + } |
| 108 | +} |
| 109 | + |
| 110 | +// sendTimeoutResponse sends a timeout message to the WebSocket client. |
| 111 | +func sendTimeoutResponse(ws *websocket.Conn) { |
| 112 | + result := models.Timeout{ |
| 113 | + Type: "timeout", |
| 114 | + Message: "No match found. Please try again later.", |
| 115 | + } |
| 116 | + if err := ws.WriteJSON(result); err != nil { |
| 117 | + log.Printf("write error: %v", err) |
| 118 | + } |
| 119 | +} |
0 commit comments