fix: major fixes

This commit is contained in:
abelith committed 2026-10-06 14:49:29 +03:00
1 parent 9d7a6a46c9
commit 4b94fcb920
6 files changed
+90 -35

No files matched your search

+22 -17
View File
@@ -2,7 +2,9 @@ package memory
import (
"context"
"github.com/abelith/gomax/v1/isolation"
"github.com/abelith/gomax/v1/state"
"github.com/google/uuid"
"sync"
"time"
)
@@ -13,7 +15,7 @@ type FSMStorage struct {
type EventIsolation struct {
mu sync.Mutex
locks map[eventIsolationKey]*lockEntry
locks map[isolation.Scope]*lockEntry
ttl time.Duration
}
@@ -23,6 +25,7 @@ type eventIsolationKey struct {
}
type lockEntry struct {
owner uuid.UUID
timer *time.Timer
done chan struct{}
}
@@ -52,19 +55,19 @@ func (f *FSMStorage) Delete(_ context.Context, userID int) error {
func NewEventIsolation(ttl time.Duration) *EventIsolation {
return &EventIsolation{
locks: make(map[eventIsolationKey]*lockEntry),
locks: make(map[isolation.Scope]*lockEntry),
ttl: ttl,
}
}
func (ei *EventIsolation) Lock(ctx context.Context, userID, chatID int) error {
key := eventIsolationKey{userID: userID, chatID: chatID}
func (ei *EventIsolation) Lock(ctx context.Context, key isolation.Key) error {
scope := key.Scope()
for {
ei.mu.Lock()
entry, busy := ei.locks[key]
entry, busy := ei.locks[scope]
if !busy {
ei.acquireLocked(key)
ei.acquireLocked(scope, key.UpdateID)
ei.mu.Unlock()
return nil
}
@@ -79,32 +82,34 @@ func (ei *EventIsolation) Lock(ctx context.Context, userID, chatID int) error {
}
}
func (ei *EventIsolation) Unlock(_ context.Context, userID, chatID int) error {
key := eventIsolationKey{userID: userID, chatID: chatID}
func (ei *EventIsolation) Unlock(_ context.Context, key isolation.Key) error {
scope := key.Scope()
ei.mu.Lock()
defer ei.mu.Unlock()
if entry, ok := ei.locks[key]; ok {
ei.releaseLocked(key, entry)
entry, ok := ei.locks[scope]
if !ok || entry.owner != key.UpdateID {
return isolation.ErrNotOwner
}
ei.releaseLocked(scope, entry)
return nil
}
func (ei *EventIsolation) acquireLocked(key eventIsolationKey) {
entry := &lockEntry{done: make(chan struct{})}
func (ei *EventIsolation) acquireLocked(scope isolation.Scope, owner uuid.UUID) {
entry := &lockEntry{owner: owner, done: make(chan struct{})}
entry.timer = time.AfterFunc(ei.ttl, func() {
ei.mu.Lock()
defer ei.mu.Unlock()
if cur, ok := ei.locks[key]; ok && cur == entry {
ei.releaseLocked(key, entry)
if cur, ok := ei.locks[scope]; ok && cur == entry {
ei.releaseLocked(scope, entry)
}
})
ei.locks[key] = entry
ei.locks[scope] = entry
}
func (ei *EventIsolation) releaseLocked(key eventIsolationKey, entry *lockEntry) {
func (ei *EventIsolation) releaseLocked(scope isolation.Scope, entry *lockEntry) {
entry.timer.Stop()
delete(ei.locks, key)
delete(ei.locks, scope)
close(entry.done)
}