space.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package app
  2. import (
  3. "errors"
  4. "github.com/v2ray/v2ray-core/common"
  5. )
  6. var (
  7. ErrMissingApplication = errors.New("App: Failed to found one or more applications.")
  8. )
  9. type ID int
  10. // Context of a function call from proxy to app.
  11. type Context interface {
  12. CallerTag() string
  13. }
  14. type Caller interface {
  15. Tag() string
  16. }
  17. type Application interface {
  18. common.Releasable
  19. }
  20. type ApplicationInitializer func() error
  21. // A Space contains all apps that may be available in a V2Ray runtime.
  22. // Caller must check the availability of an app by calling HasXXX before getting its instance.
  23. type Space interface {
  24. Initialize() error
  25. InitializeApplication(ApplicationInitializer)
  26. HasApp(ID) bool
  27. GetApp(ID) Application
  28. BindApp(ID, Application)
  29. }
  30. type spaceImpl struct {
  31. cache map[ID]Application
  32. appInit []ApplicationInitializer
  33. }
  34. func NewSpace() Space {
  35. return &spaceImpl{
  36. cache: make(map[ID]Application),
  37. appInit: make([]ApplicationInitializer, 0, 32),
  38. }
  39. }
  40. func (this *spaceImpl) InitializeApplication(f ApplicationInitializer) {
  41. this.appInit = append(this.appInit, f)
  42. }
  43. func (this *spaceImpl) Initialize() error {
  44. for _, f := range this.appInit {
  45. err := f()
  46. if err != nil {
  47. return err
  48. }
  49. }
  50. return nil
  51. }
  52. func (this *spaceImpl) HasApp(id ID) bool {
  53. _, found := this.cache[id]
  54. return found
  55. }
  56. func (this *spaceImpl) GetApp(id ID) Application {
  57. obj, found := this.cache[id]
  58. if !found {
  59. return nil
  60. }
  61. return obj
  62. }
  63. func (this *spaceImpl) BindApp(id ID, application Application) {
  64. this.cache[id] = application
  65. }