/
client.go
238 lines (194 loc) · 5.53 KB
/
client.go
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
// Copyright 2021 FerretDB Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io/fs"
"net/http"
"os"
"path/filepath"
"time"
"github.com/FerretDB/gh"
"github.com/google/go-github/v57/github"
"github.com/rogpeppe/go-internal/lockedfile"
)
// issueStatus represents a known issue status.
type issueStatus string
// Known issue statuses.
const (
issueOpen issueStatus = "open"
issueClosed issueStatus = "closed"
issueNotFound issueStatus = "not found"
)
// issue represents a single cached issue.
type issue struct {
RefreshedAt time.Time `json:"refreshedAt"`
Status issueStatus `json:"status"`
}
// cacheFile stores information regarding rate limiting and the status of issues.
type cacheFile struct {
Issues map[string]issue `json:"issues"`
RateLimitReached bool `json:"rateLimitReached"`
}
// client represent GitHub API client with shared file cache.
type client struct {
c *github.Client
cacheFilePath string
logf gh.Printf
cacheDebugF gh.Printf
clientDebugF gh.Printf
token string
}
// newClient creates a new client for the given cache file path and logging functions.
func newClient(cacheFilePath string, logf, cacheDebugF, clientDebugf gh.Printf) (*client, error) {
token := os.Getenv("GITHUB_TOKEN")
if logf == nil {
panic("logf must be set")
}
if cacheDebugF == nil {
panic("vf must be set")
}
if clientDebugf == nil {
panic("debugf must be set")
}
c, err := gh.NewRESTClient(token, clientDebugf)
if err != nil {
return nil, err
}
return &client{
c: c,
cacheFilePath: cacheFilePath,
token: token,
logf: logf,
cacheDebugF: cacheDebugF,
clientDebugF: clientDebugf,
}, nil
}
// IssueStatus returns issue status.
// It uses cache.
//
// Returned error is something fatal.
// On rate limit, the error is logged once and (issueOpen, nil) is returned.
func (c *client) IssueStatus(ctx context.Context, url, repo string, num int) (issueStatus, error) {
start := time.Now()
cache := &cacheFile{
Issues: make(map[string]issue),
}
cacheRes := "miss"
var res issueStatus
// fast path without any locks
data, err := os.ReadFile(c.cacheFilePath)
if err == nil {
_ = json.Unmarshal(data, cache)
res = cache.Issues[url].Status
}
if res != "" {
cacheRes = "fast hit"
} else {
// slow path
noUpdate := fmt.Errorf("no need to update the cache file")
err = lockedfile.Transform(c.cacheFilePath, func(data []byte) ([]byte, error) {
cache.Issues = make(map[string]issue)
if len(data) != 0 {
if err = json.Unmarshal(data, cache); err != nil {
return nil, err
}
}
if res = cache.Issues[url].Status; res != "" {
return nil, noUpdate
}
if res, err = c.checkIssueStatus(ctx, repo, num); err != nil {
var rle *github.RateLimitError
if !errors.As(err, &rle) {
return nil, fmt.Errorf("%s: %s", url, err)
}
if cache.RateLimitReached {
c.clientDebugF("Rate limit already reached: %s", url)
return nil, noUpdate
}
cache.RateLimitReached = true
msg := "Rate limit reached: " + err.Error()
if c.token == "" {
msg += "\nPlease set a GITHUB_TOKEN as described at " +
"https://github.com/FerretDB/FerretDB/blob/main/CONTRIBUTING.md#setting-a-github_token"
}
c.logf("%s", msg)
}
// unless rate limited
if res != "" {
cache.Issues[url] = issue{
RefreshedAt: time.Now(),
Status: res,
}
}
return json.MarshalIndent(cache, "", " ")
})
if errors.Is(err, noUpdate) {
cacheRes = "slow hit"
err = nil
}
}
c.cacheDebugF("%s: %s (%dms, %s)", url, res, time.Since(start).Milliseconds(), cacheRes)
// when rate limited
if err == nil && res == "" {
res = issueOpen
}
return res, err
}
// checkIssueStatus checks issue status via GitHub API.
// It does not use cache.
func (c *client) checkIssueStatus(ctx context.Context, repo string, num int) (issueStatus, error) {
issue, resp, err := c.c.Issues.Get(ctx, "FerretDB", repo, num)
if err != nil {
if resp.StatusCode == http.StatusNotFound {
return issueNotFound, nil
}
return "", err
}
switch s := issue.GetState(); s {
case "open":
return issueOpen, nil
case "closed":
return issueClosed, nil
default:
return "", fmt.Errorf("unknown issue state: %q", s)
}
}
// cacheFilePath returns the path to the cache file.
func cacheFilePath() (string, error) {
// This tool is called for multiple packages in parallel,
// with the current working directory set to the package directory.
// To use the same cache file path, we first locate the root of the project by the .git directory.
dir, err := filepath.Abs(".")
if err != nil {
return "", err
}
for {
fi, err := os.Stat(filepath.Join(dir, ".git"))
if err == nil {
if !fi.IsDir() {
return "", fmt.Errorf(".git is not a directory")
}
break
}
if !errors.Is(err, fs.ErrNotExist) {
return "", err
}
dir = filepath.Dir(dir)
}
return filepath.Join(dir, "tmp", "checkcomments", "cache.json"), nil
}