-
Notifications
You must be signed in to change notification settings - Fork 126
/
rate_limit.go
56 lines (44 loc) · 1.42 KB
/
rate_limit.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
package prisma
import (
"context"
"fmt"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/rs/zerolog"
"github.com/hatchet-dev/hatchet/internal/repository"
"github.com/hatchet-dev/hatchet/internal/repository/prisma/dbsqlc"
"github.com/hatchet-dev/hatchet/internal/repository/prisma/sqlchelpers"
"github.com/hatchet-dev/hatchet/internal/validator"
)
type rateLimitEngineRepository struct {
pool *pgxpool.Pool
v validator.Validator
queries *dbsqlc.Queries
l *zerolog.Logger
}
func NewRateLimitEngineRepository(pool *pgxpool.Pool, v validator.Validator, l *zerolog.Logger) repository.RateLimitEngineRepository {
queries := dbsqlc.New()
return &rateLimitEngineRepository{
pool: pool,
v: v,
queries: queries,
l: l,
}
}
func (r *rateLimitEngineRepository) UpsertRateLimit(ctx context.Context, tenantId string, key string, opts *repository.UpsertRateLimitOpts) (*dbsqlc.RateLimit, error) {
if err := r.v.Validate(opts); err != nil {
return nil, err
}
upsertParams := dbsqlc.UpsertRateLimitParams{
Tenantid: sqlchelpers.UUIDFromStr(tenantId),
Key: key,
Limit: int32(opts.Limit),
}
if opts.Duration != nil {
upsertParams.Window = sqlchelpers.TextFromStr(fmt.Sprintf("1 %s", *opts.Duration))
}
rateLimit, err := r.queries.UpsertRateLimit(ctx, r.pool, upsertParams)
if err != nil {
return nil, fmt.Errorf("could not upsert rate limit: %w", err)
}
return rateLimit, nil
}