Debian Codegraph @

api/v1/lib/extras/scheduler/eventrules/eventrules_generated.go

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