Skip to content

Commit

Permalink
PackageFSRepository: Add Mutex for pkgs map access
Browse files Browse the repository at this point in the history
Signed-off-by: Quentin Guidée <[email protected]>
  • Loading branch information
quentinguidee committed Sep 7, 2023
1 parent 5d0ff76 commit 236a933
Showing 1 changed file with 21 additions and 5 deletions.
26 changes: 21 additions & 5 deletions repository/package_fs.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"os"
"path"
"sync"

errors2 "github.com/pkg/errors"
"github.com/vertex-center/vertex/pkg/logger"
Expand All @@ -17,7 +18,9 @@ var (
)

type PackageFSRepository struct {
pkgs map[string]types.Package
pkgs map[string]types.Package
pkgsMutex *sync.RWMutex

dependenciesPath string
}

Expand All @@ -34,9 +37,12 @@ func NewPackageFSRepository(params *PackageRepositoryParams) PackageFSRepository
}

repo := PackageFSRepository{
pkgs: map[string]types.Package{},
pkgsMutex: &sync.RWMutex{},

dependenciesPath: params.dependenciesPath,
pkgs: map[string]types.Package{},
}

err := repo.Reload()
if err != nil {
logger.Error(fmt.Errorf("failed to reload services repository: %v", err)).Print()
Expand All @@ -45,13 +51,23 @@ func NewPackageFSRepository(params *PackageRepositoryParams) PackageFSRepository
}

func (r *PackageFSRepository) Get(id string) (types.Package, error) {
r.pkgsMutex.RLock()
defer r.pkgsMutex.RUnlock()

pkg, ok := r.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()

r.pkgs[id] = pkg
}

func (r *PackageFSRepository) GetPath(id string) string {
return path.Join(r.dependenciesPath, "packages", id)
}
Expand All @@ -69,18 +85,18 @@ func (r *PackageFSRepository) Reload() error {

name := entry.Name()

pkg, err := r.readPkgFromDisk(name)
pkg, err := r.readFromDisk(name)
if err != nil {
return err
}

r.pkgs[name] = *pkg
r.set(name, *pkg)
}

return nil
}

func (r *PackageFSRepository) readPkgFromDisk(id string) (*types.Package, error) {
func (r *PackageFSRepository) readFromDisk(id string) (*types.Package, error) {
p := path.Join(r.GetPath(id), fmt.Sprintf("%s.json", id))

file, err := os.ReadFile(p)
Expand Down

0 comments on commit 236a933

Please sign in to comment.