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 "github.com/bnema/gordon/internal/adapters/dto"
16 "github.com/bnema/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: 2 * time.Minute,
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// AttachmentSecrets represents secrets for an attachment container.
244type AttachmentSecrets struct {
245 Service string `json:"service"`
246 Keys []string `json:"keys"`
247}
248
249// SecretsListResult contains domain secrets and any attachment secrets.
250type SecretsListResult struct {
251 Domain string `json:"domain"`
252 Keys []string `json:"keys"`
253 Attachments []AttachmentSecrets `json:"attachments,omitempty"`
254}
255
256// ListSecrets returns the list of secret keys for a domain.
257func (c *Client) ListSecrets(ctx context.Context, secretDomain string) ([]string, error) {
258 result, err := c.ListSecretsWithAttachments(ctx, secretDomain)
259 if err != nil {
260 return nil, err
261 }
262 return result.Keys, nil
263}
264
265// ListSecretsWithAttachments returns domain secrets and attachment secrets.
266func (c *Client) ListSecretsWithAttachments(ctx context.Context, secretDomain string) (*SecretsListResult, error) {
267 resp, err := c.request(ctx, http.MethodGet, "/secrets/"+url.PathEscape(secretDomain), nil)
268 if err != nil {
269 return nil, err
270 }
271
272 var result SecretsListResult
273 if err := parseResponse(resp, &result); err != nil {
274 return nil, err
275 }
276
277 return &result, nil
278}
279
280// SetSecrets sets secrets for a domain.
281func (c *Client) SetSecrets(ctx context.Context, secretDomain string, secrets map[string]string) error {
282 resp, err := c.request(ctx, http.MethodPost, "/secrets/"+url.PathEscape(secretDomain), secrets)
283 if err != nil {
284 return err
285 }
286 return parseResponse(resp, nil)
287}
288
289// DeleteSecret removes a secret from a domain.
290func (c *Client) DeleteSecret(ctx context.Context, secretDomain, key string) error {
291 resp, err := c.request(ctx, http.MethodDelete, "/secrets/"+url.PathEscape(secretDomain)+"/"+url.PathEscape(key), nil)
292 if err != nil {
293 return err
294 }
295 return parseResponse(resp, nil)
296}
297
298// Status API
299
300// Status represents the Gordon server status.
301type Status struct {
302 Routes int `json:"routes"`
303 RegistryDomain string `json:"registry_domain"`
304 RegistryPort int `json:"registry_port"`
305 ServerPort int `json:"server_port"`
306 AutoRoute bool `json:"auto_route"`
307 NetworkIsolation bool `json:"network_isolation"`
308 ContainerStatus map[string]string `json:"container_status"`
309}
310
311// GetStatus returns the Gordon server status.
312func (c *Client) GetStatus(ctx context.Context) (*Status, error) {
313 resp, err := c.request(ctx, http.MethodGet, "/status", nil)
314 if err != nil {
315 return nil, err
316 }
317
318 var status Status
319 if err := parseResponse(resp, &status); err != nil {
320 return nil, err
321 }
322
323 return &status, nil
324}
325
326// RouteHealth represents the health status of a route.
327type RouteHealth struct {
328 ContainerStatus string `json:"container_status"`
329 HTTPStatus int `json:"http_status"`
330 ResponseTimeMs int64 `json:"response_time_ms"`
331 Healthy bool `json:"healthy"`
332 Error string `json:"error"`
333}
334
335// GetHealth returns health status for all routes with HTTP probing.
336func (c *Client) GetHealth(ctx context.Context) (map[string]*RouteHealth, error) {
337 resp, err := c.request(ctx, http.MethodGet, "/health", nil)
338 if err != nil {
339 return nil, err
340 }
341
342 var result struct {
343 Health map[string]*RouteHealth `json:"health"`
344 }
345 if err := parseResponse(resp, &result); err != nil {
346 return nil, err
347 }
348
349 return result.Health, nil
350}
351
352// Reload triggers a configuration reload.
353func (c *Client) Reload(ctx context.Context) error {
354 resp, err := c.request(ctx, http.MethodPost, "/reload", nil)
355 if err != nil {
356 return err
357 }
358 return parseResponse(resp, nil)
359}
360
361// Config API
362
363// Config represents the Gordon configuration.
364type Config struct {
365 Server struct {
366 Port int `json:"port"`
367 RegistryPort int `json:"registry_port"`
368 RegistryDomain string `json:"registry_domain"`
369 DataDir string `json:"data_dir"`
370 } `json:"server"`
371 AutoRoute struct {
372 Enabled bool `json:"enabled"`
373 } `json:"auto_route"`
374 NetworkIsolation struct {
375 Enabled bool `json:"enabled"`
376 Prefix string `json:"prefix"`
377 } `json:"network_isolation"`
378 Routes []domain.Route `json:"routes"`
379 ExternalRoutes map[string]string `json:"external_routes"`
380}
381
382// GetConfig returns the Gordon configuration.
383func (c *Client) GetConfig(ctx context.Context) (*Config, error) {
384 resp, err := c.request(ctx, http.MethodGet, "/config", nil)
385 if err != nil {
386 return nil, err
387 }
388
389 var config Config
390 if err := parseResponse(resp, &config); err != nil {
391 return nil, err
392 }
393
394 return &config, nil
395}
396
397// Ping checks if the remote Gordon instance is reachable.
398func (c *Client) Ping(ctx context.Context) error {
399 _, err := c.GetStatus(ctx)
400 return err
401}
402
403// Deploy API
404
405// DeployResult contains the result of a deployment.
406type DeployResult struct {
407 Status string `json:"status"`
408 ContainerID string `json:"container_id"`
409 Domain string `json:"domain"`
410}
411
412// Deploy triggers a deployment for the specified domain.
413func (c *Client) Deploy(ctx context.Context, deployDomain string) (*DeployResult, error) {
414 resp, err := c.request(ctx, http.MethodPost, "/deploy/"+url.PathEscape(deployDomain), nil)
415 if err != nil {
416 return nil, err
417 }
418
419 var result DeployResult
420 if err := parseResponse(resp, &result); err != nil {
421 return nil, err
422 }
423
424 return &result, nil
425}
426
427// Restart API
428
429// RestartResult contains the result of a restart.
430type RestartResult struct {
431 Status string `json:"status"`
432 Domain string `json:"domain"`
433}
434
435// Restart triggers a container restart for the specified domain.
436func (c *Client) Restart(ctx context.Context, restartDomain string, withAttachments bool) (*RestartResult, error) {
437 if restartDomain == "" {
438 return nil, fmt.Errorf("domain cannot be empty")
439 }
440 path := "/restart/" + url.PathEscape(restartDomain)
441 if withAttachments {
442 path += "?attachments=true"
443 }
444 resp, err := c.request(ctx, http.MethodPost, path, nil)
445 if err != nil {
446 return nil, err
447 }
448
449 var result RestartResult
450 if err := parseResponse(resp, &result); err != nil {
451 return nil, err
452 }
453
454 return &result, nil
455}
456
457// Tags API
458
459// ListTags returns available tags for a repository.
460func (c *Client) ListTags(ctx context.Context, repository string) ([]string, error) {
461 if repository == "" {
462 return nil, fmt.Errorf("repository cannot be empty")
463 }
464 resp, err := c.request(ctx, http.MethodGet, "/tags/"+url.PathEscape(repository), nil)
465 if err != nil {
466 return nil, err
467 }
468 var result struct {
469 Repository string `json:"repository"`
470 Tags []string `json:"tags"`
471 }
472 if err := parseResponse(resp, &result); err != nil {
473 return nil, err
474 }
475 return result.Tags, nil
476}
477
478// Logs API
479
480// GetProcessLogs returns Gordon process logs.
481func (c *Client) GetProcessLogs(ctx context.Context, lines int) ([]string, error) {
482 path := fmt.Sprintf("/logs?lines=%d", lines)
483 resp, err := c.request(ctx, http.MethodGet, path, nil)
484 if err != nil {
485 return nil, err
486 }
487
488 var result struct {
489 Lines []string `json:"lines"`
490 }
491 if err := parseResponse(resp, &result); err != nil {
492 return nil, err
493 }
494
495 return result.Lines, nil
496}
497
498// GetContainerLogs returns container logs for a specific domain.
499func (c *Client) GetContainerLogs(ctx context.Context, logDomain string, lines int) ([]string, error) {
500 path := fmt.Sprintf("/logs/%s?lines=%d", url.PathEscape(logDomain), lines)
501 resp, err := c.request(ctx, http.MethodGet, path, nil)
502 if err != nil {
503 return nil, err
504 }
505
506 var result struct {
507 Domain string `json:"domain"`
508 Lines []string `json:"lines"`
509 }
510 if err := parseResponse(resp, &result); err != nil {
511 return nil, err
512 }
513
514 return result.Lines, nil
515}
516
517// StreamProcessLogs returns a channel that streams Gordon process log lines via SSE.
518// The caller is responsible for reading from the channel until it's closed.
519func (c *Client) StreamProcessLogs(ctx context.Context, lines int) (<-chan string, error) {
520 path := fmt.Sprintf("/logs?lines=%d&follow=true", lines)
521 return c.streamLogs(ctx, path)
522}
523
524// StreamContainerLogs returns a channel that streams container log lines via SSE.
525// The caller is responsible for reading from the channel until it's closed.
526func (c *Client) StreamContainerLogs(ctx context.Context, logDomain string, lines int) (<-chan string, error) {
527 path := fmt.Sprintf("/logs/%s?lines=%d&follow=true", url.PathEscape(logDomain), lines)
528 return c.streamLogs(ctx, path)
529}
530
531// Attachments Config API
532
533// GetAllAttachmentsConfig returns all configured attachments.
534func (c *Client) GetAllAttachmentsConfig(ctx context.Context) (map[string][]string, error) {
535 resp, err := c.request(ctx, http.MethodGet, "/attachments", nil)
536 if err != nil {
537 return nil, err
538 }
539
540 var result struct {
541 Attachments map[string][]string `json:"attachments"`
542 }
543 if err := parseResponse(resp, &result); err != nil {
544 return nil, err
545 }
546
547 return result.Attachments, nil
548}
549
550// GetAttachmentsConfig returns attachments for a specific domain/group from config.
551func (c *Client) GetAttachmentsConfig(ctx context.Context, domainOrGroup string) ([]string, error) {
552 if domainOrGroup == "" {
553 return nil, fmt.Errorf("domain or group is required")
554 }
555 path := "/attachments/" + url.PathEscape(domainOrGroup)
556 resp, err := c.request(ctx, http.MethodGet, path, nil)
557 if err != nil {
558 return nil, err
559 }
560
561 var result struct {
562 Target string `json:"target"`
563 Images []string `json:"images"`
564 }
565 if err := parseResponse(resp, &result); err != nil {
566 return nil, err
567 }
568
569 return result.Images, nil
570}
571
572// AddAttachment adds an attachment to a domain/group.
573func (c *Client) AddAttachment(ctx context.Context, domainOrGroup, image string) error {
574 if domainOrGroup == "" {
575 return fmt.Errorf("domain or group is required")
576 }
577 if image == "" {
578 return fmt.Errorf("image is required")
579 }
580 path := "/attachments/" + url.PathEscape(domainOrGroup)
581 resp, err := c.request(ctx, http.MethodPost, path, struct {
582 Image string `json:"image"`
583 }{Image: image})
584 if err != nil {
585 return err
586 }
587 return parseResponse(resp, nil)
588}
589
590// RemoveAttachment removes an attachment from a domain/group.
591func (c *Client) RemoveAttachment(ctx context.Context, domainOrGroup, image string) error {
592 if domainOrGroup == "" {
593 return fmt.Errorf("domain or group is required")
594 }
595 if image == "" {
596 return fmt.Errorf("image is required")
597 }
598 path := "/attachments/" + url.PathEscape(domainOrGroup) + "/" + url.PathEscape(image)
599 resp, err := c.request(ctx, http.MethodDelete, path, nil)
600 if err != nil {
601 return err
602 }
603 return parseResponse(resp, nil)
604}
605
606// streamLogs handles SSE streaming for log endpoints.
607func (c *Client) streamLogs(ctx context.Context, path string) (<-chan string, error) {
608 url := c.baseURL + "/admin" + path
609
610 req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
611 if err != nil {
612 return nil, fmt.Errorf("failed to create request: %w", err)
613 }
614
615 req.Header.Set("Accept", "text/event-stream")
616 if c.token != "" {
617 req.Header.Set("Authorization", "Bearer "+c.token)
618 }
619
620 // Use a client without timeout for streaming
621 streamClient := &http.Client{}
622 resp, err := streamClient.Do(req)
623 if err != nil {
624 return nil, fmt.Errorf("failed to connect: %w", err)
625 }
626
627 if resp.StatusCode >= 400 {
628 body, _ := io.ReadAll(resp.Body)
629 resp.Body.Close()
630 return nil, fmt.Errorf("%s: %s", resp.Status, string(body))
631 }
632
633 ch := make(chan string, 100)
634
635 go func() {
636 defer close(ch)
637 defer resp.Body.Close()
638
639 buf := make([]byte, 4096)
640 var lineBuffer strings.Builder
641
642 for {
643 select {
644 case <-ctx.Done():
645 return
646 default:
647 }
648
649 n, err := resp.Body.Read(buf)
650 if n > 0 {
651 lineBuffer.Write(buf[:n])
652 }
653 if err != nil {
654 return // EOF or context cancellation — clean exit
655 }
656
657 // Process complete SSE events
658 for {
659 data := lineBuffer.String()
660 idx := strings.Index(data, "\n\n")
661 if idx == -1 {
662 break
663 }
664
665 event := data[:idx]
666 lineBuffer.Reset()
667 lineBuffer.WriteString(data[idx+2:])
668
669 // Parse SSE data lines
670 for _, line := range strings.Split(event, "\n") {
671 if strings.HasPrefix(line, "data: ") {
672 logLine := strings.TrimPrefix(line, "data: ")
673 select {
674 case ch <- logLine:
675 case <-ctx.Done():
676 return
677 }
678 }
679 }
680 }
681 }
682 }()
683
684 return ch, nil
685}
686
687// VerifyAuth checks if authentication session is valid.
688func (c *Client) VerifyAuth(ctx context.Context) (*dto.AuthVerifyResponse, error) {
689 resp, err := c.request(ctx, http.MethodGet, "/auth/verify", nil)
690 if err != nil {
691 return nil, err
692 }
693
694 var result dto.AuthVerifyResponse
695 if err := parseResponse(resp, &result); err != nil {
696 return nil, err
697 }
698
699 return &result, nil
700}