Skip to content

Commit

Permalink
Small improvements to locking in optimized revision handler
Browse files Browse the repository at this point in the history
  • Loading branch information
josephschorr committed Jun 17, 2024
1 parent 50ecb1b commit 37c79f5
Showing 1 changed file with 8 additions and 8 deletions.
16 changes: 8 additions & 8 deletions internal/datastore/revisions/optimized.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,16 +51,16 @@ func (cor *CachedOptimizedRevisions) OptimizedRevision(ctx context.Context) (dat
adjustedNow = localNow.Add(-1 * time.Duration(rand.Int63n(cor.maxRevisionStaleness.Nanoseconds())) * time.Nanosecond)
}

cor.Lock()
cor.RLock()
for _, candidate := range cor.candidates {
if candidate.validThrough.After(adjustedNow) {
cor.RUnlock()
log.Ctx(ctx).Debug().Time("now", localNow).Time("valid", candidate.validThrough).Msg("returning cached revision")
span.AddEvent("returning cached revision")
cor.Unlock()
return candidate.revision, nil
}
}
cor.Unlock()
cor.RUnlock()

newQuantizedRevision, err, _ := cor.updateGroup.Do("", func() (interface{}, error) {
log.Ctx(ctx).Debug().Time("now", localNow).Msg("computing new revision")
Expand All @@ -72,10 +72,9 @@ func (cor *CachedOptimizedRevisions) OptimizedRevision(ctx context.Context) (dat
}

rvt := localNow.Add(validFor)
cor.Lock()
defer cor.Unlock()

// Prune the candidates that have definitely expired
cor.Lock()
var numToDrop uint
for _, candidate := range cor.candidates {
if candidate.validThrough.Add(cor.maxRevisionStaleness).Before(localNow) {
Expand All @@ -84,11 +83,12 @@ func (cor *CachedOptimizedRevisions) OptimizedRevision(ctx context.Context) (dat
break
}
}
cor.candidates = cor.candidates[numToDrop:]

cor.candidates = cor.candidates[numToDrop:]
cor.candidates = append(cor.candidates, validRevision{optimized, rvt})
log.Ctx(ctx).Debug().Time("now", localNow).Time("valid", rvt).Stringer("validFor", validFor).Msg("setting valid through")
cor.Unlock()

log.Ctx(ctx).Debug().Time("now", localNow).Time("valid", rvt).Stringer("validFor", validFor).Msg("setting valid through")
return optimized, nil
})
if err != nil {
Expand All @@ -99,7 +99,7 @@ func (cor *CachedOptimizedRevisions) OptimizedRevision(ctx context.Context) (dat

// CachedOptimizedRevisions does caching and deduplication for requests for optimized revisions.
type CachedOptimizedRevisions struct {
sync.Mutex
sync.RWMutex

maxRevisionStaleness time.Duration
optimizedFunc OptimizedRevisionFunction
Expand Down

0 comments on commit 37c79f5

Please sign in to comment.