Skip to content

Commit

Permalink
clean up cache.go
Browse files Browse the repository at this point in the history
  • Loading branch information
dimkr committed Oct 15, 2024
1 parent 3d3bdc5 commit 650a5b6
Showing 1 changed file with 12 additions and 12 deletions.
24 changes: 12 additions & 12 deletions front/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func (w chanWriter) Write(p []byte) (int, error) {
return len(p), nil
}

func callAndCache(r *Request, w text.Writer, args []string, f func(text.Writer, *Request, ...string), key string, now time.Time, cache *cacheEntry) {
func buildCache(r *Request, w text.Writer, args []string, f func(text.Writer, *Request, ...string), now time.Time) []byte {
c := make(chan []byte)

ctx, cancel := context.WithCancel(context.Background())
Expand Down Expand Up @@ -91,41 +91,41 @@ func callAndCache(r *Request, w text.Writer, args []string, f func(text.Writer,
w2.Textf("(Cached response generated on %s)", now.Format(time.UnixDate))
w2.Flush()

cache.Value = buf.Bytes()
cache.Created = now
return buf.Bytes()
}

func withCache(f func(text.Writer, *Request, ...string), d time.Duration, cfg *cfg.Config) func(text.Writer, *Request, ...string) {
cache := &cacheEntry{}
lock := semaphore.NewWeighted(1)

return func(w text.Writer, r *Request, args ...string) {
key := r.URL.String()
now := time.Now()

if err := lock.Acquire(r.Context, 1); err != nil {
r.Log.Warn("Failed to acquire cache lock", "key", key)
r.Log.Warn("Failed to acquire cache lock", "error", err)
w.Error()
return
}

now := time.Now()

if cache.Value == nil {
r.Log.Info("Generating first response", "key", key)
callAndCache(r, w, args, f, key, now, cache)
r.Log.Info("Generating first response")
cache.Value = buildCache(r, w, args, f, now)
cache.Created = now
lock.Release(1)
return
}

if cache.Created.After(now.Add(-d)) {
value := cache.Value
lock.Release(1)
r.Log.Info("Sending cached response", "key", key)
r.Log.Info("Sending cached response")
w.Write(value)
return
}

r.Log.Info("Generating new response", "key", key)
callAndCache(r, w, args, f, key, now, cache)
r.Log.Info("Generating new response")
cache.Value = buildCache(r, w, args, f, now)
cache.Created = now
lock.Release(1)
}
}

0 comments on commit 650a5b6

Please sign in to comment.