v2.31.0-dev17 bd898f0

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		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// GetTLSStatus returns the public TLS/ACME status.
661func (c *Client) GetTLSStatus(ctx context.Context) (*dto.TLSStatusResponse, error) {
662	resp, err := c.request(ctx, http.MethodGet, "/tls/status", nil)
663	if err != nil {
664		return nil, err
665	}
666
667	var status dto.TLSStatusResponse
668	if err := parseResponse(resp, &status); err != nil {
669		return nil, err
670	}
671
672	return &status, nil
673}
674
675// GetStatus returns the Gordon server status.
676func (c *Client) GetStatus(ctx context.Context) (*Status, error) {
677	resp, err := c.request(ctx, http.MethodGet, "/status", nil)
678	if err != nil {
679		return nil, err
680	}
681
682	var status Status
683	if err := parseResponse(resp, &status); err != nil {
684		return nil, err
685	}
686
687	return &status, nil
688}
689
690// RouteHealth represents the health status of a route.
691type RouteHealth struct {
692	ContainerStatus string `json:"container_status"`
693	HTTPStatus      int    `json:"http_status"`
694	ResponseTimeMs  int64  `json:"response_time_ms"`
695	Healthy         bool   `json:"healthy"`
696	Error           string `json:"error"`
697}
698
699// Backups API
700
701// Images API
702
703// ListImages returns runtime images and registry tags from the admin API.
704func (c *Client) ListImages(ctx context.Context) ([]dto.Image, error) {
705	resp, err := c.request(ctx, http.MethodGet, "/images", nil)
706	if err != nil {
707		return nil, err
708	}
709
710	var result dto.ImagesResponse
711	if err := parseResponse(resp, &result); err != nil {
712		return nil, err
713	}
714
715	return result.Images, nil
716}
717
718// PruneImages prunes runtime and registry images.
719func (c *Client) PruneImages(ctx context.Context, req dto.ImagePruneRequest) (*dto.ImagePruneResponse, error) {
720	if req.KeepLast != nil && *req.KeepLast < 0 {
721		return nil, fmt.Errorf("keep_last must be >= 0")
722	}
723
724	resp, err := c.request(ctx, http.MethodPost, "/images/prune", req)
725	if err != nil {
726		return nil, err
727	}
728
729	var result dto.ImagePruneResponse
730	if err := parseResponse(resp, &result); err != nil {
731		return nil, err
732	}
733
734	return &result, nil
735}
736
737// ListBackups returns backups globally or for a domain.
738func (c *Client) ListBackups(ctx context.Context, backupDomain string) ([]dto.BackupJob, error) {
739	path := "/backups"
740	if backupDomain != "" {
741		path += "/" + url.PathEscape(backupDomain)
742	}
743
744	resp, err := c.request(ctx, http.MethodGet, path, 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// BackupStatus returns aggregate backup status.
758func (c *Client) BackupStatus(ctx context.Context) ([]dto.BackupJob, error) {
759	resp, err := c.request(ctx, http.MethodGet, "/backups/status", nil)
760	if err != nil {
761		return nil, err
762	}
763
764	var result dto.BackupsResponse
765	if err := parseResponse(resp, &result); err != nil {
766		return nil, err
767	}
768
769	return result.Backups, nil
770}
771
772// RunBackup triggers a backup for a domain.
773func (c *Client) RunBackup(ctx context.Context, backupDomain, dbName string) (*dto.BackupRunResponse, error) {
774	if backupDomain == "" {
775		return nil, fmt.Errorf("domain cannot be empty")
776	}
777
778	resp, err := c.request(ctx, http.MethodPost, "/backups/"+url.PathEscape(backupDomain), dto.BackupRunRequest{DB: dbName})
779	if err != nil {
780		return nil, err
781	}
782
783	var result dto.BackupRunResponse
784	if err := parseResponse(resp, &result); err != nil {
785		return nil, err
786	}
787
788	return &result, nil
789}
790
791// DetectDatabases detects supported databases for a domain.
792func (c *Client) DetectDatabases(ctx context.Context, backupDomain string) ([]dto.DatabaseInfo, error) {
793	if backupDomain == "" {
794		return nil, fmt.Errorf("domain cannot be empty")
795	}
796
797	resp, err := c.request(ctx, http.MethodGet, "/backups/"+url.PathEscape(backupDomain)+"/detect", nil)
798	if err != nil {
799		return nil, err
800	}
801
802	var result dto.BackupDetectResponse
803	if err := parseResponse(resp, &result); err != nil {
804		return nil, err
805	}
806
807	return result.Databases, nil
808}
809
810// GetHealth returns health status for all routes with HTTP probing.
811func (c *Client) GetHealth(ctx context.Context) (map[string]*RouteHealth, error) {
812	resp, err := c.request(ctx, http.MethodGet, "/health", nil)
813	if err != nil {
814		return nil, err
815	}
816
817	var result struct {
818		Health map[string]*RouteHealth `json:"health"`
819	}
820	if err := parseResponse(resp, &result); err != nil {
821		return nil, err
822	}
823
824	return result.Health, nil
825}
826
827// Reload triggers a configuration reload.
828func (c *Client) Reload(ctx context.Context) error {
829	resp, err := c.requestWithRetry(ctx, http.MethodPost, "/reload", nil)
830	if err != nil {
831		return err
832	}
833	return parseResponse(resp, nil)
834}
835
836// Config API
837
838// Config represents the Gordon configuration.
839type Config struct {
840	Server struct {
841		Port           int    `json:"port"`
842		RegistryPort   int    `json:"registry_port"`
843		RegistryDomain string `json:"registry_domain"`
844		DataDir        string `json:"data_dir,omitempty"`
845	} `json:"server"`
846	AutoRoute struct {
847		Enabled bool `json:"enabled"`
848	} `json:"auto_route"`
849	NetworkIsolation struct {
850		Enabled bool   `json:"enabled"`
851		Prefix  string `json:"prefix"`
852	} `json:"network_isolation"`
853	Routes         []domain.Route  `json:"routes"`
854	ExternalRoutes []ExternalRoute `json:"external_routes"`
855}
856
857// ExternalRoute represents a redacted external route config entry.
858type ExternalRoute struct {
859	Domain string `json:"domain"`
860	Target string `json:"target,omitempty"`
861}
862
863// GetConfig returns the Gordon configuration.
864func (c *Client) GetConfig(ctx context.Context) (*Config, error) {
865	resp, err := c.request(ctx, http.MethodGet, "/config", nil)
866	if err != nil {
867		return nil, err
868	}
869
870	var config Config
871	if err := parseResponse(resp, &config); err != nil {
872		return nil, err
873	}
874
875	return &config, nil
876}
877
878// Ping checks if the remote Gordon instance is reachable.
879func (c *Client) Ping(ctx context.Context) error {
880	_, err := c.GetStatus(ctx)
881	return err
882}
883
884// Deploy API
885
886// DeployResult contains the result of a deployment.
887type DeployResult struct {
888	Status      string `json:"status"`
889	ContainerID string `json:"container_id"`
890	Domain      string `json:"domain"`
891}
892
893// Deploy triggers a deployment for the specified domain.
894func (c *Client) Deploy(ctx context.Context, deployDomain string) (*DeployResult, error) {
895	resp, err := c.requestWithRetry(ctx, http.MethodPost, "/deploy/"+url.PathEscape(deployDomain), nil)
896	if err != nil {
897		return nil, err
898	}
899
900	var result DeployResult
901	if err := parseResponse(resp, &result); err != nil {
902		return nil, err
903	}
904
905	return &result, nil
906}
907
908// DeployIntent tells the server that a CLI-managed push is about to happen,
909// suppressing event-based deploys for this image.
910func (c *Client) DeployIntent(ctx context.Context, imageName string) error {
911	imageName = strings.TrimSpace(imageName)
912	if imageName == "" {
913		return fmt.Errorf("image name cannot be empty")
914	}
915	resp, err := c.requestWithRetry(ctx, http.MethodPost, "/deploy-intent/"+url.PathEscape(imageName), nil)
916	if err != nil {
917		return err
918	}
919	return parseResponse(resp, nil)
920}
921
922// Restart API
923
924// RestartResult contains the result of a restart.
925type RestartResult struct {
926	Status string `json:"status"`
927	Domain string `json:"domain"`
928}
929
930// Restart triggers a container restart for the specified domain.
931func (c *Client) Restart(ctx context.Context, restartDomain string, withAttachments bool) (*RestartResult, error) {
932	if restartDomain == "" {
933		return nil, fmt.Errorf("domain cannot be empty")
934	}
935	path := "/restart/" + url.PathEscape(restartDomain)
936	if withAttachments {
937		path += "?attachments=true"
938	}
939	resp, err := c.requestWithRetry(ctx, http.MethodPost, path, nil)
940	if err != nil {
941		return nil, err
942	}
943
944	var result RestartResult
945	if err := parseResponse(resp, &result); err != nil {
946		return nil, err
947	}
948
949	return &result, nil
950}
951
952// Tags API
953
954// ListTags returns available tags for a repository.
955func (c *Client) ListTags(ctx context.Context, repository string) ([]string, error) {
956	if repository == "" {
957		return nil, fmt.Errorf("repository cannot be empty")
958	}
959	resp, err := c.request(ctx, http.MethodGet, "/tags/"+url.PathEscape(repository), nil)
960	if err != nil {
961		return nil, err
962	}
963	var result struct {
964		Repository string   `json:"repository"`
965		Tags       []string `json:"tags"`
966	}
967	if err := parseResponse(resp, &result); err != nil {
968		return nil, err
969	}
970	return result.Tags, nil
971}
972
973// Logs API
974
975// GetProcessLogs returns Gordon process logs.
976func (c *Client) GetProcessLogs(ctx context.Context, lines int) ([]string, error) {
977	path := fmt.Sprintf("/logs?lines=%d", lines)
978	resp, err := c.request(ctx, http.MethodGet, path, nil)
979	if err != nil {
980		return nil, err
981	}
982
983	var result struct {
984		Lines []string `json:"lines"`
985	}
986	if err := parseResponse(resp, &result); err != nil {
987		return nil, err
988	}
989
990	return result.Lines, nil
991}
992
993// GetContainerLogs returns container logs for a specific domain.
994func (c *Client) GetContainerLogs(ctx context.Context, logDomain string, lines int) ([]string, error) {
995	path := fmt.Sprintf("/logs/%s?lines=%d", url.PathEscape(logDomain), lines)
996	resp, err := c.request(ctx, http.MethodGet, path, nil)
997	if err != nil {
998		return nil, err
999	}
1000
1001	var result struct {
1002		Domain string   `json:"domain"`
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// StreamProcessLogs returns a channel that streams Gordon process log lines via SSE.
1013// The caller is responsible for reading from the channel until it's closed.
1014func (c *Client) StreamProcessLogs(ctx context.Context, lines int) (<-chan string, error) {
1015	path := fmt.Sprintf("/logs?lines=%d&follow=true", lines)
1016	return c.streamLogs(ctx, path)
1017}
1018
1019// StreamContainerLogs returns a channel that streams container log lines via SSE.
1020// The caller is responsible for reading from the channel until it's closed.
1021func (c *Client) StreamContainerLogs(ctx context.Context, logDomain string, lines int) (<-chan string, error) {
1022	path := fmt.Sprintf("/logs/%s?lines=%d&follow=true", url.PathEscape(logDomain), lines)
1023	return c.streamLogs(ctx, path)
1024}
1025
1026// Attachments Config API
1027
1028// GetAllAttachmentsConfig returns all configured attachments.
1029func (c *Client) GetAllAttachmentsConfig(ctx context.Context) (map[string][]string, error) {
1030	resp, err := c.request(ctx, http.MethodGet, "/attachments", nil)
1031	if err != nil {
1032		return nil, err
1033	}
1034
1035	var result struct {
1036		Attachments map[string][]string `json:"attachments"`
1037	}
1038	if err := parseResponse(resp, &result); err != nil {
1039		return nil, err
1040	}
1041
1042	return result.Attachments, nil
1043}
1044
1045// GetAttachmentsConfig returns attachments for a specific domain/group from config.
1046func (c *Client) GetAttachmentsConfig(ctx context.Context, domainOrGroup string) ([]string, error) {
1047	if domainOrGroup == "" {
1048		return nil, fmt.Errorf("domain or group is required")
1049	}
1050	path := "/attachments/" + url.PathEscape(domainOrGroup)
1051	resp, err := c.request(ctx, http.MethodGet, path, nil)
1052	if err != nil {
1053		return nil, err
1054	}
1055
1056	var result struct {
1057		Target string   `json:"target"`
1058		Images []string `json:"images"`
1059	}
1060	if err := parseResponse(resp, &result); err != nil {
1061		return nil, err
1062	}
1063
1064	return result.Images, nil
1065}
1066
1067// FindAttachmentTargetsByImage returns all attachment targets associated with the given image name.
1068func (c *Client) FindAttachmentTargetsByImage(ctx context.Context, imageName string) ([]string, error) {
1069	resp, err := c.request(ctx, http.MethodGet, "/attachments/by-image/"+url.PathEscape(imageName), nil)
1070	if err != nil {
1071		return nil, err
1072	}
1073
1074	var result dto.AttachmentTargetsByImageResponse
1075	if err := parseResponse(resp, &result); err != nil {
1076		return nil, err
1077	}
1078
1079	return result.Targets, nil
1080}
1081
1082// AddAttachment adds an attachment to a domain/group.
1083func (c *Client) AddAttachment(ctx context.Context, domainOrGroup, image string) error {
1084	if domainOrGroup == "" {
1085		return fmt.Errorf("domain or group is required")
1086	}
1087	if image == "" {
1088		return fmt.Errorf("image is required")
1089	}
1090	path := "/attachments/" + url.PathEscape(domainOrGroup)
1091	resp, err := c.request(ctx, http.MethodPost, path, struct {
1092		Image string `json:"image"`
1093	}{Image: image})
1094	if err != nil {
1095		return err
1096	}
1097	return parseResponse(resp, nil)
1098}
1099
1100// RemoveAttachment removes an attachment from a domain/group.
1101func (c *Client) RemoveAttachment(ctx context.Context, domainOrGroup, image string) error {
1102	if domainOrGroup == "" {
1103		return fmt.Errorf("domain or group is required")
1104	}
1105	if image == "" {
1106		return fmt.Errorf("image is required")
1107	}
1108	path := "/attachments/" + url.PathEscape(domainOrGroup) + "/" + url.PathEscape(image)
1109	resp, err := c.request(ctx, http.MethodDelete, path, nil)
1110	if err != nil {
1111		return err
1112	}
1113	return parseResponse(resp, nil)
1114}
1115
1116func (c *Client) GetAutoRouteAllowedDomains(ctx context.Context) ([]string, error) {
1117	resp, err := c.request(ctx, http.MethodGet, "/autoroute/allowed-domains", nil)
1118	if err != nil {
1119		return nil, err
1120	}
1121
1122	var result dto.AutoRouteAllowedDomainsResponse
1123	if err := parseResponse(resp, &result); err != nil {
1124		return nil, err
1125	}
1126
1127	return result.Domains, nil
1128}
1129
1130func (c *Client) AddAutoRouteAllowedDomain(ctx context.Context, pattern string) error {
1131	if strings.TrimSpace(pattern) == "" {
1132		return fmt.Errorf("pattern must not be empty")
1133	}
1134	resp, err := c.request(ctx, http.MethodPost, "/autoroute/allowed-domains", dto.AutoRouteAllowedDomainRequest{Pattern: pattern})
1135	if err != nil {
1136		return err
1137	}
1138	return parseResponse(resp, nil)
1139}
1140
1141func (c *Client) RemoveAutoRouteAllowedDomain(ctx context.Context, pattern string) error {
1142	if strings.TrimSpace(pattern) == "" {
1143		return fmt.Errorf("pattern must not be empty")
1144	}
1145	resp, err := c.request(ctx, http.MethodDelete, "/autoroute/allowed-domains/"+url.PathEscape(pattern), nil)
1146	if err != nil {
1147		return err
1148	}
1149	return parseResponse(resp, nil)
1150}
1151
1152// openSSEStream opens an SSE connection to the given admin path and returns the response.
1153func (c *Client) openSSEStream(ctx context.Context, path string) (*http.Response, error) {
1154	streamURL := c.baseURL + "/admin" + path
1155
1156	req, err := http.NewRequestWithContext(ctx, http.MethodGet, streamURL, nil)
1157	if err != nil {
1158		return nil, fmt.Errorf("failed to create request: %w", err)
1159	}
1160
1161	req.Header.Set("Accept", "text/event-stream")
1162	bearer, err := c.bearerToken(ctx)
1163	if err != nil {
1164		return nil, err
1165	}
1166	if bearer != "" {
1167		req.Header.Set("Authorization", "Bearer "+bearer)
1168	}
1169
1170	// Use the same transport as the main client (honoring TLS config and
1171	// custom transports) but without a timeout so streaming doesn't get cut off.
1172	streamClient := &http.Client{
1173		Transport: c.httpClient.Transport,
1174	}
1175	resp, err := streamClient.Do(req)
1176	if err != nil {
1177		return nil, fmt.Errorf("failed to connect: %w", err)
1178	}
1179
1180	if resp.StatusCode >= 400 {
1181		body, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBodySize))
1182		resp.Body.Close()
1183		return nil, fmt.Errorf("%s: %s", resp.Status, string(body))
1184	}
1185
1186	return resp, nil
1187}
1188
1189// streamLogs handles SSE streaming for log endpoints.
1190func (c *Client) streamLogs(ctx context.Context, path string) (<-chan string, error) {
1191	resp, err := c.openSSEStream(ctx, path)
1192	if err != nil {
1193		return nil, err
1194	}
1195
1196	ch := make(chan string, 100)
1197
1198	go func() {
1199		defer close(ch)
1200		defer resp.Body.Close()
1201
1202		buf := make([]byte, 4096)
1203		var lineBuffer strings.Builder
1204
1205		for {
1206			select {
1207			case <-ctx.Done():
1208				return
1209			default:
1210			}
1211
1212			n, err := resp.Body.Read(buf)
1213			if n > 0 {
1214				lineBuffer.Write(buf[:n])
1215			}
1216			if err != nil {
1217				return // EOF or context cancellation — clean exit
1218			}
1219
1220			// Process complete SSE events
1221			for {
1222				data := lineBuffer.String()
1223				idx := strings.Index(data, "\n\n")
1224				if idx == -1 {
1225					break
1226				}
1227
1228				event := data[:idx]
1229				lineBuffer.Reset()
1230				lineBuffer.WriteString(data[idx+2:])
1231
1232				// Parse SSE data lines
1233				for _, line := range strings.Split(event, "\n") {
1234					if strings.HasPrefix(line, "data: ") {
1235						logLine := strings.TrimPrefix(line, "data: ")
1236						select {
1237						case ch <- logLine:
1238						case <-ctx.Done():
1239							return
1240						}
1241					}
1242				}
1243			}
1244		}
1245	}()
1246
1247	return ch, nil
1248}
1249
1250// VerifyAuth checks if authentication session is valid.
1251func (c *Client) VerifyAuth(ctx context.Context) (*dto.AuthVerifyResponse, error) {
1252	resp, err := c.request(ctx, http.MethodGet, "/auth/verify", nil)
1253	if err != nil {
1254		return nil, err
1255	}
1256
1257	var result dto.AuthVerifyResponse
1258	if err := parseResponse(resp, &result); err != nil {
1259		return nil, err
1260	}
1261
1262	return &result, nil
1263}
1264
1265// ListVolumes lists all volumes via the admin API.
1266func (c *Client) ListVolumes(ctx context.Context) ([]dto.Volume, error) {
1267	resp, err := c.request(ctx, http.MethodGet, "/volumes", nil)
1268	if err != nil {
1269		return nil, err
1270	}
1271
1272	var volumes []dto.Volume
1273	if err := parseResponse(resp, &volumes); err != nil {
1274		return nil, err
1275	}
1276
1277	return volumes, nil
1278}
1279
1280// PruneVolumes prunes orphaned volumes via the admin API.
1281func (c *Client) PruneVolumes(ctx context.Context, req dto.VolumePruneRequest) (*dto.VolumePruneResponse, error) {
1282	resp, err := c.request(ctx, http.MethodPost, "/volumes/prune", req)
1283	if err != nil {
1284		return nil, err
1285	}
1286
1287	var result dto.VolumePruneResponse
1288	if err := parseResponse(resp, &result); err != nil {
1289		return nil, err
1290	}
1291
1292	return &result, nil
1293}

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