Files
gocommon/session/consumer_common.go

69 lines
1.4 KiB
Go
Raw Permalink Normal View History

2023-08-30 15:43:26 +09:00
package session
import (
"context"
"sync"
"time"
)
type cache_stage[T any] struct {
cache map[storagekey]T
2024-02-21 12:08:33 +09:00
deleted map[storagekey]T
2023-08-30 15:43:26 +09:00
}
func make_cache_stage[T any]() *cache_stage[T] {
return &cache_stage[T]{
cache: make(map[storagekey]T),
2024-02-21 12:08:33 +09:00
deleted: make(map[storagekey]T),
2023-08-30 15:43:26 +09:00
}
}
type consumer_common[T any] struct {
2023-12-25 22:06:57 +09:00
lock sync.Mutex
ttl time.Duration
ctx context.Context
stages [2]*cache_stage[T]
startTime time.Time
onSessionInvalidated []func(InvalidatedSession)
2023-08-30 15:43:26 +09:00
}
func (c *consumer_common[T]) add_internal(sk storagekey, si T) {
c.stages[0].cache[sk] = si
delete(c.stages[0].deleted, sk)
c.stages[1].cache[sk] = si
delete(c.stages[1].deleted, sk)
2023-08-30 15:43:26 +09:00
}
2023-12-25 22:06:57 +09:00
func (c *consumer_common[T]) delete_internal(sk storagekey) (old T) {
if v, ok := c.stages[0].cache[sk]; ok {
old = v
2024-02-21 12:08:33 +09:00
c.stages[0].deleted[sk] = old
c.stages[1].deleted[sk] = old
2023-12-25 22:06:57 +09:00
delete(c.stages[0].cache, sk)
delete(c.stages[1].cache, sk)
} else if v, ok = c.stages[1].cache[sk]; ok {
old = v
2024-02-21 12:08:33 +09:00
c.stages[1].deleted[sk] = old
2023-12-25 22:06:57 +09:00
delete(c.stages[1].cache, sk)
}
2024-02-21 12:08:33 +09:00
2023-12-25 22:06:57 +09:00
return
2023-08-30 15:43:26 +09:00
}
2023-12-25 22:06:57 +09:00
func (c *consumer_common[T]) delete(sk storagekey) T {
2023-08-30 15:43:26 +09:00
c.lock.Lock()
defer c.lock.Unlock()
2023-12-25 22:06:57 +09:00
return c.delete_internal(sk)
2023-08-30 15:43:26 +09:00
}
func (c *consumer_common[T]) changeStage() {
c.lock.Lock()
defer c.lock.Unlock()
c.stages[1] = c.stages[0]
c.stages[0] = make_cache_stage[T]()
}