GraphQL API and utilities for the rpdata project
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
926 B

  1. package unknownnicks
  2. import (
  3. "sync"
  4. "github.com/globalsign/mgo/bson"
  5. )
  6. var updateMutex sync.Mutex
  7. var updateMap map[string]int
  8. // Add adds a nick as unknown.
  9. func Add(nick string) {
  10. updateMap[nick] = updateMap[nick] + 1
  11. }
  12. // BeginUpdate starts an add operation
  13. func BeginUpdate() error {
  14. updateMutex.Lock()
  15. _, err := collection.RemoveAll(bson.M{})
  16. if err != nil {
  17. updateMutex.Unlock()
  18. return err
  19. }
  20. if updateMap == nil {
  21. updateMap = make(map[string]int)
  22. }
  23. for key := range updateMap {
  24. delete(updateMap, key)
  25. }
  26. return nil
  27. }
  28. // CancelUpdate cancels an add operation
  29. func CancelUpdate() {
  30. updateMutex.Unlock()
  31. }
  32. // CommitUpdate commits an add operation to the database.
  33. func CommitUpdate() error {
  34. defer updateMutex.Unlock()
  35. for nick, score := range updateMap {
  36. _, err := collection.UpsertId(nick, bson.M{"$set": bson.M{"score": score}})
  37. if err != nil {
  38. return err
  39. }
  40. }
  41. return nil
  42. }