Compare commits
13
Commits
main
...
4b94fcb920
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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,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/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,225 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
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/memory"
|
||||
"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/log"
|
||||
"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, 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 Poller interface {
|
||||
Start(ctx context.Context) (<-chan model.Update, error)
|
||||
}
|
||||
|
||||
type DispatcherOption interface {
|
||||
apply(d *dispatcherOptions)
|
||||
}
|
||||
|
||||
type Dispatcher struct {
|
||||
api *maxbot.Api
|
||||
poller Poller
|
||||
fsmStorage FSMStorage
|
||||
eventIsolation EventIsolation
|
||||
rt *Router
|
||||
wg sync.WaitGroup
|
||||
}
|
||||
|
||||
type dispatcherOptions struct {
|
||||
poller Poller
|
||||
fsmStorage FSMStorage
|
||||
eventIsolation EventIsolation
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
d.handleUpdates(ch)
|
||||
d.wg.Wait()
|
||||
return nil
|
||||
}
|
||||
|
||||
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 := log.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 {
|
||||
log.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, 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.rt.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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 newDispatcherOptions(api *maxbot.Api) *dispatcherOptions {
|
||||
return &dispatcherOptions{
|
||||
poller: NewLongPoller(api),
|
||||
fsmStorage: memory.NewFSMStorage(),
|
||||
eventIsolation: memory.NewEventIsolation(defaultTTL),
|
||||
}
|
||||
}
|
||||
|
||||
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,285 @@
|
||||
package core
|
||||
|
||||
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/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
|
||||
}
|
||||
|
||||
type LongPoller struct {
|
||||
api *maxbot.Api
|
||||
pollInterval time.Duration
|
||||
}
|
||||
|
||||
type TestPoller struct {
|
||||
ch chan model.Update
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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(_ context.Context) (<-chan model.Update, error) {
|
||||
errCh := make(chan error, 1)
|
||||
defer close(errCh)
|
||||
|
||||
go func() {
|
||||
var err error
|
||||
defer func() {
|
||||
errCh <- err
|
||||
if err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
log.Fatal().Err(err).Msg("webhook server error")
|
||||
}
|
||||
}()
|
||||
|
||||
if w.srv.TLSConfig == nil {
|
||||
err = w.srv.ListenAndServe()
|
||||
return
|
||||
}
|
||||
|
||||
err = w.srv.ListenAndServeTLS("", "")
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-errCh:
|
||||
return nil, err
|
||||
case <-time.After(defaultWhStartTimeout):
|
||||
return w.ch, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Webhook) Stop(ctx context.Context) error {
|
||||
close(w.ch)
|
||||
return w.srv.Shutdown(ctx)
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
return lp
|
||||
}
|
||||
|
||||
func (lp *LongPoller) Start(ctx context.Context) (<-chan model.Update, error) {
|
||||
var updates []model.Update
|
||||
var marker int64
|
||||
var err error
|
||||
|
||||
ch := make(chan model.Update)
|
||||
|
||||
go func() {
|
||||
defer close(ch)
|
||||
|
||||
// todo: backoff on errors
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.Tick(lp.pollInterval):
|
||||
start := time.Now()
|
||||
updates, marker, err = lp.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 ch <- update:
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
return ch, 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 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 newLongPollerOptions() *longPollerOptions {
|
||||
return &longPollerOptions{
|
||||
pollInterval: defaultInterval,
|
||||
}
|
||||
}
|
||||
|
||||
func newWebhookOptions() *webhookOptions {
|
||||
return &webhookOptions{
|
||||
addr: ":8080",
|
||||
}
|
||||
}
|
||||
|
||||
func newWhOption(fn func(options *webhookOptions)) WebhookOption {
|
||||
return webhookOptionWrapper{fn: fn}
|
||||
}
|
||||
|
||||
func (wow webhookOptionWrapper) apply(opts *webhookOptions) {
|
||||
wow.fn(opts)
|
||||
}
|
||||
@@ -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/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 @@
|
||||
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} }
|
||||
@@ -2,17 +2,32 @@ package middleware
|
||||
|
||||
import (
|
||||
"errors"
|
||||
mcontext "github.com/abelith/gomax/context"
|
||||
"github.com/abelith/gomax/core"
|
||||
merrors "github.com/abelith/gomax/errors"
|
||||
mcontext "github.com/abelith/gomax/v1/context"
|
||||
"github.com/abelith/gomax/v1/core"
|
||||
merrors "github.com/abelith/gomax/v1/errors"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
func MwPanicHandler() core.Middleware {
|
||||
return func(next core.HandlerFunc) core.HandlerFunc {
|
||||
return func(c *mcontext.Context) error {
|
||||
defer func() {
|
||||
p := recover()
|
||||
if p != nil {
|
||||
log.Fatal().Any("panic", p).Send()
|
||||
}
|
||||
}()
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
err := next(c)
|
||||
var maxErr *merrors.GoMaxError
|
||||
|
||||
if errors.As(err, &maxErr) {
|
||||
return c.Respond(maxErr.Message)
|
||||
@@ -26,13 +41,13 @@ func MwErrorResponder(defaultMsg string) core.Middleware {
|
||||
}
|
||||
}
|
||||
|
||||
func MwLoggerInjector() core.Middleware {
|
||||
func MwLoggerInjector(logger zerolog.Logger) 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).
|
||||
ctx := logger.With().Int64("user_id", c.Update().UserID).
|
||||
Logger().WithContext(c.Context())
|
||||
c.SetContext(ctx)
|
||||
return next.HandleUpdate(c)
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -41,7 +56,7 @@ 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)
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -49,7 +64,7 @@ func MwDebugState() core.Middleware {
|
||||
func MwErrorLogger() core.Middleware {
|
||||
return func(next core.HandlerFunc) core.HandlerFunc {
|
||||
return func(c *mcontext.Context) error {
|
||||
if err := next.HandleUpdate(c); err != nil {
|
||||
if err := next(c); err != nil {
|
||||
log.Ctx(c).Err(err).Send()
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/abelith/gomax/v1/isolation"
|
||||
"github.com/abelith/gomax/v1/state"
|
||||
"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 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, userID int) (state.Snapshot, error) {
|
||||
st, ok := f.m.Load(userID)
|
||||
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(snapshot.ID, snapshot)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *FSMStorage) Delete(_ context.Context, userID int) error {
|
||||
f.m.Delete(userID)
|
||||
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)
|
||||
}
|
||||
File renamed without changes.
Reference in new issue
Block a user