events.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. EventTypeBuddyList EventType = "buddylist"
  13. EventTypeConversation EventType = "conversation"
  14. EventTypeIM EventType = "im"
  15. EventTypeOfflineIM EventType = "offlineIM"
  16. EventTypePreference EventType = "preference"
  17. EventTypePresence EventType = "presence"
  18. EventTypeRateLimit EventType = "rateLimit"
  19. EventTypeSentIM EventType = "sentIM"
  20. EventTypeSessionEnded EventType = "sessionEnded"
  21. EventTypeStatus EventType = "status"
  22. EventTypeTyping EventType = "typing"
  23. EventTypePermitDeny EventType = "permitDeny"
  24. )
  25. // Event represents an event to be delivered to a web client.
  26. type Event struct {
  27. Type EventType `json:"type"`
  28. SeqNum uint64 `json:"seqNum"`
  29. Timestamp int64 `json:"timestamp"`
  30. Data interface{} `json:"eventData"`
  31. }
  32. // PresenceEvent represents a presence change event.
  33. // Friendly repeats the viewer's alias for the user. The client's merge deletes any
  34. // alias it already holds, so a presence update that omits it silently renames the
  35. // buddy back to their screen name. See UserInfo.
  36. type PresenceEvent struct {
  37. AimID string `json:"aimId"`
  38. Friendly string `json:"friendly,omitempty"`
  39. State string `json:"state"` // "online", "offline", "away", "idle"
  40. StatusMsg string `json:"statusMsg,omitempty"`
  41. AwayMsg string `json:"awayMsg,omitempty"`
  42. IdleTime int `json:"idleTime,omitempty"` // Minutes idle
  43. OnlineTime int64 `json:"onlineTime,omitempty"` // Unix timestamp
  44. UserType string `json:"userType"` // "aim", "icq", "admin"
  45. BuddyIcon string `json:"buddyIcon,omitempty"` // Absolute icon URL; empty preserves the client's current icon, the placeholder URL clears it
  46. }
  47. // IMEvent represents an instant message event.
  48. type IMEvent struct {
  49. Source UserInfo `json:"source"`
  50. Message string `json:"message"`
  51. MsgID string `json:"msgId,omitempty"`
  52. Timestamp float64 `json:"timestamp"` // float64 for AMF3 encoding
  53. AutoResp bool `json:"autoresponse,omitempty"`
  54. }
  55. // SentIMEvent represents a sent instant message event.
  56. type SentIMEvent struct {
  57. Sender UserInfo `json:"sender"` // Sender user info
  58. Dest UserInfo `json:"dest"` // Destination user info
  59. Message string `json:"message"`
  60. MsgID string `json:"msgId,omitempty"`
  61. Timestamp float64 `json:"timestamp"` // float64 for AMF3 encoding
  62. AutoResp bool `json:"autoResponse,omitempty"`
  63. }
  64. // UserInfo represents basic user information in events.
  65. // AimID is the normalized screen name the client keys users by. DisplayID is the
  66. // screen name as its owner formatted it. Friendly is the viewer's private alias for
  67. // that user, and takes precedence over DisplayID when the client renders a name.
  68. //
  69. // The client merges every user map it receives onto the single user object it holds
  70. // per aimId, and that merge deletes friendly before applying the map. An alias
  71. // therefore has to be repeated on every user map, or it is lost.
  72. type UserInfo struct {
  73. AimID string `json:"aimId"`
  74. DisplayID string `json:"displayId,omitempty"`
  75. Friendly string `json:"friendly,omitempty"`
  76. UserType string `json:"userType,omitempty"`
  77. State string `json:"state,omitempty"`
  78. OnlineTime float64 `json:"onlineTime,omitempty"` // float64 for AMF3 encoding
  79. }
  80. // TypingEvent represents a typing notification event.
  81. type TypingEvent struct {
  82. AimID string `json:"aimId"`
  83. TypingStatus string `json:"typingStatus"`
  84. }
  85. // EventQueue manages a queue of events for a WebAPI session.
  86. type EventQueue struct {
  87. events []Event
  88. seqNum uint64
  89. maxSize int
  90. mu sync.RWMutex
  91. waitChan chan struct{}
  92. closed bool
  93. closedMu sync.RWMutex
  94. }
  95. // NewEventQueue creates a new event queue with the specified maximum size.
  96. func NewEventQueue(maxSize int) *EventQueue {
  97. return &EventQueue{
  98. events: make([]Event, 0),
  99. maxSize: maxSize,
  100. waitChan: make(chan struct{}, 1),
  101. }
  102. }
  103. // Push adds an event to the queue.
  104. func (q *EventQueue) Push(eventType EventType, data interface{}) {
  105. q.closedMu.RLock()
  106. if q.closed {
  107. q.closedMu.RUnlock()
  108. return
  109. }
  110. q.closedMu.RUnlock()
  111. q.mu.Lock()
  112. defer q.mu.Unlock()
  113. // Increment sequence number atomically
  114. seqNum := atomic.AddUint64(&q.seqNum, 1)
  115. event := Event{
  116. Type: eventType,
  117. SeqNum: seqNum,
  118. Timestamp: time.Now().Unix(),
  119. Data: data,
  120. }
  121. // Add event to queue
  122. q.events = append(q.events, event)
  123. // If queue exceeds max size, remove oldest events
  124. if len(q.events) > q.maxSize {
  125. // Keep only the most recent maxSize events
  126. q.events = q.events[len(q.events)-q.maxSize:]
  127. }
  128. // Signal any waiting fetchers
  129. select {
  130. case q.waitChan <- struct{}{}:
  131. default:
  132. // Channel already has a signal
  133. }
  134. }
  135. // Fetch retrieves events from the queue, optionally waiting for new events.
  136. func (q *EventQueue) Fetch(ctx context.Context, lastSeqNum uint64, timeout time.Duration) ([]Event, error) {
  137. q.closedMu.RLock()
  138. if q.closed {
  139. q.closedMu.RUnlock()
  140. return nil, errors.New("event queue is closed")
  141. }
  142. q.closedMu.RUnlock()
  143. // First, check if we have any events newer than lastSeqNum
  144. q.mu.RLock()
  145. events := q.getEventsAfter(lastSeqNum)
  146. q.mu.RUnlock()
  147. if len(events) > 0 {
  148. return events, nil
  149. }
  150. // No events available, wait for new ones or timeout
  151. timeoutChan := time.After(timeout)
  152. for {
  153. select {
  154. case <-q.waitChan:
  155. // New events may be available
  156. q.mu.RLock()
  157. events = q.getEventsAfter(lastSeqNum)
  158. q.mu.RUnlock()
  159. if len(events) > 0 {
  160. return events, nil
  161. }
  162. // False alarm, keep waiting
  163. case <-timeoutChan:
  164. // Timeout reached, return empty array
  165. return []Event{}, nil
  166. case <-ctx.Done():
  167. // Context cancelled
  168. return nil, ctx.Err()
  169. }
  170. }
  171. }
  172. // getEventsAfter returns all events with sequence number greater than the specified value.
  173. // Must be called with at least a read lock held.
  174. func (q *EventQueue) getEventsAfter(seqNum uint64) []Event {
  175. var result []Event
  176. for _, event := range q.events {
  177. if event.SeqNum > seqNum {
  178. result = append(result, event)
  179. }
  180. }
  181. return result
  182. }
  183. // GetAllEvents returns all events in the queue (for debugging).
  184. func (q *EventQueue) GetAllEvents() []Event {
  185. q.mu.RLock()
  186. defer q.mu.RUnlock()
  187. result := make([]Event, len(q.events))
  188. copy(result, q.events)
  189. return result
  190. }
  191. // Close closes the event queue, unblocking any waiting fetchers.
  192. func (q *EventQueue) Close() {
  193. q.closedMu.Lock()
  194. defer q.closedMu.Unlock()
  195. if q.closed {
  196. return
  197. }
  198. q.closed = true
  199. // Send multiple signals to unblock all potential waiters
  200. notifyWaiters:
  201. for i := 0; i < 10; i++ {
  202. select {
  203. case q.waitChan <- struct{}{}:
  204. default:
  205. break notifyWaiters
  206. }
  207. }
  208. }