removed all "paid" features - no more stars, gifts, or grams
This commit is contained in:
parent
d4451d753c
commit
21d8e91756
165 changed files with 318 additions and 40948 deletions
|
|
@ -1,392 +0,0 @@
|
|||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"telesrv/internal/domain"
|
||||
)
|
||||
|
||||
// Default page sizes for the rating reads, so an unset limit resolves to a
|
||||
// finite page the way the PostgreSQL LIMIT does.
|
||||
const (
|
||||
defaultAccountRatingListLimit = 50
|
||||
defaultAccountRatingEventLimit = 50
|
||||
defaultAccountRatingStaleLimit = 50
|
||||
)
|
||||
|
||||
// AccountRatingStore is the in-memory implementation of store.AccountRatingStore.
|
||||
// It reproduces the invariants migration 0151 encodes:
|
||||
//
|
||||
// - account_rating is keyed by user_id, so one projection row per user.
|
||||
// - the version CHECK plus optimistic concurrency: a write is applied only when
|
||||
// it carries the successor of the stored version, which is exactly what
|
||||
// domain.ResolveAccountRatingPending produces.
|
||||
// - the pending pair CHECK: a pending delta and its date exist together or not
|
||||
// at all.
|
||||
// - the component CHECKs: stars/activity/penalty components and level are
|
||||
// non-negative, and next_level_stars is either absent or above
|
||||
// current_level_stars.
|
||||
// - account_rating_events_command_idx: a replayed command key never appends a
|
||||
// second adjustment.
|
||||
type AccountRatingStore struct {
|
||||
mu sync.Mutex
|
||||
nextID int64
|
||||
// ratings is the account_rating read model.
|
||||
ratings map[int64]domain.AccountRating
|
||||
// events is the append-only contribution ledger in insertion order.
|
||||
events []domain.AccountRatingEvent
|
||||
// commands maps an adjustment command key onto the ledger row it created.
|
||||
commands map[string]int64
|
||||
// signals holds the raw contribution snapshot per user.
|
||||
//
|
||||
// PostgreSQL aggregates it from stars_transactions, message counts, saved
|
||||
// gifts and moderation cases. In memory those live in unrelated store types
|
||||
// (StarsStore, MessageStore, StarGiftStore, ModerationReportStore) that this
|
||||
// store has no handle on, and wiring them in would make the rating depend on
|
||||
// which stores a test happens to construct. The snapshot is therefore
|
||||
// injected -- deterministic, and identical for a unit test and for the
|
||||
// recompute worker, which is what domain.AccountRatingSignals promises. Only
|
||||
// the manual total is derived here, from the ledger, because the ledger is
|
||||
// this store's own data.
|
||||
signals map[int64]domain.AccountRatingSignals
|
||||
// accounts is the account universe UnratedAccounts seeds from, in declaration
|
||||
// order.
|
||||
//
|
||||
// PostgreSQL reads it from the users table. This store has no users table and
|
||||
// inventing one from whichever ids happen to appear in the ledger would be
|
||||
// circular -- an account with no rating and no adjustment is exactly the case
|
||||
// seeding exists for. So the universe is declared, like signals above.
|
||||
accounts []int64
|
||||
}
|
||||
|
||||
// NewAccountRatingStore creates an empty rating store.
|
||||
func NewAccountRatingStore() *AccountRatingStore {
|
||||
return &AccountRatingStore{
|
||||
nextID: 1,
|
||||
ratings: make(map[int64]domain.AccountRating),
|
||||
commands: make(map[string]int64),
|
||||
signals: make(map[int64]domain.AccountRatingSignals),
|
||||
}
|
||||
}
|
||||
|
||||
// SeedAccountRatingSignals installs raw contribution snapshots for tests in other
|
||||
// packages; see the signals field for why they are injected rather than derived.
|
||||
func (s *AccountRatingStore) SeedAccountRatingSignals(signals ...domain.AccountRatingSignals) {
|
||||
for _, item := range signals {
|
||||
s.setAccountRatingSignals(item)
|
||||
}
|
||||
}
|
||||
|
||||
// setAccountRatingSignals is the same hook for this package's tests.
|
||||
func (s *AccountRatingStore) setAccountRatingSignals(signals domain.AccountRatingSignals) {
|
||||
if signals.UserID <= 0 {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.signals[signals.UserID] = signals
|
||||
}
|
||||
|
||||
// AccountRating returns the stored projection, or domain.ErrAccountRatingNotFound
|
||||
// when the user was never computed.
|
||||
func (s *AccountRatingStore) AccountRating(_ context.Context, userID int64) (domain.AccountRating, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
rating, ok := s.ratings[userID]
|
||||
if !ok {
|
||||
return domain.AccountRating{}, domain.ErrAccountRatingNotFound
|
||||
}
|
||||
return rating, nil
|
||||
}
|
||||
|
||||
// AccountRatingBatch resolves several users at once; users without a row are
|
||||
// absent from the map.
|
||||
func (s *AccountRatingStore) AccountRatingBatch(_ context.Context, userIDs []int64) (map[int64]domain.AccountRating, error) {
|
||||
out := make(map[int64]domain.AccountRating, len(userIDs))
|
||||
if len(userIDs) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for _, userID := range userIDs {
|
||||
if userID <= 0 {
|
||||
continue
|
||||
}
|
||||
if rating, ok := s.ratings[userID]; ok {
|
||||
out[userID] = rating
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// SaveAccountRating upserts the projection under optimistic concurrency: the
|
||||
// incoming Version must be the successor of the stored one, which is what
|
||||
// domain.ResolveAccountRatingPending computes. A stale or missing version leaves
|
||||
// the stored row untouched and reports changed=false, so a caller that lost a
|
||||
// race can re-read and retry.
|
||||
func (s *AccountRatingStore) SaveAccountRating(_ context.Context, rating domain.AccountRating) (domain.AccountRating, bool, error) {
|
||||
if rating.UserID <= 0 {
|
||||
// account_rating.user_id references users(id): there is no row to write.
|
||||
return domain.AccountRating{}, false, domain.ErrAccountRatingNotFound
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
stored, exists := s.ratings[rating.UserID]
|
||||
if rating.Version != stored.Version+1 {
|
||||
if !exists {
|
||||
return domain.AccountRating{}, false, nil
|
||||
}
|
||||
return stored, false, nil
|
||||
}
|
||||
next := normalizeAccountRating(rating)
|
||||
s.ratings[next.UserID] = next
|
||||
return next, true, nil
|
||||
}
|
||||
|
||||
// AccountRatingSignals returns the injected raw snapshot with the manual total
|
||||
// taken from the ledger, mirroring the PostgreSQL aggregate. A user with no
|
||||
// contributions reports zeros rather than an error, because the aggregate has no
|
||||
// "missing row" state.
|
||||
func (s *AccountRatingStore) AccountRatingSignals(_ context.Context, userID int64) (domain.AccountRatingSignals, error) {
|
||||
if userID <= 0 {
|
||||
return domain.AccountRatingSignals{}, domain.ErrAccountRatingNotFound
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
signals := s.signals[userID]
|
||||
signals.UserID = userID
|
||||
signals.Manual += s.manualTotalLocked(userID)
|
||||
return signals, nil
|
||||
}
|
||||
|
||||
// AdjustAccountRating appends a manual adjustment. A replayed command key returns
|
||||
// the recorded event with applied=false and appends nothing.
|
||||
func (s *AccountRatingStore) AdjustAccountRating(_ context.Context, req domain.AdjustAccountRatingRequest) (domain.AccountRatingEvent, bool, error) {
|
||||
if err := req.Validate(); err != nil {
|
||||
return domain.AccountRatingEvent{}, false, err
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if req.CommandKey != "" {
|
||||
if id, ok := s.commands[req.CommandKey]; ok {
|
||||
for _, event := range s.events {
|
||||
if event.ID == id {
|
||||
return event, false, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
event := domain.AccountRatingEvent{
|
||||
ID: s.nextID,
|
||||
UserID: req.UserID,
|
||||
Kind: domain.AccountRatingEventManual,
|
||||
Amount: req.Amount,
|
||||
Reason: req.Reason,
|
||||
Actor: req.Actor,
|
||||
CommandKey: req.CommandKey,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
s.nextID++
|
||||
s.events = append(s.events, event)
|
||||
if event.CommandKey != "" {
|
||||
s.commands[event.CommandKey] = event.ID
|
||||
}
|
||||
return event, true, nil
|
||||
}
|
||||
|
||||
// ListAccountRatings is the admin leaderboard: level desc, stars desc, user id
|
||||
// asc, matching account_rating_leaderboard_idx. BeforeID is the keyset cursor and
|
||||
// names the last row of the previous page.
|
||||
func (s *AccountRatingStore) ListAccountRatings(_ context.Context, filter domain.AccountRatingFilter) ([]domain.AccountRating, error) {
|
||||
limit := filter.Limit
|
||||
if limit <= 0 {
|
||||
limit = defaultAccountRatingListLimit
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
cursor, hasCursor := s.ratings[filter.BeforeID]
|
||||
out := make([]domain.AccountRating, 0, len(s.ratings))
|
||||
for _, rating := range s.ratings {
|
||||
if filter.MinLevel > 0 && rating.Level < filter.MinLevel {
|
||||
continue
|
||||
}
|
||||
if filter.UserID > 0 && rating.UserID != filter.UserID {
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case filter.BeforeID <= 0:
|
||||
case hasCursor:
|
||||
// Keyset paging over the leaderboard order.
|
||||
if !accountRatingLess(cursor, rating) {
|
||||
continue
|
||||
}
|
||||
default:
|
||||
// The cursor row is gone; fall back to the id tiebreak alone so paging
|
||||
// still terminates.
|
||||
if rating.UserID <= filter.BeforeID {
|
||||
continue
|
||||
}
|
||||
}
|
||||
out = append(out, rating)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return accountRatingLess(out[i], out[j]) })
|
||||
if len(out) > limit {
|
||||
out = out[:limit]
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// AccountRatingEvents returns the ledger for one user, newest first.
|
||||
func (s *AccountRatingStore) AccountRatingEvents(_ context.Context, userID int64, limit int) ([]domain.AccountRatingEvent, error) {
|
||||
if limit <= 0 {
|
||||
limit = defaultAccountRatingEventLimit
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
out := make([]domain.AccountRatingEvent, 0, limit)
|
||||
for i := len(s.events) - 1; i >= 0 && len(out) < limit; i-- {
|
||||
if s.events[i].UserID != userID {
|
||||
continue
|
||||
}
|
||||
out = append(out, s.events[i])
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// StaleAccountRatings returns the users whose projection predates the horizon,
|
||||
// oldest first, which is the order account_rating_stale_idx serves.
|
||||
func (s *AccountRatingStore) StaleAccountRatings(_ context.Context, olderThanUnix int64, limit int) ([]int64, error) {
|
||||
if limit <= 0 {
|
||||
limit = defaultAccountRatingStaleLimit
|
||||
}
|
||||
horizon := time.Unix(olderThanUnix, 0).UTC()
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
stale := make([]domain.AccountRating, 0, len(s.ratings))
|
||||
for _, rating := range s.ratings {
|
||||
if rating.ComputedAt.Before(horizon) {
|
||||
stale = append(stale, rating)
|
||||
}
|
||||
}
|
||||
sort.Slice(stale, func(i, j int) bool {
|
||||
if !stale[i].ComputedAt.Equal(stale[j].ComputedAt) {
|
||||
return stale[i].ComputedAt.Before(stale[j].ComputedAt)
|
||||
}
|
||||
return stale[i].UserID < stale[j].UserID
|
||||
})
|
||||
if len(stale) > limit {
|
||||
stale = stale[:limit]
|
||||
}
|
||||
out := make([]int64, 0, len(stale))
|
||||
for _, rating := range stale {
|
||||
out = append(out, rating.UserID)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// SeedAccounts declares the account universe UnratedAccounts walks. Repeating an
|
||||
// id is a no-op, so a test can declare accounts as it creates them.
|
||||
func (s *AccountRatingStore) SeedAccounts(userIDs ...int64) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
known := make(map[int64]struct{}, len(s.accounts))
|
||||
for _, id := range s.accounts {
|
||||
known[id] = struct{}{}
|
||||
}
|
||||
for _, id := range userIDs {
|
||||
if id <= 0 {
|
||||
continue
|
||||
}
|
||||
if _, ok := known[id]; ok {
|
||||
continue
|
||||
}
|
||||
known[id] = struct{}{}
|
||||
s.accounts = append(s.accounts, id)
|
||||
}
|
||||
}
|
||||
|
||||
// UnratedAccounts returns declared accounts that have no projection yet, in
|
||||
// declaration order -- the memory stand-in for PostgreSQL's oldest-account-first
|
||||
// walk. A store nobody seeded reports no candidates rather than erroring: the
|
||||
// worker treats that as "nothing to seed", which is the truth.
|
||||
func (s *AccountRatingStore) UnratedAccounts(_ context.Context, limit int) ([]int64, error) {
|
||||
if limit <= 0 {
|
||||
limit = defaultAccountRatingStaleLimit
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
out := make([]int64, 0, limit)
|
||||
for _, id := range s.accounts {
|
||||
if _, rated := s.ratings[id]; rated {
|
||||
continue
|
||||
}
|
||||
out = append(out, id)
|
||||
if len(out) == limit {
|
||||
break
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// manualTotalLocked sums the manual ledger rows, the only kind that survives a
|
||||
// recompute.
|
||||
func (s *AccountRatingStore) manualTotalLocked(userID int64) int64 {
|
||||
var total int64
|
||||
for _, event := range s.events {
|
||||
if event.UserID == userID && event.Kind == domain.AccountRatingEventManual {
|
||||
total += event.Amount
|
||||
}
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
// normalizeAccountRating makes the rows the table's CHECK constraints forbid
|
||||
// unrepresentable. PostgreSQL raises an opaque constraint error there rather than
|
||||
// a domain error, so the memory store folds the impossible shapes onto the
|
||||
// closest representable one instead of inventing an error the RPC layer would
|
||||
// then have to handle only in tests.
|
||||
func normalizeAccountRating(rating domain.AccountRating) domain.AccountRating {
|
||||
if rating.Level < 0 {
|
||||
rating.Level = 0
|
||||
}
|
||||
if rating.Level > domain.MaxAccountRatingLevel {
|
||||
rating.Level = domain.MaxAccountRatingLevel
|
||||
}
|
||||
if rating.CurrentLevelStars < 0 {
|
||||
rating.CurrentLevelStars = 0
|
||||
}
|
||||
if rating.StarsComponent < 0 {
|
||||
rating.StarsComponent = 0
|
||||
}
|
||||
if rating.ActivityComponent < 0 {
|
||||
rating.ActivityComponent = 0
|
||||
}
|
||||
if rating.PenaltyComponent < 0 {
|
||||
rating.PenaltyComponent = 0
|
||||
}
|
||||
if !rating.HasNextLevel || rating.NextLevelStars <= rating.CurrentLevelStars {
|
||||
rating.HasNextLevel = false
|
||||
rating.NextLevelStars = 0
|
||||
}
|
||||
// The pending delta and its date only exist together.
|
||||
if rating.PendingStars == 0 || rating.PendingDate.IsZero() {
|
||||
rating.PendingStars = 0
|
||||
rating.PendingDate = time.Time{}
|
||||
}
|
||||
return rating
|
||||
}
|
||||
|
||||
// accountRatingLess is the leaderboard order: highest level first, then the
|
||||
// larger score, then the lower user id as a stable tiebreak.
|
||||
func accountRatingLess(a, b domain.AccountRating) bool {
|
||||
if a.Level != b.Level {
|
||||
return a.Level > b.Level
|
||||
}
|
||||
if a.Stars != b.Stars {
|
||||
return a.Stars > b.Stars
|
||||
}
|
||||
return a.UserID < b.UserID
|
||||
}
|
||||
|
|
@ -1,425 +0,0 @@
|
|||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"telesrv/internal/domain"
|
||||
"telesrv/internal/store"
|
||||
)
|
||||
|
||||
var _ store.AccountRatingStore = (*AccountRatingStore)(nil)
|
||||
|
||||
// accountRatingFixture builds a projection the table's CHECK constraints accept.
|
||||
func accountRatingFixture(userID, stars, version int64, computedAt time.Time) domain.AccountRating {
|
||||
level, current, next, hasNext := domain.AccountRatingLevelForStars(stars)
|
||||
return domain.AccountRating{
|
||||
UserID: userID,
|
||||
Level: level,
|
||||
Stars: stars,
|
||||
CurrentLevelStars: current,
|
||||
NextLevelStars: next,
|
||||
HasNextLevel: hasNext,
|
||||
StarsComponent: stars,
|
||||
ComputedAt: computedAt,
|
||||
UpdatedAt: computedAt,
|
||||
Version: version,
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveAccountRating(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
now := time.Unix(1700000000, 0).UTC()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
seed []domain.AccountRating
|
||||
input domain.AccountRating
|
||||
wantErr error
|
||||
wantChanged bool
|
||||
check func(t *testing.T, s *AccountRatingStore, stored domain.AccountRating)
|
||||
}{
|
||||
{
|
||||
name: "insert",
|
||||
input: accountRatingFixture(11, 450, 1, now),
|
||||
wantChanged: true,
|
||||
check: func(t *testing.T, s *AccountRatingStore, stored domain.AccountRating) {
|
||||
if stored.Level != 2 || stored.Stars != 450 || stored.Version != 1 ||
|
||||
stored.CurrentLevelStars != 400 || stored.NextLevelStars != 900 || !stored.HasNextLevel {
|
||||
t.Fatalf("stored=%+v", stored)
|
||||
}
|
||||
read, err := s.AccountRating(ctx, 11)
|
||||
if err != nil || read != stored {
|
||||
t.Fatalf("read=%+v err=%v", read, err)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "successor version applied",
|
||||
seed: []domain.AccountRating{accountRatingFixture(11, 450, 1, now)},
|
||||
input: accountRatingFixture(11, 1000, 2, now.Add(time.Minute)),
|
||||
wantChanged: true,
|
||||
check: func(t *testing.T, s *AccountRatingStore, stored domain.AccountRating) {
|
||||
if stored.Version != 2 || stored.Stars != 1000 || stored.Level != 3 {
|
||||
t.Fatalf("stored=%+v", stored)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "replayed version is stale",
|
||||
seed: []domain.AccountRating{accountRatingFixture(11, 450, 1, now)},
|
||||
input: accountRatingFixture(11, 9999, 1, now.Add(time.Minute)),
|
||||
wantChanged: false,
|
||||
check: func(t *testing.T, s *AccountRatingStore, stored domain.AccountRating) {
|
||||
// The loser of the race gets the current row back, untouched.
|
||||
if stored.Stars != 450 || stored.Version != 1 {
|
||||
t.Fatalf("stored=%+v", stored)
|
||||
}
|
||||
read, err := s.AccountRating(ctx, 11)
|
||||
if err != nil || read.Stars != 450 || read.Version != 1 {
|
||||
t.Fatalf("read=%+v err=%v", read, err)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "version from the future is rejected",
|
||||
seed: []domain.AccountRating{accountRatingFixture(11, 450, 1, now)},
|
||||
input: accountRatingFixture(11, 9999, 7, now.Add(time.Minute)),
|
||||
wantChanged: false,
|
||||
check: func(t *testing.T, s *AccountRatingStore, stored domain.AccountRating) {
|
||||
if stored.Stars != 450 || stored.Version != 1 {
|
||||
t.Fatalf("stored=%+v", stored)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "insert must carry version one",
|
||||
input: accountRatingFixture(11, 450, 3, now),
|
||||
wantChanged: false,
|
||||
check: func(t *testing.T, s *AccountRatingStore, stored domain.AccountRating) {
|
||||
if stored != (domain.AccountRating{}) {
|
||||
t.Fatalf("stored=%+v", stored)
|
||||
}
|
||||
if _, err := s.AccountRating(ctx, 11); !errors.Is(err, domain.ErrAccountRatingNotFound) {
|
||||
t.Fatalf("row was written: %v", err)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "no user",
|
||||
input: accountRatingFixture(0, 450, 1, now),
|
||||
wantErr: domain.ErrAccountRatingNotFound,
|
||||
},
|
||||
{
|
||||
name: "pending delta without a date is dropped",
|
||||
input: func() domain.AccountRating {
|
||||
rating := accountRatingFixture(11, 450, 1, now)
|
||||
rating.PendingStars = 120
|
||||
return rating
|
||||
}(),
|
||||
wantChanged: true,
|
||||
check: func(t *testing.T, s *AccountRatingStore, stored domain.AccountRating) {
|
||||
if stored.PendingStars != 0 || !stored.PendingDate.IsZero() {
|
||||
t.Fatalf("stored=%+v", stored)
|
||||
}
|
||||
if _, ok := stored.PendingLevel(); ok {
|
||||
t.Fatalf("pending projection survived: %+v", stored)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "pending pair is kept",
|
||||
input: func() domain.AccountRating {
|
||||
rating := accountRatingFixture(11, 450, 1, now)
|
||||
rating.PendingStars = 500
|
||||
rating.PendingDate = now.Add(time.Hour)
|
||||
return rating
|
||||
}(),
|
||||
wantChanged: true,
|
||||
check: func(t *testing.T, s *AccountRatingStore, stored domain.AccountRating) {
|
||||
pending, ok := stored.PendingLevel()
|
||||
if !ok || pending.Stars != 950 || pending.Level != 3 {
|
||||
t.Fatalf("pending=%+v ok=%v", pending, ok)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "impossible components are folded",
|
||||
input: func() domain.AccountRating {
|
||||
rating := accountRatingFixture(11, 450, 1, now)
|
||||
rating.Level = -3
|
||||
rating.StarsComponent = -10
|
||||
rating.ActivityComponent = -1
|
||||
rating.PenaltyComponent = -7
|
||||
rating.CurrentLevelStars = -5
|
||||
rating.NextLevelStars = -9
|
||||
rating.HasNextLevel = true
|
||||
return rating
|
||||
}(),
|
||||
wantChanged: true,
|
||||
check: func(t *testing.T, s *AccountRatingStore, stored domain.AccountRating) {
|
||||
if stored.Level != 0 || stored.StarsComponent != 0 || stored.ActivityComponent != 0 ||
|
||||
stored.PenaltyComponent != 0 || stored.CurrentLevelStars != 0 {
|
||||
t.Fatalf("stored=%+v", stored)
|
||||
}
|
||||
if stored.HasNextLevel || stored.NextLevelStars != 0 {
|
||||
t.Fatalf("next level survived: %+v", stored)
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
s := NewAccountRatingStore()
|
||||
for _, seed := range tc.seed {
|
||||
if _, changed, err := s.SaveAccountRating(ctx, seed); err != nil || !changed {
|
||||
t.Fatalf("seed changed=%v err=%v", changed, err)
|
||||
}
|
||||
}
|
||||
stored, changed, err := s.SaveAccountRating(ctx, tc.input)
|
||||
if !errors.Is(err, tc.wantErr) {
|
||||
t.Fatalf("err=%v want %v", err, tc.wantErr)
|
||||
}
|
||||
if changed != tc.wantChanged {
|
||||
t.Fatalf("changed=%v want %v", changed, tc.wantChanged)
|
||||
}
|
||||
if tc.wantErr != nil {
|
||||
return
|
||||
}
|
||||
if tc.check != nil {
|
||||
tc.check(t, s, stored)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccountRatingReadsAndLeaderboard(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
now := time.Unix(1700000000, 0).UTC()
|
||||
s := NewAccountRatingStore()
|
||||
for _, rating := range []domain.AccountRating{
|
||||
accountRatingFixture(11, 2500, 1, now),
|
||||
accountRatingFixture(12, 450, 1, now),
|
||||
accountRatingFixture(13, 2500, 1, now),
|
||||
accountRatingFixture(14, 0, 1, now),
|
||||
} {
|
||||
if _, changed, err := s.SaveAccountRating(ctx, rating); err != nil || !changed {
|
||||
t.Fatalf("seed %d changed=%v err=%v", rating.UserID, changed, err)
|
||||
}
|
||||
}
|
||||
|
||||
batch, err := s.AccountRatingBatch(ctx, []int64{11, 13, 99, 0, 11})
|
||||
if err != nil || len(batch) != 2 {
|
||||
t.Fatalf("batch=%+v err=%v", batch, err)
|
||||
}
|
||||
if batch[11].Stars != 2500 || batch[13].Stars != 2500 {
|
||||
t.Fatalf("batch=%+v", batch)
|
||||
}
|
||||
if empty, err := s.AccountRatingBatch(ctx, nil); err != nil || len(empty) != 0 {
|
||||
t.Fatalf("empty batch=%+v err=%v", empty, err)
|
||||
}
|
||||
|
||||
// level desc, stars desc, user id asc.
|
||||
board, err := s.ListAccountRatings(ctx, domain.AccountRatingFilter{})
|
||||
if err != nil || len(board) != 4 {
|
||||
t.Fatalf("board=%+v err=%v", board, err)
|
||||
}
|
||||
want := []int64{11, 13, 12, 14}
|
||||
for i, userID := range want {
|
||||
if board[i].UserID != userID {
|
||||
t.Fatalf("board order=%+v want %v", board, want)
|
||||
}
|
||||
}
|
||||
page, err := s.ListAccountRatings(ctx, domain.AccountRatingFilter{Limit: 2})
|
||||
if err != nil || len(page) != 2 || page[1].UserID != 13 {
|
||||
t.Fatalf("page=%+v err=%v", page, err)
|
||||
}
|
||||
next, err := s.ListAccountRatings(ctx, domain.AccountRatingFilter{
|
||||
BeforeID: page[len(page)-1].UserID, Limit: 2,
|
||||
})
|
||||
if err != nil || len(next) != 2 || next[0].UserID != 12 || next[1].UserID != 14 {
|
||||
t.Fatalf("next=%+v err=%v", next, err)
|
||||
}
|
||||
filtered, err := s.ListAccountRatings(ctx, domain.AccountRatingFilter{MinLevel: 5})
|
||||
if err != nil || len(filtered) != 2 {
|
||||
t.Fatalf("filtered=%+v err=%v", filtered, err)
|
||||
}
|
||||
single, err := s.ListAccountRatings(ctx, domain.AccountRatingFilter{UserID: 12})
|
||||
if err != nil || len(single) != 1 || single[0].UserID != 12 {
|
||||
t.Fatalf("single=%+v err=%v", single, err)
|
||||
}
|
||||
if _, err := s.AccountRating(ctx, 99); !errors.Is(err, domain.ErrAccountRatingNotFound) {
|
||||
t.Fatalf("unknown user err=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdjustAccountRating(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s := NewAccountRatingStore()
|
||||
req := domain.AdjustAccountRatingRequest{
|
||||
UserID: 11, Amount: 750, Reason: "contest prize", Actor: "admin", CommandKey: "cmd-adjust",
|
||||
}
|
||||
|
||||
event, applied, err := s.AdjustAccountRating(ctx, req)
|
||||
if err != nil || !applied {
|
||||
t.Fatalf("adjust applied=%v err=%v", applied, err)
|
||||
}
|
||||
if event.ID == 0 || event.Kind != domain.AccountRatingEventManual || event.Amount != 750 ||
|
||||
event.Reason != "contest prize" || event.Actor != "admin" || event.CreatedAt.IsZero() {
|
||||
t.Fatalf("event=%+v", event)
|
||||
}
|
||||
|
||||
// Replaying the command key returns the recorded row and appends nothing.
|
||||
replay, applied, err := s.AdjustAccountRating(ctx, req)
|
||||
if err != nil || applied {
|
||||
t.Fatalf("replay applied=%v err=%v", applied, err)
|
||||
}
|
||||
if replay != event {
|
||||
t.Fatalf("replay=%+v want %+v", replay, event)
|
||||
}
|
||||
ledger, err := s.AccountRatingEvents(ctx, 11, 10)
|
||||
if err != nil || len(ledger) != 1 {
|
||||
t.Fatalf("ledger=%+v err=%v", ledger, err)
|
||||
}
|
||||
|
||||
second := req
|
||||
second.Amount = -200
|
||||
second.CommandKey = "cmd-adjust-2"
|
||||
if _, applied, err := s.AdjustAccountRating(ctx, second); err != nil || !applied {
|
||||
t.Fatalf("second adjust applied=%v err=%v", applied, err)
|
||||
}
|
||||
// Newest first, and other users are not mixed in.
|
||||
if _, applied, err := s.AdjustAccountRating(ctx, domain.AdjustAccountRatingRequest{
|
||||
UserID: 12, Amount: 5, CommandKey: "cmd-other",
|
||||
}); err != nil || !applied {
|
||||
t.Fatalf("other user applied=%v err=%v", applied, err)
|
||||
}
|
||||
ledger, err = s.AccountRatingEvents(ctx, 11, 10)
|
||||
if err != nil || len(ledger) != 2 || ledger[0].Amount != -200 || ledger[1].Amount != 750 {
|
||||
t.Fatalf("ledger=%+v err=%v", ledger, err)
|
||||
}
|
||||
if capped, err := s.AccountRatingEvents(ctx, 11, 1); err != nil || len(capped) != 1 ||
|
||||
capped[0].Amount != -200 {
|
||||
t.Fatalf("capped=%+v err=%v", capped, err)
|
||||
}
|
||||
|
||||
// An unkeyed adjustment is always appended.
|
||||
if _, applied, err := s.AdjustAccountRating(ctx, domain.AdjustAccountRatingRequest{
|
||||
UserID: 11, Amount: 10,
|
||||
}); err != nil || !applied {
|
||||
t.Fatalf("unkeyed applied=%v err=%v", applied, err)
|
||||
}
|
||||
|
||||
for _, invalid := range []domain.AdjustAccountRatingRequest{
|
||||
{UserID: 11, Amount: 0, CommandKey: "cmd-zero"},
|
||||
{UserID: 0, Amount: 5, CommandKey: "cmd-nouser"},
|
||||
} {
|
||||
if _, applied, err := s.AdjustAccountRating(ctx, invalid); !errors.Is(err, domain.ErrAccountRatingAdjustmentInvalid) || applied {
|
||||
t.Fatalf("invalid adjust applied=%v err=%v", applied, err)
|
||||
}
|
||||
}
|
||||
|
||||
// The manual total is carried out of the ledger into the signal snapshot.
|
||||
signals, err := s.AccountRatingSignals(ctx, 11)
|
||||
if err != nil || signals.UserID != 11 || signals.Manual != 560 {
|
||||
t.Fatalf("signals=%+v err=%v", signals, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccountRatingSignals(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s := NewAccountRatingStore()
|
||||
|
||||
// A user with no contributions reports zeros rather than an error.
|
||||
signals, err := s.AccountRatingSignals(ctx, 11)
|
||||
if err != nil || signals != (domain.AccountRatingSignals{UserID: 11}) {
|
||||
t.Fatalf("signals=%+v err=%v", signals, err)
|
||||
}
|
||||
if _, err := s.AccountRatingSignals(ctx, 0); !errors.Is(err, domain.ErrAccountRatingNotFound) {
|
||||
t.Fatalf("missing user err=%v", err)
|
||||
}
|
||||
|
||||
s.setAccountRatingSignals(domain.AccountRatingSignals{
|
||||
UserID: 11, StarsReceived: 4000, StarsSpent: 2000, MessagesSent: 300,
|
||||
AccountAgeDays: 100, GiftsReceived: 4, ModerationCases: 1,
|
||||
})
|
||||
if _, applied, err := s.AdjustAccountRating(ctx, domain.AdjustAccountRatingRequest{
|
||||
UserID: 11, Amount: 250, CommandKey: "cmd-bonus",
|
||||
}); err != nil || !applied {
|
||||
t.Fatalf("adjust applied=%v err=%v", applied, err)
|
||||
}
|
||||
signals, err = s.AccountRatingSignals(ctx, 11)
|
||||
if err != nil || signals.StarsReceived != 4000 || signals.MessagesSent != 300 ||
|
||||
signals.ModerationCases != 1 || signals.Manual != 250 {
|
||||
t.Fatalf("signals=%+v err=%v", signals, err)
|
||||
}
|
||||
|
||||
// The snapshot feeds the domain formula, and the result round-trips.
|
||||
now := time.Unix(1700000000, 0).UTC()
|
||||
computed := domain.ComputeAccountRating(signals, domain.DefaultAccountRatingWeights(), now)
|
||||
stored, changed, err := s.SaveAccountRating(ctx, computed)
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("save changed=%v err=%v", changed, err)
|
||||
}
|
||||
if stored.Stars != computed.Stars || stored.Level != computed.Level ||
|
||||
stored.ManualComponent != 250 {
|
||||
t.Fatalf("stored=%+v computed=%+v", stored, computed)
|
||||
}
|
||||
|
||||
// A recompute uses the pending resolution the domain owns.
|
||||
s.setAccountRatingSignals(domain.AccountRatingSignals{UserID: 11, StarsReceived: 40000})
|
||||
signals, err = s.AccountRatingSignals(ctx, 11)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
recomputed := domain.ResolveAccountRatingPending(stored,
|
||||
domain.ComputeAccountRating(signals, domain.DefaultAccountRatingWeights(), now.Add(time.Hour)),
|
||||
24*time.Hour, now.Add(time.Hour))
|
||||
saved, changed, err := s.SaveAccountRating(ctx, recomputed)
|
||||
if err != nil || !changed || saved.Version != stored.Version+1 {
|
||||
t.Fatalf("saved=%+v changed=%v err=%v", saved, changed, err)
|
||||
}
|
||||
if saved.PendingStars <= 0 || saved.PendingDate.IsZero() {
|
||||
t.Fatalf("pending was not parked: %+v", saved)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStaleAccountRatings(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
now := time.Unix(1700000000, 0).UTC()
|
||||
s := NewAccountRatingStore()
|
||||
for _, rating := range []domain.AccountRating{
|
||||
accountRatingFixture(11, 100, 1, now.Add(-3*time.Hour)),
|
||||
accountRatingFixture(12, 100, 1, now.Add(-2*time.Hour)),
|
||||
accountRatingFixture(13, 100, 1, now.Add(-time.Hour)),
|
||||
accountRatingFixture(14, 100, 1, now),
|
||||
} {
|
||||
if _, changed, err := s.SaveAccountRating(ctx, rating); err != nil || !changed {
|
||||
t.Fatalf("seed %d changed=%v err=%v", rating.UserID, changed, err)
|
||||
}
|
||||
}
|
||||
|
||||
stale, err := s.StaleAccountRatings(ctx, now.Add(-90*time.Minute).Unix(), 10)
|
||||
if err != nil || len(stale) != 2 || stale[0] != 11 || stale[1] != 12 {
|
||||
t.Fatalf("stale=%v err=%v", stale, err)
|
||||
}
|
||||
if limited, err := s.StaleAccountRatings(ctx, now.Add(-90*time.Minute).Unix(), 1); err != nil ||
|
||||
len(limited) != 1 || limited[0] != 11 {
|
||||
t.Fatalf("limited=%v err=%v", limited, err)
|
||||
}
|
||||
if none, err := s.StaleAccountRatings(ctx, now.Add(-4*time.Hour).Unix(), 10); err != nil || len(none) != 0 {
|
||||
t.Fatalf("none=%v err=%v", none, err)
|
||||
}
|
||||
// A recompute refreshes computed_at and takes the row out of the horizon.
|
||||
refreshed := accountRatingFixture(11, 100, 2, now)
|
||||
if _, changed, err := s.SaveAccountRating(ctx, refreshed); err != nil || !changed {
|
||||
t.Fatalf("refresh changed=%v err=%v", changed, err)
|
||||
}
|
||||
stale, err = s.StaleAccountRatings(ctx, now.Add(-90*time.Minute).Unix(), 10)
|
||||
if err != nil || len(stale) != 1 || stale[0] != 12 {
|
||||
t.Fatalf("stale=%v err=%v", stale, err)
|
||||
}
|
||||
}
|
||||
|
|
@ -26,42 +26,6 @@ func (s *ChannelStore) AppendCallServiceMessage(_ context.Context, channelID, se
|
|||
return s.appendServiceMessageLocked(channelID, senderUserID, date, action)
|
||||
}
|
||||
|
||||
// AppendStarGiftAdminLog 记录频道 Star gift 到 Recent Actions,不进入频道消息历史。
|
||||
func (s *ChannelStore) AppendStarGiftAdminLog(_ context.Context, channelID, senderUserID int64, savedID int64, date int, action domain.ChannelMessageAction) error {
|
||||
if channelID == 0 || senderUserID == 0 || savedID <= 0 {
|
||||
return domain.ErrChannelInvalid
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
ch, ok := s.channels[channelID]
|
||||
if !ok || ch.Deleted {
|
||||
return domain.ErrChannelInvalid
|
||||
}
|
||||
messageID := int(savedID)
|
||||
if savedID > int64(domain.MaxMessageBoxID) {
|
||||
messageID = domain.MaxMessageBoxID
|
||||
}
|
||||
action = channelServiceActionForMessage(channelID, messageID, action)
|
||||
msg := domain.ChannelMessage{
|
||||
ChannelID: channelID,
|
||||
ID: messageID,
|
||||
SenderUserID: senderUserID,
|
||||
From: domain.Peer{Type: domain.PeerTypeUser, ID: senderUserID},
|
||||
Date: date,
|
||||
Post: ch.Broadcast,
|
||||
Action: &action,
|
||||
Pts: ch.Pts,
|
||||
}
|
||||
s.appendChannelAdminLogLocked(domain.ChannelAdminLogEvent{
|
||||
ChannelID: channelID,
|
||||
UserID: senderUserID,
|
||||
Date: date,
|
||||
Type: domain.ChannelAdminLogSendMessage,
|
||||
Message: &msg,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ChannelStore) appendServiceMessageLocked(channelID, senderUserID int64, date int, action domain.ChannelMessageAction) (domain.SendChannelMessageResult, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
|
|
|||
|
|
@ -69,14 +69,6 @@ func cloneChannelMessageAction(in *domain.ChannelMessageAction) *domain.ChannelM
|
|||
v := *in.Hidden
|
||||
out.Hidden = &v
|
||||
}
|
||||
if in.StarGift != nil {
|
||||
g := *in.StarGift
|
||||
if in.StarGift.Sticker != nil {
|
||||
sticker := *in.StarGift.Sticker
|
||||
g.Sticker = &sticker
|
||||
}
|
||||
out.StarGift = &g
|
||||
}
|
||||
if in.SuggestedPostPrice != nil {
|
||||
price := *in.SuggestedPostPrice
|
||||
out.SuggestedPostPrice = &price
|
||||
|
|
|
|||
|
|
@ -323,13 +323,6 @@ func (s *ChannelStore) lookupChannelSendReplayLocked(req domain.ChannelSendRepla
|
|||
Duplicate: true,
|
||||
ReplayDeleteEvent: replayDelete,
|
||||
}
|
||||
if first.PaidMessageStars > 0 {
|
||||
balance, ok := s.starsBalances[first.SenderUserID]
|
||||
if !ok {
|
||||
return domain.SendChannelMessageResult{}, false, fmt.Errorf("memory paid-message replay has no sender balance")
|
||||
}
|
||||
result.SenderStarsBalance = &domain.StarsBalance{UserID: first.SenderUserID, Balance: balance, Granted: true}
|
||||
}
|
||||
return result, true, nil
|
||||
}
|
||||
|
||||
|
|
@ -368,7 +361,6 @@ func (s *ChannelStore) nextChannelMessageIDLocked(channelID int64) int {
|
|||
func (s *ChannelStore) appendChannelServiceMessageLocked(channelID, senderUserID int64, date int, action domain.ChannelMessageAction) (domain.ChannelMessage, domain.ChannelUpdateEvent) {
|
||||
channel := s.channels[channelID]
|
||||
msgID := s.nextChannelMessageIDLocked(channelID)
|
||||
action = channelServiceActionForMessage(channelID, msgID, action)
|
||||
pts := s.nextChannelPtsLocked(channelID)
|
||||
msg := domain.ChannelMessage{
|
||||
ChannelID: channelID,
|
||||
|
|
@ -395,20 +387,6 @@ func (s *ChannelStore) appendChannelServiceMessageLocked(channelID, senderUserID
|
|||
return msg, event
|
||||
}
|
||||
|
||||
func channelServiceActionForMessage(channelID int64, msgID int, action domain.ChannelMessageAction) domain.ChannelMessageAction {
|
||||
if action.Type == domain.ChannelActionStarGift && action.StarGift != nil {
|
||||
g := *action.StarGift
|
||||
if g.PeerChannelID == 0 {
|
||||
g.PeerChannelID = channelID
|
||||
}
|
||||
if g.SavedID == 0 {
|
||||
g.SavedID = int64(msgID)
|
||||
}
|
||||
action.StarGift = &g
|
||||
}
|
||||
return action
|
||||
}
|
||||
|
||||
func canSendChannelMessage(channel domain.Channel, member domain.ChannelMember) bool {
|
||||
return canSendChannelMessageWithBoost(channel, member, 0)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -20,9 +20,6 @@ func (s *ChannelStore) SendMonoforumMessage(_ context.Context, req domain.SendMo
|
|||
req.SavedPeer.Type != domain.PeerTypeUser || strings.TrimSpace(req.Message) == "" && req.Media == nil {
|
||||
return domain.SendChannelMessageResult{}, domain.ErrChannelInvalid
|
||||
}
|
||||
if req.AllowPaidStars < 0 {
|
||||
return domain.SendChannelMessageResult{}, domain.ErrStarsInvalidAmount
|
||||
}
|
||||
var fingerprint []byte
|
||||
var err error
|
||||
if req.RandomID != 0 {
|
||||
|
|
@ -73,27 +70,10 @@ func (s *ChannelStore) SendMonoforumMessage(_ context.Context, req domain.SendMo
|
|||
return domain.SendChannelMessageResult{}, domain.ErrReplyMessageIDInvalid
|
||||
}
|
||||
}
|
||||
var senderBalance *domain.StarsBalance
|
||||
// telesrv has no Stars economy: Direct Messages are always free, so no
|
||||
// balance is ever checked or debited here regardless of any stale
|
||||
// per-channel price.
|
||||
paidMessageStars := int64(0)
|
||||
balanceAfter := int64(0)
|
||||
if !isAdmin && channel.SendPaidMessagesStars > 0 {
|
||||
if channel.SendPaidMessagesStars != parent.SendPaidMessagesStars {
|
||||
return domain.SendChannelMessageResult{}, domain.ErrChannelInvalid
|
||||
}
|
||||
if req.AllowPaidStars < channel.SendPaidMessagesStars {
|
||||
return domain.SendChannelMessageResult{}, &domain.StarsPaymentRequiredError{Stars: channel.SendPaidMessagesStars}
|
||||
}
|
||||
current, ok := s.starsBalances[req.SenderUserID]
|
||||
if !ok {
|
||||
current = domain.DefaultStarsStartingGrant
|
||||
}
|
||||
if current < channel.SendPaidMessagesStars {
|
||||
return domain.SendChannelMessageResult{}, domain.ErrStarsInsufficient
|
||||
}
|
||||
paidMessageStars = channel.SendPaidMessagesStars
|
||||
balanceAfter = current - paidMessageStars
|
||||
senderBalance = &domain.StarsBalance{UserID: req.SenderUserID, Balance: balanceAfter, Granted: true}
|
||||
}
|
||||
from := domain.Peer{Type: domain.PeerTypeUser, ID: req.SenderUserID}
|
||||
if isAdmin {
|
||||
from = domain.Peer{Type: domain.PeerTypeChannel, ID: parent.ID}
|
||||
|
|
@ -143,10 +123,6 @@ func (s *ChannelStore) SendMonoforumMessage(_ context.Context, req domain.SendMo
|
|||
SenderUserID: req.SenderUserID,
|
||||
}
|
||||
s.messages[req.MonoforumID] = append(s.messages[req.MonoforumID], msg)
|
||||
if paidMessageStars > 0 {
|
||||
s.starsBalances[req.SenderUserID] = balanceAfter
|
||||
s.channelStarsBalances[parent.ID] += paidMessageStars * paidMessageChannelCommissionPermille / 1000
|
||||
}
|
||||
if req.RandomID != 0 {
|
||||
replayKey := channelMessageReplayKey{channelID: req.MonoforumID, messageID: msg.ID}
|
||||
s.sendSnapshots[replayKey] = sendSnapshot
|
||||
|
|
@ -162,7 +138,7 @@ func (s *ChannelStore) SendMonoforumMessage(_ context.Context, req domain.SendMo
|
|||
recipients = append(recipients, userID)
|
||||
}
|
||||
}
|
||||
return domain.SendChannelMessageResult{Channel: cloneChannel(channel), Message: cloneChannelMessage(msg), Event: cloneChannelEvent(event), Recipients: uniqueNonZero(recipients, 0), SenderStarsBalance: senderBalance}, nil
|
||||
return domain.SendChannelMessageResult{Channel: cloneChannel(channel), Message: cloneChannelMessage(msg), Event: cloneChannelEvent(event), Recipients: uniqueNonZero(recipients, 0)}, nil
|
||||
}
|
||||
|
||||
// findMonoforumDuplicateLocked 按 (sender, saved_peer, random_id) 查 monoforum 子会话内的重发消息。
|
||||
|
|
|
|||
|
|
@ -315,73 +315,3 @@ func TestSendMonoforumMessageAndHistory(t *testing.T) {
|
|||
t.Fatalf("deleted monoforum replay mutated pts/events = %d/%d, want %d/%d", store.ptsSeq[monoID], len(store.events[monoID]), ptsBeforeReplay, eventsBeforeReplay)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendPaidMonoforumMessageLedger(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := NewChannelStore()
|
||||
broadcast, err := store.CreateChannel(ctx, domain.CreateChannelRequest{CreatorUserID: 1, Title: "Paid DM", Broadcast: true, Date: 1_700_002_000})
|
||||
if err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
enabled, err := store.SetPaidMessagesPrice(ctx, 1, broadcast.Channel.ID, 10, true)
|
||||
if err != nil {
|
||||
t.Fatalf("enable paid DM: %v", err)
|
||||
}
|
||||
monoID := enabled.Channel.LinkedMonoforumID
|
||||
sub := domain.Peer{Type: domain.PeerTypeUser, ID: 42}
|
||||
baseMessages := len(store.messages[monoID])
|
||||
|
||||
low := domain.SendMonoforumMessageRequest{MonoforumID: monoID, SenderUserID: 42, SavedPeer: sub, RandomID: 3001, Message: "too low", AllowPaidStars: 9, Date: 1_700_002_001}
|
||||
var required *domain.StarsPaymentRequiredError
|
||||
if _, err := store.SendMonoforumMessage(ctx, low); !errors.As(err, &required) || required.Stars != 10 {
|
||||
t.Fatalf("low authorization err = %v, want 10-Star payment required", err)
|
||||
}
|
||||
if len(store.messages[monoID]) != baseMessages {
|
||||
t.Fatalf("low authorization wrote a message")
|
||||
}
|
||||
|
||||
store.starsBalances[42] = 25
|
||||
paidReq := domain.SendMonoforumMessageRequest{MonoforumID: monoID, SenderUserID: 42, SavedPeer: sub, RandomID: 3002, Message: "paid", AllowPaidStars: 99, Date: 1_700_002_002}
|
||||
paid, err := store.SendMonoforumMessage(ctx, paidReq)
|
||||
if err != nil {
|
||||
t.Fatalf("paid send: %v", err)
|
||||
}
|
||||
if paid.Message.PaidMessageStars != 10 || paid.SenderStarsBalance == nil || paid.SenderStarsBalance.Balance != 15 {
|
||||
t.Fatalf("paid result = %+v balance=%+v, want actual 10 and balance 15", paid.Message, paid.SenderStarsBalance)
|
||||
}
|
||||
if store.starsBalances[42] != 15 || store.channelStarsBalances[broadcast.Channel.ID] != 8 {
|
||||
t.Fatalf("ledger sender/channel = %d/%d, want 15/8", store.starsBalances[42], store.channelStarsBalances[broadcast.Channel.ID])
|
||||
}
|
||||
|
||||
duplicate, err := store.SendMonoforumMessage(ctx, paidReq)
|
||||
if err != nil {
|
||||
t.Fatalf("paid replay: %v", err)
|
||||
}
|
||||
if !duplicate.Duplicate || duplicate.Message.ID != paid.Message.ID || duplicate.SenderStarsBalance == nil || duplicate.SenderStarsBalance.Balance != 15 {
|
||||
t.Fatalf("paid replay = %+v, want original message and balance 15", duplicate)
|
||||
}
|
||||
if store.starsBalances[42] != 15 || store.channelStarsBalances[broadcast.Channel.ID] != 8 {
|
||||
t.Fatalf("paid replay double charged: sender/channel=%d/%d", store.starsBalances[42], store.channelStarsBalances[broadcast.Channel.ID])
|
||||
}
|
||||
|
||||
admin, err := store.SendMonoforumMessage(ctx, domain.SendMonoforumMessageRequest{
|
||||
MonoforumID: monoID, SenderUserID: 1, SavedPeer: sub, RandomID: 3003, Message: "free admin reply", AllowPaidStars: 100, Date: 1_700_002_003,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("admin reply: %v", err)
|
||||
}
|
||||
if admin.Message.PaidMessageStars != 0 || admin.SenderStarsBalance != nil || store.channelStarsBalances[broadcast.Channel.ID] != 8 {
|
||||
t.Fatalf("admin reply charged: message=%+v balance=%+v channel=%d", admin.Message, admin.SenderStarsBalance, store.channelStarsBalances[broadcast.Channel.ID])
|
||||
}
|
||||
|
||||
store.starsBalances[99] = 5
|
||||
other := domain.Peer{Type: domain.PeerTypeUser, ID: 99}
|
||||
if _, err := store.SendMonoforumMessage(ctx, domain.SendMonoforumMessageRequest{
|
||||
MonoforumID: monoID, SenderUserID: 99, SavedPeer: other, RandomID: 3004, Message: "insufficient", AllowPaidStars: 10, Date: 1_700_002_004,
|
||||
}); !errors.Is(err, domain.ErrStarsInsufficient) {
|
||||
t.Fatalf("insufficient err = %v, want ErrStarsInsufficient", err)
|
||||
}
|
||||
if store.starsBalances[99] != 5 || store.channelStarsBalances[broadcast.Channel.ID] != 8 {
|
||||
t.Fatalf("insufficient send mutated ledger: sender/channel=%d/%d", store.starsBalances[99], store.channelStarsBalances[broadcast.Channel.ID])
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -168,100 +168,6 @@ func (s *ChannelStore) SetChannelMessageReactions(_ context.Context, req domain.
|
|||
}, nil
|
||||
}
|
||||
|
||||
type memoryPaidReaction struct {
|
||||
stars int64
|
||||
anonymous bool
|
||||
date int
|
||||
}
|
||||
|
||||
// AddChannelMessagePaidReaction 累计 viewer 对一条广播频道消息的付费 reaction 星数(内存镜像)。
|
||||
func (s *ChannelStore) AddChannelMessagePaidReaction(_ context.Context, req domain.SendChannelPaidReactionRequest) (domain.ChannelMessagePaidReactionResult, error) {
|
||||
if req.UserID == 0 || req.ChannelID == 0 || req.MessageID <= 0 || req.MessageID > domain.MaxMessageBoxID {
|
||||
return domain.ChannelMessagePaidReactionResult{}, domain.ErrChannelInvalid
|
||||
}
|
||||
if req.Stars <= 0 || req.Stars > domain.MaxPaidReactionStarsPerRequest {
|
||||
return domain.ChannelMessagePaidReactionResult{}, domain.ErrChannelInvalid
|
||||
}
|
||||
if req.Date == 0 {
|
||||
req.Date = int(time.Now().Unix())
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
channel, member, err := s.channelAndMemberLocked(req.UserID, req.ChannelID)
|
||||
if err != nil {
|
||||
return domain.ChannelMessagePaidReactionResult{}, err
|
||||
}
|
||||
if !channel.Broadcast || channel.Megagroup {
|
||||
return domain.ChannelMessagePaidReactionResult{}, domain.ErrReactionInvalid
|
||||
}
|
||||
msg, ok := s.findMessageLocked(req.ChannelID, req.MessageID)
|
||||
if !ok || msg.Deleted || msg.Action != nil || msg.ID <= member.AvailableMinID {
|
||||
return domain.ChannelMessagePaidReactionResult{}, domain.ErrMessageIDInvalid
|
||||
}
|
||||
if s.paidReactions[req.ChannelID] == nil {
|
||||
s.paidReactions[req.ChannelID] = make(map[int]map[int64]memoryPaidReaction)
|
||||
}
|
||||
if s.paidReactions[req.ChannelID][req.MessageID] == nil {
|
||||
s.paidReactions[req.ChannelID][req.MessageID] = make(map[int64]memoryPaidReaction)
|
||||
}
|
||||
prev := s.paidReactions[req.ChannelID][req.MessageID][req.UserID]
|
||||
s.paidReactions[req.ChannelID][req.MessageID][req.UserID] = memoryPaidReaction{
|
||||
stars: prev.stars + req.Stars,
|
||||
anonymous: req.Anonymous,
|
||||
date: req.Date,
|
||||
}
|
||||
paid := s.aggregatePaidReactionsLocked(req.ChannelID, req.MessageID, req.UserID)
|
||||
outMsg := cloneChannelMessage(msg)
|
||||
reactions := s.channelMessageReactionsLocked(req.UserID, channel, req.MessageID)
|
||||
outMsg.Reactions = cloneChannelMessageReactionsPtr(&reactions)
|
||||
return domain.ChannelMessagePaidReactionResult{
|
||||
Channel: cloneChannel(channel),
|
||||
Message: outMsg,
|
||||
Paid: paid,
|
||||
Recipients: s.activeMemberIDsLocked(req.ChannelID, 0, 0),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *ChannelStore) aggregatePaidReactionsLocked(channelID int64, messageID int, viewerUserID int64) domain.ChannelMessagePaidReactions {
|
||||
byUser := s.paidReactions[channelID][messageID]
|
||||
reactors := make([]domain.PaidReactor, 0, len(byUser))
|
||||
var out domain.ChannelMessagePaidReactions
|
||||
for userID, entry := range byUser {
|
||||
r := domain.PaidReactor{UserID: userID, Stars: entry.stars, Anonymous: entry.anonymous, My: userID == viewerUserID}
|
||||
out.TotalStars += entry.stars
|
||||
if r.My {
|
||||
out.MyStars = entry.stars
|
||||
out.MyAnonymous = entry.anonymous
|
||||
}
|
||||
reactors = append(reactors, r)
|
||||
}
|
||||
sort.Slice(reactors, func(i, j int) bool {
|
||||
if reactors[i].Stars != reactors[j].Stars {
|
||||
return reactors[i].Stars > reactors[j].Stars
|
||||
}
|
||||
return reactors[i].UserID < reactors[j].UserID
|
||||
})
|
||||
myInTop := false
|
||||
for i, r := range reactors {
|
||||
if i >= domain.MaxPaidReactionTopReactors {
|
||||
break
|
||||
}
|
||||
out.TopReactors = append(out.TopReactors, r)
|
||||
if r.My {
|
||||
myInTop = true
|
||||
}
|
||||
}
|
||||
if out.MyStars > 0 && !myInTop {
|
||||
for _, r := range reactors {
|
||||
if r.My {
|
||||
out.TopReactors = append(out.TopReactors, r)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *ChannelStore) DeleteChannelParticipantReaction(_ context.Context, req domain.DeleteChannelParticipantReactionRequest) (domain.ChannelMessageReactionsResult, error) {
|
||||
if req.UserID == 0 || req.ChannelID == 0 || req.MessageID <= 0 || req.MessageID > domain.MaxMessageBoxID || req.ParticipantUserID == 0 {
|
||||
return domain.ChannelMessageReactionsResult{}, domain.ErrChannelInvalid
|
||||
|
|
@ -867,10 +773,6 @@ func (s *ChannelStore) channelMessageReactionsLocked(viewerUserID int64, channel
|
|||
Results: []domain.ChannelMessageReactionCount{},
|
||||
Recent: []domain.ChannelMessagePeerReaction{},
|
||||
}
|
||||
// 付费 reaction 与普通 reaction 分表:即便无普通 reaction 也要回显 ReactionPaid。
|
||||
if paid := s.aggregatePaidReactionsLocked(channel.ID, messageID, viewerUserID); paid.TotalStars > 0 {
|
||||
out.Paid = &paid
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return out
|
||||
}
|
||||
|
|
@ -1012,11 +914,6 @@ func cloneChannelMessageReactionsPtr(in *domain.ChannelMessageReactions) *domain
|
|||
func cloneChannelMessageReactions(in domain.ChannelMessageReactions) domain.ChannelMessageReactions {
|
||||
in.Results = append([]domain.ChannelMessageReactionCount(nil), in.Results...)
|
||||
in.Recent = cloneChannelPeerReactions(in.Recent)
|
||||
if in.Paid != nil {
|
||||
paid := *in.Paid
|
||||
paid.TopReactors = append([]domain.PaidReactor(nil), in.Paid.TopReactors...)
|
||||
in.Paid = &paid
|
||||
}
|
||||
return in
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -63,24 +63,22 @@ func (w channelReadWatermark) advance(userID int64, maxID int) channelReadWaterm
|
|||
|
||||
// ChannelStore is an in-memory channel/supergroup store for tests and local development.
|
||||
type ChannelStore struct {
|
||||
mu sync.RWMutex
|
||||
nextID int64
|
||||
nextHash int64
|
||||
channels map[int64]domain.Channel
|
||||
members map[int64]map[int64]domain.ChannelMember
|
||||
dialogs map[int64]map[int64]domain.ChannelDialog
|
||||
topics map[int64]map[int]domain.ChannelForumTopic
|
||||
messages map[int64][]domain.ChannelMessage
|
||||
reactions map[int64]map[int]map[int64][]domain.ChannelMessagePeerReaction
|
||||
// paidReactions 是 per-(channel,message,user) 付费 reaction 累计星数 + 匿名标志。
|
||||
paidReactions map[int64]map[int]map[int64]memoryPaidReaction
|
||||
top map[int64]map[string]domain.TopMessageReaction
|
||||
recent map[int64]map[string]domain.RecentMessageReaction
|
||||
mentions map[int64]map[int64]map[int]memoryMention
|
||||
msgViews map[int64]map[int]int
|
||||
msgViewers map[int64]map[int]map[int64]struct{}
|
||||
events map[int64][]domain.ChannelUpdateEvent
|
||||
retention map[int64]domain.ChannelUpdateRetentionCheckpoint
|
||||
mu sync.RWMutex
|
||||
nextID int64
|
||||
nextHash int64
|
||||
channels map[int64]domain.Channel
|
||||
members map[int64]map[int64]domain.ChannelMember
|
||||
dialogs map[int64]map[int64]domain.ChannelDialog
|
||||
topics map[int64]map[int]domain.ChannelForumTopic
|
||||
messages map[int64][]domain.ChannelMessage
|
||||
reactions map[int64]map[int]map[int64][]domain.ChannelMessagePeerReaction
|
||||
top map[int64]map[string]domain.TopMessageReaction
|
||||
recent map[int64]map[string]domain.RecentMessageReaction
|
||||
mentions map[int64]map[int64]map[int]memoryMention
|
||||
msgViews map[int64]map[int]int
|
||||
msgViewers map[int64]map[int]map[int64]struct{}
|
||||
events map[int64][]domain.ChannelUpdateEvent
|
||||
retention map[int64]domain.ChannelUpdateRetentionCheckpoint
|
||||
// historyClearDates is the no-PTS recovery timestamp for a future
|
||||
// owner-local clear, keyed by channel then user. The member remains the
|
||||
// absolute boundary authority; this map only makes account difference
|
||||
|
|
@ -134,7 +132,6 @@ func NewChannelStore() *ChannelStore {
|
|||
topics: make(map[int64]map[int]domain.ChannelForumTopic),
|
||||
messages: make(map[int64][]domain.ChannelMessage),
|
||||
reactions: make(map[int64]map[int]map[int64][]domain.ChannelMessagePeerReaction),
|
||||
paidReactions: make(map[int64]map[int]map[int64]memoryPaidReaction),
|
||||
top: make(map[int64]map[string]domain.TopMessageReaction),
|
||||
recent: make(map[int64]map[string]domain.RecentMessageReaction),
|
||||
mentions: make(map[int64]map[int64]map[int]memoryMention),
|
||||
|
|
|
|||
|
|
@ -117,26 +117,9 @@ func (s *ChannelStore) toggleSuggestedPostApprovalLocked(req domain.ToggleSugges
|
|||
return base, nil
|
||||
}
|
||||
|
||||
starsBalance, tonBalance, enough := s.reserveSuggestedPostPaymentLocked(original.SavedPeer.ID, parent.ID, price)
|
||||
if !enough {
|
||||
if exists {
|
||||
out := cloneSuggestedPostResult(approval.lastResult)
|
||||
out.PayerStarsBalance, out.PayerTONBalance = starsBalance, tonBalance
|
||||
out.Duplicate = true
|
||||
return out, nil
|
||||
}
|
||||
service, serviceEvent := s.appendSuggestedPostServiceLocked(mono, parent, req.UserID, original.SavedPeer, original.ID, req.Date, domain.ChannelMessageAction{
|
||||
Type: domain.ChannelActionSuggestedPostApproval, SuggestedPostBalanceTooLow: true,
|
||||
SuggestedPostScheduleDate: scheduleDate, SuggestedPostPrice: price,
|
||||
})
|
||||
base.Monoforum = cloneChannel(s.channels[mono.ID])
|
||||
base.ServiceMessage, base.ServiceEvent = cloneChannelMessage(service), cloneChannelEvent(serviceEvent)
|
||||
base.PayerStarsBalance, base.PayerTONBalance = starsBalance, tonBalance
|
||||
approval = memorySuggestedPostApproval{actorUserID: req.UserID, parentID: parent.ID, savedPeer: original.SavedPeer, state: base.State, price: price, scheduleDate: scheduleDate, lastResult: cloneSuggestedPostResult(base)}
|
||||
s.suggestedPostApprovals[key] = approval
|
||||
return base, nil
|
||||
}
|
||||
|
||||
// telesrv has no Stars economy: a suggested post is approved for free
|
||||
// regardless of any price attached to it, so the balance-check/collect
|
||||
// step and its "balance too low" retry state are skipped entirely.
|
||||
original.SuggestedPost.Accepted = true
|
||||
original.SuggestedPost.Rejected = false
|
||||
effectivePublishDate := scheduleDate
|
||||
|
|
@ -150,19 +133,16 @@ func (s *ChannelStore) toggleSuggestedPostApprovalLocked(req domain.ToggleSugges
|
|||
})
|
||||
base.Monoforum, base.OriginalMessage, base.OriginalEvent = cloneChannel(s.channels[mono.ID]), cloneChannelMessage(original), cloneChannelEvent(edit)
|
||||
base.ServiceMessage, base.ServiceEvent = cloneChannelMessage(service), cloneChannelEvent(serviceEvent)
|
||||
base.PayerStarsBalance, base.PayerTONBalance = starsBalance, tonBalance
|
||||
base.State = domain.SuggestedPostStateScheduled
|
||||
approval = memorySuggestedPostApproval{actorUserID: req.UserID, parentID: parent.ID, savedPeer: original.SavedPeer, state: base.State, price: price, scheduleDate: effectivePublishDate}
|
||||
if effectivePublishDate <= req.Date {
|
||||
published := s.publishSuggestedPostLocked(parent, original, req.UserID, req.Date)
|
||||
base.Published = &published
|
||||
approval.publishedMessageID = published.Message.ID
|
||||
if price == nil {
|
||||
base.State = domain.SuggestedPostStateCompleted
|
||||
} else {
|
||||
base.State = domain.SuggestedPostStatePublished
|
||||
approval.settlementDue = req.Date + suggestedPostSettlementAge
|
||||
}
|
||||
// telesrv has no Stars economy: nothing was ever charged, so a
|
||||
// published post goes straight to Completed -- there is no
|
||||
// settlement window regardless of any attached price.
|
||||
base.State = domain.SuggestedPostStateCompleted
|
||||
approval.state = base.State
|
||||
}
|
||||
approval.lastResult = cloneSuggestedPostResult(base)
|
||||
|
|
@ -212,55 +192,21 @@ func (s *ChannelStore) ProcessSuggestedPostLifecycle(_ context.Context, req doma
|
|||
}
|
||||
result := domain.ToggleSuggestedPostApprovalResult{Monoforum: cloneChannel(mono), Parent: cloneChannel(parent), SavedPeer: approval.savedPeer, State: approval.state, Recipients: s.monoforumRecipientsLocked(parent.ID, approval.savedPeer.ID)}
|
||||
changed := false
|
||||
// telesrv has no Stars economy: nothing was ever charged, so a deleted
|
||||
// scheduled post is simply dropped (Refunded is the closest existing
|
||||
// terminal state, reused here so downstream event handling stays
|
||||
// uniform) and a published post is Completed immediately -- there is
|
||||
// no settlement window and no refund path to run.
|
||||
if approval.state == domain.SuggestedPostStateScheduled && original.Deleted {
|
||||
if approval.price != nil {
|
||||
s.refundSuggestedPostPaymentLocked(approval.savedPeer.ID, approval.price)
|
||||
service, event := s.appendSuggestedPostServiceLocked(mono, parent, approval.actorUserID, approval.savedPeer, key.messageID, req.Now, domain.ChannelMessageAction{Type: domain.ChannelActionSuggestedPostRefund})
|
||||
result.ServiceMessage, result.ServiceEvent = service, event
|
||||
}
|
||||
approval.state, result.State, changed = domain.SuggestedPostStateRefunded, domain.SuggestedPostStateRefunded, true
|
||||
}
|
||||
if approval.state == domain.SuggestedPostStateScheduled && approval.scheduleDate <= req.Now {
|
||||
published := s.publishSuggestedPostLocked(parent, original, approval.actorUserID, req.Now)
|
||||
result.Published = &published
|
||||
approval.publishedMessageID = published.Message.ID
|
||||
if approval.price == nil {
|
||||
approval.state = domain.SuggestedPostStateCompleted
|
||||
} else {
|
||||
approval.state = domain.SuggestedPostStatePublished
|
||||
approval.settlementDue = req.Now + suggestedPostSettlementAge
|
||||
}
|
||||
approval.state = domain.SuggestedPostStateCompleted
|
||||
result.State, changed = approval.state, true
|
||||
}
|
||||
if approval.state == domain.SuggestedPostStatePublished {
|
||||
if approval.price == nil || approval.publishedMessageID <= 0 || approval.settlementDue <= 0 {
|
||||
return out, fmt.Errorf("suggested post lifecycle invariant: incomplete published state %d/%d", mono.ID, key.messageID)
|
||||
}
|
||||
deleted := false
|
||||
publishedFound := false
|
||||
for _, message := range s.messages[parent.ID] {
|
||||
if message.ID == approval.publishedMessageID {
|
||||
deleted = message.Deleted
|
||||
publishedFound = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !publishedFound {
|
||||
return out, fmt.Errorf("suggested post lifecycle invariant: missing published message %d/%d", parent.ID, approval.publishedMessageID)
|
||||
}
|
||||
deleteDate := s.channelMessageDeleteDateLocked(parent.ID, approval.publishedMessageID)
|
||||
if deleted && (deleteDate == 0 || deleteDate < approval.settlementDue) {
|
||||
s.refundSuggestedPostPaymentLocked(approval.savedPeer.ID, approval.price)
|
||||
service, event := s.appendSuggestedPostServiceLocked(mono, parent, approval.actorUserID, approval.savedPeer, key.messageID, req.Now, domain.ChannelMessageAction{Type: domain.ChannelActionSuggestedPostRefund})
|
||||
result.ServiceMessage, result.ServiceEvent = service, event
|
||||
approval.state, result.State, changed = domain.SuggestedPostStateRefunded, domain.SuggestedPostStateRefunded, true
|
||||
} else if approval.settlementDue <= req.Now {
|
||||
s.settleSuggestedPostPaymentLocked(parent.ID, approval.price)
|
||||
service, event := s.appendSuggestedPostServiceLocked(mono, parent, approval.actorUserID, approval.savedPeer, key.messageID, req.Now, domain.ChannelMessageAction{Type: domain.ChannelActionSuggestedPostSuccess, SuggestedPostPrice: cloneSuggestedPostPrice(approval.price)})
|
||||
result.ServiceMessage, result.ServiceEvent = service, event
|
||||
approval.state, result.State, changed = domain.SuggestedPostStateCompleted, domain.SuggestedPostStateCompleted, true
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
result.Monoforum, result.Parent = cloneChannel(s.channels[mono.ID]), cloneChannel(s.channels[parent.ID])
|
||||
approval.lastResult = cloneSuggestedPostResult(result)
|
||||
|
|
@ -286,61 +232,6 @@ func (s *ChannelStore) channelMessageDeleteDateLocked(channelID int64, messageID
|
|||
return 0
|
||||
}
|
||||
|
||||
func (s *ChannelStore) reserveSuggestedPostPaymentLocked(payerID, parentID int64, price *domain.SuggestedPostPrice) (*domain.StarsBalance, *int64, bool) {
|
||||
if price == nil {
|
||||
return nil, nil, true
|
||||
}
|
||||
switch price.Kind {
|
||||
case domain.SuggestedPostPriceStars:
|
||||
current, ok := s.starsBalances[payerID]
|
||||
if !ok {
|
||||
current = domain.DefaultStarsStartingGrant
|
||||
}
|
||||
balance := &domain.StarsBalance{UserID: payerID, Balance: current, Granted: true}
|
||||
if price.Nanos != 0 || current < price.Amount {
|
||||
return balance, nil, false
|
||||
}
|
||||
current -= price.Amount
|
||||
s.starsBalances[payerID] = current
|
||||
balance.Balance = current
|
||||
return balance, nil, true
|
||||
case domain.SuggestedPostPriceTON:
|
||||
current := s.tonBalances[payerID]
|
||||
balance := current
|
||||
if current < price.Amount {
|
||||
return nil, &balance, false
|
||||
}
|
||||
current -= price.Amount
|
||||
s.tonBalances[payerID] = current
|
||||
balance = current
|
||||
return nil, &balance, true
|
||||
default:
|
||||
return nil, nil, false
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ChannelStore) refundSuggestedPostPaymentLocked(payerID int64, price *domain.SuggestedPostPrice) {
|
||||
if price == nil {
|
||||
return
|
||||
}
|
||||
if price.Kind == domain.SuggestedPostPriceStars {
|
||||
s.starsBalances[payerID] += price.Amount
|
||||
} else if price.Kind == domain.SuggestedPostPriceTON {
|
||||
s.tonBalances[payerID] += price.Amount
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ChannelStore) settleSuggestedPostPaymentLocked(parentID int64, price *domain.SuggestedPostPrice) {
|
||||
if price == nil {
|
||||
return
|
||||
}
|
||||
credit := price.Amount * paidMessageChannelCommissionPermille / 1000
|
||||
if price.Kind == domain.SuggestedPostPriceStars {
|
||||
s.channelStarsBalances[parentID] += credit
|
||||
} else if price.Kind == domain.SuggestedPostPriceTON {
|
||||
s.channelTONBalances[parentID] += credit
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ChannelStore) appendSuggestedPostServiceLocked(mono, parent domain.Channel, actor int64, saved domain.Peer, replyID, date int, action domain.ChannelMessageAction) (domain.ChannelMessage, domain.ChannelUpdateEvent) {
|
||||
pts := s.nextChannelPtsLocked(mono.ID)
|
||||
|
|
@ -406,13 +297,5 @@ func cloneSuggestedPostResult(in domain.ToggleSuggestedPostApprovalResult) domai
|
|||
p.Recipients = append([]int64(nil), p.Recipients...)
|
||||
in.Published = &p
|
||||
}
|
||||
if in.PayerStarsBalance != nil {
|
||||
b := *in.PayerStarsBalance
|
||||
in.PayerStarsBalance = &b
|
||||
}
|
||||
if in.PayerTONBalance != nil {
|
||||
b := *in.PayerTONBalance
|
||||
in.PayerTONBalance = &b
|
||||
}
|
||||
return in
|
||||
}
|
||||
|
|
|
|||
|
|
@ -76,10 +76,9 @@ func TestMonoforumManagerRequiresManageDirectMessages(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestSuggestedPostStarsApprovalRefundAndSettlement(t *testing.T) {
|
||||
func TestSuggestedPostApprovalRefundAndSettlement(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store, parent, mono, subscriber := newSuggestedPostMemoryFixture(t)
|
||||
store.starsBalances[subscriber.ID] = 100
|
||||
|
||||
suggestion, err := store.SendMonoforumMessage(ctx, domain.SendMonoforumMessageRequest{MonoforumID: mono.ID, SenderUserID: subscriber.ID, SavedPeer: subscriber, RandomID: 11, Message: "publish me", SuggestedPost: &domain.SuggestedPost{Price: &domain.SuggestedPostPrice{Kind: domain.SuggestedPostPriceStars, Amount: 10}}, Date: 1_700_000_100})
|
||||
if err != nil {
|
||||
|
|
@ -89,22 +88,22 @@ func TestSuggestedPostStarsApprovalRefundAndSettlement(t *testing.T) {
|
|||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if approved.State != domain.SuggestedPostStatePublished || approved.OriginalEvent.Type != domain.ChannelUpdateEditMessage || approved.ServiceMessage.Action == nil || approved.ServiceMessage.Action.Type != domain.ChannelActionSuggestedPostApproval || approved.Published == nil {
|
||||
if approved.State != domain.SuggestedPostStateCompleted || approved.OriginalEvent.Type != domain.ChannelUpdateEditMessage || approved.ServiceMessage.Action == nil || approved.ServiceMessage.Action.Type != domain.ChannelActionSuggestedPostApproval || approved.Published == nil {
|
||||
t.Fatalf("approval result=%+v", approved)
|
||||
}
|
||||
if approved.OriginalMessage.SuggestedPost.ScheduleDate != 1_700_000_200 || approved.ServiceMessage.Action.SuggestedPostScheduleDate != 1_700_000_200 {
|
||||
t.Fatalf("immediate approval dates original/action=%d/%d, want commit date", approved.OriginalMessage.SuggestedPost.ScheduleDate, approved.ServiceMessage.Action.SuggestedPostScheduleDate)
|
||||
}
|
||||
if store.starsBalances[subscriber.ID] != 90 || store.channelStarsBalances[parent.ID] != 0 {
|
||||
t.Fatalf("escrow/channel balances=%d/%d, want 90/0", store.starsBalances[subscriber.ID], store.channelStarsBalances[parent.ID])
|
||||
}
|
||||
duplicate, err := store.ToggleSuggestedPostApproval(ctx, domain.ToggleSuggestedPostApprovalRequest{UserID: 1, MonoforumID: mono.ID, MessageID: suggestion.Message.ID, Date: 1_700_000_201})
|
||||
if err != nil || !duplicate.Duplicate || store.starsBalances[subscriber.ID] != 90 {
|
||||
t.Fatalf("duplicate=%+v err=%v balance=%d", duplicate, err, store.starsBalances[subscriber.ID])
|
||||
if err != nil || !duplicate.Duplicate {
|
||||
t.Fatalf("duplicate=%+v err=%v", duplicate, err)
|
||||
}
|
||||
if duplicate.OriginalMessage.SuggestedPost.ScheduleDate != 1_700_000_200 || duplicate.ServiceMessage.Action.SuggestedPostScheduleDate != 1_700_000_200 {
|
||||
t.Fatalf("duplicate changed immediate approval date: %+v", duplicate)
|
||||
}
|
||||
// An immediate approval is already terminal (Completed): there is nothing
|
||||
// left to settle, so deleting the published post afterwards must not
|
||||
// surface it again through the lifecycle worker.
|
||||
store.mu.Lock()
|
||||
for i := range store.messages[parent.ID] {
|
||||
if store.messages[parent.ID][i].ID == approved.Published.Message.ID {
|
||||
|
|
@ -112,54 +111,59 @@ func TestSuggestedPostStarsApprovalRefundAndSettlement(t *testing.T) {
|
|||
}
|
||||
}
|
||||
store.mu.Unlock()
|
||||
lifecycle, err := store.ProcessSuggestedPostLifecycle(ctx, domain.SuggestedPostLifecycleRequest{Now: 1_700_000_300, Limit: 10})
|
||||
if err != nil || len(lifecycle) != 1 || lifecycle[0].State != domain.SuggestedPostStateRefunded || lifecycle[0].ServiceMessage.Action.Type != domain.ChannelActionSuggestedPostRefund {
|
||||
t.Fatalf("refund lifecycle=%+v err=%v", lifecycle, err)
|
||||
}
|
||||
if store.starsBalances[subscriber.ID] != 100 || store.channelStarsBalances[parent.ID] != 0 {
|
||||
t.Fatalf("refund balances=%d/%d, want 100/0", store.starsBalances[subscriber.ID], store.channelStarsBalances[parent.ID])
|
||||
if lifecycle, err := store.ProcessSuggestedPostLifecycle(ctx, domain.SuggestedPostLifecycleRequest{Now: 1_700_000_300, Limit: 10}); err != nil || len(lifecycle) != 0 {
|
||||
t.Fatalf("already-completed post must not be revisited: lifecycle=%+v err=%v", lifecycle, err)
|
||||
}
|
||||
|
||||
second, err := store.SendMonoforumMessage(ctx, domain.SendMonoforumMessageRequest{MonoforumID: mono.ID, SenderUserID: subscriber.ID, SavedPeer: subscriber, RandomID: 12, Message: "settle me", SuggestedPost: &domain.SuggestedPost{Price: &domain.SuggestedPostPrice{Kind: domain.SuggestedPostPriceStars, Amount: 20}}, Date: 1_700_000_400})
|
||||
// A scheduled (not-yet-due) approval still refunds via the lifecycle
|
||||
// worker if the suggestion is deleted before its publish date.
|
||||
second, err := store.SendMonoforumMessage(ctx, domain.SendMonoforumMessageRequest{MonoforumID: mono.ID, SenderUserID: subscriber.ID, SavedPeer: subscriber, RandomID: 12, Message: "cancel scheduled", SuggestedPost: &domain.SuggestedPost{Price: &domain.SuggestedPostPrice{Kind: domain.SuggestedPostPriceStars, Amount: 20}}, Date: 1_700_000_400})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
settling, err := store.ToggleSuggestedPostApproval(ctx, domain.ToggleSuggestedPostApprovalRequest{UserID: 1, MonoforumID: mono.ID, MessageID: second.Message.ID, Date: 1_700_000_500})
|
||||
if err != nil || settling.State != domain.SuggestedPostStatePublished {
|
||||
t.Fatalf("second approval=%+v err=%v", settling, err)
|
||||
scheduled, err := store.ToggleSuggestedPostApproval(ctx, domain.ToggleSuggestedPostApprovalRequest{UserID: 1, MonoforumID: mono.ID, MessageID: second.Message.ID, ScheduleDate: 1_700_000_900, Date: 1_700_000_401})
|
||||
if err != nil || scheduled.State != domain.SuggestedPostStateScheduled {
|
||||
t.Fatalf("scheduled approval=%+v err=%v", scheduled, err)
|
||||
}
|
||||
lifecycle, err = store.ProcessSuggestedPostLifecycle(ctx, domain.SuggestedPostLifecycleRequest{Now: 1_700_000_500 + suggestedPostSettlementAge, Limit: 10})
|
||||
if err != nil || len(lifecycle) != 1 || lifecycle[0].State != domain.SuggestedPostStateCompleted || lifecycle[0].ServiceMessage.Action.Type != domain.ChannelActionSuggestedPostSuccess {
|
||||
t.Fatalf("success lifecycle=%+v err=%v", lifecycle, err)
|
||||
store.mu.Lock()
|
||||
for i := range store.messages[mono.ID] {
|
||||
if store.messages[mono.ID][i].ID == second.Message.ID {
|
||||
store.messages[mono.ID][i].Deleted = true
|
||||
}
|
||||
}
|
||||
if store.starsBalances[subscriber.ID] != 80 || store.channelStarsBalances[parent.ID] != 17 {
|
||||
t.Fatalf("settled balances=%d/%d, want 80/17", store.starsBalances[subscriber.ID], store.channelStarsBalances[parent.ID])
|
||||
store.mu.Unlock()
|
||||
lifecycle, err := store.ProcessSuggestedPostLifecycle(ctx, domain.SuggestedPostLifecycleRequest{Now: 1_700_000_500, Limit: 10})
|
||||
if err != nil || len(lifecycle) != 1 || lifecycle[0].State != domain.SuggestedPostStateRefunded {
|
||||
t.Fatalf("refund lifecycle=%+v err=%v", lifecycle, err)
|
||||
}
|
||||
|
||||
third, err := store.SendMonoforumMessage(ctx, domain.SendMonoforumMessageRequest{MonoforumID: mono.ID, SenderUserID: subscriber.ID, SavedPeer: subscriber, RandomID: 13, Message: "settle me", SuggestedPost: &domain.SuggestedPost{Price: &domain.SuggestedPostPrice{Kind: domain.SuggestedPostPriceStars, Amount: 20}}, Date: 1_700_000_600})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
settling, err := store.ToggleSuggestedPostApproval(ctx, domain.ToggleSuggestedPostApprovalRequest{UserID: 1, MonoforumID: mono.ID, MessageID: third.Message.ID, Date: 1_700_000_700})
|
||||
if err != nil || settling.State != domain.SuggestedPostStateCompleted {
|
||||
t.Fatalf("third approval=%+v err=%v", settling, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSuggestedPostLowBalanceRetryScheduleAndRoleMatrix(t *testing.T) {
|
||||
func TestSuggestedPostScheduleRetryAndRoleMatrix(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store, parent, mono, subscriber := newSuggestedPostMemoryFixture(t)
|
||||
store.starsBalances[subscriber.ID] = 5
|
||||
suggestion, err := store.SendMonoforumMessage(ctx, domain.SendMonoforumMessageRequest{MonoforumID: mono.ID, SenderUserID: subscriber.ID, SavedPeer: subscriber, RandomID: 21, Message: "later", SuggestedPost: &domain.SuggestedPost{Price: &domain.SuggestedPostPrice{Kind: domain.SuggestedPostPriceStars, Amount: 10}}, Date: 1_700_001_000})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
low, err := store.ToggleSuggestedPostApproval(ctx, domain.ToggleSuggestedPostApprovalRequest{UserID: 1, MonoforumID: mono.ID, MessageID: suggestion.Message.ID, ScheduleDate: 1_700_001_400, Date: 1_700_001_000})
|
||||
if err != nil || low.State != domain.SuggestedPostStateBalanceLow || low.ServiceMessage.Action == nil || !low.ServiceMessage.Action.SuggestedPostBalanceTooLow {
|
||||
t.Fatalf("low=%+v err=%v", low, err)
|
||||
}
|
||||
again, err := store.ToggleSuggestedPostApproval(ctx, domain.ToggleSuggestedPostApprovalRequest{UserID: 1, MonoforumID: mono.ID, MessageID: suggestion.Message.ID, ScheduleDate: 1_700_001_400, Date: 1_700_001_001})
|
||||
if err != nil || !again.Duplicate {
|
||||
t.Fatalf("low retry=%+v err=%v", again, err)
|
||||
}
|
||||
store.starsBalances[subscriber.ID] = 20
|
||||
accepted, err := store.ToggleSuggestedPostApproval(ctx, domain.ToggleSuggestedPostApprovalRequest{UserID: 1, MonoforumID: mono.ID, MessageID: suggestion.Message.ID, ScheduleDate: 1_700_001_400, Date: 1_700_001_050})
|
||||
if err != nil || accepted.State != domain.SuggestedPostStateScheduled || accepted.Published != nil {
|
||||
t.Fatalf("scheduled=%+v err=%v", accepted, err)
|
||||
}
|
||||
again, err := store.ToggleSuggestedPostApproval(ctx, domain.ToggleSuggestedPostApprovalRequest{UserID: 1, MonoforumID: mono.ID, MessageID: suggestion.Message.ID, ScheduleDate: 1_700_001_400, Date: 1_700_001_051})
|
||||
if err != nil || !again.Duplicate {
|
||||
t.Fatalf("schedule retry=%+v err=%v", again, err)
|
||||
}
|
||||
due, err := store.ProcessSuggestedPostLifecycle(ctx, domain.SuggestedPostLifecycleRequest{Now: 1_700_001_400, Limit: 10})
|
||||
if err != nil || len(due) != 1 || due[0].Published == nil || due[0].State != domain.SuggestedPostStatePublished {
|
||||
if err != nil || len(due) != 1 || due[0].Published == nil || due[0].State != domain.SuggestedPostStateCompleted {
|
||||
t.Fatalf("due=%+v err=%v", due, err)
|
||||
}
|
||||
|
||||
|
|
@ -277,8 +281,7 @@ func TestChannelAuthoredSuggestedPostAcceptedBySubscriber(t *testing.T) {
|
|||
|
||||
func TestScheduledSuggestedPostDeletionRefundsBeforePublication(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store, parent, mono, subscriber := newSuggestedPostMemoryFixture(t)
|
||||
store.starsBalances[subscriber.ID] = 30
|
||||
store, _, mono, subscriber := newSuggestedPostMemoryFixture(t)
|
||||
suggestion, err := store.SendMonoforumMessage(ctx, domain.SendMonoforumMessageRequest{MonoforumID: mono.ID, SenderUserID: subscriber.ID, SavedPeer: subscriber, RandomID: 41, Message: "cancel scheduled", SuggestedPost: &domain.SuggestedPost{Price: &domain.SuggestedPostPrice{Kind: domain.SuggestedPostPriceStars, Amount: 10}}, Date: 1_700_004_000})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
|
@ -298,9 +301,6 @@ func TestScheduledSuggestedPostDeletionRefundsBeforePublication(t *testing.T) {
|
|||
if err != nil || len(resolved) != 1 || resolved[0].State != domain.SuggestedPostStateRefunded || resolved[0].Published != nil {
|
||||
t.Fatalf("resolved=%+v err=%v", resolved, err)
|
||||
}
|
||||
if store.starsBalances[subscriber.ID] != 30 || store.channelStarsBalances[parent.ID] != 0 {
|
||||
t.Fatalf("balances=%d/%d", store.starsBalances[subscriber.ID], store.channelStarsBalances[parent.ID])
|
||||
}
|
||||
}
|
||||
|
||||
func TestSuggestedPostLifecycleFailsFastOnCorruptAcceptedState(t *testing.T) {
|
||||
|
|
@ -332,28 +332,9 @@ func TestSuggestedPostLifecycleFailsFastOnCorruptAcceptedState(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestSuggestedPostDeletedAfterMinimumAgeStillSettles(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store, parent, mono, subscriber := newSuggestedPostMemoryFixture(t)
|
||||
store.starsBalances[subscriber.ID] = 30
|
||||
suggestion, err := store.SendMonoforumMessage(ctx, domain.SendMonoforumMessageRequest{MonoforumID: mono.ID, SenderUserID: subscriber.ID, SavedPeer: subscriber, RandomID: 51, Message: "late delete", SuggestedPost: &domain.SuggestedPost{Price: &domain.SuggestedPostPrice{Kind: domain.SuggestedPostPriceStars, Amount: 10}}, Date: 1_700_005_000})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
approvedAt := 1_700_005_100
|
||||
approved, err := store.ToggleSuggestedPostApproval(ctx, domain.ToggleSuggestedPostApprovalRequest{UserID: 1, MonoforumID: mono.ID, MessageID: suggestion.Message.ID, Date: approvedAt})
|
||||
if err != nil || approved.Published == nil {
|
||||
t.Fatalf("approved=%+v err=%v", approved, err)
|
||||
}
|
||||
due := approvedAt + suggestedPostSettlementAge
|
||||
if _, err := store.DeleteChannelMessages(ctx, domain.DeleteChannelMessagesRequest{UserID: 1, ChannelID: parent.ID, IDs: []int{approved.Published.Message.ID}, Date: due + 1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resolved, err := store.ProcessSuggestedPostLifecycle(ctx, domain.SuggestedPostLifecycleRequest{Now: due + 2, Limit: 10})
|
||||
if err != nil || len(resolved) != 1 || resolved[0].State != domain.SuggestedPostStateCompleted || resolved[0].ServiceMessage.Action == nil || resolved[0].ServiceMessage.Action.Type != domain.ChannelActionSuggestedPostSuccess {
|
||||
t.Fatalf("resolved=%+v err=%v", resolved, err)
|
||||
}
|
||||
if store.starsBalances[subscriber.ID] != 20 || store.channelStarsBalances[parent.ID] != 8 {
|
||||
t.Fatalf("balances=%d/%d, want 20/8", store.starsBalances[subscriber.ID], store.channelStarsBalances[parent.ID])
|
||||
}
|
||||
}
|
||||
// An immediately-approved suggested post is terminal (Completed) the moment
|
||||
// it is published -- there is no settlement window anymore (telesrv has no
|
||||
// Stars economy, so nothing is ever collected that would need settling).
|
||||
// Deleting the published post afterwards is therefore a no-op for the
|
||||
// suggested-post lifecycle; see TestSuggestedPostApprovalRefundAndSettlement
|
||||
// for that assertion.
|
||||
|
|
|
|||
|
|
@ -1,122 +0,0 @@
|
|||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"telesrv/internal/domain"
|
||||
)
|
||||
|
||||
func seedBroadcastPost(t *testing.T, st *ChannelStore, creator int64, broadcast bool) (channelID int64, msgID int) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
created, err := st.CreateChannel(ctx, domain.CreateChannelRequest{
|
||||
CreatorUserID: creator,
|
||||
Title: "Paid",
|
||||
Broadcast: broadcast,
|
||||
Megagroup: !broadcast,
|
||||
Date: 1700000000,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("create channel: %v", err)
|
||||
}
|
||||
sent, err := st.SendChannelMessage(ctx, domain.SendChannelMessageRequest{
|
||||
UserID: creator,
|
||||
ChannelID: created.Channel.ID,
|
||||
Message: "post",
|
||||
Date: 1700000000,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("send channel message: %v", err)
|
||||
}
|
||||
return created.Channel.ID, sent.Message.ID
|
||||
}
|
||||
|
||||
// 付费 reaction 累计 + 聚合:同一 reactor 多次增投累加,TopReactors 含本人带 My。
|
||||
func TestAddChannelMessagePaidReactionAccumulates(t *testing.T) {
|
||||
st := NewChannelStore()
|
||||
ctx := context.Background()
|
||||
const creator = int64(1000000001)
|
||||
channelID, msgID := seedBroadcastPost(t, st, creator, true)
|
||||
|
||||
res, err := st.AddChannelMessagePaidReaction(ctx, domain.SendChannelPaidReactionRequest{
|
||||
UserID: creator, ChannelID: channelID, MessageID: msgID, Stars: 100, Date: 1700000001,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("first paid reaction: %v", err)
|
||||
}
|
||||
if res.Paid.TotalStars != 100 || res.Paid.MyStars != 100 {
|
||||
t.Fatalf("after 100 = total %d my %d, want 100/100", res.Paid.TotalStars, res.Paid.MyStars)
|
||||
}
|
||||
|
||||
res, err = st.AddChannelMessagePaidReaction(ctx, domain.SendChannelPaidReactionRequest{
|
||||
UserID: creator, ChannelID: channelID, MessageID: msgID, Stars: 50, Date: 1700000002,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("second paid reaction: %v", err)
|
||||
}
|
||||
if res.Paid.TotalStars != 150 || res.Paid.MyStars != 150 {
|
||||
t.Fatalf("after +50 = total %d my %d, want 150/150 (accumulated)", res.Paid.TotalStars, res.Paid.MyStars)
|
||||
}
|
||||
if len(res.Paid.TopReactors) != 1 || res.Paid.TopReactors[0].Stars != 150 || !res.Paid.TopReactors[0].My {
|
||||
t.Fatalf("top reactors = %+v, want one My 150", res.Paid.TopReactors)
|
||||
}
|
||||
}
|
||||
|
||||
// 多 reactor:TopReactors 按星数降序,本人始终在列。
|
||||
func TestAddChannelMessagePaidReactionTopReactors(t *testing.T) {
|
||||
st := NewChannelStore()
|
||||
ctx := context.Background()
|
||||
const creator = int64(1000000001)
|
||||
channelID, msgID := seedBroadcastPost(t, st, creator, true)
|
||||
// 让另外两个用户成为成员并增投(直接写 store 累计,绕过成员校验仅测聚合)。
|
||||
for _, c := range []struct {
|
||||
user int64
|
||||
stars int64
|
||||
}{{creator, 30}, {2000000002, 200}, {2000000003, 80}} {
|
||||
// 仅 creator 经正式路径;其他用户直接累计以构造排行。
|
||||
if c.user == creator {
|
||||
if _, err := st.AddChannelMessagePaidReaction(ctx, domain.SendChannelPaidReactionRequest{
|
||||
UserID: c.user, ChannelID: channelID, MessageID: msgID, Stars: c.stars, Date: 1700000010,
|
||||
}); err != nil {
|
||||
t.Fatalf("creator paid reaction: %v", err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
st.mu.Lock()
|
||||
st.paidReactions[channelID][msgID][c.user] = memoryPaidReaction{stars: c.stars, date: 1700000010}
|
||||
st.mu.Unlock()
|
||||
}
|
||||
res, err := st.AddChannelMessagePaidReaction(ctx, domain.SendChannelPaidReactionRequest{
|
||||
UserID: creator, ChannelID: channelID, MessageID: msgID, Stars: 0 + 1, Date: 1700000011,
|
||||
})
|
||||
// creator 现在 31+? 重新算:creator 30 + 这次 1 = 31。
|
||||
if err != nil {
|
||||
t.Fatalf("paid reaction: %v", err)
|
||||
}
|
||||
if res.Paid.TotalStars != 31+200+80 {
|
||||
t.Fatalf("total = %d, want %d", res.Paid.TotalStars, 31+200+80)
|
||||
}
|
||||
// 降序:200, 80, 31。
|
||||
if len(res.Paid.TopReactors) != 3 || res.Paid.TopReactors[0].Stars != 200 || res.Paid.TopReactors[1].Stars != 80 || res.Paid.TopReactors[2].Stars != 31 {
|
||||
t.Fatalf("top reactors = %+v, want 200/80/31 desc", res.Paid.TopReactors)
|
||||
}
|
||||
if !res.Paid.TopReactors[2].My {
|
||||
t.Fatalf("creator (31) must carry My flag, got %+v", res.Paid.TopReactors[2])
|
||||
}
|
||||
}
|
||||
|
||||
// 非广播频道拒绝付费 reaction。
|
||||
func TestAddChannelMessagePaidReactionRejectsMegagroup(t *testing.T) {
|
||||
st := NewChannelStore()
|
||||
ctx := context.Background()
|
||||
const creator = int64(1000000001)
|
||||
channelID, msgID := seedBroadcastPost(t, st, creator, false)
|
||||
_, err := st.AddChannelMessagePaidReaction(ctx, domain.SendChannelPaidReactionRequest{
|
||||
UserID: creator, ChannelID: channelID, MessageID: msgID, Stars: 10, Date: 1700000001,
|
||||
})
|
||||
if !errors.Is(err, domain.ErrReactionInvalid) {
|
||||
t.Fatalf("megagroup paid reaction err = %v, want ErrReactionInvalid", err)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,938 +0,0 @@
|
|||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math/rand/v2"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"telesrv/internal/domain"
|
||||
)
|
||||
|
||||
// StarGiftStore 是 store.StarGiftStore 的内存实现。
|
||||
type StarGiftStore struct {
|
||||
mu sync.Mutex
|
||||
nextID int64
|
||||
nextGiftID int64
|
||||
nextRevID int64
|
||||
gifts []domain.SavedStarGift // 追加序
|
||||
catalog map[int64]domain.StarGift
|
||||
revisions map[int64]domain.StarGift
|
||||
enabled map[int64]bool
|
||||
sortOrder map[int64]int
|
||||
animations map[int64][]byte
|
||||
collectibles map[int64]domain.StarGiftCollectibleRevision
|
||||
uniqueByID map[int64]domain.UniqueStarGift
|
||||
uniqueBySlug map[string]int64
|
||||
collections map[domain.Peer][]domain.StarGiftCollection
|
||||
nextAttributeID int64
|
||||
nextCollectionID int
|
||||
}
|
||||
|
||||
// NewStarGiftStore 创建内存 StarGiftStore。
|
||||
func NewStarGiftStore() *StarGiftStore {
|
||||
return &StarGiftStore{
|
||||
catalog: make(map[int64]domain.StarGift), revisions: make(map[int64]domain.StarGift),
|
||||
enabled: make(map[int64]bool), sortOrder: make(map[int64]int), animations: make(map[int64][]byte),
|
||||
collectibles: make(map[int64]domain.StarGiftCollectibleRevision),
|
||||
uniqueByID: make(map[int64]domain.UniqueStarGift), uniqueBySlug: make(map[string]int64),
|
||||
collections: make(map[domain.Peer][]domain.StarGiftCollection),
|
||||
}
|
||||
}
|
||||
|
||||
// SeedCatalog installs valid immutable catalog snapshots for tests.
|
||||
func (s *StarGiftStore) SeedCatalog(gifts []domain.StarGift) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for _, gift := range gifts {
|
||||
if gift.RevisionID == 0 {
|
||||
s.nextRevID++
|
||||
gift.RevisionID = s.nextRevID
|
||||
}
|
||||
if gift.ID > s.nextGiftID {
|
||||
s.nextGiftID = gift.ID
|
||||
}
|
||||
if gift.RevisionID > s.nextRevID {
|
||||
s.nextRevID = gift.RevisionID
|
||||
}
|
||||
s.catalog[gift.ID] = gift
|
||||
s.revisions[gift.RevisionID] = gift
|
||||
s.enabled[gift.ID] = true
|
||||
}
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) Catalog(_ context.Context) ([]domain.StarGift, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
out := make([]domain.StarGift, 0, len(s.catalog))
|
||||
for id, gift := range s.catalog {
|
||||
if s.enabled[id] {
|
||||
out = append(out, gift)
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
if s.sortOrder[out[i].ID] == s.sortOrder[out[j].ID] {
|
||||
return out[i].ID < out[j].ID
|
||||
}
|
||||
return s.sortOrder[out[i].ID] < s.sortOrder[out[j].ID]
|
||||
})
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) CatalogGift(_ context.Context, giftID int64) (domain.StarGift, bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
gift, ok := s.catalog[giftID]
|
||||
return gift, ok && s.enabled[giftID], nil
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) CatalogRevision(_ context.Context, revisionID int64) (domain.StarGift, bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
gift, ok := s.revisions[revisionID]
|
||||
return gift, ok, nil
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) CreateCatalogRevision(_ context.Context, write domain.StarGiftCatalogWrite) (domain.StarGiftCatalogEntry, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.createCatalogRevisionLocked(write)
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) createCatalogRevisionLocked(write domain.StarGiftCatalogWrite) (domain.StarGiftCatalogEntry, error) {
|
||||
giftID := write.GiftID
|
||||
if giftID == 0 {
|
||||
s.nextGiftID++
|
||||
giftID = s.nextGiftID
|
||||
} else if _, ok := s.catalog[giftID]; !ok {
|
||||
return domain.StarGiftCatalogEntry{}, domain.ErrStarGiftNotFound
|
||||
}
|
||||
s.nextRevID++
|
||||
gift := domain.StarGift{
|
||||
ID: giftID, RevisionID: s.nextRevID, Stars: write.Stars, ConvertStars: write.ConvertStars,
|
||||
Title: write.Title, Sticker: write.Document,
|
||||
Limited: write.Limited, SoldOut: write.SoldOut, Birthday: write.Birthday,
|
||||
RequirePremium: write.RequirePremium, LimitedPerUser: write.LimitedPerUser,
|
||||
PeerColorAvailable: write.PeerColorAvailable, Auction: write.Auction,
|
||||
AvailabilityRemains: write.AvailabilityRemains, AvailabilityTotal: write.AvailabilityTotal,
|
||||
AvailabilityResale: write.AvailabilityResale, FirstSaleDate: write.FirstSaleDate,
|
||||
LastSaleDate: write.LastSaleDate, ResellMinStars: write.ResellMinStars,
|
||||
ReleasedBy: write.ReleasedBy, PerUserTotal: write.PerUserTotal,
|
||||
PerUserRemains: write.PerUserTotal, LockedUntilDate: write.LockedUntilDate,
|
||||
AuctionSlug: write.AuctionSlug, GiftsPerRound: write.GiftsPerRound,
|
||||
AuctionStartDate: write.AuctionStartDate, UpgradeVariants: write.UpgradeVariants,
|
||||
Background: cloneStarGiftBackground(write.Background),
|
||||
}
|
||||
s.catalog[giftID] = gift
|
||||
s.revisions[gift.RevisionID] = gift
|
||||
s.enabled[giftID] = write.Enabled
|
||||
s.sortOrder[giftID] = write.SortOrder
|
||||
s.animations[giftID] = append([]byte(nil), write.Animation.JSON...)
|
||||
return domain.StarGiftCatalogEntry{Gift: gift, Enabled: write.Enabled, SortOrder: write.SortOrder}, nil
|
||||
}
|
||||
|
||||
func cloneStarGiftBackground(value *domain.StarGiftBackground) *domain.StarGiftBackground {
|
||||
if value == nil {
|
||||
return nil
|
||||
}
|
||||
copy := *value
|
||||
return ©
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) CreateCatalogBundle(_ context.Context, write domain.StarGiftCatalogBundleWrite) (domain.StarGiftCatalogBundleResult, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if write.Collectible != nil {
|
||||
collectibleWrite := *write.Collectible
|
||||
collectibleWrite.GiftID = write.Catalog.GiftID
|
||||
if collectibleWrite.GiftID == 0 {
|
||||
collectibleWrite.GiftID = s.nextGiftID + 1
|
||||
}
|
||||
if err := domain.ValidateStarGiftCollectibleWrite(collectibleWrite); err != nil {
|
||||
return domain.StarGiftCatalogBundleResult{}, err
|
||||
}
|
||||
}
|
||||
entry, err := s.createCatalogRevisionLocked(write.Catalog)
|
||||
if err != nil {
|
||||
return domain.StarGiftCatalogBundleResult{}, err
|
||||
}
|
||||
result := domain.StarGiftCatalogBundleResult{Catalog: entry}
|
||||
if write.Collectible != nil {
|
||||
collectibleWrite := *write.Collectible
|
||||
collectibleWrite.GiftID = entry.Gift.ID
|
||||
revision, err := s.publishCollectibleRevisionLocked(collectibleWrite)
|
||||
if err != nil {
|
||||
return domain.StarGiftCatalogBundleResult{}, err
|
||||
}
|
||||
result.Collectible = &revision
|
||||
result.Catalog.Gift = s.catalog[entry.Gift.ID]
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) SetCatalogEnabled(_ context.Context, giftID int64, enabled bool) (bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if _, ok := s.catalog[giftID]; !ok {
|
||||
return false, domain.ErrStarGiftNotFound
|
||||
}
|
||||
changed := s.enabled[giftID] != enabled
|
||||
s.enabled[giftID] = enabled
|
||||
return changed, nil
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) SetCatalogSortOrder(_ context.Context, giftID int64, sortOrder int) (bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if _, ok := s.catalog[giftID]; !ok {
|
||||
return false, domain.ErrStarGiftNotFound
|
||||
}
|
||||
changed := s.sortOrder[giftID] != sortOrder
|
||||
s.sortOrder[giftID] = sortOrder
|
||||
return changed, nil
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) AnimationJSON(_ context.Context, giftID int64) ([]byte, bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
raw, ok := s.animations[giftID]
|
||||
return append([]byte(nil), raw...), ok, nil
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) PublishCollectibleRevision(_ context.Context, write domain.StarGiftCollectibleWrite) (domain.StarGiftCollectibleRevision, error) {
|
||||
if err := domain.ValidateStarGiftCollectibleWrite(write); err != nil {
|
||||
return domain.StarGiftCollectibleRevision{}, err
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.publishCollectibleRevisionLocked(write)
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) publishCollectibleRevisionLocked(write domain.StarGiftCollectibleWrite) (domain.StarGiftCollectibleRevision, error) {
|
||||
if _, ok := s.catalog[write.GiftID]; !ok {
|
||||
return domain.StarGiftCollectibleRevision{}, domain.ErrStarGiftNotFound
|
||||
}
|
||||
previous := s.collectibles[write.GiftID]
|
||||
revision := domain.StarGiftCollectibleRevision{
|
||||
ID: previous.ID + 1, GiftID: write.GiftID, Revision: previous.Revision + 1,
|
||||
UpgradeStars: write.UpgradeStars, SupplyTotal: write.SupplyTotal,
|
||||
SlugPrefix: strings.ToLower(strings.TrimSpace(write.SlugPrefix)), Published: true,
|
||||
CreatedBy: write.Actor,
|
||||
OfficialGiftID: write.OfficialGiftID, SourceManifestSHA256: append([]byte(nil), write.SourceManifestSHA256...),
|
||||
}
|
||||
if revision.ID == 1 {
|
||||
revision.ID = write.GiftID*1000 + 1
|
||||
}
|
||||
revision.Models = s.allocateCollectibleAttributes(write.Models, revision.ID)
|
||||
revision.Patterns = s.allocateCollectibleAttributes(write.Patterns, revision.ID)
|
||||
revision.Backdrops = s.allocateCollectibleAttributes(write.Backdrops, revision.ID)
|
||||
s.collectibles[write.GiftID] = revision
|
||||
gift := s.catalog[write.GiftID]
|
||||
gift.UpgradeStars = revision.UpgradeStars
|
||||
gift.UpgradeTotal = revision.SupplyTotal
|
||||
gift.UpgradeIssued = revision.Issued
|
||||
s.catalog[write.GiftID] = gift
|
||||
return cloneCollectibleRevision(revision), nil
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) allocateCollectibleAttributes(in []domain.StarGiftCollectibleAttribute, revisionID int64) []domain.StarGiftCollectibleAttribute {
|
||||
out := make([]domain.StarGiftCollectibleAttribute, len(in))
|
||||
for i, attribute := range in {
|
||||
s.nextAttributeID++
|
||||
attribute.ID = s.nextAttributeID
|
||||
attribute.CollectibleRevisionID = revisionID
|
||||
out[i] = cloneCollectibleAttribute(attribute)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) ActiveCollectibleRevision(_ context.Context, giftID int64) (domain.StarGiftCollectibleRevision, bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
revision, ok := s.collectibles[giftID]
|
||||
return cloneCollectibleRevision(revision), ok, nil
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) ActiveCollectibleProjection(_ context.Context, giftID int64, samplePerKind int) (domain.StarGiftCollectibleRevision, bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
revision, ok := s.collectibles[giftID]
|
||||
if !ok {
|
||||
return domain.StarGiftCollectibleRevision{}, false, nil
|
||||
}
|
||||
projection := cloneCollectibleRevision(revision)
|
||||
projection.Models = projectCollectibleAttributes(projection.Models, domain.StarGiftCollectibleModel, samplePerKind)
|
||||
projection.Patterns = projectCollectibleAttributes(projection.Patterns, domain.StarGiftCollectiblePattern, samplePerKind)
|
||||
projection.Backdrops = projectCollectibleAttributes(projection.Backdrops, domain.StarGiftCollectibleBackdrop, samplePerKind)
|
||||
return projection, true, nil
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) CollectibleAvailability(_ context.Context, giftIDs []int64) (map[int64]domain.StarGiftCollectibleAvailability, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
out := make(map[int64]domain.StarGiftCollectibleAvailability, len(giftIDs))
|
||||
for _, giftID := range giftIDs {
|
||||
revision, ok := s.collectibles[giftID]
|
||||
if !ok || !revision.Published {
|
||||
continue
|
||||
}
|
||||
out[giftID] = domain.StarGiftCollectibleAvailability{
|
||||
UpgradeStars: revision.UpgradeStars,
|
||||
SupplyTotal: revision.SupplyTotal,
|
||||
Issued: revision.Issued,
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) CollectibleAnimationJSON(_ context.Context, giftID int64, kind domain.StarGiftCollectibleAttributeKind, attributeID int64) ([]byte, bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
revision, ok := s.collectibles[giftID]
|
||||
if !ok {
|
||||
return nil, false, nil
|
||||
}
|
||||
var attributes []domain.StarGiftCollectibleAttribute
|
||||
switch kind {
|
||||
case domain.StarGiftCollectibleModel:
|
||||
attributes = revision.Models
|
||||
case domain.StarGiftCollectiblePattern:
|
||||
attributes = revision.Patterns
|
||||
default:
|
||||
return nil, false, nil
|
||||
}
|
||||
for _, attribute := range attributes {
|
||||
if attribute.ID == attributeID && attribute.Animation != nil {
|
||||
return append([]byte(nil), attribute.Animation.JSON...), true, nil
|
||||
}
|
||||
}
|
||||
return nil, false, nil
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) UniqueBySlug(_ context.Context, slug string) (domain.UniqueStarGift, bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
id, ok := s.uniqueBySlug[strings.ToLower(strings.TrimSpace(slug))]
|
||||
if !ok {
|
||||
return domain.UniqueStarGift{}, false, nil
|
||||
}
|
||||
unique, ok := s.uniqueByID[id]
|
||||
return unique, ok, nil
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) UniqueByID(_ context.Context, uniqueGiftID int64) (domain.UniqueStarGift, bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
unique, ok := s.uniqueByID[uniqueGiftID]
|
||||
return unique, ok, nil
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) UniqueByIDs(_ context.Context, uniqueGiftIDs []int64) (map[int64]domain.UniqueStarGift, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
out := make(map[int64]domain.UniqueStarGift, len(uniqueGiftIDs))
|
||||
for _, id := range uniqueGiftIDs {
|
||||
if gift, ok := s.uniqueByID[id]; ok {
|
||||
out[id] = gift
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) ListUniqueByOwner(_ context.Context, owner domain.Peer, limit int) ([]domain.UniqueStarGift, error) {
|
||||
if owner.ID <= 0 || limit <= 0 {
|
||||
return []domain.UniqueStarGift{}, nil
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
out := make([]domain.UniqueStarGift, 0, min(limit, len(s.uniqueByID)))
|
||||
for _, gift := range s.uniqueByID {
|
||||
if gift.Owner == owner && !gift.Burned && gift.OwnerAddress == "" {
|
||||
out = append(out, gift)
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].ID > out[j].ID })
|
||||
if len(out) > limit {
|
||||
out = out[:limit]
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) Create(_ context.Context, gift domain.SavedStarGift) (int64, error) {
|
||||
if !validSavedStarGift(gift) {
|
||||
return 0, domain.ErrStarGiftInvalid
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.nextID++
|
||||
gift.ID = s.nextID
|
||||
if gift.Owner.Type == domain.PeerTypeChannel && gift.SavedID == 0 {
|
||||
gift.SavedID = gift.ID
|
||||
}
|
||||
gift.Converted = false
|
||||
gift.LifecycleStatus = domain.StarGiftLifecycleActive
|
||||
s.gifts = append(s.gifts, gift)
|
||||
return gift.ID, nil
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) ListByOwner(_ context.Context, owner domain.Peer, excludeUnsaved bool, offset string, limit int) (domain.SavedStarGiftPage, error) {
|
||||
return s.ListByOwnerFiltered(context.Background(), domain.SavedStarGiftFilter{
|
||||
Owner: owner, ExcludeUnsaved: excludeUnsaved, Offset: offset, Limit: limit,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) ListByOwnerFiltered(_ context.Context, filter domain.SavedStarGiftFilter) (domain.SavedStarGiftPage, error) {
|
||||
owner, offset, limit := filter.Owner, filter.Offset, filter.Limit
|
||||
if !validStarGiftOwner(owner) {
|
||||
return domain.SavedStarGiftPage{}, nil
|
||||
}
|
||||
if limit <= 0 || limit > domain.MaxSavedStarGiftsLimit {
|
||||
limit = domain.MaxSavedStarGiftsLimit
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
matched := make([]domain.SavedStarGift, 0)
|
||||
for _, g := range s.gifts {
|
||||
if g.Owner != owner || !g.LifecycleStatus.Live() {
|
||||
continue
|
||||
}
|
||||
if filter.ExcludeUnsaved && g.Unsaved {
|
||||
continue
|
||||
}
|
||||
if filter.ExcludeSaved && !g.Unsaved {
|
||||
continue
|
||||
}
|
||||
if filter.ExcludeUnique && g.UniqueGiftID != 0 {
|
||||
continue
|
||||
}
|
||||
if filter.ExcludeUnlimited && g.UniqueGiftID == 0 {
|
||||
continue
|
||||
}
|
||||
upgradable := false
|
||||
if g.UniqueGiftID == 0 {
|
||||
if gift, ok := s.catalog[g.GiftID]; ok {
|
||||
upgradable = gift.UpgradeStars > 0 && gift.UpgradeIssued < gift.UpgradeTotal
|
||||
}
|
||||
}
|
||||
if filter.ExcludeUpgradable && upgradable {
|
||||
continue
|
||||
}
|
||||
if filter.ExcludeUnupgradable && !upgradable {
|
||||
continue
|
||||
}
|
||||
if filter.CollectionID > 0 && !containsInt(g.CollectionIDs, filter.CollectionID) {
|
||||
continue
|
||||
}
|
||||
matched = append(matched, g)
|
||||
}
|
||||
profileOrder := filter.CollectionID == 0
|
||||
sort.Slice(matched, func(i, j int) bool {
|
||||
if profileOrder {
|
||||
iPinned := matched[i].PinnedOrder > 0
|
||||
jPinned := matched[j].PinnedOrder > 0
|
||||
if iPinned != jPinned {
|
||||
return iPinned
|
||||
}
|
||||
if iPinned && matched[i].PinnedOrder != matched[j].PinnedOrder {
|
||||
return matched[i].PinnedOrder < matched[j].PinnedOrder
|
||||
}
|
||||
}
|
||||
return matched[i].ID > matched[j].ID
|
||||
})
|
||||
page := domain.SavedStarGiftPage{Count: len(matched)}
|
||||
cursor, hasCursor := domain.DecodeSavedStarGiftListCursor(offset)
|
||||
out := make([]domain.SavedStarGift, 0, limit+1)
|
||||
for _, g := range matched {
|
||||
if hasCursor {
|
||||
if profileOrder {
|
||||
if cursor.PinnedOrder > 0 {
|
||||
if g.PinnedOrder > 0 && (g.PinnedOrder < cursor.PinnedOrder ||
|
||||
g.PinnedOrder == cursor.PinnedOrder && g.ID >= cursor.ID) {
|
||||
continue
|
||||
}
|
||||
} else if g.PinnedOrder > 0 || g.ID >= cursor.ID {
|
||||
continue
|
||||
}
|
||||
} else if g.ID >= cursor.ID {
|
||||
continue
|
||||
}
|
||||
}
|
||||
out = append(out, g)
|
||||
if len(out) == limit+1 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if len(out) > limit {
|
||||
out = out[:limit]
|
||||
last := out[len(out)-1]
|
||||
pinnedOrder := 0
|
||||
if profileOrder {
|
||||
pinnedOrder = last.PinnedOrder
|
||||
}
|
||||
page.NextOffset = domain.EncodeSavedStarGiftListCursor(pinnedOrder, last.ID)
|
||||
}
|
||||
page.Gifts = out
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) ResolveSavedIDs(_ context.Context, owner domain.Peer, refs []domain.SavedStarGiftRef) ([]int64, error) {
|
||||
if !validStarGiftOwner(owner) || len(refs) > domain.MaxStarGiftCollectionItems {
|
||||
return nil, domain.ErrStarGiftCollectibleInvalid
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
out := make([]int64, 0, len(refs))
|
||||
seen := make(map[int64]struct{}, len(refs))
|
||||
for _, ref := range refs {
|
||||
if ref.Owner != owner || !ref.Valid() {
|
||||
return nil, domain.ErrStarGiftNotFound
|
||||
}
|
||||
var id int64
|
||||
for _, gift := range s.gifts {
|
||||
if s.savedStarGiftMatchesRef(gift, ref) && gift.LifecycleStatus.Live() {
|
||||
id = gift.ID
|
||||
break
|
||||
}
|
||||
}
|
||||
if id == 0 {
|
||||
return nil, domain.ErrStarGiftNotFound
|
||||
}
|
||||
if _, exists := seen[id]; exists {
|
||||
return nil, domain.ErrStarGiftCollectibleInvalid
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
out = append(out, id)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) GetByRef(_ context.Context, ref domain.SavedStarGiftRef) (domain.SavedStarGift, bool, error) {
|
||||
if !ref.Valid() {
|
||||
return domain.SavedStarGift{}, false, nil
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for _, g := range s.gifts {
|
||||
if s.savedStarGiftMatchesRef(g, ref) {
|
||||
return g, true, nil
|
||||
}
|
||||
}
|
||||
return domain.SavedStarGift{}, false, nil
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) ResolveUserMessageRef(_ context.Context, _ int64, _ int) (domain.SavedStarGiftRef, bool, error) {
|
||||
return domain.SavedStarGiftRef{}, false, nil
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) CountByOwner(_ context.Context, owner domain.Peer) (int, error) {
|
||||
if !validStarGiftOwner(owner) {
|
||||
return 0, nil
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
n := 0
|
||||
for _, g := range s.gifts {
|
||||
if g.Owner == owner && g.LifecycleStatus.Live() && !g.Unsaved {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) SetUnsaved(_ context.Context, ref domain.SavedStarGiftRef, unsaved bool) (bool, error) {
|
||||
if !ref.Valid() {
|
||||
return false, domain.ErrStarGiftNotFound
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for i := range s.gifts {
|
||||
if s.savedStarGiftMatchesRef(s.gifts[i], ref) && s.gifts[i].LifecycleStatus.Live() {
|
||||
s.gifts[i].Unsaved = unsaved
|
||||
if unsaved && s.gifts[i].PinnedOrder > 0 {
|
||||
removedOrder := s.gifts[i].PinnedOrder
|
||||
s.gifts[i].PinnedOrder = 0
|
||||
for j := range s.gifts {
|
||||
if s.gifts[j].Owner == ref.Owner && s.gifts[j].PinnedOrder > removedOrder {
|
||||
s.gifts[j].PinnedOrder--
|
||||
}
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) MarkConverted(_ context.Context, ref domain.SavedStarGiftRef) (domain.SavedStarGift, error) {
|
||||
if !ref.Valid() {
|
||||
return domain.SavedStarGift{}, domain.ErrStarGiftNotFound
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for i := range s.gifts {
|
||||
if s.savedStarGiftMatchesRef(s.gifts[i], ref) {
|
||||
if s.gifts[i].UniqueGiftID != 0 {
|
||||
return domain.SavedStarGift{}, domain.ErrStarGiftAlreadyUpgraded
|
||||
}
|
||||
if s.gifts[i].Converted {
|
||||
return domain.SavedStarGift{}, domain.ErrStarGiftAlreadyConverted
|
||||
}
|
||||
s.gifts[i].Converted = true
|
||||
s.gifts[i].LifecycleStatus = domain.StarGiftLifecycleConverted
|
||||
s.gifts[i].Unsaved = true
|
||||
s.gifts[i].PinnedOrder = 0
|
||||
for collectionIndex := range s.collections[ref.Owner] {
|
||||
collection := &s.collections[ref.Owner][collectionIndex]
|
||||
next := collection.GiftIDs[:0]
|
||||
for _, giftID := range collection.GiftIDs {
|
||||
if giftID != s.gifts[i].ID {
|
||||
next = append(next, giftID)
|
||||
}
|
||||
}
|
||||
collection.GiftIDs = next
|
||||
collection.Hash = domain.StarGiftCollectionHash(collection.Title, collection.GiftIDs)
|
||||
}
|
||||
s.refreshCollectionMembershipsLocked(ref.Owner)
|
||||
return s.gifts[i], nil
|
||||
}
|
||||
}
|
||||
return domain.SavedStarGift{}, domain.ErrStarGiftNotFound
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) ListCollections(_ context.Context, owner domain.Peer) ([]domain.StarGiftCollection, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return cloneStarGiftCollections(s.collections[owner]), nil
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) CreateCollection(_ context.Context, owner domain.Peer, title string, savedGiftIDs []int64) (domain.StarGiftCollection, error) {
|
||||
title = strings.TrimSpace(title)
|
||||
if !validStarGiftOwner(owner) || title == "" || len([]rune(title)) > domain.MaxStarGiftCollectionTitleRunes {
|
||||
return domain.StarGiftCollection{}, domain.ErrStarGiftCollectibleInvalid
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if len(s.collections[owner]) >= domain.MaxStarGiftCollectionsPerPeer {
|
||||
return domain.StarGiftCollection{}, domain.ErrStarGiftCollectionsFull
|
||||
}
|
||||
ids, err := s.validCollectionGiftIDsLocked(owner, savedGiftIDs)
|
||||
if err != nil {
|
||||
return domain.StarGiftCollection{}, err
|
||||
}
|
||||
s.nextCollectionID++
|
||||
collection := domain.StarGiftCollection{Owner: owner, CollectionID: s.nextCollectionID, Title: title, GiftIDs: ids, SortOrder: len(s.collections[owner])}
|
||||
collection.Hash = domain.StarGiftCollectionHash(collection.Title, collection.GiftIDs)
|
||||
s.collections[owner] = append(s.collections[owner], collection)
|
||||
s.refreshCollectionMembershipsLocked(owner)
|
||||
return collection, nil
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) UpdateCollection(_ context.Context, owner domain.Peer, collectionID int, patch domain.StarGiftCollectionPatch) (domain.StarGiftCollection, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
collections := s.collections[owner]
|
||||
index := -1
|
||||
for i := range collections {
|
||||
if collections[i].CollectionID == collectionID {
|
||||
index = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if index < 0 {
|
||||
return domain.StarGiftCollection{}, domain.ErrStarGiftCollectionNotFound
|
||||
}
|
||||
collection := collections[index]
|
||||
if patch.Title != nil {
|
||||
title := strings.TrimSpace(*patch.Title)
|
||||
if title == "" || len([]rune(title)) > domain.MaxStarGiftCollectionTitleRunes {
|
||||
return domain.StarGiftCollection{}, domain.ErrStarGiftCollectibleInvalid
|
||||
}
|
||||
collection.Title = title
|
||||
}
|
||||
deleteSet := make(map[int64]struct{}, len(patch.DeleteIDs))
|
||||
for _, id := range patch.DeleteIDs {
|
||||
deleteSet[id] = struct{}{}
|
||||
}
|
||||
next := make([]int64, 0, len(collection.GiftIDs)+len(patch.AddIDs))
|
||||
for _, id := range collection.GiftIDs {
|
||||
if _, deleted := deleteSet[id]; !deleted {
|
||||
next = append(next, id)
|
||||
}
|
||||
}
|
||||
add, err := s.validCollectionGiftIDsLocked(owner, patch.AddIDs)
|
||||
if err != nil {
|
||||
return domain.StarGiftCollection{}, err
|
||||
}
|
||||
next = appendUniqueInt64(next, add...)
|
||||
if patch.Order != nil {
|
||||
order, err := s.validCollectionGiftIDsLocked(owner, patch.Order)
|
||||
if err != nil || !sameInt64Set(order, next) {
|
||||
return domain.StarGiftCollection{}, domain.ErrStarGiftCollectibleInvalid
|
||||
}
|
||||
next = order
|
||||
}
|
||||
if len(next) > domain.MaxStarGiftCollectionItems {
|
||||
return domain.StarGiftCollection{}, domain.ErrStarGiftCollectibleInvalid
|
||||
}
|
||||
collection.GiftIDs = next
|
||||
collection.Hash = domain.StarGiftCollectionHash(collection.Title, collection.GiftIDs)
|
||||
collections[index] = collection
|
||||
s.collections[owner] = collections
|
||||
s.refreshCollectionMembershipsLocked(owner)
|
||||
return collection, nil
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) DeleteCollection(_ context.Context, owner domain.Peer, collectionID int) (bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
collections := s.collections[owner]
|
||||
for i := range collections {
|
||||
if collections[i].CollectionID == collectionID {
|
||||
collections = append(collections[:i], collections[i+1:]...)
|
||||
for j := range collections {
|
||||
collections[j].SortOrder = j
|
||||
}
|
||||
s.collections[owner] = collections
|
||||
s.refreshCollectionMembershipsLocked(owner)
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) ReorderCollections(_ context.Context, owner domain.Peer, collectionIDs []int) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
collections := s.collections[owner]
|
||||
if len(collectionIDs) != len(collections) {
|
||||
return domain.ErrStarGiftCollectibleInvalid
|
||||
}
|
||||
byID := make(map[int]domain.StarGiftCollection, len(collections))
|
||||
for _, collection := range collections {
|
||||
byID[collection.CollectionID] = collection
|
||||
}
|
||||
next := make([]domain.StarGiftCollection, 0, len(collections))
|
||||
for order, id := range collectionIDs {
|
||||
collection, ok := byID[id]
|
||||
if !ok {
|
||||
return domain.ErrStarGiftCollectibleInvalid
|
||||
}
|
||||
delete(byID, id)
|
||||
collection.SortOrder = order
|
||||
next = append(next, collection)
|
||||
}
|
||||
s.collections[owner] = next
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) SetPinned(_ context.Context, owner domain.Peer, savedGiftIDs []int64) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if len(savedGiftIDs) > domain.MaxPinnedStarGifts {
|
||||
return domain.ErrStarGiftCollectibleInvalid
|
||||
}
|
||||
ids, err := s.validCollectionGiftIDsLocked(owner, savedGiftIDs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(ids) != len(savedGiftIDs) {
|
||||
return domain.ErrStarGiftCollectibleInvalid
|
||||
}
|
||||
order := make(map[int64]int, len(ids))
|
||||
for i, id := range ids {
|
||||
order[id] = i + 1
|
||||
}
|
||||
for i := range s.gifts {
|
||||
if s.gifts[i].Owner == owner {
|
||||
s.gifts[i].PinnedOrder = order[s.gifts[i].ID]
|
||||
if s.gifts[i].PinnedOrder > 0 {
|
||||
s.gifts[i].Unsaved = false
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// refreshCollectionMembershipsLocked keeps the in-memory saved-gift projection
|
||||
// equivalent to the PostgreSQL join projection. Callers must hold s.mu.
|
||||
func (s *StarGiftStore) refreshCollectionMembershipsLocked(owner domain.Peer) {
|
||||
memberships := make(map[int64][]int)
|
||||
for _, collection := range s.collections[owner] {
|
||||
for _, giftID := range collection.GiftIDs {
|
||||
memberships[giftID] = append(memberships[giftID], collection.CollectionID)
|
||||
}
|
||||
}
|
||||
for i := range s.gifts {
|
||||
if s.gifts[i].Owner != owner {
|
||||
continue
|
||||
}
|
||||
s.gifts[i].CollectionIDs = append([]int(nil), memberships[s.gifts[i].ID]...)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) validCollectionGiftIDsLocked(owner domain.Peer, ids []int64) ([]int64, error) {
|
||||
if len(ids) > domain.MaxStarGiftCollectionItems {
|
||||
return nil, domain.ErrStarGiftCollectibleInvalid
|
||||
}
|
||||
out := make([]int64, 0, len(ids))
|
||||
seen := make(map[int64]struct{}, len(ids))
|
||||
for _, id := range ids {
|
||||
if _, ok := seen[id]; ok {
|
||||
continue
|
||||
}
|
||||
valid := false
|
||||
for _, gift := range s.gifts {
|
||||
if gift.ID == id && gift.Owner == owner && gift.LifecycleStatus.Live() {
|
||||
valid = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !valid {
|
||||
return nil, domain.ErrStarGiftNotFound
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
out = append(out, id)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func appendUniqueInt64(dst []int64, values ...int64) []int64 {
|
||||
seen := make(map[int64]struct{}, len(dst)+len(values))
|
||||
for _, id := range dst {
|
||||
seen[id] = struct{}{}
|
||||
}
|
||||
for _, id := range values {
|
||||
if _, ok := seen[id]; !ok {
|
||||
seen[id] = struct{}{}
|
||||
dst = append(dst, id)
|
||||
}
|
||||
}
|
||||
return dst
|
||||
}
|
||||
|
||||
func sameInt64Set(a, b []int64) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
seen := make(map[int64]int, len(a))
|
||||
for _, id := range a {
|
||||
seen[id]++
|
||||
}
|
||||
for _, id := range b {
|
||||
seen[id]--
|
||||
if seen[id] < 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func cloneCollectibleAttribute(in domain.StarGiftCollectibleAttribute) domain.StarGiftCollectibleAttribute {
|
||||
out := in
|
||||
if in.Document != nil {
|
||||
document := *in.Document
|
||||
out.Document = &document
|
||||
}
|
||||
if in.Animation != nil {
|
||||
animation := *in.Animation
|
||||
animation.JSON = append([]byte(nil), in.Animation.JSON...)
|
||||
animation.TGS = append([]byte(nil), in.Animation.TGS...)
|
||||
animation.SHA256 = append([]byte(nil), in.Animation.SHA256...)
|
||||
out.Animation = &animation
|
||||
}
|
||||
if in.Blob != nil {
|
||||
blob := *in.Blob
|
||||
out.Blob = &blob
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func cloneCollectibleRevision(in domain.StarGiftCollectibleRevision) domain.StarGiftCollectibleRevision {
|
||||
out := in
|
||||
out.SourceManifestSHA256 = append([]byte(nil), in.SourceManifestSHA256...)
|
||||
clone := func(attributes []domain.StarGiftCollectibleAttribute) []domain.StarGiftCollectibleAttribute {
|
||||
copy := make([]domain.StarGiftCollectibleAttribute, len(attributes))
|
||||
for i, attribute := range attributes {
|
||||
copy[i] = cloneCollectibleAttribute(attribute)
|
||||
}
|
||||
return copy
|
||||
}
|
||||
out.Models = clone(in.Models)
|
||||
out.Patterns = clone(in.Patterns)
|
||||
out.Backdrops = clone(in.Backdrops)
|
||||
return out
|
||||
}
|
||||
|
||||
func projectCollectibleAttributes(in []domain.StarGiftCollectibleAttribute, kind domain.StarGiftCollectibleAttributeKind, samplePerKind int) []domain.StarGiftCollectibleAttribute {
|
||||
out := in
|
||||
if samplePerKind > 0 {
|
||||
out = make([]domain.StarGiftCollectibleAttribute, 0, len(in))
|
||||
for _, attribute := range in {
|
||||
if attribute.RarityKind != domain.StarGiftRarityPermille || attribute.RarityPermille <= 0 ||
|
||||
(kind == domain.StarGiftCollectibleModel && attribute.Crafted) {
|
||||
continue
|
||||
}
|
||||
out = append(out, attribute)
|
||||
}
|
||||
for i := 0; i < len(out) && i < samplePerKind; i++ {
|
||||
j := i + rand.IntN(len(out)-i)
|
||||
out[i], out[j] = out[j], out[i]
|
||||
}
|
||||
if len(out) > samplePerKind {
|
||||
out = out[:samplePerKind]
|
||||
}
|
||||
}
|
||||
for i := range out {
|
||||
if out[i].Animation != nil {
|
||||
out[i].Animation.JSON = nil
|
||||
out[i].Animation.TGS = nil
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func cloneStarGiftCollections(in []domain.StarGiftCollection) []domain.StarGiftCollection {
|
||||
out := make([]domain.StarGiftCollection, len(in))
|
||||
for i, collection := range in {
|
||||
out[i] = collection
|
||||
out[i].GiftIDs = append([]int64(nil), collection.GiftIDs...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func validSavedStarGift(g domain.SavedStarGift) bool {
|
||||
if g.GiftID == 0 || g.RevisionID == 0 || !validStarGiftOwner(g.Owner) {
|
||||
return false
|
||||
}
|
||||
switch g.Owner.Type {
|
||||
case domain.PeerTypeUser:
|
||||
return g.MsgID > 0 && g.SavedID == 0
|
||||
case domain.PeerTypeChannel:
|
||||
return g.MsgID == 0 && g.SavedID >= 0
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func validStarGiftOwner(owner domain.Peer) bool {
|
||||
return owner.ID != 0 && (owner.Type == domain.PeerTypeUser || owner.Type == domain.PeerTypeChannel)
|
||||
}
|
||||
|
||||
func (s *StarGiftStore) savedStarGiftMatchesRef(g domain.SavedStarGift, ref domain.SavedStarGiftRef) bool {
|
||||
if g.Owner != ref.Owner {
|
||||
return false
|
||||
}
|
||||
if ref.Slug != "" {
|
||||
uniqueID, ok := s.uniqueBySlug[strings.ToLower(strings.TrimSpace(ref.Slug))]
|
||||
return ok && uniqueID != 0 && g.UniqueGiftID == uniqueID
|
||||
}
|
||||
switch ref.Owner.Type {
|
||||
case domain.PeerTypeUser:
|
||||
return g.MsgID == ref.MsgID
|
||||
case domain.PeerTypeChannel:
|
||||
return g.SavedID == ref.SavedID
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
|
@ -1,41 +0,0 @@
|
|||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"telesrv/internal/domain"
|
||||
)
|
||||
|
||||
func TestSavedStarGiftIdentityDoesNotAcceptUpgradeMessageID(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
owner := domain.Peer{Type: domain.PeerTypeUser, ID: 42}
|
||||
store := NewStarGiftStore()
|
||||
id, err := store.Create(ctx, domain.SavedStarGift{
|
||||
Owner: owner, GiftID: 8001, RevisionID: 9001, MsgID: 115,
|
||||
UniqueGiftID: 901, UpgradeMsgID: 116,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("create saved gift: %v", err)
|
||||
}
|
||||
store.uniqueBySlug["official-8001-1"] = 901
|
||||
|
||||
canonical := domain.SavedStarGiftRef{Owner: owner, MsgID: 115}
|
||||
if saved, found, err := store.GetByRef(ctx, canonical); err != nil || !found || saved.ID != id {
|
||||
t.Fatalf("canonical identity: saved=%+v found=%v err=%v", saved, found, err)
|
||||
}
|
||||
wrong := domain.SavedStarGiftRef{Owner: owner, MsgID: 116}
|
||||
if saved, found, err := store.GetByRef(ctx, wrong); err != nil || found {
|
||||
t.Fatalf("upgrade message id resolved gift: saved=%+v found=%v err=%v", saved, found, err)
|
||||
}
|
||||
if _, err := store.ResolveSavedIDs(ctx, owner, []domain.SavedStarGiftRef{wrong}); !errors.Is(err, domain.ErrStarGiftNotFound) {
|
||||
t.Fatalf("upgrade message id resolve err=%v, want ErrStarGiftNotFound", err)
|
||||
}
|
||||
if _, err := store.ResolveSavedIDs(ctx, owner, []domain.SavedStarGiftRef{
|
||||
canonical,
|
||||
{Owner: owner, Slug: "official-8001-1"},
|
||||
}); !errors.Is(err, domain.ErrStarGiftCollectibleInvalid) {
|
||||
t.Fatalf("duplicate official identities err=%v", err)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,87 +0,0 @@
|
|||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"telesrv/internal/domain"
|
||||
)
|
||||
|
||||
func TestStarGiftProfilePinOrderAndPagination(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
owner := domain.Peer{Type: domain.PeerTypeUser, ID: 1001}
|
||||
store := NewStarGiftStore()
|
||||
ids := make([]int64, 4)
|
||||
for i := range ids {
|
||||
id, err := store.Create(ctx, domain.SavedStarGift{
|
||||
Owner: owner, GiftID: 8001, RevisionID: 9001, MsgID: 100 + i, Date: 1700000000 + i,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("create gift %d: %v", i, err)
|
||||
}
|
||||
ids[i] = id
|
||||
}
|
||||
|
||||
if err := store.SetPinned(ctx, owner, []int64{ids[0], ids[2]}); err != nil {
|
||||
t.Fatalf("set pinned: %v", err)
|
||||
}
|
||||
|
||||
want := []int64{ids[0], ids[2], ids[3], ids[1]}
|
||||
var got []int64
|
||||
offset := ""
|
||||
for pageNumber := 0; ; pageNumber++ {
|
||||
page, err := store.ListByOwner(ctx, owner, false, offset, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("list page %d: %v", pageNumber, err)
|
||||
}
|
||||
if page.Count != len(ids) || len(page.Gifts) != 1 {
|
||||
t.Fatalf("page %d = %+v, want count=%d and one gift", pageNumber, page, len(ids))
|
||||
}
|
||||
got = append(got, page.Gifts[0].ID)
|
||||
if page.NextOffset == "" {
|
||||
break
|
||||
}
|
||||
offset = page.NextOffset
|
||||
}
|
||||
if !slices.Equal(got, want) {
|
||||
t.Fatalf("paged order = %v, want %v", got, want)
|
||||
}
|
||||
if ok, err := store.SetUnsaved(ctx, domain.SavedStarGiftRef{Owner: owner, MsgID: 100}, true); err != nil || !ok {
|
||||
t.Fatalf("hide pinned gift = %v err %v", ok, err)
|
||||
}
|
||||
hidden, found, err := store.GetByRef(ctx, domain.SavedStarGiftRef{Owner: owner, MsgID: 100})
|
||||
if err != nil || !found || !hidden.Unsaved || hidden.PinnedOrder != 0 {
|
||||
t.Fatalf("hidden pinned gift = %+v found %v err %v", hidden, found, err)
|
||||
}
|
||||
remaining, found, err := store.GetByRef(ctx, domain.SavedStarGiftRef{Owner: owner, MsgID: 102})
|
||||
if err != nil || !found || remaining.PinnedOrder != 1 {
|
||||
t.Fatalf("remaining pin = %+v found %v err %v", remaining, found, err)
|
||||
}
|
||||
if err := store.SetPinned(ctx, owner, []int64{ids[0], ids[2]}); err != nil {
|
||||
t.Fatalf("repin hidden gift: %v", err)
|
||||
}
|
||||
repinned, found, err := store.GetByRef(ctx, domain.SavedStarGiftRef{Owner: owner, MsgID: 100})
|
||||
if err != nil || !found || repinned.Unsaved || repinned.PinnedOrder != 1 {
|
||||
t.Fatalf("repinned gift = %+v found %v err %v", repinned, found, err)
|
||||
}
|
||||
|
||||
if err := store.SetPinned(ctx, owner, nil); err != nil {
|
||||
t.Fatalf("clear pinned: %v", err)
|
||||
}
|
||||
page, err := store.ListByOwner(ctx, owner, false, "", 10)
|
||||
if err != nil {
|
||||
t.Fatalf("list after clear: %v", err)
|
||||
}
|
||||
want = []int64{ids[3], ids[2], ids[1], ids[0]}
|
||||
got = got[:0]
|
||||
for _, gift := range page.Gifts {
|
||||
got = append(got, gift.ID)
|
||||
if gift.PinnedOrder != 0 {
|
||||
t.Fatalf("gift %d pinned_order=%d after clear", gift.ID, gift.PinnedOrder)
|
||||
}
|
||||
}
|
||||
if !slices.Equal(got, want) {
|
||||
t.Fatalf("order after clear = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,157 +0,0 @@
|
|||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
|
||||
"telesrv/internal/domain"
|
||||
)
|
||||
|
||||
// StarsStore 是 store.StarsStore 的内存实现,复刻 postgres 版的原子语义
|
||||
// (在单个互斥锁下完成读-检查-写,等价于 SELECT ... FOR UPDATE)。
|
||||
type StarsStore struct {
|
||||
mu sync.Mutex
|
||||
states map[int64]*starsState
|
||||
nextID int64
|
||||
}
|
||||
|
||||
type starsState struct {
|
||||
balance int64
|
||||
granted bool
|
||||
txns []domain.StarsTransaction // 追加序,读时倒序
|
||||
}
|
||||
|
||||
// NewStarsStore 创建内存 StarsStore。
|
||||
func NewStarsStore() *StarsStore {
|
||||
return &StarsStore{states: make(map[int64]*starsState)}
|
||||
}
|
||||
|
||||
func (s *StarsStore) GetBalance(_ context.Context, userID int64) (domain.StarsBalance, error) {
|
||||
if userID == 0 {
|
||||
return domain.StarsBalance{}, nil
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
st := s.states[userID]
|
||||
if st == nil {
|
||||
return domain.StarsBalance{UserID: userID}, nil
|
||||
}
|
||||
return domain.StarsBalance{UserID: userID, Balance: st.balance, Granted: st.granted}, nil
|
||||
}
|
||||
|
||||
func (s *StarsStore) EnsureGrant(_ context.Context, userID, amount int64, date int) (domain.StarsBalance, bool, error) {
|
||||
if userID == 0 {
|
||||
return domain.StarsBalance{}, false, nil
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
st := s.states[userID]
|
||||
if st == nil {
|
||||
st = &starsState{}
|
||||
s.states[userID] = st
|
||||
}
|
||||
if amount <= 0 {
|
||||
return domain.StarsBalance{UserID: userID, Balance: st.balance, Granted: st.granted}, false, nil
|
||||
}
|
||||
if st.granted {
|
||||
return domain.StarsBalance{UserID: userID, Balance: st.balance, Granted: true}, false, nil
|
||||
}
|
||||
st.balance += amount
|
||||
st.granted = true
|
||||
s.appendTxn(st, userID, amount, domain.StarsReasonGrant, domain.Peer{}, date, "", "")
|
||||
return domain.StarsBalance{UserID: userID, Balance: st.balance, Granted: true}, true, nil
|
||||
}
|
||||
|
||||
func (s *StarsStore) Credit(_ context.Context, userID, amount int64, reason domain.StarsTransactionReason, peer domain.Peer, date int, title, desc string) (domain.StarsBalance, error) {
|
||||
if userID == 0 || amount <= 0 {
|
||||
return domain.StarsBalance{}, domain.ErrStarsInvalidAmount
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
st := s.states[userID]
|
||||
if st == nil {
|
||||
st = &starsState{}
|
||||
s.states[userID] = st
|
||||
}
|
||||
st.balance += amount
|
||||
s.appendTxn(st, userID, amount, reason, peer, date, title, desc)
|
||||
return domain.StarsBalance{UserID: userID, Balance: st.balance, Granted: st.granted}, nil
|
||||
}
|
||||
|
||||
func (s *StarsStore) Debit(_ context.Context, userID, amount int64, reason domain.StarsTransactionReason, peer domain.Peer, date int, title, desc string) (domain.StarsBalance, error) {
|
||||
if userID == 0 || amount <= 0 {
|
||||
return domain.StarsBalance{}, domain.ErrStarsInvalidAmount
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
st := s.states[userID]
|
||||
if st == nil || st.balance < amount {
|
||||
return domain.StarsBalance{}, domain.ErrStarsInsufficient
|
||||
}
|
||||
st.balance -= amount
|
||||
s.appendTxn(st, userID, -amount, reason, peer, date, title, desc)
|
||||
return domain.StarsBalance{UserID: userID, Balance: st.balance, Granted: st.granted}, nil
|
||||
}
|
||||
|
||||
func (s *StarsStore) ListTransactions(_ context.Context, userID int64, query domain.StarsTransactionQuery) (domain.StarsTransactionPage, error) {
|
||||
if userID == 0 {
|
||||
return domain.StarsTransactionPage{}, nil
|
||||
}
|
||||
query, err := domain.NormalizeStarsTransactionQuery(query)
|
||||
if err != nil {
|
||||
return domain.StarsTransactionPage{}, err
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
st := s.states[userID]
|
||||
if st == nil {
|
||||
return domain.StarsTransactionPage{}, nil
|
||||
}
|
||||
page := domain.StarsTransactionPage{Balance: st.balance}
|
||||
cursor, hasCursor := domain.DecodeStarsCursor(query.Offset)
|
||||
out := make([]domain.StarsTransaction, 0, query.Limit+1)
|
||||
appendMatch := func(t domain.StarsTransaction) bool {
|
||||
if hasCursor {
|
||||
if query.Ascending && t.ID <= cursor {
|
||||
return false
|
||||
}
|
||||
if !query.Ascending && t.ID >= cursor {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if !query.Direction.IncludesAmount(t.Amount) {
|
||||
return false
|
||||
}
|
||||
out = append(out, t)
|
||||
return len(out) > query.Limit
|
||||
}
|
||||
if query.Ascending {
|
||||
for i := 0; i < len(st.txns) && len(out) <= query.Limit; i++ {
|
||||
appendMatch(st.txns[i])
|
||||
}
|
||||
} else {
|
||||
for i := len(st.txns) - 1; i >= 0 && len(out) <= query.Limit; i-- {
|
||||
appendMatch(st.txns[i])
|
||||
}
|
||||
}
|
||||
if len(out) > query.Limit {
|
||||
out = out[:query.Limit]
|
||||
page.NextOffset = domain.EncodeStarsCursor(out[len(out)-1].ID)
|
||||
}
|
||||
page.Transactions = out
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func (s *StarsStore) appendTxn(st *starsState, userID, amount int64, reason domain.StarsTransactionReason, peer domain.Peer, date int, title, desc string) {
|
||||
s.nextID++
|
||||
st.txns = append(st.txns, domain.StarsTransaction{
|
||||
ID: s.nextID,
|
||||
UserID: userID,
|
||||
Peer: peer,
|
||||
Amount: amount,
|
||||
Date: date,
|
||||
Reason: reason,
|
||||
Title: title,
|
||||
Description: desc,
|
||||
})
|
||||
}
|
||||
|
|
@ -411,7 +411,7 @@ func (s *UserStore) UpdateEmojiStatus(_ context.Context, userID int64, status do
|
|||
return domain.User{}, domain.ErrUserNotFound
|
||||
}
|
||||
if !status.Valid() {
|
||||
return domain.User{}, domain.ErrStarGiftCollectibleInvalid
|
||||
return domain.User{}, domain.ErrEmojiStatusCollectibleInvalid
|
||||
}
|
||||
u.EmojiStatusDocumentID = status.DocumentID
|
||||
u.EmojiStatusUntil = status.Until
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue