gomuks/matrix/rooms/roomcache.go

377 lines
8.3 KiB
Go
Raw Permalink Normal View History

2019-06-15 00:11:51 +02:00
// gomuks - A terminal Matrix client written in Go.
2020-04-19 17:10:14 +02:00
// Copyright (C) 2020 Tulir Asokan
2019-06-15 00:11:51 +02:00
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package rooms
import (
"compress/gzip"
"encoding/gob"
"fmt"
2019-06-15 00:11:51 +02:00
"os"
"path/filepath"
"strings"
2019-06-15 00:11:51 +02:00
"time"
sync "github.com/sasha-s/go-deadlock"
"maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/id"
"maunium.net/go/gomuks/debug"
2019-06-15 00:11:51 +02:00
)
// RoomCache contains room state info in a hashmap and linked list.
type RoomCache struct {
sync.Mutex
listPath string
directory string
maxSize int
maxAge int64
getOwner func() id.UserID
noUnload bool
2019-06-15 00:11:51 +02:00
Map map[id.RoomID]*Room
2019-06-15 00:11:51 +02:00
head *Room
tail *Room
size int
}
func NewRoomCache(listPath, directory string, maxSize int, maxAge int64, getOwner func() id.UserID) *RoomCache {
2019-06-15 00:11:51 +02:00
return &RoomCache{
listPath: listPath,
directory: directory,
maxSize: maxSize,
maxAge: maxAge,
getOwner: getOwner,
Map: make(map[id.RoomID]*Room),
2019-06-15 00:11:51 +02:00
}
}
func (cache *RoomCache) DisableUnloading() {
cache.noUnload = true
}
func (cache *RoomCache) EnableUnloading() {
cache.noUnload = false
}
func (cache *RoomCache) IsEncrypted(roomID id.RoomID) bool {
room := cache.Get(roomID)
return room != nil && room.Encrypted
}
func (cache *RoomCache) GetEncryptionEvent(roomID id.RoomID) *event.EncryptionEventContent {
room := cache.Get(roomID)
evt := room.GetStateEvent(event.StateEncryption, "")
if evt == nil {
return nil
}
content, ok := evt.Content.Parsed.(*event.EncryptionEventContent)
if !ok {
return nil
}
return content
}
func (cache *RoomCache) FindSharedRooms(userID id.UserID) (shared []id.RoomID) {
// FIXME this disables unloading so TouchNode wouldn't try to double-lock
cache.DisableUnloading()
cache.Lock()
for _, room := range cache.Map {
if !room.Encrypted {
continue
}
member, ok := room.GetMembers()[userID]
if ok && member.Membership == event.MembershipJoin {
shared = append(shared, room.ID)
}
}
cache.Unlock()
cache.EnableUnloading()
return
}
2019-06-15 00:11:51 +02:00
func (cache *RoomCache) LoadList() error {
cache.Lock()
defer cache.Unlock()
// Open room list file
file, err := os.OpenFile(cache.listPath, os.O_RDONLY, 0600)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return fmt.Errorf("failed to open room list file for reading: %w", err)
2019-06-15 00:11:51 +02:00
}
defer debugPrintError(file.Close, "Failed to close room list file after reading")
// Open gzip reader for room list file
cmpReader, err := gzip.NewReader(file)
if err != nil {
return fmt.Errorf("failed to read gzip room list: %w", err)
2019-06-15 00:11:51 +02:00
}
defer debugPrintError(cmpReader.Close, "Failed to close room list gzip reader")
// Open gob decoder for gzip reader
dec := gob.NewDecoder(cmpReader)
// Read number of items in list
var size int
err = dec.Decode(&size)
if err != nil {
return fmt.Errorf("failed to read size of room list: %w", err)
2019-06-15 00:11:51 +02:00
}
// Read list
cache.Map = make(map[id.RoomID]*Room, size)
2019-06-15 00:11:51 +02:00
for i := 0; i < size; i++ {
room := &Room{}
err = dec.Decode(room)
if err != nil {
debug.Printf("Failed to decode %dth room list entry: %v", i+1, err)
continue
}
room.path = cache.roomPath(room.ID)
room.cache = cache
cache.Map[room.ID] = room
}
return nil
}
func (cache *RoomCache) SaveLoadedRooms() {
cache.Lock()
2019-06-15 16:04:08 +02:00
cache.clean(false)
2019-06-15 00:11:51 +02:00
for node := cache.head; node != nil; node = node.prev {
node.Save()
}
2020-05-06 22:30:16 +02:00
cache.Unlock()
2019-06-15 00:11:51 +02:00
}
func (cache *RoomCache) SaveList() error {
cache.Lock()
defer cache.Unlock()
debug.Print("Saving room list...")
// Open room list file
file, err := os.OpenFile(cache.listPath, os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
return fmt.Errorf("failed to open room list file for writing: %w", err)
2019-06-15 00:11:51 +02:00
}
defer debugPrintError(file.Close, "Failed to close room list file after writing")
// Open gzip writer for room list file
cmpWriter := gzip.NewWriter(file)
defer debugPrintError(cmpWriter.Close, "Failed to close room list gzip writer")
// Open gob encoder for gzip writer
enc := gob.NewEncoder(cmpWriter)
// Write number of items in list
err = enc.Encode(len(cache.Map))
if err != nil {
return fmt.Errorf("failed to write size of room list: %w", err)
2019-06-15 00:11:51 +02:00
}
// Write list
for _, node := range cache.Map {
err = enc.Encode(node)
if err != nil {
debug.Printf("Failed to encode room list entry of %s: %v", node.ID, err)
}
}
debug.Print("Room list saved to", cache.listPath, len(cache.Map), cache.size)
return nil
}
func (cache *RoomCache) Touch(roomID id.RoomID) {
2019-06-15 00:11:51 +02:00
cache.Lock()
node, ok := cache.Map[roomID]
if !ok || node == nil {
cache.Unlock()
return
}
cache.touch(node)
cache.Unlock()
}
func (cache *RoomCache) TouchNode(node *Room) {
2020-05-06 22:30:16 +02:00
if cache.noUnload || node.touch+2 > time.Now().Unix() {
return
}
2019-06-15 00:11:51 +02:00
cache.Lock()
cache.touch(node)
cache.Unlock()
}
func (cache *RoomCache) touch(node *Room) {
if node == cache.head {
return
}
debug.Print("Touching", node.ID)
cache.llPop(node)
cache.llPush(node)
node.touch = time.Now().Unix()
}
func (cache *RoomCache) Get(roomID id.RoomID) *Room {
2019-06-15 00:11:51 +02:00
cache.Lock()
node := cache.get(roomID)
cache.Unlock()
return node
}
func (cache *RoomCache) GetOrCreate(roomID id.RoomID) *Room {
2019-06-15 00:11:51 +02:00
cache.Lock()
node := cache.get(roomID)
if node == nil {
node = cache.newRoom(roomID)
cache.llPush(node)
}
cache.Unlock()
return node
}
func (cache *RoomCache) get(roomID id.RoomID) *Room {
2019-06-15 00:11:51 +02:00
node, ok := cache.Map[roomID]
2019-06-15 16:04:08 +02:00
if ok && node != nil {
2019-06-15 00:11:51 +02:00
return node
}
return nil
}
2019-06-15 00:11:51 +02:00
func (cache *RoomCache) Put(room *Room) {
cache.Lock()
node := cache.get(room.ID)
if node != nil {
cache.touch(node)
} else {
cache.Map[room.ID] = room
if room.Loaded() {
cache.llPush(room)
}
node = room
}
cache.Unlock()
node.Save()
}
func (cache *RoomCache) roomPath(roomID id.RoomID) string {
escapedRoomID := strings.ReplaceAll(strings.ReplaceAll(string(roomID), "%", "%25"), "/", "%2F")
return filepath.Join(cache.directory, escapedRoomID+".gob.gz")
2019-06-15 00:11:51 +02:00
}
func (cache *RoomCache) Load(roomID id.RoomID) *Room {
2019-06-15 00:11:51 +02:00
cache.Lock()
defer cache.Unlock()
node, ok := cache.Map[roomID]
if ok {
return node
}
node = NewRoom(roomID, cache)
node.Load()
return node
}
func (cache *RoomCache) llPop(node *Room) {
if node.prev == nil && node.next == nil {
return
}
if node.prev != nil {
node.prev.next = node.next
}
if node.next != nil {
node.next.prev = node.prev
}
if node == cache.tail {
cache.tail = node.next
}
if node == cache.head {
cache.head = node.prev
}
node.next = nil
node.prev = nil
cache.size--
}
func (cache *RoomCache) llPush(node *Room) {
if node.next != nil || node.prev != nil {
debug.PrintStack()
debug.Print("Tried to llPush node that is already in stack")
return
}
if node == cache.head {
return
}
if cache.head != nil {
cache.head.next = node
}
node.prev = cache.head
node.next = nil
cache.head = node
if cache.tail == nil {
cache.tail = node
}
cache.size++
2019-06-15 16:04:08 +02:00
cache.clean(false)
}
func (cache *RoomCache) ForceClean() {
cache.Lock()
cache.clean(true)
cache.Unlock()
2019-06-15 00:11:51 +02:00
}
2019-06-15 16:04:08 +02:00
func (cache *RoomCache) clean(force bool) {
if cache.noUnload && !force {
return
}
2019-06-15 00:11:51 +02:00
origSize := cache.size
maxTS := time.Now().Unix() - cache.maxAge
for cache.size > cache.maxSize {
2019-06-15 16:04:08 +02:00
if cache.tail.touch > maxTS && !force {
2019-06-15 00:11:51 +02:00
break
}
2019-06-15 16:04:08 +02:00
ok := cache.tail.Unload()
node := cache.tail
cache.llPop(node)
if !ok {
debug.Print("Unload returned false, pushing node back")
cache.llPush(node)
}
2019-06-15 00:11:51 +02:00
}
if cleaned := origSize - cache.size; cleaned > 0 {
debug.Print("Cleaned", cleaned, "rooms")
}
}
func (cache *RoomCache) Unload(node *Room) {
cache.Lock()
defer cache.Unlock()
cache.llPop(node)
2019-06-15 16:04:08 +02:00
ok := node.Unload()
if !ok {
debug.Print("Unload returned false, pushing node back")
cache.llPush(node)
}
2019-06-15 00:11:51 +02:00
}
func (cache *RoomCache) newRoom(roomID id.RoomID) *Room {
2019-06-15 00:11:51 +02:00
node := NewRoom(roomID, cache)
cache.Map[node.ID] = node
return node
}