Debian Codegraph @

api/v1/lib/extras/executor/callrules/callrules_generated.go

raw symbols SCIP
1 package callrules
2
3 // go generate -import github.com/mesos/mesos-go/api/v1/lib -import github.com/mesos/mesos-go/api/v1/lib/executor -type E:*executor.Call:&executor.Call{} -type Z:mesos.Response:&mesos.ResponseWrapper{}
4 // GENERATED CODE FOLLOWS; DO NOT EDIT.
5
6 import (
7 "context"
8 "fmt"
9 "sync"
10
11 "github.com/mesos/mesos-go/api/v1/lib"
12 "github.com/mesos/mesos-go/api/v1/lib/executor"
13 )
14
15 type (
16 evaler interface {
17 // Eval executes a filter, rule, or decorator function; if the returned event is nil then
18 // no additional rule evaluation should be processed for the event.
19 // Eval implementations should not modify the given event parameter (to avoid side effects).
20 // If changes to the event object are needed, the suggested approach is to make a copy,
21 // modify the copy, and pass the copy to the chain.
22 // Eval implementations SHOULD be safe to execute concurrently.
23 Eval(context.Context, *executor.Call, mesos.Response, error, Chain) (context.Context, *executor.Call, mesos.Response, error)
24 }
25
26 // Rule is the functional adaptation of evaler.
27 // A nil Rule is valid: it is Eval'd as a noop.
28 Rule func(context.Context, *executor.Call, mesos.Response, error, Chain) (context.Context, *executor.Call, mesos.Response, error)
29
30 // Chain is invoked by a Rule to continue processing an event. If the chain is not invoked,
31 // no additional rules are processed.
32 Chain func(context.Context, *executor.Call, mesos.Response, error) (context.Context, *executor.Call, mesos.Response, error)
33
34 // Rules is a list of rules to be processed, in order.
35 Rules []Rule
36
37 // ErrorList accumulates errors that occur while processing a Chain of Rules. Accumulated
38 // errors should be appended to the end of the list. An error list should never be empty.
39 // Callers should use the package Error() func to properly accumulate (and flatten) errors.
40 ErrorList []error
41 )
42
43 var (
44 _ = evaler(Rule(nil))
45 _ = evaler(Rules{})
46 )
47
48 // ChainIdentity is a Chain that returns the arguments as its results.
49 func ChainIdentity(ctx context.Context, e *executor.Call, z mesos.Response, err error) (context.Context, *executor.Call, mesos.Response, error) {
50 return ctx, e, z, err
51 }
52
53 // Eval is a convenience func that processes a nil Rule as a noop.
54 func (r Rule) Eval(ctx context.Context, e *executor.Call, z mesos.Response, err error, ch Chain) (context.Context, *executor.Call, mesos.Response, error) {
55 if r != nil {
56 return r(ctx, e, z, err, ch)
57 }
58 return ch(ctx, e, z, err)
59 }
60
61 // Eval is a Rule func that processes the set of all Rules. If there are no rules in the
62 // set then control is simply passed to the Chain.
63 func (rs Rules) Eval(ctx context.Context, e *executor.Call, z mesos.Response, err error, ch Chain) (context.Context, *executor.Call, mesos.Response, error) {
64 return ch(rs.Chain()(ctx, e, z, err))
65 }
66
67 // Chain returns a Chain that evaluates the given Rules, in order, propagating the (context.Context, *executor.Call, error)
68 // from Rule to Rule. Chain is safe to invoke concurrently.
69 func (rs Rules) Chain() Chain {
70 if len(rs) == 0 {
71 return ChainIdentity
72 }
73 return func(ctx context.Context, e *executor.Call, z mesos.Response, err error) (context.Context, *executor.Call, mesos.Response, error) {
74 return rs[0].Eval(ctx, e, z, err, rs[1:].Chain())
75 }
76 }
77
78 // New is the semantic equivalent of Rules{r1, r2, ..., rn}.Eval and exists purely for convenience.
79 func New(rs ...Rule) Rule { return Rules(rs).Eval }
80
81 const msgNoErrors = "no errors"
82
83 // Error implements error; returns the message of the first error in the list.
84 func (es ErrorList) Error() string {
85 switch len(es) {
86 case 0:
87 return msgNoErrors
88 case 1:
89 return es[0].Error()
90 default:
91 return fmt.Sprintf("%s (and %d more errors)", es[0], len(es)-1)
92 }
93 }
94
95 // Error2 aggregates the given error params, returning nil if both are nil.
96 // Use Error2 to avoid the overhead of creating a slice when aggregating only 2 errors.
97 func Error2(a, b error) error {
98 if a == nil {
99 if b == nil {
100 return nil
101 }
102 if list, ok := b.(ErrorList); ok {
103 return flatten(list).Err()
104 }
105 return b
106 }
107 if b == nil {
108 if list, ok := a.(ErrorList); ok {
109 return flatten(list).Err()
110 }
111 return a
112 }
113 return Error(a, b)
114 }
115
116 // Err reduces an empty or singleton error list
117 func (es ErrorList) Err() error {
118 switch len(es) {
119 case 0:
120 return nil
121 case 1:
122 return es[0]
123 default:
124 return es
125 }
126 }
127
128 // IsErrorList returns true if err is a non-nil error list
129 func IsErrorList(err error) bool {
130 if err != nil {
131 _, ok := err.(ErrorList)
132 return ok
133 }
134 return false
135 }
136
137 // Error aggregates, and then flattens, a list of errors accrued during rule processing.
138 // Returns nil if the given list of errors is empty or contains all nil errors.
139 func Error(es ...error) error {
140 return flatten(es).Err()
141 }
142
143 func flatten(errors []error) ErrorList {
144 if errors == nil || len(errors) == 0 {
145 return nil
146 }
147 result := make([]error, 0, len(errors))
148 for _, err := range errors {
149 if err != nil {
150 if multi, ok := err.(ErrorList); ok {
151 result = append(result, flatten(multi)...)
152 } else {
153 result = append(result, err)
154 }
155 }
156 }
157 return ErrorList(result)
158 }
159
160 // TODO(jdef): other ideas for Rule decorators: When(func() bool), WhenNot(func() bool)
161
162 // If only executes the receiving rule if b is true; otherwise, the returned rule is a noop.
163 func (r Rule) If(b bool) Rule {
164 if b {
165 return r
166 }
167 return nil
168 }
169
170 // Unless only executes the receiving rule if b is false; otherwise, the returned rule is a noop.
171 func (r Rule) Unless(b bool) Rule {
172 if !b {
173 return r
174 }
175 return nil
176 }
177
178 // Once returns a Rule that executes the receiver only once.
179 func (r Rule) Once() Rule {
180 if r == nil {
181 return nil
182 }
183 var once sync.Once
184 return func(ctx context.Context, e *executor.Call, z mesos.Response, err error, ch Chain) (context.Context, *executor.Call, mesos.Response, error) {
185 ruleInvoked := false
186 once.Do(func() {
187 ctx, e, z, err = r(ctx, e, z, err, ch)
188 ruleInvoked = true
189 })
190 if !ruleInvoked {
191 ctx, e, z, err = ch(ctx, e, z, err)
192 }
193 return ctx, e, z, err
194 }
195 }
196
197 // UnlessDone returns a decorated rule that checks context.Done: if the context has been canceled then the rule chain
198 // is aborted and the context.Err is merged with the current error state.
199 // Returns nil (noop) if the receiving Rule is nil.
200 func (r Rule) UnlessDone() Rule {
201 if r == nil {
202 return nil
203 }
204 return func(ctx context.Context, e *executor.Call, z mesos.Response, err error, ch Chain) (context.Context, *executor.Call, mesos.Response, error) {
205 select {
206 case <-ctx.Done():
207 return ctx, e, z, Error2(err, ctx.Err())
208 default:
209 return r(ctx, e, z, err, ch)
210 }
211 }
212 }
213
214 type Overflow int
215
216 const (
217 // OverflowWait waits until the rule may execute, or the context is canceled.
218 OverflowWait Overflow = iota
219 // OverflowOtherwise skips over the decorated rule and invoke an alternative instead.
220 OverflowOtherwise
221 )
222
223 // RateLimit invokes the receiving Rule if a read of chan "p" succeeds (closed chan = no rate limit), otherwise proceeds
224 // according to the specified Overflow policy. May be useful, for example, when rate-limiting logged events.
225 // Returns nil (noop) if the receiver is nil, otherwise a nil chan will normally trigger an overflow.
226 // Panics when OverflowWait is specified with a nil chan, in order to prevent deadlock.
227 // A cancelled context will trigger the "otherwise" rule.
228 func (r Rule) RateLimit(p <-chan struct{}, over Overflow, otherwise Rule) Rule {
229 return limit(r, acquireChan(p), over, otherwise)
230 }
231
232 // acquireChan wraps a signal chan with a func that can be used with rateLimit.
233 // should only be called by rate limiting funcs (that implement deadlock avoidance).
234 func acquireChan(tokenCh <-chan struct{}) func(context.Context, bool) bool {
235 if tokenCh == nil {
236 // always false: acquire never succeeds; panic if told to block (to avoid deadlock)
237 return func(ctx context.Context, block bool) bool {
238 if block {
239 select {
240 case <-ctx.Done():
241 default:
242 panic("deadlock detected: block should never be true when the token chan is nil")
243 }
244 }
245 return false
246 }
247 }
248 return func(ctx context.Context, block bool) bool {
249 if block {
250 select {
251 case <-tokenCh:
252 // tie breaker prefers Done
253 select {
254 case <-ctx.Done():
255 default:
256 return true
257 }
258 case <-ctx.Done():
259 }
260 return false
261 }
262 select {
263 case <-tokenCh:
264 return true
265 default:
266 return false
267 }
268 }
269 }
270
271 // limit is a generic Rule decorator that limits invocations of said Rule.
272 // The "acquire" func SHOULD NOT block if the supplied Context is Done.
273 // MUST only invoke "acquire" once per event.
274 // TODO(jdef): leaving this as internal for now because the interface still feels too messy.
275 func limit(r Rule, acquire func(_ context.Context, block bool) bool, over Overflow, otherwise Rule) Rule {
276 if r == nil {
277 return nil
278 }
279 if acquire == nil {
280 panic("acquire func is not allowed to be nil")
281 }
282 blocking := false
283 switch over {
284 case OverflowOtherwise:
285 case OverflowWait:
286 blocking = true
287 default:
288 panic(fmt.Sprintf("unexpected Overflow type: %#v", over))
289 }
290 return func(ctx context.Context, e *executor.Call, z mesos.Response, err error, ch Chain) (context.Context, *executor.Call, mesos.Response, error) {
291 if !acquire(ctx, blocking) {
292 return otherwise.Eval(ctx, e, z, err, ch)
293 }
294 return r(ctx, e, z, err, ch)
295 }
296 }
297
298 /* TODO(jdef) not sure that this is very useful, leaving out for now...
299
300 // EveryN invokes the receiving rule beginning with the first event seen and then every n'th
301 // time after that. If nthTime is less then 2 then the receiver is returned, undecorated.
302 // The "otherwise" Rule (may be null) is invoked for every event in between the n'th invocations.
303 // A cancelled context will trigger the "otherwise" rule.
304 func (r Rule) EveryN(nthTime int, otherwise Rule) Rule {
305 if nthTime < 2 || r == nil {
306 return r
307 }
308 return limit(r, acquireEveryN(nthTime), OverflowOtherwise, otherwise)
309 }
310
311 // acquireEveryN returns an "acquire" func (for use w/ rate-limiting) that returns true every N'th invocation.
312 // the returned func MUST NOT be used with a potentially blocking Overflow policy (or else it panics).
313 // nthTime SHOULD be greater than math.MinInt32, values less than 2 probably don't make sense in practice.
314 func acquireEveryN(nthTime int) func(context.Context, bool) bool {
315 var (
316 i = 1 // begin with the first event seen
317 m sync.Mutex
318 )
319 return func(ctx context.Context, block bool) (result bool) {
320 if block {
321 panic("acquireEveryN should never be asked to block")
322 }
323 select {
324 case <-ctx.Done():
325 default:
326 m.Lock()
327 i--
328 if i <= 0 {
329 i = nthTime
330 result = true
331 }
332 m.Unlock()
333 }
334 return
335 }
336 }
337
338 */
339
340 // Drop aborts the Chain and returns the (context.Context, *executor.Call, error) tuple as-is.
341 func Drop() Rule {
342 return Rule(nil).ThenDrop()
343 }
344
345 // ThenDrop executes the receiving rule, but aborts the Chain, and returns the (context.Context, *executor.Call, mesos.Response, error) tuple as-is.
346 func (r Rule) ThenDrop() Rule {
347 return func(ctx context.Context, e *executor.Call, z mesos.Response, err error, _ Chain) (context.Context, *executor.Call, mesos.Response, error) {
348 return r.Eval(ctx, e, z, err, ChainIdentity)
349 }
350 }
351
352 // Fail returns a Rule that injects the given error.
353 func Fail(injected error) Rule {
354 return func(ctx context.Context, e *executor.Call, z mesos.Response, err error, ch Chain) (context.Context, *executor.Call, mesos.Response, error) {
355 return ch(ctx, e, z, Error2(err, injected))
356 }
357 }
358
359 // DropOnError returns a Rule that generates a nil event if the error state != nil
360 func DropOnError() Rule {
361 return Rule(nil).DropOnError()
362 }
363
364 // DropOnError decorates a rule by pre-checking the error state: if the error state != nil then
365 // the receiver is not invoked and (e, err) is returned; otherwise control passes to the receiving rule.
366 func (r Rule) DropOnError() Rule {
367 return func(ctx context.Context, e *executor.Call, z mesos.Response, err error, ch Chain) (context.Context, *executor.Call, mesos.Response, error) {
368 if err != nil {
369 return ctx, e, z, err
370 }
371 return r.Eval(ctx, e, z, err, ch)
372 }
373 }
374
375 // AndThen returns a list of rules, beginning with the receiver, followed by DropOnError, and then
376 // all of the rules specified by the next parameter. The net effect is: execute the receiver rule
377 // and only if there is no error state, continue processing the next rules, in order.
378 func (r Rule) AndThen(next ...Rule) Rule {
379 return append(Rules{r, DropOnError()}, next...).Eval
380 }
381
382 func DropOnSuccess() Rule {
383 return Rule(nil).DropOnSuccess()
384 }
385
386 func (r Rule) DropOnSuccess() Rule {
387 return func(ctx context.Context, e *executor.Call, z mesos.Response, err error, ch Chain) (context.Context, *executor.Call, mesos.Response, error) {
388 if err == nil {
389 // bypass remainder of chain
390 return ctx, e, z, err
391 }
392 return r.Eval(ctx, e, z, err, ch)
393 }
394 }
395
396 func (r Rule) OnFailure(next ...Rule) Rule {
397 return append(Rules{r, DropOnSuccess()}, next...).Eval
398 }