Files
gitea-tea/internal/transport/api.go
T
bircni 2b218a5bae refactor: add settings, transport and alias packages (#1122)
Part 1/5 of the tea 1.0 rewrite.

**Stack** (split from #1121; each PR targets `main` and builds, tests and lints on its own — the shipped CLI only changes in part 5):

1. #1122 Toolchain and foundation packages ← this PR
2. #1123 Credentials and Git
3. #1124 Terminal
4. #1125 Services
5. #1126 CLI wiring, docs, removal of the old tree

## Changes

- **build:** require Go 1.27; bump gofumpt and golangci-lint to releases that can read Go 1.27 export data (own commit).
- `internal/clierr`: typed errors and executable exit codes.
- `internal/version`: build version and tags.
- `internal/filelock`: moved unchanged from `modules/filelock`.
- `internal/aliases`: user-defined command aliases.
- `internal/transport`: the HTTP client the Gitea SDK runs on (part 4): token, Sudo and SSH-signature auth, retries for safe reads, connect/TLS/response-header timeouts, typed API errors that keep Gitea's message, and a redacted request log for `--debug`; plus raw requests for `tea api`, signed downloads that follow object-storage redirects, and log streaming.
- `internal/settings`: split `config.yml` / `hosts.yml` with locked transactions, plus remote URL parsing.

Nothing imports these packages yet.

Note: `flake.nix` now asks for `go_1_27`; the pinned nixpkgs in `flake.lock` predates Go 1.27 and still needs a `nix flake update nixpkgs`.
Reviewed-on: https://gitea.com/gitea/tea/pulls/1122
Reviewed-by: TheFox0x7 <95654+thefox0x7@noreply.gitea.com>
2026-10-11 17:06:38 +00:00

141 lines
4.1 KiB
Go

// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package transport
import (
"bytes"
"context"
"errors"
"io"
"net/http"
"sync/atomic"
"time"
)
// API returns an HTTP client for requests to this instance. It attaches the credential and Sudo
// header to every attempt, retries only body-free reads, never follows redirects, and records
// the sanitized error of a failed response for CaptureErrors.
func (c *Client) API() *http.Client {
base := c.HTTP.Transport
if base == nil {
base = http.DefaultTransport
}
chain := captureTransport{
base: retryTransport{base: authTransport{base: base, token: c.Token, sudo: c.Sudo, signer: c.Signer}, retries: c.Retries},
token: c.Token,
}
return &http.Client{
Transport: chain,
CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse },
Jar: c.HTTP.Jar,
Timeout: c.HTTP.Timeout,
}
}
type capturedErrorKey struct{}
// CaptureErrors returns a context under which API clients record the sanitized error of each
// response outside 2xx, and a function returning the last one recorded.
func CaptureErrors(ctx context.Context) (context.Context, func() *APIError) {
holder := new(atomic.Pointer[APIError])
return context.WithValue(ctx, capturedErrorKey{}, holder), holder.Load
}
type captureTransport struct {
base http.RoundTripper
token string
}
func (t captureTransport) RoundTrip(req *http.Request) (*http.Response, error) {
resp, err := t.base.RoundTrip(req)
holder, _ := req.Context().Value(capturedErrorKey{}).(*atomic.Pointer[APIError])
if err != nil || holder == nil || (resp.StatusCode >= 200 && resp.StatusCode < 300) {
return resp, err
}
data, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBody))
holder.Store(newAPIError(resp.StatusCode, req.Method, req.URL.Path, t.token, data))
resp.Body = struct {
io.Reader
io.Closer
}{io.MultiReader(bytes.NewReader(data), resp.Body), resp.Body}
return resp, nil
}
type retryTransport struct {
base http.RoundTripper
retries int
}
func (t retryTransport) RoundTrip(req *http.Request) (*http.Response, error) {
safe := (req.Method == http.MethodGet || req.Method == http.MethodHead) && (req.Body == nil || req.Body == http.NoBody)
for attempt := 0; ; attempt++ {
resp, err := t.base.RoundTrip(req)
if !safe || attempt >= t.retries || (err == nil && resp.StatusCode != http.StatusBadGateway && resp.StatusCode != http.StatusServiceUnavailable && resp.StatusCode != http.StatusGatewayTimeout) {
return resp, err
}
if resp != nil {
_ = resp.Body.Close()
}
timer := time.NewTimer(time.Duration(1<<attempt) * 100 * time.Millisecond)
select {
case <-req.Context().Done():
timer.Stop()
return nil, req.Context().Err()
case <-timer.C:
}
}
}
type authTransport struct {
base http.RoundTripper
token, sudo string
signer RequestSigner
}
func (t authTransport) RoundTrip(req *http.Request) (*http.Response, error) {
signed := req.Clone(req.Context())
if t.sudo != "" {
signed.Header.Set("Sudo", t.sudo)
}
if t.token != "" {
signed.Header.Set("Authorization", "token "+t.token)
} else if t.signer != nil {
body, err := signingBody(signed)
if err == nil {
err = t.signer.SignRequest(signed, body)
}
if err != nil {
if req.Body != nil {
_ = req.Body.Close()
}
return nil, err
}
}
return t.base.RoundTrip(signed)
}
// signingBody returns the request body to sign, buffering a body that cannot be replayed.
func signingBody(req *http.Request) ([]byte, error) {
if req.Body == nil || req.Body == http.NoBody {
return nil, nil
}
body := req.Body
if req.GetBody != nil {
var err error
if body, err = req.GetBody(); err != nil {
return nil, errors.New("cannot read API request body for signing")
}
}
data, err := io.ReadAll(body)
_ = body.Close()
if err != nil {
return nil, errors.New("cannot read API request body for signing")
}
if req.GetBody == nil {
req.Body = io.NopCloser(bytes.NewReader(data))
req.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(data)), nil }
}
return data, nil
}