// 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" "encoding/json" "fmt" "strconv" "strings" "sync" "git.a-wan.net/alan/pipelines/internal/buildinfo" "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) { // O(1) exact string compare; only an explicit, validated Docker transport // alias for this same endpoint is ever rewritten. conn, _, err := websocket.Dial(ctx, transportTarget(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) } // Reporter receives a build/protocol relationship notice for display. It is // called at most once per distinct notice on a connection. type Reporter func(buildinfo.Relationship) // Watch compares each received frame with this client build and records the // once-only identity and unrecognized-field notices for one server connection. // The zero value is ready to use; a nil Watch reports every warning unfiltered. type Watch struct { mu sync.Mutex identityReported bool unknownReported bool } // Observe classifies one received frame. It returns the notices that have not // already been shown on this connection and, when the server speaks a newer // protocol than this client interprets, an error naming both builds and both // protocols so the caller must not act on the frame. func (w *Watch) Observe(data []byte, response protocol.Message) ([]buildinfo.Relationship, error) { client := buildinfo.Current() relation := buildinfo.Compare(client, protocol.MaxSupportedProtocol, response.Protocol, response.Build) if relation.Severity == buildinfo.Refuse { return nil, fmt.Errorf("%s", relation.Message) } if w == nil { if relation.Severity == buildinfo.Warn { return []buildinfo.Relationship{relation}, nil } return nil, nil } w.mu.Lock() defer w.mu.Unlock() var notices []buildinfo.Relationship if relation.Severity == buildinfo.Warn && !w.identityReported { w.identityReported = true notices = append(notices, relation) } // A top-level key this client does not model would otherwise be dropped // silently: report the mismatch once instead of appearing to have no data. if unknown := protocol.UnknownFields(data); len(unknown) > 0 && !w.unknownReported { w.unknownReported = true notices = append(notices, buildinfo.Relationship{ Severity: buildinfo.Warn, Message: fmt.Sprintf( "server sent unrecognized top-level field(s) %s; this client may be older than the server (client build %s)", strings.Join(unknown, ", "), buildinfo.Describe(&client)), }) } return notices, nil } // read reads one text frame and decodes it, keeping the raw bytes so unmodeled // top-level keys can be detected without a second decode. func read(ctx context.Context, conn *websocket.Conn) (protocol.Message, []byte, error) { kind, data, err := conn.Read(ctx) if err != nil { return protocol.Message{}, nil, err } if kind != websocket.MessageText { return protocol.Message{}, data, fmt.Errorf("unexpected websocket message type %d", kind) } var response protocol.Message if err := json.Unmarshal(data, &response); err != nil { return protocol.Message{}, data, err } return response, data, nil } // ReceiveNotice reads and decodes one frame, returning the once-only // identity/unrecognized-field notices for display. A non-nil error means the // frame must not be used: an unsafe newer server, or a transport/decode failure. func ReceiveNotice(ctx context.Context, conn *websocket.Conn, watch *Watch) (protocol.Message, []string, error) { response, data, err := read(ctx, conn) if err != nil { return response, nil, err } relations, err := watch.Observe(data, response) notices := make([]string, 0, len(relations)) for _, relation := range relations { if relation.Message != "" { notices = append(notices, relation.Message) } } return response, notices, err } // Receive reads and decodes one frame without reporting its identity. Most // callers should use ReceiveNotice so an older or newer server is never silent. func Receive(ctx context.Context, conn *websocket.Conn) (protocol.Message, error) { response, _, err := ReceiveNotice(ctx, conn, nil) return response, err } type Client struct { Conn *websocket.Conn mu sync.Mutex next uint64 watch Watch reportMu sync.Mutex report Reporter } 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() } // Report installs the notice reporter used by Call. Set it once after Open and // before the first Call; a nil reporter still fails on an unsafe newer server. func (c *Client) Report(report Reporter) { c.reportMu.Lock() c.report = report c.reportMu.Unlock() } // 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, notices, err := ReceiveNotice(ctx, c.Conn, &c.watch) for _, notice := range notices { c.reportMu.Lock() report := c.report c.reportMu.Unlock() if report != nil { report(buildinfo.Relationship{Severity: buildinfo.Warn, Message: notice}) } } 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 } }