diff --git a/adapter/event_in_memory.go b/adapter/event_in_memory.go new file mode 100644 index 00000000..89f321ea --- /dev/null +++ b/adapter/event_in_memory.go @@ -0,0 +1,30 @@ +package adapter + +import ( + "github.com/google/uuid" + "github.com/vertex-center/vertex/types" +) + +type EventInMemoryAdapter struct { + listeners *map[uuid.UUID]types.Listener +} + +func NewEventInMemoryAdapter() types.EventAdapterPort { + return &EventInMemoryAdapter{ + listeners: &map[uuid.UUID]types.Listener{}, + } +} + +func (a *EventInMemoryAdapter) AddListener(l types.Listener) { + (*a.listeners)[l.GetUUID()] = l +} + +func (a *EventInMemoryAdapter) RemoveListener(l types.Listener) { + delete(*a.listeners, l.GetUUID()) +} + +func (a *EventInMemoryAdapter) Send(e interface{}) { + for _, l := range *a.listeners { + l.OnEvent(e) + } +} diff --git a/repository/event_in_memory_test.go b/adapter/event_in_memory_test.go similarity index 55% rename from repository/event_in_memory_test.go rename to adapter/event_in_memory_test.go index 2670e462..c36aeea0 100644 --- a/repository/event_in_memory_test.go +++ b/adapter/event_in_memory_test.go @@ -1,4 +1,4 @@ -package repository +package adapter import ( "testing" @@ -9,37 +9,37 @@ import ( "github.com/stretchr/testify/suite" ) -type EventInMemoryRepositoryTestSuite struct { +type EventInMemoryAdapterTestSuite struct { suite.Suite - repo EventInMemoryRepository + adapter EventInMemoryAdapter } func TestEventInMemoryRepositoryTestSuite(t *testing.T) { - suite.Run(t, new(EventInMemoryRepositoryTestSuite)) + suite.Run(t, new(EventInMemoryAdapterTestSuite)) } -func (suite *EventInMemoryRepositoryTestSuite) SetupSuite() { - suite.repo = NewEventInMemoryRepository() +func (suite *EventInMemoryAdapterTestSuite) SetupSuite() { + suite.adapter = *NewEventInMemoryAdapter().(*EventInMemoryAdapter) } -func (suite *EventInMemoryRepositoryTestSuite) TestEvents() { +func (suite *EventInMemoryAdapterTestSuite) TestEvents() { listener := MockListener{ uuid: uuid.New(), } // Add a listener - suite.repo.AddListener(&listener) - assert.Equal(suite.T(), 1, len(*suite.repo.listeners)) + suite.adapter.AddListener(&listener) + assert.Equal(suite.T(), 1, len(*suite.adapter.listeners)) // Fire event listener.On("OnEvent").Return(nil) - suite.repo.Send(MockEvent{}) + suite.adapter.Send(MockEvent{}) listener.AssertCalled(suite.T(), "OnEvent") // Remove listener - suite.repo.RemoveListener(&listener) - assert.Equal(suite.T(), 0, len(*suite.repo.listeners)) + suite.adapter.RemoveListener(&listener) + assert.Equal(suite.T(), 0, len(*suite.adapter.listeners)) } type MockEvent struct{} diff --git a/repository/instance_fs.go b/adapter/instance_fs.go similarity index 65% rename from repository/instance_fs.go rename to adapter/instance_fs.go index 4fdc796c..57b513cc 100644 --- a/repository/instance_fs.go +++ b/adapter/instance_fs.go @@ -1,4 +1,4 @@ -package repository +package adapter import ( "bufio" @@ -23,72 +23,72 @@ var ( ErrContainerNotFound = errors.New("container not found") ) -type InstanceFSRepository struct { +type InstanceFSAdapter struct { instancesPath string instances map[uuid.UUID]*types.Instance } -func NewInstanceFSRepository() InstanceFSRepository { - r := InstanceFSRepository{ +func NewInstanceFSAdapter() types.InstanceAdapterPort { + adapter := &InstanceFSAdapter{ instancesPath: path.Join(storage.Path, "instances"), instances: map[uuid.UUID]*types.Instance{}, } - err := os.MkdirAll(r.instancesPath, os.ModePerm) + err := os.MkdirAll(adapter.instancesPath, os.ModePerm) if err != nil && !os.IsExist(err) { log.Default.Error(err, vlog.String("message", "failed to create directory"), - vlog.String("path", r.instancesPath), + vlog.String("path", adapter.instancesPath), ) os.Exit(1) } - return r + return adapter } -func (r *InstanceFSRepository) Get(uuid uuid.UUID) (*types.Instance, error) { - instance, ok := r.instances[uuid] +func (a *InstanceFSAdapter) Get(uuid uuid.UUID) (*types.Instance, error) { + instance, ok := a.instances[uuid] if !ok { return nil, ErrInstanceNotFound } return instance, nil } -func (r *InstanceFSRepository) GetAll() map[uuid.UUID]*types.Instance { - return r.instances +func (a *InstanceFSAdapter) GetAll() map[uuid.UUID]*types.Instance { + return a.instances } -func (r *InstanceFSRepository) GetPath(uuid uuid.UUID) string { - return path.Join(r.instancesPath, uuid.String()) +func (a *InstanceFSAdapter) GetPath(uuid uuid.UUID) string { + return path.Join(a.instancesPath, uuid.String()) } -func (r *InstanceFSRepository) Delete(uuid uuid.UUID) error { - err := os.RemoveAll(r.GetPath(uuid)) +func (a *InstanceFSAdapter) Delete(uuid uuid.UUID) error { + err := os.RemoveAll(a.GetPath(uuid)) if err != nil { return fmt.Errorf("failed to delete server: %v", err) } - delete(r.instances, uuid) + delete(a.instances, uuid) return nil } -func (r *InstanceFSRepository) Exists(uuid uuid.UUID) bool { - return r.instances[uuid] != nil +func (a *InstanceFSAdapter) Exists(uuid uuid.UUID) bool { + return a.instances[uuid] != nil } -func (r *InstanceFSRepository) Set(uuid uuid.UUID, instance types.Instance) error { - if r.Exists(uuid) { +func (a *InstanceFSAdapter) Set(uuid uuid.UUID, instance types.Instance) error { + if a.Exists(uuid) { return ErrInstanceAlreadyExists } - r.instances[uuid] = &instance + a.instances[uuid] = &instance return nil } -func (r *InstanceFSRepository) SaveSettings(i *types.Instance) error { - settingsPath := path.Join(r.GetPath(i.UUID), ".vertex", "instance_settings.json") +func (a *InstanceFSAdapter) SaveSettings(i *types.Instance) error { + settingsPath := path.Join(a.GetPath(i.UUID), ".vertex", "instance_settings.json") settingsBytes, err := json.MarshalIndent(i.InstanceSettings, "", "\t") if err != nil { @@ -103,8 +103,8 @@ func (r *InstanceFSRepository) SaveSettings(i *types.Instance) error { return nil } -func (r *InstanceFSRepository) LoadSettings(i *types.Instance) error { - settingsPath := path.Join(r.GetPath(i.UUID), ".vertex", "instance_settings.json") +func (a *InstanceFSAdapter) LoadSettings(i *types.Instance) error { + settingsPath := path.Join(a.GetPath(i.UUID), ".vertex", "instance_settings.json") settingsBytes, err := os.ReadFile(settingsPath) if errors.Is(err, os.ErrNotExist) { @@ -121,7 +121,7 @@ func (r *InstanceFSRepository) LoadSettings(i *types.Instance) error { return nil } -func (r *InstanceFSRepository) ReadService(instancePath string) (types.Service, error) { +func (a *InstanceFSAdapter) ReadService(instancePath string) (types.Service, error) { data, err := os.ReadFile(path.Join(instancePath, ".vertex", "service.yml")) if err != nil { log.Default.Warn("'.vertex/service.yml' file not found", @@ -134,8 +134,8 @@ func (r *InstanceFSRepository) ReadService(instancePath string) (types.Service, return service, err } -func (r *InstanceFSRepository) SaveEnv(i *types.Instance, variables map[string]string) error { - filepath := path.Join(r.GetPath(i.UUID), ".env") +func (a *InstanceFSAdapter) SaveEnv(i *types.Instance, variables map[string]string) error { + filepath := path.Join(a.GetPath(i.UUID), ".env") file, err := os.OpenFile(filepath, os.O_WRONLY|os.O_CREATE, os.ModePerm) if err != nil { @@ -154,8 +154,8 @@ func (r *InstanceFSRepository) SaveEnv(i *types.Instance, variables map[string]s return nil } -func (r *InstanceFSRepository) LoadEnv(i *types.Instance) error { - filepath := path.Join(r.GetPath(i.UUID), ".env") +func (a *InstanceFSAdapter) LoadEnv(i *types.Instance) error { + filepath := path.Join(a.GetPath(i.UUID), ".env") file, err := os.Open(filepath) if os.IsNotExist(err) { @@ -179,8 +179,8 @@ func (r *InstanceFSRepository) LoadEnv(i *types.Instance) error { return nil } -func (r *InstanceFSRepository) Reload(load func(uuid uuid.UUID)) { - entries, err := os.ReadDir(r.instancesPath) +func (a *InstanceFSAdapter) Reload(load func(uuid uuid.UUID)) { + entries, err := os.ReadDir(a.instancesPath) if err != nil { log.Default.Error(err) os.Exit(1) diff --git a/repository/instance_logs_fs.go b/adapter/instance_logs_fs.go similarity index 68% rename from repository/instance_logs_fs.go rename to adapter/instance_logs_fs.go index 710a3fd3..f6b8f713 100644 --- a/repository/instance_logs_fs.go +++ b/adapter/instance_logs_fs.go @@ -1,4 +1,4 @@ -package repository +package adapter import ( "errors" @@ -28,19 +28,19 @@ type InstanceLogger struct { currentLine int } -type InstanceLogsFSRepository struct { +type InstanceLogsFSAdapter struct { loggers map[uuid.UUID]*InstanceLogger } -func NewInstanceLogsFSRepository() InstanceLogsFSRepository { - r := InstanceLogsFSRepository{ +func NewInstanceLogsFSAdapter() types.InstanceLogsAdapterPort { + r := &InstanceLogsFSAdapter{ loggers: map[uuid.UUID]*InstanceLogger{}, } r.startCron() return r } -func (r *InstanceLogsFSRepository) Open(uuid uuid.UUID) error { +func (a *InstanceLogsFSAdapter) Open(uuid uuid.UUID) error { dir := path.Join(storage.Path, "instances", uuid.String(), ".vertex", "logs") err := os.MkdirAll(dir, os.ModePerm) if err != nil { @@ -60,20 +60,20 @@ func (r *InstanceLogsFSRepository) Open(uuid uuid.UUID) error { } l.file = file - r.loggers[uuid] = &l + a.loggers[uuid] = &l return nil } -func (r *InstanceLogsFSRepository) Close(uuid uuid.UUID) error { - l, err := r.getLogger(uuid) +func (a *InstanceLogsFSAdapter) Close(uuid uuid.UUID) error { + l, err := a.getLogger(uuid) if err != nil { return err } return l.Close() } -func (r *InstanceLogsFSRepository) Push(uuid uuid.UUID, line types.LogLine) { - l, err := r.getLogger(uuid) +func (a *InstanceLogsFSAdapter) Push(uuid uuid.UUID, line types.LogLine) { + l, err := a.getLogger(uuid) if err != nil { log.Default.Error(err) return @@ -90,10 +90,10 @@ func (r *InstanceLogsFSRepository) Push(uuid uuid.UUID, line types.LogLine) { } } -func (r *InstanceLogsFSRepository) CloseAll() error { +func (a *InstanceLogsFSAdapter) CloseAll() error { var errs []error - for id := range r.loggers { - err := r.Close(id) + for id := range a.loggers { + err := a.Close(id) if err != nil { errs = append(errs, err) } @@ -101,8 +101,8 @@ func (r *InstanceLogsFSRepository) CloseAll() error { return errors.Join(errs...) } -func (r *InstanceLogsFSRepository) LoadBuffer(uuid uuid.UUID) ([]types.LogLine, error) { - l, err := r.getLogger(uuid) +func (a *InstanceLogsFSAdapter) LoadBuffer(uuid uuid.UUID) ([]types.LogLine, error) { + l, err := a.getLogger(uuid) if err != nil { return nil, err } @@ -113,24 +113,24 @@ func (l *InstanceLogger) Close() error { return l.file.Close() } -func (r *InstanceLogsFSRepository) getLogger(uuid uuid.UUID) (*InstanceLogger, error) { - l, ok := r.loggers[uuid] +func (a *InstanceLogsFSAdapter) getLogger(uuid uuid.UUID) (*InstanceLogger, error) { + l, ok := a.loggers[uuid] if !ok { return nil, ErrLoggerNotFound } return l, nil } -func (r *InstanceLogsFSRepository) startCron() { +func (a *InstanceLogsFSAdapter) startCron() { s := gocron.NewScheduler(time.Local) _, err := s.Every(1).Day().At("00:00").Do(func() { - for id := range r.loggers { - err := r.Close(id) + for id := range a.loggers { + err := a.Close(id) if err != nil { log.Default.Error(err) continue } - err = r.Open(id) + err = a.Open(id) if err != nil { log.Default.Error(err) } diff --git a/repository/package_fs.go b/adapter/package_fs.go similarity index 50% rename from repository/package_fs.go rename to adapter/package_fs.go index e19a3884..e434642d 100644 --- a/repository/package_fs.go +++ b/adapter/package_fs.go @@ -1,4 +1,4 @@ -package repository +package adapter import ( "encoding/json" @@ -17,63 +17,63 @@ var ( ErrPkgNotFound = errors.New("package not found") ) -type PackageFSRepository struct { +type PackageFSAdapter struct { pkgs map[string]types.Package pkgsMutex *sync.RWMutex dependenciesPath string } -type PackageRepositoryParams struct { +type PackageFSAdapterParams struct { dependenciesPath string } -func NewPackageFSRepository(params *PackageRepositoryParams) PackageFSRepository { +func NewPackageFSAdapter(params *PackageFSAdapterParams) types.PackageAdapterPort { if params == nil { - params = &PackageRepositoryParams{} + params = &PackageFSAdapterParams{} } if params.dependenciesPath == "" { params.dependenciesPath = path.Join(storage.Path, "packages") } - repo := PackageFSRepository{ + adapter := &PackageFSAdapter{ pkgs: map[string]types.Package{}, pkgsMutex: &sync.RWMutex{}, dependenciesPath: params.dependenciesPath, } - err := repo.Reload() + err := adapter.Reload() if err != nil { - log.Default.Error(fmt.Errorf("failed to reload services repository: %v", err)) + log.Default.Error(fmt.Errorf("failed to reload services: %v", err)) } - return repo + return adapter } -func (r *PackageFSRepository) GetByID(id string) (types.Package, error) { - r.pkgsMutex.RLock() - defer r.pkgsMutex.RUnlock() +func (a *PackageFSAdapter) GetByID(id string) (types.Package, error) { + a.pkgsMutex.RLock() + defer a.pkgsMutex.RUnlock() - pkg, ok := r.pkgs[id] + pkg, ok := a.pkgs[id] if !ok { return types.Package{}, ErrPkgNotFound } return pkg, nil } -func (r *PackageFSRepository) set(id string, pkg types.Package) { - r.pkgsMutex.Lock() - defer r.pkgsMutex.Unlock() +func (a *PackageFSAdapter) set(id string, pkg types.Package) { + a.pkgsMutex.Lock() + defer a.pkgsMutex.Unlock() - r.pkgs[id] = pkg + a.pkgs[id] = pkg } -func (r *PackageFSRepository) GetPath(id string) string { - return path.Join(r.dependenciesPath, "packages", id) +func (a *PackageFSAdapter) GetPath(id string) string { + return path.Join(a.dependenciesPath, "packages", id) } -func (r *PackageFSRepository) Reload() error { - dir, err := os.ReadDir(path.Join(r.dependenciesPath, "packages")) +func (a *PackageFSAdapter) Reload() error { + dir, err := os.ReadDir(path.Join(a.dependenciesPath, "packages")) if err != nil { return err } @@ -85,19 +85,19 @@ func (r *PackageFSRepository) Reload() error { name := entry.Name() - pkg, err := r.readFromDisk(name) + pkg, err := a.readFromDisk(name) if err != nil { return err } - r.set(name, *pkg) + a.set(name, *pkg) } return nil } -func (r *PackageFSRepository) readFromDisk(id string) (*types.Package, error) { - p := path.Join(r.GetPath(id), fmt.Sprintf("%s.json", id)) +func (a *PackageFSAdapter) readFromDisk(id string) (*types.Package, error) { + p := path.Join(a.GetPath(id), fmt.Sprintf("%s.json", id)) file, err := os.ReadFile(p) if err != nil { diff --git a/adapter/package_fs_test.go b/adapter/package_fs_test.go new file mode 100644 index 00000000..6c2f17f4 --- /dev/null +++ b/adapter/package_fs_test.go @@ -0,0 +1,53 @@ +package adapter + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/suite" +) + +const ( + PathPackages = "tests/packages" +) + +type PackageAdapterTestSuite struct { + suite.Suite + + adapter PackageFSAdapter +} + +func TestPackageRepositoryTestSuite(t *testing.T) { + suite.Run(t, new(PackageAdapterTestSuite)) +} + +func (suite *PackageAdapterTestSuite) SetupSuite() { + suite.adapter = *NewPackageFSAdapter(&PackageFSAdapterParams{ + dependenciesPath: PathPackages, + }).(*PackageFSAdapter) + + err := suite.adapter.Reload() + assert.NoError(suite.T(), err) + assert.NotEqual(suite.T(), 0, len(suite.adapter.pkgs)) + assert.Equal(suite.T(), "Redis", suite.adapter.pkgs["redis"].Name) + assert.Equal(suite.T(), "BSD-3", suite.adapter.pkgs["redis"].License) +} + +func (suite *PackageAdapterTestSuite) TestGetPath() { + p := suite.adapter.GetPath("redis") + assert.Equal(suite.T(), "tests/packages/packages/redis", p) +} + +func (suite *PackageAdapterTestSuite) TestReload() { + err := suite.adapter.Reload() + assert.NoError(suite.T(), err) +} + +func (suite *PackageAdapterTestSuite) TestGet() { + pkg, err := suite.adapter.GetByID("redis") + assert.NoError(suite.T(), err) + assert.Equal(suite.T(), pkg.Name, "Redis") + + _, err = suite.adapter.GetByID("undefined_package_name") + assert.ErrorIs(suite.T(), err, ErrPkgNotFound) +} diff --git a/repository/proxy_fs.go b/adapter/proxy_fs.go similarity index 58% rename from repository/proxy_fs.go rename to adapter/proxy_fs.go index 684ac47d..7bb0a3e8 100644 --- a/repository/proxy_fs.go +++ b/adapter/proxy_fs.go @@ -1,4 +1,4 @@ -package repository +package adapter import ( "encoding/json" @@ -18,13 +18,13 @@ type ProxyFSRepository struct { proxyPath string } -type ProxyRepositoryParams struct { +type ProxyFSAdapterParams struct { proxyPath string } -func NewProxyFSRepository(params *ProxyRepositoryParams) ProxyFSRepository { +func NewProxyFSAdapter(params *ProxyFSAdapterParams) types.ProxyAdapterPort { if params == nil { - params = &ProxyRepositoryParams{} + params = &ProxyFSAdapterParams{} } if params.proxyPath == "" { params.proxyPath = path.Join(storage.Path, "proxy") @@ -39,31 +39,31 @@ func NewProxyFSRepository(params *ProxyRepositoryParams) ProxyFSRepository { os.Exit(1) } - repo := ProxyFSRepository{ + adapter := &ProxyFSRepository{ redirects: types.ProxyRedirects{}, proxyPath: params.proxyPath, } - repo.read() + adapter.read() - return repo + return adapter } -func (r *ProxyFSRepository) GetRedirects() types.ProxyRedirects { - return r.redirects +func (a *ProxyFSRepository) GetRedirects() types.ProxyRedirects { + return a.redirects } -func (r *ProxyFSRepository) AddRedirect(id uuid.UUID, redirect types.ProxyRedirect) error { - r.redirects[id] = redirect - return r.write() +func (a *ProxyFSRepository) AddRedirect(id uuid.UUID, redirect types.ProxyRedirect) error { + a.redirects[id] = redirect + return a.write() } -func (r *ProxyFSRepository) RemoveRedirect(id uuid.UUID) error { - delete(r.redirects, id) - return r.write() +func (a *ProxyFSRepository) RemoveRedirect(id uuid.UUID) error { + delete(a.redirects, id) + return a.write() } -func (r *ProxyFSRepository) read() { - p := path.Join(r.proxyPath, "redirects.json") +func (a *ProxyFSRepository) read() { + p := path.Join(a.proxyPath, "redirects.json") file, err := os.ReadFile(p) if errors.Is(err, os.ErrNotExist) { @@ -73,17 +73,17 @@ func (r *ProxyFSRepository) read() { return } - err = json.Unmarshal(file, &r.redirects) + err = json.Unmarshal(file, &a.redirects) if err != nil { log.Default.Error(err) return } } -func (r *ProxyFSRepository) write() error { - p := path.Join(r.proxyPath, "redirects.json") +func (a *ProxyFSRepository) write() error { + p := path.Join(a.proxyPath, "redirects.json") - bytes, err := json.MarshalIndent(r.redirects, "", "\t") + bytes, err := json.MarshalIndent(a.redirects, "", "\t") if err != nil { return err } diff --git a/repository/runner_docker.go b/adapter/runner_docker.go similarity index 71% rename from repository/runner_docker.go rename to adapter/runner_docker.go index 88eafd71..4030e339 100644 --- a/repository/runner_docker.go +++ b/adapter/runner_docker.go @@ -1,4 +1,4 @@ -package repository +package adapter import ( "bufio" @@ -21,7 +21,7 @@ import ( "github.com/vertex-center/vlog" ) -type RunnerDockerRepository struct { +type RunnerDockerAdapter struct { cli *client.Client } @@ -29,43 +29,43 @@ type dockerMessage struct { Stream string `json:"stream"` } -func NewRunnerDockerRepository() RunnerDockerRepository { +func NewRunnerDockerAdapter() RunnerDockerAdapter { cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation()) if err != nil { log.Default.Warn("couldn't connect with the Docker cli.", vlog.String("error", err.Error()), ) - return RunnerDockerRepository{} + return RunnerDockerAdapter{} } - return RunnerDockerRepository{ + return RunnerDockerAdapter{ cli: cli, } } -func (r RunnerDockerRepository) Delete(instance *types.Instance) error { - id, err := r.getContainerID(*instance) +func (a RunnerDockerAdapter) Delete(instance *types.Instance) error { + id, err := a.getContainerID(*instance) if err != nil { return err } - return r.cli.ContainerRemove(context.Background(), id, dockertypes.ContainerRemoveOptions{}) + return a.cli.ContainerRemove(context.Background(), id, dockertypes.ContainerRemoveOptions{}) } -func (r RunnerDockerRepository) Start(instance *types.Instance, onLog func(msg string), onErr func(msg string), setStatus func(status string)) error { +func (a RunnerDockerAdapter) Start(instance *types.Instance, onLog func(msg string), onErr func(msg string), setStatus func(status string)) error { imageName := instance.DockerImageName() setStatus(types.InstanceStatusBuilding) - instancePath := r.getPath(*instance) + instancePath := a.getPath(*instance) // Build var err error if instance.Methods.Docker.Dockerfile != nil { - err = r.buildImageFromDockerfile(instancePath, imageName, onLog) + err = a.buildImageFromDockerfile(instancePath, imageName, onLog) } else if instance.Methods.Docker.Image != nil { - err = r.buildImageFromName(*instance.Methods.Docker.Image, onLog) + err = a.buildImageFromName(*instance.Methods.Docker.Image, onLog) } else { err = errors.New("no Docker methods found") } @@ -76,7 +76,7 @@ func (r RunnerDockerRepository) Start(instance *types.Instance, onLog func(msg s } // Create - id, err := r.getContainerID(*instance) + id, err := a.getContainerID(*instance) if errors.Is(err, ErrContainerNotFound) { containerName := instance.DockerContainerName() @@ -147,10 +147,10 @@ func (r RunnerDockerRepository) Start(instance *types.Instance, onLog func(msg s } if instance.Methods.Docker.Dockerfile != nil { - id, err = r.createContainer(options) + id, err = a.createContainer(options) } else if instance.Methods.Docker.Image != nil { options.imageName = *instance.Methods.Docker.Image - id, err = r.createContainer(options) + id, err = a.createContainer(options) } if err != nil { return err @@ -160,35 +160,35 @@ func (r RunnerDockerRepository) Start(instance *types.Instance, onLog func(msg s } // Start - err = r.cli.ContainerStart(context.Background(), id, dockertypes.ContainerStartOptions{}) + err = a.cli.ContainerStart(context.Background(), id, dockertypes.ContainerStartOptions{}) if err != nil { setStatus(types.InstanceStatusError) return err } setStatus(types.InstanceStatusRunning) - r.watchForLogs(id, instance, onLog) - r.watchForStatusChange(id, instance, setStatus) + a.watchForLogs(id, instance, onLog) + a.watchForStatusChange(id, instance, setStatus) return nil } -func (r RunnerDockerRepository) Stop(instance *types.Instance) error { - id, err := r.getContainerID(*instance) +func (a RunnerDockerAdapter) Stop(instance *types.Instance) error { + id, err := a.getContainerID(*instance) if err != nil { return err } - return r.cli.ContainerStop(context.Background(), id, container.StopOptions{}) + return a.cli.ContainerStop(context.Background(), id, container.StopOptions{}) } -func (r RunnerDockerRepository) Info(instance types.Instance) (map[string]any, error) { - id, err := r.getContainerID(instance) +func (a RunnerDockerAdapter) Info(instance types.Instance) (map[string]any, error) { + id, err := a.getContainerID(instance) if err != nil { return nil, err } - info, err := r.cli.ContainerInspect(context.Background(), id) + info, err := a.cli.ContainerInspect(context.Background(), id) if err != nil { return nil, err } @@ -201,7 +201,7 @@ func (r RunnerDockerRepository) Info(instance types.Instance) (map[string]any, e }, nil } -func (r RunnerDockerRepository) CheckForUpdates(instance *types.Instance) error { +func (a RunnerDockerAdapter) CheckForUpdates(instance *types.Instance) error { if instance.Methods.Docker.Image == nil { // TODO: Support Dockerfile updates return nil @@ -209,20 +209,20 @@ func (r RunnerDockerRepository) CheckForUpdates(instance *types.Instance) error imageName := *instance.Methods.Docker.Image - res, err := r.pullImage(imageName) + res, err := a.pullImage(imageName) if err != nil { return err } defer res.Close() - imageInfo, _, err := r.cli.ImageInspectWithRaw(context.Background(), imageName) + imageInfo, _, err := a.cli.ImageInspectWithRaw(context.Background(), imageName) if err != nil { return err } latestImageID := imageInfo.ID - currentImageID, err := r.getImageID(*instance) + currentImageID, err := a.getImageID(*instance) if err != nil { return err } @@ -245,13 +245,13 @@ func (r RunnerDockerRepository) CheckForUpdates(instance *types.Instance) error return nil } -func (r RunnerDockerRepository) HasUpdateAvailable(instance types.Instance) (bool, error) { +func (a RunnerDockerAdapter) HasUpdateAvailable(instance types.Instance) (bool, error) { //TODO implement me return false, nil } -func (r RunnerDockerRepository) getContainer(instance types.Instance) (dockertypes.Container, error) { - containers, err := r.cli.ContainerList(context.Background(), dockertypes.ContainerListOptions{ +func (a RunnerDockerAdapter) getContainer(instance types.Instance) (dockertypes.Container, error) { + containers, err := a.cli.ContainerList(context.Background(), dockertypes.ContainerListOptions{ All: true, }) if err != nil { @@ -275,32 +275,32 @@ func (r RunnerDockerRepository) getContainer(instance types.Instance) (dockertyp return *dockerContainer, nil } -func (r RunnerDockerRepository) getContainerID(instance types.Instance) (string, error) { - c, err := r.getContainer(instance) +func (a RunnerDockerAdapter) getContainerID(instance types.Instance) (string, error) { + c, err := a.getContainer(instance) if err != nil { return "", err } return c.ID, nil } -func (r RunnerDockerRepository) getImageID(instance types.Instance) (string, error) { - c, err := r.getContainer(instance) +func (a RunnerDockerAdapter) getImageID(instance types.Instance) (string, error) { + c, err := a.getContainer(instance) if err != nil { return "", err } return c.ImageID, nil } -func (r RunnerDockerRepository) pullImage(imageName string) (io.ReadCloser, error) { - res, err := r.cli.ImagePull(context.Background(), imageName, dockertypes.ImagePullOptions{}) +func (a RunnerDockerAdapter) pullImage(imageName string) (io.ReadCloser, error) { + res, err := a.cli.ImagePull(context.Background(), imageName, dockertypes.ImagePullOptions{}) if err != nil { return nil, err } return res, nil } -func (r RunnerDockerRepository) buildImageFromName(imageName string, onMsg func(msg string)) error { - res, err := r.pullImage(imageName) +func (a RunnerDockerAdapter) buildImageFromName(imageName string, onMsg func(msg string)) error { + res, err := a.pullImage(imageName) if err != nil { return err } @@ -316,7 +316,7 @@ func (r RunnerDockerRepository) buildImageFromName(imageName string, onMsg func( return nil } -func (r RunnerDockerRepository) buildImageFromDockerfile(instancePath string, imageName string, onMsg func(msg string)) error { +func (a RunnerDockerAdapter) buildImageFromDockerfile(instancePath string, imageName string, onMsg func(msg string)) error { buildOptions := dockertypes.ImageBuildOptions{ Dockerfile: "Dockerfile", Tags: []string{imageName}, @@ -330,7 +330,7 @@ func (r RunnerDockerRepository) buildImageFromDockerfile(instancePath string, im return err } - res, err := r.cli.ImageBuild(context.Background(), reader, buildOptions) + res, err := a.cli.ImageBuild(context.Background(), reader, buildOptions) if err != nil { return err } @@ -369,7 +369,7 @@ type createContainerOptions struct { sysctls map[string]string } -func (r RunnerDockerRepository) createContainer(options createContainerOptions) (string, error) { +func (a RunnerDockerAdapter) createContainer(options createContainerOptions) (string, error) { config := container.Config{ Image: options.imageName, ExposedPorts: options.exposedPorts, @@ -386,7 +386,7 @@ func (r RunnerDockerRepository) createContainer(options createContainerOptions) Sysctls: options.sysctls, } - res, err := r.cli.ContainerCreate(context.Background(), &config, &hostConfig, nil, nil, options.containerName) + res, err := a.cli.ContainerCreate(context.Background(), &config, &hostConfig, nil, nil, options.containerName) for _, warn := range res.Warnings { log.Default.Warn("warning while creating container", vlog.String("warning", warn), @@ -395,9 +395,9 @@ func (r RunnerDockerRepository) createContainer(options createContainerOptions) return res.ID, err } -func (r RunnerDockerRepository) watchForStatusChange(containerID string, instance *types.Instance, setStatus func(status string)) { +func (a RunnerDockerAdapter) watchForStatusChange(containerID string, instance *types.Instance, setStatus func(status string)) { go func() { - resChan, errChan := r.cli.ContainerWait(context.Background(), containerID, container.WaitConditionNotRunning) + resChan, errChan := a.cli.ContainerWait(context.Background(), containerID, container.WaitConditionNotRunning) select { case err := <-errChan: @@ -416,9 +416,9 @@ func (r RunnerDockerRepository) watchForStatusChange(containerID string, instanc }() } -func (r RunnerDockerRepository) watchForLogs(containerID string, instance *types.Instance, onLog func(msg string)) { +func (a RunnerDockerAdapter) watchForLogs(containerID string, instance *types.Instance, onLog func(msg string)) { go func() { - logs, err := r.cli.ContainerLogs(context.Background(), containerID, dockertypes.ContainerLogsOptions{ + logs, err := a.cli.ContainerLogs(context.Background(), containerID, dockertypes.ContainerLogsOptions{ ShowStdout: true, ShowStderr: true, Timestamps: false, @@ -442,6 +442,6 @@ func (r RunnerDockerRepository) watchForLogs(containerID string, instance *types }() } -func (r RunnerDockerRepository) getPath(instance types.Instance) string { +func (a RunnerDockerAdapter) getPath(instance types.Instance) string { return path.Join(storage.Path, "instances", instance.UUID.String()) } diff --git a/repository/runner_fs.go b/adapter/runner_fs.go similarity index 66% rename from repository/runner_fs.go rename to adapter/runner_fs.go index 25c7b955..62aa7a4c 100644 --- a/repository/runner_fs.go +++ b/adapter/runner_fs.go @@ -1,4 +1,4 @@ -package repository +package adapter import ( "bufio" @@ -15,28 +15,28 @@ import ( "github.com/vertex-center/vlog" ) -type RunnerFSRepository struct { +type RunnerFSAdapter struct { commands map[uuid.UUID]*exec.Cmd } -func NewRunnerFSRepository() RunnerFSRepository { - return RunnerFSRepository{ +func NewRunnerFSAdapter() RunnerFSAdapter { + return RunnerFSAdapter{ commands: map[uuid.UUID]*exec.Cmd{}, } } -func (r RunnerFSRepository) Delete(instance *types.Instance) error { +func (a RunnerFSAdapter) Delete(instance *types.Instance) error { return nil } -func (r RunnerFSRepository) Start(instance *types.Instance, onLog func(msg string), onErr func(msg string), setStatus func(status string)) error { - if r.commands[instance.UUID] != nil { +func (a RunnerFSAdapter) Start(instance *types.Instance, onLog func(msg string), onErr func(msg string), setStatus func(status string)) error { + if a.commands[instance.UUID] != nil { log.Default.Error(errors.New("runner already started"), vlog.String("name", instance.Name), ) } - dir := r.getPath(*instance) + dir := a.getPath(*instance) executable := instance.Methods.Script.Filename command := "./" + executable @@ -47,13 +47,13 @@ func (r RunnerFSRepository) Start(instance *types.Instance, onLog func(msg strin return err } - r.commands[instance.UUID] = exec.Command(command) + a.commands[instance.UUID] = exec.Command(command) - cmd := r.commands[instance.UUID] + cmd := a.commands[instance.UUID] cmd.Dir = dir cmd.Env = os.Environ() - envFile, err := os.Open(path.Join(r.getPath(*instance), ".env")) + envFile, err := os.Open(path.Join(a.getPath(*instance), ".env")) if err != nil { return err } @@ -112,8 +112,8 @@ func (r RunnerFSRepository) Start(instance *types.Instance, onLog func(msg strin return nil } -func (r RunnerFSRepository) Stop(instance *types.Instance) error { - cmd := r.commands[instance.UUID] +func (a RunnerFSAdapter) Stop(instance *types.Instance) error { + cmd := a.commands[instance.UUID] err := cmd.Process.Signal(os.Interrupt) if err != nil { @@ -122,25 +122,25 @@ func (r RunnerFSRepository) Stop(instance *types.Instance) error { // TODO: Force kill if the process continues - delete(r.commands, instance.UUID) + delete(a.commands, instance.UUID) return nil } -func (r RunnerFSRepository) Info(instance types.Instance) (map[string]any, error) { +func (a RunnerFSAdapter) Info(instance types.Instance) (map[string]any, error) { return map[string]any{}, nil } -func (r RunnerFSRepository) CheckForUpdates(instance *types.Instance) error { +func (a RunnerFSAdapter) CheckForUpdates(instance *types.Instance) error { //TODO implement me return nil } -func (r RunnerFSRepository) HasUpdateAvailable(instance types.Instance) (bool, error) { +func (a RunnerFSAdapter) HasUpdateAvailable(instance types.Instance) (bool, error) { //TODO implement me return false, nil } -func (r RunnerFSRepository) getPath(instance types.Instance) string { +func (a RunnerFSAdapter) getPath(instance types.Instance) string { return path.Join(storage.Path, "instances", instance.UUID.String()) } diff --git a/repository/service_fs.go b/adapter/service_fs.go similarity index 56% rename from repository/service_fs.go rename to adapter/service_fs.go index 0e361c57..24be6b74 100644 --- a/repository/service_fs.go +++ b/adapter/service_fs.go @@ -1,4 +1,4 @@ -package repository +package adapter import ( "errors" @@ -12,35 +12,35 @@ import ( "gopkg.in/yaml.v2" ) -type ServiceFSRepository struct { +type ServiceFSAdapter struct { servicesPath string services []types.Service } -type ServiceRepositoryParams struct { +type ServiceFSAdapterParams struct { servicesPath string } -func NewServiceFSRepository(params *ServiceRepositoryParams) ServiceFSRepository { +func NewServiceFSAdapter(params *ServiceFSAdapterParams) types.ServiceAdapterPort { if params == nil { - params = &ServiceRepositoryParams{} + params = &ServiceFSAdapterParams{} } if params.servicesPath == "" { params.servicesPath = path.Join(storage.Path, "services") } - repo := ServiceFSRepository{ + adapter := &ServiceFSAdapter{ servicesPath: params.servicesPath, } - err := repo.Reload() + err := adapter.Reload() if err != nil { - log.Default.Error(fmt.Errorf("failed to reload services repository: %v", err)) + log.Default.Error(fmt.Errorf("failed to reload services: %v", err)) } - return repo + return adapter } -func (r *ServiceFSRepository) Get(id string) (types.Service, error) { - for _, service := range r.services { +func (a *ServiceFSAdapter) Get(id string) (types.Service, error) { + for _, service := range a.services { if service.ID == id { return service, nil } @@ -49,8 +49,8 @@ func (r *ServiceFSRepository) Get(id string) (types.Service, error) { return types.Service{}, types.ErrServiceNotFound } -func (r *ServiceFSRepository) GetScript(id string) ([]byte, error) { - service, err := r.Get(id) +func (a *ServiceFSAdapter) GetScript(id string) ([]byte, error) { + service, err := a.Get(id) if err != nil { return nil, err } @@ -59,17 +59,17 @@ func (r *ServiceFSRepository) GetScript(id string) ([]byte, error) { return nil, errors.New("the service doesn't have a script method") } - return os.ReadFile(path.Join(r.servicesPath, "services", id, service.Methods.Script.Filename)) + return os.ReadFile(path.Join(a.servicesPath, "services", id, service.Methods.Script.Filename)) } -func (r *ServiceFSRepository) GetAll() []types.Service { - return r.services +func (a *ServiceFSAdapter) GetAll() []types.Service { + return a.services } -func (r *ServiceFSRepository) Reload() error { - servicesPath := path.Join(r.servicesPath, "services") +func (a *ServiceFSAdapter) Reload() error { + servicesPath := path.Join(a.servicesPath, "services") - r.services = []types.Service{} + a.services = []types.Service{} entries, err := os.ReadDir(servicesPath) if err != nil { @@ -94,7 +94,7 @@ func (r *ServiceFSRepository) Reload() error { return err } - r.services = append(r.services, service) + a.services = append(a.services, service) } return nil diff --git a/repository/service_fs_test.go b/adapter/service_fs_test.go similarity index 62% rename from repository/service_fs_test.go rename to adapter/service_fs_test.go index 9d191e38..21bb4877 100644 --- a/repository/service_fs_test.go +++ b/adapter/service_fs_test.go @@ -1,4 +1,4 @@ -package repository +package adapter import ( "testing" @@ -14,7 +14,7 @@ const ( type AvailableTestSuite struct { suite.Suite - repo ServiceFSRepository + adapter ServiceFSAdapter } func TestAvailableTestSuite(t *testing.T) { @@ -22,16 +22,16 @@ func TestAvailableTestSuite(t *testing.T) { } func (suite *AvailableTestSuite) SetupSuite() { - suite.repo = NewServiceFSRepository(&ServiceRepositoryParams{ + suite.adapter = *NewServiceFSAdapter(&ServiceFSAdapterParams{ servicesPath: PathServices, - }) + }).(*ServiceFSAdapter) - err := suite.repo.Reload() + err := suite.adapter.Reload() assert.NoError(suite.T(), err) - assert.NotZero(suite.T(), len(suite.repo.services)) + assert.NotZero(suite.T(), len(suite.adapter.services)) } func (suite *AvailableTestSuite) TestGetAvailable() { - assert.Equal(suite.T(), 1, len(suite.repo.GetAll())) + assert.Equal(suite.T(), 1, len(suite.adapter.GetAll())) } diff --git a/repository/settings_fs.go b/adapter/settings_fs.go similarity index 51% rename from repository/settings_fs.go rename to adapter/settings_fs.go index 2d59875e..65c6adb0 100644 --- a/repository/settings_fs.go +++ b/adapter/settings_fs.go @@ -1,4 +1,4 @@ -package repository +package adapter import ( "encoding/json" @@ -12,18 +12,18 @@ import ( "github.com/vertex-center/vlog" ) -type SettingsFSRepository struct { +type SettingsFSAdapter struct { settingsPath string settings types.Settings } -type SettingsRepositoryParams struct { +type SettingsFSAdapterParams struct { settingsPath string } -func NewSettingsFSRepository(params *SettingsRepositoryParams) SettingsFSRepository { +func NewSettingsFSAdapter(params *SettingsFSAdapterParams) types.SettingsAdapterPort { if params == nil { - params = &SettingsRepositoryParams{} + params = &SettingsFSAdapterParams{} } if params.settingsPath == "" { params.settingsPath = path.Join(storage.Path, "settings") @@ -38,39 +38,39 @@ func NewSettingsFSRepository(params *SettingsRepositoryParams) SettingsFSReposit os.Exit(1) } - repo := SettingsFSRepository{ + adapter := &SettingsFSAdapter{ settingsPath: params.settingsPath, } - err = repo.read() + err = adapter.read() if err != nil { log.Default.Error(err) } - return repo + return adapter } -func (r *SettingsFSRepository) GetSettings() types.Settings { - return r.settings +func (a *SettingsFSAdapter) GetSettings() types.Settings { + return a.settings } -func (r *SettingsFSRepository) GetNotificationsWebhook() *string { - if r.settings.Notifications == nil { +func (a *SettingsFSAdapter) GetNotificationsWebhook() *string { + if a.settings.Notifications == nil { return nil } - return r.settings.Notifications.Webhook + return a.settings.Notifications.Webhook } -func (r *SettingsFSRepository) SetNotificationsWebhook(webhook *string) error { - if r.settings.Notifications == nil { - r.settings.Notifications = &types.SettingsNotifications{} +func (a *SettingsFSAdapter) SetNotificationsWebhook(webhook *string) error { + if a.settings.Notifications == nil { + a.settings.Notifications = &types.SettingsNotifications{} } - r.settings.Notifications.Webhook = webhook - return r.write() + a.settings.Notifications.Webhook = webhook + return a.write() } -func (r *SettingsFSRepository) read() error { - p := path.Join(r.settingsPath, "settings.json") +func (a *SettingsFSAdapter) read() error { + p := path.Join(a.settingsPath, "settings.json") file, err := os.ReadFile(p) if errors.Is(err, os.ErrNotExist) { @@ -80,7 +80,7 @@ func (r *SettingsFSRepository) read() error { return err } - err = json.Unmarshal(file, &r.settings) + err = json.Unmarshal(file, &a.settings) if err != nil { return err } @@ -88,10 +88,10 @@ func (r *SettingsFSRepository) read() error { return nil } -func (r *SettingsFSRepository) write() error { - p := path.Join(r.settingsPath, "settings.json") +func (a *SettingsFSAdapter) write() error { + p := path.Join(a.settingsPath, "settings.json") - bytes, err := json.MarshalIndent(r.settings, "", "\t") + bytes, err := json.MarshalIndent(a.settings, "", "\t") if err != nil { return err } diff --git a/repository/tests/packages/packages/code-server/code-server.json b/adapter/tests/packages/packages/code-server/code-server.json similarity index 100% rename from repository/tests/packages/packages/code-server/code-server.json rename to adapter/tests/packages/packages/code-server/code-server.json diff --git a/repository/tests/packages/packages/redis/redis.json b/adapter/tests/packages/packages/redis/redis.json similarity index 100% rename from repository/tests/packages/packages/redis/redis.json rename to adapter/tests/packages/packages/redis/redis.json diff --git a/repository/tests/services/services/redis/service.yml b/adapter/tests/services/services/redis/service.yml similarity index 100% rename from repository/tests/services/services/redis/service.yml rename to adapter/tests/services/services/redis/service.yml diff --git a/repository/event_in_memory.go b/repository/event_in_memory.go deleted file mode 100644 index 66638420..00000000 --- a/repository/event_in_memory.go +++ /dev/null @@ -1,30 +0,0 @@ -package repository - -import ( - "github.com/google/uuid" - "github.com/vertex-center/vertex/types" -) - -type EventInMemoryRepository struct { - listeners *map[uuid.UUID]types.Listener -} - -func NewEventInMemoryRepository() EventInMemoryRepository { - return EventInMemoryRepository{ - listeners: &map[uuid.UUID]types.Listener{}, - } -} - -func (r *EventInMemoryRepository) AddListener(l types.Listener) { - (*r.listeners)[l.GetUUID()] = l -} - -func (r *EventInMemoryRepository) RemoveListener(l types.Listener) { - delete(*r.listeners, l.GetUUID()) -} - -func (r *EventInMemoryRepository) Send(e interface{}) { - for _, l := range *r.listeners { - l.OnEvent(e) - } -} diff --git a/repository/package_fs_test.go b/repository/package_fs_test.go deleted file mode 100644 index 2b122769..00000000 --- a/repository/package_fs_test.go +++ /dev/null @@ -1,54 +0,0 @@ -package repository - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/suite" -) - -const ( - PathPackages = "tests/packages" -) - -type PackageRepositoryTestSuite struct { - suite.Suite - - repo PackageFSRepository -} - -func TestPackageRepositoryTestSuite(t *testing.T) { - suite.Run(t, new(PackageRepositoryTestSuite)) -} - -func (suite *PackageRepositoryTestSuite) SetupSuite() { - suite.repo = NewPackageFSRepository(&PackageRepositoryParams{ - dependenciesPath: PathPackages, - }) - - err := suite.repo.Reload() - assert.NoError(suite.T(), err) - assert.NoError(suite.T(), err) - assert.NotEqual(suite.T(), 0, len(suite.repo.pkgs)) - assert.Equal(suite.T(), "Redis", suite.repo.pkgs["redis"].Name) - assert.Equal(suite.T(), "BSD-3", suite.repo.pkgs["redis"].License) -} - -func (suite *PackageRepositoryTestSuite) TestGetPath() { - p := suite.repo.GetPath("redis") - assert.Equal(suite.T(), "tests/packages/packages/redis", p) -} - -func (suite *PackageRepositoryTestSuite) TestReload() { - err := suite.repo.Reload() - assert.NoError(suite.T(), err) -} - -func (suite *PackageRepositoryTestSuite) TestGet() { - pkg, err := suite.repo.GetByID("redis") - assert.NoError(suite.T(), err) - assert.Equal(suite.T(), pkg.Name, "Redis") - - _, err = suite.repo.GetByID("undefined_package_name") - assert.ErrorIs(suite.T(), err, ErrPkgNotFound) -} diff --git a/router/instance.go b/router/instance.go index 8e0f1afb..9995aed6 100644 --- a/router/instance.go +++ b/router/instance.go @@ -195,8 +195,8 @@ func handleInstanceEvents(c *gin.Context) { } }) - eventRepo.AddListener(listener) - defer eventRepo.RemoveListener(listener) + eventInMemoryAdapter.AddListener(listener) + defer eventInMemoryAdapter.RemoveListener(listener) first := true diff --git a/router/instances.go b/router/instances.go index ac1e6e17..5dd8dfcf 100644 --- a/router/instances.go +++ b/router/instances.go @@ -46,8 +46,8 @@ func handleInstancesEvents(c *gin.Context) { } }) - eventRepo.AddListener(listener) - defer eventRepo.RemoveListener(listener) + eventInMemoryAdapter.AddListener(listener) + defer eventInMemoryAdapter.RemoveListener(listener) first := true diff --git a/router/router.go b/router/router.go index 33198f36..8843b150 100644 --- a/router/router.go +++ b/router/router.go @@ -13,24 +13,24 @@ import ( "github.com/gin-contrib/static" "github.com/gin-gonic/gin" "github.com/vertex-center/vertex-core-golang/router/middleware" + "github.com/vertex-center/vertex/adapter" "github.com/vertex-center/vertex/pkg/ginutils" "github.com/vertex-center/vertex/pkg/log" "github.com/vertex-center/vertex/pkg/storage" - "github.com/vertex-center/vertex/repository" "github.com/vertex-center/vertex/services" "github.com/vertex-center/vertex/types" ) var ( - runnerDockerRepo repository.RunnerDockerRepository - runnerFSRepo repository.RunnerFSRepository - instanceRepo repository.InstanceFSRepository - instanceLogsRepo repository.InstanceLogsFSRepository - eventRepo repository.EventInMemoryRepository - packageRepo repository.PackageFSRepository - serviceRepo repository.ServiceFSRepository - proxyRepo repository.ProxyFSRepository - settingsRepo repository.SettingsFSRepository + runnerDockerAdapter types.RunnerAdapterPort + runnerFSAdapter types.RunnerAdapterPort + instanceFSAdapter types.InstanceAdapterPort + instanceLogsFSAdapter types.InstanceLogsAdapterPort + eventInMemoryAdapter types.EventAdapterPort + packageFSAdapter types.PackageAdapterPort + serviceFSAdapter types.ServiceAdapterPort + proxyFSAdapter types.ProxyAdapterPort + settingsFSAdapter types.SettingsAdapterPort packageService services.PackageService notificationsService services.NotificationsService @@ -59,23 +59,23 @@ func NewRouter(about types.About) Router { r.Use(static.Serve("/", static.LocalFile(path.Join(".", storage.Path, "client", "dist"), true))) r.GET("/ping", handlePing) - runnerDockerRepo = repository.NewRunnerDockerRepository() - runnerFSRepo = repository.NewRunnerFSRepository() - instanceRepo = repository.NewInstanceFSRepository() - instanceLogsRepo = repository.NewInstanceLogsFSRepository() - eventRepo = repository.NewEventInMemoryRepository() - packageRepo = repository.NewPackageFSRepository(nil) - serviceRepo = repository.NewServiceFSRepository(nil) - proxyRepo = repository.NewProxyFSRepository(nil) - settingsRepo = repository.NewSettingsFSRepository(nil) - - proxyService = services.NewProxyService(&proxyRepo) - notificationsService = services.NewNotificationsService(&settingsRepo, &eventRepo, &instanceRepo) - instanceService = services.NewInstanceService(&serviceRepo, &instanceRepo, &runnerDockerRepo, &runnerFSRepo, &instanceLogsRepo, &eventRepo) - packageService = services.NewPackageService(&packageRepo) - serviceService = services.NewServiceService(&serviceRepo) + runnerDockerAdapter = adapter.NewRunnerDockerAdapter() + runnerFSAdapter = adapter.NewRunnerFSAdapter() + instanceFSAdapter = adapter.NewInstanceFSAdapter() + instanceLogsFSAdapter = adapter.NewInstanceLogsFSAdapter() + eventInMemoryAdapter = adapter.NewEventInMemoryAdapter() + packageFSAdapter = adapter.NewPackageFSAdapter(nil) + serviceFSAdapter = adapter.NewServiceFSAdapter(nil) + proxyFSAdapter = adapter.NewProxyFSAdapter(nil) + settingsFSAdapter = adapter.NewSettingsFSAdapter(nil) + + proxyService = services.NewProxyService(proxyFSAdapter) + notificationsService = services.NewNotificationsService(settingsFSAdapter, eventInMemoryAdapter, instanceFSAdapter) + instanceService = services.NewInstanceService(serviceFSAdapter, instanceFSAdapter, runnerDockerAdapter, runnerFSAdapter, instanceLogsFSAdapter, eventInMemoryAdapter) + packageService = services.NewPackageService(packageFSAdapter) + serviceService = services.NewServiceService(serviceFSAdapter) updateService = services.NewUpdateDependenciesService(about.Version) - settingsService = services.NewSettingsService(&settingsRepo) + settingsService = services.NewSettingsService(settingsFSAdapter) api := r.Group("/api") api.GET("/ping", handlePing) diff --git a/router/settings.go b/router/settings.go index a78331db..447c32aa 100644 --- a/router/settings.go +++ b/router/settings.go @@ -14,7 +14,7 @@ func addSettingsRoutes(r *gin.RouterGroup) { } func handleGetSettings(c *gin.Context) { - c.JSON(http.StatusOK, settingsRepo.GetSettings()) + c.JSON(http.StatusOK, settingsFSAdapter.GetSettings()) } func handlePatchSettings(c *gin.Context) { diff --git a/services/instance.go b/services/instance.go index 7bab5eb0..cfda8585 100644 --- a/services/instance.go +++ b/services/instance.go @@ -27,25 +27,25 @@ var ( type InstanceService struct { uuid uuid.UUID - serviceRepo types.ServiceRepository - instanceRepo types.InstanceRepository - logsRepo types.InstanceLogsRepository - eventsRepo types.EventRepository + serviceAdapter types.ServiceAdapterPort + instanceAdapter types.InstanceAdapterPort + logsAdapter types.InstanceLogsAdapterPort + eventsAdapter types.EventAdapterPort - dockerRunnerRepo types.RunnerRepository - fsRunnerRepo types.RunnerRepository + dockerRunnerAdapter types.RunnerAdapterPort + fsRunnerAdapter types.RunnerAdapterPort } -func NewInstanceService(serviceRepo types.ServiceRepository, instanceRepo types.InstanceRepository, dockerRunnerRepo types.RunnerRepository, fsRunnerRepo types.RunnerRepository, instanceLogsRepo types.InstanceLogsRepository, eventRepo types.EventRepository) InstanceService { +func NewInstanceService(serviceAdapter types.ServiceAdapterPort, instanceAdapter types.InstanceAdapterPort, dockerRunnerAdapter types.RunnerAdapterPort, fsRunnerAdapter types.RunnerAdapterPort, instanceLogsAdapter types.InstanceLogsAdapterPort, eventRepo types.EventAdapterPort) InstanceService { s := InstanceService{ uuid: uuid.New(), - serviceRepo: serviceRepo, - instanceRepo: instanceRepo, - logsRepo: instanceLogsRepo, - eventsRepo: eventRepo, - dockerRunnerRepo: dockerRunnerRepo, - fsRunnerRepo: fsRunnerRepo, + serviceAdapter: serviceAdapter, + instanceAdapter: instanceAdapter, + logsAdapter: instanceLogsAdapter, + eventsAdapter: eventRepo, + dockerRunnerAdapter: dockerRunnerAdapter, + fsRunnerAdapter: fsRunnerAdapter, } s.reload() @@ -56,15 +56,15 @@ func NewInstanceService(serviceRepo types.ServiceRepository, instanceRepo types. } func (s *InstanceService) Get(uuid uuid.UUID) (*types.Instance, error) { - return s.instanceRepo.Get(uuid) + return s.instanceAdapter.Get(uuid) } func (s *InstanceService) GetAll() map[uuid.UUID]*types.Instance { - return s.instanceRepo.GetAll() + return s.instanceAdapter.GetAll() } func (s *InstanceService) Delete(uuid uuid.UUID) error { - instance, err := s.instanceRepo.Get(uuid) + instance, err := s.instanceAdapter.Get(uuid) if err != nil { return err } @@ -74,30 +74,30 @@ func (s *InstanceService) Delete(uuid uuid.UUID) error { } if instance.IsDockerized() { - err = s.dockerRunnerRepo.Delete(instance) + err = s.dockerRunnerAdapter.Delete(instance) } else { - err = s.fsRunnerRepo.Delete(instance) + err = s.fsRunnerAdapter.Delete(instance) } if err != nil { return err } - err = s.instanceRepo.Delete(uuid) + err = s.instanceAdapter.Delete(uuid) if err != nil { return err } - s.eventsRepo.Send(types.EventInstancesChange{}) + s.eventsAdapter.Send(types.EventInstancesChange{}) return nil } func (s *InstanceService) Start(uuid uuid.UUID) error { - instance, err := s.instanceRepo.Get(uuid) + instance, err := s.instanceAdapter.Get(uuid) if err != nil { return err } - s.eventsRepo.Send(types.EventInstanceLog{ + s.eventsAdapter.Send(types.EventInstanceLog{ InstanceUUID: uuid, Kind: types.LogKindOut, Message: "Starting instance...", @@ -108,7 +108,7 @@ func (s *InstanceService) Start(uuid uuid.UUID) error { ) if instance.IsRunning() { - s.eventsRepo.Send(types.EventInstanceLog{ + s.eventsAdapter.Send(types.EventInstanceLog{ InstanceUUID: uuid, Kind: types.LogKindVertexErr, Message: ErrInstanceAlreadyRunning.Error(), @@ -117,7 +117,7 @@ func (s *InstanceService) Start(uuid uuid.UUID) error { } onLog := func(msg string) { - s.eventsRepo.Send(types.EventInstanceLog{ + s.eventsAdapter.Send(types.EventInstanceLog{ InstanceUUID: uuid, Kind: types.LogKindOut, Message: msg, @@ -125,7 +125,7 @@ func (s *InstanceService) Start(uuid uuid.UUID) error { } onErr := func(msg string) { - s.eventsRepo.Send(types.EventInstanceLog{ + s.eventsAdapter.Send(types.EventInstanceLog{ InstanceUUID: uuid, Kind: types.LogKindErr, Message: msg, @@ -137,15 +137,15 @@ func (s *InstanceService) Start(uuid uuid.UUID) error { } if instance.IsDockerized() { - err = s.dockerRunnerRepo.Start(instance, onLog, onErr, setStatus) + err = s.dockerRunnerAdapter.Start(instance, onLog, onErr, setStatus) } else { - err = s.fsRunnerRepo.Start(instance, onLog, onErr, setStatus) + err = s.fsRunnerAdapter.Start(instance, onLog, onErr, setStatus) } if err != nil { s.setStatus(instance, types.InstanceStatusError) } else { - s.eventsRepo.Send(types.EventInstanceLog{ + s.eventsAdapter.Send(types.EventInstanceLog{ InstanceUUID: uuid, Kind: types.LogKindVertexOut, Message: "Instance started.", @@ -163,7 +163,7 @@ func (s *InstanceService) StartAll() { var ids []uuid.UUID // Select instances that should launch on startup - for _, i := range s.instanceRepo.GetAll() { + for _, i := range s.instanceAdapter.GetAll() { launchOnStartup := i.InstanceSettings.LaunchOnStartup if launchOnStartup != nil && !*launchOnStartup { @@ -202,12 +202,12 @@ func (s *InstanceService) StartAll() { } func (s *InstanceService) Stop(uuid uuid.UUID) error { - instance, err := s.instanceRepo.Get(uuid) + instance, err := s.instanceAdapter.Get(uuid) if err != nil { return err } - s.eventsRepo.Send(types.EventInstanceLog{ + s.eventsAdapter.Send(types.EventInstanceLog{ InstanceUUID: uuid, Kind: types.LogKindVertexOut, Message: "Stopping instance...", @@ -218,7 +218,7 @@ func (s *InstanceService) Stop(uuid uuid.UUID) error { ) if !instance.IsRunning() { - s.eventsRepo.Send(types.EventInstanceLog{ + s.eventsAdapter.Send(types.EventInstanceLog{ InstanceUUID: uuid, Kind: types.LogKindVertexErr, Message: ErrInstanceNotRunning.Error(), @@ -229,13 +229,13 @@ func (s *InstanceService) Stop(uuid uuid.UUID) error { s.setStatus(instance, types.InstanceStatusStopping) if instance.IsDockerized() { - err = s.dockerRunnerRepo.Stop(instance) + err = s.dockerRunnerAdapter.Stop(instance) } else { - err = s.fsRunnerRepo.Stop(instance) + err = s.fsRunnerAdapter.Stop(instance) } if err == nil { - s.eventsRepo.Send(types.EventInstanceLog{ + s.eventsAdapter.Send(types.EventInstanceLog{ InstanceUUID: uuid, Kind: types.LogKindVertexOut, Message: "Instance stopped.", @@ -254,7 +254,7 @@ func (s *InstanceService) Stop(uuid uuid.UUID) error { } func (s *InstanceService) StopAll() { - for _, i := range s.instanceRepo.GetAll() { + for _, i := range s.instanceAdapter.GetAll() { if !i.IsRunning() { continue } @@ -271,14 +271,14 @@ func (s *InstanceService) WriteEnv(uuid uuid.UUID, environment map[string]string return err } - return s.instanceRepo.SaveEnv(i, environment) + return s.instanceAdapter.SaveEnv(i, environment) } func (s *InstanceService) Install(serviceID string, method string) (*types.Instance, error) { id := uuid.New() - dir := s.instanceRepo.GetPath(id) + dir := s.instanceAdapter.GetPath(id) - service, err := s.serviceRepo.Get(serviceID) + service, err := s.serviceAdapter.Get(serviceID) if err != nil { return nil, err } @@ -320,14 +320,14 @@ func (s *InstanceService) Install(serviceID string, method string) (*types.Insta return nil, err } - instance, err := s.instanceRepo.Get(id) + instance, err := s.instanceAdapter.Get(id) if err != nil { return nil, err } instance.InstanceSettings.InstallMethod = &method - err = s.instanceRepo.SaveSettings(instance) + err = s.instanceAdapter.SaveSettings(instance) if err != nil { return nil, err } @@ -337,7 +337,7 @@ func (s *InstanceService) Install(serviceID string, method string) (*types.Insta env[v.Name] = v.Default } - err = s.instanceRepo.SaveEnv(instance, env) + err = s.instanceAdapter.SaveEnv(instance, env) if err != nil { return nil, err } @@ -350,9 +350,9 @@ func (s *InstanceService) CheckForUpdates() (map[uuid.UUID]*types.Instance, erro var err error if instance.IsDockerized() { - err = s.dockerRunnerRepo.CheckForUpdates(instance) + err = s.dockerRunnerAdapter.CheckForUpdates(instance) } else { - err = s.fsRunnerRepo.CheckForUpdates(instance) + err = s.fsRunnerAdapter.CheckForUpdates(instance) } if err != nil { @@ -370,7 +370,7 @@ func (s *InstanceService) SetLaunchOnStartup(uuid uuid.UUID, value bool) error { } i.InstanceSettings.LaunchOnStartup = &value - return s.instanceRepo.SaveSettings(i) + return s.instanceAdapter.SaveSettings(i) } func (s *InstanceService) SetDisplayName(uuid uuid.UUID, value string) error { @@ -380,7 +380,7 @@ func (s *InstanceService) SetDisplayName(uuid uuid.UUID, value string) error { } i.InstanceSettings.DisplayName = &value - return s.instanceRepo.SaveSettings(i) + return s.instanceAdapter.SaveSettings(i) } func (s *InstanceService) GetDockerContainerInfo(uuid uuid.UUID) (map[string]any, error) { @@ -393,7 +393,7 @@ func (s *InstanceService) GetDockerContainerInfo(uuid uuid.UUID) (map[string]any return nil, errors.New("instance is not using docker") } - info, err := s.dockerRunnerRepo.Info(*instance) + info, err := s.dockerRunnerAdapter.Info(*instance) if err != nil { return nil, err } @@ -402,7 +402,7 @@ func (s *InstanceService) GetDockerContainerInfo(uuid uuid.UUID) (map[string]any } func (s *InstanceService) GetLatestLogs(uuid uuid.UUID) ([]types.LogLine, error) { - return s.logsRepo.LoadBuffer(uuid) + return s.logsAdapter.LoadBuffer(uuid) } func (s *InstanceService) CloneRepository(dir string, url string) error { @@ -425,7 +425,7 @@ func (s *InstanceService) DownloadRelease(dir string, repo string) error { func (s *InstanceService) Symlink(path string, repo string) error { p := strings.Split(repo, ":")[1] - _, err := s.instanceRepo.ReadService(p) + _, err := s.instanceAdapter.ReadService(p) if err != nil { return fmt.Errorf("%s is not a compatible Vertex service", repo) } @@ -436,7 +436,7 @@ func (s *InstanceService) Symlink(path string, repo string) error { func (s *InstanceService) OnEvent(e interface{}) { switch e := e.(type) { case types.EventInstanceLog: - s.logsRepo.Push(e.InstanceUUID, types.LogLine{ + s.logsAdapter.Push(e.InstanceUUID, types.LogLine{ Kind: e.Kind, Message: e.Message, }) @@ -453,15 +453,15 @@ func (s *InstanceService) setStatus(instance *types.Instance, status string) { } instance.Status = status - s.eventsRepo.Send(types.EventInstancesChange{}) - s.eventsRepo.Send(types.EventInstanceStatusChange{ + s.eventsAdapter.Send(types.EventInstancesChange{}) + s.eventsAdapter.Send(types.EventInstanceStatusChange{ InstanceUUID: instance.UUID, Status: status, }) } func (s *InstanceService) reload() { - s.instanceRepo.Reload(func(uuid uuid.UUID) { + s.instanceAdapter.Reload(func(uuid uuid.UUID) { err := s.load(uuid) if err != nil { log.Default.Error(err) @@ -471,31 +471,31 @@ func (s *InstanceService) reload() { } func (s *InstanceService) load(uuid uuid.UUID) error { - instancePath := s.instanceRepo.GetPath(uuid) + instancePath := s.instanceAdapter.GetPath(uuid) - service, err := s.instanceRepo.ReadService(instancePath) + service, err := s.instanceAdapter.ReadService(instancePath) if err != nil { return err } instance := types.NewInstance(uuid, service) - err = s.instanceRepo.LoadSettings(&instance) + err = s.instanceAdapter.LoadSettings(&instance) if err != nil { return err } - err = s.instanceRepo.LoadEnv(&instance) + err = s.instanceAdapter.LoadEnv(&instance) if err != nil { return err } - err = s.instanceRepo.Set(uuid, instance) + err = s.instanceAdapter.Set(uuid, instance) if err != nil { return err } - err = s.logsRepo.Open(uuid) + err = s.logsAdapter.Open(uuid) if err != nil { return err } @@ -515,7 +515,7 @@ func (s *InstanceService) PreInstallForScript(service types.Service, dir string) } } - script, err := s.serviceRepo.GetScript(service.ID) + script, err := s.serviceAdapter.GetScript(service.ID) if err != nil { return err } @@ -557,13 +557,13 @@ func (s *InstanceService) RecreateContainer(instance *types.Instance) error { } if instance.IsRunning() { - err := s.dockerRunnerRepo.Stop(instance) + err := s.dockerRunnerAdapter.Stop(instance) if err != nil { return err } } - err := s.dockerRunnerRepo.Delete(instance) + err := s.dockerRunnerAdapter.Delete(instance) if err != nil { return err } diff --git a/services/notifications.go b/services/notifications.go index 1f9e302d..30c829b3 100644 --- a/services/notifications.go +++ b/services/notifications.go @@ -8,27 +8,27 @@ import ( "github.com/vertex-center/vertex/types" ) -// TODO: Move webhooks use to a Discord repo +// TODO: Move webhooks use to a Discord adapter type NotificationsService struct { - settingsRepo types.SettingsRepository - eventsRepo types.EventRepository - instanceRepo types.InstanceRepository + settingsAdapter types.SettingsAdapterPort + eventsAdapter types.EventAdapterPort + instanceAdapter types.InstanceAdapterPort client webhook.Client listener types.Listener } -func NewNotificationsService(settingsRepo types.SettingsRepository, eventsRepo types.EventRepository, instanceRepo types.InstanceRepository) NotificationsService { +func NewNotificationsService(settingsAdapter types.SettingsAdapterPort, eventsAdapter types.EventAdapterPort, instanceAdapter types.InstanceAdapterPort) NotificationsService { return NotificationsService{ - settingsRepo: settingsRepo, - eventsRepo: eventsRepo, - instanceRepo: instanceRepo, + settingsAdapter: settingsAdapter, + eventsAdapter: eventsAdapter, + instanceAdapter: instanceAdapter, } } func (s *NotificationsService) StartWebhook() error { - webhookURL := s.settingsRepo.GetNotificationsWebhook() + webhookURL := s.settingsAdapter.GetNotificationsWebhook() if webhookURL == nil { return nil } @@ -48,13 +48,13 @@ func (s *NotificationsService) StartWebhook() error { } }) - s.eventsRepo.AddListener(s.listener) + s.eventsAdapter.AddListener(s.listener) return nil } func (s *NotificationsService) StopWebhook() { - s.eventsRepo.RemoveListener(s.listener) + s.eventsAdapter.RemoveListener(s.listener) } func (s *NotificationsService) sendStatus(instanceUUID uuid.UUID, status string) { @@ -69,7 +69,7 @@ func (s *NotificationsService) sendStatus(instanceUUID uuid.UUID, status string) color = 10038562 } - instance, err := s.instanceRepo.Get(instanceUUID) + instance, err := s.instanceAdapter.Get(instanceUUID) if err != nil { log.Default.Error(err) return diff --git a/services/package.go b/services/package.go index 25a9141f..b50a7db0 100644 --- a/services/package.go +++ b/services/package.go @@ -15,12 +15,12 @@ var ( ) type PackageService struct { - packageRepo types.PackageRepository + packageAdapter types.PackageAdapterPort } -func NewPackageService(packageRepo types.PackageRepository) PackageService { +func NewPackageService(packageAdapter types.PackageAdapterPort) PackageService { return PackageService{ - packageRepo: packageRepo, + packageAdapter: packageAdapter, } } @@ -82,7 +82,7 @@ func (s *PackageService) InstallationCommand(p *types.Package, pm string) (Insta } func (s *PackageService) GetByID(id string) (types.Package, error) { - pkg, err := s.packageRepo.GetByID(id) + pkg, err := s.packageAdapter.GetByID(id) if err != nil { return types.Package{}, err } @@ -93,7 +93,7 @@ func (s *PackageService) GetByID(id string) (types.Package, error) { } func (s *PackageService) checkIsInstalled(id string, pkg types.Package) (bool, error) { - pkgPath := s.packageRepo.GetPath(id) + pkgPath := s.packageAdapter.GetPath(id) isScript := strings.HasPrefix(pkg.Check, "script:") if isScript { @@ -122,5 +122,5 @@ func (s *PackageService) checkIsInstalledWithCommand(cmd string) (bool, error) { } func (s *PackageService) Reload() error { - return s.packageRepo.Reload() + return s.packageAdapter.Reload() } diff --git a/services/package_test.go b/services/package_test.go index 832abd82..00a1b1d2 100644 --- a/services/package_test.go +++ b/services/package_test.go @@ -13,7 +13,7 @@ type PackageTestSuite struct { suite.Suite service PackageService - repo MockPackageRepository + adapter MockPackageAdapter } func TestEventInMemoryRepositoryTestSuite(t *testing.T) { @@ -21,8 +21,8 @@ func TestEventInMemoryRepositoryTestSuite(t *testing.T) { } func (suite *PackageTestSuite) SetupSuite() { - suite.repo = MockPackageRepository{} - suite.service = NewPackageService(&suite.repo) + suite.adapter = MockPackageAdapter{} + suite.service = NewPackageService(&suite.adapter) } func (suite *PackageTestSuite) TestInstallationCommand() { @@ -57,21 +57,21 @@ func (suite *PackageTestSuite) TestInstallationCommand() { } } -type MockPackageRepository struct { +type MockPackageAdapter struct { mock.Mock } -func (m *MockPackageRepository) GetByID(id string) (types.Package, error) { +func (m *MockPackageAdapter) GetByID(id string) (types.Package, error) { m.Called(id) return types.Package{}, nil } -func (m *MockPackageRepository) GetPath(id string) string { +func (m *MockPackageAdapter) GetPath(id string) string { m.Called(id) return "" } -func (m *MockPackageRepository) Reload() error { +func (m *MockPackageAdapter) Reload() error { m.Called() return nil } diff --git a/services/proxy.go b/services/proxy.go index c6b843bc..aca8b530 100644 --- a/services/proxy.go +++ b/services/proxy.go @@ -22,13 +22,13 @@ var ( ) type ProxyService struct { - server *http.Server - proxyRepo types.ProxyRepository + server *http.Server + proxyAdapter types.ProxyAdapterPort } -func NewProxyService(proxyRepo types.ProxyRepository) ProxyService { +func NewProxyService(proxyAdapter types.ProxyAdapterPort) ProxyService { s := ProxyService{ - proxyRepo: proxyRepo, + proxyAdapter: proxyAdapter, } return s } @@ -72,23 +72,23 @@ func (s *ProxyService) Stop() error { } func (s *ProxyService) GetRedirects() types.ProxyRedirects { - return s.proxyRepo.GetRedirects() + return s.proxyAdapter.GetRedirects() } func (s *ProxyService) AddRedirect(redirect types.ProxyRedirect) error { id := uuid.New() - return s.proxyRepo.AddRedirect(id, redirect) + return s.proxyAdapter.AddRedirect(id, redirect) } func (s *ProxyService) RemoveRedirect(id uuid.UUID) error { - return s.proxyRepo.RemoveRedirect(id) + return s.proxyAdapter.RemoveRedirect(id) } func (s *ProxyService) handleProxy(c *gin.Context) { host := c.Request.Host var redirect *types.ProxyRedirect - for _, r := range s.proxyRepo.GetRedirects() { + for _, r := range s.proxyAdapter.GetRedirects() { if host == r.Source { redirect = &r break diff --git a/services/service.go b/services/service.go index 14c93ea8..d4cd22d1 100644 --- a/services/service.go +++ b/services/service.go @@ -5,19 +5,19 @@ import ( ) type ServiceService struct { - serviceRepo types.ServiceRepository + serviceAdapter types.ServiceAdapterPort } -func NewServiceService(serviceRepo types.ServiceRepository) ServiceService { +func NewServiceService(serviceAdapter types.ServiceAdapterPort) ServiceService { return ServiceService{ - serviceRepo: serviceRepo, + serviceAdapter: serviceAdapter, } } func (s *ServiceService) ListAvailable() []types.Service { - return s.serviceRepo.GetAll() + return s.serviceAdapter.GetAll() } func (s *ServiceService) Reload() error { - return s.serviceRepo.Reload() + return s.serviceAdapter.Reload() } diff --git a/services/settings.go b/services/settings.go index bcc3d5f2..c4b7084e 100644 --- a/services/settings.go +++ b/services/settings.go @@ -5,12 +5,12 @@ import ( ) type SettingsService struct { - settingsRepo types.SettingsRepository + settingsAdapter types.SettingsAdapterPort } -func NewSettingsService(settingsRepo types.SettingsRepository) SettingsService { +func NewSettingsService(settingsAdapter types.SettingsAdapterPort) SettingsService { return SettingsService{ - settingsRepo: settingsRepo, + settingsAdapter: settingsAdapter, } } @@ -18,7 +18,7 @@ func (s *SettingsService) Update(settings types.Settings) error { if settings.Notifications != nil { notifs := settings.Notifications if notifs.Webhook != nil { - err := s.settingsRepo.SetNotificationsWebhook(notifs.Webhook) + err := s.settingsAdapter.SetNotificationsWebhook(notifs.Webhook) if err != nil { return err } @@ -29,9 +29,9 @@ func (s *SettingsService) Update(settings types.Settings) error { } func (s *SettingsService) GetNotificationsWebhook() *string { - return s.settingsRepo.GetNotificationsWebhook() + return s.settingsAdapter.GetNotificationsWebhook() } func (s *SettingsService) SetNotificationsWebhook(webhook *string) error { - return s.settingsRepo.SetNotificationsWebhook(webhook) + return s.settingsAdapter.SetNotificationsWebhook(webhook) } diff --git a/types/event.go b/types/event.go index 65870a42..aa0c3eb3 100644 --- a/types/event.go +++ b/types/event.go @@ -17,7 +17,7 @@ type Listener interface { GetUUID() uuid.UUID } -type EventRepository interface { +type EventAdapterPort interface { AddListener(l Listener) RemoveListener(l Listener) Send(e interface{}) diff --git a/types/instance.go b/types/instance.go index 7834a281..50519a5a 100644 --- a/types/instance.go +++ b/types/instance.go @@ -59,7 +59,7 @@ func NewInstance(id uuid.UUID, service Service) Instance { } } -type InstanceRepository interface { +type InstanceAdapterPort interface { Get(uuid uuid.UUID) (*Instance, error) GetAll() map[uuid.UUID]*Instance GetPath(uuid uuid.UUID) string diff --git a/types/logs.go b/types/logs.go index 546f84f2..cee1582b 100644 --- a/types/logs.go +++ b/types/logs.go @@ -15,7 +15,7 @@ type LogLine struct { Message string `json:"message"` } -type InstanceLogsRepository interface { +type InstanceLogsAdapterPort interface { Open(uuid uuid.UUID) error Close(uuid uuid.UUID) error Push(uuid uuid.UUID, line LogLine) diff --git a/types/package.go b/types/package.go index e2a7a8c8..45853ac9 100644 --- a/types/package.go +++ b/types/package.go @@ -19,10 +19,10 @@ type Package struct { Installed *bool `json:"installed,omitempty"` } -type PackageRepository interface { +type PackageAdapterPort interface { GetByID(id string) (Package, error) GetPath(id string) string - // Reload the repository + // Reload the adapter Reload() error } diff --git a/types/proxy.go b/types/proxy.go index 651621fd..bd029573 100644 --- a/types/proxy.go +++ b/types/proxy.go @@ -9,7 +9,7 @@ type ProxyRedirect struct { Target string `json:"target"` } -type ProxyRepository interface { +type ProxyAdapterPort interface { GetRedirects() ProxyRedirects AddRedirect(id uuid.UUID, redirect ProxyRedirect) error RemoveRedirect(id uuid.UUID) error diff --git a/types/runner.go b/types/runner.go index 373f4f2c..d628619c 100644 --- a/types/runner.go +++ b/types/runner.go @@ -1,6 +1,6 @@ package types -type RunnerRepository interface { +type RunnerAdapterPort interface { Delete(instance *Instance) error Start(instance *Instance, onLog func(msg string), onErr func(msg string), setStatus func(status string)) error Stop(instance *Instance) error diff --git a/types/service.go b/types/service.go index c95e4de6..0d5cf8cb 100644 --- a/types/service.go +++ b/types/service.go @@ -160,7 +160,7 @@ var ( ErrServiceNotFound = errors.New("the service was not found") ) -type ServiceRepository interface { +type ServiceAdapterPort interface { // Get a service with its id. Returns ErrServiceNotFound if // the service was not found. Get(id string) (Service, error) @@ -170,6 +170,6 @@ type ServiceRepository interface { // GetAll gets all available services. GetAll() []Service - // Reload the repository + // Reload the adapter Reload() error } diff --git a/types/settings.go b/types/settings.go index 3599503d..d17d4d57 100644 --- a/types/settings.go +++ b/types/settings.go @@ -8,7 +8,7 @@ type Settings struct { Notifications *SettingsNotifications `json:"notifications,omitempty"` } -type SettingsRepository interface { +type SettingsAdapterPort interface { GetSettings() Settings GetNotificationsWebhook() *string