Skip to content

Commit

Permalink
refactor: server should start the receive loop (#19)
Browse files Browse the repository at this point in the history
Move the receive loop into the server package and make it restart on error

The receive loop is now managed by the server package, which will restart it automatically if it encounters an error. The loop previously lived in main.go but has been relocated to server.go for better error handling and recovery.

ref #8

Co-authored-by: Mathias Fredriksson <[email protected]>
  • Loading branch information
kalbasit and mafredri authored Dec 21, 2024
1 parent 180e9ab commit dbf7877
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 5 deletions.
2 changes: 0 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,6 @@ func realMain() int {
return 1
}

go sarc.ReceiveLoop()

srv := server.New(sarc)

server := &http.Server{
Expand Down
4 changes: 2 additions & 2 deletions receiver/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,15 +110,15 @@ func New(uri *url.URL) (*Client, error) {
// ReceiveLoop is a blocking call and it loop over receiving messages over the
// websocket and record them internally to be consumed by either Pop() or
// Flush().
func (c *Client) ReceiveLoop() {
func (c *Client) ReceiveLoop() error {
log.Print("Starting the receive loop from Signal API")

for {
_, msg, err := c.ReadMessage()
if err != nil {
log.Printf("error returned by the websocket: %s", err)

return
return err
}

c.recordMessage(msg)
Expand Down
15 changes: 14 additions & 1 deletion server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package server
import (
"encoding/json"
"fmt"
"log"
"net/http"

"github.com/kalbasit/signal-api-receiver/receiver"
Expand All @@ -19,13 +20,25 @@ type Server struct {
}

type client interface {
ReceiveLoop() error
Pop() *receiver.Message
Flush() []receiver.Message
}

// New returns a new Server.
func New(sarc client) *Server {
return &Server{sarc: sarc}
s := &Server{sarc: sarc}
go s.start()

return s
}

func (s *Server) start() {
for {
if err := s.sarc.ReceiveLoop(); err != nil {
log.Printf("Error in the receive loop: %v", err)
}
}
}

// ServeHTTP implements the http.Handler interface
Expand Down
4 changes: 4 additions & 0 deletions server/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ type mockClient struct {
msgs []receiver.Message
}

func (mc *mockClient) ReceiveLoop() error {
return nil
}

func (mc *mockClient) Pop() *receiver.Message {
if len(mc.msgs) == 0 {
return nil
Expand Down

0 comments on commit dbf7877

Please sign in to comment.