session_manager.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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, cfg ...func(sess *Session)) (*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, cfg)
  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, cfg)
  184. }
  185. func (s *InMemorySessionManager) newSession(screenName DisplayScreenName, doMultiSess bool, cfg []func(sess *Session)) (*SessionInstance, error) {
  186. sess := NewSession()
  187. sess.SetIdentScreenName(screenName.IdentScreenName())
  188. sess.SetDisplayScreenName(screenName)
  189. for _, f := range cfg {
  190. f(sess)
  191. }
  192. // Create a new instance within the session group
  193. instance := sess.AddInstance()
  194. s.mapMutex.Lock()
  195. s.store[instance.IdentScreenName()] = &sessionSlot{
  196. session: sess,
  197. removed: make(chan bool),
  198. multiSession: doMultiSess,
  199. }
  200. s.mapMutex.Unlock()
  201. return instance, nil
  202. }
  203. func (s *InMemorySessionManager) findRec(identScreenName IdentScreenName) *sessionSlot {
  204. for _, rec := range s.store {
  205. if identScreenName == rec.session.IdentScreenName() {
  206. return rec
  207. }
  208. }
  209. return nil
  210. }
  211. // RemoveSession takes a session out of the session pool.
  212. func (s *InMemorySessionManager) RemoveSession(session *Session) {
  213. s.mapMutex.Lock()
  214. defer s.mapMutex.Unlock()
  215. if rec, ok := s.store[session.IdentScreenName()]; ok && rec.session == session {
  216. delete(s.store, session.IdentScreenName())
  217. close(rec.removed)
  218. }
  219. }
  220. // RetrieveSession finds a session with a matching screen name. Returns nil if
  221. // session is not found or if there are no active instances with complete signon.
  222. func (s *InMemorySessionManager) RetrieveSession(screenName IdentScreenName) *Session {
  223. s.mapMutex.RLock()
  224. defer s.mapMutex.RUnlock()
  225. if rec, ok := s.store[screenName]; ok {
  226. if rec.session.HasLiveInstances() {
  227. return rec.session
  228. }
  229. }
  230. return nil
  231. }
  232. func (s *InMemorySessionManager) retrieveByScreenNames(screenNames []IdentScreenName) []*Session {
  233. s.mapMutex.RLock()
  234. defer s.mapMutex.RUnlock()
  235. var ret []*Session
  236. for _, sn := range screenNames {
  237. for _, rec := range s.store {
  238. if sn == rec.session.IdentScreenName() {
  239. ret = append(ret, rec.session)
  240. break
  241. }
  242. }
  243. }
  244. return ret
  245. }
  246. // Empty returns true if the session pool contains 0 sessions.
  247. func (s *InMemorySessionManager) Empty() bool {
  248. s.mapMutex.RLock()
  249. defer s.mapMutex.RUnlock()
  250. return len(s.store) == 0
  251. }
  252. // AllSessions returns all sessions in the session pool.
  253. func (s *InMemorySessionManager) AllSessions() []*Session {
  254. s.mapMutex.RLock()
  255. defer s.mapMutex.RUnlock()
  256. var sessions []*Session
  257. for _, rec := range s.store {
  258. if !rec.session.HasLiveInstances() {
  259. continue
  260. }
  261. sessions = append(sessions, rec.session)
  262. }
  263. return sessions
  264. }
  265. // NewInMemoryChatSessionManager creates a new instance of
  266. // InMemoryChatSessionManager.
  267. func NewInMemoryChatSessionManager(logger *slog.Logger) *InMemoryChatSessionManager {
  268. return &InMemoryChatSessionManager{
  269. store: make(map[string]*InMemorySessionManager),
  270. logger: logger,
  271. }
  272. }
  273. // InMemoryChatSessionManager manages chat sessions for multiple chat rooms
  274. // stored in memory. It provides thread-safe operations to add, remove, and
  275. // manipulate sessions as well as relay messages to participants.
  276. type InMemoryChatSessionManager struct {
  277. logger *slog.Logger
  278. mapMutex sync.RWMutex
  279. store map[string]*InMemorySessionManager
  280. }
  281. // AddSession adds a user to a chat room. If screenName already exists, the old
  282. // session is replaced by a new one.
  283. func (s *InMemoryChatSessionManager) AddSession(ctx context.Context, chatCookie string, screenName DisplayScreenName, cfg ...func(sess *Session)) (*SessionInstance, error) {
  284. s.mapMutex.Lock()
  285. if _, ok := s.store[chatCookie]; !ok {
  286. s.store[chatCookie] = NewInMemorySessionManager(s.logger)
  287. }
  288. sessionManager := s.store[chatCookie]
  289. s.mapMutex.Unlock()
  290. ctx, cancel := context.WithTimeout(ctx, time.Second*5)
  291. defer cancel()
  292. sess, err := sessionManager.AddSession(ctx, screenName, false, cfg...)
  293. if err != nil {
  294. return nil, fmt.Errorf("AddSession: %w", err)
  295. }
  296. sess.Session().SetChatRoomCookie(chatCookie)
  297. s.mapMutex.Lock()
  298. defer s.mapMutex.Unlock()
  299. // at this point it's guaranteed that the prior chat session and corresponding
  300. // session manager (if the room count dropped to 0) were removed.
  301. //
  302. // - SessionManager.RemoveSession() was called because that unlocks
  303. // SessionManager.AddSession(), which unblocks ChatSessionManager.AddSession()
  304. // - ChatSessionManager.RemoveSession() must call room deletion routine before
  305. // releasing mapMutex
  306. //
  307. // now restore the chat session manager, which may have been deleted by the
  308. // call to RemoveSession().
  309. if _, ok := s.store[chatCookie]; !ok {
  310. s.store[chatCookie] = sessionManager
  311. }
  312. return sess, nil
  313. }
  314. // RemoveSession removes a user session from a chat room. It panics if you
  315. // attempt to remove the session twice.
  316. func (s *InMemoryChatSessionManager) RemoveSession(sess *Session) {
  317. s.mapMutex.Lock()
  318. defer s.mapMutex.Unlock()
  319. sessionManager, ok := s.store[sess.ChatRoomCookie()]
  320. if !ok {
  321. panic("attempting to remove a session after its room has been deleted")
  322. }
  323. sessionManager.RemoveSession(sess)
  324. if sessionManager.Empty() {
  325. delete(s.store, sess.ChatRoomCookie())
  326. }
  327. }
  328. // RemoveUserFromAllChats removes a user's session from all chat rooms.
  329. func (s *InMemoryChatSessionManager) RemoveUserFromAllChats(user IdentScreenName) {
  330. var cpy []*InMemorySessionManager
  331. // make a copy since CloseSession() may call back to InMemoryChatSessionManager
  332. // and deadlock with this call
  333. s.mapMutex.RLock()
  334. for _, sessionManager := range s.store {
  335. cpy = append(cpy, sessionManager)
  336. }
  337. s.mapMutex.RUnlock()
  338. for _, sessionManager := range cpy {
  339. userSess := sessionManager.RetrieveSession(user)
  340. if userSess != nil {
  341. userSess.CloseSession()
  342. }
  343. }
  344. }
  345. // AllSessions returns all chat room participants. Returns
  346. // ErrChatRoomNotFound if the room does not exist.
  347. func (s *InMemoryChatSessionManager) AllSessions(cookie string) []*Session {
  348. s.mapMutex.RLock()
  349. defer s.mapMutex.RUnlock()
  350. sessionManager, ok := s.store[cookie]
  351. if !ok {
  352. s.logger.Debug("trying to get sessions for non-existent room", "cookie", cookie)
  353. return nil
  354. }
  355. return sessionManager.AllSessions()
  356. }
  357. // RelayToAllExcept sends a message to all chat room participants except for
  358. // the participant with a particular screen name. Returns ErrChatRoomNotFound
  359. // if the room does not exist for cookie.
  360. func (s *InMemoryChatSessionManager) RelayToAllExcept(ctx context.Context, cookie string, except IdentScreenName, msg wire.SNACMessage) {
  361. s.mapMutex.RLock()
  362. defer s.mapMutex.RUnlock()
  363. sessionManager, ok := s.store[cookie]
  364. if !ok {
  365. s.logger.Error("trying to relay message to all for non-existent room", "cookie", cookie)
  366. return
  367. }
  368. for _, sess := range sessionManager.AllSessions() {
  369. if sess.IdentScreenName() == except {
  370. continue
  371. }
  372. sessionManager.maybeRelayMessage(ctx, msg, sess)
  373. }
  374. }
  375. // RelayToScreenName sends a message to a chat room user. Returns
  376. // ErrChatRoomNotFound if the room does not exist for cookie.
  377. func (s *InMemoryChatSessionManager) RelayToScreenName(ctx context.Context, cookie string, recipient IdentScreenName, msg wire.SNACMessage) {
  378. s.mapMutex.RLock()
  379. defer s.mapMutex.RUnlock()
  380. sessionManager, ok := s.store[cookie]
  381. if !ok {
  382. s.logger.Error("trying to relay message to screen name for non-existent room", "cookie", cookie)
  383. return
  384. }
  385. sessionManager.RelayToScreenName(ctx, recipient, msg)
  386. }