1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-10-01 16:26:02 -04:00
v2fly/app/space.go

97 lines
1.8 KiB
Go
Raw Normal View History

2015-12-05 16:55:45 -05:00
package app
2016-05-18 11:12:04 -04:00
import (
"errors"
"sync/atomic"
"github.com/v2ray/v2ray-core/common"
)
var (
ErrorMissingApplication = errors.New("App: Failed to found one or more applications.")
)
2016-01-31 11:01:28 -05:00
type ID int
// Context of a function call from proxy to app.
2015-12-10 17:55:39 -05:00
type Context interface {
CallerTag() string
}
2016-05-18 02:05:52 -04:00
type Caller interface {
Tag() string
}
2016-05-18 11:12:04 -04:00
type Application interface {
common.Releasable
}
type ApplicationInitializer func() error
// 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 11:12:04 -04:00
Initialize() error
InitializeApplication(ApplicationInitializer)
2016-01-31 11:01:28 -05:00
HasApp(ID) bool
2016-05-18 11:12:04 -04:00
GetApp(ID) Application
BindApp(ID, Application)
2016-01-31 11:01:28 -05:00
}
type spaceImpl struct {
2016-05-18 11:12:04 -04:00
cache map[ID]Application
initSignal chan struct{}
initErrors chan error
appsToInit int32
appsDone int32
2016-01-31 11:01:28 -05:00
}
2015-12-11 09:56:10 -05:00
2016-05-18 02:05:52 -04:00
func NewSpace() Space {
return &spaceImpl{
2016-05-18 11:12:04 -04:00
cache: make(map[ID]Application),
initSignal: make(chan struct{}),
initErrors: make(chan error, 1),
}
}
func (this *spaceImpl) InitializeApplication(f ApplicationInitializer) {
atomic.AddInt32(&(this.appsToInit), 1)
go func() {
<-this.initSignal
err := f()
if err != nil {
this.initErrors <- err
}
count := atomic.AddInt32(&(this.appsDone), 1)
if count == this.appsToInit {
close(this.initErrors)
}
}()
}
func (this *spaceImpl) Initialize() error {
close(this.initSignal)
if err, open := <-this.initErrors; open {
return err
2016-01-31 11:01:28 -05:00
}
2016-05-18 11:12:04 -04:00
return nil
2016-01-31 11:01:28 -05:00
}
func (this *spaceImpl) HasApp(id ID) bool {
_, found := this.cache[id]
return found
}
2016-05-18 11:12:04 -04:00
func (this *spaceImpl) GetApp(id ID) Application {
2016-01-31 11:01:28 -05:00
obj, found := this.cache[id]
if !found {
return nil
}
return obj
}
2016-05-18 11:12:04 -04:00
func (this *spaceImpl) BindApp(id ID, application Application) {
this.cache[id] = application
2015-12-05 16:55:45 -05:00
}