Skip to content

Commit 3329923

Browse files
committed
fix: prevent buffer reuse in async mode for Put method
If the mode is async, we need to copy request Blob to prevent fasthttp from reusing the buffer since we are going to use the buffer in a separate goroutine beyond the scope of the current request.
1 parent a434c18 commit 3329923

File tree

2 files changed

+11
-1
lines changed

2 files changed

+11
-1
lines changed

fastcache.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,9 @@ type Item struct {
7777
ContentType string
7878
Compression string
7979
ETag string
80-
Blob []byte
80+
// If the Blob is used beyond the scope of the request, it should be copied.
81+
// Such as when the cache is written asynchronously.
82+
Blob []byte
8183
}
8284

8385
// Store represents a backend data store where bytes are cached. Individual

stores/goredis/redis.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,14 @@ type putReq struct {
169169
// Put sets a value to given session but stored only on commit
170170
func (s *Store) Put(namespace, group, uri string, b fastcache.Item, ttl time.Duration) error {
171171
if s.config.Async {
172+
// In async mode, we need to copy b.Blob to prevent fasthttp from reusing
173+
// the buffer, as we will use the buffer in a separate goroutine beyond
174+
// the scope of the current request.
175+
blobCopy := make([]byte, len(b.Blob))
176+
copy(blobCopy, b.Blob)
177+
b.Blob = blobCopy
178+
179+
// Send the put request to the async buffer channel.
172180
s.putBuf <- putReq{namespace, group, uri, b, ttl}
173181
return nil
174182
}

0 commit comments

Comments
 (0)