| 1 |
/* |
| 2 |
Copyright 2014 Canonical Ltd. |
| 3 |
|
| 4 |
This program is free software: you can redistribute it and/or modify it |
| 5 |
under the terms of the GNU General Public License version 3, as published |
| 6 |
by the Free Software Foundation. |
| 7 |
|
| 8 |
This program is distributed in the hope that it will be useful, but |
| 9 |
WITHOUT ANY WARRANTY; without even the implied warranties of |
| 10 |
MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR |
| 11 |
PURPOSE. See the GNU General Public License for more details. |
| 12 |
|
| 13 |
You should have received a copy of the GNU General Public License along |
| 14 |
with this program. If not, see <http://www.gnu.org/licenses/>. |
| 15 |
*/ |
| 16 |
|
| 17 |
package service |
| 18 |
|
| 19 |
import ( |
| 20 |
"encoding/json" |
| 21 |
) |
| 22 |
|
| 23 |
var mBoxMaxMessagesSize = 128 * 1024 |
| 24 |
|
| 25 |
// mBox can hold a size-limited amount of notification messages for one application. |
| 26 |
type mBox struct { |
| 27 |
evicted int |
| 28 |
curSize int |
| 29 |
messages []string |
| 30 |
nids []string |
| 31 |
} |
| 32 |
|
| 33 |
func (box *mBox) evictFor(sz int) { |
| 34 |
evictedSize := 0 |
| 35 |
i := box.evicted |
| 36 |
n := len(box.messages) |
| 37 |
for evictedSize < sz && i < n { |
| 38 |
evictedSize += len(box.messages[i]) |
| 39 |
box.messages[i] = "" |
| 40 |
box.nids[i] = "" |
| 41 |
box.evicted++ |
| 42 |
i++ |
| 43 |
} |
| 44 |
box.curSize -= evictedSize |
| 45 |
} |
| 46 |
|
| 47 |
// Append appends a message with notification id to the mbox. |
| 48 |
func (box *mBox) Append(message json.RawMessage, nid string) { |
| 49 |
sz := len(message) |
| 50 |
if box.curSize+sz > mBoxMaxMessagesSize { |
| 51 |
// make space |
| 52 |
box.evictFor(sz) |
| 53 |
} |
| 54 |
n := len(box.messages) |
| 55 |
evicted := box.evicted |
| 56 |
if evicted > 0 { |
| 57 |
if evicted == n { |
| 58 |
// all evicted, just start from scratch |
| 59 |
box.messages = box.messages[0:0] |
| 60 |
box.nids = box.nids[0:0] |
| 61 |
box.evicted = 0 |
| 62 |
} else if evicted >= cap(box.messages)/2 { |
| 63 |
// amortize: do a copy only each cap/2 evicted |
| 64 |
copy(box.messages, box.messages[box.evicted:]) |
| 65 |
kept := n - box.evicted |
| 66 |
box.messages = box.messages[0:kept] |
| 67 |
copy(box.nids, box.nids[box.evicted:]) |
| 68 |
box.nids = box.nids[0:kept] |
| 69 |
box.evicted = 0 |
| 70 |
} |
| 71 |
} |
| 72 |
box.messages = append(box.messages, string(message)) |
| 73 |
box.nids = append(box.nids, nid) |
| 74 |
box.curSize += sz |
| 75 |
} |
| 76 |
|
| 77 |
// AllMessages gets all messages from the mbox. |
| 78 |
func (box *mBox) AllMessages() []string { |
| 79 |
return box.messages[box.evicted:] |
| 80 |
} |