From cd1e14edc0229b0f9131a05fa265a5524024670b Mon Sep 17 00:00:00 2001 From: Tejas Poojari <140106410+TejasPoojari02@users.noreply.github.com> Date: Mon, 7 Oct 2024 19:32:51 +0530 Subject: [PATCH] Add files via upload --- services/client/client.go | 62 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/services/client/client.go b/services/client/client.go index b4688c4..58a87c2 100644 --- a/services/client/client.go +++ b/services/client/client.go @@ -43,3 +43,65 @@ type Service interface { SendCommand(ctx context.Context, input SendCommandInput) (SendCommandOutput, error) BuildClient(BuildClientBinaryInput) (string, error) } + +// function to handle reconnection +func (c *Client) reconnect() error { + backoff := time.Second + for { + c.conn, _, err := websocket.DefaultDialer.Dial(c.url, nil) + if err == nil { + return nil + } + if backoff > time.Minute { + return err + } + time.Sleep(backoff) + backoff *= 2 + } +} +// Modify the main loop to handle unexpected termination +func (c *Client) run() { + for { + err := c.readPump() + if err != nil { + if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) { + // Log the error here + log.Printf("Unexpected websocket closure: %v", err) + } + // Attempt to reconnect + if err := c.reconnect(); err != nil { + log.Printf("Failed to reconnect: %v", err) + return + } + // Reset any necessary client state here + } + } +} +// Modify the health check and device request functions +func (c *Client) sendHealthCheck() error { + if c.conn == nil { + return errors.New("Connection is not established") + } + return c.conn.WriteMessage(websocket.TextMessage, []byte("GET /health")) +} +func (c *Client) sendDeviceRequest() error { + if c.conn == nil { + return errors.New("Connection is not established") + } + return c.conn.WriteMessage(websocket.TextMessage, []byte("POST /device")) +} + +func connectWithRetry(url string, maxAttempts int) (*websocket.Conn, error) { + var conn *websocket.Conn + var err error + for attempt := 1; attempt <= maxAttempts; attempt++ { + conn, _, err = websocket.DefaultDialer.Dial(url, nil) + if err == nil { + return conn, nil + } + log.Printf("Connection attempt %d failed: %v. Retrying...", attempt, err) + time.Sleep(time.Second * time.Duration(attempt)) + } + return nil, fmt.Errorf("failed to establish connection after %d attempts", maxAttempts) +} +