-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathwrite_buffer_test.go
More file actions
327 lines (265 loc) · 9.7 KB
/
write_buffer_test.go
File metadata and controls
327 lines (265 loc) · 9.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
package blockqueue
import (
"context"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
bqio "github.com/yudhasubki/blockqueue/pkg/io"
"github.com/yudhasubki/blockqueue/pkg/sqlite"
)
// setupTestDB creates a test database and runs migrations
func setupTestDB(t *testing.T, dbName string) (*sqlite.SQLite, func()) {
sqliteDb, err := sqlite.New(dbName, sqlite.Config{
BusyTimeout: 5000,
})
require.NoError(t, err)
runMigrate(t, sqliteDb)
cleanup := func() {
sqliteDb.Database.Close()
}
return sqliteDb, cleanup
}
func TestWriteBuffer_BatchFlush(t *testing.T) {
t.Run("flushes when batch size reached", func(t *testing.T) {
dbName := "test_wb_batch_" + uuid.NewString()[:8]
sqliteDb, cleanup := setupTestDB(t, dbName)
defer cleanup()
defer removeTestDB(dbName)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
database := newDb(sqliteDb)
// Create topic and subscriber
topicId := uuid.New()
subscriberId := uuid.New()
_, err := sqliteDb.Database.Exec("INSERT INTO topics (id, name) VALUES (?, ?)", topicId, "test-topic")
require.NoError(t, err)
_, err = sqliteDb.Database.Exec(
"INSERT INTO topic_subscribers (id, topic_id, name, option) VALUES (?, ?, ?, ?)",
subscriberId, topicId, "test-subscriber", `{"max_attempts":3,"visibility_duration":"30s"}`,
)
require.NoError(t, err)
config := WriteBufferConfig{
BatchSize: 5, // Small batch for testing
FlushInterval: 10 * time.Second,
BufferSize: 100,
}
wb := NewWriteBuffer(ctx, database, config)
defer wb.Close()
// Enqueue exactly batch size messages
for i := 0; i < 5; i++ {
wb.Enqueue(topicId, uuid.NewString(), "test message", 0)
}
// Wait for flush
time.Sleep(100 * time.Millisecond)
// Verify messages were inserted
var count int
err = sqliteDb.Database.Get(&count, "SELECT COUNT(*) FROM subscriber_messages WHERE topic_id = ?", topicId)
require.NoError(t, err)
require.Equal(t, 5, count, "expected 5 messages to be flushed")
})
}
func TestWriteBuffer_TimeFlush(t *testing.T) {
t.Run("flushes on interval even with partial batch", func(t *testing.T) {
dbName := "test_wb_time_" + uuid.NewString()[:8]
sqliteDb, cleanup := setupTestDB(t, dbName)
defer cleanup()
defer removeTestDB(dbName)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
database := newDb(sqliteDb)
// Create topic and subscriber
topicId := uuid.New()
subscriberId := uuid.New()
_, err := sqliteDb.Database.Exec("INSERT INTO topics (id, name) VALUES (?, ?)", topicId, "test-topic")
require.NoError(t, err)
_, err = sqliteDb.Database.Exec(
"INSERT INTO topic_subscribers (id, topic_id, name, option) VALUES (?, ?, ?, ?)",
subscriberId, topicId, "test-subscriber", `{"max_attempts":3,"visibility_duration":"30s"}`,
)
require.NoError(t, err)
config := WriteBufferConfig{
BatchSize: 100, // Large batch - won't be reached
FlushInterval: 50 * time.Millisecond,
BufferSize: 100,
}
wb := NewWriteBuffer(ctx, database, config)
defer wb.Close()
// Enqueue less than batch size
for i := 0; i < 3; i++ {
wb.Enqueue(topicId, uuid.NewString(), "test message", 0)
}
// Wait for time-based flush
time.Sleep(150 * time.Millisecond)
// Verify messages were inserted
var count int
err = sqliteDb.Database.Get(&count, "SELECT COUNT(*) FROM subscriber_messages WHERE topic_id = ?", topicId)
require.NoError(t, err)
require.Equal(t, 3, count, "expected 3 messages to be flushed by timer")
})
}
func TestWriteBuffer_GracefulClose(t *testing.T) {
t.Run("flushes remaining messages on close", func(t *testing.T) {
dbName := "test_wb_close_" + uuid.NewString()[:8]
sqliteDb, cleanup := setupTestDB(t, dbName)
defer cleanup()
defer removeTestDB(dbName)
ctx, cancel := context.WithCancel(context.Background())
database := newDb(sqliteDb)
// Create topic and subscriber
topicId := uuid.New()
subscriberId := uuid.New()
_, err := sqliteDb.Database.Exec("INSERT INTO topics (id, name) VALUES (?, ?)", topicId, "test-topic")
require.NoError(t, err)
_, err = sqliteDb.Database.Exec(
"INSERT INTO topic_subscribers (id, topic_id, name, option) VALUES (?, ?, ?, ?)",
subscriberId, topicId, "test-subscriber", `{"max_attempts":3,"visibility_duration":"30s"}`,
)
require.NoError(t, err)
config := WriteBufferConfig{
BatchSize: 100, // Large batch - won't be reached
FlushInterval: 10 * time.Second, // Long interval - won't trigger
BufferSize: 100,
}
wb := NewWriteBuffer(ctx, database, config)
// Enqueue messages
for i := 0; i < 7; i++ {
wb.Enqueue(topicId, uuid.NewString(), "test message", 0)
}
// Small delay to ensure messages are in the channel
time.Sleep(10 * time.Millisecond)
// Close should flush remaining (cancel first, then Close waits for goroutine)
cancel()
wb.Close()
// Delay for flush to complete
time.Sleep(100 * time.Millisecond)
// Verify messages were inserted (may vary slightly due to timing)
var count int
err = sqliteDb.Database.Get(&count, "SELECT COUNT(*) FROM subscriber_messages WHERE topic_id = ?", topicId)
require.NoError(t, err)
require.GreaterOrEqual(t, count, 5, "most messages should be flushed on close")
})
}
func TestWriteBuffer_MultiTopic(t *testing.T) {
t.Run("groups messages by topic correctly", func(t *testing.T) {
dbName := "test_wb_multi_" + uuid.NewString()[:8]
sqliteDb, cleanup := setupTestDB(t, dbName)
defer cleanup()
defer removeTestDB(dbName)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
database := newDb(sqliteDb)
// Create two topics with subscribers
topic1Id := uuid.New()
topic2Id := uuid.New()
sub1Id := uuid.New()
sub2Id := uuid.New()
_, err := sqliteDb.Database.Exec("INSERT INTO topics (id, name) VALUES (?, ?)", topic1Id, "topic-1")
require.NoError(t, err)
_, err = sqliteDb.Database.Exec("INSERT INTO topics (id, name) VALUES (?, ?)", topic2Id, "topic-2")
require.NoError(t, err)
_, err = sqliteDb.Database.Exec(
"INSERT INTO topic_subscribers (id, topic_id, name, option) VALUES (?, ?, ?, ?)",
sub1Id, topic1Id, "sub-1", `{"max_attempts":3,"visibility_duration":"30s"}`,
)
require.NoError(t, err)
_, err = sqliteDb.Database.Exec(
"INSERT INTO topic_subscribers (id, topic_id, name, option) VALUES (?, ?, ?, ?)",
sub2Id, topic2Id, "sub-2", `{"max_attempts":3,"visibility_duration":"30s"}`,
)
require.NoError(t, err)
config := WriteBufferConfig{
BatchSize: 10,
FlushInterval: 50 * time.Millisecond,
BufferSize: 100,
}
wb := NewWriteBuffer(ctx, database, config)
defer wb.Close()
// Enqueue to both topics
for i := 0; i < 3; i++ {
wb.Enqueue(topic1Id, uuid.NewString(), "topic1 message", 0)
wb.Enqueue(topic2Id, uuid.NewString(), "topic2 message", 0)
}
// Wait for flush
time.Sleep(150 * time.Millisecond)
// Verify messages per topic
var count1, count2 int
err = sqliteDb.Database.Get(&count1, "SELECT COUNT(*) FROM subscriber_messages WHERE topic_id = ?", topic1Id)
require.NoError(t, err)
err = sqliteDb.Database.Get(&count2, "SELECT COUNT(*) FROM subscriber_messages WHERE topic_id = ?", topic2Id)
require.NoError(t, err)
require.Equal(t, 3, count1, "expected 3 messages for topic 1")
require.Equal(t, 3, count2, "expected 3 messages for topic 2")
})
}
func TestWriteBuffer_Concurrent(t *testing.T) {
t.Run("handles concurrent enqueue safely", func(t *testing.T) {
dbName := "test_wb_conc_" + uuid.NewString()[:8]
sqliteDb, cleanup := setupTestDB(t, dbName)
defer cleanup()
defer removeTestDB(dbName)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
database := newDb(sqliteDb)
// Create topic and subscriber
topicId := uuid.New()
subscriberId := uuid.New()
_, err := sqliteDb.Database.Exec("INSERT INTO topics (id, name) VALUES (?, ?)", topicId, "test-topic")
require.NoError(t, err)
_, err = sqliteDb.Database.Exec(
"INSERT INTO topic_subscribers (id, topic_id, name, option) VALUES (?, ?, ?, ?)",
subscriberId, topicId, "test-subscriber", `{"max_attempts":3,"visibility_duration":"30s"}`,
)
require.NoError(t, err)
config := WriteBufferConfig{
BatchSize: 50,
FlushInterval: 50 * time.Millisecond,
BufferSize: 1000,
}
wb := NewWriteBuffer(ctx, database, config)
// Concurrent producers
var wg sync.WaitGroup
msgCount := 100
goroutines := 10
for g := 0; g < goroutines; g++ {
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < msgCount/goroutines; i++ {
wb.Enqueue(topicId, uuid.NewString(), "concurrent message", 0)
}
}()
}
wg.Wait()
wb.Close()
// Small delay for final flush
time.Sleep(100 * time.Millisecond)
// Verify all messages were inserted (may have slight variations due to batch timing)
var count int
err = sqliteDb.Database.Get(&count, "SELECT COUNT(*) FROM subscriber_messages WHERE topic_id = ?", topicId)
require.NoError(t, err)
require.GreaterOrEqual(t, count, msgCount, "expected at least all concurrent messages to be flushed")
})
}
// Helper to remove test database files
func removeTestDB(dbName string) {
removeTestDBFiles(dbName)
}
// runBlockQueueTestWithBuffer is a helper for tests that need full BlockQueue with WriteBuffer
func runBlockQueueTestWithBuffer(t *testing.T, test func(bq *BlockQueue[chan bqio.ResponseMessages], sqliteDb *sqlite.SQLite)) {
dbName := "test_bq_" + uuid.NewString()[:8]
sqliteDb, cleanup := setupTestDB(t, dbName)
defer cleanup()
defer removeTestDB(dbName)
bq := New(sqliteDb, BlockQueueOption{
WriteBufferConfig: WriteBufferConfig{
BatchSize: 10,
FlushInterval: 10 * time.Millisecond,
BufferSize: 1000,
},
CheckpointInterval: 5 * time.Second,
})
test(bq, sqliteDb)
bq.Close()
}