Compare commits

...

8 Commits

Author SHA1 Message Date
Vinícius Lourenço
3040b402d7 test(e2e): disable response compression on the e2e server 2026-12-02 09:26:20 -03:00
Vinícius Lourenço
08dea1fb8d feat(apiserver): add apiserver.compression.enabled 2026-12-02 09:26:19 -03:00
Vinícius Lourenço
3a00eb69fe Merge remote-tracking branch 'origin/main' into perf/web-immutable-assets 2026-12-02 09:26:04 -03:00
Vinícius Lourenço
f0c1f4bbf9 test(http): name the cache control table loop variable testCase 2026-12-01 10:37:24 -03:00
Vinícius Lourenço
8fad61a8b5 Merge remote-tracking branch 'origin/main' into perf/web-immutable-assets
# Conflicts:
#	frontend/vite.config.ts
2026-12-01 10:22:46 -03:00
Vinícius Lourenço
ed69006a2a refactor(web): set the immutable cache header from the cache middleware on an /assets/ route 2026-12-01 10:21:58 -03:00
Vinícius Lourenço
649c3a250c build(web): pin hashed asset names that the immutable cache relies on 2026-11-23 22:46:11 -03:00
Vinícius Lourenço
f7b1383427 perf(web): cache hashed frontend assets as immutable 2026-11-23 22:46:09 -03:00
11 changed files with 254 additions and 19 deletions

View File

@@ -165,6 +165,10 @@ apiserver:
- /api/v1/health
- /api/v1/version
- /
- /assets/
compression:
# Gzip responses on the fly. Turn off when a proxy in front already compresses.
enabled: true
##################### Querier #####################
querier:

3
frontend/.gitignore vendored
View File

@@ -1,4 +1,7 @@
# Vite copies public/ unhashed, and the Go server caches /assets/ as immutable
/public/assets/
# Sentry Config File
.env.sentry-build-plugin
.qodo

View File

