Files
miti99bot/internal/keylock/keylock.go
T
tiennm99 b81b6501c5 refactor(storage): replace KVStore with generic typed DocStore[T]
Delete the byte-oriented KVStore/VersionedStore abstraction and the
DynamoDB/memory KV backends. Add a generic typed store (DocStore[T] with
Provider/Collection/Typed) persisting each value as a flattened native
Mongo document (storedDoc[T] via bson inline) — no value envelope.

- MongoDB is the only runtime backend; memory kept for tests/local.
- All modules + deploynotify use typed stores; persisted structs carry
  bson tags == json names (incl. nested lolschedule/wordle types).
- lolschedule wraps its array/scalar values in named structs.
- migrate-dynamo-to-mongo writes the flattened shape via Typed[bson.M]
  with wrap rules; Scan/--dry-run/--verify retained.

Verified: go vet/build clean; full go test green hermetically and
in-container vs real Mongo 7 + DynamoDB Local (storage integration +
migrator e2e).
2026-06-28 18:02:11 +07:00

35 lines
1.4 KiB
Go

// Package keylock serialises compound operations that target the same key
// (typically a chat / user / subject identifier) across goroutines.
//
// Why a separate package: every game module needs a per-subject mutex to
// turn the store's single-op atomicity into safe Get→mutate→Put. The bot
// dispatcher runs each Telegram update in its own goroutine, so without
// explicit per-subject serialisation two updates to the same game could
// race and drop one write.
//
// Trade-off: the underlying sync.Map grows unboundedly with distinct keys
// (~32 B each). At 1M keys that's ~32 MB — acceptable for the lifetime of
// a Lambda instance, which restarts well before reaching that scale.
// Eviction is intentionally deferred — restart frequency keeps the working set bounded.
package keylock
import "sync"
// Map gives each string key its own mutex, lazily created. Zero value is
// usable; do not copy after first use (sync.Map is non-copyable).
type Map struct {
m sync.Map // key: string → val: *sync.Mutex
}
// Acquire locks the per-key mutex and returns its Unlock as a func so the
// caller can `defer m.Acquire(key)()` at the top of a critical section.
//
// Distinct keys never block each other; same-key callers run serially in the
// order Acquire was called.
func (m *Map) Acquire(key string) func() {
v, _ := m.m.LoadOrStore(key, &sync.Mutex{})
mu := v.(*sync.Mutex)
mu.Lock()
return mu.Unlock
}