v2.31.0-dev19 35467d7

client.go RawHistoryFolder

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		var httpErr *HTTPError
508		if errors.As(err, &httpErr) && httpErr.StatusCode == http.StatusNotFound {
509			return nil, domain.ErrRouteNotFound
510		}
511		return nil, err
512	}
513
514	return &route, nil
515}
516
517// FindRoutesByImage returns all routes associated with the given image name.
518func (c *Client) FindRoutesByImage(ctx context.Context, imageName string) ([]domain.Route, error) {
519	resp, err := c.request(ctx, http.MethodGet, "/routes/by-image/"+url.PathEscape(imageName), nil)
520	if err != nil {
521		return nil, err
522	}
523
524	var result struct {
525		Image  string         `json:"image"`
526		Routes []domain.Route `json:"routes"`
527	}
528	if err := parseResponse(resp, &result); err != nil {
529		return nil, err
530	}
531
532	return result.Routes, nil
533}
534
535// AddRoute adds a new route.
536func (c *Client) AddRoute(ctx context.Context, route domain.Route) error {
537	resp, err := c.request(ctx, http.MethodPost, "/routes", route)
538	if err != nil {
539		return err
540	}
541	return parseResponse(resp, nil)
542}
543
544// UpdateRoute updates an existing route.
545func (c *Client) UpdateRoute(ctx context.Context, route domain.Route) error {
546	resp, err := c.request(ctx, http.MethodPut, "/routes/"+url.PathEscape(route.Domain), route)
547	if err != nil {
548		return err
549	}
550	return parseResponse(resp, nil)
551}
552
553// RemoveRoute removes a route by domain.
554func (c *Client) RemoveRoute(ctx context.Context, routeDomain string) error {
555	_, err := c.RemoveRouteWithCleanup(ctx, routeDomain)
556	return err
557}
558
559// RemoveRouteWithCleanup removes a route and returns the server cleanup report.
560func (c *Client) RemoveRouteWithCleanup(ctx context.Context, routeDomain string) (*dto.RouteDeleteResponse, error) {
561	resp, err := c.request(ctx, http.MethodDelete, "/routes/"+url.PathEscape(routeDomain), nil)
562	if err != nil {
563		return nil, fmt.Errorf("delete route %s failed: %w", routeDomain, err)
564	}
565	var result dto.RouteDeleteResponse
566	if err := parseResponse(resp, &result); err != nil {
567		return nil, fmt.Errorf("parse delete route %s response: %w", routeDomain, err)
568	}
569	return &result, nil
570}
571
572func (c *Client) Bootstrap(ctx context.Context, req dto.BootstrapRequest) (*dto.BootstrapResponse, error) {
573	resp, err := c.request(ctx, http.MethodPost, "/bootstrap", req)
574	if err != nil {
575		return nil, err
576	}
577	var result dto.BootstrapResponse
578	if err := parseResponse(resp, &result); err != nil {
579		return nil, err
580	}
581	return &result, nil
582}
583
584// Secrets API
585
586// AttachmentSecrets represents secrets for an attachment container.
587type AttachmentSecrets struct {
588	Service string   `json:"service"`
589	Keys    []string `json:"keys"`
590}
591
592// SecretsListResult contains domain secrets and any attachment secrets.
593type SecretsListResult struct {
594	Domain      string              `json:"domain"`
595	Keys        []string            `json:"keys"`
596	Attachments []AttachmentSecrets `json:"attachments,omitempty"`
597}
598
599// ListSecrets returns the list of secret keys for a domain.
600func (c *Client) ListSecrets(ctx context.Context, secretDomain string) ([]string, error) {
601	result, err := c.ListSecretsWithAttachments(ctx, secretDomain)
602	if err != nil {
603		return nil, err
604	}
605	return result.Keys, nil
606}
607
608// ListSecretsWithAttachments returns domain secrets and attachment secrets.
609func (c *Client) ListSecretsWithAttachments(ctx context.Context, secretDomain string) (*SecretsListResult, error) {
610	resp, err := c.request(ctx, http.MethodGet, "/secrets/"+url.PathEscape(secretDomain), nil)
611	if err != nil {
612		return nil, err
613	}
614
615	var result SecretsListResult
616	if err := parseResponse(resp, &result); err != nil {
617		return nil, err
618	}
619
620	return &result, nil
621}
622
623// SetSecrets sets secrets for a domain.
624func (c *Client) SetSecrets(ctx context.Context, secretDomain string, secrets map[string]string) error {
625	resp, err := c.request(ctx, http.MethodPost, "/secrets/"+url.PathEscape(secretDomain), secrets)
626	if err != nil {
627		return err
628	}
629	return parseResponse(resp, nil)
630}
631
632// DeleteSecret removes a secret from a domain.
633func (c *Client) DeleteSecret(ctx context.Context, secretDomain, key string) error {
634	resp, err := c.request(ctx, http.MethodDelete, "/secrets/"+url.PathEscape(secretDomain)+"/"+url.PathEscape(key), nil)
635	if err != nil {
636		return err
637	}
638	return parseResponse(resp, nil)
639}
640
641// SetAttachmentSecrets sets secrets for an attachment container.
642func (c *Client) SetAttachmentSecrets(ctx context.Context, domain, service string, secrets map[string]string) error {
643	path := "/secrets/" + url.PathEscape(domain) + "/attachments/" + url.PathEscape(service)
644	resp, err := c.request(ctx, http.MethodPost, path, secrets)
645	if err != nil {
646		return err
647	}
648	return parseResponse(resp, nil)
649}
650
651// DeleteAttachmentSecret removes a secret from an attachment container.
652func (c *Client) DeleteAttachmentSecret(ctx context.Context, domain, service, key string) error {
653	path := "/secrets/" + url.PathEscape(domain) + "/attachments/" + url.PathEscape(service) + "/" + url.PathEscape(key)
654	resp, err := c.request(ctx, http.MethodDelete, path, nil)
655	if err != nil {
656		return err
657	}
658	return parseResponse(resp, nil)
659}
660
661// Status API
662
663// Status represents the Gordon server status.
664type Status struct {
665	Routes           int               `json:"routes"`
666	RegistryDomain   string            `json:"registry_domain"`
667	RegistryPort     int               `json:"registry_port"`
668	ServerPort       int               `json:"server_port"`
669	AutoRoute        bool              `json:"auto_route"`
670	NetworkIsolation bool              `json:"network_isolation"`
671	ContainerStatus  map[string]string `json:"container_status"`
672}
673
674// GetTLSStatus returns the public TLS/ACME status.
675func (c *Client) GetTLSStatus(ctx context.Context) (*dto.TLSStatusResponse, error) {
676	resp, err := c.request(ctx, http.MethodGet, "/tls/status", nil)
677	if err != nil {
678		return nil, err
679	}
680
681	var status dto.TLSStatusResponse
682	if err := parseResponse(resp, &status); err != nil {
683		return nil, err
684	}
685
686	return &status, nil
687}
688
689// GetStatus returns the Gordon server status.
690func (c *Client) GetStatus(ctx context.Context) (*Status, error) {
691	resp, err := c.request(ctx, http.MethodGet, "/status", nil)
692	if err != nil {
693		return nil, err
694	}
695
696	var status Status
697	if err := parseResponse(resp, &status); err != nil {
698		return nil, err
699	}
700
701	return &status, nil
702}
703
704// RouteHealth represents the health status of a route.
705type RouteHealth struct {
706	ContainerStatus string `json:"container_status"`
707	HTTPStatus      int    `json:"http_status"`
708	ResponseTimeMs  int64  `json:"response_time_ms"`
709	Healthy         bool   `json:"healthy"`
710	Error           string `json:"error"`
711}
712
713// Backups API
714
715// Images API
716
717// ListImages returns runtime images and registry tags from the admin API.
718func (c *Client) ListImages(ctx context.Context) ([]dto.Image, error) {
719	resp, err := c.request(ctx, http.MethodGet, "/images", nil)
720	if err != nil {
721		return nil, err
722	}
723
724	var result dto.ImagesResponse
725	if err := parseResponse(resp, &result); err != nil {
726		return nil, err
727	}
728
729	return result.Images, nil
730}
731
732// PruneImages prunes runtime and registry images.
733func (c *Client) PruneImages(ctx context.Context, req dto.ImagePruneRequest) (*dto.ImagePruneResponse, error) {
734	if req.KeepLast != nil && *req.KeepLast < 0 {
735		return nil, fmt.Errorf("keep_last must be >= 0")
736	}
737
738	resp, err := c.request(ctx, http.MethodPost, "/images/prune", req)
739	if err != nil {
740		return nil, err
741	}
742
743	var result dto.ImagePruneResponse
744	if err := parseResponse(resp, &result); err != nil {
745		return nil, err
746	}
747
748	return &result, nil
749}
750
751// ListBackups returns backups globally or for a domain.
752func (c *Client) ListBackups(ctx context.Context, backupDomain string) ([]dto.BackupJob, error) {
753	path := "/backups"
754	if backupDomain != "" {
755		path += "/" + url.PathEscape(backupDomain)
756	}
757
758	resp, err := c.request(ctx, http.MethodGet, path, nil)
759	if err != nil {
760		return nil, err
761	}
762
763	var result dto.BackupsResponse
764	if err := parseResponse(resp, &result); err != nil {
765		return nil, err
766	}
767
768	return result.Backups, nil
769}
770
771// BackupStatus returns aggregate backup status.
772func (c *Client) BackupStatus(ctx context.Context) ([]dto.BackupJob, error) {
773	resp, err := c.request(ctx, http.MethodGet, "/backups/status", nil)
774	if err != nil {
775		return nil, err
776	}
777
778	var result dto.BackupsResponse
779	if err := parseResponse(resp, &result); err != nil {
780		return nil, err
781	}
782
783	return result.Backups, nil
784}
785
786// RunBackup triggers a backup for a domain.
787func (c *Client) RunBackup(ctx context.Context, backupDomain, dbName string) (*dto.BackupRunResponse, error) {
788	if backupDomain == "" {
789		return nil, fmt.Errorf("domain cannot be empty")
790	}
791
792	resp, err := c.request(ctx, http.MethodPost, "/backups/"+url.PathEscape(backupDomain), dto.BackupRunRequest{DB: dbName})
793	if err != nil {
794		return nil, err
795	}
796
797	var result dto.BackupRunResponse
798	if err := parseResponse(resp, &result); err != nil {
799		return nil, err
800	}
801
802	return &result, nil
803}
804
805// DetectDatabases detects supported databases for a domain.
806func (c *Client) DetectDatabases(ctx context.Context, backupDomain string) ([]dto.DatabaseInfo, error) {
807	if backupDomain == "" {
808		return nil, fmt.Errorf("domain cannot be empty")
809	}
810
811	resp, err := c.request(ctx, http.MethodGet, "/backups/"+url.PathEscape(backupDomain)+"/detect", nil)
812	if err != nil {
813		return nil, err
814	}
815
816	var result dto.BackupDetectResponse
817	if err := parseResponse(resp, &result); err != nil {
818		return nil, err
819	}
820
821	return result.Databases, nil
822}
823
824// GetHealth returns health status for all routes with HTTP probing.
825func (c *Client) GetHealth(ctx context.Context) (map[string]*RouteHealth, error) {
826	resp, err := c.request(ctx, http.MethodGet, "/health", nil)
827	if err != nil {
828		return nil, err
829	}
830
831	var result struct {
832		Health map[string]*RouteHealth `json:"health"`
833	}
834	if err := parseResponse(resp, &result); err != nil {
835		return nil, err
836	}
837
838	return result.Health, nil
839}
840
841// Reload triggers a configuration reload.
842func (c *Client) Reload(ctx context.Context) error {
843	resp, err := c.requestWithRetry(ctx, http.MethodPost, "/reload", nil)
844	if err != nil {
845		return err
846	}
847	return parseResponse(resp, nil)
848}
849
850// Config API
851
852// Config represents the Gordon configuration.
853type Config struct {
854	Server struct {
855		Port           int    `json:"port"`
856		RegistryPort   int    `json:"registry_port"`
857		RegistryDomain string `json:"registry_domain"`
858		DataDir        string `json:"data_dir,omitempty"`
859	} `json:"server"`
860	AutoRoute struct {
861		Enabled bool `json:"enabled"`
862	} `json:"auto_route"`
863	NetworkIsolation struct {
864		Enabled bool   `json:"enabled"`
865		Prefix  string `json:"prefix"`
866	} `json:"network_isolation"`
867	Volumes struct {
868		AutoCreate bool   `json:"auto_create"`
869		Prefix     string `json:"prefix"`
870		Preserve   bool   `json:"preserve"`
871	} `json:"volumes"`
872	Routes         []domain.Route  `json:"routes"`
873	ExternalRoutes []ExternalRoute `json:"external_routes"`
874}
875
876// ExternalRoute represents a redacted external route config entry.
877type ExternalRoute struct {
878	Domain string `json:"domain"`
879	Target string `json:"target,omitempty"`
880}
881
882// GetConfig returns the Gordon configuration.
883func (c *Client) GetConfig(ctx context.Context) (*Config, error) {
884	resp, err := c.request(ctx, http.MethodGet, "/config", nil)
885	if err != nil {
886		return nil, err
887	}
888
889	var config Config
890	if err := parseResponse(resp, &config); err != nil {
891		return nil, err
892	}
893
894	return &config, nil
895}
896
897// Ping checks if the remote Gordon instance is reachable.
898func (c *Client) Ping(ctx context.Context) error {
899	_, err := c.GetStatus(ctx)
900	return err
901}
902
903// Deploy API
904
905// DeployResult contains the result of a deployment.
906type DeployResult struct {
907	Status      string `json:"status"`
908	ContainerID string `json:"container_id"`
909	Domain      string `json:"domain"`
910}
911
912// Deploy triggers a deployment for the specified domain.
913func (c *Client) Deploy(ctx context.Context, deployDomain string) (*DeployResult, error) {
914	resp, err := c.requestWithRetry(ctx, http.MethodPost, "/deploy/"+url.PathEscape(deployDomain), nil)
915	if err != nil {
916		return nil, err
917	}
918
919	var result DeployResult
920	if err := parseResponse(resp, &result); err != nil {
921		return nil, err
922	}
923
924	return &result, nil
925}
926
927// DeployIntent tells the server that a CLI-managed push is about to happen,
928// suppressing event-based deploys for this image.
929func (c *Client) DeployIntent(ctx context.Context, imageName string) error {
930	imageName = strings.TrimSpace(imageName)
931	if imageName == "" {
932		return fmt.Errorf("image name cannot be empty")
933	}
934	resp, err := c.requestWithRetry(ctx, http.MethodPost, "/deploy-intent/"+url.PathEscape(imageName), nil)
935	if err != nil {
936		return err
937	}
938	return parseResponse(resp, nil)
939}
940
941// Restart API
942
943// RestartResult contains the result of a restart.
944type RestartResult struct {
945	Status string `json:"status"`
946	Domain string `json:"domain"`
947}
948
949// Restart triggers a container restart for the specified domain.
950func (c *Client) Restart(ctx context.Context, restartDomain string, withAttachments bool) (*RestartResult, error) {
951	if restartDomain == "" {
952		return nil, fmt.Errorf("domain cannot be empty")
953	}
954	path := "/restart/" + url.PathEscape(restartDomain)
955	if withAttachments {
956		path += "?attachments=true"
957	}
958	resp, err := c.requestWithRetry(ctx, http.MethodPost, path, nil)
959	if err != nil {
960		return nil, err
961	}
962
963	var result RestartResult
964	if err := parseResponse(resp, &result); err != nil {
965		return nil, err
966	}
967
968	return &result, nil
969}
970
971// Tags API
972
973// ListTags returns available tags for a repository.
974func (c *Client) ListTags(ctx context.Context, repository string) ([]string, error) {
975	if repository == "" {
976		return nil, fmt.Errorf("repository cannot be empty")
977	}
978	resp, err := c.request(ctx, http.MethodGet, "/tags/"+url.PathEscape(repository), nil)
979	if err != nil {
980		return nil, err
981	}
982	var result struct {
983		Repository string   `json:"repository"`
984		Tags       []string `json:"tags"`
985	}
986	if err := parseResponse(resp, &result); err != nil {
987		return nil, err
988	}
989	return result.Tags, nil
990}
991
992// Logs API
993
994// GetProcessLogs returns Gordon process logs.
995func (c *Client) GetProcessLogs(ctx context.Context, lines int) ([]string, error) {
996	path := fmt.Sprintf("/logs?lines=%d", lines)
997	resp, err := c.request(ctx, http.MethodGet, path, nil)
998	if err != nil {
999		return nil, err
1000	}
1001
1002	var result struct {
1003		Lines []string `json:"lines"`
1004	}
1005	if err := parseResponse(resp, &result); err != nil {
1006		return nil, err
1007	}
1008
1009	return result.Lines, nil
1010}
1011
1012// GetContainerLogs returns container logs for a specific domain.
1013func (c *Client) GetContainerLogs(ctx context.Context, logDomain string, lines int) ([]string, error) {
1014	path := fmt.Sprintf("/logs/%s?lines=%d", url.PathEscape(logDomain), lines)
1015	resp, err := c.request(ctx, http.MethodGet, path, nil)
1016	if err != nil {
1017		return nil, err
1018	}
1019
1020	var result struct {
1021		Domain string   `json:"domain"`
1022		Lines  []string `json:"lines"`
1023	}
1024	if err := parseResponse(resp, &result); err != nil {
1025		return nil, err
1026	}
1027
1028	return result.Lines, nil
1029}
1030
1031// StreamProcessLogs returns a channel that streams Gordon process log lines via SSE.
1032// The caller is responsible for reading from the channel until it's closed.
1033func (c *Client) StreamProcessLogs(ctx context.Context, lines int) (<-chan string, error) {
1034	path := fmt.Sprintf("/logs?lines=%d&follow=true", lines)
1035	return c.streamLogs(ctx, path)
1036}
1037
1038// StreamContainerLogs returns a channel that streams container log lines via SSE.
1039// The caller is responsible for reading from the channel until it's closed.
1040func (c *Client) StreamContainerLogs(ctx context.Context, logDomain string, lines int) (<-chan string, error) {
1041	path := fmt.Sprintf("/logs/%s?lines=%d&follow=true", url.PathEscape(logDomain), lines)
1042	return c.streamLogs(ctx, path)
1043}
1044
1045// Attachments Config API
1046
1047// ListOrphanedAttachments returns running attachment containers no longer configured.
1048func (c *Client) ListOrphanedAttachments(ctx context.Context) ([]domain.CleanupAttachment, error) {
1049	resp, err := c.request(ctx, http.MethodGet, "/attachments/orphans", nil)
1050	if err != nil {
1051		return nil, err
1052	}
1053	var result struct {
1054		Attachments []domain.CleanupAttachment `json:"attachments"`
1055	}
1056	if err := parseResponse(resp, &result); err != nil {
1057		return nil, err
1058	}
1059	return result.Attachments, nil
1060}
1061
1062// CleanupOrphanedAttachments optionally stops/removes orphaned attachment containers.
1063func (c *Client) CleanupOrphanedAttachments(ctx context.Context, owner string, stop bool) (*domain.CleanupReport, error) {
1064	path := "/attachments/prune"
1065	params := url.Values{}
1066	if stop {
1067		params.Set("stop", "true")
1068	}
1069	if owner != "" {
1070		params.Set("owner", owner)
1071	}
1072	if encoded := params.Encode(); encoded != "" {
1073		path += "?" + encoded
1074	}
1075	resp, err := c.request(ctx, http.MethodPost, path, nil)
1076	if err != nil {
1077		return nil, fmt.Errorf("cleanup orphaned attachments failed: %w", err)
1078	}
1079	var result domain.CleanupReport
1080	if err := parseResponse(resp, &result); err != nil {
1081		return nil, fmt.Errorf("parse orphaned attachment cleanup response: %w", err)
1082	}
1083	return &result, nil
1084}
1085
1086// GetAllAttachmentsConfig returns all configured attachments.
1087func (c *Client) GetAllAttachmentsConfig(ctx context.Context) (map[string][]string, error) {
1088	resp, err := c.request(ctx, http.MethodGet, "/attachments", nil)
1089	if err != nil {
1090		return nil, err
1091	}
1092
1093	var result struct {
1094		Attachments map[string][]string `json:"attachments"`
1095	}
1096	if err := parseResponse(resp, &result); err != nil {
1097		return nil, err
1098	}
1099
1100	return result.Attachments, nil
1101}
1102
1103// GetAttachmentsConfig returns attachments for a specific domain/group from config.
1104func (c *Client) GetAttachmentsConfig(ctx context.Context, domainOrGroup string) ([]string, error) {
1105	if domainOrGroup == "" {
1106		return nil, fmt.Errorf("domain or group is required")
1107	}
1108	path := "/attachments/" + url.PathEscape(domainOrGroup)
1109	resp, err := c.request(ctx, http.MethodGet, path, nil)
1110	if err != nil {
1111		return nil, err
1112	}
1113
1114	var result struct {
1115		Target string   `json:"target"`
1116		Images []string `json:"images"`
1117	}
1118	if err := parseResponse(resp, &result); err != nil {
1119		return nil, err
1120	}
1121
1122	return result.Images, nil
1123}
1124
1125// FindAttachmentTargetsByImage returns all attachment targets associated with the given image name.
1126func (c *Client) FindAttachmentTargetsByImage(ctx context.Context, imageName string) ([]string, error) {
1127	resp, err := c.request(ctx, http.MethodGet, "/attachments/by-image/"+url.PathEscape(imageName), nil)
1128	if err != nil {
1129		return nil, err
1130	}
1131
1132	var result dto.AttachmentTargetsByImageResponse
1133	if err := parseResponse(resp, &result); err != nil {
1134		return nil, err
1135	}
1136
1137	return result.Targets, nil
1138}
1139
1140// AddAttachment adds an attachment to a domain/group.
1141func (c *Client) AddAttachment(ctx context.Context, domainOrGroup, image string) error {
1142	if domainOrGroup == "" {
1143		return fmt.Errorf("domain or group is required")
1144	}
1145	if image == "" {
1146		return fmt.Errorf("image is required")
1147	}
1148	path := "/attachments/" + url.PathEscape(domainOrGroup)
1149	resp, err := c.request(ctx, http.MethodPost, path, struct {
1150		Image string `json:"image"`
1151	}{Image: image})
1152	if err != nil {
1153		return err
1154	}
1155	return parseResponse(resp, nil)
1156}
1157
1158// RemoveAttachment removes an attachment from a domain/group.
1159func (c *Client) RemoveAttachment(ctx context.Context, domainOrGroup, image string) error {
1160	if domainOrGroup == "" {
1161		return fmt.Errorf("domain or group is required")
1162	}
1163	if image == "" {
1164		return fmt.Errorf("image is required")
1165	}
1166	path := "/attachments/" + url.PathEscape(domainOrGroup) + "/" + url.PathEscape(image)
1167	resp, err := c.request(ctx, http.MethodDelete, path, nil)
1168	if err != nil {
1169		return err
1170	}
1171	return parseResponse(resp, nil)
1172}
1173
1174func (c *Client) GetAutoRouteAllowedDomains(ctx context.Context) ([]string, error) {
1175	resp, err := c.request(ctx, http.MethodGet, "/autoroute/allowed-domains", nil)
1176	if err != nil {
1177		return nil, err
1178	}
1179
1180	var result dto.AutoRouteAllowedDomainsResponse
1181	if err := parseResponse(resp, &result); err != nil {
1182		return nil, err
1183	}
1184
1185	return result.Domains, nil
1186}
1187
1188func (c *Client) AddAutoRouteAllowedDomain(ctx context.Context, pattern string) error {
1189	if strings.TrimSpace(pattern) == "" {
1190		return fmt.Errorf("pattern must not be empty")
1191	}
1192	resp, err := c.request(ctx, http.MethodPost, "/autoroute/allowed-domains", dto.AutoRouteAllowedDomainRequest{Pattern: pattern})
1193	if err != nil {
1194		return err
1195	}
1196	return parseResponse(resp, nil)
1197}
1198
1199func (c *Client) RemoveAutoRouteAllowedDomain(ctx context.Context, pattern string) error {
1200	if strings.TrimSpace(pattern) == "" {
1201		return fmt.Errorf("pattern must not be empty")
1202	}
1203	resp, err := c.request(ctx, http.MethodDelete, "/autoroute/allowed-domains/"+url.PathEscape(pattern), nil)
1204	if err != nil {
1205		return err
1206	}
1207	return parseResponse(resp, nil)
1208}
1209
1210// openSSEStream opens an SSE connection to the given admin path and returns the response.
1211func (c *Client) openSSEStream(ctx context.Context, path string) (*http.Response, error) {
1212	streamURL := c.baseURL + "/admin" + path
1213
1214	req, err := http.NewRequestWithContext(ctx, http.MethodGet, streamURL, nil)
1215	if err != nil {
1216		return nil, fmt.Errorf("failed to create request: %w", err)
1217	}
1218
1219	req.Header.Set("Accept", "text/event-stream")
1220	bearer, err := c.bearerToken(ctx)
1221	if err != nil {
1222		return nil, err
1223	}
1224	if bearer != "" {
1225		req.Header.Set("Authorization", "Bearer "+bearer)
1226	}
1227
1228	// Use the same transport as the main client (honoring TLS config and
1229	// custom transports) but without a timeout so streaming doesn't get cut off.
1230	streamClient := &http.Client{
1231		Transport: c.httpClient.Transport,
1232	}
1233	resp, err := streamClient.Do(req)
1234	if err != nil {
1235		return nil, fmt.Errorf("failed to connect: %w", err)
1236	}
1237
1238	if resp.StatusCode >= 400 {
1239		body, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBodySize))
1240		resp.Body.Close()
1241		return nil, fmt.Errorf("%s: %s", resp.Status, string(body))
1242	}
1243
1244	return resp, nil
1245}
1246
1247// streamLogs handles SSE streaming for log endpoints.
1248func (c *Client) streamLogs(ctx context.Context, path string) (<-chan string, error) {
1249	resp, err := c.openSSEStream(ctx, path)
1250	if err != nil {
1251		return nil, err
1252	}
1253
1254	ch := make(chan string, 100)
1255
1256	go func() {
1257		defer close(ch)
1258		defer resp.Body.Close()
1259
1260		buf := make([]byte, 4096)
1261		var lineBuffer strings.Builder
1262
1263		for {
1264			select {
1265			case <-ctx.Done():
1266				return
1267			default:
1268			}
1269
1270			n, err := resp.Body.Read(buf)
1271			if n > 0 {
1272				lineBuffer.Write(buf[:n])
1273			}
1274			if err != nil {
1275				return // EOF or context cancellation — clean exit
1276			}
1277
1278			// Process complete SSE events
1279			for {
1280				data := lineBuffer.String()
1281				idx := strings.Index(data, "\n\n")
1282				if idx == -1 {
1283					break
1284				}
1285
1286				event := data[:idx]
1287				lineBuffer.Reset()
1288				lineBuffer.WriteString(data[idx+2:])
1289
1290				// Parse SSE data lines
1291				for _, line := range strings.Split(event, "\n") {
1292					if strings.HasPrefix(line, "data: ") {
1293						logLine := strings.TrimPrefix(line, "data: ")
1294						select {
1295						case ch <- logLine:
1296						case <-ctx.Done():
1297							return
1298						}
1299					}
1300				}
1301			}
1302		}
1303	}()
1304
1305	return ch, nil
1306}
1307
1308// VerifyAuth checks if authentication session is valid.
1309func (c *Client) VerifyAuth(ctx context.Context) (*dto.AuthVerifyResponse, error) {
1310	resp, err := c.request(ctx, http.MethodGet, "/auth/verify", nil)
1311	if err != nil {
1312		return nil, err
1313	}
1314
1315	var result dto.AuthVerifyResponse
1316	if err := parseResponse(resp, &result); err != nil {
1317		return nil, err
1318	}
1319
1320	return &result, nil
1321}
1322
1323// ListVolumes lists all volumes via the admin API.
1324func (c *Client) ListVolumes(ctx context.Context) ([]dto.Volume, error) {
1325	resp, err := c.request(ctx, http.MethodGet, "/volumes", nil)
1326	if err != nil {
1327		return nil, err
1328	}
1329
1330	var volumes []dto.Volume
1331	if err := parseResponse(resp, &volumes); err != nil {
1332		return nil, err
1333	}
1334
1335	return volumes, nil
1336}
1337
1338// PruneVolumes prunes orphaned volumes via the admin API.
1339func (c *Client) PruneVolumes(ctx context.Context, req dto.VolumePruneRequest) (*dto.VolumePruneResponse, error) {
1340	resp, err := c.request(ctx, http.MethodPost, "/volumes/prune", req)
1341	if err != nil {
1342		return nil, err
1343	}
1344
1345	var result dto.VolumePruneResponse
1346	if err := parseResponse(resp, &result); err != nil {
1347		return nil, err
1348	}
1349
1350	return &result, nil
1351}

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 7

Tags 106

↑↓ moveenter openesc close