Skip to content

Commit 990013e

Browse files
authored
Symlink node_modules/.cache to tempdir (#661)
1 parent 63e177d commit 990013e

24 files changed

+448
-4
lines changed

README.md

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -40,9 +40,10 @@ file that looks like the following:
4040

4141
## Configuration
4242

43-
| Environment Variable | Description |
44-
|-------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
45-
| `$BP_NPM_VERSION` | If set, this custom version of `npm` will be used instead of the one provided by the `nodejs` installation. |
43+
| Environment Variable | Description |
44+
|-----------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
45+
| `$BP_NPM_VERSION` | If set, this custom version of `npm` will be used instead of the one provided by the `nodejs` installation. |
46+
| `$BP_KEEP_NODE_BUILD_CACHE` | If set to `true` (default `false`), the folder `node_modules/.cache` will not be removed after the build, but will be readonly at runtime. |
4647

4748
## Usage
4849

build.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ import (
1818
"github.com/paketo-buildpacks/packit/v2/scribe"
1919
)
2020

21+
const NODE_MODULES_CACHE = "node_modules_cache"
22+
2123
//go:generate faux --interface BuildManager --output fakes/build_manager.go
2224
type BuildManager interface {
2325
Resolve(workingDir string) (BuildProcess, bool, error)
@@ -282,6 +284,21 @@ func Build(entryResolver EntryResolver,
282284
return packit.BuildResult{}, err
283285
}
284286

287+
keepBuildCache, _ := environment.Lookup("BP_KEEP_NODE_BUILD_CACHE")
288+
if keepBuildCache != "true" {
289+
linkName := filepath.Join(layer.Path, "node_modules", ".cache")
290+
err = os.RemoveAll(linkName)
291+
if err != nil {
292+
return packit.BuildResult{}, err
293+
}
294+
295+
cacheFolder := filepath.Join(os.TempDir(), NODE_MODULES_CACHE)
296+
err = os.Symlink(cacheFolder, linkName)
297+
if err != nil {
298+
return packit.BuildResult{}, err
299+
}
300+
}
301+
285302
if build {
286303
err = symlinkResolver.Copy(filepath.Join(projectPath, "package-lock.json"), buildLayerPath, layer.Path)
287304
if err != nil {

build_test.go

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ func testBuild(t *testing.T, context spec.G, it spec.S) {
2828
layersDir string
2929
workingDir string
3030
cnbDir string
31+
tempDir string
3132

3233
processLayerDir string
3334
processWorkingDir string
@@ -60,6 +61,9 @@ func testBuild(t *testing.T, context spec.G, it spec.S) {
6061
cnbDir, err = os.MkdirTemp("", "cnb")
6162
Expect(err).NotTo(HaveOccurred())
6263

64+
tempDir = t.TempDir()
65+
t.Setenv("TMPDIR", tempDir)
66+
6367
t.Setenv("BP_NODE_PROJECT_PATH", "")
6468

6569
buildProcess = &fakes.BuildProcess{}
@@ -423,6 +427,38 @@ func testBuild(t *testing.T, context spec.G, it spec.S) {
423427
Expect(symlinkResolver.ResolveCall.Receives.LockfilePath).To(Equal(filepath.Join(workingDir, "package-lock.json")))
424428
Expect(symlinkResolver.ResolveCall.Receives.LayerPath).To(Equal(filepath.Join(layersDir, "launch-modules")))
425429
})
430+
431+
it("symlinks node_modules/.cache to tmp/node_modules_cache in order to work for the run user", func() {
432+
err := os.MkdirAll(filepath.Join(tempDir, "node_modules_cache", "temp-content"), os.ModePerm)
433+
Expect(err).NotTo(HaveOccurred())
434+
result, err := build(packit.BuildContext{
435+
BuildpackInfo: packit.BuildpackInfo{
436+
SBOMFormats: []string{"application/vnd.cyclonedx+json", "application/spdx+json", "application/vnd.syft+json"},
437+
},
438+
Platform: packit.Platform{
439+
Path: "some-platform-path",
440+
},
441+
WorkingDir: workingDir,
442+
Layers: packit.Layers{Path: layersDir},
443+
CNBPath: cnbDir,
444+
Plan: packit.BuildpackPlan{
445+
Entries: []packit.BuildpackPlanEntry{
446+
{Name: "node_modules"},
447+
},
448+
},
449+
})
450+
Expect(err).NotTo(HaveOccurred())
451+
452+
Expect(len(result.Layers)).To(Equal(2))
453+
454+
launchLayer := result.Layers[0]
455+
Expect(launchLayer.Name).To(Equal("launch-modules"))
456+
Expect(launchLayer.Path).To(Equal(filepath.Join(layersDir, "launch-modules")))
457+
458+
linkedTmpContent := filepath.Join(launchLayer.Path, "node_modules", ".cache", "temp-content")
459+
_, err = os.Stat(linkedTmpContent)
460+
Expect(err).NotTo(HaveOccurred())
461+
})
426462
})
427463

428464
context("when node_modules is required at build and launch", func() {
@@ -674,6 +710,39 @@ func testBuild(t *testing.T, context spec.G, it spec.S) {
674710
Expect(symlinkResolver.CopyCall.Receives.SourceLayerPath).To(Equal(filepath.Join(buildLayer.Path)))
675711
Expect(symlinkResolver.CopyCall.Receives.TargetLayerPath).To(Equal(filepath.Join(launchLayer.Path)))
676712
})
713+
714+
it("symlinks node_modules/.cache to tmp/node_modules_cache in order to work for the run user", func() {
715+
err := os.MkdirAll(filepath.Join(tempDir, "node_modules_cache", "temp-content"), os.ModePerm)
716+
Expect(err).NotTo(HaveOccurred())
717+
result, err := build(packit.BuildContext{
718+
BuildpackInfo: packit.BuildpackInfo{
719+
SBOMFormats: []string{"application/vnd.cyclonedx+json", "application/spdx+json", "application/vnd.syft+json"},
720+
},
721+
Platform: packit.Platform{
722+
Path: "some-platform-path",
723+
},
724+
WorkingDir: workingDir,
725+
Layers: packit.Layers{Path: layersDir},
726+
CNBPath: cnbDir,
727+
Plan: packit.BuildpackPlan{
728+
Entries: []packit.BuildpackPlanEntry{
729+
{Name: "node_modules"},
730+
},
731+
},
732+
})
733+
Expect(err).NotTo(HaveOccurred())
734+
735+
Expect(len(result.Layers)).To(Equal(3))
736+
737+
launchLayer := result.Layers[1]
738+
Expect(launchLayer.Name).To(Equal("launch-modules"))
739+
Expect(launchLayer.Path).To(Equal(filepath.Join(layersDir, "launch-modules")))
740+
741+
linkedTmpContent := filepath.Join(launchLayer.Path, "node_modules", ".cache", "temp-content")
742+
_, err = os.Stat(linkedTmpContent)
743+
Expect(err).NotTo(HaveOccurred())
744+
})
745+
677746
})
678747

679748
context("when one npmrc binding is detected", func() {
@@ -768,6 +837,10 @@ func testBuild(t *testing.T, context spec.G, it spec.S) {
768837
if err != nil {
769838
return err
770839
}
840+
err = os.MkdirAll(filepath.Join(ld, "node_modules"), os.ModePerm)
841+
if err != nil {
842+
return err
843+
}
771844

772845
return nil
773846
}

buildpack.toml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,11 @@ api = "0.7"
3232
name = "BP_NPM_VERSION"
3333
description = "configures a custom npm version"
3434

35+
[[metadata.configurations]]
36+
name = "BP_KEEP_NODE_BUILD_CACHE"
37+
default = "false"
38+
description = "keep the 'node_modules/.cache' folder after the build (will be readonly at runtime)'"
39+
3540
[[metadata.configurations]]
3641
name = "NODE_HOME"
3742
description = "path the Node.js installation"
@@ -45,5 +50,6 @@ api = "0.7"
4550
default = "error"
4651
description = "configures npm output verbosity"
4752

53+
4854
[[stacks]]
4955
id = "*"

cmd/setup-symlinks/internal/run.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,13 @@ func Run(executablePath, appDir string, symlinkResolver npminstall.SymlinkResolv
4242
return err
4343
}
4444

45-
return createSymlink(filepath.Join(layerPath, "node_modules"), linkPath)
45+
err = createSymlink(filepath.Join(layerPath, "node_modules"), linkPath)
46+
if err != nil {
47+
return err
48+
}
49+
50+
cacheFolder := filepath.Join(os.TempDir(), npminstall.NODE_MODULES_CACHE)
51+
return os.Mkdir(cacheFolder, os.ModePerm)
4652
}
4753

4854
func resolveWorkspaceModules(symlinkResolver npminstall.SymlinkResolver, appDir, layerPath string) error {

cmd/setup-symlinks/internal/run_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ func testRun(t *testing.T, context spec.G, it spec.S) {
4141

4242
tmpDir, err = os.MkdirTemp("", "tmp")
4343
Expect(err).NotTo(HaveOccurred())
44+
t.Setenv("TMPDIR", tmpDir)
4445

4546
Expect(os.Symlink(filepath.Join(tmpDir, "node_modules"), filepath.Join(appDir, "node_modules"))).To(Succeed())
4647

integration/init_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,7 @@ func TestIntegration(t *testing.T) {
126126
suite("EmptyNodeModules", testEmptyNodeModules)
127127
suite("Logging", testLogging)
128128
suite("NativeModules", testNativeModules)
129+
suite("NodeModulesCache", testReact)
129130
suite("NoNodeModules", testNoNodeModules)
130131
suite("Npmrc", testNpmrc)
131132
suite("PackageLockMismatch", testPackageLockMismatch)

integration/react_test.go

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
package integration_test
2+
3+
import (
4+
"os"
5+
"path/filepath"
6+
"testing"
7+
"time"
8+
9+
"github.com/paketo-buildpacks/occam"
10+
"github.com/sclevine/spec"
11+
12+
. "github.com/onsi/gomega"
13+
. "github.com/paketo-buildpacks/occam/matchers"
14+
)
15+
16+
func testReact(t *testing.T, context spec.G, it spec.S) {
17+
var (
18+
Expect = NewWithT(t).Expect
19+
Eventually = NewWithT(t).Eventually
20+
21+
pack occam.Pack
22+
docker occam.Docker
23+
imageIDs map[string]struct{}
24+
containerIDs map[string]struct{}
25+
26+
name string
27+
source string
28+
29+
pullPolicy = "never"
30+
)
31+
32+
it.Before(func() {
33+
imageIDs = make(map[string]struct{})
34+
containerIDs = make(map[string]struct{})
35+
36+
pack = occam.NewPack().WithNoColor()
37+
docker = occam.NewDocker()
38+
39+
var err error
40+
name, err = occam.RandomName()
41+
Expect(err).NotTo(HaveOccurred())
42+
43+
if settings.Extensions.UbiNodejsExtension.Online != "" {
44+
pullPolicy = "always"
45+
}
46+
47+
})
48+
49+
it.After(func() {
50+
for id := range containerIDs {
51+
Expect(docker.Container.Remove.Execute(id)).To(Succeed())
52+
}
53+
54+
for id := range imageIDs {
55+
Expect(docker.Image.Remove.Execute(id)).To(Succeed())
56+
}
57+
58+
Expect(os.RemoveAll(source)).To(Succeed())
59+
})
60+
61+
context("when the app is a react app", func() {
62+
it("works", func() {
63+
var err error
64+
source, err = occam.Source(filepath.Join("testdata", "react_app"))
65+
Expect(err).NotTo(HaveOccurred())
66+
67+
build := pack.Build.
68+
WithPullPolicy(pullPolicy).
69+
WithExtensions(
70+
settings.Extensions.UbiNodejsExtension.Online,
71+
).
72+
WithBuildpacks(
73+
settings.Buildpacks.NodeEngine.Online,
74+
settings.Buildpacks.NPMInstall.Online,
75+
settings.Buildpacks.BuildPlan.Online,
76+
)
77+
78+
image, logs, err := build.Execute(name, source)
79+
Expect(err).NotTo(HaveOccurred(), logs.String)
80+
81+
container, err := docker.Container.Run.
82+
WithCommand("npm start").
83+
WithEnv(map[string]string{"PORT": "8080"}).
84+
WithPublish("8080").
85+
Execute(image.ID)
86+
Expect(err).NotTo(HaveOccurred())
87+
88+
containerIDs[container.ID] = struct{}{}
89+
90+
Eventually(container).Should(BeAvailable())
91+
92+
Eventually(func() string {
93+
cLogs, err := docker.Container.Logs.Execute(container.ID)
94+
Expect(err).NotTo(HaveOccurred())
95+
return cLogs.String()
96+
}).WithTimeout(3 * time.Second).Should(ContainSubstring("webpack compiled successfully"))
97+
})
98+
})
99+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
{
2+
"name": "react-app",
3+
"version": "0.1.0",
4+
"private": true,
5+
"dependencies": {
6+
"@testing-library/jest-dom": "^5.17.0",
7+
"@testing-library/react": "^13.4.0",
8+
"@testing-library/user-event": "^13.5.0",
9+
"react": "^18.2.0",
10+
"react-dom": "^18.2.0",
11+
"react-scripts": "5.0.1",
12+
"web-vitals": "^2.1.4"
13+
},
14+
"scripts": {
15+
"start": "react-scripts start",
16+
"build": "react-scripts build",
17+
"test": "react-scripts test",
18+
"eject": "react-scripts eject"
19+
},
20+
"eslintConfig": {
21+
"extends": [
22+
"react-app",
23+
"react-app/jest"
24+
]
25+
},
26+
"browserslist": {
27+
"production": [
28+
">0.2%",
29+
"not dead",
30+
"not op_mini all"
31+
],
32+
"development": [
33+
"last 1 chrome version",
34+
"last 1 firefox version",
35+
"last 1 safari version"
36+
]
37+
}
38+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
[[requires]]
2+
name = "node"
3+
4+
[requires.metadata]
5+
launch = true
6+
7+
[[requires]]
8+
name = "node_modules"
9+
10+
[requires.metadata]
11+
launch = true

0 commit comments

Comments
 (0)