DNF90 服务端与启动器完整源码(含 GM 工具功能增强)
服务端(Go): - GM 塞背包/带属性装备发放:在线角色推送 op14 增量物品行,背包实时刷新,无需回角色选择界面 - GM 改金币/改等级:去掉在线拒绝,落库后推送 op14 钱包/op37 等级状态,在线实时刷新 - 等级端点统一切换到新版 GMSetCharacterLevel(自带在线刷新) - 无限/锁死疲劳模式 + 燃烧疲劳:每房间消耗 2 点、打怪与通关经验双倍 - 燃烧疲劳开关时给所有在线角色推送系统提示(op12 mode 0) - 深渊史诗掉率:GM 全局倍率 + 城镇增益药剂窗口倍率,真实接入掉落结算 启动器(Python/JS): - 标题栏自绘、窗口 1204x717、禁止拖拽改大小、仅最小化/关闭 - GM 工具:疲劳与燃烧、深渊史诗掉率、拍卖行上架(单一定价对齐) - 拍卖行上架前端对齐服务端单一价格语义,修复 400 报错
This commit is contained in:
commit
645b64fe21
4388 files changed
+1405457
No files matched your search
@@ -0,0 +1,276 @@
|
||||
package redeem
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"longheng.io/server/internal/platform/admincmd"
|
||||
"longheng.io/server/internal/platform/httpx"
|
||||
)
|
||||
|
||||
var ErrAdminMuxRequired = errors.New("redeem admin mux is required")
|
||||
|
||||
const maxAdminBodyBytes = 1 << 20
|
||||
|
||||
type AdminOptions struct {
|
||||
Prefix string
|
||||
Wrap func(http.HandlerFunc) http.HandlerFunc
|
||||
MutateWrap func(string, http.HandlerFunc) http.HandlerFunc
|
||||
CommandHooks AdminCommandHooks
|
||||
}
|
||||
|
||||
type AdminCommandHooks struct {
|
||||
Submit func(*http.Request, string, string, string, any) (admincmd.Receipt, bool, bool, error)
|
||||
MarkSucceeded func(context.Context, admincmd.Receipt) admincmd.Receipt
|
||||
MarkFailed func(context.Context, admincmd.Receipt, error)
|
||||
WriteError func(http.ResponseWriter, error) bool
|
||||
WriteDuplicate func(http.ResponseWriter, admincmd.Receipt)
|
||||
WriteJSONWithReceipt func(http.ResponseWriter, int, map[string]any, admincmd.Receipt)
|
||||
}
|
||||
|
||||
func RegisterAdminRoutes(mux *http.ServeMux, service Service, options AdminOptions) error {
|
||||
if mux == nil {
|
||||
return ErrAdminMuxRequired
|
||||
}
|
||||
prefix := normalizeAdminPrefix(options.Prefix)
|
||||
wrap := options.Wrap
|
||||
if wrap == nil {
|
||||
wrap = func(next http.HandlerFunc) http.HandlerFunc { return next }
|
||||
}
|
||||
mutateWrap := options.MutateWrap
|
||||
if mutateWrap == nil {
|
||||
mutateWrap = func(_ string, next http.HandlerFunc) http.HandlerFunc {
|
||||
return wrap(next)
|
||||
}
|
||||
}
|
||||
mux.HandleFunc(prefix, wrap(SnapshotHandler(service)))
|
||||
mux.HandleFunc(prefix+"/snapshot", wrap(SnapshotHandler(service)))
|
||||
mux.HandleFunc(prefix+"/codes", mutateWrap(httpx.AdminOperationID(http.MethodPost, prefix+"/codes"), PutCodeHandlerWithCommands(service, options.CommandHooks)))
|
||||
mux.HandleFunc(prefix+"/claim", mutateWrap(httpx.AdminOperationID(http.MethodPost, prefix+"/claim"), ClaimHandlerWithCommands(service, options.CommandHooks)))
|
||||
return nil
|
||||
}
|
||||
|
||||
func SnapshotHandler(service Service) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
writeMethodNA(w, http.MethodGet)
|
||||
return
|
||||
}
|
||||
snapshot, err := service.Snapshot(r.Context())
|
||||
if err != nil {
|
||||
writeRedeemError(w, err)
|
||||
return
|
||||
}
|
||||
httpx.WriteJSON(w, http.StatusOK, snapshot)
|
||||
}
|
||||
}
|
||||
|
||||
func PutCodeHandler(service Service) http.HandlerFunc {
|
||||
return PutCodeHandlerWithCommands(service, AdminCommandHooks{})
|
||||
}
|
||||
|
||||
func PutCodeHandlerWithCommands(service Service, commands AdminCommandHooks) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
writeMethodNA(w, http.MethodPost)
|
||||
return
|
||||
}
|
||||
var code Code
|
||||
if err := decodeRedeemJSON(w, r, &code); err != nil {
|
||||
httpx.WriteJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
receipt, duplicate, submitted, err := submitRedeemCmd(commands, r, "redeem.code.put", firstNonEmpty(code.Code, "code"), "redeem code put", code)
|
||||
if writeRedeemCmdErr(commands, w, err) {
|
||||
return
|
||||
}
|
||||
if submitted && duplicate {
|
||||
// 管理命令已提交过时直接回放 receipt,不再重复写礼包码。
|
||||
writeCmdDuplicate(commands, w, receipt)
|
||||
return
|
||||
}
|
||||
if submitted {
|
||||
code.Meta = mergeStringMap(code.Meta, map[string]string{"admin_receipt_id": receipt.ID})
|
||||
}
|
||||
saved, err := service.PutCode(r.Context(), code)
|
||||
if err != nil {
|
||||
if submitted {
|
||||
markRedeemCmdFail(commands, r.Context(), receipt, err)
|
||||
}
|
||||
writeRedeemError(w, err)
|
||||
return
|
||||
}
|
||||
response := map[string]any{"code": saved}
|
||||
if submitted {
|
||||
receipt = markRedeemCmdOK(commands, r.Context(), receipt)
|
||||
writeRedeemReceipt(commands, w, http.StatusOK, response, receipt)
|
||||
return
|
||||
}
|
||||
httpx.WriteJSON(w, http.StatusOK, response)
|
||||
}
|
||||
}
|
||||
|
||||
func ClaimHandler(service Service) http.HandlerFunc {
|
||||
return ClaimHandlerWithCommands(service, AdminCommandHooks{})
|
||||
}
|
||||
|
||||
func ClaimHandlerWithCommands(service Service, commands AdminCommandHooks) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
writeMethodNA(w, http.MethodPost)
|
||||
return
|
||||
}
|
||||
var request ClaimRequest
|
||||
if err := decodeRedeemJSON(w, r, &request); err != nil {
|
||||
httpx.WriteJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
request.AdminCommand = nil
|
||||
target := firstNonEmpty(request.AccountID, request.Code, "claim")
|
||||
receipt, duplicateCommand, submitted, err := submitRedeemCmd(commands, r, "redeem.claim.repair", target, "redeem claim repair", request)
|
||||
if writeRedeemCmdErr(commands, w, err) {
|
||||
return
|
||||
}
|
||||
if submitted && duplicateCommand {
|
||||
// 补领/修复类操作必须先挡住重复命令,避免再次消耗礼包码或重复发奖。
|
||||
writeCmdDuplicate(commands, w, receipt)
|
||||
return
|
||||
}
|
||||
if submitted {
|
||||
request.Meta = mergeStringMap(request.Meta, map[string]string{"admin_receipt_id": receipt.ID})
|
||||
}
|
||||
result, err := service.Claim(r.Context(), request)
|
||||
if err != nil {
|
||||
if submitted {
|
||||
markRedeemCmdFail(commands, r.Context(), receipt, err)
|
||||
}
|
||||
writeRedeemError(w, err)
|
||||
return
|
||||
}
|
||||
response := redeemResponseMap(result)
|
||||
if submitted {
|
||||
receipt = markRedeemCmdOK(commands, r.Context(), receipt)
|
||||
writeRedeemReceipt(commands, w, http.StatusOK, response, receipt)
|
||||
return
|
||||
}
|
||||
httpx.WriteJSON(w, http.StatusOK, result)
|
||||
}
|
||||
}
|
||||
|
||||
func submitRedeemCmd(commands AdminCommandHooks, r *http.Request, operation, target, reason string, params any) (admincmd.Receipt, bool, bool, error) {
|
||||
if commands.Submit == nil {
|
||||
return admincmd.Receipt{}, false, false, nil
|
||||
}
|
||||
return commands.Submit(r, operation, target, reason, params)
|
||||
}
|
||||
|
||||
func markRedeemCmdOK(commands AdminCommandHooks, ctx context.Context, receipt admincmd.Receipt) admincmd.Receipt {
|
||||
if commands.MarkSucceeded == nil || receipt.ID == "" {
|
||||
return receipt
|
||||
}
|
||||
return commands.MarkSucceeded(ctx, receipt)
|
||||
}
|
||||
|
||||
func markRedeemCmdFail(commands AdminCommandHooks, ctx context.Context, receipt admincmd.Receipt, err error) {
|
||||
if commands.MarkFailed == nil || receipt.ID == "" || err == nil {
|
||||
return
|
||||
}
|
||||
commands.MarkFailed(ctx, receipt, err)
|
||||
}
|
||||
|
||||
func writeRedeemCmdErr(commands AdminCommandHooks, w http.ResponseWriter, err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
if commands.WriteError != nil {
|
||||
return commands.WriteError(w, err)
|
||||
}
|
||||
writeRedeemError(w, err)
|
||||
return true
|
||||
}
|
||||
|
||||
func writeCmdDuplicate(commands AdminCommandHooks, w http.ResponseWriter, receipt admincmd.Receipt) {
|
||||
if commands.WriteDuplicate != nil {
|
||||
commands.WriteDuplicate(w, receipt)
|
||||
return
|
||||
}
|
||||
if receipt.ID != "" {
|
||||
w.Header().Set(httpx.AdminReceiptHeader, receipt.ID)
|
||||
}
|
||||
httpx.WriteJSON(w, http.StatusOK, map[string]any{
|
||||
"status": "duplicate",
|
||||
"admin_receipt": receipt,
|
||||
})
|
||||
}
|
||||
|
||||
func writeRedeemReceipt(commands AdminCommandHooks, w http.ResponseWriter, status int, response map[string]any, receipt admincmd.Receipt) {
|
||||
if commands.WriteJSONWithReceipt != nil {
|
||||
commands.WriteJSONWithReceipt(w, status, response, receipt)
|
||||
return
|
||||
}
|
||||
if response == nil {
|
||||
response = make(map[string]any)
|
||||
}
|
||||
if receipt.ID != "" {
|
||||
w.Header().Set(httpx.AdminReceiptHeader, receipt.ID)
|
||||
response["admin_receipt"] = receipt
|
||||
}
|
||||
httpx.WriteJSON(w, status, response)
|
||||
}
|
||||
|
||||
func redeemResponseMap(value any) map[string]any {
|
||||
data, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return map[string]any{"marshal_error": err.Error()}
|
||||
}
|
||||
var out map[string]any
|
||||
if err := json.Unmarshal(data, &out); err != nil {
|
||||
return map[string]any{"marshal_error": err.Error()}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func decodeRedeemJSON(w http.ResponseWriter, r *http.Request, out any) error {
|
||||
return httpx.DecodeStrictJSON(w, r, maxAdminBodyBytes, out)
|
||||
}
|
||||
|
||||
func writeRedeemError(w http.ResponseWriter, err error) {
|
||||
status := http.StatusBadRequest
|
||||
switch {
|
||||
case errors.Is(err, ErrStoreRequired):
|
||||
status = http.StatusServiceUnavailable
|
||||
case errors.Is(err, ErrCodeNotFound):
|
||||
status = http.StatusNotFound
|
||||
case errors.Is(err, ErrCodeInactive), errors.Is(err, ErrCodeExhausted), errors.Is(err, ErrAccountLimitExceeded), errors.Is(err, ErrClaimConflict):
|
||||
status = http.StatusConflict
|
||||
case errors.Is(err, admincmd.ErrMissingIdempotencyKey),
|
||||
errors.Is(err, admincmd.ErrMissingConfirmation),
|
||||
errors.Is(err, admincmd.ErrMissingActor),
|
||||
errors.Is(err, admincmd.ErrMissingReason):
|
||||
status = http.StatusForbidden
|
||||
}
|
||||
httpx.WriteJSON(w, status, map[string]string{"error": err.Error()})
|
||||
}
|
||||
|
||||
func writeMethodNA(w http.ResponseWriter, methods ...string) {
|
||||
w.Header().Set("Allow", strings.Join(methods, ", "))
|
||||
httpx.WriteJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"})
|
||||
}
|
||||
|
||||
func normalizeAdminPrefix(prefix string) string {
|
||||
prefix = strings.TrimSpace(prefix)
|
||||
if prefix == "" {
|
||||
return "/debug/redeem"
|
||||
}
|
||||
if !strings.HasPrefix(prefix, "/") {
|
||||
prefix = "/" + prefix
|
||||
}
|
||||
prefix = strings.TrimRight(prefix, "/")
|
||||
if prefix == "" {
|
||||
return "/debug/redeem"
|
||||
}
|
||||
return prefix
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package redeem
|
||||
|
||||
import "longheng.io/server/internal/platform/runtimeguard"
|
||||
|
||||
func (*MemoryStore) BackendKind() runtimeguard.Backend {
|
||||
return runtimeguard.BackendMemory
|
||||
}
|
||||
|
||||
func (*PersistentStore) BackendKind() runtimeguard.Backend {
|
||||
return runtimeguard.BackendMemory
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package redeem
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"longheng.io/server/internal/platform/eventlog"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultClaimEvStream = "redeem.claim"
|
||||
defaultClaimEvType = "redeem.claimed"
|
||||
claimRollbackTimeout = 5 * time.Second
|
||||
)
|
||||
|
||||
type claimEventPayload struct {
|
||||
ClaimID string `json:"claim_id"`
|
||||
Code string `json:"code"`
|
||||
AccountID string `json:"account_id"`
|
||||
ShardID string `json:"shard_id,omitempty"`
|
||||
Source string `json:"source,omitempty"`
|
||||
Campaign string `json:"campaign,omitempty"`
|
||||
RewardRef string `json:"reward_ref"`
|
||||
IdempotencyKey string `json:"idempotency_key"`
|
||||
Uses int `json:"uses"`
|
||||
Remaining int `json:"remaining"`
|
||||
AdminReceiptID string `json:"admin_receipt_id,omitempty"`
|
||||
Meta map[string]string `json:"meta,omitempty"`
|
||||
ClaimedAt time.Time `json:"claimed_at"`
|
||||
}
|
||||
|
||||
func (s Service) lookupClaimEvent(ctx context.Context, request ClaimRequest) (ClaimResult, bool, error) {
|
||||
if s.EventLog == nil {
|
||||
return ClaimResult{}, false, nil
|
||||
}
|
||||
event, ok, err := s.EventLog.GetByIdempotencyKey(ctx, claimEventKey(request.Code, request.AccountID, request.IdempotencyKey))
|
||||
if err != nil || !ok {
|
||||
return ClaimResult{}, false, err
|
||||
}
|
||||
result, err := claimResultFromEvent(event)
|
||||
if err != nil {
|
||||
return ClaimResult{}, false, err
|
||||
}
|
||||
if claimReplayConflict(result, request) {
|
||||
return ClaimResult{}, false, ErrClaimConflict
|
||||
}
|
||||
result.Duplicate = true
|
||||
return result, true, nil
|
||||
}
|
||||
|
||||
func (s Service) appendClaimEvent(ctx context.Context, result ClaimResult) error {
|
||||
if s.EventLog == nil {
|
||||
return nil
|
||||
}
|
||||
payload, err := json.Marshal(claimPayloadResult(result))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s.EventLog.Append(ctx, eventlog.Event{
|
||||
ID: claimEventID(result.Code, result.AccountID, result.IdempotencyKey),
|
||||
Stream: s.claimEventStream(),
|
||||
Type: s.claimEventType(),
|
||||
AggregateID: result.AccountID,
|
||||
IdempotencyKey: claimEventKey(result.Code, result.AccountID, result.IdempotencyKey),
|
||||
Payload: payload,
|
||||
Headers: map[string]string{
|
||||
"code": result.Code,
|
||||
"account_id": result.AccountID,
|
||||
"campaign": result.Campaign,
|
||||
"reward_ref": result.RewardRef,
|
||||
"remaining": strconv.Itoa(result.Remaining),
|
||||
"admin_receipt_id": result.AdminReceiptID,
|
||||
},
|
||||
})
|
||||
if errors.Is(err, eventlog.ErrIdempotencyConflict) {
|
||||
return ErrClaimConflict
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s Service) claimEventStream() string {
|
||||
if stream := strings.TrimSpace(s.EventLogStream); stream != "" {
|
||||
return stream
|
||||
}
|
||||
return defaultClaimEvStream
|
||||
}
|
||||
|
||||
func (s Service) claimEventType() string {
|
||||
if typ := strings.TrimSpace(s.EventLogType); typ != "" {
|
||||
return typ
|
||||
}
|
||||
return defaultClaimEvType
|
||||
}
|
||||
|
||||
func runClaimRollback(parent context.Context, rollback func(context.Context) error) error {
|
||||
// outbox 写失败可能来自请求超时;回滚不继承取消,但保留 trace/value 方便排障。
|
||||
base := context.Background()
|
||||
if parent != nil {
|
||||
base = context.WithoutCancel(parent)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(base, claimRollbackTimeout)
|
||||
defer cancel()
|
||||
return rollback(ctx)
|
||||
}
|
||||
|
||||
func claimPayloadResult(result ClaimResult) claimEventPayload {
|
||||
return claimEventPayload{
|
||||
ClaimID: result.ClaimID,
|
||||
Code: result.Code,
|
||||
AccountID: result.AccountID,
|
||||
ShardID: result.ShardID,
|
||||
Source: result.Source,
|
||||
Campaign: result.Campaign,
|
||||
RewardRef: result.RewardRef,
|
||||
IdempotencyKey: result.IdempotencyKey,
|
||||
Uses: result.Uses,
|
||||
Remaining: result.Remaining,
|
||||
AdminReceiptID: result.AdminReceiptID,
|
||||
Meta: cloneStringMap(result.Meta),
|
||||
ClaimedAt: result.ClaimedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func claimResultFromEvent(event eventlog.Event) (ClaimResult, error) {
|
||||
var payload claimEventPayload
|
||||
if err := json.Unmarshal(event.Payload, &payload); err != nil {
|
||||
return ClaimResult{}, err
|
||||
}
|
||||
return ClaimResult{
|
||||
Accepted: true,
|
||||
ClaimID: payload.ClaimID,
|
||||
Code: payload.Code,
|
||||
AccountID: payload.AccountID,
|
||||
ShardID: payload.ShardID,
|
||||
Source: payload.Source,
|
||||
Campaign: payload.Campaign,
|
||||
RewardRef: payload.RewardRef,
|
||||
IdempotencyKey: firstNonEmpty(payload.IdempotencyKey, event.IdempotencyKey),
|
||||
Uses: payload.Uses,
|
||||
Remaining: payload.Remaining,
|
||||
AdminReceiptID: payload.AdminReceiptID,
|
||||
Meta: cloneStringMap(payload.Meta),
|
||||
ClaimedAt: payload.ClaimedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func claimEventKey(code, accountID, key string) string {
|
||||
code = strings.TrimSpace(code)
|
||||
accountID = strings.TrimSpace(accountID)
|
||||
key = strings.TrimSpace(key)
|
||||
if code == "" || accountID == "" || key == "" {
|
||||
return ""
|
||||
}
|
||||
return strings.Join([]string{"redeem", "claim", "v1", encodeEventKeyPart(code), encodeEventKeyPart(accountID), encodeEventKeyPart(key)}, ":")
|
||||
}
|
||||
|
||||
func encodeEventKeyPart(value string) string {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
return "_"
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(value))
|
||||
}
|
||||
|
||||
func claimEventID(code, accountID, key string) string {
|
||||
sum := sha256.Sum256([]byte(claimEventKey(code, accountID, key)))
|
||||
return "redeem-claim-" + hex.EncodeToString(sum[:8])
|
||||
}
|
||||
@@ -0,0 +1,527 @@
|
||||
package redeem
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"longheng.io/server/internal/platform/admincmd"
|
||||
"longheng.io/server/internal/platform/eventlog"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrCodeRequired = errors.New("redeem code is required")
|
||||
ErrAccountRequired = errors.New("redeem account is required")
|
||||
ErrStoreRequired = errors.New("redeem store is required")
|
||||
ErrCodeNotFound = errors.New("redeem code not found")
|
||||
ErrCodeInactive = errors.New("redeem code is inactive")
|
||||
ErrCodeExhausted = errors.New("redeem code is exhausted")
|
||||
ErrAccountLimitExceeded = errors.New("redeem account limit exceeded")
|
||||
ErrClaimConflict = errors.New("redeem claim idempotency conflict")
|
||||
ErrInvalidRedeemCode = errors.New("redeem code is invalid")
|
||||
ErrInvalidRedeemOperation = errors.New("redeem operation is invalid")
|
||||
)
|
||||
|
||||
type Code struct {
|
||||
Code string `json:"code"`
|
||||
Campaign string `json:"campaign,omitempty"`
|
||||
RewardRef string `json:"reward_ref"`
|
||||
MaxUses int `json:"max_uses,omitempty"`
|
||||
PerAccountLimit int `json:"per_account_limit,omitempty"`
|
||||
StartsAt time.Time `json:"starts_at,omitempty"`
|
||||
EndsAt time.Time `json:"ends_at,omitempty"`
|
||||
Disabled bool `json:"disabled,omitempty"`
|
||||
Meta map[string]string `json:"meta,omitempty"`
|
||||
}
|
||||
|
||||
type ClaimRequest struct {
|
||||
Code string `json:"code"`
|
||||
AccountID string `json:"account_id"`
|
||||
ShardID string `json:"shard_id,omitempty"`
|
||||
Source string `json:"source,omitempty"`
|
||||
IdempotencyKey string `json:"idempotency_key,omitempty"`
|
||||
Meta map[string]string `json:"meta,omitempty"`
|
||||
AdminCommand *admincmd.Command `json:"admin_command,omitempty"`
|
||||
}
|
||||
|
||||
type ClaimResult struct {
|
||||
Accepted bool `json:"accepted"`
|
||||
Duplicate bool `json:"duplicate,omitempty"`
|
||||
ClaimID string `json:"claim_id"`
|
||||
Code string `json:"code"`
|
||||
AccountID string `json:"account_id"`
|
||||
ShardID string `json:"shard_id,omitempty"`
|
||||
Source string `json:"source,omitempty"`
|
||||
Campaign string `json:"campaign,omitempty"`
|
||||
RewardRef string `json:"reward_ref"`
|
||||
IdempotencyKey string `json:"idempotency_key"`
|
||||
Uses int `json:"uses"`
|
||||
Remaining int `json:"remaining"`
|
||||
AdminReceiptID string `json:"admin_receipt_id,omitempty"`
|
||||
Meta map[string]string `json:"meta,omitempty"`
|
||||
ClaimedAt time.Time `json:"claimed_at"`
|
||||
}
|
||||
|
||||
type Store interface {
|
||||
PutCode(context.Context, Code) (Code, error)
|
||||
Claim(context.Context, ClaimRequest, time.Time) (ClaimResult, error)
|
||||
Snapshot(context.Context) (Snapshot, error)
|
||||
}
|
||||
|
||||
type Snapshot struct {
|
||||
Codes int `json:"codes"`
|
||||
Claims int `json:"claims"`
|
||||
Uses map[string]int `json:"uses,omitempty"`
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
Store Store
|
||||
EventLog *eventlog.Log
|
||||
EventLogStream string
|
||||
EventLogType string
|
||||
Now func() time.Time
|
||||
}
|
||||
|
||||
func (s Service) PutCode(ctx context.Context, code Code) (Code, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return Code{}, err
|
||||
}
|
||||
if s.Store == nil {
|
||||
return Code{}, ErrStoreRequired
|
||||
}
|
||||
return s.Store.PutCode(ctx, code)
|
||||
}
|
||||
|
||||
func (s Service) Claim(ctx context.Context, request ClaimRequest) (ClaimResult, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return ClaimResult{}, err
|
||||
}
|
||||
if s.Store == nil {
|
||||
return ClaimResult{}, ErrStoreRequired
|
||||
}
|
||||
request = normClaimReq(request)
|
||||
if request.Code == "" {
|
||||
return ClaimResult{}, ErrCodeRequired
|
||||
}
|
||||
if request.AccountID == "" {
|
||||
return ClaimResult{}, ErrAccountRequired
|
||||
}
|
||||
if request.IdempotencyKey == "" {
|
||||
request.IdempotencyKey = IdempotencyKey(request.Code, request.AccountID)
|
||||
}
|
||||
if request.AdminCommand != nil {
|
||||
// 运营补发礼包码也走危险命令校验,确保有 reason、确认信息和幂等键。
|
||||
command := *request.AdminCommand
|
||||
command.Operation = firstNonEmpty(command.Operation, "redeem.repair")
|
||||
command.Scope = firstNonEmpty(command.Scope, "redeem")
|
||||
command.Target = firstNonEmpty(command.Target, request.AccountID)
|
||||
command.Params = mergeCommandParams(command.Params, request)
|
||||
if err := admincmd.Validate(command, admincmd.DangerousPolicy()); err != nil {
|
||||
return ClaimResult{}, err
|
||||
}
|
||||
receipt, err := admincmd.NewReceipt(command, "accepted", s.now())
|
||||
if err != nil {
|
||||
return ClaimResult{}, err
|
||||
}
|
||||
request.AdminCommand = &command
|
||||
request.Meta = mergeStringMap(request.Meta, map[string]string{"admin_receipt_id": receipt.ID})
|
||||
}
|
||||
if result, ok, err := s.lookupClaimEvent(ctx, request); err != nil || ok {
|
||||
return result, err
|
||||
}
|
||||
result, err := s.Store.Claim(ctx, request, s.now())
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
if err := s.appendClaimEvent(ctx, result); err != nil {
|
||||
return result, errors.Join(err, runClaimRollback(ctx, func(ctx context.Context) error {
|
||||
return s.rollbackClaim(ctx, result)
|
||||
}))
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
type claimRollbackStore interface {
|
||||
RollbackClaim(context.Context, ClaimResult) error
|
||||
}
|
||||
|
||||
func (s Service) rollbackClaim(ctx context.Context, result ClaimResult) error {
|
||||
if result.Duplicate || s.Store == nil {
|
||||
return nil
|
||||
}
|
||||
store, ok := s.Store.(claimRollbackStore)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return store.RollbackClaim(ctx, result)
|
||||
}
|
||||
|
||||
func (s Service) Snapshot(ctx context.Context) (Snapshot, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return Snapshot{}, err
|
||||
}
|
||||
if s.Store == nil {
|
||||
return Snapshot{}, ErrStoreRequired
|
||||
}
|
||||
return s.Store.Snapshot(ctx)
|
||||
}
|
||||
|
||||
func (s Service) now() time.Time {
|
||||
if s.Now != nil {
|
||||
return s.Now().UTC()
|
||||
}
|
||||
return time.Now().UTC()
|
||||
}
|
||||
|
||||
type MemoryStore struct {
|
||||
mu sync.Mutex
|
||||
codes map[string]Code
|
||||
claimsByKey map[string]ClaimResult
|
||||
claimsByAccount map[string]int
|
||||
uses map[string]int
|
||||
}
|
||||
|
||||
func NewMemoryStore() *MemoryStore {
|
||||
return &MemoryStore{
|
||||
codes: make(map[string]Code),
|
||||
claimsByKey: make(map[string]ClaimResult),
|
||||
claimsByAccount: make(map[string]int),
|
||||
uses: make(map[string]int),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MemoryStore) PutCode(ctx context.Context, code Code) (Code, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return Code{}, err
|
||||
}
|
||||
if s == nil {
|
||||
return Code{}, ErrStoreRequired
|
||||
}
|
||||
code = normalizeCode(code)
|
||||
if code.Code == "" {
|
||||
return Code{}, ErrCodeRequired
|
||||
}
|
||||
if code.RewardRef == "" {
|
||||
return Code{}, fmt.Errorf("%w: reward_ref is required", ErrInvalidRedeemCode)
|
||||
}
|
||||
if code.MaxUses < 0 || code.PerAccountLimit < 0 {
|
||||
return Code{}, fmt.Errorf("%w: limits cannot be negative", ErrInvalidRedeemCode)
|
||||
}
|
||||
if code.PerAccountLimit == 0 {
|
||||
code.PerAccountLimit = 1
|
||||
}
|
||||
if !code.StartsAt.IsZero() && !code.EndsAt.IsZero() && code.EndsAt.Before(code.StartsAt) {
|
||||
return Code{}, fmt.Errorf("%w: ends_at is before starts_at", ErrInvalidRedeemCode)
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.codes[code.Code] = cloneCode(code)
|
||||
s.mu.Unlock()
|
||||
return cloneCode(code), nil
|
||||
}
|
||||
|
||||
func (s *MemoryStore) Claim(ctx context.Context, request ClaimRequest, now time.Time) (ClaimResult, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return ClaimResult{}, err
|
||||
}
|
||||
if s == nil {
|
||||
return ClaimResult{}, ErrStoreRequired
|
||||
}
|
||||
request = normClaimReq(request)
|
||||
if request.Code == "" {
|
||||
return ClaimResult{}, ErrCodeRequired
|
||||
}
|
||||
if request.AccountID == "" {
|
||||
return ClaimResult{}, ErrAccountRequired
|
||||
}
|
||||
if request.IdempotencyKey == "" {
|
||||
request.IdempotencyKey = IdempotencyKey(request.Code, request.AccountID)
|
||||
}
|
||||
if now.IsZero() {
|
||||
now = time.Now().UTC()
|
||||
} else {
|
||||
now = now.UTC()
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
lookupKey := claimLookupKey(request)
|
||||
if existing, ok := s.claimsByKey[lookupKey]; ok {
|
||||
if claimReplayConflict(existing, request) {
|
||||
return ClaimResult{}, ErrClaimConflict
|
||||
}
|
||||
// 礼包码领取按 code+account+key 重放,防止客户端超时重试重复扣次数。
|
||||
existing.Duplicate = true
|
||||
return cloneClaimResult(existing), nil
|
||||
}
|
||||
code, ok := s.codes[request.Code]
|
||||
if !ok {
|
||||
return ClaimResult{}, ErrCodeNotFound
|
||||
}
|
||||
if !codeActive(code, now) {
|
||||
return ClaimResult{}, ErrCodeInactive
|
||||
}
|
||||
if code.MaxUses > 0 && s.uses[code.Code] >= code.MaxUses {
|
||||
return ClaimResult{}, ErrCodeExhausted
|
||||
}
|
||||
accountKey := code.Code + "\x00" + request.AccountID
|
||||
if s.claimsByAccount[accountKey] >= code.PerAccountLimit {
|
||||
return ClaimResult{}, ErrAccountLimitExceeded
|
||||
}
|
||||
|
||||
// 次数扣减和领取记录在同一把锁内完成;生产存储应使用同等原子写能力。
|
||||
s.uses[code.Code]++
|
||||
s.claimsByAccount[accountKey]++
|
||||
remaining := -1
|
||||
if code.MaxUses > 0 {
|
||||
remaining = code.MaxUses - s.uses[code.Code]
|
||||
}
|
||||
result := ClaimResult{
|
||||
Accepted: true,
|
||||
ClaimID: ClaimID(request.Code, request.AccountID, request.IdempotencyKey),
|
||||
Code: code.Code,
|
||||
AccountID: request.AccountID,
|
||||
ShardID: request.ShardID,
|
||||
Source: request.Source,
|
||||
Campaign: code.Campaign,
|
||||
RewardRef: code.RewardRef,
|
||||
IdempotencyKey: request.IdempotencyKey,
|
||||
Uses: s.uses[code.Code],
|
||||
Remaining: remaining,
|
||||
AdminReceiptID: request.Meta["admin_receipt_id"],
|
||||
Meta: mergeStringMap(code.Meta, request.Meta),
|
||||
ClaimedAt: now,
|
||||
}
|
||||
s.claimsByKey[lookupKey] = cloneClaimResult(result)
|
||||
return cloneClaimResult(result), nil
|
||||
}
|
||||
|
||||
func (s *MemoryStore) RollbackClaim(ctx context.Context, result ClaimResult) error {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if s == nil {
|
||||
return ErrStoreRequired
|
||||
}
|
||||
if result.Code == "" || result.AccountID == "" || result.IdempotencyKey == "" {
|
||||
return nil
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
request := ClaimRequest{Code: result.Code, AccountID: result.AccountID, IdempotencyKey: result.IdempotencyKey}
|
||||
lookupKey := claimLookupKey(request)
|
||||
existing, ok := s.claimsByKey[lookupKey]
|
||||
if !ok || existing.ClaimID != result.ClaimID {
|
||||
return nil
|
||||
}
|
||||
delete(s.claimsByKey, lookupKey)
|
||||
accountKey := result.Code + "\x00" + result.AccountID
|
||||
if s.claimsByAccount[accountKey] <= 1 {
|
||||
delete(s.claimsByAccount, accountKey)
|
||||
} else {
|
||||
s.claimsByAccount[accountKey]--
|
||||
}
|
||||
if s.uses[result.Code] <= 1 {
|
||||
delete(s.uses, result.Code)
|
||||
} else {
|
||||
s.uses[result.Code]--
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *MemoryStore) Snapshot(ctx context.Context) (Snapshot, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return Snapshot{}, err
|
||||
}
|
||||
if s == nil {
|
||||
return Snapshot{}, ErrStoreRequired
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return Snapshot{
|
||||
Codes: len(s.codes),
|
||||
Claims: len(s.claimsByKey),
|
||||
Uses: cloneIntMap(s.uses),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func normalizeCode(code Code) Code {
|
||||
code.Code = strings.TrimSpace(code.Code)
|
||||
code.Campaign = strings.TrimSpace(code.Campaign)
|
||||
code.RewardRef = strings.TrimSpace(code.RewardRef)
|
||||
code.StartsAt = normalizeTime(code.StartsAt)
|
||||
code.EndsAt = normalizeTime(code.EndsAt)
|
||||
code.Meta = normalizeStringMap(code.Meta)
|
||||
return code
|
||||
}
|
||||
|
||||
func normClaimReq(request ClaimRequest) ClaimRequest {
|
||||
request.Code = strings.TrimSpace(request.Code)
|
||||
request.AccountID = strings.TrimSpace(request.AccountID)
|
||||
request.ShardID = strings.TrimSpace(request.ShardID)
|
||||
request.Source = strings.TrimSpace(request.Source)
|
||||
request.IdempotencyKey = strings.TrimSpace(request.IdempotencyKey)
|
||||
request.Meta = normalizeStringMap(request.Meta)
|
||||
return request
|
||||
}
|
||||
|
||||
func codeActive(code Code, now time.Time) bool {
|
||||
if code.Disabled {
|
||||
return false
|
||||
}
|
||||
if !code.StartsAt.IsZero() && now.Before(code.StartsAt) {
|
||||
return false
|
||||
}
|
||||
if !code.EndsAt.IsZero() && now.After(code.EndsAt) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func IdempotencyKey(code, accountID string) string {
|
||||
code = strings.TrimSpace(code)
|
||||
accountID = strings.TrimSpace(accountID)
|
||||
if code == "" || accountID == "" {
|
||||
return ""
|
||||
}
|
||||
return strings.Join([]string{"redeem", "v1", encodeEventKeyPart(code), encodeEventKeyPart(accountID)}, ":")
|
||||
}
|
||||
|
||||
func ClaimID(code, accountID, key string) string {
|
||||
seed := strings.Join([]string{strings.TrimSpace(code), strings.TrimSpace(accountID), strings.TrimSpace(key)}, "\x00")
|
||||
sum := sha256.Sum256([]byte(seed))
|
||||
return hex.EncodeToString(sum[:16])
|
||||
}
|
||||
|
||||
func claimLookupKey(request ClaimRequest) string {
|
||||
return strings.TrimSpace(request.Code) + "\x00" + strings.TrimSpace(request.AccountID) + "\x00" + strings.TrimSpace(request.IdempotencyKey)
|
||||
}
|
||||
|
||||
func claimReplayConflict(existing ClaimResult, request ClaimRequest) bool {
|
||||
if request.Code != "" && existing.Code != request.Code {
|
||||
return true
|
||||
}
|
||||
if request.AccountID != "" && existing.AccountID != request.AccountID {
|
||||
return true
|
||||
}
|
||||
if request.ShardID != "" && existing.ShardID != request.ShardID {
|
||||
return true
|
||||
}
|
||||
if request.Source != "" && existing.Source != request.Source {
|
||||
return true
|
||||
}
|
||||
if len(request.Meta) > 0 {
|
||||
for key, value := range request.Meta {
|
||||
if key == "admin_receipt_id" {
|
||||
continue
|
||||
}
|
||||
if existing.Meta[key] != value {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func mergeCommandParams(params map[string]any, request ClaimRequest) map[string]any {
|
||||
out := make(map[string]any, len(params)+4)
|
||||
for key, value := range params {
|
||||
out[key] = value
|
||||
}
|
||||
out["code"] = request.Code
|
||||
out["account_id"] = request.AccountID
|
||||
out["shard_id"] = request.ShardID
|
||||
out["idempotency_key"] = request.IdempotencyKey
|
||||
return out
|
||||
}
|
||||
|
||||
func firstNonEmpty(values ...string) string {
|
||||
for _, value := range values {
|
||||
value = strings.TrimSpace(value)
|
||||
if value != "" {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func normalizeTime(value time.Time) time.Time {
|
||||
if value.IsZero() {
|
||||
return time.Time{}
|
||||
}
|
||||
return value.UTC()
|
||||
}
|
||||
|
||||
func normalizeStringMap(values map[string]string) map[string]string {
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
}
|
||||
out := make(map[string]string, len(values))
|
||||
for key, value := range values {
|
||||
key = strings.TrimSpace(key)
|
||||
if key == "" {
|
||||
continue
|
||||
}
|
||||
out[key] = strings.TrimSpace(value)
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return nil
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func mergeStringMap(base map[string]string, overlays ...map[string]string) map[string]string {
|
||||
out := cloneStringMap(base)
|
||||
for _, overlay := range overlays {
|
||||
for key, value := range overlay {
|
||||
if out == nil {
|
||||
out = make(map[string]string)
|
||||
}
|
||||
out[key] = value
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func cloneCode(code Code) Code {
|
||||
code.Meta = cloneStringMap(code.Meta)
|
||||
return code
|
||||
}
|
||||
|
||||
func cloneClaimResult(result ClaimResult) ClaimResult {
|
||||
result.Meta = cloneStringMap(result.Meta)
|
||||
return result
|
||||
}
|
||||
|
||||
func cloneStringMap(values map[string]string) map[string]string {
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
}
|
||||
out := make(map[string]string, len(values))
|
||||
for key, value := range values {
|
||||
out[key] = value
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func cloneIntMap(values map[string]int) map[string]int {
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
}
|
||||
out := make(map[string]int, len(values))
|
||||
for key, value := range values {
|
||||
out[key] = value
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func ctxErr(ctx context.Context) error {
|
||||
if ctx == nil {
|
||||
return nil
|
||||
}
|
||||
return ctx.Err()
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
package redeem
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
platformdb "longheng.io/server/internal/platform/db"
|
||||
)
|
||||
|
||||
type StateStore interface {
|
||||
Load(context.Context) (State, bool, error)
|
||||
Save(context.Context, State) error
|
||||
Close() error
|
||||
}
|
||||
|
||||
type State struct {
|
||||
Codes []Code `json:"codes,omitempty"`
|
||||
Claims []ClaimResult `json:"claims,omitempty"`
|
||||
Uses map[string]int `json:"uses,omitempty"`
|
||||
}
|
||||
|
||||
type PersistentStore struct {
|
||||
mu sync.Mutex
|
||||
// saveMu 串行化完整快照保存,避免慢后端把旧快照写回覆盖新状态。
|
||||
saveMu sync.Mutex
|
||||
memory *MemoryStore
|
||||
store StateStore
|
||||
version uint64
|
||||
}
|
||||
|
||||
func NewPersistentStore(ctx context.Context, store StateStore) (*PersistentStore, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if store == nil {
|
||||
return nil, ErrStoreRequired
|
||||
}
|
||||
memory := NewMemoryStore()
|
||||
if state, ok, err := store.Load(ctx); err != nil {
|
||||
return nil, err
|
||||
} else if ok {
|
||||
memory.importState(state)
|
||||
}
|
||||
return &PersistentStore{memory: memory, store: store}, nil
|
||||
}
|
||||
|
||||
func (s *PersistentStore) PutCode(ctx context.Context, code Code) (Code, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return Code{}, err
|
||||
}
|
||||
if err := s.requireWritable(); err != nil {
|
||||
return Code{}, err
|
||||
}
|
||||
s.saveMu.Lock()
|
||||
s.mu.Lock()
|
||||
before := s.memory.exportState()
|
||||
result, err := s.memory.PutCode(ctx, code)
|
||||
if err != nil {
|
||||
s.mu.Unlock()
|
||||
s.saveMu.Unlock()
|
||||
return result, err
|
||||
}
|
||||
after := s.memory.exportState()
|
||||
s.version++
|
||||
version := s.version
|
||||
s.mu.Unlock()
|
||||
return result, s.persistAfterUnlock(ctx, before, after, version)
|
||||
}
|
||||
|
||||
func (s *PersistentStore) Claim(ctx context.Context, request ClaimRequest, now time.Time) (ClaimResult, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return ClaimResult{}, err
|
||||
}
|
||||
if err := s.requireWritable(); err != nil {
|
||||
return ClaimResult{}, err
|
||||
}
|
||||
s.saveMu.Lock()
|
||||
s.mu.Lock()
|
||||
before := s.memory.exportState()
|
||||
result, err := s.memory.Claim(ctx, request, now)
|
||||
if err != nil || result.Duplicate {
|
||||
s.mu.Unlock()
|
||||
s.saveMu.Unlock()
|
||||
return result, err
|
||||
}
|
||||
after := s.memory.exportState()
|
||||
s.version++
|
||||
version := s.version
|
||||
s.mu.Unlock()
|
||||
return result, s.persistAfterUnlock(ctx, before, after, version)
|
||||
}
|
||||
|
||||
func (s *PersistentStore) RollbackClaim(ctx context.Context, result ClaimResult) error {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if s == nil || s.memory == nil || s.store == nil {
|
||||
return ErrStoreRequired
|
||||
}
|
||||
s.saveMu.Lock()
|
||||
s.mu.Lock()
|
||||
before := s.memory.exportState()
|
||||
if err := s.memory.RollbackClaim(ctx, result); err != nil {
|
||||
s.mu.Unlock()
|
||||
s.saveMu.Unlock()
|
||||
return err
|
||||
}
|
||||
after := s.memory.exportState()
|
||||
s.version++
|
||||
version := s.version
|
||||
s.mu.Unlock()
|
||||
return s.persistAfterUnlock(ctx, before, after, version)
|
||||
}
|
||||
|
||||
func (s *PersistentStore) Snapshot(ctx context.Context) (Snapshot, error) {
|
||||
if s == nil || s.memory == nil {
|
||||
return Snapshot{}, ErrStoreRequired
|
||||
}
|
||||
return s.memory.Snapshot(ctx)
|
||||
}
|
||||
|
||||
func (s *PersistentStore) Close() error {
|
||||
if s == nil || s.store == nil {
|
||||
return nil
|
||||
}
|
||||
s.saveMu.Lock()
|
||||
defer s.saveMu.Unlock()
|
||||
return s.store.Close()
|
||||
}
|
||||
|
||||
func (s *PersistentStore) requireWritable() error {
|
||||
if s == nil || s.memory == nil || s.store == nil {
|
||||
return ErrStoreRequired
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *PersistentStore) persistAfterUnlock(ctx context.Context, before, after State, version uint64) error {
|
||||
if s == nil || s.memory == nil || s.store == nil {
|
||||
return ErrStoreRequired
|
||||
}
|
||||
defer s.saveMu.Unlock()
|
||||
// 礼包码扣次属于关键权益,仍需同步 durable;慢 I/O 不能占住内存状态锁。
|
||||
if saveErr := s.store.Save(ctx, after); saveErr != nil {
|
||||
s.mu.Lock()
|
||||
// 只回滚发起本次保存的版本,避免失败的旧保存覆盖后续成功领取或补码。
|
||||
if s.version == version {
|
||||
s.memory.importState(before)
|
||||
s.version++
|
||||
}
|
||||
s.mu.Unlock()
|
||||
return saveErr
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type JSONFileStateStore struct {
|
||||
Path string
|
||||
}
|
||||
|
||||
func NewJSONFileStateStore(path string) *JSONFileStateStore {
|
||||
return &JSONFileStateStore{Path: path}
|
||||
}
|
||||
|
||||
func (s *JSONFileStateStore) Load(ctx context.Context) (State, bool, error) {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return State{}, false, err
|
||||
}
|
||||
if s == nil || s.Path == "" {
|
||||
return State{}, false, ErrStoreRequired
|
||||
}
|
||||
data, err := os.ReadFile(s.Path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return State{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return State{}, false, err
|
||||
}
|
||||
var state State
|
||||
if err := json.Unmarshal(data, &state); err != nil {
|
||||
return State{}, false, err
|
||||
}
|
||||
return state, true, nil
|
||||
}
|
||||
|
||||
func (s *JSONFileStateStore) Save(ctx context.Context, state State) error {
|
||||
if err := ctxErr(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if s == nil || s.Path == "" {
|
||||
return ErrStoreRequired
|
||||
}
|
||||
data, err := json.MarshalIndent(state, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return platformdb.WriteFileAtomically(ctx, s.Path, data, 0o600)
|
||||
}
|
||||
|
||||
func (s *JSONFileStateStore) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *MemoryStore) exportState() State {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
codes := make([]Code, 0, len(s.codes))
|
||||
for _, code := range s.codes {
|
||||
codes = append(codes, cloneCode(code))
|
||||
}
|
||||
sort.Slice(codes, func(i, j int) bool { return codes[i].Code < codes[j].Code })
|
||||
claims := make([]ClaimResult, 0, len(s.claimsByKey))
|
||||
for _, claim := range s.claimsByKey {
|
||||
claim = cloneClaimResult(claim)
|
||||
claim.Duplicate = false
|
||||
claims = append(claims, claim)
|
||||
}
|
||||
sort.Slice(claims, func(i, j int) bool {
|
||||
if claims[i].Code != claims[j].Code {
|
||||
return claims[i].Code < claims[j].Code
|
||||
}
|
||||
if claims[i].AccountID != claims[j].AccountID {
|
||||
return claims[i].AccountID < claims[j].AccountID
|
||||
}
|
||||
return claims[i].IdempotencyKey < claims[j].IdempotencyKey
|
||||
})
|
||||
return State{Codes: codes, Claims: claims, Uses: cloneIntMap(s.uses)}
|
||||
}
|
||||
|
||||
func (s *MemoryStore) importState(state State) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.codes = make(map[string]Code, len(state.Codes))
|
||||
s.claimsByKey = make(map[string]ClaimResult, len(state.Claims))
|
||||
s.claimsByAccount = make(map[string]int, len(state.Claims))
|
||||
s.uses = cloneIntMap(state.Uses)
|
||||
if s.uses == nil {
|
||||
s.uses = make(map[string]int)
|
||||
}
|
||||
replayedUses := make(map[string]int)
|
||||
for _, code := range state.Codes {
|
||||
code = normalizeCode(code)
|
||||
if code.Code != "" {
|
||||
s.codes[code.Code] = cloneCode(code)
|
||||
}
|
||||
}
|
||||
for _, claim := range state.Claims {
|
||||
claim = cloneClaimResult(claim)
|
||||
claim.Code = strings.TrimSpace(claim.Code)
|
||||
claim.AccountID = strings.TrimSpace(claim.AccountID)
|
||||
claim.IdempotencyKey = strings.TrimSpace(claim.IdempotencyKey)
|
||||
if claim.Code == "" || claim.AccountID == "" || claim.IdempotencyKey == "" {
|
||||
continue
|
||||
}
|
||||
claim.Duplicate = false
|
||||
request := ClaimRequest{Code: claim.Code, AccountID: claim.AccountID, IdempotencyKey: claim.IdempotencyKey}
|
||||
s.claimsByKey[claimLookupKey(request)] = claim
|
||||
s.claimsByAccount[claim.Code+"\x00"+claim.AccountID]++
|
||||
replayedUses[claim.Code]++
|
||||
}
|
||||
for code, uses := range replayedUses {
|
||||
if uses > s.uses[code] {
|
||||
s.uses[code] = uses
|
||||
}
|
||||
}
|
||||
for _, claim := range state.Claims {
|
||||
if claim.Uses > s.uses[strings.TrimSpace(claim.Code)] {
|
||||
s.uses[strings.TrimSpace(claim.Code)] = claim.Uses
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user