v2.13.0 7748089

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	"time"
17
18	"github.com/bnema/gordon/internal/adapters/dto"
19	"github.com/bnema/gordon/internal/domain"
20)
21
22// Client is an HTTP client for the Gordon admin API.
23type Client struct {
24	baseURL     string
25	token       string
26	httpClient  *http.Client
27	insecureTLS bool
28}
29
30var (
31	retryMaxAttempts = 4
32	retryBaseDelay   = 250 * time.Millisecond
33)
34
35// ClientOption configures the Client.
36type ClientOption func(*Client)
37
38// NewClient creates a new remote Gordon client.
39func NewClient(baseURL string, opts ...ClientOption) *Client {
40	// Normalize base URL
41	baseURL = strings.TrimSuffix(baseURL, "/")
42
43	c := &Client{
44		baseURL: baseURL,
45		httpClient: &http.Client{
46			Timeout: 2 * time.Minute,
47		},
48	}
49
50	for _, opt := range opts {
51		opt(c)
52	}
53
54	c.applyTLSConfig()
55
56	return c
57}
58
59// WithToken sets the authentication token.
60func WithToken(token string) ClientOption {
61	return func(c *Client) {
62		c.token = token
63	}
64}
65
66// WithHTTPClient sets a custom HTTP client.
67func WithHTTPClient(client *http.Client) ClientOption {
68	return func(c *Client) {
69		c.httpClient = client
70	}
71}
72
73// WithTimeout sets the HTTP client timeout.
74func WithTimeout(timeout time.Duration) ClientOption {
75	return func(c *Client) {
76		c.httpClient.Timeout = timeout
77	}
78}
79
80// WithInsecureTLS disables TLS certificate verification for remote admin API requests.
81func WithInsecureTLS(insecure bool) ClientOption {
82	return func(c *Client) {
83		c.insecureTLS = insecure
84	}
85}
86
87func (c *Client) applyTLSConfig() {
88	if !c.insecureTLS {
89		return
90	}
91
92	fmt.Fprintf(os.Stderr, "WARNING: TLS certificate verification disabled for %s\n", c.baseURL)
93
94	var transport *http.Transport
95	switch t := c.httpClient.Transport.(type) {
96	case *http.Transport:
97		transport = t.Clone()
98	case nil:
99		transport = http.DefaultTransport.(*http.Transport).Clone()
100	default:
101		// Cannot apply InsecureSkipVerify to a non-*http.Transport.
102		// Log a warning and leave the transport intact rather than
103		// silently replacing it (which would drop caller-provided behavior).
104		fmt.Fprintf(os.Stderr, "WARNING: --insecure requires *http.Transport, got %T; TLS override not applied\n", t)
105		return
106	}
107
108	if transport.TLSClientConfig == nil {
109		transport.TLSClientConfig = &tls.Config{MinVersion: tls.VersionTLS12}
110	} else {
111		transport.TLSClientConfig.MinVersion = tls.VersionTLS12
112	}
113	//nolint:gosec // Explicit CLI opt-in via --insecure for self-signed/private cert deployments.
114	transport.TLSClientConfig.InsecureSkipVerify = true
115	c.httpClient.Transport = transport
116}
117
118// request performs an HTTP request to the admin API.
119func (c *Client) request(ctx context.Context, method, path string, body any) (*http.Response, error) {
120	url := c.baseURL + "/admin" + path
121
122	var bodyReader io.Reader
123	if body != nil {
124		jsonBody, err := json.Marshal(body)
125		if err != nil {
126			return nil, fmt.Errorf("failed to marshal request body: %w", err)
127		}
128		bodyReader = bytes.NewReader(jsonBody)
129	}
130
131	req, err := http.NewRequestWithContext(ctx, method, url, bodyReader)
132	if err != nil {
133		return nil, fmt.Errorf("failed to create request: %w", err)
134	}
135
136	req.Header.Set("Content-Type", "application/json")
137	req.Header.Set("Accept", "application/json")
138
139	if c.token != "" {
140		req.Header.Set("Authorization", "Bearer "+c.token)
141	}
142
143	return c.httpClient.Do(req)
144}
145
146// parseResponse parses a JSON response into the given target.
147func parseResponse(resp *http.Response, target any) error {
148	defer resp.Body.Close()
149
150	if resp.StatusCode >= 400 {
151		body, _ := io.ReadAll(resp.Body)
152		return parseErrorResponse(resp, body)
153	}
154
155	if target != nil {
156		if err := json.NewDecoder(resp.Body).Decode(target); err != nil {
157			return fmt.Errorf("failed to decode response: %w", err)
158		}
159	}
160
161	return nil
162}
163
164func parseErrorResponse(resp *http.Response, body []byte) error {
165	var errResp struct {
166		Error string `json:"error"`
167	}
168	if err := json.Unmarshal(body, &errResp); err == nil && errResp.Error != "" {
169		return fmt.Errorf("%s: %s", resp.Status, errResp.Error)
170	}
171	return fmt.Errorf("%s: %s", resp.Status, string(body))
172}
173
174func isRetryableRequestError(err error) bool {
175	return !errors.Is(err, context.Canceled) && !errors.Is(err, context.DeadlineExceeded)
176}
177
178func isRetryableStatus(status int) bool {
179	// Only retry gateway errors; retrying 500 on non-idempotent POSTs
180	// (deploy, restart, reload) can cause duplicate state changes.
181	return status == 502 || status == 503 || status == 504
182}
183
184func retryDelay(attempt int) time.Duration {
185	if attempt <= 1 {
186		return retryBaseDelay
187	}
188	return retryBaseDelay * time.Duration(1<<(attempt-1))
189}
190
191// requestWithRetry performs an HTTP request and retries transient failures.
192// Retries occur on transport errors and gateway errors (502, 503, 504).
193func (c *Client) requestWithRetry(ctx context.Context, method, path string, body any) (*http.Response, error) {
194	var lastErr error
195
196	for attempt := 1; attempt <= retryMaxAttempts; attempt++ {
197		resp, err := c.request(ctx, method, path, body)
198		if err != nil {
199			lastErr = err
200			if attempt == retryMaxAttempts || !isRetryableRequestError(err) {
201				return nil, err
202			}
203		} else {
204			if !isRetryableStatus(resp.StatusCode) {
205				return resp, nil
206			}
207
208			respBody, _ := io.ReadAll(resp.Body)
209			_ = resp.Body.Close()
210			lastErr = parseErrorResponse(resp, respBody)
211			if attempt == retryMaxAttempts {
212				return nil, lastErr
213			}
214		}
215
216		delay := retryDelay(attempt)
217		timer := time.NewTimer(delay)
218		select {
219		case <-ctx.Done():
220			timer.Stop()
221			return nil, ctx.Err()
222		case <-timer.C:
223		}
224	}
225
226	if lastErr != nil {
227		return nil, lastErr
228	}
229	return nil, fmt.Errorf("request failed after retries")
230}
231
232// Routes API
233
234// Type aliases for API types using shared DTO package.
235type RouteInfo = dto.RouteInfo
236type Attachment = dto.Attachment
237
238// ListRoutes returns all configured routes.
239func (c *Client) ListRoutes(ctx context.Context) ([]domain.Route, error) {
240	resp, err := c.request(ctx, http.MethodGet, "/routes", nil)
241	if err != nil {
242		return nil, err
243	}
244
245	var result struct {
246		Routes []domain.Route `json:"routes"`
247	}
248	if err := parseResponse(resp, &result); err != nil {
249		return nil, err
250	}
251
252	return result.Routes, nil
253}
254
255// ListRoutesWithDetails returns routes with network and attachment info.
256func (c *Client) ListRoutesWithDetails(ctx context.Context) ([]RouteInfo, error) {
257	resp, err := c.request(ctx, http.MethodGet, "/routes?detailed=true", nil)
258	if err != nil {
259		return nil, err
260	}
261
262	var result struct {
263		Routes []RouteInfo `json:"routes"`
264	}
265	if err := parseResponse(resp, &result); err != nil {
266		return nil, err
267	}
268
269	return result.Routes, nil
270}
271
272// ListNetworks returns Gordon-managed networks.
273func (c *Client) ListNetworks(ctx context.Context) ([]*domain.NetworkInfo, error) {
274	resp, err := c.request(ctx, http.MethodGet, "/networks", nil)
275	if err != nil {
276		return nil, err
277	}
278
279	var result struct {
280		Networks []*domain.NetworkInfo `json:"networks"`
281	}
282	if err := parseResponse(resp, &result); err != nil {
283		return nil, err
284	}
285
286	return result.Networks, nil
287}
288
289// ListAttachments returns attachments for a domain.
290func (c *Client) ListAttachments(ctx context.Context, routeDomain string) ([]Attachment, error) {
291	if routeDomain == "" {
292		return nil, fmt.Errorf("domain is required")
293	}
294	path := "/routes/" + url.PathEscape(routeDomain) + "/attachments"
295	resp, err := c.request(ctx, http.MethodGet, path, nil)
296	if err != nil {
297		return nil, err
298	}
299
300	var result struct {
301		Attachments []Attachment `json:"attachments"`
302	}
303	if err := parseResponse(resp, &result); err != nil {
304		return nil, err
305	}
306
307	return result.Attachments, nil
308}
309
310// GetRoute returns a specific route by domain.
311func (c *Client) GetRoute(ctx context.Context, routeDomain string) (*domain.Route, error) {
312	resp, err := c.request(ctx, http.MethodGet, "/routes/"+url.PathEscape(routeDomain), nil)
313	if err != nil {
314		return nil, err
315	}
316
317	var route domain.Route
318	if err := parseResponse(resp, &route); err != nil {
319		return nil, err
320	}
321
322	return &route, nil
323}
324
325// AddRoute adds a new route.
326func (c *Client) AddRoute(ctx context.Context, route domain.Route) error {
327	resp, err := c.request(ctx, http.MethodPost, "/routes", route)
328	if err != nil {
329		return err
330	}
331	return parseResponse(resp, nil)
332}
333
334// UpdateRoute updates an existing route.
335func (c *Client) UpdateRoute(ctx context.Context, route domain.Route) error {
336	resp, err := c.request(ctx, http.MethodPut, "/routes/"+url.PathEscape(route.Domain), route)
337	if err != nil {
338		return err
339	}
340	return parseResponse(resp, nil)
341}
342
343// RemoveRoute removes a route by domain.
344func (c *Client) RemoveRoute(ctx context.Context, routeDomain string) error {
345	resp, err := c.request(ctx, http.MethodDelete, "/routes/"+url.PathEscape(routeDomain), nil)
346	if err != nil {
347		return err
348	}
349	return parseResponse(resp, nil)
350}
351
352// Secrets API
353
354// AttachmentSecrets represents secrets for an attachment container.
355type AttachmentSecrets struct {
356	Service string   `json:"service"`
357	Keys    []string `json:"keys"`
358}
359
360// SecretsListResult contains domain secrets and any attachment secrets.
361type SecretsListResult struct {
362	Domain      string              `json:"domain"`
363	Keys        []string            `json:"keys"`
364	Attachments []AttachmentSecrets `json:"attachments,omitempty"`
365}
366
367// ListSecrets returns the list of secret keys for a domain.
368func (c *Client) ListSecrets(ctx context.Context, secretDomain string) ([]string, error) {
369	result, err := c.ListSecretsWithAttachments(ctx, secretDomain)
370	if err != nil {
371		return nil, err
372	}
373	return result.Keys, nil
374}
375
376// ListSecretsWithAttachments returns domain secrets and attachment secrets.
377func (c *Client) ListSecretsWithAttachments(ctx context.Context, secretDomain string) (*SecretsListResult, error) {
378	resp, err := c.request(ctx, http.MethodGet, "/secrets/"+url.PathEscape(secretDomain), nil)
379	if err != nil {
380		return nil, err
381	}
382
383	var result SecretsListResult
384	if err := parseResponse(resp, &result); err != nil {
385		return nil, err
386	}
387
388	return &result, nil
389}
390
391// SetSecrets sets secrets for a domain.
392func (c *Client) SetSecrets(ctx context.Context, secretDomain string, secrets map[string]string) error {
393	resp, err := c.request(ctx, http.MethodPost, "/secrets/"+url.PathEscape(secretDomain), secrets)
394	if err != nil {
395		return err
396	}
397	return parseResponse(resp, nil)
398}
399
400// DeleteSecret removes a secret from a domain.
401func (c *Client) DeleteSecret(ctx context.Context, secretDomain, key string) error {
402	resp, err := c.request(ctx, http.MethodDelete, "/secrets/"+url.PathEscape(secretDomain)+"/"+url.PathEscape(key), nil)
403	if err != nil {
404		return err
405	}
406	return parseResponse(resp, nil)
407}
408
409// SetAttachmentSecrets sets secrets for an attachment container.
410func (c *Client) SetAttachmentSecrets(ctx context.Context, domain, service string, secrets map[string]string) error {
411	path := "/secrets/" + url.PathEscape(domain) + "/attachments/" + url.PathEscape(service)
412	resp, err := c.request(ctx, http.MethodPost, path, secrets)
413	if err != nil {
414		return err
415	}
416	return parseResponse(resp, nil)
417}
418
419// DeleteAttachmentSecret removes a secret from an attachment container.
420func (c *Client) DeleteAttachmentSecret(ctx context.Context, domain, service, key string) error {
421	path := "/secrets/" + url.PathEscape(domain) + "/attachments/" + url.PathEscape(service) + "/" + url.PathEscape(key)
422	resp, err := c.request(ctx, http.MethodDelete, path, nil)
423	if err != nil {
424		return err
425	}
426	return parseResponse(resp, nil)
427}
428
429// Status API
430
431// Status represents the Gordon server status.
432type Status struct {
433	Routes           int               `json:"routes"`
434	RegistryDomain   string            `json:"registry_domain"`
435	RegistryPort     int               `json:"registry_port"`
436	ServerPort       int               `json:"server_port"`
437	AutoRoute        bool              `json:"auto_route"`
438	NetworkIsolation bool              `json:"network_isolation"`
439	ContainerStatus  map[string]string `json:"container_status"`
440}
441
442// GetStatus returns the Gordon server status.
443func (c *Client) GetStatus(ctx context.Context) (*Status, error) {
444	resp, err := c.request(ctx, http.MethodGet, "/status", nil)
445	if err != nil {
446		return nil, err
447	}
448
449	var status Status
450	if err := parseResponse(resp, &status); err != nil {
451		return nil, err
452	}
453
454	return &status, nil
455}
456
457// RouteHealth represents the health status of a route.
458type RouteHealth struct {
459	ContainerStatus string `json:"container_status"`
460	HTTPStatus      int    `json:"http_status"`
461	ResponseTimeMs  int64  `json:"response_time_ms"`
462	Healthy         bool   `json:"healthy"`
463	Error           string `json:"error"`
464}
465
466// GetHealth returns health status for all routes with HTTP probing.
467func (c *Client) GetHealth(ctx context.Context) (map[string]*RouteHealth, error) {
468	resp, err := c.request(ctx, http.MethodGet, "/health", nil)
469	if err != nil {
470		return nil, err
471	}
472
473	var result struct {
474		Health map[string]*RouteHealth `json:"health"`
475	}
476	if err := parseResponse(resp, &result); err != nil {
477		return nil, err
478	}
479
480	return result.Health, nil
481}
482
483// Reload triggers a configuration reload.
484func (c *Client) Reload(ctx context.Context) error {
485	resp, err := c.requestWithRetry(ctx, http.MethodPost, "/reload", nil)
486	if err != nil {
487		return err
488	}
489	return parseResponse(resp, nil)
490}
491
492// Config API
493
494// Config represents the Gordon configuration.
495type Config struct {
496	Server struct {
497		Port           int    `json:"port"`
498		RegistryPort   int    `json:"registry_port"`
499		RegistryDomain string `json:"registry_domain"`
500		DataDir        string `json:"data_dir"`
501	} `json:"server"`
502	AutoRoute struct {
503		Enabled bool `json:"enabled"`
504	} `json:"auto_route"`
505	NetworkIsolation struct {
506		Enabled bool   `json:"enabled"`
507		Prefix  string `json:"prefix"`
508	} `json:"network_isolation"`
509	Routes         []domain.Route    `json:"routes"`
510	ExternalRoutes map[string]string `json:"external_routes"`
511}
512
513// GetConfig returns the Gordon configuration.
514func (c *Client) GetConfig(ctx context.Context) (*Config, error) {
515	resp, err := c.request(ctx, http.MethodGet, "/config", nil)
516	if err != nil {
517		return nil, err
518	}
519
520	var config Config
521	if err := parseResponse(resp, &config); err != nil {
522		return nil, err
523	}
524
525	return &config, nil
526}
527
528// Ping checks if the remote Gordon instance is reachable.
529func (c *Client) Ping(ctx context.Context) error {
530	_, err := c.GetStatus(ctx)
531	return err
532}
533
534// Deploy API
535
536// DeployResult contains the result of a deployment.
537type DeployResult struct {
538	Status      string `json:"status"`
539	ContainerID string `json:"container_id"`
540	Domain      string `json:"domain"`
541}
542
543// Deploy triggers a deployment for the specified domain.
544func (c *Client) Deploy(ctx context.Context, deployDomain string) (*DeployResult, error) {
545	resp, err := c.requestWithRetry(ctx, http.MethodPost, "/deploy/"+url.PathEscape(deployDomain), nil)
546	if err != nil {
547		return nil, err
548	}
549
550	var result DeployResult
551	if err := parseResponse(resp, &result); err != nil {
552		return nil, err
553	}
554
555	return &result, nil
556}
557
558// Restart API
559
560// RestartResult contains the result of a restart.
561type RestartResult struct {
562	Status string `json:"status"`
563	Domain string `json:"domain"`
564}
565
566// Restart triggers a container restart for the specified domain.
567func (c *Client) Restart(ctx context.Context, restartDomain string, withAttachments bool) (*RestartResult, error) {
568	if restartDomain == "" {
569		return nil, fmt.Errorf("domain cannot be empty")
570	}
571	path := "/restart/" + url.PathEscape(restartDomain)
572	if withAttachments {
573		path += "?attachments=true"
574	}
575	resp, err := c.requestWithRetry(ctx, http.MethodPost, path, nil)
576	if err != nil {
577		return nil, err
578	}
579
580	var result RestartResult
581	if err := parseResponse(resp, &result); err != nil {
582		return nil, err
583	}
584
585	return &result, nil
586}
587
588// Tags API
589
590// ListTags returns available tags for a repository.
591func (c *Client) ListTags(ctx context.Context, repository string) ([]string, error) {
592	if repository == "" {
593		return nil, fmt.Errorf("repository cannot be empty")
594	}
595	resp, err := c.request(ctx, http.MethodGet, "/tags/"+url.PathEscape(repository), nil)
596	if err != nil {
597		return nil, err
598	}
599	var result struct {
600		Repository string   `json:"repository"`
601		Tags       []string `json:"tags"`
602	}
603	if err := parseResponse(resp, &result); err != nil {
604		return nil, err
605	}
606	return result.Tags, nil
607}
608
609// Logs API
610
611// GetProcessLogs returns Gordon process logs.
612func (c *Client) GetProcessLogs(ctx context.Context, lines int) ([]string, error) {
613	path := fmt.Sprintf("/logs?lines=%d", lines)
614	resp, err := c.request(ctx, http.MethodGet, path, nil)
615	if err != nil {
616		return nil, err
617	}
618
619	var result struct {
620		Lines []string `json:"lines"`
621	}
622	if err := parseResponse(resp, &result); err != nil {
623		return nil, err
624	}
625
626	return result.Lines, nil
627}
628
629// GetContainerLogs returns container logs for a specific domain.
630func (c *Client) GetContainerLogs(ctx context.Context, logDomain string, lines int) ([]string, error) {
631	path := fmt.Sprintf("/logs/%s?lines=%d", url.PathEscape(logDomain), lines)
632	resp, err := c.request(ctx, http.MethodGet, path, nil)
633	if err != nil {
634		return nil, err
635	}
636
637	var result struct {
638		Domain string   `json:"domain"`
639		Lines  []string `json:"lines"`
640	}
641	if err := parseResponse(resp, &result); err != nil {
642		return nil, err
643	}
644
645	return result.Lines, nil
646}
647
648// StreamProcessLogs returns a channel that streams Gordon process log lines via SSE.
649// The caller is responsible for reading from the channel until it's closed.
650func (c *Client) StreamProcessLogs(ctx context.Context, lines int) (<-chan string, error) {
651	path := fmt.Sprintf("/logs?lines=%d&follow=true", lines)
652	return c.streamLogs(ctx, path)
653}
654
655// StreamContainerLogs returns a channel that streams container log lines via SSE.
656// The caller is responsible for reading from the channel until it's closed.
657func (c *Client) StreamContainerLogs(ctx context.Context, logDomain string, lines int) (<-chan string, error) {
658	path := fmt.Sprintf("/logs/%s?lines=%d&follow=true", url.PathEscape(logDomain), lines)
659	return c.streamLogs(ctx, path)
660}
661
662// Attachments Config API
663
664// GetAllAttachmentsConfig returns all configured attachments.
665func (c *Client) GetAllAttachmentsConfig(ctx context.Context) (map[string][]string, error) {
666	resp, err := c.request(ctx, http.MethodGet, "/attachments", nil)
667	if err != nil {
668		return nil, err
669	}
670
671	var result struct {
672		Attachments map[string][]string `json:"attachments"`
673	}
674	if err := parseResponse(resp, &result); err != nil {
675		return nil, err
676	}
677
678	return result.Attachments, nil
679}
680
681// GetAttachmentsConfig returns attachments for a specific domain/group from config.
682func (c *Client) GetAttachmentsConfig(ctx context.Context, domainOrGroup string) ([]string, error) {
683	if domainOrGroup == "" {
684		return nil, fmt.Errorf("domain or group is required")
685	}
686	path := "/attachments/" + url.PathEscape(domainOrGroup)
687	resp, err := c.request(ctx, http.MethodGet, path, nil)
688	if err != nil {
689		return nil, err
690	}
691
692	var result struct {
693		Target string   `json:"target"`
694		Images []string `json:"images"`
695	}
696	if err := parseResponse(resp, &result); err != nil {
697		return nil, err
698	}
699
700	return result.Images, nil
701}
702
703// AddAttachment adds an attachment to a domain/group.
704func (c *Client) AddAttachment(ctx context.Context, domainOrGroup, image string) error {
705	if domainOrGroup == "" {
706		return fmt.Errorf("domain or group is required")
707	}
708	if image == "" {
709		return fmt.Errorf("image is required")
710	}
711	path := "/attachments/" + url.PathEscape(domainOrGroup)
712	resp, err := c.request(ctx, http.MethodPost, path, struct {
713		Image string `json:"image"`
714	}{Image: image})
715	if err != nil {
716		return err
717	}
718	return parseResponse(resp, nil)
719}
720
721// RemoveAttachment removes an attachment from a domain/group.
722func (c *Client) RemoveAttachment(ctx context.Context, domainOrGroup, image string) error {
723	if domainOrGroup == "" {
724		return fmt.Errorf("domain or group is required")
725	}
726	if image == "" {
727		return fmt.Errorf("image is required")
728	}
729	path := "/attachments/" + url.PathEscape(domainOrGroup) + "/" + url.PathEscape(image)
730	resp, err := c.request(ctx, http.MethodDelete, path, nil)
731	if err != nil {
732		return err
733	}
734	return parseResponse(resp, nil)
735}
736
737// streamLogs handles SSE streaming for log endpoints.
738func (c *Client) streamLogs(ctx context.Context, path string) (<-chan string, error) {
739	url := c.baseURL + "/admin" + path
740
741	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
742	if err != nil {
743		return nil, fmt.Errorf("failed to create request: %w", err)
744	}
745
746	req.Header.Set("Accept", "text/event-stream")
747	if c.token != "" {
748		req.Header.Set("Authorization", "Bearer "+c.token)
749	}
750
751	// Use the same transport as the main client (honoring TLS config and
752	// custom transports) but without a timeout so streaming doesn't get cut off.
753	streamClient := &http.Client{
754		Transport: c.httpClient.Transport,
755	}
756	resp, err := streamClient.Do(req)
757	if err != nil {
758		return nil, fmt.Errorf("failed to connect: %w", err)
759	}
760
761	if resp.StatusCode >= 400 {
762		body, _ := io.ReadAll(resp.Body)
763		resp.Body.Close()
764		return nil, fmt.Errorf("%s: %s", resp.Status, string(body))
765	}
766
767	ch := make(chan string, 100)
768
769	go func() {
770		defer close(ch)
771		defer resp.Body.Close()
772
773		buf := make([]byte, 4096)
774		var lineBuffer strings.Builder
775
776		for {
777			select {
778			case <-ctx.Done():
779				return
780			default:
781			}
782
783			n, err := resp.Body.Read(buf)
784			if n > 0 {
785				lineBuffer.Write(buf[:n])
786			}
787			if err != nil {
788				return // EOF or context cancellation — clean exit
789			}
790
791			// Process complete SSE events
792			for {
793				data := lineBuffer.String()
794				idx := strings.Index(data, "\n\n")
795				if idx == -1 {
796					break
797				}
798
799				event := data[:idx]
800				lineBuffer.Reset()
801				lineBuffer.WriteString(data[idx+2:])
802
803				// Parse SSE data lines
804				for _, line := range strings.Split(event, "\n") {
805					if strings.HasPrefix(line, "data: ") {
806						logLine := strings.TrimPrefix(line, "data: ")
807						select {
808						case ch <- logLine:
809						case <-ctx.Done():
810							return
811						}
812					}
813				}
814			}
815		}
816	}()
817
818	return ch, nil
819}
820
821// VerifyAuth checks if authentication session is valid.
822func (c *Client) VerifyAuth(ctx context.Context) (*dto.AuthVerifyResponse, error) {
823	resp, err := c.request(ctx, http.MethodGet, "/auth/verify", nil)
824	if err != nil {
825		return nil, err
826	}
827
828	var result dto.AuthVerifyResponse
829	if err := parseResponse(resp, &result); err != nil {
830		return nil, err
831	}
832
833	return &result, nil
834}

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