-
-
Notifications
You must be signed in to change notification settings - Fork 149
Expand file tree
/
Copy pathtransaction_benchmark_test.go
More file actions
356 lines (303 loc) · 10 KB
/
Copy pathtransaction_benchmark_test.go
File metadata and controls
356 lines (303 loc) · 10 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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
/*
Copyright 2024 Blnk Finance Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package blnk
import (
"context"
"encoding/json"
"fmt"
"math/big"
"testing"
"time"
"github.com/blnkfinance/blnk/config"
"github.com/blnkfinance/blnk/database/mocks"
"github.com/blnkfinance/blnk/model"
"github.com/stretchr/testify/mock"
)
// setupBenchmarkConfig creates and stores a test configuration
func setupBenchmarkConfig() *config.Configuration {
cnf := &config.Configuration{
Redis: config.RedisConfig{
Dns: "localhost:6379",
},
Queue: config.QueueConfig{
WebhookQueue: "webhook_queue",
TransactionQueue: "transaction_queue",
IndexQueue: "index_queue",
InflightExpiryQueue: "inflight_expiry_queue",
NumberOfQueues: 1,
},
Server: config.ServerConfig{SecretKey: "benchmark-secret-key"},
Transaction: config.TransactionConfig{
BatchSize: 100000,
MaxQueueSize: 1000,
MaxWorkers: 10,
LockDuration: 30 * time.Second,
IndexQueuePrefix: "transactions",
},
}
config.ConfigStore.Store(cnf)
return cnf
}
// createTestBalance creates a test balance with the given ID and amount
func createTestBalance(id string, balance int64) *model.Balance {
return &model.Balance{
BalanceID: id,
Balance: big.NewInt(balance),
CreditBalance: big.NewInt(balance),
DebitBalance: big.NewInt(0),
InflightBalance: big.NewInt(0),
InflightCreditBalance: big.NewInt(0),
InflightDebitBalance: big.NewInt(0),
Currency: "USD",
LedgerID: "ledger-001",
CreatedAt: time.Now(),
Version: 1,
}
}
// createTestTransaction creates a test transaction
func createTestTransaction(source, destination, reference string, amount float64) *model.Transaction {
return &model.Transaction{
Reference: reference,
Source: source,
Destination: destination,
Amount: amount,
Precision: 100,
Currency: "USD",
AllowOverdraft: false,
}
}
// setupMockDataSource creates a mock data source with preset responses for benchmarks
func setupMockDataSource() *mocks.MockDataSource {
mockDS := new(mocks.MockDataSource)
sourceBalance := createTestBalance("source-balance-001", 100000)
destBalance := createTestBalance("dest-balance-001", 0)
mockDS.On("TransactionExistsByRef", mock.Anything, mock.Anything).Return(false, nil)
mockDS.On("GetBalanceByIDLite", "source-balance-001").Return(sourceBalance, nil)
mockDS.On("GetBalanceByIDLite", "dest-balance-001").Return(destBalance, nil)
mockDS.On("GetBalanceByID", mock.Anything, mock.Anything, mock.Anything).Return(sourceBalance, nil)
mockDS.On("RecordTransactionWithBalancesAndOutbox", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).
Return(&model.Transaction{TransactionID: "txn-001", Status: "APPLIED"}, nil)
mockDS.On("RecordTransaction", mock.Anything, mock.Anything).
Return(&model.Transaction{TransactionID: "txn-001", Status: "QUEUED"}, nil)
mockDS.On("GetBalanceMonitors", mock.Anything).Return([]model.BalanceMonitor{}, nil)
return mockDS
}
// BenchmarkConfigFetch measures the overhead of calling config.Fetch() repeatedly
// This represents the OLD approach before our optimization
func BenchmarkConfigFetch(b *testing.B) {
setupBenchmarkConfig()
for b.Loop() {
cfg, err := config.Fetch()
if err != nil {
b.Fatal(err)
}
_ = cfg.Transaction.LockDuration
}
}
// BenchmarkConfigCached measures direct config access
// This represents the NEW approach after our optimization
func BenchmarkConfigCached(b *testing.B) {
cfg := setupBenchmarkConfig()
for b.Loop() {
_ = cfg.Transaction.LockDuration
}
}
// BenchmarkTransactionMarshal measures JSON serialization overhead
func BenchmarkTransactionMarshal(b *testing.B) {
txn := createTestTransaction("source-001", "dest-001", "ref-001", 100.00)
txn.TransactionID = "txn-benchmark-001"
txn.CreatedAt = time.Now()
txn.MetaData = map[string]interface{}{
"order_id": "order-12345",
"customer_id": "cust-67890",
"description": "Payment for services",
}
for b.Loop() {
_, err := json.Marshal(txn)
if err != nil {
b.Fatal(err)
}
}
}
// BenchmarkTransactionUnmarshal measures JSON deserialization overhead
func BenchmarkTransactionUnmarshal(b *testing.B) {
txn := createTestTransaction("source-001", "dest-001", "ref-001", 100.00)
txn.TransactionID = "txn-benchmark-001"
txn.CreatedAt = time.Now()
txn.MetaData = map[string]interface{}{
"order_id": "order-12345",
"customer_id": "cust-67890",
"description": "Payment for services",
}
data, _ := json.Marshal(txn)
for b.Loop() {
var result model.Transaction
err := json.Unmarshal(data, &result)
if err != nil {
b.Fatal(err)
}
}
}
// BenchmarkApplyTransactionToBalances measures in-memory balance calculation
func BenchmarkApplyTransactionToBalances(b *testing.B) {
setupBenchmarkConfig()
txn := createTestTransaction("source-001", "dest-001", "ref-001", 100.00)
txn.PreciseAmount = big.NewInt(10000)
txn.Precision = 100
for b.Loop() {
sourceBalance := createTestBalance("source-001", 100000)
destBalance := createTestBalance("dest-001", 0)
err := model.UpdateBalances(txn, sourceBalance, destBalance)
if err != nil {
b.Fatal(err)
}
}
}
// BenchmarkApplyTransactionToBalancesParallel measures parallel balance calculations
func BenchmarkApplyTransactionToBalancesParallel(b *testing.B) {
setupBenchmarkConfig()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
txn := createTestTransaction("source-001", "dest-001", "ref-001", 100.00)
txn.PreciseAmount = big.NewInt(10000)
txn.Precision = 100
sourceBalance := createTestBalance("source-001", 100000)
destBalance := createTestBalance("dest-001", 0)
err := model.UpdateBalances(txn, sourceBalance, destBalance)
if err != nil {
b.Fatal(err)
}
}
})
}
// BenchmarkValidateTxn measures transaction reference validation
func BenchmarkValidateTxn(b *testing.B) {
setupBenchmarkConfig()
mockDS := setupMockDataSource()
blnkInstance := &Blnk{
datasource: mockDS,
config: setupBenchmarkConfig(),
}
ctx := context.Background()
for i := 0; b.Loop(); i++ {
txn := createTestTransaction("source-001", "dest-001", fmt.Sprintf("ref-%d", i), 100.00)
err := blnkInstance.validateTxn(ctx, txn)
if err != nil {
b.Fatal(err)
}
}
}
// BenchmarkHashBalanceID measures the hash function used for queue assignment
func BenchmarkHashBalanceID(b *testing.B) {
balanceID := "bln_abc123def456ghi789"
for b.Loop() {
_ = hashBalanceID(balanceID)
}
}
// BenchmarkHashBalanceIDVaried measures hashing with different balance IDs
func BenchmarkHashBalanceIDVaried(b *testing.B) {
balanceIDs := make([]string, 1000)
for i := 0; i < 1000; i++ {
balanceIDs[i] = fmt.Sprintf("bln_%d", i)
}
for i := 0; b.Loop(); i++ {
_ = hashBalanceID(balanceIDs[i%1000])
}
}
// BenchmarkTransactionHashTxn measures transaction hash generation
func BenchmarkTransactionHashTxn(b *testing.B) {
txn := createTestTransaction("source-001", "dest-001", "ref-001", 100.00)
txn.TransactionID = "txn-benchmark-001"
txn.CreatedAt = time.Now()
txn.PreciseAmount = big.NewInt(10000)
for b.Loop() {
_ = txn.HashTxn()
}
}
// BenchmarkApplyPrecision measures precision application to transactions
func BenchmarkApplyPrecision(b *testing.B) {
for b.Loop() {
txn := createTestTransaction("source-001", "dest-001", "ref-001", 100.50)
txn.Precision = 100
_ = model.ApplyPrecision(txn)
}
}
// BenchmarkSetTransactionMetadata measures transaction metadata setup
func BenchmarkSetTransactionMetadata(b *testing.B) {
for i := 0; b.Loop(); i++ {
txn := createTestTransaction("source-001", "dest-001", fmt.Sprintf("ref-%d", i), 100.00)
setTransactionMetadata(txn)
}
}
// BenchmarkBigIntOperations measures big.Int arithmetic used in balance calculations
func BenchmarkBigIntOperations(b *testing.B) {
amount := big.NewInt(10000)
balance := big.NewInt(100000)
for b.Loop() {
result := new(big.Int)
result.Sub(balance, amount)
}
}
// BenchmarkBigIntOperationsParallel measures parallel big.Int operations
func BenchmarkBigIntOperationsParallel(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
amount := big.NewInt(10000)
balance := big.NewInt(100000)
for pb.Next() {
result := new(big.Int)
result.Sub(balance, amount)
}
})
}
// BenchmarkGenerateUUID measures UUID generation overhead
func BenchmarkGenerateUUID(b *testing.B) {
for b.Loop() {
_ = model.GenerateUUIDWithSuffix("txn")
}
}
// BenchmarkGenerateUUIDParallel measures parallel UUID generation
func BenchmarkGenerateUUIDParallel(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
_ = model.GenerateUUIDWithSuffix("txn")
}
})
}
// BenchmarkIsInflightTransaction measures the inflight status check
func BenchmarkIsInflightTransaction(b *testing.B) {
txnInflight := &model.Transaction{
Status: StatusInflight,
MetaData: map[string]interface{}{"inflight": true},
}
txnQueued := &model.Transaction{
Status: StatusQueued,
MetaData: map[string]interface{}{"inflight": true},
}
txnApplied := &model.Transaction{
Status: StatusApplied,
}
transactions := []*model.Transaction{txnInflight, txnQueued, txnApplied}
for i := 0; b.Loop(); i++ {
_ = IsInflightTransaction(transactions[i%3])
}
}
// BenchmarkCreateQueueCopy measures queue copy creation for split transactions
func BenchmarkCreateQueueCopy(b *testing.B) {
txn := createTestTransaction("source-001", "dest-001", "ref-001", 100.00)
txn.TransactionID = "txn-original-001"
txn.CreatedAt = time.Now()
txn.PreciseAmount = big.NewInt(10000)
for b.Loop() {
_ = createQueueCopy(txn, "ref-original")
}
}