1package client
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "io"
8 "net"
9 "net/http"
10 "net/url"
11 stdpath "path"
12 "path/filepath"
13 "time"
14
15 "github.com/charmbracelet/crush/internal/config"
16 "github.com/charmbracelet/crush/internal/proto"
17 "github.com/charmbracelet/crush/internal/server"
18)
19
20// DummyHost is used to satisfy the http.Client's requirement for a URL.
21const DummyHost = "api.crush.localhost"
22
23// Client represents an RPC client connected to a Crush server.
24type Client struct {
25 h *http.Client
26 path string
27 network string
28 addr string
29}
30
31// DefaultClient creates a new [Client] connected to the default server address.
32func DefaultClient(path string) (*Client, error) {
33 host, err := server.ParseHostURL(server.DefaultHost())
34 if err != nil {
35 return nil, err
36 }
37 return NewClient(path, host.Scheme, host.Host)
38}
39
40// NewClient creates a new [Client] connected to the server at the given
41// network and address.
42func NewClient(path, network, address string) (*Client, error) {
43 c := new(Client)
44 c.path = filepath.Clean(path)
45 c.network = network
46 c.addr = address
47 p := &http.Protocols{}
48 p.SetHTTP1(true)
49 p.SetUnencryptedHTTP2(true)
50 tr := http.DefaultTransport.(*http.Transport).Clone()
51 tr.Protocols = p
52 tr.DialContext = c.dialer
53 if c.network == "npipe" || c.network == "unix" {
54 tr.DisableCompression = true
55 }
56 c.h = &http.Client{
57 Transport: tr,
58 Timeout: 0,
59 }
60 return c, nil
61}
62
63// Path returns the client's workspace filesystem path.
64func (c *Client) Path() string {
65 return c.path
66}
67
68// GetGlobalConfig retrieves the server's configuration.
69func (c *Client) GetGlobalConfig(ctx context.Context) (*config.Config, error) {
70 var cfg config.Config
71 rsp, err := c.get(ctx, "/config", nil, nil)
72 if err != nil {
73 return nil, err
74 }
75 defer rsp.Body.Close()
76 if err := json.NewDecoder(rsp.Body).Decode(&cfg); err != nil {
77 return nil, err
78 }
79 return &cfg, nil
80}
81
82// Health checks the server's health status.
83func (c *Client) Health(ctx context.Context) error {
84 rsp, err := c.get(ctx, "/health", nil, nil)
85 if err != nil {
86 return err
87 }
88 defer rsp.Body.Close()
89 if rsp.StatusCode != http.StatusOK {
90 return fmt.Errorf("server health check failed: %s", rsp.Status)
91 }
92 return nil
93}
94
95// VersionInfo retrieves the server's version information.
96func (c *Client) VersionInfo(ctx context.Context) (*proto.VersionInfo, error) {
97 var vi proto.VersionInfo
98 rsp, err := c.get(ctx, "version", nil, nil)
99 if err != nil {
100 return nil, err
101 }
102 defer rsp.Body.Close()
103 if err := json.NewDecoder(rsp.Body).Decode(&vi); err != nil {
104 return nil, err
105 }
106 return &vi, nil
107}
108
109// ShutdownServer sends a shutdown request to the server.
110func (c *Client) ShutdownServer(ctx context.Context) error {
111 rsp, err := c.post(ctx, "/control", nil, jsonBody(proto.ServerControl{
112 Command: "shutdown",
113 }), nil)
114 if err != nil {
115 return err
116 }
117 defer rsp.Body.Close()
118 if rsp.StatusCode != http.StatusOK {
119 return fmt.Errorf("server shutdown failed: %s", rsp.Status)
120 }
121 return nil
122}
123
124func (c *Client) dialer(ctx context.Context, network, address string) (net.Conn, error) {
125 d := net.Dialer{
126 Timeout: 30 * time.Second,
127 KeepAlive: 30 * time.Second,
128 }
129 switch c.network {
130 case "npipe":
131 ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
132 defer cancel()
133 return dialPipeContext(ctx, c.addr)
134 case "unix":
135 return d.DialContext(ctx, "unix", c.addr)
136 default:
137 return d.DialContext(ctx, network, address)
138 }
139}
140
141func (c *Client) get(ctx context.Context, path string, query url.Values, headers http.Header) (*http.Response, error) {
142 return c.sendReq(ctx, http.MethodGet, path, query, nil, headers)
143}
144
145func (c *Client) post(ctx context.Context, path string, query url.Values, body io.Reader, headers http.Header) (*http.Response, error) {
146 return c.sendReq(ctx, http.MethodPost, path, query, body, headers)
147}
148
149func (c *Client) delete(ctx context.Context, path string, query url.Values, headers http.Header) (*http.Response, error) {
150 return c.sendReq(ctx, http.MethodDelete, path, query, nil, headers)
151}
152
153func (c *Client) put(ctx context.Context, path string, query url.Values, body io.Reader, headers http.Header) (*http.Response, error) {
154 return c.sendReq(ctx, http.MethodPut, path, query, body, headers)
155}
156
157func (c *Client) sendReq(ctx context.Context, method, path string, query url.Values, body io.Reader, headers http.Header) (*http.Response, error) {
158 url := (&url.URL{
159 Path: stdpath.Join("/v1", path),
160 RawQuery: query.Encode(),
161 }).String()
162 req, err := c.buildReq(ctx, method, url, body, headers)
163 if err != nil {
164 return nil, err
165 }
166
167 rsp, err := c.h.Do(req)
168 if err != nil {
169 return nil, err
170 }
171
172 return rsp, nil
173}
174
175func (c *Client) buildReq(ctx context.Context, method, url string, body io.Reader, headers http.Header) (*http.Request, error) {
176 r, err := http.NewRequestWithContext(ctx, method, url, body)
177 if err != nil {
178 return nil, err
179 }
180
181 for k, v := range headers {
182 r.Header[http.CanonicalHeaderKey(k)] = v
183 }
184
185 r.URL.Scheme = "http"
186 r.URL.Host = c.addr
187 if c.network == "npipe" || c.network == "unix" {
188 r.Host = DummyHost
189 }
190
191 if body != nil && r.Header.Get("Content-Type") == "" {
192 r.Header.Set("Content-Type", "text/plain")
193 }
194
195 return r, nil
196}