/
processUniqueProduct.go
197 lines (176 loc) · 5.43 KB
/
processUniqueProduct.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
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
package main
import (
"database/sql"
"encoding/json"
"github.com/beeker1121/goque"
"github.com/united-manufacturing-hub/united-manufacturing-hub/internal"
"go.uber.org/zap"
"time"
)
type uniqueProductQueue struct {
DBAssetID uint32
BeginTimestampMs uint64 `json:"begin_timestamp_ms"`
EndTimestampMs uint64 `json:"end_timestamp_ms"`
ProductID int32 `json:"productID"`
IsScrap bool `json:"isScrap"`
UniqueProductAlternativeID string `json:"uniqueProductAlternativeID"`
}
type uniqueProduct struct {
BeginTimestampMs uint64 `json:"begin_timestamp_ms"`
EndTimestampMs uint64 `json:"end_timestamp_ms"`
ProductName string `json:"productID"`
IsScrap bool `json:"isScrap"`
UniqueProductAlternativeID string `json:"uniqueProductAlternativeID"`
}
type UniqueProductHandler struct {
priorityQueue *goque.PriorityQueue
shutdown bool
}
func NewUniqueProductHandler() (handler *UniqueProductHandler) {
const queuePathDB = "/data/UniqueProduct"
var priorityQueue *goque.PriorityQueue
var err error
priorityQueue, err = SetupQueue(queuePathDB)
if err != nil {
zap.S().Errorf("Error setting up remote queue (%s)", queuePathDB, err)
zap.S().Errorf("err: %s", err)
ShutdownApplicationGraceful()
panic("Failed to setup queue, exiting !")
}
handler = &UniqueProductHandler{
priorityQueue: priorityQueue,
shutdown: false,
}
return
}
func (r UniqueProductHandler) reportLength() {
for !r.shutdown {
time.Sleep(10 * time.Second)
if r.priorityQueue.Length() > 0 {
zap.S().Debugf("UniqueProductHandler queue length: %d", r.priorityQueue.Length())
}
}
}
func (r UniqueProductHandler) Setup() {
go r.reportLength()
go r.process()
}
func (r UniqueProductHandler) process() {
var items []*goque.PriorityItem
loopsWithError := int64(0)
for !r.shutdown {
items = r.dequeue()
if len(items) == 0 {
time.Sleep(10 * time.Millisecond)
continue
}
faultyItems, err := storeItemsIntoDatabaseUniqueProduct(items, 0)
// Empty the array, without de-allocating memory
items = items[:0]
for _, faultyItem := range faultyItems {
var prio uint8
prio = faultyItem.Priority + 1
if faultyItem.Priority >= 255 {
prio = 254
}
r.enqueue(faultyItem.Value, prio)
}
if err != nil {
zap.S().Errorf("err: %s", err)
switch GetPostgresErrorRecoveryOptions(err) {
case Unrecoverable:
ShutdownApplicationGraceful()
}
}
if err != nil || len(faultyItems) > 0 {
loopsWithError += 1
} else {
loopsWithError = 0
}
internal.SleepBackedOff(loopsWithError, 10000*time.Nanosecond, 1000*time.Millisecond)
}
}
func (r UniqueProductHandler) dequeue() (items []*goque.PriorityItem) {
if r.priorityQueue.Length() > 0 {
item, err := r.priorityQueue.Dequeue()
if err != nil {
return
}
items = append(items, item)
for true {
nextItem, err := r.priorityQueue.DequeueByPriority(item.Priority)
if err != nil {
break
}
items = append(items, nextItem)
}
}
return
}
func (r UniqueProductHandler) enqueue(bytes []byte, priority uint8) {
_, err := r.priorityQueue.Enqueue(priority, bytes)
if err != nil {
zap.S().Warnf("Failed to enqueue item", bytes, err)
return
}
}
func (r UniqueProductHandler) Shutdown() (err error) {
zap.S().Warnf("[UniqueProductHandler] shutting down, Queue length: %d", r.priorityQueue.Length())
r.shutdown = true
err = CloseQueue(r.priorityQueue)
return
}
func (r UniqueProductHandler) EnqueueMQTT(customerID string, location string, assetID string, payload []byte, recursionDepth int64) {
zap.S().Debugf("[UniqueProductHandler]")
var parsedPayload uniqueProduct
err := json.Unmarshal(payload, &parsedPayload)
if err != nil {
zap.S().Errorf("json.Unmarshal failed", err, payload)
return
}
DBassetID, success := GetAssetID(customerID, location, assetID, 0)
if !success {
go func() {
if r.shutdown {
storedRawMQTTHandler.EnqueueMQTT(customerID, location, assetID, payload, Prefix.AddOrder, recursionDepth+1)
} else {
internal.SleepBackedOff(recursionDepth, 10000*time.Nanosecond, 1000*time.Millisecond)
r.EnqueueMQTT(customerID, location, assetID, payload, recursionDepth+1)
}
}()
return
}
productID, err, success := GetProductID(DBassetID, parsedPayload.ProductName, 0)
if err == sql.ErrNoRows || !success {
zap.S().Errorf("Product does not exist yet", DBassetID, parsedPayload.ProductName)
go func() {
if r.shutdown {
storedRawMQTTHandler.EnqueueMQTT(customerID, location, assetID, payload, Prefix.UniqueProduct, recursionDepth+1)
} else {
internal.SleepBackedOff(recursionDepth, 10000*time.Nanosecond, 1000*time.Millisecond)
r.EnqueueMQTT(customerID, location, assetID, payload, recursionDepth+1)
}
}()
return
} else if err != nil { // never executed
PGErrorHandling("GetProductID db.QueryRow()", err)
}
newObject := uniqueProductQueue{
DBAssetID: DBassetID,
BeginTimestampMs: parsedPayload.BeginTimestampMs,
EndTimestampMs: parsedPayload.EndTimestampMs,
ProductID: productID,
IsScrap: parsedPayload.IsScrap,
UniqueProductAlternativeID: parsedPayload.UniqueProductAlternativeID,
}
if !ValidateStruct(newObject) {
zap.S().Errorf("Failed to validate struct of type uniqueProductQueue", newObject)
return
}
marshal, err := json.Marshal(newObject)
if err != nil {
return
}
r.enqueue(marshal, 0)
return
}