@@ -185,6 +185,8 @@ export default defineConfig(({ mode }): UserConfig => {
sourcemap: true,
outDir: 'build',
cssMinify: 'esbuild',
// The Go server caches /assets/ as immutable, so every file there must carry a content hash.
assetsDir: 'assets',
rolldownOptions: {
treeshake: {
moduleSideEffects: [
@@ -197,6 +199,9 @@ export default defineConfig(({ mode }): UserConfig => {
],
},
output: {
entryFileNames: 'assets/[name]-[hash].js',
chunkFileNames: 'assets/[name]-[hash].js',
assetFileNames: 'assets/[name]-[hash].[ext]',
// Without this group Rolldown splits the entry's static graph into ~300
// chunks, 324 requests on first load.
codeSplitting: {

View File

@@ -11,8 +11,9 @@ import (
// Config holds the configuration for config.
type Config struct {
httpserver.Config `mapstructure:",squash" yaml:",squash"`
Timeout Timeout `mapstructure:"timeout"`
Logging Logging `mapstructure:"logging"`
Timeout Timeout `mapstructure:"timeout"`
Logging Logging `mapstructure:"logging"`
Compression Compression `mapstructure:"compression"`
}
type Timeout struct {
@@ -29,6 +30,10 @@ type Logging struct {
ExcludedRoutes []string `mapstructure:"excluded_routes"`
}
type Compression struct {
Enabled bool `mapstructure:"enabled"`
}
func NewConfigFactory() factory.ConfigFactory {
return factory.NewConfigFactory(factory.MustNewName("apiserver"), newConfig)
}
@@ -53,8 +58,12 @@ func newConfig() factory.Config {
"/api/v1/health",
"/api/v1/version",
"/",
"/assets/",
},
},
Compression: Compression{
Enabled: true,
},
}
}

View File

@@ -68,7 +68,56 @@ func TestNewWithEnvProvider(t *testing.T) {
"/api/v1/health1",
},
},
Compression: Compression{
Enabled: true,
},
}
assert.Equal(t, expected, actual)
}
func TestCompressionWithEnvProvider(t *testing.T) {
testCases := []struct {
name string
env map[string]string
expected Compression
}{
{
name: "Defaults",
env: map[string]string{},
expected: Compression{Enabled: true},
},
{
name: "Disabled",
env: map[string]string{"SIGNOZ_APISERVER_COMPRESSION_ENABLED": "false"},
expected: Compression{Enabled: false},
},
{
name: "Disabled_Capitalized",
env: map[string]string{"SIGNOZ_APISERVER_COMPRESSION_ENABLED": "False"},
expected: Compression{Enabled: false},
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
for key, value := range testCase.env {
t.Setenv(key, value)
}
conf, err := config.New(
context.Background(),
config.ResolverConfig{
Uris: []string{"env:"},
ProviderFactories: []config.ProviderFactory{envprovider.NewFactory()},
},
[]factory.ConfigFactory{NewConfigFactory()},
)
require.NoError(t, err)
actual := &Config{}
require.NoError(t, conf.Unmarshal("apiserver", actual))
assert.Equal(t, testCase.expected, actual.Compression)
})
}
}

View File

@@ -338,7 +338,9 @@ func newProvider(
}
httpHandler := middleware.NewCors().Wrap(router)
httpHandler = middleware.NewCompress().Wrap(httpHandler)
if config.Compression.Enabled {
httpHandler = middleware.NewCompress().Wrap(httpHandler)
}
routePrefix := globalConfig.ExternalPath()
if routePrefix != "" {

View File

@@ -8,25 +8,38 @@ import (
)
type Cache struct {
maxAge time.Duration
cacheControl string
}
func NewCache(maxAge time.Duration) *Cache {
// Cache-Control: no-cache is equivalent to Cache-Control: max-age=0, must-revalidate as most HTTP/1.0 caches don't support no-cache directives
directives := []string{
"max-age=" + strconv.Itoa(int(maxAge.Seconds())),
"no-cache", // Note that no-cache does not mean "don't cache". no-cache allows caches to store a response but requires them to revalidate it before reuse.
"private", //If you forget to add private to a response with personalized content, then that response can be stored in a shared cache and end up being reused for multiple users, which can cause personal information to leak.
"must-revalidate", // HTTP allows caches to reuse stale responses when they are disconnected from the origin server. must-revalidate is a way to prevent this from happening - either the stored response is revalidated with the origin server or a 504 (Gateway Timeout) response is generated.
}
return &Cache{
maxAge: maxAge,
cacheControl: strings.Join(directives, ","),
}
}
func NewImmutableCache(maxAge time.Duration) *Cache {
directives := []string{
"public",
"max-age=" + strconv.Itoa(int(maxAge.Seconds())),
"immutable",
}
return &Cache{
cacheControl: strings.Join(directives, ","),
}
}
func (middleware *Cache) Wrap(next http.Handler) http.Handler {
// Cache-Control: no-cache is equivalent to Cache-Control: max-age=0, must-revalidate as most HTTP/1.0 caches don't support no-cache directives
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
directives := []string{
"max-age=" + strconv.Itoa(int(middleware.maxAge.Seconds())),
"no-cache", // Note that no-cache does not mean "don't cache". no-cache allows caches to store a response but requires them to revalidate it before reuse.
"private", //If you forget to add private to a response with personalized content, then that response can be stored in a shared cache and end up being reused for multiple users, which can cause personal information to leak.
"must-revalidate", // HTTP allows caches to reuse stale responses when they are disconnected from the origin server. must-revalidate is a way to prevent this from happening - either the stored response is revalidated with the origin server or a 504 (Gateway Timeout) response is generated.
}
rw.Header().Set("Cache-Control", strings.Join(directives, ","))
rw.Header().Set("Cache-Control", middleware.cacheControl)
next.ServeHTTP(rw, req)
})
}

View File

@@ -3,6 +3,7 @@ package middleware
import (
"net"
"net/http"
"net/http/httptest"
"strconv"
"testing"
"time"
@@ -44,8 +45,8 @@ func TestCache(t *testing.T) {
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
req, err := http.NewRequest("GET", "http://"+listener.Addr().String(), nil)
require.NoError(t, err)
@@ -62,3 +63,25 @@ func TestCache(t *testing.T) {
})
}
}
func TestCacheControl(t *testing.T) {
t.Parallel()
testCases := []struct {
name string
cache *Cache
expected string
}{
{name: "NoCache", cache: NewCache(0), expected: "max-age=0,no-cache,private,must-revalidate"},
{name: "Immutable", cache: NewImmutableCache(365 * 24 * time.Hour), expected: "public,max-age=31536000,immutable"},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
rw := httptest.NewRecorder()
testCase.cache.Wrap(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})).ServeHTTP(rw, httptest.NewRequest(http.MethodGet, "/", nil))
assert.Equal(t, testCase.expected, rw.Header().Get("Cache-Control"))
})
}
}

