wp-go/cache/slice.go

95 lines
1.7 KiB
Go
Raw Normal View History

2022-09-19 09:39:00 +00:00
package cache
import (
2022-09-20 04:00:09 +00:00
"context"
2022-09-20 08:11:20 +00:00
"errors"
"fmt"
2022-10-14 09:15:43 +00:00
"github/fthvgb1/wp-go/safety"
2022-09-19 09:39:00 +00:00
"sync"
"time"
)
type SliceCache[T any] struct {
2022-10-14 09:15:43 +00:00
v safety.Var[slice[T]]
}
type slice[T any] struct {
2022-09-19 09:39:00 +00:00
data []T
mutex *sync.Mutex
2022-09-20 04:00:09 +00:00
setCacheFunc func(...any) ([]T, error)
2022-09-19 09:39:00 +00:00
expireTime time.Duration
setTime time.Time
2022-09-20 04:00:09 +00:00
incr int
2022-09-19 09:39:00 +00:00
}
2022-10-07 12:37:42 +00:00
func (c *SliceCache[T]) SetTime() time.Time {
2022-10-14 09:15:43 +00:00
return c.v.Load().setTime
2022-10-07 12:37:42 +00:00
}
2022-09-20 04:00:09 +00:00
func NewSliceCache[T any](fun func(...any) ([]T, error), duration time.Duration) *SliceCache[T] {
2022-09-19 09:39:00 +00:00
return &SliceCache[T]{
2022-10-14 09:15:43 +00:00
v: safety.NewVar(slice[T]{
mutex: &sync.Mutex{},
setCacheFunc: fun,
expireTime: duration,
}),
2022-09-19 09:39:00 +00:00
}
}
2022-09-19 14:02:34 +00:00
func (c *SliceCache[T]) FlushCache() {
2022-10-14 09:15:43 +00:00
mu := c.v.Load().mutex
mu.Lock()
defer mu.Unlock()
c.v.Delete()
2022-09-19 14:02:34 +00:00
}
2022-09-20 08:11:20 +00:00
func (c *SliceCache[T]) GetCache(ctx context.Context, timeout time.Duration, params ...any) ([]T, error) {
2022-10-14 09:15:43 +00:00
v := c.v.Load()
l := len(v.data)
data := v.data
2022-09-20 08:11:20 +00:00
var err error
2022-10-14 09:15:43 +00:00
expired := time.Duration(v.setTime.UnixNano())+v.expireTime < time.Duration(time.Now().UnixNano())
if l < 1 || (l > 0 && v.expireTime >= 0 && expired) {
t := v.incr
2022-09-20 08:11:20 +00:00
call := func() {
2022-10-14 09:15:43 +00:00
v.mutex.Lock()
defer v.mutex.Unlock()
2022-10-14 13:42:24 +00:00
vv := c.v.Load()
if vv.incr > t {
2022-09-20 04:00:09 +00:00
return
}
2022-10-14 13:42:24 +00:00
r, er := vv.setCacheFunc(params...)
2022-09-20 04:00:09 +00:00
if err != nil {
2022-09-20 08:11:20 +00:00
err = er
2022-09-20 04:00:09 +00:00
return
}
2022-10-14 13:42:24 +00:00
vv.setTime = time.Now()
vv.data = r
2022-09-20 08:55:13 +00:00
data = r
2022-10-14 13:42:24 +00:00
vv.incr++
c.v.Store(vv)
2022-09-20 08:11:20 +00:00
}
if timeout > 0 {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
done := make(chan struct{})
go func() {
call()
done <- struct{}{}
close(done)
}()
select {
case <-ctx.Done():
err = errors.New(fmt.Sprintf("get cache %s", ctx.Err().Error()))
case <-done:
2022-09-20 04:00:09 +00:00
2022-09-20 08:11:20 +00:00
}
} else {
call()
2022-09-19 09:39:00 +00:00
}
2022-09-20 08:11:20 +00:00
2022-09-19 09:39:00 +00:00
}
2022-09-20 08:55:13 +00:00
return data, err
2022-09-19 09:39:00 +00:00
}