From c38fbc474c6d646ef98798cce71096bd672a26d4 Mon Sep 17 00:00:00 2001 From: Kelvin Ly Date: Wed, 27 Sep 2023 23:09:29 -0400 Subject: [PATCH] Speed up latest entry lookup by using the cache if it's not empty --- shroom_internals/cache.go | 14 ++++++++++++++ shroom_server.go | 13 +++++++++++++ 2 files changed, 27 insertions(+) diff --git a/shroom_internals/cache.go b/shroom_internals/cache.go index f1c43f4..c9824aa 100644 --- a/shroom_internals/cache.go +++ b/shroom_internals/cache.go @@ -12,6 +12,20 @@ type DataCache struct { start int } +func (dc *DataCache) LatestTime() int64 { + dc.Lock() + defer dc.Unlock() + + if len(dc.data) == 0 { + return -1 + } + if dc.start == 0 { + return int64(dc.data[len(dc.data)-1].Time) + } else { + return int64(dc.data[dc.start-1].Time) + } +} + func (dc *DataCache) Add(data *Datapoint) { dc.Lock() defer dc.Unlock() diff --git a/shroom_server.go b/shroom_server.go index e9472a2..3718997 100644 --- a/shroom_server.go +++ b/shroom_server.go @@ -106,6 +106,19 @@ func main() { dumpSecond := dumpData(db, &state.Cache, 1000) lastPoint := func(w http.ResponseWriter, _req *http.Request) { + var err error + time := state.Cache.LatestTime() + if time > 0 { + msg, err := json.Marshal(time) + if err != nil { + w.WriteHeader(500) + w.Write([]byte(err.Error())) + } else { + w.Write(msg) + } + return + } + msg, err := s.LastTime(db) if err != nil { w.WriteHeader(500)