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

+1
View File
@@ -8,6 +8,7 @@ require (
) )
require ( require (
github.com/google/uuid v1.6.0 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-isatty v0.0.20 // indirect
golang.org/x/sys v0.29.0 // indirect golang.org/x/sys v0.29.0 // indirect
+2
View File
@@ -1,3 +1,5 @@
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE= github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
+42 -16
View File
@@ -4,8 +4,10 @@ import (
"context" "context"
"errors" "errors"
mcontext "github.com/abelith/gomax/v1/context" mcontext "github.com/abelith/gomax/v1/context"
"github.com/abelith/gomax/v1/isolation"
"github.com/abelith/gomax/v1/state" "github.com/abelith/gomax/v1/state"
"github.com/abelith/gomax/v1/state/memory" "github.com/abelith/gomax/v1/state/memory"
"github.com/google/uuid"
maxbot "github.com/max-messenger/max-bot-api-client-go/v2" maxbot "github.com/max-messenger/max-bot-api-client-go/v2"
"github.com/max-messenger/max-bot-api-client-go/v2/model" "github.com/max-messenger/max-bot-api-client-go/v2/model"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
@@ -14,12 +16,14 @@ import (
) )
const ( const (
defaultTTL = 5 * time.Second defaultTTL = 30 * time.Second
defaultLockTimeout = 10 * time.Second
defaultHandlerTimeout = 10 * time.Second
) )
type EventIsolation interface { type EventIsolation interface {
Lock(ctx context.Context, userID, chatID int) error Lock(ctx context.Context, key isolation.Key) error
Unlock(ctx context.Context, userID, chatID int) error Unlock(ctx context.Context, key isolation.Key) error
} }
type FSMStorage interface { type FSMStorage interface {
@@ -78,8 +82,8 @@ func NewDispatcher(api *maxbot.Api, options ...DispatcherOption) *Dispatcher {
return d return d
} }
func (d *Dispatcher) Handle(handler UpdateHandler, filters func(c *mcontext.Context) bool) { func (d *Dispatcher) Handle(handler UpdateHandler, filters ...func(c *mcontext.Context) bool) {
d.rt.Handle(handler, filters) d.rt.Handle(handler, filters...)
} }
func (d *Dispatcher) HandleFunc(handler func(c *mcontext.Context) error, filters ...func(c *mcontext.Context) bool) { func (d *Dispatcher) HandleFunc(handler func(c *mcontext.Context) error, filters ...func(c *mcontext.Context) bool) {
@@ -101,7 +105,6 @@ func (d *Dispatcher) Start(ctx context.Context) error {
} }
d.handleUpdates(ch) d.handleUpdates(ch)
<-ctx.Done()
d.wg.Wait() d.wg.Wait()
return nil return nil
} }
@@ -109,21 +112,44 @@ func (d *Dispatcher) Start(ctx context.Context) error {
func (d *Dispatcher) handleUpdates(ch <-chan model.Update) { func (d *Dispatcher) handleUpdates(ch <-chan model.Update) {
for upd := range ch { for upd := range ch {
d.wg.Go(func() { d.wg.Go(func() {
ctx := context.Background() key := isolation.Key{
UpdateID: uuid.New(),
UserID: upd.UserID,
ChatID: upd.ChatID,
}
l := log.With().
Str("update_id", key.UpdateID.String()).
Int64("user_id", key.UserID).
Int64("chat_id", key.ChatID).
Logger()
_ = d.eventIsolation.Lock(ctx, int(upd.UserID), int(upd.ChatID)) // todo: handle error somehow (retry or smth) lockCtx, cancel := context.WithTimeout(context.Background(), defaultLockTimeout)
defer cancel()
if err := d.eventIsolation.Lock(lockCtx, key); err != nil {
log.Error().
Err(err).
Int64("user_id", key.UserID).
Int64("chat_id", key.ChatID).
Msg("failed to lock on update")
return
}
defer func() { defer func() {
err := d.eventIsolation.Unlock(ctx, int(upd.UserID), int(upd.ChatID)) unlockCtx, unlockCancel := context.WithTimeout(context.Background(), defaultLockTimeout)
if err != nil { defer unlockCancel()
log.Warn().
Err(err). err := d.eventIsolation.Unlock(unlockCtx, key)
Int64("user_id", upd.UserID). switch {
Int64("chat_id", upd.ChatID). case errors.Is(err, isolation.ErrNotOwner):
Msg("failed to unlock on update") l.Warn().Msg("lock expired before handler finished")
case err != nil:
l.Warn().Err(err).Msg("failed to unlock on update")
} }
}() }()
d.handleUpdate(ctx, upd) handleCtx, cancel := context.WithTimeout(context.Background(), defaultHandlerTimeout)
defer cancel()
d.handleUpdate(handleCtx, upd)
}) })
} }
} }
+1 -2
View File
@@ -128,6 +128,7 @@ func (w *Webhook) Start(_ context.Context) (<-chan model.Update, error) {
} }
func (w *Webhook) Stop(ctx context.Context) error { func (w *Webhook) Stop(ctx context.Context) error {
close(w.ch)
return w.srv.Shutdown(ctx) return w.srv.Shutdown(ctx)
} }
@@ -176,8 +177,6 @@ func (lp *LongPoller) Start(ctx context.Context) (<-chan model.Update, error) {
for _, update := range updates { for _, update := range updates {
select { select {
case <-ctx.Done():
return
case ch <- update: case ch <- update:
} }
} }
+22
View File
@@ -0,0 +1,22 @@
package isolation
import (
"errors"
"github.com/google/uuid"
)
var ErrNotOwner = errors.New("isolation: lock is not held by this owner")
type Key struct {
UpdateID uuid.UUID // владелец
UserID int64
ChatID int64
}
type Scope struct {
UserID int64
ChatID int64
}
func (k Key) Scope() Scope { return Scope{UserID: k.UserID, ChatID: k.ChatID} }
+22 -17
View File
@@ -2,7 +2,9 @@ package memory
import ( import (
"context" "context"
"github.com/abelith/gomax/v1/isolation"
"github.com/abelith/gomax/v1/state" "github.com/abelith/gomax/v1/state"
"github.com/google/uuid"
"sync" "sync"
"time" "time"
) )
@@ -13,7 +15,7 @@ type FSMStorage struct {
type EventIsolation struct { type EventIsolation struct {
mu sync.Mutex mu sync.Mutex
locks map[eventIsolationKey]*lockEntry locks map[isolation.Scope]*lockEntry
ttl time.Duration ttl time.Duration
} }
@@ -23,6 +25,7 @@ type eventIsolationKey struct {
} }
type lockEntry struct { type lockEntry struct {
owner uuid.UUID
timer *time.Timer timer *time.Timer
done chan struct{} done chan struct{}
} }
@@ -52,19 +55,19 @@ func (f *FSMStorage) Delete(_ context.Context, userID int) error {
func NewEventIsolation(ttl time.Duration) *EventIsolation { func NewEventIsolation(ttl time.Duration) *EventIsolation {
return &EventIsolation{ return &EventIsolation{
locks: make(map[eventIsolationKey]*lockEntry), locks: make(map[isolation.Scope]*lockEntry),
ttl: ttl, ttl: ttl,
} }
} }
func (ei *EventIsolation) Lock(ctx context.Context, userID, chatID int) error { func (ei *EventIsolation) Lock(ctx context.Context, key isolation.Key) error {
key := eventIsolationKey{userID: userID, chatID: chatID} scope := key.Scope()
for { for {
ei.mu.Lock() ei.mu.Lock()
entry, busy := ei.locks[key] entry, busy := ei.locks[scope]
if !busy { if !busy {
ei.acquireLocked(key) ei.acquireLocked(scope, key.UpdateID)
ei.mu.Unlock() ei.mu.Unlock()
return nil 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 { func (ei *EventIsolation) Unlock(_ context.Context, key isolation.Key) error {
key := eventIsolationKey{userID: userID, chatID: chatID} scope := key.Scope()
ei.mu.Lock() ei.mu.Lock()
defer ei.mu.Unlock() defer ei.mu.Unlock()
if entry, ok := ei.locks[key]; ok { entry, ok := ei.locks[scope]
ei.releaseLocked(key, entry) if !ok || entry.owner != key.UpdateID {
return isolation.ErrNotOwner
} }
ei.releaseLocked(scope, entry)
return nil return nil
} }
func (ei *EventIsolation) acquireLocked(key eventIsolationKey) { func (ei *EventIsolation) acquireLocked(scope isolation.Scope, owner uuid.UUID) {
entry := &lockEntry{done: make(chan struct{})} entry := &lockEntry{owner: owner, done: make(chan struct{})}
entry.timer = time.AfterFunc(ei.ttl, func() { entry.timer = time.AfterFunc(ei.ttl, func() {
ei.mu.Lock() ei.mu.Lock()
defer ei.mu.Unlock() defer ei.mu.Unlock()
if cur, ok := ei.locks[key]; ok && cur == entry { if cur, ok := ei.locks[scope]; ok && cur == entry {
ei.releaseLocked(key, 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() entry.timer.Stop()
delete(ei.locks, key) delete(ei.locks, scope)
close(entry.done) close(entry.done)
} }