mirror of
https://github.com/SigNoz/signoz.git
synced 2026-11-24 09:10:42 +00:00
Compare commits
6 Commits
nv/exec-st
...
perf/web-p
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8caad10117 | ||
|
|
b8b05031d2 | ||
|
|
fc2d7b0bf8 | ||
|
|
18ab0c86b1 | ||
|
|
649c3a250c | ||
|
|
f7b1383427 |
@@ -165,6 +165,12 @@ apiserver:
|
||||
- /api/v1/health
|
||||
- /api/v1/version
|
||||
- /
|
||||
compression:
|
||||
# Gzip responses on the fly. Turn off when a proxy in front already compresses.
|
||||
# Web files shipped with a .gz twin are served precompressed either way.
|
||||
enabled: true
|
||||
# Gzip level, from 1 (fastest) to 9 (smallest), or -1 for the default.
|
||||
level: -1
|
||||
|
||||
##################### Querier #####################
|
||||
querier:
|
||||
|
||||
3
frontend/.gitignore
vendored
3
frontend/.gitignore
vendored
@@ -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
|
||||
|
||||
@@ -188,6 +188,15 @@ 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: {
|
||||
output: {
|
||||
entryFileNames: 'assets/[name]-[hash].js',
|
||||
chunkFileNames: 'assets/[name]-[hash].js',
|
||||
assetFileNames: 'assets/[name]-[hash].[ext]',
|
||||
},
|
||||
},
|
||||
},
|
||||
server: {
|
||||
open: true,
|
||||
|
||||
3
go.mod
3
go.mod
@@ -29,11 +29,11 @@ require (
|
||||
github.com/gojek/heimdall/v7 v7.0.3
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/gorilla/handlers v1.5.1
|
||||
github.com/gorilla/mux v1.8.1
|
||||
github.com/huandu/go-sqlbuilder v1.39.1
|
||||
github.com/jackc/pgx/v5 v5.9.2
|
||||
github.com/json-iterator/go v1.1.13-0.20220915233716-71ac16282d12
|
||||
github.com/klauspost/compress v1.19.2
|
||||
github.com/knadh/koanf v1.5.0
|
||||
github.com/knadh/koanf/v2 v2.3.3
|
||||
github.com/mailru/easyjson v0.9.0
|
||||
@@ -248,7 +248,6 @@ require (
|
||||
github.com/josharian/intern v1.0.0 // indirect
|
||||
github.com/jpillora/backoff v1.0.0 // indirect
|
||||
github.com/jtolds/gls v4.20.0+incompatible // indirect
|
||||
github.com/klauspost/compress v1.19.2 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
||||
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
|
||||
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
|
||||
|
||||
3
go.sum
3
go.sum
@@ -299,7 +299,6 @@ github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL
|
||||
github.com/fatih/color v1.10.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGEBuJM=
|
||||
github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk=
|
||||
github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M=
|
||||
github.com/felixge/httpsnoop v1.0.1/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
|
||||
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
|
||||
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
|
||||
github.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f h1:RJ+BDPLSHQO7cSjKBqjPJSbi1qfk9WcsjQDtZiw3dZw=
|
||||
@@ -537,8 +536,6 @@ github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8
|
||||
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
|
||||
github.com/gopherjs/gopherjs v1.17.2 h1:fQnZVsXk8uxXIStYb0N4bGk7jeyTalG/wsZjQ25dO0g=
|
||||
github.com/gopherjs/gopherjs v1.17.2/go.mod h1:pRRIvn/QzFLrKfvEz3qUuEhtE/zLCWfreZ6J5gM2i+k=
|
||||
github.com/gorilla/handlers v1.5.1 h1:9lRY6j8DEeeBT10CvO9hGW0gmky0BprnvDI5vfhUHH4=
|
||||
github.com/gorilla/handlers v1.5.1/go.mod h1:t8XrUpc4KVXb7HGyJ4/cEnwQiaxrX/hz1Zv/4g96P1Q=
|
||||
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
|
||||
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
|
||||
github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 h1:JeSE6pjso5THxAzdVpqr6/geYxZytqFMBCOtn/ujyeo=
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package apiserver
|
||||
|
||||
import (
|
||||
"compress/gzip"
|
||||
"time"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
@@ -11,8 +12,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 +31,13 @@ type Logging struct {
|
||||
ExcludedRoutes []string `mapstructure:"excluded_routes"`
|
||||
}
|
||||
|
||||
type Compression struct {
|
||||
// Whether to gzip responses on the fly. Precompressed web files are served either way
|
||||
Enabled bool `mapstructure:"enabled"`
|
||||
// The gzip level, from 1 (fastest) to 9 (smallest), or -1 for the default
|
||||
Level int `mapstructure:"level"`
|
||||
}
|
||||
|
||||
func NewConfigFactory() factory.ConfigFactory {
|
||||
return factory.NewConfigFactory(factory.MustNewName("apiserver"), newConfig)
|
||||
}
|
||||
@@ -55,6 +64,10 @@ func newConfig() factory.Config {
|
||||
"/",
|
||||
},
|
||||
},
|
||||
Compression: Compression{
|
||||
Enabled: true,
|
||||
Level: gzip.DefaultCompression,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,5 +80,9 @@ func (c Config) Validate() error {
|
||||
return errors.NewInvalidInputf(errors.CodeInvalidInput, "apiserver.address is required")
|
||||
}
|
||||
|
||||
if level := c.Compression.Level; level != gzip.DefaultCompression && (level < gzip.BestSpeed || level > gzip.BestCompression) {
|
||||
return errors.NewInvalidInputf(errors.CodeInvalidInput, "apiserver.compression.level must be -1 or between 1 and 9")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -68,7 +68,95 @@ func TestNewWithEnvProvider(t *testing.T) {
|
||||
"/api/v1/health1",
|
||||
},
|
||||
},
|
||||
Compression: Compression{
|
||||
Enabled: true,
|
||||
Level: -1,
|
||||
},
|
||||
}
|
||||
|
||||
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, Level: -1},
|
||||
},
|
||||
{
|
||||
name: "Disabled",
|
||||
env: map[string]string{"SIGNOZ_APISERVER_COMPRESSION_ENABLED": "false"},
|
||||
expected: Compression{Enabled: false, Level: -1},
|
||||
},
|
||||
{
|
||||
name: "Disabled_Capitalized",
|
||||
env: map[string]string{"SIGNOZ_APISERVER_COMPRESSION_ENABLED": "False"},
|
||||
expected: Compression{Enabled: false, Level: -1},
|
||||
},
|
||||
{
|
||||
name: "Enabled_Level",
|
||||
env: map[string]string{"SIGNOZ_APISERVER_COMPRESSION_ENABLED": "true", "SIGNOZ_APISERVER_COMPRESSION_LEVEL": "9"},
|
||||
expected: Compression{Enabled: true, Level: 9},
|
||||
},
|
||||
}
|
||||
|
||||
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)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateCompressionLevel(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
level int
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "Default", level: -1, wantErr: false},
|
||||
{name: "BestSpeed", level: 1, wantErr: false},
|
||||
{name: "BestCompression", level: 9, wantErr: false},
|
||||
{name: "Zero", level: 0, wantErr: true},
|
||||
{name: "AboveBestCompression", level: 10, wantErr: true},
|
||||
{name: "BelowDefault", level: -2, wantErr: true},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
conf := NewConfigFactory().New().(*Config)
|
||||
conf.Compression.Level = testCase.level
|
||||
|
||||
err := conf.Validate()
|
||||
if testCase.wantErr {
|
||||
assert.ErrorContains(t, err, "apiserver.compression.level")
|
||||
return
|
||||
}
|
||||
assert.NoError(t, err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -338,7 +338,11 @@ func newProvider(
|
||||
}
|
||||
|
||||
httpHandler := middleware.NewCors().Wrap(router)
|
||||
httpHandler = middleware.NewCompress().Wrap(httpHandler)
|
||||
compress, err := middleware.NewCompress(config.Compression.Enabled, config.Compression.Level)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
httpHandler = compress.Wrap(httpHandler)
|
||||
|
||||
routePrefix := globalConfig.ExternalPath()
|
||||
if routePrefix != "" {
|
||||
|
||||
@@ -2,16 +2,77 @@ package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
gorillahandlers "github.com/gorilla/handlers"
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/klauspost/compress/gzhttp"
|
||||
)
|
||||
|
||||
type Compress struct{}
|
||||
type Compress struct {
|
||||
wrap func(http.Handler) http.HandlerFunc
|
||||
}
|
||||
|
||||
func NewCompress() *Compress {
|
||||
return &Compress{}
|
||||
// NewCompress gzips responses on the fly at the given compress/gzip level, and
|
||||
// passes them through untouched when disabled. Responses that already carry a
|
||||
// Content-Encoding or a Content-Range, and bodies under 1 KiB, are left as they are.
|
||||
func NewCompress(enabled bool, level int) (*Compress, error) {
|
||||
if !enabled {
|
||||
return &Compress{}, nil
|
||||
}
|
||||
|
||||
wrap, err := gzhttp.NewWrapper(
|
||||
gzhttp.CompressionLevel(level),
|
||||
gzhttp.EnableZstd(false),
|
||||
gzhttp.ContentTypeFilter(compressibleContentType),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, errors.WrapInternalf(err, errors.CodeInternal, "cannot create compress middleware")
|
||||
}
|
||||
|
||||
return &Compress{wrap: wrap}, nil
|
||||
}
|
||||
|
||||
func (middleware *Compress) Wrap(next http.Handler) http.Handler {
|
||||
return gorillahandlers.CompressHandler(next)
|
||||
if middleware.wrap == nil {
|
||||
return next
|
||||
}
|
||||
|
||||
compressed := middleware.wrap(next)
|
||||
|
||||
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
|
||||
// gzhttp sends no headers until the first body byte, which stalls event streams.
|
||||
if acceptsEventStream(req) {
|
||||
next.ServeHTTP(rw, req)
|
||||
return
|
||||
}
|
||||
|
||||
compressed.ServeHTTP(rw, req)
|
||||
})
|
||||
}
|
||||
|
||||
func acceptsEventStream(req *http.Request) bool {
|
||||
for _, accept := range req.Header.Values("Accept") {
|
||||
for _, mediaRange := range strings.Split(accept, ",") {
|
||||
mediaType, _, _ := strings.Cut(mediaRange, ";")
|
||||
if strings.EqualFold(strings.TrimSpace(mediaType), "text/event-stream") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// Raster images and woff fonts are already compressed and gain nothing from gzip.
|
||||
func compressibleContentType(contentType string) bool {
|
||||
if !gzhttp.DefaultContentTypeFilter(contentType) {
|
||||
return false
|
||||
}
|
||||
|
||||
contentType = strings.ToLower(contentType)
|
||||
if strings.HasPrefix(contentType, "image/") {
|
||||
return strings.HasPrefix(contentType, "image/svg") || strings.HasPrefix(contentType, "image/x-icon") || strings.HasPrefix(contentType, "image/vnd.microsoft.icon")
|
||||
}
|
||||
|
||||
return !strings.HasPrefix(contentType, "font/woff")
|
||||
}
|
||||
|
||||
391
pkg/http/middleware/compress_test.go
Normal file
391
pkg/http/middleware/compress_test.go
Normal file
@@ -0,0 +1,391 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func gzipPayload(t *testing.T, payload []byte) []byte {
|
||||
t.Helper()
|
||||
|
||||
var buf bytes.Buffer
|
||||
writer := gzip.NewWriter(&buf)
|
||||
_, err := writer.Write(payload)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, writer.Close())
|
||||
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
func gunzipLayers(t *testing.T, body []byte) (int, []byte) {
|
||||
t.Helper()
|
||||
|
||||
layers := 0
|
||||
for len(body) > 2 && body[0] == 0x1f && body[1] == 0x8b {
|
||||
reader, err := gzip.NewReader(bytes.NewReader(body))
|
||||
require.NoError(t, err)
|
||||
body, err = io.ReadAll(reader)
|
||||
require.NoError(t, err)
|
||||
layers++
|
||||
}
|
||||
|
||||
return layers, body
|
||||
}
|
||||
|
||||
func newCompressClient() *http.Client {
|
||||
return &http.Client{Transport: &http.Transport{DisableCompression: true}}
|
||||
}
|
||||
|
||||
func TestCompress(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
large := []byte(strings.Repeat(`{"status":"ok","value":12345}`, 200))
|
||||
small := []byte(`{"status":"ok"}`)
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
disabled bool
|
||||
accept string
|
||||
acceptEncoding string
|
||||
contentType string
|
||||
contentRange string
|
||||
status int
|
||||
payload []byte
|
||||
encoded bool
|
||||
wantEncoding string
|
||||
wantLayers int
|
||||
}{
|
||||
{
|
||||
name: "JSON_AcceptsGzip_Compressed",
|
||||
acceptEncoding: "gzip",
|
||||
contentType: "application/json",
|
||||
status: http.StatusOK,
|
||||
payload: large,
|
||||
wantEncoding: "gzip",
|
||||
wantLayers: 1,
|
||||
},
|
||||
{
|
||||
name: "JSON_NoAcceptEncoding_Plain",
|
||||
contentType: "application/json",
|
||||
status: http.StatusOK,
|
||||
payload: large,
|
||||
wantEncoding: "",
|
||||
wantLayers: 0,
|
||||
},
|
||||
{
|
||||
name: "JSON_Small_Plain",
|
||||
acceptEncoding: "gzip",
|
||||
contentType: "application/json",
|
||||
status: http.StatusOK,
|
||||
payload: small,
|
||||
wantEncoding: "",
|
||||
wantLayers: 0,
|
||||
},
|
||||
{
|
||||
name: "AlreadyEncoded_NotCompressedAgain",
|
||||
acceptEncoding: "gzip",
|
||||
contentType: "text/javascript",
|
||||
status: http.StatusOK,
|
||||
payload: large,
|
||||
encoded: true,
|
||||
wantEncoding: "gzip",
|
||||
wantLayers: 1,
|
||||
},
|
||||
{
|
||||
name: "PNG_Plain",
|
||||
acceptEncoding: "gzip",
|
||||
contentType: "image/png",
|
||||
status: http.StatusOK,
|
||||
payload: large,
|
||||
wantEncoding: "",
|
||||
wantLayers: 0,
|
||||
},
|
||||
{
|
||||
name: "WOFF2_Plain",
|
||||
acceptEncoding: "gzip",
|
||||
contentType: "font/woff2",
|
||||
status: http.StatusOK,
|
||||
payload: large,
|
||||
wantEncoding: "",
|
||||
wantLayers: 0,
|
||||
},
|
||||
{
|
||||
name: "SVG_Compressed",
|
||||
acceptEncoding: "gzip",
|
||||
contentType: "image/svg+xml",
|
||||
status: http.StatusOK,
|
||||
payload: large,
|
||||
wantEncoding: "gzip",
|
||||
wantLayers: 1,
|
||||
},
|
||||
{
|
||||
name: "JSON_AcceptsJSON_Compressed",
|
||||
accept: "application/json, text/plain, */*",
|
||||
acceptEncoding: "gzip",
|
||||
contentType: "application/json",
|
||||
status: http.StatusOK,
|
||||
payload: large,
|
||||
wantEncoding: "gzip",
|
||||
wantLayers: 1,
|
||||
},
|
||||
{
|
||||
name: "EventStream_AcceptsEventStream_Plain",
|
||||
accept: "text/event-stream",
|
||||
acceptEncoding: "gzip",
|
||||
contentType: "text/event-stream",
|
||||
status: http.StatusOK,
|
||||
payload: large,
|
||||
wantEncoding: "",
|
||||
wantLayers: 0,
|
||||
},
|
||||
{
|
||||
name: "Disabled_AcceptsGzip_Plain",
|
||||
disabled: true,
|
||||
acceptEncoding: "gzip",
|
||||
contentType: "application/json",
|
||||
status: http.StatusOK,
|
||||
payload: large,
|
||||
wantEncoding: "",
|
||||
wantLayers: 0,
|
||||
},
|
||||
{
|
||||
name: "Disabled_AlreadyEncoded_Untouched",
|
||||
disabled: true,
|
||||
acceptEncoding: "gzip",
|
||||
contentType: "text/javascript",
|
||||
status: http.StatusOK,
|
||||
payload: large,
|
||||
encoded: true,
|
||||
wantEncoding: "gzip",
|
||||
wantLayers: 1,
|
||||
},
|
||||
{
|
||||
name: "PartialContent_Plain",
|
||||
acceptEncoding: "gzip",
|
||||
contentType: "application/json",
|
||||
contentRange: "bytes 0-5999/9000",
|
||||
status: http.StatusPartialContent,
|
||||
payload: large,
|
||||
wantEncoding: "",
|
||||
wantLayers: 0,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
compress, err := NewCompress(!testCase.disabled, gzip.DefaultCompression)
|
||||
require.NoError(t, err)
|
||||
|
||||
wire := testCase.payload
|
||||
if testCase.encoded {
|
||||
wire = gzipPayload(t, testCase.payload)
|
||||
}
|
||||
|
||||
seen := make(chan string, 1)
|
||||
server := httptest.NewServer(compress.Wrap(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
|
||||
seen <- req.Header.Get("Accept-Encoding")
|
||||
rw.Header().Set("Content-Type", testCase.contentType)
|
||||
if testCase.encoded {
|
||||
rw.Header().Set("Content-Encoding", "gzip")
|
||||
}
|
||||
if testCase.contentRange != "" {
|
||||
rw.Header().Set("Content-Range", testCase.contentRange)
|
||||
}
|
||||
rw.WriteHeader(testCase.status)
|
||||
_, _ = rw.Write(wire)
|
||||
})))
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
req, err := http.NewRequest(http.MethodGet, server.URL, nil)
|
||||
require.NoError(t, err)
|
||||
if testCase.accept != "" {
|
||||
req.Header.Set("Accept", testCase.accept)
|
||||
}
|
||||
if testCase.acceptEncoding != "" {
|
||||
req.Header.Set("Accept-Encoding", testCase.acceptEncoding)
|
||||
}
|
||||
|
||||
res, err := newCompressClient().Do(req)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = res.Body.Close() }()
|
||||
|
||||
body, err := io.ReadAll(res.Body)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, testCase.status, res.StatusCode)
|
||||
assert.Equal(t, testCase.wantEncoding, res.Header.Get("Content-Encoding"))
|
||||
assert.Equal(t, testCase.acceptEncoding, <-seen)
|
||||
|
||||
layers, plain := gunzipLayers(t, body)
|
||||
assert.Equal(t, testCase.wantLayers, layers)
|
||||
assert.Equal(t, testCase.payload, plain)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompressFlushesStream(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
compress, err := NewCompress(true, gzip.DefaultCompression)
|
||||
require.NoError(t, err)
|
||||
|
||||
release := make(chan struct{})
|
||||
server := httptest.NewServer(compress.Wrap(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
|
||||
rw.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = rw.Write([]byte("data: first\n\n"))
|
||||
rw.(http.Flusher).Flush()
|
||||
|
||||
select {
|
||||
case <-release:
|
||||
case <-req.Context().Done():
|
||||
return
|
||||
}
|
||||
|
||||
_, _ = rw.Write([]byte("data: second\n\n"))
|
||||
})))
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
req, err := http.NewRequest(http.MethodGet, server.URL, nil)
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Accept-Encoding", "gzip")
|
||||
|
||||
res, err := newCompressClient().Do(req)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = res.Body.Close() }()
|
||||
require.Equal(t, "gzip", res.Header.Get("Content-Encoding"))
|
||||
|
||||
reader, err := gzip.NewReader(res.Body)
|
||||
require.NoError(t, err)
|
||||
lines := bufio.NewReader(reader)
|
||||
|
||||
first := make(chan string, 1)
|
||||
go func() {
|
||||
line, _ := lines.ReadString('\n')
|
||||
first <- line
|
||||
}()
|
||||
|
||||
select {
|
||||
case line := <-first:
|
||||
assert.Equal(t, "data: first\n", line)
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("first event was not flushed before the handler finished")
|
||||
}
|
||||
|
||||
close(release)
|
||||
rest, err := io.ReadAll(lines)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "\ndata: second\n\n", string(rest))
|
||||
}
|
||||
|
||||
func TestCompressEventStreamSendsHeaders(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
accept string
|
||||
}{
|
||||
{name: "Exact", accept: "text/event-stream"},
|
||||
{name: "MixedCase", accept: "Text/Event-Stream"},
|
||||
{name: "WithParams", accept: "text/event-stream;q=0.9"},
|
||||
{name: "InList_WildcardLast", accept: "text/event-stream, */*;q=0.1"},
|
||||
{name: "InList_WildcardFirst", accept: "application/json, */*;q=0.5 , text/event-stream"},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
compress, err := NewCompress(true, gzip.DefaultCompression)
|
||||
require.NoError(t, err)
|
||||
|
||||
release := make(chan struct{})
|
||||
server := httptest.NewServer(compress.Wrap(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
|
||||
rw.Header().Set("Content-Type", "text/event-stream")
|
||||
rw.WriteHeader(http.StatusOK)
|
||||
rw.(http.Flusher).Flush()
|
||||
|
||||
select {
|
||||
case <-release:
|
||||
case <-req.Context().Done():
|
||||
}
|
||||
})))
|
||||
t.Cleanup(server.Close)
|
||||
t.Cleanup(func() { close(release) })
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, server.URL, nil)
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Accept", testCase.accept)
|
||||
req.Header.Set("Accept-Encoding", "gzip")
|
||||
|
||||
res, err := newCompressClient().Do(req)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = res.Body.Close() }()
|
||||
|
||||
assert.Equal(t, http.StatusOK, res.StatusCode)
|
||||
assert.Equal(t, "text/event-stream", res.Header.Get("Content-Type"))
|
||||
assert.Empty(t, res.Header.Get("Content-Encoding"))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewCompressLevel(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var payload strings.Builder
|
||||
for i := range 4000 {
|
||||
fmt.Fprintf(&payload, `{"id":%d,"name":"service-%d","latency":%d}`, i*7919%10007, i%97, i*104729%1009)
|
||||
}
|
||||
|
||||
size := func(t *testing.T, level int) int {
|
||||
compress, err := NewCompress(true, level)
|
||||
require.NoError(t, err)
|
||||
|
||||
server := httptest.NewServer(compress.Wrap(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) {
|
||||
rw.Header().Set("Content-Type", "application/json")
|
||||
_, _ = rw.Write([]byte(payload.String()))
|
||||
})))
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
req, err := http.NewRequest(http.MethodGet, server.URL, nil)
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Accept-Encoding", "gzip")
|
||||
|
||||
res, err := newCompressClient().Do(req)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = res.Body.Close() }()
|
||||
|
||||
body, err := io.ReadAll(res.Body)
|
||||
require.NoError(t, err)
|
||||
|
||||
return len(body)
|
||||
}
|
||||
|
||||
assert.Less(t, size(t, gzip.BestCompression), size(t, gzip.BestSpeed))
|
||||
}
|
||||
|
||||
func TestNewCompressInvalidLevel(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
_, err := NewCompress(true, 10)
|
||||
assert.Error(t, err)
|
||||
|
||||
_, err = NewCompress(false, 10)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
@@ -26,9 +26,8 @@ const bucketCacheCellSteps = 60
|
||||
type BucketCache interface {
|
||||
// cached portion + list of gaps to fetch
|
||||
GetMissRanges(ctx context.Context, orgID valuer.UUID, q qbtypes.Query, step qbtypes.Step) (cached *qbtypes.Result, missing []*qbtypes.TimeRange)
|
||||
// store fresh buckets for future hits; only the ranges in the map were
|
||||
// queried for fresh, the rest of it came from the cache
|
||||
Put(ctx context.Context, orgID valuer.UUID, q qbtypes.Query, step qbtypes.Step, fresh *qbtypes.Result, execStatsForQueriedTimeRanges map[qbtypes.TimeRange]qbtypes.ExecStats)
|
||||
// store fresh buckets for future hits
|
||||
Put(ctx context.Context, orgID valuer.UUID, q qbtypes.Query, step qbtypes.Step, fresh *qbtypes.Result)
|
||||
}
|
||||
|
||||
// bucketCache implements the BucketCache interface.
|
||||
@@ -117,7 +116,7 @@ func (bc *bucketCache) GetMissRanges(
|
||||
}
|
||||
|
||||
// Merge buckets into a single result
|
||||
mergedResult := bc.mergeBuckets(ctx, relevantBuckets, cachedWarnings, startMs, endMs)
|
||||
mergedResult := bc.mergeBuckets(ctx, relevantBuckets, cachedWarnings)
|
||||
|
||||
// Filter the merged result to only include values within the requested time range
|
||||
mergedResult = bc.filterResultToTimeRange(mergedResult, q, startMs, endMs, stepMs)
|
||||
@@ -126,7 +125,7 @@ func (bc *bucketCache) GetMissRanges(
|
||||
}
|
||||
|
||||
// Put stores fresh query results in the cache.
|
||||
func (bc *bucketCache) Put(ctx context.Context, orgID valuer.UUID, q qbtypes.Query, step qbtypes.Step, fresh *qbtypes.Result, execStatsForQueriedTimeRanges map[qbtypes.TimeRange]qbtypes.ExecStats) {
|
||||
func (bc *bucketCache) Put(ctx context.Context, orgID valuer.UUID, q qbtypes.Query, step qbtypes.Step, fresh *qbtypes.Result) {
|
||||
// Get query window
|
||||
startMs, endMs := q.Window()
|
||||
|
||||
@@ -189,7 +188,7 @@ func (bc *bucketCache) Put(ctx context.Context, orgID valuer.UUID, q qbtypes.Que
|
||||
|
||||
// Convert trimmed result to buckets, one per grid cell it spans
|
||||
cellWidthMs := bucketCacheCellSteps * stepMs
|
||||
freshBuckets := bc.resultToBuckets(ctx, trimmedResult, cachableStartMs, cachableEndMs, cellWidthMs, execStatsForQueriedTimeRanges)
|
||||
freshBuckets := bc.resultToBuckets(ctx, trimmedResult, cachableStartMs, cachableEndMs, cellWidthMs)
|
||||
|
||||
cellKeys := make([]string, len(freshBuckets))
|
||||
cellEntries := make([]cachetypes.Cacheable, len(freshBuckets))
|
||||
@@ -211,7 +210,7 @@ func (bc *bucketCache) Put(ctx context.Context, orgID valuer.UUID, q qbtypes.Que
|
||||
cellEntry = cellEntries[i].(*qbtypes.CachedData)
|
||||
}
|
||||
|
||||
cellBuckets, changed := bc.mergeFreshBucketIntoCell(ctx, cellEntry.Buckets, freshBucket, execStatsForQueriedTimeRanges)
|
||||
cellBuckets, changed := bc.mergeFreshBucketIntoCell(ctx, cellEntry.Buckets, freshBucket)
|
||||
if !changed {
|
||||
continue
|
||||
}
|
||||
@@ -464,7 +463,7 @@ func (bc *bucketCache) filterRelevantBuckets(buckets []*qbtypes.CachedBucket, st
|
||||
}
|
||||
|
||||
// mergeBuckets combines multiple cached buckets into a single result.
|
||||
func (bc *bucketCache) mergeBuckets(ctx context.Context, buckets []*qbtypes.CachedBucket, warnings []string, startMs, endMs uint64) *qbtypes.Result {
|
||||
func (bc *bucketCache) mergeBuckets(ctx context.Context, buckets []*qbtypes.CachedBucket, warnings []string) *qbtypes.Result {
|
||||
if len(buckets) == 0 {
|
||||
return &qbtypes.Result{}
|
||||
}
|
||||
@@ -472,13 +471,12 @@ func (bc *bucketCache) mergeBuckets(ctx context.Context, buckets []*qbtypes.Cach
|
||||
// All buckets should have the same type
|
||||
resultType := buckets[0].Type
|
||||
|
||||
// A bucket can reach past the window; only the part inside it is served
|
||||
// Aggregate stats
|
||||
var totalStats qbtypes.ExecStats
|
||||
for _, bucket := range buckets {
|
||||
servedStats := bucket.ProrateStatsToWindow(startMs, endMs)
|
||||
totalStats.RowsScanned += servedStats.RowsScanned
|
||||
totalStats.BytesScanned += servedStats.BytesScanned
|
||||
totalStats.DurationMS += servedStats.DurationMS
|
||||
totalStats.RowsScanned += bucket.Stats.RowsScanned
|
||||
totalStats.BytesScanned += bucket.Stats.BytesScanned
|
||||
totalStats.DurationMS += bucket.Stats.DurationMS
|
||||
}
|
||||
|
||||
// Merge values based on type
|
||||
@@ -675,7 +673,7 @@ func (bc *bucketCache) isEmptyResult(result *qbtypes.Result) (isEmpty bool, isFi
|
||||
}
|
||||
|
||||
// resultToBuckets converts a query result into time-based buckets.
|
||||
func (bc *bucketCache) resultToBuckets(ctx context.Context, result *qbtypes.Result, startMs, endMs, cellWidthMs uint64, execStatsForQueriedTimeRanges map[qbtypes.TimeRange]qbtypes.ExecStats) []*qbtypes.CachedBucket {
|
||||
func (bc *bucketCache) resultToBuckets(ctx context.Context, result *qbtypes.Result, startMs, endMs, cellWidthMs uint64) []*qbtypes.CachedBucket {
|
||||
// Check if result is empty
|
||||
isEmpty, isFiltered := bc.isEmptyResult(result)
|
||||
|
||||
@@ -687,7 +685,7 @@ func (bc *bucketCache) resultToBuckets(ctx context.Context, result *qbtypes.Resu
|
||||
}
|
||||
|
||||
// Empty filtered results still become buckets, so the range is not re-queried
|
||||
perCellBuckets, err := result.SplitIntoCacheCellBuckets(startMs, endMs, cellWidthMs, execStatsForQueriedTimeRanges)
|
||||
perCellBuckets, err := result.SplitIntoCacheCellBuckets(startMs, endMs, cellWidthMs)
|
||||
if err != nil {
|
||||
bc.logger.ErrorContext(ctx, "failed to convert result to buckets", errors.Attr(err))
|
||||
return nil
|
||||
@@ -699,7 +697,7 @@ func (bc *bucketCache) resultToBuckets(ctx context.Context, result *qbtypes.Resu
|
||||
// and reports whether the cell changed: a bucket already covering the fresh
|
||||
// one leaves it as is, buckets inside the fresh one are replaced, buckets
|
||||
// overlapping or edge to edge with it are unioned, and the rest are kept apart.
|
||||
func (bc *bucketCache) mergeFreshBucketIntoCell(ctx context.Context, cellBuckets []*qbtypes.CachedBucket, freshBucket *qbtypes.CachedBucket, execStatsForQueriedTimeRanges map[qbtypes.TimeRange]qbtypes.ExecStats) ([]*qbtypes.CachedBucket, bool) {
|
||||
func (bc *bucketCache) mergeFreshBucketIntoCell(ctx context.Context, cellBuckets []*qbtypes.CachedBucket, freshBucket *qbtypes.CachedBucket) ([]*qbtypes.CachedBucket, bool) {
|
||||
keptBuckets := make([]*qbtypes.CachedBucket, 0, len(cellBuckets)+1)
|
||||
touchingBuckets := []*qbtypes.CachedBucket{}
|
||||
for _, cellBucket := range cellBuckets {
|
||||
@@ -712,7 +710,7 @@ func (bc *bucketCache) mergeFreshBucketIntoCell(ctx context.Context, cellBuckets
|
||||
keptBuckets = append(keptBuckets, cellBucket)
|
||||
}
|
||||
}
|
||||
keptBuckets = append(keptBuckets, bc.unionBuckets(ctx, freshBucket, touchingBuckets, execStatsForQueriedTimeRanges))
|
||||
keptBuckets = append(keptBuckets, bc.unionBuckets(ctx, freshBucket, touchingBuckets))
|
||||
|
||||
slices.SortFunc(keptBuckets, func(a, b *qbtypes.CachedBucket) int {
|
||||
return cmp.Compare(a.StartMs, b.StartMs)
|
||||
@@ -723,16 +721,7 @@ func (bc *bucketCache) mergeFreshBucketIntoCell(ctx context.Context, cellBuckets
|
||||
// unionBuckets widens the fresh bucket by the buckets it touches. Buckets
|
||||
// inside it are replaced outright, so only a genuine partial overlap decodes
|
||||
// anything.
|
||||
func (bc *bucketCache) unionBuckets(ctx context.Context, freshBucket *qbtypes.CachedBucket, touchingBuckets []*qbtypes.CachedBucket, execStatsForQueriedTimeRanges map[qbtypes.TimeRange]qbtypes.ExecStats) *qbtypes.CachedBucket {
|
||||
// Data queried again takes the new query's cost, which the fresh bucket
|
||||
// carries; a touching bucket keeps its cost only for what was not queried again
|
||||
for _, touchingBucket := range touchingBuckets {
|
||||
keptStats := touchingBucket.ProrateStatsToUnqueried(execStatsForQueriedTimeRanges)
|
||||
freshBucket.Stats.RowsScanned += keptStats.RowsScanned
|
||||
freshBucket.Stats.BytesScanned += keptStats.BytesScanned
|
||||
freshBucket.Stats.DurationMS += keptStats.DurationMS
|
||||
}
|
||||
|
||||
func (bc *bucketCache) unionBuckets(ctx context.Context, freshBucket *qbtypes.CachedBucket, touchingBuckets []*qbtypes.CachedBucket) *qbtypes.CachedBucket {
|
||||
bucketsToMerge := []*qbtypes.CachedBucket{freshBucket}
|
||||
for _, touchingBucket := range touchingBuckets {
|
||||
if !freshBucket.Contains(touchingBucket) {
|
||||
@@ -753,11 +742,14 @@ func (bc *bucketCache) unionBuckets(ctx context.Context, freshBucket *qbtypes.Ca
|
||||
EndMs: freshBucket.EndMs,
|
||||
Type: freshBucket.Type,
|
||||
Value: value,
|
||||
Stats: freshBucket.Stats,
|
||||
Stats: qbtypes.ExecStats{StepIntervals: freshBucket.Stats.StepIntervals},
|
||||
}
|
||||
for _, mergedBucket := range bucketsToMerge {
|
||||
unionBucket.StartMs = min(unionBucket.StartMs, mergedBucket.StartMs)
|
||||
unionBucket.EndMs = max(unionBucket.EndMs, mergedBucket.EndMs)
|
||||
unionBucket.Stats.RowsScanned += mergedBucket.Stats.RowsScanned
|
||||
unionBucket.Stats.BytesScanned += mergedBucket.Stats.BytesScanned
|
||||
unionBucket.Stats.DurationMS += mergedBucket.Stats.DurationMS
|
||||
}
|
||||
return unionBucket
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ func BenchmarkBucketCache_GetMissRanges(b *testing.B) {
|
||||
endMs: uint64((i + 1) * 10000),
|
||||
}
|
||||
result := createBenchmarkResult(query.startMs, query.endMs, 1000)
|
||||
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, map[qbtypes.TimeRange]qbtypes.ExecStats{{From: query.startMs, To: query.endMs}: result.Stats})
|
||||
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
|
||||
}
|
||||
|
||||
// Create test queries with varying cache hit patterns
|
||||
@@ -121,7 +121,7 @@ func BenchmarkBucketCache_Put(b *testing.B) {
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
for j := 0; j < tc.numQueries; j++ {
|
||||
bc.Put(ctx, orgID, queries[j], qbtypes.Step{Duration: 1000 * time.Millisecond}, results[j], map[qbtypes.TimeRange]qbtypes.ExecStats{{From: queries[j].startMs, To: queries[j].endMs}: results[j].Stats})
|
||||
bc.Put(ctx, orgID, queries[j], qbtypes.Step{Duration: 1000 * time.Millisecond}, results[j])
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -259,7 +259,7 @@ func BenchmarkBucketCache_ConcurrentOperations(b *testing.B) {
|
||||
endMs: uint64((i + 1) * 10000),
|
||||
}
|
||||
result := createBenchmarkResult(query.startMs, query.endMs, 1000)
|
||||
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, map[qbtypes.TimeRange]qbtypes.ExecStats{{From: query.startMs, To: query.endMs}: result.Stats})
|
||||
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
|
||||
}
|
||||
|
||||
b.ResetTimer()
|
||||
@@ -284,7 +284,7 @@ func BenchmarkBucketCache_ConcurrentOperations(b *testing.B) {
|
||||
endMs: uint64((i + 1) * 10000),
|
||||
}
|
||||
result := createBenchmarkResult(query.startMs, query.endMs, 1000)
|
||||
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, map[qbtypes.TimeRange]qbtypes.ExecStats{{From: query.startMs, To: query.endMs}: result.Stats})
|
||||
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
|
||||
case 2: // Partial read
|
||||
query := &mockQuery{
|
||||
fingerprint: fmt.Sprintf("concurrent-query-%d", i%100),
|
||||
|
||||
@@ -59,7 +59,7 @@ func TestBucketCacheStepAlignment(t *testing.T) {
|
||||
}
|
||||
|
||||
// Put result in cache
|
||||
bc.Put(ctx, orgID, query, step, result, nil)
|
||||
bc.Put(ctx, orgID, query, step, result)
|
||||
|
||||
// Get cached data
|
||||
cached, missing := bc.GetMissRanges(ctx, orgID, query, step)
|
||||
@@ -109,7 +109,7 @@ func TestBucketCacheNoStepInterval(t *testing.T) {
|
||||
}
|
||||
|
||||
// Should cache the entire range when step is 0
|
||||
bc.Put(ctx, orgID, query, step, result, nil)
|
||||
bc.Put(ctx, orgID, query, step, result)
|
||||
|
||||
cached, missing := bc.GetMissRanges(ctx, orgID, query, step)
|
||||
assert.NotNil(t, cached)
|
||||
|
||||
@@ -156,7 +156,7 @@ func TestBucketCache_Put_And_Get(t *testing.T) {
|
||||
}
|
||||
|
||||
// Store in cache
|
||||
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, map[qbtypes.TimeRange]qbtypes.ExecStats{{From: query.startMs, To: query.endMs}: result.Stats})
|
||||
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
|
||||
|
||||
// Wait a bit for cache to be written
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
@@ -189,7 +189,7 @@ func TestBucketCache_PartialHit(t *testing.T) {
|
||||
Type: qbtypes.RequestTypeTimeSeries,
|
||||
Value: createTestTimeSeries("A", 1000, 3000, 1000),
|
||||
}
|
||||
bc.Put(context.Background(), valuer.UUID{}, query1, qbtypes.Step{Duration: 1000 * time.Millisecond}, result1, nil)
|
||||
bc.Put(context.Background(), valuer.UUID{}, query1, qbtypes.Step{Duration: 1000 * time.Millisecond}, result1)
|
||||
|
||||
// Wait for cache write
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
@@ -225,7 +225,7 @@ func TestBucketCache_MultipleBuckets(t *testing.T) {
|
||||
bc.Put(context.Background(), valuer.UUID{}, query1, qbtypes.Step{Duration: 100 * time.Millisecond}, &qbtypes.Result{
|
||||
Type: qbtypes.RequestTypeTimeSeries,
|
||||
Value: createTestTimeSeries("A", 1000, 2000, 100),
|
||||
}, nil)
|
||||
})
|
||||
|
||||
query2 := &mockQuery{
|
||||
fingerprint: "test-query",
|
||||
@@ -235,7 +235,7 @@ func TestBucketCache_MultipleBuckets(t *testing.T) {
|
||||
bc.Put(context.Background(), valuer.UUID{}, query2, qbtypes.Step{Duration: 100 * time.Millisecond}, &qbtypes.Result{
|
||||
Type: qbtypes.RequestTypeTimeSeries,
|
||||
Value: createTestTimeSeries("A", 3000, 4000, 100),
|
||||
}, nil)
|
||||
})
|
||||
|
||||
// Wait for cache writes
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
@@ -280,7 +280,7 @@ func TestBucketCache_FluxInterval(t *testing.T) {
|
||||
}
|
||||
|
||||
// This should not be cached due to flux interval
|
||||
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
|
||||
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
|
||||
|
||||
// Wait a bit
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
@@ -358,7 +358,7 @@ func TestBucketCache_MergeTimeSeriesResults(t *testing.T) {
|
||||
{Series: []*qbtypes.TimeSeries{series1}},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
// Cache second part
|
||||
query2 := &mockQuery{
|
||||
@@ -374,7 +374,7 @@ func TestBucketCache_MergeTimeSeriesResults(t *testing.T) {
|
||||
{Series: []*qbtypes.TimeSeries{series2}},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
// Wait for cache writes
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
@@ -441,7 +441,7 @@ func TestBucketCache_RawData(t *testing.T) {
|
||||
Value: rawData,
|
||||
}
|
||||
|
||||
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
|
||||
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
cached, missing := bc.GetMissRanges(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond})
|
||||
@@ -481,7 +481,7 @@ func TestBucketCache_ScalarData(t *testing.T) {
|
||||
Value: scalarData,
|
||||
}
|
||||
|
||||
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
|
||||
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
cached, missing := bc.GetMissRanges(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond})
|
||||
@@ -509,7 +509,7 @@ func TestBucketCache_EmptyFingerprint(t *testing.T) {
|
||||
Value: createTestTimeSeries("A", 1000, 5000, 1000),
|
||||
}
|
||||
|
||||
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
|
||||
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
// Should still be able to retrieve
|
||||
@@ -564,7 +564,7 @@ func TestBucketCache_ConcurrentAccess(t *testing.T) {
|
||||
Type: qbtypes.RequestTypeTimeSeries,
|
||||
Value: createTestTimeSeries(fmt.Sprintf("Q%d", id), query.startMs, query.endMs, 100),
|
||||
}
|
||||
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 100 * time.Microsecond}, result, nil)
|
||||
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 100 * time.Microsecond}, result)
|
||||
done <- true
|
||||
}(i)
|
||||
}
|
||||
@@ -624,7 +624,7 @@ func TestBucketCache_GetMissRanges_FluxInterval(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, cachedResult, nil)
|
||||
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, cachedResult)
|
||||
|
||||
// Get miss ranges
|
||||
cached, missing := bc.GetMissRanges(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond})
|
||||
@@ -686,7 +686,7 @@ func TestBucketCache_Put_FluxIntervalTrimming(t *testing.T) {
|
||||
}
|
||||
|
||||
// Put the result
|
||||
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, map[qbtypes.TimeRange]qbtypes.ExecStats{{From: query.startMs, To: query.endMs}: result.Stats})
|
||||
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
|
||||
|
||||
// Retrieve cached data
|
||||
cached, missing := bc.GetMissRanges(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond})
|
||||
@@ -756,7 +756,7 @@ func TestBucketCache_Put_EntireRangeInFluxInterval(t *testing.T) {
|
||||
}
|
||||
|
||||
// Put the result - should not cache anything
|
||||
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
|
||||
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
|
||||
|
||||
// Try to get cached data - should have no cached data
|
||||
cached, missing := bc.GetMissRanges(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond})
|
||||
@@ -862,7 +862,7 @@ func TestBucketCache_EmptyDataHandling(t *testing.T) {
|
||||
}
|
||||
|
||||
// Put the result
|
||||
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, tt.result, nil)
|
||||
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, tt.result)
|
||||
|
||||
// Wait a bit for cache to be written
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
@@ -927,7 +927,7 @@ func TestBucketCache_PartialValues(t *testing.T) {
|
||||
}
|
||||
|
||||
// Put the result
|
||||
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, map[qbtypes.TimeRange]qbtypes.ExecStats{{From: query.startMs, To: query.endMs}: result.Stats})
|
||||
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
|
||||
|
||||
// Wait for cache to be written
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
@@ -997,7 +997,7 @@ func TestBucketCache_AllPartialValues(t *testing.T) {
|
||||
}
|
||||
|
||||
// Put the result
|
||||
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
|
||||
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
|
||||
|
||||
// Wait for cache to be written
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
@@ -1058,7 +1058,7 @@ func TestBucketCache_FilteredCachedResults(t *testing.T) {
|
||||
}
|
||||
|
||||
// Cache the wide range
|
||||
bc.Put(ctx, orgID, query1, qbtypes.Step{Duration: 1000 * time.Millisecond}, result1, nil)
|
||||
bc.Put(ctx, orgID, query1, qbtypes.Step{Duration: 1000 * time.Millisecond}, result1)
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
// Now query for a smaller range (2000-3500ms)
|
||||
@@ -1125,7 +1125,7 @@ func TestBucketCache_PromQLKeepsTheValueAtTheWindowEnd(t *testing.T) {
|
||||
}},
|
||||
}},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
cached, missing := bc.GetMissRanges(ctx, orgID, query, step)
|
||||
@@ -1291,7 +1291,7 @@ func TestBucketCache_PartialValueDetection(t *testing.T) {
|
||||
}
|
||||
|
||||
// Put the result
|
||||
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
|
||||
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
// Get cached data
|
||||
@@ -1345,7 +1345,7 @@ func TestBucketCache_PartialValueDetection(t *testing.T) {
|
||||
}
|
||||
|
||||
// Put the result
|
||||
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
|
||||
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
// Get cached data
|
||||
@@ -1397,7 +1397,7 @@ func TestBucketCache_PartialValueDetection(t *testing.T) {
|
||||
}
|
||||
|
||||
// Put the result
|
||||
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
|
||||
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
// Get cached data
|
||||
@@ -1454,7 +1454,7 @@ func TestBucketCache_NoCache(t *testing.T) {
|
||||
}
|
||||
|
||||
// Put the result in cache
|
||||
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
|
||||
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
// Verify data is cached
|
||||
@@ -1475,12 +1475,11 @@ func TestBucketCachePutSlicesAtCellBoundaries(t *testing.T) {
|
||||
|
||||
// a 1s step gives 60s cells, so 30s to 150s spans three of them
|
||||
query := &mockQuery{fingerprint: "sliced-query", startMs: 30000, endMs: 150000}
|
||||
result := &qbtypes.Result{
|
||||
bc.Put(ctx, orgID, query, step, &qbtypes.Result{
|
||||
Type: qbtypes.RequestTypeTimeSeries,
|
||||
Value: createTestTimeSeries("A", 30000, 150000, 1000),
|
||||
Stats: qbtypes.ExecStats{RowsScanned: 120, BytesScanned: 1200, DurationMS: 12},
|
||||
}
|
||||
bc.Put(ctx, orgID, query, step, result, map[qbtypes.TimeRange]qbtypes.ExecStats{{From: 30000, To: 150000}: result.Stats})
|
||||
})
|
||||
|
||||
type bucketShape struct {
|
||||
cell, startMs, endMs, rowsScanned uint64
|
||||
@@ -1540,7 +1539,7 @@ func TestBucketCachePutAbsorbsWritesWithinACell(t *testing.T) {
|
||||
name: "OverlappingWrites_BecomeOne",
|
||||
firstWindow: qbtypes.TimeRange{From: 1000, To: 4000},
|
||||
secondWindow: qbtypes.TimeRange{From: 3000, To: 6000},
|
||||
expectedBuckets: []bucketShape{{1000, 6000, 5}},
|
||||
expectedBuckets: []bucketShape{{1000, 6000, 6}},
|
||||
expectedMissingRanges: []*qbtypes.TimeRange{},
|
||||
expectedValueCount: 5,
|
||||
},
|
||||
@@ -1571,13 +1570,12 @@ func TestBucketCachePutAbsorbsWritesWithinACell(t *testing.T) {
|
||||
|
||||
for _, window := range []qbtypes.TimeRange{testCase.firstWindow, testCase.secondWindow} {
|
||||
query := &mockQuery{fingerprint: "absorb-query", startMs: window.From, endMs: window.To}
|
||||
result := &qbtypes.Result{
|
||||
bc.Put(ctx, orgID, query, step, &qbtypes.Result{
|
||||
Type: qbtypes.RequestTypeTimeSeries,
|
||||
Value: createTestTimeSeries("A", window.From, window.To, 1000),
|
||||
// one row per second, so a bucket's stats read as the seconds of data it holds
|
||||
// one row per second, so a bucket's stats read as the seconds it was scanned for
|
||||
Stats: qbtypes.ExecStats{RowsScanned: (window.To - window.From) / 1000},
|
||||
}
|
||||
bc.Put(ctx, orgID, query, step, result, map[qbtypes.TimeRange]qbtypes.ExecStats{window: result.Stats})
|
||||
})
|
||||
}
|
||||
|
||||
query := &mockQuery{
|
||||
@@ -1611,7 +1609,7 @@ func TestBucketCachePutLeavesAnUnchangedCellAlone(t *testing.T) {
|
||||
Type: qbtypes.RequestTypeTimeSeries,
|
||||
Value: createTestTimeSeries("A", 1000, 10000, 1000),
|
||||
Warnings: []string{"from the wide write"},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
// a write already covered by the cell's bucket must not rewrite the entry,
|
||||
// which shows as its warnings never arriving
|
||||
@@ -1620,7 +1618,7 @@ func TestBucketCachePutLeavesAnUnchangedCellAlone(t *testing.T) {
|
||||
Type: qbtypes.RequestTypeTimeSeries,
|
||||
Value: createTestTimeSeries("A", 3000, 5000, 1000),
|
||||
Warnings: []string{"from the inside write"},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
var cellEntry qbtypes.CachedData
|
||||
require.NoError(t, bc.cache.Get(ctx, orgID, bc.generateCacheKey(wide, 0), &cellEntry))
|
||||
|
||||
@@ -828,7 +828,7 @@ func (q *querier) executeWithCache(ctx context.Context, orgID valuer.UUID, query
|
||||
return nil, err
|
||||
}
|
||||
// Store in cache for future use
|
||||
q.bucketCache.Put(ctx, orgID, query, step, result, map[qbtypes.TimeRange]qbtypes.ExecStats{{From: startMs, To: endMs}: result.Stats})
|
||||
q.bucketCache.Put(ctx, orgID, query, step, result)
|
||||
return result, nil
|
||||
}
|
||||
}
|
||||
@@ -884,19 +884,16 @@ func (q *querier) executeWithCache(ctx context.Context, orgID valuer.UUID, query
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
startMs, endMs := query.Window()
|
||||
q.bucketCache.Put(ctx, orgID, query, step, result, map[qbtypes.TimeRange]qbtypes.ExecStats{{From: startMs, To: endMs}: result.Stats})
|
||||
q.bucketCache.Put(ctx, orgID, query, step, result)
|
||||
return result, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate total stats and filter out nil results
|
||||
validResults := make([]*qbtypes.Result, 0, len(freshResults))
|
||||
execStatsForQueriedTimeRanges := make(map[qbtypes.TimeRange]qbtypes.ExecStats, len(freshResults))
|
||||
for i, result := range freshResults {
|
||||
for _, result := range freshResults {
|
||||
if result != nil {
|
||||
validResults = append(validResults, result)
|
||||
execStatsForQueriedTimeRanges[*missingRanges[i]] = result.Stats
|
||||
totalStats.RowsScanned += result.Stats.RowsScanned
|
||||
totalStats.BytesScanned += result.Stats.BytesScanned
|
||||
totalStats.DurationMS += result.Stats.DurationMS
|
||||
@@ -911,7 +908,7 @@ func (q *querier) executeWithCache(ctx context.Context, orgID valuer.UUID, query
|
||||
mergedResult.Stats.DurationMS += totalStats.DurationMS
|
||||
|
||||
// Store merged result in cache
|
||||
q.bucketCache.Put(ctx, orgID, query, step, mergedResult, execStatsForQueriedTimeRanges)
|
||||
q.bucketCache.Put(ctx, orgID, query, step, mergedResult)
|
||||
|
||||
return mergedResult, nil
|
||||
}
|
||||
|
||||
@@ -43,23 +43,6 @@ func (c *CachedBucket) Touches(other *CachedBucket) bool {
|
||||
return c.StartMs <= other.EndMs && other.StartMs <= c.EndMs
|
||||
}
|
||||
|
||||
// ProrateStatsToWindow returns the share of the stats for the part of the
|
||||
// bucket inside [startMs, endMs).
|
||||
func (c *CachedBucket) ProrateStatsToWindow(startMs, endMs uint64) ExecStats {
|
||||
return c.Stats.prorate(overlapMs(c.StartMs, c.EndMs, startMs, endMs), c.EndMs-c.StartMs)
|
||||
}
|
||||
|
||||
// ProrateStatsToUnqueried returns the share of the stats for the part of the
|
||||
// bucket no queried range covers.
|
||||
func (c *CachedBucket) ProrateStatsToUnqueried(execStatsForQueriedTimeRanges map[TimeRange]ExecStats) ExecStats {
|
||||
widthMs := c.EndMs - c.StartMs
|
||||
queriedMs := uint64(0)
|
||||
for queried := range execStatsForQueriedTimeRanges {
|
||||
queriedMs += overlapMs(c.StartMs, c.EndMs, queried.From, queried.To)
|
||||
}
|
||||
return c.Stats.prorate(widthMs-min(queriedMs, widthMs), widthMs)
|
||||
}
|
||||
|
||||
// CachedData represents the full cached data for a query.
|
||||
type CachedData struct {
|
||||
Buckets []*CachedBucket `json:"buckets"`
|
||||
@@ -105,7 +88,7 @@ func (c *CachedData) Cost() int64 {
|
||||
return size
|
||||
}
|
||||
|
||||
func (r *Result) SplitIntoCacheCellBuckets(startMs, endMs, cellWidthMs uint64, execStatsForQueriedTimeRanges map[TimeRange]ExecStats) ([]*CachedBucket, error) {
|
||||
func (r *Result) SplitIntoCacheCellBuckets(startMs, endMs, cellWidthMs uint64) ([]*CachedBucket, error) {
|
||||
tsData, ok := r.Value.(*TimeSeriesData)
|
||||
if !ok || tsData == nil {
|
||||
return nil, errors.NewInternalf(errors.CodeInternal, "result of type %s cannot be bucketed", r.Type.StringValue())
|
||||
@@ -128,39 +111,18 @@ func (r *Result) SplitIntoCacheCellBuckets(startMs, endMs, cellWidthMs uint64, e
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// A slice costs what was queried inside it; the rest of the result came
|
||||
// out of the cache and is costed there already
|
||||
sliceStats := ExecStats{StepIntervals: maps.Clone(r.Stats.StepIntervals)}
|
||||
for queried, stats := range execStatsForQueriedTimeRanges {
|
||||
queriedMs := overlapMs(from, to, queried.From, queried.To)
|
||||
if queriedMs == 0 {
|
||||
continue
|
||||
}
|
||||
share := stats.prorate(queriedMs, queried.To-queried.From)
|
||||
sliceStats.RowsScanned += share.RowsScanned
|
||||
sliceStats.BytesScanned += share.BytesScanned
|
||||
sliceStats.DurationMS += share.DurationMS
|
||||
}
|
||||
cellBuckets = append(cellBuckets, &CachedBucket{
|
||||
StartMs: from,
|
||||
EndMs: to,
|
||||
Type: r.Type,
|
||||
Value: value,
|
||||
Stats: sliceStats,
|
||||
Stats: r.Stats.prorate(to-from, endMs-startMs),
|
||||
})
|
||||
from = to
|
||||
}
|
||||
return cellBuckets, nil
|
||||
}
|
||||
|
||||
// overlapMs is the length of [aFromMs, aToMs) ∩ [bFromMs, bToMs).
|
||||
func overlapMs(aFromMs, aToMs, bFromMs, bToMs uint64) uint64 {
|
||||
if fromMs, toMs := max(aFromMs, bFromMs), min(aToMs, bToMs); fromMs < toMs {
|
||||
return toMs - fromMs
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// prorate returns the share of the stats that partMs out of wholeMs of the
|
||||
// scanned window accounts for.
|
||||
func (e ExecStats) prorate(partMs, wholeMs uint64) ExecStats {
|
||||
|
||||
164
pkg/web/routerweb/precompressed.go
Normal file
164
pkg/web/routerweb/precompressed.go
Normal file
@@ -0,0 +1,164 @@
|
||||
package routerweb
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// precompressedHandler serves "<file>.gz" in place of "<file>" when the client
|
||||
// accepts gzip, and defers to next (http.FileServer) otherwise.
|
||||
type precompressedHandler struct {
|
||||
dir http.Dir
|
||||
index string
|
||||
next http.Handler
|
||||
}
|
||||
|
||||
func newPrecompressedHandler(dir http.Dir, index string) http.Handler {
|
||||
return &precompressedHandler{dir: dir, index: index, next: http.FileServer(dir)}
|
||||
}
|
||||
|
||||
func (handler *precompressedHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||
name := path.Clean("/" + req.URL.Path)
|
||||
|
||||
// FileServer redirects non-canonical paths and the index (always
|
||||
// "/index.html"), and the configured index is templated in memory. Twins
|
||||
// are sent whole, so Range requests get the identity file.
|
||||
if (req.Method != http.MethodGet && req.Method != http.MethodHead) ||
|
||||
name != req.URL.Path ||
|
||||
strings.HasSuffix(name, "/"+handler.index) ||
|
||||
strings.HasSuffix(name, "/index.html") ||
|
||||
req.Header.Get("Range") != "" {
|
||||
handler.next.ServeHTTP(rw, req)
|
||||
return
|
||||
}
|
||||
|
||||
file, err := handler.dir.Open(name + ".gz")
|
||||
if err != nil {
|
||||
handler.next.ServeHTTP(rw, req)
|
||||
return
|
||||
}
|
||||
defer func() { _ = file.Close() }()
|
||||
|
||||
info, err := file.Stat()
|
||||
if err != nil || info.IsDir() {
|
||||
handler.next.ServeHTTP(rw, req)
|
||||
return
|
||||
}
|
||||
|
||||
// A twin whose trailer records another size was not regenerated after its file changed.
|
||||
plainInfo, err := handler.stat(name)
|
||||
if err != nil || !gzipSizeEquals(file, info.Size(), plainInfo.Size()) {
|
||||
handler.next.ServeHTTP(rw, req)
|
||||
return
|
||||
}
|
||||
|
||||
// ServeContent sniffs the twin's bytes when the extension has no type.
|
||||
if mime.TypeByExtension(path.Ext(name)) == "" {
|
||||
handler.next.ServeHTTP(rw, req)
|
||||
return
|
||||
}
|
||||
|
||||
if !slices.Contains(rw.Header().Values("Vary"), "Accept-Encoding") {
|
||||
rw.Header().Add("Vary", "Accept-Encoding")
|
||||
}
|
||||
|
||||
if !acceptsGzip(req.Header.Get("Accept-Encoding")) {
|
||||
handler.next.ServeHTTP(rw, req)
|
||||
return
|
||||
}
|
||||
|
||||
http.ServeContent(&twinWriter{ResponseWriter: rw}, req, name, info.ModTime(), file)
|
||||
}
|
||||
|
||||
func (handler *precompressedHandler) stat(name string) (os.FileInfo, error) {
|
||||
file, err := handler.dir.Open(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = file.Close() }()
|
||||
|
||||
return file.Stat()
|
||||
}
|
||||
|
||||
// gzipSizeEquals compares want with the uncompressed size, modulo 2^32, that
|
||||
// the gzip trailer records.
|
||||
func gzipSizeEquals(file http.File, size int64, want int64) bool {
|
||||
if size < 18 {
|
||||
return false
|
||||
}
|
||||
|
||||
if _, err := file.Seek(size-4, io.SeekStart); err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
var trailer [4]byte
|
||||
if _, err := io.ReadFull(file, trailer[:]); err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
return binary.LittleEndian.Uint32(trailer[:]) == uint32(want)
|
||||
}
|
||||
|
||||
// twinWriter marks only a 200 as the gzip twin: ServeContent's 304 and 412
|
||||
// carry no body. Content-Encoding stays unset until then so ServeContent
|
||||
// writes the twin's Content-Length.
|
||||
type twinWriter struct {
|
||||
http.ResponseWriter
|
||||
}
|
||||
|
||||
func (writer *twinWriter) WriteHeader(code int) {
|
||||
if code == http.StatusOK {
|
||||
writer.Header().Set("Content-Encoding", "gzip")
|
||||
writer.Header().Set("Accept-Ranges", "none")
|
||||
}
|
||||
|
||||
writer.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func (writer *twinWriter) Unwrap() http.ResponseWriter {
|
||||
return writer.ResponseWriter
|
||||
}
|
||||
|
||||
// acceptsGzip reports whether an Accept-Encoding value allows gzip, honouring
|
||||
// q=0 and falling back to the "*" entry when gzip is not listed.
|
||||
func acceptsGzip(header string) bool {
|
||||
star, gzip := -1.0, -1.0
|
||||
for _, part := range strings.Split(header, ",") {
|
||||
token, params, _ := strings.Cut(strings.TrimSpace(part), ";")
|
||||
token = strings.ToLower(strings.TrimSpace(token))
|
||||
if token != "gzip" && token != "*" {
|
||||
continue
|
||||
}
|
||||
|
||||
q := 1.0
|
||||
for _, param := range strings.Split(params, ";") {
|
||||
key, value, ok := strings.Cut(strings.TrimSpace(param), "=")
|
||||
if !ok || !strings.EqualFold(strings.TrimSpace(key), "q") {
|
||||
continue
|
||||
}
|
||||
|
||||
if parsed, err := strconv.ParseFloat(strings.TrimSpace(value), 64); err == nil {
|
||||
q = parsed
|
||||
}
|
||||
}
|
||||
|
||||
if token == "gzip" {
|
||||
gzip = q
|
||||
} else {
|
||||
star = q
|
||||
}
|
||||
}
|
||||
|
||||
if gzip >= 0 {
|
||||
return gzip > 0
|
||||
}
|
||||
|
||||
return star > 0
|
||||
}
|
||||
552
pkg/web/routerweb/precompressed_test.go
Normal file
552
pkg/web/routerweb/precompressed_test.go
Normal file
@@ -0,0 +1,552 @@
|
||||
package routerweb
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/factory/factorytest"
|
||||
"github.com/SigNoz/signoz/pkg/global"
|
||||
"github.com/SigNoz/signoz/pkg/http/middleware"
|
||||
"github.com/SigNoz/signoz/pkg/web"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func gzipBest(t *testing.T, content []byte) []byte {
|
||||
t.Helper()
|
||||
|
||||
var buf bytes.Buffer
|
||||
writer, err := gzip.NewWriterLevel(&buf, gzip.BestCompression)
|
||||
require.NoError(t, err)
|
||||
_, err = writer.Write(content)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, writer.Close())
|
||||
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
func gunzipLayers(t *testing.T, body []byte) (int, []byte) {
|
||||
t.Helper()
|
||||
|
||||
layers := 0
|
||||
for len(body) > 2 && body[0] == 0x1f && body[1] == 0x8b {
|
||||
reader, err := gzip.NewReader(bytes.NewReader(body))
|
||||
require.NoError(t, err)
|
||||
body, err = io.ReadAll(reader)
|
||||
require.NoError(t, err)
|
||||
layers++
|
||||
}
|
||||
|
||||
return layers, body
|
||||
}
|
||||
|
||||
func newIndex(body string) []byte {
|
||||
return []byte(fmt.Sprintf(`<html><head><base href="[[.BaseHref]]" /></head><body>%s</body></html>`, body))
|
||||
}
|
||||
|
||||
func newWebServer(t *testing.T, directory string, externalPath string, compression bool) *httptest.Server {
|
||||
t.Helper()
|
||||
|
||||
routerWeb, err := New(context.Background(), factorytest.NewSettings(), web.Config{Index: "index.html", Directory: directory}, global.Config{ExternalURL: &url.URL{Scheme: "https", Host: "example.com", Path: externalPath}})
|
||||
require.NoError(t, err)
|
||||
|
||||
router := mux.NewRouter().UseEncodedPath()
|
||||
require.NoError(t, routerWeb.AddToRouter(router))
|
||||
|
||||
compress, err := middleware.NewCompress(compression, gzip.DefaultCompression)
|
||||
require.NoError(t, err)
|
||||
handler := compress.Wrap(router)
|
||||
|
||||
if externalPath != "" {
|
||||
handler = http.StripPrefix(externalPath, handler)
|
||||
}
|
||||
|
||||
server := httptest.NewServer(handler)
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
return server
|
||||
}
|
||||
|
||||
func TestServePrecompressed(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
script := bytes.Repeat([]byte("export const a=1;\n"), 400)
|
||||
scriptTwin := gzipBest(t, script)
|
||||
manifest := bytes.Repeat([]byte(`{"name":"signoz"}`), 100)
|
||||
manifestTwin := gzipBest(t, manifest)
|
||||
padding := strings.Repeat("welcome ", 200)
|
||||
|
||||
directory := t.TempDir()
|
||||
files := map[string][]byte{
|
||||
"index.html": newIndex(padding),
|
||||
"index.html.gz": gzipBest(t, []byte("untemplated [[.BaseHref]]")),
|
||||
"manifest.json": manifest,
|
||||
"manifest.json.gz": manifestTwin,
|
||||
"assets/app.js": script,
|
||||
"assets/app.js.gz": scriptTwin,
|
||||
"assets/plain.css": []byte("body{}"),
|
||||
"assets/data.unknown": []byte("unknown"),
|
||||
"assets/data.unknown.gz": gzipBest(t, []byte("unknown")),
|
||||
"assets/stale.js": []byte("export const v=22;"),
|
||||
"assets/stale.js.gz": gzipBest(t, []byte("export const v=1;")),
|
||||
}
|
||||
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), content, 0o644))
|
||||
}
|
||||
|
||||
rootIndex := strings.ReplaceAll(string(files["index.html"]), "[[.BaseHref]]", "/")
|
||||
prefixedIndex := strings.ReplaceAll(string(files["index.html"]), "[[.BaseHref]]", "/signoz/")
|
||||
jsType := mime.TypeByExtension(".js")
|
||||
require.NotEmpty(t, jsType)
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
method string
|
||||
path string
|
||||
externalPath string
|
||||
headers map[string]string
|
||||
noCompress bool
|
||||
|
||||
wantStatus int
|
||||
wantEncoding string
|
||||
wantContentType string
|
||||
wantContentLength string
|
||||
wantCacheControl string
|
||||
wantAcceptRanges string
|
||||
wantVary []string
|
||||
wantWire []byte
|
||||
wantContent []byte
|
||||
wantLayers int
|
||||
}{
|
||||
{
|
||||
name: "Twin_AcceptsGzip_ServedOnce",
|
||||
path: "/assets/app.js",
|
||||
headers: map[string]string{"Accept-Encoding": "gzip, deflate, br"},
|
||||
wantStatus: http.StatusOK,
|
||||
wantEncoding: "gzip",
|
||||
wantContentType: jsType,
|
||||
wantContentLength: strconv.Itoa(len(scriptTwin)),
|
||||
wantCacheControl: immutableCacheControl,
|
||||
wantAcceptRanges: "none",
|
||||
wantVary: []string{"Accept-Encoding"},
|
||||
wantWire: scriptTwin,
|
||||
wantContent: script,
|
||||
wantLayers: 1,
|
||||
},
|
||||
{
|
||||
name: "Twin_OutsideAssets_NotImmutable",
|
||||
path: "/manifest.json",
|
||||
headers: map[string]string{"Accept-Encoding": "gzip"},
|
||||
wantStatus: http.StatusOK,
|
||||
wantEncoding: "gzip",
|
||||
wantContentType: mime.TypeByExtension(".json"),
|
||||
wantContentLength: strconv.Itoa(len(manifestTwin)),
|
||||
wantCacheControl: "max-age=0,no-cache,private,must-revalidate",
|
||||
wantVary: []string{"Accept-Encoding"},
|
||||
wantWire: manifestTwin,
|
||||
wantContent: manifest,
|
||||
wantLayers: 1,
|
||||
},
|
||||
{
|
||||
name: "Twin_CompressionDisabled_AcceptsGzip_Served",
|
||||
path: "/assets/app.js",
|
||||
noCompress: true,
|
||||
headers: map[string]string{"Accept-Encoding": "gzip"},
|
||||
wantStatus: http.StatusOK,
|
||||
wantEncoding: "gzip",
|
||||
wantContentType: jsType,
|
||||
wantContentLength: strconv.Itoa(len(scriptTwin)),
|
||||
wantCacheControl: immutableCacheControl,
|
||||
wantVary: []string{"Accept-Encoding"},
|
||||
wantWire: scriptTwin,
|
||||
wantContent: script,
|
||||
wantLayers: 1,
|
||||
},
|
||||
{
|
||||
name: "Twin_CompressionDisabled_NoAcceptEncoding_PlainWithVary",
|
||||
path: "/assets/app.js",
|
||||
noCompress: true,
|
||||
wantStatus: http.StatusOK,
|
||||
wantContentType: jsType,
|
||||
wantContentLength: strconv.Itoa(len(script)),
|
||||
wantCacheControl: immutableCacheControl,
|
||||
wantVary: []string{"Accept-Encoding"},
|
||||
wantWire: script,
|
||||
wantContent: script,
|
||||
},
|
||||
{
|
||||
name: "NoTwin_CompressionDisabled_PlainWithoutVary",
|
||||
path: "/assets/plain.css",
|
||||
noCompress: true,
|
||||
headers: map[string]string{"Accept-Encoding": "gzip"},
|
||||
wantStatus: http.StatusOK,
|
||||
wantCacheControl: immutableCacheControl,
|
||||
wantWire: []byte("body{}"),
|
||||
wantContent: []byte("body{}"),
|
||||
},
|
||||
{
|
||||
name: "Twin_NoAcceptEncoding_Plain",
|
||||
path: "/assets/app.js",
|
||||
wantStatus: http.StatusOK,
|
||||
wantContentType: jsType,
|
||||
wantCacheControl: immutableCacheControl,
|
||||
wantAcceptRanges: "bytes",
|
||||
wantVary: []string{"Accept-Encoding"},
|
||||
wantWire: script,
|
||||
wantContent: script,
|
||||
},
|
||||
{
|
||||
name: "Twin_GzipRefused_Plain",
|
||||
path: "/assets/app.js",
|
||||
headers: map[string]string{"Accept-Encoding": "gzip;q=0, br"},
|
||||
wantStatus: http.StatusOK,
|
||||
wantContentType: jsType,
|
||||
wantCacheControl: immutableCacheControl,
|
||||
wantVary: []string{"Accept-Encoding"},
|
||||
wantWire: script,
|
||||
wantContent: script,
|
||||
},
|
||||
{
|
||||
name: "Twin_OnlyBrotliAccepted_Plain",
|
||||
path: "/assets/app.js",
|
||||
headers: map[string]string{"Accept-Encoding": "br"},
|
||||
wantStatus: http.StatusOK,
|
||||
wantContentType: jsType,
|
||||
wantCacheControl: immutableCacheControl,
|
||||
wantVary: []string{"Accept-Encoding"},
|
||||
wantWire: script,
|
||||
wantContent: script,
|
||||
},
|
||||
{
|
||||
name: "Twin_Range_PlainSlice",
|
||||
path: "/assets/app.js",
|
||||
headers: map[string]string{"Accept-Encoding": "gzip", "Range": "bytes=0-9"},
|
||||
wantStatus: http.StatusPartialContent,
|
||||
wantContentType: jsType,
|
||||
wantCacheControl: immutableCacheControl,
|
||||
wantVary: []string{"Accept-Encoding"},
|
||||
wantWire: script[:10],
|
||||
wantContent: script[:10],
|
||||
},
|
||||
{
|
||||
name: "Twin_Post_CompressionDisabled_Plain",
|
||||
method: http.MethodPost,
|
||||
path: "/assets/app.js",
|
||||
noCompress: true,
|
||||
headers: map[string]string{"Accept-Encoding": "gzip"},
|
||||
wantStatus: http.StatusOK,
|
||||
wantContentType: jsType,
|
||||
wantCacheControl: immutableCacheControl,
|
||||
wantWire: script,
|
||||
wantContent: script,
|
||||
},
|
||||
{
|
||||
name: "Twin_Head_HeadersOnly",
|
||||
method: http.MethodHead,
|
||||
path: "/assets/app.js",
|
||||
headers: map[string]string{"Accept-Encoding": "gzip"},
|
||||
wantStatus: http.StatusOK,
|
||||
wantEncoding: "gzip",
|
||||
wantContentType: jsType,
|
||||
wantContentLength: strconv.Itoa(len(scriptTwin)),
|
||||
wantCacheControl: immutableCacheControl,
|
||||
wantVary: []string{"Accept-Encoding"},
|
||||
wantWire: []byte{},
|
||||
wantContent: []byte{},
|
||||
},
|
||||
{
|
||||
name: "Twin_IfModifiedSince_NotModified",
|
||||
path: "/assets/app.js",
|
||||
headers: map[string]string{"Accept-Encoding": "gzip", "If-Modified-Since": time.Now().Add(time.Hour).UTC().Format(http.TimeFormat)},
|
||||
wantStatus: http.StatusNotModified,
|
||||
wantCacheControl: immutableCacheControl,
|
||||
wantVary: []string{"Accept-Encoding"},
|
||||
wantWire: []byte{},
|
||||
wantContent: []byte{},
|
||||
},
|
||||
{
|
||||
name: "Twin_IfUnmodifiedSinceFails_PreconditionFailedWithoutBody",
|
||||
path: "/assets/app.js",
|
||||
headers: map[string]string{"Accept-Encoding": "gzip", "If-Unmodified-Since": time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC).Format(http.TimeFormat)},
|
||||
wantStatus: http.StatusPreconditionFailed,
|
||||
wantCacheControl: immutableCacheControl,
|
||||
wantVary: []string{"Accept-Encoding"},
|
||||
wantWire: []byte{},
|
||||
wantContent: []byte{},
|
||||
},
|
||||
{
|
||||
name: "Twin_SizeMismatch_Plain",
|
||||
path: "/assets/stale.js",
|
||||
headers: map[string]string{"Accept-Encoding": "gzip"},
|
||||
wantStatus: http.StatusOK,
|
||||
wantContentType: jsType,
|
||||
wantCacheControl: immutableCacheControl,
|
||||
wantVary: []string{"Accept-Encoding"},
|
||||
wantWire: []byte("export const v=22;"),
|
||||
wantContent: []byte("export const v=22;"),
|
||||
},
|
||||
{
|
||||
name: "Twin_TrailingSlash_RedirectsWithoutImmutable",
|
||||
path: "/assets/app.js/",
|
||||
headers: map[string]string{"Accept-Encoding": "gzip"},
|
||||
wantStatus: http.StatusMovedPermanently,
|
||||
wantCacheControl: "max-age=0,no-cache,private,must-revalidate",
|
||||
wantVary: []string{"Accept-Encoding"},
|
||||
},
|
||||
{
|
||||
name: "Twin_DotDotOutOfAssets_NotImmutable",
|
||||
path: "/assets/%2e%2e/manifest.json",
|
||||
headers: map[string]string{"Accept-Encoding": "gzip"},
|
||||
wantStatus: http.StatusOK,
|
||||
wantEncoding: "gzip",
|
||||
wantContentType: mime.TypeByExtension(".json"),
|
||||
wantCacheControl: "max-age=0,no-cache,private,must-revalidate",
|
||||
wantVary: []string{"Accept-Encoding"},
|
||||
wantContent: manifest,
|
||||
wantLayers: 1,
|
||||
},
|
||||
{
|
||||
name: "NoTwin_AcceptsGzip_Plain",
|
||||
path: "/assets/plain.css",
|
||||
headers: map[string]string{"Accept-Encoding": "gzip"},
|
||||
wantStatus: http.StatusOK,
|
||||
wantCacheControl: immutableCacheControl,
|
||||
wantVary: []string{"Accept-Encoding"},
|
||||
wantWire: []byte("body{}"),
|
||||
wantContent: []byte("body{}"),
|
||||
},
|
||||
{
|
||||
name: "Twin_UnknownExtension_Plain",
|
||||
path: "/assets/data.unknown",
|
||||
headers: map[string]string{"Accept-Encoding": "gzip"},
|
||||
wantStatus: http.StatusOK,
|
||||
wantCacheControl: immutableCacheControl,
|
||||
wantVary: []string{"Accept-Encoding"},
|
||||
wantWire: []byte("unknown"),
|
||||
wantContent: []byte("unknown"),
|
||||
},
|
||||
{
|
||||
name: "IndexFile_Redirects",
|
||||
path: "/index.html",
|
||||
headers: map[string]string{"Accept-Encoding": "gzip"},
|
||||
wantStatus: http.StatusMovedPermanently,
|
||||
wantCacheControl: "max-age=0,no-cache,private,must-revalidate",
|
||||
wantVary: []string{"Accept-Encoding"},
|
||||
wantWire: nil,
|
||||
},
|
||||
{
|
||||
name: "Root_ServesTemplatedIndexNotTwin",
|
||||
path: "/",
|
||||
headers: map[string]string{"Accept-Encoding": "gzip"},
|
||||
wantStatus: http.StatusOK,
|
||||
wantEncoding: "gzip",
|
||||
wantContentType: "text/html; charset=utf-8",
|
||||
wantCacheControl: "max-age=0,no-cache,private,must-revalidate",
|
||||
wantVary: []string{"Accept-Encoding"},
|
||||
wantContent: []byte(rootIndex),
|
||||
wantLayers: 1,
|
||||
},
|
||||
{
|
||||
name: "MissingAsset_FallsBackToIndexWithoutImmutable",
|
||||
path: "/assets/missing.js",
|
||||
headers: map[string]string{"Accept-Encoding": "gzip"},
|
||||
wantStatus: http.StatusOK,
|
||||
wantEncoding: "gzip",
|
||||
wantContentType: "text/html; charset=utf-8",
|
||||
wantCacheControl: "max-age=0,no-cache,private,must-revalidate",
|
||||
wantVary: []string{"Accept-Encoding"},
|
||||
wantContent: []byte(rootIndex),
|
||||
wantLayers: 1,
|
||||
},
|
||||
{
|
||||
name: "BasePath_Twin_AcceptsGzip_Served",
|
||||
path: "/signoz/assets/app.js",
|
||||
externalPath: "/signoz",
|
||||
headers: map[string]string{"Accept-Encoding": "gzip"},
|
||||
wantStatus: http.StatusOK,
|
||||
wantEncoding: "gzip",
|
||||
wantContentType: jsType,
|
||||
wantContentLength: strconv.Itoa(len(scriptTwin)),
|
||||
wantCacheControl: immutableCacheControl,
|
||||
wantVary: []string{"Accept-Encoding"},
|
||||
wantWire: scriptTwin,
|
||||
wantContent: script,
|
||||
wantLayers: 1,
|
||||
},
|
||||
{
|
||||
name: "BasePath_MissingAsset_FallsBackToIndexWithBaseHref",
|
||||
path: "/signoz/assets/missing.js",
|
||||
externalPath: "/signoz",
|
||||
headers: map[string]string{"Accept-Encoding": "gzip"},
|
||||
wantStatus: http.StatusOK,
|
||||
wantEncoding: "gzip",
|
||||
wantContentType: "text/html; charset=utf-8",
|
||||
wantCacheControl: "max-age=0,no-cache,private,must-revalidate",
|
||||
wantVary: []string{"Accept-Encoding"},
|
||||
wantContent: []byte(prefixedIndex),
|
||||
wantLayers: 1,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
server := newWebServer(t, directory, testCase.externalPath, !testCase.noCompress)
|
||||
|
||||
method := testCase.method
|
||||
if method == "" {
|
||||
method = http.MethodGet
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(method, server.URL+testCase.path, nil)
|
||||
require.NoError(t, err)
|
||||
for key, value := range testCase.headers {
|
||||
req.Header.Set(key, value)
|
||||
}
|
||||
|
||||
client := &http.Client{
|
||||
Transport: &http.Transport{DisableCompression: true},
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
|
||||
}
|
||||
res, err := client.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = res.Body.Close() }()
|
||||
|
||||
body, err := io.ReadAll(res.Body)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, testCase.wantStatus, res.StatusCode)
|
||||
assert.Equal(t, testCase.wantEncoding, res.Header.Get("Content-Encoding"))
|
||||
assert.Equal(t, testCase.wantCacheControl, res.Header.Get("Cache-Control"))
|
||||
assert.Equal(t, testCase.wantVary, res.Header.Values("Vary"))
|
||||
if testCase.wantAcceptRanges != "" {
|
||||
assert.Equal(t, testCase.wantAcceptRanges, res.Header.Get("Accept-Ranges"))
|
||||
}
|
||||
if testCase.wantContentType != "" {
|
||||
assert.Equal(t, testCase.wantContentType, res.Header.Get("Content-Type"))
|
||||
}
|
||||
if testCase.wantContentLength != "" {
|
||||
assert.Equal(t, testCase.wantContentLength, res.Header.Get("Content-Length"))
|
||||
}
|
||||
if testCase.wantWire != nil {
|
||||
assert.Equal(t, testCase.wantWire, body)
|
||||
}
|
||||
|
||||
layers, content := gunzipLayers(t, body)
|
||||
assert.Equal(t, testCase.wantLayers, layers)
|
||||
if testCase.wantContent != nil {
|
||||
assert.Equal(t, testCase.wantContent, content)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestServePrecompressedLastModified(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
script := bytes.Repeat([]byte("export const a=1;\n"), 400)
|
||||
directory := t.TempDir()
|
||||
require.NoError(t, os.MkdirAll(filepath.Join(directory, "assets"), 0o755))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(directory, "index.html"), newIndex("index"), 0o644))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(directory, "assets", "app.js"), script, 0o644))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(directory, "assets", "app.js.gz"), gzipBest(t, script), 0o644))
|
||||
|
||||
plainTime := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
|
||||
twinTime := time.Date(2026, 1, 2, 3, 5, 6, 0, time.UTC)
|
||||
require.NoError(t, os.Chtimes(filepath.Join(directory, "assets", "app.js"), plainTime, plainTime))
|
||||
require.NoError(t, os.Chtimes(filepath.Join(directory, "assets", "app.js.gz"), twinTime, twinTime))
|
||||
|
||||
server := newWebServer(t, directory, "", true)
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
acceptEncoding string
|
||||
wantModified time.Time
|
||||
}{
|
||||
{name: "AcceptsGzip_TwinModTime", acceptEncoding: "gzip", wantModified: twinTime},
|
||||
{name: "NoAcceptEncoding_PlainModTime", acceptEncoding: "", wantModified: plainTime},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
req, err := http.NewRequest(http.MethodGet, server.URL+"/assets/app.js", nil)
|
||||
require.NoError(t, err)
|
||||
if testCase.acceptEncoding != "" {
|
||||
req.Header.Set("Accept-Encoding", testCase.acceptEncoding)
|
||||
}
|
||||
|
||||
res, err := (&http.Client{Transport: &http.Transport{DisableCompression: true}}).Do(req)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = res.Body.Close() }()
|
||||
|
||||
assert.Equal(t, testCase.wantModified.Format(http.TimeFormat), res.Header.Get("Last-Modified"))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestServePrecompressedCustomIndex(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
directory := t.TempDir()
|
||||
require.NoError(t, os.WriteFile(filepath.Join(directory, "index.html"), []byte("untemplated"), 0o644))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(directory, "index.html.gz"), gzipBest(t, []byte("untemplated")), 0o644))
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/index.html", nil)
|
||||
req.Header.Set("Accept-Encoding", "gzip")
|
||||
rec := httptest.NewRecorder()
|
||||
newPrecompressedHandler(http.Dir(directory), "main.html").ServeHTTP(rec, req)
|
||||
|
||||
assert.Equal(t, http.StatusMovedPermanently, rec.Code)
|
||||
assert.Empty(t, rec.Header().Get("Content-Encoding"))
|
||||
}
|
||||
|
||||
func TestAcceptsGzip(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
header string
|
||||
want bool
|
||||
}{
|
||||
{name: "Empty", header: "", want: false},
|
||||
{name: "Gzip", header: "gzip", want: true},
|
||||
{name: "Gzip_UpperCase", header: "GZIP", want: true},
|
||||
{name: "Gzip_AmongOthers", header: "gzip, deflate, br, zstd", want: true},
|
||||
{name: "Gzip_LowQuality", header: "br, gzip;q=0.5", want: true},
|
||||
{name: "Gzip_ZeroQuality", header: "gzip;q=0", want: false},
|
||||
{name: "Gzip_ZeroQualityWithSpaces", header: "gzip; q=0.0", want: false},
|
||||
{name: "Gzip_InvalidQuality", header: "gzip;q=notanumber", want: true},
|
||||
{name: "Gzip_ZeroQualityAfterOtherParam", header: "gzip;level=1;q=0", want: false},
|
||||
{name: "Star", header: "*", want: true},
|
||||
{name: "Star_ZeroQuality", header: "*;q=0", want: false},
|
||||
{name: "Star_LowQuality", header: "deflate, *;q=0.1", want: true},
|
||||
{name: "Gzip_RefusedOverridesStar", header: "gzip;q=0, *", want: false},
|
||||
{name: "Identity", header: "identity", want: false},
|
||||
{name: "Brotli", header: "br", want: false},
|
||||
{name: "XGzip", header: "x-gzip", want: false},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
assert.Equal(t, testCase.want, acceptsGzip(testCase.header))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,9 @@ import (
|
||||
"html/template"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/factory"
|
||||
@@ -16,6 +18,11 @@ import (
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
const (
|
||||
assetsPathPrefix = "/assets/"
|
||||
immutableCacheControl = "public, max-age=31536000, immutable"
|
||||
)
|
||||
|
||||
type provider struct {
|
||||
config web.Config
|
||||
indexContents []byte
|
||||
@@ -59,7 +66,7 @@ func New(ctx context.Context, settings factory.ProviderSettings, config web.Conf
|
||||
return &provider{
|
||||
config: config,
|
||||
indexContents: indexContents,
|
||||
fileHandler: http.FileServer(http.Dir(config.Directory)),
|
||||
fileHandler: newPrecompressedHandler(http.Dir(config.Directory), config.Index),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -78,10 +85,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) {
|
||||
@@ -101,6 +108,12 @@ func (provider *provider) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// files under /assets/ are content-hashed, so their URL changes with their content.
|
||||
// A non-canonical URL can name a file outside /assets/ or get a redirect.
|
||||
if req.URL.Path == path.Clean(req.URL.Path) && strings.HasPrefix(req.URL.Path, assetsPathPrefix) {
|
||||
rw.Header().Set("Cache-Control", immutableCacheControl)
|
||||
}
|
||||
|
||||
// otherwise, use http.FileServer to serve the static file
|
||||
provider.fileHandler.ServeHTTP(rw, req)
|
||||
}
|
||||
|
||||
@@ -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))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -442,55 +442,3 @@ def test_builder_refreshing_a_sliding_time_range(
|
||||
assert uncached.status_code == HTTPStatus.OK, uncached.text
|
||||
|
||||
assert_results_equal(from_cache.json(), uncached.json(), "A", "the twentieth refresh")
|
||||
|
||||
|
||||
def test_builder_refreshing_does_not_inflate_rows_scanned(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_metrics: Callable[[list[Metrics]], None],
|
||||
) -> None:
|
||||
metric_name = f"cache_rows_scanned_{uuid4().hex[:8]}"
|
||||
|
||||
# 90 minutes back so even the last refresh closes clear of the flux
|
||||
# interval, which holds recent data out of the cache
|
||||
start_time = datetime.fromtimestamp(int((datetime.now(tz=UTC) - timedelta(minutes=90)).timestamp()) // 60 * 60, tz=UTC)
|
||||
start_time_ms = int(start_time.timestamp() * 1000)
|
||||
|
||||
query = [build_builder_query("A", metric_name, "max", "max")]
|
||||
|
||||
insert_metrics(
|
||||
[
|
||||
Metrics(
|
||||
metric_name=metric_name,
|
||||
labels={"service": "api"},
|
||||
timestamp=start_time + timedelta(minutes=minute),
|
||||
value=minute,
|
||||
type_="Gauge",
|
||||
is_monotonic=False,
|
||||
)
|
||||
for minute in range(70)
|
||||
]
|
||||
)
|
||||
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
# a dashboard left open on a thirty minute range, re-running a minute later
|
||||
# each time. rowsScanned is a cost indicator, so a refresh served mostly out
|
||||
# of the cache cannot claim more than every read made so far: the first
|
||||
# full read and then one new minute per refresh, measured with the cache off
|
||||
uncached_rows_scanned_so_far = 0
|
||||
for refresh in range(10):
|
||||
refresh_start_ms = start_time_ms + refresh * MINUTE_MS
|
||||
refresh_end_ms = refresh_start_ms + 30 * MINUTE_MS
|
||||
|
||||
uncached_start_ms = refresh_start_ms if refresh == 0 else refresh_end_ms - MINUTE_MS
|
||||
uncached_response = make_query_request(signoz, token, uncached_start_ms, refresh_end_ms, query, no_cache=True)
|
||||
assert uncached_response.status_code == HTTPStatus.OK, f"refresh {refresh}: uncached read failed: {uncached_response.text}"
|
||||
uncached_rows_scanned_so_far += uncached_response.json()["data"]["meta"]["rowsScanned"]
|
||||
assert uncached_rows_scanned_so_far > 0, f"refresh {refresh}: uncached read reported no rows scanned"
|
||||
|
||||
cached_response = make_query_request(signoz, token, refresh_start_ms, refresh_end_ms, query, no_cache=False)
|
||||
assert cached_response.status_code == HTTPStatus.OK, f"refresh {refresh}: cached read failed: {cached_response.text}"
|
||||
cached_rows_scanned = cached_response.json()["data"]["meta"]["rowsScanned"]
|
||||
assert cached_rows_scanned <= uncached_rows_scanned_so_far, f"refresh {refresh}: cached read reported {cached_rows_scanned} rows scanned, more than the {uncached_rows_scanned_so_far} rows all uncached reads scanned so far"
|
||||
|
||||
Reference in New Issue
Block a user