bbgo_origin/pkg/bbgo/isolation.go

57 lines
1.7 KiB
Go
Raw Normal View History

2022-10-02 11:34:52 +00:00
package bbgo
2022-10-03 08:01:08 +00:00
import (
"context"
"github.com/c9s/bbgo/pkg/service"
2022-10-03 08:01:08 +00:00
)
const IsolationContextKey = "bbgo"
var defaultIsolation = NewDefaultIsolation()
2022-10-02 11:34:52 +00:00
type Isolation struct {
gracefulShutdown GracefulShutdown
persistenceServiceFacade *service.PersistenceServiceFacade
2022-10-02 11:34:52 +00:00
}
func NewDefaultIsolation() *Isolation {
return &Isolation{
gracefulShutdown: GracefulShutdown{},
persistenceServiceFacade: defaultPersistenceServiceFacade,
}
2022-10-02 11:34:52 +00:00
}
2022-10-03 08:01:08 +00:00
func NewIsolation(persistenceFacade *service.PersistenceServiceFacade) *Isolation {
return &Isolation{
gracefulShutdown: GracefulShutdown{},
persistenceServiceFacade: persistenceFacade,
}
}
func GetIsolationFromContext(ctx context.Context) *Isolation {
isolatedContext, ok := ctx.Value(IsolationContextKey).(*Isolation)
2022-10-03 08:01:08 +00:00
if ok {
return isolatedContext
}
return defaultIsolation
2022-10-03 08:01:08 +00:00
}
2022-10-11 06:22:46 +00:00
// NewTodoContextWithExistingIsolation creates a new context object with the existing isolation of the parent context.
func NewTodoContextWithExistingIsolation(parent context.Context) context.Context {
isolatedContext := GetIsolationFromContext(parent)
todo := context.WithValue(context.TODO(), IsolationContextKey, isolatedContext)
return todo
}
// NewContextWithIsolation creates a new context from the parent context with a custom isolation
func NewContextWithIsolation(parent context.Context, isolation *Isolation) context.Context {
return context.WithValue(parent, IsolationContextKey, isolation)
}
2022-10-11 06:22:46 +00:00
// NewContextWithDefaultIsolation creates a new context from the parent context with a default isolation
func NewContextWithDefaultIsolation(parent context.Context) context.Context {
return context.WithValue(parent, IsolationContextKey, defaultIsolation)
}