Skip to content

Commit 63d4a7d

Browse files
committed
Improve LogMonitor to handle empty writes and ensure buffer immutability
- Add a check to return immediately if the write buffer is empty - Create a copy of new history data to ensure it is immutable - Update the `GetHistory` method to use the `any` type for the buffer interface - Add a test case to verify that the buffer remains unchanged even if the original message is modified after writing
1 parent f45469f commit 63d4a7d

File tree

2 files changed

+40
-2
lines changed

2 files changed

+40
-2
lines changed

proxy/logMonitor.go

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,13 +30,19 @@ func NewLogMonitorWriter(stdout io.Writer) *LogMonitor {
3030
}
3131

3232
func (w *LogMonitor) Write(p []byte) (n int, err error) {
33+
if len(p) == 0 {
34+
return 0, nil
35+
}
36+
3337
n, err = w.stdout.Write(p)
3438
if err != nil {
3539
return n, err
3640
}
3741

3842
w.bufferMu.Lock()
39-
w.buffer.Value = p
43+
bufferCopy := make([]byte, len(p))
44+
copy(bufferCopy, p)
45+
w.buffer.Value = bufferCopy
4046
w.buffer = w.buffer.Next()
4147
w.bufferMu.Unlock()
4248

@@ -49,7 +55,7 @@ func (w *LogMonitor) GetHistory() []byte {
4955
defer w.bufferMu.RUnlock()
5056

5157
var history []byte
52-
w.buffer.Do(func(p interface{}) {
58+
w.buffer.Do(func(p any) {
5359
if p != nil {
5460
if content, ok := p.([]byte); ok {
5561
history = append(history, content...)

proxy/logMonitor_test.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package proxy
22

33
import (
4+
"bytes"
45
"io"
56
"sync"
67
"testing"
@@ -61,3 +62,34 @@ func TestLogMonitor(t *testing.T) {
6162
t.Errorf("Client2 expected %s, got: %s", expectedHistory, c2Data)
6263
}
6364
}
65+
66+
func TestWrite_ImmutableBuffer(t *testing.T) {
67+
// Create a new LogMonitor instance
68+
lm := NewLogMonitorWriter(io.Discard)
69+
70+
// Prepare a message to write
71+
msg := []byte("Hello, World!")
72+
lenmsg := len(msg)
73+
74+
// Write the message to the LogMonitor
75+
n, err := lm.Write(msg)
76+
if err != nil {
77+
t.Fatalf("Write failed: %v", err)
78+
}
79+
80+
if n != lenmsg {
81+
t.Errorf("Expected %d bytes written but got %d", lenmsg, n)
82+
}
83+
84+
// Change the original message
85+
msg[0] = 'B' // This should not affect the buffer
86+
87+
// Get the history from the LogMonitor
88+
history := lm.GetHistory()
89+
90+
// Check that the history contains the original message, not the modified one
91+
expected := []byte("Hello, World!")
92+
if !bytes.Equal(history, expected) {
93+
t.Errorf("Expected history to be %q, got %q", expected, history)
94+
}
95+
}

0 commit comments

Comments
 (0)