1// Package remote provides an HTTP client for connecting to remote Gordon instances.
2package remote
3
4import (
5 "bytes"
6 "context"
7 "encoding/json"
8 "fmt"
9 "io"
10 "net/http"
11 "net/url"
12 "strings"
13 "time"
14
15 "gordon/internal/adapters/dto"
16 "gordon/internal/domain"
17)
18
19// Client is an HTTP client for the Gordon admin API.
20type Client struct {
21 baseURL string
22 token string
23 httpClient *http.Client
24}
25
26// ClientOption configures the Client.
27type ClientOption func(*Client)
28
29// NewClient creates a new remote Gordon client.
30func NewClient(baseURL string, opts ...ClientOption) *Client {
31 // Normalize base URL
32 baseURL = strings.TrimSuffix(baseURL, "/")
33
34 c := &Client{
35 baseURL: baseURL,
36 httpClient: &http.Client{
37 Timeout: 30 * time.Second,
38 },
39 }
40
41 for _, opt := range opts {
42 opt(c)
43 }
44
45 return c
46}
47
48// WithToken sets the authentication token.
49func WithToken(token string) ClientOption {
50 return func(c *Client) {
51 c.token = token
52 }
53}
54
55// WithHTTPClient sets a custom HTTP client.
56func WithHTTPClient(client *http.Client) ClientOption {
57 return func(c *Client) {
58 c.httpClient = client
59 }
60}
61
62// WithTimeout sets the HTTP client timeout.
63func WithTimeout(timeout time.Duration) ClientOption {
64 return func(c *Client) {
65 c.httpClient.Timeout = timeout
66 }
67}
68
69// request performs an HTTP request to the admin API.
70func (c *Client) request(ctx context.Context, method, path string, body any) (*http.Response, error) {
71 url := c.baseURL + "/admin" + path
72
73 var bodyReader io.Reader
74 if body != nil {
75 jsonBody, err := json.Marshal(body)
76 if err != nil {
77 return nil, fmt.Errorf("failed to marshal request body: %w", err)
78 }
79 bodyReader = bytes.NewReader(jsonBody)
80 }
81
82 req, err := http.NewRequestWithContext(ctx, method, url, bodyReader)
83 if err != nil {
84 return nil, fmt.Errorf("failed to create request: %w", err)
85 }
86
87 req.Header.Set("Content-Type", "application/json")
88 req.Header.Set("Accept", "application/json")
89
90 if c.token != "" {
91 req.Header.Set("Authorization", "Bearer "+c.token)
92 }
93
94 return c.httpClient.Do(req)
95}
96
97// parseResponse parses a JSON response into the given target.
98func parseResponse(resp *http.Response, target any) error {
99 defer resp.Body.Close()
100
101 if resp.StatusCode >= 400 {
102 body, _ := io.ReadAll(resp.Body)
103 var errResp struct {
104 Error string `json:"error"`
105 }
106 if err := json.Unmarshal(body, &errResp); err == nil && errResp.Error != "" {
107 return fmt.Errorf("%s: %s", resp.Status, errResp.Error)
108 }
109 return fmt.Errorf("%s: %s", resp.Status, string(body))
110 }
111
112 if target != nil {
113 if err := json.NewDecoder(resp.Body).Decode(target); err != nil {
114 return fmt.Errorf("failed to decode response: %w", err)
115 }
116 }
117
118 return nil
119}
120
121// Routes API
122
123// Type aliases for API types using shared DTO package.
124type RouteInfo = dto.RouteInfo
125type Attachment = dto.Attachment
126
127// ListRoutes returns all configured routes.
128func (c *Client) ListRoutes(ctx context.Context) ([]domain.Route, error) {
129 resp, err := c.request(ctx, http.MethodGet, "/routes", nil)
130 if err != nil {
131 return nil, err
132 }
133
134 var result struct {
135 Routes []domain.Route `json:"routes"`
136 }
137 if err := parseResponse(resp, &result); err != nil {
138 return nil, err
139 }
140
141 return result.Routes, nil
142}
143
144// ListRoutesWithDetails returns routes with network and attachment info.
145func (c *Client) ListRoutesWithDetails(ctx context.Context) ([]RouteInfo, error) {
146 resp, err := c.request(ctx, http.MethodGet, "/routes?detailed=true", nil)
147 if err != nil {
148 return nil, err
149 }
150
151 var result struct {
152 Routes []RouteInfo `json:"routes"`
153 }
154 if err := parseResponse(resp, &result); err != nil {
155 return nil, err
156 }
157
158 return result.Routes, nil
159}
160
161// ListNetworks returns Gordon-managed networks.
162func (c *Client) ListNetworks(ctx context.Context) ([]*domain.NetworkInfo, error) {
163 resp, err := c.request(ctx, http.MethodGet, "/networks", nil)
164 if err != nil {
165 return nil, err
166 }
167
168 var result struct {
169 Networks []*domain.NetworkInfo `json:"networks"`
170 }
171 if err := parseResponse(resp, &result); err != nil {
172 return nil, err
173 }
174
175 return result.Networks, nil
176}
177
178// ListAttachments returns attachments for a domain.
179func (c *Client) ListAttachments(ctx context.Context, routeDomain string) ([]Attachment, error) {
180 if routeDomain == "" {
181 return nil, fmt.Errorf("domain is required")
182 }
183 path := "/routes/" + url.PathEscape(routeDomain) + "/attachments"
184 resp, err := c.request(ctx, http.MethodGet, path, nil)
185 if err != nil {
186 return nil, err
187 }
188
189 var result struct {
190 Attachments []Attachment `json:"attachments"`
191 }
192 if err := parseResponse(resp, &result); err != nil {
193 return nil, err
194 }
195
196 return result.Attachments, nil
197}
198
199// GetRoute returns a specific route by domain.
200func (c *Client) GetRoute(ctx context.Context, routeDomain string) (*domain.Route, error) {
201 resp, err := c.request(ctx, http.MethodGet, "/routes/"+url.PathEscape(routeDomain), nil)
202 if err != nil {
203 return nil, err
204 }
205
206 var route domain.Route
207 if err := parseResponse(resp, &route); err != nil {
208 return nil, err
209 }
210
211 return &route, nil
212}
213
214// AddRoute adds a new route.
215func (c *Client) AddRoute(ctx context.Context, route domain.Route) error {
216 resp, err := c.request(ctx, http.MethodPost, "/routes", route)
217 if err != nil {
218 return err
219 }
220 return parseResponse(resp, nil)
221}
222
223// UpdateRoute updates an existing route.
224func (c *Client) UpdateRoute(ctx context.Context, route domain.Route) error {
225 resp, err := c.request(ctx, http.MethodPut, "/routes/"+url.PathEscape(route.Domain), route)
226 if err != nil {
227 return err
228 }
229 return parseResponse(resp, nil)
230}
231
232// RemoveRoute removes a route by domain.
233func (c *Client) RemoveRoute(ctx context.Context, routeDomain string) error {
234 resp, err := c.request(ctx, http.MethodDelete, "/routes/"+url.PathEscape(routeDomain), nil)
235 if err != nil {
236 return err
237 }
238 return parseResponse(resp, nil)
239}
240
241// Secrets API
242
243// ListSecrets returns the list of secret keys for a domain.
244func (c *Client) ListSecrets(ctx context.Context, secretDomain string) ([]string, error) {
245 resp, err := c.request(ctx, http.MethodGet, "/secrets/"+url.PathEscape(secretDomain), nil)
246 if err != nil {
247 return nil, err
248 }
249
250 var result struct {
251 Domain string `json:"domain"`
252 Keys []string `json:"keys"`
253 }
254 if err := parseResponse(resp, &result); err != nil {
255 return nil, err
256 }
257
258 return result.Keys, nil
259}
260
261// SetSecrets sets secrets for a domain.
262func (c *Client) SetSecrets(ctx context.Context, secretDomain string, secrets map[string]string) error {
263 resp, err := c.request(ctx, http.MethodPost, "/secrets/"+url.PathEscape(secretDomain), secrets)
264 if err != nil {
265 return err
266 }
267 return parseResponse(resp, nil)
268}
269
270// DeleteSecret removes a secret from a domain.
271func (c *Client) DeleteSecret(ctx context.Context, secretDomain, key string) error {
272 resp, err := c.request(ctx, http.MethodDelete, "/secrets/"+url.PathEscape(secretDomain)+"/"+url.PathEscape(key), nil)
273 if err != nil {
274 return err
275 }
276 return parseResponse(resp, nil)
277}
278
279// Status API
280
281// Status represents the Gordon server status.
282type Status struct {
283 Routes int `json:"routes"`
284 RegistryDomain string `json:"registry_domain"`
285 RegistryPort int `json:"registry_port"`
286 ServerPort int `json:"server_port"`
287 AutoRoute bool `json:"auto_route"`
288 NetworkIsolation bool `json:"network_isolation"`
289 ContainerStatus map[string]string `json:"container_status"`
290}
291
292// GetStatus returns the Gordon server status.
293func (c *Client) GetStatus(ctx context.Context) (*Status, error) {
294 resp, err := c.request(ctx, http.MethodGet, "/status", nil)
295 if err != nil {
296 return nil, err
297 }
298
299 var status Status
300 if err := parseResponse(resp, &status); err != nil {
301 return nil, err
302 }
303
304 return &status, nil
305}
306
307// RouteHealth represents the health status of a route.
308type RouteHealth struct {
309 ContainerStatus string `json:"container_status"`
310 HTTPStatus int `json:"http_status"`
311 ResponseTimeMs int64 `json:"response_time_ms"`
312 Healthy bool `json:"healthy"`
313 Error string `json:"error"`
314}
315
316// GetHealth returns health status for all routes with HTTP probing.
317func (c *Client) GetHealth(ctx context.Context) (map[string]*RouteHealth, error) {
318 resp, err := c.request(ctx, http.MethodGet, "/health", nil)
319 if err != nil {
320 return nil, err
321 }
322
323 var result struct {
324 Health map[string]*RouteHealth `json:"health"`
325 }
326 if err := parseResponse(resp, &result); err != nil {
327 return nil, err
328 }
329
330 return result.Health, nil
331}
332
333// Reload triggers a configuration reload.
334func (c *Client) Reload(ctx context.Context) error {
335 resp, err := c.request(ctx, http.MethodPost, "/reload", nil)
336 if err != nil {
337 return err
338 }
339 return parseResponse(resp, nil)
340}
341
342// Config API
343
344// Config represents the Gordon configuration.
345type Config struct {
346 Server struct {
347 Port int `json:"port"`
348 RegistryPort int `json:"registry_port"`
349 RegistryDomain string `json:"registry_domain"`
350 DataDir string `json:"data_dir"`
351 } `json:"server"`
352 AutoRoute struct {
353 Enabled bool `json:"enabled"`
354 } `json:"auto_route"`
355 NetworkIsolation struct {
356 Enabled bool `json:"enabled"`
357 Prefix string `json:"prefix"`
358 } `json:"network_isolation"`
359 Routes []domain.Route `json:"routes"`
360 ExternalRoutes map[string]string `json:"external_routes"`
361}
362
363// GetConfig returns the Gordon configuration.
364func (c *Client) GetConfig(ctx context.Context) (*Config, error) {
365 resp, err := c.request(ctx, http.MethodGet, "/config", nil)
366 if err != nil {
367 return nil, err
368 }
369
370 var config Config
371 if err := parseResponse(resp, &config); err != nil {
372 return nil, err
373 }
374
375 return &config, nil
376}
377
378// Ping checks if the remote Gordon instance is reachable.
379func (c *Client) Ping(ctx context.Context) error {
380 _, err := c.GetStatus(ctx)
381 return err
382}
383
384// Deploy API
385
386// DeployResult contains the result of a deployment.
387type DeployResult struct {
388 Status string `json:"status"`
389 ContainerID string `json:"container_id"`
390 Domain string `json:"domain"`
391}
392
393// Deploy triggers a deployment for the specified domain.
394func (c *Client) Deploy(ctx context.Context, deployDomain string) (*DeployResult, error) {
395 resp, err := c.request(ctx, http.MethodPost, "/deploy/"+url.PathEscape(deployDomain), nil)
396 if err != nil {
397 return nil, err
398 }
399
400 var result DeployResult
401 if err := parseResponse(resp, &result); err != nil {
402 return nil, err
403 }
404
405 return &result, nil
406}
407
408// Logs API
409
410// GetProcessLogs returns Gordon process logs.
411func (c *Client) GetProcessLogs(ctx context.Context, lines int) ([]string, error) {
412 path := fmt.Sprintf("/logs?lines=%d", lines)
413 resp, err := c.request(ctx, http.MethodGet, path, nil)
414 if err != nil {
415 return nil, err
416 }
417
418 var result struct {
419 Lines []string `json:"lines"`
420 }
421 if err := parseResponse(resp, &result); err != nil {
422 return nil, err
423 }
424
425 return result.Lines, nil
426}
427
428// GetContainerLogs returns container logs for a specific domain.
429func (c *Client) GetContainerLogs(ctx context.Context, logDomain string, lines int) ([]string, error) {
430 path := fmt.Sprintf("/logs/%s?lines=%d", url.PathEscape(logDomain), lines)
431 resp, err := c.request(ctx, http.MethodGet, path, nil)
432 if err != nil {
433 return nil, err
434 }
435
436 var result struct {
437 Domain string `json:"domain"`
438 Lines []string `json:"lines"`
439 }
440 if err := parseResponse(resp, &result); err != nil {
441 return nil, err
442 }
443
444 return result.Lines, nil
445}
446
447// StreamProcessLogs returns a channel that streams Gordon process log lines via SSE.
448// The caller is responsible for reading from the channel until it's closed.
449func (c *Client) StreamProcessLogs(ctx context.Context, lines int) (<-chan string, error) {
450 path := fmt.Sprintf("/logs?lines=%d&follow=true", lines)
451 return c.streamLogs(ctx, path)
452}
453
454// StreamContainerLogs returns a channel that streams container log lines via SSE.
455// The caller is responsible for reading from the channel until it's closed.
456func (c *Client) StreamContainerLogs(ctx context.Context, logDomain string, lines int) (<-chan string, error) {
457 path := fmt.Sprintf("/logs/%s?lines=%d&follow=true", url.PathEscape(logDomain), lines)
458 return c.streamLogs(ctx, path)
459}
460
461// Attachments Config API
462
463// GetAllAttachmentsConfig returns all configured attachments.
464func (c *Client) GetAllAttachmentsConfig(ctx context.Context) (map[string][]string, error) {
465 resp, err := c.request(ctx, http.MethodGet, "/attachments", nil)
466 if err != nil {
467 return nil, err
468 }
469
470 var result struct {
471 Attachments map[string][]string `json:"attachments"`
472 }
473 if err := parseResponse(resp, &result); err != nil {
474 return nil, err
475 }
476
477 return result.Attachments, nil
478}
479
480// GetAttachmentsConfig returns attachments for a specific domain/group from config.
481func (c *Client) GetAttachmentsConfig(ctx context.Context, domainOrGroup string) ([]string, error) {
482 if domainOrGroup == "" {
483 return nil, fmt.Errorf("domain or group is required")
484 }
485 path := "/attachments/" + url.PathEscape(domainOrGroup)
486 resp, err := c.request(ctx, http.MethodGet, path, nil)
487 if err != nil {
488 return nil, err
489 }
490
491 var result struct {
492 Target string `json:"target"`
493 Images []string `json:"images"`
494 }
495 if err := parseResponse(resp, &result); err != nil {
496 return nil, err
497 }
498
499 return result.Images, nil
500}
501
502// AddAttachment adds an attachment to a domain/group.
503func (c *Client) AddAttachment(ctx context.Context, domainOrGroup, image string) error {
504 if domainOrGroup == "" {
505 return fmt.Errorf("domain or group is required")
506 }
507 if image == "" {
508 return fmt.Errorf("image is required")
509 }
510 path := "/attachments/" + url.PathEscape(domainOrGroup)
511 resp, err := c.request(ctx, http.MethodPost, path, struct {
512 Image string `json:"image"`
513 }{Image: image})
514 if err != nil {
515 return err
516 }
517 return parseResponse(resp, nil)
518}
519
520// RemoveAttachment removes an attachment from a domain/group.
521func (c *Client) RemoveAttachment(ctx context.Context, domainOrGroup, image string) error {
522 if domainOrGroup == "" {
523 return fmt.Errorf("domain or group is required")
524 }
525 if image == "" {
526 return fmt.Errorf("image is required")
527 }
528 path := "/attachments/" + url.PathEscape(domainOrGroup) + "/" + url.PathEscape(image)
529 resp, err := c.request(ctx, http.MethodDelete, path, nil)
530 if err != nil {
531 return err
532 }
533 return parseResponse(resp, nil)
534}
535
536// streamLogs handles SSE streaming for log endpoints.
537func (c *Client) streamLogs(ctx context.Context, path string) (<-chan string, error) {
538 url := c.baseURL + "/admin" + path
539
540 req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
541 if err != nil {
542 return nil, fmt.Errorf("failed to create request: %w", err)
543 }
544
545 req.Header.Set("Accept", "text/event-stream")
546 if c.token != "" {
547 req.Header.Set("Authorization", "Bearer "+c.token)
548 }
549
550 // Use a client without timeout for streaming
551 streamClient := &http.Client{}
552 resp, err := streamClient.Do(req)
553 if err != nil {
554 return nil, fmt.Errorf("failed to connect: %w", err)
555 }
556
557 if resp.StatusCode >= 400 {
558 body, _ := io.ReadAll(resp.Body)
559 resp.Body.Close()
560 return nil, fmt.Errorf("%s: %s", resp.Status, string(body))
561 }
562
563 ch := make(chan string, 100)
564
565 go func() {
566 defer close(ch)
567 defer resp.Body.Close()
568
569 buf := make([]byte, 4096)
570 var lineBuffer strings.Builder
571
572 for {
573 select {
574 case <-ctx.Done():
575 return
576 default:
577 }
578
579 n, err := resp.Body.Read(buf)
580 if err != nil {
581 // EOF is expected when stream ends, other errors are ignored
582 return
583 }
584
585 lineBuffer.Write(buf[:n])
586
587 // Process complete SSE events
588 for {
589 data := lineBuffer.String()
590 idx := strings.Index(data, "\n\n")
591 if idx == -1 {
592 break
593 }
594
595 event := data[:idx]
596 lineBuffer.Reset()
597 lineBuffer.WriteString(data[idx+2:])
598
599 // Parse SSE data lines
600 for _, line := range strings.Split(event, "\n") {
601 if strings.HasPrefix(line, "data: ") {
602 logLine := strings.TrimPrefix(line, "data: ")
603 select {
604 case ch <- logLine:
605 case <-ctx.Done():
606 return
607 }
608 }
609 }
610 }
611 }
612 }()
613
614 return ch, nil
615}