103 lines
2.1 KiB
Go
103 lines
2.1 KiB
Go
|
package ats_tracer
|
||
|
|
||
|
import (
|
||
|
"slices"
|
||
|
"sync"
|
||
|
"time"
|
||
|
|
||
|
"gitea.timerzz.com/kedaya_haitao/common/structs/storage"
|
||
|
v2 "gitea.timerzz.com/kedaya_haitao/common/structs/v2"
|
||
|
"github.com/golang/glog"
|
||
|
)
|
||
|
|
||
|
type Tracer struct {
|
||
|
pArticle *v2.ProviderArticle
|
||
|
tracing bool //是不是正在抓
|
||
|
lastTraceTime time.Time //上次是什么时候抓的
|
||
|
lastAts int // 上次抓取的库存
|
||
|
}
|
||
|
|
||
|
type Tracers struct {
|
||
|
m sync.RWMutex
|
||
|
list []*Tracer
|
||
|
|
||
|
providerId v2.ProviderId
|
||
|
storage *storage.Storage
|
||
|
ready bool
|
||
|
}
|
||
|
|
||
|
func NewTracers(storage *storage.Storage, providerId v2.ProviderId) *Tracers {
|
||
|
return &Tracers{
|
||
|
storage: storage,
|
||
|
providerId: providerId,
|
||
|
list: make([]*Tracer, 0),
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (w *Tracers) Add(article *v2.ProviderArticle) {
|
||
|
w.m.Lock()
|
||
|
defer w.m.Unlock()
|
||
|
if !slices.ContainsFunc(w.list, func(item *Tracer) bool {
|
||
|
return item.pArticle.SkuID == article.SkuID
|
||
|
}) {
|
||
|
w.list = append(w.list, &Tracer{pArticle: article, lastAts: -1})
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (w *Tracers) Remove(skuID string) {
|
||
|
for i, item := range w.list {
|
||
|
if item.pArticle.SkuID == skuID {
|
||
|
w.m.Lock()
|
||
|
w.list = append(w.list[:i], w.list[i+1:]...)
|
||
|
w.m.Unlock()
|
||
|
return
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (w *Tracers) Range(filter func(tracer *Tracer) bool, do func(tracer *Tracer)) {
|
||
|
w.m.RLock()
|
||
|
defer w.m.RUnlock()
|
||
|
for _, item := range w.list {
|
||
|
if filter(item) {
|
||
|
do(item)
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (w *Tracers) Exist(skuID string) bool {
|
||
|
w.m.RLock()
|
||
|
defer w.m.RUnlock()
|
||
|
for _, item := range w.list {
|
||
|
if item.pArticle.SkuID == skuID {
|
||
|
return true
|
||
|
}
|
||
|
}
|
||
|
return false
|
||
|
}
|
||
|
|
||
|
func (w *Tracers) Load() (err error) {
|
||
|
var articles []*v2.ProviderArticle
|
||
|
articles, err = w.storage.ProviderArticle().Find(
|
||
|
storage.NewGetProviderArticleQuery().
|
||
|
SetProviderId(w.providerId).
|
||
|
SetTraceAts(true),
|
||
|
)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
w.m.Lock()
|
||
|
defer w.m.Unlock()
|
||
|
for _, article := range articles {
|
||
|
w.list = append(w.list, &Tracer{pArticle: article})
|
||
|
}
|
||
|
glog.Infof("共加载%d个需要追踪库存的商品\n", len(w.list))
|
||
|
w.ready = true
|
||
|
return
|
||
|
}
|
||
|
|
||
|
// 返回ready
|
||
|
func (w *Tracers) Ready() bool {
|
||
|
return w.ready
|
||
|
}
|