-
Notifications
You must be signed in to change notification settings - Fork 2
/
best_effort_unit.go
287 lines (248 loc) · 7.57 KB
/
best_effort_unit.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
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
/* Copyright 2019 Freerware
*
* 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 work
import (
"errors"
"fmt"
"go.uber.org/multierr"
"go.uber.org/zap"
)
var (
bestEffortUnitTag = map[string]string{
"unit_type": "best_effort",
}
)
type bestEffortUnit struct {
unit
mappers map[TypeName]DataMapper
successfulInserts map[TypeName][]interface{}
successfulUpdates map[TypeName][]interface{}
successfulDeletes map[TypeName][]interface{}
successfulInsertCount int
successfulUpdateCount int
successfulDeleteCount int
}
// NewBestEffortUnit constructs a work unit that when faced
// with adversity, attempts rollback a single time.
func NewBestEffortUnit(
mappers map[TypeName]DataMapper, options ...Option) (Unit, error) {
if len(mappers) < 1 {
return nil, errors.New("must have at least one data mapper")
}
var o UnitOptions
for _, applyOption := range options {
applyOption(&o)
}
u := bestEffortUnit{
unit: newUnit(o),
mappers: mappers,
successfulInserts: make(map[TypeName][]interface{}),
successfulUpdates: make(map[TypeName][]interface{}),
successfulDeletes: make(map[TypeName][]interface{}),
}
if u.hasScope() {
u.scope = u.scope.Tagged(bestEffortUnitTag)
}
return &u, nil
}
func (u *bestEffortUnit) rollbackInserts() (err error) {
//delete successfully inserted entities.
u.logDebug("attempting to rollback inserted entities",
zap.Int("count", u.successfulInsertCount))
for typeName, inserts := range u.successfulInserts {
if err = u.mappers[typeName].Delete(inserts...); err != nil {
u.logError(err.Error(), zap.String("typeName", typeName.String()))
return
}
}
return nil
}
func (u *bestEffortUnit) rollbackUpdates() (err error) {
//reapply previously registered state for the entities.
u.logDebug("attempting to rollback updated entities",
zap.Int("count", u.successfulUpdateCount))
for typeName, r := range u.registered {
if err = u.mappers[typeName].Update(r...); err != nil {
u.logError(err.Error(), zap.String("typeName", typeName.String()))
return
}
}
return
}
func (u *bestEffortUnit) rollbackDeletes() (err error) {
//reinsert successfully deleted entities.
u.logDebug("attempting to rollback deleted entities",
zap.Int("count", u.successfulDeleteCount))
for typeName, deletes := range u.successfulDeletes {
if err = u.mappers[typeName].Insert(deletes...); err != nil {
u.logError(err.Error(), zap.String("typeName", typeName.String()))
return
}
}
return
}
func (u *bestEffortUnit) rollback() (err error) {
//setup timer.
stop := u.startTimer(rollback)
//log and capture metrics if there is a panic.
defer func() {
stop()
if r := recover(); r != nil {
msg := "panic: unable to rollback work unit"
u.logError(msg, zap.String("panic", fmt.Sprintf("%v", r)))
u.incrementCounter(rollbackFailure, 1)
panic(r)
}
if err != nil {
u.incrementCounter(rollbackFailure, 1)
} else {
u.incrementCounter(rollbackSuccess, 1)
}
}()
if err = u.rollbackDeletes(); err != nil {
return
}
if err = u.rollbackUpdates(); err != nil {
return
}
if err = u.rollbackInserts(); err != nil {
return
}
return
}
func (u *bestEffortUnit) applyInserts() (err error) {
u.logDebug("attempting to insert entities", zap.Int("count", len(u.additions)))
for typeName, additions := range u.additions {
if err = u.mappers[typeName].Insert(additions...); err != nil {
err = multierr.Combine(err, u.rollback())
u.logError(err.Error(), zap.String("typeName", typeName.String()))
return
}
if _, ok := u.successfulInserts[typeName]; !ok {
u.successfulInserts[typeName] = []interface{}{}
}
u.successfulInserts[typeName] =
append(u.successfulInserts[typeName], additions...)
u.successfulInsertCount = u.successfulInsertCount + len(additions)
}
return
}
func (u *bestEffortUnit) applyUpdates() (err error) {
u.logDebug("attempting to update entities", zap.Int("count", len(u.alterations)))
for typeName, alterations := range u.alterations {
if err = u.mappers[typeName].Update(alterations...); err != nil {
err = multierr.Combine(err, u.rollback())
u.logError(err.Error(), zap.String("typeName", typeName.String()))
return
}
if _, ok := u.successfulUpdates[typeName]; !ok {
u.successfulUpdates[typeName] = []interface{}{}
}
u.successfulUpdates[typeName] =
append(u.successfulUpdates[typeName], alterations...)
u.successfulUpdateCount = u.successfulUpdateCount + len(alterations)
}
return
}
func (u *bestEffortUnit) applyDeletes() (err error) {
u.logDebug("attempting to remove entities", zap.Int("count", len(u.removals)))
for typeName, removals := range u.removals {
if err = u.mappers[typeName].Delete(removals...); err != nil {
err = multierr.Combine(err, u.rollback())
u.logError(err.Error(), zap.String("typeName", typeName.String()))
return
}
if _, ok := u.successfulDeletes[typeName]; !ok {
u.successfulDeletes[typeName] = []interface{}{}
}
u.successfulDeletes[typeName] =
append(u.successfulDeletes[typeName], removals...)
u.successfulDeleteCount = u.successfulDeleteCount + len(removals)
}
return
}
// Register tracks the provided entities as clean.
func (u *bestEffortUnit) Register(entities ...interface{}) error {
c := func(t TypeName) bool {
_, ok := u.mappers[t]
return ok
}
return u.register(c, entities...)
}
// Add marks the provided entities as new additions.
func (u *bestEffortUnit) Add(entities ...interface{}) error {
c := func(t TypeName) bool {
_, ok := u.mappers[t]
return ok
}
return u.add(c, entities...)
}
// Alter marks the provided entities as modifications.
func (u *bestEffortUnit) Alter(entities ...interface{}) error {
c := func(t TypeName) bool {
_, ok := u.mappers[t]
return ok
}
return u.alter(c, entities...)
}
// Remove marks the provided entities as removals.
func (u *bestEffortUnit) Remove(entities ...interface{}) error {
c := func(t TypeName) bool {
_, ok := u.mappers[t]
return ok
}
return u.remove(c, entities...)
}
// Save commits the new additions, modifications, and removals
// within the work unit to a persistent store.
func (u *bestEffortUnit) Save() (err error) {
//setup timer.
stop := u.startTimer(save)
//rollback if there is a panic.
defer func() {
stop()
if r := recover(); r != nil {
err = multierr.Combine(
fmt.Errorf("panic: unable to save work unit\n%v", r), u.rollback())
u.logError("panic: unable to save work unit",
zap.String("panic", fmt.Sprintf("%v", r)))
panic(r)
}
if err == nil {
u.incrementCounter(saveSuccess, 1)
}
}()
//insert newly added entities.
if err = u.applyInserts(); err != nil {
return
}
//update altered entities.
if err = u.applyUpdates(); err != nil {
return
}
//delete removed entities.
if err = u.applyDeletes(); err != nil {
return
}
totalCount :=
u.additionCount + u.alterationCount + u.removalCount + u.registerCount
u.logInfo("successfully saved unit",
zap.Int("insertCount", u.additionCount),
zap.Int("updateCount", u.alterationCount),
zap.Int("deleteCount", u.removalCount),
zap.Int("registerCount", u.registerCount),
zap.Int("totalCount", totalCount))
return
}