roomHistoryTimelineRepo.go 10.4 KB
Newer Older
T
tanggen 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
// Copyright (C) 2020 Finogeeks Co., Ltd
//
// This program is free software: you can redistribute it and/or  modify
// it under the terms of the GNU Affero General Public License, version 3,
// as published by the Free Software Foundation.
//
// 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 <http://www.gnu.org/licenses/>.

package repos

import (
	"context"
	"sync"
	"time"

	mon "github.com/finogeeks/ligase/skunkworks/monitor/go-client/monitor"

	"github.com/finogeeks/ligase/model/feedstypes"
	"github.com/finogeeks/ligase/model/syncapitypes"
	"github.com/finogeeks/ligase/model/types"
	"github.com/finogeeks/ligase/skunkworks/gomatrixserverlib"
	"github.com/finogeeks/ligase/skunkworks/log"
	"github.com/finogeeks/ligase/storage/model"
)

type RoomHistoryTimeLineRepo struct {
	repo                   *TimeLineRepo
	persist                model.SyncAPIDatabase
	loading                sync.Map
	ready                  sync.Map
	roomLatest             sync.Map //room latest offset
	roomMutex              *sync.Mutex
	roomMinStream          sync.Map
	domainMaxOffset        sync.Map
	loadingDomainMaxOffset sync.Map

	queryHitCounter mon.LabeledCounter
}

func NewRoomHistoryTimeLineRepo(
	bukSize,
	maxEntries,
	gcPerNum int,
) *RoomHistoryTimeLineRepo {
	tls := new(RoomHistoryTimeLineRepo)
	tls.repo = NewTimeLineRepo(bukSize, 128, true, maxEntries, gcPerNum)
	tls.roomMutex = new(sync.Mutex)

	return tls
}

func (tl *RoomHistoryTimeLineRepo) SetPersist(db model.SyncAPIDatabase) {
	tl.persist = db
}

func (tl *RoomHistoryTimeLineRepo) SetMonitor(queryHitCounter mon.LabeledCounter) {
	tl.queryHitCounter = queryHitCounter
}

func (tl *RoomHistoryTimeLineRepo) AddEv(ctx context.Context, ev *gomatrixserverlib.ClientEvent, offset int64, load bool) {
	if load == true && ev.Type != "m.room.create" {
		tl.LoadHistory(ctx, ev.RoomID, true)
	}

	sev := new(feedstypes.StreamEvent)
	sev.Ev = ev
	sev.Offset = offset
	tl.repo.add(ev.RoomID, sev)
	if sev.Ev.StateKey != nil {
		log.Infof("update roomHistoryTimeineRepo sender:%s,statekey:%s,room:%s,offset:%d", sev.Ev.Sender, *sev.Ev.StateKey, sev.Ev.RoomID, sev.Offset)
	} else {
		log.Infof("update roomHistoryTimeineRepo sender:%s,room:%s,offset:%d", sev.Ev.Sender, sev.Ev.RoomID, sev.Offset)
	}
	tl.setRoomLatest(ev.RoomID, offset)
}

func (tl *RoomHistoryTimeLineRepo) loadHistory(ctx context.Context, roomID string) {
	defer tl.loading.Delete(roomID)

	bs := time.Now().UnixNano() / 1000000
	evs, offsets, err := tl.persist.GetHistoryEvents(ctx, roomID, 30) //注意是倒序的event,需要排列下
	spend := time.Now().UnixNano()/1000000 - bs
	if err != nil {
		log.Errorf("load db failed RoomHistoryTimeLineRepo load room:%s history spend:%d ms err:%v", roomID, spend, err)
		return
	}
	if spend > types.DB_EXCEED_TIME {
		log.Warnf("load db exceed %d ms RoomHistoryTimeLineRepo.loadHistory finished room:%s spend:%d ms", types.DB_EXCEED_TIME, roomID, spend)
	} else {
		log.Infof("load db succ RoomHistoryTimeLineRepo.loadHistory finished room:%s spend:%d ms", roomID, spend)
	}
	length := len(evs)
	for i := 0; i < length/2; i++ {
		ev := evs[i]
		evs[i] = evs[length-1-i]
		evs[length-1-i] = ev

		off := offsets[i]
		offsets[i] = offsets[length-1-i]
		offsets[length-1-i] = off
	}

	for idx := range evs {
		tl.AddEv(ctx, &evs[idx], offsets[idx], false)
	}

	tl.ready.Store(roomID, true)

}

