Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[#59] Add node states #60

Merged
merged 2 commits into from
Mar 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 23 additions & 2 deletions cmd/generator/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,10 @@ func newGenerator(nodeType string) *generator {
func (g *generator) printImports() {
g.p("import (")
g.in()
g.p("\"sync/atomic\"")
g.p("\"unsafe\"")
if g.features[expiration] {
g.p("")
g.p("\"github.com/maypok86/otter/internal/unixtime\"")
}
g.out()
Expand Down Expand Up @@ -178,6 +180,7 @@ func (g *generator) printStruct() {
g.p("cost uint32")
}

g.p("state uint32")
g.p("frequency uint8")
g.p("queueType uint8")
g.out()
Expand All @@ -199,6 +202,7 @@ func (g *generator) printConstructors() {
if g.features[cost] {
g.p("cost: cost,")
}
g.p("state: aliveState,")
g.out()
g.p("}")
g.out()
Expand Down Expand Up @@ -365,6 +369,14 @@ func (g *generator) printFunctions() {
g.p("}")

const otherFunctions = `
func (n *%s[K, V]) IsAlive() bool {
return atomic.LoadUint32(&n.state) == aliveState
}

func (n *%s[K, V]) Die() {
atomic.StoreUint32(&n.state, deadState)
}

func (n *%s[K, V]) Frequency() uint8 {
return n.frequency
}
Expand Down Expand Up @@ -460,6 +472,11 @@ const (
maxFrequency uint8 = 3
)

const (
aliveState uint32 = iota
deadState
)

// Node is a cache entry.
type Node[K comparable, V any] interface {
// Key returns the key.
Expand Down Expand Up @@ -490,6 +507,10 @@ type Node[K comparable, V any] interface {
Expiration() uint32
// Cost returns the cost of the node.
Cost() uint32
// IsAlive returns true if the entry is available in the hash-table.
IsAlive() bool
// Die sets the node to the dead state.
Die()
// Frequency returns the frequency of the node.
Frequency() uint8
// IncrementFrequency increments the frequency of the node.
Expand Down Expand Up @@ -522,11 +543,11 @@ func Equals[K comparable, V any](a, b Node[K, V]) bool {

type Config struct {
WithExpiration bool
WithCost bool
WithCost bool
}

type Manager[K comparable, V any] struct {
create func(key K, value V, expiration, cost uint32) Node[K, V]
create func(key K, value V, expiration, cost uint32) Node[K, V]
fromPointer func(ptr unsafe.Pointer) Node[K, V]
}

Expand Down
95 changes: 58 additions & 37 deletions internal/core/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ import (
"github.com/maypok86/otter/internal/queue"
"github.com/maypok86/otter/internal/s3fifo"
"github.com/maypok86/otter/internal/stats"
"github.com/maypok86/otter/internal/task"
"github.com/maypok86/otter/internal/unixtime"
"github.com/maypok86/otter/internal/xmath"
"github.com/maypok86/otter/internal/xruntime"
Expand Down Expand Up @@ -68,7 +67,7 @@ type Cache[K comparable, V any] struct {
expirePolicy expirePolicy[K, V]
stats *stats.Stats
readBuffers []*lossy.Buffer[K, V]
writeBuffer *queue.MPSC[task.WriteTask[K, V]]
writeBuffer *queue.MPSC[task[K, V]]
evictionMutex sync.Mutex
closeOnce sync.Once
doneClear chan struct{}
Expand Down Expand Up @@ -120,7 +119,7 @@ func NewCache[K comparable, V any](c Config[K, V]) *Cache[K, V] {
policy: s3fifo.NewPolicy[K, V](uint32(c.Capacity)),
expirePolicy: expPolicy,
readBuffers: readBuffers,
writeBuffer: queue.NewMPSC[task.WriteTask[K, V]](writeBufferCapacity),
writeBuffer: queue.NewMPSC[task[K, V]](writeBufferCapacity),
doneClear: make(chan struct{}),
mask: uint32(readBuffersCount - 1),
costFunc: c.CostFunc,
Expand Down Expand Up @@ -159,13 +158,13 @@ func (c *Cache[K, V]) Has(key K) bool {
// Get returns the value associated with the key in this cache.
func (c *Cache[K, V]) Get(key K) (V, bool) {
got, ok := c.hashmap.Get(key)
if !ok {
if !ok || !got.IsAlive() {
c.stats.IncMisses()
return zeroValue[V](), false
}

if got.IsExpired() {
c.writeBuffer.Insert(task.NewDeleteTask(got))
c.writeBuffer.Insert(newDeleteTask(got))
c.stats.IncMisses()
return zeroValue[V](), false
}
Expand Down Expand Up @@ -240,7 +239,7 @@ func (c *Cache[K, V]) set(key K, value V, expiration uint32, onlyIfAbsent bool)
res := c.hashmap.SetIfAbsent(n)
if res == nil {
// insert
c.writeBuffer.Insert(task.NewAddTask(n))
c.writeBuffer.Insert(newAddTask(n))
return true
}
return false
Expand All @@ -249,34 +248,36 @@ func (c *Cache[K, V]) set(key K, value V, expiration uint32, onlyIfAbsent bool)
evicted := c.hashmap.Set(n)
if evicted != nil {
// update
c.writeBuffer.Insert(task.NewUpdateTask(n, evicted))
evicted.Die()
c.writeBuffer.Insert(newUpdateTask(n, evicted))
} else {
// insert
c.writeBuffer.Insert(task.NewAddTask(n))
c.writeBuffer.Insert(newAddTask(n))
}

return true
}

// Delete removes the association for this key from the cache.
func (c *Cache[K, V]) Delete(key K) {
deleted := c.hashmap.Delete(key)
if deleted != nil {
c.writeBuffer.Insert(task.NewDeleteTask(deleted))
}
c.afterDelete(c.hashmap.Delete(key))
}

func (c *Cache[K, V]) deleteNode(n node.Node[K, V]) {
deleted := c.hashmap.DeleteNode(n)
c.afterDelete(c.hashmap.DeleteNode(n))
}

func (c *Cache[K, V]) afterDelete(deleted node.Node[K, V]) {
if deleted != nil {
c.writeBuffer.Insert(task.NewDeleteTask(deleted))
deleted.Die()
c.writeBuffer.Insert(newDeleteTask(deleted))
}
}

// DeleteByFunc removes the association for this key from the cache when the given function returns true.
func (c *Cache[K, V]) DeleteByFunc(f func(key K, value V) bool) {
c.hashmap.Range(func(n node.Node[K, V]) bool {
if n.IsExpired() {
if !n.IsAlive() || n.IsExpired() {
return true
}

Expand All @@ -289,7 +290,8 @@ func (c *Cache[K, V]) DeleteByFunc(f func(key K, value V) bool) {
}

func (c *Cache[K, V]) cleanup() {
expired := make([]node.Node[K, V], 0, 128)
bufferCapacity := 64
expired := make([]node.Node[K, V], 0, bufferCapacity)
for {
time.Sleep(time.Second)

Expand All @@ -298,41 +300,47 @@ func (c *Cache[K, V]) cleanup() {
return
}

e := c.expirePolicy.RemoveExpired(expired)
c.policy.Delete(e)
expired = c.expirePolicy.RemoveExpired(expired)
for _, n := range expired {
c.policy.Delete(n)
}

c.evictionMutex.Unlock()

for _, n := range e {
for _, n := range expired {
c.hashmap.DeleteNode(n)
n.Die()
}

expired = clearBuffer(expired)
if cap(expired) > 3*bufferCapacity {
expired = make([]node.Node[K, V], 0, bufferCapacity)
}
}
}

func (c *Cache[K, V]) process() {
bufferCapacity := 64
buffer := make([]task.WriteTask[K, V], 0, bufferCapacity)
buffer := make([]task[K, V], 0, bufferCapacity)
deleted := make([]node.Node[K, V], 0, bufferCapacity)
i := 0
for {
t := c.writeBuffer.Remove()

if t.IsClear() || t.IsClose() {
if t.isClear() || t.isClose() {
buffer = clearBuffer(buffer)
c.writeBuffer.Clear()

c.evictionMutex.Lock()
c.policy.Clear()
c.expirePolicy.Clear()
if t.IsClose() {
if t.isClose() {
c.isClosed = true
}
c.evictionMutex.Unlock()

c.doneClear <- struct{}{}
if t.IsClose() {
if t.isClose() {
break
}
continue
Expand All @@ -346,30 +354,43 @@ func (c *Cache[K, V]) process() {
c.evictionMutex.Lock()

for _, t := range buffer {
n := t.node()
switch {
case t.IsDelete():
c.expirePolicy.Delete(t.Node())
case t.IsAdd():
c.expirePolicy.Add(t.Node())
case t.IsUpdate():
c.expirePolicy.Delete(t.OldNode())
c.expirePolicy.Add(t.Node())
case t.isDelete():
c.expirePolicy.Delete(n)
c.policy.Delete(n)
case t.isAdd():
if n.IsAlive() {
c.expirePolicy.Add(n)
deleted = c.policy.Add(deleted, n)
}
case t.isUpdate():
oldNode := t.oldNode()
c.expirePolicy.Delete(oldNode)
c.policy.Delete(oldNode)
if n.IsAlive() {
c.expirePolicy.Add(n)
deleted = c.policy.Add(deleted, n)
}
}
}

d := c.policy.Write(deleted, buffer)
for _, n := range d {
for _, n := range deleted {
c.expirePolicy.Delete(n)
}

c.evictionMutex.Unlock()

for _, n := range d {
for _, n := range deleted {
c.hashmap.DeleteNode(n)
n.Die()
}

buffer = clearBuffer(buffer)
deleted = clearBuffer(deleted)
if cap(deleted) > 3*bufferCapacity {
deleted = make([]node.Node[K, V], 0, bufferCapacity)
}
}
}
}
Expand All @@ -379,7 +400,7 @@ func (c *Cache[K, V]) process() {
// Iteration stops early when the given function returns false.
func (c *Cache[K, V]) Range(f func(key K, value V) bool) {
c.hashmap.Range(func(n node.Node[K, V]) bool {
if n.IsExpired() {
if !n.IsAlive() || n.IsExpired() {
return true
}

Expand All @@ -391,10 +412,10 @@ func (c *Cache[K, V]) Range(f func(key K, value V) bool) {
//
// NOTE: this operation must be performed when no requests are made to the cache otherwise the behavior is undefined.
func (c *Cache[K, V]) Clear() {
c.clear(task.NewClearTask[K, V]())
c.clear(newClearTask[K, V]())
}

func (c *Cache[K, V]) clear(t task.WriteTask[K, V]) {
func (c *Cache[K, V]) clear(t task[K, V]) {
c.hashmap.Clear()
for i := 0; i < len(c.readBuffers); i++ {
c.readBuffers[i].Clear()
Expand All @@ -411,7 +432,7 @@ func (c *Cache[K, V]) clear(t task.WriteTask[K, V]) {
// NOTE: this operation must be performed when no requests are made to the cache otherwise the behavior is undefined.
func (c *Cache[K, V]) Close() {
c.closeOnce.Do(func() {
c.clear(task.NewCloseTask[K, V]())
c.clear(newCloseTask[K, V]())
if c.withExpiration {
unixtime.Stop()
}
Expand Down
Loading
Loading