Welcome to mirror list, hosted at ThFree Co, Russian Federation.

memstore.go « cache « gitlab « source « internal - gitlab.com/gitlab-org/gitlab-pages.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 721a2b0a4723449954e09aeed21ca58bd59a9607 (plain)
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
package cache

import (
	"sync"
	"time"

	"github.com/patrickmn/go-cache"

	"gitlab.com/gitlab-org/gitlab-pages/internal/config"
)

type memstore struct {
	store                  *cache.Cache
	mux                    *sync.RWMutex
	entryRefreshTimeout    time.Duration
	entryExpirationTimeout time.Duration
}

func newMemStore(cc *config.Cache) Store {
	return &memstore{
		store:                  cache.New(cc.CacheExpiry, cc.CacheCleanupInterval),
		mux:                    &sync.RWMutex{},
		entryRefreshTimeout:    cc.EntryRefreshTimeout,
		entryExpirationTimeout: cc.CacheExpiry,
	}
}

// LoadOrCreate writes or retrieves a domain entry from the cache in a
// thread-safe way, trying to make this read-preferring RW locking.
func (m *memstore) LoadOrCreate(domain string) *Entry {
	m.mux.RLock()
	entry, exists := m.store.Get(domain)
	m.mux.RUnlock()

	if exists {
		return entry.(*Entry)
	}

	m.mux.Lock()
	defer m.mux.Unlock()

	if entry, exists = m.store.Get(domain); exists {
		return entry.(*Entry)
	}

	newEntry := newCacheEntry(domain, m.entryRefreshTimeout, m.entryExpirationTimeout)
	m.store.SetDefault(domain, newEntry)

	return newEntry
}

func (m *memstore) ReplaceOrCreate(domain string, entry *Entry) *Entry {
	m.mux.Lock()
	defer m.mux.Unlock()

	m.store.Delete(domain)
	m.store.SetDefault(domain, entry)

	return entry
}