session_manager.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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. // AddSession adds a new session to the pool, ensuring only one session exists
  64. // for a given screen name. If a session with the same screen name is already
  65. // active, the call blocks until the active session is terminated by
  66. // [InMemorySessionManager.RemoveSession] or the context is canceled. When
  67. // concurrent calls are made for the same screen name, only one call succeeds
  68. // and the others return an error.
  69. func (s *InMemorySessionManager) AddSession(ctx context.Context, screenName DisplayScreenName) (*Session, error) {
  70. s.mapMutex.Lock()
  71. active := s.findRec(screenName.IdentScreenName())
  72. if active != nil {
  73. // there's an active session that needs to be removed. don't hold the
  74. // lock while we wait.
  75. s.mapMutex.Unlock()
  76. // signal to callers that this session has to go
  77. active.sess.Close()
  78. select {
  79. case <-active.removed: // wait for RemoveSession to be called
  80. case <-ctx.Done():
  81. return nil, fmt.Errorf("waiting for previous session to terminate: %w", ctx.Err())
  82. }
  83. // the session has been removed, let's try to replace it
  84. s.mapMutex.Lock()
  85. }
  86. defer s.mapMutex.Unlock()
  87. // make sure a concurrent call didn't already add a session
  88. if active != nil && s.findRec(screenName.IdentScreenName()) != nil {
  89. return nil, errSessConflict
  90. }
  91. sess := NewSession()
  92. sess.SetIdentScreenName(screenName.IdentScreenName())
  93. sess.SetDisplayScreenName(screenName)
  94. s.store[sess.IdentScreenName()] = &sessionSlot{
  95. sess: sess,
  96. removed: make(chan bool),
  97. }
  98. return sess, nil
  99. }
  100. func (s *InMemorySessionManager) findRec(identScreenName IdentScreenName) *sessionSlot {
  101. for _, rec := range s.store {
  102. if identScreenName == rec.sess.IdentScreenName() {
  103. return rec
  104. }
  105. }
  106. return nil
  107. }
  108. // RemoveSession takes a session out of the session pool.
  109. func (s *InMemorySessionManager) RemoveSession(sess *Session) {
  110. s.mapMutex.Lock()
  111. defer s.mapMutex.Unlock()
  112. if rec, ok := s.store[sess.IdentScreenName()]; ok && rec.sess == sess {
  113. delete(s.store, sess.IdentScreenName())
  114. close(rec.removed)
  115. }
  116. }
  117. // RetrieveSession finds a session with a matching sessionID. Returns nil if
  118. // session is not found.
  119. func (s *InMemorySessionManager) RetrieveSession(screenName IdentScreenName) *Session {
  120. s.mapMutex.RLock()
  121. defer s.mapMutex.RUnlock()
  122. if rec, ok := s.store[screenName]; ok {
  123. return rec.sess
  124. }
  125. return nil
  126. }
  127. func (s *InMemorySessionManager) retrieveByScreenNames(screenNames []IdentScreenName) []*Session {
  128. s.mapMutex.RLock()
  129. defer s.mapMutex.RUnlock()
  130. var ret []*Session
  131. for _, sn := range screenNames {
  132. for _, rec := range s.store {
  133. if sn == rec.sess.IdentScreenName() {
  134. ret = append(ret, rec.sess)
  135. }
  136. }
  137. }
  138. return ret
  139. }
  140. // Empty returns true if the session pool contains 0 sessions.
  141. func (s *InMemorySessionManager) Empty() bool {
  142. s.mapMutex.RLock()
  143. defer s.mapMutex.RUnlock()
  144. return len(s.store) == 0
  145. }
  146. // AllSessions returns all sessions in the session pool.
  147. func (s *InMemorySessionManager) AllSessions() []*Session {
  148. s.mapMutex.RLock()
  149. defer s.mapMutex.RUnlock()
  150. var sessions []*Session
  151. for _, rec := range s.store {
  152. sessions = append(sessions, rec.sess)
  153. }
  154. return sessions
  155. }
  156. // NewInMemoryChatSessionManager creates a new instance of
  157. // InMemoryChatSessionManager.
  158. func NewInMemoryChatSessionManager(logger *slog.Logger) *InMemoryChatSessionManager {
  159. return &InMemoryChatSessionManager{
  160. store: make(map[string]*InMemorySessionManager),
  161. logger: logger,
  162. }
  163. }
  164. // InMemoryChatSessionManager manages chat sessions for multiple chat rooms
  165. // stored in memory. It provides thread-safe operations to add, remove, and
  166. // manipulate sessions as well as relay messages to participants.
  167. type InMemoryChatSessionManager struct {
  168. logger *slog.Logger
  169. mapMutex sync.RWMutex
  170. store map[string]*InMemorySessionManager
  171. }
  172. // AddSession adds a user to a chat room. If screenName already exists, the old
  173. // session is replaced by a new one.
  174. func (s *InMemoryChatSessionManager) AddSession(ctx context.Context, chatCookie string, screenName DisplayScreenName) (*Session, error) {
  175. s.mapMutex.Lock()
  176. if _, ok := s.store[chatCookie]; !ok {
  177. s.store[chatCookie] = NewInMemorySessionManager(s.logger)
  178. }
  179. sessionManager := s.store[chatCookie]
  180. s.mapMutex.Unlock()
  181. ctx, cancel := context.WithTimeout(ctx, time.Second*5)
  182. defer cancel()
  183. sess, err := sessionManager.AddSession(ctx, screenName)
  184. if err != nil {
  185. return nil, fmt.Errorf("AddSession: %w", err)
  186. }
  187. sess.SetChatRoomCookie(chatCookie)
  188. s.mapMutex.Lock()
  189. defer s.mapMutex.Unlock()
  190. // at this point it's guaranteed that the prior chat session and corresponding
  191. // session manager (if the room count dropped to 0) were removed.
  192. //
  193. // - SessionManager.RemoveSession() was called because that unlocks
  194. // SessionManager.AddSession(), which unblocks ChatSessionManager.AddSession()
  195. // - ChatSessionManager.RemoveSession() must call room deletion routine before
  196. // releasing mapMutex
  197. //
  198. // now restore the chat session manager, which may have been deleted by the
  199. // call to RemoveSession().
  200. if _, ok := s.store[chatCookie]; !ok {
  201. s.store[chatCookie] = sessionManager
  202. }
  203. return sess, nil
  204. }
  205. // RemoveSession removes a user session from a chat room. It panics if you
  206. // attempt to remove the session twice.
  207. func (s *InMemoryChatSessionManager) RemoveSession(sess *Session) {
  208. s.mapMutex.Lock()
  209. defer s.mapMutex.Unlock()
  210. sessionManager, ok := s.store[sess.ChatRoomCookie()]
  211. if !ok {
  212. panic("attempting to remove a session after its room has been deleted")
  213. }
  214. sessionManager.RemoveSession(sess)
  215. if sessionManager.Empty() {
  216. delete(s.store, sess.ChatRoomCookie())
  217. }
  218. }
  219. // RemoveUserFromAllChats removes a user's session from all chat rooms.
  220. func (s *InMemoryChatSessionManager) RemoveUserFromAllChats(user IdentScreenName) {
  221. s.mapMutex.Lock()
  222. defer s.mapMutex.Unlock()
  223. for _, sessionManager := range s.store {
  224. userSess := sessionManager.RetrieveSession(user)
  225. if userSess != nil {
  226. userSess.Close()
  227. sessionManager.RemoveSession(userSess)
  228. }
  229. }
  230. }
  231. // AllSessions returns all chat room participants. Returns
  232. // ErrChatRoomNotFound if the room does not exist.
  233. func (s *InMemoryChatSessionManager) AllSessions(cookie string) []*Session {
  234. s.mapMutex.RLock()
  235. defer s.mapMutex.RUnlock()
  236. sessionManager, ok := s.store[cookie]
  237. if !ok {
  238. s.logger.Debug("trying to get sessions for non-existent room", "cookie", cookie)
  239. return nil
  240. }
  241. return sessionManager.AllSessions()
  242. }
  243. // RelayToAllExcept sends a message to all chat room participants except for
  244. // the participant with a particular screen name. Returns ErrChatRoomNotFound
  245. // if the room does not exist for cookie.
  246. func (s *InMemoryChatSessionManager) RelayToAllExcept(ctx context.Context, cookie string, except IdentScreenName, msg wire.SNACMessage) {
  247. s.mapMutex.RLock()
  248. defer s.mapMutex.RUnlock()
  249. sessionManager, ok := s.store[cookie]
  250. if !ok {
  251. s.logger.Error("trying to relay message to all for non-existent room", "cookie", cookie)
  252. return
  253. }
  254. for _, sess := range sessionManager.AllSessions() {
  255. if sess.IdentScreenName() == except {
  256. continue
  257. }
  258. sessionManager.maybeRelayMessage(ctx, msg, sess)
  259. }
  260. }
  261. // RelayToScreenName sends a message to a chat room user. Returns
  262. // ErrChatRoomNotFound if the room does not exist for cookie.
  263. func (s *InMemoryChatSessionManager) RelayToScreenName(ctx context.Context, cookie string, recipient IdentScreenName, msg wire.SNACMessage) {
  264. s.mapMutex.RLock()
  265. defer s.mapMutex.RUnlock()
  266. sessionManager, ok := s.store[cookie]
  267. if !ok {
  268. s.logger.Error("trying to relay message to screen name for non-existent room", "cookie", cookie)
  269. return
  270. }
  271. sessionManager.RelayToScreenName(ctx, recipient, msg)
  272. }