1// Package remote provides an HTTP client for connecting to remote Gordon instances.
2package remote
3
4import (
5 "bytes"
6 "context"
7 "crypto/tls"
8 "encoding/json"
9 "errors"
10 "fmt"
11 "io"
12 "net/http"
13 "net/url"
14 "os"
15 "strings"
16 "sync"
17 "time"
18
19 "github.com/golang-jwt/jwt/v5"
20
21 "github.com/bnema/gordon/internal/adapters/dto"
22 "github.com/bnema/gordon/internal/domain"
23)
24
25// Client is an HTTP client for the Gordon admin API.
26type Client struct {
27 baseURL string
28 token string
29 httpClient *http.Client
30 insecureTLS bool
31
32 // Ephemeral admin token exchange fields.
33 mu sync.Mutex // protects ephemeral and ephemeralExp
34 subject string // JWT subject extracted from long-lived token
35 ephemeral string // cached ephemeral admin token
36 ephemeralExp time.Time // expiry of cached ephemeral token
37}
38
39var (
40 retryMaxAttempts = 4
41 retryBaseDelay = 250 * time.Millisecond
42)
43
44const maxErrorBodySize int64 = 1024 // cap error response reads at 1 KB
45
46// ClientOption configures the Client.
47type ClientOption func(*Client)
48
49// NewClient creates a new remote Gordon client.
50func NewClient(baseURL string, opts ...ClientOption) *Client {
51 // Normalize base URL
52 baseURL = strings.TrimSuffix(baseURL, "/")
53
54 c := &Client{
55 baseURL: baseURL,
56 httpClient: &http.Client{
57 Timeout: 2 * time.Minute,
58 },
59 }
60
61 for _, opt := range opts {
62 opt(c)
63 }
64
65 c.applyTLSConfig()
66
67 return c
68}
69
70// WithToken sets the authentication token.
71// The token must be a valid JWT — the subject claim is extracted for
72// ephemeral token exchange. If parsing fails, requests will return
73// an error rather than sending the long-lived token directly.
74func WithToken(token string) ClientOption {
75 return func(c *Client) {
76 c.token = token
77 c.subject = extractJWTSubject(token)
78 }
79}
80
81// extractJWTSubject parses a JWT without verification and returns the
82// "sub" claim. Returns "" if the token is not a valid JWT or has no sub.
83func extractJWTSubject(tokenStr string) string {
84 if tokenStr == "" {
85 return ""
86 }
87 parser := jwt.NewParser()
88 claims := jwt.MapClaims{}
89 // We only need the claims; signature verification happens server-side.
90 _, _, err := parser.ParseUnverified(tokenStr, claims)
91 if err != nil {
92 return ""
93 }
94 sub, _ := claims.GetSubject()
95 return sub
96}
97
98// WithHTTPClient sets a custom HTTP client.
99func WithHTTPClient(client *http.Client) ClientOption {
100 return func(c *Client) {
101 c.httpClient = client
102 }
103}
104
105// WithTimeout sets the HTTP client timeout.
106func WithTimeout(timeout time.Duration) ClientOption {
107 return func(c *Client) {
108 c.httpClient.Timeout = timeout
109 }
110}
111
112// WithInsecureTLS disables TLS certificate verification for remote admin API requests.
113func WithInsecureTLS(insecure bool) ClientOption {
114 return func(c *Client) {
115 c.insecureTLS = insecure
116 }
117}
118
119// ephemeralMargin is the safety margin before expiry at which
120// the cached ephemeral token is considered stale.
121const ephemeralMargin = 30 * time.Second
122
123// ephemeralValid reports whether the cached ephemeral token is still usable.
124func (c *Client) ephemeralValid() bool {
125 return c.ephemeral != "" && time.Now().Before(c.ephemeralExp.Add(-ephemeralMargin))
126}
127
128// exchangeToken exchanges the long-lived token for a short-lived ephemeral
129// admin token via /auth/token. Follows the same pattern as ExchangeRegistryToken.
130// The caller must hold c.mu.
131func (c *Client) exchangeToken(ctx context.Context) error {
132 url := c.baseURL + "/auth/token?scope=admin:*:*&service=gordon-registry"
133
134 req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
135 if err != nil {
136 return fmt.Errorf("ephemeral token exchange: %w", err)
137 }
138
139 req.SetBasicAuth(c.subject, c.token)
140 req.Header.Set("Accept", "application/json")
141
142 resp, err := c.httpClient.Do(req)
143 if err != nil {
144 return fmt.Errorf("ephemeral token exchange: %w", err)
145 }
146 defer resp.Body.Close()
147
148 if resp.StatusCode >= 400 {
149 body, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBodySize))
150 var errResp struct {
151 Error string `json:"error"`
152 }
153 if err := json.Unmarshal(body, &errResp); err == nil && errResp.Error != "" {
154 return fmt.Errorf("ephemeral token exchange: %s: %s", resp.Status, errResp.Error)
155 }
156 return fmt.Errorf("ephemeral token exchange: %s: %s", resp.Status, string(body))
157 }
158
159 var result dto.TokenResponse
160 if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
161 return fmt.Errorf("ephemeral token exchange: decode: %w", err)
162 }
163
164 token := result.Token
165 if token == "" {
166 token = result.AccessToken
167 }
168 if token == "" {
169 return fmt.Errorf("ephemeral token exchange returned empty token")
170 }
171
172 if result.ExpiresIn <= 0 {
173 return fmt.Errorf("ephemeral token exchange: invalid expires_in value: %d", result.ExpiresIn)
174 }
175
176 c.ephemeral = token
177 c.ephemeralExp = time.Now().Add(time.Duration(result.ExpiresIn) * time.Second)
178 return nil
179}
180
181// bearerToken returns the token to use in Authorization headers.
182// It exchanges the long-lived token for an ephemeral one via /auth/token.
183// If subject extraction failed, uses "unknown" — the server validates everything.
184func (c *Client) bearerToken(ctx context.Context) (string, error) {
185 if c.token == "" {
186 return "", nil
187 }
188 if c.subject == "" {
189 c.subject = "unknown"
190 }
191 c.mu.Lock()
192 defer c.mu.Unlock()
193 if !c.ephemeralValid() {
194 if err := c.exchangeToken(ctx); err != nil {
195 return "", err
196 }
197 }
198 return c.ephemeral, nil
199}
200
201func (c *Client) applyTLSConfig() {
202 if !c.insecureTLS {
203 return
204 }
205
206 fmt.Fprintf(os.Stderr, "WARNING: TLS certificate verification disabled for %s\n", c.baseURL)
207
208 var transport *http.Transport
209 switch t := c.httpClient.Transport.(type) {
210 case *http.Transport:
211 transport = t.Clone()
212 case nil:
213 transport = http.DefaultTransport.(*http.Transport).Clone()
214 default:
215 // Cannot apply InsecureSkipVerify to a non-*http.Transport.
216 // Log a warning and leave the transport intact rather than
217 // silently replacing it (which would drop caller-provided behavior).
218 fmt.Fprintf(os.Stderr, "WARNING: --insecure requires *http.Transport, got %T; TLS override not applied\n", t)
219 return
220 }
221
222 if transport.TLSClientConfig == nil {
223 transport.TLSClientConfig = &tls.Config{MinVersion: tls.VersionTLS12}
224 } else {
225 transport.TLSClientConfig.MinVersion = tls.VersionTLS12
226 }
227 //nolint:gosec // Explicit CLI opt-in via --insecure for self-signed/private cert deployments.
228 transport.TLSClientConfig.InsecureSkipVerify = true
229 c.httpClient.Transport = transport
230}
231
232// request performs an HTTP request to the admin API.
233func (c *Client) request(ctx context.Context, method, path string, body any) (*http.Response, error) {
234 // Marshal body once so it can be replayed on 401 retry.
235 var jsonBody []byte
236 if body != nil {
237 var err error
238 jsonBody, err = json.Marshal(body)
239 if err != nil {
240 return nil, fmt.Errorf("failed to marshal request body: %w", err)
241 }
242 }
243
244 resp, err := c.doRequest(ctx, method, path, jsonBody)
245 if err != nil {
246 return nil, err
247 }
248
249 // On 401: invalidate ephemeral, re-exchange, retry once.
250 if resp.StatusCode == http.StatusUnauthorized && c.subject != "" && c.ephemeral != "" {
251 // Drain and close the first response.
252 _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, maxErrorBodySize))
253 resp.Body.Close()
254
255 c.mu.Lock()
256 c.ephemeral = ""
257 c.ephemeralExp = time.Time{}
258 if exErr := c.exchangeToken(ctx); exErr != nil {
259 c.mu.Unlock()
260 return nil, fmt.Errorf("token re-exchange after 401: %w", exErr)
261 }
262 c.mu.Unlock()
263 return c.doRequest(ctx, method, path, jsonBody)
264 }
265
266 return resp, nil
267}
268
269// doRequest builds and executes a single HTTP request to the admin API.
270func (c *Client) doRequest(ctx context.Context, method, path string, jsonBody []byte) (*http.Response, error) {
271 reqURL := c.baseURL + "/admin" + path
272
273 var bodyReader io.Reader
274 if jsonBody != nil {
275 bodyReader = bytes.NewReader(jsonBody)
276 }
277
278 req, err := http.NewRequestWithContext(ctx, method, reqURL, bodyReader)
279 if err != nil {
280 return nil, fmt.Errorf("failed to create request: %w", err)
281 }
282
283 req.Header.Set("Content-Type", "application/json")
284 req.Header.Set("Accept", "application/json")
285
286 bearer, err := c.bearerToken(ctx)
287 if err != nil {
288 return nil, err
289 }
290 if bearer != "" {
291 req.Header.Set("Authorization", "Bearer "+bearer)
292 }
293
294 resp, err := c.httpClient.Do(req)
295 if err != nil {
296 return nil, err
297 }
298
299 return resp, nil
300}
301
302// parseResponse parses a JSON response into the given target.
303func parseResponse(resp *http.Response, target any) error {
304 defer resp.Body.Close()
305
306 if resp.StatusCode >= 400 {
307 body, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBodySize))
308 return parseErrorResponse(resp, body)
309 }
310
311 if target != nil {
312 if err := json.NewDecoder(resp.Body).Decode(target); err != nil {
313 return fmt.Errorf("failed to decode response: %w", err)
314 }
315 }
316
317 return nil
318}
319
320// HTTPError represents an HTTP error response with a status code.
321// Use errors.As to check for specific status codes in error handling.
322type HTTPError struct {
323 StatusCode int
324 Status string
325 Body string
326 Cause string
327 Hint string
328 Logs []string
329 Structured bool
330}
331
332func (e *HTTPError) Error() string {
333 return e.Status + ": " + e.Body
334}
335
336func parseErrorResponse(resp *http.Response, body []byte) error {
337 msg := string(body)
338 structured := false
339 var errResp struct {
340 Error string `json:"error"`
341 Cause string `json:"cause"`
342 Hint string `json:"hint"`
343 Logs []string `json:"logs"`
344 }
345 if err := json.Unmarshal(body, &errResp); err == nil {
346 structured = errResp.Cause != "" || errResp.Hint != "" || len(errResp.Logs) > 0
347 if errResp.Error != "" {
348 msg = errResp.Error
349 }
350 }
351 return &HTTPError{
352 StatusCode: resp.StatusCode,
353 Status: resp.Status,
354 Body: msg,
355 Cause: errResp.Cause,
356 Hint: errResp.Hint,
357 Logs: errResp.Logs,
358 Structured: structured,
359 }
360}
361
362func isRetryableRequestError(err error) bool {
363 return !errors.Is(err, context.Canceled) && !errors.Is(err, context.DeadlineExceeded)
364}
365
366func isRetryableStatus(status int) bool {
367 // Only retry gateway errors; retrying 500 on non-idempotent POSTs
368 // (deploy, restart, reload) can cause duplicate state changes.
369 return status == 502 || status == 503 || status == 504
370}
371
372func retryDelay(attempt int) time.Duration {
373 if attempt <= 1 {
374 return retryBaseDelay
375 }
376 return retryBaseDelay * time.Duration(1<<(attempt-1))
377}
378
379// requestWithRetry performs an HTTP request and retries transient failures.
380// Retries occur on transport errors and gateway errors (502, 503, 504).
381func (c *Client) requestWithRetry(ctx context.Context, method, path string, body any) (*http.Response, error) {
382 var lastErr error
383
384 for attempt := 1; attempt <= retryMaxAttempts; attempt++ {
385 resp, err := c.request(ctx, method, path, body)
386 if err != nil {
387 lastErr = err
388 if attempt == retryMaxAttempts || !isRetryableRequestError(err) {
389 return nil, err
390 }
391 } else {
392 if !isRetryableStatus(resp.StatusCode) {
393 return resp, nil
394 }
395
396 respBody, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBodySize))
397 _ = resp.Body.Close()
398 lastErr = parseErrorResponse(resp, respBody)
399 if attempt == retryMaxAttempts {
400 return nil, lastErr
401 }
402 }
403
404 delay := retryDelay(attempt)
405 timer := time.NewTimer(delay)
406 select {
407 case <-ctx.Done():
408 timer.Stop()
409 return nil, ctx.Err()
410 case <-timer.C:
411 }
412 }
413
414 if lastErr != nil {
415 return nil, lastErr
416 }
417 return nil, fmt.Errorf("request failed after retries")
418}
419
420// Routes API
421
422// Type aliases for API types using shared DTO package.
423type RouteInfo = dto.RouteInfo
424type Attachment = dto.Attachment
425
426// ListRoutes returns all configured routes.
427func (c *Client) ListRoutes(ctx context.Context) ([]domain.Route, error) {
428 resp, err := c.request(ctx, http.MethodGet, "/routes", nil)
429 if err != nil {
430 return nil, err
431 }
432
433 var result struct {
434 Routes []domain.Route `json:"routes"`
435 }
436 if err := parseResponse(resp, &result); err != nil {
437 return nil, err
438 }
439
440 return result.Routes, nil
441}
442
443// ListRoutesWithDetails returns routes with network and attachment info.
444func (c *Client) ListRoutesWithDetails(ctx context.Context) ([]RouteInfo, error) {
445 resp, err := c.request(ctx, http.MethodGet, "/routes?detailed=true", nil)
446 if err != nil {
447 return nil, err
448 }
449
450 var result struct {
451 Routes []RouteInfo `json:"routes"`
452 }
453 if err := parseResponse(resp, &result); err != nil {
454 return nil, err
455 }
456
457 return result.Routes, nil
458}
459
460// ListNetworks returns Gordon-managed networks.
461func (c *Client) ListNetworks(ctx context.Context) ([]*domain.NetworkInfo, error) {
462 resp, err := c.request(ctx, http.MethodGet, "/networks", nil)
463 if err != nil {
464 return nil, err
465 }
466
467 var result struct {
468 Networks []*domain.NetworkInfo `json:"networks"`
469 }
470 if err := parseResponse(resp, &result); err != nil {
471 return nil, err
472 }
473
474 return result.Networks, nil
475}
476
477// ListAttachments returns attachments for a domain.
478func (c *Client) ListAttachments(ctx context.Context, routeDomain string) ([]Attachment, error) {
479 if routeDomain == "" {
480 return nil, fmt.Errorf("domain is required")
481 }
482 path := "/routes/" + url.PathEscape(routeDomain) + "/attachments"
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 Attachments []Attachment `json:"attachments"`
490 }
491 if err := parseResponse(resp, &result); err != nil {
492 return nil, err
493 }
494
495 return result.Attachments, nil
496}
497
498// GetRoute returns a specific route by domain.
499func (c *Client) GetRoute(ctx context.Context, routeDomain string) (*domain.Route, error) {
500 resp, err := c.request(ctx, http.MethodGet, "/routes/"+url.PathEscape(routeDomain), nil)
501 if err != nil {
502 return nil, err
503 }
504
505 var route domain.Route
506 if err := parseResponse(resp, &route); err != nil {
507 return nil, err
508 }
509
510 return &route, nil
511}
512
513// FindRoutesByImage returns all routes associated with the given image name.
514func (c *Client) FindRoutesByImage(ctx context.Context, imageName string) ([]domain.Route, error) {
515 resp, err := c.request(ctx, http.MethodGet, "/routes/by-image/"+url.PathEscape(imageName), nil)
516 if err != nil {
517 return nil, err
518 }
519
520 var result struct {
521 Image string `json:"image"`
522 Routes []domain.Route `json:"routes"`
523 }
524 if err := parseResponse(resp, &result); err != nil {
525 return nil, err
526 }
527
528 return result.Routes, nil
529}
530
531// AddRoute adds a new route.
532func (c *Client) AddRoute(ctx context.Context, route domain.Route) error {
533 resp, err := c.request(ctx, http.MethodPost, "/routes", route)
534 if err != nil {
535 return err
536 }
537 return parseResponse(resp, nil)
538}
539
540// UpdateRoute updates an existing route.
541func (c *Client) UpdateRoute(ctx context.Context, route domain.Route) error {
542 resp, err := c.request(ctx, http.MethodPut, "/routes/"+url.PathEscape(route.Domain), route)
543 if err != nil {
544 return err
545 }
546 return parseResponse(resp, nil)
547}
548
549// RemoveRoute removes a route by domain.
550func (c *Client) RemoveRoute(ctx context.Context, routeDomain string) error {
551 resp, err := c.request(ctx, http.MethodDelete, "/routes/"+url.PathEscape(routeDomain), nil)
552 if err != nil {
553 return err
554 }
555 return parseResponse(resp, nil)
556}
557
558func (c *Client) Bootstrap(ctx context.Context, req dto.BootstrapRequest) (*dto.BootstrapResponse, error) {
559 resp, err := c.request(ctx, http.MethodPost, "/bootstrap", req)
560 if err != nil {
561 return nil, err
562 }
563 var result dto.BootstrapResponse
564 if err := parseResponse(resp, &result); err != nil {
565 return nil, err
566 }
567 return &result, nil
568}
569
570// Secrets API
571
572// AttachmentSecrets represents secrets for an attachment container.
573type AttachmentSecrets struct {
574 Service string `json:"service"`
575 Keys []string `json:"keys"`
576}
577
578// SecretsListResult contains domain secrets and any attachment secrets.
579type SecretsListResult struct {
580 Domain string `json:"domain"`
581 Keys []string `json:"keys"`
582 Attachments []AttachmentSecrets `json:"attachments,omitempty"`
583}
584
585// ListSecrets returns the list of secret keys for a domain.
586func (c *Client) ListSecrets(ctx context.Context, secretDomain string) ([]string, error) {
587 result, err := c.ListSecretsWithAttachments(ctx, secretDomain)
588 if err != nil {
589 return nil, err
590 }
591 return result.Keys, nil
592}
593
594// ListSecretsWithAttachments returns domain secrets and attachment secrets.
595func (c *Client) ListSecretsWithAttachments(ctx context.Context, secretDomain string) (*SecretsListResult, error) {
596 resp, err := c.request(ctx, http.MethodGet, "/secrets/"+url.PathEscape(secretDomain), nil)
597 if err != nil {
598 return nil, err
599 }
600
601 var result SecretsListResult
602 if err := parseResponse(resp, &result); err != nil {
603 return nil, err
604 }
605
606 return &result, nil
607}
608
609// SetSecrets sets secrets for a domain.
610func (c *Client) SetSecrets(ctx context.Context, secretDomain string, secrets map[string]string) error {
611 resp, err := c.request(ctx, http.MethodPost, "/secrets/"+url.PathEscape(secretDomain), secrets)
612 if err != nil {
613 return err
614 }
615 return parseResponse(resp, nil)
616}
617
618// DeleteSecret removes a secret from a domain.
619func (c *Client) DeleteSecret(ctx context.Context, secretDomain, key string) error {
620 resp, err := c.request(ctx, http.MethodDelete, "/secrets/"+url.PathEscape(secretDomain)+"/"+url.PathEscape(key), nil)
621 if err != nil {
622 return err
623 }
624 return parseResponse(resp, nil)
625}
626
627// SetAttachmentSecrets sets secrets for an attachment container.
628func (c *Client) SetAttachmentSecrets(ctx context.Context, domain, service string, secrets map[string]string) error {
629 path := "/secrets/" + url.PathEscape(domain) + "/attachments/" + url.PathEscape(service)
630 resp, err := c.request(ctx, http.MethodPost, path, secrets)
631 if err != nil {
632 return err
633 }
634 return parseResponse(resp, nil)
635}
636
637// DeleteAttachmentSecret removes a secret from an attachment container.
638func (c *Client) DeleteAttachmentSecret(ctx context.Context, domain, service, key string) error {
639 path := "/secrets/" + url.PathEscape(domain) + "/attachments/" + url.PathEscape(service) + "/" + url.PathEscape(key)
640 resp, err := c.request(ctx, http.MethodDelete, path, nil)
641 if err != nil {
642 return err
643 }
644 return parseResponse(resp, nil)
645}
646
647// Status API
648
649// Status represents the Gordon server status.
650type Status struct {
651 Routes int `json:"routes"`
652 RegistryDomain string `json:"registry_domain"`
653 RegistryPort int `json:"registry_port"`
654 ServerPort int `json:"server_port"`
655 AutoRoute bool `json:"auto_route"`
656 NetworkIsolation bool `json:"network_isolation"`
657 ContainerStatus map[string]string `json:"container_status"`
658}
659
660// GetStatus returns the Gordon server status.
661func (c *Client) GetStatus(ctx context.Context) (*Status, error) {
662 resp, err := c.request(ctx, http.MethodGet, "/status", nil)
663 if err != nil {
664 return nil, err
665 }
666
667 var status Status
668 if err := parseResponse(resp, &status); err != nil {
669 return nil, err
670 }
671
672 return &status, nil
673}
674
675// RouteHealth represents the health status of a route.
676type RouteHealth struct {
677 ContainerStatus string `json:"container_status"`
678 HTTPStatus int `json:"http_status"`
679 ResponseTimeMs int64 `json:"response_time_ms"`
680 Healthy bool `json:"healthy"`
681 Error string `json:"error"`
682}
683
684// Backups API
685
686// Images API
687
688// ListImages returns runtime images and registry tags from the admin API.
689func (c *Client) ListImages(ctx context.Context) ([]dto.Image, error) {
690 resp, err := c.request(ctx, http.MethodGet, "/images", nil)
691 if err != nil {
692 return nil, err
693 }
694
695 var result dto.ImagesResponse
696 if err := parseResponse(resp, &result); err != nil {
697 return nil, err
698 }
699
700 return result.Images, nil
701}
702
703// PruneImages prunes runtime and registry images.
704func (c *Client) PruneImages(ctx context.Context, req dto.ImagePruneRequest) (*dto.ImagePruneResponse, error) {
705 if req.KeepLast != nil && *req.KeepLast < 0 {
706 return nil, fmt.Errorf("keep_last must be >= 0")
707 }
708
709 resp, err := c.request(ctx, http.MethodPost, "/images/prune", req)
710 if err != nil {
711 return nil, err
712 }
713
714 var result dto.ImagePruneResponse
715 if err := parseResponse(resp, &result); err != nil {
716 return nil, err
717 }
718
719 return &result, nil
720}
721
722// ListBackups returns backups globally or for a domain.
723func (c *Client) ListBackups(ctx context.Context, backupDomain string) ([]dto.BackupJob, error) {
724 path := "/backups"
725 if backupDomain != "" {
726 path += "/" + url.PathEscape(backupDomain)
727 }
728
729 resp, err := c.request(ctx, http.MethodGet, path, nil)
730 if err != nil {
731 return nil, err
732 }
733
734 var result dto.BackupsResponse
735 if err := parseResponse(resp, &result); err != nil {
736 return nil, err
737 }
738
739 return result.Backups, nil
740}
741
742// BackupStatus returns aggregate backup status.
743func (c *Client) BackupStatus(ctx context.Context) ([]dto.BackupJob, error) {
744 resp, err := c.request(ctx, http.MethodGet, "/backups/status", nil)
745 if err != nil {
746 return nil, err
747 }
748
749 var result dto.BackupsResponse
750 if err := parseResponse(resp, &result); err != nil {
751 return nil, err
752 }
753
754 return result.Backups, nil
755}
756
757// RunBackup triggers a backup for a domain.
758func (c *Client) RunBackup(ctx context.Context, backupDomain, dbName string) (*dto.BackupRunResponse, error) {
759 if backupDomain == "" {
760 return nil, fmt.Errorf("domain cannot be empty")
761 }
762
763 resp, err := c.request(ctx, http.MethodPost, "/backups/"+url.PathEscape(backupDomain), dto.BackupRunRequest{DB: dbName})
764 if err != nil {
765 return nil, err
766 }
767
768 var result dto.BackupRunResponse
769 if err := parseResponse(resp, &result); err != nil {
770 return nil, err
771 }
772
773 return &result, nil
774}
775
776// DetectDatabases detects supported databases for a domain.
777func (c *Client) DetectDatabases(ctx context.Context, backupDomain string) ([]dto.DatabaseInfo, error) {
778 if backupDomain == "" {
779 return nil, fmt.Errorf("domain cannot be empty")
780 }
781
782 resp, err := c.request(ctx, http.MethodGet, "/backups/"+url.PathEscape(backupDomain)+"/detect", nil)
783 if err != nil {
784 return nil, err
785 }
786
787 var result dto.BackupDetectResponse
788 if err := parseResponse(resp, &result); err != nil {
789 return nil, err
790 }
791
792 return result.Databases, nil
793}
794
795// GetHealth returns health status for all routes with HTTP probing.
796func (c *Client) GetHealth(ctx context.Context) (map[string]*RouteHealth, error) {
797 resp, err := c.request(ctx, http.MethodGet, "/health", nil)
798 if err != nil {
799 return nil, err
800 }
801
802 var result struct {
803 Health map[string]*RouteHealth `json:"health"`
804 }
805 if err := parseResponse(resp, &result); err != nil {
806 return nil, err
807 }
808
809 return result.Health, nil
810}
811
812// Reload triggers a configuration reload.
813func (c *Client) Reload(ctx context.Context) error {
814 resp, err := c.requestWithRetry(ctx, http.MethodPost, "/reload", nil)
815 if err != nil {
816 return err
817 }
818 return parseResponse(resp, nil)
819}
820
821// Config API
822
823// Config represents the Gordon configuration.
824type Config struct {
825 Server struct {
826 Port int `json:"port"`
827 RegistryPort int `json:"registry_port"`
828 RegistryDomain string `json:"registry_domain"`
829 DataDir string `json:"data_dir,omitempty"`
830 } `json:"server"`
831 AutoRoute struct {
832 Enabled bool `json:"enabled"`
833 } `json:"auto_route"`
834 NetworkIsolation struct {
835 Enabled bool `json:"enabled"`
836 Prefix string `json:"prefix"`
837 } `json:"network_isolation"`
838 Routes []domain.Route `json:"routes"`
839 ExternalRoutes []ExternalRoute `json:"external_routes"`
840}
841
842// ExternalRoute represents a redacted external route config entry.
843type ExternalRoute struct {
844 Domain string `json:"domain"`
845 Target string `json:"target,omitempty"`
846}
847
848// GetConfig returns the Gordon configuration.
849func (c *Client) GetConfig(ctx context.Context) (*Config, error) {
850 resp, err := c.request(ctx, http.MethodGet, "/config", nil)
851 if err != nil {
852 return nil, err
853 }
854
855 var config Config
856 if err := parseResponse(resp, &config); err != nil {
857 return nil, err
858 }
859
860 return &config, nil
861}
862
863// Ping checks if the remote Gordon instance is reachable.
864func (c *Client) Ping(ctx context.Context) error {
865 _, err := c.GetStatus(ctx)
866 return err
867}
868
869// Deploy API
870
871// DeployResult contains the result of a deployment.
872type DeployResult struct {
873 Status string `json:"status"`
874 ContainerID string `json:"container_id"`
875 Domain string `json:"domain"`
876}
877
878// Deploy triggers a deployment for the specified domain.
879func (c *Client) Deploy(ctx context.Context, deployDomain string) (*DeployResult, error) {
880 resp, err := c.requestWithRetry(ctx, http.MethodPost, "/deploy/"+url.PathEscape(deployDomain), nil)
881 if err != nil {
882 return nil, err
883 }
884
885 var result DeployResult
886 if err := parseResponse(resp, &result); err != nil {
887 return nil, err
888 }
889
890 return &result, nil
891}
892
893// DeployIntent tells the server that a CLI-managed push is about to happen,
894// suppressing event-based deploys for this image.
895func (c *Client) DeployIntent(ctx context.Context, imageName string) error {
896 imageName = strings.TrimSpace(imageName)
897 if imageName == "" {
898 return fmt.Errorf("image name cannot be empty")
899 }
900 resp, err := c.requestWithRetry(ctx, http.MethodPost, "/deploy-intent/"+url.PathEscape(imageName), nil)
901 if err != nil {
902 return err
903 }
904 return parseResponse(resp, nil)
905}
906
907// Restart API
908
909// RestartResult contains the result of a restart.
910type RestartResult struct {
911 Status string `json:"status"`
912 Domain string `json:"domain"`
913}
914
915// Restart triggers a container restart for the specified domain.
916func (c *Client) Restart(ctx context.Context, restartDomain string, withAttachments bool) (*RestartResult, error) {
917 if restartDomain == "" {
918 return nil, fmt.Errorf("domain cannot be empty")
919 }
920 path := "/restart/" + url.PathEscape(restartDomain)
921 if withAttachments {
922 path += "?attachments=true"
923 }
924 resp, err := c.requestWithRetry(ctx, http.MethodPost, path, nil)
925 if err != nil {
926 return nil, err
927 }
928
929 var result RestartResult
930 if err := parseResponse(resp, &result); err != nil {
931 return nil, err
932 }
933
934 return &result, nil
935}
936
937// Tags API
938
939// ListTags returns available tags for a repository.
940func (c *Client) ListTags(ctx context.Context, repository string) ([]string, error) {
941 if repository == "" {
942 return nil, fmt.Errorf("repository cannot be empty")
943 }
944 resp, err := c.request(ctx, http.MethodGet, "/tags/"+url.PathEscape(repository), nil)
945 if err != nil {
946 return nil, err
947 }
948 var result struct {
949 Repository string `json:"repository"`
950 Tags []string `json:"tags"`
951 }
952 if err := parseResponse(resp, &result); err != nil {
953 return nil, err
954 }
955 return result.Tags, nil
956}
957
958// Logs API
959
960// GetProcessLogs returns Gordon process logs.
961func (c *Client) GetProcessLogs(ctx context.Context, lines int) ([]string, error) {
962 path := fmt.Sprintf("/logs?lines=%d", lines)
963 resp, err := c.request(ctx, http.MethodGet, path, nil)
964 if err != nil {
965 return nil, err
966 }
967
968 var result struct {
969 Lines []string `json:"lines"`
970 }
971 if err := parseResponse(resp, &result); err != nil {
972 return nil, err
973 }
974
975 return result.Lines, nil
976}
977
978// GetContainerLogs returns container logs for a specific domain.
979func (c *Client) GetContainerLogs(ctx context.Context, logDomain string, lines int) ([]string, error) {
980 path := fmt.Sprintf("/logs/%s?lines=%d", url.PathEscape(logDomain), lines)
981 resp, err := c.request(ctx, http.MethodGet, path, nil)
982 if err != nil {
983 return nil, err
984 }
985
986 var result struct {
987 Domain string `json:"domain"`
988 Lines []string `json:"lines"`
989 }
990 if err := parseResponse(resp, &result); err != nil {
991 return nil, err
992 }
993
994 return result.Lines, nil
995}
996
997// StreamProcessLogs returns a channel that streams Gordon process log lines via SSE.
998// The caller is responsible for reading from the channel until it's closed.
999func (c *Client) StreamProcessLogs(ctx context.Context, lines int) (<-chan string, error) {
1000 path := fmt.Sprintf("/logs?lines=%d&follow=true", lines)
1001 return c.streamLogs(ctx, path)
1002}
1003
1004// StreamContainerLogs returns a channel that streams container log lines via SSE.
1005// The caller is responsible for reading from the channel until it's closed.
1006func (c *Client) StreamContainerLogs(ctx context.Context, logDomain string, lines int) (<-chan string, error) {
1007 path := fmt.Sprintf("/logs/%s?lines=%d&follow=true", url.PathEscape(logDomain), lines)
1008 return c.streamLogs(ctx, path)
1009}
1010
1011// Attachments Config API
1012
1013// GetAllAttachmentsConfig returns all configured attachments.
1014func (c *Client) GetAllAttachmentsConfig(ctx context.Context) (map[string][]string, error) {
1015 resp, err := c.request(ctx, http.MethodGet, "/attachments", nil)
1016 if err != nil {
1017 return nil, err
1018 }
1019
1020 var result struct {
1021 Attachments map[string][]string `json:"attachments"`
1022 }
1023 if err := parseResponse(resp, &result); err != nil {
1024 return nil, err
1025 }
1026
1027 return result.Attachments, nil
1028}
1029
1030// GetAttachmentsConfig returns attachments for a specific domain/group from config.
1031func (c *Client) GetAttachmentsConfig(ctx context.Context, domainOrGroup string) ([]string, error) {
1032 if domainOrGroup == "" {
1033 return nil, fmt.Errorf("domain or group is required")
1034 }
1035 path := "/attachments/" + url.PathEscape(domainOrGroup)
1036 resp, err := c.request(ctx, http.MethodGet, path, nil)
1037 if err != nil {
1038 return nil, err
1039 }
1040
1041 var result struct {
1042 Target string `json:"target"`
1043 Images []string `json:"images"`
1044 }
1045 if err := parseResponse(resp, &result); err != nil {
1046 return nil, err
1047 }
1048
1049 return result.Images, nil
1050}
1051
1052// FindAttachmentTargetsByImage returns all attachment targets associated with the given image name.
1053func (c *Client) FindAttachmentTargetsByImage(ctx context.Context, imageName string) ([]string, error) {
1054 resp, err := c.request(ctx, http.MethodGet, "/attachments/by-image/"+url.PathEscape(imageName), nil)
1055 if err != nil {
1056 return nil, err
1057 }
1058
1059 var result dto.AttachmentTargetsByImageResponse
1060 if err := parseResponse(resp, &result); err != nil {
1061 return nil, err
1062 }
1063
1064 return result.Targets, nil
1065}
1066
1067// AddAttachment adds an attachment to a domain/group.
1068func (c *Client) AddAttachment(ctx context.Context, domainOrGroup, image string) error {
1069 if domainOrGroup == "" {
1070 return fmt.Errorf("domain or group is required")
1071 }
1072 if image == "" {
1073 return fmt.Errorf("image is required")
1074 }
1075 path := "/attachments/" + url.PathEscape(domainOrGroup)
1076 resp, err := c.request(ctx, http.MethodPost, path, struct {
1077 Image string `json:"image"`
1078 }{Image: image})
1079 if err != nil {
1080 return err
1081 }
1082 return parseResponse(resp, nil)
1083}
1084
1085// RemoveAttachment removes an attachment from a domain/group.
1086func (c *Client) RemoveAttachment(ctx context.Context, domainOrGroup, image string) error {
1087 if domainOrGroup == "" {
1088 return fmt.Errorf("domain or group is required")
1089 }
1090 if image == "" {
1091 return fmt.Errorf("image is required")
1092 }
1093 path := "/attachments/" + url.PathEscape(domainOrGroup) + "/" + url.PathEscape(image)
1094 resp, err := c.request(ctx, http.MethodDelete, path, nil)
1095 if err != nil {
1096 return err
1097 }
1098 return parseResponse(resp, nil)
1099}
1100
1101func (c *Client) GetAutoRouteAllowedDomains(ctx context.Context) ([]string, error) {
1102 resp, err := c.request(ctx, http.MethodGet, "/autoroute/allowed-domains", nil)
1103 if err != nil {
1104 return nil, err
1105 }
1106
1107 var result dto.AutoRouteAllowedDomainsResponse
1108 if err := parseResponse(resp, &result); err != nil {
1109 return nil, err
1110 }
1111
1112 return result.Domains, nil
1113}
1114
1115func (c *Client) AddAutoRouteAllowedDomain(ctx context.Context, pattern string) error {
1116 if strings.TrimSpace(pattern) == "" {
1117 return fmt.Errorf("pattern must not be empty")
1118 }
1119 resp, err := c.request(ctx, http.MethodPost, "/autoroute/allowed-domains", dto.AutoRouteAllowedDomainRequest{Pattern: pattern})
1120 if err != nil {
1121 return err
1122 }
1123 return parseResponse(resp, nil)
1124}
1125
1126func (c *Client) RemoveAutoRouteAllowedDomain(ctx context.Context, pattern string) error {
1127 if strings.TrimSpace(pattern) == "" {
1128 return fmt.Errorf("pattern must not be empty")
1129 }
1130 resp, err := c.request(ctx, http.MethodDelete, "/autoroute/allowed-domains/"+url.PathEscape(pattern), nil)
1131 if err != nil {
1132 return err
1133 }
1134 return parseResponse(resp, nil)
1135}
1136
1137// openSSEStream opens an SSE connection to the given admin path and returns the response.
1138func (c *Client) openSSEStream(ctx context.Context, path string) (*http.Response, error) {
1139 streamURL := c.baseURL + "/admin" + path
1140
1141 req, err := http.NewRequestWithContext(ctx, http.MethodGet, streamURL, nil)
1142 if err != nil {
1143 return nil, fmt.Errorf("failed to create request: %w", err)
1144 }
1145
1146 req.Header.Set("Accept", "text/event-stream")
1147 bearer, err := c.bearerToken(ctx)
1148 if err != nil {
1149 return nil, err
1150 }
1151 if bearer != "" {
1152 req.Header.Set("Authorization", "Bearer "+bearer)
1153 }
1154
1155 // Use the same transport as the main client (honoring TLS config and
1156 // custom transports) but without a timeout so streaming doesn't get cut off.
1157 streamClient := &http.Client{
1158 Transport: c.httpClient.Transport,
1159 }
1160 resp, err := streamClient.Do(req)
1161 if err != nil {
1162 return nil, fmt.Errorf("failed to connect: %w", err)
1163 }
1164
1165 if resp.StatusCode >= 400 {
1166 body, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBodySize))
1167 resp.Body.Close()
1168 return nil, fmt.Errorf("%s: %s", resp.Status, string(body))
1169 }
1170
1171 return resp, nil
1172}
1173
1174// streamLogs handles SSE streaming for log endpoints.
1175func (c *Client) streamLogs(ctx context.Context, path string) (<-chan string, error) {
1176 resp, err := c.openSSEStream(ctx, path)
1177 if err != nil {
1178 return nil, err
1179 }
1180
1181 ch := make(chan string, 100)
1182
1183 go func() {
1184 defer close(ch)
1185 defer resp.Body.Close()
1186
1187 buf := make([]byte, 4096)
1188 var lineBuffer strings.Builder
1189
1190 for {
1191 select {
1192 case <-ctx.Done():
1193 return
1194 default:
1195 }
1196
1197 n, err := resp.Body.Read(buf)
1198 if n > 0 {
1199 lineBuffer.Write(buf[:n])
1200 }
1201 if err != nil {
1202 return // EOF or context cancellation — clean exit
1203 }
1204
1205 // Process complete SSE events
1206 for {
1207 data := lineBuffer.String()
1208 idx := strings.Index(data, "\n\n")
1209 if idx == -1 {
1210 break
1211 }
1212
1213 event := data[:idx]
1214 lineBuffer.Reset()
1215 lineBuffer.WriteString(data[idx+2:])
1216
1217 // Parse SSE data lines
1218 for _, line := range strings.Split(event, "\n") {
1219 if strings.HasPrefix(line, "data: ") {
1220 logLine := strings.TrimPrefix(line, "data: ")
1221 select {
1222 case ch <- logLine:
1223 case <-ctx.Done():
1224 return
1225 }
1226 }
1227 }
1228 }
1229 }
1230 }()
1231
1232 return ch, nil
1233}
1234
1235// VerifyAuth checks if authentication session is valid.
1236func (c *Client) VerifyAuth(ctx context.Context) (*dto.AuthVerifyResponse, error) {
1237 resp, err := c.request(ctx, http.MethodGet, "/auth/verify", nil)
1238 if err != nil {
1239 return nil, err
1240 }
1241
1242 var result dto.AuthVerifyResponse
1243 if err := parseResponse(resp, &result); err != nil {
1244 return nil, err
1245 }
1246
1247 return &result, nil
1248}
1249
1250// ListVolumes lists all volumes via the admin API.
1251func (c *Client) ListVolumes(ctx context.Context) ([]dto.Volume, error) {
1252 resp, err := c.request(ctx, http.MethodGet, "/volumes", nil)
1253 if err != nil {
1254 return nil, err
1255 }
1256
1257 var volumes []dto.Volume
1258 if err := parseResponse(resp, &volumes); err != nil {
1259 return nil, err
1260 }
1261
1262 return volumes, nil
1263}
1264
1265// PruneVolumes prunes orphaned volumes via the admin API.
1266func (c *Client) PruneVolumes(ctx context.Context, req dto.VolumePruneRequest) (*dto.VolumePruneResponse, error) {
1267 resp, err := c.request(ctx, http.MethodPost, "/volumes/prune", req)
1268 if err != nil {
1269 return nil, err
1270 }
1271
1272 var result dto.VolumePruneResponse
1273 if err := parseResponse(resp, &result); err != nil {
1274 return nil, err
1275 }
1276
1277 return &result, nil
1278}