Files
pipelines/internal/client/client.go
T

73 lines
1.7 KiB
Go

// Package client is the common command transport for CLI, TUI, and automation.
// Validation and mutation remain exclusively owned by the server.
package client
import (
"context"
"fmt"
"strconv"
"sync"
"git.a-wan.net/alan/pipelines/internal/protocol"
"github.com/coder/websocket"
"github.com/coder/websocket/wsjson"
)
func Dial(ctx context.Context, url string) (*websocket.Conn, error) {
conn, _, err := websocket.Dial(ctx, url, nil)
if err == nil {
conn.SetReadLimit(8 << 20)
}
return conn, err
}
func Send(ctx context.Context, conn *websocket.Conn, request protocol.Message) error {
return wsjson.Write(ctx, conn, request)
}
func Receive(ctx context.Context, conn *websocket.Conn) (protocol.Message, error) {
var response protocol.Message
err := wsjson.Read(ctx, conn, &response)
return response, err
}
type Client struct {
Conn *websocket.Conn
mu sync.Mutex
next uint64
}
func Open(ctx context.Context, url string) (*Client, error) {
conn, err := Dial(ctx, url)
if err != nil {
return nil, err
}
return &Client{Conn: conn}, nil
}
func (c *Client) Close() { c.Conn.CloseNow() }
// Call serializes request/reply pairs, skipping the unsolicited welcome envelope.
func (c *Client) Call(ctx context.Context, request protocol.Message) (protocol.Message, error) {
c.mu.Lock()
defer c.mu.Unlock()
c.next++
request.ID = "cli-" + strconv.FormatUint(c.next, 10)
if err := Send(ctx, c.Conn, request); err != nil {
return protocol.Message{}, err
}
for {
response, err := Receive(ctx, c.Conn)
if err != nil {
return response, err
}
if response.ID != request.ID {
continue
}
if response.Type == protocol.Error {
return response, fmt.Errorf("%s", response.Error)
}
return response, nil
}
}