- middleware(Auth, Idempotency)를 클로저 팩토리 패턴으로 DI 전환 - database.DB/RDB 전역 변수 제거, ConnectMySQL/Redis 값 반환으로 변경 - download API X-API-Version 헤더 + 하위 호환성 규칙 문서화 - SaveGameData PlayTimeDelta 원자적 UPDATE (race condition 해소) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
220 lines
7.0 KiB
Go
220 lines
7.0 KiB
Go
package player
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// validateGameData checks that game data fields are within acceptable ranges.
|
|
func validateGameData(data *GameDataRequest) error {
|
|
if data.Level != nil && (*data.Level < 1 || *data.Level > 999) {
|
|
return fmt.Errorf("레벨은 1~999 범위여야 합니다")
|
|
}
|
|
if data.Experience != nil && *data.Experience < 0 {
|
|
return fmt.Errorf("경험치는 0 이상이어야 합니다")
|
|
}
|
|
if data.MaxHP != nil && (*data.MaxHP < 1 || *data.MaxHP > 999999) {
|
|
return fmt.Errorf("최대 HP는 1~999999 범위여야 합니다")
|
|
}
|
|
if data.MaxMP != nil && (*data.MaxMP < 1 || *data.MaxMP > 999999) {
|
|
return fmt.Errorf("최대 MP는 1~999999 범위여야 합니다")
|
|
}
|
|
if data.AttackPower != nil && (*data.AttackPower < 0 || *data.AttackPower > 999999) {
|
|
return fmt.Errorf("공격력은 0~999999 범위여야 합니다")
|
|
}
|
|
if data.AttackRange != nil && (*data.AttackRange < 0 || *data.AttackRange > 100) {
|
|
return fmt.Errorf("attack_range must be 0-100")
|
|
}
|
|
if data.SprintMultiplier != nil && (*data.SprintMultiplier < 0 || *data.SprintMultiplier > 10) {
|
|
return fmt.Errorf("sprint_multiplier must be 0-10")
|
|
}
|
|
if data.PlayTimeDelta != nil && *data.PlayTimeDelta < 0 {
|
|
return fmt.Errorf("플레이 시간 변화량은 0 이상이어야 합니다")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
type Service struct {
|
|
repo *Repository
|
|
userResolver func(username string) (uint, error)
|
|
}
|
|
|
|
func NewService(repo *Repository) *Service {
|
|
return &Service{repo: repo}
|
|
}
|
|
|
|
func (s *Service) SetUserResolver(fn func(username string) (uint, error)) {
|
|
s.userResolver = fn
|
|
}
|
|
|
|
// CreateProfile 회원가입 시 자동 호출되어 기본 프로필을 생성한다.
|
|
func (s *Service) CreateProfile(userID uint) error {
|
|
profile := &PlayerProfile{
|
|
UserID: userID,
|
|
}
|
|
return s.repo.Create(profile)
|
|
}
|
|
|
|
// GetProfile JWT 인증된 유저의 프로필을 조회한다. 없으면 자동 생성.
|
|
func (s *Service) GetProfile(userID uint) (*PlayerProfile, error) {
|
|
profile, err := s.repo.FindByUserID(userID)
|
|
if err != nil {
|
|
if err == gorm.ErrRecordNotFound {
|
|
profile = &PlayerProfile{UserID: userID}
|
|
if createErr := s.repo.Create(profile); createErr != nil {
|
|
return nil, fmt.Errorf("프로필 자동 생성에 실패했습니다: %w", createErr)
|
|
}
|
|
return profile, nil
|
|
}
|
|
return nil, fmt.Errorf("프로필 조회에 실패했습니다")
|
|
}
|
|
return profile, nil
|
|
}
|
|
|
|
// GetProfileByUsername 내부 API용: username으로 프로필 조회.
|
|
func (s *Service) GetProfileByUsername(username string) (*PlayerProfile, error) {
|
|
if s.userResolver == nil {
|
|
return nil, fmt.Errorf("userResolver가 설정되지 않았습니다")
|
|
}
|
|
userID, err := s.userResolver(username)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("존재하지 않는 유저입니다")
|
|
}
|
|
return s.GetProfile(userID)
|
|
}
|
|
|
|
// UpdateProfile 유저 자신의 프로필(닉네임)을 수정한다.
|
|
func (s *Service) UpdateProfile(userID uint, nickname string) (*PlayerProfile, error) {
|
|
profile, err := s.repo.FindByUserID(userID)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("프로필이 존재하지 않습니다")
|
|
}
|
|
if nickname != "" {
|
|
profile.Nickname = nickname
|
|
}
|
|
if err := s.repo.Update(profile); err != nil {
|
|
return nil, fmt.Errorf("프로필 수정에 실패했습니다")
|
|
}
|
|
return profile, nil
|
|
}
|
|
|
|
// SaveGameData 게임 서버에서 호출: 게임 데이터를 저장한다.
|
|
func (s *Service) SaveGameData(userID uint, data *GameDataRequest) error {
|
|
if err := validateGameData(data); err != nil {
|
|
return err
|
|
}
|
|
|
|
updates := map[string]interface{}{}
|
|
|
|
if data.Level != nil {
|
|
updates["level"] = *data.Level
|
|
}
|
|
if data.Experience != nil {
|
|
updates["experience"] = *data.Experience
|
|
}
|
|
if data.MaxHP != nil {
|
|
updates["max_hp"] = *data.MaxHP
|
|
}
|
|
if data.MaxMP != nil {
|
|
updates["max_mp"] = *data.MaxMP
|
|
}
|
|
if data.AttackPower != nil {
|
|
updates["attack_power"] = *data.AttackPower
|
|
}
|
|
if data.AttackRange != nil {
|
|
updates["attack_range"] = *data.AttackRange
|
|
}
|
|
if data.SprintMultiplier != nil {
|
|
updates["sprint_multiplier"] = *data.SprintMultiplier
|
|
}
|
|
if data.LastPosX != nil {
|
|
updates["last_pos_x"] = *data.LastPosX
|
|
}
|
|
if data.LastPosY != nil {
|
|
updates["last_pos_y"] = *data.LastPosY
|
|
}
|
|
if data.LastPosZ != nil {
|
|
updates["last_pos_z"] = *data.LastPosZ
|
|
}
|
|
if data.LastRotY != nil {
|
|
updates["last_rot_y"] = *data.LastRotY
|
|
}
|
|
if data.PlayTimeDelta != nil {
|
|
// 원자적 SQL 업데이트로 동시 요청 시 race condition 방지
|
|
updates["total_play_time"] = gorm.Expr("total_play_time + ?", *data.PlayTimeDelta)
|
|
}
|
|
|
|
if len(updates) == 0 {
|
|
return nil
|
|
}
|
|
|
|
return s.repo.UpdateStats(userID, updates)
|
|
}
|
|
|
|
// SaveGameDataByUsername 내부 API용: username 기반으로 게임 데이터 저장.
|
|
func (s *Service) SaveGameDataByUsername(username string, data *GameDataRequest) error {
|
|
if s.userResolver == nil {
|
|
return fmt.Errorf("userResolver가 설정되지 않았습니다")
|
|
}
|
|
// Note: validateGameData is called inside SaveGameData, no need to call it here.
|
|
userID, err := s.userResolver(username)
|
|
if err != nil {
|
|
return fmt.Errorf("존재하지 않는 유저입니다")
|
|
}
|
|
return s.SaveGameData(userID, data)
|
|
}
|
|
|
|
// GrantExperience adds experience to a player and handles level ups + stat recalculation.
|
|
func (s *Service) GrantExperience(userID uint, exp int) (*LevelUpResult, error) {
|
|
profile, err := s.repo.FindByUserID(userID)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("프로필이 존재하지 않습니다")
|
|
}
|
|
|
|
result := ApplyExperience(profile.Level, profile.Experience, exp)
|
|
|
|
updates := map[string]interface{}{
|
|
"level": result.NewLevel,
|
|
"experience": result.Experience,
|
|
"max_hp": result.MaxHP,
|
|
"max_mp": result.MaxMP,
|
|
"attack_power": result.AttackPower,
|
|
}
|
|
|
|
if err := s.repo.UpdateStats(userID, updates); err != nil {
|
|
return nil, fmt.Errorf("레벨업 저장 실패: %w", err)
|
|
}
|
|
|
|
return &result, nil
|
|
}
|
|
|
|
// GrantExperienceByUsername grants experience to a player by username.
|
|
func (s *Service) GrantExperienceByUsername(username string, exp int) error {
|
|
if s.userResolver == nil {
|
|
return fmt.Errorf("userResolver가 설정되지 않았습니다")
|
|
}
|
|
userID, err := s.userResolver(username)
|
|
if err != nil {
|
|
return fmt.Errorf("존재하지 않는 유저입니다")
|
|
}
|
|
_, err = s.GrantExperience(userID, exp)
|
|
return err
|
|
}
|
|
|
|
// GameDataRequest 게임 데이터 저장 요청 (nil 필드는 변경하지 않음).
|
|
type GameDataRequest struct {
|
|
Level *int `json:"level,omitempty"`
|
|
Experience *int `json:"experience,omitempty"`
|
|
MaxHP *float64 `json:"maxHp,omitempty"`
|
|
MaxMP *float64 `json:"maxMp,omitempty"`
|
|
AttackPower *float64 `json:"attackPower,omitempty"`
|
|
AttackRange *float64 `json:"attackRange,omitempty"`
|
|
SprintMultiplier *float64 `json:"sprintMultiplier,omitempty"`
|
|
LastPosX *float64 `json:"lastPosX,omitempty"`
|
|
LastPosY *float64 `json:"lastPosY,omitempty"`
|
|
LastPosZ *float64 `json:"lastPosZ,omitempty"`
|
|
LastRotY *float64 `json:"lastRotY,omitempty"`
|
|
PlayTimeDelta *int64 `json:"playTimeDelta,omitempty"` // 누적할 플레이 시간(초)
|
|
}
|