feat(service):lab4 add advisory lock to Reconciler.tick
This commit is contained in:
@@ -61,7 +61,40 @@ func (r *Reconciler) Run(ctx context.Context, interval time.Duration) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *Reconciler) tick(ctx context.Context) {
|
func (r *Reconciler) tick(ctx context.Context) {
|
||||||
if err := ctx.Err(); err != nil {
|
acquired, release, err := r.acquireLock(ctx)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("reconciler: acquire lock: %v", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if !acquired {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer release()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Reconciler) acquireLock(ctx context.Context) (bool, func(), error) {
|
||||||
|
conn, err := r.pool.Acquire(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return false, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var ok bool
|
||||||
|
if err := conn.QueryRow(ctx, `SELECT pg_try_advisory_lock($1)`, advisoryLockKey).Scan(&ok); err != nil {
|
||||||
|
conn.Release()
|
||||||
|
return false, nil, err
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
conn.Release()
|
||||||
|
return false, nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
release := func() {
|
||||||
|
unlockCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if _, err := conn.Exec(unlockCtx, `SELECT pg_advisory_unlock($1)`, advisoryLockKey); err != nil {
|
||||||
|
log.Printf("reconciler: unlock: %v", err)
|
||||||
|
}
|
||||||
|
conn.Release()
|
||||||
|
}
|
||||||
|
return true, release, nil
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user