feat: implemented update isolation
This commit is contained in:
1 parent
fd2ae3db72
commit
cda370c78c
2 files changed
+102
-11
No files matched your search
+28
-7
@@ -10,9 +10,17 @@ import (
|
||||
"github.com/max-messenger/max-bot-api-client-go/v2/model"
|
||||
"github.com/rs/zerolog/log"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type EventIsolation interface{}
|
||||
const (
|
||||
defaultTTL = 5 * time.Second
|
||||
)
|
||||
|
||||
type EventIsolation interface {
|
||||
Lock(ctx context.Context, userID, chatID int) error
|
||||
Unlock(ctx context.Context, userID, chatID int) error
|
||||
}
|
||||
|
||||
type FSMStorage interface {
|
||||
Get(ctx context.Context, userID int) (state.Snapshot, error)
|
||||
@@ -91,15 +99,28 @@ func (d *Dispatcher) Start(ctx context.Context) error {
|
||||
}
|
||||
|
||||
func (d *Dispatcher) handleUpdates(ch <-chan model.Update) {
|
||||
for update := range ch {
|
||||
for upd := range ch {
|
||||
d.wg.Go(func() {
|
||||
d.handleUpdate(update)
|
||||
ctx := context.Background()
|
||||
|
||||
_ = d.eventIsolation.Lock(ctx, int(upd.UserID), int(upd.ChatID)) // todo: handle error somehow (retry or smth)
|
||||
defer func() {
|
||||
err := d.eventIsolation.Unlock(ctx, int(upd.UserID), int(upd.ChatID))
|
||||
if err != nil {
|
||||
log.Warn().
|
||||
Err(err).
|
||||
Int64("user_id", upd.UserID).
|
||||
Int64("chat_id", upd.ChatID).
|
||||
Msg("failed to unlock on update")
|
||||
}
|
||||
}()
|
||||
|
||||
d.handleUpdate(ctx, upd)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (d *Dispatcher) handleUpdate(upd model.Update) {
|
||||
ctx := context.Background()
|
||||
func (d *Dispatcher) handleUpdate(ctx context.Context, upd model.Update) {
|
||||
var st *state.Context
|
||||
|
||||
snapshot, err := d.fsmStorage.Get(ctx, int(upd.UserID))
|
||||
@@ -156,8 +177,8 @@ func WithEventIsolation(eventIsolation EventIsolation) DispatcherOption {
|
||||
func newDispatcherOptions(api *maxbot.Api) *dispatcherOptions {
|
||||
return &dispatcherOptions{
|
||||
poller: NewLongPoller(api),
|
||||
fsmStorage: memory.NewMemoryFSMStorage(),
|
||||
eventIsolation: memory.NewMemoryEventIsolation(),
|
||||
fsmStorage: memory.NewFSMStorage(),
|
||||
eventIsolation: memory.NewEventIsolation(defaultTTL),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user