store.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package captcha
  2. import (
  3. "container/list"
  4. "sync"
  5. "time"
  6. )
  7. // expValue stores timestamp and id of captchas. It is used in a list inside
  8. // store for indexing generated captchas by timestamp to enable garbage
  9. // collection of expired captchas.
  10. type expValue struct {
  11. timestamp int64
  12. id string
  13. }
  14. // store is an internal store for captcha ids and their values.
  15. type store struct {
  16. mu sync.RWMutex
  17. ids map[string][]byte
  18. exp *list.List
  19. // Number of items stored after last collection.
  20. numStored int
  21. // Number of saved items that triggers collection.
  22. collectNum int
  23. // Expiration time of captchas.
  24. expiration int64
  25. }
  26. // newStore initializes and returns a new store.
  27. func newStore(collectNum int, expiration int64) *store {
  28. s := new(store)
  29. s.ids = make(map[string][]byte)
  30. s.exp = list.New()
  31. s.collectNum = collectNum
  32. s.expiration = expiration
  33. return s
  34. }
  35. // saveCaptcha saves the captcha id and the corresponding digits.
  36. func (s *store) saveCaptcha(id string, digits []byte) {
  37. s.mu.Lock()
  38. defer s.mu.Unlock()
  39. s.ids[id] = digits
  40. s.exp.PushBack(expValue{time.Seconds(), id})
  41. s.numStored++
  42. if s.numStored > s.collectNum {
  43. go s.collect()
  44. s.numStored = 0
  45. }
  46. }
  47. // getDigits returns the digits for the given id.
  48. func (s *store) getDigits(id string) (digits []byte) {
  49. s.mu.RLock()
  50. defer s.mu.RUnlock()
  51. digits, _ = s.ids[id]
  52. return
  53. }
  54. // getDigitsClear returns the digits for the given id, and removes them from
  55. // the store.
  56. func (s *store) getDigitsClear(id string) (digits []byte) {
  57. s.mu.Lock()
  58. defer s.mu.Unlock()
  59. digits, ok := s.ids[id]
  60. if !ok {
  61. return
  62. }
  63. s.ids[id] = nil, false
  64. // XXX(dchest) Index (s.exp) will be cleaned when collecting expired
  65. // captchas. Can't clean it here, because we don't store reference to
  66. // expValue in the map. Maybe store it?
  67. return
  68. }
  69. // collect deletes expired captchas from the store.
  70. func (s *store) collect() {
  71. now := time.Seconds()
  72. s.mu.Lock()
  73. defer s.mu.Unlock()
  74. for e := s.exp.Front(); e != nil; e = e.Next() {
  75. ev, ok := e.Value.(expValue)
  76. if !ok {
  77. return
  78. }
  79. if ev.timestamp+s.expiration < now {
  80. s.ids[ev.id] = nil, false
  81. s.exp.Remove(e)
  82. } else {
  83. return
  84. }
  85. }
  86. }