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

     1  package ipc
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  
     7  	"github.com/ActiveState/cli/internal/logging"
     8  )
     9  
    10  // Key/Value associations. Keys start with rare characters to try to ensure
    11  // that they do not match higher-level keys in a quick manner. The response
    12  // values are of little interest.
    13  var (
    14  	keyPing = "|ping"
    15  	valPong = "|pong"
    16  	keyStop = "%stop"
    17  	valStop = "%okok"
    18  )
    19  
    20  func pingHandler() RequestHandler {
    21  	return func(key string) (string, bool) {
    22  		if key == keyPing {
    23  			logging.Debug("handling ping request")
    24  			return valPong, true
    25  		}
    26  
    27  		return "", false
    28  	}
    29  }
    30  
    31  func getPing(ctx context.Context, c *Client) (string, error) {
    32  	val, err := c.Request(ctx, keyPing)
    33  	if err != nil {
    34  		return val, err
    35  	}
    36  
    37  	if val != valPong {
    38  		// this should never be seen by users
    39  		return val, errors.New("ipc.IPC should be constructed with a ping handler")
    40  	}
    41  
    42  	return val, nil
    43  }
    44  
    45  func stopHandler(stop func()) RequestHandler {
    46  	return func(key string) (string, bool) {
    47  		if key == keyStop {
    48  			logging.Debug("handling stop request")
    49  			stop()
    50  			return valStop, true
    51  		}
    52  
    53  		return "", false
    54  	}
    55  }
    56  
    57  func getStop(ctx context.Context, c *Client) (string, error) {
    58  	val, err := c.Request(ctx, keyStop)
    59  	if err != nil {
    60  		return val, err
    61  	}
    62  
    63  	if val != valStop {
    64  		// this should never be seen by users
    65  		return val, errors.New("ipc.IPC should be constructed with a stop handler")
    66  	}
    67  
    68  	return val, nil
    69  }