Compare commits
23
Commits
main
...
6935d8533f
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6935d8533f | ||
|
|
b1bd827574 | ||
|
|
caacccec56 | ||
|
|
7a4e34528f | ||
|
|
7bb08f60f3 | ||
|
|
c4e06aeecd | ||
|
|
d7ef71dc7c | ||
|
|
5f03d4d832 | ||
|
|
cb1ed91e05 | ||
|
|
ec12f29fdb | ||
|
|
4b94fcb920 | ||
|
|
9d7a6a46c9 | ||
|
|
5f65f6c506 | ||
|
|
bf78cd75d3 | ||
|
|
a78e9927bc | ||
|
|
6af79d8cda | ||
|
|
185f859ee3 | ||
|
|
43e3a8a397 | ||
|
|
522ba1b639 | ||
|
|
cda370c78c | ||
|
|
fd2ae3db72 | ||
|
|
b5f1b426af | ||
|
|
fbf716c7bc |
No files matched your search
@@ -1 +1,13 @@
|
||||
**gomax** is a framework for MAX BotAPI, originating from [github.com/abelith/etu-bot/pkg/maxlib](https://github.com/abelith/etu-bot/tree/main/pkg/maxlib)
|
||||
**gomax** is a framework for [MAX BotAPI](https://dev.max.ru/docs-api), originating from [github.com/abelith/etu-bot/pkg/maxlib](https://github.com/abelith/etu-bot/tree/main/pkg/maxlib)
|
||||
|
||||
The project is inspired by [aiogram](https://aiogram.dev)
|
||||
|
||||
The project is in active development, so things may change quickly
|
||||
|
||||
# Table of Contents
|
||||
- [General](#general)
|
||||
- [Future plans](#future-plans)
|
||||
|
||||
# General
|
||||
|
||||
# Future plans
|
||||
@@ -1,118 +0,0 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
mcontext "github.com/abelith/gomax/context"
|
||||
"github.com/abelith/gomax/state"
|
||||
maxbot "github.com/max-messenger/max-bot-api-client-go/v2"
|
||||
"github.com/max-messenger/max-bot-api-client-go/v2/model"
|
||||
"github.com/rs/zerolog/log"
|
||||
"time"
|
||||
)
|
||||
|
||||
type FSMStorage interface {
|
||||
Get(ctx context.Context, userID int) (state.Snapshot, error)
|
||||
Put(ctx context.Context, state state.Snapshot) error
|
||||
Delete(ctx context.Context, userID int) error
|
||||
}
|
||||
|
||||
type UpdateHandler interface {
|
||||
HandleUpdate(c *mcontext.Context) error
|
||||
Use(mw ...Middleware)
|
||||
}
|
||||
|
||||
type Dispatcher struct {
|
||||
PollInterval time.Duration
|
||||
Api *maxbot.Api
|
||||
Handler UpdateHandler
|
||||
FSMStorage FSMStorage
|
||||
}
|
||||
|
||||
func (d *Dispatcher) getUpdates(ctx context.Context) <-chan model.Update {
|
||||
var updates []model.Update
|
||||
var marker int64
|
||||
var err error
|
||||
|
||||
ch := make(chan model.Update)
|
||||
|
||||
go func() {
|
||||
defer close(ch)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.Tick(d.PollInterval):
|
||||
start := time.Now()
|
||||
updates, marker, err = d.Api.Subscriptions.GetUpdates(ctx, marker)
|
||||
latency := time.Since(start)
|
||||
if err != nil && !errors.Is(err, context.Canceled) {
|
||||
log.Error().Err(err).Send()
|
||||
}
|
||||
log.Ctx(ctx).Debug().
|
||||
Int("received", len(updates)).
|
||||
Dur("latency", latency).
|
||||
Msg("received updates")
|
||||
|
||||
for _, update := range updates {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case ch <- update:
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
return ch
|
||||
}
|
||||
|
||||
func (d *Dispatcher) handleUpdates(ch <-chan model.Update) {
|
||||
for update := range ch {
|
||||
go d.handleUpdate(update)
|
||||
}
|
||||
}
|
||||
|
||||
func (d *Dispatcher) StartPolling(ctx context.Context) {
|
||||
d.handleUpdates(d.getUpdates(ctx))
|
||||
<-ctx.Done()
|
||||
}
|
||||
|
||||
func (d *Dispatcher) handleUpdate(upd model.Update) {
|
||||
ctx := context.Background()
|
||||
var st *state.Context
|
||||
|
||||
snapshot, err := d.FSMStorage.Get(ctx, int(upd.UserID))
|
||||
if err != nil && !errors.Is(err, state.ErrStateNotFound) {
|
||||
log.Error().Err(err).Send()
|
||||
return
|
||||
}
|
||||
if errors.Is(err, state.ErrStateNotFound) {
|
||||
st = state.New(int(upd.UserID))
|
||||
} else {
|
||||
st = state.Restore(snapshot)
|
||||
}
|
||||
|
||||
c := mcontext.New(ctx, upd, st, d.Api)
|
||||
|
||||
if err := d.Handler.HandleUpdate(c); err != nil {
|
||||
log.Error().Err(err).Send()
|
||||
return
|
||||
}
|
||||
|
||||
st = c.State()
|
||||
if st.State() == state.ClearState {
|
||||
if err := d.FSMStorage.Delete(ctx, int(upd.UserID)); err != nil {
|
||||
log.Error().Err(err).Send()
|
||||
return
|
||||
}
|
||||
}
|
||||
if st.State() != "" {
|
||||
if err := d.FSMStorage.Put(ctx, st.Snapshot()); err != nil {
|
||||
log.Error().Err(err).Send()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ require (
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
golang.org/x/sys v0.29.0 // indirect
|
||||
|
||||
@@ -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/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"errors"
|
||||
mcontext "github.com/abelith/gomax/context"
|
||||
"github.com/abelith/gomax/core"
|
||||
merrors "github.com/abelith/gomax/errors"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
func MwErrorResponder(defaultMsg string) core.Middleware {
|
||||
return func(next core.HandlerFunc) core.HandlerFunc {
|
||||
return func(c *mcontext.Context) error {
|
||||
err := next.HandleUpdate(c)
|
||||
var maxErr *merrors.GomaxError
|
||||
|
||||
if errors.As(err, &maxErr) {
|
||||
return c.Respond(maxErr.Message)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return c.Respond(defaultMsg)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func MwLoggerInjector() core.Middleware {
|
||||
return func(next core.HandlerFunc) core.HandlerFunc {
|
||||
return func(c *mcontext.Context) error {
|
||||
ctx := log.Logger.With().Int64("user_id", c.Update().UserID).
|
||||
Logger().WithContext(c.Context())
|
||||
c.SetContext(ctx)
|
||||
return next.HandleUpdate(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func MwDebugState() core.Middleware {
|
||||
return func(next core.HandlerFunc) core.HandlerFunc {
|
||||
return func(c *mcontext.Context) error {
|
||||
log.Debug().Any("state", c.State()).Any("update", c.Update()).Send()
|
||||
return next.HandleUpdate(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func MwErrorLogger() core.Middleware {
|
||||
return func(next core.HandlerFunc) core.HandlerFunc {
|
||||
return func(c *mcontext.Context) error {
|
||||
if err := next.HandleUpdate(c); err != nil {
|
||||
log.Ctx(c).Err(err).Send()
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/abelith/gomax/state"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type FSMStorage struct {
|
||||
m sync.Map
|
||||
}
|
||||
|
||||
func NewMemoryFSMStorage() *FSMStorage {
|
||||
return &FSMStorage{}
|
||||
}
|
||||
|
||||
func (f *FSMStorage) Get(_ context.Context, userID int) (*state.Snapshot, error) {
|
||||
st, ok := f.m.Load(userID)
|
||||
if !ok {
|
||||
return nil, state.ErrStateNotFound
|
||||
}
|
||||
|
||||
return st.(*state.Snapshot), nil
|
||||
}
|
||||
|
||||
func (f *FSMStorage) Put(_ context.Context, snapshot *state.Snapshot) error {
|
||||
f.m.Store(snapshot.ID, snapshot)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *FSMStorage) Delete(_ context.Context, snapshot *state.Snapshot) error {
|
||||
f.m.Delete(snapshot.ID)
|
||||
return nil
|
||||
}
|
||||
@@ -2,7 +2,7 @@ package context
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/abelith/gomax/state"
|
||||
"github.com/abelith/gomax/v1/fsm/state"
|
||||
maxbot "github.com/max-messenger/max-bot-api-client-go/v2"
|
||||
"github.com/max-messenger/max-bot-api-client-go/v2/model"
|
||||
"time"
|
||||
File renamed without changes.
@@ -0,0 +1,275 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
mcontext "github.com/abelith/gomax/v1/context"
|
||||
"github.com/abelith/gomax/v1/core/pollers"
|
||||
"github.com/abelith/gomax/v1/fsm/memory"
|
||||
"github.com/abelith/gomax/v1/fsm/state"
|
||||
"github.com/abelith/gomax/v1/isolation"
|
||||
"github.com/google/uuid"
|
||||
maxbot "github.com/max-messenger/max-bot-api-client-go/v2"
|
||||
"github.com/max-messenger/max-bot-api-client-go/v2/model"
|
||||
"github.com/rs/zerolog"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultTTL = 30 * time.Second
|
||||
defaultLockTimeout = 10 * time.Second
|
||||
defaultHandlerTimeout = 10 * time.Second
|
||||
)
|
||||
|
||||
type EventIsolation interface {
|
||||
Lock(ctx context.Context, key isolation.Key) error
|
||||
Unlock(ctx context.Context, key isolation.Key) error
|
||||
}
|
||||
|
||||
type FSMStorage interface {
|
||||
Get(ctx context.Context, scope isolation.Scope) (state.Snapshot, error)
|
||||
Put(ctx context.Context, state state.Snapshot) error
|
||||
Delete(ctx context.Context, scope isolation.Scope) error
|
||||
}
|
||||
|
||||
type UpdateHandler interface {
|
||||
HandleUpdate(c *mcontext.Context) error
|
||||
Use(mw ...Middleware)
|
||||
}
|
||||
|
||||
type Poller interface {
|
||||
Start(ctx context.Context) (<-chan model.Update, error)
|
||||
Stop(ctx context.Context) error
|
||||
}
|
||||
|
||||
type DispatcherOption interface {
|
||||
apply(d *dispatcherOptions)
|
||||
}
|
||||
|
||||
type Dispatcher struct {
|
||||
api *maxbot.Api
|
||||
poller Poller
|
||||
fsmStorage FSMStorage
|
||||
eventIsolation EventIsolation
|
||||
onStart func(ctx context.Context) error
|
||||
onStop func(ctx context.Context) error
|
||||
rt *Router
|
||||
logger zerolog.Logger
|
||||
wg sync.WaitGroup
|
||||
}
|
||||
|
||||
type dispatcherOptions struct {
|
||||
poller Poller
|
||||
fsmStorage FSMStorage
|
||||
eventIsolation EventIsolation
|
||||
logger zerolog.Logger
|
||||
}
|
||||
|
||||
type dispatcherOptionWrapper struct {
|
||||
fn func(options *dispatcherOptions)
|
||||
}
|
||||
|
||||
func NewDispatcher(api *maxbot.Api, options ...DispatcherOption) *Dispatcher {
|
||||
d := &Dispatcher{
|
||||
api: api,
|
||||
rt: &Router{},
|
||||
}
|
||||
|
||||
opts := newDispatcherOptions(api)
|
||||
for _, opt := range options {
|
||||
opt.apply(opts)
|
||||
}
|
||||
|
||||
d.poller = opts.poller
|
||||
d.fsmStorage = opts.fsmStorage
|
||||
d.eventIsolation = opts.eventIsolation
|
||||
d.logger = opts.logger
|
||||
|
||||
return d
|
||||
}
|
||||
|
||||
func (d *Dispatcher) Handle(handler UpdateHandler, filters ...func(c *mcontext.Context) bool) {
|
||||
d.rt.Handle(handler, filters...)
|
||||
}
|
||||
|
||||
func (d *Dispatcher) HandleFunc(handler func(c *mcontext.Context) error, filters ...func(c *mcontext.Context) bool) {
|
||||
d.rt.HandleFunc(handler, filters...)
|
||||
}
|
||||
|
||||
func (d *Dispatcher) HandleUpdate(c *mcontext.Context) error {
|
||||
return d.rt.HandleUpdate(c)
|
||||
}
|
||||
|
||||
func (d *Dispatcher) Use(mw ...Middleware) {
|
||||
d.rt.Use(mw...)
|
||||
}
|
||||
|
||||
func (d *Dispatcher) Start(ctx context.Context) error {
|
||||
ch, err := d.poller.Start(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if d.onStart != nil {
|
||||
if err := d.onStart(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
d.handleUpdates(ch)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *Dispatcher) Stop(ctx context.Context) error {
|
||||
if err := d.poller.Stop(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
done := make(chan struct{})
|
||||
|
||||
go func() {
|
||||
d.wg.Wait()
|
||||
done <- struct{}{}
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-done:
|
||||
}
|
||||
|
||||
if d.onStop != nil {
|
||||
return d.onStop(ctx)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *Dispatcher) OnStart(f func(ctx context.Context) error) {
|
||||
d.onStart = f
|
||||
}
|
||||
|
||||
func (d *Dispatcher) OnStop(f func(ctx context.Context) error) {
|
||||
d.onStop = f
|
||||
}
|
||||
|
||||
func (d *Dispatcher) handleUpdates(ch <-chan model.Update) {
|
||||
for upd := range ch {
|
||||
d.wg.Go(func() {
|
||||
key := isolation.Key{
|
||||
UpdateID: uuid.New(),
|
||||
UserID: upd.UserID,
|
||||
ChatID: upd.ChatID,
|
||||
}
|
||||
l := d.logger.With().
|
||||
Str("update_id", key.UpdateID.String()).
|
||||
Int64("user_id", key.UserID).
|
||||
Int64("chat_id", key.ChatID).
|
||||
Logger()
|
||||
|
||||
lockCtx, cancel := context.WithTimeout(context.Background(), defaultLockTimeout)
|
||||
defer cancel()
|
||||
|
||||
if err := d.eventIsolation.Lock(lockCtx, key); err != nil {
|
||||
d.logger.Error().
|
||||
Err(err).
|
||||
Int64("user_id", key.UserID).
|
||||
Int64("chat_id", key.ChatID).
|
||||
Msg("failed to lock on update")
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
unlockCtx, unlockCancel := context.WithTimeout(context.Background(), defaultLockTimeout)
|
||||
defer unlockCancel()
|
||||
|
||||
err := d.eventIsolation.Unlock(unlockCtx, key)
|
||||
switch {
|
||||
case errors.Is(err, isolation.ErrNotOwner):
|
||||
l.Warn().Msg("lock expired before handler finished")
|
||||
case err != nil:
|
||||
l.Warn().Err(err).Msg("failed to unlock on update")
|
||||
}
|
||||
}()
|
||||
|
||||
handleCtx, cancel := context.WithTimeout(context.Background(), defaultHandlerTimeout)
|
||||
defer cancel()
|
||||
d.handleUpdate(handleCtx, upd)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (d *Dispatcher) handleUpdate(ctx context.Context, upd model.Update) {
|
||||
var st *state.Context
|
||||
|
||||
snapshot, err := d.fsmStorage.Get(ctx, isolation.Scope{UserID: upd.UserID, ChatID: upd.ChatID})
|
||||
if err != nil && !errors.Is(err, state.ErrStateNotFound) {
|
||||
d.logger.Error().Err(err).Send()
|
||||
return
|
||||
}
|
||||
if errors.Is(err, state.ErrStateNotFound) {
|
||||
st = state.New(isolation.Scope{UserID: upd.UserID, ChatID: upd.ChatID})
|
||||
} else {
|
||||
st = state.Restore(snapshot)
|
||||
}
|
||||
|
||||
c := mcontext.New(ctx, upd, st, d.api)
|
||||
|
||||
if err := d.rt.HandleUpdate(c); err != nil {
|
||||
d.logger.Error().Err(err).Send()
|
||||
return
|
||||
}
|
||||
|
||||
st = c.State()
|
||||
if st.IsEmpty() {
|
||||
if err := d.fsmStorage.Delete(ctx, isolation.Scope{UserID: upd.UserID, ChatID: upd.ChatID}); err != nil {
|
||||
d.logger.Error().Err(err).Send()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if err := d.fsmStorage.Put(ctx, st.Snapshot()); err != nil {
|
||||
d.logger.Error().Err(err).Send()
|
||||
}
|
||||
}
|
||||
|
||||
func WithPoller(poller Poller) DispatcherOption {
|
||||
return newOption(func(opts *dispatcherOptions) {
|
||||
opts.poller = poller
|
||||
})
|
||||
}
|
||||
|
||||
func WithFSMStorage(storage FSMStorage) DispatcherOption {
|
||||
return newOption(func(opts *dispatcherOptions) {
|
||||
opts.fsmStorage = storage
|
||||
})
|
||||
}
|
||||
|
||||
func WithEventIsolation(eventIsolation EventIsolation) DispatcherOption {
|
||||
return newOption(func(opts *dispatcherOptions) {
|
||||
opts.eventIsolation = eventIsolation
|
||||
})
|
||||
}
|
||||
|
||||
func WithZerolog(logger zerolog.Logger) DispatcherOption {
|
||||
return newOption(func(options *dispatcherOptions) {
|
||||
options.logger = logger
|
||||
})
|
||||
}
|
||||
|
||||
func newDispatcherOptions(api *maxbot.Api) *dispatcherOptions {
|
||||
return &dispatcherOptions{
|
||||
poller: pollers.NewLongPoller(api),
|
||||
fsmStorage: memory.NewFSMStorage(),
|
||||
eventIsolation: memory.NewEventIsolation(defaultTTL),
|
||||
logger: zerolog.Nop(),
|
||||
}
|
||||
}
|
||||
|
||||
func newOption(fn func(options *dispatcherOptions)) DispatcherOption {
|
||||
return dispatcherOptionWrapper{fn: fn}
|
||||
}
|
||||
|
||||
func (dow dispatcherOptionWrapper) apply(opts *dispatcherOptions) {
|
||||
dow.fn(opts)
|
||||
}
|
||||
File renamed without changes.
@@ -1,6 +1,6 @@
|
||||
package core
|
||||
|
||||
import mcontext "github.com/abelith/gomax/context"
|
||||
import mcontext "github.com/abelith/gomax/v1/context"
|
||||
|
||||
type HandlerFunc func(c *mcontext.Context) error
|
||||
|
||||
@@ -0,0 +1,432 @@
|
||||
package pollers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
maxbot "github.com/max-messenger/max-bot-api-client-go/v2"
|
||||
"github.com/max-messenger/max-bot-api-client-go/v2/model"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/rs/zerolog/log"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultInterval = 200 * time.Millisecond
|
||||
defaultWhStartTimeout = 10 * time.Second
|
||||
)
|
||||
|
||||
type WebhookOption interface {
|
||||
apply(opts *webhookOptions)
|
||||
}
|
||||
|
||||
type LongPollerOption interface {
|
||||
apply(opts *longPollerOptions)
|
||||
}
|
||||
|
||||
type Webhook struct {
|
||||
srv *http.Server
|
||||
ch chan model.Update
|
||||
wg *sync.WaitGroup
|
||||
}
|
||||
|
||||
type LongPoller struct {
|
||||
api *maxbot.Api
|
||||
pollInterval time.Duration
|
||||
logger zerolog.Logger
|
||||
wg sync.WaitGroup
|
||||
}
|
||||
|
||||
type TestPoller struct {
|
||||
ch chan model.Update
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
type backoff struct {
|
||||
base time.Duration
|
||||
max time.Duration
|
||||
|
||||
window []bool
|
||||
pos int
|
||||
count int
|
||||
errors int
|
||||
|
||||
sinceAdjust int
|
||||
interval time.Duration
|
||||
}
|
||||
|
||||
type webhookOptions struct {
|
||||
addr string
|
||||
tlsConfig *tls.Config
|
||||
readTimeout time.Duration
|
||||
readHeaderTimeout time.Duration
|
||||
writeTimeout time.Duration
|
||||
idleTimeout time.Duration
|
||||
maxHeaderBytes int
|
||||
baseContext func(l net.Listener) context.Context
|
||||
connContext func(ctx context.Context, conn net.Conn) context.Context
|
||||
}
|
||||
|
||||
type longPollerOptions struct {
|
||||
pollInterval time.Duration
|
||||
logger zerolog.Logger
|
||||
}
|
||||
|
||||
type longPollerOptionWrapper struct {
|
||||
fn func(opts *longPollerOptions)
|
||||
}
|
||||
|
||||
type webhookOptionWrapper struct {
|
||||
fn func(opts *webhookOptions)
|
||||
}
|
||||
|
||||
func NewWebhookPoller(api *maxbot.Api, secret string, options ...WebhookOption) *Webhook {
|
||||
ch := make(chan model.Update, 1)
|
||||
|
||||
handler := api.GetHandler(func(ctx context.Context, update model.Update) {
|
||||
select {
|
||||
case ch <- update:
|
||||
case <-ctx.Done():
|
||||
}
|
||||
}, secret)
|
||||
|
||||
srv := &http.Server{
|
||||
Handler: handler,
|
||||
}
|
||||
|
||||
wh := &Webhook{
|
||||
srv: srv,
|
||||
ch: ch,
|
||||
}
|
||||
|
||||
opts := newWebhookOptions()
|
||||
for _, opt := range options {
|
||||
opt.apply(opts)
|
||||
}
|
||||
|
||||
wh.srv.Addr = opts.addr
|
||||
wh.srv.TLSConfig = opts.tlsConfig
|
||||
wh.srv.ReadTimeout = opts.readTimeout
|
||||
wh.srv.ReadHeaderTimeout = opts.readHeaderTimeout
|
||||
wh.srv.WriteTimeout = opts.writeTimeout
|
||||
wh.srv.IdleTimeout = opts.idleTimeout
|
||||
wh.srv.MaxHeaderBytes = opts.maxHeaderBytes
|
||||
wh.srv.BaseContext = opts.baseContext
|
||||
wh.srv.ConnContext = opts.connContext
|
||||
|
||||
return wh
|
||||
}
|
||||
|
||||
func (w *Webhook) Start(ctx context.Context) (<-chan model.Update, error) {
|
||||
l, err := net.Listen("tcp", w.srv.Addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
go func() {
|
||||
var err error
|
||||
|
||||
if w.srv.TLSConfig == nil {
|
||||
err = w.srv.Serve(l)
|
||||
} else {
|
||||
err = w.srv.ServeTLS(l, "", "")
|
||||
}
|
||||
|
||||
if err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
log.Ctx(ctx).Error().Err(err).Msg("failed to start webhook server")
|
||||
}
|
||||
}()
|
||||
|
||||
return w.ch, nil
|
||||
}
|
||||
|
||||
func (w *Webhook) Stop(ctx context.Context) error {
|
||||
defer close(w.ch)
|
||||
|
||||
if err := w.srv.Shutdown(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewLongPoller(api *maxbot.Api, options ...LongPollerOption) *LongPoller {
|
||||
lp := &LongPoller{
|
||||
api: api,
|
||||
}
|
||||
|
||||
opts := newLongPollerOptions()
|
||||
for _, opt := range options {
|
||||
opt.apply(opts)
|
||||
}
|
||||
|
||||
lp.pollInterval = opts.pollInterval
|
||||
lp.logger = opts.logger
|
||||
|
||||
return lp
|
||||
}
|
||||
|
||||
func (lp *LongPoller) Start(ctx context.Context) (<-chan model.Update, error) {
|
||||
ch := make(chan model.Update)
|
||||
|
||||
lp.wg.Go(func() {
|
||||
defer close(ch)
|
||||
lp.poll(ctx, ch)
|
||||
})
|
||||
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
func (lp *LongPoller) Stop(ctx context.Context) error {
|
||||
done := make(chan struct{})
|
||||
|
||||
go func() {
|
||||
lp.wg.Wait()
|
||||
done <- struct{}{}
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-done:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (tp *TestPoller) Inject(ctx context.Context, updates []model.Update) {
|
||||
ch := make(chan model.Update, 1)
|
||||
|
||||
go func() {
|
||||
defer close(ch)
|
||||
|
||||
for _, upd := range updates {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case ch <- upd:
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
tp.mu.Lock()
|
||||
tp.ch = ch
|
||||
defer tp.mu.Unlock()
|
||||
}
|
||||
|
||||
func (tp *TestPoller) Start(_ context.Context) (<-chan model.Update, error) {
|
||||
return tp.ch, nil
|
||||
}
|
||||
|
||||
func (tp *TestPoller) Stop(_ context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func WithPollInterval(interval time.Duration) LongPollerOption {
|
||||
return newLpOption(func(opts *longPollerOptions) {
|
||||
opts.pollInterval = interval
|
||||
})
|
||||
}
|
||||
|
||||
func WithZerolog(logger zerolog.Logger) LongPollerOption {
|
||||
return newLpOption(func(opts *longPollerOptions) {
|
||||
opts.logger = logger
|
||||
})
|
||||
}
|
||||
|
||||
func WithAddress(addr string) WebhookOption {
|
||||
return newWhOption(func(opts *webhookOptions) {
|
||||
opts.addr = addr
|
||||
})
|
||||
}
|
||||
|
||||
func WithTLSConfig(cfg *tls.Config) WebhookOption {
|
||||
return newWhOption(func(opts *webhookOptions) {
|
||||
opts.tlsConfig = cfg
|
||||
})
|
||||
}
|
||||
|
||||
func WithReadTimeout(timeout time.Duration) WebhookOption {
|
||||
return newWhOption(func(opts *webhookOptions) {
|
||||
opts.readTimeout = timeout
|
||||
})
|
||||
}
|
||||
|
||||
func WithReadHeaderTimeout(timeout time.Duration) WebhookOption {
|
||||
return newWhOption(func(opts *webhookOptions) {
|
||||
opts.readHeaderTimeout = timeout
|
||||
})
|
||||
}
|
||||
|
||||
func WithWriteTimeout(timeout time.Duration) WebhookOption {
|
||||
return newWhOption(func(opts *webhookOptions) {
|
||||
opts.writeTimeout = timeout
|
||||
})
|
||||
}
|
||||
|
||||
func WithIdleTimeout(timeout time.Duration) WebhookOption {
|
||||
return newWhOption(func(opts *webhookOptions) {
|
||||
opts.idleTimeout = timeout
|
||||
})
|
||||
}
|
||||
|
||||
func WithMaxHeaderBytes(bytes int) WebhookOption {
|
||||
return newWhOption(func(opts *webhookOptions) {
|
||||
opts.maxHeaderBytes = bytes
|
||||
})
|
||||
}
|
||||
|
||||
func WithBaseContext(fn func(l net.Listener) context.Context) WebhookOption {
|
||||
return newWhOption(func(opts *webhookOptions) {
|
||||
opts.baseContext = fn
|
||||
})
|
||||
}
|
||||
|
||||
func WithConnContext(fn func(ctx context.Context, c net.Conn) context.Context) WebhookOption {
|
||||
return newWhOption(func(opts *webhookOptions) {
|
||||
opts.connContext = fn
|
||||
})
|
||||
}
|
||||
|
||||
func newBackoff(
|
||||
base, max time.Duration,
|
||||
windowSize int,
|
||||
) *backoff {
|
||||
if base <= 0 || max < base || windowSize <= 0 {
|
||||
panic("backoff: invalid configuration")
|
||||
}
|
||||
|
||||
return &backoff{
|
||||
base: base,
|
||||
max: max,
|
||||
window: make([]bool, windowSize),
|
||||
interval: base,
|
||||
}
|
||||
}
|
||||
|
||||
func (b *backoff) observe(err error) time.Duration {
|
||||
failed := err != nil
|
||||
|
||||
if b.count == len(b.window) && b.window[b.pos] {
|
||||
b.errors--
|
||||
} else {
|
||||
b.count++
|
||||
}
|
||||
|
||||
b.window[b.pos] = failed
|
||||
if failed {
|
||||
b.errors++
|
||||
}
|
||||
|
||||
b.pos = (b.pos + 1) % len(b.window)
|
||||
b.sinceAdjust++
|
||||
|
||||
if b.count < len(b.window) ||
|
||||
b.sinceAdjust < len(b.window) {
|
||||
return b.interval
|
||||
}
|
||||
|
||||
b.sinceAdjust = 0
|
||||
errorRate := float64(b.errors) / float64(b.count)
|
||||
|
||||
switch {
|
||||
case errorRate >= 0.3:
|
||||
b.interval = min(b.interval*2, b.max)
|
||||
case errorRate <= 0.1:
|
||||
b.interval = max(b.interval/2, b.base)
|
||||
}
|
||||
|
||||
return b.interval
|
||||
}
|
||||
|
||||
func (lp *LongPoller) poll(ctx context.Context, ch chan model.Update) {
|
||||
b := newBackoff(
|
||||
lp.pollInterval,
|
||||
30*time.Second,
|
||||
20,
|
||||
)
|
||||
|
||||
var marker int64
|
||||
|
||||
for {
|
||||
if err := wait(ctx, b.interval); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
updates, nextMarker, err := lp.api.Subscriptions.GetUpdates(ctx, marker)
|
||||
latency := time.Since(start)
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, context.Canceled) ||
|
||||
ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
|
||||
delay := b.observe(err)
|
||||
|
||||
lp.logger.Error().
|
||||
Err(err).
|
||||
Dur("latency", latency).
|
||||
Dur("next_interval", delay).
|
||||
Msg("failed to receive updates")
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
b.observe(nil)
|
||||
marker = nextMarker
|
||||
|
||||
lp.logger.Debug().
|
||||
Int("received", len(updates)).
|
||||
Dur("latency", latency).
|
||||
Msg("received updates")
|
||||
|
||||
for _, update := range updates {
|
||||
select {
|
||||
case ch <- update:
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func newLongPollerOptions() *longPollerOptions {
|
||||
return &longPollerOptions{
|
||||
pollInterval: defaultInterval,
|
||||
logger: zerolog.Nop(),
|
||||
}
|
||||
}
|
||||
|
||||
func newWebhookOptions() *webhookOptions {
|
||||
return &webhookOptions{
|
||||
addr: ":8080",
|
||||
}
|
||||
}
|
||||
|
||||
func newLpOption(fn func(opts *longPollerOptions)) LongPollerOption {
|
||||
return longPollerOptionWrapper{fn: fn}
|
||||
}
|
||||
|
||||
func newWhOption(fn func(options *webhookOptions)) WebhookOption {
|
||||
return webhookOptionWrapper{fn: fn}
|
||||
}
|
||||
|
||||
func (low longPollerOptionWrapper) apply(opts *longPollerOptions) {
|
||||
low.fn(opts)
|
||||
}
|
||||
|
||||
func (wow webhookOptionWrapper) apply(opts *webhookOptions) {
|
||||
wow.fn(opts)
|
||||
}
|
||||
|
||||
func wait(ctx context.Context, delay time.Duration) error {
|
||||
timer := time.NewTimer(delay)
|
||||
defer timer.Stop()
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -2,13 +2,11 @@ package core
|
||||
|
||||
import (
|
||||
"errors"
|
||||
mcontext "github.com/abelith/gomax/context"
|
||||
mcontext "github.com/abelith/gomax/v1/context"
|
||||
)
|
||||
|
||||
type Middleware func(next HandlerFunc) HandlerFunc
|
||||
|
||||
type Filter func(c *mcontext.Context) bool
|
||||
|
||||
type route struct {
|
||||
h UpdateHandler
|
||||
filters []func(c *mcontext.Context) bool
|
||||
@@ -1,16 +1,20 @@
|
||||
package errors
|
||||
|
||||
type GomaxError struct {
|
||||
type GoMaxError struct {
|
||||
Message string
|
||||
Err error
|
||||
}
|
||||
|
||||
func (ge *GomaxError) Error() string {
|
||||
func (ge *GoMaxError) Error() string {
|
||||
return ge.Err.Error()
|
||||
}
|
||||
|
||||
func (ge *GoMaxError) Unwrap() error {
|
||||
return ge.Err
|
||||
}
|
||||
|
||||
func New(parent error, text string) error {
|
||||
return &GomaxError{
|
||||
return &GoMaxError{
|
||||
Message: text,
|
||||
Err: parent,
|
||||
}
|
||||
@@ -1,17 +1,44 @@
|
||||
package filters
|
||||
|
||||
import (
|
||||
mcontext "github.com/abelith/gomax/context"
|
||||
"github.com/abelith/gomax/core"
|
||||
"github.com/abelith/gomax/state"
|
||||
mcontext "github.com/abelith/gomax/v1/context"
|
||||
"github.com/abelith/gomax/v1/fsm/state"
|
||||
"github.com/max-messenger/max-bot-api-client-go/v2/model"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type CallbackFilter core.Filter
|
||||
type Filter func(c *mcontext.Context) bool
|
||||
|
||||
func StartCommand() core.Filter {
|
||||
type CallbackFilter Filter
|
||||
|
||||
type MessageFilter Filter
|
||||
|
||||
func And(filters ...func(c *mcontext.Context) bool) func(c *mcontext.Context) bool {
|
||||
return func(c *mcontext.Context) bool {
|
||||
for _, filter := range filters {
|
||||
if !filter(c) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
func Or(filters ...func(c *mcontext.Context) bool) func(c *mcontext.Context) bool {
|
||||
return func(c *mcontext.Context) bool {
|
||||
for _, filter := range filters {
|
||||
if filter(c) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func StartCommand() Filter {
|
||||
return func(c *mcontext.Context) bool {
|
||||
upd := c.Update()
|
||||
if upd.UpdateType == model.UpdateBotStarted {
|
||||
@@ -22,41 +49,54 @@ func StartCommand() core.Filter {
|
||||
}
|
||||
}
|
||||
|
||||
func Command(cmd string) core.Filter {
|
||||
func Command(cmd string) Filter {
|
||||
return func(c *mcontext.Context) bool {
|
||||
upd := c.Update()
|
||||
return upd.UpdateType == model.UpdateMessageCreated && strings.HasPrefix(upd.GetCommand().Command, cmd)
|
||||
}
|
||||
}
|
||||
|
||||
func State(state state.State) core.Filter {
|
||||
func State(state state.State) Filter {
|
||||
return func(c *mcontext.Context) bool {
|
||||
return c.State().State() == state
|
||||
}
|
||||
}
|
||||
|
||||
func MessageText(s string) core.Filter {
|
||||
func BotStopped() Filter {
|
||||
return func(c *mcontext.Context) bool {
|
||||
if msg := c.Update().Message; msg != nil {
|
||||
return s == msg.Body.Text
|
||||
}
|
||||
return false
|
||||
return c.Update().UpdateType == model.UpdateBotStopped
|
||||
}
|
||||
}
|
||||
|
||||
func MessageTextRe(re *regexp.Regexp) core.Filter {
|
||||
func Message() MessageFilter {
|
||||
return func(c *mcontext.Context) bool {
|
||||
if msg := c.Update().Message; msg != nil {
|
||||
s := strings.TrimSpace(msg.Body.Text)
|
||||
return re.MatchString(s)
|
||||
}
|
||||
return false
|
||||
return c.Update().UpdateType == model.UpdateMessageCreated && c.Update().Message != nil
|
||||
}
|
||||
}
|
||||
|
||||
func MessageGeo() core.Filter {
|
||||
func (mf MessageFilter) Text(s string) MessageFilter {
|
||||
return func(c *mcontext.Context) bool {
|
||||
if c.Update().Message == nil {
|
||||
if !mf(c) {
|
||||
return false
|
||||
}
|
||||
|
||||
return c.Update().Message.Body.Text == s
|
||||
}
|
||||
}
|
||||
|
||||
func (mf MessageFilter) Regex(re *regexp.Regexp) MessageFilter {
|
||||
return func(c *mcontext.Context) bool {
|
||||
if !mf(c) {
|
||||
return false
|
||||
}
|
||||
|
||||
return re.MatchString(c.Update().Message.Body.Text)
|
||||
}
|
||||
}
|
||||
|
||||
func (mf MessageFilter) Geo() MessageFilter {
|
||||
return func(c *mcontext.Context) bool {
|
||||
if !mf(c) {
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -70,29 +110,6 @@ func MessageGeo() core.Filter {
|
||||
}
|
||||
}
|
||||
|
||||
func BotStopped() core.Filter {
|
||||
return func(c *mcontext.Context) bool {
|
||||
return c.Update().UpdateType == model.UpdateBotStopped
|
||||
}
|
||||
}
|
||||
|
||||
func Or(filters ...core.Filter) core.Filter {
|
||||
return func(c *mcontext.Context) bool {
|
||||
for _, filter := range filters {
|
||||
if filter(c) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func Message() core.Filter {
|
||||
return func(c *mcontext.Context) bool {
|
||||
return c.Update().UpdateType == model.UpdateMessageCreated && c.Update().Message != nil
|
||||
}
|
||||
}
|
||||
|
||||
func Callback() CallbackFilter {
|
||||
return func(c *mcontext.Context) bool {
|
||||
return c.Update().UpdateType == model.UpdateMessageCallback
|
||||
@@ -104,15 +121,12 @@ func (cf CallbackFilter) StartsWith(prefix string) CallbackFilter {
|
||||
if !cf(c) {
|
||||
return false
|
||||
}
|
||||
payload, ok := getCallbackPayload(c)
|
||||
return ok && strings.HasPrefix(payload, prefix)
|
||||
}
|
||||
}
|
||||
|
||||
func getCallbackPayload(c *mcontext.Context) (string, bool) {
|
||||
upd := c.Update()
|
||||
if upd.Callback == nil {
|
||||
return "", false
|
||||
upd := c.Update().Callback
|
||||
if upd == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
return strings.HasPrefix(upd.Payload, prefix)
|
||||
}
|
||||
return upd.Callback.Payload, true
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/abelith/gomax/v1/fsm/state"
|
||||
"github.com/abelith/gomax/v1/isolation"
|
||||
"github.com/google/uuid"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type FSMStorage struct {
|
||||
m sync.Map
|
||||
}
|
||||
|
||||
type EventIsolation struct {
|
||||
mu sync.Mutex
|
||||
locks map[isolation.Scope]*lockEntry
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
type fsmKey struct {
|
||||
userID int64
|
||||
chatID int64
|
||||
}
|
||||
|
||||
type eventIsolationKey struct {
|
||||
userID int
|
||||
chatID int
|
||||
}
|
||||
|
||||
type lockEntry struct {
|
||||
owner uuid.UUID
|
||||
timer *time.Timer
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
func NewFSMStorage() *FSMStorage {
|
||||
return &FSMStorage{}
|
||||
}
|
||||
|
||||
func (f *FSMStorage) Get(_ context.Context, scope isolation.Scope) (state.Snapshot, error) {
|
||||
st, ok := f.m.Load(fsmKey{
|
||||
userID: scope.UserID,
|
||||
chatID: scope.ChatID,
|
||||
})
|
||||
if !ok {
|
||||
return state.Snapshot{}, state.ErrStateNotFound
|
||||
}
|
||||
|
||||
return st.(state.Snapshot), nil
|
||||
}
|
||||
|
||||
func (f *FSMStorage) Put(_ context.Context, snapshot state.Snapshot) error {
|
||||
f.m.Store(fsmKey{
|
||||
userID: snapshot.Scope.UserID,
|
||||
chatID: snapshot.Scope.ChatID,
|
||||
}, snapshot)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *FSMStorage) Delete(_ context.Context, scope isolation.Scope) error {
|
||||
f.m.Delete(fsmKey{
|
||||
userID: scope.UserID,
|
||||
chatID: scope.ChatID,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewEventIsolation(ttl time.Duration) *EventIsolation {
|
||||
return &EventIsolation{
|
||||
locks: make(map[isolation.Scope]*lockEntry),
|
||||
ttl: ttl,
|
||||
}
|
||||
}
|
||||
|
||||
func (ei *EventIsolation) Lock(ctx context.Context, key isolation.Key) error {
|
||||
scope := key.Scope()
|
||||
|
||||
for {
|
||||
ei.mu.Lock()
|
||||
entry, busy := ei.locks[scope]
|
||||
if !busy {
|
||||
ei.acquireLocked(scope, key.UpdateID)
|
||||
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, key isolation.Key) error {
|
||||
scope := key.Scope()
|
||||
|
||||
ei.mu.Lock()
|
||||
defer ei.mu.Unlock()
|
||||
|
||||
entry, ok := ei.locks[scope]
|
||||
if !ok || entry.owner != key.UpdateID {
|
||||
return isolation.ErrNotOwner
|
||||
}
|
||||
ei.releaseLocked(scope, entry)
|
||||
return nil
|
||||
}
|
||||
|
||||
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[scope]; ok && cur == entry {
|
||||
ei.releaseLocked(scope, entry)
|
||||
}
|
||||
})
|
||||
ei.locks[scope] = entry
|
||||
}
|
||||
|
||||
func (ei *EventIsolation) releaseLocked(scope isolation.Scope, entry *lockEntry) {
|
||||
entry.timer.Stop()
|
||||
delete(ei.locks, scope)
|
||||
close(entry.done)
|
||||
}
|
||||
@@ -3,8 +3,8 @@ package state
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/abelith/gomax/v1/isolation"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -12,9 +12,15 @@ var (
|
||||
ErrKeyNotFound = fmt.Errorf("state: key not found")
|
||||
)
|
||||
|
||||
const ClearState State = "clear"
|
||||
type State struct {
|
||||
group string
|
||||
name string
|
||||
}
|
||||
|
||||
type State string
|
||||
type Group struct {
|
||||
name string
|
||||
states map[string]*State
|
||||
}
|
||||
|
||||
type Codec interface {
|
||||
Marshal(v any) ([]byte, error)
|
||||
@@ -32,25 +38,69 @@ func (JSONCodec) Unmarshal(d []byte, v any) error {
|
||||
}
|
||||
|
||||
type Snapshot struct {
|
||||
ID int `json:"id"`
|
||||
State State `json:"state"`
|
||||
Scope isolation.Scope `json:"id"`
|
||||
State string `json:"state"`
|
||||
Data map[string][]byte `json:"data"`
|
||||
}
|
||||
|
||||
type Context struct {
|
||||
id int
|
||||
scope isolation.Scope
|
||||
state State
|
||||
data map[string][]byte
|
||||
codec Codec
|
||||
clear bool
|
||||
}
|
||||
|
||||
type Option func(*Context)
|
||||
|
||||
func NewStateGroup(name string) *Group {
|
||||
return &Group{
|
||||
name: name,
|
||||
states: make(map[string]*State),
|
||||
}
|
||||
}
|
||||
|
||||
func (g *Group) State(name string) State {
|
||||
state := g.states[name]
|
||||
|
||||
if state != nil {
|
||||
return *state
|
||||
}
|
||||
|
||||
if state = g.states[name]; state != nil {
|
||||
return *state
|
||||
}
|
||||
|
||||
state = &State{
|
||||
group: g.name,
|
||||
name: name,
|
||||
}
|
||||
|
||||
g.states[name] = state
|
||||
return *state
|
||||
}
|
||||
|
||||
func (s *State) String() string {
|
||||
return fmt.Sprintf("%s:%s", s.group, s.name)
|
||||
}
|
||||
|
||||
func fromString(s string) State {
|
||||
pieces := strings.Split(s, ":")
|
||||
if len(pieces) < 2 {
|
||||
return State{}
|
||||
}
|
||||
|
||||
return State{
|
||||
group: pieces[0],
|
||||
name: pieces[1],
|
||||
}
|
||||
}
|
||||
|
||||
func WithCodec(c Codec) Option { return func(sc *Context) { sc.codec = c } }
|
||||
|
||||
func New(id int, opts ...Option) *Context {
|
||||
func New(scope isolation.Scope, opts ...Option) *Context {
|
||||
sc := &Context{
|
||||
id: id,
|
||||
scope: scope,
|
||||
data: make(map[string][]byte),
|
||||
codec: JSONCodec{},
|
||||
}
|
||||
@@ -61,8 +111,8 @@ func New(id int, opts ...Option) *Context {
|
||||
}
|
||||
|
||||
func Restore(s Snapshot, opts ...Option) *Context {
|
||||
sc := New(s.ID, opts...)
|
||||
sc.state = s.State
|
||||
sc := New(s.Scope, opts...)
|
||||
sc.state = fromString(s.State)
|
||||
for k, v := range s.Data {
|
||||
sc.data[k] = v
|
||||
}
|
||||
@@ -74,25 +124,25 @@ func (sc *Context) Snapshot() Snapshot {
|
||||
for k, v := range sc.data {
|
||||
data[k] = v
|
||||
}
|
||||
return Snapshot{ID: sc.id, State: sc.state, Data: data}
|
||||
return Snapshot{Scope: sc.scope, State: sc.state.String(), Data: data}
|
||||
}
|
||||
|
||||
func (sc *Context) Set(state State) {
|
||||
log.Debug().
|
||||
Int("user_id", sc.id).
|
||||
Str("from", string(sc.state)).
|
||||
Str("to", string(state)).
|
||||
Msg("fsm state transition")
|
||||
sc.state = state
|
||||
}
|
||||
|
||||
func (sc *Context) State() State { return sc.state }
|
||||
|
||||
func (sc *Context) Clear() {
|
||||
sc.state = ClearState
|
||||
sc.state = State{}
|
||||
sc.clear = true
|
||||
sc.data = make(map[string][]byte)
|
||||
}
|
||||
|
||||
func (sc *Context) IsEmpty() bool {
|
||||
return sc.state == State{} && sc.clear
|
||||
}
|
||||
|
||||
func (sc *Context) Store(key string, val any) error {
|
||||
b, err := sc.codec.Marshal(val)
|
||||
if err != nil {
|
||||
@@ -0,0 +1 @@
|
||||
package v1
|
||||
@@ -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} }
|
||||
@@ -0,0 +1,63 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
mcontext "github.com/abelith/gomax/v1/context"
|
||||
"github.com/abelith/gomax/v1/core"
|
||||
merrors "github.com/abelith/gomax/v1/errors"
|
||||
)
|
||||
|
||||
func MwPanicHandler(onPanic func()) core.Middleware {
|
||||
return func(next core.HandlerFunc) core.HandlerFunc {
|
||||
return func(c *mcontext.Context) (err error) {
|
||||
defer func() {
|
||||
p := recover()
|
||||
if p != nil {
|
||||
onPanic()
|
||||
err = fmt.Errorf("panic: %v", p)
|
||||
}
|
||||
}()
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func MwErrorResponder(defaultMsg string) core.Middleware {
|
||||
return func(next core.HandlerFunc) core.HandlerFunc {
|
||||
return func(c *mcontext.Context) error {
|
||||
err := next(c)
|
||||
var maxErr *merrors.GoMaxError
|
||||
|
||||
if errors.As(err, &maxErr) {
|
||||
return errors.Join(c.Respond(maxErr.Message), maxErr)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return errors.Join(c.Respond(defaultMsg), err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func MwCallback(callback func(c *mcontext.Context)) core.Middleware {
|
||||
return func(next core.HandlerFunc) core.HandlerFunc {
|
||||
return func(c *mcontext.Context) error {
|
||||
callback(c)
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func MwErrorHandler(onError func(err error)) core.Middleware {
|
||||
return func(next core.HandlerFunc) core.HandlerFunc {
|
||||
return func(c *mcontext.Context) error {
|
||||
var err error
|
||||
if err = next(c); err != nil {
|
||||
onError(err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user