github.com/ActiveState/cli@v0.0.0-20240508170324-6801f60cd051/internal/ipc/client.go (about)

     1  package ipc
     2  
     3  import (
     4  	"context"
     5  	"time"
     6  
     7  	"github.com/ActiveState/cli/internal/errs"
     8  	"github.com/ActiveState/cli/internal/ipc/internal/flisten"
     9  	"github.com/ActiveState/cli/internal/logging"
    10  )
    11  
    12  type Client struct {
    13  	sockpath *SockPath
    14  	dialer   *flisten.Dial
    15  }
    16  
    17  func NewClient(n *SockPath) *Client {
    18  	logging.Debug("Initializing ipc client with socket: %s", n)
    19  
    20  	return &Client{
    21  		sockpath: n,
    22  		dialer:   flisten.NewDial(),
    23  	}
    24  }
    25  
    26  func (c *Client) SockPath() *SockPath {
    27  	return c.sockpath
    28  }
    29  
    30  func (c *Client) Request(ctx context.Context, key string) (string, error) {
    31  	spath := c.sockpath.String()
    32  	conn, err := c.dialer.DialContext(ctx, network, spath)
    33  	if err != nil {
    34  		err = asServerDownError(err)
    35  		return "", errs.Wrap(err, "Cannot connect to ipc via %q", spath)
    36  	}
    37  	defer conn.Close()
    38  
    39  	_, err = conn.Write([]byte(key))
    40  	if err != nil {
    41  		return "", errs.Wrap(err, "Failed to write to server connection")
    42  	}
    43  
    44  	buf := make([]byte, msgWidth)
    45  	n, err := conn.Read(buf)
    46  	if err != nil {
    47  		return "", errs.Wrap(err, "Failed to read from server connection")
    48  	}
    49  
    50  	msg := string(buf[:n])
    51  
    52  	return msg, nil
    53  }
    54  
    55  func (c *Client) PingServer(ctx context.Context) (time.Duration, error) {
    56  	start := time.Now()
    57  
    58  	if _, err := getPing(ctx, c); err != nil {
    59  		return 0, errs.Wrap(err, "Failed to complete ping request")
    60  	}
    61  
    62  	return time.Since(start), nil
    63  }
    64  
    65  func (c *Client) StopServer(ctx context.Context) error {
    66  	if _, err := getStop(ctx, c); err != nil {
    67  		return errs.Wrap(err, "Failed to complete stop request")
    68  	}
    69  
    70  	return nil
    71  }