about summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorBen Morrison <ben@gbmor.dev>2020-05-09 14:48:55 -0400
committerBen Morrison <ben@gbmor.dev>2020-05-09 14:48:55 -0400
commitd55a6f801394ec9dccf9b51b662d35b4f53e1f5a (patch)
treec99b5462404830773ade647ea150e4d0451d904f
parent707e45702f7aed6d0a0f12c68f235f0fe8bdd9a1 (diff)
downloadapi-d55a6f801394ec9dccf9b51b662d35b4f53e1f5a.tar.gz
removed race condition when checking if a page is null
will now lock for the duration of the null check.
changed unNullPage(requestPath) to a method on the cacheWrapper
type called checkedInit(requestPath) as this is more descriptive.
-rw-r--r--cache.go15
1 files changed, 6 insertions, 9 deletions
diff --git a/cache.go b/cache.go
index 9ec1109..bc3ab3e 100644
--- a/cache.go
+++ b/cache.go
@@ -30,18 +30,15 @@ var cache = &cacheWrapper{
 
 // Checks if a page exists in the cache already.
 // If it doesn't, creates an empty entry.
-func unNullPage(path string) {
-	cache.RLock()
-	pageBlob := cache.pages[path]
-	cache.RUnlock()
+func (cache *cacheWrapper) checkedInit(path string) {
+	cache.Lock()
+	defer cache.Unlock()
 
-	if pageBlob == nil {
-		cache.Lock()
+	if cache.pages[path] == nil {
 		cache.pages[path] = &page{
 			raw:     []byte{},
 			expires: time.Time{},
 		}
-		cache.Unlock()
 	}
 }
 
@@ -65,7 +62,7 @@ func (cache *cacheWrapper) bap(requestPath string) {
 	format := split[0]
 	query := split[1]
 
-	unNullPage(requestPath)
+	cache.checkedInit(requestPath)
 
 	if cache.isFresh(requestPath) {
 		return
@@ -111,7 +108,7 @@ func (cache *cacheWrapper) yoink(path string) ([]byte, string) {
 // the index. If so, it yoinks the page from disk and
 // sets the expiration time.
 func bapIndex() {
-	unNullPage("/")
+	cache.checkedInit("/")
 
 	if cache.isFresh("/") {
 		return