From 236a93351b194194090b6f31f0abe5b79da2b9a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Quentin=20Guid=C3=A9e?= Date: Thu, 7 Sep 2023 10:52:34 -0400 Subject: [PATCH] PackageFSRepository: Add Mutex for pkgs map access MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Quentin Guidée --- repository/package_fs.go | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/repository/package_fs.go b/repository/package_fs.go index 8ad934dc..cb8b29af 100644 --- a/repository/package_fs.go +++ b/repository/package_fs.go @@ -5,6 +5,7 @@ import ( "fmt" "os" "path" + "sync" errors2 "github.com/pkg/errors" "github.com/vertex-center/vertex/pkg/logger" @@ -17,7 +18,9 @@ var ( ) type PackageFSRepository struct { - pkgs map[string]types.Package + pkgs map[string]types.Package + pkgsMutex *sync.RWMutex + dependenciesPath string } @@ -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() @@ -45,6 +51,9 @@ 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 @@ -52,6 +61,13 @@ func (r *PackageFSRepository) Get(id string) (types.Package, error) { 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) } @@ -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)