session_manager.go 9.7 KB

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