Find, verify, and analyze leaked credentials
Go credentialsdevsecopsdynamic-analysisprecommitscanningsecretsecret-managementsecretssecuritysecurity-toolstrufflehogverification
[perf] - Optimize Chunk Size Handling for Improved I/O and Memory Efficiency (#3134)
ahravd0b1fbadfe66
diff --git a/pkg/sources/chunker.go b/pkg/sources/chunker.goindex ab1d1e828..3bce67bb0 100644--- a/pkg/sources/chunker.go+++ b/pkg/sources/chunker.go@@ -10,18 +10,19 @@ import ()const (- // ChunkSize is the maximum size of a chunk.- ChunkSize = 10 * 1024- // PeekSize is the size of the peek into the previous chunk.- PeekSize = 3 * 1024+ // DefaultChunkSize used by the chunker.+ DefaultChunkSize = 10 * 1024+ // DefaultPeekSize is the size of the peek into the previous chunk.+ DefaultPeekSize = 3 * 1024// TotalChunkSize is the total size of a chunk with peek data.- TotalChunkSize = ChunkSize + PeekSize+ TotalChunkSize = DefaultChunkSize + DefaultPeekSize)type chunkReaderConfig struct {chunkSize inttotalSize intpeekSize int+ fileSize int}// ConfigOption is a function that configures a chunker.@@ -29,16 +30,18 @@ type ConfigOption func(*chunkReaderConfig)// WithChunkSize sets the chunk size.func WithChunkSize(size int) ConfigOption {- return func(c *chunkReaderConfig) {- c.chunkSize = size- }+ return func(c *chunkReaderConfig) { c.chunkSize = size }}// WithPeekSize sets the peek size.func WithPeekSize(size int) ConfigOption {- return func(c *chunkReaderConfig) {- c.peekSize = size- }+ return func(c *chunkReaderConfig) { c.peekSize = size }+}++// WithFileSize sets the file size.+// Note: If WithChunkSize is also provided, WithChunkSize takes precedence.+func WithFileSize(size int) ConfigOption {+ return func(c *chunkReaderConfig) { c.fileSize = size }}// ChunkResult is the output unit of a ChunkReader,@@ -58,6 +61,21 @@ func (cr ChunkResult) Error() error {return cr.err}+const (+ // Size thresholds.+ xsmallFileSizeThreshold = 4 * 1024 // 4KB+ smallFileSizeThreshold = 10 * 1024 // 10KB+ mediumFileSizeThreshold = 100 * 1024 // 100KB+ largeFileSizeThreshold = 1 * 1024 * 1024 // 1MB++ // Chunk sizes.+ xsmallFileChunkSize = 1 << 12 // 4KB+ smallFileChunkSize = 1 << 13 // 8KB+ mediumFileChunkSize = 1 << 14 // 16KB+ largeFileChunkSize = 1 << 15 // 32KB+ xlargeFileChunkSize = 1 << 16 // 64KB+)+// ChunkReader reads chunks from a reader and returns a channel of chunks and a channel of errors.// The channel of chunks is closed when the reader is closed.// This should be used whenever a large amount of data is read from a reader.@@ -73,19 +91,39 @@ func NewChunkReader(opts ...ConfigOption) ChunkReader {func applyOptions(opts []ConfigOption) *chunkReaderConfig {// Set defaults.config := &chunkReaderConfig{- chunkSize: ChunkSize, // default- peekSize: PeekSize, // default+ chunkSize: DefaultChunkSize, // default+ peekSize: DefaultPeekSize, // default}for _, opt := range opts {opt(config)}+ // Prioritize chunkSize over fileSize if both are provided.+ if config.fileSize != 0 && config.chunkSize == DefaultChunkSize {+ config.chunkSize = calculateOptimalChunkSize(config.fileSize)+ }+config.totalSize = config.chunkSize + config.peekSizereturn config}+func calculateOptimalChunkSize(fileSize int) int {+ switch {+ case fileSize < xsmallFileSizeThreshold:+ return xsmallFileChunkSize+ case fileSize < smallFileSizeThreshold:+ return smallFileChunkSize+ case fileSize < mediumFileSizeThreshold:+ return mediumFileChunkSize+ case fileSize < largeFileSizeThreshold:+ return largeFileChunkSize+ default:+ return xlargeFileChunkSize+ }+}+func createReaderFn(config *chunkReaderConfig) ChunkReader {return func(ctx context.Context, reader io.Reader) <-chan ChunkResult {return readInChunks(ctx, reader, config)diff --git a/pkg/sources/chunker_test.go b/pkg/sources/chunker_test.goindex 1051de135..ea3e45f3f 100644--- a/pkg/sources/chunker_test.go+++ b/pkg/sources/chunker_test.go@@ -28,8 +28,8 @@ func TestNewChunkedReader(t *testing.T) {{name: "Smaller data than default chunkSize and peekSize",input: "example input",- chunkSize: ChunkSize,- peekSize: PeekSize,+ chunkSize: DefaultChunkSize,+ peekSize: DefaultPeekSize,wantChunks: []string{"example input"},wantErr: false,},@@ -142,7 +142,7 @@ func BenchmarkChunkReader(b *testing.B) {var bigChunk = make([]byte, 1<<24) // 16MBreader := bytes.NewReader(bigChunk)- chunkReader := NewChunkReader(WithChunkSize(ChunkSize), WithPeekSize(PeekSize))+ chunkReader := NewChunkReader(WithChunkSize(DefaultChunkSize), WithPeekSize(DefaultPeekSize))b.ReportAllocs()b.ResetTimer()diff --git a/pkg/sources/docker/docker.go b/pkg/sources/docker/docker.goindex 0d9bf444c..fca5b920f 100644--- a/pkg/sources/docker/docker.go+++ b/pkg/sources/docker/docker.go@@ -366,7 +366,7 @@ func (s *Source) processChunk(ctx context.Context, info chunkProcessingInfo, chureturn nil}- chunkReader := sources.NewChunkReader()+ chunkReader := sources.NewChunkReader(sources.WithFileSize(int(info.size)))chunkResChan := chunkReader(ctx, info.reader)for data := range chunkResChan {diff --git a/pkg/sources/filesystem/filesystem_test.go b/pkg/sources/filesystem/filesystem_test.goindex f7adc0916..c161ec529 100644--- a/pkg/sources/filesystem/filesystem_test.go+++ b/pkg/sources/filesystem/filesystem_test.go@@ -95,7 +95,7 @@ func TestSource_Scan(t *testing.T) {}func TestScanFile(t *testing.T) {- chunkSize := sources.ChunkSize+ chunkSize := sources.DefaultChunkSizesecretPart1 := "SECRET"secretPart2 := "SPLIT"// Split the secret into two parts and pad the rest of the chunk with A's.diff --git a/pkg/sources/git/git.go b/pkg/sources/git/git.goindex 1bb1ae372..929e14de6 100644--- a/pkg/sources/git/git.go+++ b/pkg/sources/git/git.go@@ -724,7 +724,7 @@ func (s *Git) ScanCommits(ctx context.Context, repo *git.Repository, path stringcontinue}- if diff.Len() > sources.ChunkSize+sources.PeekSize {+ if diff.Len() > sources.DefaultChunkSize+sources.DefaultPeekSize {s.gitChunk(ctx, diff, fileName, email, fullHash, when, remoteURL, reporter)continue}@@ -785,7 +785,7 @@ func (s *Git) gitChunk(ctx context.Context, diff *gitparse.Diff, fileName, emailline := make([]byte, len(originalChunk.Bytes())+1)copy(line, originalChunk.Bytes())line[len(line)-1] = byte('\n')- if len(line) > sources.ChunkSize || len(line)+newChunkBuffer.Len() > sources.ChunkSize {+ if len(line) > sources.DefaultChunkSize || len(line)+newChunkBuffer.Len() > sources.DefaultChunkSize {// Add oversize chunk infoif newChunkBuffer.Len() > 0 {// Send the existing fragment.@@ -807,7 +807,7 @@ func (s *Git) gitChunk(ctx context.Context, diff *gitparse.Diff, fileName, emailnewChunkBuffer.Reset()lastOffset = offset}- if len(line) > sources.ChunkSize {+ if len(line) > sources.DefaultChunkSize {// Send the oversize line.metadata := s.sourceMetadataFunc(fileName, email, hash, when, urlMetadata, int64(diff.LineStart+offset))chunk := sources.Chunk{diff --git a/pkg/sources/jenkins/jenkins_test.go b/pkg/sources/jenkins/jenkins_test.goindex 359baa5e8..90461805e 100644--- a/pkg/sources/jenkins/jenkins_test.go+++ b/pkg/sources/jenkins/jenkins_test.go@@ -93,11 +93,11 @@ func createMockJenkinsServer(jobName string, buildNumber int, logContent string)// logs to large CI/CD outputs.func TestJenkinsVariousSizes(t *testing.T) {testCases := []struct {- name string- dataSize int- pattern string- jobName string- buildNumber int+ name string+ dataSize int+ pattern string+ jobName string+ buildNumber int}{{name: "small_60KB",@@ -179,9 +179,9 @@ func TestJenkinsVariousSizes(t *testing.T) {// Verify that large logs are actually being split into multiple chunks.// This catches regressions where chunking logic might not be working.// Data larger than a single chunk should result in multiple chunks.- if tc.dataSize > sources.ChunkSize && len(chunks) <= 1 {+ if tc.dataSize > sources.DefaultChunkSize && len(chunks) <= 1 {t.Logf("Got only %d chunk for data size %d bytes (chunk size: %d bytes), may indicate chunking not working as expected",- len(chunks), tc.dataSize, sources.ChunkSize)+ len(chunks), tc.dataSize, sources.DefaultChunkSize)}// Ensure no individual chunk exceeds the maximum allowed size.