bbgo_origin/pkg/bbgo/persistence.go

77 lines
1.8 KiB
Go
Raw Permalink Normal View History

package bbgo
import (
"fmt"
log "github.com/sirupsen/logrus"
2022-03-14 13:21:04 +00:00
"github.com/c9s/bbgo/pkg/service"
)
2020-12-07 03:43:17 +00:00
type PersistenceSelector struct {
// StoreID is the store you want to use.
StoreID string `json:"store" yaml:"store"`
// Type is the persistence type
Type string `json:"type" yaml:"type"`
}
// Persistence is used for strategy to inject the persistence.
type Persistence struct {
PersistenceSelector *PersistenceSelector `json:"persistence,omitempty" yaml:"persistence,omitempty"`
Facade *service.PersistenceServiceFacade `json:"-" yaml:"-"`
2020-12-07 03:43:17 +00:00
}
2021-03-18 09:20:07 +00:00
func (p *Persistence) backendService(t string) (service.PersistenceService, error) {
2020-12-07 03:43:17 +00:00
switch t {
case "json":
2021-03-18 09:20:07 +00:00
return p.Facade.Json, nil
2020-12-07 03:43:17 +00:00
case "redis":
if p.Facade.Redis == nil {
log.Warn("redis persistence is not available, fallback to memory backend")
return p.Facade.Memory, nil
}
2021-03-18 09:20:07 +00:00
return p.Facade.Redis, nil
2020-12-07 03:43:17 +00:00
2020-12-07 04:03:56 +00:00
case "memory":
2021-03-18 09:20:07 +00:00
return p.Facade.Memory, nil
2020-12-07 04:03:56 +00:00
2020-12-07 03:43:17 +00:00
}
2021-03-18 09:20:07 +00:00
return nil, fmt.Errorf("unsupported persistent type %s", t)
2020-12-07 03:43:17 +00:00
}
func (p *Persistence) Load(val interface{}, subIDs ...string) error {
2021-03-18 09:20:07 +00:00
ps, err := p.backendService(p.PersistenceSelector.Type)
2020-12-07 03:43:17 +00:00
if err != nil {
return err
}
2022-03-14 13:21:04 +00:00
log.Debugf("using persistence store %T for loading", ps)
2020-12-07 03:43:17 +00:00
if p.PersistenceSelector.StoreID == "" {
2021-03-18 09:20:07 +00:00
p.PersistenceSelector.StoreID = "default"
2020-12-07 03:43:17 +00:00
}
2021-03-18 09:20:07 +00:00
store := ps.NewStore(p.PersistenceSelector.StoreID, subIDs...)
2020-12-07 03:43:17 +00:00
return store.Load(val)
}
func (p *Persistence) Save(val interface{}, subIDs ...string) error {
2021-03-18 09:20:07 +00:00
ps, err := p.backendService(p.PersistenceSelector.Type)
2020-12-07 03:43:17 +00:00
if err != nil {
return err
}
2022-03-14 13:21:04 +00:00
log.Debugf("using persistence store %T for storing", ps)
2020-12-07 03:43:17 +00:00
if p.PersistenceSelector.StoreID == "" {
2021-03-18 09:20:07 +00:00
p.PersistenceSelector.StoreID = "default"
2020-12-07 03:43:17 +00:00
}
2021-03-18 09:20:07 +00:00
store := ps.NewStore(p.PersistenceSelector.StoreID, subIDs...)
2020-12-07 03:43:17 +00:00
return store.Save(val)
}