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: 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// 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// Logs API
428
429// GetProcessLogs returns Gordon process logs.
430func (c *Client) GetProcessLogs(ctx context.Context, lines int) ([]string, error) {
431 path := fmt.Sprintf("/logs?lines=%d", lines)
432 resp, err := c.request(ctx, http.MethodGet, path, nil)
433 if err != nil {
434 return nil, err
435 }
436
437 var result struct {
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// GetContainerLogs returns container logs for a specific domain.
448func (c *Client) GetContainerLogs(ctx context.Context, logDomain string, lines int) ([]string, error) {
449 path := fmt.Sprintf("/logs/%s?lines=%d", url.PathEscape(logDomain), lines)
450 resp, err := c.request(ctx, http.MethodGet, path, nil)
451 if err != nil {
452 return nil, err
453 }
454
455 var result struct {
456 Domain string `json:"domain"`
457 Lines []string `json:"lines"`
458 }
459 if err := parseResponse(resp, &result); err != nil {
460 return nil, err
461 }
462
463 return result.Lines, nil
464}
465
466// StreamProcessLogs returns a channel that streams Gordon process log lines via SSE.
467// The caller is responsible for reading from the channel until it's closed.
468func (c *Client) StreamProcessLogs(ctx context.Context, lines int) (<-chan string, error) {
469 path := fmt.Sprintf("/logs?lines=%d&follow=true", lines)
470 return c.streamLogs(ctx, path)
471}
472
473// StreamContainerLogs returns a channel that streams container log lines via SSE.
474// The caller is responsible for reading from the channel until it's closed.
475func (c *Client) StreamContainerLogs(ctx context.Context, logDomain string, lines int) (<-chan string, error) {
476 path := fmt.Sprintf("/logs/%s?lines=%d&follow=true", url.PathEscape(logDomain), lines)
477 return c.streamLogs(ctx, path)
478}
479
480// Attachments Config API
481
482// GetAllAttachmentsConfig returns all configured attachments.
483func (c *Client) GetAllAttachmentsConfig(ctx context.Context) (map[string][]string, error) {
484 resp, err := c.request(ctx, http.MethodGet, "/attachments", nil)
485 if err != nil {
486 return nil, err
487 }
488
489 var result struct {
490 Attachments map[string][]string `json:"attachments"`
491 }
492 if err := parseResponse(resp, &result); err != nil {
493 return nil, err
494 }
495
496 return result.Attachments, nil
497}
498
499// GetAttachmentsConfig returns attachments for a specific domain/group from config.
500func (c *Client) GetAttachmentsConfig(ctx context.Context, domainOrGroup string) ([]string, error) {
501 if domainOrGroup == "" {
502 return nil, fmt.Errorf("domain or group is required")
503 }
504 path := "/attachments/" + url.PathEscape(domainOrGroup)
505 resp, err := c.request(ctx, http.MethodGet, path, nil)
506 if err != nil {
507 return nil, err
508 }
509
510 var result struct {
511 Target string `json:"target"`
512 Images []string `json:"images"`
513 }
514 if err := parseResponse(resp, &result); err != nil {
515 return nil, err
516 }
517
518 return result.Images, nil
519}
520
521// AddAttachment adds an attachment to a domain/group.
522func (c *Client) AddAttachment(ctx context.Context, domainOrGroup, image string) error {
523 if domainOrGroup == "" {
524 return fmt.Errorf("domain or group is required")
525 }
526 if image == "" {
527 return fmt.Errorf("image is required")
528 }
529 path := "/attachments/" + url.PathEscape(domainOrGroup)
530 resp, err := c.request(ctx, http.MethodPost, path, struct {
531 Image string `json:"image"`
532 }{Image: image})
533 if err != nil {
534 return err
535 }
536 return parseResponse(resp, nil)
537}
538
539// RemoveAttachment removes an attachment from a domain/group.
540func (c *Client) RemoveAttachment(ctx context.Context, domainOrGroup, image string) error {
541 if domainOrGroup == "" {
542 return fmt.Errorf("domain or group is required")
543 }
544 if image == "" {
545 return fmt.Errorf("image is required")
546 }
547 path := "/attachments/" + url.PathEscape(domainOrGroup) + "/" + url.PathEscape(image)
548 resp, err := c.request(ctx, http.MethodDelete, path, nil)
549 if err != nil {
550 return err
551 }
552 return parseResponse(resp, nil)
553}
554
555// streamLogs handles SSE streaming for log endpoints.
556func (c *Client) streamLogs(ctx context.Context, path string) (<-chan string, error) {
557 url := c.baseURL + "/admin" + path
558
559 req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
560 if err != nil {
561 return nil, fmt.Errorf("failed to create request: %w", err)
562 }
563
564 req.Header.Set("Accept", "text/event-stream")
565 if c.token != "" {
566 req.Header.Set("Authorization", "Bearer "+c.token)
567 }
568
569 // Use a client without timeout for streaming
570 streamClient := &http.Client{}
571 resp, err := streamClient.Do(req)
572 if err != nil {
573 return nil, fmt.Errorf("failed to connect: %w", err)
574 }
575
576 if resp.StatusCode >= 400 {
577 body, _ := io.ReadAll(resp.Body)
578 resp.Body.Close()
579 return nil, fmt.Errorf("%s: %s", resp.Status, string(body))
580 }
581
582 ch := make(chan string, 100)
583
584 go func() {
585 defer close(ch)
586 defer resp.Body.Close()
587
588 buf := make([]byte, 4096)
589 var lineBuffer strings.Builder
590
591 for {
592 select {
593 case <-ctx.Done():
594 return
595 default:
596 }
597
598 n, err := resp.Body.Read(buf)
599 if err != nil {
600 // EOF is expected when stream ends, other errors are ignored
601 return
602 }
603
604 lineBuffer.Write(buf[:n])
605
606 // Process complete SSE events
607 for {
608 data := lineBuffer.String()
609 idx := strings.Index(data, "\n\n")
610 if idx == -1 {
611 break
612 }
613
614 event := data[:idx]
615 lineBuffer.Reset()
616 lineBuffer.WriteString(data[idx+2:])
617
618 // Parse SSE data lines
619 for _, line := range strings.Split(event, "\n") {
620 if strings.HasPrefix(line, "data: ") {
621 logLine := strings.TrimPrefix(line, "data: ")
622 select {
623 case ch <- logLine:
624 case <-ctx.Done():
625 return
626 }
627 }
628 }
629 }
630 }
631 }()
632
633 return ch, nil
634}
635
636// VerifyAuth checks if authentication session is valid.
637func (c *Client) VerifyAuth(ctx context.Context) (*dto.AuthVerifyResponse, error) {
638 resp, err := c.request(ctx, http.MethodGet, "/auth/verify", nil)
639 if err != nil {
640 return nil, err
641 }
642
643 var result dto.AuthVerifyResponse
644 if err := parseResponse(resp, &result); err != nil {
645 return nil, err
646 }
647
648 return &result, nil
649}