func (tl *RoomHistoryTimeLineRepo) LoadHistory(ctx context.Context, roomID string, sync bool) {
	if _, ok := tl.ready.Load(roomID); !ok {
		if _, ok := tl.loading.Load(roomID); !ok {
			tl.loading.Store(roomID, true)
			if sync == false {
				go tl.loadHistory(ctx, roomID)
			} else {
				tl.loadHistory(ctx, roomID)
			}

			tl.queryHitCounter.WithLabelValues("db", "RoomHistoryTimeLineRepo", "LoadHistory").Add(1)
		} else {
			if sync == false {
				return
			}
			tl.CheckLoadReady(ctx, roomID, true)
		}
	} else {
		res := tl.repo.getTimeLine(roomID)
		if res == nil {
			tl.ready.Delete(roomID)
			tl.LoadHistory(ctx, roomID, sync)
		} else {
			tl.queryHitCounter.WithLabelValues("db", "RoomHistoryTimeLineRepo", "LoadHistory").Add(1)
		}
	}
}

func (tl *RoomHistoryTimeLineRepo) CheckLoadReady(ctx context.Context, roomID string, sync bool) bool {
	_, ok := tl.ready.Load(roomID)
	if ok || sync == false {
		if sync == false {
			tl.LoadHistory(ctx, roomID, false)
		}
		return ok
	}

	start := time.Now().Unix()
	for {
		if _, ok := tl.ready.Load(roomID); ok {
			break
		}

		tl.LoadHistory(ctx, roomID, false)

		now := time.Now().Unix()
		if now-start > 35 {
			log.Errorf("checkloadready failed RoomHistoryTimeLineRepo.CheckLoadReady room %s spend:%d s but still not ready, break", roomID, now-start)
			break
		}

		time.Sleep(time.Millisecond * 50)
	}

	_, ok = tl.ready.Load(roomID)
	return ok
}

func (tl *RoomHistoryTimeLineRepo) GetHistory(ctx context.Context, roomID string) *feedstypes.TimeLines {
	tl.LoadHistory(ctx, roomID, true)
	return tl.repo.getTimeLine(roomID)
}

func (tl *RoomHistoryTimeLineRepo) GetStreamEv(ctx context.Context, roomID, eventId string) *feedstypes.StreamEvent {
	history := tl.GetHistory(ctx, roomID)
	if history == nil {
		return nil
	}

	var sev *feedstypes.StreamEvent
	history.ForRangeReverse(func(offset int, feed feedstypes.Feed) bool {
		if feed != nil {
			stream := feed.(*feedstypes.StreamEvent)
			if stream.GetEv().EventID == eventId {
				sev = stream
				return false
			}
			return true
		}
		return true
	})

	return sev
}

func (tl *RoomHistoryTimeLineRepo) GetLastEvent(ctx context.Context, roomID string) *feedstypes.StreamEvent {
	history := tl.GetHistory(ctx, roomID)
	if history == nil {
		return nil
	}

	var sev *feedstypes.StreamEvent
	history.ForRangeReverse(func(offset int, feed feedstypes.Feed) bool {
		if feed != nil {
			sev = feed.(*feedstypes.StreamEvent)
			return false
		}
		return true
	})
	return sev
}

func (tl *RoomHistoryTimeLineRepo) GetRoomLastOffset(roomID string) int64 {
	if val, ok := tl.roomLatest.Load(roomID); ok {
		return val.(int64)
	}

	return int64(-1)
}

func (tl *RoomHistoryTimeLineRepo) GetRoomMinStream(ctx context.Context, roomID string) int64 {
	if val, ok := tl.roomMinStream.Load(roomID); ok {
		tl.queryHitCounter.WithLabelValues("cache", "RoomHistoryTimeLineRepo", "GetRoomMinStream").Add(1)
		return val.(int64)
	}
	bs := time.Now().UnixNano() / 1000000
	pos, err := tl.persist.SelectOutputMinStream(ctx, roomID)
	spend := time.Now().UnixNano()/1000000 - bs
	if err != nil {
		log.Errorf("load db failed RoomHistoryTimeLineRepo.SelectOutputMinStream roomID:%s spend:%d ms err %v", roomID, spend, err)
		return -1
	}
	if spend > types.DB_EXCEED_TIME {
		log.Warnf("load db exceed %d ms RoomHistoryTimeLineRepo.SelectOutputMinStream roomID:%s spend:%d ms", types.DB_EXCEED_TIME, roomID, spend)
	} else {
		log.Infof("load db succ RoomHistoryTimeLineRepo.SelectOutputMinStream roomID:%s spend:%d ms", roomID, spend)
	}
	val, _ := tl.roomMinStream.LoadOrStore(roomID, pos)
	pos = val.(int64)

	tl.queryHitCounter.WithLabelValues("db", "RoomHistoryTimeLineRepo", "GetRoomMinStream").Add(1)

	return pos
}

