Repository navigation
Expand file tree
/
Copy pathclient.go
More file actions
524 lines (470 loc) · 15.9 KB
/
Copy pathclient.go
File metadata and controls
524 lines (470 loc) · 15.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
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
// Package seatlayer is the official Go server SDK for the SeatLayer
// reserved-seating ticketing API: seating charts, seat maps, events, sales
// channels, seat holds, seat booking, and live inventory.
//
// This is the trusted side of a reserved-seating integration. The buyer
// surface selects and holds seats; this package inspects the hold, prices it
// from server data, and books it with a stable booking reference.
//
// SeatLayer is interactive seating chart software built for stadium scale.
// Platforms embed the white-label seat picker with their own checkout;
// organizers sell seated events on their own website with their own payment
// gateway.
//
// Server-side only: this package authenticates with your secret key. Never
// embed it in anything a ticket buyer can reach. Browser surfaces get
// short-lived, origin-bound tokens that you mint with Sessions.
//
// Start here:
//
// - Quickstart: https://docs.seatlayer.io/start/quickstart/
//
// - Holds and checkout: https://docs.seatlayer.io/buyer-sdk/holds-and-checkout/
//
// - API reference: https://docs.seatlayer.io/openapi.json
//
// A minimal server-side hold:
//
// client, err := seatlayer.New(os.Getenv("SEATLAYER_SECRET_KEY"))
// if err != nil {
// return err
// }
// held, err := client.Inventory.HoldBestAvailable(ctx, "summer-gala",
// seatlayer.BestAvailableParams{Qty: 4})
package seatlayer
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"math/rand"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"time"
)
const (
// DefaultBaseURL is the public API.
DefaultBaseURL = "https://api.seatlayer.io"
// DefaultMaxRetries counts total attempts, not extra ones.
DefaultMaxRetries = 3
// DefaultTimeout applies per attempt.
DefaultTimeout = 30 * time.Second
userAgent = "seatlayer-go"
)
// idempotencyKeyPattern is the API's own charset for Idempotency-Key.
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
// Client talks to the SeatLayer server API.
//
// It is safe for concurrent use: the underlying http.Client is, and Client
// holds no mutable state of its own.
type Client struct {
Charts *ChartsService
Channels *ChannelsService
Events *EventsService
EventSeries *EventSeriesService
Holders *HoldersService
Inventory *InventoryService
Orders *OrdersService
PerformanceGroups *PerformanceGroupsService
Seasons *SeasonsService
Sessions *SessionsService
Templates *TemplatesService
Webhooks *WebhooksService
Workspaces *WorkspacesService
secretKey string
baseURL string
maxRetries int
mode string
httpClient *http.Client
}
type rawRequestBody struct {
data []byte
contentType string
}
// Option configures a Client.
type Option func(*Client)
// WithBaseURL points the client at a different API host.
func WithBaseURL(baseURL string) Option {
return func(c *Client) { c.baseURL = strings.TrimRight(baseURL, "/") }
}
// WithMaxRetries sets total attempts for retryable failures.
func WithMaxRetries(attempts int) Option {
return func(c *Client) { c.maxRetries = attempts }
}
// WithHTTPClient supplies your own http.Client — for a custom transport, a
// proxy, or a test server. Its Timeout applies per attempt.
func WithHTTPClient(httpClient *http.Client) Option {
return func(c *Client) { c.httpClient = httpClient }
}
// New builds a Client from a secret key.
//
// It returns an error rather than panicking on a bad key, so a misconfigured
// deployment fails at startup with a message that names the problem.
func New(secretKey string, options ...Option) (*Client, error) {
if secretKey == "" {
return nil, errors.New("seatlayer: a secret key is required")
}
// Caught here rather than as a 401 three round-trips later. The pk_ case
// gets its own message: it is the one people paste by mistake.
if strings.HasPrefix(secretKey, "pk_") {
return nil, errors.New(
"seatlayer: that is a publishable key; the server SDK needs a secret key (sk_live_… or sk_test_…)")
}
if !strings.HasPrefix(secretKey, "sk_") {
return nil, errors.New("seatlayer: a secret key starts with sk_live_ or sk_test_")
}
client := &Client{
secretKey: secretKey,
baseURL: DefaultBaseURL,
maxRetries: DefaultMaxRetries,
httpClient: &http.Client{Timeout: DefaultTimeout},
}
switch {
case strings.HasPrefix(secretKey, "sk_test_"):
client.mode = "test"
case strings.HasPrefix(secretKey, "sk_live_"):
client.mode = "live"
default:
client.mode = "unknown"
}
for _, option := range options {
option(client)
}
client.Charts = &ChartsService{client: client}
client.Channels = &ChannelsService{client: client}
client.Events = &EventsService{client: client}
client.EventSeries = &EventSeriesService{client: client}
client.Holders = &HoldersService{client: client}
client.Inventory = &InventoryService{client: client}
client.Orders = &OrdersService{client: client}
client.PerformanceGroups = &PerformanceGroupsService{client: client}
client.Seasons = &SeasonsService{client: client}
client.Sessions = &SessionsService{client: client}
client.Templates = &TemplatesService{client: client}
client.Webhooks = &WebhooksService{client: client}
client.Workspaces = &WorkspacesService{client: client}
return client, nil
}
// Mode reports "live" or "test", derived from the key prefix.
func (c *Client) Mode() string { return c.mode }
// Ready runs the dependency-aware readiness probe.
func (c *Client) Ready(ctx context.Context) (map[string]any, error) {
return c.Do(ctx, http.MethodGet, "/health/ready", nil, nil, "")
}
// Do is the escape hatch for surface this SDK does not wrap yet. Reads retain
// retries; raw mutations are single-attempt because their replay contract is
// unknown.
func (c *Client) Do(
ctx context.Context,
method, path string,
query url.Values,
body any,
idempotencyKey string,
) (map[string]any, error) {
return c.do(ctx, method, path, query, body, idempotencyKey, false)
}
// do keeps mutation retry policy out of the raw escape hatch. Only resource
// methods backed by the API's exact response replay opt in to headerReplay.
func (c *Client) do(
ctx context.Context,
method, path string,
query url.Values,
body any,
idempotencyKey string,
headerReplay bool,
) (map[string]any, error) {
responseBody, status, err := c.send(
ctx, method, path, query, body, idempotencyKey, headerReplay, "application/json")
if err != nil {
return nil, err
}
if status == http.StatusNoContent || len(responseBody) == 0 {
return map[string]any{}, nil
}
var decoded map[string]any
if err := json.Unmarshal(responseBody, &decoded); err != nil {
return nil, fmt.Errorf("seatlayer: decoding response: %w", err)
}
return decoded, nil
}
// getText reads a route that answers with text rather than JSON, such as a
// CSV export, and returns the body unchanged. Errors still arrive as JSON and
// map to the usual error types.
func (c *Client) getText(
ctx context.Context, path string, query url.Values, accept string,
) (string, error) {
responseBody, _, err := c.send(ctx, http.MethodGet, path, query, nil, "", false, accept)
if err != nil {
return "", err
}
return string(responseBody), nil
}
// send runs one logical request with its retry policy and returns the raw
// success body and status. Callers decide how to read the body.
func (c *Client) send(
ctx context.Context,
method, path string,
query url.Values,
body any,
idempotencyKey string,
headerReplay bool,
accept string,
) ([]byte, int, error) {
endpoint := c.baseURL + path
if len(query) > 0 {
endpoint += "?" + query.Encode()
}
var payload []byte
contentType := "application/json"
if body != nil {
if raw, ok := body.(rawRequestBody); ok {
payload = append([]byte(nil), raw.data...)
contentType = raw.contentType
if contentType == "" {
contentType = "application/octet-stream"
}
} else {
encoded, err := json.Marshal(body)
if err != nil {
return nil, 0, fmt.Errorf("seatlayer: encoding request body: %w", err)
}
payload = encoded
}
}
header := http.Header{}
header.Set("Authorization", "Bearer "+c.secretKey)
header.Set("Accept", accept)
header.Set("User-Agent", userAgent)
if payload != nil {
header.Set("Content-Type", contentType)
}
// Only operations with exact server-side response replay get an automatic
// key. A caller key on any other mutation is forwarded, but cannot opt that
// operation into automatic retries.
if method != http.MethodGet && method != http.MethodHead {
key := idempotencyKey
if key == "" && headerReplay {
key = newIdempotencyKey()
}
if key != "" && !idempotencyKeyPattern.MatchString(key) {
return nil, 0, fmt.Errorf(
"seatlayer: invalid Idempotency-Key %q: allowed characters are A-Z a-z 0-9 . _ : - and the length must be 1-128",
key)
}
if key != "" {
header.Set("Idempotency-Key", key)
}
}
retryAllowed := method == http.MethodGet || method == http.MethodHead || headerReplay
var lastErr error
for attempt := 0; attempt < c.maxRetries; attempt++ {
var reader io.Reader
if payload != nil {
reader = bytes.NewReader(payload)
}
request, err := http.NewRequestWithContext(ctx, method, endpoint, reader)
if err != nil {
return nil, 0, fmt.Errorf("seatlayer: building request: %w", err)
}
request.Header = header.Clone()
response, err := c.httpClient.Do(request)
if err != nil {
// A cancelled context is the caller's decision, not a transient fault.
if ctx.Err() != nil {
return nil, 0, &ConnectionError{Op: method + " " + path, Err: ctx.Err()}
}
lastErr = &ConnectionError{Op: method + " " + path, Err: err}
if retryAllowed && attempt < c.maxRetries-1 {
if err := sleepCtx(ctx, backoff(attempt, -1)); err != nil {
return nil, 0, err
}
continue
}
return nil, 0, lastErr
}
responseBody, readErr := io.ReadAll(response.Body)
response.Body.Close()
if readErr != nil {
lastErr = &ConnectionError{Op: method + " " + path, Err: readErr}
if retryAllowed && attempt < c.maxRetries-1 {
if err := sleepCtx(ctx, backoff(attempt, -1)); err != nil {
return nil, 0, err
}
continue
}
return nil, 0, lastErr
}
if response.StatusCode >= 200 && response.StatusCode < 300 {
return responseBody, response.StatusCode, nil
}
// A proxy or WAF can answer with HTML; that must not become a decode
// failure that hides the real status from the caller.
errorBody := map[string]any{}
_ = json.Unmarshal(responseBody, &errorBody)
retryAfter := parseRetryAfter(response.Header, errorBody)
if retryAllowed && isRetryable(response.StatusCode) && attempt < c.maxRetries-1 {
wait := backoff(attempt, -1)
if response.StatusCode == http.StatusTooManyRequests {
wait = time.Duration(retryAfter * float64(time.Second))
}
if err := sleepCtx(ctx, wait); err != nil {
return nil, 0, err
}
continue
}
return nil, 0, errorFromResponse(
response.StatusCode, errorBody, response.Header.Get("X-Request-ID"), retryAfter)
}
if lastErr != nil {
return nil, 0, lastErr
}
return nil, 0, &ConnectionError{Op: method + " " + path, Err: errors.New("no attempts made")}
}
func (c *Client) get(ctx context.Context, path string, query url.Values) (map[string]any, error) {
return c.Do(ctx, http.MethodGet, path, query, nil, "")
}
func (c *Client) post(ctx context.Context, path string, body any, idempotencyKey string) (map[string]any, error) {
return c.Do(ctx, http.MethodPost, path, nil, body, idempotencyKey)
}
func (c *Client) postHeaderReplay(
ctx context.Context, path string, body any, idempotencyKey string,
) (map[string]any, error) {
return c.do(ctx, http.MethodPost, path, nil, body, idempotencyKey, true)
}
func (c *Client) mutationHeaderReplay(
ctx context.Context, method, path string, body any, idempotencyKey string,
) (map[string]any, error) {
return c.do(ctx, method, path, nil, body, idempotencyKey, true)
}
func (c *Client) put(ctx context.Context, path string, body any) (map[string]any, error) {
return c.Do(ctx, http.MethodPut, path, nil, body, "")
}
func (c *Client) putRaw(
ctx context.Context, path string, body []byte, contentType string,
) (map[string]any, error) {
return c.Do(ctx, http.MethodPut, path, nil,
rawRequestBody{data: body, contentType: contentType}, "")
}
func (c *Client) patch(ctx context.Context, path string, body any) (map[string]any, error) {
return c.Do(ctx, http.MethodPatch, path, nil, body, "")
}
func (c *Client) delete(ctx context.Context, path string) (map[string]any, error) {
return c.Do(ctx, http.MethodDelete, path, nil, nil, "")
}
func (c *Client) deleteQuery(
ctx context.Context, path string, query url.Values,
) (map[string]any, error) {
return c.Do(ctx, http.MethodDelete, path, query, nil, "")
}
// isRetryable reports whether a status is worth another attempt.
//
// 429 and 5xx are transient by definition. A 4xx is the API saying the request
// itself is wrong; retrying only burns rate-limit budget and delays the error
// the caller needs to see.
func isRetryable(status int) bool {
return status == http.StatusTooManyRequests ||
status == http.StatusRequestTimeout ||
(status >= 500 && status < 600)
}
// backoff returns exponential delay with full jitter, so a fleet of workers
// limited at the same moment does not retry in lockstep and re-limit itself.
func backoff(attempt int, retryAfterSeconds float64) time.Duration {
if retryAfterSeconds >= 0 {
return time.Duration(retryAfterSeconds * float64(time.Second))
}
ceiling := math.Min(8, 0.25*math.Pow(2, float64(attempt)))
return time.Duration(rand.Float64() * ceiling * float64(time.Second))
}
// sleepCtx waits, but gives up immediately if the caller cancels.
func sleepCtx(ctx context.Context, d time.Duration) error {
if d <= 0 {
return nil
}
timer := time.NewTimer(d)
defer timer.Stop()
select {
case <-timer.C:
return nil
case <-ctx.Done():
return &ConnectionError{Op: "waiting to retry", Err: ctx.Err()}
}
}
func parseRetryAfter(header http.Header, body map[string]any) float64 {
if raw := header.Get("Retry-After"); raw != "" {
if seconds, err := strconv.ParseFloat(strings.TrimSpace(raw), 64); err == nil && seconds >= 0 {
return seconds
}
}
// Fall back to the JSON field for routes that predate the headers.
if seconds, ok := body["retryAfterSeconds"].(float64); ok {
return seconds
}
return 1
}
func newIdempotencyKey() string {
// A UUID-shaped random string; the exact shape does not matter, only that it
// is unique per logical call and stable across that call's retries.
const hex = "0123456789abcdef"
b := make([]byte, 36)
for i := range b {
switch i {
case 8, 13, 18, 23:
b[i] = '-'
default:
b[i] = hex[rand.Intn(16)]
}
}
return string(b)
}
// escape percent-encodes a path segment, including slashes.
func escape(segment string) string {
return url.PathEscape(segment)
}
// params builds a request body, dropping nil values so optional fields stay
// optional rather than being sent as JSON null.
func params(pairs ...any) map[string]any {
if len(pairs)%2 != 0 {
panic("seatlayer: params takes alternating keys and values")
}
out := make(map[string]any, len(pairs)/2)
for i := 0; i < len(pairs); i += 2 {
key, _ := pairs[i].(string)
if pairs[i+1] != nil {
out[key] = pairs[i+1]
}
}
return out
}
func boolOrNil(value bool) any {
if !value {
return nil
}
return value
}
// pointerOrNil sends an optional pointer field only when it is set, so an
// explicit false or zero still reaches the API.
func pointerOrNil[T any](value *T) any {
if value == nil {
return nil
}
return *value
}
// decodeResponse projects the transport's forward-compatible JSON object into
// a named public wire type. Unknown additive fields remain harmless.
func decodeResponse[T any](response map[string]any) (T, error) {
var decoded T
encoded, err := json.Marshal(response)
if err != nil {
return decoded, fmt.Errorf("seatlayer: encoding response projection: %w", err)
}
if err := json.Unmarshal(encoded, &decoded); err != nil {
return decoded, fmt.Errorf("seatlayer: decoding response projection: %w", err)
}
return decoded, nil
}