| 1 | package as400 |
| 2 | |
| 3 | import "context" |
| 4 | |
| 5 | const ( |
| 6 | networkInterfaceLimit = 50 |
| 7 | httpServerLimit = 200 |
| 8 | ) |
| 9 | |
| 10 | type cardinalityGuard struct { |
| 11 | max int |
| 12 | checked bool |
| 13 | allowed bool |
| 14 | lastCount int |
| 15 | } |
| 16 | |
| 17 | func (g *cardinalityGuard) Configure(max int) { |
| 18 | if g.max != max { |
| 19 | g.max = max |
| 20 | g.checked = false |
| 21 | g.allowed = true |
| 22 | g.lastCount = 0 |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | func (g *cardinalityGuard) Allow(ctx context.Context, counter func(context.Context) (int, error)) (bool, int, error) { |
| 27 | if g.max <= 0 { |
| 28 | g.checked = true |
| 29 | g.allowed = true |
| 30 | g.lastCount = 0 |
| 31 | return true, 0, nil |
| 32 | } |
| 33 | if g.checked { |
| 34 | return g.allowed, g.lastCount, nil |
| 35 | } |
| 36 | count, err := counter(ctx) |
| 37 | if err != nil { |
| 38 | return false, 0, err |
| 39 | } |
| 40 | g.checked = true |
| 41 | g.lastCount = count |
| 42 | g.allowed = count <= g.max |
| 43 | return g.allowed, count, nil |
| 44 | } |
| 45 | |
| 46 | func (g *cardinalityGuard) Exceeded() bool { |
| 47 | return g.checked && !g.allowed |
| 48 | } |
| 49 | |
| 50 | func (g *cardinalityGuard) LastCount() int { |
| 51 | return g.lastCount |
| 52 | } |
| 53 | |
| 54 | func (g *cardinalityGuard) Max() int { |
| 55 | return g.max |
| 56 | } |