-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun.go
More file actions
352 lines (302 loc) · 7.79 KB
/
run.go
File metadata and controls
352 lines (302 loc) · 7.79 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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"time"
crdbpgx "github.com/cockroachdb/cockroach-go/v2/crdb/crdbpgxv5"
"github.com/gofrs/uuid/v5"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"golang.org/x/sync/errgroup"
"golang.org/x/time/rate"
)
const (
validCheckTimeout = time.Hour * 24 * 7
validCheckInterval = time.Hour * 24
nameCheckInterval = validCheckInterval
)
type token struct {
AccountId uuid.UUID
Gw2AccountId uuid.UUID
Gw2AccountName string
Gw2ApiToken string
}
type apiRequestError struct {
statusCode int
error
}
func (err apiRequestError) penalize() bool {
return err.statusCode >= 400 && err.statusCode < 500
}
type TokenChecker struct {
pool *pgxpool.Pool
httpClient *http.Client
tracer trace.Tracer
limiter *rate.Limiter
}
func NewTokenChecker(pool *pgxpool.Pool, httpClient *http.Client) *TokenChecker {
tracer := otel.Tracer("github.com/gw2auth/gw2auth.com-background-jobs::TokenChecker", trace.WithInstrumentationVersion("v0.0.1"))
limiter := rate.NewLimiter(rate.Every(time.Minute)*250, 300)
return &TokenChecker{
pool: pool,
httpClient: httpClient,
tracer: tracer,
limiter: limiter,
}
}
func (tc *TokenChecker) Run(ctx context.Context) error {
for {
tokensToCheck, err := tc.loadBatch(ctx, 20)
if err != nil {
return fmt.Errorf("failed to load token batch: %w", err)
}
if len(tokensToCheck) < 1 {
break
}
if err := tc.checkBatch(ctx, tokensToCheck); err != nil {
return fmt.Errorf("failed to check token batch: %w", err)
}
}
return nil
}
func (tc *TokenChecker) loadBatch(ctx context.Context, batchSize int) ([]token, error) {
now := time.Now()
minLastValidTime := now.Add(-validCheckTimeout)
maxValidCheckTime := now.Add(-validCheckInterval)
maxNameCheckTime := now.Add(-nameCheckInterval)
tokensToCheck := make([]token, 0, batchSize)
err := crdbpgx.ExecuteTx(ctx, tc.pool, pgx.TxOptions{AccessMode: pgx.ReadOnly}, func(tx pgx.Tx) error {
rows, err := tx.Query(
ctx,
`
SELECT tk.account_id, tk.gw2_account_id, acc.gw2_account_name, tk.gw2_api_token
FROM gw2_account_api_tokens tk
INNER JOIN gw2_accounts acc
ON tk.account_id = acc.account_id AND tk.gw2_account_id = acc.gw2_account_id
WHERE tk.last_valid_time >= $1
AND (tk.last_valid_check_time <= $2 OR acc.last_name_check_time <= $3)
ORDER BY LEAST(tk.last_valid_check_time, acc.last_name_check_time) ASC
LIMIT $4
`,
minLastValidTime,
maxValidCheckTime,
maxNameCheckTime,
batchSize,
)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
var t token
if err := rows.Scan(&t.AccountId, &t.Gw2AccountId, &t.Gw2AccountName, &t.Gw2ApiToken); err != nil {
return err
}
tokensToCheck = append(tokensToCheck, t)
}
return rows.Err()
})
if err != nil {
return nil, err
}
return tokensToCheck, nil
}
func (tc *TokenChecker) checkBatch(ctx context.Context, tokensToCheck []token) error {
slog.InfoContext(ctx, "checking batch", slog.Int("batch.size", len(tokensToCheck)))
g, ctx := errgroup.WithContext(ctx)
for _, t := range tokensToCheck {
g.Go(func() error {
return tc.checkSingle(ctx, t)
})
}
if err := g.Wait(); err != nil {
return fmt.Errorf("token check failed: %w", err)
}
return nil
}
func (tc *TokenChecker) checkSingle(ctx context.Context, tk token) error {
ctx, span := tc.tracer.Start(
ctx,
"CheckSingle",
trace.WithSpanKind(trace.SpanKindServer),
trace.WithAttributes(
attribute.String("account.id", tk.AccountId.String()),
attribute.String("gw2account.id", tk.Gw2AccountId.String()),
),
)
defer span.End()
if err := tc.checkSingleInternal(ctx, tk); err != nil {
span.RecordError(err)
return err
}
return nil
}
func (tc *TokenChecker) checkSingleInternal(ctx context.Context, tk token) error {
var newGw2AccountName string
var isValid bool
{
var err error
newGw2AccountName, err = tc.getGw2AccountName(ctx, tk.Gw2ApiToken)
if err != nil {
slog.InfoContext(
ctx,
"could not get gw2 account name",
slog.String("account.id", tk.AccountId.String()),
slog.String("gw2account.id", tk.Gw2AccountId.String()),
slog.String("gw2account.name.old", tk.Gw2AccountName),
slog.String("error", err.Error()),
)
} else {
slog.InfoContext(
ctx,
"token check succeeded",
slog.String("account.id", tk.AccountId.String()),
slog.String("gw2account.id", tk.Gw2AccountId.String()),
slog.String("gw2account.name.new", newGw2AccountName),
slog.String("gw2account.name.old", tk.Gw2AccountName),
slog.Bool("gw2account.name.changed", newGw2AccountName != tk.Gw2AccountName),
)
}
if err != nil {
var rErr apiRequestError
if !errors.As(err, &rErr) || rErr.statusCode == http.StatusTooManyRequests {
return err
}
if rErr.penalize() {
isValid = false
} else {
isValid = true
newGw2AccountName = tk.Gw2AccountName
}
} else {
isValid = true
}
}
now := time.Now()
return crdbpgx.ExecuteTx(ctx, tc.pool, pgx.TxOptions{}, func(tx pgx.Tx) error {
var err error
if isValid {
_, err1 := tx.Exec(
ctx,
`
UPDATE gw2_account_api_tokens
SET last_valid_check_time = $1, last_valid_time = $1
WHERE account_id = $2
AND gw2_account_id = $3
`,
now,
tk.AccountId,
tk.Gw2AccountId,
)
_, err2 := tx.Exec(
ctx,
`
UPDATE gw2_accounts
SET
gw2_account_name = $1,
last_name_check_time = $2,
display_name = IF(display_name = gw2_account_name, $1, display_name)
WHERE account_id = $3
AND gw2_account_id = $4
`,
newGw2AccountName,
now,
tk.AccountId,
tk.Gw2AccountId,
)
err = errors.Join(err1, err2)
} else {
_, err1 := tx.Exec(
ctx,
`
UPDATE gw2_account_api_tokens
SET last_valid_check_time = $1
WHERE account_id = $2
AND gw2_account_id = $3
`,
now,
tk.AccountId,
tk.Gw2AccountId,
)
_, err2 := tx.Exec(
ctx,
`
UPDATE gw2_accounts
SET last_name_check_time = $1
WHERE account_id = $2
AND gw2_account_id = $3
`,
now,
tk.AccountId,
tk.Gw2AccountId,
)
err = errors.Join(err1, err2)
}
return err
})
}
func (tc *TokenChecker) getGw2AccountName(ctx context.Context, gw2ApiToken string) (string, error) {
q := make(url.Values)
q.Set("v", "2025-08-29T00:00:00.000Z")
q.Set("access_token", gw2ApiToken)
resp, err := tc.getFromApi(ctx, "https://api.guildwars2.com/v2/account", q)
if err != nil {
return "", apiRequestError{statusCode: 0, error: err}
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
content, _ := io.ReadAll(resp.Body)
err := fmt.Errorf("unexpected status code: %d (body=%q)", resp.StatusCode, string(content))
return "", apiRequestError{statusCode: resp.StatusCode, error: err}
}
var body struct {
Name string `json:"name"`
}
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
return "", apiRequestError{statusCode: resp.StatusCode, error: err}
}
return body.Name, nil
}
func (tc *TokenChecker) getFromApi(ctx context.Context, url string, q url.Values) (*http.Response, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
baseQuery := req.URL.Query()
for k, v := range q {
for _, vv := range v {
baseQuery.Add(k, vv)
}
}
req.URL.RawQuery = baseQuery.Encode()
const maxAttempts = 5
for i := 0; i < maxAttempts; i++ {
if err := tc.limiter.Wait(ctx); err != nil {
return nil, err
}
resp, err := tc.httpClient.Do(req)
if err != nil {
return nil, err
}
switch resp.StatusCode {
case http.StatusOK:
return resp, nil
case http.StatusNotFound, http.StatusGatewayTimeout:
// retry
_ = resp.Body.Close()
default:
// abort
return resp, nil
}
}
return nil, errors.New("max attempts exceeded")
}