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// Backups API
467
468// ListBackups returns backups globally or for a domain.
469func (c *Client) ListBackups(ctx context.Context, backupDomain string) ([]dto.BackupJob, error) {
470 path := "/backups"
471 if backupDomain != "" {
472 path += "/" + url.PathEscape(backupDomain)
473 }
474
475 resp, err := c.request(ctx, http.MethodGet, path, nil)
476 if err != nil {
477 return nil, err
478 }
479
480 var result dto.BackupsResponse
481 if err := parseResponse(resp, &result); err != nil {
482 return nil, err
483 }
484
485 return result.Backups, nil
486}
487
488// BackupStatus returns aggregate backup status.
489func (c *Client) BackupStatus(ctx context.Context) ([]dto.BackupJob, error) {
490 resp, err := c.request(ctx, http.MethodGet, "/backups/status", nil)
491 if err != nil {
492 return nil, err
493 }
494
495 var result dto.BackupsResponse
496 if err := parseResponse(resp, &result); err != nil {
497 return nil, err
498 }
499
500 return result.Backups, nil
501}
502
503// RunBackup triggers a backup for a domain.
504func (c *Client) RunBackup(ctx context.Context, backupDomain, dbName string) (*dto.BackupRunResponse, error) {
505 if backupDomain == "" {
506 return nil, fmt.Errorf("domain cannot be empty")
507 }
508
509 resp, err := c.request(ctx, http.MethodPost, "/backups/"+url.PathEscape(backupDomain), dto.BackupRunRequest{DB: dbName})
510 if err != nil {
511 return nil, err
512 }
513
514 var result dto.BackupRunResponse
515 if err := parseResponse(resp, &result); err != nil {
516 return nil, err
517 }
518
519 return &result, nil
520}
521
522// DetectDatabases detects supported databases for a domain.
523func (c *Client) DetectDatabases(ctx context.Context, backupDomain string) ([]dto.DatabaseInfo, error) {
524 if backupDomain == "" {
525 return nil, fmt.Errorf("domain cannot be empty")
526 }
527
528 resp, err := c.request(ctx, http.MethodGet, "/backups/"+url.PathEscape(backupDomain)+"/detect", nil)
529 if err != nil {
530 return nil, err
531 }
532
533 var result dto.BackupDetectResponse
534 if err := parseResponse(resp, &result); err != nil {
535 return nil, err
536 }
537
538 return result.Databases, nil
539}
540
541// GetHealth returns health status for all routes with HTTP probing.
542func (c *Client) GetHealth(ctx context.Context) (map[string]*RouteHealth, error) {
543 resp, err := c.request(ctx, http.MethodGet, "/health", nil)
544 if err != nil {
545 return nil, err
546 }
547
548 var result struct {
549 Health map[string]*RouteHealth `json:"health"`
550 }
551 if err := parseResponse(resp, &result); err != nil {
552 return nil, err
553 }
554
555 return result.Health, nil
556}
557
558// Reload triggers a configuration reload.
559func (c *Client) Reload(ctx context.Context) error {
560 resp, err := c.requestWithRetry(ctx, http.MethodPost, "/reload", nil)
561 if err != nil {
562 return err
563 }
564 return parseResponse(resp, nil)
565}
566
567// Config API
568
569// Config represents the Gordon configuration.
570type Config struct {
571 Server struct {
572 Port int `json:"port"`
573 RegistryPort int `json:"registry_port"`
574 RegistryDomain string `json:"registry_domain"`
575 DataDir string `json:"data_dir"`
576 } `json:"server"`
577 AutoRoute struct {
578 Enabled bool `json:"enabled"`
579 } `json:"auto_route"`
580 NetworkIsolation struct {
581 Enabled bool `json:"enabled"`
582 Prefix string `json:"prefix"`
583 } `json:"network_isolation"`
584 Routes []domain.Route `json:"routes"`
585 ExternalRoutes map[string]string `json:"external_routes"`
586}
587
588// GetConfig returns the Gordon configuration.
589func (c *Client) GetConfig(ctx context.Context) (*Config, error) {
590 resp, err := c.request(ctx, http.MethodGet, "/config", nil)
591 if err != nil {
592 return nil, err
593 }
594
595 var config Config
596 if err := parseResponse(resp, &config); err != nil {
597 return nil, err
598 }
599
600 return &config, nil
601}
602
603// Ping checks if the remote Gordon instance is reachable.
604func (c *Client) Ping(ctx context.Context) error {
605 _, err := c.GetStatus(ctx)
606 return err
607}
608
609// Deploy API
610
611// DeployResult contains the result of a deployment.
612type DeployResult struct {
613 Status string `json:"status"`
614 ContainerID string `json:"container_id"`
615 Domain string `json:"domain"`
616}
617
618// Deploy triggers a deployment for the specified domain.
619func (c *Client) Deploy(ctx context.Context, deployDomain string) (*DeployResult, error) {
620 resp, err := c.requestWithRetry(ctx, http.MethodPost, "/deploy/"+url.PathEscape(deployDomain), nil)
621 if err != nil {
622 return nil, err
623 }
624
625 var result DeployResult
626 if err := parseResponse(resp, &result); err != nil {
627 return nil, err
628 }
629
630 return &result, nil
631}
632
633// Restart API
634
635// RestartResult contains the result of a restart.
636type RestartResult struct {
637 Status string `json:"status"`
638 Domain string `json:"domain"`
639}
640
641// Restart triggers a container restart for the specified domain.
642func (c *Client) Restart(ctx context.Context, restartDomain string, withAttachments bool) (*RestartResult, error) {
643 if restartDomain == "" {
644 return nil, fmt.Errorf("domain cannot be empty")
645 }
646 path := "/restart/" + url.PathEscape(restartDomain)
647 if withAttachments {
648 path += "?attachments=true"
649 }
650 resp, err := c.requestWithRetry(ctx, http.MethodPost, path, nil)
651 if err != nil {
652 return nil, err
653 }
654
655 var result RestartResult
656 if err := parseResponse(resp, &result); err != nil {
657 return nil, err
658 }
659
660 return &result, nil
661}
662
663// Tags API
664
665// ListTags returns available tags for a repository.
666func (c *Client) ListTags(ctx context.Context, repository string) ([]string, error) {
667 if repository == "" {
668 return nil, fmt.Errorf("repository cannot be empty")
669 }
670 resp, err := c.request(ctx, http.MethodGet, "/tags/"+url.PathEscape(repository), nil)
671 if err != nil {
672 return nil, err
673 }
674 var result struct {
675 Repository string `json:"repository"`
676 Tags []string `json:"tags"`
677 }
678 if err := parseResponse(resp, &result); err != nil {
679 return nil, err
680 }
681 return result.Tags, nil
682}
683
684// Logs API
685
686// GetProcessLogs returns Gordon process logs.
687func (c *Client) GetProcessLogs(ctx context.Context, lines int) ([]string, error) {
688 path := fmt.Sprintf("/logs?lines=%d", lines)
689 resp, err := c.request(ctx, http.MethodGet, path, nil)
690 if err != nil {
691 return nil, err
692 }
693
694 var result struct {
695 Lines []string `json:"lines"`
696 }
697 if err := parseResponse(resp, &result); err != nil {
698 return nil, err
699 }
700
701 return result.Lines, nil
702}
703
704// GetContainerLogs returns container logs for a specific domain.
705func (c *Client) GetContainerLogs(ctx context.Context, logDomain string, lines int) ([]string, error) {
706 path := fmt.Sprintf("/logs/%s?lines=%d", url.PathEscape(logDomain), lines)
707 resp, err := c.request(ctx, http.MethodGet, path, nil)
708 if err != nil {
709 return nil, err
710 }
711
712 var result struct {
713 Domain string `json:"domain"`
714 Lines []string `json:"lines"`
715 }
716 if err := parseResponse(resp, &result); err != nil {
717 return nil, err
718 }
719
720 return result.Lines, nil
721}
722
723// StreamProcessLogs returns a channel that streams Gordon process log lines via SSE.
724// The caller is responsible for reading from the channel until it's closed.
725func (c *Client) StreamProcessLogs(ctx context.Context, lines int) (<-chan string, error) {
726 path := fmt.Sprintf("/logs?lines=%d&follow=true", lines)
727 return c.streamLogs(ctx, path)
728}
729
730// StreamContainerLogs returns a channel that streams container log lines via SSE.
731// The caller is responsible for reading from the channel until it's closed.
732func (c *Client) StreamContainerLogs(ctx context.Context, logDomain string, lines int) (<-chan string, error) {
733 path := fmt.Sprintf("/logs/%s?lines=%d&follow=true", url.PathEscape(logDomain), lines)
734 return c.streamLogs(ctx, path)
735}
736
737// Attachments Config API
738
739// GetAllAttachmentsConfig returns all configured attachments.
740func (c *Client) GetAllAttachmentsConfig(ctx context.Context) (map[string][]string, error) {
741 resp, err := c.request(ctx, http.MethodGet, "/attachments", nil)
742 if err != nil {
743 return nil, err
744 }
745
746 var result struct {
747 Attachments map[string][]string `json:"attachments"`
748 }
749 if err := parseResponse(resp, &result); err != nil {
750 return nil, err
751 }
752
753 return result.Attachments, nil
754}
755
756// GetAttachmentsConfig returns attachments for a specific domain/group from config.
757func (c *Client) GetAttachmentsConfig(ctx context.Context, domainOrGroup string) ([]string, error) {
758 if domainOrGroup == "" {
759 return nil, fmt.Errorf("domain or group is required")
760 }
761 path := "/attachments/" + url.PathEscape(domainOrGroup)
762 resp, err := c.request(ctx, http.MethodGet, path, nil)
763 if err != nil {
764 return nil, err
765 }
766
767 var result struct {
768 Target string `json:"target"`
769 Images []string `json:"images"`
770 }
771 if err := parseResponse(resp, &result); err != nil {
772 return nil, err
773 }
774
775 return result.Images, nil
776}
777
778// AddAttachment adds an attachment to a domain/group.
779func (c *Client) AddAttachment(ctx context.Context, domainOrGroup, image string) error {
780 if domainOrGroup == "" {
781 return fmt.Errorf("domain or group is required")
782 }
783 if image == "" {
784 return fmt.Errorf("image is required")
785 }
786 path := "/attachments/" + url.PathEscape(domainOrGroup)
787 resp, err := c.request(ctx, http.MethodPost, path, struct {
788 Image string `json:"image"`
789 }{Image: image})
790 if err != nil {
791 return err
792 }
793 return parseResponse(resp, nil)
794}
795
796// RemoveAttachment removes an attachment from a domain/group.
797func (c *Client) RemoveAttachment(ctx context.Context, domainOrGroup, image string) error {
798 if domainOrGroup == "" {
799 return fmt.Errorf("domain or group is required")
800 }
801 if image == "" {
802 return fmt.Errorf("image is required")
803 }
804 path := "/attachments/" + url.PathEscape(domainOrGroup) + "/" + url.PathEscape(image)
805 resp, err := c.request(ctx, http.MethodDelete, path, nil)
806 if err != nil {
807 return err
808 }
809 return parseResponse(resp, nil)
810}
811
812// streamLogs handles SSE streaming for log endpoints.
813func (c *Client) streamLogs(ctx context.Context, path string) (<-chan string, error) {
814 url := c.baseURL + "/admin" + path
815
816 req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
817 if err != nil {
818 return nil, fmt.Errorf("failed to create request: %w", err)
819 }
820
821 req.Header.Set("Accept", "text/event-stream")
822 if c.token != "" {
823 req.Header.Set("Authorization", "Bearer "+c.token)
824 }
825
826 // Use the same transport as the main client (honoring TLS config and
827 // custom transports) but without a timeout so streaming doesn't get cut off.
828 streamClient := &http.Client{
829 Transport: c.httpClient.Transport,
830 }
831 resp, err := streamClient.Do(req)
832 if err != nil {
833 return nil, fmt.Errorf("failed to connect: %w", err)
834 }
835
836 if resp.StatusCode >= 400 {
837 body, _ := io.ReadAll(resp.Body)
838 resp.Body.Close()
839 return nil, fmt.Errorf("%s: %s", resp.Status, string(body))
840 }
841
842 ch := make(chan string, 100)
843
844 go func() {
845 defer close(ch)
846 defer resp.Body.Close()
847
848 buf := make([]byte, 4096)
849 var lineBuffer strings.Builder
850
851 for {
852 select {
853 case <-ctx.Done():
854 return
855 default:
856 }
857
858 n, err := resp.Body.Read(buf)
859 if n > 0 {
860 lineBuffer.Write(buf[:n])
861 }
862 if err != nil {
863 return // EOF or context cancellation — clean exit
864 }
865
866 // Process complete SSE events
867 for {
868 data := lineBuffer.String()
869 idx := strings.Index(data, "\n\n")
870 if idx == -1 {
871 break
872 }
873
874 event := data[:idx]
875 lineBuffer.Reset()
876 lineBuffer.WriteString(data[idx+2:])
877
878 // Parse SSE data lines
879 for _, line := range strings.Split(event, "\n") {
880 if strings.HasPrefix(line, "data: ") {
881 logLine := strings.TrimPrefix(line, "data: ")
882 select {
883 case ch <- logLine:
884 case <-ctx.Done():
885 return
886 }
887 }
888 }
889 }
890 }
891 }()
892
893 return ch, nil
894}
895
896// VerifyAuth checks if authentication session is valid.
897func (c *Client) VerifyAuth(ctx context.Context) (*dto.AuthVerifyResponse, error) {
898 resp, err := c.request(ctx, http.MethodGet, "/auth/verify", nil)
899 if err != nil {
900 return nil, err
901 }
902
903 var result dto.AuthVerifyResponse
904 if err := parseResponse(resp, &result); err != nil {
905 return nil, err
906 }
907
908 return &result, nil
909}