| 1 |
package centrifuge |
| 2 |
|
| 3 |
import ( |
| 4 |
"container/heap" |
| 5 |
"sync" |
| 6 |
"time" |
| 7 |
|
| 8 |
"github.com/centrifugal/centrifuge/internal/memstream" |
| 9 |
"github.com/centrifugal/centrifuge/internal/priority" |
| 10 |
) |
| 11 |
|
| 12 |
// MemoryBroker is builtin default Broker which allows to run Centrifuge-based |
| 13 |
// server without any external broker. All data managed inside process memory. |
| 14 |
// |
| 15 |
// With this Broker you can only run single Centrifuge node. If you need to scale |
| 16 |
// you should consider using another Broker implementation instead – for example |
| 17 |
// RedisBroker. |
| 18 |
// |
| 19 |
// Running single node can be sufficient for many use cases especially when you |
| 20 |
// need maximum performance and not too many online clients. Consider configuring |
| 21 |
// your load balancer to have one backup Centrifuge node for HA in this case. |
| 22 |
type MemoryBroker struct { |
| 23 |
node *Node |
| 24 |
historyHub *historyHub |
| 25 |
eventHandler BrokerEventHandler |
| 26 |
|
| 27 |
// pubLocks synchronize access to publishing. We have to sync publish |
| 28 |
// to handle publications in the order of offset to prevent InsufficientState |
| 29 |
// errors. |
| 30 |
// TODO: maybe replace with sharded pool of workers with buffered channels. |
| 31 |
pubLocks map[int]*sync.Mutex |
| 32 |
} |
| 33 |
|
| 34 |
var _ Broker = (*MemoryBroker)(nil) |
| 35 |
|
| 36 |
// MemoryBrokerConfig is a memory broker config. |
| 37 |
type MemoryBrokerConfig struct { |
| 38 |
// HistoryMetaTTL sets a time of inactive stream meta information expiration. |
| 39 |
// This information contains an epoch and offset of each stream. Having this |
| 40 |
// meta information helps in message recovery process. |
| 41 |
// Must have a reasonable value for application. |
| 42 |
// At moment works with seconds precision. |
| 43 |
// TODO v1: since we have epoch, things should also properly work without meta |
| 44 |
// information at all (but we loose possibility of long-term recover in stream |
| 45 |
// without new messages). We can make this optional and disabled by default at |
| 46 |
// least. |
| 47 |
HistoryMetaTTL time.Duration |
| 48 |
} |
| 49 |
|
| 50 |
const numPubLocks = 4096 |
| 51 |
|
| 52 |
// NewMemoryBroker initializes MemoryBroker. |
| 53 |
func NewMemoryBroker(n *Node, c MemoryBrokerConfig) (*MemoryBroker, error) { |
| 54 |
pubLocks := make(map[int]*sync.Mutex, numPubLocks) |
| 55 |
for i := 0; i < numPubLocks; i++ { |
| 56 |
pubLocks[i] = &sync.Mutex{} |
| 57 |
} |
| 58 |
b := &MemoryBroker{ |
| 59 |
node: n, |
| 60 |
historyHub: newHistoryHub(c.HistoryMetaTTL), |
| 61 |
pubLocks: pubLocks, |
| 62 |
} |
| 63 |
return b, nil |
| 64 |
} |
| 65 |
|
| 66 |
// Run runs memory broker. |
| 67 |
func (b *MemoryBroker) Run(h BrokerEventHandler) error { |
| 68 |
b.eventHandler = h |
| 69 |
b.historyHub.runCleanups() |
| 70 |
return nil |
| 71 |
} |
| 72 |
|
| 73 |
func (b *MemoryBroker) pubLock(ch string) *sync.Mutex { |
| 74 |
return b.pubLocks[index(ch, numPubLocks)] |
| 75 |
} |
| 76 |
|
| 77 |
// Publish adds message into history hub and calls node method to handle message. |
| 78 |
// We don't have any PUB/SUB here as Memory Engine is single node only. |
| 79 |
func (b *MemoryBroker) Publish(ch string, data []byte, opts PublishOptions) (StreamPosition, error) { |
| 80 |
mu := b.pubLock(ch) |
| 81 |
mu.Lock() |
| 82 |
defer mu.Unlock() |
| 83 |
|
| 84 |
pub := &Publication{ |
| 85 |
Data: data, |
| 86 |
Info: opts.ClientInfo, |
| 87 |
} |
| 88 |
if opts.HistorySize > 0 && opts.HistoryTTL > 0 { |
| 89 |
streamTop, err := b.historyHub.add(ch, pub, opts) |
| 90 |
if err != nil { |
| 91 |
return StreamPosition{}, err |
| 92 |
} |
| 93 |
pub.Offset = streamTop.Offset |
| 94 |
return streamTop, b.eventHandler.HandlePublication(ch, pub, streamTop) |
| 95 |
} |
| 96 |
return StreamPosition{}, b.eventHandler.HandlePublication(ch, pub, StreamPosition{}) |
| 97 |
} |
| 98 |
|
| 99 |
// PublishJoin - see Broker interface description. |
| 100 |
func (b *MemoryBroker) PublishJoin(ch string, info *ClientInfo) error { |
| 101 |
return b.eventHandler.HandleJoin(ch, info) |
| 102 |
} |
| 103 |
|
| 104 |
// PublishLeave - see Broker interface description. |
| 105 |
func (b *MemoryBroker) PublishLeave(ch string, info *ClientInfo) error { |
| 106 |
return b.eventHandler.HandleLeave(ch, info) |
| 107 |
} |
| 108 |
|
| 109 |
// PublishControl - see Broker interface description. |
| 110 |
func (b *MemoryBroker) PublishControl(data []byte, _ string) error { |
| 111 |
return b.eventHandler.HandleControl(data) |
| 112 |
} |
| 113 |
|
| 114 |
// Subscribe is noop here. |
| 115 |
func (b *MemoryBroker) Subscribe(_ string) error { |
| 116 |
return nil |
| 117 |
} |
| 118 |
|
| 119 |
// Unsubscribe node from channel. Noop here. |
| 120 |
func (b *MemoryBroker) Unsubscribe(_ string) error { |
| 121 |
return nil |
| 122 |
} |
| 123 |
|
| 124 |
// History - see Broker interface description. |
| 125 |
func (b *MemoryBroker) History(ch string, filter HistoryFilter) ([]*Publication, StreamPosition, error) { |
| 126 |
return b.historyHub.get(ch, filter) |
| 127 |
} |
| 128 |
|
| 129 |
// RemoveHistory - see Broker interface description. |
| 130 |
func (b *MemoryBroker) RemoveHistory(ch string) error { |
| 131 |
return b.historyHub.remove(ch) |
| 132 |
} |
| 133 |
|
| 134 |
type historyHub struct { |
| 135 |
sync.RWMutex |
| 136 |
streams map[string]*memstream.Stream |
| 137 |
nextExpireCheck int64 |
| 138 |
expireQueue priority.Queue |
| 139 |
expires map[string]int64 |
| 140 |
historyMetaTTL time.Duration |
| 141 |
nextRemoveCheck int64 |
| 142 |
removeQueue priority.Queue |
| 143 |
removes map[string]int64 |
| 144 |
} |
| 145 |
|
| 146 |
func newHistoryHub(historyMetaTTL time.Duration) *historyHub { |
| 147 |
return &historyHub{ |
| 148 |
streams: make(map[string]*memstream.Stream), |
| 149 |
expireQueue: priority.MakeQueue(), |
| 150 |
expires: make(map[string]int64), |
| 151 |
historyMetaTTL: historyMetaTTL, |
| 152 |
removeQueue: priority.MakeQueue(), |
| 153 |
removes: make(map[string]int64), |
| 154 |
} |
| 155 |
} |
| 156 |
|
| 157 |
func (h *historyHub) runCleanups() { |
| 158 |
go h.expireStreams() |
| 159 |
if h.historyMetaTTL > 0 { |
| 160 |
go h.removeStreams() |
| 161 |
} |
| 162 |
} |
| 163 |
|
| 164 |
func (h *historyHub) removeStreams() { |
| 165 |
var nextRemoveCheck int64 |
| 166 |
for { |
| 167 |
time.Sleep(time.Second) |
| 168 |
h.Lock() |
| 169 |
if h.nextRemoveCheck == 0 || h.nextRemoveCheck > time.Now().Unix() { |
| 170 |
h.Unlock() |
| 171 |
continue |
| 172 |
} |
| 173 |
nextRemoveCheck = 0 |
| 174 |
for h.removeQueue.Len() > 0 { |
| 175 |
item := heap.Pop(&h.removeQueue).(*priority.Item) |
| 176 |
expireAt := item.Priority |
| 177 |
if expireAt > time.Now().Unix() { |
| 178 |
heap.Push(&h.removeQueue, item) |
| 179 |
nextRemoveCheck = expireAt |
| 180 |
break |
| 181 |
} |
| 182 |
ch := item.Value |
| 183 |
exp, ok := h.removes[ch] |
| 184 |
if !ok { |
| 185 |
continue |
| 186 |
} |
| 187 |
if exp <= expireAt { |
| 188 |
delete(h.removes, ch) |
| 189 |
delete(h.streams, ch) |
| 190 |
} else { |
| 191 |
heap.Push(&h.removeQueue, &priority.Item{Value: ch, Priority: exp}) |
| 192 |
} |
| 193 |
} |
| 194 |
h.nextRemoveCheck = nextRemoveCheck |
| 195 |
h.Unlock() |
| 196 |
} |
| 197 |
} |
| 198 |
|
| 199 |
func (h *historyHub) expireStreams() { |
| 200 |
var nextExpireCheck int64 |
| 201 |
for { |
| 202 |
time.Sleep(time.Second) |
| 203 |
h.Lock() |
| 204 |
if h.nextExpireCheck == 0 || h.nextExpireCheck > time.Now().Unix() { |
| 205 |
h.Unlock() |
| 206 |
continue |
| 207 |
} |
| 208 |
nextExpireCheck = 0 |
| 209 |
for h.expireQueue.Len() > 0 { |
| 210 |
item := heap.Pop(&h.expireQueue).(*priority.Item) |
| 211 |
expireAt := item.Priority |
| 212 |
if expireAt > time.Now().Unix() { |
| 213 |
heap.Push(&h.expireQueue, item) |
| 214 |
nextExpireCheck = expireAt |
| 215 |
break |
| 216 |
} |
| 217 |
ch := item.Value |
| 218 |
exp, ok := h.expires[ch] |
| 219 |
if !ok { |
| 220 |
continue |
| 221 |
} |
| 222 |
if exp <= expireAt { |
| 223 |
delete(h.expires, ch) |
| 224 |
if stream, ok := h.streams[ch]; ok { |
| 225 |
stream.Clear() |
| 226 |
} |
| 227 |
} else { |
| 228 |
heap.Push(&h.expireQueue, &priority.Item{Value: ch, Priority: exp}) |
| 229 |
} |
| 230 |
} |
| 231 |
h.nextExpireCheck = nextExpireCheck |
| 232 |
h.Unlock() |
| 233 |
} |
| 234 |
} |
| 235 |
|
| 236 |
func (h *historyHub) add(ch string, pub *Publication, opts PublishOptions) (StreamPosition, error) { |
| 237 |
h.Lock() |
| 238 |
defer h.Unlock() |
| 239 |
|
| 240 |
var index uint64 |
| 241 |
var epoch string |
| 242 |
|
| 243 |
expireAt := time.Now().Unix() + int64(opts.HistoryTTL.Seconds()) |
| 244 |
if _, ok := h.expires[ch]; !ok { |
| 245 |
heap.Push(&h.expireQueue, &priority.Item{Value: ch, Priority: expireAt}) |
| 246 |
} |
| 247 |
h.expires[ch] = expireAt |
| 248 |
if h.nextExpireCheck == 0 || h.nextExpireCheck > expireAt { |
| 249 |
h.nextExpireCheck = expireAt |
| 250 |
} |
| 251 |
|
| 252 |
if h.historyMetaTTL > 0 { |
| 253 |
removeAt := time.Now().Unix() + int64(h.historyMetaTTL.Seconds()) |
| 254 |
if _, ok := h.removes[ch]; !ok { |
| 255 |
heap.Push(&h.removeQueue, &priority.Item{Value: ch, Priority: removeAt}) |
| 256 |
} |
| 257 |
h.removes[ch] = removeAt |
| 258 |
if h.nextRemoveCheck == 0 || h.nextRemoveCheck > removeAt { |
| 259 |
h.nextRemoveCheck = removeAt |
| 260 |
} |
| 261 |
} |
| 262 |
|
| 263 |
if stream, ok := h.streams[ch]; ok { |
| 264 |
index, _ = stream.Add(pub, opts.HistorySize) |
| 265 |
epoch = stream.Epoch() |
| 266 |
} else { |
| 267 |
stream := memstream.New() |
| 268 |
index, _ = stream.Add(pub, opts.HistorySize) |
| 269 |
epoch = stream.Epoch() |
| 270 |
h.streams[ch] = stream |
| 271 |
} |
| 272 |
pub.Offset = index |
| 273 |
|
| 274 |
return StreamPosition{Offset: index, Epoch: epoch}, nil |
| 275 |
} |
| 276 |
|
| 277 |
// Lock must be held outside. |
| 278 |
func (h *historyHub) createStream(ch string) StreamPosition { |
| 279 |
stream := memstream.New() |
| 280 |
h.streams[ch] = stream |
| 281 |
streamPosition := StreamPosition{} |
| 282 |
streamPosition.Offset = 0 |
| 283 |
streamPosition.Epoch = stream.Epoch() |
| 284 |
return streamPosition |
| 285 |
} |
| 286 |
|
| 287 |
func getPosition(stream *memstream.Stream) StreamPosition { |
| 288 |
streamPosition := StreamPosition{} |
| 289 |
streamPosition.Offset = stream.Top() |
| 290 |
streamPosition.Epoch = stream.Epoch() |
| 291 |
return streamPosition |
| 292 |
} |
| 293 |
|
| 294 |
func (h *historyHub) get(ch string, filter HistoryFilter) ([]*Publication, StreamPosition, error) { |
| 295 |
h.Lock() |
| 296 |
defer h.Unlock() |
| 297 |
|
| 298 |
if h.historyMetaTTL > 0 { |
| 299 |
removeAt := time.Now().Unix() + int64(h.historyMetaTTL.Seconds()) |
| 300 |
if _, ok := h.removes[ch]; !ok { |
| 301 |
heap.Push(&h.removeQueue, &priority.Item{Value: ch, Priority: removeAt}) |
| 302 |
} |
| 303 |
h.removes[ch] = removeAt |
| 304 |
if h.nextRemoveCheck == 0 || h.nextRemoveCheck > removeAt { |
| 305 |
h.nextRemoveCheck = removeAt |
| 306 |
} |
| 307 |
} |
| 308 |
|
| 309 |
stream, ok := h.streams[ch] |
| 310 |
if !ok { |
| 311 |
return nil, h.createStream(ch), nil |
| 312 |
} |
| 313 |
|
| 314 |
if filter.Since == nil { |
| 315 |
if filter.Limit == 0 { |
| 316 |
return nil, getPosition(stream), nil |
| 317 |
} |
| 318 |
items, _, err := stream.Get(0, filter.Limit) |
| 319 |
if err != nil { |
| 320 |
return nil, StreamPosition{}, err |
| 321 |
} |
| 322 |
pubs := make([]*Publication, 0, len(items)) |
| 323 |
for _, item := range items { |
| 324 |
pub := item.Value.(*Publication) |
| 325 |
pubs = append(pubs, pub) |
| 326 |
} |
| 327 |
return pubs, getPosition(stream), nil |
| 328 |
} |
| 329 |
|
| 330 |
since := filter.Since |
| 331 |
|
| 332 |
streamPosition := getPosition(stream) |
| 333 |
if streamPosition.Offset == since.Offset && since.Epoch == stream.Epoch() { |
| 334 |
return nil, streamPosition, nil |
| 335 |
} |
| 336 |
|
| 337 |
streamOffset := since.Offset + 1 |
| 338 |
|
| 339 |
items, _, err := stream.Get(streamOffset, filter.Limit) |
| 340 |
if err != nil { |
| 341 |
return nil, StreamPosition{}, err |
| 342 |
} |
| 343 |
|
| 344 |
pubs := make([]*Publication, 0, len(items)) |
| 345 |
for _, item := range items { |
| 346 |
pub := item.Value.(*Publication) |
| 347 |
pubs = append(pubs, pub) |
| 348 |
} |
| 349 |
return pubs, streamPosition, nil |
| 350 |
} |
| 351 |
|
| 352 |
func (h *historyHub) remove(ch string) error { |
| 353 |
h.Lock() |
| 354 |
defer h.Unlock() |
| 355 |
if stream, ok := h.streams[ch]; ok { |
| 356 |
stream.Clear() |
| 357 |
} |
| 358 |
return nil |
| 359 |
} |