4
0

session_manager.go 9.2 KB

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