Debian Codegraph @

server/store/store.go

raw
1 /*
2 Copyright 2013-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 store takes care of storing pending notifications.
18 package store
19
20 import (
21 "encoding/hex"
22 "encoding/json"
23 "errors"
24 "fmt"
25 "strings"
26 "time"
27
28 "gitlab.com/ubports/development/core/lomiri-push-service/protocol"
29 )
30
31 type InternalChannelId string
32
33 // BroadcastChannel returns whether the id represents a broadcast channel.
34 func (icid InternalChannelId) BroadcastChannel() bool {
35 marker := icid[0]
36 return marker == 'B' || marker == '0'
37 }
38
39 // UnicastChannel returns whether the id represents a unicast channel.
40 func (icid InternalChannelId) UnicastChannel() bool {
41 marker := icid[0]
42 return marker == 'U'
43 }
44
45 // UnicastUserAndDevice returns the user and device ids of a unicast channel.
46 func (icid InternalChannelId) UnicastUserAndDevice() (userId, deviceId string) {
47 if !icid.UnicastChannel() {
48 panic("UnicastUserAndDevice is for unicast channels")
49 }
50 parts := strings.SplitN(string(icid)[1:], ":", 2)
51 return parts[0], parts[1]
52 }
53
54 var ErrUnknownChannel = errors.New("unknown channel name")
55 var ErrUnknownToken = errors.New("unknown token")
56 var ErrUnauthorized = errors.New("unauthorized")
57 var ErrFull = errors.New("channel is full")
58 var ErrExpected128BitsHexRepr = errors.New("expected 128 bits hex repr")
59
60 const SystemInternalChannelId = InternalChannelId("0")
61
62 func InternalChannelIdToHex(chanId InternalChannelId) string {
63 if chanId == SystemInternalChannelId {
64 return "0"
65 }
66 if !chanId.BroadcastChannel() {
67 panic("InternalChannelIdToHex is for broadcast channels")
68 }
69 return string(chanId)[1:]
70 }
71
72 var zero128 [16]byte
73
74 const noId = InternalChannelId("")
75
76 func HexToInternalChannelId(hexRepr string) (InternalChannelId, error) {
77 if hexRepr == "0" {
78 return SystemInternalChannelId, nil
79 }
80 if len(hexRepr) != 32 {
81 return noId, ErrExpected128BitsHexRepr
82 }
83 var idbytes [16]byte
84 _, err := hex.Decode(idbytes[:], []byte(hexRepr))
85 if err != nil {
86 return noId, ErrExpected128BitsHexRepr
87 }
88 if idbytes == zero128 {
89 return SystemInternalChannelId, nil
90 }
91 // mark with B(roadcast) prefix
92 s := "B" + hexRepr
93 return InternalChannelId(s), nil
94 }
95
96 // UnicastInternalChannelId builds a channel id for the userId, deviceId pair.
97 func UnicastInternalChannelId(userId, deviceId string) InternalChannelId {
98 return InternalChannelId(fmt.Sprintf("U%s:%s", userId, deviceId))
99 }
100
101 // Metadata holds the metadata stored for a notification.
102 type Metadata struct {
103 Expiration time.Time
104 ReplaceTag string
105 Obsolete bool
106 }
107
108 // Before checks whether the expiration date in the metadata is before ref.
109 func (m *Metadata) Before(ref time.Time) bool {
110 return m.Expiration.Before(ref)
111 }
112
113 // PendingStore let store notifications into channels.
114 type PendingStore interface {
115 // Register returns a token for a device id, application id pair.
116 Register(deviceId, appId string) (token string, err error)
117 // Unregister forgets the token for a device id, application id pair.
118 Unregister(deviceId, appId string) error
119 // GetInternalChannelId returns the internal store id for a channel
120 // given the name.
121 GetInternalChannelId(name string) (InternalChannelId, error)
122 // AppendToChannel appends a notification to the channel.
123 AppendToChannel(chanId InternalChannelId, notification json.RawMessage, expiration time.Time) error
124 // GetInternalChannelIdFromToken returns the matching internal store
125 // id for a channel given a registered token and application id or
126 // directly a device id, user id pair.
127 GetInternalChannelIdFromToken(token, appId, userId, deviceId string) (InternalChannelId, error)
128 // AppendToUnicastChannel appends a notification to the unicast channel.
129 AppendToUnicastChannel(chanId InternalChannelId, appId string, notification json.RawMessage, msgId string, meta Metadata) error
130 // GetChannelSnapshot gets all the current notifications and
131 // current top level in the channel.
132 GetChannelSnapshot(chanId InternalChannelId) (topLevel int64, notifications []protocol.Notification, err error)
133 // GetChannelUnfiltered gets all the stored notifications with
134 // metadata and current top level in the channel.
135 GetChannelUnfiltered(chanId InternalChannelId) (topLevel int64, notifications []protocol.Notification, metadata []Metadata, err error)
136 // Scrub removes notifications from the channel based on criteria.
137 // Usages:
138 // Scrub(chanId) removes all expired notifications.
139 // Scrub(chanId, appId) removes all expired notifications and
140 // all notifications for appId.
141 // Scrub(chanId, appId, replaceTag) removes all expired notifications
142 // and all notifications matching both appId and replaceTag.
143 Scrub(chanId InternalChannelId, criteria ...string) error
144 // DropByMsgId drops notifications from a unicast channel
145 // based on message ids.
146 DropByMsgId(chanId InternalChannelId, targets []protocol.Notification) error
147 // Close is to be called when done with the store.
148 Close()
149 }
150
151 // FilterOutByMsgId returns the notifications from orig whose msg id is not
152 // mentioned in targets.
153 func FilterOutByMsgId(orig, targets []protocol.Notification) []protocol.Notification {
154 n := len(orig)
155 t := len(targets)
156 // common case, removing the continuous head
157 if t > 0 && n >= t {
158 if targets[0].MsgId == orig[0].MsgId {
159 for i := t - 1; i >= 0; i-- {
160 if i == 0 {
161 return orig[t:]
162 }
163 if targets[i].MsgId != orig[i].MsgId {
164 break
165 }
166 }
167 }
168 }
169 // slow way
170 ids := make(map[string]bool, t)
171 for _, target := range targets {
172 ids[target.MsgId] = true
173 }
174 acc := make([]protocol.Notification, 0, n)
175 for _, notif := range orig {
176 if !ids[notif.MsgId] {
177 acc = append(acc, notif)
178 }
179 }
180 return acc
181 }
182
183 type tagKey struct {
184 appId, replaceTag string
185 }
186
187 // FilterOutObsolete filters out expired notifications and superseded
188 // notifications sharing a replace tag based on paired meta
189 // information.
190 func FilterOutObsolete(notifications []protocol.Notification, meta []Metadata) []protocol.Notification {
191 now := time.Now()
192 seenTags := make(map[tagKey]bool, 10)
193 n := 0
194 // walk backward to keep the latest ones with a given ReplaceTag
195 for j := len(meta) - 1; j >= 0; j-- {
196 if meta[j].Before(now) {
197 meta[j].Obsolete = true
198 continue
199 }
200 if meta[j].ReplaceTag != "" {
201 key := tagKey{notifications[j].AppId, meta[j].ReplaceTag}
202 seen := seenTags[key]
203 if seen {
204 meta[j].Obsolete = true
205 continue
206 } else {
207 seenTags[key] = true
208 }
209 }
210 n++
211 }
212 res := make([]protocol.Notification, n)
213 j := 0
214 for i := range meta {
215 if !meta[i].Obsolete {
216 res[j] = notifications[i]
217 j++
218 }
219 }
220 return res
221 }