mirror of
https://github.com/therootcompany/golib.git
synced 2026-04-24 12:48:00 +00:00
fix: skip redundant pull when another caller just synced under the lock
Records lastSynced time after each pull. A concurrent caller that was waiting behind the mutex sees lastSynced < 1s ago and returns early, avoiding a wasted network round-trip.
This commit is contained in:
parent
bd62122ac8
commit
b2eb5aef9a
@ -7,6 +7,7 @@ import (
|
|||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Repo manages a shallow git clone used as a periodically-updated data source.
|
// Repo manages a shallow git clone used as a periodically-updated data source.
|
||||||
@ -22,8 +23,9 @@ type Repo struct {
|
|||||||
// N — aggressive gc after every Nth pull
|
// N — aggressive gc after every Nth pull
|
||||||
GCInterval int
|
GCInterval int
|
||||||
|
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
pullCount int
|
pullCount int
|
||||||
|
lastSynced time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
// New creates a new Repo instance.
|
// New creates a new Repo instance.
|
||||||
@ -175,15 +177,26 @@ func (r *Repo) syncGit() (updated bool, err error) {
|
|||||||
r.mu.Lock()
|
r.mu.Lock()
|
||||||
defer r.mu.Unlock()
|
defer r.mu.Unlock()
|
||||||
|
|
||||||
|
// If another caller just finished a sync while we were waiting for the
|
||||||
|
// lock, skip the pull — the repo is already current.
|
||||||
|
if !r.lastSynced.IsZero() && time.Since(r.lastSynced) < time.Second {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
|
||||||
if cloned, err := r.clone(); err != nil {
|
if cloned, err := r.clone(); err != nil {
|
||||||
return false, err
|
return false, err
|
||||||
} else if cloned {
|
} else if cloned {
|
||||||
|
r.lastSynced = time.Now()
|
||||||
return true, nil
|
return true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
updated, err = r.pull()
|
updated, err = r.pull()
|
||||||
if err != nil || !updated {
|
if err != nil {
|
||||||
return updated, err
|
return false, err
|
||||||
|
}
|
||||||
|
r.lastSynced = time.Now()
|
||||||
|
if !updated {
|
||||||
|
return false, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if r.GCInterval > 0 {
|
if r.GCInterval > 0 {
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user