-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalgorithmvisualizer.go
More file actions
255 lines (233 loc) · 5.9 KB
/
Copy pathalgorithmvisualizer.go
File metadata and controls
255 lines (233 loc) · 5.9 KB
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
// Package algorithmvisualizer is the library behind the algvis command line:
// the HTTP client, request shaping, and the typed data models for Algorithm Visualizer.
//
// The Client here is the spine every command shares. It sets a real
// User-Agent, paces requests so a busy session stays polite, and retries the
// transient failures (429 and 5xx) that any public API throws under load.
package algorithmvisualizer
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"sync"
"time"
)
const DefaultUserAgent = "algvis/dev (+https://github.com/tamnd/algorithmvisualizer-cli)"
// Config holds constructor parameters.
type Config struct {
BaseURL string
UserAgent string
Rate time.Duration
Retries int
Timeout time.Duration
}
// DefaultConfig returns sensible defaults.
func DefaultConfig() Config {
return Config{
BaseURL: "https://api.github.com",
UserAgent: DefaultUserAgent,
Rate: 500 * time.Millisecond,
Retries: 3,
Timeout: 30 * time.Second,
}
}
// Algorithm is a single algorithm entry.
type Algorithm struct {
Rank int `json:"rank"`
Category string `json:"category"`
Name string `json:"name"`
URL string `json:"url"`
}
// Category is a group of algorithms.
type Category struct {
Rank int `json:"rank"`
Name string `json:"name"`
Count int `json:"count"`
}
// treeResponse is the GitHub Git Trees API response shape.
type treeResponse struct {
Tree []struct {
Path string `json:"path"`
Type string `json:"type"`
} `json:"tree"`
}
// Client talks to the GitHub API for Algorithm Visualizer data.
type Client struct {
cfg Config
httpClient *http.Client
mu sync.Mutex
last time.Time
}
// NewClient returns a Client with the given config.
func NewClient(cfg Config) *Client {
return &Client{
cfg: cfg,
httpClient: &http.Client{Timeout: cfg.Timeout},
}
}
func (c *Client) get(ctx context.Context, rawURL string) ([]byte, error) {
var lastErr error
for attempt := 0; attempt <= c.cfg.Retries; attempt++ {
if attempt > 0 {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(backoff(attempt)):
}
}
body, retry, err := c.do(ctx, rawURL)
if err == nil {
return body, nil
}
lastErr = err
if !retry {
return nil, err
}
}
return nil, fmt.Errorf("get %s: %w", rawURL, lastErr)
}
func (c *Client) do(ctx context.Context, rawURL string) (body []byte, retry bool, err error) {
c.pace()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
if err != nil {
return nil, false, err
}
req.Header.Set("User-Agent", c.cfg.UserAgent)
req.Header.Set("Accept", "application/vnd.github+json")
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, true, err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500 {
return nil, true, fmt.Errorf("http %d", resp.StatusCode)
}
if resp.StatusCode != http.StatusOK {
return nil, false, fmt.Errorf("http %d", resp.StatusCode)
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, true, err
}
return b, false, nil
}
func (c *Client) pace() {
c.mu.Lock()
defer c.mu.Unlock()
if c.cfg.Rate <= 0 {
return
}
if wait := c.cfg.Rate - time.Since(c.last); wait > 0 {
time.Sleep(wait)
}
c.last = time.Now()
}
func backoff(attempt int) time.Duration {
d := time.Duration(attempt) * 500 * time.Millisecond
if d > 5*time.Second {
d = 5 * time.Second
}
return d
}
// fetchTree fetches the algorithm tree from GitHub and returns all algorithms.
func (c *Client) fetchTree(ctx context.Context) ([]Algorithm, error) {
raw, err := c.get(ctx, c.cfg.BaseURL+"/repos/algorithm-visualizer/algorithms/git/trees/master?recursive=1")
if err != nil {
return nil, err
}
var resp treeResponse
if err := json.Unmarshal(raw, &resp); err != nil {
return nil, err
}
var out []Algorithm
rank := 0
for _, item := range resp.Tree {
if item.Type != "tree" {
continue
}
parts := strings.SplitN(item.Path, "/", 2)
if len(parts) != 2 {
continue
}
cat, name := parts[0], parts[1]
if strings.HasPrefix(cat, ".") {
continue
}
if strings.Contains(name, "/") {
continue
}
rank++
out = append(out, Algorithm{
Rank: rank,
Category: cat,
Name: name,
URL: "https://github.com/algorithm-visualizer/algorithms/tree/master/" + item.Path,
})
}
return out, nil
}
// List returns algorithms, optionally filtered by category, up to limit.
func (c *Client) List(ctx context.Context, category string, limit int) ([]Algorithm, error) {
all, err := c.fetchTree(ctx)
if err != nil {
return nil, err
}
var out []Algorithm
rank := 0
for _, a := range all {
if category != "" && !strings.EqualFold(a.Category, category) {
continue
}
rank++
a.Rank = rank
out = append(out, a)
if limit > 0 && len(out) >= limit {
break
}
}
return out, nil
}
// Search finds algorithms matching query in name or category.
func (c *Client) Search(ctx context.Context, query string, limit int) ([]Algorithm, error) {
all, err := c.fetchTree(ctx)
if err != nil {
return nil, err
}
q := strings.ToLower(query)
var out []Algorithm
rank := 0
for _, a := range all {
if strings.Contains(strings.ToLower(a.Name), q) || strings.Contains(strings.ToLower(a.Category), q) {
rank++
a.Rank = rank
out = append(out, a)
if limit > 0 && len(out) >= limit {
break
}
}
}
return out, nil
}
// Categories returns all categories with algorithm counts.
func (c *Client) Categories(ctx context.Context) ([]Category, error) {
all, err := c.fetchTree(ctx)
if err != nil {
return nil, err
}
counts := make(map[string]int)
order := []string{}
for _, a := range all {
if _, ok := counts[a.Category]; !ok {
order = append(order, a.Category)
}
counts[a.Category]++
}
var out []Category
for i, cat := range order {
out = append(out, Category{Rank: i + 1, Name: cat, Count: counts[cat]})
}
return out, nil
}