feat: implemented update isolation
This commit is contained in:
1 parent
fd2ae3db72
commit
cda370c78c
2 files changed
+102
-11
No files matched your search
+74
-4
@@ -4,15 +4,30 @@ import (
|
||||
"context"
|
||||
"github.com/abelith/gomax/state"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type FSMStorage struct {
|
||||
m sync.Map
|
||||
}
|
||||
|
||||
type EventIsolation struct{}
|
||||
type EventIsolation struct {
|
||||
mu sync.Mutex
|
||||
locks map[eventIsolationKey]*lockEntry
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
func NewMemoryFSMStorage() *FSMStorage {
|
||||
type eventIsolationKey struct {
|
||||
userID int
|
||||
chatID int
|
||||
}
|
||||
|
||||
type lockEntry struct {
|
||||
timer *time.Timer
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
func NewFSMStorage() *FSMStorage {
|
||||
return &FSMStorage{}
|
||||
}
|
||||
|
||||
@@ -35,6 +50,61 @@ func (f *FSMStorage) Delete(_ context.Context, userID int) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewMemoryEventIsolation() *EventIsolation {
|
||||
return &EventIsolation{}
|
||||
func NewEventIsolation(ttl time.Duration) *EventIsolation {
|
||||
return &EventIsolation{
|
||||
locks: make(map[eventIsolationKey]*lockEntry),
|
||||
ttl: ttl,
|
||||
}
|
||||
}
|
||||
|
||||
func (ei *EventIsolation) Lock(ctx context.Context, userID, chatID int) error {
|
||||
key := eventIsolationKey{userID: userID, chatID: chatID}
|
||||
|
||||
for {
|
||||
ei.mu.Lock()
|
||||
entry, busy := ei.locks[key]
|
||||
if !busy {
|
||||
ei.acquireLocked(key)
|
||||
ei.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
done := entry.done
|
||||
ei.mu.Unlock()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (ei *EventIsolation) Unlock(_ context.Context, userID, chatID int) error {
|
||||
key := eventIsolationKey{userID: userID, chatID: chatID}
|
||||
|
||||
ei.mu.Lock()
|
||||
defer ei.mu.Unlock()
|
||||
|
||||
if entry, ok := ei.locks[key]; ok {
|
||||
ei.releaseLocked(key, entry)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ei *EventIsolation) acquireLocked(key eventIsolationKey) {
|
||||
entry := &lockEntry{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)
|
||||
}
|
||||
})
|
||||
ei.locks[key] = entry
|
||||
}
|
||||
|
||||
func (ei *EventIsolation) releaseLocked(key eventIsolationKey, entry *lockEntry) {
|
||||
entry.timer.Stop()
|
||||
delete(ei.locks, key)
|
||||
close(entry.done)
|
||||
}
|
||||
Reference in new issue
Block a user