You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
v2ray-core/app/space.go

132 lines
2.6 KiB

package app
import (
"context"
8 years ago
"reflect"
8 years ago
"v2ray.com/core/common"
"v2ray.com/core/common/errors"
)
type Application interface {
8 years ago
Interface() interface{}
Start() error
Close()
}
type InitializationCallback func() error
8 years ago
func CreateAppFromConfig(ctx context.Context, config interface{}) (Application, error) {
application, err := common.CreateObject(ctx, config)
if err != nil {
return nil, err
}
8 years ago
switch a := application.(type) {
case Application:
return a, nil
default:
return nil, errors.New("App: Not an application.")
}
}
// A Space contains all apps that may be available in a V2Ray runtime.
// Caller must check the availability of an app by calling HasXXX before getting its instance.
type Space interface {
8 years ago
GetApplication(appInterface interface{}) Application
AddApplication(application Application) error
Initialize() error
OnInitialize(InitializationCallback)
Start() error
Close()
}
type spaceImpl struct {
initialized bool
8 years ago
cache map[reflect.Type]Application
appInit []InitializationCallback
}
9 years ago
func NewSpace() Space {
return &spaceImpl{
8 years ago
cache: make(map[reflect.Type]Application),
appInit: make([]InitializationCallback, 0, 32),
}
}
func (v *spaceImpl) OnInitialize(f InitializationCallback) {
if v.initialized {
f()
} else {
v.appInit = append(v.appInit, f)
}
}
8 years ago
func (v *spaceImpl) Initialize() error {
for _, f := range v.appInit {
if err := f(); err != nil {
return err
}
}
v.appInit = nil
v.initialized = true
return nil
}
8 years ago
func (v *spaceImpl) GetApplication(appInterface interface{}) Application {
8 years ago
if v == nil {
return nil
}
8 years ago
appType := reflect.TypeOf(appInterface)
return v.cache[appType]
}
8 years ago
func (v *spaceImpl) AddApplication(app Application) error {
8 years ago
if v == nil {
return errors.New("App: Nil space.")
}
8 years ago
appType := reflect.TypeOf(app.Interface())
v.cache[appType] = app
return nil
}
func (s *spaceImpl) Start() error {
for _, app := range s.cache {
if err := app.Start(); err != nil {
return err
}
}
return nil
}
func (s *spaceImpl) Close() {
for _, app := range s.cache {
app.Close()
}
}
type contextKey int
const (
spaceKey = contextKey(0)
)
8 years ago
func AddApplicationToSpace(ctx context.Context, appConfig interface{}) error {
space := SpaceFromContext(ctx)
if space == nil {
return errors.New("App: No space in context.")
}
application, err := CreateAppFromConfig(ctx, appConfig)
if err != nil {
return err
}
return space.AddApplication(application)
}
func SpaceFromContext(ctx context.Context) Space {
return ctx.Value(spaceKey).(Space)
}
func ContextWithSpace(ctx context.Context, space Space) context.Context {
return context.WithValue(ctx, spaceKey, space)
}