cocrrent.go 977 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package middleware
  2. import (
  3. "net/http"
  4. "sync"
  5. "github.com/gin-gonic/gin"
  6. "github.com/langgenius/dify-sandbox/internal/types"
  7. "github.com/langgenius/dify-sandbox/internal/utils/log"
  8. )
  9. func MaxWorker(max int) gin.HandlerFunc {
  10. log.Info("setting max workers to %d", max)
  11. sem := make(chan struct{}, max)
  12. return func(c *gin.Context) {
  13. sem <- struct{}{}
  14. defer func() {
  15. <-sem
  16. }()
  17. c.Next()
  18. }
  19. }
  20. type MaxRequestIface struct {
  21. current int
  22. lock *sync.RWMutex
  23. }
  24. func MaxRequest(max int) gin.HandlerFunc {
  25. log.Info("setting max requests to %d", max)
  26. m := &MaxRequestIface{
  27. current: 0,
  28. lock: &sync.RWMutex{},
  29. }
  30. return func(c *gin.Context) {
  31. m.lock.RLock()
  32. if m.current >= max {
  33. m.lock.RUnlock()
  34. c.JSON(http.StatusServiceUnavailable, types.ErrorResponse(-503, "Too many requests"))
  35. c.Abort()
  36. return
  37. }
  38. m.lock.RUnlock()
  39. m.lock.Lock()
  40. m.current++
  41. m.lock.Unlock()
  42. c.Next()
  43. m.lock.Lock()
  44. m.current--
  45. m.lock.Unlock()
  46. }
  47. }