View File

@@ -6,7 +6,10 @@ import (
"html/template"
"net/http"
"os"
"path"
"path/filepath"
"strings"
"time"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/factory"
@@ -16,6 +19,11 @@ import (
"github.com/gorilla/mux"
)
const (
assetsPathPrefix = "/assets/"
assetsMaxAge = 365 * 24 * time.Hour
)
type provider struct {
config web.Config
indexContents []byte
@@ -64,8 +72,18 @@ func New(ctx context.Context, settings factory.ProviderSettings, config web.Conf
}
func (provider *provider) AddToRouter(router *mux.Router) error {
assetsCache := middleware.NewImmutableCache(assetsMaxAge)
err := router.PathPrefix(assetsPathPrefix).
MatcherFunc(provider.matchAsset).
Handler(
assetsCache.Wrap(http.HandlerFunc(provider.ServeHTTP)),
).GetError()
if err != nil {
return errors.WrapInternalf(err, errors.CodeInternal, "unable to add web assets to router")
}
cache := middleware.NewCache(0)
err := router.PathPrefix("/").
err = router.PathPrefix("/").
Handler(
cache.Wrap(http.HandlerFunc(provider.ServeHTTP)),
).GetError()
@@ -78,10 +96,10 @@ func (provider *provider) AddToRouter(router *mux.Router) error {
func (provider *provider) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
// Join internally call path.Clean to prevent directory traversal
path := filepath.Join(provider.config.Directory, req.URL.Path)
filePath := filepath.Join(provider.config.Directory, req.URL.Path)
// check whether a file exists or is a directory at the given path
fi, err := os.Stat(path)
fi, err := os.Stat(filePath)
if err != nil {
// if the file doesn't exist, serve index.html
if os.IsNotExist(err) {
@@ -105,6 +123,28 @@ func (provider *provider) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
provider.fileHandler.ServeHTTP(rw, req)
}
// matchAsset matches files under /assets/, which are content-hashed, so their URL changes with their content.
func (provider *provider) matchAsset(req *http.Request, _ *mux.RouteMatch) bool {
// a non-canonical URL can name a file outside /assets/ or get a redirect
if req.URL.Path != path.Clean(req.URL.Path) {
return false
}
if !strings.HasPrefix(req.URL.Path, assetsPathPrefix) {
return false
}
filePath := filepath.Join(provider.config.Directory, req.URL.Path)
// a missing file or a directory serves index.html
fi, err := os.Stat(filePath)
if err != nil {
return false
}
return !fi.IsDir()
}
func (provider *provider) serveIndex(rw http.ResponseWriter) {
rw.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = rw.Write(provider.indexContents)

View File

@@ -6,6 +6,7 @@ import (
"io"
"net"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
@@ -251,3 +252,87 @@ func TestServeStaticFilesUnchanged(t *testing.T) {
assert.Equal(t, string(expected), httpGet(t, base+"/assets/style.css"))
}
func TestServeCacheControl(t *testing.T) {
t.Parallel()
directory := t.TempDir()
files := map[string]string{
"index.html": "<html>index</html>",
"assets/x.js": "console.log('x')",
"assets/nested/y.css": "body{}",
"assets-legacy/z.js": "console.log('z')",
"favicon.ico": "icon",
"css/uPlot.min.css": ".uplot{}",
"locales/en/main.json": "{}",
}
for name, content := range files {
require.NoError(t, os.MkdirAll(filepath.Join(directory, filepath.Dir(name)), 0o755))
require.NoError(t, os.WriteFile(filepath.Join(directory, name), []byte(content), 0o644))
}
testCases := []struct {
name string
basePath string
path string
expectedStatus int
expectedBody string
expectedCC string
}{
{name: "ExistingAsset_Immutable", path: "/assets/x.js", expectedBody: files["assets/x.js"], expectedCC: "public,max-age=31536000,immutable"},
{name: "ExistingNestedAsset_Immutable", path: "/assets/nested/y.css", expectedBody: files["assets/nested/y.css"], expectedCC: "public,max-age=31536000,immutable"},
{name: "MissingAsset_ServesIndex_NoCache", path: "/assets/missing-AAAA.js", expectedBody: files["index.html"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "AssetsDirectory_ServesIndex_NoCache", path: "/assets/nested/", expectedBody: files["index.html"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "Root_ServesIndex_NoCache", path: "/", expectedBody: files["index.html"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "UnknownRoute_ServesIndex_NoCache", path: "/does-not-exist", expectedBody: files["index.html"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "NonAssetFile_NoCache", path: "/favicon.ico", expectedBody: files["favicon.ico"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "NonAssetNestedFile_NoCache", path: "/css/uPlot.min.css", expectedBody: files["css/uPlot.min.css"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "LocaleFile_NoCache", path: "/locales/en/main.json", expectedBody: files["locales/en/main.json"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "AssetsPrefixLookalike_NoCache", path: "/assets-legacy/z.js", expectedBody: files["assets-legacy/z.js"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "BasePath_ExistingAsset_Immutable", basePath: "/signoz", path: "/assets/x.js", expectedBody: files["assets/x.js"], expectedCC: "public,max-age=31536000,immutable"},
{name: "BasePath_MissingAsset_ServesIndex_NoCache", basePath: "/signoz", path: "/assets/missing-AAAA.js", expectedBody: files["index.html"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "BasePath_NonAssetFile_NoCache", basePath: "/signoz", path: "/favicon.ico", expectedBody: files["favicon.ico"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "AssetTrailingSlash_Redirects_NoCache", path: "/assets/x.js/", expectedStatus: http.StatusMovedPermanently, expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "EncodedDotDotOutOfAssets_NoCache", path: "/assets/%2e%2e/locales/en/main.json", expectedBody: files["locales/en/main.json"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
{name: "BasePath_Root_ServesIndex_NoCache", basePath: "/signoz", path: "/", expectedBody: files["index.html"], expectedCC: "max-age=0,no-cache,private,must-revalidate"},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
routerWeb, err := New(
context.Background(),
factorytest.NewSettings(),
web.Config{Index: "index.html", Directory: directory},
global.Config{ExternalURL: &url.URL{Path: testCase.basePath}},
)
require.NoError(t, err)
router := mux.NewRouter().UseEncodedPath()
require.NoError(t, routerWeb.AddToRouter(router))
var handler http.Handler = router
if testCase.basePath != "" {
handler = http.StripPrefix(testCase.basePath, router)
}
server := httptest.NewServer(handler)
t.Cleanup(server.Close)
client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
res, err := client.Get(server.URL + testCase.basePath + testCase.path)
require.NoError(t, err)
defer func() { _ = res.Body.Close() }()
body, err := io.ReadAll(res.Body)
require.NoError(t, err)
expectedStatus := testCase.expectedStatus
if expectedStatus == 0 {
expectedStatus = http.StatusOK
}
assert.Equal(t, expectedStatus, res.StatusCode)
assert.Equal(t, testCase.expectedCC, res.Header.Get("Cache-Control"))
assert.Equal(t, testCase.expectedBody, string(body))
})
}
}

View File

@@ -17,10 +17,12 @@ def e2e_env() -> dict:
"""Environment every e2e SigNoz gets. Each Playwright worker logs in once,
and the default cap of 5 sessions per user evicts the oldest, which turns a
worker's requests into 401s mid-run. Metrics reduction is off by default in
pkg/flagger/registry.go and the Volume Control specs need it."""
pkg/flagger/registry.go and the Volume Control specs need it. On-the-fly gzip
is slow in the -race build, so compression is off."""
return {
"SIGNOZ_TOKENIZER_OPAQUE_TOKEN_MAX__PER__USER": 100,
"SIGNOZ_FLAGGER_CONFIG_BOOLEAN_ENABLE__METRICS__REDUCTION": True,
"SIGNOZ_APISERVER_COMPRESSION_ENABLED": False,
}