Browse Source

Improve encapsulation: Add shallowClone() method to vidMap

Added a shallowClone() method to vidMap to improve encapsulation and prevent
MasterClient from directly accessing vidMap's internal fields.

Changes:
1. Added vidMap.shallowClone() in vid_map.go
   - Encapsulates the shallow copy logic within vidMap
   - Makes vidMap responsible for its own state representation
   - Documented that caller is responsible for thread safety

2. Simplified resetVidMap() in masterclient.go
   - Uses tail := mc.vidMap.shallowClone() instead of manual field access
   - Cleaner, more maintainable code
   - Better adherence to encapsulation principles

Benefits:
- Improved code organization and maintainability
- vidMap internals are now properly encapsulated
- Easier to modify vidMap structure in the future
- More self-documenting code

Verified with: go test -race ./weed/wdclient/... (passes)
pr-7412
chrislu 1 month ago
parent
commit
bba8931d64
  1. 10
      weed/wdclient/masterclient.go
  2. 11
      weed/wdclient/vid_map.go

10
weed/wdclient/masterclient.go

@ -592,14 +592,10 @@ func (mc *MasterClient) resetVidMap() {
mc.vidMapLock.Lock()
defer mc.vidMapLock.Unlock()
tail := &vidMap{
vid2Locations: mc.vidMap.vid2Locations,
ecVid2Locations: mc.vidMap.ecVid2Locations,
DataCenter: mc.vidMap.DataCenter,
cache: mc.vidMap.cache,
}
// Create a shallow clone to preserve in the cache chain
tail := mc.vidMap.shallowClone()
nvm := newVidMap(mc.vidMap.DataCenter)
nvm := newVidMap(tail.DataCenter)
nvm.cache = tail
mc.vidMap = nvm

11
weed/wdclient/vid_map.go

@ -53,6 +53,17 @@ func newVidMap(dataCenter string) *vidMap {
}
}
// shallowClone creates a shallow copy of the vidMap for use in cache chaining.
// The caller is responsible for ensuring thread safety.
func (vc *vidMap) shallowClone() *vidMap {
return &vidMap{
vid2Locations: vc.vid2Locations,
ecVid2Locations: vc.ecVid2Locations,
DataCenter: vc.DataCenter,
cache: vc.cache,
}
}
func (vc *vidMap) getLocationIndex(length int) (int, error) {
if length <= 0 {
return 0, fmt.Errorf("invalid length: %d", length)

Loading…
Cancel
Save