/
transaction.go
93 lines (87 loc) 路 2.68 KB
/
transaction.go
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
package transaction
import (
"math"
"math/rand"
"sort"
"sync"
)
// transaction defines business transaction
type transaction struct {
amount float64 `gopium:"memory_pack,struct_annotate_comment,add_tag_group_force"`
serial uint64 `gopium:"memory_pack,struct_annotate_comment,add_tag_group_force"`
discount float64 `gopium:"memory_pack,struct_annotate_comment,add_tag_group_force"`
void bool `gopium:"memory_pack,struct_annotate_comment,add_tag_group_force"`
skip bool `gopium:"memory_pack,struct_annotate_comment,add_tag_group_force"`
} // struct size: 26 bytes; struct align: 8 bytes; struct aligned size: 32 bytes; - 馃尯 gopium @1pkg
// aggregate defines compressed set of transactions
type aggregate struct {
total float64
} // struct size: 8 bytes; struct align: 8 bytes; struct aligned size: 8 bytes; - 馃尯 gopium @1pkg
// generate creates n pseudo random transactions
func generate(number uint) []transaction {
// generate n pseudo random transactions
transactions := make([]transaction, 0, number)
for i := 0; i < int(number); i++ {
transactions = append(transactions, transaction{
void: i%10 == 0,
amount: math.Abs(rand.Float64()),
serial: uint64(i) + 1,
skip: i%25 == 0,
discount: rand.Float64(),
})
}
// and shuffle them
for i := range transactions {
j := rand.Intn(i + 1)
transactions[i], transactions[j] = transactions[j], transactions[i]
}
return transactions
}
// normalize preprocess list of transactions before compressing
func normalize(transactions []transaction) []transaction {
// filter and normalize transactions
normalized := make([]transaction, 0, len(transactions))
for _, trx := range transactions {
if trx.skip || trx.serial == 0 {
continue
}
if trx.void {
trx.amount = -trx.amount
}
trx.discount = math.Abs(trx.discount)
normalized = append(normalized, trx)
}
// sort transactions by serial
sort.Slice(normalized, func(i int, j int) bool {
return normalized[i].serial < normalized[j].serial
})
return normalized
}
// compress builds single aggregate from provided normalized transactions list
func compress(transactions []transaction) aggregate {
var amount, discont aggregate
var wg sync.WaitGroup
wg.Add(2)
// run amount calculation in separate goroutine
go func() {
for _, tr := range transactions {
amount.total += tr.amount
}
wg.Done()
}()
// run discounts calculation in separate goroutine
go func() {
for _, tr := range transactions {
discont.total += tr.discount
}
wg.Done()
}()
wg.Wait()
// apply discount logic to final aggregate
if discont.total > amount.total/2 {
discont.total = amount.total / 2
}
result := amount
result.total -= discont.total
return result
}