github.com/hyperledger/aries-framework-go@v0.3.2/pkg/didcomm/transport/ws/upgrade_srv.go (about)

     1  // +build !js,!wasm
     2  
     3  /*
     4  Copyright SecureKey Technologies Inc. All Rights Reserved.
     5  
     6  SPDX-License-Identifier: Apache-2.0
     7  */
     8  
     9  package ws
    10  
    11  import (
    12  	"context"
    13  	"net/http"
    14  	"time"
    15  
    16  	"nhooyr.io/websocket"
    17  )
    18  
    19  // Accept accepts a WebSocket handshake from a client and upgrades the connection to a WebSocket.
    20  func Accept(w http.ResponseWriter, r *http.Request) (*websocket.Conn, error) {
    21  	// TODO Allow user to enable InsecureSkipVerify https://github.com/hyperledger/aries-framework-go/issues/928
    22  	return websocket.Accept(w, r, &websocket.AcceptOptions{
    23  		InsecureSkipVerify: true,
    24  		CompressionMode:    websocket.CompressionDisabled,
    25  	})
    26  }
    27  
    28  func acceptRecipient(pool *connPool, keys []string) bool {
    29  	for _, v := range keys {
    30  		// check if the connection exists for the key
    31  		if c := pool.fetch(v); c != nil {
    32  			// verify the connection is alive
    33  			if err := c.Ping(context.Background()); err != nil {
    34  				// remove from the pool
    35  				pool.remove(v)
    36  
    37  				logger.Infof("failed to ping to the connection for key=%s err=%v. Connection removed from pool.", v, err)
    38  
    39  				return false
    40  			}
    41  
    42  			return true
    43  		}
    44  	}
    45  
    46  	return false
    47  }
    48  
    49  // keepConnAlive sends the pings the server based on time frequency. The web server, load balancer, network routers
    50  // between the client and server closes the TCP keepalives connection. This function calls websocket ping request
    51  // directly to the server and keeps the connection active.
    52  func keepConnAlive(conn *websocket.Conn, outbound bool, frequency time.Duration) {
    53  	if outbound {
    54  		ticker := time.NewTicker(frequency)
    55  		done := make(chan struct{})
    56  
    57  		for {
    58  			select {
    59  			case <-done:
    60  				return
    61  			case <-ticker.C:
    62  				if err := conn.Ping(context.Background()); err != nil {
    63  					logger.Errorf("websocket ping error : %v", err)
    64  
    65  					ticker.Stop()
    66  					done <- struct{}{}
    67  				}
    68  			}
    69  		}
    70  	}
    71  }