forked from mtusi2026/mtusi2026lab7
142 lines
4.2 KiB
Go
142 lines
4.2 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"slices"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
|
|
"mtusi-messenger/internal/domain"
|
|
"mtusi-messenger/internal/platform/ratelimit"
|
|
)
|
|
|
|
var nextLoginLimitCleanup atomic.Int64
|
|
|
|
var _ ratelimit.Limiter = (*Store)(nil)
|
|
|
|
type loginCounter struct {
|
|
limit ratelimit.Limit
|
|
count int64
|
|
expiresAt time.Time
|
|
}
|
|
|
|
// Reserve uses sorted row locks, including newly created counters, so requests
|
|
// on different replicas consume every dimension together or none of them.
|
|
func (s *Store) Reserve(ctx context.Context, limits []ratelimit.Limit) (retryAfter time.Duration, err error) {
|
|
if len(limits) == 0 {
|
|
return 0, nil
|
|
}
|
|
counters := make([]loginCounter, len(limits))
|
|
for i, limit := range limits {
|
|
if limit.Key == "" || limit.Count <= 0 || limit.Window < time.Microsecond {
|
|
return 0, fmt.Errorf("login admission: %w: invalid limit", domain.ErrUnavailable)
|
|
}
|
|
digest := sha256.Sum256([]byte(limit.Key))
|
|
limit.Key = hex.EncodeToString(digest[:])
|
|
counters[i].limit = limit
|
|
}
|
|
slices.SortFunc(counters, func(a, b loginCounter) int {
|
|
switch {
|
|
case a.limit.Key < b.limit.Key:
|
|
return -1
|
|
case a.limit.Key > b.limit.Key:
|
|
return 1
|
|
default:
|
|
return 0
|
|
}
|
|
})
|
|
for i := 1; i < len(counters); i++ {
|
|
if counters[i-1].limit.Key == counters[i].limit.Key {
|
|
return 0, fmt.Errorf("login admission: %w: duplicate limit", domain.ErrUnavailable)
|
|
}
|
|
}
|
|
|
|
ctx, cancel := s.timeout(ctx)
|
|
defer cancel()
|
|
if err := s.cleanupLoginLimits(ctx); err != nil {
|
|
return 0, err
|
|
}
|
|
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
|
|
if err != nil {
|
|
return 0, loginLimitError("begin admission", err)
|
|
}
|
|
defer func() {
|
|
rollbackCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second)
|
|
defer cancel()
|
|
if rollbackErr := tx.Rollback(rollbackCtx); rollbackErr != nil && !errors.Is(rollbackErr, pgx.ErrTxClosed) {
|
|
err = errors.Join(err, loginLimitError("rollback admission", rollbackErr))
|
|
}
|
|
}()
|
|
|
|
for i := range counters {
|
|
counter := &counters[i]
|
|
if err := tx.QueryRow(ctx, `
|
|
INSERT INTO login_limits (key_hash, count, expires_at)
|
|
VALUES ($1, 0, 'epoch')
|
|
ON CONFLICT (key_hash) DO UPDATE SET key_hash = EXCLUDED.key_hash
|
|
RETURNING count, expires_at`, counter.limit.Key).Scan(&counter.count, &counter.expiresAt); err != nil {
|
|
return 0, loginLimitError("lock admission counter", err)
|
|
}
|
|
}
|
|
// Read the database clock only after acquiring every dimension's lock.
|
|
var now time.Time
|
|
if err := tx.QueryRow(ctx, "SELECT clock_timestamp()").Scan(&now); err != nil {
|
|
return 0, loginLimitError("read admission clock", err)
|
|
}
|
|
for i := range counters {
|
|
counter := &counters[i]
|
|
if !counter.expiresAt.After(now) {
|
|
counter.count = 0
|
|
counter.expiresAt = now.Add(counter.limit.Window)
|
|
}
|
|
if counter.count >= int64(counter.limit.Count) {
|
|
retryAfter = max(retryAfter, counter.expiresAt.Sub(now))
|
|
}
|
|
}
|
|
if retryAfter > 0 {
|
|
return retryAfter, nil
|
|
}
|
|
for _, counter := range counters {
|
|
if _, err := tx.Exec(ctx, `
|
|
UPDATE login_limits SET count = $2, expires_at = $3
|
|
WHERE key_hash = $1`, counter.limit.Key, counter.count+1, counter.expiresAt); err != nil {
|
|
return 0, loginLimitError("reserve admission counter", err)
|
|
}
|
|
}
|
|
if err := tx.Commit(ctx); err != nil {
|
|
return 0, loginLimitError("commit admission", err)
|
|
}
|
|
return 0, nil
|
|
}
|
|
|
|
func (s *Store) cleanupLoginLimits(ctx context.Context) error {
|
|
now := time.Now().UnixNano()
|
|
next := nextLoginLimitCleanup.Load()
|
|
if now < next || !nextLoginLimitCleanup.CompareAndSwap(next, now+int64(time.Second)) {
|
|
return nil
|
|
}
|
|
// Its own short transaction avoids mixing cleanup locks with the sorted
|
|
// reservation locks. SKIP LOCKED never waits for an in-flight admission.
|
|
_, err := s.pool.Exec(ctx, `
|
|
WITH expired AS (
|
|
SELECT key_hash FROM login_limits
|
|
WHERE expires_at <= now()
|
|
ORDER BY expires_at, key_hash LIMIT 64 FOR UPDATE SKIP LOCKED
|
|
)
|
|
DELETE FROM login_limits l USING expired e WHERE l.key_hash = e.key_hash`)
|
|
if err != nil {
|
|
return loginLimitError("clean admission counters", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func loginLimitError(operation string, err error) error {
|
|
return fmt.Errorf("%s: %w: %w", operation, domain.ErrUnavailable, err)
|
|
}
|