session_manager.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. package state
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "log/slog"
  7. "sync"
  8. "time"
  9. "github.com/mk6i/retro-aim-server/wire"
  10. )
  11. type sessionSlot struct {
  12. sess *Session
  13. removed chan bool
  14. }
  15. var errSessConflict = errors.New("session conflict: another session was created concurrently for this user")
  16. // InMemorySessionManager handles the lifecycle of a user session and provides
  17. // synchronized message relay between sessions in the session pool. An
  18. // InMemorySessionManager is safe for concurrent use by multiple goroutines.
  19. type InMemorySessionManager struct {
  20. store map[IdentScreenName]*sessionSlot
  21. mapMutex sync.RWMutex
  22. logger *slog.Logger
  23. }
  24. // NewInMemorySessionManager creates a new instance of InMemorySessionManager.
  25. func NewInMemorySessionManager(logger *slog.Logger) *InMemorySessionManager {
  26. return &InMemorySessionManager{
  27. logger: logger,
  28. store: make(map[IdentScreenName]*sessionSlot),
  29. }
  30. }
  31. // RelayToAll relays a message to all sessions in the session pool.
  32. func (s *InMemorySessionManager) RelayToAll(ctx context.Context, msg wire.SNACMessage) {
  33. s.mapMutex.RLock()
  34. defer s.mapMutex.RUnlock()
  35. for _, rec := range s.store {
  36. s.maybeRelayMessage(ctx, msg, rec.sess)
  37. }
  38. }
  39. // RelayToScreenName relays a message to a session with a matching screen name.
  40. func (s *InMemorySessionManager) RelayToScreenName(ctx context.Context, screenName IdentScreenName, msg wire.SNACMessage) {
  41. sess := s.RetrieveSession(screenName)
  42. if sess == nil {
  43. s.logger.WarnContext(ctx, "can't send notification because user is not online", "recipient", screenName, "message", msg)
  44. return
  45. }
  46. s.maybeRelayMessage(ctx, msg, sess)
  47. }
  48. // RelayToScreenNames relays a message to sessions with matching screenNames.
  49. func (s *InMemorySessionManager) RelayToScreenNames(ctx context.Context, screenNames []IdentScreenName, msg wire.SNACMessage) {
  50. for _, sess := range s.retrieveByScreenNames(screenNames) {
  51. s.maybeRelayMessage(ctx, msg, sess)
  52. }
  53. }
  54. func (s *InMemorySessionManager) maybeRelayMessage(ctx context.Context, msg wire.SNACMessage, sess *Session) {
  55. switch sess.RelayMessage(msg) {
  56. case SessSendClosed:
  57. s.logger.WarnContext(ctx, "can't send notification because the user's session is closed", "recipient", sess.IdentScreenName(), "message", msg)
  58. case SessQueueFull:
  59. s.logger.WarnContext(ctx, "can't send notification because queue is full", "recipient", sess.IdentScreenName(), "message", msg)
  60. sess.Close()
  61. }
  62. }
  63. func (s *InMemorySessionManager) AddSession(ctx context.Context, screenName DisplayScreenName) (*Session, error) {
  64. s.mapMutex.Lock()
  65. active := s.findRec(screenName.IdentScreenName())
  66. if active != nil {
  67. // there's an active session that needs to be removed. don't hold the
  68. // lock while we wait.
  69. s.mapMutex.Unlock()
  70. // signal to callers that this session has to go
  71. active.sess.Close()
  72. select {
  73. case <-active.removed: // wait for RemoveSession to be called
  74. case <-ctx.Done():
  75. return nil, fmt.Errorf("waiting for previous session to terminate: %w", ctx.Err())
  76. }
  77. // the session has been removed, let's try to replace it
  78. s.mapMutex.Lock()
  79. }
  80. defer s.mapMutex.Unlock()
  81. // make sure a concurrent call didn't already add a session
  82. if active != nil && s.findRec(screenName.IdentScreenName()) != nil {
  83. return nil, errSessConflict
  84. }
  85. sess := NewSession()
  86. sess.SetIdentScreenName(screenName.IdentScreenName())
  87. sess.SetDisplayScreenName(screenName)
  88. s.store[sess.IdentScreenName()] = &sessionSlot{
  89. sess: sess,
  90. removed: make(chan bool),
  91. }
  92. return sess, nil
  93. }
  94. func (s *InMemorySessionManager) findRec(identScreenName IdentScreenName) *sessionSlot {
  95. for _, rec := range s.store {
  96. if identScreenName == rec.sess.IdentScreenName() {
  97. return rec
  98. }
  99. }
  100. return nil
  101. }
  102. // RemoveSession takes a session out of the session pool.
  103. func (s *InMemorySessionManager) RemoveSession(sess *Session) {
  104. s.mapMutex.Lock()
  105. defer s.mapMutex.Unlock()
  106. if rec, ok := s.store[sess.IdentScreenName()]; ok && rec.sess == sess {
  107. delete(s.store, sess.IdentScreenName())
  108. close(rec.removed)
  109. }
  110. }
  111. // RetrieveSession finds a session with a matching sessionID. Returns nil if
  112. // session is not found.
  113. func (s *InMemorySessionManager) RetrieveSession(screenName IdentScreenName) *Session {
  114. s.mapMutex.RLock()
  115. defer s.mapMutex.RUnlock()
  116. if rec, ok := s.store[screenName]; ok {
  117. return rec.sess
  118. }
  119. return nil
  120. }
  121. func (s *InMemorySessionManager) retrieveByScreenNames(screenNames []IdentScreenName) []*Session {
  122. s.mapMutex.RLock()
  123. defer s.mapMutex.RUnlock()
  124. var ret []*Session
  125. for _, sn := range screenNames {
  126. for _, rec := range s.store {
  127. if sn == rec.sess.IdentScreenName() {
  128. ret = append(ret, rec.sess)
  129. }
  130. }
  131. }
  132. return ret
  133. }
  134. // Empty returns true if the session pool contains 0 sessions.
  135. func (s *InMemorySessionManager) Empty() bool {
  136. s.mapMutex.RLock()
  137. defer s.mapMutex.RUnlock()
  138. return len(s.store) == 0
  139. }
  140. // AllSessions returns all sessions in the session pool.
  141. func (s *InMemorySessionManager) AllSessions() []*Session {
  142. s.mapMutex.RLock()
  143. defer s.mapMutex.RUnlock()
  144. var sessions []*Session
  145. for _, rec := range s.store {
  146. sessions = append(sessions, rec.sess)
  147. }
  148. return sessions
  149. }
  150. // NewInMemoryChatSessionManager creates a new instance of
  151. // InMemoryChatSessionManager.
  152. func NewInMemoryChatSessionManager(logger *slog.Logger) *InMemoryChatSessionManager {
  153. return &InMemoryChatSessionManager{
  154. store: make(map[string]*InMemorySessionManager),
  155. logger: logger,
  156. }
  157. }
  158. // InMemoryChatSessionManager manages chat sessions for multiple chat rooms
  159. // stored in memory. It provides thread-safe operations to add, remove, and
  160. // manipulate sessions as well as relay messages to participants.
  161. type InMemoryChatSessionManager struct {
  162. logger *slog.Logger
  163. mapMutex sync.RWMutex
  164. store map[string]*InMemorySessionManager
  165. }
  166. // AddSession adds a user to a chat room. If screenName already exists, the old
  167. // session is replaced by a new one.
  168. func (s *InMemoryChatSessionManager) AddSession(ctx context.Context, chatCookie string, screenName DisplayScreenName) (*Session, error) {
  169. s.mapMutex.Lock()
  170. if _, ok := s.store[chatCookie]; !ok {
  171. s.store[chatCookie] = NewInMemorySessionManager(s.logger)
  172. }
  173. sessionManager := s.store[chatCookie]
  174. s.mapMutex.Unlock()
  175. ctx, cancel := context.WithTimeout(ctx, time.Second*5)
  176. defer cancel()
  177. sess, err := sessionManager.AddSession(ctx, screenName)
  178. if err != nil {
  179. return nil, fmt.Errorf("AddSession: %w", err)
  180. }
  181. sess.SetChatRoomCookie(chatCookie)
  182. s.mapMutex.Lock()
  183. defer s.mapMutex.Unlock()
  184. // at this point it's guaranteed that the prior chat session and corresponding
  185. // session manager (if the room count dropped to 0) were removed.
  186. //
  187. // - SessionManager.RemoveSession() was called because that unlocks
  188. // SessionManager.AddSession(), which unblocks ChatSessionManager.AddSession()
  189. // - ChatSessionManager.RemoveSession() must call room deletion routine before
  190. // releasing mapMutex
  191. //
  192. // now restore the chat session manager, which may have been deleted by the
  193. // call to RemoveSession().
  194. if _, ok := s.store[chatCookie]; !ok {
  195. s.store[chatCookie] = sessionManager
  196. }
  197. return sess, nil
  198. }
  199. // RemoveSession removes a user session from a chat room. It panics if you
  200. // attempt to remove the session twice.
  201. func (s *InMemoryChatSessionManager) RemoveSession(sess *Session) {
  202. s.mapMutex.Lock()
  203. defer s.mapMutex.Unlock()
  204. sessionManager, ok := s.store[sess.ChatRoomCookie()]
  205. if !ok {
  206. panic("attempting to remove a session after its room has been deleted")
  207. }
  208. sessionManager.RemoveSession(sess)
  209. if sessionManager.Empty() {
  210. delete(s.store, sess.ChatRoomCookie())
  211. }
  212. }
  213. // RemoveUserFromAllChats removes a user's session from all chat rooms.
  214. func (s *InMemoryChatSessionManager) RemoveUserFromAllChats(user IdentScreenName) {
  215. s.mapMutex.Lock()
  216. defer s.mapMutex.Unlock()
  217. for _, sessionManager := range s.store {
  218. userSess := sessionManager.RetrieveSession(user)
  219. if userSess != nil {
  220. userSess.Close()
  221. sessionManager.RemoveSession(userSess)
  222. }
  223. }
  224. }
  225. // AllSessions returns all chat room participants. Returns
  226. // ErrChatRoomNotFound if the room does not exist.
  227. func (s *InMemoryChatSessionManager) AllSessions(cookie string) []*Session {
  228. s.mapMutex.RLock()
  229. defer s.mapMutex.RUnlock()
  230. sessionManager, ok := s.store[cookie]
  231. if !ok {
  232. s.logger.Debug("trying to get sessions for non-existent room", "cookie", cookie)
  233. return nil
  234. }
  235. return sessionManager.AllSessions()
  236. }
  237. // RelayToAllExcept sends a message to all chat room participants except for
  238. // the participant with a particular screen name. Returns ErrChatRoomNotFound
  239. // if the room does not exist for cookie.
  240. func (s *InMemoryChatSessionManager) RelayToAllExcept(ctx context.Context, cookie string, except IdentScreenName, msg wire.SNACMessage) {
  241. s.mapMutex.RLock()
  242. defer s.mapMutex.RUnlock()
  243. sessionManager, ok := s.store[cookie]
  244. if !ok {
  245. s.logger.Error("trying to relay message to all for non-existent room", "cookie", cookie)
  246. return
  247. }
  248. for _, sess := range sessionManager.AllSessions() {
  249. if sess.IdentScreenName() == except {
  250. continue
  251. }
  252. sessionManager.maybeRelayMessage(ctx, msg, sess)
  253. }
  254. }
  255. // RelayToScreenName sends a message to a chat room user. Returns
  256. // ErrChatRoomNotFound if the room does not exist for cookie.
  257. func (s *InMemoryChatSessionManager) RelayToScreenName(ctx context.Context, cookie string, recipient IdentScreenName, msg wire.SNACMessage) {
  258. s.mapMutex.RLock()
  259. defer s.mapMutex.RUnlock()
  260. sessionManager, ok := s.store[cookie]
  261. if !ok {
  262. s.logger.Error("trying to relay message to screen name for non-existent room", "cookie", cookie)
  263. return
  264. }
  265. sessionManager.RelayToScreenName(ctx, recipient, msg)
  266. }