Skip to content

Commit

Permalink
fix: 🐛 同じtokenを5回以上連続で落とさないように
Browse files Browse the repository at this point in the history
  • Loading branch information
ryoha000 committed Dec 6, 2024
1 parent 9fb61c6 commit 8c12353
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
20 changes: 12 additions & 8 deletions bench/payment/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,22 +81,26 @@ func (s *Server) PostPaymentsHandler(w http.ResponseWriter, r *http.Request) {
if failurePercentage > 50 {
failurePercentage = 50
}
if rand.IntN(100) > failurePercentage {
failureCount, _ := s.failureCounts.GetOrSetDefault(token, func() int { return 0 })
if rand.IntN(100) > failurePercentage || failureCount >= 4 {
// lock はここでしか触らない。lock が true の場合は idempotency key が同じリクエストが処理中の場合のみ
if p.locked.CompareAndSwap(false, true) {
s.processedPayments.Append(&processedPayment{payment: p, processedAt: time.Now()})
p.Status = s.verifier.Verify(p)
if p.Status.Err != nil {
s.errChan <- p.Status.Err
}
s.failureCounts.Delete(token)
switch rand.IntN(2) {
case 0:
writeRandomError(w)
case 1:
writeResponse(w, p.Status)
}
return
}
switch rand.IntN(2) {
case 0:
writeRandomError(w)
case 1:
writeResponse(w, p.Status)
}
return
} else {
s.failureCounts.Set(token, failureCount+1)
}

// 不安定なエラーを再現
Expand Down
2 changes: 2 additions & 0 deletions bench/payment/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ type processedPayment struct {
type Server struct {
mux *http.ServeMux
knownKeys *concurrent.SimpleMap[string, *Payment]
failureCounts *concurrent.SimpleMap[string, int]
processedPayments *concurrent.SimpleSlice[*processedPayment]
processTime time.Duration
verifier Verifier
Expand All @@ -30,6 +31,7 @@ func NewServer(verifier Verifier, processTime time.Duration, errChan chan error)
s := &Server{
mux: http.NewServeMux(),
knownKeys: concurrent.NewSimpleMap[string, *Payment](),
failureCounts: concurrent.NewSimpleMap[string, int](),
processedPayments: concurrent.NewSimpleSlice[*processedPayment](),
processTime: processTime,
verifier: verifier,
Expand Down

0 comments on commit 8c12353

Please sign in to comment.