diff options
author | Steve Manuel <nilslice@gmail.com> | 2017-04-11 20:04:09 -0700 |
---|---|---|
committer | Steve Manuel <nilslice@gmail.com> | 2017-04-11 20:04:09 -0700 |
commit | cb2bca32efd00545b86fbcbd62abf379cf2c7144 (patch) | |
tree | 35315f3b6e2952cc814710cae90964eaa9efc701 | |
parent | 3c277a7c41aed0fe3e59fa1ccfd19b48d810b545 (diff) | |
parent | af644c49edf6272880b998496f0f4080dbddbc00 (diff) |
Merge branch 'throttle-sort' into ponzu-dev
-rw-r--r-- | system/db/content.go | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/system/db/content.go b/system/db/content.go index 5db2896..fbdd8dd 100644 --- a/system/db/content.go +++ b/system/db/content.go @@ -9,6 +9,7 @@ import ( "sort" "strconv" "strings" + "time" "github.com/ponzu-cms/ponzu/system/item" @@ -563,10 +564,54 @@ func Query(namespace string, opts QueryOptions) (int, [][]byte) { return total, posts } +var sortContentCalls = make(map[string]time.Time) +var waitDuration = time.Millisecond * 2000 + +func enoughTime(key string, withDelay bool) bool { + last, ok := sortContentCalls[key] + if !ok { + // no invocation yet + // track next invocation + sortContentCalls[key] = time.Now() + return true + } + + // if our required wait time has not been met, return false + if !time.Now().After(last.Add(waitDuration)) { + return false + } + + // dispatch a delayed envocation in case no additional one follows + if withDelay { + go func() { + select { + case <-time.After(waitDuration): + if enoughTime(key, false) { + // track next invocation + sortContentCalls[key] = time.Now() + SortContent(key) + } else { + // retrigger + SortContent(key) + } + } + }() + } + + // track next invocation + sortContentCalls[key] = time.Now() + return true +} + // SortContent sorts all content of the type supplied as the namespace by time, // in descending order, from most recent to least recent // Should be called from a goroutine after SetContent is successful func SortContent(namespace string) { + // wait if running too frequently per namespace + if !enoughTime(namespace, true) { + return + } + // only sort main content types i.e. Post if strings.Contains(namespace, "__") { return |