detector.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package email
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. //FastDetector detecte speed and unique analyze
  7. type FastDetector struct {
  8. lastSec int64
  9. sameSecCnt int
  10. sameSecThreshold int
  11. overspeedCnt int
  12. overspeedThreshold int
  13. uniqueSpeed map[int64]int
  14. fastUnique int64
  15. }
  16. //NewFastDetector new
  17. func NewFastDetector(speedThreshold, overspeedThreshold int) *FastDetector {
  18. return &FastDetector{
  19. lastSec: time.Now().Unix(),
  20. sameSecCnt: 0,
  21. sameSecThreshold: speedThreshold,
  22. overspeedCnt: 0,
  23. overspeedThreshold: overspeedThreshold,
  24. uniqueSpeed: map[int64]int{},
  25. }
  26. }
  27. //String string info
  28. func (fd *FastDetector) String() string {
  29. return fmt.Sprintf("same_sec_cnt=%d,overspeed_cnt=%d,fast_unique=%d,unique_speed=%v",
  30. fd.sameSecCnt, fd.overspeedCnt, fd.fastUnique, fd.uniqueSpeed)
  31. }
  32. //Detect 快慢探查, 超限名单只能被慢速/下一个超速名单/间隔5s后空名单代替,超限名单只有在(overspeedthreshold+1) * samesecthreshold时才确定,此时返回true
  33. func (fd *FastDetector) Detect(unique int64) (fast bool) {
  34. now := time.Now().Unix()
  35. //连续n次超限
  36. if now == fd.lastSec {
  37. fd.sameSecCnt++
  38. if fd.sameSecCnt == fd.sameSecThreshold {
  39. fd.overspeedCnt++
  40. }
  41. } else {
  42. if fd.sameSecCnt < fd.sameSecThreshold || (now-fd.lastSec > 5) {
  43. fd.overspeedCnt = 0
  44. fd.fastUnique = 0
  45. fd.uniqueSpeed = map[int64]int{}
  46. }
  47. fd.sameSecCnt = 1
  48. fd.lastSec = now
  49. }
  50. //连续超限后,最先超限的unique指定为超限名单
  51. if fd.overspeedCnt == fd.overspeedThreshold && fd.sameSecCnt == fd.sameSecThreshold {
  52. fd.uniqueSpeed[unique] = 0
  53. }
  54. if (fd.overspeedCnt == fd.overspeedThreshold && fd.sameSecCnt != fd.sameSecThreshold) || (fd.overspeedCnt > fd.overspeedThreshold) {
  55. fd.uniqueSpeed[unique]++
  56. if fd.uniqueSpeed[unique] >= fd.sameSecThreshold {
  57. fast = true
  58. fd.fastUnique = unique //指定超限名单
  59. fd.uniqueSpeed = map[int64]int{}
  60. fd.overspeedCnt = 0
  61. }
  62. }
  63. return
  64. }
  65. //IsFastUnique 是否为超限名单
  66. func (fd *FastDetector) IsFastUnique(unique int64) bool {
  67. return fd.fastUnique == unique
  68. }