DNF90 服务端与启动器完整源码(含 GM 工具功能增强)
服务端(Go): - GM 塞背包/带属性装备发放:在线角色推送 op14 增量物品行,背包实时刷新,无需回角色选择界面 - GM 改金币/改等级:去掉在线拒绝,落库后推送 op14 钱包/op37 等级状态,在线实时刷新 - 等级端点统一切换到新版 GMSetCharacterLevel(自带在线刷新) - 无限/锁死疲劳模式 + 燃烧疲劳:每房间消耗 2 点、打怪与通关经验双倍 - 燃烧疲劳开关时给所有在线角色推送系统提示(op12 mode 0) - 深渊史诗掉率:GM 全局倍率 + 城镇增益药剂窗口倍率,真实接入掉落结算 启动器(Python/JS): - 标题栏自绘、窗口 1204x717、禁止拖拽改大小、仅最小化/关闭 - GM 工具:疲劳与燃烧、深渊史诗掉率、拍卖行上架(单一定价对齐) - 拍卖行上架前端对齐服务端单一价格语义,修复 400 报错
This commit is contained in:
commit
645b64fe21
4388 files changed
+1405457
No files matched your search
@@ -0,0 +1,329 @@
|
||||
package leaderboard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
histQueueMax = 4096
|
||||
histFlushTimeout = 3 * time.Second
|
||||
histRetryInterval = 200 * time.Millisecond
|
||||
)
|
||||
|
||||
var (
|
||||
errHistStoreNil = errors.New("leaderboard history store is nil")
|
||||
errHistClosed = errors.New("leaderboard history queue is closed")
|
||||
errHistFull = errors.New("leaderboard history queue is full")
|
||||
)
|
||||
|
||||
// AsyncHistoryStore 把排行榜历史写入移出热路径,适用于非 strict 的 SQL/outbox 历史。
|
||||
type AsyncHistoryStore struct {
|
||||
next HistoryStore
|
||||
max int
|
||||
timeout time.Duration
|
||||
|
||||
mu sync.Mutex
|
||||
pending []HistoryEntry
|
||||
closed bool
|
||||
flushing bool
|
||||
flushDone chan struct{}
|
||||
errs uint64
|
||||
|
||||
wake chan struct{}
|
||||
stop chan struct{}
|
||||
done chan struct{}
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
// NewAsyncHistoryStore 创建异步排行榜历史存储。
|
||||
func NewAsyncHistoryStore(next HistoryStore) *AsyncHistoryStore {
|
||||
store := &AsyncHistoryStore{
|
||||
next: next,
|
||||
max: histQueueMax,
|
||||
timeout: histFlushTimeout,
|
||||
wake: make(chan struct{}, 1),
|
||||
stop: make(chan struct{}),
|
||||
done: make(chan struct{}),
|
||||
}
|
||||
go store.run()
|
||||
return store
|
||||
}
|
||||
|
||||
// Append 只入队历史,后台负责慢存储写入。
|
||||
func (s *AsyncHistoryStore) Append(ctx context.Context, entry HistoryEntry) error {
|
||||
if s == nil || s.next == nil {
|
||||
return errHistStoreNil
|
||||
}
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
entry = normHistoryEntry(entry)
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.closed {
|
||||
return errHistClosed
|
||||
}
|
||||
if len(s.pending) >= s.max {
|
||||
atomic.AddUint64(&s.errs, 1)
|
||||
return errHistFull
|
||||
}
|
||||
s.pending = append(s.pending, entry)
|
||||
s.wakeLocked()
|
||||
return nil
|
||||
}
|
||||
|
||||
// List 刷新 pending 后透传底层查询,管理面能读到已排队历史。
|
||||
func (s *AsyncHistoryStore) List(ctx context.Context, leaderboardID string, limit int) ([]HistoryEntry, error) {
|
||||
if s == nil || s.next == nil {
|
||||
return nil, errHistStoreNil
|
||||
}
|
||||
if err := s.Flush(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.next.List(ctx, leaderboardID, limit)
|
||||
}
|
||||
|
||||
// Flush 同步排空待写历史。
|
||||
func (s *AsyncHistoryStore) Flush(ctx context.Context) error {
|
||||
if s == nil || s.next == nil {
|
||||
return errHistStoreNil
|
||||
}
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
for {
|
||||
batch, wait := s.beginFlush()
|
||||
if wait != nil {
|
||||
if err := waitHistFlush(ctx, wait); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if len(batch) == 0 {
|
||||
return nil
|
||||
}
|
||||
if err := s.writeBatch(ctx, batch); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Close 停止后台 worker 并排空待写历史。
|
||||
func (s *AsyncHistoryStore) Close(ctx context.Context) error {
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
closeCtx, cancel := s.closeContext(ctx)
|
||||
defer cancel()
|
||||
s.once.Do(func() {
|
||||
s.mu.Lock()
|
||||
s.closed = true
|
||||
s.mu.Unlock()
|
||||
close(s.stop)
|
||||
})
|
||||
select {
|
||||
case <-s.done:
|
||||
case <-closeCtx.Done():
|
||||
return closeCtx.Err()
|
||||
}
|
||||
return errors.Join(s.Flush(closeCtx), closeHistory(closeCtx, s.next))
|
||||
}
|
||||
|
||||
// HistoryErrors 返回异步写入失败计数。
|
||||
func (s *AsyncHistoryStore) HistoryErrors() uint64 {
|
||||
if s == nil {
|
||||
return 0
|
||||
}
|
||||
return atomic.LoadUint64(&s.errs)
|
||||
}
|
||||
|
||||
// EventLogErrors 透传被包装历史存储的 outbox 错误计数。
|
||||
func (s *AsyncHistoryStore) EventLogErrors() uint64 {
|
||||
if s == nil {
|
||||
return 0
|
||||
}
|
||||
return historyStoreErrors(s.next)
|
||||
}
|
||||
|
||||
func (s *AsyncHistoryStore) run() {
|
||||
defer close(s.done)
|
||||
retry := time.NewTimer(time.Hour)
|
||||
stopHistTimer(retry)
|
||||
var retryC <-chan time.Time
|
||||
defer stopHistTimer(retry)
|
||||
for {
|
||||
select {
|
||||
case <-s.wake:
|
||||
if err := s.flushBackground(); err != nil {
|
||||
resetHistTimer(retry, histRetryInterval)
|
||||
retryC = retry.C
|
||||
} else {
|
||||
retryC = nil
|
||||
}
|
||||
case <-retryC:
|
||||
retryC = nil
|
||||
if err := s.flushBackground(); err != nil {
|
||||
resetHistTimer(retry, histRetryInterval)
|
||||
retryC = retry.C
|
||||
}
|
||||
case <-s.stop:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *AsyncHistoryStore) flushBackground() error {
|
||||
timeout := s.timeout
|
||||
if timeout <= 0 {
|
||||
timeout = histFlushTimeout
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
err := s.Flush(ctx)
|
||||
cancel()
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *AsyncHistoryStore) closeContext(ctx context.Context) (context.Context, context.CancelFunc) {
|
||||
if _, ok := ctx.Deadline(); ok {
|
||||
return ctx, func() {}
|
||||
}
|
||||
timeout := s.timeout
|
||||
if timeout <= 0 {
|
||||
timeout = histFlushTimeout
|
||||
}
|
||||
return context.WithTimeout(ctx, timeout)
|
||||
}
|
||||
|
||||
func (s *AsyncHistoryStore) beginFlush() ([]HistoryEntry, <-chan struct{}) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.flushing {
|
||||
return nil, s.flushDone
|
||||
}
|
||||
if len(s.pending) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
batch := cloneHistoryEntries(s.pending)
|
||||
s.pending = nil
|
||||
s.flushing = true
|
||||
s.flushDone = make(chan struct{})
|
||||
return batch, nil
|
||||
}
|
||||
|
||||
func (s *AsyncHistoryStore) writeBatch(ctx context.Context, batch []HistoryEntry) error {
|
||||
var err error
|
||||
failedAt := len(batch)
|
||||
for i, entry := range batch {
|
||||
if err = ctxErr(ctx); err != nil {
|
||||
failedAt = i
|
||||
break
|
||||
}
|
||||
if err = s.next.Append(ctx, entry); err != nil {
|
||||
failedAt = i
|
||||
break
|
||||
}
|
||||
}
|
||||
s.finishFlush(batch[failedAt:], err)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *AsyncHistoryStore) finishFlush(failed []HistoryEntry, err error) {
|
||||
s.mu.Lock()
|
||||
if err != nil {
|
||||
atomic.AddUint64(&s.errs, 1)
|
||||
restored := cloneHistoryEntries(failed)
|
||||
restored = append(restored, s.pending...)
|
||||
s.pending = restored
|
||||
}
|
||||
done := s.flushDone
|
||||
s.flushing = false
|
||||
s.flushDone = nil
|
||||
s.mu.Unlock()
|
||||
if done != nil {
|
||||
close(done)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *AsyncHistoryStore) wakeLocked() {
|
||||
select {
|
||||
case s.wake <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func wrapHistoryStore(store HistoryStore, strict bool) HistoryStore {
|
||||
if strict {
|
||||
return store
|
||||
}
|
||||
switch store.(type) {
|
||||
case nil, *MemoryHistoryStore, *AsyncHistoryStore:
|
||||
return store
|
||||
case *SQLHistoryStore, *EventLogHistoryStore:
|
||||
return NewAsyncHistoryStore(store)
|
||||
default:
|
||||
return store
|
||||
}
|
||||
}
|
||||
|
||||
func flushHistory(ctx context.Context, store HistoryStore) error {
|
||||
if flusher, ok := store.(interface {
|
||||
Flush(context.Context) error
|
||||
}); ok {
|
||||
return flusher.Flush(ctx)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func closeHistory(ctx context.Context, store HistoryStore) error {
|
||||
if closer, ok := store.(interface {
|
||||
Close(context.Context) error
|
||||
}); ok {
|
||||
return closer.Close(ctx)
|
||||
}
|
||||
return flushHistory(ctx, store)
|
||||
}
|
||||
|
||||
func waitHistFlush(ctx context.Context, done <-chan struct{}) error {
|
||||
if done == nil {
|
||||
return nil
|
||||
}
|
||||
select {
|
||||
case <-done:
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
func resetHistTimer(timer *time.Timer, delay time.Duration) {
|
||||
if timer == nil {
|
||||
return
|
||||
}
|
||||
if !timer.Stop() {
|
||||
select {
|
||||
case <-timer.C:
|
||||
default:
|
||||
}
|
||||
}
|
||||
timer.Reset(delay)
|
||||
}
|
||||
|
||||
func stopHistTimer(timer *time.Timer) {
|
||||
if timer == nil {
|
||||
return
|
||||
}
|
||||
if !timer.Stop() {
|
||||
select {
|
||||
case <-timer.C:
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
package leaderboard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"longheng.io/server/internal/platform/eventlog"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNilEventLogHistoryStore = errors.New("leaderboard eventlog history store is required")
|
||||
ErrNilEventLog = errors.New("leaderboard eventlog is required")
|
||||
)
|
||||
|
||||
const (
|
||||
LeaderboardEventStream = "leaderboard"
|
||||
DefaultLeaderboardHistoryEventType = "history.appended"
|
||||
histUndoTimeout = 3 * time.Second
|
||||
)
|
||||
|
||||
type HistoryStoreOptions struct {
|
||||
Stream string
|
||||
Type string
|
||||
Strict bool
|
||||
}
|
||||
|
||||
type EventLogHistoryStore struct {
|
||||
next HistoryStore
|
||||
log *eventlog.Log
|
||||
stream string
|
||||
typ string
|
||||
strict bool
|
||||
errors uint64
|
||||
}
|
||||
|
||||
type evErrorReporter interface {
|
||||
EventLogErrors() uint64
|
||||
}
|
||||
|
||||
type histErrorReporter interface {
|
||||
HistoryErrors() uint64
|
||||
}
|
||||
|
||||
type histUndo func(context.Context) error
|
||||
|
||||
type histUndoer interface {
|
||||
appendWithRollback(context.Context, HistoryEntry) (histUndo, error)
|
||||
}
|
||||
|
||||
func NewEventLogHistoryStore(next HistoryStore, log *eventlog.Log, options HistoryStoreOptions) (*EventLogHistoryStore, error) {
|
||||
if next == nil {
|
||||
return nil, ErrNilEventLogHistoryStore
|
||||
}
|
||||
if log == nil {
|
||||
return nil, ErrNilEventLog
|
||||
}
|
||||
stream := strings.TrimSpace(options.Stream)
|
||||
if stream == "" {
|
||||
stream = LeaderboardEventStream
|
||||
}
|
||||
typ := strings.TrimSpace(options.Type)
|
||||
if typ == "" {
|
||||
typ = DefaultLeaderboardHistoryEventType
|
||||
}
|
||||
return &EventLogHistoryStore{
|
||||
next: next,
|
||||
log: log,
|
||||
stream: stream,
|
||||
typ: typ,
|
||||
strict: options.Strict,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type eventHistoryStore struct {
|
||||
log *eventlog.Log
|
||||
stream string
|
||||
typ string
|
||||
}
|
||||
|
||||
func newEventHistoryStore(log *eventlog.Log, stream string, typ string) *eventHistoryStore {
|
||||
return &eventHistoryStore{
|
||||
log: log,
|
||||
stream: normalizeEventStream(stream),
|
||||
typ: normHistoryEventType(typ),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *EventLogHistoryStore) Append(ctx context.Context, entry HistoryEntry) error {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if s == nil || s.next == nil {
|
||||
return ErrNilEventLogHistoryStore
|
||||
}
|
||||
if s.log == nil {
|
||||
return ErrNilEventLog
|
||||
}
|
||||
entry = normHistoryEntry(entry)
|
||||
payload, err := json.Marshal(entry)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rollback, err := appendHist(ctx, s.next, entry)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s.log.Append(ctx, eventlog.Event{
|
||||
Stream: s.stream,
|
||||
Type: s.typ,
|
||||
AggregateID: entry.LeaderboardID,
|
||||
IdempotencyKey: historyIdemKey(entry, payload),
|
||||
Payload: payload,
|
||||
Headers: map[string]string{
|
||||
"action": entry.Action,
|
||||
"leaderboard_id": entry.LeaderboardID,
|
||||
"owner_id": entry.OwnerID,
|
||||
},
|
||||
})
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
atomic.AddUint64(&s.errors, 1)
|
||||
if s.strict {
|
||||
if rollbackErr := undoHist(ctx, rollback); rollbackErr != nil {
|
||||
return errors.Join(err, rollbackErr)
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *EventLogHistoryStore) List(ctx context.Context, leaderboardID string, limit int) ([]HistoryEntry, error) {
|
||||
if s == nil || s.next == nil {
|
||||
return nil, ErrNilEventLogHistoryStore
|
||||
}
|
||||
return s.next.List(ctx, leaderboardID, limit)
|
||||
}
|
||||
|
||||
func (s *EventLogHistoryStore) EventLogErrors() uint64 {
|
||||
if s == nil {
|
||||
return 0
|
||||
}
|
||||
return atomic.LoadUint64(&s.errors)
|
||||
}
|
||||
|
||||
func (s *eventHistoryStore) Append(ctx context.Context, entry HistoryEntry) error {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if s == nil || s.log == nil {
|
||||
return ErrNilEventLog
|
||||
}
|
||||
entry = normHistoryEntry(entry)
|
||||
payload, err := json.Marshal(entry)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s.log.Append(ctx, eventlog.Event{
|
||||
Stream: s.stream,
|
||||
Type: s.typ,
|
||||
AggregateID: entry.LeaderboardID,
|
||||
IdempotencyKey: historyIdemKey(entry, payload),
|
||||
Payload: payload,
|
||||
Headers: map[string]string{
|
||||
"action": entry.Action,
|
||||
"leaderboard_id": entry.LeaderboardID,
|
||||
"owner_id": entry.OwnerID,
|
||||
},
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *eventHistoryStore) List(context.Context, string, int) ([]HistoryEntry, error) {
|
||||
return nil, ErrNilEventLogHistoryStore
|
||||
}
|
||||
|
||||
func historyStoreErrors(store HistoryStore) uint64 {
|
||||
reporter, ok := store.(evErrorReporter)
|
||||
if !ok {
|
||||
return 0
|
||||
}
|
||||
return reporter.EventLogErrors()
|
||||
}
|
||||
|
||||
func historyErrors(store HistoryStore) uint64 {
|
||||
reporter, ok := store.(histErrorReporter)
|
||||
if !ok {
|
||||
return 0
|
||||
}
|
||||
return reporter.HistoryErrors()
|
||||
}
|
||||
|
||||
func appendHist(ctx context.Context, store HistoryStore, entry HistoryEntry) (histUndo, error) {
|
||||
if rollbacker, ok := store.(histUndoer); ok {
|
||||
return rollbacker.appendWithRollback(ctx, entry)
|
||||
}
|
||||
if err := store.Append(ctx, entry); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func undoHist(parent context.Context, rollback histUndo) error {
|
||||
if rollback == nil {
|
||||
return nil
|
||||
}
|
||||
base := context.Background()
|
||||
if parent != nil {
|
||||
base = context.WithoutCancel(parent)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(base, histUndoTimeout)
|
||||
defer cancel()
|
||||
return rollback(ctx)
|
||||
}
|
||||
|
||||
func normHistoryEntry(entry HistoryEntry) HistoryEntry {
|
||||
entry = cloneHistoryEntry(entry)
|
||||
entry.Action = strings.TrimSpace(entry.Action)
|
||||
entry.LeaderboardID = strings.TrimSpace(entry.LeaderboardID)
|
||||
entry.OwnerID = strings.TrimSpace(entry.OwnerID)
|
||||
if entry.At.IsZero() {
|
||||
entry.At = time.Now().UTC()
|
||||
} else {
|
||||
entry.At = entry.At.UTC()
|
||||
}
|
||||
return entry
|
||||
}
|
||||
|
||||
func historyIdemKey(entry HistoryEntry, payload []byte) string {
|
||||
raw := fmt.Sprintf("%s|%s|%s|%d|%x",
|
||||
entry.LeaderboardID,
|
||||
entry.Action,
|
||||
entry.OwnerID,
|
||||
entry.At.UTC().UnixNano(),
|
||||
payload,
|
||||
)
|
||||
hash := sha256.Sum256([]byte(raw))
|
||||
return "leaderboard:history:" + hex.EncodeToString(hash[:16])
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
package leaderboard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func normalizeSubmission(submission Submission) (Submission, error) {
|
||||
submission.OwnerID = strings.TrimSpace(submission.OwnerID)
|
||||
if submission.OwnerID == "" {
|
||||
return Submission{}, fmt.Errorf("%w: owner_id is required", ErrInvalidSubmission)
|
||||
}
|
||||
submission.Metadata = cloneStringMap(submission.Metadata)
|
||||
return submission, nil
|
||||
}
|
||||
|
||||
func addScoreValue(left int64, right int64) (int64, error) {
|
||||
if (right > 0 && left > math.MaxInt64-right) || (right < 0 && left < math.MinInt64-right) {
|
||||
return 0, fmt.Errorf("%w: %w", ErrInvalidSubmission, ErrScoreOverflow)
|
||||
}
|
||||
return left + right, nil
|
||||
}
|
||||
|
||||
func normRepairReq(request RepairRequest) (RepairRequest, error) {
|
||||
request.OwnerID = strings.TrimSpace(request.OwnerID)
|
||||
if request.OwnerID == "" {
|
||||
return RepairRequest{}, fmt.Errorf("%w: owner_id is required", ErrInvalidSubmission)
|
||||
}
|
||||
request.Reason = strings.TrimSpace(request.Reason)
|
||||
request.OperatorID = strings.TrimSpace(request.OperatorID)
|
||||
request.RequestID = strings.TrimSpace(request.RequestID)
|
||||
request.Metadata = cloneStringMap(request.Metadata)
|
||||
return request, nil
|
||||
}
|
||||
|
||||
func repairIdempotencyKey(leaderboardID string, requestID string) string {
|
||||
leaderboardID = strings.TrimSpace(leaderboardID)
|
||||
requestID = strings.TrimSpace(requestID)
|
||||
if leaderboardID == "" || requestID == "" {
|
||||
return ""
|
||||
}
|
||||
return strings.Join([]string{"v1", encodeKeyPart(leaderboardID), encodeKeyPart(requestID)}, ":")
|
||||
}
|
||||
|
||||
func encodeKeyPart(value string) string {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
return "_"
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(value))
|
||||
}
|
||||
|
||||
func normCaptureOpts(options CaptureOptions) CaptureOptions {
|
||||
if options.Limit <= 0 {
|
||||
options.Limit = defaultListLimit
|
||||
}
|
||||
if options.Limit > maxListLimit {
|
||||
options.Limit = maxListLimit
|
||||
}
|
||||
options.Reason = strings.TrimSpace(options.Reason)
|
||||
options.OperatorID = strings.TrimSpace(options.OperatorID)
|
||||
options.RequestID = strings.TrimSpace(options.RequestID)
|
||||
options.Metadata = cloneStringMap(options.Metadata)
|
||||
return options
|
||||
}
|
||||
|
||||
func normalizeSortOrder(sortOrder string) (string, error) {
|
||||
sortOrder = strings.ToLower(strings.TrimSpace(sortOrder))
|
||||
switch sortOrder {
|
||||
case "", SortDescending:
|
||||
return SortDescending, nil
|
||||
case SortAscending:
|
||||
return SortAscending, nil
|
||||
default:
|
||||
return "", fmt.Errorf("%w: unsupported sort_order %q", ErrInvalidDefinition, sortOrder)
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeOperator(operator string) (string, error) {
|
||||
operator = strings.ToLower(strings.TrimSpace(operator))
|
||||
switch operator {
|
||||
case "", OperatorBest:
|
||||
return OperatorBest, nil
|
||||
case OperatorSet, OperatorIncrement:
|
||||
return operator, nil
|
||||
default:
|
||||
return "", fmt.Errorf("%w: unsupported operator %q", ErrInvalidDefinition, operator)
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeListOptions(options ListOptions) (int, int) {
|
||||
offset := options.Offset
|
||||
if offset < 0 {
|
||||
offset = 0
|
||||
}
|
||||
limit := options.Limit
|
||||
if limit <= 0 {
|
||||
limit = defaultListLimit
|
||||
}
|
||||
if limit > maxListLimit {
|
||||
limit = maxListLimit
|
||||
}
|
||||
return offset, limit
|
||||
}
|
||||
|
||||
func betterThan(candidate Record, existing Record, sortOrder string) bool {
|
||||
switch {
|
||||
case candidate.Score != existing.Score:
|
||||
if sortOrder == SortAscending {
|
||||
return candidate.Score < existing.Score
|
||||
}
|
||||
return candidate.Score > existing.Score
|
||||
case candidate.Subscore != existing.Subscore:
|
||||
if sortOrder == SortAscending {
|
||||
return candidate.Subscore < existing.Subscore
|
||||
}
|
||||
return candidate.Subscore > existing.Subscore
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func compareRecords(a Record, b Record, sortOrder string) int {
|
||||
if a.Score != b.Score {
|
||||
if sortOrder == SortAscending {
|
||||
if a.Score < b.Score {
|
||||
return -1
|
||||
}
|
||||
return 1
|
||||
}
|
||||
if a.Score > b.Score {
|
||||
return -1
|
||||
}
|
||||
return 1
|
||||
}
|
||||
if a.Subscore != b.Subscore {
|
||||
if sortOrder == SortAscending {
|
||||
if a.Subscore < b.Subscore {
|
||||
return -1
|
||||
}
|
||||
return 1
|
||||
}
|
||||
if a.Subscore > b.Subscore {
|
||||
return -1
|
||||
}
|
||||
return 1
|
||||
}
|
||||
if !a.CreatedAt.Equal(b.CreatedAt) {
|
||||
if a.CreatedAt.Before(b.CreatedAt) {
|
||||
return -1
|
||||
}
|
||||
return 1
|
||||
}
|
||||
if a.OwnerID < b.OwnerID {
|
||||
return -1
|
||||
}
|
||||
if a.OwnerID > b.OwnerID {
|
||||
return 1
|
||||
}
|
||||
if a.LeaderboardID < b.LeaderboardID {
|
||||
return -1
|
||||
}
|
||||
if a.LeaderboardID > b.LeaderboardID {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func cloneDefinition(definition Definition) Definition {
|
||||
definition.Metadata = cloneStringMap(definition.Metadata)
|
||||
return definition
|
||||
}
|
||||
|
||||
func cloneRecord(record Record) Record {
|
||||
record.Metadata = cloneStringMap(record.Metadata)
|
||||
return record
|
||||
}
|
||||
|
||||
func cloneRecords(records []Record) []Record {
|
||||
out := make([]Record, len(records))
|
||||
for i, record := range records {
|
||||
out[i] = cloneRecord(record)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func cloneDefinitionMap(definitions map[string]Definition) map[string]Definition {
|
||||
out := make(map[string]Definition, len(definitions))
|
||||
for id, definition := range definitions {
|
||||
out[id] = cloneDefinition(definition)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func cloneRecordMap(records map[string]map[string]Record) map[string]map[string]Record {
|
||||
out := make(map[string]map[string]Record, len(records))
|
||||
for leaderboardID, boardRecords := range records {
|
||||
out[leaderboardID] = cloneRecordSet(boardRecords)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func cloneRecordSet(records map[string]Record) map[string]Record {
|
||||
out := make(map[string]Record, len(records))
|
||||
for ownerID, record := range records {
|
||||
out[ownerID] = cloneRecord(record)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func cloneRepairMap(repairs map[string]RepairReceipt) map[string]RepairReceipt {
|
||||
out := make(map[string]RepairReceipt, len(repairs))
|
||||
for key, receipt := range repairs {
|
||||
out[key] = cloneRepairReceipt(receipt)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func cloneRepairReceipt(receipt RepairReceipt) RepairReceipt {
|
||||
if receipt.Before != nil {
|
||||
before := cloneRecord(*receipt.Before)
|
||||
receipt.Before = &before
|
||||
}
|
||||
if receipt.After != nil {
|
||||
after := cloneRecord(*receipt.After)
|
||||
receipt.After = &after
|
||||
}
|
||||
receipt.Metadata = cloneStringMap(receipt.Metadata)
|
||||
return receipt
|
||||
}
|
||||
|
||||
func cloneCapture(capture Capture) Capture {
|
||||
capture.Records = cloneRecords(capture.Records)
|
||||
capture.Metadata = cloneStringMap(capture.Metadata)
|
||||
return capture
|
||||
}
|
||||
|
||||
func repairHistoryEntry(receipt RepairReceipt, record *Record) HistoryEntry {
|
||||
entry := HistoryEntry{
|
||||
Action: HistoryActionRepairRecord,
|
||||
LeaderboardID: receipt.LeaderboardID,
|
||||
OwnerID: receipt.OwnerID,
|
||||
Reason: receipt.Reason,
|
||||
OperatorID: receipt.OperatorID,
|
||||
RequestID: receipt.RequestID,
|
||||
Metadata: cloneStringMap(receipt.Metadata),
|
||||
At: receipt.At,
|
||||
}
|
||||
if record != nil {
|
||||
cloned := cloneRecord(*record)
|
||||
entry.Record = &cloned
|
||||
} else if receipt.Before != nil {
|
||||
cloned := cloneRecord(*receipt.Before)
|
||||
entry.Record = &cloned
|
||||
}
|
||||
return entry
|
||||
}
|
||||
|
||||
func cloneStringMap(in map[string]string) map[string]string {
|
||||
if len(in) == 0 {
|
||||
return nil
|
||||
}
|
||||
out := make(map[string]string, len(in))
|
||||
for key, value := range in {
|
||||
out[key] = value
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func ctxErr(ctx context.Context) error {
|
||||
if ctx == nil {
|
||||
return nil
|
||||
}
|
||||
return ctx.Err()
|
||||
}
|
||||
@@ -0,0 +1,433 @@
|
||||
package leaderboard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNilHistoryStoreDB = errors.New("leaderboard history sql db is required")
|
||||
ErrInvalidTableName = errors.New("leaderboard history table name is invalid")
|
||||
ErrHistoryAppendRollbackMissed = errors.New("leaderboard history append rollback missed")
|
||||
ErrSQLHistoryRows = errors.New("leaderboard sql history rows are required")
|
||||
)
|
||||
|
||||
const defaultHistoryTable = "leaderboard_history"
|
||||
|
||||
type MemoryHistoryStore struct {
|
||||
mu sync.Mutex
|
||||
limit int
|
||||
entries map[string][]HistoryEntry
|
||||
}
|
||||
|
||||
func NewMemoryHistoryStore(limit int) *MemoryHistoryStore {
|
||||
return &MemoryHistoryStore{
|
||||
limit: limit,
|
||||
entries: make(map[string][]HistoryEntry),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MemoryHistoryStore) Append(ctx context.Context, entry HistoryEntry) error {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if s == nil {
|
||||
return errors.New("leaderboard memory history store is nil")
|
||||
}
|
||||
entry, err := normHistStore(entry)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.appendLocked(entry)
|
||||
s.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *MemoryHistoryStore) appendWithRollback(ctx context.Context, entry HistoryEntry) (histUndo, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if s == nil {
|
||||
return nil, errors.New("leaderboard memory history store is nil")
|
||||
}
|
||||
entry, err := normHistStore(entry)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
leaderboardID := entry.LeaderboardID
|
||||
s.mu.Lock()
|
||||
before := cloneHistoryEntries(s.entries[leaderboardID])
|
||||
s.appendLocked(entry)
|
||||
s.mu.Unlock()
|
||||
return func(ctx context.Context) error {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
s.mu.Lock()
|
||||
if len(before) == 0 {
|
||||
delete(s.entries, leaderboardID)
|
||||
} else {
|
||||
s.entries[leaderboardID] = cloneHistoryEntries(before)
|
||||
}
|
||||
s.mu.Unlock()
|
||||
return nil
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *MemoryHistoryStore) appendLocked(entry HistoryEntry) {
|
||||
if s.entries == nil {
|
||||
s.entries = make(map[string][]HistoryEntry)
|
||||
}
|
||||
s.entries[entry.LeaderboardID] = append(s.entries[entry.LeaderboardID], cloneHistoryEntry(entry))
|
||||
if s.limit > 0 && len(s.entries[entry.LeaderboardID]) > s.limit {
|
||||
s.entries[entry.LeaderboardID] = append([]HistoryEntry(nil), s.entries[entry.LeaderboardID][len(s.entries[entry.LeaderboardID])-s.limit:]...)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MemoryHistoryStore) List(ctx context.Context, leaderboardID string, limit int) ([]HistoryEntry, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if s == nil {
|
||||
return nil, errors.New("leaderboard memory history store is nil")
|
||||
}
|
||||
leaderboardID = strings.TrimSpace(leaderboardID)
|
||||
if leaderboardID == "" {
|
||||
return nil, ErrLeaderboardNotFound
|
||||
}
|
||||
if limit <= 0 {
|
||||
limit = defaultListLimit
|
||||
}
|
||||
s.mu.Lock()
|
||||
entries := s.entries[leaderboardID]
|
||||
start := 0
|
||||
if limit > 0 && len(entries) > limit {
|
||||
start = len(entries) - limit
|
||||
}
|
||||
out := cloneHistoryEntries(entries[start:])
|
||||
s.mu.Unlock()
|
||||
return out, nil
|
||||
}
|
||||
|
||||
type SQLHistoryRows interface {
|
||||
Next() bool
|
||||
Scan(...any) error
|
||||
Close() error
|
||||
Err() error
|
||||
}
|
||||
|
||||
type SQLHistoryDB interface {
|
||||
ExecContext(context.Context, string, ...any) (sql.Result, error)
|
||||
QueryHistoryContext(context.Context, string, ...any) (SQLHistoryRows, error)
|
||||
}
|
||||
|
||||
type SQLHistoryDBAdapter struct {
|
||||
DB *sql.DB
|
||||
}
|
||||
|
||||
func (a SQLHistoryDBAdapter) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) {
|
||||
if a.DB == nil {
|
||||
return nil, ErrNilHistoryStoreDB
|
||||
}
|
||||
return a.DB.ExecContext(ctx, query, args...)
|
||||
}
|
||||
|
||||
func (a SQLHistoryDBAdapter) QueryHistoryContext(ctx context.Context, query string, args ...any) (SQLHistoryRows, error) { //nolint:rowserrcheck // 适配层只返回 rows,调用方负责遍历结束后的 Err 检查。
|
||||
if a.DB == nil {
|
||||
return nil, ErrNilHistoryStoreDB
|
||||
}
|
||||
return a.DB.QueryContext(ctx, query, args...) //nolint:rowserrcheck // rows 返回后由上层统一关闭并检查 Err。
|
||||
}
|
||||
|
||||
type SQLHistoryStoreOptions struct {
|
||||
Table string
|
||||
}
|
||||
|
||||
type SQLHistoryStore struct {
|
||||
db SQLHistoryDB
|
||||
table string
|
||||
}
|
||||
|
||||
func NewSQLHistoryStore(db SQLHistoryDB, options SQLHistoryStoreOptions) (*SQLHistoryStore, error) {
|
||||
if db == nil {
|
||||
return nil, ErrNilHistoryStoreDB
|
||||
}
|
||||
table, err := normHistoryTable(options.Table)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &SQLHistoryStore{db: db, table: table}, nil
|
||||
}
|
||||
|
||||
func NewSQLHistoryStoreFromDB(db *sql.DB, options SQLHistoryStoreOptions) (*SQLHistoryStore, error) {
|
||||
if db == nil {
|
||||
return nil, ErrNilHistoryStoreDB
|
||||
}
|
||||
return NewSQLHistoryStore(SQLHistoryDBAdapter{DB: db}, options)
|
||||
}
|
||||
|
||||
func (s *SQLHistoryStore) EnsureSchema(ctx context.Context) error {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if s == nil || s.db == nil {
|
||||
return ErrNilHistoryStoreDB
|
||||
}
|
||||
_, err := s.db.ExecContext(ctx, s.Schema())
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *SQLHistoryStore) Schema() string {
|
||||
table := quoteHistoryID(s.table)
|
||||
return fmt.Sprintf(`CREATE TABLE IF NOT EXISTS %s (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
leaderboard_id VARCHAR(128) NOT NULL,
|
||||
owner_id VARCHAR(128) NOT NULL DEFAULT '',
|
||||
action VARCHAR(64) NOT NULL,
|
||||
record_json JSON NULL,
|
||||
definition_json JSON NULL,
|
||||
entry_json JSON NOT NULL,
|
||||
created_at DATETIME(6) NOT NULL,
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_leaderboard_history_board_id (leaderboard_id, id),
|
||||
KEY idx_leaderboard_history_owner_id (owner_id, id),
|
||||
KEY idx_leaderboard_history_action_id (action, id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`, table)
|
||||
}
|
||||
|
||||
func (s *SQLHistoryStore) Append(ctx context.Context, entry HistoryEntry) error {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if s == nil || s.db == nil {
|
||||
return ErrNilHistoryStoreDB
|
||||
}
|
||||
_, err := s.appendWithRollback(ctx, entry)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *SQLHistoryStore) appendWithRollback(ctx context.Context, entry HistoryEntry) (histUndo, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if s == nil || s.db == nil {
|
||||
return nil, ErrNilHistoryStoreDB
|
||||
}
|
||||
entry, err := normHistStore(entry)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
entryJSON, err := json.Marshal(entry)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
recordJSON, err := nullableJSON(entry.Record)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
definitionJSON, err := nullableJSON(entry.Definition)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result, err := s.db.ExecContext(ctx,
|
||||
"INSERT INTO "+quoteHistoryID(s.table)+" (leaderboard_id, owner_id, action, record_json, definition_json, entry_json, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
|
||||
entry.LeaderboardID,
|
||||
entry.OwnerID,
|
||||
entry.Action,
|
||||
recordJSON,
|
||||
definitionJSON,
|
||||
string(entryJSON),
|
||||
entry.At,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return func(ctx context.Context) error {
|
||||
return s.rollbackAppend(ctx, entry, result)
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *SQLHistoryStore) rollbackAppend(ctx context.Context, entry HistoryEntry, result sql.Result) error {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if s == nil || s.db == nil {
|
||||
return ErrNilHistoryStoreDB
|
||||
}
|
||||
table := quoteHistoryID(s.table)
|
||||
if result != nil {
|
||||
if id, err := result.LastInsertId(); err == nil && id > 0 {
|
||||
deleted, err := s.db.ExecContext(ctx,
|
||||
"DELETE FROM "+table+" WHERE id = ? AND leaderboard_id = ? AND owner_id = ? AND action = ?",
|
||||
id,
|
||||
entry.LeaderboardID,
|
||||
entry.OwnerID,
|
||||
entry.Action,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return checkHistUndo(deleted)
|
||||
}
|
||||
}
|
||||
deleted, err := s.db.ExecContext(ctx,
|
||||
"DELETE FROM "+table+" WHERE id = (SELECT id FROM (SELECT id FROM "+table+" WHERE leaderboard_id = ? AND owner_id = ? AND action = ? AND created_at = ? ORDER BY id DESC LIMIT 1) AS rollback_candidate)",
|
||||
entry.LeaderboardID,
|
||||
entry.OwnerID,
|
||||
entry.Action,
|
||||
entry.At,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return checkHistUndo(deleted)
|
||||
}
|
||||
|
||||
func checkHistUndo(result sql.Result) error {
|
||||
if result == nil {
|
||||
return nil
|
||||
}
|
||||
affected, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
if affected == 0 {
|
||||
return ErrHistoryAppendRollbackMissed
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func normHistStore(entry HistoryEntry) (HistoryEntry, error) {
|
||||
entry = cloneHistoryEntry(entry)
|
||||
entry.LeaderboardID = strings.TrimSpace(entry.LeaderboardID)
|
||||
if entry.LeaderboardID == "" {
|
||||
return HistoryEntry{}, ErrLeaderboardNotFound
|
||||
}
|
||||
if entry.At.IsZero() {
|
||||
entry.At = time.Now().UTC()
|
||||
} else {
|
||||
entry.At = entry.At.UTC()
|
||||
}
|
||||
return entry, nil
|
||||
}
|
||||
|
||||
func (s *SQLHistoryStore) List(ctx context.Context, leaderboardID string, limit int) (out []HistoryEntry, err error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if s == nil || s.db == nil {
|
||||
return nil, ErrNilHistoryStoreDB
|
||||
}
|
||||
leaderboardID = strings.TrimSpace(leaderboardID)
|
||||
if leaderboardID == "" {
|
||||
return nil, ErrLeaderboardNotFound
|
||||
}
|
||||
if limit <= 0 {
|
||||
limit = defaultListLimit
|
||||
}
|
||||
if limit > maxListLimit {
|
||||
limit = maxListLimit
|
||||
}
|
||||
rows, err := s.db.QueryHistoryContext(ctx,
|
||||
"SELECT entry_json FROM "+quoteHistoryID(s.table)+" WHERE leaderboard_id = ? ORDER BY id DESC LIMIT ?",
|
||||
leaderboardID,
|
||||
limit,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if rows == nil {
|
||||
return nil, ErrSQLHistoryRows
|
||||
}
|
||||
defer closeHistRowsErr(rows, &err)
|
||||
out = make([]HistoryEntry, 0, limit)
|
||||
for rows.Next() {
|
||||
var data []byte
|
||||
if err := rows.Scan(&data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var entry HistoryEntry
|
||||
if err := json.Unmarshal(data, &entry); err != nil {
|
||||
return nil, fmt.Errorf("decode leaderboard sql history: %w", err)
|
||||
}
|
||||
out = append(out, cloneHistoryEntry(entry))
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
reverseHistory(out)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func closeHistRowsErr(rows SQLHistoryRows, err *error) {
|
||||
if rows == nil || err == nil {
|
||||
return
|
||||
}
|
||||
if closeErr := rows.Close(); closeErr != nil && *err == nil {
|
||||
*err = closeErr
|
||||
}
|
||||
}
|
||||
|
||||
func cloneHistoryEntry(entry HistoryEntry) HistoryEntry {
|
||||
if entry.Record != nil {
|
||||
record := cloneRecord(*entry.Record)
|
||||
entry.Record = &record
|
||||
}
|
||||
entry.Records = cloneRecords(entry.Records)
|
||||
if entry.Definition != nil {
|
||||
definition := cloneDefinition(*entry.Definition)
|
||||
entry.Definition = &definition
|
||||
}
|
||||
entry.Metadata = cloneStringMap(entry.Metadata)
|
||||
return entry
|
||||
}
|
||||
|
||||
func cloneHistoryEntries(entries []HistoryEntry) []HistoryEntry {
|
||||
out := make([]HistoryEntry, len(entries))
|
||||
for i, entry := range entries {
|
||||
out[i] = cloneHistoryEntry(entry)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func reverseHistory(entries []HistoryEntry) {
|
||||
for i, j := 0, len(entries)-1; i < j; i, j = i+1, j-1 {
|
||||
entries[i], entries[j] = entries[j], entries[i]
|
||||
}
|
||||
}
|
||||
|
||||
func nullableJSON(value any) (any, error) {
|
||||
if value == nil {
|
||||
return nil, nil
|
||||
}
|
||||
data, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return string(data), nil
|
||||
}
|
||||
|
||||
func normHistoryTable(table string) (string, error) {
|
||||
table = strings.TrimSpace(table)
|
||||
if table == "" {
|
||||
table = defaultHistoryTable
|
||||
}
|
||||
if !histTablePattern.MatchString(table) {
|
||||
return "", ErrInvalidTableName
|
||||
}
|
||||
return table, nil
|
||||
}
|
||||
|
||||
func quoteHistoryID(identifier string) string {
|
||||
return "`" + identifier + "`"
|
||||
}
|
||||
|
||||
var histTablePattern = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
|
||||
@@ -0,0 +1,865 @@
|
||||
package leaderboard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Manager struct {
|
||||
name string
|
||||
now func() time.Time
|
||||
gen func(prefix string) string
|
||||
hist HistoryStore
|
||||
|
||||
historyStrict bool
|
||||
historyErrors int
|
||||
|
||||
mu sync.Mutex
|
||||
next uint64
|
||||
definitions map[string]Definition
|
||||
records map[string]map[string]Record
|
||||
repairs map[string]RepairReceipt
|
||||
}
|
||||
|
||||
type managerStateSnapshot struct {
|
||||
definitions map[string]Definition
|
||||
records map[string]map[string]Record
|
||||
repairs map[string]RepairReceipt
|
||||
}
|
||||
|
||||
type boardRankData struct {
|
||||
definition Definition
|
||||
records map[string]Record
|
||||
}
|
||||
|
||||
func New(options Options) *Manager {
|
||||
name := strings.TrimSpace(options.Name)
|
||||
if name == "" {
|
||||
name = "leaderboard"
|
||||
}
|
||||
now := options.Now
|
||||
if now == nil {
|
||||
now = time.Now
|
||||
}
|
||||
historyStore := options.HistoryStore
|
||||
if historyStore == nil && options.HistoryLimit >= 0 {
|
||||
historyLimit := options.HistoryLimit
|
||||
if historyLimit == 0 {
|
||||
historyLimit = defaultHistoryLimit
|
||||
}
|
||||
historyStore = NewMemoryHistoryStore(historyLimit)
|
||||
}
|
||||
historyStore = wrapHistoryStore(historyStore, options.HistoryStrict)
|
||||
return &Manager{
|
||||
name: name,
|
||||
now: now,
|
||||
gen: options.IDGenerator,
|
||||
hist: historyStore,
|
||||
historyStrict: options.HistoryStrict,
|
||||
definitions: make(map[string]Definition),
|
||||
records: make(map[string]map[string]Record),
|
||||
repairs: make(map[string]RepairReceipt),
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) Create(ctx context.Context, definition Definition) (Definition, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return Definition{}, err
|
||||
}
|
||||
if m == nil {
|
||||
return Definition{}, ErrManagerRequired
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.ensureReadyLocked()
|
||||
|
||||
normalized, err := m.normDefinitionLocked(definition)
|
||||
if err != nil {
|
||||
return Definition{}, err
|
||||
}
|
||||
if _, exists := m.definitions[normalized.ID]; exists {
|
||||
return Definition{}, ErrLeaderboardExists
|
||||
}
|
||||
before := m.snapshotStateLocked()
|
||||
m.definitions[normalized.ID] = normalized
|
||||
m.records[normalized.ID] = make(map[string]Record)
|
||||
if err := m.appendHistoryLocked(ctx, HistoryActionCreate, normalized.ID, nil, &normalized, normalized.CreatedAt); err != nil {
|
||||
m.restoreStateLocked(before)
|
||||
return Definition{}, err
|
||||
}
|
||||
return cloneDefinition(normalized), nil
|
||||
}
|
||||
|
||||
func (m *Manager) Delete(ctx context.Context, leaderboardID string) (Definition, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return Definition{}, err
|
||||
}
|
||||
if m == nil {
|
||||
return Definition{}, ErrManagerRequired
|
||||
}
|
||||
leaderboardID = strings.TrimSpace(leaderboardID)
|
||||
if leaderboardID == "" {
|
||||
return Definition{}, ErrLeaderboardNotFound
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.ensureReadyLocked()
|
||||
|
||||
definition, ok := m.definitions[leaderboardID]
|
||||
if !ok {
|
||||
return Definition{}, ErrLeaderboardNotFound
|
||||
}
|
||||
before := m.snapshotStateLocked()
|
||||
delete(m.definitions, leaderboardID)
|
||||
delete(m.records, leaderboardID)
|
||||
if err := m.appendHistoryLocked(ctx, HistoryDeleteBoard, definition.ID, nil, &definition, m.now().UTC()); err != nil {
|
||||
m.restoreStateLocked(before)
|
||||
return Definition{}, err
|
||||
}
|
||||
return cloneDefinition(definition), nil
|
||||
}
|
||||
|
||||
func (m *Manager) Definition(leaderboardID string) (Definition, bool) {
|
||||
leaderboardID = strings.TrimSpace(leaderboardID)
|
||||
if m == nil || leaderboardID == "" {
|
||||
return Definition{}, false
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.ensureReadyLocked()
|
||||
definition, ok := m.definitions[leaderboardID]
|
||||
return cloneDefinition(definition), ok
|
||||
}
|
||||
|
||||
func (m *Manager) Definitions() []Definition {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.ensureReadyLocked()
|
||||
|
||||
out := make([]Definition, 0, len(m.definitions))
|
||||
for _, definition := range m.definitions {
|
||||
out = append(out, cloneDefinition(definition))
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
|
||||
return out
|
||||
}
|
||||
|
||||
func (m *Manager) Submit(ctx context.Context, leaderboardID string, submission Submission) (Record, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return Record{}, err
|
||||
}
|
||||
if m == nil {
|
||||
return Record{}, ErrManagerRequired
|
||||
}
|
||||
leaderboardID = strings.TrimSpace(leaderboardID)
|
||||
if leaderboardID == "" {
|
||||
return Record{}, ErrLeaderboardNotFound
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.ensureReadyLocked()
|
||||
|
||||
definition, ok := m.definitions[leaderboardID]
|
||||
if !ok {
|
||||
return Record{}, ErrLeaderboardNotFound
|
||||
}
|
||||
normalized, err := normalizeSubmission(submission)
|
||||
if err != nil {
|
||||
return Record{}, err
|
||||
}
|
||||
now := m.now().UTC()
|
||||
recordMap := m.records[leaderboardID]
|
||||
existing, exists := recordMap[normalized.OwnerID]
|
||||
record := Record{
|
||||
LeaderboardID: leaderboardID,
|
||||
OwnerID: normalized.OwnerID,
|
||||
Score: normalized.Score,
|
||||
Subscore: normalized.Subscore,
|
||||
Metadata: cloneStringMap(normalized.Metadata),
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
if exists {
|
||||
record.CreatedAt = existing.CreatedAt
|
||||
switch definition.Operator {
|
||||
case OperatorBest:
|
||||
candidate := record
|
||||
if !betterThan(candidate, existing, definition.SortOrder) {
|
||||
// Best 模式只接受更优成绩;较差提交返回当前排名,不写历史噪音。
|
||||
ranked, ok := m.recordWithRankLocked(leaderboardID, normalized.OwnerID)
|
||||
if !ok {
|
||||
return Record{}, ErrRecordNotFound
|
||||
}
|
||||
return ranked, nil
|
||||
}
|
||||
case OperatorIncrement:
|
||||
// Increment 模式用于累计榜,调用方要保证加分来源已经在关键写路径里做幂等。
|
||||
record.Score, err = addScoreValue(existing.Score, normalized.Score)
|
||||
if err != nil {
|
||||
return Record{}, err
|
||||
}
|
||||
record.Subscore, err = addScoreValue(existing.Subscore, normalized.Subscore)
|
||||
if err != nil {
|
||||
return Record{}, err
|
||||
}
|
||||
case OperatorSet:
|
||||
default:
|
||||
return Record{}, fmt.Errorf("%w: unsupported operator %q", ErrInvalidDefinition, definition.Operator)
|
||||
}
|
||||
}
|
||||
before := m.snapshotStateLocked()
|
||||
recordMap[normalized.OwnerID] = record
|
||||
var trimmed []Record
|
||||
if definition.MaxSize > 0 {
|
||||
// 内存实现按 MaxSize 裁剪只保证当前进程视角;跨服榜生产应使用 Redis/SQL 方案。
|
||||
trimmed = m.trimLocked(definition)
|
||||
}
|
||||
if err := m.appendHistoryLocked(ctx, HistoryActionSubmit, definition.ID, &record, nil, record.UpdatedAt); err != nil {
|
||||
m.restoreStateLocked(before)
|
||||
return Record{}, err
|
||||
}
|
||||
for _, trimmedRecord := range trimmed {
|
||||
if err := m.appendHistoryLocked(ctx, HistoryActionTrimRecord, definition.ID, &trimmedRecord, nil, m.now().UTC()); err != nil {
|
||||
m.restoreStateLocked(before)
|
||||
return Record{}, err
|
||||
}
|
||||
}
|
||||
ranked, ok := m.recordWithRankLocked(leaderboardID, normalized.OwnerID)
|
||||
if !ok {
|
||||
return Record{}, ErrRecordTrimmed
|
||||
}
|
||||
return ranked, nil
|
||||
}
|
||||
|
||||
func (m *Manager) DeleteRecord(ctx context.Context, leaderboardID string, ownerID string) (Record, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return Record{}, err
|
||||
}
|
||||
if m == nil {
|
||||
return Record{}, ErrManagerRequired
|
||||
}
|
||||
leaderboardID = strings.TrimSpace(leaderboardID)
|
||||
ownerID = strings.TrimSpace(ownerID)
|
||||
if leaderboardID == "" {
|
||||
return Record{}, ErrLeaderboardNotFound
|
||||
}
|
||||
if ownerID == "" {
|
||||
return Record{}, ErrRecordNotFound
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.ensureReadyLocked()
|
||||
|
||||
if _, ok := m.definitions[leaderboardID]; !ok {
|
||||
return Record{}, ErrLeaderboardNotFound
|
||||
}
|
||||
record, ok := m.recordWithRankLocked(leaderboardID, ownerID)
|
||||
if !ok {
|
||||
return Record{}, ErrRecordNotFound
|
||||
}
|
||||
before := m.snapshotStateLocked()
|
||||
delete(m.records[leaderboardID], ownerID)
|
||||
if err := m.appendHistoryLocked(ctx, HistoryActionDeleteRecord, leaderboardID, &record, nil, m.now().UTC()); err != nil {
|
||||
m.restoreStateLocked(before)
|
||||
return Record{}, err
|
||||
}
|
||||
return record, nil
|
||||
}
|
||||
|
||||
func (m *Manager) Repair(ctx context.Context, leaderboardID string, request RepairRequest) (RepairReceipt, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return RepairReceipt{}, err
|
||||
}
|
||||
if m == nil {
|
||||
return RepairReceipt{}, ErrManagerRequired
|
||||
}
|
||||
leaderboardID = strings.TrimSpace(leaderboardID)
|
||||
if leaderboardID == "" {
|
||||
return RepairReceipt{}, ErrLeaderboardNotFound
|
||||
}
|
||||
normalized, err := normRepairReq(request)
|
||||
if err != nil {
|
||||
return RepairReceipt{}, err
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.ensureReadyLocked()
|
||||
|
||||
definition, ok := m.definitions[leaderboardID]
|
||||
if !ok {
|
||||
return RepairReceipt{}, ErrLeaderboardNotFound
|
||||
}
|
||||
repairKey := repairIdempotencyKey(leaderboardID, normalized.RequestID)
|
||||
if repairKey != "" {
|
||||
// GM 修榜必须支持 request_id 重放,避免审批系统或网络重试重复修改成绩。
|
||||
if previous, ok := m.repairs[repairKey]; ok {
|
||||
return cloneRepairReceipt(previous), nil
|
||||
}
|
||||
}
|
||||
now := m.now().UTC()
|
||||
receipt := RepairReceipt{
|
||||
LeaderboardID: leaderboardID,
|
||||
OwnerID: normalized.OwnerID,
|
||||
Action: HistoryActionRepairRecord,
|
||||
Reason: normalized.Reason,
|
||||
OperatorID: normalized.OperatorID,
|
||||
RequestID: normalized.RequestID,
|
||||
Metadata: cloneStringMap(normalized.Metadata),
|
||||
At: now,
|
||||
}
|
||||
if before, found := m.recordWithRankLocked(leaderboardID, normalized.OwnerID); found {
|
||||
before := before
|
||||
receipt.Before = &before
|
||||
}
|
||||
stateBefore := m.snapshotStateLocked()
|
||||
if normalized.Delete {
|
||||
if receipt.Before == nil {
|
||||
return RepairReceipt{}, ErrRecordNotFound
|
||||
}
|
||||
// 删除和改分都写 history,方便后续审计、回滚和跨节点重建。
|
||||
delete(m.records[leaderboardID], normalized.OwnerID)
|
||||
if err := m.appendHistoryEntry(ctx, repairHistoryEntry(receipt, nil)); err != nil {
|
||||
m.restoreStateLocked(stateBefore)
|
||||
return RepairReceipt{}, err
|
||||
}
|
||||
if repairKey != "" {
|
||||
m.repairs[repairKey] = cloneRepairReceipt(receipt)
|
||||
}
|
||||
return cloneRepairReceipt(receipt), nil
|
||||
}
|
||||
createdAt := now
|
||||
if receipt.Before != nil && !normalized.ResetCreatedAt {
|
||||
createdAt = receipt.Before.CreatedAt
|
||||
}
|
||||
record := Record{
|
||||
LeaderboardID: leaderboardID,
|
||||
OwnerID: normalized.OwnerID,
|
||||
Score: normalized.Score,
|
||||
Subscore: normalized.Subscore,
|
||||
Metadata: cloneStringMap(normalized.Metadata),
|
||||
CreatedAt: createdAt,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
m.records[leaderboardID][record.OwnerID] = record
|
||||
trimmed := m.trimLocked(definition)
|
||||
if after, found := m.recordWithRankLocked(leaderboardID, record.OwnerID); found {
|
||||
after := after
|
||||
receipt.After = &after
|
||||
}
|
||||
if err := m.appendHistoryEntry(ctx, repairHistoryEntry(receipt, receipt.After)); err != nil {
|
||||
m.restoreStateLocked(stateBefore)
|
||||
return RepairReceipt{}, err
|
||||
}
|
||||
for _, trimmedRecord := range trimmed {
|
||||
if err := m.appendHistoryLocked(ctx, HistoryActionTrimRecord, definition.ID, &trimmedRecord, nil, now); err != nil {
|
||||
m.restoreStateLocked(stateBefore)
|
||||
return RepairReceipt{}, err
|
||||
}
|
||||
}
|
||||
if repairKey != "" {
|
||||
m.repairs[repairKey] = cloneRepairReceipt(receipt)
|
||||
}
|
||||
return cloneRepairReceipt(receipt), nil
|
||||
}
|
||||
|
||||
func (m *Manager) Record(leaderboardID string, ownerID string) (Record, bool) {
|
||||
leaderboardID = strings.TrimSpace(leaderboardID)
|
||||
ownerID = strings.TrimSpace(ownerID)
|
||||
if m == nil || leaderboardID == "" || ownerID == "" {
|
||||
return Record{}, false
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.ensureReadyLocked()
|
||||
data, ok := m.rankDataLocked(leaderboardID)
|
||||
m.mu.Unlock()
|
||||
if !ok {
|
||||
return Record{}, false
|
||||
}
|
||||
return recordWithRank(data.definition, data.records, ownerID)
|
||||
}
|
||||
|
||||
func (m *Manager) List(ctx context.Context, leaderboardID string, options ListOptions) ([]Record, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if m == nil {
|
||||
return nil, ErrManagerRequired
|
||||
}
|
||||
leaderboardID = strings.TrimSpace(leaderboardID)
|
||||
if leaderboardID == "" {
|
||||
return nil, ErrLeaderboardNotFound
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.ensureReadyLocked()
|
||||
data, ok := m.rankDataLocked(leaderboardID)
|
||||
m.mu.Unlock()
|
||||
if !ok {
|
||||
return nil, ErrLeaderboardNotFound
|
||||
}
|
||||
ranked := rankRecords(data.definition, data.records)
|
||||
offset, limit := normalizeListOptions(options)
|
||||
if offset >= len(ranked) {
|
||||
return []Record{}, nil
|
||||
}
|
||||
end := offset + limit
|
||||
if end > len(ranked) {
|
||||
end = len(ranked)
|
||||
}
|
||||
return cloneRecords(ranked[offset:end]), nil
|
||||
}
|
||||
|
||||
func (m *Manager) AroundOwner(ctx context.Context, leaderboardID string, ownerID string, limit int) ([]Record, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if m == nil {
|
||||
return nil, ErrManagerRequired
|
||||
}
|
||||
leaderboardID = strings.TrimSpace(leaderboardID)
|
||||
ownerID = strings.TrimSpace(ownerID)
|
||||
if leaderboardID == "" {
|
||||
return nil, ErrLeaderboardNotFound
|
||||
}
|
||||
if ownerID == "" {
|
||||
return nil, ErrRecordNotFound
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.ensureReadyLocked()
|
||||
data, ok := m.rankDataLocked(leaderboardID)
|
||||
m.mu.Unlock()
|
||||
if !ok {
|
||||
return nil, ErrLeaderboardNotFound
|
||||
}
|
||||
ranked := rankRecords(data.definition, data.records)
|
||||
idx := -1
|
||||
for i, record := range ranked {
|
||||
if record.OwnerID == ownerID {
|
||||
idx = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if idx < 0 {
|
||||
return nil, ErrRecordNotFound
|
||||
}
|
||||
if limit <= 0 {
|
||||
limit = defaultAroundLimit
|
||||
}
|
||||
if limit > maxListLimit {
|
||||
limit = maxListLimit
|
||||
}
|
||||
if limit > len(ranked) {
|
||||
limit = len(ranked)
|
||||
}
|
||||
start := idx - limit/2
|
||||
if start < 0 {
|
||||
start = 0
|
||||
}
|
||||
end := start + limit
|
||||
if end > len(ranked) {
|
||||
end = len(ranked)
|
||||
start = end - limit
|
||||
if start < 0 {
|
||||
start = 0
|
||||
}
|
||||
}
|
||||
return cloneRecords(ranked[start:end]), nil
|
||||
}
|
||||
|
||||
func (m *Manager) Rank(ctx context.Context, leaderboardID string, ownerID string) (int, bool, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
if m == nil {
|
||||
return 0, false, ErrManagerRequired
|
||||
}
|
||||
leaderboardID = strings.TrimSpace(leaderboardID)
|
||||
ownerID = strings.TrimSpace(ownerID)
|
||||
if leaderboardID == "" {
|
||||
return 0, false, ErrLeaderboardNotFound
|
||||
}
|
||||
if ownerID == "" {
|
||||
return 0, false, nil
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.ensureReadyLocked()
|
||||
data, ok := m.rankDataLocked(leaderboardID)
|
||||
m.mu.Unlock()
|
||||
if !ok {
|
||||
return 0, false, ErrLeaderboardNotFound
|
||||
}
|
||||
record, ok := recordWithRank(data.definition, data.records, ownerID)
|
||||
return record.Rank, ok, nil
|
||||
}
|
||||
|
||||
func (m *Manager) Reset(ctx context.Context, leaderboardID string) (Definition, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return Definition{}, err
|
||||
}
|
||||
if m == nil {
|
||||
return Definition{}, ErrManagerRequired
|
||||
}
|
||||
leaderboardID = strings.TrimSpace(leaderboardID)
|
||||
if leaderboardID == "" {
|
||||
return Definition{}, ErrLeaderboardNotFound
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.ensureReadyLocked()
|
||||
|
||||
definition, ok := m.definitions[leaderboardID]
|
||||
if !ok {
|
||||
return Definition{}, ErrLeaderboardNotFound
|
||||
}
|
||||
before := m.snapshotStateLocked()
|
||||
definition.UpdatedAt = m.now().UTC()
|
||||
m.definitions[leaderboardID] = definition
|
||||
m.records[leaderboardID] = make(map[string]Record)
|
||||
if err := m.appendHistoryLocked(ctx, HistoryActionReset, definition.ID, nil, &definition, definition.UpdatedAt); err != nil {
|
||||
m.restoreStateLocked(before)
|
||||
return Definition{}, err
|
||||
}
|
||||
return cloneDefinition(definition), nil
|
||||
}
|
||||
|
||||
func (m *Manager) Capture(ctx context.Context, leaderboardID string, options CaptureOptions) (Capture, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return Capture{}, err
|
||||
}
|
||||
if m == nil {
|
||||
return Capture{}, ErrManagerRequired
|
||||
}
|
||||
leaderboardID = strings.TrimSpace(leaderboardID)
|
||||
if leaderboardID == "" {
|
||||
return Capture{}, ErrLeaderboardNotFound
|
||||
}
|
||||
normalized := normCaptureOpts(options)
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.ensureReadyLocked()
|
||||
|
||||
if _, ok := m.definitions[leaderboardID]; !ok {
|
||||
return Capture{}, ErrLeaderboardNotFound
|
||||
}
|
||||
ranked := m.rankedRecordsLocked(leaderboardID)
|
||||
limit := normalized.Limit
|
||||
if limit > len(ranked) {
|
||||
limit = len(ranked)
|
||||
}
|
||||
capture := Capture{
|
||||
LeaderboardID: leaderboardID,
|
||||
Records: cloneRecords(ranked[:limit]),
|
||||
RecordCount: len(ranked),
|
||||
Reason: normalized.Reason,
|
||||
OperatorID: normalized.OperatorID,
|
||||
RequestID: normalized.RequestID,
|
||||
Metadata: cloneStringMap(normalized.Metadata),
|
||||
CapturedAt: m.now().UTC(),
|
||||
}
|
||||
if err := m.appendHistoryEntry(ctx, HistoryEntry{
|
||||
Action: HistoryActionCapture,
|
||||
LeaderboardID: leaderboardID,
|
||||
Records: capture.Records,
|
||||
Reason: capture.Reason,
|
||||
OperatorID: capture.OperatorID,
|
||||
RequestID: capture.RequestID,
|
||||
Metadata: capture.Metadata,
|
||||
At: capture.CapturedAt,
|
||||
}); err != nil {
|
||||
return Capture{}, err
|
||||
}
|
||||
return cloneCapture(capture), nil
|
||||
}
|
||||
|
||||
func (m *Manager) History(ctx context.Context, leaderboardID string, limit int) ([]HistoryEntry, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if m == nil {
|
||||
return nil, ErrManagerRequired
|
||||
}
|
||||
leaderboardID = strings.TrimSpace(leaderboardID)
|
||||
if leaderboardID == "" {
|
||||
return nil, ErrLeaderboardNotFound
|
||||
}
|
||||
if limit <= 0 {
|
||||
limit = defaultListLimit
|
||||
}
|
||||
if limit > maxListLimit {
|
||||
limit = maxListLimit
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
m.ensureReadyLocked()
|
||||
store := m.hist
|
||||
strict := m.historyStrict
|
||||
m.mu.Unlock()
|
||||
if store == nil {
|
||||
return []HistoryEntry{}, nil
|
||||
}
|
||||
history, err := store.List(ctx, leaderboardID, limit)
|
||||
if err != nil {
|
||||
m.mu.Lock()
|
||||
m.historyErrors++
|
||||
m.mu.Unlock()
|
||||
if strict {
|
||||
return nil, err
|
||||
}
|
||||
return []HistoryEntry{}, nil
|
||||
}
|
||||
return history, nil
|
||||
}
|
||||
|
||||
func (m *Manager) Snapshot() Snapshot {
|
||||
if m == nil {
|
||||
return Snapshot{}
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.ensureReadyLocked()
|
||||
|
||||
snapshot := Snapshot{
|
||||
Name: m.name,
|
||||
LeaderboardCount: len(m.definitions),
|
||||
RecordsByBoard: make(map[string]int, len(m.records)),
|
||||
HistoryStoreErrors: m.historyErrors + intFromU64Sat(historyErrors(m.hist)),
|
||||
}
|
||||
for id, records := range m.records {
|
||||
if len(records) == 0 {
|
||||
continue
|
||||
}
|
||||
snapshot.RecordCount += len(records)
|
||||
snapshot.RecordsByBoard[id] = len(records)
|
||||
}
|
||||
if len(snapshot.RecordsByBoard) == 0 {
|
||||
snapshot.RecordsByBoard = nil
|
||||
}
|
||||
return snapshot
|
||||
}
|
||||
|
||||
// Flush 刷新排行榜历史异步队列。
|
||||
func (m *Manager) Flush(ctx context.Context) error {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.ensureReadyLocked()
|
||||
store := m.hist
|
||||
m.mu.Unlock()
|
||||
return flushHistory(ctx, store)
|
||||
}
|
||||
|
||||
// Close 关闭排行榜历史异步队列。
|
||||
func (m *Manager) Close(ctx context.Context) error {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.ensureReadyLocked()
|
||||
store := m.hist
|
||||
m.mu.Unlock()
|
||||
return closeHistory(ctx, store)
|
||||
}
|
||||
|
||||
func (m *Manager) ensureReadyLocked() {
|
||||
if m.name == "" {
|
||||
m.name = "leaderboard"
|
||||
}
|
||||
if m.now == nil {
|
||||
m.now = time.Now
|
||||
}
|
||||
if m.definitions == nil {
|
||||
m.definitions = make(map[string]Definition)
|
||||
}
|
||||
if m.records == nil {
|
||||
m.records = make(map[string]map[string]Record)
|
||||
}
|
||||
if m.repairs == nil {
|
||||
m.repairs = make(map[string]RepairReceipt)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) snapshotStateLocked() managerStateSnapshot {
|
||||
return managerStateSnapshot{
|
||||
definitions: cloneDefinitionMap(m.definitions),
|
||||
records: cloneRecordMap(m.records),
|
||||
repairs: cloneRepairMap(m.repairs),
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) restoreStateLocked(snapshot managerStateSnapshot) {
|
||||
m.definitions = cloneDefinitionMap(snapshot.definitions)
|
||||
m.records = cloneRecordMap(snapshot.records)
|
||||
m.repairs = cloneRepairMap(snapshot.repairs)
|
||||
}
|
||||
|
||||
func (m *Manager) normDefinitionLocked(definition Definition) (Definition, error) {
|
||||
definition.ID = strings.TrimSpace(definition.ID)
|
||||
if definition.ID == "" {
|
||||
definition.ID = m.nextIDLocked("leaderboard")
|
||||
}
|
||||
definition.Title = strings.TrimSpace(definition.Title)
|
||||
sortOrder, err := normalizeSortOrder(definition.SortOrder)
|
||||
if err != nil {
|
||||
return Definition{}, err
|
||||
}
|
||||
operator, err := normalizeOperator(definition.Operator)
|
||||
if err != nil {
|
||||
return Definition{}, err
|
||||
}
|
||||
definition.SortOrder = sortOrder
|
||||
definition.Operator = operator
|
||||
if definition.MaxSize < 0 {
|
||||
return Definition{}, fmt.Errorf("%w: max_size must not be negative", ErrInvalidDefinition)
|
||||
}
|
||||
now := m.now().UTC()
|
||||
if definition.CreatedAt.IsZero() {
|
||||
definition.CreatedAt = now
|
||||
} else {
|
||||
definition.CreatedAt = definition.CreatedAt.UTC()
|
||||
}
|
||||
if definition.UpdatedAt.IsZero() {
|
||||
definition.UpdatedAt = definition.CreatedAt
|
||||
} else {
|
||||
definition.UpdatedAt = definition.UpdatedAt.UTC()
|
||||
}
|
||||
definition.Metadata = cloneStringMap(definition.Metadata)
|
||||
return definition, nil
|
||||
}
|
||||
|
||||
func (m *Manager) rankedRecordsLocked(leaderboardID string) []Record {
|
||||
data, ok := m.rankDataLocked(leaderboardID)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return rankRecords(data.definition, data.records)
|
||||
}
|
||||
|
||||
func (m *Manager) rankDataLocked(leaderboardID string) (boardRankData, bool) {
|
||||
definition, ok := m.definitions[leaderboardID]
|
||||
if !ok {
|
||||
return boardRankData{}, false
|
||||
}
|
||||
return boardRankData{
|
||||
definition: cloneDefinition(definition),
|
||||
records: cloneRecordSet(m.records[leaderboardID]),
|
||||
}, true
|
||||
}
|
||||
|
||||
func rankRecords(definition Definition, records map[string]Record) []Record {
|
||||
out := make([]Record, 0, len(records))
|
||||
for _, record := range records {
|
||||
out = append(out, cloneRecord(record))
|
||||
}
|
||||
sort.SliceStable(out, func(i, j int) bool {
|
||||
return compareRecords(out[i], out[j], definition.SortOrder) < 0
|
||||
})
|
||||
for i := range out {
|
||||
out[i].Rank = i + 1
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (m *Manager) recordWithRankLocked(leaderboardID string, ownerID string) (Record, bool) {
|
||||
ranked := m.rankedRecordsLocked(leaderboardID)
|
||||
return recordFromRanked(ranked, ownerID)
|
||||
}
|
||||
|
||||
func recordWithRank(definition Definition, records map[string]Record, ownerID string) (Record, bool) {
|
||||
return recordFromRanked(rankRecords(definition, records), ownerID)
|
||||
}
|
||||
|
||||
func recordFromRanked(ranked []Record, ownerID string) (Record, bool) {
|
||||
for _, record := range ranked {
|
||||
if record.OwnerID == ownerID {
|
||||
return cloneRecord(record), true
|
||||
}
|
||||
}
|
||||
return Record{}, false
|
||||
}
|
||||
|
||||
func (m *Manager) trimLocked(definition Definition) []Record {
|
||||
if definition.MaxSize <= 0 {
|
||||
return nil
|
||||
}
|
||||
ranked := m.rankedRecordsLocked(definition.ID)
|
||||
if len(ranked) <= definition.MaxSize {
|
||||
return nil
|
||||
}
|
||||
keep := make(map[string]struct{}, definition.MaxSize)
|
||||
for _, record := range ranked[:definition.MaxSize] {
|
||||
keep[record.OwnerID] = struct{}{}
|
||||
}
|
||||
trimmed := cloneRecords(ranked[definition.MaxSize:])
|
||||
for ownerID := range m.records[definition.ID] {
|
||||
if _, ok := keep[ownerID]; !ok {
|
||||
delete(m.records[definition.ID], ownerID)
|
||||
}
|
||||
}
|
||||
return trimmed
|
||||
}
|
||||
|
||||
func (m *Manager) appendHistoryLocked(ctx context.Context, action string, leaderboardID string, record *Record, definition *Definition, at time.Time) error {
|
||||
if at.IsZero() {
|
||||
at = m.now().UTC()
|
||||
} else {
|
||||
at = at.UTC()
|
||||
}
|
||||
entry := HistoryEntry{
|
||||
Action: action,
|
||||
LeaderboardID: strings.TrimSpace(leaderboardID),
|
||||
At: at,
|
||||
}
|
||||
if record != nil {
|
||||
cloned := cloneRecord(*record)
|
||||
entry.OwnerID = cloned.OwnerID
|
||||
entry.Record = &cloned
|
||||
}
|
||||
if definition != nil {
|
||||
cloned := cloneDefinition(*definition)
|
||||
entry.Definition = &cloned
|
||||
}
|
||||
return m.appendHistoryEntry(ctx, entry)
|
||||
}
|
||||
|
||||
func (m *Manager) appendHistoryEntry(ctx context.Context, entry HistoryEntry) error {
|
||||
if m.hist == nil {
|
||||
return nil
|
||||
}
|
||||
entry = cloneHistoryEntry(entry)
|
||||
entry.LeaderboardID = strings.TrimSpace(entry.LeaderboardID)
|
||||
entry.Action = strings.TrimSpace(entry.Action)
|
||||
entry.OwnerID = strings.TrimSpace(entry.OwnerID)
|
||||
entry.Reason = strings.TrimSpace(entry.Reason)
|
||||
entry.OperatorID = strings.TrimSpace(entry.OperatorID)
|
||||
entry.RequestID = strings.TrimSpace(entry.RequestID)
|
||||
entry.Metadata = cloneStringMap(entry.Metadata)
|
||||
if entry.At.IsZero() {
|
||||
entry.At = m.now().UTC()
|
||||
} else {
|
||||
entry.At = entry.At.UTC()
|
||||
}
|
||||
if err := m.hist.Append(ctx, entry); err != nil {
|
||||
m.historyErrors++
|
||||
if m.historyStrict {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Manager) nextIDLocked(prefix string) string {
|
||||
if m.gen != nil {
|
||||
if id := strings.TrimSpace(m.gen(prefix)); id != "" {
|
||||
return id
|
||||
}
|
||||
}
|
||||
m.next++
|
||||
return fmt.Sprintf("%s-%d", prefix, m.next)
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package leaderboard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (m *Manager) MergedView(ctx context.Context, options MergedViewOptions) (MergedView, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return MergedView{}, err
|
||||
}
|
||||
if m == nil {
|
||||
return MergedView{}, ErrManagerRequired
|
||||
}
|
||||
normalized, err := normMergedViewOpts(options)
|
||||
if err != nil {
|
||||
return MergedView{}, err
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
m.ensureReadyLocked()
|
||||
sources := make([]boardRankData, 0, len(normalized.IDs))
|
||||
for _, id := range normalized.IDs {
|
||||
data, ok := m.rankDataLocked(id)
|
||||
if !ok {
|
||||
m.mu.Unlock()
|
||||
return MergedView{}, ErrLeaderboardNotFound
|
||||
}
|
||||
sources = append(sources, data)
|
||||
}
|
||||
generatedAt := m.now().UTC()
|
||||
m.mu.Unlock()
|
||||
|
||||
records := make([]Record, 0)
|
||||
for _, data := range sources {
|
||||
records = append(records, rankRecords(data.definition, data.records)...)
|
||||
}
|
||||
return buildMergedView(normalized, records, generatedAt), nil
|
||||
}
|
||||
|
||||
func (m *RedisManager) MergedView(ctx context.Context, options MergedViewOptions) (MergedView, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return MergedView{}, err
|
||||
}
|
||||
normalized, err := normMergedViewOpts(options)
|
||||
if err != nil {
|
||||
return MergedView{}, err
|
||||
}
|
||||
|
||||
records := make([]Record, 0)
|
||||
for _, id := range normalized.IDs {
|
||||
if _, ok, err := m.definition(ctx, id); err != nil || !ok {
|
||||
if err != nil {
|
||||
return MergedView{}, err
|
||||
}
|
||||
return MergedView{}, ErrLeaderboardNotFound
|
||||
}
|
||||
ranked, err := m.rankedRecords(ctx, id)
|
||||
if err != nil {
|
||||
return MergedView{}, err
|
||||
}
|
||||
records = append(records, ranked...)
|
||||
}
|
||||
return buildMergedView(normalized, records, m.nowUTC()), nil
|
||||
}
|
||||
|
||||
func normMergedViewOpts(options MergedViewOptions) (MergedViewOptions, error) {
|
||||
ids := make([]string, 0, len(options.IDs))
|
||||
seen := make(map[string]struct{}, len(options.IDs))
|
||||
for _, id := range options.IDs {
|
||||
id = strings.TrimSpace(id)
|
||||
if id == "" {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[id]; ok {
|
||||
continue
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return MergedViewOptions{}, fmt.Errorf("%w: ids are required", ErrInvalidDefinition)
|
||||
}
|
||||
sortOrder, err := normalizeSortOrder(options.SortOrder)
|
||||
if err != nil {
|
||||
return MergedViewOptions{}, err
|
||||
}
|
||||
options.IDs = ids
|
||||
options.SortOrder = sortOrder
|
||||
return options, nil
|
||||
}
|
||||
|
||||
func buildMergedView(options MergedViewOptions, records []Record, generatedAt time.Time) MergedView {
|
||||
records = cloneRecords(records)
|
||||
sort.SliceStable(records, func(i, j int) bool {
|
||||
return compareRecords(records[i], records[j], options.SortOrder) < 0
|
||||
})
|
||||
if options.DedupeOwner {
|
||||
records = dedupeMergedRecords(records)
|
||||
}
|
||||
for i := range records {
|
||||
records[i].Rank = i + 1
|
||||
}
|
||||
|
||||
total := len(records)
|
||||
offset, limit := normalizeListOptions(ListOptions{Offset: options.Offset, Limit: options.Limit})
|
||||
if offset >= len(records) {
|
||||
records = []Record{}
|
||||
} else {
|
||||
end := offset + limit
|
||||
if end > len(records) {
|
||||
end = len(records)
|
||||
}
|
||||
records = cloneRecords(records[offset:end])
|
||||
}
|
||||
return MergedView{
|
||||
IDs: append([]string(nil), options.IDs...),
|
||||
SortOrder: options.SortOrder,
|
||||
Records: records,
|
||||
RecordCount: total,
|
||||
GeneratedAt: generatedAt.UTC(),
|
||||
}
|
||||
}
|
||||
|
||||
func dedupeMergedRecords(records []Record) []Record {
|
||||
seen := make(map[string]struct{}, len(records))
|
||||
out := make([]Record, 0, len(records))
|
||||
for _, record := range records {
|
||||
if _, ok := seen[record.OwnerID]; ok {
|
||||
continue
|
||||
}
|
||||
seen[record.OwnerID] = struct{}{}
|
||||
out = append(out, record)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,751 @@
|
||||
package leaderboard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"longheng.io/server/internal/platform/db"
|
||||
"longheng.io/server/internal/platform/eventlog"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNilRedisExecutor = errors.New("leaderboard redis executor is required")
|
||||
ErrRedisLockToken = errors.New("leaderboard redis lock token generation failed")
|
||||
)
|
||||
|
||||
const (
|
||||
defRedisHistory = defaultHistoryLimit
|
||||
defaultRedisLockTTL = 5 * time.Second
|
||||
defRedisBoardPrefix = "longheng:leaderboards"
|
||||
defRedisBoardMgr = "redis-leaderboard"
|
||||
)
|
||||
|
||||
type RedisOptions struct {
|
||||
Name string
|
||||
Executor db.RedisExecutor
|
||||
KeyPrefix string
|
||||
Now func() time.Time
|
||||
HistoryLimit int
|
||||
HistoryStore HistoryStore
|
||||
HistoryStrict bool
|
||||
EventLog *eventlog.Log
|
||||
EventLogStrict bool
|
||||
EventLogStream string
|
||||
EventLogType string
|
||||
LockTTL time.Duration
|
||||
}
|
||||
|
||||
type RedisManager struct {
|
||||
name string
|
||||
executor db.RedisExecutor
|
||||
prefix string
|
||||
now func() time.Time
|
||||
historyLimit int
|
||||
historyStore HistoryStore
|
||||
historyStrict bool
|
||||
historyErrors uint64
|
||||
eventLog *eventlog.Log
|
||||
eventHist HistoryStore
|
||||
eventLogStrict bool
|
||||
eventLogStream string
|
||||
eventLogType string
|
||||
eventLogErrors uint64
|
||||
lockTTL time.Duration
|
||||
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func NewRedis(options RedisOptions) *RedisManager {
|
||||
name := strings.TrimSpace(options.Name)
|
||||
if name == "" {
|
||||
name = defRedisBoardMgr
|
||||
}
|
||||
now := options.Now
|
||||
if now == nil {
|
||||
now = time.Now
|
||||
}
|
||||
historyLimit := options.HistoryLimit
|
||||
if historyLimit == 0 {
|
||||
historyLimit = defRedisHistory
|
||||
}
|
||||
lockTTL := options.LockTTL
|
||||
if lockTTL <= 0 {
|
||||
lockTTL = defaultRedisLockTTL
|
||||
}
|
||||
historyStore := wrapHistoryStore(options.HistoryStore, options.HistoryStrict)
|
||||
eventLog := options.EventLog
|
||||
var eventHist HistoryStore
|
||||
if eventLog != nil && !options.EventLogStrict {
|
||||
eventHist = NewAsyncHistoryStore(newEventHistoryStore(eventLog, options.EventLogStream, options.EventLogType))
|
||||
eventLog = nil
|
||||
}
|
||||
return &RedisManager{
|
||||
name: name,
|
||||
executor: options.Executor,
|
||||
prefix: normRedisBoardPrefix(options.KeyPrefix),
|
||||
now: now,
|
||||
historyLimit: historyLimit,
|
||||
historyStore: historyStore,
|
||||
historyStrict: options.HistoryStrict,
|
||||
eventLog: eventLog,
|
||||
eventHist: eventHist,
|
||||
eventLogStrict: options.EventLogStrict,
|
||||
eventLogStream: normalizeEventStream(options.EventLogStream),
|
||||
eventLogType: normHistoryEventType(options.EventLogType),
|
||||
lockTTL: lockTTL,
|
||||
}
|
||||
}
|
||||
|
||||
func (m *RedisManager) Create(ctx context.Context, definition Definition) (Definition, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return Definition{}, err
|
||||
}
|
||||
normalized, err := m.normalizeDefinition(ctx, definition)
|
||||
if err != nil {
|
||||
return Definition{}, err
|
||||
}
|
||||
data, err := json.Marshal(normalized)
|
||||
if err != nil {
|
||||
return Definition{}, err
|
||||
}
|
||||
history, err := m.historyData(HistoryActionCreate, normalized.ID, nil, &normalized, normalized.CreatedAt)
|
||||
if err != nil {
|
||||
return Definition{}, err
|
||||
}
|
||||
result, err := m.redisEvalInt(ctx, redisCreateScript, []string{
|
||||
m.definitionKey(normalized.ID),
|
||||
m.indexKey(),
|
||||
m.historyKey(normalized.ID),
|
||||
}, normalized.ID, data, history, m.historyLimitValue())
|
||||
if err != nil {
|
||||
return Definition{}, err
|
||||
}
|
||||
if result < 0 {
|
||||
return Definition{}, ErrLeaderboardExists
|
||||
}
|
||||
if err := m.appendHistoryData(ctx, history); err != nil {
|
||||
return Definition{}, err
|
||||
}
|
||||
return cloneDefinition(normalized), nil
|
||||
}
|
||||
|
||||
func (m *RedisManager) Delete(ctx context.Context, leaderboardID string) (Definition, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return Definition{}, err
|
||||
}
|
||||
leaderboardID = strings.TrimSpace(leaderboardID)
|
||||
if leaderboardID == "" {
|
||||
return Definition{}, ErrLeaderboardNotFound
|
||||
}
|
||||
var deleted Definition
|
||||
err := m.withLeaderboardLock(ctx, leaderboardID, func() error {
|
||||
definition, ok, err := m.definition(ctx, leaderboardID)
|
||||
if err != nil || !ok {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ErrLeaderboardNotFound
|
||||
}
|
||||
history, err := m.historyData(HistoryDeleteBoard, definition.ID, nil, &definition, m.nowUTC())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result, err := m.redisEvalInt(ctx, redisDeleteScript, []string{
|
||||
m.definitionKey(definition.ID),
|
||||
m.recordsKey(definition.ID),
|
||||
m.zsetKey(definition.ID),
|
||||
m.indexKey(),
|
||||
m.historyKey(definition.ID),
|
||||
}, definition.ID, history, m.historyLimitValue())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if result < 0 {
|
||||
return ErrLeaderboardNotFound
|
||||
}
|
||||
if err := m.appendHistoryData(ctx, history); err != nil {
|
||||
return err
|
||||
}
|
||||
deleted = definition
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return Definition{}, err
|
||||
}
|
||||
return deleted, nil
|
||||
}
|
||||
|
||||
func (m *RedisManager) Definition(leaderboardID string) (Definition, bool) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
definition, ok, err := m.DefinitionContext(ctx, leaderboardID)
|
||||
if err != nil {
|
||||
return Definition{}, false
|
||||
}
|
||||
return definition, ok
|
||||
}
|
||||
|
||||
// DefinitionContext 让生产读路径区分 Redis 故障和榜单不存在,避免把后端抖动误判为业务空结果。
|
||||
func (m *RedisManager) DefinitionContext(ctx context.Context, leaderboardID string) (Definition, bool, error) {
|
||||
return m.definition(ctx, leaderboardID)
|
||||
}
|
||||
|
||||
func (m *RedisManager) Definitions() []Definition {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
definitions, err := m.DefinitionsContext(ctx)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return definitions
|
||||
}
|
||||
|
||||
// DefinitionsContext 让管理面在 Redis 故障时返回错误,而不是把榜单列表显示为空。
|
||||
func (m *RedisManager) DefinitionsContext(ctx context.Context) ([]Definition, error) {
|
||||
return m.definitions(ctx)
|
||||
}
|
||||
|
||||
func (m *RedisManager) Submit(ctx context.Context, leaderboardID string, submission Submission) (Record, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return Record{}, err
|
||||
}
|
||||
leaderboardID = strings.TrimSpace(leaderboardID)
|
||||
if leaderboardID == "" {
|
||||
return Record{}, ErrLeaderboardNotFound
|
||||
}
|
||||
normalized, err := normalizeSubmission(submission)
|
||||
if err != nil {
|
||||
return Record{}, err
|
||||
}
|
||||
var out Record
|
||||
err = m.withLeaderboardLock(ctx, leaderboardID, func() error {
|
||||
definition, ok, err := m.definition(ctx, leaderboardID)
|
||||
if err != nil || !ok {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ErrLeaderboardNotFound
|
||||
}
|
||||
existing, exists, err := m.record(ctx, definition.ID, normalized.OwnerID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
now := m.nowUTC()
|
||||
record := Record{
|
||||
LeaderboardID: definition.ID,
|
||||
OwnerID: normalized.OwnerID,
|
||||
Score: normalized.Score,
|
||||
Subscore: normalized.Subscore,
|
||||
Metadata: cloneStringMap(normalized.Metadata),
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
if exists {
|
||||
record.CreatedAt = existing.CreatedAt
|
||||
switch definition.Operator {
|
||||
case OperatorBest:
|
||||
if !betterThan(record, existing, definition.SortOrder) {
|
||||
ranked, ok, err := m.recordWithRank(ctx, definition.ID, normalized.OwnerID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
return ErrRecordNotFound
|
||||
}
|
||||
out = ranked
|
||||
return nil
|
||||
}
|
||||
case OperatorIncrement:
|
||||
record.Score, err = addScoreValue(existing.Score, normalized.Score)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
record.Subscore, err = addScoreValue(existing.Subscore, normalized.Subscore)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
case OperatorSet:
|
||||
default:
|
||||
return fmt.Errorf("%w: unsupported operator %q", ErrInvalidDefinition, definition.Operator)
|
||||
}
|
||||
}
|
||||
if err := m.saveRecord(ctx, definition, record); err != nil {
|
||||
return err
|
||||
}
|
||||
if definition.MaxSize > 0 {
|
||||
if err := m.trim(ctx, definition); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
ranked, ok, err := m.recordWithRank(ctx, definition.ID, normalized.OwnerID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
return ErrRecordTrimmed
|
||||
}
|
||||
out = ranked
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return Record{}, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (m *RedisManager) DeleteRecord(ctx context.Context, leaderboardID string, ownerID string) (Record, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return Record{}, err
|
||||
}
|
||||
leaderboardID = strings.TrimSpace(leaderboardID)
|
||||
if leaderboardID == "" {
|
||||
return Record{}, ErrLeaderboardNotFound
|
||||
}
|
||||
ownerID = strings.TrimSpace(ownerID)
|
||||
if ownerID == "" {
|
||||
return Record{}, ErrRecordNotFound
|
||||
}
|
||||
var deleted Record
|
||||
err := m.withLeaderboardLock(ctx, leaderboardID, func() error {
|
||||
definition, ok, err := m.definition(ctx, leaderboardID)
|
||||
if err != nil || !ok {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ErrLeaderboardNotFound
|
||||
}
|
||||
record, ok, err := m.recordWithRank(ctx, definition.ID, ownerID)
|
||||
if err != nil || !ok {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ErrRecordNotFound
|
||||
}
|
||||
if err := m.deleteRecords(ctx, definition, []Record{record}, HistoryActionDeleteRecord); err != nil {
|
||||
return err
|
||||
}
|
||||
deleted = record
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return Record{}, err
|
||||
}
|
||||
return deleted, nil
|
||||
}
|
||||
|
||||
func (m *RedisManager) Repair(ctx context.Context, leaderboardID string, request RepairRequest) (RepairReceipt, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return RepairReceipt{}, err
|
||||
}
|
||||
leaderboardID = strings.TrimSpace(leaderboardID)
|
||||
if leaderboardID == "" {
|
||||
return RepairReceipt{}, ErrLeaderboardNotFound
|
||||
}
|
||||
normalized, err := normRepairReq(request)
|
||||
if err != nil {
|
||||
return RepairReceipt{}, err
|
||||
}
|
||||
var receipt RepairReceipt
|
||||
err = m.withLeaderboardLock(ctx, leaderboardID, func() error {
|
||||
definition, ok, err := m.definition(ctx, leaderboardID)
|
||||
if err != nil || !ok {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ErrLeaderboardNotFound
|
||||
}
|
||||
now := m.nowUTC()
|
||||
receipt = RepairReceipt{
|
||||
LeaderboardID: definition.ID,
|
||||
OwnerID: normalized.OwnerID,
|
||||
Action: HistoryActionRepairRecord,
|
||||
Reason: normalized.Reason,
|
||||
OperatorID: normalized.OperatorID,
|
||||
RequestID: normalized.RequestID,
|
||||
Metadata: cloneStringMap(normalized.Metadata),
|
||||
At: now,
|
||||
}
|
||||
if before, found, err := m.recordWithRank(ctx, definition.ID, normalized.OwnerID); err != nil {
|
||||
return err
|
||||
} else if found {
|
||||
before := before
|
||||
receipt.Before = &before
|
||||
}
|
||||
details := HistoryDetails{
|
||||
Reason: normalized.Reason,
|
||||
OperatorID: normalized.OperatorID,
|
||||
RequestID: normalized.RequestID,
|
||||
Metadata: cloneStringMap(normalized.Metadata),
|
||||
}
|
||||
if normalized.Delete {
|
||||
if receipt.Before == nil {
|
||||
return ErrRecordNotFound
|
||||
}
|
||||
if err := m.delRecordsDetail(ctx, definition, []Record{*receipt.Before}, HistoryActionRepairRecord, details); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
createdAt := now
|
||||
if receipt.Before != nil && !normalized.ResetCreatedAt {
|
||||
createdAt = receipt.Before.CreatedAt
|
||||
}
|
||||
record := Record{
|
||||
LeaderboardID: definition.ID,
|
||||
OwnerID: normalized.OwnerID,
|
||||
Score: normalized.Score,
|
||||
Subscore: normalized.Subscore,
|
||||
Metadata: cloneStringMap(normalized.Metadata),
|
||||
CreatedAt: createdAt,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
if err := m.saveRecordDetails(ctx, definition, record, HistoryActionRepairRecord, details); err != nil {
|
||||
return err
|
||||
}
|
||||
if definition.MaxSize > 0 {
|
||||
if err := m.trim(ctx, definition); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if after, found, err := m.recordWithRank(ctx, definition.ID, normalized.OwnerID); err != nil {
|
||||
return err
|
||||
} else if found {
|
||||
after := after
|
||||
receipt.After = &after
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return RepairReceipt{}, err
|
||||
}
|
||||
return cloneRepairReceipt(receipt), nil
|
||||
}
|
||||
|
||||
func (m *RedisManager) Record(leaderboardID string, ownerID string) (Record, bool) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
leaderboardID = strings.TrimSpace(leaderboardID)
|
||||
ownerID = strings.TrimSpace(ownerID)
|
||||
if leaderboardID == "" || ownerID == "" {
|
||||
return Record{}, false
|
||||
}
|
||||
record, found, err := m.recordWithRank(ctx, leaderboardID, ownerID)
|
||||
if err != nil {
|
||||
return Record{}, false
|
||||
}
|
||||
return record, found
|
||||
}
|
||||
|
||||
func (m *RedisManager) List(ctx context.Context, leaderboardID string, options ListOptions) ([]Record, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
leaderboardID = strings.TrimSpace(leaderboardID)
|
||||
if leaderboardID == "" {
|
||||
return nil, ErrLeaderboardNotFound
|
||||
}
|
||||
if _, ok, err := m.definition(ctx, leaderboardID); err != nil || !ok {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, ErrLeaderboardNotFound
|
||||
}
|
||||
offset, limit := normalizeListOptions(options)
|
||||
out, err := m.rangeRecords(ctx, leaderboardID, offset, offset+limit-1, offset+1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (m *RedisManager) AroundOwner(ctx context.Context, leaderboardID string, ownerID string, limit int) ([]Record, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ownerID = strings.TrimSpace(ownerID)
|
||||
if ownerID == "" {
|
||||
return nil, ErrRecordNotFound
|
||||
}
|
||||
leaderboardID = strings.TrimSpace(leaderboardID)
|
||||
if leaderboardID == "" {
|
||||
return nil, ErrLeaderboardNotFound
|
||||
}
|
||||
if _, ok, err := m.definition(ctx, leaderboardID); err != nil || !ok {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, ErrLeaderboardNotFound
|
||||
}
|
||||
rank, ok, err := m.redisRank(ctx, leaderboardID, ownerID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return nil, ErrRecordNotFound
|
||||
}
|
||||
if limit <= 0 {
|
||||
limit = defaultAroundLimit
|
||||
}
|
||||
if limit > maxListLimit {
|
||||
limit = maxListLimit
|
||||
}
|
||||
total, err := m.redisInt(ctx, "ZCARD", m.zsetKey(leaderboardID))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if total <= 0 {
|
||||
return nil, ErrRecordNotFound
|
||||
}
|
||||
if limit > int(total) {
|
||||
limit = int(total)
|
||||
}
|
||||
start := rank - 1 - limit/2
|
||||
if start < 0 {
|
||||
start = 0
|
||||
}
|
||||
if start+limit > int(total) {
|
||||
start = int(total) - limit
|
||||
if start < 0 {
|
||||
start = 0
|
||||
}
|
||||
}
|
||||
out, err := m.rangeRecords(ctx, leaderboardID, start, start+limit-1, start+1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (m *RedisManager) Rank(ctx context.Context, leaderboardID string, ownerID string) (int, bool, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
leaderboardID = strings.TrimSpace(leaderboardID)
|
||||
ownerID = strings.TrimSpace(ownerID)
|
||||
if leaderboardID == "" {
|
||||
return 0, false, ErrLeaderboardNotFound
|
||||
}
|
||||
if ownerID == "" {
|
||||
return 0, false, nil
|
||||
}
|
||||
return m.redisRank(ctx, leaderboardID, ownerID)
|
||||
}
|
||||
|
||||
func (m *RedisManager) Reset(ctx context.Context, leaderboardID string) (Definition, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return Definition{}, err
|
||||
}
|
||||
leaderboardID = strings.TrimSpace(leaderboardID)
|
||||
if leaderboardID == "" {
|
||||
return Definition{}, ErrLeaderboardNotFound
|
||||
}
|
||||
var reset Definition
|
||||
err := m.withLeaderboardLock(ctx, leaderboardID, func() error {
|
||||
definition, ok, err := m.definition(ctx, leaderboardID)
|
||||
if err != nil || !ok {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ErrLeaderboardNotFound
|
||||
}
|
||||
definition.UpdatedAt = m.nowUTC()
|
||||
data, err := json.Marshal(definition)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
history, err := m.historyData(HistoryActionReset, definition.ID, nil, &definition, definition.UpdatedAt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result, err := m.redisEvalInt(ctx, redisResetScript, []string{
|
||||
m.definitionKey(definition.ID),
|
||||
m.recordsKey(definition.ID),
|
||||
m.zsetKey(definition.ID),
|
||||
m.historyKey(definition.ID),
|
||||
}, data, history, m.historyLimitValue())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if result < 0 {
|
||||
return ErrLeaderboardNotFound
|
||||
}
|
||||
if err := m.appendHistoryData(ctx, history); err != nil {
|
||||
return err
|
||||
}
|
||||
reset = cloneDefinition(definition)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return Definition{}, err
|
||||
}
|
||||
return reset, nil
|
||||
}
|
||||
|
||||
func (m *RedisManager) Capture(ctx context.Context, leaderboardID string, options CaptureOptions) (Capture, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return Capture{}, err
|
||||
}
|
||||
leaderboardID = strings.TrimSpace(leaderboardID)
|
||||
if leaderboardID == "" {
|
||||
return Capture{}, ErrLeaderboardNotFound
|
||||
}
|
||||
normalized := normCaptureOpts(options)
|
||||
var capture Capture
|
||||
err := m.withLeaderboardLock(ctx, leaderboardID, func() error {
|
||||
if _, ok, err := m.definition(ctx, leaderboardID); err != nil || !ok {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ErrLeaderboardNotFound
|
||||
}
|
||||
ranked, err := m.rankedRecords(ctx, leaderboardID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
limit := normalized.Limit
|
||||
if limit > len(ranked) {
|
||||
limit = len(ranked)
|
||||
}
|
||||
capture = Capture{
|
||||
LeaderboardID: leaderboardID,
|
||||
Records: cloneRecords(ranked[:limit]),
|
||||
RecordCount: len(ranked),
|
||||
Reason: normalized.Reason,
|
||||
OperatorID: normalized.OperatorID,
|
||||
RequestID: normalized.RequestID,
|
||||
Metadata: cloneStringMap(normalized.Metadata),
|
||||
CapturedAt: m.nowUTC(),
|
||||
}
|
||||
history, err := m.historyData(HistoryActionCapture, leaderboardID, nil, nil, capture.CapturedAt, HistoryDetails{
|
||||
Reason: capture.Reason,
|
||||
OperatorID: capture.OperatorID,
|
||||
RequestID: capture.RequestID,
|
||||
Metadata: capture.Metadata,
|
||||
Records: capture.Records,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return m.appendHistoryPayload(ctx, leaderboardID, history)
|
||||
})
|
||||
if err != nil {
|
||||
return Capture{}, err
|
||||
}
|
||||
return cloneCapture(capture), nil
|
||||
}
|
||||
|
||||
func (m *RedisManager) History(ctx context.Context, leaderboardID string, limit int) ([]HistoryEntry, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if m == nil {
|
||||
return nil, ErrNilRedisExecutor
|
||||
}
|
||||
leaderboardID = strings.TrimSpace(leaderboardID)
|
||||
if leaderboardID == "" {
|
||||
return nil, ErrLeaderboardNotFound
|
||||
}
|
||||
if limit <= 0 {
|
||||
limit = defaultListLimit
|
||||
}
|
||||
historyLimit := m.historyLimitValue()
|
||||
if limit > historyLimit && historyLimit > 0 {
|
||||
limit = historyLimit
|
||||
}
|
||||
if m.historyStore != nil {
|
||||
history, err := m.historyStore.List(ctx, leaderboardID, limit)
|
||||
if err == nil {
|
||||
return history, nil
|
||||
}
|
||||
if m.historyStrict {
|
||||
return nil, err
|
||||
}
|
||||
atomic.AddUint64(&m.historyErrors, 1)
|
||||
}
|
||||
value, err := m.do(ctx, "LRANGE", m.historyKey(leaderboardID), -limit, -1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items, err := redisStrings(value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
history := make([]HistoryEntry, 0, len(items))
|
||||
for _, item := range items {
|
||||
var entry HistoryEntry
|
||||
if err := json.Unmarshal([]byte(item), &entry); err != nil {
|
||||
return nil, fmt.Errorf("decode leaderboard history: %w", err)
|
||||
}
|
||||
if entry.Record != nil {
|
||||
cloned := cloneRecord(*entry.Record)
|
||||
entry.Record = &cloned
|
||||
}
|
||||
if entry.Definition != nil {
|
||||
cloned := cloneDefinition(*entry.Definition)
|
||||
entry.Definition = &cloned
|
||||
}
|
||||
history = append(history, entry)
|
||||
}
|
||||
return history, nil
|
||||
}
|
||||
|
||||
func (m *RedisManager) Snapshot() Snapshot {
|
||||
if m == nil {
|
||||
return Snapshot{}
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
definitions, err := m.definitions(ctx)
|
||||
if err != nil {
|
||||
return Snapshot{Name: m.redisName()}
|
||||
}
|
||||
snapshot := Snapshot{
|
||||
Name: m.redisName(),
|
||||
LeaderboardCount: len(definitions),
|
||||
RecordsByBoard: make(map[string]int, len(definitions)),
|
||||
HistoryStoreErrors: intFromU64Sat(atomic.LoadUint64(&m.historyErrors) + historyErrors(m.historyStore)),
|
||||
EventLogErrors: intFromU64Sat(atomic.LoadUint64(&m.eventLogErrors) + historyStoreErrors(m.historyStore) + historyErrors(m.eventHist)),
|
||||
}
|
||||
for _, definition := range definitions {
|
||||
count, err := m.redisInt(ctx, "HLEN", m.recordsKey(definition.ID))
|
||||
if err != nil || count <= 0 {
|
||||
continue
|
||||
}
|
||||
snapshot.RecordCount += int(count)
|
||||
snapshot.RecordsByBoard[definition.ID] = int(count)
|
||||
}
|
||||
if len(snapshot.RecordsByBoard) == 0 {
|
||||
snapshot.RecordsByBoard = nil
|
||||
}
|
||||
return snapshot
|
||||
}
|
||||
|
||||
// Flush 刷新排行榜外部历史和事件异步队列。
|
||||
func (m *RedisManager) Flush(ctx context.Context) error {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
return errors.Join(flushHistory(ctx, m.historyStore), flushHistory(ctx, m.eventHist))
|
||||
}
|
||||
|
||||
// Close 关闭排行榜外部历史和事件异步队列。
|
||||
func (m *RedisManager) Close(ctx context.Context) error {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
return errors.Join(closeHistory(ctx, m.historyStore), closeHistory(ctx, m.eventHist))
|
||||
}
|
||||
|
||||
func intFromU64Sat(value uint64) int {
|
||||
if value > uint64(math.MaxInt) {
|
||||
return math.MaxInt
|
||||
}
|
||||
return int(value) //nolint:gosec // G115:前面已按 int 最大值钳制。
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
package leaderboard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"longheng.io/server/internal/platform/eventlog"
|
||||
)
|
||||
|
||||
func (m *RedisManager) redisInt(ctx context.Context, command string, args ...any) (int64, error) {
|
||||
value, err := m.do(ctx, command, args...)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return redisInt64(value)
|
||||
}
|
||||
|
||||
func (m *RedisManager) redisEvalInt(ctx context.Context, script string, keys []string, args ...any) (int64, error) {
|
||||
params := make([]any, 0, 2+len(keys)+len(args))
|
||||
params = append(params, script, len(keys))
|
||||
for _, key := range keys {
|
||||
params = append(params, key)
|
||||
}
|
||||
params = append(params, args...)
|
||||
value, err := m.do(ctx, "EVAL", params...)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return redisInt64(value)
|
||||
}
|
||||
|
||||
func (m *RedisManager) nextID(ctx context.Context) (string, error) {
|
||||
if m == nil {
|
||||
return "", ErrNilRedisExecutor
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
n, err := m.redisInt(ctx, "INCR", m.counterKey())
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf("leaderboard-%d", n), nil
|
||||
}
|
||||
|
||||
func (m *RedisManager) do(ctx context.Context, command string, args ...any) (any, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if m == nil || m.executor == nil {
|
||||
return nil, ErrNilRedisExecutor
|
||||
}
|
||||
return m.executor.Do(ctx, command, args...)
|
||||
}
|
||||
|
||||
func (m *RedisManager) indexKey() string {
|
||||
return m.redisPrefix() + ":index"
|
||||
}
|
||||
|
||||
func (m *RedisManager) counterKey() string {
|
||||
return m.redisPrefix() + ":counter"
|
||||
}
|
||||
|
||||
func (m *RedisManager) definitionKey(id string) string {
|
||||
return m.redisPrefix() + ":definition:" + strings.TrimSpace(id)
|
||||
}
|
||||
|
||||
func (m *RedisManager) recordsKey(id string) string {
|
||||
return m.redisPrefix() + ":records:" + strings.TrimSpace(id)
|
||||
}
|
||||
|
||||
func (m *RedisManager) zsetKey(id string) string {
|
||||
return m.redisPrefix() + ":z:" + strings.TrimSpace(id)
|
||||
}
|
||||
|
||||
func (m *RedisManager) historyKey(id string) string {
|
||||
return m.redisPrefix() + ":history:" + strings.TrimSpace(id)
|
||||
}
|
||||
|
||||
func (m *RedisManager) lockKey(id string) string {
|
||||
return m.redisPrefix() + ":lock:leaderboard:" + strings.TrimSpace(id)
|
||||
}
|
||||
|
||||
func (m *RedisManager) redisPrefix() string {
|
||||
if m == nil {
|
||||
return defRedisBoardPrefix
|
||||
}
|
||||
return normRedisBoardPrefix(m.prefix)
|
||||
}
|
||||
|
||||
func normRedisBoardPrefix(prefix string) string {
|
||||
prefix = strings.Trim(strings.TrimSpace(prefix), ":")
|
||||
if prefix == "" {
|
||||
return defRedisBoardPrefix
|
||||
}
|
||||
return prefix
|
||||
}
|
||||
|
||||
func (m *RedisManager) redisName() string {
|
||||
if m == nil {
|
||||
return ""
|
||||
}
|
||||
name := strings.TrimSpace(m.name)
|
||||
if name == "" {
|
||||
return defRedisBoardMgr
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
func (m *RedisManager) nowUTC() time.Time {
|
||||
if m == nil || m.now == nil {
|
||||
return time.Now().UTC()
|
||||
}
|
||||
return m.now().UTC()
|
||||
}
|
||||
|
||||
func (m *RedisManager) historyLimitValue() int {
|
||||
if m == nil || m.historyLimit == 0 {
|
||||
return defRedisHistory
|
||||
}
|
||||
return m.historyLimit
|
||||
}
|
||||
|
||||
func (m *RedisManager) lockTTLValue() time.Duration {
|
||||
if m == nil || m.lockTTL <= 0 {
|
||||
return defaultRedisLockTTL
|
||||
}
|
||||
return m.lockTTL
|
||||
}
|
||||
|
||||
func (m *RedisManager) appendHistoryData(ctx context.Context, payloads ...[]byte) error {
|
||||
if len(payloads) == 0 || (m.historyStore == nil && m.eventLog == nil && m.eventHist == nil) {
|
||||
return nil
|
||||
}
|
||||
for _, payload := range payloads {
|
||||
var entry HistoryEntry
|
||||
if err := json.Unmarshal(payload, &entry); err != nil {
|
||||
atomic.AddUint64(&m.historyErrors, 1)
|
||||
if m.historyStrict {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if m.historyStore != nil {
|
||||
if err := m.historyStore.Append(ctx, entry); err != nil {
|
||||
atomic.AddUint64(&m.historyErrors, 1)
|
||||
if m.historyStrict {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if m.eventHist != nil {
|
||||
if err := m.eventHist.Append(ctx, entry); err != nil {
|
||||
atomic.AddUint64(&m.eventLogErrors, 1)
|
||||
if m.eventLogStrict {
|
||||
return err
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err := m.appendEventHistory(ctx, entry); err != nil {
|
||||
atomic.AddUint64(&m.eventLogErrors, 1)
|
||||
if m.eventLogStrict {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *RedisManager) appendEventHistory(ctx context.Context, entry HistoryEntry) error {
|
||||
if m == nil || m.eventLog == nil {
|
||||
return nil
|
||||
}
|
||||
entry = normHistoryEntry(entry)
|
||||
payload, err := json.Marshal(entry)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = m.eventLog.Append(ctx, eventlog.Event{
|
||||
Stream: m.eventLogStream,
|
||||
Type: m.eventLogType,
|
||||
AggregateID: entry.LeaderboardID,
|
||||
IdempotencyKey: historyIdemKey(entry, payload),
|
||||
Payload: payload,
|
||||
Headers: map[string]string{
|
||||
"action": entry.Action,
|
||||
"leaderboard_id": entry.LeaderboardID,
|
||||
"owner_id": entry.OwnerID,
|
||||
},
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func normalizeEventStream(stream string) string {
|
||||
stream = strings.TrimSpace(stream)
|
||||
if stream == "" {
|
||||
return LeaderboardEventStream
|
||||
}
|
||||
return stream
|
||||
}
|
||||
|
||||
func normHistoryEventType(eventType string) string {
|
||||
eventType = strings.TrimSpace(eventType)
|
||||
if eventType == "" {
|
||||
return DefaultLeaderboardHistoryEventType
|
||||
}
|
||||
return eventType
|
||||
}
|
||||
|
||||
func (m *RedisManager) historyData(action string, leaderboardID string, record *Record, definition *Definition, at time.Time, details ...HistoryDetails) ([]byte, error) {
|
||||
if at.IsZero() {
|
||||
at = m.nowUTC()
|
||||
} else {
|
||||
at = at.UTC()
|
||||
}
|
||||
entry := HistoryEntry{
|
||||
Action: action,
|
||||
LeaderboardID: strings.TrimSpace(leaderboardID),
|
||||
At: at,
|
||||
}
|
||||
if len(details) > 0 {
|
||||
detail := details[0]
|
||||
entry.Reason = strings.TrimSpace(detail.Reason)
|
||||
entry.OperatorID = strings.TrimSpace(detail.OperatorID)
|
||||
entry.RequestID = strings.TrimSpace(detail.RequestID)
|
||||
entry.Metadata = cloneStringMap(detail.Metadata)
|
||||
entry.Records = cloneRecords(detail.Records)
|
||||
}
|
||||
if record != nil {
|
||||
cloned := cloneRecord(*record)
|
||||
entry.OwnerID = cloned.OwnerID
|
||||
entry.Record = &cloned
|
||||
}
|
||||
if definition != nil {
|
||||
cloned := cloneDefinition(*definition)
|
||||
entry.Definition = &cloned
|
||||
}
|
||||
return json.Marshal(entry)
|
||||
}
|
||||
|
||||
func redisRankScore(record Record, sortOrder string) float64 {
|
||||
score := float64(record.Score)
|
||||
if sortOrder == SortAscending {
|
||||
return -score
|
||||
}
|
||||
return score
|
||||
}
|
||||
|
||||
func redisBytes(value any) ([]byte, bool, error) {
|
||||
switch v := value.(type) {
|
||||
case nil:
|
||||
return nil, false, nil
|
||||
case []byte:
|
||||
return append([]byte(nil), v...), true, nil
|
||||
case string:
|
||||
return []byte(v), true, nil
|
||||
default:
|
||||
return nil, false, fmt.Errorf("unexpected redis bulk type %T", value)
|
||||
}
|
||||
}
|
||||
|
||||
func redisStrings(value any) ([]string, error) {
|
||||
switch v := value.(type) {
|
||||
case nil:
|
||||
return nil, nil
|
||||
case []string:
|
||||
return append([]string(nil), v...), nil
|
||||
case [][]byte:
|
||||
out := make([]string, len(v))
|
||||
for i := range v {
|
||||
out[i] = string(v[i])
|
||||
}
|
||||
return out, nil
|
||||
case []any:
|
||||
out := make([]string, 0, len(v))
|
||||
for _, item := range v {
|
||||
switch x := item.(type) {
|
||||
case []byte:
|
||||
out = append(out, string(x))
|
||||
case string:
|
||||
out = append(out, x)
|
||||
default:
|
||||
return nil, fmt.Errorf("unexpected redis string item %T", item)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("unexpected redis string slice type %T", value)
|
||||
}
|
||||
}
|
||||
|
||||
func redisBulkBytes(value any) ([][]byte, []bool, error) {
|
||||
switch v := value.(type) {
|
||||
case nil:
|
||||
return nil, nil, nil
|
||||
case []any:
|
||||
data := make([][]byte, len(v))
|
||||
found := make([]bool, len(v))
|
||||
for i, item := range v {
|
||||
bytes, ok, err := redisBytes(item)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
data[i] = bytes
|
||||
found[i] = ok
|
||||
}
|
||||
return data, found, nil
|
||||
case [][]byte:
|
||||
data := make([][]byte, len(v))
|
||||
found := make([]bool, len(v))
|
||||
for i := range v {
|
||||
data[i] = append([]byte(nil), v[i]...)
|
||||
found[i] = true
|
||||
}
|
||||
return data, found, nil
|
||||
default:
|
||||
return nil, nil, fmt.Errorf("unexpected redis bulk slice type %T", value)
|
||||
}
|
||||
}
|
||||
|
||||
func redisInt64(value any) (int64, error) {
|
||||
switch v := value.(type) {
|
||||
case int:
|
||||
return int64(v), nil
|
||||
case int64:
|
||||
return v, nil
|
||||
case uint64:
|
||||
const maxInt64 = uint64(1<<63 - 1)
|
||||
if v > maxInt64 {
|
||||
return 0, fmt.Errorf("redis integer overflows int64: %d", v)
|
||||
}
|
||||
return int64(v), nil
|
||||
case []byte:
|
||||
return strconv.ParseInt(string(v), 10, 64)
|
||||
case string:
|
||||
return strconv.ParseInt(v, 10, 64)
|
||||
default:
|
||||
return 0, fmt.Errorf("unexpected redis integer type %T", value)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package leaderboard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
lockkit "longheng.io/server/internal/platform/lock"
|
||||
)
|
||||
|
||||
var redisLockRandRead = rand.Read
|
||||
|
||||
func (m *RedisManager) withLeaderboardLock(ctx context.Context, leaderboardID string, fn func() error) error {
|
||||
if m == nil || m.executor == nil {
|
||||
return ErrNilRedisExecutor
|
||||
}
|
||||
leaderboardID = strings.TrimSpace(leaderboardID)
|
||||
if leaderboardID == "" {
|
||||
return ErrLeaderboardNotFound
|
||||
}
|
||||
token, err := redisLockToken()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := m.acquireLbLock(ctx, leaderboardID, token); err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
releaseCtx, cancel := detachedTimeoutCtx(ctx, time.Second)
|
||||
defer cancel()
|
||||
_ = m.releaseLbLock(releaseCtx, leaderboardID, token)
|
||||
}()
|
||||
return fn()
|
||||
}
|
||||
|
||||
func redisLockToken() (string, error) {
|
||||
var raw [16]byte
|
||||
if _, err := redisLockRandRead(raw[:]); err != nil {
|
||||
return "", fmt.Errorf("%w: %w", ErrRedisLockToken, err)
|
||||
}
|
||||
return hex.EncodeToString(raw[:]), nil
|
||||
}
|
||||
|
||||
func (m *RedisManager) acquireLbLock(ctx context.Context, leaderboardID string, token string) error {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
if m == nil || m.executor == nil {
|
||||
return ErrNilRedisExecutor
|
||||
}
|
||||
for {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
ok, err := lockkit.AcquireRedis(ctx, m.executor, m.lockKey(leaderboardID), token, m.lockTTLValue())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ok {
|
||||
return nil
|
||||
}
|
||||
timer := time.NewTimer(10 * time.Millisecond)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (m *RedisManager) releaseLbLock(ctx context.Context, leaderboardID string, token string) error {
|
||||
if m == nil || m.executor == nil {
|
||||
return ErrNilRedisExecutor
|
||||
}
|
||||
err := lockkit.ReleaseRedis(ctx, m.executor, m.lockKey(leaderboardID), token)
|
||||
if errors.Is(err, lockkit.ErrTokenMismatch) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func detachedTimeoutCtx(parent context.Context, timeout time.Duration) (context.Context, context.CancelFunc) {
|
||||
if parent == nil {
|
||||
return context.WithTimeout(context.Background(), timeout)
|
||||
}
|
||||
return context.WithTimeout(context.WithoutCancel(parent), timeout)
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package leaderboard
|
||||
|
||||
const redisCreateScript = `
|
||||
if redis.call("EXISTS", KEYS[1]) == 1 then
|
||||
return -1
|
||||
end
|
||||
redis.call("SET", KEYS[1], ARGV[2])
|
||||
redis.call("SADD", KEYS[2], ARGV[1])
|
||||
local limit = tonumber(ARGV[4])
|
||||
if limit > 0 then
|
||||
redis.call("RPUSH", KEYS[3], ARGV[3])
|
||||
redis.call("LTRIM", KEYS[3], -limit, -1)
|
||||
end
|
||||
return 1
|
||||
`
|
||||
|
||||
const redisDeleteScript = `
|
||||
if redis.call("EXISTS", KEYS[1]) == 0 then
|
||||
return -1
|
||||
end
|
||||
redis.call("DEL", KEYS[1], KEYS[2], KEYS[3])
|
||||
redis.call("SREM", KEYS[4], ARGV[1])
|
||||
local limit = tonumber(ARGV[3])
|
||||
if limit > 0 then
|
||||
redis.call("RPUSH", KEYS[5], ARGV[2])
|
||||
redis.call("LTRIM", KEYS[5], -limit, -1)
|
||||
end
|
||||
return 1
|
||||
`
|
||||
|
||||
const redisSaveRecord = `
|
||||
redis.call("HSET", KEYS[1], ARGV[1], ARGV[2])
|
||||
redis.call("ZADD", KEYS[2], ARGV[3], ARGV[1])
|
||||
local limit = tonumber(ARGV[5])
|
||||
if limit > 0 then
|
||||
redis.call("RPUSH", KEYS[3], ARGV[4])
|
||||
redis.call("LTRIM", KEYS[3], -limit, -1)
|
||||
end
|
||||
return 1
|
||||
`
|
||||
|
||||
const redisDeleteRecords = `
|
||||
local count = tonumber(ARGV[1])
|
||||
local limit = tonumber(ARGV[2])
|
||||
local offset = 3
|
||||
for i = 1, count do
|
||||
local owner_id = ARGV[offset]
|
||||
local history = ARGV[offset + 1]
|
||||
redis.call("HDEL", KEYS[1], owner_id)
|
||||
redis.call("ZREM", KEYS[2], owner_id)
|
||||
if limit > 0 then
|
||||
redis.call("RPUSH", KEYS[3], history)
|
||||
end
|
||||
offset = offset + 2
|
||||
end
|
||||
if limit > 0 then
|
||||
redis.call("LTRIM", KEYS[3], -limit, -1)
|
||||
end
|
||||
return count
|
||||
`
|
||||
|
||||
const redisResetScript = `
|
||||
if redis.call("EXISTS", KEYS[1]) == 0 then
|
||||
return -1
|
||||
end
|
||||
redis.call("SET", KEYS[1], ARGV[1])
|
||||
redis.call("DEL", KEYS[2], KEYS[3])
|
||||
local limit = tonumber(ARGV[3])
|
||||
if limit > 0 then
|
||||
redis.call("RPUSH", KEYS[4], ARGV[2])
|
||||
redis.call("LTRIM", KEYS[4], -limit, -1)
|
||||
end
|
||||
return 1
|
||||
`
|
||||
@@ -0,0 +1,315 @@
|
||||
package leaderboard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func (m *RedisManager) normalizeDefinition(ctx context.Context, definition Definition) (Definition, error) {
|
||||
if m == nil {
|
||||
return Definition{}, ErrNilRedisExecutor
|
||||
}
|
||||
definition.ID = strings.TrimSpace(definition.ID)
|
||||
if definition.ID == "" {
|
||||
id, err := m.nextID(ctx)
|
||||
if err != nil {
|
||||
return Definition{}, err
|
||||
}
|
||||
definition.ID = id
|
||||
}
|
||||
definition.Title = strings.TrimSpace(definition.Title)
|
||||
sortOrder, err := normalizeSortOrder(definition.SortOrder)
|
||||
if err != nil {
|
||||
return Definition{}, err
|
||||
}
|
||||
operator, err := normalizeOperator(definition.Operator)
|
||||
if err != nil {
|
||||
return Definition{}, err
|
||||
}
|
||||
definition.SortOrder = sortOrder
|
||||
definition.Operator = operator
|
||||
if definition.MaxSize < 0 {
|
||||
return Definition{}, fmt.Errorf("%w: max_size must not be negative", ErrInvalidDefinition)
|
||||
}
|
||||
now := m.nowUTC()
|
||||
if definition.CreatedAt.IsZero() {
|
||||
definition.CreatedAt = now
|
||||
} else {
|
||||
definition.CreatedAt = definition.CreatedAt.UTC()
|
||||
}
|
||||
if definition.UpdatedAt.IsZero() {
|
||||
definition.UpdatedAt = definition.CreatedAt
|
||||
} else {
|
||||
definition.UpdatedAt = definition.UpdatedAt.UTC()
|
||||
}
|
||||
definition.Metadata = cloneStringMap(definition.Metadata)
|
||||
return definition, nil
|
||||
}
|
||||
|
||||
func (m *RedisManager) definitions(ctx context.Context) ([]Definition, error) {
|
||||
value, err := m.do(ctx, "SMEMBERS", m.indexKey())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids, err := redisStrings(value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
definitions := make([]Definition, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
definition, ok, err := m.definition(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
_, _ = m.do(ctx, "SREM", m.indexKey(), id)
|
||||
continue
|
||||
}
|
||||
definitions = append(definitions, definition)
|
||||
}
|
||||
sort.Slice(definitions, func(i, j int) bool { return definitions[i].ID < definitions[j].ID })
|
||||
return definitions, nil
|
||||
}
|
||||
|
||||
func (m *RedisManager) definition(ctx context.Context, leaderboardID string) (Definition, bool, error) {
|
||||
leaderboardID = strings.TrimSpace(leaderboardID)
|
||||
if leaderboardID == "" {
|
||||
return Definition{}, false, nil
|
||||
}
|
||||
value, err := m.do(ctx, "GET", m.definitionKey(leaderboardID))
|
||||
if err != nil {
|
||||
return Definition{}, false, err
|
||||
}
|
||||
data, ok, err := redisBytes(value)
|
||||
if err != nil || !ok {
|
||||
if err != nil {
|
||||
return Definition{}, false, err
|
||||
}
|
||||
return Definition{}, false, nil
|
||||
}
|
||||
var definition Definition
|
||||
if err := json.Unmarshal(data, &definition); err != nil {
|
||||
return Definition{}, false, fmt.Errorf("decode leaderboard definition: %w", err)
|
||||
}
|
||||
return cloneDefinition(definition), true, nil
|
||||
}
|
||||
|
||||
func (m *RedisManager) saveRecord(ctx context.Context, definition Definition, record Record) error {
|
||||
return m.saveRecordDetails(ctx, definition, record, HistoryActionSubmit, HistoryDetails{})
|
||||
}
|
||||
|
||||
func (m *RedisManager) saveRecordDetails(ctx context.Context, definition Definition, record Record, action string, details HistoryDetails) error {
|
||||
data, err := json.Marshal(record)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
history, err := m.historyData(action, definition.ID, &record, nil, record.UpdatedAt, details)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = m.redisEvalInt(ctx, redisSaveRecord, []string{
|
||||
m.recordsKey(definition.ID),
|
||||
m.zsetKey(definition.ID),
|
||||
m.historyKey(definition.ID),
|
||||
}, record.OwnerID, data, redisRankScore(record, definition.SortOrder), history, m.historyLimitValue())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return m.appendHistoryData(ctx, history)
|
||||
}
|
||||
|
||||
func (m *RedisManager) record(ctx context.Context, leaderboardID string, ownerID string) (Record, bool, error) {
|
||||
leaderboardID = strings.TrimSpace(leaderboardID)
|
||||
ownerID = strings.TrimSpace(ownerID)
|
||||
if leaderboardID == "" || ownerID == "" {
|
||||
return Record{}, false, nil
|
||||
}
|
||||
value, err := m.do(ctx, "HGET", m.recordsKey(leaderboardID), ownerID)
|
||||
if err != nil {
|
||||
return Record{}, false, err
|
||||
}
|
||||
data, ok, err := redisBytes(value)
|
||||
if err != nil || !ok {
|
||||
if err != nil {
|
||||
return Record{}, false, err
|
||||
}
|
||||
return Record{}, false, nil
|
||||
}
|
||||
var record Record
|
||||
if err := json.Unmarshal(data, &record); err != nil {
|
||||
return Record{}, false, fmt.Errorf("decode leaderboard record: %w", err)
|
||||
}
|
||||
return cloneRecord(record), true, nil
|
||||
}
|
||||
|
||||
func (m *RedisManager) rankedRecords(ctx context.Context, leaderboardID string) ([]Record, error) {
|
||||
definition, ok, err := m.definition(ctx, leaderboardID)
|
||||
if err != nil || !ok {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, ErrLeaderboardNotFound
|
||||
}
|
||||
return m.rangeRecords(ctx, definition.ID, 0, -1, 1)
|
||||
}
|
||||
|
||||
func (m *RedisManager) rangeRecords(ctx context.Context, leaderboardID string, start int, stop int, rankStart int) ([]Record, error) {
|
||||
value, err := m.do(ctx, "ZREVRANGE", m.zsetKey(leaderboardID), start, stop)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
owners, err := redisStrings(value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(owners) == 0 {
|
||||
return []Record{}, nil
|
||||
}
|
||||
return m.recordsByOwners(ctx, leaderboardID, owners, rankStart)
|
||||
}
|
||||
|
||||
func (m *RedisManager) recordsByOwners(ctx context.Context, leaderboardID string, owners []string, rankStart int) ([]Record, error) {
|
||||
if len(owners) == 0 {
|
||||
return []Record{}, nil
|
||||
}
|
||||
args := make([]any, 0, len(owners)+1)
|
||||
args = append(args, m.recordsKey(leaderboardID))
|
||||
for _, ownerID := range owners {
|
||||
args = append(args, ownerID)
|
||||
}
|
||||
value, err := m.do(ctx, "HMGET", args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items, found, err := redisBulkBytes(value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]Record, 0, len(owners))
|
||||
for idx, ownerID := range owners {
|
||||
if idx >= len(items) || idx >= len(found) || !found[idx] {
|
||||
_, _ = m.do(ctx, "ZREM", m.zsetKey(leaderboardID), ownerID)
|
||||
continue
|
||||
}
|
||||
var record Record
|
||||
if err := json.Unmarshal(items[idx], &record); err != nil {
|
||||
_, _ = m.do(ctx, "HDEL", m.recordsKey(leaderboardID), ownerID)
|
||||
_, _ = m.do(ctx, "ZREM", m.zsetKey(leaderboardID), ownerID)
|
||||
continue
|
||||
}
|
||||
record.Rank = rankStart + idx
|
||||
out = append(out, cloneRecord(record))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (m *RedisManager) recordWithRank(ctx context.Context, leaderboardID string, ownerID string) (Record, bool, error) {
|
||||
leaderboardID = strings.TrimSpace(leaderboardID)
|
||||
ownerID = strings.TrimSpace(ownerID)
|
||||
if leaderboardID == "" {
|
||||
return Record{}, false, ErrLeaderboardNotFound
|
||||
}
|
||||
if ownerID == "" {
|
||||
return Record{}, false, nil
|
||||
}
|
||||
rank, ok, err := m.redisRank(ctx, leaderboardID, ownerID)
|
||||
if err != nil {
|
||||
return Record{}, false, err
|
||||
}
|
||||
if !ok {
|
||||
return Record{}, false, nil
|
||||
}
|
||||
record, ok, err := m.record(ctx, leaderboardID, ownerID)
|
||||
if err != nil || !ok {
|
||||
if err != nil {
|
||||
return Record{}, false, err
|
||||
}
|
||||
_, _ = m.do(ctx, "ZREM", m.zsetKey(leaderboardID), ownerID)
|
||||
return Record{}, false, nil
|
||||
}
|
||||
record.Rank = rank
|
||||
return cloneRecord(record), true, nil
|
||||
}
|
||||
|
||||
func (m *RedisManager) redisRank(ctx context.Context, leaderboardID string, ownerID string) (int, bool, error) {
|
||||
value, err := m.do(ctx, "ZREVRANK", m.zsetKey(leaderboardID), ownerID)
|
||||
if err != nil || value == nil {
|
||||
if err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
return 0, false, nil
|
||||
}
|
||||
rank, err := redisInt64(value)
|
||||
if err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
return int(rank) + 1, true, nil
|
||||
}
|
||||
|
||||
func (m *RedisManager) trim(ctx context.Context, definition Definition) error {
|
||||
if definition.MaxSize <= 0 {
|
||||
return nil
|
||||
}
|
||||
total, err := m.redisInt(ctx, "ZCARD", m.zsetKey(definition.ID))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if total <= int64(definition.MaxSize) {
|
||||
return nil
|
||||
}
|
||||
trimmed, err := m.rangeRecords(ctx, definition.ID, definition.MaxSize, -1, definition.MaxSize+1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return m.deleteRecords(ctx, definition, trimmed, HistoryActionTrimRecord)
|
||||
}
|
||||
|
||||
func (m *RedisManager) deleteRecords(ctx context.Context, definition Definition, records []Record, action string) error {
|
||||
return m.delRecordsDetail(ctx, definition, records, action, HistoryDetails{})
|
||||
}
|
||||
|
||||
func (m *RedisManager) delRecordsDetail(ctx context.Context, definition Definition, records []Record, action string, details HistoryDetails) error {
|
||||
if len(records) == 0 {
|
||||
return nil
|
||||
}
|
||||
args := make([]any, 0, 2+len(records)*2)
|
||||
args = append(args, len(records), m.historyLimitValue())
|
||||
histories := make([][]byte, 0, len(records))
|
||||
now := m.nowUTC()
|
||||
for _, record := range records {
|
||||
history, err := m.historyData(action, definition.ID, &record, nil, now, details)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
args = append(args, record.OwnerID, history)
|
||||
histories = append(histories, history)
|
||||
}
|
||||
_, err := m.redisEvalInt(ctx, redisDeleteRecords, []string{
|
||||
m.recordsKey(definition.ID),
|
||||
m.zsetKey(definition.ID),
|
||||
m.historyKey(definition.ID),
|
||||
}, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return m.appendHistoryData(ctx, histories...)
|
||||
}
|
||||
|
||||
func (m *RedisManager) appendHistoryPayload(ctx context.Context, leaderboardID string, history []byte) error {
|
||||
if len(history) == 0 {
|
||||
return nil
|
||||
}
|
||||
historyLimit := m.historyLimitValue()
|
||||
if historyLimit > 0 {
|
||||
if _, err := m.do(ctx, "RPUSH", m.historyKey(leaderboardID), history); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := m.do(ctx, "LTRIM", m.historyKey(leaderboardID), -historyLimit, -1); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return m.appendHistoryData(ctx, history)
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
package leaderboard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidSettlement = fmt.Errorf("%w: settlement is invalid", ErrInvalidSubmission)
|
||||
ErrNilRewardOutbox = errors.New("leaderboard reward outbox is required")
|
||||
)
|
||||
|
||||
const RewardOutboxPending = "pending"
|
||||
|
||||
type RewardRule struct {
|
||||
MinRank int `json:"min_rank"`
|
||||
MaxRank int `json:"max_rank"`
|
||||
Payload json.RawMessage `json:"payload,omitempty"`
|
||||
}
|
||||
|
||||
type RewardOptions struct {
|
||||
SettlementID string `json:"settlement_id"`
|
||||
Rules []RewardRule `json:"rules"`
|
||||
}
|
||||
|
||||
type RewardGrant struct {
|
||||
SettlementID string `json:"settlement_id"`
|
||||
LeaderboardID string `json:"leaderboard_id"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
Rank int `json:"rank"`
|
||||
Score int64 `json:"score"`
|
||||
Subscore int64 `json:"subscore,omitempty"`
|
||||
IdempotencyKey string `json:"idempotency_key"`
|
||||
Payload json.RawMessage `json:"payload,omitempty"`
|
||||
}
|
||||
|
||||
type RewardOutboxEvent struct {
|
||||
ID string `json:"id"`
|
||||
Grant RewardGrant `json:"grant"`
|
||||
Status string `json:"status"`
|
||||
Attempts int `json:"attempts,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type RewardOutbox interface {
|
||||
EnqueueRewardGrants(context.Context, []RewardGrant) ([]RewardOutboxEvent, error)
|
||||
PendingRewardGrants(context.Context, int) ([]RewardOutboxEvent, error)
|
||||
}
|
||||
|
||||
type MemoryRewardOutbox struct {
|
||||
mu sync.Mutex
|
||||
now func() time.Time
|
||||
order []string
|
||||
events map[string]RewardOutboxEvent
|
||||
}
|
||||
|
||||
type SeasonSettlementOptions struct {
|
||||
SettlementID string `json:"settlement_id"`
|
||||
RewardRules []RewardRule `json:"reward_rules,omitempty"`
|
||||
RewardOutbox RewardOutbox `json:"-"`
|
||||
CaptureLimit int `json:"capture_limit,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
OperatorID string `json:"operator_id,omitempty"`
|
||||
RequestID string `json:"request_id,omitempty"`
|
||||
}
|
||||
|
||||
type SeasonSettlement struct {
|
||||
SettlementID string `json:"settlement_id"`
|
||||
LeaderboardID string `json:"leaderboard_id"`
|
||||
Capture Capture `json:"capture"`
|
||||
Grants []RewardGrant `json:"grants"`
|
||||
OutboxEvents []RewardOutboxEvent `json:"outbox_events,omitempty"`
|
||||
Reset Definition `json:"reset"`
|
||||
}
|
||||
|
||||
func NewMemoryRewardOutbox(now func() time.Time) *MemoryRewardOutbox {
|
||||
if now == nil {
|
||||
now = time.Now
|
||||
}
|
||||
return &MemoryRewardOutbox{
|
||||
now: now,
|
||||
events: make(map[string]RewardOutboxEvent),
|
||||
}
|
||||
}
|
||||
|
||||
func (o *MemoryRewardOutbox) EnqueueRewardGrants(ctx context.Context, grants []RewardGrant) ([]RewardOutboxEvent, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if o == nil {
|
||||
return nil, ErrNilRewardOutbox
|
||||
}
|
||||
o.mu.Lock()
|
||||
defer o.mu.Unlock()
|
||||
|
||||
// 内存 outbox 以 grant.IdempotencyKey 去重;同 key 不重复追加奖励事件,方便结算任务安全重跑。
|
||||
events := make([]RewardOutboxEvent, 0, len(grants))
|
||||
for _, grant := range grants {
|
||||
normalized := cloneRewardGrant(grant)
|
||||
normalized.IdempotencyKey = strings.TrimSpace(normalized.IdempotencyKey)
|
||||
if normalized.IdempotencyKey == "" {
|
||||
return nil, ErrInvalidSettlement
|
||||
}
|
||||
if existing, ok := o.events[normalized.IdempotencyKey]; ok {
|
||||
events = append(events, cloneRewardOutbox(existing))
|
||||
continue
|
||||
}
|
||||
now := o.now().UTC()
|
||||
event := RewardOutboxEvent{
|
||||
ID: normalized.IdempotencyKey,
|
||||
Grant: normalized,
|
||||
Status: RewardOutboxPending,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
o.order = append(o.order, event.ID)
|
||||
o.events[event.ID] = event
|
||||
events = append(events, cloneRewardOutbox(event))
|
||||
}
|
||||
return events, nil
|
||||
}
|
||||
|
||||
func (o *MemoryRewardOutbox) PendingRewardGrants(ctx context.Context, limit int) ([]RewardOutboxEvent, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if o == nil {
|
||||
return nil, ErrNilRewardOutbox
|
||||
}
|
||||
if limit <= 0 || limit > maxListLimit {
|
||||
limit = maxListLimit
|
||||
}
|
||||
o.mu.Lock()
|
||||
defer o.mu.Unlock()
|
||||
|
||||
events := make([]RewardOutboxEvent, 0, limit)
|
||||
for _, id := range o.order {
|
||||
event := o.events[id]
|
||||
if event.Status != RewardOutboxPending {
|
||||
continue
|
||||
}
|
||||
events = append(events, cloneRewardOutbox(event))
|
||||
if len(events) >= limit {
|
||||
break
|
||||
}
|
||||
}
|
||||
return events, nil
|
||||
}
|
||||
|
||||
func CloseSeason(ctx context.Context, runtime Runtime, leaderboardID string, options SeasonSettlementOptions) (SeasonSettlement, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return SeasonSettlement{}, err
|
||||
}
|
||||
if runtime == nil {
|
||||
return SeasonSettlement{}, ErrLeaderboardNotFound
|
||||
}
|
||||
settlementID := strings.TrimSpace(options.SettlementID)
|
||||
if settlementID == "" {
|
||||
return SeasonSettlement{}, ErrInvalidSettlement
|
||||
}
|
||||
// 结算顺序固定为:截榜快照 -> 生成奖励幂等键 -> 写奖励 outbox -> 可选清榜,避免清榜后丢奖励证据。
|
||||
capture, err := runtime.Capture(ctx, leaderboardID, CaptureOptions{
|
||||
Limit: options.CaptureLimit,
|
||||
Reason: options.Reason,
|
||||
OperatorID: options.OperatorID,
|
||||
RequestID: options.RequestID,
|
||||
Metadata: map[string]string{"settlement_id": settlementID},
|
||||
})
|
||||
if err != nil {
|
||||
return SeasonSettlement{}, err
|
||||
}
|
||||
grants, err := BuildRewardGrants(capture, RewardOptions{SettlementID: settlementID, Rules: options.RewardRules})
|
||||
if err != nil {
|
||||
return SeasonSettlement{}, err
|
||||
}
|
||||
var events []RewardOutboxEvent
|
||||
if len(grants) > 0 {
|
||||
if options.RewardOutbox == nil {
|
||||
return SeasonSettlement{}, ErrNilRewardOutbox
|
||||
}
|
||||
events, err = options.RewardOutbox.EnqueueRewardGrants(ctx, grants)
|
||||
if err != nil {
|
||||
return SeasonSettlement{}, err
|
||||
}
|
||||
}
|
||||
reset, err := runtime.Reset(ctx, leaderboardID)
|
||||
if err != nil {
|
||||
return SeasonSettlement{}, err
|
||||
}
|
||||
return SeasonSettlement{
|
||||
SettlementID: settlementID,
|
||||
LeaderboardID: strings.TrimSpace(leaderboardID),
|
||||
Capture: cloneCapture(capture),
|
||||
Grants: cloneRewardGrants(grants),
|
||||
OutboxEvents: cloneRewardEvents(events),
|
||||
Reset: cloneDefinition(reset),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func BuildRewardGrants(capture Capture, options RewardOptions) ([]RewardGrant, error) {
|
||||
settlementID := strings.TrimSpace(options.SettlementID)
|
||||
if settlementID == "" || strings.TrimSpace(capture.LeaderboardID) == "" {
|
||||
return nil, ErrInvalidSettlement
|
||||
}
|
||||
rules, err := normalizeRewardRules(options.Rules)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(rules) == 0 || len(capture.Records) == 0 {
|
||||
return []RewardGrant{}, nil
|
||||
}
|
||||
// 奖励幂等键由 settlement/leaderboard/player/rank 组成,同一次结算重放不会重复发奖。
|
||||
grants := make([]RewardGrant, 0, len(capture.Records))
|
||||
for _, record := range capture.Records {
|
||||
if strings.TrimSpace(record.OwnerID) == "" || record.Rank <= 0 {
|
||||
continue
|
||||
}
|
||||
rule, ok := rewardRuleForRank(rules, record.Rank)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
grants = append(grants, RewardGrant{
|
||||
SettlementID: settlementID,
|
||||
LeaderboardID: strings.TrimSpace(capture.LeaderboardID),
|
||||
OwnerID: strings.TrimSpace(record.OwnerID),
|
||||
Rank: record.Rank,
|
||||
Score: record.Score,
|
||||
Subscore: record.Subscore,
|
||||
IdempotencyKey: rewardGrantKey(settlementID, capture.LeaderboardID, record.OwnerID, record.Rank),
|
||||
Payload: cloneRewardPayload(rule.Payload),
|
||||
})
|
||||
}
|
||||
return grants, nil
|
||||
}
|
||||
|
||||
func normalizeRewardRules(rules []RewardRule) ([]RewardRule, error) {
|
||||
out := make([]RewardRule, 0, len(rules))
|
||||
for _, rule := range rules {
|
||||
if rule.MinRank <= 0 {
|
||||
return nil, ErrInvalidSettlement
|
||||
}
|
||||
if rule.MaxRank <= 0 {
|
||||
rule.MaxRank = rule.MinRank
|
||||
}
|
||||
if rule.MaxRank < rule.MinRank {
|
||||
return nil, ErrInvalidSettlement
|
||||
}
|
||||
if len(rule.Payload) > 0 && !json.Valid(rule.Payload) {
|
||||
return nil, ErrInvalidSettlement
|
||||
}
|
||||
rule.Payload = cloneRewardPayload(rule.Payload)
|
||||
out = append(out, rule)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func rewardRuleForRank(rules []RewardRule, rank int) (RewardRule, bool) {
|
||||
for _, rule := range rules {
|
||||
if rank >= rule.MinRank && rank <= rule.MaxRank {
|
||||
return rule, true
|
||||
}
|
||||
}
|
||||
return RewardRule{}, false
|
||||
}
|
||||
|
||||
func rewardGrantKey(settlementID, leaderboardID, ownerID string, rank int) string {
|
||||
return fmt.Sprintf("leaderboard:settlement:v1:%s:%s:%s:%d",
|
||||
encodeKeyPart(settlementID),
|
||||
encodeKeyPart(leaderboardID),
|
||||
encodeKeyPart(ownerID),
|
||||
rank,
|
||||
)
|
||||
}
|
||||
|
||||
func cloneRewardPayload(payload json.RawMessage) json.RawMessage {
|
||||
if payload == nil {
|
||||
return nil
|
||||
}
|
||||
return append(json.RawMessage(nil), payload...)
|
||||
}
|
||||
|
||||
func cloneRewardGrant(grant RewardGrant) RewardGrant {
|
||||
grant.Payload = cloneRewardPayload(grant.Payload)
|
||||
return grant
|
||||
}
|
||||
|
||||
func cloneRewardGrants(grants []RewardGrant) []RewardGrant {
|
||||
out := make([]RewardGrant, len(grants))
|
||||
for i, grant := range grants {
|
||||
out[i] = cloneRewardGrant(grant)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func cloneRewardOutbox(event RewardOutboxEvent) RewardOutboxEvent {
|
||||
event.Grant = cloneRewardGrant(event.Grant)
|
||||
return event
|
||||
}
|
||||
|
||||
func cloneRewardEvents(events []RewardOutboxEvent) []RewardOutboxEvent {
|
||||
out := make([]RewardOutboxEvent, len(events))
|
||||
for i, event := range events {
|
||||
out[i] = cloneRewardOutbox(event)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
package leaderboard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrLeaderboardExists = errors.New("leaderboard already exists")
|
||||
ErrLeaderboardNotFound = errors.New("leaderboard not found")
|
||||
ErrRecordNotFound = errors.New("leaderboard record not found")
|
||||
ErrRecordTrimmed = errors.New("leaderboard record was trimmed")
|
||||
ErrInvalidDefinition = errors.New("leaderboard definition is invalid")
|
||||
ErrInvalidSubmission = errors.New("leaderboard submission is invalid")
|
||||
ErrScoreOverflow = errors.New("leaderboard score overflow")
|
||||
ErrManagerRequired = errors.New("leaderboard manager is required")
|
||||
)
|
||||
|
||||
const (
|
||||
SortDescending = "desc"
|
||||
SortAscending = "asc"
|
||||
|
||||
OperatorBest = "best"
|
||||
OperatorSet = "set"
|
||||
OperatorIncrement = "increment"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultListLimit = 50
|
||||
defaultAroundLimit = 5
|
||||
maxListLimit = 500
|
||||
defaultHistoryLimit = 1000
|
||||
)
|
||||
|
||||
type Runtime interface {
|
||||
Create(context.Context, Definition) (Definition, error)
|
||||
Delete(context.Context, string) (Definition, error)
|
||||
Definition(string) (Definition, bool)
|
||||
Definitions() []Definition
|
||||
Submit(context.Context, string, Submission) (Record, error)
|
||||
DeleteRecord(context.Context, string, string) (Record, error)
|
||||
Repair(context.Context, string, RepairRequest) (RepairReceipt, error)
|
||||
Record(string, string) (Record, bool)
|
||||
List(context.Context, string, ListOptions) ([]Record, error)
|
||||
MergedView(context.Context, MergedViewOptions) (MergedView, error)
|
||||
AroundOwner(context.Context, string, string, int) ([]Record, error)
|
||||
Rank(context.Context, string, string) (int, bool, error)
|
||||
Reset(context.Context, string) (Definition, error)
|
||||
Capture(context.Context, string, CaptureOptions) (Capture, error)
|
||||
History(context.Context, string, int) ([]HistoryEntry, error)
|
||||
Snapshot() Snapshot
|
||||
}
|
||||
|
||||
type Options struct {
|
||||
Name string
|
||||
Now func() time.Time
|
||||
IDGenerator func(prefix string) string
|
||||
HistoryLimit int
|
||||
HistoryStore HistoryStore
|
||||
HistoryStrict bool
|
||||
}
|
||||
|
||||
type Definition struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title,omitempty"`
|
||||
SortOrder string `json:"sort_order"`
|
||||
Operator string `json:"operator"`
|
||||
MaxSize int `json:"max_size,omitempty"`
|
||||
Metadata map[string]string `json:"metadata,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type Submission struct {
|
||||
OwnerID string `json:"owner_id"`
|
||||
Score int64 `json:"score"`
|
||||
Subscore int64 `json:"subscore,omitempty"`
|
||||
Metadata map[string]string `json:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
type Record struct {
|
||||
LeaderboardID string `json:"leaderboard_id"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
Score int64 `json:"score"`
|
||||
Subscore int64 `json:"subscore,omitempty"`
|
||||
Rank int `json:"rank,omitempty"`
|
||||
Metadata map[string]string `json:"metadata,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
const (
|
||||
HistoryActionCreate = "create"
|
||||
HistoryActionSubmit = "submit"
|
||||
HistoryActionDeleteRecord = "delete_record"
|
||||
HistoryActionTrimRecord = "trim_record"
|
||||
HistoryActionReset = "reset"
|
||||
HistoryDeleteBoard = "delete_leaderboard"
|
||||
HistoryActionRepairRecord = "repair_record"
|
||||
HistoryActionCapture = "capture"
|
||||
)
|
||||
|
||||
type HistoryEntry struct {
|
||||
Action string `json:"action"`
|
||||
LeaderboardID string `json:"leaderboard_id"`
|
||||
OwnerID string `json:"owner_id,omitempty"`
|
||||
Record *Record `json:"record,omitempty"`
|
||||
Records []Record `json:"records,omitempty"`
|
||||
Definition *Definition `json:"definition,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
OperatorID string `json:"operator_id,omitempty"`
|
||||
RequestID string `json:"request_id,omitempty"`
|
||||
Metadata map[string]string `json:"metadata,omitempty"`
|
||||
At time.Time `json:"at"`
|
||||
}
|
||||
|
||||
type HistoryDetails struct {
|
||||
Reason string `json:"reason,omitempty"`
|
||||
OperatorID string `json:"operator_id,omitempty"`
|
||||
RequestID string `json:"request_id,omitempty"`
|
||||
Metadata map[string]string `json:"metadata,omitempty"`
|
||||
Records []Record `json:"records,omitempty"`
|
||||
}
|
||||
|
||||
type HistoryStore interface {
|
||||
Append(context.Context, HistoryEntry) error
|
||||
List(context.Context, string, int) ([]HistoryEntry, error)
|
||||
}
|
||||
|
||||
type ListOptions struct {
|
||||
Offset int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type MergedViewOptions struct {
|
||||
IDs []string `json:"ids"`
|
||||
SortOrder string `json:"sort_order,omitempty"`
|
||||
Offset int `json:"offset,omitempty"`
|
||||
Limit int `json:"limit,omitempty"`
|
||||
DedupeOwner bool `json:"dedupe_owner,omitempty"`
|
||||
}
|
||||
|
||||
type MergedView struct {
|
||||
IDs []string `json:"ids"`
|
||||
SortOrder string `json:"sort_order"`
|
||||
Records []Record `json:"records"`
|
||||
RecordCount int `json:"record_count"`
|
||||
GeneratedAt time.Time `json:"generated_at"`
|
||||
}
|
||||
|
||||
type RepairRequest struct {
|
||||
OwnerID string `json:"owner_id"`
|
||||
Score int64 `json:"score,omitempty"`
|
||||
Subscore int64 `json:"subscore,omitempty"`
|
||||
Metadata map[string]string `json:"metadata,omitempty"`
|
||||
Delete bool `json:"delete,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
OperatorID string `json:"operator_id,omitempty"`
|
||||
RequestID string `json:"request_id,omitempty"`
|
||||
ResetCreatedAt bool `json:"reset_created_at,omitempty"`
|
||||
}
|
||||
|
||||
type RepairReceipt struct {
|
||||
LeaderboardID string `json:"leaderboard_id"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
Action string `json:"action"`
|
||||
Before *Record `json:"before,omitempty"`
|
||||
After *Record `json:"after,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
OperatorID string `json:"operator_id,omitempty"`
|
||||
RequestID string `json:"request_id,omitempty"`
|
||||
Metadata map[string]string `json:"metadata,omitempty"`
|
||||
At time.Time `json:"at"`
|
||||
}
|
||||
|
||||
type CaptureOptions struct {
|
||||
Limit int `json:"limit,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
OperatorID string `json:"operator_id,omitempty"`
|
||||
RequestID string `json:"request_id,omitempty"`
|
||||
Metadata map[string]string `json:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
type Capture struct {
|
||||
LeaderboardID string `json:"leaderboard_id"`
|
||||
Records []Record `json:"records"`
|
||||
RecordCount int `json:"record_count"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
OperatorID string `json:"operator_id,omitempty"`
|
||||
RequestID string `json:"request_id,omitempty"`
|
||||
Metadata map[string]string `json:"metadata,omitempty"`
|
||||
CapturedAt time.Time `json:"captured_at"`
|
||||
}
|
||||
|
||||
type Snapshot struct {
|
||||
Name string `json:"name"`
|
||||
LeaderboardCount int `json:"leaderboard_count"`
|
||||
RecordCount int `json:"record_count"`
|
||||
RecordsByBoard map[string]int `json:"records_by_board,omitempty"`
|
||||
HistoryStoreErrors int `json:"history_store_errors,omitempty"`
|
||||
EventLogErrors int `json:"eventlog_errors,omitempty"`
|
||||
}
|
||||
Reference in new issue
Block a user