agents.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package simple
  2. import (
  3. "sync"
  4. cerr "github.com/mhaya/error"
  5. cfacade "github.com/mhaya/facade"
  6. clog "github.com/mhaya/logger"
  7. )
  8. var (
  9. lock = &sync.RWMutex{}
  10. sidAgentMap = make(map[cfacade.SID]*Agent) // sid -> Agent
  11. uidMap = make(map[cfacade.UID]cfacade.SID) // uid -> sid
  12. )
  13. func BindSID(agent *Agent) {
  14. lock.Lock()
  15. defer lock.Unlock()
  16. sidAgentMap[agent.SID()] = agent
  17. }
  18. func BindUID(sid cfacade.SID, uid cfacade.UID) error {
  19. if sid == "" {
  20. return cerr.Errorf("[sid = %s] less than 1.", sid)
  21. }
  22. if uid < 1 {
  23. return cerr.Errorf("[uid = %d] less than 1.", uid)
  24. }
  25. lock.Lock()
  26. defer lock.Unlock()
  27. agent, found := sidAgentMap[sid]
  28. if !found {
  29. return cerr.Errorf("[sid = %s] does not exist.", sid)
  30. }
  31. if agent.UID() > 0 && agent.UID() == uid {
  32. return cerr.Errorf("[uid = %d] has already bound.", agent.UID())
  33. }
  34. agent.session.Uid = uid
  35. uidMap[uid] = sid
  36. return nil
  37. }
  38. func Unbind(sid cfacade.SID) {
  39. lock.Lock()
  40. defer lock.Unlock()
  41. agent, found := sidAgentMap[sid]
  42. if !found {
  43. return
  44. }
  45. delete(sidAgentMap, sid)
  46. delete(uidMap, agent.UID())
  47. sidCount := len(sidAgentMap)
  48. uidCount := len(uidMap)
  49. if sidCount == 0 || uidCount == 0 {
  50. clog.Infof("Unbind agent sid = %s, sidCount = %d, uidCount = %d", sid, sidCount, uidCount)
  51. }
  52. }
  53. func GetAgent(sid cfacade.SID) (*Agent, bool) {
  54. lock.Lock()
  55. defer lock.Unlock()
  56. agent, found := sidAgentMap[sid]
  57. return agent, found
  58. }
  59. func GetAgentWithUID(uid cfacade.UID) (*Agent, bool) {
  60. if uid < 1 {
  61. return nil, false
  62. }
  63. lock.Lock()
  64. defer lock.Unlock()
  65. sid, found := uidMap[uid]
  66. if !found {
  67. return nil, false
  68. }
  69. agent, found := sidAgentMap[sid]
  70. return agent, found
  71. }
  72. func ForeachAgent(fn func(a *Agent)) {
  73. for _, agent := range sidAgentMap {
  74. fn(agent)
  75. }
  76. }
  77. func Count() int {
  78. lock.RLock()
  79. defer lock.RUnlock()
  80. return len(sidAgentMap)
  81. }