Files
gocommon/session/consumer_common.go

79 lines
1.6 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[string]T
deleted map[string]bool
}
func make_cache_stage[T any]() *cache_stage[T] {
return &cache_stage[T]{
cache: make(map[string]T),
deleted: make(map[string]bool),
}
}
type Consumer interface {
2023-08-30 16:35:22 +09:00
Query(string) *Authorization
Touch(string) 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(key string, si T) {
c.stages[0].cache[key] = si
delete(c.stages[0].deleted, key)
c.stages[1].cache[key] = si
delete(c.stages[1].deleted, key)
logger.Printf("add : %v, %v\n", *c.stages[0], *c.stages[1])
}
func (c *consumer_common[T]) add(key string, si T) {
c.lock.Lock()
defer c.lock.Unlock()
c.add_internal(key, si)
}
func (c *consumer_common[T]) delete_internal(key string) {
delete(c.stages[0].cache, key)
c.stages[0].deleted[key] = true
delete(c.stages[1].cache, key)
c.stages[1].deleted[key] = true
logger.Printf("delete : %v, %v\n", *c.stages[0], *c.stages[1])
}
func (c *consumer_common[T]) delete(key string) {
c.lock.Lock()
defer c.lock.Unlock()
c.delete_internal(key)
}
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])
}