Repository navigation
Expand file tree
/
Copy pathpull.go
More file actions
66 lines (58 loc) · 2.4 KB
/
Copy pathpull.go
File metadata and controls
66 lines (58 loc) · 2.4 KB
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
package main
import "time"
// PullConsumer is the SYNCHRONOUS approach: when it needs an entitlement it
// doesn't own, it calls the owner per request. To blunt the cost of that call it
// adds a cache with a TTL and a retry. This is the "senior engineer adds
// resilience to a bad boundary" path — every mechanism here exists to compensate
// for the fact that the consumer depends on the owner being reachable and fresh.
//
// Read the fields as a list of band-aids: cache (hide latency), TTL (bound
// staleness), retry (survive a blip). None of them remove the dependency; they
// only make it hurt less, and each adds a failure mode of its own.
type PullConsumer struct {
owner *Owner
ttl time.Duration
maxRetry int
cache map[string]cacheEntry // "subject|perm" -> cached answer
now func() time.Time // injectable clock so tests are deterministic
}
type cacheEntry struct {
granted bool
at time.Time
}
func NewPullConsumer(owner *Owner, ttl time.Duration, maxRetry int) *PullConsumer {
return &PullConsumer{
owner: owner,
ttl: ttl,
maxRetry: maxRetry,
cache: map[string]cacheEntry{},
now: time.Now,
}
}
// Allowed answers the question "does subject have perm?" It serves a fresh-enough
// cache entry if it has one; otherwise it calls the owner (with retries). The two
// honest failure modes live right here:
//
// 1. Staleness: within the TTL window, a cached grant that the owner has since
// revoked is served as still-granted. The consumer is confidently wrong and
// raises no error. This is the dangerous case — silent, not loud.
// 2. Hard failure: on a cache miss while the owner is down, there is no answer to
// give. Retries exhaust and the call returns an error. The consumer is blocked
// on someone else's uptime for data it needs right now.
func (p *PullConsumer) Allowed(subject, perm string) (bool, error) {
key := subject + "|" + perm
if e, ok := p.cache[key]; ok && p.now().Sub(e.at) < p.ttl {
return e.granted, nil // may be stale — failure mode #1
}
var lastErr error
for attempt := 0; attempt <= p.maxRetry; attempt++ {
granted, err := p.owner.Lookup(subject, perm)
if err == nil {
p.cache[key] = cacheEntry{granted: granted, at: p.now()}
return granted, nil
}
lastErr = err
time.Sleep(time.Millisecond) // token backoff between attempts
}
return false, lastErr // owner down on a cold key — failure mode #2
}