func (tl *RoomHistoryTimeLineRepo) SetRoomMinStream(roomID string, minStream int64) {
	tl.roomMinStream.Store(roomID, minStream)
}

func (tl *RoomHistoryTimeLineRepo) GetDomainMaxStream(ctx context.Context, roomID, domain string) int64 {
	for {
		if val, ok := tl.domainMaxOffset.Load(roomID); !ok {
			if _, loaded := tl.loadingDomainMaxOffset.LoadOrStore(roomID, true); loaded {
				time.Sleep(time.Millisecond * 3)
				continue
			} else {
				defer tl.loadingDomainMaxOffset.Delete(roomID)
				domains, offsets, err := tl.persist.SelectDomainMaxOffset(ctx, roomID)
				if err != nil {
					log.Errorf("RoomHistoryTimeLineRepo GetDomainMaxStream roomID %s err %v", roomID, err)
					return -1
				}
				domainMap := new(sync.Map)
				for index, domain := range domains {
					domainMap.Store(domain, offsets[index])
				}
				tl.domainMaxOffset.Store(roomID, domainMap)
				if val, ok := domainMap.Load(domain); ok {
					tl.queryHitCounter.WithLabelValues("db", "RoomHistoryTimeLineRepo", "GetDomainMaxStream").Add(1)

					return val.(int64)
				}
				return -1
			}
		} else {
			if val, ok := val.(*sync.Map).Load(domain); ok {
				tl.queryHitCounter.WithLabelValues("cache", "RoomHistoryTimeLineRepo", "GetDomainMaxStream").Add(1)

				return val.(int64)
			}
			return -1
		}
	}
}

func (tl *RoomHistoryTimeLineRepo) SetDomainMaxStream(roomID, domain string, offset int64) {
	val, ok := tl.domainMaxOffset.Load(roomID)
	if !ok {
		val, _ = tl.domainMaxOffset.LoadOrStore(roomID, new(sync.Map))
	}
	val.(*sync.Map).Store(domain, offset)
}

func (tl *RoomHistoryTimeLineRepo) setRoomLatest(roomID string, offset int64) {
	tl.roomMutex.Lock()
	defer tl.roomMutex.Unlock()

	val, ok := tl.roomLatest.Load(roomID)
	if ok {
		lastoffset := val.(int64)
		if offset > lastoffset {
			log.Debugf("update roomId:%s lastoffset:%d,offset:%d", roomID, lastoffset, offset)
			tl.roomLatest.Store(roomID, offset)
		}
	} else {
		log.Debugf("update roomId:%s first offset:%d ", roomID, offset)
		tl.roomLatest.Store(roomID, offset)
	}
}

func (tl *RoomHistoryTimeLineRepo) LoadRoomLatest(ctx context.Context, rooms []syncapitypes.SyncRoom) error {
	var loadRooms []string
	for _, room := range rooms {
		_, ok := tl.roomLatest.Load(room.RoomID)
		if !ok {
			loadRooms = append(loadRooms, room.RoomID)
		}
	}

	if len(loadRooms) > 0 {
		bs := time.Now().UnixNano() / 1000000
		roomMap, err := tl.persist.GetRoomLastOffsets(ctx, loadRooms)
		spend := time.Now().UnixNano()/1000000 - bs
		if err != nil {
			log.Errorf("load db failed RoomHistoryTimeLineRepo.LoadRoomLatest spend:%d ms err:%v", spend, err)
			return err
		}
		if spend > types.DB_EXCEED_TIME {
			log.Warnf("load db exceed %d ms RoomHistoryTimeLineRepo.LoadRoomLatest spend:%d ms", types.DB_EXCEED_TIME, spend)
		} else {
			log.Infof("load db succ RoomHistoryTimeLineRepo.LoadRoomLatest spend:%d ms", spend)
		}
		if roomMap != nil {
			for roomID, offset := range roomMap {
				tl.setRoomLatest(roomID, offset)
			}
		}

		tl.queryHitCounter.WithLabelValues("db", "RoomHistoryTimeLineRepo", "LoadRoomLatest").Add(1)
	} else {
		tl.queryHitCounter.WithLabelValues("cache", "RoomHistoryTimeLineRepo", "LoadRoomLatest").Add(1)
	}
	return nil
}