session_manager.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. package state
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "log/slog"
  7. "sync"
  8. "time"
  9. "github.com/mk6i/open-oscar-server/wire"
  10. )
  11. type sessionSlot struct {
  12. session *Session
  13. removed chan bool
  14. multiSession bool
  15. }
  16. type userLock struct {
  17. sync.Mutex
  18. refCount int
  19. }
  20. // InMemorySessionManager handles the lifecycle of a user session and provides
  21. // synchronized message relay between sessions in the session pool. An
  22. // InMemorySessionManager is safe for concurrent use by multiple goroutines.
  23. type InMemorySessionManager struct {
  24. store map[IdentScreenName]*sessionSlot
  25. mapMutex sync.RWMutex
  26. userLocks map[IdentScreenName]*userLock
  27. userLocksMutex sync.Mutex
  28. logger *slog.Logger
  29. maxConcurrentSessions int
  30. }
  31. const (
  32. // DefaultMaxConcurrentSessions is the default maximum number of concurrent
  33. // sessions allowed when multi-session is enabled.
  34. DefaultMaxConcurrentSessions = 5
  35. )
  36. // ErrMaxConcurrentSessionsReached is returned when attempting to add a new
  37. // session instance but the maximum number of concurrent sessions has been
  38. // reached.
  39. var ErrMaxConcurrentSessionsReached = errors.New("maximum number of concurrent sessions reached")
  40. // NewInMemorySessionManager creates a new instance of InMemorySessionManager.
  41. func NewInMemorySessionManager(logger *slog.Logger) *InMemorySessionManager {
  42. return &InMemorySessionManager{
  43. logger: logger,
  44. store: make(map[IdentScreenName]*sessionSlot),
  45. userLocks: make(map[IdentScreenName]*userLock),
  46. maxConcurrentSessions: DefaultMaxConcurrentSessions,
  47. }
  48. }
  49. func (s *InMemorySessionManager) lockUser(sn IdentScreenName) {
  50. s.userLocksMutex.Lock()
  51. lock, ok := s.userLocks[sn]
  52. if !ok {
  53. lock = &userLock{}
  54. s.userLocks[sn] = lock
  55. }
  56. lock.refCount++
  57. s.userLocksMutex.Unlock()
  58. lock.Lock()
  59. }
  60. func (s *InMemorySessionManager) unlockUser(sn IdentScreenName) {
  61. s.userLocksMutex.Lock()
  62. defer s.userLocksMutex.Unlock()
  63. lock, ok := s.userLocks[sn]
  64. if !ok {
  65. return
  66. }
  67. lock.Unlock()
  68. lock.refCount--
  69. if lock.refCount == 0 {
  70. delete(s.userLocks, sn)
  71. }
  72. }
  73. // RelayToAll relays a message to all sessions in the session pool.
  74. func (s *InMemorySessionManager) RelayToAll(ctx context.Context, msg wire.SNACMessage) {
  75. s.mapMutex.RLock()
  76. defer s.mapMutex.RUnlock()
  77. for _, rec := range s.store {
  78. s.maybeRelayMessage(ctx, msg, rec.session)
  79. }
  80. }
  81. // RelayToScreenName relays a message to a session with a matching screen name.
  82. func (s *InMemorySessionManager) RelayToScreenName(ctx context.Context, screenName IdentScreenName, msg wire.SNACMessage) {
  83. sess := s.RetrieveSession(screenName)
  84. if sess == nil {
  85. s.logger.WarnContext(ctx, "can't send notification because user is not online", "recipient", screenName, "message", msg)
  86. return
  87. }
  88. s.maybeRelayMessage(ctx, msg, sess)
  89. }
  90. // RelayToScreenNames relays a message to sessions with matching screenNames.
  91. func (s *InMemorySessionManager) RelayToScreenNames(ctx context.Context, screenNames []IdentScreenName, msg wire.SNACMessage) {
  92. for _, sess := range s.retrieveByScreenNames(screenNames) {
  93. s.maybeRelayMessage(ctx, msg, sess)
  94. }
  95. }
  96. func (s *InMemorySessionManager) RelayToSelf(ctx context.Context, instance *SessionInstance, msg wire.SNACMessage) {
  97. switch instance.RelayMessageToInstance(msg) {
  98. case SessSendClosed:
  99. s.logger.WarnContext(ctx, "can't send notification because the user's session is closed", "recipient", instance.IdentScreenName(), "message", msg)
  100. case SessQueueFull:
  101. s.logger.WarnContext(ctx, "can't send notification because queue is full", "recipient", instance.IdentScreenName(), "message", msg)
  102. instance.CloseInstance()
  103. }
  104. }
  105. func (s *InMemorySessionManager) RelayToOtherInstances(ctx context.Context, instance *SessionInstance, msg wire.SNACMessage) {
  106. for _, inst := range instance.Session().Instances() {
  107. if instance == inst || !inst.live() {
  108. continue
  109. }
  110. switch inst.RelayMessageToInstance(msg) {
  111. case SessSendClosed:
  112. s.logger.WarnContext(ctx, "can't send notification because the user's session is closed", "recipient", instance.IdentScreenName(), "message", msg)
  113. case SessQueueFull:
  114. s.logger.WarnContext(ctx, "can't send notification because queue is full", "recipient", instance.IdentScreenName(), "message", msg)
  115. inst.CloseInstance()
  116. }
  117. }
  118. }
  119. func (s *InMemorySessionManager) RelayToScreenNameActiveOnly(ctx context.Context, screenName IdentScreenName, msg wire.SNACMessage) {
  120. sess := s.RetrieveSession(screenName)
  121. if sess == nil {
  122. s.logger.WarnContext(ctx, "can't send notification because user is not online", "recipient", screenName, "message", msg)
  123. return
  124. }
  125. s.maybeRelayMessageActiveOnly(ctx, msg, sess)
  126. }
  127. func (s *InMemorySessionManager) maybeRelayMessage(ctx context.Context, msg wire.SNACMessage, sess *Session) {
  128. for _, instance := range sess.Instances() {
  129. if !instance.live() {
  130. continue
  131. }
  132. switch instance.RelayMessageToInstance(msg) {
  133. case SessSendClosed:
  134. s.logger.WarnContext(ctx, "can't send notification because the user's session is closed", "recipient", sess.IdentScreenName(), "message", msg)
  135. case SessQueueFull:
  136. s.logger.WarnContext(ctx, "can't send notification because queue is full", "recipient", sess.IdentScreenName(), "message", msg)
  137. instance.CloseInstance()
  138. }
  139. }
  140. }
  141. func (s *InMemorySessionManager) maybeRelayMessageActiveOnly(ctx context.Context, msg wire.SNACMessage, sess *Session) {
  142. for _, instance := range sess.Instances() {
  143. if !instance.active() {
  144. continue
  145. }
  146. switch instance.RelayMessageToInstance(msg) {
  147. case SessSendClosed:
  148. s.logger.WarnContext(ctx, "can't send notification because the user's session is closed", "recipient", sess.IdentScreenName(), "message", msg)
  149. case SessQueueFull:
  150. s.logger.WarnContext(ctx, "can't send notification because queue is full", "recipient", sess.IdentScreenName(), "message", msg)
  151. instance.CloseInstance()
  152. }
  153. }
  154. }
  155. func (s *InMemorySessionManager) AddSession(ctx context.Context, screenName DisplayScreenName, doMultiSess bool) (*SessionInstance, error) {
  156. s.lockUser(screenName.IdentScreenName())
  157. defer s.unlockUser(screenName.IdentScreenName())
  158. s.mapMutex.Lock()
  159. active := s.findRec(screenName.IdentScreenName())
  160. s.mapMutex.Unlock()
  161. if active != nil {
  162. if doMultiSess {
  163. if !active.multiSession {
  164. active.session.CloseSession()
  165. return s.newSession(screenName, doMultiSess)
  166. }
  167. // Check if we've reached the maximum number of concurrent sessions
  168. if active.session.InstanceCount() >= s.maxConcurrentSessions {
  169. return nil, fmt.Errorf("%w: max instance(s) = %d", ErrMaxConcurrentSessionsReached, s.maxConcurrentSessions)
  170. }
  171. instance := active.session.AddInstance()
  172. return instance, nil
  173. } else {
  174. // signal to callers that this session group has to go
  175. active.session.CloseSession()
  176. select {
  177. case <-active.removed: // wait for RemoveSession to be called
  178. case <-ctx.Done():
  179. return nil, fmt.Errorf("waiting for previous session to terminate: %w", ctx.Err())
  180. }
  181. }
  182. }
  183. return s.newSession(screenName, doMultiSess)
  184. }
  185. func (s *InMemorySessionManager) newSession(screenName DisplayScreenName, doMultiSess bool) (*SessionInstance, error) {
  186. sess := NewSession()
  187. sess.SetIdentScreenName(screenName.IdentScreenName())
  188. sess.SetDisplayScreenName(screenName)
  189. // Create a new instance within the session group
  190. instance := sess.AddInstance()
  191. s.mapMutex.Lock()
  192. s.store[instance.IdentScreenName()] = &sessionSlot{
  193. session: sess,
  194. removed: make(chan bool),
  195. multiSession: doMultiSess,
  196. }
  197. s.mapMutex.Unlock()
  198. return instance, nil
  199. }
  200. func (s *InMemorySessionManager) findRec(identScreenName IdentScreenName) *sessionSlot {
  201. for _, rec := range s.store {
  202. if identScreenName == rec.session.IdentScreenName() {
  203. return rec
  204. }
  205. }
  206. return nil
  207. }
  208. // RemoveSession takes a session out of the session pool.
  209. func (s *InMemorySessionManager) RemoveSession(instance *SessionInstance) {
  210. s.mapMutex.Lock()
  211. defer s.mapMutex.Unlock()
  212. if rec, ok := s.store[instance.IdentScreenName()]; ok && rec.session == instance.Session() {
  213. delete(s.store, instance.IdentScreenName())
  214. close(rec.removed)
  215. }
  216. }
  217. // RetrieveSession finds a session with a matching screen name. Returns nil if
  218. // session is not found or if there are no active instances with complete signon.
  219. func (s *InMemorySessionManager) RetrieveSession(screenName IdentScreenName) *Session {
  220. s.mapMutex.RLock()
  221. defer s.mapMutex.RUnlock()
  222. if rec, ok := s.store[screenName]; ok {
  223. if rec.session.HasLiveInstances() {
  224. return rec.session
  225. }
  226. }
  227. return nil
  228. }
  229. func (s *InMemorySessionManager) retrieveByScreenNames(screenNames []IdentScreenName) []*Session {
  230. s.mapMutex.RLock()
  231. defer s.mapMutex.RUnlock()
  232. var ret []*Session
  233. for _, sn := range screenNames {
  234. for _, rec := range s.store {
  235. if sn == rec.session.IdentScreenName() {
  236. ret = append(ret, rec.session)
  237. break
  238. }
  239. }
  240. }
  241. return ret
  242. }
  243. // Empty returns true if the session pool contains 0 sessions.
  244. func (s *InMemorySessionManager) Empty() bool {
  245. s.mapMutex.RLock()
  246. defer s.mapMutex.RUnlock()
  247. return len(s.store) == 0
  248. }
  249. // AllSessions returns all sessions in the session pool.
  250. func (s *InMemorySessionManager) AllSessions() []*Session {
  251. s.mapMutex.RLock()
  252. defer s.mapMutex.RUnlock()
  253. var sessions []*Session
  254. for _, rec := range s.store {
  255. if !rec.session.HasLiveInstances() {
  256. continue
  257. }
  258. sessions = append(sessions, rec.session)
  259. }
  260. return sessions
  261. }
  262. // NewInMemoryChatSessionManager creates a new instance of
  263. // InMemoryChatSessionManager.
  264. func NewInMemoryChatSessionManager(logger *slog.Logger) *InMemoryChatSessionManager {
  265. return &InMemoryChatSessionManager{
  266. store: make(map[string]*InMemorySessionManager),
  267. logger: logger,
  268. }
  269. }
  270. // InMemoryChatSessionManager manages chat sessions for multiple chat rooms
  271. // stored in memory. It provides thread-safe operations to add, remove, and
  272. // manipulate sessions as well as relay messages to participants.
  273. type InMemoryChatSessionManager struct {
  274. logger *slog.Logger
  275. mapMutex sync.RWMutex
  276. store map[string]*InMemorySessionManager
  277. }
  278. // AddSession adds a user to a chat room. If screenName already exists, the old
  279. // session is replaced by a new one.
  280. func (s *InMemoryChatSessionManager) AddSession(ctx context.Context, chatCookie string, screenName DisplayScreenName) (*SessionInstance, error) {
  281. s.mapMutex.Lock()
  282. if _, ok := s.store[chatCookie]; !ok {
  283. s.store[chatCookie] = NewInMemorySessionManager(s.logger)
  284. }
  285. sessionManager := s.store[chatCookie]
  286. s.mapMutex.Unlock()
  287. ctx, cancel := context.WithTimeout(ctx, time.Second*5)
  288. defer cancel()
  289. sess, err := sessionManager.AddSession(ctx, screenName, false)
  290. if err != nil {
  291. return nil, fmt.Errorf("AddSession: %w", err)
  292. }
  293. sess.Session().SetChatRoomCookie(chatCookie)
  294. s.mapMutex.Lock()
  295. defer s.mapMutex.Unlock()
  296. // at this point it's guaranteed that the prior chat session and corresponding
  297. // session manager (if the room count dropped to 0) were removed.
  298. //
  299. // - SessionManager.RemoveSession() was called because that unlocks
  300. // SessionManager.AddSession(), which unblocks ChatSessionManager.AddSession()
  301. // - ChatSessionManager.RemoveSession() must call room deletion routine before
  302. // releasing mapMutex
  303. //
  304. // now restore the chat session manager, which may have been deleted by the
  305. // call to RemoveSession().
  306. if _, ok := s.store[chatCookie]; !ok {
  307. s.store[chatCookie] = sessionManager
  308. }
  309. return sess, nil
  310. }
  311. // RemoveSession removes a user session from a chat room. It panics if you
  312. // attempt to remove the session twice.
  313. func (s *InMemoryChatSessionManager) RemoveSession(instance *SessionInstance) {
  314. s.mapMutex.Lock()
  315. defer s.mapMutex.Unlock()
  316. sessionManager, ok := s.store[instance.ChatRoomCookie()]
  317. if !ok {
  318. panic("attempting to remove a session after its room has been deleted")
  319. }
  320. sessionManager.RemoveSession(instance)
  321. if sessionManager.Empty() {
  322. delete(s.store, instance.ChatRoomCookie())
  323. }
  324. }
  325. // RemoveUserFromAllChats removes a user's session from all chat rooms.
  326. func (s *InMemoryChatSessionManager) RemoveUserFromAllChats(user IdentScreenName) {
  327. s.mapMutex.Lock()
  328. defer s.mapMutex.Unlock()
  329. for _, sessionManager := range s.store {
  330. userSess := sessionManager.RetrieveSession(user)
  331. if userSess != nil {
  332. userSess.CloseSession()
  333. }
  334. }
  335. }
  336. // AllSessions returns all chat room participants. Returns
  337. // ErrChatRoomNotFound if the room does not exist.
  338. func (s *InMemoryChatSessionManager) AllSessions(cookie string) []*Session {
  339. s.mapMutex.RLock()
  340. defer s.mapMutex.RUnlock()
  341. sessionManager, ok := s.store[cookie]
  342. if !ok {
  343. s.logger.Debug("trying to get sessions for non-existent room", "cookie", cookie)
  344. return nil
  345. }
  346. return sessionManager.AllSessions()
  347. }
  348. // RelayToAllExcept sends a message to all chat room participants except for
  349. // the participant with a particular screen name. Returns ErrChatRoomNotFound
  350. // if the room does not exist for cookie.
  351. func (s *InMemoryChatSessionManager) RelayToAllExcept(ctx context.Context, cookie string, except IdentScreenName, msg wire.SNACMessage) {
  352. s.mapMutex.RLock()
  353. defer s.mapMutex.RUnlock()
  354. sessionManager, ok := s.store[cookie]
  355. if !ok {
  356. s.logger.Error("trying to relay message to all for non-existent room", "cookie", cookie)
  357. return
  358. }
  359. for _, sess := range sessionManager.AllSessions() {
  360. if sess.IdentScreenName() == except {
  361. continue
  362. }
  363. sessionManager.maybeRelayMessage(ctx, msg, sess)
  364. }
  365. }
  366. // RelayToScreenName sends a message to a chat room user. Returns
  367. // ErrChatRoomNotFound if the room does not exist for cookie.
  368. func (s *InMemoryChatSessionManager) RelayToScreenName(ctx context.Context, cookie string, recipient IdentScreenName, msg wire.SNACMessage) {
  369. s.mapMutex.RLock()
  370. defer s.mapMutex.RUnlock()
  371. sessionManager, ok := s.store[cookie]
  372. if !ok {
  373. s.logger.Error("trying to relay message to screen name for non-existent room", "cookie", cookie)
  374. return
  375. }
  376. sessionManager.RelayToScreenName(ctx, recipient, msg)
  377. }