| 1 | // gomuks - A terminal Matrix client written in Go. |
| 2 | // Copyright (C) 2020 Tulir Asokan |
| 3 | // |
| 4 | // This program is free software: you can redistribute it and/or modify |
| 5 | // it under the terms of the GNU Affero General Public License as published by |
| 6 | // the Free Software Foundation, either version 3 of the License, or |
| 7 | // (at your option) any later version. |
| 8 | // |
| 9 | // This program is distributed in the hope that it will be useful, |
| 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | // GNU Affero General Public License for more details. |
| 13 | // |
| 14 | // You should have received a copy of the GNU Affero General Public License |
| 15 | // along with this program. If not, see <https://www.gnu.org/licenses/>. |
| 16 | |
| 17 | package matrix |
| 18 | |
| 19 | import ( |
| 20 | "bytes" |
| 21 | "compress/gzip" |
| 22 | "encoding/binary" |
| 23 | "encoding/gob" |
| 24 | "errors" |
| 25 | |
| 26 | sync "github.com/sasha-s/go-deadlock" |
| 27 | bolt "go.etcd.io/bbolt" |
| 28 | |
| 29 | "maunium.net/go/mautrix/event" |
| 30 | "maunium.net/go/mautrix/id" |
| 31 | |
| 32 | "maunium.net/go/gomuks/matrix/muksevt" |
| 33 | "maunium.net/go/gomuks/matrix/rooms" |
| 34 | ) |
| 35 | |
| 36 | type HistoryManager struct { |
| 37 | sync.Mutex |
| 38 | |
| 39 | db *bolt.DB |
| 40 | |
| 41 | historyEndPtr map[*rooms.Room]uint64 |
| 42 | } |
| 43 | |
| 44 | var bucketRoomStreams = []byte("room_streams") |
| 45 | var bucketRoomEventIDs = []byte("room_event_ids") |
| 46 | var bucketStreamPointers = []byte("room_stream_pointers") |
| 47 | |
| 48 | const halfUint64 = ^uint64(0) >> 1 |
| 49 | |
| 50 | func NewHistoryManager(dbPath string) (*HistoryManager, error) { |
| 51 | hm := &HistoryManager{ |
| 52 | historyEndPtr: make(map[*rooms.Room]uint64), |
| 53 | } |
| 54 | db, err := bolt.Open(dbPath, 0600, &bolt.Options{ |
| 55 | Timeout: 1, |
| 56 | NoGrowSync: false, |
| 57 | FreelistType: bolt.FreelistArrayType, |
| 58 | }) |
| 59 | if err != nil { |
| 60 | return nil, err |
| 61 | } |
| 62 | err = db.Update(func(tx *bolt.Tx) error { |
| 63 | _, err = tx.CreateBucketIfNotExists(bucketRoomStreams) |
| 64 | if err != nil { |
| 65 | return err |
| 66 | } |
| 67 | _, err = tx.CreateBucketIfNotExists(bucketRoomEventIDs) |
| 68 | if err != nil { |
| 69 | return err |
| 70 | } |
| 71 | _, err = tx.CreateBucketIfNotExists(bucketStreamPointers) |
| 72 | if err != nil { |
| 73 | return err |
| 74 | } |
| 75 | return nil |
| 76 | }) |
| 77 | if err != nil { |
| 78 | return nil, err |
| 79 | } |
| 80 | hm.db = db |
| 81 | return hm, nil |
| 82 | } |
| 83 | |
| 84 | func (hm *HistoryManager) Close() error { |
| 85 | return hm.db.Close() |
| 86 | } |
| 87 | |
| 88 | var ( |
| 89 | EventNotFoundError = errors.New("event not found") |
| 90 | RoomNotFoundError = errors.New("room not found") |
| 91 | ) |
| 92 | |
| 93 | func (hm *HistoryManager) getStreamIndex(tx *bolt.Tx, roomID []byte, eventID []byte) (*bolt.Bucket, []byte, error) { |
| 94 | eventIDs := tx.Bucket(bucketRoomEventIDs).Bucket(roomID) |
| 95 | if eventIDs == nil { |
| 96 | return nil, nil, RoomNotFoundError |
| 97 | } |
| 98 | index := eventIDs.Get(eventID) |
| 99 | if index == nil { |
| 100 | return nil, nil, EventNotFoundError |
| 101 | } |
| 102 | stream := tx.Bucket(bucketRoomStreams).Bucket(roomID) |
| 103 | return stream, index, nil |
| 104 | } |
| 105 | |
| 106 | func (hm *HistoryManager) getEvent(tx *bolt.Tx, stream *bolt.Bucket, index []byte) (*muksevt.Event, error) { |
| 107 | eventData := stream.Get(index) |
| 108 | if eventData == nil || len(eventData) == 0 { |
| 109 | return nil, EventNotFoundError |
| 110 | } |
| 111 | return unmarshalEvent(eventData) |
| 112 | } |
| 113 | |
| 114 | func (hm *HistoryManager) Get(room *rooms.Room, eventID id.EventID) (evt *muksevt.Event, err error) { |
| 115 | err = hm.db.View(func(tx *bolt.Tx) error { |
| 116 | if stream, index, err := hm.getStreamIndex(tx, []byte(room.ID), []byte(eventID)); err != nil { |
| 117 | return err |
| 118 | } else if evt, err = hm.getEvent(tx, stream, index); err != nil { |
| 119 | return err |
| 120 | } |
| 121 | return nil |
| 122 | }) |
| 123 | return |
| 124 | } |
| 125 | |
| 126 | func (hm *HistoryManager) Update(room *rooms.Room, eventID id.EventID, update func(evt *muksevt.Event) error) error { |
| 127 | return hm.db.Update(func(tx *bolt.Tx) error { |
| 128 | if stream, index, err := hm.getStreamIndex(tx, []byte(room.ID), []byte(eventID)); err != nil { |
| 129 | return err |
| 130 | } else if evt, err := hm.getEvent(tx, stream, index); err != nil { |
| 131 | return err |
| 132 | } else if err = update(evt); err != nil { |
| 133 | return err |
| 134 | } else if eventData, err := marshalEvent(evt); err != nil { |
| 135 | return err |
| 136 | } else if err := stream.Put(index, eventData); err != nil { |
| 137 | return err |
| 138 | } |
| 139 | return nil |
| 140 | }) |
| 141 | } |
| 142 | |
| 143 | func (hm *HistoryManager) Append(room *rooms.Room, events []*event.Event) ([]*muksevt.Event, error) { |
| 144 | muksEvts, _, err := hm.store(room, events, true) |
| 145 | return muksEvts, err |
| 146 | } |
| 147 | |
| 148 | func (hm *HistoryManager) Prepend(room *rooms.Room, events []*event.Event) ([]*muksevt.Event, uint64, error) { |
| 149 | return hm.store(room, events, false) |
| 150 | } |
| 151 | |
| 152 | func (hm *HistoryManager) store(room *rooms.Room, events []*event.Event, append bool) (newEvents []*muksevt.Event, newPtrStart uint64, err error) { |
| 153 | hm.Lock() |
| 154 | defer hm.Unlock() |
| 155 | newEvents = make([]*muksevt.Event, len(events)) |
| 156 | err = hm.db.Update(func(tx *bolt.Tx) error { |
| 157 | streamPointers := tx.Bucket(bucketStreamPointers) |
| 158 | rid := []byte(room.ID) |
| 159 | stream, err := tx.Bucket(bucketRoomStreams).CreateBucketIfNotExists(rid) |
| 160 | if err != nil { |
| 161 | return err |
| 162 | } |
| 163 | eventIDs, err := tx.Bucket(bucketRoomEventIDs).CreateBucketIfNotExists(rid) |
| 164 | if err != nil { |
| 165 | return err |
| 166 | } |
| 167 | if stream.Sequence() < halfUint64 { |
| 168 | // The sequence counter (i.e. the future) the part after 2^63, i.e. the second half of uint64 |
| 169 | // We set it to -1 because NextSequence will increment it by one. |
| 170 | err = stream.SetSequence(halfUint64 - 1) |
| 171 | if err != nil { |
| 172 | return err |
| 173 | } |
| 174 | } |
| 175 | if append { |
| 176 | ptrStart, err := stream.NextSequence() |
| 177 | if err != nil { |
| 178 | return err |
| 179 | } |
| 180 | for i, evt := range events { |
| 181 | newEvents[i] = muksevt.Wrap(evt) |
| 182 | if err := put(stream, eventIDs, newEvents[i], ptrStart+uint64(i)); err != nil { |
| 183 | return err |
| 184 | } |
| 185 | } |
| 186 | err = stream.SetSequence(ptrStart + uint64(len(events)) - 1) |
| 187 | if err != nil { |
| 188 | return err |
| 189 | } |
| 190 | } else { |
| 191 | ptrStart, ok := hm.historyEndPtr[room] |
| 192 | if !ok { |
| 193 | ptrStartRaw := streamPointers.Get(rid) |
| 194 | if ptrStartRaw != nil { |
| 195 | ptrStart = btoi(ptrStartRaw) |
| 196 | } else { |
| 197 | ptrStart = halfUint64 - 1 |
| 198 | } |
| 199 | } |
| 200 | eventCount := uint64(len(events)) |
| 201 | for i, evt := range events { |
| 202 | newEvents[i] = muksevt.Wrap(evt) |
| 203 | if err := put(stream, eventIDs, newEvents[i], -ptrStart-uint64(i)); err != nil { |
| 204 | return err |
| 205 | } |
| 206 | } |
| 207 | hm.historyEndPtr[room] = ptrStart + eventCount |
| 208 | // TODO this is not the correct value for newPtrStart, figure out what the f*ck is going on here |
| 209 | newPtrStart = ptrStart + eventCount |
| 210 | err := streamPointers.Put(rid, itob(ptrStart+eventCount)) |
| 211 | if err != nil { |
| 212 | return err |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | return nil |
| 217 | }) |
| 218 | return |
| 219 | } |
| 220 | |
| 221 | func (hm *HistoryManager) Load(room *rooms.Room, num int, ptrStart uint64) (events []*muksevt.Event, newPtrStart uint64, err error) { |
| 222 | hm.Lock() |
| 223 | defer hm.Unlock() |
| 224 | err = hm.db.View(func(tx *bolt.Tx) error { |
| 225 | stream := tx.Bucket(bucketRoomStreams).Bucket([]byte(room.ID)) |
| 226 | if stream == nil { |
| 227 | return nil |
| 228 | } |
| 229 | if ptrStart == 0 { |
| 230 | ptrStart = stream.Sequence() + 1 |
| 231 | } |
| 232 | c := stream.Cursor() |
| 233 | k, v := c.Seek(itob(ptrStart - uint64(num))) |
| 234 | ptrStartFound := btoi(k) |
| 235 | if k == nil || ptrStartFound >= ptrStart { |
| 236 | return nil |
| 237 | } |
| 238 | newPtrStart = ptrStartFound |
| 239 | for ; k != nil && btoi(k) < ptrStart; k, v = c.Next() { |
| 240 | evt, parseError := unmarshalEvent(v) |
| 241 | if parseError != nil { |
| 242 | return parseError |
| 243 | } |
| 244 | events = append(events, evt) |
| 245 | } |
| 246 | return nil |
| 247 | }) |
| 248 | // Reverse array because we read/append the history in reverse order. |
| 249 | i := 0 |
| 250 | j := len(events) - 1 |
| 251 | for i < j { |
| 252 | events[i], events[j] = events[j], events[i] |
| 253 | i++ |
| 254 | j-- |
| 255 | } |
| 256 | return |
| 257 | } |
| 258 | |
| 259 | func itob(v uint64) []byte { |
| 260 | b := make([]byte, 8) |
| 261 | binary.BigEndian.PutUint64(b, v) |
| 262 | return b |
| 263 | } |
| 264 | |
| 265 | func btoi(b []byte) uint64 { |
| 266 | return binary.BigEndian.Uint64(b) |
| 267 | } |
| 268 | |
| 269 | func stripRaw(evt *muksevt.Event) { |
| 270 | evtCopy := *evt.Event |
| 271 | evtCopy.Content = event.Content{ |
| 272 | Parsed: evt.Content.Parsed, |
| 273 | } |
| 274 | evt.Event = &evtCopy |
| 275 | } |
| 276 | |
| 277 | func marshalEvent(evt *muksevt.Event) ([]byte, error) { |
| 278 | stripRaw(evt) |
| 279 | var buf bytes.Buffer |
| 280 | enc, _ := gzip.NewWriterLevel(&buf, gzip.BestSpeed) |
| 281 | if err := gob.NewEncoder(enc).Encode(evt); err != nil { |
| 282 | _ = enc.Close() |
| 283 | return nil, err |
| 284 | } else if err := enc.Close(); err != nil { |
| 285 | return nil, err |
| 286 | } |
| 287 | return buf.Bytes(), nil |
| 288 | } |
| 289 | |
| 290 | func unmarshalEvent(data []byte) (*muksevt.Event, error) { |
| 291 | evt := &muksevt.Event{} |
| 292 | if cmpReader, err := gzip.NewReader(bytes.NewReader(data)); err != nil { |
| 293 | return nil, err |
| 294 | } else if err := gob.NewDecoder(cmpReader).Decode(evt); err != nil { |
| 295 | _ = cmpReader.Close() |
| 296 | return nil, err |
| 297 | } else if err := cmpReader.Close(); err != nil { |
| 298 | return nil, err |
| 299 | } |
| 300 | return evt, nil |
| 301 | } |
| 302 | |
| 303 | func put(streams, eventIDs *bolt.Bucket, evt *muksevt.Event, key uint64) error { |
| 304 | data, err := marshalEvent(evt) |
| 305 | if err != nil { |
| 306 | return err |
| 307 | } |
| 308 | keyBytes := itob(key) |
| 309 | if err = streams.Put(keyBytes, data); err != nil { |
| 310 | return err |
| 311 | } |
| 312 | if err = eventIDs.Put([]byte(evt.ID), keyBytes); err != nil { |
| 313 | return err |
| 314 | } |
| 315 | return nil |
| 316 | } |