Debian Codegraph @

exp/lmdbsync/handler.go

raw symbols SCIP
1 package lmdbsync
2
3 import (
4 "errors"
5 "math"
6 "math/rand"
7 "time"
8
9 "golang.org/x/net/context"
10
11 "github.com/bmatsuo/lmdb-go/lmdb"
12 )
13
14 // Handler can intercept errors returned by a transaction and handle them in an
15 // application-specific way, including by resizing the environment and retrying
16 // the transaction by returning ErrTxnRetry.
17 type Handler interface {
18 HandleTxnErr(ctx context.Context, env *Env, err error) (context.Context, error)
19 }
20
21 // HandlerChain is a Handler implementation that iteratively calls each handler
22 // in the underlying slice when handling an error.
23 type HandlerChain []Handler
24
25 // HandleTxnErr implements the Handler interface. Each handler in c processes
26 // the context.Context and error returned by the previous handler.
27 func (c HandlerChain) HandleTxnErr(ctx context.Context, env *Env, err error) (context.Context, error) {
28 for _, h := range c {
29 ctx, err = h.HandleTxnErr(ctx, env, err)
30 }
31 return ctx, err
32 }
33
34 // Append returns a new HandlerChain that will evaluate h in sequence after the
35 // Handlers already in C are evaluated. Append does not modify the storage
36 // undelying c.
37 func (c HandlerChain) Append(h ...Handler) HandlerChain {
38 _c := make(HandlerChain, len(c)+len(h))
39 copy(_c, c)
40 copy(_c[len(c):], h)
41 return _c
42 }
43
44 // MapResizedHandler returns a Handler that transparently adopts map sizes set
45 // by external processes and retries any transactions that failed to start
46 // because of lmdb.MapResized.
47 //
48 // If the database is growing too rapidly and maxRetry consecutive transactions
49 // fail due to lmdb.MapResized then the Handler returned by MapResizedHandler
50 // gives up and returns the lmdb.MapResized error to the caller. Delay will be
51 // called before each call to Env.SetMapSize to insert an optional delay.
52 //
53 // Open transactions must not directly create new (non-child) transactions when
54 // using MapResizedHandler or the environment will deadlock.
55 func MapResizedHandler(maxRetry int, delay DelayFunc) Handler {
56 if maxRetry == 0 {
57 maxRetry = MapResizedDefaultRetry
58 }
59 if delay == nil {
60 delay = MapResizedDefaultDelay
61 }
62 return &resizedHandler{
63 MaxRetry: maxRetry,
64 Delay: delay,
65 }
66 }
67
68 // MapResizedDefaultRetry is the default number of attempts MapResizedHandler
69 // will make adopt a new map size when lmdb.MapResized is encountered
70 // repeatedly.
71 var MapResizedDefaultRetry = 2
72
73 // DelayFunc takes as input the number of previous attempts and returns the
74 // delay before making another attempt.
75 type DelayFunc func(attempt int) time.Duration
76
77 // ExponentialBackoff returns a function that delays each attempt by random
78 // number between 0 and the minimum of max and base*factor^attempt.
79 func ExponentialBackoff(base time.Duration, max time.Duration, factor float64) DelayFunc {
80 return func(attempt int) time.Duration {
81 _max := float64(base) * math.Pow(factor, float64(attempt))
82 _max = math.Min(_max, float64(max))
83 n := rand.Int63n(int64(_max))
84 return time.Duration(n)
85 }
86 }
87
88 // MapResizedDefaultDelay is the default DelayFunc when MapResizedHandler is
89 // passed a nil value.
90 var MapResizedDefaultDelay = ExponentialBackoff(time.Millisecond, 5*time.Millisecond, 2)
91
92 // MapFullFunc is a function for resizing a memory map after it has become
93 // full. The function receives the current map size as its argument and
94 // returns a new map size. The new size will only be applied if the second
95 // return value is true.
96 type MapFullFunc func(size int64) (int64, bool)
97
98 // MapFullHandler returns a Handler that retries updates which failed to commit
99 // due to lmdb.MapFull errors. When lmdb.MapFull is encountered fn is used to
100 // set a new new map size before opening a new transaction and executing the
101 // lmdb.TxnOp again.
102 //
103 // When using MapFullHandler it is important that updates are idempotent. An
104 // Env.Update that encounters lmdb.MapFull may execute its lmdb.TxnOp function
105 // multiple times before successfully committing it (or aborting).
106 //
107 // Open view transactions must not wait for updates to complete when using
108 // MapFullHandler or the environment will deadlock.
109 func MapFullHandler(fn MapFullFunc) Handler {
110 return &mapFullHandler{fn}
111 }
112
113 // ErrTxnRetry is returned by a Handler to have the Env retry the transaction.
114 var ErrTxnRetry = errors.New("lmdbsync: retry failed txn")
115
116 // TxnRunner is an interface for types that can run lmdb transactions.
117 // TxnRunner is satisfied by Env.
118 type TxnRunner interface {
119 RunTxn(flags uint, op lmdb.TxnOp) error
120 View(op lmdb.TxnOp) error
121 Update(op lmdb.TxnOp) error
122 UpdateLocked(op lmdb.TxnOp) error
123 WithHandler(h Handler) TxnRunner
124 }
125
126 type handlerRunner struct {
127 env *Env
128 h Handler
129 }
130
131 func (r *handlerRunner) WithHandler(h Handler) TxnRunner {
132 return &handlerRunner{
133 env: r.env,
134 h: HandlerChain{r.h, h},
135 }
136 }
137
138 func (r *handlerRunner) RunTxn(flags uint, op lmdb.TxnOp) error {
139 readonly := flags&lmdb.Readonly != 0
140 return r.env.runHandler(readonly, func() error { return r.env.RunTxn(flags, op) }, r.h)
141 }
142
143 func (r *handlerRunner) View(op lmdb.TxnOp) error {
144 return r.env.runHandler(true, func() error { return r.env.View(op) }, r.h)
145 }
146
147 func (r *handlerRunner) Update(op lmdb.TxnOp) error {
148 return r.env.runHandler(false, func() error { return r.env.Update(op) }, r.h)
149 }
150
151 func (r *handlerRunner) UpdateLocked(op lmdb.TxnOp) error {
152 return r.env.runHandler(false, func() error { return r.env.UpdateLocked(op) }, r.h)
153 }
154
155 type mapFullHandler struct {
156 fn MapFullFunc
157 }
158
159 func (h *mapFullHandler) HandleTxnErr(ctx context.Context, env *Env, err error) (context.Context, error) {
160 if !lmdb.IsMapFull(err) {
161 return ctx, err
162 }
163
164 newsize, ok := h.getNewSize(env)
165 if !ok {
166 return ctx, err
167 }
168 if env.setMapSize(newsize, 0) != nil {
169 return ctx, err
170 }
171
172 return ctx, ErrTxnRetry
173 }
174
175 func (h *mapFullHandler) getNewSize(env *Env) (int64, bool) {
176 info, err := env.Info()
177 if err != nil {
178 return 0, false
179 }
180 newsize, ok := h.fn(info.MapSize)
181 if !ok || newsize <= info.MapSize {
182 return 0, false
183 }
184 return newsize, true
185 }
186
187 type resizedHandlerKey int
188
189 type resizeRetryCount struct {
190 n int
191 }
192
193 func (r *resizeRetryCount) Get() int {
194 if r == nil {
195 return 0
196 }
197 return r.n
198 }
199
200 func (r *resizeRetryCount) Add(n int) *resizeRetryCount {
201 if r == nil {
202 return &resizeRetryCount{1}
203 }
204 return &resizeRetryCount{r.n + 1}
205 }
206
207 func getResizedRetryCount(ctx context.Context) *resizeRetryCount {
208 v, _ := ctx.Value(resizedHandlerKey(0)).(*resizeRetryCount)
209 return v
210 }
211
212 func withResizedRetryCount(ctx context.Context, count *resizeRetryCount) context.Context {
213 return context.WithValue(ctx, resizedHandlerKey(0), count)
214 }
215
216 type resizedHandler struct {
217 MaxRetry int
218 Delay DelayFunc
219 }
220
221 func (h *resizedHandler) HandleTxnErr(ctx context.Context, env *Env, err error) (context.Context, error) {
222 if !lmdb.IsMapResized(err) {
223 ctx := context.WithValue(ctx, resizedHandlerKey(0), nil)
224 return ctx, err
225 }
226
227 count := getResizedRetryCount(ctx)
228 numRetry := count.Get()
229
230 // fail the transaction with MapResized error when too many attempts have
231 // been made.
232 maxRetry := h.MaxRetry
233 if maxRetry > 0 && numRetry >= maxRetry {
234 ctx := withResizedRetryCount(ctx, nil)
235 return ctx, err
236 }
237
238 ctx = withResizedRetryCount(ctx, count.Add(1))
239
240 delay := h.Delay(numRetry)
241 err = env.setMapSize(0, delay)
242 if err != nil {
243 return ctx, err
244 }
245 return ctx, ErrTxnRetry
246 }