events.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. package types
  2. import (
  3. "context"
  4. "errors"
  5. "sync"
  6. "sync/atomic"
  7. "time"
  8. )
  9. // EventType defines the type of WebAPI event.
  10. type EventType string
  11. const (
  12. // Event types that can be subscribed to
  13. EventTypeBuddyList EventType = "buddylist"
  14. EventTypePresence EventType = "presence"
  15. EventTypeIM EventType = "im"
  16. EventTypeSentIM EventType = "sentIM"
  17. EventTypeTyping EventType = "typing"
  18. EventTypeStatus EventType = "status"
  19. EventTypeOfflineIM EventType = "offlineIM"
  20. EventTypeSessionEnded EventType = "sessionEnded"
  21. EventTypeRateLimit EventType = "rateLimit"
  22. )
  23. // Event represents an event to be delivered to a web client.
  24. type Event struct {
  25. Type EventType `json:"type"`
  26. SeqNum uint64 `json:"seqNum"`
  27. Timestamp int64 `json:"timestamp"`
  28. Data interface{} `json:"data"`
  29. }
  30. // PresenceEvent represents a presence change event.
  31. type PresenceEvent struct {
  32. AimID string `json:"aimId"`
  33. State string `json:"state"` // "online", "offline", "away", "idle"
  34. StatusMsg string `json:"statusMsg,omitempty"`
  35. AwayMsg string `json:"awayMsg,omitempty"`
  36. IdleTime int `json:"idleTime,omitempty"` // Minutes idle
  37. OnlineTime int64 `json:"onlineTime,omitempty"` // Unix timestamp
  38. UserType string `json:"userType"` // "aim", "icq", "admin"
  39. }
  40. // IMEvent represents an instant message event.
  41. type IMEvent struct {
  42. From string `json:"from"`
  43. Message string `json:"message"`
  44. Timestamp float64 `json:"timestamp"` // float64 for AMF3 encoding
  45. AutoResp bool `json:"autoResponse,omitempty"`
  46. }
  47. // SentIMEvent represents a sent instant message event.
  48. type SentIMEvent struct {
  49. Sender UserInfo `json:"sender"` // Sender user info
  50. Dest UserInfo `json:"dest"` // Destination user info
  51. Message string `json:"message"`
  52. Timestamp float64 `json:"timestamp"` // float64 for AMF3 encoding
  53. AutoResp bool `json:"autoResponse,omitempty"`
  54. }
  55. // UserInfo represents basic user information in events.
  56. type UserInfo struct {
  57. AimID string `json:"aimId"`
  58. DisplayID string `json:"displayId,omitempty"`
  59. UserType string `json:"userType,omitempty"`
  60. State string `json:"state,omitempty"`
  61. OnlineTime float64 `json:"onlineTime,omitempty"` // float64 for AMF3 encoding
  62. }
  63. // TypingEvent represents a typing notification event.
  64. type TypingEvent struct {
  65. From string `json:"from"`
  66. Typing bool `json:"typing"`
  67. }
  68. // BuddyListEvent represents a buddy list change event.
  69. type BuddyListEvent struct {
  70. Action string `json:"action"` // "add", "remove", "update"
  71. Buddy interface{} `json:"buddy"`
  72. Group string `json:"group,omitempty"`
  73. }
  74. // EventQueue manages a queue of events for a WebAPI session.
  75. type EventQueue struct {
  76. events []Event
  77. seqNum uint64
  78. maxSize int
  79. mu sync.RWMutex
  80. waitChan chan struct{}
  81. closed bool
  82. closedMu sync.RWMutex
  83. }
  84. // NewEventQueue creates a new event queue with the specified maximum size.
  85. func NewEventQueue(maxSize int) *EventQueue {
  86. return &EventQueue{
  87. events: make([]Event, 0),
  88. maxSize: maxSize,
  89. waitChan: make(chan struct{}, 1),
  90. }
  91. }
  92. // Push adds an event to the queue.
  93. func (q *EventQueue) Push(eventType EventType, data interface{}) {
  94. q.closedMu.RLock()
  95. if q.closed {
  96. q.closedMu.RUnlock()
  97. return
  98. }
  99. q.closedMu.RUnlock()
  100. q.mu.Lock()
  101. defer q.mu.Unlock()
  102. // Increment sequence number atomically
  103. seqNum := atomic.AddUint64(&q.seqNum, 1)
  104. event := Event{
  105. Type: eventType,
  106. SeqNum: seqNum,
  107. Timestamp: time.Now().Unix(),
  108. Data: data,
  109. }
  110. // Add event to queue
  111. q.events = append(q.events, event)
  112. // If queue exceeds max size, remove oldest events
  113. if len(q.events) > q.maxSize {
  114. // Keep only the most recent maxSize events
  115. q.events = q.events[len(q.events)-q.maxSize:]
  116. }
  117. // Signal any waiting fetchers
  118. select {
  119. case q.waitChan <- struct{}{}:
  120. default:
  121. // Channel already has a signal
  122. }
  123. }
  124. // Fetch retrieves events from the queue, optionally waiting for new events.
  125. func (q *EventQueue) Fetch(ctx context.Context, lastSeqNum uint64, timeout time.Duration) ([]Event, error) {
  126. q.closedMu.RLock()
  127. if q.closed {
  128. q.closedMu.RUnlock()
  129. return nil, errors.New("event queue is closed")
  130. }
  131. q.closedMu.RUnlock()
  132. // First, check if we have any events newer than lastSeqNum
  133. q.mu.RLock()
  134. events := q.getEventsAfter(lastSeqNum)
  135. q.mu.RUnlock()
  136. if len(events) > 0 {
  137. return events, nil
  138. }
  139. // No events available, wait for new ones or timeout
  140. timeoutChan := time.After(timeout)
  141. for {
  142. select {
  143. case <-q.waitChan:
  144. // New events may be available
  145. q.mu.RLock()
  146. events = q.getEventsAfter(lastSeqNum)
  147. q.mu.RUnlock()
  148. if len(events) > 0 {
  149. return events, nil
  150. }
  151. // False alarm, keep waiting
  152. case <-timeoutChan:
  153. // Timeout reached, return empty array
  154. return []Event{}, nil
  155. case <-ctx.Done():
  156. // Context cancelled
  157. return nil, ctx.Err()
  158. }
  159. }
  160. }
  161. // getEventsAfter returns all events with sequence number greater than the specified value.
  162. // Must be called with at least a read lock held.
  163. func (q *EventQueue) getEventsAfter(seqNum uint64) []Event {
  164. var result []Event
  165. for _, event := range q.events {
  166. if event.SeqNum > seqNum {
  167. result = append(result, event)
  168. }
  169. }
  170. return result
  171. }
  172. // GetAllEvents returns all events in the queue (for debugging).
  173. func (q *EventQueue) GetAllEvents() []Event {
  174. q.mu.RLock()
  175. defer q.mu.RUnlock()
  176. result := make([]Event, len(q.events))
  177. copy(result, q.events)
  178. return result
  179. }
  180. // Clear removes all events from the queue.
  181. func (q *EventQueue) Clear() {
  182. q.mu.Lock()
  183. defer q.mu.Unlock()
  184. q.events = make([]Event, 0)
  185. }
  186. // Size returns the current number of events in the queue.
  187. func (q *EventQueue) Size() int {
  188. q.mu.RLock()
  189. defer q.mu.RUnlock()
  190. return len(q.events)
  191. }
  192. // Close closes the event queue, unblocking any waiting fetchers.
  193. func (q *EventQueue) Close() {
  194. q.closedMu.Lock()
  195. defer q.closedMu.Unlock()
  196. if q.closed {
  197. return
  198. }
  199. q.closed = true
  200. // Send multiple signals to unblock all potential waiters
  201. for i := 0; i < 10; i++ {
  202. select {
  203. case q.waitChan <- struct{}{}:
  204. default:
  205. break
  206. }
  207. }
  208. }
  209. // IsClosed returns whether the queue is closed.
  210. func (q *EventQueue) IsClosed() bool {
  211. q.closedMu.RLock()
  212. defer q.closedMu.RUnlock()
  213. return q.closed
  214. }