summaryrefslogtreecommitdiffhomepage
path: root/cmd/cigocacher/http.go
blob: 16d0ae899acbc60a48252c861e6a99668e7fcc07 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause

package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"net/http"
)

type gocachedClient struct {
	baseURL     string       // base URL of the cacher server, like "http://localhost:31364".
	cl          *http.Client // http.Client to use.
	accessToken string       // Bearer token to use in the Authorization header.
	verbose     bool
}

// drainAndClose reads and throws away a small bounded amount of data. This is a
// best-effort attempt to allow connection reuse; Go's HTTP/1 Transport won't
// reuse a TCP connection unless you fully consume HTTP responses.
func drainAndClose(body io.ReadCloser) {
	io.CopyN(io.Discard, body, 4<<10)
	body.Close()
}

func tryReadErrorMessage(res *http.Response) []byte {
	msg, _ := io.ReadAll(io.LimitReader(res.Body, 4<<10))
	return msg
}

func (c *gocachedClient) get(ctx context.Context, actionID string) (outputID string, resp *http.Response, err error) {
	req, _ := http.NewRequestWithContext(ctx, "GET", c.baseURL+"/action/"+actionID, nil)
	req.Header.Set("Want-Object", "1") // opt in to single roundtrip protocol
	if c.accessToken != "" {
		req.Header.Set("Authorization", "Bearer "+c.accessToken)
	}

	res, err := c.cl.Do(req)
	if err != nil {
		return "", nil, err
	}
	defer func() {
		if resp == nil {
			drainAndClose(res.Body)
		}
	}()
	if res.StatusCode == http.StatusNotFound {
		return "", nil, nil
	}
	if res.StatusCode != http.StatusOK {
		msg := tryReadErrorMessage(res)
		if c.verbose {
			log.Printf("error GET /action/%s: %v, %s", actionID, res.Status, msg)
		}
		return "", nil, fmt.Errorf("unexpected GET /action/%s status %v", actionID, res.Status)
	}

	outputID = res.Header.Get("Go-Output-Id")
	if outputID == "" {
		return "", nil, fmt.Errorf("missing Go-Output-Id header in response")
	}
	if res.ContentLength == -1 {
		return "", nil, fmt.Errorf("no Content-Length from server")
	}
	return outputID, res, nil
}

func (c *gocachedClient) put(ctx context.Context, actionID, outputID string, size int64, body io.Reader) error {
	req, _ := http.NewRequestWithContext(ctx, "PUT", c.baseURL+"/"+actionID+"/"+outputID, body)
	req.ContentLength = size
	if c.accessToken != "" {
		req.Header.Set("Authorization", "Bearer "+c.accessToken)
	}
	res, err := c.cl.Do(req)
	if err != nil {
		if c.verbose {
			log.Printf("error PUT /%s/%s: %v", actionID, outputID, err)
		}
		return err
	}
	defer res.Body.Close()
	if res.StatusCode != http.StatusNoContent {
		msg := tryReadErrorMessage(res)
		if c.verbose {
			log.Printf("error PUT /%s/%s: %v, %s", actionID, outputID, res.Status, msg)
		}
		return fmt.Errorf("unexpected PUT /%s/%s status %v", actionID, outputID, res.Status)
	}

	return nil
}

func (c *gocachedClient) fetchStats() (string, error) {
	req, _ := http.NewRequest("GET", c.baseURL+"/session/stats", nil)
	req.Header.Set("Authorization", "Bearer "+c.accessToken)
	resp, err := c.cl.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	b, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	return string(b), nil
}