From b73ec71bdc020febb6f2be88322c72bb1f1fb656 Mon Sep 17 00:00:00 2001 From: Yingjie Date: Thu, 12 Nov 2026 17:55:09 +0800 Subject: [PATCH] feat: add an opt-in library store and fetch libraries concurrently --- README.md | 22 + fetch_with_dependencies_test.go | 267 +++++++++++ initialize.go | 278 +++++++++-- internal/environment/environment.go | 16 +- internal/environment/environment_test.go | 32 ++ library_store.go | 355 ++++++++++++++ library_store_test.go | 587 +++++++++++++++++++++++ metadata.go | 38 +- metadata_test.go | 4 +- 9 files changed, 1541 insertions(+), 58 deletions(-) create mode 100644 fetch_with_dependencies_test.go create mode 100644 internal/environment/environment_test.go create mode 100644 library_store.go create mode 100644 library_store_test.go diff --git a/README.md b/README.md index 2f62e11..3db7189 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,28 @@ The module uses the following environment variables: - `ALZLIB_DIR`: The local temporary directory where the libraries will be cloned. Default is `.alzlib` - `ALZLIB_LIBRARY_GIT_URL`: The URL of the Azure Landing Zones Library repository. Default is `github.com/Azure/Azure-Landing-Zones-Library` +- `ALZLIB_LIBRARY_STORE_ENABLED`: Set to `true` to enable the [library store](#library-store). Default is `false` + +`LibraryReferences.FetchWithDependencies()` fetches up to four libraries at the same time. +The libraries are always returned in the same order: each library is listed once, after its dependencies. + +### Library store + +By default, a library is fetched again each time it is used. +When the library store is enabled, with the `ALZLIB_LIBRARY_STORE_ENABLED` environment variable or with `alzlib.LibraryStoreEnabled.Store(true)`, the libraries that cannot change are fetched once into `/store`, and then reused, also by other processes that use the same `ALZLIB_DIR`: + +- ALZ Library members, which are fetched at release tags. Release tags are assumed never to move. +- Libraries with a go-getter git URL whose `ref` is a full, 40-character, commit SHA, for example `git::https://github.com/contoso/alz-library//platform?ref=`. + +Other libraries, such as local directories, or git branches and tags, are fetched as when the store is disabled. + +Each library is kept in `/store/`, with the library in `lib` and a `fetch.json` file that describes it. +`fetch.json` records the URL without credentials, such as the user information of the URL or an `sshkey` parameter, and identifies the complete URL by its SHA-256 hash. +A library is fetched into a temporary directory of the store, which is then renamed, so that processes never use a library that is only partly fetched. +A fetch that is interrupted can leave such a `tmp-*` directory behind: it is never used and can be deleted. +A store directory that is incomplete or has been changed is neither used nor changed: delete it to fetch the library into the store again. +Nothing is removed from the store: delete `/store` to clear it. +In CI/CD pipelines, you can cache `ALZLIB_DIR` with a key based on your library references. ## Contributing diff --git a/fetch_with_dependencies_test.go b/fetch_with_dependencies_test.go new file mode 100644 index 0000000..3360bf5 --- /dev/null +++ b/fetch_with_dependencies_test.go @@ -0,0 +1,267 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package alzlib + +import ( + "context" + "encoding/json" + "fmt" + "math/rand/v2" + "os" + "path/filepath" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/Azure/alzlib/internal/processor" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const ( + testRandomGraphs = 40 + testRandomGraphMaxSize = 8 + testIndependentLibraries = 10 + testConcurrencyWaitPeriod = 5 * time.Second + testDownloadDuration = 20 * time.Millisecond + testErrorRepetitions = 5 +) + +// sequentialFetchLibraryWithDependencies is the implementation of FetchWithDependencies from before +// libraries were fetched concurrently. The tests check that the libraries are returned in the same +// order. +func sequentialFetchLibraryWithDependencies( + ctx context.Context, + processed map[string]bool, + lib LibraryReference, + result *LibraryReferences, +) error { + if processed[lib.String()] { + return nil + } + + f, err := lib.Fetch(ctx, hash(lib)) + if err != nil { + return err + } + + libmeta, err := processor.NewClient(f).Metadata() + if err != nil { + return err + } + + for _, dep := range NewMetadata(libmeta, lib).Dependencies() { + if err := sequentialFetchLibraryWithDependencies(ctx, processed, dep, result); err != nil { + return err + } + } + + *result = append(*result, lib) + processed[lib.String()] = true + + return nil +} + +// writeTestLibrary writes a library to dir, with dependencies on the libraries in the directories deps. +func writeTestLibrary(t *testing.T, dir string, deps ...string) { + t.Helper() + + dependencies := make([]processor.LibMetadataDependency, len(deps)) + for i, dep := range deps { + dependencies[i] = processor.LibMetadataDependency{CustomURL: filepath.ToSlash(dep)} + } + + data, err := json.Marshal(processor.LibMetadata{ + Name: filepath.Base(dir), + DisplayName: filepath.Base(dir), + Description: "test library", + Dependencies: dependencies, + }) + require.NoError(t, err) + require.NoError(t, os.MkdirAll(dir, libraryStoreDirPerm)) + require.NoError(t, os.WriteFile(filepath.Join(dir, testLibraryMetadataFile), data, libraryStoreFilePerm)) +} + +// libraryNames returns the String() of the libraries. +func libraryNames(libs LibraryReferences) []string { + names := make([]string, len(libs)) + for i, lib := range libs { + names[i] = lib.String() + } + + return names +} + +// TestFetchWithDependenciesOrder checks that libraries are returned in the same order as by the +// sequential implementation, for random dependency graphs with shared and diamond dependencies. +func TestFetchWithDependenciesOrder(t *testing.T) { + t.Setenv("ALZLIB_DIR", t.TempDir()) + + ctx := context.Background() + + for seed := range uint64(testRandomGraphs) { + t.Run(fmt.Sprintf("seed %d", seed), func(t *testing.T) { + rnd := rand.New(rand.NewPCG(seed, seed)) + libDir := t.TempDir() + size := 1 + rnd.IntN(testRandomGraphMaxSize) + + dirs := make([]string, size) + for i := range dirs { + dirs[i] = filepath.Join(libDir, fmt.Sprintf("lib%d", i)) + } + + // A library only depends on libraries with a lower index, so that there is no cycle. + for i, dir := range dirs { + var deps []string + + for _, j := range rnd.Perm(i) { + if rnd.IntN(2) == 0 { + deps = append(deps, dirs[j]) + } + } + + writeTestLibrary(t, dir, deps...) + } + + top := rnd.Perm(size)[:1+rnd.IntN(size)] + newRefs := func() LibraryReferences { + refs := make(LibraryReferences, len(top)) + for i, j := range top { + refs[i] = NewCustomLibraryReference(filepath.ToSlash(dirs[j])) + } + + return refs + } + + var want LibraryReferences + + processed := make(map[string]bool) + for _, lib := range newRefs() { + require.NoError(t, sequentialFetchLibraryWithDependencies(ctx, processed, lib, &want)) + } + + got, err := newRefs().FetchWithDependencies(ctx) + require.NoError(t, err) + assert.Equal(t, libraryNames(want), libraryNames(got)) + + for _, lib := range got { + assert.NotNil(t, lib.FS(), lib.String()) + } + }) + } +} + +// TestFetchWithDependenciesConcurrency checks that independent libraries are fetched concurrently, at +// most maxConcurrentLibraryFetches at a time. +func TestFetchWithDependenciesConcurrency(t *testing.T) { + t.Setenv("ALZLIB_DIR", t.TempDir()) + + libDir := t.TempDir() + refs := make(LibraryReferences, testIndependentLibraries) + + for i := range refs { + dir := filepath.Join(libDir, fmt.Sprintf("lib%d", i)) + writeTestLibrary(t, dir) + refs[i] = NewCustomLibraryReference(filepath.ToSlash(dir)) + } + + var ( + inFlight, maxInFlight atomic.Int32 + concurrent = make(chan struct{}) + closeConcurrent sync.Once + ) + + download := downloadLibrary + downloadLibrary = func(ctx context.Context, getterString, dst string) error { + n := inFlight.Add(1) + defer inFlight.Add(-1) + + for current := maxInFlight.Load(); n > current && !maxInFlight.CompareAndSwap(current, n); { + current = maxInFlight.Load() + } + + // Wait until two downloads overlap, which never happens if the libraries are fetched one by one. + if n > 1 { + closeConcurrent.Do(func() { close(concurrent) }) + } + + select { + case <-concurrent: + case <-time.After(testConcurrencyWaitPeriod): + } + + time.Sleep(testDownloadDuration) + + return download(ctx, getterString, dst) + } + + t.Cleanup(func() { downloadLibrary = download }) + + got, err := refs.FetchWithDependencies(context.Background()) + require.NoError(t, err) + assert.Equal(t, libraryNames(refs), libraryNames(got)) + assert.Greater(t, maxInFlight.Load(), int32(1)) + assert.LessOrEqual(t, maxInFlight.Load(), int32(maxConcurrentLibraryFetches)) +} + +// TestFetchWithDependenciesReusesPrefetchedLibrary checks that a library is fetched once when it is +// referenced more than once, and that the first reference in the depth-first walk is returned, as by +// the sequential implementation. +func TestFetchWithDependenciesReusesPrefetchedLibrary(t *testing.T) { + t.Setenv("ALZLIB_DIR", t.TempDir()) + + libDir := t.TempDir() + shared := filepath.Join(libDir, "shared") + dependent := filepath.Join(libDir, "dependent") + + writeTestLibrary(t, shared) + writeTestLibrary(t, dependent, shared) + + downloads := observeDownloads(t, nil) + sharedRef := NewCustomLibraryReference(filepath.ToSlash(shared)) + refs := LibraryReferences{NewCustomLibraryReference(filepath.ToSlash(dependent)), sharedRef} + + got, err := refs.FetchWithDependencies(context.Background()) + require.NoError(t, err) + assert.Equal(t, []string{filepath.ToSlash(shared), filepath.ToSlash(dependent)}, libraryNames(got)) + assert.Equal(t, int32(2), downloads.Load()) + + // The shared library is returned as the dependency of the dependent library, not as sharedRef. + assert.NotSame(t, sharedRef, got[0]) + assert.NotNil(t, got[0].FS()) +} + +// TestFetchWithDependenciesCircularDependency checks that a circular dependency is an error. +func TestFetchWithDependenciesCircularDependency(t *testing.T) { + t.Setenv("ALZLIB_DIR", t.TempDir()) + + libDir := t.TempDir() + libA := filepath.Join(libDir, "libA") + libB := filepath.Join(libDir, "libB") + + writeTestLibrary(t, libA, libB) + writeTestLibrary(t, libB, libA) + + _, err := NewCustomLibraryReference(filepath.ToSlash(libA)).FetchWithDependencies(context.Background()) + require.ErrorContains(t, err, "circular dependency on library "+filepath.ToSlash(libA)) +} + +// TestFetchWithDependenciesFirstError checks that the error of the first library that fails, in the +// depth-first walk, is returned, whichever fetch fails first. +func TestFetchWithDependenciesFirstError(t *testing.T) { + t.Setenv("ALZLIB_DIR", t.TempDir()) + + libDir := t.TempDir() + missing1 := filepath.ToSlash(filepath.Join(libDir, "missing1")) + missing2 := filepath.ToSlash(filepath.Join(libDir, "missing2")) + + for range testErrorRepetitions { + refs := LibraryReferences{NewCustomLibraryReference(missing1), NewCustomLibraryReference(missing2)} + libs, err := refs.FetchWithDependencies(context.Background()) + require.ErrorContains(t, err, "error fetching library "+missing1+":") + assert.NotContains(t, err.Error(), missing2) + assert.Nil(t, libs) + } +} diff --git a/initialize.go b/initialize.go index 207555c..7cafa84 100644 --- a/initialize.go +++ b/initialize.go @@ -6,12 +6,14 @@ package alzlib import ( "context" "crypto/sha256" + "errors" "fmt" "io/fs" "net/url" "os" "path/filepath" "strconv" + "sync" "sync/atomic" "github.com/Azure/alzlib/internal/environment" @@ -23,27 +25,78 @@ import ( // When set by the caller, it prevents collisions in the .alzlib directory. var Instance atomic.Uint32 -// fetchLibraryWithDependencies takes a library reference, fetches it, and then fetches all of its -// dependencies. The destination directory is an integer that will be appended to the `.alzlib` -// directory in the current working -// directory. -// This can be override by setting the `ALZLIB_DIR` environment variable. -// The `LibraryReferences` slice can be used to initialize the AlzLib instance. -func fetchLibraryWithDependencies( +// maxConcurrentLibraryFetches is the maximum number of libraries that FetchWithDependencies fetches at +// the same time. +const maxConcurrentLibraryFetches = 4 + +// prefetchableLibraryReference is implemented by the library references of this package. Their Fetch +// method keeps the filesystem that it fetched, so a prefetched reference is not fetched again, and they +// can take the filesystem that was fetched for another reference to the same library. +type prefetchableLibraryReference interface { + LibraryReference + setFS(filesystem fs.FS) +} + +// fetchLibrariesWithDependencies fetches libs and all of their dependencies. The result lists each +// library (by String()) once, after its dependencies, in the order of a depth-first walk of libs and +// their dependencies. This order decides which library overwrites another one when overwriting is +// allowed, so it must not depend on the order in which concurrent fetches complete: +// +// 1. prefetchLibraries fetches the libraries and their dependencies concurrently. +// 2. libraryWalk walks the libraries as they were walked before they were prefetched. It uses the +// prefetched filesystems, and fetches anything that was not prefetched, so it returns the same +// libraries and errors as before. +// +// The destination directory of each library is the hash of the library reference, appended to the +// `/` directory, unless the library is in the library store. +// On error, the libraries added so far are returned with the error. +func fetchLibrariesWithDependencies( ctx context.Context, - processed map[string]bool, - lib LibraryReference, - result *LibraryReferences, -) error { - if processed[lib.String()] { + libs ...LibraryReference, +) (LibraryReferences, error) { + walk := libraryWalk{ + prefetched: prefetchLibraries(ctx, libs), + processed: make(map[string]bool), + inProgress: make(map[string]bool), + result: make(LibraryReferences, 0, InitialLibraryReferencesCapacity), + } + + for _, lib := range libs { + if err := walk.visit(ctx, lib); err != nil { + return walk.result, err + } + } + + return walk.result, nil +} + +// libraryWalk is the depth-first walk of fetchLibrariesWithDependencies. +type libraryWalk struct { + prefetched map[string]fs.FS // filesystems fetched by prefetchLibraries, by library + processed map[string]bool // libraries added to result + inProgress map[string]bool // libraries whose dependencies are being walked + result LibraryReferences +} + +// visit fetches lib and its dependencies, and adds them to the result after their dependencies. +func (w *libraryWalk) visit(ctx context.Context, lib LibraryReference) error { + key := lib.String() + if w.processed[key] { return nil } - f, err := lib.Fetch(ctx, hash(lib)) + if w.inProgress[key] { + return fmt.Errorf("FetchLibraryWithDependencies: circular dependency on library %s", key) + } + + w.inProgress[key] = true + defer delete(w.inProgress, key) + + f, err := w.fetch(ctx, lib) if err != nil { return fmt.Errorf( "FetchLibraryWithDependencies: error fetching library %s: %w", - lib.String(), + key, err, ) } @@ -54,7 +107,7 @@ func fetchLibraryWithDependencies( if err != nil { return fmt.Errorf( "FetchLibraryWithDependencies: error getting metadata for library %s: %w", - lib.String(), + key, err, ) } @@ -62,22 +115,130 @@ func fetchLibraryWithDependencies( meta := NewMetadata(libmeta, lib) // for each dependency, recurse using this function for _, dep := range meta.Dependencies() { - err = fetchLibraryWithDependencies(ctx, processed, dep, result) - if err != nil { + if err := w.visit(ctx, dep); err != nil { return fmt.Errorf( "FetchLibraryWithDependencies: error fetching dependencies for library %s: %w", - lib.String(), + key, err, ) } } // add the current library reference to the list - *result = append(*result, lib) - processed[lib.String()] = true + w.result = append(w.result, lib) + w.processed[key] = true return nil } +// fetch returns the filesystem of lib. A reference without a filesystem takes the filesystem that was +// prefetched for the same library: its own fetch would have used the same destination directory. +func (w *libraryWalk) fetch(ctx context.Context, lib LibraryReference) (fs.FS, error) { + if p, ok := lib.(prefetchableLibraryReference); ok && p.FS() == nil { + if f, ok := w.prefetched[p.String()]; ok { + p.setFS(f) + } + } + + return lib.Fetch(ctx, hash(lib)) +} + +// prefetchLibraries fetches libs and their dependencies, at most maxConcurrentLibraryFetches at a time, +// and returns the filesystems that it fetched, by library (String()). Each library is prefetched once, +// with the first reference to it that is found. Only the library references of this package are +// prefetched: the Fetch method of other implementations might fetch again when the walk calls it. +// Errors are ignored: the walk fetches a library that was not prefetched, and reports its error. +func prefetchLibraries(ctx context.Context, libs LibraryReferences) map[string]fs.FS { + var ( + mu sync.Mutex + wg sync.WaitGroup + seen = make(map[string]bool) + prefetched = make(map[string]fs.FS) + slots = make(chan struct{}, maxConcurrentLibraryFetches) + ) + + var prefetch func(lib LibraryReference) + + prefetch = func(lib LibraryReference) { + p, ok := lib.(prefetchableLibraryReference) + if !ok { + return + } + + key := p.String() + + mu.Lock() + + if seen[key] { + mu.Unlock() + return + } + + seen[key] = true + + mu.Unlock() + + wg.Go(func() { + f, fetched := prefetchLibrary(ctx, p, slots) + if f == nil { + return + } + + if fetched { + mu.Lock() + prefetched[key] = f + mu.Unlock() + } + + libmeta, err := processor.NewClient(f).Metadata() + if err != nil { + return + } + + for _, dep := range NewMetadata(libmeta, p).Dependencies() { + prefetch(dep) + } + }) + } + + for _, lib := range libs { + prefetch(lib) + } + + wg.Wait() + + return prefetched +} + +// prefetchLibrary returns the filesystem of lib, and whether it fetched lib to get it. A reference that +// already has a filesystem, for example one created with NewCustomLibraryReferenceFromFS, is not +// fetched, and its filesystem is not used for other references to the same library, as these fetch +// the library themselves. It returns a nil filesystem if lib could not be fetched. slots limits the +// number of concurrent fetches. +func prefetchLibrary( + ctx context.Context, + lib prefetchableLibraryReference, + slots chan struct{}, +) (fs.FS, bool) { + if f := lib.FS(); f != nil { + return f, false + } + + select { + case slots <- struct{}{}: + case <-ctx.Done(): + return nil, false + } + + defer func() { <-slots }() + + f, err := lib.Fetch(ctx, hash(lib)) + if err != nil { + return nil, false + } + + return f, true +} + // hash returns the SHA224 hash of a fmt.Stringer, as a string. func hash(s fmt.Stringer) string { return hashStr(s.String()) @@ -95,20 +256,24 @@ func hashStr(s string) string { // The destination directory will be appended to the `.alzlib` directory in the current working // directory. // This can be override by setting the `ALZLIB_DIR` environment variable. +// If the library store is enabled (see LibraryStoreEnabled), the member is fetched into the store, or +// reused from it, instead: ALZ Library members are fetched at release tags, which are assumed not to +// move. // To fetch the ALZ reference, supply "platform/alz" as the member, with the tag (e.g. 2024.03.03). func FetchAzureLandingZonesLibraryMember( ctx context.Context, path, ref, dstDir string, ) (fs.FS, error) { - ref = fmt.Sprintf("%s/%s", path, ref) - q := url.Values{} - q.Add("ref", ref) - - gitURL := environment.AlzLibraryGitURL() + return fetchLibrary(ctx, alzLibraryMemberGetterString(path, ref), dstDir, true) +} - u := fmt.Sprintf("git::%s//%s?%s", gitURL, path, q.Encode()) +// alzLibraryMemberGetterString returns the go-getter URL of the ALZ Library member at path, at the +// release tag ref. +func alzLibraryMemberGetterString(path, ref string) string { + q := url.Values{} + q.Add("ref", fmt.Sprintf("%s/%s", path, ref)) - return FetchLibraryByGetterString(ctx, u, dstDir) + return fmt.Sprintf("git::%s//%s?%s", environment.AlzLibraryGitURL(), path, q.Encode()) } // FetchLibraryByGetterString fetches a library from a URL using the go-getter library. @@ -116,19 +281,35 @@ func FetchAzureLandingZonesLibraryMember( // to // the `.alzlib` directory in the current working directory. // This can be override by setting the `ALZLIB_DIR` environment variable. +// If the library store is enabled (see LibraryStoreEnabled) and the URL is a git URL whose `ref` is a +// full commit SHA, the library is fetched into the store, or reused from it, instead. // It returns an fs.FS interface to the fetched library to be used in the AlzLib.Init() method. func FetchLibraryByGetterString(ctx context.Context, getterString, dstDir string) (fs.FS, error) { + return fetchLibrary(ctx, getterString, dstDir, isPinnedGitSource(getterString)) +} + +// fetchLibrary fetches the library at getterString. If immutable is true, the library cannot change, +// and it is fetched into the library store, or reused from it, when the store is enabled. Otherwise +// it is fetched to `//`, replacing what is there. +func fetchLibrary(ctx context.Context, getterString, dstDir string, immutable bool) (fs.FS, error) { + if immutable && libraryStoreEnabled() { + f, err := fetchLibraryIntoStore(ctx, getterString) + if !errors.Is(err, errLibraryStoreEntryInvalid) { + return f, err + } + // The store entry exists but is not complete for getterString. It is left as it is, as another + // process might be using it, and the library is fetched as if the store was disabled. + } + + return fetchLibraryToInstanceDir(ctx, getterString, dstDir) +} + +// fetchLibraryToInstanceDir fetches the library at getterString to `//`, +// replacing what is there. +func fetchLibraryToInstanceDir(ctx context.Context, getterString, dstDir string) (fs.FS, error) { baseDir := environment.AlzLibDir() instance := strconv.Itoa(int(Instance.Load())) dst := filepath.Join(baseDir, instance, dstDir) - client := getter.Client{ - DisableSymlinks: true, - } - - wd, err := os.Getwd() - if err != nil { - return nil, fmt.Errorf("FetchLibraryByGetterString: error getting working directory: %w", err) - } if err := os.RemoveAll(dst); err != nil { return nil, fmt.Errorf( @@ -138,15 +319,34 @@ func FetchLibraryByGetterString(ctx context.Context, getterString, dstDir string ) } + if err := downloadLibrary(ctx, getterString, dst); err != nil { + return nil, err + } + + return os.DirFS(dst), nil +} + +// downloadLibrary downloads the library at getterString to the directory dst, using go-getter. +// Relative paths are relative to the working directory. +// It is a variable so that tests can observe downloads. +var downloadLibrary = func(ctx context.Context, getterString, dst string) error { + client := getter.Client{ + DisableSymlinks: true, + } + + wd, err := os.Getwd() + if err != nil { + return fmt.Errorf("FetchLibraryByGetterString: error getting working directory: %w", err) + } + req := &getter.Request{ Src: getterString, Dst: dst, Pwd: wd, } - _, err = client.Get(ctx, req) - if err != nil { - return nil, fmt.Errorf( + if _, err := client.Get(ctx, req); err != nil { + return fmt.Errorf( "FetchLibraryByGetterString: error fetching library. source `%s`, destination `%s`, wd `%s`: %w", getterString, dst, @@ -155,5 +355,5 @@ func FetchLibraryByGetterString(ctx context.Context, getterString, dstDir string ) } - return os.DirFS(dst), nil + return nil } diff --git a/internal/environment/environment.go b/internal/environment/environment.go index 2904b4a..cbbce2a 100644 --- a/internal/environment/environment.go +++ b/internal/environment/environment.go @@ -3,7 +3,10 @@ package environment -import "os" +import ( + "os" + "strconv" +) const ( // fetchDefaultBaseDir is the default base directory for fetching libraries. @@ -14,6 +17,8 @@ const ( alzLibraryGitURL = "github.com/Azure/Azure-Landing-Zones-Library" // alzLibraryGitURLEnv is the environment variable to override the default git URL. alzLibraryGitURLEnv = "ALZLIB_LIBRARY_GIT_URL" + // libraryStoreEnabledEnv is the environment variable that enables the library store. + libraryStoreEnabledEnv = "ALZLIB_LIBRARY_STORE_ENABLED" ) // AlzLibDir contents of the `ALZLIB_DIR` environment variable, or the default which is `.alzlib`. @@ -37,3 +42,12 @@ func AlzLibraryGitURL() string { return url } + +// LibraryStoreEnabled reports whether the `ALZLIB_LIBRARY_STORE_ENABLED` environment variable is set +// to a true value, as accepted by strconv.ParseBool (for example `true` or `1`). +// It returns false when the variable is not set or is not a boolean. +func LibraryStoreEnabled() bool { + enabled, err := strconv.ParseBool(os.Getenv(libraryStoreEnabledEnv)) + + return err == nil && enabled +} diff --git a/internal/environment/environment_test.go b/internal/environment/environment_test.go new file mode 100644 index 0000000..f187e44 --- /dev/null +++ b/internal/environment/environment_test.go @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package environment + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestLibraryStoreEnabled(t *testing.T) { + cases := []struct { + value string + want bool + }{ + {value: "", want: false}, + {value: "true", want: true}, + {value: "TRUE", want: true}, + {value: "1", want: true}, + {value: "false", want: false}, + {value: "0", want: false}, + {value: "yes", want: false}, + } + + for _, tc := range cases { + t.Run(tc.value, func(t *testing.T) { + t.Setenv(libraryStoreEnabledEnv, tc.value) + assert.Equal(t, tc.want, LibraryStoreEnabled()) + }) + } +} diff --git a/library_store.go b/library_store.go new file mode 100644 index 0000000..bf562ff --- /dev/null +++ b/library_store.go @@ -0,0 +1,355 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package alzlib + +import ( + "context" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "io/fs" + "net/url" + "os" + "path/filepath" + "regexp" + "runtime" + "runtime/debug" + "strings" + "sync" + "sync/atomic" + "time" + + "github.com/Azure/alzlib/internal/environment" + "github.com/hashicorp/go-getter/v2" +) + +// LibraryStoreEnabled enables the library store when it is set to true. Setting the +// `ALZLIB_LIBRARY_STORE_ENABLED` environment variable to true also enables it. The store is disabled +// by default. +// +// The library store keeps the libraries that cannot change in `/store`, so that each one +// is downloaded once and then reused, also by other processes that use the same `ALZLIB_DIR`: +// +// - ALZ Library members, which are fetched at release tags. Release tags are assumed never to move. +// - Libraries fetched from a go-getter git URL whose `ref` is a full, 40-character, commit SHA. +// +// Other libraries, such as local directories, or git branches and tags, are fetched as when the store +// is disabled. Nothing is removed from the store: delete `/store` to clear it. +var LibraryStoreEnabled atomic.Bool + +const ( + libraryStoreDirName = "store" // directory of ALZLIB_DIR that holds the library store + libraryStoreLibDirName = "lib" // directory of a store entry that holds the library + libraryStoreMarkerFileName = "fetch.json" // file of a store entry that describes the entry + libraryStoreTempDirPattern = "tmp-" // pattern of the directories in which entries are prepared + libraryStoreDirPerm = 0o755 + libraryStoreFilePerm = 0o644 + // libraryStoreRenameTimeout is how long a failing rename of a new entry is retried on Windows. + libraryStoreRenameTimeout = 2 * time.Second + // libraryStoreRenameDelay is the first delay between attempts to rename a new entry on Windows. + libraryStoreRenameDelay = 10 * time.Millisecond + // libraryStoreRenameBackoff multiplies the delay between attempts to rename a new entry. + libraryStoreRenameBackoff = 2 + alzlibModulePath = "github.com/Azure/alzlib" + // redactedGetterValue replaces the credentials of a go-getter URL in a store marker. + redactedGetterValue = "REDACTED" +) + +// errLibraryStoreEntryInvalid is returned for a store entry that exists, but does not hold the library +// of the requested URL, as written by this version of the library store. +var errLibraryStoreEntryInvalid = errors.New("library store entry is not valid") + +// commitSHARegex matches a full, 40-character, git commit SHA. +var commitSHARegex = regexp.MustCompile(`^[0-9a-fA-F]{40}$`) + +// libraryStoreLocks holds a lock for each store entry, so that the goroutines of this process fetch a +// library into the store one at a time: the first one fetches it, and the others reuse it. +var libraryStoreLocks sync.Map // map[string]chan struct{} + +// libraryStoreMarker is the content of the marker file of a store entry. An entry is prepared in a +// temporary directory, which is then renamed to the entry, so an entry with a marker file is complete. +// The marker identifies the URL by its hash, and records it without credentials only: the store can be +// shared, for example in a CI/CD cache, and must not hold the credentials that a URL can contain. +type libraryStoreMarker struct { + // Getter is the go-getter URL that the library was fetched from, without credentials. + Getter string `json:"getter"` + // GetterSHA256 is the SHA-256 hash of the complete go-getter URL that the library was fetched from. + GetterSHA256 string `json:"getterSha256"` + // AlzlibVersion is the version of alzlib that fetched the library, if it is known. + AlzlibVersion string `json:"alzlibVersion,omitempty"` + // FetchedAt is when the library was fetched. + FetchedAt time.Time `json:"fetchedAt"` +} + +// newLibraryStoreMarker returns the marker of a store entry for the library fetched from getterString. +func newLibraryStoreMarker(getterString string) libraryStoreMarker { + return libraryStoreMarker{ + Getter: redactGetterString(getterString), + GetterSHA256: sha256Hex(getterString), + AlzlibVersion: alzlibVersion(), + FetchedAt: time.Now().UTC(), + } +} + +// matches reports whether the marker was written for the library fetched from getterString. +func (m libraryStoreMarker) matches(getterString string) bool { + return m.GetterSHA256 == sha256Hex(getterString) +} + +// sha256Hex returns the SHA-256 hash of s, as a hexadecimal string. +func sha256Hex(s string) string { + return fmt.Sprintf("%x", sha256.Sum256([]byte(s))) +} + +// redactGetterString returns getterString without the credentials that a go-getter URL can contain: +// the user information of the URL, such as `user:token@`, and the value of the `sshkey` parameter, +// which is a private SSH key. Each is replaced with redactedGetterValue. +func redactGetterString(getterString string) string { + base, rawQuery, hasQuery := strings.Cut(getterString, "?") + + if i := strings.Index(base, "://"); i >= 0 { + authorityStart := i + len("://") + authority, _, _ := strings.Cut(base[authorityStart:], "/") + + if at := strings.LastIndex(authority, "@"); at >= 0 { + base = base[:authorityStart] + redactedGetterValue + base[authorityStart+at:] + } + } + + if !hasQuery { + return base + } + + query, err := url.ParseQuery(rawQuery) + if err != nil { + return base + "?" + redactedGetterValue + } + + for key := range query { + if strings.EqualFold(key, "sshkey") { + query.Set(key, redactedGetterValue) + } + } + + return base + "?" + query.Encode() +} + +// alzlibVersion returns the version of the alzlib module in this program, if it is known. +var alzlibVersion = sync.OnceValue(func() string { + info, ok := debug.ReadBuildInfo() + if !ok { + return "" + } + + if info.Main.Path == alzlibModulePath { + return info.Main.Version + } + + for _, dep := range info.Deps { + if dep.Path == alzlibModulePath { + return dep.Version + } + } + + return "" +}) + +// libraryStoreEnabled reports whether the library store is enabled, by LibraryStoreEnabled or by the +// `ALZLIB_LIBRARY_STORE_ENABLED` environment variable. +func libraryStoreEnabled() bool { + return LibraryStoreEnabled.Load() || environment.LibraryStoreEnabled() +} + +// isPinnedGitSource reports whether go-getter fetches getterString with git, at a full commit SHA, so +// that the library cannot change. +func isPinnedGitSource(getterString string) bool { + _, rawQuery, ok := strings.Cut(getterString, "?") + if !ok { + return false + } + + query, err := url.ParseQuery(rawQuery) + if err != nil || !commitSHARegex.MatchString(query.Get("ref")) { + return false + } + + // Only git uses the ref parameter: other getters, such as http, pass it on to the server. + for _, g := range getter.Getters { + if _, isGit := g.(*getter.GitGetter); !isGit { + continue + } + + detected, err := getter.Detect(&getter.Request{Src: getterString}, g) + + return err == nil && detected + } + + return false +} + +// fetchLibraryIntoStore returns the library at getterString from its entry in the library store, +// `/store/`, and fetches it first if the entry does not exist. +// The library and the marker file are written to a temporary directory of the store, which is then +// renamed to the entry: other processes see either no entry or a complete one. If another process +// adds the entry first, the library of that entry is returned. +// It returns errLibraryStoreEntryInvalid if the entry exists but is not complete for getterString. +func fetchLibraryIntoStore(ctx context.Context, getterString string) (fs.FS, error) { + storeDir := filepath.Join(environment.AlzLibDir(), libraryStoreDirName) + entryDir := filepath.Join(storeDir, hashStr(getterString)) + libDir := filepath.Join(entryDir, libraryStoreLibDirName) + + unlock, err := lockLibraryStoreEntry(ctx, entryDir) + if err != nil { + return nil, err + } + + defer unlock() + + if libraryStoreEntryComplete(entryDir, getterString) { + return os.DirFS(libDir), nil + } + + if _, err := os.Lstat(entryDir); err == nil { + return nil, fmt.Errorf("%w: %s", errLibraryStoreEntryInvalid, entryDir) + } + + if err := os.MkdirAll(storeDir, libraryStoreDirPerm); err != nil { + return nil, fmt.Errorf( + "FetchLibraryByGetterString: error creating library store directory %s: %w", + storeDir, + err, + ) + } + + tmpDir, err := os.MkdirTemp(storeDir, libraryStoreTempDirPattern) + if err != nil { + return nil, fmt.Errorf( + "FetchLibraryByGetterString: error creating temporary directory in library store %s: %w", + storeDir, + err, + ) + } + + // Once tmpDir has been renamed to entryDir, there is nothing left to remove. + defer func() { _ = os.RemoveAll(tmpDir) }() + + if err := prepareLibraryStoreEntry(ctx, getterString, tmpDir); err != nil { + return nil, err + } + + if err := renameLibraryStoreEntry(ctx, tmpDir, entryDir); err != nil { + if libraryStoreEntryComplete(entryDir, getterString) { + // Another process added the entry first. + return os.DirFS(libDir), nil + } + + return nil, fmt.Errorf( + "FetchLibraryByGetterString: error adding library %s to library store entry %s: %w", + getterString, + entryDir, + err, + ) + } + + return os.DirFS(libDir), nil +} + +// prepareLibraryStoreEntry fetches the library at getterString into the store entry that is prepared +// in dir, and writes the marker file of the entry. +func prepareLibraryStoreEntry(ctx context.Context, getterString, dir string) error { + // os.MkdirTemp creates a directory that only its owner can read. + if err := os.Chmod(dir, libraryStoreDirPerm); err != nil { + return fmt.Errorf("FetchLibraryByGetterString: error setting permissions of %s: %w", dir, err) + } + + if err := downloadLibrary(ctx, getterString, filepath.Join(dir, libraryStoreLibDirName)); err != nil { + return err + } + + marker, err := json.MarshalIndent(newLibraryStoreMarker(getterString), "", " ") + if err != nil { + return fmt.Errorf("FetchLibraryByGetterString: error encoding library store marker: %w", err) + } + + markerFile := filepath.Join(dir, libraryStoreMarkerFileName) + if err := os.WriteFile(markerFile, marker, libraryStoreFilePerm); err != nil { + return fmt.Errorf( + "FetchLibraryByGetterString: error writing library store marker %s: %w", + markerFile, + err, + ) + } + + return nil +} + +// libraryStoreEntryComplete reports whether the store entry entryDir holds the library fetched from +// getterString. +func libraryStoreEntryComplete(entryDir, getterString string) bool { + data, err := os.ReadFile(filepath.Join(entryDir, libraryStoreMarkerFileName)) + if err != nil { + return false + } + + var marker libraryStoreMarker + if err := json.Unmarshal(data, &marker); err != nil || !marker.matches(getterString) { + return false + } + + info, err := os.Stat(filepath.Join(entryDir, libraryStoreLibDirName)) + + return err == nil && info.IsDir() +} + +// renameLibraryStoreEntry renames the prepared store entry tmpDir to entryDir, and fails if entryDir +// exists. On Windows, renaming a directory also fails while another process, such as a virus scanner +// that checks the new files, has a file in it open. There, the rename is retried for up to +// libraryStoreRenameTimeout, as the Go command does for its module cache, until entryDir exists. +func renameLibraryStoreEntry(ctx context.Context, tmpDir, entryDir string) error { + deadline := time.Now().Add(libraryStoreRenameTimeout) + delay := libraryStoreRenameDelay + + for { + err := os.Rename(tmpDir, entryDir) + if err == nil || runtime.GOOS != "windows" { + return err + } + + remaining := time.Until(deadline) + if remaining <= 0 { + return err + } + + if _, statErr := os.Lstat(entryDir); statErr == nil { + return err + } + + select { + case <-ctx.Done(): + return errors.Join(err, ctx.Err()) + case <-time.After(min(delay, remaining)): + } + + delay *= libraryStoreRenameBackoff + } +} + +// lockLibraryStoreEntry waits until no other goroutine of this process holds the lock of the store +// entry entryDir, takes the lock, and returns the function that releases it. +func lockLibraryStoreEntry(ctx context.Context, entryDir string) (func(), error) { + lock, _ := libraryStoreLocks.LoadOrStore(entryDir, make(chan struct{}, 1)) + ch := lock.(chan struct{}) + + select { + case ch <- struct{}{}: + return func() { <-ch }, nil + case <-ctx.Done(): + return nil, fmt.Errorf( + "FetchLibraryByGetterString: error waiting for library store entry %s: %w", + entryDir, + ctx.Err(), + ) + } +} diff --git a/library_store_test.go b/library_store_test.go new file mode 100644 index 0000000..8719df3 --- /dev/null +++ b/library_store_test.go @@ -0,0 +1,587 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package alzlib + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io/fs" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const ( + testAlzMemberPath = "platform/alz" + testAlzMemberRef = "2026.01.0" + testLibraryMetadataFile = "alz_library_metadata.json" + testLibraryMetadata = `{"name": "test", "display_name": "test", "description": "test"}` + testLibraryStoreHelperEnv = "ALZLIB_TEST_LIBRARY_STORE_HELPER" + testLibraryStoreProcesses = 3 + testLibraryStoreGoroutines = 8 + testOpenFileDuration = 200 * time.Millisecond +) + +// runGit runs git in dir, without signing commits or tags, and returns its trimmed output. +func runGit(t *testing.T, dir string, args ...string) string { + t.Helper() + + args = append([]string{ + "-c", "user.name=alzlib", "-c", "user.email=alzlib@example.com", + "-c", "commit.gpgsign=false", "-c", "tag.gpgsign=false", + }, args...) + cmd := exec.Command("git", args...) + cmd.Dir = dir + + out, err := cmd.Output() + if exitErr := (*exec.ExitError)(nil); errors.As(err, &exitErr) { + t.Fatalf("git %v: %v: %s", args, err, exitErr.Stderr) + } + + require.NoError(t, err) + + return strings.TrimSpace(string(out)) +} + +// newTestLibraryRepo creates a git repository with files, commits them, and returns the directory of +// the repository and the commit SHA. It skips the test if git is not installed. +func newTestLibraryRepo(t *testing.T, files map[string]string) (string, string) { + t.Helper() + + if _, err := exec.LookPath("git"); err != nil { + t.Skip("git is not installed") + } + + dir := t.TempDir() + runGit(t, dir, "init", "--quiet") + + for name, content := range files { + path := filepath.Join(dir, filepath.FromSlash(name)) + require.NoError(t, os.MkdirAll(filepath.Dir(path), libraryStoreDirPerm)) + require.NoError(t, os.WriteFile(path, []byte(content), libraryStoreFilePerm)) + } + + runGit(t, dir, "add", "--all") + runGit(t, dir, "commit", "--quiet", "--message", "library") + + return dir, runGit(t, dir, "rev-parse", "HEAD") +} + +// fileURL returns the file URL of the directory dir. +func fileURL(dir string) string { + path := filepath.ToSlash(dir) + if !strings.HasPrefix(path, "/") { + path = "/" + path + } + + return "file://" + path +} + +// newTestAlzLibrary creates a git repository in place of the ALZ Library, with the member +// testAlzMemberPath at the release testAlzMemberRef, and points ALZLIB_LIBRARY_GIT_URL to it. +func newTestAlzLibrary(t *testing.T) { + t.Helper() + + dir, _ := newTestLibraryRepo(t, map[string]string{ + testAlzMemberPath + "/" + testLibraryMetadataFile: testLibraryMetadata, + }) + runGit(t, dir, "tag", testAlzMemberPath+"/"+testAlzMemberRef) + t.Setenv("ALZLIB_LIBRARY_GIT_URL", fileURL(dir)) +} + +// useLibraryStore points ALZLIB_DIR to a new directory, which it returns, and enables the library store +// until the end of the test. +func useLibraryStore(t *testing.T) string { + t.Helper() + + dir := t.TempDir() + t.Setenv("ALZLIB_DIR", dir) + t.Setenv("ALZLIB_LIBRARY_STORE_ENABLED", "") + LibraryStoreEnabled.Store(true) + t.Cleanup(func() { LibraryStoreEnabled.Store(false) }) + + return dir +} + +// observeDownloads replaces downloadLibrary until the end of the test with a function that counts the +// downloads and then calls after, if it is not nil, with the result of the download. +func observeDownloads( + t *testing.T, + after func(getterString, dst string, err error) error, +) *atomic.Int32 { + t.Helper() + + var count atomic.Int32 + + download := downloadLibrary + downloadLibrary = func(ctx context.Context, getterString, dst string) error { + count.Add(1) + + err := download(ctx, getterString, dst) + if after != nil { + return after(getterString, dst, err) + } + + return err + } + + t.Cleanup(func() { downloadLibrary = download }) + + return &count +} + +// libraryStoreEntry returns the store entry directory of getterString. +func libraryStoreEntry(alzlibDir, getterString string) string { + return filepath.Join(alzlibDir, libraryStoreDirName, hashStr(getterString)) +} + +// instanceDir returns the directory that libraries are fetched to when they are not in the store. +func instanceDir(alzlibDir string) string { + return filepath.Join(alzlibDir, strconv.Itoa(int(Instance.Load()))) +} + +// requireLibraryFile checks that the library libFS has the file name. +func requireLibraryFile(t *testing.T, libFS fs.FS, name string) { + t.Helper() + require.NotNil(t, libFS) + + _, err := fs.Stat(libFS, name) + require.NoError(t, err) +} + +func TestIsPinnedGitSource(t *testing.T) { + const sha = "0123456789abcdef0123456789abcdef01234567" + + cases := []struct { + name string + source string + want bool + }{ + {name: "git commit", source: "git::https://example.com/repo.git//lib?ref=" + sha, want: true}, + {name: "github commit", source: "github.com/org/repo//lib?ref=" + sha, want: true}, + {name: "upper case commit", source: "git::https://example.com/repo.git?ref=" + strings.ToUpper(sha), want: true}, + {name: "other parameters", source: "git::https://example.com/repo.git?depth=1&ref=" + sha, want: true}, + {name: "git tag", source: "git::https://example.com/repo.git//lib?ref=v1.0.0", want: false}, + {name: "short commit", source: "git::https://example.com/repo.git?ref=" + sha[:7], want: false}, + {name: "no ref", source: "git::https://example.com/repo.git//lib", want: false}, + {name: "http", source: "https://example.com/lib.zip?ref=" + sha, want: false}, + {name: "local directory", source: "./lib?ref=" + sha, want: false}, + {name: "alz library member", source: alzLibraryMemberGetterString(testAlzMemberPath, testAlzMemberRef), want: false}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, isPinnedGitSource(tc.source)) + }) + } +} + +func TestRedactGetterString(t *testing.T) { + const sha = "0123456789abcdef0123456789abcdef01234567" + + cases := []struct { + name string + source string + want string + }{ + { + name: "no credentials", + source: "git::https://example.com/repo.git//lib?ref=" + sha, + want: "git::https://example.com/repo.git//lib?ref=" + sha, + }, + { + name: "user and password", + source: "git::https://user:secret@example.com/repo.git//lib?ref=" + sha, + want: "git::https://REDACTED@example.com/repo.git//lib?ref=" + sha, + }, + { + name: "token as user", + source: "git::https://secret@example.com/repo.git?ref=" + sha, + want: "git::https://REDACTED@example.com/repo.git?ref=" + sha, + }, + { + name: "ssh key", + source: "git::ssh://git@example.com/repo.git?ref=" + sha + "&sshkey=c2VjcmV0", + want: "git::ssh://REDACTED@example.com/repo.git?ref=" + sha + "&sshkey=REDACTED", + }, + { + name: "scp-like ssh", + source: "git::git@example.com:org/repo.git?ref=" + sha, + want: "git::git@example.com:org/repo.git?ref=" + sha, + }, + { + name: "invalid query", + source: "git::https://example.com/repo.git?ref=%zz&sshkey=c2VjcmV0", + want: "git::https://example.com/repo.git?REDACTED", + }, + { + name: "local directory", + source: "./lib", + want: "./lib", + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, redactGetterString(tc.source)) + }) + } +} + +// TestLibraryStoreMarkerHasNoCredentials checks that the marker of a store entry does not hold the +// credentials of the URL, and still identifies the URL. +func TestLibraryStoreMarkerHasNoCredentials(t *testing.T) { + const getterString = "git::https://user:pa55word@example.com/repo.git//lib?" + + "ref=0123456789abcdef0123456789abcdef01234567&sshkey=c3NoLWtleQ" + + data, err := json.Marshal(newLibraryStoreMarker(getterString)) + require.NoError(t, err) + assert.NotContains(t, string(data), "pa55word") + assert.NotContains(t, string(data), "c3NoLWtleQ") + + var marker libraryStoreMarker + require.NoError(t, json.Unmarshal(data, &marker)) + assert.True(t, marker.matches(getterString)) + assert.False(t, marker.matches(strings.Replace(getterString, "pa55word", "other", 1))) +} + +// TestLibraryStoreAlzLibraryMember checks that an ALZ Library member is fetched into the store once, +// and reused by later fetches. +func TestLibraryStoreAlzLibraryMember(t *testing.T) { + newTestAlzLibrary(t) + alzlibDir := useLibraryStore(t) + downloads := observeDownloads(t, nil) + ctx := context.Background() + + libFS, err := NewAlzLibraryReference(testAlzMemberPath, testAlzMemberRef).Fetch(ctx, "dst") + require.NoError(t, err) + requireLibraryFile(t, libFS, testLibraryMetadataFile) + assert.Equal(t, int32(1), downloads.Load()) + + getterString := alzLibraryMemberGetterString(testAlzMemberPath, testAlzMemberRef) + entryDir := libraryStoreEntry(alzlibDir, getterString) + assert.True(t, libraryStoreEntryComplete(entryDir, getterString)) + + data, err := os.ReadFile(filepath.Join(entryDir, libraryStoreMarkerFileName)) + require.NoError(t, err) + + var marker libraryStoreMarker + require.NoError(t, json.Unmarshal(data, &marker)) + assert.Equal(t, getterString, marker.Getter) + assert.True(t, marker.matches(getterString)) + assert.False(t, marker.FetchedAt.IsZero()) + + // A new reference to the member, in another instance, reuses the entry. + instance := Instance.Load() + Instance.Store(instance + 1) + t.Cleanup(func() { Instance.Store(instance) }) + + libFS, err = NewAlzLibraryReference(testAlzMemberPath, testAlzMemberRef).Fetch(ctx, "dst") + require.NoError(t, err) + requireLibraryFile(t, libFS, testLibraryMetadataFile) + assert.Equal(t, int32(1), downloads.Load()) + + // The library is only in the store, and no temporary directory is left. + entries, err := os.ReadDir(alzlibDir) + require.NoError(t, err) + require.Len(t, entries, 1) + assert.Equal(t, libraryStoreDirName, entries[0].Name()) + + entries, err = os.ReadDir(filepath.Join(alzlibDir, libraryStoreDirName)) + require.NoError(t, err) + require.Len(t, entries, 1) + assert.Equal(t, filepath.Base(entryDir), entries[0].Name()) +} + +// TestLibraryStoreCustomLibrary checks that a custom library is only stored when its git ref is a +// commit SHA. +func TestLibraryStoreCustomLibrary(t *testing.T) { + repoDir, commit := newTestLibraryRepo(t, map[string]string{ + "lib/" + testLibraryMetadataFile: testLibraryMetadata, + }) + runGit(t, repoDir, "branch", "release") + + alzlibDir := useLibraryStore(t) + downloads := observeDownloads(t, nil) + ctx := context.Background() + + t.Run("commit", func(t *testing.T) { + downloads.Store(0) + + getterString := "git::" + fileURL(repoDir) + "//lib?ref=" + commit + + for range 2 { + libFS, err := NewCustomLibraryReference(getterString).Fetch(ctx, "commit") + require.NoError(t, err) + requireLibraryFile(t, libFS, testLibraryMetadataFile) + } + + assert.Equal(t, int32(1), downloads.Load()) + assert.True(t, libraryStoreEntryComplete(libraryStoreEntry(alzlibDir, getterString), getterString)) + assert.NoDirExists(t, filepath.Join(instanceDir(alzlibDir), "commit")) + }) + + t.Run("branch", func(t *testing.T) { + downloads.Store(0) + + getterString := "git::" + fileURL(repoDir) + "//lib?ref=release" + + for range 2 { + libFS, err := NewCustomLibraryReference(getterString).Fetch(ctx, "branch") + require.NoError(t, err) + requireLibraryFile(t, libFS, testLibraryMetadataFile) + } + + assert.Equal(t, int32(2), downloads.Load()) + assert.NoDirExists(t, libraryStoreEntry(alzlibDir, getterString)) + assert.DirExists(t, filepath.Join(instanceDir(alzlibDir), "branch")) + }) + + t.Run("local directory", func(t *testing.T) { + downloads.Store(0) + + libFS, err := FetchLibraryByGetterString(ctx, "./testdata/simple", "local") + require.NoError(t, err) + require.NotNil(t, libFS) + assert.Equal(t, int32(1), downloads.Load()) + + // go-getter links a local directory to the destination, rather than copying it. + _, err = os.Lstat(filepath.Join(instanceDir(alzlibDir), "local")) + require.NoError(t, err) + }) +} + +// TestLibraryStoreDisabled checks that nothing is stored when the store is disabled. +func TestLibraryStoreDisabled(t *testing.T) { + newTestAlzLibrary(t) + + alzlibDir := t.TempDir() + t.Setenv("ALZLIB_DIR", alzlibDir) + t.Setenv("ALZLIB_LIBRARY_STORE_ENABLED", "") + + downloads := observeDownloads(t, nil) + + for range 2 { + libFS, err := NewAlzLibraryReference(testAlzMemberPath, testAlzMemberRef).Fetch(context.Background(), "dst") + require.NoError(t, err) + requireLibraryFile(t, libFS, testLibraryMetadataFile) + } + + assert.Equal(t, int32(2), downloads.Load()) + assert.NoDirExists(t, filepath.Join(alzlibDir, libraryStoreDirName)) + assert.DirExists(t, filepath.Join(instanceDir(alzlibDir), "dst")) +} + +// TestLibraryStoreEnabledByEnvironment checks that the environment variable enables the store. +func TestLibraryStoreEnabledByEnvironment(t *testing.T) { + newTestAlzLibrary(t) + + alzlibDir := t.TempDir() + t.Setenv("ALZLIB_DIR", alzlibDir) + t.Setenv("ALZLIB_LIBRARY_STORE_ENABLED", "true") + + _, err := NewAlzLibraryReference(testAlzMemberPath, testAlzMemberRef).Fetch(context.Background(), "dst") + require.NoError(t, err) + + getterString := alzLibraryMemberGetterString(testAlzMemberPath, testAlzMemberRef) + assert.True(t, libraryStoreEntryComplete(libraryStoreEntry(alzlibDir, getterString), getterString)) +} + +// TestLibraryStoreInvalidEntry checks that an entry that is not complete for the requested library is +// left as it is, and that the library is fetched as if the store was disabled. +func TestLibraryStoreInvalidEntry(t *testing.T) { + newTestAlzLibrary(t) + + getterString := alzLibraryMemberGetterString(testAlzMemberPath, testAlzMemberRef) + otherMarker, err := json.Marshal(newLibraryStoreMarker("other")) + require.NoError(t, err) + + cases := []struct { + name string + marker []byte // nil for no marker file + }{ + {name: "no marker", marker: nil}, + {name: "marker of another library", marker: otherMarker}, + {name: "marker is not json", marker: []byte("{")}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + alzlibDir := useLibraryStore(t) + downloads := observeDownloads(t, nil) + entryDir := libraryStoreEntry(alzlibDir, getterString) + require.NoError(t, os.MkdirAll(filepath.Join(entryDir, libraryStoreLibDirName), libraryStoreDirPerm)) + + markerFile := filepath.Join(entryDir, libraryStoreMarkerFileName) + if tc.marker != nil { + require.NoError(t, os.WriteFile(markerFile, tc.marker, libraryStoreFilePerm)) + } + + libFS, err := NewAlzLibraryReference(testAlzMemberPath, testAlzMemberRef).Fetch(context.Background(), "dst") + require.NoError(t, err) + requireLibraryFile(t, libFS, testLibraryMetadataFile) + assert.Equal(t, int32(1), downloads.Load()) + assert.DirExists(t, filepath.Join(instanceDir(alzlibDir), "dst")) + + // The entry is unchanged. + if tc.marker == nil { + assert.NoFileExists(t, markerFile) + } else { + data, err := os.ReadFile(markerFile) + require.NoError(t, err) + assert.Equal(t, tc.marker, data) + } + + entries, err := os.ReadDir(filepath.Join(entryDir, libraryStoreLibDirName)) + require.NoError(t, err) + assert.Empty(t, entries) + }) + } +} + +// TestLibraryStoreConcurrentFetches checks that goroutines fetching the same library download it once. +func TestLibraryStoreConcurrentFetches(t *testing.T) { + newTestAlzLibrary(t) + useLibraryStore(t) + downloads := observeDownloads(t, nil) + + var wg sync.WaitGroup + + errs := make([]error, testLibraryStoreGoroutines) + fss := make([]fs.FS, testLibraryStoreGoroutines) + + for i := range testLibraryStoreGoroutines { + wg.Go(func() { + ref := NewAlzLibraryReference(testAlzMemberPath, testAlzMemberRef) + fss[i], errs[i] = ref.Fetch(context.Background(), "dst") + }) + } + + wg.Wait() + + for i := range testLibraryStoreGoroutines { + require.NoError(t, errs[i]) + requireLibraryFile(t, fss[i], testLibraryMetadataFile) + } + + assert.Equal(t, int32(1), downloads.Load()) +} + +// TestLibraryStoreEntryAddedByAnotherProcess checks that the entry of another process is used when that +// process adds it first. +func TestLibraryStoreEntryAddedByAnotherProcess(t *testing.T) { + newTestAlzLibrary(t) + alzlibDir := useLibraryStore(t) + + const otherFile = "other.json" + + getterString := alzLibraryMemberGetterString(testAlzMemberPath, testAlzMemberRef) + entryDir := libraryStoreEntry(alzlibDir, getterString) + + observeDownloads(t, func(_, _ string, err error) error { + // The other process adds the entry while this one downloads the library. + otherLibDir := filepath.Join(entryDir, libraryStoreLibDirName) + require.NoError(t, os.MkdirAll(otherLibDir, libraryStoreDirPerm)) + require.NoError(t, os.WriteFile(filepath.Join(otherLibDir, otherFile), []byte("{}"), libraryStoreFilePerm)) + + marker, merr := json.Marshal(newLibraryStoreMarker(getterString)) + require.NoError(t, merr) + require.NoError(t, os.WriteFile(filepath.Join(entryDir, libraryStoreMarkerFileName), marker, libraryStoreFilePerm)) + + return err + }) + + libFS, err := NewAlzLibraryReference(testAlzMemberPath, testAlzMemberRef).Fetch(context.Background(), "dst") + require.NoError(t, err) + requireLibraryFile(t, libFS, otherFile) + + // The library that this process downloaded has been removed. + entries, err := os.ReadDir(filepath.Join(alzlibDir, libraryStoreDirName)) + require.NoError(t, err) + require.Len(t, entries, 1) + assert.Equal(t, filepath.Base(entryDir), entries[0].Name()) +} + +// TestLibraryStoreRenameWhileFileIsOpen checks that an entry is added while another process has one of +// its files open for a short time. On Windows, this makes the rename fail until the file is closed. +func TestLibraryStoreRenameWhileFileIsOpen(t *testing.T) { + newTestAlzLibrary(t) + useLibraryStore(t) + + observeDownloads(t, func(_, dst string, err error) error { + if err != nil { + return err + } + + f, err := os.Open(filepath.Join(dst, testLibraryMetadataFile)) + require.NoError(t, err) + + time.AfterFunc(testOpenFileDuration, func() { _ = f.Close() }) + + return nil + }) + + libFS, err := NewAlzLibraryReference(testAlzMemberPath, testAlzMemberRef).Fetch(context.Background(), "dst") + require.NoError(t, err) + requireLibraryFile(t, libFS, testLibraryMetadataFile) +} + +// TestLibraryStoreConcurrentProcesses checks that processes fetching the same library into the same +// store at the same time all get the complete library, and leave one entry. +func TestLibraryStoreConcurrentProcesses(t *testing.T) { + newTestAlzLibrary(t) + alzlibDir := useLibraryStore(t) + + cmds := make([]*exec.Cmd, testLibraryStoreProcesses) + outputs := make([]*bytes.Buffer, testLibraryStoreProcesses) + + for i := range cmds { + outputs[i] = new(bytes.Buffer) + cmds[i] = exec.Command(os.Args[0], "-test.run=^TestLibraryStoreHelperProcess$", "-test.count=1") + + cmds[i].Env = append(os.Environ(), testLibraryStoreHelperEnv+"=1", "ALZLIB_LIBRARY_STORE_ENABLED=true") + cmds[i].Stdout = outputs[i] + cmds[i].Stderr = outputs[i] + } + + for _, cmd := range cmds { + require.NoError(t, cmd.Start()) + } + + for i, cmd := range cmds { + require.NoError(t, cmd.Wait(), "process %d: %s", i, outputs[i]) + } + + getterString := alzLibraryMemberGetterString(testAlzMemberPath, testAlzMemberRef) + entryDir := libraryStoreEntry(alzlibDir, getterString) + assert.True(t, libraryStoreEntryComplete(entryDir, getterString)) + + entries, err := os.ReadDir(filepath.Join(alzlibDir, libraryStoreDirName)) + require.NoError(t, err) + require.Len(t, entries, 1) + assert.Equal(t, filepath.Base(entryDir), entries[0].Name()) +} + +// TestLibraryStoreHelperProcess fetches the test ALZ Library member in a process started by +// TestLibraryStoreConcurrentProcesses. +func TestLibraryStoreHelperProcess(t *testing.T) { + if os.Getenv(testLibraryStoreHelperEnv) != "1" { + t.Skip("run by TestLibraryStoreConcurrentProcesses") + } + + libFS, err := NewAlzLibraryReference(testAlzMemberPath, testAlzMemberRef).Fetch(context.Background(), "dst") + require.NoError(t, err) + requireLibraryFile(t, libFS, testLibraryMetadataFile) +} diff --git a/metadata.go b/metadata.go index 38deb01..7b4088b 100644 --- a/metadata.go +++ b/metadata.go @@ -45,15 +45,13 @@ func (m LibraryReferences) FSs() []fs.FS { // The destination directory a hash value that will be appended to the `.alzlib` directory in the // current working // directory unless overridden by the `ALZLIB_DIR` environment variable. +// Libraries are fetched concurrently, but the result is always in the same order: each library is +// listed once, after its dependencies, in the order of a depth-first walk of the references and their +// dependencies. func (m LibraryReferences) FetchWithDependencies(ctx context.Context) (LibraryReferences, error) { - processed := make(map[string]bool) - result := make(LibraryReferences, 0, InitialLibraryReferencesCapacity) - - for _, lib := range m { - err := fetchLibraryWithDependencies(ctx, processed, lib, &result) - if err != nil { - return nil, err - } + result, err := fetchLibrariesWithDependencies(ctx, m...) + if err != nil { + return nil, err } return result, nil @@ -68,6 +66,7 @@ type LibraryReference interface { desinationDirectory string, ) (fs.FS, error) // Fetch fetches the library member to the `.alzlib/destinationDirectory`. // Override the base dir using `ALZLIB_DIR` env var. + // Libraries in the library store are fetched to the store instead, see LibraryStoreEnabled. FetchWithDependencies( ctx context.Context, ) (LibraryReferences, error) // FetchWithDependencies fetches the library member and its dependencies. @@ -77,6 +76,9 @@ type LibraryReference interface { var ( _ LibraryReference = (*AlzLibraryReference)(nil) _ LibraryReference = (*CustomLibraryReference)(nil) + + _ prefetchableLibraryReference = (*AlzLibraryReference)(nil) + _ prefetchableLibraryReference = (*CustomLibraryReference)(nil) ) // AlzLibraryReference is a struct that represents a dependency of a library member that is fetched @@ -154,6 +156,11 @@ func (m *AlzLibraryReference) FS() fs.FS { return m.filesystem } +// setFS sets the filesystem of the library member, as Fetch does. +func (m *AlzLibraryReference) setFS(filesystem fs.FS) { + m.filesystem = filesystem +} + // String returns the formatted path and the tag of the library member. func (m *AlzLibraryReference) String() string { return strings.Join([]string{m.path, m.ref}, "@") @@ -175,10 +182,7 @@ func (m *AlzLibraryReference) Ref() string { func (m *AlzLibraryReference) FetchWithDependencies( ctx context.Context, ) (LibraryReferences, error) { - processed := make(map[string]bool) - result := make(LibraryReferences, 0, InitialLibraryReferencesCapacity) - - return result, fetchLibraryWithDependencies(ctx, processed, m, &result) + return fetchLibrariesWithDependencies(ctx, m) } // CustomLibraryReference is a struct that represents a dependency of a library member that is @@ -237,6 +241,11 @@ func (m *CustomLibraryReference) FS() fs.FS { return m.filesystem } +// setFS sets the filesystem of the library member, as Fetch does. +func (m *CustomLibraryReference) setFS(filesystem fs.FS) { + m.filesystem = filesystem +} + // String returns the URL of the custom go-getter. func (m *CustomLibraryReference) String() string { return m.url @@ -248,10 +257,7 @@ func (m *CustomLibraryReference) String() string { func (m *CustomLibraryReference) FetchWithDependencies( ctx context.Context, ) (LibraryReferences, error) { - processed := make(map[string]bool) - result := make(LibraryReferences, 0, InitialLibraryReferencesCapacity) - - return result, fetchLibraryWithDependencies(ctx, processed, m, &result) + return fetchLibrariesWithDependencies(ctx, m) } // NewMetadata creates a new Metadata instance from the processor.LibMetadata and a LibraryReference. diff --git a/metadata_test.go b/metadata_test.go index 16c56a7..773ea63 100644 --- a/metadata_test.go +++ b/metadata_test.go @@ -42,7 +42,7 @@ func TestFetchLibrariesWithDependencies(t *testing.T) { result[i] = lib.String() } - assert.ElementsMatch(t, expcted, result) + assert.Equal(t, expcted, result) } // TestFetchLibrariesWithCommonDependency checks that a libraries having a common dependency is @@ -71,7 +71,7 @@ func TestFetchLibrariesWithCommonDependency(t *testing.T) { result[i] = lib.String() } - assert.ElementsMatch(t, expcted, result) + assert.Equal(t, expcted, result) } // TestNewAlzLibraryReferenceFromFS verifies that Fetch returns the pre-supplied fs.FS