hub.go93 lines, 1.9 KB
| 1 | package live |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "sync" |
| 6 | ) |
| 7 | |
| 8 | // An Event is one piece of news for one user. An ID is something a client can |
| 9 | // come back for after a break. Zero means there is nothing to come back for. |
| 10 | type Event struct { |
| 11 | ID int64 `json:"id,omitempty"` |
| 12 | Kind string `json:"kind"` |
| 13 | Data json.RawMessage `json:"data"` |
| 14 | } |
| 15 | |
| 16 | // buffer is how many events may wait for one stream. |
| 17 | const buffer = 64 |
| 18 | |
| 19 | // A Hub knows the streams that are open on this server, by user. |
| 20 | type Hub struct { |
| 21 | mu sync.Mutex |
| 22 | streams map[int64]map[chan Event]bool |
| 23 | dropped int |
| 24 | } |
| 25 | |
| 26 | func NewHub() *Hub { |
| 27 | return &Hub{streams: map[int64]map[chan Event]bool{}} |
| 28 | } |
| 29 | |
| 30 | func (h *Hub) Register(user int64) chan Event { |
| 31 | c := make(chan Event, buffer) |
| 32 | h.mu.Lock() |
| 33 | defer h.mu.Unlock() |
| 34 | if h.streams[user] == nil { |
| 35 | h.streams[user] = map[chan Event]bool{} |
| 36 | } |
| 37 | h.streams[user][c] = true |
| 38 | return c |
| 39 | } |
| 40 | |
| 41 | func (h *Hub) Unregister(user int64, c chan Event) { |
| 42 | h.mu.Lock() |
| 43 | defer h.mu.Unlock() |
| 44 | delete(h.streams[user], c) |
| 45 | if len(h.streams[user]) == 0 { |
| 46 | delete(h.streams, user) |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | // Deliver hands e to every stream of user. It never waits. |
| 51 | func (h *Hub) Deliver(user int64, e Event) { |
| 52 | h.mu.Lock() |
| 53 | defer h.mu.Unlock() |
| 54 | for c := range h.streams[user] { |
| 55 | select { |
| 56 | case c <- e: |
| 57 | default: |
| 58 | close(c) |
| 59 | delete(h.streams[user], c) |
| 60 | h.dropped++ |
| 61 | } |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | // Reset drops every stream. Their clients come back, and catch up. |
| 66 | func (h *Hub) Reset() { |
| 67 | h.mu.Lock() |
| 68 | defer h.mu.Unlock() |
| 69 | for user, open := range h.streams { |
| 70 | for c := range open { |
| 71 | close(c) |
| 72 | } |
| 73 | delete(h.streams, user) |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | // Open is how many streams are open on this server, right now. |
| 78 | func (h *Hub) Open() int { |
| 79 | h.mu.Lock() |
| 80 | defer h.mu.Unlock() |
| 81 | n := 0 |
| 82 | for _, open := range h.streams { |
| 83 | n += len(open) |
| 84 | } |
| 85 | return n |
| 86 | } |
| 87 | |
| 88 | // Dropped is how many streams this server has let go of, because they fell behind. |
| 89 | func (h *Hub) Dropped() int { |
| 90 | h.mu.Lock() |
| 91 | defer h.mu.Unlock() |
| 92 | return h.dropped |
| 93 | } |