2015-12-05 21:55:45 +00:00
|
|
|
package app
|
|
|
|
|
2016-05-18 15:12:04 +00:00
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
|
|
|
|
"github.com/v2ray/v2ray-core/common"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
ErrorMissingApplication = errors.New("App: Failed to found one or more applications.")
|
|
|
|
)
|
|
|
|
|
2016-01-31 16:01:28 +00:00
|
|
|
type ID int
|
|
|
|
|
2015-12-11 11:01:20 +00:00
|
|
|
// Context of a function call from proxy to app.
|
2015-12-10 22:55:39 +00:00
|
|
|
type Context interface {
|
|
|
|
CallerTag() string
|
|
|
|
}
|
|
|
|
|
2016-05-18 06:05:52 +00:00
|
|
|
type Caller interface {
|
|
|
|
Tag() string
|
|
|
|
}
|
|
|
|
|
2016-05-18 15:12:04 +00:00
|
|
|
type Application interface {
|
|
|
|
common.Releasable
|
|
|
|
}
|
|
|
|
|
|
|
|
type ApplicationInitializer func() error
|
|
|
|
|
2015-12-11 11:01:20 +00:00
|
|
|
// 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 {
|
2016-05-18 15:12:04 +00:00
|
|
|
Initialize() error
|
|
|
|
InitializeApplication(ApplicationInitializer)
|
|
|
|
|
2016-01-31 16:01:28 +00:00
|
|
|
HasApp(ID) bool
|
2016-05-18 15:12:04 +00:00
|
|
|
GetApp(ID) Application
|
|
|
|
BindApp(ID, Application)
|
2016-01-31 16:01:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type spaceImpl struct {
|
2016-05-22 17:32:28 +00:00
|
|
|
cache map[ID]Application
|
|
|
|
appInit []ApplicationInitializer
|
2016-01-31 16:01:28 +00:00
|
|
|
}
|
2015-12-11 14:56:10 +00:00
|
|
|
|
2016-05-18 06:05:52 +00:00
|
|
|
func NewSpace() Space {
|
|
|
|
return &spaceImpl{
|
2016-05-22 17:32:28 +00:00
|
|
|
cache: make(map[ID]Application),
|
|
|
|
appInit: make([]ApplicationInitializer, 0, 32),
|
2016-05-18 15:12:04 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (this *spaceImpl) InitializeApplication(f ApplicationInitializer) {
|
2016-05-22 17:32:28 +00:00
|
|
|
this.appInit = append(this.appInit, f)
|
2016-05-18 15:12:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (this *spaceImpl) Initialize() error {
|
2016-05-22 17:32:28 +00:00
|
|
|
for _, f := range this.appInit {
|
|
|
|
err := f()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2016-01-31 16:01:28 +00:00
|
|
|
}
|
2016-05-18 15:12:04 +00:00
|
|
|
return nil
|
2016-01-31 16:01:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (this *spaceImpl) HasApp(id ID) bool {
|
|
|
|
_, found := this.cache[id]
|
|
|
|
return found
|
|
|
|
}
|
|
|
|
|
2016-05-18 15:12:04 +00:00
|
|
|
func (this *spaceImpl) GetApp(id ID) Application {
|
2016-01-31 16:01:28 +00:00
|
|
|
obj, found := this.cache[id]
|
|
|
|
if !found {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return obj
|
|
|
|
}
|
|
|
|
|
2016-05-18 15:12:04 +00:00
|
|
|
func (this *spaceImpl) BindApp(id ID, application Application) {
|
|
|
|
this.cache[id] = application
|
2015-12-05 21:55:45 +00:00
|
|
|
}
|