forked from writefreely/writefreely
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
69 lines (59 loc) · 1.2 KB
/
cache.go
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
/*
* Copyright © 2018 A Bunch Tell LLC.
*
* This file is part of WriteFreely.
*
* WriteFreely is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, included
* in the LICENSE file in this source code package.
*/
package writefreely
import (
"sync"
"time"
)
const (
postsCacheTime = 4 * time.Second
)
type (
postsCacheItem struct {
Expire time.Time
Posts *[]PublicPost
ready chan struct{}
}
AuthCache struct {
Alias, Pass, Token string
BadPasses map[string]bool
expire time.Time
}
)
var (
userPostsCache = struct {
sync.RWMutex
users map[int64]postsCacheItem
}{
users: map[int64]postsCacheItem{},
}
)
func CachePosts(userID int64, p *[]PublicPost) {
close(userPostsCache.users[userID].ready)
userPostsCache.Lock()
userPostsCache.users[userID] = postsCacheItem{
Expire: time.Now().Add(postsCacheTime),
Posts: p,
}
userPostsCache.Unlock()
}
func GetPostsCache(userID int64) *[]PublicPost {
userPostsCache.RLock()
pci, ok := userPostsCache.users[userID]
userPostsCache.RUnlock()
if !ok {
return nil
}
if pci.Expire.Before(time.Now()) {
// Cache is expired
return nil
}
return pci.Posts
}