Skip to content

Commit 0aca4b4

Browse files
committed
feat: add garbage collection
1 parent acee681 commit 0aca4b4

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

lock.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -610,6 +610,23 @@ func (c *Client) Renew(ctx context.Context, lockId string, ttl uint) ([]LockStat
610610
return statuses, nil
611611
}
612612

613+
// GC removes all lock entries in the collection that have expired
614+
// Specifically, this removes lock entries where exclusive.lockId is nil AND shared.count is 0
615+
func (c *Client) GC(ctx context.Context) error {
616+
// Get all empty locks and remove
617+
selector := bson.M{
618+
"exclusive.lockId": nil,
619+
"shared.count": 0,
620+
}
621+
622+
_, err := c.collection.DeleteMany(ctx, selector)
623+
if err != nil {
624+
return err
625+
}
626+
627+
return nil
628+
}
629+
613630
// ------------------------------------------------------------------------- //
614631

615632
// xUnlock unlocks an exclusive lock on a resource.

purge.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,5 +49,11 @@ func (p *purger) Purge(ctx context.Context) ([]LockStatus, error) {
4949
allUnlocked = append(allUnlocked, unlocked...)
5050
}
5151

52+
// Garbage collect unused lock records
53+
err = p.client.GC(ctx)
54+
if err != nil {
55+
return allUnlocked, err
56+
}
57+
5258
return allUnlocked, nil
5359
}

0 commit comments

Comments
 (0)