fix(concurrency): guard the three shared maps with a mutex
clientPointer, myClientPointer and killChannel are created once at startup and
passed by reference into eleven packages. All of them read and wrote those plain
Go maps from different goroutines, with no synchronisation.
Go does not tolerate that: the runtime kills the process with
fatal error: concurrent map writes
and a fatal error is not recoverable — a deferred recover() does not catch it.
Measured in production: the process died inside StartClient while five instances
were connecting at once. The orchestrator restarted it within seconds, but every
number was offline in the meantime, and it repeats on any restart that brings up
more than a couple of instances together.
The three maps become safemap.Map[T], a generic wrapper over a RWMutex. It lives
in its own package because MyClient is defined in pkg/whatsmeow/service, and
putting the type there would create an import cycle with the ten packages that
receive the maps.
98 call sites changed across 12 files, with the compiler as the judge: anything
missed is a build error, not a silent bug.
Tests: with -race, a plain map running the same exercise reports DATA RACE and
fails, while safemap.Map passes. Both halves verified.
(cherry picked from commit 3860fa278dc2b901705ffbddbed5cf59d70a85e4)
This commit is contained in:
1 parent
a5f7e1c98a
commit
0c4ac7d9a9
14 files changed
+311
-129
No files matched your search
@@ -0,0 +1,99 @@
|
||||
// Package safemap holds the process-wide maps that are shared across goroutines.
|
||||
//
|
||||
// WHY THIS EXISTS
|
||||
//
|
||||
// The three state maps of the process (clientPointer, myClientPointer and
|
||||
// killChannel) are created once at startup and passed BY REFERENCE into eleven
|
||||
// packages. Every one of them read and wrote those maps directly, from different
|
||||
// goroutines, with no synchronisation at all.
|
||||
//
|
||||
// Go does not tolerate that. Concurrent writes do not corrupt silently: the
|
||||
// runtime kills the process with
|
||||
//
|
||||
// fatal error: concurrent map writes
|
||||
//
|
||||
// and a fatal error is NOT recoverable — a deferred recover() does not catch it.
|
||||
//
|
||||
// Measured in production: a process died at StartClient while five instances
|
||||
// were connecting at the same time. The container orchestrator brought it back
|
||||
// within seconds, but every number was offline in the meantime, and it repeats
|
||||
// on every restart that brings up more than a couple of instances at once.
|
||||
//
|
||||
// WHY A SEPARATE PACKAGE, AND WHY GENERICS
|
||||
//
|
||||
// MyClient lives in pkg/whatsmeow/service. If the safe type lived there, the
|
||||
// other ten packages would have to import that package and an import cycle
|
||||
// would appear. This package has no internal dependencies — only the standard
|
||||
// library — so anything can use it.
|
||||
package safemap
|
||||
|
||||
import "sync"
|
||||
|
||||
// Map is a map[string]T guarded by a read/write mutex.
|
||||
//
|
||||
// Always use the pointer (*Map[T]): copying the struct would copy the mutex,
|
||||
// and a copied mutex stops protecting the original — two owners, one lock each,
|
||||
// and the race comes back silently.
|
||||
type Map[T any] struct {
|
||||
mu sync.RWMutex
|
||||
m map[string]T
|
||||
}
|
||||
|
||||
// New returns an empty map, ready to use.
|
||||
func New[T any]() *Map[T] {
|
||||
return &Map[T]{m: make(map[string]T)}
|
||||
}
|
||||
|
||||
// Get returns the value, or the zero value of T when the key is absent —
|
||||
// exactly like the m[k] it replaces, so swapping call sites changes no
|
||||
// behaviour.
|
||||
func (s *Map[T]) Get(k string) T {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return s.m[k]
|
||||
}
|
||||
|
||||
// Lookup is the v, ok := m[k] form.
|
||||
func (s *Map[T]) Lookup(k string) (T, bool) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
v, ok := s.m[k]
|
||||
return v, ok
|
||||
}
|
||||
|
||||
// Set is the m[k] = v form.
|
||||
func (s *Map[T]) Set(k string, v T) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.m[k] = v
|
||||
}
|
||||
|
||||
// Delete is the delete(m, k) form.
|
||||
func (s *Map[T]) Delete(k string) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
delete(s.m, k)
|
||||
}
|
||||
|
||||
// Len is the len(m) form.
|
||||
func (s *Map[T]) Len() int {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return len(s.m)
|
||||
}
|
||||
|
||||
// Snapshot returns a copy for range loops.
|
||||
//
|
||||
// Ranging over the map from the inside would hold the lock for the whole loop,
|
||||
// and the loop bodies here talk to WhatsApp — the lock would be held across
|
||||
// network calls. The snapshot costs one copy of the pointers and releases the
|
||||
// lock immediately.
|
||||
func (s *Map[T]) Snapshot() map[string]T {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
out := make(map[string]T, len(s.m))
|
||||
for k, v := range s.m {
|
||||
out[k] = v
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package safemap
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestPlainMapRaces is the calibration test: it proves the detector can see the
|
||||
// bug in the first place.
|
||||
//
|
||||
// It drives a plain Go map the way this code used to — N goroutines writing the
|
||||
// same key. Under -race the detector flags it. Without -race the runtime kills
|
||||
// the process with "fatal error: concurrent map writes", which is exactly the
|
||||
// failure this package exists to prevent.
|
||||
//
|
||||
// Skipped by default precisely because that failure is not recoverable and
|
||||
// would take the whole suite down. Run it on purpose to confirm the detector is
|
||||
// not blind:
|
||||
//
|
||||
// go test -race -run TestPlainMapRaces ./pkg/safemap/
|
||||
func TestPlainMapRaces(t *testing.T) {
|
||||
t.Skip("calibration: run by hand — see the comment above")
|
||||
|
||||
m := map[string]int{}
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 50; i++ {
|
||||
wg.Add(1)
|
||||
go func(n int) {
|
||||
defer wg.Done()
|
||||
m["key"] = n // <- the race
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
// TestConcurrentAccess runs the same exercise through the guarded map: fifty
|
||||
// goroutines writing, reading and ranging over the same key at once — the shape
|
||||
// of a startup where several instances connect simultaneously.
|
||||
func TestConcurrentAccess(t *testing.T) {
|
||||
m := New[int]()
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 50; i++ {
|
||||
wg.Add(3)
|
||||
go func(n int) { defer wg.Done(); m.Set("key", n) }(i)
|
||||
go func() { defer wg.Done(); _ = m.Get("key") }()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
_, _ = m.Lookup("key")
|
||||
_ = m.Len()
|
||||
for range m.Snapshot() {
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
if _, ok := m.Lookup("key"); !ok {
|
||||
t.Fatal("key should still be in the map")
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetMissingKeyReturnsZero pins the behaviour the call sites relied on:
|
||||
// m[k] on an absent key yields the zero value, and Get must do the same —
|
||||
// otherwise swapping the call sites would have changed logic silently.
|
||||
func TestGetMissingKeyReturnsZero(t *testing.T) {
|
||||
if v := New[*int]().Get("absent"); v != nil {
|
||||
t.Fatalf("want nil, got %v", v)
|
||||
}
|
||||
if n := New[int]().Get("absent"); n != 0 {
|
||||
t.Fatalf("want 0, got %d", n)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user