Files
gocommon/session/consumer_common.go

74 lines
1.5 KiB
Go
Raw Normal View History

2023-08-30 15:43:26 +09:00
package session
import (
"context"
"sync"
"time"
"repositories.action2quare.com/ayo/gocommon/logger"
)
type cache_stage[T any] struct {
cache map[storagekey]T
deleted map[storagekey]bool
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),
deleted: make(map[storagekey]bool),
2023-08-30 15:43:26 +09:00
}
}
type consumer_common[T any] struct {
lock sync.Mutex
ttl time.Duration
ctx context.Context
stages [2]*cache_stage[T]
startTime time.Time
}
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
logger.Printf("add : %v, %v\n", *c.stages[0], *c.stages[1])
}
func (c *consumer_common[T]) add(sk storagekey, si T) {
2023-08-30 15:43:26 +09:00
c.lock.Lock()
defer c.lock.Unlock()
c.add_internal(sk, si)
2023-08-30 15:43:26 +09:00
}
func (c *consumer_common[T]) delete_internal(sk storagekey) {
delete(c.stages[0].cache, sk)
c.stages[0].deleted[sk] = true
delete(c.stages[1].cache, sk)
c.stages[1].deleted[sk] = true
2023-08-30 15:43:26 +09:00
logger.Printf("delete : %v, %v\n", *c.stages[0], *c.stages[1])
}
func (c *consumer_common[T]) delete(sk storagekey) {
2023-08-30 15:43:26 +09:00
c.lock.Lock()
defer c.lock.Unlock()
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()
logger.Printf("changeStage : %v, %v\n", *c.stages[0], *c.stages[1])
c.stages[1] = c.stages[0]
c.stages[0] = make_cache_stage[T]()
logger.Printf("---> : %v, %v\n", *c.stages[0], *c.stages[1])
}