v2.31.0-dev5 4162c86

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// 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"`
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 map[string]string `json:"external_routes"`
840}
841
842// GetConfig returns the Gordon configuration.
843func (c *Client) GetConfig(ctx context.Context) (*Config, error) {
844	resp, err := c.request(ctx, http.MethodGet, "/config", nil)
845	if err != nil {
846		return nil, err
847	}
848
849	var config Config
850	if err := parseResponse(resp, &config); err != nil {
851		return nil, err
852	}
853
854	return &config, nil
855}
856
857// Ping checks if the remote Gordon instance is reachable.
858func (c *Client) Ping(ctx context.Context) error {
859	_, err := c.GetStatus(ctx)
860	return err
861}
862
863// Deploy API
864
865// DeployResult contains the result of a deployment.
866type DeployResult struct {
867	Status      string `json:"status"`
868	ContainerID string `json:"container_id"`
869	Domain      string `json:"domain"`
870}
871
872// Deploy triggers a deployment for the specified domain.
873func (c *Client) Deploy(ctx context.Context, deployDomain string) (*DeployResult, error) {
874	resp, err := c.requestWithRetry(ctx, http.MethodPost, "/deploy/"+url.PathEscape(deployDomain), nil)
875	if err != nil {
876		return nil, err
877	}
878
879	var result DeployResult
880	if err := parseResponse(resp, &result); err != nil {
881		return nil, err
882	}
883
884	return &result, nil
885}
886
887// DeployIntent tells the server that a CLI-managed push is about to happen,
888// suppressing event-based deploys for this image.
889func (c *Client) DeployIntent(ctx context.Context, imageName string) error {
890	imageName = strings.TrimSpace(imageName)
891	if imageName == "" {
892		return fmt.Errorf("image name cannot be empty")
893	}
894	resp, err := c.requestWithRetry(ctx, http.MethodPost, "/deploy-intent/"+url.PathEscape(imageName), nil)
895	if err != nil {
896		return err
897	}
898	return parseResponse(resp, nil)
899}
900
901// Restart API
902
903// RestartResult contains the result of a restart.
904type RestartResult struct {
905	Status string `json:"status"`
906	Domain string `json:"domain"`
907}
908
909// Restart triggers a container restart for the specified domain.
910func (c *Client) Restart(ctx context.Context, restartDomain string, withAttachments bool) (*RestartResult, error) {
911	if restartDomain == "" {
912		return nil, fmt.Errorf("domain cannot be empty")
913	}
914	path := "/restart/" + url.PathEscape(restartDomain)
915	if withAttachments {
916		path += "?attachments=true"
917	}
918	resp, err := c.requestWithRetry(ctx, http.MethodPost, path, nil)
919	if err != nil {
920		return nil, err
921	}
922
923	var result RestartResult
924	if err := parseResponse(resp, &result); err != nil {
925		return nil, err
926	}
927
928	return &result, nil
929}
930
931// Tags API
932
933// ListTags returns available tags for a repository.
934func (c *Client) ListTags(ctx context.Context, repository string) ([]string, error) {
935	if repository == "" {
936		return nil, fmt.Errorf("repository cannot be empty")
937	}
938	resp, err := c.request(ctx, http.MethodGet, "/tags/"+url.PathEscape(repository), nil)
939	if err != nil {
940		return nil, err
941	}
942	var result struct {
943		Repository string   `json:"repository"`
944		Tags       []string `json:"tags"`
945	}
946	if err := parseResponse(resp, &result); err != nil {
947		return nil, err
948	}
949	return result.Tags, nil
950}
951
952// Logs API
953
954// GetProcessLogs returns Gordon process logs.
955func (c *Client) GetProcessLogs(ctx context.Context, lines int) ([]string, error) {
956	path := fmt.Sprintf("/logs?lines=%d", lines)
957	resp, err := c.request(ctx, http.MethodGet, path, nil)
958	if err != nil {
959		return nil, err
960	}
961
962	var result struct {
963		Lines []string `json:"lines"`
964	}
965	if err := parseResponse(resp, &result); err != nil {
966		return nil, err
967	}
968
969	return result.Lines, nil
970}
971
972// GetContainerLogs returns container logs for a specific domain.
973func (c *Client) GetContainerLogs(ctx context.Context, logDomain string, lines int) ([]string, error) {
974	path := fmt.Sprintf("/logs/%s?lines=%d", url.PathEscape(logDomain), lines)
975	resp, err := c.request(ctx, http.MethodGet, path, nil)
976	if err != nil {
977		return nil, err
978	}
979
980	var result struct {
981		Domain string   `json:"domain"`
982		Lines  []string `json:"lines"`
983	}
984	if err := parseResponse(resp, &result); err != nil {
985		return nil, err
986	}
987
988	return result.Lines, nil
989}
990
991// StreamProcessLogs returns a channel that streams Gordon process log lines via SSE.
992// The caller is responsible for reading from the channel until it's closed.
993func (c *Client) StreamProcessLogs(ctx context.Context, lines int) (<-chan string, error) {
994	path := fmt.Sprintf("/logs?lines=%d&follow=true", lines)
995	return c.streamLogs(ctx, path)
996}
997
998// StreamContainerLogs returns a channel that streams container log lines via SSE.
999// The caller is responsible for reading from the channel until it's closed.
1000func (c *Client) StreamContainerLogs(ctx context.Context, logDomain string, lines int) (<-chan string, error) {
1001	path := fmt.Sprintf("/logs/%s?lines=%d&follow=true", url.PathEscape(logDomain), lines)
1002	return c.streamLogs(ctx, path)
1003}
1004
1005// Attachments Config API
1006
1007// GetAllAttachmentsConfig returns all configured attachments.
1008func (c *Client) GetAllAttachmentsConfig(ctx context.Context) (map[string][]string, error) {
1009	resp, err := c.request(ctx, http.MethodGet, "/attachments", nil)
1010	if err != nil {
1011		return nil, err
1012	}
1013
1014	var result struct {
1015		Attachments map[string][]string `json:"attachments"`
1016	}
1017	if err := parseResponse(resp, &result); err != nil {
1018		return nil, err
1019	}
1020
1021	return result.Attachments, nil
1022}
1023
1024// GetAttachmentsConfig returns attachments for a specific domain/group from config.
1025func (c *Client) GetAttachmentsConfig(ctx context.Context, domainOrGroup string) ([]string, error) {
1026	if domainOrGroup == "" {
1027		return nil, fmt.Errorf("domain or group is required")
1028	}
1029	path := "/attachments/" + url.PathEscape(domainOrGroup)
1030	resp, err := c.request(ctx, http.MethodGet, path, nil)
1031	if err != nil {
1032		return nil, err
1033	}
1034
1035	var result struct {
1036		Target string   `json:"target"`
1037		Images []string `json:"images"`
1038	}
1039	if err := parseResponse(resp, &result); err != nil {
1040		return nil, err
1041	}
1042
1043	return result.Images, nil
1044}
1045
1046// FindAttachmentTargetsByImage returns all attachment targets associated with the given image name.
1047func (c *Client) FindAttachmentTargetsByImage(ctx context.Context, imageName string) ([]string, error) {
1048	resp, err := c.request(ctx, http.MethodGet, "/attachments/by-image/"+url.PathEscape(imageName), nil)
1049	if err != nil {
1050		return nil, err
1051	}
1052
1053	var result dto.AttachmentTargetsByImageResponse
1054	if err := parseResponse(resp, &result); err != nil {
1055		return nil, err
1056	}
1057
1058	return result.Targets, nil
1059}
1060
1061// AddAttachment adds an attachment to a domain/group.
1062func (c *Client) AddAttachment(ctx context.Context, domainOrGroup, image string) error {
1063	if domainOrGroup == "" {
1064		return fmt.Errorf("domain or group is required")
1065	}
1066	if image == "" {
1067		return fmt.Errorf("image is required")
1068	}
1069	path := "/attachments/" + url.PathEscape(domainOrGroup)
1070	resp, err := c.request(ctx, http.MethodPost, path, struct {
1071		Image string `json:"image"`
1072	}{Image: image})
1073	if err != nil {
1074		return err
1075	}
1076	return parseResponse(resp, nil)
1077}
1078
1079// RemoveAttachment removes an attachment from a domain/group.
1080func (c *Client) RemoveAttachment(ctx context.Context, domainOrGroup, image string) error {
1081	if domainOrGroup == "" {
1082		return fmt.Errorf("domain or group is required")
1083	}
1084	if image == "" {
1085		return fmt.Errorf("image is required")
1086	}
1087	path := "/attachments/" + url.PathEscape(domainOrGroup) + "/" + url.PathEscape(image)
1088	resp, err := c.request(ctx, http.MethodDelete, path, nil)
1089	if err != nil {
1090		return err
1091	}
1092	return parseResponse(resp, nil)
1093}
1094
1095func (c *Client) GetAutoRouteAllowedDomains(ctx context.Context) ([]string, error) {
1096	resp, err := c.request(ctx, http.MethodGet, "/autoroute/allowed-domains", nil)
1097	if err != nil {
1098		return nil, err
1099	}
1100
1101	var result dto.AutoRouteAllowedDomainsResponse
1102	if err := parseResponse(resp, &result); err != nil {
1103		return nil, err
1104	}
1105
1106	return result.Domains, nil
1107}
1108
1109func (c *Client) AddAutoRouteAllowedDomain(ctx context.Context, pattern string) error {
1110	if strings.TrimSpace(pattern) == "" {
1111		return fmt.Errorf("pattern must not be empty")
1112	}
1113	resp, err := c.request(ctx, http.MethodPost, "/autoroute/allowed-domains", dto.AutoRouteAllowedDomainRequest{Pattern: pattern})
1114	if err != nil {
1115		return err
1116	}
1117	return parseResponse(resp, nil)
1118}
1119
1120func (c *Client) RemoveAutoRouteAllowedDomain(ctx context.Context, pattern string) error {
1121	if strings.TrimSpace(pattern) == "" {
1122		return fmt.Errorf("pattern must not be empty")
1123	}
1124	resp, err := c.request(ctx, http.MethodDelete, "/autoroute/allowed-domains/"+url.PathEscape(pattern), nil)
1125	if err != nil {
1126		return err
1127	}
1128	return parseResponse(resp, nil)
1129}
1130
1131// openSSEStream opens an SSE connection to the given admin path and returns the response.
1132func (c *Client) openSSEStream(ctx context.Context, path string) (*http.Response, error) {
1133	streamURL := c.baseURL + "/admin" + path
1134
1135	req, err := http.NewRequestWithContext(ctx, http.MethodGet, streamURL, nil)
1136	if err != nil {
1137		return nil, fmt.Errorf("failed to create request: %w", err)
1138	}
1139
1140	req.Header.Set("Accept", "text/event-stream")
1141	bearer, err := c.bearerToken(ctx)
1142	if err != nil {
1143		return nil, err
1144	}
1145	if bearer != "" {
1146		req.Header.Set("Authorization", "Bearer "+bearer)
1147	}
1148
1149	// Use the same transport as the main client (honoring TLS config and
1150	// custom transports) but without a timeout so streaming doesn't get cut off.
1151	streamClient := &http.Client{
1152		Transport: c.httpClient.Transport,
1153	}
1154	resp, err := streamClient.Do(req)
1155	if err != nil {
1156		return nil, fmt.Errorf("failed to connect: %w", err)
1157	}
1158
1159	if resp.StatusCode >= 400 {
1160		body, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBodySize))
1161		resp.Body.Close()
1162		return nil, fmt.Errorf("%s: %s", resp.Status, string(body))
1163	}
1164
1165	return resp, nil
1166}
1167
1168// streamLogs handles SSE streaming for log endpoints.
1169func (c *Client) streamLogs(ctx context.Context, path string) (<-chan string, error) {
1170	resp, err := c.openSSEStream(ctx, path)
1171	if err != nil {
1172		return nil, err
1173	}
1174
1175	ch := make(chan string, 100)
1176
1177	go func() {
1178		defer close(ch)
1179		defer resp.Body.Close()
1180
1181		buf := make([]byte, 4096)
1182		var lineBuffer strings.Builder
1183
1184		for {
1185			select {
1186			case <-ctx.Done():
1187				return
1188			default:
1189			}
1190
1191			n, err := resp.Body.Read(buf)
1192			if n > 0 {
1193				lineBuffer.Write(buf[:n])
1194			}
1195			if err != nil {
1196				return // EOF or context cancellation — clean exit
1197			}
1198
1199			// Process complete SSE events
1200			for {
1201				data := lineBuffer.String()
1202				idx := strings.Index(data, "\n\n")
1203				if idx == -1 {
1204					break
1205				}
1206
1207				event := data[:idx]
1208				lineBuffer.Reset()
1209				lineBuffer.WriteString(data[idx+2:])
1210
1211				// Parse SSE data lines
1212				for _, line := range strings.Split(event, "\n") {
1213					if strings.HasPrefix(line, "data: ") {
1214						logLine := strings.TrimPrefix(line, "data: ")
1215						select {
1216						case ch <- logLine:
1217						case <-ctx.Done():
1218							return
1219						}
1220					}
1221				}
1222			}
1223		}
1224	}()
1225
1226	return ch, nil
1227}
1228
1229// VerifyAuth checks if authentication session is valid.
1230func (c *Client) VerifyAuth(ctx context.Context) (*dto.AuthVerifyResponse, error) {
1231	resp, err := c.request(ctx, http.MethodGet, "/auth/verify", nil)
1232	if err != nil {
1233		return nil, err
1234	}
1235
1236	var result dto.AuthVerifyResponse
1237	if err := parseResponse(resp, &result); err != nil {
1238		return nil, err
1239	}
1240
1241	return &result, nil
1242}
1243
1244// ListVolumes lists all volumes via the admin API.
1245func (c *Client) ListVolumes(ctx context.Context) ([]dto.Volume, error) {
1246	resp, err := c.request(ctx, http.MethodGet, "/volumes", nil)
1247	if err != nil {
1248		return nil, err
1249	}
1250
1251	var volumes []dto.Volume
1252	if err := parseResponse(resp, &volumes); err != nil {
1253		return nil, err
1254	}
1255
1256	return volumes, nil
1257}
1258
1259// PruneVolumes prunes orphaned volumes via the admin API.
1260func (c *Client) PruneVolumes(ctx context.Context, req dto.VolumePruneRequest) (*dto.VolumePruneResponse, error) {
1261	resp, err := c.request(ctx, http.MethodPost, "/volumes/prune", req)
1262	if err != nil {
1263		return nil, err
1264	}
1265
1266	var result dto.VolumePruneResponse
1267	if err := parseResponse(resp, &result); err != nil {
1268		return nil, err
1269	}
1270
1271	return &result, nil
1272}

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